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 <pthread.h> #include "hitls_build.h" #include "crypt_errno.h" #include "crypt_eal_cipher.h" #include "bsl_sal.h" #include "securec.h" typedef struct { uint8_t *key; uint8_t *iv; uint8_t *aad; uint8_t *pt; uint8_t *ct; uint8_t *tag; uint32_t keyLen; uint32_t ivLen; uint32_t aadLen; uint32_t ptLen; uint32_t ctLen; uint32_t tagLen; int algId; int isProvider; } ThreadParameter; void MultiThreadTest(void *arg) { ThreadParameter *threadParameter = (ThreadParameter *)arg; uint32_t outLen = threadParameter->ctLen; uint64_t msgLen = threadParameter->ctLen; uint32_t tagLen = threadParameter->tagLen; uint8_t out[threadParameter->ctLen]; uint8_t tag[threadParameter->tagLen]; CRYPT_EAL_CipherCtx *ctx = TestCipherNewCtx(NULL, threadParameter->algId, "provider=default", threadParameter->isProvider); ASSERT_TRUE(ctx != NULL); ASSERT_TRUE(CRYPT_EAL_CipherInit(ctx, threadParameter->key, threadParameter->keyLen, threadParameter->iv, threadParameter->ivLen, true) == CRYPT_SUCCESS); ASSERT_TRUE(CRYPT_EAL_CipherCtrl(ctx, CRYPT_CTRL_SET_TAGLEN, &tagLen, sizeof(tagLen)) == CRYPT_SUCCESS); ASSERT_TRUE(CRYPT_EAL_CipherCtrl(ctx, CRYPT_CTRL_SET_MSGLEN, &msgLen, sizeof(msgLen)) == CRYPT_SUCCESS); ASSERT_TRUE(CRYPT_EAL_CipherCtrl(ctx, CRYPT_CTRL_SET_AAD, threadParameter->aad, threadParameter->aadLen) == CRYPT_SUCCESS); ASSERT_TRUE(CRYPT_EAL_CipherUpdate(ctx, threadParameter->pt, threadParameter->ptLen, (uint8_t *)out, &outLen) == CRYPT_SUCCESS); ASSERT_TRUE(CRYPT_EAL_CipherCtrl(ctx, CRYPT_CTRL_GET_TAG, (uint8_t *)tag, tagLen) == CRYPT_SUCCESS); ASSERT_COMPARE("Compare Ct", out, threadParameter->ctLen, threadParameter->ct, threadParameter->ctLen); ASSERT_COMPARE("Compare Enc Tag", tag, tagLen, threadParameter->tag, threadParameter->tagLen); CRYPT_EAL_CipherDeinit(ctx); ASSERT_TRUE(CRYPT_EAL_CipherInit(ctx, threadParameter->key, threadParameter->keyLen, threadParameter->iv, threadParameter->ivLen, false) == CRYPT_SUCCESS); ASSERT_TRUE(CRYPT_EAL_CipherCtrl(ctx, CRYPT_CTRL_SET_TAGLEN, &tagLen, sizeof(tagLen)) == CRYPT_SUCCESS); ASSERT_TRUE(CRYPT_EAL_CipherCtrl(ctx, CRYPT_CTRL_SET_MSGLEN, &msgLen, sizeof(msgLen)) == CRYPT_SUCCESS); ASSERT_TRUE(CRYPT_EAL_CipherCtrl(ctx, CRYPT_CTRL_SET_AAD, threadParameter->aad, threadParameter->aadLen) == CRYPT_SUCCESS); ASSERT_TRUE(CRYPT_EAL_CipherUpdate(ctx, threadParameter->ct, threadParameter->ctLen, (uint8_t *)out, &outLen) == CRYPT_SUCCESS); ASSERT_TRUE(CRYPT_EAL_CipherCtrl(ctx, CRYPT_CTRL_GET_TAG, (uint8_t *)tag, tagLen) == CRYPT_SUCCESS); ASSERT_COMPARE("Compare Pt", out, threadParameter->ptLen, threadParameter->pt, threadParameter->ptLen); ASSERT_COMPARE("Compare Dec Tag", tag, tagLen, threadParameter->tag, threadParameter->tagLen); EXIT: CRYPT_EAL_CipherFreeCtx(ctx); } /* END_HEADER */ /** * @test SDV_CRYPTO_AES_CCM_REINIT_API_TC001 * @title CRYPT_EAL_CipherReinit different iv length Test * @precon Registering memory-related functions. * @brief * 1.Create the context ctx. Expected result 1 is obtained. * 2.Call the Init interface. Expected result 2 is obtained. * 3.Call the Reinit interface, ctx is not NULL, iv is not NULL, and ivLen is 6. Expected result 3 is obtained. * 4.Call the Reinit interface, ctx is not NULL, iv is not NULL, and ivLen is 7. Expected result 4 is obtained. * 5.Call the Reinit interface, ctx is not NULL, iv is not NULL, and ivLen is 13. Expected result 5 is obtained. * 6.Call the Reinit interface, ctx is not NULL, iv is not NULL, and ivLen is 14. Expected result 6 is obtained. * @expect * 1.The creation is successful and the ctx is not empty. * 2.The init is successful and return CRYPT_SUCCESS. * 3.Failed. Return CRYPT_MODES_IVLEN_ERROR. * 4.Success. Return CRYPT_SUCCESS. * 5.Success. Return CRYPT_SUCCESS. * 6.Failed. Return CRYPT_MODES_IVLEN_ERROR. */ /* BEGIN_CASE */ void SDV_CRYPTO_AES_CCM_REINIT_API_TC001(int id, int keyLen) { TestMemInit(); uint8_t key[32] = { 0 }; uint8_t iv[14] = { 0 }; uint32_t ivLen = 0; CRYPT_EAL_CipherCtx *ctx = CRYPT_EAL_CipherNewCtx(id); ASSERT_TRUE(ctx != NULL); ivLen = 13; ASSERT_TRUE(CRYPT_EAL_CipherInit(ctx, (uint8_t *)key, keyLen, (uint8_t *)iv, ivLen, true) == CRYPT_SUCCESS); ivLen = 6; ASSERT_TRUE(CRYPT_EAL_CipherReinit(ctx, (uint8_t *)iv, ivLen) == CRYPT_MODES_IVLEN_ERROR); ivLen = 7; ASSERT_TRUE(CRYPT_EAL_CipherReinit(ctx, (uint8_t *)iv, ivLen) == CRYPT_SUCCESS); ivLen = 13; ASSERT_TRUE(CRYPT_EAL_CipherReinit(ctx, (uint8_t *)iv, ivLen) == CRYPT_SUCCESS); ivLen = 14; ASSERT_TRUE(CRYPT_EAL_CipherReinit(ctx, (uint8_t *)iv, ivLen) == CRYPT_MODES_IVLEN_ERROR); EXIT: CRYPT_EAL_CipherFreeCtx(ctx); } /* END_CASE */ /** * @test SDV_CRYPTO_AES_CCM_CTRL_API_TC001 * @title Relationship between CRYPT_CTRL_SET_MSGLEN and ivlen of the CRYPT_EAL_CipherCtrl interface Test * @precon Registering memory-related functions. * @brief * 1.Create the context ctx. Expected result 1 is obtained. * 2.Call the Init interface. Expected result 2 is obtained. * 3.Call the Ctrl interface, ctx is not NULL, and msg len is 0. Expected result 3 is obtained. * 4.Call the Update interface, ctx is not NULL, and plain len is 0. Expected result 4 is obtained. * 5.Call the Reinit interface, ctx is not NULL, iv is not NULL, and ivLen is 13. Expected result 5 is obtained. * 6.Call the Ctrl interface, ctx is not NULL, and msg len is 0. Expected result 6 is obtained. * 7.Call the Update interface, ctx is not NULL, and plain len is 1. Expected result 7 is obtained. * 8.Call the Reinit interface, ctx is not NULL, iv is not NULL, and ivLen is 8. Expected result 8 is obtained. * 9.Call the Ctrl interface, ctx is not NULL, and msg len is 1 << ((15 - 8) * 8)) - 1. Expected result 9 is obtained. * 10.Call the Ctrl interface, ctx is not NULL, and msg len is 1 << ((15 - 8) * 8)). Expected result 10 is obtained. * 11.Call the Reinit interface, ctx is not NULL, iv is not NULL, and ivLen is 12. Expected result 11 is obtained. * 12.Call the Ctrl interface, ctx is not NULL, and msg len is 1 << ((15 - 12) * 8)) - 1. Expected result 12 is obtained. * 13.Call the Ctrl interface, ctx is not NULL, and msg len is 1 << ((15 - 12) * 8)). Expected result 13 is obtained. * @expect * 1.The creation is successful and the ctx is not empty. * 2.The init is successful and return CRYPT_SUCCESS. * 3.Success. Return CRYPT_SUCCESS. * 4.Success. Return CRYPT_SUCCESS. * 5.Success. Return CRYPT_SUCCESS. * 6.Success. Return CRYPT_SUCCESS. * 7.Success. Return CRYPT_SUCCESS. * 8.Success. Return CRYPT_SUCCESS. * 9.Success. Return CRYPT_SUCCESS. * 10.Failed. Return CRYPT_MODES_CTRL_MSGLEN_ERROR. * 11.Success. Return CRYPT_SUCCESS. * 12.Success. Return CRYPT_SUCCESS. * 13.Failed. CRYPT_MODES_CTRL_MSGLEN_ERROR. */ /* BEGIN_CASE */ void SDV_CRYPTO_AES_CCM_CTRL_API_TC001(int id, int keyLen) { TestMemInit(); uint8_t key[32] = { 0 }; uint8_t iv[13] = { 0 }; uint32_t ivLen = sizeof(iv); uint8_t data[16] = { 0 }; uint8_t out[16] = { 0 }; uint32_t outLen = sizeof(out); uint64_t count = 0; CRYPT_EAL_CipherCtx *ctx = CRYPT_EAL_CipherNewCtx(id); ASSERT_TRUE(ctx != NULL); ASSERT_TRUE(CRYPT_EAL_CipherInit(ctx, key, keyLen, iv, ivLen, true) == CRYPT_SUCCESS); ASSERT_TRUE(CRYPT_EAL_CipherCtrl(ctx, CRYPT_CTRL_SET_MSGLEN, &count, sizeof(count)) == CRYPT_SUCCESS); ASSERT_TRUE(CRYPT_EAL_CipherUpdate(ctx, data, 0, out, &outLen) == CRYPT_SUCCESS); ASSERT_TRUE(CRYPT_EAL_CipherReinit(ctx, iv, ivLen) == CRYPT_SUCCESS); ASSERT_TRUE(CRYPT_EAL_CipherCtrl(ctx, CRYPT_CTRL_SET_MSGLEN, &count, sizeof(count)) == CRYPT_SUCCESS); outLen = sizeof(out); ASSERT_TRUE(CRYPT_EAL_CipherUpdate(ctx, data, 1, out, &outLen) == CRYPT_MODES_MSGLEN_OVERFLOW); ivLen = 8; ASSERT_TRUE(CRYPT_EAL_CipherReinit(ctx, iv, ivLen) == CRYPT_SUCCESS); count = ((uint64_t)1 << ((15 - 8) * 8)) - 1; ASSERT_TRUE(CRYPT_EAL_CipherCtrl(ctx, CRYPT_CTRL_SET_MSGLEN, &count, sizeof(count)) == CRYPT_SUCCESS); count = (uint64_t)1 << ((15 - 8) * 8); ASSERT_TRUE(CRYPT_EAL_CipherCtrl(ctx, CRYPT_CTRL_SET_MSGLEN, &count, sizeof(count)) == CRYPT_MODES_CTRL_MSGLEN_ERROR); ivLen = 12; ASSERT_TRUE(CRYPT_EAL_CipherReinit(ctx, iv, ivLen) == CRYPT_SUCCESS); count = ((uint64_t)1 << ((15 - 12) * 8)) - 1; ASSERT_TRUE(CRYPT_EAL_CipherCtrl(ctx, CRYPT_CTRL_SET_MSGLEN, &count, sizeof(count)) == CRYPT_SUCCESS); count = (uint64_t)1 << ((15 - 12) * 8); ASSERT_TRUE(CRYPT_EAL_CipherCtrl(ctx, CRYPT_CTRL_SET_MSGLEN, &count, sizeof(count)) == CRYPT_MODES_CTRL_MSGLEN_ERROR); EXIT: CRYPT_EAL_CipherFreeCtx(ctx); } /* END_CASE */ /** * @test SDV_CRYPTO_AES_CCM_UPDATE_API_TC001 * @title Relationship between the CRYPT_CTRL_SET_MSGLEN and the update length of the CRYPT_EAL_CipherCtrl interface Test * @precon Registering memory-related functions. * @brief * 1.Create the context ctx. Expected result 1 is obtained. * 2.Call the Init interface. Expected result 2 is obtained. * 3.Call the Ctrl interface, ctx is not NULL, and msg len is 10. Expected result 3 is obtained. * 4.Call the Ctrl interface, ctx is not NULL, and msg len is 20. Expected result 4 is obtained. * 5.Call the Update interface, ctx is not NULL, and plain len is 20. Expected result 5 is obtained. * 6.Call the Update interface, ctx is not NULL, and plain len is 0. Expected result 6 is obtained. * 7.Call the Update interface, ctx is not NULL, and plain len is 10. Expected result 7 is obtained. * @expect * 1.The creation is successful and the ctx is not empty. * 2.The init is successful and return CRYPT_SUCCESS. * 3.Success. Return CRYPT_SUCCESS. * 4.Success. Return CRYPT_SUCCESS. * 5.Success. Return CRYPT_SUCCESS. * 6.Success. Return CRYPT_SUCCESS. * 7.Failed. Return CRYPT_MODES_MSGLEN_OVERFLOW. */ /* BEGIN_CASE */ void SDV_CRYPTO_AES_CCM_UPDATE_API_TC001(int id, int keyLen) { TestMemInit(); uint8_t key[32] = { 0 }; uint8_t iv[13] = { 0 }; uint32_t ivLen = sizeof(iv); uint8_t data[20] = { 0 }; uint32_t dataLen = 0; uint8_t out[20] = { 0 }; uint32_t outLen = sizeof(out); uint64_t count = 0; CRYPT_EAL_CipherCtx *ctx = CRYPT_EAL_CipherNewCtx(id); ASSERT_TRUE(ctx != NULL); ASSERT_TRUE(CRYPT_EAL_CipherInit(ctx, key, keyLen, iv, ivLen, true) == CRYPT_SUCCESS); count = 10; ASSERT_TRUE(CRYPT_EAL_CipherCtrl(ctx, CRYPT_CTRL_SET_MSGLEN, &count, sizeof(count)) == CRYPT_SUCCESS); count = 20; ASSERT_TRUE(CRYPT_EAL_CipherCtrl(ctx, CRYPT_CTRL_SET_MSGLEN, &count, sizeof(count)) == CRYPT_SUCCESS); dataLen = 20; ASSERT_TRUE(CRYPT_EAL_CipherUpdate(ctx, data, dataLen, out, &outLen) == CRYPT_SUCCESS); outLen = sizeof(out); dataLen = 0; ASSERT_TRUE(CRYPT_EAL_CipherUpdate(ctx, data, dataLen, out, &outLen) == CRYPT_SUCCESS); outLen = sizeof(out); dataLen = 10; ASSERT_TRUE(CRYPT_EAL_CipherUpdate(ctx, data, dataLen, out, &outLen) == CRYPT_MODES_MSGLEN_OVERFLOW); EXIT: CRYPT_EAL_CipherFreeCtx(ctx); } /* END_CASE */ /** * @test SDV_CRYPTO_AES_CCM_UPDATE_API_TC001 * @title Test after AAD is set for the CRYPT_EAL_CipherCtrl interface, msglen cannot be set. * @precon Registering memory-related functions. * @brief * 1.Create the context ctx. Expected result 1 is obtained. * 2.Call the Init interface. Expected result 2 is obtained. * 3.Call the Ctrl interface, ctx is not NULL, and set aad. Expected result 3 is obtained. * 4.Call the Ctrl interface, ctx is not NULL, and set msglen. Expected result 4 is obtained. * 5.Call the Reinit interface, ctx is not NULL, iv is not NULL, and ivLen is 13. Expected result 5 is obtained. * 6.Call the Ctrl interface, ctx is not NULL, and set msglen. Expected result 6 is obtained. * @expect * 1.The creation is successful and the ctx is not empty. * 2.The init is successful and return CRYPT_SUCCESS. * 3.Success. Return CRYPT_SUCCESS. * 4.Failed. Return CRYPT_EAL_ERR_STATE. * 5.Success. Return CRYPT_SUCCESS. * 6.Success. Return CRYPT_SUCCESS. */ /* BEGIN_CASE */ void SDV_CRYPTO_AES_CCM_CTRL_API_TC002(int id, int keyLen) { TestMemInit(); uint8_t key[32] = { 0 }; uint8_t iv[13] = { 0 }; uint32_t ivLen = sizeof(iv); uint8_t aad[16] = { 0 }; uint64_t count = 0; CRYPT_EAL_CipherCtx *ctx = CRYPT_EAL_CipherNewCtx(id); ASSERT_TRUE(ctx != NULL); ASSERT_EQ(CRYPT_EAL_CipherInit(ctx, key, keyLen, iv, ivLen, true), CRYPT_SUCCESS); ASSERT_EQ(CRYPT_EAL_CipherCtrl(ctx, CRYPT_CTRL_SET_AAD, aad, sizeof(aad)), CRYPT_SUCCESS); ASSERT_EQ(CRYPT_EAL_CipherCtrl(ctx, CRYPT_CTRL_SET_MSGLEN, &count, sizeof(count)), CRYPT_EAL_ERR_STATE); ASSERT_EQ(CRYPT_EAL_CipherReinit(ctx, iv, ivLen), CRYPT_SUCCESS); ASSERT_EQ(CRYPT_EAL_CipherCtrl(ctx, CRYPT_CTRL_SET_MSGLEN, &count, sizeof(count)), CRYPT_SUCCESS); EXIT: CRYPT_EAL_CipherFreeCtx(ctx); } /* END_CASE */ /** * @test SDV_CRYPTO_AES_CCM_CTRL_API_TC003 * @title CRYPT_EAL_CipherCtrl interface set aad Test * @precon Registering memory-related functions. * @brief * 1.Create the context ctx. Expected result 1 is obtained. * 2.Call the Init interface. Expected result 2 is obtained. * 3.Call the Ctrl interface, ctx is not NULL, and set aad. Expected result 3 is obtained. * 4.Call the Ctrl interface, ctx is not NULL, and set aad. Expected result 4 is obtained. * 5.Call the Reinit interface, ctx is not NULL, iv is not NULL, and ivLen is 13. Expected result 5 is obtained. * 6.Call the Ctrl interface, ctx is not NULL, and set aad. Expected result 6 is obtained. * @expect * 1.The creation is successful and the ctx is not empty. * 2.The init is successful and return CRYPT_SUCCESS. * 3.Success. Return CRYPT_SUCCESS. * 4.Failed. Return CRYPT_EAL_ERR_STATE. * 5.Success. Return CRYPT_SUCCESS. * 6.Success. Return CRYPT_SUCCESS. */ /* BEGIN_CASE */ void SDV_CRYPTO_AES_CCM_CTRL_API_TC003(int id, int keyLen) { TestMemInit(); uint8_t key[32] = { 0 }; uint8_t iv[13] = { 0 }; uint32_t ivLen = sizeof(iv); uint8_t aad[16] = { 0 }; CRYPT_EAL_CipherCtx *ctx = CRYPT_EAL_CipherNewCtx(id); ASSERT_TRUE(ctx != NULL); ASSERT_TRUE(CRYPT_EAL_CipherInit(ctx, key, keyLen, iv, ivLen, true) == CRYPT_SUCCESS); ASSERT_TRUE(CRYPT_EAL_CipherCtrl(ctx, CRYPT_CTRL_SET_AAD, aad, sizeof(aad)) == CRYPT_SUCCESS); ASSERT_EQ(CRYPT_EAL_CipherCtrl(ctx, CRYPT_CTRL_SET_AAD, aad, sizeof(aad)), CRYPT_EAL_ERR_STATE); ASSERT_TRUE(CRYPT_EAL_CipherReinit(ctx, iv, ivLen) == CRYPT_SUCCESS); ASSERT_TRUE(CRYPT_EAL_CipherCtrl(ctx, CRYPT_CTRL_SET_AAD, aad, sizeof(aad)) == CRYPT_SUCCESS); EXIT: CRYPT_EAL_CipherFreeCtx(ctx); } /* END_CASE */ /** * @test SDV_CRYPTO_AES_CCM_CTRL_API_TC004 * @title CRYPT_EAL_CipherCtrl interface set tag len Test * @precon Registering memory-related functions. * @brief * 1.Create the context ctx. Expected result 1 is obtained. * 2.Call the Init interface. Expected result 2 is obtained. * 3.Call the Ctrl interface, ctx is not NULL, and tag len is 4. Expected result 3 is obtained. * 4.Call the Ctrl interface, ctx is not NULL, and tag len is 6. Expected result 4 is obtained. * 5.Call the Ctrl interface, ctx is not NULL, and tag len is 8. Expected result 5 is obtained. * 6.Call the Ctrl interface, ctx is not NULL, and tag len is 10. Expected result 6 is obtained. * 7.Call the Ctrl interface, ctx is not NULL, and tag len is 12. Expected result 7 is obtained. * 8.Call the Ctrl interface, ctx is not NULL, and tag len is 14. Expected result 8 is obtained. * 9.Call the Ctrl interface, ctx is not NULL, and tag len is 16. Expected result 9 is obtained. * 10.Call the Reinit interface, ctx is not NULL, iv is not NULL, and ivLen is 1. Expected result 10 is obtained. * 11.Call the Ctrl interface, ctx is not NULL, and tag len is 2. Expected result 11 is obtained. * 12.Call the Ctrl interface, ctx is not NULL, and tag len is 18. Expected result 12 is obtained. * 13.Call the Ctrl interface, ctx is not NULL, and tag len is 0. Expected result 13 is obtained. * 14.Call the Ctrl interface, ctx is not NULL, and tag len is 5. Expected result 14 is obtained. * @expect * 1.The creation is successful and the ctx is not empty. * 2.The init is successful and return CRYPT_SUCCESS. * 3.Success. Return CRYPT_SUCCESS. * 4.Success. Return CRYPT_SUCCESS. * 5.Success. Return CRYPT_SUCCESS. * 6.Success. Return CRYPT_SUCCESS. * 7.Success. Return CRYPT_SUCCESS. * 8.Success. Return CRYPT_SUCCESS. * 9.Success. Return CRYPT_SUCCESS. * 10.Success. Return CRYPT_SUCCESS. * 11.Failed. Return CRYPT_MODES_CTRL_TAGLEN_ERROR. * 12.Failed. Return CRYPT_MODES_CTRL_TAGLEN_ERROR. * 13.Failed. Return CRYPT_MODES_CTRL_TAGLEN_ERROR. * 14.Failed. Return CRYPT_MODES_CTRL_TAGLEN_ERROR. */ /* BEGIN_CASE */ void SDV_CRYPTO_AES_CCM_CTRL_API_TC004(int id, int keyLen) { TestMemInit(); uint8_t key[32] = { 0 }; uint8_t iv[13] = { 0 }; uint32_t ivLen = sizeof(iv); uint32_t tagLen; CRYPT_EAL_CipherCtx *ctx = CRYPT_EAL_CipherNewCtx(id); ASSERT_TRUE(ctx != NULL); ASSERT_TRUE(CRYPT_EAL_CipherInit(ctx, key, keyLen, iv, ivLen, true) == CRYPT_SUCCESS); tagLen = 4; ASSERT_TRUE(CRYPT_EAL_CipherCtrl(ctx, CRYPT_CTRL_SET_TAGLEN, &tagLen, sizeof(tagLen)) == CRYPT_SUCCESS); tagLen = 6; ASSERT_TRUE(CRYPT_EAL_CipherCtrl(ctx, CRYPT_CTRL_SET_TAGLEN, &tagLen, sizeof(tagLen)) == CRYPT_SUCCESS); tagLen = 8; ASSERT_TRUE(CRYPT_EAL_CipherCtrl(ctx, CRYPT_CTRL_SET_TAGLEN, &tagLen, sizeof(tagLen)) == CRYPT_SUCCESS); tagLen = 10; ASSERT_TRUE(CRYPT_EAL_CipherCtrl(ctx, CRYPT_CTRL_SET_TAGLEN, &tagLen, sizeof(tagLen)) == CRYPT_SUCCESS); tagLen = 12; ASSERT_TRUE(CRYPT_EAL_CipherCtrl(ctx, CRYPT_CTRL_SET_TAGLEN, &tagLen, sizeof(tagLen)) == CRYPT_SUCCESS); tagLen = 14; ASSERT_TRUE(CRYPT_EAL_CipherCtrl(ctx, CRYPT_CTRL_SET_TAGLEN, &tagLen, sizeof(tagLen)) == CRYPT_SUCCESS); tagLen = 16; ASSERT_TRUE(CRYPT_EAL_CipherCtrl(ctx, CRYPT_CTRL_SET_TAGLEN, &tagLen, sizeof(tagLen)) == CRYPT_SUCCESS); ASSERT_TRUE(CRYPT_EAL_CipherReinit(ctx, iv, ivLen) == CRYPT_SUCCESS); tagLen = 2; ASSERT_TRUE(CRYPT_EAL_CipherCtrl(ctx, CRYPT_CTRL_SET_TAGLEN, &tagLen, sizeof(tagLen)) == CRYPT_MODES_CTRL_TAGLEN_ERROR); tagLen = 18; ASSERT_TRUE(CRYPT_EAL_CipherCtrl(ctx, CRYPT_CTRL_SET_TAGLEN, &tagLen, sizeof(tagLen)) == CRYPT_MODES_CTRL_TAGLEN_ERROR); tagLen = 0; ASSERT_TRUE(CRYPT_EAL_CipherCtrl(ctx, CRYPT_CTRL_SET_TAGLEN, &tagLen, sizeof(tagLen)) == CRYPT_MODES_CTRL_TAGLEN_ERROR); tagLen = 5; ASSERT_TRUE(CRYPT_EAL_CipherCtrl(ctx, CRYPT_CTRL_SET_TAGLEN, &tagLen, sizeof(tagLen)) == CRYPT_MODES_CTRL_TAGLEN_ERROR); EXIT: CRYPT_EAL_CipherFreeCtx(ctx); } /* END_CASE */ /** * @test SDV_CRYPTO_AES_CCM_CTRL_API_TC005 * @title CRYPT_EAL_CipherCtrl interface get tag Test * @precon Registering memory-related functions. * @brief * 1.Create the context ctx. Expected result 1 is obtained. * 2.Call the Init interface. Expected result 2 is obtained. * 3.Call the Ctrl interface, ctx is not NULL, and tag len is 8. Expected result 3 is obtained. * 4.Call the Ctrl interface, ctx is not NULL, and msg len is 7. Expected result 4 is obtained. * 5.Call the Ctrl interface, ctx is not NULL, and set aad. Expected result 5 is obtained. * 6.Call the Update interface, ctx is not NULL, and plain len is 7. Expected result 6 is obtained. * 7.Call the Ctrl interface, ctx is not NULL, and get tag. Expected result 7 is obtained. * 8.Call the Ctrl interface, ctx is not NULL, and get tag. Expected result 8 is obtained. * 9.Call the Reinit interface, ctx is not NULL, iv is not NULL, and ivLen is 8. Expected result 9 is obtained. * 10.Call the Ctrl interface, ctx is not NULL, and get tag. Expected result 10 is obtained. * @expect * 1.The creation is successful and the ctx is not empty. * 2.The init is successful and return CRYPT_SUCCESS. * 3.Success. Return CRYPT_SUCCESS. * 4.Success. Return CRYPT_SUCCESS. * 5.Success. Return CRYPT_SUCCESS. * 6.Success. Return CRYPT_SUCCESS. * 7.Success. Return CRYPT_SUCCESS. * 8.Failed. Return CRYPT_EAL_ERR_STATE. * 9.Success. Return CRYPT_SUCCESS. * 10.Success. Return CRYPT_SUCCESS. */ /* BEGIN_CASE */ void SDV_CRYPTO_AES_CCM_CTRL_API_TC005(int id, int keyLen) { TestMemInit(); uint8_t key[32] = { 0 }; uint8_t iv[8] = { 0 }; uint32_t ivLen = sizeof(iv); uint8_t aad[10] = { 0 }; uint8_t tag[16] = { 0 }; uint8_t cmpTag[16] = { 0 }; uint32_t tagLen; uint64_t count = 0; uint8_t data[20] = { 0 }; uint8_t out[16] = { 0 }; uint32_t outLen = sizeof(out); CRYPT_EAL_CipherCtx *ctx = CRYPT_EAL_CipherNewCtx(id); ASSERT_TRUE(ctx != NULL); ASSERT_TRUE(CRYPT_EAL_CipherInit(ctx, key, keyLen, iv, ivLen, true) == CRYPT_SUCCESS); tagLen = 8; ASSERT_TRUE(CRYPT_EAL_CipherCtrl(ctx, CRYPT_CTRL_SET_TAGLEN, &tagLen, sizeof(tagLen)) == CRYPT_SUCCESS); count = 7; ASSERT_TRUE(CRYPT_EAL_CipherCtrl(ctx, CRYPT_CTRL_SET_MSGLEN, &count, sizeof(count)) == CRYPT_SUCCESS); ASSERT_TRUE(CRYPT_EAL_CipherCtrl(ctx, CRYPT_CTRL_SET_AAD, aad, sizeof(aad)) == CRYPT_SUCCESS); ASSERT_TRUE(CRYPT_EAL_CipherUpdate(ctx, data, 7, out, &outLen) == CRYPT_SUCCESS); ASSERT_TRUE(CRYPT_EAL_CipherCtrl(ctx, CRYPT_CTRL_GET_TAG, tag, tagLen) == CRYPT_SUCCESS); ASSERT_EQ(CRYPT_EAL_CipherCtrl(ctx, CRYPT_CTRL_GET_TAG, cmpTag, tagLen), CRYPT_EAL_ERR_STATE); ASSERT_TRUE(CRYPT_EAL_CipherReinit(ctx, iv, ivLen) == CRYPT_SUCCESS); ASSERT_TRUE(CRYPT_EAL_CipherCtrl(ctx, CRYPT_CTRL_GET_TAG, tag, tagLen) == CRYPT_SUCCESS); EXIT: CRYPT_EAL_CipherFreeCtx(ctx); } /* END_CASE */ /** * @test SDV_CRYPTO_AES_CCM_CTRL_API_TC006 * @title CRYPT_EAL_CipherCtrl interface get tag Test * @precon Registering memory-related functions. * @brief * 1.Create the context ctx. Expected result 1 is obtained. * 2.Call the Init interface. Expected result 2 is obtained. * 3.Call the Ctrl interface, ctx is not NULL, and msg len is 20. Expected result 3 is obtained. * 4.Call the Ctrl interface, ctx is not NULL, and plain len is 20. Expected result 4 is obtained. * 5.Call the Reinit interface, ctx is not NULL, iv is not NULL, and ivLen is 8. Expected result 5 is obtained. * 6.Call the Ctrl interface, ctx is not NULL, and msg len is 40. Expected result 6 is obtained. * 7.Call the Ctrl interface, ctx is not NULL, and plain len is 30. Expected result 7 is obtained. * 8.Call the Ctrl interface, ctx is not NULL, and tag len is 10. Expected result 8 is obtained. * 9.Call the Ctrl interface, ctx is not NULL, and get tag. Expected result 9 is obtained. * @expect * 1.The creation is successful and the ctx is not empty. * 2.The init is successful and return CRYPT_SUCCESS. * 3.Success. Return CRYPT_SUCCESS. * 4.Success. Return CRYPT_SUCCESS. * 5.Success. Return CRYPT_SUCCESS. * 6.Success. Return CRYPT_SUCCESS. * 7.Success. Return CRYPT_SUCCESS. * 8.Failed. Return CRYPT_EAL_ERR_STATE. * 9.Failed. Return CRYPT_MODES_MSGLEN_LEFT_ERROR. */ /* BEGIN_CASE */ void SDV_CRYPTO_AES_CCM_CTRL_API_TC006(int id, int keyLen) { TestMemInit(); uint8_t key[32] = { 0 }; uint8_t iv[8] = { 0 }; uint32_t ivLen = sizeof(iv); uint8_t tag[16] = { 0 }; uint32_t tagLen = sizeof(tag); uint64_t count = 0; uint8_t data[40] = { 0 }; uint32_t dataLen = 0; uint8_t out[40] = { 0 }; uint32_t outLen = sizeof(out); CRYPT_EAL_CipherCtx *ctx = CRYPT_EAL_CipherNewCtx(id); ASSERT_TRUE(ctx != NULL); ASSERT_TRUE(CRYPT_EAL_CipherInit(ctx, key, keyLen, iv, ivLen, true) == CRYPT_SUCCESS); count = 20; ASSERT_TRUE(CRYPT_EAL_CipherCtrl(ctx, CRYPT_CTRL_SET_MSGLEN, &count, sizeof(count)) == CRYPT_SUCCESS); dataLen = 20; ASSERT_TRUE(CRYPT_EAL_CipherUpdate(ctx, data, dataLen, out, &outLen) == CRYPT_SUCCESS); ASSERT_TRUE(CRYPT_EAL_CipherReinit(ctx, iv, ivLen) == CRYPT_SUCCESS); count = 40; ASSERT_TRUE(CRYPT_EAL_CipherCtrl(ctx, CRYPT_CTRL_SET_MSGLEN, &count, sizeof(count)) == CRYPT_SUCCESS); outLen = sizeof(out); dataLen = 30; ASSERT_TRUE(CRYPT_EAL_CipherUpdate(ctx, data, dataLen, out, &outLen) == CRYPT_SUCCESS); tagLen = 10; ASSERT_EQ(CRYPT_EAL_CipherCtrl(ctx, CRYPT_CTRL_SET_TAGLEN, &tagLen, sizeof(tagLen)), CRYPT_EAL_ERR_STATE); tagLen = 16; ASSERT_TRUE(CRYPT_EAL_CipherCtrl(ctx, CRYPT_CTRL_GET_TAG, tag, tagLen) == CRYPT_MODES_MSGLEN_LEFT_ERROR); EXIT: CRYPT_EAL_CipherFreeCtx(ctx); } /* END_CASE */ /** * @test SDV_CRYPTO_AES_CCM_UPDATE_FUNC_TC001 * @title AES CCM update encryption and decryption Test * @precon Registering memory-related functions. * @brief * 1.Create the context ctx. * 2.Call the Init interface. * 3.Call the Reinit interface. * 4.Call the Ctrl interface, set msg len, tag len and aad. * 5.Call the Update interface, ctx is not NULL, and encrypt data. Expected result 1 is obtained. * 6.Call the Ctrl interface, ctx is not NULL, and get tag. Expected result 2 is obtained. * 7.Call the Init interface. * 8.Call the Reinit interface. * 9.Call the Ctrl interface, set msg len, tag len and aad. * 10.Call the Update interface, ctx is not NULL, and decrypt data. Expected result 3 is obtained. * 11.Call the Ctrl interface, ctx is not NULL, and get tag. Expected result 4 is obtained. * @expect * 1.Success. Return CRYPT_SUCCESS. * 2.Success. Return CRYPT_SUCCESS. * 3.Success. Return CRYPT_SUCCESS. * 4.Success. Return CRYPT_SUCCESS. */ /* BEGIN_CASE */ void SDV_CRYPTO_AES_CCM_UPDATE_FUNC_TC001(int isProvider, int id, Hex *key, Hex *iv, Hex *aad, Hex *plaintext, Hex *ciphertext) { #ifndef HITLS_CRYPTO_CCM SKIP_TEST(); #endif TestMemInit(); uint8_t iv0[8] = { 0 }; uint8_t tag[16] = { 0 }; uint32_t tagLen = sizeof(tag); uint64_t count; uint8_t out[1024] = { 0 }; uint32_t outLen = sizeof(out); CRYPT_EAL_CipherCtx *ctx = TestCipherNewCtx(NULL, id, "provider=default", isProvider); ASSERT_TRUE(ctx != NULL); // encrypt ASSERT_EQ(CRYPT_EAL_CipherInit(ctx, key->x, key->len, iv0, sizeof(iv0), true), CRYPT_SUCCESS); ASSERT_TRUE(CRYPT_EAL_CipherReinit(ctx, iv->x, iv->len) == CRYPT_SUCCESS); count = plaintext->len; ASSERT_TRUE(CRYPT_EAL_CipherCtrl(ctx, CRYPT_CTRL_SET_MSGLEN, &count, sizeof(count)) == CRYPT_SUCCESS); tagLen = ciphertext->len - plaintext->len; ASSERT_TRUE(CRYPT_EAL_CipherCtrl(ctx, CRYPT_CTRL_SET_TAGLEN, &tagLen, sizeof(tagLen)) == CRYPT_SUCCESS); ASSERT_TRUE(CRYPT_EAL_CipherCtrl(ctx, CRYPT_CTRL_SET_AAD, aad->x, aad->len) == CRYPT_SUCCESS); ASSERT_TRUE(CRYPT_EAL_CipherUpdate(ctx, plaintext->x, plaintext->len, out, &outLen) == CRYPT_SUCCESS); ASSERT_TRUE(CRYPT_EAL_CipherCtrl(ctx, CRYPT_CTRL_GET_TAG, tag, tagLen) == CRYPT_SUCCESS); ASSERT_TRUE(memcmp(out, ciphertext->x, outLen) == 0); ASSERT_TRUE(memcmp(tag, ciphertext->x + outLen, tagLen) == 0); // decrypt ASSERT_EQ(CRYPT_EAL_CipherInit(ctx, key->x, key->len, iv0, sizeof(iv0), false), CRYPT_SUCCESS); ASSERT_TRUE(CRYPT_EAL_CipherReinit(ctx, iv->x, iv->len) == CRYPT_SUCCESS); count = plaintext->len; ASSERT_TRUE(CRYPT_EAL_CipherCtrl(ctx, CRYPT_CTRL_SET_MSGLEN, &count, sizeof(count)) == CRYPT_SUCCESS); tagLen = ciphertext->len - plaintext->len; ASSERT_TRUE(CRYPT_EAL_CipherCtrl(ctx, CRYPT_CTRL_SET_TAGLEN, &tagLen, sizeof(tagLen)) == CRYPT_SUCCESS); ASSERT_TRUE(CRYPT_EAL_CipherCtrl(ctx, CRYPT_CTRL_SET_AAD, aad->x, aad->len) == CRYPT_SUCCESS); ASSERT_TRUE(CRYPT_EAL_CipherUpdate(ctx, ciphertext->x, plaintext->len, out, &outLen) == CRYPT_SUCCESS); ASSERT_TRUE(CRYPT_EAL_CipherCtrl(ctx, CRYPT_CTRL_GET_TAG, tag, tagLen) == CRYPT_SUCCESS); ASSERT_TRUE(memcmp(out, plaintext->x, outLen) == 0); ASSERT_TRUE(memcmp(tag, ciphertext->x + outLen, tagLen) == 0); EXIT: CRYPT_EAL_CipherFreeCtx(ctx); } /* END_CASE */ /** * @test SDV_CRYPTO_AES_CCM_CTRL_API_TC007 * @title CRYPT_EAL_CipherCtrl state switching Test * @precon Registering memory-related functions. * @brief * 1.Call the Reinit interface and then Call the Ctrl interface to get tag. Expected result 1 is obtained. * 2.Call the update interface and then Call the Ctrl interface to get tag. Expected result 2 is obtained. * 3.Call the Init interface and then Call the Ctrl interface to get tag. Expected result 3 is obtained. * 4.Call the Init and the Deinit interface, and then Call the Init interface. Expected result 4 is obtained. * 5.Call the Ctrl interface to get tag. Expected result 5 is obtained. * 6.Call the Init and the Deinit interface, and then Call the Ctrl interface to get tag. Expected result 6 is obtained. * 7.Call the Init interface and the Reinit interface, then Call the Deinit interface, * and then Call the Ctrl interface to get tag. Expected result 7 is obtained. * 8.Call the Init interface, call the Ctrl interface set aad, set tag len. Expected result 8 is obtained. * 9.Call the Init interface, call the Ctrl interface set msglen, and call Update interface and Reinit interface, * and then call the Ctrl interface get tag. Expected result 9 is obtained. * 10.Call the Init interface, call the Ctrl interface set msglen, call the update interface for encryption, * and then call the Ctrl interface set msglen. Expected result 10 is obtained, * 11.Call the Ctrl interface get tag. Expected result 11 is obtained. * 12.Call the Init interface, call the Ctrl interface set msglen, call the update interface for encryption, * and then call the Ctrl interface set aad. Expected result 12 is obtained, * 13.Call the Ctrl interface get tag. Expected result 13 is obtained. * 14.Call the Init interface, call the ctrl interface set msglen, call the update interface for encryption, * and then call the Ctrl interface set taglen. Expected result 14 is obtained, * 15.Call the Ctrl interface get tag. Expected result 15 is obtained. * @expect * 1.Success. Return CRYPT_SUCCESS. * 2.Success. Return CRYPT_SUCCESS. * 3.Success. Return CRYPT_SUCCESS. * 4.Failed. Return CRYPT_EAL_ERR_STATE. * 5.Failed. Return CRYPT_EAL_ERR_STATE. * 6.Failed. Return CRYPT_EAL_ERR_STATE. * 7.Failed. Return CRYPT_EAL_ERR_STATE. * 9.Success. Return CRYPT_SUCCESS. * 10.Failed. Return CRYPT_EAL_ERR_STATE. * 11.Success. Return CRYPT_SUCCESS. * 12.Failed. Return CRYPT_EAL_ERR_STATE. * 13.Success. Return CRYPT_SUCCESS. * 14.Failed. Return CRYPT_EAL_ERR_STATE. * 15.Success. Return CRYPT_SUCCESS. */ /* BEGIN_CASE */ void SDV_CRYPTO_AES_CCM_CTRL_API_TC007(int id, int keyLen) { TestMemInit(); uint8_t key[32] = { 0 }; uint8_t iv[8] = { 0 }; uint32_t ivLen = sizeof(iv); uint8_t tag[16] = { 0 }; uint32_t tagLen = sizeof(tag); uint64_t count = 0; uint8_t data[40] = { 0 }; uint8_t out[40] = { 0 }; uint8_t aad[40] = { 0 }; uint32_t outLen = sizeof(out); CRYPT_EAL_CipherCtx *ctx = CRYPT_EAL_CipherNewCtx(id); ASSERT_TRUE(ctx != NULL); ASSERT_EQ(CRYPT_EAL_CipherInit(ctx, key, keyLen, iv, ivLen, true), CRYPT_SUCCESS); ASSERT_EQ(CRYPT_EAL_CipherReinit(ctx, iv, ivLen), CRYPT_SUCCESS); ASSERT_EQ(CRYPT_EAL_CipherCtrl(ctx, CRYPT_CTRL_GET_TAG, tag, tagLen), CRYPT_SUCCESS); ASSERT_EQ(CRYPT_EAL_CipherInit(ctx, key, keyLen, iv, ivLen, true), CRYPT_SUCCESS); ASSERT_EQ(CRYPT_EAL_CipherUpdate(ctx, data, 0, out, &outLen), CRYPT_SUCCESS); ASSERT_EQ(CRYPT_EAL_CipherCtrl(ctx, CRYPT_CTRL_GET_TAG, tag, tagLen), CRYPT_SUCCESS); ASSERT_EQ(CRYPT_EAL_CipherInit(ctx, key, keyLen, iv, ivLen, true), CRYPT_SUCCESS); ASSERT_EQ(CRYPT_EAL_CipherCtrl(ctx, CRYPT_CTRL_GET_TAG, tag, tagLen), CRYPT_SUCCESS); ASSERT_EQ(CRYPT_EAL_CipherInit(ctx, key, keyLen, iv, ivLen, true), CRYPT_SUCCESS); CRYPT_EAL_CipherDeinit(ctx); ASSERT_EQ(CRYPT_EAL_CipherReinit(ctx, iv, ivLen), CRYPT_EAL_ERR_STATE); ASSERT_EQ(CRYPT_EAL_CipherCtrl(ctx, CRYPT_CTRL_GET_TAG, tag, tagLen), CRYPT_EAL_ERR_STATE); ASSERT_EQ(CRYPT_EAL_CipherInit(ctx, key, keyLen, iv, ivLen, true), CRYPT_SUCCESS); CRYPT_EAL_CipherDeinit(ctx); ASSERT_EQ(CRYPT_EAL_CipherCtrl(ctx, CRYPT_CTRL_GET_TAG, tag, tagLen), CRYPT_EAL_ERR_STATE); ASSERT_EQ(CRYPT_EAL_CipherInit(ctx, key, keyLen, iv, ivLen, true), CRYPT_SUCCESS); ASSERT_EQ(CRYPT_EAL_CipherReinit(ctx, iv, ivLen), CRYPT_SUCCESS); CRYPT_EAL_CipherDeinit(ctx); ASSERT_EQ(CRYPT_EAL_CipherCtrl(ctx, CRYPT_CTRL_GET_TAG, tag, tagLen), CRYPT_EAL_ERR_STATE); ASSERT_EQ(CRYPT_EAL_CipherInit(ctx, key, keyLen, iv, ivLen, true), CRYPT_SUCCESS); ASSERT_EQ(CRYPT_EAL_CipherCtrl(ctx, CRYPT_CTRL_SET_AAD, aad, sizeof(aad)), CRYPT_SUCCESS); ASSERT_EQ(CRYPT_EAL_CipherCtrl(ctx, CRYPT_CTRL_SET_TAGLEN, &tagLen, sizeof(tagLen)), CRYPT_EAL_ERR_STATE); ASSERT_EQ(CRYPT_EAL_CipherInit(ctx, key, keyLen, iv, ivLen, true), CRYPT_SUCCESS); ASSERT_EQ(CRYPT_EAL_CipherCtrl(ctx, CRYPT_CTRL_SET_MSGLEN, &count, sizeof(count)), CRYPT_SUCCESS); ASSERT_EQ(CRYPT_EAL_CipherUpdate(ctx, data, 0, out, &outLen), CRYPT_SUCCESS); ASSERT_EQ(CRYPT_EAL_CipherReinit(ctx, iv, ivLen), CRYPT_SUCCESS); ASSERT_EQ(CRYPT_EAL_CipherCtrl(ctx, CRYPT_CTRL_GET_TAG, tag, tagLen), CRYPT_SUCCESS); ASSERT_EQ(CRYPT_EAL_CipherInit(ctx, key, keyLen, iv, ivLen, true), CRYPT_SUCCESS); ASSERT_EQ(CRYPT_EAL_CipherCtrl(ctx, CRYPT_CTRL_SET_MSGLEN, &count, sizeof(count)), CRYPT_SUCCESS); ASSERT_EQ(CRYPT_EAL_CipherUpdate(ctx, data, 0, out, &outLen), CRYPT_SUCCESS); ASSERT_EQ(CRYPT_EAL_CipherCtrl(ctx, CRYPT_CTRL_SET_MSGLEN, &count, sizeof(count)), CRYPT_EAL_ERR_STATE); ASSERT_EQ(CRYPT_EAL_CipherCtrl(ctx, CRYPT_CTRL_GET_TAG, tag, tagLen), CRYPT_SUCCESS); ASSERT_EQ(CRYPT_EAL_CipherInit(ctx, key, keyLen, iv, ivLen, true), CRYPT_SUCCESS); ASSERT_EQ(CRYPT_EAL_CipherCtrl(ctx, CRYPT_CTRL_SET_MSGLEN, &count, sizeof(count)), CRYPT_SUCCESS); ASSERT_EQ(CRYPT_EAL_CipherUpdate(ctx, data, 0, out, &outLen), CRYPT_SUCCESS); ASSERT_EQ(CRYPT_EAL_CipherCtrl(ctx, CRYPT_CTRL_SET_AAD, aad, sizeof(aad)), CRYPT_EAL_ERR_STATE); ASSERT_EQ(CRYPT_EAL_CipherCtrl(ctx, CRYPT_CTRL_GET_TAG, tag, tagLen), CRYPT_SUCCESS); ASSERT_EQ(CRYPT_EAL_CipherInit(ctx, key, keyLen, iv, ivLen, true), CRYPT_SUCCESS); ASSERT_EQ(CRYPT_EAL_CipherCtrl(ctx, CRYPT_CTRL_SET_MSGLEN, &count, sizeof(count)), CRYPT_SUCCESS); ASSERT_EQ(CRYPT_EAL_CipherUpdate(ctx, data, 0, out, &outLen), CRYPT_SUCCESS); ASSERT_EQ(CRYPT_EAL_CipherCtrl(ctx, CRYPT_CTRL_SET_TAGLEN, &tagLen, sizeof(tagLen)), CRYPT_EAL_ERR_STATE); ASSERT_EQ(CRYPT_EAL_CipherCtrl(ctx, CRYPT_CTRL_GET_TAG, tag, tagLen), CRYPT_SUCCESS); EXIT: CRYPT_EAL_CipherFreeCtx(ctx); } /* END_CASE */ /** * @test SDV_CRYPTO_AES_CCM_UPDATE_FUNC_TC002 * @title Test on the same address in plaintext and ciphertext * @precon Registering memory-related functions. * @brief * 1.Create the context ctx. Expected result 1 is obtained. * 2.Call the Init interface. Expected result 2 is obtained. * 3.Call the Ctrl interface, ctx is not NULL, and set tag len. Expected result 3 is obtained. * 4.Call the Ctrl interface, ctx is not NULL, and set msg len. Expected result 4 is obtained. * 5.Call the Ctrl interface, ctx is not NULL, and set aad. Expected result 5 is obtained. * 6.Call the Update interface, ctx is not NULL, and encrypt data. Expected result 6 is obtained. * 7.Compare the ciphertext. Expected result 7 is obtained. * 8.Compare the tag. Expected result 8 is obtained. * 9.Call the Deinit interface and Call the Init interface. Expected result 9 is obtained. * 10.Call the Ctrl interface set tag len. Expected result 10 is obtained. * 11.Call the Ctrl interface set msg len. Expected result 11 is obtained. * 12.Call the Ctrl interface set aad. Expected result 12 is obtained. * 13.Call the Update interface to decrypt data. Expected result 13 is obtained. * 14.Compare the plaintext. Expected result 14 is obtained. * 15.Compare the tag. Expected result 15 is obtained. * @expect * 1.The creation is successful and the ctx is not empty. * 2.Success. Return CRYPT_SUCCESS. * 3.Success. Return CRYPT_SUCCESS. * 4.Success. Return CRYPT_SUCCESS. * 5.Success. Return CRYPT_SUCCESS. * 6.Success. Return CRYPT_SUCCESS. * 7.Consistent with expected vector. * 8.Consistent with expected vector. * 9.Success, Return CRYPT_SUCCESS * 10.Success, Return CRYPT_SUCCESS * 11.Success, Return CRYPT_SUCCESS * 12.Success, Return CRYPT_SUCCESS * 13.Success, Return CRYPT_SUCCESS * 14.Consistent with expected vector. * 15.Consistent with expected vector. */ /* BEGIN_CASE */ void SDV_CRYPTO_AES_CCM_UPDATE_FUNC_TC002(int algId, Hex *key, Hex *iv, Hex *aad, Hex *pt, Hex *ct, Hex *tag) { #ifndef HITLS_CRYPTO_CCM SKIP_TEST(); #endif TestMemInit(); CRYPT_EAL_CipherCtx *ctx = NULL; uint8_t *outTag = NULL; uint8_t *out = NULL; uint32_t tagLen = tag->len; uint32_t outLen = pt->len; uint64_t msgLen = pt->len; out = (uint8_t *)malloc(outLen * sizeof(uint8_t)); ASSERT_TRUE(out != NULL); outTag = (uint8_t *)malloc(sizeof(uint8_t) * tagLen); ASSERT_TRUE(outTag != NULL); ASSERT_TRUE(memcpy_s(out, outLen, pt->x, pt->len) == EOK); ctx = CRYPT_EAL_CipherNewCtx(algId); ASSERT_TRUE(ctx != NULL); ASSERT_TRUE(CRYPT_EAL_CipherInit(ctx, key->x, key->len, iv->x, iv->len, true) == CRYPT_SUCCESS); ASSERT_TRUE(CRYPT_EAL_CipherCtrl(ctx, CRYPT_CTRL_SET_TAGLEN, &tagLen, sizeof(tagLen)) == CRYPT_SUCCESS); ASSERT_TRUE(CRYPT_EAL_CipherCtrl(ctx, CRYPT_CTRL_SET_MSGLEN, &msgLen, sizeof(msgLen)) == CRYPT_SUCCESS); ASSERT_TRUE(CRYPT_EAL_CipherCtrl(ctx, CRYPT_CTRL_SET_AAD, aad->x, aad->len) == CRYPT_SUCCESS); ASSERT_TRUE(CRYPT_EAL_CipherUpdate(ctx, out, pt->len, (uint8_t *)out, &outLen) == CRYPT_SUCCESS); ASSERT_TRUE(CRYPT_EAL_CipherCtrl(ctx, CRYPT_CTRL_GET_TAG, (uint8_t *)outTag, tagLen) == CRYPT_SUCCESS); ASSERT_COMPARE("Compare Ct", out, ct->len, ct->x, ct->len); ASSERT_COMPARE("Compare Enc Tag", outTag, tagLen, tag->x, tag->len); CRYPT_EAL_CipherDeinit(ctx); ASSERT_TRUE(memcpy_s(out, outLen, ct->x, ct->len) == EOK); ASSERT_TRUE(CRYPT_EAL_CipherInit(ctx, key->x, key->len, iv->x, iv->len, false) == CRYPT_SUCCESS); ASSERT_TRUE(CRYPT_EAL_CipherCtrl(ctx, CRYPT_CTRL_SET_TAGLEN, &tagLen, sizeof(tagLen)) == CRYPT_SUCCESS); ASSERT_TRUE(CRYPT_EAL_CipherCtrl(ctx, CRYPT_CTRL_SET_MSGLEN, &msgLen, sizeof(msgLen)) == CRYPT_SUCCESS); ASSERT_TRUE(CRYPT_EAL_CipherCtrl(ctx, CRYPT_CTRL_SET_AAD, aad->x, aad->len) == CRYPT_SUCCESS); ASSERT_TRUE(CRYPT_EAL_CipherUpdate(ctx, out, ct->len, (uint8_t *)out, &outLen) == CRYPT_SUCCESS); ASSERT_TRUE(CRYPT_EAL_CipherCtrl(ctx, CRYPT_CTRL_GET_TAG, (uint8_t *)outTag, tagLen) == CRYPT_SUCCESS); ASSERT_COMPARE("Compare Pt", out, pt->len, pt->x, pt->len); ASSERT_COMPARE("Compare Dec Tag", outTag, tagLen, tag->x, tag->len); EXIT: CRYPT_EAL_CipherFreeCtx(ctx); free(out); free(outTag); } /* END_CASE */ /** * @test SDV_CRYPTO_AES_CCM_MULTI_THREAD_FUNC_TC001 * @title Multi-thread Test * @precon Registering memory-related functions. * @brief * 1.Start three threads. Expected result 1 is obtained. * 2.Call the eal interface in the thread for encryption. Expected result 2 is obtained. * 3.Call the eal interface in the thread for decryption. Expected result 2 is obtained. * @expect * 1.Success. * 2.The encryption is successful. The ciphertext and tag are the same as the vector. * 3.The decryption is successful. The plaintext and tag are consistent with the vector. */ /* BEGIN_CASE */ void SDV_CRYPTO_AES_CCM_MULTI_THREAD_FUNC_TC001(int isProvider, int algId, Hex *key, Hex *iv, Hex *aad, Hex *pt, Hex *ct, Hex *tag) { int ret; TestMemInit(); const uint32_t threadNum = 3; // Number of threads. pthread_t thrd[threadNum]; ThreadParameter arg[3] = { // 3 Threads {.key = key->x, .iv = iv->x, .aad = aad->x, .pt = pt->x, .ct = ct->x, .tag = tag->x, .keyLen = key->len, .ivLen = iv->len, .aadLen = aad->len, .ptLen = pt->len, .ctLen = ct->len, .tagLen = tag->len, .algId = algId, .isProvider = isProvider}, {.key = key->x, .iv = iv->x, .aad = aad->x, .pt = pt->x, .ct = ct->x, .tag = tag->x, .keyLen = key->len, .ivLen = iv->len, .aadLen = aad->len, .ptLen = pt->len, .ctLen = ct->len, .tagLen = tag->len, .algId = algId, .isProvider = isProvider}, {.key = key->x, .iv = iv->x, .aad = aad->x, .pt = pt->x, .ct = ct->x, .tag = tag->x, .keyLen = key->len, .ivLen = iv->len, .aadLen = aad->len, .ptLen = pt->len, .ctLen = ct->len, .tagLen = tag->len, .algId = algId, .isProvider = isProvider}, }; for (uint32_t i = 0; i < threadNum; i++) { ret = pthread_create(&thrd[i], NULL, (void *)MultiThreadTest, &arg[i]); ASSERT_TRUE(ret == 0); } for (uint32_t i = 0; i < threadNum; i++) { pthread_join(thrd[i], NULL); } EXIT: return; } /* END_CASE */
2301_79861745/bench_create
testcode/sdv/testcase/crypto/aes/test_suite_sdv_eal_aes_ccm.c
C
unknown
42,413
/* * This file is part of the openHiTLS project. * * openHiTLS is licensed under the Mulan PSL v2. * You can use this software according to the terms and conditions of the Mulan PSL v2. * You may obtain a copy of Mulan PSL v2 at: * * http://license.coscl.org.cn/MulanPSL2 * * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, * EITHER EXPRESS 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 "securec.h" #include "bsl_sal.h" #include "crypt_errno.h" #include "crypt_modes_gcm.h" #include "crypt_local_types.h" #include "crypt_aes.h" #include "crypt_eal_cipher.h" #define FREE(res) \ do { \ if ((res) != NULL) { \ free(res); \ } \ } while (0) /* END_HEADER */ /** * @test SDV_CRYPTO_AES_GCM_UPDATE_FUNC_TC001 * @title AES-GCM decryption full vector test * @precon Registering memory-related functions. * @brief * 1.Call the Init interface. Expected result 1 is obtained. * 2.Call the Ctrl interface to set parameters. Expected result 2 is obtained. * 3.Call the update interface to update message. Expected result 3 is obtained. * 4.Call the Ctrl interface to get tag. Expected result 4 is obtained. * 5.Compare the plaintext data. Expected result 5 is obtained. * 6.Compare the tag data. Expected result 6 is obtained. * @expect * 1.The init is successful, return CRYPT_SUCCESS. * 2.The setting is successful, return CRYPT_SUCCESS. * 3.The update is successful, return CRYPT_SUCCESS. * 4.The getting is successful, return CRYPT_SUCCESS. * 5.Plaintext is consistent with the test vector. * 6.Tag is consistent with the test vector. */ /* BEGIN_CASE */ void SDV_CRYPTO_AES_GCM_UPDATE_FUNC_TC001(int isProvider, int algId, Hex *key, Hex *iv, Hex *aad, Hex *pt, Hex *ct, Hex *tag, int result) { #ifndef HITLS_CRYPTO_GCM SKIP_TEST(); #endif TestMemInit(); CRYPT_EAL_CipherCtx *ctx = NULL; uint8_t *outTag = NULL; uint8_t *out = NULL; uint32_t tagLen = tag->len; uint32_t outLen; if (ct->len > 0) { out = (uint8_t *)BSL_SAL_Malloc(ct->len * sizeof(uint8_t)); outLen = ct->len * sizeof(uint8_t); ASSERT_TRUE(out != NULL); } else { out = (uint8_t *)BSL_SAL_Malloc(1 * sizeof(uint8_t)); outLen = 1 * sizeof(uint8_t); ASSERT_TRUE(out != NULL); } ctx = TestCipherNewCtx(NULL, algId, "provider=default", isProvider); ASSERT_TRUE(ctx != NULL); ASSERT_TRUE(CRYPT_EAL_CipherInit(ctx, key->x, key->len, iv->x, iv->len, false) == CRYPT_SUCCESS); ASSERT_TRUE(CRYPT_EAL_CipherCtrl(ctx, CRYPT_CTRL_SET_TAGLEN, &tagLen, sizeof(tagLen)) == CRYPT_SUCCESS); ASSERT_TRUE(CRYPT_EAL_CipherCtrl(ctx, CRYPT_CTRL_SET_AAD, aad->x, aad->len) == CRYPT_SUCCESS); ASSERT_TRUE(CRYPT_EAL_CipherUpdate(ctx, ct->x, ct->len, (uint8_t *)out, &outLen) == CRYPT_SUCCESS); outTag = (uint8_t *)BSL_SAL_Malloc(sizeof(uint8_t) * tagLen); ASSERT_TRUE(outTag != NULL); ASSERT_TRUE(CRYPT_EAL_CipherCtrl(ctx, CRYPT_CTRL_GET_TAG, (uint8_t *)outTag, tagLen) == CRYPT_SUCCESS); if (pt->x != NULL) { ASSERT_TRUE(memcmp(out, pt->x, pt->len) == 0); } if (result == 0) { ASSERT_COMPARE("Compare Tag", outTag, tagLen, tag->x, tag->len); } else { ASSERT_TRUE(memcmp(outTag, tag->x, tag->len) != 0); } EXIT: CRYPT_EAL_CipherFreeCtx(ctx); FREE(out); FREE(outTag); } /* END_CASE */ /** * @test SDV_CRYPTO_AES_GCM_UPDATE_FUNC_TC002 * @title AES-GCM encryption full vector test * @precon Registering memory-related functions. * @brief * 1.Call the Init interface. Expected result 1 is obtained. * 2.Call the Ctrl interface to set parameters. Expected result 2 is obtained. * 3.Call the update interface to update message. Expected result 3 is obtained. * 4.Call the Ctrl interface to get tag. Expected result 4 is obtained. * 5.Compare the ciphertext data. Expected result 5 is obtained. * 6.Compare the tag data. Expected result 6 is obtained. * @expect * 1.The init is successful, return CRYPT_SUCCESS. * 2.The setting is successful, return CRYPT_SUCCESS. * 3.The update is successful, return CRYPT_SUCCESS. * 4.The getting is successful, return CRYPT_SUCCESS. * 5.Ciphertext is consistent with the test vector. * 6.Tag is consistent with the test vector. */ /* BEGIN_CASE */ void SDV_CRYPTO_AES_GCM_UPDATE_FUNC_TC002(int isProvider, int algId, Hex *key, Hex *iv, Hex *aad, Hex *pt, Hex *ct, Hex *tag) { #ifndef HITLS_CRYPTO_GCM SKIP_TEST(); #endif TestMemInit(); CRYPT_EAL_CipherCtx *ctx = NULL; uint8_t *outTag = NULL; uint8_t *out = NULL; uint32_t tagLen = tag->len; uint32_t outLen; if (ct->len > 0) { out = (uint8_t *)BSL_SAL_Malloc(ct->len * sizeof(uint8_t)); outLen = ct->len * sizeof(uint8_t); ASSERT_TRUE(out != NULL); } else { out = (uint8_t *)BSL_SAL_Malloc(1 * sizeof(uint8_t)); outLen = 1 * sizeof(uint8_t); ASSERT_TRUE(out != NULL); } ctx = TestCipherNewCtx(NULL, algId, "provider=default", isProvider); ASSERT_TRUE(ctx != NULL); ASSERT_TRUE(CRYPT_EAL_CipherInit(ctx, key->x, key->len, iv->x, iv->len, true) == CRYPT_SUCCESS); ASSERT_TRUE(CRYPT_EAL_CipherCtrl(ctx, CRYPT_CTRL_SET_TAGLEN, &tagLen, sizeof(tagLen)) == CRYPT_SUCCESS); ASSERT_TRUE(CRYPT_EAL_CipherCtrl(ctx, CRYPT_CTRL_SET_AAD, aad->x, aad->len) == CRYPT_SUCCESS); ASSERT_TRUE(CRYPT_EAL_CipherUpdate(ctx, pt->x, pt->len, (uint8_t *)out, &outLen) == CRYPT_SUCCESS); outTag = (uint8_t *)BSL_SAL_Malloc(sizeof(uint8_t) * tagLen); ASSERT_TRUE(outTag != NULL); ASSERT_TRUE(CRYPT_EAL_CipherCtrl(ctx, CRYPT_CTRL_GET_TAG, (uint8_t *)outTag, tagLen) == CRYPT_SUCCESS); if (ct->x != NULL) { ASSERT_TRUE(memcmp(out, ct->x, ct->len) == 0); } ASSERT_COMPARE("Compare Tag", outTag, tagLen, tag->x, tag->len); EXIT: CRYPT_EAL_CipherFreeCtx(ctx); FREE(out); FREE(outTag); } /* END_CASE */
2301_79861745/bench_create
testcode/sdv/testcase/crypto/aes/test_suite_sdv_eal_aes_gcm.c
C
unknown
6,263
/* * This file is part of the openHiTLS project. * * openHiTLS is licensed under the Mulan PSL v2. * You can use this software according to the terms and conditions of the Mulan PSL v2. * You may obtain a copy of Mulan PSL v2 at: * * http://license.coscl.org.cn/MulanPSL2 * * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, * EITHER EXPRESS 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 "securec.h" #include "bsl_sal.h" #include "crypt_errno.h" #include "crypt_modes_gcm.h" #include "crypt_local_types.h" #include "crypt_aes.h" #include "crypt_eal_cipher.h" #include "eal_cipher_local.h" #define DATA_LEN 16 #define DATA_MAX_LEN 1024 #define MAX_OUTPUT 50000 /* END_HEADER */ /** * @test SDV_CRYPTO_AES_MULTI_UPDATE_FUNC_TC001 * @title Impact of two updates on the encryption and decryption functions * @precon Registering memory-related functions. * @brief * 1.Call the EAL interface to encrypt a piece of data twice, and then verify the encryption result and tag. Expected result 1 is obtained. * 2.Call the EAL interface to decrypt a piece of data twice, and check the decryption result and tag. Expected result 2 is obtained. * @expect * 1.The encryption result and tag value are the same as expected, the verification is successful. * 2.The decryption result and tag value are the same as expected, the verification is successful. */ /* BEGIN_CASE */ void SDV_CRYPTO_AES_MULTI_UPDATE_FUNC_TC001(int algId, Hex *key, Hex *iv, Hex *aad, Hex *pt1, Hex *pt2, Hex *ct, Hex *tag) { if (IsCipherAlgDisabled(algId)) { SKIP_TEST(); } TestMemInit(); CRYPT_EAL_CipherCtx *ctx = NULL; uint32_t tagLen = tag->len; uint8_t result[DATA_MAX_LEN]; uint8_t tagResult[DATA_LEN]; uint32_t outLen = DATA_MAX_LEN; ctx = CRYPT_EAL_CipherNewCtx(algId); ASSERT_TRUE(ctx != NULL); ASSERT_TRUE(CRYPT_EAL_CipherInit(ctx, key->x, key->len, iv->x, iv->len, true) == CRYPT_SUCCESS); ASSERT_TRUE(CRYPT_EAL_CipherCtrl(ctx, CRYPT_CTRL_SET_TAGLEN, &tagLen, sizeof(tagLen)) == CRYPT_SUCCESS); ASSERT_TRUE(CRYPT_EAL_CipherCtrl(ctx, CRYPT_CTRL_SET_AAD, aad->x, aad->len) == CRYPT_SUCCESS); ASSERT_TRUE(CRYPT_EAL_CipherUpdate(ctx, pt1->x, pt1->len, result, &outLen) == CRYPT_SUCCESS); outLen = DATA_MAX_LEN - pt1->len; ASSERT_TRUE(CRYPT_EAL_CipherUpdate(ctx, pt2->x, pt2->len, result + pt1->len, &outLen) == CRYPT_SUCCESS); ASSERT_TRUE(CRYPT_EAL_CipherCtrl(ctx, CRYPT_CTRL_GET_TAG, (uint8_t *)tagResult, tag->len) == CRYPT_SUCCESS); ASSERT_COMPARE("enc result", (uint8_t *)result, pt1->len + pt2->len, ct->x, ct->len); ASSERT_COMPARE("enc tagResult", (uint8_t *)tagResult, tag->len, tag->x, tag->len); CRYPT_EAL_CipherFreeCtx(ctx); ctx = CRYPT_EAL_CipherNewCtx(algId); ASSERT_TRUE(ctx != NULL); ASSERT_TRUE(CRYPT_EAL_CipherInit(ctx, key->x, key->len, iv->x, iv->len, false) == CRYPT_SUCCESS); ASSERT_TRUE(CRYPT_EAL_CipherCtrl(ctx, CRYPT_CTRL_SET_TAGLEN, &tagLen, sizeof(tagLen)) == CRYPT_SUCCESS); ASSERT_TRUE(CRYPT_EAL_CipherCtrl(ctx, CRYPT_CTRL_SET_AAD, aad->x, aad->len) == CRYPT_SUCCESS); (void)memset_s(result, sizeof(result), 0, sizeof(result)); (void)memset_s(tagResult, sizeof(tagResult), 0, sizeof(tagResult)); outLen = DATA_MAX_LEN; ASSERT_TRUE(CRYPT_EAL_CipherUpdate(ctx, ct->x, pt1->len, result, &outLen) == CRYPT_SUCCESS); outLen = DATA_MAX_LEN - pt1->len; ASSERT_TRUE(CRYPT_EAL_CipherUpdate(ctx, ct->x + pt1->len, pt2->len, result + pt1->len, &outLen) == CRYPT_SUCCESS); ASSERT_TRUE(CRYPT_EAL_CipherCtrl(ctx, CRYPT_CTRL_GET_TAG, (uint8_t *)tagResult, tag->len) == CRYPT_SUCCESS); ASSERT_COMPARE("dec result1", (uint8_t *)result, pt1->len, pt1->x, pt1->len); ASSERT_COMPARE("dec result2", (uint8_t *)result + pt1->len, pt2->len, pt2->x, pt2->len); ASSERT_COMPARE("dec tagResult", (uint8_t *)tagResult, tag->len, tag->x, tag->len); EXIT: CRYPT_EAL_CipherFreeCtx(ctx); } /* END_CASE */ /** * @test SDV_CRYPTO_AES_MULTI_UPDATE_FUNC_TC002 * @title Impact of three updates on the encryption function * @precon Registering memory-related functions. * @brief * 1.Call the EAL interface to encrypt a piece of data for three times, and then verify the encryption result and tag. Expected result 1 is obtained. * 2.Call the EAL interface to decrypt a piece of data for three times, and then verify the decryption result and tag. Expected result 2 is obtained. * @expect * 1.The encryption result and tag value are the same as expected, the verification is successful. * 2.The decryption result and tag value are the same as expected, the verification is successful. */ /* BEGIN_CASE */ void SDV_CRYPTO_AES_MULTI_UPDATE_FUNC_TC002(int isProvider, int algId, Hex *key, Hex *iv, Hex *aad, Hex *pt1, Hex *pt2, Hex *pt3, Hex *ct, Hex *tag) { TestMemInit(); CRYPT_EAL_CipherCtx *ctx = NULL; CRYPT_EAL_CipherCtx *decCtx = NULL; uint32_t tagLen = tag->len; uint8_t result[DATA_MAX_LEN]; uint8_t tagResult[tagLen]; uint32_t outLen = DATA_MAX_LEN; uint64_t count; ctx = (isProvider == 0) ? CRYPT_EAL_CipherNewCtx(algId) : CRYPT_EAL_ProviderCipherNewCtx(NULL, algId, "provider=default"); ASSERT_TRUE(ctx != NULL); ASSERT_TRUE(CRYPT_EAL_CipherInit(ctx, key->x, key->len, iv->x, iv->len, true) == CRYPT_SUCCESS); if (algId == CRYPT_CIPHER_AES128_CCM || algId == CRYPT_CIPHER_AES192_CCM || algId == CRYPT_CIPHER_AES256_CCM) { count = pt1->len + pt2->len + pt3->len; ASSERT_TRUE(CRYPT_EAL_CipherCtrl(ctx, CRYPT_CTRL_SET_MSGLEN, &count, sizeof(count)) == CRYPT_SUCCESS); } ASSERT_TRUE(CRYPT_EAL_CipherCtrl(ctx, CRYPT_CTRL_SET_TAGLEN, &tagLen, sizeof(tagLen)) == CRYPT_SUCCESS); ASSERT_TRUE(CRYPT_EAL_CipherCtrl(ctx, CRYPT_CTRL_SET_AAD, aad->x, aad->len) == CRYPT_SUCCESS); ASSERT_TRUE(CRYPT_EAL_CipherUpdate(ctx, pt1->x, pt1->len, result, &outLen) == CRYPT_SUCCESS); outLen = DATA_MAX_LEN - pt1->len; ASSERT_TRUE(CRYPT_EAL_CipherUpdate(ctx, pt2->x, pt2->len, result + pt1->len, &outLen) == CRYPT_SUCCESS); outLen = DATA_MAX_LEN - pt1->len - pt2->len; ASSERT_TRUE(CRYPT_EAL_CipherUpdate(ctx, pt3->x, pt3->len, result + pt1->len + pt2->len, &outLen) == CRYPT_SUCCESS); ASSERT_TRUE(CRYPT_EAL_CipherCtrl(ctx, CRYPT_CTRL_GET_TAG, (uint8_t *)tagResult, tag->len) == CRYPT_SUCCESS); ASSERT_COMPARE("enc result", (uint8_t *)result, pt1->len + pt2->len + pt3->len, ct->x, ct->len); ASSERT_COMPARE("enc tagResult", (uint8_t *)tagResult, tag->len, tag->x, tag->len); (void)memset_s(result, sizeof(result), 0, sizeof(result)); (void)memset_s(tagResult, sizeof(tagResult), 0, sizeof(tagResult)); outLen = DATA_MAX_LEN; tagLen = tag->len; // decrypt decCtx = CRYPT_EAL_CipherNewCtx(algId); ASSERT_TRUE(CRYPT_EAL_CipherInit(decCtx, key->x, key->len, iv->x, iv->len, false) == CRYPT_SUCCESS); if (algId == CRYPT_CIPHER_AES128_CCM || algId == CRYPT_CIPHER_AES192_CCM || algId == CRYPT_CIPHER_AES256_CCM) { count = ct->len; ASSERT_TRUE(CRYPT_EAL_CipherCtrl(decCtx, CRYPT_CTRL_SET_MSGLEN, &count, sizeof(count)) == CRYPT_SUCCESS); } ASSERT_TRUE(CRYPT_EAL_CipherCtrl(decCtx, CRYPT_CTRL_SET_TAGLEN, &tagLen, sizeof(tagLen)) == CRYPT_SUCCESS); ASSERT_TRUE(CRYPT_EAL_CipherCtrl(decCtx, CRYPT_CTRL_SET_AAD, aad->x, aad->len) == CRYPT_SUCCESS); ASSERT_TRUE(CRYPT_EAL_CipherUpdate(decCtx, ct->x, pt1->len, result, &outLen) == CRYPT_SUCCESS); outLen = DATA_MAX_LEN - pt1->len; ASSERT_TRUE(CRYPT_EAL_CipherUpdate(decCtx, ct->x + pt1->len, pt2->len, result + pt1->len, &outLen) == CRYPT_SUCCESS); outLen = DATA_MAX_LEN - pt1->len - pt2->len; ASSERT_TRUE(CRYPT_EAL_CipherUpdate(decCtx, ct->x + pt1->len + pt2->len, pt3->len, result + pt1->len + pt2->len, &outLen) == CRYPT_SUCCESS); ASSERT_TRUE(CRYPT_EAL_CipherCtrl(decCtx, CRYPT_CTRL_GET_TAG, (uint8_t *)tagResult, tag->len) == CRYPT_SUCCESS); ASSERT_TRUE(memcmp(result, pt1->x, pt1->len) == 0); ASSERT_TRUE(memcmp(result + pt1->len, pt2->x, pt2->len) == 0); ASSERT_TRUE(memcmp(result + pt1->len + pt2->len, pt3->x, pt3->len) == 0); ASSERT_TRUE(memcmp(tagResult, tag->x, tag->len) == 0); EXIT: CRYPT_EAL_CipherFreeCtx(ctx); CRYPT_EAL_CipherFreeCtx(decCtx); } /* END_CASE */ /** * @test SDV_CRYPTO_AES_GETINFO_API_TC001 * @title CRYPT_EAL_CipherGetInfo Checking the Algorithm Grouping Mode Function Test * @precon Registering memory-related functions. * @brief * 1.Call the GetInfo interface with a correct ID, set type to CRYPT_INFO_IS_AEAD, and set infoStatus to NULL. Expected result 1 is obtained. * 2.Call the GetInfo interface with a wrong ID, set type to CRYPT_INFO_IS_AEAD, and set infoStatus to not NULL. Expected result 2 is obtained. * 3.Call the GetInfo interface with ID CRYPT_CIPHER_AES128_CCM, set type to CRYPT_INFO_MAX, and set infoStatus to not NULL. Expected result 3 is obtained. * 4.Call the GetInfo interface with ID CRYPT_CIPHER_AES128_CCM, set type to CRYPT_INFO_IS_AEAD, and set infoStatus to not NULL. Expected result 4 is obtained. * 5.Call the GetInfo interface with ID CRYPT_CIPHER_AES128_CFB, set type to CRYPT_INFO_IS_AEAD, and set infoStatus to not NULL. Expected result 5 is obtained. * 6.Call the GetInfo interface with ID CRYPT_CIPHER_AES128_CCM, set type to CRYPT_INFO_IS_STREAM, and set infoStatus to not NULL. Expected result 6 is obtained. * 7.Call the GetInfo interface with ID CRYPT_CIPHER_SM4_CBC, set type to CRYPT_INFO_IS_STREAM, and set infoStatus to not NULL. Expected result 7 is obtained. * 8.Call the GetInfo interface with ID CRYPT_CIPHER_AES128_CBC, set type to CRYPT_INFO_IV_LEN. Expected result 8 is obtained. * 9.Call the GetInfo interface with ID CRYPT_CIPHER_AES192_CBC, set type to CRYPT_INFO_KEY_LEN. Expected result 9 is obtained. * @expect * 1.Failed. Return CRYPT_INVALID_ARG. * 2.Failed. Return CRYPT_ERR_ALGID. * 3.Failed. Return CRYPT_EAL_INTO_TYPE_NOT_SUPPORT. * 4.Success. Return CRYPT_SUCCESS, infoStatus is 0. * 5.Success. Return CRYPT_SUCCESS, infoStatus is 1. * 6.Success. Return CRYPT_SUCCESS, infoStatus is 1. * 7.Success. Return CRYPT_SUCCESS, infoStatus is 0. * 8.Success. Return CRYPT_SUCCESS, ivLen is 16. * 9.Success. Return CRYPT_SUCCESS, keyLen is 24. */ /* BEGIN_CASE */ void SDV_CRYPTO_AES_GETINFO_API_TC001(void) { TestMemInit(); uint32_t infoStatus = 0; ASSERT_TRUE(CRYPT_EAL_CipherGetInfo(CRYPT_CIPHER_AES128_CCM, CRYPT_INFO_IS_AEAD, NULL) == CRYPT_INVALID_ARG); ASSERT_TRUE(CRYPT_EAL_CipherGetInfo(CRYPT_CIPHER_MAX, CRYPT_INFO_IS_AEAD, &infoStatus) == CRYPT_ERR_ALGID); ASSERT_TRUE(CRYPT_EAL_CipherGetInfo(CRYPT_CIPHER_AES128_CCM, CRYPT_INFO_MAX, &infoStatus) == CRYPT_EAL_INTO_TYPE_NOT_SUPPORT); ASSERT_TRUE(CRYPT_EAL_CipherGetInfo(CRYPT_CIPHER_AES128_CCM, CRYPT_INFO_IS_AEAD, &infoStatus) == CRYPT_SUCCESS); ASSERT_TRUE(infoStatus == 1); ASSERT_TRUE(CRYPT_EAL_CipherGetInfo(CRYPT_CIPHER_AES128_CFB, CRYPT_INFO_IS_AEAD, &infoStatus) == CRYPT_SUCCESS); ASSERT_TRUE(infoStatus == 0); ASSERT_TRUE(CRYPT_EAL_CipherGetInfo(CRYPT_CIPHER_AES128_CCM, CRYPT_INFO_IS_STREAM, &infoStatus) == CRYPT_SUCCESS); ASSERT_TRUE(infoStatus == 1); ASSERT_TRUE(CRYPT_EAL_CipherGetInfo(CRYPT_CIPHER_SM4_CBC, CRYPT_INFO_IS_STREAM, &infoStatus) == CRYPT_SUCCESS); ASSERT_TRUE(infoStatus == 0); uint32_t ivLen = 0; ASSERT_TRUE(CRYPT_EAL_CipherGetInfo(CRYPT_CIPHER_AES128_CBC, CRYPT_INFO_IV_LEN, &ivLen) == CRYPT_SUCCESS); ASSERT_TRUE(ivLen == 16); uint32_t keyLen = 0; ASSERT_TRUE(CRYPT_EAL_CipherGetInfo(CRYPT_CIPHER_AES192_CBC, CRYPT_INFO_KEY_LEN, &keyLen) == CRYPT_SUCCESS); ASSERT_TRUE(keyLen == 24); EXIT: return; } /* END_CASE */
2301_79861745/bench_create
testcode/sdv/testcase/crypto/aes/test_suite_sdv_eal_cipher.c
C
unknown
12,007
/* * This file is part of the openHiTLS project. * * openHiTLS is licensed under the Mulan PSL v2. * You can use this software according to the terms and conditions of the Mulan PSL v2. * You may obtain a copy of Mulan PSL v2 at: * * http://license.coscl.org.cn/MulanPSL2 * * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, * EITHER EXPRESS 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 "securec.h" #include "bsl_sal.h" #include "crypt_errno.h" #include "crypt_bn.h" #include "bn_basic.h" #include "crypt_eal_rand.h" #include "crypt_util_rand.h" #include "crypto_test_util.h" #if defined(HITLS_SIXTY_FOUR_BITS) #define BN_UINT_MAX UINT64_MAX #define BN_DIGITS_MAX 65 #define DH_BN_DIGITS_MAX 129 #elif defined(HITLS_THIRTY_TWO_BITS) #define BN_UINT_MAX UINT32_MAX #define BN_DIGITS_MAX 65 * 2 #define DH_BN_DIGITS_MAX 129 * 2 #else #error #endif #define BITS_OF_BYTE 8 #define BIGNUM_REDUNDANCY_BITS 64 #define LONG_BN_BYTES_32 32 #define SHORT_BN_BITS_128 128 #define LONG_BN_BITS_256 256 #define UINT8_MAX_NUM 255 #define BN_SIZE 1024 extern int32_t ModExpInputCheck( const BN_BigNum *r, const BN_BigNum *a, const BN_BigNum *e, const BN_BigNum *m, const BN_Optimizer *opt); extern int32_t ModExpCore(BN_BigNum *x, BN_BigNum *y, const BN_BigNum *e, const BN_BigNum *m, BN_Optimizer *opt); extern int32_t BnGcdCheckInput(const BN_BigNum *r, const BN_BigNum *a, const BN_BigNum *b, const BN_Optimizer *opt); extern int32_t InverseInputCheck(const BN_BigNum *r, const BN_BigNum *x, const BN_BigNum *m, const BN_Optimizer *opt); static int32_t TEST_Random(uint8_t *r, uint32_t randLen) { for (uint32_t i = 0; i < randLen; i++) { r[i] = rand() % UINT8_MAX_NUM; } return 0; } static int32_t TEST_RandomEx(void *libCtx, uint8_t *r, uint32_t randLen) { (void) libCtx; for (uint32_t i = 0; i < randLen; i++) { r[i] = rand() % UINT8_MAX_NUM; } return 0; } uint32_t TEST_GetMax(uint32_t num1, uint32_t num2, uint32_t num3) { uint32_t res = num1; res = (res > num2) ? res : num2; res = (res > num3) ? res : num3; return res; } BN_BigNum *TEST_VectorToBN(int sign, uint8_t *buff, uint32_t length) { if (length == 0) { return NULL; } BN_BigNum *bn = BN_Create(length * 8); // 8 bits per byte if (bn != NULL) { if (BN_Bin2Bn(bn, buff, length) != CRYPT_SUCCESS) { BN_Destroy(bn); bn = NULL; } else { BN_SetSign(bn, sign != 0); } } return bn; } void TEST_RegSimpleRand(void) { CRYPT_RandRegist(TestSimpleRand); } int32_t TEST_BnTestCaseInit(void) { TEST_RegSimpleRand(); TestMemInit(); return CRYPT_SUCCESS; } /* END_HEADER */ /** * @test SDV_CRYPTO_BN_CREATE_API_TC001 * @title BN_Create: Invalid parameter. * @precon nan * @brief * 1. Call the BN_Create method, input parameter is BN_MAX_BITS + 1, expected result 1 * 2. Call the BN_Create method, input parameter is 0, expected result 2 * @expect * 1. Return NULL. * 2. Return non-NULL. */ /* BEGIN_CASE */ void SDV_CRYPTO_BN_CREATE_API_TC001(void) { BN_BigNum *bn = NULL; TestMemInit(); bn = BN_Create((1u << 29) + 1); // BN_MAX_BITS + 1 ASSERT_TRUE(bn == NULL); bn = BN_Create(0); ASSERT_TRUE(bn != NULL); EXIT: BN_Destroy(bn); } /* END_CASE */ /** * @test SDV_CRYPTO_BN_SETSIGN_API_TC001 * @title BN_SetSign: Test invalid parameters and normal functions. * @precon nan * @brief * 1. Create BN_BigNum bn, the initial value is 0. * 2. Call the BN_SetSign method, a is null, expected result 1 * 3. Call the BN_SetSign method, a is bn, sign is true, expected result 2 * 4. Set bn to 1, expected result 3 * 5. Call the BN_SetSign method, a is bn, sign is true/false, expected result 4 * @expect * 1. CRYPT_NULL_INPUT * 2. CRYPT_BN_NO_NEGATIVE_ZERO * 3-4. CRYPT_SUCCESS */ /* BEGIN_CASE */ void SDV_CRYPTO_BN_SETSIGN_API_TC001(void) { BN_BigNum *bn = NULL; TestMemInit(); ASSERT_TRUE(BN_SetSign(NULL, 0) == CRYPT_NULL_INPUT); bn = BN_Create(BN_MAX_BITS); ASSERT_TRUE(bn != NULL); ASSERT_TRUE(BN_SetSign(bn, true) == CRYPT_BN_NO_NEGATIVE_ZERO); ASSERT_TRUE(BN_SetLimb(bn, 1) == CRYPT_SUCCESS); ASSERT_TRUE(BN_SetSign(bn, false) == CRYPT_SUCCESS); EXIT: BN_Destroy(bn); } /* END_CASE */ /** * @test SDV_CRYPTO_BN_COPY_API_TC001 * @title BN_Copy: The dest parameter space is smaller than src parameter. * @precon nan * @brief * 1. Call the BN_Copy method, parameters are all, expected result 1 * 2. Create BN_BigNum bn a and r, the size of r is half of a, expected result 2 * 3. Call the BN_Copy method, copy a to r, expected result 3 * @expect * 1. CRYPT_NULL_INPUT * 2. CRYPT_SUCCESS * 3. CRYPT_SUCCESS(Big number can be automatically expanded.) */ /* BEGIN_CASE */ void SDV_CRYPTO_BN_COPY_API_TC001(void) { BN_BigNum *r = NULL; BN_BigNum *a = NULL; uint8_t buff[LONG_BN_BYTES_32] = {'F'}; TestMemInit(); ASSERT_TRUE(BN_Copy(NULL, NULL) == CRYPT_NULL_INPUT); // r.room < a.bits r = BN_Create(SHORT_BN_BITS_128); ASSERT_TRUE(r != NULL); // SHORT_BN_BYTES 16 = 32 / 2 ASSERT_TRUE(BN_Bin2Bn(r, buff, sizeof(buff) / 2) == CRYPT_SUCCESS); a = BN_Create(LONG_BN_BITS_256); ASSERT_TRUE(a != NULL); ASSERT_TRUE(BN_Bin2Bn(a, buff, sizeof(buff)) == CRYPT_SUCCESS); ASSERT_TRUE(BN_Copy(r, a) == CRYPT_SUCCESS); EXIT: BN_Destroy(r); BN_Destroy(a); } /* END_CASE */ /** * @test SDV_CRYPTO_BN_ZEROIZE_API_TC001 * @title BN_Zeroize: Invalid parameter. * @precon nan * @brief * 1. Call the BN_Zeroize, parameter is null, expected result 1 * @expect * 1. CRYPT_NULL_INPUT */ /* BEGIN_CASE */ void SDV_CRYPTO_BN_ZEROIZE_API_TC001(void) { ASSERT_TRUE(BN_Zeroize(NULL) == CRYPT_NULL_INPUT); EXIT: return; } /* END_CASE */ /** * @test SDV_CRYPTO_BN_SETLIMB_API_TC001 * @title BN_SetLimb: Test invalid parameters and normal functions. * @precon nan * @brief * 1. Create BN_BigNum bn. * 2. Call the BN_SetLimb method, r is null, w is 0, expected result 1 * 3. Call the BN_SetLimb method, r is bn, w is 0, expected result 2 * @expect * 1. CRYPT_NULL_INPUT * 2. CRYPT_SUCCESS */ /* BEGIN_CASE */ void SDV_CRYPTO_BN_SETLIMB_API_TC001(void) { TestMemInit(); BN_BigNum *bn = BN_Create(1); ASSERT_TRUE(BN_SetLimb(NULL, 0) == CRYPT_NULL_INPUT); ASSERT_TRUE(BN_SetLimb(bn, 0) == CRYPT_SUCCESS); EXIT: BN_Destroy(bn); return; } /* END_CASE */ /** * @test SDV_CRYPTO_BN_SETBIT_API_TC001 * @title BN_SetBit: Test invalid parameters and normal functions. * @precon nan * @brief * 1. Create BN_BigNum bn. * 2. Call the BN_SetBit method, a is null, n is 0, expected result 1 * 3. Call the BN_SetBit method, a is bn, n is invalid, expected result 2 * 4. Call the BN_SetBit method, a is bn, n is valid, expected result 3 * @expect * 1. CRYPT_NULL_INPUT * 2. CRYPT_BN_SPACE_NOT_ENOUGH * 2. CRYPT_SUCCESS */ /* BEGIN_CASE */ void SDV_CRYPTO_BN_SETBIT_API_TC001(void) { TestMemInit(); BN_BigNum *bn = BN_Create(1); ASSERT_TRUE(BN_SetBit(NULL, 0) == CRYPT_NULL_INPUT); ASSERT_TRUE(BN_SetBit(bn, (uint32_t)sizeof(BN_UINT) << 3) == CRYPT_BN_SPACE_NOT_ENOUGH); ASSERT_TRUE(BN_SetBit(bn, ((uint32_t)sizeof(BN_UINT) << 3) - 1) == CRYPT_SUCCESS); EXIT: BN_Destroy(bn); return; } /* END_CASE */ /** * @test SDV_CRYPTO_BN_GETBIT_API_TC001 * @title BN_GetBit: Test invalid parameters and normal functions. * @precon nan * @brief * 1. Call the BN_GetBit method, a is null, n is 0, expected result 1 * 2. Create BN_BigNum bn, bn = 0, expected result 2 * 3. Call the BN_GetBit method, get the first bit of bn, expected result 3 * 4. Set limb of bn to BN_UINT_MAX, expected result 4 * 5. Call the BN_GetBit method, Check whether the number of the specified bit is 1: * (1) bit = limbBits - 1, expected result 5 * (1) bit = limbBits, expected result 6 * (1) bit = limbBits + 1, expected result 7 * @expect * 1. Return 0. * 2. CRYPT_SUCCESS * 3. The first bit of bn is 0. * 4. CRYPT_SUCCESS. The number of bits in the limb is limbBits. * 5. true * 6. false * 7. false */ /* BEGIN_CASE */ void SDV_CRYPTO_BN_GETBIT_API_TC001(void) { BN_BigNum *bn = NULL; const int limbBits = sizeof(BN_UINT) * BITS_OF_BYTE; ASSERT_TRUE(BN_GetBit(NULL, 0) == 0); TestMemInit(); bn = BN_Create(SHORT_BN_BITS_128); ASSERT_TRUE(bn != NULL); // a = 0 , n = 0 ASSERT_TRUE(BN_SetLimb(bn, 0) == CRYPT_SUCCESS); ASSERT_TRUE(BN_GetBit(bn, 0) == 0); ASSERT_TRUE(BN_SetLimb(bn, BN_UINT_MAX) == CRYPT_SUCCESS); ASSERT_TRUE(BN_GetBit(bn, limbBits - 1) == true); ASSERT_TRUE(BN_GetBit(bn, limbBits) == false); ASSERT_TRUE(BN_GetBit(bn, limbBits + 1) == false); EXIT: BN_Destroy(bn); } /* END_CASE */ /** * @test SDV_CRYPTO_BN_CLRBIT_API_TC001 * @title BN_ClrBit: Test invalid parameters and normal functions. * @precon nan * @brief * 1. Call the BN_ClrBit method, a is null, n is 0, expected result 1 * 2. Create BN_BigNum bn, and set bn to -1, expected result 2 * 3. Call the BN_ClrBit method, set the lowest bit to 0, expected result 3 * 4. Set bn to 1, expected result 4 * 5. Call the BN_ClrBit method, a is bn, n is BN_UINT_BITS, expected result 5 * 6. Call the BN_ClrBit method, a is bn, n is valid, expected result 6 * @expect * 1. CRYPT_NULL_INPUT * 2. CRYPT_SUCCESS * 3. CRYPT_SUCCESS, bn changed from - 1 to 0. * 4. CRYPT_SUCCESS * 5. CRYPT_BN_SPACE_NOT_ENOUGH * 6. CRYPT_SUCCESS */ /* BEGIN_CASE */ void SDV_CRYPTO_BN_CLRBIT_API_TC001(void) { BN_BigNum *bn = NULL; ASSERT_TRUE(BN_ClrBit(NULL, 0) == CRYPT_NULL_INPUT); TestMemInit(); bn = BN_Create(BN_MAX_BITS); /* bn = -1 */ ASSERT_TRUE(BN_SetLimb(bn, 1) == CRYPT_SUCCESS); ASSERT_TRUE(BN_SetSign(bn, 1) == CRYPT_SUCCESS); /* Set the lowest bit to 0. */ ASSERT_TRUE(BN_ClrBit(bn, 0) == CRYPT_SUCCESS); ASSERT_TRUE(BN_IsZero(bn)); ASSERT_TRUE(BN_IsNegative(bn) == false); /* bn = 1 */ ASSERT_TRUE(BN_SetLimb(bn, 1) == CRYPT_SUCCESS); ASSERT_EQ(BN_ClrBit(bn, ((uint32_t)sizeof(BN_UINT) << 3)), CRYPT_BN_SPACE_NOT_ENOUGH); // BN_UINT_BITS ASSERT_TRUE(BN_ClrBit(bn, ((uint32_t)sizeof(BN_UINT) << 3) - 1) == CRYPT_SUCCESS); // BN_UINT_BITS - 1 EXIT: BN_Destroy(bn); return; } /* END_CASE */ /** * @test SDV_CRYPTO_BN_RSHIFT_FUNC_TC001 * @title BN_Rshift test. * @precon Vectors: hex and its result after right-shifting n bits. * @brief * 1. Convert vectors to bn. * 2. Call BN_Rshift, and compared the result with vector, expected result 1: * (1) Pointer addresses for parameters are different from each other. * (2) The address of the output parameter pointer r is the same as that of the input parameter pointer a. * 3. Test the scenario where the output parameter space is insufficient, expected result 1. * @expect * 1. The calculation result is consistent with the vector. */ /* BEGIN_CASE */ void SDV_CRYPTO_BN_RSHIFT_FUNC_TC001(int sign, Hex *hex, int n, int signRes, Hex *result) { TestMemInit(); BN_BigNum *r = NULL; BN_BigNum *q = NULL; BN_BigNum *p = NULL; BN_BigNum *a = TEST_VectorToBN(sign, hex->x, hex->len); BN_BigNum *res = TEST_VectorToBN(signRes, result->x, result->len); ASSERT_TRUE(a != NULL && res != NULL); r = BN_Create(BN_Bits(a) + BIGNUM_REDUNDANCY_BITS); ASSERT_TRUE(r != NULL); ASSERT_EQ(BN_Rshift(r, a, n), CRYPT_SUCCESS); // r != a ASSERT_TRUE(BN_Cmp(r, res) == 0); ASSERT_EQ(BN_Copy(r, a), CRYPT_SUCCESS); ASSERT_EQ(BN_Rshift(r, r, n), CRYPT_SUCCESS); // r == a ASSERT_TRUE(BN_Cmp(r, res) == 0); /* Test the scenario where the output parameter space of q is insufficient */ q = BN_Create(0); ASSERT_TRUE(q != NULL); ASSERT_EQ(BN_Rshift(q, a, n), CRYPT_SUCCESS); // r != a ASSERT_TRUE(BN_Cmp(r, res) == 0); EXIT: BN_Destroy(a); BN_Destroy(r); BN_Destroy(q); BN_Destroy(p); BN_Destroy(res); } /* END_CASE */ /** * @test SDV_CRYPTO_BN_MODINV_API_TC001 * @title BN_ModInv test. * @precon nan * @brief * 1. Call BN_ModInv method: * (1) all parameters are valid, expected result 1. * (2) r is null, expected result 2. * (3) a is null, expected result 3. * (4) m is null, expected result 4. * (5) opt is null, expected result 5. * (6) a is zero or m is zero, expected result 6. * (7) r.room.bits < m.bits, expected result 7. * (8) r.room.bits = m.bits, expected result 8. * (9) r.room.bits > m.bits, expected result 9. * @expect * 1. CRYPT_SUCCESS * 2-5. CRYPT_NULL_INPUT * 6. CRYPT_BN_ERR_DIVISOR_ZERO * 7-9. CRYPT_SUCCESS */ /* BEGIN_CASE */ void SDV_CRYPTO_BN_MODINV_API_TC001(void) { TestMemInit(); uint8_t buff[LONG_BN_BYTES_32]; BN_BigNum *a = BN_Create(LONG_BN_BITS_256); BN_BigNum *m = BN_Create(LONG_BN_BITS_256); BN_BigNum *zero = BN_Create(LONG_BN_BITS_256); BN_BigNum *r128 = BN_Create(SHORT_BN_BITS_128); BN_BigNum *r256 = BN_Create(LONG_BN_BITS_256); BN_BigNum *r257 = BN_Create(LONG_BN_BITS_256 + 1); BN_Optimizer *opt = BN_OptimizerCreate(); ASSERT_TRUE(a != NULL && m != NULL && r128 != NULL && r256 != NULL && zero != NULL && opt != NULL); ASSERT_TRUE(BN_IsZero(zero) == true); // a = FF...FF (32 bytes) ASSERT_TRUE(memset_s(buff, sizeof(buff), 0xFF, LONG_BN_BYTES_32) == EOK); ASSERT_TRUE(BN_Bin2Bn(a, buff, LONG_BN_BYTES_32) == CRYPT_SUCCESS); // m == FF...FD (32 bytes) buff[LONG_BN_BYTES_32 - 1] = (uint8_t)0xFD; ASSERT_TRUE(BN_Bin2Bn(m, buff, LONG_BN_BYTES_32) == CRYPT_SUCCESS); // NULL ASSERT_TRUE(BN_ModInv(r256, a, m, opt) == CRYPT_SUCCESS); ASSERT_TRUE(BN_ModInv(NULL, a, m, opt) == CRYPT_NULL_INPUT); ASSERT_TRUE(BN_ModInv(r256, NULL, m, opt) == CRYPT_NULL_INPUT); ASSERT_TRUE(BN_ModInv(r256, a, NULL, opt) == CRYPT_NULL_INPUT); ASSERT_TRUE(BN_ModInv(r256, a, m, NULL) == CRYPT_NULL_INPUT); // zero ASSERT_TRUE(BN_ModInv(r256, a, zero, opt) == CRYPT_BN_ERR_DIVISOR_ZERO); ASSERT_TRUE(BN_ModInv(r256, zero, m, opt) == CRYPT_BN_ERR_DIVISOR_ZERO); // r.room.bits < m.bits ASSERT_TRUE(BN_ModInv(r128, a, m, opt) == CRYPT_SUCCESS); // r.room.bits == m.bits ASSERT_TRUE(BN_ModInv(r256, a, m, opt) == CRYPT_SUCCESS); // r.room.bits > m.bits ASSERT_TRUE(BN_ModInv(r257, a, m, opt) == CRYPT_SUCCESS); EXIT: BN_Destroy(a); BN_Destroy(m); BN_Destroy(zero); BN_Destroy(r128); BN_Destroy(r256); BN_Destroy(r257); BN_OptimizerDestroy(opt); } /* END_CASE */ /** * @test SDV_CRYPTO_BN_MODINV_FUNC_TC002 * @title BN_ModInv test. * @precon Vectors: hex1^(-1) mod modulo = result * @brief * 1. Convert vectors to bn. * 2. Call BN_ModInv, and compared the result with vector, expected result 1. * 3. If success is returned in the previous step, continue to test BN_ModInv when the output parameter address * is the same as the input parameter address. expected result 2: * (1) The address of the output parameter pointer r is the same as that of the input parameter pointer a. * (2) The address of the output parameter pointer r is the same as that of the input parameter pointer m. * 4. Test the scenario where the output parameter space is insufficient, expected result 2. * @expect * 1. Reutrn CRYPT_BN_ERR_NO_INVERSE on result is null. Otherwise, CRYPT_SUCCESS and result is same with vector. * 2. The calculation result is consistent with the vector. */ /* BEGIN_CASE */ void SDV_CRYPTO_BN_MODINV_FUNC_TC002(int sign, Hex *hex, Hex *modulo, Hex *result) { TestMemInit(); int32_t ret; BN_BigNum *res = NULL; BN_BigNum *r = NULL; BN_Optimizer *opt = BN_OptimizerCreate(); BN_BigNum *a = TEST_VectorToBN(sign, hex->x, hex->len); BN_BigNum *m = TEST_VectorToBN(0, modulo->x, modulo->len); ASSERT_TRUE(a != NULL && m != NULL && opt != NULL); r = BN_Create(BN_Bits(a) + BN_Bits(m) + BIGNUM_REDUNDANCY_BITS); ASSERT_TRUE(r != NULL); ASSERT_TRUE(BN_Copy(r, a) == CRYPT_SUCCESS); ret = BN_ModInv(r, a, m, opt); // r != a if (result->len == 0) { ASSERT_TRUE(ret == CRYPT_BN_ERR_NO_INVERSE); // No results exist } else { ASSERT_TRUE(ret == CRYPT_SUCCESS); res = BN_Create(result->len * BITS_OF_BYTE); ASSERT_TRUE(res != NULL); ASSERT_TRUE(BN_Bin2Bn(res, result->x, result->len) == CRYPT_SUCCESS); ASSERT_TRUE(BN_Cmp(r, res) == 0); ASSERT_TRUE(BN_Copy(r, a) == CRYPT_SUCCESS); ASSERT_TRUE(BN_ModInv(r, r, m, opt) == CRYPT_SUCCESS); ASSERT_TRUE_AND_LOG("r == a", BN_Cmp(r, res) == 0); ASSERT_TRUE(BN_Copy(r, m) == CRYPT_SUCCESS); ASSERT_TRUE(BN_ModInv(r, a, r, opt) == CRYPT_SUCCESS); ASSERT_TRUE_AND_LOG("r == m", BN_Cmp(r, res) == 0); BN_Destroy(r); /* Test the scenario where the output parameter space is insufficient. */ r = BN_Create(0); ASSERT_TRUE(r != NULL); ASSERT_TRUE(BN_ModInv(r, a, m, opt) == CRYPT_SUCCESS); ASSERT_TRUE(BN_Cmp(r, res) == 0); BN_Destroy(r); r = BN_Create(0); ASSERT_TRUE(r != NULL); ASSERT_TRUE(BN_Copy(r, a) == CRYPT_SUCCESS); ASSERT_TRUE(BN_ModInv(r, r, m, opt) == CRYPT_SUCCESS); ASSERT_TRUE_AND_LOG("r == a", BN_Cmp(r, res) == 0); BN_Destroy(r); r = BN_Create(0); ASSERT_TRUE(r != NULL); ASSERT_TRUE(BN_Copy(r, m) == CRYPT_SUCCESS); ASSERT_TRUE(BN_ModInv(r, a, r, opt) == CRYPT_SUCCESS); ASSERT_TRUE_AND_LOG("r == m", BN_Cmp(r, res) == 0); } EXIT: BN_Destroy(a); BN_Destroy(m); BN_Destroy(r); BN_Destroy(res); BN_OptimizerDestroy(opt); } /* END_CASE */ /** * @test SDV_CRYPTO_BN_MOD_EXP_INPUT_CHECK_API_TC001 * @title ModExpInputCheck: Test invalid parameters and normal functions. * @precon nan * @brief * 1. Call the ModExpInputCheck method, parameters are null,expected result 1 * 2. Call the ModExpInputCheck method, the size of r is smaller then m, expected result 2 * 3. Call the ModExpInputCheck method, m is 0, expected result 3 * 4. Call the ModExpInputCheck method, e is a negative number, expected result 4 * @expect * 1. CRYPT_NULL_INPUT * 2. CRYPT_SUCCESS * 3. CRYPT_BN_ERR_DIVISOR_ZERO * 4. CRYPT_BN_ERR_EXP_NO_NEGATIVE */ /* BEGIN_CASE */ void SDV_CRYPTO_BN_MOD_EXP_INPUT_CHECK_API_TC001(void) { BN_BigNum *bn = NULL; BN_BigNum *r = NULL; BN_BigNum *a = NULL; BN_BigNum *e = NULL; BN_BigNum *m = NULL; BN_Optimizer *opt = NULL; TestMemInit(); ASSERT_TRUE(ModExpInputCheck(NULL, NULL, NULL, NULL, NULL) == CRYPT_NULL_INPUT); bn = BN_Create(1); a = BN_Create(BN_MAX_BITS); e = BN_Create(BN_MAX_BITS); opt = BN_OptimizerCreate(); r = BN_Create(1); m = BN_Create(BN_MAX_BITS); ASSERT_TRUE(BN_SetBit(m, BN_SIZE) == CRYPT_SUCCESS); ASSERT_TRUE(ModExpInputCheck(r, a, e, m, opt) == CRYPT_SUCCESS); BN_Destroy(r); r = BN_Create(BN_MAX_BITS); ASSERT_TRUE(ModExpInputCheck(r, a, e, bn, opt) == CRYPT_BN_ERR_DIVISOR_ZERO); ASSERT_TRUE(BN_SetBit(e, BN_SIZE) == CRYPT_SUCCESS); ASSERT_TRUE(BN_SetSign(e, true) == CRYPT_SUCCESS); ASSERT_TRUE(ModExpInputCheck(r, a, e, m, opt) == CRYPT_BN_ERR_EXP_NO_NEGATIVE); EXIT: BN_Destroy(bn); BN_Destroy(r); BN_Destroy(a); BN_Destroy(e); BN_Destroy(m); BN_OptimizerDestroy(opt); } /* END_CASE */ /** * @test SDV_CRYPTO_BN_MODEXP_API_TC001 * @title BN_ModExp: Test invalid parameters. * @precon nan * @brief * 1. Call the BN_ModExp method, parameters are null, expected result 1 * 2. Call the BN_ModExp method, the size of r is smaller then m, expected result 2 * @expect * 1. CRYPT_NULL_INPUT * 2. CRYPT_SUCCESS */ /* BEGIN_CASE */ void SDV_CRYPTO_BN_MODEXP_API_TC001(void) { uint8_t buff[LONG_BN_BYTES_32]; TestMemInit(); BN_BigNum *a = BN_Create(LONG_BN_BITS_256); BN_BigNum *e = BN_Create(LONG_BN_BITS_256); BN_BigNum *r = BN_Create(LONG_BN_BITS_256); BN_BigNum *m = BN_Create(LONG_BN_BITS_256); BN_Optimizer *opt = BN_OptimizerCreate(); ASSERT_TRUE(a != NULL); ASSERT_TRUE(e != NULL); ASSERT_TRUE(r != NULL); ASSERT_TRUE(m != NULL); ASSERT_TRUE(opt != NULL); ASSERT_TRUE(memset_s(buff, sizeof(buff), 0xFF, LONG_BN_BYTES_32) == EOK); ASSERT_TRUE(BN_Bin2Bn(a, buff, LONG_BN_BYTES_32) == CRYPT_SUCCESS); ASSERT_TRUE(BN_Bin2Bn(e, buff, LONG_BN_BYTES_32) == CRYPT_SUCCESS); ASSERT_TRUE(BN_Bin2Bn(m, buff, LONG_BN_BYTES_32) == CRYPT_SUCCESS); // NULL ASSERT_TRUE(BN_ModExp(NULL, NULL, NULL, NULL, NULL) == CRYPT_NULL_INPUT); BN_Destroy(r); r = BN_Create(LONG_BN_BITS_256 - BIGNUM_REDUNDANCY_BITS); ASSERT_TRUE(BN_ModExp(r, a, e, m, opt) == CRYPT_SUCCESS); EXIT: BN_Destroy(a); BN_Destroy(e); BN_Destroy(r); BN_Destroy(m); BN_OptimizerDestroy(opt); } /* END_CASE */ /** * @test SDV_CRYPTO_BN_MODEXP_API_TC002 * @title BN_ModExp: Invalid parameter and function test. * @precon nan * @brief * 1. Call the BN_ModExp method, the divisor is 0, expected result 1 * 2. Call the BN_ModExp method, the value of the exponent is negative, expected result 2 * 3. Call the BN_ModExp method, all parameters are valid, expected result 3 * @expect * 1. CRYPT_BN_ERR_DIVISOR_ZERO * 2. CRYPT_BN_ERR_EXP_NO_NEGATIVE * 3. CRYPT_SUCCESS */ /* BEGIN_CASE */ void SDV_CRYPTO_BN_MODEXP_API_TC002(void) { uint8_t buff[LONG_BN_BYTES_32]; BN_BigNum *a = BN_Create(LONG_BN_BYTES_32 * 8); BN_BigNum *e = BN_Create(LONG_BN_BYTES_32 * 8); BN_BigNum *m = BN_Create(LONG_BN_BYTES_32 * 8); BN_BigNum *r = BN_Create(LONG_BN_BITS_256); BN_BigNum *zero = BN_Create(LONG_BN_BITS_256); BN_BigNum *one = BN_Create(LONG_BN_BITS_256); BN_BigNum *negOne = BN_Create(LONG_BN_BITS_256); BN_Optimizer *opt = BN_OptimizerCreate(); TestMemInit(); ASSERT_TRUE(r != NULL); ASSERT_TRUE(zero != NULL); ASSERT_TRUE(one != NULL); ASSERT_TRUE(negOne != NULL); ASSERT_TRUE(opt != NULL); ASSERT_TRUE(memset_s(buff, sizeof(buff), 0xFF, LONG_BN_BYTES_32) == EOK); ASSERT_TRUE(a != NULL); ASSERT_TRUE(BN_Bin2Bn(a, buff, LONG_BN_BYTES_32) == CRYPT_SUCCESS); ASSERT_TRUE(BN_SetSign(a, false) == CRYPT_SUCCESS); ASSERT_TRUE(e != NULL); ASSERT_TRUE(BN_Bin2Bn(e, buff, LONG_BN_BYTES_32) == CRYPT_SUCCESS); ASSERT_TRUE(BN_SetSign(e, false) == CRYPT_SUCCESS); ASSERT_TRUE(m != NULL); ASSERT_TRUE(BN_Bin2Bn(m, buff, LONG_BN_BYTES_32) == CRYPT_SUCCESS); ASSERT_TRUE(BN_SetSign(m, false) == CRYPT_SUCCESS); ASSERT_TRUE(BN_Zeroize(zero) == CRYPT_SUCCESS); ASSERT_TRUE(BN_SetLimb(one, 1) == CRYPT_SUCCESS); ASSERT_TRUE(BN_SetLimb(negOne, 1) == CRYPT_SUCCESS); ASSERT_TRUE(BN_SetSign(negOne, true) == CRYPT_SUCCESS); ASSERT_TRUE(BN_ModExp(r, a, e, zero, opt) == CRYPT_BN_ERR_DIVISOR_ZERO); ASSERT_TRUE(BN_ModExp(r, a, negOne, m, opt) == CRYPT_BN_ERR_EXP_NO_NEGATIVE); ASSERT_TRUE(BN_ModExp(r, zero, zero, m, opt) == CRYPT_SUCCESS); ASSERT_TRUE(BN_Cmp(r, one) == 0); ASSERT_TRUE(BN_ModExp(r, zero, zero, one, opt) == CRYPT_SUCCESS); ASSERT_TRUE(BN_Cmp(r, zero) == 0); ASSERT_TRUE(BN_ModExp(r, a, e, negOne, opt) == CRYPT_SUCCESS); ASSERT_TRUE(BN_Cmp(r, zero) == 0); EXIT: BN_Destroy(a); BN_Destroy(e); BN_Destroy(r); BN_Destroy(m); BN_Destroy(zero); BN_Destroy(one); BN_Destroy(negOne); BN_OptimizerDestroy(opt); } /* END_CASE */ /** * @test SDV_CRYPTO_BN_MODEXP_FUNC_TC001 * @title BN_ModExp test. * @precon Vectors: two big numbers, mod, result. * @brief * 1. Convert vectors to big numbers. * 2. Call BN_ModExp to calculate the modular exponentiation, and compared to the vector value, expected result 1: * (1) Pointer addresses for parameters are different from each other. * (2) The address of the output parameter pointer r is the same as that of the input parameter pointer a. * (3) The address of the output parameter pointer r is the same as that of the input parameter pointer e. * (4) The address of the output parameter pointer r is the same as that of the input parameter pointer m. * 3. Test the scenario where the output parameter space is insufficient, expected result 1. * @expect * 1. The calculation result is consistent with the vector. */ /* BEGIN_CASE */ void SDV_CRYPTO_BN_MODEXP_FUNC_TC001(int sign1, Hex *hex1, Hex *hex2, Hex *modulo, Hex *result) { TestMemInit(); BN_BigNum *r = NULL; BN_Optimizer *opt = NULL; uint32_t maxBits; BN_BigNum *res = TEST_VectorToBN(0, result->x, result->len); BN_BigNum *a = TEST_VectorToBN(sign1, hex1->x, hex1->len); BN_BigNum *e = TEST_VectorToBN(0, hex2->x, hex2->len); BN_BigNum *m = TEST_VectorToBN(0, modulo->x, modulo->len); ASSERT_TRUE(res != NULL && a != NULL && e != NULL && m != NULL); maxBits = TEST_GetMax(BN_Bits(a), BN_Bits(e), BN_Bits(m)); r = BN_Create(maxBits + BIGNUM_REDUNDANCY_BITS); ASSERT_TRUE(r != NULL); opt = BN_OptimizerCreate(); ASSERT_TRUE(opt != NULL); ASSERT_TRUE(BN_Copy(r, a) == CRYPT_SUCCESS); ASSERT_TRUE(BN_ModExp(r, a, e, m, opt) == CRYPT_SUCCESS); // r != a ASSERT_TRUE_AND_LOG("r != a", BN_Cmp(r, res) == 0); ASSERT_TRUE(BN_Copy(r, a) == CRYPT_SUCCESS); ASSERT_TRUE(BN_ModExp(r, r, e, m, opt) == CRYPT_SUCCESS); // r == a ASSERT_TRUE_AND_LOG("r == a", BN_Cmp(r, res) == 0); ASSERT_TRUE(BN_Copy(r, e) == CRYPT_SUCCESS); ASSERT_TRUE(BN_ModExp(r, a, r, m, opt) == CRYPT_SUCCESS); // r == e ASSERT_TRUE_AND_LOG("r == e", BN_Cmp(r, res) == 0); ASSERT_TRUE(BN_Copy(r, m) == CRYPT_SUCCESS); ASSERT_TRUE(BN_ModExp(r, a, e, r, opt) == CRYPT_SUCCESS); // r == m ASSERT_TRUE_AND_LOG("r == m", BN_Cmp(r, res) == 0); // Test the scenario where the output parameter space is insufficient. BN_Destroy(r); r = BN_Create(0); ASSERT_TRUE(r != NULL); ASSERT_TRUE(BN_ModExp(r, a, e, m, opt) == CRYPT_SUCCESS); // r != a ASSERT_TRUE_AND_LOG("r != a", BN_Cmp(r, res) == 0); BN_Destroy(r); r = BN_Create(0); ASSERT_TRUE(r != NULL); ASSERT_TRUE(BN_Copy(r, a) == CRYPT_SUCCESS); ASSERT_TRUE(BN_ModExp(r, r, e, m, opt) == CRYPT_SUCCESS); // r == a ASSERT_TRUE_AND_LOG("r == a", BN_Cmp(r, res) == 0); BN_Destroy(r); r = BN_Create(0); ASSERT_TRUE(r != NULL); ASSERT_TRUE(BN_Copy(r, e) == CRYPT_SUCCESS); ASSERT_TRUE(BN_ModExp(r, a, r, m, opt) == CRYPT_SUCCESS); // r == e ASSERT_TRUE_AND_LOG("r == e", BN_Cmp(r, res) == 0); BN_Destroy(r); r = BN_Create(0); ASSERT_TRUE(r != NULL); ASSERT_TRUE(BN_Copy(r, m) == CRYPT_SUCCESS); ASSERT_TRUE(BN_ModExp(r, a, e, r, opt) == CRYPT_SUCCESS); // r == m ASSERT_TRUE_AND_LOG("r == m", BN_Cmp(r, res) == 0); EXIT: BN_Destroy(a); BN_Destroy(e); BN_Destroy(m); BN_Destroy(r); BN_Destroy(res); BN_OptimizerDestroy(opt); } /* END_CASE */ /** * @test SDV_CRYPTO_BN_MODEXPCORE_API_TC001 * @title ModExpCore: Invalid parameter. * @precon nan * @brief * 1. Call the ModExpCore method, the divisor is 0, expected result 1 * @expect * 1. CRYPT_BN_ERR_DIVISOR_ZERO */ /* BEGIN_CASE */ void SDV_CRYPTO_BN_MODEXPCORE_API_TC001(void) { TestMemInit(); BN_BigNum *a = BN_Create(LONG_BN_BITS_256); BN_BigNum *e = BN_Create(LONG_BN_BITS_256); BN_BigNum *r = BN_Create(LONG_BN_BITS_256); BN_BigNum *m = BN_Create(LONG_BN_BITS_256); BN_Optimizer *opt = BN_OptimizerCreate(); ASSERT_TRUE(BN_SetLimb(e, 10) == CRYPT_SUCCESS); ASSERT_TRUE(ModExpCore(r, a, e, m, opt) == CRYPT_BN_ERR_DIVISOR_ZERO); EXIT: BN_Destroy(a); BN_Destroy(e); BN_Destroy(r); BN_Destroy(m); BN_OptimizerDestroy(opt); } /* END_CASE */ /** * @test SDV_CRYPTO_BN_MOD_API_TC001 * @title BN_Mod: Invalid parameter. * @precon nan * @brief * 1. Call the BN_Mod method, all parameters are null, expected result 1 * 2. Call the BN_Mod method, mod is UINT8_MAX_NUM, expected result 2 * 3. Call the BN_Mod method, mod is 0, expected result 3 * @expect * 1. CRYPT_NULL_INPUT * 2. CRYPT_SUCCESS * 3. CRYPT_BN_ERR_DIVISOR_ZERO */ /* BEGIN_CASE */ void SDV_CRYPTO_BN_MOD_API_TC001(void) { TestMemInit(); BN_BigNum *a = BN_Create(LONG_BN_BITS_256); BN_BigNum *r = BN_Create(SHORT_BN_BITS_128); BN_BigNum *m = BN_Create(LONG_BN_BITS_256); BN_Optimizer *opt = BN_OptimizerCreate(); ASSERT_TRUE(BN_Mod(NULL, NULL, NULL, NULL) == CRYPT_NULL_INPUT); ASSERT_TRUE(BN_SetBit(m, UINT8_MAX_NUM) == CRYPT_SUCCESS); ASSERT_TRUE(BN_Mod(r, a, m, opt) == CRYPT_SUCCESS); ASSERT_TRUE(BN_SetLimb(m, 0) == CRYPT_SUCCESS); ASSERT_TRUE(BN_Mod(r, a, m, opt) == CRYPT_BN_ERR_DIVISOR_ZERO); EXIT: BN_Destroy(a); BN_Destroy(r); BN_Destroy(m); BN_OptimizerDestroy(opt); } /* END_CASE */ /** * @test SDV_CRYPTO_BN_MOD_FUNC_TC001 * @title BN_Mod test. * @precon Vectors: hex1 mod module = result * @brief * 1. Convert vectors to bn. * 2. Call BN_Mod, and compared the result with vector, expected result 1: * (1) Pointer addresses for parameters are different from each other. * (2) The address of the output parameter pointer r is the same as that of the input parameter pointer a. * (3) The address of the output parameter pointer r is the same as that of the input parameter pointer m. * 3. Test the scenario where the output parameter space is insufficient, expected result 1. * @expect * 1. The calculation result is consistent with the vector. */ /* BEGIN_CASE */ void SDV_CRYPTO_BN_MOD_FUNC_TC001(int sign1, Hex *hex1, int sign2, Hex *modulo, Hex *result) { TestMemInit(); BN_BigNum *r = NULL; BN_Optimizer *opt = NULL; BN_BigNum *res = TEST_VectorToBN(0, result->x, result->len); BN_BigNum *a = TEST_VectorToBN(sign1, hex1->x, hex1->len); BN_BigNum *m = TEST_VectorToBN(sign2, modulo->x, modulo->len); ASSERT_TRUE(a != NULL && m != NULL && res != NULL); r = BN_Create(BN_Bits(a) + BN_Bits(m) + BIGNUM_REDUNDANCY_BITS); ASSERT_TRUE(r != NULL); opt = BN_OptimizerCreate(); ASSERT_TRUE(opt != NULL); ASSERT_EQ(BN_Copy(r, a), CRYPT_SUCCESS); ASSERT_EQ(BN_Mod(r, a, m, opt), CRYPT_SUCCESS); ASSERT_TRUE_AND_LOG("r != a", BN_Cmp(r, res) == 0); ASSERT_EQ(BN_Copy(r, a), CRYPT_SUCCESS); ASSERT_EQ(BN_Mod(r, r, m, opt), CRYPT_SUCCESS); ASSERT_TRUE_AND_LOG("r == a", BN_Cmp(r, res) == 0); ASSERT_EQ(BN_Copy(r, m), CRYPT_SUCCESS); ASSERT_EQ(BN_Mod(r, a, r, opt), CRYPT_SUCCESS); ASSERT_TRUE_AND_LOG("r == m", BN_Cmp(r, res) == 0); /* Test the scenario where the output parameter space is insufficient. */ BN_Destroy(r); r = BN_Create(0); ASSERT_TRUE(r != NULL); ASSERT_EQ(BN_Mod(r, a, m, opt), CRYPT_SUCCESS); ASSERT_TRUE_AND_LOG("r != a", BN_Cmp(r, res) == 0); ASSERT_EQ(BN_Copy(r, m), CRYPT_SUCCESS); ASSERT_EQ(BN_Mod(r, a, r, opt), CRYPT_SUCCESS); ASSERT_TRUE_AND_LOG("r == m", BN_Cmp(r, res) == 0); BN_Destroy(r); r = BN_Create(0); ASSERT_TRUE(r != NULL); ASSERT_EQ(BN_Copy(r, a), CRYPT_SUCCESS); ASSERT_EQ(BN_Mod(r, r, m, opt), CRYPT_SUCCESS); ASSERT_TRUE_AND_LOG("r == a", BN_Cmp(r, res) == 0); EXIT: BN_Destroy(a); BN_Destroy(m); BN_Destroy(r); BN_Destroy(res); BN_OptimizerDestroy(opt); } /* END_CASE */ /** * @test SDV_CRYPTO_BN_PRIMECHECK_API_TC001 * @title BN_PrimeCheck: Invalid parameter. * @precon nan * @brief * 1. Create BN_BigNum bn, set the value of bn to 10, expected result 1 * 2. Call the BN_PrimeCheck to check bn, expected result 2 * @expect * 1. CRYPT_SUCCESS * 1. CRYPT_BN_NOR_CHECK_PRIME */ /* BEGIN_CASE */ void SDV_CRYPTO_BN_PRIMECHECK_API_TC001(void) { TestMemInit(); BN_BigNum *bn = BN_Create(LONG_BN_BITS_256); BN_Optimizer *opt = BN_OptimizerCreate(); ASSERT_TRUE(BN_SetLimb(bn, 10) == CRYPT_SUCCESS); // bn == 10 ASSERT_TRUE(BN_PrimeCheck(bn, 0, opt, NULL) == CRYPT_BN_NOR_CHECK_PRIME); EXIT: BN_Destroy(bn); BN_OptimizerDestroy(opt); } /* END_CASE */ /** * @test SDV_CRYPTO_BN_PRIME_CHECK_FUNC_TC001 * @title BN_PrimeCheck method test. * @precon A big number and information about whether the big number is prime. * @brief * 1. Convert hex to bn. * 2. Init the drbg. * 3. Call the BN_PrimeCheck method to check whether the big number is prime, expected result 1 * @expect * 1. Return CRYPT_SUCCESS on isPrime != 0, CRYPT_BN_NOR_CHECK_PRIME otherwise. */ /* BEGIN_CASE */ void SDV_CRYPTO_BN_PRIME_CHECK_FUNC_TC001(Hex *hex, int isPrime) { #ifndef HITLS_CRYPTO_DRBG (void)hex; (void)isPrime; SKIP_TEST(); #else TestMemInit(); int32_t ret; BN_BigNum *bn = BN_Create(hex->len * BITS_OF_BYTE); BN_Optimizer *opt = BN_OptimizerCreate(); ASSERT_TRUE(bn != NULL && opt != NULL); ASSERT_EQ(BN_Bin2Bn(bn, hex->x, hex->len), CRYPT_SUCCESS); ASSERT_EQ(TestRandInit(), CRYPT_SUCCESS); ret = BN_PrimeCheck(bn, 0, opt, NULL); if (isPrime != 0) { ASSERT_EQ(ret, CRYPT_SUCCESS); } else { ASSERT_EQ(ret, CRYPT_BN_NOR_CHECK_PRIME); } EXIT: TestRandDeInit(); BN_Destroy(bn); BN_OptimizerDestroy(opt); #endif } /* END_CASE */ static int32_t PrimeGenCb(BN_CbCtx *callBack, int32_t process, int32_t target) { if (callBack == NULL) return CRYPT_SUCCESS; int32_t *limit = BN_CbCtxGetArg(callBack); if (process < *limit) { return CRYPT_SUCCESS; } (void)target; printf("now try tims is %d, gen failed\n", process); return -1; } /** * @test SDV_CRYPTO_BN_GENPRIMELIMB_API_TC001 * @title BN_GenPrime method test. * @precon nan * @brief * 1. Create BN_CbCtx and call the BN_CbCtxSet method to register BN_CallBack method. * 2. Init the drbg. * 3. Call the BN_GenPrime method to generate prime, bits is LONG_BN_BITS_256, half is false, expected result 1 * 4. Call the BN_GenPrime method to generate prime, bits < 14, half is true, expected result 2 * 5. Call the BN_GenPrime method to generate prime, bits is 10, expected result 3 * @expect * 1-3. CRYPT_SUCCESS */ /* BEGIN_CASE */ void SDV_CRYPTO_BN_GENPRIMELIMB_API_TC001(void) { TestMemInit(); BN_Optimizer *opt = BN_OptimizerCreate(); ASSERT_TRUE(opt != NULL); BN_CbCtx *cb = BN_CbCtxCreate(); ASSERT_TRUE(cb != NULL); int32_t limit = 256; BN_CbCtxSet(cb, PrimeGenCb, &limit); const uint32_t bits = LONG_BN_BITS_256; bool half = false; BN_BigNum *r = BN_Create(LONG_BN_BITS_256); ASSERT_TRUE(r != NULL); CRYPT_RandRegist(TEST_Random); CRYPT_RandRegistEx(TEST_RandomEx); ASSERT_TRUE(BN_GenPrime(r, NULL, bits, half, opt, cb) == CRYPT_SUCCESS); ASSERT_TRUE(BN_GenPrime(r, NULL, 13, true, opt, cb) == CRYPT_SUCCESS); ASSERT_TRUE(BN_GenPrime(r, NULL, 10, half, opt, cb) == CRYPT_SUCCESS); EXIT: BN_CbCtxDestroy(cb); BN_Destroy(r); BN_OptimizerDestroy(opt); } /* END_CASE */ /** * @test SDV_CRYPTO_BN_ADDLIMB_FUNC_TC001 * @title BN_AddLimb method test. * @precon nan * @brief * 1. Convert vectors to big numbers. * 2. Call the BN_AddLimb method to calculate the sum of two numbers, expected result 1. * 3. If expectRet=CRYPT_SUCCESS, call the BN_Cmp to compare r and resHex, expected result 3. * @expect * 1. The return value is the same as 'expectRet'. * 2. The calculated sum is 0. * 3. Both are the same. */ /* BEGIN_CASE */ void SDV_CRYPTO_BN_ADDLIMB_FUNC_TC001(int sign, Hex *rHex, int limb, int resSign, Hex *resHex, int expectRet) { TestMemInit(); BN_BigNum *resBn = NULL; BN_BigNum *a = TEST_VectorToBN(sign, rHex->x, rHex->len); BN_BigNum *r = TEST_VectorToBN(resSign, resHex->x, resHex->len); /* a and r can be null. */ resBn = BN_Create(SHORT_BN_BITS_128); ASSERT_TRUE(resBn != NULL); ASSERT_EQ(BN_AddLimb(resBn, a, limb), expectRet); if (expectRet == CRYPT_SUCCESS) { ASSERT_EQ(BN_Cmp(resBn, r), 0); } EXIT: BN_Destroy(a); BN_Destroy(r); BN_Destroy(resBn); } /* END_CASE */ /** * @test SDV_CRYPTO_BN_SUB_FUNC_TC001 * @title BN_Sub test. * @precon Vectors: hex1 - hex2 = result * @brief * 1. Convert vectors to big numbers. * 2. Call BN_Sub to calculate hex1 minus hex2, and compared the result with vector, expected result 1: * (1) Pointer addresses for parameters are different from each other. * (2) The address of the output parameter pointer r is the same as that of the input parameter pointer a. * (3) The address of the output parameter pointer r is the same as that of the input parameter pointer b. * 3. Test the scenario where the output parameter space is insufficient, expected result 1. * @expect * 1. The calculation result is consistent with the vector. */ /* BEGIN_CASE */ void SDV_CRYPTO_BN_SUB_FUNC_TC001(int sign1, Hex *hex1, int sign2, Hex *hex2, int signRes, Hex *result) { TestMemInit(); BN_BigNum *r = NULL; BN_BigNum *n = NULL; uint32_t maxBits; BN_BigNum *res = TEST_VectorToBN(signRes, result->x, result->len); BN_BigNum *a = TEST_VectorToBN(sign1, hex1->x, hex1->len); BN_BigNum *b = TEST_VectorToBN(sign2, hex2->x, hex2->len); ASSERT_TRUE(res != NULL && a != NULL && b != NULL); maxBits = TEST_GetMax(BN_Bits(a), BN_Bits(b), 0); r = BN_Create(maxBits + BIGNUM_REDUNDANCY_BITS); ASSERT_TRUE(r != NULL); ASSERT_EQ(BN_Copy(r, a), CRYPT_SUCCESS); ASSERT_EQ(BN_Sub(r, a, b), CRYPT_SUCCESS); ASSERT_TRUE_AND_LOG("r != a", BN_Cmp(r, res) == 0); ASSERT_EQ(BN_Copy(r, a), CRYPT_SUCCESS); ASSERT_EQ(BN_Sub(r, r, b), CRYPT_SUCCESS); ASSERT_TRUE_AND_LOG("r == a", BN_Cmp(r, res) == 0); ASSERT_EQ(BN_Copy(r, b), CRYPT_SUCCESS); ASSERT_EQ(BN_Sub(r, a, r), CRYPT_SUCCESS); ASSERT_TRUE_AND_LOG("r == b", BN_Cmp(r, res) == 0); /* Test the scenario where the output parameter space is insufficient. */ n = BN_Create(0); ASSERT_TRUE(n != NULL); ASSERT_EQ(BN_Sub(n, a, b), CRYPT_SUCCESS); ASSERT_TRUE_AND_LOG("n != a", BN_Cmp(n, res) == 0); ASSERT_EQ(BN_Sub(a, a, b), CRYPT_SUCCESS); ASSERT_TRUE_AND_LOG("a == a", BN_Cmp(a, res) == 0); EXIT: BN_Destroy(a); BN_Destroy(b); BN_Destroy(r); BN_Destroy(n); BN_Destroy(res); } /* END_CASE */ /** * @test SDV_CRYPTO_BN_SUBLIMB_API_TC001 * @title BN_SubLimb method test. * @precon nan * @brief * 1. Create BN_BigNum r and a. * 2. Call the BN_SubLimb method, parameters are null, expected result 1 * 3. Call the BN_AddLimb method to subtract a from 2, expected result 2 * 4. Call the BN_AddLimb method to subtract a from 1, expected result 3 * 5. Call the BN_AddLimb method to subtract a from 0, expected result 4 * @expect * 1. CRYPT_NULL_INPUT * 2. CRYPT_SUCCESS */ /* BEGIN_CASE */ void SDV_CRYPTO_BN_SUBLIMB_API_TC001(void) { BN_BigNum *r = NULL; BN_BigNum *a = NULL; TestMemInit(); r = BN_Create(LONG_BN_BITS_256); a = BN_Create(LONG_BN_BITS_256); ASSERT_TRUE(r != NULL && a != NULL); ASSERT_TRUE(BN_SubLimb(NULL, NULL, 0) == CRYPT_NULL_INPUT); ASSERT_TRUE(BN_SubLimb(r, a, 2) == CRYPT_SUCCESS); // r == LONG_BN_BITS_256 - 2 ASSERT_TRUE(BN_SetBit(a, 1) == CRYPT_SUCCESS); // a->size == 1 ASSERT_TRUE(BN_SetSign(a, true) == CRYPT_SUCCESS); ASSERT_TRUE(BN_SubLimb(r, a, 1) == CRYPT_SUCCESS); // r == LONG_BN_BITS_256 - 1 ASSERT_TRUE(BN_SetBit(a, SHORT_BN_BITS_128 - 1) == CRYPT_SUCCESS); ASSERT_TRUE(BN_SubLimb(r, a, 0) == CRYPT_SUCCESS); ASSERT_TRUE(BN_SetBit(a, 0) == CRYPT_SUCCESS); ASSERT_TRUE(BN_SubLimb(r, a, 0) == CRYPT_SUCCESS); BN_Destroy(a); a = NULL; a = BN_Create(0); ASSERT_TRUE(a != NULL); ASSERT_TRUE(BN_SubLimb(r, a, 10) == CRYPT_SUCCESS); EXIT: BN_Destroy(r); BN_Destroy(a); } /* END_CASE */ /** * @test SDV_CRYPTO_BN_SUB_LIMB_FUNC_TC001 * @title BN_SubLimb test. * @precon Vectors: hex1 - hex2 = result * @brief * 1. Convert vectors to big numbers. * 2. Call BN_SubLimb to calculate hex1 minus hex2, and compared the result with vector, expected result 1. * 3. Test the scenario where the output parameter space is insufficient, expected result 1. * @expect * 1. The calculation result is consistent with the vector. */ /* BEGIN_CASE */ void SDV_CRYPTO_BN_SUB_LIMB_FUNC_TC001(int sign1, Hex *hex1, Hex *hex2, int signRes, Hex *result) { TestMemInit(); BN_BigNum *r = NULL; BN_BigNum *n = NULL; BN_UINT w = 0; BN_BigNum *res = TEST_VectorToBN(signRes, result->x, result->len); BN_BigNum *a = TEST_VectorToBN(sign1, hex1->x, hex1->len); ASSERT_TRUE(res != NULL && a != NULL); // w ASSERT_TRUE(sizeof(BN_UINT) >= hex2->len); for (uint32_t i = 0; i < hex2->len; i++) { w <<= BITS_OF_BYTE; w += hex2->x[i]; } // r r = BN_Create(BN_Bits(a) + BIGNUM_REDUNDANCY_BITS); ASSERT_TRUE(r != NULL); ASSERT_EQ(BN_Copy(r, a), CRYPT_SUCCESS); ASSERT_EQ(BN_SubLimb(r, a, w), CRYPT_SUCCESS); ASSERT_TRUE(BN_Cmp(r, res) == 0); /* Test the scenario where the output parameter space is insufficient. */ n = BN_Create(0); ASSERT_TRUE(n != NULL); ASSERT_EQ(BN_Zeroize(a), CRYPT_SUCCESS); ASSERT_TRUE(BN_SubLimb(n, a, w) == CRYPT_SUCCESS); ASSERT_TRUE(BN_SetLimb(res, w) == CRYPT_SUCCESS); if (w != 0) { res->sign = true; } ASSERT_TRUE(BN_Cmp(n, res) == 0); EXIT: BN_Destroy(a); BN_Destroy(r); BN_Destroy(n); BN_Destroy(res); } /* END_CASE */ /** * @test SDV_CRYPTO_BN_DIV_FUNC_TC001 * @title BN_Div test. * @precon Vectors: hex1 / hex2 = resultQ, hex1 % hex2 = resultR * @brief * 1. Convert vectors to big numbers. * 2. Call BN_Div method, and compared the result with vector, expected result 1: * (1) Pointer addresses for parameters are different from each other. * (2) q == x, r == y. * 3. Test the scenario where the output parameter space is insufficient, expected result 1. * @expect * 1. The calculation result is consistent with the vector. */ /* BEGIN_CASE */ void SDV_CRYPTO_BN_DIV_FUNC_TC001( int sign1, Hex *hex1, int sign2, Hex *hex2, int signQ, Hex *resultQ, int signR, Hex *resultR) { TestMemInit(); BN_BigNum *q = NULL; BN_BigNum *r = NULL; BN_BigNum *q1 = NULL; BN_BigNum *n = NULL; BN_Optimizer *opt = NULL; uint32_t maxBits; BN_BigNum *resQ = TEST_VectorToBN(signQ, resultQ->x, resultQ->len); BN_BigNum *resR = TEST_VectorToBN(signR, resultR->x, resultR->len); BN_BigNum *x = TEST_VectorToBN(sign1, hex1->x, hex1->len); BN_BigNum *y = TEST_VectorToBN(sign2, hex2->x, hex2->len); ASSERT_TRUE(resQ != NULL && resR != NULL && x != NULL && y != NULL); maxBits = TEST_GetMax(BN_Bits(x), BN_Bits(y), 0); // q q = BN_Create(maxBits + BIGNUM_REDUNDANCY_BITS); r = BN_Create(maxBits + BIGNUM_REDUNDANCY_BITS); ASSERT_TRUE(q != NULL && r != NULL); opt = BN_OptimizerCreate(); ASSERT_TRUE(opt != NULL); ASSERT_EQ(BN_Copy(q, x), CRYPT_SUCCESS); ASSERT_EQ(BN_Copy(r, y), CRYPT_SUCCESS); ASSERT_EQ(BN_Div(q, r, x, y, opt), CRYPT_SUCCESS); ASSERT_TRUE_AND_LOG("q != x, r != y", BN_Cmp(q, resQ) == 0); ASSERT_TRUE_AND_LOG("q != x, r != y", BN_Cmp(r, resR) == 0); ASSERT_EQ(BN_Copy(q, x), CRYPT_SUCCESS); ASSERT_EQ(BN_Copy(r, y), CRYPT_SUCCESS); ASSERT_EQ(BN_Div(q, r, q, r, opt), CRYPT_SUCCESS); ASSERT_TRUE_AND_LOG("q == x, r == y", BN_Cmp(q, resQ) == 0); ASSERT_TRUE_AND_LOG("q == x, r == y", BN_Cmp(r, resR) == 0); /* Test the scenario where the output parameter space is insufficient. */ n = BN_Create(0); q1 = BN_Create(0); ASSERT_TRUE(n != NULL); ASSERT_TRUE(q1 != NULL); ASSERT_EQ(BN_Div(q1, n, x, y, opt), CRYPT_SUCCESS); ASSERT_TRUE_AND_LOG("q1 != x, n != y", BN_Cmp(q1, resQ) == 0); ASSERT_TRUE_AND_LOG("q1 != x, n != y", BN_Cmp(n, resR) == 0); EXIT: BN_Destroy(x); BN_Destroy(y); BN_Destroy(q); BN_Destroy(r); BN_Destroy(n); BN_Destroy(q1); BN_Destroy(resQ); BN_Destroy(resR); BN_OptimizerDestroy(opt); } /* END_CASE */ /** * @test SDV_CRYPTO_BN_SQR_API_TC001 * @title BN_Sqr method test. * @precon nan * @brief * 1. Call the BN_Sqr method, parameters are null, expected result 1 * 2. Call the BN_Sqr method, parameters are valid, expected result 2 * @expect * 1. CRYPT_NULL_INPUT * 2. CRYPT_SUCCESS */ /* BEGIN_CASE */ void SDV_CRYPTO_BN_SQR_API_TC001(void) { uint8_t buff[LONG_BN_BYTES_32]; BN_BigNum *a = NULL; BN_BigNum *r = NULL; BN_BigNum *zero = NULL; BN_Optimizer *opt = NULL; TestMemInit(); a = BN_Create(SHORT_BN_BITS_128); r = BN_Create(SHORT_BN_BITS_128); ASSERT_TRUE(a != NULL && r != NULL); opt = BN_OptimizerCreate(); ASSERT_TRUE(opt != NULL); ASSERT_TRUE(BN_Sqr(NULL, NULL, NULL) == CRYPT_NULL_INPUT); ASSERT_TRUE(BN_Sqr(r, a, opt) == CRYPT_SUCCESS); memset_s(buff, sizeof(buff), 0xFF, LONG_BN_BYTES_32); ASSERT_TRUE(BN_Bin2Bn(a, buff, sizeof(buff)) == CRYPT_SUCCESS); ASSERT_TRUE(BN_Sqr(r, a, opt) == CRYPT_SUCCESS); ASSERT_TRUE(BN_Bin2Bn(a, buff, sizeof(buff) / 2) == CRYPT_SUCCESS); ASSERT_TRUE(BN_Sqr(r, a, opt) == CRYPT_SUCCESS); EXIT: BN_Destroy(a); BN_Destroy(r); BN_Destroy(zero); BN_OptimizerDestroy(opt); } /* END_CASE */ /** * @test SDV_CRYPTO_BN_SQR_FUNC_TC001 * @title BN_Sqr method test. * @precon nan * @brief * 1. Call the BN_Copy method, Compute (-1)*(-1) or 1*1, expected result 1 * 2. Compare r and result, expected result 2 * @expect * 1. CRYPT_SUCCESS * 2. r = result */ /* BEGIN_CASE */ void SDV_CRYPTO_BN_SQR_FUNC_TC001(int sign1, Hex *hex1, Hex *result) { TestMemInit(); BN_BigNum *a; BN_BigNum *res = NULL; BN_BigNum *r = NULL; BN_Optimizer *opt = NULL; a = BN_Create(hex1->len * BITS_OF_BYTE); res = BN_Create(result->len * BITS_OF_BYTE); ASSERT_TRUE(a != NULL && res != NULL); ASSERT_TRUE(BN_Bin2Bn(res, result->x, result->len) == CRYPT_SUCCESS); ASSERT_TRUE(BN_Bin2Bn(a, hex1->x, hex1->len) == CRYPT_SUCCESS); ASSERT_TRUE(BN_SetSign(a, sign1 != 0) == CRYPT_SUCCESS); // r.bits > a.bits * 2 r = BN_Create(BN_Bits(a) * 2 + BIGNUM_REDUNDANCY_BITS); ASSERT_TRUE(r != NULL); opt = BN_OptimizerCreate(); ASSERT_TRUE(opt != NULL); ASSERT_TRUE(BN_Copy(r, a) == CRYPT_SUCCESS); ASSERT_TRUE(BN_Sqr(r, a, opt) == CRYPT_SUCCESS); ASSERT_TRUE(BN_Cmp(r, res) == 0); EXIT: BN_Destroy(a); BN_Destroy(r); BN_Destroy(res); BN_OptimizerDestroy(opt); } /* END_CASE */ /** * @test SDV_CRYPTO_BN_RAND_API_TC001 * @title BN_Rand: Invalid parameter. * @precon nan * @brief * 1. Call the BN_Rand, parameters are null and 0, expected result 1 * 2. Call the BN_Rand, top is out of maximum value(BN_RAND_TOP_TWOBIT + 1), expected result 2 * 3. Call the BN_Rand, bottom is out of maximum value(BN_RAND_BOTTOM_TWOBIT + 1), expected result 3 * 4. Call the BN_Rand, bit is 0, top and bottom are not 0, expected result 4 * 5. Call the BN_Rand, bit > BN_MAX_BITS, expected result 5 * 6. Call the BN_Rand, bit, top and bottom is 0, expected result 6 * @expect * 1. CRYPT_NULL_INPUT * 2-3. CRYPT_BN_ERR_RAND_TOP_BOTTOM * 4. CRYPT_BN_ERR_RAND_BITS_NOT_ENOUGH * 5. CRYPT_BN_BITS_TOO_MAX * 6. CRYPT_SUCCESS */ /* BEGIN_CASE */ void SDV_CRYPTO_BN_RAND_API_TC001(void) { #ifndef HITLS_CRYPTO_DRBG SKIP_TEST(); #else BN_BigNum *bn = NULL; TestMemInit(); bn = BN_Create(BITS_OF_BYTE); ASSERT_TRUE(BN_Rand(NULL, 0, 0, 0) == CRYPT_NULL_INPUT); ASSERT_TRUE( BN_Rand(bn, BITS_OF_BYTE, BN_RAND_TOP_TWOBIT + 1, BN_RAND_BOTTOM_TWOBIT) == CRYPT_BN_ERR_RAND_TOP_BOTTOM); ASSERT_TRUE( BN_Rand(bn, BITS_OF_BYTE, BN_RAND_TOP_TWOBIT, BN_RAND_BOTTOM_TWOBIT + 1) == CRYPT_BN_ERR_RAND_TOP_BOTTOM); ASSERT_TRUE(BN_Rand(bn, 0, BN_RAND_TOP_TWOBIT, BN_RAND_BOTTOM_TWOBIT) == CRYPT_BN_ERR_RAND_BITS_NOT_ENOUGH); ASSERT_TRUE(BN_Rand(bn, BN_MAX_BITS + 1, BN_RAND_TOP_TWOBIT, BN_RAND_BOTTOM_TWOBIT) == CRYPT_BN_BITS_TOO_MAX); ASSERT_EQ(TestRandInit(), CRYPT_SUCCESS); ASSERT_TRUE(BN_Rand(bn, 0, 0, 0) == CRYPT_SUCCESS); EXIT: BN_Destroy(bn); return; #endif } /* END_CASE */ /** * @test SDV_CRYPTO_BN_RANDRANGE_API_TC001 * @title BN_RandRange: Invalid parameter. * @precon nan * @brief * 1. Call the BN_RandRange method, parameters are null, expected result 1 * 2. Call the BN_RandRange method, parameters are 0, expected result 2 * 3. Call the BN_RandRange method, parameters are -1, expected result 3 * @expect * 1. CRYPT_NULL_INPUT * 2. CRYPT_BN_ERR_RAND_ZERO * 3. CRYPT_BN_ERR_RAND_NEGATIVE */ /* BEGIN_CASE */ void SDV_CRYPTO_BN_RANDRANGE_API_TC001(void) { BN_BigNum *bn = NULL; TestMemInit(); bn = BN_Create(BITS_OF_BYTE); ASSERT_TRUE(BN_RandRange(NULL, NULL) == CRYPT_NULL_INPUT); ASSERT_TRUE(BN_RandRange(bn, bn) == CRYPT_BN_ERR_RAND_ZERO); ASSERT_TRUE(BN_SetLimb(bn, 1) == CRYPT_SUCCESS); ASSERT_TRUE(BN_SetSign(bn, true) == CRYPT_SUCCESS); ASSERT_TRUE(BN_RandRange(bn, bn) == CRYPT_BN_ERR_RAND_NEGATIVE); EXIT: BN_Destroy(bn); return; } /* END_CASE */ /** * @test SDV_CRYPTO_BN_BNGCDCHECKINPUT_API_TC001 * @title BnGcdCheckInput: Invalid parameter. * @precon nan * @brief * 1. Call the BnGcdCheckInput method, parameters are null, expected result 1 * 2. Call the BnGcdCheckInput method, a and b are BN_MAX_BITS, expected result 2 * 3. Call the BnGcdCheckInput method, a and b are 0, expected result 3 * @expect * 1. CRYPT_NULL_INPUT * 2. CRYPT_SUCCESS * 3. CRYPT_BN_ERR_GCD_NO_ZERO */ /* BEGIN_CASE */ void SDV_CRYPTO_BN_BNGCDCHECKINPUT_API_TC001(void) { BN_BigNum *r; BN_BigNum *a; BN_BigNum *b; BN_Optimizer *opt = NULL; TestMemInit(); r = BN_Create(BITS_OF_BYTE); a = BN_Create(LONG_BN_BITS_256); b = BN_Create(LONG_BN_BITS_256); opt = BN_OptimizerCreate(); ASSERT_TRUE(BnGcdCheckInput(NULL, NULL, NULL, NULL) == CRYPT_NULL_INPUT); ASSERT_TRUE(BN_SetLimb(a, BN_MAX_BITS) == CRYPT_SUCCESS); ASSERT_TRUE(BN_SetLimb(b, BN_MAX_BITS) == CRYPT_SUCCESS); ASSERT_TRUE(BnGcdCheckInput(r, a, b, opt) == CRYPT_SUCCESS); ASSERT_TRUE(BN_Zeroize(a) == CRYPT_SUCCESS); ASSERT_TRUE(BN_Zeroize(b) == CRYPT_SUCCESS); ASSERT_TRUE(BnGcdCheckInput(r, a, b, opt) == CRYPT_BN_ERR_GCD_NO_ZERO); EXIT: BN_Destroy(r); BN_Destroy(a); BN_Destroy(b); BN_OptimizerDestroy(opt); return; } /* END_CASE */ /** * @test SDV_CRYPTO_BN_MODINVINPUTCHECK_API_TC001 * @title InverseInputCheck: Invalid parameter. * @precon nan * @brief * 1. Call the InverseInputCheck method, parameters are null, expected result 1 * 2. Call the InverseInputCheck method, x and m are BN_MAX_BITS, expected result 2 * 3. Call the InverseInputCheck method, x and m are 0, expected result 3 * @expect * 1. CRYPT_NULL_INPUT * 2. CRYPT_SUCCESS * 3. CRYPT_BN_ERR_DIVISOR_ZERO */ /* BEGIN_CASE */ void SDV_CRYPTO_BN_MODINVINPUTCHECK_API_TC001(void) { BN_BigNum *r; BN_BigNum *x; BN_BigNum *m; BN_Optimizer *opt = NULL; TestMemInit(); r = BN_Create(BITS_OF_BYTE); x = BN_Create(LONG_BN_BITS_256); m = BN_Create(LONG_BN_BITS_256); opt = BN_OptimizerCreate(); ASSERT_TRUE(r != NULL && x != NULL && m != NULL && opt != NULL); ASSERT_TRUE(InverseInputCheck(NULL, NULL, NULL, NULL) == CRYPT_NULL_INPUT); ASSERT_TRUE(BN_SetLimb(x, BN_MAX_BITS) == CRYPT_SUCCESS); ASSERT_TRUE(BN_SetLimb(m, BN_MAX_BITS) == CRYPT_SUCCESS); ASSERT_TRUE(InverseInputCheck(r, x, m, opt) == CRYPT_SUCCESS); ASSERT_TRUE(BN_Zeroize(x) == CRYPT_SUCCESS); ASSERT_TRUE(BN_Zeroize(m) == CRYPT_SUCCESS); ASSERT_TRUE(InverseInputCheck(r, x, m, opt) == CRYPT_BN_ERR_DIVISOR_ZERO); EXIT: BN_Destroy(r); BN_Destroy(x); BN_Destroy(m); BN_OptimizerDestroy(opt); return; } /* END_CASE */ /** * @test SDV_CRYPTO_BN_U64_FUNC_TC001 * @title BN_U64Array2Bn/BN_Bn2U64Array test. * @precon nan * @brief * 1. Randomly generate a 64-bit unsigned array. * 2. Convert the array to a big number, and then convert the big number to array, expected result 1. * 3. compare whether the arrays are the same, expected result 2 * @expect * 1. CRYPT_SUCCESS * 2. The two arrays are the same. */ /* BEGIN_CASE */ void SDV_CRYPTO_BN_U64_FUNC_TC001(int len) { TestMemInit(); BN_BigNum *a = BN_Create(0); uint64_t *input = calloc(1, len * sizeof(uint64_t)); uint64_t *output = calloc(1, len * sizeof(uint64_t)); uint32_t outlen = len; for (int i = 0; i < len; i++) { input[i] = rand(); } input[len - 1] = 1; ASSERT_TRUE(BN_U64Array2Bn(a, input, (uint32_t)len) == CRYPT_SUCCESS); ASSERT_TRUE(BN_Bn2U64Array(a, output, &outlen) == CRYPT_SUCCESS); ASSERT_TRUE(memcmp(input, output, outlen * sizeof(uint64_t)) == 0); input[len - 1] = 0; ASSERT_TRUE(BN_U64Array2Bn(a, input, len) == CRYPT_SUCCESS); ASSERT_TRUE(BN_Bn2U64Array(a, output, &outlen) == CRYPT_SUCCESS); ASSERT_TRUE(memcmp(input, output, outlen * sizeof(uint64_t)) == 0); EXIT: BN_Destroy(a); free(input); free(output); } /* END_CASE */ /** * @test SDV_CRYPTO_BN_UINT_FUNC_TC001 * @title BN_Array2BN/BN_BN2Array test. * @precon nan * @brief * 1. Randomly generate a BN_UINT unsigned array. * 2. Convert the array to a big number, and then convert the big number to array, expected result 1. * 3. compare whether the arrays are the same, expected result 2 * @expect * 1. CRYPT_SUCCESS * 2. The two arrays are the same. */ /* BEGIN_CASE */ void SDV_CRYPTO_BN_UINT_FUNC_TC001(int len) { #if defined(HITLS_CRYPTO_CURVE_SM2_ASM) || (defined(HITLS_CRYPTO_CURVE_NISTP256_ASM) && \ defined(HITLS_CRYPTO_NIST_USE_ACCEL)) TestMemInit(); BN_BigNum *a = BN_Create(0); BN_UINT *input = calloc(1, len * sizeof(BN_UINT)); BN_UINT *output = calloc(1, len * sizeof(BN_UINT)); for (int i = 0; i < len; i++) { input[i] = rand(); } ASSERT_TRUE(BN_Array2BN(a, input, len) == CRYPT_SUCCESS); ASSERT_TRUE(BN_BN2Array(a, output, len) == CRYPT_SUCCESS); ASSERT_TRUE(memcmp(input, output, len * sizeof(BN_UINT)) == 0); EXIT: BN_Destroy(a); free(input); free(output); #else (void)len; #endif } /* END_CASE */ /** * @test SDV_CRYPTO_BN_GCD_FUNC_TC001 * @title BN_Gcd test. * @precon Vectors: two big numbers, result. * @brief * 1. Convert vectors to big numbers. * 2. Call BN_Gcd to calculate the modular exponentiation, and compared to the vector value, expected result 1: * (1) Pointer addresses for parameters are different from each other. * (2) The address of the output parameter pointer r is the same as that of the input parameter pointer a. * (3) The address of the output parameter pointer r is the same as that of the input parameter pointer b. * 3. Test the scenario where the output parameter space is insufficient, expected result 1. * @expect * 1. The calculation result is consistent with the vector. */ /* BEGIN_CASE */ void SDV_CRYPTO_BN_GCD_FUNC_TC001(int sign1, Hex *hex1, int sign2, Hex *hex2, Hex *result) { TestMemInit(); BN_BigNum *out = NULL; BN_Optimizer *opt = NULL; uint32_t maxBits; BN_BigNum *bn = TEST_VectorToBN(sign1, hex1->x, hex1->len); BN_BigNum *bn2 = TEST_VectorToBN(sign2, hex2->x, hex2->len); BN_BigNum *res = TEST_VectorToBN(0, result->x, result->len); ASSERT_TRUE(bn != NULL && bn2 != NULL && res != NULL); maxBits = TEST_GetMax(BN_Bits(bn), BN_Bits(bn2), 0); out = BN_Create(maxBits + BIGNUM_REDUNDANCY_BITS); ASSERT_TRUE(out != NULL); opt = BN_OptimizerCreate(); ASSERT_TRUE(opt != NULL); ASSERT_EQ(BN_Copy(out, bn), CRYPT_SUCCESS); ASSERT_EQ(BN_Gcd(out, bn, bn2, opt), CRYPT_SUCCESS); ASSERT_TRUE_AND_LOG("r != a", BN_Cmp(out, res) == 0); ASSERT_EQ(BN_Copy(out, bn), CRYPT_SUCCESS); ASSERT_EQ(BN_Gcd(out, out, bn2, opt), CRYPT_SUCCESS); ASSERT_TRUE_AND_LOG("r == a", BN_Cmp(out, res) == 0); ASSERT_EQ(BN_Copy(out, bn2), CRYPT_SUCCESS); ASSERT_EQ(BN_Gcd(out, bn, out, opt), CRYPT_SUCCESS); ASSERT_TRUE_AND_LOG("r == b", BN_Cmp(out, res) == 0); BN_Destroy(out); /* Test the scenario where the output parameter space is insufficient. */ out = BN_Create(0); ASSERT_TRUE(out != NULL); ASSERT_EQ(BN_Gcd(out, bn, bn2, opt), CRYPT_SUCCESS); ASSERT_TRUE_AND_LOG("r != a", BN_Cmp(out, res) == 0); BN_Destroy(out); out = BN_Create(0); ASSERT_TRUE(out != NULL); ASSERT_EQ(BN_Copy(out, bn), CRYPT_SUCCESS); ASSERT_EQ(BN_Gcd(out, out, bn2, opt), CRYPT_SUCCESS); ASSERT_TRUE_AND_LOG("r == a", BN_Cmp(out, res) == 0); BN_Destroy(out); out = BN_Create(0); ASSERT_TRUE(out != NULL); ASSERT_EQ(BN_Copy(out, bn2), CRYPT_SUCCESS); ASSERT_EQ(BN_Gcd(out, bn, out, opt), CRYPT_SUCCESS); ASSERT_TRUE_AND_LOG("r == b", BN_Cmp(out, res) == 0); EXIT: BN_Destroy(bn); BN_Destroy(bn2); BN_Destroy(res); BN_Destroy(out); BN_OptimizerDestroy(opt); } /* END_CASE */ /** * @test SDV_CRYPTO_BN_CMP_FUNC_TC001 * @title BN_Cmp test. * @precon Vectors: two big numbers, result. * @brief * 1. Convert vectors to big numbers. * 2. Call the BN_Cmp method to compare two large numbers, expected result 1. * @expect * 1. The comparison results are the same as 'result'. */ /* BEGIN_CASE */ void SDV_CRYPTO_BN_CMP_FUNC_TC001(int sign1, Hex *hex1, int sign2, Hex *hex2, int result) { TestMemInit(); BN_BigNum *bn1 = TEST_VectorToBN(sign1, hex1->x, hex1->len); BN_BigNum *bn2 = TEST_VectorToBN(sign2, hex2->x, hex2->len); /* bn1 and bn2 can be null. */ ASSERT_EQ(BN_Cmp(bn1, bn2), result); EXIT: BN_Destroy(bn1); BN_Destroy(bn2); } /* END_CASE */ /** * @test SDV_CRYPTO_BN_ADD_FUNC_TC001 * @title BN_Add test. * @precon a + b = r * @brief * 1. Convert vectors to big numbers. * 2. Call the BN_Add method to calculate the sum of two large numbers, expected result 1. * 3. If expectRet=CRYPT_SUCCESS and r=null(i.e.a=-b), call BN_IsZero to check whether sum is 0, expected result 2. * 4. If expectRet=CRYPT_SUCCESS, call the BN_Cmp to compare r and resBn, expected result 3. * @expect * 1. The return value is the same as 'expectRet'. * 2. The calculated sum is 0. * 3. Both are the same. */ /* BEGIN_CASE */ void SDV_CRYPTO_BN_ADD_FUNC_TC001(int sign1, int sign2, int sign3, Hex *a, Hex *b, Hex *r, int expectRet) { TestMemInit(); BN_BigNum *resBn = NULL; BN_BigNum *bn1 = TEST_VectorToBN(sign1, a->x, a->len); BN_BigNum *bn2 = TEST_VectorToBN(sign2, b->x, b->len); BN_BigNum *sum = TEST_VectorToBN(sign3, r->x, r->len); /* bn1, bn2 and sum can be null. */ resBn = BN_Create(SHORT_BN_BITS_128); ASSERT_TRUE(resBn != NULL); ASSERT_EQ(BN_Add(resBn, bn1, bn2), expectRet); if (expectRet == CRYPT_SUCCESS) { if (r->len == 0) { ASSERT_EQ(BN_IsZero(resBn), 1); } else { ASSERT_EQ(BN_Cmp(resBn, sum), 0); } } EXIT: BN_Destroy(bn1); BN_Destroy(bn2); BN_Destroy(sum); BN_Destroy(resBn); } /* END_CASE */ /** * @test SDV_CRYPTO_BN_TO_BIN_FIX_ZERO_API_TC001 * @title BN_Bn2BinFixZero test. * @precon nan * @brief * 1. Call the BN_Create method to create bn, parameter is 0, expected result 1. * 2. Call the BN_Bn2BinFixZero method, expected result 2: * (1) bn is null * (2) bin is null * (3) binLen is 0 * 3. Call the BN_Bn2BinFixZero method, all parameters are valid, expected result 3 * 4. Destroy bn and recreate bn, bits is 128, expected result 4. * 5. Set the highest bit of bn to 1, expected result 5. * 6. Call the BN_Bn2BinFixZero method, binLen is 1, expected result 6. * @expect * 1. Success. * 2. CRYPT_NULL_INPUT. * 3. CRYPT_SUCCESS. * 4. Success. * 5. CRYPT_SUCCESS. * 6. CRYPT_BN_BUFF_LEN_NOT_ENOUGH. */ /* BEGIN_CASE */ void SDV_CRYPTO_BN_TO_BIN_FIX_ZERO_API_TC001(void) { TestMemInit(); uint8_t bin[1] = {0}; BN_BigNum *bn = BN_Create(0); ASSERT_TRUE(bn != NULL); ASSERT_EQ(BN_Bn2BinFixZero(NULL, bin, 1), CRYPT_NULL_INPUT); ASSERT_EQ(BN_Bn2BinFixZero(bn, NULL, 1), CRYPT_NULL_INPUT); ASSERT_EQ(BN_Bn2BinFixZero(bn, bin, 0), CRYPT_NULL_INPUT); // bn bytes is 0 ASSERT_EQ(BN_Bn2BinFixZero(bn, bin, 1), CRYPT_SUCCESS); BN_Destroy(bn); bn = BN_Create(SHORT_BN_BITS_128); ASSERT_TRUE(bn != NULL); ASSERT_EQ(BN_SetBit(bn, SHORT_BN_BITS_128 - 1), CRYPT_SUCCESS); ASSERT_EQ(BN_Bn2BinFixZero(bn, bin, 1), CRYPT_BN_BUFF_LEN_NOT_ENOUGH); EXIT: BN_Destroy(bn); } /* END_CASE */ /* BEGIN_CASE */ void SDV_CRYPTO_BN_Rand_API_TC001(void) { TEST_BnTestCaseInit(); BN_BigNum bn[2] = {{0}}; BN_UINT bn_data[DH_BN_DIGITS_MAX * 2] = { 0 }; BN_Init(bn, bn_data, DH_BN_DIGITS_MAX, 2); ASSERT_TRUE(BN_Rand(&bn[0], 8192, 1, 1) == CRYPT_SUCCESS); ASSERT_TRUE(BN_RandRange(&bn[1], &bn[0]) == CRYPT_SUCCESS); EXIT: return; } /* END_CASE */ /* BEGIN_CASE */ void SDV_CRYPTO_BN_Add_API_TC001(void) { TEST_BnTestCaseInit(); BN_BigNum bn[3] = {{0}}; BN_UINT bn_data[BN_DIGITS_MAX * 3] = { 0 }; BN_Init(bn, bn_data, BN_DIGITS_MAX, 3); ASSERT_TRUE(BN_Rand(&bn[0], 4096, 1, 1) == CRYPT_SUCCESS); ASSERT_TRUE(BN_Rand(&bn[1], 4096, 1, 1) == CRYPT_SUCCESS); ASSERT_TRUE(BN_Add(&bn[2], &bn[0], &bn[1]) == CRYPT_SUCCESS); EXIT: return; } /* END_CASE */ /* BEGIN_CASE */ void SDV_CRYPTO_BN_Mul_API_TC001(void) { TEST_BnTestCaseInit(); BN_Optimizer *opt = BN_OptimizerCreate(); BN_BigNum bn[2] = {{0}}; BN_BigNum rn = {0}; BN_UINT bn_data[BN_DIGITS_MAX * 2] = { 0 }; BN_UINT r_data[DH_BN_DIGITS_MAX * 2] = { 0 }; BN_Init(bn, bn_data, BN_DIGITS_MAX, 2); ASSERT_TRUE(BN_Rand(&bn[0], 4096, 1, 1) == CRYPT_SUCCESS); ASSERT_TRUE(BN_Rand(&bn[1], 4096, 1, 1) == CRYPT_SUCCESS); BN_Init(&rn, r_data, DH_BN_DIGITS_MAX, 1); ASSERT_TRUE(BN_Mul(&rn, &bn[0], &bn[1], opt) == CRYPT_SUCCESS); EXIT: BN_OptimizerDestroy(opt); return; } /* END_CASE */ /* BEGIN_CASE */ void SDV_CRYPTO_BN_Div_API_TC001(void) { TEST_BnTestCaseInit(); BN_Optimizer *opt = BN_OptimizerCreate(); BN_BigNum bn[4] = {{0}}; BN_UINT bn_data[BN_DIGITS_MAX * 4] = { 0 }; BN_Init(bn, bn_data, BN_DIGITS_MAX, 4); ASSERT_TRUE(BN_Rand(&bn[2], 4096, 1, 1) == CRYPT_SUCCESS); ASSERT_TRUE(BN_Rand(&bn[3], 4096, 1, 1) == CRYPT_SUCCESS); ASSERT_TRUE(BN_Div(&bn[0], &bn[1], &bn[2], &bn[3], opt) == CRYPT_SUCCESS); EXIT: BN_OptimizerDestroy(opt); return; } /* END_CASE */ /* BEGIN_CASE */ void SDV_CRYPTO_BN_Mod_API_TC001(void) { TEST_BnTestCaseInit(); BN_Optimizer *opt = BN_OptimizerCreate(); BN_UINT res = 0; BN_UINT input = 3; BN_BigNum bn[4] = {{0}}; BN_UINT bn_data[BN_DIGITS_MAX * 4] = { 0 }; BN_Init(bn, bn_data, BN_DIGITS_MAX, 4); ASSERT_TRUE(BN_Rand(&bn[1], 4096, 1, 1) == CRYPT_SUCCESS); ASSERT_TRUE(BN_Rand(&bn[2], 4096, 1, 1) == CRYPT_SUCCESS); ASSERT_TRUE(BN_Rand(&bn[3], 4096, 1, 1) == CRYPT_SUCCESS); ASSERT_TRUE(BN_ModMul(&bn[0], &bn[1], &bn[2], &bn[3], opt) == CRYPT_SUCCESS); ASSERT_TRUE(BN_ModSqr(&bn[0], &bn[1], &bn[2], opt) == CRYPT_SUCCESS); ASSERT_TRUE(BN_ModAdd(&bn[0], &bn[1], &bn[2], &bn[3], opt) == CRYPT_SUCCESS); ASSERT_TRUE(BN_ModLimb(&res, &bn[1], input) == CRYPT_SUCCESS); ASSERT_TRUE(BN_AddLimb(&bn[0], &bn[1], input) == CRYPT_SUCCESS); ASSERT_TRUE(BN_SetLimb(&bn[0], input) == CRYPT_SUCCESS); ASSERT_TRUE(BN_Cmp(&bn[1], &bn[2]) != CRYPT_SUCCESS); EXIT: BN_OptimizerDestroy(opt); return; } /* END_CASE */ /* BEGIN_CASE */ void SDV_CRYPTO_BN_ModLimb_API_TC001(void) { TEST_BnTestCaseInit(); BN_Optimizer *opt = BN_OptimizerCreate(); ASSERT_TRUE(opt != NULL); BN_UINT res = 0; BN_UINT input = 3; BN_BigNum bn[2] = {{0}}; BN_UINT bn_data[DH_BN_DIGITS_MAX * 2] = { 0 }; BN_Init(bn, bn_data, DH_BN_DIGITS_MAX, 2); ASSERT_TRUE(BN_ModLimb(&res, &bn[1], input) == CRYPT_SUCCESS); EXIT: BN_OptimizerDestroy(opt); return; } /* END_CASE */ /* BEGIN_CASE */ void SDV_CRYPTO_BN_rshift_API_TC001(void) { TEST_BnTestCaseInit(); BN_UINT input = 3; BN_BigNum bn[2] = {{0}}; BN_UINT bn_data[DH_BN_DIGITS_MAX * 2] = { 0 }; BN_Init(bn, bn_data, DH_BN_DIGITS_MAX, 2); ASSERT_TRUE(BN_Rand(&bn[1], 4096, 1, 1) == CRYPT_SUCCESS); ASSERT_TRUE(BN_Rshift(&bn[0], &bn[1], input) == CRYPT_SUCCESS); EXIT: return; } /* END_CASE */ /* BEGIN_CASE */ void SDV_CRYPTO_BN_ModExp_API_TC001(void) { TEST_BnTestCaseInit(); BN_Optimizer *opt = BN_OptimizerCreate(); ASSERT_TRUE(opt != NULL); BN_BigNum bn[4] = {{0}}; BN_UINT bn_data[DH_BN_DIGITS_MAX * 4] = { 0 }; BN_Init(bn, bn_data, DH_BN_DIGITS_MAX, 4); ASSERT_TRUE(BN_Rand(&bn[1], 8192, 1, 1) == CRYPT_SUCCESS); ASSERT_TRUE(BN_Rand(&bn[2], 8192, 1, 1) == CRYPT_SUCCESS); ASSERT_TRUE(BN_Rand(&bn[3], 8192, 1, 1) == CRYPT_SUCCESS); ASSERT_TRUE(BN_ModExp(&bn[0], &bn[1], &bn[2], &bn[3], opt) == CRYPT_SUCCESS); EXIT: BN_OptimizerDestroy(opt); return; } /* END_CASE */ /* BEGIN_CASE */ void SDV_CRYPTO_BN_SET_FLAG_TC001(void) { TEST_BnTestCaseInit(); BN_BigNum a = {0}; ASSERT_TRUE(BN_SetFlag(&a, 0xFF) == CRYPT_BN_FLAG_INVALID); ASSERT_TRUE(BN_SetFlag(&a, CRYPT_BN_FLAG_STATIC) == CRYPT_SUCCESS); EXIT: return; } /* END_CASE */ /* BEGIN_CASE */ void SDV_CRYPTO_BN_GETLIMB_API_TC001(void) { TEST_BnTestCaseInit(); int32_t ret; BN_BigNum *a = BN_Create(LONG_BN_BITS_256); ASSERT_TRUE(a != NULL); ASSERT_TRUE(BN_GetLimb(NULL) == 0); ret = BN_SetLimb(a, 0); ASSERT_TRUE(ret == CRYPT_SUCCESS); ASSERT_TRUE(BN_GetLimb(a) == 0); ret = BN_SetLimb(a, 1); ASSERT_TRUE(ret == CRYPT_SUCCESS); ASSERT_TRUE(BN_GetLimb(a) == 1); ret = BN_SetLimb(a, 2); ASSERT_TRUE(ret == CRYPT_SUCCESS); ASSERT_TRUE(BN_GetLimb(a) == 2); ret = BN_SetLimb(a, BN_UINT_MAX - 1); ASSERT_TRUE(ret == CRYPT_SUCCESS); ASSERT_TRUE(BN_GetLimb(a) == BN_UINT_MAX - 1); ret = BN_SetLimb(a, BN_UINT_MAX); ASSERT_TRUE(ret == CRYPT_SUCCESS); ASSERT_TRUE(BN_GetLimb(a) == BN_UINT_MAX); ret = BN_Lshift(a, a, BN_UINT_MAX + 1); ASSERT_TRUE(ret == CRYPT_SUCCESS); ASSERT_TRUE(BN_GetLimb(a) == BN_UINT_MAX); EXIT: BN_Destroy(a); } /* END_CASE */ /* BEGIN_CASE */ void SDV_CRYPTO_BN_MASKBIT_API_TC001(void) { TEST_BnTestCaseInit(); ASSERT_TRUE(BN_MaskBit(NULL, 0) == CRYPT_NULL_INPUT); int32_t ret; BN_BigNum *bn = BN_Create(1); ret = BN_SetBit(bn, 1); ASSERT_TRUE(ret == CRYPT_SUCCESS); BN_SetSign(bn, 1); ret = BN_MaskBit(bn, 0); ASSERT_TRUE(ret == CRYPT_SUCCESS); ASSERT_TRUE(bn->sign == 0); ret = BN_SetLimb(bn, BN_UINT_MAX * 2); ASSERT_TRUE(ret == CRYPT_SUCCESS); ret = BN_MaskBit(bn, BN_UINT_BITS * 3); ASSERT_TRUE(ret == CRYPT_BN_SPACE_NOT_ENOUGH); EXIT: BN_Destroy(bn); } /* END_CASE */ /* BEGIN_CASE */ void SDV_CRYPTO_BN_MULLIMB_API_TC001(void) { TEST_BnTestCaseInit(); int32_t ret; uint8_t buff[LONG_BN_BYTES_32]; BN_BigNum *a = BN_Create(LONG_BN_BITS_256); BN_BigNum *b = BN_Create(LONG_BN_BITS_256); BN_BigNum *r1 = BN_Create(LONG_BN_BITS_256); BN_BigNum *r2 = BN_Create(LONG_BN_BITS_256 * 2); // 512 == 2 * 256 BN_BigNum *zero = BN_Create(LONG_BN_BITS_256); BN_Optimizer *opt = BN_OptimizerCreate(); ASSERT_TRUE(a != NULL); ASSERT_TRUE(b != NULL); ASSERT_TRUE(r1 != NULL); ASSERT_TRUE(r2 != NULL); ASSERT_TRUE(zero != NULL); ASSERT_TRUE(opt != NULL); memset_s(buff, sizeof(buff), 0xFF, LONG_BN_BYTES_32); ret = BN_Bin2Bn(a, buff, LONG_BN_BYTES_32); ASSERT_TRUE(ret == CRYPT_SUCCESS); ret = BN_SetLimb(b, BN_UINT_MAX); ASSERT_TRUE(ret == CRYPT_SUCCESS); ret = BN_Zeroize(zero); ASSERT_TRUE(ret == CRYPT_SUCCESS); ASSERT_TRUE(BN_IsZero(zero)); // NULL ASSERT_TRUE(BN_MulLimb(NULL, a, BN_UINT_MAX) == CRYPT_NULL_INPUT); ASSERT_TRUE(BN_MulLimb(r1, NULL, BN_UINT_MAX) == CRYPT_NULL_INPUT); // a == 0 ret = BN_MulLimb(r1, zero, BN_UINT_MAX); ASSERT_TRUE(ret == CRYPT_SUCCESS); ASSERT_TRUE(BN_IsZero(r1)); // w == 0 ret = BN_MulLimb(r1, a, 0); ASSERT_TRUE(ret == CRYPT_SUCCESS); ASSERT_TRUE(BN_IsZero(r1)); // a == 0 ret = BN_MulLimb(r1, a, BN_UINT_MAX); ASSERT_TRUE(ret == CRYPT_SUCCESS); ret = BN_Mul(r2, a, b, opt); ASSERT_TRUE(ret == CRYPT_SUCCESS); ASSERT_TRUE(BN_Cmp(r1, r2) == CRYPT_SUCCESS); EXIT: BN_Destroy(a); BN_Destroy(b); BN_Destroy(r1); BN_Destroy(r2); BN_Destroy(zero); BN_OptimizerDestroy(opt); } /* END_CASE */ /* BEGIN_CASE */ void SDV_CRYPTO_BN_DIVLIMB_API_TC001(void) { TEST_BnTestCaseInit(); int32_t ret; uint8_t buff[LONG_BN_BYTES_32]; BN_BigNum *a = BN_Create(LONG_BN_BITS_256); BN_BigNum *b = BN_Create(LONG_BN_BITS_256); BN_BigNum *r1 = BN_Create(LONG_BN_BITS_256); BN_BigNum *r2 = BN_Create(LONG_BN_BITS_256 * 2); // 512 == 2 * 256 BN_BigNum *res2 = BN_Create(LONG_BN_BITS_256 * 2); // 512 == 2 * 256 BN_BigNum *zero = BN_Create(LONG_BN_BITS_256); BN_Optimizer *opt = BN_OptimizerCreate(); ASSERT_TRUE(a != NULL); ASSERT_TRUE(b != NULL); ASSERT_TRUE(r1 != NULL); ASSERT_TRUE(r2 != NULL); ASSERT_TRUE(zero != NULL); ASSERT_TRUE(opt != NULL); BN_UINT res1; // BN_UINT res2; memset_s(buff, sizeof(buff), 0xFF, LONG_BN_BYTES_32); ret = BN_Bin2Bn(a, buff, LONG_BN_BYTES_32); ASSERT_TRUE(ret == CRYPT_SUCCESS); ret = BN_SetLimb(b, BN_UINT_MAX); ASSERT_TRUE(ret == CRYPT_SUCCESS); ret = BN_Zeroize(zero); ASSERT_TRUE(ret == CRYPT_SUCCESS); ASSERT_TRUE(BN_IsZero(zero)); // NULL ASSERT_TRUE(BN_DivLimb(NULL, &res1, a, BN_UINT_MAX) == CRYPT_SUCCESS); ASSERT_TRUE(BN_DivLimb(r1, NULL, a, BN_UINT_MAX) == CRYPT_SUCCESS); ASSERT_TRUE(BN_DivLimb(NULL, NULL, a, BN_UINT_MAX) == CRYPT_NULL_INPUT); ASSERT_TRUE(BN_DivLimb(r1, &res1, NULL, BN_UINT_MAX) == CRYPT_NULL_INPUT); // a == 0 ret = BN_DivLimb(r1, &res1, zero, BN_UINT_MAX); ASSERT_TRUE(ret == CRYPT_SUCCESS); ASSERT_TRUE(BN_IsZero(r1)); ASSERT_TRUE(res1 == 0); // w == 0 ret = BN_DivLimb(r1, &res1, a, 0); ASSERT_TRUE(ret == CRYPT_BN_ERR_DIVISOR_ZERO); ret = BN_Copy(r1, a); ASSERT_TRUE(ret == CRYPT_SUCCESS); ret = BN_DivLimb(r1, &res1, r1, BN_UINT_MAX); ASSERT_TRUE(ret == CRYPT_SUCCESS); ret = BN_Div(r2, res2, a, b, opt); ASSERT_TRUE(ret == CRYPT_SUCCESS); ASSERT_TRUE(BN_Cmp(r1, r2) == CRYPT_SUCCESS); ASSERT_TRUE(res1 == res2->data[0]); EXIT: BN_Destroy(a); BN_Destroy(b); BN_Destroy(r1); BN_Destroy(r2); BN_Destroy(res2); BN_Destroy(zero); BN_OptimizerDestroy(opt); } /* END_CASE */ /* BEGIN_CASE */ void SDV_CRYPTO_BN_EXTEND_API_TC001(void) { TEST_BnTestCaseInit(); uint32_t word = BITS_TO_BN_UNIT(BN_MAX_BITS) + 1; BN_BigNum *a = BN_Create(LONG_BN_BITS_256); ASSERT_TRUE(a != NULL); ASSERT_TRUE(BN_Extend(a, 0) == CRYPT_SUCCESS); ASSERT_TRUE(BN_SetFlag(a, CRYPT_BN_FLAG_STATIC) == CRYPT_SUCCESS); ASSERT_TRUE(BN_Extend(a, word) == CRYPT_BN_NOT_SUPPORT_EXTENSION); ASSERT_TRUE(BN_SetFlag(a, CRYPT_BN_FLAG_CONSTTIME) == CRYPT_SUCCESS); ASSERT_TRUE(BN_Extend(a, word) == CRYPT_BN_BITS_TOO_MAX); ASSERT_TRUE(BN_Extend(a, word - 1) == CRYPT_SUCCESS); EXIT: BN_Destroy(a); } /* END_CASE */ /* BEGIN_CASE */ void SDV_CRYPTO_BN_FIXSIZE_API_TC001(void) { TEST_BnTestCaseInit(); BN_BigNum *a = BN_Create(LONG_BN_BITS_256); ASSERT_TRUE(a != NULL); a->size = 1; BN_FixSize(a); ASSERT_TRUE(a->size == 0); EXIT: BN_Destroy(a); } /* END_CASE */
2301_79861745/bench_create
testcode/sdv/testcase/crypto/bn/test_suite_sdv_bn.c
C
unknown
72,996
/* * This file is part of the openHiTLS project. * * openHiTLS is licensed under the Mulan PSL v2. * You can use this software according to the terms and conditions of the Mulan PSL v2. * You may obtain a copy of Mulan PSL v2 at: * * http://license.coscl.org.cn/MulanPSL2 * * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, * EITHER EXPRESS 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 "crypt_eal_mac.h" #include "crypt_errno.h" #include "bsl_sal.h" #define CBC_MAC_MAC_LEN 16 #define SM4_KEY_LEN 16 #define SM4_IV_LEN 16 #define SM4_BLOCK_SIZE 16 #define TEST_FAIL (-1) #define TEST_SUCCESS (0) #define DATA_MAX_LEN (65538) /* END_HEADER */ /* @ * @test SDV_CRYPT_EAL_CBC_MAC_API_TC001 * @spec - * @title Impact of the algorithm ID on the CRYPT_EAL_MacNewCtx interface * @precon nan * @brief 1. algorithm is CRYPT_MAC_CBC_MAC_SM4 2. algorithm is CRYPT_MAC_MAX * @prior Level 1 * @auto TRUE @ */ /* BEGIN_CASE */ void SDV_CRYPT_EAL_CBC_MAC_API_TC001(void) { TestMemInit(); CRYPT_EAL_MacCtx *ctx = CRYPT_EAL_MacNewCtx(CRYPT_MAC_CBC_MAC_SM4); ASSERT_TRUE(ctx != NULL); CRYPT_EAL_MacFreeCtx(ctx); EXIT: return; } /* END_CASE */ /* @ * @test SDV_CRYPT_EAL_CMAC_API_TC003 * @spec - * @title Impact of the ctx status on the CRYPT_EAL_MacInit interface * @precon nan * @brief * @prior Level 1 * @auto TRUE @ */ /* BEGIN_CASE */ void SDV_CRYPT_EAL_CBC_MAC_API_TC003(int algId, int padType) { if (IsMacAlgDisabled(algId)) { SKIP_TEST(); } TestMemInit(); const uint32_t keyLen = SM4_KEY_LEN; uint8_t key[keyLen]; uint32_t macLen = CBC_MAC_MAC_LEN; uint8_t mac[macLen]; const uint32_t dataLen = CBC_MAC_MAC_LEN; uint8_t data[dataLen]; CRYPT_EAL_MacCtx *ctx = CRYPT_EAL_MacNewCtx(algId); ASSERT_TRUE(ctx != NULL); ASSERT_TRUE(CRYPT_EAL_MacInit(ctx, key, keyLen) == CRYPT_SUCCESS); ASSERT_TRUE(CRYPT_EAL_MacInit(ctx, key, keyLen) == CRYPT_SUCCESS); ASSERT_TRUE(CRYPT_EAL_MacCtrl(ctx, CRYPT_CTRL_SET_CBC_MAC_PADDING, &padType, sizeof(CRYPT_PaddingType)) == CRYPT_SUCCESS); ASSERT_TRUE(CRYPT_EAL_MacUpdate(ctx, data, dataLen) == CRYPT_SUCCESS); ASSERT_TRUE(CRYPT_EAL_MacInit(ctx, key, keyLen) == CRYPT_SUCCESS); ASSERT_TRUE(CRYPT_EAL_MacFinal(ctx, mac, &macLen) == CRYPT_SUCCESS); ASSERT_TRUE(CRYPT_EAL_MacInit(ctx, key, keyLen) == CRYPT_SUCCESS); CRYPT_EAL_MacDeinit(ctx); ASSERT_TRUE(CRYPT_EAL_MacInit(ctx, key, keyLen) == CRYPT_SUCCESS); ASSERT_TRUE(CRYPT_EAL_MacReinit(ctx) == CRYPT_SUCCESS); ASSERT_TRUE(CRYPT_EAL_MacInit(ctx, key, keyLen) == CRYPT_SUCCESS); EXIT: CRYPT_EAL_MacFreeCtx(ctx); } /* END_CASE */ /* @ * @test SDV_CRYPT_EAL_CBC_MAC_API_TC004 * @spec - * @title Impact of Input Parameters on the CRYPT_EAL_MacUpdate Interface * @precon nan * @brief * @prior Level 1 * @auto TRUE @ */ /* BEGIN_CASE */ void SDV_CRYPT_EAL_CBC_MAC_API_TC004(int algId, int padType) { if (IsMacAlgDisabled(algId)) { SKIP_TEST(); } TestMemInit(); const uint32_t len = SM4_KEY_LEN; uint8_t key[len]; const uint32_t dataLen = SM4_KEY_LEN; uint8_t data[dataLen]; CRYPT_EAL_MacCtx *ctx = CRYPT_EAL_MacNewCtx(algId); ASSERT_TRUE(ctx != NULL); ASSERT_TRUE(CRYPT_EAL_MacInit(ctx, key, len) == CRYPT_SUCCESS); ASSERT_TRUE(CRYPT_EAL_MacCtrl(ctx, CRYPT_CTRL_SET_CBC_MAC_PADDING, &padType, sizeof(CRYPT_PaddingType)) == CRYPT_SUCCESS); ASSERT_TRUE(CRYPT_EAL_MacUpdate(NULL, data, dataLen) == CRYPT_NULL_INPUT); ASSERT_TRUE(CRYPT_EAL_MacUpdate(ctx, NULL, dataLen) == CRYPT_NULL_INPUT); ASSERT_TRUE(CRYPT_EAL_MacUpdate(ctx, data, 0) == CRYPT_SUCCESS); ASSERT_TRUE(CRYPT_EAL_MacUpdate(ctx, NULL, 0) == CRYPT_SUCCESS); ASSERT_TRUE(CRYPT_EAL_MacUpdate(ctx, data, dataLen) == CRYPT_SUCCESS); EXIT: CRYPT_EAL_MacFreeCtx(ctx); } /* END_CASE */ /* @ * @test SDV_CRYPT_EAL_CBC_MAC_API_TC005 * @spec - * @title Impact of the ctx status on the CRYPT_EAL_MacUpdate interface * @precon nan * @brief 15.update成功,返回CRYPT_SUCCESS * @prior Level 1 * @auto TRUE @ */ /* BEGIN_CASE */ void SDV_CRYPT_EAL_CBC_MAC_API_TC005(int algId, int padType) { if (IsMacAlgDisabled(algId)) { SKIP_TEST(); } TestMemInit(); const uint32_t len = SM4_KEY_LEN; uint8_t key[len]; uint32_t macLen = CBC_MAC_MAC_LEN; uint8_t mac[macLen]; const uint32_t dataLen = SM4_KEY_LEN; uint8_t data[dataLen]; CRYPT_EAL_MacCtx *ctx = CRYPT_EAL_MacNewCtx(algId); ASSERT_TRUE(ctx != NULL); ASSERT_TRUE(CRYPT_EAL_MacUpdate(ctx, data, dataLen) == CRYPT_EAL_ERR_STATE); ASSERT_TRUE(CRYPT_EAL_MacInit(ctx, key, len) == CRYPT_SUCCESS); ASSERT_TRUE(CRYPT_EAL_MacCtrl(ctx, CRYPT_CTRL_SET_CBC_MAC_PADDING, &padType, sizeof(CRYPT_PaddingType)) == CRYPT_SUCCESS); ASSERT_TRUE(CRYPT_EAL_MacUpdate(ctx, data, dataLen) == CRYPT_SUCCESS); ASSERT_TRUE(CRYPT_EAL_MacFinal(ctx, mac, &macLen) == CRYPT_SUCCESS); ASSERT_TRUE(CRYPT_EAL_MacUpdate(ctx, data, dataLen) == CRYPT_EAL_ERR_STATE); ASSERT_TRUE(CRYPT_EAL_MacUpdate(ctx, data, dataLen) == CRYPT_EAL_ERR_STATE); CRYPT_EAL_MacDeinit(ctx); ASSERT_TRUE(CRYPT_EAL_MacUpdate(ctx, data, dataLen) == CRYPT_EAL_ERR_STATE); ASSERT_TRUE(CRYPT_EAL_MacFinal(ctx, mac, &macLen) == CRYPT_EAL_ERR_STATE); ASSERT_TRUE(CRYPT_EAL_MacInit(ctx, key, len) == CRYPT_SUCCESS); ASSERT_TRUE(CRYPT_EAL_MacUpdate(ctx, data, dataLen) == CRYPT_SUCCESS); ASSERT_TRUE(CRYPT_EAL_MacReinit(ctx) == CRYPT_SUCCESS); ASSERT_TRUE(CRYPT_EAL_MacUpdate(ctx, data, dataLen) == CRYPT_SUCCESS); ASSERT_TRUE(CRYPT_EAL_MacUpdate(ctx, data, dataLen) == CRYPT_SUCCESS); EXIT: CRYPT_EAL_MacFreeCtx(ctx); } /* END_CASE */ /* @ * @test SDV_CRYPT_EAL_CBC_MAC_API_TC006 * @spec - * @title Impact of Input Parameters on the CRYPT_EAL_MacFinal Interface * @precon nan * @brief * @prior Level 1 * @auto TRUE @ */ /* BEGIN_CASE */ void SDV_CRYPT_EAL_CBC_MAC_API_TC006(int algId, int padType) { if (IsMacAlgDisabled(algId)) { SKIP_TEST(); } TestMemInit(); const uint32_t len = SM4_KEY_LEN; uint8_t key[len]; uint32_t macLen = CBC_MAC_MAC_LEN; uint8_t mac[macLen]; CRYPT_EAL_MacCtx *ctx = CRYPT_EAL_MacNewCtx(algId); ASSERT_TRUE(ctx != NULL); ASSERT_TRUE(CRYPT_EAL_MacInit(ctx, key, len) == CRYPT_SUCCESS); ASSERT_TRUE(CRYPT_EAL_MacCtrl(ctx, CRYPT_CTRL_SET_CBC_MAC_PADDING, &padType, sizeof(CRYPT_PaddingType)) == CRYPT_SUCCESS); ASSERT_TRUE(CRYPT_EAL_MacFinal(NULL, mac, &macLen) == CRYPT_NULL_INPUT); ASSERT_TRUE(CRYPT_EAL_MacFinal(ctx, NULL, &macLen) == CRYPT_NULL_INPUT); ASSERT_TRUE(CRYPT_EAL_MacFinal(ctx, mac, NULL) == CRYPT_NULL_INPUT); macLen = CBC_MAC_MAC_LEN - 1; ASSERT_TRUE(CRYPT_EAL_MacFinal(ctx, mac, &macLen) == CRYPT_CBC_MAC_OUT_BUFF_LEN_NOT_ENOUGH); macLen = CBC_MAC_MAC_LEN + 1; ASSERT_TRUE(CRYPT_EAL_MacFinal(ctx, mac, &macLen) == CRYPT_SUCCESS); ASSERT_TRUE(CRYPT_EAL_MacInit(ctx, key, len) == CRYPT_SUCCESS); ASSERT_TRUE(CRYPT_EAL_MacFinal(ctx, mac, &macLen) == CRYPT_SUCCESS); EXIT: CRYPT_EAL_MacFreeCtx(ctx); } /* END_CASE */ /* @ * @test SDV_CRYPT_EAL_CBC_MAC_API_TC007 * @spec - * @title Impact of ctx Status Change on the CRYPT_EAL_MacFinal Interface * @precon nan * @brief * @prior Level 1 * @auto TRUE @ */ /* BEGIN_CASE */ void SDV_CRYPT_EAL_CBC_MAC_API_TC007(int algId, int padType, Hex *key1, Hex *mac1, Hex *key2, Hex *data2, Hex *mac2, Hex *mac3) { if (IsMacAlgDisabled(algId)) { SKIP_TEST(); } TestMemInit(); uint32_t macLen = CBC_MAC_MAC_LEN; uint8_t mac[macLen]; CRYPT_EAL_MacCtx *ctx = CRYPT_EAL_MacNewCtx(algId); ASSERT_TRUE(ctx != NULL); ASSERT_TRUE(CRYPT_EAL_MacFinal(ctx, mac, &macLen) == CRYPT_EAL_ERR_STATE); ASSERT_TRUE(CRYPT_EAL_MacFinal(ctx, mac, &macLen) == CRYPT_EAL_ERR_STATE); ASSERT_TRUE(CRYPT_EAL_MacUpdate(ctx, data2->x, data2->len) == CRYPT_EAL_ERR_STATE); // mac1 ASSERT_TRUE(CRYPT_EAL_MacInit(ctx, key1->x, key1->len) == CRYPT_SUCCESS); ASSERT_TRUE(CRYPT_EAL_MacCtrl(ctx, CRYPT_CTRL_SET_CBC_MAC_PADDING, &padType, sizeof(CRYPT_PaddingType)) == CRYPT_SUCCESS); ASSERT_TRUE(CRYPT_EAL_MacFinal(ctx, mac, &macLen) == CRYPT_SUCCESS); ASSERT_COMPARE("mac1 result cmp", mac, macLen, mac1->x, mac1->len); // mac2 ASSERT_TRUE(CRYPT_EAL_MacInit(ctx, key2->x, key2->len) == CRYPT_SUCCESS); ASSERT_TRUE(CRYPT_EAL_MacUpdate(ctx, data2->x, data2->len) == CRYPT_SUCCESS); ASSERT_TRUE(CRYPT_EAL_MacFinal(ctx, mac, &macLen) == CRYPT_SUCCESS); ASSERT_COMPARE("mac2 result cmp", mac, macLen, mac2->x, mac2->len); CRYPT_EAL_MacDeinit(ctx); ASSERT_TRUE(CRYPT_EAL_MacFinal(ctx, mac, &macLen) == CRYPT_EAL_ERR_STATE); // mac3 ASSERT_TRUE(CRYPT_EAL_MacInit(ctx, key2->x, key2->len) == CRYPT_SUCCESS); ASSERT_TRUE(CRYPT_EAL_MacReinit(ctx) == CRYPT_SUCCESS); ASSERT_TRUE(CRYPT_EAL_MacFinal(ctx, mac, &macLen) == CRYPT_SUCCESS); ASSERT_COMPARE("mac3 result cmp", mac, macLen, mac3->x, mac3->len); ASSERT_TRUE(CRYPT_EAL_MacFinal(ctx, mac, &macLen) == CRYPT_EAL_ERR_STATE); EXIT: CRYPT_EAL_MacFreeCtx(ctx); } /* END_CASE */ /* @ * @test SDV_CRYPT_EAL_CBC_MAC_API_TC008 * @spec - * @title Impact of Input Parameters on the CRYPT_EAL_GetMacLen Interface. * @precon nan * @brief * @prior Level 1 * @auto TRUE @ */ /* BEGIN_CASE */ void SDV_CRYPT_EAL_CBC_MAC_API_TC008(int algId) { if (IsMacAlgDisabled(algId)) { SKIP_TEST(); } TestMemInit(); const uint32_t len = SM4_KEY_LEN; uint8_t key[len]; CRYPT_EAL_MacCtx *ctx = CRYPT_EAL_MacNewCtx(algId); ASSERT_TRUE(CRYPT_EAL_MacInit(ctx, key, len) == CRYPT_SUCCESS); ASSERT_TRUE(CRYPT_EAL_GetMacLen(NULL) == 0); ASSERT_TRUE(CRYPT_EAL_GetMacLen(ctx) == CBC_MAC_MAC_LEN); uint32_t result = 0; ASSERT_TRUE(CRYPT_EAL_MacCtrl(ctx, CRYPT_CTRL_GET_MACLEN, &result, sizeof(uint32_t)) == CRYPT_SUCCESS); ASSERT_TRUE(result == CBC_MAC_MAC_LEN); EXIT: CRYPT_EAL_MacFreeCtx(ctx); } /* END_CASE */ /* @ * @test SDV_CRYPT_EAL_CBC_MAC_API_TC009 * @spec - * @title Impact of the ctx Status on the CRYPT_EAL_GetMacLen Interface * @precon nan * @brief * @prior Level 1 * @auto TRUE @ */ /* BEGIN_CASE */ void SDV_CRYPT_EAL_CBC_MAC_API_TC009(int algId, int padType) { if (IsMacAlgDisabled(algId)) { SKIP_TEST(); } TestMemInit(); const uint32_t len = SM4_KEY_LEN; uint8_t key[len]; uint32_t macLen = CBC_MAC_MAC_LEN; uint8_t mac[macLen]; const uint32_t dataLen = CBC_MAC_MAC_LEN; uint8_t data[dataLen]; CRYPT_EAL_MacCtx *ctx = CRYPT_EAL_MacNewCtx(algId); ASSERT_TRUE(ctx != NULL); ASSERT_TRUE(CRYPT_EAL_GetMacLen(ctx) == CBC_MAC_MAC_LEN); ASSERT_TRUE(CRYPT_EAL_MacInit(ctx, key, len) == CRYPT_SUCCESS); ASSERT_TRUE(CRYPT_EAL_GetMacLen(ctx) == CBC_MAC_MAC_LEN); ASSERT_TRUE(CRYPT_EAL_MacCtrl(ctx, CRYPT_CTRL_SET_CBC_MAC_PADDING, &padType, sizeof(CRYPT_PaddingType)) == CRYPT_SUCCESS); ASSERT_TRUE(CRYPT_EAL_MacUpdate(ctx, data, dataLen) == CRYPT_SUCCESS); ASSERT_TRUE(CRYPT_EAL_GetMacLen(ctx) == CBC_MAC_MAC_LEN); ASSERT_TRUE(CRYPT_EAL_MacFinal(ctx, mac, &macLen) == CRYPT_SUCCESS); ASSERT_TRUE(CRYPT_EAL_GetMacLen(ctx) == CBC_MAC_MAC_LEN); CRYPT_EAL_MacDeinit(ctx); ASSERT_TRUE(CRYPT_EAL_GetMacLen(ctx) == CBC_MAC_MAC_LEN); ASSERT_TRUE(CRYPT_EAL_MacFinal(ctx, mac, &macLen) == CRYPT_EAL_ERR_STATE); ASSERT_TRUE(CRYPT_EAL_GetMacLen(ctx) == CBC_MAC_MAC_LEN); EXIT: CRYPT_EAL_MacFreeCtx(ctx); } /* END_CASE */ /* @ * @test SDV_CRYPT_EAL_CBC_MAC_API_TC010 * @spec - * @title Impact of Input Parameters on the CRYPT_EAL_MacDeinit Interface Test * @precon nan * @brief * @prior Level 1 * @auto TRUE @ */ /* BEGIN_CASE */ void SDV_CRYPT_EAL_CBC_MAC_API_TC010(int algId) { if (IsMacAlgDisabled(algId)) { SKIP_TEST(); } TestMemInit(); const uint32_t len = SM4_KEY_LEN; uint8_t key[len]; CRYPT_EAL_MacCtx *ctx = CRYPT_EAL_MacNewCtx(algId); ASSERT_TRUE(ctx != NULL); ASSERT_TRUE(CRYPT_EAL_MacInit(ctx, key, len) == CRYPT_SUCCESS); CRYPT_EAL_MacDeinit(ctx); ASSERT_TRUE(CRYPT_EAL_MacInit(ctx, key, len) == CRYPT_SUCCESS); CRYPT_EAL_MacDeinit(NULL); EXIT: CRYPT_EAL_MacFreeCtx(ctx); } /* END_CASE */ /* @ * @test SDV_CRYPT_EAL_CBC_MAC_API_TC011 * @spec - * @title Impact of Input Parameters on the CRYPT_EAL_MacReinit Interface * @precon nan * @brief * @prior Level 1 * @auto TRUE @ */ /* BEGIN_CASE */ void SDV_CRYPT_EAL_CBC_MAC_API_TC011(int algId) { if (IsMacAlgDisabled(algId)) { SKIP_TEST(); } TestMemInit(); const uint32_t len = SM4_KEY_LEN; uint8_t key[len]; CRYPT_EAL_MacCtx *ctx = CRYPT_EAL_MacNewCtx(algId); ASSERT_TRUE(ctx != NULL); ASSERT_TRUE(CRYPT_EAL_MacInit(ctx, key, len) == CRYPT_SUCCESS); ASSERT_TRUE(CRYPT_EAL_MacReinit(NULL) == CRYPT_NULL_INPUT); ASSERT_TRUE(CRYPT_EAL_MacReinit(ctx) == CRYPT_SUCCESS); EXIT: CRYPT_EAL_MacFreeCtx(ctx); } /* END_CASE */ /* @ * @test SDV_CRYPT_EAL_CBC_MAC_API_TC012 * @spec - * @title Impact of ctx status change on the CRYPT_EAL_MacReinit interface * @precon nan * @brief * @prior Level 1 * @auto TRUE @ */ /* BEGIN_CASE */ void SDV_CRYPT_EAL_CBC_MAC_API_TC012(int algId, int padType) { if (IsMacAlgDisabled(algId)) { SKIP_TEST(); } TestMemInit(); const uint32_t len = SM4_KEY_LEN; uint8_t key[len]; uint32_t macLen = CBC_MAC_MAC_LEN; uint8_t mac[macLen]; const uint32_t dataLen = SM4_KEY_LEN; uint8_t data[dataLen]; CRYPT_EAL_MacCtx *ctx = CRYPT_EAL_MacNewCtx(algId); ASSERT_TRUE(ctx != NULL); ASSERT_TRUE(CRYPT_EAL_MacReinit(ctx) == CRYPT_EAL_ERR_STATE); ASSERT_TRUE(CRYPT_EAL_MacReinit(ctx) == CRYPT_EAL_ERR_STATE); ASSERT_TRUE(CRYPT_EAL_MacInit(ctx, key, len) == CRYPT_SUCCESS); ASSERT_TRUE(CRYPT_EAL_MacCtrl(ctx, CRYPT_CTRL_SET_CBC_MAC_PADDING, &padType, sizeof(CRYPT_PaddingType)) == CRYPT_SUCCESS); ASSERT_TRUE(CRYPT_EAL_MacReinit(ctx) == CRYPT_SUCCESS); ASSERT_TRUE(CRYPT_EAL_MacReinit(ctx) == CRYPT_SUCCESS); ASSERT_TRUE(CRYPT_EAL_MacUpdate(ctx, data, dataLen) == CRYPT_SUCCESS); ASSERT_TRUE(CRYPT_EAL_MacReinit(ctx) == CRYPT_SUCCESS); ASSERT_TRUE(CRYPT_EAL_MacFinal(ctx, mac, &macLen) == CRYPT_SUCCESS); ASSERT_TRUE(CRYPT_EAL_MacReinit(ctx) == CRYPT_SUCCESS); CRYPT_EAL_MacDeinit(ctx); ASSERT_TRUE(CRYPT_EAL_MacReinit(ctx) == CRYPT_EAL_ERR_STATE); EXIT: CRYPT_EAL_MacFreeCtx(ctx); } /* END_CASE */ /* @ * @test SDV_CRYPT_EAL_CBC_MAC_FUN_TC004 * @spec - * @title Impact of All-0 and All-F Data Keys on CBC MAC Calculation * @precon nan * @brief * @prior Level 1 * @auto TRUE @ */ /* BEGIN_CASE */ void SDV_CRYPT_EAL_CBC_MAC_FUN_TC004(int algId, int padType, Hex *key, Hex *data, Hex *vecMac) { if (IsMacAlgDisabled(algId)) { SKIP_TEST(); } TestMemInit(); uint32_t macLen = CBC_MAC_MAC_LEN; uint8_t mac[macLen]; CRYPT_EAL_MacCtx *ctx = CRYPT_EAL_MacNewCtx(algId); ASSERT_TRUE(ctx != NULL); ASSERT_TRUE(CRYPT_EAL_MacInit(ctx, key->x, key->len) == CRYPT_SUCCESS); ASSERT_TRUE(CRYPT_EAL_MacCtrl(ctx, CRYPT_CTRL_SET_CBC_MAC_PADDING, &padType, sizeof(CRYPT_PaddingType)) == CRYPT_SUCCESS); ASSERT_TRUE(CRYPT_EAL_MacUpdate(ctx, data->x, data->len) == CRYPT_SUCCESS); ASSERT_TRUE(CRYPT_EAL_MacFinal(ctx, mac, &macLen) == CRYPT_SUCCESS); ASSERT_COMPARE("mac1 result cmp", mac, macLen, vecMac->x, vecMac->len); EXIT: CRYPT_EAL_MacFreeCtx(ctx); } /* END_CASE */ static int32_t UpdateMultiTime(CRYPT_EAL_MacCtx *ctx, Hex *data, int updateTimes, uint8_t *mac, uint32_t *macLen) { int32_t ret = CRYPT_SUCCESS; for (int i = 0; i < updateTimes; i++) { ret = CRYPT_EAL_MacUpdate(ctx, data->x, data->len); if (ret != CRYPT_SUCCESS) { return ret; } } return CRYPT_EAL_MacFinal(ctx, mac, macLen); } /* @ * @test SDV_CRYPT_EAL_CBC_MAC_FUN_TC006 * @spec - * @title Compare the cmac results of multiple updates and one update. * @precon nan * @brief * @prior Level 1 * @auto TRUE @ */ /* BEGIN_CASE */ void SDV_CRYPT_EAL_CBC_MAC_FUN_TC006(int algId, int padType, Hex *key, Hex *data, int updateTimes) { if (IsMacAlgDisabled(algId)) { SKIP_TEST(); } TestMemInit(); uint32_t macLen1 = CBC_MAC_MAC_LEN; uint8_t mac1[CBC_MAC_MAC_LEN] = {}; uint32_t macLen2 = CBC_MAC_MAC_LEN; uint8_t mac2[CBC_MAC_MAC_LEN] = {}; uint8_t *totalInData = NULL; uint32_t totalLen = 0; CRYPT_EAL_MacCtx *ctx = CRYPT_EAL_MacNewCtx(algId); ASSERT_TRUE(ctx != NULL); ASSERT_TRUE(CRYPT_EAL_MacInit(ctx, key->x, key->len) == CRYPT_SUCCESS); ASSERT_TRUE(CRYPT_EAL_MacCtrl(ctx, CRYPT_CTRL_SET_CBC_MAC_PADDING, &padType, sizeof(CRYPT_PaddingType)) == CRYPT_SUCCESS); ASSERT_TRUE(UpdateMultiTime(ctx, data, updateTimes, mac1, &macLen1) == CRYPT_SUCCESS); CRYPT_EAL_MacDeinit(ctx); totalInData = BSL_SAL_Calloc(data->len * updateTimes, 1); ASSERT_TRUE(totalInData != NULL); for (int i = 0; i < updateTimes; i++) { memcpy(totalInData + totalLen, data->x, data->len); totalLen += data->len; } ASSERT_TRUE(CRYPT_EAL_MacInit(ctx, key->x, key->len) == CRYPT_SUCCESS); ASSERT_TRUE(CRYPT_EAL_MacCtrl(ctx, CRYPT_CTRL_SET_CBC_MAC_PADDING, &padType, sizeof(CRYPT_PaddingType)) == CRYPT_SUCCESS); ASSERT_TRUE(CRYPT_EAL_MacUpdate(ctx, totalInData, totalLen) == CRYPT_SUCCESS); ASSERT_TRUE(CRYPT_EAL_MacFinal(ctx, mac2, &macLen2) == CRYPT_SUCCESS); ASSERT_TRUE(macLen1 == macLen2); ASSERT_COMPARE("mac1 vs mac2 result cmp", mac2, macLen2, mac1, macLen1); EXIT: BSL_SAL_FREE(totalInData); CRYPT_EAL_MacFreeCtx(ctx); } /* END_CASE */ /** * @test SDV_CRYPT_EAL_CBC_MAC_SAMEADDR_FUNC_TC001 * @title CBC-MAC in/out同地址测试 * @precon nan * @brief * 1.使用EAL层接口进行CBC-MAC计算,其中所有的输入和输出地址相同,有预期结果1 * @expect * 1.计算成功,结果与mac向量一致 */ /* BEGIN_CASE */ void SDV_CRYPT_EAL_CBC_MAC_SAMEADDR_FUNC_TC001(int algId, Hex *key, Hex *data, Hex *mac) { TestMacSameAddr(algId, key, data, mac); } /* END_CASE */ /** * @test SDV_CRYPT_EAL_CBC_MAC_ADDR_NOT_ALIGN_FUNC_TC001 * @title CBC-MAC 非地址对齐测试 * @precon nan * @brief * 1.使用EAL层接口进行CBC-MAC计算,其中所有的buffer地址未对齐,有预期结果1 * @expect * 1.计算成功,结果与mac向量一致 */ /* BEGIN_CASE */ void SDV_CRYPT_EAL_CBC_MAC_ADDR_NOT_ALIGN_FUNC_TC001(int algId, Hex *key, Hex *data, Hex *mac) { TestMacAddrNotAlign(algId, key, data, mac); } /* END_CASE */
2301_79861745/bench_create
testcode/sdv/testcase/crypto/cbc_mac/test_suite_sdv_eal_mac_cbc_mac.c
C
unknown
19,510
/* * This file is part of the openHiTLS project. * * openHiTLS is licensed under the Mulan PSL v2. * You can use this software according to the terms and conditions of the Mulan PSL v2. * You may obtain a copy of Mulan PSL v2 at: * * http://license.coscl.org.cn/MulanPSL2 * * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, * EITHER EXPRESS 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_errno.h" #include "crypt_eal_cipher.h" #include "bsl_sal.h" #include "securec.h" /* END_HEADER */ /** * @test SDV_CRYPTO_CHACHA20POLY1305_INIT_API_TC001 * @title CRYPT_EAL_CipherInit Invalid input parameter * @precon Registering memory-related functions. * @brief * 1.Create the context ctx. Expected result 1 is obtained. * 2.Call the Init interface, ctx is NULL, other parameters are normal. Expected result 1 is obtained. * 3.Call the Init interface, key is NULL, other parameters are normal. Expected result 2 is obtained. * 4.Call the Init interface, iv is NULL, other parameters are normal. Expected result 2 is obtained. * @expect * 1.Failed. Return CRYPT_NULL_INPUT. * 2.Failed. Return CRYPT_NULL_INPUT. * 3.Failed. Return CRYPT_NULL_INPUT. */ /* BEGIN_CASE */ void SDV_CRYPTO_CHACHA20POLY1305_INIT_API_TC001(void) { TestMemInit(); uint8_t key[32] = {0}; uint8_t iv[12] = {0}; CRYPT_EAL_CipherCtx *ctx = CRYPT_EAL_CipherNewCtx(CRYPT_CIPHER_CHACHA20_POLY1305); ASSERT_TRUE(CRYPT_EAL_CipherInit(NULL, key, sizeof(key), iv, sizeof(iv), true) == CRYPT_NULL_INPUT); ASSERT_EQ(CRYPT_EAL_CipherInit(ctx, NULL, sizeof(key), iv, sizeof(iv), true), CRYPT_NULL_INPUT); ASSERT_EQ(CRYPT_EAL_CipherInit(ctx, key, sizeof(key), NULL, sizeof(iv), true), CRYPT_NULL_INPUT); EXIT: CRYPT_EAL_CipherFreeCtx(ctx); } /* END_CASE */ /** * @test SDV_CRYPTO_CHACHA20POLY1305_INIT_API_TC002 * @title CRYPT_EAL_CipherInit Invalid input parameter * @precon Registering memory-related functions. * @brief * 1.Create the context ctx. Expected result 1 is obtained. * 2.Call the Init interface with keyLen is 33, other parameters are normal. Expected result 1 is obtained. * 3.Call the Init interface with keyLen is 31, other parameters are normal. Expected result 2 is obtained. * 4.Call the Init interface with ivLen is 11, other parameters are normal. Expected result 3 is obtained. * 5.Call the Init interface with ivLen is 13, other parameters are normal. Expected result 4 is obtained. * 6.Call the Init interface with ivLen is 9, other parameters are normal. Expected result 5 is obtained. * 7.Call the Init interface with ivLen is 7, other parameters are normal. Expected result 6 is obtained. * @expect * 1.Failed. Return CRYPT_CHACHA20_KEYLEN_ERROR. * 2.Failed. Return CRYPT_CHACHA20_KEYLEN_ERROR. * 3.Failed. Return CRYPT_MODES_IVLEN_ERROR. * 4.Failed. Return CRYPT_MODES_IVLEN_ERROR. * 5.Failed. Return CRYPT_MODES_IVLEN_ERROR. * 6.Failed. Return CRYPT_MODES_IVLEN_ERROR. */ /* BEGIN_CASE */ void SDV_CRYPTO_CHACHA20POLY1305_INIT_API_TC002(void) { TestMemInit(); uint8_t key[32] = {0}; uint8_t iv[12] = {0}; CRYPT_EAL_CipherCtx *ctx = CRYPT_EAL_CipherNewCtx(CRYPT_CIPHER_CHACHA20_POLY1305); ASSERT_EQ(CRYPT_EAL_CipherInit(ctx, (uint8_t *)key, 33, iv, sizeof(iv), true), CRYPT_CHACHA20_KEYLEN_ERROR); ASSERT_EQ(CRYPT_EAL_CipherInit(ctx, (uint8_t *)key, 31, iv, sizeof(iv), true), CRYPT_CHACHA20_KEYLEN_ERROR); ASSERT_EQ(CRYPT_EAL_CipherInit(ctx, key, sizeof(key), (uint8_t *)iv, 13, true), CRYPT_MODES_IVLEN_ERROR); ASSERT_EQ(CRYPT_EAL_CipherInit(ctx, key, sizeof(key), (uint8_t *)iv, 11, true), CRYPT_MODES_IVLEN_ERROR); ASSERT_EQ(CRYPT_EAL_CipherInit(ctx, key, sizeof(key), (uint8_t *)iv, 9, true), CRYPT_MODES_IVLEN_ERROR); ASSERT_EQ(CRYPT_EAL_CipherInit(ctx, key, sizeof(key), (uint8_t *)iv, 7, true), CRYPT_MODES_IVLEN_ERROR); EXIT: CRYPT_EAL_CipherFreeCtx(ctx); } /* END_CASE */ /** * @test SDV_CRYPTO_CHACHA20POLY1305_REINIT_API_TC001 * @title CRYPT_EAL_CipherReinit Invalid input parameter Test * @precon Registering memory-related functions. * @brief * 1.Create the context ctx. * 2.Call the Init interface. Expected result 1 is obtained. * 3.Call the Reinit interface with iv is NULL, and set other parameters correctly. Expected result 2 is obtained. * 4.Call the Reinit interface with ctx is NULL, and set other parameters correctly. Expected result 3 is obtained. * @expect * 1.The init is successful and return CRYPT_SUCCESS. * 2.Failed. Return CRYPT_NULL_INPUT. * 3.Failed. Return CRYPT_NULL_INPUT. */ /* BEGIN_CASE */ void SDV_CRYPTO_CHACHA20POLY1305_REINIT_API_TC001(void) { TestMemInit(); uint8_t key[32] = {0}; uint8_t iv[12] = {0}; CRYPT_EAL_CipherCtx *ctx = CRYPT_EAL_CipherNewCtx(CRYPT_CIPHER_CHACHA20_POLY1305); ASSERT_TRUE(CRYPT_EAL_CipherInit(ctx, key, sizeof(key), iv, sizeof(iv), true) == CRYPT_SUCCESS); ASSERT_TRUE(CRYPT_EAL_CipherReinit(ctx, NULL, sizeof(iv)) == CRYPT_NULL_INPUT); ASSERT_TRUE(CRYPT_EAL_CipherReinit(NULL, iv, sizeof(iv)) == CRYPT_NULL_INPUT); EXIT: CRYPT_EAL_CipherFreeCtx(ctx); } /* END_CASE */ /** * @test SDV_CRYPTO_CHACHA20POLY1305_REINIT_API_TC002 * @title CRYPT_EAL_CipherReinit Invalid input parameter Test * @precon Registering memory-related functions. * @brief * 1.Create the context ctx. * 2.Call the Init interface. Expected result 1 is obtained. * 3.Call the Reinit interface with ivLen is 11, and set other parameters correctly. Expected result 2 is obtained. * 4.Call the Reinit interface with ivLen is 13, and set other parameters correctly. Expected result 3 is obtained. * 5.Call the Reinit interface with ivLen is 9, and set other parameters correctly. Expected result 4 is obtained. * 6.Call the Reinit interface with ivLen is 7, and set other parameters correctly. Expected result 5 is obtained. * @expect * 1.The init is successful and return CRYPT_SUCCESS. * 2.Failed. Return CRYPT_MODES_IVLEN_ERROR. * 3.Failed. Return CRYPT_MODES_IVLEN_ERROR. * 4.Failed. Return CRYPT_MODES_IVLEN_ERROR. * 5.Failed. Return CRYPT_MODES_IVLEN_ERROR. */ /* BEGIN_CASE */ void SDV_CRYPTO_CHACHA20POLY1305_REINIT_API_TC002(void) { TestMemInit(); uint8_t key[32] = {0}; uint8_t iv[12] = {0}; CRYPT_EAL_CipherCtx *ctx = CRYPT_EAL_CipherNewCtx(CRYPT_CIPHER_CHACHA20_POLY1305); ASSERT_TRUE(CRYPT_EAL_CipherInit(ctx, key, sizeof(key), iv, sizeof(iv), true) == CRYPT_SUCCESS); ASSERT_TRUE(CRYPT_EAL_CipherReinit(ctx, (uint8_t *)iv, 13) == CRYPT_MODES_IVLEN_ERROR); ASSERT_TRUE(CRYPT_EAL_CipherReinit(ctx, (uint8_t *)iv, 11) == CRYPT_MODES_IVLEN_ERROR); ASSERT_TRUE(CRYPT_EAL_CipherReinit(ctx, (uint8_t *)iv, 9) == CRYPT_MODES_IVLEN_ERROR); ASSERT_TRUE(CRYPT_EAL_CipherReinit(ctx, (uint8_t *)iv, 7) == CRYPT_MODES_IVLEN_ERROR); EXIT: CRYPT_EAL_CipherFreeCtx(ctx); } /* END_CASE */ /** * @test SDV_CRYPTO_CHACHA20POLY1305_REINIT_API_TC003 * @title Call sequence error Test * @precon Registering memory-related functions. * @brief * 1.Create the context ctx. * 2.Call the Reinit interface. All parameters are normal. Expected result 1 is obtained. * @expect * 1.Failed. Return CRYPT_EAL_ERR_STATE. */ /* BEGIN_CASE */ void SDV_CRYPTO_CHACHA20POLY1305_REINIT_API_TC003(void) { TestMemInit(); uint8_t iv[12] = {0}; CRYPT_EAL_CipherCtx *ctx = CRYPT_EAL_CipherNewCtx(CRYPT_CIPHER_CHACHA20_POLY1305); ASSERT_TRUE(CRYPT_EAL_CipherReinit(ctx, iv, sizeof(iv)) == CRYPT_EAL_ERR_STATE); EXIT: CRYPT_EAL_CipherFreeCtx(ctx); } /* END_CASE */ /** * @test SDV_CRYPTO_CHACHA20POLY1305_UPDATE_API_TC001 * @title Invalid input parameter of CRYPT_EAL_CipherUpdate Test * @precon Registering memory-related functions. * @brief * 1.Create the context ctx. * 2.Call the Init interface. Expected result 1 is obtained. * 3.Call the Ctrl interface to set aad. Expected result 2 is obtained. * 4.Call the Update interface, ctx is NULL, and other parameters are normal. Expected result 3 is obtained. * 4.Call the Update interface, in is NULL, and other parameters are normal. Expected result 4 is obtained. * 5.Call the Update interface, inLen is 0, and other parameters are normal. Expected result 5 is obtained. * 6.Call the Update interface, out is NULL, and other parameters are normal. Expected result 6 is obtained. * 7.Call the Update interface, outLen is NULL, and other parameters are normal. Expected result 7 is obtained. * @expect * 1.The init is successful and return CRYPT_SUCCESS. * 2.Success. Return CRYPT_SUCCESS. * 3.Failed. Return CRYPT_NULL_INPUT. * 4.Failed. Return CRYPT_NULL_INPUT. * 5.Success. Return CRYPT_SUCCESS. * 6.Failed. Return CRYPT_NULL_INPUT. * 7.Failed. Return CRYPT_NULL_INPUT. */ /* BEGIN_CASE */ void SDV_CRYPTO_CHACHA20POLY1305_UPDATE_API_TC001(void) { TestMemInit(); uint8_t key[32] = {0}; uint8_t iv[12] = {0}; uint8_t data[100] = {0}; uint8_t aad[20] = {0}; uint8_t out[100]; uint32_t outLen = sizeof(out); CRYPT_EAL_CipherCtx *ctx = CRYPT_EAL_CipherNewCtx(CRYPT_CIPHER_CHACHA20_POLY1305); ASSERT_TRUE(CRYPT_EAL_CipherInit(ctx, key, sizeof(key), iv, sizeof(iv), true) == CRYPT_SUCCESS); ASSERT_TRUE(CRYPT_EAL_CipherCtrl(ctx, CRYPT_CTRL_SET_AAD, aad, sizeof(aad)) == CRYPT_SUCCESS); ASSERT_TRUE(CRYPT_EAL_CipherUpdate(NULL, data, sizeof(data), out, &outLen) == CRYPT_NULL_INPUT); ASSERT_TRUE(CRYPT_EAL_CipherUpdate(ctx, NULL, sizeof(data), out, &outLen) == CRYPT_NULL_INPUT); ASSERT_TRUE(CRYPT_EAL_CipherUpdate(ctx, data, 0, out, &outLen) == CRYPT_SUCCESS); ASSERT_TRUE(CRYPT_EAL_CipherUpdate(ctx, data, sizeof(data), NULL, &outLen) == CRYPT_NULL_INPUT); ASSERT_TRUE(CRYPT_EAL_CipherUpdate(ctx, data, sizeof(data), (uint8_t *)out, NULL) == CRYPT_NULL_INPUT); EXIT: CRYPT_EAL_CipherFreeCtx(ctx); } /* END_CASE */ /** * @test SDV_CRYPTO_CHACHA20POLY1305_UPDATE_API_TC002 * @title CRYPT_EAL_CipherUpdate Invalid input parameter Test * @precon Registering memory-related functions. * @brief * 1.Create the context ctx. * 2.Call the Init interface. All parameters are normal. Expected result 1 is obtained. * 3.Call the Ctrl interface to set aad. Expected result 2 is obtained. * 4.Call the Update interface, outLen is inLen - 1, and other parameters are normal. Expected result 3 is obtained. * @expect * 1.The init is successful and return CRYPT_SUCCESS. * 2.Success. Return CRYPT_SUCCESS. * 3.Failed. The buffer is not enough. */ /* BEGIN_CASE */ void SDV_CRYPTO_CHACHA20POLY1305_UPDATE_API_TC002(void) { TestMemInit(); uint8_t key[32] = {0}; uint8_t iv[12] = {0}; uint8_t data[100] = {0}; uint8_t aad[20] = {0}; uint8_t out[100]; uint32_t outLen = sizeof(data) - 1; CRYPT_EAL_CipherCtx *ctx = CRYPT_EAL_CipherNewCtx(CRYPT_CIPHER_CHACHA20_POLY1305); ASSERT_EQ(CRYPT_EAL_CipherInit(ctx, key, sizeof(key), iv, sizeof(iv), true), CRYPT_SUCCESS); ASSERT_EQ(CRYPT_EAL_CipherCtrl(ctx, CRYPT_CTRL_SET_AAD, aad, sizeof(aad)), CRYPT_SUCCESS); ASSERT_NE(CRYPT_EAL_CipherUpdate(ctx, data, sizeof(data), (uint8_t *)out, &outLen), CRYPT_SUCCESS); EXIT: CRYPT_EAL_CipherFreeCtx(ctx); } /* END_CASE */ /** * @test SDV_CRYPTO_CHACHA20POLY1305_UPDATE_API_TC003 * @title CRYPT_EAL_CipherUpdate Error State Test * @precon Registering memory-related functions. * @brief * 1.Create the context ctx. * 2.Call the Update interface. All parameters are normal. Expected result 1 is obtained. * @expect * 1.Failed. return CRYPT_EAL_ERR_STATE. */ /* BEGIN_CASE */ void SDV_CRYPTO_CHACHA20POLY1305_UPDATE_API_TC003(void) { TestMemInit(); uint8_t data[100] = {0}; uint8_t out[100]; uint32_t outLen = sizeof(out); CRYPT_EAL_CipherCtx *ctx = CRYPT_EAL_CipherNewCtx(CRYPT_CIPHER_CHACHA20_POLY1305); ASSERT_TRUE(CRYPT_EAL_CipherUpdate(ctx, data, sizeof(data), out, &outLen) == CRYPT_EAL_ERR_STATE); EXIT: CRYPT_EAL_CipherFreeCtx(ctx); } /* END_CASE */ /** * @test SDV_CRYPTO_CHACHA20POLY1305_CTRL_API_TC001 * @title CRYPT_EAL_CipherCtrl set aad invalid parameter Test * @precon Registering memory-related functions. * @brief * 1.Create the context ctx. * 2.Call the Init interface. All parameters are normal. Expected result 1 is obtained. * 3.Call the Ctrl interface to set aad with aad is NULL and aadLen is not 0. Expected result 2 is obtained. * 4.Call the Ctrl interface to set aad with ctx is NULL. Expected result 3 is obtained. * @expect * 1.Success. Return CRYPT_SUCCESS. * 2.Failed. Return CRYPT_NULL_INPUT. * 3.Failed. Return CRYPT_NULL_INPUT. */ /* BEGIN_CASE */ void SDV_CRYPTO_CHACHA20POLY1305_CTRL_API_TC001(void) { TestMemInit(); uint8_t key[32] = {0}; uint8_t iv[12] = {0}; uint8_t aad[20] = {0}; CRYPT_EAL_CipherCtx *ctx = CRYPT_EAL_CipherNewCtx(CRYPT_CIPHER_CHACHA20_POLY1305); ASSERT_TRUE(CRYPT_EAL_CipherInit(ctx, key, sizeof(key), iv, sizeof(iv), true) == CRYPT_SUCCESS); ASSERT_TRUE(CRYPT_EAL_CipherCtrl(ctx, CRYPT_CTRL_SET_AAD, NULL, sizeof(aad)) == CRYPT_NULL_INPUT); ASSERT_TRUE(CRYPT_EAL_CipherCtrl(NULL, CRYPT_CTRL_SET_AAD, aad, sizeof(aad)) == CRYPT_NULL_INPUT); EXIT: CRYPT_EAL_CipherFreeCtx(ctx); } /* END_CASE */ /** * @test SDV_CRYPTO_CHACHA20POLY1305_CTRL_API_TC002 * @title CRYPT_EAL_CipherCtrl get tag invalid parameter Test * @precon Registering memory-related functions. * @brief * 1.Create the context ctx. * 2.Call the Init interface. All parameters are normal. Expected result 1 is obtained. * 3.Call the Ctrl interface to set aad. Expected result 2 is obtained. * 4.Call the Ctrl interface to get tag with ctx is NULL. Expected result 3 is obtained. * 5.Call the Ctrl interface to get tag with data is NULL. Expected result 4 is obtained. * 6.Call the Ctrl interface to get tag with dataLen is 15. Expected result 5 is obtained. * 7.Call the Ctrl interface to get tag with dataLen is 17. Expected result 6 is obtained. * @expect * 1.Success. Return CRYPT_SUCCESS. * 2.Success. Return CRYPT_SUCCESS. * 3.Failed. Return CRYPT_NULL_INPUT. * 4.Failed. Return CRYPT_NULL_INPUT. * 5.Failed. Return CRYPT_MODES_TAGLEN_ERROR. * 6.Failed. Return CRYPT_MODES_TAGLEN_ERROR. */ /* BEGIN_CASE */ void SDV_CRYPTO_CHACHA20POLY1305_CTRL_API_TC002(void) { TestMemInit(); uint8_t key[32] = {0}; uint8_t iv[12] = {0}; uint8_t aad[20] = {0}; uint8_t out[16]; CRYPT_EAL_CipherCtx *ctx = CRYPT_EAL_CipherNewCtx(CRYPT_CIPHER_CHACHA20_POLY1305); ASSERT_TRUE(CRYPT_EAL_CipherInit(ctx, key, sizeof(key), iv, sizeof(iv), true) == CRYPT_SUCCESS); ASSERT_TRUE(CRYPT_EAL_CipherCtrl(ctx, CRYPT_CTRL_SET_AAD, aad, sizeof(aad)) == CRYPT_SUCCESS); ASSERT_TRUE(CRYPT_EAL_CipherCtrl(NULL, CRYPT_CTRL_GET_TAG, out, sizeof(out)) == CRYPT_NULL_INPUT); ASSERT_TRUE(CRYPT_EAL_CipherCtrl(ctx, CRYPT_CTRL_GET_TAG, NULL, sizeof(out)) == CRYPT_NULL_INPUT); ASSERT_TRUE(CRYPT_EAL_CipherInit(ctx, key, sizeof(key), iv, sizeof(iv), true) == CRYPT_SUCCESS); ASSERT_TRUE(CRYPT_EAL_CipherCtrl(ctx, CRYPT_CTRL_SET_AAD, aad, sizeof(aad)) == CRYPT_SUCCESS); ASSERT_TRUE(CRYPT_EAL_CipherCtrl(ctx, CRYPT_CTRL_GET_TAG, out, sizeof(out) - 1) == CRYPT_MODES_TAGLEN_ERROR); ASSERT_TRUE(CRYPT_EAL_CipherInit(ctx, key, sizeof(key), iv, sizeof(iv), true) == CRYPT_SUCCESS); ASSERT_TRUE(CRYPT_EAL_CipherCtrl(ctx, CRYPT_CTRL_SET_AAD, aad, sizeof(aad)) == CRYPT_SUCCESS); ASSERT_TRUE(CRYPT_EAL_CipherCtrl(ctx, CRYPT_CTRL_GET_TAG, out, sizeof(out) + 1) == CRYPT_MODES_TAGLEN_ERROR); EXIT: CRYPT_EAL_CipherFreeCtx(ctx); } /* END_CASE */ /** * @test SDV_CRYPTO_CHACHA20POLY1305_CTRL_API_TC003 * @title Invalid Algorithms to call Ctrl Interface Test * @precon Registering memory-related functions. * @brief * 1.Create the context ctx. * 2.Call the Init interface. All parameters are normal. Expected result 1 is obtained. * 3.Call the Ctrl interface to set iv. Expected result 2 is obtained. * 4.Call the Ctrl interface to get iv. Expected result 3 is obtained. * 5.Call the Ctrl interface to get blockSize. Expected result 4 is obtained. * 6.Call the Ctrl interface to set tag len. Expected result 5 is obtained. * 7.Call the Ctrl interface to set msg len. Expected result 6 is obtained. * @expect * 1.The init is successful and return CRYPT_SUCCESS. * 2.Setting failed. * 3.Getting failed. * 4.Getting failed. * 5.Setting failed. The algorithm is not supported. * 6.Setting failed. The algorithm is not supported. */ /* BEGIN_CASE */ void SDV_CRYPTO_CHACHA20POLY1305_CTRL_API_TC003(void) { TestMemInit(); uint8_t key[32] = {0}; uint8_t iv[12] = {0}; uint8_t buf[100] = {0}; uint8_t num = 0; uint32_t num32 = 0; uint64_t num64 = 0; CRYPT_EAL_CipherCtx *ctx = CRYPT_EAL_CipherNewCtx(CRYPT_CIPHER_CHACHA20_POLY1305); ASSERT_TRUE(CRYPT_EAL_CipherInit(ctx, key, sizeof(key), iv, sizeof(iv), true) == CRYPT_SUCCESS); ASSERT_TRUE(CRYPT_EAL_CipherCtrl(ctx, CRYPT_CTRL_GET_IV, (uint8_t *)buf, 12) != CRYPT_SUCCESS); ASSERT_TRUE(CRYPT_EAL_CipherCtrl(ctx, CRYPT_CTRL_GET_BLOCKSIZE, &num, sizeof(uint8_t)) != CRYPT_SUCCESS); ASSERT_TRUE(CRYPT_EAL_CipherCtrl(ctx, CRYPT_CTRL_SET_TAGLEN, &num32, sizeof(uint32_t)) != CRYPT_SUCCESS); ASSERT_TRUE(CRYPT_EAL_CipherCtrl(ctx, CRYPT_CTRL_SET_MSGLEN, &num64, sizeof(uint64_t)) != CRYPT_SUCCESS); EXIT: CRYPT_EAL_CipherFreeCtx(ctx); } /* END_CASE */ /** * @test SDV_CRYPTO_CHACHA20POLY1305_CTRL_API_TC004 * @title Set aad but not initialized Test * @precon Registering memory-related functions. * @brief * 1.Create the context ctx. * 2.Call the Ctrl interface to set iv. Expected result 1 is obtained. * @expect * 1.Failed. Return CRYPT_EAL_ERR_STATE. */ /* BEGIN_CASE */ void SDV_CRYPTO_CHACHA20POLY1305_CTRL_API_TC004(void) { TestMemInit(); uint8_t aad[20] = {0}; CRYPT_EAL_CipherCtx *ctx = CRYPT_EAL_CipherNewCtx(CRYPT_CIPHER_CHACHA20_POLY1305); ASSERT_EQ(CRYPT_EAL_CipherCtrl(ctx, CRYPT_CTRL_SET_AAD, aad, sizeof(aad)), CRYPT_EAL_ERR_STATE); EXIT: CRYPT_EAL_CipherFreeCtx(ctx); } /* END_CASE */ /** * @test SDV_CRYPTO_CHACHA20POLY1305_CTRL_API_TC005 * @title Set aad repeatedly Test * @precon Registering memory-related functions. * @brief * 1.Create the context ctx. * 2.Call the Init interface. All parameters are normal. Expected result 1 is obtained. * 3.Call the Ctrl interface to set aad. Expected result 2 is obtained. * 4.Call the Ctrl interface to set aad. Expected result 3 is obtained. * @expect * 1.The init is successful and return CRYPT_SUCCESS. * 2.Success. Return CRYPT_SUCCESS. * 3.Failed. The Aad has been set. */ /* BEGIN_CASE */ void SDV_CRYPTO_CHACHA20POLY1305_CTRL_API_TC005(void) { TestMemInit(); uint8_t key[32] = {0}; uint8_t iv[12] = {0}; uint8_t aad[20] = {0}; CRYPT_EAL_CipherCtx *ctx = CRYPT_EAL_CipherNewCtx(CRYPT_CIPHER_CHACHA20_POLY1305); ASSERT_TRUE(CRYPT_EAL_CipherInit(ctx, key, sizeof(key), iv, sizeof(iv), true) == CRYPT_SUCCESS); ASSERT_TRUE(CRYPT_EAL_CipherCtrl(ctx, CRYPT_CTRL_SET_AAD, aad, sizeof(aad)) == CRYPT_SUCCESS); ASSERT_TRUE(CRYPT_EAL_CipherCtrl(ctx, CRYPT_CTRL_SET_AAD, aad, sizeof(aad)) != CRYPT_SUCCESS); EXIT: CRYPT_EAL_CipherFreeCtx(ctx); } /* END_CASE */ /** * @test SDV_CRYPTO_CHACHA20POLY1305_CTRL_API_TC006 * @title Get tag but not initialized Test * @precon Registering memory-related functions. * @brief * 1.Create the context ctx. * 2.Call the Ctrl interface to get tag. Expected result 1 is obtained. * @expect * 1.Failed. Has not been initialized. */ /* BEGIN_CASE */ void SDV_CRYPTO_CHACHA20POLY1305_CTRL_API_TC006(void) { TestMemInit(); uint8_t tag[16] = {0}; const uint32_t tagLen = 16; // chacha-poly tag len is 16 CRYPT_EAL_CipherCtx *ctx = CRYPT_EAL_CipherNewCtx(CRYPT_CIPHER_CHACHA20_POLY1305); ASSERT_NE(CRYPT_EAL_CipherCtrl(ctx, CRYPT_CTRL_GET_TAG, tag, tagLen), CRYPT_SUCCESS); EXIT: CRYPT_EAL_CipherFreeCtx(ctx); } /* END_CASE */ /** * @test SDV_CRYPTO_CHACHA20POLY1305_FINAL_API_TC001 * @title Invalid Algorithms to call Final Interface Test * @precon Registering memory-related functions. * @brief * 1.Create the context ctx. * 2.Call the Init interface. Expected result 1 is obtained. * 3.Call the Ctrl interface to set aad. All parameters are normal. Expected result 2 is obtained. * 4.Call the Update interface. All parameters are normal. Expected result 3 is obtained. * 5.Call the Final interface. Expected result 4 is obtained. * @expect * 1.Success. Return CRYPT_SUCCESS. * 2.Success. Return CRYPT_SUCCESS. * 3.Success. Return CRYPT_SUCCESS. * 4.Failed. The algorithm is not supported. */ /* BEGIN_CASE */ void SDV_CRYPTO_CHACHA20POLY1305_FINAL_API_TC001(void) { TestMemInit(); uint8_t key[32] = {0}; uint8_t iv[12] = {0}; uint8_t aad[20] = {0}; uint8_t data[100] = {0}; uint32_t dataLen = sizeof(data); uint8_t out[100]; uint32_t outLen = sizeof(out); CRYPT_EAL_CipherCtx *ctx = CRYPT_EAL_CipherNewCtx(CRYPT_CIPHER_CHACHA20_POLY1305); ASSERT_TRUE(CRYPT_EAL_CipherInit(ctx, key, sizeof(key), iv, sizeof(iv), true) == CRYPT_SUCCESS); ASSERT_TRUE(CRYPT_EAL_CipherCtrl(ctx, CRYPT_CTRL_SET_AAD, aad, sizeof(aad)) == CRYPT_SUCCESS); ASSERT_TRUE(CRYPT_EAL_CipherUpdate(ctx, data, dataLen, out, &outLen) == CRYPT_SUCCESS); outLen = sizeof(out); ASSERT_TRUE(CRYPT_EAL_CipherFinal(ctx, out, &outLen) != CRYPT_SUCCESS); EXIT: CRYPT_EAL_CipherFreeCtx(ctx); } /* END_CASE */ /** * @test SDV_CRYPTO_CHACHA20POLY1305_SETPADDING_API_TC001 * @title Invalid Algorithms to call set padding Test * @precon Registering memory-related functions. * @brief * 1.Create the context ctx. * 2.Call the Init interface. All parameters are normal. Expected result 1 is obtained. * 3.Call the Ctrl interface to set aad. All parameters are normal. Expected result 2 is obtained. * 4.Call the Getpadding interface. Expected result 3 is obtained. * @expect * 1.Success. Return CRYPT_SUCCESS. * 2.Success. Return CRYPT_SUCCESS. * 3.Failed. The algorithm is not supported. */ /* BEGIN_CASE */ void SDV_CRYPTO_CHACHA20POLY1305_SETPADDING_API_TC001(void) { TestMemInit(); uint8_t key[32] = {0}; uint8_t iv[12] = {0}; uint8_t aad[20] = {0}; CRYPT_EAL_CipherCtx *ctx = CRYPT_EAL_CipherNewCtx(CRYPT_CIPHER_CHACHA20_POLY1305); ASSERT_TRUE(CRYPT_EAL_CipherInit(ctx, key, sizeof(key), iv, sizeof(iv), true) == CRYPT_SUCCESS); ASSERT_TRUE(CRYPT_EAL_CipherCtrl(ctx, CRYPT_CTRL_SET_AAD, aad, sizeof(aad)) == CRYPT_SUCCESS); ASSERT_TRUE(CRYPT_EAL_CipherSetPadding(ctx, CRYPT_PADDING_ZEROS) != CRYPT_SUCCESS); EXIT: CRYPT_EAL_CipherFreeCtx(ctx); } /* END_CASE */ /** * @test SDV_CRYPTO_CHACHA20POLY1305_GETPADDING_API_TC001 * @title Invalid Algorithms to call get padding Test * @precon Registering memory-related functions. * @brief * 1.Create the context ctx. * 2.Call the Init interface. All parameters are normal. Expected result 1 is obtained. * 3.Call the Ctrl interface to set aad. All parameters are normal. Expected result 2 is obtained. * 4.Call the Setpadding interface. Expected result 3 is obtained. * @expect * 1.Success. Return CRYPT_SUCCESS. * 2.Success. Return CRYPT_SUCCESS. * 3.Failed. The algorithm is not supported. */ /* BEGIN_CASE */ void SDV_CRYPTO_CHACHA20POLY1305_GETPADDING_API_TC001(void) { TestMemInit(); uint8_t key[32] = {0}; uint8_t iv[12] = {0}; uint8_t aad[20] = {0}; CRYPT_EAL_CipherCtx *ctx = CRYPT_EAL_CipherNewCtx(CRYPT_CIPHER_CHACHA20_POLY1305); ASSERT_TRUE(CRYPT_EAL_CipherInit(ctx, key, sizeof(key), iv, sizeof(iv), true) == CRYPT_SUCCESS); ASSERT_TRUE(CRYPT_EAL_CipherCtrl(ctx, CRYPT_CTRL_SET_AAD, aad, sizeof(aad)) == CRYPT_SUCCESS); ASSERT_TRUE(CRYPT_EAL_CipherGetPadding(ctx) == CRYPT_PADDING_MAX_COUNT); EXIT: CRYPT_EAL_CipherFreeCtx(ctx); } /* END_CASE */ /** * @test SDV_CRYPTO_CHACHA20POLY1305_UPDATE_FUNC_TC001 * @title Encryption and decryption Test * @precon Registering memory-related functions. * @brief * 1.Create the context ctx. Expected result 1 is obtained. * 2.Call the Init interface and set to encrypt. Expected result 2 is obtained. * 3.Call the Ctrl interface to set aad. All parameters are normal. Expected result 3 is obtained. * 4.Call the Update interface to encrypt data. Expected result 4 is obtained. * 5.Call the Ctrl interface to obtain the tag and compare with test vector. Expected result 5 is obtained. * 6.Call the deinit interface to deinitialize the ctx. * 7.Call the Init interface and set to decrypt. Expected result 6 is obtained. * 8.Call the Ctrl interface to set aad. All parameters are normal. Expected result 7 is obtained. * 9.Call the Update interface to decrypt data. Expected result 8 is obtained. * 10.Call the Ctrl interface to obtain the tag and compare with test vector. Expected result 9 is obtained. * @expect * 1.The creation is successful and the ctx is not empty. * 2.The init is successful and return CRYPT_SUCCESS. * 3.Succeeded in setting the AAD. * 4.The encryption is successful and consistent with expected vector. * 5.Tag is consistent with expected vector. * 6.The init is successful and return CRYPT_SUCCESS. * 7.Succeeded in setting the AAD. * 8.The decryption is successful and consistent with origin plain data. * 9.Tag is consistent with expected vector. */ /* BEGIN_CASE */ void SDV_CRYPTO_CHACHA20POLY1305_UPDATE_FUNC_TC001(Hex *key, Hex *iv, Hex *aad, Hex *data, Hex *cipher, Hex *tag) { TestMemInit(); uint8_t outTag[16]; uint8_t out[300]; uint32_t tagLen = tag->len; uint32_t outLen = sizeof(out); CRYPT_EAL_CipherCtx *ctx = CRYPT_EAL_CipherNewCtx(CRYPT_CIPHER_CHACHA20_POLY1305); ASSERT_TRUE(ctx != NULL); ASSERT_TRUE(CRYPT_EAL_CipherInit(ctx, key->x, key->len, iv->x, iv->len, true) == CRYPT_SUCCESS); ASSERT_TRUE(CRYPT_EAL_CipherCtrl(ctx, CRYPT_CTRL_SET_AAD, aad->x, aad->len) == CRYPT_SUCCESS); ASSERT_TRUE(CRYPT_EAL_CipherUpdate(ctx, data->x, data->len, out, &outLen) == CRYPT_SUCCESS); ASSERT_TRUE(CRYPT_EAL_CipherCtrl(ctx, CRYPT_CTRL_GET_TAG, (uint8_t *)outTag, tagLen) == CRYPT_SUCCESS); ASSERT_TRUE(outLen == cipher->len); ASSERT_TRUE(memcmp(out, cipher->x, cipher->len) == 0); ASSERT_TRUE(memcmp(outTag, tag->x, tag->len) == 0); CRYPT_EAL_CipherDeinit(ctx); ASSERT_TRUE(CRYPT_EAL_CipherInit(ctx, key->x, key->len, iv->x, iv->len, false) == CRYPT_SUCCESS); ASSERT_TRUE(CRYPT_EAL_CipherCtrl(ctx, CRYPT_CTRL_SET_AAD, aad->x, aad->len) == CRYPT_SUCCESS); outLen = sizeof(out); ASSERT_TRUE(CRYPT_EAL_CipherUpdate(ctx, cipher->x, cipher->len, (uint8_t *)out, &outLen) == CRYPT_SUCCESS); ASSERT_TRUE(CRYPT_EAL_CipherCtrl(ctx, CRYPT_CTRL_GET_TAG, (uint8_t *)outTag, tagLen) == CRYPT_SUCCESS); ASSERT_TRUE(outLen == data->len); ASSERT_TRUE(memcmp(out, data->x, data->len) == 0); ASSERT_TRUE(memcmp(outTag, tag->x, tag->len) == 0); EXIT: CRYPT_EAL_CipherFreeCtx(ctx); } /* END_CASE */ /** * @test SDV_CRYPTO_CHACHA20POLY1305_UPDATE_FUNC_TC002 * @title Multi segment encryption and decryption * @precon Registering memory-related functions. * @brief * 1.Create the context ctx. Expected result 1 is obtained. * 2.Call the Init interface and set to encrypt. Expected result 2 is obtained. * 3.Call the Ctrl interface to set aad. All parameters are normal. Expected result 3 is obtained. * 4.Call the Update interface to encrypt partial data. Expected result 4 is obtained. * 5.Call the Update interface to encrypt remaining data. Expected result 5 is obtained. * 6.Compare the ciphertext with the test vector. Expected result 6 is obtained. * 7.Call the Ctrl interface to obtain the tag and compare with test vector. Expected result 7 is obtained. * 8.Call the deinit interface to deinitialize the ctx. * 9.Call the Init interface and set to decrypt. Expected result 8 is obtained. * 10.Call the Ctrl interface to set aad. All parameters are normal. Expected result 9 is obtained. * 11.Call the Update interface to decrypt partial data. Expected result 10 is obtained. * 12.all the Update interface to decrypt remaining data. Expected result 11 is obtained. * 13.Compare the plaintext with the test vector. Expected result 12 is obtained. * 14.Call the Ctrl interface to obtain the tag and compare with test vector. Expected result 13 is obtained. * @expect * 1.The creation is successful and the ctx is not empty. * 2.The init is successful and return CRYPT_SUCCESS. * 3.Succeeded in setting the AAD. * 4.The encryption is successful. * 5.The encryption is successful. * 6.Ciphertext is consistent with expected vector. * 7.Tag is consistent with expected vector. * 8.The init is successful and return CRYPT_SUCCESS. * 9.Succeeded in setting the AAD. * 10.The decryption is successful. * 11.The decryption is successful. * 12.Decryption result is consistent with origin plain data. * 13.Tag is consistent with expected vector. */ /* BEGIN_CASE */ void SDV_CRYPTO_CHACHA20POLY1305_UPDATE_FUNC_TC002(Hex *key, Hex *iv, Hex *aad, Hex *data, Hex *cipher, Hex *tag) { TestMemInit(); uint8_t outTag[16]; uint8_t out[300]; uint32_t tagLen = tag->len; uint32_t first = data->len / 2; uint32_t outLen; CRYPT_EAL_CipherCtx *ctx = CRYPT_EAL_CipherNewCtx(CRYPT_CIPHER_CHACHA20_POLY1305); ASSERT_TRUE(ctx != NULL); ASSERT_TRUE(CRYPT_EAL_CipherInit(ctx, key->x, key->len, iv->x, iv->len, true) == CRYPT_SUCCESS); ASSERT_TRUE(CRYPT_EAL_CipherCtrl(ctx, CRYPT_CTRL_SET_AAD, aad->x, aad->len) == CRYPT_SUCCESS); outLen = first; ASSERT_TRUE(CRYPT_EAL_CipherUpdate(ctx, data->x, first, (uint8_t *)out, &outLen) == CRYPT_SUCCESS); outLen = data->len - first; ASSERT_TRUE(CRYPT_EAL_CipherUpdate(ctx, data->x + first, data->len - first, out + first, &outLen) == CRYPT_SUCCESS); ASSERT_TRUE(CRYPT_EAL_CipherCtrl(ctx, CRYPT_CTRL_GET_TAG, (uint8_t *)outTag, tagLen) == CRYPT_SUCCESS); ASSERT_TRUE(memcmp(out, cipher->x, cipher->len) == 0); ASSERT_TRUE(memcmp(outTag, tag->x, tag->len) == 0); CRYPT_EAL_CipherDeinit(ctx); outLen = first; ASSERT_TRUE(CRYPT_EAL_CipherInit(ctx, key->x, key->len, iv->x, iv->len, false) == CRYPT_SUCCESS); ASSERT_TRUE(CRYPT_EAL_CipherCtrl(ctx, CRYPT_CTRL_SET_AAD, aad->x, aad->len) == CRYPT_SUCCESS); ASSERT_TRUE(CRYPT_EAL_CipherUpdate(ctx, cipher->x, first, (uint8_t *)out, &outLen) == CRYPT_SUCCESS); outLen = cipher->len - first; ASSERT_TRUE(CRYPT_EAL_CipherUpdate(ctx, cipher->x + first, cipher->len - first, out + first, &outLen) == CRYPT_SUCCESS); ASSERT_TRUE(CRYPT_EAL_CipherCtrl(ctx, CRYPT_CTRL_GET_TAG, (uint8_t *)outTag, tagLen) == CRYPT_SUCCESS); ASSERT_TRUE(memcmp(out, data->x, data->len) == 0); ASSERT_TRUE(memcmp(outTag, tag->x, tag->len) == 0); EXIT: CRYPT_EAL_CipherFreeCtx(ctx); } /* END_CASE */ /** * @test SDV_CRYPTO_CHACHA20POLY1305_UPDATE_FUNC_TC003 * @title Encryption and decryption with reinitialization Test * @precon Registering memory-related functions. * @brief * 1.Create the context ctx. Expected result 1 is obtained. * 2.Call the init interface to set to encrypt with the test vector key and non-vector IV. Expected result 2 is obtained. * 3.Call the Ctrl interface to set non-vector AAD. Expected result 3 is obtained. * 4.Call the Reinit interface with the test vector IV. Expected result 4 is obtained. * 5.Call the Ctrl interface to set the test vector AAD. Expected result 5 is obtained. * 6.Call the Update interface to encrypt data. Expected result 6 is obtained. * 7.Compare the ciphertext with the test vector. Expected result 7 is obtained. * 8.Call the Ctrl interface to obtain the tag and compare with test vector. Expected result 8 is obtained. * @expect * 1.The creation is successful and the ctx is not empty. * 2.The init is successful and return CRYPT_SUCCESS. * 3.Succeeded in setting the AAD. * 4.The reinitialization is successful. * 5.Succeeded in setting the AAD. * 6.The encryption is successful. * 7.Ciphertext is consistent with expected vector. * 8.Tag is consistent with expected vector. */ /* BEGIN_CASE */ void SDV_CRYPTO_CHACHA20POLY1305_UPDATE_FUNC_TC003(Hex *key, Hex *iv, Hex *aad, Hex *data, Hex *cipher, Hex *tag) { TestMemInit(); uint8_t outTag[16]; uint8_t out[300]; uint8_t badIv[12] = {0}; uint8_t badAad[30] = {0}; uint32_t tagLen = tag->len; uint32_t outLen = sizeof(out); CRYPT_EAL_CipherCtx *ctx = CRYPT_EAL_CipherNewCtx(CRYPT_CIPHER_CHACHA20_POLY1305); ASSERT_TRUE(ctx != NULL); ASSERT_TRUE(CRYPT_EAL_CipherInit(ctx, key->x, key->len, badIv, sizeof(badIv), true) == CRYPT_SUCCESS); ASSERT_TRUE(CRYPT_EAL_CipherCtrl(ctx, CRYPT_CTRL_SET_AAD, badAad, sizeof(badAad)) == CRYPT_SUCCESS); ASSERT_TRUE(CRYPT_EAL_CipherReinit(ctx, iv->x, iv->len) == CRYPT_SUCCESS); ASSERT_TRUE(CRYPT_EAL_CipherCtrl(ctx, CRYPT_CTRL_SET_AAD, aad->x, aad->len) == CRYPT_SUCCESS); ASSERT_TRUE(CRYPT_EAL_CipherUpdate(ctx, data->x, data->len, out, &outLen) == CRYPT_SUCCESS); ASSERT_TRUE(CRYPT_EAL_CipherCtrl(ctx, CRYPT_CTRL_GET_TAG, (uint8_t *)outTag, tagLen) == CRYPT_SUCCESS); ASSERT_TRUE(outLen == cipher->len); ASSERT_TRUE(memcmp(out, cipher->x, cipher->len) == 0); ASSERT_TRUE(memcmp(outTag, tag->x, tag->len) == 0); EXIT: CRYPT_EAL_CipherFreeCtx(ctx); } /* END_CASE */ /* * @test SDV_CRYPTO_CHACHA20POLY1305_UPDATE_FUNC_TC004 * @title Repeated init Test * @precon Registering memory-related functions. * @brief * 1.Create the context ctx. Expected result 1 is obtained. * 2.Call the init interface to set to encrypt with the non-vector key and non-vector IV. Expected result 2 is obtained. * 3.Call the Ctrl interface to set non-vector AAD. Expected result 3 is obtained. * 4.Call the init interface to set to encrypt with the test vector key and IV. Expected result 4 is obtained. * 5.Call the Ctrl interface to set the test vector AAD. Expected result 5 is obtained. * 6.Call the Update interface to encrypt data. Expected result 6 is obtained. * 7.Compare the ciphertext with the test vector. Expected result 7 is obtained. * 8.Call the Ctrl interface to obtain the tag and compare with test vector. Expected result 8 is obtained. * @expect * 1.The creation is successful and the ctx is not empty. * 2.The init is successful and return CRYPT_SUCCESS. * 3.Succeeded in setting the AAD. * 4.The init is successful. * 5.Succeeded in setting the AAD. * 6.The encryption is successful. * 7.Ciphertext is consistent with expected vector. * 8.Tag is consistent with expected vector. */ /* BEGIN_CASE */ void SDV_CRYPTO_CHACHA20POLY1305_UPDATE_FUNC_TC004(Hex *key, Hex *iv, Hex *aad, Hex *data, Hex *cipher, Hex *tag) { TestMemInit(); uint8_t outTag[16]; uint8_t out[300]; uint8_t badIv[12] = {0}; uint8_t badAad[30] = {0}; uint8_t badKey[32] = {0}; uint32_t tagLen = tag->len; uint32_t outLen = sizeof(out); CRYPT_EAL_CipherCtx *ctx = CRYPT_EAL_CipherNewCtx(CRYPT_CIPHER_CHACHA20_POLY1305); ASSERT_TRUE(ctx != NULL); ASSERT_TRUE(CRYPT_EAL_CipherInit(ctx, badKey, sizeof(badKey), badIv, sizeof(badIv), true) == CRYPT_SUCCESS); ASSERT_TRUE(CRYPT_EAL_CipherCtrl(ctx, CRYPT_CTRL_SET_AAD, badAad, sizeof(badAad)) == CRYPT_SUCCESS); ASSERT_TRUE(CRYPT_EAL_CipherInit(ctx, key->x, key->len, iv->x, iv->len, true) == CRYPT_SUCCESS); ASSERT_TRUE(CRYPT_EAL_CipherCtrl(ctx, CRYPT_CTRL_SET_AAD, aad->x, aad->len) == CRYPT_SUCCESS); ASSERT_TRUE(CRYPT_EAL_CipherUpdate(ctx, data->x, data->len, out, &outLen) == CRYPT_SUCCESS); ASSERT_TRUE(CRYPT_EAL_CipherCtrl(ctx, CRYPT_CTRL_GET_TAG, (uint8_t *)outTag, tagLen) == CRYPT_SUCCESS); ASSERT_TRUE(outLen == cipher->len); ASSERT_TRUE(memcmp(out, cipher->x, cipher->len) == 0); ASSERT_TRUE(memcmp(outTag, tag->x, tag->len) == 0); EXIT: CRYPT_EAL_CipherFreeCtx(ctx); } /* END_CASE */ /** * @test SDV_CRYPTO_CHACHA20POLY1305_UPDATE_FUNC_TC005 * @title No message scenario Test * @precon Registering memory-related functions. * @brief * 1.Create the context ctx. Expected result 1 is obtained. * 2.Call the init interface to set to encrypt with the test vector key and IV. Expected result 2 is obtained. * 3.Call the Ctrl interface to set AAD. Expected result 3 is obtained. * 4.Call the Ctrl interface to obtain the tag and compare with test vector. Expected result 4 is obtained. * @expect * 1.The creation is successful and the ctx is not empty. * 2.The init is successful and return CRYPT_SUCCESS. * 3.Succeeded in setting the AAD. * 4.Tag is consistent with expected vector. */ /* BEGIN_CASE */ void SDV_CRYPTO_CHACHA20POLY1305_UPDATE_FUNC_TC005(Hex *key, Hex *iv, Hex *aad, Hex *tag) { TestMemInit(); uint8_t outTag[16]; uint32_t tagLen = tag->len; CRYPT_EAL_CipherCtx *ctx = CRYPT_EAL_CipherNewCtx(CRYPT_CIPHER_CHACHA20_POLY1305); ASSERT_TRUE(ctx != NULL); ASSERT_TRUE(CRYPT_EAL_CipherInit(ctx, key->x, key->len, iv->x, iv->len, true) == CRYPT_SUCCESS); ASSERT_TRUE(CRYPT_EAL_CipherCtrl(ctx, CRYPT_CTRL_SET_AAD, aad->x, aad->len) == CRYPT_SUCCESS); ASSERT_TRUE(CRYPT_EAL_CipherCtrl(ctx, CRYPT_CTRL_GET_TAG, (uint8_t *)outTag, tagLen) == CRYPT_SUCCESS); ASSERT_COMPARE("tag equal", outTag, tagLen, tag->x, tag->len); EXIT: CRYPT_EAL_CipherFreeCtx(ctx); } /* END_CASE */ /** * @test SDV_CRYPTO_CHACHA20POLY1305_UPDATE_FUNC_TC006 * @title Obtaining tag repeatedly Test * @precon Registering memory-related functions. * @brief * 1.Create the context ctx. Expected result 1 is obtained. * 2.Call the init interface to set to encrypt. Expected result 2 is obtained. * 3.Call the Ctrl interface to set AAD. Expected result 3 is obtained. * 4.Call the Update interface to encrypt data. Expected result 4 is obtained. * 5.Compare the ciphertext with the test vector. Expected result 5 is obtained. * 6.Call the Ctrl interface to obtain the tag and compare with test vector. Expected result 6 is obtained. * 7.Call the Ctrl interface again to obtain the tag and compare with test vector. Expected result 7 is obtained. * @expect * 1.The creation is successful and the ctx is not empty. * 2.The init is successful and return CRYPT_SUCCESS. * 3.Succeeded in setting the AAD. * 4.The encryption is successful. * 5.Ciphertext is consistent with expected vector. * 6.Tag is consistent with expected vector. * 7.Failed to obtain the tag for the second time. */ /* BEGIN_CASE */ void SDV_CRYPTO_CHACHA20POLY1305_UPDATE_FUNC_TC006(Hex *key, Hex *iv, Hex *aad, Hex *data, Hex *cipher, Hex *tag) { TestMemInit(); uint8_t outTag[16]; uint8_t out[300]; uint32_t tagLen = tag->len; uint32_t outLen = sizeof(out); CRYPT_EAL_CipherCtx *ctx = CRYPT_EAL_CipherNewCtx(CRYPT_CIPHER_CHACHA20_POLY1305); ASSERT_TRUE(ctx != NULL); ASSERT_TRUE(CRYPT_EAL_CipherInit(ctx, key->x, key->len, iv->x, iv->len, true) == CRYPT_SUCCESS); ASSERT_TRUE(CRYPT_EAL_CipherCtrl(ctx, CRYPT_CTRL_SET_AAD, aad->x, aad->len) == CRYPT_SUCCESS); ASSERT_TRUE(CRYPT_EAL_CipherUpdate(ctx, data->x, data->len, out, &outLen) == CRYPT_SUCCESS); ASSERT_TRUE(CRYPT_EAL_CipherCtrl(ctx, CRYPT_CTRL_GET_TAG, (uint8_t *)outTag, tagLen) == CRYPT_SUCCESS); ASSERT_TRUE(outLen == cipher->len); ASSERT_TRUE(memcmp(out, cipher->x, cipher->len) == 0); ASSERT_TRUE(memcmp(outTag, tag->x, tag->len) == 0); ASSERT_EQ(CRYPT_EAL_CipherCtrl(ctx, CRYPT_CTRL_GET_TAG, (uint8_t *)outTag, tagLen), CRYPT_EAL_ERR_STATE); EXIT: CRYPT_EAL_CipherFreeCtx(ctx); } /* END_CASE */ /** * @test SDV_CRYPTO_CHACHA20POLY1305_UPDATE_FUNC_TC007 * @title Memory overlap in plaintext and ciphertext Test * @precon Registering memory-related functions. * @brief * 1.Create the context ctx. Expected result 1 is obtained. * 2.Call the init interface to set to encrypt. Expected result 2 is obtained. * 3.Call the Ctrl interface to set AAD. Expected result 3 is obtained. * 4.Call the Update interface to encrypt data. The plaintext and ciphertext memory completely overlap. Expected result 4 is obtained. * 5.Compare the ciphertext with the test vector. Expected result 5 is obtained. * 6.Call the Ctrl interface to obtain the tag and compare with test vector. Expected result 6 is obtained. * @expect * 1.The creation is successful and the ctx is not empty. * 2.The init is successful and return CRYPT_SUCCESS. * 3.Succeeded in setting the AAD. * 4.The encryption is successful. * 5.Ciphertext is consistent with expected vector. * 6.Tag is consistent with expected vector. */ /* BEGIN_CASE */ void SDV_CRYPTO_CHACHA20POLY1305_UPDATE_FUNC_TC007(Hex *key, Hex *iv, Hex *aad, Hex *data, Hex *cipher, Hex *tag) { TestMemInit(); uint8_t outTag[16]; uint8_t buf[300]; uint32_t tagLen = tag->len; uint32_t bufLen = sizeof(buf); CRYPT_EAL_CipherCtx *ctx = CRYPT_EAL_CipherNewCtx(CRYPT_CIPHER_CHACHA20_POLY1305); ASSERT_TRUE(ctx != NULL); ASSERT_TRUE(memcpy_s(buf, bufLen, data->x, data->len) == 0); ASSERT_TRUE(CRYPT_EAL_CipherInit(ctx, key->x, key->len, iv->x, iv->len, true) == CRYPT_SUCCESS); ASSERT_TRUE(CRYPT_EAL_CipherCtrl(ctx, CRYPT_CTRL_SET_AAD, aad->x, aad->len) == CRYPT_SUCCESS); ASSERT_TRUE(CRYPT_EAL_CipherUpdate(ctx, buf, data->len, buf, &bufLen) == CRYPT_SUCCESS); ASSERT_TRUE(CRYPT_EAL_CipherCtrl(ctx, CRYPT_CTRL_GET_TAG, (uint8_t *)outTag, tagLen) == CRYPT_SUCCESS); ASSERT_TRUE(bufLen == cipher->len); ASSERT_TRUE(memcmp(buf, cipher->x, cipher->len) == 0); ASSERT_TRUE(memcmp(outTag, tag->x, tag->len) == 0); EXIT: CRYPT_EAL_CipherFreeCtx(ctx); } /* END_CASE */ /** * @test SDV_CRYPTO_CHACHA20POLY1305_UPDATE_FUNC_TC008 * @title 64-bit IV encryption and decryption Test * @precon Registering memory-related functions. * @brief * 1.Create the context ctx. Expected result 1 is obtained. * 2.Call the init interface to set to encrypt. Expected result 2 is obtained. * 3.Call the Ctrl interface to set AAD. Expected result 3 is obtained. * 4.Call the Update interface to encrypt data. Expected result 4 is obtained. * 5.Call the Ctrl interface to obtain the tag and compare with test vector. Expected result 5 is obtained. * 6.Call the deinit interface to deinitialize the ctx. * 7.Call the init interface to set to decrypt. Expected result 6 is obtained. * 8.Call the Ctrl interface to set AAD. Expected result 7 is obtained. * 9.Call the Update interface to decrypt data. Expected result 8 is obtained. * 10.Compare the plaintext with the test vector. Expected result 9 is obtained. * 11.Call the Ctrl interface to obtain the tag and compare with encryption tag. Expected result 10 is obtained. * @expect * 1.The creation is successful and the ctx is not empty. * 2.The init is successful and return CRYPT_SUCCESS. * 3.Succeeded in setting the AAD. * 4.The encryption is successful. * 5.The getting tag is successful. * 6.The init is successful and return CRYPT_SUCCESS. * 7.Succeeded in setting the AAD. * 8.The decryption is successful. * 9.Decryption result is consistent with origin plaintext. * 10.Tag is consistent with expected value. */ /* BEGIN_CASE */ void SDV_CRYPTO_CHACHA20POLY1305_UPDATE_FUNC_TC008(Hex *key, Hex *aad, Hex *data) { TestMemInit(); uint8_t outTag1[16]; uint8_t outTag2[16]; uint8_t out[300]; const uint32_t tagLen = sizeof(outTag1); uint32_t outLen = sizeof(out); uint8_t iv[8]; (void)memset_s(iv, sizeof(iv), 'A', sizeof(iv)); CRYPT_EAL_CipherCtx *ctx = CRYPT_EAL_CipherNewCtx(CRYPT_CIPHER_CHACHA20_POLY1305); ASSERT_TRUE(ctx != NULL); ASSERT_TRUE(CRYPT_EAL_CipherInit(ctx, key->x, key->len, iv, sizeof(iv), true) == CRYPT_SUCCESS); ASSERT_TRUE(CRYPT_EAL_CipherCtrl(ctx, CRYPT_CTRL_SET_AAD, aad->x, aad->len) == CRYPT_SUCCESS); ASSERT_TRUE(CRYPT_EAL_CipherUpdate(ctx, data->x, data->len, out, &outLen) == CRYPT_SUCCESS); ASSERT_TRUE(CRYPT_EAL_CipherCtrl(ctx, CRYPT_CTRL_GET_TAG, (uint8_t *)outTag1, tagLen) == CRYPT_SUCCESS); CRYPT_EAL_CipherDeinit(ctx); ASSERT_TRUE(CRYPT_EAL_CipherInit(ctx, key->x, key->len, iv, sizeof(iv), false) == CRYPT_SUCCESS); ASSERT_TRUE(CRYPT_EAL_CipherCtrl(ctx, CRYPT_CTRL_SET_AAD, aad->x, aad->len) == CRYPT_SUCCESS); ASSERT_TRUE(CRYPT_EAL_CipherUpdate(ctx, out, outLen, out, &outLen) == CRYPT_SUCCESS); ASSERT_TRUE(CRYPT_EAL_CipherCtrl(ctx, CRYPT_CTRL_GET_TAG, (uint8_t *)outTag2, tagLen) == CRYPT_SUCCESS); ASSERT_TRUE(outLen == data->len); ASSERT_TRUE(memcmp(out, data->x, data->len) == 0); ASSERT_TRUE(memcmp(outTag1, outTag2, tagLen) == 0); EXIT: CRYPT_EAL_CipherFreeCtx(ctx); } /* END_CASE */ /** * @test SDV_CRYPTO_CHACHA20POLY1305_UPDATE_FUNC_TC009 * @title Invalid tag in the encryption and decryption Test * @precon Registering memory-related functions. * @brief * 1.Create the context ctx. Expected result 1 is obtained. * 2.Call the init interface to set to encrypt. Expected result 2 is obtained. * 3.Call the Ctrl interface to set AAD. Expected result 3 is obtained. * 4.Call the Update interface to encrypt data. Expected result 4 is obtained. * 5.Compare the ciphertext with the test vector. Expected result 5 is obtained. * 6.Call the Ctrl interface to obtain the tag and compare with test vector. Expected result 6 is obtained. * 7.Call the deinit interface to deinitialize the ctx. * 8.Call the init interface to set to decrypt. Expected result 7 is obtained. * 9.Call the Ctrl interface to set AAD. Expected result 8 is obtained. * 10.Call the Update interface to decrypt data. Expected result 9 is obtained. * 11.Compare the plaintext with the test vector. Expected result 10 is obtained. * 12.Call the Ctrl interface to obtain the tag and compare with test vector. Expected result 11 is obtained. * @expect * 1.The creation is successful and the ctx is not empty. * 2.The init is successful and return CRYPT_SUCCESS. * 3.Succeeded in setting the AAD. * 4.The encryption is successful. * 5.Ciphertext is consistent with expected vector. * 6.Tag is not consistent with expected vector. * 7.The init is successful and return CRYPT_SUCCESS. * 8.Succeeded in setting the AAD. * 9.The decryption is successful. * 10.Decryption result is consistent with origin plain data. * 11.Tag is not consistent with expected vector. */ /* BEGIN_CASE */ void SDV_CRYPTO_CHACHA20POLY1305_UPDATE_FUNC_TC009(Hex *key, Hex *iv, Hex *aad, Hex *data, Hex *cipher, Hex *tag) { TestMemInit(); uint8_t outTag[16]; uint8_t out[300]; uint32_t tagLen = tag->len; uint32_t outLen = sizeof(out); CRYPT_EAL_CipherCtx *ctx = CRYPT_EAL_CipherNewCtx(CRYPT_CIPHER_CHACHA20_POLY1305); ASSERT_TRUE(ctx != NULL); ASSERT_TRUE(CRYPT_EAL_CipherInit(ctx, key->x, key->len, iv->x, iv->len, true) == CRYPT_SUCCESS); ASSERT_TRUE(CRYPT_EAL_CipherCtrl(ctx, CRYPT_CTRL_SET_AAD, aad->x, aad->len) == CRYPT_SUCCESS); ASSERT_TRUE(CRYPT_EAL_CipherUpdate(ctx, data->x, data->len, out, &outLen) == CRYPT_SUCCESS); ASSERT_TRUE(CRYPT_EAL_CipherCtrl(ctx, CRYPT_CTRL_GET_TAG, (uint8_t *)outTag, tagLen) == CRYPT_SUCCESS); ASSERT_TRUE(outLen == cipher->len); ASSERT_TRUE(memcmp(out, cipher->x, cipher->len) == 0); ASSERT_TRUE(memcmp(outTag, tag->x, tag->len) != 0); CRYPT_EAL_CipherDeinit(ctx); ASSERT_TRUE(CRYPT_EAL_CipherInit(ctx, key->x, key->len, iv->x, iv->len, false) == CRYPT_SUCCESS); ASSERT_TRUE(CRYPT_EAL_CipherCtrl(ctx, CRYPT_CTRL_SET_AAD, aad->x, aad->len) == CRYPT_SUCCESS); outLen = sizeof(out); ASSERT_TRUE(CRYPT_EAL_CipherUpdate(ctx, cipher->x, cipher->len, (uint8_t *)out, &outLen) == CRYPT_SUCCESS); ASSERT_TRUE(CRYPT_EAL_CipherCtrl(ctx, CRYPT_CTRL_GET_TAG, (uint8_t *)outTag, tagLen) == CRYPT_SUCCESS); ASSERT_TRUE(outLen == data->len); ASSERT_TRUE(memcmp(out, data->x, data->len) == 0); ASSERT_TRUE(memcmp(outTag, tag->x, tag->len) != 0); EXIT: CRYPT_EAL_CipherFreeCtx(ctx); } /* END_CASE */ /** * @test SDV_CRYPTO_CHACHA20POLY1305_UPDATE_FUNC_TC002 * @title Encryption and decryption of multiple segments with different lengths Test * @precon Registering memory-related functions. * @brief * 1.Create the context ctx. Expected result 1 is obtained. * 2.Call the init interface to set to encrypt. Expected result 2 is obtained. * 3.Call the Ctrl interface to set AAD. Expected result 3 is obtained. * 4.Call the Update interface to encrypt data 1. Expected result 4 is obtained. * 5.Call the Update interface to encrypt data 2. Expected result 5 is obtained. * 6.Call the Update interface to encrypt data 3. Expected result 6 is obtained. * 7.Compare the ciphertext with the test vector. Expected result 7 is obtained. * 8.Call the Ctrl interface to obtain the tag and compare with test vector. Expected result 8 is obtained. * 9.Call the deinit interface to deinitialize the ctx. * 10.Call the init interface to set to decrypt. Expected result 9 is obtained. * 11.Call the Ctrl interface to set AAD. Expected result 10 is obtained. * 12.Call the Update interface to decrypt data 1. Expected result 11 is obtained. * 13.Call the Update interface to decrypt data 2. Expected result 12 is obtained. * 14.Call the Update interface to decrypt data 3. Expected result 13 is obtained. * 15.Compare the plaintext with the test vector. Expected result 14 is obtained. * 16.Call the Ctrl interface to obtain the tag and compare with test vector tag. Expected result 15 is obtained. * @expect * 1.The creation is successful and the ctx is not empty. * 2.The init is successful and return CRYPT_SUCCESS. * 3.Succeeded in setting the AAD. * 4.The encryption is successful. * 5.The encryption is successful. * 6.The encryption is successful. * 7.Ciphertext is consistent with expected vector. * 8.Tag is consistent with expected value. * 9.The init is successful and return CRYPT_SUCCESS. * 10.Succeeded in setting the AAD. * 11.The decryption is successful. * 12.The decryption is successful. * 13.The decryption is successful. * 14.Decryption result is consistent with origin plaintext. * 15.Tag is consistent with expected value. */ /* BEGIN_CASE */ void SDV_CRYPTO_CHACHA20POLY1305_UPDATE_FUNC_TC010(Hex *key, Hex *iv, Hex *aad, Hex *pt1, Hex *pt2, Hex *pt3, Hex *cipher, Hex *tag) { TestMemInit(); uint8_t outTag[16]; uint8_t out[300]; uint32_t tagLen = tag->len; uint32_t outLen; uint32_t totalLen = 0; CRYPT_EAL_CipherCtx *ctx = CRYPT_EAL_CipherNewCtx(CRYPT_CIPHER_CHACHA20_POLY1305); ASSERT_TRUE(ctx != NULL); ASSERT_TRUE(CRYPT_EAL_CipherInit(ctx, key->x, key->len, iv->x, iv->len, true) == CRYPT_SUCCESS); ASSERT_TRUE(CRYPT_EAL_CipherCtrl(ctx, CRYPT_CTRL_SET_AAD, aad->x, aad->len) == CRYPT_SUCCESS); outLen = sizeof(out); ASSERT_TRUE(CRYPT_EAL_CipherUpdate(ctx, pt1->x, pt1->len, (uint8_t *)out, &outLen) == CRYPT_SUCCESS); totalLen += outLen; outLen = sizeof(out) - pt1->len; ASSERT_TRUE(CRYPT_EAL_CipherUpdate(ctx, pt2->x, pt2->len, out + totalLen, &outLen) == CRYPT_SUCCESS); totalLen += outLen; outLen = sizeof(out) - pt1->len - pt2->len; ASSERT_TRUE(CRYPT_EAL_CipherUpdate(ctx, pt3->x, pt3->len, out + totalLen, &outLen) == CRYPT_SUCCESS); ASSERT_TRUE(CRYPT_EAL_CipherCtrl(ctx, CRYPT_CTRL_GET_TAG, (uint8_t *)outTag, tagLen) == CRYPT_SUCCESS); ASSERT_TRUE(memcmp(out, cipher->x, cipher->len) == 0); ASSERT_TRUE(memcmp(outTag, tag->x, tag->len) == 0); CRYPT_EAL_CipherDeinit(ctx); outLen = sizeof(out); ASSERT_TRUE(CRYPT_EAL_CipherInit(ctx, key->x, key->len, iv->x, iv->len, false) == CRYPT_SUCCESS); ASSERT_TRUE(CRYPT_EAL_CipherCtrl(ctx, CRYPT_CTRL_SET_AAD, aad->x, aad->len) == CRYPT_SUCCESS); ASSERT_TRUE(CRYPT_EAL_CipherUpdate(ctx, cipher->x, pt1->len, (uint8_t *)out, &outLen) == CRYPT_SUCCESS); outLen = cipher->len - pt1->len; ASSERT_TRUE(CRYPT_EAL_CipherUpdate(ctx, cipher->x + pt1->len, pt2->len, out + pt1->len, &outLen) == CRYPT_SUCCESS); outLen = cipher->len - pt1->len - pt2->len; ASSERT_TRUE(CRYPT_EAL_CipherUpdate(ctx, cipher->x + pt1->len + pt2->len, pt3->len, out + pt1->len + pt2->len, &outLen) == CRYPT_SUCCESS); ASSERT_TRUE(CRYPT_EAL_CipherCtrl(ctx, CRYPT_CTRL_GET_TAG, (uint8_t *)outTag, tagLen) == CRYPT_SUCCESS); ASSERT_TRUE(memcmp(out, pt1->x, pt1->len) == 0); ASSERT_TRUE(memcmp(out + pt1->len, pt2->x, pt2->len) == 0); ASSERT_TRUE(memcmp(out + pt1->len + pt2->len, pt3->x, pt3->len) == 0); ASSERT_TRUE(memcmp(outTag, tag->x, tag->len) == 0); EXIT: CRYPT_EAL_CipherFreeCtx(ctx); } /* END_CASE */
2301_79861745/bench_create
testcode/sdv/testcase/crypto/chacha-poly/test_suite_sdv_eal_chachapoly.c
C
unknown
53,845
/* * This file is part of the openHiTLS project. * * openHiTLS is licensed under the Mulan PSL v2. * You can use this software according to the terms and conditions of the Mulan PSL v2. * You may obtain a copy of Mulan PSL v2 at: * * http://license.coscl.org.cn/MulanPSL2 * * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, * EITHER EXPRESS 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 <limits.h> #include <pthread.h> #include "securec.h" #include "crypt_eal_mac.h" #include "crypt_errno.h" #include "bsl_sal.h" #define AES128_KEY_LEN 16 #define AES192_KEY_LEN 24 #define AES256_KEY_LEN 32 #define SM4_KEY_LEN 16 #define CMAC_MAC_AES_LEN 16 #define CMAC_MAC_LEN 16 uint32_t GetKeyLen(int algId) { switch (algId) { case CRYPT_MAC_CMAC_AES128: return AES128_KEY_LEN; case CRYPT_MAC_CMAC_AES192: return AES192_KEY_LEN; case CRYPT_MAC_CMAC_AES256: return AES256_KEY_LEN; case CRYPT_MAC_CMAC_SM4: return SM4_KEY_LEN; default: return 0; } } /* END_HEADER */ /* @ * @test SDV_CRYPT_EAL_CMAC_API_TC001 * @spec - * @title valid algorithm ID and invalid algorithm ID * @precon nan * @brief 1.Invoke the new interface with the input parameter CRYPT_MAC_CMAC_AES128. Expected result 1 is obtained. 2.Invoke the new interface with the input parameter CRYPT_MAC_CMAC_AES192,Expected result 2 is obtained. 3.Invoke the new interface with the input parameter CRYPT_MAC_CMAC_AES256,Expected result 3 is obtained. 4.Invoke the new interface with the input parameter CRYPT_MAC_MAX, Expected result 4 is obtained. * @expect 1.sucess 2.sucess 3.sucess 4.failed,return NULL * @prior Level 1 * @auto TRUE @ */ /* BEGIN_CASE */ void SDV_CRYPT_EAL_CMAC_API_TC001(void) { TestMemInit(); CRYPT_EAL_MacCtx *ctx = CRYPT_EAL_MacNewCtx(CRYPT_MAC_CMAC_AES128); ASSERT_TRUE(ctx != NULL); CRYPT_EAL_MacFreeCtx(ctx); ctx = CRYPT_EAL_MacNewCtx(CRYPT_MAC_CMAC_AES192); ASSERT_TRUE(ctx != NULL); CRYPT_EAL_MacFreeCtx(ctx); ctx = CRYPT_EAL_MacNewCtx(CRYPT_MAC_CMAC_AES256); ASSERT_TRUE(ctx != NULL); CRYPT_EAL_MacFreeCtx(ctx); ctx = CRYPT_EAL_MacNewCtx(CRYPT_MAC_CMAC_SM4); ASSERT_TRUE(ctx != NULL); EXIT: CRYPT_EAL_MacFreeCtx(ctx); } /* END_CASE */ /* @ * @test SDV_CRYPT_EAL_CMAC_API_TC002 * @spec - * @title init interface: valid input parameter, invalid input parameter * @precon nan * @brief 1.Invoke the new interface. Expected result 1 is obtained. 2.Invoke the init interface and set ctx to NULL. Expected result 2 is obtained. 3.Invoke the init interface and set key to NULL. Expected result 3 is obtained. 4.Invoke the init interface. Set the key to a value other than NULL and len to a value less than the specified key length. Expected result 4 is obtained. 5.Invoke the init interface and ensure that the input parameters are normal. Expected result 5 is obtained. 6.Invoke the init interface. The key is not NULL and len is greater than the specified key length. Expected result 6 is obtained. * @expect 1.new sucess,return CRYPT_EAL_MacCtx pointer 2.init failed, return CRYPT_NULL_INPUT 3.init failed, return CRYPT_NULL_INPUT 4.init failed, return CRYPT_AES_ERR_KEYLEN 5.init sucess, return CRYPT_SUCCESS 6.init failed, return CRYPT_AES_ERR_KEYLEN * @prior Level 1 * @auto TRUE @ */ /* BEGIN_CASE */ void SDV_CRYPT_EAL_CMAC_API_TC002(int algId) { if (IsCmacAlgDisabled(algId)) { SKIP_TEST(); } TestMemInit(); const uint32_t len = GetKeyLen(algId); uint8_t key[len]; CRYPT_EAL_MacCtx *ctx = CRYPT_EAL_MacNewCtx(algId); ASSERT_TRUE(ctx != NULL); int32_t ret; if (algId >= CRYPT_MAC_CMAC_AES128 && algId <= CRYPT_MAC_CMAC_AES256) { ret = CRYPT_AES_ERR_KEYLEN; } else if (algId == CRYPT_MAC_CMAC_SM4) { ret = CRYPT_SM4_ERR_KEY_LEN; } ASSERT_TRUE(CRYPT_EAL_MacInit(NULL, key, len) == CRYPT_NULL_INPUT); ASSERT_TRUE(CRYPT_EAL_MacInit(ctx, NULL, len) == CRYPT_NULL_INPUT); ASSERT_TRUE(CRYPT_EAL_MacInit(ctx, key, len - 1) == ret); ASSERT_TRUE(CRYPT_EAL_MacInit(ctx, key, len) == CRYPT_SUCCESS); ASSERT_TRUE(CRYPT_EAL_MacInit(ctx, key, len + 1) == ret); EXIT: CRYPT_EAL_MacFreeCtx(ctx); } /* END_CASE */ /* @ * @test SDV_CRYPT_EAL_CMAC_API_TC003 * @spec - * @title test ctx status * @precon nan * @brief 1.Invoke the new interface. Expected result 1 is obtained. 2.Invoke the init interface. Expected result 2 is obtained. 3.Invoke the init interface repeatedly. Expected result 3 is obtained. 4.Invoke the update interface. Expected result 4 is obtained. 5.Invoke the init interface. Expected result 5 is obtained. 6.Invoke the final interface. Expected result 6 is obtained. 7.Invoke the init interface. Expected result 7 is obtained. 8.Invoke the deinit interface. Expected result 8 is obtained. 9.Invoke the init interface. Expected result 9 is obtained. 10.Invoke the reinit interface. Expected result 10 is obtained. 11.Invoke the init interface. Expected result 11 is obtained. * @expect 1.new sucess, return CRYPT_EAL_MacCtx pointer 2.init sucess, return CRYPT_SUCCESS 3.init sucess, return CRYPT_SUCCESS 4.update sucess, return CRYPT_SUCCESS 5.init sucess, return CRYPT_SUCCESS 6.final sucess, return CRYPT_SUCCESS 7.init sucess, return CRYPT_SUCCESS 8.deinit sucess 9.init sucess, return CRYPT_SUCCESS 10.reinit sucess, return CRYPT_SUCCESS 11.init sucess, return CRYPT_SUCCESS * @prior Level 1 * @auto TRUE @ */ /* BEGIN_CASE */ void SDV_CRYPT_EAL_CMAC_API_TC003(int algId) { if (IsCmacAlgDisabled(algId)) { SKIP_TEST(); } TestMemInit(); const uint32_t keyLen = GetKeyLen(algId); uint8_t key[keyLen]; uint32_t macLen = TestGetMacLen(algId); uint8_t mac[macLen]; const uint32_t dataLen = TestGetMacLen(algId); uint8_t data[dataLen]; CRYPT_EAL_MacCtx *ctx = CRYPT_EAL_MacNewCtx(algId); ASSERT_TRUE(ctx != NULL); ASSERT_TRUE(CRYPT_EAL_MacInit(ctx, key, keyLen) == CRYPT_SUCCESS); ASSERT_TRUE(CRYPT_EAL_MacInit(ctx, key, keyLen) == CRYPT_SUCCESS); ASSERT_TRUE(CRYPT_EAL_MacUpdate(ctx, data, dataLen) == CRYPT_SUCCESS); ASSERT_TRUE(CRYPT_EAL_MacInit(ctx, key, keyLen) == CRYPT_SUCCESS); ASSERT_TRUE(CRYPT_EAL_MacFinal(ctx, mac, &macLen) == CRYPT_SUCCESS); ASSERT_TRUE(CRYPT_EAL_MacInit(ctx, key, keyLen) == CRYPT_SUCCESS); CRYPT_EAL_MacDeinit(ctx); ASSERT_TRUE(CRYPT_EAL_MacInit(ctx, key, keyLen) == CRYPT_SUCCESS); ASSERT_TRUE(CRYPT_EAL_MacReinit(ctx) == CRYPT_SUCCESS); ASSERT_TRUE(CRYPT_EAL_MacInit(ctx, key, keyLen) == CRYPT_SUCCESS); EXIT: CRYPT_EAL_MacFreeCtx(ctx); } /* END_CASE */ /* @ * @test SDV_CRYPT_EAL_CMAC_API_TC004 * @spec - * @title update: valid input parameter, invalid input parameter * @precon nan * @brief 1.Invoke the new interface. Expected result 1 is obtained. 2.Invoke the init interface. Expected result 2 is obtained. 3.Invoke the update interface and set ctx to NULL. Expected result 3 is obtained. 4.Invoke the update interface. Set in to NULL and len to a value other than 0. Expected result 4 is obtained. 5.Invoke the update interface. Set in to a value other than NULL and len to 0. Expected result 5 is obtained. 6.Invoke the update interface. Set in to NULL and len to 0. Expected result 6 is obtained. 7.Invoke the update interface and ensure that the input parameters are normal. Expected result 7 is obtained. * @expect 1.new sucess,return CRYPT_EAL_MacCtx pointer 2.init sucess,return CRYPT_SUCCESS 3.update failed,return CRYPT_NULL_INPUT 4.update failed,return CRYPT_NULL_INPUT 5.update sucess,return CRYPT_SUCCESS 6.update sucess,return CRYPT_SUCCESS 7.update sucess,return CRYPT_SUCCESS * @prior Level 1 * @auto TRUE @ */ /* BEGIN_CASE */ void SDV_CRYPT_EAL_CMAC_API_TC004(int algId) { if (IsCmacAlgDisabled(algId)) { SKIP_TEST(); } TestMemInit(); const uint32_t len = GetKeyLen(algId); uint8_t key[len]; const uint32_t dataLen = GetKeyLen(algId); uint8_t data[dataLen]; CRYPT_EAL_MacCtx *ctx = CRYPT_EAL_MacNewCtx(algId); ASSERT_TRUE(ctx != NULL); ASSERT_TRUE(CRYPT_EAL_MacInit(ctx, key, len) == CRYPT_SUCCESS); ASSERT_TRUE(CRYPT_EAL_MacUpdate(NULL, data, dataLen) == CRYPT_NULL_INPUT); ASSERT_TRUE(CRYPT_EAL_MacUpdate(ctx, NULL, dataLen) == CRYPT_NULL_INPUT); ASSERT_TRUE(CRYPT_EAL_MacUpdate(ctx, data, 0) == CRYPT_SUCCESS); ASSERT_TRUE(CRYPT_EAL_MacUpdate(ctx, NULL, 0) == CRYPT_SUCCESS); ASSERT_TRUE(CRYPT_EAL_MacUpdate(ctx, data, dataLen) == CRYPT_SUCCESS); EXIT: CRYPT_EAL_MacFreeCtx(ctx); } /* END_CASE */ /* @ * @test SDV_CRYPT_EAL_CMAC_API_TC005 * @spec - * @precon nan * @brief 1.Invoke the new interface. Expected result 1 is obtained. 2.Invoke the update interface. Expected result 2 is obtained. 3.Invoke the new interface. Expected result 3 is obtained. 4.Invoke the update interface. Expected result 4 is obtained. 5.Invoke the final interface. Expected result 5 is obtained. 6.Invoke the new interface. Expected result 6 is obtained. 7.Invoke the new interface. Expected result 7 is obtained. 8.Invoke the deinit interface. Expected result 8 is obtained. 9.Invoke the new interface. Expected result 9 is obtained. 10.Invoke the final interface. Expected result 10 is obtained. 11.Invoke the new interface. Expected result 11 is obtained. 12.Invoke the new interface. Expected result 12 is obtained. 13.Invoke the reinit interface. Expected result 13 is obtained. 14.Invoke the new interface. Expected result 14 is obtained. 15.repeat invoke the new interface. Expected result 15 is obtained. * @expect 1.new sucess,return CRYPT_EAL_MacCtx pointer 2.update failed,return RYPT_EAL_ERR_STATE 3.init sucess,return CRYPT_SUCCESS 4.update sucess,return CRYPT_SUCCESS 5.final sucess,return CRYPT_SUCCESS 6.update failed,return CRYPT_EAL_ERR_STATE 7.update failed,return CRYPT_EAL_ERR_STATE 8. 9.update failed,return CRYPT_EAL_ERR_STATE 10.final sucess,return CRYPT_EAL_ERR_STATE 11.init sucess,return CRYPT_SUCCESS 12.update sucess,return CRYPT_SUCCESS 13.reinit sucess,return CRYPT_SUCCESS 14.update sucess,return CRYPT_SUCCESS 15.update sucess,return CRYPT_SUCCESS * @prior Level 1 * @auto TRUE @ */ /* BEGIN_CASE */ void SDV_CRYPT_EAL_CMAC_API_TC005(int algId) { if (IsCmacAlgDisabled(algId)) { SKIP_TEST(); } TestMemInit(); const uint32_t len = GetKeyLen(algId); uint8_t key[len]; uint32_t macLen = TestGetMacLen(algId); uint8_t mac[macLen]; const uint32_t dataLen = GetKeyLen(algId); uint8_t data[dataLen]; CRYPT_EAL_MacCtx *ctx = CRYPT_EAL_MacNewCtx(algId); ASSERT_TRUE(ctx != NULL); ASSERT_TRUE(CRYPT_EAL_MacUpdate(ctx, data, dataLen) == CRYPT_EAL_ERR_STATE); ASSERT_TRUE(CRYPT_EAL_MacInit(ctx, key, len) == CRYPT_SUCCESS); ASSERT_TRUE(CRYPT_EAL_MacUpdate(ctx, data, dataLen) == CRYPT_SUCCESS); ASSERT_TRUE(CRYPT_EAL_MacFinal(ctx, mac, &macLen) == CRYPT_SUCCESS); ASSERT_TRUE(CRYPT_EAL_MacUpdate(ctx, data, dataLen) == CRYPT_EAL_ERR_STATE); ASSERT_TRUE(CRYPT_EAL_MacUpdate(ctx, data, dataLen) == CRYPT_EAL_ERR_STATE); CRYPT_EAL_MacDeinit(ctx); ASSERT_TRUE(CRYPT_EAL_MacUpdate(ctx, data, dataLen) == CRYPT_EAL_ERR_STATE); ASSERT_TRUE(CRYPT_EAL_MacFinal(ctx, mac, &macLen) == CRYPT_EAL_ERR_STATE); ASSERT_TRUE(CRYPT_EAL_MacInit(ctx, key, len) == CRYPT_SUCCESS); ASSERT_TRUE(CRYPT_EAL_MacUpdate(ctx, data, dataLen) == CRYPT_SUCCESS); ASSERT_TRUE(CRYPT_EAL_MacReinit(ctx) == CRYPT_SUCCESS); ASSERT_TRUE(CRYPT_EAL_MacUpdate(ctx, data, dataLen) == CRYPT_SUCCESS); ASSERT_TRUE(CRYPT_EAL_MacUpdate(ctx, data, dataLen) == CRYPT_SUCCESS); EXIT: CRYPT_EAL_MacFreeCtx(ctx); } /* END_CASE */ /* @ * @test SDV_CRYPT_EAL_CMAC_API_TC006 * @spec - * @title finsl : valid input parameter, invalid input parameter * @precon nan * @brief 1.调用new接口,有预期结果1 2.调用init接口,有预期结果2 3.调用final接口,ctx为NULL,有预期结果3 4.调用final接口,out为NULL,有预期结果4 5.调用final接口,len为NULL,有预期结果5 6.调用final接口,len数值小于mac数据长度,有预期结果6 7.调用final接口,len数值大于mac数据长度,有预期结果7 8.调用init接口,有预期结果8 9.调用final接口,正常入参,有预期结果9 * @expect 1.new sucess,return CRYPT_EAL_MacCtx pointer 2.init sucess,return CRYPT_SUCCESS 3.final failed,return CRYPT_NULL_INPUT 4.final failed,return CRYPT_NULL_INPUT 5.final failed,return CRYPT_NULL_INPUT 6.final failed,return CRYPT_CMAC_OUT_BUFF_LEN_NOT_ENOUGH 7.final sucess,return CRYPT_SUCCESS 8.init sucess,return CRYPT_SUCCESS 9.final sucess,return CRYPT_SUCCESS * @prior Level 1 * @auto TRUE @ */ /* BEGIN_CASE */ void SDV_CRYPT_EAL_CMAC_API_TC006(int algId) { if (IsCmacAlgDisabled(algId)) { SKIP_TEST(); } TestMemInit(); const uint32_t len = GetKeyLen(algId); uint8_t key[len]; uint32_t macLen = TestGetMacLen(algId); uint8_t mac[macLen]; CRYPT_EAL_MacCtx *ctx = CRYPT_EAL_MacNewCtx(algId); ASSERT_TRUE(ctx != NULL); ASSERT_TRUE(CRYPT_EAL_MacInit(ctx, key, len) == CRYPT_SUCCESS); ASSERT_TRUE(CRYPT_EAL_MacFinal(NULL, mac, &macLen) == CRYPT_NULL_INPUT); ASSERT_TRUE(CRYPT_EAL_MacFinal(ctx, NULL, &macLen) == CRYPT_NULL_INPUT); ASSERT_TRUE(CRYPT_EAL_MacFinal(ctx, mac, NULL) == CRYPT_NULL_INPUT); macLen = TestGetMacLen(algId) - 1; ASSERT_TRUE(CRYPT_EAL_MacFinal(ctx, mac, &macLen) == CRYPT_CMAC_OUT_BUFF_LEN_NOT_ENOUGH); macLen = TestGetMacLen(algId) + 1; ASSERT_TRUE(CRYPT_EAL_MacFinal(ctx, mac, &macLen) == CRYPT_SUCCESS); ASSERT_TRUE(CRYPT_EAL_MacInit(ctx, key, len) == CRYPT_SUCCESS); ASSERT_TRUE(CRYPT_EAL_MacFinal(ctx, mac, &macLen) == CRYPT_SUCCESS); EXIT: CRYPT_EAL_MacFreeCtx(ctx); } /* END_CASE */ /* @ * @test SDV_CRYPT_EAL_CMAC_API_TC007 * @spec - * @title test final * @precon nan * @brief 1.Invoke the new interface. Expected result 1 is obtained. 2.Invoke the final interface. Expected result 2 is obtained. 3.Invoke the final interface. Expected result 3 is obtained. 4.Invoke the update interface. Expected result 4 is obtained. 5.Invoke the init interface. Expected result 5 is obtained. 6.Invoke the final interface. Expected result 6 is obtained. 7.Invoke the init interface. Expected result 7 is obtained. 8.Invoke the update interface. Expected result 8 is obtained. 9.Invoke the final interface. Expected result 9 is obtained. 10.Invoke the reinit interface. Expected result 10 is obtained. 11.Invoke the final interface. Expected result 11 is obtained. 12.Invoke the init interface. Expected result 12 is obtained. 13.Invoke the reinit interface. Expected result 13 is obtained. 14.Invoke the final interface. Expected result 14 is obtained. 15.repeat invoke the final interface. Expected result 15 is obtained. * @expect 1.new sucess,return CRYPT_EAL_MacCtx pointer 2.final failed,return RYPT_EAL_ERR_STATE 3.final failed,return RYPT_EAL_ERR_STATE 4.update failed,return YPT_EAL_ERR_STATE 5.init sucess,return CRYPT_SUCCESS 6.final sucess,return CRYPT_SUCCESS 7.init sucess,return CRYPT_SUCCESS 8.update sucess,return CRYPT_SUCCESS 9.final sucess,return CRYPT_SUCCESS 10. 11.final failed,return CRYPT_EAL_ERR_STATE 12.init sucess,return CRYPT_SUCCESS 13.reinit sucess,return CRYPT_SUCCESS 14.final sucess,return CRYPT_SUCCESS 15.final failed,return RYPT_EAL_ERR_STATE * @prior Level 1 * @auto TRUE @ */ /* BEGIN_CASE */ void SDV_CRYPT_EAL_CMAC_API_TC007(int algId, Hex *key1, Hex *mac1, Hex *key2, Hex *data2, Hex *mac2, Hex *mac3) { if (IsCmacAlgDisabled(algId)) { SKIP_TEST(); } TestMemInit(); uint32_t macLen = TestGetMacLen(algId); uint8_t mac[macLen]; CRYPT_EAL_MacCtx *ctx = CRYPT_EAL_MacNewCtx(algId); ASSERT_TRUE(ctx != NULL); ASSERT_TRUE(CRYPT_EAL_MacFinal(ctx, mac, &macLen) == CRYPT_EAL_ERR_STATE); ASSERT_TRUE(CRYPT_EAL_MacFinal(ctx, mac, &macLen) == CRYPT_EAL_ERR_STATE); ASSERT_TRUE(CRYPT_EAL_MacUpdate(ctx, data2->x, data2->len) == CRYPT_EAL_ERR_STATE); // mac1 ASSERT_TRUE(CRYPT_EAL_MacInit(ctx, key1->x, key1->len) == CRYPT_SUCCESS); ASSERT_TRUE(CRYPT_EAL_MacFinal(ctx, mac, &macLen) == CRYPT_SUCCESS); ASSERT_COMPARE("mac1 result cmp", mac, macLen, mac1->x, mac1->len); // mac2 ASSERT_TRUE(CRYPT_EAL_MacInit(ctx, key2->x, key2->len) == CRYPT_SUCCESS); ASSERT_TRUE(CRYPT_EAL_MacUpdate(ctx, data2->x, data2->len) == CRYPT_SUCCESS); ASSERT_TRUE(CRYPT_EAL_MacFinal(ctx, mac, &macLen) == CRYPT_SUCCESS); ASSERT_COMPARE("mac2 result cmp", mac, macLen, mac2->x, mac2->len); CRYPT_EAL_MacDeinit(ctx); ASSERT_TRUE(CRYPT_EAL_MacFinal(ctx, mac, &macLen) == CRYPT_EAL_ERR_STATE); // mac3 ASSERT_TRUE(CRYPT_EAL_MacInit(ctx, key2->x, key2->len) == CRYPT_SUCCESS); ASSERT_TRUE(CRYPT_EAL_MacReinit(ctx) == CRYPT_SUCCESS); ASSERT_TRUE(CRYPT_EAL_MacFinal(ctx, mac, &macLen) == CRYPT_SUCCESS); ASSERT_COMPARE("mac3 result cmp", mac, macLen, mac3->x, mac3->len); ASSERT_TRUE(CRYPT_EAL_MacFinal(ctx, mac, &macLen) == CRYPT_EAL_ERR_STATE); EXIT: CRYPT_EAL_MacFreeCtx(ctx); } /* END_CASE */ /* @ * @test SDV_CRYPT_EAL_CMAC_API_TC008 * @spec - * @title getMacLen: valid input parameter, invalid input parameter * @precon nan * @brief 1. Invoke the new interface. Expected result 1 is obtained. 2. Invoke the init interface. Expected result 2 is obtained. 3. Invoke the getLen interface and set the input parameter to NULL. Expected result 3 is obtained. 4. Invoke the getLen interface and set normal input parameters. Expected result 4 is obtained. * @expect 1.new sucess,return CRYPT_EAL_MacCtx pointer 2.init sucess,return CRYPT_SUCCESS 3. failed,return 0 4. sucess,return mac length * @prior Level 1 * @auto TRUE @ */ /* BEGIN_CASE */ void SDV_CRYPT_EAL_CMAC_API_TC008(int algId) { if (IsCmacAlgDisabled(algId)) { SKIP_TEST(); } TestMemInit(); const uint32_t len = GetKeyLen(algId); uint8_t key[len]; CRYPT_EAL_MacCtx *ctx = CRYPT_EAL_MacNewCtx(algId); ASSERT_TRUE(CRYPT_EAL_MacInit(ctx, key, len) == CRYPT_SUCCESS); ASSERT_TRUE(CRYPT_EAL_GetMacLen(NULL) == 0); ASSERT_TRUE(CRYPT_EAL_GetMacLen(ctx) == TestGetMacLen(algId)); uint32_t result = 0; ASSERT_TRUE(CRYPT_EAL_MacCtrl(ctx, CRYPT_CTRL_GET_MACLEN, &result, sizeof(uint32_t)) == CRYPT_SUCCESS); ASSERT_TRUE(result == TestGetMacLen(algId)); EXIT: CRYPT_EAL_MacFreeCtx(ctx); } /* END_CASE */ /* @ * @test SDV_CRYPT_EAL_CMAC_API_TC009 * @spec - * @precon nan * @brief 1. Invoke the new interface. Expected result 1 is obtained. 2. Invoke the getLen interface. Expected result 2 is obtained. 3. Invoke the init interface. Expected result 3 is obtained. 4. Invoke the getLen interface. Expected result 4 is obtained. 5. Invoke the update interface. Expected result 5 is obtained. 6. Invoke the getLen interface. Expected result 6 is obtained. 7. Invoke the final interface. Expected result 7 is obtained. 8. Invoke the getLen interface. Expected result 8 is obtained. 9. Invoke the deinit interface. Expected result 9 is obtained. 10. Invoke the getLen interface. Expected result 10 is obtained. 11. Invoke the deinit interface. Expected result 11 is obtained. 12. Invoke the getLen interface. Expected result 12 is obtained. * @expect 1.new sucess,return CRYPT_EAL_MacCtx pointer 2. sucess,return mac length 3.init sucess,return CRYPT_SUCCESS 4. sucess,return mac length 5.update sucess,return CRYPT_SUCCESS 6. sucess,return mac length 7.final sucess,return CRYPT_SUCCESS 8. sucess,return mac length 9. 10. sucess,return mac length 11.deinit sucess,return CRYPT_SUCCESS 12. sucess,return mac length * @prior Level 1 * @auto TRUE @ */ /* BEGIN_CASE */ void SDV_CRYPT_EAL_CMAC_API_TC009(int algId) { if (IsCmacAlgDisabled(algId)) { SKIP_TEST(); } TestMemInit(); const uint32_t len = GetKeyLen(algId); uint8_t key[len]; uint32_t macLen = TestGetMacLen(algId); uint8_t mac[macLen]; const uint32_t dataLen = TestGetMacLen(algId); uint8_t data[dataLen]; CRYPT_EAL_MacCtx *ctx = CRYPT_EAL_MacNewCtx(algId); ASSERT_TRUE(ctx != NULL); ASSERT_TRUE(CRYPT_EAL_GetMacLen(ctx) == TestGetMacLen(algId)); ASSERT_TRUE(CRYPT_EAL_MacInit(ctx, key, len) == CRYPT_SUCCESS); ASSERT_TRUE(CRYPT_EAL_GetMacLen(ctx) == TestGetMacLen(algId)); ASSERT_TRUE(CRYPT_EAL_MacUpdate(ctx, data, dataLen) == CRYPT_SUCCESS); ASSERT_TRUE(CRYPT_EAL_GetMacLen(ctx) == TestGetMacLen(algId)); ASSERT_TRUE(CRYPT_EAL_MacFinal(ctx, mac, &macLen) == CRYPT_SUCCESS); ASSERT_TRUE(CRYPT_EAL_GetMacLen(ctx) == TestGetMacLen(algId)); CRYPT_EAL_MacDeinit(ctx); ASSERT_TRUE(CRYPT_EAL_GetMacLen(ctx) == TestGetMacLen(algId)); ASSERT_TRUE(CRYPT_EAL_MacFinal(ctx, mac, &macLen) == CRYPT_EAL_ERR_STATE); ASSERT_TRUE(CRYPT_EAL_GetMacLen(ctx) == TestGetMacLen(algId)); EXIT: CRYPT_EAL_MacFreeCtx(ctx); } /* END_CASE */ /* @ * @test SDV_CRYPT_EAL_CMAC_API_TC010 * @spec - * @title deinit interface test * @precon nan * @brief 1. Invoke the new interface. Expected result 1 is obtained. 2. Invoke the init interface. Expected result 2 is obtained. 3. Invoke the deinit interface. Expected result 3 is obtained. 4. Invoke the deinit interface repeatedly. Expected result 4 is obtained. 5. Invoke the init interface. Expected result 5 is obtained. * @expect 1.new sucess,return CRYPT_EAL_MacCtx pointer 2.init sucess,return CRYPT_SUCCESS3. 4. 5.init sucess,return CRYPT_SUCCESS * @prior Level 1 * @auto TRUE @ */ /* BEGIN_CASE */ void SDV_CRYPT_EAL_CMAC_API_TC010(int algId) { if (IsCmacAlgDisabled(algId)) { SKIP_TEST(); } TestMemInit(); const uint32_t len = GetKeyLen(algId); uint8_t key[len]; CRYPT_EAL_MacCtx *ctx = CRYPT_EAL_MacNewCtx(algId); ASSERT_TRUE(ctx != NULL); ASSERT_TRUE(CRYPT_EAL_MacInit(ctx, key, len) == CRYPT_SUCCESS); CRYPT_EAL_MacDeinit(ctx); CRYPT_EAL_MacDeinit(ctx); ASSERT_TRUE(CRYPT_EAL_MacInit(ctx, key, len) == CRYPT_SUCCESS); CRYPT_EAL_MacDeinit(NULL); EXIT: CRYPT_EAL_MacFreeCtx(ctx); } /* END_CASE */ /* @ * @test SDV_CRYPT_EAL_CMAC_API_TC011 * @spec - * @title reinit test * @precon nan * @brief 1. Invoke the new interface. Expected result 1 is obtained. 2. Invoke the init interface. Expected result 2 is obtained. 3. Invoke the reinit interface. The value of ctx is NULL. Expected result 3 is obtained. 4. Invoke the reinit interface. The value of ctx is not NUL. Expected result 4 is obtained. * @expect 1.new sucess,return CRYPT_EAL_MacCtx pointer 2.init sucess,return CRYPT_SUCCESS 3.init failed,return CRYPT_NULL_INPUT 4.reinit sucess,return CRYPT_SUCCESS * @prior Level 1 * @auto TRUE @ */ /* BEGIN_CASE */ void SDV_CRYPT_EAL_CMAC_API_TC011(int algId) { if (IsCmacAlgDisabled(algId)) { SKIP_TEST(); } TestMemInit(); const uint32_t len = GetKeyLen(algId); uint8_t key[len]; CRYPT_EAL_MacCtx *ctx = CRYPT_EAL_MacNewCtx(algId); ASSERT_TRUE(ctx != NULL); ASSERT_TRUE(CRYPT_EAL_MacInit(ctx, key, len) == CRYPT_SUCCESS); ASSERT_TRUE(CRYPT_EAL_MacReinit(NULL) == CRYPT_NULL_INPUT); ASSERT_TRUE(CRYPT_EAL_MacReinit(ctx) == CRYPT_SUCCESS); EXIT: CRYPT_EAL_MacFreeCtx(ctx); } /* END_CASE */ /* @ * @test SDV_CRYPT_EAL_CMAC_API_TC012 * @spec - * @precon nan * @brief 1. Invoke the new interface. Expected result 1 is obtained. 2. Invoke the reinit interface. Expected result 2 is obtained. 3. Invoke the reinit interface repeatedly. Expected result 3 is obtained. 4. Invoke the init interface. Expected result 4 is obtained. 5. Invoke the reinit interface. Expected result 5 is obtained. 6. Invoke the reinit interface repeatedly. Expected result 6 is obtained. 7. Invoke the update interface. Expected result 7 is obtained. 8. Invoke the reinit interface. Expected result 8 is obtained. 9. Invoke the final interface. Expected result 9 is obtained. 10. Invoke the reinit interface. Expected result 10 is obtained. 11. Invoke the deinit interface. Expected result 11 is obtained. 12. Invoke the reinit interface. Expected result 12 is obtained. * @expect 1.new sucess,return CRYPT_EAL_MacCtx pointer 2.reinit failed,return CRYPT_NULL_INPUT 3.reinit failed,return CRYPT_NULL_INPUT 4.init sucess,return CRYPT_SUCCESS 5.reinit sucess,return CRYPT_SUCCESS 6.reinit sucess,return CRYPT_SUCCESS 7.update sucess,return CRYPT_SUCCESS 8.reinit sucess,return CRYPT_SUCCESS 9.final sucess,return CRYPT_SUCCESS 10.reinit sucess,return CRYPT_SUCCESS 11. 12.reinit failed,return CRYPT_EAL_ERR_STATE * @prior Level 1 * @auto TRUE @ */ /* BEGIN_CASE */ void SDV_CRYPT_EAL_CMAC_API_TC012(int algId) { if (IsCmacAlgDisabled(algId)) { SKIP_TEST(); } TestMemInit(); const uint32_t len = GetKeyLen(algId); uint8_t key[len]; uint32_t macLen = TestGetMacLen(algId); uint8_t mac[macLen]; const uint32_t dataLen = GetKeyLen(algId); uint8_t data[dataLen]; CRYPT_EAL_MacCtx *ctx = CRYPT_EAL_MacNewCtx(algId); ASSERT_TRUE(ctx != NULL); ASSERT_TRUE(CRYPT_EAL_MacReinit(ctx) == CRYPT_EAL_ERR_STATE); ASSERT_TRUE(CRYPT_EAL_MacReinit(ctx) == CRYPT_EAL_ERR_STATE); ASSERT_TRUE(CRYPT_EAL_MacInit(ctx, key, len) == CRYPT_SUCCESS); ASSERT_TRUE(CRYPT_EAL_MacReinit(ctx) == CRYPT_SUCCESS); ASSERT_TRUE(CRYPT_EAL_MacReinit(ctx) == CRYPT_SUCCESS); ASSERT_TRUE(CRYPT_EAL_MacUpdate(ctx, data, dataLen) == CRYPT_SUCCESS); ASSERT_TRUE(CRYPT_EAL_MacReinit(ctx) == CRYPT_SUCCESS); ASSERT_TRUE(CRYPT_EAL_MacFinal(ctx, mac, &macLen) == CRYPT_SUCCESS); ASSERT_TRUE(CRYPT_EAL_MacReinit(ctx) == CRYPT_SUCCESS); CRYPT_EAL_MacDeinit(ctx); ASSERT_TRUE(CRYPT_EAL_MacReinit(ctx) == CRYPT_EAL_ERR_STATE); EXIT: CRYPT_EAL_MacFreeCtx(ctx); } /* END_CASE */ /* @ * @test SDV_CRYPT_EAL_CMAC_FUN_TC004 * @spec - * @title All 0s and all Fs data key * @precon nan * @brief 1.Invoke the new interface. Expected result 1 is obtained. 2. Invoke the init interface. Expected result 2 is obtained. 3. Invoke the update interface. Expected result 3 is obtained. 4. Invoke the final interface. Expected result 4 is obtained. * @expect 1.new sucess,return CRYPT_EAL_MacCtx pointer 2.init sucess,return CRYPT_SUCCESS 3.update sucess,return CRYPT_SUCCESS 4.final sucess,return CRYPT_SUCCESS * @prior Level 1 * @auto TRUE @ */ /* BEGIN_CASE */ void SDV_CRYPT_EAL_CMAC_FUN_TC004(int algId, Hex *key, Hex *data, Hex *vecMac) { if (IsCmacAlgDisabled(algId)) { SKIP_TEST(); } TestMemInit(); uint32_t macLen = TestGetMacLen(algId); uint8_t mac[macLen]; CRYPT_EAL_MacCtx *ctx = CRYPT_EAL_MacNewCtx(algId); ASSERT_TRUE(ctx != NULL); ASSERT_TRUE(CRYPT_EAL_MacInit(ctx, key->x, key->len) == CRYPT_SUCCESS); ASSERT_TRUE(CRYPT_EAL_MacUpdate(ctx, data->x, data->len) == CRYPT_SUCCESS); ASSERT_TRUE(CRYPT_EAL_MacFinal(ctx, mac, &macLen) == CRYPT_SUCCESS); ASSERT_COMPARE("mac1 result cmp", mac, macLen, vecMac->x, vecMac->len); EXIT: CRYPT_EAL_MacFreeCtx(ctx); } /* END_CASE */ static int32_t UpdateMultiTime(CRYPT_EAL_MacCtx *ctx, Hex *data, int updateTimes, uint8_t *mac, uint32_t *macLen) { int32_t ret = CRYPT_SUCCESS; for (int i = 0; i < updateTimes; i++) { ret = CRYPT_EAL_MacUpdate(ctx, data->x, data->len); if (ret != CRYPT_SUCCESS) { return ret; } } return CRYPT_EAL_MacFinal(ctx, mac, macLen); } /* @ * @test SDV_CRYPT_EAL_CMAC_FUN_TC006 * @spec - * @title Compare the CMACC result with that of the CMACC result after multiple updates and one update. * @precon nan * @brief Run the updateTimes command to compare the cmac result with the update command. * The expected results are the same. * @prior Level 1 * @auto TRUE @ */ /* BEGIN_CASE */ void SDV_CRYPT_EAL_CMAC_FUN_TC006(int algId, Hex *key, Hex *data, int updateTimes) { if (IsCmacAlgDisabled(algId)) { SKIP_TEST(); } TestMemInit(); uint32_t macLen1 = CMAC_MAC_LEN; uint8_t mac1[CMAC_MAC_LEN] = {}; uint32_t macLen2 = CMAC_MAC_LEN; uint8_t mac2[CMAC_MAC_LEN] = {}; uint8_t *totalInData = NULL; uint32_t totalLen = 0; CRYPT_EAL_MacCtx *ctx = CRYPT_EAL_MacNewCtx(algId); ASSERT_TRUE(ctx != NULL); ASSERT_TRUE(CRYPT_EAL_MacInit(ctx, key->x, key->len) == CRYPT_SUCCESS); ASSERT_TRUE(UpdateMultiTime(ctx, data, updateTimes, mac1, &macLen1) == CRYPT_SUCCESS); CRYPT_EAL_MacDeinit(ctx); totalInData = BSL_SAL_Calloc(data->len * updateTimes, 1); ASSERT_TRUE(totalInData != NULL); for (int i = 0; i < updateTimes; i++) { memcpy(totalInData + totalLen, data->x, data->len); totalLen += data->len; } ASSERT_TRUE(CRYPT_EAL_MacInit(ctx, key->x, key->len) == CRYPT_SUCCESS); ASSERT_TRUE(CRYPT_EAL_MacUpdate(ctx, totalInData, totalLen) == CRYPT_SUCCESS); ASSERT_TRUE(CRYPT_EAL_MacFinal(ctx, mac2, &macLen2) == CRYPT_SUCCESS); ASSERT_TRUE(macLen1 == macLen2); ASSERT_COMPARE("mac1 vs mac2 result cmp", mac2, macLen2, mac1, macLen1); EXIT: BSL_SAL_FREE(totalInData); CRYPT_EAL_MacFreeCtx(ctx); } /* END_CASE */ /** * @test SDV_CRYPT_EAL_CMAC_SAMEADDR_FUNC_TC001 * @title CMAC in/out same addr * @precon nan * @brief * 1.Use the EAL layer interface to perform CMAC calculation. All input and output addresses are the same. * Expected result 1 is displayed. * @expect * 1.compute sucess */ /* BEGIN_CASE */ void SDV_CRYPT_EAL_CMAC_SAMEADDR_FUNC_TC001(int algId, Hex *key, Hex *data, Hex *mac) { TestMacSameAddr(algId, key, data, mac); } /* END_CASE */ /** * @test SDV_CRYPT_EAL_CMAC_ADDR_NOT_ALIGN_FUNC_TC001 * @title CMAC non-address alignment test * @precon nan * @brief * 1.Use the EAL layer interface to perform CMAC calculation. All buffer addresses are not aligned. * Expected result 1 is obtained. * @expect * 1.compute sucess */ /* BEGIN_CASE */ void SDV_CRYPT_EAL_CMAC_ADDR_NOT_ALIGN_FUNC_TC001(int algId, Hex *key, Hex *data, Hex *mac) { TestMacAddrNotAlign(algId, key, data, mac); } /* END_CASE */
2301_79861745/bench_create
testcode/sdv/testcase/crypto/cmac/test_suite_sdv_eal_mac_cmac.c
C
unknown
31,290
/* * This file is part of the openHiTLS project. * * openHiTLS is licensed under the Mulan PSL v2. * You can use this software according to the terms and conditions of the Mulan PSL v2. * You may obtain a copy of Mulan PSL v2 at: * * http://license.coscl.org.cn/MulanPSL2 * * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, * EITHER EXPRESS 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 <stddef.h> #include <stdbool.h> #include "crypt_bn.h" #include "bsl_sal.h" #include "crypt_algid.h" #include "crypt_types.h" #include "crypt_eal_pkey.h" #include "crypt_errno.h" #include "crypt_curve25519.h" #include "eal_pkey_local.h" #include "crypt_eal_rand.h" #include "securec.h" #include "curve25519_local.h" #include "crypt_curve25519.h" #define CRYPT_EAL_PKEY_KEYMGMT_OPERATE 0 #define CRYPT_EAL_PKEY_CIPHER_OPERATE 1 #define CRYPT_EAL_PKEY_EXCH_OPERATE 2 #define CRYPT_EAL_PKEY_SIGN_OPERATE 4 void *malloc_fail(uint32_t size) { (void)size; return NULL; } static void Set_Curve25519_Prv(CRYPT_EAL_PkeyPrv *prv, int id, uint8_t *key, uint32_t keyLen) { prv->id = id; prv->key.curve25519Prv.data = key; prv->key.curve25519Prv.len = keyLen; } static void Set_Curve25519_Pub(CRYPT_EAL_PkeyPub *pub, int id, uint8_t *key, uint32_t keyLen) { pub->id = id; pub->key.curve25519Pub.data = key; pub->key.curve25519Pub.len = keyLen; } /* END_HEADER */ /** * @test SDV_CRYPTO_CURVE25519_SET_PARA_API_TC001 * @title CURVE25519: CRYPT_EAL_PkeySetPara test. * @precon nan * @brief * 1. Create the context of the curve25519 algorithm, expected result 1. * 2. Call the CRYPT_EAL_PkeySetPara method, where parameter para.id is CRYPT_PKEY_*25519, expected result 2. * 3. Call the CRYPT_EAL_PkeySetPara method, where parameter para.id is not CRYPT_PKEY_*25519, expected result 3. * @expect * 1. Success, and context is not NULL. * 2. CRYPT_EAL_ALG_NOT_SUPPORT * 3. CRYPT_EAL_ERR_ALGID */ /* BEGIN_CASE */ void SDV_CRYPTO_CURVE25519_SET_PARA_API_TC001(int id, int isProvider) { TestMemInit(); CRYPT_EAL_PkeyPara para; CRYPT_EAL_PkeyCtx *pkey = TestPkeyNewCtx(NULL, id, CRYPT_EAL_PKEY_KEYMGMT_OPERATE, "provider=default", isProvider); ASSERT_TRUE(pkey != NULL); para.id = id; ASSERT_EQ(CRYPT_EAL_PkeySetPara(pkey, &para), CRYPT_EAL_ALG_NOT_SUPPORT); para.id = CRYPT_PKEY_DSA; ASSERT_EQ(CRYPT_EAL_PkeySetPara(pkey, &para), CRYPT_EAL_ERR_ALGID); EXIT: CRYPT_EAL_PkeyFreeCtx(pkey); } /* END_CASE */ /** * @test SDV_CRYPTO_CURVE25519_SET_PRV_API_TC001 * @title CURVE25519: CRYPT_EAL_PkeySetPrv test. * @precon Create a valid private key prv. * @brief * 1. Create the context of the curve25519 algorithm, expected result 1. * 2. Call the CRYPT_EAL_PkeySetPrv method: * (1). pkey = NULL, expected result 2. * (2). prv = NULL, expected result 2. * (3). prv.data = NULL, expected result 2. * (4). prv.len = 0, expected result 2. * (5). prv.id != pkey.id, expected result 3. * (6). prv.len = 33|31, expected result 4. * (7). All parameters are valid, expected result 5. * @expect * 1. Success, and context is not NULL. * 2. CRYPT_NULL_INPUT * 3. CRYPT_EAL_ERR_ALGID * 4. CRYPT_CURVE25519_KEYLEN_ERROR * 5. CRYPT_SUCCESS */ /* BEGIN_CASE */ void SDV_CRYPTO_CURVE25519_SET_PRV_API_TC001(int id, int isProvider) { uint8_t key[CRYPT_CURVE25519_KEYLEN] = {0}; CRYPT_EAL_PkeyPrv prv = {0}; Set_Curve25519_Prv(&prv, id, key, CRYPT_CURVE25519_KEYLEN); TestMemInit(); CRYPT_EAL_PkeyCtx *pkey = TestPkeyNewCtx(NULL, id, CRYPT_EAL_PKEY_KEYMGMT_OPERATE, "provider=default", isProvider); ASSERT_TRUE(pkey != NULL); ASSERT_EQ(CRYPT_EAL_PkeySetPrv(NULL, &prv), CRYPT_NULL_INPUT); ASSERT_EQ(CRYPT_EAL_PkeySetPrv(pkey, NULL), CRYPT_NULL_INPUT); prv.key.curve25519Prv.data = NULL; ASSERT_EQ(CRYPT_EAL_PkeySetPrv(pkey, &prv), CRYPT_NULL_INPUT); prv.key.curve25519Prv.data = key; prv.key.curve25519Prv.len = 0; ASSERT_EQ(CRYPT_EAL_PkeySetPrv(NULL, &prv), CRYPT_NULL_INPUT); prv.id = CRYPT_PKEY_DSA; ASSERT_EQ(CRYPT_EAL_PkeySetPrv(pkey, &prv), CRYPT_EAL_ERR_ALGID); prv.id = id; prv.key.curve25519Prv.len = CRYPT_CURVE25519_KEYLEN - 1; ASSERT_EQ(CRYPT_EAL_PkeySetPrv(pkey, &prv), CRYPT_CURVE25519_KEYLEN_ERROR); prv.key.curve25519Prv.len = CRYPT_CURVE25519_KEYLEN + 1; ASSERT_EQ(CRYPT_EAL_PkeySetPrv(pkey, &prv), CRYPT_CURVE25519_KEYLEN_ERROR); prv.key.curve25519Prv.len = CRYPT_CURVE25519_KEYLEN; ASSERT_EQ(CRYPT_EAL_PkeySetPrv(pkey, &prv), CRYPT_SUCCESS); EXIT: CRYPT_EAL_PkeyFreeCtx(pkey); } /* END_CASE */ /** * @test SDV_CRYPTO_CURVE25519_SET_PUB_API_TC001 * @title CURVE25519: CRYPT_EAL_PkeySetPub test. * @precon Create a valid public key pub. * @brief * 1. Create the context of the curve25519 algorithm, expected result 1. * 2. Call the CRYPT_EAL_PkeySetPub method: * (1). pkey = NULL, expected result 2. * (2). pub = NULL, expected result 2. * (3). pub.data = NULL, expected result 2. * (4). pub.len = 0, expected result 2. * (5). pub.id != pkey.id, expected result 3. * (6). pub.len = 33|31, expected result 4. * (7). All parameters are valid, expected result 5. * @expect * 1. Success, and context is not NULL. * 2. CRYPT_NULL_INPUT * 3. CRYPT_EAL_ERR_ALGID * 4. CRYPT_CURVE25519_KEYLEN_ERROR * 5. CRYPT_SUCCESS */ /* BEGIN_CASE */ void SDV_CRYPTO_CURVE25519_SET_PUB_API_TC001(int id) { uint8_t key[CRYPT_CURVE25519_KEYLEN] = {0}; CRYPT_EAL_PkeyPub pub = {0}; Set_Curve25519_Pub(&pub, id, key, CRYPT_CURVE25519_KEYLEN); TestMemInit(); CRYPT_EAL_PkeyCtx *pkey = CRYPT_EAL_PkeyNewCtx(id); ASSERT_TRUE(pkey != NULL); ASSERT_EQ(CRYPT_EAL_PkeySetPub(NULL, &pub), CRYPT_NULL_INPUT); ASSERT_EQ(CRYPT_EAL_PkeySetPub(pkey, NULL), CRYPT_NULL_INPUT); pub.key.curve25519Pub.data = NULL; ASSERT_EQ(CRYPT_EAL_PkeySetPub(pkey, &pub), CRYPT_NULL_INPUT); pub.key.curve25519Pub.data = key; pub.key.curve25519Pub.len = 0; ASSERT_EQ(CRYPT_EAL_PkeySetPub(NULL, &pub), CRYPT_NULL_INPUT); pub.id = CRYPT_PKEY_DSA; ASSERT_EQ(CRYPT_EAL_PkeySetPub(pkey, &pub), CRYPT_EAL_ERR_ALGID); pub.id = id; pub.key.curve25519Pub.len = CRYPT_CURVE25519_KEYLEN - 1; ASSERT_EQ(CRYPT_EAL_PkeySetPub(pkey, &pub), CRYPT_CURVE25519_KEYLEN_ERROR); pub.key.curve25519Pub.len = CRYPT_CURVE25519_KEYLEN + 1; ASSERT_EQ(CRYPT_EAL_PkeySetPub(pkey, &pub), CRYPT_CURVE25519_KEYLEN_ERROR); pub.key.curve25519Pub.len = CRYPT_CURVE25519_KEYLEN; ASSERT_EQ(CRYPT_EAL_PkeySetPub(pkey, &pub), CRYPT_SUCCESS); EXIT: CRYPT_EAL_PkeyFreeCtx(pkey); } /* END_CASE */ /** * @test SDV_CRYPTO_CURVE25519_GET_PRV_API_TC001 * @title CURVE25519: CRYPT_EAL_PkeyGetPrv test. * @precon Create a valid private key prv. * @brief * 1. Create the context of the curve25519 algorithm, expected result 1. * 2. Call the CRYPT_EAL_PkeyGetPrv method, where all parameters are valid, expected result 2. * 3. Call the CRYPT_EAL_PkeySetPrv method to set private key, expected result 3. * 4. Call the CRYPT_EAL_PkeyGetPrv method, where other parameters are valid, but: * (1). pkey = NULL, expected result 4. * (2). prv = NULL, expected result 4. * (5). prv.id != pkey.id, expected result 5. * (6). prv.len = 31, expected result 6. * (6). prv.len = 33, expected result 7. * (7). All parameters are valid, expected result 7. * @expect * 1. Success, and context is not NULL. * 2. CRYPT_CURVE25519_NO_PRVKEY * 3. CRYPT_SUCCESS * 4. CRYPT_NULL_INPUT * 5. CRYPT_EAL_ERR_ALGID * 6. CRYPT_CURVE25519_KEYLEN_ERROR * 7. CRYPT_SUCCESS */ /* BEGIN_CASE */ void SDV_CRYPTO_CURVE25519_GET_PRV_API_TC001(int id, int isProvider) { uint8_t key[CRYPT_CURVE25519_KEYLEN] = {0}; CRYPT_EAL_PkeyPrv prv = {0}; Set_Curve25519_Prv(&prv, id, key, CRYPT_CURVE25519_KEYLEN); TestMemInit(); CRYPT_EAL_PkeyCtx *pkey = TestPkeyNewCtx(NULL, id, CRYPT_EAL_PKEY_KEYMGMT_OPERATE, "provider=default", isProvider); ASSERT_TRUE(pkey != NULL); ASSERT_EQ(CRYPT_EAL_PkeyGetPrv(pkey, &prv), CRYPT_CURVE25519_NO_PRVKEY); ASSERT_EQ(CRYPT_EAL_PkeySetPrv(pkey, &prv), CRYPT_SUCCESS); ASSERT_EQ(CRYPT_EAL_PkeyGetPrv(NULL, &prv), CRYPT_NULL_INPUT); ASSERT_EQ(CRYPT_EAL_PkeyGetPrv(pkey, NULL), CRYPT_NULL_INPUT); prv.id = CRYPT_PKEY_DSA; ASSERT_EQ(CRYPT_EAL_PkeyGetPrv(pkey, &prv), CRYPT_EAL_ERR_ALGID); prv.id = id; prv.key.curve25519Prv.len = CRYPT_CURVE25519_KEYLEN - 1; ASSERT_EQ(CRYPT_EAL_PkeyGetPrv(pkey, &prv), CRYPT_CURVE25519_KEYLEN_ERROR); prv.key.curve25519Prv.len = CRYPT_CURVE25519_KEYLEN; ASSERT_EQ(CRYPT_EAL_PkeyGetPrv(pkey, &prv), CRYPT_SUCCESS); prv.key.curve25519Prv.len = CRYPT_CURVE25519_KEYLEN + 1; ASSERT_EQ(CRYPT_EAL_PkeyGetPrv(pkey, &prv), CRYPT_SUCCESS); EXIT: CRYPT_EAL_PkeyFreeCtx(pkey); } /* END_CASE */ /** * @test SDV_CRYPTO_CURVE25519_GET_PUB_API_TC001 * @title CURVE25519: CRYPT_EAL_PkeyGetPub test. * @precon Create a valid public key pub. * @brief * 1. Create the context of the curve25519 algorithm, expected result 1. * 2. Call the CRYPT_EAL_PkeyGetPub method, where all parameters are valid, expected result 2. * 3. Call the CRYPT_EAL_PkeySetPub method to set private key, expected result 3. * 4. Call the CRYPT_EAL_PkeyGetPub method, where other parameters are valid, but : * (1). pkey = NULL, expected result 4. * (2). pub = NULL, expected result 4. * (5). pub.id != pkey.id, expected result 5. * (6). pub.len = 31, expected result 6. * (6). pub.len = 33, expected result 7. * (7). All parameters are valid, expected result 7. * @expect * 1. Success, and context is not NULL. * 2. CRYPT_CURVE25519_NO_PUBKEY * 3. CRYPT_SUCCESS * 4. CRYPT_NULL_INPUT * 5. CRYPT_EAL_ERR_ALGID * 6. CRYPT_CURVE25519_KEYLEN_ERROR * 7. CRYPT_SUCCESS */ /* BEGIN_CASE */ void SDV_CRYPTO_CURVE25519_GET_PUB_API_TC001(int id, int isProvider) { uint8_t key[CRYPT_CURVE25519_KEYLEN] = {0}; CRYPT_EAL_PkeyPub pub; Set_Curve25519_Pub(&pub, id, key, CRYPT_CURVE25519_KEYLEN); TestMemInit(); CRYPT_EAL_PkeyCtx *pkey = TestPkeyNewCtx(NULL, id, CRYPT_EAL_PKEY_KEYMGMT_OPERATE, "provider=default", isProvider); ASSERT_TRUE(pkey != NULL); ASSERT_EQ(CRYPT_EAL_PkeyGetPub(pkey, &pub), CRYPT_CURVE25519_NO_PUBKEY); ASSERT_EQ(CRYPT_EAL_PkeySetPub(pkey, &pub), CRYPT_SUCCESS); ASSERT_EQ(CRYPT_EAL_PkeyGetPub(NULL, &pub), CRYPT_NULL_INPUT); ASSERT_EQ(CRYPT_EAL_PkeyGetPub(pkey, NULL), CRYPT_NULL_INPUT); pub.id = CRYPT_PKEY_DSA; ASSERT_EQ(CRYPT_EAL_PkeyGetPub(pkey, &pub), CRYPT_EAL_ERR_ALGID); pub.id = id; pub.key.curve25519Pub.len = CRYPT_CURVE25519_KEYLEN - 1; ASSERT_EQ(CRYPT_EAL_PkeyGetPub(pkey, &pub), CRYPT_CURVE25519_KEYLEN_ERROR); pub.key.curve25519Pub.len = CRYPT_CURVE25519_KEYLEN; ASSERT_EQ(CRYPT_EAL_PkeyGetPub(pkey, &pub), CRYPT_SUCCESS); pub.key.curve25519Pub.len = CRYPT_CURVE25519_KEYLEN + 1; ASSERT_EQ(CRYPT_EAL_PkeyGetPub(pkey, &pub), CRYPT_SUCCESS); EXIT: CRYPT_EAL_PkeyFreeCtx(pkey); } /* END_CASE */ /** * @test SDV_CRYPTO_CURVE25519_GET_KEY_LEN_API_TC001 * @title CURVE25519: CRYPT_EAL_PkeyGetKeyLen test. * @precon nan * @brief * 1. Create the context of the curve25519 algorithm, expected result 1. * 2. Call the CRYPT_EAL_PkeyGetKeyLen method, where pkey is NULL, expected result 1. * 3. Call the CRYPT_EAL_PkeyGetKeyLen method, where pkey is valid, expected result 2. * @expect * 1. Success, and context is not NULL. * 2. Reutrn 0. * 3. Return CRYPT_CURVE25519_KEYLEN(32) */ /* BEGIN_CASE */ void SDV_CRYPTO_CURVE25519_GET_KEY_LEN_API_TC001(int id, int isProvider) { TestMemInit(); CRYPT_EAL_PkeyCtx *pkey = TestPkeyNewCtx(NULL, id, CRYPT_EAL_PKEY_KEYMGMT_OPERATE, "provider=default", isProvider); ASSERT_TRUE(pkey != NULL); ASSERT_EQ(CRYPT_EAL_PkeyGetKeyLen(NULL), 0); ASSERT_EQ(CRYPT_EAL_PkeyGetKeyLen(pkey), CRYPT_CURVE25519_KEYLEN); EXIT: CRYPT_EAL_PkeyFreeCtx(pkey); } /* END_CASE */ /** * @test SDV_CRYPTO_CURVE25519_KEY_GEN_API_TC001 * @title CURVE25519: CRYPT_EAL_PkeyGen test. * @precon nan * @brief * 1. Create the context of the curve25519 algorithm, expected result 1. * 2. Call the CRYPT_EAL_PkeyGen method, where pkey is NULL, expected result 1. * 3. Call the CRYPT_EAL_PkeyGen method, where pkey is valid, expected result 2. * @expect * 1. Success, and context is not NULL. * 2. CRYPT_NULL_INPUT * 3. CRYPT_NO_REGIST_RAND */ /* BEGIN_CASE */ void SDV_CRYPTO_CURVE25519_KEY_GEN_API_TC001(int id) { TestMemInit(); CRYPT_EAL_PkeyCtx *pkey = CRYPT_EAL_PkeyNewCtx(id); ASSERT_TRUE(pkey != NULL); ASSERT_EQ(CRYPT_EAL_PkeyGen(NULL), CRYPT_NULL_INPUT); ASSERT_EQ(CRYPT_EAL_PkeyGen(pkey), CRYPT_NO_REGIST_RAND); EXIT: CRYPT_EAL_PkeyFreeCtx(pkey); } /* END_CASE */ /** * @test SDV_CRYPTO_CURVE25519_KEY_GEN_API_TC002 * @title CURVE25519: CRYPT_EAL_PkeyGen test. * @precon nan * @brief * 1. Create the context of the curve25519 algorithm, expected result 1. * 2. Init the drbg, expected result 2. * 3. Generate a key pair, expected result 2. * 4. Call the CRYPT_EAL_PkeyGetPub method to get public key, expected result 2. * 5. Call the CRYPT_EAL_PkeyGetPub method to get private key, expected result 2. * @expect * 1. Success, and context is not NULL. * 2. Success */ /* BEGIN_CASE */ void SDV_CRYPTO_CURVE25519_KEY_GEN_API_TC002(int id, int isProvider) { if (IsCurve25519AlgDisabled(id)) { SKIP_TEST(); } uint8_t key[CRYPT_CURVE25519_KEYLEN] = {0}; CRYPT_EAL_PkeyPub pub; Set_Curve25519_Pub(&pub, id, key, CRYPT_CURVE25519_KEYLEN); CRYPT_EAL_PkeyPrv prv = {0}; Set_Curve25519_Prv(&prv, id, key, CRYPT_CURVE25519_KEYLEN); TestMemInit(); CRYPT_EAL_PkeyCtx *pkey = TestPkeyNewCtx(NULL, id, CRYPT_EAL_PKEY_KEYMGMT_OPERATE, "provider=default", isProvider); ASSERT_TRUE(pkey != NULL); /* Sets the entropy source. */ ASSERT_EQ(TestRandInit(), CRYPT_SUCCESS); ASSERT_EQ(CRYPT_EAL_PkeyGen(pkey), CRYPT_SUCCESS); ASSERT_EQ(CRYPT_EAL_PkeyGetPub(pkey, &pub), CRYPT_SUCCESS); ASSERT_EQ(CRYPT_EAL_PkeyGetPrv(pkey, &prv), CRYPT_SUCCESS); EXIT: TestRandDeInit(); CRYPT_EAL_PkeyFreeCtx(pkey); } /* END_CASE */ /** * @test SDV_CRYPTO_CURVE25519_SIGN_API_TC001 * @title CURVE25519: CRYPT_EAL_PkeySign test. * @precon Prepare data for signature. * @brief * 1. Create the context of the ed25519 algorithm, expected result 1. * 2. Call the CRYPT_EAL_PkeySign method, where all parameters are valid, expected result 2. * 3. Call the CRYPT_EAL_PkeySetPrv method to set private key, expected result 3. * 4. Call the CRYPT_EAL_PkeySign method, where other parameters are valid, but : * (1) hashId != CRYPT_MD_SHA512, expected result 4 * (2) data = NULL, expected result 4 * (3) sign = NULL, expected result 4 * (4) signLen = NULL, expected result 4 * (5) signLen = 0 | 63, expected result 5 * (6) signLen = 64 | 65, expected result 6 * @expect * 1. Success, and context is not NULL. * 2. CRYPT_CURVE25519_NO_PRVKEY * 3. CRYPT_SUCCESS * 4. CRYPT_EAL_ERR_ALGID * 5. CRYPT_NULL_INPUT * 6. CRYPT_CURVE25519_SIGNLEN_ERROR * 7. CRYPT_SUCCESS */ /* BEGIN_CASE */ void SDV_CRYPTO_CURVE25519_SIGN_API_TC001(int isProvider) { uint8_t key[CRYPT_CURVE25519_KEYLEN] = {0}; uint8_t data[CRYPT_CURVE25519_KEYLEN] = {0}; uint8_t sign[CRYPT_CURVE25519_SIGNLEN] = {0}; uint32_t signLen = sizeof(sign); CRYPT_EAL_PkeyPrv prv = {0}; Set_Curve25519_Prv(&prv, CRYPT_PKEY_ED25519, key, CRYPT_CURVE25519_KEYLEN); TestMemInit(); CRYPT_EAL_PkeyCtx *pkey = TestPkeyNewCtx(NULL, CRYPT_PKEY_ED25519, CRYPT_EAL_PKEY_KEYMGMT_OPERATE + CRYPT_EAL_PKEY_SIGN_OPERATE, "provider=default", isProvider); ASSERT_TRUE(pkey != NULL); ASSERT_EQ(CRYPT_EAL_PkeySign(pkey, CRYPT_MD_SHA512, data, sizeof(data), sign, &signLen), CRYPT_CURVE25519_NO_PRVKEY); ASSERT_EQ(CRYPT_EAL_PkeySetPrv(pkey, &prv), CRYPT_SUCCESS); ASSERT_EQ(CRYPT_EAL_PkeySign(pkey, CRYPT_MD_SHA256, data, sizeof(data), sign, &signLen), CRYPT_SUCCESS); ASSERT_EQ(CRYPT_EAL_PkeySign(pkey, CRYPT_MD_SHA512, NULL, sizeof(data), sign, &signLen), CRYPT_NULL_INPUT); ASSERT_EQ(CRYPT_EAL_PkeySign(pkey, CRYPT_MD_SHA512, data, sizeof(data), NULL, &signLen), CRYPT_NULL_INPUT); ASSERT_EQ(CRYPT_EAL_PkeySign(pkey, CRYPT_MD_SHA512, data, sizeof(data), (uint8_t *)sign, NULL), CRYPT_NULL_INPUT); signLen = 0; ASSERT_EQ(CRYPT_EAL_PkeySign(pkey, CRYPT_MD_SHA512, data, sizeof(data), sign, &signLen), CRYPT_CURVE25519_SIGNLEN_ERROR); signLen = CRYPT_CURVE25519_SIGNLEN - 1; ASSERT_EQ(CRYPT_EAL_PkeySign(pkey, CRYPT_MD_SHA512, data, sizeof(data), sign, &signLen), CRYPT_CURVE25519_SIGNLEN_ERROR); signLen = CRYPT_CURVE25519_SIGNLEN; ASSERT_EQ(CRYPT_EAL_PkeySign(pkey, CRYPT_MD_SHA512, data, sizeof(data), sign, &signLen), CRYPT_SUCCESS); signLen = CRYPT_CURVE25519_SIGNLEN + 1; ASSERT_EQ(CRYPT_EAL_PkeySign(pkey, CRYPT_MD_SHA512, data, sizeof(data), sign, &signLen), CRYPT_SUCCESS); EXIT: CRYPT_EAL_PkeyFreeCtx(pkey); } /* END_CASE */ /** * @test SDV_CRYPTO_CURVE25519_VERIFY_API_TC001 * @title CURVE25519: CRYPT_EAL_PkeyVerify test. * @precon Prepare data for verify. * @brief * 1. Create the context of the ed25519 algorithm, expected result 1. * 2. Call the CRYPT_EAL_PkeySetPrv method to set private key, expected result 2. * 3. Call the CRYPT_EAL_PkeySign method to sign, expected result 2. * 4. Call the CRYPT_EAL_PkeyVerify method, where all parameters are valid, expected result 2 * 5. Call the CRYPT_EAL_PkeyVerify method, where other parameters are valid, but : * (1) hashId != CRYPT_MD_SHA512, expected result 3 * (2) data = NULL, expected result 4 * (3) sign = NULL, expected result 4 * (4) signLen = 0 | 63 | 65, expected result 5 * @expect * 1. Success, and context is not NULL. * 2. CRYPT_SUCCESS * 3. CRYPT_EAL_ERR_ALGID * 4. CRYPT_NULL_INPUT * 5. CRYPT_CURVE25519_SIGNLEN_ERROR */ /* BEGIN_CASE */ void SDV_CRYPTO_CURVE25519_VERIFY_API_TC001(int isProvider) { uint8_t data[CRYPT_CURVE25519_KEYLEN] = {0}; uint8_t sign[CRYPT_CURVE25519_SIGNLEN] = {0}; uint32_t signLen = sizeof(sign); uint8_t key[CRYPT_CURVE25519_KEYLEN] = {0}; CRYPT_EAL_PkeyPrv prv = {0}; Set_Curve25519_Prv(&prv, CRYPT_PKEY_ED25519, key, CRYPT_CURVE25519_KEYLEN); CRYPT_EAL_PkeyPub pub = {0}; Set_Curve25519_Pub(&pub, CRYPT_PKEY_ED25519, key, CRYPT_CURVE25519_KEYLEN); TestMemInit(); CRYPT_EAL_PkeyCtx *pkey = TestPkeyNewCtx(NULL, CRYPT_PKEY_ED25519, CRYPT_EAL_PKEY_KEYMGMT_OPERATE + CRYPT_EAL_PKEY_SIGN_OPERATE, "provider=default", isProvider); ASSERT_TRUE(pkey != NULL); ASSERT_EQ(CRYPT_EAL_PkeySetPrv(pkey, &prv), CRYPT_SUCCESS); ASSERT_EQ(CRYPT_EAL_PkeySign(pkey, CRYPT_MD_SHA512, data, sizeof(data), sign, &signLen), CRYPT_SUCCESS); ASSERT_EQ(CRYPT_EAL_PkeyVerify(pkey, CRYPT_MD_SHA256, data, sizeof(data), sign, signLen), CRYPT_EAL_ERR_ALGID); ASSERT_EQ(CRYPT_EAL_PkeyVerify(pkey, CRYPT_MD_SHA512, data, sizeof(data), sign, signLen), CRYPT_SUCCESS); ASSERT_EQ(CRYPT_EAL_PkeyVerify(pkey, CRYPT_MD_SHA512, NULL, sizeof(data), sign, signLen), CRYPT_NULL_INPUT); ASSERT_EQ(CRYPT_EAL_PkeyVerify(pkey, CRYPT_MD_SHA512, data, sizeof(data), NULL, signLen), CRYPT_NULL_INPUT); signLen = 0; ASSERT_EQ(CRYPT_EAL_PkeyVerify(pkey, CRYPT_MD_SHA512, data, sizeof(data), sign, signLen), CRYPT_CURVE25519_SIGNLEN_ERROR); signLen = CRYPT_CURVE25519_SIGNLEN - 1; ASSERT_EQ(CRYPT_EAL_PkeyVerify(pkey, CRYPT_MD_SHA512, data, sizeof(data), sign, signLen), CRYPT_CURVE25519_SIGNLEN_ERROR); signLen = CRYPT_CURVE25519_SIGNLEN + 1; ASSERT_EQ(CRYPT_EAL_PkeyVerify(pkey, CRYPT_MD_SHA512, data, sizeof(data), sign, signLen), CRYPT_CURVE25519_SIGNLEN_ERROR); EXIT: CRYPT_EAL_RandDeinit(); CRYPT_EAL_PkeyFreeCtx(pkey); } /* END_CASE */ /** * @test SDV_CRYPTO_CURVE25519_DUP_CTX_API_TC001 * @title CURVE25519: CRYPT_EAL_PkeyDupCtx test. * @precon nan * @brief * 1. Create the context of the ed25519 algorithm, expected result 1. * 2. Init the drbg, expected result 2. * 3. Generate a key pair, expected result 2. * 4. Call the CRYPT_EAL_PkeyDupCtx method to dup ed25519 context, expected result 2. * 5. Call the CRYPT_EAL_PkeyGetPub method to obtain the public key from the contexts, expected result 2. * 6. Compare public keys, expected result 3. * @expect * 1. Success, and context is not NULL. * 2. CRYPT_SUCCESS * 3. The two public keys are the same. */ /* BEGIN_CASE */ void SDV_CRYPTO_CURVE25519_DUP_CTX_API_TC001(int id) { uint8_t key1[CRYPT_CURVE25519_KEYLEN] = {0}; uint8_t key2[CRYPT_CURVE25519_KEYLEN] = {0}; CRYPT_EAL_PkeyPub pub = {0}; Set_Curve25519_Pub(&pub, id, key1, CRYPT_CURVE25519_KEYLEN); TestMemInit(); CRYPT_EAL_PkeyCtx *pkey = CRYPT_EAL_PkeyNewCtx(id); ASSERT_TRUE(pkey != NULL); ASSERT_EQ(TestRandInit(), CRYPT_SUCCESS); ASSERT_EQ(CRYPT_EAL_PkeyGen(pkey), CRYPT_SUCCESS); CRYPT_EAL_PkeyCtx *newPkey = CRYPT_EAL_PkeyDupCtx(pkey); ASSERT_TRUE(newPkey != NULL); ASSERT_EQ(newPkey->references.count, 1); ASSERT_EQ(CRYPT_EAL_PkeyGetPub(pkey, &pub), CRYPT_SUCCESS); pub.key.curve25519Pub.data = key2; ASSERT_EQ(CRYPT_EAL_PkeyGetPub(newPkey, &pub), CRYPT_SUCCESS); ASSERT_COMPARE("curve25519 copy ctx", key1, CRYPT_CURVE25519_KEYLEN, key2, CRYPT_CURVE25519_KEYLEN); EXIT: TestRandDeInit(); CRYPT_EAL_PkeyFreeCtx(pkey); CRYPT_EAL_PkeyFreeCtx(newPkey); } /* END_CASE */ /** * @test SDV_CRYPTO_ED25519_SIGN_FUNC_TC001 * @title ED25519 signature test: set the key and sign. * @precon Test Vectors for Ed25519: SECRET KEY, MESSAGE(different length), SIGNATURE * @brief * 1. Create the context of the ed25519 algorithm, expected result 1. * 2. Set the private key for ed25519, expected result 2. * 3. Compute the signature of ed25519, expected result 2. * 4. Compare the signature computed by step 3 and the signature vector, expected result 3. * @expect * 1. Success, and context is not NULL. * 2. Success. * 3. The signature calculation result is the same as the signature vector. */ /* BEGIN_CASE */ void SDV_CRYPTO_ED25519_SIGN_FUNC_TC001(Hex *key, Hex *msg, Hex *sign, int isProvider) { uint8_t *out = NULL; uint32_t outLen = sizeof(out); CRYPT_EAL_PkeyPrv prv = {0}; Set_Curve25519_Prv(&prv, CRYPT_PKEY_ED25519, key->x, key->len); TestMemInit(); CRYPT_EAL_PkeyCtx *ctx = TestPkeyNewCtx(NULL, CRYPT_PKEY_ED25519, CRYPT_EAL_PKEY_KEYMGMT_OPERATE + CRYPT_EAL_PKEY_SIGN_OPERATE, "provider=default", isProvider); ASSERT_TRUE(ctx != NULL); ASSERT_EQ(CRYPT_EAL_PkeySetPrv(ctx, &prv), CRYPT_SUCCESS); outLen = CRYPT_EAL_PkeyGetSignLen(ctx); out = calloc(1u, outLen); ASSERT_TRUE(out != NULL); ASSERT_EQ(CRYPT_EAL_PkeySign(ctx, CRYPT_MD_SHA512, msg->x, msg->len, out, &outLen), CRYPT_SUCCESS); ASSERT_EQ(memcmp(out, sign->x, sign->len), 0); EXIT: CRYPT_EAL_PkeyFreeCtx(ctx); free(out); } /* END_CASE */ /** * @test SDV_CRYPTO_ED25519_VERIFY_FUNC_TC001 * @title ED25519 signature verification test: set the public key and verify the signature. * @precon Test Vectors for Ed25519: PUBLIC KEY, MESSAGE(different length), SIGNATURE * @brief * 1. Create the context of the ed25519 algorithm, expected result 1. * 2. Set the public key for ed25519, expected result 2. * 3. Verify the signature of ed25519, expected result 2. * @expect * 1. Success, and context is not NULL. * 2. Success. */ /* BEGIN_CASE */ void SDV_CRYPTO_ED25519_VERIFY_FUNC_TC001(Hex *key, Hex *msg, Hex *sign, int isProvider) { CRYPT_EAL_PkeyPub pub = {0}; Set_Curve25519_Pub(&pub, CRYPT_PKEY_ED25519, key->x, key->len); TestMemInit(); CRYPT_EAL_PkeyCtx *pkey = TestPkeyNewCtx(NULL, CRYPT_PKEY_ED25519, CRYPT_EAL_PKEY_KEYMGMT_OPERATE + CRYPT_EAL_PKEY_SIGN_OPERATE, "provider=default", isProvider); ASSERT_TRUE(pkey != NULL); ASSERT_EQ(CRYPT_EAL_PkeySetPub(pkey, &pub), CRYPT_SUCCESS); ASSERT_EQ(CRYPT_EAL_PkeyVerify(pkey, CRYPT_MD_SHA512, msg->x, msg->len, sign->x, sign->len), CRYPT_SUCCESS); EXIT: CRYPT_EAL_PkeyFreeCtx(pkey); } /* END_CASE */ /** * @test SDV_CRYPTO_ED25519_SIGN_VERIFY_FUNC_TC001 * @title ED25519: Set(or copy) the key, sign, and verify the signature. * @precon Test Vectors for Ed25519: SECRET KEY, PUBLIC KEY, MESSAGE(different length), SIGNATURE * @brief * 1. Create the context of the ed25519 algorithm, expected result 1 * 2. Set the private key for ed25519, expected result 2 * 3. Set the public key for ed25519(Public key and private key can coexist.), expected result 2 * 4. Compute the signature of ed25519, expected result 2 * 5. Compare Signatures, expected result 3. * 6. Verify the signature of ed25519, expected result 2. * 7. Copy the context of ed25519, expected result 2. * 8. Repeat steps 4 through 6 above. * @expect * 1. Success, and context is not NULL. * 2. Success. * 3. The signature calculation result is the same as the signature vector. */ /* BEGIN_CASE */ void SDV_CRYPTO_ED25519_SIGN_VERIFY_FUNC_TC001(Hex *prvKey, Hex *pubKey, Hex *msg, Hex *sign, int isProvider) { #ifndef HITLS_CRYPTO_ED25519 SKIP_TEST(); #endif uint8_t out[CRYPT_CURVE25519_SIGNLEN] = {0}; uint32_t outLen = sizeof(out); CRYPT_EAL_PkeyCtx *cpyCtx = NULL; CRYPT_EAL_PkeyPub pub = {0}; CRYPT_EAL_PkeyPrv prv = {0}; Set_Curve25519_Pub(&pub, CRYPT_PKEY_ED25519, pubKey->x, pubKey->len); Set_Curve25519_Prv(&prv, CRYPT_PKEY_ED25519, prvKey->x, prvKey->len); TestMemInit(); CRYPT_EAL_PkeyCtx *pkey = TestPkeyNewCtx(NULL, CRYPT_PKEY_ED25519, CRYPT_EAL_PKEY_KEYMGMT_OPERATE + CRYPT_EAL_PKEY_SIGN_OPERATE, "provider=default", isProvider); ASSERT_TRUE(pkey != NULL); ASSERT_EQ(CRYPT_EAL_PkeySetPrv(pkey, &prv), CRYPT_SUCCESS); ASSERT_EQ(CRYPT_EAL_PkeySetPub(pkey, &pub), CRYPT_SUCCESS); ASSERT_EQ(CRYPT_EAL_PkeySign(pkey, CRYPT_MD_SHA512, msg->x, msg->len, out, &outLen), CRYPT_SUCCESS); ASSERT_EQ(memcmp(out, sign->x, sign->len), 0); ASSERT_EQ(CRYPT_EAL_PkeyVerify(pkey, CRYPT_MD_SHA512, msg->x, msg->len, sign->x, sign->len), CRYPT_SUCCESS); cpyCtx = TestPkeyNewCtx(NULL, CRYPT_PKEY_ED25519, CRYPT_EAL_PKEY_KEYMGMT_OPERATE + CRYPT_EAL_PKEY_SIGN_OPERATE, "provider=default", isProvider); ASSERT_TRUE(cpyCtx != NULL); ASSERT_EQ(CRYPT_EAL_PkeyCopyCtx(cpyCtx, pkey), CRYPT_SUCCESS); outLen = sizeof(out); ASSERT_EQ(CRYPT_EAL_PkeySign(cpyCtx, CRYPT_MD_SHA512, msg->x, msg->len, out, &outLen), CRYPT_SUCCESS); ASSERT_EQ(memcmp(out, sign->x, sign->len), 0); ASSERT_EQ(CRYPT_EAL_PkeyVerify(cpyCtx, CRYPT_MD_SHA512, msg->x, msg->len, sign->x, sign->len), CRYPT_SUCCESS); EXIT: CRYPT_EAL_PkeyFreeCtx(pkey); CRYPT_EAL_PkeyFreeCtx(cpyCtx); } /* END_CASE */ /** * @test SDV_CRYPTO_X25519_EXCH_FUNC_TC001 * @title X25519 key exchange test: generate key pair and key exchange. * @precon nan * @brief * 1. Create two contexts(pkey1, pkey2) of the ed25519 algorithm, expected result 1. * 2. Init the drbg, expected result 2. * 3. Generate a key pair, expected result 2. * 4. Compute the shared key from the privite value in pkey1 and the public vlaue in pkey2, expected result 2. * 5. Compute the shared key from the privite value in pkey2 and the public vlaue in pkey1, expected result 2. * 6. Compare the shared keys computed in the preceding two steps, expected result 3. * @expect * 1. Success, and two contexts are not NULL. * 2. Success. * 3. The two shared keys are the same. */ /* BEGIN_CASE */ void SDV_CRYPTO_X25519_EXCH_FUNC_TC001(int isProvider) { #ifndef HITLS_CRYPTO_X25519 SKIP_TEST(); #endif uint8_t share1[CRYPT_CURVE25519_KEYLEN] = {0}; uint8_t share2[CRYPT_CURVE25519_KEYLEN] = {0}; uint32_t share1Len = sizeof(share1); uint32_t share2Len = sizeof(share2); TestMemInit(); CRYPT_EAL_PkeyCtx *pkey1 = TestPkeyNewCtx(NULL, CRYPT_PKEY_X25519, CRYPT_EAL_PKEY_KEYMGMT_OPERATE + CRYPT_EAL_PKEY_EXCH_OPERATE, "provider=default", isProvider); CRYPT_EAL_PkeyCtx *pkey2 = TestPkeyNewCtx(NULL, CRYPT_PKEY_X25519, CRYPT_EAL_PKEY_KEYMGMT_OPERATE + CRYPT_EAL_PKEY_EXCH_OPERATE, "provider=default", isProvider); ASSERT_TRUE(pkey1 != NULL && pkey2 != NULL); // Sets the entropy source. ASSERT_EQ(TestRandInit(), CRYPT_SUCCESS); ASSERT_EQ(CRYPT_EAL_PkeyGen(pkey1), CRYPT_SUCCESS); ASSERT_EQ(CRYPT_EAL_PkeyGen(pkey2), CRYPT_SUCCESS); ASSERT_EQ(CRYPT_EAL_PkeyComputeShareKey(pkey1, pkey2, share1, &share1Len), CRYPT_SUCCESS); ASSERT_EQ(CRYPT_EAL_PkeyComputeShareKey(pkey2, pkey1, share2, &share2Len), CRYPT_SUCCESS); ASSERT_EQ(share1Len, share2Len); ASSERT_EQ(memcmp(share1, share2, share1Len), 0); EXIT: TestRandDeInit(); CRYPT_EAL_PkeyFreeCtx(pkey1); CRYPT_EAL_PkeyFreeCtx(pkey2); } /* END_CASE */ /** * @test SDV_CRYPTO_X25519_EXCH_FUNC_TC002 * @title X25519 key exchange test: set the key or copy the context, and exchange the key. * @precon Test Vectors for X25519: One's public key, The other's private key, Their shared key * @brief * 1. Create two contexts(pkey1, pkey2) of the X25519 algorithm, expected result 1. * 2. Set the public key and private key for pkey1 and pkey2, expected result 2. * 3. Compute the shared key from the privite value in pkey1 and the public vlaue in pkey2, expected result 2. * 4. Compare the shared key computed by step 5 and the share secret vector, expected result 3. * 5. Copy the two contexts, expected result 2. * 6. Repeat steps 3 and 4 above. * @expect * 1. Success, and two contexts are not NULL. * 2. Success. * 3. The two shared keys are the same. */ /* BEGIN_CASE */ void SDV_CRYPTO_X25519_EXCH_FUNC_TC002(Hex *pubkey, Hex *prvkey, Hex *share, int isProvider) { #ifndef HITLS_CRYPTO_X25519 SKIP_TEST(); #endif uint8_t shareKey[CRYPT_CURVE25519_KEYLEN]; uint32_t shareLen = sizeof(shareKey); CRYPT_EAL_PkeyCtx *cpyCtx1 = NULL; CRYPT_EAL_PkeyCtx *cpyCtx2 = NULL; CRYPT_EAL_PkeyPub pub = {0}; CRYPT_EAL_PkeyPrv prv = {0}; Set_Curve25519_Pub(&pub, CRYPT_PKEY_X25519, pubkey->x, pubkey->len); Set_Curve25519_Prv(&prv, CRYPT_PKEY_X25519, prvkey->x, prvkey->len); TestMemInit(); CRYPT_EAL_PkeyCtx *pkey1 = TestPkeyNewCtx(NULL, CRYPT_PKEY_X25519, CRYPT_EAL_PKEY_KEYMGMT_OPERATE + CRYPT_EAL_PKEY_EXCH_OPERATE, "provider=default", isProvider); CRYPT_EAL_PkeyCtx *pkey2 = TestPkeyNewCtx(NULL, CRYPT_PKEY_X25519, CRYPT_EAL_PKEY_KEYMGMT_OPERATE + CRYPT_EAL_PKEY_EXCH_OPERATE, "provider=default", isProvider); ASSERT_TRUE(pkey1 != NULL && pkey2 != NULL); ASSERT_EQ(CRYPT_EAL_PkeySetPrv(pkey1, &prv), CRYPT_SUCCESS); ASSERT_EQ(CRYPT_EAL_PkeySetPub(pkey1, &pub), CRYPT_SUCCESS); ASSERT_EQ(CRYPT_EAL_PkeySetPub(pkey2, &pub), CRYPT_SUCCESS); ASSERT_EQ(CRYPT_EAL_PkeySetPrv(pkey2, &prv), CRYPT_SUCCESS); ASSERT_EQ(CRYPT_EAL_PkeyComputeShareKey(pkey1, pkey2, shareKey, &shareLen), CRYPT_SUCCESS); ASSERT_EQ(shareLen, share->len); ASSERT_EQ(memcmp(shareKey, share->x, shareLen), 0); cpyCtx1 = TestPkeyNewCtx(NULL, CRYPT_PKEY_X25519, CRYPT_EAL_PKEY_KEYMGMT_OPERATE + CRYPT_EAL_PKEY_EXCH_OPERATE, "provider=default", isProvider); cpyCtx2 = TestPkeyNewCtx(NULL, CRYPT_PKEY_X25519, CRYPT_EAL_PKEY_KEYMGMT_OPERATE + CRYPT_EAL_PKEY_EXCH_OPERATE, "provider=default", isProvider); ASSERT_TRUE(cpyCtx1 != NULL && cpyCtx2 != NULL); ASSERT_EQ(CRYPT_EAL_PkeyCopyCtx(cpyCtx1, pkey1), CRYPT_SUCCESS); ASSERT_EQ(CRYPT_EAL_PkeyCopyCtx(cpyCtx2, pkey2), CRYPT_SUCCESS); shareLen = sizeof(shareKey); ASSERT_EQ(CRYPT_EAL_PkeyComputeShareKey(cpyCtx1, cpyCtx2, shareKey, &shareLen), CRYPT_SUCCESS); ASSERT_EQ(shareLen, share->len); ASSERT_EQ(memcmp(shareKey, share->x, shareLen), 0); EXIT: CRYPT_EAL_PkeyFreeCtx(pkey1); CRYPT_EAL_PkeyFreeCtx(pkey2); CRYPT_EAL_PkeyFreeCtx(cpyCtx1); CRYPT_EAL_PkeyFreeCtx(cpyCtx2); } /* END_CASE */ /** * @test SDV_CRYPTO_CURVE25519_CMP_FUNC_TC001 * @title Curve25519: The input and output parameters address are the same. * @precon Vector: private key and public key. * @brief * 1. Create the contexts(ctx1, ctx2) of the curve25519 algorithm, expected result 1 * 2. Call the CRYPT_EAL_PkeyCmp to compare ctx1 and ctx2, expected result 2 * 3. Set public key for ctx1, expected result 3 * 4. Call the CRYPT_EAL_PkeyCmp to compare ctx1 and ctx2, expected result 4 * 5. Set public key for ctx2, expected result 5 * 6. Call the CRYPT_EAL_PkeyCmp to compare ctx1 and ctx2, expected result 6 * @expect * 1. Success, and contexts are not NULL. * 2. CRYPT_ECC_KEY_PUBKEY_NOT_EQUAL * 3. CRYPT_SUCCESS * 4. CRYPT_ECC_KEY_PUBKEY_NOT_EQUAL * 5-6. CRYPT_SUCCESS */ /* BEGIN_CASE */ void SDV_CRYPTO_CURVE25519_CMP_FUNC_TC001(int algId, Hex *pubKey, int isProvider) { CRYPT_EAL_PkeyPub pub = {0}; Set_Curve25519_Pub(&pub, algId, pubKey->x, pubKey->len); TestMemInit(); CRYPT_EAL_PkeyCtx *ctx1 = TestPkeyNewCtx(NULL, algId, CRYPT_EAL_PKEY_KEYMGMT_OPERATE, "provider=default", isProvider); CRYPT_EAL_PkeyCtx *ctx2 = TestPkeyNewCtx(NULL, algId, CRYPT_EAL_PKEY_KEYMGMT_OPERATE, "provider=default", isProvider); ASSERT_TRUE(ctx1 != NULL && ctx2 != NULL); ASSERT_EQ(CRYPT_EAL_PkeyCmp(ctx1, ctx2), CRYPT_CURVE25519_NO_PUBKEY); ASSERT_EQ(CRYPT_EAL_PkeySetPub(ctx1, &pub), CRYPT_SUCCESS); ASSERT_EQ(CRYPT_EAL_PkeyCmp(ctx1, ctx2), CRYPT_CURVE25519_NO_PUBKEY); ASSERT_EQ(CRYPT_EAL_PkeySetPub(ctx2, &pub), CRYPT_SUCCESS); ASSERT_EQ(CRYPT_EAL_PkeyCmp(ctx1, ctx2), CRYPT_SUCCESS); EXIT: CRYPT_EAL_PkeyFreeCtx(ctx1); CRYPT_EAL_PkeyFreeCtx(ctx2); } /* END_CASE */ /** * @test SDV_CRYPTO_ED25519_KEY_PAIR_CHECK_FUNC_TC001 * @title Ed25519: key pair check. * @precon Registering memory-related functions. * @brief * 1. Create two contexts(pubCtx, prvCtx) of the ed25519 algorithm, expected result 1 * 2. Set public key for pubCtx, expected result 2 * 3. Set private key for prvCtx, expected result 3 * 4. Check whether the public key matches the private key, expected result 4 * @expect * 1. Success, and contexts are not NULL. * 2. CRYPT_SUCCESS * 3. CRYPT_SUCCESS * 4. Return CRYPT_SUCCESS when expect is 1, CRYPT_CURVE25519_VERIFY_FAIL otherwise. */ /* BEGIN_CASE */ void SDV_CRYPTO_ED25519_KEY_PAIR_CHECK_FUNC_TC001(Hex *pubkey, Hex *prvkey, int expect, int isProvider) { #if !defined(HITLS_CRYPTO_ED25519_CHECK) (void)prvkey; (void)pubkey; (void)expect; (void)isProvider; SKIP_TEST(); #else CRYPT_EAL_PkeyCtx *pubCtx = NULL; CRYPT_EAL_PkeyCtx *prvCtx = NULL; CRYPT_EAL_PkeyPub pub = {0}; CRYPT_EAL_PkeyPrv prv = {0}; int expectRet = expect == 1 ? CRYPT_SUCCESS : CRYPT_CURVE25519_PAIRWISE_CHECK_FAIL; Set_Curve25519_Prv(&prv, CRYPT_PKEY_ED25519, prvkey->x, prvkey->len); Set_Curve25519_Pub(&pub, CRYPT_PKEY_ED25519, pubkey->x, pubkey->len); TestMemInit(); pubCtx = TestPkeyNewCtx(NULL, CRYPT_PKEY_ED25519, CRYPT_EAL_PKEY_KEYMGMT_OPERATE + CRYPT_EAL_PKEY_SIGN_OPERATE, "provider=default", isProvider); prvCtx = TestPkeyNewCtx(NULL, CRYPT_PKEY_ED25519, CRYPT_EAL_PKEY_KEYMGMT_OPERATE + CRYPT_EAL_PKEY_SIGN_OPERATE, "provider=default", isProvider); ASSERT_TRUE(pubCtx != NULL && prvCtx != NULL); ASSERT_EQ(CRYPT_EAL_PkeySetPub(pubCtx, &pub), CRYPT_SUCCESS); ASSERT_EQ(CRYPT_EAL_PkeySetPrv(prvCtx, &prv), CRYPT_SUCCESS); ASSERT_EQ(CRYPT_EAL_PkeyPairCheck(pubCtx, prvCtx), expectRet); EXIT: CRYPT_EAL_PkeyFreeCtx(pubCtx); CRYPT_EAL_PkeyFreeCtx(prvCtx); #endif } /* END_CASE */ /** * @test SDV_CRYPTO_CURVE25519_GET_KEY_BITS_FUNC_TC001 * @title CURVE25519: get key bits. * @brief * 1. Create a context of the Curve25519 algorithm, expected result 1 * 2. Get key bits, expected result 2 * @expect * 1. Success, and context is not NULL. * 2. Equal to keyBits. */ /* BEGIN_CASE */ void SDV_CRYPTO_CURVE25519_GET_KEY_BITS_FUNC_TC001(int id, int keyBits, int isProvider) { CRYPT_EAL_PkeyCtx *pkey = TestPkeyNewCtx(NULL, id, CRYPT_EAL_PKEY_KEYMGMT_OPERATE, "provider=default", isProvider); ASSERT_TRUE(pkey != NULL); ASSERT_TRUE(CRYPT_EAL_PkeyGetKeyBits(pkey) == (uint32_t)keyBits); EXIT: CRYPT_EAL_PkeyFreeCtx(pkey); } /* END_CASE */ /** * @test SDV_CRYPTO_CURVE25519_GET_SECURITY_BITS_FUNC_TC001 * @title CURVE25519 CRYPT_EAL_PkeyGetSecurityBits test. * @precon nan * @brief * 1. Create the context of the X25519 algorithm, expected result 1 * 2. Call the CRYPT_EAL_PkeyGetSecurityBits Obtains secbits, expected result 2 * @expect * 1. Success, and the context is not null. * 2. The return value is secBits. */ /* BEGIN_CASE */ void SDV_CRYPTO_CURVE25519_GET_SECURITY_BITS_FUNC_TC001(int id, int secBits) { CRYPT_EAL_PkeyCtx *pkey = CRYPT_EAL_PkeyNewCtx(id); ASSERT_TRUE(pkey != NULL); ASSERT_TRUE(CRYPT_EAL_PkeyGetSecurityBits(pkey) == (uint32_t)secBits); EXIT: CRYPT_EAL_PkeyFreeCtx(pkey); } /* END_CASE */ /** * @test SDV_CRYPTO_CURVE25519_KEY_PAIR_CHECK_FUNC_TC001 * @brief CURVE25519: key pair check. */ /* BEGIN_CASE */ void SDV_CRYPTO_CURVE25519_KEY_PAIR_CHECK_FUNC_TC001(int id, int isProvider) { #if !defined(HITLS_CRYPTO_ED25519_CHECK) && !defined(HITLS_CRYPTO_X25519_CHECK) (void)id; (void)isProvider; SKIP_TEST(); #else CRYPT_EAL_PkeyCtx *pubCtx = NULL; CRYPT_EAL_PkeyCtx *prvCtx = NULL; TestMemInit(); ASSERT_EQ(TestRandInit(), CRYPT_SUCCESS); pubCtx = TestPkeyNewCtx(NULL, id, CRYPT_EAL_PKEY_KEYMGMT_OPERATE, "provider=default", isProvider); prvCtx = TestPkeyNewCtx(NULL, id, CRYPT_EAL_PKEY_KEYMGMT_OPERATE, "provider=default", isProvider); ASSERT_TRUE(pubCtx != NULL && prvCtx != NULL); ASSERT_EQ(CRYPT_EAL_PkeyPairCheck(NULL, NULL), CRYPT_NULL_INPUT); ASSERT_EQ(CRYPT_EAL_PkeyPairCheck(pubCtx, prvCtx), CRYPT_CURVE25519_NO_PRVKEY); // no prv key and pub key. ASSERT_EQ(CRYPT_EAL_PkeyGen(prvCtx), CRYPT_SUCCESS); ASSERT_EQ(CRYPT_EAL_PkeyPairCheck(pubCtx, prvCtx), CRYPT_CURVE25519_NO_PUBKEY); // no pub key ASSERT_EQ(CRYPT_EAL_PkeyGen(pubCtx), CRYPT_SUCCESS); ASSERT_EQ(CRYPT_EAL_PkeyPairCheck(pubCtx, prvCtx), CRYPT_CURVE25519_PAIRWISE_CHECK_FAIL); ASSERT_EQ(CRYPT_EAL_PkeyPairCheck(prvCtx, prvCtx), CRYPT_SUCCESS); ASSERT_EQ(CRYPT_EAL_PkeyPairCheck(pubCtx, pubCtx), CRYPT_SUCCESS); EXIT: TestRandDeInit(); CRYPT_EAL_PkeyFreeCtx(pubCtx); CRYPT_EAL_PkeyFreeCtx(prvCtx); #endif } /* END_CASE */ /** * @test SDV_CRYPTO_CURVE25519_PRV_KEY_CHECK_FUNC_TC001 * @brief CURE25519: private key check. */ /* BEGIN_CASE */ void SDV_CRYPTO_CURVE25519_PRV_KEY_CHECK_FUNC_TC001(int id, int isProvider) { #if !defined(HITLS_CRYPTO_ED25519_CHECK) && !defined(HITLS_CRYPTO_X25519_CHECK) (void)id; (void)isProvider; SKIP_TEST(); #else TestMemInit(); ASSERT_EQ(TestRandInit(), CRYPT_SUCCESS); CRYPT_CURVE25519_Ctx *ctx = NULL; CRYPT_EAL_PkeyCtx *pkey = TestPkeyNewCtx(NULL, id, CRYPT_EAL_PKEY_KEYMGMT_OPERATE, "provider=default", isProvider); ASSERT_TRUE(pkey != NULL); ASSERT_EQ(CRYPT_EAL_PkeyPrvCheck(NULL), CRYPT_NULL_INPUT); ASSERT_EQ(CRYPT_EAL_PkeyPrvCheck(pkey), CRYPT_CURVE25519_NO_PRVKEY); ASSERT_EQ(CRYPT_EAL_PkeyGen(pkey), CRYPT_SUCCESS); ASSERT_EQ(CRYPT_EAL_PkeyPrvCheck(pkey), CRYPT_SUCCESS); ctx = (CRYPT_CURVE25519_Ctx *)pkey->key; (void)memset_s(ctx->prvKey, CRYPT_CURVE25519_KEYLEN, 0, CRYPT_CURVE25519_KEYLEN); ASSERT_EQ(CRYPT_EAL_PkeyPrvCheck(pkey), CRYPT_CURVE25519_INVALID_PRVKEY); EXIT: TestRandDeInit(); CRYPT_EAL_PkeyFreeCtx(pkey); #endif } /* END_CASE */
2301_79861745/bench_create
testcode/sdv/testcase/crypto/curve25519/test_suite_sdv_eal_curve25519.c
C
unknown
40,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 <stdint.h> #include <stdbool.h> #include "securec.h" #include "bsl_sal.h" #include "crypt_algid.h" #include "crypt_types.h" #include "crypt_eal_pkey.h" #include "crypt_errno.h" #include "crypt_eal_rand.h" #include "crypt_util_rand.h" #include "crypt_bn.h" #include "dh_local.h" #include "crypt_dh.h" #include "eal_pkey_local.h" #define UINT8_MAX_NUM 255 #define CRYPT_EAL_PKEY_KEYMGMT_OPERATE 0 static int32_t RandFunc(uint8_t *randNum, uint32_t randLen) { for (uint32_t i = 0; i < randLen; i++) { randNum[i] = (uint8_t)(rand() % UINT8_MAX_NUM); } return 0; } static int32_t RandFuncEx(void *libCtx, uint8_t *randNum, uint32_t randLen) { (void)libCtx; for (uint32_t i = 0; i < randLen; i++) { randNum[i] = (uint8_t)(rand() % UINT8_MAX_NUM); } return 0; } static void Set_DH_Para( CRYPT_EAL_PkeyPara *para, uint8_t *p, uint8_t *q, uint8_t *g, uint32_t pLen, uint32_t qLen, uint32_t gLen) { para->id = CRYPT_PKEY_DH; para->para.dhPara.p = p; para->para.dhPara.q = q; para->para.dhPara.g = g; para->para.dhPara.pLen = pLen; para->para.dhPara.qLen = qLen; para->para.dhPara.gLen = gLen; } static void Set_DH_Prv(CRYPT_EAL_PkeyPrv *prv, uint8_t *key, uint32_t keyLen) { prv->id = CRYPT_PKEY_DH; prv->key.dhPrv.data = key; prv->key.dhPrv.len = keyLen; } static void Set_DH_Pub(CRYPT_EAL_PkeyPub *pub, uint8_t *key, uint32_t keyLen) { pub->id = CRYPT_PKEY_DH; pub->key.dhPub.data = key; pub->key.dhPub.len = keyLen; } /* END_HEADER */ /** * @test SDV_CRYPTO_DH_FUNC_TC001 * @title DH Key exchange vector test. * @precon Registering memory-related functions. * NIST test vectors. * @brief * 1. Create the contexts(pkey1, pkey2) of the dh algorithm, expected result 1 * 2. Set parameters for pkey1, expected result 2 * 3. Call the CRYPT_EAL_PkeyComputeShareKey method: pkey1(A.prvKey) and pkey2(B.pubKey), expected result 3 * 4. Check whether the generated key is consistent with the vector, expected result 4 * 5. Call the CRYPT_EAL_PkeyComputeShareKey method: pkey1(B.prvKey) and pkey2(A.pubKey), expected result 5 * 6. Check whether the generated key is consistent with the vector, expected result 6 * @expect * 1. Success, and context is not NULL. * 2. CRYPT_SUCCESS * 3. CRYPT_SUCCESS * 4. Both are consistent. * 5. CRYPT_SUCCESS * 6. Both are consistent. */ /* BEGIN_CASE */ void SDV_CRYPTO_DH_FUNC_TC001( Hex *p, Hex *g, Hex *q, Hex *prv1, Hex *pub1, Hex *prv2, Hex *pub2, Hex *share, int isProvider) { CRYPT_RandRegist(RandFunc); CRYPT_RandRegistEx(RandFuncEx); uint8_t shareLocal[1030]; uint32_t shareLen = sizeof(shareLocal); CRYPT_EAL_PkeyPara para = {0}; CRYPT_EAL_PkeyPrv prv = {0}; CRYPT_EAL_PkeyPub pub = {0}; Set_DH_Para(&para, p->x, q->x, g->x, p->len, q->len, g->len); Set_DH_Prv(&prv, prv1->x, prv1->len); Set_DH_Pub(&pub, pub2->x, pub2->len); TestMemInit(); CRYPT_EAL_PkeyCtx *pkey1 = TestPkeyNewCtx(NULL, CRYPT_PKEY_DH, CRYPT_EAL_PKEY_KEYMGMT_OPERATE + CRYPT_EAL_PKEY_EXCH_OPERATE, "provider=default", isProvider); CRYPT_EAL_PkeyCtx *pkey2 = TestPkeyNewCtx(NULL, CRYPT_PKEY_DH, CRYPT_EAL_PKEY_KEYMGMT_OPERATE + CRYPT_EAL_PKEY_EXCH_OPERATE, "provider=default", isProvider); ASSERT_TRUE(pkey1 != NULL && pkey2 != NULL); ASSERT_TRUE(CRYPT_EAL_PkeySetPara(pkey1, &para) == CRYPT_SUCCESS); ASSERT_TRUE(CRYPT_EAL_PkeySetPrv(pkey1, &prv) == CRYPT_SUCCESS); ASSERT_TRUE(CRYPT_EAL_PkeySetPub(pkey2, &pub) == CRYPT_SUCCESS); ASSERT_TRUE(CRYPT_EAL_PkeyComputeShareKey(pkey1, pkey2, shareLocal, &shareLen) == CRYPT_SUCCESS); ASSERT_TRUE(shareLen == share->len); ASSERT_TRUE(memcmp(shareLocal, share->x, shareLen) == 0); Set_DH_Prv(&prv, prv2->x, prv2->len); Set_DH_Pub(&pub, pub1->x, pub1->len); ASSERT_TRUE(CRYPT_EAL_PkeySetPrv(pkey1, &prv) == CRYPT_SUCCESS); ASSERT_TRUE(CRYPT_EAL_PkeySetPub(pkey2, &pub) == CRYPT_SUCCESS); ASSERT_TRUE(CRYPT_EAL_PkeyComputeShareKey(pkey1, pkey2, shareLocal, &shareLen) == CRYPT_SUCCESS); ASSERT_TRUE(shareLen == share->len); ASSERT_TRUE(memcmp(shareLocal, share->x, shareLen) == 0); EXIT: CRYPT_EAL_PkeyFreeCtx(pkey1); CRYPT_EAL_PkeyFreeCtx(pkey2); } /* END_CASE */ /** * @test SDV_CRYPTO_DH_FUNC_TC002 * @title DH Key exchange test: Generate key pairs. * @precon Registering memory-related functions. * Nist test vectors: DH parameters. * @brief * 1. Create the contexts(pkey1, pkey2) of the dh algorithm, expected result 1 * 2. Set parameters for pkey1 and pkey2, expected result 2 * 3. Generate key pairs, expected result 2 * 4. Compute the shared key from the privite value in pkey1 and the public vlaue in peky2, expected result 2. * 5. Compute the shared key from the privite value in pkey2 and the public vlaue in pkey1, expected result 2. * 6. Compare the shared keys computed in the preceding two steps, expected result 3. * @expect * 1. Success, and context is not NULL. * 2. CRYPT_SUCCESS * 3. The two shared keys are the same. */ /* BEGIN_CASE */ void SDV_CRYPTO_DH_FUNC_TC002(Hex *p, Hex *g, Hex *q, int isProvider) { CRYPT_RandRegist(RandFunc); CRYPT_RandRegistEx(RandFuncEx); uint8_t share1[1030]; uint8_t share2[1030]; uint32_t share1Len = sizeof(share1); uint32_t share2Len = sizeof(share2); CRYPT_EAL_PkeyPara para = {0}; Set_DH_Para(&para, p->x, q->x, g->x, p->len, q->len, g->len); TestMemInit(); CRYPT_EAL_PkeyCtx *pkey1 = TestPkeyNewCtx(NULL, CRYPT_PKEY_DH, CRYPT_EAL_PKEY_KEYMGMT_OPERATE + CRYPT_EAL_PKEY_EXCH_OPERATE, "provider=default", isProvider); CRYPT_EAL_PkeyCtx *pkey2 = TestPkeyNewCtx(NULL, CRYPT_PKEY_DH, CRYPT_EAL_PKEY_KEYMGMT_OPERATE + CRYPT_EAL_PKEY_EXCH_OPERATE, "provider=default", isProvider); ASSERT_TRUE(pkey1 != NULL && pkey2 != NULL); ASSERT_TRUE(CRYPT_EAL_PkeySetPara(pkey1, &para) == CRYPT_SUCCESS); ASSERT_TRUE(CRYPT_EAL_PkeySetPara(pkey2, &para) == CRYPT_SUCCESS); ASSERT_TRUE(CRYPT_EAL_PkeyGen(pkey1) == CRYPT_SUCCESS); ASSERT_TRUE(CRYPT_EAL_PkeyGen(pkey2) == CRYPT_SUCCESS); ASSERT_TRUE(CRYPT_EAL_PkeyComputeShareKey(pkey1, pkey2, share1, &share1Len) == CRYPT_SUCCESS); ASSERT_TRUE(CRYPT_EAL_PkeyComputeShareKey(pkey2, pkey1, share2, &share2Len) == CRYPT_SUCCESS); ASSERT_TRUE(share1Len == share2Len); ASSERT_TRUE(memcmp(share1, share2, share1Len) == 0); EXIT: CRYPT_RandRegist(NULL); CRYPT_RandRegistEx(NULL); CRYPT_EAL_PkeyFreeCtx(pkey1); CRYPT_EAL_PkeyFreeCtx(pkey2); } /* END_CASE */ /** * @test SDV_CRYPTO_DH_FUNC_TC003 * @title DH Key exchange test: Set parameters based on the ID to generate key pairs. * @precon Registering memory-related functions. * @brief * 1. Create the contexts(pkey1, pkey2) of the dh algorithm, expected result 1 * 2. Set parameters byt id for pkey1 and pkey2, expected result 2 * 3. Generate key pairs, expected result 2 * 4. Compute the shared key from the privite value in pkey1 and the public vlaue in peky2, expected result 2. * 5. Compute the shared key from the privite value in pkey2 and the public vlaue in pkey1, expected result 2. * 6. Compare the shared keys computed in the preceding two steps, expected result 3. * @expect * 1. Success, and context is not NULL. * 2. CRYPT_SUCCESS * 3. The two shared keys are the same. */ /* BEGIN_CASE */ void SDV_CRYPTO_DH_FUNC_TC003(int id, int isProvider) { uint8_t share1[1030]; uint8_t share2[1030]; uint32_t share1Len = sizeof(share1); uint32_t share2Len = sizeof(share2); CRYPT_RandRegist(RandFunc); CRYPT_RandRegistEx(RandFuncEx); TestMemInit(); CRYPT_EAL_PkeyCtx *pkey1 = TestPkeyNewCtx(NULL, CRYPT_PKEY_DH, CRYPT_EAL_PKEY_KEYMGMT_OPERATE + CRYPT_EAL_PKEY_EXCH_OPERATE, "provider=default", isProvider); CRYPT_EAL_PkeyCtx *pkey2 = TestPkeyNewCtx(NULL, CRYPT_PKEY_DH, CRYPT_EAL_PKEY_KEYMGMT_OPERATE + CRYPT_EAL_PKEY_EXCH_OPERATE, "provider=default", isProvider); ASSERT_TRUE(pkey1 != NULL && pkey2 != NULL); ASSERT_TRUE(CRYPT_EAL_PkeySetParaById(pkey1, id) == CRYPT_SUCCESS); ASSERT_TRUE(CRYPT_EAL_PkeySetParaById(pkey2, id) == CRYPT_SUCCESS); ASSERT_TRUE(CRYPT_EAL_PkeyGen(pkey1) == CRYPT_SUCCESS); ASSERT_TRUE(CRYPT_EAL_PkeyGen(pkey2) == CRYPT_SUCCESS); ASSERT_TRUE(CRYPT_EAL_PkeyComputeShareKey(pkey1, pkey2, share1, &share1Len) == CRYPT_SUCCESS); ASSERT_TRUE(CRYPT_EAL_PkeyComputeShareKey(pkey2, pkey1, share2, &share2Len) == CRYPT_SUCCESS); ASSERT_TRUE(share1Len == share2Len); ASSERT_TRUE(memcmp(share1, share2, share1Len) == 0); EXIT: CRYPT_RandRegist(NULL); CRYPT_RandRegistEx(NULL); CRYPT_EAL_PkeyFreeCtx(pkey1); CRYPT_EAL_PkeyFreeCtx(pkey2); } /* END_CASE */ /** * @test SDV_CRYPTO_DH_FUNC_TC004 * @title DH Key exchange test: Generate a key pair repeatedly. * @precon Registering memory-related functions. * Nist test vectors: DH parameters. * @brief * 1. Create the contexts(pkey1, pkey2) of the dh algorithm, expected result 1 * 2. Set parameters for pkey1 and pkey2, expected result 2 * 3. Generate a key pair repeatedly, expected result 2 * 4. Compute the shared key from the privite value in pkey1 and the public vlaue in peky2, expected result 2. * 5. Compute the shared key from the privite value in pkey2 and the public vlaue in pkey1, expected result 2. * 6. Compare the shared keys computed in the preceding two steps, expected result 3. * @expect * 1. Success, and context is not NULL. * 2. CRYPT_SUCCESS * 3. The two shared keys are the same. */ /* BEGIN_CASE */ void SDV_CRYPTO_DH_FUNC_TC004(Hex *p, Hex *g, Hex *q, int isProvider) { CRYPT_RandRegist(RandFunc); CRYPT_RandRegistEx(RandFuncEx); uint8_t share1[1030]; uint8_t share2[1030]; uint32_t share1Len = sizeof(share1); uint32_t share2Len = sizeof(share2); CRYPT_EAL_PkeyPara para = {0}; Set_DH_Para(&para, p->x, q->x, g->x, p->len, q->len, g->len); TestMemInit(); CRYPT_EAL_PkeyCtx *pkey1 = TestPkeyNewCtx(NULL, CRYPT_PKEY_DH, CRYPT_EAL_PKEY_KEYMGMT_OPERATE + CRYPT_EAL_PKEY_EXCH_OPERATE, "provider=default", isProvider); CRYPT_EAL_PkeyCtx *pkey2 = TestPkeyNewCtx(NULL, CRYPT_PKEY_DH, CRYPT_EAL_PKEY_KEYMGMT_OPERATE + CRYPT_EAL_PKEY_EXCH_OPERATE, "provider=default", isProvider); ASSERT_TRUE(pkey1 != NULL && pkey2 != NULL); ASSERT_TRUE(CRYPT_EAL_PkeySetPara(pkey1, &para) == CRYPT_SUCCESS); ASSERT_TRUE(CRYPT_EAL_PkeySetPara(pkey2, &para) == CRYPT_SUCCESS); ASSERT_TRUE(CRYPT_EAL_PkeyGen(pkey1) == CRYPT_SUCCESS); ASSERT_TRUE(CRYPT_EAL_PkeyGen(pkey2) == CRYPT_SUCCESS); ASSERT_TRUE(CRYPT_EAL_PkeyGen(pkey1) == CRYPT_SUCCESS); ASSERT_TRUE(CRYPT_EAL_PkeyGen(pkey2) == CRYPT_SUCCESS); ASSERT_TRUE(CRYPT_EAL_PkeyComputeShareKey(pkey1, pkey2, share1, &share1Len) == CRYPT_SUCCESS); ASSERT_TRUE(CRYPT_EAL_PkeyComputeShareKey(pkey2, pkey1, share2, &share2Len) == CRYPT_SUCCESS); ASSERT_TRUE(share1Len == share2Len); ASSERT_TRUE(memcmp(share1, share2, share1Len) == 0); EXIT: CRYPT_RandRegist(NULL); CRYPT_RandRegistEx(NULL); CRYPT_EAL_PkeyFreeCtx(pkey1); CRYPT_EAL_PkeyFreeCtx(pkey2); } /* END_CASE */ /** * @test SDV_CRYPTO_DH_FUNC_TC005 * @title DH Key exchange failed. The public key is invalid. * @precon Registering memory-related functions. * Nist test vectors: DH parameters, private key, public key. * @brief * 1. Create the contexts(pkey1, pkey2) of the dh algorithm, expected result 1. * 2. Set parameters for pkey1, expected result 2 * 3. Call the CRYPT_EAL_PkeyComputeShareKey method: * (1) pkey1(valid prvKey), pkey2(pubKey = p - 1), expected result 3 * (2) pkey1(valid prvKey), pkey2(pubKey ^ q mod p != 1), expected result 3 * (3) pkey1(valid prvKey), pkey2(pubKey = 0), expected result 3 * (4) pkey1(valid prvKey), pkey2(pubKey = 1), expected result 3 * @expect * 1. Success, and contexts are not NULL. * 2. CRYPT_SUCCESS * 3. CRYPT_DH_KEYINFO_ERROR */ /* BEGIN_CASE */ void SDV_CRYPTO_DH_FUNC_TC005(Hex *p, Hex *g, Hex *q, Hex *prv1, int isProvider) { uint8_t shareLocal[1030]; uint32_t shareLen = sizeof(shareLocal); CRYPT_EAL_PkeyPara para = {0}; CRYPT_EAL_PkeyPrv prv = {0}; CRYPT_EAL_PkeyPub pub = {0}; uint8_t *tmpPub = (uint8_t *)malloc(sizeof(uint8_t) * p->len); ASSERT_TRUE(tmpPub != NULL); ASSERT_TRUE(memcpy_s(tmpPub, p->len, p->x, p->len) == 0); int last = p->len - 1; tmpPub[last] -= 1; // pubKey = p - 1 Set_DH_Prv(&prv, prv1->x, prv1->len); Set_DH_Pub(&pub, tmpPub, p->len); Set_DH_Para(&para, p->x, q->x, g->x, p->len, q->len, g->len); TestMemInit(); CRYPT_EAL_PkeyCtx *pkey1 = TestPkeyNewCtx(NULL, CRYPT_PKEY_DH, CRYPT_EAL_PKEY_KEYMGMT_OPERATE + CRYPT_EAL_PKEY_EXCH_OPERATE, "provider=default", isProvider); CRYPT_EAL_PkeyCtx *pkey2 = TestPkeyNewCtx(NULL, CRYPT_PKEY_DH, CRYPT_EAL_PKEY_KEYMGMT_OPERATE + CRYPT_EAL_PKEY_EXCH_OPERATE, "provider=default", isProvider); ASSERT_TRUE(pkey1 != NULL && pkey2 != NULL); ASSERT_TRUE(CRYPT_EAL_PkeySetPara(pkey1, &para) == CRYPT_SUCCESS); ASSERT_TRUE(CRYPT_EAL_PkeySetPrv(pkey1, &prv) == CRYPT_SUCCESS); ASSERT_TRUE(CRYPT_EAL_PkeySetPub(pkey2, &pub) == CRYPT_SUCCESS); ASSERT_EQ(CRYPT_EAL_PkeyComputeShareKey(pkey1, pkey2, shareLocal, &shareLen), CRYPT_DH_KEYINFO_ERROR); ASSERT_TRUE(memset_s(tmpPub, p->len, 0, p->len) == 0); // pubKey = 0; ASSERT_TRUE(CRYPT_EAL_PkeySetPub(pkey2, &pub) == CRYPT_SUCCESS); ASSERT_EQ(CRYPT_EAL_PkeyComputeShareKey(pkey1, pkey2, shareLocal, &shareLen), CRYPT_DH_KEYINFO_ERROR); tmpPub[last] = 1; // pubKey = 1 ASSERT_TRUE(CRYPT_EAL_PkeySetPub(pkey2, &pub) == CRYPT_SUCCESS); ASSERT_EQ(CRYPT_EAL_PkeyComputeShareKey(pkey1, pkey2, shareLocal, &shareLen), CRYPT_DH_KEYINFO_ERROR); EXIT: CRYPT_EAL_PkeyFreeCtx(pkey1); CRYPT_EAL_PkeyFreeCtx(pkey2); if (tmpPub != NULL) { free(tmpPub); } } /* END_CASE */ /** * @test SDV_CRYPTO_DH_FUNC_TC006 * @title Key exchange failure vector test, invalid vector. * @precon Registering memory-related functions. * NIST test vectors. * @brief * 1. Create the contexts(pkey1, pkey2) of the dh algorithm, expected result 1. * 2. Set parameters for pkey1, expected result 2 * 3. Call the CRYPT_EAL_PkeyComputeShareKey method: pkey1(A.prvKey) and pkey2(B.pubKey) * 4. Check whether the generated shared key is consistent with the vector * 5. Call the CRYPT_EAL_PkeyComputeShareKey method: pkey1(B.prvKey) and pkey2(A.pubKey) * 6. Check whether the generated key is consistent with the vector * 7. Check the values returned in steps 3 to 6, expected result 3 * @expect * 1. Success, and contexts are not NULL. * 2. CRYPT_SUCCESS * 3. At least one failure or the generated key and vector are not equal. */ /* BEGIN_CASE */ void SDV_CRYPTO_DH_FUNC_TC006( Hex *p, Hex *g, Hex *q, Hex *prv1, Hex *pub1, Hex *prv2, Hex *pub2, Hex *share, int isProvider) { uint8_t shareLocal[1030]; uint32_t shareLen = sizeof(shareLocal); int ret1, ret2; int cmpRet1, cmpRet2; CRYPT_EAL_PkeyPara para = {0}; CRYPT_EAL_PkeyPrv prv = {0}; CRYPT_EAL_PkeyPub pub = {0}; Set_DH_Para(&para, p->x, q->x, g->x, p->len, q->len, g->len); Set_DH_Prv(&prv, prv1->x, prv1->len); Set_DH_Pub(&pub, pub2->x, pub2->len); TestMemInit(); CRYPT_EAL_PkeyCtx *pkey1 = TestPkeyNewCtx(NULL, CRYPT_PKEY_DH, CRYPT_EAL_PKEY_KEYMGMT_OPERATE + CRYPT_EAL_PKEY_EXCH_OPERATE, "provider=default", isProvider); CRYPT_EAL_PkeyCtx *pkey2 = TestPkeyNewCtx(NULL, CRYPT_PKEY_DH, CRYPT_EAL_PKEY_KEYMGMT_OPERATE + CRYPT_EAL_PKEY_EXCH_OPERATE, "provider=default", isProvider); ASSERT_TRUE(pkey1 != NULL && pkey2 != NULL); ASSERT_TRUE(CRYPT_EAL_PkeySetPara(pkey1, &para) == CRYPT_SUCCESS); ASSERT_TRUE(CRYPT_EAL_PkeySetPrv(pkey1, &prv) == CRYPT_SUCCESS); ASSERT_TRUE(CRYPT_EAL_PkeySetPub(pkey2, &pub) == CRYPT_SUCCESS); ret1 = CRYPT_EAL_PkeyComputeShareKey(pkey1, pkey2, shareLocal, &shareLen); cmpRet1 = memcmp(shareLocal, share->x, share->len); Set_DH_Prv(&prv, prv2->x, prv2->len); Set_DH_Pub(&pub, pub1->x, pub1->len); ASSERT_TRUE(CRYPT_EAL_PkeySetPrv(pkey1, &prv) == CRYPT_SUCCESS); ASSERT_TRUE(CRYPT_EAL_PkeySetPub(pkey2, &pub) == CRYPT_SUCCESS); ret2 = CRYPT_EAL_PkeyComputeShareKey(pkey1, pkey2, shareLocal, &shareLen); ret2 = CRYPT_EAL_PkeyComputeShareKey(pkey1, pkey2, shareLocal, &shareLen); cmpRet2 = memcmp(shareLocal, share->x, share->len); ASSERT_TRUE(ret1 != CRYPT_SUCCESS || cmpRet1 != 0 || ret2 != CRYPT_SUCCESS || cmpRet2 != 0); EXIT: CRYPT_EAL_PkeyFreeCtx(pkey1); CRYPT_EAL_PkeyFreeCtx(pkey2); } /* END_CASE */ /** * @test SDV_CRYPTO_DH_SET_PARA_API_TC001 * @title DH CRYPT_EAL_PkeySetPara: Invalid parameter (NULL). * @precon Registering memory-related functions. * DH parameters. * @brief * 1. Create the context(pkey) of the dh algorithm, expected result 1. * 2. Call the CRYPT_EAL_PkeySetPara method: p = null, expected result 2 * 3. Call the CRYPT_EAL_PkeySetPara method: pLen = 0, expected result 2 * 4. Call the CRYPT_EAL_PkeySetPara method: g = null, expected result 2 * 5. Call the CRYPT_EAL_PkeySetPara method: gLen = 0, expected result 2 * 6. Call the CRYPT_EAL_PkeySetPara method: q = null, qLen != 0, expected result 2 * 7. Call the CRYPT_EAL_PkeySetPara method: ctx = null, expected result 3 * @expect * 1. Success, and context is not NULL. * 2. CRYPT_EAL_ERR_NEW_PARA_FAIL * 3. CRYPT_NULL_INPUT */ /* BEGIN_CASE */ void SDV_CRYPTO_DH_SET_PARA_API_TC001(Hex *p, Hex *g, Hex *q, int isProvider) { CRYPT_EAL_PkeyPara para = {0}; Set_DH_Para(&para, NULL, q->x, g->x, p->len, q->len, g->len); TestMemInit(); CRYPT_EAL_PkeyCtx *pkey = TestPkeyNewCtx(NULL, CRYPT_PKEY_DH, CRYPT_EAL_PKEY_KEYMGMT_OPERATE + CRYPT_EAL_PKEY_EXCH_OPERATE, "provider=default", isProvider); ASSERT_TRUE(pkey != NULL); ASSERT_TRUE_AND_LOG("p is null", CRYPT_EAL_PkeySetPara(pkey, &para) == CRYPT_EAL_ERR_NEW_PARA_FAIL); para.para.dhPara.p = p->x; para.para.dhPara.pLen = 0; ASSERT_TRUE_AND_LOG("pLen is zero", CRYPT_EAL_PkeySetPara(pkey, &para) == CRYPT_EAL_ERR_NEW_PARA_FAIL); para.para.dhPara.pLen = p->len; para.para.dhPara.g = NULL; ASSERT_TRUE_AND_LOG("g is null", CRYPT_EAL_PkeySetPara(pkey, &para) == CRYPT_EAL_ERR_NEW_PARA_FAIL); para.para.dhPara.g = g->x; para.para.dhPara.gLen = 0; ASSERT_TRUE_AND_LOG("gLen is zero", CRYPT_EAL_PkeySetPara(pkey, &para) == CRYPT_EAL_ERR_NEW_PARA_FAIL); para.para.dhPara.gLen = g->len; para.para.dhPara.q = NULL; ASSERT_TRUE_AND_LOG("q is null but qLen != 0", CRYPT_EAL_PkeySetPara(pkey, &para) == CRYPT_EAL_ERR_NEW_PARA_FAIL); para.para.dhPara.q = q->x; ASSERT_TRUE(CRYPT_EAL_PkeySetPara(NULL, &para) == CRYPT_NULL_INPUT); EXIT: CRYPT_EAL_PkeyFreeCtx(pkey); } /* END_CASE */ /** * @test SDV_CRYPTO_DH_SET_PARA_API_TC002 * @title DH CRYPT_EAL_PkeySetPara: Invalid parameter(length). * @precon Registering memory-related functions. * DH parameters. * @brief * 1. Create the context(pkey) of the dh algorithm, expected result 1. * 2. Call the CRYPT_EAL_PkeySetPara method: pLen > 8192, expected result 2 * 3. Call the CRYPT_EAL_PkeySetPara method: pLen < 768, expected result 2 * 4. Call the CRYPT_EAL_PkeySetPara method: pLen > 768, but actual data Len < 768, expected result 3 * 5. Call the CRYPT_EAL_PkeySetPara method: qLen < 160, expected result 3 * 6. Call the CRYPT_EAL_PkeySetPara method: qLen > pLen, expected result 2 * 7. Call the CRYPT_EAL_PkeySetPara method: qLen > 160, but actual data Len < 160, expected result 3 * @expect * 1. Success, and context is not NULL. * 2. CRYPT_EAL_ERR_NEW_PARA_FAIL * 3. CRYPT_DH_PARA_ERROR */ /* BEGIN_CASE */ void SDV_CRYPTO_DH_SET_PARA_API_TC002(Hex *p, Hex *g, Hex *q, int isProvider) { uint8_t longBuf[1030] = {0}; uint32_t bufLen = sizeof(longBuf); CRYPT_EAL_PkeyPara para = {0}; Set_DH_Para(&para, longBuf, q->x, g->x, bufLen, q->len, g->len); TestMemInit(); CRYPT_EAL_PkeyCtx *pkey = TestPkeyNewCtx(NULL, CRYPT_PKEY_DH, CRYPT_EAL_PKEY_KEYMGMT_OPERATE + CRYPT_EAL_PKEY_EXCH_OPERATE, "provider=default", isProvider); ASSERT_TRUE(pkey != NULL); longBuf[0] = 1; longBuf[1024] = 1; ASSERT_TRUE_AND_LOG("p greater than 8192", CRYPT_EAL_PkeySetPara(pkey, &para) == CRYPT_EAL_ERR_NEW_PARA_FAIL); para.para.dhPara.p = p->x; para.para.dhPara.pLen = 95; // 768 / 8 = 96, 96 - 1 = 95 ASSERT_TRUE_AND_LOG("p smaller than 768", CRYPT_EAL_PkeySetPara(pkey, &para) == CRYPT_EAL_ERR_NEW_PARA_FAIL); (void)memset_s(longBuf, sizeof(longBuf), 0, sizeof(longBuf)); longBuf[p->len - 1] = 1; para.para.dhPara.p = longBuf; para.para.dhPara.pLen = p->len; ASSERT_TRUE_AND_LOG("p greater than 768 but value smaller than 768 bits", CRYPT_EAL_PkeySetPara(pkey, &para) == CRYPT_DH_PARA_ERROR); para.para.dhPara.p = p->x; para.para.dhPara.pLen = p->len; para.para.dhPara.qLen = 19; // 160 / 8 = 20, 19 < 20 para.para.dhPara.q = longBuf; (void)memset_s(longBuf, sizeof(longBuf), 0, sizeof(longBuf)); longBuf[18] = 1; ASSERT_TRUE_AND_LOG("q smaller than 160", CRYPT_EAL_PkeySetPara(pkey, &para) == CRYPT_DH_PARA_ERROR); para.para.dhPara.qLen = p->len + 1; ASSERT_TRUE_AND_LOG("q longer than p", CRYPT_EAL_PkeySetPara(pkey, &para) == CRYPT_EAL_ERR_NEW_PARA_FAIL); (void)memset_s(longBuf, sizeof(longBuf), 0, sizeof(longBuf)); longBuf[20] = 1; para.para.dhPara.qLen = 21; ASSERT_TRUE_AND_LOG("q greater than 160 but value smaller than 160 bits", CRYPT_EAL_PkeySetPara(pkey, &para) == CRYPT_DH_PARA_ERROR); EXIT: CRYPT_EAL_PkeyFreeCtx(pkey); } /* END_CASE */ /** * @test SDV_CRYPTO_DH_SET_PARA_API_TC003 * @title DH CRYPT_EAL_PkeySetPara: Invalid parameter (value). * @precon Registering memory-related functions. * DH parameters. * @brief * 1. Create the context(pkey) of the dh algorithm, expected result 1. * 2. Call the CRYPT_EAL_PkeySetPara method: p is an even number, expected result 2 * 3. Call the CRYPT_EAL_PkeySetPara method: q is an even number, expected result 2 * 4. Call the CRYPT_EAL_PkeySetPara method: g=0, expected result 2 * 5. Call the CRYPT_EAL_PkeySetPara method: g=1, expected result 2 * 6. Call the CRYPT_EAL_PkeySetPara method: g=p-1, expected result 2 * 7. Call the CRYPT_EAL_PkeySetPara method: q=p-1, expected result 2 * 8. Call the CRYPT_EAL_PkeySetPara method: q=p-2, expected result 2 * 9. Call the CRYPT_EAL_PkeySetPara method: q=p+2>p, expected result 2 * @expect * 1. Success, and context is not NULL. * 2. CRYPT_DH_PARA_ERROR */ /* BEGIN_CASE */ void SDV_CRYPTO_DH_SET_PARA_API_TC003(Hex *p, Hex *g, Hex *q, int isProvider) { uint8_t buf[1030]; uint32_t bufLen = sizeof(buf); CRYPT_EAL_PkeyPara para = {0}; Set_DH_Para(&para, NULL, q->x, g->x, 0, q->len, g->len); TestMemInit(); CRYPT_EAL_PkeyCtx *pkey = TestPkeyNewCtx(NULL, CRYPT_PKEY_DH, CRYPT_EAL_PKEY_KEYMGMT_OPERATE + CRYPT_EAL_PKEY_EXCH_OPERATE, "provider=default", isProvider); ASSERT_TRUE(pkey != NULL); int last = p->len - 1; ASSERT_TRUE(memcpy_s(buf, bufLen, p->x, p->len) == 0); buf[last] += 1; // p is even para.para.dhPara.p = buf; para.para.dhPara.pLen = p->len; ASSERT_TRUE(CRYPT_EAL_PkeySetPara(pkey, &para) == CRYPT_DH_PARA_ERROR); ASSERT_TRUE(memcpy_s(buf, bufLen, q->x, q->len) == 0); last = q->len - 1; buf[last] += 1; // q is even para.para.dhPara.p = p->x; para.para.dhPara.q = buf; ASSERT_TRUE(CRYPT_EAL_PkeySetPara(pkey, &para) == CRYPT_DH_PARA_ERROR); (void)memset_s(buf, sizeof(buf), 0, sizeof(buf)); // g = 0 para.para.dhPara.q = q->x; para.para.dhPara.g = buf; ASSERT_TRUE(CRYPT_EAL_PkeySetPara(pkey, &para) == CRYPT_DH_PARA_ERROR); last = g->len - 1; buf[last] = 1; // g = 1 ASSERT_TRUE(CRYPT_EAL_PkeySetPara(pkey, &para) == CRYPT_DH_PARA_ERROR); last = p->len - 1; para.para.dhPara.gLen = p->len; ASSERT_TRUE(memcpy_s(buf, bufLen, p->x, p->len) == 0); buf[last] -= 1; // g = p - 1 ASSERT_TRUE(CRYPT_EAL_PkeySetPara(pkey, &para) == CRYPT_DH_PARA_ERROR); // q = p - 1 para.para.dhPara.g = g->x; para.para.dhPara.gLen = g->len; para.para.dhPara.q = buf; para.para.dhPara.qLen = p->len; ASSERT_TRUE(CRYPT_EAL_PkeySetPara(pkey, &para) == CRYPT_DH_PARA_ERROR); buf[last] -= 1; // q = p - 2 ASSERT_TRUE(CRYPT_EAL_PkeySetPara(pkey, &para) == CRYPT_DH_PARA_ERROR); buf[last] += 4; // q = p - 2 + 4 = p + 2 > p ASSERT_TRUE(CRYPT_EAL_PkeySetPara(pkey, &para) == CRYPT_DH_PARA_ERROR); EXIT: CRYPT_EAL_PkeyFreeCtx(pkey); } /* END_CASE */ /** * @test SDV_CRYPTO_DH_SET_PARA_API_TC004 * @title DH CRYPT_EAL_PkeySetPara: Repeated call. * @precon Registering memory-related functions. * DH parameters. * @brief * 1. Create the context(pkey) of the dh algorithm, expected result 1. * 2. Call the CRYPT_EAL_PkeySetPara method with normal parameters, expected result 2 * 3. Call the CRYPT_EAL_PkeySetPara method with normal parameters again, expected result 3 * 4. Call the CRYPT_EAL_PkeySetPara method: pLen < 768, expected result 4 * 5. Call the CRYPT_EAL_PkeySetPara method with normal parameters again, expected result 5 * @expect * 1. Success, and context is not NULL. * 2. CRYPT_SUCCESS * 3. CRYPT_SUCCESS * 4. CRYPT_EAL_ERR_NEW_PARA_FAIL * 5. CRYPT_SUCCESS */ /* BEGIN_CASE */ void SDV_CRYPTO_DH_SET_PARA_API_TC004(Hex *p, Hex *g, Hex *q, int isProvider) { CRYPT_EAL_PkeyPara para = {0}; Set_DH_Para(&para, p->x, q->x, g->x, p->len, q->len, g->len); TestMemInit(); CRYPT_EAL_PkeyCtx *pkey = TestPkeyNewCtx(NULL, CRYPT_PKEY_DH, CRYPT_EAL_PKEY_KEYMGMT_OPERATE + CRYPT_EAL_PKEY_EXCH_OPERATE, "provider=default", isProvider); ASSERT_TRUE(pkey != NULL); ASSERT_TRUE(CRYPT_EAL_PkeySetPara(pkey, &para) == CRYPT_SUCCESS); ASSERT_TRUE(CRYPT_EAL_PkeySetPara(pkey, &para) == CRYPT_SUCCESS); para.para.dhPara.pLen = 95; // 768 / 8 = 96, 95 < 96 ASSERT_TRUE(CRYPT_EAL_PkeySetPara(pkey, &para) == CRYPT_EAL_ERR_NEW_PARA_FAIL); para.para.dhPara.pLen = p->len; ASSERT_TRUE(CRYPT_EAL_PkeySetPara(pkey, &para) == CRYPT_SUCCESS); EXIT: CRYPT_EAL_PkeyFreeCtx(pkey); } /* END_CASE */ /** * @test SDV_CRYPTO_DH_SET_PRV_API_TC001 * @title DH: CRYPT_EAL_PkeySetPrv test. * @precon Registering memory-related functions. * DH parameters and private key. * @brief * 1. Create the context(pkey) of the dh algorithm, expected result 1. * 2. Call the CRYPT_EAL_PkeySetPrv method before CRYPT_EAL_PkeySetPara, expected result 2 * 3. Call the CRYPT_EAL_PkeySetPara method to set para, expected result 3 * 4. Call the CRYPT_EAL_PkeySetPrv method: * (1). pkey = NULL, expected result 4. * (2). prv = NULL, expected result 4. * (3). prv.data = NULL, expected result 4. * (4). prv.len = 0, expected result 4. * (5). prv.id != pkey.id, expected result 3. * @expect * 1. Success, and context is not NULL. * 2. CRYPT_DH_PARA_ERROR * 3. CRYPT_SUCCESS * 4. CRYPT_NULL_INPUT */ /* BEGIN_CASE */ void SDV_CRYPTO_DH_SET_PRV_API_TC001(Hex *p, Hex *g, Hex *q, Hex *prvKey, int isProvider) { CRYPT_EAL_PkeyPara para = {0}; CRYPT_EAL_PkeyPrv prv = {0}; Set_DH_Para(&para, p->x, q->x, g->x, p->len, q->len, g->len); Set_DH_Prv(&prv, prvKey->x, prvKey->len); TestMemInit(); CRYPT_EAL_PkeyCtx *pkey = TestPkeyNewCtx(NULL, CRYPT_PKEY_DH, CRYPT_EAL_PKEY_KEYMGMT_OPERATE + CRYPT_EAL_PKEY_EXCH_OPERATE, "provider=default", isProvider); ASSERT_TRUE(pkey != NULL); ASSERT_TRUE(CRYPT_EAL_PkeySetPrv(pkey, &prv) == CRYPT_DH_PARA_ERROR); ASSERT_TRUE(CRYPT_EAL_PkeySetPara(pkey, &para) == CRYPT_SUCCESS); ASSERT_TRUE(CRYPT_EAL_PkeySetPrv(NULL, &prv) == CRYPT_NULL_INPUT); ASSERT_TRUE(CRYPT_EAL_PkeySetPrv(pkey, NULL) == CRYPT_NULL_INPUT); prv.key.dhPrv.data = NULL; ASSERT_TRUE(CRYPT_EAL_PkeySetPrv(pkey, &prv) == CRYPT_NULL_INPUT); prv.key.dhPrv.data = prvKey->x; prv.key.dhPrv.len = 0; ASSERT_TRUE(CRYPT_EAL_PkeySetPrv(pkey, &prv) == CRYPT_NULL_INPUT); EXIT: CRYPT_EAL_PkeyFreeCtx(pkey); } /* END_CASE */ /** * @test SDV_CRYPTO_DH_SET_PRV_API_TC002 * @title DH: CRYPT_EAL_PkeySetPrv test. Boundary value test for the private key. * @precon Registering memory-related functions. * DH parameters. * @brief * 1. Create the context(pkey) of the dh algorithm, expected result 1. * 2. Call the CRYPT_EAL_PkeySetPara method to set para(q = NULL), expected result 2 * 3. Call the CRYPT_EAL_PkeySetPrv method: * (1) prvKey = p - 1, expected result 3 * (2) prvKey = p - 2, expected result 4 * 4. Call the CRYPT_EAL_PkeySetPara method to set para(q != NULL), expected result 5 * 5. Call the CRYPT_EAL_PkeySetPrv method: * (1) prvKey = q, expected result 6 * (1) prvKey = 0, expected result 7 * (1) prvKey = 1, expected result 8 * (1) prvKey = q - 1, expected result 9 * @expect * 1. Success, and context is not NULL. * 2. CRYPT_SUCCESS * 3. CRYPT_DH_KEYINFO_ERROR * 4. CRYPT_SUCCESS * 5. CRYPT_SUCCESS * 6. CRYPT_DH_KEYINFO_ERROR * 7. CRYPT_SUCCESS * 8. CRYPT_DH_KEYINFO_ERROR * 9. CRYPT_SUCCESS */ /* BEGIN_CASE */ void SDV_CRYPTO_DH_SET_PRV_API_TC002(Hex *p, Hex *g, Hex *q, int isProvider) { uint8_t *tmpPrv = NULL; int last; CRYPT_EAL_PkeyPara para = {0}; Set_DH_Para(&para, p->x, NULL, g->x, p->len, 0, g->len); CRYPT_EAL_PkeyPrv prv = {0}; prv.id = CRYPT_PKEY_DH; TestMemInit(); CRYPT_EAL_PkeyCtx *pkey = TestPkeyNewCtx(NULL, CRYPT_PKEY_DH, CRYPT_EAL_PKEY_KEYMGMT_OPERATE + CRYPT_EAL_PKEY_EXCH_OPERATE, "provider=default", isProvider); ASSERT_TRUE(pkey != NULL); ASSERT_TRUE(CRYPT_EAL_PkeySetPara(pkey, &para) == CRYPT_SUCCESS); tmpPrv = (uint8_t *)malloc(sizeof(uint8_t) * p->len); ASSERT_TRUE(memcpy_s(tmpPrv, p->len, p->x, p->len) == 0); last = p->len - 1; tmpPrv[last] -= 1; // tmpPrv = p - 1, Vectors are guaranteed not to wrap around. prv.key.dhPrv.data = tmpPrv; prv.key.dhPrv.len = p->len; ASSERT_TRUE_AND_LOG("prvKey = p - 1", CRYPT_EAL_PkeySetPrv(pkey, &prv) == CRYPT_DH_KEYINFO_ERROR); tmpPrv[last] -= 1; // tmpPrv = p - 2, Vectors are guaranteed not to wrap around. ASSERT_TRUE_AND_LOG("prvKey = p - 2", CRYPT_EAL_PkeySetPrv(pkey, &prv) == CRYPT_SUCCESS); para.para.dhPara.q = q->x; para.para.dhPara.qLen = q->len; ASSERT_TRUE(CRYPT_EAL_PkeySetPara(pkey, &para) == CRYPT_SUCCESS); /* In normal para, p>q does not exceed the threshold. */ ASSERT_TRUE(memcpy_s(tmpPrv, p->len, q->x, q->len) == 0); prv.key.dhPrv.len = q->len; ASSERT_TRUE_AND_LOG("prvKey = q", CRYPT_EAL_PkeySetPrv(pkey, &prv) == CRYPT_DH_KEYINFO_ERROR); last = q->len - 1; tmpPrv[last] -= 1; ASSERT_TRUE_AND_LOG("prvKey = q - 1", CRYPT_EAL_PkeySetPrv(pkey, &prv) == CRYPT_SUCCESS); (void)memset_s(tmpPrv, p->len, 0, p->len); ASSERT_TRUE_AND_LOG("prvKey = 0", CRYPT_EAL_PkeySetPrv(pkey, &prv) == CRYPT_DH_KEYINFO_ERROR); last = q->len - 1; tmpPrv[last] = 1; ASSERT_TRUE_AND_LOG("prvKey = 1", CRYPT_EAL_PkeySetPrv(pkey, &prv) == CRYPT_SUCCESS); EXIT: CRYPT_EAL_PkeyFreeCtx(pkey); if (tmpPrv != NULL) { free(tmpPrv); } } /* END_CASE */ /** * @test SDV_CRYPTO_DH_SET_PUB_API_TC001 * @title DH CRYPT_EAL_PkeySetPub: Invalid parameter(NULL). * @precon Registering memory-related functions. * Public key. * @brief * 1. Create the context(pkey) of the dh algorithm, expected result 1. * 2. Call the CRYPT_EAL_PkeySetPub method: * (1) pkey = null, expected result 2 * (2) pubKey = null, expected result 2 * (3) pubKeyLen = 0, expected result 2 * @expect * 1. Success, and context is not NULL. * 2. CRYPT_NULL_INPUT */ /* BEGIN_CASE */ void SDV_CRYPTO_DH_SET_PUB_API_TC001(Hex *pubKey, int isProvider) { CRYPT_EAL_PkeyPub pub = {0}; Set_DH_Pub(&pub, pubKey->x, pubKey->len); TestMemInit(); CRYPT_EAL_PkeyCtx *pkey = TestPkeyNewCtx(NULL, CRYPT_PKEY_DH, CRYPT_EAL_PKEY_KEYMGMT_OPERATE + CRYPT_EAL_PKEY_EXCH_OPERATE, "provider=default", isProvider); ASSERT_TRUE(pkey != NULL); ASSERT_TRUE(CRYPT_EAL_PkeySetPub(NULL, &pub) == CRYPT_NULL_INPUT); pub.key.dhPub.data = NULL; ASSERT_TRUE(CRYPT_EAL_PkeySetPub(pkey, &pub) == CRYPT_NULL_INPUT); pub.key.dhPub.data = pubKey->x; pub.key.dhPub.len = 0; ASSERT_TRUE(CRYPT_EAL_PkeySetPub(pkey, &pub) == CRYPT_NULL_INPUT); EXIT: CRYPT_EAL_PkeyFreeCtx(pkey); } /* END_CASE */ /** * @test SDV_CRYPTO_DH_SET_PUB_API_TC002 * @title DH CRYPT_EAL_PkeySetPub: Invalid parameter(Overlong public key). * @precon Registering memory-related functions. * @brief * 1. Create the context(pkey) of the dh algorithm, expected result 1. * 2. Call the CRYPT_EAL_PkeySetPub method: * (1) pub array Len > 8192, actual Len > 8192, expected result 2 * (2) pub array Len > 8192, actual Len < 8192, expected result 2 * @expect * 1. Success, and context is not NULL. * 2. CRYPT_DH_KEYINFO_ERROR */ /* BEGIN_CASE */ void SDV_CRYPTO_DH_SET_PUB_API_TC002(int isProvider) { uint8_t pubKey[1025] = {0}; // 8192/8 + 1 = 1025 uint32_t pubLen = sizeof(pubKey); pubKey[0] = 1; pubKey[1024] = 5; // 1024 is last block CRYPT_EAL_PkeyPub pub = {0}; Set_DH_Pub(&pub, pubKey, pubLen); TestMemInit(); CRYPT_EAL_PkeyCtx *pkey = TestPkeyNewCtx(NULL, CRYPT_PKEY_DH, CRYPT_EAL_PKEY_KEYMGMT_OPERATE + CRYPT_EAL_PKEY_EXCH_OPERATE, "provider=default", isProvider); ASSERT_TRUE(pkey != NULL); ASSERT_TRUE(CRYPT_EAL_PkeySetPub(pkey, &pub) == CRYPT_DH_KEYINFO_ERROR); pubKey[0] = 0; ASSERT_TRUE(CRYPT_EAL_PkeySetPub(pkey, &pub) == CRYPT_DH_KEYINFO_ERROR); EXIT: CRYPT_EAL_PkeyFreeCtx(pkey); } /* END_CASE */ /** * @test SDV_CRYPTO_DH_GET_PRV_API_TC001 * @title DH CRYPT_EAL_PkeyGetPrv: Invalid parameter. * @precon Registering memory-related functions. * DH parameters and private key. * @brief * 1. Create the context(pkey) of the dh algorithm, expected result 1. * 2. Set para, expected result 2 * 3. Call the CRYPT_EAL_PkeyGetPrv method: all parameters are valid, expected result 3 * 4. Call the CRYPT_EAL_PkeySetPrv method: all parameters are valid, expected result 4 * 5. Call the CRYPT_EAL_PkeyGetPrv method: prv.data=NULL, expected result 5 * 6. Call the CRYPT_EAL_PkeyGetPrv method: prv.len < prvKeyLen, expected result 6 * 7. Compare the setted public key with the obtained public key, expected result 7 * @expect * 1. Success, and context is not NULL. * 2. CRYPT_SUCCESS * 3. CRYPT_DH_KEYINFO_ERROR * 4. CRYPT_SUCCESS * 5. CRYPT_NULL_INPUT * 6. CRYPT_DH_BUFF_LEN_NOT_ENOUGH * 7. The two private keys are the same. */ /* BEGIN_CASE */ void SDV_CRYPTO_DH_GET_PRV_API_TC001(Hex *p, Hex *g, Hex *q, Hex *prvKey, int isProvider) { uint8_t output[1030]; uint32_t outLen = sizeof(output); CRYPT_EAL_PkeyPara para = {0}; CRYPT_EAL_PkeyPrv prv = {0}; Set_DH_Para(&para, p->x, q->x, g->x, p->len, q->len, g->len); Set_DH_Prv(&prv, output, outLen); TestMemInit(); CRYPT_EAL_PkeyCtx *pkey = TestPkeyNewCtx(NULL, CRYPT_PKEY_DH, CRYPT_EAL_PKEY_KEYMGMT_OPERATE + CRYPT_EAL_PKEY_EXCH_OPERATE, "provider=default", isProvider); ASSERT_TRUE(pkey != NULL); ASSERT_TRUE(CRYPT_EAL_PkeySetPara(pkey, &para) == CRYPT_SUCCESS); ASSERT_TRUE(CRYPT_EAL_PkeyGetPrv(pkey, &prv) == CRYPT_DH_KEYINFO_ERROR); prv.key.dhPrv.data = prvKey->x; prv.key.dhPrv.len = prvKey->len; ASSERT_TRUE(CRYPT_EAL_PkeySetPrv(pkey, &prv) == CRYPT_SUCCESS); prv.key.dhPrv.data = NULL; prv.key.dhPrv.len = outLen; ASSERT_TRUE(CRYPT_EAL_PkeyGetPrv(pkey, &prv) == CRYPT_NULL_INPUT); prv.key.dhPrv.data = output; prv.key.dhPrv.len = prvKey->len - 1; ASSERT_TRUE(CRYPT_EAL_PkeyGetPrv(pkey, &prv) == CRYPT_DH_BUFF_LEN_NOT_ENOUGH); prv.key.dhPrv.len = p->len > q->len ? p->len : q->len; ASSERT_EQ(CRYPT_EAL_PkeyGetPrv(pkey, &prv), CRYPT_SUCCESS); ASSERT_TRUE(prv.key.dhPrv.len == prvKey->len); ASSERT_TRUE(memcmp(output, prvKey->x, prvKey->len) == 0); EXIT: CRYPT_EAL_PkeyFreeCtx(pkey); } /* END_CASE */ /** * @test SDV_CRYPTO_DH_GET_PUB_API_TC001 * @title DH CRYPT_EAL_PkeyGetPub: Invalid parameter. * @precon Registering memory-related functions. * Public key. * @brief * 1. Create the context(pkey) of the dh algorithm, expected result 1. * 2. Call the CRYPT_EAL_PkeyGetPub method: all parameters are valid, expected result 2 * 3. Call the CRYPT_EAL_PkeySetPub method: all parameters are valid, expected result 3 * 4. Call the CRYPT_EAL_PkeyGetPub method: pub.data=NULL, expected result 4 * 5. Call the CRYPT_EAL_PkeyGetPub method: pub.len < pubKeyLen, expected result 5 * 6. Compare the setted public key with the obtained public key, expected result 6. * @expect * 1. Success, and context is not NULL. * 2. CRYPT_DH_KEYINFO_ERROR * 3. CRYPT_SUCCESS * 4. CRYPT_NULL_INPUT * 5. CRYPT_DH_BUFF_LEN_NOT_ENOUGH * 6. The two public keys are the same. */ /* BEGIN_CASE */ void SDV_CRYPTO_DH_GET_PUB_API_TC001(Hex *p, Hex *g, Hex *q, Hex *pubKey, int isProvider) { uint8_t output[1030]; uint32_t outLen = sizeof(output); CRYPT_EAL_PkeyPub pub = {0}; CRYPT_EAL_PkeyPara para = {0}; Set_DH_Pub(&pub, output, outLen); Set_DH_Para(&para, p->x, q->x, g->x, p->len, q->len, g->len); TestMemInit(); CRYPT_EAL_PkeyCtx *pkey = TestPkeyNewCtx(NULL, CRYPT_PKEY_DH, CRYPT_EAL_PKEY_KEYMGMT_OPERATE + CRYPT_EAL_PKEY_EXCH_OPERATE, "provider=default", isProvider); ASSERT_TRUE(pkey != NULL); ASSERT_TRUE(CRYPT_EAL_PkeyGetPub(pkey, &pub) == CRYPT_DH_PARA_ERROR); ASSERT_TRUE(CRYPT_EAL_PkeySetPara(pkey, &para) == CRYPT_SUCCESS); ASSERT_TRUE(CRYPT_EAL_PkeyGetPub(pkey, &pub) == CRYPT_DH_KEYINFO_ERROR); pub.key.dhPub.data = pubKey->x; pub.key.dhPub.len = pubKey->len; ASSERT_TRUE(CRYPT_EAL_PkeySetPub(pkey, &pub) == CRYPT_SUCCESS); pub.key.dhPub.data = NULL; pub.key.dhPub.len = outLen; ASSERT_TRUE(CRYPT_EAL_PkeyGetPub(pkey, &pub) == CRYPT_NULL_INPUT); pub.key.dhPub.data = output; pub.key.dhPub.len = pubKey->len - 1; ASSERT_TRUE(CRYPT_EAL_PkeyGetPub(pkey, &pub) == CRYPT_DH_BUFF_LEN_NOT_ENOUGH); pub.key.dhPub.len = pubKey->len; ASSERT_TRUE(CRYPT_EAL_PkeyGetPub(pkey, &pub) == CRYPT_SUCCESS); ASSERT_TRUE(pub.key.dhPub.len == pubKey->len); ASSERT_TRUE(memcmp(output, pubKey->x, pubKey->len) == 0); EXIT: CRYPT_EAL_PkeyFreeCtx(pkey); } /* END_CASE */ /** * @test SDV_CRYPTO_DH_GET_KEY_LEN_API_TC001 * @title CRYPT_EAL_PkeyGetKeyLen test. * @precon Registering memory-related functions. * DH parameters. * @brief * 1. Create the context(pkey) of the dh algorithm, expected result 1. * 2. Call the CRYPT_EAL_PkeyGetKeyLen, expected result 2 * 3. Set para, expected result 3 * 4. Call the CRYPT_EAL_PkeyGetKeyLen, expected result 4 * @expect * 1. Success, and context is not NULL. * 2. 0 is returned because the parameter is not set. * 3. CRYPT_SUCCESS * 4. The obtained length is equal to p->len. */ /* BEGIN_CASE */ void SDV_CRYPTO_DH_GET_KEY_LEN_API_TC001(Hex *p, Hex *g, Hex *q, int isProvider) { CRYPT_EAL_PkeyPara para = {0}; Set_DH_Para(&para, p->x, q->x, g->x, p->len, q->len, g->len); TestMemInit(); CRYPT_EAL_PkeyCtx *pkey = TestPkeyNewCtx(NULL, CRYPT_PKEY_DH, CRYPT_EAL_PKEY_KEYMGMT_OPERATE + CRYPT_EAL_PKEY_EXCH_OPERATE, "provider=default", isProvider); ASSERT_TRUE(pkey != NULL); ASSERT_EQ(CRYPT_EAL_PkeyGetKeyLen(pkey), 0); ASSERT_EQ(CRYPT_EAL_PkeySetPara(pkey, &para), CRYPT_SUCCESS); ASSERT_EQ(CRYPT_EAL_PkeyGetKeyLen(pkey), p->len); EXIT: CRYPT_EAL_PkeyFreeCtx(pkey); } /* END_CASE */ /** * @test SDV_CRYPTO_DH_GEN_API_TC001 * @title DH CRYPT_EAL_PkeyGen test. * @precon Registering memory-related functions. * DH parameters. * @brief * 1. Create the context(pkey) of the dh algorithm, expected result 1. * 2. Call the CRYPT_EAL_PkeyGen method: pkey = NULL, expected result 2 * 3. Call the CRYPT_EAL_PkeyGen method: pkey != NULL, expected result 3 * 4. Set para, expected result 4 * 5. Call the CRYPT_EAL_PkeyGen method: pkey != NULL, expected result 5 * 6. Initializes the random number, expected result 6 * 7. Call the CRYPT_EAL_PkeyGen method: pkey != NULL, expected result 6 * @expect * 1. Success, and context is not NULL. * 2. CRYPT_NULL_INPUT * 3. CRYPT_DH_PARA_ERROR * 4. CRYPT_SUCCESS * 5. CRYPT_NO_REGIST_RAND * 6. CRYPT_SUCCESS */ /* BEGIN_CASE */ void SDV_CRYPTO_DH_GEN_API_TC001(Hex *p, Hex *g, Hex *q) { CRYPT_EAL_PkeyPara para = {0}; Set_DH_Para(&para, p->x, q->x, g->x, p->len, q->len, g->len); TestMemInit(); CRYPT_EAL_PkeyCtx *pkey = CRYPT_EAL_PkeyNewCtx(CRYPT_PKEY_DH); ASSERT_TRUE(pkey != NULL); ASSERT_TRUE(CRYPT_EAL_PkeyGen(NULL) == CRYPT_NULL_INPUT); ASSERT_TRUE(CRYPT_EAL_PkeyGen(pkey) == CRYPT_DH_PARA_ERROR); ASSERT_TRUE(CRYPT_EAL_PkeySetPara(pkey, &para) == CRYPT_SUCCESS); ASSERT_TRUE(CRYPT_EAL_PkeyGen(pkey) == CRYPT_NO_REGIST_RAND); ASSERT_EQ(TestRandInit(), CRYPT_SUCCESS); ASSERT_TRUE(CRYPT_EAL_PkeyGen(pkey) == CRYPT_SUCCESS); EXIT: TestRandDeInit(); CRYPT_EAL_PkeyFreeCtx(pkey); } /* END_CASE */ /** * @test SDV_CRYPTO_DH_SET_PARA_BY_ID_API_TC001 * @title DH CRYPT_EAL_PkeySetParaById test: invalid pkey or wrong ID. * @precon Registering memory-related functions. * @brief * 1. Create the context(pkey) of the dh algorithm, expected result 1 * 2. Call the PkeySetParaById method: pkey = NULL, expected result 2 * 3. Call the PkeySetParaById method: invalid id, expected result 3 * @expect * 1. Success, and context is not NULL. * 2. CRYPT_NULL_INPUT * 3. CRYPT_EAL_ERR_NEW_PARA_FAIL */ /* BEGIN_CASE */ void SDV_CRYPTO_DH_SET_PARA_BY_ID_API_TC001(int isProvider) { TestMemInit(); CRYPT_EAL_PkeyCtx *pkey = TestPkeyNewCtx(NULL, CRYPT_PKEY_DH, CRYPT_EAL_PKEY_KEYMGMT_OPERATE + CRYPT_EAL_PKEY_EXCH_OPERATE, "provider=default", isProvider); ASSERT_TRUE(pkey != NULL); ASSERT_TRUE(CRYPT_EAL_PkeySetParaById(NULL, CRYPT_DH_RFC3526_2048) == CRYPT_NULL_INPUT); ASSERT_TRUE(CRYPT_EAL_PkeySetParaById(pkey, 100) == CRYPT_EAL_ERR_NEW_PARA_FAIL); EXIT: CRYPT_EAL_PkeyFreeCtx(pkey); } /* END_CASE */ /** * @test SDV_CRYPTO_DH_EXCH_API_TC001 * @title DH CRYPT_EAL_PkeyComputeShareKey test: Invalid parameter(NULL). * @precon Registering memory-related functions. * DH vectors. * @brief * 1. Create two contexts(pkey1, pkey2) of the dh algorithm, expected result 1 * 2. Set the correct public key for pkey2, expected result 2 * 3. Call the CRYPT_EAL_PkeyComputeShareKey method, expected result 3 * 4. Set the correct para and private key for pkey1, expected result 4 * 5. Call the CRYPT_EAL_PkeyComputeShareKey method: pkey=null, expected result 5 * 6. Call the CRYPT_EAL_PkeyComputeShareKey method: pubKey=null, expected result 5 * 7. Call the CRYPT_EAL_PkeyComputeShareKey method: share=null, expected result 5 * 8. Call the CRYPT_EAL_PkeyComputeShareKey method: shareLen=null, expected result 5 * @expect * 1. Success, and context is not NULL. * 2. CRYPT_SUCCESS * 3. CRYPT_DH_PARA_ERROR * 4. CRYPT_SUCCESS * 5. CRYPT_NULL_INPUT */ /* BEGIN_CASE */ void SDV_CRYPTO_DH_EXCH_API_TC001(Hex *p, Hex *g, Hex *q, Hex *pubKey, Hex *prvKey, int isProvider) { uint8_t share[1030]; uint32_t shareLen = sizeof(share); CRYPT_EAL_PkeyPara para = {0}; CRYPT_EAL_PkeyPrv prv = {0}; CRYPT_EAL_PkeyPub pub = {0}; Set_DH_Para(&para, p->x, q->x, g->x, p->len, q->len, g->len); Set_DH_Prv(&prv, prvKey->x, prvKey->len); Set_DH_Pub(&pub, pubKey->x, pubKey->len); TestMemInit(); CRYPT_EAL_PkeyCtx *pkey1 = TestPkeyNewCtx(NULL, CRYPT_PKEY_DH, CRYPT_EAL_PKEY_KEYMGMT_OPERATE + CRYPT_EAL_PKEY_EXCH_OPERATE, "provider=default", isProvider); CRYPT_EAL_PkeyCtx *pkey2 = TestPkeyNewCtx(NULL, CRYPT_PKEY_DH, CRYPT_EAL_PKEY_KEYMGMT_OPERATE + CRYPT_EAL_PKEY_EXCH_OPERATE, "provider=default", isProvider); ASSERT_TRUE(pkey1 != NULL && pkey2 != NULL); ASSERT_TRUE(CRYPT_EAL_PkeySetPub(pkey2, &pub) == CRYPT_SUCCESS); ASSERT_TRUE(CRYPT_EAL_PkeyComputeShareKey(pkey1, pkey2, share, &shareLen) == CRYPT_DH_PARA_ERROR); ASSERT_TRUE(CRYPT_EAL_PkeySetPara(pkey1, &para) == CRYPT_SUCCESS); ASSERT_TRUE(CRYPT_EAL_PkeySetPrv(pkey1, &prv) == CRYPT_SUCCESS); ASSERT_TRUE(CRYPT_EAL_PkeyComputeShareKey(NULL, pkey2, share, &shareLen) == CRYPT_NULL_INPUT); ASSERT_TRUE(CRYPT_EAL_PkeyComputeShareKey(pkey1, NULL, share, &shareLen) == CRYPT_NULL_INPUT); ASSERT_TRUE(CRYPT_EAL_PkeyComputeShareKey(pkey1, pkey2, NULL, &shareLen) == CRYPT_NULL_INPUT); ASSERT_TRUE(CRYPT_EAL_PkeyComputeShareKey(pkey1, pkey2, (uint8_t *)share, NULL) == CRYPT_NULL_INPUT); EXIT: CRYPT_EAL_PkeyFreeCtx(pkey1); CRYPT_EAL_PkeyFreeCtx(pkey2); } /* END_CASE */ /** * @test SDV_CRYPTO_DH_EXCH_API_TC002 * @title DH CRYPT_EAL_PkeyComputeShareKey test: Invalid parameter(The public key or private key is missing). * @precon Registering memory-related functions. * DH vectors. * @brief * 1. Create the contexts of the dh algorithm, expected result 1. * 2. Set the correct para, expected result 2 * 3. Call the CRYPT_EAL_PkeyComputeShareKey method: no private key, expected result 3 * 4. Call the CRYPT_EAL_PkeyComputeShareKey method: no public key, expected result 4 * @expect * 1. Success, and context is not NULL. * 2. CRYPT_SUCCESS * 3. CRYPT_DH_KEYINFO_ERROR * 4. CRYPT_DH_KEYINFO_ERROR */ /* BEGIN_CASE */ void SDV_CRYPTO_DH_EXCH_API_TC002(Hex *p, Hex *g, Hex *q, Hex *pubKey, Hex *prvKey, int isProvider) { uint8_t share[1030]; uint32_t shareLen = sizeof(share); CRYPT_EAL_PkeyPara para = {0}; CRYPT_EAL_PkeyPrv prv = {0}; CRYPT_EAL_PkeyPub pub = {0}; Set_DH_Para(&para, p->x, q->x, g->x, p->len, q->len, g->len); Set_DH_Prv(&prv, prvKey->x, prvKey->len); Set_DH_Pub(&pub, pubKey->x, pubKey->len); TestMemInit(); CRYPT_EAL_PkeyCtx *pkey1 = TestPkeyNewCtx(NULL, CRYPT_PKEY_DH, CRYPT_EAL_PKEY_KEYMGMT_OPERATE + CRYPT_EAL_PKEY_EXCH_OPERATE, "provider=default", isProvider); CRYPT_EAL_PkeyCtx *pkey2 = TestPkeyNewCtx(NULL, CRYPT_PKEY_DH, CRYPT_EAL_PKEY_KEYMGMT_OPERATE + CRYPT_EAL_PKEY_EXCH_OPERATE, "provider=default", isProvider); CRYPT_EAL_PkeyCtx *pkey3 = TestPkeyNewCtx(NULL, CRYPT_PKEY_DH, CRYPT_EAL_PKEY_KEYMGMT_OPERATE + CRYPT_EAL_PKEY_EXCH_OPERATE, "provider=default", isProvider); ASSERT_TRUE(pkey1 != NULL && pkey2 != NULL && pkey3 != NULL); ASSERT_TRUE(CRYPT_EAL_PkeySetPara(pkey1, &para) == CRYPT_SUCCESS); ASSERT_TRUE(CRYPT_EAL_PkeySetPara(pkey3, &para) == CRYPT_SUCCESS); ASSERT_TRUE(CRYPT_EAL_PkeySetPrv(pkey1, &prv) == CRYPT_SUCCESS); ASSERT_TRUE(CRYPT_EAL_PkeyComputeShareKey(pkey1, pkey2, share, &shareLen) == CRYPT_DH_KEYINFO_ERROR); ASSERT_TRUE(CRYPT_EAL_PkeySetPub(pkey2, &pub) == CRYPT_SUCCESS); ASSERT_TRUE(CRYPT_EAL_PkeyComputeShareKey(pkey3, pkey2, share, &shareLen) == CRYPT_DH_KEYINFO_ERROR); EXIT: CRYPT_EAL_PkeyFreeCtx(pkey1); CRYPT_EAL_PkeyFreeCtx(pkey2); CRYPT_EAL_PkeyFreeCtx(pkey3); } /* END_CASE */ /** * @test SDV_CRYPTO_DH_EXCH_API_TC003 * @title DH CRYPT_EAL_PkeyComputeShareKey test: Invalid parameter(The length of the output parameter is insufficient). * @precon Registering memory-related functions. * DH vectors. * @brief * 1. Create the contexts of the dh algorithm, expected result 1. * 2. Set the correct para and keys, expected result 2 * 3. Call the CRYPT_EAL_PkeyComputeShareKey method: shareLen=keyLen-1, expected result 3 * @expect * 1. Success, and context is not NULL. * 2. CRYPT_SUCCESS * 3. CRYPT_DH_BUFF_LEN_NOT_ENOUGH */ /* BEGIN_CASE */ void SDV_CRYPTO_DH_EXCH_API_TC003(Hex *p, Hex *g, Hex *q, Hex *pubKey, Hex *prvKey, int isProvider) { uint8_t share[1030]; uint32_t shareLen; CRYPT_EAL_PkeyPara para = {0}; CRYPT_EAL_PkeyPrv prv = {0}; CRYPT_EAL_PkeyPub pub = {0}; Set_DH_Para(&para, p->x, q->x, g->x, p->len, q->len, g->len); Set_DH_Prv(&prv, prvKey->x, prvKey->len); Set_DH_Pub(&pub, pubKey->x, pubKey->len); TestMemInit(); CRYPT_EAL_PkeyCtx *pkey1 = TestPkeyNewCtx(NULL, CRYPT_PKEY_DH, CRYPT_EAL_PKEY_KEYMGMT_OPERATE + CRYPT_EAL_PKEY_EXCH_OPERATE, "provider=default", isProvider); CRYPT_EAL_PkeyCtx *pkey2 = TestPkeyNewCtx(NULL, CRYPT_PKEY_DH, CRYPT_EAL_PKEY_KEYMGMT_OPERATE + CRYPT_EAL_PKEY_EXCH_OPERATE, "provider=default", isProvider); ASSERT_TRUE(pkey1 != NULL && pkey2 != NULL); ASSERT_TRUE(CRYPT_EAL_PkeySetPara(pkey1, &para) == CRYPT_SUCCESS); ASSERT_TRUE(CRYPT_EAL_PkeySetPrv(pkey1, &prv) == CRYPT_SUCCESS); ASSERT_TRUE(CRYPT_EAL_PkeySetPub(pkey2, &pub) == CRYPT_SUCCESS); shareLen = CRYPT_EAL_PkeyGetKeyLen(pkey1) - 1; ASSERT_EQ(CRYPT_EAL_PkeyComputeShareKey(pkey1, pkey2, (uint8_t *)share, &shareLen), CRYPT_DH_BUFF_LEN_NOT_ENOUGH); EXIT: CRYPT_EAL_PkeyFreeCtx(pkey1); CRYPT_EAL_PkeyFreeCtx(pkey2); } /* END_CASE */ /** * @test SDV_CRYPTO_DH_GET_PARA_API_TC001 * @title DH CRYPT_EAL_PkeyGetPara test. * @precon Registering memory-related functions. * DH parameters. * @brief * 1. Create the contexts of the dh algorithm, expected result 1. * 2. Call the CRYPT_EAL_PkeySetPara method with correct parameters, expected result 2 * 3. Call the CRYPT_EAL_PkeySetPara method: para.id != pkey.id, expected result 3 * 4. Call the CRYPT_EAL_PkeySetPara method: pkey=NULL or para=NULL, expected result 4 * 5. Call the CRYPT_EAL_PkeySetPara method with correct parameters, expected result 5 * 6. Check whether the configured parameters are the same as the obtained parameters, expected result 6 * @expect * 1. Success, and context is not NULL. * 2. CRYPT_SUCCESS * 3. CRYPT_EAL_ERR_ALGID * 4. CRYPT_NULL_INPUT * 5. CRYPT_SUCCESS * 6. Parameters are equal. */ /* BEGIN_CASE */ void SDV_CRYPTO_DH_GET_PARA_API_TC001(Hex *p, Hex *q, Hex *g, int isProvider) { uint8_t buf_p[1030] = {0}; uint32_t bufLen = sizeof(buf_p); uint8_t buf_q[1030] = {0}; uint8_t buf_g[1030] = {0}; CRYPT_EAL_PkeyPara para = {0}; CRYPT_EAL_PkeyPara para2 = {0}; Set_DH_Para(&para, p->x, q->x, g->x, p->len, q->len, g->len); Set_DH_Para(&para2, buf_p, buf_q, buf_g, bufLen, bufLen, bufLen); para2.id = CRYPT_PKEY_RSA; TestMemInit(); CRYPT_EAL_PkeyCtx *pKey = TestPkeyNewCtx(NULL, CRYPT_PKEY_DH, CRYPT_EAL_PKEY_KEYMGMT_OPERATE + CRYPT_EAL_PKEY_EXCH_OPERATE, "provider=default", isProvider); ASSERT_TRUE(pKey != NULL); ASSERT_TRUE(CRYPT_EAL_PkeySetPara(pKey, &para) == CRYPT_SUCCESS); ASSERT_TRUE(CRYPT_EAL_PkeyGetPara(pKey, &para2) == CRYPT_EAL_ERR_ALGID); ASSERT_TRUE(CRYPT_EAL_PkeyGetPara(NULL, &para2) == CRYPT_NULL_INPUT); ASSERT_TRUE(CRYPT_EAL_PkeyGetPara(pKey, NULL) == CRYPT_NULL_INPUT); para2.id = CRYPT_PKEY_DH; ASSERT_TRUE(CRYPT_EAL_PkeyGetPara(pKey, &para2) == CRYPT_SUCCESS); ASSERT_TRUE(para.para.dhPara.pLen == para2.para.dhPara.pLen); ASSERT_TRUE(memcmp(para.para.dhPara.p, para2.para.dhPara.p, para.para.dhPara.pLen) == 0); ASSERT_TRUE(para.para.dhPara.qLen == para2.para.dhPara.qLen); ASSERT_TRUE(memcmp(para.para.dhPara.q, para2.para.dhPara.q, para.para.dhPara.qLen) == 0); ASSERT_TRUE(para.para.dhPara.gLen == para2.para.dhPara.gLen); ASSERT_TRUE(memcmp(para.para.dhPara.g, para2.para.dhPara.g, para.para.dhPara.gLen) == 0); EXIT: CRYPT_EAL_PkeyFreeCtx(pKey); } /* END_CASE */ /** * @test SDV_CRYPTO_DH_CMP_API_TC001 * @title DH: CRYPT_EAL_PkeyCmp invalid parameter test. * @precon Registering memory-related functions. * para id and public key. * @brief * 1. Create the contexts(ctx1, ctx2) of the dh algorithm, expected result 1 * 2. Call the CRYPT_EAL_PkeyCmp to compare ctx1 and ctx2, expected result 2 * 3. Set public key for ctx1, expected result 3 * 4. Call the CRYPT_EAL_PkeyCmp to compare ctx1 and ctx2, expected result 4 * 5. Set public key for ctx2, expected result 5 * 6. Call the CRYPT_EAL_PkeyCmp to compare ctx1 and ctx2, expected result 6 * @expect * 1. Success, and contexts are not NULL. * 2. CRYPT_ECC_KEY_PUBKEY_NOT_EQUAL * 3. CRYPT_SUCCESS * 4. CRYPT_ECC_KEY_PUBKEY_NOT_EQUAL * 5-6. CRYPT_SUCCESS */ /* BEGIN_CASE */ void SDV_CRYPTO_DH_CMP_API_TC001(int paraId, Hex *pubKey, int isProvider) { CRYPT_EAL_PkeyPub pub = {0}; Set_DH_Pub(&pub, pubKey->x, pubKey->len); TestMemInit(); CRYPT_EAL_PkeyCtx *ctx1 = TestPkeyNewCtx(NULL, CRYPT_PKEY_DH, CRYPT_EAL_PKEY_KEYMGMT_OPERATE + CRYPT_EAL_PKEY_EXCH_OPERATE, "provider=default", isProvider); CRYPT_EAL_PkeyCtx *ctx2 = TestPkeyNewCtx(NULL, CRYPT_PKEY_DH, CRYPT_EAL_PKEY_KEYMGMT_OPERATE + CRYPT_EAL_PKEY_EXCH_OPERATE, "provider=default", isProvider); ASSERT_TRUE(ctx1 != NULL && ctx2 != NULL); ASSERT_EQ(CRYPT_EAL_PkeyCmp(ctx1, ctx2), CRYPT_DH_KEYINFO_ERROR); // no key and no para ASSERT_EQ(CRYPT_EAL_PkeySetParaById(ctx1, paraId), CRYPT_SUCCESS); ASSERT_EQ(CRYPT_EAL_PkeySetPub(ctx1, &pub), CRYPT_SUCCESS); ASSERT_EQ(CRYPT_EAL_PkeyCmp(ctx1, ctx2), CRYPT_DH_KEYINFO_ERROR); // ctx2 no pubkey ASSERT_EQ(CRYPT_EAL_PkeySetPub(ctx2, &pub), CRYPT_SUCCESS); ASSERT_EQ(CRYPT_EAL_PkeyCmp(ctx1, ctx2), CRYPT_DH_PARA_ERROR); // ctx2 no para EXIT: CRYPT_EAL_PkeyFreeCtx(ctx1); CRYPT_EAL_PkeyFreeCtx(ctx2); } /* END_CASE */ /** * @test SDV_CRYPTO_DH_CTRL_API_TC001 * @title DH: CRYPT_EAL_PkeyCtrl test. * @precon Registering memory-related functions. * @brief * 1. Create the context(ctx) of the dh algorithm, expected result 1 * 2. Call the CRYPT_EAL_PkeyCtrl method: * (1) val = NULL, expected result 2 * (2) len = 0, expected result 3 * (3) opt = CRYPT_CTRL_SET_RSA_PADDING, expected result 4 * @expect * 1. Success, and contexts are not NULL. * 2. CRYPT_NULL_INPUT * 3. CRYPT_DH_UNSUPPORTED_CTRL_OPTION * 4. CRYPT_DH_UNSUPPORTED_CTRL_OPTION */ /* BEGIN_CASE */ void SDV_CRYPTO_DH_CTRL_API_TC001(int isProvider) { int32_t ref = 1; TestMemInit(); CRYPT_EAL_PkeyCtx *ctx = TestPkeyNewCtx(NULL, CRYPT_PKEY_DH, CRYPT_EAL_PKEY_KEYMGMT_OPERATE + CRYPT_EAL_PKEY_EXCH_OPERATE, "provider=default", isProvider); ASSERT_TRUE(ctx != NULL); ASSERT_EQ(CRYPT_EAL_PkeyCtrl(ctx, CRYPT_CTRL_UP_REFERENCES, NULL, sizeof(uint32_t)), CRYPT_INVALID_ARG); ASSERT_EQ(CRYPT_EAL_PkeyCtrl(ctx, CRYPT_CTRL_UP_REFERENCES, &ref, 0), CRYPT_INVALID_ARG); ASSERT_EQ( CRYPT_EAL_PkeyCtrl(ctx, CRYPT_CTRL_SET_RSA_PADDING, &ref, sizeof(int32_t)), CRYPT_DH_UNSUPPORTED_CTRL_OPTION); EXIT: CRYPT_EAL_PkeyFreeCtx(ctx); } /* END_CASE */ /** * @test SDV_CRYPTO_DH_DUP_CTX_FUNC_TC001 * @title DH: CRYPT_EAL_PkeyDupCtx test. * @precon Registering memory-related functions. * @brief * 1. Create the context of the dh algorithm, expected result 1. * 2. Init the drbg, expected result 2. * 3. Set para by CRYPT_DH_RFC7919_8192 and, generate a key pair, expected result 3. * 4. Call the CRYPT_EAL_PkeyDupCtx method to dup dh context, expected result 4. * 5. Call the CRYPT_EAL_PkeyCmp method to compare public key, expected result 5. * 6. Call the CRYPT_EAL_PkeyGetKeyBits to get keyLen from contexts, expected result 6. * 7. Call the CRYPT_EAL_PkeyGetPub method to obtain the public key from the contexts, expected result 7. * 8. Compare public keys, expected result 8. * 9. Get para id from dupCtx, expected result 9. * @expect * 1. Success, and context is not NULL. * 2-5. CRYPT_SUCCESS * 6. The key length obtained from both contexts is the same. * 7. CRYPT_SUCCESS * 8. The two public keys are the same. * 9. Para id is CRYPT_DH_RFC7919_8192. */ /* BEGIN_CASE */ void SDV_CRYPTO_DH_DUP_CTX_FUNC_TC001(int isProvider) { uint8_t *pubKey1 = NULL; uint8_t *pubKey2 = NULL; uint32_t keyLen1; uint32_t keyLen2; CRYPT_PKEY_ParaId paraId = CRYPT_DH_RFC7919_8192; CRYPT_EAL_PkeyPub pub = {0}; CRYPT_EAL_PkeyCtx *ctx = NULL; CRYPT_EAL_PkeyCtx *dupCtx = NULL; TestMemInit(); ctx = TestPkeyNewCtx(NULL, CRYPT_PKEY_DH, CRYPT_EAL_PKEY_KEYMGMT_OPERATE + CRYPT_EAL_PKEY_EXCH_OPERATE, "provider=default", isProvider); ASSERT_TRUE(ctx != NULL); ASSERT_EQ(TestRandInit(), CRYPT_SUCCESS); ASSERT_EQ(CRYPT_EAL_PkeySetParaById(ctx, paraId), CRYPT_SUCCESS); ASSERT_EQ(CRYPT_EAL_PkeyGen(ctx), CRYPT_SUCCESS); dupCtx = CRYPT_EAL_PkeyDupCtx(ctx); ASSERT_TRUE(dupCtx != NULL); ASSERT_EQ(CRYPT_EAL_PkeyCmp(ctx, dupCtx), CRYPT_SUCCESS); keyLen1 = CRYPT_EAL_PkeyGetKeyBits(ctx); keyLen2 = CRYPT_EAL_PkeyGetKeyBits(dupCtx); ASSERT_EQ(keyLen1, keyLen2); pubKey1 = calloc(1u, keyLen1); pubKey2 = calloc(1u, keyLen2); ASSERT_TRUE(pubKey1 != NULL && pubKey2 != NULL); Set_DH_Pub(&pub, pubKey1, keyLen1); ASSERT_EQ(CRYPT_EAL_PkeyGetPub(ctx, &pub), CRYPT_SUCCESS); Set_DH_Pub(&pub, pubKey2, keyLen2); ASSERT_EQ(CRYPT_EAL_PkeyGetPub(dupCtx, &pub), CRYPT_SUCCESS); ASSERT_COMPARE("Compare dup key", pubKey1, keyLen1, pubKey2, keyLen2); ASSERT_TRUE(CRYPT_EAL_PkeyGetParaId(dupCtx) == paraId); EXIT: TestRandDeInit(); CRYPT_EAL_PkeyFreeCtx(ctx); CRYPT_EAL_PkeyFreeCtx(dupCtx); BSL_SAL_Free(pubKey1); BSL_SAL_Free(pubKey2); } /* END_CASE */ /** * @test SDV_CRYPTO_DH_GET_KEY_BITS_FUNC_TC001 * @title DH: get key bits. * @brief * 1. Create a context of the DH algorithm, expected result 1 * 2. Get key bits, expected result 2 * @expect * 1. Success, and context is not NULL. * 2. Equal to keyBits. */ /* BEGIN_CASE */ void SDV_CRYPTO_DH_GET_KEY_BITS_FUNC_TC001(int id, int keyBits, Hex *p, Hex *g, Hex *q, int isProvider) { CRYPT_EAL_PkeyCtx *pkey = TestPkeyNewCtx(NULL, id, CRYPT_EAL_PKEY_KEYMGMT_OPERATE + CRYPT_EAL_PKEY_EXCH_OPERATE, "provider=default", isProvider); ASSERT_TRUE(pkey != NULL); CRYPT_EAL_PkeyPara para; para.id = id; para.para.dhPara.p = p->x; para.para.dhPara.pLen = p->len; para.para.dhPara.q = q->x; para.para.dhPara.qLen = q->len; para.para.dhPara.g = g->x; para.para.dhPara.gLen = g->len; ASSERT_TRUE(CRYPT_EAL_PkeySetPara(pkey, &para) == CRYPT_SUCCESS); ASSERT_TRUE(CRYPT_EAL_PkeyGetKeyBits(pkey) == (uint32_t)keyBits); EXIT: CRYPT_EAL_PkeyFreeCtx(pkey); } /* END_CASE */ /** * @test SDV_CRYPTO_DH_TEST_FLAG_SET_TC002 * @title for test dh flag setting no leading flag. */ /* BEGIN_CASE */ void SDV_CRYPTO_DH_TEST_FLAG_SET_TC001(Hex *p, Hex *g, Hex *q, Hex *prv1, Hex *pub2, Hex *share, int isProvider) { CRYPT_RandRegist(RandFunc); CRYPT_RandRegistEx(RandFuncEx); uint8_t shareLocal[1030]; uint32_t shareLen = sizeof(shareLocal); uint32_t flag = CRYPT_DH_NO_PADZERO; CRYPT_EAL_PkeyPara para = {0}; CRYPT_EAL_PkeyPrv prv = {0}; CRYPT_EAL_PkeyPub pub = {0}; Set_DH_Para(&para, p->x, q->x, g->x, p->len, q->len, g->len); Set_DH_Prv(&prv, prv1->x, prv1->len); Set_DH_Pub(&pub, pub2->x, pub2->len); TestMemInit(); CRYPT_EAL_PkeyCtx *pkey1 = TestPkeyNewCtx(NULL, CRYPT_PKEY_DH, CRYPT_EAL_PKEY_KEYMGMT_OPERATE + CRYPT_EAL_PKEY_EXCH_OPERATE, "provider=default", isProvider); CRYPT_EAL_PkeyCtx *pkey2 = TestPkeyNewCtx(NULL, CRYPT_PKEY_DH, CRYPT_EAL_PKEY_KEYMGMT_OPERATE + CRYPT_EAL_PKEY_EXCH_OPERATE, "provider=default", isProvider); ASSERT_TRUE(pkey1 != NULL && pkey2 != NULL); ASSERT_TRUE(CRYPT_EAL_PkeySetPara(pkey1, &para) == CRYPT_SUCCESS); ASSERT_TRUE(CRYPT_EAL_PkeySetPrv(pkey1, &prv) == CRYPT_SUCCESS); ASSERT_TRUE(CRYPT_EAL_PkeySetPub(pkey2, &pub) == CRYPT_SUCCESS); ASSERT_TRUE(CRYPT_EAL_PkeyCtrl(pkey1, CRYPT_CTRL_SET_DH_FLAG, (void *)&flag, sizeof(uint32_t)) == CRYPT_SUCCESS); ASSERT_TRUE(CRYPT_EAL_PkeyComputeShareKey(pkey1, pkey2, shareLocal, &shareLen) == CRYPT_SUCCESS); ASSERT_TRUE(shareLen == share->len - 1); // The highest bit of this vector is 0 ASSERT_TRUE(memcmp(shareLocal, share->x + 1, shareLen) == 0); EXIT: CRYPT_EAL_PkeyFreeCtx(pkey1); CRYPT_EAL_PkeyFreeCtx(pkey2); } /* END_CASE */ /** * @test SDV_CRYPTO_DH_CHECK_KEYPAIR_TC001 * @brief * Create a dh key pairs to check the key pair consistency. */ /* BEGIN_CASE */ void SDV_CRYPTO_DH_CHECK_KEYPAIR_TC001(Hex *p, Hex *g, Hex *q, int isProvider) { #if !defined(HITLS_CRYPTO_DH_CHECK) (void)p; (void)g; (void)q; (void)isProvider; SKIP_TEST(); #else CRYPT_EAL_PkeyPara para = {0}; Set_DH_Para(&para, p->x, q->x, g->x, p->len, q->len, g->len); TestMemInit(); CRYPT_EAL_PkeyCtx *pkey = TestPkeyNewCtx(NULL, CRYPT_PKEY_DH, CRYPT_EAL_PKEY_KEYMGMT_OPERATE + CRYPT_EAL_PKEY_EXCH_OPERATE, "provider=default", isProvider); ASSERT_TRUE(pkey != NULL); ASSERT_EQ(TestRandInit(), CRYPT_SUCCESS); ASSERT_TRUE(CRYPT_EAL_PkeySetPara(pkey, &para) == CRYPT_SUCCESS); ASSERT_TRUE(CRYPT_EAL_PkeyGen(pkey) == CRYPT_SUCCESS); ASSERT_TRUE(CRYPT_EAL_PkeyPairCheck(pkey, pkey) == CRYPT_SUCCESS); EXIT: TestRandDeInit(); CRYPT_EAL_PkeyFreeCtx(pkey); #endif } /* END_CASE */ /** * @test SDV_CRYPTO_DH_CHECK_KEYPAIR_TC002 * @brief * Create a dh key pairs to check the key pair consistency. */ /* BEGIN_CASE */ void SDV_CRYPTO_DH_CHECK_KEYPAIR_TC002(int id, int isProvider) { #if !defined(HITLS_CRYPTO_DH_CHECK) (void)id; (void)isProvider; SKIP_TEST(); #else TestMemInit(); CRYPT_EAL_PkeyCtx *pkey = TestPkeyNewCtx(NULL, CRYPT_PKEY_DH, CRYPT_EAL_PKEY_KEYMGMT_OPERATE + CRYPT_EAL_PKEY_EXCH_OPERATE, "provider=default", isProvider); ASSERT_TRUE(pkey != NULL); ASSERT_EQ(TestRandInit(), CRYPT_SUCCESS); ASSERT_TRUE(CRYPT_EAL_PkeySetParaById(pkey, id) == CRYPT_SUCCESS); ASSERT_TRUE(CRYPT_EAL_PkeyGen(pkey) == CRYPT_SUCCESS); ASSERT_TRUE(CRYPT_EAL_PkeyPairCheck(pkey, pkey) == CRYPT_SUCCESS); EXIT: TestRandDeInit(); CRYPT_EAL_PkeyFreeCtx(pkey); #endif } /* END_CASE */ /** * @test SDV_CRYPTO_DH_CHECK_KEYPAIR_INVALIED_TC001 * @brief * Create a dh key pairs to check the key pair consistency. */ /* BEGIN_CASE */ void SDV_CRYPTO_DH_CHECK_KEYPAIR_INVALIED_TC001(Hex *p, Hex *g, Hex *q, int isProvider) { #if !defined(HITLS_CRYPTO_DH_CHECK) (void)p; (void)g; (void)q; (void)isProvider; SKIP_TEST(); #else TestMemInit(); uint8_t pubKey[1030]; uint32_t pubKeyLen = sizeof(pubKey); uint8_t prvKey[1030]; uint32_t prvKeyLen = sizeof(prvKey); CRYPT_EAL_PkeyPub pub = {0}; CRYPT_EAL_PkeyPrv prv = {0}; Set_DH_Pub(&pub, pubKey, pubKeyLen); Set_DH_Prv(&prv, prvKey, prvKeyLen); CRYPT_EAL_PkeyPara para = {0}; Set_DH_Para(&para, p->x, q->x, g->x, p->len, q->len, g->len); CRYPT_EAL_PkeyCtx *pkey = TestPkeyNewCtx(NULL, CRYPT_PKEY_DH, CRYPT_EAL_PKEY_KEYMGMT_OPERATE + CRYPT_EAL_PKEY_EXCH_OPERATE, "provider=default", isProvider); CRYPT_EAL_PkeyCtx *pubCtx = TestPkeyNewCtx(NULL, CRYPT_PKEY_DH, CRYPT_EAL_PKEY_KEYMGMT_OPERATE + CRYPT_EAL_PKEY_EXCH_OPERATE, "provider=default", isProvider); CRYPT_EAL_PkeyCtx *prvCtx = TestPkeyNewCtx(NULL, CRYPT_PKEY_DH, CRYPT_EAL_PKEY_KEYMGMT_OPERATE + CRYPT_EAL_PKEY_EXCH_OPERATE, "provider=default", isProvider); ASSERT_TRUE(pkey != NULL); ASSERT_TRUE(prvCtx != NULL); ASSERT_TRUE(pubCtx != NULL); ASSERT_EQ(TestRandInit(), CRYPT_SUCCESS); ASSERT_TRUE(CRYPT_EAL_PkeySetPara(pkey, &para) == CRYPT_SUCCESS); ASSERT_TRUE(CRYPT_EAL_PkeySetPara(pubCtx, &para) == CRYPT_SUCCESS); ASSERT_TRUE(CRYPT_EAL_PkeySetPara(prvCtx, &para) == CRYPT_SUCCESS); ASSERT_TRUE(CRYPT_EAL_PkeyGen(pkey) == CRYPT_SUCCESS); // get prv and pub ASSERT_TRUE(CRYPT_EAL_PkeyGetPub(pkey, &pub) == CRYPT_SUCCESS); ASSERT_TRUE(CRYPT_EAL_PkeyGetPrv(pkey, &prv) == CRYPT_SUCCESS); ASSERT_TRUE(CRYPT_EAL_PkeyPairCheck(NULL, NULL) == CRYPT_NULL_INPUT); ASSERT_TRUE(CRYPT_EAL_PkeySetPub(pubCtx, &pub) == CRYPT_SUCCESS); ASSERT_TRUE(CRYPT_EAL_PkeyPairCheck(pubCtx, prvCtx) == CRYPT_NULL_INPUT); // no prv key ASSERT_TRUE(CRYPT_EAL_PkeySetPrv(prvCtx, &prv) == CRYPT_SUCCESS); ASSERT_TRUE(CRYPT_EAL_PkeyPairCheck(pubCtx, prvCtx) == CRYPT_SUCCESS); ASSERT_TRUE(CRYPT_EAL_PkeyGen(pubCtx) == CRYPT_SUCCESS); ASSERT_TRUE(CRYPT_EAL_PkeyPairCheck(pubCtx, prvCtx) == CRYPT_DH_PAIRWISE_CHECK_FAIL); EXIT: TestRandDeInit(); CRYPT_EAL_PkeyFreeCtx(pkey); CRYPT_EAL_PkeyFreeCtx(pubCtx); CRYPT_EAL_PkeyFreeCtx(prvCtx); #endif } /* END_CASE */ /** * @test SDV_CRYPTO_DH_CHECK_PRV_TC001 * @brief * Create a dh key pairs to check the prv key. */ /* BEGIN_CASE */ void SDV_CRYPTO_DH_CHECK_PRV_TC001(Hex *p, Hex *g, Hex *q, int isProvider) { #if !defined(HITLS_CRYPTO_DH_CHECK) (void)p; (void)g; (void)q; (void)isProvider; SKIP_TEST(); #else TestMemInit(); int32_t bits; CRYPT_EAL_PkeyPara para = {0}; Set_DH_Para(&para, p->x, q->x, g->x, p->len, q->len, g->len); BN_BigNum *x = NULL; CRYPT_DH_Ctx *ctx = NULL; BN_BigNum *maxValue = NULL; CRYPT_EAL_PkeyCtx *pkey = TestPkeyNewCtx(NULL, CRYPT_PKEY_DH, CRYPT_EAL_PKEY_KEYMGMT_OPERATE + CRYPT_EAL_PKEY_EXCH_OPERATE, "provider=default", isProvider); ASSERT_TRUE(pkey != NULL); ASSERT_EQ(TestRandInit(), CRYPT_SUCCESS); ASSERT_TRUE(CRYPT_EAL_PkeySetPara(pkey, &para) == CRYPT_SUCCESS); ASSERT_EQ(CRYPT_EAL_PkeyPrvCheck(NULL), CRYPT_NULL_INPUT); ASSERT_EQ(CRYPT_EAL_PkeyPrvCheck(pkey), CRYPT_NULL_INPUT); ASSERT_TRUE(CRYPT_EAL_PkeyGen(pkey) == CRYPT_SUCCESS); // get prv and pub ASSERT_EQ(CRYPT_EAL_PkeyPrvCheck(pkey), CRYPT_SUCCESS); ctx = (CRYPT_DH_Ctx *)pkey->key; x = ctx->x; if (q->len != 0) { ctx->x = ctx->para->q; ASSERT_EQ(CRYPT_EAL_PkeyPrvCheck(pkey), CRYPT_DH_INVALID_PRVKEY); } else { maxValue = BN_Create(0); bits = BN_Bits(ctx->para->p); ASSERT_EQ(BN_SetLimb(maxValue, 1), CRYPT_SUCCESS); BN_Lshift(maxValue, maxValue, bits); ctx->x = maxValue; ASSERT_EQ(CRYPT_EAL_PkeyPrvCheck(pkey), CRYPT_DH_INVALID_PRVKEY); } ctx->x = x; EXIT: BN_Destroy(maxValue); TestRandDeInit(); CRYPT_EAL_PkeyFreeCtx(pkey); #endif } /* END_CASE */
2301_79861745/bench_create
testcode/sdv/testcase/crypto/dh/test_suite_sdv_eal_dh.c
C
unknown
68,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. */ /* BEGIN_HEADER */ #include <stdint.h> #include <stddef.h> #include <stdbool.h> #include <pthread.h> #include "crypt_eal_init.h" #include "securec.h" #include "bsl_errno.h" #include "bsl_sal.h" #include "crypt_errno.h" #include "crypt_algid.h" #include "crypt_types.h" #include "crypt_eal_rand.h" #include "crypt_eal_implprovider.h" #include "drbg_local.h" #include "eal_md_local.h" #include "crypt_drbg_local.h" #include "bsl_err_internal.h" #include "bsl_err.h" #include "bsl_params.h" #include "crypt_params_key.h" #include "crypt_provider.h" /* END_HEADER */ #define CTR_AES128_SEEDLEN (32) #define AES_BLOCK_LEN (16) #define TEST_DRBG_DATA_SIZE (256) #define DRBG_OUTPUT_SIZE (1024) #define DRBG_MAX_OUTPUT_SIZE (65536) #define DRBG_MAX_ADIN_SIZE (65536) typedef struct { bool entropyState; bool nonceState; } CallBackCtl_t; typedef enum { RAND_AES128_KEYLEN = 16, RAND_AES192_KEYLEN = 24, RAND_AES256_KEYLEN = 32, } RAND_AES_KeyLen; CallBackCtl_t g_callBackCtl = { 0 }; typedef struct { CRYPT_Data *entropy; CRYPT_Data *nonce; CRYPT_Data *pers; CRYPT_Data *addin1; CRYPT_Data *entropyPR1; CRYPT_Data *addin2; CRYPT_Data *entropyPR2; CRYPT_Data *retBits; } DRBG_Vec_t; #define DRBG_FREE(ptr) \ do { \ if ((ptr) != NULL) { \ free(ptr); \ } \ } while (0) static int32_t PthreadRWLockNew(BSL_SAL_ThreadLockHandle *lock) { if (lock == NULL) { return BSL_SAL_ERR_BAD_PARAM; } pthread_rwlock_t *newLock; newLock = (pthread_rwlock_t *)malloc(sizeof(pthread_rwlock_t)); if (newLock == NULL) { return BSL_MALLOC_FAIL; } if (pthread_rwlock_init(newLock, NULL) != 0) { return BSL_SAL_ERR_UNKNOWN; } *lock = newLock; return BSL_SUCCESS; } static void PthreadRWLockFree(BSL_SAL_ThreadLockHandle lock) { if (lock == NULL) { return; } pthread_rwlock_destroy((pthread_rwlock_t *)lock); DRBG_FREE(lock); } static int32_t PthreadRWLockReadLock(BSL_SAL_ThreadLockHandle lock) { if (lock == NULL) { return BSL_SAL_ERR_BAD_PARAM; } if (pthread_rwlock_rdlock((pthread_rwlock_t *)lock) != 0) { return BSL_SAL_ERR_UNKNOWN; } return BSL_SUCCESS; } static int32_t PthreadRWLockWriteLock(BSL_SAL_ThreadLockHandle lock) { if (lock == NULL) { return BSL_SAL_ERR_BAD_PARAM; } if (pthread_rwlock_wrlock((pthread_rwlock_t *)lock) != 0) { return BSL_SAL_ERR_UNKNOWN; } return BSL_SUCCESS; } static int32_t PthreadRWLockUnlock(BSL_SAL_ThreadLockHandle lock) { if (lock == NULL) { return BSL_SAL_ERR_BAD_PARAM; } if (pthread_rwlock_unlock((pthread_rwlock_t *)lock) != 0) { return BSL_SAL_ERR_UNKNOWN; } return BSL_SUCCESS; } static uint64_t PthreadGetId(void) { return (uint64_t)pthread_self(); } static void RegThreadFunc(void) { BSL_SAL_CallBack_Ctrl(BSL_SAL_THREAD_LOCK_NEW_CB_FUNC, PthreadRWLockNew); BSL_SAL_CallBack_Ctrl(BSL_SAL_THREAD_LOCK_FREE_CB_FUNC, PthreadRWLockFree); BSL_SAL_CallBack_Ctrl(BSL_SAL_THREAD_LOCK_READ_LOCK_CB_FUNC, PthreadRWLockReadLock); BSL_SAL_CallBack_Ctrl(BSL_SAL_THREAD_LOCK_WRITE_LOCK_CB_FUNC, PthreadRWLockWriteLock); BSL_SAL_CallBack_Ctrl(BSL_SAL_THREAD_LOCK_UNLOCK_CB_FUNC, PthreadRWLockUnlock); BSL_SAL_CallBack_Ctrl(BSL_SAL_THREAD_GET_ID_CB_FUNC, PthreadGetId); } static void seedCtxFree(DRBG_Vec_t *seedCtx) { if (seedCtx != NULL) { DRBG_FREE(seedCtx->entropy); DRBG_FREE(seedCtx->entropyPR1); DRBG_FREE(seedCtx->entropyPR2); DRBG_FREE(seedCtx->addin1); DRBG_FREE(seedCtx->addin2); DRBG_FREE(seedCtx->nonce); DRBG_FREE(seedCtx->retBits); DRBG_FREE(seedCtx->pers); } free(seedCtx); } static DRBG_Vec_t *seedCtxMem(void) { DRBG_Vec_t *seedCtx; seedCtx = calloc(1u, sizeof(DRBG_Vec_t)); ASSERT_TRUE(seedCtx != NULL); seedCtx->entropy = calloc(1u, sizeof(CRYPT_Data)); ASSERT_TRUE(seedCtx->entropy != NULL); seedCtx->entropyPR1 = calloc(1u, sizeof(CRYPT_Data)); ASSERT_TRUE(seedCtx->entropyPR1 != NULL); seedCtx->entropyPR2 = calloc(1u, sizeof(CRYPT_Data)); ASSERT_TRUE(seedCtx->entropyPR2 != NULL); seedCtx->addin1 = calloc(1u, sizeof(CRYPT_Data)); ASSERT_TRUE(seedCtx->addin1 != NULL); seedCtx->addin2 = calloc(1u, sizeof(CRYPT_Data)); ASSERT_TRUE(seedCtx->addin2 != NULL); seedCtx->nonce = calloc(1u, sizeof(CRYPT_Data)); ASSERT_TRUE(seedCtx->nonce != NULL); seedCtx->retBits = calloc(1u, sizeof(CRYPT_Data)); ASSERT_TRUE(seedCtx->retBits != NULL); seedCtx->pers = calloc(1u, sizeof(CRYPT_Data)); ASSERT_TRUE(seedCtx->pers != NULL); return seedCtx; EXIT: seedCtxFree(seedCtx); return NULL; } /* Initializes the drbg context seed. Internally, ensure that the parameters are correct. */ static void seedCtxCfg(DRBG_Vec_t *seedCtx, Hex *entropy, Hex *nonce, Hex *pers, Hex *addin1, Hex *entropyPR1, Hex *addin2, Hex *entropyPR2, Hex *retBits) { seedCtx->entropy->data = entropy->x; seedCtx->entropy->len = entropy->len; seedCtx->nonce->data = nonce->x; seedCtx->nonce->len = nonce->len; seedCtx->pers->data = pers->x; seedCtx->pers->len = pers->len; seedCtx->addin1->data = addin1->x; seedCtx->addin1->len = addin1->len; seedCtx->entropyPR1->data = entropyPR1->x; seedCtx->entropyPR1->len = entropyPR1->len; seedCtx->addin2->data = addin2->x; seedCtx->addin2->len = addin2->len; seedCtx->entropyPR2->data = entropyPR2->x; seedCtx->entropyPR2->len = entropyPR2->len; seedCtx->retBits->data = retBits->x; seedCtx->retBits->len = retBits->len; } static int32_t getEntropyError(void *ctx, CRYPT_Data *entropy, uint32_t strength, CRYPT_Range *lenRange) { (void)strength; (void)lenRange; CallBackCtl_t *state = (CallBackCtl_t *)ctx; if (state->entropyState != 0) { entropy = NULL; return CRYPT_DRBG_FAIL_GET_ENTROPY; } uint32_t entroyLen = sizeof(uint8_t) * TEST_DRBG_DATA_SIZE; entropy->data = calloc(1u, entroyLen); entropy->len = entroyLen; return CRYPT_SUCCESS; } static void cleanEntropyError(void *ctx, CRYPT_Data *entropy) { (void)ctx; if (entropy != NULL && entropy->data != NULL) { free(entropy->data); } return; } static int32_t getNonceError(void *ctx, CRYPT_Data *nonce, uint32_t strength, CRYPT_Range *lenRange) { (void)strength; (void)lenRange; CallBackCtl_t *state = (CallBackCtl_t *)ctx; if (state->nonceState != 0) { nonce = NULL; return CRYPT_DRBG_FAIL_GET_NONCE; } uint32_t nonceLen = sizeof(uint8_t) * TEST_DRBG_DATA_SIZE; nonce->data = calloc(1u, nonceLen); nonce->len = nonceLen; return CRYPT_SUCCESS; } static void cleanNonceError(void *ctx, CRYPT_Data *nonce) { (void)ctx; if (nonce != NULL && nonce->data != NULL) { free(nonce->data); } return; } static int32_t getEntropy(void *ctx, CRYPT_Data *entropy, uint32_t strength, CRYPT_Range *lenRange) { (void)strength; if (ctx == NULL || entropy == NULL || lenRange == NULL) { return CRYPT_NULL_INPUT; } DRBG_Vec_t *seedCtx = (DRBG_Vec_t *)ctx; if (seedCtx->entropy->len > lenRange->max || seedCtx->entropy->len < lenRange->min) { return CRYPT_DRBG_INVALID_LEN; } entropy->data = seedCtx->entropy->data; entropy->len = seedCtx->entropy->len; return CRYPT_SUCCESS; } static void cleanEntropy(void *ctx, CRYPT_Data *entropy) { if (ctx == NULL || entropy == NULL) { return; } return; } static int32_t getNonce(void *ctx, CRYPT_Data *nonce, uint32_t strength, CRYPT_Range *lenRange) { (void)strength; if (ctx == NULL || nonce == NULL || lenRange == NULL) { return CRYPT_NULL_INPUT; } DRBG_Vec_t *seedCtx = (DRBG_Vec_t *)ctx; if (seedCtx->nonce->len > lenRange->max || seedCtx->nonce->len < lenRange->min) { return CRYPT_DRBG_INVALID_LEN; } nonce->data = seedCtx->nonce->data; nonce->len = seedCtx->nonce->len; return CRYPT_SUCCESS; } static void cleanNonce(void *ctx, CRYPT_Data *nonce) { if (ctx == NULL || nonce == NULL) { return; } return; } static int32_t getEntropyUnCheckPara(void *ctx, CRYPT_Data *entropy, uint32_t strength, CRYPT_Range *lenRange) { (void)strength; (void)lenRange; DRBG_Vec_t *seedCtx = (DRBG_Vec_t *)ctx; entropy->data = seedCtx->entropy->data; entropy->len = seedCtx->entropy->len; return CRYPT_SUCCESS; } static int32_t getNonceUnCheckPara(void *ctx, CRYPT_Data *nonce, uint32_t strength, CRYPT_Range *lenRange) { (void)strength; (void)lenRange; DRBG_Vec_t *seedCtx = (DRBG_Vec_t *)ctx; nonce->data = seedCtx->nonce->data; nonce->len = seedCtx->nonce->len; return CRYPT_SUCCESS; } static void regSeedMeth(CRYPT_RandSeedMethod *seedMeth) { seedMeth->getEntropy = getEntropy; seedMeth->cleanEntropy = cleanEntropy; seedMeth->getNonce = getNonce; seedMeth->cleanNonce = cleanNonce; } static void drbgDataInit(CRYPT_Data *data, uint32_t size) { uint8_t *dataTmp = NULL; if (size != 0) { dataTmp = malloc(sizeof(uint8_t) * size); if (dataTmp == NULL) { return; } (void)memset_s(dataTmp, size, 0, size); } data->data = dataTmp; data->len = size; } static void drbgDataFree(CRYPT_Data *data) { if (data != NULL) { if (data->data != NULL) { free(data->data); } } } /* Mapping between RAND and specific random number generation algorithms */ static const int g_drbgMethodMap[] = { CRYPT_MD_SHA1, CRYPT_MD_SHA224, CRYPT_MD_SHA256, CRYPT_MD_SHA384, CRYPT_MD_SHA512, CRYPT_MD_SM3, CRYPT_MAC_HMAC_SHA1, CRYPT_MAC_HMAC_SHA224, CRYPT_MAC_HMAC_SHA256, CRYPT_MAC_HMAC_SHA384, CRYPT_MAC_HMAC_SHA512, CRYPT_SYM_AES128, CRYPT_SYM_AES192, CRYPT_SYM_AES256, CRYPT_SYM_AES128, CRYPT_SYM_AES192, CRYPT_SYM_AES256 }; static uint32_t GetAesKeyLen(int id, uint32_t *keyLen) { switch (id) { case CRYPT_SYM_AES128: *keyLen = RAND_AES128_KEYLEN; break; case CRYPT_SYM_AES192: *keyLen = RAND_AES192_KEYLEN; break; case CRYPT_SYM_AES256: *keyLen = RAND_AES256_KEYLEN; break; default: return CRYPT_DRBG_ALG_NOT_SUPPORT; } return CRYPT_SUCCESS; } static void InitSeedCtx(CRYPT_RAND_AlgId id, DRBG_Vec_t *seedCtx, CRYPT_Data *data) { if (id < CRYPT_RAND_AES128_CTR || id > CRYPT_RAND_AES256_CTR) { drbgDataInit(data, TEST_DRBG_DATA_SIZE); seedCtx->entropy = data; seedCtx->nonce = data; } else { uint32_t keyLen = 0; GetAesKeyLen(g_drbgMethodMap[id - CRYPT_RAND_SHA1], &keyLen); drbgDataInit(data, (AES_BLOCK_LEN + keyLen)); seedCtx->entropy = data; } return; } static int sdvCryptEalRandSeedAdinApiTest(uint8_t *addin, uint32_t addinLen) { int ret; uint8_t *output = NULL; CRYPT_Data data = { 0 }; CRYPT_RandSeedMethod seedMeth = { 0 }; DRBG_Vec_t seedCtx = { 0 }; TestMemInit(); regSeedMeth(&seedMeth); drbgDataInit(&data, TEST_DRBG_DATA_SIZE); seedCtx.entropy = &data; seedCtx.nonce = &data; ASSERT_EQ(CRYPT_EAL_RandInit(CRYPT_RAND_SHA256, &seedMeth, &seedCtx, NULL, 0), CRYPT_SUCCESS); output = malloc(sizeof(uint8_t) * DRBG_OUTPUT_SIZE); ASSERT_TRUE(output != NULL); (void)memset_s(output, sizeof(uint8_t) * DRBG_OUTPUT_SIZE, 0, sizeof(uint8_t) * DRBG_OUTPUT_SIZE); ret = CRYPT_EAL_RandbytesWithAdin(output, DRBG_OUTPUT_SIZE, NULL, 0); ASSERT_EQ(ret, CRYPT_SUCCESS); ret = CRYPT_EAL_RandSeedWithAdin(addin, addinLen); ASSERT_EQ(ret, CRYPT_SUCCESS); ret = CRYPT_EAL_RandSeed(); ASSERT_EQ(ret, CRYPT_SUCCESS); EXIT: CRYPT_EAL_RandDeinit(); drbgDataFree(&data); free(output); return ret; } static int sdvCryptEalDrbgSeedAdinApiTest(uint8_t *addin, uint32_t addinLen) { int ret; uint8_t *output = NULL; CRYPT_Data data = { 0 }; CRYPT_RandSeedMethod seedMeth = { 0 }; DRBG_Vec_t seedCtx = { 0 }; void *drbgCtx = NULL; TestMemInit(); regSeedMeth(&seedMeth); drbgDataInit(&data, TEST_DRBG_DATA_SIZE); seedCtx.entropy = &data; seedCtx.nonce = &data; drbgCtx = CRYPT_EAL_DrbgNew(CRYPT_RAND_SHA256, &seedMeth, &seedCtx); ASSERT_TRUE(drbgCtx != NULL); ASSERT_TRUE(CRYPT_EAL_DrbgInstantiate(drbgCtx, NULL, 0) == CRYPT_SUCCESS); output = malloc(sizeof(uint8_t) * DRBG_OUTPUT_SIZE); ASSERT_TRUE(output != NULL); (void)memset_s(output, sizeof(uint8_t) * DRBG_OUTPUT_SIZE, 0, sizeof(uint8_t) * DRBG_OUTPUT_SIZE); ret = CRYPT_EAL_DrbgbytesWithAdin(drbgCtx, output, DRBG_OUTPUT_SIZE, NULL, 0); ASSERT_EQ(ret, CRYPT_SUCCESS); ret = CRYPT_EAL_DrbgSeedWithAdin(drbgCtx, addin, addinLen); ASSERT_EQ(ret, CRYPT_SUCCESS); ret = CRYPT_EAL_DrbgSeed(drbgCtx); ASSERT_EQ(ret, CRYPT_SUCCESS); EXIT: CRYPT_EAL_DrbgDeinit(drbgCtx); drbgDataFree(&data); free(output); return ret; } static void sdvCryptEalThreadTest(void *drbgCtx) { int i = 0; int ret; uint8_t *output = NULL; output = malloc(sizeof(uint8_t) * DRBG_OUTPUT_SIZE); ASSERT_TRUE(output != NULL); for (i = 0; i < 100; i++) { // Perform 100 * 2 times random number generation in the thread. ret = CRYPT_EAL_DrbgbytesWithAdin(drbgCtx, output, sizeof(uint8_t) * DRBG_OUTPUT_SIZE, NULL, 0); ASSERT_EQ(ret, CRYPT_SUCCESS); ret = CRYPT_EAL_DrbgSeedWithAdin(drbgCtx, NULL, 0); ASSERT_EQ(ret, CRYPT_SUCCESS); ret = CRYPT_EAL_DrbgbytesWithAdin(drbgCtx, output, sizeof(uint8_t) * DRBG_OUTPUT_SIZE, NULL, 0); ASSERT_EQ(ret, CRYPT_SUCCESS); } EXIT: DRBG_FREE(output); return; } static void sdvCryptGlobalThreadTest(void) { int i = 0; uint8_t *output = NULL; output = malloc(sizeof(uint8_t) * DRBG_OUTPUT_SIZE); ASSERT_TRUE(output != NULL); for (i = 0; i < 100; i++) { // Perform 100 times random number generation in the thread. ASSERT_EQ(CRYPT_EAL_Randbytes(output, sizeof(uint8_t) * DRBG_OUTPUT_SIZE), CRYPT_SUCCESS); } EXIT: DRBG_FREE(output); return; } /** * @test SDV_CRYPT_DRBG_RAND_INIT_API_TC001 * @title Use different algorithm ID to initialize the DRBG. * @precon nan * @brief * 1.Initialize the random number seed, expected result 1. * 2.Call CRYPT_EAL_RandInit, expected result 2. * 3.Call CRYPT_EAL_DrbgNew, expected result 3. * @expect * 1.successful. * 2.Success with or without a random number seed. * 3.successful. */ /* BEGIN_CASE */ void SDV_CRYPT_DRBG_RAND_INIT_API_TC001(int algId) { if (IsRandAlgDisabled(algId)) { SKIP_TEST(); } void *drbg = NULL; CRYPT_RandSeedMethod seedMeth = { 0 }; CRYPT_Data data = { 0 }; DRBG_Vec_t seedCtx = { 0 }; TestMemInit(); seedMeth.getEntropy = getEntropy; seedMeth.cleanEntropy = cleanEntropy; InitSeedCtx(algId, &seedCtx, &data); ASSERT_EQ(CRYPT_EAL_RandInit(algId, &seedMeth, (void *)&seedCtx, NULL, 0), CRYPT_SUCCESS); CRYPT_EAL_RandDeinit(); ASSERT_EQ(CRYPT_EAL_RandInit(algId, NULL, NULL, NULL, 0), CRYPT_SUCCESS); CRYPT_EAL_RandDeinit(); drbg = CRYPT_EAL_DrbgNew(algId, &seedMeth, &seedCtx); ASSERT_TRUE(drbg != NULL); ASSERT_TRUE(CRYPT_EAL_DrbgInstantiate(drbg, NULL, 0) == CRYPT_SUCCESS); EXIT: CRYPT_EAL_RandDeinit(); CRYPT_EAL_DrbgDeinit(drbg); drbgDataFree(&data); return; } /* END_CASE */ /** * @test SDV_CRYPT_DRBG_RAND_INIT_API_TC002 * @title DRBG initialization test,the value of data is 0 or 255. * @precon nan * @brief * 1.Initialize the random number seed, expected result 1. * 2.Call CRYPT_EAL_RandInit, expected result 2. * 3.Call CRYPT_EAL_DrbgNew, expected result 3. * @expect * 1.successful. * 2.successful. * 3.successful. */ /* BEGIN_CASE */ void SDV_CRYPT_DRBG_RAND_INIT_API_TC002(int agId, int value, int size) { uint8_t *pers = malloc(size); ASSERT_TRUE(pers != NULL); ASSERT_EQ(memset_s(pers, size, value, size), 0); void *drbg = NULL; CRYPT_RandSeedMethod seedMeth = { 0 }; CRYPT_Data data = { 0 }; DRBG_Vec_t seedCtx = { 0 }; TestMemInit(); regSeedMeth(&seedMeth); drbgDataInit(&data, size); seedCtx.entropy = &data; seedCtx.nonce = &data; ASSERT_EQ(CRYPT_EAL_RandInit(agId, &seedMeth, (void *)&seedCtx, pers, size), CRYPT_SUCCESS); CRYPT_EAL_RandDeinit(); drbg = CRYPT_EAL_DrbgNew(agId, &seedMeth, &seedCtx); ASSERT_TRUE(drbg != NULL); CRYPT_EAL_DrbgDeinit(drbg); EXIT: CRYPT_EAL_RandDeinit(); drbgDataFree(&data); free(pers); return; } /* END_CASE */ /** * @test SDV_CRYPT_DRBG_RAND_INIT_API_TC003 * @title Test the impact of persLen on DRGB initialization. * @precon nan * @brief * 1.Initialize the random number seed, expected result 1. * 2.Call CRYPT_EAL_RandInit, expected result 2. * 3.Call CRYPT_EAL_DrbgNew, expected result 3. * @expect * 1.successful. * 2.successful. * 3.successful. */ /* BEGIN_CASE */ void SDV_CRYPT_DRBG_RAND_INIT_API_TC003(int agId, int size) { uint8_t *pers = malloc(TEST_DRBG_DATA_SIZE); ASSERT_TRUE(pers != NULL); void *drbg = NULL; CRYPT_RandSeedMethod seedMeth = { 0 }; CRYPT_Data data = { 0 }; DRBG_Vec_t seedCtx = { 0 }; TestMemInit(); regSeedMeth(&seedMeth); drbgDataInit(&data, size); seedCtx.entropy = &data; seedCtx.nonce = &data; ASSERT_EQ(CRYPT_EAL_RandInit(agId, &seedMeth, (void *)&seedCtx, pers, size), CRYPT_SUCCESS); CRYPT_EAL_RandDeinit(); drbg = CRYPT_EAL_DrbgNew(agId, &seedMeth, &seedCtx); ASSERT_TRUE(drbg != NULL); CRYPT_EAL_DrbgDeinit(drbg); EXIT: CRYPT_EAL_RandDeinit(); drbgDataFree(&data); free(pers); return; } /* END_CASE */ /** * @test SDV_CRYPT_DRBG_RAND_INIT_API_TC004 * @title DRBG is initialized repeatedly. * @precon nan * @brief * 1.Initialize the random number seed, expected result 1. * 2.Call CRYPT_EAL_RandInit, expected result 2. * 3.Call CRYPT_EAL_RandInit again, expected result 3. * @expect * 1.successful. * 2.successful. * 3.return failed. */ /* BEGIN_CASE */ void SDV_CRYPT_DRBG_RAND_INIT_API_TC004(int algId) { CRYPT_Data data = { 0 }; CRYPT_RandSeedMethod seedMeth = { 0 }; DRBG_Vec_t seedCtx = { 0 }; TestMemInit(); regSeedMeth(&seedMeth); drbgDataInit(&data, TEST_DRBG_DATA_SIZE); seedCtx.entropy = &data; seedCtx.nonce = &data; ASSERT_EQ(CRYPT_EAL_RandInit(algId, &seedMeth, (void *)&seedCtx, NULL, 0), CRYPT_SUCCESS); ASSERT_EQ(CRYPT_EAL_RandInit(algId, &seedMeth, (void *)&seedCtx, NULL, 0), CRYPT_EAL_ERR_DRBG_REPEAT_INIT); EXIT: CRYPT_EAL_RandDeinit(); drbgDataFree(&data); return; } /* END_CASE */ /** * @test SDV_CRYPT_DRBG_RAND_INIT_API_TC005 * @title DRBG initialization test,the configuration context parameter is empty. * @precon nan * @brief * 1.Initialize the random number seed, expected result 1. * 2.Call CRYPT_EAL_RandInit, expected result 2. * 3.Call CRYPT_EAL_DrbgNew, expected result 3. * @expect * 1.successful. * 2.successful. * 3.return NULL. */ /* BEGIN_CASE */ void SDV_CRYPT_DRBG_RAND_INIT_API_TC005(int algId) { DRBG_Vec_t seedCtx = { 0 }; void *drbg = NULL; ASSERT_EQ(CRYPT_EAL_RandInit(algId, NULL, NULL, NULL, 0), CRYPT_SUCCESS); CRYPT_EAL_RandDeinit(); ASSERT_NE(CRYPT_EAL_RandInit(algId, NULL, &seedCtx, NULL, 0), CRYPT_SUCCESS); drbg = CRYPT_EAL_DrbgNew(algId, NULL, NULL); ASSERT_TRUE(drbg != NULL); CRYPT_EAL_DrbgDeinit(drbg); drbg = CRYPT_EAL_DrbgNew(algId, NULL, &seedCtx); ASSERT_TRUE(drbg == NULL); EXIT: CRYPT_EAL_RandDeinit(); CRYPT_EAL_DrbgDeinit(drbg); return; } /* END_CASE */ /** * @test SDV_CRYPT_DRBG_RAND_INIT_API_TC006 * @title DRBG initialization test,use the abnormal persLen. * @precon nan * @brief * 1.Initialize the random number seed, expected result 1. * 2.Call CRYPT_EAL_RandInit, expected result 2. * 3.Call CRYPT_EAL_DrbgNew, expected result 3. * @expect * 1.successful. * 2.return failed. * 3.return NULL. */ /* BEGIN_CASE */ void SDV_CRYPT_DRBG_RAND_INIT_API_TC006(int algId, int keyLen) { CRYPT_Data data = { 0 }; CRYPT_RandSeedMethod seedMeth = { 0 }; DRBG_Vec_t seedCtx = { 0 }; uint8_t *pers = NULL; void *drbg = NULL; pers = malloc(TEST_DRBG_DATA_SIZE + keyLen); ASSERT_TRUE(pers != NULL); TestMemInit(); regSeedMeth(&seedMeth); drbgDataInit(&data, keyLen + 16); seedCtx.entropy = &data; seedCtx.nonce = &data; ASSERT_NE(CRYPT_EAL_RandInit(algId, &seedMeth, (void *)&seedCtx, pers, keyLen + 16 + 1), CRYPT_SUCCESS); CRYPT_EAL_RandDeinit(); drbg = CRYPT_EAL_DrbgNew(algId, &seedMeth, &seedCtx); ASSERT_TRUE(drbg != NULL); ASSERT_NE(CRYPT_EAL_DrbgInstantiate(drbg, pers, keyLen + 16 + 1), CRYPT_SUCCESS); CRYPT_EAL_DrbgDeinit(drbg); ASSERT_EQ(CRYPT_EAL_RandInit(algId, &seedMeth, (void *)&seedCtx, pers, keyLen + 16), CRYPT_SUCCESS); drbg = CRYPT_EAL_DrbgNew(algId, &seedMeth, &seedCtx); ASSERT_TRUE(drbg != NULL); EXIT: CRYPT_EAL_DrbgDeinit(drbg); CRYPT_EAL_RandDeinit(); free(data.data); free(pers); return; } /* END_CASE */ /** * @test SDV_CRYPT_DRBG_RAND_SEED_ADIN_API_TC001 * @title When the RAND is initialized and a random number has been generated, the counter is reset when the random number is obtained from personal data. * @precon nan * @brief * 1.Call sdvCryptEalRandSeedAdinApiTest,addinData is NULL, expected result 1. * 2.Call sdvCryptEalRandSeedAdinApiTest,addinData not NULL, expected result 2. * @expect * 1.All operations succeeded. * 2.All operations succeeded. */ /* BEGIN_CASE */ void SDV_CRYPT_DRBG_RAND_SEED_ADIN_API_TC001(void) { uint8_t *addinData = NULL; ASSERT_EQ(sdvCryptEalRandSeedAdinApiTest(NULL, 0), CRYPT_SUCCESS); addinData = malloc(sizeof(uint8_t) * DRBG_MAX_ADIN_SIZE); ASSERT_TRUE(addinData != NULL); ASSERT_EQ(sdvCryptEalRandSeedAdinApiTest(addinData, sizeof(uint8_t) * DRBG_MAX_ADIN_SIZE), CRYPT_SUCCESS); EXIT: free(addinData); return; } /* END_CASE */ /** * @test SDV_CRYPT_DRBG_DRBG_SEED_ADIN_API_TC001 * @title When the DRBG is initialized and a random number has been generated, the counter is reset when the random number is obtained from personal data. * @precon nan * @brief * 1.Call sdvCryptEalDrbgSeedAdinApiTest,addinData is NULL, expected result 1. * 2.Call sdvCryptEalDrbgSeedAdinApiTest,addinData not NULL, expected result 2. * @expect * 1.All operations succeeded. * 2.All operations succeeded. */ /* BEGIN_CASE */ void SDV_CRYPT_DRBG_DRBG_SEED_ADIN_API_TC001(void) { uint8_t *addinData = NULL; ASSERT_EQ(sdvCryptEalDrbgSeedAdinApiTest(NULL, 0), CRYPT_SUCCESS); addinData = malloc(sizeof(uint8_t) * DRBG_MAX_ADIN_SIZE); ASSERT_TRUE(addinData != NULL); ASSERT_EQ(sdvCryptEalDrbgSeedAdinApiTest(addinData, sizeof(uint8_t) * DRBG_MAX_ADIN_SIZE), CRYPT_SUCCESS); EXIT: free(addinData); return; } /* END_CASE */ /** * @test SDV_CRYPT_DRBG_RAND_SEED_ADIN_API_TC002 * @title Call random interface before CRYPT_EAL_RandInit. * @precon nan * @brief * 1.Call CRYPT_EAL_RandbytesWithAdin, expected result 1. * 2.Call CRYPT_EAL_Randbytes, expected result 2. * 3.Call CRYPT_EAL_RandSeedWithAdin, expected result 3. * 4.Call CRYPT_EAL_RandSeed, expected result 4. * @expect * 1.return CRYPT_EAL_ERR_GLOBAL_DRBG_NULL. * 2.return CRYPT_EAL_ERR_GLOBAL_DRBG_NULL. * 3.return CRYPT_EAL_ERR_GLOBAL_DRBG_NULL. * 4.return CRYPT_EAL_ERR_GLOBAL_DRBG_NULL. */ /* BEGIN_CASE */ void SDV_CRYPT_DRBG_RAND_SEED_ADIN_API_TC002(void) { uint8_t data[TEST_DRBG_DATA_SIZE] = {0}; ASSERT_EQ(CRYPT_EAL_RandbytesWithAdin(data, TEST_DRBG_DATA_SIZE, NULL, 0), CRYPT_EAL_ERR_GLOBAL_DRBG_NULL); ASSERT_EQ(CRYPT_EAL_Randbytes(data, TEST_DRBG_DATA_SIZE), CRYPT_EAL_ERR_GLOBAL_DRBG_NULL); ASSERT_EQ(CRYPT_EAL_RandSeedWithAdin(NULL, 0), CRYPT_EAL_ERR_GLOBAL_DRBG_NULL); ASSERT_EQ(CRYPT_EAL_RandSeed(), CRYPT_EAL_ERR_GLOBAL_DRBG_NULL); EXIT: return; } /* END_CASE */ /** * @test SDV_CRYPT_DRBG_RAND_BYTES_ADIN_ERR_PARA_API_TC001 * @title CRYPT_EAL_RandbytesWithAdin abnormal parameter test. * @precon nan * @brief * 1.Call CRYPT_EAL_DrbgbytesWithAdin,use normal parameters, expected result 1. * 2.Call CRYPT_EAL_DrbgbytesWithAdin,the array length is abnormal, expected result 2. * @expect * 1.All interface succeeded. * 2.The interface returns an exception. */ /* BEGIN_CASE */ void SDV_CRYPT_DRBG_RAND_BYTES_ADIN_ERR_PARA_API_TC001(int algId) { uint8_t *output = malloc(sizeof(uint8_t) * (DRBG_MAX_OUTPUT_SIZE + 1)); ASSERT_TRUE(output != NULL); uint8_t *addin = malloc(sizeof(uint8_t) * DRBG_MAX_ADIN_SIZE); ASSERT_TRUE(addin != NULL); CRYPT_RandSeedMethod seedMeth = { 0 }; CRYPT_Data data = { 0 }; DRBG_Vec_t seedCtx = { 0 }; regSeedMeth(&seedMeth); drbgDataInit(&data, TEST_DRBG_DATA_SIZE); seedCtx.entropy = &data; seedCtx.nonce = &data; TestMemInit(); CRYPT_EAL_RndCtx *drbgCtx = CRYPT_EAL_DrbgNew(algId, &seedMeth, &seedCtx); ASSERT_TRUE(drbgCtx != NULL); ASSERT_TRUE(CRYPT_EAL_DrbgInstantiate(drbgCtx, NULL, 0) == CRYPT_SUCCESS); memset_s(addin, DRBG_MAX_ADIN_SIZE, 0, DRBG_MAX_ADIN_SIZE); ASSERT_EQ(CRYPT_EAL_DrbgbytesWithAdin(drbgCtx, output, DRBG_MAX_OUTPUT_SIZE, addin, DRBG_MAX_ADIN_SIZE), CRYPT_SUCCESS); memset_s(addin, DRBG_MAX_ADIN_SIZE, 'F', DRBG_MAX_ADIN_SIZE); ASSERT_EQ(CRYPT_EAL_DrbgbytesWithAdin(drbgCtx, output, DRBG_MAX_OUTPUT_SIZE, addin, DRBG_MAX_ADIN_SIZE), CRYPT_SUCCESS); ASSERT_EQ(CRYPT_EAL_DrbgbytesWithAdin(drbgCtx, output, DRBG_MAX_OUTPUT_SIZE, NULL, 0), CRYPT_SUCCESS); ASSERT_EQ(CRYPT_EAL_DrbgbytesWithAdin(drbgCtx, output, DRBG_MAX_OUTPUT_SIZE, addin, 0), CRYPT_SUCCESS); memset_s(addin, DRBG_MAX_ADIN_SIZE, 0, DRBG_MAX_ADIN_SIZE); ASSERT_NE(CRYPT_EAL_DrbgbytesWithAdin(drbgCtx, output, 0, addin, DRBG_MAX_ADIN_SIZE), CRYPT_SUCCESS); ASSERT_EQ(CRYPT_EAL_DrbgbytesWithAdin(drbgCtx, output, DRBG_MAX_OUTPUT_SIZE + 1, addin, DRBG_MAX_ADIN_SIZE), CRYPT_SUCCESS); ASSERT_NE(CRYPT_EAL_DrbgbytesWithAdin(drbgCtx, NULL, 0, addin, DRBG_MAX_ADIN_SIZE), CRYPT_SUCCESS); EXIT: free(addin); free(output); CRYPT_EAL_DrbgDeinit(drbgCtx); drbgDataFree(&data); return; } /* END_CASE */ /** * @test SDV_CRYPT_DRBG_RAND_BYTES_ERR_PARA_API_TC001 * @title Test the CRYPT_EAL_Randbytes interface for generating random numbers. * @precon nan * @brief * 1.Initialize the random number seed, expected result 1. * 2.Call CRYPT_EAL_Randbytes,use normal parameters, expected result 2. * 3.Call CRYPT_EAL_Randbytes,the array length is abnormal, expected result 3. * @expect * 1.successful. * 2.All interface succeeded. * 3.The interface returns an exception. */ /* BEGIN_CASE */ void SDV_CRYPT_DRBG_RAND_BYTES_ERR_PARA_API_TC001(void) { uint8_t *output = malloc(DRBG_MAX_OUTPUT_SIZE + 1); ASSERT_TRUE(output != NULL); CRYPT_RandSeedMethod seedMeth = { 0 }; CRYPT_Data data = { 0 }; DRBG_Vec_t seedCtx = { 0 }; TestMemInit(); regSeedMeth(&seedMeth); drbgDataInit(&data, TEST_DRBG_DATA_SIZE); seedCtx.nonce = &data; seedCtx.entropy = &data; ASSERT_EQ(CRYPT_EAL_RandInit(CRYPT_RAND_SHA256, &seedMeth, (void *)&seedCtx, NULL, 0), CRYPT_SUCCESS); ASSERT_EQ(CRYPT_EAL_Randbytes(output, DRBG_OUTPUT_SIZE), CRYPT_SUCCESS); ASSERT_EQ(CRYPT_EAL_Randbytes(output, DRBG_MAX_OUTPUT_SIZE), CRYPT_SUCCESS); ASSERT_NE(CRYPT_EAL_Randbytes(output, 0), CRYPT_SUCCESS); ASSERT_EQ(CRYPT_EAL_Randbytes(output, DRBG_MAX_OUTPUT_SIZE + 1), CRYPT_SUCCESS); // MAX SIZE + 1 ASSERT_EQ(CRYPT_EAL_Randbytes(NULL, 0), CRYPT_NULL_INPUT); EXIT: CRYPT_EAL_RandDeinit(); drbgDataFree(&data); free(output); return; } /* END_CASE */ /** * @test SDV_CRYPT_DRBG_BYTES_ERR_PARA_API_TC001 * @title Test the CRYPT_EAL_Drbgbytes interface for generating random numbers. * @precon nan * @brief * 1.Initialize the random number seed, expected result 1. * 2.Call CRYPT_EAL_Drbgbytes,use normal parameters, expected result 2. * 3.Call CRYPT_EAL_Drbgbytes,the array length is abnormal, expected result 3. * @expect * 1.successful. * 2.All interface succeeded. * 3.The interface returns an exception. */ /* BEGIN_CASE */ void SDV_CRYPT_DRBG_BYTES_ERR_PARA_API_TC001(void) { uint8_t *output = malloc(DRBG_MAX_OUTPUT_SIZE + 1); ASSERT_TRUE(output != NULL); CRYPT_RandSeedMethod seedMeth = { 0 }; CRYPT_Data data = { 0 }; DRBG_Vec_t seedCtx = { 0 }; void *drbg = NULL; TestMemInit(); regSeedMeth(&seedMeth); drbgDataInit(&data, TEST_DRBG_DATA_SIZE); seedCtx.nonce = &data; seedCtx.entropy = &data; drbg = CRYPT_EAL_DrbgNew(CRYPT_RAND_SHA256, &seedMeth, &seedCtx); ASSERT_TRUE(drbg != NULL); ASSERT_TRUE(CRYPT_EAL_DrbgInstantiate(drbg, NULL, 0) == CRYPT_SUCCESS); ASSERT_EQ(CRYPT_EAL_Drbgbytes(drbg, output, DRBG_OUTPUT_SIZE), CRYPT_SUCCESS); ASSERT_EQ(CRYPT_EAL_Drbgbytes(drbg, output, DRBG_MAX_OUTPUT_SIZE), CRYPT_SUCCESS); ASSERT_NE(CRYPT_EAL_Drbgbytes(drbg, output, 0), CRYPT_SUCCESS); ASSERT_EQ(CRYPT_EAL_Drbgbytes(drbg, output, DRBG_MAX_OUTPUT_SIZE + 1), CRYPT_SUCCESS); // MAX SIZE + 1 ASSERT_NE(CRYPT_EAL_Drbgbytes(drbg, NULL, 0), CRYPT_SUCCESS); ASSERT_EQ(CRYPT_EAL_Drbgbytes(NULL, output, DRBG_OUTPUT_SIZE), CRYPT_NULL_INPUT); EXIT: CRYPT_EAL_DrbgDeinit(drbg); drbgDataFree(&data); free(output); return; } /* END_CASE */ /** * @test SDV_CRYPT_DRBG_RAND_SEED_ADIN_ERR_PARA_API_TC001 * @title Test the CRYPT_EAL_RandSeedWithAdin interface. * @precon nan * @brief * 1.Initialize the random number seed, expected result 1. * 2.Call CRYPT_EAL_RandSeedWithAdin,use exception parameters, expected result 2. * @expect * 1.successful. * 2.The interface returns an exception. */ /* BEGIN_CASE */ void SDV_CRYPT_DRBG_RAND_SEED_ADIN_ERR_PARA_API_TC001(void) { uint32_t addinLen = sizeof(uint8_t) * DRBG_MAX_ADIN_SIZE; uint8_t *addin = malloc(addinLen); ASSERT_TRUE(addin != NULL); memset_s(addin, addinLen, 0, addinLen); TestMemInit(); ASSERT_NE(CRYPT_EAL_RandSeedWithAdin(addin, 0), CRYPT_SUCCESS); ASSERT_NE(CRYPT_EAL_RandSeedWithAdin(addin, addinLen), CRYPT_SUCCESS); ASSERT_NE(CRYPT_EAL_RandSeedWithAdin(NULL, addinLen), CRYPT_SUCCESS); ASSERT_NE(CRYPT_EAL_RandSeedWithAdin(NULL, 0), CRYPT_SUCCESS); EXIT: free(addin); return; } /* END_CASE */ /** * @test SDV_CRYPT_DRBG_SEED_ADIN_ERR_PARA_API_TC001 * @title Test the CRYPT_EAL_DrbgSeedWithAdin interface. * @precon nan * @brief * 1.Initialize the random number seed, expected result 1. * 2.Call CRYPT_EAL_DrbgSeedWithAdin,use normal parameters, expected result 2. * 3.Call CRYPT_EAL_DrbgSeedWithAdin,the array length is abnormal, expected result 3. * @expect * 1.successful. * 2.All interface succeeded. * 3.The interface returns an exception. */ /* BEGIN_CASE */ void SDV_CRYPT_DRBG_SEED_ADIN_ERR_PARA_API_TC001(void) { uint8_t *addin; uint32_t addinLen = sizeof(uint8_t) * DRBG_MAX_ADIN_SIZE; CRYPT_RandSeedMethod seedMeth = { 0 }; CRYPT_Data data = { 0 }; DRBG_Vec_t seedCtx = { 0 }; void *drbg = NULL; addin = malloc(addinLen); ASSERT_TRUE(addin != NULL); memset_s(addin, addinLen, 0, addinLen); TestMemInit(); regSeedMeth(&seedMeth); drbgDataInit(&data, TEST_DRBG_DATA_SIZE); seedCtx.nonce = &data; seedCtx.entropy = &data; drbg = CRYPT_EAL_DrbgNew(CRYPT_RAND_SHA256, &seedMeth, &seedCtx); ASSERT_TRUE(drbg != NULL); ASSERT_TRUE(CRYPT_EAL_DrbgInstantiate(drbg, NULL, 0) == CRYPT_SUCCESS); ASSERT_EQ(CRYPT_EAL_DrbgSeedWithAdin(drbg, addin, 0), CRYPT_SUCCESS); ASSERT_EQ(CRYPT_EAL_DrbgSeedWithAdin(drbg, addin, addinLen), CRYPT_SUCCESS); ASSERT_EQ(CRYPT_EAL_DrbgSeedWithAdin(drbg, NULL, 0), CRYPT_SUCCESS); ASSERT_NE(CRYPT_EAL_DrbgSeedWithAdin(NULL, addin, addinLen), CRYPT_SUCCESS); ASSERT_NE(CRYPT_EAL_DrbgSeedWithAdin(drbg, NULL, addinLen), CRYPT_SUCCESS); EXIT: CRYPT_EAL_DrbgDeinit(drbg); free(addin); free(data.data); return; } /* END_CASE */ /** * @test SDV_CRYPT_DRBG_SEED_ADIN_ERR_PARA_API_TC001 * @title Random number generation test. * @precon nan * @brief * 1.Initialize the random number seed, expected result 1. * 2.Call CRYPT_EAL_RandbytesWithAdin num times, expected result 2. * @expect * 1.successful. * 2.All interface succeeded. */ /* BEGIN_CASE */ void SDV_CRYPT_DRBG_RAND_NUM_FUNC_TC001(int agId, int num, int dataSize) { if (IsRandAlgDisabled(agId)) { SKIP_TEST(); } int i; uint8_t *output = NULL; CRYPT_RandSeedMethod seedMeth = { 0 }; DRBG_Vec_t seedCtx = { 0 }; CRYPT_Data data = { 0 }; TestMemInit(); regSeedMeth(&seedMeth); drbgDataInit(&data, dataSize); seedCtx.entropy = &data; seedCtx.nonce = &data; ASSERT_EQ(CRYPT_EAL_RandInit(agId, &seedMeth, (void *)&seedCtx, NULL, 0), CRYPT_SUCCESS); output = malloc(sizeof(uint8_t) * DRBG_OUTPUT_SIZE); ASSERT_TRUE(output != NULL); for (i = 0; i < num; i++) { ASSERT_EQ(CRYPT_EAL_RandbytesWithAdin(output, sizeof(uint8_t) * DRBG_OUTPUT_SIZE, NULL, 0), CRYPT_SUCCESS); } EXIT: CRYPT_EAL_RandDeinit(); drbgDataFree(&data); free(output); return; } /* END_CASE */ /** * @test SDV_CRYPT_DRBG_NUM_FUNC_TC001 * @title Random number generation test. * @precon nan * @brief * 1.Initialize the random number seed, expected result 1. * 2.Call CRYPT_EAL_DrbgbytesWithAdin num times, expected result 2. * @expect * 1.successful. * 2.All interface succeeded. */ /* BEGIN_CASE */ void SDV_CRYPT_DRBG_NUM_FUNC_TC001(int agId, int num, int dataSize) { if (IsRandAlgDisabled(agId)) { SKIP_TEST(); } int i; uint8_t *output = NULL; CRYPT_RandSeedMethod seedMeth = { 0 }; DRBG_Vec_t seedCtx = { 0 }; CRYPT_Data data = { 0 }; void *drbgCtx = NULL; TestMemInit(); regSeedMeth(&seedMeth); drbgDataInit(&data, dataSize); seedCtx.entropy = &data; seedCtx.nonce = &data; drbgCtx = CRYPT_EAL_DrbgNew(agId, &seedMeth, &seedCtx); ASSERT_TRUE(drbgCtx != NULL); ASSERT_TRUE(CRYPT_EAL_DrbgInstantiate(drbgCtx, NULL, 0) == CRYPT_SUCCESS); output = malloc(sizeof(uint8_t) * DRBG_OUTPUT_SIZE); ASSERT_TRUE(output != NULL); for (i = 0; i < num; i++) { ASSERT_EQ(CRYPT_EAL_DrbgbytesWithAdin(drbgCtx, output, sizeof(uint8_t) * DRBG_OUTPUT_SIZE, NULL, 0), CRYPT_SUCCESS); } EXIT: CRYPT_EAL_DrbgDeinit(drbgCtx); drbgDataFree(&data); free(output); return; } /* END_CASE */ /** * @test SDV_CRYPT_DRBG_PTHREAD_FUNC_TC001 * @title DRGB multi-thread function test. * @precon nan * @brief * 1.Initialize the random number seed, expected result 1. * 2.Create 10 threads for execute CRYPT_EAL_Randbytes, expected result 2. * @expect * 1.init successful. * 2.All threads are executed successfully.. */ /* BEGIN_CASE */ void SDV_CRYPT_DRBG_PTHREAD_FUNC_TC001(int agId) { CRYPT_Data data = { 0 }; CRYPT_RandSeedMethod seedMeth = { 0 }; DRBG_Vec_t seedCtx = { 0 }; TestMemInit(); RegThreadFunc(); regSeedMeth(&seedMeth); drbgDataInit(&data, TEST_DRBG_DATA_SIZE); seedCtx.entropy = &data; seedCtx.nonce = &data; ASSERT_EQ(CRYPT_EAL_RandInit(agId, &seedMeth, &seedCtx, NULL, 0), CRYPT_SUCCESS); for(uint32_t iter = 0; iter < 10; iter++) { pthread_t thrd; ASSERT_EQ(pthread_create(&thrd, NULL, (void *)sdvCryptGlobalThreadTest, NULL), 0); pthread_join(thrd, NULL); } EXIT: CRYPT_EAL_RandDeinit(); drbgDataFree(&data); return; } /* END_CASE */ /** * @test SDV_CRYPT_DRBG_CLEANENTROPY_FUNC_TC001 * @title Failed to obtain the entropy source test. * @precon nan * @brief * 1.Register the interface that fails to obtain the entropy source, expected result 1. * 2.Initialize the random number seed, expected result 2. * @expect * 1.register successful. * 2.Failed to initialize the random number seed. */ /* BEGIN_CASE */ void SDV_CRYPT_DRBG_CLEANENTROPY_FUNC_TC001(int agId) { CallBackCtl_t seedCtx = { 0 }; CRYPT_RandSeedMethod seedMeth = { .getEntropy = getEntropyError, .cleanEntropy = cleanEntropyError, .getNonce = getNonceError, .cleanNonce = cleanNonceError, }; void *drbg = NULL; TestMemInit(); seedCtx.entropyState = 1; ASSERT_NE(CRYPT_EAL_RandInit(agId, &seedMeth, (void *)&seedCtx, NULL, 0), CRYPT_SUCCESS); drbg = CRYPT_EAL_DrbgNew(agId, &seedMeth, (void *)&seedCtx); ASSERT_TRUE(drbg != NULL); ASSERT_NE(CRYPT_EAL_DrbgInstantiate(drbg, NULL, 0), CRYPT_SUCCESS); EXIT: CRYPT_EAL_DrbgDeinit(drbg); CRYPT_EAL_RandDeinit(); return; } /* END_CASE */ /** * @test SDV_CRYPT_DRBG_GETENTROPY_FUNC_TC001 * @title Failed to obtain the entropy source test. * @precon nan * @brief * 1.Do not register the entropy source obtaining function., expected result 1. * 2.Initialize the random number seed, expected result 2. * @expect * 1.register successful. * 2.Failed to initialize the random number seed. */ /* BEGIN_CASE */ void SDV_CRYPT_DRBG_GETENTROPY_FUNC_TC001(int agId) { CallBackCtl_t seedCtx = { 0 }; CRYPT_RandSeedMethod seedMeth = { .getEntropy = NULL, .cleanEntropy = cleanEntropyError, .getNonce = getNonceError, .cleanNonce = cleanNonceError, }; void *drbg = NULL; TestMemInit(); ASSERT_NE(CRYPT_EAL_RandInit(agId, &seedMeth, (void *)&seedCtx, NULL, 0), CRYPT_SUCCESS); drbg = CRYPT_EAL_DrbgNew(agId, &seedMeth, (void *)&seedCtx); ASSERT_TRUE(drbg != NULL); ASSERT_EQ(CRYPT_EAL_DrbgInstantiate(drbg, NULL, 0), CRYPT_SUCCESS); EXIT: CRYPT_EAL_DrbgDeinit(drbg); CRYPT_EAL_RandDeinit(); return; } /* END_CASE */ /** * @test SDV_CRYPT_DRBG_GETENTROPY_FUNC_TC002 * @title To verify that the entropy data is empty and the length is 0 or a non-zero value. * @precon nan * @brief * 1.Registering the callback function, expected result 1. * 2.The entropy->data is empty and the length is 0,initialize the random number seed, expected result 2. * 2.The entropy->data is empty and the length not 0,initialize the random number seed, expected result 3. * @expect * 1.Register successful. * 2.Failed to initialize the random number seed. * 3.Failed to initialize the random number seed. */ /* BEGIN_CASE */ void SDV_CRYPT_DRBG_GETENTROPY_FUNC_TC002(void) { DRBG_Vec_t seedCtx = { 0 }; CRYPT_RandSeedMethod seedMeth = { .getEntropy = getEntropyUnCheckPara, .cleanEntropy = cleanEntropy, .getNonce = NULL, .cleanNonce = NULL, }; void *drbg = NULL; TestMemInit(); seedCtx.entropy = calloc(1u, sizeof(CRYPT_Data)); ASSERT_NE(CRYPT_EAL_RandInit(CRYPT_RAND_SHA256, &seedMeth, (void *)&seedCtx, NULL, 0), CRYPT_SUCCESS); CRYPT_EAL_RandDeinit(); drbg = CRYPT_EAL_DrbgNew(CRYPT_RAND_SHA256, &seedMeth, (void *)&seedCtx); ASSERT_TRUE(drbg != NULL); ASSERT_NE(CRYPT_EAL_DrbgInstantiate(drbg, NULL, 0), CRYPT_SUCCESS); CRYPT_EAL_DrbgDeinit(drbg); seedCtx.entropy->len = 1; // Set the entropy length to 1 verify that the data is empty but the data length is not 0. ASSERT_NE(CRYPT_EAL_RandInit(CRYPT_RAND_SHA256, &seedMeth, (void *)&seedCtx, NULL, 0), CRYPT_SUCCESS); drbg = CRYPT_EAL_DrbgNew(CRYPT_RAND_SHA256, &seedMeth, (void *)&seedCtx); ASSERT_TRUE(drbg != NULL); ASSERT_NE(CRYPT_EAL_DrbgInstantiate(drbg, NULL, 0), CRYPT_SUCCESS); EXIT: CRYPT_EAL_DrbgDeinit(drbg); CRYPT_EAL_RandDeinit(); DRBG_FREE(seedCtx.entropy); return; } /* END_CASE */ /** * @test SDV_CRYPT_DRBG_GETNONCE_FUNC_TC001 * @title Test that the nonce data is empty and the length is 0 or a non-zero value. * @precon nan * @brief * 1.Registering the callback function, expected result 1. * 2.The nonce->data is empty and the length is 0,initialize the random number seed, expected result 2. * 2.The nonce->data is empty and the length not 0,initialize the random number seed, expected result 3. * @expect * 1.Register successful. * 2.Failed to initialize the random number seed. * 3.Failed to initialize the random number seed. */ /* BEGIN_CASE */ void SDV_CRYPT_DRBG_GETNONCE_FUNC_TC001(void) { DRBG_Vec_t seedCtx = { 0 }; CRYPT_RandSeedMethod seedMeth = { .getEntropy = getEntropyError, .cleanEntropy = cleanEntropyError, .getNonce = getNonceUnCheckPara, .cleanNonce = cleanNonceError, }; void *drbg = NULL; TestMemInit(); seedCtx.nonce = calloc(1u, sizeof(CRYPT_Data)); ASSERT_NE(CRYPT_EAL_RandInit(CRYPT_RAND_SHA256, &seedMeth, (void *)&seedCtx, NULL, 0), CRYPT_SUCCESS); CRYPT_EAL_RandDeinit(); drbg = CRYPT_EAL_DrbgNew(CRYPT_RAND_SHA256, &seedMeth, (void *)&seedCtx); ASSERT_TRUE(drbg != NULL); ASSERT_NE(CRYPT_EAL_DrbgInstantiate(drbg, NULL, 0), CRYPT_SUCCESS); CRYPT_EAL_DrbgDeinit(drbg); seedCtx.nonce->len = 1; // Set the nonce length to 1 verify that the data is empty but the data length is not 0. ASSERT_NE(CRYPT_EAL_RandInit(CRYPT_RAND_SHA256, &seedMeth, (void *)&seedCtx, NULL, 0), CRYPT_SUCCESS); drbg = CRYPT_EAL_DrbgNew(CRYPT_RAND_SHA256, &seedMeth, (void *)&seedCtx); ASSERT_TRUE(drbg != NULL); ASSERT_NE(CRYPT_EAL_DrbgInstantiate(drbg, NULL, 0), CRYPT_SUCCESS); EXIT: CRYPT_EAL_DrbgDeinit(drbg); CRYPT_EAL_RandDeinit(); DRBG_FREE(seedCtx.nonce); return; } /* END_CASE */ /** * @test SDV_CRYPT_DRBG_GETNONCE_FUNC_TC002 * @title Failed to obtain nonce during DRBG initialization. * @precon nan * @brief * 1.Registering the interface for failed to obtain the nonce, expected result 1. * 2.Initializing the DRBG, expected result 2. * @expect * 1.Register successful. * 2.Failed to initialize the random number seed. */ /* BEGIN_CASE */ void SDV_CRYPT_DRBG_GETNONCE_FUNC_TC002(void) { DRBG_Vec_t seedCtx = { 0 }; CRYPT_RandSeedMethod seedMeth = { .getEntropy = getEntropyError, .cleanEntropy = cleanEntropyError, .getNonce = getNonce, .cleanNonce = cleanNonce, }; void *drbg = NULL; TestMemInit(); seedCtx.nonce = calloc(1u, sizeof(CRYPT_Data)); ASSERT_NE(CRYPT_EAL_RandInit(CRYPT_RAND_SHA256, &seedMeth, (void *)&seedCtx, NULL, 0), CRYPT_SUCCESS); drbg = CRYPT_EAL_DrbgNew(CRYPT_RAND_SHA256, &seedMeth, (void *)&seedCtx); ASSERT_TRUE(drbg != NULL); ASSERT_NE(CRYPT_EAL_DrbgInstantiate(drbg, NULL, 0), CRYPT_SUCCESS); EXIT: CRYPT_EAL_DrbgDeinit(drbg); CRYPT_EAL_RandDeinit(); DRBG_FREE(seedCtx.nonce); return; } /* END_CASE */ /** * @test SDV_CRYPT_DRBG_GETNONCE_FUNC_TC003 * @title Failed to obtain nonce during DRBG instantiation. * @precon nan * @brief * 1.Registering the interface for failed to obtain the nonce, expected result 1. * 2.Initializing the DRBG, expected result 2. * @expect * 1.Register successful. * 2.Failed to initialize the random number seed. */ /* BEGIN_CASE */ void SDV_CRYPT_DRBG_GETNONCE_FUNC_TC003(void) { CallBackCtl_t seedCtx = { 0 }; CRYPT_RandSeedMethod seedMeth = { .getNonce = getNonceError, .cleanNonce = cleanNonceError, .getEntropy = getEntropyError, .cleanEntropy = cleanEntropyError, }; void *drbg = NULL; TestMemInit(); seedCtx.nonceState = 1; ASSERT_TRUE(CRYPT_EAL_RandInit(CRYPT_RAND_SHA224, &seedMeth, (void *)&seedCtx, NULL, 0) != CRYPT_SUCCESS); drbg = CRYPT_EAL_DrbgNew(CRYPT_RAND_SHA224, &seedMeth, (void *)&seedCtx); ASSERT_TRUE(drbg != NULL); ASSERT_NE(CRYPT_EAL_DrbgInstantiate(drbg, NULL, 0), CRYPT_SUCCESS); EXIT: CRYPT_EAL_DrbgDeinit(drbg); CRYPT_EAL_RandDeinit(); return; } /* END_CASE */ /** * @test SDV_CRYPT_DRBG_INSTANTIATE_FUNC_TC001 * @title The personal data provided during DRBG instantiation is empty. * @precon nan * @brief * 1.set the personal data is empty. * 2.Initializing the DRBG, expected result 1. * 3.Uninitializing the DRBG, expected result 2. * @expect * 1.The DRBG is successfully initialized regardless of whether the data field is empty. * 2.The DRBG is successfully uninitialized. */ /* BEGIN_CASE */ void SDV_CRYPT_DRBG_INSTANTIATE_FUNC_TC001(void) { CRYPT_Data *pers = NULL; DRBG_Vec_t seedCtx = { 0 }; CRYPT_RandSeedMethod seedMeth = { .getEntropy = getEntropyError, .cleanEntropy = cleanEntropyError, .getNonce = getNonceError, .cleanNonce = cleanNonceError, }; TestMemInit(); pers = calloc(1u, sizeof(CRYPT_Data)); ASSERT_EQ(CRYPT_EAL_RandInit(CRYPT_RAND_SHA256, &seedMeth, (void *)&seedCtx, pers->data, pers->len), CRYPT_SUCCESS); CRYPT_EAL_RandDeinit(); void *drbg = CRYPT_EAL_DrbgNew(CRYPT_RAND_SHA256, &seedMeth, (void *)&seedCtx); ASSERT_TRUE(drbg != NULL); ASSERT_EQ(CRYPT_EAL_DrbgInstantiate(drbg, pers->data, pers->len), CRYPT_SUCCESS); CRYPT_EAL_DrbgDeinit(drbg); drbg = NULL; pers->data = calloc(DRBG_MAX_ADIN_SIZE + 1, sizeof(uint8_t)); pers->len = DRBG_MAX_ADIN_SIZE + 1; ASSERT_EQ(CRYPT_EAL_RandInit(CRYPT_RAND_SHA256, &seedMeth, (void *)&seedCtx, pers->data, pers->len), CRYPT_SUCCESS); drbg = CRYPT_EAL_DrbgNew(CRYPT_RAND_SHA256, &seedMeth, (void *)&seedCtx); ASSERT_TRUE(drbg != NULL); ASSERT_EQ(CRYPT_EAL_DrbgInstantiate(drbg, pers->data, pers->len), CRYPT_SUCCESS); EXIT: CRYPT_EAL_DrbgDeinit(drbg); CRYPT_EAL_RandDeinit(); DRBG_FREE(pers->data); DRBG_FREE(pers); return; } /* END_CASE */ /** * @test SDV_CRYPT_DRBG_DUP_API_TC001 * @title Test the DRBG dup interface. * @precon nan * @brief * 1.Call DRBG_NewHashCtx create ctx, expected result 1. * 2.Call dup function,give an empty input parameter, expected result 2. * 3.Call dup function,give the correct DRBG context, expected result 3. * @expect * 1.successful. * 2.The interface returns a null pointer. * 3.The interface returns new ctx. */ /* BEGIN_CASE */ void SDV_CRYPT_DRBG_DUP_API_TC001(int algId) { CRYPT_RandSeedMethod seedMeth = { 0 }; CRYPT_Data data = { 0 }; DRBG_Vec_t seedCtx = { 0 }; TestMemInit(); regSeedMeth(&seedMeth); drbgDataInit(&data, TEST_DRBG_DATA_SIZE); seedCtx.nonce = &data; seedCtx.entropy = &data; CRYPT_EAL_RndCtx *drbg = CRYPT_EAL_DrbgNew(algId, &seedMeth, &seedCtx); ASSERT_TRUE(drbg != NULL); DRBG_Ctx *ctx = (DRBG_Ctx*)(drbg->ctx); DRBG_Ctx *newCtx = ctx->meth->dup(ctx); ASSERT_TRUE(newCtx != NULL); ASSERT_TRUE(ctx->meth->dup(NULL) == NULL); EXIT: CRYPT_EAL_DrbgDeinit(drbg); DRBG_Free(newCtx); drbgDataFree(&data); } /* END_CASE */ /** * @test SDV_CRYPT_DRBG_PTHREAD_FUNC_TC002 * @title DRGB multi-thread function test. * @precon nan * @brief * 1.Initialize 10 drbgCtx, expected result 1. * 2.Create 10 threads for execute CRYPT_EAL_DrbgbytesWithAdin, expected result 2. * @expect * 1.init successful. * 2.All threads are executed successfully.. */ /* BEGIN_CASE */ void SDV_CRYPT_DRBG_PTHREAD_FUNC_TC002(int agId) { if (IsRandAlgDisabled(agId)) { SKIP_TEST(); } CRYPT_Data data = { 0 }; CRYPT_RandSeedMethod seedMeth = { 0 }; DRBG_Vec_t seedCtx = { 0 }; TestMemInit(); RegThreadFunc(); regSeedMeth(&seedMeth); drbgDataInit(&data, TEST_DRBG_DATA_SIZE); seedCtx.entropy = &data; seedCtx.nonce = &data; for (uint32_t iter = 0; iter < 10; iter++) { pthread_t thrd; void *drbgCtx = CRYPT_EAL_DrbgNew(agId, &seedMeth, &seedCtx); ASSERT_TRUE(drbgCtx != NULL); ASSERT_TRUE(CRYPT_EAL_DrbgInstantiate(drbgCtx, NULL, 0) == CRYPT_SUCCESS); ASSERT_EQ(pthread_create(&thrd, NULL, (void *)sdvCryptEalThreadTest, drbgCtx), 0); pthread_join(thrd, NULL); CRYPT_EAL_DrbgDeinit(drbgCtx); drbgCtx = NULL; } EXIT: drbgDataFree(&data); return; } /* END_CASE */ /** * @test SDV_CRYPT_DRBG_PTHREAD_FUNC_TC003 * @title DRGB multi-thread function test. * @precon nan * @brief * 1.Initialize drbgCtx, expected result 1. * 2.Create 10 threads for execute CRYPT_EAL_DrbgbytesWithAdin, expected result 2. * @expect * 1.init successful. * 2.All threads are executed successfully.. */ /* BEGIN_CASE */ void SDV_CRYPT_DRBG_PTHREAD_FUNC_TC003(int agId) { CRYPT_Data data = { 0 }; CRYPT_RandSeedMethod seedMeth = { 0 }; DRBG_Vec_t seedCtx = { 0 }; TestMemInit(); RegThreadFunc(); regSeedMeth(&seedMeth); drbgDataInit(&data, TEST_DRBG_DATA_SIZE); seedCtx.entropy = &data; seedCtx.nonce = &data; void *drbgCtx = CRYPT_EAL_DrbgNew(agId, &seedMeth, &seedCtx); ASSERT_TRUE(drbgCtx != NULL); ASSERT_TRUE(CRYPT_EAL_DrbgInstantiate(drbgCtx, NULL, 0) == CRYPT_SUCCESS); for (uint32_t iter = 0; iter < 10; iter++) { pthread_t thrd; ASSERT_EQ(pthread_create(&thrd, NULL, (void *)sdvCryptEalThreadTest, drbgCtx), 0); pthread_join(thrd, NULL); } EXIT: CRYPT_EAL_DrbgDeinit(drbgCtx); drbgDataFree(&data); return; } /* END_CASE */ static int32_t getEntropyWithoutSeedCtx(void *ctx, CRYPT_Data *entropy, uint32_t strength, CRYPT_Range *lenRange) { (void)ctx; (void)strength; (void)lenRange; uint32_t entroyLen = sizeof(uint8_t) * TEST_DRBG_DATA_SIZE; entropy->data = calloc(1u, entroyLen); entropy->len = entroyLen; return CRYPT_SUCCESS; } static int32_t getEntropyWithoutSeedCtxSpecial(void *ctx, CRYPT_Data *entropy, uint32_t strength, CRYPT_Range *lenRange) { (void)ctx; (void)strength; (void)lenRange; uint32_t entroyLen = sizeof(uint8_t) * CTR_AES128_SEEDLEN; entropy->data = calloc(1u, entroyLen); entropy->len = entroyLen; return CRYPT_SUCCESS; } static int32_t getNonceWithoutSeedCtx(void *ctx, CRYPT_Data *nonce, uint32_t strength, CRYPT_Range *lenRange) { (void)ctx; (void)strength; (void)lenRange; uint32_t nonceLen = sizeof(uint8_t) * TEST_DRBG_DATA_SIZE; nonce->data = calloc(1u, nonceLen); nonce->len = nonceLen; return CRYPT_SUCCESS; } /** * @test SDV_CRYPT_EAL_RAND_BYTES_FUNC_TC001 * @title Generating random numbers based on entropy sources. * @precon nan * @brief * 1.Initialize the random number seed, expected result 1. * 2.Call CRYPT_EAL_RandbytesWithAdin, expected result 2. * 3.Call CRYPT_EAL_Randbytes get random numbers, expected result 3. * @expect * 1.init successful. * 2.successful. * 3.Random number generated successfully. */ /* BEGIN_CASE */ void SDV_CRYPT_EAL_RAND_BYTES_FUNC_TC001(int id, Hex *entropy, Hex *nonce, Hex *pers, Hex *addin1, Hex *entropyPR1, Hex *addin2, Hex *entropyPR2, Hex *retBits) { if (IsRandAlgDisabled(id)){ SKIP_TEST(); } uint8_t output[DRBG_MAX_OUTPUT_SIZE]; CRYPT_RandSeedMethod seedMeth = { 0 }; DRBG_Vec_t *seedCtx; regSeedMeth(&seedMeth); TestMemInit(); seedCtx = seedCtxMem(); ASSERT_TRUE(seedCtx != NULL); seedCtxCfg(seedCtx, entropy, nonce, pers, addin1, entropyPR1, addin2, entropyPR2, retBits); ASSERT_EQ(CRYPT_EAL_RandInit((CRYPT_RAND_AlgId)id, &seedMeth, (void *)seedCtx, seedCtx->pers->data, seedCtx->pers->len), CRYPT_SUCCESS); ASSERT_EQ(CRYPT_EAL_RandbytesWithAdin(output, sizeof(uint8_t) * retBits->len, addin1->x, addin1->len), CRYPT_SUCCESS); ASSERT_EQ(CRYPT_EAL_Randbytes(output, sizeof(uint8_t) * retBits->len), CRYPT_SUCCESS); ASSERT_EQ(CRYPT_EAL_RandIsValidAlgId(id), true); EXIT: CRYPT_EAL_RandDeinit(); seedCtxFree(seedCtx); return; } /* END_CASE */ /** * @test SDV_CRYPT_EAL_DRBG_BYTES_FUNC_TC001 * @title Generating random numbers based on entropy sources. * @precon nan * @brief * 1.Initialize the random number seed, expected result 1. * 2.Call CRYPT_EAL_DrbgbytesWithAdin, expected result 2. * 3.Call CRYPT_EAL_Drbgbytes get random numbers, expected result 3. * @expect * 1.Init successful. * 2.Successful. * 3.Random number generated successfully. */ /* BEGIN_CASE */ void SDV_CRYPT_EAL_DRBG_BYTES_FUNC_TC001(int id, Hex *entropy, Hex *nonce, Hex *pers, Hex *addin1, Hex *entropyPR1, Hex *addin2, Hex *entropyPR2, Hex *retBits) { if (IsRandAlgDisabled(id)){ SKIP_TEST(); } uint8_t *output = NULL; CRYPT_RandSeedMethod seedMeth = { 0 }; DRBG_Vec_t *seedCtx; void *drbgCtx = NULL; regSeedMeth(&seedMeth); TestMemInit(); seedCtx = seedCtxMem(); ASSERT_TRUE(seedCtx != NULL); seedCtxCfg(seedCtx, entropy, nonce, pers, addin1, entropyPR1, addin2, entropyPR2, retBits); drbgCtx = CRYPT_EAL_DrbgNew(id, &seedMeth, seedCtx); ASSERT_TRUE(drbgCtx != NULL); ASSERT_TRUE(CRYPT_EAL_DrbgInstantiate(drbgCtx, NULL, 0) == CRYPT_SUCCESS); output = malloc(sizeof(uint8_t) * retBits->len); ASSERT_TRUE(output != NULL); ASSERT_EQ(CRYPT_EAL_DrbgbytesWithAdin(drbgCtx, output, sizeof(uint8_t) * retBits->len, addin1->x, addin1->len), CRYPT_SUCCESS); ASSERT_EQ(CRYPT_EAL_Drbgbytes(drbgCtx, output, sizeof(uint8_t) * retBits->len), CRYPT_SUCCESS); EXIT: CRYPT_EAL_DrbgDeinit(drbgCtx); seedCtxFree(seedCtx); free(output); return; } /* END_CASE */ /** * @test SDV_CRYPT_EAL_RAND_BYTES_FUNC_TC002 * @title Generating random numbers based on entropy sources,the user only provides the seed method, not the seed context. * @precon nan * @brief * 1.Initialize the random number seed, expected result 1. * 2.Call CRYPT_EAL_RandSeed, expected result 2. * 3.Call CRYPT_EAL_Randbytes get random numbers, expected result 3. * @expect * 1.init successful. * 2.successful. * 3.Random number generated successfully. */ /* BEGIN_CASE */ void SDV_CRYPT_EAL_RAND_BYTES_FUNC_TC002(int id) { if (IsRandAlgDisabled(id)){ SKIP_TEST(); } uint8_t output[DRBG_MAX_OUTPUT_SIZE]; CRYPT_RandSeedMethod seedMeth = { .getEntropy = getEntropyWithoutSeedCtx, .cleanEntropy = cleanEntropyError, .getNonce = getNonceWithoutSeedCtx, .cleanNonce = cleanNonceError, }; TestMemInit(); /* The DRBG-CTR mode requires the entropy source length of a specific length, and seedMeth needs to generate entropy of the corresponding length.(DRBG-CTR AES128/AES192/AES256 length is 32, 40, 48). */ if (id == CRYPT_RAND_AES128_CTR || id == CRYPT_RAND_AES192_CTR || id == CRYPT_RAND_AES256_CTR) { seedMeth.getEntropy = getEntropyWithoutSeedCtxSpecial; seedMeth.getNonce = NULL; seedMeth.cleanNonce = NULL; } ASSERT_EQ(CRYPT_EAL_RandInit((CRYPT_RAND_AlgId)id, &seedMeth, NULL, NULL, 0), CRYPT_SUCCESS); ASSERT_EQ(CRYPT_EAL_RandSeed(), CRYPT_SUCCESS); ASSERT_EQ(CRYPT_EAL_Randbytes(output, DRBG_MAX_OUTPUT_SIZE), CRYPT_SUCCESS); EXIT: CRYPT_EAL_RandDeinit(); return; } /* END_CASE */ /** * @test SDV_CRYPT_EAL_RAND_DEFAULT_PROVIDER_BYTES_FUNC_TC001 * @title Default provider testing * @precon nan * @brief * Load the default provider and use the test vector to test its correctness * Generating random numbers based on entropy sources * 1.Initialize the random number seed, expected result 1. * 2.Call CRYPT_EAL_RandbytesWithAdin, expected result 2. * 3.Call CRYPT_EAL_Randbytes get random numbers, expected result 3. * @expect * 1.init successful. * 2.successful. * 3.Random number generated successfully. */ /* BEGIN_CASE */ void SDV_CRYPT_EAL_RAND_DEFAULT_PROVIDER_BYTES_FUNC_TC001(int id, Hex *entropy, Hex *nonce, Hex *pers, Hex *addin1, Hex *entropyPR1, Hex *addin2, Hex *entropyPR2, Hex *retBits) { #ifndef HITLS_CRYPTO_PROVIDER (void)id; (void)entropy; (void)nonce; (void)pers; (void)addin1; (void)entropyPR1; (void)addin2; (void)entropyPR2; (void)retBits; SKIP_TEST(); #else if (IsRandAlgDisabled(id)) { SKIP_TEST(); } uint8_t output[DRBG_MAX_OUTPUT_SIZE]; CRYPT_RandSeedMethod seedMeth = { 0 }; DRBG_Vec_t *seedCtx; regSeedMeth(&seedMeth); TestMemInit(); seedCtx = seedCtxMem(); ASSERT_TRUE(seedCtx != NULL); seedCtxCfg(seedCtx, entropy, nonce, pers, addin1, entropyPR1, addin2, entropyPR2, retBits); BSL_Param param[6] = {0}; ASSERT_EQ(BSL_PARAM_InitValue(&param[0], CRYPT_PARAM_RAND_SEEDCTX, BSL_PARAM_TYPE_CTX_PTR, seedCtx, 0), BSL_SUCCESS); ASSERT_EQ(BSL_PARAM_InitValue(&param[1], CRYPT_PARAM_RAND_SEED_GETENTROPY, BSL_PARAM_TYPE_FUNC_PTR, seedMeth.getEntropy, 0), BSL_SUCCESS); ASSERT_EQ(BSL_PARAM_InitValue(&param[2], CRYPT_PARAM_RAND_SEED_CLEANENTROPY, BSL_PARAM_TYPE_FUNC_PTR, seedMeth.cleanEntropy, 0), BSL_SUCCESS); ASSERT_EQ(BSL_PARAM_InitValue(&param[3], CRYPT_PARAM_RAND_SEED_GETNONCE, BSL_PARAM_TYPE_FUNC_PTR, seedMeth.getNonce, 0), BSL_SUCCESS); ASSERT_EQ(BSL_PARAM_InitValue(&param[4], CRYPT_PARAM_RAND_SEED_CLEANNONCE, BSL_PARAM_TYPE_FUNC_PTR, seedMeth.cleanNonce, 0), BSL_SUCCESS); ASSERT_EQ(CRYPT_EAL_ProviderRandInitCtx(NULL, (CRYPT_RAND_AlgId)id, "provider=default", seedCtx->pers->data, seedCtx->pers->len, param), CRYPT_SUCCESS); ASSERT_EQ(CRYPT_EAL_RandbytesWithAdinEx(NULL, output, sizeof(uint8_t) * retBits->len, addin1->x, addin1->len), CRYPT_SUCCESS); ASSERT_EQ(CRYPT_EAL_RandbytesEx(NULL, output, sizeof(uint8_t) * retBits->len), CRYPT_SUCCESS); ASSERT_EQ(CRYPT_EAL_RandIsValidAlgId(id), true); EXIT: CRYPT_EAL_RandDeinitEx(NULL); seedCtxFree(seedCtx); return; #endif } /* END_CASE */ /** * @test SDV_CRYPT_EAL_DRBG_DEFAULT_PROVIDER_BYTES_FUNC_TC001 * @title Default provider testing * @precon nan * @brief * Load the default provider and use the test vector to test its correctness * Generating random numbers based on entropy sources. * 1.Initialize the random number seed, expected result 1. * 2.Call CRYPT_EAL_DrbgbytesWithAdin, expected result 2. * 3.Call CRYPT_EAL_Drbgbytes get random numbers, expected result 3. * @expect * 1.Init successful. * 2.Successful. * 3.Random number generated successfully. */ /* BEGIN_CASE */ void SDV_CRYPT_EAL_DRBG_DEFAULT_PROVIDER_BYTES_FUNC_TC001(int id, Hex *entropy, Hex *nonce, Hex *pers, Hex *addin1, Hex *entropyPR1, Hex *addin2, Hex *entropyPR2, Hex *retBits) { #ifndef HITLS_CRYPTO_PROVIDER (void)id; (void)entropy; (void)nonce; (void)pers; (void)addin1; (void)entropyPR1; (void)addin2; (void)entropyPR2; (void)retBits; SKIP_TEST(); #else if (IsRandAlgDisabled(id)) { SKIP_TEST(); } uint8_t *output = NULL; CRYPT_RandSeedMethod seedMeth = { 0 }; DRBG_Vec_t *seedCtx; void *drbgCtx = NULL; regSeedMeth(&seedMeth); TestMemInit(); seedCtx = seedCtxMem(); ASSERT_TRUE(seedCtx != NULL); seedCtxCfg(seedCtx, entropy, nonce, pers, addin1, entropyPR1, addin2, entropyPR2, retBits); BSL_Param param[6] = {0}; ASSERT_EQ(BSL_PARAM_InitValue(&param[0], CRYPT_PARAM_RAND_SEEDCTX, BSL_PARAM_TYPE_CTX_PTR, seedCtx, 0), BSL_SUCCESS); ASSERT_EQ(BSL_PARAM_InitValue(&param[1], CRYPT_PARAM_RAND_SEED_GETENTROPY, BSL_PARAM_TYPE_FUNC_PTR, seedMeth.getEntropy, 0), BSL_SUCCESS); ASSERT_EQ(BSL_PARAM_InitValue(&param[2], CRYPT_PARAM_RAND_SEED_CLEANENTROPY, BSL_PARAM_TYPE_FUNC_PTR, seedMeth.cleanEntropy, 0), BSL_SUCCESS); ASSERT_EQ(BSL_PARAM_InitValue(&param[3], CRYPT_PARAM_RAND_SEED_GETNONCE, BSL_PARAM_TYPE_FUNC_PTR, seedMeth.getNonce, 0), BSL_SUCCESS); ASSERT_EQ(BSL_PARAM_InitValue(&param[4], CRYPT_PARAM_RAND_SEED_CLEANNONCE, BSL_PARAM_TYPE_FUNC_PTR, seedMeth.cleanNonce, 0), BSL_SUCCESS); drbgCtx = CRYPT_EAL_ProviderDrbgNewCtx(NULL, (CRYPT_RAND_AlgId)id, "provider=default", param); ASSERT_TRUE(drbgCtx != NULL); ASSERT_TRUE(CRYPT_EAL_DrbgInstantiate(drbgCtx, NULL, 0) == CRYPT_SUCCESS); output = malloc(sizeof(uint8_t) * retBits->len); ASSERT_TRUE(output != NULL); ASSERT_EQ(CRYPT_EAL_DrbgbytesWithAdin(drbgCtx, output, sizeof(uint8_t) * retBits->len, addin1->x, addin1->len), CRYPT_SUCCESS); ASSERT_EQ(CRYPT_EAL_Drbgbytes(drbgCtx, output, sizeof(uint8_t) * retBits->len), CRYPT_SUCCESS); EXIT: CRYPT_EAL_DrbgDeinit(drbgCtx); seedCtxFree(seedCtx); free(output); return; #endif } /* END_CASE */ /** * @test SDV_CRYPT_EAL_RAND_DEFAULT_PROVIDER_BYTES_FUNC_TC002 * @title Default provider testing * @precon nan * @brief * Load the default provider and use the test vector to test its correctness * Generating random numbers based on entropy sources,the user only provides the seed method, * not the seed context. * 1.Initialize the random number seed, expected result 1. * 2.Call CRYPT_EAL_RandSeed, expected result 2. * 3.Call CRYPT_EAL_Randbytes get random numbers, expected result 3. * 4.Initialize the random number without seedMeth, expected result 4. * @expect * 1.init successful. * 2.successful. * 3.Random number generated successfully. * 4.init successful. */ /* BEGIN_CASE */ void SDV_CRYPT_EAL_RAND_DEFAULT_PROVIDER_BYTES_FUNC_TC002(int id) { #ifndef HITLS_CRYPTO_PROVIDER (void)id; SKIP_TEST(); #else if (IsRandAlgDisabled(id)) { SKIP_TEST(); } uint8_t output[DRBG_MAX_OUTPUT_SIZE]; CRYPT_RandSeedMethod seedMeth = { .getEntropy = getEntropyWithoutSeedCtx, .cleanEntropy = cleanEntropyError, .getNonce = getNonceWithoutSeedCtx, .cleanNonce = cleanNonceError, }; TestMemInit(); /* The DRBG-CTR mode requires the entropy source length of a specific length, and seedMeth needs to generate entropy of the corresponding length.(DRBG-CTR AES128/AES192/AES256 length is 32, 40, 48). */ if (id == CRYPT_RAND_AES128_CTR || id == CRYPT_RAND_AES192_CTR || id == CRYPT_RAND_AES256_CTR) { seedMeth.getEntropy = getEntropyWithoutSeedCtxSpecial; seedMeth.getNonce = NULL; seedMeth.cleanNonce = NULL; } BSL_Param param[6] = {0}; ASSERT_EQ(BSL_PARAM_InitValue(&param[0], CRYPT_PARAM_RAND_SEEDCTX, BSL_PARAM_TYPE_CTX_PTR, NULL, 0), BSL_SUCCESS); ASSERT_EQ(BSL_PARAM_InitValue(&param[1], CRYPT_PARAM_RAND_SEED_GETENTROPY, BSL_PARAM_TYPE_FUNC_PTR, seedMeth.getEntropy, 0), BSL_SUCCESS); ASSERT_EQ(BSL_PARAM_InitValue(&param[2], CRYPT_PARAM_RAND_SEED_CLEANENTROPY, BSL_PARAM_TYPE_FUNC_PTR, seedMeth.cleanEntropy, 0), BSL_SUCCESS); ASSERT_EQ(BSL_PARAM_InitValue(&param[3], CRYPT_PARAM_RAND_SEED_GETNONCE, BSL_PARAM_TYPE_FUNC_PTR, seedMeth.getNonce, 0), BSL_SUCCESS); ASSERT_EQ(BSL_PARAM_InitValue(&param[4], CRYPT_PARAM_RAND_SEED_CLEANNONCE, BSL_PARAM_TYPE_FUNC_PTR, seedMeth.cleanNonce, 0), BSL_SUCCESS); ASSERT_EQ(CRYPT_EAL_ProviderRandInitCtx(NULL, (CRYPT_RAND_AlgId)id, "provider=default", NULL, 0, param), CRYPT_SUCCESS); ASSERT_EQ(CRYPT_EAL_RandSeedEx(NULL), CRYPT_SUCCESS); ASSERT_EQ(CRYPT_EAL_RandbytesEx(NULL, output, DRBG_MAX_OUTPUT_SIZE), CRYPT_SUCCESS); CRYPT_EAL_DrbgDeinit(CRYPT_EAL_GetGlobalLibCtx()->drbg); CRYPT_EAL_GetGlobalLibCtx()->drbg = NULL; param[1] = (BSL_Param){0, 0, NULL, 0, 0}; ASSERT_EQ(CRYPT_EAL_ProviderRandInitCtx(NULL, (CRYPT_RAND_AlgId)id, "provider=default", NULL, 0, param), CRYPT_SUCCESS); ASSERT_EQ(CRYPT_EAL_RandSeedEx(NULL), CRYPT_SUCCESS); ASSERT_EQ(CRYPT_EAL_RandbytesEx(NULL, output, DRBG_MAX_OUTPUT_SIZE), CRYPT_SUCCESS); EXIT: CRYPT_EAL_RandDeinitEx(NULL); return; #endif } /* END_CASE */ /* BEGIN_CASE */ void SDV_CRYPT_EAL_RAND_DEFAULT_PROVIDER_BYTES_FUNC_TC003(int id) { #ifndef HITLS_CRYPTO_PROVIDER (void)id; SKIP_TEST(); #else if (IsRandAlgDisabled(id)) { SKIP_TEST(); } uint8_t output[DRBG_MAX_OUTPUT_SIZE]; CRYPT_RandSeedMethod seedMeth = { .getEntropy = getEntropyWithoutSeedCtx, .cleanEntropy = cleanEntropyError, .getNonce = getNonceWithoutSeedCtx, .cleanNonce = cleanNonceError, }; TestMemInit(); BSL_Param param[6] = {0}; ASSERT_EQ(BSL_PARAM_InitValue(&param[0], CRYPT_PARAM_RAND_SEED_GETNONCE, BSL_PARAM_TYPE_FUNC_PTR, seedMeth.getNonce, 0), BSL_SUCCESS); ASSERT_EQ(BSL_PARAM_InitValue(&param[1], CRYPT_PARAM_RAND_SEED_CLEANNONCE, BSL_PARAM_TYPE_FUNC_PTR, seedMeth.cleanNonce, 0), BSL_SUCCESS); ASSERT_EQ(BSL_PARAM_InitValue(&param[2], CRYPT_PARAM_RAND_SEEDCTX, BSL_PARAM_TYPE_CTX_PTR, NULL, 0), BSL_SUCCESS); ASSERT_EQ(CRYPT_EAL_ProviderRandInitCtx(NULL, (CRYPT_RAND_AlgId)id, "provider=default", NULL, 0, NULL), CRYPT_SUCCESS); ASSERT_EQ(CRYPT_EAL_RandSeedEx(NULL), CRYPT_SUCCESS); ASSERT_EQ(CRYPT_EAL_RandbytesEx(NULL, output, DRBG_MAX_OUTPUT_SIZE), CRYPT_SUCCESS); CRYPT_EAL_DrbgDeinit(CRYPT_EAL_GetGlobalLibCtx()->drbg); CRYPT_EAL_GetGlobalLibCtx()->drbg = NULL; ASSERT_EQ(CRYPT_EAL_ProviderRandInitCtx(NULL, (CRYPT_RAND_AlgId)id, "provider=default", NULL, 0, param), CRYPT_EAL_ERR_DRBG_INIT_FAIL); param[2] = (BSL_Param){0, 0, NULL, 0, 0}; ASSERT_EQ(CRYPT_EAL_ProviderRandInitCtx(NULL, (CRYPT_RAND_AlgId)id, "provider=default", NULL, 0, param), CRYPT_EAL_ERR_DRBG_INIT_FAIL); EXIT: CRYPT_EAL_RandDeinitEx(NULL); return; #endif } /* END_CASE */ /* BEGIN_CASE */ void SDV_CRYPTO_DRBG_SET_PREDICTION_RESISTANCE_API_TC001() { uint8_t *output = NULL; void *drbgCtx = NULL; CRYPT_Data data = { 0 }; CRYPT_RandSeedMethod seedMeth = { 0 }; DRBG_Vec_t seedCtx = { 0 }; bool pr = true; TestMemInit(); regSeedMeth(&seedMeth); drbgDataInit(&data, TEST_DRBG_DATA_SIZE); seedCtx.entropy = &data; seedCtx.nonce = &data; drbgCtx = CRYPT_EAL_DrbgNew(CRYPT_RAND_SHA256, &seedMeth, &seedCtx); ASSERT_TRUE(drbgCtx != NULL); ASSERT_TRUE(CRYPT_EAL_DrbgInstantiate(drbgCtx, NULL, 0) == CRYPT_SUCCESS); output = malloc(sizeof(uint8_t) * DRBG_OUTPUT_SIZE); ASSERT_TRUE(output != NULL); (void)memset_s(output, sizeof(uint8_t) * DRBG_OUTPUT_SIZE, 0, sizeof(uint8_t) * DRBG_OUTPUT_SIZE); ASSERT_EQ(CRYPT_EAL_DrbgbytesWithAdin(drbgCtx, output, DRBG_OUTPUT_SIZE, NULL, 0), CRYPT_SUCCESS); CRYPT_EAL_DrbgDeinit(drbgCtx); drbgCtx = CRYPT_EAL_DrbgNew(CRYPT_RAND_SHA256, &seedMeth, &seedCtx); ASSERT_TRUE(drbgCtx != NULL); ASSERT_EQ(CRYPT_EAL_DrbgCtrl(drbgCtx, CRYPT_CTRL_SET_PREDICTION_RESISTANCE, &pr, sizeof(pr)), CRYPT_SUCCESS); ASSERT_TRUE(CRYPT_EAL_DrbgInstantiate(drbgCtx, NULL, 0) == CRYPT_SUCCESS); ASSERT_EQ(CRYPT_EAL_DrbgbytesWithAdin(drbgCtx, output, DRBG_OUTPUT_SIZE, NULL, 0), CRYPT_SUCCESS); EXIT: CRYPT_EAL_DrbgDeinit(drbgCtx); drbgDataFree(&data); free(output); } /* END_CASE */ /** * @test SDV_CRYPT_PRIMARY_DRBG_RESEED_FUNC_TC001 * @title DRGB get seed ctx and reseed test. * @precon nan * @brief * 1.Initialize the random number and obtain the seed. * 2.Call the reseed function and obtain a random number. * @expect * 1.successful. * 2.successful. */ /* BEGIN_CASE */ void SDV_CRYPT_PRIMARY_DRBG_RESEED_FUNC_TC001(int algId) { #if (!defined(HITLS_CRYPTO_ENTROPY)) (void)algId; #else if (IsRandAlgDisabled(algId)) { SKIP_TEST(); } uint8_t addin[40] = {1, 2, 3, 4}; uint8_t randByte[64]; uint32_t working = 0; TestMemInit(); ASSERT_TRUE(CRYPT_EAL_GetSeedCtx(true) == NULL); ASSERT_EQ(CRYPT_EAL_DrbgCtrl(NULL, CRYPT_CTRL_GET_WORKING_STATUS, &working, sizeof(working)), CRYPT_NULL_INPUT); ASSERT_EQ(CRYPT_EAL_RandInit(algId, NULL, NULL, NULL, 0), CRYPT_SUCCESS); CRYPT_EAL_RndCtx *seedCtx = CRYPT_EAL_GetSeedCtx(true); ASSERT_EQ(CRYPT_EAL_DrbgCtrl(seedCtx, CRYPT_CTRL_GET_WORKING_STATUS, &working, sizeof(working)), CRYPT_SUCCESS); ASSERT_EQ(working, 1); ASSERT_EQ(CRYPT_EAL_DrbgSeedWithAdin(seedCtx, addin, sizeof(addin)), CRYPT_SUCCESS); ASSERT_EQ(CRYPT_EAL_Randbytes(randByte, sizeof(randByte)), CRYPT_SUCCESS); seedCtx = CRYPT_EAL_GetSeedCtx(false); ASSERT_EQ(CRYPT_EAL_DrbgCtrl(seedCtx, CRYPT_CTRL_GET_WORKING_STATUS, &working, sizeof(working)), CRYPT_SUCCESS); ASSERT_EQ(working, 1); ASSERT_EQ(CRYPT_EAL_DrbgSeedWithAdin(seedCtx, addin, sizeof(addin)), CRYPT_SUCCESS); ASSERT_EQ(CRYPT_EAL_Randbytes(randByte, sizeof(randByte)), CRYPT_SUCCESS); EXIT: CRYPT_EAL_RandDeinit(); return; #endif } /* END_CASE */
2301_79861745/bench_create
testcode/sdv/testcase/crypto/drbg/test_suite_sdv_drbg.c
C
unknown
69,937
/* * This file is part of the openHiTLS project. * * openHiTLS is licensed under the Mulan PSL v2. * You can use this software according to the terms and conditions of the Mulan PSL v2. * You may obtain a copy of Mulan PSL v2 at: * * http://license.coscl.org.cn/MulanPSL2 * * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, * EITHER EXPRESS 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 <stdio.h> #include <string.h> #include <pthread.h> #include "securec.h" #include "bsl_err.h" #include "bsl_sal.h" #include "crypt_errno.h" #include "crypt_dsa.h" #include "dsa_local.h" #include "crypt_eal_pkey.h" #include "crypt_eal_rand.h" #include "crypt_bn.h" #include "eal_pkey_local.h" #include "stub_replace.h" #include "crypt_util_rand.h" #include "crypt_encode_internal.h" #include "crypt_eal_md.h" /* END_HEADER */ #define SUCCESS 0 #define ERROR (-1) #define BITS_OF_BYTE 8 #define CRYPT_EAL_PKEY_KEYMGMT_OPERATE 0 static uint8_t g_kRandBuf[64]; static uint32_t g_kRandBufLen = 0; extern int32_t CryptDsaFips1864GenPq(CRYPT_DSA_Ctx *ctx, DSA_FIPS186_4_Para *fipsPara, uint32_t type, BSL_Buffer *seed, uint32_t *counter); extern int32_t CryptDsaFips1864ValidatePq(int32_t algId, void *libCtx, const char *mdAttr, uint32_t type, BSL_Buffer *seed, CRYPT_DSA_Para *dsaPara, uint32_t counter); extern int32_t CryptDsaFips1864GenUnverifiableG(CRYPT_DSA_Para *dsaPara); extern int32_t CryptDsaFips1864GenVerifiableG(DSA_FIPS186_4_Para *fipsPara, BSL_Buffer *seed, CRYPT_DSA_Para *dsaPara); extern int32_t CryptDsaFips1864PartialValidateG(const CRYPT_DSA_Para *dsaPara); extern int32_t CryptDsaFips1864ValidateG(DSA_FIPS186_4_Para *fipsPara, BSL_Buffer *seed, CRYPT_DSA_Para *dsaPara); int32_t STUB_RandRangeK(void *libCtx, BN_BigNum *r, const BN_BigNum *p) { (void)p; (void)libCtx; BN_Bin2Bn(r, g_kRandBuf, g_kRandBufLen); return CRYPT_SUCCESS; } int Compute_Md(CRYPT_MD_AlgId mdId, Hex *msgIn, Hex *mdOut) { uint32_t outLen; CRYPT_EAL_MdCTX *mdCtx = NULL; uint32_t mdOutLen = CRYPT_EAL_MdGetDigestSize(mdId); ASSERT_TRUE(mdOutLen != 0); mdOut->x = (uint8_t *)malloc(mdOutLen); ASSERT_TRUE(mdOut->x != NULL); mdOut->len = mdOutLen; outLen = mdOutLen; mdCtx = CRYPT_EAL_MdNewCtx(mdId); ASSERT_TRUE_AND_LOG("CRYPT_EAL_MdNewCtx", mdCtx != NULL); ASSERT_TRUE_AND_LOG("CRYPT_EAL_MdInit", CRYPT_EAL_MdInit(mdCtx) == 0); ASSERT_TRUE_AND_LOG("CRYPT_EAL_MdUpdate", CRYPT_EAL_MdUpdate(mdCtx, msgIn->x, msgIn->len) == 0); ASSERT_TRUE_AND_LOG("CRYPT_EAL_MdFinal", CRYPT_EAL_MdFinal(mdCtx, mdOut->x, &outLen) == 0); mdOut->len = outLen; CRYPT_EAL_MdFreeCtx(mdCtx); return SUCCESS; EXIT: CRYPT_EAL_MdFreeCtx(mdCtx); free(mdOut->x); mdOut->x = NULL; return ERROR; } void Set_DSA_Para( CRYPT_EAL_PkeyPara *para, CRYPT_EAL_PkeyPrv *prv, CRYPT_EAL_PkeyPub *pub, Hex *P, Hex *Q, Hex *G, Hex *X, Hex *Y) { para->id = CRYPT_PKEY_DSA; para->para.dsaPara.p = P->x; para->para.dsaPara.pLen = P->len; para->para.dsaPara.q = Q->x; para->para.dsaPara.qLen = Q->len; para->para.dsaPara.g = G->x; para->para.dsaPara.gLen = G->len; if (prv && X) { prv->id = CRYPT_PKEY_DSA; prv->key.dsaPrv.data = X->x; prv->key.dsaPrv.len = X->len; } if (pub && Y) { pub->id = CRYPT_PKEY_DSA; pub->key.dsaPub.data = Y->x; pub->key.dsaPub.len = Y->len; } } static void Set_DSA_Pub(CRYPT_EAL_PkeyPub *pub, uint8_t *key, uint32_t keyLen) { pub->id = CRYPT_PKEY_DSA; pub->key.dsaPub.data = key; pub->key.dsaPub.len = keyLen; } static void Set_DSA_Prv(CRYPT_EAL_PkeyPrv *prv, uint8_t *key, uint32_t keyLen) { prv->id = CRYPT_PKEY_DSA; prv->key.dsaPrv.data = key; prv->key.dsaPrv.len = keyLen; } int SignEncode(uint8_t *vectorSign, uint32_t *vectorSignLen, Hex *R, Hex *S, BN_BigNum **bnR, BN_BigNum **bnS) { *bnR = BN_Create(R->len * BITS_OF_BYTE); *bnS = BN_Create(S->len * BITS_OF_BYTE); ASSERT_EQ(BN_Bin2Bn(*bnR, R->x, R->len), CRYPT_SUCCESS); ASSERT_EQ(BN_Bin2Bn(*bnS, S->x, S->len), CRYPT_SUCCESS); ASSERT_EQ(CRYPT_EAL_EncodeSign(*bnR, *bnS, vectorSign, vectorSignLen), CRYPT_SUCCESS); return CRYPT_SUCCESS; EXIT: return ERROR; } /** * @test SDV_CRYPTO_DSA_SET_PARA_API_TC001 * @title DSA: CRYPT_EAL_PkeySetPara test. * @precon Registering memory-related functions. * Dsa para vertors. * @brief * 1. Create the context of the dsa algorithm, expected result 1. * 2. CRYPT_EAL_PkeySetPara: para = NULL, expected result 2. * 3. CRYPT_EAL_PkeySetPara, expected result 3, the parameters are as follows: * (1) p != NULL, pLen = 0 * (2) p = NULL, pLen != 0 * (3) q != NULL, qLen = 0 * (4) q = NULL, qLen != 0 * (5) g != NULL, gLen = 0 * (6) g = NULL, gLen != 0 * @expect * 1. Success, and context is not NULL. * 2. CRYPT_NULL_INPUT * 3. CRYPT_EAL_ERR_NEW_PARA_FAIL */ /* BEGIN_CASE */ void SDV_CRYPTO_DSA_SET_PARA_API_TC001(Hex *p, Hex *q, Hex *g, int isProvider) { CRYPT_EAL_PkeyCtx *pkey = NULL; uint8_t tmp[1]; CRYPT_EAL_PkeyPara para; para.id = CRYPT_PKEY_DSA; para.para.dsaPara.p = p->x; para.para.dsaPara.pLen = p->len; para.para.dsaPara.q = q->x; para.para.dsaPara.qLen = q->len; para.para.dsaPara.g = g->x; para.para.dsaPara.gLen = g->len; TestMemInit(); pkey = TestPkeyNewCtx(NULL, CRYPT_PKEY_DSA, CRYPT_EAL_PKEY_KEYMGMT_OPERATE, "provider=default", isProvider); ASSERT_TRUE(pkey != NULL); ASSERT_EQ(CRYPT_EAL_PkeySetPara(pkey, NULL), CRYPT_NULL_INPUT); if (p->x == NULL) { para.para.dsaPara.p = tmp; ASSERT_TRUE_AND_LOG("p != NULL, pLen = 0", CRYPT_EAL_PkeySetPara(pkey, &para) == CRYPT_EAL_ERR_NEW_PARA_FAIL); para.para.dsaPara.p = p->x; para.para.dsaPara.pLen = 128; ASSERT_TRUE_AND_LOG("p = NULL, pLen != 0", CRYPT_EAL_PkeySetPara(pkey, &para) == CRYPT_EAL_ERR_NEW_PARA_FAIL); para.para.dsaPara.pLen = p->len; } if (q->x == NULL) { para.para.dsaPara.q = tmp; ASSERT_TRUE_AND_LOG("q != NULL, qLen = 0", CRYPT_EAL_PkeySetPara(pkey, &para) == CRYPT_EAL_ERR_NEW_PARA_FAIL); para.para.dsaPara.q = q->x; para.para.dsaPara.qLen = 20; ASSERT_TRUE_AND_LOG("q == NULL, qLen != 0", CRYPT_EAL_PkeySetPara(pkey, &para) == CRYPT_EAL_ERR_NEW_PARA_FAIL); para.para.dsaPara.qLen = q->len; } if (g->x == NULL) { para.para.dsaPara.g = tmp; ASSERT_TRUE_AND_LOG("g != NULL, gLen = 0", CRYPT_EAL_PkeySetPara(pkey, &para) == CRYPT_EAL_ERR_NEW_PARA_FAIL); para.para.dsaPara.g = g->x; para.para.dsaPara.gLen = 128; ASSERT_TRUE_AND_LOG("g!= NULL, gLen != 0", CRYPT_EAL_PkeySetPara(pkey, &para) == CRYPT_EAL_ERR_NEW_PARA_FAIL); } EXIT: CRYPT_EAL_PkeyFreeCtx(pkey); } /* END_CASE */ /** * @test SDV_CRYPTO_DSA_CMP_API_TC001 * @title DSA: CRYPT_EAL_PkeyCmp test. * @precon Registering memory-related functions. * Dsa para vertors. * @brief * 1. Create the contexts(ctx1, ctx2) of the dsa algorithm, expected result 1 * 2. Call the CRYPT_EAL_PkeyCmp to compare ctx1 and ctx2, expected result 2 * 3. Set public key and para for ctx1, expected result 3 * 4. Call the CRYPT_EAL_PkeyCmp to compare ctx1 and ctx2, expected result 4 * 5. Set public key and para for ctx2, expected result 5 * 6. Call the CRYPT_EAL_PkeyCmp to compare ctx1 and ctx2, expected result 6 * @expect * 1. Success, and contexts are not NULL. * 2. CRYPT_DSA_ERR_KEY_INFO * 3. CRYPT_SUCCESS * 4. CRYPT_DSA_ERR_KEY_INFO * 5. CRYPT_SUCCESS * 6. CRYPT_SUCCESS */ /* BEGIN_CASE */ void SDV_CRYPTO_DSA_CMP_API_TC001(Hex *p, Hex *q, Hex *g, Hex *y, int isProvider) { CRYPT_EAL_PkeyPara para = {0}; CRYPT_EAL_PkeyPub pub = {0}; Set_DSA_Para(&para, NULL, &pub, p, q, g, NULL, y); TestMemInit(); CRYPT_EAL_PkeyCtx *ctx1 = TestPkeyNewCtx(NULL, CRYPT_PKEY_DSA, CRYPT_EAL_PKEY_KEYMGMT_OPERATE, "provider=default", isProvider); CRYPT_EAL_PkeyCtx *ctx2 = TestPkeyNewCtx(NULL, CRYPT_PKEY_DSA, CRYPT_EAL_PKEY_KEYMGMT_OPERATE, "provider=default", isProvider); ASSERT_TRUE(ctx1 != NULL && ctx2 != NULL); ASSERT_EQ(CRYPT_EAL_PkeyCmp(ctx1, ctx2), CRYPT_DSA_ERR_KEY_INFO); // no key and no para ASSERT_EQ(CRYPT_EAL_PkeySetPara(ctx1, &para), CRYPT_SUCCESS); ASSERT_EQ(CRYPT_EAL_PkeySetPub(ctx1, &pub), CRYPT_SUCCESS); ASSERT_EQ(CRYPT_EAL_PkeyCmp(ctx1, ctx2), CRYPT_DSA_ERR_KEY_INFO); // ctx2 no pubkey ASSERT_EQ(CRYPT_EAL_PkeySetPara(ctx2, &para), CRYPT_SUCCESS); ASSERT_EQ(CRYPT_EAL_PkeySetPub(ctx2, &pub), CRYPT_SUCCESS); ASSERT_EQ(CRYPT_EAL_PkeyCmp(ctx1, ctx2), CRYPT_SUCCESS); EXIT: CRYPT_EAL_PkeyFreeCtx(ctx1); CRYPT_EAL_PkeyFreeCtx(ctx2); } /* END_CASE */ /** * @test SDV_CRYPTO_DSA_CTRL_API_TC001 * @title DSA: CRYPT_EAL_PkeyCtrl test. * @precon Registering memory-related functions. * @brief * 1. Create the context(ctx) of the dsa algorithm, expected result 1 * 2. Call the CRYPT_EAL_PkeyCtrl method: * (1) val = NULL, expected result 2 * (2) len = 0, expected result 3 * (3) opt = CRYPT_CTRL_SET_RSA_PADDING, expected result 4 * @expect * 1. Success, and contexts are not NULL. * 2. CRYPT_NULL_INPUT * 3. CRYPT_DSA_UNSUPPORTED_CTRL_OPTION * 4. CRYPT_DSA_UNSUPPORTED_CTRL_OPTION */ /* BEGIN_CASE */ void SDV_CRYPTO_DSA_CTRL_API_TC001(int isProvider) { int32_t ref = 1; TestMemInit(); CRYPT_EAL_PkeyCtx *ctx = TestPkeyNewCtx(NULL, CRYPT_PKEY_DSA, CRYPT_EAL_PKEY_KEYMGMT_OPERATE, "provider=default", isProvider); ASSERT_TRUE(ctx != NULL); ASSERT_EQ(CRYPT_EAL_PkeyCtrl(ctx, CRYPT_CTRL_UP_REFERENCES, NULL, sizeof(uint32_t)), CRYPT_INVALID_ARG); ASSERT_EQ(CRYPT_EAL_PkeyCtrl(ctx, CRYPT_CTRL_UP_REFERENCES, &ref, 0), CRYPT_INVALID_ARG); ASSERT_EQ( CRYPT_EAL_PkeyCtrl(ctx, CRYPT_CTRL_SET_RSA_PADDING, &ref, sizeof(int32_t)), CRYPT_DSA_UNSUPPORTED_CTRL_OPTION); EXIT: CRYPT_EAL_PkeyFreeCtx(ctx); } /* END_CASE */ /** * @test SDV_CRYPTO_DSA_GET_PARA_API_TC001 * @title DSA: CRYPT_EAL_PkeyGetPara test. * @precon Registering memory-related functions. * Dsa para vertors. * @brief * 1. Create the contexts of the dsa algorithm, expected result 1. * 2. Call the CRYPT_EAL_PkeySetPara method with correct parameters, expected result 2 * 3. Call the CRYPT_EAL_PkeySetPara method: para.id != pkey.id, expected result 3 * 4. Call the CRYPT_EAL_PkeySetPara method: pkey=NULL or para=NULL, expected result 4 * 5. Call the CRYPT_EAL_PkeySetPara method with correct parameters, expected result 5 * 6. Check whether the configured parameters are the same as the obtained parameters, expected result 6 * @expect * 1. Success, and context is not NULL. * 2. CRYPT_SUCCESS * 3. CRYPT_EAL_ERR_ALGID * 4. CRYPT_NULL_INPUT * 5. CRYPT_SUCCESS * 6. Parameters are equal. */ /* BEGIN_CASE */ void SDV_CRYPTO_DSA_GET_PARA_API_TC001(Hex *p, Hex *q, Hex *g, int isProvider) { uint8_t buf_p[1030] = {0}; uint32_t bufLen = sizeof(buf_p); uint8_t buf_q[1030] = {0}; uint8_t buf_g[1030] = {0}; Hex getP = {buf_p, bufLen}; Hex getQ = {buf_q, bufLen}; Hex getG = {buf_g, bufLen}; CRYPT_EAL_PkeyPara para1 = {0}; CRYPT_EAL_PkeyPara para2 = {0}; Set_DSA_Para(&para1, NULL, NULL, p, q, g, NULL, NULL); Set_DSA_Para(&para2, NULL, NULL, &getP, &getQ, &getG, NULL, NULL); TestMemInit(); CRYPT_EAL_PkeyCtx *pKey = TestPkeyNewCtx(NULL, CRYPT_PKEY_DSA, CRYPT_EAL_PKEY_KEYMGMT_OPERATE, "provider=default", isProvider); ASSERT_TRUE(pKey != NULL); para2.id = CRYPT_PKEY_RSA; ASSERT_TRUE(CRYPT_EAL_PkeySetPara(pKey, &para1) == CRYPT_SUCCESS); ASSERT_TRUE(CRYPT_EAL_PkeyGetPara(pKey, &para2) == CRYPT_EAL_ERR_ALGID); ASSERT_TRUE(CRYPT_EAL_PkeyGetPara(NULL, &para2) == CRYPT_NULL_INPUT); ASSERT_TRUE(CRYPT_EAL_PkeyGetPara(pKey, NULL) == CRYPT_NULL_INPUT); para2.id = CRYPT_PKEY_DSA; ASSERT_TRUE(CRYPT_EAL_PkeyGetPara(pKey, &para2) == CRYPT_SUCCESS); ASSERT_TRUE(para1.para.dsaPara.pLen == para2.para.dsaPara.pLen); ASSERT_TRUE(memcmp(para1.para.dsaPara.p, para2.para.dsaPara.p, para1.para.dsaPara.pLen) == 0); ASSERT_TRUE(para1.para.dsaPara.qLen == para2.para.dsaPara.qLen); ASSERT_TRUE(memcmp(para1.para.dsaPara.q, para2.para.dsaPara.q, para1.para.dsaPara.qLen) == 0); ASSERT_TRUE(para1.para.dsaPara.gLen == para2.para.dsaPara.gLen); ASSERT_TRUE(memcmp(para1.para.dsaPara.g, para2.para.dsaPara.g, para1.para.dsaPara.gLen) == 0); EXIT: CRYPT_EAL_PkeyFreeCtx(pKey); } /* END_CASE */ /** * @test SDV_CRYPTO_DSA_SIGN_VERIFY_FUNC_TC001 * @title DSA: Set(or copy) the key, sign, and verify the signature. * @precon Registering memory-related functions. * Dsa vertors. * @brief * 1. Mock BN_RandRange method to generate vector K. * 2. Create the context of the dsa algorithm, expected result 1. * 3. Set para, private key and public key, expected result 2. * 4. Call the CRYPT_EAL_PkeyGetSignLen method to get sign length, expected result 3. * 5. Allocate the memory for the signature, expected result 4. * 6. Encoding r and s vectors, expected result 5. * 7. Sign and compare the signatures of hitls and vector, expected result 6. * 8. Verify, expected result 7. * 9. Copy the ctx and repeat steps 7 through 8. * @expect * 1. Success, and context is not NULL. * 2. CRYPT_SUCCESS * 3. signLen > 0 * 4. Success * 5. Success * 6. CRYPT_SUCCESS, the two signatures are the same. * 7. CRYPT_SUCCESS */ /* BEGIN_CASE */ void SDV_CRYPTO_DSA_SIGN_VERIFY_FUNC_TC001( int hashId, Hex *P, Hex *Q, Hex *G, Hex *Msg, Hex *X, Hex *Y, Hex *K, Hex *R, Hex *S, int isProvider) { if (IsMdAlgDisabled(hashId)) { SKIP_TEST(); } uint32_t signLen; uint8_t *vectorSign = NULL; uint8_t *hitlsSign = NULL; uint32_t vectorSignLen, hitlsSignOutLen; BN_BigNum *bnR = NULL; BN_BigNum *bnS = NULL; CRYPT_EAL_PkeyCtx *pkey = NULL; CRYPT_EAL_PkeyCtx *cpyCtx = NULL; CRYPT_EAL_PkeyPara para = {0}; CRYPT_EAL_PkeyPrv prv = {0}; CRYPT_EAL_PkeyPub pub = {0}; Set_DSA_Para(&para, &prv, &pub, P, Q, G, X, Y); FuncStubInfo tmpRpInfo; ASSERT_EQ(memcpy_s(g_kRandBuf, sizeof(g_kRandBuf), K->x, K->len), 0); g_kRandBufLen = K->len; STUB_Init(); STUB_Replace(&tmpRpInfo, BN_RandRangeEx, STUB_RandRangeK); TestMemInit(); pkey = TestPkeyNewCtx(NULL, CRYPT_PKEY_DSA, CRYPT_EAL_PKEY_KEYMGMT_OPERATE + CRYPT_EAL_PKEY_SIGN_OPERATE, "provider=default", isProvider); ASSERT_TRUE(pkey != NULL); ASSERT_EQ(CRYPT_EAL_PkeySetPara(pkey, &para), CRYPT_SUCCESS); ASSERT_EQ(CRYPT_EAL_PkeySetPrv(pkey, &prv), CRYPT_SUCCESS); ASSERT_EQ(CRYPT_EAL_PkeySetPub(pkey, &pub), CRYPT_SUCCESS); signLen = CRYPT_EAL_PkeyGetSignLen(pkey); ASSERT_TRUE(signLen > 0); /* Encoding r and s vectors */ vectorSign = (uint8_t *)malloc(signLen); vectorSignLen = signLen; ASSERT_EQ(SignEncode(vectorSign, &vectorSignLen, R, S, &bnR, &bnS), CRYPT_SUCCESS); /* Sign */ hitlsSign = (uint8_t *)malloc(signLen); hitlsSignOutLen = signLen; ASSERT_EQ(CRYPT_EAL_PkeySign(pkey, hashId, Msg->x, Msg->len, hitlsSign, &hitlsSignOutLen), CRYPT_SUCCESS); /* Compare the signatures of hitls and vector. */ ASSERT_EQ(hitlsSignOutLen, vectorSignLen); ASSERT_EQ(memcmp(vectorSign, hitlsSign, hitlsSignOutLen), 0); /* Verify */ ASSERT_EQ(CRYPT_EAL_PkeyVerify(pkey, hashId, Msg->x, Msg->len, hitlsSign, hitlsSignOutLen), CRYPT_SUCCESS); /* Copy the ctx and verify the signature. */ cpyCtx = TestPkeyNewCtx(NULL, CRYPT_PKEY_DSA, CRYPT_EAL_PKEY_KEYMGMT_OPERATE + CRYPT_EAL_PKEY_SIGN_OPERATE, "provider=default", isProvider); ASSERT_TRUE(cpyCtx != NULL); ASSERT_EQ(CRYPT_EAL_PkeyCopyCtx(cpyCtx, pkey), CRYPT_SUCCESS); hitlsSignOutLen = signLen; ASSERT_EQ(CRYPT_EAL_PkeySign(cpyCtx, hashId, Msg->x, Msg->len, hitlsSign, &hitlsSignOutLen), CRYPT_SUCCESS); ASSERT_EQ(CRYPT_EAL_PkeyVerify(cpyCtx, hashId, Msg->x, Msg->len, hitlsSign, hitlsSignOutLen), CRYPT_SUCCESS); EXIT: STUB_Reset(&tmpRpInfo); free(vectorSign); free(hitlsSign); BN_Destroy(bnR); BN_Destroy(bnS); BSL_ERR_RemoveErrorStack(true); CRYPT_EAL_PkeyFreeCtx(pkey); CRYPT_EAL_PkeyFreeCtx(cpyCtx); } /* END_CASE */ /** * @test SDV_CRYPTO_DSA_SIGN_VERIFY_DATA_FUNC_TC001 * @title DSA sets the key and performs signature and signature verification tests on the hash data. * @precon Registering memory-related functions. * Dsa vertors. * @brief * 1. Mock BN_RandRange method to generate vector K. * 2. Create the context of the dsa algorithm, expected result 1. * 3. Set para, private key and public key, expected result 2. * 4. Call the CRYPT_EAL_PkeyGetSignLen method to get sign length, expected result 3. * 5. Allocate the memory for the signature, expected result 4. * 6. Encoding r and s vectors, expected result 5. * 7. Compute the hash of the msg, sign and compare the signatures of hitls and vector, expected result 6. * 8. Verify, expected result 7. * @expect * 1. Success, and context is not NULL. * 2. CRYPT_SUCCESS * 3. signLen > 0 * 4. Success * 5. Success * 6. CRYPT_SUCCESS, the two signatures are the same. */ /* BEGIN_CASE */ void SDV_CRYPTO_DSA_SIGN_VERIFY_DATA_FUNC_TC001( int hashId, Hex *P, Hex *Q, Hex *G, Hex *Msg, Hex *X, Hex *Y, Hex *K, Hex *R, Hex *S, int isProvider) { if (IsMdAlgDisabled(hashId)) { SKIP_TEST(); } uint32_t signLen; uint8_t *vectorSign = NULL; uint8_t *hitlsSign = NULL; uint32_t vectorSignLen, hitlsSignOutLen; BN_BigNum *bnR = NULL; BN_BigNum *bnS = NULL; CRYPT_EAL_PkeyCtx *pkey = NULL; Hex mdOut = {0}; FuncStubInfo tmpRpInfo; ASSERT_EQ(memcpy_s(g_kRandBuf, sizeof(g_kRandBuf), K->x, K->len), 0); g_kRandBufLen = K->len; STUB_Init(); STUB_Replace(&tmpRpInfo, BN_RandRangeEx, STUB_RandRangeK); CRYPT_EAL_PkeyPara para; CRYPT_EAL_PkeyPrv prv = {0}; CRYPT_EAL_PkeyPub pub; Set_DSA_Para(&para, &prv, &pub, P, Q, G, X, Y); TestMemInit(); pkey = TestPkeyNewCtx(NULL, CRYPT_PKEY_DSA, CRYPT_EAL_PKEY_KEYMGMT_OPERATE + CRYPT_EAL_PKEY_SIGN_OPERATE, "provider=default", isProvider); ASSERT_TRUE(pkey != NULL); ASSERT_EQ(CRYPT_EAL_PkeySetPara(pkey, &para), CRYPT_SUCCESS); ASSERT_EQ(CRYPT_EAL_PkeySetPrv(pkey, &prv), CRYPT_SUCCESS); ASSERT_EQ(CRYPT_EAL_PkeySetPub(pkey, &pub), CRYPT_SUCCESS); signLen = CRYPT_EAL_PkeyGetSignLen(pkey); ASSERT_TRUE(signLen > 0); /* Encoding r and s vectors */ vectorSign = (uint8_t *)malloc(signLen); vectorSignLen = signLen; ASSERT_EQ(SignEncode(vectorSign, &vectorSignLen, R, S, &bnR, &bnS), CRYPT_SUCCESS); /* Calculates the hash of the msg. */ ASSERT_EQ(Compute_Md(hashId, Msg, &mdOut), SUCCESS); /* Sign */ hitlsSign = (uint8_t *)malloc(signLen); hitlsSignOutLen = signLen; ASSERT_EQ(CRYPT_EAL_PkeySignData(pkey, mdOut.x, mdOut.len, hitlsSign, &hitlsSignOutLen), CRYPT_SUCCESS); /* Compare the signatures of hitls and vector. */ ASSERT_EQ(hitlsSignOutLen, vectorSignLen); ASSERT_EQ(memcmp(vectorSign, hitlsSign, hitlsSignOutLen), 0); /* Verify the signature of the hash data. */ ASSERT_EQ(CRYPT_EAL_PkeyVerifyData(pkey, mdOut.x, mdOut.len, hitlsSign, hitlsSignOutLen), CRYPT_SUCCESS); EXIT: STUB_Reset(&tmpRpInfo); if (mdOut.x != NULL) { free(mdOut.x); } free(vectorSign); free(hitlsSign); BN_Destroy(bnR); BN_Destroy(bnS); BSL_ERR_RemoveErrorStack(true); CRYPT_EAL_PkeyFreeCtx(pkey); } /* END_CASE */ /** * @test SDV_CRYPTO_DSA_GEN_FUNC_TC001 * @title DSA function test (gen a key pair). * @precon Registering memory-related functions. * Dsa vertors. * @brief * 1. Init the drbg, expected result 1. * 2. Create the context(ctx) of the DSA algorithm, expected result 2. * 3. Set para for dsa, expected result 3. * 4. Generate a key pair, expected result 4. * 5. Call the CRYPT_EAL_PkeyGetSignLen method to get sign length, expected result 5. * 6. Allocate the memory for the signature, expected result 6. * 7. Sign, expected result 7. * 8. Verify, expected result 8. * @expect * 1. CRYPT_SUCCESS * 2. Success, and two contexts are not NULL. * 3. CRYPT_SUCCESS * 4. CRYPT_SUCCESS * 5. signLen > 0 * 6. Success * 7. CRYPT_SUCCESS * 8. CRYPT_SUCCESS */ /* BEGIN_CASE */ void SDV_CRYPTO_DSA_GEN_FUNC_TC001(Hex *p, Hex *q, Hex *g, Hex *data, int isProvider) { CRYPT_EAL_PkeyCtx *ctx = NULL; CRYPT_EAL_PkeyPara para = {0}; uint8_t *sign = NULL; uint32_t signLen; Set_DSA_Para(&para, NULL, NULL, p, q, g, NULL, NULL); TestMemInit(); ASSERT_EQ(TestRandInit(), CRYPT_SUCCESS); ctx = TestPkeyNewCtx(NULL, CRYPT_PKEY_DSA, CRYPT_EAL_PKEY_KEYMGMT_OPERATE + CRYPT_EAL_PKEY_SIGN_OPERATE, "provider=default", isProvider); ASSERT_TRUE(ctx != NULL); ASSERT_EQ(CRYPT_EAL_PkeySetPara(ctx, &para), CRYPT_SUCCESS); ASSERT_EQ(CRYPT_EAL_PkeyGen(ctx), CRYPT_SUCCESS); signLen = CRYPT_EAL_PkeyGetSignLen(ctx); ASSERT_TRUE(signLen > 0); sign = (uint8_t *)malloc(signLen); ASSERT_EQ(CRYPT_EAL_PkeySign(ctx, CRYPT_MD_SHA256, data->x, data->len, sign, &signLen), CRYPT_SUCCESS); ASSERT_EQ(CRYPT_EAL_PkeyVerify(ctx, CRYPT_MD_SHA256, data->x, data->len, sign, signLen), CRYPT_SUCCESS); EXIT: CRYPT_EAL_PkeyFreeCtx(ctx); free(sign); TestRandDeInit(); } /* END_CASE */ /** * @test SDV_CRYPTO_DSA_DUP_CTX_FUNC_TC001 * @title DSA: CRYPT_EAL_PkeyDupCtx test. * @precon Registering memory-related functions. * Dsa vertors. * @brief * 1. Create the context of the dsa algorithm, expected result 1. * 2. Init the drbg, expected result 2. * 3. Set para and generate a key pair, expected result 3. * 4. Call the CRYPT_EAL_PkeyDupCtx method to dup dsa context, expected result 4. * 5. Call the CRYPT_EAL_PkeyCmp method to compare public key, expected result 5. * 6. Call the CRYPT_EAL_PkeyGetKeyBits to get keyLen from contexts, expected result 6. * 7. Call the CRYPT_EAL_PkeyGetPub method to obtain the public key from the contexts, expected result 7. * 8. Compare public keys, expected result 8. * 9. Call the CRYPT_EAL_PkeyGetPrv method to obtain the private key from the contexts, expected result 9. * 10. Compare privates keys, expected result 10. * @expect * 1. Success, and context is not NULL. * 2-3. CRYPT_SUCCESS * 4. Success, and context is not NULL. * 5. CRYPT_SUCCESS * 6. The key length obtained from both contexts is the same. * 7. CRYPT_SUCCESS * 8. The two public keys are the same. * 9. CRYPT_SUCCESS * 10. The two private keys are the same. */ /* BEGIN_CASE */ void SDV_CRYPTO_DSA_DUP_CTX_FUNC_TC001(Hex *p, Hex *q, Hex *g, int isProvider) { uint8_t *key1 = NULL; uint8_t *key2 = NULL; uint32_t keyLen1, keyLen2; CRYPT_EAL_PkeyPara para = {0}; CRYPT_EAL_PkeyPub pub1, pub2; CRYPT_EAL_PkeyPrv prv1, prv2; CRYPT_EAL_PkeyCtx *ctx = NULL; CRYPT_EAL_PkeyCtx *dupCtx = NULL; Set_DSA_Para(&para, NULL, NULL, p, q, g, NULL, NULL); TestMemInit(); ctx = TestPkeyNewCtx(NULL, CRYPT_PKEY_DSA, CRYPT_EAL_PKEY_KEYMGMT_OPERATE, "provider=default", isProvider); ASSERT_TRUE(ctx != NULL); ASSERT_EQ(TestRandInit(), CRYPT_SUCCESS); ASSERT_EQ(CRYPT_EAL_PkeySetPara(ctx, &para), CRYPT_SUCCESS); ASSERT_EQ(CRYPT_EAL_PkeyGen(ctx), CRYPT_SUCCESS); dupCtx = CRYPT_EAL_PkeyDupCtx(ctx); ASSERT_TRUE(dupCtx != NULL); ASSERT_EQ(CRYPT_EAL_PkeyCmp(ctx, dupCtx), CRYPT_SUCCESS); keyLen1 = CRYPT_EAL_PkeyGetKeyBits(ctx); keyLen2 = CRYPT_EAL_PkeyGetKeyBits(dupCtx); ASSERT_EQ(keyLen1, keyLen2); key1 = calloc(1u, keyLen1); key2 = calloc(1u, keyLen2); ASSERT_TRUE(key1 != NULL && key2 != NULL); Set_DSA_Pub(&pub1, key1, keyLen1); Set_DSA_Pub(&pub2, key2, keyLen2); ASSERT_EQ(CRYPT_EAL_PkeyGetPub(ctx, &pub1), CRYPT_SUCCESS); ASSERT_EQ(CRYPT_EAL_PkeyGetPub(dupCtx, &pub2), CRYPT_SUCCESS); ASSERT_COMPARE("Compare public key", key1, pub1.key.dsaPub.len, key2, pub2.key.dsaPub.len); Set_DSA_Prv(&prv1, key1, keyLen1); Set_DSA_Prv(&prv2, key2, keyLen2); ASSERT_EQ(CRYPT_EAL_PkeyGetPrv(ctx, &prv1), CRYPT_SUCCESS); ASSERT_EQ(CRYPT_EAL_PkeyGetPrv(dupCtx, &prv2), CRYPT_SUCCESS); ASSERT_COMPARE("Compare private key", key1, prv1.key.dsaPrv.len, key2, prv2.key.dsaPrv.len); EXIT: TestRandDeInit(); CRYPT_EAL_PkeyFreeCtx(ctx); CRYPT_EAL_PkeyFreeCtx(dupCtx); BSL_SAL_Free(key1); BSL_SAL_Free(key2); } /* END_CASE */ /** * @test SDV_CRYPTO_DSA_KEY_PAIR_CHECK_FUNC_TC001 * @title DSA: key pair check. * @precon Registering memory-related functions. * @brief * 1. Create two contexts(pubCtx, prvCtx) of the dsa algorithm, expected result 1 * 2. Set para and public key for pubCtx, expected result 2 * 3. Set para and private key for prvCtx, expected result 3 * 4. Init the drbg, expected result 5, expected result 4 * 5. Check whether the public key matches the private key, expected result 5 * @expect * 1. Success, and contexts are not NULL. * 2-4. CRYPT_SUCCESS * 5. Return CRYPT_SUCCESS when expect is 1, CRYPT_DSA_VERIFY_FAIL otherwise. */ /* BEGIN_CASE */ void SDV_CRYPTO_DSA_KEY_PAIR_CHECK_FUNC_TC001(Hex *P, Hex *Q, Hex *G, Hex *X, Hex *Y, int expect) { #if !defined(HITLS_CRYPTO_DSA_CHECK) (void)P; (void)Q; (void)G; (void)X; (void)Y; (void)expect; SKIP_TEST(); #else CRYPT_EAL_PkeyCtx *pubCtx = NULL; CRYPT_EAL_PkeyCtx *prvCtx = NULL; CRYPT_EAL_PkeyPara para = {0}; CRYPT_EAL_PkeyPrv prv = {0}; CRYPT_EAL_PkeyPub pub = {0}; int expectRet = expect == 1 ? CRYPT_SUCCESS : CRYPT_DSA_PAIRWISE_CHECK_FAIL; Set_DSA_Para(&para, &prv, &pub, P, Q, G, X, Y); TestMemInit(); pubCtx = CRYPT_EAL_PkeyNewCtx(CRYPT_PKEY_DSA); prvCtx = CRYPT_EAL_PkeyNewCtx(CRYPT_PKEY_DSA); ASSERT_TRUE(pubCtx != NULL && prvCtx != NULL); ASSERT_EQ(CRYPT_EAL_PkeySetPara(pubCtx, &para), CRYPT_SUCCESS); ASSERT_EQ(CRYPT_EAL_PkeySetPub(pubCtx, &pub), CRYPT_SUCCESS); ASSERT_EQ(CRYPT_EAL_PkeySetPara(prvCtx, &para), CRYPT_SUCCESS); ASSERT_EQ(CRYPT_EAL_PkeySetPrv(prvCtx, &prv), CRYPT_SUCCESS); ASSERT_EQ(TestRandInit(), CRYPT_SUCCESS); ASSERT_EQ(CRYPT_EAL_PkeyPairCheck(pubCtx, prvCtx), expectRet); EXIT: TestRandDeInit(); CRYPT_EAL_PkeyFreeCtx(pubCtx); CRYPT_EAL_PkeyFreeCtx(prvCtx); #endif } /* END_CASE */ /** * @test SDV_CRYPTO_DSA_GET_KEY_BITS_FUNC_TC001 * @title DSA: get key bits. * @brief * 1. Create a context of the DSA algorithm, expected result 1 * 2. Get key bits, expected result 2 * @expect * 1. Success, and context is not NULL. * 2. Equal to keyBits. */ /* BEGIN_CASE */ void SDV_CRYPTO_DSA_GET_KEY_BITS_FUNC_TC001(int id, int keyBits, Hex *P, Hex *Q, Hex *G, int isProvider) { CRYPT_EAL_PkeyCtx *pkey = TestPkeyNewCtx(NULL, id, CRYPT_EAL_PKEY_KEYMGMT_OPERATE, "provider=default", isProvider); ASSERT_TRUE(pkey != NULL); CRYPT_EAL_PkeyPara para; para.id = CRYPT_PKEY_DSA; para.para.dsaPara.p = P->x; para.para.dsaPara.pLen = P->len; para.para.dsaPara.q = Q->x; para.para.dsaPara.qLen = Q->len; para.para.dsaPara.g = G->x; para.para.dsaPara.gLen = G->len; ASSERT_TRUE(CRYPT_EAL_PkeySetPara(pkey, &para) == CRYPT_SUCCESS); ASSERT_TRUE(CRYPT_EAL_PkeyGetKeyBits(pkey) == (uint32_t)keyBits); EXIT: CRYPT_EAL_PkeyFreeCtx(pkey); } /* END_CASE */ /** * @test SDV_CRYPTO_DSA_GET_SEC_BITS_FUNC_TC001 * @title DSA CRYPT_EAL_PkeyGetSecurityBits test. * @precon nan * @brief * 1. Create the context of the dsa algorithm, expected result 1 * 2. Set dsa para, expected result 2 * 3. Call the CRYPT_EAL_PkeyGetSecurityBits Obtains secbits, expected result 3 * @expect * 1. Success, and the context is not null. * 2. CRYPT_SUCCESS * 3. The return value is secBits. */ /* BEGIN_CASE */ void SDV_CRYPTO_DSA_GET_SEC_BITS_FUNC_TC001(int id, int secBits, Hex *P, Hex *Q, Hex *G) { CRYPT_EAL_PkeyCtx *pkey = CRYPT_EAL_PkeyNewCtx(id); ASSERT_TRUE(pkey != NULL); CRYPT_EAL_PkeyPara para; para.id = CRYPT_PKEY_DSA; para.para.dsaPara.p = P->x; para.para.dsaPara.pLen = P->len; para.para.dsaPara.q = Q->x; para.para.dsaPara.qLen = Q->len; para.para.dsaPara.g = G->x; para.para.dsaPara.gLen = G->len; ASSERT_TRUE(CRYPT_EAL_PkeySetPara(pkey, &para) == CRYPT_SUCCESS); ASSERT_EQ(CRYPT_EAL_PkeyGetSecurityBits(pkey), secBits); EXIT: CRYPT_EAL_PkeyFreeCtx(pkey); } /* END_CASE */ #ifdef HITLS_CRYPTO_DSA_GEN_PARA static uint8_t *g_dsa_seed = NULL; static int32_t ref = 0; int32_t STUB_CRYPT_EAL_Randbytes(uint8_t *byte, uint32_t len) { if (ref == 0) { (void)memcpy_s(byte, len, g_dsa_seed, len); ref = 1; } else { for (uint32_t i = 0; i < len; i++) { byte[i] = (uint8_t)(rand() % 255); // mod 255 get 8bit number. } } return CRYPT_SUCCESS; } int32_t STUB_CRYPT_EAL_RandbytesEx(CRYPT_EAL_LibCtx *libCtx, uint8_t *byte, uint32_t len) { (void)libCtx; return STUB_CRYPT_EAL_Randbytes(byte, len); } #endif /* HITLS_CRYPTO_DSA */ /* BEGIN_CASE */ void SDV_CRYPTO_DSA_VERIFY_PQ_FUNC_TC001(int algId, Hex *seed, char *pHex, char *qHex) { #ifndef HITLS_CRYPTO_DSA_GEN_PARA (void)algId; (void)seed; (void)pHex; (void)qHex; SKIP_TEST(); #else BSL_Buffer seedTmp = {seed->x, seed->len}; BN_BigNum *p = NULL; BN_BigNum *q = NULL; ASSERT_EQ(BN_Hex2Bn(&p, pHex), CRYPT_SUCCESS); ASSERT_EQ(BN_Hex2Bn(&q, qHex), CRYPT_SUCCESS); CRYPT_DSA_Para dsaPara = {p, q, NULL}; uint32_t counter = 5; ASSERT_EQ(TestRandInit(), CRYPT_SUCCESS); ASSERT_EQ(CryptDsaFips1864ValidatePq(algId, NULL, NULL, CRYPT_DSA_FFC_PARAM, &seedTmp, &dsaPara, counter), 0); EXIT: TestRandDeInit(); BN_Destroy(p); BN_Destroy(q); #endif } /* END_CASE */ /* BEGIN_CASE */ void SDV_CRYPTO_DSA_GEN_PQ_FUNC_TC001(int algId, int L, int N, Hex *seed, char *pHex, char *qHex) { #ifndef HITLS_CRYPTO_DSA_GEN_PARA (void)algId; (void)L; (void)N; (void)seed; (void)pHex; (void)qHex; SKIP_TEST(); #else BN_BigNum *pReq = NULL; BN_BigNum *qReq = NULL; uint32_t counter = 0; g_dsa_seed = seed->x; ASSERT_EQ(TestRandInit(), CRYPT_SUCCESS); FuncStubInfo tmpRpInfo; STUB_Init(); STUB_Replace(&tmpRpInfo, CRYPT_EAL_RandbytesEx, STUB_CRYPT_EAL_RandbytesEx); CRYPT_RandRegist(STUB_CRYPT_EAL_Randbytes); ref = 0; DSA_FIPS186_4_Para fipsPara = {algId, 0, L, N}; BSL_Buffer seedTmp = {seed->x, seed->len}; CRYPT_DSA_Ctx *ctx = CRYPT_DSA_NewCtx(); ASSERT_TRUE(ctx != NULL); CRYPT_DSA_Para *dsaPara = (CRYPT_DSA_Para *)BSL_SAL_Calloc(1, sizeof(CRYPT_DSA_Para)); ASSERT_TRUE(dsaPara != NULL); ctx->para = dsaPara; ASSERT_EQ(CryptDsaFips1864GenPq(ctx, &fipsPara, CRYPT_DSA_FFC_PARAM, &seedTmp, &counter), CRYPT_SUCCESS); ASSERT_EQ(CryptDsaFips1864ValidatePq(algId, NULL, NULL, CRYPT_DSA_FFC_PARAM, &seedTmp, ctx->para, counter), 0); ASSERT_EQ(BN_Hex2Bn(&pReq, pHex), CRYPT_SUCCESS); ASSERT_EQ(BN_Hex2Bn(&qReq, qHex), CRYPT_SUCCESS); ASSERT_EQ(BN_Cmp(ctx->para->p, pReq), 0); ASSERT_EQ(BN_Cmp(ctx->para->q, qReq), 0); EXIT: CRYPT_EAL_RandDeinit(); STUB_Reset(&tmpRpInfo); TestRandDeInit(); g_dsa_seed = NULL; CRYPT_DSA_FreeCtx(ctx); BN_Destroy(pReq); BN_Destroy(qReq); #endif } /* END_CASE */ /* BEGIN_CASE */ void SDV_CRYPTO_DSA_GEN_G_FUNC_TC001(char *pHex, char *qHex, char *gHex) { #ifndef HITLS_CRYPTO_DSA_GEN_PARA (void)pHex; (void)qHex; (void)gHex; SKIP_TEST(); #else BN_BigNum *p = NULL; BN_BigNum *q = NULL; BN_BigNum *gReq = NULL; ASSERT_EQ(BN_Hex2Bn(&p, pHex), CRYPT_SUCCESS); ASSERT_EQ(BN_Hex2Bn(&q, qHex), CRYPT_SUCCESS); ASSERT_EQ(BN_Hex2Bn(&gReq, gHex), CRYPT_SUCCESS); CRYPT_DSA_Para dsaPara = {p, q, NULL}; ASSERT_EQ(CryptDsaFips1864GenUnverifiableG(&dsaPara), CRYPT_SUCCESS); ASSERT_EQ(CryptDsaFips1864PartialValidateG(&dsaPara), CRYPT_SUCCESS); ASSERT_EQ(BN_Cmp(dsaPara.g, gReq), 0); EXIT: BN_Destroy(p); BN_Destroy(q); BN_Destroy(dsaPara.g); BN_Destroy(gReq); #endif } /* END_CASE */ /* BEGIN_CASE */ void SDV_CRYPTO_DSA_GEN_G_FUNC_TC002(int algId, int index, Hex *seed, char *pHex, char *qHex) { #ifndef HITLS_CRYPTO_DSA_GEN_PARA (void)algId; (void)index; (void)seed; (void)pHex; (void)qHex; SKIP_TEST(); #else BN_BigNum *p = NULL; BN_BigNum *q = NULL; ASSERT_EQ(BN_Hex2Bn(&p, pHex), CRYPT_SUCCESS); ASSERT_EQ(BN_Hex2Bn(&q, qHex), CRYPT_SUCCESS); DSA_FIPS186_4_Para fipsPara = {algId, index, 0, 0}; BSL_Buffer seedTmp = {seed->x, seed->len}; CRYPT_DSA_Para dsaPara = {p, q, NULL}; ASSERT_EQ(CryptDsaFips1864GenVerifiableG(&fipsPara, &seedTmp, &dsaPara), CRYPT_SUCCESS); ASSERT_EQ(CryptDsaFips1864ValidateG(&fipsPara, &seedTmp, &dsaPara), CRYPT_SUCCESS); EXIT: BN_Destroy(p); BN_Destroy(q); BN_Destroy(dsaPara.g); #endif } /* END_CASE */ /* BEGIN_CASE */ void SDV_CRYPTO_DSA_GEN_G_FUNC_TC003(int algId, int index, Hex *seed, char *pHex, char *qHex) { #ifndef HITLS_CRYPTO_DSA_GEN_PARA (void)algId; (void)index; (void)seed; (void)pHex; (void)qHex; SKIP_TEST(); #else BN_BigNum *p = NULL; BN_BigNum *q = NULL; ASSERT_EQ(BN_Hex2Bn(&p, pHex), CRYPT_SUCCESS); ASSERT_EQ(BN_Hex2Bn(&q, qHex), CRYPT_SUCCESS); DSA_FIPS186_4_Para fipsPara = {algId, index, 0, 0}; BSL_Buffer seedTmp = {seed->x, seed->len}; CRYPT_DSA_Para dsaPara = {p, q, NULL}; ASSERT_EQ(CryptDsaFips1864GenVerifiableG(&fipsPara, &seedTmp, &dsaPara), CRYPT_DSA_ERR_TRY_CNT); EXIT: BN_Destroy(p); BN_Destroy(q); BN_Destroy(dsaPara.g); #endif } /* END_CASE */ /* BEGIN_CASE */ void SDV_CRYPTO_DSA_GEN_G_FUNC_TC004(int algId, int index, Hex *seed, char *pHex, char *qHex, char *gHex) { #ifndef HITLS_CRYPTO_DSA_GEN_PARA (void)algId; (void)index; (void)seed; (void)pHex; (void)qHex; (void)gHex; SKIP_TEST(); #else BN_BigNum *p = NULL; BN_BigNum *q = NULL; BN_BigNum *gReq = NULL; ASSERT_EQ(BN_Hex2Bn(&p, pHex), CRYPT_SUCCESS); ASSERT_EQ(BN_Hex2Bn(&q, qHex), CRYPT_SUCCESS); ASSERT_EQ(BN_Hex2Bn(&gReq, gHex), CRYPT_SUCCESS); DSA_FIPS186_4_Para fipsPara = {algId, index, 0, 0}; BSL_Buffer seedTmp = {seed->x, seed->len}; CRYPT_DSA_Para dsaPara = {p, q, NULL}; ASSERT_EQ(CryptDsaFips1864GenVerifiableG(&fipsPara, &seedTmp, &dsaPara), CRYPT_SUCCESS); ASSERT_EQ(CryptDsaFips1864ValidateG(&fipsPara, &seedTmp, &dsaPara), CRYPT_SUCCESS); ASSERT_EQ(BN_Cmp(dsaPara.g, gReq), 0); EXIT: BN_Destroy(p); BN_Destroy(q); BN_Destroy(gReq); BN_Destroy(dsaPara.g); #endif } /* END_CASE */ /* BEGIN_CASE */ void SDV_CRYPTO_DSA_KEY_PAIR_GEN_BY_PARAM_FUNC_TC001(int flag, int gIndex) { #ifndef HITLS_CRYPTO_DSA_GEN_PARA (void)flag; (void)gIndex; SKIP_TEST(); #else int32_t algId = CRYPT_MD_SHA256; uint32_t L = 2048; uint32_t N = 256; uint32_t seedLen = 256; int32_t index = gIndex; BSL_Param params[6] = { {CRYPT_PARAM_DSA_ALGID, BSL_PARAM_TYPE_INT32, &algId, sizeof(int32_t), 0}, {CRYPT_PARAM_DSA_PBITS, BSL_PARAM_TYPE_UINT32, &L, sizeof(uint32_t), 0}, {CRYPT_PARAM_DSA_QBITS, BSL_PARAM_TYPE_UINT32, &N, sizeof(uint32_t), 0}, {CRYPT_PARAM_DSA_SEEDLEN, BSL_PARAM_TYPE_UINT32, &seedLen, sizeof(uint32_t), 0}, {CRYPT_PARAM_DSA_GINDEX, BSL_PARAM_TYPE_INT32, &index, sizeof(int32_t), 0}, BSL_PARAM_END }; CRYPT_EAL_PkeyCtx *pkey = NULL; uint8_t *sign = NULL; TestMemInit(); ASSERT_EQ(TestRandInit(), CRYPT_SUCCESS); #ifdef HITLS_CRYPTO_PROVIDER ASSERT_EQ(CRYPT_EAL_RandInit(CRYPT_RAND_SHA256, NULL, NULL, NULL, 0), CRYPT_SUCCESS); #endif pkey = CRYPT_EAL_PkeyNewCtx(CRYPT_PKEY_DSA); ASSERT_TRUE(pkey != NULL); ASSERT_EQ(CRYPT_EAL_PkeyGen(pkey), CRYPT_DSA_ERR_KEY_PARA); ASSERT_EQ(CRYPT_EAL_PkeyCtrl(pkey, CRYPT_CTRL_GEN_PARA, params, 0), CRYPT_SUCCESS); uint32_t genFlag = (uint8_t)flag; ASSERT_EQ(CRYPT_EAL_PkeyCtrl(pkey, CRYPT_CTRL_SET_GEN_FLAG, &genFlag, sizeof(genFlag)), CRYPT_SUCCESS); ASSERT_EQ(CRYPT_EAL_PkeyGen(pkey), CRYPT_SUCCESS); uint32_t signLen = CRYPT_EAL_PkeyGetSignLen(pkey); ASSERT_NE(signLen, 0); sign = (uint8_t *)BSL_SAL_Calloc(signLen, 1); ASSERT_TRUE(sign != NULL); uint8_t data[] = "testdata"; uint32_t dataLen = 8; ASSERT_EQ(CRYPT_EAL_PkeySign(pkey, CRYPT_MD_SHA256, data, dataLen, sign, &signLen), CRYPT_SUCCESS); ASSERT_EQ(CRYPT_EAL_PkeyVerify(pkey, CRYPT_MD_SHA256, data, dataLen, sign, signLen), CRYPT_SUCCESS); EXIT: CRYPT_EAL_RandDeinit(); CRYPT_EAL_PkeyFreeCtx(pkey); BSL_SAL_Free(sign); #endif } /* END_CASE */ /** * @test SDV_CRYPTO_DSA_CHECK_KEYPAIR_TC001 * @brief * Create a dsa key pairs to check the key pair consistency. */ /* BEGIN_CASE */ void SDV_CRYPTO_DSA_CHECK_KEYPAIR_TC001(Hex *p, Hex *g, Hex *q, int isProvider) { #if !defined(HITLS_CRYPTO_DSA_CHECK) (void)p; (void)g; (void)q; (void)isProvider; SKIP_TEST(); #else CRYPT_EAL_PkeyPara para = {0}; Set_DSA_Para(&para, NULL, NULL, p, q, g, NULL, NULL); TestMemInit(); CRYPT_EAL_PkeyCtx *pkey = TestPkeyNewCtx(NULL, CRYPT_PKEY_DSA, CRYPT_EAL_PKEY_KEYMGMT_OPERATE, "provider=default", isProvider); ASSERT_TRUE(pkey != NULL); ASSERT_EQ(TestRandInit(), CRYPT_SUCCESS); ASSERT_TRUE(CRYPT_EAL_PkeySetPara(pkey, &para) == CRYPT_SUCCESS); ASSERT_TRUE(CRYPT_EAL_PkeyGen(pkey) == CRYPT_SUCCESS); ASSERT_TRUE(CRYPT_EAL_PkeyPairCheck(pkey, pkey) == CRYPT_SUCCESS); EXIT: TestRandDeInit(); CRYPT_EAL_PkeyFreeCtx(pkey); #endif } /* END_CASE */ /** * @test SDV_CRYPTO_DSA_CHECK_KEYPAIR_INVALIED_TC001 * @brief * Create a dsa key pairs to check the key pair consistency. */ /* BEGIN_CASE */ void SDV_CRYPTO_DSA_CHECK_KEYPAIR_INVALIED_TC001(Hex *p, Hex *g, Hex *q, int isProvider) { #if !defined(HITLS_CRYPTO_DSA_CHECK) (void)p; (void)g; (void)q; (void)isProvider; SKIP_TEST(); #else TestMemInit(); uint8_t pubKey[1030]; uint32_t pubKeyLen = sizeof(pubKey); uint8_t prvKey[1030]; uint32_t prvKeyLen = sizeof(prvKey); CRYPT_EAL_PkeyPub pub = {0}; CRYPT_EAL_PkeyPrv prv = {0}; Set_DSA_Pub(&pub, pubKey, pubKeyLen); Set_DSA_Prv(&prv, prvKey, prvKeyLen); CRYPT_EAL_PkeyPara para = {0}; Set_DSA_Para(&para, NULL, NULL, p, q, g, NULL, NULL); CRYPT_EAL_PkeyCtx *pkey = TestPkeyNewCtx(NULL, CRYPT_PKEY_DSA, CRYPT_EAL_PKEY_KEYMGMT_OPERATE, "provider=default", isProvider); CRYPT_EAL_PkeyCtx *pubCtx = TestPkeyNewCtx(NULL, CRYPT_PKEY_DSA, CRYPT_EAL_PKEY_KEYMGMT_OPERATE, "provider=default", isProvider); CRYPT_EAL_PkeyCtx *prvCtx = TestPkeyNewCtx(NULL, CRYPT_PKEY_DSA, CRYPT_EAL_PKEY_KEYMGMT_OPERATE, "provider=default", isProvider); ASSERT_TRUE(pkey != NULL); ASSERT_TRUE(prvCtx != NULL); ASSERT_TRUE(pubCtx != NULL); ASSERT_EQ(TestRandInit(), CRYPT_SUCCESS); ASSERT_TRUE(CRYPT_EAL_PkeySetPara(pkey, &para) == CRYPT_SUCCESS); ASSERT_TRUE(CRYPT_EAL_PkeySetPara(pubCtx, &para) == CRYPT_SUCCESS); ASSERT_TRUE(CRYPT_EAL_PkeySetPara(prvCtx, &para) == CRYPT_SUCCESS); ASSERT_TRUE(CRYPT_EAL_PkeyGen(pkey) == CRYPT_SUCCESS); // get prv and pub ASSERT_TRUE(CRYPT_EAL_PkeyGetPub(pkey, &pub) == CRYPT_SUCCESS); ASSERT_TRUE(CRYPT_EAL_PkeyGetPrv(pkey, &prv) == CRYPT_SUCCESS); ASSERT_TRUE(CRYPT_EAL_PkeyPairCheck(NULL, NULL) == CRYPT_NULL_INPUT); ASSERT_TRUE(CRYPT_EAL_PkeySetPub(pubCtx, &pub) == CRYPT_SUCCESS); ASSERT_TRUE(CRYPT_EAL_PkeyPairCheck(pubCtx, prvCtx) == CRYPT_NULL_INPUT); // no prv key ASSERT_TRUE(CRYPT_EAL_PkeySetPrv(prvCtx, &prv) == CRYPT_SUCCESS); ASSERT_TRUE(CRYPT_EAL_PkeyPairCheck(pubCtx, prvCtx) == CRYPT_SUCCESS); ASSERT_TRUE(CRYPT_EAL_PkeyGen(pubCtx) == CRYPT_SUCCESS); ASSERT_TRUE(CRYPT_EAL_PkeyPairCheck(pubCtx, prvCtx) == CRYPT_DSA_PAIRWISE_CHECK_FAIL); EXIT: TestRandDeInit(); CRYPT_EAL_PkeyFreeCtx(pkey); CRYPT_EAL_PkeyFreeCtx(pubCtx); CRYPT_EAL_PkeyFreeCtx(prvCtx); #endif } /* END_CASE */ /** * @test SDV_CRYPTO_DSA_CHECK_PRV_TC001 * @brief * Create a dsa key pairs to check the prv key. */ /* BEGIN_CASE */ void SDV_CRYPTO_DSA_CHECK_PRV_TC001(Hex *p, Hex *g, Hex *q, int isProvider) { #if !defined(HITLS_CRYPTO_DSA_CHECK) (void)p; (void)g; (void)q; (void)isProvider; SKIP_TEST(); #else TestMemInit(); int32_t bits; CRYPT_EAL_PkeyPara para = {0}; Set_DSA_Para(&para, NULL, NULL, p, q, g, NULL, NULL); BN_BigNum *x = NULL; CRYPT_DSA_Ctx *ctx = NULL; BN_BigNum *maxValue = NULL; CRYPT_EAL_PkeyCtx *pkey = TestPkeyNewCtx(NULL, CRYPT_PKEY_DSA, CRYPT_EAL_PKEY_KEYMGMT_OPERATE, "provider=default", isProvider); ASSERT_TRUE(pkey != NULL); ASSERT_EQ(TestRandInit(), CRYPT_SUCCESS); ASSERT_TRUE(CRYPT_EAL_PkeySetPara(pkey, &para) == CRYPT_SUCCESS); ASSERT_EQ(CRYPT_EAL_PkeyPrvCheck(NULL), CRYPT_NULL_INPUT); ASSERT_EQ(CRYPT_EAL_PkeyPrvCheck(pkey), CRYPT_NULL_INPUT); ASSERT_TRUE(CRYPT_EAL_PkeyGen(pkey) == CRYPT_SUCCESS); // get prv and pub ASSERT_EQ(CRYPT_EAL_PkeyPrvCheck(pkey), CRYPT_SUCCESS); ctx = (CRYPT_DSA_Ctx *)pkey->key; x = ctx->x; if (q->len != 0) { ctx->x = ctx->para->q; ASSERT_EQ(CRYPT_EAL_PkeyPrvCheck(pkey), CRYPT_DSA_INVALID_PRVKEY); } else { maxValue = BN_Create(0); bits = BN_Bits(ctx->para->p); ASSERT_EQ(BN_SetLimb(maxValue, 1), CRYPT_SUCCESS); BN_Lshift(maxValue, maxValue, bits); ctx->x = maxValue; ASSERT_EQ(CRYPT_EAL_PkeyPrvCheck(pkey), CRYPT_DSA_INVALID_PRVKEY); } ctx->x = x; EXIT: BN_Destroy(maxValue); TestRandDeInit(); CRYPT_EAL_PkeyFreeCtx(pkey); #endif } /* END_CASE */
2301_79861745/bench_create
testcode/sdv/testcase/crypto/dsa/test_suite_sdv_eal_dsa.c
C
unknown
42,695
/* * This file is part of the openHiTLS project. * * openHiTLS is licensed under the Mulan PSL v2. * You can use this software according to the terms and conditions of the Mulan PSL v2. * You may obtain a copy of Mulan PSL v2 at: * * http://license.coscl.org.cn/MulanPSL2 * * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, * EITHER EXPRESS 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 "bsl_sal.h" #include "crypt_errno.h" #include "eal_md_local.h" #include "eal_pkey_local.h" #include "crypt_eal_md.h" #include "crypt_eal_mac.h" #include "crypt_dsa.h" #include "crypt_eal_cipher.h" #include "crypt_eal_pkey.h" #include "eal_cipher_local.h" #include "modes_local.h" #include "eal_common.h" static bool IsMacAlgIdValid(int id) { int algList[] = { CRYPT_MAC_HMAC_MD5, CRYPT_MAC_HMAC_SHA1, CRYPT_MAC_HMAC_SHA224, CRYPT_MAC_HMAC_SHA256, CRYPT_MAC_HMAC_SHA384, CRYPT_MAC_HMAC_SHA512, CRYPT_MAC_HMAC_SHA3_224, CRYPT_MAC_HMAC_SHA3_256, CRYPT_MAC_HMAC_SHA3_384, CRYPT_MAC_HMAC_SHA3_512, CRYPT_MAC_HMAC_SM3, CRYPT_MAC_CMAC_AES128, CRYPT_MAC_CMAC_AES192, CRYPT_MAC_CMAC_AES256, CRYPT_MAC_GMAC_AES128, CRYPT_MAC_GMAC_AES192, CRYPT_MAC_GMAC_AES256, CRYPT_MAC_SIPHASH64, CRYPT_MAC_SIPHASH128 }; int algIdCnt = sizeof(algList) / sizeof(int); for (int i = 0; i < algIdCnt; i++) { if (id == algList[i]) { return true; } } return false; } static bool IsCipherAlgIdValid(int id) { int algList[] = { CRYPT_CIPHER_AES128_CBC, CRYPT_CIPHER_AES192_CBC, CRYPT_CIPHER_AES256_CBC, CRYPT_CIPHER_AES128_CTR, CRYPT_CIPHER_AES192_CTR, CRYPT_CIPHER_AES256_CTR, CRYPT_CIPHER_AES128_ECB, CRYPT_CIPHER_AES192_ECB, CRYPT_CIPHER_AES256_ECB, CRYPT_CIPHER_AES128_XTS, CRYPT_CIPHER_AES256_XTS, CRYPT_CIPHER_AES128_CCM, CRYPT_CIPHER_AES192_CCM, CRYPT_CIPHER_AES256_CCM, CRYPT_CIPHER_AES128_GCM, CRYPT_CIPHER_AES192_GCM, CRYPT_CIPHER_AES256_GCM, CRYPT_CIPHER_AES128_CFB, CRYPT_CIPHER_AES192_CFB, CRYPT_CIPHER_AES256_CFB, CRYPT_CIPHER_AES128_OFB, CRYPT_CIPHER_AES192_OFB, CRYPT_CIPHER_AES256_OFB, CRYPT_CIPHER_CHACHA20_POLY1305, CRYPT_CIPHER_SM4_XTS, CRYPT_CIPHER_SM4_CBC, CRYPT_CIPHER_SM4_ECB, CRYPT_CIPHER_SM4_CTR, CRYPT_CIPHER_SM4_GCM, CRYPT_CIPHER_SM4_CFB, CRYPT_CIPHER_SM4_OFB, }; int algIdCnt = sizeof(algList) / sizeof(int); for (int i = 0; i < algIdCnt; i++) { if (id == algList[i]) { return true; } } return false; } static bool IsPkeyAlgIdValid(int id) { int algList[] = { CRYPT_PKEY_DSA, CRYPT_PKEY_ED25519, CRYPT_PKEY_X25519, CRYPT_PKEY_RSA, CRYPT_PKEY_DH, CRYPT_PKEY_ECDSA, CRYPT_PKEY_ECDH, CRYPT_PKEY_SM2 }; int algIdCnt = sizeof(algList) / sizeof(int); for (int i = 0; i < algIdCnt; i++) { if (id == algList[i]) { return true; } } return false; } #define MD_OUTPUT_MAXSIZE 128 static int32_t MdTest(CRYPT_EAL_MdCTX *ctx, Hex *msg, Hex *hash) { (void)msg; (void)hash; uint8_t output[MD_OUTPUT_MAXSIZE]; uint32_t outLen = MD_OUTPUT_MAXSIZE; ASSERT_EQ(CRYPT_EAL_MdInit(ctx), CRYPT_SUCCESS); ASSERT_EQ(CRYPT_EAL_MdUpdate(ctx, msg->x, msg->len), CRYPT_SUCCESS); ASSERT_EQ(CRYPT_EAL_MdFinal(ctx, output, &outLen), CRYPT_SUCCESS); if (ctx->id != CRYPT_MD_SHAKE128 && ctx->id != CRYPT_MD_SHAKE256) { ASSERT_TRUE(outLen == hash->len); } ASSERT_EQ(memcmp(output, hash->x, hash->len), 0); return 0; EXIT: return -1; } /* END_HEADER */ /** * @test SDV_CRYPTO_MAC_ALG_CHECK_TC001 * @title Check the validity of the mac algorithm ID. * @precon nan * @brief * 1. Call the CRYPT_EAL_MacIsValidAlgId method, compare the returned value with 'isValid', expected result 1 * @expect * 1. Both are the same. */ /* BEGIN_CASE */ void SDV_CRYPTO_MAC_ALG_CHECK_TC001(int algId) { int isValid = IsMacAlgIdValid(algId); ASSERT_TRUE(CRYPT_EAL_MacIsValidAlgId(algId) == isValid); EXIT: return; } /* END_CASE */ /** * @test SDV_CRYPTO_CIPHER_ALG_CHECK_TC001 * @title Check the validity of the symmetric algorithm ID. * @precon nan * @brief * 1. Call the CRYPT_EAL_CipherIsValidAlgId method, compare the returned value with 'isValid', expected result 1 * @expect * 1. Both are the same. */ /* BEGIN_CASE */ void SDV_CRYPTO_CIPHER_ALG_CHECK_TC001(int algId) { int isValid = IsCipherAlgIdValid(algId); ASSERT_TRUE(CRYPT_EAL_CipherIsValidAlgId(algId) == isValid); EXIT: return; } /* END_CASE */ /** * @test SDV_CRYPTO_MD_COPY_FUNC_TC001 * @title CRYPT_EAL_MdCopyCtx function test. * @precon nan * @brief * 1. Create the context ctx of md algorithm, expected result 1 * 2. Calculate the hash of msg, and compare the calculated result with hash vector, expected result 2 * 3. Call to CRYPT_EAL_MdCopyCtx method to copy ctx, expected result 3 * 4. Calculate the hash of msg, and compare the calculated result with hash vector, expected result 4 * @expect * 1. Success, the context is not null. * 2. Success, the hashs are the same. * 3. CRYPT_SUCCESS * 4. Success, the hashs are the same. */ /* BEGIN_CASE */ void SDV_CRYPTO_MD_COPY_FUNC_TC001(int id, Hex *msg, Hex *hash) { TestMemInit(); CRYPT_EAL_MdCTX *cpyCtx = NULL; CRYPT_EAL_MdCTX *ctx = CRYPT_EAL_MdNewCtx(id); ASSERT_TRUE(ctx != NULL); ASSERT_EQ(MdTest(ctx, msg, hash), 0); cpyCtx = CRYPT_EAL_MdNewCtx(id); ASSERT_TRUE(cpyCtx != NULL); ASSERT_EQ(CRYPT_EAL_MdCopyCtx(cpyCtx, ctx), CRYPT_SUCCESS); ASSERT_EQ(MdTest(cpyCtx, msg, hash), 0); EXIT: CRYPT_EAL_MdFreeCtx(ctx); CRYPT_EAL_MdFreeCtx(cpyCtx); } /* END_CASE */ /** * @test SDV_CRYPTO_EAL_PKEY_NEW_CTX_API_TC001 * @title CRYPT_EAL_PkeyNewCtx test. * @precon nan * @brief * 1. Call the CRYPT_EAL_PkeyNewCtx method, algId is CRYPT_PKEY_MAX, expected result 1 * @expect * 1. Return null. */ /* BEGIN_CASE */ void SDV_CRYPTO_EAL_PKEY_NEW_CTX_API_TC001(void) { CRYPT_EAL_PkeyCtx *pkey = CRYPT_EAL_PkeyNewCtx(CRYPT_PKEY_MAX); ASSERT_TRUE(pkey == NULL); EXIT: return; } /* END_CASE */ /** * @test SDV_CRYPTO_EAL_PKEY_FREE_CTX_API_TC001 * @title CRYPT_EAL_PkeyFreeCtx test. * @precon nan * @brief * 1. Call the CRYPT_EAL_PkeyFreeCtx method, ctx is null, expected result 1 * @expect * 1. No memory leakage occurs. */ /* BEGIN_CASE */ void SDV_CRYPTO_EAL_PKEY_FREE_CTX_API_TC001(void) { CRYPT_EAL_PkeyFreeCtx(NULL); } /* END_CASE */ /** * @test SDV_CRYPTO_EAL_PKEY_SET_PARA_API_TC001 * @title Check the validity of the asymmetric algorithm ID. * @precon nan * @brief * 1. Call the CRYPT_EAL_PkeySetPara method: * (1) pkey = NULL, expected result 1 * (2) para = NULL, expected result 1 * (3) pkey.id != para.id, expected result 2 * @expect * 1. CRYPT_NULL_INPUT. * 2. CRYPT_EAL_ERR_ALGID. */ /* BEGIN_CASE */ void SDV_CRYPTO_EAL_PKEY_SET_PARA_API_TC001(void) { CRYPT_EAL_PkeyPara para = {0}; CRYPT_EAL_PkeyCtx *pkey = CRYPT_EAL_PkeyNewCtx(CRYPT_PKEY_DSA); ASSERT_TRUE(pkey != NULL); ASSERT_TRUE(CRYPT_EAL_PkeySetPara(NULL, &para) == CRYPT_NULL_INPUT); ASSERT_TRUE(CRYPT_EAL_PkeySetPara(pkey, NULL) == CRYPT_NULL_INPUT); para.id = CRYPT_PKEY_RSA; ASSERT_TRUE(CRYPT_EAL_PkeySetPara(pkey, &para) == CRYPT_EAL_ERR_ALGID); EXIT: CRYPT_EAL_PkeyFreeCtx(pkey); } /* END_CASE */ /** * @test SDV_CRYPTO_EAL_PKEY_ALG_CHECK_TC001 * @title Check the validity of the asymmetric algorithm ID. * @precon nan * @brief * 1. Call the CRYPT_EAL_PkeyIsValidAlgId method, compare the returned value with 'isValid', expected result 1 * @expect * 1. Both are the same. */ /* BEGIN_CASE */ void SDV_CRYPTO_EAL_PKEY_ALG_CHECK_TC001(int algId) { int isValid = IsPkeyAlgIdValid(algId); ASSERT_TRUE(CRYPT_EAL_PkeyIsValidAlgId(algId) == isValid); EXIT: return; } /* END_CASE */ /** * @test SDV_CRYPTO_EAL_PKEY_SET_PRV_API_TC001 * @title CRYPT_EAL_PkeySetPrv bad arguments. * @precon nan * @brief * 1. Call the CRYPT_EAL_PkeySetPrv: * (1) pkey=NULL, expected result 1 * (2) prv=NULL, expected result 1 * (3) pkey.id != prv.id, expected result 2 * @expect * 1. CRYPT_NULL_INPUT * 2. CRYPT_EAL_ERR_ALGID */ /* BEGIN_CASE */ void SDV_CRYPTO_EAL_PKEY_SET_PRV_API_TC001(void) { CRYPT_EAL_PkeyCtx *pkey = NULL; CRYPT_EAL_PkeyPrv prv = {0}; pkey = CRYPT_EAL_PkeyNewCtx(CRYPT_PKEY_RSA); ASSERT_TRUE(pkey != NULL); ASSERT_EQ(CRYPT_EAL_PkeySetPrv(NULL, &prv), CRYPT_NULL_INPUT); ASSERT_EQ(CRYPT_EAL_PkeySetPrv(pkey, NULL), CRYPT_NULL_INPUT); prv.id = CRYPT_PKEY_DSA; ASSERT_EQ(CRYPT_EAL_PkeySetPrv(pkey, &prv), CRYPT_EAL_ERR_ALGID); EXIT: CRYPT_EAL_PkeyFreeCtx(pkey); } /* END_CASE */ /** * @test SDV_CRYPTO_EAL_PKEY_SET_PUB_API_TC001 * @title CRYPT_EAL_PkeySetPub bad arguments. * @precon nan * @brief * 1. Call the CRYPT_EAL_PkeySetPub: * (1) pkey=NULL, expected result 1 * (2) prv=NULL, expected result 1 * (3) pkey.id != prv.id, expected result 2 * @expect * 1. CRYPT_NULL_INPUT * 2. CRYPT_EAL_ERR_ALGID */ /* BEGIN_CASE */ void SDV_CRYPTO_EAL_PKEY_SET_PUB_API_TC001(void) { CRYPT_EAL_PkeyCtx *pkey = NULL; CRYPT_EAL_PkeyPub pub = {0}; pkey = CRYPT_EAL_PkeyNewCtx(CRYPT_PKEY_RSA); ASSERT_TRUE(pkey != NULL); ASSERT_EQ(CRYPT_EAL_PkeySetPub(NULL, &pub), CRYPT_NULL_INPUT); ASSERT_EQ(CRYPT_EAL_PkeySetPub(pkey, NULL), CRYPT_NULL_INPUT); pub.id = CRYPT_PKEY_DSA; ASSERT_EQ(CRYPT_EAL_PkeySetPub(pkey, &pub), CRYPT_EAL_ERR_ALGID); EXIT: CRYPT_EAL_PkeyFreeCtx(pkey); } /* END_CASE */ /** * @test SDV_CRYPTO_EAL_PKEY_GEN_API_TC001 * @title CRYPT_EAL_PkeyGen bad arguments. * @precon nan * @brief * 1. Call the CRYPT_EAL_PkeySetPub: peky = NULL, expected result 1 * @expect * 1. CRYPT_NULL_INPUT */ /* BEGIN_CASE */ void SDV_CRYPTO_EAL_PKEY_GEN_API_TC001(void) { ASSERT_EQ(CRYPT_EAL_PkeyGen(NULL), CRYPT_NULL_INPUT); EXIT: return; } /* END_CASE */ /** * @test SDV_CRYPTO_EAL_PKEY_CMP_TC001 * @title CRYPT_EAL_PkeyCmp Test. * @precon nan * @brief * 1. Call the CRYPT_EAL_PkeyCmp, ctx1=NULL, ctx2=NULL, expected result 1 * 2. Call the CRYPT_EAL_PkeyCmp, ctx1=NULL, ctx2!=NULL or ctx1=NULL, ctx2!=NULL, expected result 2 * 3. Call the CRYPT_EAL_PkeyCmp, ctx1!=NULL, ctx2!=NULL, the content in ctx1 and ctx2 is empty, expected result 2 * 4. Call the CRYPT_EAL_PkeyCmp, ctx1!=NULL, ctx2!=NULL, ctx1.id!=ctx2.id, expected result 3 * 5. Call the CRYPT_EAL_PkeyCmp, ctx1->pkey=NULL, expected result 2 * @expect * 1. CRYPT_SUCCESS * 2. CRYPT_NULL_INPUT * 3. CRYPT_EAL_PKEY_CMP_DIFF_KEY_TYPE */ /* BEGIN_CASE */ void SDV_CRYPTO_EAL_PKEY_CMP_TC001(void) { CRYPT_EAL_PkeyCtx ctx1 = {0}; CRYPT_EAL_PkeyCtx ctx2 = {0}; CRYPT_EAL_PkeyCtx *pkey = NULL; ASSERT_EQ(CRYPT_EAL_PkeyCmp(NULL, NULL), CRYPT_SUCCESS); ASSERT_EQ(CRYPT_EAL_PkeyCmp(NULL, &ctx2), CRYPT_NULL_INPUT); ASSERT_EQ(CRYPT_EAL_PkeyCmp(&ctx1, NULL), CRYPT_NULL_INPUT); ASSERT_EQ(CRYPT_EAL_PkeyCmp(&ctx1, &ctx2), CRYPT_NULL_INPUT); ctx1.id = CRYPT_PKEY_DH; ctx2.id = CRYPT_PKEY_DSA; ASSERT_EQ(CRYPT_EAL_PkeyCmp(&ctx1, &ctx2), CRYPT_EAL_PKEY_CMP_DIFF_KEY_TYPE); ctx2.id = CRYPT_PKEY_DH; pkey = CRYPT_EAL_PkeyNewCtx(CRYPT_PKEY_DH); ASSERT_TRUE(pkey != NULL); ASSERT_TRUE(pkey->method != NULL); ctx1.method = pkey->method; ctx2.method = pkey->method; ASSERT_EQ(CRYPT_EAL_PkeyCmp(&ctx1, &ctx2), CRYPT_NULL_INPUT); EXIT: CRYPT_EAL_PkeyFreeCtx(pkey); } /* END_CASE */ /** * @test SDV_CRYPTO_EAL_PKEY_GET_ID_API_TC001 * @title CRYPT_EAL_PkeyGetId Test. * @precon nan * @brief * 1. Create the context(ctx) of pkeyId, expected result 1 * 2. Call the CRYPT_EAL_PkeyGetId to get id of ctx, expected result 2 * 3. Call the CRYPT_EAL_PkeyGetId to get id of NULL, expected result 3 * @expect * 1. Success, and context is not NULL. * 2. The getted id and pkeyId are the same. * 3. Get id: CRYPT_PKEY_MAX */ /* BEGIN_CASE */ void SDV_CRYPTO_EAL_PKEY_GET_ID_API_TC001(void) { int pkeyId = CRYPT_PKEY_DSA; CRYPT_EAL_PkeyCtx *ctx = CRYPT_EAL_PkeyNewCtx(pkeyId); ASSERT_TRUE(ctx != NULL); ASSERT_EQ(CRYPT_EAL_PkeyGetId(ctx), pkeyId); ASSERT_EQ(CRYPT_EAL_PkeyGetId(NULL), CRYPT_PKEY_MAX); EXIT: CRYPT_EAL_PkeyFreeCtx(ctx); } /* END_CASE */ /** * @test SDV_CRYPTO_EAL_PKEY_EXT_DATA_API_TC001 * @title CRYPT_EAL_PkeySetExtData/CRYPT_EAL_PkeyGetExtData Test. * @precon nan * @brief * 1. Create the context(ctx) of pkeyId, expected result 1 * 2. Call the CRYPT_EAL_PkeySetExtData to set ext data, ctx is null, expected result 2 * 3. Call the CRYPT_EAL_PkeySetExtData to set ext data, all parameters are valid, expected result 3 * 4. Call the CRYPT_EAL_PkeyGetExtData to get ext data, ctx is null, expected result 4 * 5. Call the CRYPT_EAL_PkeyGetExtData to get ext data, all parameters are valid, expected result 5 * @expect * 1. Success, and context is not NULL. * 2. CRYPT_NULL_INPUT * 3. CRYPT_SUCCESS * 4. Return null. * 5. The returned value is not null and the value is correct. */ /* BEGIN_CASE */ void SDV_CRYPTO_EAL_PKEY_EXT_DATA_API_TC001(void) { int pkeyId = CRYPT_PKEY_DSA; int data = 1; void *ptr = NULL; CRYPT_EAL_PkeyCtx *ctx = CRYPT_EAL_PkeyNewCtx(pkeyId); ASSERT_TRUE(ctx != NULL); ASSERT_EQ(CRYPT_EAL_PkeySetExtData(NULL, &data), CRYPT_NULL_INPUT); ASSERT_EQ(CRYPT_EAL_PkeySetExtData(ctx, &data), CRYPT_SUCCESS); ASSERT_TRUE(CRYPT_EAL_PkeyGetExtData(NULL) == NULL); ptr = CRYPT_EAL_PkeyGetExtData(ctx); ASSERT_TRUE(ptr != NULL); ASSERT_EQ(*(int *)ptr, data); EXIT: CRYPT_EAL_PkeyFreeCtx(ctx); } /* END_CASE */ /** * @test SDV_CRYPTO_EAL_REINIT_TC001 */ /* BEGIN_CASE */ void SDV_CRYPTO_EAL_REINIT_TC001(int id) { uint8_t key[16] = {0}; uint32_t keyLen = 16; uint8_t iv[16] = {0}; uint32_t ivLen = 16; uint8_t in[15] = {0}; uint32_t inLen = 15; uint8_t out[64] = {0}; uint32_t outLen = 64; CRYPT_EAL_CipherCtx *ctx = CRYPT_EAL_CipherNewCtx((CRYPT_CIPHER_AlgId)id); ASSERT_TRUE(ctx != NULL); ASSERT_EQ(CRYPT_EAL_CipherInit(ctx, key, keyLen, iv, ivLen, true), CRYPT_SUCCESS); (void)CRYPT_EAL_CipherSetPadding(ctx, CRYPT_PADDING_PKCS7); ASSERT_EQ(CRYPT_EAL_CipherUpdate(ctx, in, inLen, out, &outLen), CRYPT_SUCCESS); ASSERT_EQ(CRYPT_EAL_CipherReinit(ctx, iv, ivLen), CRYPT_SUCCESS); struct ModesCipherCtx *ciphCtx = ((struct CryptEalCipherCtx *)ctx)->ctx; ASSERT_TRUE(ciphCtx != NULL); // Check data dataLen ASSERT_EQ(ciphCtx->dataLen, 0); for (uint32_t i = 0; i < EAL_MAX_BLOCK_LENGTH; i++) { ASSERT_EQ(ciphCtx->data[i], 0); } EXIT: CRYPT_EAL_CipherDeinit(ctx); CRYPT_EAL_CipherFreeCtx(ctx); } /* END_CASE */ /** * @test SDV_CRYPTO_EAL_REINIT_TC002 */ /* BEGIN_CASE */ void SDV_CRYPTO_EAL_REINIT_TC002(int id) { uint8_t key[32] = {0}; uint32_t keyLen = 32; uint8_t iv[12] = {0}; uint32_t ivLen = 12; uint8_t in[15] = {0}; uint32_t inLen = 15; uint8_t out[64] = {0}; uint32_t outLen = 64; CRYPT_EAL_CipherCtx *ctx = CRYPT_EAL_CipherNewCtx((CRYPT_CIPHER_AlgId)id); ASSERT_TRUE(ctx != NULL); ASSERT_EQ(CRYPT_EAL_CipherInit(ctx, key, keyLen, iv, ivLen, true), CRYPT_SUCCESS); ASSERT_EQ(CRYPT_EAL_CipherUpdate(ctx, in, inLen, out, &outLen), CRYPT_SUCCESS); ASSERT_EQ(CRYPT_EAL_CipherReinit(ctx, iv, ivLen), CRYPT_SUCCESS); struct ModesChaChaCtx *ciphCtx = ((struct CryptEalCipherCtx *)ctx)->ctx; ASSERT_TRUE(ciphCtx != NULL); // Check data dataLen ASSERT_EQ(ciphCtx->chachaCtx.polyCtx.lastLen, 0); uint32_t lastSize = (uint32_t)sizeof(ciphCtx->chachaCtx.polyCtx.last); for (uint32_t i = 0; i < lastSize; i++) { ASSERT_EQ(ciphCtx->chachaCtx.polyCtx.last[i], 0); } // Check aadLen cipherTextLen ASSERT_EQ(ciphCtx->chachaCtx.aadLen, 0); ASSERT_EQ(ciphCtx->chachaCtx.cipherTextLen, 0); EXIT: CRYPT_EAL_CipherDeinit(ctx); CRYPT_EAL_CipherFreeCtx(ctx); } /* END_CASE */ /** * @test SDV_CRYPTO_EAL_REINIT_TC003 */ /* BEGIN_CASE */ void SDV_CRYPTO_EAL_REINIT_TC003(int id) { uint8_t key[16] = {0}; uint32_t keyLen = 16; uint8_t iv[12] = {0}; uint32_t ivLen = 12; uint8_t in[15] = {0}; uint32_t inLen = 15; uint8_t out[64] = {0}; uint32_t outLen = 64; CRYPT_EAL_CipherCtx *ctx = CRYPT_EAL_CipherNewCtx((CRYPT_CIPHER_AlgId)id); ASSERT_TRUE(ctx != NULL); ASSERT_EQ(CRYPT_EAL_CipherInit(ctx, key, keyLen, iv, ivLen, true), CRYPT_SUCCESS); ASSERT_EQ(CRYPT_EAL_CipherUpdate(ctx, in, inLen, out, &outLen), CRYPT_SUCCESS); ASSERT_EQ(CRYPT_EAL_CipherReinit(ctx, iv, ivLen), CRYPT_SUCCESS); struct ModesGcmCtx *ciphCtx = ((struct CryptEalCipherCtx *)ctx)->ctx; ASSERT_TRUE(ciphCtx != NULL); // Check data dataLen ASSERT_EQ(ciphCtx->gcmCtx.aadLen, 0); ASSERT_EQ(ciphCtx->gcmCtx.lastLen, 0); ASSERT_EQ(ciphCtx->gcmCtx.plaintextLen, 0); for (uint32_t i = 0; i < GCM_BLOCKSIZE; i++) { ASSERT_EQ(ciphCtx->gcmCtx.ghash[i], 0); } EXIT: CRYPT_EAL_CipherDeinit(ctx); CRYPT_EAL_CipherFreeCtx(ctx); } /* END_CASE */ /** * @test SDV_CRYPTO_EAL_GET_KEY_LEN_TC001 */ /* BEGIN_CASE */ void SDV_CRYPTO_EAL_GET_KEY_LEN_TC001(int algid, int paramId, int pubLen, int prvLen, int sharedLen) { CRYPT_EAL_PkeyCtx *ctx = CRYPT_EAL_PkeyNewCtx(algid); ASSERT_TRUE(ctx != NULL); int32_t ret; if (paramId != 0) { ret = CRYPT_EAL_PkeySetParaById(ctx, paramId); ASSERT_EQ(ret, CRYPT_SUCCESS); } uint32_t val = 0; ret = CRYPT_EAL_PkeyCtrl(ctx, CRYPT_CTRL_GET_PUBKEY_LEN, &val, sizeof(val)); ASSERT_EQ(ret, CRYPT_SUCCESS); ASSERT_EQ(val, pubLen); ret = CRYPT_EAL_PkeyCtrl(ctx, CRYPT_CTRL_GET_PRVKEY_LEN, &val, sizeof(val)); ASSERT_EQ(ret, CRYPT_SUCCESS); ASSERT_EQ(val, prvLen); ret = CRYPT_EAL_PkeyCtrl(ctx, CRYPT_CTRL_GET_SHARED_KEY_LEN, &val, sizeof(val)); ASSERT_EQ(ret, CRYPT_SUCCESS); ASSERT_EQ(val, sharedLen); EXIT: CRYPT_EAL_PkeyFreeCtx(ctx); } /* END_CASE */ /** * @test SDV_CRYPTO_EAL_GET_KEY_LEN_TC002 */ /* BEGIN_CASE */ void SDV_CRYPTO_EAL_GET_KEY_LEN_TC002(int algid, int paramId, int pubLen, int prvLen) { CRYPT_EAL_PkeyCtx *ctx = CRYPT_EAL_PkeyNewCtx(algid); ASSERT_TRUE(ctx != NULL); int32_t ret; if (paramId != 0) { ret = CRYPT_EAL_PkeySetParaById(ctx, paramId); ASSERT_EQ(ret, CRYPT_SUCCESS); } uint32_t val = 0; ret = CRYPT_EAL_PkeyCtrl(ctx, CRYPT_CTRL_GET_PUBKEY_LEN, &val, sizeof(val)); ASSERT_EQ(ret, CRYPT_SUCCESS); ASSERT_EQ(val, pubLen); ret = CRYPT_EAL_PkeyCtrl(ctx, CRYPT_CTRL_GET_PRVKEY_LEN, &val, sizeof(val)); ASSERT_EQ(ret, CRYPT_SUCCESS); ASSERT_EQ(val, prvLen); EXIT: CRYPT_EAL_PkeyFreeCtx(ctx); } /* END_CASE */ /** * @test SDV_CRYPTO_EAL_GET_KEY_LEN_TC003_1 */ /* BEGIN_CASE */ void SDV_CRYPTO_EAL_GET_KEY_LEN_TC003_1(int algid, int rsaBits, Hex *p, Hex *q, Hex *g) { TestRandInit(); CRYPT_EAL_PkeyCtx *ctx = CRYPT_EAL_PkeyNewCtx(algid); ASSERT_TRUE(ctx != NULL); int32_t ret; CRYPT_EAL_PkeyPara para = {0}; uint8_t e[3] = {1, 0, 1}; if (algid == CRYPT_PKEY_RSA) { para.id = CRYPT_PKEY_RSA; para.para.rsaPara.e = e; para.para.rsaPara.eLen = 3; para.para.rsaPara.bits = rsaBits; } else { para.id = algid; // DH or DSA para.para.dhPara.p = p->x; para.para.dhPara.q = q->x; para.para.dhPara.g = g->x; para.para.dhPara.pLen = p->len; para.para.dhPara.qLen = q->len; para.para.dhPara.gLen = g->len; } ASSERT_EQ(CRYPT_EAL_PkeySetPara(ctx, &para), CRYPT_SUCCESS); ASSERT_EQ(CRYPT_EAL_PkeyGen(ctx), CRYPT_SUCCESS); uint32_t val = 0; ret = CRYPT_EAL_PkeyCtrl(ctx, CRYPT_CTRL_GET_PUBKEY_LEN, &val, sizeof(val)); ASSERT_EQ(ret, CRYPT_SUCCESS); ret = CRYPT_EAL_PkeyCtrl(ctx, CRYPT_CTRL_GET_PRVKEY_LEN, &val, sizeof(val)); ASSERT_EQ(ret, CRYPT_SUCCESS); if (algid == CRYPT_PKEY_DH) { ret = CRYPT_EAL_PkeyCtrl(ctx, CRYPT_CTRL_GET_SHARED_KEY_LEN, &val, sizeof(val)); ASSERT_EQ(ret, CRYPT_SUCCESS); } EXIT: CRYPT_EAL_PkeyFreeCtx(ctx); } /* END_CASE */ /** * @test SDV_CRYPTO_EAL_GET_KEY_LEN_TC003_2 */ /* BEGIN_CASE */ void SDV_CRYPTO_EAL_GET_KEY_LEN_TC003_2(int algid, int rsaBits, Hex *p, Hex *q, Hex *g) { TestRandInit(); CRYPT_EAL_PkeyCtx *ctx = CRYPT_EAL_PkeyNewCtx(algid); ASSERT_TRUE(ctx != NULL); int32_t ret; CRYPT_EAL_PkeyPara para = {0}; uint8_t e[3] = {1, 0, 1}; if (algid == CRYPT_PKEY_RSA) { para.id = CRYPT_PKEY_RSA; para.para.rsaPara.e = e; para.para.rsaPara.eLen = 3; para.para.rsaPara.bits = rsaBits; } else { para.id = algid; // DH or DSA para.para.dhPara.p = p->x; para.para.dhPara.q = q->x; para.para.dhPara.g = g->x; para.para.dhPara.pLen = p->len; para.para.dhPara.qLen = q->len; para.para.dhPara.gLen = g->len; } ASSERT_EQ(CRYPT_EAL_PkeySetPara(ctx, &para), CRYPT_SUCCESS); uint32_t flag = CRYPT_ENABLE_SP800_KEYGEN_FLAG; ret = CRYPT_EAL_PkeyCtrl(ctx, CRYPT_CTRL_SET_GEN_FLAG, &flag, sizeof(flag)); ASSERT_EQ(ret, CRYPT_SUCCESS); ASSERT_EQ(CRYPT_EAL_PkeyGen(ctx), CRYPT_DSA_PARA_ERROR); flag = CRYPT_DISABLE_SP800_KEYGEN_FLAG; ret = CRYPT_EAL_PkeyCtrl(ctx, CRYPT_CTRL_SET_GEN_FLAG, &flag, sizeof(flag)); ASSERT_EQ(ret, CRYPT_SUCCESS); ASSERT_EQ(CRYPT_EAL_PkeyGen(ctx), CRYPT_SUCCESS); EXIT: CRYPT_EAL_PkeyFreeCtx(ctx); } /* END_CASE */ /** * @test SDV_CRYPTO_EAL_GET_KEY_LEN_TC003_3 */ /* BEGIN_CASE */ void SDV_CRYPTO_EAL_GET_KEY_LEN_TC003_3(int algid, int rsaBits, Hex *p, Hex *q, Hex *g) { TestRandInit(); CRYPT_EAL_PkeyCtx *ctx = CRYPT_EAL_PkeyNewCtx(algid); ASSERT_TRUE(ctx != NULL); int32_t ret; CRYPT_EAL_PkeyPara para = {0}; uint8_t e[3] = {1, 0, 1}; if (algid == CRYPT_PKEY_RSA) { para.id = CRYPT_PKEY_RSA; para.para.rsaPara.e = e; para.para.rsaPara.eLen = 3; para.para.rsaPara.bits = rsaBits; } else { para.id = algid; // DH or DSA para.para.dhPara.p = p->x; para.para.dhPara.q = q->x; para.para.dhPara.g = g->x; para.para.dhPara.pLen = p->len; para.para.dhPara.qLen = q->len; para.para.dhPara.gLen = g->len; } ASSERT_EQ(CRYPT_EAL_PkeySetPara(ctx, &para), CRYPT_SUCCESS); uint32_t flag = CRYPT_ENABLE_SP800_KEYGEN_FLAG; ret = CRYPT_EAL_PkeyCtrl(ctx, CRYPT_CTRL_SET_GEN_FLAG, &flag, sizeof(flag)); ASSERT_EQ(ret, CRYPT_SUCCESS); ASSERT_EQ(CRYPT_EAL_PkeyGen(ctx), CRYPT_SUCCESS); EXIT: CRYPT_EAL_PkeyFreeCtx(ctx); } /* END_CASE */
2301_79861745/bench_create
testcode/sdv/testcase/crypto/eal/test_suite_sdv_eal.c
C
unknown
23,501
/* * This file is part of the openHiTLS project. * * openHiTLS is licensed under the Mulan PSL v2. * You can use this software according to the terms and conditions of the Mulan PSL v2. * You may obtain a copy of Mulan PSL v2 at: * * http://license.coscl.org.cn/MulanPSL2 * * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. * See the Mulan PSL v2 for more details. */ /* BEGIN_HEADER */ #include "stub_replace.h" #include "crypt_errno.h" #include "crypt_utils.h" #include "bsl_init.h" #include "bsl_err.h" #include "bsl_err_internal.h" #include "crypt_types.h" #include "crypt_eal_rand.h" #include "crypt_eal_md.h" #include "crypt_eal_pkey.h" #include "crypt_eal_mac.h" #include "crypt_eal_kdf.h" #include "crypt_eal_cipher.h" #include "asmcap_local.h" #include "bsl_params.h" #include "crypt_params_key.h" /* END_HEADER */ #define DATA_LEN (64) void ResetStatus(void) { CRYPT_EAL_RandDeinit(); BSL_GLOBAL_DeInit(); } bool STUB_IsSupportAVX() { return false; } bool STUB_CRYPT_AES_AsmCheck() { return false; } bool STUB_IsSupportNEON() { return false; } bool STUB_IsSupportBMI1() { return false; } bool STUB_IsSupportMOVBE() { return false; } bool STUB_IsSupportAES() { return false; } int32_t STUB_CRYPT_GHASH_AsmCheck() { return CRYPT_EAL_ALG_ASM_NOT_SUPPORT; } int32_t STUB_CRYPT_POLY1305_AsmCheck() { return CRYPT_EAL_ALG_ASM_NOT_SUPPORT; } #define CRYPT_INIT_ABILITY_CPU_POS 0 #define CRYPT_INIT_ABILITY_BSL_POS 1 #define CRYPT_INIT_ABILITY_RAND_POS 2 #define CRYPT_INIT_ABILITY_BITMAP(value, pos) (((value) >> (pos)) & 0x1) #define CRYPT_INIT_SUPPORT_ABILITY(cap, pos) (CRYPT_INIT_ABILITY_BITMAP(cap, pos) != 0) #define DRBG_MAX_OUTPUT_SIZE (1 << 16) /* @ * @test SDV_CRYPT_INIT_FUNC_TC001 * @spec - * @title CRYPT_EAL_Init functional test as constructor * @precon nan * @brief 1. CRYPT_EAL_Init called as constructor 2. check if DRBG is initialized. 3、check if BSL is initialized. * @expect 1. DRBG is initialized 2、BSL is initialized * @prior Level 1 * @auto TRUE @ */ /* BEGIN_CASE */ void SDV_CRYPT_INIT_FUNC_TC001() { #if defined(HITLS_EAL_INIT_OPTS) uint8_t output[DATA_LEN]; uint32_t len = DATA_LEN; int32_t ret = CRYPT_SUCCESS; if(CRYPT_INIT_SUPPORT_ABILITY(HITLS_EAL_INIT_OPTS, CRYPT_INIT_ABILITY_RAND_POS)) { ret = CRYPT_EAL_ERR_DRBG_REPEAT_INIT; } ASSERT_TRUE(CRYPT_EAL_RandInit(CRYPT_RAND_AES128_CTR, NULL, NULL, NULL, 0) == ret); ASSERT_TRUE(CRYPT_EAL_Randbytes(output, len) == CRYPT_SUCCESS); EXIT: ResetStatus(); #endif } /* END_CASE */ /** * @test SDV_CRYPTO_CRYPT_EAL_Init_TC002 * @title Check if cpu capability is called at entry point. * @precon nan * @brief * 1. STUB function * 1. call CRYPT_EAL_CipherNewCtx * @expect * 1. CRYPT_EAL_CipherNewCtx returns NULL */ /* BEGIN_CASE */ void SDV_CRYPTO_CRYPT_EAL_Init_TC002() { FuncStubInfo tmpStubInfo = {0}; CRYPT_EAL_CipherCtx *ctx = NULL; STUB_Init(); ctx = CRYPT_EAL_CipherNewCtx(CRYPT_CIPHER_AES128_CBC); ASSERT_TRUE(ctx != NULL); CRYPT_EAL_CipherFreeCtx(ctx); #if defined(HITLS_CRYPTO_ASM_CHECK) #if defined(__x86_64__) #if defined(HITLS_CRYPTO_AES_ASM) STUB_Replace(&tmpStubInfo, IsSupportAVX, STUB_IsSupportAVX); ctx = CRYPT_EAL_CipherNewCtx(CRYPT_CIPHER_AES128_CBC); ASSERT_TRUE(ctx == NULL); #endif #if defined(HITLS_CRYPTO_SM4_ASM) ctx = CRYPT_EAL_CipherNewCtx(CRYPT_CIPHER_SM4_CBC); ASSERT_TRUE(ctx == NULL); #endif STUB_Reset(&tmpStubInfo); #elif defined(__aarch64__) #if defined(HITLS_CRYPTO_AES_ASM) STUB_Replace(&tmpStubInfo, IsSupportAES, STUB_IsSupportAES); ctx = CRYPT_EAL_CipherNewCtx(CRYPT_CIPHER_AES128_CBC); ASSERT_TRUE(ctx == NULL); #endif #endif #endif EXIT: STUB_Reset(&tmpStubInfo); ResetStatus(); } /* END_CASE */ /** * @test SDV_CRYPTO_CRYPT_EAL_Init_TC003 * @title Check if cpu capability is called at entry point. * @precon nan * @brief * 1. STUB function * 1. call CRYPT_EAL_MdNewCtx * @expect * 1. CRYPT_EAL_CipherNewCtx returns NULL */ /* BEGIN_CASE */ void SDV_CRYPTO_CRYPT_EAL_Init_TC003() { CRYPT_EAL_MdCTX *ctx = NULL; ctx = CRYPT_EAL_MdNewCtx(CRYPT_MD_SHA256); ASSERT_TRUE(ctx != NULL); CRYPT_EAL_MdFreeCtx(ctx); #if defined(HITLS_CRYPTO_ASM_CHECK) #if defined(__x86_64__) #if defined(HITLS_CRYPTO_SM2_ASM) FuncStubInfo tmpStubInfo = {0}; STUB_Init(); STUB_Replace(&tmpStubInfo, IsSupportMOVBE, STUB_IsSupportMOVBE); ctx = CRYPT_EAL_MdNewCtx(CRYPT_MD_SM3); ASSERT_TRUE(ctx == NULL); STUB_Reset(&tmpStubInfo); #endif #endif #endif EXIT: ResetStatus(); } /* END_CASE */ /** * @test SDV_CRYPTO_CRYPT_EAL_Init_TC004 * @title Check if cpu capability is called at entry point. * @precon nan * @brief * 1. STUB function * 1. call CRYPT_EAL_MdNewCtx * @expect * 1. CRYPT_EAL_CipherNewCtx returns NULL */ /* BEGIN_CASE */ void SDV_CRYPTO_CRYPT_EAL_Init_TC004() { ResetStatus(); FuncStubInfo tmpStubInfo = {0}; STUB_Init(); uint32_t keyLen = DATA_LEN; uint8_t key[keyLen]; uint32_t saltLen = DATA_LEN; uint8_t salt[saltLen]; uint32_t it = 1024; uint32_t outLen = DATA_LEN; uint8_t out[outLen]; CRYPT_EAL_KdfCTX *ctx = CRYPT_EAL_KdfNewCtx(CRYPT_KDF_PBKDF2); ASSERT_TRUE(ctx != NULL); CRYPT_MAC_AlgId macAlgId = CRYPT_MAC_HMAC_SHA256; BSL_Param params[5] = {{0}, {0}, {0}, {0}, BSL_PARAM_END}; ASSERT_EQ(BSL_PARAM_InitValue(&params[0], CRYPT_PARAM_KDF_MAC_ID, BSL_PARAM_TYPE_UINT32, &macAlgId, sizeof(macAlgId)), CRYPT_SUCCESS); ASSERT_EQ(BSL_PARAM_InitValue(&params[1], CRYPT_PARAM_KDF_PASSWORD, BSL_PARAM_TYPE_OCTETS, key, keyLen), CRYPT_SUCCESS); ASSERT_EQ(BSL_PARAM_InitValue(&params[2], CRYPT_PARAM_KDF_SALT, BSL_PARAM_TYPE_OCTETS, salt, saltLen), CRYPT_SUCCESS); ASSERT_EQ(BSL_PARAM_InitValue(&params[3], CRYPT_PARAM_KDF_ITER, BSL_PARAM_TYPE_UINT32, &it, sizeof(it)), CRYPT_SUCCESS); ASSERT_EQ(CRYPT_EAL_KdfSetParam(ctx, params), CRYPT_SUCCESS); ASSERT_EQ(CRYPT_EAL_KdfDerive(ctx, out, outLen), CRYPT_SUCCESS); #if defined(HITLS_CRYPTO_ASM_CHECK) #if defined(__x86_64__) #if defined(HITLS_CRYPTO_SHA2_ASM) STUB_Replace(&tmpStubInfo, IsSupportAVX, STUB_IsSupportAVX); ASSERT_TRUE(CRYPT_EAL_KdfSetParam(ctx, params) != CRYPT_SUCCESS); STUB_Reset(&tmpStubInfo); #endif #if defined(HITLS_CRYPTO_MD5_ASM) STUB_Replace(&tmpStubInfo, IsSupportBMI1, STUB_IsSupportBMI1); macAlgId = CRYPT_MAC_HMAC_MD5; ASSERT_TRUE(CRYPT_EAL_KdfSetParam(ctx, params) != CRYPT_SUCCESS); STUB_Reset(&tmpStubInfo); #endif #if defined(HITLS_CRYPTO_SM3_ASM) STUB_Replace(&tmpStubInfo, IsSupportMOVBE, STUB_IsSupportMOVBE); macAlgId = CRYPT_MAC_HMAC_SM3; ASSERT_TRUE(CRYPT_EAL_KdfSetParam(ctx, params) != CRYPT_SUCCESS); STUB_Reset(&tmpStubInfo); #endif #endif #endif EXIT: CRYPT_EAL_KdfFreeCtx(ctx); STUB_Reset(&tmpStubInfo); ResetStatus(); } /* END_CASE */ /** * @test SDV_CRYPTO_CRYPT_EAL_Init_TC005 * @title Check if cpu capability is called at entry point. * @precon nan * @brief * 1. STUB function * 1. call CRYPT_EAL_MdNewCtx * @expect * 1. CRYPT_EAL_CipherNewCtx returns NULL */ /* BEGIN_CASE */ void SDV_CRYPTO_CRYPT_EAL_Init_TC005() { ResetStatus(); FuncStubInfo tmpStubInfo = {0}; CRYPT_EAL_RndCtx *ctx = NULL; STUB_Init(); ctx = CRYPT_EAL_DrbgNew(CRYPT_RAND_SHA256, NULL, NULL); ASSERT_TRUE(ctx != NULL); ASSERT_TRUE(CRYPT_EAL_DrbgInstantiate(ctx, NULL, 0) == CRYPT_SUCCESS); CRYPT_EAL_DrbgDeinit(ctx); #if defined(HITLS_CRYPTO_ASM_CHECK) #if defined(__x86_64__) STUB_Replace(&tmpStubInfo, IsSupportAVX, STUB_IsSupportAVX); #if defined(HITLS_CRYPTO_SHA1_ASM) ctx = CRYPT_EAL_DrbgNew(CRYPT_RAND_SHA1, NULL, NULL); ASSERT_TRUE(ctx == NULL); ASSERT_NE(CRYPT_EAL_RandInit(CRYPT_RAND_SHA1, NULL, NULL, NULL, 0), CRYPT_SUCCESS); #endif #if defined(HITLS_CRYPTO_SHA2_ASM) ctx = CRYPT_EAL_DrbgNew(CRYPT_RAND_SHA256, NULL, NULL); ASSERT_TRUE(ctx == NULL); ASSERT_NE(CRYPT_EAL_RandInit(CRYPT_RAND_SHA256, NULL, NULL, NULL, 0), CRYPT_SUCCESS); #endif #if defined(HITLS_CRYPTO_AES_ASM) ctx = CRYPT_EAL_DrbgNew(CRYPT_RAND_AES128_CTR, NULL, NULL); ASSERT_TRUE(ctx == NULL); ASSERT_NE(CRYPT_EAL_RandInit(CRYPT_RAND_AES128_CTR, NULL, NULL, NULL, 0), CRYPT_SUCCESS); #endif #elif defined(__aarch64__) #if defined(HITLS_CRYPTO_AES_ASM) STUB_Replace(&tmpStubInfo, IsSupportAES, STUB_IsSupportAES); ctx = CRYPT_EAL_DrbgNew(CRYPT_RAND_AES128_CTR, NULL, NULL); ASSERT_TRUE(ctx == NULL); ASSERT_NE(CRYPT_EAL_RandInit(CRYPT_RAND_AES128_CTR, NULL, NULL, NULL, 0), CRYPT_SUCCESS); #endif #endif #endif EXIT: STUB_Reset(&tmpStubInfo); ResetStatus(); } /* END_CASE */
2301_79861745/bench_create
testcode/sdv/testcase/crypto/ealinit/test_suite_sdv_ealinit.c
C
unknown
9,001
/* * This file is part of the openHiTLS project. * * openHiTLS is licensed under the Mulan PSL v2. * You can use this software according to the terms and conditions of the Mulan PSL v2. * You may obtain a copy of Mulan PSL v2 at: * * http://license.coscl.org.cn/MulanPSL2 * * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, * EITHER EXPRESS 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 <stdio.h> #include <string.h> #include <pthread.h> #include "securec.h" #include "crypt_bn.h" #include "bsl_err.h" #include "bsl_sal.h" #include "crypt_errno.h" #include "crypt_dsa.h" #include "crypt_eal_pkey.h" #include "crypt_eal_rand.h" #include "stub_replace.h" #include "crypt_util_rand.h" #include "crypt_encode_internal.h" #include "crypt_eal_md.h" #include "crypt_dsa.h" #include "crypt_ecdh.h" #include "crypt_ecdsa.h" #include "crypt_ecc.h" #include "eal_pkey_local.h" #define SUCCESS 0 #define ERROR (-1) #define BITS_OF_BYTE 8 #define KEY_MAX_LEN 133 #define PUBKEY_MAX_LEN 133 // 521(The public key length of the longest curve.) * 2 + 1 1043 #define PRVKEY_MAX_LEN 65 #define ECC_MAX_BIT_LEN 521 #define CRYPT_EAL_PKEY_KEYMGMT_OPERATE 0 static uint8_t gkRandBuf[80]; static uint32_t gkRandBufLen = 0; typedef struct { uint8_t data[KEY_MAX_LEN]; uint32_t len; } KeyData; static int32_t RandFunc(uint8_t *randNum, uint32_t randLen) { const int maxNum = 255; for (uint32_t i = 0; i < randLen; i++) { randNum[i] = (uint8_t)(rand() % maxNum); } return 0; } static int32_t RandFuncEx(void *libCtx, uint8_t *randNum, uint32_t randLen) { (void)libCtx; const int maxNum = 255; for (uint32_t i = 0; i < randLen; i++) { randNum[i] = (uint8_t)(rand() % maxNum); } return 0; } static int32_t STUB_RandRangeK(void *libCtx, BN_BigNum *r, const BN_BigNum *p) { (void)p; (void)libCtx; BN_Bin2Bn(r, gkRandBuf, gkRandBufLen); return CRYPT_SUCCESS; } static int32_t EccPointToBuffer(Hex *pubKeyX, Hex *pubKeyY, CRYPT_PKEY_PointFormat pointFormat, KeyData *pubKey) { uint8_t value; value = *(uint8_t *)(pubKeyY->x + pubKeyY->len - 1); int sign = 0; /* The value 0 indicates an odd number.*/ if (value % 2 == 0) { sign = 1; } switch (pointFormat) { case CRYPT_POINT_COMPRESSED: { pubKey->data[0] = (sign == 1) ? 0x02 : 0x03; ASSERT_TRUE_AND_LOG( "memcpy_s", memcpy_s(pubKey->data + 1, pubKey->len - 1, pubKeyX->x, pubKeyX->len) == EOK); pubKey->len = pubKeyX->len + 1; } break; case CRYPT_POINT_UNCOMPRESSED: { pubKey->data[0] = 0x04; ASSERT_TRUE_AND_LOG( "memcpy_s", memcpy_s(pubKey->data + 1, pubKey->len - 1, pubKeyX->x, pubKeyX->len) == EOK); ASSERT_TRUE_AND_LOG("memcpy_s", memcpy_s(pubKey->data + 1 + pubKeyX->len, pubKey->len - 1 - pubKeyX->len, pubKeyY->x, pubKeyY->len) == EOK); pubKey->len = pubKeyX->len + pubKeyY->len + 1; } break; case CRYPT_POINT_HYBRID: { pubKey->data[0] = (sign == 1) ? 0x06 : 0x07; ASSERT_TRUE_AND_LOG( "memcpy_s", memcpy_s(pubKey->data + 1, pubKey->len - 1, pubKeyX->x, pubKeyX->len) == EOK); ASSERT_TRUE_AND_LOG("memcpy_s", memcpy_s(pubKey->data + 1 + pubKeyX->len, pubKey->len - 1 - pubKeyX->len, pubKeyY->x, pubKeyY->len) == EOK); pubKey->len = pubKeyX->len + pubKeyY->len + 1; } break; default: return ERROR; } return SUCCESS; EXIT: return -1; /* -1 indicates an exception. */ } static int GetPubKeyLen(int eccId) { switch (eccId) { case CRYPT_ECC_NISTP224: return 57; /* SECP224R1 */ case CRYPT_ECC_NISTP256: /* (32 * 2) + 1 SECP256R1, brainpoolP256r1 */ case CRYPT_ECC_BRAINPOOLP256R1: return 65; case CRYPT_ECC_NISTP384: /* (48 * 2) + 1 SECP384R1, brainpoolP384r1 */ case CRYPT_ECC_BRAINPOOLP384R1: return 97; case CRYPT_ECC_BRAINPOOLP512R1: return 129; /* brainpoolP512r1 */ case CRYPT_ECC_NISTP521: return 133; /* (66 * 2) + 1 SECP521R1 */ default: return SUCCESS; } } static int GetPrvKeyLen(int eccId) { switch (eccId) { case CRYPT_ECC_NISTP224: return 28; case CRYPT_ECC_NISTP256: case CRYPT_ECC_BRAINPOOLP256R1: return 32; case CRYPT_ECC_NISTP384: case CRYPT_ECC_BRAINPOOLP384R1: return 48; case CRYPT_ECC_BRAINPOOLP512R1: return 64; case CRYPT_ECC_NISTP521: return 66; default: return SUCCESS; } } static void Ecc_SetPubKey(CRYPT_EAL_PkeyPub *pub, int id, uint8_t *key, uint32_t len) { pub->id = id; pub->key.eccPub.data = key; pub->key.eccPub.len = len; } static void Ecc_SetPrvKey(CRYPT_EAL_PkeyPrv *prv, int id, uint8_t *key, uint32_t len) { prv->id = id; prv->key.eccPrv.data = key; prv->key.eccPrv.len = len; } static int Ecc_GenKey( int algId, int eccId, Hex *prvKeyVector, Hex *pubKeyX, Hex *pubKeyY, int pointFormat, int isProvider) { int ret; FuncStubInfo tmpRpInfo; CRYPT_EAL_PkeyCtx *pkey = NULL; KeyData pubKeyVector = {{0}, KEY_MAX_LEN}; CRYPT_EAL_PkeyPub ecdsaPubKey = {0}; CRYPT_EAL_PkeyPrv ecdsaPrvKey = {0}; /* Init the DRBG */ TestMemInit(); /* Create a key structure. */ pkey = TestPkeyNewCtx(NULL, algId, CRYPT_EAL_PKEY_KEYMGMT_OPERATE, "provider=default", isProvider); ASSERT_TRUE(pkey != NULL); ASSERT_EQ(CRYPT_EAL_PkeySetParaById(pkey, eccId), CRYPT_SUCCESS); /* Mock BN_RandRange to STUB_RandRangeK */ ASSERT_TRUE(memcpy_s(gkRandBuf, sizeof(gkRandBuf), prvKeyVector->x, prvKeyVector->len) == 0); gkRandBufLen = prvKeyVector->len; STUB_Init(); STUB_Replace(&tmpRpInfo, BN_RandRangeEx, STUB_RandRangeK); /* Generate a key pair */ ASSERT_EQ(TestRandInit(), CRYPT_SUCCESS); ASSERT_EQ(CRYPT_EAL_PkeyGen(pkey), CRYPT_SUCCESS); /* Set point format*/ ASSERT_EQ(CRYPT_EAL_PkeyCtrl(pkey, CRYPT_CTRL_SET_ECC_POINT_FORMAT, &pointFormat, sizeof(uint32_t)), CRYPT_SUCCESS); /* Get public key */ ecdsaPubKey.id = algId; ecdsaPubKey.key.eccPub.data = (uint8_t *)malloc(GetPubKeyLen(eccId)); ASSERT_TRUE(ecdsaPubKey.key.eccPub.data != NULL); ecdsaPubKey.key.eccPub.len = GetPubKeyLen(eccId); ASSERT_EQ(CRYPT_EAL_PkeyGetPub(pkey, &ecdsaPubKey), CRYPT_SUCCESS); /* Get private key */ ecdsaPrvKey.id = algId; ecdsaPrvKey.key.eccPrv.data = (uint8_t *)malloc(GetPrvKeyLen(eccId)); ASSERT_TRUE(ecdsaPrvKey.key.eccPrv.data != NULL); ecdsaPrvKey.key.eccPrv.len = GetPrvKeyLen(eccId); ASSERT_EQ(CRYPT_EAL_PkeyGetPrv(pkey, &ecdsaPrvKey), CRYPT_SUCCESS); /* Convert the point to buffer */ ret = EccPointToBuffer(pubKeyX, pubKeyY, pointFormat, &pubKeyVector); ASSERT_TRUE_AND_LOG("EccPointToBuffer", ret == CRYPT_SUCCESS); ASSERT_COMPARE("Compare PubKey", pubKeyVector.data, ecdsaPubKey.key.eccPub.len, ecdsaPubKey.key.eccPub.data, ecdsaPubKey.key.eccPub.len); ASSERT_COMPARE("Compare PrvKey", prvKeyVector->x, ecdsaPrvKey.key.eccPrv.len, ecdsaPrvKey.key.eccPrv.data, ecdsaPrvKey.key.eccPrv.len); free(ecdsaPubKey.key.eccPub.data); free(ecdsaPrvKey.key.eccPrv.data); STUB_Reset(&tmpRpInfo); TestRandDeInit(); CRYPT_EAL_PkeyFreeCtx(pkey); return SUCCESS; EXIT: free(ecdsaPubKey.key.eccPub.data); free(ecdsaPrvKey.key.eccPrv.data); STUB_Reset(&tmpRpInfo); TestRandDeInit(); CRYPT_EAL_PkeyFreeCtx(pkey); return ERROR; } int EAL_PkeyNewCtx_Api_TC001(int algId) { CRYPT_EAL_PkeyCtx *pkeyCtx = NULL; /* Registers memory functions. */ TestMemInit(); pkeyCtx = CRYPT_EAL_PkeyNewCtx(algId); ASSERT_TRUE_AND_LOG("CRYPT_EAL_PkeyNewCtx", pkeyCtx != NULL); CRYPT_EAL_PkeyFreeCtx(pkeyCtx); return SUCCESS; EXIT: CRYPT_EAL_PkeyFreeCtx(pkeyCtx); return ERROR; } int EAL_PkeyFreeCtx_Api_TC001(int algId) { CRYPT_EAL_PkeyCtx *pkeyCtx = NULL; TestMemInit(); pkeyCtx = CRYPT_EAL_PkeyNewCtx(algId); ASSERT_TRUE_AND_LOG("CRYPT_EAL_PkeyNewCtx", pkeyCtx != NULL); CRYPT_EAL_PkeyFreeCtx(pkeyCtx); pkeyCtx = NULL; CRYPT_EAL_PkeyFreeCtx(pkeyCtx); return SUCCESS; EXIT: CRYPT_EAL_PkeyFreeCtx(pkeyCtx); return ERROR; } int EAL_PkeySetParaById_Api_TC001(int algId) { int ret = ERROR; CRYPT_EAL_PkeyCtx *pkeyCtx = NULL; TestMemInit(); pkeyCtx = CRYPT_EAL_PkeyNewCtx(algId); ASSERT_TRUE_AND_LOG("CRYPT_EAL_PkeyNewCtx", pkeyCtx != NULL); ASSERT_TRUE_AND_LOG("Invalid Pkey", CRYPT_EAL_PkeySetParaById(NULL, CRYPT_ECC_NISTP224) == CRYPT_NULL_INPUT); ASSERT_TRUE_AND_LOG("CRYPT_ECC_NISTP224", CRYPT_EAL_PkeySetParaById(pkeyCtx, CRYPT_ECC_NISTP224) == CRYPT_SUCCESS); ASSERT_TRUE_AND_LOG("CRYPT_ECC_NISTP256", CRYPT_EAL_PkeySetParaById(pkeyCtx, CRYPT_ECC_NISTP256) == CRYPT_SUCCESS); ASSERT_TRUE_AND_LOG("CRYPT_ECC_NISTP384", CRYPT_EAL_PkeySetParaById(pkeyCtx, CRYPT_ECC_NISTP384) == CRYPT_SUCCESS); ASSERT_TRUE_AND_LOG("CRYPT_ECC_NISTP521", CRYPT_EAL_PkeySetParaById(pkeyCtx, CRYPT_ECC_NISTP521) == CRYPT_SUCCESS); ASSERT_TRUE_AND_LOG( "CRYPT_ECC_BRAINPOOLP256R1", CRYPT_EAL_PkeySetParaById(pkeyCtx, CRYPT_ECC_BRAINPOOLP256R1) == CRYPT_SUCCESS); ASSERT_TRUE_AND_LOG( "CRYPT_ECC_BRAINPOOLP384R1", CRYPT_EAL_PkeySetParaById(pkeyCtx, CRYPT_ECC_BRAINPOOLP384R1) == CRYPT_SUCCESS); ASSERT_TRUE_AND_LOG( "CRYPT_ECC_BRAINPOOLP512R1", CRYPT_EAL_PkeySetParaById(pkeyCtx, CRYPT_ECC_BRAINPOOLP512R1) == CRYPT_SUCCESS); ret = SUCCESS; EXIT: CRYPT_EAL_PkeyFreeCtx(pkeyCtx); return ret; } int EAL_PkeyCtrl_Api_TC001(int algId, int type, int expect) { int ret = ERROR; int32_t value = 1; CRYPT_EAL_PkeyCtx *pkeyCtx = NULL; TestMemInit(); pkeyCtx = CRYPT_EAL_PkeyNewCtx(algId); ASSERT_TRUE_AND_LOG("CRYPT_EAL_PkeyNewCtx", pkeyCtx != NULL); ASSERT_TRUE_AND_LOG("CRYPT_EAL_PkeyCtrl", CRYPT_EAL_PkeyCtrl(pkeyCtx, type, &value, sizeof(int32_t)) == expect); ret = SUCCESS; EXIT: CRYPT_EAL_PkeyFreeCtx(pkeyCtx); return ret; } int EAL_PkeyCtrl_Api_TC002(int algId) { uint32_t ret, pointFormat; CRYPT_EAL_PkeyCtx *pkeyCtx = NULL; TestMemInit(); pkeyCtx = CRYPT_EAL_PkeyNewCtx(algId); ASSERT_TRUE_AND_LOG("CRYPT_EAL_PkeyNewCtx", pkeyCtx != NULL); pointFormat = 1; ret = CRYPT_EAL_PkeyCtrl(NULL, CRYPT_CTRL_SET_ECC_POINT_FORMAT, &pointFormat, sizeof(uint32_t)); ASSERT_TRUE_AND_LOG("pkey = null", ret == CRYPT_NULL_INPUT); ret = CRYPT_EAL_PkeyCtrl(pkeyCtx, CRYPT_CTRL_SET_ECC_POINT_FORMAT, NULL, 0); ASSERT_TRUE_AND_LOG("val = null, len = 0", ret == CRYPT_NULL_INPUT); ret = CRYPT_EAL_PkeyCtrl(pkeyCtx, CRYPT_CTRL_SET_ECC_POINT_FORMAT, NULL, sizeof(uint32_t)); ASSERT_TRUE_AND_LOG("val = null, len != 0", ret == CRYPT_NULL_INPUT); ret = CRYPT_EAL_PkeyCtrl(pkeyCtx, CRYPT_CTRL_SET_ECC_POINT_FORMAT, &pointFormat, 0); ASSERT_TRUE_AND_LOG("val != null, len = 0", ret == CRYPT_ECC_PKEY_ERR_CTRL_LEN); pointFormat = CRYPT_POINT_MAX; ret = CRYPT_EAL_PkeyCtrl(pkeyCtx, CRYPT_CTRL_SET_ECC_POINT_FORMAT, &pointFormat, sizeof(uint32_t)); ASSERT_TRUE_AND_LOG("PointFormat = CRYPT_POINT_MAX", ret == CRYPT_ECC_PKEY_ERR_INVALID_POINT_FORMAT); pointFormat = CRYPT_POINT_COMPRESSED; ret = CRYPT_EAL_PkeyCtrl(pkeyCtx, CRYPT_CTRL_SET_ECC_POINT_FORMAT, &pointFormat, sizeof(uint32_t)); ASSERT_TRUE_AND_LOG("PointFormat = CRYPT_POINT_COMPRESSED", ret == CRYPT_SUCCESS); pointFormat = CRYPT_POINT_UNCOMPRESSED; ret = CRYPT_EAL_PkeyCtrl(pkeyCtx, CRYPT_CTRL_SET_ECC_POINT_FORMAT, &pointFormat, sizeof(uint32_t)); ASSERT_TRUE_AND_LOG("PointFormat = CRYPT_POINT_UNCOMPRESSED", ret == CRYPT_SUCCESS); pointFormat = CRYPT_POINT_HYBRID; ret = CRYPT_EAL_PkeyCtrl(pkeyCtx, CRYPT_CTRL_SET_ECC_POINT_FORMAT, &pointFormat, sizeof(uint32_t)); ASSERT_TRUE_AND_LOG("PointFormat = CRYPT_POINT_HYBRID", ret == CRYPT_SUCCESS); CRYPT_EAL_PkeyFreeCtx(pkeyCtx); return SUCCESS; EXIT: CRYPT_EAL_PkeyFreeCtx(pkeyCtx); return ERROR; } int EAL_PkeyCtrl_Api_TC003(int algId, int eccId, Hex *pubKeyX, Hex *pubKeyY) { uint32_t ret, pointFormat; CRYPT_EAL_PkeyCtx *ctx = NULL; CRYPT_EAL_PkeyPub pub1 = {0}; CRYPT_EAL_PkeyPub pub2 = {0}; KeyData pubKeyVector1 = {{0}, KEY_MAX_LEN}; KeyData pubKeyVector2 = {{0}, KEY_MAX_LEN}; KeyData pubKeyVector3 = {{0}, KEY_MAX_LEN}; TestMemInit(); CRYPT_RandRegist(RandFunc); CRYPT_RandRegistEx(RandFuncEx); /* Create a key structure. */ ctx = CRYPT_EAL_PkeyNewCtx(algId); ASSERT_TRUE_AND_LOG("NewCtx", ctx != NULL); ASSERT_TRUE_AND_LOG("CRYPT_EAL_PkeySetParaById", CRYPT_EAL_PkeySetParaById(ctx, eccId) == CRYPT_SUCCESS); /* Convert the format of point to compressed. */ ret = EccPointToBuffer(pubKeyX, pubKeyY, CRYPT_POINT_COMPRESSED, &pubKeyVector1); ASSERT_TRUE_AND_LOG("EccPointToBuffer", ret == CRYPT_SUCCESS); /* Set public key. */ Ecc_SetPubKey(&pub1, algId, pubKeyVector1.data, pubKeyVector1.len); ASSERT_EQ(CRYPT_EAL_PkeySetPub(ctx, &pub1), CRYPT_SUCCESS); /* Set the point format to compressed. */ pointFormat = CRYPT_POINT_COMPRESSED; ret = CRYPT_EAL_PkeyCtrl(ctx, CRYPT_CTRL_SET_ECC_POINT_FORMAT, &pointFormat, sizeof(uint32_t)); ASSERT_TRUE_AND_LOG("Set CRYPT_POINT_COMPRESSED", ret == CRYPT_SUCCESS); /* Set the point format to hybrid. */ pointFormat = CRYPT_POINT_HYBRID; ret = CRYPT_EAL_PkeyCtrl(ctx, CRYPT_CTRL_SET_ECC_POINT_FORMAT, &pointFormat, sizeof(uint32_t)); ASSERT_TRUE_AND_LOG("Set CRYPT_POINT_HYBRID", ret == CRYPT_SUCCESS); /* Get the public key. */ Ecc_SetPubKey(&pub2, algId, pubKeyVector2.data, GetPubKeyLen(eccId)); ASSERT_EQ(CRYPT_EAL_PkeyGetPub(ctx, &pub2), CRYPT_SUCCESS); /* Convert the format of point to hybrid. */ ret = EccPointToBuffer(pubKeyX, pubKeyY, pointFormat, &pubKeyVector3); ASSERT_TRUE_AND_LOG("EccPointToBuffer", ret == CRYPT_SUCCESS); /* Compare */ ASSERT_TRUE_AND_LOG("Compare PubKey Len", pub2.key.eccPub.len == pubKeyVector3.len); ASSERT_TRUE_AND_LOG("Compare PubKey", memcmp(pub2.key.eccPub.data, pubKeyVector3.data, pubKeyVector3.len) == 0); CRYPT_EAL_PkeyFreeCtx(ctx); CRYPT_EAL_RandDeinit(); return SUCCESS; EXIT: CRYPT_EAL_PkeyFreeCtx(ctx); CRYPT_EAL_RandDeinit(); return ERROR; } int EAL_PkeyGetPrv_Api_TC001(int algId, Hex *prvKey) { int ret = ERROR; CRYPT_EAL_PkeyCtx *ctx = NULL; CRYPT_EAL_PkeyPrv prv1 = {0}; CRYPT_EAL_PkeyPrv prv2 = {0}; KeyData prvKeyBuffer = {{0}, KEY_MAX_LEN}; TestMemInit(); /* Create a key structure. */ ctx = CRYPT_EAL_PkeyNewCtx(algId); ASSERT_TRUE_AND_LOG("NewCtx", ctx != NULL); ASSERT_TRUE_AND_LOG("SetParaById", CRYPT_EAL_PkeySetParaById(ctx, CRYPT_ECC_NISTP224) == CRYPT_SUCCESS); /* Get the private key when there is no private key. */ Ecc_SetPrvKey(&prv2, algId, prvKeyBuffer.data, GetPrvKeyLen(CRYPT_ECC_NISTP224)); ASSERT_EQ(CRYPT_EAL_PkeyGetPrv(ctx, &prv2), CRYPT_ECC_PKEY_ERR_EMPTY_KEY); /* Set the private key. */ Ecc_SetPrvKey(&prv1, algId, prvKey->x, prvKey->len); ASSERT_EQ(CRYPT_EAL_PkeySetPrv(ctx, &prv1), CRYPT_SUCCESS); /* Input parameter test of CRYPT_EAL_PkeyGetPrv. */ ASSERT_EQ(CRYPT_EAL_PkeyGetPrv(NULL, &prv2), CRYPT_NULL_INPUT); ASSERT_EQ(CRYPT_EAL_PkeyGetPrv(ctx, NULL), CRYPT_NULL_INPUT); prv2.id = CRYPT_PKEY_DH; ASSERT_EQ(CRYPT_EAL_PkeyGetPrv(ctx, &prv2), CRYPT_EAL_ERR_ALGID); prv2.id = algId; ASSERT_EQ(CRYPT_EAL_PkeyGetPrv(ctx, &prv2), CRYPT_SUCCESS); ret = SUCCESS; EXIT: CRYPT_EAL_PkeyFreeCtx(ctx); return ret; } int EAL_PkeyGetPrv_Provider_Api_TC001(int algId, Hex *prvKey) { int ret = ERROR; CRYPT_EAL_PkeyCtx *ctx = NULL; CRYPT_EAL_PkeyPrv prv1 = {0}; CRYPT_EAL_PkeyPrv prv2 = {0}; KeyData prvKeyBuffer = {{0}, KEY_MAX_LEN}; TestMemInit(); /* Create a key structure. */ ctx = TestPkeyNewCtx(NULL, algId, CRYPT_EAL_PKEY_KEYMGMT_OPERATE, "provider=default", true); ASSERT_TRUE_AND_LOG("NewCtx", ctx != NULL); ASSERT_TRUE_AND_LOG("SetParaById", CRYPT_EAL_PkeySetParaById(ctx, CRYPT_ECC_NISTP224) == CRYPT_SUCCESS); /* Get the private key when there is no private key. */ Ecc_SetPrvKey(&prv2, algId, prvKeyBuffer.data, GetPrvKeyLen(CRYPT_ECC_NISTP224)); ASSERT_EQ(CRYPT_EAL_PkeyGetPrv(ctx, &prv2), CRYPT_ECC_PKEY_ERR_EMPTY_KEY); /* Set the private key. */ Ecc_SetPrvKey(&prv1, algId, prvKey->x, prvKey->len); ASSERT_EQ(CRYPT_EAL_PkeySetPrv(ctx, &prv1), CRYPT_SUCCESS); /* Input parameter test of CRYPT_EAL_PkeyGetPrv. */ ASSERT_EQ(CRYPT_EAL_PkeyGetPrv(NULL, &prv2), CRYPT_NULL_INPUT); ASSERT_EQ(CRYPT_EAL_PkeyGetPrv(ctx, NULL), CRYPT_NULL_INPUT); prv2.id = CRYPT_PKEY_DH; ASSERT_EQ(CRYPT_EAL_PkeyGetPrv(ctx, &prv2), CRYPT_EAL_ERR_ALGID); prv2.id = algId; ASSERT_EQ(CRYPT_EAL_PkeyGetPrv(ctx, &prv2), CRYPT_SUCCESS); ret = SUCCESS; EXIT: CRYPT_EAL_PkeyFreeCtx(ctx); return ret; } int EAL_PkeyGetPub_Api_TC001(int algId, Hex *pubKeyX, Hex *pubKeyY) { int ret = ERROR; CRYPT_EAL_PkeyCtx *ctx = NULL; CRYPT_EAL_PkeyPub pub1, pub2; KeyData pubKeyVector1 = {{0}, KEY_MAX_LEN}; KeyData pubKeyVector2 = {{0}, KEY_MAX_LEN}; TestMemInit(); /* Create a key structure. */ ctx = CRYPT_EAL_PkeyNewCtx(algId); ASSERT_TRUE_AND_LOG("NewCtx", ctx != NULL); ASSERT_TRUE_AND_LOG("SetParaById", CRYPT_EAL_PkeySetParaById(ctx, CRYPT_ECC_NISTP224) == CRYPT_SUCCESS); /* Get the public key when there is no public key. */ Ecc_SetPubKey(&pub2, algId, pubKeyVector2.data, GetPubKeyLen(CRYPT_ECC_NISTP224)); ASSERT_EQ(CRYPT_EAL_PkeyGetPub(ctx, &pub2), CRYPT_ECC_PKEY_ERR_EMPTY_KEY); /* Set the public key. */ ASSERT_TRUE_AND_LOG("EccPointToBuffer", EccPointToBuffer(pubKeyX, pubKeyY, CRYPT_POINT_UNCOMPRESSED, &pubKeyVector1) == CRYPT_SUCCESS); Ecc_SetPubKey(&pub1, algId, pubKeyVector1.data, pubKeyVector1.len); ASSERT_EQ(CRYPT_EAL_PkeySetPub(ctx, &pub1), CRYPT_SUCCESS); /* Input parameter test of CRYPT_EAL_PkeyGetPub. */ ASSERT_EQ(CRYPT_EAL_PkeyGetPub(NULL, &pub2), CRYPT_NULL_INPUT); ASSERT_EQ(CRYPT_EAL_PkeyGetPub(ctx, NULL), CRYPT_NULL_INPUT); pub2.id = CRYPT_PKEY_DH; ASSERT_EQ(CRYPT_EAL_PkeyGetPub(ctx, &pub2), CRYPT_EAL_ERR_ALGID); pub2.id = algId; ASSERT_EQ(CRYPT_EAL_PkeyGetPub(ctx, &pub2), CRYPT_SUCCESS); ret = SUCCESS; EXIT: CRYPT_EAL_PkeyFreeCtx(ctx); return ret; } int EAL_PkeyGetPub_Provider_Api_TC001(int algId, Hex *pubKeyX, Hex *pubKeyY) { int ret = ERROR; CRYPT_EAL_PkeyCtx *ctx = NULL; CRYPT_EAL_PkeyPub pub1, pub2; KeyData pubKeyVector1 = {{0}, KEY_MAX_LEN}; KeyData pubKeyVector2 = {{0}, KEY_MAX_LEN}; TestMemInit(); /* Create a key structure. */ ctx = TestPkeyNewCtx(NULL, algId, CRYPT_EAL_PKEY_KEYMGMT_OPERATE, "provider=default", true); ASSERT_TRUE_AND_LOG("NewCtx", ctx != NULL); ASSERT_TRUE_AND_LOG("SetParaById", CRYPT_EAL_PkeySetParaById(ctx, CRYPT_ECC_NISTP224) == CRYPT_SUCCESS); /* Get the public key when there is no public key. */ Ecc_SetPubKey(&pub2, algId, pubKeyVector2.data, GetPubKeyLen(CRYPT_ECC_NISTP224)); ASSERT_EQ(CRYPT_EAL_PkeyGetPub(ctx, &pub2), CRYPT_ECC_PKEY_ERR_EMPTY_KEY); /* Set the public key. */ ASSERT_TRUE_AND_LOG("EccPointToBuffer", EccPointToBuffer(pubKeyX, pubKeyY, CRYPT_POINT_UNCOMPRESSED, &pubKeyVector1) == CRYPT_SUCCESS); Ecc_SetPubKey(&pub1, algId, pubKeyVector1.data, pubKeyVector1.len); ASSERT_EQ(CRYPT_EAL_PkeySetPub(ctx, &pub1), CRYPT_SUCCESS); /* Input parameter test of CRYPT_EAL_PkeyGetPub. */ ASSERT_EQ(CRYPT_EAL_PkeyGetPub(NULL, &pub2), CRYPT_NULL_INPUT); ASSERT_EQ(CRYPT_EAL_PkeyGetPub(ctx, NULL), CRYPT_NULL_INPUT); pub2.id = CRYPT_PKEY_DH; ASSERT_EQ(CRYPT_EAL_PkeyGetPub(ctx, &pub2), CRYPT_EAL_ERR_ALGID); pub2.id = algId; ASSERT_EQ(CRYPT_EAL_PkeyGetPub(ctx, &pub2), CRYPT_SUCCESS); ret = SUCCESS; EXIT: CRYPT_EAL_PkeyFreeCtx(ctx); return ret; } int EAL_PkeySetPrv_Api_TC001(int algId, Hex *prvKey, Hex *errorPrvKey) { int ret = ERROR; CRYPT_EAL_PkeyCtx *ctx = NULL; CRYPT_EAL_PkeyPrv prv = {0}; TestMemInit(); /* Create a key structure. */ ctx = CRYPT_EAL_PkeyNewCtx(algId); ASSERT_TRUE_AND_LOG("NewCtx", ctx != NULL); /* Set the key without curve */ Ecc_SetPrvKey(&prv, algId, prvKey->x, prvKey->len); ASSERT_EQ(CRYPT_EAL_PkeySetPrv(ctx, &prv), CRYPT_NULL_INPUT); ASSERT_TRUE(CRYPT_EAL_PkeySetParaById(ctx, CRYPT_ECC_NISTP224) == CRYPT_SUCCESS); /* Input parameter test of CRYPT_EAL_PkeySetPrv. */ ASSERT_EQ(CRYPT_EAL_PkeySetPrv(NULL, &prv), CRYPT_NULL_INPUT); ASSERT_EQ(CRYPT_EAL_PkeySetPrv(ctx, NULL), CRYPT_NULL_INPUT); prv.id = CRYPT_PKEY_DH; ASSERT_EQ(CRYPT_EAL_PkeySetPrv(ctx, &prv), CRYPT_EAL_ERR_ALGID); prv.id = algId; ASSERT_EQ(CRYPT_EAL_PkeySetPrv(ctx, &prv), CRYPT_SUCCESS); prv.key.eccPrv.data = errorPrvKey->x; prv.key.eccPrv.len = errorPrvKey->len; ASSERT_EQ(CRYPT_EAL_PkeySetPrv(ctx, &prv), CRYPT_ECC_PKEY_ERR_INVALID_PRIVATE_KEY); ret = SUCCESS; EXIT: CRYPT_EAL_PkeyFreeCtx(ctx); return ret; } int EAL_PkeySetPrv_Api_TC002(int algId, Hex *prvKey, Hex *pubKeyX, Hex *pubKeyY) { int ret = ERROR; CRYPT_EAL_PkeyCtx *ctx = NULL; CRYPT_EAL_PkeyPrv prv = {0}; CRYPT_EAL_PkeyPub pub1, pub2; KeyData pubKeyVector = {{0}, KEY_MAX_LEN}; KeyData pubKeyVector2 = {{0}, KEY_MAX_LEN}; TestMemInit(); /* Create a key structure. */ ctx = CRYPT_EAL_PkeyNewCtx(algId); ASSERT_TRUE_AND_LOG("NewCtx", ctx != NULL); ASSERT_TRUE(CRYPT_EAL_PkeySetParaById(ctx, CRYPT_ECC_NISTP224) == CRYPT_SUCCESS); /* Set the public key. */ ASSERT_TRUE_AND_LOG("EccPointToBuffer", EccPointToBuffer(pubKeyX, pubKeyY, CRYPT_POINT_UNCOMPRESSED, &pubKeyVector) == CRYPT_SUCCESS); Ecc_SetPubKey(&pub1, algId, pubKeyVector.data, pubKeyVector.len); ASSERT_EQ(CRYPT_EAL_PkeySetPub(ctx, &pub1), CRYPT_SUCCESS); /* Set the private key. */ Ecc_SetPrvKey(&prv, algId, prvKey->x, prvKey->len); ASSERT_EQ(CRYPT_EAL_PkeySetPrv(ctx, &prv), CRYPT_SUCCESS); /* Get the public key. */ Ecc_SetPubKey(&pub2, algId, pubKeyVector2.data, pubKeyVector2.len); ASSERT_EQ(CRYPT_EAL_PkeyGetPub(ctx, &pub2), CRYPT_SUCCESS); ret = SUCCESS; EXIT: CRYPT_EAL_PkeyFreeCtx(ctx); return ret; } int EAL_PkeySetPub_Api_TC001(int algId, Hex *pubKeyVector) { int ret = ERROR; CRYPT_EAL_PkeyCtx *ctx = NULL; CRYPT_EAL_PkeyPub pub; TestMemInit(); /* Create a key structure. */ ctx = CRYPT_EAL_PkeyNewCtx(algId); ASSERT_TRUE_AND_LOG("NewCtx", ctx != NULL); Ecc_SetPubKey(&pub, algId, pubKeyVector->x, pubKeyVector->len); /* Set the pubilc key without curve. */ ASSERT_EQ(CRYPT_EAL_PkeySetPub(ctx, &pub), CRYPT_NULL_INPUT); ASSERT_TRUE(CRYPT_EAL_PkeySetParaById(ctx, CRYPT_ECC_NISTP224) == CRYPT_SUCCESS); /* Input parameter test of CRYPT_EAL_PkeySetPub. */ ASSERT_EQ(CRYPT_EAL_PkeySetPub(NULL, &pub), CRYPT_NULL_INPUT); ASSERT_EQ(CRYPT_EAL_PkeySetPub(ctx, NULL), CRYPT_NULL_INPUT); pub.id = CRYPT_PKEY_DH; ASSERT_EQ(CRYPT_EAL_PkeySetPub(ctx, &pub), CRYPT_EAL_ERR_ALGID); pub.id = algId; ASSERT_EQ(CRYPT_EAL_PkeySetPub(ctx, &pub), CRYPT_SUCCESS); ret = SUCCESS; EXIT: CRYPT_EAL_PkeyFreeCtx(ctx); return ret; } int EAL_PkeySetPub_Api_TC002(int algId, Hex *prvKey, Hex *pubKey) { int ret = ERROR; CRYPT_EAL_PkeyCtx *ctx = NULL; CRYPT_EAL_PkeyPrv prv1, prv2; (void)memset_s(&prv1.key.rsaPrv, sizeof(prv1.key.rsaPrv), 0, sizeof(prv1.key.rsaPrv)); (void)memset_s(&prv2.key.rsaPrv, sizeof(prv2.key.rsaPrv), 0, sizeof(prv2.key.rsaPrv)); CRYPT_EAL_PkeyPub ecdsaPubkey; KeyData pubKeyVector = {{0}, KEY_MAX_LEN}; TestMemInit(); /* Create a key structure. */ ctx = CRYPT_EAL_PkeyNewCtx(algId); ASSERT_TRUE_AND_LOG("NewCtx", ctx != NULL); ASSERT_TRUE(CRYPT_EAL_PkeySetParaById(ctx, CRYPT_ECC_NISTP224) == CRYPT_SUCCESS); /* Set the private key. */ Ecc_SetPrvKey(&prv1, algId, prvKey->x, prvKey->len); ASSERT_EQ(CRYPT_EAL_PkeySetPrv(ctx, &prv1), CRYPT_SUCCESS); /* Set the public key. */ Ecc_SetPubKey(&ecdsaPubkey, algId, pubKey->x, pubKey->len); ASSERT_EQ(CRYPT_EAL_PkeySetPub(ctx, &ecdsaPubkey), CRYPT_SUCCESS); /* Get the private key. */ Ecc_SetPrvKey(&prv2, algId, pubKeyVector.data, pubKeyVector.len); ASSERT_EQ(CRYPT_EAL_PkeyGetPrv(ctx, &prv2), CRYPT_SUCCESS); ret = SUCCESS; EXIT: CRYPT_EAL_PkeyFreeCtx(ctx); return ret; } int EAL_PkeySetPub_Api_TC003(int algId, int eccId, Hex *pubKey, Hex *errorPubKey, int isProvider) { CRYPT_EAL_PkeyCtx *pkey = NULL; CRYPT_EAL_PkeyPub pub = {0}; TestMemInit(); /* Create a key structure. */ pkey = TestPkeyNewCtx(NULL, algId, CRYPT_EAL_PKEY_KEYMGMT_OPERATE, "provider=default", isProvider); ASSERT_TRUE_AND_LOG("NewCtx", pkey != NULL); ASSERT_TRUE(CRYPT_EAL_PkeySetParaById(pkey, eccId) == CRYPT_SUCCESS); /* Constructing a public key that is too long. */ pub.id = algId; pub.key.eccPub.data = (uint8_t *)malloc(GetPubKeyLen(eccId) + 1); // Allocate for 1 more byte. ASSERT_TRUE(pub.key.eccPub.data != NULL); pub.key.eccPub.len = GetPubKeyLen(eccId) + 1; ASSERT_EQ(CRYPT_EAL_PkeySetPub(pkey, &pub), CRYPT_ECC_ERR_POINT_CODE); free(pub.key.eccPub.data); /* Constructing a public key that is too short. */ pub.id = algId; pub.key.eccPub.data = (uint8_t *)malloc(GetPubKeyLen(eccId) - 1); // Allocate 1 byte less. ASSERT_TRUE(pub.key.eccPub.data != NULL); pub.key.eccPub.len = GetPubKeyLen(eccId) - 1; ASSERT_EQ(CRYPT_EAL_PkeySetPub(pkey, &pub), CRYPT_ECC_ERR_POINT_CODE); free(pub.key.eccPub.data); pub.key.eccPub.data = NULL; /* Abnormal public key point: The length is abnormal. */ if (pubKey->x != NULL) { Ecc_SetPubKey(&pub, algId, pubKey->x, pubKey->len); ASSERT_EQ(CRYPT_EAL_PkeySetPub(pkey, &pub), CRYPT_ECC_ERR_POINT_CODE); } if (errorPubKey->x != NULL) { Ecc_SetPubKey(&pub, algId, errorPubKey->x, errorPubKey->len); ASSERT_EQ(CRYPT_EAL_PkeySetPub(pkey, &pub), CRYPT_ECC_POINT_NOT_ON_CURVE); } CRYPT_EAL_PkeyFreeCtx(pkey); return SUCCESS; EXIT: if (pub.key.eccPub.data != NULL) { free(pub.key.eccPub.data); } CRYPT_EAL_PkeyFreeCtx(pkey); return ERROR; } int EAL_PkeyGetParaId_Api_TC001(int algId, int paraId) { int ret = ERROR; CRYPT_EAL_PkeyCtx *pkey = NULL; TestMemInit(); ASSERT_TRUE(CRYPT_EAL_PkeyGetParaId(pkey) == CRYPT_PKEY_PARAID_MAX); pkey = CRYPT_EAL_PkeyNewCtx(algId); ASSERT_TRUE(pkey != NULL); ASSERT_TRUE(CRYPT_EAL_PkeyGetParaId(pkey) == CRYPT_PKEY_PARAID_MAX); ASSERT_TRUE(CRYPT_EAL_PkeySetParaById(pkey, (CRYPT_PKEY_ParaId)paraId) == CRYPT_SUCCESS); ASSERT_TRUE(CRYPT_EAL_PkeyGetParaId(pkey) == (CRYPT_PKEY_ParaId)paraId); ret = SUCCESS; EXIT: CRYPT_EAL_PkeyFreeCtx(pkey); return ret; } int EAL_PkeyCmp_Api_TC001(int algId, Hex *pubKeyX, Hex *pubKeyY) { int ret = ERROR; CRYPT_EAL_PkeyPub pub = {0}; KeyData pubkey = {{0}, KEY_MAX_LEN}; TestMemInit(); ASSERT_EQ(TestRandInit(), CRYPT_SUCCESS); CRYPT_EAL_PkeyCtx *ctx1 = CRYPT_EAL_PkeyNewCtx(algId); CRYPT_EAL_PkeyCtx *ctx2 = CRYPT_EAL_PkeyNewCtx(algId); ASSERT_TRUE(ctx1 != NULL && ctx2 != NULL); ASSERT_EQ(CRYPT_EAL_PkeyCmp(ctx1, ctx2), CRYPT_ECC_KEY_PUBKEY_NOT_EQUAL); ASSERT_EQ(EccPointToBuffer(pubKeyX, pubKeyY, CRYPT_POINT_COMPRESSED, &pubkey), CRYPT_SUCCESS); Ecc_SetPubKey(&pub, algId, pubkey.data, pubkey.len); ASSERT_EQ(CRYPT_EAL_PkeySetParaById(ctx1, CRYPT_ECC_NISTP224), CRYPT_SUCCESS); ASSERT_EQ(CRYPT_EAL_PkeySetPub(ctx1, &pub), CRYPT_SUCCESS); ASSERT_EQ(CRYPT_EAL_PkeyCmp(ctx1, ctx2), CRYPT_ECC_KEY_PUBKEY_NOT_EQUAL); ASSERT_EQ(CRYPT_EAL_PkeySetParaById(ctx2, CRYPT_ECC_NISTP256), CRYPT_SUCCESS); ASSERT_EQ(CRYPT_EAL_PkeySetPub(ctx2, &pub), CRYPT_ECC_ERR_POINT_CODE); ASSERT_EQ(CRYPT_EAL_PkeySetParaById(ctx2, CRYPT_ECC_NISTP224), CRYPT_SUCCESS); ASSERT_EQ(CRYPT_EAL_PkeySetPub(ctx2, &pub), CRYPT_SUCCESS); ASSERT_EQ(CRYPT_EAL_PkeyCmp(ctx1, ctx2), CRYPT_SUCCESS); ret = SUCCESS; EXIT: TestRandDeInit(); CRYPT_EAL_PkeyFreeCtx(ctx1); CRYPT_EAL_PkeyFreeCtx(ctx2); return ret; } int EAL_PkeyCmp_Provider_Api_TC001(int algId, Hex *pubKeyX, Hex *pubKeyY) { int ret = ERROR; CRYPT_EAL_PkeyPub pub = {0}; KeyData pubkey = {{0}, KEY_MAX_LEN}; TestMemInit(); ASSERT_EQ(TestRandInit(), CRYPT_SUCCESS); CRYPT_EAL_PkeyCtx *ctx1 = TestPkeyNewCtx(NULL, algId, CRYPT_EAL_PKEY_KEYMGMT_OPERATE + CRYPT_EAL_PKEY_SIGN_OPERATE, "provider=default", true); CRYPT_EAL_PkeyCtx *ctx2 = TestPkeyNewCtx(NULL, algId, CRYPT_EAL_PKEY_KEYMGMT_OPERATE + CRYPT_EAL_PKEY_SIGN_OPERATE, "provider=default", true); ASSERT_TRUE(ctx1 != NULL && ctx2 != NULL); ASSERT_EQ(CRYPT_EAL_PkeyCmp(ctx1, ctx2), CRYPT_ECC_KEY_PUBKEY_NOT_EQUAL); ASSERT_EQ(EccPointToBuffer(pubKeyX, pubKeyY, CRYPT_POINT_COMPRESSED, &pubkey), CRYPT_SUCCESS); Ecc_SetPubKey(&pub, algId, pubkey.data, pubkey.len); ASSERT_EQ(CRYPT_EAL_PkeySetParaById(ctx1, CRYPT_ECC_NISTP224), CRYPT_SUCCESS); ASSERT_EQ(CRYPT_EAL_PkeySetPub(ctx1, &pub), CRYPT_SUCCESS); ASSERT_EQ(CRYPT_EAL_PkeyCmp(ctx1, ctx2), CRYPT_ECC_KEY_PUBKEY_NOT_EQUAL); ASSERT_EQ(CRYPT_EAL_PkeySetParaById(ctx2, CRYPT_ECC_NISTP256), CRYPT_SUCCESS); ASSERT_EQ(CRYPT_EAL_PkeySetPub(ctx2, &pub), CRYPT_ECC_ERR_POINT_CODE); ASSERT_EQ(CRYPT_EAL_PkeySetParaById(ctx2, CRYPT_ECC_NISTP224), CRYPT_SUCCESS); ASSERT_EQ(CRYPT_EAL_PkeySetPub(ctx2, &pub), CRYPT_SUCCESS); ASSERT_EQ(CRYPT_EAL_PkeyCmp(ctx1, ctx2), CRYPT_SUCCESS); ret = SUCCESS; EXIT: TestRandDeInit(); CRYPT_EAL_PkeyFreeCtx(ctx1); CRYPT_EAL_PkeyFreeCtx(ctx2); return ret; } int EAL_PkeyGetPara_Func_TC001(int algId, Hex *p, Hex *a, Hex *b, Hex *x, Hex *y, Hex *n, Hex *h) { int ret = ERROR; CRYPT_EAL_PkeyCtx *ctx = NULL; uint8_t pData[ECC_MAX_BIT_LEN] = {0}; uint8_t aData[ECC_MAX_BIT_LEN] = {0}; uint8_t bData[ECC_MAX_BIT_LEN] = {0}; uint8_t nData[ECC_MAX_BIT_LEN] = {0}; uint8_t xData[ECC_MAX_BIT_LEN] = {0}; uint8_t yData[ECC_MAX_BIT_LEN] = {0}; uint8_t hData[ECC_MAX_BIT_LEN] = {0}; CRYPT_EAL_PkeyPara eccPara = { .id = algId, .para.eccPara.a = a->x, .para.eccPara.aLen = a->len, .para.eccPara.b = b->x, .para.eccPara.bLen = b->len, .para.eccPara.n = n->x, .para.eccPara.nLen = n->len, .para.eccPara.p = p->x, .para.eccPara.pLen = p->len, .para.eccPara.x = x->x, .para.eccPara.xLen = x->len, .para.eccPara.y = y->x, .para.eccPara.yLen = y->len, .para.eccPara.h = h->x, .para.eccPara.hLen = h->len, }; CRYPT_EAL_PkeyPara para = {.id = algId, .para.eccPara.a = aData, .para.eccPara.aLen = ECC_MAX_BIT_LEN, .para.eccPara.b = bData, .para.eccPara.bLen = ECC_MAX_BIT_LEN, .para.eccPara.n = nData, .para.eccPara.nLen = ECC_MAX_BIT_LEN, .para.eccPara.p = pData, .para.eccPara.pLen = ECC_MAX_BIT_LEN, .para.eccPara.x = xData, .para.eccPara.xLen = ECC_MAX_BIT_LEN, .para.eccPara.y = yData, .para.eccPara.yLen = ECC_MAX_BIT_LEN, .para.eccPara.h = hData, .para.eccPara.hLen = ECC_MAX_BIT_LEN}; TestMemInit(); ctx = CRYPT_EAL_PkeyNewCtx(algId); ASSERT_TRUE(ctx != NULL); /* Set and get elliptic curve */ ASSERT_EQ(CRYPT_EAL_PkeySetPara(ctx, &eccPara), CRYPT_SUCCESS); ASSERT_EQ(CRYPT_EAL_PkeyGetPara(ctx, &para), CRYPT_SUCCESS); ASSERT_TRUE(para.para.eccPara.aLen == a->len); ASSERT_TRUE(memcmp(aData, a->x, a->len) == 0); ASSERT_TRUE(para.para.eccPara.bLen == b->len); ASSERT_TRUE(memcmp(bData, b->x, b->len) == 0); ASSERT_TRUE(para.para.eccPara.nLen == n->len); ASSERT_TRUE(memcmp(nData, n->x, n->len) == 0); ASSERT_TRUE(para.para.eccPara.pLen == p->len); ASSERT_TRUE(memcmp(pData, p->x, p->len) == 0); ASSERT_TRUE(para.para.eccPara.xLen == x->len); ASSERT_TRUE(memcmp(xData, x->x, x->len) == 0); ASSERT_TRUE(para.para.eccPara.yLen == y->len); ASSERT_TRUE(memcmp(yData, y->x, y->len) == 0); ASSERT_TRUE(para.para.eccPara.hLen == h->len); ASSERT_TRUE(memcmp(hData, h->x, h->len) == 0); ret = SUCCESS; EXIT: CRYPT_EAL_PkeyFreeCtx(ctx); return ret; }
2301_79861745/bench_create
testcode/sdv/testcase/crypto/ecc/test_suite_sdv_eal_ecc.base.c
C
unknown
33,252
/* * This file is part of the openHiTLS project. * * openHiTLS is licensed under the Mulan PSL v2. * You can use this software according to the terms and conditions of the Mulan PSL v2. * You may obtain a copy of Mulan PSL v2 at: * * http://license.coscl.org.cn/MulanPSL2 * * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, * EITHER EXPRESS 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 test_suite_sdv_eal_ecc */ /* BEGIN_HEADER */ #include "crypt_ecc.h" #include "ecc_local.h" /* END_HEADER */ #define ECDH_MAX_BIT_LEN 521 /** * @test SDV_CRYPTO_ECDH_NEW_CTX_API_TC001 * @title ECDH CRYPT_EAL_PkeyNewCtx test. * @precon Registering memory-related functions. * @brief * 1. Call the CRYPT_EAL_PkeyNewCtx method to create a pkey structure, algId is CRYPT_PKEY_ECDH, expected result 1 * 2. Releases the pkey structure, expected result 2 * @expect * 1. Success, and the structure is not NULL. * 2. No memory leakage occurs. */ /* BEGIN_CASE */ void SDV_CRYPTO_ECDH_NEW_CTX_API_TC001(void) { ASSERT_TRUE(EAL_PkeyNewCtx_Api_TC001(CRYPT_PKEY_ECDH) == SUCCESS); EXIT: return; } /* END_CASE */ /** * @test SDV_CRYPTO_ECDH_SET_PARA_BY_ID_API_TC001 * @title ECDH CRYPT_EAL_PkeySetParaById: Test the validity of input parameters. * @precon Registering memory-related functions. * @brief * 1. Create the context of the ecdh algorithm, expected result 1 * 2. Call the CRYPT_EAL_PkeySetParaById method: * (1) context = NULL, expected result 2. * (2) CRYPT_PKEY_ParaId = CRYPT_ECC_NISTP224, expected result 3. * (3) CRYPT_PKEY_ParaId = CRYPT_ECC_NISTP256, expected result 3. * (4) CRYPT_PKEY_ParaId = CRYPT_ECC_NISTP384, expected result 3. * (5) CRYPT_PKEY_ParaId = CRYPT_ECC_NISTP521, expected result 3. * (6) CRYPT_PKEY_ParaId = CRYPT_ECC_BRAINPOOLP256R1, expected result 3. * (7) CRYPT_PKEY_ParaId = CRYPT_ECC_BRAINPOOLP384R1, expected result 3. * (8) CRYPT_PKEY_ParaId = CRYPT_ECC_BRAINPOOLP512R1, expected result 3. * @expect * 1. Success, and the context is not NULL. * 2. CRYPT_NULL_INPUT * 3. CRYPT_SUCCESS */ /* BEGIN_CASE */ void SDV_CRYPTO_ECDH_SET_PARA_BY_ID_API_TC001(void) { ASSERT_TRUE(EAL_PkeySetParaById_Api_TC001(CRYPT_PKEY_ECDH) == SUCCESS); EXIT: return; } /* END_CASE */ /** * @test SDV_CRYPTO_ECDH_EXCH_API_TC001 * @title ECDH CRYPT_EAL_PkeyComputeShareKey: Test the validity of parameters. * @precon Registering memory-related functions. * Test Vectors for ECDH : public key, private key, share secret * @brief * 1. Create two contexts(ecdhPkey, ecdhPkey2, peerEcdhPkey) of the ECDH algorithm, expected result 1 * 2. ecdhPkey: Set elliptic curve type and private key, expected result 2 * 3. peerEcdhPkey: Set elliptic curve type and public key, expected result 3 * 4. Call the CRYPT_EAL_PkeyComputeShareKey method before init the drbg, expected result 4: * 5. Call the CRYPT_EAL_PkeyComputeShareKey method: * (1) pkey = NULL, expected result 5 * (2) pubPkey = NULL, expected result 6 * (3) share = NULL, shareLen != 0, expected result 7 * (4) share != NULL, shareLen = NULL, expected result 8 * (5) share != NULL, shareLen = 1, expected result 9 * (6) all parameters are valid, but the local ctx does not have a private key, expected result 10 * (7) pkey.id != pubPkey.id, expected result 11 * (8) all parameters are valid, expected result 12 * @expect * 1. Success, and contexts are not NULL. * 2-3. CRYPT_SUCCESS * 4. CRYPT_NO_REGIST_RAND * 5-8. CRYPT_NULL_INPUT * 9. CRYPT_ECC_BUFF_LEN_NOT_ENOUGH * 10. CRYPT_ECDH_ERR_EMPTY_KEY * 11. CRYPT_EAL_ERR_ALGID * 12. CRYPT_SUCCESS */ /* BEGIN_CASE */ void SDV_CRYPTO_ECDH_EXCH_API_TC001(Hex *prvKeyVector, Hex *peerPubKeyVector, Hex *shareKeyVector) { CRYPT_EAL_PkeyCtx *ecdhPkey = NULL; CRYPT_EAL_PkeyCtx *ecdhPkey2 = NULL; CRYPT_EAL_PkeyCtx *peerEcdhPkey = NULL; CRYPT_EAL_PkeyPrv ecdhPrvkey = {0}; CRYPT_EAL_PkeyPub peerEcdhPubkey; uint8_t *shareKey = NULL; uint32_t shareKeyLen; TestMemInit(); ecdhPkey = CRYPT_EAL_PkeyNewCtx(CRYPT_PKEY_ECDH); ecdhPkey2 = CRYPT_EAL_PkeyNewCtx(CRYPT_PKEY_ECDH); peerEcdhPkey = CRYPT_EAL_PkeyNewCtx(CRYPT_PKEY_ECDH); ASSERT_TRUE(ecdhPkey != NULL && ecdhPkey2 != NULL && peerEcdhPkey != NULL); /* Local: Set elliptic curve type and private key. */ ASSERT_EQ(CRYPT_EAL_PkeySetParaById(ecdhPkey, CRYPT_ECC_NISTP256), CRYPT_SUCCESS); Ecc_SetPrvKey(&ecdhPrvkey, CRYPT_PKEY_ECDH, prvKeyVector->x, prvKeyVector->len); ASSERT_EQ(CRYPT_EAL_PkeySetPrv(ecdhPkey, &ecdhPrvkey), CRYPT_SUCCESS); /* Peer: Set elliptic curve type and public key. */ ASSERT_EQ(CRYPT_EAL_PkeySetParaById(peerEcdhPkey, CRYPT_ECC_NISTP256), CRYPT_SUCCESS); Ecc_SetPubKey(&peerEcdhPubkey, CRYPT_PKEY_ECDH, peerPubKeyVector->x, peerPubKeyVector->len); ASSERT_EQ(CRYPT_EAL_PkeySetPub(peerEcdhPkey, &peerEcdhPubkey), CRYPT_SUCCESS); /* Input parameter test of CRYPT_EAL_PkeyComputeShareKey. */ shareKey = (uint8_t *)malloc(shareKeyVector->len); ASSERT_TRUE(shareKey != NULL); shareKeyLen = shareKeyVector->len; ASSERT_EQ(TestRandInit(), CRYPT_SUCCESS); ASSERT_EQ(CRYPT_EAL_PkeyComputeShareKey(NULL, peerEcdhPkey, shareKey, &shareKeyLen), CRYPT_NULL_INPUT); ASSERT_EQ(CRYPT_EAL_PkeyComputeShareKey(ecdhPkey, NULL, shareKey, &shareKeyLen), CRYPT_NULL_INPUT); ASSERT_EQ(CRYPT_EAL_PkeyComputeShareKey(ecdhPkey, peerEcdhPkey, NULL, &shareKeyLen), CRYPT_NULL_INPUT); ASSERT_EQ(CRYPT_EAL_PkeyComputeShareKey(ecdhPkey, peerEcdhPkey, shareKey, NULL), CRYPT_NULL_INPUT); shareKeyLen = 1; // 1 is invalid ASSERT_EQ( CRYPT_EAL_PkeyComputeShareKey(ecdhPkey, peerEcdhPkey, shareKey, &shareKeyLen), CRYPT_ECC_BUFF_LEN_NOT_ENOUGH); ASSERT_EQ(CRYPT_EAL_PkeyComputeShareKey(ecdhPkey2, peerEcdhPkey, shareKey, &shareKeyLen), CRYPT_ECDH_ERR_EMPTY_KEY); ecdhPkey->id = CRYPT_PKEY_DH; ASSERT_EQ(CRYPT_EAL_PkeyComputeShareKey(ecdhPkey, peerEcdhPkey, shareKey, &shareKeyLen), CRYPT_EAL_ERR_ALGID); ecdhPkey->id = CRYPT_PKEY_ECDH; shareKeyLen = shareKeyVector->len; ASSERT_EQ(CRYPT_EAL_PkeyComputeShareKey(ecdhPkey, peerEcdhPkey, shareKey, &shareKeyLen), CRYPT_SUCCESS); EXIT: free(shareKey); CRYPT_EAL_PkeyFreeCtx(ecdhPkey); CRYPT_EAL_PkeyFreeCtx(ecdhPkey2); CRYPT_EAL_PkeyFreeCtx(peerEcdhPkey); TestRandDeInit(); return; } /* END_CASE */ /** * @test SDV_CRYPTO_ECDH_CTRL_API_TC001 * @title ECDH CRYPT_EAL_PkeyCtrl: Test the validity of opt. * @precon Registering memory-related functions. * @brief * 1. Create the context of the ecdh algorithm, expected result 1 * 2. Call the CRYPT_EAL_PkeyCtrl method: * (1) opt = CRYPT_CTRL_SET_RSA_RSAES_PKCSV15, expected result 2 * (2) opt = CRYPT_CTRL_SET_ECC_POINT_FORMAT, expected result 3 * (3) opt = CRYPT_CTRL_SET_ECC_USE_COFACTOR_MODE, expected result 4 * (4) opt = CRYPT_CTRL_SET_SM2_USER_ID, expected result 5 * (5) opt = CRYPT_CTRL_SET_RSA_PADDING, expected result 6 * @expect * 1. Success, and the context is not NULL. * 2. CRYPT_ECC_PKEY_ERR_UNSUPPORTED_CTRL_OPTION * 3. CRYPT_SUCCESS * 4. CRYPT_SUCCESS * 5. CRYPT_ECC_PKEY_ERR_UNSUPPORTED_CTRL_OPTION * 6. CRYPT_ECC_PKEY_ERR_UNSUPPORTED_CTRL_OPTION */ /* BEGIN_CASE */ void SDV_CRYPTO_ECDH_CTRL_API_TC001(int type, int expect) { ASSERT_TRUE(EAL_PkeyCtrl_Api_TC001(CRYPT_PKEY_ECDH, type, expect) == SUCCESS); EXIT: return; } /* END_CASE */ /** * @test SDV_CRYPTO_ECDH_CTRL_API_TC002 * @title ECDH CRYPT_EAL_PkeyCtrl: Test the validity of pkey and value. * @precon Registering memory-related functions. * @brief * 1. Create the context of the ecdh algorithm, expected result 1 * 2. Call the CRYPT_EAL_PkeyCtrl method: * (1) pkey = null, expected result 2 * (2) val = null, len = 0, expected result 3 * (3) val = null, len != 0, expected result 4 * (4) val != null, len = 0, expected result 5 * (5) PointFormat = CRYPT_POINT_MAX, expected result 6 * (6) PointFormat = CRYPT_POINT_COMPRESSED, expected result 7 * (7) PointFormat = CRYPT_POINT_UNCOMPRESSED, expected result 8 * (8) PointFormat = CRYPT_POINT_HYBRID, expected result 9 * @expect * 1. Success, and the context is not NULL. * 2-4. CRYPT_NULL_INPUT * 5. CRYPT_ECC_PKEY_ERR_CTRL_LEN * 6. CRYPT_ECC_PKEY_ERR_INVALID_POINT_FORMAT * 7-9. CRYPT_SUCCESS */ /* BEGIN_CASE */ void SDV_CRYPTO_ECDH_CTRL_API_TC002(void) { ASSERT_TRUE(EAL_PkeyCtrl_Api_TC002(CRYPT_PKEY_ECDH) == 0); EXIT: return; } /* END_CASE */ /** * @test SDV_CRYPTO_ECDH_CTRL_API_TC003 * @title ECDH CRYPT_EAL_PkeyCtrl: Test the effect of the point format on the key. * @precon Registering memory-related functions. * public key point * @brief * 1. Create the context of the ecdh algorithm, expected result 1 * 2. Set the para by eccId(p-224/256/384/512, bp256r1/384r1/512/r1), expected result 2 * 3. Convert the format of the public key vector to COMPRESSED, expected result 3 * 4. Set the public key, expected result 4 * 5. Call the CRYPT_EAL_PkeyCtrl method to set point format to COMPRESSED, expected result 5 * 6. Call the CRYPT_EAL_PkeyCtrl method to set point format to HYBRID, expected result 6 * 7. Get the public key, expected result 7 * 8. Convert the format of the public key vector to HYBRID, expected result 8 * 9. Compare the output of the preceding two steps, expected result 9 * @expect * 1. Success, and the context is not NULL. * 2-8. CRYPT_SUCCESS * 9. The two are same. */ /* BEGIN_CASE */ void SDV_CRYPTO_ECDH_CTRL_API_TC003(int eccId, Hex *pubKeyX, Hex *pubKeyY) { if (IsCurveDisabled(eccId)) { SKIP_TEST(); } ASSERT_TRUE(EAL_PkeyCtrl_Api_TC003(CRYPT_PKEY_ECDH, eccId, pubKeyX, pubKeyY) == 0); EXIT: return; } /* END_CASE */ /** * @test SDV_CRYPTO_ECDH_GET_PRV_API_TC001 * @title ECDH CRYPT_EAL_PkeyGetPrv: Test the validity of parameters. * @precon Registering memory-related functions. * private key * @brief * 1. Create the context of the ecdh algorithm, expected result 1 * 2. Set the para by eccId(p-224), expected result 2 * 3. Get the private key when there is no private key, expected result 3 * 4. Set the private key, expected result 4 * 5. Call the CRYPT_EAL_PkeyGetPrv method: * (1) pkey = null, expected result 5 * (2) prv = null, expected result 6 * (3) pkey.id != prv.id, expected result 7 * (4) Correct parameters., expected result 8 * @expect * 1. Success, and the context is not NULL. * 2. CRYPT_SUCCESS * 3. CRYPT_ECC_PKEY_ERR_EMPTY_KEY * 4. CRYPT_SUCCESS * 5-6. CRYPT_NULL_INPUT * 7. CRYPT_EAL_ERR_ALGID * 8. CRYPT_SUCCESS */ /* BEGIN_CASE */ void SDV_CRYPTO_ECDH_GET_PRV_API_TC001(Hex *prvKey) { ASSERT_TRUE(EAL_PkeyGetPrv_Api_TC001(CRYPT_PKEY_ECDH, prvKey) == 0); EXIT: return; } /* END_CASE */ /** * @test SDV_CRYPTO_ECDH_GET_PUB_API_TC001 * @title ECDH CRYPT_EAL_PkeyGetPub: Test the validity of parameters. * @precon Registering memory-related functions. * public key point * @brief * 1. Create the context of the ecdh algorithm, expected result 1 * 2. Set the para by eccId(p-224), expected result 2 * 3. Get the public key when there is no public key, expected result 3 * 4. Set the public key, expected result 4 * 5. Call the CRYPT_EAL_PkeyGetPub method: * (1) pkey = null, expected result 5 * (2) pub = null, expected result 6 * (3) pkey.id != pub.id, expected result 7 * (4) Correct parameters, expected result 8 * @expect * 1. Success, and the context is not NULL. * 2. CRYPT_SUCCESS * 3. CRYPT_ECC_PKEY_ERR_EMPTY_KEY * 4. CRYPT_SUCCESS * 5-6. CRYPT_NULL_INPUT * 7. CRYPT_EAL_ERR_ALGID * 8. CRYPT_SUCCESS */ /* BEGIN_CASE */ void SDV_CRYPTO_ECDH_GET_PUB_API_TC001(Hex *pubKeyX, Hex *pubKeyY) { ASSERT_TRUE(EAL_PkeyGetPub_Api_TC001(CRYPT_PKEY_ECDH, pubKeyX, pubKeyY) == 0); EXIT: return; } /* END_CASE */ /** * @test SDV_CRYPTO_ECDH_SET_PRV_API_TC001 * @title ECDH CRYPT_EAL_PkeySetPrv: Test the validity of parameters. * @precon Registering memory-related functions. * Prepare valid private key and invalid private key. * @brief * 1. Create the context of the ecdh algorithm, expected result 1 * 2. Set the the valid private key before setting the curve, expected result 2 * 3. Set the para by eccId(p-224), expected result 3 * 4. Call the CRYPT_EAL_PkeySetPrv method: * (1) pkey = null, expected result 4 * (2) prv = null, expected result 5 * (3) pkey.id != prv.id, expected result 6 * (4) Set the valid private key, expected result 7 * (5) Set the invalid private key, expected result 8 * @expect * 1. Success, and the context is not NULL. * 2. CRYPT_NULL_INPUT * 3. CRYPT_SUCCESS * 4-5. CRYPT_NULL_INPUT * 6. CRYPT_EAL_ERR_ALGID * 7. CRYPT_SUCCESS * 8. CRYPT_ECC_PKEY_ERR_INVALID_PRIVATE_KEY */ /* BEGIN_CASE */ void SDV_CRYPTO_ECDH_SET_PRV_API_TC001(Hex *prvKey, Hex *errorPrvKey) { ASSERT_TRUE(EAL_PkeySetPrv_Api_TC001(CRYPT_PKEY_ECDH, prvKey, errorPrvKey) == 0); EXIT: return; } /* END_CASE */ /** * @test SDV_CRYPTO_ECDH_SET_PRV_API_TC002 * @title Check whether the public key is cleared when the private key is set. * @precon Registering memory-related functions. * private key, public key point * @brief * 1. Create the context of the ecdh algorithm, expected result 1 * 2. Set the para by eccId(p-224), expected result 2 * 3. Set the the public key, expected result 3 * 4. Set the the private key, expected result 4 * 5. Get the the public key, expected result 5 * @expect * 1. Success, and the context is not NULL. * 2-5. CRYPT_SUCCESSY */ /* BEGIN_CASE */ void SDV_CRYPTO_ECDH_SET_PRV_API_TC002(Hex *prvKey, Hex *pubKeyX, Hex *pubKeyY) { ASSERT_TRUE(EAL_PkeySetPrv_Api_TC002(CRYPT_PKEY_ECDH, prvKey, pubKeyX, pubKeyY) == 0); EXIT: return; } /* END_CASE */ /** * @test SDV_CRYPTO_ECDH_SET_PUB_API_TC001 * @title ECDH CRYPT_EAL_PkeySetPub: Test the validity of parameters. * @precon Prepare valid public key. * @brief * 1. Create the context of the ecdh algorithm, expected result 1 * 2. Set the the public key before setting the curve, expected result 2 * 3. Set the para by eccId(p-224), expected result 3 * 4. Call the CRYPT_EAL_PkeySetPub method: * (1) pkey = null, expected result 4 * (2) pub = null, expected result 5 * (3) pkey.id != pub.id, expected result 6 * (4) Set the valid public key, expected result 7 * @expect * 1. Success, and the context is not NULL. * 2. CRYPT_NULL_INPUT * 3. CRYPT_SUCCESS * 4-5. CRYPT_NULL_INPUT * 6. CRYPT_EAL_ERR_ALGID * 7. CRYPT_SUCCESS */ /* BEGIN_CASE */ void SDV_CRYPTO_ECDH_SET_PUB_API_TC001(Hex *pubKeyVector) { ASSERT_TRUE(EAL_PkeySetPub_Api_TC001(CRYPT_PKEY_ECDH, pubKeyVector) == 0); EXIT: return; } /* END_CASE */ /** * @test SDV_CRYPTO_ECDH_SET_PUB_API_TC002 * @title Check whether the private key is cleared when the public key is set. * @precon Registering memory-related functions. * public key, private key * @brief * 1. Create the context of the ecdh algorithm, expected result 1 * 2. Set the para by eccId(p-224), expected result 2 * 3. Set the the private key, expected result 3 * 4. Set the the public key, expected result 4 * 5. Get the the private key, expected result 5 * @expect * 1. Success, and the context is not NULL. * 2-5. CRYPT_SUCCESSY */ /* BEGIN_CASE */ void SDV_CRYPTO_ECDH_SET_PUB_API_TC002(Hex *prvKey, Hex *pubKey) { ASSERT_TRUE(EAL_PkeySetPub_Api_TC002(CRYPT_PKEY_ECDH, prvKey, pubKey) == 0); EXIT: return; } /* END_CASE */ /** * @test SDV_CRYPTO_ECDH_SET_PUB_API_TC003 * @title Test the function of setting public keys of different lengths. * @precon Public keys of different lengths. * @brief * 1. Create the context of the ecdh algorithm, expected result 1 * 2. Set the para by eccId(p-224/256/384/512, bp256r1/384r1/512/r1), expected result 2 * 3. Set public keys of different lengths, expected result 3 * @expect * 1. Success, and the context is not NULL. * 2. CRYPT_SUCCESSY * 3. CRYPT_ECC_ERR_POINT_CODE */ /* BEGIN_CASE */ void SDV_CRYPTO_ECDH_SET_PUB_API_TC003(int eccId, Hex *pubKey, Hex *errorPubKey, int isProvider) { ASSERT_TRUE(EAL_PkeySetPub_Api_TC003(CRYPT_PKEY_ECDSA, eccId, pubKey, errorPubKey, isProvider) == 0); EXIT: return; } /* END_CASE */ /** * @test SDV_CRYPTO_ECDH_GET_PARA_ID_API_TC001 * @title ECDH CRYPT_EAL_PkeyGetParaId test. * @precon Registering memory-related functions. * @brief * 1. Get para id before creating context, expected result 1 * 1. Create the context of the ecdh algorithm, expected result 2 * 2. Set para id(p-224/256/384/512), expected result 3 * 3. Get para id, expected result 4 * @expect * 1. CRYPT_PKEY_PARAID_MAX * 2. Success, and the context is not NULL. * 3. CRYPT_SUCCESS * 4. The obtained id is the same as the set id. */ /* BEGIN_CASE */ void SDV_CRYPTO_ECDH_GET_PARA_ID_API_TC001(int id) { ASSERT_TRUE(EAL_PkeyGetParaId_Api_TC001(CRYPT_PKEY_ECDH, id) == 0); EXIT: return; } /* END_CASE */ /** * @test SDV_CRYPTO_ECDH_DUP_CTX_API_TC001 * @title ECDH CRYPT_EAL_PkeyDupCtx test. * @precon Registering memory-related functions. * @brief * 1. Create the context(pKeyCtx) of the ecdh algorithm, expected result 1 * 2. Set the para by eccId(p-224/256/384/512, bp256r1/384r1/512/r1), expected result 2 * 3. Call the CRYPT_EAL_PkeyDupCtx to dup context where the parameter is null, expected result 3 * 4. Call the CRYPT_EAL_PkeyDupCtx to dup context(newCtx), expected result 4 * 5. Get the reference count, expected result 5 * 6. Compare the pkey ids obtained from pKeyCtx and newCtx, , expected result 6 * 7. Compare the curve ids obtained from pKeyCtx and newCtx, expected result 7 * @expect * 1. Success, and the context is not NULL. * 2. CRYPT_SUCCESSY * 3. Return null. * 4. Return non-null. * 5. The reference count is 1. * 6-7. Both are the same. */ /* BEGIN_CASE */ void SDV_CRYPTO_ECDH_DUP_CTX_API_TC001(int paraId, int isProvider) { CRYPT_EAL_PkeyCtx *pKeyCtx = NULL; CRYPT_EAL_PkeyCtx *newCtx = NULL; pKeyCtx = TestPkeyNewCtx(NULL, CRYPT_PKEY_ECDH, CRYPT_EAL_PKEY_KEYMGMT_OPERATE, "provider=default", isProvider); ASSERT_TRUE(pKeyCtx != NULL); ASSERT_TRUE(CRYPT_EAL_PkeySetParaById(pKeyCtx, (CRYPT_PKEY_ParaId)paraId) == CRYPT_SUCCESS); ASSERT_TRUE(CRYPT_EAL_PkeyDupCtx(NULL) == NULL); newCtx = CRYPT_EAL_PkeyDupCtx(pKeyCtx); ASSERT_TRUE(newCtx != NULL); ASSERT_EQ(newCtx->references.count, 1); ASSERT_TRUE(CRYPT_EAL_PkeyGetId(pKeyCtx) == CRYPT_EAL_PkeyGetId(newCtx)); ASSERT_TRUE(CRYPT_EAL_PkeyGetParaId(pKeyCtx) == CRYPT_EAL_PkeyGetParaId(newCtx)); EXIT: CRYPT_EAL_PkeyFreeCtx(pKeyCtx); CRYPT_EAL_PkeyFreeCtx(newCtx); } /* END_CASE */ /** * @test SDV_CRYPTO_ECDH_CMP_FUNC_TC001 * @title ECDH: CRYPT_EAL_PkeyCmp test. * @precon Registering memory-related functions. * @brief * 1. Create the contexts(ctx1, ctx2) of the ecdh algorithm, expected result 1 * 2. Call the CRYPT_EAL_PkeyCmp to compare ctx1 and ctx2, expected result 2 * 3. Set para id CRYPT_ECC_NISTP224 and public key for ctx1, expected result 3 * 4. Call the CRYPT_EAL_PkeyCmp to compare ctx1 and ctx2, expected result 4 * 5. Set para id CRYPT_ECC_NISTP256 for ctx2, expected result 5 * 6. Set public key for ctx2, expected result 6 * 7. Set para id CRYPT_ECC_NISTP224 and public key for ctx2, expected result 7 * 8. Call the CRYPT_EAL_PkeyCmp to compare ctx1 and ctx2, expected result 8 * @expect * 1. Success, and contexts are not NULL. * 2. CRYPT_ECC_KEY_PUBKEY_NOT_EQUAL * 3. CRYPT_SUCCESS * 4. CRYPT_ECC_KEY_PUBKEY_NOT_EQUAL * 5. CRYPT_SUCCESS * 6. CRYPT_ECC_ERR_POINT_CODE * 7. CRYPT_SUCCESS * 8. CRYPT_SUCCESS */ /* BEGIN_CASE */ void SDV_CRYPTO_ECDH_CMP_FUNC_TC001(Hex *pubKeyX, Hex *pubKeyY) { ASSERT_TRUE(EAL_PkeyCmp_Api_TC001(CRYPT_PKEY_ECDH, pubKeyX, pubKeyY) == 0); EXIT: return; } /* END_CASE */ /** * @test SDV_CRYPTO_ECDH_EXCH_FUNC_TC001 * @title ECDH key exchange test: set the key and exchange the key. * @precon Registering memory-related functions. * @brief * 1. Create two contexts(ecdhPkey, peerEcdhPubPkey) of the ECDH algorithm, expected result 1 * 2. Init the drbg, expected result 2 * 3. ecdhPkey: Set elliptic curve type(p-224/256/384/512, bp256r1/384r1/512/r1) and private key, expected result 3 * 4. peerEcdhPubPkey: Set elliptic curve type(p-224/256/384/512, bp256r1/384r1/512/r1) and public key(compressed/ * uncompressed/hybrid), expected result 4 * 5. Compute the shared key, expected result 5 * 6. Compare the output shared secret and shared secret vector, expected result 6 * @expect * 1. Success, and two contexts are not NULL. * 2-5. CRYPT_SUCCESS * 6. The two shared secrets are the same. */ /* BEGIN_CASE */ void SDV_CRYPTO_ECDH_EXCH_FUNC_TC001( int eccId, Hex *prvKeyVector, Hex *pubKeyX, Hex *pubKeyY, int pointFormat, Hex *shareKeyVector, int isProvider) { if (IsCurveDisabled(eccId)) { SKIP_TEST(); } int ret; CRYPT_EAL_PkeyCtx *ecdhPkey = NULL; CRYPT_EAL_PkeyCtx *peerEcdhPubPkey = NULL; CRYPT_EAL_PkeyPrv ecdhPrvkey = {0}; CRYPT_EAL_PkeyPub peerEcdhPubkey; KeyData pubKeyVector = {{0}, KEY_MAX_LEN}; uint8_t *shareKey = NULL; uint32_t shareKeyLen; TestMemInit(); ASSERT_EQ(TestRandInit(), CRYPT_SUCCESS); ecdhPkey = TestPkeyNewCtx(NULL, CRYPT_PKEY_ECDH, CRYPT_EAL_PKEY_KEYMGMT_OPERATE + CRYPT_EAL_PKEY_EXCH_OPERATE, "provider=default", isProvider); peerEcdhPubPkey = CRYPT_EAL_PkeyNewCtx(CRYPT_PKEY_ECDH); ASSERT_TRUE(ecdhPkey != NULL && peerEcdhPubPkey != NULL); /* Local: Set elliptic curve type and private key. */ ASSERT_EQ(CRYPT_EAL_PkeySetParaById(ecdhPkey, eccId), CRYPT_SUCCESS); Ecc_SetPrvKey(&ecdhPrvkey, CRYPT_PKEY_ECDH, prvKeyVector->x, prvKeyVector->len); ASSERT_EQ(CRYPT_EAL_PkeySetPrv(ecdhPkey, &ecdhPrvkey), CRYPT_SUCCESS); /* Peer: Set elliptic curve type and public key. */ /* Create a key structure to store the public key. */ ret = EccPointToBuffer(pubKeyX, pubKeyY, pointFormat, &pubKeyVector); ASSERT_TRUE_AND_LOG("EccPointToVector", ret == CRYPT_SUCCESS); Ecc_SetPubKey(&peerEcdhPubkey, CRYPT_PKEY_ECDH, pubKeyVector.data, pubKeyVector.len); ASSERT_EQ(CRYPT_EAL_PkeySetParaById(peerEcdhPubPkey, eccId), CRYPT_SUCCESS); ASSERT_EQ(CRYPT_EAL_PkeySetPub(peerEcdhPubPkey, &peerEcdhPubkey), CRYPT_SUCCESS); /* Compute share secret. */ shareKeyLen = CRYPT_EAL_PkeyGetKeyLen(ecdhPkey); ASSERT_TRUE(shareKeyLen > shareKeyVector->len); shareKey = (uint8_t *)malloc(shareKeyVector->len); ASSERT_TRUE(shareKey != NULL); ASSERT_EQ(CRYPT_EAL_PkeyComputeShareKey(ecdhPkey, peerEcdhPubPkey, shareKey, &shareKeyLen), CRYPT_SUCCESS); ASSERT_TRUE_AND_LOG("Compare ShareKey Len", shareKeyLen == shareKeyVector->len); ASSERT_COMPARE("Compare ShareKey", shareKey, shareKeyLen, shareKeyVector->x, shareKeyVector->len); EXIT: CRYPT_EAL_PkeyFreeCtx(ecdhPkey); CRYPT_EAL_PkeyFreeCtx(peerEcdhPubPkey); TestRandDeInit(); free(shareKey); } /* END_CASE */ /** * @test SDV_CRYPTO_ECDH_GET_PARA_FUNC_TC001 * @title ECDH CRYPT_EAL_PkeyGetPara test. * @precon Registering memory-related functions. * @brief * 1. Create context of the ECDH algorithm, expected result 1 * 2. Set para, expected result 2 * 3. Get para, expected result 3 * 4. Check whether the set parameters and the obtained parameters are the same, expected result 4 * @expect * 1. Success, and two contexts are not NULL. * 2-3. CRYPT_SUCCESS * 4. The parameters are the same. */ /* BEGIN_CASE */ void SDV_CRYPTO_ECDH_GET_PARA_FUNC_TC001(Hex *p, Hex *a, Hex *b, Hex *x, Hex *y, Hex *n, Hex *h) { ASSERT_TRUE(EAL_PkeyGetPara_Func_TC001(CRYPT_PKEY_ECDH, p, a, b, x, y, n, h) == 0); EXIT: return; } /* END_CASE */ /** * @test SDV_CRYPTO_ECDH_GEN_KEY_FUNC_TC001 * @title ECDH CRYPT_EAL_PkeyGen test. * @precon Registering memory-related functions. * @brief * 1. Create context of the ECDH algorithm, expected result 1 * 2. Set elliptic curve type, expected result 2 * 3. Mock BN_RandRange to STUB_RandRangeK, expected result 3 * 4. Init the drbg, expected result 4 * 5. Call the CRYPT_EAL_PkeyGen method to generate a key pair, expected result 5 * 6. Get public key and private key, expected result 6 * 7. Compare the getted key and vector, expected result 7 * @expect * 1. Success, and two contexts are not NULL. * 2. CRYPT_SUCCESS * 3. SUccess. * 4-6. CRYPT_SUCCESS * 7. The getted key and vector are the same. */ /* BEGIN_CASE */ void SDV_CRYPTO_ECDH_GEN_KEY_FUNC_TC001( int eccId, Hex *prvKeyVector, Hex *pubKeyX, Hex *pubKeyY, int pointFormat, int isProvider) { if (IsCurveDisabled(eccId)) { SKIP_TEST(); } Ecc_GenKey(CRYPT_PKEY_ECDH, eccId, prvKeyVector, pubKeyX, pubKeyY, pointFormat, isProvider); } /* END_CASE */ /** * @test SDV_CRYPTO_ECDH_GET_KEY_BITS_FUNC_TC001 * @title ECDH: get key bits. * @brief * 1. Create a context of the ECDH algorithm, expected result 1 * 2. Get key bits, expected result 2 * @expect * 1. Success, and context is not NULL. * 2. Equal to keyBits. */ /* BEGIN_CASE */ void SDV_CRYPTO_ECDH_GET_KEY_BITS_FUNC_TC001(int paraid, int keyBits, int isProvider) { CRYPT_EAL_PkeyCtx *pkey = TestPkeyNewCtx(NULL, CRYPT_PKEY_ECDH, CRYPT_EAL_PKEY_KEYMGMT_OPERATE, "provider=default", isProvider); ASSERT_TRUE(pkey != NULL); ASSERT_EQ(CRYPT_EAL_PkeySetParaById(pkey, paraid), CRYPT_SUCCESS); ASSERT_TRUE(CRYPT_EAL_PkeyGetKeyBits(pkey) == (uint32_t)keyBits); EXIT: CRYPT_EAL_PkeyFreeCtx(pkey); } /* END_CASE */ /** * @test SDV_CRYPTO_ECDH_GET_SEC_BITS_FUNC_TC001 * @title ECDH CRYPT_EAL_PkeyGetSecurityBits test. * @precon nan * @brief * 1. Create the context of the ecdh algorithm, expected result 1 * 2. Set ecdh para, expected result 2 * 3. Call the CRYPT_EAL_PkeyGetSecurityBits Obtains secbits, expected result 3 * @expect * 1. Success, and the context is not null. * 2. CRYPT_SUCCESS * 3. The return value is secBits. */ /* BEGIN_CASE */ void SDV_CRYPTO_ECDH_GET_SEC_BITS_FUNC_TC001(int paraid, int secBits) { CRYPT_EAL_PkeyCtx *pkey = CRYPT_EAL_PkeyNewCtx(CRYPT_PKEY_ECDH); ASSERT_TRUE(pkey != NULL); ASSERT_EQ(CRYPT_EAL_PkeySetParaById(pkey, paraid), CRYPT_SUCCESS); ASSERT_EQ(CRYPT_EAL_PkeyGetSecurityBits(pkey), secBits); EXIT: CRYPT_EAL_PkeyFreeCtx(pkey); } /* END_CASE */ /** * @test SDV_CRYPTO_ECDH_CHECK_KEYPAIR_FUNC_TC001 * @title ECDH CRYPT_EAL_PkeyPairCheck test. */ /* BEGIN_CASE */ void SDV_CRYPTO_ECDH_CHECK_KEYPAIR_FUNC_TC001(int paraid, int isProvider) { #if !defined(HITLS_CRYPTO_ECDH_CHECK) (void)paraid; (void)isProvider; SKIP_TEST(); #else TestMemInit(); uint8_t wrong[KEY_MAX_LEN] = {1}; CRYPT_EAL_PkeyPub ecdhPubKey = {0}; CRYPT_EAL_PkeyPrv ecdhPrvKey = {0}; KeyData pubKeyVector = {{0}, KEY_MAX_LEN}; KeyData prvKeyVector = {{0}, KEY_MAX_LEN}; CRYPT_EAL_PkeyCtx *pkey = TestPkeyNewCtx(NULL, CRYPT_PKEY_ECDH, CRYPT_EAL_PKEY_KEYMGMT_OPERATE, "provider=default", isProvider); CRYPT_EAL_PkeyCtx *pubCtx = TestPkeyNewCtx(NULL, CRYPT_PKEY_ECDH, CRYPT_EAL_PKEY_KEYMGMT_OPERATE, "provider=default", isProvider); CRYPT_EAL_PkeyCtx *prvCtx = TestPkeyNewCtx(NULL, CRYPT_PKEY_ECDH, CRYPT_EAL_PKEY_KEYMGMT_OPERATE, "provider=default", isProvider); ASSERT_TRUE(pkey != NULL); ASSERT_TRUE(pubCtx != NULL); ASSERT_TRUE(prvCtx != NULL); ASSERT_EQ(TestRandInit(), CRYPT_SUCCESS); ASSERT_EQ(CRYPT_EAL_PkeySetParaById(pkey, paraid), CRYPT_SUCCESS); ASSERT_EQ(CRYPT_EAL_PkeySetParaById(pubCtx, paraid), CRYPT_SUCCESS); ASSERT_EQ(CRYPT_EAL_PkeySetParaById(prvCtx, paraid), CRYPT_SUCCESS); Ecc_SetPubKey(&ecdhPubKey, CRYPT_PKEY_ECDH, pubKeyVector.data, pubKeyVector.len); Ecc_SetPrvKey(&ecdhPrvKey, CRYPT_PKEY_ECDH, prvKeyVector.data, prvKeyVector.len); ASSERT_EQ(CRYPT_EAL_PkeyGen(pkey), CRYPT_SUCCESS); ASSERT_EQ(CRYPT_EAL_PkeyPairCheck(pkey, pkey), CRYPT_SUCCESS); ASSERT_EQ(CRYPT_EAL_PkeyPrvCheck(pkey), CRYPT_SUCCESS); ASSERT_EQ(CRYPT_EAL_PkeyGetPub(pkey, &ecdhPubKey), CRYPT_SUCCESS); ASSERT_EQ(CRYPT_EAL_PkeyGetPrv(pkey, &ecdhPrvKey), CRYPT_SUCCESS); ASSERT_EQ(CRYPT_EAL_PkeySetPub(pubCtx, &ecdhPubKey), CRYPT_SUCCESS); ASSERT_EQ(CRYPT_EAL_PkeySetPrv(prvCtx, &ecdhPrvKey), CRYPT_SUCCESS); ASSERT_EQ(CRYPT_EAL_PkeyPairCheck(pubCtx, prvCtx), CRYPT_SUCCESS); ecdhPrvKey.key.eccPrv.data = wrong; ASSERT_EQ(CRYPT_EAL_PkeySetPrv(prvCtx, &ecdhPrvKey), CRYPT_SUCCESS); ASSERT_EQ(CRYPT_EAL_PkeyPairCheck(pubCtx, prvCtx), CRYPT_ECDH_PAIRWISE_CHECK_FAIL); EXIT: TestRandDeInit(); CRYPT_EAL_PkeyFreeCtx(pkey); CRYPT_EAL_PkeyFreeCtx(pubCtx); CRYPT_EAL_PkeyFreeCtx(prvCtx); #endif } /* END_CASE */ /** * @test SDV_CRYPTO_ECDH_CHECK_PRVKEY_FUNC_TC001 * @title ECDH CRYPT_EAL_PkeyPrvCheck test. */ /* BEGIN_CASE */ void SDV_CRYPTO_ECDH_CHECK_PRVKEY_FUNC_TC001(int paraid, int isProvider) { #if !defined(HITLS_CRYPTO_ECDH_CHECK) (void)paraid; (void)isProvider; SKIP_TEST(); #else TestMemInit(); CRYPT_EAL_PkeyPrv ecdhPrvKey = {0}; CRYPT_ECDH_Ctx *ctx = NULL; BN_BigNum *n = NULL; BN_BigNum *prvKey = NULL; KeyData prvKeyVector = {{0}, KEY_MAX_LEN}; CRYPT_EAL_PkeyCtx *pkey = TestPkeyNewCtx(NULL, CRYPT_PKEY_ECDH, CRYPT_EAL_PKEY_KEYMGMT_OPERATE, "provider=default", isProvider); CRYPT_EAL_PkeyCtx *prvCtx = TestPkeyNewCtx(NULL, CRYPT_PKEY_ECDH, CRYPT_EAL_PKEY_KEYMGMT_OPERATE, "provider=default", isProvider); ASSERT_TRUE(pkey != NULL); ASSERT_TRUE(prvCtx != NULL); ASSERT_EQ(TestRandInit(), CRYPT_SUCCESS); ASSERT_EQ(CRYPT_EAL_PkeySetParaById(pkey, paraid), CRYPT_SUCCESS); ASSERT_EQ(CRYPT_EAL_PkeySetParaById(prvCtx, paraid), CRYPT_SUCCESS); Ecc_SetPrvKey(&ecdhPrvKey, CRYPT_PKEY_ECDH, prvKeyVector.data, prvKeyVector.len); ASSERT_EQ(CRYPT_EAL_PkeyPrvCheck(NULL), CRYPT_NULL_INPUT); ASSERT_EQ(CRYPT_EAL_PkeyPrvCheck(pkey), CRYPT_ECC_PKEY_ERR_EMPTY_KEY); ASSERT_EQ(CRYPT_EAL_PkeyGen(pkey), CRYPT_SUCCESS); ASSERT_EQ(CRYPT_EAL_PkeyPrvCheck(pkey), CRYPT_SUCCESS); ctx = (CRYPT_ECDH_Ctx *)pkey->key; prvKey = ctx->prvkey; n = ECC_GetParaN(ctx->para); (void)BN_Copy(prvKey, n); ASSERT_EQ(CRYPT_EAL_PkeyPrvCheck(pkey), CRYPT_ECDH_INVALID_PRVKEY); (void)BN_SubLimb(prvKey, prvKey, 1); // key = n - 1 ASSERT_EQ(CRYPT_EAL_PkeyPrvCheck(pkey), CRYPT_SUCCESS); (void)BN_Zeroize(prvKey); // key = 0 ASSERT_EQ(CRYPT_EAL_PkeyPrvCheck(pkey), CRYPT_ECDH_INVALID_PRVKEY); EXIT: TestRandDeInit(); CRYPT_EAL_PkeyFreeCtx(pkey); CRYPT_EAL_PkeyFreeCtx(prvCtx); BN_Destroy(n); #endif } /* END_CASE */ /** * @test SDV_CRYPTO_ECC_MUL_CAL_TEST_FUNC_TC001 * @title ECDH SDV_CRYPTO_ECC_MUL_CAL_TEST_FUNC_TC001 test. */ /* BEGIN_CASE */ void SDV_CRYPTO_ECC_MUL_CAL_TEST_FUNC_TC001(int paraId) { if (IsCurveDisabled(paraId) && paraId != CRYPT_ECC_SM2) { SKIP_TEST(); } TestMemInit(); ASSERT_EQ(TestRandInit(), CRYPT_SUCCESS); ECC_Para *para = ECC_NewPara(paraId); ASSERT_TRUE(para != NULL); BN_BigNum *N = ECC_GetParaN(para); ASSERT_TRUE(N != NULL); BN_BigNum *rand = BN_Create(0); ASSERT_TRUE(rand != NULL); ASSERT_EQ(BN_RandRange(rand, N), CRYPT_SUCCESS); ECC_Point *point1 = ECC_NewPoint(para); ASSERT_TRUE(point1 != NULL); ECC_Point *point2 = ECC_NewPoint(para); ASSERT_TRUE(point2 != NULL); ECC_Point *point3 = ECC_NewPoint(para); ASSERT_TRUE(point3 != NULL); // cal N*G ASSERT_EQ(ECC_PointMul(para, point1, N, NULL), CRYPT_SUCCESS); ASSERT_EQ(ECP_PointMulFast(para, point2, N, NULL), CRYPT_SUCCESS); ASSERT_EQ(ECC_PointCmp(para, point1, point2), CRYPT_SUCCESS); // cal random*G ASSERT_EQ(ECC_PointMul(para, point1, rand, NULL), CRYPT_SUCCESS); ASSERT_EQ(ECP_PointMulFast(para, point2, rand, NULL), CRYPT_SUCCESS); ASSERT_EQ(ECC_PointCmp(para, point1, point2), CRYPT_SUCCESS); // cal random*Point ASSERT_EQ(ECC_PointMul(para, point2, rand, point1), CRYPT_SUCCESS); ASSERT_EQ(ECP_PointMulFast(para, point3, rand, point1), CRYPT_SUCCESS); ASSERT_EQ(ECC_PointCmp(para, point2, point3), CRYPT_SUCCESS); EXIT: ECC_FreePara(para); ECC_FreePoint(point1); ECC_FreePoint(point2); ECC_FreePoint(point3); BN_Destroy(rand); BN_Destroy(N); TestRandDeInit(); } /* END_CASE */ /** * @test SDV_CRYPTO_ECC_ADD_CAL_TEST_FUNC_TC001 * @title ECDH SDV_CRYPTO_ECC_ADD_CAL_TEST_FUNC_TC001 test. */ /* BEGIN_CASE */ void SDV_CRYPTO_ECC_ADD_CAL_TEST_FUNC_TC001(int paraId, Hex *bk1, Hex *bk2, Hex *bk3) { if (IsCurveDisabled(paraId) && paraId != CRYPT_ECC_SM2) { SKIP_TEST(); } TestMemInit(); ASSERT_EQ(TestRandInit(), CRYPT_SUCCESS); ECC_Para *para = ECC_NewPara(paraId); ECC_Point *twoG = ECC_NewPoint(para); ECC_Point *pt1 = ECC_NewPoint(para); ECC_Point *pt2 = ECC_NewPoint(para); ECC_Point *r1 = ECC_NewPoint(para); ECC_Point *r2 = ECC_NewPoint(para); BN_BigNum *bnk1 = BN_Create(0); BN_BigNum *bnk2 = BN_Create(0); BN_BigNum *bnk3 = BN_Create(0); ASSERT_TRUE(bnk1 != NULL); ASSERT_TRUE(bnk2 != NULL); ASSERT_TRUE(bnk3 != NULL); ASSERT_TRUE(twoG != NULL); ASSERT_TRUE(pt1 != NULL); ASSERT_TRUE(pt2 != NULL); ASSERT_TRUE(r1 != NULL); ASSERT_TRUE(r2 != NULL); ASSERT_EQ(BN_Bin2Bn(bnk1, bk1->x, bk1->len), CRYPT_SUCCESS); ASSERT_EQ(BN_Bin2Bn(bnk2, bk2->x, bk2->len), CRYPT_SUCCESS); ASSERT_EQ(BN_Bin2Bn(bnk3, bk3->x, bk3->len), CRYPT_SUCCESS); // cal 2*G ASSERT_EQ(ECP_PointMulFast(para, twoG, bnk3, NULL), CRYPT_SUCCESS); ASSERT_EQ(ECP_PointMulFast(para, pt1, bnk1, NULL), CRYPT_SUCCESS); ASSERT_EQ(ECP_PointMulFast(para, pt2, bnk2, twoG), CRYPT_SUCCESS); ASSERT_EQ(ECC_PointAddAffine(para, r1, pt1, pt2), CRYPT_SUCCESS); ASSERT_EQ(ECC_PointMulAdd(para, r2, bnk1, bnk2, twoG), CRYPT_SUCCESS); ASSERT_EQ(ECC_PointCmp(para, r1, r2), CRYPT_SUCCESS); EXIT: ECC_FreePara(para); ECC_FreePoint(twoG); ECC_FreePoint(pt1); ECC_FreePoint(pt2); ECC_FreePoint(r1); ECC_FreePoint(r2); BN_Destroy(bnk1); BN_Destroy(bnk2); BN_Destroy(bnk3); TestRandDeInit(); } /* END_CASE */
2301_79861745/bench_create
testcode/sdv/testcase/crypto/ecc/test_suite_sdv_eal_ecdh.c
C
unknown
35,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_BASE test_suite_sdv_eal_ecc */ /* BEGIN_HEADER */ int SignEncode(Hex *R, Hex *S, uint8_t *vectorSign, uint32_t *vectorSignLen) { int ret; BN_BigNum *bnR = BN_Create(R->len * BITS_OF_BYTE); BN_BigNum *bnS = BN_Create(S->len * BITS_OF_BYTE); ASSERT_TRUE(bnS != NULL && bnR != NULL); ASSERT_TRUE(BN_Bin2Bn(bnR, R->x, R->len) == CRYPT_SUCCESS); ASSERT_TRUE(BN_Bin2Bn(bnS, S->x, S->len) == CRYPT_SUCCESS); ret = CRYPT_EAL_EncodeSign(bnR, bnS, vectorSign, vectorSignLen); EXIT: BN_Destroy(bnR); BN_Destroy(bnS); return ret; } /* END_HEADER */ #define CRYPT_EAL_PKEY_KEYMGMT_OPERATE 0 /** * @test SDV_CRYPTO_ECDSA_NEW_CTX_API_TC001 * @title ECDSA CRYPT_EAL_PkeyNewCtx test. * @precon nan * @brief * 1. Call the CRYPT_EAL_PkeyNewCtx method to create a pkey structure, algId is CRYPT_PKEY_ECDSA, expected result 1 * 2. Releases the pkey structure, expected result 2 * @expect * 1. Success, and the structure is not NULL. * 1. No memory leakage occurs. */ /* BEGIN_CASE */ void SDV_CRYPTO_ECDSA_NEW_CTX_API_TC001(void) { ASSERT_TRUE(EAL_PkeyNewCtx_Api_TC001(CRYPT_PKEY_ECDSA) == 0); EXIT: return; } /* END_CASE */ /** * @test SDV_CRYPTO_ECDSA_SET_PARA_BY_ID_API_TC001 * @title ECDSA CRYPT_EAL_PkeySetParaById: Test the validity of input parameters. * @precon * @brief * 1. Create the context of the ecdsa algorithm, expected result 1 * 2. Call the CRYPT_EAL_PkeySetParaById method: * (1) context = NULL, expected result 2. * (2) CRYPT_PKEY_ParaId = CRYPT_ECC_NISTP224, expected result 3. * (3) CRYPT_PKEY_ParaId = CRYPT_ECC_NISTP256, expected result 3. * (4) CRYPT_PKEY_ParaId = CRYPT_ECC_NISTP384, expected result 3. * (5) CRYPT_PKEY_ParaId = CRYPT_ECC_NISTP521, expected result 3. * (6) CRYPT_PKEY_ParaId = CRYPT_ECC_BRAINPOOLP256R1, expected result 3. * (7) CRYPT_PKEY_ParaId = CRYPT_ECC_BRAINPOOLP384R1, expected result 3. * (8) CRYPT_PKEY_ParaId = CRYPT_ECC_BRAINPOOLP512R1, expected result 3. * @expect * 1. Success, and the context is not NULL. * 2. CRYPT_NULL_INPUT * 3. CRYPT_SUCCESS */ /* BEGIN_CASE */ void SDV_CRYPTO_ECDSA_SET_PARA_BY_ID_API_TC001(void) { ASSERT_TRUE(EAL_PkeySetParaById_Api_TC001(CRYPT_PKEY_ECDSA) == 0); EXIT: return; } /* END_CASE */ /** * @test SDV_CRYPTO_ECDSA_SET_PARA_BY_ID_API_TC002 * @title Repeat to set different curves. * @precon nan * @brief * 1. Create context(ecdsaPkey) of the ECDSA algorithm, expected result 1 * 2. Set elliptic curve type to P224, expected result 2 * 3. Set elliptic curve type to paraId, expected result 3 * 4. Set private key, expected result 4 * 5. Take over random numbers, mock BN_RandRange to generate randVector. * 6. Compute the signature by ecdsaPkey, expected result 5 * 7. Compares the hitls signature, expected result 6 * @expect * 1. Success, and two contexts are not NULL. * 2-5. CRYPT_SUCCESS * 6. Both are the same. */ /* BEGIN_CASE */ void SDV_CRYPTO_ECDSA_SET_PARA_BY_ID_API_TC002( int paraId, int mdId, Hex *prvKeyVector, Hex *plainText, Hex *signR, Hex *signS, Hex *randVector, int isProvider) { CRYPT_EAL_PkeyCtx *ecdsaPkey = NULL; FuncStubInfo tmpRpInfo; int ret, vectorSignLen, hitlsSginLen; uint8_t *vectorSign = NULL; uint8_t *hitlsSign = NULL; CRYPT_EAL_PkeyPrv ecdsaPrvkey = {0}; TestMemInit(); ecdsaPkey = TestPkeyNewCtx(NULL, CRYPT_PKEY_ECDSA, CRYPT_EAL_PKEY_KEYMGMT_OPERATE + CRYPT_EAL_PKEY_SIGN_OPERATE, "provider=default", isProvider); ASSERT_TRUE(ecdsaPkey != NULL); ASSERT_TRUE_AND_LOG( "SetParaById NISTP224", CRYPT_EAL_PkeySetParaById(ecdsaPkey, CRYPT_ECC_NISTP224) == CRYPT_SUCCESS); ASSERT_TRUE_AND_LOG("SetParaById", CRYPT_EAL_PkeySetParaById(ecdsaPkey, paraId) == CRYPT_SUCCESS); /* Take over random numbers. */ ASSERT_TRUE(memcpy_s(gkRandBuf, sizeof(gkRandBuf), randVector->x, randVector->len) == 0); gkRandBufLen = randVector->len; STUB_Init(); STUB_Replace(&tmpRpInfo, BN_RandRangeEx, STUB_RandRangeK); /* Set private key */ Ecc_SetPrvKey(&ecdsaPrvkey, CRYPT_PKEY_ECDSA, prvKeyVector->x, prvKeyVector->len); ASSERT_EQ(CRYPT_EAL_PkeySetPrv(ecdsaPkey, &ecdsaPrvkey), CRYPT_SUCCESS); /* Signature */ hitlsSginLen = CRYPT_EAL_PkeyGetSignLen(ecdsaPkey); hitlsSign = (uint8_t *)malloc(hitlsSginLen); ASSERT_TRUE(hitlsSign != NULL); ret = CRYPT_EAL_PkeySign(ecdsaPkey, mdId, plainText->x, plainText->len, hitlsSign, (uint32_t *)&hitlsSginLen); ASSERT_EQ(ret, CRYPT_SUCCESS); /* Encode the R and S of the vector. */ vectorSignLen = CRYPT_EAL_PkeyGetSignLen(ecdsaPkey); vectorSign = (uint8_t *)malloc(vectorSignLen); ASSERT_TRUE(vectorSign != NULL); ret = SignEncode(signR, signS, vectorSign, (uint32_t *)&vectorSignLen); ASSERT_TRUE_AND_LOG("SignEncode", ret == CRYPT_SUCCESS); /* Compare the results of HiTLS vs. Vector. */ ASSERT_EQ(hitlsSginLen, vectorSignLen); ASSERT_TRUE(memcmp(vectorSign, hitlsSign, hitlsSginLen) == 0); EXIT: STUB_Reset(&tmpRpInfo); free(hitlsSign); free(vectorSign); CRYPT_EAL_PkeyFreeCtx(ecdsaPkey); } /* END_CASE */ /** * @test SDV_CRYPTO_ECDSA_SIGN_API_TC001 * @title ECDSA CRYPT_EAL_PkeySign: Test the validity of parameters. * @precon nan * @brief * 1. Create the context of the ecdsa algorithm, expected result 1 * 2. Set para by curve id(P-224) and set private key, expected result 2 * 3. Call the CRYPT_EAL_PkeySign method: * (1) pkey = null, expected result 3 * (2) msg = null, expected result 4 * (3) sign = NULL, signLen != 0, expected result 5 * (4) sign != NULL, signLen = 0, expected result 6 * (5) sign != NULL, signLen = 1, expected result 7 * (6) msg != NULL, msgLen = 0, expected result 8 * (7) Correct parameters, expected result 9 * 4. Compare the signgures of HiTLS and vector, expected result 10 * @expect * 1. Success, and the context is not NULL. * 2. CRYPT_SUCCESS * 3-5. CRYPT_NULL_INPUT * 6-7. CRYPT_DSA_BUFF_LEN_NOT_ENOUGH * 8-9. CRYPT_SUCCESS * 10. Both are the same. */ /* BEGIN_CASE */ void SDV_CRYPTO_ECDSA_SIGN_API_TC001( int mdId, Hex *prvKeyVector, Hex *msg, Hex *signR, Hex *signS, Hex *randVector, int isProvider) { CRYPT_EAL_PkeyCtx *ecdsaPkey = NULL; FuncStubInfo tmpRpInfo; int vectorSignLen; uint32_t signLen; uint8_t *vectorSign = NULL; uint8_t *sign = NULL; CRYPT_EAL_PkeyPrv ecdsaPrvkey = {0}; /* Register memory */ TestMemInit(); /* Take over random numbers. */ ASSERT_TRUE(memcpy_s(gkRandBuf, sizeof(gkRandBuf), randVector->x, randVector->len) == 0); gkRandBufLen = randVector->len; STUB_Init(); STUB_Replace(&tmpRpInfo, BN_RandRangeEx, STUB_RandRangeK); ecdsaPkey = TestPkeyNewCtx(NULL, CRYPT_PKEY_ECDSA, CRYPT_EAL_PKEY_KEYMGMT_OPERATE + CRYPT_EAL_PKEY_SIGN_OPERATE, "provider=default", isProvider); ASSERT_TRUE(ecdsaPkey != NULL); /* Set para by curve id and set private key. */ ASSERT_TRUE(CRYPT_EAL_PkeySetParaById(ecdsaPkey, CRYPT_ECC_NISTP224) == CRYPT_SUCCESS); Ecc_SetPrvKey(&ecdsaPrvkey, CRYPT_PKEY_ECDSA, prvKeyVector->x, prvKeyVector->len); ASSERT_EQ(CRYPT_EAL_PkeySetPrv(ecdsaPkey, &ecdsaPrvkey), CRYPT_SUCCESS); /* Input parameter test of CRYPT_EAL_PkeySign. */ signLen = CRYPT_EAL_PkeyGetSignLen(ecdsaPkey); sign = (uint8_t *)malloc(signLen); ASSERT_TRUE(sign != NULL); ASSERT_EQ(CRYPT_EAL_PkeySign(NULL, mdId, msg->x, msg->len, sign, &signLen), CRYPT_NULL_INPUT); ASSERT_EQ(CRYPT_EAL_PkeySign(ecdsaPkey, mdId, NULL, msg->len, sign, &signLen), CRYPT_NULL_INPUT); ASSERT_EQ(CRYPT_EAL_PkeySign(ecdsaPkey, mdId, msg->x, msg->len, NULL, &signLen), CRYPT_NULL_INPUT); signLen = 0; ASSERT_EQ(CRYPT_EAL_PkeySign(ecdsaPkey, mdId, msg->x, msg->len, sign, &signLen), CRYPT_ECDSA_BUFF_LEN_NOT_ENOUGH); signLen = 1; ASSERT_EQ(CRYPT_EAL_PkeySign(ecdsaPkey, mdId, msg->x, msg->len, sign, &signLen), CRYPT_ECDSA_BUFF_LEN_NOT_ENOUGH); signLen = CRYPT_EAL_PkeyGetSignLen(ecdsaPkey); /* The plaintext length is 0 and the other parameters are normal, and it is expected to succeed. */ ASSERT_EQ(CRYPT_EAL_PkeySign(ecdsaPkey, mdId, msg->x, 0, sign, &signLen), CRYPT_SUCCESS); signLen = CRYPT_EAL_PkeyGetSignLen(ecdsaPkey); ASSERT_TRUE(CRYPT_EAL_PkeySign(ecdsaPkey, mdId, msg->x, msg->len, sign, (uint32_t *)&signLen) == CRYPT_SUCCESS); /* Encode the R and S of the vector. */ vectorSignLen = CRYPT_EAL_PkeyGetSignLen(ecdsaPkey); vectorSign = (uint8_t *)malloc(vectorSignLen); ASSERT_TRUE(vectorSign != NULL); ASSERT_TRUE_AND_LOG( "SignEncode", SignEncode(signR, signS, vectorSign, (uint32_t *)&vectorSignLen) == CRYPT_SUCCESS); /* Compare the results of HiTLS vs. Vector. */ ASSERT_EQ(signLen, vectorSignLen); ASSERT_TRUE(memcmp(vectorSign, sign, signLen) == 0); EXIT: STUB_Reset(&tmpRpInfo); free(sign); free(vectorSign); CRYPT_EAL_PkeyFreeCtx(ecdsaPkey); } /* END_CASE */ /** * @test SDV_CRYPTO_ECDSA_SIGN_API_TC002 * @title ECDSA CRYPT_EAL_PkeySign: Missing private key. * @precon nan * @brief * 1. Create the context of the ecdsa algorithm, expected result 1 * 2. Set para by curve id(P-224), expected result 2 * 3. Call the CRYPT_EAL_PkeySign method to compute signature,expected result 3 * @expect * 1. Success, and the context is not NULL. * 2. CRYPT_SUCCESS * 3. CRYPT_ECDSA_ERR_EMPTY_KEY */ /* BEGIN_CASE */ void SDV_CRYPTO_ECDSA_SIGN_API_TC002(int mdId, Hex *plainText, int isProvider) { uint32_t hitlsSignLen; uint8_t *hitlsSign = NULL; CRYPT_EAL_PkeyCtx *ecdsaPkey = NULL; TestMemInit(); ecdsaPkey = TestPkeyNewCtx(NULL, CRYPT_PKEY_ECDSA, CRYPT_EAL_PKEY_KEYMGMT_OPERATE + CRYPT_EAL_PKEY_SIGN_OPERATE, "provider=default", isProvider); ASSERT_TRUE(ecdsaPkey != NULL); ASSERT_TRUE(CRYPT_EAL_PkeySetParaById(ecdsaPkey, CRYPT_ECC_NISTP224) == CRYPT_SUCCESS); /* Signature */ hitlsSignLen = CRYPT_EAL_PkeyGetSignLen(ecdsaPkey); hitlsSign = (uint8_t *)malloc(hitlsSignLen); ASSERT_TRUE(hitlsSign != NULL); ASSERT_TRUE_AND_LOG("CRYPT_EAL_PkeySign No PrvKey", CRYPT_EAL_PkeySign(ecdsaPkey, mdId, plainText->x, plainText->len, hitlsSign, &hitlsSignLen) == CRYPT_ECDSA_ERR_EMPTY_KEY); EXIT: free(hitlsSign); CRYPT_EAL_PkeyFreeCtx(ecdsaPkey); CRYPT_EAL_RandDeinit(); } /* END_CASE */ /** * @test SDV_CRYPTO_ECDSA_SIGN_API_TC003 * @title ECDSA CRYPT_EAL_PkeySign: Missing private key. * @precon nan * @brief * 1. Create the context of the ecdsa algorithm, expected result 1 * 2. Set para by curve id(P-224) and set private key, expected result 2 * 3. Call the CRYPT_EAL_PkeySign method to compute signature,expected result 3 * 4. Mock BN_RandRange to STUB_RandRangeK * 5. Call the CRYPT_EAL_PkeySign method to compute signature,expected result 4 * @expect * 1. Success, and the context is not NULL. * 2. CRYPT_SUCCESS * 3. CRYPT_NO_REGIST_RAND * 4. CRYPT_ECDSA_ERR_TRY_CNT on randVector is 0, otherwise CRYPT_SUCCESS. */ /* BEGIN_CASE */ void SDV_CRYPTO_ECDSA_SIGN_API_TC003( int mdId, Hex *prvKeyVector, Hex *plainText, Hex *randVector, int result, int isProvider) { CRYPT_EAL_PkeyCtx *ecdsaPkey = NULL; FuncStubInfo tmpRpInfo; int ret, hitlsSginLen; uint8_t *hitlsSign = NULL; CRYPT_EAL_PkeyPrv ecdsaPrvkey = {0}; /* Register memory */ TestMemInit(); ecdsaPkey = TestPkeyNewCtx(NULL, CRYPT_PKEY_ECDSA, CRYPT_EAL_PKEY_KEYMGMT_OPERATE + CRYPT_EAL_PKEY_SIGN_OPERATE, "provider=default", isProvider); ASSERT_TRUE(ecdsaPkey != NULL); /* Set para by curve id and set private key */ ASSERT_TRUE(CRYPT_EAL_PkeySetParaById(ecdsaPkey, CRYPT_ECC_NISTP256) == CRYPT_SUCCESS); Ecc_SetPrvKey(&ecdsaPrvkey, CRYPT_PKEY_ECDSA, prvKeyVector->x, prvKeyVector->len); ASSERT_EQ(CRYPT_EAL_PkeySetPrv(ecdsaPkey, &ecdsaPrvkey), CRYPT_SUCCESS); /* Signature */ hitlsSginLen = CRYPT_EAL_PkeyGetSignLen(ecdsaPkey); hitlsSign = (uint8_t *)malloc(hitlsSginLen); ASSERT_TRUE(hitlsSign != NULL); ret = CRYPT_EAL_PkeySign(ecdsaPkey, mdId, plainText->x, plainText->len, hitlsSign, (uint32_t *)&hitlsSginLen); ASSERT_EQ(ret, CRYPT_NO_REGIST_RAND); /* Take over random numbers. */ ASSERT_TRUE(memcpy_s(gkRandBuf, sizeof(gkRandBuf), randVector->x, randVector->len) == 0); gkRandBufLen = randVector->len; STUB_Init(); STUB_Replace(&tmpRpInfo, BN_RandRangeEx, STUB_RandRangeK); ret = CRYPT_EAL_PkeySign(ecdsaPkey, mdId, plainText->x, plainText->len, hitlsSign, (uint32_t *)&hitlsSginLen); if (result == 1) { ASSERT_EQ(ret, CRYPT_SUCCESS); } else { ASSERT_EQ(ret, CRYPT_ECDSA_ERR_TRY_CNT); } EXIT: STUB_Reset(&tmpRpInfo); free(hitlsSign); CRYPT_EAL_PkeyFreeCtx(ecdsaPkey); CRYPT_EAL_RandDeinit(); } /* END_CASE */ /** * @test SDV_CRYPTO_ECDSA_SIGN_DATA_API_TC001 * @title ECDSA CRYPT_EAL_PkeySign: Test the validity of parameters. * @precon nan * @brief * 1. Create the context of the ecdsa algorithm, expected result 1 * 2. Set para by curve id(P-224) and set private key, expected result 2 * 3. Call the CRYPT_EAL_PkeySignData method: * (1) pkey = null, expected result 3 * (2) msg = null, msgLen != 0, expected result 3 * (3) msg != NULL, msgLen = 0, expected result 3 * (4) sign = NULL, signLen != 0, expected result 6 * (5) sign != NULL, signLen = NULL, expected result 7 * (6) Correct parameters, expected result 8 * (7) sign != NULL, signLen = 0, expected result 9 * @expect * 1. Success, and the context is not NULL. * 2. CRYPT_SUCCESS * 3-4. CRYPT_ERR_ALGID * 5-7. CRYPT_NULL_INPUT * 8. CRYPT_NO_REGIST_RAND * 9. CRYPT_ECDSA_BUFF_LEN_NOT_ENOUGH */ /* BEGIN_CASE */ void SDV_CRYPTO_ECDSA_SIGN_DATA_API_TC001(Hex *prvKeyVector, Hex *msg, int isProvider) { uint32_t hitlsSignLen; uint8_t *hitlsSign = NULL; CRYPT_EAL_PkeyCtx *ecdsaPkey = NULL; CRYPT_EAL_PkeyPrv ecdsaPrvkey = {0}; TestMemInit(); ecdsaPkey = TestPkeyNewCtx(NULL, CRYPT_PKEY_ECDSA, CRYPT_EAL_PKEY_KEYMGMT_OPERATE + CRYPT_EAL_PKEY_SIGN_OPERATE, "provider=default", isProvider); ASSERT_TRUE(ecdsaPkey != NULL); /* Set para by curve id and set private key */ ASSERT_TRUE(CRYPT_EAL_PkeySetParaById(ecdsaPkey, CRYPT_ECC_NISTP256) == CRYPT_SUCCESS); Ecc_SetPrvKey(&ecdsaPrvkey, CRYPT_PKEY_ECDSA, prvKeyVector->x, prvKeyVector->len); ASSERT_EQ(CRYPT_EAL_PkeySetPrv(ecdsaPkey, &ecdsaPrvkey), CRYPT_SUCCESS); /* Signature */ hitlsSignLen = CRYPT_EAL_PkeyGetSignLen(ecdsaPkey); hitlsSign = (uint8_t *)malloc(hitlsSignLen); ASSERT_TRUE(hitlsSign != NULL); ASSERT_EQ(CRYPT_EAL_PkeySignData(NULL, msg->x, msg->len, hitlsSign, &hitlsSignLen), CRYPT_NULL_INPUT); ASSERT_EQ(CRYPT_EAL_PkeySignData(ecdsaPkey, NULL, msg->len, hitlsSign, &hitlsSignLen), CRYPT_INVALID_ARG); ASSERT_EQ(CRYPT_EAL_PkeySignData(ecdsaPkey, msg->x, 0, hitlsSign, &hitlsSignLen), CRYPT_INVALID_ARG); ASSERT_EQ(CRYPT_EAL_PkeySignData(ecdsaPkey, msg->x, msg->len, NULL, &hitlsSignLen), CRYPT_NULL_INPUT); ASSERT_EQ(CRYPT_EAL_PkeySignData(ecdsaPkey, msg->x, msg->len, hitlsSign, NULL), CRYPT_NULL_INPUT); ASSERT_EQ(CRYPT_EAL_PkeySignData(ecdsaPkey, msg->x, msg->len, hitlsSign, &hitlsSignLen), CRYPT_NO_REGIST_RAND); hitlsSignLen = 0; ASSERT_EQ( CRYPT_EAL_PkeySignData(ecdsaPkey, msg->x, msg->len, hitlsSign, &hitlsSignLen), CRYPT_ECDSA_BUFF_LEN_NOT_ENOUGH); EXIT: free(hitlsSign); CRYPT_EAL_PkeyFreeCtx(ecdsaPkey); CRYPT_EAL_RandDeinit(); } /* END_CASE */ /** * @test SDV_CRYPTO_ECDSA_CTRL_API_TC001 * @title ECDSA CRYPT_EAL_PkeyCtrl: Test the validity of opt. * @precon nan * @brief * 1. Create the context of the ecdsa algorithm, expected result 1 * 2. Call the CRYPT_EAL_PkeyCtrl method: * (1) opt = CRYPT_CTRL_SET_RSA_RSAES_PKCSV15, expected result 2 * (2) opt = CRYPT_CTRL_SET_ECC_POINT_FORMAT, expected result 3 * (3) opt = CRYPT_CTRL_SET_ECC_USE_COFACTOR_MODE, expected result 4 * (4) opt = CRYPT_CTRL_SET_SM2_USER_ID, expected result 5 * (5) opt = CRYPT_CTRL_SET_RSA_PADDING, expected result 6 * @expect * 1. Success, and the context is not NULL. * 2. CRYPT_ECC_PKEY_ERR_UNSUPPORTED_CTRL_OPTION * 3. CRYPT_SUCCESS * 4. CRYPT_ECDSA_ERR_UNSUPPORTED_CTRL_OPTION * 5. CRYPT_ECC_PKEY_ERR_UNSUPPORTED_CTRL_OPTION * 6. CRYPT_ECC_PKEY_ERR_UNSUPPORTED_CTRL_OPTION */ /* BEGIN_CASE */ void SDV_CRYPTO_ECDSA_CTRL_API_TC001(int type, int expect) { ASSERT_TRUE(EAL_PkeyCtrl_Api_TC001(CRYPT_PKEY_ECDSA, type, expect) == SUCCESS); EXIT: return; } /* END_CASE */ /** * @test SDV_CRYPTO_ECDSA_CTRL_API_TC002 * @title ECDSA CRYPT_EAL_PkeyCtrl: Test the validity of pkey and value. * @precon nan * @brief * 1. Create the context of the ECDSA algorithm, expected result 1 * 2. Call the CRYPT_EAL_PkeyCtrl method: * (1) pkey = null, expected result 2 * (2) val = null, len = 0, expected result 3 * (3) val = null, len != 0, expected result 4 * (4) val != null, len = 0, expected result 5 * (5) PointFormat = CRYPT_POINT_MAX, expected result 6 * (6) PointFormat = CRYPT_POINT_COMPRESSED, expected result 7 * (7) PointFormat = CRYPT_POINT_UNCOMPRESSED, expected result 8 * (8) PointFormat = CRYPT_POINT_HYBRID, expected result 9 * @expect * 1. Success, and the context is not NULL. * 2-4. CRYPT_NULL_INPUT * 5. CRYPT_ECC_PKEY_ERR_CTRL_LEN * 6. CRYPT_ECC_PKEY_ERR_INVALID_POINT_FORMAT * 7-9. CRYPT_SUCCESS */ /* BEGIN_CASE */ void SDV_CRYPTO_ECDSA_CTRL_API_TC002(void) { ASSERT_TRUE(EAL_PkeyCtrl_Api_TC002(CRYPT_PKEY_ECDSA) == 0); EXIT: return; } /* END_CASE */ /** * @test SDV_CRYPTO_ECDSA_CTRL_API_TC003 * @title ECDSA CRYPT_EAL_PkeyCtrl: Test the effect of the point format on the key. * @precon public key point * @brief * 1. Create the context of the ecdsa algorithm, expected result 1 * 2. Set the para by eccId(p-224/256/384/512, bp256r1/384r1/512/r1), expected result 2 * 3. Convert the format of the public key vector to COMPRESSED, expected result 3 * 4. Set the public key, expected result 4 * 5. Call the CRYPT_EAL_PkeyCtrl method to set point format to COMPRESSED, expected result 5 * 6. Call the CRYPT_EAL_PkeyCtrl method to set point format to HYBRID, expected result 6 * 7. Get the public key, expected result 7 * 8. Convert the format of the public key vector to HYBRID, expected result 8 * 9. Compare the output of the preceding two steps, expected result 9 * @expect * 1. Success, and the context is not NULL. * 2-7. CRYPT_SUCCESS * 9. The two are same. */ /* BEGIN_CASE */ void SDV_CRYPTO_ECDSA_CTRL_API_TC003(int eccId, Hex *pubKeyX, Hex *pubKeyY) { ASSERT_TRUE(EAL_PkeyCtrl_Api_TC003(CRYPT_PKEY_ECDSA, eccId, pubKeyX, pubKeyY) == 0); EXIT: return; } /* END_CASE */ /** * @test SDV_CRYPTO_ECDSA_GET_PRV_API_TC001 * @title ECDSA CRYPT_EAL_PkeyGetPrv: Test the validity of parameters. * @precon private key * @brief * 1. Create the context of the ecdsa algorithm, expected result 1 * 2. Set the para by eccId(p-224), expected result 2 * 3. Get the private key when there is no private key, expected result 3 * 4. Set the private key, expected result 4 * 5. Call the CRYPT_EAL_PkeyGetPrv method: * (1) pkey = null, expected result 5 * (2) prv = null, expected result 6 * (3) pkey.id != prv.id, expected result 7 * (4) Correct parameters, expected result 8 * @expect * 1. Success, and the context is not NULL. * 2. CRYPT_SUCCESS * 3. CRYPT_ECC_PKEY_ERR_EMPTY_KEY * 4. CRYPT_SUCCESS * 5-6. CRYPT_NULL_INPUT * 7. CRYPT_EAL_ERR_ALGID * 8. CRYPT_SUCCESS */ /* BEGIN_CASE */ void SDV_CRYPTO_ECDSA_GET_PRV_API_TC001(Hex *prvKey) { ASSERT_TRUE(EAL_PkeyGetPrv_Api_TC001(CRYPT_PKEY_ECDSA, prvKey) == 0); EXIT: return; } /* END_CASE */ /** * @test SDV_CRYPTO_ECDSA_GET_PUB_API_TC001 * @title ECDSA CRYPT_EAL_PkeyGetPub: Test the validity of parameters. * @precon public key point * @brief * 1. Create the context of the ecdsa algorithm, expected result 1 * 2. Set the para by eccId(p-224), expected result 2 * 3. Get the public key when there is no public key, expected result 3 * 4. Set the public key, expected result 4 * 5. Call the CRYPT_EAL_PkeyGetPub method: * (1) pkey = null, expected result 5 * (2) pub = null, expected result 6 * (3) pkey.id != pub.id, expected result 7 * (4) Correct parameters, expected result 8 * @expect * 1. Success, and the context is not NULL. * 2. CRYPT_SUCCESS * 3. CRYPT_ECC_PKEY_ERR_EMPTY_KEY * 4. CRYPT_SUCCESS * 5-6. CRYPT_NULL_INPUT * 7. CRYPT_EAL_ERR_ALGID * 8. CRYPT_SUCCESS */ /* BEGIN_CASE */ void SDV_CRYPTO_ECDSA_GET_PUB_API_TC001(Hex *pubKeyX, Hex *pubKeyY) { ASSERT_TRUE(EAL_PkeyGetPub_Api_TC001(CRYPT_PKEY_ECDSA, pubKeyX, pubKeyY) == 0); EXIT: return; } /* END_CASE */ /** * @test SDV_CRYPTO_ECDSA_SET_PRV_API_TC001 * @title ECDSA CRYPT_EAL_PkeySetPrv: Test the validity of parameters. * @precon Prepare valid private key and invalid private key. * @brief * 1. Create the context of the ecdsa algorithm, expected result 1 * 2. Set the the valid private key before setting the curve, expected result 2 * 3. Set the para by eccId(p-224), expected result 3 * 4. Call the CRYPT_EAL_PkeySetPrv method: * (1) pkey = null, expected result 4 * (2) prv = null, expected result 5 * (3) pkey.id != prv.id, expected result 6 * (4) Set the valid private key, expected result 7 * (5) Set the invalid private key, expected result 8 * @expect * 1. Success, and the context is not NULL. * 2. CRYPT_NULL_INPUT * 3. CRYPT_SUCCESS * 4-5. CRYPT_NULL_INPUT * 6. CRYPT_EAL_ERR_ALGID * 7. CRYPT_SUCCESS * 8. CRYPT_ECC_PKEY_ERR_INVALID_PRIVATE_KEY */ /* BEGIN_CASE */ void SDV_CRYPTO_ECDSA_SET_PRV_API_TC001(Hex *prvKey, Hex *errorPrvKey) { ASSERT_TRUE(EAL_PkeySetPrv_Api_TC001(CRYPT_PKEY_ECDSA, prvKey, errorPrvKey) == 0); EXIT: return; } /* END_CASE */ /** * @test SDV_CRYPTO_ECDSA_SET_PRV_API_TC002 * @title Check whether the public key is cleared when the private key is set. * @precon private key, public key point * @brief * 1. Create the context of the ecdsa algorithm, expected result 1 * 2. Set the para by eccId(p-224), expected result 2 * 3. Set the the public key, expected result 3 * 4. Set the the private key, expected result 4 * 5. Get the the public key, expected result 5 * @expect * 1. Success, and the context is not NULL. * 2-5. CRYPT_SUCCESSY */ /* BEGIN_CASE */ void SDV_CRYPTO_ECDSA_SET_PRV_API_TC002(Hex *prvKey, Hex *pubKeyX, Hex *pubKeyY) { ASSERT_TRUE(EAL_PkeySetPrv_Api_TC002(CRYPT_PKEY_ECDSA, prvKey, pubKeyX, pubKeyY) == 0); EXIT: return; } /* END_CASE */ /** * @test SDV_CRYPTO_ECDSA_SET_PUB_API_TC001 * @title ECDSA CRYPT_EAL_PkeySetPub: Test the validity of parameters. * @precon Prepare valid public key. * @brief * 1. Create the context of the ecdsa algorithm, expected result 1 * 2. Set the the public key before setting the curve, expected result 2 * 3. Set the para by eccId(p-224), expected result 3 * 4. Call the CRYPT_EAL_PkeySetPub method: * (1) pkey = null, expected result 4 * (2) pub = null, expected result 5 * (3) pkey.id != pub.id, expected result 6 * (4) Set the valid public key, expected result 7 * @expect * 1. Success, and the context is not NULL. * 2. CRYPT_NULL_INPUT * 3. CRYPT_SUCCESS * 4-5. CRYPT_NULL_INPUT * 6. CRYPT_EAL_ERR_ALGID * 7. CRYPT_SUCCESS */ /* BEGIN_CASE */ void SDV_CRYPTO_ECDSA_SET_PUB_API_TC001(Hex *pubKeyVector) { ASSERT_TRUE(EAL_PkeySetPub_Api_TC001(CRYPT_PKEY_ECDSA, pubKeyVector) == 0); EXIT: return; } /* END_CASE */ /** * @test SDV_CRYPTO_ECDSA_SET_PUB_API_TC002 * @title Check whether the private key is cleared when the public key is set. * @precon public key, private key * @brief * 1. Create the context of the ecdsa algorithm, expected result 1 * 2. Set the para by eccId(p-224), expected result 2 * 3. Set the the private key, expected result 3 * 4. Set the the public key, expected result 4 * 5. Get the the private key, expected result 5 * @expect * 1. Success, and the context is not NULL. * 2-5. CRYPT_SUCCESSY */ /* BEGIN_CASE */ void SDV_CRYPTO_ECDSA_SET_PUB_API_TC002(Hex *prvKey, Hex *pubKey) { ASSERT_TRUE(EAL_PkeySetPub_Api_TC002(CRYPT_PKEY_ECDSA, prvKey, pubKey) == 0); EXIT: return; } /* END_CASE */ /** * @test SDV_CRYPTO_ECDSA_SET_PUB_API_TC003 * @title Test the function of setting public keys of different lengths. * @precon Public keys of different lengths. * @brief * 1. Create the context of the ecdsa algorithm, expected result 1 * 2. Set the para by eccId(p-224/256/384/512, bp256r1/384r1/512/r1), expected result 2 * 3. Set public keys of different lengths, expected result 3 * @expect * 1. Success, and the context is not NULL. * 2. CRYPT_SUCCESSY * 3. CRYPT_ECC_ERR_POINT_CODE */ /* BEGIN_CASE */ void SDV_CRYPTO_ECDSA_SET_PUB_API_TC003(int eccId, Hex *pubKey, Hex *errorPubKey, int isProvider) { ASSERT_TRUE(EAL_PkeySetPub_Api_TC003(CRYPT_PKEY_ECDSA, eccId, pubKey, errorPubKey, isProvider) == 0); EXIT: return; } /* END_CASE */ /** * @test SDV_CRYPTO_ECDSA_GET_PARA_ID_API_TC001 * @title ECDSA CRYPT_EAL_PkeyGetParaId test. * @precon Registering memory-related functions. * @brief * 1. Get para id before creating context, expected result 1 * 2. Create the context of the ECDSA algorithm, expected result 2 * 3. Set para id(p-224/256/384/512), expected result 3 * 4. Get para id, expected result 4 * @expect * 1. CRYPT_PKEY_PARAID_MAX * 2. Success, and the context is not NULL. * 3. CRYPT_SUCCESS * 4. The obtained id is the same as the set id. */ /* BEGIN_CASE */ void SDV_CRYPTO_ECDSA_GET_PARA_ID_API_TC001(int id) { ASSERT_TRUE(EAL_PkeyGetParaId_Api_TC001(CRYPT_PKEY_ECDSA, id) == 0); EXIT: return; } /* END_CASE */ /** * @test SDV_CRYPTO_ECDSA_CMP_FUNC_TC001 * @title ECDSA: CRYPT_EAL_PkeyCmp test. * @precon Registering memory-related functions. * @brief * 1. Create the contexts(ctx1, ctx2) of the ecdsa algorithm, expected result 1 * 2. Call the CRYPT_EAL_PkeyCmp to compare ctx1 and ctx2, expected result 2 * 3. Set para id CRYPT_ECC_NISTP224 and public key for ctx1, expected result 3 * 4. Call the CRYPT_EAL_PkeyCmp to compare ctx1 and ctx2, expected result 4 * 5. Set para id CRYPT_ECC_NISTP256 for ctx2, expected result 5 * 6. Set public key for ctx2, expected result 6 * 7. Set para id CRYPT_ECC_NISTP224 and public key for ctx2, expected result 7 * 8. Call the CRYPT_EAL_PkeyCmp to compare ctx1 and ctx2, expected result 8 * @expect * 1. Success, and contexts are not NULL. * 2. CRYPT_ECC_KEY_PUBKEY_NOT_EQUAL * 3. CRYPT_SUCCESS * 4. CRYPT_ECC_KEY_PUBKEY_NOT_EQUAL * 5. CRYPT_SUCCESS * 6. CRYPT_ECC_ERR_POINT_CODE * 7. CRYPT_SUCCESS * 8. CRYPT_SUCCESS */ /* BEGIN_CASE */ void SDV_CRYPTO_ECDSA_CMP_FUNC_TC001(Hex *pubKeyX, Hex *pubKeyY) { ASSERT_TRUE(EAL_PkeyCmp_Api_TC001(CRYPT_PKEY_ECDSA, pubKeyX, pubKeyY) == 0); EXIT: return; } /* END_CASE */ /** * @test SDV_CRYPTO_ECDSA_VERIFY_API_TC001 * @title ECDSA CRYPT_EAL_PkeyVerify: Test the validity of parameters. * @precon nan * @brief * 1. Create the context of the ecdsa algorithm, expected result 1 * 2. Set para by curve id(P-224), expected result 2 * 3. Verify when there is no public key, expected result 3 * 4. Set public key, expected result 4 * 5. Call the CRYPT_EAL_PkeyVerify method: * (1) pkey = null, expected result 5 * (2) data = null, dataLen != 0, expected result 6 * (3) data = null or data != null, and dataLen = 0, expected result 7 * (4) sign = null, signLen != 0 or signLen = 0, expected result 8 * (5) sign != null, signLen = 0, expected result 9 * (6) sign != null, signLen = 1, expected result 10 * (7) Correct parameters, expected result 11 * @expect * 1. Success, and the context is not null. * 2. CRYPT_SUCCESS * 3. CRYPT_ECDSA_ERR_EMPTY_KEY * 4. CRYPT_SUCCESS * 5-6. CRYPT_NULL_INPUT * 7. CRYPT_ECDSA_BUFF_LEN_NOT_ENOUGH * 8-9. CRYPT_NULL_INPUT * 10. CRYPT_DSA_DECODE_FAIL * 11. CRYPT_SUCCESS */ /* BEGIN_CASE */ void SDV_CRYPTO_ECDSA_VERIFY_API_TC001(Hex *data, Hex *pubKeyX, Hex *pubKeyY, Hex *sign, int isProvider) { CRYPT_EAL_PkeyCtx *pkey = NULL; CRYPT_EAL_PkeyPub ecdsaPubkey; KeyData pubKeyVector = {{0}, KEY_MAX_LEN}; CRYPT_MD_AlgId mdId = CRYPT_MD_SHA224; TestMemInit(); pkey = TestPkeyNewCtx(NULL, CRYPT_PKEY_ECDSA, CRYPT_EAL_PKEY_KEYMGMT_OPERATE + CRYPT_EAL_PKEY_SIGN_OPERATE, "provider=default", isProvider); ASSERT_TRUE_AND_LOG("New ECDSA Pkey", pkey != NULL); /* Set para by curve id. */ ASSERT_EQ(CRYPT_EAL_PkeySetParaById(pkey, CRYPT_ECC_NISTP224), CRYPT_SUCCESS); ASSERT_TRUE_AND_LOG("EccPointToBuffer", EccPointToBuffer(pubKeyX, pubKeyY, 1, &pubKeyVector) == CRYPT_SUCCESS); /* Verify when there is no public key. */ ASSERT_TRUE(CRYPT_EAL_PkeyVerify(pkey, mdId, data->x, data->len, sign->x, sign->len) == CRYPT_ECDSA_ERR_EMPTY_KEY); /* Set public key. */ Ecc_SetPubKey(&ecdsaPubkey, CRYPT_PKEY_ECDSA, pubKeyVector.data, pubKeyVector.len); ASSERT_EQ(CRYPT_EAL_PkeySetPub(pkey, &ecdsaPubkey), CRYPT_SUCCESS); /* Input parameter test of CRYPT_EAL_PkeyVerify. */ ASSERT_EQ(CRYPT_EAL_PkeyVerify(NULL, mdId, data->x, data->len, sign->x, sign->len), CRYPT_NULL_INPUT); ASSERT_EQ(CRYPT_EAL_PkeyVerify(pkey, mdId, NULL, data->len, sign->x, sign->len), CRYPT_NULL_INPUT); ASSERT_EQ(CRYPT_EAL_PkeyVerify(pkey, mdId, NULL, 0, sign->x, sign->len), CRYPT_ECDSA_VERIFY_FAIL); ASSERT_EQ(CRYPT_EAL_PkeyVerify(pkey, mdId, data->x, 0, sign->x, sign->len), CRYPT_ECDSA_VERIFY_FAIL); ASSERT_EQ(CRYPT_EAL_PkeyVerify(pkey, mdId, data->x, data->len, NULL, sign->len), CRYPT_NULL_INPUT); ASSERT_EQ(CRYPT_EAL_PkeyVerify(pkey, mdId, data->x, data->len, NULL, 0), CRYPT_NULL_INPUT); ASSERT_EQ(CRYPT_EAL_PkeyVerify(pkey, mdId, data->x, data->len, sign->x, 0), CRYPT_NULL_INPUT); ASSERT_EQ(CRYPT_EAL_PkeyVerify(pkey, mdId, data->x, data->len, sign->x, 1), BSL_ASN1_ERR_DECODE_LEN); ASSERT_EQ(CRYPT_EAL_PkeyVerify(pkey, mdId, data->x, data->len, sign->x, sign->len), CRYPT_SUCCESS); EXIT: CRYPT_EAL_PkeyFreeCtx(pkey); return; } /* END_CASE */ /** * @test SDV_CRYPTO_ECDSA_SIGN_VERIFY_FUNC_TC002 * @title ED25519 sets the keys and performs signature and verifiy tests on the hash data. * @precon nan * @brief * 1. Create context(ecdsaPkey) of the ECDSA algorithm, expected result 1 * 2. Set elliptic curve type, private key, expected result 2 * 3. Take over random numbers, mock BN_RandRange to generate randVector. * 4. Sign the hash data(all 0x00 or all 0xFF) using ecdsaPkey, expected result 3 * 5. Reset the stubbed function. * 6. Create context(ecdsaPkey2) of the ECDSA algorithm, expected result 4 * 7. Set elliptic curve type, public key, expected result 5 * 9. Verify the signature by ecdsaPkey2, expected result 6 * @expect * 1. Success, and context is not NULL. * 2-3. CRYPT_SUCCESS * 4. Success, and context is not NULL. * 5-6. CRYPT_SUCCESS */ /* BEGIN_CASE */ void SDV_CRYPTO_ECDSA_SIGN_VERIFY_FUNC_TC002(int eccId, Hex *prvKeyVector, Hex *hashData, Hex *randVector, Hex *pubKeyX, Hex *pubKeyY, int pointFormat, int isProvider) { uint32_t hitlsSignLen; FuncStubInfo tmpRpInfo; uint8_t *hitlsSign = NULL; CRYPT_EAL_PkeyCtx *ecdsaPkey = NULL; CRYPT_EAL_PkeyCtx *ecdsaPkey2 = NULL; CRYPT_EAL_PkeyPrv ecdsaPrvkey = {0}; CRYPT_EAL_PkeyPub ecdsaPubkey; KeyData pubKeyVector = {{0}, KEY_MAX_LEN}; /* Register memory */ TestMemInit(); /* Create an ECDSA context for signing*/ ecdsaPkey = TestPkeyNewCtx(NULL, CRYPT_PKEY_ECDSA, CRYPT_EAL_PKEY_KEYMGMT_OPERATE + CRYPT_EAL_PKEY_SIGN_OPERATE, "provider=default", isProvider); ASSERT_TRUE(ecdsaPkey != NULL); /* Set para by curve id and set private key */ ASSERT_TRUE_AND_LOG("CRYPT_EAL_PkeySetParaById", CRYPT_EAL_PkeySetParaById(ecdsaPkey, eccId) == CRYPT_SUCCESS); Ecc_SetPrvKey(&ecdsaPrvkey, CRYPT_PKEY_ECDSA, prvKeyVector->x, prvKeyVector->len); ASSERT_EQ(CRYPT_EAL_PkeySetPrv(ecdsaPkey, &ecdsaPrvkey), CRYPT_SUCCESS); /* Take over random numbers. */ ASSERT_TRUE(memcpy_s(gkRandBuf, sizeof(gkRandBuf), randVector->x, randVector->len) == 0); gkRandBufLen = randVector->len; STUB_Init(); STUB_Replace(&tmpRpInfo, BN_RandRangeEx, STUB_RandRangeK); /* Sign hash data */ hitlsSignLen = CRYPT_EAL_PkeyGetSignLen(ecdsaPkey); hitlsSign = (uint8_t *)malloc(hitlsSignLen); ASSERT_TRUE(hitlsSign != NULL); ASSERT_EQ(CRYPT_EAL_PkeySignData(ecdsaPkey, hashData->x, hashData->len, hitlsSign, &hitlsSignLen), CRYPT_SUCCESS); /* Reset the stubbed function */ STUB_Reset(&tmpRpInfo); /* Create an ESA context for signature verification. */ ecdsaPkey2 = TestPkeyNewCtx(NULL, CRYPT_PKEY_ECDSA, CRYPT_EAL_PKEY_KEYMGMT_OPERATE + CRYPT_EAL_PKEY_SIGN_OPERATE, "provider=default", isProvider); ASSERT_TRUE_AND_LOG("CRYPT_EAL_PkeyNewCtx", ecdsaPkey2 != NULL); /* Set para by curve id and set public key */ ASSERT_TRUE_AND_LOG("CRYPT_EAL_PkeySetParaById", CRYPT_EAL_PkeySetParaById(ecdsaPkey2, eccId) == CRYPT_SUCCESS); ASSERT_TRUE_AND_LOG( "EccPointToBuffer", EccPointToBuffer(pubKeyX, pubKeyY, pointFormat, &pubKeyVector) == CRYPT_SUCCESS); Ecc_SetPubKey(&ecdsaPubkey, CRYPT_PKEY_ECDSA, pubKeyVector.data, pubKeyVector.len); ASSERT_EQ(CRYPT_EAL_PkeySetPub(ecdsaPkey2, &ecdsaPubkey), CRYPT_SUCCESS); /* Verify hash data */ ASSERT_EQ(CRYPT_EAL_PkeyVerifyData(ecdsaPkey2, hashData->x, hashData->len, hitlsSign, hitlsSignLen), CRYPT_SUCCESS); EXIT: free(hitlsSign); CRYPT_EAL_PkeyFreeCtx(ecdsaPkey); CRYPT_EAL_PkeyFreeCtx(ecdsaPkey2); CRYPT_EAL_RandDeinit(); } /* END_CASE */ /** * @test SDV_CRYPTO_ECDSA_VERIFY_DATA_API_TC001 * @title ECDSA CRYPT_EAL_PkeyVerifyData: Test the validity of parameters. * @precon nan * @brief * 1. Create the context of the ecdsa algorithm, expected result 1 * 2. Set para by curve id, expected result 2 * 3. Verify when there is no public key, expected result 3 * 4. Set public key, expected result 4 * 5. Call the CRYPT_EAL_PkeyVerify method: * (1) pkey = null, expected result 5 * (2) data = null, dataLen != 0 || data != null, dataLen == 0 expected result 5 * (3) sign = null, signLen != 0 or signLen = 0, expected result 8 * (4) sign != null, signLen = 0, expected result 9 * @expect * 1. Success, and the context is not null. * 2. CRYPT_SUCCESS * 3. CRYPT_ECDSA_ERR_EMPTY_KEY * 4. CRYPT_SUCCESS * 5. CRYPT_INVALID_ARG * 6-9. CRYPT_NULL_INPUT */ /* BEGIN_CASE */ void SDV_CRYPTO_ECDSA_VERIFY_DATA_API_TC001( int paraId, Hex *hashData, Hex *pubKeyX, Hex *pubKeyY, Hex *sign, int isProvider) { CRYPT_EAL_PkeyCtx *pkey = NULL; CRYPT_EAL_PkeyPub ecdsaPubkey; KeyData pubKeyVector = {{0}, KEY_MAX_LEN}; TestMemInit(); pkey = TestPkeyNewCtx(NULL, CRYPT_PKEY_ECDSA, CRYPT_EAL_PKEY_KEYMGMT_OPERATE + CRYPT_EAL_PKEY_SIGN_OPERATE, "provider=default", isProvider); ASSERT_TRUE(pkey != NULL); /* Set para by curve id */ ASSERT_EQ(CRYPT_EAL_PkeySetParaById(pkey, paraId), CRYPT_SUCCESS); ASSERT_TRUE_AND_LOG("EccPointToBuffer", EccPointToBuffer(pubKeyX, pubKeyY, 1, &pubKeyVector) == CRYPT_SUCCESS); ASSERT_TRUE( CRYPT_EAL_PkeyVerifyData(pkey, hashData->x, hashData->len, sign->x, sign->len) == CRYPT_ECDSA_ERR_EMPTY_KEY); /* Set public key */ Ecc_SetPubKey(&ecdsaPubkey, CRYPT_PKEY_ECDSA, pubKeyVector.data, pubKeyVector.len); ASSERT_EQ(CRYPT_EAL_PkeySetPub(pkey, &ecdsaPubkey), CRYPT_SUCCESS); /* Input parameter test of CRYPT_EAL_PkeyVerifyData. */ ASSERT_TRUE(CRYPT_EAL_PkeyVerifyData(NULL, hashData->x, hashData->len, sign->x, sign->len) == CRYPT_NULL_INPUT); ASSERT_TRUE(CRYPT_EAL_PkeyVerifyData(pkey, NULL, hashData->len, sign->x, sign->len) == CRYPT_INVALID_ARG); ASSERT_TRUE(CRYPT_EAL_PkeyVerifyData(pkey, hashData->x, 0, sign->x, sign->len) == CRYPT_INVALID_ARG); ASSERT_TRUE(CRYPT_EAL_PkeyVerifyData(pkey, hashData->x, hashData->len, NULL, sign->len) == CRYPT_NULL_INPUT); ASSERT_TRUE(CRYPT_EAL_PkeyVerifyData(pkey, hashData->x, hashData->len, NULL, 0) == CRYPT_NULL_INPUT); ASSERT_TRUE(CRYPT_EAL_PkeyVerifyData(pkey, hashData->x, hashData->len, sign->x, 0) == CRYPT_NULL_INPUT); EXIT: CRYPT_EAL_PkeyFreeCtx(pkey); return; } /* END_CASE */ /** * @test SDV_CRYPTO_ECDSA_GET_SECURITY_BITS_API_TC001 * @title ECDSA CRYPT_EAL_PkeyGetSecurityBits: Test the validity of parameters. * @precon nan * @brief * 1. Create the context of the ecdsa algorithm, expected result 1 * 2. Set para by curve id, expected result 2 * 3. Call the CRYPT_EAL_PkeyVerify method and set the parameter to null, expected result 3 * 4. Call the CRYPT_EAL_PkeyVerify method and the parameter is correct, expected result 4 * @expect * 1. Success, and the context is not null. * 2. CRYPT_SUCCESS * 3. The return value is 0. * 4. The return value is not 0. */ /* BEGIN_CASE */ void SDV_CRYPTO_ECDSA_GET_SECURITY_BITS_API_TC001(int paraId, int securitybits, int isProvider) { CRYPT_EAL_PkeyCtx *ecdsaPkey = NULL; TestMemInit(); /* Create an ECDSA context */ ecdsaPkey = TestPkeyNewCtx(NULL, CRYPT_PKEY_ECDSA, CRYPT_EAL_PKEY_KEYMGMT_OPERATE, "provider=default", isProvider); ASSERT_TRUE_AND_LOG("New ECDSA Pkey", ecdsaPkey != NULL); ASSERT_EQ(CRYPT_EAL_PkeySetParaById(ecdsaPkey, paraId), CRYPT_SUCCESS); /* Input parameter test of CRYPT_EAL_PkeyGetSecurityBits. */ ASSERT_TRUE(CRYPT_EAL_PkeyGetSecurityBits(NULL) == 0); ASSERT_TRUE(CRYPT_EAL_PkeyGetSecurityBits(ecdsaPkey) == (uint32_t)securitybits); EXIT: CRYPT_EAL_PkeyFreeCtx(ecdsaPkey); return; } /* END_CASE */ /** * @test SDV_CRYPTO_ECDSA_GET_KEY_BITS_API_TC001 * @title ECDSA CRYPT_EAL_PkeyGetKeyBits: Test the validity of parameters. * @precon nan * @brief * 1. Create the context of the ecdsa algorithm, expected result 1 * 2. Set para by curve id, expected result 2 * 3. Call the CRYPT_EAL_PkeyGetKeyBits method and set the parameter to null, expected result 3 * 4. Call the CRYPT_EAL_PkeyGetKeyBits method and the parameter is correct, expected result 4 * @expect * 1. Success, and the context is not null. * 2. CRYPT_SUCCESS * 3. The return value is 0. * 4. The return value is not 0. */ /* BEGIN_CASE */ void SDV_CRYPTO_ECDSA_GET_KEY_BITS_API_TC001(int paraId, int keyBitsLen, int isProvider) { CRYPT_EAL_PkeyCtx *ecdsaPkey = NULL; TestMemInit(); /* Create an ECDSA context */ ecdsaPkey = TestPkeyNewCtx(NULL, CRYPT_PKEY_ECDSA, CRYPT_EAL_PKEY_KEYMGMT_OPERATE, "provider=default", isProvider); ASSERT_TRUE_AND_LOG("New ECDSA Pkey", ecdsaPkey != NULL); ASSERT_EQ(CRYPT_EAL_PkeySetParaById(ecdsaPkey, paraId), CRYPT_SUCCESS); /* Input parameter test of CRYPT_EAL_PkeyGetKeyBits. */ ASSERT_TRUE(CRYPT_EAL_PkeyGetKeyBits(NULL) == 0); ASSERT_TRUE(CRYPT_EAL_PkeyGetKeyBits(ecdsaPkey) == (uint32_t)keyBitsLen); EXIT: CRYPT_EAL_PkeyFreeCtx(ecdsaPkey); return; } /* END_CASE */ /** * @test SDV_CRYPTO_ECDSA_SET_PARA_API_TC001 * @title ECDSA CRYPT_EAL_PkeySetPara: Test the validity of parameters. * @precon Prepare valid private key and invalid private key. * @brief * 1. Create the context of the ecdsa algorithm, expected result 1 * 2. Set the para by eccId, expected result 2 * 3. Call the CRYPT_EAL_PkeySetPara method: * (1) pkey = null, expected result 3 * (2) para = null, expected result 4 * (3) pkey.id != para.id, expected result 5 * (4) The parameter structure is empty, expected result 6 * @expect * 1. Success, and the context is not NULL. * 2. CRYPT_SUCCESS * 3-4. CRYPT_NULL_INPUT * 5. CRYPT_EAL_ERR_ALGID * 6. CRYPT_EAL_ERR_NEW_PARA_FAIL */ /* BEGIN_CASE */ void SDV_CRYPTO_ECDSA_SET_PARA_API_TC001(int paraId, int isProvider) { CRYPT_EAL_PkeyPara para = {0}; CRYPT_EAL_PkeyCtx *pkey = NULL; TestMemInit(); pkey = TestPkeyNewCtx(NULL, CRYPT_PKEY_ECDSA, CRYPT_EAL_PKEY_KEYMGMT_OPERATE, "provider=default", isProvider); ASSERT_TRUE(pkey != NULL); ASSERT_EQ(CRYPT_EAL_PkeySetParaById(pkey, paraId), CRYPT_SUCCESS); /* Input parameter test of CRYPT_EAL_PkeySetPara. */ ASSERT_EQ(CRYPT_EAL_PkeySetPara(NULL, &para), CRYPT_NULL_INPUT); ASSERT_EQ(CRYPT_EAL_PkeySetPara(pkey, NULL), CRYPT_NULL_INPUT); para.id = CRYPT_PKEY_DSA; ASSERT_EQ(CRYPT_EAL_PkeySetPara(pkey, &para), CRYPT_EAL_ERR_ALGID); para.id = CRYPT_PKEY_ECDSA; ASSERT_EQ(CRYPT_EAL_PkeySetPara(pkey, &para), CRYPT_NULL_INPUT); EXIT: CRYPT_EAL_PkeyFreeCtx(pkey); } /* END_CASE */ /** * @test SDV_CRYPTO_ECDSA_SIGN_VERIFY_FUNC_TC001 * @title ECDSA sign and verify test: different hash and curve. * @precon nan * @brief * 1. Init the drbg, expected result 1 * 2. Create context(ecdsaPkey) of the ECDSA algorithm, expected result 2 * 3. Set elliptic curve type, private key and public key, expected result 3 * 4. Take over random numbers, mock BN_RandRange to generate randVector. * 5. Compute the signature by ecdsaPkey, expected result 4 * 6. Compares the hitls signature, expected result 5 * 7. Verify the signature by ecdsaPkey, expected result 6 * 8. Call the CRYPT_EAL_PkeyCopyCtx method to copy the context, expected result 7 * 9. Use the copied context for signing and verification, expected result 8 * @expect * 1. Success, and two contexts are not NULL. * 2-4. CRYPT_SUCCESS * 5. Both are the same. * 6-8. CRYPT_SUCCESS */ /* BEGIN_CASE */ void SDV_CRYPTO_ECDSA_SIGN_VERIFY_FUNC_TC001(int eccId, int mdId, Hex *prvKeyVector, Hex *msg, Hex *signR, Hex *signS, Hex *randVector, Hex *pubKeyX, Hex *pubKeyY, int pointFormat, int isProvider) { if (IsCurveDisabled(eccId) || IsMdAlgDisabled(mdId)) { SKIP_TEST(); } int ret, vectorSignLen, hitlsSginLen; uint8_t *vectorSign = NULL; uint8_t *hitlsSign = NULL; CRYPT_EAL_PkeyCtx *ecdsaPkey = NULL; CRYPT_EAL_PkeyCtx *cpyCtx = NULL; CRYPT_EAL_PkeyPrv ecdsaPrvkey = {0}; CRYPT_EAL_PkeyPub ecdsaPubkey; KeyData pubKeyVector = {{0}, KEY_MAX_LEN}; FuncStubInfo tmpRpInfo; TestMemInit(); ASSERT_EQ(TestRandInit(), CRYPT_SUCCESS); ecdsaPkey = TestPkeyNewCtx(NULL, CRYPT_PKEY_ECDSA, CRYPT_EAL_PKEY_KEYMGMT_OPERATE + CRYPT_EAL_PKEY_SIGN_OPERATE, "provider=default", isProvider); ASSERT_TRUE_AND_LOG("New ECDSA Pkey", ecdsaPkey != NULL); /* Set para by curve id */ ASSERT_EQ(CRYPT_EAL_PkeySetParaById(ecdsaPkey, eccId), CRYPT_SUCCESS); /* Set private key */ Ecc_SetPrvKey(&ecdsaPrvkey, CRYPT_PKEY_ECDSA, prvKeyVector->x, prvKeyVector->len); ASSERT_EQ(CRYPT_EAL_PkeySetPrv(ecdsaPkey, &ecdsaPrvkey), CRYPT_SUCCESS); /* Set public key */ ret = EccPointToBuffer(pubKeyX, pubKeyY, pointFormat, &pubKeyVector); ASSERT_TRUE_AND_LOG("EccPointToBuffer", ret == CRYPT_SUCCESS); Ecc_SetPubKey(&ecdsaPubkey, CRYPT_PKEY_ECDSA, pubKeyVector.data, pubKeyVector.len); ASSERT_EQ(CRYPT_EAL_PkeySetPub(ecdsaPkey, &ecdsaPubkey), CRYPT_SUCCESS); /* Take over random numbers. */ ASSERT_TRUE(memcpy_s(gkRandBuf, sizeof(gkRandBuf), randVector->x, randVector->len) == 0); gkRandBufLen = randVector->len; STUB_Init(); STUB_Replace(&tmpRpInfo, BN_RandRangeEx, STUB_RandRangeK); /* Signature */ hitlsSginLen = CRYPT_EAL_PkeyGetSignLen(ecdsaPkey); hitlsSign = (uint8_t *)malloc(hitlsSginLen); ASSERT_TRUE(hitlsSign != NULL); ret = CRYPT_EAL_PkeySign(ecdsaPkey, mdId, msg->x, msg->len, hitlsSign, (uint32_t *)&hitlsSginLen); ASSERT_TRUE_AND_LOG("CRYPT_EAL_PkeySign", ret == CRYPT_SUCCESS); /* Encode the R and S of the vector. */ vectorSignLen = CRYPT_EAL_PkeyGetSignLen(ecdsaPkey); vectorSign = (uint8_t *)malloc(vectorSignLen); ASSERT_TRUE(vectorSign != NULL); ret = SignEncode(signR, signS, vectorSign, (uint32_t *)&vectorSignLen); ASSERT_TRUE_AND_LOG("SignEncode", ret == CRYPT_SUCCESS); /* Compare the results of HiTLS vs. Vector. */ ASSERT_EQ(hitlsSginLen, vectorSignLen); ASSERT_TRUE(memcmp(vectorSign, hitlsSign, hitlsSginLen) == 0); STUB_Reset(&tmpRpInfo); /* Verify */ ASSERT_TRUE(CRYPT_EAL_PkeyVerify(ecdsaPkey, mdId, msg->x, msg->len, hitlsSign, hitlsSginLen) == CRYPT_SUCCESS); /* Copy the contexts: sign and verify */ cpyCtx = TestPkeyNewCtx(NULL, CRYPT_PKEY_ECDSA, CRYPT_EAL_PKEY_KEYMGMT_OPERATE + CRYPT_EAL_PKEY_SIGN_OPERATE, "provider=default", isProvider); ASSERT_TRUE(cpyCtx != NULL); ASSERT_EQ(CRYPT_EAL_PkeyCopyCtx(cpyCtx, ecdsaPkey), CRYPT_SUCCESS); hitlsSginLen = CRYPT_EAL_PkeyGetSignLen(cpyCtx); ASSERT_EQ(CRYPT_EAL_PkeySign(cpyCtx, mdId, msg->x, msg->len, hitlsSign, (uint32_t *)&hitlsSginLen), CRYPT_SUCCESS); ASSERT_EQ(CRYPT_EAL_PkeyVerify(cpyCtx, mdId, msg->x, msg->len, hitlsSign, hitlsSginLen), CRYPT_SUCCESS); EXIT: STUB_Reset(&tmpRpInfo); free(hitlsSign); free(vectorSign); CRYPT_EAL_PkeyFreeCtx(ecdsaPkey); CRYPT_EAL_PkeyFreeCtx(cpyCtx); TestRandDeInit(); return; } /* END_CASE */ /** * @test SDV_CRYPTO_ECDSA_SET_PUB_FUNC_TC001 * @title Test set public key. * @precon nan * @brief * 1. Init the drbg, expected result 1 * 2. Create context(ecdsaPkey) of the ECDSA algorithm, expected result 2 * 3. Set elliptic curve type, private key and public key, expected result 3 * 4. Convert the format of the public key vector to COMPRESSED, expected result 4 * 5. Call the CRYPT_EAL_PkeySetPub to set public key, expected result 5 * @expect * 1. CRYPT_SUCCESS * 2. Success, and context is not NULL. * 3. CRYPT_SUCCESS * 4. CRYPT_SUCCESS * 5. CRYPT_SUCCESS on result=1 */ /* BEGIN_CASE */ void SDV_CRYPTO_ECDSA_SET_PUB_FUNC_TC001( int eccId, Hex *publicX, Hex *publicY, int result, int pointFormat, int isProvider) { if (IsCurveDisabled(eccId)) { SKIP_TEST(); } int ret; CRYPT_EAL_PkeyCtx *ecdsaPkey = NULL; CRYPT_EAL_PkeyPub ECDSAPubkey; KeyData pubKeyVector = {{0}, KEY_MAX_LEN}; TestMemInit(); ASSERT_EQ(TestRandInit(), CRYPT_SUCCESS); ecdsaPkey = TestPkeyNewCtx(NULL, CRYPT_PKEY_ECDSA, CRYPT_EAL_PKEY_KEYMGMT_OPERATE, "provider=default", isProvider); ASSERT_TRUE_AND_LOG("New ECDSA Pkey", ecdsaPkey != NULL); ASSERT_EQ(CRYPT_EAL_PkeySetParaById(ecdsaPkey, eccId), CRYPT_SUCCESS); ret = EccPointToBuffer(publicX, publicY, pointFormat, &pubKeyVector); ASSERT_TRUE_AND_LOG("EccPointToBuffer", ret == CRYPT_SUCCESS); Ecc_SetPubKey(&ECDSAPubkey, CRYPT_PKEY_ECDSA, pubKeyVector.data, pubKeyVector.len); if (result == 1) { ASSERT_EQ(CRYPT_EAL_PkeySetPub(ecdsaPkey, &ECDSAPubkey), CRYPT_SUCCESS); } else { ASSERT_NE(CRYPT_EAL_PkeySetPub(ecdsaPkey, &ECDSAPubkey), CRYPT_SUCCESS); } EXIT: CRYPT_EAL_PkeyFreeCtx(ecdsaPkey); TestRandDeInit(); return; } /* END_CASE */ /** * @test SDV_CRYPTO_ECDSA_GET_PARA_FUNC_TC001 * @title ECD CRYPT_EAL_PkeyGetPara test. * @precon Registering memory-related functions. * @brief * 1. Create context of the ECDSA algorithm, expected result 1 * 2. Set para, expected result 2 * 3. Get para, expected result 3 * 4. Check whether the set parameters and the obtained parameters are the same, expected result 4 * @expect * 1. Success, and two contexts are not NULL. * 2-3. CRYPT_SUCCESS * 4. The parameters are the same. */ /* BEGIN_CASE */ void SDV_CRYPTO_ECDSA_GET_PARA_FUNC_TC001(Hex *p, Hex *a, Hex *b, Hex *x, Hex *y, Hex *n, Hex *h) { ASSERT_TRUE(EAL_PkeyGetPara_Func_TC001(CRYPT_PKEY_ECDSA, p, a, b, x, y, n, h) == 0); EXIT: return; } /* END_CASE */ /** * @test SDV_CRYPTO_ECDSA_GEN_KEY_FUNC_TC001 * @title ECDSA CRYPT_EAL_PkeyGen test. * @precon nan * @brief * 1. Create context of the ECDSA algorithm, expected result 1 * 2. Set elliptic curve type, expected result 2 * 3. Mock BN_RandRange to STUB_RandRangeK * 4. Init the drbg, expected result 4 * 5. Call the CRYPT_EAL_PkeyGen method to generate a key pair, expected result 5 * 6. Get public key and private key, expected result 6 * 7. Compare the getted key and vector, expected result 7 * @expect * 1. Success, and two contexts are not NULL. * 2. non * 4-6. CRYPT_SUCCESS * 7. The getted key and vector are the same. */ /* BEGIN_CASE */ void SDV_CRYPTO_ECDSA_GEN_KEY_FUNC_TC001( int eccId, Hex *prvKeyVector, Hex *pubKeyX, Hex *pubKeyY, int pointFormat, int isProvider) { if (IsCurveDisabled(eccId)) { SKIP_TEST(); } Ecc_GenKey(CRYPT_PKEY_ECDSA, eccId, prvKeyVector, pubKeyX, pubKeyY, pointFormat, isProvider); } /* END_CASE */ /** * @test SDV_CRYPTO_ECDSA_KEY_PAIR_CHECK_FUNC_TC001 * @title ECDSA: key pair check. * @precon Registering memory-related functions. * @brief * 1. Create two contexts(pubCtx, prvCtx) of the ecdsa algorithm, expected result 1 * 2. Init the drbg, expected result 2 * 3. Set para for pubCtx, expected result 3 * 4. Set public key for pubCtx, expected result 4 * 5. Set para and private key for prvCtx, expected result 5 * 6. Check whether the public key matches the private key, expected result 6 * @expect * 1. Success, and contexts are not NULL. * 2-5. CRYPT_SUCCESS * 6. Return CRYPT_SUCCESS when expect is 1, CRYPT_ECDSA_VERIFY_FAIL otherwise. */ /* BEGIN_CASE */ void SDV_CRYPTO_ECDSA_KEY_PAIR_CHECK_FUNC_TC001( int eccId, Hex *prvKeyVector, Hex *pubKeyX, Hex *pubKeyY, int pointFormat, int expect) { #if !defined(HITLS_CRYPTO_ECDSA_CHECK) (void)eccId; (void)prvKeyVector; (void)pubKeyX; (void)pubKeyY; (void)pointFormat; (void)expect; SKIP_TEST(); #else if (IsCurveDisabled(eccId)) { SKIP_TEST(); } CRYPT_EAL_PkeyCtx *pubCtx = NULL; CRYPT_EAL_PkeyCtx *prvCtx = NULL; CRYPT_EAL_PkeyPrv prv = {0}; CRYPT_EAL_PkeyPub pub = {0}; KeyData pubKeyVector = {{0}, KEY_MAX_LEN}; int expectRet = expect == 1 ? CRYPT_SUCCESS : CRYPT_ECDSA_PAIRWISE_CHECK_FAIL; ASSERT_EQ(EccPointToBuffer(pubKeyX, pubKeyY, pointFormat, &pubKeyVector), CRYPT_SUCCESS); Ecc_SetPubKey(&pub, CRYPT_PKEY_ECDSA, pubKeyVector.data, pubKeyVector.len); Ecc_SetPrvKey(&prv, CRYPT_PKEY_ECDSA, prvKeyVector->x, prvKeyVector->len); TestMemInit(); pubCtx = CRYPT_EAL_PkeyNewCtx(CRYPT_PKEY_ECDSA); prvCtx = CRYPT_EAL_PkeyNewCtx(CRYPT_PKEY_ECDSA); ASSERT_TRUE(pubCtx != NULL && prvCtx != NULL); /* pubCtx*/ ASSERT_EQ(CRYPT_EAL_PkeySetParaById(pubCtx, eccId), CRYPT_SUCCESS); ASSERT_EQ(TestRandInit(), CRYPT_SUCCESS); ASSERT_EQ(CRYPT_EAL_PkeySetPub(pubCtx, &pub), CRYPT_SUCCESS); /* prvCtx*/ ASSERT_EQ(CRYPT_EAL_PkeySetParaById(prvCtx, eccId), CRYPT_SUCCESS); ASSERT_EQ(CRYPT_EAL_PkeySetPrv(prvCtx, &prv), CRYPT_SUCCESS); ASSERT_EQ(CRYPT_EAL_PkeyPairCheck(pubCtx, prvCtx), expectRet); EXIT: TestRandDeInit(); CRYPT_EAL_PkeyFreeCtx(pubCtx); CRYPT_EAL_PkeyFreeCtx(prvCtx); #endif } /* END_CASE */ /* @ * @test SDV_CRYPTO_ECDSA_API_TC026 * @title ECDSA get key length * @brief 1.create ECDSA context. Expect result 1 2.set curve,expect result 2 3.get key length, expect result 3 * @expect 1.context created successfully 2.Success 3.Success @ */ /* BEGIN_CASE */ void SDV_CRYPTO_ECDSA_API_TC026(int paraId, int keyLen, int isProvider) { CRYPT_EAL_PkeyCtx *ecdsaPkey = TestPkeyNewCtx(NULL, CRYPT_PKEY_ECDSA, CRYPT_EAL_PKEY_KEYMGMT_OPERATE, "provider=default", isProvider); ASSERT_EQ(CRYPT_EAL_PkeySetParaById(ecdsaPkey, paraId), CRYPT_SUCCESS); ASSERT_EQ(CRYPT_EAL_PkeyGetKeyLen(ecdsaPkey), keyLen); EXIT: CRYPT_EAL_PkeyFreeCtx(ecdsaPkey); } /* END_CASE */ /** * @test SDV_CRYPTO_GETSECURITYBITS_API_TC001 * @title Get security bits test * @brief * 1. Create context of the ECDSA algorithm, expected result 1 * 2. Set curve type, expected result 2 * 3. Get para, expected result 3 * 4. Obtain security bits are the same, expected result 4 * @expect * 1. Success, and two contexts are not NULL. * 2-3. CRYPT_SUCCESS * 4. The security bits are correct. */ /* BEGIN_CASE */ void SDV_CRYPTO_GETSECURITYBITS_API_TC001(int eccId, Hex *prvKeyVector, int secBits, int isProvider) { CRYPT_EAL_PkeyCtx *ecdsaPkey = NULL; CRYPT_EAL_PkeyPrv ecdsaPrvkey = {0}; ecdsaPkey = TestPkeyNewCtx(NULL, CRYPT_PKEY_ECDSA, CRYPT_EAL_PKEY_KEYMGMT_OPERATE, "provider=default", isProvider); ASSERT_TRUE_AND_LOG("New ECDH Pkey", ecdsaPkey != NULL); // Set elliptic curve type CRYPT_ECC_NISTP224 = 13 ASSERT_EQ(CRYPT_EAL_PkeySetParaById(ecdsaPkey, eccId), CRYPT_SUCCESS); // Set private key ecdsaPrvkey.id = CRYPT_PKEY_ECDSA; ecdsaPrvkey.key.eccPrv.data = prvKeyVector->x; ecdsaPrvkey.key.eccPrv.len = prvKeyVector->len; ASSERT_EQ(CRYPT_EAL_PkeySetPrv(ecdsaPkey, &ecdsaPrvkey), CRYPT_SUCCESS); ASSERT_TRUE(CRYPT_EAL_PkeyGetSecurityBits(ecdsaPkey) == (uint32_t)secBits); EXIT: CRYPT_EAL_PkeyFreeCtx(ecdsaPkey); return; } /* END_CASE */ /** * @test SDV_CRYPTO_ECDSA_CHECK_KEYPAIR_FUNC_TC001 * @title ECDSA CRYPT_EAL_PkeyPairCheck test. */ /* BEGIN_CASE */ void SDV_CRYPTO_ECDSA_CHECK_KEYPAIR_FUNC_TC001(int paraid, int isProvider) { #if !defined(HITLS_CRYPTO_ECDSA_CHECK) (void)paraid; (void)isProvider; SKIP_TEST(); #else TestMemInit(); uint8_t wrong[KEY_MAX_LEN] = {1}; CRYPT_EAL_PkeyPub ecdsaPubKey = {0}; CRYPT_EAL_PkeyPrv ecdsaPrvKey = {0}; KeyData pubKeyVector = {{0}, KEY_MAX_LEN}; KeyData prvKeyVector = {{0}, KEY_MAX_LEN}; CRYPT_EAL_PkeyCtx *pkey = TestPkeyNewCtx(NULL, CRYPT_PKEY_ECDSA, CRYPT_EAL_PKEY_KEYMGMT_OPERATE, "provider=default", isProvider); CRYPT_EAL_PkeyCtx *pubCtx = TestPkeyNewCtx(NULL, CRYPT_PKEY_ECDSA, CRYPT_EAL_PKEY_KEYMGMT_OPERATE, "provider=default", isProvider); CRYPT_EAL_PkeyCtx *prvCtx = TestPkeyNewCtx(NULL, CRYPT_PKEY_ECDSA, CRYPT_EAL_PKEY_KEYMGMT_OPERATE, "provider=default", isProvider); ASSERT_TRUE(pkey != NULL); ASSERT_TRUE(pubCtx != NULL); ASSERT_TRUE(prvCtx != NULL); ASSERT_EQ(TestRandInit(), CRYPT_SUCCESS); ASSERT_EQ(CRYPT_EAL_PkeySetParaById(pkey, paraid), CRYPT_SUCCESS); ASSERT_EQ(CRYPT_EAL_PkeySetParaById(pubCtx, paraid), CRYPT_SUCCESS); ASSERT_EQ(CRYPT_EAL_PkeySetParaById(prvCtx, paraid), CRYPT_SUCCESS); Ecc_SetPubKey(&ecdsaPubKey, CRYPT_PKEY_ECDSA, pubKeyVector.data, pubKeyVector.len); Ecc_SetPrvKey(&ecdsaPrvKey, CRYPT_PKEY_ECDSA, prvKeyVector.data, prvKeyVector.len); ASSERT_EQ(CRYPT_EAL_PkeyGen(pkey), CRYPT_SUCCESS); ASSERT_EQ(CRYPT_EAL_PkeyPairCheck(pkey, pkey), CRYPT_SUCCESS); ASSERT_EQ(CRYPT_EAL_PkeyPrvCheck(pkey), CRYPT_SUCCESS); ASSERT_EQ(CRYPT_EAL_PkeyGetPub(pkey, &ecdsaPubKey), CRYPT_SUCCESS); ASSERT_EQ(CRYPT_EAL_PkeyGetPrv(pkey, &ecdsaPrvKey), CRYPT_SUCCESS); ASSERT_EQ(CRYPT_EAL_PkeySetPub(pubCtx, &ecdsaPubKey), CRYPT_SUCCESS); ASSERT_EQ(CRYPT_EAL_PkeySetPrv(prvCtx, &ecdsaPrvKey), CRYPT_SUCCESS); ASSERT_EQ(CRYPT_EAL_PkeyPairCheck(pubCtx, prvCtx), CRYPT_SUCCESS); ecdsaPrvKey.key.eccPrv.data = wrong; ASSERT_EQ(CRYPT_EAL_PkeySetPrv(prvCtx, &ecdsaPrvKey), CRYPT_SUCCESS); ASSERT_EQ(CRYPT_EAL_PkeyPairCheck(pubCtx, prvCtx), CRYPT_ECDSA_PAIRWISE_CHECK_FAIL); EXIT: TestRandDeInit(); CRYPT_EAL_PkeyFreeCtx(pkey); CRYPT_EAL_PkeyFreeCtx(pubCtx); CRYPT_EAL_PkeyFreeCtx(prvCtx); #endif } /* END_CASE */ /** * @test SDV_CRYPTO_ECDSA_CHECK_PRVKEY_FUNC_TC001 * @title ECDSA CRYPT_EAL_PkeyPrvCheck test. */ /* BEGIN_CASE */ void SDV_CRYPTO_ECDSA_CHECK_PRVKEY_FUNC_TC001(int paraid, int isProvider) { #if !defined(HITLS_CRYPTO_ECDSA_CHECK) (void)paraid; (void)isProvider; SKIP_TEST(); #else TestMemInit(); CRYPT_EAL_PkeyPrv ecdsaPrvKey = {0}; CRYPT_ECDSA_Ctx *ctx = NULL; BN_BigNum *n = NULL; BN_BigNum *prvKey = NULL; KeyData prvKeyVector = {{0}, KEY_MAX_LEN}; CRYPT_EAL_PkeyCtx *pkey = TestPkeyNewCtx(NULL, CRYPT_PKEY_ECDSA, CRYPT_EAL_PKEY_KEYMGMT_OPERATE, "provider=default", isProvider); CRYPT_EAL_PkeyCtx *prvCtx = TestPkeyNewCtx(NULL, CRYPT_PKEY_ECDSA, CRYPT_EAL_PKEY_KEYMGMT_OPERATE, "provider=default", isProvider); ASSERT_TRUE(pkey != NULL); ASSERT_TRUE(prvCtx != NULL); ASSERT_EQ(TestRandInit(), CRYPT_SUCCESS); ASSERT_EQ(CRYPT_EAL_PkeySetParaById(pkey, paraid), CRYPT_SUCCESS); ASSERT_EQ(CRYPT_EAL_PkeySetParaById(prvCtx, paraid), CRYPT_SUCCESS); Ecc_SetPrvKey(&ecdsaPrvKey, CRYPT_PKEY_ECDSA, prvKeyVector.data, prvKeyVector.len); ASSERT_EQ(CRYPT_EAL_PkeyPrvCheck(NULL), CRYPT_NULL_INPUT); ASSERT_EQ(CRYPT_EAL_PkeyPrvCheck(pkey), CRYPT_ECC_PKEY_ERR_EMPTY_KEY); ASSERT_EQ(CRYPT_EAL_PkeyGen(pkey), CRYPT_SUCCESS); ASSERT_EQ(CRYPT_EAL_PkeyPrvCheck(pkey), CRYPT_SUCCESS); ctx = (CRYPT_ECDSA_Ctx *)pkey->key; prvKey = ctx->prvkey; n = ECC_GetParaN(ctx->para); (void)BN_Copy(prvKey, n); ASSERT_EQ(CRYPT_EAL_PkeyPrvCheck(pkey), CRYPT_ECDSA_INVALID_PRVKEY); (void)BN_SubLimb(prvKey, prvKey, 1); // key = n - 1 ASSERT_EQ(CRYPT_EAL_PkeyPrvCheck(pkey), CRYPT_SUCCESS); (void)BN_Zeroize(prvKey); // key = 0 ASSERT_EQ(CRYPT_EAL_PkeyPrvCheck(pkey), CRYPT_ECDSA_INVALID_PRVKEY); EXIT: TestRandDeInit(); CRYPT_EAL_PkeyFreeCtx(pkey); CRYPT_EAL_PkeyFreeCtx(prvCtx); BN_Destroy(n); #endif } /* END_CASE */
2301_79861745/bench_create
testcode/sdv/testcase/crypto/ecc/test_suite_sdv_eal_ecdsa.c
C
unknown
59,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. */ /* BEGIN_HEADER */ #include <stdlib.h> #include <stdio.h> #include <string.h> #include <pthread.h> #include "bsl_err.h" #include "bsl_sal.h" #include "crypt_errno.h" #include "crypt_eal_pkey.h" #include "crypt_eal_rand.h" #include "crypt_bn.h" #include "eal_pkey_local.h" #include "stub_replace.h" #include "crypt_util_rand.h" #include "crypt_elgamal.h" #include "elgamal_local.h" #include "bn_basic.h" #include "securec.h" /* END_HEADER */ #define CRYPT_EAL_PKEY_KEYMGMT_OPERATE 0 #define CRYPT_EAL_PKEY_CIPHER_OPERATE 1 #define CRYPT_EAL_PKEY_EXCH_OPERATE 2 #define CRYPT_EAL_PKEY_SIGN_OPERATE 4 void *malloc_fail(uint32_t size) { (void)size; return NULL; } void SetElGamalPara(CRYPT_EAL_PkeyPara *para, Hex *q, uint32_t bits,uint32_t k_bits) { para->id = CRYPT_PKEY_ELGAMAL; para->para.elgamalPara.q = q->x; para->para.elgamalPara.qLen = q->len; para->para.elgamalPara.bits = bits; para->para.elgamalPara.k_bits = k_bits; } void SetElGamalPubKey(CRYPT_EAL_PkeyPub *pubKey, uint8_t *g, uint32_t gLen, uint8_t *p, uint32_t pLen, uint8_t *y, uint32_t yLen, uint8_t *q, uint32_t qLen) { pubKey->id = CRYPT_PKEY_ELGAMAL; pubKey->key.elgamalPub.g = g; pubKey->key.elgamalPub.gLen = gLen; pubKey->key.elgamalPub.p = p; pubKey->key.elgamalPub.pLen = pLen; pubKey->key.elgamalPub.y = y; pubKey->key.elgamalPub.yLen = yLen; pubKey->key.elgamalPub.q = q; pubKey->key.elgamalPub.qLen = qLen; } void SetElGamalPrvKey(CRYPT_EAL_PkeyPrv *prvKey, uint8_t *x, uint32_t xLen) { prvKey->id = CRYPT_PKEY_ELGAMAL; prvKey->key.elgamalPrv.x = x; prvKey->key.elgamalPrv.xLen = xLen; } int32_t RandFunc(uint8_t *randNum, uint32_t randLen) { const int maxNum = 255; for (uint32_t i = 0; i < randLen; i++) { randNum[i] = (uint8_t)(rand() % maxNum); } return 0; } int32_t RandFuncEx(void *libCtx, uint8_t *randNum, uint32_t randLen) { (void)libCtx; return RandFunc(randNum, randLen); } /** * @test SDV_CRYPTO_ELGAMAL_NEW_API_TC001 * @title ELGAMAL CRYPT_EAL_PkeyNewCtx test. * @precon nan * @brief * 1. Call the CRYPT_EAL_PkeyNewCtx method to create ctx, algId is CRYPT_PKEY_ELGAMAL, expected result 1. * 2. Release the ctx. * 3. Repeat steps 1 to 2 for 100 times. * @expect * 1. The returned result is not empty. */ /* BEGIN_CASE */ void SDV_CRYPTO_ELGAMAL_NEW_API_TC001(int isProvider) { TestMemInit(); CRYPT_EAL_PkeyCtx *pkey = NULL; /* Run 100 times */ for (int i = 0; i < 100; i++) { pkey = TestPkeyNewCtx(NULL, CRYPT_PKEY_ELGAMAL, CRYPT_EAL_PKEY_KEYMGMT_OPERATE, "provider=default", isProvider); ASSERT_TRUE(pkey != NULL); CRYPT_EAL_PkeyFreeCtx(pkey); } EXIT: return; } /* END_CASE */ /** * @test SDV_CRYPTO_ELGAMAL_NEW_API_TC002 * @title ELGAMAL CRYPT_EAL_PkeyNewCtx test: Malloc failed. * @precon Mock BSL_SAL_Malloc to malloc_fail. * @brief * 1. Call the CRYPT_EAL_PkeyNewCtx method to create ctx, algId is CRYPT_PKEY_ELGAMAL, expected result 1. * 2. Release the ctx. * 3. Reset the BSL_SAL_Malloc. * @expect * 1. Failed to create the ctx. */ /* BEGIN_CASE */ void SDV_CRYPTO_ELGAMAL_NEW_API_TC002(int isProvider) { CRYPT_EAL_PkeyCtx *pkey = NULL; FuncStubInfo tmpRpInfo = {0}; STUB_Init(); ASSERT_TRUE(STUB_Replace(&tmpRpInfo, BSL_SAL_Malloc, malloc_fail) == 0); TestMemInit(); pkey = TestPkeyNewCtx(NULL, CRYPT_PKEY_ELGAMAL, CRYPT_EAL_PKEY_KEYMGMT_OPERATE, "provider=default", isProvider); ASSERT_TRUE(pkey == NULL); EXIT: STUB_Reset(&tmpRpInfo); CRYPT_EAL_PkeyFreeCtx(pkey); } /* END_CASE */ /** * @test SDV_CRYPTO_ELGAMAL_SET_PARA_API_TC001 * @title ELGAMAL CRYPT_EAL_PkeySetPara test. * @precon Create the context of the elgamal algorithm. * * @brief * 1. Call the CRYPT_EAL_PkeySetPara method: * (1) para = NULL, expected result 1. * (2) qLen != BN_BITS_TO_BYTES(k_bits), expected result 2. * (3) q = NULL, bits = 0, expected result 2. * (4) qLen = BN_BITS_TO_BYTES(k_bits), bits != 0, expected result 3. * @expect * 1. CRYPT_NULL_INPUT * 2. CRYPT_EAL_ERR_NEW_PARA_FAIL * 3. CRYPT_SUCCESS */ /* BEGIN_CASE */ void SDV_CRYPTO_ELGAMAL_SET_PARA_API_TC001(Hex *q,int k_bits, int bits, int isProvider) { CRYPT_EAL_PkeyCtx *pkey = NULL; CRYPT_EAL_PkeyPara para = {0}; SetElGamalPara(&para, q, bits , k_bits); TestMemInit(); pkey = TestPkeyNewCtx(NULL, CRYPT_PKEY_ELGAMAL, CRYPT_EAL_PKEY_KEYMGMT_OPERATE, "provider=default", isProvider); ASSERT_TRUE(pkey != NULL); ASSERT_EQ(CRYPT_EAL_PkeySetPara(pkey, NULL), CRYPT_NULL_INPUT); uint32_t bytes = BN_BITS_TO_BYTES(k_bits); if (q->len != bytes) { ASSERT_TRUE_AND_LOG("qLen != BN_BITS_TO_BYTES(k_bits)", CRYPT_EAL_PkeySetPara(pkey, &para) == CRYPT_MEM_ALLOC_FAIL); } if ( q->len == bytes && bits == 0) { ASSERT_TRUE_AND_LOG(" q = NULL, bits = 0", CRYPT_EAL_PkeySetPara(pkey, &para) == CRYPT_MEM_ALLOC_FAIL); } if (q->len == bytes && bits <= k_bits ){ ASSERT_TRUE_AND_LOG(" bits <= k_bits ", CRYPT_EAL_PkeySetPara(pkey, &para) == CRYPT_MEM_ALLOC_FAIL); } if (q->len == bytes && bits != 0) { ASSERT_TRUE(CRYPT_EAL_PkeySetPara(pkey, &para) == CRYPT_SUCCESS); } EXIT: CRYPT_EAL_PkeyFreeCtx(pkey); } /* END_CASE */ /** * @test SDV_CRYPTO_ELGAMAL_GEN_API_TC001 * @title ELGAMAL CRYPT_EAL_PkeyGen: No regist rand. * @precon Create the contexts of the elgamal algorithm and set para. * @brief * 1. Call the CRYPT_EAL_PkeyGen method to generate a key pair, expected result 1. * @expect * 1. Failed to generate a key pair, the return value is CRYPT_NO_REGIST_RAND. */ /* BEGIN_CASE */ void SDV_CRYPTO_ELGAMAL_GEN_API_TC001( Hex *q,int k_bits, int bits, int isProvider) { CRYPT_EAL_PkeyPara para = {0}; SetElGamalPara(&para, q, bits, k_bits); TestMemInit(); CRYPT_EAL_PkeyCtx *pkey; pkey = TestPkeyNewCtx(NULL, CRYPT_PKEY_ELGAMAL, CRYPT_EAL_PKEY_KEYMGMT_OPERATE, "provider=default", isProvider); ASSERT_TRUE(pkey != NULL); ASSERT_TRUE(CRYPT_EAL_PkeySetPara(pkey, &para) == CRYPT_SUCCESS); ASSERT_EQ(CRYPT_EAL_PkeyGen(pkey), CRYPT_NO_REGIST_RAND); EXIT: CRYPT_EAL_PkeyFreeCtx(pkey); } /* END_CASE */ /** * @test SDV_CRYPTO_ELGAMAL_GET_PUB_API_TC001 * @title ELGAMAL CRYPT_EAL_PkeyGetPub test. * @precon 1. Create the context of the elgamal algorithm. * 2. Initialize the DRBG. * @brief * 1. Call the CRYPT_EAL_PkeyGetPub method without public key, expected result 1 * 2. Set para and generate a key pair, expected result 2 * 3. Call the CRYPT_EAL_PkeyGetPub method: * (1) pkey = NULL, expected result 1. * (2) pub = NULL, expected result 1. * (3) p = NULL, expected result 1. * (4) p != NULL and pLen = 0, expected result 3. * (5) g = NULL, expected result 1. * (6) g != NULL, gLen = 0, expected result 3. * (7) y = NULL, expected result 1. * (8) y != NULL and yLen = 0, expected result 3. * @expect * 1. CRYPT_NULL_INPUT * 2. CRYPT_SUCCESS * 3. CRYPT_BN_BUFF_LEN_NOT_ENOUGH */ /* BEGIN_CASE */ void SDV_CRYPTO_ELGAMAL_GET_PUB_API_TC001( Hex *q, int k_bits, int bits, int isProvider) { CRYPT_EAL_PkeyCtx *pkey = NULL; CRYPT_EAL_PkeyPara para = {0}; CRYPT_EAL_PkeyPub pubKey = {0}; uint8_t pubG[600]; uint8_t pubP[600]; uint8_t pubY[600]; uint8_t pubQ[600]; SetElGamalPara(&para, q, bits,k_bits); SetElGamalPubKey(&pubKey, pubG, 600, pubP, 600,pubY, 600,pubQ,600); TestMemInit(); ASSERT_EQ(TestRandInit(), CRYPT_SUCCESS); pkey = TestPkeyNewCtx(NULL, CRYPT_PKEY_ELGAMAL, CRYPT_EAL_PKEY_KEYMGMT_OPERATE, "provider=default", isProvider); ASSERT_TRUE(pkey != NULL); /* Missing public key */ ASSERT_EQ(CRYPT_EAL_PkeyGetPub(pkey, &pubKey), CRYPT_NULL_INPUT); ASSERT_EQ(CRYPT_EAL_PkeySetPara(pkey, &para), CRYPT_SUCCESS); ASSERT_EQ(CRYPT_EAL_PkeyGen(pkey), CRYPT_SUCCESS); ASSERT_EQ(CRYPT_EAL_PkeyGetPub(NULL, &pubKey), CRYPT_NULL_INPUT); ASSERT_EQ(CRYPT_EAL_PkeyGetPub(pkey, NULL), CRYPT_NULL_INPUT); /* p = NULL */ pubKey.key.elgamalPub.p = NULL; ASSERT_EQ(CRYPT_EAL_PkeyGetPub(pkey, &pubKey), CRYPT_NULL_INPUT); pubKey.key.elgamalPub.p = pubP; /* p != NULL and pLen = 0 */ pubKey.key.elgamalPub.pLen = 0; ASSERT_EQ(CRYPT_EAL_PkeyGetPub(pkey, &pubKey), CRYPT_BN_BUFF_LEN_NOT_ENOUGH); pubKey.key.elgamalPub.pLen = 600; /* g = NULL */ pubKey.key.elgamalPub.g = NULL; ASSERT_EQ(CRYPT_EAL_PkeyGetPub(pkey, &pubKey), CRYPT_NULL_INPUT); pubKey.key.elgamalPub.g = pubG; /* g != NULL, gLen = 0 */ pubKey.key.elgamalPub.gLen = 0; ASSERT_EQ(CRYPT_EAL_PkeyGetPub(pkey, &pubKey), CRYPT_BN_BUFF_LEN_NOT_ENOUGH); /* y = NULL */ pubKey.key.elgamalPub.y = NULL; ASSERT_EQ(CRYPT_EAL_PkeyGetPub(pkey, &pubKey), CRYPT_NULL_INPUT); pubKey.key.elgamalPub.y = pubY; /* y != NULL and yLen = 0 */ pubKey.key.elgamalPub.yLen = 0; ASSERT_EQ(CRYPT_EAL_PkeyGetPub(pkey, &pubKey), CRYPT_BN_BUFF_LEN_NOT_ENOUGH); pubKey.key.elgamalPub.yLen = 600; /* q = NULL */ pubKey.key.elgamalPub.q = NULL; ASSERT_EQ(CRYPT_EAL_PkeyGetPub(pkey, &pubKey), CRYPT_NULL_INPUT); pubKey.key.elgamalPub.q = pubQ; /* q != NULL and qLen = 0 */ pubKey.key.elgamalPub.qLen = 0; ASSERT_EQ(CRYPT_EAL_PkeyGetPub(pkey, &pubKey), CRYPT_BN_BUFF_LEN_NOT_ENOUGH); pubKey.key.elgamalPub.qLen = 600; EXIT: TestRandDeInit(); CRYPT_EAL_PkeyFreeCtx(pkey); } /* END_CASE */ /** * @test SDV_CRYPTO_ELGAMAL_GET_PRV_API_TC001 * @title ELGAMAL CRYPT_EAL_PkeyGetPrv: Bad private key. * @precon 1. Create the context of the elgamal algorithm. * 2. Initialize the DRBG. * @brief * 1. Call the CRYPT_EAL_PkeyGetPrv method without private key, expected result 1 * 2. Set para and generate a key pair, expected result 2 * 3. Call the CRYPT_EAL_PkeyGetPrv method: * (1) pkey = NULL, expected result 1. * (2) prv = NULL, expected result 1. * (3) x = NULL, expected result 1. * (4) x != NULL and xLen = 0, expected result 3. * (5) x != NULL, xLen != 0, , expected result 2. * @expect * 1. CRYPT_NULL_INPUT * 2. CRYPT_SUCCESS * 3. CRYPT_BN_BUFF_LEN_NOT_ENOUGH */ /* BEGIN_CASE */ void SDV_CRYPTO_ELGAMAL_GET_PRV_API_TC001(Hex *q, int k_bits,int bits, int isProvider) { CRYPT_EAL_PkeyCtx *pkey = NULL; CRYPT_EAL_PkeyPrv prvKey = {0}; CRYPT_EAL_PkeyPara para = {0}; uint8_t prvX[600]; SetElGamalPrvKey(&prvKey, prvX, 600); SetElGamalPara(&para, q, bits,k_bits); TestMemInit(); ASSERT_EQ(TestRandInit(), CRYPT_SUCCESS); pkey = TestPkeyNewCtx(NULL, CRYPT_PKEY_ELGAMAL, CRYPT_EAL_PKEY_KEYMGMT_OPERATE, "provider=default", isProvider); ASSERT_TRUE(pkey != NULL); /* Missing private key */ ASSERT_EQ(CRYPT_EAL_PkeyGetPrv(pkey, &prvKey), CRYPT_NULL_INPUT); ASSERT_EQ(CRYPT_EAL_PkeySetPara(pkey, &para), CRYPT_SUCCESS); ASSERT_EQ(CRYPT_EAL_PkeyGen(pkey), CRYPT_SUCCESS); ASSERT_EQ(CRYPT_EAL_PkeyGetPrv(NULL, &prvKey), CRYPT_NULL_INPUT); ASSERT_EQ(CRYPT_EAL_PkeyGetPrv(pkey, NULL), CRYPT_NULL_INPUT); /* x = NULL */ prvKey.key.elgamalPrv.x = NULL; ASSERT_EQ(CRYPT_EAL_PkeyGetPrv(pkey, &prvKey), CRYPT_ELGAMAL_ERR_INPUT_VALUE); prvKey.key.elgamalPrv.x = prvX; /* x != NULL and xLen = 0 */ prvKey.key.elgamalPrv.xLen = 0; ASSERT_EQ(CRYPT_EAL_PkeyGetPrv(pkey, &prvKey), CRYPT_BN_BUFF_LEN_NOT_ENOUGH); prvKey.key.elgamalPrv.xLen = 600; /* x != NULL, xLen != 0 */ ASSERT_EQ(CRYPT_EAL_PkeyGetPrv(pkey, &prvKey), CRYPT_SUCCESS); EXIT: TestRandDeInit(); CRYPT_EAL_PkeyFreeCtx(pkey); } /* END_CASE */ /** * @test SDV_CRYPTO_ELGAMAL_SET_PRV_API_TC001 * @title ELGAMAL CRYPT_EAL_PkeySetPrv: Bad private key. * @precon Create the contexts of the elgamal algorithm and set para: * pkey1: Generate a key pair. * pkey2: set the private key. * @brief * 1. Call the CRYPT_EAL_PkeySetPrv method: * (1) pKey is NULL, expected result 1. * (2) prv is NULL, expected result 1. * (3) p = NULL, expected result 2. * (4) g = NULL, expected result 2. * (5) x = NULL, expected result 2. * (6) pLen = 0, expected result 2. * (7) gLen = 0, expected result 2. * (8) xLen = 0, expected result 2. * @expect * 1. CRYPT_NULL_INPUT * 2. CRYPT_ELGAMAL_ERR_INPUT_VALUE */ /* BEGIN_CASE */ void SDV_CRYPTO_ELGAMAL_SET_PRV_API_TC001(Hex *q,int k_bits, int bits, int isProvider) { CRYPT_EAL_PkeyCtx *pkey = NULL; CRYPT_EAL_PkeyCtx *pkey2 = NULL; CRYPT_EAL_PkeyPara para = {0}; CRYPT_EAL_PkeyPrv prvKey = {0}; uint8_t prvP[600]; uint8_t prvG[600]; uint8_t prvX[600]; SetElGamalPrvKey(&prvKey, prvX, 600); SetElGamalPara(&para, q, bits,k_bits); TestMemInit(); ASSERT_EQ(TestRandInit(), CRYPT_SUCCESS); pkey = TestPkeyNewCtx(NULL, CRYPT_PKEY_ELGAMAL, CRYPT_EAL_PKEY_KEYMGMT_OPERATE, "provider=default", isProvider); pkey2 = TestPkeyNewCtx(NULL, CRYPT_PKEY_ELGAMAL, CRYPT_EAL_PKEY_KEYMGMT_OPERATE, "provider=default", isProvider); ASSERT_TRUE(pkey != NULL && pkey2 != NULL); ASSERT_TRUE(CRYPT_EAL_PkeySetPara(pkey, &para) == CRYPT_SUCCESS); ASSERT_TRUE(CRYPT_EAL_PkeySetPara(pkey2, &para) == CRYPT_SUCCESS); ASSERT_TRUE(CRYPT_EAL_PkeyGen(pkey) == CRYPT_SUCCESS); ASSERT_TRUE(CRYPT_EAL_PkeyGetPrv(pkey, &prvKey) == CRYPT_SUCCESS); /*pKey is NULL*/ ASSERT_TRUE(CRYPT_EAL_PkeySetPrv(NULL, &prvKey) == CRYPT_NULL_INPUT); /*prvKey is NULL*/ ASSERT_TRUE(CRYPT_EAL_PkeySetPrv(pkey2, NULL) == CRYPT_NULL_INPUT); prvKey.key.elgamalPrv.p = prvP; prvKey.key.elgamalPrv.pLen = 600; prvKey.key.elgamalPrv.g= prvG; prvKey.key.elgamalPrv.gLen = 600; /*p = NULL*/ prvKey.key.elgamalPrv.p = NULL; ASSERT_TRUE_AND_LOG("p is NULL", CRYPT_EAL_PkeySetPrv(pkey2, &prvKey) == CRYPT_ELGAMAL_ERR_INPUT_VALUE); prvKey.key.elgamalPrv.p = prvP; /*g = NULL*/ ASSERT_TRUE(CRYPT_EAL_PkeyGetPrv(pkey, &prvKey) == CRYPT_SUCCESS); prvKey.key.elgamalPrv.g = NULL; ASSERT_TRUE_AND_LOG("g is NULL", CRYPT_EAL_PkeySetPrv(pkey2, &prvKey) == CRYPT_ELGAMAL_ERR_INPUT_VALUE); prvKey.key.elgamalPrv.g = prvG; /*x = NULL*/ ASSERT_TRUE(CRYPT_EAL_PkeyGetPrv(pkey, &prvKey) == CRYPT_SUCCESS); prvKey.key.elgamalPrv.x = NULL; ASSERT_TRUE_AND_LOG("x is NULL", CRYPT_EAL_PkeySetPrv(pkey2, &prvKey) == CRYPT_ELGAMAL_ERR_INPUT_VALUE); prvKey.key.elgamalPrv.x = prvX; /*pLen = 0*/ ASSERT_TRUE(CRYPT_EAL_PkeyGetPrv(pkey, &prvKey) == CRYPT_SUCCESS); prvKey.key.elgamalPrv.pLen = 0; ASSERT_TRUE_AND_LOG("pLen is 0", CRYPT_EAL_PkeySetPrv(pkey2, &prvKey) == CRYPT_ELGAMAL_ERR_INPUT_VALUE); prvKey.key.elgamalPrv.pLen = 600; /*gLen = 0*/ ASSERT_TRUE(CRYPT_EAL_PkeyGetPrv(pkey, &prvKey) == CRYPT_SUCCESS); prvKey.key.elgamalPrv.gLen = 0; ASSERT_TRUE_AND_LOG("gLen is 0", CRYPT_EAL_PkeySetPrv(pkey2, &prvKey) == CRYPT_ELGAMAL_ERR_INPUT_VALUE); prvKey.key.elgamalPrv.gLen = 600; /*xLen = 0*/ ASSERT_TRUE(CRYPT_EAL_PkeyGetPrv(pkey, &prvKey) == CRYPT_SUCCESS); prvKey.key.elgamalPrv.xLen = 0; ASSERT_TRUE_AND_LOG("xLen is 0", CRYPT_EAL_PkeySetPrv(pkey2, &prvKey) == CRYPT_ELGAMAL_ERR_INPUT_VALUE); prvKey.key.elgamalPrv.xLen = 600; EXIT: TestRandDeInit(); CRYPT_EAL_PkeyFreeCtx(pkey); CRYPT_EAL_PkeyFreeCtx(pkey2); } /* END_CASE */ /** * @test SDV_CRYPTO_ELGAMAL_SET_PUB_API_TC001 * @title ELGAMAL CRYPT_EAL_PkeyGetPub: Bad public key. * @precon Create the contexts of the elgamal algorithm and set para: * pkey1: Generate a key pair. * pkey2: Set the public key. * @brief * 1. Call the CRYPT_EAL_PkeyGetPub method: * (1) pKey is NULL, expected result 1. * (2) prv is NULL, expected result 1. * (3) p = NULL, expected result 1. * (4) g = NULL, expected result 1. * (5) y = NULL, expected result 1. * @expect * 1. CRYPT_NULL_INPUT */ /* BEGIN_CASE */ void SDV_CRYPTO_ELGAMAL_SET_PUB_API_TC001( Hex *q,int k_bits, int bits, int isProvider) { CRYPT_EAL_PkeyCtx *pkey = NULL; CRYPT_EAL_PkeyCtx *pkey2 = NULL; CRYPT_EAL_PkeyPara para = {0}; CRYPT_EAL_PkeyPub pubKey; uint8_t pubG[600]; uint8_t pubP[600]; uint8_t pubY[600]; uint8_t pubQ[600]; SetElGamalPara(&para, q, bits,k_bits); SetElGamalPubKey(&pubKey, pubP, 600, pubG, 600, pubY, 600, pubQ, 600); TestMemInit(); ASSERT_EQ(TestRandInit(), CRYPT_SUCCESS); pkey = TestPkeyNewCtx(NULL, CRYPT_PKEY_ELGAMAL, CRYPT_EAL_PKEY_KEYMGMT_OPERATE, "provider=default", isProvider); pkey2 = TestPkeyNewCtx(NULL, CRYPT_PKEY_ELGAMAL, CRYPT_EAL_PKEY_KEYMGMT_OPERATE, "provider=default", isProvider); ASSERT_TRUE(pkey != NULL && pkey2 != NULL); ASSERT_TRUE(CRYPT_EAL_PkeySetPara(pkey, &para) == CRYPT_SUCCESS); ASSERT_TRUE(CRYPT_EAL_PkeySetPara(pkey2, &para) == CRYPT_SUCCESS); ASSERT_TRUE(CRYPT_EAL_PkeyGen(pkey) == CRYPT_SUCCESS); /*pKey is NULL*/ ASSERT_TRUE(CRYPT_EAL_PkeySetPub(NULL, &pubKey) == CRYPT_NULL_INPUT); /*pubKey is NULL*/ ASSERT_TRUE(CRYPT_EAL_PkeySetPub(pkey2, NULL) == CRYPT_NULL_INPUT); /*p = NULL*/ ASSERT_TRUE(CRYPT_EAL_PkeyGetPub(pkey, &pubKey) == CRYPT_SUCCESS); pubKey.key.elgamalPub.p = NULL; ASSERT_TRUE_AND_LOG("p is NULL", CRYPT_EAL_PkeySetPub(pkey2, &pubKey) == CRYPT_NULL_INPUT); pubKey.key.elgamalPub.p = pubP; /*g = NULL*/ ASSERT_TRUE(CRYPT_EAL_PkeyGetPub(pkey, &pubKey) == CRYPT_SUCCESS); pubKey.key.elgamalPub.g = NULL; ASSERT_TRUE_AND_LOG("g is NULL", CRYPT_EAL_PkeySetPub(pkey2, &pubKey) == CRYPT_NULL_INPUT); pubKey.key.elgamalPub.g = pubG; /*q = NULL*/ ASSERT_TRUE(CRYPT_EAL_PkeyGetPub(pkey, &pubKey) == CRYPT_SUCCESS); pubKey.key.elgamalPub.q = NULL; ASSERT_TRUE_AND_LOG("g is NULL", CRYPT_EAL_PkeySetPub(pkey2, &pubKey) == CRYPT_NULL_INPUT); pubKey.key.elgamalPub.q = pubQ; /*y = NULL*/ ASSERT_TRUE(CRYPT_EAL_PkeyGetPub(pkey, &pubKey) == CRYPT_SUCCESS); pubKey.key.elgamalPub.y = NULL; ASSERT_TRUE_AND_LOG("y is NULL", CRYPT_EAL_PkeySetPub(pkey2, &pubKey) == CRYPT_NULL_INPUT); pubKey.key.elgamalPub.y = pubY; ASSERT_TRUE(CRYPT_EAL_PkeyGetPub(pkey, &pubKey) == CRYPT_SUCCESS); ASSERT_TRUE_AND_LOG("set prvKey success", CRYPT_EAL_PkeySetPub(pkey2, &pubKey) == CRYPT_SUCCESS); EXIT: TestRandDeInit(); CRYPT_EAL_PkeyFreeCtx(pkey); CRYPT_EAL_PkeyFreeCtx(pkey2); } /* END_CASE */ /** * @test SDV_CRYPTO_ELGAMAL_ENC_API_TC001 * @title ELGAMAL CRYPT_EAL_PkeyEncrypt: Test the validity of input parameters. * @precon Create the context of the elgamal algorithm: * @brief * 1. Call the CRYPT_EAL_PkeyEncrypt method without public key, expected result 1 * 2. Set pubkey, expected result 2 * 3. Call the CRYPT_EAL_PkeyEncrypt method: * (1) pkey = NULL, expected result 3 * (2) data = NULL, expected result 3 * (3) data != NULL dataLen > bytes of ctx, expected result 4 * (4) out = NULL, expected result 3 * (5) outLen = NULL, expected result 3 * (6) outLen = 0, expected result 5 * (7) no modification, expected result 2 * @expect * 1. CRYPT_ELGAMAL_NO_KEY_INFO * 2. CRYPT_SUCCESS * 3. CRYPT_NULL_INPUT * 4. CRYPT_ELGAMAL_ERR_ENC_BITS * 5. CRYPT_ELGAMAL_BUFF_LEN_NOT_ENOUGH */ /* BEGIN_CASE */ void SDV_CRYPTO_ELGAMAL_ENC_API_TC001(Hex *q,Hex *p, Hex *g, Hex *y, Hex *in, int isProvider) { uint8_t crypt[512]; uint32_t cryptLen = 512; CRYPT_EAL_PkeyCtx *pkey = NULL; CRYPT_EAL_PkeyPub pubkey = {0}; SetElGamalPubKey(&pubkey, g->x, g->len, p->x, p->len, y->x, y->len,q->x,q->len); TestMemInit(); ASSERT_EQ(TestRandInit(), CRYPT_SUCCESS); pkey = TestPkeyNewCtx(NULL, CRYPT_PKEY_ELGAMAL, CRYPT_EAL_PKEY_KEYMGMT_OPERATE + CRYPT_EAL_PKEY_CIPHER_OPERATE, "provider=default", isProvider); ASSERT_TRUE(pkey != NULL); ASSERT_EQ(CRYPT_EAL_PkeyEncrypt(pkey, in->x, in->len, crypt, &cryptLen), CRYPT_ELGAMAL_NO_KEY_INFO); ASSERT_TRUE(CRYPT_EAL_PkeySetPub(pkey, &pubkey) == CRYPT_SUCCESS); ASSERT_TRUE(CRYPT_EAL_PkeyEncrypt(NULL, in->x, in->len, crypt, &cryptLen) == CRYPT_NULL_INPUT); ASSERT_TRUE(CRYPT_EAL_PkeyEncrypt(pkey, NULL, in->len, crypt, &cryptLen) == CRYPT_NULL_INPUT); ASSERT_TRUE(CRYPT_EAL_PkeyEncrypt(pkey, in->x, 257, crypt, &cryptLen) == CRYPT_ELGAMAL_ERR_ENC_BITS); ASSERT_TRUE(CRYPT_EAL_PkeyEncrypt(pkey, in->x, in->len, NULL, &cryptLen) == CRYPT_NULL_INPUT); ASSERT_TRUE(CRYPT_EAL_PkeyEncrypt(pkey, in->x, in->len, crypt, NULL) == CRYPT_NULL_INPUT); cryptLen = 0; ASSERT_TRUE(CRYPT_EAL_PkeyEncrypt(pkey, in->x, in->len, crypt, &cryptLen) == CRYPT_ELGAMAL_BUFF_LEN_NOT_ENOUGH); cryptLen = 512; ASSERT_TRUE(CRYPT_EAL_PkeyEncrypt(pkey, in->x, in->len, crypt, &cryptLen) == CRYPT_SUCCESS); EXIT: CRYPT_EAL_PkeyFreeCtx(pkey); TestRandDeInit(); } /* END_CASE */ /** * @test SDV_CRYPTO_ELGAMAL_DEC_API_TC001 * @title ELGAMAL CRYPT_EAL_PkeyDecrypt: Test the validity of input parameters. * @precon Create the context of the elgamal algorithm: * @brief * 1. Call the CRYPT_EAL_PkeyDecrypt method without private key, expected result 1 * 2. Set private key, expected result 2 * 4. Call the CRYPT_EAL_PkeyDecrypt method: * (1) pkey = NULL, expected result 3 * (2) data = NULL, expected result 3 * (3) data != NULL, dataLen = 0, expected result 4 * (4) data != NULL, dataLen is invalid , expected result 4 * (5) out = NULL, expected result 3 * (6) outLen = NULL, expected result 3 * (7) outLen = 0, expected result 5 * (8) no modification, expected result 2 * @expect * 1. CRYPT_ELGAMAL_NO_KEY_INFO * 2. CRYPT_SUCCESS * 3. CRYPT_NULL_INPUT * 4. CRYPT_ELGAMAL_ERR_DEC_BITS * 5. CRYPT_ELGAMAL_BUFF_LEN_NOT_ENOUGH */ /* BEGIN_CASE */ void SDV_CRYPTO_ELGAMAL_DEC_API_TC001(Hex *p, Hex *g ,Hex *x, Hex *in, int isProvider) { uint8_t crypt[512]; uint32_t cryptLen = 512; CRYPT_EAL_PkeyPrv prvkey = {0}; CRYPT_EAL_PkeyCtx *pkey = NULL; SetElGamalPrvKey(&prvkey, x->x, x->len); prvkey.key.elgamalPrv.p = p->x; prvkey.key.elgamalPrv.pLen = p->len; prvkey.key.elgamalPrv.g = g->x; prvkey.key.elgamalPrv.gLen = g->len; TestMemInit(); pkey = TestPkeyNewCtx(NULL, CRYPT_PKEY_ELGAMAL, CRYPT_EAL_PKEY_KEYMGMT_OPERATE + CRYPT_EAL_PKEY_CIPHER_OPERATE, "provider=default", isProvider); ASSERT_TRUE(pkey != NULL); ASSERT_TRUE(CRYPT_EAL_PkeyDecrypt(pkey, in->x, in->len, crypt, &cryptLen) == CRYPT_ELGAMAL_NO_KEY_INFO); ASSERT_TRUE(CRYPT_EAL_PkeySetPrv(pkey, &prvkey) == CRYPT_SUCCESS); ASSERT_TRUE(CRYPT_EAL_PkeyDecrypt(NULL, in->x, in->len, crypt, &cryptLen) == CRYPT_NULL_INPUT); ASSERT_TRUE(CRYPT_EAL_PkeyDecrypt(pkey, NULL, in->len, crypt, &cryptLen) == CRYPT_NULL_INPUT); ASSERT_TRUE(CRYPT_EAL_PkeyDecrypt(pkey, in->x, 0, crypt, &cryptLen) == CRYPT_ELGAMAL_ERR_DEC_BITS); ASSERT_TRUE(CRYPT_EAL_PkeyDecrypt(pkey, in->x, 257, crypt, &cryptLen) == CRYPT_ELGAMAL_ERR_DEC_BITS); ASSERT_TRUE(CRYPT_EAL_PkeyDecrypt(pkey, in->x, in->len, NULL, &cryptLen) == CRYPT_NULL_INPUT); ASSERT_TRUE(CRYPT_EAL_PkeyDecrypt(pkey, in->x, in->len, crypt, NULL) == CRYPT_NULL_INPUT); cryptLen = 0; ASSERT_TRUE(CRYPT_EAL_PkeyDecrypt(pkey, in->x, in->len, crypt, &cryptLen) == CRYPT_ELGAMAL_BUFF_LEN_NOT_ENOUGH); cryptLen = 512; ASSERT_EQ(CRYPT_EAL_PkeyDecrypt(pkey, in->x, in->len, crypt, &cryptLen), CRYPT_SUCCESS); EXIT: CRYPT_EAL_PkeyFreeCtx(pkey); } /* END_CASE */ int Compare_PubKey(CRYPT_EAL_PkeyPub *pubKey1, CRYPT_EAL_PkeyPub *pubKey2) { if (pubKey1->key.elgamalPub.pLen != pubKey2->key.elgamalPub.pLen || pubKey1->key.elgamalPub.gLen != pubKey2->key.elgamalPub.gLen|| pubKey1->key.elgamalPub.qLen != pubKey2->key.elgamalPub. qLen || pubKey1->key.elgamalPub.yLen != pubKey2->key.elgamalPub.yLen) { return -1; // -1 indicates failure } if (memcmp(pubKey1->key.elgamalPub.p, pubKey2->key.elgamalPub.p, pubKey1->key.elgamalPub.pLen) != 0 || memcmp(pubKey1->key.elgamalPub.g, pubKey2->key.elgamalPub.g, pubKey1->key.elgamalPub.gLen) != 0 || memcmp(pubKey1->key.elgamalPub.q, pubKey2->key.elgamalPub.q, pubKey1->key.elgamalPub.qLen) != 0 || memcmp(pubKey1->key.elgamalPub.y, pubKey2->key.elgamalPub.y, pubKey1->key.elgamalPub.yLen) != 0 ) { return -1; // -1 indicates failure } return 0; } int Compare_PrvKey(CRYPT_EAL_PkeyPrv *prvKey1, CRYPT_EAL_PkeyPrv *prvKey2) { if (prvKey1->key.elgamalPrv.pLen != prvKey2->key.elgamalPrv.pLen || prvKey1->key.elgamalPrv.gLen != prvKey2->key.elgamalPrv.gLen || prvKey1->key.elgamalPrv.xLen != prvKey2->key.elgamalPrv.xLen ) { return -1; // -1 indicates failure } if (memcmp(prvKey1->key.elgamalPrv.g, prvKey2->key.elgamalPrv.g, prvKey1->key.elgamalPrv.gLen) != 0 || memcmp(prvKey1->key.elgamalPrv.p, prvKey2->key.elgamalPrv.p, prvKey1->key.elgamalPrv.pLen) != 0 || memcmp(prvKey1->key.elgamalPrv.x, prvKey2->key.elgamalPrv.x, prvKey1->key.elgamalPrv.xLen) != 0) { return -1; // -1 indicates failure } return 0; } /** * @test SDV_CRYPTO_ELGAMAL_SET_KEY_API_TC001 * @title ELGAMAL Set the public key and private key multiple times. * @precon Create the contexts of the elgamal algorithm and: * pkey1: Set paran and generate a key pair: test obtaining the key. * pkey2: Test set keys, and verify that the public and private keys can exist at the same time. * @brief * 1. pkey1: Get public key and get private key, expected result 1 * 2. pkey2: * (1) Set public key and set private key, expected result 1 * (2) Get public key, get private key and check private key, expected result 2 * (3) Set private key and set public key, expected result 3 * (4) Get private key, get public key and check public key, expected result 4 * @expect * 1. CRYPT_SUCCESS * 2. The obtained private key is equal to the set private key. * 3. CRYPT_SUCCESS * 4. The obtained public key is equal to the set public key. */ /* BEGIN_CASE */ void SDV_CRYPTO_ELGAMAL_SET_KEY_API_TC001( Hex *q, int k_bits, int bits, int isProvider) { uint8_t pubP[600]; uint8_t pubG[600]; uint8_t pubQ[600]; uint8_t pubY[600]; uint8_t prvP[600]; uint8_t prvG[600]; uint8_t prvX[600]; CRYPT_EAL_PkeyPara para = {0}; CRYPT_EAL_PkeyPub pubKey = {0}; CRYPT_EAL_PkeyPrv prvKey = {0}; SetElGamalPara(&para, q, bits, k_bits); SetElGamalPubKey(&pubKey, pubG, 600, pubP, 600, pubY, 600, pubQ, 600); SetElGamalPrvKey(&prvKey, prvX, 600); prvKey.key.elgamalPrv.p = prvP; prvKey.key.elgamalPrv.pLen = 600; prvKey.key.elgamalPrv.g = prvG; prvKey.key.elgamalPrv.gLen = 600; TestMemInit(); CRYPT_RandRegist(RandFunc); CRYPT_RandRegistEx(RandFuncEx); CRYPT_EAL_PkeyCtx *pkey1 = TestPkeyNewCtx(NULL, CRYPT_PKEY_ELGAMAL, CRYPT_EAL_PKEY_KEYMGMT_OPERATE, "provider=default", isProvider); CRYPT_EAL_PkeyCtx *pkey2 = TestPkeyNewCtx(NULL, CRYPT_PKEY_ELGAMAL, CRYPT_EAL_PKEY_KEYMGMT_OPERATE, "provider=default", isProvider); ASSERT_TRUE(pkey1 != NULL && pkey2 != NULL); /* pkey1 */ /* Generate a key pair. */ ASSERT_TRUE(CRYPT_EAL_PkeySetPara(pkey1, &para) == CRYPT_SUCCESS); ASSERT_EQ(CRYPT_EAL_PkeyGen(pkey1), CRYPT_SUCCESS); /* Get keys. */ ASSERT_EQ(CRYPT_EAL_PkeyGetPub(pkey1, &pubKey), CRYPT_SUCCESS); ASSERT_EQ(CRYPT_EAL_PkeyGetPrv(pkey1, &prvKey), CRYPT_SUCCESS); /* pkey2 */ /* Set public key and set private key. */ ASSERT_EQ(CRYPT_EAL_PkeySetPub(pkey2, &pubKey), CRYPT_SUCCESS); ASSERT_EQ(CRYPT_EAL_PkeySetPrv(pkey2, &prvKey), CRYPT_SUCCESS); /* Get public key, get private key and check private key.*/ SetElGamalPubKey(&pubKey, pubG, 600, pubP, 600, pubY, 600, pubQ, 600); ASSERT_EQ(CRYPT_EAL_PkeyGetPub(pkey2, &pubKey), CRYPT_SUCCESS); SetElGamalPrvKey(&prvKey, prvX, 600); prvKey.key.elgamalPrv.p = prvP; prvKey.key.elgamalPrv.pLen = 600; prvKey.key.elgamalPrv.g = prvG; prvKey.key.elgamalPrv.gLen = 600; ASSERT_EQ(CRYPT_EAL_PkeyGetPrv(pkey2, &prvKey), CRYPT_SUCCESS); ASSERT_EQ(Compare_PrvKey(&prvKey, &prvKey), 0); /* Set private key and set public key. */ ASSERT_EQ(CRYPT_EAL_PkeyGetPrv(pkey2, &prvKey), CRYPT_SUCCESS); ASSERT_EQ(CRYPT_EAL_PkeySetPub(pkey2, &pubKey), CRYPT_SUCCESS); /* Get private key, get public key and check public key.*/ ASSERT_EQ(CRYPT_EAL_PkeyGetPrv(pkey2, &prvKey), CRYPT_SUCCESS); SetElGamalPubKey(&pubKey, pubG, 600, pubP, 600, pubY, 600, pubQ, 600); ASSERT_EQ(CRYPT_EAL_PkeyGetPub(pkey2, &pubKey), CRYPT_SUCCESS); ASSERT_EQ(Compare_PubKey(&pubKey, &pubKey), 0); EXIT: CRYPT_EAL_PkeyFreeCtx(pkey1); CRYPT_EAL_PkeyFreeCtx(pkey2); CRYPT_RandRegist(NULL); CRYPT_RandRegistEx(NULL); } /* END_CASE */ /** * @test SDV_CRYPTO_ELGAMAL_DUP_CTX_API_TC001 * @title ELGAMAL CRYPT_EAL_PkeyDupCtx test. * @precon Create the contexts of the elgamal algorithm, set para and generate a key pair. * @brief * 1. Call the CRYPT_EAL_PkeyDupCtx mehod to dup elgamal, expected result 1 * @expect * 1. Success. */ /* BEGIN_CASE */ void SDV_CRYPTO_ELGAMAL_DUP_CTX_API_TC001( Hex *q,int k_bits, int bits, int isProvider) { CRYPT_EAL_PkeyPara para = {0}; CRYPT_EAL_PkeyCtx *newPkey = NULL; CRYPT_EAL_PkeyCtx *pkey = NULL; SetElGamalPara(&para, q,bits, k_bits); TestMemInit(); CRYPT_RandRegist(RandFunc); CRYPT_RandRegistEx(RandFuncEx); pkey = TestPkeyNewCtx(NULL, CRYPT_PKEY_ELGAMAL, CRYPT_EAL_PKEY_KEYMGMT_OPERATE, "provider=default", isProvider); ASSERT_TRUE(pkey != NULL); ASSERT_EQ(CRYPT_EAL_PkeySetPara(pkey, &para), 0); ASSERT_EQ(CRYPT_EAL_PkeyGen(pkey), CRYPT_SUCCESS); CRYPT_ELGAMAL_Ctx *elgamalCtx = (CRYPT_ELGAMAL_Ctx *)pkey->key; ASSERT_TRUE(elgamalCtx != NULL); newPkey = CRYPT_EAL_PkeyDupCtx(pkey); ASSERT_TRUE(newPkey != NULL); ASSERT_EQ(newPkey->references.count, 1); CRYPT_ELGAMAL_Ctx *elgamalCtx2 = (CRYPT_ELGAMAL_Ctx *)newPkey->key; ASSERT_TRUE(elgamalCtx2 != NULL); ASSERT_COMPARE("elgamal compare x", elgamalCtx->prvKey->x->data, elgamalCtx->prvKey->x->size * sizeof(BN_UINT), elgamalCtx2->prvKey->x->data, elgamalCtx2->prvKey->x->size * sizeof(BN_UINT)); EXIT: CRYPT_EAL_PkeyFreeCtx(pkey); CRYPT_EAL_PkeyFreeCtx(newPkey); CRYPT_RandRegist(NULL); CRYPT_RandRegistEx(NULL); } /* END_CASE */ /** * @test SDV_CRYPTO_ELGAMAL_GET_SECURITY_BITS_FUNC_TC001 * @title ELGAMAL CRYPT_EAL_PkeyGetSecurityBits test. * @precon nan * @brief * 1. Create the context of the elgamal algorithm, expected result 1 * 2. Set public key, expected result 2 * 3. Call the CRYPT_EAL_PkeyVerify method and the parameter is correct, expected result 3 * @expect * 1. Success, and the context is not null. * 2. CRYPT_SUCCESS * 3. The return value is not 0. */ /* BEGIN_CASE */ void SDV_CRYPTO_ELGAMAL_GET_SECURITY_BITS_FUNC_TC001(Hex *q,Hex *p, Hex *g, Hex *y, int securityBits, int isProvider) { CRYPT_EAL_PkeyCtx *pkey = NULL; CRYPT_EAL_PkeyPub pubkey = {0}; SetElGamalPubKey(&pubkey, g->x, g->len, p->x, p->len, y->x, y->len, q->x, q->len); TestMemInit(); pkey = TestPkeyNewCtx(NULL, CRYPT_PKEY_ELGAMAL, CRYPT_EAL_PKEY_KEYMGMT_OPERATE, "provider=default", isProvider); ASSERT_TRUE(pkey != NULL); ASSERT_EQ(CRYPT_EAL_PkeySetPub(pkey, &pubkey), CRYPT_SUCCESS); ASSERT_EQ(CRYPT_EAL_PkeyGetSecurityBits(pkey), securityBits); EXIT: CRYPT_EAL_PkeyFreeCtx(pkey); }
2301_79861745/bench_create
testcode/sdv/testcase/crypto/elgamal/test_suite_sdv_eal_elgamal.c
C
unknown
32,586
/* * This file is part of the openHiTLS project. * * openHiTLS is licensed under the Mulan PSL v2. * You can use this software according to the terms and conditions of the Mulan PSL v2. * You may obtain a copy of Mulan PSL v2 at: * * http://license.coscl.org.cn/MulanPSL2 * * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. * See the Mulan PSL v2 for more details. */ /* BEGIN_HEADER */ #include <unistd.h> #include <stdlib.h> #include <pthread.h> #include <string.h> #include "securec.h" #include "bsl_sal.h" #include "bsl_asn1_internal.h" #include "bsl_err.h" #include "bsl_log.h" #include "bsl_init.h" #include "sal_file.h" #include "crypt_eal_pkey.h" #include "crypt_errno.h" #include "crypt_eal_codecs.h" #include "crypt_eal_init.h" #include "crypt_encode_decode_local.h" #include "crypt_encode_decode_key.h" #include "crypt_util_rand.h" #include "bsl_obj_internal.h" #include "crypt_eal_rand.h" #include "bsl_params.h" #include "crypt_params_key.h" /* END_HEADER */ // clang-format off /* They are placed in their respective implementations and belong to specific applications, not asn1 modules */ #define BSL_ASN1_CTX_SPECIFIC_TAG_VER 0 #define BSL_ASN1_CTX_SPECIFIC_TAG_ISSUERID 1 #define BSL_ASN1_CTX_SPECIFIC_TAG_SUBJECTID 2 #define BSL_ASN1_CTX_SPECIFIC_TAG_EXTENSION 3 BSL_ASN1_TemplateItem rsaPrvTempl[] = { {BSL_ASN1_TAG_CONSTRUCTED | BSL_ASN1_TAG_SEQUENCE, 0, 0}, /* seq */ {BSL_ASN1_TAG_INTEGER, 0, 1}, /* version */ {BSL_ASN1_TAG_INTEGER, 0, 1}, /* n */ {BSL_ASN1_TAG_INTEGER, 0, 1}, /* e */ {BSL_ASN1_TAG_INTEGER, 0, 1}, /* d */ {BSL_ASN1_TAG_INTEGER, 0, 1}, /* p */ {BSL_ASN1_TAG_INTEGER, 0, 1}, /* q */ {BSL_ASN1_TAG_INTEGER, 0, 1}, /* d mod (p-1) */ {BSL_ASN1_TAG_INTEGER, 0, 1}, /* d mod (q-1) */ {BSL_ASN1_TAG_INTEGER, 0, 1}, /* q^-1 mod p */ {BSL_ASN1_TAG_CONSTRUCTED | BSL_ASN1_TAG_SEQUENCE, BSL_ASN1_FLAG_OPTIONAL | BSL_ASN1_FLAG_HEADERONLY | BSL_ASN1_FLAG_SAME, 1}, /* OtherPrimeInfos OPTIONAL */ {BSL_ASN1_TAG_CONSTRUCTED | BSL_ASN1_TAG_SEQUENCE, 0, 2}, /* OtherPrimeInfo */ {BSL_ASN1_TAG_INTEGER, 0, 3}, /* ri */ {BSL_ASN1_TAG_INTEGER, 0, 3}, /* di */ {BSL_ASN1_TAG_INTEGER, 0, 3} /* ti */ }; typedef enum { RSA_PRV_VERSION_IDX = 0, RSA_PRV_N_IDX = 1, RSA_PRV_E_IDX = 2, RSA_PRV_D_IDX = 3, RSA_PRV_P_IDX = 4, RSA_PRV_Q_IDX = 5, RSA_PRV_DP_IDX = 6, RSA_PRV_DQ_IDX = 7, RSA_PRV_QINV_IDX = 8, RSA_PRV_OTHER_PRIME_IDX = 9 } RSA_PRV_TEMPL_IDX; // clang-format on #define BSL_ASN1_TIME_UTC_1 14 #define BSL_ASN1_TIME_UTC_2 15 #define BSL_ASN1_ID_ANY_1 7 #define BSL_ASN1_ID_ANY_2 24 #define BSL_ASN1_ID_ANY_3 34 int32_t BSL_ASN1_CertTagGetOrCheck(int32_t type, uint32_t idx, void *data, void *expVal) { switch (type) { case BSL_ASN1_TYPE_CHECK_CHOICE_TAG: { if (idx == BSL_ASN1_TIME_UTC_1 || idx == BSL_ASN1_TIME_UTC_2) { uint8_t tag = *(uint8_t *)data; if (tag & BSL_ASN1_TAG_UTCTIME || tag & BSL_ASN1_TAG_GENERALIZEDTIME) { *(uint8_t *)expVal = tag; return BSL_SUCCESS; } } return BSL_ASN1_FAIL; } case BSL_ASN1_TYPE_GET_ANY_TAG: { BSL_ASN1_Buffer *param = (BSL_ASN1_Buffer *)data; BslOidString oidStr = {param->len, (char *)param->buff, 0}; BslCid cid = BSL_OBJ_GetCID(&oidStr); if (idx == BSL_ASN1_ID_ANY_1 || idx == BSL_ASN1_ID_ANY_3) { if (cid == BSL_CID_RSASSAPSS) { // note: any It can be encoded empty or it can be null *(uint8_t *)expVal = BSL_ASN1_TAG_CONSTRUCTED | BSL_ASN1_TAG_SEQUENCE; return BSL_SUCCESS; } else { *(uint8_t *)expVal = BSL_ASN1_TAG_NULL; // is null return BSL_SUCCESS; } } if (idx == BSL_ASN1_ID_ANY_2) { if (cid == BSL_CID_EC_PUBLICKEY) { // note: any It can be encoded empty or it can be null *(uint8_t *)expVal = BSL_ASN1_TAG_OBJECT_ID; return BSL_SUCCESS; } else { // *(uint8_t *)expVal = BSL_ASN1_TAG_NULL; // is null return BSL_SUCCESS; } return BSL_ASN1_FAIL; } } default: break; } return BSL_ASN1_FAIL; } int32_t BSL_ASN1_SubKeyInfoTagGetOrCheck(int32_t type, int32_t idx, void *data, void *expVal) { switch (type) { case BSL_ASN1_TYPE_CHECK_CHOICE_TAG: { if (idx == BSL_ASN1_TIME_UTC_1 || idx == BSL_ASN1_TIME_UTC_2) { uint8_t tag = *(uint8_t *)data; if (tag & BSL_ASN1_TAG_UTCTIME || tag & BSL_ASN1_TAG_GENERALIZEDTIME) { return BSL_SUCCESS; } } return BSL_ASN1_FAIL; } case BSL_ASN1_TYPE_GET_ANY_TAG: { BSL_ASN1_Buffer *param = (BSL_ASN1_Buffer *)data; BslOidString oidStr = {param->len, (char *)param->buff, 0}; BslCid cid = BSL_OBJ_GetCID(&oidStr); if (cid == BSL_CID_EC_PUBLICKEY) { // note: any It can be encoded empty or it can be null *(uint8_t *)expVal = BSL_ASN1_TAG_OBJECT_ID; return BSL_SUCCESS; } else { // *(uint8_t *)expVal = BSL_ASN1_TAG_NULL; // is null return BSL_SUCCESS; } } default: break; } return BSL_ASN1_FAIL; } static int32_t ReadCert(const char *path, uint8_t **buff, uint32_t *len) { size_t readLen; size_t fileLen = 0; int32_t ret = BSL_SAL_FileLength(path, &fileLen); if (ret != BSL_SUCCESS) { return ret; } bsl_sal_file_handle stream = NULL; ret = BSL_SAL_FileOpen(&stream, path, "rb"); if (ret != BSL_SUCCESS) { return ret; } uint8_t *fileBuff = BSL_SAL_Malloc(fileLen); if (fileBuff == NULL) { BSL_SAL_FileClose(stream); return BSL_MALLOC_FAIL; } do { ret = BSL_SAL_FileRead(stream, fileBuff, 1, fileLen, &readLen); BSL_SAL_FileClose(stream); if (ret != BSL_SUCCESS) { break; } *buff = fileBuff; *len = (uint32_t)fileLen; return ret; } while (0); BSL_SAL_FREE(fileBuff); return ret; } void BinLogFixLenFunc(uint32_t logId, uint32_t logLevel, uint32_t logType, void *format, void *para1, void *para2, void *para3, void *para4) { (void)logLevel; (void)logType; printf("logId:%u\t", logId); printf(format, para1, para2, para3, para4); printf("\n"); } void BinLogVarLenFunc(uint32_t logId, uint32_t logLevel, uint32_t logType, void *format, void *para) { (void)logLevel; (void)logType; printf("logId:%u\t", logId); printf(format, para); printf("\n"); } static void RegisterLogFunc() { BSL_LOG_BinLogFuncs func = {0}; func.fixLenFunc = BinLogFixLenFunc; func.varLenFunc = BinLogVarLenFunc; BSL_LOG_RegBinLogFunc(&func); BSL_GLOBAL_Init(); } static int32_t RandFunc(uint8_t *randNum, uint32_t randLen) { for (uint32_t i = 0; i < randLen; i++) { randNum[i] = (uint8_t)rand(); } return 0; } static int32_t RandFuncEx(void *libCtx, uint8_t *randNum, uint32_t randLen) { (void)libCtx; for (uint32_t i = 0; i < randLen; i++) { randNum[i] = (uint8_t)rand(); } return 0; } /* BEGIN_CASE */ void SDV_BSL_ASN1_PARSE_RSA_PRV_TC001(char *path, Hex *version, Hex *n, Hex *e, Hex *d, Hex *p, Hex *q, Hex *dp, Hex *dq, Hex *qinv, int mdId, Hex *msg, Hex *sign) { RegisterLogFunc(); uint32_t fileLen = 0; uint8_t *fileBuff = NULL; int32_t ret = ReadCert(path, &fileBuff, &fileLen); ASSERT_EQ(ret, BSL_SUCCESS); uint8_t *rawBuff = fileBuff; uint8_t *signdata = NULL; BSL_ASN1_Buffer asnArr[RSA_PRV_OTHER_PRIME_IDX + 1] = {0}; BSL_ASN1_Template templ = {rsaPrvTempl, sizeof(rsaPrvTempl) / sizeof(rsaPrvTempl[0])}; ret = BSL_ASN1_DecodeTemplate(&templ, BSL_ASN1_CertTagGetOrCheck, &fileBuff, &fileLen, asnArr, RSA_PRV_OTHER_PRIME_IDX + 1); ASSERT_EQ(ret, BSL_SUCCESS); ASSERT_EQ(fileLen, 0); // version if (version->len != 0) { ASSERT_EQ_LOG("version compare tag", asnArr[RSA_PRV_VERSION_IDX].tag, BSL_ASN1_TAG_INTEGER); ASSERT_COMPARE("version compare", version->x, version->len, asnArr[RSA_PRV_VERSION_IDX].buff, asnArr[RSA_PRV_VERSION_IDX].len); } // n ASSERT_EQ_LOG("n compare tag", asnArr[RSA_PRV_N_IDX].tag, BSL_ASN1_TAG_INTEGER); ASSERT_COMPARE("n compare", n->x, n->len, asnArr[RSA_PRV_N_IDX].buff, asnArr[RSA_PRV_N_IDX].len); // e ASSERT_EQ_LOG("e compare tag", asnArr[RSA_PRV_E_IDX].tag, BSL_ASN1_TAG_INTEGER); ASSERT_COMPARE("e compare", e->x, e->len, asnArr[RSA_PRV_E_IDX].buff, asnArr[RSA_PRV_E_IDX].len); // d ASSERT_EQ_LOG("d compare tag", asnArr[RSA_PRV_D_IDX].tag, BSL_ASN1_TAG_INTEGER); ASSERT_COMPARE("d compare", d->x, d->len, asnArr[RSA_PRV_D_IDX].buff, asnArr[RSA_PRV_D_IDX].len); // p ASSERT_EQ_LOG("p compare tag", asnArr[RSA_PRV_P_IDX].tag, BSL_ASN1_TAG_INTEGER); ASSERT_COMPARE("p compare", p->x, p->len, asnArr[RSA_PRV_P_IDX].buff, asnArr[RSA_PRV_P_IDX].len); // q ASSERT_EQ_LOG("q compare tag", asnArr[RSA_PRV_Q_IDX].tag, BSL_ASN1_TAG_INTEGER); ASSERT_COMPARE("q compare", q->x, q->len, asnArr[RSA_PRV_Q_IDX].buff, asnArr[RSA_PRV_Q_IDX].len); // d mod (p-1) ASSERT_EQ_LOG("dp compare tag", asnArr[RSA_PRV_DP_IDX].tag, BSL_ASN1_TAG_INTEGER); ASSERT_COMPARE("dp compare", dp->x, dp->len, asnArr[RSA_PRV_DP_IDX].buff, asnArr[RSA_PRV_DP_IDX].len); // d mod (q-1) ASSERT_EQ_LOG("dq compare tag", asnArr[RSA_PRV_DQ_IDX].tag, BSL_ASN1_TAG_INTEGER); ASSERT_COMPARE("dq compare", dq->x, dq->len, asnArr[RSA_PRV_DQ_IDX].buff, asnArr[RSA_PRV_DQ_IDX].len); // qinv ASSERT_EQ_LOG("qinv compare tag", asnArr[RSA_PRV_QINV_IDX].tag, BSL_ASN1_TAG_INTEGER); ASSERT_COMPARE("qinv compare", qinv->x, qinv->len, asnArr[RSA_PRV_QINV_IDX].buff, asnArr[RSA_PRV_QINV_IDX].len); // create CRYPT_EAL_PkeyPrv rsaPrv = {0}; rsaPrv.id = CRYPT_PKEY_RSA; rsaPrv.key.rsaPrv.d = asnArr[RSA_PRV_D_IDX].buff; rsaPrv.key.rsaPrv.dLen = asnArr[RSA_PRV_D_IDX].len; rsaPrv.key.rsaPrv.n = asnArr[RSA_PRV_N_IDX].buff; rsaPrv.key.rsaPrv.nLen = asnArr[RSA_PRV_N_IDX].len; rsaPrv.key.rsaPrv.e = asnArr[RSA_PRV_E_IDX].buff; rsaPrv.key.rsaPrv.eLen = asnArr[RSA_PRV_E_IDX].len; rsaPrv.key.rsaPrv.p = asnArr[RSA_PRV_P_IDX].buff; rsaPrv.key.rsaPrv.pLen = asnArr[RSA_PRV_P_IDX].len; rsaPrv.key.rsaPrv.q = asnArr[RSA_PRV_Q_IDX].buff; rsaPrv.key.rsaPrv.qLen = asnArr[RSA_PRV_Q_IDX].len; rsaPrv.key.rsaPrv.dP = asnArr[RSA_PRV_DP_IDX].buff; rsaPrv.key.rsaPrv.dPLen = asnArr[RSA_PRV_DP_IDX].len; rsaPrv.key.rsaPrv.dQ = asnArr[RSA_PRV_DQ_IDX].buff; rsaPrv.key.rsaPrv.dQLen = asnArr[RSA_PRV_DQ_IDX].len; rsaPrv.key.rsaPrv.qInv = asnArr[RSA_PRV_QINV_IDX].buff; rsaPrv.key.rsaPrv.qInvLen = asnArr[RSA_PRV_QINV_IDX].len; CRYPT_EAL_PkeyCtx *pkeyCtx = CRYPT_EAL_PkeyNewCtx(CRYPT_PKEY_RSA); ASSERT_TRUE(pkeyCtx != NULL); int32_t pkcsv15 = mdId; ASSERT_EQ(CRYPT_EAL_PkeySetPrv(pkeyCtx, &rsaPrv), CRYPT_SUCCESS); ASSERT_EQ(CRYPT_EAL_PkeyCtrl(pkeyCtx, CRYPT_CTRL_SET_RSA_EMSA_PKCSV15, &pkcsv15, sizeof(pkcsv15)), 0); /* Malloc signature buffer */ uint32_t signLen = CRYPT_EAL_PkeyGetSignLen(pkeyCtx); signdata = (uint8_t *)BSL_SAL_Malloc(signLen); ASSERT_TRUE(signdata != NULL); ASSERT_EQ(CRYPT_EAL_PkeySign(pkeyCtx, mdId, msg->x, msg->len, signdata, &signLen), CRYPT_SUCCESS); ASSERT_COMPARE("CRYPT_EAL_PkeySign Compare", sign->x, sign->len, signdata, signLen); EXIT: CRYPT_EAL_PkeyFreeCtx(pkeyCtx); BSL_SAL_FREE(signdata); BSL_SAL_FREE(rawBuff); BSL_GLOBAL_DeInit(); } /* END_CASE */ /* BEGIN_CASE */ void SDV_BSL_ASN1_PARSE_PUBKEY_FILE_TC001(char *path, int fileType, int mdId, Hex *msg, Hex *sign) { RegisterLogFunc(); CRYPT_EAL_PkeyCtx *pkeyCtx = NULL; ASSERT_EQ(CRYPT_EAL_DecodeFileKey(BSL_FORMAT_ASN1, fileType, path, NULL, 0, &pkeyCtx), CRYPT_SUCCESS); if (fileType == CRYPT_PUBKEY_RSA) { int32_t pkcsv15 = mdId; ASSERT_EQ(CRYPT_EAL_PkeyCtrl(pkeyCtx, CRYPT_CTRL_SET_RSA_EMSA_PKCSV15, &pkcsv15, sizeof(pkcsv15)), 0); } /* verify signature */ ASSERT_EQ(CRYPT_EAL_PkeyVerify(pkeyCtx, mdId, msg->x, msg->len, sign->x, sign->len), CRYPT_SUCCESS); EXIT: CRYPT_EAL_PkeyFreeCtx(pkeyCtx); BSL_GLOBAL_DeInit(); } /* END_CASE */ /* BEGIN_CASE */ void SDV_BSL_ASN1_PARSE_SUBPUBKEY_TC001(int encodeType, Hex *subKeyInfo) { RegisterLogFunc(); (void)encodeType; CRYPT_EAL_PkeyCtx *pctx = NULL; ASSERT_EQ(CRYPT_EAL_ParseAsn1SubPubkey(subKeyInfo->x, subKeyInfo->len, (void **)&pctx, false), 0); EXIT: CRYPT_EAL_PkeyFreeCtx(pctx); BSL_GLOBAL_DeInit(); } /* END_CASE */ static int32_t DecodeKeyFile(int isProvider, const char *path, int format, const char *formatStr, int fileType, const char *fileTypeStr, uint8_t *pwd, uint32_t pwdLen, CRYPT_EAL_PkeyCtx **pkeyCtx) { #ifdef HITLS_CRYPTO_PROVIDER (void)format; (void)fileType; if (isProvider) { BSL_Buffer pwdBuff = {pwd, pwdLen}; return CRYPT_EAL_ProviderDecodeFileKey(NULL, NULL, BSL_CID_UNKNOWN, formatStr, fileTypeStr, path, &pwdBuff, pkeyCtx); } else #endif { (void)isProvider; (void)formatStr; (void)fileTypeStr; return CRYPT_EAL_DecodeFileKey(format, fileType, path, pwd, pwdLen, pkeyCtx); } } static int32_t DecodeKeyBuff(int isProvider, BSL_Buffer *encode, int format, const char *formatStr, int fileType, const char *fileTypeStr, uint8_t *pwd, uint32_t pwdLen, CRYPT_EAL_PkeyCtx **pkeyCtx) { #ifdef HITLS_CRYPTO_PROVIDER (void)format; (void)fileType; if (isProvider) { BSL_Buffer pwdBuff = {pwd, pwdLen}; return CRYPT_EAL_ProviderDecodeBuffKey(NULL, NULL, BSL_CID_UNKNOWN, formatStr, fileTypeStr, encode, &pwdBuff, pkeyCtx); } else #endif { (void)isProvider; (void)formatStr; (void)fileTypeStr; return CRYPT_EAL_DecodeBuffKey(format, fileType, encode, pwd, pwdLen, pkeyCtx); } } /* BEGIN_CASE */ void SDV_BSL_ASN1_PARSE_PRIKEY_FILE_TC001(int isProvider, char *path, int fileType, char *fileTypeStr, int mdId, Hex *msg, Hex *sign) { RegisterLogFunc(); CRYPT_RandRegist(RandFunc); CRYPT_RandRegistEx(RandFuncEx); uint8_t *signdata = NULL; CRYPT_EAL_PkeyCtx *pkeyCtx = NULL; ASSERT_EQ(DecodeKeyFile(isProvider, path, BSL_FORMAT_ASN1, "ASN1", fileType, fileTypeStr, NULL, 0, &pkeyCtx), 0); if (fileType == CRYPT_PRIKEY_RSA || strcmp(fileTypeStr, "PRIKEY_RSA") == 0 || CRYPT_EAL_PkeyGetId(pkeyCtx) == CRYPT_PKEY_RSA) { int32_t pkcsv15 = mdId; ASSERT_EQ(CRYPT_EAL_PkeyCtrl(pkeyCtx, CRYPT_CTRL_SET_RSA_EMSA_PKCSV15, &pkcsv15, sizeof(pkcsv15)), 0); } /* Malloc signature buffer */ uint32_t signLen = CRYPT_EAL_PkeyGetSignLen(pkeyCtx); signdata = (uint8_t *)BSL_SAL_Malloc(signLen); ASSERT_TRUE(signdata != NULL); ASSERT_EQ(CRYPT_EAL_PkeySign(pkeyCtx, mdId, msg->x, msg->len, signdata, &signLen), CRYPT_SUCCESS); if (sign->len != 0) { ASSERT_COMPARE("Signature Compare", sign->x, sign->len, signdata, signLen); } EXIT: BSL_SAL_Free(signdata); CRYPT_EAL_PkeyFreeCtx(pkeyCtx); BSL_GLOBAL_DeInit(); } /* END_CASE */ /* BEGIN_CASE */ void SDV_BSL_ASN1_PARSE_ECCPRIKEY_FILE_TC001(int isProvider, char *path, int fileType, char *fileTypeStr, int mdId, Hex *msg, int alg, Hex *rawKey, int paraId) { RegisterLogFunc(); CRYPT_RandRegist(RandFunc); CRYPT_RandRegistEx(RandFuncEx); uint8_t rawPriKey[100] = {0}; uint32_t rawPriKeyLen = 100; uint8_t *signdata = NULL; CRYPT_EAL_PkeyCtx *pkeyCtx = NULL; ASSERT_EQ(DecodeKeyFile(isProvider, path, BSL_FORMAT_ASN1, "ASN1", fileType, fileTypeStr, NULL, 0, &pkeyCtx), 0); CRYPT_EAL_PkeyPrv pkeyPrv = {0}; pkeyPrv.id = alg; pkeyPrv.key.eccPrv.data = rawPriKey; pkeyPrv.key.eccPrv.len = rawPriKeyLen; ASSERT_EQ(CRYPT_EAL_PkeyGetPrv(pkeyCtx, &pkeyPrv), CRYPT_SUCCESS); ASSERT_COMPARE("key cmp", rawKey->x, rawKey->len, rawPriKey, rawKey->len); ASSERT_EQ(CRYPT_EAL_PkeyGetId(pkeyCtx), alg); if (alg != CRYPT_PKEY_SM2) { // sm2 is null ASSERT_EQ(CRYPT_EAL_PkeyGetParaId(pkeyCtx), paraId); } /* Malloc signature buffer */ uint32_t signLen = CRYPT_EAL_PkeyGetSignLen(pkeyCtx); signdata = (uint8_t *)BSL_SAL_Malloc(signLen); ASSERT_TRUE(signdata != NULL); ASSERT_EQ(CRYPT_EAL_PkeySign(pkeyCtx, mdId, msg->x, msg->len, signdata, &signLen), CRYPT_SUCCESS); EXIT: BSL_SAL_Free(signdata); CRYPT_EAL_PkeyFreeCtx(pkeyCtx); BSL_GLOBAL_DeInit(); } /* END_CASE */ /* BEGIN_CASE */ void SDV_BSL_ASN1_PARSE_ED25519PRIKEY_FILE_TC001(int alg, char *path, int format, int type, Hex *prv) { RegisterLogFunc(); uint8_t rawPriKey[32] = {0}; uint32_t rawPriKeyLen = 32; CRYPT_EAL_PkeyPrv pkeyPrv = {0}; pkeyPrv.id = alg; pkeyPrv.key.eccPrv.data = rawPriKey; pkeyPrv.key.eccPrv.len = rawPriKeyLen; CRYPT_EAL_PkeyCtx *pkeyCtx = NULL; ASSERT_EQ(CRYPT_EAL_DecodeFileKey(format, type, path, NULL, 0, &pkeyCtx), CRYPT_SUCCESS); ASSERT_EQ(CRYPT_EAL_PkeyGetPrv(pkeyCtx, &pkeyPrv), CRYPT_SUCCESS); ASSERT_COMPARE("key cmp", prv->x, prv->len, pkeyPrv.key.eccPrv.data, pkeyPrv.key.eccPrv.len); EXIT: CRYPT_EAL_PkeyFreeCtx(pkeyCtx); } /* END_CASE */ /* BEGIN_CASE */ void SDV_BSL_ASN1_PARSE_ED25519PRIKEY_FILE_TC002(char *path, int format, int type, int ret) { CRYPT_EAL_PkeyCtx *pkeyCtx = NULL; ASSERT_EQ(CRYPT_EAL_DecodeFileKey(format, type, path, NULL, 0, &pkeyCtx), ret); EXIT: CRYPT_EAL_PkeyFreeCtx(pkeyCtx); } /* END_CASE */ /* BEGIN_CASE */ void SDV_BSL_ASN1_PARSE_ENCPK8_TC001(int isProvider, char *path, int fileType, char *fileTypeStr, Hex *pass, int mdId, Hex *msg, Hex *sign) { RegisterLogFunc(); CRYPT_RandRegist(RandFunc); CRYPT_RandRegistEx(RandFuncEx); uint8_t *signdata = NULL; CRYPT_EAL_PkeyCtx *pkeyCtx = NULL; ASSERT_EQ(DecodeKeyFile(isProvider, path, BSL_FORMAT_ASN1, "ASN1", fileType, fileTypeStr, pass->x, pass->len, &pkeyCtx), 0); if (fileType == CRYPT_PRIKEY_RSA || CRYPT_EAL_PkeyGetId(pkeyCtx) == CRYPT_PKEY_RSA) { int32_t pkcsv15 = mdId; ASSERT_EQ(CRYPT_EAL_PkeyCtrl(pkeyCtx, CRYPT_CTRL_SET_RSA_EMSA_PKCSV15, &pkcsv15, sizeof(pkcsv15)), 0); } /* Malloc signature buffer */ uint32_t signLen = CRYPT_EAL_PkeyGetSignLen(pkeyCtx); signdata = (uint8_t *)BSL_SAL_Malloc(signLen); ASSERT_TRUE(signdata != NULL); ASSERT_EQ(CRYPT_EAL_PkeySign(pkeyCtx, mdId, msg->x, msg->len, signdata, &signLen), CRYPT_SUCCESS); if (sign->len != 0) { ASSERT_COMPARE("Signature Compare", sign->x, sign->len, signdata, signLen); } EXIT: BSL_SAL_Free(signdata); CRYPT_EAL_PkeyFreeCtx(pkeyCtx); BSL_GLOBAL_DeInit(); } /* END_CASE */ /* BEGIN_CASE */ void SDV_BSL_ASN1_PARSE_BUFF_TC001(int isProvider, char *typeStr, int type, Hex *pass, Hex *data) { RegisterLogFunc(); CRYPT_RandRegist(RandFunc); CRYPT_RandRegistEx(RandFuncEx); BSL_Buffer encode = {data->x, data->len}; CRYPT_EAL_PkeyCtx *pkeyCtx = NULL; int32_t ret; #ifdef HITLS_CRYPTO_PROVIDER ret = isProvider ? CRYPT_DECODE_ERR_NO_USABLE_DECODER : CRYPT_NULL_INPUT; #else ret = CRYPT_NULL_INPUT; #endif ASSERT_EQ(DecodeKeyBuff(isProvider, &encode, BSL_FORMAT_ASN1, "ASN1", type, typeStr, pass->x, pass->len, &pkeyCtx), ret); EXIT: CRYPT_EAL_PkeyFreeCtx(pkeyCtx); } /* END_CASE */ /* BEGIN_CASE */ void SDV_BSL_ASN1_ENCODE_PUBKEY_BUFF_TC001(char *path, int fileType, int isComplete, Hex *asn1) { RegisterLogFunc(); CRYPT_RandRegist(RandFunc); CRYPT_RandRegistEx(RandFuncEx); CRYPT_EAL_PkeyCtx *pkeyCtx = NULL; BSL_Buffer encodeAsn1 = {0}; ASSERT_EQ(CRYPT_EAL_DecodeFileKey(BSL_FORMAT_UNKNOWN, fileType, path, NULL, 0, &pkeyCtx), CRYPT_SUCCESS); ASSERT_EQ(CRYPT_EAL_EncodePubKeyBuffInternal(pkeyCtx, BSL_FORMAT_ASN1, fileType, isComplete, &encodeAsn1), CRYPT_SUCCESS); ASSERT_COMPARE("asn1 compare.", encodeAsn1.data, encodeAsn1.dataLen, asn1->x, asn1->len); EXIT: CRYPT_EAL_PkeyFreeCtx(pkeyCtx); BSL_SAL_FREE(encodeAsn1.data); BSL_GLOBAL_DeInit(); } /* END_CASE */ /* BEGIN_CASE */ void SDV_BSL_PEM_ENCODE_PUBKEY_BUFF_TC001(char *path, int fileType, int isComplete, char *pemPath) { RegisterLogFunc(); CRYPT_RandRegist(RandFunc); CRYPT_RandRegistEx(RandFuncEx); CRYPT_EAL_PkeyCtx *pkeyCtx = NULL; BSL_Buffer encodePem = {0}; ASSERT_EQ(CRYPT_EAL_DecodeFileKey(BSL_FORMAT_UNKNOWN, fileType, path, NULL, 0, &pkeyCtx), CRYPT_SUCCESS); ASSERT_EQ(CRYPT_EAL_EncodePubKeyBuffInternal(pkeyCtx, BSL_FORMAT_PEM, fileType, isComplete, &encodePem), CRYPT_SUCCESS); uint8_t *pem = NULL; uint32_t pemLen = 0; ASSERT_EQ(BSL_SAL_ReadFile(pemPath, &pem, &pemLen), CRYPT_SUCCESS); ASSERT_COMPARE("pem compare.", encodePem.data, encodePem.dataLen, pem, pemLen); EXIT: CRYPT_EAL_PkeyFreeCtx(pkeyCtx); BSL_SAL_FREE(encodePem.data); BSL_SAL_FREE(pem); BSL_GLOBAL_DeInit(); } /* END_CASE */ /* BEGIN_CASE */ void SDV_BSL_ASN1_ENCODE_PRIKEY_BUFF_TC001(char *path, int fileType, Hex *asn1) { RegisterLogFunc(); CRYPT_RandRegist(RandFunc); CRYPT_RandRegistEx(RandFuncEx); CRYPT_EAL_PkeyCtx *pkeyCtx = NULL; BSL_Buffer encodeAsn1 = {0}; ASSERT_EQ(CRYPT_EAL_DecodeFileKey(BSL_FORMAT_UNKNOWN, fileType, path, NULL, 0, &pkeyCtx), CRYPT_SUCCESS); ASSERT_EQ(CRYPT_EAL_EncodeBuffKey(pkeyCtx, NULL, BSL_FORMAT_ASN1, fileType, &encodeAsn1), CRYPT_SUCCESS); ASSERT_COMPARE("asn1 compare.", encodeAsn1.data, encodeAsn1.dataLen, asn1->x, asn1->len); EXIT: CRYPT_EAL_PkeyFreeCtx(pkeyCtx); BSL_SAL_FREE(encodeAsn1.data); BSL_GLOBAL_DeInit(); } /* END_CASE */ /* BEGIN_CASE */ void SDV_BSL_ASN1_ENCODE_ENCRYPTED_PRIKEY_BUFF_TC001(char *path, int fileType, int hmacId, int symId, int saltLen, Hex *pwd, int itCnt, Hex *asn1) { RegisterLogFunc(); CRYPT_EAL_PkeyCtx *pkeyCtx = NULL; BSL_Buffer encodeAsn1 = {0}; BSL_Buffer encodeAsn1Out = {0}; CRYPT_Pbkdf2Param param = {0}; param.pbesId = BSL_CID_PBES2; param.pbkdfId = BSL_CID_PBKDF2; param.hmacId = hmacId; param.symId = symId; param.pwd = pwd->x; param.pwdLen = pwd->len; param.saltLen = saltLen; param.itCnt = itCnt; CRYPT_EncodeParam paramEx = {CRYPT_DERIVE_PBKDF2, &param}; ASSERT_EQ(CRYPT_EAL_DecodeFileKey(BSL_FORMAT_UNKNOWN, fileType, path, pwd->x, pwd->len, &pkeyCtx), CRYPT_SUCCESS); ASSERT_EQ(TestRandInit(), CRYPT_SUCCESS); ASSERT_EQ(CRYPT_EAL_EncodeBuffKey(pkeyCtx, &paramEx, BSL_FORMAT_ASN1, fileType, &encodeAsn1), CRYPT_SUCCESS); CRYPT_EAL_PkeyCtx *decodeCtx = NULL; ASSERT_EQ(CRYPT_EAL_DecodeBuffKey(BSL_FORMAT_ASN1, fileType, &encodeAsn1, pwd->x, pwd->len, &decodeCtx), CRYPT_SUCCESS); ASSERT_EQ(CRYPT_EAL_EncodeBuffKey(decodeCtx, NULL, BSL_FORMAT_ASN1, CRYPT_PRIKEY_PKCS8_UNENCRYPT, &encodeAsn1Out), CRYPT_SUCCESS); ASSERT_COMPARE("asn1 compare.", encodeAsn1Out.data, encodeAsn1Out.dataLen, asn1->x, asn1->len); EXIT: CRYPT_EAL_PkeyFreeCtx(decodeCtx); CRYPT_EAL_PkeyFreeCtx(pkeyCtx); BSL_SAL_FREE(encodeAsn1.data); BSL_SAL_FREE(encodeAsn1Out.data); BSL_GLOBAL_DeInit(); TestRandDeInit(); } /* END_CASE */ /* BEGIN_CASE */ void SDV_BSL_ASN1_ENCODE_PRAPSSPRIKEY_BUFF_TC001(char *path, int fileType, int saltLen, int mdId, int mgfId, Hex *asn1) { RegisterLogFunc(); CRYPT_RandRegist(RandFunc); CRYPT_RandRegistEx(RandFuncEx); CRYPT_EAL_PkeyCtx *pkeyCtx = NULL; BSL_Buffer encodeAsn1 = {0}; ASSERT_EQ(CRYPT_EAL_DecodeFileKey(BSL_FORMAT_UNKNOWN, fileType, path, NULL, 0, &pkeyCtx), CRYPT_SUCCESS); BSL_Param pssParam[4] = { {CRYPT_PARAM_RSA_MD_ID, BSL_PARAM_TYPE_INT32, &mdId, sizeof(mdId), 0}, {CRYPT_PARAM_RSA_MGF1_ID, BSL_PARAM_TYPE_INT32, &mgfId, sizeof(mgfId), 0}, {CRYPT_PARAM_RSA_SALTLEN, BSL_PARAM_TYPE_INT32, &saltLen, sizeof(saltLen), 0}, BSL_PARAM_END}; ASSERT_EQ(CRYPT_EAL_PkeyCtrl(pkeyCtx, CRYPT_CTRL_SET_RSA_EMSA_PSS, pssParam, 0), CRYPT_SUCCESS); ASSERT_EQ(CRYPT_EAL_EncodeBuffKey(pkeyCtx, NULL, BSL_FORMAT_ASN1, fileType, &encodeAsn1), CRYPT_SUCCESS); ASSERT_COMPARE("asn1 compare.", encodeAsn1.data, encodeAsn1.dataLen, asn1->x, asn1->len); EXIT: CRYPT_EAL_PkeyFreeCtx(pkeyCtx); BSL_SAL_FREE(encodeAsn1.data); BSL_GLOBAL_DeInit(); } /* END_CASE */ /* BEGIN_CASE */ void SDV_BSL_ASN1_ENCODE_AND_DECODE_RSAPSS_PUBLICKEY_TC001(int keyLen, int saltLen) { TestMemInit(); CRYPT_RandRegist(RandFunc); CRYPT_RandRegistEx(RandFuncEx); RegisterLogFunc(); uint8_t e[] = {1, 0, 1}; // RSA public exponent CRYPT_EAL_PkeyCtx *pkey = NULL; CRYPT_EAL_PkeyPara para = {0}; CRYPT_EAL_PkeyCtx *decodedPkey = NULL; int32_t mdId = CRYPT_MD_SHA256; BSL_Buffer encode = {0}; // set rsa para para.id = CRYPT_PKEY_RSA; para.para.rsaPara.e = e; para.para.rsaPara.eLen = 3; // public exponent length = 3 para.para.rsaPara.bits = keyLen; // pss param BSL_Param pssParam[4] = { {CRYPT_PARAM_RSA_MD_ID, BSL_PARAM_TYPE_INT32, &mdId, sizeof(mdId), 0}, {CRYPT_PARAM_RSA_MGF1_ID, BSL_PARAM_TYPE_INT32, &mdId, sizeof(mdId), 0}, {CRYPT_PARAM_RSA_SALTLEN, BSL_PARAM_TYPE_INT32, &saltLen, sizeof(saltLen), 0}, BSL_PARAM_END}; // create new pkey ctx pkey = CRYPT_EAL_PkeyNewCtx(CRYPT_PKEY_RSA); ASSERT_TRUE(pkey != NULL); // set para and generate key pair ASSERT_EQ(CRYPT_EAL_PkeySetPara(pkey, &para), CRYPT_SUCCESS); ASSERT_EQ(TestRandInit(), CRYPT_SUCCESS); ASSERT_EQ(CRYPT_EAL_PkeyGen(pkey), CRYPT_SUCCESS); ASSERT_EQ(CRYPT_EAL_PkeyCtrl(pkey, CRYPT_CTRL_SET_RSA_EMSA_PSS, pssParam, 0), CRYPT_SUCCESS); // encode key ASSERT_EQ(CRYPT_EAL_EncodeBuffKey(pkey, NULL, BSL_FORMAT_ASN1, CRYPT_PUBKEY_SUBKEY, &encode), CRYPT_SUCCESS); // decode key ASSERT_EQ(CRYPT_EAL_DecodeBuffKey(BSL_FORMAT_ASN1, CRYPT_PUBKEY_SUBKEY, &encode, NULL, 0, &decodedPkey), CRYPT_SUCCESS); ASSERT_TRUE(decodedPkey != NULL); EXIT: TestRandDeInit(); CRYPT_EAL_PkeyFreeCtx(pkey); CRYPT_EAL_PkeyFreeCtx(decodedPkey); BSL_SAL_FREE(encode.data); } /* END_CASE */ /* BEGIN_CASE */ void SDV_BSL_ASN1_ENCODE_RSAPSS_PUBLICKEY_BUFF_TC002(char *path, Hex *asn1) { RegisterLogFunc(); CRYPT_RandRegist(RandFunc); CRYPT_RandRegistEx(RandFuncEx); CRYPT_EAL_PkeyCtx *pkeyCtx = NULL; BSL_Buffer encodeAsn1 = {0}; ASSERT_EQ(CRYPT_EAL_DecodeFileKey(BSL_FORMAT_UNKNOWN, CRYPT_PUBKEY_SUBKEY, path, NULL, 0, &pkeyCtx), CRYPT_SUCCESS); ASSERT_EQ(CRYPT_EAL_EncodeBuffKey(pkeyCtx, NULL, BSL_FORMAT_ASN1, CRYPT_PUBKEY_SUBKEY, &encodeAsn1), CRYPT_SUCCESS); ASSERT_COMPARE("asn1 compare.", encodeAsn1.data, encodeAsn1.dataLen, asn1->x, asn1->len); EXIT: CRYPT_EAL_PkeyFreeCtx(pkeyCtx); BSL_SAL_FREE(encodeAsn1.data); BSL_GLOBAL_DeInit(); } /* END_CASE */ /* BEGIN_CASE */ void SDV_BSL_ASN1_PARSE_ECCPRIKEY_FAIL_TC001(Hex *asn1) { RegisterLogFunc(); CRYPT_EAL_PkeyCtx *pkeyCtx = NULL; uint8_t *buff = (uint8_t *)BSL_SAL_Calloc(asn1->len + 1, 1); ASSERT_TRUE(buff != NULL); (void)memcpy_s(buff, asn1->len, asn1->x, asn1->len); BSL_Buffer encode = {buff, asn1->len}; ASSERT_EQ(CRYPT_EAL_DecodeBuffKey(BSL_FORMAT_UNKNOWN, CRYPT_PRIKEY_ECC, &encode, NULL, 0, &pkeyCtx), CRYPT_DECODE_ASN1_BUFF_FAILED); EXIT: BSL_SAL_FREE(buff); BSL_GLOBAL_DeInit(); } /* END_CASE */ /* BEGIN_CASE */ void SDV_BSL_ASN1_PARSE_BUFF_PROVIDER_TC001(char *formatStr, char *typeStr, char *path, Hex *password) { #ifndef HITLS_CRYPTO_PROVIDER (void)formatStr; (void)typeStr; (void)path; (void)password; SKIP_TEST(); #else RegisterLogFunc(); CRYPT_RandRegist(RandFunc); CRYPT_RandRegistEx(RandFuncEx); uint8_t *data = NULL; uint32_t dataLen = 0; ASSERT_EQ(BSL_SAL_ReadFile(path, &data, &dataLen), BSL_SUCCESS); BSL_Buffer encode = {data, dataLen}; BSL_Buffer pass = {password->x, password->len}; CRYPT_EAL_PkeyCtx *pkeyCtx = NULL; ASSERT_EQ(CRYPT_EAL_ProviderDecodeBuffKey(NULL, NULL, BSL_CID_UNKNOWN, NULL, NULL, &encode, &pass, &pkeyCtx), CRYPT_SUCCESS); CRYPT_EAL_PkeyFreeCtx(pkeyCtx); pkeyCtx = NULL; encode.data = data; encode.dataLen = dataLen; ASSERT_EQ(CRYPT_EAL_ProviderDecodeBuffKey(NULL, NULL, BSL_CID_UNKNOWN, formatStr, typeStr, &encode, &pass, &pkeyCtx), 0); CRYPT_EAL_PkeyFreeCtx(pkeyCtx); pkeyCtx = NULL; #ifdef HITLS_CRYPTO_PROVIDER /* default provider not loading */ CRYPT_EAL_Cleanup(9); // 9 denotes to deinit CRYPT_EAL_INIT_CPU and CRYPT_EAL_INIT_PROVIDER encode.data = data; encode.dataLen = dataLen; ASSERT_EQ(CRYPT_EAL_ProviderDecodeBuffKey(NULL, NULL, BSL_CID_UNKNOWN, NULL, NULL, &encode, &pass, &pkeyCtx), CRYPT_PROVIDER_INVALID_LIB_CTX); encode.data = data; encode.dataLen = dataLen; ASSERT_NE(CRYPT_EAL_ProviderDecodeBuffKey(NULL, NULL, BSL_CID_UNKNOWN, formatStr, typeStr, &encode, &pass, &pkeyCtx), 0); CRYPT_EAL_Init(9); // 9 denotes to deinit CRYPT_EAL_INIT_CPU and CRYPT_EAL_INIT_PROVIDER encode.data = data; encode.dataLen = dataLen; ASSERT_EQ(CRYPT_EAL_ProviderDecodeBuffKey(NULL, NULL, BSL_CID_UNKNOWN, formatStr, typeStr, &encode, &pass, &pkeyCtx), CRYPT_SUCCESS); #endif EXIT: CRYPT_EAL_PkeyFreeCtx(pkeyCtx); BSL_SAL_FREE(data); BSL_GLOBAL_DeInit(); #endif } /* END_CASE */ /** * @test SDV_BSL_ASN1_PARSE_BUFF_PROVIDER_TC002 * title 1. Test the decode provider and key provider are not same * 2. Test the JSON2Key * */ /* BEGIN_CASE */ void SDV_BSL_ASN1_PARSE_BUFF_PROVIDER_TC002(char *providerPath, char *providerName, int cmd, char *attrName, char *formatStr, char *typeStr, char *path) { #ifndef HITLS_CRYPTO_PROVIDER (void)providerPath; (void)providerName; (void)cmd; (void)attrName; (void)formatStr; (void)typeStr; (void)path; SKIP_TEST(); #else RegisterLogFunc(); CRYPT_RandRegist(RandFunc); CRYPT_RandRegistEx(RandFuncEx); CRYPT_EAL_PkeyCtx *pkeyCtx = NULL; CRYPT_EAL_LibCtx *libCtx = CRYPT_EAL_LibCtxNew(); ASSERT_TRUE(libCtx != NULL); ASSERT_EQ(CRYPT_EAL_ProviderSetLoadPath(libCtx, providerPath), CRYPT_SUCCESS); ASSERT_EQ(CRYPT_EAL_ProviderLoad(libCtx, BSL_SAL_LIB_FMT_OFF, "default", NULL, NULL), CRYPT_SUCCESS); ASSERT_EQ(CRYPT_EAL_ProviderLoad(libCtx, cmd, providerName, NULL, NULL), CRYPT_SUCCESS); ASSERT_EQ(CRYPT_EAL_ProviderDecodeFileKey(libCtx, attrName, BSL_CID_UNKNOWN, formatStr, typeStr, path, NULL, &pkeyCtx), CRYPT_SUCCESS); EXIT: CRYPT_EAL_PkeyFreeCtx(pkeyCtx); CRYPT_EAL_LibCtxFree(libCtx); BSL_GLOBAL_DeInit(); #endif } /* END_CASE */
2301_79861745/bench_create
testcode/sdv/testcase/crypto/encode/test_suite_sdv_asn1_certkey.c
C
unknown
31,665
/* * This file is part of the openHiTLS project. * * openHiTLS is licensed under the Mulan PSL v2. * You can use this software according to the terms and conditions of the Mulan PSL v2. * You may obtain a copy of Mulan PSL v2 at: * * http://license.coscl.org.cn/MulanPSL2 * * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, * EITHER EXPRESS 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_encode_decode_key.h" #include "crypt_encode_internal.h" #include "crypt_sm2.h" #include "crypt_bn.h" #include "crypt_errno.h" #define MAX_ENCODE_LEN 1024 #define SM2_POINT_COORDINATE_LEN 65 #define SM2_POINT_SINGLE_COORDINATE_LEN 32 #define SM3_MD_SIZE 32 #define MAX_BN_BITS 2048 #define BITS_IN_A_BYTE 8 /* END_HEADER */ /** * @test SDV_ENCODE_SIGN_BN_FUNC_TC001 * @title Test CRYPT_EAL_EncodeSign normal encode function */ /* BEGIN_CASE */ void SDV_ENCODE_SIGN_BN_FUNC_TC001(Hex *r, Hex *s, Hex *expect) { uint8_t encode[MAX_ENCODE_LEN] = {0}; uint32_t encodeLen = sizeof(encode); BN_BigNum *bnR = NULL; BN_BigNum *bnS = NULL; ASSERT_TRUE((bnR = BN_Create(MAX_BN_BITS)) != NULL); ASSERT_TRUE((bnS = BN_Create(MAX_BN_BITS)) != NULL); ASSERT_TRUE(r->len * BITS_IN_A_BYTE <= MAX_BN_BITS); ASSERT_TRUE(s->len * BITS_IN_A_BYTE <= MAX_BN_BITS); ASSERT_EQ(BN_Bin2Bn(bnR, r->x, r->len), CRYPT_SUCCESS); ASSERT_EQ(BN_SetSign(bnR, false), CRYPT_SUCCESS); ASSERT_EQ(BN_Bin2Bn(bnS, s->x, s->len), CRYPT_SUCCESS); ASSERT_EQ(BN_SetSign(bnS, false), CRYPT_SUCCESS); ASSERT_EQ(CRYPT_EAL_EncodeSign(bnR, bnS, encode, &encodeLen), CRYPT_SUCCESS); ASSERT_EQ(encodeLen, expect->len); ASSERT_TRUE(memcmp(encode, expect->x, expect->len) == 0); EXIT: BN_Destroy(bnR); BN_Destroy(bnS); } /* END_CASE */ /** * @test SDV_ENCODE_SIGN_BN_API_TC001 * @title Test CRYPT_EAL_EncodeSign abnormal input parameter */ /* BEGIN_CASE */ void SDV_ENCODE_SIGN_BN_API_TC001(Hex *r, Hex *s) { uint8_t encode[MAX_ENCODE_LEN] = {0}; uint32_t encodeLen = sizeof(encode); BN_BigNum *bnR = NULL; BN_BigNum *bnS = NULL; ASSERT_TRUE((bnR = BN_Create(MAX_BN_BITS)) != NULL); ASSERT_TRUE((bnS = BN_Create(MAX_BN_BITS)) != NULL); // Test big number is zero ASSERT_EQ(CRYPT_EAL_EncodeSign(bnR, bnS, encode, &encodeLen), CRYPT_INVALID_ARG); ASSERT_TRUE(BN_Bin2Bn(bnR, r->x, r->len) == CRYPT_SUCCESS); ASSERT_EQ(CRYPT_EAL_EncodeSign(bnR, bnS, encode, &encodeLen), CRYPT_INVALID_ARG); ASSERT_TRUE(BN_Bin2Bn(bnS, s->x, s->len) == CRYPT_SUCCESS); // Test null pointer ASSERT_EQ(CRYPT_EAL_EncodeSign(NULL, bnS, encode, &encodeLen), CRYPT_NULL_INPUT); ASSERT_EQ(CRYPT_EAL_EncodeSign(bnR, NULL, encode, &encodeLen), CRYPT_NULL_INPUT); ASSERT_EQ(CRYPT_EAL_EncodeSign(bnR, bnS, NULL, &encodeLen), CRYPT_NULL_INPUT); ASSERT_EQ(CRYPT_EAL_EncodeSign(bnR, bnS, encode, NULL), CRYPT_NULL_INPUT); // Test big number is negative ASSERT_EQ(BN_SetSign(bnR, true), CRYPT_SUCCESS); ASSERT_EQ(CRYPT_EAL_EncodeSign(bnR, bnS, encode, &encodeLen), CRYPT_INVALID_ARG); ASSERT_EQ(BN_SetSign(bnR, false), CRYPT_SUCCESS); ASSERT_EQ(BN_SetSign(bnS, true), CRYPT_SUCCESS); ASSERT_EQ(CRYPT_EAL_EncodeSign(bnR, bnS, encode, &encodeLen), CRYPT_INVALID_ARG); ASSERT_EQ(BN_SetSign(bnS, false), CRYPT_SUCCESS); // Test buffer length is not enough encodeLen = 1; ASSERT_EQ(CRYPT_EAL_EncodeSign(bnR, bnS, encode, &encodeLen), CRYPT_ENCODE_BUFF_NOT_ENOUGH); EXIT: BN_Destroy(bnR); BN_Destroy(bnS); } /* END_CASE */ /** * @test SDV_DECODE_SIGN_BN_FUNC_TC001 * @title Test CRYPT_EAL_DecodeSign normal decode function */ /* BEGIN_CASE */ void SDV_DECODE_SIGN_BN_FUNC_TC001(Hex *encode, Hex *expectR, Hex *expectS, int ret) { BN_BigNum *bnR = NULL; BN_BigNum *bnS = NULL; uint8_t rBuf[MAX_ENCODE_LEN] = {0}; uint8_t sBuf[MAX_ENCODE_LEN] = {0}; uint32_t rLen = sizeof(rBuf); uint32_t sLen = sizeof(sBuf); ASSERT_TRUE((bnR = BN_Create(MAX_BN_BITS)) != NULL); ASSERT_TRUE((bnS = BN_Create(MAX_BN_BITS)) != NULL); ASSERT_EQ(CRYPT_EAL_DecodeSign(encode->x, encode->len, bnR, bnS), ret); if (ret == CRYPT_SUCCESS) { ASSERT_TRUE(!BN_IsNegative(bnR)); ASSERT_TRUE(!BN_IsNegative(bnS)); ASSERT_EQ(BN_Bn2Bin(bnR, rBuf, &rLen), CRYPT_SUCCESS); ASSERT_EQ(BN_Bn2Bin(bnS, sBuf, &sLen), CRYPT_SUCCESS); ASSERT_EQ(rLen, expectR->len); ASSERT_EQ(sLen, expectS->len); ASSERT_TRUE(memcmp(rBuf, expectR->x, rLen) == 0); ASSERT_TRUE(memcmp(sBuf, expectS->x, sLen) == 0); } EXIT: BN_Destroy(bnR); BN_Destroy(bnS); } /* END_CASE */ /** * @test SDV_DECODE_SIGN_BN_API_TC001 * @title Test CRYPT_EAL_DecodeSign abnormal input parameter */ /* BEGIN_CASE */ void SDV_DECODE_SIGN_BN_API_TC001(Hex *encode) { BN_BigNum *bnR = NULL; BN_BigNum *bnS = NULL; ASSERT_TRUE((bnR = BN_Create(MAX_BN_BITS)) != NULL); ASSERT_TRUE((bnS = BN_Create(MAX_BN_BITS)) != NULL); // Test null pointer ASSERT_EQ(CRYPT_EAL_DecodeSign(NULL, encode->len, bnR, bnS), CRYPT_NULL_INPUT); ASSERT_EQ(CRYPT_EAL_DecodeSign(encode->x, 0, bnR, bnS), CRYPT_NULL_INPUT); ASSERT_EQ(CRYPT_EAL_DecodeSign(encode->x, encode->len, NULL, bnS), CRYPT_NULL_INPUT); ASSERT_EQ(CRYPT_EAL_DecodeSign(encode->x, encode->len, bnR, NULL), CRYPT_NULL_INPUT); EXIT: BN_Destroy(bnR); BN_Destroy(bnS); } /* END_CASE */ /** * @test SDV_ENCODE_SM2_ENCRYPT_DATA_FUNC_TC001 * @title Test CRYPT_EAL_EncodeSm2EncryptData normal encode function */ /* BEGIN_CASE */ void SDV_ENCODE_SM2_ENCRYPT_DATA_FUNC_TC001(Hex *x, Hex *y, Hex *hash, Hex *cipher, Hex *expect, int ret) { uint8_t encode[MAX_ENCODE_LEN] = {0}; uint32_t encodeLen = sizeof(encode); CRYPT_SM2_EncryptData data = { .x = x->x, .xLen = x->len, .y = y->x, .yLen = y->len, .hash = hash->x, .hashLen = hash->len, .cipher = cipher->x, .cipherLen = cipher->len }; ASSERT_EQ(CRYPT_EAL_EncodeSm2EncryptData(&data, encode, &encodeLen), ret); if (ret == CRYPT_SUCCESS) { ASSERT_EQ(encodeLen, expect->len); ASSERT_TRUE(memcmp(encode, expect->x, expect->len) == 0); } EXIT: return; } /* END_CASE */ /** * @test SDV_ENCODE_SM2_ENCRYPT_DATA_API_TC001 * @title Test CRYPT_EAL_EncodeSm2EncryptData abnormal input parameter */ /* BEGIN_CASE */ void SDV_ENCODE_SM2_ENCRYPT_DATA_API_TC001(Hex *x, Hex *y, Hex *hash, Hex *cipher) { uint8_t encode[MAX_ENCODE_LEN] = {0}; uint32_t encodeLen = sizeof(encode); CRYPT_SM2_EncryptData data = { .x = x->x, .xLen = x->len, .y = y->x, .yLen = y->len, .hash = hash->x, .hashLen = hash->len, .cipher = cipher->x, .cipherLen = cipher->len }; // Test null pointer ASSERT_EQ(CRYPT_EAL_EncodeSm2EncryptData(NULL, encode, &encodeLen), CRYPT_NULL_INPUT); ASSERT_EQ(CRYPT_EAL_EncodeSm2EncryptData(&data, NULL, &encodeLen), CRYPT_NULL_INPUT); ASSERT_EQ(CRYPT_EAL_EncodeSm2EncryptData(&data, encode, NULL), CRYPT_NULL_INPUT); // Test invalid x data.x = NULL; ASSERT_EQ(CRYPT_EAL_EncodeSm2EncryptData(&data, encode, &encodeLen), CRYPT_INVALID_ARG); data.x = x->x; data.xLen = 0; ASSERT_EQ(CRYPT_EAL_EncodeSm2EncryptData(&data, encode, &encodeLen), CRYPT_INVALID_ARG); data.xLen = x->len; // Test invalid y data.y = NULL; ASSERT_EQ(CRYPT_EAL_EncodeSm2EncryptData(&data, encode, &encodeLen), CRYPT_INVALID_ARG); data.y = y->x; data.yLen = 0; ASSERT_EQ(CRYPT_EAL_EncodeSm2EncryptData(&data, encode, &encodeLen), CRYPT_INVALID_ARG); data.yLen = y->len; // Test invalid hash data.hash = NULL; ASSERT_EQ(CRYPT_EAL_EncodeSm2EncryptData(&data, encode, &encodeLen), CRYPT_INVALID_ARG); data.hash = hash->x; data.hashLen = 0; ASSERT_EQ(CRYPT_EAL_EncodeSm2EncryptData(&data, encode, &encodeLen), CRYPT_INVALID_ARG); data.hashLen = hash->len; // Test invalid cipher data.cipher = NULL; ASSERT_EQ(CRYPT_EAL_EncodeSm2EncryptData(&data, encode, &encodeLen), CRYPT_INVALID_ARG); data.cipher = cipher->x; data.cipherLen = 0; ASSERT_EQ(CRYPT_EAL_EncodeSm2EncryptData(&data, encode, &encodeLen), CRYPT_INVALID_ARG); data.cipherLen = cipher->len; // Test buffer length is not enough data.xLen = x->len; encodeLen = 1; ASSERT_EQ(CRYPT_EAL_EncodeSm2EncryptData(&data, encode, &encodeLen), CRYPT_ENCODE_BUFF_NOT_ENOUGH); EXIT: return; } /* END_CASE */ /** * @test SDV_DECODE_SM2_ENCRYPT_DATA_FUNC_TC001 * @title Test CRYPT_EAL_DecodeSm2EncryptData normal decode function */ /* BEGIN_CASE */ void SDV_DECODE_SM2_ENCRYPT_DATA_FUNC_TC001(Hex *encode, Hex *expectX, Hex *expectY, Hex *expectHash, Hex *expectCipher, int ret) { uint8_t decode[MAX_ENCODE_LEN] = {0}; CRYPT_SM2_EncryptData data = { .x = decode, .xLen = SM2_POINT_SINGLE_COORDINATE_LEN, .y = decode + SM2_POINT_SINGLE_COORDINATE_LEN, .yLen = SM2_POINT_SINGLE_COORDINATE_LEN, .hash = decode + SM2_POINT_COORDINATE_LEN, .hashLen = SM3_MD_SIZE, .cipher = decode + SM2_POINT_COORDINATE_LEN + SM3_MD_SIZE, .cipherLen = sizeof(decode) - SM2_POINT_COORDINATE_LEN - SM3_MD_SIZE }; ASSERT_EQ(CRYPT_EAL_DecodeSm2EncryptData(encode->x, encode->len, &data), ret); if (ret == CRYPT_SUCCESS) { ASSERT_EQ(data.hashLen, expectHash->len); ASSERT_EQ(data.cipherLen, expectCipher->len); ASSERT_TRUE(memcmp(data.x + (data.xLen - expectX->len), expectX->x, expectX->len) == 0); ASSERT_TRUE(memcmp(data.y + (data.yLen - expectY->len), expectY->x, expectY->len) == 0); ASSERT_TRUE(memcmp(data.hash, expectHash->x, data.hashLen) == 0); ASSERT_TRUE(memcmp(data.cipher, expectCipher->x, data.cipherLen) == 0); } EXIT: return; } /* END_CASE */ /** * @test SDV_DECODE_SM2_ENCRYPT_DATA_API_TC001 * @title Test CRYPT_EAL_DecodeSm2EncryptData abnormal input parameter */ /* BEGIN_CASE */ void SDV_DECODE_SM2_ENCRYPT_DATA_API_TC001(Hex *encode) { uint8_t x; uint8_t y; uint8_t hash; uint8_t cipher; CRYPT_SM2_EncryptData data = { .x = &x, .xLen = 1, .y = &y, .yLen = 1, .hash = &hash, .hashLen = 1, .cipher = &cipher, .cipherLen = 1 }; // Test null pointer ASSERT_EQ(CRYPT_EAL_DecodeSm2EncryptData(NULL, encode->len, &data), CRYPT_NULL_INPUT); ASSERT_EQ(CRYPT_EAL_DecodeSm2EncryptData(encode->x, encode->len, NULL), CRYPT_NULL_INPUT); // Test invlaid data data.x = NULL; ASSERT_EQ(CRYPT_EAL_DecodeSm2EncryptData(encode->x, encode->len, &data), CRYPT_INVALID_ARG); data.x = &x; data.xLen = 0; ASSERT_EQ(CRYPT_EAL_DecodeSm2EncryptData(encode->x, encode->len, &data), CRYPT_INVALID_ARG); data.xLen = 1; // Test buffer length is not enough ASSERT_EQ(CRYPT_EAL_DecodeSm2EncryptData(encode->x, encode->len, &data), CRYPT_DECODE_BUFF_NOT_ENOUGH); EXIT: return; } /* END_CASE */ /** * @test SDV_ENCODE_GET_SIGN_LEN_API_TC001 * @title Test CRYPT_EAL_GetSignEncodeLen */ /* BEGIN_CASE */ void SDV_ENCODE_GET_SIGN_LEN_API_TC001(void) { uint32_t maxLen = 0; // Normal case test ASSERT_EQ(CRYPT_SUCCESS, CRYPT_EAL_GetSignEncodeLen(32, 32, &maxLen)); ASSERT_EQ(72, maxLen); // (32 + 1(leading 0x00) + 1(len) + 1(tag)) * 2(r,s) + 1(tag) + 1(len) = 72 // Invalid parameter test ASSERT_EQ(CRYPT_EAL_GetSignEncodeLen(0, 32, &maxLen), CRYPT_INVALID_ARG); ASSERT_EQ(CRYPT_EAL_GetSignEncodeLen(32, 0, &maxLen), CRYPT_INVALID_ARG); ASSERT_EQ(CRYPT_EAL_GetSignEncodeLen(32, 32, NULL), CRYPT_INVALID_ARG); // Overflow test ASSERT_EQ(CRYPT_EAL_GetSignEncodeLen(UINT32_MAX, 32, &maxLen), CRYPT_INVALID_ARG); ASSERT_EQ(CRYPT_EAL_GetSignEncodeLen(32, UINT32_MAX, &maxLen), CRYPT_INVALID_ARG); ASSERT_EQ(CRYPT_EAL_GetSignEncodeLen(UINT32_MAX - 1, 32, &maxLen), BSL_ASN1_ERR_LEN_OVERFLOW); ASSERT_EQ(CRYPT_EAL_GetSignEncodeLen(32, UINT32_MAX - 1, &maxLen), BSL_ASN1_ERR_LEN_OVERFLOW); // 1(tag) + 1(len) + 1(integer) // Indefinite form: 1(tag) + 1 + 1(lenNum) + 1(len) ASSERT_EQ(CRYPT_EAL_GetSignEncodeLen(1, UINT32_MAX - (1 + 1 + 1) - (1 + 1 + 4), &maxLen), CRYPT_ENCODE_ERR_SIGN_LEN_OVERFLOW); EXIT: return; } /* END_CASE */ /** * @test SDV_ENCODE_GET_SM2_ENC_LEN_API_TC001 * @title Test CRYPT_EAL_GetSm2EncryptDataEncodeLen */ /* BEGIN_CASE */ void SDV_ENCODE_GET_SM2_ENC_LEN_API_TC001(void) { uint32_t encodeLen = 0; // Normal case test ASSERT_EQ(CRYPT_EAL_GetSm2EncryptDataEncodeLen(32, 32, 32, 64, &encodeLen), CRYPT_SUCCESS); ASSERT_EQ(encodeLen, 173); // (32 + 1 + 1 + 1) * 2 + (32+1+1) + (64+1+1) + 2(length > 127) + 1 = 173 // Minimum valid input test ASSERT_EQ(CRYPT_EAL_GetSm2EncryptDataEncodeLen(1, 1, 1, 1, &encodeLen), CRYPT_SUCCESS); ASSERT_EQ(encodeLen, 16); // (1 + 1 + 1 + 1) * 2 + (1+1+1) + (1+1+1) + 1 + 1 = 16 // Invalid parameter test ASSERT_EQ(CRYPT_INVALID_ARG, CRYPT_EAL_GetSm2EncryptDataEncodeLen(32, 32, 32, 32, NULL)); // Overflow test ASSERT_EQ(CRYPT_EAL_GetSm2EncryptDataEncodeLen(UINT32_MAX - 1, UINT32_MAX - 1, 32, 32, &encodeLen), BSL_ASN1_ERR_LEN_OVERFLOW); ASSERT_EQ(CRYPT_EAL_GetSm2EncryptDataEncodeLen(1000, 1000, UINT32_MAX - 2000, 32, &encodeLen), CRYPT_ENCODE_ERR_SM2_ENCRYPT_DATA_LEN_OVERFLOW); ASSERT_EQ(CRYPT_EAL_GetSm2EncryptDataEncodeLen(1000, 1000, 1000, UINT32_MAX - 3000, &encodeLen), CRYPT_ENCODE_ERR_SM2_ENCRYPT_DATA_LEN_OVERFLOW); EXIT: return; } /* END_CASE */ /** * @test SDV_ENCODE_DECODE_SIGN_COMBO_TC001 * @title Test combined encode and decode for signature */ /* BEGIN_CASE */ void SDV_ENCODE_DECODE_SIGN_COMBO_TC001(Hex *r, Hex *s) { uint32_t maxLen = 0; uint8_t *encode = NULL; BN_BigNum *bnR = NULL; BN_BigNum *bnS = NULL; BN_BigNum *decR = NULL; BN_BigNum *decS = NULL; uint8_t rBuf[MAX_ENCODE_LEN] = {0}; uint8_t sBuf[MAX_ENCODE_LEN] = {0}; uint32_t rLen = sizeof(rBuf); uint32_t sLen = sizeof(sBuf); // Create big numbers ASSERT_TRUE((bnR = BN_Create(MAX_BN_BITS)) != NULL); ASSERT_TRUE((bnS = BN_Create(MAX_BN_BITS)) != NULL); ASSERT_TRUE((decR = BN_Create(MAX_BN_BITS)) != NULL); ASSERT_TRUE((decS = BN_Create(MAX_BN_BITS)) != NULL); // Convert input hex to big numbers ASSERT_TRUE(r->len * BITS_IN_A_BYTE <= MAX_BN_BITS); ASSERT_TRUE(s->len * BITS_IN_A_BYTE <= MAX_BN_BITS); ASSERT_EQ(BN_Bin2Bn(bnR, r->x, r->len), CRYPT_SUCCESS); ASSERT_EQ(BN_SetSign(bnR, false), CRYPT_SUCCESS); ASSERT_EQ(BN_Bin2Bn(bnS, s->x, s->len), CRYPT_SUCCESS); ASSERT_EQ(BN_SetSign(bnS, false), CRYPT_SUCCESS); // Get encode length and allocate buffer ASSERT_EQ(CRYPT_EAL_GetSignEncodeLen(r->len, s->len, &maxLen), CRYPT_SUCCESS); ASSERT_TRUE((encode = (uint8_t *)BSL_SAL_Malloc(maxLen)) != NULL); // Encode signature uint32_t encodeLen = maxLen; ASSERT_EQ(CRYPT_EAL_EncodeSign(bnR, bnS, encode, &encodeLen), CRYPT_SUCCESS); // Decode signature ASSERT_EQ(CRYPT_EAL_DecodeSign(encode, encodeLen, decR, decS), CRYPT_SUCCESS); // Convert decoded big numbers back to binary and compare ASSERT_EQ(BN_Bn2Bin(decR, rBuf, &rLen), CRYPT_SUCCESS); ASSERT_EQ(BN_Bn2Bin(decS, sBuf, &sLen), CRYPT_SUCCESS); ASSERT_COMPARE("Compare r", rBuf, rLen, r->x, r->len); ASSERT_COMPARE("Compare s", sBuf, sLen, s->x, s->len); EXIT: BSL_SAL_Free(encode); BN_Destroy(bnR); BN_Destroy(bnS); BN_Destroy(decR); BN_Destroy(decS); } /* END_CASE */ /** * @test SDV_ENCODE_DECODE_SM2_ENCRYPT_COMBO_TC001 * @title Test combined encode and decode for SM2 encryption data */ /* BEGIN_CASE */ void SDV_ENCODE_DECODE_SM2_ENCRYPT_COMBO_TC001(Hex *x, Hex *y, Hex *hash, Hex *cipher) { uint32_t maxLen = 0; uint8_t *encode = NULL; uint8_t decBuf[MAX_ENCODE_LEN] = {0}; // Original data CRYPT_SM2_EncryptData data = { .x = x->x, .xLen = x->len, .y = y->x, .yLen = y->len, .hash = hash->x, .hashLen = hash->len, .cipher = cipher->x, .cipherLen = cipher->len }; // Prepare decode buffer decBuf[0] = 0x04; CRYPT_SM2_EncryptData decData = { .x = decBuf + 1, .xLen = SM2_POINT_SINGLE_COORDINATE_LEN, .y = decBuf + 1 + SM2_POINT_SINGLE_COORDINATE_LEN, .yLen = SM2_POINT_SINGLE_COORDINATE_LEN, .hash = decBuf + SM2_POINT_COORDINATE_LEN, .hashLen = SM3_MD_SIZE, .cipher = decBuf + SM2_POINT_COORDINATE_LEN + hash->len, .cipherLen = sizeof(decBuf) - SM3_MD_SIZE - SM2_POINT_COORDINATE_LEN }; // Get encode length and allocate buffer ASSERT_EQ(CRYPT_EAL_GetSm2EncryptDataEncodeLen(x->len, y->len, hash->len, cipher->len, &maxLen), CRYPT_SUCCESS); ASSERT_TRUE((encode = (uint8_t *)BSL_SAL_Malloc(maxLen)) != NULL); // Encode SM2 encryption data uint32_t encodeLen = maxLen; ASSERT_EQ(CRYPT_EAL_EncodeSm2EncryptData(&data, encode, &encodeLen), CRYPT_SUCCESS); // Decode SM2 encryption data ASSERT_EQ(CRYPT_EAL_DecodeSm2EncryptData(encode, encodeLen, &decData), CRYPT_SUCCESS); // Compare decoded data with original data ASSERT_COMPARE("Compare x", decData.x + (decData.xLen - x->len), x->len, x->x, x->len); ASSERT_COMPARE("Compare y", decData.y + (decData.yLen - y->len), y->len, y->x, y->len); ASSERT_COMPARE("Compare hash", decData.hash, decData.hashLen, hash->x, hash->len); ASSERT_COMPARE("Compare cipher", decData.cipher, decData.cipherLen, cipher->x, cipher->len); EXIT: BSL_SAL_Free(encode); } /* END_CASE */
2301_79861745/bench_create
testcode/sdv/testcase/crypto/encode/test_suite_sdv_encode.c
C
unknown
18,110
/* * This file is part of the openHiTLS project. * * openHiTLS is licensed under the Mulan PSL v2. * You can use this software according to the terms and conditions of the Mulan PSL v2. * You may obtain a copy of Mulan PSL v2 at: * * http://license.coscl.org.cn/MulanPSL2 * * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, * EITHER EXPRESS 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 <stdio.h> #include <string.h> #include <unistd.h> #include <pthread.h> #include "bsl_sal.h" #include "crypt_errno.h" #include "crypt_entropy.h" #include "crypt_eal_rand.h" #include "eal_entropy.h" #include "securec.h" #include "crypt_eal_entropy.h" #include "crypt_algid.h" #ifdef HITLS_CRYPTO_ENTROPY_SYS static bool IsCollectionEntropy(void *ctx) { bool isWork = false; ASSERT_TRUE(CRYPT_EAL_EsCtrl(ctx, CRYPT_ENTROPY_GET_STATE, &isWork, 1) == CRYPT_SUCCESS); uint32_t poolSize = 0; uint32_t currSize = 0; uint32_t cfSize = 0; ASSERT_TRUE(CRYPT_EAL_EsCtrl(ctx, CRYPT_ENTROPY_GET_POOL_SIZE, &poolSize, 4) == CRYPT_SUCCESS); ASSERT_TRUE(CRYPT_EAL_EsCtrl(ctx, CRYPT_ENTROPY_POOL_GET_CURRSIZE, &currSize, 4) == CRYPT_SUCCESS); ASSERT_TRUE(CRYPT_EAL_EsCtrl(ctx, CRYPT_ENTROPY_GET_CF_SIZE, &cfSize, 4) == CRYPT_SUCCESS); return isWork && (cfSize <= poolSize - currSize); EXIT: return false; } static void *EsGatherAuto(void *ctx) { while(true) { if (!IsCollectionEntropy(ctx)) { break; } ASSERT_TRUE(CRYPT_EAL_EsCtrl(ctx, CRYPT_ENTROPY_GATHER_ENTROPY, NULL, 0) == CRYPT_SUCCESS); uint32_t size; ASSERT_TRUE(CRYPT_EAL_EsCtrl(ctx, CRYPT_ENTROPY_POOL_GET_CURRSIZE, (void *)&size, sizeof(uint32_t)) == CRYPT_SUCCESS); usleep(1000); } EXIT: return NULL; } static void *EsGetAuto(void *ctx) { uint8_t buf[48] = {0}; for (int32_t iter = 0; iter < 3; iter++) { uint32_t len = CRYPT_EAL_EsEntropyGet(ctx, buf, 48); ASSERT_TRUE(len > 0); } EXIT: return NULL; } static const char *EsGetCfMode(uint32_t algId) { switch (algId) { case CRYPT_MD_SM3: return "sm3_df"; case CRYPT_MD_SHA224: return "sha224_df"; case CRYPT_MD_SHA256: return "sha256_df"; case CRYPT_MD_SHA384: return "sha384_df"; case CRYPT_MD_SHA512: return "sha512_df"; default: return NULL; } } static uint32_t EsGetCfLen(uint32_t algId) { switch (algId) { case CRYPT_MD_SM3: return 32u; case CRYPT_MD_SHA224: return 28u; case CRYPT_MD_SHA256: return 32u; case CRYPT_MD_SHA384: return 48u; case CRYPT_MD_SHA512: return 64u; default: return 0u; } } static int32_t EntropyReadNormal(void *ctx, uint32_t timeout, uint8_t *buf, uint32_t bufLen) { (void)ctx; (void)timeout; memset_s(buf, bufLen, 0xff, bufLen); return CRYPT_SUCCESS; } static void *EntropyInitTest(void *para) { (void)para; return EntropyInitTest; } static void *EntropyInitError(void *para) { (void)para; return NULL; } static int32_t EntropyReadError(void *ctx, uint32_t timeout, uint8_t *buf, uint32_t bufLen) { (void)ctx; (void)timeout; memset_s(buf, bufLen, 0xff, bufLen); return -1; } static int32_t EntropyReadDiffData(void *ctx, uint32_t timeout, uint8_t *buf, uint32_t bufLen) { (void)ctx; (void)timeout; for (uint32_t iter = 0; iter < bufLen; iter++) { buf[iter] = iter % 128; } return CRYPT_SUCCESS; } static void EntropyDeinitTest(void *ctx) { (void)ctx; return; } static void *EsMutiAuto(void *ctx) { CRYPT_EAL_NsPara para = { "aaa", false, 7, { NULL, NULL, EntropyReadNormal, NULL, }, {5, 39, 512}, }; CRYPT_EAL_EsCtrl(ctx, CRYPT_ENTROPY_SET_CF, (void *)(intptr_t)"sha256_df", strlen("sha256_df")); CRYPT_EAL_EsCtrl(ctx, CRYPT_ENTROPY_ADD_NS, (void *)&para, sizeof(CRYPT_EAL_NsPara)); uint32_t size = 512; CRYPT_EAL_EsCtrl(ctx, CRYPT_ENTROPY_SET_POOL_SIZE, (void *)&size, sizeof(uint32_t)); ASSERT_TRUE(CRYPT_EAL_EsInit(ctx) == CRYPT_SUCCESS); uint8_t buf[48] = {0}; for (int32_t iter = 0; iter < 3; iter++) { uint32_t len = CRYPT_EAL_EsEntropyGet(ctx, buf, 48); ASSERT_TRUE(len > 0); } EXIT: return NULL; } static void EntropyESMutilTest(void *alg) { uint32_t poolSize = 4096; uint32_t expectGetLen = 32; uint8_t buf[1024] = {0}; uint32_t currPoolSize = 0; CRYPT_EAL_Es *es = CRYPT_EAL_EsNew(); ASSERT_TRUE(es != NULL); const char *mode = EsGetCfMode((uint32_t)(*(int *)alg)); ASSERT_TRUE(CRYPT_EAL_EsCtrl(es, CRYPT_ENTROPY_SET_CF, (void *)(intptr_t)mode, strlen(mode)) == CRYPT_SUCCESS); ASSERT_TRUE(CRYPT_EAL_EsCtrl(es, CRYPT_ENTROPY_SET_POOL_SIZE, (void *)&poolSize, sizeof(uint32_t)) == CRYPT_SUCCESS); ASSERT_TRUE(CRYPT_EAL_EsInit(es) == CRYPT_SUCCESS); for(int iter = 0; iter < 1; iter++) { ASSERT_TRUE(CRYPT_EAL_EsCtrl(es, CRYPT_ENTROPY_GATHER_ENTROPY, NULL, 0) == CRYPT_SUCCESS); } ASSERT_TRUE(CRYPT_EAL_EsCtrl(es, CRYPT_ENTROPY_POOL_GET_CURRSIZE, &currPoolSize, sizeof(uint32_t)) == CRYPT_SUCCESS); ASSERT_TRUE(currPoolSize > expectGetLen); uint32_t resLen = CRYPT_EAL_EsEntropyGet(es, buf, expectGetLen); ASSERT_TRUE(resLen == expectGetLen); EXIT: CRYPT_EAL_EsFree(es); } static int32_t GetEntropyTest(void *seedCtx, CRYPT_Data *entropy, uint32_t strength, CRYPT_Range *lenRange) { (void)strength; entropy->len = lenRange->min; entropy->data = malloc(entropy->len); ASSERT_TRUE(CRYPT_EAL_EsEntropyGet(seedCtx, entropy->data, entropy->len) == entropy->len); EXIT: return CRYPT_SUCCESS; } static void CleanEntropyTest(void *ctx, CRYPT_Data *entropy) { (void)ctx; BSL_SAL_FREE(entropy->data); } static int32_t GetNonceTest(void *ctx, CRYPT_Data *nonce, uint32_t strength, CRYPT_Range *lenRange) { return GetEntropyTest(ctx, nonce, strength, lenRange); } static void CleanNonceTest(void *ctx, CRYPT_Data *nonce) { CleanEntropyTest(ctx, nonce); } #endif static uint32_t EntropyGetNormal(void *ctx, uint8_t *buf, uint32_t bufLen) { (void)ctx; (void)buf; (void)bufLen; memset_s(buf, bufLen, 'a', bufLen); return 32 > bufLen ? bufLen : 32; } static uint32_t EntropyGet0Normal(void *ctx, uint8_t *buf, uint32_t bufLen) { (void)ctx; (void)buf; (void)bufLen; memset_s(buf, bufLen, 'a', bufLen); return 0; } static void *DrbgSeedTest(void *ctx) { CRYPT_RandSeedMethod meth = {0}; ASSERT_TRUE(EAL_SetDefaultEntropyMeth(&meth) == CRYPT_SUCCESS); CRYPT_EAL_RndCtx *randCtx = CRYPT_EAL_DrbgNew(CRYPT_RAND_AES128_CTR_DF, &meth, ctx); ASSERT_TRUE(randCtx != NULL); uint32_t in = 1; ASSERT_TRUE(CRYPT_EAL_DrbgCtrl(randCtx, CRYPT_CTRL_SET_RESEED_INTERVAL, &in, 4) == CRYPT_SUCCESS); ASSERT_TRUE(CRYPT_EAL_DrbgInstantiate(randCtx, NULL, 0) == CRYPT_SUCCESS); for (int32_t index = 0; index < 10; index++) { uint8_t buf[32] = {0}; ASSERT_TRUE(CRYPT_EAL_Drbgbytes(randCtx, buf, 32) == CRYPT_SUCCESS); } EXIT: CRYPT_EAL_DrbgDeinit(randCtx); return NULL; } #ifdef HITLS_CRYPTO_ENTROPY_SYS static uint32_t ErrorGetEsEntropy(CRYPT_EAL_Es *esCtx, uint8_t *data, uint32_t len) { (void)esCtx; (void)data; (void)len; return 0; } #endif static CRYPT_EAL_SeedPoolCtx *GetPoolCtx(uint32_t ent1, uint32_t ent2, bool pes1, bool pes2) { CRYPT_EAL_SeedPoolCtx *pool = CRYPT_EAL_SeedPoolNew(true); CRYPT_EAL_EsPara para1 = {pes2, ent2, NULL, (CRYPT_EAL_EntropyGet)EntropyGetNormal}; CRYPT_EAL_EsPara para2 = {pes1, ent1, NULL, (CRYPT_EAL_EntropyGet)EntropyGetNormal}; ASSERT_TRUE(CRYPT_EAL_SeedPoolAddEs(pool, &para1) == CRYPT_SUCCESS); ASSERT_TRUE(CRYPT_EAL_SeedPoolAddEs(pool, &para2) == CRYPT_SUCCESS); return pool; EXIT: CRYPT_EAL_SeedPoolFree(pool); return NULL; } /* END_HEADER */ /* @ * @test SDV_CRYPTO_ENTROPY_EsNormalTest * @spec - * @title Basic function test of the entropy source. * @precon nan * @prior Level 1 * @auto TRUE @ */ /* BEGIN_CASE */ void SDV_CRYPTO_ENTROPY_EsNormalTest(int alg, int size, int test) { #ifdef HITLS_CRYPTO_ENTROPY_SYS CRYPT_EAL_Es *es = CRYPT_EAL_EsNew(); ASSERT_TRUE(es != NULL); const char *mode = EsGetCfMode((uint32_t)alg); ASSERT_TRUE(CRYPT_EAL_EsCtrl(es, CRYPT_ENTROPY_SET_CF, (void *)(intptr_t)mode, strlen(mode)) == CRYPT_SUCCESS); bool healthTest = (bool)test; ASSERT_TRUE(CRYPT_EAL_EsCtrl(es, CRYPT_ENTROPY_ENABLE_TEST, &healthTest, 1) == CRYPT_SUCCESS); ASSERT_TRUE(CRYPT_EAL_EsCtrl(es, CRYPT_ENTROPY_SET_POOL_SIZE, (void *)&size, sizeof(uint32_t)) == CRYPT_SUCCESS); ASSERT_TRUE(CRYPT_EAL_EsInit(es) == CRYPT_SUCCESS); BSL_SAL_ThreadId thrd; ASSERT_TRUE(BSL_SAL_ThreadCreate(&thrd, EsGatherAuto, es) == 0); BSL_SAL_ThreadId thrdget; ASSERT_TRUE(BSL_SAL_ThreadCreate(&thrdget, EsGetAuto, es) == 0); BSL_SAL_ThreadClose(thrd); BSL_SAL_ThreadClose(thrdget); EXIT: CRYPT_EAL_EsFree(es); return; #else (void)alg; (void)size; (void)test; SKIP_TEST(); #endif } /* END_CASE */ /* @ * @test SDV_CRYPTO_ENTROPY_EsCtrlTest1 * @spec - * @title Testing the entropy source setting interface. * @precon nan * @prior Level 1 * @auto TRUE @ */ /* BEGIN_CASE */ void SDV_CRYPTO_ENTROPY_EsCtrlTest1(int type, int state, int excRes) { #ifdef HITLS_CRYPTO_ENTROPY_SYS CRYPT_EAL_Es *es = CRYPT_EAL_EsNew(); ASSERT_TRUE(es != NULL); uint32_t len = 512; if (state == 1) { ASSERT_TRUE(CRYPT_EAL_EsCtrl(es, CRYPT_ENTROPY_SET_CF, (void *)(intptr_t)"sm3_df", strlen("sm3_df")) == CRYPT_SUCCESS); ASSERT_TRUE(CRYPT_EAL_EsCtrl(es, CRYPT_ENTROPY_SET_POOL_SIZE, (void *)&len, sizeof(uint32_t)) == CRYPT_SUCCESS); ASSERT_TRUE(CRYPT_EAL_EsInit(es) == CRYPT_SUCCESS); } if (excRes == 1) { ASSERT_TRUE(CRYPT_EAL_EsCtrl(es, type, (void *)&len, sizeof(uint32_t)) == CRYPT_SUCCESS); } else { ASSERT_TRUE(CRYPT_EAL_EsCtrl(es, type, (void *)&len, sizeof(uint32_t)) != CRYPT_SUCCESS); } EXIT: CRYPT_EAL_EsFree(es); return; #else (void)type; (void)state; (void)excRes; SKIP_TEST(); #endif } /* END_CASE */ /* @ * @test SDV_CRYPTO_ENTROPY_EsCtrlTest2 * @spec - * @title Testing the entropy source setting interface. * @precon nan * @prior Level 1 * @auto TRUE @ */ /* BEGIN_CASE */ void SDV_CRYPTO_ENTROPY_EsCtrlTest2(void) { #ifdef HITLS_CRYPTO_ENTROPY_SYS CRYPT_EAL_Es *es = CRYPT_EAL_EsNew(); ASSERT_TRUE(es != NULL); ASSERT_TRUE(CRYPT_EAL_EsCtrl(es, CRYPT_ENTROPY_SET_CF, (void *)(intptr_t)"sm3_df", strlen("sm3_df")) == CRYPT_SUCCESS); bool healthTest = true; ASSERT_TRUE(CRYPT_EAL_EsCtrl(es, CRYPT_ENTROPY_ENABLE_TEST, &healthTest, 1) == CRYPT_SUCCESS); CRYPT_EAL_NsPara para = { "aaa", false, 7, { NULL, NULL, EntropyReadNormal, NULL, }, {5, 39, 512}, }; ASSERT_TRUE(CRYPT_EAL_EsCtrl(es, CRYPT_ENTROPY_ADD_NS, (void *)&para, sizeof(CRYPT_EAL_NsPara)) == CRYPT_SUCCESS); ASSERT_TRUE(CRYPT_EAL_EsCtrl(es, CRYPT_ENTROPY_REMOVE_NS, (void *)(intptr_t)para.name, strlen(para.name)) == CRYPT_SUCCESS); bool flag = false; ASSERT_TRUE(CRYPT_EAL_EsCtrl(es, CRYPT_ENTROPY_GET_STATE, &flag, 1) == CRYPT_SUCCESS); ASSERT_TRUE(flag == false); ASSERT_TRUE(CRYPT_EAL_EsInit(es) == CRYPT_SUCCESS); ASSERT_TRUE(CRYPT_EAL_EsCtrl(es, CRYPT_ENTROPY_GET_STATE, &flag, 1) == CRYPT_SUCCESS); ASSERT_TRUE(flag == true); ASSERT_TRUE(CRYPT_EAL_EsCtrl(es, CRYPT_ENTROPY_SET_CF, (void *)(intptr_t)"sm3_df", strlen("sm3_df")) != CRYPT_SUCCESS); ASSERT_TRUE(CRYPT_EAL_EsCtrl(es, CRYPT_ENTROPY_ENABLE_TEST, &healthTest, 1) != CRYPT_SUCCESS); ASSERT_TRUE(CRYPT_EAL_EsCtrl(es, CRYPT_ENTROPY_ADD_NS, (void *)&para, sizeof(CRYPT_EAL_NsPara)) != CRYPT_SUCCESS); ASSERT_TRUE(CRYPT_EAL_EsCtrl(es, CRYPT_ENTROPY_REMOVE_NS, (void *)(intptr_t)para.name, strlen(para.name)) != CRYPT_SUCCESS); EXIT: CRYPT_EAL_EsFree(es); return; #else SKIP_TEST(); #endif } /* END_CASE */ /* @ * @test SDV_CRYPTO_ENTROPY_EsGatherTest * @spec - * @title Testing the entropy source gather interface. * @precon nan * @prior Level 1 * @auto TRUE @ */ /* BEGIN_CASE */ void SDV_CRYPTO_ENTROPY_EsGatherTest(int gather, int length, int expRes) { #ifdef HITLS_CRYPTO_ENTROPY_SYS CRYPT_EAL_Es *es = CRYPT_EAL_EsNew(); ASSERT_TRUE(es != NULL); ASSERT_TRUE(CRYPT_EAL_EsCtrl(es, CRYPT_ENTROPY_SET_CF, (void *)(intptr_t)"sm3_df", strlen("sm3_df")) == CRYPT_SUCCESS); bool healthTest = true; ASSERT_TRUE(CRYPT_EAL_EsCtrl(es, CRYPT_ENTROPY_ENABLE_TEST, &healthTest, 1) == CRYPT_SUCCESS); uint32_t size = 512; ASSERT_TRUE(CRYPT_EAL_EsCtrl(es, CRYPT_ENTROPY_SET_POOL_SIZE, (void *)&size, sizeof(uint32_t)) == CRYPT_SUCCESS); ASSERT_TRUE(CRYPT_EAL_EsInit(es) == CRYPT_SUCCESS); if (gather == 1) { BSL_SAL_ThreadId thrd; ASSERT_TRUE(BSL_SAL_ThreadCreate(&thrd, EsGatherAuto, es) == 0); BSL_SAL_ThreadClose(thrd); } uint8_t buf[513] = {0}; uint32_t len = CRYPT_EAL_EsEntropyGet(es, buf, length); ASSERT_TRUE(len == (uint32_t)expRes); EXIT: CRYPT_EAL_EsFree(es); return; #else (void)gather; (void)length; (void)expRes; SKIP_TEST(); #endif } /* END_CASE */ /* @ * @test SDV_CRYPTO_ENTROPY_EsWithoutNsTest * @spec - * @title No or no available noise source test. * @precon nan * @prior Level 1 * @auto TRUE @ */ /* BEGIN_CASE */ void SDV_CRYPTO_ENTROPY_EsWithoutNsTest() { #ifdef HITLS_CRYPTO_ENTROPY_SYS CRYPT_EAL_Es *es = CRYPT_EAL_EsNew(); ASSERT_TRUE(es != NULL); ASSERT_TRUE(CRYPT_EAL_EsCtrl(es, CRYPT_ENTROPY_SET_CF, (void *)(intptr_t)"sm3_df", strlen("sm3_df")) == CRYPT_SUCCESS); ASSERT_TRUE(CRYPT_EAL_EsCtrl(es, CRYPT_ENTROPY_REMOVE_NS, (void *)(uintptr_t)"timestamp", 9) == CRYPT_SUCCESS); ASSERT_TRUE(CRYPT_EAL_EsCtrl(es, CRYPT_ENTROPY_REMOVE_NS, (void *)(uintptr_t)"CPU-Jitter", 10) == CRYPT_SUCCESS); ASSERT_TRUE(CRYPT_EAL_EsInit(es) != CRYPT_SUCCESS); CRYPT_EAL_NsPara para = { "aaa", false, 7, { NULL, EntropyInitError, EntropyReadError, EntropyDeinitTest, }, {5, 39, 512}, }; ASSERT_TRUE(CRYPT_EAL_EsCtrl(es, CRYPT_ENTROPY_ADD_NS, (void *)&para, sizeof(CRYPT_EAL_NsPara)) == CRYPT_SUCCESS); ASSERT_TRUE(CRYPT_EAL_EsInit(es) != CRYPT_SUCCESS); EXIT: CRYPT_EAL_EsFree(es); return; #else SKIP_TEST(); #endif } /* END_CASE */ /* @ * @test SDV_CRYPTO_ENTROPY_EsMultiNsTest * @spec - * @title Test with available and various unavailable noise sources. * @precon nan * @prior Level 1 * @auto TRUE @ */ /* BEGIN_CASE */ void SDV_CRYPTO_ENTROPY_EsMultiNsTest() { #ifdef HITLS_CRYPTO_ENTROPY_SYS CRYPT_EAL_Es *es = CRYPT_EAL_EsNew(); ASSERT_TRUE(es != NULL); ASSERT_TRUE(CRYPT_EAL_EsCtrl(es, CRYPT_ENTROPY_SET_CF, (void *)(intptr_t)"sm3_df", strlen("sm3_df")) == CRYPT_SUCCESS); bool healthTest = true; ASSERT_TRUE(CRYPT_EAL_EsCtrl(es, CRYPT_ENTROPY_ENABLE_TEST, &healthTest, 1) == CRYPT_SUCCESS); CRYPT_EAL_NsPara errPara = { "read-err-ns", false, 7, { NULL, NULL, EntropyReadError, NULL, }, {5, 39, 512}, }; ASSERT_TRUE(CRYPT_EAL_EsCtrl(es, CRYPT_ENTROPY_ADD_NS, (void *)&errPara, sizeof(CRYPT_EAL_NsPara)) == CRYPT_SUCCESS); CRYPT_EAL_NsPara initPara = { "init-err-ns", false, 7, { NULL, EntropyInitError, EntropyReadDiffData, EntropyDeinitTest, }, {5, 39, 512}, }; ASSERT_TRUE(CRYPT_EAL_EsCtrl(es, CRYPT_ENTROPY_ADD_NS, (void *)&initPara, sizeof(CRYPT_EAL_NsPara)) == CRYPT_SUCCESS); CRYPT_EAL_NsPara heaPara = { "health-err-ns", false, 7, { NULL, EntropyInitTest, EntropyReadNormal, EntropyDeinitTest, }, {5, 39, 512}, }; ASSERT_TRUE(CRYPT_EAL_EsCtrl(es, CRYPT_ENTROPY_ADD_NS, (void *)&heaPara, sizeof(CRYPT_EAL_NsPara)) == CRYPT_SUCCESS); CRYPT_EAL_NsPara norPara = { "normal-ns", false, 7, { NULL, EntropyInitTest, EntropyReadDiffData, EntropyDeinitTest, }, {5, 39, 512}, }; ASSERT_TRUE(CRYPT_EAL_EsCtrl(es, CRYPT_ENTROPY_ADD_NS, (void *)&norPara, sizeof(CRYPT_EAL_NsPara)) == CRYPT_SUCCESS); ASSERT_TRUE(CRYPT_EAL_EsInit(es) == CRYPT_SUCCESS); uint8_t buf[32] = {0}; ASSERT_TRUE(CRYPT_EAL_EsEntropyGet(es, buf, 32) == 32); EXIT: CRYPT_EAL_EsFree(es); return; #else SKIP_TEST(); #endif } /* END_CASE */ /* @ * @test SDV_CRYPTO_ENTROPY_EsNsNumberTest * @spec - * @title Test with available and various unavailable noise sources. * @precon nan * @prior Level 1 * @auto TRUE @ */ /* BEGIN_CASE */ void SDV_CRYPTO_ENTROPY_EsNsNumberTest(int number, int minEn, int expLen) { #ifdef HITLS_CRYPTO_ENTROPY_SYS CRYPT_EAL_Es *es = CRYPT_EAL_EsNew(); ASSERT_TRUE(es != NULL); ASSERT_TRUE(CRYPT_EAL_EsCtrl(es, CRYPT_ENTROPY_SET_CF, (void *)(intptr_t)"sm3_df", strlen("sm3_df")) == CRYPT_SUCCESS); bool healthTest = true; ASSERT_TRUE(CRYPT_EAL_EsCtrl(es, CRYPT_ENTROPY_ENABLE_TEST, &healthTest, 1) == CRYPT_SUCCESS); ASSERT_TRUE(CRYPT_EAL_EsCtrl(es, CRYPT_ENTROPY_REMOVE_NS, (void *)(uintptr_t)"timestamp", 9) == CRYPT_SUCCESS); ASSERT_TRUE(CRYPT_EAL_EsCtrl(es, CRYPT_ENTROPY_REMOVE_NS, (void *)(uintptr_t)"CPU-Jitter", 10) == CRYPT_SUCCESS); CRYPT_EAL_NsPara errPara = { NULL, false, minEn, { NULL, NULL, EntropyReadDiffData, NULL, }, {5, 39, 512}, }; const char *name = "ns-normal-"; errPara.name = BSL_SAL_Malloc(strlen(name) + 3); ASSERT_TRUE(errPara.name != NULL); for(int32_t iter = 0; iter < number; iter++) { char str[3] = {0}; strncpy_s((char *)(intptr_t)errPara.name, strlen(name) + 3, name, strlen(name)); sprintf_s(str, 3, "%d", iter); strcat_s((char *)(intptr_t)errPara.name, strlen(name) + 3, str); if (iter >= 16) { ASSERT_TRUE(CRYPT_EAL_EsCtrl(es, CRYPT_ENTROPY_ADD_NS, (void *)&errPara, sizeof(CRYPT_EAL_NsPara)) != CRYPT_SUCCESS); } else { ASSERT_TRUE(CRYPT_EAL_EsCtrl(es, CRYPT_ENTROPY_ADD_NS, (void *)&errPara, sizeof(CRYPT_EAL_NsPara)) == CRYPT_SUCCESS); } } ASSERT_TRUE(CRYPT_EAL_EsInit(es) == CRYPT_SUCCESS); uint8_t buf[32] = {0}; ASSERT_TRUE(CRYPT_EAL_EsEntropyGet(es, buf, 32) == (uint32_t)expLen); EXIT: BSL_SAL_Free((void *)(intptr_t)errPara.name); CRYPT_EAL_EsFree(es); return; #else (void)number; (void)minEn; (void)expLen; SKIP_TEST(); #endif } /* END_CASE */ /* @ * @test SDV_CRYPTO_ENTROPY_EorTest * @spec - * @title Test with available and various unavailable noise sources. * @brief 1.conditioning function not set, expected result 1 2.entropy source not initialized, expected result 2 3.repeated setting of conditioning function, expected result 3 * @expect 1. result 1: failed 2. result 2: failed 3. result 3: failed * @prior Level 1 * @auto TRUE @ */ /* BEGIN_CASE */ void SDV_CRYPTO_ENTROPY_EorTest(void) { #ifdef HITLS_CRYPTO_ENTROPY_SYS CRYPT_EAL_Es *es = CRYPT_EAL_EsNew(); ASSERT_TRUE(es != NULL); ASSERT_TRUE(CRYPT_EAL_EsInit(es) != CRYPT_SUCCESS); ASSERT_TRUE(CRYPT_EAL_EsCtrl(es, CRYPT_ENTROPY_SET_CF, (void *)(intptr_t)"sm3_df", strlen("sm3_df")) == CRYPT_SUCCESS); uint8_t buf[32] = {0}; ASSERT_TRUE(CRYPT_EAL_EsEntropyGet(es, buf, 32) == 0); ASSERT_TRUE(CRYPT_EAL_EsCtrl(es, CRYPT_ENTROPY_SET_CF, (void *)(intptr_t)"sm3_df", strlen("sm3_df")) != CRYPT_SUCCESS); EXIT: CRYPT_EAL_EsFree(es); return; #else SKIP_TEST(); #endif } /* END_CASE */ /* @ * @test SDV_CRYPTO_ENTROPY_MutiTest * @spec - * @title Test with available and various unavailable noise sources. * @brief * @prior Level 1 * @auto TRUE @ */ /* BEGIN_CASE */ void SDV_CRYPTO_ENTROPY_MutiTest(void) { #ifdef HITLS_CRYPTO_ENTROPY_SYS CRYPT_EAL_Es *es = CRYPT_EAL_EsNew(); ASSERT_TRUE(es != NULL); ASSERT_TRUE(CRYPT_EAL_EsCtrl(es, CRYPT_ENTROPY_SET_CF, (void *)(intptr_t)"sha256_df", strlen("sha256_df")) == CRYPT_SUCCESS); uint32_t size = 512; ASSERT_TRUE(CRYPT_EAL_EsCtrl(es, CRYPT_ENTROPY_SET_POOL_SIZE, (void *)&size, sizeof(uint32_t)) == CRYPT_SUCCESS); ASSERT_TRUE(CRYPT_EAL_EsInit(es) == CRYPT_SUCCESS); BSL_SAL_ThreadId thrd; ASSERT_TRUE(BSL_SAL_ThreadCreate(&thrd, EsGatherAuto, es) == 0); BSL_SAL_ThreadClose(thrd); for (int32_t iter = 0; iter < 3; iter++) { BSL_SAL_ThreadId thrdget; ASSERT_TRUE(BSL_SAL_ThreadCreate(&thrdget, EsGetAuto, es) == 0); BSL_SAL_ThreadClose(thrdget); } EXIT: CRYPT_EAL_EsFree(es); return; #else SKIP_TEST(); #endif } /* END_CASE */ /* @ * @test SDV_CRYPTO_ENTROPY_MutiBeforeInitTest * @spec - * @title Test with available and various unavailable noise sources. * @brief * @prior Level 1 * @auto TRUE @ */ /* BEGIN_CASE */ void SDV_CRYPTO_ENTROPY_MutiBeforeInitTest(void) { #ifdef HITLS_CRYPTO_ENTROPY_SYS CRYPT_EAL_Es *es = CRYPT_EAL_EsNew(); ASSERT_TRUE(es != NULL); for (int32_t iter = 0; iter < 3; iter++) { BSL_SAL_ThreadId thrdget; ASSERT_TRUE(BSL_SAL_ThreadCreate(&thrdget, EsMutiAuto, es) == 0); BSL_SAL_ThreadClose(thrdget); } BSL_SAL_ThreadId thrd; ASSERT_TRUE(BSL_SAL_ThreadCreate(&thrd, EsGatherAuto, es) == 0); BSL_SAL_ThreadClose(thrd); EXIT: CRYPT_EAL_EsFree(es); return; #else SKIP_TEST(); #endif } /* END_CASE */ /* @ * @test SDV_CRYPTO_ENTROPY_ES_FUNC_0001 * @spec - * @title Function test with the health test disabled, noise source not added, and entropy not added. * @precon nan * @prior Level 1 * @auto TRUE @ */ /* BEGIN_CASE */ void SDV_CRYPTO_ENTROPY_ES_FUNC_0001(int enableTest) { #ifdef HITLS_CRYPTO_ENTROPY_SYS CRYPT_EAL_Es *es = CRYPT_EAL_EsNew(); ASSERT_TRUE(es != NULL); ASSERT_TRUE(CRYPT_EAL_EsCtrl(es, CRYPT_ENTROPY_SET_CF, (void *)(intptr_t)"sha512_df", strlen("sha512_df")) == CRYPT_SUCCESS); if(enableTest) { bool healthTest = true; ASSERT_TRUE(CRYPT_EAL_EsCtrl(es, CRYPT_ENTROPY_ENABLE_TEST, &healthTest, 1) == CRYPT_SUCCESS); } ASSERT_TRUE(CRYPT_EAL_EsInit(es) == CRYPT_SUCCESS); uint32_t size; ASSERT_TRUE(CRYPT_EAL_EsCtrl(es, CRYPT_ENTROPY_POOL_GET_CURRSIZE, (void *)&size, sizeof(uint32_t)) == CRYPT_SUCCESS); ASSERT_EQ(size, 0); ASSERT_TRUE(CRYPT_EAL_EsCtrl(es, CRYPT_ENTROPY_GATHER_ENTROPY, NULL, 0) == CRYPT_SUCCESS); ASSERT_TRUE(CRYPT_EAL_EsCtrl(es, CRYPT_ENTROPY_POOL_GET_CURRSIZE, (void *)&size, sizeof(uint32_t)) == CRYPT_SUCCESS); ASSERT_EQ(size, 64); uint8_t buf[8192] = {0}; uint32_t resLen = CRYPT_EAL_EsEntropyGet(es, buf, 8192); ASSERT_TRUE(resLen == 64); EXIT: CRYPT_EAL_EsFree(es); return; #else (void)enableTest; SKIP_TEST(); #endif } /* END_CASE */ /* @ * @test SDV_CRYPTO_ENTROPY_ES_FUNC_0002 * @spec - * @title Function test of adding noise sources and entropy by pressing Ctrl when the health check mode is disabled. * @precon nan * @prior Level 1 * @auto TRUE @ */ /* BEGIN_CASE */ void SDV_CRYPTO_ENTROPY_ES_FUNC_0002(int enableTest) { #ifdef HITLS_CRYPTO_ENTROPY_SYS CRYPT_EAL_Es *es = CRYPT_EAL_EsNew(); ASSERT_TRUE(es != NULL); ASSERT_TRUE(CRYPT_EAL_EsCtrl(es, CRYPT_ENTROPY_SET_CF, (void *)(intptr_t)"sm3_df", strlen("sm3_df")) == CRYPT_SUCCESS); ASSERT_TRUE(CRYPT_EAL_EsCtrl(es, CRYPT_ENTROPY_REMOVE_NS, (void *)(uintptr_t)"timestamp", 9) == CRYPT_SUCCESS); ASSERT_TRUE(CRYPT_EAL_EsCtrl(es, CRYPT_ENTROPY_REMOVE_NS, (void *)(uintptr_t)"CPU-Jitter", 10) == CRYPT_SUCCESS); CRYPT_EAL_NsPara norPara = { "normal-ns", enableTest, 7, { NULL, EntropyInitTest, EntropyReadDiffData, EntropyDeinitTest, }, {5, 39, 512}, }; ASSERT_TRUE(CRYPT_EAL_EsCtrl(es, CRYPT_ENTROPY_ADD_NS, (void *)&norPara, sizeof(CRYPT_EAL_NsPara)) == CRYPT_SUCCESS); if(enableTest) { bool healthTest = true; ASSERT_TRUE(CRYPT_EAL_EsCtrl(es, CRYPT_ENTROPY_ENABLE_TEST, &healthTest, 1) == CRYPT_SUCCESS); } ASSERT_TRUE(CRYPT_EAL_EsInit(es) == CRYPT_SUCCESS); uint32_t size; ASSERT_TRUE(CRYPT_EAL_EsCtrl(es, CRYPT_ENTROPY_POOL_GET_CURRSIZE, (void *)&size, sizeof(uint32_t)) == CRYPT_SUCCESS); ASSERT_EQ(size, 0); ASSERT_TRUE(CRYPT_EAL_EsCtrl(es, CRYPT_ENTROPY_GATHER_ENTROPY, NULL, 0) == CRYPT_SUCCESS); ASSERT_TRUE(CRYPT_EAL_EsCtrl(es, CRYPT_ENTROPY_POOL_GET_CURRSIZE, (void *)&size, sizeof(uint32_t)) == CRYPT_SUCCESS); ASSERT_EQ(size, 32); uint8_t buf[8192] = {0}; uint32_t resLen = CRYPT_EAL_EsEntropyGet(es, buf, 8192); ASSERT_TRUE(resLen == 32); ASSERT_TRUE(CRYPT_EAL_EsCtrl(es, CRYPT_ENTROPY_POOL_GET_CURRSIZE, (void *)&size, sizeof(uint32_t)) == CRYPT_SUCCESS); ASSERT_EQ(size, 0); EXIT: CRYPT_EAL_EsFree(es); return; #else (void)enableTest; SKIP_TEST(); #endif } /* END_CASE */ /* @ * @test SDV_CRYPTO_ENTROPY_ES_FUNC_0003 * @spec - * @title Entropy source traversal test with the health test disabled, no noise source added, and different compression functions enabled. * @precon nan * @prior Level 1 * @auto TRUE @ */ /* BEGIN_CASE */ void SDV_CRYPTO_ENTROPY_ES_FUNC_0003(int alg, int enableTest) { #ifdef HITLS_CRYPTO_ENTROPY_SYS CRYPT_EAL_Es *es = CRYPT_EAL_EsNew(); ASSERT_TRUE(es != NULL); const char *mode = EsGetCfMode((uint32_t)alg); uint32_t expectGetLen = EsGetCfLen((uint32_t)alg); ASSERT_TRUE(CRYPT_EAL_EsCtrl(es, CRYPT_ENTROPY_SET_CF, (void *)(intptr_t)mode, strlen(mode)) == CRYPT_SUCCESS); if(enableTest) { bool healthTest = true; ASSERT_TRUE(CRYPT_EAL_EsCtrl(es, CRYPT_ENTROPY_ENABLE_TEST, &healthTest, 1) == CRYPT_SUCCESS); } ASSERT_TRUE(CRYPT_EAL_EsInit(es) == CRYPT_SUCCESS); uint32_t size; ASSERT_TRUE(CRYPT_EAL_EsCtrl(es, CRYPT_ENTROPY_POOL_GET_CURRSIZE, (void *)&size, sizeof(uint32_t)) == CRYPT_SUCCESS); ASSERT_EQ(size, 0); ASSERT_TRUE(CRYPT_EAL_EsCtrl(es, CRYPT_ENTROPY_GATHER_ENTROPY, NULL, 0) == CRYPT_SUCCESS); ASSERT_TRUE(CRYPT_EAL_EsCtrl(es, CRYPT_ENTROPY_POOL_GET_CURRSIZE, (void *)&size, sizeof(uint32_t)) == CRYPT_SUCCESS); ASSERT_EQ(size, expectGetLen); uint8_t buf[8192] = {0}; uint32_t resLen = CRYPT_EAL_EsEntropyGet(es, buf, 8192); ASSERT_TRUE(resLen == expectGetLen); EXIT: CRYPT_EAL_EsFree(es); return; #else (void)alg; (void)enableTest; SKIP_TEST(); #endif } /* END_CASE */ /* @ * @test SDV_CRYPTO_ENTROPY_ES_FUNC_0004 * @spec - * @title Function test of adding noise source and removing noise source after obtaining entropy source in health test disabled mode. * @precon nan * @prior Level 1 * @auto TRUE @ */ /* BEGIN_CASE */ void SDV_CRYPTO_ENTROPY_ES_FUNC_0004(int enableTest) { #ifdef HITLS_CRYPTO_ENTROPY_SYS uint32_t expectGetLen = 32; CRYPT_EAL_Es *es = CRYPT_EAL_EsNew(); ASSERT_TRUE(es != NULL); ASSERT_TRUE(CRYPT_EAL_EsCtrl(es, CRYPT_ENTROPY_SET_CF, (void *)(intptr_t)"sm3_df", strlen("sm3_df")) == CRYPT_SUCCESS); ASSERT_TRUE(CRYPT_EAL_EsCtrl(es, CRYPT_ENTROPY_REMOVE_NS, (void *)(uintptr_t)"timestamp", 9) == CRYPT_SUCCESS); ASSERT_TRUE(CRYPT_EAL_EsCtrl(es, CRYPT_ENTROPY_REMOVE_NS, (void *)(uintptr_t)"CPU-Jitter", 10) == CRYPT_SUCCESS); ASSERT_TRUE(CRYPT_EAL_EsInit(es) == CRYPT_ENTROPY_ES_NO_NS); CRYPT_EAL_NsPara norPara1 = { "normal-ns", enableTest, 7, { NULL, EntropyInitTest, EntropyReadDiffData, EntropyDeinitTest, }, {0, 0, 512}, }; CRYPT_EAL_NsPara norPara2 = { "timestamp", enableTest, 7, { NULL, EntropyInitTest, EntropyReadDiffData, EntropyDeinitTest, }, {5, 39, 512}, }; ASSERT_TRUE(CRYPT_EAL_EsCtrl(es, CRYPT_ENTROPY_ADD_NS, (void *)&norPara1, sizeof(CRYPT_EAL_NsPara)) == CRYPT_SUCCESS); if(enableTest) { bool healthTest = true; ASSERT_TRUE(CRYPT_EAL_EsCtrl(es, CRYPT_ENTROPY_ENABLE_TEST, &healthTest, 1) == CRYPT_SUCCESS); } ASSERT_TRUE(CRYPT_EAL_EsInit(es) == CRYPT_SUCCESS); uint32_t size; ASSERT_TRUE(CRYPT_EAL_EsCtrl(es, CRYPT_ENTROPY_POOL_GET_CURRSIZE, (void *)&size, sizeof(uint32_t)) == CRYPT_SUCCESS); ASSERT_EQ(size, 0); ASSERT_TRUE(CRYPT_EAL_EsCtrl(es, CRYPT_ENTROPY_GATHER_ENTROPY, NULL, 0) == CRYPT_SUCCESS); ASSERT_TRUE(CRYPT_EAL_EsCtrl(es, CRYPT_ENTROPY_POOL_GET_CURRSIZE, (void *)&size, sizeof(uint32_t)) == CRYPT_SUCCESS); ASSERT_EQ(size, expectGetLen); uint8_t buf[8192] = {0}; uint32_t resLen = CRYPT_EAL_EsEntropyGet(es, buf, 8192); ASSERT_TRUE(resLen == expectGetLen); ASSERT_TRUE(CRYPT_EAL_EsCtrl(es, CRYPT_ENTROPY_POOL_GET_CURRSIZE, (void *)&size, sizeof(uint32_t)) == CRYPT_SUCCESS); ASSERT_EQ(size, 0); (void)BSL_SAL_ThreadWriteLock(es->lock); ENTROPY_EsDeinit(es->es); (void)BSL_SAL_ThreadUnlock(es->lock); ASSERT_TRUE(CRYPT_EAL_EsCtrl(es, CRYPT_ENTROPY_REMOVE_NS, (void *)(uintptr_t)"normal-ns", 10) == CRYPT_SUCCESS); ASSERT_TRUE(CRYPT_EAL_EsInit(es) == CRYPT_ENTROPY_ES_NO_NS); ASSERT_TRUE(CRYPT_EAL_EsCtrl(es, CRYPT_ENTROPY_ADD_NS, (void *)&norPara2, sizeof(CRYPT_EAL_NsPara)) == CRYPT_SUCCESS); ASSERT_TRUE(CRYPT_EAL_EsInit(es) == CRYPT_SUCCESS); ASSERT_TRUE(CRYPT_EAL_EsCtrl(es, CRYPT_ENTROPY_GATHER_ENTROPY, NULL, 0) == CRYPT_SUCCESS); resLen = CRYPT_EAL_EsEntropyGet(es, buf, 8192); ASSERT_TRUE(resLen == expectGetLen); EXIT: CRYPT_EAL_EsFree(es); return; #else (void)enableTest; SKIP_TEST(); #endif } /* END_CASE */ /* @ * @test SDV_CRYPTO_ENTROPY_ES_FUNC_0005 * @spec - * @title Functional testing of boundary values for different entropy pool sizes. * @precon nan * @prior Level 1 * @auto TRUE @ */ /* BEGIN_CASE */ void SDV_CRYPTO_ENTROPY_ES_FUNC_0005(void) { #ifdef HITLS_CRYPTO_ENTROPY_SYS uint32_t poolErrorSize[] = {511, 4097, 1024}; uint32_t poolSize = 512; int32_t ret = 1; CRYPT_EAL_Es *es = CRYPT_EAL_EsNew(); ASSERT_TRUE(es != NULL); ASSERT_TRUE(CRYPT_EAL_EsCtrl(es, CRYPT_ENTROPY_SET_CF, (void *)(intptr_t)"sm3_df", strlen("sm3_df")) == CRYPT_SUCCESS); for (uint32_t i = 0; i < sizeof(poolErrorSize)/sizeof(uint32_t); i++) { ret = CRYPT_EAL_EsCtrl(es, CRYPT_ENTROPY_SET_POOL_SIZE, (void *)&poolErrorSize[i], sizeof(uint32_t)); if (ret == CRYPT_SUCCESS) { ASSERT_TRUE(CRYPT_EAL_EsCtrl(es, CRYPT_ENTROPY_GET_POOL_SIZE, &poolSize, sizeof(uint32_t)) == CRYPT_ENTROPY_ES_STATE_ERROR); ASSERT_TRUE(CRYPT_EAL_EsInit(es) == CRYPT_SUCCESS); ASSERT_TRUE(CRYPT_EAL_EsCtrl(es, CRYPT_ENTROPY_GET_POOL_SIZE, &poolSize, sizeof(uint32_t)) == CRYPT_SUCCESS); ASSERT_EQ(poolSize, poolErrorSize[i]); } else { ASSERT_TRUE(ret == CRYPT_ENTROPY_CTRL_INVALID_PARAM); } } EXIT: CRYPT_EAL_EsFree(es); return; #else SKIP_TEST(); #endif } /* END_CASE */ /* @ * @test SDV_CRYPTO_ENTROPY_ES_FUNC_0006 * @spec - * @title Entropy source function test in the multi-thread concurrency scenario. * @precon nan * @prior Level 1 * @auto TRUE @ */ /* BEGIN_CASE */ void SDV_CRYPTO_ENTROPY_ES_FUNC_0006(int alg) { #ifdef HITLS_CRYPTO_ENTROPY_SYS const uint32_t threadNum = 5; pthread_t threadId[threadNum]; for(uint32_t i = 0; i < threadNum; i++) { int ret = pthread_create(&threadId[i], NULL, (void *)EntropyESMutilTest, &alg); ASSERT_TRUE(ret == 0); } for(uint32_t i = 0; i < threadNum; i++) { pthread_join(threadId[i], NULL); } EXIT: return; #else (void)alg; SKIP_TEST(); #endif } /* END_CASE */ /* @ * @test SDV_CRYPTO_ENTROPY_ES_FUNC_0007 * @spec - * @title Adding an Existing Noise Source Control Test. * @precon nan * @prior Level 1 * @auto TRUE @ */ /* BEGIN_CASE */ void SDV_CRYPTO_ENTROPY_ES_FUNC_0007(int enableTest) { #ifdef HITLS_CRYPTO_ENTROPY_SYS CRYPT_EAL_NsPara norPara = { "timestamp", enableTest, 7, { NULL, EntropyInitTest, EntropyReadDiffData, EntropyDeinitTest, }, {5, 39, 512}, }; CRYPT_EAL_Es *es = CRYPT_EAL_EsNew(); ASSERT_TRUE(es != NULL); ASSERT_TRUE(CRYPT_EAL_EsCtrl(es, CRYPT_ENTROPY_SET_CF, (void *)(intptr_t)"sm3_df", strlen("sm3_df")) == CRYPT_SUCCESS); ASSERT_TRUE(CRYPT_EAL_EsCtrl(es, CRYPT_ENTROPY_ADD_NS, (void *)&norPara, sizeof(CRYPT_EAL_NsPara)) == CRYPT_ENTROPY_ES_DUP_NS); ASSERT_TRUE(CRYPT_EAL_EsCtrl(es, CRYPT_ENTROPY_REMOVE_NS, (void *)(uintptr_t)"notExistNs", 10) == CRYPT_ENTROPY_ES_NS_NOT_FOUND); EXIT: CRYPT_EAL_EsFree(es); return; #else (void)enableTest; SKIP_TEST(); #endif } /* END_CASE */ /* @ * @test SDV_CRYPTO_EAL_SEEDPOOL_GetTest * @spec - * @title seedpool_GetTest * @precon nan * @brief 1. Entropy data length: 32 - 512, entropy amount: 384, npes not available, return length: 48 2. Entropy data length: 32 - 512, entropy amount: 384, npes available, return length: 64 3. entropy data length: 64 - 512, entropy: 380, npes not available, return length: 64 4. Entropy data length: 64 - 512, entropy amount: 380, npes available, return length: 64 5. Entropy data length: 48 - 512, entropy amount: 384, npes available, return length: 54 6. entropy data length: 32 - 32, entropy amount: 256, npes not available, return length: 32 7. entropy data length: 48 - 48, entropy amount: 256, npes available, return length: 48 8. entropy data length: 48 - 512, entropy amount: 680, npes available, return length: 48 * @expect * @prior Level 1 * @auto TRUE @ */ /* BEGIN_CASE */ void SDV_CRYPTO_EAL_SEEDPOOL_GetTest(int min, int max, int entropy, int npes, int exp) { uint8_t *buf = NULL; CRYPT_EAL_SeedPoolCtx *pool = CRYPT_EAL_SeedPoolNew(true); ASSERT_TRUE(pool != NULL); CRYPT_EAL_EsPara para1 = {false, 6, NULL, (CRYPT_EAL_EntropyGet)EntropyGetNormal}; CRYPT_EAL_EsPara para2 = {true, 8, NULL, (CRYPT_EAL_EntropyGet)EntropyGetNormal}; ASSERT_TRUE(CRYPT_EAL_SeedPoolAddEs(pool, &para1) == CRYPT_SUCCESS); ASSERT_TRUE(CRYPT_EAL_SeedPoolAddEs(pool, &para2) == CRYPT_SUCCESS); EAL_EntropyCtx *ctx = EAL_EntropyNewCtx(pool, (bool)npes, (uint32_t)min, (uint32_t)max, (uint32_t)entropy); ASSERT_TRUE(ctx != NULL); ASSERT_TRUE(EAL_EntropyCollection(pool, ctx) == CRYPT_SUCCESS); uint32_t len; buf = EAL_EntropyDetachBuf(ctx, &len); ASSERT_TRUE(len == (uint32_t)exp); if (exp == 0) { ASSERT_TRUE(buf == NULL); } else { ASSERT_TRUE(buf != NULL); } EXIT: BSL_SAL_Free(buf); EAL_EntropyFreeCtx(ctx); CRYPT_EAL_SeedPoolFree(pool); return; } /* END_CASE */ #if defined(HITLS_CRYPTO_ENTROPY_GETENTROPY) || defined(HITLS_CRYPTO_ENTROPY_DEVRANDOM) #include "entropy_seed_pool.h" typedef struct EntCtx { uint32_t entSum; } EntCtx; static uint32_t EntropyGetSum(void *ctx, uint8_t *buf, uint32_t bufLen) { EntCtx *enctx = (EntCtx *)ctx; uint32_t ret = ENTROPY_SysEntropyGet(ctx, buf, bufLen); enctx->entSum += ret; return ret; } #endif /* BEGIN_CASE */ void SDV_CRYPTO_EAL_SEEDPOOL_EntropySumTest(int minEntropy1, int minEntropy2, int min, int entropy, int exp) { #if defined(HITLS_CRYPTO_ENTROPY_GETENTROPY) || defined(HITLS_CRYPTO_ENTROPY_DEVRANDOM) uint8_t *buf = NULL; EntCtx enctx = {0}; CRYPT_EAL_SeedPoolCtx *pool = CRYPT_EAL_SeedPoolNew(true); ASSERT_TRUE(pool != NULL); CRYPT_EAL_EsPara para1 = {false, minEntropy1, &enctx, (CRYPT_EAL_EntropyGet)EntropyGetSum}; CRYPT_EAL_EsPara para2 = {false, minEntropy2, &enctx, (CRYPT_EAL_EntropyGet)EntropyGetSum}; ASSERT_TRUE(CRYPT_EAL_SeedPoolAddEs(pool, &para1) == CRYPT_SUCCESS); ASSERT_TRUE(CRYPT_EAL_SeedPoolAddEs(pool, &para2) == CRYPT_SUCCESS); EAL_EntropyCtx *ctx = EAL_EntropyNewCtx(pool, true, (uint32_t)min, (uint32_t)min, (uint32_t)entropy); ASSERT_TRUE(ctx != NULL); ASSERT_TRUE(EAL_EntropyCollection(pool, ctx) == CRYPT_SUCCESS); uint32_t len; buf = EAL_EntropyDetachBuf(ctx, &len); ASSERT_TRUE(len == (uint32_t)min); if (exp == 0) { ASSERT_TRUE(buf == NULL); } else { ASSERT_TRUE(buf != NULL); } ASSERT_TRUE(enctx.entSum == (uint32_t)exp); EXIT: BSL_SAL_Free(buf); EAL_EntropyFreeCtx(ctx); CRYPT_EAL_SeedPoolFree(pool); return; #else (void)minEntropy1; (void)minEntropy2; (void)min; (void)entropy; (void)exp; SKIP_TEST(); #endif } /* END_CASE */ /* @ * @test SDV_CRYPTO_SEEDPOOL_DrbgTest * @spec - * @title use seedpool to construct an entropy source and generate a random number. * @precon nan * @prior Level 1 * @auto TRUE @ */ /* BEGIN_CASE */ void SDV_CRYPTO_SEEDPOOL_DrbgTest(int isNull, int algId) { #ifndef HITLS_CRYPTO_DRBG_GM if (algId == CRYPT_RAND_SM3 || algId == CRYPT_RAND_SM4_CTR_DF) { (void)isNull; SKIP_TEST(); } #endif #ifndef HITLS_CRYPTO_DRBG_HASH if (algId == CRYPT_RAND_SHA256) { (void)isNull; SKIP_TEST(); } #endif #ifndef HITLS_CRYPTO_DRBG_HMAC if (algId == CRYPT_RAND_HMAC_SHA256 || algId == CRYPT_RAND_HMAC_SHA384) { (void)isNull; SKIP_TEST(); } #endif #ifndef HITLS_CRYPTO_DRBG_CTR if (algId == CRYPT_RAND_AES128_CTR_DF || algId == CRYPT_RAND_SM4_CTR_DF) { (void)isNull; SKIP_TEST(); } #endif uint8_t output[16]; CRYPT_EAL_SeedPoolCtx *pool = CRYPT_EAL_SeedPoolNew((bool)isNull); CRYPT_EAL_EsPara para1 = {true, 6, NULL, (CRYPT_EAL_EntropyGet)EntropyGetNormal}; CRYPT_EAL_EsPara para2 = {false, 7, NULL, (CRYPT_EAL_EntropyGet)EntropyGetNormal}; ASSERT_TRUE(CRYPT_EAL_SeedPoolAddEs(pool, &para1) == CRYPT_SUCCESS); ASSERT_TRUE(CRYPT_EAL_SeedPoolAddEs(pool, &para2) == CRYPT_SUCCESS); CRYPT_RandSeedMethod meth = {0}; ASSERT_TRUE(EAL_SetDefaultEntropyMeth(&meth) == CRYPT_SUCCESS); CRYPT_EAL_RandDeinit(); ASSERT_TRUE(CRYPT_EAL_RandInit((CRYPT_RAND_AlgId)algId, &meth, (void *)pool, NULL, 0) == CRYPT_SUCCESS); ASSERT_TRUE(CRYPT_EAL_Randbytes(output, 16) == CRYPT_SUCCESS); EXIT: CRYPT_EAL_RandDeinit(); CRYPT_EAL_SeedPoolFree(pool); return; } /* END_CASE */ /* @ * @test SDV_CRYPTO_ENTROPY_DrbgTest * @spec - * @title use hitls es to construct an entropy source and generate a random number. * @precon nan * @prior Level 1 * @auto TRUE @ */ /* BEGIN_CASE */ void SDV_CRYPTO_ENTROPY_DrbgTest(void) { #ifdef HITLS_CRYPTO_ENTROPY_SYS uint8_t output[256]; CRYPT_EAL_Es *es = CRYPT_EAL_EsNew(); ASSERT_TRUE(es != NULL); ASSERT_TRUE(CRYPT_EAL_EsCtrl(es, CRYPT_ENTROPY_SET_CF, (void *)(intptr_t)"sha256_df", strlen("sha256_df")) == CRYPT_SUCCESS); CRYPT_EAL_NsPara para = { "aaa", true, 7, { NULL, NULL, EntropyReadNormal, NULL, }, {5, 39, 512}, }; ASSERT_TRUE(CRYPT_EAL_EsCtrl(es, CRYPT_ENTROPY_ADD_NS, (void *)&para, sizeof(CRYPT_EAL_NsPara)) == CRYPT_SUCCESS); ASSERT_TRUE(CRYPT_EAL_EsInit(es) == CRYPT_SUCCESS); for (int32_t iter = 0; iter < 5; iter++) { ASSERT_TRUE(CRYPT_EAL_EsCtrl(es, CRYPT_ENTROPY_GATHER_ENTROPY, NULL, 0) == CRYPT_SUCCESS); } CRYPT_RandSeedMethod meth = {GetEntropyTest, CleanEntropyTest, GetNonceTest, CleanNonceTest}; ASSERT_TRUE(CRYPT_EAL_RandInit(CRYPT_RAND_SHA256, &meth, (void *)es, NULL, 0) == CRYPT_SUCCESS); ASSERT_TRUE(CRYPT_EAL_Randbytes(output, 256) == CRYPT_SUCCESS); EXIT: CRYPT_EAL_RandDeinit(); CRYPT_EAL_EsFree(es); return; #else SKIP_TEST(); #endif } /* END_CASE */ /* @ * @test SDV_CRYPTO_SEEDPOOL_MutiTest * @spec - * @title use seedpool to construct the entropy source and perform the multi-thread test. * @precon nan * @prior Level 1 * @auto TRUE @ */ /* BEGIN_CASE */ void SDV_CRYPTO_SEEDPOOL_MutiTest(void) { CRYPT_EAL_SeedPoolCtx *pool = CRYPT_EAL_SeedPoolNew(false); CRYPT_EAL_EsPara para1 = {true, 6, NULL, (CRYPT_EAL_EntropyGet)EntropyGetNormal}; CRYPT_EAL_EsPara para2 = {false, 7, NULL, (CRYPT_EAL_EntropyGet)EntropyGetNormal}; ASSERT_TRUE(CRYPT_EAL_SeedPoolAddEs(pool, &para1) == CRYPT_SUCCESS); ASSERT_TRUE(CRYPT_EAL_SeedPoolAddEs(pool, &para2) == CRYPT_SUCCESS); CRYPT_RandSeedMethod meth = {0}; ASSERT_TRUE(EAL_SetDefaultEntropyMeth(&meth) == CRYPT_SUCCESS); for (int32_t index = 0; index < 3; index++) { pthread_t thrd; ASSERT_TRUE(pthread_create(&thrd, NULL, DrbgSeedTest, pool) == 0); pthread_join(thrd, NULL); } EXIT: CRYPT_EAL_SeedPoolFree(pool); return; } /* END_CASE */ /* @ * @test SDV_CRYPTO_SEEDPOOL_GetEntropyErrTest * @spec - * @title The entropy source quality is too poor to meet the requirements. * @precon nan * @prior Level 1 * @auto TRUE @ */ /* BEGIN_CASE */ void SDV_CRYPTO_SEEDPOOL_GetEntropyErrTest(void) { CRYPT_EAL_SeedPoolCtx *pool = GetPoolCtx(5, 5, true, false); ASSERT_TRUE(pool != NULL); EAL_EntropyCtx *ctx = EAL_EntropyNewCtx(pool, true, 32, 48, 256); ASSERT_TRUE(ctx != NULL); ASSERT_TRUE(EAL_EntropyCollection(pool, ctx) != CRYPT_SUCCESS); EXIT: CRYPT_EAL_SeedPoolFree(pool); EAL_EntropyFreeCtx(ctx); return; } /* END_CASE */ /* @ * @test SDV_CRYPTO_SEEDPOOL_EntLenLessMinTest * @spec - * @title The supplied entropy source data is smaller than the minimum length. * @precon nan * @prior Level 1 * @auto TRUE @ */ /* BEGIN_CASE */ void SDV_CRYPTO_SEEDPOOL_EntLenLessMinTest(void) { CRYPT_EAL_SeedPoolCtx *pool = GetPoolCtx(5, 5, true, false); ASSERT_TRUE(pool != NULL); EAL_EntropyCtx *ctx = EAL_EntropyNewCtx(pool, true, 32, 48, 128); ASSERT_TRUE(ctx != NULL); ASSERT_TRUE(EAL_EntropyCollection(pool, ctx) == CRYPT_SUCCESS); EXIT: CRYPT_EAL_SeedPoolFree(pool); EAL_EntropyFreeCtx(ctx); return; } /* END_CASE */ /* @ * @test SDV_CRYPTO_SEEDPOOL_Get0EntropyTest * @spec - * @title failed to obtain entropy data from the entropy pool. * @precon nan * @prior Level 1 * @auto TRUE @ */ /* BEGIN_CASE */ void SDV_CRYPTO_SEEDPOOL_Get0EntropyTest(void) { CRYPT_EAL_SeedPoolCtx *pool = CRYPT_EAL_SeedPoolNew(true); CRYPT_EAL_EsPara para1 = {true, 6, NULL, (CRYPT_EAL_EntropyGet)EntropyGet0Normal}; ASSERT_TRUE(CRYPT_EAL_SeedPoolAddEs(pool, &para1) == CRYPT_SUCCESS); EAL_EntropyCtx *ctx = EAL_EntropyNewCtx(pool, true, 32, 48, 256); ASSERT_TRUE(ctx != NULL); ASSERT_TRUE(EAL_EntropyCollection(pool, ctx) != CRYPT_SUCCESS); EXIT: CRYPT_EAL_SeedPoolFree(pool); EAL_EntropyFreeCtx(ctx); return; } /* END_CASE */ /* @ * @test SDV_CRYPTO_SEEDPOOL_UnsedSeedPoolTest * @spec - * @title Failed to obtain the entropy data of sufficient length. * @precon nan * @prior Level 1 * @auto TRUE @ */ /* BEGIN_CASE */ void SDV_CRYPTO_SEEDPOOL_UnsedSeedPoolTest(void) { CRYPT_EAL_SeedPoolCtx *pool = GetPoolCtx(8, 8, true, false); ASSERT_TRUE(pool != NULL); EAL_EntropyCtx *ctx = EAL_EntropyNewCtx(pool, true, 81, 100, 128); ASSERT_TRUE(ctx != NULL); ASSERT_TRUE(EAL_EntropyCollection(pool, ctx) != CRYPT_SUCCESS); EXIT: CRYPT_EAL_SeedPoolFree(pool); EAL_EntropyFreeCtx(ctx); return; } /* END_CASE */ /* @ * @test SDV_CRYPTO_SEEDPOOL_DiffEntropyTest * @spec - * @title The entropy pool used for handle creation is inconsistent with the obtained entropy pool. As a result, the entropy source fails to be obtained. * @precon nan * @prior Level 1 * @auto TRUE @ */ /* BEGIN_CASE */ void SDV_CRYPTO_SEEDPOOL_DiffEntropyTest(void) { CRYPT_EAL_SeedPoolCtx *pool = GetPoolCtx(8, 8, true, false); ASSERT_TRUE(pool != NULL); EAL_EntropyCtx *ctx = EAL_EntropyNewCtx(pool, true, 32, 64, 256); ASSERT_TRUE(ctx != NULL); CRYPT_EAL_SeedPoolCtx *pool1 = GetPoolCtx(6, 6, true, false); ASSERT_TRUE(pool1 != NULL); ASSERT_TRUE(EAL_EntropyCollection(pool1, ctx) != CRYPT_SUCCESS); CRYPT_EAL_SeedPoolFree(pool1); EXIT: CRYPT_EAL_SeedPoolFree(pool); EAL_EntropyFreeCtx(ctx); return; } /* END_CASE */ /* @ * @test SDV_CRYPTO_SEEDPOOL_Get0EntropyTest * @spec - * @title Obtains the total entropy output without using the conditioning function. * @precon nan * @prior Level 1 * @auto TRUE @ */ /* BEGIN_CASE */ void SDV_CRYPTO_SEEDPOOL_FENoEcfTest(int ent) { CRYPT_EAL_SeedPoolCtx *pool = GetPoolCtx(8, 7, true, false); ASSERT_TRUE(pool != NULL); EAL_EntropyCtx *ctx = EAL_EntropyNewCtx(pool, true, 32, 32, ent); ASSERT_TRUE(ctx != NULL); ASSERT_TRUE(EAL_EntropyCollection(pool, ctx) == CRYPT_SUCCESS); uint32_t len; uint8_t *data = EAL_EntropyDetachBuf(ctx, &len); ASSERT_TRUE(data != NULL); ASSERT_TRUE(len == 32); BSL_SAL_Free(data); EXIT: CRYPT_EAL_SeedPoolFree(pool); EAL_EntropyFreeCtx(ctx); return; } /* END_CASE */ /* @ * @test SDV_CRYPTO_SEEDPOOL_FEWithEcfTest * @spec - * @title Obtains the total entropy output without using the conditioning function. * @precon nan * @prior Level 1 * @auto TRUE @ */ /* BEGIN_CASE */ void SDV_CRYPTO_SEEDPOOL_FEWithEcfTest(void) { #ifndef HITLS_CRYPTO_HMAC SKIP_TEST(); #endif CRYPT_EAL_SeedPoolCtx *pool = GetPoolCtx(8, 7, true, false); ASSERT_TRUE(pool != NULL); EAL_EntropyCtx *ctx = EAL_EntropyNewCtx(pool, true, 48, 48, 384); ASSERT_TRUE(ctx != NULL); ASSERT_TRUE(EAL_EntropyCollection(pool, ctx) == CRYPT_SUCCESS); uint32_t len; uint8_t *data = EAL_EntropyDetachBuf(ctx, &len); ASSERT_TRUE(data != NULL); ASSERT_TRUE(len == 48); BSL_SAL_Free(data); EXIT: CRYPT_EAL_SeedPoolFree(pool); EAL_EntropyFreeCtx(ctx); return; } /* END_CASE */ /* @ * @test SDV_CRYPTO_SEEDPOOL_CompleteTest * @spec - * @title Complete usage testing from entropy source to drbg. * @precon nan * @prior Level 1 * @auto TRUE @ */ /* BEGIN_CASE */ void SDV_CRYPTO_SEEDPOOL_CompleteTest(void) { CRYPT_EAL_RndCtx *rndCtx = NULL; CRYPT_EAL_SeedPoolCtx *pool = CRYPT_EAL_SeedPoolNew(false); #ifdef HITLS_CRYPTO_ENTROPY_SYS CRYPT_EAL_Es *es = CRYPT_EAL_EsNew(); ASSERT_TRUE(es != NULL); char *mode = "sm3_df"; ASSERT_TRUE(CRYPT_EAL_EsCtrl(es, CRYPT_ENTROPY_SET_CF, (void *)(intptr_t)mode, strlen(mode)) == CRYPT_SUCCESS); bool healthTest = true; ASSERT_TRUE(CRYPT_EAL_EsCtrl(es, CRYPT_ENTROPY_ENABLE_TEST, &healthTest, 1) == CRYPT_SUCCESS); uint32_t size = 512; ASSERT_TRUE(CRYPT_EAL_EsCtrl(es, CRYPT_ENTROPY_SET_POOL_SIZE, (void *)&size, sizeof(uint32_t)) == CRYPT_SUCCESS); CRYPT_EAL_NsPara para = { "aaa", false, 5, { NULL, NULL, EntropyReadNormal, NULL, }, {5, 39, 512}, }; ASSERT_TRUE(CRYPT_EAL_EsCtrl(es, CRYPT_ENTROPY_ADD_NS, (void *)&para, sizeof(CRYPT_EAL_NsPara)) == CRYPT_SUCCESS); ASSERT_TRUE(CRYPT_EAL_EsInit(es) == CRYPT_SUCCESS); BSL_SAL_ThreadId thrd; ASSERT_TRUE(BSL_SAL_ThreadCreate(&thrd, EsGatherAuto, es) == 0); BSL_SAL_ThreadClose(thrd); CRYPT_EAL_EsPara para1 = {false, 8, es, (CRYPT_EAL_EntropyGet)CRYPT_EAL_EsEntropyGet}; ASSERT_TRUE(CRYPT_EAL_SeedPoolAddEs(pool, &para1) == CRYPT_SUCCESS); #endif CRYPT_RandSeedMethod meth = {0}; ASSERT_TRUE(EAL_SetDefaultEntropyMeth(&meth) == CRYPT_SUCCESS); #ifdef HITLS_CRYPTO_DRBG_GM rndCtx = CRYPT_EAL_DrbgNew(CRYPT_RAND_SM4_CTR_DF, &meth, pool); #else rndCtx = CRYPT_EAL_DrbgNew(CRYPT_RAND_AES256_CTR_DF, &meth, pool); #endif ASSERT_TRUE(rndCtx != NULL); ASSERT_TRUE(CRYPT_EAL_DrbgInstantiate(rndCtx, NULL, 0) == CRYPT_SUCCESS); uint8_t out[16] = {0}; ASSERT_TRUE(CRYPT_EAL_Drbgbytes(rndCtx, out, 16) == CRYPT_SUCCESS); ASSERT_TRUE(CRYPT_EAL_DrbgSeed(rndCtx) == CRYPT_SUCCESS); EXIT: CRYPT_EAL_DrbgDeinit(rndCtx); CRYPT_EAL_SeedPoolFree(pool); #ifdef HITLS_CRYPTO_ENTROPY_SYS CRYPT_EAL_EsFree(es); #endif return; } /* END_CASE */ /* @ * @test HITLS_SDV_DRBG_GM_FUNC_TC019 * @spec - * @title Complete usage testing from entropy sources. * @precon nan * @prior Level 1 * @auto TRUE @ */ /* BEGIN_CASE */ void HITLS_SDV_DRBG_GM_FUNC_TC019(int isCreateNullPool, int isPhysical, int minEntropy, int minL, int maxL, int entropyL, int isValid) { #ifdef HITLS_CRYPTO_ENTROPY_SYS CRYPT_EAL_Es *es = CRYPT_EAL_EsNew(); ASSERT_TRUE(es != NULL); char *mode = "sm3_df"; ASSERT_TRUE(CRYPT_EAL_EsCtrl(es, CRYPT_ENTROPY_SET_CF, (void *)(intptr_t)mode, strlen(mode)) == CRYPT_SUCCESS); bool healthTest = true; ASSERT_TRUE(CRYPT_EAL_EsCtrl(es, CRYPT_ENTROPY_ENABLE_TEST, &healthTest, sizeof(bool)) == CRYPT_SUCCESS); ASSERT_TRUE(CRYPT_EAL_EsInit(es) == CRYPT_SUCCESS); if (isCreateNullPool) { for (int i = 0; i < 16; i++) { ASSERT_TRUE(CRYPT_EAL_EsCtrl(es, CRYPT_ENTROPY_GATHER_ENTROPY, NULL, 0) == CRYPT_SUCCESS); } } CRYPT_EAL_EsPara esPara = {isPhysical, (uint32_t)minEntropy, es, NULL}; if (isValid) { esPara.entropyGet = (CRYPT_EAL_EntropyGet)CRYPT_EAL_EsEntropyGet; } else { esPara.entropyGet = (CRYPT_EAL_EntropyGet)ErrorGetEsEntropy; } CRYPT_EAL_SeedPoolCtx *pool = CRYPT_EAL_SeedPoolNew(isCreateNullPool); ASSERT_TRUE(CRYPT_EAL_SeedPoolAddEs(pool, &esPara) == CRYPT_SUCCESS); uint8_t isNpesUsed = true; uint32_t minLen = (uint32_t)minL; uint32_t maxLen = (uint32_t)maxL; uint32_t entropy = (uint32_t)entropyL; EAL_EntropyCtx *ctx = EAL_EntropyNewCtx(pool, isNpesUsed, minLen, maxLen, entropy); ASSERT_TRUE(ctx != NULL); if (isCreateNullPool && !isValid) { ASSERT_TRUE(EAL_EntropyCollection(pool, ctx) == CRYPT_SEED_POOL_NOT_MEET_REQUIREMENT); } else { ASSERT_TRUE(EAL_EntropyCollection(pool, ctx) == CRYPT_SUCCESS); } EXIT: CRYPT_EAL_SeedPoolFree(pool); EAL_EntropyFreeCtx(ctx); CRYPT_EAL_EsFree(es); return; #else (void)isCreateNullPool; (void)isPhysical; (void)minEntropy; (void)minL; (void)maxL; (void)entropyL; (void)isValid; SKIP_TEST(); #endif } /* END_CASE */ /* @ * @test HITLS_SDV_DRBG_GM_FUNC_TC039 * @spec - * @title Complete usage testing from entropy sources. * @precon nan * @prior Level 1 * @auto TRUE @ */ /* BEGIN_CASE */ void HITLS_SDV_DRBG_GM_FUNC_TC039(int isCreateNullPool, int isPhysical, int minEntropy, int minL, int maxL, int entropyL) { #ifdef HITLS_CRYPTO_ENTROPY_SYS CRYPT_EAL_SeedPoolCtx *pool = CRYPT_EAL_SeedPoolNew(isCreateNullPool); CRYPT_EAL_Es *es1 = CRYPT_EAL_EsNew(); ASSERT_TRUE(es1 != NULL); char *mode = "sm3_df"; ASSERT_TRUE(CRYPT_EAL_EsCtrl(es1, CRYPT_ENTROPY_SET_CF, (void *)(intptr_t)mode, strlen(mode)) == CRYPT_SUCCESS); bool healthTest = true; ASSERT_TRUE(CRYPT_EAL_EsCtrl(es1, CRYPT_ENTROPY_ENABLE_TEST, &healthTest, sizeof(bool)) == CRYPT_SUCCESS); ASSERT_TRUE(CRYPT_EAL_EsInit(es1) == CRYPT_SUCCESS); ASSERT_TRUE(CRYPT_EAL_EsCtrl(es1, CRYPT_ENTROPY_GATHER_ENTROPY, NULL, 0) == CRYPT_SUCCESS); CRYPT_EAL_EsPara esPara1 = {isPhysical, (uint32_t)minEntropy, es1, (CRYPT_EAL_EntropyGet)CRYPT_EAL_EsEntropyGet}; CRYPT_EAL_Es *es2 = CRYPT_EAL_EsNew(); ASSERT_TRUE(es2 != NULL); ASSERT_TRUE(CRYPT_EAL_EsCtrl(es2, CRYPT_ENTROPY_SET_CF, (void *)(intptr_t)mode, strlen(mode)) == CRYPT_SUCCESS); ASSERT_TRUE(CRYPT_EAL_EsCtrl(es2, CRYPT_ENTROPY_ENABLE_TEST, &healthTest, sizeof(bool)) == CRYPT_SUCCESS); ASSERT_TRUE(CRYPT_EAL_EsInit(es2) == CRYPT_SUCCESS); ASSERT_TRUE(CRYPT_EAL_EsCtrl(es2, CRYPT_ENTROPY_GATHER_ENTROPY, NULL, 0) == CRYPT_SUCCESS); CRYPT_EAL_EsPara esPara2 = {!isPhysical, (uint32_t)minEntropy, es2, (CRYPT_EAL_EntropyGet)CRYPT_EAL_EsEntropyGet}; CRYPT_EAL_Es *es3 = CRYPT_EAL_EsNew(); ASSERT_TRUE(es3 != NULL); ASSERT_TRUE(CRYPT_EAL_EsCtrl(es3, CRYPT_ENTROPY_SET_CF, (void *)(intptr_t)mode, strlen(mode)) == CRYPT_SUCCESS); ASSERT_TRUE(CRYPT_EAL_EsCtrl(es3, CRYPT_ENTROPY_ENABLE_TEST, &healthTest, sizeof(bool)) == CRYPT_SUCCESS); ASSERT_TRUE(CRYPT_EAL_EsInit(es3) == CRYPT_SUCCESS); if (isCreateNullPool) { for (int i = 0; i < 3; i++) { ASSERT_TRUE(CRYPT_EAL_EsCtrl(es3, CRYPT_ENTROPY_GATHER_ENTROPY, NULL, 0) == CRYPT_SUCCESS); } } CRYPT_EAL_EsPara esPara3 = {isPhysical, (uint32_t)minEntropy, es3, (CRYPT_EAL_EntropyGet)CRYPT_EAL_EsEntropyGet}; ASSERT_TRUE(CRYPT_EAL_SeedPoolAddEs(pool, &esPara1) == CRYPT_SUCCESS); ASSERT_TRUE(CRYPT_EAL_SeedPoolAddEs(pool, &esPara2) == CRYPT_SUCCESS); ASSERT_TRUE(CRYPT_EAL_SeedPoolAddEs(pool, &esPara3) == CRYPT_SUCCESS); EAL_EntropyCtx *ctx = EAL_EntropyNewCtx(pool, true, (uint32_t)minL, (uint32_t)maxL, (uint32_t)entropyL); ASSERT_TRUE(ctx != NULL); ASSERT_TRUE(EAL_EntropyCollection(pool, ctx) == CRYPT_SUCCESS); EXIT: CRYPT_EAL_SeedPoolFree(pool); EAL_EntropyFreeCtx(ctx); CRYPT_EAL_EsFree(es1); CRYPT_EAL_EsFree(es2); CRYPT_EAL_EsFree(es3); return; #else (void)isCreateNullPool; (void)isPhysical; (void)minEntropy; (void)minL; (void)maxL; (void)entropyL; SKIP_TEST(); #endif } /* END_CASE */ /* @ * @test HITLS_SDV_DRBG_GM_FUNC_TC067 * @spec - * @title Complete usage testing from entropy sources. * @precon nan * @prior Level 1 * @auto TRUE @ */ /* BEGIN_CASE */ void HITLS_SDV_DRBG_GM_FUNC_TC067(int isCreateNullPool, int isPhysical, int minEntropy, int minL, int maxL, int entropyL) { #ifdef HITLS_CRYPTO_ENTROPY_SYS CRYPT_EAL_SeedPoolCtx *pool = CRYPT_EAL_SeedPoolNew(isCreateNullPool); CRYPT_EAL_Es *es1 = CRYPT_EAL_EsNew(); ASSERT_TRUE(es1 != NULL); char *mode = "sm3_df"; ASSERT_TRUE(CRYPT_EAL_EsCtrl(es1, CRYPT_ENTROPY_SET_CF, (void *)(intptr_t)mode, strlen(mode)) == CRYPT_SUCCESS); bool healthTest = true; ASSERT_TRUE(CRYPT_EAL_EsCtrl(es1, CRYPT_ENTROPY_ENABLE_TEST, &healthTest, sizeof(bool)) == CRYPT_SUCCESS); ASSERT_TRUE(CRYPT_EAL_EsInit(es1) == CRYPT_SUCCESS); ASSERT_TRUE(CRYPT_EAL_EsCtrl(es1, CRYPT_ENTROPY_GATHER_ENTROPY, NULL, 0) == CRYPT_SUCCESS); CRYPT_EAL_EsPara esPara1 = {isPhysical, (uint32_t)minEntropy, es1, (CRYPT_EAL_EntropyGet)ErrorGetEsEntropy}; CRYPT_EAL_Es *es2 = CRYPT_EAL_EsNew(); ASSERT_TRUE(es2 != NULL); ASSERT_TRUE(CRYPT_EAL_EsCtrl(es2, CRYPT_ENTROPY_SET_CF, (void *)(intptr_t)mode, strlen(mode)) == CRYPT_SUCCESS); ASSERT_TRUE(CRYPT_EAL_EsCtrl(es2, CRYPT_ENTROPY_ENABLE_TEST, &healthTest, sizeof(bool)) == CRYPT_SUCCESS); ASSERT_TRUE(CRYPT_EAL_EsInit(es2) == CRYPT_SUCCESS); ASSERT_TRUE(CRYPT_EAL_EsCtrl(es2, CRYPT_ENTROPY_GATHER_ENTROPY, NULL, 0) == CRYPT_SUCCESS); CRYPT_EAL_EsPara esPara2 = {!isPhysical, (uint32_t)minEntropy, es2, (CRYPT_EAL_EntropyGet)ErrorGetEsEntropy}; CRYPT_EAL_Es *es3 = CRYPT_EAL_EsNew(); ASSERT_TRUE(es3 != NULL); ASSERT_TRUE(CRYPT_EAL_EsCtrl(es3, CRYPT_ENTROPY_SET_CF, (void *)(intptr_t)mode, strlen(mode)) == CRYPT_SUCCESS); ASSERT_TRUE(CRYPT_EAL_EsCtrl(es3, CRYPT_ENTROPY_ENABLE_TEST, &healthTest, sizeof(bool)) == CRYPT_SUCCESS); ASSERT_TRUE(CRYPT_EAL_EsInit(es3) == CRYPT_SUCCESS); CRYPT_EAL_EsPara esPara3 = {isPhysical, (uint32_t)minEntropy, es3, (CRYPT_EAL_EntropyGet)ErrorGetEsEntropy}; ASSERT_TRUE(CRYPT_EAL_SeedPoolAddEs(pool, &esPara1) == CRYPT_SUCCESS); ASSERT_TRUE(CRYPT_EAL_SeedPoolAddEs(pool, &esPara2) == CRYPT_SUCCESS); ASSERT_TRUE(CRYPT_EAL_SeedPoolAddEs(pool, &esPara3) == CRYPT_SUCCESS); EAL_EntropyCtx *ctx = EAL_EntropyNewCtx(pool, true, (uint32_t)minL, (uint32_t)maxL, (uint32_t)entropyL); ASSERT_TRUE(ctx != NULL); if (isCreateNullPool) { ASSERT_TRUE(EAL_EntropyCollection(pool, ctx) != CRYPT_SUCCESS); } else { ASSERT_TRUE(EAL_EntropyCollection(pool, ctx) == CRYPT_SUCCESS); } EXIT: CRYPT_EAL_SeedPoolFree(pool); EAL_EntropyFreeCtx(ctx); CRYPT_EAL_EsFree(es1); CRYPT_EAL_EsFree(es2); CRYPT_EAL_EsFree(es3); return; #else (void)isCreateNullPool; (void)isPhysical; (void)minEntropy; (void)minL; (void)maxL; (void)entropyL; SKIP_TEST(); #endif } /* END_CASE */ /* @ * @test HITLS_SDV_DRBG_GM_FUNC_TC071 * @spec - * @title Complete usage testing from entropy sources. * @precon nan * @prior Level 1 * @auto TRUE @ */ /* BEGIN_CASE */ void HITLS_SDV_DRBG_GM_FUNC_TC071(int isCreateNullPool, int isPhysical, int minEntropy, int minL, int maxL, int entropyL) { #ifdef HITLS_CRYPTO_ENTROPY_SYS CRYPT_EAL_SeedPoolCtx *pool = CRYPT_EAL_SeedPoolNew(isCreateNullPool); CRYPT_EAL_Es *es1 = CRYPT_EAL_EsNew(); ASSERT_TRUE(es1 != NULL); char *mode = "sm3_df"; ASSERT_TRUE(CRYPT_EAL_EsCtrl(es1, CRYPT_ENTROPY_SET_CF, (void *)(intptr_t)mode, strlen(mode)) == CRYPT_SUCCESS); bool healthTest = true; ASSERT_TRUE(CRYPT_EAL_EsCtrl(es1, CRYPT_ENTROPY_ENABLE_TEST, &healthTest, sizeof(bool)) == CRYPT_SUCCESS); ASSERT_TRUE(CRYPT_EAL_EsInit(es1) == CRYPT_SUCCESS); ASSERT_TRUE(CRYPT_EAL_EsCtrl(es1, CRYPT_ENTROPY_GATHER_ENTROPY, NULL, 0) == CRYPT_SUCCESS); CRYPT_EAL_EsPara esPara1 = {!isPhysical, (uint32_t)minEntropy, es1, (CRYPT_EAL_EntropyGet)ErrorGetEsEntropy}; CRYPT_EAL_Es *es2 = CRYPT_EAL_EsNew(); ASSERT_TRUE(es2 != NULL); ASSERT_TRUE(CRYPT_EAL_EsCtrl(es2, CRYPT_ENTROPY_SET_CF, (void *)(intptr_t)mode, strlen(mode)) == CRYPT_SUCCESS); ASSERT_TRUE(CRYPT_EAL_EsCtrl(es2, CRYPT_ENTROPY_ENABLE_TEST, &healthTest, sizeof(bool)) == CRYPT_SUCCESS); ASSERT_TRUE(CRYPT_EAL_EsInit(es2) == CRYPT_SUCCESS); ASSERT_TRUE(CRYPT_EAL_EsCtrl(es2, CRYPT_ENTROPY_GATHER_ENTROPY, NULL, 0) == CRYPT_SUCCESS); CRYPT_EAL_EsPara esPara2 = {isPhysical, (uint32_t)minEntropy, es2, (CRYPT_EAL_EntropyGet)ErrorGetEsEntropy}; CRYPT_EAL_Es *es3 = CRYPT_EAL_EsNew(); ASSERT_TRUE(es3 != NULL); ASSERT_TRUE(CRYPT_EAL_EsCtrl(es3, CRYPT_ENTROPY_SET_CF, (void *)(intptr_t)mode, strlen(mode)) == CRYPT_SUCCESS); ASSERT_TRUE(CRYPT_EAL_EsCtrl(es3, CRYPT_ENTROPY_ENABLE_TEST, &healthTest, sizeof(bool)) == CRYPT_SUCCESS); ASSERT_TRUE(CRYPT_EAL_EsInit(es3) == CRYPT_SUCCESS); if (isCreateNullPool) { for (int i = 0; i < 13; i++) { ASSERT_TRUE(CRYPT_EAL_EsCtrl(es3, CRYPT_ENTROPY_GATHER_ENTROPY, NULL, 0) == CRYPT_SUCCESS); } } CRYPT_EAL_EsPara esPara3 = {isPhysical, (uint32_t)minEntropy, es3, (CRYPT_EAL_EntropyGet)CRYPT_EAL_EsEntropyGet}; ASSERT_TRUE(CRYPT_EAL_SeedPoolAddEs(pool, &esPara1) == CRYPT_SUCCESS); ASSERT_TRUE(CRYPT_EAL_SeedPoolAddEs(pool, &esPara2) == CRYPT_SUCCESS); ASSERT_TRUE(CRYPT_EAL_SeedPoolAddEs(pool, &esPara3) == CRYPT_SUCCESS); EAL_EntropyCtx *ctx = EAL_EntropyNewCtx(pool, true, (uint32_t)minL, (uint32_t)maxL, (uint32_t)entropyL); ASSERT_TRUE(ctx != NULL); ASSERT_TRUE(EAL_EntropyCollection(pool, ctx) == CRYPT_SUCCESS); EXIT: CRYPT_EAL_SeedPoolFree(pool); EAL_EntropyFreeCtx(ctx); CRYPT_EAL_EsFree(es1); CRYPT_EAL_EsFree(es2); CRYPT_EAL_EsFree(es3); return; #else (void)isCreateNullPool; (void)isPhysical; (void)minEntropy; (void)minL; (void)maxL; (void)entropyL; SKIP_TEST(); #endif } /* END_CASE */ /* @ * @test HITLS_SDV_DRBG_GM_FUNC_TC051 * @spec - * @title Complete usage testing from entropy sources. * @precon nan * @prior Level 1 * @auto TRUE @ */ /* BEGIN_CASE */ void HITLS_SDV_DRBG_GM_FUNC_TC051(int isCreateNullPool, int isPhysical, int minEntropy1, int minEntropy2, int minEntropy3, int minL, int maxL, int entropyL) { #ifdef HITLS_CRYPTO_ENTROPY_SYS CRYPT_EAL_SeedPoolCtx *pool = CRYPT_EAL_SeedPoolNew(isCreateNullPool); CRYPT_EAL_Es *es1 = CRYPT_EAL_EsNew(); ASSERT_TRUE(es1 != NULL); char *mode = "sm3_df"; ASSERT_TRUE(CRYPT_EAL_EsCtrl(es1, CRYPT_ENTROPY_SET_CF, (void *)(intptr_t)mode, strlen(mode)) == CRYPT_SUCCESS); bool healthTest = true; ASSERT_TRUE(CRYPT_EAL_EsCtrl(es1, CRYPT_ENTROPY_ENABLE_TEST, &healthTest, sizeof(bool)) == CRYPT_SUCCESS); ASSERT_TRUE(CRYPT_EAL_EsInit(es1) == CRYPT_SUCCESS); if (isCreateNullPool) { for (int i = 0; i < 1; i++) { ASSERT_TRUE(CRYPT_EAL_EsCtrl(es1, CRYPT_ENTROPY_GATHER_ENTROPY, NULL, 0) == CRYPT_SUCCESS); } } CRYPT_EAL_EsPara esPara1 = {!isPhysical, (uint32_t)minEntropy1, es1, (CRYPT_EAL_EntropyGet)ErrorGetEsEntropy}; CRYPT_EAL_Es *es2 = CRYPT_EAL_EsNew(); ASSERT_TRUE(es2 != NULL); ASSERT_TRUE(CRYPT_EAL_EsCtrl(es2, CRYPT_ENTROPY_SET_CF, (void *)(intptr_t)mode, strlen(mode)) == CRYPT_SUCCESS); ASSERT_TRUE(CRYPT_EAL_EsCtrl(es2, CRYPT_ENTROPY_ENABLE_TEST, &healthTest, sizeof(bool)) == CRYPT_SUCCESS); ASSERT_TRUE(CRYPT_EAL_EsInit(es2) == CRYPT_SUCCESS); if (isCreateNullPool) { for (int i = 0; i < 2; i++) { ASSERT_TRUE(CRYPT_EAL_EsCtrl(es2, CRYPT_ENTROPY_GATHER_ENTROPY, NULL, 0) == CRYPT_SUCCESS); } } CRYPT_EAL_EsPara esPara2 = {isPhysical, (uint32_t)minEntropy2, es2, (CRYPT_EAL_EntropyGet)ErrorGetEsEntropy}; CRYPT_EAL_Es *es3 = CRYPT_EAL_EsNew(); ASSERT_TRUE(es3 != NULL); ASSERT_TRUE(CRYPT_EAL_EsCtrl(es3, CRYPT_ENTROPY_SET_CF, (void *)(intptr_t)mode, strlen(mode)) == CRYPT_SUCCESS); ASSERT_TRUE(CRYPT_EAL_EsCtrl(es3, CRYPT_ENTROPY_ENABLE_TEST, &healthTest, sizeof(bool)) == CRYPT_SUCCESS); ASSERT_TRUE(CRYPT_EAL_EsInit(es3) == CRYPT_SUCCESS); if (isCreateNullPool) { for (int i = 0; i < 13; i++) { ASSERT_TRUE(CRYPT_EAL_EsCtrl(es3, CRYPT_ENTROPY_GATHER_ENTROPY, NULL, 0) == CRYPT_SUCCESS); } } CRYPT_EAL_EsPara esPara3 = {isPhysical, (uint32_t)minEntropy3, es3, (CRYPT_EAL_EntropyGet)CRYPT_EAL_EsEntropyGet}; ASSERT_TRUE(CRYPT_EAL_SeedPoolAddEs(pool, &esPara1) == CRYPT_SUCCESS); ASSERT_TRUE(CRYPT_EAL_SeedPoolAddEs(pool, &esPara2) == CRYPT_SUCCESS); ASSERT_TRUE(CRYPT_EAL_SeedPoolAddEs(pool, &esPara3) == CRYPT_SUCCESS); EAL_EntropyCtx *ctx = EAL_EntropyNewCtx(pool, true, (uint32_t)minL, (uint32_t)maxL, (uint32_t)entropyL); ASSERT_TRUE(ctx != NULL); ASSERT_TRUE(EAL_EntropyCollection(pool, ctx) == CRYPT_SUCCESS); EXIT: CRYPT_EAL_SeedPoolFree(pool); EAL_EntropyFreeCtx(ctx); CRYPT_EAL_EsFree(es1); CRYPT_EAL_EsFree(es2); CRYPT_EAL_EsFree(es3); return; #else (void)isCreateNullPool; (void)isPhysical; (void)minEntropy1; (void)minEntropy2; (void)minEntropy3; (void)minL; (void)maxL; (void)entropyL; SKIP_TEST(); #endif } /* END_CASE */ /* @ * @test HITLS_SDV_DRBG_GM_FUNC_TC056 * @spec - * @title Complete usage testing from entropy sources. * @precon nan * @prior Level 1 * @auto TRUE @ */ /* BEGIN_CASE */ void HITLS_SDV_DRBG_GM_FUNC_TC056(int isCreateNullPool, int isPhysical, int minEntropy1, int minEntropy2, int minEntropy3, int minL, int maxL, int entropyL) { #ifdef HITLS_CRYPTO_ENTROPY_SYS CRYPT_EAL_SeedPoolCtx *pool = CRYPT_EAL_SeedPoolNew(isCreateNullPool); CRYPT_EAL_Es *es1 = CRYPT_EAL_EsNew(); ASSERT_TRUE(es1 != NULL); char *mode = "sm3_df"; ASSERT_TRUE(CRYPT_EAL_EsCtrl(es1, CRYPT_ENTROPY_SET_CF, (void *)(intptr_t)mode, strlen(mode)) == CRYPT_SUCCESS); bool healthTest = true; ASSERT_TRUE(CRYPT_EAL_EsCtrl(es1, CRYPT_ENTROPY_ENABLE_TEST, &healthTest, sizeof(bool)) == CRYPT_SUCCESS); ASSERT_TRUE(CRYPT_EAL_EsInit(es1) == CRYPT_SUCCESS); CRYPT_EAL_EsPara esPara1 = {!isPhysical, (uint32_t)minEntropy1, es1, (CRYPT_EAL_EntropyGet)ErrorGetEsEntropy}; CRYPT_EAL_Es *es2 = CRYPT_EAL_EsNew(); ASSERT_TRUE(es2 != NULL); ASSERT_TRUE(CRYPT_EAL_EsCtrl(es2, CRYPT_ENTROPY_SET_CF, (void *)(intptr_t)mode, strlen(mode)) == CRYPT_SUCCESS); ASSERT_TRUE(CRYPT_EAL_EsCtrl(es2, CRYPT_ENTROPY_ENABLE_TEST, &healthTest, sizeof(bool)) == CRYPT_SUCCESS); ASSERT_TRUE(CRYPT_EAL_EsInit(es2) == CRYPT_SUCCESS); CRYPT_EAL_EsPara esPara2 = {isPhysical, (uint32_t)minEntropy2, es2, (CRYPT_EAL_EntropyGet)ErrorGetEsEntropy}; CRYPT_EAL_Es *es3 = CRYPT_EAL_EsNew(); ASSERT_TRUE(es3 != NULL); ASSERT_TRUE(CRYPT_EAL_EsCtrl(es3, CRYPT_ENTROPY_SET_CF, (void *)(intptr_t)mode, strlen(mode)) == CRYPT_SUCCESS); ASSERT_TRUE(CRYPT_EAL_EsCtrl(es3, CRYPT_ENTROPY_ENABLE_TEST, &healthTest, sizeof(bool)) == CRYPT_SUCCESS); ASSERT_TRUE(CRYPT_EAL_EsInit(es3) == CRYPT_SUCCESS); CRYPT_EAL_EsPara esPara3 = {isPhysical, (uint32_t)minEntropy3, es3, (CRYPT_EAL_EntropyGet)ErrorGetEsEntropy}; ASSERT_TRUE(CRYPT_EAL_SeedPoolAddEs(pool, &esPara1) == CRYPT_SUCCESS); ASSERT_TRUE(CRYPT_EAL_SeedPoolAddEs(pool, &esPara2) == CRYPT_SUCCESS); ASSERT_TRUE(CRYPT_EAL_SeedPoolAddEs(pool, &esPara3) == CRYPT_SUCCESS); EAL_EntropyCtx *ctx = EAL_EntropyNewCtx(pool, true, (uint32_t)minL, (uint32_t)maxL, (uint32_t)entropyL); ASSERT_TRUE(ctx != NULL); if (isCreateNullPool && minL != maxL) { ASSERT_TRUE(EAL_EntropyCollection(pool, ctx) == CRYPT_SEED_POOL_NO_ENTROPY_OBTAINED); } else if (isCreateNullPool) { ASSERT_TRUE(EAL_EntropyCollection(pool, ctx) == CRYPT_SEED_POOL_NOT_MEET_REQUIREMENT); } else { ASSERT_TRUE(EAL_EntropyCollection(pool, ctx) == CRYPT_SUCCESS); } EXIT: CRYPT_EAL_SeedPoolFree(pool); EAL_EntropyFreeCtx(ctx); CRYPT_EAL_EsFree(es1); CRYPT_EAL_EsFree(es2); CRYPT_EAL_EsFree(es3); return; #else (void)isCreateNullPool; (void)isPhysical; (void)minEntropy1; (void)minEntropy2; (void)minEntropy3; (void)minL; (void)maxL; (void)entropyL; SKIP_TEST(); #endif } /* END_CASE */
2301_79861745/bench_create
testcode/sdv/testcase/crypto/entropy/test_suite_sdv_entropy.c
C
unknown
66,541
/* * This file is part of the openHiTLS project. * * openHiTLS is licensed under the Mulan PSL v2. * You can use this software according to the terms and conditions of the Mulan PSL v2. * You may obtain a copy of Mulan PSL v2 at: * * http://license.coscl.org.cn/MulanPSL2 * * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, * EITHER EXPRESS 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 <stdio.h> #include <string.h> #include <pthread.h> #include "securec.h" #include "bsl_err.h" #include "bsl_sal.h" #include "crypt_errno.h" #include "crypt_dsa.h" #include "crypt_eal_pkey.h" #include "crypt_eal_rand.h" #include "crypt_bn.h" #include "crypt_util_rand.h" #include "crypt_eal_md.h" #include "crypt_eal_cipher.h" /* END_HEADER */ #define SUCCESS 0 #define ERROR (-1) typedef struct { uint8_t *key; uint8_t *iv; uint8_t *aad; uint8_t *pt; uint8_t *ct; uint8_t *tag; uint32_t keyLen; uint32_t ivLen; uint32_t aadLen; uint32_t ptLen; uint32_t ctLen; uint32_t tagLen; int algId; } ThreadParameter; void MultiThreadTest(void *arg) { ThreadParameter *threadParameter = (ThreadParameter *)arg; uint32_t outLen = threadParameter->ctLen; uint32_t tagLen = threadParameter->tagLen; uint8_t out[threadParameter->ctLen]; uint8_t tag[threadParameter->tagLen]; CRYPT_EAL_CipherCtx *ctx = CRYPT_EAL_CipherNewCtx(threadParameter->algId); ASSERT_TRUE(ctx != NULL); ASSERT_TRUE(CRYPT_EAL_CipherInit(ctx, threadParameter->key, threadParameter->keyLen, threadParameter->iv, threadParameter->ivLen, true) == CRYPT_SUCCESS); ASSERT_TRUE(CRYPT_EAL_CipherCtrl(ctx, CRYPT_CTRL_SET_TAGLEN, &tagLen, sizeof(tagLen)) == CRYPT_SUCCESS); ASSERT_TRUE(CRYPT_EAL_CipherCtrl(ctx, CRYPT_CTRL_SET_AAD, threadParameter->aad, threadParameter->aadLen) == CRYPT_SUCCESS); ASSERT_TRUE(CRYPT_EAL_CipherUpdate(ctx, threadParameter->pt, threadParameter->ptLen, (uint8_t *)out, &outLen) == CRYPT_SUCCESS); ASSERT_TRUE(CRYPT_EAL_CipherCtrl(ctx, CRYPT_CTRL_GET_TAG, (uint8_t *)tag, tagLen) == CRYPT_SUCCESS); ASSERT_COMPARE("Compare Ct", out, threadParameter->ctLen, threadParameter->ct, threadParameter->ctLen); ASSERT_COMPARE("Compare Enc Tag", tag, tagLen, threadParameter->tag, threadParameter->tagLen); CRYPT_EAL_CipherDeinit(ctx); ASSERT_TRUE(CRYPT_EAL_CipherInit(ctx, threadParameter->key, threadParameter->keyLen, threadParameter->iv, threadParameter->ivLen, false) == CRYPT_SUCCESS); ASSERT_TRUE(CRYPT_EAL_CipherCtrl(ctx, CRYPT_CTRL_SET_TAGLEN, &tagLen, sizeof(tagLen)) == CRYPT_SUCCESS); ASSERT_TRUE(CRYPT_EAL_CipherCtrl(ctx, CRYPT_CTRL_SET_AAD, threadParameter->aad, threadParameter->aadLen) == CRYPT_SUCCESS); ASSERT_TRUE(CRYPT_EAL_CipherUpdate(ctx, threadParameter->ct, threadParameter->ctLen, (uint8_t *)out, &outLen) == CRYPT_SUCCESS); ASSERT_TRUE(CRYPT_EAL_CipherCtrl(ctx, CRYPT_CTRL_GET_TAG, (uint8_t *)tag, tagLen) == CRYPT_SUCCESS); ASSERT_COMPARE("Compare Pt", out, threadParameter->ptLen, threadParameter->pt, threadParameter->ptLen); ASSERT_COMPARE("Compare Dec Tag", tag, tagLen, threadParameter->tag, threadParameter->tagLen); EXIT: CRYPT_EAL_CipherFreeCtx(ctx); } /* BEGIN_CASE */ void SDV_CRYPTO_GCM_API_TC001(int id, int keyLen, int ivLen) { uint8_t key[32] = { 0 }; // The maximum length of the key is 32 bytes. uint8_t iv[256] = { 0 }; // The maximum length of the iv is 256 bytes. TestMemInit(); CRYPT_EAL_CipherCtx *ctx = CRYPT_EAL_CipherNewCtx(id); ASSERT_TRUE(ctx != NULL); ASSERT_TRUE(CRYPT_EAL_CipherInit(ctx, (uint8_t *)key, keyLen, (uint8_t *)iv, ivLen, true) == CRYPT_SUCCESS); ASSERT_TRUE(CRYPT_EAL_CipherReinit(ctx, (uint8_t *)iv, 0) != CRYPT_SUCCESS); // Repeat the settings. ASSERT_TRUE(CRYPT_EAL_CipherReinit(ctx, (uint8_t *)iv, ivLen) == CRYPT_SUCCESS); EXIT: CRYPT_EAL_CipherFreeCtx(ctx); } /* END_CASE */ /* BEGIN_CASE */ void SDV_CRYPTO_GCM_API_TC002(int id, int keyLen) { CRYPT_EAL_CipherCtx *ctx = NULL; uint8_t key[32] = { 0 }; // The maximum length of the key is 32 bytes. uint8_t iv[256] = { 0 }; // The maximum length of the iv is 256 bytes. TestMemInit(); ASSERT_TRUE(CRYPT_EAL_CipherNewCtx(99) == NULL); // 99 Indicates an invalid algorithm ID. ctx = CRYPT_EAL_CipherNewCtx(id); ASSERT_TRUE(ctx != NULL); // 256 indicates the IV length. ASSERT_TRUE(CRYPT_EAL_CipherInit(ctx, NULL, keyLen, (uint8_t *)iv, 256, true) != CRYPT_SUCCESS); ASSERT_TRUE(CRYPT_EAL_CipherInit(ctx, (uint8_t *)key, 0, (uint8_t *)iv, 256, true) != CRYPT_SUCCESS); ASSERT_TRUE(CRYPT_EAL_CipherInit(ctx, (uint8_t *)key, keyLen, NULL, 256, true) != CRYPT_SUCCESS); ASSERT_TRUE(CRYPT_EAL_CipherInit(ctx, (uint8_t *)key, keyLen, (uint8_t *)iv, 0, true) != CRYPT_SUCCESS); ASSERT_TRUE(CRYPT_EAL_CipherReinit(NULL, (uint8_t *)iv, 256) != CRYPT_SUCCESS); ASSERT_TRUE(CRYPT_EAL_CipherReinit(ctx, NULL, 256) != CRYPT_SUCCESS); ASSERT_TRUE(CRYPT_EAL_CipherReinit(NULL, (uint8_t *)iv, 0) != CRYPT_SUCCESS); EXIT: CRYPT_EAL_CipherFreeCtx(ctx); } /* END_CASE */ /* BEGIN_CASE */ void SDV_CRYPTO_GCM_API_TC003(int id, int keyLen) { TestMemInit(); uint8_t key[32] = { 0 }; // The maximum length of the key is 32 bytes. uint8_t iv[256] = { 0 }; // The maximum length of the iv is 256 bytes. uint8_t data[256]; CRYPT_EAL_CipherCtx *ctx = CRYPT_EAL_CipherNewCtx(id); ASSERT_TRUE(ctx != NULL); ASSERT_TRUE(CRYPT_EAL_CipherInit(ctx, (uint8_t *)key, keyLen, iv, sizeof(iv), true) == CRYPT_SUCCESS); ASSERT_TRUE(CRYPT_EAL_CipherCtrl(ctx, CRYPT_CTRL_SET_MSGLEN, data, sizeof(data)) != CRYPT_SUCCESS); EXIT: CRYPT_EAL_CipherFreeCtx(ctx); } /* END_CASE */ /* BEGIN_CASE */ void SDV_CRYPTO_GCM_API_TC004(int id, int keyLen) { TestMemInit(); uint8_t key[32] = { 0 }; // The maximum length of the key is 32 bytes. uint8_t iv[13] = { 0 }; uint8_t data[256] = { 0 }; CRYPT_EAL_CipherCtx *ctx = CRYPT_EAL_CipherNewCtx(id); ASSERT_TRUE(ctx != NULL); ASSERT_TRUE(CRYPT_EAL_CipherInit(ctx, (uint8_t *)key, keyLen, iv, sizeof(iv), true) == CRYPT_SUCCESS); ASSERT_TRUE(CRYPT_EAL_CipherCtrl(ctx, CRYPT_CTRL_SET_AAD, NULL, 0) == CRYPT_SUCCESS); ASSERT_TRUE(CRYPT_EAL_CipherCtrl(ctx, CRYPT_CTRL_GET_TAG, data, sizeof(data)) != CRYPT_SUCCESS); EXIT: CRYPT_EAL_CipherFreeCtx(ctx); } /* END_CASE */ /* BEGIN_CASE */ void SDV_CRYPTO_GCM_API_TC005(int id, int keyLen) { TestMemInit(); uint8_t key[32] = { 0 }; // The maximum length of the key is 32 bytes. uint8_t iv[13] = { 0 }; CRYPT_EAL_CipherCtx *ctx = CRYPT_EAL_CipherNewCtx(id); ASSERT_TRUE(ctx != NULL); ASSERT_TRUE(CRYPT_EAL_CipherInit(ctx, (uint8_t *)key, keyLen, iv, sizeof(iv), true) == CRYPT_SUCCESS); ASSERT_TRUE(CRYPT_EAL_CipherCtrl(ctx, CRYPT_CTRL_SET_AAD, NULL, 0) == CRYPT_SUCCESS); ASSERT_EQ(CRYPT_EAL_CipherCtrl(ctx, CRYPT_CTRL_SET_AAD, NULL, 0), CRYPT_EAL_ERR_STATE); EXIT: CRYPT_EAL_CipherFreeCtx(ctx); } /* END_CASE */ /* BEGIN_CASE */ void SDV_CRYPTO_GCM_API_TC006(int id, int keyLen) { TestMemInit(); uint8_t key[32] = { 0 }; // The maximum length of the key is 32 bytes. uint8_t iv[13] = { 0 }; uint8_t data[256] = { 0 }; uint8_t out[256] = { 0 }; uint32_t outLen = sizeof(out); CRYPT_EAL_CipherCtx *ctx = CRYPT_EAL_CipherNewCtx(id); ASSERT_TRUE(ctx != NULL); ASSERT_TRUE(CRYPT_EAL_CipherInit(ctx, (uint8_t *)key, keyLen, iv, sizeof(iv), true) == CRYPT_SUCCESS); ASSERT_TRUE(CRYPT_EAL_CipherUpdate(ctx, data, sizeof(data), out, &outLen) == CRYPT_SUCCESS); EXIT: CRYPT_EAL_CipherFreeCtx(ctx); } /* END_CASE */ /** * @test SDV_CRYPTO_GCM_FUNC_TC001 * @title Test on the same address in plaintext and ciphertext * @precon Registering memory-related functions. * @brief * 1.Create the context ctx. Expected result 1 is obtained. * 2.Call the Init interface. Expected result 2 is obtained. * 3.Call the Ctrl interface, ctx is not NULL, and set tag len. Expected result 3 is obtained. * 4.Call the Ctrl interface, ctx is not NULL, and set aad. Expected result 4 is obtained. * 5.Call the Update interface, ctx is not NULL, and encrypt data. Expected result 5 is obtained. * 6.Compare the ciphertext. Expected result 6 is obtained. * 7.Compare the tag. Expected result 7 is obtained. * 8.Call the Deinit interface and Call the Init interface. Expected result 8 is obtained. * 9.Call the Ctrl interface set tag len. Expected result 9 is obtained. * 10.Call the Ctrl interface set aad. Expected result 10 is obtained. * 11.Call the Update interface to decrypt data. Expected result 11 is obtained. * 12.Compare the plaintext. Expected result 12 is obtained. * 13.Compare the tag. Expected result 13 is obtained. * @expect * 1.The creation is successful and the ctx is not empty. * 2.Success. Return CRYPT_SUCCESS. * 3.Success. Return CRYPT_SUCCESS. * 4.Success. Return CRYPT_SUCCESS. * 5.Success. Return CRYPT_SUCCESS. * 6.Consistent with expected vector. * 7.Consistent with expected vector. * 8.Success, Return CRYPT_SUCCESS * 9.Success, Return CRYPT_SUCCESS * 10.Success, Return CRYPT_SUCCESS * 11.Success, Return CRYPT_SUCCESS * 12.Consistent with expected vector. * 13.Consistent with expected vector. */ /* BEGIN_CASE */ void SDV_CRYPTO_GCM_FUNC_TC001(int algId, Hex *key, Hex *iv, Hex *aad, Hex *pt, Hex *ct, Hex *tag) { TestMemInit(); CRYPT_EAL_CipherCtx *ctx = NULL; uint8_t *outTag = NULL; uint8_t *out = NULL; uint32_t tagLen = tag->len; uint32_t outLen = ct->len; out = (uint8_t *)malloc(outLen * sizeof(uint8_t)); ASSERT_TRUE(out != NULL); outTag = (uint8_t *)malloc(sizeof(uint8_t) * tagLen); ASSERT_TRUE(outTag != NULL); ASSERT_TRUE(memcpy_s(out, outLen, pt->x, pt->len) == EOK); ctx = CRYPT_EAL_CipherNewCtx(algId); ASSERT_TRUE(ctx != NULL); ASSERT_TRUE(CRYPT_EAL_CipherInit(ctx, key->x, key->len, iv->x, iv->len, true) == CRYPT_SUCCESS); ASSERT_TRUE(CRYPT_EAL_CipherCtrl(ctx, CRYPT_CTRL_SET_TAGLEN, &tagLen, sizeof(tagLen)) == CRYPT_SUCCESS); ASSERT_TRUE(CRYPT_EAL_CipherCtrl(ctx, CRYPT_CTRL_SET_AAD, aad->x, aad->len) == CRYPT_SUCCESS); ASSERT_TRUE(CRYPT_EAL_CipherUpdate(ctx, out, pt->len, (uint8_t *)out, &outLen) == CRYPT_SUCCESS); ASSERT_TRUE(CRYPT_EAL_CipherCtrl(ctx, CRYPT_CTRL_GET_TAG, (uint8_t *)outTag, tagLen) == CRYPT_SUCCESS); ASSERT_COMPARE("Compare Ct", out, ct->len, ct->x, ct->len); ASSERT_COMPARE("Compare Enc Tag", outTag, tagLen, tag->x, tag->len); CRYPT_EAL_CipherDeinit(ctx); ASSERT_TRUE(memcpy_s(out, outLen, ct->x, ct->len) == EOK); ASSERT_TRUE(CRYPT_EAL_CipherInit(ctx, key->x, key->len, iv->x, iv->len, false) == CRYPT_SUCCESS); ASSERT_TRUE(CRYPT_EAL_CipherCtrl(ctx, CRYPT_CTRL_SET_TAGLEN, &tagLen, sizeof(tagLen)) == CRYPT_SUCCESS); ASSERT_TRUE(CRYPT_EAL_CipherCtrl(ctx, CRYPT_CTRL_SET_AAD, aad->x, aad->len) == CRYPT_SUCCESS); ASSERT_TRUE(CRYPT_EAL_CipherUpdate(ctx, out, ct->len, (uint8_t *)out, &outLen) == CRYPT_SUCCESS); ASSERT_TRUE(CRYPT_EAL_CipherCtrl(ctx, CRYPT_CTRL_GET_TAG, (uint8_t *)outTag, tagLen) == CRYPT_SUCCESS); ASSERT_COMPARE("Compare Pt", out, pt->len, pt->x, pt->len); ASSERT_COMPARE("Compare Dec Tag", outTag, tagLen, tag->x, tag->len); EXIT: CRYPT_EAL_CipherFreeCtx(ctx); free(out); free(outTag); } /* END_CASE */ /** * @test SDV_CRYPTO_GCM_FUNC_TC002 * @title Multi-thread Test * @precon Registering memory-related functions. * @brief * 1.Start three threads. Expected result 1 is obtained. * 2.Call the eal interface in the thread for encryption. Expected result 2 is obtained. * 3.Call the eal interface in the thread for decryption. Expected result 2 is obtained. * @expect * 1.Success. * 2.The encryption is successful. The ciphertext and tag are the same as the vector. * 3.The decryption is successful. The plaintext and tag are consistent with the vector. */ /* BEGIN_CASE */ void SDV_CRYPTO_GCM_FUNC_TC002(int algId, Hex *key, Hex *iv, Hex *aad, Hex *pt, Hex *ct, Hex *tag) { int ret; TestMemInit(); const uint32_t threadNum = 3; // Number of threads. pthread_t thrd[threadNum]; ThreadParameter arg[3] = { // 3 threads. {.key = key->x, .iv = iv->x, .aad = aad->x, .pt = pt->x, .ct = ct->x, .tag = tag->x, .keyLen = key->len, .ivLen = iv->len, .aadLen = aad->len, .ptLen = pt->len, .ctLen = ct->len, .tagLen = tag->len, .algId = algId}, {.key = key->x, .iv = iv->x, .aad = aad->x, .pt = pt->x, .ct = ct->x, .tag = tag->x, .keyLen = key->len, .ivLen = iv->len, .aadLen = aad->len, .ptLen = pt->len, .ctLen = ct->len, .tagLen = tag->len, .algId = algId}, {.key = key->x, .iv = iv->x, .aad = aad->x, .pt = pt->x, .ct = ct->x, .tag = tag->x, .keyLen = key->len, .ivLen = iv->len, .aadLen = aad->len, .ptLen = pt->len, .ctLen = ct->len, .tagLen = tag->len, .algId = algId}, }; for (uint32_t i = 0; i < threadNum; i++) { ret = pthread_create(&thrd[i], NULL, (void *)MultiThreadTest, &arg[i]); ASSERT_TRUE(ret == 0); } for (uint32_t i = 0; i < threadNum; i++) { pthread_join(thrd[i], NULL); } EXIT: return; } /* END_CASE */
2301_79861745/bench_create
testcode/sdv/testcase/crypto/gcm/test_suite_sdv_gcm.c
C
unknown
13,645
/* * This file is part of the openHiTLS project. * * openHiTLS is licensed under the Mulan PSL v2. * You can use this software according to the terms and conditions of the Mulan PSL v2. * You may obtain a copy of Mulan PSL v2 at: * * http://license.coscl.org.cn/MulanPSL2 * * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, * EITHER EXPRESS 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 <limits.h> #include <pthread.h> #include "securec.h" #include "stub_replace.h" #include "crypt_algid.h" #include "crypt_errno.h" #include "crypt_eal_mac.h" #include "bsl_sal.h" #include "eal_mac_local.h" /* END_HEADER */ #define GMAC_DEFAULT_TAGLEN 16 /* BEGIN_CASE */ void SDV_CRYPTO_EAL_GMAC_FUNC_TC001(int id, Hex *key, Hex *iv, Hex *msg, Hex *mac) { uint32_t outLen = mac->len; uint8_t *output = NULL; CRYPT_EAL_MacCtx *gmacCtx = NULL; ASSERT_TRUE((output = malloc(outLen)) != NULL); TestMemInit(); ASSERT_TRUE((gmacCtx = CRYPT_EAL_MacNewCtx(id)) != NULL); ASSERT_TRUE(CRYPT_EAL_MacInit(gmacCtx, key->x, key->len) == CRYPT_SUCCESS); ASSERT_TRUE(CRYPT_EAL_MacCtrl(gmacCtx, CRYPT_CTRL_SET_IV, iv->x, iv->len) == CRYPT_SUCCESS); ASSERT_TRUE(CRYPT_EAL_MacCtrl(gmacCtx, CRYPT_CTRL_SET_TAGLEN, &outLen, sizeof(uint32_t)) == CRYPT_SUCCESS); ASSERT_TRUE(CRYPT_EAL_MacUpdate(gmacCtx, msg->x, msg->len) == CRYPT_SUCCESS); ASSERT_TRUE(CRYPT_EAL_MacFinal(gmacCtx, output, &outLen) == CRYPT_SUCCESS); ASSERT_TRUE(memcmp(output, mac->x, outLen) == 0); EXIT: free(output); CRYPT_EAL_MacDeinit(gmacCtx); CRYPT_EAL_MacFreeCtx(gmacCtx); } /* END_CASE */ /* BEGIN_CASE */ void SDV_CRYPTO_EAL_GMAC_API_TC001(Hex *key, Hex *iv) { TestMemInit(); CRYPT_EAL_MacCtx *gmacCtx = CRYPT_EAL_MacNewCtx(CRYPT_MAC_GMAC_AES128); ASSERT_TRUE(gmacCtx != NULL); ASSERT_TRUE(CRYPT_EAL_MacInit(gmacCtx, key->x, key->len) == CRYPT_SUCCESS); // ctrl abnormal parameter ASSERT_TRUE(CRYPT_EAL_MacCtrl(NULL, CRYPT_CTRL_SET_IV, iv->x, iv->len) == CRYPT_NULL_INPUT); // ctrl abnormal parameter ASSERT_TRUE( CRYPT_EAL_MacCtrl(gmacCtx, CRYPT_CTRL_SET_AAD, iv->x, iv->len) == CRYPT_EAL_MAC_CTRL_TYPE_ERROR); // ctrl abnormal parameter ASSERT_TRUE(CRYPT_EAL_MacCtrl(gmacCtx, CRYPT_CTRL_SET_IV, NULL, iv->len) == CRYPT_NULL_INPUT); // ctrl abnormal parameter ASSERT_TRUE(CRYPT_EAL_MacCtrl(gmacCtx, CRYPT_CTRL_SET_IV, iv->x, 0) == CRYPT_NULL_INPUT); CRYPT_EAL_MacDeinit(gmacCtx); ASSERT_TRUE(CRYPT_EAL_MacCtrl(gmacCtx, CRYPT_CTRL_SET_IV, iv->x, iv->len) == CRYPT_EAL_ERR_STATE); EXIT: CRYPT_EAL_MacDeinit(gmacCtx); CRYPT_EAL_MacFreeCtx(gmacCtx); } /* END_CASE */ /* BEGIN_CASE */ void SDV_CRYPTO_EAL_GMAC_API_TC002(Hex *key, Hex *iv, Hex *msg, Hex *mac) { TestMemInit(); unsigned char output[GMAC_DEFAULT_TAGLEN]; uint32_t outLen = GMAC_DEFAULT_TAGLEN; CRYPT_EAL_MacCtx *gmacCtx = CRYPT_EAL_MacNewCtx(CRYPT_MAC_GMAC_AES128); ASSERT_TRUE(gmacCtx != NULL); // GMAC init abnormal parameter ASSERT_TRUE(CRYPT_EAL_MacInit(gmacCtx, key->x, 0) == CRYPT_AES_ERR_KEYLEN); ASSERT_TRUE(CRYPT_EAL_MacInit(gmacCtx, key->x, key->len) == CRYPT_SUCCESS); // GMAC Ctrl abnormal parameter ASSERT_TRUE(CRYPT_EAL_MacCtrl(gmacCtx, CRYPT_CTRL_SET_IV, iv->x, 0) == CRYPT_NULL_INPUT); ASSERT_TRUE(CRYPT_EAL_MacCtrl(gmacCtx, CRYPT_CTRL_SET_IV, iv->x, iv->len) == CRYPT_SUCCESS); // GMAC update abnormal parameter ASSERT_TRUE(CRYPT_EAL_MacUpdate(gmacCtx, NULL, msg->len) == CRYPT_NULL_INPUT); ASSERT_TRUE(CRYPT_EAL_MacUpdate(gmacCtx, msg->x, msg->len) == CRYPT_SUCCESS); // GMAC final abnormal parameter outLen = 0; ASSERT_TRUE(CRYPT_EAL_MacFinal(gmacCtx, output, &outLen) == CRYPT_MODES_TAGLEN_ERROR); outLen = GMAC_DEFAULT_TAGLEN; ASSERT_TRUE(CRYPT_EAL_MacFinal(gmacCtx, output, &outLen) == CRYPT_SUCCESS); ASSERT_TRUE(memcmp(output, mac->x, outLen) == 0); EXIT: CRYPT_EAL_MacDeinit(gmacCtx); CRYPT_EAL_MacFreeCtx(gmacCtx); } /* END_CASE */ /** * @test SDV_CRYPT_EAL_GMAC_STATE_FUNC_TC001 * @title Gmac state test * @precon nan */ /* BEGIN_CASE */ void SDV_CRYPT_EAL_GMAC_STATE_FUNC_TC001(int algId, Hex *key, Hex *iv, Hex *msg, Hex *mac) { uint32_t outLen = mac->len; unsigned char output[outLen]; CRYPT_EAL_MacCtx *gmacCtx = NULL; TestMemInit(); // ctrl, update, final and deinit after new. ASSERT_TRUE((gmacCtx = CRYPT_EAL_MacNewCtx(algId)) != NULL); ASSERT_EQ(CRYPT_EAL_MacCtrl(gmacCtx, CRYPT_CTRL_SET_IV, iv->x, iv->len), CRYPT_EAL_ERR_STATE); ASSERT_EQ(CRYPT_EAL_MacUpdate(gmacCtx, msg->x, msg->len), CRYPT_EAL_ERR_STATE); ASSERT_EQ(CRYPT_EAL_MacFinal(gmacCtx, output, &outLen), CRYPT_EAL_ERR_STATE); ASSERT_EQ(CRYPT_EAL_MacReinit(gmacCtx), CRYPT_EAL_ERR_STATE); CRYPT_EAL_MacDeinit(gmacCtx); // init after new, repeat the init ASSERT_EQ(CRYPT_EAL_MacInit(gmacCtx, key->x, key->len), CRYPT_SUCCESS); ASSERT_EQ(CRYPT_EAL_MacInit(gmacCtx, key->x, key->len), CRYPT_SUCCESS); // reinit after init ASSERT_EQ(CRYPT_EAL_MacReinit(gmacCtx), CRYPT_EAL_ALG_NOT_SUPPORT); // final after init ASSERT_EQ(CRYPT_EAL_MacFinal(gmacCtx, output, &outLen), CRYPT_MODES_TAGLEN_ERROR); // update after init, repeat the update ASSERT_EQ(CRYPT_EAL_MacUpdate(gmacCtx, msg->x, msg->len), CRYPT_SUCCESS); if (msg->len == 0) { ASSERT_EQ(CRYPT_EAL_MacUpdate(gmacCtx, msg->x, msg->len), CRYPT_SUCCESS); } else { ASSERT_EQ(CRYPT_EAL_MacUpdate(gmacCtx, msg->x, msg->len), CRYPT_MODES_AAD_REPEAT_SET_ERROR); } // ctrl after update ASSERT_EQ(CRYPT_EAL_MacCtrl(gmacCtx, CRYPT_CTRL_SET_IV, iv->x, iv->len), CRYPT_EAL_ERR_STATE); // final after update ASSERT_EQ(CRYPT_EAL_MacFinal(gmacCtx, output, &outLen), CRYPT_MODES_TAGLEN_ERROR); // init ASSERT_EQ(CRYPT_EAL_MacInit(gmacCtx, key->x, key->len), CRYPT_SUCCESS); // ctrl after init, repeat to taglen ASSERT_EQ(CRYPT_EAL_MacCtrl(gmacCtx, CRYPT_CTRL_SET_TAGLEN, &outLen, sizeof(uint32_t)), CRYPT_SUCCESS); ASSERT_EQ(CRYPT_EAL_MacCtrl(gmacCtx, CRYPT_CTRL_SET_TAGLEN, &outLen, sizeof(uint32_t)), CRYPT_SUCCESS); // final after ctrl,repeat the final ASSERT_EQ(CRYPT_EAL_MacFinal(gmacCtx, output, &outLen), CRYPT_SUCCESS); ASSERT_EQ(CRYPT_EAL_MacFinal(gmacCtx, output, &outLen), CRYPT_EAL_ERR_STATE); // ctrl after final ASSERT_EQ(CRYPT_EAL_MacCtrl(gmacCtx, CRYPT_CTRL_SET_IV, iv->x, iv->len), CRYPT_EAL_ERR_STATE); // update after final ASSERT_EQ(CRYPT_EAL_MacUpdate(gmacCtx, msg->x, msg->len), CRYPT_EAL_ERR_STATE); EXIT: CRYPT_EAL_MacDeinit(gmacCtx); CRYPT_EAL_MacFreeCtx(gmacCtx); } /* END_CASE */ /** * @test SDV_CRYPT_EAL_GMAC_SAMEADDR_FUNC_TC001 * @title GMAC in/out same address test * @precon nan * @brief * 1.Use the EAL-layer interface to perform GMAC calculation. The input and output addresses are the same. * Expected result 1 is displayed. * @expect * 1. success */ /* BEGIN_CASE */ void SDV_CRYPT_EAL_GMAC_SAMEADDR_FUNC_TC001(int algId, Hex *key, Hex *iv, Hex *data, Hex *mac) { uint32_t outLen = data->len > mac->len ? data->len : mac->len; uint32_t tagLen = mac->len; uint8_t *out = NULL; CRYPT_EAL_MacCtx *ctx = NULL; ASSERT_TRUE((out = malloc(outLen)) != NULL); ASSERT_EQ(memcpy_s(out, outLen, data->x, data->len), 0); ASSERT_TRUE((ctx = CRYPT_EAL_MacNewCtx(algId)) != NULL); ASSERT_EQ(CRYPT_EAL_MacInit(ctx, key->x, key->len), CRYPT_SUCCESS); ASSERT_EQ(CRYPT_EAL_MacCtrl(ctx, CRYPT_CTRL_SET_IV, iv->x, iv->len), CRYPT_SUCCESS); ASSERT_EQ(CRYPT_EAL_MacCtrl(ctx, CRYPT_CTRL_SET_TAGLEN, &tagLen, sizeof(uint32_t)), CRYPT_SUCCESS); ASSERT_EQ(CRYPT_EAL_MacUpdate(ctx, out, data->len), CRYPT_SUCCESS); ASSERT_EQ(CRYPT_EAL_MacFinal(ctx, out, &tagLen), CRYPT_SUCCESS); ASSERT_COMPARE("gmac result cmp", out, tagLen, mac->x, mac->len); EXIT: free(out); CRYPT_EAL_MacFreeCtx(ctx); } /* END_CASE */ /** * @test SDV_CRYPT_EAL_GMAC_ADDR_NOT_ALIGN_FUNC_TC001 * @title GMAC non-address alignment test * @precon nan * @brief * 1.Use the EAL layer interface to perform GMAC calculation. All buffer addresses are not aligned. * Expected result 1 is obtained. * @expect * 1.success. */ /* BEGIN_CASE */ void SDV_CRYPT_EAL_GMAC_ADDR_NOT_ALIGN_FUNC_TC001(int algId, Hex *key, Hex *iv, Hex *data, Hex *mac) { uint32_t outLen = data->len > mac->len ? data->len : mac->len; uint8_t *out = NULL; uint32_t tagLen = mac->len; CRYPT_EAL_MacCtx *ctx = NULL; uint8_t *keyTmp = NULL; uint8_t *ivTmp = NULL; uint8_t *dataTmp = NULL; ASSERT_TRUE((out = malloc(outLen)) != NULL); ASSERT_TRUE((keyTmp = malloc(key->len + 1)) != NULL); ASSERT_TRUE((ivTmp = malloc(iv->len + 1)) != NULL); ASSERT_TRUE((dataTmp = malloc(data->len + 1)) != NULL); uint8_t *pKey = keyTmp + 1; uint8_t *pIv = ivTmp + 1; uint8_t *pData = dataTmp + 1; ASSERT_TRUE(memcpy_s(pKey, key->len, key->x, key->len) == 0); ASSERT_TRUE(memcpy_s(pIv, iv->len, iv->x, iv->len) == 0); ASSERT_TRUE(memcpy_s(pData, data->len, data->x, data->len) == 0); TestMemInit(); ASSERT_TRUE((ctx = CRYPT_EAL_MacNewCtx(algId)) != NULL); ASSERT_EQ(CRYPT_EAL_MacInit(ctx, pKey, key->len), CRYPT_SUCCESS); ASSERT_EQ(CRYPT_EAL_MacCtrl(ctx, CRYPT_CTRL_SET_IV, pIv, iv->len), CRYPT_SUCCESS); ASSERT_EQ(CRYPT_EAL_MacCtrl(ctx, CRYPT_CTRL_SET_TAGLEN, &tagLen, sizeof(uint32_t)), CRYPT_SUCCESS); ASSERT_EQ(CRYPT_EAL_MacUpdate(ctx, pData, data->len), CRYPT_SUCCESS); ASSERT_EQ(CRYPT_EAL_MacFinal(ctx, out, &tagLen), CRYPT_SUCCESS); ASSERT_COMPARE("mac result cmp", out, tagLen, mac->x, mac->len); EXIT: free(out); free(keyTmp); free(ivTmp); free(dataTmp); CRYPT_EAL_MacFreeCtx(ctx); } /* END_CASE */
2301_79861745/bench_create
testcode/sdv/testcase/crypto/gmac/test_suite_sdv_eal_gmac.c
C
unknown
10,016
/* * This file is part of the openHiTLS project. * * openHiTLS is licensed under the Mulan PSL v2. * You can use this software according to the terms and conditions of the Mulan PSL v2. * You may obtain a copy of Mulan PSL v2 at: * * http://license.coscl.org.cn/MulanPSL2 * * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, * EITHER EXPRESS 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 "crypt_eal_kdf.h" #include "crypt_errno.h" #include "bsl_sal.h" #include "bsl_params.h" #include "crypt_params_key.h" /* END_HEADER */ #define DATA_LEN (64) static uint32_t GetMaxKeyLen(int algId) { switch (algId) { case CRYPT_MAC_HMAC_SHA1: return 5100; case CRYPT_MAC_HMAC_SHA224: return 7140; case CRYPT_MAC_HMAC_SHA256: return 8160; case CRYPT_MAC_HMAC_SHA384: return 12240; case CRYPT_MAC_HMAC_SHA512: return 16320; default: return 0; } } /** * @test SDV_CRYPT_EAL_KDF_HKDF_API_TC001 * @title hkdf api test. */ /* BEGIN_CASE */ void SDV_CRYPT_EAL_KDF_HKDF_API_TC001(int algId) { TestMemInit(); uint32_t keyLen = DATA_LEN; uint8_t key[DATA_LEN]; uint32_t saltLen = DATA_LEN; uint8_t salt[DATA_LEN]; uint32_t infoLen = DATA_LEN; uint8_t info[DATA_LEN]; uint32_t outLen = DATA_LEN; uint8_t out[DATA_LEN]; CRYPT_EAL_KdfCTX *ctx = CRYPT_EAL_KdfNewCtx(CRYPT_KDF_HKDF); ASSERT_TRUE(ctx != NULL); CRYPT_HKDF_MODE mode = CRYPT_KDF_HKDF_MODE_FULL; BSL_Param params[7] = {{0}, {0}, {0}, {0}, {0}, {0}, BSL_PARAM_END}; ASSERT_EQ(BSL_PARAM_InitValue(&params[0], CRYPT_PARAM_KDF_MAC_ID, BSL_PARAM_TYPE_UINT32, &algId, sizeof(algId)), CRYPT_SUCCESS); ASSERT_EQ(BSL_PARAM_InitValue(&params[1], CRYPT_PARAM_KDF_MODE, BSL_PARAM_TYPE_UINT32, &mode, sizeof(mode)), CRYPT_SUCCESS); ASSERT_EQ(BSL_PARAM_InitValue(&params[2], CRYPT_PARAM_KDF_KEY, BSL_PARAM_TYPE_OCTETS, key, keyLen), CRYPT_SUCCESS); ASSERT_EQ(BSL_PARAM_InitValue(&params[3], CRYPT_PARAM_KDF_SALT, BSL_PARAM_TYPE_OCTETS, salt, saltLen), CRYPT_SUCCESS); ASSERT_EQ(BSL_PARAM_InitValue(&params[4], CRYPT_PARAM_KDF_INFO, BSL_PARAM_TYPE_OCTETS, info, infoLen), CRYPT_SUCCESS); ASSERT_EQ(BSL_PARAM_InitValue(&params[5], CRYPT_PARAM_KDF_PRK, BSL_PARAM_TYPE_OCTETS, key, keyLen), CRYPT_SUCCESS); ASSERT_EQ(CRYPT_EAL_KdfSetParam(ctx, params), CRYPT_SUCCESS); ASSERT_EQ(CRYPT_EAL_KdfDerive(ctx, out, outLen), CRYPT_SUCCESS); ASSERT_EQ(BSL_PARAM_InitValue(&params[2], CRYPT_PARAM_KDF_KEY, BSL_PARAM_TYPE_OCTETS, NULL, 0), CRYPT_SUCCESS); ASSERT_EQ(CRYPT_EAL_KdfSetParam(ctx, params), CRYPT_SUCCESS); ASSERT_EQ(CRYPT_EAL_KdfDerive(ctx, out, outLen), CRYPT_SUCCESS); ASSERT_EQ(BSL_PARAM_InitValue(&params[3], CRYPT_PARAM_KDF_SALT, BSL_PARAM_TYPE_OCTETS, NULL, 0), CRYPT_SUCCESS); ASSERT_EQ(CRYPT_EAL_KdfSetParam(ctx, params), CRYPT_SUCCESS); ASSERT_EQ(CRYPT_EAL_KdfDerive(ctx, out, outLen), CRYPT_SUCCESS); ASSERT_EQ(BSL_PARAM_InitValue(&params[4], CRYPT_PARAM_KDF_INFO, BSL_PARAM_TYPE_OCTETS, NULL, 0), CRYPT_SUCCESS); ASSERT_EQ(CRYPT_EAL_KdfSetParam(ctx, params), CRYPT_SUCCESS); ASSERT_EQ(CRYPT_EAL_KdfDerive(ctx, out, outLen), CRYPT_SUCCESS); ASSERT_EQ(BSL_PARAM_InitValue(&params[5], CRYPT_PARAM_KDF_PRK, BSL_PARAM_TYPE_OCTETS, NULL, 0), CRYPT_SUCCESS); ASSERT_EQ(CRYPT_EAL_KdfSetParam(ctx, params), CRYPT_SUCCESS); ASSERT_EQ(CRYPT_EAL_KdfDerive(ctx, out, outLen), CRYPT_SUCCESS); ASSERT_EQ(CRYPT_EAL_KdfSetParam(ctx, NULL), CRYPT_NULL_INPUT); ASSERT_EQ(CRYPT_EAL_KdfDerive(ctx, NULL, outLen), CRYPT_NULL_INPUT); ASSERT_EQ(CRYPT_EAL_KdfDerive(ctx, out, 0), CRYPT_NULL_INPUT); outLen = GetMaxKeyLen(algId) + 1; ASSERT_EQ(CRYPT_EAL_KdfDerive(ctx, out, outLen), CRYPT_HKDF_DKLEN_OVERFLOW); outLen = DATA_LEN; CRYPT_MAC_AlgId macAlgIdFailed = CRYPT_MAC_MAX; ASSERT_EQ(BSL_PARAM_InitValue(&params[0], CRYPT_PARAM_KDF_MAC_ID, BSL_PARAM_TYPE_UINT32, &macAlgIdFailed, sizeof(macAlgIdFailed)), CRYPT_SUCCESS); ASSERT_EQ(CRYPT_EAL_KdfSetParam(ctx, params), CRYPT_HKDF_PARAM_ERROR); ASSERT_EQ(CRYPT_EAL_KdfDeInitCtx(ctx), CRYPT_SUCCESS); EXIT: CRYPT_EAL_KdfFreeCtx(ctx); } /* END_CASE */ /** * @test SDV_CRYPT_EAL_KDF_HKDF_FUN_TC001 * @title Perform the vector test to check whether the calculation result is consistent with the standard output. * @precon nan * @brief * 1.Call CRYPT_EAL_KdfCTX functions get output, expected result 1. * 2.Compare the result to the expected value, expected result 2. * @expect * 1.Successful. * 2.The results are as expected. */ /* BEGIN_CASE */ void SDV_CRYPT_EAL_KDF_HKDF_FUN_TC001(int algId, Hex *key, Hex *salt, Hex *info, Hex *result) { if (IsHmacAlgDisabled(algId)) { SKIP_TEST(); } TestMemInit(); uint32_t outLen = result->len; uint8_t *out = malloc(outLen * sizeof(uint8_t)); ASSERT_TRUE(out != NULL); CRYPT_EAL_KdfCTX *ctx = CRYPT_EAL_KdfNewCtx(CRYPT_KDF_HKDF); ASSERT_TRUE(ctx != NULL); CRYPT_HKDF_MODE mode = CRYPT_KDF_HKDF_MODE_FULL; BSL_Param params[6] = {{0}, {0}, {0}, {0}, {0}, BSL_PARAM_END}; ASSERT_EQ(BSL_PARAM_InitValue(&params[0], CRYPT_PARAM_KDF_MAC_ID, BSL_PARAM_TYPE_UINT32, &algId, sizeof(algId)), CRYPT_SUCCESS); ASSERT_EQ(BSL_PARAM_InitValue(&params[1], CRYPT_PARAM_KDF_MODE, BSL_PARAM_TYPE_UINT32, &mode, sizeof(mode)), CRYPT_SUCCESS); ASSERT_EQ(BSL_PARAM_InitValue(&params[2], CRYPT_PARAM_KDF_KEY, BSL_PARAM_TYPE_OCTETS, key->x, key->len), CRYPT_SUCCESS); ASSERT_EQ(BSL_PARAM_InitValue(&params[3], CRYPT_PARAM_KDF_SALT, BSL_PARAM_TYPE_OCTETS, salt->x, salt->len), CRYPT_SUCCESS); ASSERT_EQ(BSL_PARAM_InitValue(&params[4], CRYPT_PARAM_KDF_INFO, BSL_PARAM_TYPE_OCTETS, info->x, info->len), CRYPT_SUCCESS); ASSERT_EQ(CRYPT_EAL_KdfSetParam(ctx, params), CRYPT_SUCCESS); ASSERT_EQ(CRYPT_EAL_KdfDerive(ctx, out, outLen), CRYPT_SUCCESS); ASSERT_COMPARE("result cmp", out, outLen, result->x, result->len); EXIT: if (out != NULL) { free(out); } CRYPT_EAL_KdfFreeCtx(ctx); } /* END_CASE */ /** * @test SDV_CRYPTO_HKDF_DEFAULT_PROVIDER_FUNC_TC001 * @title Default provider testing * @precon nan * @brief * Load the default provider and use the test vector to test its correctness */ /* BEGIN_CASE */ void SDV_CRYPTO_HKDF_DEFAULT_PROVIDER_FUNC_TC001(int algId, Hex *key, Hex *salt, Hex *info, Hex *result) { if (IsHmacAlgDisabled(algId)) { SKIP_TEST(); } TestMemInit(); uint32_t outLen = result->len; uint8_t *out = malloc(outLen * sizeof(uint8_t)); ASSERT_TRUE(out != NULL); CRYPT_EAL_KdfCTX *ctx = NULL; #ifdef HITLS_CRYPTO_PROVIDER ctx = CRYPT_EAL_ProviderKdfNewCtx(NULL, CRYPT_KDF_HKDF, "provider=default"); #else ctx = CRYPT_EAL_KdfNewCtx(CRYPT_KDF_HKDF); #endif ASSERT_TRUE(ctx != NULL); CRYPT_HKDF_MODE mode = CRYPT_KDF_HKDF_MODE_FULL; BSL_Param params[6] = {{0}, {0}, {0}, {0}, {0}, BSL_PARAM_END}; ASSERT_EQ(BSL_PARAM_InitValue(&params[0], CRYPT_PARAM_KDF_MAC_ID, BSL_PARAM_TYPE_UINT32, &algId, sizeof(algId)), CRYPT_SUCCESS); ASSERT_EQ(BSL_PARAM_InitValue(&params[1], CRYPT_PARAM_KDF_MODE, BSL_PARAM_TYPE_UINT32, &mode, sizeof(mode)), CRYPT_SUCCESS); ASSERT_EQ(BSL_PARAM_InitValue(&params[2], CRYPT_PARAM_KDF_KEY, BSL_PARAM_TYPE_OCTETS, key->x, key->len), CRYPT_SUCCESS); ASSERT_EQ(BSL_PARAM_InitValue(&params[3], CRYPT_PARAM_KDF_SALT, BSL_PARAM_TYPE_OCTETS, salt->x, salt->len), CRYPT_SUCCESS); ASSERT_EQ(BSL_PARAM_InitValue(&params[4], CRYPT_PARAM_KDF_INFO, BSL_PARAM_TYPE_OCTETS, info->x, info->len), CRYPT_SUCCESS); ASSERT_EQ(CRYPT_EAL_KdfSetParam(ctx, params), CRYPT_SUCCESS); ASSERT_EQ(CRYPT_EAL_KdfDerive(ctx, out, outLen), CRYPT_SUCCESS); ASSERT_COMPARE("result cmp", out, outLen, result->x, result->len); EXIT: if (out != NULL) { free(out); } CRYPT_EAL_KdfFreeCtx(ctx); } /* END_CASE */ /* BEGIN_CASE */ void SDV_CRYPTO_HKDF_BSL_PARAM_MAKER_TC001(int algId, Hex *key, Hex *salt, Hex *info, Hex *result) { TestMemInit(); uint32_t outLen = result->len; uint8_t *out = malloc(outLen * sizeof(uint8_t)); ASSERT_TRUE(out != NULL); CRYPT_EAL_KdfCTX *ctx = CRYPT_EAL_KdfNewCtx(CRYPT_KDF_HKDF); ASSERT_TRUE(ctx != NULL); CRYPT_HKDF_MODE mode = CRYPT_KDF_HKDF_MODE_FULL; BSL_ParamMaker *maker = BSL_PARAM_MAKER_New(); ASSERT_EQ(BSL_PARAM_MAKER_PushValue(maker, CRYPT_PARAM_KDF_MAC_ID, BSL_PARAM_TYPE_UINT32, &algId, sizeof(algId)), BSL_SUCCESS); ASSERT_EQ(BSL_PARAM_MAKER_PushValue(maker, CRYPT_PARAM_KDF_MODE, BSL_PARAM_TYPE_UINT32, &mode, sizeof(mode)), BSL_SUCCESS); ASSERT_EQ(BSL_PARAM_MAKER_PushValue(maker, CRYPT_PARAM_KDF_KEY, BSL_PARAM_TYPE_OCTETS, key->x, key->len), BSL_SUCCESS); ASSERT_EQ(BSL_PARAM_MAKER_PushValue(maker, CRYPT_PARAM_KDF_SALT, BSL_PARAM_TYPE_OCTETS, salt->x, salt->len), BSL_SUCCESS); ASSERT_EQ(BSL_PARAM_MAKER_PushValue(maker, CRYPT_PARAM_KDF_INFO, BSL_PARAM_TYPE_OCTETS, info->x, info->len), BSL_SUCCESS); BSL_Param *params = BSL_PARAM_MAKER_ToParam(maker); ASSERT_EQ(CRYPT_EAL_KdfSetParam(ctx, params), BSL_SUCCESS); ASSERT_EQ(CRYPT_EAL_KdfDerive(ctx, out, outLen), BSL_SUCCESS); ASSERT_COMPARE("result cmp", out, outLen, result->x, result->len); EXIT: if (out != NULL) { free(out); } CRYPT_EAL_KdfFreeCtx(ctx); BSL_PARAM_MAKER_Free(maker); BSL_PARAM_Free(params); } /* END_CASE */ /* BEGIN_CASE */ void SDV_CRYPTO_HKDF_BSL_PARAM_MAKER_TC002(int algId, Hex *key, Hex *salt, Hex *info, Hex *result) { TestMemInit(); uint32_t outLen = result->len; uint8_t *out = malloc(outLen * sizeof(uint8_t)); ASSERT_TRUE(out != NULL); CRYPT_EAL_KdfCTX *ctx = CRYPT_EAL_KdfNewCtx(CRYPT_KDF_HKDF); ASSERT_TRUE(ctx != NULL); CRYPT_HKDF_MODE mode = CRYPT_KDF_HKDF_MODE_FULL; BSL_ParamMaker *maker = BSL_PARAM_MAKER_New(); ASSERT_EQ(BSL_PARAM_MAKER_PushValue(maker, CRYPT_PARAM_KDF_MAC_ID, BSL_PARAM_TYPE_UINT32, &algId, sizeof(algId)), BSL_SUCCESS); ASSERT_EQ(BSL_PARAM_MAKER_PushValue(maker, CRYPT_PARAM_KDF_MODE, BSL_PARAM_TYPE_UINT32, &mode, sizeof(mode)), BSL_SUCCESS); ASSERT_EQ(BSL_PARAM_MAKER_DeepPushValue(maker, CRYPT_PARAM_KDF_KEY, BSL_PARAM_TYPE_OCTETS, key->x, key->len), BSL_SUCCESS); ASSERT_EQ(BSL_PARAM_MAKER_DeepPushValue(maker, CRYPT_PARAM_KDF_SALT, BSL_PARAM_TYPE_OCTETS, salt->x, salt->len), BSL_SUCCESS); ASSERT_EQ(BSL_PARAM_MAKER_DeepPushValue(maker, CRYPT_PARAM_KDF_INFO, BSL_PARAM_TYPE_OCTETS, info->x, info->len), BSL_SUCCESS); BSL_Param *params = BSL_PARAM_MAKER_ToParam(maker); ASSERT_EQ(CRYPT_EAL_KdfSetParam(ctx, params), BSL_SUCCESS); ASSERT_EQ(CRYPT_EAL_KdfDerive(ctx, out, outLen), BSL_SUCCESS); ASSERT_COMPARE("result cmp", out, outLen, result->x, result->len); EXIT: if (out != NULL) { free(out); } CRYPT_EAL_KdfFreeCtx(ctx); BSL_PARAM_MAKER_Free(maker); BSL_PARAM_Free(params); } /* END_CASE */
2301_79861745/bench_create
testcode/sdv/testcase/crypto/hkdf/test_suite_sdv_eal_kdf_hkdf.c
C
unknown
11,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. */ #include <pthread.h> #include "securec.h" #include "crypt_eal_mac.h" #include "crypt_errno.h" #include "bsl_sal.h" #include "crypt_sha1.h" #include "crypt_sha2.h" #include "crypt_sha3.h" #include "crypt_sm3.h" #include "crypt_md5.h" #define TEST_FAIL (-1) #define TEST_SUCCESS (0) #define DATA_MAX_LEN (65538) uint32_t GetMacLen(int algId) { switch (algId) { #ifdef HITLS_CRYPTO_MD5 case CRYPT_MAC_HMAC_MD5: return CRYPT_MD5_DIGESTSIZE; #endif #ifdef HITLS_CRYPTO_SHA1 case CRYPT_MAC_HMAC_SHA1: return CRYPT_SHA1_DIGESTSIZE; #endif #ifdef HITLS_CRYPTO_SHA224 case CRYPT_MAC_HMAC_SHA224: return CRYPT_SHA2_224_DIGESTSIZE; #endif #ifdef HITLS_CRYPTO_SHA256 case CRYPT_MAC_HMAC_SHA256: return CRYPT_SHA2_256_DIGESTSIZE; #endif #ifdef HITLS_CRYPTO_SHA384 case CRYPT_MAC_HMAC_SHA384: return CRYPT_SHA2_384_DIGESTSIZE; #endif #ifdef HITLS_CRYPTO_SHA512 case CRYPT_MAC_HMAC_SHA512: return CRYPT_SHA2_512_DIGESTSIZE; #endif #ifdef HITLS_CRYPTO_SM3 case CRYPT_MAC_HMAC_SM3: return CRYPT_SM3_DIGESTSIZE; #endif #ifdef HITLS_CRYPTO_SHA3 case CRYPT_MAC_HMAC_SHA3_224: return CRYPT_SHA3_224_DIGESTSIZE; case CRYPT_MAC_HMAC_SHA3_256: return CRYPT_SHA3_256_DIGESTSIZE; case CRYPT_MAC_HMAC_SHA3_384: return CRYPT_SHA3_384_DIGESTSIZE; case CRYPT_MAC_HMAC_SHA3_512: return CRYPT_SHA3_512_DIGESTSIZE; #endif default: return 0; } } typedef struct { uint8_t *data; uint8_t *mac; uint8_t *key; uint32_t dataLen; uint32_t macLen; uint32_t keyLen; int algId; } ThreadParameter; void MultiThreadTest(void *arg) { ThreadParameter *threadParameter = (ThreadParameter *)arg; uint32_t outLen = GetMacLen(threadParameter->algId); uint8_t out[outLen]; CRYPT_EAL_MacCtx *ctx = NULL; ctx = CRYPT_EAL_MacNewCtx(threadParameter->algId); ASSERT_TRUE(ctx != NULL); for (uint32_t i = 0; i < 10; i++) { ASSERT_EQ(CRYPT_EAL_MacInit(ctx, threadParameter->key, threadParameter->keyLen), CRYPT_SUCCESS); ASSERT_EQ(CRYPT_EAL_MacUpdate(ctx, threadParameter->data, threadParameter->dataLen), CRYPT_SUCCESS); ASSERT_EQ(CRYPT_EAL_MacFinal(ctx, out, &outLen), CRYPT_SUCCESS); ASSERT_COMPARE("hash result cmp", out, outLen, threadParameter->mac, threadParameter->macLen); } EXIT: CRYPT_EAL_MacFreeCtx(ctx); }
2301_79861745/bench_create
testcode/sdv/testcase/crypto/hmac/test_suite_sdv_eal_mac_hmac.base.c
C
unknown
3,052
/* * This file is part of the openHiTLS project. * * openHiTLS is licensed under the Mulan PSL v2. * You can use this software according to the terms and conditions of the Mulan PSL v2. * You may obtain a copy of Mulan PSL v2 at: * * http://license.coscl.org.cn/MulanPSL2 * * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, * EITHER EXPRESS 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 test_suite_sdv_eal_mac_hmac */ /* BEGIN_HEADER */ /* END_HEADER */ #define HMAC_MAX_BUFF_LEN (64 + 1) // CRYPT_SHA2_512_DIGESTSIZE + 1 /** * @test SDV_CRYPT_EAL_HMAC_API_TC001 * @title Create hmac context test. * @precon nan * @brief * 1.Create context with invalid id, expected result 1. * 2.Create context using CRYPT_MAC_AlgId, expected result 2. * @expect * 1.The result is NULL. * 2.Create successful. */ /* BEGIN_CASE */ void SDV_CRYPT_EAL_HMAC_API_TC001(void) { TestMemInit(); CRYPT_MAC_AlgId testIds[] = { CRYPT_MAC_HMAC_MD5, CRYPT_MAC_HMAC_SHA1, CRYPT_MAC_HMAC_SHA224, CRYPT_MAC_HMAC_SHA256, CRYPT_MAC_HMAC_SHA384, CRYPT_MAC_HMAC_SHA512, CRYPT_MAC_HMAC_SM3, CRYPT_MAC_HMAC_SHA3_224, CRYPT_MAC_HMAC_SHA3_256, CRYPT_MAC_HMAC_SHA3_384, CRYPT_MAC_HMAC_SHA3_512 }; CRYPT_EAL_MacCtx *ctx = NULL; for (int i = 0; i < (int)(sizeof(testIds) / sizeof(CRYPT_MAC_AlgId)); i++) { ctx = CRYPT_EAL_MacNewCtx(testIds[i]); ASSERT_TRUE(ctx != NULL); CRYPT_EAL_MacFreeCtx(ctx); } ctx = CRYPT_EAL_MacNewCtx(CRYPT_MAC_MAX); ASSERT_TRUE(ctx == NULL); EXIT: CRYPT_EAL_MacFreeCtx(ctx); } /* END_CASE */ /** * @test SDV_CRYPT_EAL_HMAC_API_TC002 * @title hmac init test. * @precon nan * @brief * 1.Call CRYPT_EAL_MdNewCtx create the CTX, expected result 1. * 2.Call CRYPT_EAL_MacInit,ctx is NULL or key is NULL but keylen not 0, expected result 2. * 3.Call CRYPT_EAL_MacInit,key is NULL and keyLen is 0, expected result 3. * 4.Call CRYPT_EAL_MacInit normally, expected result 4. * @expect * 1.Create successful. * 2.Return CRYPT_NULL_INPUT. * 3.Successful. * 4.Successful. */ /* BEGIN_CASE */ void SDV_CRYPT_EAL_HMAC_API_TC002(int algId) { TestMemInit(); const uint32_t len = GetMacLen(algId); uint8_t key[HMAC_MAX_BUFF_LEN]; CRYPT_EAL_MacCtx *ctx = CRYPT_EAL_MacNewCtx(algId); ASSERT_TRUE(ctx != NULL); ASSERT_EQ(CRYPT_EAL_MacInit(NULL, key, len), CRYPT_NULL_INPUT); ASSERT_EQ(CRYPT_EAL_MacInit(ctx, NULL, len), CRYPT_NULL_INPUT); ASSERT_EQ(CRYPT_EAL_MacInit(ctx, NULL, 0), CRYPT_SUCCESS); ASSERT_EQ(CRYPT_EAL_MacInit(ctx, (uint8_t *)key, 0), CRYPT_SUCCESS); ASSERT_EQ(CRYPT_EAL_MacInit(ctx, key, len), CRYPT_SUCCESS); EXIT: CRYPT_EAL_MacFreeCtx(ctx); } /* END_CASE */ /** * @test SDV_CRYPT_EAL_HMAC_API_TC003 * @title hmac init test. * @precon nan * @brief * 1.Call CRYPT_EAL_MdNewCtx create the CTX, expected result 1. * 2.Call CRYPT_EAL_MacInit repeatedly, expected result 2. * 3.Call CRYPT_EAL_MacInit after update, expected result 3. * 4.Call CRYPT_EAL_MacReinit, expected result 4. * @expect * 1.Create successful. * 2.Successful. * 3.Successful. * 4.Successful. */ /* BEGIN_CASE */ void SDV_CRYPT_EAL_HMAC_API_TC003(int algId) { TestMemInit(); const uint32_t len = GetMacLen(algId); uint32_t macLen = len; const uint32_t dataLen = HMAC_MAX_BUFF_LEN; uint8_t key[HMAC_MAX_BUFF_LEN]; uint8_t mac[HMAC_MAX_BUFF_LEN]; uint8_t data[HMAC_MAX_BUFF_LEN]; CRYPT_EAL_MacCtx *ctx = CRYPT_EAL_MacNewCtx(algId); ASSERT_TRUE(ctx != NULL); ASSERT_EQ(CRYPT_EAL_MacInit(ctx, key, len), CRYPT_SUCCESS); ASSERT_EQ(CRYPT_EAL_MacInit(ctx, key, len), CRYPT_SUCCESS); ASSERT_EQ(CRYPT_EAL_MacUpdate(ctx, data, dataLen), CRYPT_SUCCESS); ASSERT_EQ(CRYPT_EAL_MacInit(ctx, key, len), CRYPT_SUCCESS); ASSERT_EQ(CRYPT_EAL_MacFinal(ctx, mac, &macLen), CRYPT_SUCCESS); ASSERT_EQ(CRYPT_EAL_MacInit(ctx, key, len), CRYPT_SUCCESS); CRYPT_EAL_MacDeinit(ctx); ASSERT_EQ(CRYPT_EAL_MacInit(ctx, key, len), CRYPT_SUCCESS); ASSERT_EQ(CRYPT_EAL_MacReinit(ctx), CRYPT_SUCCESS); ASSERT_EQ(CRYPT_EAL_MacInit(ctx, key, len), CRYPT_SUCCESS); EXIT: CRYPT_EAL_MacFreeCtx(ctx); } /* END_CASE */ /** * @test SDV_CRYPT_EAL_HMAC_API_TC004 * @title hmac init test. * @precon nan * @brief * 1.Call CRYPT_EAL_MdNewCtx create the CTX, expected result 1. * 2.Call CRYPT_EAL_MacUpdate before init, expected result 2. * 3.Call CRYPT_EAL_MacUpdate,ctx or data is NULL, expected result 3. * 4.Call CRYPT_EAL_MacUpdate,dataLen is 0, expected result 4. * 5.Call CRYPT_EAL_MacUpdate normally, expected result 5. * @expect * 1.Create successful. * 2.Return CRYPT_EAL_ERR_STATE. * 3.Return CRYPT_NULL_INPUT. * 4.Successful. * 5.Successful. */ /* BEGIN_CASE */ void SDV_CRYPT_EAL_HMAC_API_TC004(int algId) { TestMemInit(); const uint32_t len = GetMacLen(algId); const uint32_t dataLen = HMAC_MAX_BUFF_LEN; uint8_t key[HMAC_MAX_BUFF_LEN]; uint8_t data[HMAC_MAX_BUFF_LEN]; CRYPT_EAL_MacCtx *ctx = CRYPT_EAL_MacNewCtx(algId); ASSERT_TRUE(ctx != NULL); ASSERT_EQ(CRYPT_EAL_MacUpdate(ctx, data, dataLen), CRYPT_EAL_ERR_STATE); ASSERT_EQ(CRYPT_EAL_MacInit(ctx, key, len), CRYPT_SUCCESS); ASSERT_EQ(CRYPT_EAL_MacUpdate(NULL, data, dataLen), CRYPT_NULL_INPUT); ASSERT_EQ(CRYPT_EAL_MacUpdate(ctx, NULL, dataLen), CRYPT_NULL_INPUT); ASSERT_EQ(CRYPT_EAL_MacUpdate(ctx, data, 0), CRYPT_SUCCESS); ASSERT_EQ(CRYPT_EAL_MacUpdate(ctx, NULL, 0), CRYPT_SUCCESS); ASSERT_EQ(CRYPT_EAL_MacUpdate(ctx, data, dataLen), CRYPT_SUCCESS); EXIT: CRYPT_EAL_MacFreeCtx(ctx); } /* END_CASE */ /** * @test SDV_CRYPT_EAL_HMAC_API_TC005 * @title hmac final test. * @precon nan * @brief * 1.Call CRYPT_EAL_MdNewCtx create the CTX, expected result 1. * 2.Call CRYPT_EAL_MacFinal before init, expected result 2. * 3.Call CRYPT_EAL_MacFinal,ctx or mac is NULL, expected result 3. * 4.Call CRYPT_EAL_MacFinal,macLen not enough, expected result 4. * 5.Call CRYPT_EAL_MacFinal normally, expected result 5. * @expect * 1.Create successful. * 2.Return CRYPT_EAL_ERR_STATE. * 3.Return CRYPT_NULL_INPUT. * 4.Return CRYPT_HMAC_OUT_BUFF_LEN_NOT_ENOUGH. * 5.Successful. */ /* BEGIN_CASE */ void SDV_CRYPT_EAL_HMAC_API_TC005(int algId) { TestMemInit(); const uint32_t len = GetMacLen(algId); uint32_t macLen = len; uint8_t key[HMAC_MAX_BUFF_LEN]; uint8_t mac[HMAC_MAX_BUFF_LEN]; CRYPT_EAL_MacCtx *ctx = CRYPT_EAL_MacNewCtx(algId); ASSERT_TRUE(ctx != NULL); ASSERT_EQ(CRYPT_EAL_MacFinal(ctx, mac, &macLen), CRYPT_EAL_ERR_STATE); ASSERT_EQ(CRYPT_EAL_MacInit(ctx, key, len), CRYPT_SUCCESS); ASSERT_EQ(CRYPT_EAL_MacFinal(NULL, mac, &macLen), CRYPT_NULL_INPUT); ASSERT_EQ(CRYPT_EAL_MacFinal(ctx, NULL, &macLen), CRYPT_NULL_INPUT); ASSERT_EQ(CRYPT_EAL_MacFinal(ctx, mac, NULL), CRYPT_NULL_INPUT); macLen = GetMacLen(algId) - 1; ASSERT_EQ(CRYPT_EAL_MacFinal(ctx, mac, &macLen), CRYPT_HMAC_OUT_BUFF_LEN_NOT_ENOUGH); macLen = GetMacLen(algId) + 1; ASSERT_EQ(CRYPT_EAL_MacFinal(ctx, mac, &macLen), CRYPT_SUCCESS); ASSERT_EQ(CRYPT_EAL_MacFinal(ctx, mac, &macLen), CRYPT_EAL_ERR_STATE); EXIT: CRYPT_EAL_MacFreeCtx(ctx); } /* END_CASE */ /** * @test SDV_CRYPT_EAL_HMAC_API_TC006 * @title get mac len test. * @precon nan * @brief * 1.Call CRYPT_EAL_MdNewCtx create the ctx and init, expected result 1. * 2.Call CRYPT_EAL_GetMacLen,the input parameter is null, expected result 2. * 3.Call CRYPT_EAL_GetMacLen after init,update final and deinit, expected result 3. * @expect * 1.Create successful. * 2.Return 0. * 3.Successful. */ /* BEGIN_CASE */ void SDV_CRYPT_EAL_HMAC_API_TC006(int algId) { TestMemInit(); const uint32_t len = GetMacLen(algId); uint8_t key[HMAC_MAX_BUFF_LEN]; const uint32_t dataLen = HMAC_MAX_BUFF_LEN; uint8_t data[HMAC_MAX_BUFF_LEN]; uint32_t macLen = len; uint8_t mac[HMAC_MAX_BUFF_LEN]; CRYPT_EAL_MacCtx *ctx = CRYPT_EAL_MacNewCtx(algId); ASSERT_EQ(CRYPT_EAL_GetMacLen(NULL), 0); ASSERT_EQ(CRYPT_EAL_GetMacLen(ctx), GetMacLen(algId)); ASSERT_EQ(CRYPT_EAL_MacInit(ctx, key, len), CRYPT_SUCCESS); ASSERT_EQ(CRYPT_EAL_GetMacLen(ctx), GetMacLen(algId)); ASSERT_EQ(CRYPT_EAL_MacUpdate(ctx, data, dataLen), CRYPT_SUCCESS); ASSERT_EQ(CRYPT_EAL_GetMacLen(ctx), GetMacLen(algId)); ASSERT_EQ(CRYPT_EAL_MacFinal(ctx, mac, &macLen), CRYPT_SUCCESS); ASSERT_EQ(CRYPT_EAL_GetMacLen(ctx), GetMacLen(algId)); CRYPT_EAL_MacDeinit(ctx); ASSERT_EQ(CRYPT_EAL_GetMacLen(ctx), GetMacLen(algId)); EXIT: CRYPT_EAL_MacFreeCtx(ctx); } /* END_CASE */ /** * @test SDV_CRYPT_EAL_HMAC_API_TC007 * @title reinit ctx test. * @precon nan * @brief * 1.Call CRYPT_EAL_MdNewCtx create the ctx and init, expected result 1. * 2.Call CRYPT_EAL_MacReinit,the input parameter is null, expected result 2. * 3.Call CRYPT_EAL_MacReinit after init,update final, expected result 3. * 3.Call CRYPT_EAL_MacReinit after deinit, expected result 4. * @expect * 1.Create successful. * 2.Return 0. * 3.Successful. * 4.Return CRYPT_EAL_ERR_STATE. */ /* BEGIN_CASE */ void SDV_CRYPT_EAL_HMAC_API_TC007(int algId) { TestMemInit(); const uint32_t len = GetMacLen(algId); uint32_t macLen = len; const uint32_t dataLen = HMAC_MAX_BUFF_LEN; uint8_t key[HMAC_MAX_BUFF_LEN]; uint8_t mac[HMAC_MAX_BUFF_LEN]; uint8_t data[HMAC_MAX_BUFF_LEN]; CRYPT_EAL_MacCtx *ctx = CRYPT_EAL_MacNewCtx(algId); ASSERT_TRUE(ctx != NULL); ASSERT_EQ(CRYPT_EAL_MacReinit(NULL), CRYPT_NULL_INPUT); ASSERT_EQ(CRYPT_EAL_MacReinit(ctx), CRYPT_EAL_ERR_STATE); ASSERT_EQ(CRYPT_EAL_MacInit(ctx, key, len), CRYPT_SUCCESS); ASSERT_EQ(CRYPT_EAL_MacReinit(ctx), CRYPT_SUCCESS); ASSERT_EQ(CRYPT_EAL_MacUpdate(ctx, data, dataLen), CRYPT_SUCCESS); ASSERT_EQ(CRYPT_EAL_MacReinit(ctx), CRYPT_SUCCESS); ASSERT_EQ(CRYPT_EAL_MacFinal(ctx, mac, &macLen), CRYPT_SUCCESS); ASSERT_EQ(CRYPT_EAL_MacReinit(ctx), CRYPT_SUCCESS); CRYPT_EAL_MacDeinit(ctx); ASSERT_EQ(CRYPT_EAL_MacReinit(ctx), CRYPT_EAL_ERR_STATE); EXIT: CRYPT_EAL_MacFreeCtx(ctx); } /* END_CASE */ /** * @test SDV_CRYPT_EAL_HMAC_FUN_TC001 * @title Perform the vector test to check whether the calculation result is consistent with the standard output. * @precon nan * @brief * 1.Calculate the hmac of each group of data, expected result 1. * 2.Compare the result to the expected value, expected result 2. * @expect * 1.Hmac calculation succeeded. * 2.The results are as expected. */ /* BEGIN_CASE */ void SDV_CRYPT_EAL_HMAC_FUN_TC001(int algId, Hex *key, Hex *data, Hex *vecMac) { if (IsHmacAlgDisabled(algId)) { SKIP_TEST(); } TestMemInit(); uint32_t macLen = GetMacLen(algId); uint8_t *mac = malloc(macLen); ASSERT_TRUE(mac != NULL); CRYPT_EAL_MacCtx *ctx = CRYPT_EAL_MacNewCtx(algId); ASSERT_TRUE(ctx != NULL); ASSERT_EQ(CRYPT_EAL_MacInit(ctx, key->x, key->len), CRYPT_SUCCESS); ASSERT_EQ(CRYPT_EAL_MacUpdate(ctx, data->x, data->len), CRYPT_SUCCESS); ASSERT_EQ(CRYPT_EAL_MacFinal(ctx, mac, &macLen), CRYPT_SUCCESS); ASSERT_COMPARE("mac1 result cmp", mac, macLen, vecMac->x, vecMac->len); EXIT: CRYPT_EAL_MacFreeCtx(ctx); free(mac); } /* END_CASE */ /** * @test SDV_CRYPT_EAL_HMAC_FUN_TC002 * @title Hash calculation for multiple updates,comparison with standard results. * @precon nan * @brief * 1.Call CRYPT_EAL_MacNewCtx to create a ctx and initialize, expected result 1. * 2.Call CRYPT_EAL_MacUpdate to calculate the hash of a data segmentxpected result 2. * 3.Call CRYPT_EAL_MacUpdate to calculate the next data segmentxpected result 3. * 4.Call CRYPT_EAL_MacUpdate to calculate the next data segmentxpected result 4. * 5.Call CRYPT_EAL_MacFinal get the result, expected result 5. * @expect * 1.Successful * 2.Successful * 3.Successful * 4.Successful * 5.The results are as expected. */ /* BEGIN_CASE */ void SDV_CRYPT_EAL_HMAC_FUN_TC002(int algId, Hex *key, Hex *data1, Hex *data2, Hex *data3, Hex *vecMac) { TestMemInit(); uint32_t macLen = GetMacLen(algId); uint8_t *mac = malloc(macLen); ASSERT_TRUE(mac != NULL); CRYPT_EAL_MacCtx *ctx = CRYPT_EAL_MacNewCtx(algId); ASSERT_TRUE(ctx != NULL); ASSERT_EQ(CRYPT_EAL_MacInit(ctx, key->x, key->len), CRYPT_SUCCESS); ASSERT_EQ(CRYPT_EAL_MacUpdate(ctx, data1->x, data1->len), CRYPT_SUCCESS); ASSERT_EQ(CRYPT_EAL_MacUpdate(ctx, data2->x, data2->len), CRYPT_SUCCESS); ASSERT_EQ(CRYPT_EAL_MacUpdate(ctx, data3->x, data3->len), CRYPT_SUCCESS); ASSERT_EQ(CRYPT_EAL_MacFinal(ctx, mac, &macLen), CRYPT_SUCCESS); ASSERT_COMPARE("mac1 result cmp", mac, macLen, vecMac->x, vecMac->len); CRYPT_EAL_MacDeinit(ctx); EXIT: CRYPT_EAL_MacFreeCtx(ctx); free(mac); } /* END_CASE */ /** * @test SDV_CRYPT_EAL_SHA1_FUN_TC003 * @title Test multi-thread hmac calculation. * @precon nan * @brief * 1.Create two threads and calculate the hmac, expected result 1. * 2.Compare the result to the expected value, expected result 2. * @expect * 1.Hmac calculation succeeded. * 2.The results are as expected. */ /* BEGIN_CASE */ void SDV_CRYPT_EAL_HMAC_FUN_TC003(int algId, Hex *key1, Hex *data1, Hex *vecMac1, Hex *key2, Hex *data2, Hex *vecMac2) { int ret; TestMemInit(); const uint32_t threadNum = 2; // 2 threads pthread_t thrd[2]; ThreadParameter arg[2] = { {.data = data1->x, .key = key1->x, .mac = vecMac1->x, .dataLen = data1->len, .keyLen = key1->len, .macLen = vecMac1->len, .algId = algId}, {.data = data2->x, .key = key2->x, .mac = vecMac2->x, .dataLen = data2->len, .keyLen = key2->len, .macLen = vecMac2->len, .algId = algId}, }; for (uint32_t i = 0; i < threadNum; i++) { ret = pthread_create(&thrd[i], NULL, (void *)MultiThreadTest, &arg[i]); ASSERT_TRUE(ret == 0); } for (uint32_t i = 0; i < threadNum; i++) { pthread_join(thrd[i], NULL); } EXIT: return; } /* END_CASE */ /** * @test SDV_CRYPTO_HMAC_DEFAULT_PROVIDER_FUNC_TC001 * @title Default provider testing * @precon nan * @brief * Load the default provider and use the test vector to test its correctness */ /* BEGIN_CASE */ void SDV_CRYPT_HMAC_DEFAULT_PROVIDER_FUNC_TC001(int algId, Hex *key, Hex *data, Hex *vecMac) { if (IsHmacAlgDisabled(algId)) { SKIP_TEST(); } TestMemInit(); CRYPT_EAL_MacCtx *ctx = NULL; #ifdef HITLS_CRYPTO_PROVIDER ctx = CRYPT_EAL_ProviderMacNewCtx(NULL, algId, "provider=default"); #else ctx = CRYPT_EAL_MacNewCtx(algId); #endif ASSERT_TRUE(ctx != NULL); uint32_t macLen = GetMacLen(algId); uint8_t *mac = BSL_SAL_Calloc(1, macLen); ASSERT_TRUE(mac != NULL); ASSERT_EQ(CRYPT_EAL_GetMacLen(ctx), GetMacLen(algId)); ASSERT_EQ(CRYPT_EAL_MacInit(ctx, key->x, key->len), CRYPT_SUCCESS); ASSERT_EQ(CRYPT_EAL_MacUpdate(ctx, data->x, data->len), CRYPT_SUCCESS); ASSERT_EQ(CRYPT_EAL_MacFinal(ctx, mac, &macLen), CRYPT_SUCCESS); ASSERT_COMPARE("mac1 result cmp", mac, macLen, vecMac->x, vecMac->len); CRYPT_EAL_MacDeinit(ctx); ASSERT_EQ(CRYPT_EAL_MacInit(ctx, key->x, key->len), CRYPT_SUCCESS); ASSERT_EQ(CRYPT_EAL_MacReinit(ctx), CRYPT_SUCCESS); EXIT: CRYPT_EAL_MacFreeCtx(ctx); BSL_SAL_FREE(mac); } /* END_CASE */
2301_79861745/bench_create
testcode/sdv/testcase/crypto/hmac/test_suite_sdv_eal_mac_hmac.c
C
unknown
15,751
/* * This file is part of the openHiTLS project. * * openHiTLS is licensed under the Mulan PSL v2. * You can use this software according to the terms and conditions of the Mulan PSL v2. * You may obtain a copy of Mulan PSL v2 at: * * http://license.coscl.org.cn/MulanPSL2 * * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, * EITHER EXPRESS 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 "crypt_eal_rand.h" #include "crypt_eal_hpke.h" /* END_HEADER */ #define HPKE_KEM_MAX_ENCAPSULATED_KEY_LEN 133 #define HPKE_KEM_MAX_PUBLIC_KEY_LEN 133 #define HPKE_KEM_MAX_PRIVATE_KEY_LEN 66 #define HPKE_HKDF_MAX_EXTRACT_KEY_LEN 64 #define HPKE_KEM_MAX_SHARED_KEY_LEN 64 #define HPKE_AEAD_MAX_KEY_LEN 32 #define HPKE_AEAD_NONCE_LEN 12 #define HPKE_AEAD_TAG_LEN 16 #define HPKE_ERR -1 static int32_t GenerateHpkeCtxSAndCtxR(int mode, CRYPT_HPKE_CipherSuite cipherSuite, Hex *info, Hex *psk, Hex *pskId, Hex *ikmE, Hex *ikmR, Hex *ikmS, CRYPT_EAL_HpkeCtx **ctxS, CRYPT_EAL_HpkeCtx **ctxR, CRYPT_EAL_PkeyCtx **pkeyE, CRYPT_EAL_PkeyCtx **pkeyR, CRYPT_EAL_PkeyCtx **pkeyS, uint8_t *encapsulatedKey, uint32_t *encapsulatedKeyLen) { CRYPT_EAL_HpkeCtx *ctxS1 = NULL; CRYPT_EAL_HpkeCtx *ctxR1 = NULL; CRYPT_EAL_PkeyCtx *pkeyE1 = NULL; CRYPT_EAL_PkeyCtx *pkeyR1 = NULL; CRYPT_EAL_PkeyCtx *pkeyS1 = NULL; ASSERT_EQ(CRYPT_EAL_HpkeGenerateKeyPair(NULL, NULL, cipherSuite, ikmE->x, ikmE->len, &pkeyE1), CRYPT_SUCCESS); ASSERT_EQ(CRYPT_EAL_HpkeGenerateKeyPair(NULL, NULL, cipherSuite, ikmR->x, ikmR->len, &pkeyR1), CRYPT_SUCCESS); if(mode == CRYPT_HPKE_MODE_AUTH || mode ==CRYPT_HPKE_MODE_AUTH_PSK) { ASSERT_EQ(CRYPT_EAL_HpkeGenerateKeyPair(NULL, NULL, cipherSuite, ikmS->x, ikmS->len, &pkeyS1), CRYPT_SUCCESS); } CRYPT_EAL_PkeyPub pubR1; pubR1.id = CRYPT_EAL_PkeyGetId(pkeyR1); pubR1.key.eccPub.len = HPKE_KEM_MAX_PUBLIC_KEY_LEN; uint8_t pubRKeyBuf[HPKE_KEM_MAX_PUBLIC_KEY_LEN]; pubR1.key.eccPub.data = pubRKeyBuf; ASSERT_EQ(CRYPT_EAL_PkeyGetPub(pkeyR1, &pubR1), CRYPT_SUCCESS); ctxS1 = CRYPT_EAL_HpkeNewCtx(NULL, NULL, CRYPT_HPKE_SENDER, mode, cipherSuite); ASSERT_TRUE(ctxS1 != NULL); if(mode == CRYPT_HPKE_MODE_PSK || mode == CRYPT_HPKE_MODE_AUTH_PSK) { ASSERT_EQ(CRYPT_EAL_HpkeSetPsk(ctxS1, psk->x, psk->len , pskId->x, pskId->len), CRYPT_SUCCESS); } if(mode == CRYPT_HPKE_MODE_AUTH || mode ==CRYPT_HPKE_MODE_AUTH_PSK) { ASSERT_EQ(CRYPT_EAL_HpkeSetAuthPriKey(ctxS1, pkeyS1),CRYPT_SUCCESS); } ASSERT_EQ(CRYPT_EAL_HpkeSetupSender(ctxS1, pkeyE1, info->x, info->len, pubR1.key.eccPub.data, pubR1.key.eccPub.len, encapsulatedKey, encapsulatedKeyLen), CRYPT_SUCCESS); ctxR1 = CRYPT_EAL_HpkeNewCtx(NULL, NULL, CRYPT_HPKE_RECIPIENT, mode, cipherSuite); ASSERT_TRUE(ctxR1 != NULL); if(mode == CRYPT_HPKE_MODE_PSK || mode == CRYPT_HPKE_MODE_AUTH_PSK){ ASSERT_EQ(CRYPT_EAL_HpkeSetPsk(ctxR1, psk->x, psk->len , pskId->x, pskId->len), CRYPT_SUCCESS); } if(mode == CRYPT_HPKE_MODE_AUTH || mode ==CRYPT_HPKE_MODE_AUTH_PSK){ CRYPT_EAL_PkeyPub pubS1; pubS1.id = CRYPT_EAL_PkeyGetId(pkeyS1); pubS1.key.eccPub.len = HPKE_KEM_MAX_PUBLIC_KEY_LEN; uint8_t pubSKeyBuf[HPKE_KEM_MAX_PUBLIC_KEY_LEN]; pubS1.key.eccPub.data = pubSKeyBuf; ASSERT_EQ(CRYPT_EAL_PkeyGetPub(pkeyS1, &pubS1), CRYPT_SUCCESS); ASSERT_EQ(CRYPT_EAL_HpkeSetAuthPubKey(ctxR1, pubS1.key.eccPub.data, pubS1.key.eccPub.len),CRYPT_SUCCESS); } ASSERT_EQ(CRYPT_EAL_HpkeSetupRecipient(ctxR1, pkeyR1, info->x, info->len, encapsulatedKey, *encapsulatedKeyLen), CRYPT_SUCCESS); *ctxS = ctxS1; *ctxR = ctxR1; *pkeyS = pkeyS1; *pkeyR = pkeyR1; *pkeyE = pkeyE1; return CRYPT_SUCCESS; EXIT: CRYPT_EAL_HpkeFreeCtx(ctxS1); CRYPT_EAL_HpkeFreeCtx(ctxR1); CRYPT_EAL_PkeyFreeCtx(pkeyS1); CRYPT_EAL_PkeyFreeCtx(pkeyR1); CRYPT_EAL_PkeyFreeCtx(pkeyE1); return HPKE_ERR; } /** * @test SDV_CRYPT_EAL_HPKE_KEM_TC001 * @title hpke key derivation test based on standard vectors. */ /* BEGIN_CASE */ void SDV_CRYPT_EAL_HPKE_KEM_TC001(int mode, int kemId, int kdfId, int aeadId, Hex *info, Hex *psk, Hex *pskId, Hex *ikmE, Hex *pkEm, Hex *skEm, Hex *ikmR, Hex *pkRm, Hex *skRm, Hex *ikmS, Hex *pkSm, Hex *skSm, Hex *enc, Hex *sharedSecret, Hex *keyScheduleContext, Hex *secret, Hex *key, Hex *baseNonce, Hex *exporterSecret) { (void)secret; (void)keyScheduleContext; (void)key; (void)baseNonce; (void)exporterSecret; ASSERT_EQ(TestRandInit(), CRYPT_SUCCESS); CRYPT_HPKE_CipherSuite cipherSuite = {kemId, kdfId, aeadId}; CRYPT_EAL_HpkeCtx *ctxS = NULL; CRYPT_EAL_HpkeCtx *ctxR = NULL; CRYPT_EAL_PkeyCtx *pkeyS = NULL; CRYPT_EAL_PkeyCtx *pkeyR = NULL; CRYPT_EAL_PkeyCtx *pkeyE = NULL; uint8_t encapsulatedKey[HPKE_KEM_MAX_ENCAPSULATED_KEY_LEN]; uint32_t encapsulatedKeyLen = HPKE_KEM_MAX_ENCAPSULATED_KEY_LEN; ASSERT_EQ(GenerateHpkeCtxSAndCtxR(mode, cipherSuite, info, psk, pskId, ikmE, ikmR, ikmS, &ctxS, &ctxR, &pkeyE, &pkeyR, &pkeyS, encapsulatedKey, &encapsulatedKeyLen), CRYPT_SUCCESS); CRYPT_EAL_PkeyPrv priE; priE.id = CRYPT_EAL_PkeyGetId(pkeyE); priE.key.eccPrv.len = HPKE_KEM_MAX_PRIVATE_KEY_LEN; uint8_t priEKeyBuf[HPKE_KEM_MAX_PRIVATE_KEY_LEN]; priE.key.eccPrv.data = priEKeyBuf; ASSERT_EQ(CRYPT_EAL_PkeyGetPrv(pkeyE, &priE), CRYPT_SUCCESS); ASSERT_COMPARE("hpke priE cmp", priE.key.eccPrv.data, priE.key.eccPrv.len, skEm->x, skEm->len); CRYPT_EAL_PkeyPub pubE; pubE.id = CRYPT_EAL_PkeyGetId(pkeyE); pubE.key.eccPub.len = HPKE_KEM_MAX_PUBLIC_KEY_LEN; uint8_t pubEKeyBuf[HPKE_KEM_MAX_PUBLIC_KEY_LEN]; pubE.key.eccPub.data = pubEKeyBuf; ASSERT_EQ(CRYPT_EAL_PkeyGetPub(pkeyE, &pubE), CRYPT_SUCCESS); ASSERT_COMPARE("hpke pubE cmp", pubE.key.eccPub.data, pubE.key.eccPub.len, pkEm->x, pkEm->len); CRYPT_EAL_PkeyPrv priR; priR.id = CRYPT_EAL_PkeyGetId(pkeyR); priR.key.eccPrv.len = HPKE_KEM_MAX_PRIVATE_KEY_LEN; uint8_t priRKeyBuf[HPKE_KEM_MAX_PRIVATE_KEY_LEN]; priR.key.eccPrv.data = priRKeyBuf; ASSERT_EQ(CRYPT_EAL_PkeyGetPrv(pkeyR, &priR), CRYPT_SUCCESS); ASSERT_COMPARE("hpke priR cmp", priR.key.eccPrv.data, priR.key.eccPrv.len, skRm->x, skRm->len); CRYPT_EAL_PkeyPub pubR; pubR.id = CRYPT_EAL_PkeyGetId(pkeyR); pubR.key.eccPub.len = HPKE_KEM_MAX_PUBLIC_KEY_LEN; uint8_t pubRKeyBuf[HPKE_KEM_MAX_PUBLIC_KEY_LEN]; pubR.key.eccPub.data = pubRKeyBuf; ASSERT_EQ(CRYPT_EAL_PkeyGetPub(pkeyR, &pubR), CRYPT_SUCCESS); ASSERT_COMPARE("hpke pubR cmp", pubR.key.eccPub.data, pubR.key.eccPub.len, pkRm->x, pkRm->len); if(mode == CRYPT_HPKE_MODE_AUTH || mode ==CRYPT_HPKE_MODE_AUTH_PSK){ CRYPT_EAL_PkeyPrv priS; priS.id = CRYPT_EAL_PkeyGetId(pkeyS); priS.key.eccPrv.len = HPKE_KEM_MAX_PRIVATE_KEY_LEN; uint8_t priSKeyBuf[HPKE_KEM_MAX_PRIVATE_KEY_LEN]; priS.key.eccPrv.data = priSKeyBuf; ASSERT_EQ(CRYPT_EAL_PkeyGetPrv(pkeyS, &priS), CRYPT_SUCCESS); ASSERT_COMPARE("hpke priS cmp", priS.key.eccPrv.data, priS.key.eccPrv.len, skSm->x, skSm->len); CRYPT_EAL_PkeyPub pubS; pubS.id = CRYPT_EAL_PkeyGetId(pkeyS); pubS.key.eccPub.len = HPKE_KEM_MAX_PUBLIC_KEY_LEN; uint8_t pubSKeyBuf[HPKE_KEM_MAX_PUBLIC_KEY_LEN]; pubS.key.eccPub.data = pubSKeyBuf; ASSERT_EQ(CRYPT_EAL_PkeyGetPub(pkeyS, &pubS), CRYPT_SUCCESS); ASSERT_COMPARE("hpke pubS cmp", pubS.key.eccPub.data, pubS.key.eccPub.len, pkSm->x, pkSm->len); } // check enc ASSERT_COMPARE("hpke enc cmp", encapsulatedKey, encapsulatedKeyLen, enc->x, enc->len); uint8_t sharedSecretBuf[HPKE_KEM_MAX_SHARED_KEY_LEN] = {0}; uint32_t buffLen = HPKE_KEM_MAX_SHARED_KEY_LEN; ASSERT_EQ(CRYPT_EAL_HpkeGetSharedSecret(ctxS, sharedSecretBuf, &buffLen), CRYPT_SUCCESS); ASSERT_COMPARE("hpke S sharedSecret cmp", sharedSecretBuf, buffLen, sharedSecret->x, sharedSecret->len); (void)memset_s(sharedSecretBuf, 0, HPKE_KEM_MAX_SHARED_KEY_LEN, 0); buffLen = HPKE_KEM_MAX_SHARED_KEY_LEN; ASSERT_EQ(CRYPT_EAL_HpkeGetSharedSecret(ctxR, sharedSecretBuf, &buffLen), CRYPT_SUCCESS); ASSERT_COMPARE("hpke R sharedSecret cmp", sharedSecretBuf, buffLen, sharedSecret->x, sharedSecret->len); EXIT: CRYPT_EAL_HpkeFreeCtx(ctxS); CRYPT_EAL_HpkeFreeCtx(ctxR); CRYPT_EAL_PkeyFreeCtx(pkeyS); CRYPT_EAL_PkeyFreeCtx(pkeyR); CRYPT_EAL_PkeyFreeCtx(pkeyE); TestRandDeInit(); } /* END_CASE */ /** * @test SDV_CRYPT_EAL_HPKE_AEAD_TC001 * @title hpke seal and open test based on standard vectors. */ /* BEGIN_CASE */ void SDV_CRYPT_EAL_HPKE_AEAD_TC001(int mode, int kemId, int kdfId, int aeadId, Hex *info, Hex *psk, Hex *pskId, Hex *ikmE, Hex *ikmR, Hex *ikmS,int seq, Hex *pt, Hex *aad, Hex *ct) { ASSERT_EQ(TestRandInit(), CRYPT_SUCCESS); CRYPT_HPKE_CipherSuite cipherSuite = {kemId, kdfId, aeadId}; CRYPT_EAL_HpkeCtx *ctxS = NULL; CRYPT_EAL_HpkeCtx *ctxR = NULL; CRYPT_EAL_PkeyCtx *pkeyE = NULL; CRYPT_EAL_PkeyCtx *pkeyR = NULL; CRYPT_EAL_PkeyCtx *pkeyS = NULL; uint8_t encapsulatedKey[HPKE_KEM_MAX_ENCAPSULATED_KEY_LEN]; uint32_t encapsulatedKeyLen = HPKE_KEM_MAX_ENCAPSULATED_KEY_LEN; ASSERT_EQ(GenerateHpkeCtxSAndCtxR(mode, cipherSuite, info, psk, pskId, ikmE, ikmR, ikmS, &ctxS, &ctxR, &pkeyE, &pkeyR, &pkeyS, encapsulatedKey, &encapsulatedKeyLen), CRYPT_SUCCESS); uint8_t cipher[200] = { 0 }; uint32_t cipherLen = 200; ASSERT_EQ(CRYPT_EAL_HpkeSetSeq(ctxS, seq), CRYPT_SUCCESS); ASSERT_EQ(CRYPT_EAL_HpkeSeal(ctxS, aad->x, aad->len, pt->x, pt->len, cipher, &cipherLen), CRYPT_SUCCESS); ASSERT_COMPARE("hpke seal cmp", cipher, cipherLen, ct->x, ct->len); uint64_t nextSeq; ASSERT_EQ(CRYPT_EAL_HpkeGetSeq(ctxS, &nextSeq), CRYPT_SUCCESS); ASSERT_EQ(nextSeq, seq + 1); uint8_t plain[200] = { 0 }; uint32_t plainLen = 200; ASSERT_EQ(CRYPT_EAL_HpkeSetSeq(ctxR, seq), CRYPT_SUCCESS); ASSERT_EQ(CRYPT_EAL_HpkeOpen(ctxR, aad->x, aad->len, cipher, cipherLen, plain, &plainLen), CRYPT_SUCCESS); ASSERT_COMPARE("hpke open cmp", plain, plainLen, pt->x, pt->len); ASSERT_EQ(CRYPT_EAL_HpkeGetSeq(ctxR, &nextSeq), CRYPT_SUCCESS); ASSERT_EQ(nextSeq, seq + 1); EXIT: CRYPT_EAL_HpkeFreeCtx(ctxS); CRYPT_EAL_HpkeFreeCtx(ctxR); CRYPT_EAL_PkeyFreeCtx(pkeyE); CRYPT_EAL_PkeyFreeCtx(pkeyR); CRYPT_EAL_PkeyFreeCtx(pkeyS); TestRandDeInit(); } /* END_CASE */ /** * @test SDV_CRYPT_EAL_HPKE_EXPORT_SECRET_TC001 * @title hpke export secret test based on standard vectors. */ /* BEGIN_CASE */ void SDV_CRYPT_EAL_HPKE_EXPORT_SECRET_TC001(int mode, int kemId, int kdfId, int aeadId, Hex *info, Hex *psk, Hex *pskId, Hex *ikmE, Hex *ikmR, Hex *ikmS, Hex *exporterContext, int L, Hex *exportedValue) { ASSERT_EQ(TestRandInit(), CRYPT_SUCCESS); CRYPT_HPKE_CipherSuite cipherSuite = {kemId, kdfId, aeadId}; CRYPT_EAL_HpkeCtx *ctxS = NULL; CRYPT_EAL_HpkeCtx *ctxR = NULL; CRYPT_EAL_PkeyCtx *pkeyE = NULL; CRYPT_EAL_PkeyCtx *pkeyR = NULL; CRYPT_EAL_PkeyCtx *pkeyS = NULL; uint8_t encapsulatedKey[HPKE_KEM_MAX_ENCAPSULATED_KEY_LEN]; uint32_t encapsulatedKeyLen = HPKE_KEM_MAX_ENCAPSULATED_KEY_LEN; ASSERT_EQ(GenerateHpkeCtxSAndCtxR(mode, cipherSuite, info, psk, pskId, ikmE, ikmR, ikmS, &ctxS, &ctxR, &pkeyE, &pkeyR, &pkeyS, encapsulatedKey, &encapsulatedKeyLen), CRYPT_SUCCESS); uint8_t exportedValueBuf[HPKE_HKDF_MAX_EXTRACT_KEY_LEN] = {0}; ASSERT_EQ(CRYPT_EAL_HpkeExportSecret(ctxS, exporterContext->x, exporterContext->len, exportedValueBuf, L), CRYPT_SUCCESS); ASSERT_COMPARE("hpke S exportedValue cmp", exportedValueBuf, exportedValue->len, exportedValue->x, exportedValue->len); memset(exportedValueBuf, 0, HPKE_HKDF_MAX_EXTRACT_KEY_LEN); ASSERT_EQ(CRYPT_EAL_HpkeExportSecret(ctxR, exporterContext->x, exporterContext->len, exportedValueBuf, L), CRYPT_SUCCESS); ASSERT_COMPARE("hpke R exportedValue cmp", exportedValueBuf, exportedValue->len, exportedValue->x, exportedValue->len); EXIT: CRYPT_EAL_HpkeFreeCtx(ctxS); CRYPT_EAL_HpkeFreeCtx(ctxR); CRYPT_EAL_PkeyFreeCtx(pkeyE); CRYPT_EAL_PkeyFreeCtx(pkeyR); CRYPT_EAL_PkeyFreeCtx(pkeyS); TestRandDeInit(); } /* END_CASE */ static int32_t HpkeTestSealAndOpen(CRYPT_EAL_HpkeCtx *ctxS, CRYPT_EAL_HpkeCtx *ctxR) { uint8_t massage[100]; uint32_t massageLen = 100; uint8_t plain[100]; uint32_t plainLen = 100; uint8_t cipherText[116]; uint32_t cipherTextLen = 116; int count = 100; while (count--) { #ifdef HITLS_CRYPTO_PROVIDER ASSERT_EQ(CRYPT_EAL_RandbytesEx(NULL, massage, massageLen), CRYPT_SUCCESS); #else ASSERT_EQ(CRYPT_EAL_Randbytes(massage, massageLen), CRYPT_SUCCESS); #endif ASSERT_EQ(CRYPT_EAL_HpkeSeal(ctxS, NULL, 0, massage, massageLen, cipherText, &cipherTextLen), CRYPT_SUCCESS); ASSERT_EQ(CRYPT_EAL_HpkeOpen(ctxR, NULL, 0, cipherText, cipherTextLen, plain, &plainLen), CRYPT_SUCCESS); ASSERT_COMPARE("hpke Seal Open cmp", massage, massageLen, plain, plainLen); } uint64_t seqS; uint64_t seqR; ASSERT_EQ(CRYPT_EAL_HpkeGetSeq(ctxS, &seqS), CRYPT_SUCCESS); ASSERT_EQ(CRYPT_EAL_HpkeGetSeq(ctxR, &seqR), CRYPT_SUCCESS); ASSERT_EQ(seqS, seqR); ASSERT_EQ(seqS, 100); count = 100; ASSERT_EQ(CRYPT_EAL_HpkeSetSeq(ctxS, 10000000), CRYPT_SUCCESS); ASSERT_EQ(CRYPT_EAL_HpkeSetSeq(ctxR, 10000000), CRYPT_SUCCESS); while (count--) { #ifdef HITLS_CRYPTO_PROVIDER ASSERT_EQ(CRYPT_EAL_RandbytesEx(NULL, massage, massageLen), CRYPT_SUCCESS); #else ASSERT_EQ(CRYPT_EAL_Randbytes(massage, massageLen), CRYPT_SUCCESS); #endif ASSERT_EQ(CRYPT_EAL_HpkeSeal(ctxS, NULL, 0, massage, massageLen, NULL, &cipherTextLen), CRYPT_SUCCESS); ASSERT_EQ(CRYPT_EAL_HpkeSeal(ctxS, NULL, 0, massage, massageLen, cipherText, &cipherTextLen), CRYPT_SUCCESS); ASSERT_EQ(CRYPT_EAL_HpkeOpen(ctxR, NULL, 0, cipherText, cipherTextLen, NULL, &plainLen), CRYPT_SUCCESS); ASSERT_EQ(CRYPT_EAL_HpkeOpen(ctxR, NULL, 0, cipherText, cipherTextLen, plain, &plainLen), CRYPT_SUCCESS); ASSERT_COMPARE("hpke Seal Open cmp", massage, massageLen, plain, plainLen); } ASSERT_EQ(CRYPT_EAL_HpkeGetSeq(ctxS, &seqS), CRYPT_SUCCESS); ASSERT_EQ(CRYPT_EAL_HpkeGetSeq(ctxR, &seqR), CRYPT_SUCCESS); ASSERT_EQ(seqS, seqR); ASSERT_EQ(seqS, 10000000 + 100); return CRYPT_SUCCESS; EXIT: return HPKE_ERR; } static int32_t HpkeRandomTest(CRYPT_HPKE_Mode mode, CRYPT_HPKE_KEM_AlgId kemId, CRYPT_HPKE_KDF_AlgId kdfId, CRYPT_HPKE_AEAD_AlgId aeadId) { CRYPT_HPKE_CipherSuite cipherSuite = {kemId, kdfId, aeadId}; CRYPT_EAL_HpkeCtx *ctxS = NULL; CRYPT_EAL_HpkeCtx *ctxR = NULL; CRYPT_EAL_PkeyCtx *pkeyE = NULL; CRYPT_EAL_PkeyCtx *pkeyR = NULL; CRYPT_EAL_PkeyCtx *pkeyS = NULL; Hex info = { 0 }; info.len = 16; uint8_t infoData[16] = { 0 }; info.x = infoData; int32_t ret = HPKE_ERR; #ifdef HITLS_CRYPTO_PROVIDER CRYPT_EAL_RandbytesEx(NULL, info.x, info.len); #else CRYPT_EAL_Randbytes(info.x, info.len); #endif Hex psk = { 0 }; psk.len = 32; uint8_t pskData[32] = { 0 }; psk.x = pskData; CRYPT_EAL_Randbytes(psk.x, psk.len); Hex pskId = { 0 }; pskId.len = 16; uint8_t pskIdData[16] = { 0 }; pskId.x = pskIdData; CRYPT_EAL_Randbytes(pskId.x, pskId.len); // prepare Recipient key ASSERT_EQ(CRYPT_EAL_HpkeGenerateKeyPair(NULL, NULL, cipherSuite, NULL, 0, &pkeyE), CRYPT_SUCCESS); // prepare Recipient key ASSERT_EQ(CRYPT_EAL_HpkeGenerateKeyPair(NULL, NULL, cipherSuite, NULL, 0, &pkeyR), CRYPT_SUCCESS); ASSERT_EQ(CRYPT_EAL_HpkeGenerateKeyPair(NULL, NULL, cipherSuite, NULL, 0, &pkeyS), CRYPT_SUCCESS); CRYPT_EAL_PkeyPub pubR; pubR.id = CRYPT_EAL_PkeyGetId(pkeyR); pubR.key.eccPub.len = HPKE_KEM_MAX_PUBLIC_KEY_LEN; uint8_t pubRKeyBuf[HPKE_KEM_MAX_PUBLIC_KEY_LEN]; pubR.key.eccPub.data = pubRKeyBuf; ASSERT_EQ(CRYPT_EAL_PkeyGetPub(pkeyR, &pubR), CRYPT_SUCCESS); // Sender init ctxS = CRYPT_EAL_HpkeNewCtx(NULL, NULL, CRYPT_HPKE_SENDER, mode, cipherSuite); ASSERT_TRUE(ctxS != NULL); uint8_t encapsulatedKey[HPKE_KEM_MAX_ENCAPSULATED_KEY_LEN]; uint32_t encapsulatedKeyLen = HPKE_KEM_MAX_ENCAPSULATED_KEY_LEN; if(mode == CRYPT_HPKE_MODE_AUTH || mode ==CRYPT_HPKE_MODE_AUTH_PSK){ ASSERT_EQ(CRYPT_EAL_HpkeSetAuthPriKey(ctxS, pkeyS), CRYPT_SUCCESS); } if (mode != CRYPT_HPKE_MODE_PSK && mode != CRYPT_HPKE_MODE_AUTH_PSK) { ASSERT_EQ(CRYPT_EAL_HpkeSetPsk(ctxS, psk.x, psk.len, pskId.x, pskId.len), CRYPT_HPKE_ERR_CALL); } if(mode != CRYPT_HPKE_MODE_AUTH && mode != CRYPT_HPKE_MODE_AUTH_PSK){ ASSERT_EQ(CRYPT_EAL_HpkeSetAuthPriKey(ctxS, pkeyS), CRYPT_HPKE_ERR_CALL); } if(mode == CRYPT_HPKE_MODE_PSK || mode == CRYPT_HPKE_MODE_AUTH_PSK){ ASSERT_EQ(CRYPT_EAL_HpkeSetPsk(ctxS, psk.x, psk.len, pskId.x, pskId.len), CRYPT_SUCCESS); } ASSERT_EQ(CRYPT_EAL_HpkeSetupSender(ctxS, NULL, info.x, info.len, pubR.key.eccPub.data, pubR.key.eccPub.len, encapsulatedKey, &encapsulatedKeyLen), CRYPT_SUCCESS); CRYPT_EAL_HpkeFreeCtx(ctxS); ctxS = CRYPT_EAL_HpkeNewCtx(NULL, NULL, CRYPT_HPKE_SENDER, mode, cipherSuite); ASSERT_TRUE(ctxS != NULL); if(mode == CRYPT_HPKE_MODE_PSK || mode == CRYPT_HPKE_MODE_AUTH_PSK){ ASSERT_EQ(CRYPT_EAL_HpkeSetPsk(ctxS, psk.x, psk.len, pskId.x, pskId.len), CRYPT_SUCCESS); } if(mode == CRYPT_HPKE_MODE_AUTH || mode ==CRYPT_HPKE_MODE_AUTH_PSK){ ASSERT_EQ(CRYPT_EAL_HpkeSetAuthPriKey(ctxS, pkeyS),CRYPT_SUCCESS); } ASSERT_EQ(CRYPT_EAL_HpkeSetupSender(ctxS, pkeyE, info.x, info.len, pubR.key.eccPub.data, pubR.key.eccPub.len, encapsulatedKey, &encapsulatedKeyLen), CRYPT_SUCCESS); // Recipient init ctxR = CRYPT_EAL_HpkeNewCtx(NULL, NULL, CRYPT_HPKE_RECIPIENT, mode, cipherSuite); ASSERT_TRUE(ctxR != NULL); if(mode == CRYPT_HPKE_MODE_PSK || mode == CRYPT_HPKE_MODE_AUTH_PSK){ ASSERT_EQ(CRYPT_EAL_HpkeSetPsk(ctxR, psk.x, psk.len, pskId.x, pskId.len), CRYPT_SUCCESS); } if(mode == CRYPT_HPKE_MODE_AUTH || mode ==CRYPT_HPKE_MODE_AUTH_PSK){ CRYPT_EAL_PkeyPub pubS; pubS.id = CRYPT_EAL_PkeyGetId(pkeyS); pubS.key.eccPub.len = HPKE_KEM_MAX_PUBLIC_KEY_LEN; uint8_t pubSKeyBuf[HPKE_KEM_MAX_PUBLIC_KEY_LEN]; pubS.key.eccPub.data = pubSKeyBuf; ASSERT_EQ(CRYPT_EAL_PkeyGetPub(pkeyS, &pubS), CRYPT_SUCCESS); ASSERT_EQ(CRYPT_EAL_HpkeSetAuthPubKey(ctxR,pubS.key.eccPub.data, pubS.key.eccPub.len),CRYPT_SUCCESS); } ASSERT_EQ(CRYPT_EAL_HpkeSetupRecipient(ctxR, pkeyR, info.x, info.len, encapsulatedKey, encapsulatedKeyLen), CRYPT_SUCCESS); ASSERT_EQ(HpkeTestSealAndOpen(ctxS, ctxR), CRYPT_SUCCESS); ret = CRYPT_SUCCESS; EXIT: CRYPT_EAL_HpkeFreeCtx(ctxS); CRYPT_EAL_HpkeFreeCtx(ctxR); CRYPT_EAL_PkeyFreeCtx(pkeyE); CRYPT_EAL_PkeyFreeCtx(pkeyS); CRYPT_EAL_PkeyFreeCtx(pkeyR); return ret; } /** * @test SDV_CRYPT_EAL_HPKE_TEST_RANDOMLY_TC001 * @title test key derivation, seal and open randomly. */ /* BEGIN_CASE */ void SDV_CRYPT_EAL_HPKE_TEST_RANDOMLY_TC001(void) { ASSERT_EQ(TestRandInit(), CRYPT_SUCCESS); CRYPT_HPKE_Mode modes[] = {CRYPT_HPKE_MODE_BASE}; CRYPT_HPKE_KEM_AlgId kemIds[] = {CRYPT_KEM_DHKEM_P256_HKDF_SHA256, CRYPT_KEM_DHKEM_P384_HKDF_SHA384, CRYPT_KEM_DHKEM_P521_HKDF_SHA512, CRYPT_KEM_DHKEM_X25519_HKDF_SHA256}; CRYPT_HPKE_KDF_AlgId kdfIds[] = {CRYPT_KDF_HKDF_SHA256, CRYPT_KDF_HKDF_SHA384, CRYPT_KDF_HKDF_SHA512}; CRYPT_HPKE_AEAD_AlgId aeadIds[] = {CRYPT_AEAD_AES_128_GCM, CRYPT_AEAD_AES_256_GCM, CRYPT_AEAD_CHACHA20_POLY1305}; size_t p; size_t i; size_t j; size_t k; for (p = 0; p < sizeof(modes) / sizeof(CRYPT_HPKE_Mode); p++) { for (i = 0; i < sizeof(kemIds) / sizeof(CRYPT_HPKE_KEM_AlgId); i++) { for (j = 0; j < sizeof(kdfIds) / sizeof(CRYPT_HPKE_KDF_AlgId); j++) { for (k = 0; k < sizeof(aeadIds) / sizeof(CRYPT_HPKE_AEAD_AlgId); k++) { ASSERT_EQ(HpkeRandomTest(modes[p], kemIds[i], kdfIds[j], aeadIds[k]), CRYPT_SUCCESS); } } } } EXIT: TestRandDeInit(); return; } /* END_CASE */ /** * @test SDV_CRYPT_EAL_HPKE_TEST_RANDOMLY_TC001 * @title test key derivation, seal and open randomly. */ /* BEGIN_CASE */ void SDV_CRYPT_EAL_HPKE_TEST_RANDOMLY_TC002(void) { ASSERT_EQ(TestRandInit(), CRYPT_SUCCESS); CRYPT_HPKE_Mode modes[] = {CRYPT_HPKE_MODE_PSK}; CRYPT_HPKE_KEM_AlgId kemIds[] = {CRYPT_KEM_DHKEM_P256_HKDF_SHA256, CRYPT_KEM_DHKEM_P384_HKDF_SHA384, CRYPT_KEM_DHKEM_P521_HKDF_SHA512, CRYPT_KEM_DHKEM_X25519_HKDF_SHA256}; CRYPT_HPKE_KDF_AlgId kdfIds[] = {CRYPT_KDF_HKDF_SHA256, CRYPT_KDF_HKDF_SHA384, CRYPT_KDF_HKDF_SHA512}; CRYPT_HPKE_AEAD_AlgId aeadIds[] = {CRYPT_AEAD_AES_128_GCM, CRYPT_AEAD_AES_256_GCM, CRYPT_AEAD_CHACHA20_POLY1305}; size_t p; size_t i; size_t j; size_t k; for (p = 0; p < sizeof(modes) / sizeof(CRYPT_HPKE_Mode); p++) { for (i = 0; i < sizeof(kemIds) / sizeof(CRYPT_HPKE_KEM_AlgId); i++) { for (j = 0; j < sizeof(kdfIds) / sizeof(CRYPT_HPKE_KDF_AlgId); j++) { for (k = 0; k < sizeof(aeadIds) / sizeof(CRYPT_HPKE_AEAD_AlgId); k++) { ASSERT_EQ(HpkeRandomTest(modes[p], kemIds[i], kdfIds[j], aeadIds[k]), CRYPT_SUCCESS); } } } } EXIT: TestRandDeInit(); return; } /* END_CASE */ /** * @test SDV_CRYPT_EAL_HPKE_TEST_RANDOMLY_TC001 * @title test key derivation, seal and open randomly. */ /* BEGIN_CASE */ void SDV_CRYPT_EAL_HPKE_TEST_RANDOMLY_TC003(void) { ASSERT_EQ(TestRandInit(), CRYPT_SUCCESS); CRYPT_HPKE_Mode modes[] = {CRYPT_HPKE_MODE_AUTH}; CRYPT_HPKE_KEM_AlgId kemIds[] = {CRYPT_KEM_DHKEM_P256_HKDF_SHA256, CRYPT_KEM_DHKEM_P384_HKDF_SHA384, CRYPT_KEM_DHKEM_P521_HKDF_SHA512, CRYPT_KEM_DHKEM_X25519_HKDF_SHA256}; CRYPT_HPKE_KDF_AlgId kdfIds[] = {CRYPT_KDF_HKDF_SHA256, CRYPT_KDF_HKDF_SHA384, CRYPT_KDF_HKDF_SHA512}; CRYPT_HPKE_AEAD_AlgId aeadIds[] = {CRYPT_AEAD_AES_128_GCM, CRYPT_AEAD_AES_256_GCM, CRYPT_AEAD_CHACHA20_POLY1305}; size_t p; size_t i; size_t j; size_t k; for (p = 0; p < sizeof(modes) / sizeof(CRYPT_HPKE_Mode); p++) { for (i = 0; i < sizeof(kemIds) / sizeof(CRYPT_HPKE_KEM_AlgId); i++) { for (j = 0; j < sizeof(kdfIds) / sizeof(CRYPT_HPKE_KDF_AlgId); j++) { for (k = 0; k < sizeof(aeadIds) / sizeof(CRYPT_HPKE_AEAD_AlgId); k++) { ASSERT_EQ(HpkeRandomTest(modes[p], kemIds[i], kdfIds[j], aeadIds[k]), CRYPT_SUCCESS); } } } } EXIT: TestRandDeInit(); return; } /* END_CASE */ /** * @test SDV_CRYPT_EAL_HPKE_TEST_RANDOMLY_TC001 * @title test key derivation, seal and open randomly. */ /* BEGIN_CASE */ void SDV_CRYPT_EAL_HPKE_TEST_RANDOMLY_TC004(void) { ASSERT_EQ(TestRandInit(), CRYPT_SUCCESS); CRYPT_HPKE_Mode modes[] = {CRYPT_HPKE_MODE_AUTH_PSK}; CRYPT_HPKE_KEM_AlgId kemIds[] = {CRYPT_KEM_DHKEM_P256_HKDF_SHA256, CRYPT_KEM_DHKEM_P384_HKDF_SHA384, CRYPT_KEM_DHKEM_P521_HKDF_SHA512, CRYPT_KEM_DHKEM_X25519_HKDF_SHA256}; CRYPT_HPKE_KDF_AlgId kdfIds[] = {CRYPT_KDF_HKDF_SHA256, CRYPT_KDF_HKDF_SHA384, CRYPT_KDF_HKDF_SHA512}; CRYPT_HPKE_AEAD_AlgId aeadIds[] = {CRYPT_AEAD_AES_128_GCM, CRYPT_AEAD_AES_256_GCM, CRYPT_AEAD_CHACHA20_POLY1305}; size_t p; size_t i; size_t j; size_t k; for (p = 0; p < sizeof(modes) / sizeof(CRYPT_HPKE_Mode); p++) { for (i = 0; i < sizeof(kemIds) / sizeof(CRYPT_HPKE_KEM_AlgId); i++) { for (j = 0; j < sizeof(kdfIds) / sizeof(CRYPT_HPKE_KDF_AlgId); j++) { for (k = 0; k < sizeof(aeadIds) / sizeof(CRYPT_HPKE_AEAD_AlgId); k++) { ASSERT_EQ(HpkeRandomTest(modes[p], kemIds[i], kdfIds[j], aeadIds[k]), CRYPT_SUCCESS); } } } } EXIT: TestRandDeInit(); return; } /* END_CASE */ /** * @test SDV_CRYPT_EAL_HPKE_ABNORMAL_TC001 * @title hpke abnormal test. */ /* BEGIN_CASE */ void SDV_CRYPT_EAL_HPKE_ABNORMAL_TC001(int role) { ASSERT_EQ(TestRandInit(), CRYPT_SUCCESS); int32_t ret; CRYPT_EAL_HpkeCtx *hpkeCtx = NULL; CRYPT_HPKE_CipherSuite cipherSuite = {0, 0, 0}; uint8_t massage[100]; uint32_t massageLen = 100; uint8_t buff[100]; uint32_t buffLen = 100; uint8_t cipherText[116]; uint32_t cipherTextLen = 116; hpkeCtx = CRYPT_EAL_HpkeNewCtx(NULL, NULL, role, CRYPT_HPKE_MODE_BASE, cipherSuite); ASSERT_TRUE(hpkeCtx == NULL); // test sender cipherSuite.kemId = CRYPT_KEM_DHKEM_P256_HKDF_SHA256; cipherSuite.kdfId = CRYPT_KDF_HKDF_SHA256; cipherSuite.aeadId = CRYPT_AEAD_AES_128_GCM; #ifdef HITLS_CRYPTO_PROVIDER hpkeCtx = CRYPT_EAL_HpkeNewCtx(NULL, "provider=none", role, CRYPT_HPKE_MODE_BASE, cipherSuite); ASSERT_TRUE(hpkeCtx == NULL); hpkeCtx = CRYPT_EAL_HpkeNewCtx(NULL, "provider=default", role, CRYPT_HPKE_MODE_BASE, cipherSuite); ASSERT_TRUE(hpkeCtx != NULL); CRYPT_EAL_HpkeFreeCtx(hpkeCtx); #endif hpkeCtx = CRYPT_EAL_HpkeNewCtx(NULL, NULL, role, CRYPT_HPKE_MODE_BASE, cipherSuite); ASSERT_TRUE(hpkeCtx != NULL); ret = CRYPT_EAL_HpkeSetupSender(hpkeCtx, NULL, NULL, 0, NULL, 0, NULL, NULL); if (role == CRYPT_HPKE_SENDER) { ASSERT_EQ(ret, CRYPT_NULL_INPUT); } else { ASSERT_EQ(ret, CRYPT_HPKE_ERR_CALL); } ret = CRYPT_EAL_HpkeSetupRecipient(hpkeCtx, NULL, NULL, 0, NULL, 0); if (role == CRYPT_HPKE_RECIPIENT) { ASSERT_EQ(ret, CRYPT_NULL_INPUT); } else { ASSERT_EQ(ret, CRYPT_HPKE_ERR_CALL); } ASSERT_EQ(CRYPT_EAL_HpkeSeal(hpkeCtx, NULL, 0, massage, massageLen, cipherText, &cipherTextLen), CRYPT_HPKE_ERR_CALL); ASSERT_EQ(CRYPT_EAL_HpkeSeal(NULL, NULL, 0, massage, massageLen, cipherText, &cipherTextLen), CRYPT_NULL_INPUT); ASSERT_EQ(CRYPT_EAL_HpkeSetSeq(NULL, 0), CRYPT_NULL_INPUT); ASSERT_EQ(CRYPT_EAL_HpkeSetSeq(hpkeCtx, 0xFFFFFFFFFFFFFFFF), CRYPT_INVALID_ARG); ASSERT_EQ(CRYPT_EAL_HpkeOpen(hpkeCtx, NULL, 0, massage, massageLen, cipherText, &cipherTextLen), CRYPT_HPKE_ERR_CALL); ASSERT_EQ(CRYPT_EAL_HpkeExportSecret(hpkeCtx, NULL, 0, buff, 0), CRYPT_NULL_INPUT); ASSERT_EQ(CRYPT_EAL_HpkeExportSecret(hpkeCtx, NULL, 0, buff, buffLen), CRYPT_HPKE_ERR_CALL); ASSERT_EQ(CRYPT_EAL_HpkeGenerateKeyPair(NULL, NULL, cipherSuite, NULL, 0, NULL), CRYPT_NULL_INPUT); CRYPT_EAL_PkeyCtx *pkey = NULL; uint8_t ikm[10]; ASSERT_EQ(CRYPT_EAL_HpkeGenerateKeyPair(NULL, NULL, cipherSuite, ikm, 10, &pkey), CRYPT_INVALID_ARG); EXIT: CRYPT_EAL_HpkeFreeCtx(hpkeCtx); TestRandDeInit(); } /* END_CASE */ static CRYPT_EAL_HpkeCtx *GenHpkeCtxWithSharedSecret(CRYPT_HPKE_Role role, CRYPT_HPKE_Mode mode, CRYPT_HPKE_CipherSuite cipherSuite, uint8_t *info, uint32_t infoLen, uint8_t* psk,uint32_t pskLen, uint8_t *pskId, uint32_t pskIdLen, uint8_t *sharedSecret, uint32_t sharedSecretLen) { CRYPT_EAL_HpkeCtx *ctx = NULL; ctx = CRYPT_EAL_HpkeNewCtx(NULL, NULL, role, mode, cipherSuite); ASSERT_TRUE(ctx != NULL); if(mode == CRYPT_HPKE_MODE_PSK || mode == CRYPT_HPKE_MODE_AUTH_PSK){ ASSERT_EQ(CRYPT_EAL_HpkeSetPsk(ctx, psk, pskLen, pskId, pskIdLen), CRYPT_SUCCESS); } ASSERT_EQ(CRYPT_EAL_HpkeSetSharedSecret(ctx, info, infoLen, sharedSecret, sharedSecretLen), CRYPT_SUCCESS); return ctx; EXIT: CRYPT_EAL_HpkeFreeCtx(ctx); return NULL; } static int32_t HpkeTestImportSharedSecret(CRYPT_HPKE_Mode mode, CRYPT_HPKE_CipherSuite cipherSuite) { CRYPT_EAL_HpkeCtx *ctxS = NULL; CRYPT_EAL_HpkeCtx *ctxR = NULL; uint32_t sharedSecretLen = 32; // CRYPT_KEM_DHKEM_X25519_HKDF_SHA256 CRYPT_KEM_DHKEM_P256_HKDF_SHA256 if (cipherSuite.kemId == CRYPT_KEM_DHKEM_P384_HKDF_SHA384) { sharedSecretLen = 48; } else if (cipherSuite.kemId == CRYPT_KEM_DHKEM_P521_HKDF_SHA512) { sharedSecretLen = 64; } uint8_t psk[10]={0}; uint32_t pskLen=10; uint8_t pskId[10]={0}; uint32_t pskIdLen=10; uint8_t sharedSecret[HPKE_KEM_MAX_SHARED_KEY_LEN]; ctxS = GenHpkeCtxWithSharedSecret(CRYPT_HPKE_SENDER, mode, cipherSuite, NULL, 0, psk, pskLen, pskId, pskIdLen, sharedSecret, sharedSecretLen); ASSERT_TRUE(ctxS != NULL); ctxR = GenHpkeCtxWithSharedSecret(CRYPT_HPKE_RECIPIENT, mode, cipherSuite, NULL, 0, psk, pskLen, pskId, pskIdLen, sharedSecret, sharedSecretLen); ASSERT_TRUE(ctxR != NULL); ASSERT_EQ(HpkeTestSealAndOpen(ctxS, ctxR), CRYPT_SUCCESS); EXIT: CRYPT_EAL_HpkeFreeCtx(ctxS); CRYPT_EAL_HpkeFreeCtx(ctxR); return CRYPT_SUCCESS; } /** * @test SDV_CRYPT_EAL_HPKE_SHARED_SECRET_RANDOMLY_TC001 * @title import shared secret test randomly. */ /* BEGIN_CASE */ void SDV_CRYPT_EAL_HPKE_SHARED_SECRET_RANDOMLY_TC001(void) { ASSERT_EQ(TestRandInit(), CRYPT_SUCCESS); CRYPT_HPKE_Mode mode = CRYPT_HPKE_MODE_BASE; CRYPT_HPKE_KEM_AlgId kemIds[] = {CRYPT_KEM_DHKEM_P256_HKDF_SHA256, CRYPT_KEM_DHKEM_P384_HKDF_SHA384, CRYPT_KEM_DHKEM_P521_HKDF_SHA512}; CRYPT_HPKE_KDF_AlgId kdfIds[] = {CRYPT_KDF_HKDF_SHA256, CRYPT_KDF_HKDF_SHA384, CRYPT_KDF_HKDF_SHA512}; CRYPT_HPKE_AEAD_AlgId aeadIds[] = {CRYPT_AEAD_AES_128_GCM, CRYPT_AEAD_AES_256_GCM, CRYPT_AEAD_CHACHA20_POLY1305}; size_t i; size_t j; size_t k; for (i = 0; i < sizeof(kemIds) / sizeof(CRYPT_HPKE_KEM_AlgId); i++) { for (j = 0; j < sizeof(kdfIds) / sizeof(CRYPT_HPKE_KDF_AlgId); j++) { for (k = 0; k < sizeof(aeadIds) / sizeof(CRYPT_HPKE_AEAD_AlgId); k++) { CRYPT_HPKE_CipherSuite cipherSuite = {kemIds[i], kdfIds[j], aeadIds[k]}; ASSERT_EQ(HpkeTestImportSharedSecret(mode, cipherSuite), CRYPT_SUCCESS); } } } EXIT: TestRandDeInit(); } /* END_CASE */ /** * @test SDV_CRYPT_EAL_HPKE_SHARED_SECRET_RANDOMLY_TC001 * @title import shared secret test randomly. */ /* BEGIN_CASE */ void SDV_CRYPT_EAL_HPKE_SHARED_SECRET_RANDOMLY_TC002(void) { ASSERT_EQ(TestRandInit(), CRYPT_SUCCESS); CRYPT_HPKE_Mode mode = CRYPT_HPKE_MODE_PSK; CRYPT_HPKE_KEM_AlgId kemIds[] = {CRYPT_KEM_DHKEM_P256_HKDF_SHA256, CRYPT_KEM_DHKEM_P384_HKDF_SHA384, CRYPT_KEM_DHKEM_P521_HKDF_SHA512}; CRYPT_HPKE_KDF_AlgId kdfIds[] = {CRYPT_KDF_HKDF_SHA256, CRYPT_KDF_HKDF_SHA384, CRYPT_KDF_HKDF_SHA512}; CRYPT_HPKE_AEAD_AlgId aeadIds[] = {CRYPT_AEAD_AES_128_GCM, CRYPT_AEAD_AES_256_GCM, CRYPT_AEAD_CHACHA20_POLY1305}; size_t i; size_t j; size_t k; for (i = 0; i < sizeof(kemIds) / sizeof(CRYPT_HPKE_KEM_AlgId); i++) { for (j = 0; j < sizeof(kdfIds) / sizeof(CRYPT_HPKE_KDF_AlgId); j++) { for (k = 0; k < sizeof(aeadIds) / sizeof(CRYPT_HPKE_AEAD_AlgId); k++) { CRYPT_HPKE_CipherSuite cipherSuite = {kemIds[i], kdfIds[j], aeadIds[k]}; ASSERT_EQ(HpkeTestImportSharedSecret(mode, cipherSuite), CRYPT_SUCCESS); } } } EXIT: TestRandDeInit(); } /* END_CASE */ /** * @test SDV_CRYPT_EAL_HPKE_SHARED_SECRET_RANDOMLY_TC001 * @title import shared secret test randomly. */ /* BEGIN_CASE */ void SDV_CRYPT_EAL_HPKE_SHARED_SECRET_RANDOMLY_TC003(void) { ASSERT_EQ(TestRandInit(), CRYPT_SUCCESS); CRYPT_HPKE_Mode mode = CRYPT_HPKE_MODE_AUTH; CRYPT_HPKE_KEM_AlgId kemIds[] = {CRYPT_KEM_DHKEM_P256_HKDF_SHA256, CRYPT_KEM_DHKEM_P384_HKDF_SHA384, CRYPT_KEM_DHKEM_P521_HKDF_SHA512}; CRYPT_HPKE_KDF_AlgId kdfIds[] = {CRYPT_KDF_HKDF_SHA256, CRYPT_KDF_HKDF_SHA384, CRYPT_KDF_HKDF_SHA512}; CRYPT_HPKE_AEAD_AlgId aeadIds[] = {CRYPT_AEAD_AES_128_GCM, CRYPT_AEAD_AES_256_GCM, CRYPT_AEAD_CHACHA20_POLY1305}; size_t i; size_t j; size_t k; for (i = 0; i < sizeof(kemIds) / sizeof(CRYPT_HPKE_KEM_AlgId); i++) { for (j = 0; j < sizeof(kdfIds) / sizeof(CRYPT_HPKE_KDF_AlgId); j++) { for (k = 0; k < sizeof(aeadIds) / sizeof(CRYPT_HPKE_AEAD_AlgId); k++) { CRYPT_HPKE_CipherSuite cipherSuite = {kemIds[i], kdfIds[j], aeadIds[k]}; ASSERT_EQ(HpkeTestImportSharedSecret(mode, cipherSuite), CRYPT_SUCCESS); } } } EXIT: TestRandDeInit(); } /* END_CASE */ /** * @test SDV_CRYPT_EAL_HPKE_SHARED_SECRET_RANDOMLY_TC001 * @title import shared secret test randomly. */ /* BEGIN_CASE */ void SDV_CRYPT_EAL_HPKE_SHARED_SECRET_RANDOMLY_TC004(void) { ASSERT_EQ(TestRandInit(), CRYPT_SUCCESS); CRYPT_HPKE_Mode mode = CRYPT_HPKE_MODE_AUTH_PSK; CRYPT_HPKE_KEM_AlgId kemIds[] = {CRYPT_KEM_DHKEM_P256_HKDF_SHA256, CRYPT_KEM_DHKEM_P384_HKDF_SHA384, CRYPT_KEM_DHKEM_P521_HKDF_SHA512}; CRYPT_HPKE_KDF_AlgId kdfIds[] = {CRYPT_KDF_HKDF_SHA256, CRYPT_KDF_HKDF_SHA384, CRYPT_KDF_HKDF_SHA512}; CRYPT_HPKE_AEAD_AlgId aeadIds[] = {CRYPT_AEAD_AES_128_GCM, CRYPT_AEAD_AES_256_GCM, CRYPT_AEAD_CHACHA20_POLY1305}; size_t i; size_t j; size_t k; for (i = 0; i < sizeof(kemIds) / sizeof(CRYPT_HPKE_KEM_AlgId); i++) { for (j = 0; j < sizeof(kdfIds) / sizeof(CRYPT_HPKE_KDF_AlgId); j++) { for (k = 0; k < sizeof(aeadIds) / sizeof(CRYPT_HPKE_AEAD_AlgId); k++) { CRYPT_HPKE_CipherSuite cipherSuite = {kemIds[i], kdfIds[j], aeadIds[k]}; ASSERT_EQ(HpkeTestImportSharedSecret(mode, cipherSuite), CRYPT_SUCCESS); } } } EXIT: TestRandDeInit(); } /* END_CASE */ /** * @test SDV_CRYPT_EAL_HPKE_SHARED_SECRET_TC001 * @title import sharedSecret and seal/open test based on standard vector. */ /* BEGIN_CASE */ void SDV_CRYPT_EAL_HPKE_SHARED_SECRET_TC001(int mode, int kemId, int kdfId, int aeadId, Hex *info, Hex *psk, Hex *pskId, Hex *sharedSecret, int seq, Hex *pt, Hex *aad, Hex *ct) { ASSERT_EQ(TestRandInit(), CRYPT_SUCCESS); CRYPT_HPKE_CipherSuite cipherSuite = {kemId, kdfId, aeadId}; CRYPT_EAL_HpkeCtx *ctxS = NULL; CRYPT_EAL_HpkeCtx *ctxR = NULL; ctxS = GenHpkeCtxWithSharedSecret(CRYPT_HPKE_SENDER, mode, cipherSuite, info->x, info->len, psk->x, psk->len, pskId->x, pskId->len, sharedSecret->x, sharedSecret->len); ASSERT_TRUE(ctxS != NULL); ctxR = GenHpkeCtxWithSharedSecret(CRYPT_HPKE_RECIPIENT, mode, cipherSuite, info->x, info->len, psk->x, psk->len, pskId->x, pskId->len, sharedSecret->x, sharedSecret->len); ASSERT_TRUE(ctxR != NULL); uint8_t cipher[200] = { 0 }; uint32_t cipherLen = 200; ASSERT_EQ(CRYPT_EAL_HpkeSetSeq(ctxS, seq), CRYPT_SUCCESS); ASSERT_EQ(CRYPT_EAL_HpkeSeal(ctxS, aad->x, aad->len, pt->x, pt->len, cipher, &cipherLen), CRYPT_SUCCESS); ASSERT_COMPARE("hpke seal cmp", cipher, cipherLen, ct->x, ct->len); uint64_t nextSeq; ASSERT_EQ(CRYPT_EAL_HpkeGetSeq(ctxS, &nextSeq), CRYPT_SUCCESS); ASSERT_EQ(nextSeq, seq + 1); uint8_t plain[200] = { 0 }; uint32_t plainLen = 200; ASSERT_EQ(CRYPT_EAL_HpkeSetSeq(ctxR, seq), CRYPT_SUCCESS); ASSERT_EQ(CRYPT_EAL_HpkeOpen(ctxR, aad->x, aad->len, cipher, cipherLen, plain, &plainLen), CRYPT_SUCCESS); ASSERT_COMPARE("hpke open cmp", plain, plainLen, pt->x, pt->len); ASSERT_EQ(CRYPT_EAL_HpkeGetSeq(ctxR, &nextSeq), CRYPT_SUCCESS); ASSERT_EQ(nextSeq, seq + 1); EXIT: CRYPT_EAL_HpkeFreeCtx(ctxS); CRYPT_EAL_HpkeFreeCtx(ctxR); TestRandDeInit(); } /* END_CASE */ /** * @test SDV_CRYPT_EAL_HPKE_SHARED_SECRET_TC002 * @title import sharedSecret and export secret test based on standard vector. */ /* BEGIN_CASE */ void SDV_CRYPT_EAL_HPKE_SHARED_SECRET_TC002(int mode, int kemId, int kdfId, int aeadId, Hex *info, Hex *psk,Hex *pskId,Hex *sharedSecret, Hex *exporterContext, int L, Hex *exportedValue) { ASSERT_EQ(TestRandInit(), CRYPT_SUCCESS); CRYPT_HPKE_CipherSuite cipherSuite = {kemId, kdfId, aeadId}; CRYPT_EAL_HpkeCtx *ctxS = NULL; CRYPT_EAL_HpkeCtx *ctxR = NULL; ctxS = GenHpkeCtxWithSharedSecret(CRYPT_HPKE_SENDER, mode, cipherSuite, info->x, info->len, psk->x, psk->len, pskId->x, pskId->len, sharedSecret->x, sharedSecret->len); ASSERT_TRUE(ctxS != NULL); ctxR = GenHpkeCtxWithSharedSecret(CRYPT_HPKE_RECIPIENT, mode, cipherSuite, info->x, info->len, psk->x, psk->len, pskId->x, pskId->len, sharedSecret->x, sharedSecret->len); ASSERT_TRUE(ctxR != NULL); uint8_t exportedValueBuf[HPKE_HKDF_MAX_EXTRACT_KEY_LEN] = {0}; ASSERT_EQ(CRYPT_EAL_HpkeExportSecret(ctxS, exporterContext->x, exporterContext->len, exportedValueBuf, L), CRYPT_SUCCESS); ASSERT_COMPARE("hpke S exportedValue cmp", exportedValueBuf, exportedValue->len, exportedValue->x, exportedValue->len); memset(exportedValueBuf, 0, HPKE_HKDF_MAX_EXTRACT_KEY_LEN); ASSERT_EQ(CRYPT_EAL_HpkeExportSecret(ctxR, exporterContext->x, exporterContext->len, exportedValueBuf, L), CRYPT_SUCCESS); ASSERT_COMPARE("hpke R exportedValue cmp", exportedValueBuf, exportedValue->len, exportedValue->x, exportedValue->len); EXIT: CRYPT_EAL_HpkeFreeCtx(ctxS); CRYPT_EAL_HpkeFreeCtx(ctxR); TestRandDeInit(); } /* END_CASE */ /** * @test SDV_CRYPT_EAL_HPKE_GENERATE_KEY_PAIR_TC001 * @title hpke generate key pair test. */ /* BEGIN_CASE */ void SDV_CRYPT_EAL_HPKE_GENERATE_KEY_PAIR_TC001(void) { ASSERT_EQ(TestRandInit(), CRYPT_SUCCESS); CRYPT_HPKE_KEM_AlgId kemIds[] = {CRYPT_KEM_DHKEM_P256_HKDF_SHA256, CRYPT_KEM_DHKEM_P384_HKDF_SHA384, CRYPT_KEM_DHKEM_P521_HKDF_SHA512}; CRYPT_HPKE_KDF_AlgId kdfIds[] = {CRYPT_KDF_HKDF_SHA256, CRYPT_KDF_HKDF_SHA384, CRYPT_KDF_HKDF_SHA512}; CRYPT_HPKE_AEAD_AlgId aeadIds[] = {CRYPT_AEAD_AES_128_GCM, CRYPT_AEAD_AES_256_GCM, CRYPT_AEAD_CHACHA20_POLY1305}; size_t i; size_t j; size_t k; for (i = 0; i < sizeof(kemIds) / sizeof(CRYPT_HPKE_KEM_AlgId); i++) { for (j = 0; j < sizeof(kdfIds) / sizeof(CRYPT_HPKE_KDF_AlgId); j++) { for (k = 0; k < sizeof(aeadIds) / sizeof(CRYPT_HPKE_AEAD_AlgId); k++) { CRYPT_HPKE_CipherSuite cipherSuite = {kemIds[i], kdfIds[j], aeadIds[k]}; CRYPT_EAL_PkeyCtx *pctx = NULL; ASSERT_EQ(CRYPT_EAL_HpkeGenerateKeyPair(NULL, NULL, cipherSuite, NULL, 0, &pctx), CRYPT_SUCCESS); CRYPT_EAL_PkeyFreeCtx(pctx); pctx = NULL; uint32_t ikmLen = 1024*1024; uint8_t *ikm = (uint8_t *)malloc(ikmLen); memset_s(ikm, ikmLen, 0xFF, ikmLen); ASSERT_EQ(CRYPT_EAL_HpkeGenerateKeyPair(NULL, NULL, cipherSuite, ikm, ikmLen, &pctx), CRYPT_SUCCESS); CRYPT_EAL_PkeyFreeCtx(pctx); free(ikm); } } } EXIT: TestRandDeInit(); } /* END_CASE */
2301_79861745/bench_create
testcode/sdv/testcase/crypto/hpke/test_suite_sdv_eal_hpke.c
C
unknown
39,326
/* * This file is part of the openHiTLS project. * * openHiTLS is licensed under the Mulan PSL v2. * You can use this software according to the terms and conditions of the Mulan PSL v2. * You may obtain a copy of Mulan PSL v2 at: * * http://license.coscl.org.cn/MulanPSL2 * * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, * EITHER EXPRESS 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 "bsl_sal.h" #include "bsl_err.h" #include "crypt_errno.h" #include "crypt_eal_pkey.h" #include "crypt_util_rand.h" #include "eal_pkey_local.h" #include "securec.h" /* END_HEADER */ /* @ * @test SDV_CRYPTO_HYBRID_API_TC001 * @spec - * @title Check the value returned by the ctrl interface meets the expectation. * @precon nan * @brief * 1.Create the context of the algorithm. * 2.Call CRYPT_EAL_PkeyCtrl to set and get parameters in the context. * @expect 1.success 2.success * @prior nan * @auto FALSE @ */ /* BEGIN_CASE */ void SDV_CRYPTO_HYBRID_API_TC001(int algid, int type, int ekLen, int ctLen, int skLen) { TestMemInit(); CRYPT_EAL_PkeyCtx *ctxA = CRYPT_EAL_PkeyNewCtx((int32_t)algid); ASSERT_TRUE(ctxA != NULL); int32_t val = CRYPT_PKEY_PARAID_MAX; ASSERT_EQ(CRYPT_EAL_PkeySetParaById(ctxA, val), CRYPT_ERR_ALGID); ASSERT_EQ(CRYPT_EAL_PkeyCtrl(ctxA, 0, &val, sizeof(val)), CRYPT_NOT_SUPPORT); val = (int32_t)type; ASSERT_EQ(CRYPT_EAL_PkeySetParaById(ctxA, val), CRYPT_SUCCESS); uint32_t encapsKeyLen = 0; ASSERT_EQ(CRYPT_EAL_PkeyCtrl(ctxA, CRYPT_CTRL_GET_PUBKEY_LEN, &encapsKeyLen, sizeof(encapsKeyLen)), CRYPT_SUCCESS); ASSERT_EQ(encapsKeyLen, ekLen); uint32_t cipherLen = 0; ASSERT_EQ(CRYPT_EAL_PkeyCtrl(ctxA, CRYPT_CTRL_GET_CIPHERTEXT_LEN, &cipherLen, sizeof(cipherLen)), CRYPT_SUCCESS); ASSERT_EQ(cipherLen, ctLen); uint32_t sharedLen = 0; ASSERT_EQ(CRYPT_EAL_PkeyCtrl(ctxA, CRYPT_CTRL_GET_SHARED_KEY_LEN, &sharedLen, sizeof(sharedLen)), CRYPT_SUCCESS); ASSERT_EQ(sharedLen, skLen); if (type != CRYPT_HYBRID_X25519_MLKEM512 && type != CRYPT_HYBRID_X25519_MLKEM768 && type != CRYPT_HYBRID_X25519_MLKEM1024) { val = CRYPT_POINT_COMPRESSED; ASSERT_EQ(CRYPT_EAL_PkeyCtrl(ctxA, CRYPT_CTRL_SET_ECC_POINT_FORMAT, &val, sizeof(val)), CRYPT_SUCCESS); } EXIT: CRYPT_EAL_PkeyFreeCtx(ctxA); return; } /* END_CASE */ /* @ * @test SDV_CRYPTO_HYBRID_ENCAPS_DECAPS_FUNC_TC001 * @spec - * @title Generating key pairs and key exchange tests * @precon nan * @brief * 1.Registers the callback function of the memory and random. * 2.Create a context for key exchange and set parameters. * 3.Generating a key pair. * 4.Perform key exchange. * 5.Check whether the shared keys are the same. * @expect 1.success 2.success 3.success 4.success 5.The shared key is the same. * @prior nan * @auto FALSE @ */ /* BEGIN_CASE */ void SDV_CRYPTO_HYBRID_ENCAPS_DECAPS_FUNC_TC001(int algid, int type, int isProvider) { TestMemInit(); CRYPT_RandRegist(TestSimpleRand); CRYPT_RandRegistEx(TestSimpleRandEx); CRYPT_EAL_PkeyCtx *ctxA = NULL; CRYPT_EAL_PkeyCtx *ctxB = NULL; #ifdef HITLS_CRYPTO_PROVIDER if (isProvider == 1) { ctxA = CRYPT_EAL_ProviderPkeyNewCtx(NULL, algid, CRYPT_EAL_PKEY_KEM_OPERATE, "provider=default"); ASSERT_TRUE(ctxA != NULL); ctxB = CRYPT_EAL_ProviderPkeyNewCtx(NULL, algid, CRYPT_EAL_PKEY_KEM_OPERATE, "provider=default"); ASSERT_TRUE(ctxB != NULL); } else #endif { (void) isProvider; ctxA = CRYPT_EAL_PkeyNewCtx(algid); ASSERT_TRUE(ctxA != NULL); ctxB = CRYPT_EAL_PkeyNewCtx(algid); ASSERT_TRUE(ctxB != NULL); } uint32_t val = (uint32_t)type; ASSERT_EQ(CRYPT_EAL_PkeySetParaById(ctxA, val), CRYPT_SUCCESS); ASSERT_EQ(CRYPT_EAL_PkeySetParaById(ctxB, val), CRYPT_SUCCESS); uint32_t encapsKeyLen = 0; ASSERT_EQ(CRYPT_EAL_PkeyCtrl(ctxA, CRYPT_CTRL_GET_PUBKEY_LEN, &encapsKeyLen, sizeof(encapsKeyLen)), CRYPT_SUCCESS); uint32_t cipherLen = 0; ASSERT_EQ(CRYPT_EAL_PkeyCtrl(ctxA, CRYPT_CTRL_GET_CIPHERTEXT_LEN, &cipherLen, sizeof(cipherLen)), CRYPT_SUCCESS); uint8_t *ciphertext = BSL_SAL_Malloc(cipherLen); CRYPT_EAL_PkeyPub ek = { 0 }; ek.id = algid; ek.key.kemEk.len = encapsKeyLen; ek.key.kemEk.data = BSL_SAL_Malloc(encapsKeyLen); ASSERT_TRUE(ek.key.kemEk.data != NULL); uint32_t sharedLenA = 0; ASSERT_EQ(CRYPT_EAL_PkeyCtrl(ctxA, CRYPT_CTRL_GET_SHARED_KEY_LEN, &sharedLenA, sizeof(sharedLenA)), CRYPT_SUCCESS); uint8_t *sharedKeyA = BSL_SAL_Malloc(sharedLenA); ASSERT_TRUE(sharedKeyA != NULL); uint32_t sharedLenB = sharedLenA; uint8_t *sharedKeyB = BSL_SAL_Malloc(sharedLenB); ASSERT_TRUE(sharedKeyB != NULL); ASSERT_EQ(CRYPT_EAL_PkeyGen(ctxA), CRYPT_SUCCESS); ASSERT_EQ(CRYPT_EAL_PkeyGetPub(ctxA, &ek), CRYPT_SUCCESS); ASSERT_EQ(CRYPT_EAL_PkeySetPub(ctxB, &ek), CRYPT_SUCCESS); ASSERT_EQ(CRYPT_EAL_PkeyEncaps(ctxB, ciphertext, &cipherLen, sharedKeyA, &sharedLenA), CRYPT_SUCCESS); ASSERT_EQ(CRYPT_EAL_PkeyDecaps(ctxA, ciphertext, cipherLen, sharedKeyB, &sharedLenB), CRYPT_SUCCESS); ASSERT_COMPARE("compare sharedKey", sharedKeyB, sharedLenB, sharedKeyA, sharedLenA); EXIT: BSL_SAL_Free(ek.key.kemEk.data); BSL_SAL_Free(ciphertext); BSL_SAL_Free(sharedKeyA); BSL_SAL_Free(sharedKeyB); CRYPT_EAL_PkeyFreeCtx(ctxA); CRYPT_EAL_PkeyFreeCtx(ctxB); CRYPT_RandRegist(NULL); CRYPT_RandRegistEx(NULL); return; } /* END_CASE */ /* Use default random numbers for end-to-end testing */ /* BEGIN_CASE */ void SDV_CRYPTO_HYBRID_ENCAPS_DECAPS_API_TC002(int algid, int type, int isProvider) { TestMemInit(); TestRandInit(); CRYPT_EAL_PkeyCtx *ctxA = NULL; CRYPT_EAL_PkeyCtx *ctxB = NULL; #ifdef HITLS_CRYPTO_PROVIDER if (isProvider == 1) { ctxA = CRYPT_EAL_ProviderPkeyNewCtx(NULL, algid, CRYPT_EAL_PKEY_KEM_OPERATE, "provider=default"); ASSERT_TRUE(ctxA != NULL); ctxB = CRYPT_EAL_ProviderPkeyNewCtx(NULL, algid, CRYPT_EAL_PKEY_KEM_OPERATE, "provider=default"); ASSERT_TRUE(ctxB != NULL); } else #endif { (void) isProvider; ctxA = CRYPT_EAL_PkeyNewCtx(algid); ASSERT_TRUE(ctxA != NULL); ctxB = CRYPT_EAL_PkeyNewCtx(algid); ASSERT_TRUE(ctxB != NULL); } uint32_t val = (uint32_t)type; ASSERT_EQ(CRYPT_EAL_PkeySetParaById(ctxA, val), CRYPT_SUCCESS); ASSERT_EQ(CRYPT_EAL_PkeySetParaById(ctxB, val), CRYPT_SUCCESS); uint32_t encapsKeyLen = 0; ASSERT_EQ(CRYPT_EAL_PkeyCtrl(ctxA, CRYPT_CTRL_GET_PUBKEY_LEN, &encapsKeyLen, sizeof(encapsKeyLen)), CRYPT_SUCCESS); uint32_t cipherLen = 0; ASSERT_EQ(CRYPT_EAL_PkeyCtrl(ctxA, CRYPT_CTRL_GET_CIPHERTEXT_LEN, &cipherLen, sizeof(cipherLen)), CRYPT_SUCCESS); uint8_t *ciphertext = BSL_SAL_Malloc(cipherLen); CRYPT_EAL_PkeyPub ek = { 0 }; ek.id = algid; ek.key.kemEk.len = encapsKeyLen; ek.key.kemEk.data = BSL_SAL_Malloc(encapsKeyLen); ASSERT_TRUE(ek.key.kemEk.data != NULL); uint32_t sharedLenA = 0; ASSERT_EQ(CRYPT_EAL_PkeyCtrl(ctxA, CRYPT_CTRL_GET_SHARED_KEY_LEN, &sharedLenA, sizeof(sharedLenA)), CRYPT_SUCCESS); uint8_t *sharedKeyA = BSL_SAL_Malloc(sharedLenA); ASSERT_TRUE(sharedKeyA != NULL); uint32_t sharedLenB = sharedLenA; uint8_t *sharedKeyB = BSL_SAL_Malloc(sharedLenB); ASSERT_TRUE(sharedKeyB != NULL); ASSERT_EQ(CRYPT_EAL_PkeyGen(ctxA), CRYPT_SUCCESS); ASSERT_EQ(CRYPT_EAL_PkeyGetPub(ctxA, &ek), CRYPT_SUCCESS); ASSERT_EQ(CRYPT_EAL_PkeySetPub(ctxB, &ek), CRYPT_SUCCESS); ASSERT_EQ(CRYPT_EAL_PkeyEncaps(ctxB, ciphertext, &cipherLen, sharedKeyA, &sharedLenA), CRYPT_SUCCESS); ASSERT_EQ(CRYPT_EAL_PkeyDecaps(ctxA, ciphertext, cipherLen, sharedKeyB, &sharedLenB), CRYPT_SUCCESS); EXIT: BSL_SAL_Free(ek.key.kemEk.data); BSL_SAL_Free(ciphertext); BSL_SAL_Free(sharedKeyA); BSL_SAL_Free(sharedKeyB); CRYPT_EAL_PkeyFreeCtx(ctxA); CRYPT_EAL_PkeyFreeCtx(ctxB); TestRandDeInit(); return; } /* END_CASE */ /* @ * @test SDV_CRYPTO_HYBRID_ENCAPS_DECAPS_FUNC_TC002 * @spec - * @title Setting the key pair and key exchange test * @precon nan * @brief * 1.Registers the callback function of the memory and random. * 2.Create a context for key exchange and set parameters. * 3.Setting a key pair. * 4.Perform key exchange. * 5.Check whether the shared keys are the same. * @expect 1.success 2.success 3.success 4.success 5.The shared key is the same. * @prior nan * @auto FALSE @ */ /* BEGIN_CASE */ void SDV_CRYPTO_HYBRID_ENCAPS_DECAPS_FUNC_TC002(int algid, int type, int isProvider, Hex *encapsKeyA, Hex *decapsKeyA) { TestMemInit(); CRYPT_RandRegist(TestSimpleRand); CRYPT_RandRegistEx(TestSimpleRandEx); CRYPT_EAL_PkeyCtx *ctxA = NULL; CRYPT_EAL_PkeyCtx *ctxB = NULL; #ifdef HITLS_CRYPTO_PROVIDER if (isProvider == 1) { ctxA = CRYPT_EAL_ProviderPkeyNewCtx(NULL, algid, CRYPT_EAL_PKEY_KEM_OPERATE, "provider=default"); ASSERT_TRUE(ctxA != NULL); ctxB = CRYPT_EAL_ProviderPkeyNewCtx(NULL, algid, CRYPT_EAL_PKEY_KEM_OPERATE, "provider=default"); ASSERT_TRUE(ctxB != NULL); } else #endif { (void)isProvider; ctxA = CRYPT_EAL_PkeyNewCtx(algid); ASSERT_TRUE(ctxA != NULL); ctxB = CRYPT_EAL_PkeyNewCtx(algid); ASSERT_TRUE(ctxB != NULL); } uint32_t val = (uint32_t)type; ASSERT_EQ(CRYPT_EAL_PkeySetParaById(ctxA, val), CRYPT_SUCCESS); ASSERT_EQ(CRYPT_EAL_PkeySetParaById(ctxB, val), CRYPT_SUCCESS); uint32_t cipherLen = 0; ASSERT_EQ(CRYPT_EAL_PkeyCtrl(ctxA, CRYPT_CTRL_GET_CIPHERTEXT_LEN, &cipherLen, sizeof(cipherLen)), CRYPT_SUCCESS); uint8_t *ciphertext = BSL_SAL_Malloc(cipherLen); uint32_t sharedLenA = 0; ASSERT_EQ(CRYPT_EAL_PkeyCtrl(ctxA, CRYPT_CTRL_GET_SHARED_KEY_LEN, &sharedLenA, sizeof(sharedLenA)), CRYPT_SUCCESS); uint8_t *sharedKeyA = BSL_SAL_Malloc(sharedLenA); ASSERT_TRUE(sharedKeyA != NULL); uint32_t sharedLenB = sharedLenA; uint8_t *sharedKeyB = BSL_SAL_Malloc(sharedLenB); ASSERT_TRUE(sharedKeyB != NULL); CRYPT_EAL_PkeyPub ek = { 0 }; ek.id = algid; ek.key.kemEk.len = encapsKeyA->len; ek.key.kemEk.data = encapsKeyA->x; ASSERT_EQ(CRYPT_EAL_PkeySetPub(ctxA, &ek), CRYPT_SUCCESS); CRYPT_EAL_PkeyPrv dk = { 0 }; dk.id = algid; dk.key.kemDk.len = decapsKeyA->len; dk.key.kemDk.data = decapsKeyA->x; ASSERT_EQ(CRYPT_EAL_PkeySetPrv(ctxA, &dk), CRYPT_SUCCESS); ek.key.kemEk.len = encapsKeyA->len; ek.key.kemEk.data = encapsKeyA->x; ASSERT_EQ(CRYPT_EAL_PkeySetPub(ctxB, &ek), CRYPT_SUCCESS); uint32_t decapsLen = 0; ASSERT_EQ(CRYPT_EAL_PkeyCtrl(ctxA, CRYPT_CTRL_GET_PRVKEY_LEN, &decapsLen, sizeof(decapsLen)), CRYPT_SUCCESS); ASSERT_EQ(decapsLen, dk.key.kemDk.len); ASSERT_EQ(CRYPT_EAL_PkeyGetPrv(ctxA, &dk), CRYPT_SUCCESS); ASSERT_COMPARE("compare private key", dk.key.kemDk.data, dk.key.kemDk.len, decapsKeyA->x, decapsKeyA->len); ASSERT_EQ(CRYPT_EAL_PkeyEncaps(ctxB, ciphertext, &cipherLen, sharedKeyB, &sharedLenB), CRYPT_SUCCESS); ASSERT_EQ(CRYPT_EAL_PkeyDecaps(ctxA, ciphertext, cipherLen, sharedKeyA, &sharedLenA), CRYPT_SUCCESS); ASSERT_COMPARE("compare sharedKey", sharedKeyB, sharedLenB, sharedKeyA, sharedLenA); EXIT: BSL_SAL_Free(ciphertext); BSL_SAL_Free(sharedKeyA); BSL_SAL_Free(sharedKeyB); CRYPT_EAL_PkeyFreeCtx(ctxA); CRYPT_EAL_PkeyFreeCtx(ctxB); CRYPT_RandRegist(NULL); CRYPT_RandRegistEx(NULL); return; } /* END_CASE */
2301_79861745/bench_create
testcode/sdv/testcase/crypto/hybridkem/test_suite_sdv_hybridkem.c
C
unknown
11,827
/* * This file is part of the openHiTLS project. * * openHiTLS is licensed under the Mulan PSL v2. * You can use this software according to the terms and conditions of the Mulan PSL v2. * You may obtain a copy of Mulan PSL v2 at: * * http://license.coscl.org.cn/MulanPSL2 * * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, * EITHER EXPRESS 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 "crypt_eal_kdf.h" #include "crypt_errno.h" #include "bsl_sal.h" #include "bsl_params.h" #include "crypt_params_key.h" /* END_HEADER */ #define DATA_LEN (64) /** * @test SDV_CRYPT_EAL_KDF_TLS12_API_TC001 * @title kdftls12 interface test. * @precon nan * @brief * 1.Normal parameter test,the key and label can be empty,parameter limitation see unction declaration, expected result 1. * @expect * 1.The results are as expected, algId only supported CRYPT_MAC_HMAC_SHA256, CRYPT_MAC_HMAC_SHA384, and CRYPT_MAC_HMAC_SHA512. */ /* BEGIN_CASE */ void SDV_CRYPT_EAL_KDF_TLS12_API_TC001(int algId) { TestMemInit(); uint32_t keyLen = DATA_LEN; uint8_t key[DATA_LEN]; uint32_t labelLen = DATA_LEN; uint8_t label[DATA_LEN]; uint32_t seedLen = DATA_LEN; uint8_t seed[DATA_LEN]; uint32_t outLen = DATA_LEN; uint8_t out[DATA_LEN]; CRYPT_EAL_KdfCTX *ctx = CRYPT_EAL_KdfNewCtx(CRYPT_KDF_KDFTLS12); ASSERT_TRUE(ctx != NULL); BSL_Param params[5] = {{0}, {0}, {0}, {0}, BSL_PARAM_END}; ASSERT_EQ(BSL_PARAM_InitValue(&params[0], CRYPT_PARAM_KDF_MAC_ID, BSL_PARAM_TYPE_UINT32, &algId, sizeof(algId)), CRYPT_SUCCESS); ASSERT_EQ(BSL_PARAM_InitValue(&params[1], CRYPT_PARAM_KDF_KEY, BSL_PARAM_TYPE_OCTETS, key, keyLen), CRYPT_SUCCESS); ASSERT_EQ(BSL_PARAM_InitValue(&params[2], CRYPT_PARAM_KDF_LABEL, BSL_PARAM_TYPE_OCTETS, label, labelLen), CRYPT_SUCCESS); ASSERT_EQ(BSL_PARAM_InitValue(&params[3], CRYPT_PARAM_KDF_SEED, BSL_PARAM_TYPE_OCTETS, seed, seedLen), CRYPT_SUCCESS); ASSERT_EQ(CRYPT_EAL_KdfSetParam(ctx, params), CRYPT_SUCCESS); ASSERT_EQ(CRYPT_EAL_KdfDerive(ctx, out, outLen), CRYPT_SUCCESS); ASSERT_EQ(BSL_PARAM_InitValue(&params[1], CRYPT_PARAM_KDF_KEY, BSL_PARAM_TYPE_OCTETS, NULL, 0), CRYPT_SUCCESS); ASSERT_EQ(CRYPT_EAL_KdfSetParam(ctx, params), CRYPT_SUCCESS); ASSERT_EQ(CRYPT_EAL_KdfDerive(ctx, out, outLen), CRYPT_SUCCESS); ASSERT_EQ(BSL_PARAM_InitValue(&params[2], CRYPT_PARAM_KDF_LABEL, BSL_PARAM_TYPE_OCTETS, NULL, 0), CRYPT_SUCCESS); ASSERT_EQ(CRYPT_EAL_KdfSetParam(ctx, params), CRYPT_SUCCESS); ASSERT_EQ(CRYPT_EAL_KdfDerive(ctx, out, outLen), CRYPT_SUCCESS); ASSERT_EQ(BSL_PARAM_InitValue(&params[3], CRYPT_PARAM_KDF_SEED, BSL_PARAM_TYPE_OCTETS, NULL, 0), CRYPT_SUCCESS); ASSERT_EQ(CRYPT_EAL_KdfSetParam(ctx, params), CRYPT_SUCCESS); ASSERT_EQ(CRYPT_EAL_KdfDerive(ctx, out, outLen), CRYPT_SUCCESS); ASSERT_EQ(CRYPT_EAL_KdfDerive(ctx, NULL, outLen), CRYPT_NULL_INPUT); ASSERT_EQ(CRYPT_EAL_KdfDerive(ctx, out, 0), CRYPT_NULL_INPUT); CRYPT_MAC_AlgId macAlgIdFailed = CRYPT_MAC_HMAC_SHA224; ASSERT_EQ(BSL_PARAM_InitValue(&params[0], CRYPT_PARAM_KDF_MAC_ID, BSL_PARAM_TYPE_UINT32, &macAlgIdFailed, sizeof(macAlgIdFailed)), CRYPT_SUCCESS); ASSERT_EQ(CRYPT_EAL_KdfSetParam(ctx, params), CRYPT_KDFTLS12_PARAM_ERROR); ASSERT_EQ(CRYPT_EAL_KdfDeInitCtx(ctx), CRYPT_SUCCESS); EXIT: CRYPT_EAL_KdfFreeCtx(ctx); } /* END_CASE */ /** * @test SDV_CRYPT_EAL_KDF_TLS12_FUN_TC001 * @title kdftls12 vector test. * @precon nan * @brief * 1.Calculate the output using the given parameters, expected result 1. * 2.Compare the calculated result with the standard value, expected result 2. * @expect * 1.Calculation succeeded. * 2.The results are the same. */ /* BEGIN_CASE */ void SDV_CRYPT_EAL_KDF_TLS12_FUN_TC001(int algId, Hex *key, Hex *label, Hex *seed, Hex *result) { if (IsHmacAlgDisabled(algId)) { SKIP_TEST(); } TestMemInit(); uint32_t outLen = result->len; uint8_t *out = malloc(outLen * sizeof(uint8_t)); ASSERT_TRUE(out != NULL); CRYPT_EAL_KdfCTX *ctx = CRYPT_EAL_KdfNewCtx(CRYPT_KDF_KDFTLS12); ASSERT_TRUE(ctx != NULL); BSL_Param params[5] = {{0}, {0}, {0}, {0}, BSL_PARAM_END}; ASSERT_EQ(BSL_PARAM_InitValue(&params[0], CRYPT_PARAM_KDF_MAC_ID, BSL_PARAM_TYPE_UINT32, &algId, sizeof(algId)), CRYPT_SUCCESS); ASSERT_EQ(BSL_PARAM_InitValue(&params[1], CRYPT_PARAM_KDF_KEY, BSL_PARAM_TYPE_OCTETS, key->x, key->len), CRYPT_SUCCESS); ASSERT_EQ(BSL_PARAM_InitValue(&params[2], CRYPT_PARAM_KDF_LABEL, BSL_PARAM_TYPE_OCTETS, label->x, label->len), CRYPT_SUCCESS); ASSERT_EQ(BSL_PARAM_InitValue(&params[3], CRYPT_PARAM_KDF_SEED, BSL_PARAM_TYPE_OCTETS, seed->x, seed->len), CRYPT_SUCCESS); ASSERT_EQ(CRYPT_EAL_KdfSetParam(ctx, params), CRYPT_SUCCESS); ASSERT_EQ(CRYPT_EAL_KdfDerive(ctx, out, outLen), CRYPT_SUCCESS); ASSERT_COMPARE("result cmp", out, outLen, result->x, result->len); EXIT: if (out != NULL) { free(out); } CRYPT_EAL_KdfFreeCtx(ctx); } /* END_CASE */ /** * @test SDV_CRYPTO_KDFTLS12_DEFAULT_PROVIDER_FUNC_TC001 * @title Default provider testing * @precon nan * @brief * Load the default provider and use the test vector to test its correctness */ /* BEGIN_CASE */ void SDV_CRYPTO_KDFTLS12_DEFAULT_PROVIDER_FUNC_TC001(int algId, Hex *key, Hex *label, Hex *seed, Hex *result) { if (IsHmacAlgDisabled(algId)) { SKIP_TEST(); } TestMemInit(); uint32_t outLen = result->len; uint8_t *out = malloc(outLen * sizeof(uint8_t)); ASSERT_TRUE(out != NULL); CRYPT_EAL_KdfCTX *ctx = NULL; #ifdef HITLS_CRYPTO_PROVIDER ctx = CRYPT_EAL_ProviderKdfNewCtx(NULL, CRYPT_KDF_KDFTLS12, "provider=default"); #else ctx = CRYPT_EAL_KdfNewCtx(CRYPT_KDF_KDFTLS12); #endif ASSERT_TRUE(ctx != NULL); BSL_Param params[5] = {{0}, {0}, {0}, {0}, BSL_PARAM_END}; ASSERT_EQ(BSL_PARAM_InitValue(&params[0], CRYPT_PARAM_KDF_MAC_ID, BSL_PARAM_TYPE_UINT32, &algId, sizeof(algId)), CRYPT_SUCCESS); ASSERT_EQ(BSL_PARAM_InitValue(&params[1], CRYPT_PARAM_KDF_KEY, BSL_PARAM_TYPE_OCTETS, key->x, key->len), CRYPT_SUCCESS); ASSERT_EQ(BSL_PARAM_InitValue(&params[2], CRYPT_PARAM_KDF_LABEL, BSL_PARAM_TYPE_OCTETS, label->x, label->len), CRYPT_SUCCESS); ASSERT_EQ(BSL_PARAM_InitValue(&params[3], CRYPT_PARAM_KDF_SEED, BSL_PARAM_TYPE_OCTETS, seed->x, seed->len), CRYPT_SUCCESS); ASSERT_EQ(CRYPT_EAL_KdfSetParam(ctx, params), CRYPT_SUCCESS); ASSERT_EQ(CRYPT_EAL_KdfDerive(ctx, out, outLen), CRYPT_SUCCESS); ASSERT_COMPARE("result cmp", out, outLen, result->x, result->len); EXIT: if (out != NULL) { free(out); } CRYPT_EAL_KdfFreeCtx(ctx); } /* END_CASE */
2301_79861745/bench_create
testcode/sdv/testcase/crypto/kdf_tls12/test_suite_sdv_eal_kdf_tls12.c
C
unknown
7,025
/* * This file is part of the openHiTLS project. * * openHiTLS is licensed under the Mulan PSL v2. * You can use this software according to the terms and conditions of the Mulan PSL v2. * You may obtain a copy of Mulan PSL v2 at: * * http://license.coscl.org.cn/MulanPSL2 * * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. * See the Mulan PSL v2 for more details. */ /* BEGIN_HEADER */ #include <pthread.h> #include <limits.h> #include "crypt_eal_md.h" #include "bsl_sal.h" #include "eal_md_local.h" #include "crypt_algid.h" #include "crypt_errno.h" #include "crypt_md5.h" /* END_HEADER */ typedef struct { uint8_t *data; uint8_t *hash; uint32_t dataLen; uint32_t hashLen; CRYPT_MD_AlgId id; } ThreadParameter; void Md5MultiThreadTest(void *arg) { ThreadParameter *threadParameter = (ThreadParameter *)arg; uint32_t outLen = CRYPT_MD5_DIGESTSIZE; uint8_t out[CRYPT_MD5_DIGESTSIZE]; CRYPT_EAL_MdCTX *ctx = NULL; ctx = CRYPT_EAL_MdNewCtx(threadParameter->id); ASSERT_TRUE(ctx != NULL); for (uint32_t i = 0; i < 10; i++) { // Repeat 10 times ASSERT_EQ(CRYPT_EAL_MdInit(ctx), CRYPT_SUCCESS); ASSERT_EQ(CRYPT_EAL_MdUpdate(ctx, threadParameter->data, threadParameter->dataLen), CRYPT_SUCCESS); ASSERT_EQ(CRYPT_EAL_MdFinal(ctx, out, &outLen), CRYPT_SUCCESS); ASSERT_COMPARE("hash result cmp", out, outLen, threadParameter->hash, threadParameter->hashLen); } EXIT: CRYPT_EAL_MdFreeCtx(ctx); } /** * @test SDV_CRYPTO_MD5_API_TC001 * @title update and final test. * @precon nan * @brief * 1.Call CRYPT_EAL_MdDeinit the null CTX, expected result 1. * 2.Call CRYPT_EAL_MdNewCtx create the CTX, expected result 2. * 3.Call CRYPT_EAL_MdUpdate and CRYPT_EAL_MdFinal before initialization, expected result 3. * 4.Call CRYPT_EAL_MdUpdate and CRYPT_EAL_MdFinal use null pointer, expected result 4. * 5.Call CRYPT_EAL_MdUpdate and CRYPT_EAL_MdFinal normally, expected result 5. * 6.Call CRYPT_EAL_MdDeinit the CTX, expected result 6. * 7.Call CRYPT_EAL_MdFinal after CRYPT_EAL_MdFinal, expected result 7. * 8.Call CRYPT_EAL_MdUpdate after CRYPT_EAL_MdFinal expected result 8. * @expect * 1.Return CRYPT_NULL_INPUT. * 2.Create successful. * 3.Return CRYPT_EAL_ERR_STATE. * 4.Return CRYPT_NULL_INPUT. * 5.Successful. * 6.Successful. * 7.Return CRYPT_EAL_ERR_STATE. * 8.Return CRYPT_EAL_ERR_STATE. */ /* BEGIN_CASE */ void SDV_CRYPTO_MD5_API_TC001(void) { TestMemInit(); uint8_t data[100]; uint32_t dataLen = sizeof(data); uint8_t output[CRYPT_MD5_DIGESTSIZE + 1]; uint32_t outputLen = CRYPT_MD5_DIGESTSIZE; CRYPT_EAL_MdCTX *md5Ctx = NULL; ASSERT_EQ(CRYPT_EAL_MdDeinit(md5Ctx), CRYPT_NULL_INPUT); md5Ctx = CRYPT_EAL_MdNewCtx(CRYPT_MD_MD5); ASSERT_TRUE(md5Ctx != NULL); ASSERT_EQ(CRYPT_EAL_MdGetDigestSize(CRYPT_MD_MD5), CRYPT_MD5_DIGESTSIZE); ASSERT_EQ(CRYPT_EAL_MdUpdate(md5Ctx, data, dataLen), CRYPT_EAL_ERR_STATE); ASSERT_EQ(CRYPT_EAL_MdFinal(md5Ctx, output, &outputLen), CRYPT_EAL_ERR_STATE); ASSERT_EQ(CRYPT_EAL_MdInit(md5Ctx), CRYPT_SUCCESS); ASSERT_EQ(CRYPT_EAL_MdUpdate(md5Ctx, NULL, dataLen), CRYPT_NULL_INPUT); ASSERT_EQ(CRYPT_EAL_MdUpdate(md5Ctx, data, dataLen), CRYPT_SUCCESS); ASSERT_EQ(CRYPT_EAL_MdFinal(NULL, output, &outputLen), CRYPT_NULL_INPUT); ASSERT_EQ(CRYPT_EAL_MdFinal(md5Ctx, NULL, &outputLen), CRYPT_NULL_INPUT); ASSERT_EQ(CRYPT_EAL_MdFinal(md5Ctx, output, NULL), CRYPT_NULL_INPUT); outputLen = CRYPT_MD5_DIGESTSIZE - 1; ASSERT_EQ(CRYPT_EAL_MdFinal(md5Ctx, output, &outputLen), CRYPT_MD5_OUT_BUFF_LEN_NOT_ENOUGH); outputLen = CRYPT_MD5_DIGESTSIZE; ASSERT_EQ(CRYPT_EAL_MdFinal(md5Ctx, output, &outputLen), CRYPT_SUCCESS); ASSERT_EQ(CRYPT_EAL_MdDeinit(md5Ctx), CRYPT_SUCCESS); ASSERT_EQ(CRYPT_EAL_MdInit(md5Ctx), CRYPT_SUCCESS); ASSERT_EQ(CRYPT_EAL_MdUpdate(md5Ctx, data, dataLen), CRYPT_SUCCESS); outputLen = CRYPT_MD5_DIGESTSIZE + 1; ASSERT_EQ(CRYPT_EAL_MdFinal(md5Ctx, output, &outputLen), CRYPT_SUCCESS); ASSERT_EQ(CRYPT_EAL_MdFinal(md5Ctx, output, &outputLen), CRYPT_EAL_ERR_STATE); ASSERT_EQ(CRYPT_EAL_MdUpdate(md5Ctx, data, dataLen), CRYPT_EAL_ERR_STATE); EXIT: CRYPT_EAL_MdFreeCtx(md5Ctx); } /* END_CASE */ /** * @test SDV_CRYPTO_MD5_FUNC_TC001 * @title CRYPT_EAL_MdFinal test without update. * @precon nan * @brief * 1.Call CRYPT_EAL_MdNewCtx to create ctx, expected result 1. * 2.Call CRYPT_EAL_MdFinal get results. expected result 2. * 3.Compare with expected results. expected result 3. * @expect * 1.The ctx is created successfully. * 2.Successful. * 2.Consistent with expected results. */ /* BEGIN_CASE */ void SDV_CRYPTO_MD5_FUNC_TC001(Hex *hash) { TestMemInit(); uint8_t output[CRYPT_MD5_DIGESTSIZE]; uint32_t outLen = CRYPT_MD5_DIGESTSIZE; CRYPT_EAL_MdCTX *md5Ctx = CRYPT_EAL_MdNewCtx(CRYPT_MD_MD5); ASSERT_TRUE(md5Ctx != NULL); ASSERT_EQ(CRYPT_EAL_MdInit(md5Ctx), CRYPT_SUCCESS); ASSERT_EQ(CRYPT_EAL_MdFinal(md5Ctx, output, &outLen), CRYPT_SUCCESS); ASSERT_EQ(outLen, CRYPT_MD5_DIGESTSIZE); ASSERT_COMPARE("md5", output, outLen, hash->x, hash->len); EXIT: CRYPT_EAL_MdFreeCtx(md5Ctx); } /* END_CASE */ /** * @test SDV_CRYPTO_MD5_FUNC_TC002 * @title Perform the vector test to check whether the calculation result is consistent with the standard output. * @precon nan * @brief * 1.Calculate the hash of each group of data, expected result 1. * 2.Compare the result to the expected value, expected result 2. * 3.Call CRYPT_EAL_Md to calculate the hash of each group of data, expected result 3. * @expect * 1.Hash calculation succeeded. * 2.The results are as expected. * 3.The results are as expected. */ /* BEGIN_CASE */ void SDV_CRYPTO_MD5_FUNC_TC002(Hex *msg, Hex *hash) { TestMemInit(); uint8_t output[CRYPT_MD5_DIGESTSIZE]; uint32_t outLen = CRYPT_MD5_DIGESTSIZE; CRYPT_EAL_MdCTX *md5Ctx = CRYPT_EAL_MdNewCtx(CRYPT_MD_MD5); ASSERT_TRUE(md5Ctx != NULL); ASSERT_EQ(CRYPT_EAL_MdInit(md5Ctx), CRYPT_SUCCESS); ASSERT_EQ(CRYPT_EAL_MdUpdate(md5Ctx, msg->x, msg->len), CRYPT_SUCCESS); ASSERT_EQ(CRYPT_EAL_MdFinal(md5Ctx, output, &outLen), CRYPT_SUCCESS); ASSERT_EQ(outLen, CRYPT_MD5_DIGESTSIZE); ASSERT_COMPARE("md5", output, outLen, hash->x, hash->len); ASSERT_EQ(CRYPT_EAL_Md(CRYPT_MD_MD5, msg->x, msg->len, output, &outLen), CRYPT_SUCCESS); ASSERT_COMPARE("md5", output, outLen, hash->x, hash->len); EXIT: CRYPT_EAL_MdFreeCtx(md5Ctx); } /* END_CASE */ /** * @test SDV_CRYPTO_MD5_FUNC_TC003 * @title Split the data and update test. * @precon nan * @brief * 1.Create two ctx and initialize them, expected result 1. * 2.Use ctx1 to update data 100 times, expected result 2. * 3.Use ctx2 to update all data at once, expected result 3. * 4.Compare two outputs, expected result 4. * @expect * 1.Successful. * 2.Successful. * 3.Successful. * 4.The results are the same. */ /* BEGIN_CASE */ void SDV_CRYPTO_MD5_FUNC_TC003(void) { TestMemInit(); CRYPT_EAL_MdCTX *ctx1 = NULL; CRYPT_EAL_MdCTX *ctx2 = NULL; ctx1 = CRYPT_EAL_MdNewCtx(CRYPT_MD_MD5); ASSERT_TRUE(ctx1 != NULL); ctx2 = CRYPT_EAL_MdNewCtx(CRYPT_MD_MD5); ASSERT_TRUE(ctx2 != NULL); uint8_t input[5050]; uint32_t inLenTotal = 0; uint32_t inLenBase; uint8_t out1[CRYPT_MD5_DIGESTSIZE]; uint8_t out2[CRYPT_MD5_DIGESTSIZE]; uint32_t outLen = CRYPT_MD5_DIGESTSIZE; ASSERT_EQ(CRYPT_EAL_MdInit(ctx1), CRYPT_SUCCESS); ASSERT_EQ(CRYPT_EAL_MdInit(ctx2), CRYPT_SUCCESS); for (inLenBase = 1; inLenBase <= 100; inLenBase++) { ASSERT_EQ(CRYPT_EAL_MdUpdate(ctx1, input + inLenTotal, inLenBase), CRYPT_SUCCESS); inLenTotal += inLenBase; } ASSERT_EQ(CRYPT_EAL_MdFinal(ctx1, out1, &outLen), CRYPT_SUCCESS); ASSERT_EQ(outLen, CRYPT_MD5_DIGESTSIZE); ASSERT_EQ(CRYPT_EAL_MdUpdate(ctx2, input, inLenTotal), CRYPT_SUCCESS); ASSERT_EQ(CRYPT_EAL_MdFinal(ctx2, out2, &outLen), CRYPT_SUCCESS); ASSERT_EQ(outLen, CRYPT_MD5_DIGESTSIZE); ASSERT_COMPARE("md5", out1, outLen, out2, outLen); EXIT: CRYPT_EAL_MdFreeCtx(ctx1); CRYPT_EAL_MdFreeCtx(ctx2); } /* END_CASE */ /** * @test SDV_CRYPTO_MD5_FUNC_TC004 * @title Hash calculation for multiple updates,comparison with standard results. * @precon nan * @brief * 1.Call CRYPT_EAL_MdNewCtx to create a ctx and initialize, expected result 1. * 2.Call CRYPT_EAL_MdUpdate to calculate the hash of a data segmentxpected result 2. * 3.Call CRYPT_EAL_MdUpdate to calculate the next data segmentxpected result 3. * 4.Call CRYPT_EAL_MdUpdate to calculate the next data segmentxpected result 4. * 5.Call CRYPT_EAL_MdFinal get the result, expected result 5. * @expect * 1.Successful * 2.Successful * 3.Successful * 4.Successful * 5.The results are as expected. */ /* BEGIN_CASE */ void SDV_CRYPTO_MD5_FUNC_TC004(Hex *data1, Hex *data2, Hex *data3, Hex *hash) { TestMemInit(); uint8_t output[CRYPT_MD5_DIGESTSIZE]; uint32_t outLen = CRYPT_MD5_DIGESTSIZE; CRYPT_EAL_MdCTX *md5Ctx = CRYPT_EAL_MdNewCtx(CRYPT_MD_MD5); ASSERT_TRUE(md5Ctx != NULL); ASSERT_EQ(CRYPT_EAL_MdInit(md5Ctx), CRYPT_SUCCESS); ASSERT_EQ(CRYPT_EAL_MdUpdate(md5Ctx, data1->x, data1->len), CRYPT_SUCCESS); ASSERT_EQ(CRYPT_EAL_MdUpdate(md5Ctx, data2->x, data2->len), CRYPT_SUCCESS); ASSERT_EQ(CRYPT_EAL_MdUpdate(md5Ctx, data3->x, data3->len), CRYPT_SUCCESS); ASSERT_EQ(CRYPT_EAL_MdFinal(md5Ctx, output, &outLen), CRYPT_SUCCESS); ASSERT_EQ(outLen, CRYPT_MD5_DIGESTSIZE); ASSERT_COMPARE("md5", output, outLen, hash->x, hash->len); EXIT: CRYPT_EAL_MdFreeCtx(md5Ctx); } /* END_CASE */ /** * @test SDV_CRYPTO_MD5_COPY_CTX_FUNC_TC001 * @title MD5 copy ctx function test. * @precon nan * @brief * 1. Create the context ctx of md algorithm, expected result 1 * 2. Call to CRYPT_EAL_MdCopyCtx method to copy ctx, expected result 2 * 2. Call to CRYPT_EAL_MdCopyCtx method to copy a null ctx, expected result 3 * 3. Calculate the hash of msg, and compare the calculated result with hash vector, expected result 4 * 4. Call to CRYPT_EAL_MdDupCtx method to copy ctx, expected result 5 * 3. Calculate the hash of msg, and compare the calculated result with hash vector, expected result 6 * @expect * 1. Success, the context is not null. * 2. CRYPT_SUCCESS * 3. CRYPT_NULL_INPUT * 4. Success, the context is not null. * 5. CRYPT_SUCCESS * 6. Success, the hashs are the same. */ /* BEGIN_CASE */ void SDV_CRYPTO_MD5_COPY_CTX_FUNC_TC001(int id, Hex *msg, Hex *hash) { TestMemInit(); CRYPT_EAL_MdCTX *cpyCtx = NULL; CRYPT_EAL_MdCTX *dupCtx = NULL; CRYPT_EAL_MdCTX *ctx = CRYPT_EAL_MdNewCtx(id); ASSERT_TRUE(ctx != NULL); uint8_t output[CRYPT_MD5_DIGESTSIZE]; uint32_t outLen = CRYPT_MD5_DIGESTSIZE; dupCtx=CRYPT_EAL_MdDupCtx(cpyCtx); ASSERT_TRUE(dupCtx == NULL); ASSERT_EQ(CRYPT_MD_MAX, CRYPT_EAL_MdGetId(dupCtx)); ASSERT_EQ(CRYPT_EAL_MdCopyCtx(cpyCtx, ctx), CRYPT_NULL_INPUT); cpyCtx = CRYPT_EAL_MdNewCtx(id); ASSERT_TRUE(cpyCtx != NULL); ASSERT_TRUE(dupCtx == NULL); ASSERT_EQ(CRYPT_EAL_MdCopyCtx(cpyCtx, dupCtx), CRYPT_NULL_INPUT); ASSERT_EQ(CRYPT_EAL_MdCopyCtx(cpyCtx, ctx), CRYPT_SUCCESS); ASSERT_EQ(CRYPT_EAL_MdInit(cpyCtx), CRYPT_SUCCESS); ASSERT_EQ(CRYPT_EAL_MdUpdate(cpyCtx, msg->x, msg->len), CRYPT_SUCCESS); ASSERT_EQ(CRYPT_EAL_MdFinal(cpyCtx, output, &outLen), CRYPT_SUCCESS); ASSERT_EQ(id, cpyCtx->id); ASSERT_EQ(memcmp(output, hash->x, hash->len), 0); dupCtx=CRYPT_EAL_MdDupCtx(ctx); ASSERT_TRUE(dupCtx != NULL); ASSERT_EQ(CRYPT_EAL_MdInit(dupCtx), CRYPT_SUCCESS); ASSERT_EQ(CRYPT_EAL_MdUpdate(dupCtx, msg->x, msg->len), CRYPT_SUCCESS); ASSERT_EQ(CRYPT_EAL_MdFinal(dupCtx, output, &outLen), CRYPT_SUCCESS); ASSERT_EQ(id, CRYPT_EAL_MdGetId(dupCtx)); ASSERT_EQ(memcmp(output, hash->x, hash->len), 0); EXIT: CRYPT_EAL_MdFreeCtx(ctx); CRYPT_EAL_MdFreeCtx(cpyCtx); CRYPT_EAL_MdFreeCtx(dupCtx); } /* END_CASE */ /** * @test SDV_CRYPTO_MD5_FUNC_TC005 * @title Default provider testing * @precon nan * @brief * Load the default provider and use the test vector to test its correctness */ /* BEGIN_CASE */ void SDV_CRYPTO_MD5_FUNC_TC005(int id, Hex *msg, Hex *hash) { TestMemInit(); uint8_t output[CRYPT_MD5_DIGESTSIZE]; uint32_t outLen = CRYPT_MD5_DIGESTSIZE; CRYPT_EAL_MdCTX *ctx = NULL; #ifdef HITLS_CRYPTO_PROVIDER ctx = CRYPT_EAL_ProviderMdNewCtx(NULL, id, "provider=default"); #else ctx = CRYPT_EAL_MdNewCtx(id); #endif ASSERT_TRUE(ctx != NULL); ASSERT_EQ(CRYPT_EAL_MdInit(ctx), CRYPT_SUCCESS); ASSERT_EQ(CRYPT_EAL_MdUpdate(ctx, msg->x, msg->len), CRYPT_SUCCESS); ASSERT_EQ(CRYPT_EAL_MdFinal(ctx, output, &outLen), CRYPT_SUCCESS); ASSERT_EQ(memcmp(output, hash->x, hash->len), 0); EXIT: CRYPT_EAL_MdFreeCtx(ctx); } /* END_CASE */ /** * @test SDV_CRYPT_EAL_MD_MD5_FUNC_TC001 * @title Test multi-thread hash calculation. * @precon nan * @brief * 1.Create two threads and calculate the hash, expected result 1. * 2.Compare the result to the expected value, expected result 2. * @expect * 1.Hash calculation succeeded. * 2.The results are as expected. */ /* BEGIN_CASE */ void SDV_CRYPT_EAL_MD_MD5_FUNC_TC001(int algId, Hex *data, Hex *hash) { int ret; TestMemInit(); const uint32_t threadNum = 2; pthread_t thrd[2]; ThreadParameter arg[2] = { {data->x, hash->x, data->len, hash->len, algId}, {data->x, hash->x, data->len, hash->len, algId} }; for (uint32_t i = 0; i < threadNum; i++) { ret = pthread_create(&thrd[i], NULL, (void *)Md5MultiThreadTest, &arg[i]); ASSERT_EQ(ret, 0); } for (uint32_t i = 0; i < threadNum; i++) { pthread_join(thrd[i], NULL); } EXIT: return; } /* END_CASE */
2301_79861745/bench_create
testcode/sdv/testcase/crypto/md5/test_suite_sdv_eal_md5.c
C
unknown
14,310
/* * This file is part of the openHiTLS project. * * openHiTLS is licensed under the Mulan PSL v2. * You can use this software according to the terms and conditions of the Mulan PSL v2. * You may obtain a copy of Mulan PSL v2 at: * * http://license.coscl.org.cn/MulanPSL2 * * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, * EITHER EXPRESS 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 <stdio.h> #include <string.h> #include "securec.h" #include "hitls_build.h" #include "bsl_err.h" #include "bsl_sal.h" #include "crypt_errno.h" #include "crypt_eal_pkey.h" #include "crypt_eal_rand.h" #include "crypt_eal_md.h" #include "crypt_util_rand.h" /* END_HEADER */ static uint8_t gMlDsaRandBuf[3][32] = { 0 }; uint32_t gMlDsaRandNum = 0; static int32_t TEST_MLDSARandom(uint8_t *randNum, uint32_t randLen) { memcpy_s(randNum, randLen, gMlDsaRandBuf[gMlDsaRandNum], 32); gMlDsaRandNum++; return 0; } static int32_t TEST_MLDSARandomEx(void *libCtx, uint8_t *randNum, uint32_t randLen) { (void) libCtx; return TEST_MLDSARandom(randNum, randLen); } /* @ * @test SDV_CRYPTO_MLDSA_API_TC001 * @spec - * @title Test the MLDSA external interface. * @precon nan * @brief * 1.Generate the context. * 2.Call the copy and cmp interfaces. * @expect * 1.success * 2.The result is same as expected. * @prior nan * @auto FALSE @ */ /* BEGIN_CASE */ void SDV_CRYPTO_MLDSA_API_TC001(int type, int setBits) { TestMemInit(); TestRandInit(); CRYPT_EAL_PkeyCtx *ctx1 = NULL; CRYPT_EAL_PkeyCtx *ctx2 = NULL; CRYPT_EAL_PkeyCtx *ctx3 = NULL; #ifdef HITLS_CRYPTO_PROVIDER ctx1 = CRYPT_EAL_ProviderPkeyNewCtx(NULL, CRYPT_PKEY_ML_DSA, CRYPT_EAL_PKEY_SIGN_OPERATE, "provider=default"); #else ctx1 = CRYPT_EAL_PkeyNewCtx(CRYPT_PKEY_ML_DSA); #endif ASSERT_TRUE(ctx1 != NULL); uint32_t val = (uint32_t)type; int32_t ret = CRYPT_EAL_PkeyCtrl(ctx1, CRYPT_CTRL_SET_PARA_BY_ID, &val, sizeof(val)); ASSERT_EQ(ret, CRYPT_SUCCESS); ret = CRYPT_EAL_PkeyGen(ctx1); ASSERT_EQ(ret, CRYPT_SUCCESS); #ifdef HITLS_CRYPTO_PROVIDER ctx2 = CRYPT_EAL_ProviderPkeyNewCtx(NULL, CRYPT_PKEY_ML_DSA, CRYPT_EAL_PKEY_SIGN_OPERATE, "provider=default"); #else ctx2 = CRYPT_EAL_PkeyNewCtx(CRYPT_PKEY_ML_DSA); #endif ASSERT_TRUE(ctx2 != NULL); val = (uint32_t)type; ret = CRYPT_EAL_PkeyCtrl(ctx2, CRYPT_CTRL_SET_PARA_BY_ID, &val, sizeof(val)); ASSERT_EQ(ret, CRYPT_SUCCESS); ret = CRYPT_EAL_PkeyGen(ctx2); ASSERT_EQ(ret, CRYPT_SUCCESS); ret = CRYPT_EAL_PkeyCmp(ctx1, ctx2); ASSERT_NE(ret, CRYPT_SUCCESS); ctx3 = CRYPT_EAL_PkeyDupCtx(ctx1); ASSERT_TRUE(ctx3 != NULL); ret = CRYPT_EAL_PkeyCmp(ctx1, ctx3); ASSERT_EQ(ret, CRYPT_SUCCESS); uint32_t secBits = CRYPT_EAL_PkeyGetSecurityBits(ctx1); ASSERT_EQ(secBits, setBits); EXIT: CRYPT_EAL_PkeyFreeCtx(ctx1); CRYPT_EAL_PkeyFreeCtx(ctx2); CRYPT_EAL_PkeyFreeCtx(ctx3); TestRandDeInit(); return; } /* END_CASE */ /* @ * @test SDV_CRYPTO_MLDSA_FUNC_KEYGEN_TC001 * @spec - * @title Generate public and private key tests. * @precon nan * @brief * 1.Registers a random number that returns the specified value. * 2.Call the key generation interface. * @expect * 1.success * 2.The public and private key is same as expected. * @prior nan * @auto FALSE @ */ /* BEGIN_CASE */ void SDV_CRYPTO_MLDSA_FUNC_KEYGEN_TC001(int type, Hex *d, Hex *testPubkey, Hex *testPrvKey) { TestMemInit(); gMlDsaRandNum = 0; memcpy_s(gMlDsaRandBuf[0], 32, d->x, d->len); CRYPT_RandRegist(TEST_MLDSARandom); CRYPT_RandRegistEx(TEST_MLDSARandomEx); CRYPT_EAL_PkeyPub pubKey = { 0 }; pubKey.id = CRYPT_PKEY_ML_DSA; pubKey.key.mldsaPub.len = testPubkey->len; pubKey.key.mldsaPub.data = BSL_SAL_Malloc(testPubkey->len); ASSERT_TRUE(pubKey.key.mldsaPub.data != NULL); CRYPT_EAL_PkeyPrv prvKey = { 0 }; prvKey.id = CRYPT_PKEY_ML_DSA; prvKey.key.mldsaPrv.len = testPrvKey->len; prvKey.key.mldsaPrv.data = BSL_SAL_Malloc(testPrvKey->len); ASSERT_TRUE(prvKey.key.mldsaPrv.data != NULL); CRYPT_EAL_PkeyCtx *ctx = CRYPT_EAL_PkeyNewCtx(CRYPT_PKEY_ML_DSA); ASSERT_TRUE(ctx != NULL); uint32_t val = (uint32_t)type; int32_t ret = CRYPT_EAL_PkeySetParaById(ctx, val); ASSERT_EQ(ret, CRYPT_SUCCESS); pubKey.key.mldsaPub.len = testPubkey->len; ret = CRYPT_EAL_PkeyGetPub(ctx, &pubKey); ASSERT_EQ(ret, CRYPT_MLDSA_KEY_NOT_SET); prvKey.key.mldsaPrv.len = testPrvKey->len; ret = CRYPT_EAL_PkeyGetPrv(ctx, &prvKey); ASSERT_EQ(ret, CRYPT_MLDSA_KEY_NOT_SET); ret = CRYPT_EAL_PkeyGen(ctx); ASSERT_EQ(ret, CRYPT_SUCCESS); pubKey.key.mldsaPub.len = testPubkey->len - 1; ret = CRYPT_EAL_PkeyGetPub(ctx, &pubKey); ASSERT_EQ(ret, CRYPT_MLDSA_LEN_NOT_ENOUGH); pubKey.key.mldsaPub.len = testPubkey->len; ret = CRYPT_EAL_PkeyGetPub(ctx, &pubKey); ASSERT_EQ(ret, CRYPT_SUCCESS); prvKey.key.mldsaPrv.len = testPrvKey->len - 1; ret = CRYPT_EAL_PkeyGetPrv(ctx, &prvKey); ASSERT_EQ(ret, CRYPT_MLDSA_LEN_NOT_ENOUGH); prvKey.key.mldsaPrv.len = testPrvKey->len; ret = CRYPT_EAL_PkeyGetPrv(ctx, &prvKey); ASSERT_EQ(ret, CRYPT_SUCCESS); ASSERT_COMPARE("compare pubkey", pubKey.key.mldsaPub.data, pubKey.key.mldsaPub.len, testPubkey->x, testPubkey->len); ASSERT_COMPARE("compare prvkey", prvKey.key.mldsaPrv.data, prvKey.key.mldsaPrv.len, testPrvKey->x, testPrvKey->len); EXIT: CRYPT_EAL_PkeyFreeCtx(ctx); BSL_SAL_FREE(pubKey.key.mldsaPub.data); BSL_SAL_FREE(prvKey.key.mldsaPrv.data); return; } /* END_CASE */ /* @ * @test SDV_CRYPTO_MLDSA_FUNC_SIGNDATA_TC001 * @spec - * @title Signature test. * @precon nan * @brief * 1.Registers a random number that returns the specified value. * 2.Set the private key. * 3.Call the signature interface. * @expect * 1.success * 2.success * 3.The signature value is consistent with the test vector. * @prior nan * @auto FALSE @ */ /* BEGIN_CASE */ void SDV_CRYPTO_MLDSA_FUNC_SIGNDATA_TC001(int type, Hex *seed, Hex *testPrvKey, Hex *msg, Hex *sign) { TestMemInit(); gMlDsaRandNum = 0; memcpy_s(gMlDsaRandBuf[0], 32, seed->x, seed->len); CRYPT_RandRegist(TEST_MLDSARandom); CRYPT_RandRegistEx(TEST_MLDSARandomEx); CRYPT_EAL_PkeyCtx *ctx = CRYPT_EAL_PkeyNewCtx(CRYPT_PKEY_ML_DSA); ASSERT_TRUE(ctx != NULL); uint32_t val = (uint32_t)type; int32_t ret = CRYPT_EAL_PkeySetParaById(ctx, val); ASSERT_EQ(ret, CRYPT_SUCCESS); val = 0; ret = CRYPT_EAL_PkeyCtrl(ctx, CRYPT_CTRL_SET_MLDSA_ENCODE_FLAG, &val, sizeof(val)); ASSERT_EQ(ret, CRYPT_SUCCESS); uint32_t outLen = CRYPT_EAL_PkeyGetSignLen(ctx); ASSERT_EQ(outLen, sign->len); uint8_t *out = BSL_SAL_Malloc(outLen); CRYPT_EAL_PkeyPrv prvKey = { 0 }; prvKey.id = CRYPT_PKEY_ML_DSA; prvKey.key.mldsaPrv.data = testPrvKey->x; prvKey.key.mldsaPrv.len = testPrvKey->len - 1; ret = CRYPT_EAL_PkeySetPrv(ctx, &prvKey); ASSERT_EQ(ret, CRYPT_MLDSA_KEYLEN_ERROR); prvKey.key.mldsaPrv.len = testPrvKey->len + 1; ret = CRYPT_EAL_PkeySetPrv(ctx, &prvKey); ASSERT_EQ(ret, CRYPT_MLDSA_KEYLEN_ERROR); prvKey.key.mldsaPrv.len = testPrvKey->len; ret = CRYPT_EAL_PkeySetPrv(ctx, &prvKey); ASSERT_EQ(ret, CRYPT_SUCCESS); ret = CRYPT_EAL_PkeySign(ctx, CRYPT_MD_MAX, msg->x, msg->len, out, &outLen); ASSERT_EQ(ret, CRYPT_SUCCESS); ASSERT_COMPARE("compare sign", out, outLen, sign->x, sign->len); EXIT: CRYPT_EAL_PkeyFreeCtx(ctx); BSL_SAL_FREE(out); CRYPT_RandRegist(NULL); CRYPT_RandRegistEx(NULL); return; } /* END_CASE */ /* @ * @test SDV_CRYPTO_MLDSA_FUNC_VERIFYDATA_TC001 * @spec - * @title Verify test. * @precon nan * @brief * 1.Set the public key. * 2.Call the verify interface. * @expect * 1.success * 2.The verify value is consistent with the test vector. * @prior nan * @auto FALSE @ */ /* BEGIN_CASE */ void SDV_CRYPTO_MLDSA_FUNC_VERIFYDATA_TC001(int type, Hex *testPubKey, Hex *msg, Hex *sign, int res) { TestMemInit(); CRYPT_EAL_PkeyCtx *ctx = CRYPT_EAL_PkeyNewCtx(CRYPT_PKEY_ML_DSA); ASSERT_TRUE(ctx != NULL); uint32_t val = (uint32_t)type; int32_t ret = CRYPT_EAL_PkeySetParaById(ctx, val); ASSERT_EQ(ret, CRYPT_SUCCESS); val = 0; ret = CRYPT_EAL_PkeyCtrl(ctx, CRYPT_CTRL_SET_MLDSA_ENCODE_FLAG, &val, sizeof(val)); ASSERT_EQ(ret, CRYPT_SUCCESS); CRYPT_EAL_PkeyPub pubKey = { 0 }; pubKey.id = CRYPT_PKEY_ML_DSA; pubKey.key.mldsaPub.data = testPubKey->x; pubKey.key.mldsaPub.len = testPubKey->len - 1; ret = CRYPT_EAL_PkeySetPub(ctx, &pubKey); ASSERT_EQ(ret, CRYPT_MLDSA_KEYLEN_ERROR); pubKey.key.mldsaPub.len = testPubKey->len + 1; ret = CRYPT_EAL_PkeySetPub(ctx, &pubKey); ASSERT_EQ(ret, CRYPT_MLDSA_KEYLEN_ERROR); pubKey.key.mldsaPub.len = testPubKey->len; ret = CRYPT_EAL_PkeySetPub(ctx, &pubKey); ASSERT_EQ(ret, CRYPT_SUCCESS); ret = CRYPT_EAL_PkeyVerify(ctx, CRYPT_MD_MAX, msg->x, msg->len, sign->x, sign->len); if (res == 1) { ASSERT_EQ(ret, CRYPT_SUCCESS); } else { ASSERT_NE(ret, CRYPT_SUCCESS); } EXIT: CRYPT_EAL_PkeyFreeCtx(ctx); return; } /* END_CASE */ /* @ * @test SDV_CRYPTO_MLDSA_FUNC_SIGNDATA_TC002 * @spec - * @title Signature test. * @precon nan * @brief * 1.Registers a random number that returns the specified value. * 2.Set the private key and additional messages. * 3.Call the signature interface. * @expect * 1.success * 2.success * 3.The signature value is consistent with the test vector. * @prior nan * @auto FALSE @ */ /* BEGIN_CASE */ void SDV_CRYPTO_MLDSA_FUNC_SIGNDATA_TC002(int type, Hex *seed, Hex *testPrvKey, Hex *msg, Hex *ctxText, Hex *sign, int deterministic, int externalMu, int encodeCtx) { TestMemInit(); gMlDsaRandNum = 0; memcpy_s(gMlDsaRandBuf[0], 32, seed->x, seed->len); CRYPT_RandRegist(TEST_MLDSARandom); CRYPT_RandRegistEx(TEST_MLDSARandomEx); CRYPT_EAL_PkeyCtx *ctx = CRYPT_EAL_PkeyNewCtx(CRYPT_PKEY_ML_DSA); ASSERT_TRUE(ctx != NULL); uint32_t val = (uint32_t)type; int32_t ret = CRYPT_EAL_PkeySetParaById(ctx, val); ASSERT_EQ(ret, CRYPT_SUCCESS); val = (uint32_t)deterministic; ret = CRYPT_EAL_PkeyCtrl(ctx, CRYPT_CTRL_SET_DETERMINISTIC_FLAG, &val, sizeof(val)); ASSERT_EQ(ret, CRYPT_SUCCESS); ret = CRYPT_EAL_PkeyCtrl(ctx, CRYPT_CTRL_SET_CTX_INFO, ctxText->x, ctxText->len); ASSERT_EQ(ret, CRYPT_SUCCESS); val = (uint32_t)encodeCtx; ret = CRYPT_EAL_PkeyCtrl(ctx, CRYPT_CTRL_SET_MLDSA_ENCODE_FLAG, &val, sizeof(val)); ASSERT_EQ(ret, CRYPT_SUCCESS); val = (uint32_t)externalMu; ret = CRYPT_EAL_PkeyCtrl(ctx, CRYPT_CTRL_SET_MLDSA_MUMSG_FLAG, &val, sizeof(val)); ASSERT_EQ(ret, CRYPT_SUCCESS); uint32_t outLen = CRYPT_EAL_PkeyGetSignLen(ctx); ASSERT_EQ(outLen, sign->len); uint8_t *out = BSL_SAL_Malloc(outLen); CRYPT_EAL_PkeyPrv prvKey = { 0 }; prvKey.id = CRYPT_PKEY_ML_DSA; prvKey.key.mldsaPrv.data = testPrvKey->x; prvKey.key.mldsaPrv.len = testPrvKey->len; ret = CRYPT_EAL_PkeySetPrv(ctx, &prvKey); ASSERT_EQ(ret, CRYPT_SUCCESS); ret = CRYPT_EAL_PkeySign(ctx, CRYPT_MD_MAX, msg->x, msg->len, out, &outLen); ASSERT_EQ(ret, CRYPT_SUCCESS); ASSERT_COMPARE("compare sign", out, outLen, sign->x, sign->len); EXIT: CRYPT_EAL_PkeyFreeCtx(ctx); BSL_SAL_FREE(out); CRYPT_RandRegist(NULL); CRYPT_RandRegistEx(NULL); return; } /* END_CASE */ /* @ * @test SDV_CRYPTO_MLDSA_FUNC_VERIFYDATA_TC002 * @spec - * @title Verify test. * @precon nan * @brief * 1.Set the public key. * 2.Call the verify interface. * @expect * 1.success * 2.The verify value is consistent with the test vector. * @prior nan * @auto FALSE @ */ /* BEGIN_CASE */ void SDV_CRYPTO_MLDSA_FUNC_VERIFYDATA_TC002(int type, Hex *testPubKey, Hex *msg, Hex *sign, Hex *ctxText, int externalMu, int encodeCtx, int res) { TestMemInit(); CRYPT_EAL_PkeyCtx *ctx = CRYPT_EAL_PkeyNewCtx(CRYPT_PKEY_ML_DSA); ASSERT_TRUE(ctx != NULL); uint32_t val = (uint32_t)type; int32_t ret = CRYPT_EAL_PkeySetParaById(ctx, val); ASSERT_EQ(ret, CRYPT_SUCCESS); ret = CRYPT_EAL_PkeyCtrl(ctx, CRYPT_CTRL_SET_CTX_INFO, ctxText->x, ctxText->len); ASSERT_EQ(ret, CRYPT_SUCCESS); val = (uint32_t)encodeCtx; ret = CRYPT_EAL_PkeyCtrl(ctx, CRYPT_CTRL_SET_MLDSA_ENCODE_FLAG, &val, sizeof(val)); ASSERT_EQ(ret, CRYPT_SUCCESS); val = (uint32_t)externalMu; ret = CRYPT_EAL_PkeyCtrl(ctx, CRYPT_CTRL_SET_MLDSA_MUMSG_FLAG, &val, sizeof(val)); ASSERT_EQ(ret, CRYPT_SUCCESS); CRYPT_EAL_PkeyPub pubKey = { 0 }; pubKey.id = CRYPT_PKEY_ML_DSA; pubKey.key.mldsaPub.data = testPubKey->x; pubKey.key.mldsaPub.len = testPubKey->len; ret = CRYPT_EAL_PkeySetPub(ctx, &pubKey); ASSERT_EQ(ret, CRYPT_SUCCESS); ret = CRYPT_EAL_PkeyVerify(ctx, CRYPT_MD_MAX, msg->x, msg->len, sign->x, sign->len); if (res == 0) { ASSERT_EQ(ret, CRYPT_SUCCESS); } else { ASSERT_NE(ret, CRYPT_SUCCESS); } EXIT: CRYPT_EAL_PkeyFreeCtx(ctx); return; } /* END_CASE */ /* @ * @test SDV_CRYPTO_MLDSA_FUNC_SIGN_TC001 * @spec - * @title Signature test. * @precon nan * @brief * 1.Registers a random number that returns the specified value. * 2.Set the private key and additional messages. * 3.Call the signature interface. * @expect * 1.success * 2.success * 3.The signature value is consistent with the test vector. * @prior nan * @auto FALSE @ */ /* BEGIN_CASE */ void SDV_CRYPTO_MLDSA_FUNC_SIGN_TC001(int type, int hashId, Hex *seed, Hex *testPrvKey, Hex *msg, Hex *ctxText, Hex *sign, int deterministic, int externalMu, int encodeCtx) { TestMemInit(); gMlDsaRandNum = 0; memcpy_s(gMlDsaRandBuf[0], 32, seed->x, seed->len); CRYPT_RandRegist(TEST_MLDSARandom); CRYPT_RandRegistEx(TEST_MLDSARandomEx); CRYPT_EAL_PkeyCtx *ctx = CRYPT_EAL_PkeyNewCtx(CRYPT_PKEY_ML_DSA); ASSERT_TRUE(ctx != NULL); uint32_t val = (uint32_t)type; int32_t ret = CRYPT_EAL_PkeySetParaById(ctx, val); ASSERT_EQ(ret, CRYPT_SUCCESS); val = (uint32_t)deterministic; ret = CRYPT_EAL_PkeyCtrl(ctx, CRYPT_CTRL_SET_DETERMINISTIC_FLAG, &val, sizeof(val)); ASSERT_EQ(ret, CRYPT_SUCCESS); ret = CRYPT_EAL_PkeyCtrl(ctx, CRYPT_CTRL_SET_CTX_INFO, ctxText->x, ctxText->len); ASSERT_EQ(ret, CRYPT_SUCCESS); val = (uint32_t)encodeCtx; ret = CRYPT_EAL_PkeyCtrl(ctx, CRYPT_CTRL_SET_MLDSA_ENCODE_FLAG, &val, sizeof(val)); ASSERT_EQ(ret, CRYPT_SUCCESS); val = (uint32_t)externalMu; ret = CRYPT_EAL_PkeyCtrl(ctx, CRYPT_CTRL_SET_MLDSA_MUMSG_FLAG, &val, sizeof(val)); ASSERT_EQ(ret, CRYPT_SUCCESS); uint32_t outLen = CRYPT_EAL_PkeyGetSignLen(ctx); ASSERT_EQ(outLen, sign->len); uint8_t *out = BSL_SAL_Malloc(outLen); CRYPT_EAL_PkeyPrv prvKey = { 0 }; prvKey.id = CRYPT_PKEY_ML_DSA; prvKey.key.mldsaPrv.data = testPrvKey->x; prvKey.key.mldsaPrv.len = testPrvKey->len; ret = CRYPT_EAL_PkeySetPrv(ctx, &prvKey); ASSERT_EQ(ret, CRYPT_SUCCESS); val = 1; ret = CRYPT_EAL_PkeyCtrl(ctx, CRYPT_CTRL_SET_PREHASH_FLAG, &val, sizeof(val)); ASSERT_EQ(ret, CRYPT_SUCCESS); ret = CRYPT_EAL_PkeySign(ctx, hashId, msg->x, msg->len, out, &outLen); ASSERT_EQ(ret, CRYPT_SUCCESS); ASSERT_COMPARE("compare sign", out, outLen, sign->x, sign->len); EXIT: CRYPT_EAL_PkeyFreeCtx(ctx); BSL_SAL_FREE(out); CRYPT_RandRegist(NULL); CRYPT_RandRegistEx(NULL); return; } /* END_CASE */ /* @ * @test SDV_CRYPTO_MLDSA_FUNC_VERIFY_TC001 * @spec - * @title Verify test. * @precon nan * @brief * 1.Set the public key. * 2.Call the verify interface. * @expect * 1.success * 2.The verify value is consistent with the test vector. * @prior nan * @auto FALSE @ */ /* BEGIN_CASE */ void SDV_CRYPTO_MLDSA_FUNC_VERIFY_TC001(int type, int hashId, Hex *testPubKey, Hex *msg, Hex *sign, Hex *ctxText, int externalMu, int encodeCtx, int res) { TestMemInit(); CRYPT_EAL_PkeyCtx *ctx = CRYPT_EAL_PkeyNewCtx(CRYPT_PKEY_ML_DSA); ASSERT_TRUE(ctx != NULL); uint32_t val = (uint32_t)type; int32_t ret = CRYPT_EAL_PkeySetParaById(ctx, val); ASSERT_EQ(ret, CRYPT_SUCCESS); val = (int32_t)encodeCtx; ret = CRYPT_EAL_PkeyCtrl(ctx, CRYPT_CTRL_SET_MLDSA_ENCODE_FLAG, &val, sizeof(val)); ASSERT_EQ(ret, CRYPT_SUCCESS); ret = CRYPT_EAL_PkeyCtrl(ctx, CRYPT_CTRL_SET_CTX_INFO, ctxText->x, ctxText->len); ASSERT_EQ(ret, CRYPT_SUCCESS); val = (int32_t)externalMu; ret = CRYPT_EAL_PkeyCtrl(ctx, CRYPT_CTRL_SET_MLDSA_MUMSG_FLAG, &val, sizeof(val)); ASSERT_EQ(ret, CRYPT_SUCCESS); CRYPT_EAL_PkeyPub pubKey = { 0 }; pubKey.id = CRYPT_PKEY_ML_DSA; pubKey.key.mldsaPub.data = testPubKey->x; pubKey.key.mldsaPub.len = testPubKey->len; ret = CRYPT_EAL_PkeySetPub(ctx, &pubKey); ASSERT_EQ(ret, CRYPT_SUCCESS); val = 1; ret = CRYPT_EAL_PkeyCtrl(ctx, CRYPT_CTRL_SET_PREHASH_FLAG, &val, sizeof(val)); ASSERT_EQ(ret, CRYPT_SUCCESS); ret = CRYPT_EAL_PkeyVerify(ctx, hashId, msg->x, msg->len, sign->x, sign->len); if (res == 0) { ASSERT_EQ(ret, CRYPT_SUCCESS); } else { ASSERT_NE(ret, CRYPT_SUCCESS); } EXIT: CRYPT_EAL_PkeyFreeCtx(ctx); return; } /* END_CASE */ /** * @test SDV_CRYPTO_MLDSA_FUNC_PROVIDER_TC001 * @title To test the provisioner function. * @precon Registering memory-related functions. * @brief * Invoke the signature and signature verification functions to test the function correctness. * @expect * Success, and contexts are not NULL. */ /* BEGIN_CASE */ void SDV_CRYPTO_MLDSA_FUNC_PROVIDER_TC001(int type, Hex *testPubKey, Hex *testPrvKey, Hex *msg, Hex *context, Hex *sign) { TestMemInit(); TestRandInit(); uint8_t *out = NULL; CRYPT_EAL_PkeyCtx *ctx = NULL; #ifdef HITLS_CRYPTO_PROVIDER ctx = CRYPT_EAL_ProviderPkeyNewCtx(NULL, CRYPT_PKEY_ML_DSA, CRYPT_EAL_PKEY_SIGN_OPERATE, "provider=default"); #else ctx = CRYPT_EAL_PkeyNewCtx(CRYPT_PKEY_ML_DSA); #endif ASSERT_TRUE(ctx != NULL); uint32_t val = (uint32_t)type; int32_t ret = CRYPT_EAL_PkeySetParaById(ctx, val); ASSERT_EQ(ret, CRYPT_SUCCESS); ret = CRYPT_EAL_PkeyCtrl(ctx, CRYPT_CTRL_SET_CTX_INFO, context->x, context->len); ASSERT_EQ(ret, CRYPT_SUCCESS); val = 1; ret = CRYPT_EAL_PkeyCtrl(ctx, CRYPT_CTRL_SET_DETERMINISTIC_FLAG, &val, sizeof(val)); ASSERT_EQ(ret, CRYPT_SUCCESS); uint32_t outLen = CRYPT_EAL_PkeyGetSignLen(ctx); ASSERT_EQ(outLen, sign->len); out = BSL_SAL_Malloc(outLen); ASSERT_TRUE(out != NULL); CRYPT_EAL_PkeyPrv prvKey = { 0 }; prvKey.id = CRYPT_PKEY_ML_DSA; prvKey.key.mldsaPrv.data = testPrvKey->x; prvKey.key.mldsaPrv.len = testPrvKey->len; ret = CRYPT_EAL_PkeySetPrv(ctx, &prvKey); ASSERT_EQ(ret, CRYPT_SUCCESS); ret = CRYPT_EAL_PkeySign(ctx, CRYPT_MD_MAX, msg->x, msg->len, out, &outLen); ASSERT_EQ(ret, CRYPT_SUCCESS); ASSERT_COMPARE("compare sign", out, outLen, sign->x, sign->len); CRYPT_EAL_PkeyPub pubKey = { 0 }; pubKey.id = CRYPT_PKEY_ML_DSA; pubKey.key.mldsaPub.len = testPubKey->len; pubKey.key.mldsaPub.data = testPubKey->x; ret = CRYPT_EAL_PkeySetPub(ctx, &pubKey); ASSERT_EQ(ret, CRYPT_SUCCESS); ret = CRYPT_EAL_PkeyVerify(ctx, CRYPT_MD_MAX, msg->x, msg->len, sign->x, sign->len); ASSERT_EQ(ret, CRYPT_SUCCESS); CRYPT_EAL_PkeyCtx *ctx2 = NULL; #ifdef HITLS_CRYPTO_PROVIDER ctx2 = CRYPT_EAL_ProviderPkeyNewCtx(NULL, CRYPT_PKEY_ML_DSA, CRYPT_EAL_PKEY_SIGN_OPERATE, "provider=default"); #else ctx2 = CRYPT_EAL_PkeyNewCtx(CRYPT_PKEY_ML_DSA); #endif ASSERT_TRUE(ctx2 != NULL); val = (uint32_t)type; ret = CRYPT_EAL_PkeySetParaById(ctx2, val); ASSERT_EQ(ret, CRYPT_SUCCESS); ret = CRYPT_EAL_PkeyGen(ctx2); ASSERT_EQ(ret, CRYPT_SUCCESS); ret = CRYPT_EAL_PkeyGetPub(ctx2, &pubKey); ASSERT_EQ(ret, CRYPT_SUCCESS); ASSERT_EQ(pubKey.key.mldsaPub.len, testPubKey->len); ret = CRYPT_EAL_PkeyGetPrv(ctx2, &prvKey); ASSERT_EQ(ret, CRYPT_SUCCESS); ASSERT_EQ(prvKey.key.mldsaPrv.len, testPrvKey->len); val = 1; ret = CRYPT_EAL_PkeyCtrl(ctx2, CRYPT_CTRL_SET_PREHASH_FLAG, &val, sizeof(val)); ASSERT_EQ(ret, CRYPT_SUCCESS); ret = CRYPT_EAL_PkeySign(ctx2, CRYPT_MD_SHA256, msg->x, msg->len, out, &outLen); ASSERT_EQ(ret, CRYPT_SUCCESS); ret = CRYPT_EAL_PkeyVerify(ctx2, CRYPT_MD_SHA256, msg->x, msg->len, out, outLen); ASSERT_EQ(ret, CRYPT_SUCCESS); ret = CRYPT_EAL_PkeyCmp(ctx, ctx2); ASSERT_NE(ret, CRYPT_SUCCESS); CRYPT_EAL_PkeyCtx *ctx3 = CRYPT_EAL_PkeyDupCtx(ctx); ASSERT_TRUE(ctx3 != NULL); ret = CRYPT_EAL_PkeyCmp(ctx, ctx3); ASSERT_EQ(ret, CRYPT_SUCCESS); EXIT: CRYPT_EAL_PkeyFreeCtx(ctx); CRYPT_EAL_PkeyFreeCtx(ctx2); CRYPT_EAL_PkeyFreeCtx(ctx3); BSL_SAL_Free(out); TestRandDeInit(); } /* END_CASE */
2301_79861745/bench_create
testcode/sdv/testcase/crypto/mldsa/test_suite_sdv_mldsa.c
C
unknown
21,851
/* * This file is part of the openHiTLS project. * * openHiTLS is licensed under the Mulan PSL v2. * You can use this software according to the terms and conditions of the Mulan PSL v2. * You may obtain a copy of Mulan PSL v2 at: * * http://license.coscl.org.cn/MulanPSL2 * * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, * EITHER EXPRESS 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 <stdio.h> #include <string.h> #include "securec.h" #include "hitls_build.h" #include "bsl_err.h" #include "bsl_sal.h" #include "crypt_errno.h" #include "crypt_eal_pkey.h" #include "crypt_algid.h" #include "crypt_mldsa.h" #include "ml_dsa_local.h" #include "crypt_eal_pkey.h" #include "eal_pkey_local.h" /* END_HEADER */ /* @ * @test SDV_CRYPTO_MLDSA_CHECK_KEYPAIR_TC001 * @spec - * @title Key pair generation function test @ */ /* BEGIN_CASE */ void SDV_CRYPTO_MLDSA_CHECK_KEYPAIR_TC001(int type) { #if !defined(HITLS_CRYPTO_MLDSA_CHECK) (void)type; SKIP_TEST(); #else TestMemInit(); TestRandInit(); CRYPT_EAL_PkeyCtx *ctx = NULL; CRYPT_EAL_PkeyCtx *pubCtx = NULL; CRYPT_EAL_PkeyCtx *prvCtx = NULL; CRYPT_EAL_PkeyPrv prvKey = { 0 }; CRYPT_EAL_PkeyPub pubKey = { 0 }; uint32_t prvKeyLen = 4896; // max len = 4896 uint32_t pubKeyLen = 2592; // max len = 2592 uint8_t *prvKeyBuf = BSL_SAL_Malloc(prvKeyLen); uint8_t *pubKeyBuf = BSL_SAL_Malloc(pubKeyLen); #ifdef HITLS_CRYPTO_PROVIDER ctx = CRYPT_EAL_ProviderPkeyNewCtx(NULL, CRYPT_PKEY_ML_DSA, CRYPT_EAL_PKEY_SIGN_OPERATE, "provider=default"); pubCtx = CRYPT_EAL_ProviderPkeyNewCtx(NULL, CRYPT_PKEY_ML_DSA, CRYPT_EAL_PKEY_SIGN_OPERATE, "provider=default"); prvCtx = CRYPT_EAL_ProviderPkeyNewCtx(NULL, CRYPT_PKEY_ML_DSA, CRYPT_EAL_PKEY_SIGN_OPERATE, "provider=default"); #else ctx = CRYPT_EAL_PkeyNewCtx(CRYPT_PKEY_ML_DSA); pubCtx = CRYPT_EAL_PkeyNewCtx(CRYPT_PKEY_ML_DSA); prvCtx = CRYPT_EAL_PkeyNewCtx(CRYPT_PKEY_ML_DSA); #endif ASSERT_TRUE(pubKeyBuf != NULL); ASSERT_TRUE(prvKeyBuf != NULL); ASSERT_TRUE(ctx != NULL); ASSERT_TRUE(pubCtx != NULL); ASSERT_TRUE(prvCtx != NULL); prvKey.id = CRYPT_PKEY_ML_DSA; pubKey.id = CRYPT_PKEY_ML_DSA; ASSERT_EQ(CRYPT_EAL_PkeySetParaById(ctx, type), CRYPT_SUCCESS); ASSERT_EQ(CRYPT_EAL_PkeySetParaById(pubCtx, type), CRYPT_SUCCESS); ASSERT_EQ(CRYPT_EAL_PkeySetParaById(prvCtx, type), CRYPT_SUCCESS); prvKey.key.mldsaPrv.len = prvKeyLen; prvKey.key.mldsaPrv.data = prvKeyBuf; pubKey.key.mldsaPub.len = pubKeyLen; pubKey.key.mldsaPub.data = pubKeyBuf; ASSERT_EQ(CRYPT_EAL_PkeyGen(ctx), CRYPT_SUCCESS); ASSERT_EQ(CRYPT_EAL_PkeyPairCheck(ctx, ctx), CRYPT_SUCCESS); ASSERT_EQ(CRYPT_EAL_PkeyGetPrv(ctx, &prvKey), CRYPT_SUCCESS); ASSERT_EQ(CRYPT_EAL_PkeyGetPub(ctx, &pubKey), CRYPT_SUCCESS); ASSERT_EQ(CRYPT_EAL_PkeySetPrv(prvCtx, &prvKey), CRYPT_SUCCESS); ASSERT_EQ(CRYPT_EAL_PkeySetPub(pubCtx, &pubKey), CRYPT_SUCCESS); ASSERT_EQ(CRYPT_EAL_PkeyPairCheck(prvCtx, pubCtx), CRYPT_MLDSA_INVALID_PUBKEY); // no pub ASSERT_EQ(CRYPT_EAL_PkeyPairCheck(pubCtx, pubCtx), CRYPT_MLDSA_INVALID_PRVKEY); // no prv ASSERT_EQ(CRYPT_EAL_PkeyPairCheck(pubCtx, prvCtx), CRYPT_SUCCESS); EXIT: CRYPT_EAL_PkeyFreeCtx(ctx); CRYPT_EAL_PkeyFreeCtx(pubCtx); CRYPT_EAL_PkeyFreeCtx(prvCtx); BSL_SAL_Free(prvKeyBuf); BSL_SAL_Free(pubKeyBuf); TestRandDeInit(); #endif } /* END_CASE */ /* @ * @test SDV_CRYPTO_MLDSA_CHECK_KEYPAIR_TC002 * @spec - * @title Key pair generation function invalid test @ */ /* BEGIN_CASE */ void SDV_CRYPTO_MLDSA_CHECK_KEYPAIR_TC002(void) { #if !defined(HITLS_CRYPTO_MLDSA_CHECK) SKIP_TEST(); #else TestMemInit(); TestRandInit(); int32_t bits1 = CRYPT_MLDSA_TYPE_MLDSA_44; int32_t bits2 = CRYPT_MLDSA_TYPE_MLDSA_65; CRYPT_EAL_PkeyCtx *ctx1 = NULL; CRYPT_EAL_PkeyCtx *ctx2 = NULL; CRYPT_EAL_PkeyCtx *ctx3 = NULL; #ifdef HITLS_CRYPTO_PROVIDER ctx1 = CRYPT_EAL_ProviderPkeyNewCtx(NULL, CRYPT_PKEY_ML_DSA, CRYPT_EAL_PKEY_SIGN_OPERATE, "provider=default"); ctx2 = CRYPT_EAL_ProviderPkeyNewCtx(NULL, CRYPT_PKEY_ML_DSA, CRYPT_EAL_PKEY_SIGN_OPERATE, "provider=default"); ctx3 = CRYPT_EAL_ProviderPkeyNewCtx(NULL, CRYPT_PKEY_ML_DSA, CRYPT_EAL_PKEY_SIGN_OPERATE, "provider=default"); #else ctx1 = CRYPT_EAL_PkeyNewCtx(CRYPT_PKEY_ML_DSA); ctx2 = CRYPT_EAL_PkeyNewCtx(CRYPT_PKEY_ML_DSA); ctx3 = CRYPT_EAL_PkeyNewCtx(CRYPT_PKEY_ML_DSA); #endif ASSERT_TRUE(ctx1 != NULL); ASSERT_TRUE(ctx2 != NULL); ASSERT_TRUE(ctx3 != NULL); ASSERT_EQ(CRYPT_EAL_PkeyPairCheck(NULL, NULL), CRYPT_NULL_INPUT); ASSERT_EQ(CRYPT_EAL_PkeyPairCheck(ctx1, ctx2), CRYPT_MLDSA_KEYINFO_NOT_SET); // different key-info ASSERT_EQ(CRYPT_EAL_PkeySetParaById(ctx1, bits1), CRYPT_SUCCESS); ASSERT_EQ(CRYPT_EAL_PkeySetParaById(ctx2, bits1), CRYPT_SUCCESS); ASSERT_EQ(CRYPT_EAL_PkeySetParaById(ctx3, bits2), CRYPT_SUCCESS); ASSERT_EQ(CRYPT_EAL_PkeyGen(ctx1), CRYPT_SUCCESS); ASSERT_EQ(CRYPT_EAL_PkeyGen(ctx2), CRYPT_SUCCESS); ASSERT_EQ(CRYPT_EAL_PkeyPairCheck(ctx1, ctx1), CRYPT_SUCCESS); ASSERT_EQ(CRYPT_EAL_PkeyPairCheck(ctx2, ctx2), CRYPT_SUCCESS); ASSERT_EQ(CRYPT_EAL_PkeyPairCheck(ctx1, ctx2), CRYPT_MLDSA_PAIRWISE_CHECK_FAIL); EXIT: CRYPT_EAL_PkeyFreeCtx(ctx1); CRYPT_EAL_PkeyFreeCtx(ctx2); CRYPT_EAL_PkeyFreeCtx(ctx3); TestRandDeInit(); #endif } /* END_CASE */ /* @ * @test SDV_CRYPTO_MLDSA_CHECK_PRVKEY_TC001 * @spec - * @title Key generation and check prv key @ */ /* BEGIN_CASE */ void SDV_CRYPTO_MLDSA_CHECK_PRVKEY_TC001(int type) { #if !defined(HITLS_CRYPTO_MLDSA_CHECK) (void)type; SKIP_TEST(); #else TestMemInit(); TestRandInit(); CRYPT_EAL_PkeyCtx *ctx = NULL; CRYPT_EAL_PkeyCtx *prvCtx = NULL; CRYPT_EAL_PkeyPrv sk = { 0 }; uint32_t skLen = 0; CRYPT_ML_DSA_Ctx *tmp = NULL; #ifdef HITLS_CRYPTO_PROVIDER ctx = CRYPT_EAL_ProviderPkeyNewCtx(NULL, CRYPT_PKEY_ML_DSA, CRYPT_EAL_PKEY_SIGN_OPERATE, "provider=default"); prvCtx = CRYPT_EAL_ProviderPkeyNewCtx(NULL, CRYPT_PKEY_ML_DSA, CRYPT_EAL_PKEY_SIGN_OPERATE, "provider=default"); #else ctx = CRYPT_EAL_PkeyNewCtx(CRYPT_PKEY_ML_DSA); prvCtx = CRYPT_EAL_PkeyNewCtx(CRYPT_PKEY_ML_DSA); #endif ASSERT_TRUE(ctx != NULL); ASSERT_TRUE(prvCtx != NULL); uint32_t val = (uint32_t)type; sk.id = CRYPT_PKEY_ML_DSA; ASSERT_EQ(CRYPT_EAL_PkeyPrvCheck(NULL), CRYPT_NULL_INPUT); ASSERT_EQ(CRYPT_EAL_PkeyPrvCheck(prvCtx), CRYPT_MLDSA_KEYINFO_NOT_SET); ASSERT_EQ(CRYPT_EAL_PkeySetParaById(ctx, val), CRYPT_SUCCESS); ASSERT_EQ(CRYPT_EAL_PkeySetParaById(prvCtx, val), CRYPT_SUCCESS); ASSERT_EQ(CRYPT_EAL_PkeyCtrl(ctx, CRYPT_CTRL_GET_PRVKEY_LEN, &skLen, sizeof(skLen)), CRYPT_SUCCESS); sk.key.mldsaPrv.len = skLen; sk.key.mldsaPrv.data = BSL_SAL_Malloc(skLen); ASSERT_EQ(CRYPT_EAL_PkeyGen(ctx), CRYPT_SUCCESS); ASSERT_EQ(CRYPT_EAL_PkeyGetPrv(ctx, &sk), CRYPT_SUCCESS); ASSERT_EQ(CRYPT_EAL_PkeyPrvCheck(prvCtx), CRYPT_MLDSA_INVALID_PRVKEY); // no dk ASSERT_EQ(CRYPT_EAL_PkeySetPrv(prvCtx, &sk), CRYPT_SUCCESS); ASSERT_EQ(CRYPT_EAL_PkeyPrvCheck(prvCtx), CRYPT_SUCCESS); // dk is set tmp = (CRYPT_ML_DSA_Ctx *)prvCtx->key; tmp->prvLen = 1; ASSERT_EQ(CRYPT_EAL_PkeyPrvCheck(prvCtx), CRYPT_MLDSA_INVALID_PRVKEY); // dk is set EXIT: CRYPT_EAL_PkeyFreeCtx(ctx); CRYPT_EAL_PkeyFreeCtx(prvCtx); BSL_SAL_Free(sk.key.mldsaPrv.data); TestRandDeInit(); #endif } /* END_CASE */
2301_79861745/bench_create
testcode/sdv/testcase/crypto/mldsa/test_suite_sdv_mldsa_util.c
C
unknown
7,715
/* * This file is part of the openHiTLS project. * * openHiTLS is licensed under the Mulan PSL v2. * You can use this software according to the terms and conditions of the Mulan PSL v2. * You may obtain a copy of Mulan PSL v2 at: * * http://license.coscl.org.cn/MulanPSL2 * * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, * EITHER EXPRESS 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 "bsl_sal.h" #include "crypt_errno.h" #include "crypt_algid.h" #include "crypt_eal_pkey.h" #include "crypt_util_rand.h" #include "eal_pkey_local.h" #include "securec.h" #include "crypt_mlkem.h" #include "ml_kem_local.h" /* END_HEADER */ static uint8_t gKyberRandBuf[3][32] = { 0 }; uint32_t gKyberRandNum = 0; static int32_t TEST_KyberRandom(uint8_t *randNum, uint32_t randLen) { memcpy_s(randNum, randLen, gKyberRandBuf[gKyberRandNum], 32); gKyberRandNum++; return 0; } static int32_t TEST_KyberRandomEx(void *libCtx, uint8_t *randNum, uint32_t randLen) { (void)libCtx; return TEST_KyberRandom(randNum, randLen); } /* @ * @test SDV_CRYPTO_MLKEM_CTRL_API_TC001 * @spec - * @title CRYPT_EAL_PkeyCtrl test * @precon nan * @brief 1. creat context * 2.invoke CRYPT_EAL_PkeyCtrl to transfer various exception parameters. * 3.call CRYPT_EAL_PkeyCtrl repeatedly to set the key information. * @expect 1.success 2.returned as expected 3.cannot be set repeatedly. * @prior nan * @auto FALSE @ */ /* BEGIN_CASE */ void SDV_CRYPTO_MLKEM_CTRL_API_TC001(int bits) { TestMemInit(); CRYPT_RandRegist(TestSimpleRand); CRYPT_EAL_PkeyCtx *ctx = CRYPT_EAL_PkeyNewCtx(CRYPT_PKEY_ML_KEM); uint32_t val = (uint32_t)bits; int ret = CRYPT_EAL_PkeyCtrl(ctx, CRYPT_CTRL_SET_PARA_BY_ID + 100, &val, sizeof(val)); ASSERT_EQ(ret, CRYPT_MLKEM_CTRL_NOT_SUPPORT); ret = CRYPT_EAL_PkeyCtrl(NULL, CRYPT_CTRL_SET_PARA_BY_ID, &val, sizeof(val)); ASSERT_EQ(ret, CRYPT_NULL_INPUT); ret = CRYPT_EAL_PkeyCtrl(ctx, CRYPT_CTRL_SET_PARA_BY_ID, NULL, sizeof(val)); ASSERT_EQ(ret, CRYPT_NULL_INPUT); ret = CRYPT_EAL_PkeyCtrl(ctx, CRYPT_CTRL_SET_PARA_BY_ID, &val, sizeof(val) - 1); ASSERT_EQ(ret, CRYPT_INVALID_ARG); ret = CRYPT_EAL_PkeyCtrl(ctx, CRYPT_CTRL_SET_PARA_BY_ID, &val, sizeof(val)); ASSERT_EQ(ret, CRYPT_SUCCESS); ret = CRYPT_EAL_PkeyCtrl(ctx, CRYPT_CTRL_SET_PARA_BY_ID, &val, sizeof(val)); ASSERT_EQ(ret, CRYPT_MLKEM_CTRL_INIT_REPEATED); EXIT: CRYPT_EAL_PkeyFreeCtx(ctx); CRYPT_RandRegist(NULL); return; } /* END_CASE */ /* @ * @test SDV_CRYPTO_MLKEM_KEYGEN_API_TC001 * @spec - * @title CRYPT_EAL_PkeyGen test * @precon nan * @brief 1.register a random number and create a context. * 2.invoke CRYPT_EAL_PkeyGen and transfer various parameters. * 3.check the return value. * @expect 1.success 2.success 3.the returned value is the same as expected. * @prior nan * @auto FALSE @ */ /* BEGIN_CASE */ void SDV_CRYPTO_MLKEM_KEYGEN_API_TC001(int bits) { TestMemInit(); CRYPT_EAL_PkeyCtx *ctx = NULL; #ifdef HITLS_CRYPTO_PROVIDER ctx = CRYPT_EAL_ProviderPkeyNewCtx(NULL, CRYPT_PKEY_ML_KEM, CRYPT_EAL_PKEY_KEM_OPERATE, "provider=default"); #else ctx = CRYPT_EAL_PkeyNewCtx(CRYPT_PKEY_ML_KEM); #endif ASSERT_TRUE(ctx != NULL); int32_t ret = CRYPT_EAL_PkeyGen(ctx); ASSERT_EQ(ret, CRYPT_MLKEM_KEYINFO_NOT_SET); uint32_t val = (uint32_t)bits; ret = CRYPT_EAL_PkeySetParaById(ctx, val); ASSERT_EQ(ret, CRYPT_SUCCESS); ret = CRYPT_EAL_PkeyEncapsInit(ctx, NULL); ASSERT_EQ(ret, CRYPT_SUCCESS); ret = CRYPT_EAL_PkeyGen(ctx); ASSERT_EQ(ret, CRYPT_NO_REGIST_RAND); CRYPT_RandRegist(TestSimpleRand); CRYPT_RandRegistEx(TestSimpleRandEx); ret = CRYPT_EAL_PkeyGen(ctx); ASSERT_EQ(ret, CRYPT_SUCCESS); ret = CRYPT_EAL_PkeyGen(ctx); ASSERT_EQ(ret, CRYPT_SUCCESS); EXIT: CRYPT_EAL_PkeyFreeCtx(ctx); CRYPT_RandRegist(NULL); CRYPT_RandRegistEx(NULL); return; } /* END_CASE */ /* Use default random numbers for end-to-end testing */ /* BEGIN_CASE */ void SDV_CRYPTO_MLKEM_KEYGEN_API_TC002(int bits) { TestMemInit(); TestRandInit(); CRYPT_EAL_PkeyCtx *ctx = NULL; #ifdef HITLS_CRYPTO_PROVIDER ctx = CRYPT_EAL_ProviderPkeyNewCtx(NULL, CRYPT_PKEY_ML_KEM, CRYPT_EAL_PKEY_KEM_OPERATE, "provider=default"); #else ctx = CRYPT_EAL_PkeyNewCtx(CRYPT_PKEY_ML_KEM); #endif ASSERT_TRUE(ctx != NULL); uint32_t val = (uint32_t)bits; int32_t ret = CRYPT_EAL_PkeySetParaById(ctx, val); ASSERT_EQ(ret, CRYPT_SUCCESS); ret = CRYPT_EAL_PkeyEncapsInit(ctx, NULL); ASSERT_EQ(ret, CRYPT_SUCCESS); ret = CRYPT_EAL_PkeyGen(ctx); ASSERT_EQ(ret, CRYPT_SUCCESS); ret = CRYPT_EAL_PkeyGen(ctx); ASSERT_EQ(ret, CRYPT_SUCCESS); EXIT: CRYPT_EAL_PkeyFreeCtx(ctx); TestRandDeInit(); return; } /* END_CASE */ /* @ * @test SDV_CRYPTO_MLKEM_ENCAPS_API_TC001 * @spec - * @title CRYPT_EAL_PkeyEncaps test * @precon nan * @brief 1.register a random number and generate a context and key pair. * 2.call CRYPT_EAL_PkeyEncaps to transfer abnormal values. * 3. check the return value. * @expect 1.success 2.success 3.the returned value is the same as expected. * @prior nan * @auto FALSE @ */ /* BEGIN_CASE */ void SDV_CRYPTO_MLKEM_ENCAPS_API_TC001(int bits) { TestMemInit(); TestRandInit(); CRYPT_EAL_PkeyCtx *ctx = NULL; #ifdef HITLS_CRYPTO_PROVIDER ctx = CRYPT_EAL_ProviderPkeyNewCtx(NULL, CRYPT_PKEY_ML_KEM, CRYPT_EAL_PKEY_KEM_OPERATE, "provider=default"); #else ctx = CRYPT_EAL_PkeyNewCtx(CRYPT_PKEY_ML_KEM); #endif ASSERT_TRUE(ctx != NULL); uint32_t val = (uint32_t)bits; int32_t ret = CRYPT_EAL_PkeySetParaById(ctx, val); ASSERT_EQ(ret, CRYPT_SUCCESS); ret = CRYPT_EAL_PkeyEncapsInit(ctx, NULL); ASSERT_EQ(ret, CRYPT_SUCCESS); uint32_t cipherLen = 0; ret = CRYPT_EAL_PkeyCtrl(ctx, CRYPT_CTRL_GET_CIPHERTEXT_LEN, &cipherLen, sizeof(cipherLen)); ASSERT_EQ(ret, CRYPT_SUCCESS); uint8_t *ciphertext = BSL_SAL_Malloc(cipherLen); uint32_t sharedLen = 32; uint8_t *sharedKey = BSL_SAL_Malloc(sharedLen); ret = CRYPT_EAL_PkeyGen(ctx); ASSERT_EQ(ret, CRYPT_SUCCESS); ret = CRYPT_EAL_PkeyEncaps(NULL, ciphertext, &cipherLen, sharedKey, &sharedLen); ASSERT_EQ(ret, CRYPT_NULL_INPUT); ret = CRYPT_EAL_PkeyEncaps(ctx, NULL, &cipherLen, sharedKey, &sharedLen); ASSERT_EQ(ret, CRYPT_NULL_INPUT); ret = CRYPT_EAL_PkeyEncaps(ctx, ciphertext, NULL, sharedKey, &sharedLen); ASSERT_EQ(ret, CRYPT_NULL_INPUT); ret = CRYPT_EAL_PkeyEncaps(ctx, ciphertext, &cipherLen, NULL, &sharedLen); ASSERT_EQ(ret, CRYPT_NULL_INPUT); ret = CRYPT_EAL_PkeyEncaps(ctx, ciphertext, &cipherLen, sharedKey, NULL); ASSERT_EQ(ret, CRYPT_NULL_INPUT); cipherLen = cipherLen - 1; ret = CRYPT_EAL_PkeyEncaps(ctx, ciphertext, &cipherLen, sharedKey, &sharedLen); ASSERT_EQ(ret, CRYPT_MLKEM_LEN_NOT_ENOUGH); cipherLen = cipherLen + 1; sharedLen = sharedLen - 1; ret = CRYPT_EAL_PkeyEncaps(ctx, ciphertext, &cipherLen, sharedKey, &sharedLen); ASSERT_EQ(ret, CRYPT_MLKEM_LEN_NOT_ENOUGH); sharedLen = sharedLen + 1; ret = CRYPT_EAL_PkeyEncaps(ctx, ciphertext, &cipherLen, sharedKey, &sharedLen); ASSERT_EQ(ret, CRYPT_SUCCESS); EXIT: CRYPT_EAL_PkeyFreeCtx(ctx); BSL_SAL_Free(ciphertext); BSL_SAL_Free(sharedKey); TestRandDeInit(); return; } /* END_CASE */ /* @ * @test SDV_CRYPTO_MLKEM_DECAPS_API_TC001 * @spec - * @title CRYPT_EAL_PkeyEncaps test * @precon nan * @brief 1.register a random number and generate a context and key pair. * 2.call CRYPT_EAL_PkeyDecaps to transfer various abnormal values. * 3.check return value * @expect 1.success 2.success 3.the returned value is the same as expected. * @prior nan * @auto FALSE @ */ /* BEGIN_CASE */ void SDV_CRYPTO_MLKEM_DECAPS_API_TC001(int bits) { TestMemInit(); TestRandInit(); CRYPT_EAL_PkeyCtx *ctx = NULL; #ifdef HITLS_CRYPTO_PROVIDER ctx = CRYPT_EAL_ProviderPkeyNewCtx(NULL, CRYPT_PKEY_ML_KEM, CRYPT_EAL_PKEY_KEM_OPERATE, "provider=default"); #else ctx = CRYPT_EAL_PkeyNewCtx(CRYPT_PKEY_ML_KEM); #endif ASSERT_TRUE(ctx != NULL); uint32_t val = (uint32_t)bits; int32_t ret = CRYPT_EAL_PkeySetParaById(ctx, val); ASSERT_EQ(ret, CRYPT_SUCCESS); ret = CRYPT_EAL_PkeyDecapsInit(ctx, NULL); ASSERT_EQ(ret, CRYPT_SUCCESS); uint32_t cipherLen = 0; ret = CRYPT_EAL_PkeyCtrl(ctx, CRYPT_CTRL_GET_CIPHERTEXT_LEN, &cipherLen, sizeof(cipherLen)); ASSERT_EQ(ret, CRYPT_SUCCESS); uint8_t *ciphertext = BSL_SAL_Malloc(cipherLen); uint32_t sharedLen = 32; uint8_t *sharedKey = BSL_SAL_Malloc(sharedLen); ret = CRYPT_EAL_PkeyGen(ctx); ASSERT_EQ(ret, CRYPT_SUCCESS); ret = CRYPT_EAL_PkeyEncaps(ctx, ciphertext, &cipherLen, sharedKey, &sharedLen); ASSERT_EQ(ret, CRYPT_SUCCESS); ret = CRYPT_EAL_PkeyDecaps(NULL, ciphertext, cipherLen, sharedKey, &sharedLen); ASSERT_EQ(ret, CRYPT_NULL_INPUT); ret = CRYPT_EAL_PkeyDecaps(ctx, NULL, cipherLen, sharedKey, &sharedLen); ASSERT_EQ(ret, CRYPT_NULL_INPUT); ret = CRYPT_EAL_PkeyDecaps(ctx, ciphertext, cipherLen, NULL, &sharedLen); ASSERT_EQ(ret, CRYPT_NULL_INPUT); ret = CRYPT_EAL_PkeyDecaps(ctx, ciphertext, cipherLen, sharedKey, NULL); ASSERT_EQ(ret, CRYPT_NULL_INPUT); cipherLen = cipherLen - 1; ret = CRYPT_EAL_PkeyDecaps(ctx, ciphertext, cipherLen, sharedKey, &sharedLen); ASSERT_EQ(ret, CRYPT_MLKEM_LEN_NOT_ENOUGH); cipherLen = cipherLen + 1; sharedLen = sharedLen - 1; ret = CRYPT_EAL_PkeyDecaps(ctx, ciphertext, cipherLen, sharedKey, &sharedLen); ASSERT_EQ(ret, CRYPT_MLKEM_LEN_NOT_ENOUGH); sharedLen = sharedLen + 1; ret = CRYPT_EAL_PkeyDecaps(ctx, ciphertext, cipherLen, sharedKey, &sharedLen); ASSERT_EQ(ret, CRYPT_SUCCESS); EXIT: CRYPT_EAL_PkeyFreeCtx(ctx); BSL_SAL_Free(ciphertext); BSL_SAL_Free(sharedKey); TestRandDeInit(); return; } /* END_CASE */ /* @ * @test SDV_CRYPTO_MLKEM_SETPUB_API_TC002 * @spec - * @title CRYPT_EAL_PkeySetPub and CRYPT_EAL_PkeyGetPub * @precon nan * @brief 1.register a random number and create a context. * 2.call CRYPT_EAL_PkeySetPub and CRYPT_EAL_PkeyGetPub and transfer various parameters. * 3.check return value * @expect 1.success 2.success 3.the returned value is the same as expected. * @prior nan * @auto FALSE @ */ /* BEGIN_CASE */ void SDV_CRYPTO_MLKEM_SETPUB_API_TC002(int bits, Hex *testEK) { TestMemInit(); CRYPT_RandRegist(TestSimpleRand); CRYPT_EAL_PkeyCtx *ctx = CRYPT_EAL_PkeyNewCtx(CRYPT_PKEY_ML_KEM); uint32_t val = (uint32_t)bits; int ret = CRYPT_EAL_PkeySetParaById(ctx, val); ASSERT_EQ(ret, CRYPT_SUCCESS); ret = CRYPT_EAL_PkeyEncapsInit(ctx, NULL); ASSERT_EQ(ret, CRYPT_SUCCESS); uint32_t encapsKeyLen = 0; ret = CRYPT_EAL_PkeyCtrl(ctx, CRYPT_CTRL_GET_PUBKEY_LEN, &encapsKeyLen, sizeof(encapsKeyLen)); ASSERT_EQ(ret, CRYPT_SUCCESS); CRYPT_EAL_PkeyPub ek = { 0 }; ASSERT_EQ(CRYPT_EAL_PkeySetPub(ctx, &ek), CRYPT_EAL_ERR_ALGID); ek.id = CRYPT_PKEY_ML_KEM; ASSERT_EQ(CRYPT_EAL_PkeySetPub(ctx, &ek), CRYPT_NULL_INPUT); ek.key.kemEk.data = BSL_SAL_Malloc(encapsKeyLen); (void)memcpy_s(ek.key.kemEk.data, encapsKeyLen, testEK->x, testEK->len); ek.key.kemEk.len = encapsKeyLen - 1; ASSERT_EQ(CRYPT_EAL_PkeySetPub(ctx, &ek), CRYPT_MLKEM_KEYLEN_ERROR); ek.key.kemEk.len = encapsKeyLen; ASSERT_EQ(CRYPT_EAL_PkeyGetPub(ctx, &ek), CRYPT_MLKEM_KEY_NOT_SET); ASSERT_EQ(CRYPT_EAL_PkeySetPub(ctx, &ek), CRYPT_SUCCESS); (void)memset_s(ek.key.kemEk.data, encapsKeyLen, 0, encapsKeyLen); ek.key.kemEk.len = encapsKeyLen - 1; ASSERT_EQ(CRYPT_EAL_PkeyGetPub(ctx, &ek), CRYPT_MLKEM_KEYLEN_ERROR); ek.key.kemEk.len = encapsKeyLen + 1; ASSERT_EQ(CRYPT_EAL_PkeyGetPub(ctx, &ek), CRYPT_SUCCESS); ASSERT_COMPARE("compare ek", ek.key.kemEk.data, ek.key.kemEk.len, testEK->x, testEK->len); EXIT: CRYPT_EAL_PkeyFreeCtx(ctx); BSL_SAL_Free(ek.key.kemEk.data); CRYPT_RandRegist(NULL); return; } /* END_CASE */ /* @ * @test SDV_CRYPTO_MLKEM_SETPRV_API_TC002 * @spec - * @title CRYPT_EAL_PkeySetPrv and CRYPT_EAL_PkeyGetPrv * @precon nan * @brief 1.register a random number and create a context. * 2.call CRYPT_EAL_PkeySetPrv and CRYPT_EAL_PkeyGetPrv and transfer various parameters. * 3.check return value * @expect 1.success 2.success 3.the returned value is the same as expected. * @prior nan * @auto FALSE @ */ /* BEGIN_CASE */ void SDV_CRYPTO_MLKEM_SETPRV_API_TC002(int bits, Hex *testDK) { TestMemInit(); CRYPT_RandRegist(TestSimpleRand); CRYPT_EAL_PkeyCtx *ctx = CRYPT_EAL_PkeyNewCtx(CRYPT_PKEY_ML_KEM); uint32_t val = (uint32_t)bits; int ret = CRYPT_EAL_PkeySetParaById(ctx, val); ASSERT_EQ(ret, CRYPT_SUCCESS); ret = CRYPT_EAL_PkeyEncapsInit(ctx, NULL); ASSERT_EQ(ret, CRYPT_SUCCESS); uint32_t decapsKeyLen = 0; ret = CRYPT_EAL_PkeyCtrl(ctx, CRYPT_CTRL_GET_PRVKEY_LEN, &decapsKeyLen, sizeof(decapsKeyLen)); ASSERT_EQ(ret, CRYPT_SUCCESS); CRYPT_EAL_PkeyPrv dk = { 0 }; ASSERT_EQ(CRYPT_EAL_PkeySetPrv(ctx, &dk), CRYPT_EAL_ERR_ALGID); dk.id = CRYPT_PKEY_ML_KEM; ASSERT_EQ(CRYPT_EAL_PkeySetPrv(ctx, &dk), CRYPT_NULL_INPUT); dk.key.kemDk.data = BSL_SAL_Malloc(decapsKeyLen); (void)memcpy_s(dk.key.kemDk.data, decapsKeyLen, testDK->x, testDK->len); dk.key.kemDk.len = decapsKeyLen - 1; ASSERT_EQ(CRYPT_EAL_PkeySetPrv(ctx, &dk), CRYPT_MLKEM_KEYLEN_ERROR); dk.key.kemDk.len = decapsKeyLen; ASSERT_EQ(CRYPT_EAL_PkeyGetPrv(ctx, &dk), CRYPT_MLKEM_KEY_NOT_SET); ASSERT_EQ(CRYPT_EAL_PkeySetPrv(ctx, &dk), CRYPT_SUCCESS); (void)memset_s(dk.key.kemDk.data, decapsKeyLen, 0, decapsKeyLen); dk.key.kemDk.len = decapsKeyLen - 1; ASSERT_EQ(CRYPT_EAL_PkeyGetPrv(ctx, &dk), CRYPT_MLKEM_KEYLEN_ERROR); dk.key.kemDk.len = decapsKeyLen; ASSERT_EQ(CRYPT_EAL_PkeyGetPrv(ctx, &dk), CRYPT_SUCCESS); ASSERT_COMPARE("compare de", dk.key.kemDk.data, dk.key.kemDk.len, testDK->x, testDK->len); EXIT: CRYPT_EAL_PkeyFreeCtx(ctx); BSL_SAL_Free(dk.key.kemDk.data); CRYPT_RandRegist(NULL); return; } /* END_CASE */ /* @ * @test SDV_CRYPTO_MLKEM_KEYCMP_FUNC_TC001 * @spec - * @title Context Comparison and Copy Test * @precon nan * @brief 1.Registers a random number that returns the specified value. * 2. Call CRYPT_EAL_PkeyGen to generate a key pair. The first two groups of random numbers are the same, * and the third group of random numbers is different. * 3. Call CRYPT_EAL_PkeyCopyCtx to copy the key pair. * 4. Invoke CRYPT_EAL_PkeyCmp to compare key pairs. * @expect 1.success 2.success 3.success 4.the returned value is the same as expected. * @prior nan * @auto FALSE @ */ /* BEGIN_CASE */ void SDV_CRYPTO_MLKEM_KEYCMP_FUNC_TC001(int bits, Hex *r0, Hex *r1, Hex *r2, int isProvider) { TestMemInit(); gKyberRandNum = 0; memcpy_s(gKyberRandBuf[0], 32, r0->x, r0->len); memcpy_s(gKyberRandBuf[1], 32, r1->x, r1->len); memcpy_s(gKyberRandBuf[2], 32, r2->x, r2->len); CRYPT_RandRegist(TEST_KyberRandom); CRYPT_RandRegistEx(TEST_KyberRandomEx); CRYPT_EAL_PkeyCtx *ctx = TestPkeyNewCtx(NULL, CRYPT_PKEY_ML_KEM, CRYPT_EAL_PKEY_KEM_OPERATE, "provider=default", isProvider); ASSERT_NE(ctx, NULL); uint32_t val = (uint32_t)bits; ASSERT_EQ(CRYPT_EAL_PkeySetParaById(ctx, val), CRYPT_SUCCESS); ASSERT_EQ(CRYPT_EAL_PkeyEncapsInit(ctx, NULL), CRYPT_SUCCESS); ASSERT_EQ(CRYPT_EAL_PkeyGen(ctx), CRYPT_SUCCESS); ASSERT_EQ(CRYPT_EAL_PkeyCmp(ctx, NULL), CRYPT_NULL_INPUT); gKyberRandNum = 0; CRYPT_EAL_PkeyCtx *ctx2 = TestPkeyNewCtx(NULL, CRYPT_PKEY_ML_KEM, CRYPT_EAL_PKEY_KEM_OPERATE, "provider=default", isProvider); ASSERT_NE(ctx2, NULL); ASSERT_EQ(CRYPT_EAL_PkeyCmp(ctx, ctx2), CRYPT_MLKEM_KEY_NOT_EQUAL); val = (uint32_t)bits; ASSERT_EQ(CRYPT_EAL_PkeySetParaById(ctx2, val), CRYPT_SUCCESS); ASSERT_EQ(CRYPT_EAL_PkeyCmp(ctx, ctx2), CRYPT_MLKEM_KEY_NOT_EQUAL); ASSERT_EQ(CRYPT_EAL_PkeyEncapsInit(ctx2, NULL), CRYPT_SUCCESS); ASSERT_EQ(CRYPT_EAL_PkeyCmp(ctx, ctx2), CRYPT_MLKEM_KEY_NOT_EQUAL); ASSERT_EQ(CRYPT_EAL_PkeyGen(ctx2), CRYPT_SUCCESS); ASSERT_EQ(CRYPT_EAL_PkeyCmp(ctx, ctx2), CRYPT_SUCCESS); gKyberRandNum = 1; CRYPT_EAL_PkeyCtx *ctx3 = TestPkeyNewCtx(NULL, CRYPT_PKEY_ML_KEM, CRYPT_EAL_PKEY_KEM_OPERATE, "provider=default", isProvider); ASSERT_NE(ctx3, NULL); val = (uint32_t)bits; ASSERT_EQ(CRYPT_EAL_PkeySetParaById(ctx3, val), CRYPT_SUCCESS); ASSERT_EQ(CRYPT_EAL_PkeyEncapsInit(ctx3, NULL), CRYPT_SUCCESS); ASSERT_EQ(CRYPT_EAL_PkeyGen(ctx3), CRYPT_SUCCESS); ASSERT_EQ(CRYPT_EAL_PkeyCmp(ctx, ctx3), CRYPT_MLKEM_KEY_NOT_EQUAL); CRYPT_EAL_PkeyCtx *ctx4 = BSL_SAL_Calloc(1u, sizeof(CRYPT_EAL_PkeyCtx)); ASSERT_EQ(CRYPT_EAL_PkeyCopyCtx(ctx4, ctx), CRYPT_SUCCESS); ASSERT_EQ(CRYPT_EAL_PkeyCmp(ctx, ctx4), CRYPT_SUCCESS); CRYPT_EAL_PkeyCtx *ctx5 = CRYPT_EAL_PkeyDupCtx(ctx); ASSERT_TRUE(ctx5 != NULL); ASSERT_EQ(CRYPT_EAL_PkeyCmp(ctx, ctx5), CRYPT_SUCCESS); EXIT: CRYPT_EAL_PkeyFreeCtx(ctx); CRYPT_EAL_PkeyFreeCtx(ctx2); CRYPT_EAL_PkeyFreeCtx(ctx3); CRYPT_EAL_PkeyFreeCtx(ctx4); CRYPT_EAL_PkeyFreeCtx(ctx5); CRYPT_RandRegist(NULL); CRYPT_RandRegistEx(NULL); return; } /* END_CASE */ /* @ * @test SDV_CRYPTO_MLKEM_KEYGEN_FUNC_TC001 * @spec - * @title Generating a Key Pair * @precon nan * @brief * 1. Register a random number and return the specified random number of the test vector. * 2. Call CRYPT_EAL_PkeyGen to generate a key pair. * 3. Compare key pairs and test vectors. * @expect * 1. success * 2. success * 3. the key pair is the same as the test vector. * @prior nan * @auto FALSE @ */ /* BEGIN_CASE */ void SDV_CRYPTO_MLKEM_KEYGEN_FUNC_TC001(int bits, Hex *z, Hex *d, Hex *testEK, Hex *testDK, int isProvider) { TestMemInit(); gKyberRandNum = 0; memcpy_s(gKyberRandBuf[0], 32, d->x, d->len); memcpy_s(gKyberRandBuf[1], 32, z->x, z->len); CRYPT_RandRegist(TEST_KyberRandom); CRYPT_RandRegistEx(TEST_KyberRandomEx); CRYPT_EAL_PkeyCtx *ctx = TestPkeyNewCtx(NULL, CRYPT_PKEY_ML_KEM, CRYPT_EAL_PKEY_KEM_OPERATE, "provider=default", isProvider); ASSERT_NE(ctx, NULL); uint32_t val = (uint32_t)bits; ASSERT_EQ(CRYPT_EAL_PkeySetParaById(ctx, val), CRYPT_SUCCESS); ASSERT_EQ(CRYPT_EAL_PkeyEncapsInit(ctx, NULL), CRYPT_SUCCESS); uint32_t encapsKeyLen = 0; ASSERT_EQ(CRYPT_EAL_PkeyCtrl(ctx, CRYPT_CTRL_GET_PUBKEY_LEN, &encapsKeyLen, sizeof(encapsKeyLen)), CRYPT_SUCCESS); uint32_t decapsKeyLen = 0; ASSERT_EQ(CRYPT_EAL_PkeyCtrl(ctx, CRYPT_CTRL_GET_PRVKEY_LEN, &decapsKeyLen, sizeof(decapsKeyLen)), CRYPT_SUCCESS); CRYPT_EAL_PkeyPub ek = { 0 }; ek.id = CRYPT_PKEY_ML_KEM; ek.key.kemEk.len = encapsKeyLen; ek.key.kemEk.data = BSL_SAL_Malloc(encapsKeyLen); CRYPT_EAL_PkeyPrv dk = { 0 }; dk.id = CRYPT_PKEY_ML_KEM; dk.key.kemDk.len = decapsKeyLen; dk.key.kemDk.data = BSL_SAL_Malloc(decapsKeyLen); ASSERT_EQ(CRYPT_EAL_PkeyGen(ctx), CRYPT_SUCCESS); ASSERT_EQ(CRYPT_EAL_PkeyGetPub(ctx, &ek), CRYPT_SUCCESS); ASSERT_EQ(CRYPT_EAL_PkeyGetPrv(ctx, &dk), CRYPT_SUCCESS); ASSERT_COMPARE("compare ek", ek.key.kemEk.data, ek.key.kemEk.len, testEK->x, testEK->len); ASSERT_COMPARE("compare dk", dk.key.kemDk.data, dk.key.kemDk.len, testDK->x, testDK->len); EXIT: BSL_SAL_Free(ek.key.kemEk.data); BSL_SAL_Free(dk.key.kemDk.data); CRYPT_EAL_PkeyFreeCtx(ctx); CRYPT_RandRegist(NULL); CRYPT_RandRegistEx(NULL); return; } /* END_CASE */ /* @ * @test SDV_CRYPTO_MLKEM_ENCAPS_DECAPS_FUNC_TC001 * @spec - * @title Vector test for generating ciphertext, shared key, and decapsulation * @precon nan * @brief * 1. Register a random number and return the specified random number of the test vector. * 2. Call CRYPT_EAL_PkeyEncaps to generate the ciphertext and shared key. * 3. Compare the ciphertext and shared key with the test vector. * 4. Call CRYPT_EAL_PkeyDecaps to generate a shared key. * 5. Compare the shared key with the test vector. * @expect 1. Success 2. Success 3. The generation result is the same as expected 4. Success * 5. The generation result is the same as expected * @prior nan * @auto FALSE @ */ /* BEGIN_CASE */ void SDV_CRYPTO_MLKEM_ENCAPS_DECAPS_FUNC_TC001(int bits, Hex *m, Hex *testEK, Hex *testDK, Hex *testCT, Hex *testSK, int isProvider) { TestMemInit(); gKyberRandNum = 0; memcpy_s(gKyberRandBuf[0], 32, m->x, m->len); CRYPT_RandRegist(TEST_KyberRandom); CRYPT_RandRegistEx(TEST_KyberRandomEx); CRYPT_EAL_PkeyCtx *ctx = TestPkeyNewCtx(NULL, CRYPT_PKEY_ML_KEM, CRYPT_EAL_PKEY_KEM_OPERATE, "provider=default", isProvider); ASSERT_NE(ctx, NULL); uint32_t val = (uint32_t)bits; ASSERT_EQ(CRYPT_EAL_PkeySetParaById(ctx, val), CRYPT_SUCCESS); ASSERT_EQ(CRYPT_EAL_PkeyEncapsInit(ctx, NULL), CRYPT_SUCCESS); uint32_t encapsKeyLen = 0; ASSERT_EQ(CRYPT_EAL_PkeyCtrl(ctx, CRYPT_CTRL_GET_PUBKEY_LEN, &encapsKeyLen, sizeof(encapsKeyLen)), CRYPT_SUCCESS); uint32_t decapsKeyLen = 0; ASSERT_EQ(CRYPT_EAL_PkeyCtrl(ctx, CRYPT_CTRL_GET_PRVKEY_LEN, &decapsKeyLen, sizeof(decapsKeyLen)), CRYPT_SUCCESS); uint32_t cipherLen = 0; ASSERT_EQ(CRYPT_EAL_PkeyCtrl(ctx, CRYPT_CTRL_GET_CIPHERTEXT_LEN, &cipherLen, sizeof(cipherLen)), CRYPT_SUCCESS); CRYPT_EAL_PkeyPub ek = { 0 }; ek.id = CRYPT_PKEY_ML_KEM; ek.key.kemEk.len = encapsKeyLen; ek.key.kemEk.data = BSL_SAL_Malloc(encapsKeyLen); (void)memcpy_s(ek.key.kemEk.data, ek.key.kemEk.len, testEK->x, testEK->len); CRYPT_EAL_PkeyPrv dk = { 0 }; dk.id = CRYPT_PKEY_ML_KEM; dk.key.kemDk.len = decapsKeyLen; dk.key.kemDk.data = BSL_SAL_Malloc(decapsKeyLen); (void)memcpy_s(dk.key.kemDk.data, dk.key.kemDk.len, testDK->x, testDK->len); uint8_t *ciphertext = BSL_SAL_Malloc(cipherLen); uint32_t sharedLen = 32; uint8_t *sharedKey = BSL_SAL_Malloc(sharedLen); uint32_t decSharedLen = 32; uint8_t *decSharedKey = BSL_SAL_Malloc(decSharedLen); ASSERT_EQ(CRYPT_EAL_PkeySetPub(ctx, &ek), CRYPT_SUCCESS); ASSERT_EQ(CRYPT_EAL_PkeyEncaps(ctx, ciphertext, &cipherLen, sharedKey, &sharedLen), CRYPT_SUCCESS); ASSERT_COMPARE("compare ct", ciphertext, cipherLen, testCT->x, testCT->len); ASSERT_COMPARE("compare sk", sharedKey, sharedLen, testSK->x, testSK->len); ASSERT_EQ(CRYPT_EAL_PkeySetPrv(ctx, &dk), CRYPT_SUCCESS); ASSERT_EQ(CRYPT_EAL_PkeyDecaps(ctx, testCT->x, testCT->len, decSharedKey, &decSharedLen), CRYPT_SUCCESS); ASSERT_COMPARE("compare dec sk", decSharedKey, decSharedLen, testSK->x, testSK->len); EXIT: BSL_SAL_Free(ek.key.kemEk.data); BSL_SAL_Free(dk.key.kemDk.data); BSL_SAL_Free(ciphertext); BSL_SAL_Free(sharedKey); BSL_SAL_Free(decSharedKey); CRYPT_EAL_PkeyFreeCtx(ctx); CRYPT_RandRegist(NULL); CRYPT_RandRegistEx(NULL); return; } /* END_CASE */ /* @ * @test SDV_CRYPTO_MLKEM_DECAPS_FUNC_TC001 * @spec - * @title Vector test using ciphertext and shared key decapsulation * @precon nan * @brief * 1. Set the decapsulation key. * 2. Invoke CRYPT_EAL_PkeyDecaps to generate a shared key. * 3. Compare the shared key with the test vector. * @expect 1. Succeeded 2. Succeeded 3. The generation result is the same as expected. * @prior nan * @auto FALSE @ */ /* BEGIN_CASE */ void SDV_CRYPTO_MLKEM_DECAPS_FUNC_TC001(int bits, Hex *testDK, Hex *testCT, Hex *testSK, int isProvider) { TestMemInit(); CRYPT_EAL_PkeyCtx *ctx = TestPkeyNewCtx(NULL, CRYPT_PKEY_ML_KEM, CRYPT_EAL_PKEY_KEM_OPERATE, "provider=default", isProvider); ASSERT_NE(ctx, NULL); uint32_t val = (uint32_t)bits; int ret = CRYPT_EAL_PkeySetParaById(ctx, val); ASSERT_EQ(ret, CRYPT_SUCCESS); ret = CRYPT_EAL_PkeyDecapsInit(ctx, NULL); ASSERT_EQ(ret, CRYPT_SUCCESS); uint32_t decapsKeyLen = 0; ret = CRYPT_EAL_PkeyCtrl(ctx, CRYPT_CTRL_GET_PRVKEY_LEN, &decapsKeyLen, sizeof(decapsKeyLen)); ASSERT_EQ(ret, CRYPT_SUCCESS); CRYPT_EAL_PkeyPrv dk = { 0 }; dk.id = CRYPT_PKEY_ML_KEM; dk.key.kemDk.len = decapsKeyLen; dk.key.kemDk.data = BSL_SAL_Malloc(decapsKeyLen); (void)memcpy_s(dk.key.kemDk.data, dk.key.kemDk.len, testDK->x, testDK->len); uint32_t sharedLen = 32; uint8_t *sharedKey = BSL_SAL_Malloc(sharedLen); ASSERT_EQ(CRYPT_EAL_PkeySetPrv(ctx, &dk), CRYPT_SUCCESS); ASSERT_EQ(CRYPT_EAL_PkeyDecaps(ctx, testCT->x, testCT->len, sharedKey, &sharedLen), CRYPT_SUCCESS); ASSERT_COMPARE("compare sk", sharedKey, sharedLen, testSK->x, testSK->len); EXIT: BSL_SAL_Free(dk.key.kemDk.data); BSL_SAL_Free(sharedKey); CRYPT_EAL_PkeyFreeCtx(ctx); return; } /* END_CASE */ /* @ * @test SDV_CRYPTO_MLKEM_PKEYNEWCTX_API_TC001 * @spec - * @title CRYPT_EAL_PkeyNewCtx interface test * @precon nan * @brief 1. The input parameter is the ID of the algorithm that does not support key generation CRYPT_MD_SHA256. * 2. The input parameter is - 1. * 3. The input parameter is CRYPT_PKEY_MAX + 1. * @expect 1. Failure 2. Failure 3. Failure * @prior nan * @auto FALSE @ */ /* BEGIN_CASE */ void SDV_CRYPTO_MLKEM_PKEYNEWCTX_API_TC001() { TestMemInit(); CRYPT_RandRegist(TestSimpleRand); CRYPT_EAL_PkeyCtx *ctx1 = CRYPT_EAL_PkeyNewCtx((CRYPT_PKEY_AlgId)CRYPT_MD_SHA256); ASSERT_TRUE(ctx1 == NULL); CRYPT_EAL_PkeyCtx *ctx2 = CRYPT_EAL_PkeyNewCtx(-1); ASSERT_TRUE(ctx2 == NULL); CRYPT_EAL_PkeyCtx *ctx3 = CRYPT_EAL_PkeyNewCtx(CRYPT_PKEY_MAX + 1); ASSERT_TRUE(ctx3 == NULL); EXIT: CRYPT_EAL_PkeyFreeCtx(ctx1); CRYPT_EAL_PkeyFreeCtx(ctx2); CRYPT_EAL_PkeyFreeCtx(ctx3); CRYPT_RandRegist(NULL); return; } /* END_CASE */ /* @ * @test SDV_CRYPTO_MLKEM_ABNORMAL_DECAPS_FUNC_TC001 * @spec - * @title Invalid ciphertext. Decapsulation failed. * @precon nan * @brief 1. Generate a key pair. * 2. Call CRYPT_EAL_PkeyEncaps for encapsulation. * 3. Modify the content in ciphertext and call CRYPT_EAL_PkeyDecaps for decapsulation. * 4. Inconsistent sharedKeys * @expect 1. Success 2. Success 3. Success 4. Inconsistency * @prior nan * @auto FALSE @ */ /* BEGIN_CASE */ void SDV_CRYPTO_MLKEM_ABNORMAL_DECAPS_FUNC_TC001(int bits, Hex *m, Hex *testEK, Hex *testDK, Hex *testCT, Hex *testSK, Hex *changeCT) { TestMemInit(); gKyberRandNum = 0; memcpy_s(gKyberRandBuf[0], 32, m->x, m->len); CRYPT_RandRegist(TEST_KyberRandom); CRYPT_RandRegistEx(TEST_KyberRandomEx); CRYPT_EAL_PkeyCtx *ctx = CRYPT_EAL_PkeyNewCtx(CRYPT_PKEY_ML_KEM); uint32_t val = (uint32_t)bits; uint32_t ret = CRYPT_EAL_PkeySetParaById(ctx, val); ASSERT_EQ(ret, CRYPT_SUCCESS); ret = CRYPT_EAL_PkeyEncapsInit(ctx, NULL); ASSERT_EQ(ret, CRYPT_SUCCESS); uint32_t encapsKeyLen = 0; ret = CRYPT_EAL_PkeyCtrl(ctx, CRYPT_CTRL_GET_PUBKEY_LEN, &encapsKeyLen, sizeof(encapsKeyLen)); ASSERT_EQ(ret, CRYPT_SUCCESS); uint32_t decapsKeyLen = 0; ret = CRYPT_EAL_PkeyCtrl(ctx, CRYPT_CTRL_GET_PRVKEY_LEN, &decapsKeyLen, sizeof(decapsKeyLen)); ASSERT_EQ(ret, CRYPT_SUCCESS); uint32_t cipherLen = 0; ret = CRYPT_EAL_PkeyCtrl(ctx, CRYPT_CTRL_GET_CIPHERTEXT_LEN, &cipherLen, sizeof(cipherLen)); ASSERT_EQ(ret, CRYPT_SUCCESS); CRYPT_EAL_PkeyPub ek = { 0 }; ek.id = CRYPT_PKEY_ML_KEM; ek.key.kemEk.len = encapsKeyLen; ek.key.kemEk.data = BSL_SAL_Malloc(encapsKeyLen); (void)memcpy_s(ek.key.kemEk.data, ek.key.kemEk.len, testEK->x, testEK->len); CRYPT_EAL_PkeyPrv dk = { 0 }; dk.id = CRYPT_PKEY_ML_KEM; dk.key.kemDk.len = decapsKeyLen; dk.key.kemDk.data = BSL_SAL_Malloc(decapsKeyLen); (void)memcpy_s(dk.key.kemDk.data, dk.key.kemDk.len, testDK->x, testDK->len); uint8_t *ciphertext = BSL_SAL_Malloc(cipherLen); uint32_t sharedLen = 32; uint8_t *sharedKey = BSL_SAL_Malloc(sharedLen); uint32_t decSharedLen = 32; uint8_t *decSharedKey = BSL_SAL_Malloc(decSharedLen); ASSERT_EQ(CRYPT_EAL_PkeySetPub(ctx, &ek), CRYPT_SUCCESS); ASSERT_EQ(CRYPT_EAL_PkeyEncaps(ctx, ciphertext, &cipherLen, sharedKey, &sharedLen), CRYPT_SUCCESS); ASSERT_COMPARE("compare ct", ciphertext, cipherLen, testCT->x, testCT->len); ASSERT_COMPARE("compare sk", sharedKey, sharedLen, testSK->x, testSK->len); ASSERT_EQ(CRYPT_EAL_PkeySetPrv(ctx, &dk), CRYPT_SUCCESS); ASSERT_EQ(CRYPT_EAL_PkeyDecaps(ctx, changeCT->x, changeCT->len, decSharedKey, &decSharedLen), CRYPT_SUCCESS); ASSERT_TRUE(memcmp(sharedKey, decSharedKey, sharedLen) != 0); EXIT: BSL_SAL_Free(ek.key.kemEk.data); BSL_SAL_Free(dk.key.kemDk.data); BSL_SAL_Free(ciphertext); BSL_SAL_Free(sharedKey); BSL_SAL_Free(decSharedKey); CRYPT_EAL_PkeyFreeCtx(ctx); CRYPT_RandRegist(NULL); CRYPT_RandRegistEx(NULL); return; } /* END_CASE */ /* @ * @test SDV_CRYPTO_MLKEM_ABNORMAL_DECAPS_FUNC_TC002 * @spec - * @title Invalid private key. Decapsulation failed. * @precon nan * @brief 1. Generate a key pair. * 2. Call CRYPT_EAL_PkeyEncaps for encapsulation. * 3. Call SetPrvKey to set invalid prvKey to the CTX. * 4. Call CRYPT_EAL_PkeyDecaps for decapsulation. * 5. Inconsistent sharedKeys * @expect 1. Success 2. Success 3. Success 4. Success 5. Inconsistency * @prior nan * @auto FALSE @ */ /* BEGIN_CASE */ void SDV_CRYPTO_MLKEM_ABNORMAL_DECAPS_FUNC_TC002(int bits, Hex *m, Hex *testEK, Hex *testCT, Hex *testSK, Hex *changeDK) { TestMemInit(); gKyberRandNum = 0; memcpy_s(gKyberRandBuf[0], 32, m->x, m->len); CRYPT_RandRegist(TEST_KyberRandom); CRYPT_RandRegistEx(TEST_KyberRandomEx); CRYPT_EAL_PkeyCtx *ctx = CRYPT_EAL_PkeyNewCtx(CRYPT_PKEY_ML_KEM); uint32_t val = (uint32_t)bits; int ret = CRYPT_EAL_PkeySetParaById(ctx, val); ASSERT_EQ(ret, CRYPT_SUCCESS); ret = CRYPT_EAL_PkeyEncapsInit(ctx, NULL); ASSERT_EQ(ret, CRYPT_SUCCESS); uint32_t encapsKeyLen = 0; ret = CRYPT_EAL_PkeyCtrl(ctx, CRYPT_CTRL_GET_PUBKEY_LEN, &encapsKeyLen, sizeof(encapsKeyLen)); ASSERT_EQ(ret, CRYPT_SUCCESS); uint32_t decapsKeyLen = 0; ret = CRYPT_EAL_PkeyCtrl(ctx, CRYPT_CTRL_GET_PRVKEY_LEN, &decapsKeyLen, sizeof(decapsKeyLen)); ASSERT_EQ(ret, CRYPT_SUCCESS); uint32_t cipherLen = 0; ret = CRYPT_EAL_PkeyCtrl(ctx, CRYPT_CTRL_GET_CIPHERTEXT_LEN, &cipherLen, sizeof(cipherLen)); ASSERT_EQ(ret, CRYPT_SUCCESS); CRYPT_EAL_PkeyPub ek = { 0 }; ek.id = CRYPT_PKEY_ML_KEM; ek.key.kemEk.len = encapsKeyLen; ek.key.kemEk.data = BSL_SAL_Malloc(encapsKeyLen); (void)memcpy_s(ek.key.kemEk.data, ek.key.kemEk.len, testEK->x, testEK->len); CRYPT_EAL_PkeyPrv dk = { 0 }; dk.id = CRYPT_PKEY_ML_KEM; dk.key.kemDk.len = decapsKeyLen; dk.key.kemDk.data = BSL_SAL_Malloc(decapsKeyLen); (void)memcpy_s(dk.key.kemDk.data, dk.key.kemDk.len, changeDK->x, changeDK->len); uint8_t *ciphertext = BSL_SAL_Malloc(cipherLen); uint32_t sharedLen = 32; uint8_t *sharedKey = BSL_SAL_Malloc(sharedLen); uint32_t decSharedLen = 32; uint8_t *decSharedKey = BSL_SAL_Malloc(decSharedLen); ASSERT_EQ(CRYPT_EAL_PkeySetPub(ctx, &ek), CRYPT_SUCCESS); ASSERT_EQ(CRYPT_EAL_PkeyEncaps(ctx, ciphertext, &cipherLen, sharedKey, &sharedLen), CRYPT_SUCCESS); ASSERT_COMPARE("compare ct", ciphertext, cipherLen, testCT->x, testCT->len); ASSERT_COMPARE("compare sk", sharedKey, sharedLen, testSK->x, testSK->len); ASSERT_EQ(CRYPT_EAL_PkeySetPrv(ctx, &dk), CRYPT_SUCCESS); ASSERT_EQ(CRYPT_EAL_PkeyDecaps(ctx, ciphertext, cipherLen, decSharedKey, &decSharedLen), CRYPT_SUCCESS); ASSERT_TRUE(memcmp(sharedKey, decSharedKey, sharedLen) != 0); EXIT: BSL_SAL_Free(ek.key.kemEk.data); BSL_SAL_Free(dk.key.kemDk.data); BSL_SAL_Free(ciphertext); BSL_SAL_Free(sharedKey); BSL_SAL_Free(decSharedKey); CRYPT_EAL_PkeyFreeCtx(ctx); CRYPT_RandRegist(NULL); CRYPT_RandRegistEx(NULL); return; } /* END_CASE */ /* @ * @test SDV_CRYPTO_MLKEM_ABNORMAL_DECAPS_FUNC_TC002 * @spec - * @title Invalid public key. Decapsulation failed. * @precon nan * @brief 1. Generate a key pair. * 2. Call CRYPT_EAL_PkeyEncaps for encapsulation. * 3. Call SetPrvKey to set invalid prvKey to the CTX. * 4. Call CRYPT_EAL_PkeyDecaps for decapsulation. * 5. Inconsistent sharedKeys * @expect 1. Success 2. Success 3. Success 4. Success 5. Failure * @prior nan * @auto FALSE @ */ /* BEGIN_CASE */ void SDV_CRYPTO_MLKEM_ABNORMAL_DECAPS_FUNC_TC003(int bits, Hex *m, Hex *testDK, Hex *changeEK) { TestMemInit(); gKyberRandNum = 0; memcpy_s(gKyberRandBuf[0], 32, m->x, m->len); CRYPT_RandRegist(TEST_KyberRandom); CRYPT_RandRegistEx(TEST_KyberRandomEx); CRYPT_EAL_PkeyCtx *ctx = CRYPT_EAL_PkeyNewCtx(CRYPT_PKEY_ML_KEM); uint32_t val = (uint32_t)bits; int ret = CRYPT_EAL_PkeySetParaById(ctx, val); ASSERT_EQ(ret, CRYPT_SUCCESS); ret = CRYPT_EAL_PkeyEncapsInit(ctx, NULL); ASSERT_EQ(ret, CRYPT_SUCCESS); uint32_t encapsKeyLen = 0; ret = CRYPT_EAL_PkeyCtrl(ctx, CRYPT_CTRL_GET_PUBKEY_LEN, &encapsKeyLen, sizeof(encapsKeyLen)); ASSERT_EQ(ret, CRYPT_SUCCESS); uint32_t decapsKeyLen = 0; ret = CRYPT_EAL_PkeyCtrl(ctx, CRYPT_CTRL_GET_PRVKEY_LEN, &decapsKeyLen, sizeof(decapsKeyLen)); ASSERT_EQ(ret, CRYPT_SUCCESS); uint32_t cipherLen = 0; ret = CRYPT_EAL_PkeyCtrl(ctx, CRYPT_CTRL_GET_CIPHERTEXT_LEN, &cipherLen, sizeof(cipherLen)); ASSERT_EQ(ret, CRYPT_SUCCESS); CRYPT_EAL_PkeyPub ek = { 0 }; ek.id = CRYPT_PKEY_ML_KEM; ek.key.kemEk.len = encapsKeyLen; ek.key.kemEk.data = BSL_SAL_Malloc(encapsKeyLen); (void)memcpy_s(ek.key.kemEk.data, ek.key.kemEk.len, changeEK->x, changeEK->len); CRYPT_EAL_PkeyPrv dk = { 0 }; dk.id = CRYPT_PKEY_ML_KEM; dk.key.kemDk.len = decapsKeyLen; dk.key.kemDk.data = BSL_SAL_Malloc(decapsKeyLen); (void)memcpy_s(dk.key.kemDk.data, dk.key.kemDk.len, testDK->x, testDK->len); uint8_t *ciphertext = BSL_SAL_Malloc(cipherLen); uint32_t sharedLen = 32; uint8_t *sharedKey = BSL_SAL_Malloc(sharedLen); uint32_t decSharedLen = 32; uint8_t *decSharedKey = BSL_SAL_Malloc(decSharedLen); ASSERT_EQ(CRYPT_EAL_PkeySetPub(ctx, &ek), CRYPT_SUCCESS); ASSERT_EQ(CRYPT_EAL_PkeyEncaps(ctx, ciphertext, &cipherLen, sharedKey, &sharedLen), CRYPT_SUCCESS); ASSERT_EQ(CRYPT_EAL_PkeySetPrv(ctx, &dk), CRYPT_SUCCESS); ASSERT_EQ(CRYPT_EAL_PkeyDecaps(ctx, ciphertext, cipherLen, decSharedKey, &decSharedLen), CRYPT_SUCCESS); ASSERT_TRUE(memcmp(sharedKey, decSharedKey, sharedLen) != 0); EXIT: BSL_SAL_Free(ek.key.kemEk.data); BSL_SAL_Free(dk.key.kemDk.data); BSL_SAL_Free(ciphertext); BSL_SAL_Free(sharedKey); BSL_SAL_Free(decSharedKey); CRYPT_EAL_PkeyFreeCtx(ctx); CRYPT_RandRegist(NULL); CRYPT_RandRegistEx(NULL); return; } /* END_CASE */ /* @ * @test SDV_CRYPTO_MLKEM_KEY_PAIR_FUNC_TC001 * @spec - * @title Key pair generation function test @ */ /* BEGIN_CASE */ void SDV_CRYPTO_MLKEM_KEY_PAIR_FUNC_TC001(int bits) { #if !defined(HITLS_CRYPTO_MLKEM_CHECK) (void)bits; SKIP_TEST(); #else TestMemInit(); TestRandInit(); CRYPT_EAL_PkeyCtx *ctx = NULL; CRYPT_EAL_PkeyCtx *pubCtx = NULL; CRYPT_EAL_PkeyCtx *prvCtx = NULL; CRYPT_EAL_PkeyPrv dk = { 0 }; CRYPT_EAL_PkeyPub ek = { 0 }; uint32_t decapsKeyLen = 0; uint32_t encapsKeyLen = 0; #ifdef HITLS_CRYPTO_PROVIDER ctx = CRYPT_EAL_ProviderPkeyNewCtx(NULL, CRYPT_PKEY_ML_KEM, CRYPT_EAL_PKEY_KEM_OPERATE, "provider=default"); pubCtx = CRYPT_EAL_ProviderPkeyNewCtx(NULL, CRYPT_PKEY_ML_KEM, CRYPT_EAL_PKEY_KEM_OPERATE, "provider=default"); prvCtx = CRYPT_EAL_ProviderPkeyNewCtx(NULL, CRYPT_PKEY_ML_KEM, CRYPT_EAL_PKEY_KEM_OPERATE, "provider=default"); #else ctx = CRYPT_EAL_PkeyNewCtx(CRYPT_PKEY_ML_KEM); pubCtx = CRYPT_EAL_PkeyNewCtx(CRYPT_PKEY_ML_KEM); prvCtx = CRYPT_EAL_PkeyNewCtx(CRYPT_PKEY_ML_KEM); #endif ASSERT_TRUE(ctx != NULL); ASSERT_TRUE(pubCtx != NULL); ASSERT_TRUE(prvCtx != NULL); uint32_t val = (uint32_t)bits; dk.id = CRYPT_PKEY_ML_KEM; ek.id = CRYPT_PKEY_ML_KEM; ASSERT_EQ(CRYPT_EAL_PkeySetParaById(ctx, val), CRYPT_SUCCESS); ASSERT_EQ(CRYPT_EAL_PkeySetParaById(pubCtx, val), CRYPT_SUCCESS); ASSERT_EQ(CRYPT_EAL_PkeySetParaById(prvCtx, val), CRYPT_SUCCESS); ASSERT_EQ(CRYPT_EAL_PkeyCtrl(ctx, CRYPT_CTRL_GET_PRVKEY_LEN, &decapsKeyLen, sizeof(decapsKeyLen)), CRYPT_SUCCESS); ASSERT_EQ(CRYPT_EAL_PkeyCtrl(ctx, CRYPT_CTRL_GET_PUBKEY_LEN, &encapsKeyLen, sizeof(encapsKeyLen)), CRYPT_SUCCESS); dk.key.kemDk.len = decapsKeyLen; dk.key.kemDk.data = BSL_SAL_Malloc(decapsKeyLen); ek.key.kemEk.len = encapsKeyLen; ek.key.kemEk.data = BSL_SAL_Malloc(encapsKeyLen); ASSERT_EQ(CRYPT_EAL_PkeyGen(ctx), CRYPT_SUCCESS); ASSERT_EQ(CRYPT_EAL_PkeyGetPrv(ctx, &dk), CRYPT_SUCCESS); ASSERT_EQ(CRYPT_EAL_PkeyGetPub(ctx, &ek), CRYPT_SUCCESS); ASSERT_EQ(CRYPT_EAL_PkeySetPrv(prvCtx, &dk), CRYPT_SUCCESS); ASSERT_EQ(CRYPT_EAL_PkeySetPub(pubCtx, &ek), CRYPT_SUCCESS); ASSERT_EQ(CRYPT_EAL_PkeyPairCheck(pubCtx, prvCtx), CRYPT_SUCCESS); ASSERT_EQ(CRYPT_EAL_PkeyPairCheck(prvCtx, pubCtx), CRYPT_NULL_INPUT); // no pub ASSERT_EQ(CRYPT_EAL_PkeyPairCheck(pubCtx, pubCtx), CRYPT_NULL_INPUT); // no prv EXIT: CRYPT_EAL_PkeyFreeCtx(ctx); CRYPT_EAL_PkeyFreeCtx(pubCtx); CRYPT_EAL_PkeyFreeCtx(prvCtx); BSL_SAL_Free(dk.key.kemDk.data); BSL_SAL_Free(ek.key.kemEk.data); TestRandDeInit(); #endif } /* END_CASE */ /* @ * @test SDV_CRYPTO_MLKEM_KEY_PAIR_FUNC_TC002 * @spec - * @title Key pair generation function invalid test @ */ /* BEGIN_CASE */ void SDV_CRYPTO_MLKEM_KEY_PAIR_FUNC_TC002(void) { #if !defined(HITLS_CRYPTO_MLKEM_CHECK) SKIP_TEST(); #else TestMemInit(); TestRandInit(); int32_t bits1 = CRYPT_KEM_TYPE_MLKEM_512; int32_t bits2 = CRYPT_KEM_TYPE_MLKEM_768; CRYPT_EAL_PkeyCtx *ctx1 = NULL; CRYPT_EAL_PkeyCtx *ctx2 = NULL; CRYPT_EAL_PkeyCtx *ctx3 = NULL; #ifdef HITLS_CRYPTO_PROVIDER ctx1 = CRYPT_EAL_ProviderPkeyNewCtx(NULL, CRYPT_PKEY_ML_KEM, CRYPT_EAL_PKEY_KEM_OPERATE, "provider=default"); ctx2 = CRYPT_EAL_ProviderPkeyNewCtx(NULL, CRYPT_PKEY_ML_KEM, CRYPT_EAL_PKEY_KEM_OPERATE, "provider=default"); ctx3 = CRYPT_EAL_ProviderPkeyNewCtx(NULL, CRYPT_PKEY_ML_KEM, CRYPT_EAL_PKEY_KEM_OPERATE, "provider=default"); #else ctx1 = CRYPT_EAL_PkeyNewCtx(CRYPT_PKEY_ML_KEM); ctx2 = CRYPT_EAL_PkeyNewCtx(CRYPT_PKEY_ML_KEM); ctx3 = CRYPT_EAL_PkeyNewCtx(CRYPT_PKEY_ML_KEM); #endif ASSERT_TRUE(ctx1 != NULL); ASSERT_TRUE(ctx2 != NULL); ASSERT_TRUE(ctx3 != NULL); ASSERT_EQ(CRYPT_EAL_PkeyPairCheck(NULL, NULL), CRYPT_NULL_INPUT); ASSERT_EQ(CRYPT_EAL_PkeyPairCheck(ctx1, ctx2), CRYPT_MLKEM_KEYINFO_NOT_SET); // different key-info ASSERT_EQ(CRYPT_EAL_PkeySetParaById(ctx1, bits1), CRYPT_SUCCESS); ASSERT_EQ(CRYPT_EAL_PkeySetParaById(ctx2, bits1), CRYPT_SUCCESS); ASSERT_EQ(CRYPT_EAL_PkeySetParaById(ctx3, bits2), CRYPT_SUCCESS); ASSERT_EQ(CRYPT_EAL_PkeyPairCheck(ctx1, ctx2), CRYPT_NULL_INPUT); // no key. ASSERT_EQ(CRYPT_EAL_PkeyGen(ctx1), CRYPT_SUCCESS); ASSERT_EQ(CRYPT_EAL_PkeyGen(ctx2), CRYPT_SUCCESS); ASSERT_EQ(CRYPT_EAL_PkeyPairCheck(ctx1, ctx1), CRYPT_SUCCESS); ASSERT_EQ(CRYPT_EAL_PkeyPairCheck(ctx2, ctx2), CRYPT_SUCCESS); ASSERT_EQ(CRYPT_EAL_PkeyPairCheck(ctx1, ctx2), CRYPT_MLKEM_PAIRWISE_CHECK_FAIL); EXIT: CRYPT_EAL_PkeyFreeCtx(ctx1); CRYPT_EAL_PkeyFreeCtx(ctx2); CRYPT_EAL_PkeyFreeCtx(ctx3); TestRandDeInit(); #endif } /* END_CASE */ /* @ * @test SDV_CRYPTO_MLKEM_PRV_KEY_FUNC_TC001 * @spec - * @title Key generation and check prv key @ */ /* BEGIN_CASE */ void SDV_CRYPTO_MLKEM_PRV_KEY_FUNC_TC001(int bits) { #if !defined(HITLS_CRYPTO_MLKEM_CHECK) (void)bits; SKIP_TEST(); #else TestMemInit(); TestRandInit(); CRYPT_EAL_PkeyCtx *ctx = NULL; CRYPT_EAL_PkeyCtx *prvCtx = NULL; CRYPT_EAL_PkeyPrv dk = { 0 }; uint32_t decapsKeyLen = 0; CRYPT_ML_KEM_Ctx *tmp = NULL; #ifdef HITLS_CRYPTO_PROVIDER ctx = CRYPT_EAL_ProviderPkeyNewCtx(NULL, CRYPT_PKEY_ML_KEM, CRYPT_EAL_PKEY_KEM_OPERATE, "provider=default"); prvCtx = CRYPT_EAL_ProviderPkeyNewCtx(NULL, CRYPT_PKEY_ML_KEM, CRYPT_EAL_PKEY_KEM_OPERATE, "provider=default"); #else ctx = CRYPT_EAL_PkeyNewCtx(CRYPT_PKEY_ML_KEM); prvCtx = CRYPT_EAL_PkeyNewCtx(CRYPT_PKEY_ML_KEM); #endif ASSERT_TRUE(ctx != NULL); ASSERT_TRUE(prvCtx != NULL); uint32_t val = (uint32_t)bits; dk.id = CRYPT_PKEY_ML_KEM; ASSERT_EQ(CRYPT_EAL_PkeyPrvCheck(NULL), CRYPT_NULL_INPUT); ASSERT_EQ(CRYPT_EAL_PkeyPrvCheck(prvCtx), CRYPT_MLKEM_KEYINFO_NOT_SET); ASSERT_EQ(CRYPT_EAL_PkeySetParaById(ctx, val), CRYPT_SUCCESS); ASSERT_EQ(CRYPT_EAL_PkeySetParaById(prvCtx, val), CRYPT_SUCCESS); ASSERT_EQ(CRYPT_EAL_PkeyCtrl(ctx, CRYPT_CTRL_GET_PRVKEY_LEN, &decapsKeyLen, sizeof(decapsKeyLen)), CRYPT_SUCCESS); dk.key.kemDk.len = decapsKeyLen; dk.key.kemDk.data = BSL_SAL_Malloc(decapsKeyLen); ASSERT_EQ(CRYPT_EAL_PkeyGen(ctx), CRYPT_SUCCESS); ASSERT_EQ(CRYPT_EAL_PkeyGetPrv(ctx, &dk), CRYPT_SUCCESS); ASSERT_EQ(CRYPT_EAL_PkeyPrvCheck(prvCtx), CRYPT_MLKEM_INVALID_PRVKEY); // no dk ASSERT_EQ(CRYPT_EAL_PkeySetPrv(prvCtx, &dk), CRYPT_SUCCESS); ASSERT_EQ(CRYPT_EAL_PkeyPrvCheck(prvCtx), CRYPT_SUCCESS); // dk is set tmp = (CRYPT_ML_KEM_Ctx *)prvCtx->key; tmp->dkLen = 1; ASSERT_EQ(CRYPT_EAL_PkeyPrvCheck(prvCtx), CRYPT_MLKEM_INVALID_PRVKEY); // dk is set EXIT: CRYPT_EAL_PkeyFreeCtx(ctx); CRYPT_EAL_PkeyFreeCtx(prvCtx); BSL_SAL_Free(dk.key.kemDk.data); TestRandDeInit(); #endif } /* END_CASE */
2301_79861745/bench_create
testcode/sdv/testcase/crypto/mlkem/test_suite_sdv_mlkem.c
C
unknown
42,041
/* * This file is part of the openHiTLS project. * * openHiTLS is licensed under the Mulan PSL v2. * You can use this software according to the terms and conditions of the Mulan PSL v2. * You may obtain a copy of Mulan PSL v2 at: * * http://license.coscl.org.cn/MulanPSL2 * * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, * EITHER EXPRESS 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 <stdio.h> #include <string.h> #include <limits.h> #include <pthread.h> #include "bsl_err.h" #include "bsl_sal.h" #include "crypt_errno.h" #include "crypt_eal_pkey.h" #include "crypt_eal_rand.h" #include "crypt_bn.h" #include "eal_pkey_local.h" #include "stub_replace.h" #include "crypt_util_rand.h" #include "crypt_paillier.h" #include "paillier_local.h" #include "bn_basic.h" #include "securec.h" #include "crypt_encode_decode_key.h" /* END_HEADER */ #define CRYPT_EAL_PKEY_KEYMGMT_OPERATE 0 #define CRYPT_EAL_PKEY_CIPHER_OPERATE 1 #define CRYPT_EAL_PKEY_EXCH_OPERATE 2 #define CRYPT_EAL_PKEY_SIGN_OPERATE 4 void *malloc_fail(uint32_t size) { (void)size; return NULL; } void SetPaillierPara(CRYPT_EAL_PkeyPara *para, Hex *p, Hex *q, uint32_t bits) { para->id = CRYPT_PKEY_PAILLIER; para->para.paillierPara.p = p->x; para->para.paillierPara.q = q->x; para->para.paillierPara.pLen = p->len; para->para.paillierPara.qLen = q->len; para->para.paillierPara.bits = bits; } void SetPaillierPubKey(CRYPT_EAL_PkeyPub *pubKey, uint8_t *g, uint32_t gLen, uint8_t *n, uint32_t nLen, uint8_t *n2, uint32_t n2Len) { pubKey->id = CRYPT_PKEY_PAILLIER; pubKey->key.paillierPub.g = g; pubKey->key.paillierPub.gLen = gLen; pubKey->key.paillierPub.n = n; pubKey->key.paillierPub.nLen = nLen; pubKey->key.paillierPub.n2 = n2; pubKey->key.paillierPub.n2Len = n2Len; } void SetPaillierPrvKey(CRYPT_EAL_PkeyPrv *prvKey, uint8_t *lambda, uint32_t lambdaLen, uint8_t *mu, uint32_t muLen) { prvKey->id = CRYPT_PKEY_PAILLIER; prvKey->key.paillierPrv.lambda = lambda; prvKey->key.paillierPrv.lambdaLen = lambdaLen; prvKey->key.paillierPrv.mu = mu; prvKey->key.paillierPrv.muLen = muLen; } int32_t RandFunc(uint8_t *randNum, uint32_t randLen) { const int maxNum = 255; for (uint32_t i = 0; i < randLen; i++) { randNum[i] = (uint8_t)(rand() % maxNum); } return 0; } int32_t RandFuncEx(void *libCtx, uint8_t *randNum, uint32_t randLen) { (void)libCtx; const int maxNum = 255; for (uint32_t i = 0; i < randLen; i++) { randNum[i] = (uint8_t)(rand() % maxNum); } return 0; } /** * @test SDV_CRYPTO_PAILLIER_NEW_API_TC001 * @title PAILLIER CRYPT_EAL_PkeyNewCtx test. * @precon nan * @brief * 1. Call the CRYPT_EAL_PkeyNewCtx method to create ctx, algId is CRYPT_PKEY_PAILLIER, expected result 1. * 2. Release the ctx. * 3. Repeat steps 1 to 2 for 100 times. * @expect * 1. The returned result is not empty. */ /* BEGIN_CASE */ void SDV_CRYPTO_PAILLIER_NEW_API_TC001(int isProvider) { TestMemInit(); CRYPT_EAL_PkeyCtx *pkey = NULL; /* Run 100 times */ for (int i = 0; i < 100; i++) { pkey = TestPkeyNewCtx(NULL, CRYPT_PKEY_PAILLIER, CRYPT_EAL_PKEY_KEYMGMT_OPERATE, "provider=default", isProvider); ASSERT_TRUE(pkey != NULL); CRYPT_EAL_PkeyFreeCtx(pkey); } EXIT: return; } /* END_CASE */ /** * @test SDV_CRYPTO_PAILLIER_NEW_API_TC002 * @title PAILLIER CRYPT_EAL_PkeyNewCtx test: Malloc failed. * @precon Mock BSL_SAL_Malloc to malloc_fail. * @brief * 1. Call the CRYPT_EAL_PkeyNewCtx method to create ctx, algId is CRYPT_PKEY_PAILLIER, expected result 1. * 2. Release the ctx. * 3. Reset the BSL_SAL_Malloc. * @expect * 1. Failed to create the ctx. */ /* BEGIN_CASE */ void SDV_CRYPTO_PAILLIER_NEW_API_TC002(int isProvider) { CRYPT_EAL_PkeyCtx *pkey = NULL; FuncStubInfo tmpRpInfo = {0}; STUB_Init(); ASSERT_TRUE(STUB_Replace(&tmpRpInfo, BSL_SAL_Malloc, malloc_fail) == 0); TestMemInit(); pkey = TestPkeyNewCtx(NULL, CRYPT_PKEY_PAILLIER, CRYPT_EAL_PKEY_KEYMGMT_OPERATE, "provider=default", isProvider); ASSERT_TRUE(pkey == NULL); EXIT: STUB_Reset(&tmpRpInfo); CRYPT_EAL_PkeyFreeCtx(pkey); } /* END_CASE */ /** * @test SDV_CRYPTO_PAILLIER_SET_PARA_API_TC001 * @title PAILLIER CRYPT_EAL_PkeySetPara test. * @precon Create the context of the paillier algorithm. * * @brief * 1. Call the CRYPT_EAL_PkeySetPara method: * (1) para = NULL, expected result 1. * (2) pLen != BN_BITS_TO_BYTES(bits), expected result 2. * (3) qLen != BN_BITS_TO_BYTES(bits), expected result 2. * (4) p = NULL, q = NULL, bits = 0, expected result 2. * (4) pLen = BN_BITS_TO_BYTES(bits) qLen = BN_BITS_TO_BYTES(bits), bits != 0, expected result 3. * @expect * 1. CRYPT_NULL_INPUT * 2. CRYPT_EAL_ERR_NEW_PARA_FAIL * 3. CRYPT_SUCCESS */ /* BEGIN_CASE */ void SDV_CRYPTO_PAILLIER_SET_PARA_API_TC001(Hex *p, Hex *q, int bits, int isProvider) { CRYPT_EAL_PkeyCtx *pkey = NULL; CRYPT_EAL_PkeyPara para = {0}; SetPaillierPara(&para, p, q, bits); TestMemInit(); pkey = TestPkeyNewCtx(NULL, CRYPT_PKEY_PAILLIER, CRYPT_EAL_PKEY_KEYMGMT_OPERATE, "provider=default", isProvider); ASSERT_TRUE(pkey != NULL); ASSERT_EQ(CRYPT_EAL_PkeySetPara(pkey, NULL), CRYPT_NULL_INPUT); uint32_t bytes = BN_BITS_TO_BYTES(bits); if (p->len != bytes) { ASSERT_TRUE_AND_LOG("pLen != BN_BITS_TO_BYTES(bits)", CRYPT_EAL_PkeySetPara(pkey, &para) == CRYPT_MEM_ALLOC_FAIL); } if (q->len != bytes) { ASSERT_TRUE_AND_LOG("qLen != BN_BITS_TO_BYTES(bits)", CRYPT_EAL_PkeySetPara(pkey, &para) == CRYPT_MEM_ALLOC_FAIL); } if (p->len == bytes && q->len == bytes && bits == 0) { ASSERT_TRUE_AND_LOG("p = NULL, q = NULL, bits = 0", CRYPT_EAL_PkeySetPara(pkey, &para) == CRYPT_MEM_ALLOC_FAIL); } if (p->len == bytes && q->len == bytes && bits != 0) { ASSERT_TRUE(CRYPT_EAL_PkeySetPara(pkey, &para) == CRYPT_SUCCESS); } EXIT: CRYPT_EAL_PkeyFreeCtx(pkey); } /* END_CASE */ /** * @test SDV_CRYPTO_PAILLIER_GEN_API_TC001 * @title PAILLIER CRYPT_EAL_PkeyGen: No regist rand. * @precon Create the contexts of the paillier algorithm and set para. * @brief * 1. Call the CRYPT_EAL_PkeyGen method to generate a key pair, expected result 1. * @expect * 1. Failed to generate a key pair, the return value is CRYPT_NO_REGIST_RAND. */ /* BEGIN_CASE */ void SDV_CRYPTO_PAILLIER_GEN_API_TC001(Hex *p, Hex *q, int bits, int isProvider) { CRYPT_EAL_PkeyPara para = {0}; SetPaillierPara(&para, p, q, bits); TestMemInit(); CRYPT_EAL_PkeyCtx *pkey; pkey = TestPkeyNewCtx(NULL, CRYPT_PKEY_PAILLIER, CRYPT_EAL_PKEY_KEYMGMT_OPERATE, "provider=default", isProvider); ASSERT_TRUE(pkey != NULL); ASSERT_TRUE(CRYPT_EAL_PkeySetPara(pkey, &para) == CRYPT_SUCCESS); ASSERT_EQ(CRYPT_EAL_PkeyGen(pkey), CRYPT_NO_REGIST_RAND); EXIT: CRYPT_EAL_PkeyFreeCtx(pkey); } /* END_CASE */ /** * @test SDV_CRYPTO_PAILLIER_GET_PUB_API_TC001 * @title PAILLIER CRYPT_EAL_PkeyGetPub test. * @precon 1. Create the context of the paillier algorithm. * 2. Initialize the DRBG. * @brief * 1. Call the CRYPT_EAL_PkeyGetPub method without public key, expected result 1 * 2. Set para and generate a key pair, expected result 2 * 3. Call the CRYPT_EAL_PkeyGetPub method: * (1) pkey = NULL, expected result 1. * (2) pub = NULL, expected result 1. * (3) n = NULL, expected result 1. * (4) n != NULL and nLen = 0, expected result 3. * (5) g = NULL, expected result 1. * (6) g != NULL, gLen = 0, expected result 3. * @expect * 1. CRYPT_NULL_INPUT * 2. CRYPT_SUCCESS * 3. CRYPT_BN_BUFF_LEN_NOT_ENOUGH */ /* BEGIN_CASE */ void SDV_CRYPTO_PAILLIER_GET_PUB_API_TC001(Hex *p, Hex *q, int bits, int isProvider) { CRYPT_EAL_PkeyCtx *pkey = NULL; CRYPT_EAL_PkeyPara para = {0}; CRYPT_EAL_PkeyPub pubKey = {0}; uint8_t pubG[600]; uint8_t pubN[600]; uint8_t pubN2[600]; SetPaillierPara(&para, p, q, bits); SetPaillierPubKey(&pubKey, pubG, 600, pubN, 600, pubN2, 600); TestMemInit(); ASSERT_EQ(TestRandInit(), CRYPT_SUCCESS); pkey = TestPkeyNewCtx(NULL, CRYPT_PKEY_PAILLIER, CRYPT_EAL_PKEY_KEYMGMT_OPERATE, "provider=default", isProvider); ASSERT_TRUE(pkey != NULL); /* Missing public key */ ASSERT_EQ(CRYPT_EAL_PkeyGetPub(pkey, &pubKey), CRYPT_NULL_INPUT); ASSERT_EQ(CRYPT_EAL_PkeySetPara(pkey, &para), CRYPT_SUCCESS); ASSERT_EQ(CRYPT_EAL_PkeyGen(pkey), CRYPT_SUCCESS); ASSERT_EQ(CRYPT_EAL_PkeyGetPub(NULL, &pubKey), CRYPT_NULL_INPUT); ASSERT_EQ(CRYPT_EAL_PkeyGetPub(pkey, NULL), CRYPT_NULL_INPUT); /* n = NULL */ pubKey.key.paillierPub.n = NULL; ASSERT_EQ(CRYPT_EAL_PkeyGetPub(pkey, &pubKey), CRYPT_NULL_INPUT); pubKey.key.paillierPub.n = pubN; /* n != NULL and nLen = 0 */ pubKey.key.paillierPub.nLen = 0; ASSERT_EQ(CRYPT_EAL_PkeyGetPub(pkey, &pubKey), CRYPT_BN_BUFF_LEN_NOT_ENOUGH); pubKey.key.paillierPub.nLen = 600; /* g = NULL */ pubKey.key.paillierPub.g = NULL; ASSERT_EQ(CRYPT_EAL_PkeyGetPub(pkey, &pubKey), CRYPT_NULL_INPUT); pubKey.key.paillierPub.g = pubG; /* g != NULL, gLen = 0 */ pubKey.key.paillierPub.gLen = 0; ASSERT_EQ(CRYPT_EAL_PkeyGetPub(pkey, &pubKey), CRYPT_BN_BUFF_LEN_NOT_ENOUGH); EXIT: TestRandDeInit(); CRYPT_EAL_PkeyFreeCtx(pkey); } /* END_CASE */ /** * @test SDV_CRYPTO_PAILLIER_GET_PRV_API_TC001 * @title PAILLIER CRYPT_EAL_PkeyGetPrv: Bad private key. * @precon 1. Create the context of the paillier algorithm. * 2. Initialize the DRBG. * @brief * 1. Call the CRYPT_EAL_PkeyGetPrv method without private key, expected result 1 * 2. Set para and generate a key pair, expected result 2 * 3. Call the CRYPT_EAL_PkeyGetPrv method: * (1) pkey = NULL, expected result 1. * (2) prv = NULL, expected result 1. * (3) lambda = NULL, expected result 1. * (4) lambda != NULL and lambdaLen = 0, expected result 3. * (5) mu = NULL, expected result 1. * (6) mu != NULL, muLen = 0, expected result 3. * (7) lambda != NULL, mu != NULL, lambdaLen != 0, muLen != 0, expected result 2. * @expect * 1. CRYPT_NULL_INPUT * 2. CRYPT_SUCCESS * 3. CRYPT_BN_BUFF_LEN_NOT_ENOUGH */ /* BEGIN_CASE */ void SDV_CRYPTO_PAILLIER_GET_PRV_API_TC001(Hex *p, Hex *q, int bits, int isProvider) { CRYPT_EAL_PkeyCtx *pkey = NULL; CRYPT_EAL_PkeyPrv prvKey = {0}; CRYPT_EAL_PkeyPara para = {0}; uint8_t prvLambda[600]; uint8_t prvMu[600]; SetPaillierPrvKey(&prvKey, prvLambda, 600, prvMu, 600); SetPaillierPara(&para, p, q, bits); TestMemInit(); ASSERT_EQ(TestRandInit(), CRYPT_SUCCESS); pkey = TestPkeyNewCtx(NULL, CRYPT_PKEY_PAILLIER, CRYPT_EAL_PKEY_KEYMGMT_OPERATE, "provider=default", isProvider); ASSERT_TRUE(pkey != NULL); /* Missing private key */ ASSERT_EQ(CRYPT_EAL_PkeyGetPrv(pkey, &prvKey), CRYPT_NULL_INPUT); ASSERT_EQ(CRYPT_EAL_PkeySetPara(pkey, &para), CRYPT_SUCCESS); ASSERT_EQ(CRYPT_EAL_PkeyGen(pkey), CRYPT_SUCCESS); ASSERT_EQ(CRYPT_EAL_PkeyGetPrv(NULL, &prvKey), CRYPT_NULL_INPUT); ASSERT_EQ(CRYPT_EAL_PkeyGetPrv(pkey, NULL), CRYPT_NULL_INPUT); /* lambda = NULL */ prvKey.key.paillierPrv.lambda = NULL; ASSERT_EQ(CRYPT_EAL_PkeyGetPrv(pkey, &prvKey), CRYPT_PAILLIER_ERR_INPUT_VALUE); prvKey.key.paillierPrv.lambda = prvLambda; /* lambda != NULL and lambdaLen = 0 */ prvKey.key.paillierPrv.lambdaLen = 0; ASSERT_EQ(CRYPT_EAL_PkeyGetPrv(pkey, &prvKey), CRYPT_BN_BUFF_LEN_NOT_ENOUGH); prvKey.key.paillierPrv.lambdaLen = 600; /* mu = NULL */ prvKey.key.paillierPrv.mu = NULL; ASSERT_EQ(CRYPT_EAL_PkeyGetPrv(pkey, &prvKey), CRYPT_PAILLIER_ERR_INPUT_VALUE); prvKey.key.paillierPrv.mu = prvMu; /* mu != NULL, muLen = 0 */ prvKey.key.paillierPrv.muLen = 0; ASSERT_EQ(CRYPT_EAL_PkeyGetPrv(pkey, &prvKey), CRYPT_BN_BUFF_LEN_NOT_ENOUGH); prvKey.key.paillierPrv.muLen = 600; /* lambda != NULL, mu != NULL, lambdaLen != 0, muLen != 0 */ ASSERT_EQ(CRYPT_EAL_PkeyGetPrv(pkey, &prvKey), CRYPT_SUCCESS); EXIT: TestRandDeInit(); CRYPT_EAL_PkeyFreeCtx(pkey); } /* END_CASE */ /** * @test SDV_CRYPTO_PAILLIER_SET_PRV_API_TC001 * @title PAILLIER CRYPT_EAL_PkeySetPrv: Bad private key. * @precon Create the contexts of the paillier algorithm and set para: * pkey1: Generate a key pair. * pkey2: set the private key. * @brief * 1. Call the CRYPT_EAL_PkeySetPrv method: * (1) pKey is NULL, expected result 1. * (2) prv is NULL, expected result 1. * (3) n = NULL, expected result 2. * (4) lambda = NULL, expected result 2. * (5) mu = NULL, expected result 2. * (6) n2 = NULL, expected result 2. * (7) lambdaLen = 0, expected result 2. * (8) muLen = 0, expected result 2. * (9) n2Len = 0, expected result 2. * @expect * 1. CRYPT_NULL_INPUT * 2. CRYPT_PAILLIER_ERR_INPUT_VALUE */ /* BEGIN_CASE */ void SDV_CRYPTO_PAILLIER_SET_PRV_API_TC001(Hex *p, Hex *q, int bits, int isProvider) { CRYPT_EAL_PkeyCtx *pkey = NULL; CRYPT_EAL_PkeyCtx *pkey2 = NULL; CRYPT_EAL_PkeyPara para = {0}; CRYPT_EAL_PkeyPrv prvKey = {0}; uint8_t prvMu[600]; uint8_t prvLambda[600]; uint8_t prvN[600]; uint8_t prvN2[600]; SetPaillierPrvKey(&prvKey, prvLambda, 600, prvMu, 600); SetPaillierPara(&para, p, q, bits); TestMemInit(); ASSERT_EQ(TestRandInit(), CRYPT_SUCCESS); pkey = TestPkeyNewCtx(NULL, CRYPT_PKEY_PAILLIER, CRYPT_EAL_PKEY_KEYMGMT_OPERATE, "provider=default", isProvider); pkey2 = TestPkeyNewCtx(NULL, CRYPT_PKEY_PAILLIER, CRYPT_EAL_PKEY_KEYMGMT_OPERATE, "provider=default", isProvider); ASSERT_TRUE(pkey != NULL && pkey2 != NULL); ASSERT_TRUE(CRYPT_EAL_PkeySetPara(pkey, &para) == CRYPT_SUCCESS); ASSERT_TRUE(CRYPT_EAL_PkeySetPara(pkey2, &para) == CRYPT_SUCCESS); ASSERT_TRUE(CRYPT_EAL_PkeyGen(pkey) == CRYPT_SUCCESS); ASSERT_TRUE(CRYPT_EAL_PkeyGetPrv(pkey, &prvKey) == CRYPT_SUCCESS); /*pKey is NULL*/ ASSERT_TRUE(CRYPT_EAL_PkeySetPrv(NULL, &prvKey) == CRYPT_NULL_INPUT); /*prvKey is NULL*/ ASSERT_TRUE(CRYPT_EAL_PkeySetPrv(pkey2, NULL) == CRYPT_NULL_INPUT); prvKey.key.paillierPrv.n = prvN; prvKey.key.paillierPrv.nLen = 600; prvKey.key.paillierPrv.n2 = prvN2; prvKey.key.paillierPrv.n2Len = 600; /*n = NULL*/ prvKey.key.paillierPrv.n = NULL; ASSERT_TRUE_AND_LOG("n is NULL", CRYPT_EAL_PkeySetPrv(pkey2, &prvKey) == CRYPT_PAILLIER_ERR_INPUT_VALUE); prvKey.key.paillierPrv.n = prvN; /*lambda = NULL*/ ASSERT_TRUE(CRYPT_EAL_PkeyGetPrv(pkey, &prvKey) == CRYPT_SUCCESS); prvKey.key.paillierPrv.lambda = NULL; ASSERT_TRUE_AND_LOG("lambda is NULL", CRYPT_EAL_PkeySetPrv(pkey2, &prvKey) == CRYPT_PAILLIER_ERR_INPUT_VALUE); prvKey.key.paillierPrv.lambda = prvLambda; /*mu = NULL*/ ASSERT_TRUE(CRYPT_EAL_PkeyGetPrv(pkey, &prvKey) == CRYPT_SUCCESS); prvKey.key.paillierPrv.mu = NULL; ASSERT_TRUE_AND_LOG("mu is NULL", CRYPT_EAL_PkeySetPrv(pkey2, &prvKey) == CRYPT_PAILLIER_ERR_INPUT_VALUE); prvKey.key.paillierPrv.mu = prvMu; /*n2 = NULL*/ ASSERT_TRUE(CRYPT_EAL_PkeyGetPrv(pkey, &prvKey) == CRYPT_SUCCESS); prvKey.key.paillierPrv.n2 = NULL; ASSERT_TRUE_AND_LOG("n2 is NULL", CRYPT_EAL_PkeySetPrv(pkey2, &prvKey) == CRYPT_PAILLIER_ERR_INPUT_VALUE); prvKey.key.paillierPrv.n2 = prvN2; /*lambdaLen = 0*/ ASSERT_TRUE(CRYPT_EAL_PkeyGetPrv(pkey, &prvKey) == CRYPT_SUCCESS); prvKey.key.paillierPrv.lambdaLen = 0; ASSERT_TRUE_AND_LOG("lambdaLen is 0", CRYPT_EAL_PkeySetPrv(pkey2, &prvKey) == CRYPT_PAILLIER_ERR_INPUT_VALUE); prvKey.key.paillierPrv.lambdaLen = 600; /*muLen = 0*/ ASSERT_TRUE(CRYPT_EAL_PkeyGetPrv(pkey, &prvKey) == CRYPT_SUCCESS); prvKey.key.paillierPrv.muLen = 0; ASSERT_TRUE_AND_LOG("muLen is 0", CRYPT_EAL_PkeySetPrv(pkey2, &prvKey) == CRYPT_PAILLIER_ERR_INPUT_VALUE); prvKey.key.paillierPrv.muLen = 600; /*n2Len = 0*/ ASSERT_TRUE(CRYPT_EAL_PkeyGetPrv(pkey, &prvKey) == CRYPT_SUCCESS); prvKey.key.paillierPrv.n2Len = 0; ASSERT_TRUE_AND_LOG("n2Len is 0", CRYPT_EAL_PkeySetPrv(pkey2, &prvKey) == CRYPT_PAILLIER_ERR_INPUT_VALUE); prvKey.key.paillierPrv.n2Len = 600; EXIT: TestRandDeInit(); CRYPT_EAL_PkeyFreeCtx(pkey); CRYPT_EAL_PkeyFreeCtx(pkey2); } /* END_CASE */ /** * @test SDV_CRYPTO_PAILLIER_SET_PRV_API_TC002 * @title PAILLIER CRYPT_EAL_PkeySetPrv: Specification test. * @precon Create the contexts of the paillier algorithm and set para: * pkey1: Generate a key pair. * pkey2: set the private key. * @brief * 1. Call the CRYPT_EAL_PkeySetPrv method: * (1) n2 is not equal to n^2, expected result 1. * (2) n2 is equal to n^2, expceted result 2. * @expect * 1. CRYPT_PAILLIER_ERR_INPUT_VALUE * 2. CRYPT_SUCCESS */ /* BEGIN_CASE */ void SDV_CRYPTO_PAILLIER_SET_PRV_API_TC002(Hex *p, Hex *q, Hex *n, Hex *n2, int bits, int isProvider) { CRYPT_EAL_PkeyCtx *pkey = NULL; CRYPT_EAL_PkeyCtx *pkey2 = NULL; CRYPT_EAL_PkeyPara para = {0}; CRYPT_EAL_PkeyPrv prvKey = {0}; uint8_t prvMu[256]; uint8_t prvLambda[256]; SetPaillierPrvKey(&prvKey, prvLambda, 256, prvMu, 256); SetPaillierPara(&para, p, q, bits); TestMemInit(); ASSERT_EQ(TestRandInit(), CRYPT_SUCCESS); pkey = TestPkeyNewCtx(NULL, CRYPT_PKEY_PAILLIER, CRYPT_EAL_PKEY_KEYMGMT_OPERATE, "provider=default", isProvider); pkey2 = TestPkeyNewCtx(NULL, CRYPT_PKEY_PAILLIER, CRYPT_EAL_PKEY_KEYMGMT_OPERATE, "provider=default", isProvider); ASSERT_TRUE(pkey != NULL && pkey2 != NULL); ASSERT_TRUE(CRYPT_EAL_PkeySetPara(pkey, &para) == CRYPT_SUCCESS); ASSERT_TRUE(CRYPT_EAL_PkeySetPara(pkey2, &para) == CRYPT_SUCCESS); ASSERT_TRUE(CRYPT_EAL_PkeyGen(pkey) == CRYPT_SUCCESS); ASSERT_TRUE(CRYPT_EAL_PkeyGetPrv(pkey, &prvKey) == CRYPT_SUCCESS); prvKey.key.paillierPrv.n = n->x; prvKey.key.paillierPrv.nLen = n->len; prvKey.key.paillierPrv.n2 = n->x; prvKey.key.paillierPrv.n2Len = n->len; ASSERT_TRUE_AND_LOG("n2 is not equal to n^2", CRYPT_EAL_PkeySetPrv(pkey2, &prvKey) == CRYPT_PAILLIER_ERR_INPUT_VALUE); prvKey.key.paillierPrv.n2 = n2->x; prvKey.key.paillierPrv.n2Len = n2->len; ASSERT_TRUE_AND_LOG("set success", CRYPT_EAL_PkeySetPrv(pkey2, &prvKey) == CRYPT_SUCCESS); EXIT: TestRandDeInit(); CRYPT_EAL_PkeyFreeCtx(pkey); CRYPT_EAL_PkeyFreeCtx(pkey2); } /* END_CASE */ /** * @test SDV_CRYPTO_PAILLIER_SET_PUB_API_TC001 * @title PAILLIER CRYPT_EAL_PkeyGetPub: Bad public key. * @precon Create the contexts of the paillier algorithm and set para: * pkey1: Generate a key pair. * pkey2: Set the public key. * @brief * 1. Call the CRYPT_EAL_PkeyGetPub method: * (1) pKey is NULL, expected result 1. * (2) prv is NULL, expected result 1. * (3) n = NULL, expected result 1. * (4) g = NULL, expected result 1. * (5) n2 = NULL, expected result 1. * @expect * 1. CRYPT_NULL_INPUT */ /* BEGIN_CASE */ void SDV_CRYPTO_PAILLIER_SET_PUB_API_TC001(Hex *p, Hex *q, int bits, int isProvider) { CRYPT_EAL_PkeyCtx *pkey = NULL; CRYPT_EAL_PkeyCtx *pkey2 = NULL; CRYPT_EAL_PkeyPara para = {0}; CRYPT_EAL_PkeyPub pubKey; uint8_t pubG[600]; uint8_t pubN[600]; uint8_t pubN2[600]; SetPaillierPara(&para, p, q, bits); SetPaillierPubKey(&pubKey, pubN, 600, pubG, 600, pubN2, 600); TestMemInit(); ASSERT_EQ(TestRandInit(), CRYPT_SUCCESS); pkey = TestPkeyNewCtx(NULL, CRYPT_PKEY_PAILLIER, CRYPT_EAL_PKEY_KEYMGMT_OPERATE, "provider=default", isProvider); pkey2 = TestPkeyNewCtx(NULL, CRYPT_PKEY_PAILLIER, CRYPT_EAL_PKEY_KEYMGMT_OPERATE, "provider=default", isProvider); ASSERT_TRUE(pkey != NULL && pkey2 != NULL); ASSERT_TRUE(CRYPT_EAL_PkeySetPara(pkey, &para) == CRYPT_SUCCESS); ASSERT_TRUE(CRYPT_EAL_PkeySetPara(pkey2, &para) == CRYPT_SUCCESS); ASSERT_EQ(CRYPT_EAL_PkeyGen(pkey), CRYPT_SUCCESS); /*pKey is NULL*/ ASSERT_TRUE(CRYPT_EAL_PkeySetPub(NULL, &pubKey) == CRYPT_NULL_INPUT); /*pubKey is NULL*/ ASSERT_TRUE(CRYPT_EAL_PkeySetPub(pkey2, NULL) == CRYPT_NULL_INPUT); /*n = NULL*/ ASSERT_TRUE(CRYPT_EAL_PkeyGetPub(pkey, &pubKey) == CRYPT_SUCCESS); pubKey.key.paillierPub.n = NULL; ASSERT_TRUE_AND_LOG("lambda is NULL", CRYPT_EAL_PkeySetPub(pkey2, &pubKey) == CRYPT_NULL_INPUT); pubKey.key.paillierPub.n = pubN; /*g = NULL*/ ASSERT_TRUE(CRYPT_EAL_PkeyGetPub(pkey, &pubKey) == CRYPT_SUCCESS); pubKey.key.paillierPub.g = NULL; ASSERT_TRUE_AND_LOG("mu is NULL", CRYPT_EAL_PkeySetPub(pkey2, &pubKey) == CRYPT_NULL_INPUT); pubKey.key.paillierPub.g = pubG; /*n2 = NULL*/ ASSERT_TRUE(CRYPT_EAL_PkeyGetPub(pkey, &pubKey) == CRYPT_SUCCESS); pubKey.key.paillierPub.n2 = NULL; ASSERT_TRUE_AND_LOG("n2 is NULL", CRYPT_EAL_PkeySetPub(pkey2, &pubKey) == CRYPT_NULL_INPUT); pubKey.key.paillierPub.n2 = pubN2; ASSERT_TRUE(CRYPT_EAL_PkeyGetPub(pkey, &pubKey) == CRYPT_SUCCESS); ASSERT_TRUE_AND_LOG("set prvKey success", CRYPT_EAL_PkeySetPub(pkey2, &pubKey) == CRYPT_SUCCESS); EXIT: TestRandDeInit(); CRYPT_EAL_PkeyFreeCtx(pkey); CRYPT_EAL_PkeyFreeCtx(pkey2); } /* END_CASE */ /** * @test SDV_CRYPTO_PAILLIER_SET_PUB_API_TC002 * @title PAILLIER CRYPT_EAL_PkeyGetPub: Bad public key. * @precon Create the contexts of the paillier algorithm and set para: * pkey1: Generate a key pair. * pkey2: Set the public key. * @brief * 1. Call the CRYPT_EAL_PkeyGetPub method: * (1) n2 is not equal to n^2, expected result 1. * (2) n2 is equal to n^2, expceted result 2. * @expect * 1. CRYPT_PAILLIER_ERR_INPUT_VALUE * 2. CRYPT_SUCCESS */ /* BEGIN_CASE */ void SDV_CRYPTO_PAILLIER_SET_PUB_API_TC002(Hex *p, Hex *q, Hex *n, Hex *n2, int bits, int isProvider) { CRYPT_EAL_PkeyCtx *pkey = NULL; CRYPT_EAL_PkeyCtx *pkey2 = NULL; CRYPT_EAL_PkeyPara para = {0}; CRYPT_EAL_PkeyPub pubKey; uint8_t pubG[128]; SetPaillierPara(&para, p, q, bits); SetPaillierPubKey(&pubKey, pubG, 128, n->x, n->len, n2->x, n2->len); TestMemInit(); ASSERT_EQ(TestRandInit(), CRYPT_SUCCESS); pkey = TestPkeyNewCtx(NULL, CRYPT_PKEY_PAILLIER, CRYPT_EAL_PKEY_KEYMGMT_OPERATE, "provider=default", isProvider); pkey2 = TestPkeyNewCtx(NULL, CRYPT_PKEY_PAILLIER, CRYPT_EAL_PKEY_KEYMGMT_OPERATE, "provider=default", isProvider); ASSERT_TRUE(pkey != NULL && pkey2 != NULL); ASSERT_TRUE(CRYPT_EAL_PkeySetPara(pkey, &para) == CRYPT_SUCCESS); ASSERT_TRUE(CRYPT_EAL_PkeySetPara(pkey2, &para) == CRYPT_SUCCESS); ASSERT_EQ(CRYPT_EAL_PkeyGen(pkey), CRYPT_SUCCESS); pubKey.key.paillierPub.n2 = n->x; pubKey.key.paillierPub.n2Len = n->len; ASSERT_TRUE_AND_LOG("n2 is not equal to n^2", CRYPT_EAL_PkeySetPub(pkey2, &pubKey) == CRYPT_PAILLIER_ERR_INPUT_VALUE); pubKey.key.paillierPub.n2 = n2->x; pubKey.key.paillierPub.n2Len = n2->len; ASSERT_TRUE_AND_LOG("set success", CRYPT_EAL_PkeySetPub(pkey2, &pubKey) == CRYPT_SUCCESS); EXIT: TestRandDeInit(); CRYPT_EAL_PkeyFreeCtx(pkey); CRYPT_EAL_PkeyFreeCtx(pkey2); } /* END_CASE */ /** * @test SDV_CRYPTO_PAILLIER_ENC_API_TC001 * @title PAILLIER CRYPT_EAL_PkeyEncrypt: Test the validity of input parameters. * @precon Create the context of the paillier algorithm: * @brief * 1. Call the CRYPT_EAL_PkeyEncrypt method without public key, expected result 1 * 2. Set pubkey, expected result 2 * 3. Call the CRYPT_EAL_PkeyEncrypt method: * (1) pkey = NULL, expected result 3 * (2) data = NULL, expected result 3 * (3) data != NULL dataLen > bytes of ctx, expected result 4 * (4) out = NULL, expected result 3 * (5) outLen = NULL, expected result 3 * (6) outLen = 0, expected result 5 * (7) no modification, expected result 2 * @expect * 1. CRYPT_PAILLIER_NO_KEY_INFO * 2. CRYPT_SUCCESS * 3. CRYPT_NULL_INPUT * 4. CRYPT_PAILLIER_ERR_ENC_BITS * 5. CRYPT_PAILLIER_BUFF_LEN_NOT_ENOUGH */ /* BEGIN_CASE */ void SDV_CRYPTO_PAILLIER_ENC_API_TC001(Hex *n, Hex *g, Hex *n2, Hex *in, int isProvider) { uint8_t crypt[512]; uint32_t cryptLen = 512; CRYPT_EAL_PkeyCtx *pkey = NULL; CRYPT_EAL_PkeyPub pubkey = {0}; SetPaillierPubKey(&pubkey, g->x, g->len, n->x, n->len, n2->x, n2->len); TestMemInit(); ASSERT_EQ(TestRandInit(), CRYPT_SUCCESS); pkey = TestPkeyNewCtx(NULL, CRYPT_PKEY_PAILLIER, CRYPT_EAL_PKEY_KEYMGMT_OPERATE + CRYPT_EAL_PKEY_CIPHER_OPERATE, "provider=default", isProvider); ASSERT_TRUE(pkey != NULL); ASSERT_EQ(CRYPT_EAL_PkeyEncrypt(pkey, in->x, in->len, crypt, &cryptLen), CRYPT_PAILLIER_NO_KEY_INFO); ASSERT_TRUE(CRYPT_EAL_PkeySetPub(pkey, &pubkey) == CRYPT_SUCCESS); ASSERT_TRUE(CRYPT_EAL_PkeyEncrypt(NULL, in->x, in->len, crypt, &cryptLen) == CRYPT_NULL_INPUT); ASSERT_TRUE(CRYPT_EAL_PkeyEncrypt(pkey, NULL, in->len, crypt, &cryptLen) == CRYPT_NULL_INPUT); ASSERT_TRUE(CRYPT_EAL_PkeyEncrypt(pkey, in->x, 257, crypt, &cryptLen) == CRYPT_PAILLIER_ERR_ENC_BITS); ASSERT_TRUE(CRYPT_EAL_PkeyEncrypt(pkey, in->x, in->len, NULL, &cryptLen) == CRYPT_NULL_INPUT); ASSERT_TRUE(CRYPT_EAL_PkeyEncrypt(pkey, in->x, in->len, crypt, NULL) == CRYPT_NULL_INPUT); cryptLen = 0; ASSERT_TRUE(CRYPT_EAL_PkeyEncrypt(pkey, in->x, in->len, crypt, &cryptLen) == CRYPT_PAILLIER_BUFF_LEN_NOT_ENOUGH); cryptLen = 512; ASSERT_TRUE(CRYPT_EAL_PkeyEncrypt(pkey, in->x, in->len, crypt, &cryptLen) == CRYPT_SUCCESS); EXIT: CRYPT_EAL_PkeyFreeCtx(pkey); TestRandDeInit(); } /* END_CASE */ /** * @test SDV_CRYPTO_PAILLIER_DEC_API_TC001 * @title PAILLIER CRYPT_EAL_PkeyDecrypt: Test the validity of input parameters. * @precon Create the context of the paillier algorithm: * @brief * 1. Call the CRYPT_EAL_PkeyDecrypt method without private key, expected result 1 * 2. Set private key, expected result 2 * 4. Call the CRYPT_EAL_PkeyDecrypt method: * (1) pkey = NULL, expected result 3 * (2) data = NULL, expected result 3 * (3) data != NULL, dataLen = 0, expected result 4 * (4) data != NULL, dataLen is invalid , expected result 4 * (5) out = NULL, expected result 3 * (6) outLen = NULL, expected result 3 * (7) outLen = 0, expected result 5 * (8) no modification, expected result 2 * @expect * 1. CRYPT_PAILLIER_NO_KEY_INFO * 2. CRYPT_SUCCESS * 3. CRYPT_NULL_INPUT * 4. CRYPT_PAILLIER_ERR_DEC_BITS * 5. CRYPT_PAILLIER_BUFF_LEN_NOT_ENOUGH */ /* BEGIN_CASE */ void SDV_CRYPTO_PAILLIER_DEC_API_TC001(Hex *Lambda, Hex *mu, Hex *n, Hex *n2, Hex *in, int isProvider) { uint8_t crypt[256]; uint32_t cryptLen = 256; CRYPT_EAL_PkeyPrv prvkey = {0}; CRYPT_EAL_PkeyCtx *pkey = NULL; SetPaillierPrvKey(&prvkey, Lambda->x, Lambda->len, mu->x, mu->len); prvkey.key.paillierPrv.n = n->x; prvkey.key.paillierPrv.nLen = n->len; prvkey.key.paillierPrv.n2 = n2->x; prvkey.key.paillierPrv.n2Len = n2->len; TestMemInit(); pkey = TestPkeyNewCtx(NULL, CRYPT_PKEY_PAILLIER, CRYPT_EAL_PKEY_KEYMGMT_OPERATE + CRYPT_EAL_PKEY_CIPHER_OPERATE, "provider=default", isProvider); ASSERT_TRUE(pkey != NULL); ASSERT_TRUE(CRYPT_EAL_PkeyDecrypt(pkey, in->x, in->len, crypt, &cryptLen) == CRYPT_PAILLIER_NO_KEY_INFO); ASSERT_TRUE(CRYPT_EAL_PkeySetPrv(pkey, &prvkey) == CRYPT_SUCCESS); ASSERT_TRUE(CRYPT_EAL_PkeyDecrypt(NULL, in->x, in->len, crypt, &cryptLen) == CRYPT_NULL_INPUT); ASSERT_TRUE(CRYPT_EAL_PkeyDecrypt(pkey, NULL, in->len, crypt, &cryptLen) == CRYPT_NULL_INPUT); ASSERT_TRUE(CRYPT_EAL_PkeyDecrypt(pkey, in->x, 0, crypt, &cryptLen) == CRYPT_PAILLIER_ERR_DEC_BITS); ASSERT_TRUE(CRYPT_EAL_PkeyDecrypt(pkey, in->x, 257, crypt, &cryptLen) == CRYPT_PAILLIER_ERR_DEC_BITS); ASSERT_TRUE(CRYPT_EAL_PkeyDecrypt(pkey, in->x, in->len, NULL, &cryptLen) == CRYPT_NULL_INPUT); ASSERT_TRUE(CRYPT_EAL_PkeyDecrypt(pkey, in->x, in->len, crypt, NULL) == CRYPT_NULL_INPUT); cryptLen = 0; ASSERT_TRUE(CRYPT_EAL_PkeyDecrypt(pkey, in->x, in->len, crypt, &cryptLen) == CRYPT_PAILLIER_BUFF_LEN_NOT_ENOUGH); cryptLen = 256; ASSERT_EQ(CRYPT_EAL_PkeyDecrypt(pkey, in->x, in->len, crypt, &cryptLen), CRYPT_SUCCESS); EXIT: CRYPT_EAL_PkeyFreeCtx(pkey); } /* END_CASE */ int Compare_PubKey(CRYPT_EAL_PkeyPub *pubKey1, CRYPT_EAL_PkeyPub *pubKey2) { if (pubKey1->key.paillierPub.nLen != pubKey2->key.paillierPub.nLen || pubKey1->key.paillierPub.gLen != pubKey2->key.paillierPub.gLen) { return -1; // -1 indicates failure } if (memcmp(pubKey1->key.paillierPub.n, pubKey2->key.paillierPub.n, pubKey1->key.paillierPub.nLen) != 0 || memcmp(pubKey1->key.paillierPub.g, pubKey2->key.paillierPub.g, pubKey1->key.paillierPub.gLen) != 0) { return -1; // -1 indicates failure } return 0; } int Compare_PrvKey(CRYPT_EAL_PkeyPrv *prvKey1, CRYPT_EAL_PkeyPrv *prvKey2) { if (prvKey1->key.paillierPrv.nLen != prvKey2->key.paillierPrv.nLen || prvKey1->key.paillierPrv.muLen != prvKey2->key.paillierPrv.muLen || prvKey1->key.paillierPrv.lambdaLen != prvKey2->key.paillierPrv.lambdaLen) { return -1; // -1 indicates failure } if (memcmp(prvKey1->key.paillierPrv.lambda, prvKey2->key.paillierPrv.lambda, prvKey1->key.paillierPrv.lambdaLen) != 0 || memcmp(prvKey1->key.paillierPrv.mu, prvKey2->key.paillierPrv.mu, prvKey1->key.paillierPrv.muLen) != 0 || memcmp(prvKey1->key.paillierPrv.n, prvKey2->key.paillierPrv.n, prvKey1->key.paillierPrv.nLen) != 0) { return -1; // -1 indicates failure } return 0; } /** * @test SDV_CRYPTO_PAILLIER_SET_KEY_API_TC001 * @title PAILLIER Set the public key and private key multiple times. * @precon Create the contexts of the paillier algorithm and: * pkey1: Set paran and generate a key pair: test obtaining the key. * pkey2: Test set keys, and verify that the public and private keys can exist at the same time. * @brief * 1. pkey1: Get public key and get private key, expected result 1 * 2. pkey2: * (1) Set public key and set private key, expected result 1 * (2) Get public key, get private key and check private key, expected result 2 * (3) Set private key and set public key, expected result 3 * (4) Get private key, get public key and check public key, expected result 4 * @expect * 1. CRYPT_SUCCESS * 2. The obtained private key is equal to the set private key. * 3. CRYPT_SUCCESS * 4. The obtained public key is equal to the set public key. */ /* BEGIN_CASE */ void SDV_CRYPTO_PAILLIER_SET_KEY_API_TC001(Hex *p, Hex *q, int bits, int isProvider) { uint8_t pubN[600]; uint8_t pubG[600]; uint8_t pubN2[600]; uint8_t prvN[600]; uint8_t prvLambda[600]; uint8_t prvMu[600]; uint8_t prvN2[600]; CRYPT_EAL_PkeyPara para = {0}; CRYPT_EAL_PkeyPub pubKey = {0}; CRYPT_EAL_PkeyPrv prvKey = {0}; SetPaillierPara(&para, p, q, bits); SetPaillierPubKey(&pubKey, pubG, 600, pubN, 600, pubN2, 600); SetPaillierPrvKey(&prvKey, prvLambda, 600, prvMu, 600); prvKey.key.paillierPrv.n = prvN; prvKey.key.paillierPrv.nLen = 600; prvKey.key.paillierPrv.n2 = prvN2; prvKey.key.paillierPrv.n2Len = 600; TestMemInit(); CRYPT_RandRegist(RandFunc); CRYPT_RandRegistEx(RandFuncEx); CRYPT_EAL_PkeyCtx *pkey1 = TestPkeyNewCtx(NULL, CRYPT_PKEY_PAILLIER, CRYPT_EAL_PKEY_KEYMGMT_OPERATE, "provider=default", isProvider); CRYPT_EAL_PkeyCtx *pkey2 = TestPkeyNewCtx(NULL, CRYPT_PKEY_PAILLIER, CRYPT_EAL_PKEY_KEYMGMT_OPERATE, "provider=default", isProvider); ASSERT_TRUE(pkey1 != NULL && pkey2 != NULL); /* pkey1 */ /* Generate a key pair. */ ASSERT_TRUE(CRYPT_EAL_PkeySetPara(pkey1, &para) == CRYPT_SUCCESS); ASSERT_EQ(CRYPT_EAL_PkeyGen(pkey1), CRYPT_SUCCESS); /* Get keys. */ ASSERT_EQ(CRYPT_EAL_PkeyGetPub(pkey1, &pubKey), CRYPT_SUCCESS); ASSERT_EQ(CRYPT_EAL_PkeyGetPrv(pkey1, &prvKey), CRYPT_SUCCESS); /* pkey2 */ /* Set public key and set private key. */ ASSERT_EQ(CRYPT_EAL_PkeySetPub(pkey2, &pubKey), CRYPT_SUCCESS); ASSERT_EQ(CRYPT_EAL_PkeySetPrv(pkey2, &prvKey), CRYPT_SUCCESS); /* Get public key, get private key and check private key.*/ SetPaillierPubKey(&pubKey, pubG, 600, pubN, 600, pubN2, 600); ASSERT_EQ(CRYPT_EAL_PkeyGetPub(pkey2, &pubKey), CRYPT_SUCCESS); SetPaillierPrvKey(&prvKey, prvLambda, 600, prvMu, 600); prvKey.key.paillierPrv.n = prvN; prvKey.key.paillierPrv.nLen = 600; ASSERT_EQ(CRYPT_EAL_PkeyGetPrv(pkey2, &prvKey), CRYPT_SUCCESS); ASSERT_EQ(Compare_PrvKey(&prvKey, &prvKey), 0); /* Set private key and set public key. */ ASSERT_EQ(CRYPT_EAL_PkeyGetPrv(pkey2, &prvKey), CRYPT_SUCCESS); ASSERT_EQ(CRYPT_EAL_PkeySetPub(pkey2, &pubKey), CRYPT_SUCCESS); /* Get private key, get public key and check public key.*/ ASSERT_EQ(CRYPT_EAL_PkeyGetPrv(pkey2, &prvKey), CRYPT_SUCCESS); SetPaillierPubKey(&pubKey, pubG, 600, pubN, 600, pubN2, 600); ASSERT_EQ(CRYPT_EAL_PkeyGetPub(pkey2, &pubKey), CRYPT_SUCCESS); ASSERT_EQ(Compare_PubKey(&pubKey, &pubKey), 0); EXIT: CRYPT_EAL_PkeyFreeCtx(pkey1); CRYPT_EAL_PkeyFreeCtx(pkey2); TestRandDeInit(); } /* END_CASE */ /** * @test SDV_CRYPTO_PAILLIER_DUP_CTX_API_TC001 * @title PAILLIER CRYPT_EAL_PkeyDupCtx test. * @precon Create the contexts of the paillier algorithm, set para and generate a key pair. * @brief * 1. Call the CRYPT_EAL_PkeyDupCtx mehod to dup paillier, expected result 1 * @expect * 1. Success. */ /* BEGIN_CASE */ void SDV_CRYPTO_PAILLIER_DUP_CTX_API_TC001(Hex *p, Hex *q, int bits, int isProvider) { CRYPT_EAL_PkeyPara para = {0}; CRYPT_EAL_PkeyCtx *newPkey = NULL; CRYPT_EAL_PkeyCtx *pkey = NULL; SetPaillierPara(&para, p, q, bits); TestMemInit(); CRYPT_RandRegist(RandFunc); CRYPT_RandRegistEx(RandFuncEx); pkey = TestPkeyNewCtx(NULL, CRYPT_PKEY_PAILLIER, CRYPT_EAL_PKEY_KEYMGMT_OPERATE, "provider=default", isProvider); ASSERT_TRUE(pkey != NULL); ASSERT_EQ(CRYPT_EAL_PkeySetPara(pkey, &para), 0); ASSERT_EQ(CRYPT_EAL_PkeyGen(pkey), CRYPT_SUCCESS); CRYPT_PAILLIER_Ctx *paillierCtx = (CRYPT_PAILLIER_Ctx *)pkey->key; ASSERT_TRUE(paillierCtx != NULL); newPkey = CRYPT_EAL_PkeyDupCtx(pkey); ASSERT_TRUE(newPkey != NULL); ASSERT_EQ(newPkey->references.count, 1); CRYPT_PAILLIER_Ctx *paillierCtx2 = (CRYPT_PAILLIER_Ctx *)newPkey->key; ASSERT_TRUE(paillierCtx2 != NULL); ASSERT_COMPARE("paillier compare lambda", paillierCtx->prvKey->lambda->data, paillierCtx->prvKey->lambda->size * sizeof(BN_UINT), paillierCtx2->prvKey->lambda->data, paillierCtx2->prvKey->lambda->size * sizeof(BN_UINT)); ASSERT_COMPARE("paillier compare mu", paillierCtx->prvKey->mu->data, paillierCtx->prvKey->mu->size * sizeof(BN_UINT), paillierCtx2->prvKey->mu->data, paillierCtx2->prvKey->mu->size * sizeof(BN_UINT)); EXIT: CRYPT_EAL_PkeyFreeCtx(pkey); CRYPT_EAL_PkeyFreeCtx(newPkey); TestRandDeInit(); } /* END_CASE */ /** * @test SDV_CRYPTO_PAILLIER_GET_SECURITY_BITS_FUNC_TC001 * @title PAILLIER CRYPT_EAL_PkeyGetSecurityBits test. * @precon nan * @brief * 1. Create the context of the paillier algorithm, expected result 1 * 2. Set public key, expected result 2 * 3. Call the CRYPT_EAL_PkeyVerify method and the parameter is correct, expected result 3 * @expect * 1. Success, and the context is not null. * 2. CRYPT_SUCCESS * 3. The return value is not 0. */ /* BEGIN_CASE */ void SDV_CRYPTO_PAILLIER_GET_SECURITY_BITS_FUNC_TC001(Hex *n, Hex *g, Hex *n2, int securityBits, int isProvider) { CRYPT_EAL_PkeyCtx *pkey = NULL; CRYPT_EAL_PkeyPub pubkey = {0}; SetPaillierPubKey(&pubkey, g->x, g->len, n->x, n->len, n2->x, n2->len); TestMemInit(); pkey = TestPkeyNewCtx(NULL, CRYPT_PKEY_PAILLIER, CRYPT_EAL_PKEY_KEYMGMT_OPERATE, "provider=default", isProvider); ASSERT_TRUE(pkey != NULL); ASSERT_EQ(CRYPT_EAL_PkeySetPub(pkey, &pubkey), CRYPT_SUCCESS); ASSERT_EQ(CRYPT_EAL_PkeyGetSecurityBits(pkey), securityBits); EXIT: CRYPT_EAL_PkeyFreeCtx(pkey); } /* END_CASE */ int HEAdd_Correctness_Check(CRYPT_EAL_PkeyCtx *pkey, Hex *c1, Hex *c2, uint8_t *addResult, uint32_t addLen) { uint8_t m1[256] = {0}; uint8_t m2[256] = {0}; uint8_t sum[256] = {0}; uint32_t m1Len = 256; uint32_t m2Len = 256; uint32_t sumLen = 256; if (CRYPT_EAL_PkeyDecrypt(pkey, c1->x, c1->len, m1, &m1Len) != CRYPT_SUCCESS || CRYPT_EAL_PkeyDecrypt(pkey, c2->x, c2->len, m2, &m2Len) != CRYPT_SUCCESS || CRYPT_EAL_PkeyDecrypt(pkey, addResult, addLen, sum, &sumLen) != CRYPT_SUCCESS) { return -1; } uint8_t expected_sum[256] = {0}; uint32_t maxLen = (m1Len > m2Len ? m1Len : m2Len); uint16_t carry = 0; for (uint32_t i = 0; i < maxLen || carry; i++) { uint16_t v1 = (i < m1Len) ? m1[i] : 0; uint16_t v2 = (i < m2Len) ? m2[i] : 0; uint16_t s = v1 + v2 + carry; expected_sum[i] = (uint8_t)(s & 0xFF); carry = (s >> CHAR_BIT); } uint32_t expected_sum_len = maxLen + (carry ? 1 : 0); if (sumLen != expected_sum_len) { return -1; // -1 indicates failure } if (memcmp(sum, expected_sum, expected_sum_len) != 0) { return -1; // -1 indicates failure } return 0; } /** * @test SDV_CRYPTO_PAILLIER_ADD_API_TC001 * @title PAILLIER CRYPT_EAL_PkeyHEAdd: Test the validity of input parameters and homomorphic addition functionality. * @precon Create the context of the paillier algorithm. * @brief * 1. Call the CRYPT_EAL_PkeyHEAdd method without public key, expected result 1. * 2. Set valid ciphertexts, expected result 3. * 3. Call the CRYPT_EAL_PkeyHEAdd method: * (1) pkey = NULL, expected result 4. * (2) params = NULL, expected result 4. * (3) out = NULL, expected result 4. * (4) outLen = NULL, expected result 4. * (5) ciphertext length is invalid, expected result 2. * (6) ciphertext value is out of range [0, n^2) or not coprime to n^2, expected result 2. * (7) outLen = 0, expected result 5 * (8) all parameters are valid, expected result 3. * @expect * 1. CRYPT_PAILLIER_NO_KEY_INFO * 2. CRYPT_PAILLIER_ERR_INPUT_VALUE * 3. CRYPT_SUCCESS * 4. CRYPT_NULL_INPUT * 5. CRYPT_PAILLIER_BUFF_LEN_NOT_ENOUGH */ /* BEGIN_CASE */ void SDV_CRYPTO_PAILLIER_ADD_API_TC001(Hex *Lambda, Hex *mu, Hex *n, Hex *g, Hex *n2, Hex *c1, Hex *c2, int isProvider) { CRYPT_EAL_PkeyCtx *pkey = NULL; CRYPT_EAL_PkeyPub pubkey = {0}; uint8_t addResult[512]; uint32_t addLen = 512; enum { IDX_C1 = 0, IDX_C2 = 1, IDX_END = 2 }; BSL_Param items[3]; // Two ciphertexts + end marker SetPaillierPubKey(&pubkey, g->x, g->len, n->x, n->len, n2->x, n2->len); TestMemInit(); ASSERT_EQ(TestRandInit(), CRYPT_SUCCESS); // Create context and set public key pkey = TestPkeyNewCtx(NULL, CRYPT_PKEY_PAILLIER, CRYPT_EAL_PKEY_KEYMGMT_OPERATE + CRYPT_EAL_PKEY_CIPHER_OPERATE, "provider=default", isProvider); ASSERT_TRUE(pkey != NULL); /* pKey is NULL */ ASSERT_TRUE(CRYPT_EAL_PkeyHEAdd(pkey, items, addResult, &addLen) == CRYPT_PAILLIER_NO_KEY_INFO); ASSERT_EQ(CRYPT_EAL_PkeySetPub(pkey, &pubkey), CRYPT_SUCCESS); /* Prepare homomorphic addition input */ ASSERT_EQ( BSL_PARAM_InitValue(&items[IDX_C1], CRYPT_PARAM_PKEY_HE_CIPHERTEXT1, BSL_PARAM_TYPE_OCTETS, c1->x, c1->len), BSL_SUCCESS); ASSERT_EQ( BSL_PARAM_InitValue(&items[IDX_C2], CRYPT_PARAM_PKEY_HE_CIPHERTEXT2, BSL_PARAM_TYPE_OCTETS, c2->x, c2->len), BSL_SUCCESS); (void)memset_s(&items[IDX_END], sizeof(items[IDX_END]), 0, sizeof(items[IDX_END])); /* Test invalid inputs */ ASSERT_EQ(CRYPT_EAL_PkeyHEAdd(NULL, items, addResult, &addLen), CRYPT_NULL_INPUT); ASSERT_EQ(CRYPT_EAL_PkeyHEAdd(pkey, NULL, addResult, &addLen), CRYPT_NULL_INPUT); ASSERT_EQ(CRYPT_EAL_PkeyHEAdd(pkey, items, NULL, &addLen), CRYPT_NULL_INPUT); ASSERT_EQ(CRYPT_EAL_PkeyHEAdd(pkey, items, addResult, NULL), CRYPT_NULL_INPUT); /* Test invalid ciphertext length */ items[IDX_C1].valueLen = c1->len + 1; // Corrupt length ASSERT_EQ(CRYPT_EAL_PkeyHEAdd(pkey, items, addResult, &addLen), CRYPT_PAILLIER_ERR_INPUT_VALUE); /* Restore the correct value */ ASSERT_EQ( BSL_PARAM_InitValue(&items[IDX_C1], CRYPT_PARAM_PKEY_HE_CIPHERTEXT1, BSL_PARAM_TYPE_OCTETS, c1->x, c1->len), BSL_SUCCESS); ASSERT_EQ( BSL_PARAM_InitValue(&items[IDX_C2], CRYPT_PARAM_PKEY_HE_CIPHERTEXT2, BSL_PARAM_TYPE_OCTETS, c2->x, c2->len), BSL_SUCCESS); /* Test invalid outLen */ addLen = 0; ASSERT_EQ(CRYPT_EAL_PkeyHEAdd(pkey, items, addResult, &addLen), CRYPT_PAILLIER_BUFF_LEN_NOT_ENOUGH); /* Test valid homomorphic addition */ addLen = 512; ASSERT_EQ(CRYPT_EAL_PkeyHEAdd(pkey, items, addResult, &addLen), CRYPT_SUCCESS); CRYPT_EAL_PkeyPrv prvkey = {0}; SetPaillierPrvKey(&prvkey, Lambda->x, Lambda->len, mu->x, mu->len); prvkey.key.paillierPrv.n = n->x; prvkey.key.paillierPrv.nLen = n->len; prvkey.key.paillierPrv.n2 = n2->x; prvkey.key.paillierPrv.n2Len = n2->len; ASSERT_EQ(CRYPT_EAL_PkeySetPrv(pkey, &prvkey), CRYPT_SUCCESS); ASSERT_EQ(HEAdd_Correctness_Check(pkey, c1, c2, addResult, addLen), 0); EXIT: CRYPT_EAL_PkeyFreeCtx(pkey); TestRandDeInit(); }
2301_79861745/bench_create
testcode/sdv/testcase/crypto/paillier/test_suite_sdv_eal_paillier.c
C
unknown
42,349
/* * This file is part of the openHiTLS project. * * openHiTLS is licensed under the Mulan PSL v2. * You can use this software according to the terms and conditions of the Mulan PSL v2. * You may obtain a copy of Mulan PSL v2 at: * * http://license.coscl.org.cn/MulanPSL2 * * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, * EITHER EXPRESS 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 <pthread.h> #include "securec.h" #include "crypt_eal_kdf.h" #include "crypt_errno.h" #include "bsl_sal.h" #include "bsl_params.h" #include "crypt_params_key.h" /* END_HEADER */ #define DATA_LEN (64) #define ITERATION_COUNT (1024) #define DATA_MAX_LEN (512) #define TEST_FAIL (-1) #define TEST_SUCCESS (0) /** * @test SDV_CRYPT_EAL_KDF_PBKDF2_API_TC001 * @title pbkdf2 api test. */ /* BEGIN_CASE */ void SDV_CRYPT_EAL_KDF_PBKDF2_API_TC001(void) { TestMemInit(); uint32_t keyLen = DATA_LEN; uint8_t key[DATA_LEN]; uint32_t saltLen = DATA_LEN; uint8_t salt[DATA_LEN]; uint32_t it = ITERATION_COUNT; // The number of iterations cannot be less than 1024.. GM/T 0091-2020 uint32_t outLen = DATA_LEN; uint8_t out[DATA_LEN]; CRYPT_EAL_KdfCTX *ctx = CRYPT_EAL_KdfNewCtx(CRYPT_KDF_PBKDF2); ASSERT_TRUE(ctx != NULL); CRYPT_MAC_AlgId macAlgId = CRYPT_MAC_HMAC_SHA1; BSL_Param params[5] = {{0}, {0}, {0}, {0}, BSL_PARAM_END}; ASSERT_EQ(BSL_PARAM_InitValue(&params[0], CRYPT_PARAM_KDF_MAC_ID, BSL_PARAM_TYPE_UINT32, &macAlgId, sizeof(macAlgId)), CRYPT_SUCCESS); ASSERT_EQ(BSL_PARAM_InitValue(&params[1], CRYPT_PARAM_KDF_PASSWORD, BSL_PARAM_TYPE_OCTETS, key, keyLen), CRYPT_SUCCESS); ASSERT_EQ(BSL_PARAM_InitValue(&params[2], CRYPT_PARAM_KDF_SALT, BSL_PARAM_TYPE_OCTETS, salt, saltLen), CRYPT_SUCCESS); ASSERT_EQ(BSL_PARAM_InitValue(&params[3], CRYPT_PARAM_KDF_ITER, BSL_PARAM_TYPE_UINT32, &it, sizeof(it)), CRYPT_SUCCESS); ASSERT_EQ(CRYPT_EAL_KdfSetParam(ctx, params), CRYPT_SUCCESS); ASSERT_EQ(CRYPT_EAL_KdfDerive(ctx, out, outLen), CRYPT_SUCCESS); ASSERT_EQ(BSL_PARAM_InitValue(&params[1], CRYPT_PARAM_KDF_PASSWORD, BSL_PARAM_TYPE_OCTETS, NULL, 0), CRYPT_SUCCESS); ASSERT_EQ(CRYPT_EAL_KdfSetParam(ctx, params), CRYPT_SUCCESS); ASSERT_EQ(CRYPT_EAL_KdfDerive(ctx, out, outLen), CRYPT_SUCCESS); ASSERT_EQ(BSL_PARAM_InitValue(&params[2], CRYPT_PARAM_KDF_SALT, BSL_PARAM_TYPE_OCTETS, NULL, 0), CRYPT_SUCCESS); ASSERT_EQ(CRYPT_EAL_KdfSetParam(ctx, params), CRYPT_SUCCESS); ASSERT_EQ(CRYPT_EAL_KdfDerive(ctx, out, outLen), CRYPT_SUCCESS); uint32_t iterCntFailed = 0; ASSERT_EQ(BSL_PARAM_InitValue(&params[3], CRYPT_PARAM_KDF_ITER, BSL_PARAM_TYPE_UINT32, &iterCntFailed, sizeof(iterCntFailed)), CRYPT_SUCCESS); ASSERT_EQ(CRYPT_EAL_KdfSetParam(ctx, params), CRYPT_PBKDF2_PARAM_ERROR); ASSERT_EQ(BSL_PARAM_InitValue(&params[3], CRYPT_PARAM_KDF_ITER, BSL_PARAM_TYPE_UINT32, &it, sizeof(it)), CRYPT_SUCCESS); ASSERT_EQ(CRYPT_EAL_KdfDerive(ctx, NULL, outLen), CRYPT_NULL_INPUT); ASSERT_EQ(CRYPT_EAL_KdfDerive(ctx, out, 0), CRYPT_PBKDF2_PARAM_ERROR); macAlgId = CRYPT_MAC_HMAC_MD5; ASSERT_EQ(BSL_PARAM_InitValue(&params[0], CRYPT_PARAM_KDF_MAC_ID, BSL_PARAM_TYPE_UINT32, &macAlgId, sizeof(macAlgId)), CRYPT_SUCCESS); ASSERT_EQ(CRYPT_EAL_KdfSetParam(ctx, params), CRYPT_SUCCESS); ASSERT_EQ(CRYPT_EAL_KdfDerive(ctx, out, outLen), CRYPT_SUCCESS); macAlgId = CRYPT_MAC_HMAC_SHA1; ASSERT_EQ(BSL_PARAM_InitValue(&params[0], CRYPT_PARAM_KDF_MAC_ID, BSL_PARAM_TYPE_UINT32, &macAlgId, sizeof(macAlgId)), CRYPT_SUCCESS); ASSERT_EQ(CRYPT_EAL_KdfSetParam(ctx, params), CRYPT_SUCCESS); ASSERT_EQ(CRYPT_EAL_KdfDerive(ctx, out, outLen), CRYPT_SUCCESS); macAlgId = CRYPT_MAC_HMAC_SHA224; ASSERT_EQ(BSL_PARAM_InitValue(&params[0], CRYPT_PARAM_KDF_MAC_ID, BSL_PARAM_TYPE_UINT32, &macAlgId, sizeof(macAlgId)), CRYPT_SUCCESS); ASSERT_EQ(CRYPT_EAL_KdfSetParam(ctx, params), CRYPT_SUCCESS); ASSERT_EQ(CRYPT_EAL_KdfDerive(ctx, out, outLen), CRYPT_SUCCESS); macAlgId = CRYPT_MAC_HMAC_SHA256; ASSERT_EQ(BSL_PARAM_InitValue(&params[0], CRYPT_PARAM_KDF_MAC_ID, BSL_PARAM_TYPE_UINT32, &macAlgId, sizeof(macAlgId)), CRYPT_SUCCESS); ASSERT_EQ(CRYPT_EAL_KdfSetParam(ctx, params), CRYPT_SUCCESS); ASSERT_EQ(CRYPT_EAL_KdfDerive(ctx, out, outLen), CRYPT_SUCCESS); macAlgId = CRYPT_MAC_HMAC_SHA384; ASSERT_EQ(BSL_PARAM_InitValue(&params[0], CRYPT_PARAM_KDF_MAC_ID, BSL_PARAM_TYPE_UINT32, &macAlgId, sizeof(macAlgId)), CRYPT_SUCCESS); ASSERT_EQ(CRYPT_EAL_KdfSetParam(ctx, params), CRYPT_SUCCESS); ASSERT_EQ(CRYPT_EAL_KdfDerive(ctx, out, outLen), CRYPT_SUCCESS); macAlgId = CRYPT_MAC_HMAC_SHA512; ASSERT_EQ(BSL_PARAM_InitValue(&params[0], CRYPT_PARAM_KDF_MAC_ID, BSL_PARAM_TYPE_UINT32, &macAlgId, sizeof(macAlgId)), CRYPT_SUCCESS); ASSERT_EQ(CRYPT_EAL_KdfSetParam(ctx, params), CRYPT_SUCCESS); ASSERT_EQ(CRYPT_EAL_KdfDerive(ctx, out, outLen), CRYPT_SUCCESS); macAlgId = CRYPT_MAC_HMAC_SM3; ASSERT_EQ(BSL_PARAM_InitValue(&params[0], CRYPT_PARAM_KDF_MAC_ID, BSL_PARAM_TYPE_UINT32, &macAlgId, sizeof(macAlgId)), CRYPT_SUCCESS); ASSERT_EQ(CRYPT_EAL_KdfSetParam(ctx, params), CRYPT_SUCCESS); ASSERT_EQ(CRYPT_EAL_KdfDerive(ctx, out, outLen), CRYPT_SUCCESS); ASSERT_EQ(CRYPT_EAL_KdfDeInitCtx(NULL), CRYPT_NULL_INPUT); ASSERT_EQ(CRYPT_EAL_KdfDeInitCtx(ctx), CRYPT_SUCCESS); EXIT: CRYPT_EAL_KdfFreeCtx(ctx); } /* END_CASE */ /** * @test SDV_CRYPT_EAL_KDF_PBKDF2_FUN_TC001 * @title Perform the vector test to check whether the calculation result is consistent with the standard output. * @precon nan * @brief * 1.Call CRYPT_EAL_KDFCTX functions get output, expected result 1. * 2.Compare the result to the expected value, expected result 2. * @expect * 1.Successful. * 2.The results are as expected. */ /* BEGIN_CASE */ void SDV_CRYPT_EAL_KDF_PBKDF2_FUN_TC001(int algId, Hex *key, Hex *salt, int it, Hex *result) { if (IsHmacAlgDisabled(algId)) { SKIP_TEST(); } TestMemInit(); uint32_t outLen = result->len; uint8_t *out = malloc(outLen * sizeof(uint8_t)); ASSERT_TRUE(out != NULL); CRYPT_EAL_KdfCTX *ctx = CRYPT_EAL_KdfNewCtx(CRYPT_KDF_PBKDF2); ASSERT_TRUE(ctx != NULL); BSL_Param params[5] = {{0}, {0}, {0}, {0}, BSL_PARAM_END}; ASSERT_EQ(BSL_PARAM_InitValue(&params[0], CRYPT_PARAM_KDF_MAC_ID, BSL_PARAM_TYPE_UINT32, &algId, sizeof(algId)), CRYPT_SUCCESS); ASSERT_EQ(BSL_PARAM_InitValue(&params[1], CRYPT_PARAM_KDF_PASSWORD, BSL_PARAM_TYPE_OCTETS, key->x, key->len), CRYPT_SUCCESS); ASSERT_EQ(BSL_PARAM_InitValue(&params[2], CRYPT_PARAM_KDF_SALT, BSL_PARAM_TYPE_OCTETS, salt->x, salt->len), CRYPT_SUCCESS); ASSERT_EQ(BSL_PARAM_InitValue(&params[3], CRYPT_PARAM_KDF_ITER, BSL_PARAM_TYPE_UINT32, &it, sizeof(it)), CRYPT_SUCCESS); ASSERT_EQ(CRYPT_EAL_KdfSetParam(ctx, params), CRYPT_SUCCESS); ASSERT_EQ(CRYPT_EAL_KdfDerive(ctx, out, outLen), CRYPT_SUCCESS); ASSERT_COMPARE("result cmp", out, outLen, result->x, result->len); EXIT: if (out != NULL) { free(out); } CRYPT_EAL_KdfFreeCtx(ctx); } /* END_CASE */ /** * @test SDV_CRYPTO_PBKDF2_DEFAULT_PROVIDER_FUNC_TC001 * @title Default provider testing * @precon nan * @brief * Load the default provider and use the test vector to test its correctness */ /* BEGIN_CASE */ void SDV_CRYPTO_PBKDF2_DEFAULT_PROVIDER_FUNC_TC001(int algId, Hex *key, Hex *salt, int it, Hex *result) { if (IsHmacAlgDisabled(algId)) { SKIP_TEST(); } TestMemInit(); uint32_t outLen = result->len; uint8_t *out = malloc(outLen * sizeof(uint8_t)); ASSERT_TRUE(out != NULL); CRYPT_EAL_KdfCTX *ctx = NULL; #ifdef HITLS_CRYPTO_PROVIDER ctx = CRYPT_EAL_ProviderKdfNewCtx(NULL, CRYPT_KDF_PBKDF2, "provider=default"); #else ctx = CRYPT_EAL_KdfNewCtx(CRYPT_KDF_PBKDF2); #endif ASSERT_TRUE(ctx != NULL); BSL_Param params[5] = {{0}, {0}, {0}, {0}, BSL_PARAM_END}; ASSERT_EQ(BSL_PARAM_InitValue(&params[0], CRYPT_PARAM_KDF_MAC_ID, BSL_PARAM_TYPE_UINT32, &algId, sizeof(algId)), CRYPT_SUCCESS); ASSERT_EQ(BSL_PARAM_InitValue(&params[1], CRYPT_PARAM_KDF_PASSWORD, BSL_PARAM_TYPE_OCTETS, key->x, key->len), CRYPT_SUCCESS); ASSERT_EQ(BSL_PARAM_InitValue(&params[2], CRYPT_PARAM_KDF_SALT, BSL_PARAM_TYPE_OCTETS, salt->x, salt->len), CRYPT_SUCCESS); ASSERT_EQ(BSL_PARAM_InitValue(&params[3], CRYPT_PARAM_KDF_ITER, BSL_PARAM_TYPE_UINT32, &it, sizeof(it)), CRYPT_SUCCESS); ASSERT_EQ(CRYPT_EAL_KdfSetParam(ctx, params), CRYPT_SUCCESS); ASSERT_EQ(CRYPT_EAL_KdfDerive(ctx, out, outLen), CRYPT_SUCCESS); ASSERT_EQ(CRYPT_EAL_KdfDerive(ctx, out, outLen), CRYPT_SUCCESS); ASSERT_COMPARE("result cmp", out, outLen, result->x, result->len); EXIT: if (out != NULL) { free(out); } CRYPT_EAL_KdfFreeCtx(ctx); } /* END_CASE */
2301_79861745/bench_create
testcode/sdv/testcase/crypto/pbkdf2/test_suite_sdv_eal_kdf_pbkdf2.c
C
unknown
9,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. */ /* BEGIN_HEADER */ #include <stdlib.h> #include "securec.h" #include "bsl_sal.h" #include "crypt_errno.h" #include "crypt_algid.h" #include "crypt_eal_init.h" #include "crypt_eal_provider.h" #include "crypt_provider_local.h" #include "crypt_eal_implprovider.h" #include "crypt_provider.h" #include "crypt_eal_mac.h" #include "eal_mac_local.h" #include "crypt_eal_kdf.h" #include "eal_kdf_local.h" #include "crypt_eal_md.h" #include "eal_md_local.h" #include "crypt_eal_pkey.h" #include "eal_pkey_local.h" #include "test.h" #include "crypt_eal_cmvp.h" #include "crypt_errno.h" #include "bsl_sal.h" #include "bsl_list.h" #include "bsl_errno.h" #include "crypt_eal_md.h" #include "hitls_crypt_type.h" #include "hitls_cert_type.h" #include "hitls_type.h" #include "crypt_eal_entropy.h" #include "crypt_util_rand.h" #include <stdio.h> #include <time.h> #include <string.h> /* END_HEADER */ #ifdef HITLS_CRYPTO_CMVP_ISO19790_PURE_C #define HITLS_CRYPTO_CMVP_ISO19790 #define HITLS_ISO_PROVIDER_PATH "../../output/CMVP/C/lib" #endif #ifdef HITLS_CRYPTO_CMVP_ISO19790_ARMV8_LE #define HITLS_CRYPTO_CMVP_ISO19790 #define HITLS_ISO_PROVIDER_PATH "../../output/CMVP/armv8_le/lib" #endif #ifdef HITLS_CRYPTO_CMVP_ISO19790_X86_64 #define HITLS_CRYPTO_CMVP_ISO19790 #define HITLS_ISO_PROVIDER_PATH "../../output/CMVP/x86_64/lib" #endif #ifdef HITLS_CRYPTO_CMVP_ISO19790 #define ISO19790_LOG_FILE "iso19790_audit.log" #define HITLS_ISO_LIB_NAME "libhitls_iso.so" #define HITLS_ISO_PROVIDER_ATTR "provider=iso" static FILE* g_logFile = NULL; static int32_t InitLogFile(void) { if (g_logFile == NULL) { g_logFile = fopen(ISO19790_LOG_FILE, "a"); if (g_logFile == NULL) { return CRYPT_NULL_INPUT; } } return CRYPT_SUCCESS; } static void CloseLogFile(void) { if (g_logFile != NULL) { fclose(g_logFile); g_logFile = NULL; } } static void ISO19790_RunLogCb(CRYPT_EVENT_TYPE oper, CRYPT_ALGO_TYPE type, int32_t id, int32_t err) { char timeStr[72] = {0}; time_t now = time(NULL); struct tm *tm_info = gmtime(&now); if (InitLogFile() != CRYPT_SUCCESS) { return; } sprintf(timeStr, "%d-%d-%d %d:%d:%d", tm_info->tm_year + 1900, tm_info->tm_mon + 1, tm_info->tm_mday, tm_info->tm_hour, tm_info->tm_min, tm_info->tm_sec); if (oper == CRYPT_EVENT_INTEGRITY_TEST) { if (err == CRYPT_SUCCESS) { fprintf(g_logFile, "[%s] [open hitls] [INFO] Integrity test begin.\n", timeStr); } else { fprintf(g_logFile, "[%s] [open hitls] [ERR] Integrity test failed, errcode: 0x%x\n", timeStr, err); } fflush(g_logFile); CloseLogFile(); return; } // ISO/IEC 19790:2012 AS09.33 // The module shall provide an output status indication when zeroing is complete if (oper == CRYPT_EVENT_ZERO && err == CRYPT_SUCCESS) { fprintf(g_logFile, "[%s] [open hitls] [INFO] SSP already zeroisation - algorithm type: %d, id: %d\n", timeStr, type, id); fflush(g_logFile); } /* ISO/IEC 19790:2012 AS06.26 The following events of the cryptographic module should be recorded by the OS audit mechanism: ● Attempted to provide invalid input for the cryptographic officer function; */ if (err != CRYPT_SUCCESS) { fprintf(g_logFile, "[%s] [open hitls] [ERR] Occur error - algorithm type: %d, id: %d, operate: %d, errcode: 0x%x\n", timeStr, type, id, oper, err); fflush(g_logFile); } /* ISO/IEC 19790:2012 AS06.26 The following events of the cryptographic module should be recorded by the OS audit mechanism: ● Modify, access, delete, and add encrypted data and SSPs; ● Use security-related encryption features ISO/IEC 19790:2012 AS02.24 When a service uses approved encryption algorithms, security functions or processes, and specified services or processes in an approved manner, the service shall provide corresponding status indications. */ fprintf(g_logFile, "[%s] [open hitls] [INFO] Excute - algorithm type: %d, id: %d, operate: %d\n", timeStr, type, id, oper); fflush(g_logFile); CloseLogFile(); } static int32_t GetEntropy(void *ctx, CRYPT_Data *entropy, uint32_t strength, CRYPT_Range *lenRange) { return CRYPT_EAL_SeedPoolGetEntropy((CRYPT_EAL_SeedPoolCtx *)ctx, entropy, strength, lenRange); } static void CleanEntropy(void *ctx, CRYPT_Data *entropy) { (void)ctx; BSL_SAL_ClearFree(entropy->data, entropy->len); } static int32_t GetNonce(void *ctx, CRYPT_Data *nonce, uint32_t strength, CRYPT_Range *lenRange) { return GetEntropy(ctx, nonce, strength, lenRange); } static void CleanNonce(void *ctx, CRYPT_Data *nonce) { CleanEntropy(ctx, nonce); } static void EntropyRunLogCb(int32_t ret) { char timeStr[72] = {0}; time_t now = time(NULL); struct tm *tm_info = gmtime(&now); if (InitLogFile() != CRYPT_SUCCESS) { return; } sprintf(timeStr, "%d-%d-%d %d:%d:%d", tm_info->tm_year + 1900, tm_info->tm_mon + 1, tm_info->tm_mday, tm_info->tm_hour, tm_info->tm_min, tm_info->tm_sec); fprintf(g_logFile, "[%s] [open hitls] [INFO] Excute entropy health test - ret: %d\n", timeStr, ret); fflush(g_logFile); CloseLogFile(); } static void GetSeedPool(void **seedPool, void **es) { CRYPT_EAL_Es *esTemp = NULL; CRYPT_EAL_SeedPoolCtx *poolTemp = NULL; int32_t ret = 0; esTemp = CRYPT_EAL_EsNew(); ASSERT_TRUE(esTemp != NULL); ret = CRYPT_EAL_EsCtrl(esTemp, CRYPT_ENTROPY_SET_CF, "sha256_df", (uint32_t)strlen("sha256_df")); ASSERT_EQ(ret, CRYPT_SUCCESS); ret = CRYPT_EAL_EsCtrl(esTemp, CRYPT_ENTROPY_REMOVE_NS, "timestamp", (uint32_t)strlen("timestamp")); ASSERT_EQ(ret, CRYPT_SUCCESS); ret = CRYPT_EAL_EsCtrl(esTemp, CRYPT_ENTROPY_SET_LOG_CALLBACK, EntropyRunLogCb, 0); ASSERT_EQ(ret, CRYPT_SUCCESS); bool healthTest = true; ret = CRYPT_EAL_EsCtrl(esTemp, CRYPT_ENTROPY_ENABLE_TEST, &healthTest, sizeof(healthTest)); ASSERT_EQ(ret, CRYPT_SUCCESS); uint32_t size = 4096; ret = CRYPT_EAL_EsCtrl(esTemp, CRYPT_ENTROPY_SET_POOL_SIZE, &size, sizeof(size)); ASSERT_EQ(ret, CRYPT_SUCCESS); do { ret = CRYPT_EAL_EsInit(esTemp); } while (ret == CRYPT_ENTROPY_ES_NO_NS || ret == CRYPT_DRBG_FAIL_GET_ENTROPY || ret == CRYPT_DRBG_FAIL_GET_NONCE); ASSERT_EQ(ret, CRYPT_SUCCESS); poolTemp = CRYPT_EAL_SeedPoolNew(true); ASSERT_TRUE(poolTemp != NULL); CRYPT_EAL_EsPara para = { false, 8, esTemp, (CRYPT_EAL_EntropyGet)CRYPT_EAL_EsEntropyGet, }; ret = CRYPT_EAL_SeedPoolAddEs(poolTemp, &para); ASSERT_EQ(ret, CRYPT_SUCCESS); *seedPool = poolTemp; *es = esTemp; return; EXIT: CRYPT_EAL_SeedPoolFree(poolTemp); CRYPT_EAL_EsFree(esTemp); return; } typedef struct { CRYPT_EAL_LibCtx *libCtx; CRYPT_EAL_Es *es; CRYPT_EAL_SeedPoolCtx *pool; } Iso19790_ProviderLoadCtx; static void Iso19790_ProviderLoad(Iso19790_ProviderLoadCtx *ctx) { CRYPT_EAL_LibCtx *libCtx = NULL; CRYPT_EAL_Es *es = NULL; CRYPT_EAL_SeedPoolCtx *pool = NULL; libCtx = CRYPT_EAL_LibCtxNew(); ASSERT_TRUE(libCtx != NULL); CRYPT_EAL_RegEventReport(ISO19790_RunLogCb); ASSERT_EQ(CRYPT_EAL_ProviderSetLoadPath(libCtx, HITLS_ISO_PROVIDER_PATH), CRYPT_SUCCESS); BSL_Param param[2] = {{0}, BSL_PARAM_END}; (void)BSL_PARAM_InitValue(&param[0], CRYPT_PARAM_CMVP_LOG_FUNC, BSL_PARAM_TYPE_FUNC_PTR, ISO19790_RunLogCb, 0); int32_t ret; do { ret = CRYPT_EAL_ProviderLoad(libCtx, 0, HITLS_ISO_LIB_NAME, param, NULL); } while (ret == CRYPT_ENTROPY_ES_NO_NS || ret == CRYPT_DRBG_FAIL_GET_ENTROPY || ret == CRYPT_DRBG_FAIL_GET_NONCE); ASSERT_EQ(ret, CRYPT_SUCCESS); GetSeedPool((void **)&pool, (void **)&es); ASSERT_TRUE(pool != NULL && es != NULL); BSL_Param randParam[6] = {{0}, {0}, {0}, {0}, {0}, BSL_PARAM_END}; (void)BSL_PARAM_InitValue(&randParam[0], CRYPT_PARAM_RAND_SEED_GETENTROPY, BSL_PARAM_TYPE_FUNC_PTR, GetEntropy, 0); (void)BSL_PARAM_InitValue(&randParam[1], CRYPT_PARAM_RAND_SEED_CLEANENTROPY, BSL_PARAM_TYPE_FUNC_PTR, CleanEntropy, 0); (void)BSL_PARAM_InitValue(&randParam[2], CRYPT_PARAM_RAND_SEED_GETNONCE, BSL_PARAM_TYPE_FUNC_PTR, GetNonce, 0); (void)BSL_PARAM_InitValue(&randParam[3], CRYPT_PARAM_RAND_SEED_CLEANNONCE, BSL_PARAM_TYPE_FUNC_PTR, CleanNonce, 0); (void)BSL_PARAM_InitValue(&randParam[4], CRYPT_PARAM_RAND_SEEDCTX, BSL_PARAM_TYPE_CTX_PTR, pool, 0); do { ret = CRYPT_EAL_ProviderRandInitCtx(libCtx, CRYPT_RAND_SHA256, HITLS_ISO_PROVIDER_ATTR, NULL, 0, randParam); } while (ret == CRYPT_ENTROPY_ES_NO_NS || ret == CRYPT_DRBG_FAIL_GET_ENTROPY || ret == CRYPT_DRBG_FAIL_GET_NONCE); ASSERT_EQ(ret, CRYPT_SUCCESS); ctx->libCtx = libCtx; ctx->es = es; ctx->pool = pool; return; EXIT: CRYPT_EAL_LibCtxFree(libCtx); CRYPT_EAL_SeedPoolFree(pool); CRYPT_EAL_EsFree(es); return; } static void Iso19790_ProviderUnload(Iso19790_ProviderLoadCtx *ctx) { CRYPT_EAL_RandDeinitEx(ctx->libCtx); CRYPT_EAL_LibCtxFree(ctx->libCtx); CRYPT_EAL_SeedPoolFree(ctx->pool); CRYPT_EAL_EsFree(ctx->es); (void)memset_s(ctx, sizeof(Iso19790_ProviderLoadCtx), 0, sizeof(Iso19790_ProviderLoadCtx)); } #endif /* BEGIN_CASE */ void SDV_ISO19790_PROVIDER_PKEY_SIGN_VERIFY_TEST_TC001() { #ifndef HITLS_CRYPTO_CMVP_ISO19790 SKIP_TEST(); #else Iso19790_ProviderLoadCtx ctx = {0}; CRYPT_EAL_PkeyCtx *keyCtx = NULL; uint8_t signature[128] = {0}; uint32_t signatureLen = sizeof(signature); uint8_t testData[] = "Test data for signing and verification with ECDSA"; uint32_t testDataLen = sizeof(testData) - 1; Iso19790_ProviderLoad(&ctx); ASSERT_TRUE(ctx.libCtx != NULL && ctx.es != NULL && ctx.pool != NULL); keyCtx = CRYPT_EAL_ProviderPkeyNewCtx(ctx.libCtx, CRYPT_PKEY_SM2, 0, HITLS_ISO_PROVIDER_ATTR); ASSERT_TRUE(keyCtx != NULL); ASSERT_EQ(CRYPT_EAL_PkeyGen(keyCtx), CRYPT_SUCCESS); ASSERT_EQ(CRYPT_EAL_PkeySign(keyCtx, CRYPT_MD_SM3, testData, testDataLen, signature, &signatureLen), 0); ASSERT_TRUE(signatureLen > 0); ASSERT_EQ(CRYPT_EAL_PkeyVerify(keyCtx, CRYPT_MD_SM3, testData, testDataLen, signature, signatureLen), CRYPT_SUCCESS); EXIT: CRYPT_EAL_PkeyFreeCtx(keyCtx); Iso19790_ProviderUnload(&ctx); return; #endif } /* END_CASE */ #ifdef HITLS_CRYPTO_CMVP_ISO19790 static void SetRsaPara(CRYPT_EAL_PkeyPara *para, uint8_t *e, uint32_t eLen, uint32_t bits) { para->id = CRYPT_PKEY_RSA; para->para.rsaPara.e = e; para->para.rsaPara.eLen = eLen; para->para.rsaPara.bits = bits; } #endif /* BEGIN_CASE */ void SDV_ISO19790_PROVIDER_PKEY_SIGN_VERIFY_TEST_TC002() { #ifndef HITLS_CRYPTO_CMVP_ISO19790 SKIP_TEST(); #else Iso19790_ProviderLoadCtx ctx = {0}; CRYPT_EAL_PkeyCtx *pkeyCtx = NULL; uint8_t e[] = {1, 0, 1}; CRYPT_EAL_PkeyPara para = {0}; int32_t mdId = CRYPT_MD_SHA256; int32_t pkcsv15 = mdId; uint8_t signature[256] = {0}; uint32_t signatureLen = sizeof(signature); uint8_t testData[] = "Test data for signing and verification with ECDSA"; uint32_t testDataLen = sizeof(testData) - 1; Iso19790_ProviderLoad(&ctx); ASSERT_TRUE(ctx.libCtx != NULL && ctx.es != NULL && ctx.pool != NULL); pkeyCtx = CRYPT_EAL_ProviderPkeyNewCtx(ctx.libCtx, CRYPT_PKEY_RSA, 0, HITLS_ISO_PROVIDER_ATTR); ASSERT_TRUE(pkeyCtx != NULL); SetRsaPara(&para, e, 3, 2048); ASSERT_EQ(CRYPT_EAL_PkeySetPara(pkeyCtx, &para), CRYPT_SUCCESS); ASSERT_EQ(CRYPT_EAL_PkeyGen(pkeyCtx), CRYPT_SUCCESS); ASSERT_EQ(CRYPT_EAL_PkeyCtrl(pkeyCtx, CRYPT_CTRL_SET_RSA_EMSA_PKCSV15, &pkcsv15, sizeof(pkcsv15)), CRYPT_SUCCESS); ASSERT_EQ(CRYPT_EAL_PkeySign(pkeyCtx, mdId, testData, testDataLen, signature, &signatureLen), 0); ASSERT_TRUE(signatureLen > 0); ASSERT_EQ(CRYPT_EAL_PkeyVerify(pkeyCtx, mdId, testData, testDataLen, signature, signatureLen), CRYPT_SUCCESS); EXIT: CRYPT_EAL_PkeyFreeCtx(pkeyCtx); Iso19790_ProviderUnload(&ctx); return; #endif } /* END_CASE */ /* BEGIN_CASE */ void SDV_ISO_PROVIDER_PKEY_ENCRYPT_DECRYPT_TEST_TC001() { #ifndef HITLS_CRYPTO_CMVP_ISO19790 SKIP_TEST(); #else Iso19790_ProviderLoadCtx ctx = {0}; CRYPT_EAL_PkeyCtx *pkeyCtx = NULL; uint8_t e[] = {1, 0, 1}; CRYPT_EAL_PkeyPara para = {0}; int32_t mdId = CRYPT_MD_SHA256; uint8_t plaintext[256] = {0}; uint32_t plaintextLen = sizeof(plaintext); uint8_t ciphertext[256] = {0}; uint32_t ciphertextLen = sizeof(ciphertext); uint8_t testData[] = "Test data for encrypt and decrypt with RSA."; uint32_t testDataLen = sizeof(testData) - 1; Iso19790_ProviderLoad(&ctx); ASSERT_TRUE(ctx.libCtx != NULL && ctx.es != NULL && ctx.pool != NULL); BSL_Param oaep[3] = {{CRYPT_PARAM_RSA_MD_ID, BSL_PARAM_TYPE_INT32, &mdId, sizeof(mdId), 0}, {CRYPT_PARAM_RSA_MGF1_ID, BSL_PARAM_TYPE_INT32, &mdId, sizeof(mdId), 0}, BSL_PARAM_END }; pkeyCtx = CRYPT_EAL_ProviderPkeyNewCtx(ctx.libCtx, CRYPT_PKEY_RSA, 0, HITLS_ISO_PROVIDER_ATTR); ASSERT_TRUE(pkeyCtx != NULL); SetRsaPara(&para, e, 3, 2048); ASSERT_EQ(CRYPT_EAL_PkeySetPara(pkeyCtx, &para), CRYPT_SUCCESS); ASSERT_EQ(CRYPT_EAL_PkeyGen(pkeyCtx), CRYPT_SUCCESS); ASSERT_EQ(CRYPT_EAL_PkeyCtrl(pkeyCtx, CRYPT_CTRL_SET_RSA_RSAES_OAEP, oaep, 0), CRYPT_SUCCESS); ASSERT_EQ(CRYPT_EAL_PkeyEncrypt(pkeyCtx, testData, testDataLen, ciphertext, &ciphertextLen), CRYPT_SUCCESS); ASSERT_EQ(CRYPT_EAL_PkeyDecrypt(pkeyCtx, ciphertext, ciphertextLen, plaintext, &plaintextLen), CRYPT_SUCCESS); ASSERT_EQ(testDataLen, plaintextLen); ASSERT_EQ(memcmp(testData, plaintext, plaintextLen), 0); EXIT: CRYPT_EAL_PkeyFreeCtx(pkeyCtx); Iso19790_ProviderUnload(&ctx); return; #endif } /* END_CASE */ /* BEGIN_CASE */ void SDV_ISO19790_PROVIDER_DRBG_TEST_TC001() { #ifndef HITLS_CRYPTO_CMVP_ISO19790 SKIP_TEST(); #else CRYPT_EAL_Es *es = NULL; CRYPT_EAL_SeedPoolCtx *pool = NULL; CRYPT_EAL_RndCtx *randCtx = NULL; Iso19790_ProviderLoadCtx ctx = {0}; Iso19790_ProviderLoad(&ctx); ASSERT_TRUE(ctx.libCtx != NULL && ctx.es != NULL && ctx.pool != NULL); es = CRYPT_EAL_EsNew(); ASSERT_TRUE(es != NULL); int32_t ret = CRYPT_EAL_EsCtrl(es, CRYPT_ENTROPY_SET_CF, "sha256_df", (uint32_t)strlen("sha256_df")); ASSERT_EQ(ret, CRYPT_SUCCESS); ret = CRYPT_EAL_EsCtrl(es, CRYPT_ENTROPY_REMOVE_NS, "timestamp", (uint32_t)strlen("timestamp")); ASSERT_EQ(ret, CRYPT_SUCCESS); ret = CRYPT_EAL_EsCtrl(es, CRYPT_ENTROPY_SET_LOG_CALLBACK, EntropyRunLogCb, 0); ASSERT_EQ(ret, CRYPT_SUCCESS); bool healthTest = true; ret = CRYPT_EAL_EsCtrl(es, CRYPT_ENTROPY_ENABLE_TEST, &healthTest, sizeof(healthTest)); ASSERT_EQ(ret, CRYPT_SUCCESS); uint32_t size = 4096; ret = CRYPT_EAL_EsCtrl(es, CRYPT_ENTROPY_SET_POOL_SIZE, &size, sizeof(size)); ASSERT_EQ(ret, CRYPT_SUCCESS); do { ret = CRYPT_EAL_EsInit(es); } while (ret == CRYPT_ENTROPY_ES_NO_NS || ret == CRYPT_DRBG_FAIL_GET_ENTROPY || ret == CRYPT_DRBG_FAIL_GET_NONCE); ASSERT_EQ(ret, CRYPT_SUCCESS); pool = CRYPT_EAL_SeedPoolNew(true); ASSERT_TRUE(pool != NULL); CRYPT_EAL_EsPara para = { false, 8, es, (CRYPT_EAL_EntropyGet)CRYPT_EAL_EsEntropyGet, }; ret = CRYPT_EAL_SeedPoolAddEs(pool, &para); ASSERT_EQ(ret, CRYPT_SUCCESS); BSL_Param param[6] = {0}; ASSERT_EQ(BSL_PARAM_InitValue(&param[0], CRYPT_PARAM_RAND_SEED_GETENTROPY, BSL_PARAM_TYPE_FUNC_PTR, GetEntropy, 0), CRYPT_SUCCESS); ASSERT_EQ(BSL_PARAM_InitValue(&param[1], CRYPT_PARAM_RAND_SEED_CLEANENTROPY, BSL_PARAM_TYPE_FUNC_PTR, CleanEntropy, 0), CRYPT_SUCCESS); ASSERT_EQ(BSL_PARAM_InitValue(&param[2], CRYPT_PARAM_RAND_SEED_GETNONCE, BSL_PARAM_TYPE_FUNC_PTR, GetNonce, 0), CRYPT_SUCCESS); ASSERT_EQ(BSL_PARAM_InitValue(&param[3], CRYPT_PARAM_RAND_SEED_CLEANNONCE, BSL_PARAM_TYPE_FUNC_PTR, CleanNonce, 0), CRYPT_SUCCESS); ASSERT_EQ(BSL_PARAM_InitValue(&param[4], CRYPT_PARAM_RAND_SEEDCTX, BSL_PARAM_TYPE_CTX_PTR, pool, 0), CRYPT_SUCCESS); randCtx = CRYPT_EAL_ProviderDrbgNewCtx(ctx.libCtx, CRYPT_RAND_SHA256, NULL, param); ASSERT_TRUE(randCtx != NULL); ret = CRYPT_EAL_DrbgInstantiate(randCtx, NULL, 0); ASSERT_EQ(ret, CRYPT_SUCCESS); unsigned char data[16] = {0}; uint32_t dataLen = sizeof(data); ret = CRYPT_EAL_Drbgbytes(randCtx, data, dataLen); ASSERT_EQ(ret, CRYPT_SUCCESS); ret = CRYPT_EAL_DrbgSeed(randCtx); ASSERT_EQ(ret, CRYPT_SUCCESS); ret = CRYPT_EAL_Drbgbytes(randCtx, data, dataLen); ASSERT_EQ(ret, CRYPT_SUCCESS); EXIT: CRYPT_EAL_DrbgDeinit(randCtx); CRYPT_EAL_SeedPoolFree(pool); CRYPT_EAL_EsFree(es); Iso19790_ProviderUnload(&ctx); #endif } /* END_CASE */ /* BEGIN_CASE */ void SDV_ISO19790_PROVIDER_MD_TEST_TC001(int algId) { #ifndef HITLS_CRYPTO_CMVP_ISO19790 (void)algId; SKIP_TEST(); #else Iso19790_ProviderLoadCtx ctx = {0}; CRYPT_EAL_MdCTX *mdCtx = NULL; uint8_t plaintext[128] = {0}; uint32_t plaintextLen = sizeof(plaintext); uint8_t md[128] = {0}; uint32_t mdLen = sizeof(md); Iso19790_ProviderLoad(&ctx); ASSERT_TRUE(ctx.libCtx != NULL && ctx.es != NULL && ctx.pool != NULL); mdCtx = CRYPT_EAL_ProviderMdNewCtx(ctx.libCtx, algId, HITLS_ISO_PROVIDER_ATTR); ASSERT_TRUE(mdCtx != NULL); int32_t ret = CRYPT_EAL_MdInit(mdCtx); ASSERT_EQ(ret, CRYPT_SUCCESS); ret = CRYPT_EAL_MdUpdate(mdCtx, plaintext, plaintextLen); ASSERT_EQ(ret, CRYPT_SUCCESS); ret = CRYPT_EAL_MdFinal(mdCtx, md, &mdLen); ASSERT_EQ(ret, CRYPT_SUCCESS); EXIT: CRYPT_EAL_MdFreeCtx(mdCtx); Iso19790_ProviderUnload(&ctx); return; #endif } /* END_CASE */ /* BEGIN_CASE */ void SDV_ISO19790_PROVIDER_MAC_TEST_TC001(int algId, int keyLen) { #ifndef HITLS_CRYPTO_CMVP_ISO19790 (void)algId; (void)keyLen; SKIP_TEST(); #else Iso19790_ProviderLoadCtx ctx = {0}; CRYPT_EAL_MacCtx *macCtx = NULL; uint8_t macKey[32] = {0}; uint32_t macKeyLen = keyLen; uint8_t plaintext[128] = {0}; uint32_t plaintextLen = sizeof(plaintext); uint8_t iv[16] = {0}; uint32_t ivLen = sizeof(iv); int32_t tagLen = 16; uint8_t mac[128] = {0}; uint32_t macLen = sizeof(mac); Iso19790_ProviderLoad(&ctx); ASSERT_TRUE(ctx.libCtx != NULL && ctx.es != NULL && ctx.pool != NULL); macCtx = CRYPT_EAL_ProviderMacNewCtx(ctx.libCtx, algId, HITLS_ISO_PROVIDER_ATTR); ASSERT_TRUE(macCtx != NULL); int32_t ret = CRYPT_EAL_MacInit(macCtx, macKey, macKeyLen); ASSERT_EQ(ret, CRYPT_SUCCESS); if (algId == CRYPT_MAC_GMAC_AES128 || algId == CRYPT_MAC_GMAC_AES192 || algId == CRYPT_MAC_GMAC_AES256) { ret = CRYPT_EAL_MacCtrl(macCtx, CRYPT_CTRL_SET_IV, iv, ivLen); ASSERT_EQ(ret, CRYPT_SUCCESS); ret = CRYPT_EAL_MacCtrl(macCtx, CRYPT_CTRL_SET_TAGLEN, &tagLen, sizeof(tagLen)); ASSERT_EQ(ret, CRYPT_SUCCESS); } ret = CRYPT_EAL_MacUpdate(macCtx, plaintext, plaintextLen); ASSERT_EQ(ret, CRYPT_SUCCESS); if (algId == CRYPT_MAC_GMAC_AES128 || algId == CRYPT_MAC_GMAC_AES192 || algId == CRYPT_MAC_GMAC_AES256) { macLen = tagLen; } ret = CRYPT_EAL_MacFinal(macCtx, mac, &macLen); ASSERT_EQ(ret, CRYPT_SUCCESS); EXIT: CRYPT_EAL_MacFreeCtx(macCtx); Iso19790_ProviderUnload(&ctx); return; #endif } /* END_CASE */ /* BEGIN_CASE */ void SDV_ISO19790_PROVIDER_KDF_TEST_TC001(int macId, int iter, int saltLen) { #ifndef HITLS_CRYPTO_CMVP_ISO19790 (void)macId; (void)iter; (void)saltLen; SKIP_TEST(); #else Iso19790_ProviderLoadCtx ctx = {0}; CRYPT_EAL_KdfCTX *kdfCtx = NULL; uint8_t password[32] = {0}; uint32_t passwordLen = sizeof(password); uint8_t salt[32] = {0}; uint8_t derivedKey[32] = {0}; uint32_t derivedKeyLen = sizeof(derivedKey); Iso19790_ProviderLoad(&ctx); ASSERT_TRUE(ctx.libCtx != NULL && ctx.es != NULL && ctx.pool != NULL); kdfCtx = CRYPT_EAL_ProviderKdfNewCtx(ctx.libCtx, CRYPT_KDF_PBKDF2, HITLS_ISO_PROVIDER_ATTR); ASSERT_TRUE(kdfCtx != NULL); BSL_Param param[5] = {{0}, {0}, {0}, {0}, BSL_PARAM_END}; (void)BSL_PARAM_InitValue(&param[0], CRYPT_PARAM_KDF_MAC_ID, BSL_PARAM_TYPE_UINT32, &macId, sizeof(macId)); (void)BSL_PARAM_InitValue(&param[1], CRYPT_PARAM_KDF_PASSWORD, BSL_PARAM_TYPE_OCTETS, password, passwordLen); (void)BSL_PARAM_InitValue(&param[2], CRYPT_PARAM_KDF_SALT, BSL_PARAM_TYPE_OCTETS, salt, saltLen); (void)BSL_PARAM_InitValue(&param[3], CRYPT_PARAM_KDF_ITER, BSL_PARAM_TYPE_UINT32, &iter, sizeof(iter)); int32_t ret = CRYPT_EAL_KdfSetParam(kdfCtx, param); ASSERT_EQ(ret, CRYPT_SUCCESS); ret = CRYPT_EAL_KdfDerive(kdfCtx, derivedKey, derivedKeyLen); ASSERT_EQ(ret, CRYPT_SUCCESS); EXIT: CRYPT_EAL_KdfFreeCtx(kdfCtx); Iso19790_ProviderUnload(&ctx); return; #endif } /* END_CASE */ /* BEGIN_CASE */ void SDV_ISO19790_PROVIDER_KDF_TEST_TC002(int algId, Hex *key, Hex *salt, Hex *info) { #ifndef HITLS_CRYPTO_CMVP_ISO19790 (void)algId; (void)key; (void)salt; (void)info; SKIP_TEST(); #else if (IsHmacAlgDisabled(algId)) { SKIP_TEST(); } TestMemInit(); Iso19790_ProviderLoadCtx ctx = {0}; CRYPT_EAL_KdfCTX *kdfCtx = NULL; uint32_t outLen = 32; uint8_t *out = malloc(outLen * sizeof(uint8_t)); ASSERT_TRUE(out != NULL); Iso19790_ProviderLoad(&ctx); ASSERT_TRUE(ctx.libCtx != NULL && ctx.es != NULL && ctx.pool != NULL); kdfCtx = CRYPT_EAL_ProviderKdfNewCtx(ctx.libCtx, CRYPT_KDF_HKDF, HITLS_ISO_PROVIDER_ATTR); ASSERT_TRUE(kdfCtx != NULL); CRYPT_HKDF_MODE mode = CRYPT_KDF_HKDF_MODE_FULL; BSL_Param params[6] = {{0}, {0}, {0}, {0}, {0}, BSL_PARAM_END}; ASSERT_EQ(BSL_PARAM_InitValue(&params[0], CRYPT_PARAM_KDF_MAC_ID, BSL_PARAM_TYPE_UINT32, &algId, sizeof(algId)), CRYPT_SUCCESS); ASSERT_EQ(BSL_PARAM_InitValue(&params[1], CRYPT_PARAM_KDF_MODE, BSL_PARAM_TYPE_UINT32, &mode, sizeof(mode)), CRYPT_SUCCESS); ASSERT_EQ(BSL_PARAM_InitValue(&params[2], CRYPT_PARAM_KDF_KEY, BSL_PARAM_TYPE_OCTETS, key->x, key->len), CRYPT_SUCCESS); ASSERT_EQ(BSL_PARAM_InitValue(&params[3], CRYPT_PARAM_KDF_SALT, BSL_PARAM_TYPE_OCTETS, salt->x, salt->len), CRYPT_SUCCESS); ASSERT_EQ(BSL_PARAM_InitValue(&params[4], CRYPT_PARAM_KDF_INFO, BSL_PARAM_TYPE_OCTETS, info->x, info->len), CRYPT_SUCCESS); ASSERT_EQ(CRYPT_EAL_KdfSetParam(kdfCtx, params), CRYPT_SUCCESS); ASSERT_EQ(CRYPT_EAL_KdfDerive(kdfCtx, out, outLen), CRYPT_SUCCESS); EXIT: if (out != NULL) { free(out); } CRYPT_EAL_KdfFreeCtx(kdfCtx); Iso19790_ProviderUnload(&ctx); #endif } /* END_CASE */ /* BEGIN_CASE */ void SDV_ISO19790_PROVIDER_KDF_TEST_TC003(int algId, Hex *key, Hex *label, Hex *seed) { #ifndef HITLS_CRYPTO_CMVP_ISO19790 (void)algId; (void)key; (void)label; (void)seed; SKIP_TEST(); #else if (IsHmacAlgDisabled(algId)) { SKIP_TEST(); } TestMemInit(); uint32_t outLen = 32; uint8_t *out = malloc(outLen * sizeof(uint8_t)); ASSERT_TRUE(out != NULL); Iso19790_ProviderLoadCtx ctx = {0}; CRYPT_EAL_KdfCTX *kdfCtx = NULL; Iso19790_ProviderLoad(&ctx); ASSERT_TRUE(ctx.libCtx != NULL && ctx.es != NULL && ctx.pool != NULL); kdfCtx = CRYPT_EAL_ProviderKdfNewCtx(ctx.libCtx, CRYPT_KDF_KDFTLS12, HITLS_ISO_PROVIDER_ATTR); ASSERT_TRUE(kdfCtx != NULL); BSL_Param params[5] = {{0}, {0}, {0}, {0}, BSL_PARAM_END}; ASSERT_EQ(BSL_PARAM_InitValue(&params[0], CRYPT_PARAM_KDF_MAC_ID, BSL_PARAM_TYPE_UINT32, &algId, sizeof(algId)), CRYPT_SUCCESS); ASSERT_EQ(BSL_PARAM_InitValue(&params[1], CRYPT_PARAM_KDF_KEY, BSL_PARAM_TYPE_OCTETS, key->x, key->len), CRYPT_SUCCESS); ASSERT_EQ(BSL_PARAM_InitValue(&params[2], CRYPT_PARAM_KDF_LABEL, BSL_PARAM_TYPE_OCTETS, label->x, label->len), CRYPT_SUCCESS); ASSERT_EQ(BSL_PARAM_InitValue(&params[3], CRYPT_PARAM_KDF_SEED, BSL_PARAM_TYPE_OCTETS, seed->x, seed->len), CRYPT_SUCCESS); ASSERT_EQ(CRYPT_EAL_KdfSetParam(kdfCtx, params), CRYPT_SUCCESS); ASSERT_EQ(CRYPT_EAL_KdfDerive(kdfCtx, out, outLen), CRYPT_SUCCESS); EXIT: if (out != NULL) { free(out); } CRYPT_EAL_KdfFreeCtx(kdfCtx); Iso19790_ProviderUnload(&ctx); #endif } /* END_CASE */ /* BEGIN_CASE */ void SDV_ISO19790_PROVIDER_Get_Status_Test_TC001() { #ifndef HITLS_CRYPTO_CMVP_ISO19790 SKIP_TEST(); #else CRYPT_EAL_LibCtx *libCtx = NULL; CRYPT_EAL_ProvMgrCtx *providerMgr = NULL; libCtx = CRYPT_EAL_LibCtxNew(); ASSERT_TRUE(libCtx != NULL); ASSERT_EQ(CRYPT_EAL_ProviderSetLoadPath(libCtx, HITLS_ISO_PROVIDER_PATH), CRYPT_SUCCESS); bool isLoaded = false; int32_t ret = CRYPT_EAL_ProviderIsLoaded(libCtx, 0, HITLS_ISO_LIB_NAME, &isLoaded); ASSERT_EQ(ret, CRYPT_SUCCESS); ASSERT_TRUE(isLoaded == false); BSL_Param providerParam[2] = {{0}, BSL_PARAM_END}; (void)BSL_PARAM_InitValue(&providerParam[0], CRYPT_PARAM_CMVP_LOG_FUNC, BSL_PARAM_TYPE_FUNC_PTR, ISO19790_RunLogCb, 0); do { ret = CRYPT_EAL_ProviderLoad(libCtx, 0, HITLS_ISO_LIB_NAME, providerParam, &providerMgr); } while (ret == CRYPT_ENTROPY_ES_NO_NS || ret == CRYPT_DRBG_FAIL_GET_ENTROPY || ret == CRYPT_DRBG_FAIL_GET_NONCE); ASSERT_EQ(ret, CRYPT_SUCCESS); ASSERT_TRUE(providerMgr != NULL); ret = CRYPT_EAL_ProviderIsLoaded(libCtx, 0, HITLS_ISO_LIB_NAME, &isLoaded); ASSERT_EQ(ret, CRYPT_SUCCESS); ASSERT_TRUE(isLoaded); providerMgr = NULL; ASSERT_EQ(CRYPT_EAL_ProviderLoad(libCtx, 0, HITLS_ISO_LIB_NAME, providerParam, &providerMgr), CRYPT_SUCCESS); ASSERT_TRUE(providerMgr != NULL); ret = CRYPT_EAL_ProviderUnload(libCtx, 0, HITLS_ISO_LIB_NAME); ASSERT_EQ(ret, CRYPT_SUCCESS); ret = CRYPT_EAL_ProviderIsLoaded(libCtx, 0, HITLS_ISO_LIB_NAME, &isLoaded); ASSERT_EQ(ret, CRYPT_SUCCESS); ASSERT_TRUE(isLoaded); ret = CRYPT_EAL_ProviderUnload(libCtx, 0, HITLS_ISO_LIB_NAME); ASSERT_EQ(ret, CRYPT_SUCCESS); ret = CRYPT_EAL_ProviderIsLoaded(libCtx, 0, HITLS_ISO_LIB_NAME, &isLoaded); ASSERT_EQ(ret, CRYPT_SUCCESS); ASSERT_TRUE(isLoaded == false); EXIT: CRYPT_EAL_ProviderUnload(libCtx, 0, HITLS_ISO_LIB_NAME); CRYPT_EAL_LibCtxFree(libCtx); return; #endif } /* END_CASE */ /* BEGIN_CASE */ void SDV_ISO19790_PROVIDER_CMVP_SELFTEST_Test_TC001() { #ifndef HITLS_CRYPTO_CMVP_ISO19790 SKIP_TEST(); #else Iso19790_ProviderLoadCtx ctx = {0}; CRYPT_SelftestCtx *selftestCtx = NULL; Iso19790_ProviderLoad(&ctx); ASSERT_TRUE(ctx.libCtx != NULL && ctx.es != NULL && ctx.pool != NULL); selftestCtx = CRYPT_CMVP_SelftestNewCtx(ctx.libCtx, HITLS_ISO_PROVIDER_ATTR); ASSERT_TRUE(selftestCtx != NULL); const char *version = CRYPT_CMVP_GetVersion(selftestCtx); ASSERT_TRUE(version != NULL); BSL_Param params[2] = {{0}, BSL_PARAM_END}; int32_t type = CRYPT_CMVP_KAT_TEST; ASSERT_EQ(BSL_PARAM_InitValue(&params[0], CRYPT_PARAM_CMVP_SELFTEST_TYPE, BSL_PARAM_TYPE_INT32, &type, sizeof(type)), CRYPT_SUCCESS); int32_t ret = CRYPT_CMVP_Selftest(selftestCtx, params); ASSERT_EQ(ret, CRYPT_SUCCESS); type = CRYPT_CMVP_INTEGRITY_TEST; ASSERT_EQ(BSL_PARAM_InitValue(&params[0], CRYPT_PARAM_CMVP_SELFTEST_TYPE, BSL_PARAM_TYPE_INT32, &type, sizeof(type)), CRYPT_SUCCESS); ret = CRYPT_CMVP_Selftest(selftestCtx, params); ASSERT_EQ(ret, CRYPT_SUCCESS); EXIT: CRYPT_CMVP_SelftestFreeCtx(selftestCtx); Iso19790_ProviderUnload(&ctx); return; #endif } /* END_CASE */ /* BEGIN_CASE */ void SDV_ISO19790_PROVIDER_ML_DSA_TEST_TC001() { #ifndef HITLS_CRYPTO_CMVP_ISO19790 SKIP_TEST(); #else Iso19790_ProviderLoadCtx ctx = {0}; CRYPT_EAL_PkeyCtx *pkeyCtx = NULL; int32_t mdId = CRYPT_MD_SHAKE128; uint8_t signature[4627] = {0}; uint32_t signatureLen = sizeof(signature); uint8_t testData[] = "Test data for signing and verification with ECDSA"; uint32_t testDataLen = sizeof(testData) - 1; Iso19790_ProviderLoad(&ctx); ASSERT_TRUE(ctx.libCtx != NULL && ctx.es != NULL && ctx.pool != NULL); pkeyCtx = CRYPT_EAL_ProviderPkeyNewCtx(ctx.libCtx, CRYPT_PKEY_ML_DSA, 0, HITLS_ISO_PROVIDER_ATTR); ASSERT_TRUE(pkeyCtx != NULL); uint32_t val = CRYPT_MLDSA_TYPE_MLDSA_44; int32_t ret = CRYPT_EAL_PkeyCtrl(pkeyCtx, CRYPT_CTRL_SET_PARA_BY_ID, &val, sizeof(val)); ASSERT_EQ(ret, CRYPT_SUCCESS); ASSERT_EQ(CRYPT_EAL_PkeyGen(pkeyCtx), CRYPT_SUCCESS); ASSERT_EQ(CRYPT_EAL_PkeySign(pkeyCtx, mdId, testData, testDataLen, signature, &signatureLen), 0); ASSERT_TRUE(signatureLen > 0); ASSERT_EQ(CRYPT_EAL_PkeyVerify(pkeyCtx, mdId, testData, testDataLen, signature, signatureLen), CRYPT_SUCCESS); EXIT: CRYPT_EAL_PkeyFreeCtx(pkeyCtx); Iso19790_ProviderUnload(&ctx); return; #endif } /* END_CASE */ /* BEGIN_CASE */ void SDV_ISO19790_PROVIDER_ML_KEM_TEST_TC001() { #ifndef HITLS_CRYPTO_CMVP_ISO19790 SKIP_TEST(); #else Iso19790_ProviderLoadCtx ctx = {0}; CRYPT_EAL_PkeyCtx *pkeyCtx = NULL; uint32_t cipherLen = 0; uint8_t *ciphertext = NULL; uint32_t sharedLen = 32; uint8_t *sharedKey = NULL; Iso19790_ProviderLoad(&ctx); ASSERT_TRUE(ctx.libCtx != NULL && ctx.es != NULL && ctx.pool != NULL); pkeyCtx = CRYPT_EAL_ProviderPkeyNewCtx(ctx.libCtx, CRYPT_PKEY_ML_KEM, 0, HITLS_ISO_PROVIDER_ATTR); ASSERT_TRUE(pkeyCtx != NULL); uint32_t val = CRYPT_KEM_TYPE_MLKEM_512; int32_t ret = CRYPT_EAL_PkeyCtrl(pkeyCtx, CRYPT_CTRL_SET_PARA_BY_ID, &val, sizeof(val)); ASSERT_EQ(ret, CRYPT_SUCCESS); ASSERT_EQ(CRYPT_EAL_PkeyGen(pkeyCtx), CRYPT_SUCCESS); ret = CRYPT_EAL_PkeyCtrl(pkeyCtx, CRYPT_CTRL_GET_CIPHERTEXT_LEN, &cipherLen, sizeof(cipherLen)); ASSERT_EQ(ret, CRYPT_SUCCESS); ciphertext = BSL_SAL_Malloc(cipherLen); ASSERT_TRUE(ciphertext != NULL); sharedKey = BSL_SAL_Malloc(sharedLen); ASSERT_TRUE(sharedKey != NULL); ret = CRYPT_EAL_PkeyEncaps(pkeyCtx, ciphertext, &cipherLen, sharedKey, &sharedLen); ASSERT_EQ(ret, CRYPT_SUCCESS); EXIT: BSL_SAL_Free(ciphertext); BSL_SAL_Free(sharedKey); CRYPT_EAL_PkeyFreeCtx(pkeyCtx); Iso19790_ProviderUnload(&ctx); return; #endif } /* END_CASE */ /* BEGIN_CASE */ void SDV_ISO19790_PROVIDER_CIPHPER_TEST_TC001() { #ifndef HITLS_CRYPTO_CMVP_ISO19790 SKIP_TEST(); #else Iso19790_ProviderLoadCtx ctx = {0}; CRYPT_EAL_CipherCtx *cipherCtx = NULL; uint8_t key[32] = {0}; uint32_t keyLen = 16; uint8_t iv[32] = {0}; uint32_t ivLen = 16; uint8_t plain[] = "Test data for signing and verification with ECDSA"; uint32_t plainLen = sizeof(plainLen) - 1; uint8_t cipher[128] = {0}; uint32_t cipherLen = sizeof(cipher); Iso19790_ProviderLoad(&ctx); ASSERT_TRUE(ctx.libCtx != NULL && ctx.es != NULL && ctx.pool != NULL); cipherCtx = CRYPT_EAL_ProviderCipherNewCtx(ctx.libCtx, CRYPT_CIPHER_AES128_CBC, HITLS_ISO_PROVIDER_ATTR); ASSERT_TRUE(cipherCtx != NULL); int32_t ret = CRYPT_EAL_CipherInit(cipherCtx, key, keyLen, iv, ivLen, true); ASSERT_EQ(ret, CRYPT_SUCCESS); ret = CRYPT_EAL_CipherSetPadding(cipherCtx, CRYPT_PADDING_PKCS7); ASSERT_EQ(ret, CRYPT_SUCCESS); uint32_t tmpLen = cipherLen; ret = CRYPT_EAL_CipherUpdate(cipherCtx, plain, plainLen, cipher, &tmpLen); ASSERT_EQ(ret, CRYPT_SUCCESS); cipherLen = tmpLen; tmpLen = sizeof(cipher) - cipherLen; ret = CRYPT_EAL_CipherFinal(cipherCtx, cipher + cipherLen, &tmpLen); ASSERT_EQ(ret, CRYPT_SUCCESS); cipherLen += tmpLen; EXIT: CRYPT_EAL_CipherFreeCtx(cipherCtx); Iso19790_ProviderUnload(&ctx); return; #endif } /* END_CASE */ #ifdef HITLS_CRYPTO_CMVP_ISO19790 static void SetDsaPara(CRYPT_EAL_PkeyPara *para, uint8_t *p, uint32_t pLen, uint8_t *q, uint32_t qLen, uint8_t *g, uint32_t gLen) { para->id = CRYPT_PKEY_DSA; para->para.dsaPara.p = p; para->para.dsaPara.pLen = pLen; para->para.dsaPara.q = q; para->para.dsaPara.qLen = qLen; para->para.dsaPara.g = g; para->para.dsaPara.gLen = gLen; } #endif /* SDV_ISO19790_PROVIDER_PKEY_TEST_TC001 测试DSA set para */ /* BEGIN_CASE */ void SDV_ISO19790_PROVIDER_PKEY_TEST_TC001(int hashId, Hex *p, Hex *q, Hex *g) { #ifndef HITLS_CRYPTO_CMVP_ISO19790 (void)hashId; (void)p; (void)q; (void)g; SKIP_TEST(); #else Iso19790_ProviderLoadCtx ctx = {0}; CRYPT_EAL_PkeyCtx *pkeyCtx = NULL; CRYPT_EAL_PkeyPara para = {0}; uint8_t signature[128] = {0}; uint32_t signatureLen = sizeof(signature); uint8_t testData[] = "Test data for signing and verification with ECDSA"; uint32_t testDataLen = sizeof(testData) - 1; Iso19790_ProviderLoad(&ctx); ASSERT_TRUE(ctx.libCtx != NULL && ctx.es != NULL && ctx.pool != NULL); pkeyCtx = CRYPT_EAL_ProviderPkeyNewCtx(ctx.libCtx, CRYPT_PKEY_DSA, 0, HITLS_ISO_PROVIDER_ATTR); ASSERT_TRUE(pkeyCtx != NULL); SetDsaPara(&para, p->x, p->len, q->x, q->len, g->x, g->len); ASSERT_EQ(CRYPT_EAL_PkeySetPara(pkeyCtx, &para), CRYPT_SUCCESS); ASSERT_EQ(CRYPT_EAL_PkeyGen(pkeyCtx), CRYPT_SUCCESS); ASSERT_EQ(CRYPT_EAL_PkeySign(pkeyCtx, hashId, testData, testDataLen, signature, &signatureLen), 0); ASSERT_EQ(CRYPT_EAL_PkeyVerify(pkeyCtx, hashId, testData, testDataLen, signature, signatureLen), CRYPT_SUCCESS); EXIT: CRYPT_EAL_PkeyFreeCtx(pkeyCtx); Iso19790_ProviderUnload(&ctx); return; #endif } /* END_CASE */ /* BEGIN_CASE */ void SDV_ISO19790_PROVIDER_MAC_PARAM_CHECK_TC001(int algId, int keyLen) { #ifndef HITLS_CRYPTO_CMVP_ISO19790 (void)algId; (void)keyLen; SKIP_TEST(); #else Iso19790_ProviderLoadCtx ctx = {0}; CRYPT_EAL_MacCtx *macCtx = NULL; uint8_t macKey[32] = {0}; uint32_t macKeyLen = 13; Iso19790_ProviderLoad(&ctx); ASSERT_TRUE(ctx.libCtx != NULL && ctx.es != NULL && ctx.pool != NULL); macCtx = CRYPT_EAL_ProviderMacNewCtx(ctx.libCtx, algId, HITLS_ISO_PROVIDER_ATTR); ASSERT_TRUE(macCtx != NULL); int32_t ret = CRYPT_EAL_MacInit(macCtx, macKey, macKeyLen); ASSERT_EQ(ret, CRYPT_CMVP_ERR_PARAM_CHECK); macKeyLen = keyLen; ret = CRYPT_EAL_MacInit(macCtx, macKey, macKeyLen); ASSERT_EQ(ret, CRYPT_SUCCESS); EXIT: CRYPT_EAL_MacFreeCtx(macCtx); Iso19790_ProviderUnload(&ctx); return; #endif } /* END_CASE */ /* BEGIN_CASE */ void SDV_ISO19790_PROVIDER_KDF_PARAM_CHECK_TC001(Hex *key, Hex *label, Hex *seed) { #ifndef HITLS_CRYPTO_CMVP_ISO19790 (void)key; (void)label; (void)seed; SKIP_TEST(); #else Iso19790_ProviderLoadCtx ctx = {0}; CRYPT_EAL_KdfCTX *kdfCtx = NULL; Iso19790_ProviderLoad(&ctx); ASSERT_TRUE(ctx.libCtx != NULL && ctx.es != NULL && ctx.pool != NULL); kdfCtx = CRYPT_EAL_ProviderKdfNewCtx(ctx.libCtx, CRYPT_KDF_KDFTLS12, HITLS_ISO_PROVIDER_ATTR); ASSERT_TRUE(kdfCtx != NULL); BSL_Param params[5] = {{0}, {0}, {0}, {0}, BSL_PARAM_END}; ASSERT_EQ(BSL_PARAM_InitValue(&params[1], CRYPT_PARAM_KDF_KEY, BSL_PARAM_TYPE_OCTETS, key->x, 14), CRYPT_SUCCESS); ASSERT_EQ(BSL_PARAM_InitValue(&params[2], CRYPT_PARAM_KDF_LABEL, BSL_PARAM_TYPE_OCTETS, label->x, label->len), CRYPT_SUCCESS); ASSERT_EQ(BSL_PARAM_InitValue(&params[3], CRYPT_PARAM_KDF_SEED, BSL_PARAM_TYPE_OCTETS, seed->x, seed->len), CRYPT_SUCCESS); int32_t macId = CRYPT_MAC_HMAC_SHA224; ASSERT_EQ(BSL_PARAM_InitValue(&params[0], CRYPT_PARAM_KDF_MAC_ID, BSL_PARAM_TYPE_UINT32, &macId, sizeof(macId)), CRYPT_SUCCESS); ASSERT_EQ(CRYPT_EAL_KdfSetParam(kdfCtx, params), CRYPT_CMVP_ERR_PARAM_CHECK); macId = CRYPT_MAC_HMAC_SHA256; ASSERT_EQ(BSL_PARAM_InitValue(&params[0], CRYPT_PARAM_KDF_MAC_ID, BSL_PARAM_TYPE_UINT32, &macId, sizeof(macId)), CRYPT_SUCCESS); ASSERT_EQ(CRYPT_EAL_KdfSetParam(kdfCtx, params), CRYPT_SUCCESS); // key len < 112 / 8 ASSERT_EQ(BSL_PARAM_InitValue(&params[1], CRYPT_PARAM_KDF_KEY, BSL_PARAM_TYPE_OCTETS, key->x, 13), CRYPT_SUCCESS); ASSERT_EQ(CRYPT_EAL_KdfSetParam(kdfCtx, params), CRYPT_CMVP_ERR_PARAM_CHECK); EXIT: CRYPT_EAL_KdfFreeCtx(kdfCtx); Iso19790_ProviderUnload(&ctx); #endif } /* END_CASE */ /* BEGIN_CASE */ void SDV_ISO19790_PROVIDER_KDF_PARAM_CHECK_TC002(Hex *key, Hex *salt, Hex *info) { #ifndef HITLS_CRYPTO_CMVP_ISO19790 (void)key; (void)salt; (void)info; SKIP_TEST(); #else Iso19790_ProviderLoadCtx ctx = {0}; CRYPT_EAL_KdfCTX *kdfCtx = NULL; Iso19790_ProviderLoad(&ctx); ASSERT_TRUE(ctx.libCtx != NULL && ctx.es != NULL && ctx.pool != NULL); kdfCtx = CRYPT_EAL_ProviderKdfNewCtx(ctx.libCtx, CRYPT_KDF_HKDF, HITLS_ISO_PROVIDER_ATTR); ASSERT_TRUE(kdfCtx != NULL); int32_t macId = CRYPT_MAC_HMAC_SHA256; CRYPT_HKDF_MODE mode = CRYPT_KDF_HKDF_MODE_FULL; BSL_Param params[6] = {{0}, {0}, {0}, {0}, {0}, BSL_PARAM_END}; ASSERT_EQ(BSL_PARAM_InitValue(&params[0], CRYPT_PARAM_KDF_MAC_ID, BSL_PARAM_TYPE_UINT32, &macId, sizeof(macId)), CRYPT_SUCCESS); ASSERT_EQ(BSL_PARAM_InitValue(&params[1], CRYPT_PARAM_KDF_MODE, BSL_PARAM_TYPE_UINT32, &mode, sizeof(mode)), CRYPT_SUCCESS); ASSERT_EQ(BSL_PARAM_InitValue(&params[2], CRYPT_PARAM_KDF_KEY, BSL_PARAM_TYPE_OCTETS, key->x, key->len), CRYPT_SUCCESS); ASSERT_EQ(BSL_PARAM_InitValue(&params[3], CRYPT_PARAM_KDF_SALT, BSL_PARAM_TYPE_OCTETS, salt->x, salt->len), CRYPT_SUCCESS); ASSERT_EQ(BSL_PARAM_InitValue(&params[4], CRYPT_PARAM_KDF_INFO, BSL_PARAM_TYPE_OCTETS, info->x, info->len), CRYPT_SUCCESS); macId = CRYPT_MAC_HMAC_SM3; ASSERT_EQ(CRYPT_EAL_KdfSetParam(kdfCtx, params), CRYPT_CMVP_ERR_PARAM_CHECK); macId = CRYPT_MAC_HMAC_SHA256; ASSERT_EQ(CRYPT_EAL_KdfSetParam(kdfCtx, params), CRYPT_SUCCESS); // key len < 112 / 8 ASSERT_EQ(BSL_PARAM_InitValue(&params[2], CRYPT_PARAM_KDF_KEY, BSL_PARAM_TYPE_OCTETS, key->x, 13), CRYPT_SUCCESS); ASSERT_EQ(CRYPT_EAL_KdfSetParam(kdfCtx, params), CRYPT_CMVP_ERR_PARAM_CHECK); ASSERT_EQ(BSL_PARAM_InitValue(&params[2], CRYPT_PARAM_KDF_KEY, BSL_PARAM_TYPE_OCTETS, key->x, 14), CRYPT_SUCCESS); ASSERT_EQ(CRYPT_EAL_KdfSetParam(kdfCtx, params), CRYPT_SUCCESS); EXIT: CRYPT_EAL_KdfFreeCtx(kdfCtx); Iso19790_ProviderUnload(&ctx); #endif } /* END_CASE */ /* BEGIN_CASE */ void SDV_ISO19790_PROVIDER_KDF_PARAM_CHECK_TC003() { #ifndef HITLS_CRYPTO_CMVP_ISO19790 SKIP_TEST(); #else Iso19790_ProviderLoadCtx ctx = {0}; CRYPT_EAL_KdfCTX *kdfCtx = NULL; uint8_t password[32] = {0}; uint32_t passwordLen = sizeof(password); uint8_t salt[32] = {0}; uint8_t derivedKey[32] = {0}; Iso19790_ProviderLoad(&ctx); ASSERT_TRUE(ctx.libCtx != NULL && ctx.es != NULL && ctx.pool != NULL); kdfCtx = CRYPT_EAL_ProviderKdfNewCtx(ctx.libCtx, CRYPT_KDF_PBKDF2, HITLS_ISO_PROVIDER_ATTR); ASSERT_TRUE(kdfCtx != NULL); int32_t iter = 1024; int32_t saltLen = 16; int32_t macId = CRYPT_MAC_SIPHASH64; BSL_Param param[5] = {{0}, {0}, {0}, {0}, BSL_PARAM_END}; (void)BSL_PARAM_InitValue(&param[0], CRYPT_PARAM_KDF_MAC_ID, BSL_PARAM_TYPE_UINT32, &macId, sizeof(macId)); (void)BSL_PARAM_InitValue(&param[1], CRYPT_PARAM_KDF_PASSWORD, BSL_PARAM_TYPE_OCTETS, password, passwordLen); (void)BSL_PARAM_InitValue(&param[2], CRYPT_PARAM_KDF_SALT, BSL_PARAM_TYPE_OCTETS, salt, saltLen); (void)BSL_PARAM_InitValue(&param[3], CRYPT_PARAM_KDF_ITER, BSL_PARAM_TYPE_UINT32, &iter, sizeof(iter)); int32_t ret = CRYPT_EAL_KdfSetParam(kdfCtx, param); ASSERT_EQ(ret, CRYPT_CMVP_ERR_PARAM_CHECK); macId = CRYPT_MAC_HMAC_SHA1; ASSERT_EQ(CRYPT_EAL_KdfSetParam(kdfCtx, param), CRYPT_SUCCESS); iter = 999; ASSERT_EQ(CRYPT_EAL_KdfSetParam(kdfCtx, param), CRYPT_CMVP_ERR_PARAM_CHECK); iter = 1000; ASSERT_EQ(CRYPT_EAL_KdfSetParam(kdfCtx, param), CRYPT_SUCCESS); saltLen = 15; (void)BSL_PARAM_InitValue(&param[2], CRYPT_PARAM_KDF_SALT, BSL_PARAM_TYPE_OCTETS, salt, saltLen); ASSERT_EQ(CRYPT_EAL_KdfSetParam(kdfCtx, param), CRYPT_CMVP_ERR_PARAM_CHECK); saltLen = 16; (void)BSL_PARAM_InitValue(&param[2], CRYPT_PARAM_KDF_SALT, BSL_PARAM_TYPE_OCTETS, salt, saltLen); ASSERT_EQ(CRYPT_EAL_KdfSetParam(kdfCtx, param), CRYPT_SUCCESS); uint32_t derivedKeyLen = 13; ret = CRYPT_EAL_KdfDerive(kdfCtx, derivedKey, derivedKeyLen); ASSERT_EQ(ret, CRYPT_CMVP_ERR_PARAM_CHECK); derivedKeyLen = 14; ret = CRYPT_EAL_KdfDerive(kdfCtx, derivedKey, derivedKeyLen); ASSERT_EQ(ret, CRYPT_SUCCESS); EXIT: CRYPT_EAL_KdfFreeCtx(kdfCtx); Iso19790_ProviderUnload(&ctx); return; #endif } /* END_CASE */ /* BEGIN_CASE */ void SDV_ISO19790_PROVIDER_DSA_PARAM_CHECK_TC001(Hex *p, Hex *q, Hex *g) { #ifndef HITLS_CRYPTO_CMVP_ISO19790 (void)p; (void)q; (void)g; SKIP_TEST(); #else Iso19790_ProviderLoadCtx ctx = {0}; CRYPT_EAL_PkeyCtx *pkeyCtx = NULL; CRYPT_EAL_PkeyPara para = {0}; Iso19790_ProviderLoad(&ctx); ASSERT_TRUE(ctx.libCtx != NULL && ctx.es != NULL && ctx.pool != NULL); pkeyCtx = CRYPT_EAL_ProviderPkeyNewCtx(ctx.libCtx, CRYPT_PKEY_DSA, 0, HITLS_ISO_PROVIDER_ATTR); ASSERT_TRUE(pkeyCtx != NULL); SetDsaPara(&para, p->x, 256, q->x, 27, g->x, 256); ASSERT_EQ(CRYPT_EAL_PkeySetPara(pkeyCtx, &para), CRYPT_CMVP_ERR_PARAM_CHECK); SetDsaPara(&para, p->x, 256, q->x, 31, g->x, 256); ASSERT_EQ(CRYPT_EAL_PkeySetPara(pkeyCtx, &para), CRYPT_CMVP_ERR_PARAM_CHECK); SetDsaPara(&para, p->x, 384, q->x, 31, g->x, 384); ASSERT_EQ(CRYPT_EAL_PkeySetPara(pkeyCtx, &para), CRYPT_CMVP_ERR_PARAM_CHECK); EXIT: CRYPT_EAL_PkeyFreeCtx(pkeyCtx); Iso19790_ProviderUnload(&ctx); return; #endif } /* END_CASE */ /* BEGIN_CASE */ void SDV_ISO19790_PROVIDER_RSA_PARAM_CHECK_TC001() { #ifndef HITLS_CRYPTO_CMVP_ISO19790 SKIP_TEST(); #else Iso19790_ProviderLoadCtx ctx = {0}; CRYPT_EAL_PkeyCtx *pkeyCtx = NULL; uint8_t e[] = {1, 0, 1}; CRYPT_EAL_PkeyPara para = {0}; Iso19790_ProviderLoad(&ctx); ASSERT_TRUE(ctx.libCtx != NULL && ctx.es != NULL && ctx.pool != NULL); pkeyCtx = CRYPT_EAL_ProviderPkeyNewCtx(ctx.libCtx, CRYPT_PKEY_RSA, 0, HITLS_ISO_PROVIDER_ATTR); ASSERT_TRUE(pkeyCtx != NULL); SetRsaPara(&para, e, 3, 1024); ASSERT_EQ(CRYPT_EAL_PkeySetPara(pkeyCtx, &para), CRYPT_CMVP_ERR_PARAM_CHECK); SetRsaPara(&para, e, 3, 2048); ASSERT_EQ(CRYPT_EAL_PkeySetPara(pkeyCtx, &para), CRYPT_SUCCESS); EXIT: CRYPT_EAL_PkeyFreeCtx(pkeyCtx); Iso19790_ProviderUnload(&ctx); return; #endif } /* END_CASE */ /* Check the padding mode of the RSA. */ /* BEGIN_CASE */ void SDV_ISO19790_PROVIDER_RSA_PARAM_CHECK_TC002() { #ifndef HITLS_CRYPTO_CMVP_ISO19790 SKIP_TEST(); #else Iso19790_ProviderLoadCtx ctx = {0}; CRYPT_EAL_PkeyCtx *pkeyCtx = NULL; uint8_t e[] = {1, 0, 1}; CRYPT_EAL_PkeyPara para = {0}; int32_t mdId = CRYPT_MD_SHA256; Iso19790_ProviderLoad(&ctx); ASSERT_TRUE(ctx.libCtx != NULL && ctx.es != NULL && ctx.pool != NULL); pkeyCtx = CRYPT_EAL_ProviderPkeyNewCtx(ctx.libCtx, CRYPT_PKEY_RSA, 0, HITLS_ISO_PROVIDER_ATTR); ASSERT_TRUE(pkeyCtx != NULL); SetRsaPara(&para, e, 3, 2048); ASSERT_EQ(CRYPT_EAL_PkeySetPara(pkeyCtx, &para), CRYPT_SUCCESS); ASSERT_EQ(CRYPT_EAL_PkeyGen(pkeyCtx), CRYPT_SUCCESS); int32_t pkcsv15 = mdId; ASSERT_EQ(CRYPT_EAL_PkeyCtrl(pkeyCtx, CRYPT_CTRL_SET_RSA_RSAES_PKCSV15, &pkcsv15, sizeof(pkcsv15)), CRYPT_CMVP_ERR_PARAM_CHECK); ASSERT_EQ(CRYPT_EAL_PkeyCtrl(pkeyCtx, CRYPT_CTRL_SET_RSA_RSAES_PKCSV15_TLS, &pkcsv15, sizeof(pkcsv15)), CRYPT_CMVP_ERR_PARAM_CHECK); ASSERT_EQ(CRYPT_EAL_PkeyCtrl(pkeyCtx, CRYPT_CTRL_SET_NO_PADDING, NULL, 0), CRYPT_CMVP_ERR_PARAM_CHECK); int32_t pad = CRYPT_EMSA_PKCSV15; ASSERT_EQ(CRYPT_EAL_PkeyCtrl(pkeyCtx, CRYPT_CTRL_SET_RSA_PADDING, &pad, sizeof(pad)), CRYPT_SUCCESS); pad = CRYPT_EMSA_PSS; ASSERT_EQ(CRYPT_EAL_PkeyCtrl(pkeyCtx, CRYPT_CTRL_SET_RSA_PADDING, &pad, sizeof(pad)), CRYPT_SUCCESS); pad = CRYPT_RSAES_OAEP; ASSERT_EQ(CRYPT_EAL_PkeyCtrl(pkeyCtx, CRYPT_CTRL_SET_RSA_PADDING, &pad, sizeof(pad)), CRYPT_SUCCESS); pad = CRYPT_RSAES_PKCSV15; ASSERT_EQ(CRYPT_EAL_PkeyCtrl(pkeyCtx, CRYPT_CTRL_SET_RSA_PADDING, &pad, sizeof(pad)), CRYPT_CMVP_ERR_PARAM_CHECK); pad = CRYPT_RSA_NO_PAD; ASSERT_EQ(CRYPT_EAL_PkeyCtrl(pkeyCtx, CRYPT_CTRL_SET_RSA_PADDING, &pad, sizeof(pad)), CRYPT_CMVP_ERR_PARAM_CHECK); pad = CRYPT_RSAES_PKCSV15_TLS; ASSERT_EQ(CRYPT_EAL_PkeyCtrl(pkeyCtx, CRYPT_CTRL_SET_RSA_PADDING, &pad, sizeof(pad)), CRYPT_CMVP_ERR_PARAM_CHECK); ASSERT_EQ(CRYPT_EAL_PkeyCtrl(pkeyCtx, CRYPT_CTRL_SET_RSA_EMSA_PKCSV15, &pkcsv15, sizeof(pkcsv15)), CRYPT_SUCCESS); BSL_Param pssParam[3] = { {CRYPT_PARAM_RSA_MD_ID, BSL_PARAM_TYPE_INT32, &mdId, sizeof(mdId), 0}, {CRYPT_PARAM_RSA_MGF1_ID, BSL_PARAM_TYPE_INT32, &mdId, sizeof(mdId), 0}, BSL_PARAM_END}; ASSERT_EQ(CRYPT_EAL_PkeyCtrl(pkeyCtx, CRYPT_CTRL_SET_RSA_EMSA_PSS, pssParam, 0), CRYPT_SUCCESS); BSL_Param oaep[3] = {{CRYPT_PARAM_RSA_MD_ID, BSL_PARAM_TYPE_INT32, &mdId, sizeof(mdId), 0}, {CRYPT_PARAM_RSA_MGF1_ID, BSL_PARAM_TYPE_INT32, &mdId, sizeof(mdId), 0}, BSL_PARAM_END }; ASSERT_EQ(CRYPT_EAL_PkeyCtrl(pkeyCtx, CRYPT_CTRL_SET_RSA_RSAES_OAEP, oaep, 0), CRYPT_SUCCESS); EXIT: CRYPT_EAL_PkeyFreeCtx(pkeyCtx); Iso19790_ProviderUnload(&ctx); return; #endif } /* END_CASE */ /* BEGIN_CASE */ void SDV_ISO19790_PROVIDER_ECDH_SM2_TEST_TC001() { #ifndef HITLS_CRYPTO_CMVP_ISO19790 SKIP_TEST(); #else Iso19790_ProviderLoadCtx ctx = {0}; CRYPT_EAL_PkeyCtx *pkeyCtx1 = NULL; CRYPT_EAL_PkeyCtx *pkeyCtx2 = NULL; Iso19790_ProviderLoad(&ctx); ASSERT_TRUE(ctx.libCtx != NULL && ctx.es != NULL && ctx.pool != NULL); pkeyCtx1 = CRYPT_EAL_ProviderPkeyNewCtx(ctx.libCtx, CRYPT_PKEY_ECDH, 0, HITLS_ISO_PROVIDER_ATTR); pkeyCtx2 = CRYPT_EAL_ProviderPkeyNewCtx(ctx.libCtx, CRYPT_PKEY_ECDH, 0, HITLS_ISO_PROVIDER_ATTR); ASSERT_TRUE(pkeyCtx1 != NULL && pkeyCtx2 != NULL); ASSERT_EQ(CRYPT_EAL_PkeySetParaById(pkeyCtx1, CRYPT_ECC_SM2), CRYPT_SUCCESS); ASSERT_EQ(CRYPT_EAL_PkeySetParaById(pkeyCtx2, CRYPT_ECC_SM2), CRYPT_SUCCESS); ASSERT_EQ(CRYPT_EAL_PkeyGen(pkeyCtx1), CRYPT_SUCCESS); ASSERT_EQ(CRYPT_EAL_PkeyGen(pkeyCtx2), CRYPT_SUCCESS); uint8_t sharedKey1[32] = {0}; uint32_t sharedKeyLen1 = sizeof(sharedKey1); ASSERT_EQ(CRYPT_EAL_PkeyComputeShareKey(pkeyCtx1, pkeyCtx2, sharedKey1, &sharedKeyLen1), CRYPT_SUCCESS); ASSERT_EQ(sharedKeyLen1, 32); uint8_t sharedKey2[32] = {0}; uint32_t sharedKeyLen2 = sizeof(sharedKey2); ASSERT_EQ(CRYPT_EAL_PkeyComputeShareKey(pkeyCtx2, pkeyCtx1, sharedKey2, &sharedKeyLen2), CRYPT_SUCCESS); ASSERT_EQ(sharedKeyLen2, 32); ASSERT_EQ(memcmp(sharedKey1, sharedKey2, sharedKeyLen1), 0); EXIT: CRYPT_EAL_PkeyFreeCtx(pkeyCtx1); CRYPT_EAL_PkeyFreeCtx(pkeyCtx2); Iso19790_ProviderUnload(&ctx); return; #endif } /* END_CASE */ /* Test event report log. */ /* BEGIN_CASE */ void SDV_ISO19790_PROVIDER_RUN_LOG_TEST_TC001() { #ifndef HITLS_CRYPTO_CMVP_ISO19790 SKIP_TEST(); #else Iso19790_ProviderLoadCtx ctx = {0}; CRYPT_EAL_PkeyCtx *pkeyCtx = NULL; CRYPT_EAL_RegEventReport(ISO19790_RunLogCb); Iso19790_ProviderLoad(&ctx); ASSERT_TRUE(ctx.libCtx != NULL && ctx.es != NULL && ctx.pool != NULL); pkeyCtx = CRYPT_EAL_ProviderPkeyNewCtx(ctx.libCtx, BSL_CID_UNKNOWN, 0, HITLS_ISO_PROVIDER_ATTR); ASSERT_TRUE(pkeyCtx == NULL); EXIT: Iso19790_ProviderUnload(&ctx); return; #endif } /* END_CASE */ /* BEGIN_CASE */ void SDV_ISO19790_PROVIDER_DH_CHECK_TEST_TC001() { #ifndef HITLS_CRYPTO_CMVP_ISO19790 SKIP_TEST(); #else Iso19790_ProviderLoadCtx ctx = {0}; CRYPT_EAL_PkeyCtx *pkeyCtx = NULL; Iso19790_ProviderLoad(&ctx); ASSERT_TRUE(ctx.libCtx != NULL && ctx.es != NULL && ctx.pool != NULL); pkeyCtx = CRYPT_EAL_ProviderPkeyNewCtx(ctx.libCtx, CRYPT_PKEY_DH, 0, HITLS_ISO_PROVIDER_ATTR); ASSERT_TRUE(pkeyCtx != NULL); ASSERT_EQ(CRYPT_EAL_PkeySetParaById(pkeyCtx, CRYPT_DH_RFC7919_2048), CRYPT_SUCCESS); ASSERT_EQ(CRYPT_EAL_PkeyGen(pkeyCtx), CRYPT_SUCCESS); ASSERT_EQ(CRYPT_EAL_PkeyPrvCheck(pkeyCtx), CRYPT_SUCCESS); ASSERT_EQ(CRYPT_EAL_PkeyPairCheck(pkeyCtx, pkeyCtx), CRYPT_SUCCESS); EXIT: CRYPT_EAL_PkeyFreeCtx(pkeyCtx); Iso19790_ProviderUnload(&ctx); return; #endif } /* END_CASE */ /* BEGIN_CASE */ void SDV_ISO19790_PROVIDER_MD_USE_DEFAULT_LIBCTX_TEST_TC001(int algId) { #ifndef HITLS_CRYPTO_CMVP_ISO19790 (void)algId; SKIP_TEST(); #else int32_t ret = CRYPT_SUCCESS; CRYPT_EAL_MdCTX *mdCtx = NULL; uint8_t plaintext[128] = {0}; uint32_t plaintextLen = sizeof(plaintext); uint8_t md[128] = {0}; uint32_t mdLen = sizeof(md); BSL_Param param[2] = {{0}, BSL_PARAM_END}; (void)BSL_PARAM_InitValue(&param[0], CRYPT_PARAM_CMVP_LOG_FUNC, BSL_PARAM_TYPE_FUNC_PTR, ISO19790_RunLogCb, 0); ASSERT_EQ(CRYPT_EAL_ProviderSetLoadPath(NULL, HITLS_ISO_PROVIDER_PATH), CRYPT_SUCCESS); do { ret = CRYPT_EAL_ProviderLoad(NULL, 0, HITLS_ISO_LIB_NAME, param, NULL); } while (ret == CRYPT_ENTROPY_ES_NO_NS || ret == CRYPT_DRBG_FAIL_GET_ENTROPY || ret == CRYPT_DRBG_FAIL_GET_NONCE); ASSERT_EQ(ret, CRYPT_SUCCESS); do { ret = CRYPT_EAL_ProviderRandInitCtx(NULL, CRYPT_RAND_SHA256, HITLS_ISO_PROVIDER_ATTR, NULL, 0, NULL); } while (ret == CRYPT_ENTROPY_ES_NO_NS || ret == CRYPT_DRBG_FAIL_GET_ENTROPY || ret == CRYPT_DRBG_FAIL_GET_NONCE); ASSERT_EQ(ret, CRYPT_SUCCESS); mdCtx = CRYPT_EAL_ProviderMdNewCtx(NULL, algId, HITLS_ISO_PROVIDER_ATTR); ASSERT_TRUE(mdCtx != NULL); ret = CRYPT_EAL_MdInit(mdCtx); ASSERT_EQ(ret, CRYPT_SUCCESS); ret = CRYPT_EAL_MdUpdate(mdCtx, plaintext, plaintextLen); ASSERT_EQ(ret, CRYPT_SUCCESS); ret = CRYPT_EAL_MdFinal(mdCtx, md, &mdLen); ASSERT_EQ(ret, CRYPT_SUCCESS); EXIT: CRYPT_EAL_MdFreeCtx(mdCtx); CRYPT_EAL_RandDeinitEx(NULL); CRYPT_EAL_ProviderUnload(NULL, 0, HITLS_ISO_LIB_NAME); return; #endif } /* END_CASE */
2301_79861745/bench_create
testcode/sdv/testcase/crypto/provider/test_suite_sdv_eal_iso19790_provider.c
C
unknown
51,313
/* * This file is part of the openHiTLS project. * * openHiTLS is licensed under the Mulan PSL v2. * You can use this software according to the terms and conditions of the Mulan PSL v2. * You may obtain a copy of Mulan PSL v2 at: * * http://license.coscl.org.cn/MulanPSL2 * * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. * See the Mulan PSL v2 for more details. */ /* BEGIN_HEADER */ #include <stdio.h> #include "crypt_errno.h" #include "crypt_algid.h" #include "crypt_eal_md.h" #include "crypt_eal_mac.h" #include "crypt_eal_kdf.h" #include "crypt_eal_pkey.h" #include "crypt_eal_rand.h" #include "crypt_eal_provider.h" #include "crypt_params_key.h" /* END_HEADER */ #define SHA2_OUTPUT_MAXSIZE 32 #define MAX_CIPHERTEXT_LEN 2048 #define DEFAULT_PROVIDER "default" #ifdef HITLS_CRYPTO_PROVIDER static int32_t InitTwoProviders(CRYPT_EAL_LibCtx **libCtx, const char *path, const char *providerName1, const char *providerName2) { *libCtx = CRYPT_EAL_LibCtxNew(); ASSERT_TRUE(*libCtx != NULL); ASSERT_EQ(CRYPT_EAL_ProviderSetLoadPath(*libCtx, path), 0); if (strcmp(providerName1, DEFAULT_PROVIDER) == 0) { ASSERT_EQ(CRYPT_EAL_ProviderLoad(*libCtx, BSL_SAL_LIB_FMT_OFF, providerName1, NULL, NULL), 0); } else { ASSERT_EQ(CRYPT_EAL_ProviderLoad(*libCtx, BSL_SAL_LIB_FMT_SO, providerName1, NULL, NULL), 0); } if (strcmp(providerName2, DEFAULT_PROVIDER) == 0) { ASSERT_EQ(CRYPT_EAL_ProviderLoad(*libCtx, BSL_SAL_LIB_FMT_OFF, providerName2, NULL, NULL), 0); } else { ASSERT_EQ(CRYPT_EAL_ProviderLoad(*libCtx, BSL_SAL_LIB_FMT_SO, providerName2, NULL, NULL), 0); } return 0; EXIT: CRYPT_EAL_LibCtxFree(*libCtx); *libCtx = NULL; return 1; } #endif void NoUsedParam(char *path, char *defProName, char *customProName, char *defAttr, char *customAttr) { (void)path; (void)defProName; (void)customProName; (void)defAttr; (void)customAttr; } /** * @test SDV_PROVIDER_SHA256_TC001 * @title SHA256 test: sha256 from no-provider, default provider or other provider */ /* BEGIN_CASE */ void SDV_PROVIDER_SHA256_TC001(char *path, char *defProName, char *customProName, char *customAttr, Hex *in, Hex *digest) { #if defined(HITLS_CRYPTO_MD) && defined(HITLS_CRYPTO_PROVIDER) CRYPT_EAL_MdCTX *ctx = NULL; CRYPT_EAL_LibCtx *libCtx = NULL; uint8_t out[SHA2_OUTPUT_MAXSIZE]; uint32_t outLen = SHA2_OUTPUT_MAXSIZE; TestMemInit(); ASSERT_EQ(InitTwoProviders(&libCtx, path, defProName, customProName), 0); ctx = CRYPT_EAL_ProviderMdNewCtx(libCtx, CRYPT_MD_SHA256, customAttr); ASSERT_TRUE(ctx != NULL); ASSERT_EQ(CRYPT_EAL_MdInit(ctx), 0); ASSERT_EQ(CRYPT_EAL_MdUpdate(ctx, in->x, in->len), 0); ASSERT_EQ(CRYPT_EAL_MdFinal(ctx, out, &outLen), 0); ASSERT_COMPARE("other provider sha256", out, outLen, digest->x, digest->len); EXIT: CRYPT_EAL_MdFreeCtx(ctx); CRYPT_EAL_LibCtxFree(libCtx); #else NoUsedParam(path, defProName, customProName, NULL, customAttr); (void)in; (void)digest; SKIP_TEST(); #endif } /* END_CASE */ /** * @test SDV_PROVIDER_HMAC_TC001 * @title HMAC test */ /* BEGIN_CASE */ void SDV_PROVIDER_HMAC_TC001(char *path, char *defProName, char *customProName, char *defAttr, char *customAttr, int algId, Hex *key, Hex *data, Hex *vecMac) { #if defined(HITLS_CRYPTO_HMAC) && defined(HITLS_CRYPTO_PROVIDER) uint8_t *out = NULL; uint32_t outLen = vecMac->len; CRYPT_EAL_MacCtx *ctx = NULL; CRYPT_EAL_LibCtx *libCtx = NULL; BSL_Param params[] = {{0}, BSL_PARAM_END}; // Set 1 parameter for hmac TestMemInit(); ASSERT_EQ(InitTwoProviders(&libCtx, path, defProName, customProName), 0); out = (uint8_t *)BSL_SAL_Malloc(outLen); ASSERT_TRUE(out != NULL); // HMAC-SHA256: hmac from default provider, sha256 from custom provider ctx = CRYPT_EAL_ProviderMacNewCtx(libCtx, algId, strlen(defAttr) == 0 ? NULL : defAttr); ASSERT_TRUE(ctx != NULL); ASSERT_EQ(BSL_PARAM_InitValue(&params[0], CRYPT_PARAM_MD_ATTR, BSL_PARAM_TYPE_UTF8_STR, customAttr, strlen(customAttr)), 0); ASSERT_EQ(CRYPT_EAL_MacSetParam(ctx, params), 0); ASSERT_EQ(CRYPT_EAL_MacInit(ctx, key->x, key->len), 0); ASSERT_EQ(CRYPT_EAL_MacUpdate(ctx, data->x, data->len), 0); ASSERT_EQ(CRYPT_EAL_MacFinal(ctx, out, &outLen), 0); ASSERT_COMPARE("default hmac other sha256", out, outLen, vecMac->x, vecMac->len); EXIT: CRYPT_EAL_MacFreeCtx(ctx); CRYPT_EAL_LibCtxFree(libCtx); BSL_SAL_Free(out); #else NoUsedParam(path, defProName, customProName, defAttr, customAttr); (void)algId; (void)key; (void)data; (void)vecMac; SKIP_TEST(); #endif } /* END_CASE */ /** * @test SDV_PROVIDER_HKDF_TC001 * @title hkdf-hmac-sha256 provider test, hkdf-hmac from default provider, sha256 from provider1 or provider2 */ /* BEGIN_CASE */ void SDV_PROVIDER_HKDF_TC001(char *path, char *defProName, char *customProName, char *defAttr, char *customAttr, int macId, Hex *key, Hex *salt, Hex *info, Hex *result) { #if defined(HITLS_CRYPTO_HKDF) && defined(HITLS_CRYPTO_PROVIDER) uint8_t *out = NULL; uint32_t outLen = result->len; CRYPT_EAL_LibCtx *libCtx = NULL; CRYPT_EAL_KdfCTX *ctx = NULL; BSL_Param params[7] = {{0}, {0}, {0}, {0}, {0}, {0}, BSL_PARAM_END}; // Set 6 parameters for hkdf CRYPT_HKDF_MODE mode = CRYPT_KDF_HKDF_MODE_FULL; TestMemInit(); ASSERT_EQ(InitTwoProviders(&libCtx, path, defProName, customProName), 0); out = (uint8_t *)BSL_SAL_Malloc(outLen); ASSERT_TRUE(out != NULL); ASSERT_EQ(BSL_PARAM_InitValue(&params[0], CRYPT_PARAM_KDF_MAC_ID, BSL_PARAM_TYPE_UINT32, &macId, sizeof(macId)), 0); ASSERT_EQ(BSL_PARAM_InitValue(&params[1], CRYPT_PARAM_KDF_MODE, BSL_PARAM_TYPE_UINT32, &mode, sizeof(mode)), 0); ASSERT_EQ(BSL_PARAM_InitValue(&params[2], CRYPT_PARAM_KDF_KEY, BSL_PARAM_TYPE_OCTETS, key->x, key->len), 0); ASSERT_EQ(BSL_PARAM_InitValue(&params[3], CRYPT_PARAM_KDF_SALT, BSL_PARAM_TYPE_OCTETS, salt->x, salt->len), 0); ASSERT_EQ(BSL_PARAM_InitValue(&params[4], CRYPT_PARAM_KDF_INFO, BSL_PARAM_TYPE_OCTETS, info->x, info->len), 0); ASSERT_EQ(BSL_PARAM_InitValue(&params[5], CRYPT_PARAM_MD_ATTR, BSL_PARAM_TYPE_UTF8_STR, customAttr, strlen(customAttr)), 0); // HMAC-SHA256: hmac from default provider, sha256 from custom provider ctx = CRYPT_EAL_ProviderKdfNewCtx(libCtx, CRYPT_KDF_HKDF, strlen(defAttr) == 0 ? NULL : defAttr); ASSERT_TRUE(ctx != NULL); // sha256 form provider2 ASSERT_EQ(CRYPT_EAL_KdfSetParam(ctx, params), 0); ASSERT_EQ(CRYPT_EAL_KdfDerive(ctx, out, outLen), 0); ASSERT_COMPARE("default hkdf-hmac other sha256", out, outLen, result->x, result->len); EXIT: CRYPT_EAL_KdfFreeCtx(ctx); CRYPT_EAL_LibCtxFree(libCtx); BSL_SAL_Free(out); #else NoUsedParam(path, defProName, customProName, defAttr, customAttr); (void)macId; (void)key; (void)salt; (void)info; (void)result; SKIP_TEST(); #endif } /* END_CASE */ /** * @test SDV_PROVIDER_PBKDF2_TC001 * @title pbkdf2-hmac-sha256 provider test, pbkdf2 from default provider, sha256 from provider1 or provider2 */ /* BEGIN_CASE */ void SDV_PROVIDER_PBKDF2_TC001(char *path, char *defProName, char *customProName, char *defAttr, char *customAttr, int macId, Hex *key, Hex *salt, int it, Hex *result) { #if defined(HITLS_CRYPTO_PBKDF2) && defined(HITLS_CRYPTO_PROVIDER) uint8_t *out = NULL; uint32_t outLen = result->len; CRYPT_EAL_LibCtx *libCtx = NULL; CRYPT_EAL_KdfCTX *ctx = NULL; BSL_Param params[6] = {{0}, {0}, {0}, {0}, {0}, BSL_PARAM_END}; // Set 5 parameters for pbkdf2 TestMemInit(); ASSERT_EQ(InitTwoProviders(&libCtx, path, defProName, customProName), 0); out = (uint8_t *)BSL_SAL_Malloc(outLen); ASSERT_TRUE(out != NULL); ASSERT_EQ(BSL_PARAM_InitValue(&params[0], CRYPT_PARAM_KDF_MAC_ID, BSL_PARAM_TYPE_UINT32, &macId, sizeof(macId)), 0); ASSERT_EQ(BSL_PARAM_InitValue(&params[1], CRYPT_PARAM_KDF_PASSWORD, BSL_PARAM_TYPE_OCTETS, key->x, key->len), 0); ASSERT_EQ(BSL_PARAM_InitValue(&params[2], CRYPT_PARAM_KDF_SALT, BSL_PARAM_TYPE_OCTETS, salt->x, salt->len), 0); ASSERT_EQ(BSL_PARAM_InitValue(&params[3], CRYPT_PARAM_KDF_ITER, BSL_PARAM_TYPE_UINT32, &it, sizeof(it)), 0); ASSERT_EQ(BSL_PARAM_InitValue(&params[4], CRYPT_PARAM_MD_ATTR, BSL_PARAM_TYPE_UTF8_STR, customAttr, strlen(customAttr)), 0); // provider1: pbkdf2, provider2: sha256 ctx = CRYPT_EAL_ProviderKdfNewCtx(libCtx, CRYPT_KDF_PBKDF2, strlen(defAttr) == 0 ? NULL : defAttr); ASSERT_TRUE(ctx != NULL); // sha256 form provider2 ASSERT_EQ(CRYPT_EAL_KdfSetParam(ctx, params), 0); ASSERT_EQ(CRYPT_EAL_KdfDerive(ctx, out, outLen), 0); ASSERT_COMPARE("default pbkdf2 other sha256", out, outLen, result->x, result->len); EXIT: CRYPT_EAL_KdfFreeCtx(ctx); CRYPT_EAL_LibCtxFree(libCtx); BSL_SAL_Free(out); #else NoUsedParam(path, defProName, customProName, defAttr, customAttr); (void)macId; (void)key; (void)salt; (void)it; (void)result; SKIP_TEST(); #endif } /* END_CASE */ /** * @test SDV_PROVIDER_KDFTLS12_TC001 * @title kdftls12-hmac-sha256 provider test, kdftls12 from default provider, sha256 from provider1 or provider2 */ /* BEGIN_CASE */ void SDV_PROVIDER_KDFTLS12_TC001(char *path, char *defProName, char *customProName, char *defAttr, char *customAttr, int macId, Hex *key, Hex *label, Hex *seed, Hex *result) { #if defined(HITLS_CRYPTO_KDFTLS12) && defined(HITLS_CRYPTO_PROVIDER) uint8_t *out = NULL; uint32_t outLen = result->len; CRYPT_EAL_LibCtx *libCtx = NULL; CRYPT_EAL_KdfCTX *ctx = NULL; BSL_Param params[6] = {{0}, {0}, {0}, {0}, {0}, BSL_PARAM_END}; // Set 5 parameters for kdftls12 TestMemInit(); ASSERT_EQ(InitTwoProviders(&libCtx, path, defProName, customProName), 0); out = (uint8_t *)BSL_SAL_Malloc(outLen); ASSERT_TRUE(out != NULL); ASSERT_EQ(BSL_PARAM_InitValue(&params[0], CRYPT_PARAM_KDF_MAC_ID, BSL_PARAM_TYPE_UINT32, &macId, sizeof(macId)), 0); ASSERT_EQ(BSL_PARAM_InitValue(&params[1], CRYPT_PARAM_KDF_KEY, BSL_PARAM_TYPE_OCTETS, key->x, key->len), 0); ASSERT_EQ(BSL_PARAM_InitValue(&params[2], CRYPT_PARAM_KDF_LABEL, BSL_PARAM_TYPE_OCTETS, label->x, label->len), 0); ASSERT_EQ(BSL_PARAM_InitValue(&params[3], CRYPT_PARAM_KDF_SEED, BSL_PARAM_TYPE_OCTETS, seed->x, seed->len), 0); ASSERT_EQ(BSL_PARAM_InitValue(&params[4], CRYPT_PARAM_MD_ATTR, BSL_PARAM_TYPE_UTF8_STR, customAttr, strlen(customAttr)), 0); // provider1: kdftls12, provider2: sha256 ctx = CRYPT_EAL_ProviderKdfNewCtx(libCtx, CRYPT_KDF_KDFTLS12, strlen(defAttr) == 0 ? NULL : defAttr); ASSERT_TRUE(ctx != NULL); // sha256 form provider2 ASSERT_EQ(CRYPT_EAL_KdfSetParam(ctx, params), 0); ASSERT_EQ(CRYPT_EAL_KdfDerive(ctx, out, outLen), 0); ASSERT_COMPARE("default kdftls12 other sha256", out, outLen, result->x, result->len); EXIT: CRYPT_EAL_KdfFreeCtx(ctx); CRYPT_EAL_LibCtxFree(libCtx); BSL_SAL_Free(out); #else NoUsedParam(path, defProName, customProName, defAttr, customAttr); (void)macId; (void)key; (void)label; (void)seed; (void)result; SKIP_TEST(); #endif } /* END_CASE */ /** * @test SDV_CRYPTO_PROVIDER_RSA_SIGN_TC001 * @title rsa-sign provider test, rsa-sign from default provider, sha256 from provider1 or provider2 */ /* BEGIN_CASE */ void SDV_PROVIDER_RSA_SIGN_VERIFY_PKCSV15_TC001(char *path, char *defProName, char *customProName, char *defAttr, char *customAttr, int mdId, Hex *n, Hex *e, Hex *d, Hex *msg) { #if defined(HITLS_CRYPTO_RSA_SIGN) && defined(HITLS_CRYPTO_RSA_EMSA_PKCSV15) && defined(HITLS_CRYPTO_PROVIDER) CRYPT_EAL_LibCtx *libCtx = NULL; CRYPT_EAL_PkeyCtx *ctx = NULL; uint8_t sign[MAX_CIPHERTEXT_LEN] = {0}; uint32_t signLen = MAX_CIPHERTEXT_LEN; CRYPT_EAL_PkeyPrv prvKey = {.id = CRYPT_PKEY_RSA, .key.rsaPrv.n = n->x, .key.rsaPrv.nLen = n->len, .key.rsaPrv.d = d->x, .key.rsaPrv.dLen = d->len}; CRYPT_EAL_PkeyPub pubKey = {.id = CRYPT_PKEY_RSA, .key.rsaPub.n = n->x, .key.rsaPub.nLen = n->len, .key.rsaPub.e = e->x, .key.rsaPub.eLen = e->len}; BSL_Param params[2] = {{0}, BSL_PARAM_END}; // Set 1 parameter for hmac TestMemInit(); ASSERT_EQ(InitTwoProviders(&libCtx, path, defProName, customProName), 0); ASSERT_EQ(TestRandInitEx(libCtx), 0); // rsa-sign-verify-pkcsv15 from default provider, sha256 from custom provider ctx = CRYPT_EAL_ProviderPkeyNewCtx(libCtx, CRYPT_PKEY_RSA, CRYPT_EAL_PKEY_SIGN_OPERATE, strlen(defAttr) == 0 ? NULL : defAttr); ASSERT_TRUE(ctx != NULL); ASSERT_EQ(CRYPT_EAL_PkeySetPub(ctx, &pubKey), 0); ASSERT_EQ(CRYPT_EAL_PkeySetPrv(ctx, &prvKey), 0); ASSERT_EQ(BSL_PARAM_InitValue(&params[0], CRYPT_PARAM_MD_ATTR, BSL_PARAM_TYPE_UTF8_STR, customAttr, strlen(customAttr)), 0); ASSERT_EQ(CRYPT_EAL_PkeySetParaEx(ctx, params), 0); ASSERT_EQ(CRYPT_EAL_PkeyCtrl(ctx, CRYPT_CTRL_SET_RSA_EMSA_PKCSV15, &mdId, sizeof(mdId)), 0); signLen = MAX_CIPHERTEXT_LEN; ASSERT_EQ(CRYPT_EAL_PkeySign(ctx, mdId, msg->x, msg->len, sign, &signLen), 0); ASSERT_EQ(CRYPT_EAL_PkeyVerify(ctx, mdId, msg->x, msg->len, sign, signLen), 0); EXIT: CRYPT_EAL_PkeyFreeCtx(ctx); CRYPT_EAL_LibCtxFree(libCtx); CRYPT_EAL_RandDeinit(); #else NoUsedParam(path, defProName, customProName, defAttr, customAttr); (void)mdId; (void)n; (void)e; (void)d; (void)msg; SKIP_TEST(); #endif } /* END_CASE */ /** * @test SDV_CRYPTO_PROVIDER_RSA_SIGN_VERIFY_PSS_TC001 * @title rsa-sign-verify-pss provider test, rsa-sign-verify-pss from default provider */ /* BEGIN_CASE */ void SDV_PROVIDER_RSA_SIGN_VERIFY_PSS_TC001(char *path, char *defProName, char *customProName, char *defAttr, char *customAttr, int mdId, Hex *n, Hex *e, Hex *d, Hex *msg, int saltLen) { #if defined(HITLS_CRYPTO_RSA_SIGN) && defined(HITLS_CRYPTO_RSA_EMSA_PSS) && defined(HITLS_CRYPTO_PROVIDER) CRYPT_EAL_LibCtx *libCtx = NULL; CRYPT_EAL_PkeyCtx *ctx = NULL; CRYPT_EAL_PkeyPrv prvKey = {.id = CRYPT_PKEY_RSA, .key.rsaPrv.n = n->x, .key.rsaPrv.nLen = n->len, .key.rsaPrv.d = d->x, .key.rsaPrv.dLen = d->len}; CRYPT_EAL_PkeyPub pubKey = {.id = CRYPT_PKEY_RSA, .key.rsaPub.n = n->x, .key.rsaPub.nLen = n->len, .key.rsaPub.e = e->x, .key.rsaPub.eLen = e->len}; uint8_t sign[MAX_CIPHERTEXT_LEN] = {0}; uint32_t signLen = MAX_CIPHERTEXT_LEN; BSL_Param pssParam[4] = { {CRYPT_PARAM_RSA_MD_ID, BSL_PARAM_TYPE_INT32, &mdId, sizeof(mdId), 0}, {CRYPT_PARAM_RSA_MGF1_ID, BSL_PARAM_TYPE_INT32, &mdId, sizeof(mdId), 0}, {CRYPT_PARAM_RSA_SALTLEN, BSL_PARAM_TYPE_INT32, &saltLen, sizeof(saltLen), 0}, BSL_PARAM_END}; BSL_Param params[2] = {{0}, BSL_PARAM_END}; // Set 1 parameter for RSA TestMemInit(); ASSERT_EQ(InitTwoProviders(&libCtx, path, defProName, customProName), 0); ASSERT_EQ(TestRandInitEx(libCtx), 0); // rsa-sign-verify-pss from default provider, sha256 from custom provider ctx = CRYPT_EAL_ProviderPkeyNewCtx(libCtx, CRYPT_PKEY_RSA, CRYPT_EAL_PKEY_SIGN_OPERATE, strlen(defAttr) == 0 ? NULL : defAttr); ASSERT_TRUE(ctx != NULL); ASSERT_EQ(CRYPT_EAL_PkeySetPub(ctx, &pubKey), 0); ASSERT_EQ(CRYPT_EAL_PkeySetPrv(ctx, &prvKey), 0); ASSERT_EQ(CRYPT_EAL_PkeyCtrl(ctx, CRYPT_CTRL_SET_RSA_EMSA_PSS, &pssParam, 0), 0); ASSERT_EQ(BSL_PARAM_InitValue(&params[0], CRYPT_PARAM_MD_ATTR, BSL_PARAM_TYPE_UTF8_STR, customAttr, strlen(customAttr)), 0); ASSERT_EQ(CRYPT_EAL_PkeySetParaEx(ctx, params), 0); signLen = MAX_CIPHERTEXT_LEN; ASSERT_EQ(CRYPT_EAL_PkeySign(ctx, mdId, msg->x, msg->len, sign, &signLen), 0); ASSERT_EQ(CRYPT_EAL_PkeyVerify(ctx, mdId, msg->x, msg->len, sign, signLen), 0); EXIT: CRYPT_EAL_PkeyFreeCtx(ctx); CRYPT_EAL_LibCtxFree(libCtx); CRYPT_EAL_RandDeinit(); #else NoUsedParam(path, defProName, customProName, defAttr, customAttr); (void)mdId; (void)n; (void)e; (void)d; (void)msg; (void)saltLen; SKIP_TEST(); #endif } /* END_CASE */ /** * @test SDV_CRYPTO_PROVIDER_RSA_RSABSSA_BLINDING_TC001 * @title rsa-rsabssa-blinding provider test, rsa-rsabssa-blinding from default provider */ /* BEGIN_CASE */ void SDV_PROVIDER_RSA_RSABSSA_BLINDING_TC001(char *path, char *defProName, char *customProName, char *defAttr, char *customAttr, int mdId, Hex *n, Hex *e, Hex *d, Hex *msg, int saltLen) { #if defined(HITLS_CRYPTO_RSA_SIGN) && defined(HITLS_CRYPTO_RSA_BSSA) && defined(HITLS_CRYPTO_PROVIDER) CRYPT_EAL_LibCtx *libCtx = NULL; CRYPT_EAL_PkeyCtx *ctx = NULL; CRYPT_EAL_PkeyPrv prvKey = {.id = CRYPT_PKEY_RSA, .key.rsaPrv.n = n->x, .key.rsaPrv.nLen = n->len, .key.rsaPrv.d = d->x, .key.rsaPrv.dLen = d->len}; CRYPT_EAL_PkeyPub pubKey = {.id = CRYPT_PKEY_RSA, .key.rsaPub.n = n->x, .key.rsaPub.nLen = n->len, .key.rsaPub.e = e->x, .key.rsaPub.eLen = e->len}; #ifdef HITLS_CRYPTO_RSA_SIGN uint8_t blindMsg[MAX_CIPHERTEXT_LEN] = {0}; uint32_t blindMsgLen = MAX_CIPHERTEXT_LEN; #endif #ifdef HITLS_CRYPTO_RSA_VERIFY uint8_t unBlindSig[MAX_CIPHERTEXT_LEN] = {0}; uint32_t unBlindSigLen = MAX_CIPHERTEXT_LEN; #endif uint32_t flag = CRYPT_RSA_BSSA; uint8_t sign[MAX_CIPHERTEXT_LEN] = {0}; uint32_t signLen = MAX_CIPHERTEXT_LEN; BSL_Param pssParam[4] = { {CRYPT_PARAM_RSA_MD_ID, BSL_PARAM_TYPE_INT32, &mdId, sizeof(mdId), 0}, {CRYPT_PARAM_RSA_MGF1_ID, BSL_PARAM_TYPE_INT32, &mdId, sizeof(mdId), 0}, {CRYPT_PARAM_RSA_SALTLEN, BSL_PARAM_TYPE_INT32, &saltLen, sizeof(saltLen), 0}, BSL_PARAM_END}; BSL_Param params[2] = {{0}, BSL_PARAM_END}; // Set 1 parameter for RSA TestMemInit(); ASSERT_EQ(InitTwoProviders(&libCtx, path, defProName, customProName), 0); ASSERT_EQ(TestRandInitEx(libCtx), 0); // rsa-rsabssa-blinding from default provider, sha256 from custom provider ctx = CRYPT_EAL_ProviderPkeyNewCtx(libCtx, CRYPT_PKEY_RSA, CRYPT_EAL_PKEY_SIGN_OPERATE, strlen(defAttr) == 0 ? NULL : defAttr); ASSERT_TRUE(ctx != NULL); ASSERT_EQ(CRYPT_EAL_PkeySetPub(ctx, &pubKey), 0); ASSERT_EQ(CRYPT_EAL_PkeySetPrv(ctx, &prvKey), 0); ASSERT_EQ(CRYPT_EAL_PkeyCtrl(ctx, CRYPT_CTRL_SET_RSA_EMSA_PSS, &pssParam, 0), 0); ASSERT_EQ(BSL_PARAM_InitValue(&params[0], CRYPT_PARAM_MD_ATTR, BSL_PARAM_TYPE_UTF8_STR, customAttr, strlen(customAttr)), 0); ASSERT_EQ(CRYPT_EAL_PkeySetParaEx(ctx, params), 0); ASSERT_EQ(CRYPT_EAL_PkeyCtrl(ctx, CRYPT_CTRL_SET_RSA_FLAG, (void *)&flag, sizeof(uint32_t)), 0); #ifdef HITLS_CRYPTO_RSA_SIGN ASSERT_EQ(CRYPT_EAL_PkeyBlind(ctx, mdId, msg->x, msg->len, blindMsg, &blindMsgLen), 0); ASSERT_EQ(CRYPT_EAL_PkeySignData(ctx, blindMsg, blindMsgLen, sign, &signLen), 0); #endif #ifdef HITLS_CRYPTO_RSA_VERIFY ASSERT_EQ(CRYPT_EAL_PkeyUnBlind(ctx, sign, signLen, unBlindSig, &unBlindSigLen), 0); ASSERT_EQ(CRYPT_EAL_PkeyVerify(ctx, mdId, msg->x, msg->len, unBlindSig, unBlindSigLen), 0); #endif EXIT: CRYPT_EAL_PkeyFreeCtx(ctx); CRYPT_EAL_LibCtxFree(libCtx); CRYPT_EAL_RandDeinit(); #else NoUsedParam(path, defProName, customProName, defAttr, customAttr); (void)mdId; (void)n; (void)e; (void)d; (void)msg; (void)saltLen; SKIP_TEST(); #endif } /* END_CASE */ /* BEGIN_CASE */ void SDV_PROVIDER_RSA_CRYPT_FUNC_TC001(char *path, char *defProName, char *customProName, char *defAttr, char *customAttr, int padMode, int mdId, Hex *n, Hex *e, Hex *d, Hex *plaintext) { #if defined(HITLS_CRYPTO_RSA_DECRYPT) && defined(HITLS_CRYPTO_RSA_ENCRYPT) && defined(HITLS_CRYPTO_PROVIDER) CRYPT_EAL_LibCtx *libCtx = NULL; CRYPT_EAL_PkeyPrv prvkey = {.id = CRYPT_PKEY_RSA, .key.rsaPrv.n = n->x, .key.rsaPrv.nLen = n->len, .key.rsaPrv.d = d->x, .key.rsaPrv.dLen = d->len}; CRYPT_EAL_PkeyPub pubkey = {.id = CRYPT_PKEY_RSA, .key.rsaPub.n = n->x, .key.rsaPub.nLen = n->len, .key.rsaPub.e = e->x, .key.rsaPub.eLen = e->len}; CRYPT_EAL_PkeyCtx *ctx = NULL; BSL_Param oaepParam[3] = { {CRYPT_PARAM_RSA_MD_ID, BSL_PARAM_TYPE_INT32, &mdId, sizeof(mdId), 0}, {CRYPT_PARAM_RSA_MGF1_ID, BSL_PARAM_TYPE_INT32, &mdId, sizeof(mdId), 0}, BSL_PARAM_END}; int32_t pkcsv15 = mdId; uint8_t pt[MAX_CIPHERTEXT_LEN] = {0}; uint32_t ptLen = MAX_CIPHERTEXT_LEN; uint8_t ct[MAX_CIPHERTEXT_LEN] = {0}; uint32_t ctLen = MAX_CIPHERTEXT_LEN; int paraSize; void *paraPtr; BSL_Param params[2] = {{0}, BSL_PARAM_END}; // Set 1 parameter for RSA if (padMode == CRYPT_CTRL_SET_RSA_RSAES_OAEP) { paraSize = 0; paraPtr = oaepParam; } else if (padMode == CRYPT_CTRL_SET_RSA_RSAES_PKCSV15) { paraSize = sizeof(pkcsv15); paraPtr = &pkcsv15; } TestMemInit(); ASSERT_EQ(InitTwoProviders(&libCtx, path, defProName, customProName), 0); ASSERT_EQ(TestRandInitEx(libCtx), 0); ctx = CRYPT_EAL_ProviderPkeyNewCtx(libCtx, CRYPT_PKEY_RSA, CRYPT_EAL_PKEY_CIPHER_OPERATE, strlen(defAttr) == 0 ? NULL : defAttr); ASSERT_TRUE(ctx != NULL); ASSERT_EQ(CRYPT_EAL_PkeySetPrv(ctx, &prvkey), 0); ASSERT_EQ(CRYPT_EAL_PkeySetPub(ctx, &pubkey), 0); ASSERT_EQ(CRYPT_EAL_PkeyCtrl(ctx, padMode, paraPtr, paraSize), 0); ASSERT_EQ(BSL_PARAM_InitValue(&params[0], CRYPT_PARAM_MD_ATTR, BSL_PARAM_TYPE_UTF8_STR, customAttr, strlen(customAttr)), 0); ASSERT_EQ(CRYPT_EAL_PkeySetParaEx(ctx, params), 0); ASSERT_EQ(CRYPT_EAL_PkeyEncrypt(ctx, plaintext->x, plaintext->len, ct, &ctLen), 0); ASSERT_EQ(CRYPT_EAL_PkeyDecrypt(ctx, ct, ctLen, pt, &ptLen), 0); ASSERT_EQ(ptLen, plaintext->len); ASSERT_COMPARE("rsa encrypt and decrypt", pt, ptLen, plaintext->x, plaintext->len); EXIT: CRYPT_EAL_PkeyFreeCtx(ctx); CRYPT_EAL_LibCtxFree(libCtx); CRYPT_EAL_RandDeinit(); #else NoUsedParam(path, defProName, customProName, defAttr, customAttr); (void)padMode; (void)mdId; (void)n; (void)e; (void)d; (void)plaintext; SKIP_TEST(); #endif } /* END_CASE */
2301_79861745/bench_create
testcode/sdv/testcase/crypto/provider/test_suite_sdv_eal_multi_provider.c
C
unknown
22,400
/* * This file is part of the openHiTLS project. * * openHiTLS is licensed under the Mulan PSL v2. * You can use this software according to the terms and conditions of the Mulan PSL v2. * You may obtain a copy of Mulan PSL v2 at: * * http://license.coscl.org.cn/MulanPSL2 * * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, * EITHER EXPRESS 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 "securec.h" #include "bsl_sal.h" #include "crypt_errno.h" #include "crypt_eal_init.h" #include "crypt_eal_provider.h" #include "crypt_provider_local.h" #include "crypt_eal_implprovider.h" #include "crypt_provider.h" #include "crypt_eal_mac.h" #include "eal_mac_local.h" #include "crypt_eal_kdf.h" #include "eal_kdf_local.h" #include "crypt_eal_md.h" #include "eal_md_local.h" #include "crypt_eal_pkey.h" #include "eal_pkey_local.h" #include "test.h" #include "crypt_errno.h" #include "bsl_sal.h" #include "bsl_list.h" #include "bsl_errno.h" #include "crypt_eal_md.h" #include "hitls_crypt_type.h" #include "hitls_cert_type.h" #include "hitls_type.h" /* END_HEADER */ #define PROVIDER_LOAD_SAIZE_2 2 #define PATH_EXCEED 4097 #define NEW_PARA_ALGID (BSL_CID_MAX + 1) #define NEW_PKEY_ALGID (BSL_CID_MAX + 2) #define NEW_SIGN_HASH_ALGID (BSL_CID_MAX + 3) #define NEW_HASH_ALGID (BSL_CID_MAX + 4) /** * @test SDV_CRYPTO_PROVIDER_LOAD_FUNC_TC001 * @title Provider load and unload functionality test * @precon None */ /* BEGIN_CASE */ void SDV_CRYPTO_PROVIDER_LOAD_TC001(char *path, char *path2, char *test1, char *test2, char *testNoInit, char *testNoFullfunc, int cmd, int cmd2) { #ifndef HITLS_CRYPTO_PROVIDER (void)path; (void)path2; (void)test1; (void)test2; (void)testNoInit; (void)testNoFullfunc; (void)cmd; (void)cmd2; SKIP_TEST(); #else CRYPT_EAL_LibCtx *libCtx = NULL; // Test CRYPT_EAL_LibCtxNew libCtx = CRYPT_EAL_LibCtxNew(); ASSERT_TRUE(libCtx != NULL); // Test CRYPT_EAL_ProviderSetLoadPath ASSERT_EQ(CRYPT_EAL_ProviderSetLoadPath(libCtx, path), CRYPT_SUCCESS); // Test CRYPT_EAL_ProviderLoad ASSERT_EQ(CRYPT_EAL_ProviderLoad(libCtx, cmd, test1, NULL, NULL), CRYPT_SUCCESS); // Test CRYPT_EAL_ProviderLoad ASSERT_EQ(CRYPT_EAL_ProviderLoad(libCtx, BSL_SAL_LIB_FMT_OFF, "default", NULL, NULL), CRYPT_SUCCESS); // Test CRYPT_EAL_ProviderLoad ASSERT_EQ(CRYPT_EAL_ProviderLoad(libCtx, BSL_SAL_LIB_FMT_OFF, "default", NULL, NULL), CRYPT_SUCCESS); // Test loading the same provider consecutively ASSERT_EQ(CRYPT_EAL_ProviderLoad(libCtx, cmd, test1, NULL, NULL), CRYPT_SUCCESS); // Verify only one EAL_ProviderMgrCtx structure for this provider in the providers list,and ref == 2 ASSERT_EQ(BSL_LIST_COUNT(libCtx->providers), 2); CRYPT_EAL_ProvMgrCtx *providerMgr = (CRYPT_EAL_ProvMgrCtx *)BSL_LIST_FIRST_ELMT(libCtx->providers); ASSERT_TRUE(providerMgr != NULL); ASSERT_EQ(providerMgr->ref.count, PROVIDER_LOAD_SAIZE_2); providerMgr = (CRYPT_EAL_ProvMgrCtx *)BSL_LIST_LAST_ELMT(libCtx->providers); ASSERT_TRUE(providerMgr != NULL); ASSERT_EQ(providerMgr->ref.count, PROVIDER_LOAD_SAIZE_2); // Test if loading the same name with different cmd is successful and not recognized as the same provider ASSERT_EQ(CRYPT_EAL_ProviderLoad(libCtx, cmd2, test1, NULL, NULL), CRYPT_SUCCESS); ASSERT_EQ(providerMgr->ref.count, PROVIDER_LOAD_SAIZE_2); // Test if loading the same provider name with the same cmd from different paths is successful // and will recognized as the same provider。 ASSERT_EQ(CRYPT_EAL_ProviderSetLoadPath(libCtx, path2), CRYPT_SUCCESS); ASSERT_EQ(CRYPT_EAL_ProviderLoad(libCtx, cmd, test1, NULL, NULL), CRYPT_SUCCESS); providerMgr = (CRYPT_EAL_ProvMgrCtx *)BSL_LIST_FIRST_ELMT(libCtx->providers); ASSERT_TRUE(providerMgr != NULL); ASSERT_EQ(providerMgr->ref.count, PROVIDER_LOAD_SAIZE_2 + 1); ASSERT_EQ(CRYPT_EAL_ProviderSetLoadPath(libCtx, path), CRYPT_SUCCESS); ASSERT_EQ(CRYPT_EAL_ProviderLoad(libCtx, cmd, test2, NULL, NULL), CRYPT_SUCCESS); // Test loading a non-existent provider ASSERT_EQ(CRYPT_EAL_ProviderLoad(libCtx, cmd, "non_existent_provider", NULL, NULL), BSL_SAL_ERR_DL_NOT_FOUND); // Test loading a provider without initialization function ASSERT_EQ(CRYPT_EAL_ProviderLoad(libCtx, cmd, testNoInit, NULL, NULL), BSL_SAL_ERR_DL_NON_FUNCTION); // Test loading a provider without complete return methods ASSERT_EQ(CRYPT_EAL_ProviderLoad(libCtx, cmd, testNoFullfunc, NULL, NULL), CRYPT_PROVIDER_ERR_UNEXPECTED_IMPL); ASSERT_EQ(CRYPT_EAL_ProviderUnload(libCtx, cmd, test2), CRYPT_SUCCESS); ASSERT_EQ(CRYPT_EAL_ProviderSetLoadPath(libCtx, NULL), CRYPT_SUCCESS); ASSERT_EQ(CRYPT_EAL_ProviderLoad(libCtx, cmd, test2, NULL, NULL), CRYPT_SUCCESS); // Test CRYPT_EAL_ProviderUnload ASSERT_EQ(CRYPT_EAL_ProviderUnload(libCtx, cmd, test1), CRYPT_SUCCESS); ASSERT_EQ(CRYPT_EAL_ProviderUnload(libCtx, cmd, test1), CRYPT_SUCCESS); ASSERT_EQ(CRYPT_EAL_ProviderUnload(libCtx, cmd, test1), CRYPT_SUCCESS); ASSERT_EQ(CRYPT_EAL_ProviderUnload(libCtx, cmd, test2), CRYPT_SUCCESS); // Test unloading a non-existent provider ASSERT_EQ(CRYPT_EAL_ProviderUnload(libCtx, cmd, "non_existent_provider"), CRYPT_SUCCESS); EXIT: if (libCtx != NULL) { CRYPT_EAL_LibCtxFree(libCtx); } return; #endif } /* END_CASE */ /** * @test SDV_CRYPTO_PROVIDER_LOAD_FUNC_TC002 * @title Test if an error occurs when the length of the set path exceeds * @precon None * @brief * 1. Test if an error is reported when the path length exceeds the maximum length in Linux. * @expect * 1. CRYPT_INVALID_ARG * @prior Level 1 * @auto TRUE */ /* BEGIN_CASE */ void SDV_CRYPTO_PROVIDER_LOAD_TC002(void) { #ifndef HITLS_CRYPTO_PROVIDER SKIP_TEST(); #else CRYPT_EAL_LibCtx *libCtx = NULL; int32_t ret; libCtx = CRYPT_EAL_LibCtxNew(); ASSERT_TRUE(libCtx != NULL); // Test if an error is reported when the path length exceeds the maximum length in Linux char *overpath = (char *)BSL_SAL_Calloc(1, PATH_EXCEED); ASSERT_TRUE(overpath != NULL); ret = memset_s(overpath, PATH_EXCEED, 'a', PATH_EXCEED - 1); ASSERT_EQ(ret, 0); ret = CRYPT_EAL_ProviderSetLoadPath(libCtx, overpath); ASSERT_EQ(ret, CRYPT_INVALID_ARG); BSL_SAL_Free(overpath); EXIT: if (libCtx != NULL) { CRYPT_EAL_LibCtxFree(libCtx); } return; #endif } /* END_CASE */ #define RIGHT_RESULT 1415926 /** * @test SDV_CRYPTO_PROVIDER_LOAD_TC003 * @title Test load provider into global libctx * @precon None * @prior Level 1 * @auto TRUE */ /* BEGIN_CASE */ void SDV_CRYPTO_PROVIDER_LOAD_TC003(char *path, int cmd, char *test1, char *attrName) { #ifndef HITLS_CRYPTO_PROVIDER (void)path; (void)cmd; (void)test1; (void)attrName; SKIP_TEST(); #else CRYPT_EAL_MdCTX *mdCtx = NULL; ASSERT_EQ(CRYPT_EAL_ProviderSetLoadPath(NULL, path), CRYPT_SUCCESS); ASSERT_EQ(CRYPT_EAL_ProviderLoad(NULL, cmd, test1, NULL, NULL), CRYPT_SUCCESS); ASSERT_EQ(CRYPT_EAL_ProviderUnload(NULL, cmd, test1), CRYPT_SUCCESS); CRYPT_EAL_Cleanup(1); ASSERT_EQ(CRYPT_EAL_ProviderLoad(NULL, cmd, test1, NULL, NULL), CRYPT_PROVIDER_INVALID_LIB_CTX); ASSERT_EQ(CRYPT_EAL_Init(CRYPT_EAL_INIT_CPU|CRYPT_EAL_INIT_PROVIDER|CRYPT_EAL_INIT_PROVIDER_RAND), CRYPT_SUCCESS); ASSERT_EQ(CRYPT_EAL_ProviderSetLoadPath(NULL, path), CRYPT_SUCCESS); ASSERT_EQ(CRYPT_EAL_ProviderLoad(NULL, cmd, test1, NULL, NULL), CRYPT_SUCCESS); mdCtx = CRYPT_EAL_ProviderMdNewCtx(NULL, CRYPT_MD_MD5, NULL); ASSERT_TRUE(mdCtx != NULL); ASSERT_EQ(CRYPT_EAL_MdInit(mdCtx), CRYPT_SUCCESS); CRYPT_EAL_MdFreeCtx(mdCtx); mdCtx = CRYPT_EAL_ProviderMdNewCtx(NULL, CRYPT_MD_MD5, attrName); ASSERT_TRUE(mdCtx != NULL); ASSERT_EQ(CRYPT_EAL_MdInit(mdCtx), RIGHT_RESULT); EXIT: CRYPT_EAL_MdFreeCtx(mdCtx); CRYPT_EAL_Cleanup(1); ASSERT_EQ(CRYPT_EAL_Init(CRYPT_EAL_INIT_CPU|CRYPT_EAL_INIT_PROVIDER|CRYPT_EAL_INIT_PROVIDER_RAND), CRYPT_SUCCESS); #endif } /* END_CASE */ /** * @test SDV_CRYPTO_PROVIDER_LOAD_COMPARE_TC001 * @title Test the normal scenarios of provider lookup mechanism * @precon None * @brief * 1. Test if the corresponding funcs can be found based on the attribute * @expect * 1. CRYPT_SUCCESS for loading providers and getting functions * 2. The result of mdInitCtx matches the expected result * @prior Level 1 * @auto TRUE */ /* BEGIN_CASE */ void SDV_CRYPTO_PROVIDER_LOAD_COMPARE_TC001(char *path, char *test1, char *test2, int cmd, char *attribute, int result) { #ifndef HITLS_CRYPTO_PROVIDER (void)path; (void)test1; (void)test2; (void)cmd; (void)attribute; (void)result; SKIP_TEST(); #else CRYPT_EAL_LibCtx *libCtx = NULL; int32_t ret; libCtx = CRYPT_EAL_LibCtxNew(); ASSERT_TRUE(libCtx != NULL); ret = CRYPT_EAL_ProviderSetLoadPath(libCtx, path); ASSERT_EQ(ret, CRYPT_SUCCESS); ret = CRYPT_EAL_ProviderLoad(libCtx, cmd, test1, NULL, NULL); ASSERT_EQ(ret, CRYPT_SUCCESS); ret = CRYPT_EAL_ProviderLoad(libCtx, cmd, test2, NULL, NULL); ASSERT_EQ(ret, CRYPT_SUCCESS); const CRYPT_EAL_Func *funcs; void *provCtx; // Test if the corresponding funcs can be found based on the attribute ret = CRYPT_EAL_ProviderGetFuncs(libCtx, CRYPT_EAL_OPERAID_HASH, CRYPT_MD_MD5, attribute, &funcs, &provCtx); ASSERT_EQ(ret, CRYPT_SUCCESS); ASSERT_TRUE(funcs != NULL); CRYPT_EAL_ImplMdInitCtx mdInitCtx = (CRYPT_EAL_ImplMdInitCtx)(funcs[1].func); ASSERT_TRUE(mdInitCtx != NULL); ret = mdInitCtx(provCtx, NULL); ASSERT_EQ(ret, result); ret = CRYPT_EAL_ProviderUnload(libCtx, cmd, test1); ASSERT_EQ(ret, CRYPT_SUCCESS); ret = CRYPT_EAL_ProviderUnload(libCtx, cmd, test2); ASSERT_EQ(ret, CRYPT_SUCCESS); EXIT: if (libCtx != NULL) { CRYPT_EAL_LibCtxFree(libCtx); } return; #endif } /* END_CASE */ /** * @test SDV_CRYPTO_PROVIDER_LOAD_COMPARE_TC002 * @title Test special scenarios of provider lookup mechanism * @precon None * @brief * 1. Test when attribute is NULL * 2. Test when no provider can meet the attribute requirements * 3. Test when operaid and operaid are out of range * @expect * 1. CRYPT_SUCCESS for loading providers and getting functions * 2. CRYPT_NOT_SUPPORT when no provider meets the requirements or operaid is out of range * 3. The result of mdInitCtx matches the expected result * @prior Level 1 * @auto TRUE */ /* BEGIN_CASE */ void SDV_CRYPTO_PROVIDER_LOAD_COMPARE_TC002(char *path, char *test1, char *test2, int cmd, int result) { #ifndef HITLS_CRYPTO_PROVIDER (void)path; (void)test1; (void)test2; (void)cmd; (void)result; SKIP_TEST(); #else CRYPT_EAL_LibCtx *libCtx = NULL; int32_t ret; libCtx = CRYPT_EAL_LibCtxNew(); ASSERT_TRUE(libCtx != NULL); ASSERT_EQ(CRYPT_EAL_ProviderSetLoadPath(libCtx, path), CRYPT_SUCCESS); ASSERT_EQ(CRYPT_EAL_ProviderLoad(libCtx, cmd, test1, NULL, NULL), CRYPT_SUCCESS); ASSERT_EQ(CRYPT_EAL_ProviderLoad(libCtx, cmd, test2, NULL, NULL), CRYPT_SUCCESS); const CRYPT_EAL_Func *funcs; void *provCtx; // Demonstrate normal scenario ASSERT_EQ(CRYPT_EAL_ProviderGetFuncs(libCtx, CRYPT_EAL_OPERAID_HASH, CRYPT_MD_MD5, "provider=test1", &funcs, &provCtx), CRYPT_SUCCESS); CRYPT_EAL_ImplMdInitCtx mdInitCtx = (CRYPT_EAL_ImplMdInitCtx)(funcs[1].func); ASSERT_EQ(mdInitCtx(provCtx, NULL), RIGHT_RESULT); ASSERT_EQ(CRYPT_EAL_ProviderGetFuncs(libCtx, CRYPT_EAL_OPERAID_HASH, CRYPT_MD_MD5, "provider=test1,provider!=test2", &funcs, &provCtx), CRYPT_SUCCESS); mdInitCtx = (CRYPT_EAL_ImplMdInitCtx)(funcs[1].func); ASSERT_EQ(mdInitCtx(provCtx, NULL), RIGHT_RESULT); // Test 1: Test when attribute is NULL ASSERT_EQ(CRYPT_EAL_ProviderGetFuncs(libCtx, CRYPT_EAL_OPERAID_HASH, CRYPT_MD_MD5, NULL, &funcs, &provCtx), CRYPT_SUCCESS); mdInitCtx = (CRYPT_EAL_ImplMdInitCtx)(funcs[1].func); ASSERT_EQ(mdInitCtx(provCtx, NULL), result); funcs = provCtx = NULL; // Test 2: Test when no provider can meet the attribute requirements ret = CRYPT_EAL_ProviderGetFuncs(libCtx, CRYPT_EAL_OPERAID_HASH, CRYPT_MD_MD5, "n_atr=test3", &funcs, &provCtx); ASSERT_EQ(ret, CRYPT_NOT_SUPPORT); // Test 3: Test when both operaid and operaid are out of range ret = CRYPT_EAL_ProviderGetFuncs(libCtx, 0, CRYPT_MD_MD5, "provider=test1", &funcs, &provCtx); ASSERT_EQ(ret, CRYPT_NOT_SUPPORT); ret = CRYPT_EAL_ProviderGetFuncs(libCtx, CRYPT_EAL_OPERAID_HASH, 0, "provider=test1", &funcs, &provCtx); ASSERT_EQ(ret, CRYPT_NOT_SUPPORT); // Test 4: Test when attribute format is non-standard ret = CRYPT_EAL_ProviderGetFuncs(libCtx, CRYPT_EAL_OPERAID_HASH, CRYPT_MD_MD5, "provider", &funcs, &provCtx); ASSERT_EQ(ret, CRYPT_PROVIDER_ERR_ATTRIBUTE); ret = CRYPT_EAL_ProviderGetFuncs(libCtx, CRYPT_EAL_OPERAID_HASH, CRYPT_MD_MD5, "provider=test1provider!=test2", &funcs, &provCtx); ASSERT_EQ(ret, CRYPT_NOT_SUPPORT); ret = CRYPT_EAL_ProviderGetFuncs(libCtx, CRYPT_EAL_OPERAID_HASH, CRYPT_MD_MD5, "provider!test2", &funcs, &provCtx); ASSERT_EQ(ret, CRYPT_PROVIDER_ERR_ATTRIBUTE); ret = CRYPT_EAL_ProviderGetFuncs(libCtx, CRYPT_EAL_OPERAID_HASH, CRYPT_MD_MD5, "!=tesst2", &funcs, &provCtx); ASSERT_EQ(ret, CRYPT_PROVIDER_ERR_ATTRIBUTE); EXIT: if (libCtx != NULL) { CRYPT_EAL_LibCtxFree(libCtx); } return; #endif } /* END_CASE */ /** * @test SDV_CRYPTO_PROVIDER_LOAD_UNINSTALL_TC001 * @title Test whether the external interface of each algorithm reports an error * when using the provider method provided by a third party that does not contain newctx * @precon None * @prior Level 1 * @auto TRUE */ /* BEGIN_CASE */ void SDV_CRYPTO_PROVIDER_LOAD_UNINSTALL_TC001(char *path, char *providerNoInit, int cmd) { #ifndef HITLS_CRYPTO_PROVIDER (void)path; (void)providerNoInit; (void)cmd; SKIP_TEST(); #else CRYPT_EAL_LibCtx *libCtx = NULL; libCtx = CRYPT_EAL_LibCtxNew(); ASSERT_TRUE(libCtx != NULL); ASSERT_EQ(CRYPT_EAL_ProviderSetLoadPath(libCtx, path), CRYPT_SUCCESS); ASSERT_EQ(CRYPT_EAL_ProviderLoad(libCtx, cmd, providerNoInit, NULL, NULL), CRYPT_SUCCESS); CRYPT_EAL_KdfCTX *kdfCtx = CRYPT_EAL_ProviderKdfNewCtx(libCtx, CRYPT_KDF_SCRYPT, NULL); ASSERT_TRUE(kdfCtx == NULL); CRYPT_EAL_MacCtx *macCtx = CRYPT_EAL_ProviderMacNewCtx(libCtx, CRYPT_MAC_HMAC_MD5, NULL); ASSERT_TRUE(macCtx == NULL); CRYPT_EAL_MdCTX *mdCtx = CRYPT_EAL_ProviderMdNewCtx(libCtx, CRYPT_MD_MD5, NULL); ASSERT_TRUE(mdCtx == NULL); CRYPT_EAL_PkeyCtx *pkeyCtx = CRYPT_EAL_ProviderPkeyNewCtx(libCtx, CRYPT_PKEY_DSA, 0, NULL); ASSERT_TRUE(pkeyCtx == NULL); EXIT: CRYPT_EAL_LibCtxFree(libCtx); return; #endif } /* END_CASE */ /** * @test SDV_CRYPTO_PROVIDER_LOAD_UNINSTALL_TC002 * @title Test whether the external interfaces of each algorithm run normally * when using the provider method provided by a third party without freectx * @precon None * @prior Level 1 * @auto TRUE */ /* BEGIN_CASE */ void SDV_CRYPTO_PROVIDER_LOAD_UNINSTALL_TC002(char *path, char *providerNoFree, int cmd) { #ifndef HITLS_CRYPTO_PROVIDER (void)path; (void)providerNoFree; (void)cmd; SKIP_TEST(); #else CRYPT_EAL_LibCtx *libCtx = NULL; libCtx = CRYPT_EAL_LibCtxNew(); ASSERT_TRUE(libCtx != NULL); ASSERT_EQ(CRYPT_EAL_ProviderSetLoadPath(libCtx, path), CRYPT_SUCCESS); ASSERT_EQ(CRYPT_EAL_ProviderLoad(libCtx, cmd, providerNoFree, NULL, NULL), CRYPT_SUCCESS); CRYPT_EAL_KdfCTX *kdfCtx = CRYPT_EAL_ProviderKdfNewCtx(libCtx, CRYPT_KDF_SCRYPT, NULL); ASSERT_TRUE(kdfCtx != NULL); void *tempData = kdfCtx->data; CRYPT_EAL_KdfFreeCtx(kdfCtx); BSL_SAL_FREE(tempData); CRYPT_EAL_MacCtx *macCtx = CRYPT_EAL_ProviderMacNewCtx(libCtx, CRYPT_MAC_HMAC_MD5, NULL); ASSERT_TRUE(macCtx != NULL); tempData = macCtx->ctx; CRYPT_EAL_MacFreeCtx(macCtx); BSL_SAL_FREE(tempData); CRYPT_EAL_MdCTX *mdCtx = CRYPT_EAL_ProviderMdNewCtx(libCtx, CRYPT_MD_MD5, NULL); ASSERT_TRUE(mdCtx != NULL); tempData = mdCtx->data; CRYPT_EAL_MdFreeCtx(mdCtx); BSL_SAL_FREE(tempData); CRYPT_EAL_PkeyCtx *pkeyCtx = CRYPT_EAL_ProviderPkeyNewCtx(libCtx, CRYPT_PKEY_DSA, 0, NULL); ASSERT_TRUE(pkeyCtx != NULL); tempData = pkeyCtx->key; CRYPT_EAL_PkeyFreeCtx(pkeyCtx); BSL_SAL_FREE(tempData); EXIT: CRYPT_EAL_LibCtxFree(libCtx); return; #endif } /* END_CASE */ /** * @test SDV_CRYPTO_PROVIDER_LOAD_DEFAULT_TC001 * Load two providers, one of which is the default provider, * query the algorithm from the default provider, and calculate the result */ /* BEGIN_CASE */ void SDV_CRYPTO_PROVIDER_LOAD_DEFAULT_TC001(char *path, char *test1, int cmd, Hex *msg, Hex *hash) { #ifndef HITLS_CRYPTO_PROVIDER (void)path; (void)test1; (void)cmd; (void)msg; (void)hash; SKIP_TEST(); #else CRYPT_EAL_LibCtx *libCtx = NULL; CRYPT_EAL_MdCTX *ctx = NULL; int32_t ret; // Test CRYPT_EAL_LibCtxNew libCtx = CRYPT_EAL_LibCtxNew(); ASSERT_TRUE(libCtx != NULL); // Test CRYPT_EAL_ProviderSetLoadPath ret = CRYPT_EAL_ProviderSetLoadPath(libCtx, path); ASSERT_EQ(ret, CRYPT_SUCCESS); // Test CRYPT_EAL_ProviderLoad ret = CRYPT_EAL_ProviderLoad(libCtx, cmd, test1, NULL, NULL); ASSERT_EQ(ret, CRYPT_SUCCESS); // Test CRYPT_EAL_ProviderLoad ret = CRYPT_EAL_ProviderLoad(libCtx, BSL_SAL_LIB_FMT_OFF, "default", NULL, NULL); ASSERT_EQ(ret, CRYPT_SUCCESS); // Test CRYPT_EAL_ProviderLoad ret = CRYPT_EAL_ProviderLoad(libCtx, BSL_SAL_LIB_FMT_OFF, "default", NULL, NULL); ASSERT_EQ(ret, CRYPT_SUCCESS); ctx = CRYPT_EAL_ProviderMdNewCtx(libCtx, CRYPT_MD_SHA224, "provider=default"); ASSERT_TRUE(ctx != NULL); uint8_t output[32]; uint32_t outLen = sizeof(output); ASSERT_EQ(CRYPT_EAL_MdInit(ctx), CRYPT_SUCCESS); ASSERT_EQ(CRYPT_EAL_MdUpdate(ctx, msg->x, msg->len), CRYPT_SUCCESS); ASSERT_EQ(CRYPT_EAL_MdFinal(ctx, output, &outLen), CRYPT_SUCCESS); ASSERT_EQ(memcmp(output, hash->x, hash->len), 0); EXIT: CRYPT_EAL_LibCtxFree(libCtx); CRYPT_EAL_MdFreeCtx(ctx); return; #endif } /* END_CASE */ #ifdef HITLS_CRYPTO_PROVIDER static int32_t GroupCapsCallback(BSL_Param *param, void *args) { int *count = (int *)args; (*count)++; BSL_Param *groupNameParam = BSL_PARAM_FindParam(param, CRYPT_PARAM_CAP_TLS_GROUP_IANA_GROUP_NAME); ASSERT_TRUE(groupNameParam != NULL); ASSERT_EQ(groupNameParam->valueType, BSL_PARAM_TYPE_OCTETS_PTR); ASSERT_TRUE(groupNameParam->value != NULL); BSL_Param *groupIdParam = BSL_PARAM_FindParam(param, CRYPT_PARAM_CAP_TLS_GROUP_IANA_GROUP_ID); ASSERT_TRUE(groupIdParam != NULL); ASSERT_EQ(groupIdParam->valueType, BSL_PARAM_TYPE_UINT16); ASSERT_TRUE(groupIdParam->value != NULL); ASSERT_TRUE(groupIdParam->valueLen == sizeof(uint16_t)); groupIdParam->useLen = sizeof(uint16_t); BSL_Param *paraIdParam = BSL_PARAM_FindParam(param, CRYPT_PARAM_CAP_TLS_GROUP_PARA_ID); ASSERT_TRUE(paraIdParam != NULL); ASSERT_EQ(paraIdParam->valueType, BSL_PARAM_TYPE_INT32); ASSERT_TRUE(paraIdParam->value != NULL); ASSERT_TRUE(paraIdParam->valueLen == sizeof(int32_t)); paraIdParam->useLen = sizeof(int32_t); BSL_Param *algIdParam = BSL_PARAM_FindParam(param, CRYPT_PARAM_CAP_TLS_GROUP_ALG_ID); ASSERT_TRUE(algIdParam != NULL); ASSERT_EQ(algIdParam->valueType, BSL_PARAM_TYPE_INT32); ASSERT_TRUE(algIdParam->value != NULL); ASSERT_TRUE(algIdParam->valueLen == sizeof(int32_t)); algIdParam->useLen = sizeof(int32_t); BSL_Param *secBitsParam = BSL_PARAM_FindParam(param, CRYPT_PARAM_CAP_TLS_GROUP_SEC_BITS); ASSERT_TRUE(secBitsParam != NULL); ASSERT_EQ(secBitsParam->valueType, BSL_PARAM_TYPE_INT32); ASSERT_TRUE(secBitsParam->value != NULL); ASSERT_TRUE(secBitsParam->valueLen == sizeof(int32_t)); secBitsParam->useLen = sizeof(int32_t); BSL_Param *versionBitsParam = BSL_PARAM_FindParam(param, CRYPT_PARAM_CAP_TLS_GROUP_VERSION_BITS); ASSERT_TRUE(versionBitsParam != NULL); ASSERT_EQ(versionBitsParam->valueType, BSL_PARAM_TYPE_UINT32); ASSERT_TRUE(versionBitsParam->value != NULL); ASSERT_TRUE(versionBitsParam->valueLen == sizeof(uint32_t)); versionBitsParam->useLen = sizeof(uint32_t); BSL_Param *isKemParam = BSL_PARAM_FindParam(param, CRYPT_PARAM_CAP_TLS_GROUP_IS_KEM); ASSERT_TRUE(isKemParam != NULL); ASSERT_EQ(isKemParam->valueType, BSL_PARAM_TYPE_BOOL); ASSERT_TRUE(isKemParam->valueLen == sizeof(bool)); isKemParam->useLen = sizeof(bool); if (groupNameParam->value != NULL && strcmp((char *)groupNameParam->value, "secp256r1") == 0) { ASSERT_EQ(*((uint16_t *)groupIdParam->value), HITLS_EC_GROUP_SECP256R1); ASSERT_EQ(*((int32_t *)paraIdParam->value), CRYPT_ECC_NISTP256); ASSERT_EQ(*((int32_t *)algIdParam->value), CRYPT_PKEY_ECDH); ASSERT_EQ(*((int32_t *)secBitsParam->value), 128); ASSERT_EQ(*((uint32_t *)versionBitsParam->value), (TLS_VERSION_MASK | DTLS_VERSION_MASK)); ASSERT_EQ(*((bool *)isKemParam->value), false); } else if (groupNameParam->value != NULL && strcmp((char *)groupNameParam->value, "test_new_group") == 0) { // Verify the custom group parameters from provider_get_cap_test1 ASSERT_EQ(*((uint16_t *)groupIdParam->value), 477); ASSERT_EQ(*((int32_t *)paraIdParam->value), NEW_PARA_ALGID); ASSERT_EQ(*((int32_t *)algIdParam->value), NEW_PKEY_ALGID); ASSERT_EQ(*((int32_t *)secBitsParam->value), 1024); ASSERT_EQ(*((uint32_t *)versionBitsParam->value), (TLS12_VERSION_BIT | TLS13_VERSION_BIT)); ASSERT_EQ(*((bool *)isKemParam->value), false); } return CRYPT_SUCCESS; EXIT: return CRYPT_NOT_SUPPORT; } static int32_t SigAlgCapsCallback(BSL_Param *param, void *args) { int *count = (int *)args; (*count)++; // 验证必要参数存在 BSL_Param *sigNameParam = BSL_PARAM_FindParam(param, CRYPT_PARAM_CAP_TLS_SIGNALG_IANA_SIGN_NAME); ASSERT_TRUE(sigNameParam != NULL); ASSERT_EQ(sigNameParam->valueType, BSL_PARAM_TYPE_OCTETS_PTR); BSL_Param *sigIanaIdParam = BSL_PARAM_FindParam(param, CRYPT_PARAM_CAP_TLS_SIGNALG_IANA_SIGN_ID); ASSERT_TRUE(sigIanaIdParam != NULL); ASSERT_EQ(sigIanaIdParam->valueType, BSL_PARAM_TYPE_UINT16); ASSERT_TRUE(sigIanaIdParam->valueLen == sizeof(uint16_t)); sigIanaIdParam->useLen = sizeof(uint16_t); BSL_Param *keyTypeParam = BSL_PARAM_FindParam(param, CRYPT_PARAM_CAP_TLS_SIGNALG_KEY_TYPE); ASSERT_TRUE(keyTypeParam != NULL); ASSERT_EQ(keyTypeParam->valueType, BSL_PARAM_TYPE_INT32); ASSERT_TRUE(keyTypeParam->valueLen == sizeof(int32_t)); keyTypeParam->useLen = sizeof(int32_t); BSL_Param *paraIdParam = BSL_PARAM_FindParam(param, CRYPT_PARAM_CAP_TLS_SIGNALG_PARA_ID); ASSERT_TRUE(paraIdParam != NULL); ASSERT_EQ(paraIdParam->valueType, BSL_PARAM_TYPE_INT32); ASSERT_TRUE(paraIdParam->valueLen == sizeof(int32_t)); paraIdParam->useLen = sizeof(int32_t); BSL_Param *signHashAlgIdParam = BSL_PARAM_FindParam(param, CRYPT_PARAM_CAP_TLS_SIGNALG_SIGNWITHMD_ID); ASSERT_TRUE(signHashAlgIdParam != NULL); ASSERT_EQ(signHashAlgIdParam->valueType, BSL_PARAM_TYPE_INT32); ASSERT_TRUE(signHashAlgIdParam->valueLen == sizeof(int32_t)); signHashAlgIdParam->useLen = sizeof(int32_t); BSL_Param *signHashAlgOidParam = BSL_PARAM_FindParam(param, CRYPT_PARAM_CAP_TLS_SIGNALG_SIGNWITHMD_OID); BSL_Param *signHashAlgNameParam = BSL_PARAM_FindParam(param, CRYPT_PARAM_CAP_TLS_SIGNALG_SIGNWITHMD_NAME); BSL_Param *signAlgIdParam = BSL_PARAM_FindParam(param, CRYPT_PARAM_CAP_TLS_SIGNALG_SIGN_ID); ASSERT_TRUE(signAlgIdParam != NULL); ASSERT_EQ(signAlgIdParam->valueType, BSL_PARAM_TYPE_INT32); ASSERT_TRUE(signAlgIdParam->valueLen == sizeof(int32_t)); signAlgIdParam->useLen = sizeof(int32_t); BSL_Param *hashAlgIdParam = BSL_PARAM_FindParam(param, CRYPT_PARAM_CAP_TLS_SIGNALG_MD_ID); ASSERT_TRUE(hashAlgIdParam != NULL); ASSERT_EQ(hashAlgIdParam->valueType, BSL_PARAM_TYPE_INT32); ASSERT_TRUE(hashAlgIdParam->valueLen == sizeof(int32_t)); hashAlgIdParam->useLen = sizeof(int32_t); BSL_Param *hashAlgOidParam = BSL_PARAM_FindParam(param, CRYPT_PARAM_CAP_TLS_SIGNALG_MD_OID); BSL_Param *hashAlgNameParam = BSL_PARAM_FindParam(param, CRYPT_PARAM_CAP_TLS_SIGNALG_MD_NAME); BSL_Param *secBitsParam = BSL_PARAM_FindParam(param, CRYPT_PARAM_CAP_TLS_SIGNALG_SEC_BITS); ASSERT_TRUE(secBitsParam != NULL); ASSERT_EQ(secBitsParam->valueType, BSL_PARAM_TYPE_INT32); ASSERT_TRUE(secBitsParam->valueLen == sizeof(int32_t)); secBitsParam->useLen = sizeof(int32_t); BSL_Param *certVersionParam = BSL_PARAM_FindParam(param, CRYPT_PARAM_CAP_TLS_SIGNALG_CERT_VERSION_BITS); ASSERT_TRUE(certVersionParam != NULL); ASSERT_EQ(certVersionParam->valueType, BSL_PARAM_TYPE_UINT32); ASSERT_TRUE(certVersionParam->valueLen == sizeof(uint32_t)); certVersionParam->useLen = sizeof(uint32_t); BSL_Param *chainVersionParam = BSL_PARAM_FindParam(param, CRYPT_PARAM_CAP_TLS_SIGNALG_CHAIN_VERSION_BITS); ASSERT_TRUE(chainVersionParam != NULL); ASSERT_EQ(chainVersionParam->valueType, BSL_PARAM_TYPE_UINT32); ASSERT_TRUE(chainVersionParam->valueLen == sizeof(uint32_t)); chainVersionParam->useLen = sizeof(uint32_t); if (sigNameParam->value != NULL && strcmp((char *)sigNameParam->value, "ecdsa_secp256r1_sha256") == 0) { ASSERT_EQ(*((uint16_t *)sigIanaIdParam->value), CERT_SIG_SCHEME_ECDSA_SECP256R1_SHA256); ASSERT_EQ(*((int32_t *)keyTypeParam->value), TLS_CERT_KEY_TYPE_ECDSA); ASSERT_EQ(*((int32_t *)paraIdParam->value), CRYPT_ECC_NISTP256); ASSERT_EQ(*((int32_t *)signHashAlgIdParam->value), BSL_CID_ECDSAWITHSHA256); ASSERT_EQ(*((int32_t *)signAlgIdParam->value), CRYPT_PKEY_ECDSA); ASSERT_EQ(*((int32_t *)hashAlgIdParam->value), HITLS_HASH_SHA_256); ASSERT_EQ(*((int32_t *)secBitsParam->value), 128); ASSERT_EQ(*((uint32_t *)certVersionParam->value), (TLS_VERSION_MASK | DTLS_VERSION_MASK)); ASSERT_EQ(*((uint32_t *)chainVersionParam->value), (TLS_VERSION_MASK | DTLS_VERSION_MASK)); } else if (sigNameParam->value != NULL && strcmp((char *)sigNameParam->value, "test_new_sign_alg_name") == 0) { ASSERT_EQ(*((uint16_t *)sigIanaIdParam->value), 23333); ASSERT_EQ(*((int32_t *)keyTypeParam->value), CRYPT_PKEY_ECDSA); ASSERT_EQ(*((int32_t *)paraIdParam->value), BSL_CID_SECP384R1); if (signHashAlgOidParam != NULL) { char *signHashAlgOid = (char *)signHashAlgOidParam->value; ASSERT_EQ(strcmp(signHashAlgOid, "\150\40\66\77\55"), 0); } if (signHashAlgNameParam != NULL) { char *signHashAlgName = (char *)signHashAlgNameParam->value; ASSERT_EQ(strcmp(signHashAlgName, "test_new_sign_with_md_name"), 0); } ASSERT_EQ(*((int32_t *)signHashAlgIdParam->value), NEW_SIGN_HASH_ALGID); ASSERT_EQ(*((int32_t *)signAlgIdParam->value), CRYPT_PKEY_ECDSA); ASSERT_EQ(*((int32_t *)hashAlgIdParam->value), NEW_HASH_ALGID); if (hashAlgOidParam != NULL) { char *hashAlgOid = (char *)hashAlgOidParam->value; ASSERT_EQ(strcmp(hashAlgOid, "\150\40\66\71\55"), 0); } if (hashAlgNameParam != NULL) { char *hashAlgName = (char *)hashAlgNameParam->value; ASSERT_EQ(strcmp(hashAlgName, "test_new_md_name"), 0); } ASSERT_EQ(*((int32_t *)secBitsParam->value), 1024); ASSERT_EQ(*((uint32_t *)certVersionParam->value), (TLS12_VERSION_BIT | TLS13_VERSION_BIT)); ASSERT_EQ(*((uint32_t *)chainVersionParam->value), (TLS12_VERSION_BIT | TLS13_VERSION_BIT)); } return CRYPT_SUCCESS; EXIT: return CRYPT_NOT_SUPPORT; } #endif /** * @test SDV_CRYPTO_PROVIDER_GET_CAPS_TC002 * @title Test CRYPT_EAL_ProviderGetCaps for default provider capabilities * @precon None * @brief * 1. Test getting group capabilities (curves) * 2. Test getting signature algorithm capabilities * @expect * 1. Successfully get and verify group parameters * 2. Successfully get and verify signature algorithm parameters * @prior Level 1 * @auto TRUE */ /* BEGIN_CASE */ void SDV_CRYPTO_PROVIDER_GET_CAPS_TC001(void) { #ifndef HITLS_CRYPTO_PROVIDER SKIP_TEST(); #else CRYPT_EAL_LibCtx *libCtx = NULL; CRYPT_EAL_ProvMgrCtx *providerMgr = NULL; CRYPT_EAL_ProvMgrCtx provMgrWithGetCapCb = {0}; int groupCount = 0; int sigAlgCount = 0; libCtx = CRYPT_EAL_LibCtxNew(); ASSERT_TRUE(libCtx != NULL); // Load default provider ASSERT_EQ(CRYPT_EAL_ProviderLoad(libCtx, BSL_SAL_LIB_FMT_OFF, "default", NULL, &providerMgr), 0); ASSERT_TRUE(providerMgr != NULL); // Test getting group capabilities ASSERT_EQ(CRYPT_EAL_ProviderGetCaps(providerMgr, CRYPT_EAL_GET_GROUP_CAP, (CRYPT_EAL_ProcessFuncCb)GroupCapsCallback, &groupCount), CRYPT_SUCCESS); ASSERT_EQ(groupCount, 16); // Test getting signature algorithm capabilities ASSERT_EQ(CRYPT_EAL_ProviderGetCaps(providerMgr, CRYPT_EAL_GET_SIGALG_CAP, (CRYPT_EAL_ProcessFuncCb)SigAlgCapsCallback, &sigAlgCount), CRYPT_SUCCESS); ASSERT_EQ(sigAlgCount, 23); // Test invalid mgrCtx ASSERT_EQ(CRYPT_EAL_ProviderGetCaps(NULL, CRYPT_EAL_GET_GROUP_CAP, (CRYPT_EAL_ProcessFuncCb)GroupCapsCallback, &groupCount), CRYPT_NULL_INPUT); // Test invalid CRYPT_EAL_ProcessFuncCb ASSERT_EQ(CRYPT_EAL_ProviderGetCaps(providerMgr, CRYPT_EAL_GET_GROUP_CAP, NULL, &groupCount), CRYPT_NULL_INPUT); // Test invalid mgrCtx provMgrWithGetCapCb.provCtx = NULL; provMgrWithGetCapCb.provGetCap = NULL; ASSERT_EQ(CRYPT_EAL_ProviderGetCaps(&provMgrWithGetCapCb, CRYPT_EAL_GET_GROUP_CAP, (CRYPT_EAL_ProcessFuncCb)GroupCapsCallback, &groupCount), CRYPT_SUCCESS); // Test invalid command ASSERT_EQ(CRYPT_EAL_ProviderGetCaps(providerMgr, -1, (CRYPT_EAL_ProcessFuncCb)GroupCapsCallback, &groupCount), CRYPT_NOT_SUPPORT); // Cleanup ASSERT_EQ(CRYPT_EAL_ProviderUnload(libCtx, BSL_SAL_LIB_FMT_OFF, "default"), CRYPT_SUCCESS); EXIT: CRYPT_EAL_LibCtxFree(libCtx); return; #endif } /* END_CASE */ #ifdef HITLS_CRYPTO_PROVIDER static int32_t CountProvidersCallback(CRYPT_EAL_ProvMgrCtx *provMgr, void *args) { (void)provMgr; int *count = (int *)args; if (count != NULL) { (*count)++; } return CRYPT_SUCCESS; } // Callback function that returns an error static int32_t ErrorCallback(CRYPT_EAL_ProvMgrCtx *provMgr, void *args) { (void)provMgr; int *count = (int *)args; if (count != NULL) { (*count)++; } return CRYPT_NOT_SUPPORT; } #endif /** * @test SDV_CRYPTO_PROVIDER_PROC_ALL_TC001 * @title Test CRYPT_EAL_ProviderProcessAll functionality * @precon None * @brief * 1. Test processing all loaded providers with a callback function * 2. Test error handling for NULL inputs * 3. Test error propagation from callback function * @expect * 1. Successfully process all providers * 2. Return CRYPT_NULL_INPUT for NULL inputs * 3. Properly propagate errors from callback function * @prior Level 1 * @auto TRUE */ /* BEGIN_CASE */ void SDV_CRYPTO_PROVIDER_PROC_ALL_TC001(char *path, char *test1, char *test2, int cmd) { #ifndef HITLS_CRYPTO_PROVIDER (void)path; (void)test1; (void)test2; (void)cmd; SKIP_TEST(); #else CRYPT_EAL_LibCtx *libCtx = NULL; int providerCount = 0; int errorProviderCount = 0; // Initialize library context libCtx = CRYPT_EAL_LibCtxNew(); ASSERT_TRUE(libCtx != NULL); // Set provider path ASSERT_EQ(CRYPT_EAL_ProviderSetLoadPath(libCtx, path), CRYPT_SUCCESS); // Load multiple providers ASSERT_EQ(CRYPT_EAL_ProviderLoad(libCtx, cmd, test1, NULL, NULL), CRYPT_SUCCESS); ASSERT_EQ(CRYPT_EAL_ProviderLoad(libCtx, cmd, test2, NULL, NULL), CRYPT_SUCCESS); ASSERT_EQ(CRYPT_EAL_ProviderLoad(libCtx, BSL_SAL_LIB_FMT_OFF, "default", NULL, NULL), CRYPT_SUCCESS); // Test 1: Process all providers with a counting callback ASSERT_EQ(CRYPT_EAL_ProviderProcessAll(libCtx, CountProvidersCallback, &providerCount), CRYPT_SUCCESS); ASSERT_EQ(providerCount, 3); // Should have processed 3 providers // Test 2: Test NULL libCtx providerCount = 0; ASSERT_EQ(CRYPT_EAL_ProviderProcessAll(NULL, CountProvidersCallback, &providerCount), CRYPT_SUCCESS); ASSERT_EQ(providerCount, 1); // Test 3: Test NULL inputs ASSERT_EQ(CRYPT_EAL_ProviderProcessAll(libCtx, NULL, &providerCount), CRYPT_NULL_INPUT); // Test 4: Test error propagation from callback ASSERT_EQ(CRYPT_EAL_ProviderProcessAll(libCtx, ErrorCallback, &errorProviderCount), CRYPT_NOT_SUPPORT); ASSERT_EQ(errorProviderCount, 1); // Should have processed only the first provider before error // Cleanup ASSERT_EQ(CRYPT_EAL_ProviderUnload(libCtx, cmd, test1), CRYPT_SUCCESS); ASSERT_EQ(CRYPT_EAL_ProviderUnload(libCtx, cmd, test2), CRYPT_SUCCESS); ASSERT_EQ(CRYPT_EAL_ProviderUnload(libCtx, BSL_SAL_LIB_FMT_OFF, "default"), CRYPT_SUCCESS); EXIT: CRYPT_EAL_LibCtxFree(libCtx); return; #endif } /* END_CASE */ #ifdef HITLS_CRYPTO_PROVIDER typedef struct { int totalProviders; int providersWithMd5; int providersWithSha256; } ProviderStats; int32_t CheckAlgorithmsCallback(CRYPT_EAL_ProvMgrCtx *provMgr, void *args) { ProviderStats *stats = (ProviderStats *)args; if (stats != NULL) { stats->totalProviders++; const CRYPT_EAL_Func *funcs; void *provCtx; int32_t ret = CRYPT_EAL_ProviderGetFuncs(provMgr->libCtx, CRYPT_EAL_OPERAID_HASH, CRYPT_MD_MD5, NULL, &funcs, &provCtx); if (ret == CRYPT_SUCCESS && funcs != NULL) { stats->providersWithMd5++; } ret = CRYPT_EAL_ProviderGetFuncs(provMgr->libCtx, CRYPT_EAL_OPERAID_HASH, CRYPT_MD_SHA256, NULL, &funcs, &provCtx); if (ret == CRYPT_SUCCESS && funcs != NULL) { stats->providersWithSha256++; } } return CRYPT_SUCCESS; } #endif /** * @test SDV_CRYPTO_PROVIDER_PROC_ALL_TC002 * @title Test CRYPT_EAL_ProviderProcessAll with specific provider operations * @precon None * @brief * 1. Test processing all providers to collect specific information * 2. Test processing all providers to perform specific operations * @expect * 1. Successfully collect information from all providers * 2. Successfully perform operations on all providers * @prior Level 1 * @auto TRUE */ /* BEGIN_CASE */ void SDV_CRYPTO_PROVIDER_PROC_ALL_TC002(char *path, char *test1, char *test2, int cmd) { #ifndef HITLS_CRYPTO_PROVIDER (void)path; (void)test1; (void)test2; (void)cmd; SKIP_TEST(); #else CRYPT_EAL_LibCtx *libCtx = NULL; ProviderStats stats = {0}; // Initialize library context libCtx = CRYPT_EAL_LibCtxNew(); ASSERT_TRUE(libCtx != NULL); // Set provider path ASSERT_EQ(CRYPT_EAL_ProviderSetLoadPath(libCtx, path), CRYPT_SUCCESS); // Load multiple providers ASSERT_EQ(CRYPT_EAL_ProviderLoad(libCtx, cmd, test1, NULL, NULL), CRYPT_SUCCESS); ASSERT_EQ(CRYPT_EAL_ProviderLoad(libCtx, cmd, test2, NULL, NULL), CRYPT_SUCCESS); ASSERT_EQ(CRYPT_EAL_ProviderLoad(libCtx, BSL_SAL_LIB_FMT_OFF, "default", NULL, NULL), CRYPT_SUCCESS); // Process all providers to collect algorithm information ASSERT_EQ(CRYPT_EAL_ProviderProcessAll(libCtx, CheckAlgorithmsCallback, &stats), CRYPT_SUCCESS); // Verify results ASSERT_EQ(stats.totalProviders, 3); ASSERT_TRUE(stats.providersWithMd5 > 0); // At least one provider should support MD5 ASSERT_TRUE(stats.providersWithSha256 > 0); // At least one provider should support SHA256 // Test with empty provider list CRYPT_EAL_LibCtx *emptyLibCtx = CRYPT_EAL_LibCtxNew(); ASSERT_TRUE(emptyLibCtx != NULL); ProviderStats emptyStats = {0}; ASSERT_EQ(CRYPT_EAL_ProviderProcessAll(emptyLibCtx, CheckAlgorithmsCallback, &emptyStats), CRYPT_SUCCESS); ASSERT_EQ(emptyStats.totalProviders, 0); // No providers should be processed // Cleanup ASSERT_EQ(CRYPT_EAL_ProviderUnload(libCtx, cmd, test1), CRYPT_SUCCESS); ASSERT_EQ(CRYPT_EAL_ProviderUnload(libCtx, cmd, test2), CRYPT_SUCCESS); ASSERT_EQ(CRYPT_EAL_ProviderUnload(libCtx, BSL_SAL_LIB_FMT_OFF, "default"), CRYPT_SUCCESS); EXIT: CRYPT_EAL_LibCtxFree(libCtx); CRYPT_EAL_LibCtxFree(emptyLibCtx); return; #endif } /* END_CASE */ /** * @test SDV_CRYPTO_PROVIDER_GET_CAP_TEST_TC001 * @title Test provider_get_cap_test1 provider functionality * @precon None * @brief * 1. Load provider_get_cap_test1 provider * 2. Test key generation, shared key computation, signing and verification * @expect * 1. Successfully load the provider * 2. Successfully perform cryptographic operations * @prior Level 1 * @auto TRUE */ /* BEGIN_CASE */ void SDV_CRYPTO_PROVIDER_GET_CAP_TEST_TC001(char *path, char *get_cap_test1, int cmd) { #ifndef HITLS_CRYPTO_PROVIDER (void)path; (void)get_cap_test1; (void)cmd; SKIP_TEST(); #else CRYPT_EAL_LibCtx *libCtx = NULL; CRYPT_EAL_ProvMgrCtx *providerMgr = NULL; CRYPT_EAL_PkeyCtx *keyCtx1 = NULL; CRYPT_EAL_PkeyCtx *keyCtx2 = NULL; uint8_t sharedKey1[256] = {0}; uint32_t sharedKeyLen1 = sizeof(sharedKey1); uint8_t sharedKey2[256] = {0}; uint32_t sharedKeyLen2 = sizeof(sharedKey2); // Initialize library context libCtx = CRYPT_EAL_LibCtxNew(); ASSERT_TRUE(libCtx != NULL); ASSERT_EQ(CRYPT_EAL_ProviderSetLoadPath(libCtx, path), CRYPT_SUCCESS); ASSERT_EQ(CRYPT_EAL_ProviderLoad(libCtx, cmd, get_cap_test1, NULL, &providerMgr), CRYPT_SUCCESS); ASSERT_TRUE(providerMgr != NULL); int groupCount = 0; int sigAlgCount = 0; ASSERT_EQ(CRYPT_EAL_ProviderGetCaps(providerMgr, CRYPT_EAL_GET_GROUP_CAP, (CRYPT_EAL_ProcessFuncCb)GroupCapsCallback, &groupCount), CRYPT_SUCCESS); ASSERT_EQ(groupCount, 2); ASSERT_EQ(CRYPT_EAL_ProviderGetCaps(providerMgr, CRYPT_EAL_GET_SIGALG_CAP, (CRYPT_EAL_ProcessFuncCb)SigAlgCapsCallback, &sigAlgCount), CRYPT_SUCCESS); ASSERT_EQ(sigAlgCount, 1); keyCtx1 = CRYPT_EAL_ProviderPkeyNewCtx(libCtx, NEW_PKEY_ALGID, CRYPT_EAL_PKEY_UNKNOWN_OPERATE, "provider=provider_get_cap_test1"); ASSERT_TRUE(keyCtx1 != NULL); ASSERT_EQ(CRYPT_EAL_PkeySetParaById(keyCtx1, NEW_PARA_ALGID), CRYPT_SUCCESS); ASSERT_EQ(CRYPT_EAL_PkeyGen(keyCtx1), CRYPT_SUCCESS); keyCtx2 = CRYPT_EAL_ProviderPkeyNewCtx(libCtx, NEW_PKEY_ALGID, CRYPT_EAL_PKEY_UNKNOWN_OPERATE, "provider=provider_get_cap_test1"); ASSERT_TRUE(keyCtx2 != NULL); ASSERT_EQ(CRYPT_EAL_PkeySetParaById(keyCtx2, NEW_PARA_ALGID), CRYPT_SUCCESS); ASSERT_EQ(CRYPT_EAL_PkeyGen(keyCtx2), CRYPT_SUCCESS); ASSERT_EQ(CRYPT_EAL_PkeyComputeShareKey(keyCtx1, keyCtx2, sharedKey1, &sharedKeyLen1), CRYPT_SUCCESS); ASSERT_EQ(CRYPT_EAL_PkeyComputeShareKey(keyCtx2, keyCtx1, sharedKey2, &sharedKeyLen2), CRYPT_SUCCESS); ASSERT_TRUE(sharedKeyLen1 > 0); ASSERT_TRUE(sharedKeyLen2 > 0); ASSERT_EQ(memcmp(sharedKey1, sharedKey2, sharedKeyLen1), 0); EXIT: CRYPT_EAL_PkeyFreeCtx(keyCtx1); CRYPT_EAL_PkeyFreeCtx(keyCtx2); CRYPT_EAL_ProviderUnload(libCtx, cmd, get_cap_test1); CRYPT_EAL_LibCtxFree(libCtx); return; #endif } /* END_CASE */ /** * @test SDV_CRYPTO_PROVIDER_GET_CAP_TEST_TC002 * @title Test provider_get_cap_test1 provider signature and verification * @precon None * @brief * 1. Load provider_get_cap_test1 provider * 2. Test signature generation and verification with ECDSA * @expect * 1. Successfully load the provider * 2. Successfully sign and verify data * 3. Verification fails with modified signature * @prior Level 1 * @auto TRUE */ /* BEGIN_CASE */ void SDV_CRYPTO_PROVIDER_GET_CAP_TEST_TC002(char *path, char *get_cap_test1, int cmd) { #ifndef HITLS_CRYPTO_PROVIDER (void)path; (void)get_cap_test1; (void)cmd; SKIP_TEST(); #else CRYPT_EAL_LibCtx *libCtx = NULL; CRYPT_EAL_ProvMgrCtx *providerMgr = NULL; CRYPT_EAL_PkeyCtx *keyCtx = NULL; uint8_t signature[128] = {0}; uint32_t signatureLen = sizeof(signature); uint8_t testData[] = "Test data for signing and verification with ECDSA"; uint32_t testDataLen = sizeof(testData) - 1; libCtx = CRYPT_EAL_LibCtxNew(); ASSERT_TRUE(libCtx != NULL); ASSERT_EQ(CRYPT_EAL_ProviderSetLoadPath(libCtx, path), CRYPT_SUCCESS); ASSERT_EQ(CRYPT_EAL_ProviderLoad(libCtx, cmd, get_cap_test1, NULL, &providerMgr), CRYPT_SUCCESS); ASSERT_TRUE(providerMgr != NULL); keyCtx = CRYPT_EAL_ProviderPkeyNewCtx(libCtx, CRYPT_PKEY_ECDSA, 0, "provider=provider_get_cap_test1"); ASSERT_TRUE(keyCtx != NULL); ASSERT_EQ(CRYPT_EAL_PkeySetParaById(keyCtx, NEW_PARA_ALGID), CRYPT_SUCCESS); ASSERT_EQ(CRYPT_EAL_PkeyGen(keyCtx), CRYPT_SUCCESS); ASSERT_EQ(CRYPT_EAL_PkeySign(keyCtx, CRYPT_MD_SHA256, testData, testDataLen, signature, &signatureLen), 0); ASSERT_TRUE(signatureLen > 0); ASSERT_EQ(CRYPT_EAL_PkeyVerify(keyCtx, CRYPT_MD_SHA256, testData, testDataLen, signature, signatureLen), CRYPT_SUCCESS); // Test 4: Modify signature and verify it should fail signature[10] ^= 0xFF; // Flip bits in the signature ASSERT_EQ(CRYPT_EAL_PkeyVerify(keyCtx, CRYPT_MD_SHA256, testData, testDataLen, signature, signatureLen), CRYPT_ECDSA_VERIFY_FAIL); EXIT: CRYPT_EAL_PkeyFreeCtx(keyCtx); CRYPT_EAL_ProviderUnload(libCtx, cmd, get_cap_test1); CRYPT_EAL_LibCtxFree(libCtx); return; #endif } /* END_CASE */ /* BEGIN_CASE */ void SDV_CRYPTO_PROVIDER_GET_CAP_TEST_TC003(void) { #ifndef HITLS_CRYPTO_PROVIDER SKIP_TEST(); #else CRYPT_EAL_LibCtx *libCtx = CRYPT_EAL_LibCtxNew(); ASSERT_TRUE(libCtx != NULL); ASSERT_EQ(CRYPT_EAL_ProviderLoad(libCtx, 0, "default", NULL, NULL), CRYPT_SUCCESS); CRYPT_EAL_ProviderUnload(libCtx, 0, "default"); ASSERT_EQ(CRYPT_EAL_ProviderLoad(libCtx, 0, "default", NULL, NULL), CRYPT_SUCCESS); EXIT: CRYPT_EAL_ProviderUnload(libCtx, 0, "default"); CRYPT_EAL_LibCtxFree(libCtx); #endif } /* END_CASE */
2301_79861745/bench_create
testcode/sdv/testcase/crypto/provider/test_suite_sdv_eal_provider_load.c
C
unknown
42,989
/* * This file is part of the openHiTLS project. * * openHiTLS is licensed under the Mulan PSL v2. * You can use this software according to the terms and conditions of the Mulan PSL v2. * You may obtain a copy of Mulan PSL v2 at: * * http://license.coscl.org.cn/MulanPSL2 * * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. * See the Mulan PSL v2 for more details. */ /* BEGIN_HEADER */ #include <stdlib.h> #include "securec.h" #include "crypt_params_key.h" #include "crypt_errno.h" #include "crypt_eal_md.h" #include "crypt_eal_provider.h" #include "crypt_eal_implprovider.h" #include "crypt_provider.h" /* END_HEADER */ #define PROVIDER_A_NAME "provider_a" #define PROVIDER_B_NAME "provider_b" #define PROVIDER_DEFAULT_NAME "default" #define PROVIDER_A_ATTR "provider=a,md=sha256" #define PROVIDER_B_ATTR "provider=b,md=md5" #define PROVIDER_DEFAULT_ATTR "provider=default" #define DEFAULT_SHA256_INIT_RET 0 #define DEFAULT_MD5_INIT_RET 0 #define PROVIDER_A_SHA256_INIT_RET (-1) #define PROVIDER_B_MD5_INIT_RET (-2) uint8_t md = 1; static void *MdNewCtx(void *provCtx, int32_t algId) { (void)provCtx; (void)algId; return &md; } static int32_t MdInitA(void *ctx, BSL_Param *param) { (void)ctx; (void)param; return PROVIDER_A_SHA256_INIT_RET; } static int32_t MdInitB(void *ctx, BSL_Param *param) { (void)ctx; (void)param; return PROVIDER_B_MD5_INIT_RET; } static int32_t MdDeinit(void *ctx) { (void)ctx; return 0; } static int32_t MdCopyCtx(void *dst, const void *src) { (void)dst; (void)src; return 0; } static int32_t MdUpdate(void *ctx, const uint8_t *data, uint32_t nbytes) { (void)ctx; (void)data; (void)nbytes; return 0; } static int32_t MdFinal(void *ctx, uint8_t *digest, uint32_t *outlen) { (void)ctx; (void)digest; (void)outlen; return 0; } static void *MdDupCtx(const void *src) { (void)src; return NULL; } static void MdFreeCtx(void *ctx) { (void)ctx; return; } static int32_t MdGetParam(void *ctx, BSL_Param *param) { (void)ctx; (void)param; return 0; } // SHA256 algorithm function table const CRYPT_EAL_Func providerAMd[] = { {CRYPT_EAL_IMPLMD_NEWCTX, MdNewCtx}, {CRYPT_EAL_IMPLMD_INITCTX, MdInitA}, {CRYPT_EAL_IMPLMD_UPDATE, MdUpdate}, {CRYPT_EAL_IMPLMD_FINAL, MdFinal}, {CRYPT_EAL_IMPLMD_DEINITCTX, MdDeinit}, {CRYPT_EAL_IMPLMD_DUPCTX, MdDupCtx}, {CRYPT_EAL_IMPLMD_COPYCTX, MdCopyCtx}, {CRYPT_EAL_IMPLMD_GETPARAM, MdGetParam}, {CRYPT_EAL_IMPLMD_FREECTX, MdFreeCtx}, CRYPT_EAL_FUNC_END, }; // Algorithm information table static const CRYPT_EAL_AlgInfo providerAMds[] = { {CRYPT_MD_SHA256, providerAMd, PROVIDER_A_ATTR}, CRYPT_EAL_ALGINFO_END }; // SHA256 algorithm function table const CRYPT_EAL_Func providerBMd[] = { {CRYPT_EAL_IMPLMD_NEWCTX, MdNewCtx}, {CRYPT_EAL_IMPLMD_INITCTX, MdInitB}, {CRYPT_EAL_IMPLMD_UPDATE, MdUpdate}, {CRYPT_EAL_IMPLMD_FINAL, MdFinal}, {CRYPT_EAL_IMPLMD_DEINITCTX, MdDeinit}, {CRYPT_EAL_IMPLMD_DUPCTX, MdDupCtx}, {CRYPT_EAL_IMPLMD_COPYCTX, MdCopyCtx}, {CRYPT_EAL_IMPLMD_GETPARAM, MdGetParam}, {CRYPT_EAL_IMPLMD_FREECTX, MdFreeCtx}, CRYPT_EAL_FUNC_END, }; // Algorithm information table static const CRYPT_EAL_AlgInfo providerBMds[] = { {CRYPT_MD_MD5, providerBMd, PROVIDER_B_ATTR}, CRYPT_EAL_ALGINFO_END }; static void MdProvFree(void *provCtx) { (void)provCtx; return; } static int32_t MdProvQueryA(void *provCtx, int32_t operaId, const CRYPT_EAL_AlgInfo **algInfos) { (void)provCtx; switch (operaId) { case CRYPT_EAL_OPERAID_HASH: *algInfos = providerAMds; return 0; default: return 1; } } static int32_t MdProvQueryB(void *provCtx, int32_t operaId, const CRYPT_EAL_AlgInfo **algInfos) { (void)provCtx; switch (operaId) { case CRYPT_EAL_OPERAID_HASH: *algInfos = providerBMds; return 0; default: return 1; } } // Provider output functions table static CRYPT_EAL_Func providerAProvOutFuncs[] = { {CRYPT_EAL_PROVCB_QUERY, MdProvQueryA}, {CRYPT_EAL_PROVCB_FREE, MdProvFree}, {CRYPT_EAL_PROVCB_CTRL, NULL}, CRYPT_EAL_FUNC_END }; static CRYPT_EAL_Func providerBProvOutFuncs[] = { {CRYPT_EAL_PROVCB_QUERY, MdProvQueryB}, {CRYPT_EAL_PROVCB_FREE, MdProvFree}, {CRYPT_EAL_PROVCB_CTRL, NULL}, CRYPT_EAL_FUNC_END }; // Provider initialization function int32_t ProviderAInit(CRYPT_EAL_ProvMgrCtx *mgrCtx, BSL_Param *param, CRYPT_EAL_Func *capFuncs, CRYPT_EAL_Func **outFuncs, void **provCtx) { (void)mgrCtx; (void)param; (void)capFuncs; *outFuncs = providerAProvOutFuncs; *provCtx = NULL; return 0; } int32_t ProviderBInit(CRYPT_EAL_ProvMgrCtx *mgrCtx, BSL_Param *param, CRYPT_EAL_Func *capFuncs, CRYPT_EAL_Func **outFuncs, void **provCtx) { (void)mgrCtx; (void)param; (void)capFuncs; *outFuncs = providerBProvOutFuncs; *provCtx = NULL; return 0; } /** * @test SDV_CRYPTO_PROVIDER_REG_FUNC_TC001 * @title Register default provider first and then register custom provider * @precon None */ /* BEGIN_CASE */ void SDV_CRYPTO_PROVIDER_REG_FUNC_TC001(void) { #ifndef HITLS_CRYPTO_PROVIDER SKIP_TEST(); #else CRYPT_EAL_MdCTX *mdCtx = NULL; TestMemInit(); CRYPT_EAL_LibCtx *libCtx = CRYPT_EAL_LibCtxNew(); ASSERT_TRUE(libCtx != NULL); // 1st: default provider, 2nd: A provider, 3rd: B provider ASSERT_EQ(CRYPT_EAL_ProviderRegister(libCtx, PROVIDER_DEFAULT_NAME, NULL, NULL, NULL), 0); ASSERT_EQ(CRYPT_EAL_ProviderRegister(libCtx, PROVIDER_A_NAME, ProviderAInit, NULL, NULL), 0); ASSERT_EQ(CRYPT_EAL_ProviderRegister(libCtx, PROVIDER_B_NAME, ProviderBInit, NULL, NULL), 0); mdCtx = CRYPT_EAL_ProviderMdNewCtx(libCtx, CRYPT_MD_SHA256, "provider=default"); ASSERT_TRUE(mdCtx != NULL); ASSERT_EQ(CRYPT_EAL_MdInit(mdCtx), DEFAULT_SHA256_INIT_RET); CRYPT_EAL_MdFreeCtx(mdCtx); mdCtx = CRYPT_EAL_ProviderMdNewCtx(libCtx, CRYPT_MD_SHA256, NULL); ASSERT_TRUE(mdCtx != NULL); ASSERT_EQ(CRYPT_EAL_MdInit(mdCtx), DEFAULT_SHA256_INIT_RET); CRYPT_EAL_MdFreeCtx(mdCtx); mdCtx = CRYPT_EAL_ProviderMdNewCtx(libCtx, CRYPT_MD_SHA256, "provider=a"); ASSERT_TRUE(mdCtx != NULL); ASSERT_EQ(CRYPT_EAL_MdInit(mdCtx), PROVIDER_A_SHA256_INIT_RET); CRYPT_EAL_MdFreeCtx(mdCtx); mdCtx = CRYPT_EAL_ProviderMdNewCtx(libCtx, CRYPT_MD_SHA256, "provider=b"); ASSERT_TRUE(mdCtx == NULL); mdCtx = CRYPT_EAL_ProviderMdNewCtx(libCtx, CRYPT_MD_MD5, "provider=a"); ASSERT_TRUE(mdCtx == NULL); mdCtx = CRYPT_EAL_ProviderMdNewCtx(libCtx, CRYPT_MD_SHA256, "md=sha256"); ASSERT_TRUE(mdCtx != NULL); ASSERT_EQ(CRYPT_EAL_MdInit(mdCtx), PROVIDER_A_SHA256_INIT_RET); CRYPT_EAL_MdFreeCtx(mdCtx); mdCtx = CRYPT_EAL_ProviderMdNewCtx(libCtx, CRYPT_MD_MD5, "provider=b"); ASSERT_TRUE(mdCtx != NULL); ASSERT_EQ(CRYPT_EAL_MdInit(mdCtx), PROVIDER_B_MD5_INIT_RET); EXIT: CRYPT_EAL_LibCtxFree(libCtx); CRYPT_EAL_MdFreeCtx(mdCtx); #endif } /* END_CASE */ /** * @test SDV_CRYPTO_PROVIDER_REG_FUNC_TC002 * @title Register custom provider first and then register default provider * @precon None */ /* BEGIN_CASE */ void SDV_CRYPTO_PROVIDER_REG_FUNC_TC002(void) { #ifndef HITLS_CRYPTO_PROVIDER SKIP_TEST(); #else CRYPT_EAL_MdCTX *mdCtx = NULL; TestMemInit(); CRYPT_EAL_LibCtx *libCtx = CRYPT_EAL_LibCtxNew(); ASSERT_TRUE(libCtx != NULL); // 1st: A provider, 2nd: B provider, 3rd: default provider ASSERT_EQ(CRYPT_EAL_ProviderRegister(libCtx, PROVIDER_A_NAME, ProviderAInit, NULL, NULL), 0); ASSERT_EQ(CRYPT_EAL_ProviderRegister(libCtx, PROVIDER_B_NAME, ProviderBInit, NULL, NULL), 0); ASSERT_EQ(CRYPT_EAL_ProviderRegister(libCtx, PROVIDER_DEFAULT_NAME, NULL, NULL, NULL), 0); mdCtx = CRYPT_EAL_ProviderMdNewCtx(libCtx, CRYPT_MD_SHA256, NULL); ASSERT_TRUE(mdCtx != NULL); ASSERT_EQ(CRYPT_EAL_MdInit(mdCtx), PROVIDER_A_SHA256_INIT_RET); CRYPT_EAL_MdFreeCtx(mdCtx); mdCtx = CRYPT_EAL_ProviderMdNewCtx(libCtx, CRYPT_MD_MD5, NULL); ASSERT_TRUE(mdCtx != NULL); ASSERT_EQ(CRYPT_EAL_MdInit(mdCtx), PROVIDER_B_MD5_INIT_RET); CRYPT_EAL_MdFreeCtx(mdCtx); mdCtx = CRYPT_EAL_ProviderMdNewCtx(libCtx, CRYPT_MD_SHA256, "provider?default"); ASSERT_TRUE(mdCtx != NULL); ASSERT_EQ(CRYPT_EAL_MdInit(mdCtx), DEFAULT_SHA256_INIT_RET); CRYPT_EAL_MdFreeCtx(mdCtx); mdCtx = CRYPT_EAL_ProviderMdNewCtx(libCtx, CRYPT_MD_MD5, "provider=default"); ASSERT_TRUE(mdCtx != NULL); ASSERT_EQ(CRYPT_EAL_MdInit(mdCtx), DEFAULT_MD5_INIT_RET); EXIT: CRYPT_EAL_LibCtxFree(libCtx); CRYPT_EAL_MdFreeCtx(mdCtx); #endif } /* END_CASE */ /** * @test SDV_CRYPTO_PROVIDER_REG_API_TC001 * @title Api test for CRYPT_EAL_ProviderRegister * @precon None */ /* BEGIN_CASE */ void SDV_CRYPTO_PROVIDER_REG_API_TC001(void) { #ifndef HITLS_CRYPTO_PROVIDER SKIP_TEST(); #else TestMemInit(); CRYPT_EAL_LibCtx *libCtx = CRYPT_EAL_LibCtxNew(); ASSERT_TRUE(libCtx != NULL); /* Test case 1: libCtx test */ // 1.1 Test with NULL libCtx and NULL providerName ASSERT_EQ(CRYPT_EAL_ProviderRegister(NULL, NULL, ProviderAInit, NULL, NULL), CRYPT_INVALID_ARG); // 1.2 Test with NULL libCtx and valid providerName but NULL init for non-default ASSERT_EQ(CRYPT_EAL_ProviderRegister(NULL, "non_default_null_init", NULL, NULL, NULL), CRYPT_NULL_INPUT); // 1.3 libCtx is NULL (should use global context) ASSERT_EQ(CRYPT_EAL_ProviderRegister(NULL, PROVIDER_DEFAULT_NAME, NULL, NULL, NULL), CRYPT_SUCCESS); ASSERT_EQ(CRYPT_EAL_ProviderRegister(NULL, PROVIDER_DEFAULT_NAME, ProviderAInit, NULL, NULL), CRYPT_SUCCESS); /* Test case 2: provider name test */ // 2.1 Test with NULL provider name ASSERT_EQ(CRYPT_EAL_ProviderRegister(libCtx, NULL, ProviderAInit, NULL, NULL), CRYPT_INVALID_ARG); // 2.2 Test with empty provider name ASSERT_EQ(CRYPT_EAL_ProviderRegister(libCtx, "", ProviderAInit, NULL, NULL), CRYPT_INVALID_ARG); // 2.3 Test with very long provider name char longProviderName[4096]; (void)memset_s(longProviderName, sizeof(longProviderName), 'a', sizeof(longProviderName) - 1); longProviderName[sizeof(longProviderName) - 1] = '\0'; ASSERT_EQ(CRYPT_EAL_ProviderRegister(libCtx, longProviderName, ProviderAInit, NULL, NULL), CRYPT_INVALID_ARG); // 2.4 Test with special characters in provider name ASSERT_EQ(CRYPT_EAL_ProviderRegister(libCtx, "special_chars_!@#$%", ProviderAInit, NULL, NULL), CRYPT_SUCCESS); // 2.5 Register the same provider twice ASSERT_EQ(CRYPT_EAL_ProviderRegister(libCtx, PROVIDER_A_NAME, ProviderAInit, NULL, NULL), CRYPT_SUCCESS); ASSERT_EQ(CRYPT_EAL_ProviderRegister(libCtx, PROVIDER_A_NAME, ProviderAInit, NULL, NULL), CRYPT_SUCCESS); // 2.6 Test with different init function for same provider name ASSERT_EQ(CRYPT_EAL_ProviderRegister(libCtx, "same_name_different_init", ProviderAInit, NULL, NULL), CRYPT_SUCCESS); ASSERT_EQ(CRYPT_EAL_ProviderRegister(libCtx, "same_name_different_init", ProviderBInit, NULL, NULL), CRYPT_SUCCESS); // 2.7 Test that default provider can be registered multiple times ASSERT_EQ(CRYPT_EAL_ProviderRegister(libCtx, PROVIDER_DEFAULT_NAME, NULL, NULL, NULL), CRYPT_SUCCESS); ASSERT_EQ(CRYPT_EAL_ProviderRegister(libCtx, PROVIDER_DEFAULT_NAME, NULL, NULL, NULL), CRYPT_SUCCESS); /* Test case 3: Init function test */ // 3.1 For non-predefined provider, init function is NULL ASSERT_EQ(CRYPT_EAL_ProviderRegister(libCtx, "non_default_provider", NULL, NULL, NULL), CRYPT_NULL_INPUT); // 3.2 For predefined provider (default), init function can be NULL ASSERT_EQ(CRYPT_EAL_ProviderRegister(libCtx, PROVIDER_DEFAULT_NAME, NULL, NULL, NULL), CRYPT_SUCCESS); // 3.3 Test with valid param but NULL init function for non-default provider BSL_Param validParam[] = {{0}}; ASSERT_EQ(CRYPT_EAL_ProviderRegister(libCtx, "provider_valid_param_null_init", NULL, validParam, NULL), CRYPT_NULL_INPUT); /* Test case 4: mgrCtx test */ // 4.1 mgrCtx is not NULL but *mgrCtx is not NULL CRYPT_EAL_ProvMgrCtx *dummyCtx = (CRYPT_EAL_ProvMgrCtx *)0x12345678; ASSERT_EQ(CRYPT_EAL_ProviderRegister(libCtx, PROVIDER_A_NAME, ProviderAInit, NULL, &dummyCtx), CRYPT_INVALID_ARG); // 4.2 Register provider with valid mgrCtx parameter CRYPT_EAL_ProvMgrCtx *mgrCtx = NULL; ASSERT_EQ(CRYPT_EAL_ProviderRegister(libCtx, PROVIDER_B_NAME, ProviderBInit, NULL, &mgrCtx), CRYPT_SUCCESS); ASSERT_TRUE(mgrCtx != NULL); EXIT: CRYPT_EAL_LibCtxFree(libCtx); #endif } /* END_CASE */
2301_79861745/bench_create
testcode/sdv/testcase/crypto/provider/test_suite_sdv_eal_provider_reg.c
C
unknown
12,926
/* * This file is part of the openHiTLS project. * * openHiTLS is licensed under the Mulan PSL v2. * You can use this software according to the terms and conditions of the Mulan PSL v2. * You may obtain a copy of Mulan PSL v2 at: * * http://license.coscl.org.cn/MulanPSL2 * * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, * EITHER EXPRESS 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 <stdio.h> #include <time.h> #include <string.h> #include "securec.h" #include "bsl_sal.h" #include "crypt_errno.h" #include "crypt_eal_init.h" #include "crypt_eal_provider.h" #include "crypt_provider_local.h" #include "crypt_eal_implprovider.h" #include "crypt_provider.h" #include "crypt_eal_mac.h" #include "eal_mac_local.h" #include "crypt_eal_kdf.h" #include "eal_kdf_local.h" #include "crypt_eal_md.h" #include "eal_md_local.h" #include "crypt_eal_pkey.h" #include "eal_pkey_local.h" #include "test.h" #include "crypt_eal_cmvp.h" #include "crypt_errno.h" #include "bsl_sal.h" #include "bsl_list.h" #include "bsl_errno.h" #include "crypt_eal_md.h" #include "hitls_crypt_type.h" #include "hitls_cert_type.h" #include "hitls_type.h" #include "crypt_eal_entropy.h" #include "crypt_util_rand.h" /* END_HEADER */ #ifdef HITLS_CRYPTO_CMVP_SM_PURE_C #define HITLS_CRYPTO_CMVP_SM #define HITLS_SM_PROVIDER_PATH "../../output/CMVP/C/lib" #endif #ifdef HITLS_CRYPTO_CMVP_SM_ARMV8_LE #define HITLS_CRYPTO_CMVP_SM #define HITLS_SM_PROVIDER_PATH "../../output/CMVP/armv8_le/lib" #endif #ifdef HITLS_CRYPTO_CMVP_SM_X86_64 #define HITLS_CRYPTO_CMVP_SM #define HITLS_SM_PROVIDER_PATH "../../output/CMVP/x86_64/lib" #endif #ifdef HITLS_CRYPTO_CMVP_SM #define HITLS_SM_LIB_NAME "libhitls_sm.so" #define HITLS_SM_PROVIDER_ATTR "provider=sm" static CRYPT_EAL_LibCtx *SM_ProviderLoad(void) { CRYPT_EAL_LibCtx *libCtx = CRYPT_EAL_LibCtxNew(); ASSERT_TRUE(libCtx != NULL); ASSERT_EQ(CRYPT_EAL_ProviderSetLoadPath(libCtx, HITLS_SM_PROVIDER_PATH), CRYPT_SUCCESS); ASSERT_EQ(CRYPT_EAL_ProviderLoad(libCtx, 0, HITLS_SM_LIB_NAME, NULL, NULL), CRYPT_SUCCESS); ASSERT_EQ(CRYPT_EAL_ProviderRandInitCtx(libCtx, CRYPT_RAND_SM3, HITLS_SM_PROVIDER_ATTR, NULL, 0, NULL), CRYPT_SUCCESS); return libCtx; EXIT: CRYPT_EAL_LibCtxFree(libCtx); return NULL; } static void SM_ProviderUnload(CRYPT_EAL_LibCtx *ctx) { CRYPT_EAL_RandDeinitEx(ctx); CRYPT_EAL_LibCtxFree(ctx); } #endif /* HITLS_CRYPTO_CMVP_SM */ /* BEGIN_CASE */ void SDV_SM_PROVIDER_PKEY_SIGN_VERIFY_TEST_TC001() { #ifndef HITLS_CRYPTO_CMVP_SM SKIP_TEST(); #else CRYPT_EAL_LibCtx *libCtx = NULL; CRYPT_EAL_PkeyCtx *pkeyCtx = NULL; uint8_t signature[128] = {0}; uint32_t signatureLen = sizeof(signature); uint8_t testData[] = "Test data for signing and verification with ECDSA"; uint32_t testDataLen = sizeof(testData) - 1; libCtx = SM_ProviderLoad(); ASSERT_TRUE(libCtx != NULL); pkeyCtx = CRYPT_EAL_ProviderPkeyNewCtx(libCtx, CRYPT_PKEY_SM2, 0, HITLS_SM_PROVIDER_ATTR); ASSERT_TRUE(pkeyCtx != NULL); ASSERT_EQ(CRYPT_EAL_PkeyGen(pkeyCtx), CRYPT_SUCCESS); ASSERT_EQ(CRYPT_EAL_PkeySign(pkeyCtx, CRYPT_MD_SM3, testData, testDataLen, signature, &signatureLen), 0); ASSERT_TRUE(signatureLen > 0); ASSERT_EQ(CRYPT_EAL_PkeyVerify(pkeyCtx, CRYPT_MD_SM3, testData, testDataLen, signature, signatureLen), CRYPT_SUCCESS); EXIT: CRYPT_EAL_PkeyFreeCtx(pkeyCtx); SM_ProviderUnload(libCtx); return; #endif } /* END_CASE */ /* BEGIN_CASE */ void SDV_SM_PROVIDER_DRBG_TEST_TC001(int algId) { #ifndef HITLS_CRYPTO_CMVP_SM (void)algId; SKIP_TEST(); #else CRYPT_EAL_RndCtx *randCtx = NULL; CRYPT_EAL_LibCtx *libCtx = NULL; libCtx = SM_ProviderLoad(); ASSERT_TRUE(libCtx != NULL); randCtx = CRYPT_EAL_ProviderDrbgNewCtx(libCtx, algId, NULL, NULL); ASSERT_TRUE(randCtx != NULL); ASSERT_EQ(CRYPT_EAL_DrbgInstantiate(randCtx, NULL, 0), CRYPT_SUCCESS); uint8_t data[16] = {0}; uint32_t dataLen = sizeof(data); ASSERT_EQ(CRYPT_EAL_Drbgbytes(randCtx, data, dataLen), CRYPT_SUCCESS); ASSERT_EQ(CRYPT_EAL_DrbgSeed(randCtx), CRYPT_SUCCESS); ASSERT_EQ(CRYPT_EAL_Drbgbytes(randCtx, data, dataLen), CRYPT_SUCCESS); EXIT: CRYPT_EAL_DrbgDeinit(randCtx); SM_ProviderUnload(libCtx); #endif } /* END_CASE */ /* BEGIN_CASE */ void SDV_SM_PROVIDER_MD_TEST_TC001(int algId) { #ifndef HITLS_CRYPTO_CMVP_SM (void)algId; SKIP_TEST(); #else CRYPT_EAL_LibCtx *libCtx = NULL; CRYPT_EAL_MdCTX *mdCtx = NULL; uint8_t plaintext[128] = {0}; uint32_t plaintextLen = sizeof(plaintext); uint8_t md[128] = {0}; uint32_t mdLen = sizeof(md); libCtx = SM_ProviderLoad(); ASSERT_TRUE(libCtx != NULL); mdCtx = CRYPT_EAL_ProviderMdNewCtx(libCtx, algId, HITLS_SM_PROVIDER_ATTR); ASSERT_TRUE(mdCtx != NULL); int32_t ret = CRYPT_EAL_MdInit(mdCtx); ASSERT_EQ(ret, CRYPT_SUCCESS); ret = CRYPT_EAL_MdUpdate(mdCtx, plaintext, plaintextLen); ASSERT_EQ(ret, CRYPT_SUCCESS); ret = CRYPT_EAL_MdFinal(mdCtx, md, &mdLen); ASSERT_EQ(ret, CRYPT_SUCCESS); EXIT: CRYPT_EAL_MdFreeCtx(mdCtx); SM_ProviderUnload(libCtx); return; #endif } /* END_CASE */ /* BEGIN_CASE */ void SDV_SM_PROVIDER_MAC_TEST_TC001(int algId, int keyLen) { #ifndef HITLS_CRYPTO_CMVP_SM (void)algId; (void)keyLen; SKIP_TEST(); #else CRYPT_EAL_LibCtx *libCtx = NULL; CRYPT_EAL_MacCtx *macCtx = NULL; uint8_t macKey[32] = {0}; uint32_t macKeyLen = keyLen; uint8_t plaintext[128] = {0}; uint32_t plaintextLen = sizeof(plaintext); uint8_t mac[128] = {0}; uint32_t macLen = sizeof(mac); libCtx = SM_ProviderLoad(); ASSERT_TRUE(libCtx != NULL); macCtx = CRYPT_EAL_ProviderMacNewCtx(libCtx, algId, HITLS_SM_PROVIDER_ATTR); ASSERT_TRUE(macCtx != NULL); int32_t ret = CRYPT_EAL_MacInit(macCtx, macKey, macKeyLen); ASSERT_EQ(ret, CRYPT_SUCCESS); if (algId == CRYPT_MAC_CBC_MAC_SM4) { CRYPT_PaddingType padType = CRYPT_PADDING_ZEROS; ASSERT_EQ(CRYPT_EAL_MacCtrl(macCtx, CRYPT_CTRL_SET_CBC_MAC_PADDING, &padType, sizeof(CRYPT_PaddingType)), CRYPT_SUCCESS); } ret = CRYPT_EAL_MacUpdate(macCtx, plaintext, plaintextLen); ASSERT_EQ(ret, CRYPT_SUCCESS); ret = CRYPT_EAL_MacFinal(macCtx, mac, &macLen); ASSERT_EQ(ret, CRYPT_SUCCESS); EXIT: CRYPT_EAL_MacFreeCtx(macCtx); SM_ProviderUnload(libCtx); return; #endif } /* END_CASE */ /* BEGIN_CASE */ void SDV_SM_PROVIDER_KDF_TEST_TC001(int macId, int iter, int saltLen) { #ifndef HITLS_CRYPTO_CMVP_SM (void)macId; (void)iter; (void)saltLen; SKIP_TEST(); #else CRYPT_EAL_LibCtx *libCtx = NULL; CRYPT_EAL_KdfCTX *kdfCtx = NULL; uint8_t password[32] = {0}; uint32_t passwordLen = sizeof(password); uint8_t salt[32] = {0}; uint8_t derivedKey[32] = {0}; uint32_t derivedKeyLen = sizeof(derivedKey); libCtx = SM_ProviderLoad(); ASSERT_TRUE(libCtx != NULL); kdfCtx = CRYPT_EAL_ProviderKdfNewCtx(libCtx, CRYPT_KDF_PBKDF2, HITLS_SM_PROVIDER_ATTR); ASSERT_TRUE(kdfCtx != NULL); BSL_Param param[5] = {{0}, {0}, {0}, {0}, BSL_PARAM_END}; (void)BSL_PARAM_InitValue(&param[0], CRYPT_PARAM_KDF_MAC_ID, BSL_PARAM_TYPE_UINT32, &macId, sizeof(macId)); (void)BSL_PARAM_InitValue(&param[1], CRYPT_PARAM_KDF_PASSWORD, BSL_PARAM_TYPE_OCTETS, password, passwordLen); (void)BSL_PARAM_InitValue(&param[2], CRYPT_PARAM_KDF_SALT, BSL_PARAM_TYPE_OCTETS, salt, saltLen); (void)BSL_PARAM_InitValue(&param[3], CRYPT_PARAM_KDF_ITER, BSL_PARAM_TYPE_UINT32, &iter, sizeof(iter)); int32_t ret = CRYPT_EAL_KdfSetParam(kdfCtx, param); ASSERT_EQ(ret, CRYPT_SUCCESS); ret = CRYPT_EAL_KdfDerive(kdfCtx, derivedKey, derivedKeyLen); ASSERT_EQ(ret, CRYPT_SUCCESS); EXIT: CRYPT_EAL_KdfFreeCtx(kdfCtx); SM_ProviderUnload(libCtx); return; #endif } /* END_CASE */ /* BEGIN_CASE */ void SDV_SM_PROVIDER_CMVP_SELFTEST_Test_TC001() { #ifndef HITLS_CRYPTO_CMVP_SM SKIP_TEST(); #else CRYPT_EAL_LibCtx *libCtx = NULL; CRYPT_SelftestCtx *selftestCtx = NULL; libCtx = SM_ProviderLoad(); ASSERT_TRUE(libCtx != NULL); selftestCtx = CRYPT_CMVP_SelftestNewCtx(libCtx, HITLS_SM_PROVIDER_ATTR); ASSERT_TRUE(selftestCtx != NULL); const char *version = CRYPT_CMVP_GetVersion(selftestCtx); ASSERT_TRUE(version != NULL); BSL_Param params[3] = {{0}, BSL_PARAM_END, BSL_PARAM_END}; int32_t type = CRYPT_CMVP_KAT_TEST; ASSERT_EQ(BSL_PARAM_InitValue(&params[0], CRYPT_PARAM_CMVP_SELFTEST_TYPE, BSL_PARAM_TYPE_INT32, &type, sizeof(type)), CRYPT_SUCCESS); int32_t ret = CRYPT_CMVP_Selftest(selftestCtx, params); ASSERT_EQ(ret, CRYPT_SUCCESS); type = CRYPT_CMVP_INTEGRITY_TEST; ret = CRYPT_CMVP_Selftest(selftestCtx, params); ASSERT_EQ(ret, CRYPT_SUCCESS); type = CRYPT_CMVP_RANDOMNESS_TEST; uint8_t random[32] = {0}; uint32_t randomLen = sizeof(random); ASSERT_EQ(CRYPT_EAL_RandbytesEx(libCtx, random, randomLen), CRYPT_SUCCESS); ASSERT_EQ(BSL_PARAM_InitValue(&params[1], CRYPT_PARAM_CMVP_RANDOM, BSL_PARAM_TYPE_OCTETS, random, randomLen), CRYPT_SUCCESS); ret = CRYPT_CMVP_Selftest(selftestCtx, params); ASSERT_TRUE(ret == CRYPT_SUCCESS || ret == CRYPT_CMVP_RANDOMNESS_ERR); EXIT: CRYPT_CMVP_SelftestFreeCtx(selftestCtx); SM_ProviderUnload(libCtx); return; #endif } /* END_CASE */ /* BEGIN_CASE */ void SDV_SM_PROVIDER_CIPHPER_TEST_TC001() { #ifndef HITLS_CRYPTO_CMVP_SM SKIP_TEST(); #else CRYPT_EAL_LibCtx *libCtx = NULL; CRYPT_EAL_CipherCtx *cipherCtx = NULL; uint8_t key[32] = {0}; uint32_t keyLen = 16; uint8_t iv[32] = {0}; uint32_t ivLen = 16; uint8_t plain[] = "Test data for signing and verification with ECDSA"; uint32_t plainLen = sizeof(plainLen) - 1; uint8_t cipher[128] = {0}; uint32_t cipherLen = sizeof(cipher); libCtx = SM_ProviderLoad(); ASSERT_TRUE(libCtx != NULL); cipherCtx = CRYPT_EAL_ProviderCipherNewCtx(libCtx, CRYPT_CIPHER_SM4_CBC, HITLS_SM_PROVIDER_ATTR); ASSERT_TRUE(cipherCtx != NULL); int32_t ret = CRYPT_EAL_CipherInit(cipherCtx, key, keyLen, iv, ivLen, true); ASSERT_EQ(ret, CRYPT_SUCCESS); ret = CRYPT_EAL_CipherSetPadding(cipherCtx, CRYPT_PADDING_PKCS7); ASSERT_EQ(ret, CRYPT_SUCCESS); uint32_t tmpLen = cipherLen; ret = CRYPT_EAL_CipherUpdate(cipherCtx, plain, plainLen, cipher, &tmpLen); ASSERT_EQ(ret, CRYPT_SUCCESS); cipherLen = tmpLen; tmpLen = sizeof(cipher) - cipherLen; ret = CRYPT_EAL_CipherFinal(cipherCtx, cipher + cipherLen, &tmpLen); ASSERT_EQ(ret, CRYPT_SUCCESS); cipherLen += tmpLen; EXIT: CRYPT_EAL_CipherFreeCtx(cipherCtx); SM_ProviderUnload(libCtx); return; #endif } /* END_CASE */ /* BEGIN_CASE */ void SDV_SM_PROVIDER_KDF_PARAM_CHECK_TC001() { #ifndef HITLS_CRYPTO_CMVP_SM SKIP_TEST(); #else CRYPT_EAL_LibCtx *libCtx = NULL; CRYPT_EAL_KdfCTX *kdfCtx = NULL; uint8_t password[32] = {0}; uint32_t passwordLen = sizeof(password); uint8_t salt[32] = {0}; uint8_t derivedKey[32] = {0}; libCtx = SM_ProviderLoad(); ASSERT_TRUE(libCtx != NULL); kdfCtx = CRYPT_EAL_ProviderKdfNewCtx(libCtx, CRYPT_KDF_PBKDF2, HITLS_SM_PROVIDER_ATTR); ASSERT_TRUE(kdfCtx != NULL); int32_t iter = 1024; int32_t saltLen = 8; int32_t macId = CRYPT_MAC_HMAC_SHA256; BSL_Param param[5] = {{0}, {0}, {0}, {0}, BSL_PARAM_END}; (void)BSL_PARAM_InitValue(&param[0], CRYPT_PARAM_KDF_MAC_ID, BSL_PARAM_TYPE_UINT32, &macId, sizeof(macId)); (void)BSL_PARAM_InitValue(&param[1], CRYPT_PARAM_KDF_PASSWORD, BSL_PARAM_TYPE_OCTETS, password, passwordLen); (void)BSL_PARAM_InitValue(&param[2], CRYPT_PARAM_KDF_SALT, BSL_PARAM_TYPE_OCTETS, salt, saltLen); (void)BSL_PARAM_InitValue(&param[3], CRYPT_PARAM_KDF_ITER, BSL_PARAM_TYPE_UINT32, &iter, sizeof(iter)); int32_t ret = CRYPT_EAL_KdfSetParam(kdfCtx, param); ASSERT_EQ(ret, CRYPT_CMVP_ERR_PARAM_CHECK); macId = CRYPT_MAC_HMAC_SM3; ASSERT_EQ(CRYPT_EAL_KdfSetParam(kdfCtx, param), CRYPT_SUCCESS); iter = 1023; ASSERT_EQ(CRYPT_EAL_KdfSetParam(kdfCtx, param), CRYPT_CMVP_ERR_PARAM_CHECK); iter = 1024; ASSERT_EQ(CRYPT_EAL_KdfSetParam(kdfCtx, param), CRYPT_SUCCESS); saltLen = 7; (void)BSL_PARAM_InitValue(&param[2], CRYPT_PARAM_KDF_SALT, BSL_PARAM_TYPE_OCTETS, salt, saltLen); ASSERT_EQ(CRYPT_EAL_KdfSetParam(kdfCtx, param), CRYPT_CMVP_ERR_PARAM_CHECK); saltLen = 8; (void)BSL_PARAM_InitValue(&param[2], CRYPT_PARAM_KDF_SALT, BSL_PARAM_TYPE_OCTETS, salt, saltLen); ASSERT_EQ(CRYPT_EAL_KdfSetParam(kdfCtx, param), CRYPT_SUCCESS); uint32_t derivedKeyLen = 1; ret = CRYPT_EAL_KdfDerive(kdfCtx, derivedKey, derivedKeyLen); ASSERT_EQ(ret, CRYPT_SUCCESS); EXIT: CRYPT_EAL_KdfFreeCtx(kdfCtx); SM_ProviderUnload(libCtx); return; #endif } /* END_CASE */ /* BEGIN_CASE */ void SDV_SM_PROVIDER_SM2_CHECK_TEST_TC001() { #ifndef HITLS_CRYPTO_CMVP_SM SKIP_TEST(); #else CRYPT_EAL_LibCtx *libCtx = NULL; CRYPT_EAL_PkeyCtx *pkeyCtx = NULL; libCtx = SM_ProviderLoad(); ASSERT_TRUE(libCtx != NULL); pkeyCtx = CRYPT_EAL_ProviderPkeyNewCtx(libCtx, CRYPT_PKEY_SM2, 0, HITLS_SM_PROVIDER_ATTR); ASSERT_TRUE(pkeyCtx != NULL); ASSERT_EQ(CRYPT_EAL_PkeyGen(pkeyCtx), CRYPT_SUCCESS); ASSERT_EQ(CRYPT_EAL_PkeyPrvCheck(pkeyCtx), CRYPT_SUCCESS); ASSERT_EQ(CRYPT_EAL_PkeyPairCheck(pkeyCtx, pkeyCtx), CRYPT_SUCCESS); EXIT: CRYPT_EAL_PkeyFreeCtx(pkeyCtx); SM_ProviderUnload(libCtx); return; #endif } /* END_CASE */
2301_79861745/bench_create
testcode/sdv/testcase/crypto/provider/test_suite_sdv_eal_sm_provider.c
C
unknown
13,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 <stdint.h> #include <stddef.h> #include <stdbool.h> #include <pthread.h> #include "crypt_bn.h" #include "bsl_sal.h" #include "crypt_algid.h" #include "crypt_types.h" #include "crypt_eal_pkey.h" #include "crypt_errno.h" #include "stub_replace.h" #include "crypt_eal_rand.h" #include "crypt_util_rand.h" #include "eal_pkey_local.h" #include "crypt_rsa.h" #include "rsa_local.h" #include "bn_basic.h" #include "securec.h" #define SUCCESS 0 #define FAIL (-1) #define RSA_MAX_KEYLEN 2048 #define RSA_MIN_KEYLEN 128 #define MAX_PARAM_LEN 2048 #define MAX_CIPHERTEXT_LEN 2048 #define PUB_EXP 3 #define KEYLEN_IN_BYTES(keyLen) ((keyLen) >> 3) int32_t RandFunc(uint8_t *randNum, uint32_t randLen) { const int maxNum = 255; for (uint32_t i = 0; i < randLen; i++) { randNum[i] = (uint8_t)(rand() % maxNum); } return 0; } int32_t RandFuncEx(void *libCtx, uint8_t *randNum, uint32_t randLen) { (void)libCtx; const int maxNum = 255; for (uint32_t i = 0; i < randLen; i++) { randNum[i] = (uint8_t)(rand() % maxNum); } return 0; } void *malloc_fail(uint32_t size) { (void)size; return NULL; } void PubkeyFree(CRYPT_EAL_PkeyPub *pubkey) { if (pubkey == NULL) { return; } free(pubkey); } void PrvkeyFree(CRYPT_EAL_PkeyPrv *prvkey) { if (prvkey == NULL) { return; } free(prvkey); } #define TMP_BUFF_LEN 2048 static uint8_t g_RandBuf[TMP_BUFF_LEN]; int32_t STUB_ReplaceRandom(uint8_t *r, uint32_t randLen) { if (randLen > TMP_BUFF_LEN) { return -1; } for (uint32_t i = 0; i < randLen; i++) { r[i] = g_RandBuf[i]; } return 0; } int32_t STUB_ReplaceRandomEx(void *libCtx, uint8_t *r, uint32_t randLen) { (void)libCtx; if (randLen > TMP_BUFF_LEN) { return -1; } for (uint32_t i = 0; i < randLen; i++) { r[i] = g_RandBuf[i]; } return 0; } void SetRsaPara(CRYPT_EAL_PkeyPara *para, uint8_t *e, uint32_t eLen, uint32_t bits) { para->id = CRYPT_PKEY_RSA; para->para.rsaPara.e = e; para->para.rsaPara.eLen = eLen; para->para.rsaPara.bits = bits; } void SetRsaPubKey(CRYPT_EAL_PkeyPub *pubKey, uint8_t *n, uint32_t nLen, uint8_t *e, uint32_t eLen) { pubKey->id = CRYPT_PKEY_RSA; pubKey->key.rsaPub.n = n; pubKey->key.rsaPub.nLen = nLen; pubKey->key.rsaPub.e = e; pubKey->key.rsaPub.eLen = eLen; } void SetRsaPrvKey(CRYPT_EAL_PkeyPrv *prvKey, uint8_t *n, uint32_t nLen, uint8_t *d, uint32_t dLen) { prvKey->id = CRYPT_PKEY_RSA; prvKey->key.rsaPrv.n = n; prvKey->key.rsaPrv.nLen = nLen; prvKey->key.rsaPrv.d = d; prvKey->key.rsaPrv.dLen = dLen; }
2301_79861745/bench_create
testcode/sdv/testcase/crypto/rsa/test_suite_sdv_eal_rsa.base.c
C
unknown
3,217
/* * This file is part of the openHiTLS project. * * openHiTLS is licensed under the Mulan PSL v2. * You can use this software according to the terms and conditions of the Mulan PSL v2. * You may obtain a copy of Mulan PSL v2 at: * * http://license.coscl.org.cn/MulanPSL2 * * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, * EITHER EXPRESS 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 test_suite_sdv_eal_rsa */ /* BEGIN_HEADER */ #include "bsl_params.h" #include "bsl_err.h" #include "crypt_params_key.h" #include "bn_bincal.h" #include "bn_basic.h" /* END_HEADER */ #define CRYPT_EAL_PKEY_KEYMGMT_OPERATE 0 /** * @test SDV_CRYPTO_RSA_NEW_API_TC001 * @title RSA CRYPT_EAL_PkeyNewCtx test. * @precon nan * @brief * 1. Call the CRYPT_EAL_PkeyNewCtx method to create ctx, algId is CRYPT_PKEY_RSA, expected result 1. * 2. Release the ctx. * 3. Repeat steps 1 to 2 for 100 times. * @expect * 1. The returned result is not empty. */ /* BEGIN_CASE */ void SDV_CRYPTO_RSA_NEW_API_TC001(int isProvider) { TestMemInit(); CRYPT_EAL_PkeyCtx *pkey = NULL; /* Run 100 times */ for (int i = 0; i < 100; i++) { pkey = TestPkeyNewCtx(NULL, CRYPT_PKEY_RSA, CRYPT_EAL_PKEY_KEYMGMT_OPERATE, "provider=default", isProvider); ASSERT_TRUE(pkey != NULL); CRYPT_EAL_PkeyFreeCtx(pkey); } EXIT: return; } /* END_CASE */ /** * @test SDV_CRYPTO_RSA_NEW_API_TC002 * @title RSA CRYPT_EAL_PkeyNewCtx test: Malloc failed. * @precon Mock BSL_SAL_Malloc to malloc_fail. * @brief * 1. Call the CRYPT_EAL_PkeyNewCtx method to create ctx, algId is CRYPT_PKEY_RSA, expected result 1. * 2. Release the ctx. * 3. Reset the BSL_SAL_Malloc. * @expect * 1. Failed to create the ctx. */ /* BEGIN_CASE */ void SDV_CRYPTO_RSA_NEW_API_TC002(int isProvider) { CRYPT_EAL_PkeyCtx *pkey = NULL; FuncStubInfo tmpRpInfo = {0}; STUB_Init(); ASSERT_TRUE(STUB_Replace(&tmpRpInfo, BSL_SAL_Malloc, malloc_fail) == 0); TestMemInit(); pkey = TestPkeyNewCtx(NULL, CRYPT_PKEY_RSA, CRYPT_EAL_PKEY_KEYMGMT_OPERATE, "provider=default", isProvider); ASSERT_TRUE(pkey == NULL); EXIT: STUB_Reset(&tmpRpInfo); CRYPT_EAL_PkeyFreeCtx(pkey); } /* END_CASE */ /** * @test SDV_CRYPTO_RSA_PARA_API_TC001 * @title RSA CRYPT_EAL_PkeySetPara: The e value of para is invalid. * @precon Create the contexts of the rsa algorithm. * @brief * 1. Call the CRYPT_EAL_PkeySetPara method: * (1) e = NULL, expected result 1. * (2) e len = 0, expected result 1. * (3) e = 0, expected result 2. * (4) e is even, expected result 2. * (5) e len = 1025, expected result 1. * @expect * 1. CRYPT_EAL_ERR_NEW_PARA_FAIL * 2. CRYPT_RSA_ERR_E_VALUE */ /* BEGIN_CASE */ void SDV_CRYPTO_RSA_PARA_API_TC001(int isProvider) { uint8_t e[] = {1, 0, 1}; uint8_t e2[] = {1, 0}; uint8_t e0[] = {0, 0, 0}; uint8_t longE[1025] = {0}; longE[0] = 0x01; longE[1024] = 0x01; // The tail of 1024 is set to 1. CRYPT_EAL_PkeyPara para = {0}; CRYPT_EAL_PkeyCtx *pkey = NULL; SetRsaPara(&para, e, 3, 1024); // bits: 1024 is valid TestMemInit(); pkey = TestPkeyNewCtx(NULL, CRYPT_PKEY_RSA, CRYPT_EAL_PKEY_KEYMGMT_OPERATE, "provider=default", isProvider); ASSERT_TRUE(pkey != NULL); para.para.rsaPara.e = NULL; ASSERT_TRUE_AND_LOG("e = NULL", CRYPT_EAL_PkeySetPara(pkey, &para) == CRYPT_EAL_ERR_NEW_PARA_FAIL); para.para.rsaPara.eLen = 0; ASSERT_TRUE_AND_LOG("e len = 0", CRYPT_EAL_PkeySetPara(pkey, &para) == CRYPT_EAL_ERR_NEW_PARA_FAIL); para.para.rsaPara.e = e0; para.para.rsaPara.eLen = 1; ASSERT_TRUE_AND_LOG("e = 0", CRYPT_EAL_PkeySetPara(pkey, &para) == CRYPT_RSA_ERR_E_VALUE); para.para.rsaPara.eLen = 2; para.para.rsaPara.e = e2; ASSERT_TRUE_AND_LOG("e is even", CRYPT_EAL_PkeySetPara(pkey, &para) == CRYPT_RSA_ERR_E_VALUE); para.para.rsaPara.eLen = 1025; // 1025 is invalid, but the length is sufficient. para.para.rsaPara.e = longE; ASSERT_TRUE_AND_LOG("e len = 1025", CRYPT_EAL_PkeySetPara(pkey, &para) == CRYPT_EAL_ERR_NEW_PARA_FAIL); EXIT: CRYPT_EAL_PkeyFreeCtx(pkey); } /* END_CASE */ /** * @test SDV_CRYPTO_RSA_PARA_API_TC002 * @title RSA CRYPT_EAL_PkeySetPara: The bits value of para is invalid. * @precon Create the contexts of the rsa algorithm. * @brief * 1. Call the CRYPT_EAL_PkeySetPara method with invalid bits, expected result 1. * @expect * 1. CRYPT_EAL_ERR_NEW_PARA_FAIL */ /* BEGIN_CASE */ void SDV_CRYPTO_RSA_PARA_API_TC002(int bits, int isProvider) { uint8_t e[] = {1, 0, 1}; CRYPT_EAL_PkeyPara para = {0}; SetRsaPara(&para, e, 3, bits); // eLen = 3 TestMemInit(); CRYPT_EAL_PkeyCtx *pkey = NULL; pkey = TestPkeyNewCtx(NULL, CRYPT_PKEY_RSA, CRYPT_EAL_PKEY_KEYMGMT_OPERATE, "provider=default", isProvider); ASSERT_TRUE(pkey != NULL); ASSERT_EQ(CRYPT_EAL_PkeySetPara(pkey, &para), CRYPT_EAL_ERR_NEW_PARA_FAIL); EXIT: CRYPT_EAL_PkeyFreeCtx(pkey); } /* END_CASE */ /** * @test SDV_CRYPTO_RSA_PARA_API_TC003 * @title RSA CRYPT_EAL_PkeySetPara: Success. * @precon Create the contexts of the rsa algorithm. * @brief * 1. Call the CRYPT_EAL_PkeySetPara method, key len is 1024|1025|5120|16384 bits, expected result 1. * @expect * 1. CRYPT_SUCCESS */ /* BEGIN_CASE */ void SDV_CRYPTO_RSA_PARA_API_TC003(int isProvider) { uint8_t e3[] = {1, 0, 1}; uint8_t e5[] = {1, 0, 0, 0, 1}; uint8_t e7[] = {1, 0, 0, 0, 0, 0, 1}; CRYPT_EAL_PkeyPara para = {0}; CRYPT_EAL_PkeyCtx *pkey = NULL; TestMemInit(); pkey = TestPkeyNewCtx(NULL, CRYPT_PKEY_RSA, CRYPT_EAL_PKEY_KEYMGMT_OPERATE + CRYPT_EAL_PKEY_SIGN_OPERATE, "provider=default", isProvider); ASSERT_TRUE(pkey != NULL); SetRsaPara(&para, e3, 3, 1024); // Valid parameters: elen = 3, bits =1024 ASSERT_TRUE_AND_LOG("1k key", CRYPT_EAL_PkeySetPara(pkey, &para) == CRYPT_SUCCESS); para.para.rsaPara.bits = 1025; ASSERT_TRUE_AND_LOG("1025 bits key", CRYPT_EAL_PkeySetPara(pkey, &para) == CRYPT_SUCCESS); SetRsaPara(&para, e5, 5, 5120); ASSERT_TRUE_AND_LOG("5k key", CRYPT_EAL_PkeySetPara(pkey, &para) == CRYPT_SUCCESS); SetRsaPara(&para, e7, 7, 16384); ASSERT_TRUE_AND_LOG("16k key", CRYPT_EAL_PkeySetPara(pkey, &para) == CRYPT_SUCCESS); EXIT: CRYPT_EAL_PkeyFreeCtx(pkey); } /* END_CASE */ /** * @test SDV_CRYPTO_RSA_GEN_API_TC001 * @title RSA CRYPT_EAL_PkeyGen: No regist rand. * @precon Create the contexts of the rsa algorithm and set para. * @brief * 1. Call the CRYPT_EAL_PkeyGen method to generate a key pair, expected result 1. * @expect * 1. Failed to genrate a key pair, the return value is CRYPT_NO_REGIST_RAND. */ /* BEGIN_CASE */ void SDV_CRYPTO_RSA_GEN_API_TC001(int isProvider) { uint8_t e[] = {1, 0, 1}; CRYPT_EAL_PkeyPara para = {0}; SetRsaPara(&para, e, 3, 1024); // Valid parameters: elen = 3, bits =1024 TestMemInit(); CRYPT_EAL_PkeyCtx *pkey = NULL; pkey = TestPkeyNewCtx(NULL, CRYPT_PKEY_RSA, CRYPT_EAL_PKEY_KEYMGMT_OPERATE, "provider=default", isProvider); ASSERT_TRUE(pkey != NULL); ASSERT_TRUE(CRYPT_EAL_PkeySetPara(pkey, &para) == CRYPT_SUCCESS); ASSERT_EQ(CRYPT_EAL_PkeyGen(pkey), CRYPT_NO_REGIST_RAND); EXIT: CRYPT_EAL_PkeyFreeCtx(pkey); } /* END_CASE */ /** * @test SDV_CRYPTO_RSA_GET_PUB_API_TC001 * @title RSA CRYPT_EAL_PkeyGetPub test. * @precon 1. Create the context of the rsa algorithm. * 2. Initialize the DRBG. * @brief * 1. Call the CRYPT_EAL_PkeyGetPub method without public key, expected result 1 * 2. Set para and generate a key pair, expected result 2 * 3. Call the CRYPT_EAL_PkeyGetPub method: * (1) pkey = NULL, expected result 1. * (2) pub = NULL, expected result 1. * (3) n = NULL, expected result 1. * (4) n != NULL and nLen = 0, expected result 3. * (5) e = NULL, expected result 1. * (6) e != NULL, eLen = 0, expected result 3. * @expect * 1. CRYPT_NULL_INPUT * 2. CRYPT_SUCCESS * 3. CRYPT_BN_BUFF_LEN_NOT_ENOUGH */ /* BEGIN_CASE */ void SDV_CRYPTO_RSA_GET_PUB_API_TC001(int isProvider) { CRYPT_EAL_PkeyCtx *pkey = NULL; uint8_t e[] = {1, 0, 1}; CRYPT_EAL_PkeyPara para = {0}; CRYPT_EAL_PkeyPub pubKey = {0}; uint8_t pubE[600]; uint8_t pubN[600]; SetRsaPara(&para, e, 3, 1024); SetRsaPubKey(&pubKey, pubE, 600, pubN, 600); // 600 bytes > 1024 bits TestMemInit(); ASSERT_EQ(TestRandInit(), CRYPT_SUCCESS); pkey = TestPkeyNewCtx(NULL, CRYPT_PKEY_RSA, CRYPT_EAL_PKEY_KEYMGMT_OPERATE, "provider=default", isProvider); ASSERT_TRUE(pkey != NULL); /* Missing public key */ ASSERT_EQ(CRYPT_EAL_PkeyGetPub(pkey, &pubKey), CRYPT_NULL_INPUT); ASSERT_EQ(CRYPT_EAL_PkeySetPara(pkey, &para), CRYPT_SUCCESS); ASSERT_EQ(CRYPT_EAL_PkeyGen(pkey), CRYPT_SUCCESS); ASSERT_EQ(CRYPT_EAL_PkeyGetPub(NULL, &pubKey), CRYPT_NULL_INPUT); ASSERT_EQ(CRYPT_EAL_PkeyGetPub(pkey, NULL), CRYPT_NULL_INPUT); /* n = NULL */ pubKey.key.rsaPub.n = NULL; ASSERT_EQ(CRYPT_EAL_PkeyGetPub(pkey, &pubKey), CRYPT_NULL_INPUT); pubKey.key.rsaPub.n = pubN; /* n != NULL and nLen = 0 */ pubKey.key.rsaPub.nLen = 0; ASSERT_EQ(CRYPT_EAL_PkeyGetPub(pkey, &pubKey), CRYPT_BN_BUFF_LEN_NOT_ENOUGH); pubKey.key.rsaPub.nLen = 600; /* e = NULL */ pubKey.key.rsaPub.e = NULL; ASSERT_EQ(CRYPT_EAL_PkeyGetPub(pkey, &pubKey), CRYPT_NULL_INPUT); pubKey.key.rsaPub.e = pubE; /* e != NULL, eLen = 0 */ pubKey.key.rsaPub.eLen = 0; ASSERT_EQ(CRYPT_EAL_PkeyGetPub(pkey, &pubKey), CRYPT_BN_BUFF_LEN_NOT_ENOUGH); EXIT: TestRandDeInit(); CRYPT_EAL_PkeyFreeCtx(pkey); } /* END_CASE */ /** * @test SDV_CRYPTO_RSA_GET_PRV_API_TC001 * @title RSA CRYPT_EAL_PkeyGetPrv: Bad private key. * @precon 1. Create the context of the rsa algorithm. * 2. Initialize the DRBG. * @brief * 1. Call the CRYPT_EAL_PkeyGetPrv method without private key, expected result 1 * 2. Set para and generate a key pair, expected result 2 * 3. Call the CRYPT_EAL_PkeyGetPrv method: * (1) pkey = NULL, expected result 1. * (2) prv = NULL, expected result 1. * (3) p = NULL and q = NULL, expected result 2. * (4) p = NULL and q != NULL, expected result 1. * (5) p != NULL and q != NULL, expected result 2. * (6) d = NULL, expected result 1. * @expect * 1. CRYPT_NULL_INPUT * 2. CRYPT_SUCCESS */ /* BEGIN_CASE */ void SDV_CRYPTO_RSA_GET_PRV_API_TC001(int isProvider) { CRYPT_EAL_PkeyCtx *pkey = NULL; CRYPT_EAL_PkeyPrv prvKey = {0}; CRYPT_EAL_PkeyPara para = {0}; uint8_t e[] = {1, 0, 1}; uint8_t prvD[600]; uint8_t prvN[600]; uint8_t prvP[600]; uint8_t prvQ[600]; SetRsaPrvKey(&prvKey, prvN, 600, prvD, 600); SetRsaPara(&para, e, 3, 1024); TestMemInit(); ASSERT_EQ(TestRandInit(), CRYPT_SUCCESS); pkey = TestPkeyNewCtx(NULL, CRYPT_PKEY_RSA, CRYPT_EAL_PKEY_KEYMGMT_OPERATE, "provider=default", isProvider); ASSERT_TRUE(pkey != NULL); /* Missing private key */ ASSERT_EQ(CRYPT_EAL_PkeyGetPrv(pkey, &prvKey), CRYPT_NULL_INPUT); ASSERT_EQ(CRYPT_EAL_PkeySetPara(pkey, &para), CRYPT_SUCCESS); ASSERT_EQ(CRYPT_EAL_PkeyGen(pkey), CRYPT_SUCCESS); ASSERT_EQ(CRYPT_EAL_PkeyGetPrv(NULL, &prvKey), CRYPT_NULL_INPUT); ASSERT_EQ(CRYPT_EAL_PkeyGetPrv(pkey, NULL), CRYPT_NULL_INPUT); /* p is NULL and q is NULL */ ASSERT_EQ(CRYPT_EAL_PkeyGetPrv(pkey, &prvKey), CRYPT_SUCCESS); /* p = NULL and q != NULL */ prvKey.key.rsaPrv.q = prvQ; prvKey.key.rsaPrv.qLen = 600; ASSERT_EQ(CRYPT_EAL_PkeyGetPrv(pkey, &prvKey), CRYPT_NULL_INPUT); /* p != NULL and q != NULL */ prvKey.key.rsaPrv.p = prvP; prvKey.key.rsaPrv.pLen = 600; ASSERT_EQ(CRYPT_EAL_PkeyGetPrv(pkey, &prvKey), CRYPT_SUCCESS); /* d = NULL */ prvKey.key.rsaPrv.d = NULL; ASSERT_EQ(CRYPT_EAL_PkeyGetPrv(pkey, &prvKey), CRYPT_NULL_INPUT); EXIT: TestRandDeInit(); CRYPT_EAL_PkeyFreeCtx(pkey); } /* END_CASE */ /** * @test SDV_CRYPTO_RSA_SET_PRV_API_TC001 * @title RSA CRYPT_EAL_PkeySetPrv: Bad private key. * @precon Create the contexts of the rsa algorithm and set para: * pkey1: Generate a key pair. * pkey2: set the private key. * @brief * 1. Call the CRYPT_EAL_PkeySetPrv method: * (1) d is 0, expected result 1. * (2) d is 1, expected result 1. * (3) n is 0, expected result 2. * (4) p is 0, expected result 1. * (5) q is 0, expected result 1. * (6) nLen is 2049, expected result 2. * (7) p is null, expected result 3. * @expect * 1. CRYPT_RSA_ERR_INPUT_VALUE * 2. CRYPT_RSA_ERR_KEY_BITS * 3. CRYPT_RSA_NO_KEY_INFO */ /* BEGIN_CASE */ void SDV_CRYPTO_RSA_SET_PRV_API_TC001(int isProvider) { CRYPT_EAL_PkeyCtx *pkey = NULL; CRYPT_EAL_PkeyCtx *pkey2 = NULL; CRYPT_EAL_PkeyPara para = {0}; CRYPT_EAL_PkeyPrv prvKey = {0}; uint8_t e[] = {1, 0, 1}; uint8_t prvD[600]; uint8_t prvN[2500]; uint8_t prvP[600]; uint8_t prvQ[600]; uint8_t prvE[600]; SetRsaPrvKey(&prvKey, prvN, 600, prvD, 600); SetRsaPara(&para, e, 3, 1024); TestMemInit(); ASSERT_EQ(TestRandInit(), CRYPT_SUCCESS); pkey = TestPkeyNewCtx(NULL, CRYPT_PKEY_RSA, CRYPT_EAL_PKEY_KEYMGMT_OPERATE, "provider=default", isProvider); pkey2 = TestPkeyNewCtx(NULL, CRYPT_PKEY_RSA, CRYPT_EAL_PKEY_KEYMGMT_OPERATE, "provider=default", isProvider); ASSERT_TRUE(pkey != NULL && pkey2 != NULL); ASSERT_TRUE(CRYPT_EAL_PkeySetPara(pkey, &para) == CRYPT_SUCCESS); ASSERT_TRUE(CRYPT_EAL_PkeySetPara(pkey2, &para) == CRYPT_SUCCESS); ASSERT_TRUE(CRYPT_EAL_PkeyGen(pkey) == CRYPT_SUCCESS); ASSERT_TRUE(CRYPT_EAL_PkeyGetPrv(pkey, &prvKey) == CRYPT_SUCCESS); (void)memset_s(prvD, sizeof(prvD), 0x00, sizeof(prvD)); ASSERT_TRUE_AND_LOG("d is 0", CRYPT_EAL_PkeySetPrv(pkey2, &prvKey) == CRYPT_RSA_ERR_INPUT_VALUE); prvD[sizeof(prvD) - 1] = 1; ASSERT_TRUE_AND_LOG("d is 1", CRYPT_EAL_PkeySetPrv(pkey2, &prvKey) == CRYPT_RSA_ERR_INPUT_VALUE); ASSERT_TRUE(CRYPT_EAL_PkeyGetPrv(pkey, &prvKey) == CRYPT_SUCCESS); (void)memset_s(prvN, sizeof(prvN), 0x00, sizeof(prvN)); ASSERT_TRUE_AND_LOG("n is 0", CRYPT_EAL_PkeySetPrv(pkey2, &prvKey) == CRYPT_RSA_ERR_KEY_BITS); prvKey.key.rsaPrv.q = prvQ; prvKey.key.rsaPrv.qLen = 600; // 600 bytes > 1024 bits prvKey.key.rsaPrv.p = prvP; prvKey.key.rsaPrv.pLen = 600; // 600 bytes > 1024 bits ASSERT_TRUE(CRYPT_EAL_PkeyGetPrv(pkey, &prvKey) == CRYPT_SUCCESS); (void)memset_s(prvP, sizeof(prvP), 0x00, sizeof(prvP)); ASSERT_TRUE_AND_LOG("p is 0", CRYPT_EAL_PkeySetPrv(pkey2, &prvKey) == CRYPT_RSA_ERR_INPUT_VALUE); ASSERT_TRUE(CRYPT_EAL_PkeyGetPrv(pkey, &prvKey) == CRYPT_SUCCESS); (void)memset_s(prvQ, sizeof(prvQ), 0x00, sizeof(prvQ)); ASSERT_TRUE_AND_LOG("q is 0", CRYPT_EAL_PkeySetPrv(pkey2, &prvKey) == CRYPT_RSA_ERR_INPUT_VALUE); ASSERT_TRUE(CRYPT_EAL_PkeyGetPrv(pkey, &prvKey) == CRYPT_SUCCESS); prvKey.key.rsaPrv.nLen = 2049; // 2049 > MAx n len ASSERT_TRUE_AND_LOG("nLen is 2049", CRYPT_EAL_PkeySetPrv(pkey2, &prvKey) == CRYPT_RSA_ERR_KEY_BITS); prvKey.key.rsaPrv.nLen = 600; // 600 bytes > 1024 bits ASSERT_TRUE(CRYPT_EAL_PkeyGetPrv(pkey, &prvKey) == CRYPT_SUCCESS); prvKey.key.rsaPrv.p = NULL; ASSERT_TRUE_AND_LOG("p is NULL", CRYPT_EAL_PkeySetPrv(pkey2, &prvKey) == CRYPT_RSA_NO_KEY_INFO); prvKey.key.rsaPrv.p = prvP; prvKey.key.rsaPrv.e = prvE; prvKey.key.rsaPrv.eLen = 600; ASSERT_EQ(CRYPT_EAL_PkeyGetPrv(pkey, &prvKey), CRYPT_SUCCESS); ASSERT_COMPARE("rsa e", prvKey.key.rsaPrv.e, prvKey.key.rsaPrv.eLen, e, 3); ASSERT_TRUE(CRYPT_EAL_PkeySetPrv(pkey2, &prvKey) == CRYPT_SUCCESS); ASSERT_TRUE(CRYPT_EAL_PkeyGetPrv(pkey2, &prvKey) == CRYPT_SUCCESS); ASSERT_COMPARE("rsa e", prvKey.key.rsaPrv.e, prvKey.key.rsaPrv.eLen, e, 3); EXIT: TestRandDeInit(); CRYPT_EAL_PkeyFreeCtx(pkey); CRYPT_EAL_PkeyFreeCtx(pkey2); } /* END_CASE */ /** * @test SDV_CRYPTO_RSA_SET_PRV_API_TC002 * @title RSA CRYPT_EAL_PkeySetPrv: Specification test. * @precon Create the context(pkey) of the rsa algorithm. * @brief * 1. Call the CRYPT_EAL_PkeySetPrv method: * (1) d = n, expected result 1 * (2) n less than 1024 bits, expected result 2 * (3) n greater than 16384 bits, expected result 2 * (4) d greater than 16384 bits, expected result 2 * (5) d greater than n, expected result 2 * (6) Min len success case, expected result 3 * (7) Max len success case, expected result 3 * @expect * 1. CRYPT_RSA_ERR_INPUT_VALUE * 2. CRYPT_RSA_ERR_KEY_BITS * 3. CRYPT_SUCCESS */ /* BEGIN_CASE */ void SDV_CRYPTO_RSA_SET_PRV_API_TC002(int isProvider) { uint8_t prvD[2050]; // max rsa key len is 16384 bits, 16384/8 = 2048, 2050 > 2048 uint8_t prvN[2050]; // max rsa key len is 16384 bits, 16384/8 = 2048, 2050 > 2048 CRYPT_EAL_PkeyPrv prvKey = {0}; (void)memset_s(prvD, sizeof(prvD), 0xff, sizeof(prvD)); (void)memset_s(prvN, sizeof(prvN), 0xff, sizeof(prvN)); SetRsaPrvKey(&prvKey, prvN, RSA_MIN_KEYLEN, prvD, RSA_MIN_KEYLEN); TestMemInit(); CRYPT_EAL_PkeyCtx *pkey = NULL; pkey = TestPkeyNewCtx(NULL, CRYPT_PKEY_RSA, CRYPT_EAL_PKEY_KEYMGMT_OPERATE, "provider=default", isProvider); ASSERT_TRUE(pkey != NULL); ASSERT_TRUE_AND_LOG("d = n", CRYPT_EAL_PkeySetPrv(pkey, &prvKey) == CRYPT_RSA_ERR_INPUT_VALUE); prvKey.key.rsaPrv.nLen = RSA_MIN_KEYLEN - 1; ASSERT_TRUE_AND_LOG("n less than 1024 bits", CRYPT_EAL_PkeySetPrv(pkey, &prvKey) == CRYPT_RSA_ERR_KEY_BITS); prvKey.key.rsaPrv.nLen = RSA_MAX_KEYLEN + 1; ASSERT_TRUE_AND_LOG("n greater than 16384 bits", CRYPT_EAL_PkeySetPrv(pkey, &prvKey) == CRYPT_RSA_ERR_KEY_BITS); prvKey.key.rsaPrv.nLen = RSA_MAX_KEYLEN; prvKey.key.rsaPrv.dLen = RSA_MAX_KEYLEN + 1; ASSERT_TRUE_AND_LOG("d greater than 16384 bits", CRYPT_EAL_PkeySetPrv(pkey, &prvKey) == CRYPT_RSA_ERR_KEY_BITS); prvKey.key.rsaPrv.nLen = RSA_MIN_KEYLEN; prvKey.key.rsaPrv.dLen = RSA_MIN_KEYLEN + 1; ASSERT_TRUE_AND_LOG("d greater than n", CRYPT_EAL_PkeySetPrv(pkey, &prvKey) == CRYPT_RSA_ERR_KEY_BITS); prvKey.key.rsaPrv.dLen = RSA_MIN_KEYLEN; prvD[0] = 0; ASSERT_TRUE_AND_LOG("Min len success case", CRYPT_EAL_PkeySetPrv(pkey, &prvKey) == CRYPT_SUCCESS); prvKey.key.rsaPrv.nLen = RSA_MAX_KEYLEN; prvKey.key.rsaPrv.dLen = RSA_MAX_KEYLEN; ASSERT_TRUE_AND_LOG("Max len success case", CRYPT_EAL_PkeySetPrv(pkey, &prvKey) == CRYPT_SUCCESS); EXIT: CRYPT_EAL_PkeyFreeCtx(pkey); } /* END_CASE */ /** * @test SDV_CRYPTO_RSA_SET_PUB_API_TC001 * @title RSA CRYPT_EAL_PkeyGetPub: Bad public key. * @precon Create the contexts of the rsa algorithm and set para: * pkey1: Generate a key pair. * pkey2: Set the public key.. * @brief * 1. Call the CRYPT_EAL_PkeyGetPub method: * (1) nLen > maxNLen, expected result 1 * (2) n is Null, expected result 2 * (3) n is 0, expected result 1 * (4) e is NULL, expected result 2 * (5) e is 0, expected result 3 * @ex pect * 1. CRYPT_RSA_ERR_KEY_BITS * 2. CRYPT_NULL_INPUT * 3. CRYPT_RSA_ERR_INPUT_VALUE */ /* BEGIN_CASE */ void SDV_CRYPTO_RSA_SET_PUB_API_TC001(int isProvider) { uint8_t e[] = {1, 0, 1}; CRYPT_EAL_PkeyCtx *pkey = NULL; CRYPT_EAL_PkeyCtx *pkey2 = NULL; CRYPT_EAL_PkeyPara para = {0}; CRYPT_EAL_PkeyPub pubKey; uint8_t pubE[600]; uint8_t pubN[2500]; SetRsaPara(&para, e, 3, 1024); SetRsaPubKey(&pubKey, pubN, 600, pubE, 600); TestMemInit(); ASSERT_EQ(TestRandInit(), CRYPT_SUCCESS); pkey = TestPkeyNewCtx(NULL, CRYPT_PKEY_RSA, CRYPT_EAL_PKEY_KEYMGMT_OPERATE, "provider=default", isProvider); pkey2 = TestPkeyNewCtx(NULL, CRYPT_PKEY_RSA, CRYPT_EAL_PKEY_KEYMGMT_OPERATE, "provider=default", isProvider); ASSERT_TRUE(pkey != NULL && pkey2 != NULL); ASSERT_TRUE(CRYPT_EAL_PkeySetPara(pkey, &para) == CRYPT_SUCCESS); ASSERT_TRUE(CRYPT_EAL_PkeySetPara(pkey2, &para) == CRYPT_SUCCESS); ASSERT_TRUE(CRYPT_EAL_PkeyGen(pkey) == CRYPT_SUCCESS); ASSERT_TRUE(CRYPT_EAL_PkeyGetPub(pkey, &pubKey) == CRYPT_SUCCESS); pubKey.key.rsaPub.nLen = 2049; ASSERT_TRUE_AND_LOG("nLen > maxNLen", CRYPT_EAL_PkeySetPub(pkey2, &pubKey) == CRYPT_RSA_ERR_KEY_BITS); pubKey.key.rsaPub.nLen = 600; // 600 bytes > 1024 bits ASSERT_TRUE(CRYPT_EAL_PkeyGetPub(pkey, &pubKey) == CRYPT_SUCCESS); pubKey.key.rsaPub.n = NULL; ASSERT_TRUE_AND_LOG("n is Null", CRYPT_EAL_PkeySetPub(pkey2, &pubKey) == CRYPT_NULL_INPUT); pubKey.key.rsaPub.n = pubN; ASSERT_TRUE(CRYPT_EAL_PkeyGetPub(pkey, &pubKey) == CRYPT_SUCCESS); (void)memset_s(pubN, sizeof(pubN), 0x00, sizeof(pubN)); ASSERT_TRUE_AND_LOG("n is 0", CRYPT_EAL_PkeySetPub(pkey2, &pubKey) == CRYPT_RSA_ERR_KEY_BITS); ASSERT_TRUE(CRYPT_EAL_PkeyGetPub(pkey, &pubKey) == CRYPT_SUCCESS); pubKey.key.rsaPub.e = NULL; ASSERT_TRUE_AND_LOG("e is Null", CRYPT_EAL_PkeySetPub(pkey2, &pubKey) == CRYPT_NULL_INPUT); pubKey.key.rsaPub.e = pubE; ASSERT_TRUE(CRYPT_EAL_PkeyGetPub(pkey, &pubKey) == CRYPT_SUCCESS); (void)memset_s(pubE, sizeof(pubE), 0x00, sizeof(pubE)); ASSERT_TRUE_AND_LOG("e is 0", CRYPT_EAL_PkeySetPub(pkey2, &pubKey) == CRYPT_RSA_ERR_INPUT_VALUE); EXIT: TestRandDeInit(); CRYPT_EAL_PkeyFreeCtx(pkey); CRYPT_EAL_PkeyFreeCtx(pkey2); } /* END_CASE */ /** * @test SDV_CRYPTO_RSA_SET_PUB_API_TC002 * @title RSA CRYPT_EAL_PkeySetPub: Specification test. * @precon Create the context(pkey) of the rsa algorithm. * @brief * 1. Call the CRYPT_EAL_PkeySetPub method: * (1) e = n, expected result 1 * (2) nLen < 1024 bits, expected result 2 * (3) eLen > 16384 bits, expected result 2 * (3) nLen > 16384 bits, expected result 2 * (4) e > n, expected result 2 * (6) Min len success case, expected result 3 * (7) Max len success case, expected result 3 * (8) e = 1, expected result 1 * (9) n = 1, expected result 1 * @expect * 1. CRYPT_RSA_ERR_INPUT_VALUE * 2. CRYPT_RSA_ERR_KEY_BITS * 3. CRYPT_SUCCESS */ /* BEGIN_CASE */ void SDV_CRYPTO_RSA_SET_PUB_API_TC002(int isProvider) { uint8_t pubE[2050]; // max rsa key len is 16384 bits, 16384/8 = 2048, 2050 > 2048 uint8_t pubN[2050]; // max rsa key len is 16384 bits, 16384/8 = 2048, 2050 > 2048 CRYPT_EAL_PkeyCtx *pkey = NULL; CRYPT_EAL_PkeyPub pubKey = {0}; SetRsaPubKey(&pubKey, pubN, RSA_MIN_KEYLEN, pubE, RSA_MIN_KEYLEN); TestMemInit(); pkey = TestPkeyNewCtx(NULL, CRYPT_PKEY_RSA, CRYPT_EAL_PKEY_KEYMGMT_OPERATE, "provider=default", isProvider); ASSERT_TRUE(pkey != NULL); (void)memset_s(pubE, sizeof(pubE), 0xff, sizeof(pubE)); (void)memset_s(pubN, sizeof(pubN), 0xff, sizeof(pubN)); ASSERT_TRUE_AND_LOG("e = n", CRYPT_EAL_PkeySetPub(pkey, &pubKey) == CRYPT_RSA_ERR_INPUT_VALUE); pubKey.key.rsaPub.nLen = RSA_MIN_KEYLEN - 1; ASSERT_TRUE_AND_LOG("n less than 1024 bits", CRYPT_EAL_PkeySetPub(pkey, &pubKey) == CRYPT_RSA_ERR_KEY_BITS); pubKey.key.rsaPub.nLen = RSA_MAX_KEYLEN; pubKey.key.rsaPub.eLen = RSA_MAX_KEYLEN + 1; ASSERT_TRUE_AND_LOG("e greater than 16384 bits", CRYPT_EAL_PkeySetPub(pkey, &pubKey) == CRYPT_RSA_ERR_KEY_BITS); pubKey.key.rsaPub.nLen = RSA_MAX_KEYLEN + 1; pubKey.key.rsaPub.eLen = RSA_MAX_KEYLEN; ASSERT_TRUE_AND_LOG("n greater than 16384 bits", CRYPT_EAL_PkeySetPub(pkey, &pubKey) == CRYPT_RSA_ERR_KEY_BITS); pubKey.key.rsaPub.nLen = RSA_MIN_KEYLEN; pubKey.key.rsaPub.eLen = RSA_MIN_KEYLEN + 1; ASSERT_TRUE_AND_LOG("e greater than n", CRYPT_EAL_PkeySetPub(pkey, &pubKey) == CRYPT_RSA_ERR_KEY_BITS); pubE[0] = 0; pubKey.key.rsaPub.eLen = RSA_MIN_KEYLEN; ASSERT_TRUE_AND_LOG("Min len success case", CRYPT_EAL_PkeySetPub(pkey, &pubKey) == CRYPT_SUCCESS); pubKey.key.rsaPub.nLen = RSA_MAX_KEYLEN; pubKey.key.rsaPub.eLen = RSA_MAX_KEYLEN; ASSERT_TRUE_AND_LOG("Max len failed case", CRYPT_EAL_PkeySetPub(pkey, &pubKey) == CRYPT_RSA_ERR_KEY_BITS); (void)memset_s(pubE, sizeof(pubE), 0, sizeof(pubE)); ASSERT_TRUE_AND_LOG("e = 0", CRYPT_EAL_PkeySetPub(pkey, &pubKey) == CRYPT_RSA_ERR_INPUT_VALUE); pubE[RSA_MAX_KEYLEN - 1] = 1; ASSERT_TRUE_AND_LOG("e = 1", CRYPT_EAL_PkeySetPub(pkey, &pubKey) == CRYPT_RSA_ERR_INPUT_VALUE); EXIT: CRYPT_EAL_PkeyFreeCtx(pkey); } /* END_CASE */ /** * @test SDV_CRYPTO_RSA_ENC_API_TC001 * @title RSA CRYPT_EAL_PkeyEncrypt: Test the validity of input parameters. * @precon Create the context of the rsa algorithm: * @brief * 1. Call the CRYPT_EAL_PkeyEncrypt method without public key, expected result 1 * 2. Set pubkey and call the CRYPT_EAL_PkeyEncrypt method, expected result 2 * 3. Set the oaep paading mode, expected result 3 * 4. Call the CRYPT_EAL_PkeyEncrypt method: * (1) pkey = NULL, expected result 4 * (2) data = NULL, expected result 4 * (3) data != NULL, dataLen = 0, expected result 3 * (4) data != NULL dataLen > k - 2*hashLen - 2, expected result 5 * (5) out = NULL, expected result 4 * (6) outLen = NULL, expected result 4 * (7) outLen = 0, expected result 6 * @expect * 1. CRYPT_RSA_NO_KEY_INFO * 2. CRYPT_RSA_PAD_NO_SET_ERROR * 3. CRYPT_SUCCESS * 4. CRYPT_NULL_INPUT * 5. CRYPT_RSA_ERR_ENC_BITS * 6. CRYPT_RSA_BUFF_LEN_NOT_ENOUGH */ /* BEGIN_CASE */ void SDV_CRYPTO_RSA_ENC_API_TC001(Hex *n, Hex *e, int hashId, Hex *in, int isProvider) { uint8_t crypt[TMP_BUFF_LEN]; uint32_t cryptLen = TMP_BUFF_LEN; CRYPT_EAL_PkeyCtx *pkey = NULL; CRYPT_EAL_PkeyPub pubkey = {0}; BSL_Param oaepParam[3] = { {CRYPT_PARAM_RSA_MD_ID, BSL_PARAM_TYPE_INT32, &hashId, sizeof(hashId), 0}, {CRYPT_PARAM_RSA_MGF1_ID, BSL_PARAM_TYPE_INT32, &hashId, sizeof(hashId), 0}, BSL_PARAM_END}; SetRsaPubKey(&pubkey, n->x, n->len, e->x, e->len); TestMemInit(); ASSERT_EQ(TestRandInit(), CRYPT_SUCCESS); pkey = TestPkeyNewCtx(NULL, CRYPT_PKEY_RSA, CRYPT_EAL_PKEY_KEYMGMT_OPERATE + CRYPT_EAL_PKEY_CIPHER_OPERATE, "provider=default", isProvider); ASSERT_TRUE(pkey != NULL); ASSERT_EQ(CRYPT_EAL_PkeyEncrypt(pkey, in->x, in->len, crypt, &cryptLen), CRYPT_RSA_NO_KEY_INFO); ASSERT_TRUE(CRYPT_EAL_PkeySetPub(pkey, &pubkey) == CRYPT_SUCCESS); ASSERT_TRUE(CRYPT_EAL_PkeyEncrypt(pkey, in->x, in->len, crypt, &cryptLen) == CRYPT_RSA_PAD_NO_SET_ERROR); ASSERT_TRUE(CRYPT_EAL_PkeyCtrl(pkey, CRYPT_CTRL_SET_RSA_RSAES_OAEP, oaepParam, 0) == CRYPT_SUCCESS); ASSERT_TRUE(CRYPT_EAL_PkeyEncrypt(NULL, in->x, in->len, crypt, &cryptLen) == CRYPT_NULL_INPUT); ASSERT_TRUE(CRYPT_EAL_PkeyEncrypt(pkey, NULL, in->len, crypt, &cryptLen) == CRYPT_NULL_INPUT); ASSERT_EQ(CRYPT_EAL_PkeyEncrypt(pkey, in->x, 0, crypt, &cryptLen), CRYPT_SUCCESS); // inLen > k-2hashLen-2 , 87 = (128 - 2 * 20 - 2) ASSERT_TRUE(CRYPT_EAL_PkeyEncrypt(pkey, in->x, 87, crypt, &cryptLen) == CRYPT_RSA_ERR_ENC_BITS); ASSERT_TRUE(CRYPT_EAL_PkeyEncrypt(pkey, in->x, in->len, NULL, &cryptLen) == CRYPT_NULL_INPUT); ASSERT_TRUE(CRYPT_EAL_PkeyEncrypt(pkey, in->x, in->len, crypt, NULL) == CRYPT_NULL_INPUT); cryptLen = 0; ASSERT_TRUE(CRYPT_EAL_PkeyEncrypt(pkey, in->x, in->len, crypt, &cryptLen) == CRYPT_RSA_BUFF_LEN_NOT_ENOUGH); EXIT: CRYPT_EAL_PkeyFreeCtx(pkey); TestRandDeInit(); } /* END_CASE */ /** * @test SDV_CRYPTO_RSA_DEC_API_TC001 * @title RSA CRYPT_EAL_PkeyDecrypt: Test the validity of input parameters. * @precon Create the context of the rsa algorithm: * @brief * 1. Call the CRYPT_EAL_PkeyDecrypt method without private key, expected result 1 * 2. Set private and call the CRYPT_EAL_PkeyDecrypt method, expected result 2 * 3. Set the oaep paading mode, expected result 3 * 4. Call the CRYPT_EAL_PkeyDecrypt method: * (1) pkey = NULL, expected result 4 * (2) data = NULL, expected result 4 * (3) data != NULL, dataLen = 0, expected result 3 * (4) data != NULL, dataLen iis invalid , expected result 5 * (5) out = NULL, expected result 4 * (6) outLen = NULL, expected result 4 * (7) outLen = 0, expected result 6 * (8) outLen = 2049(invalid), expected result 6 * @expect * 1. CRYPT_RSA_NO_KEY_INFO * 2. CRYPT_RSA_PAD_NO_SET_ERROR * 3. CRYPT_SUCCESS * 4. CRYPT_NULL_INPUT * 5. CRYPT_RSA_ERR_DEC_BITS * 6. CRYPT_RSA_ERR_INPUT_VALUE */ /* BEGIN_CASE */ void SDV_CRYPTO_RSA_DEC_API_TC001(Hex *n, Hex *d, int hashId, Hex *in, int isProvider) { uint8_t crypt[TMP_BUFF_LEN]; uint32_t cryptLen = TMP_BUFF_LEN; CRYPT_EAL_PkeyPrv prvkey = {0}; CRYPT_EAL_PkeyCtx *pkey = NULL; BSL_Param oaepParam[3] = { {CRYPT_PARAM_RSA_MD_ID, BSL_PARAM_TYPE_INT32, &hashId, sizeof(hashId), 0}, {CRYPT_PARAM_RSA_MGF1_ID, BSL_PARAM_TYPE_INT32, &hashId, sizeof(hashId), 0}, BSL_PARAM_END}; SetRsaPrvKey(&prvkey, n->x, n->len, d->x, d->len); TestMemInit(); pkey = TestPkeyNewCtx(NULL, CRYPT_PKEY_RSA, CRYPT_EAL_PKEY_KEYMGMT_OPERATE + CRYPT_EAL_PKEY_CIPHER_OPERATE, "provider=default", isProvider); ASSERT_TRUE(pkey != NULL); ASSERT_TRUE(CRYPT_EAL_PkeyDecrypt(pkey, in->x, in->len, crypt, &cryptLen) == CRYPT_RSA_NO_KEY_INFO); ASSERT_TRUE(CRYPT_EAL_PkeySetPrv(pkey, &prvkey) == CRYPT_SUCCESS); ASSERT_EQ(CRYPT_EAL_PkeyDecrypt(pkey, in->x, in->len, crypt, &cryptLen), CRYPT_RSA_PAD_NO_SET_ERROR); ASSERT_TRUE(CRYPT_EAL_PkeyCtrl(pkey, CRYPT_CTRL_SET_RSA_RSAES_OAEP, oaepParam, 0) == CRYPT_SUCCESS); ASSERT_TRUE(CRYPT_EAL_PkeyDecrypt(NULL, in->x, in->len, crypt, &cryptLen) == CRYPT_NULL_INPUT); ASSERT_TRUE(CRYPT_EAL_PkeyDecrypt(pkey, NULL, in->len, crypt, &cryptLen) == CRYPT_NULL_INPUT); ASSERT_TRUE(CRYPT_EAL_PkeyDecrypt(pkey, in->x, 0, crypt, &cryptLen) == CRYPT_RSA_ERR_DEC_BITS); const uint32_t invalidInLen = 1025; // 1025: invalid data length ASSERT_TRUE(CRYPT_EAL_PkeyDecrypt(pkey, in->x, invalidInLen, crypt, &cryptLen) == CRYPT_RSA_ERR_DEC_BITS); ASSERT_TRUE(CRYPT_EAL_PkeyDecrypt(pkey, in->x, in->len, NULL, &cryptLen) == CRYPT_NULL_INPUT); ASSERT_TRUE(CRYPT_EAL_PkeyDecrypt(pkey, in->x, in->len, crypt, NULL) == CRYPT_NULL_INPUT); cryptLen = 0; ASSERT_TRUE(CRYPT_EAL_PkeyDecrypt(pkey, in->x, in->len, crypt, &cryptLen) == CRYPT_RSA_ERR_INPUT_VALUE); cryptLen = 2049; // 2049 is an invalid data length. ASSERT_TRUE(CRYPT_EAL_PkeyDecrypt(pkey, in->x, in->len, crypt, &cryptLen) == CRYPT_RSA_ERR_INPUT_VALUE); EXIT: CRYPT_EAL_PkeyFreeCtx(pkey); } /* END_CASE */ /** * @test SDV_CRYPTO_RSA_CTRL_API_TC001 * @title Rsa CRYPT_EAL_PkeyCtrl test. * @precon Create the context of the rsa algorithm and set the private key(n, d). */ /* BEGIN_CASE */ void SDV_CRYPTO_RSA_CTRL_API_TC001(Hex *n, Hex *d, Hex *salt, int hashId, int isProvider) { CRYPT_EAL_PkeyCtx *pkey = NULL; CRYPT_EAL_PkeyPrv prvkey = {0}; int32_t pssSaltLen = salt->len; int32_t pssMdId = hashId; int32_t pssMgfId = hashId; BSL_Param pssParam[4] = { {CRYPT_PARAM_RSA_MD_ID, BSL_PARAM_TYPE_INT32, &pssMdId, sizeof(pssMdId), 0}, {CRYPT_PARAM_RSA_MGF1_ID, BSL_PARAM_TYPE_INT32, &pssMgfId, sizeof(pssMgfId), 0}, {CRYPT_PARAM_RSA_SALTLEN, BSL_PARAM_TYPE_INT32, &pssSaltLen, sizeof(pssSaltLen), 0}, BSL_PARAM_END}; int32_t pkcsv15 = hashId; uint8_t badSalt[2500]; (void)memset_s(badSalt, sizeof(badSalt), 'A', sizeof(badSalt)); const uint32_t badSaltLen = 2500; // 2500 is greater than the maximum length. SetRsaPrvKey(&prvkey, n->x, n->len, d->x, d->len); TestMemInit(); CRYPT_RandRegist(STUB_ReplaceRandom); CRYPT_RandRegistEx(STUB_ReplaceRandomEx); pkey = TestPkeyNewCtx(NULL, CRYPT_PKEY_RSA, CRYPT_EAL_PKEY_KEYMGMT_OPERATE, "provider=default", isProvider); ASSERT_TRUE(pkey != NULL); ASSERT_EQ(CRYPT_EAL_PkeySetPrv(pkey, &prvkey), CRYPT_SUCCESS); // OAEP The parameter is a null pointer. ASSERT_EQ(CRYPT_EAL_PkeyCtrl(pkey, CRYPT_CTRL_SET_RSA_RSAES_OAEP, NULL, 0), CRYPT_NULL_INPUT); // PKCS1.5 The parameter is a null pointer. ASSERT_EQ(CRYPT_EAL_PkeyCtrl(pkey, CRYPT_CTRL_SET_RSA_RSAES_PKCSV15, NULL, sizeof(pkcsv15)), CRYPT_NULL_INPUT); // PKCS1.5 The parameter length is 0. ASSERT_EQ( CRYPT_EAL_PkeyCtrl(pkey, CRYPT_CTRL_SET_RSA_RSAES_PKCSV15, &pkcsv15, 0), CRYPT_RSA_SET_EMS_PKCSV15_LEN_ERROR); ASSERT_EQ(CRYPT_EAL_PkeyCtrl(pkey, CRYPT_CTRL_SET_RSA_EMSA_PSS, NULL, 0), CRYPT_NULL_INPUT); /* PSS saltLen: - 1 - 2 - 3 0 are valid values, -4 is invalid. */ pssSaltLen = -4; ASSERT_EQ(CRYPT_EAL_PkeyCtrl(pkey, CRYPT_CTRL_SET_RSA_EMSA_PSS, pssParam, 0), CRYPT_RSA_ERR_SALT_LEN); ASSERT_EQ(CRYPT_EAL_PkeyCtrl(pkey, CRYPT_CTRL_SET_RSA_SALT, salt->x, salt->len), CRYPT_RSA_SET_SALT_NOT_PSS_ERROR); pssSaltLen = salt->len; ASSERT_EQ(CRYPT_EAL_PkeyCtrl(pkey, CRYPT_CTRL_SET_RSA_EMSA_PSS, pssParam, 0), CRYPT_SUCCESS); ASSERT_EQ(CRYPT_EAL_PkeyCtrl(pkey, CRYPT_CTRL_SET_RSA_SALT, badSalt, badSaltLen), CRYPT_RSA_ERR_SALT_LEN); ASSERT_EQ(CRYPT_EAL_PkeyCtrl(pkey, CRYPT_CTRL_SET_RSA_SALT, salt->x, salt->len), CRYPT_SUCCESS); int32_t pad = CRYPT_EMSA_PKCSV15; ASSERT_EQ(CRYPT_EAL_PkeyCtrl(pkey, CRYPT_CTRL_SET_RSA_PADDING, NULL, sizeof(pad)), CRYPT_NULL_INPUT); ASSERT_EQ(CRYPT_EAL_PkeyCtrl(pkey, CRYPT_CTRL_SET_RSA_PADDING, &pad, 2), CRYPT_INVALID_ARG); pad = 0; ASSERT_EQ(CRYPT_EAL_PkeyCtrl(pkey, CRYPT_CTRL_SET_RSA_PADDING, &pad, sizeof(pad)), CRYPT_INVALID_ARG); pad = CRYPT_RSA_PADDINGMAX; ASSERT_EQ(CRYPT_EAL_PkeyCtrl(pkey, CRYPT_CTRL_SET_RSA_PADDING, &pad, sizeof(pad)), CRYPT_INVALID_ARG); pad = CRYPT_EMSA_PKCSV15; ASSERT_EQ(CRYPT_EAL_PkeyCtrl(pkey, CRYPT_CTRL_SET_RSA_PADDING, &pad, sizeof(pad)), CRYPT_SUCCESS); pad = CRYPT_RSA_NO_PAD; ASSERT_EQ(CRYPT_EAL_PkeyCtrl(pkey, CRYPT_CTRL_SET_RSA_PADDING, &pad, sizeof(pad)), CRYPT_SUCCESS); EXIT: CRYPT_EAL_PkeyFreeCtx(pkey); TestRandDeInit(); } /* END_CASE */ /** * @test SDV_CRYPTO_RSA_CTRL_API_TC002 * @title Rsa CRYPT_EAL_PkeyCtrl test. * @precon Create the context of the rsa algorithm, set the private key(n, d) and set the padding type to pss. * @brief * 1. Call the CRYPT_EAL_PkeyCtrl method: * (1) opt = CRYPT_CTRL_GET_RSA_PADDING, val is null, expected result 1 * (2) opt = CRYPT_CTRL_GET_RSA_PADDING, expected result 2 * (3) opt = CRYPT_CTRL_GET_RSA_MD, val is null, expected result 3 * (4) opt = CRYPT_CTRL_GET_RSA_MD, expected result 4 * (5) opt = CRYPT_CTRL_GET_RSA_MGF, val is null, expected result 5 * (6) opt = CRYPT_CTRL_GET_RSA_MGF, expected result 6 * (7) opt = CRYPT_CTRL_GET_RSA_SALT, val is null, expected result 7 * (8) opt = CRYPT_CTRL_GET_RSA_SALT, expected result 8 * (9) opt = CRYPT_CTRL_CLR_RSA_FLAG, val is null, expected result 9 * (10) opt = CRYPT_CTRL_CLR_RSA_FLAG, expected result 10 * @expect * 1. CRYPT_NULL_INPUT * 2. The return value is CRYPT_SUCCESS, and the output parameter(padType) value is pss. * 3. CRYPT_NULL_INPUT * 4. The return value is CRYPT_SUCCESS, and the output parameter(mdType) value is hashId. * 5. CRYPT_NULL_INPUT * 6. The return value is CRYPT_SUCCESS, and the output parameter(mgfId) value is hashId. * 7. CRYPT_NULL_INPUT * 8. The return value is CRYPT_SUCCESS, and the output parameter(saltLen) value is para.saltLen. * 9. CRYPT_NULL_INPUT * 10. CRYPT_SUCCESS. */ /* BEGIN_CASE */ void SDV_CRYPTO_RSA_CTRL_API_TC002(Hex *n, Hex *d, int hashId, int isProvider) { uint32_t flag = CRYPT_RSA_BLINDING; CRYPT_EAL_PkeyPrv prvkey = {0}; int32_t pssSaltLen = 10; int32_t pssMdId = hashId; int32_t pssMgfId = hashId; BSL_Param pssParam[4] = { {CRYPT_PARAM_RSA_MD_ID, BSL_PARAM_TYPE_INT32, &pssMdId, sizeof(pssMdId), 0}, {CRYPT_PARAM_RSA_MGF1_ID, BSL_PARAM_TYPE_INT32, &pssMgfId, sizeof(pssMgfId), 0}, {CRYPT_PARAM_RSA_SALTLEN, BSL_PARAM_TYPE_INT32, &pssSaltLen, sizeof(pssSaltLen), 0}, BSL_PARAM_END}; CRYPT_EAL_PkeyCtx *pkey = NULL; SetRsaPrvKey(&prvkey, n->x, n->len, d->x, d->len); TestMemInit(); pkey = TestPkeyNewCtx(NULL, CRYPT_PKEY_RSA, CRYPT_EAL_PKEY_KEYMGMT_OPERATE, "provider=default", isProvider); ASSERT_TRUE(pkey != NULL); ASSERT_EQ(CRYPT_EAL_PkeySetPrv(pkey, &prvkey), CRYPT_SUCCESS); ASSERT_EQ(CRYPT_EAL_PkeyCtrl(pkey, CRYPT_CTRL_SET_RSA_EMSA_PSS, pssParam, 0), CRYPT_SUCCESS); RSA_PadType padType = 0; ASSERT_EQ(CRYPT_EAL_PkeyCtrl(pkey, CRYPT_CTRL_GET_RSA_PADDING, NULL, sizeof(RSA_PadType)), CRYPT_NULL_INPUT); ASSERT_EQ(CRYPT_EAL_PkeyCtrl(pkey, CRYPT_CTRL_GET_RSA_PADDING, &padType, sizeof(RSA_PadType)), CRYPT_SUCCESS); ASSERT_EQ(padType, CRYPT_EMSA_PSS); CRYPT_MD_AlgId mdType = 0; ASSERT_EQ(CRYPT_EAL_PkeyCtrl(pkey, CRYPT_CTRL_GET_RSA_MD, NULL, sizeof(CRYPT_MD_AlgId)), CRYPT_NULL_INPUT); ASSERT_EQ(CRYPT_EAL_PkeyCtrl(pkey, CRYPT_CTRL_GET_RSA_MD, &mdType, sizeof(CRYPT_MD_AlgId)), CRYPT_SUCCESS); ASSERT_EQ(mdType, hashId); CRYPT_MD_AlgId mgfId = 0; ASSERT_EQ(CRYPT_EAL_PkeyCtrl(pkey, CRYPT_CTRL_GET_RSA_MGF, NULL, sizeof(CRYPT_MD_AlgId)), CRYPT_NULL_INPUT); ASSERT_EQ(CRYPT_EAL_PkeyCtrl(pkey, CRYPT_CTRL_GET_RSA_MGF, &mgfId, sizeof(CRYPT_MD_AlgId)), CRYPT_SUCCESS); ASSERT_EQ(mgfId, hashId); int32_t saltLen = 0; ASSERT_EQ(CRYPT_EAL_PkeyCtrl(pkey, CRYPT_CTRL_GET_RSA_SALTLEN, NULL, sizeof(int32_t)), CRYPT_NULL_INPUT); ASSERT_EQ(CRYPT_EAL_PkeyCtrl(pkey, CRYPT_CTRL_GET_RSA_SALTLEN, &saltLen, sizeof(int32_t)), CRYPT_SUCCESS); ASSERT_EQ(saltLen, pssSaltLen); ASSERT_TRUE(CRYPT_EAL_PkeyCtrl(pkey, CRYPT_CTRL_CLR_RSA_FLAG, NULL, sizeof(uint32_t)) == CRYPT_NULL_INPUT); ASSERT_TRUE(CRYPT_EAL_PkeyCtrl(pkey, CRYPT_CTRL_CLR_RSA_FLAG, (void *)&flag, sizeof(uint32_t)) == CRYPT_SUCCESS); EXIT: CRYPT_EAL_PkeyFreeCtx(pkey); } /* END_CASE */ /** * @test SDV_CRYPTO_RSA_CTRL_API_TC003 * @title Rsa CRYPT_EAL_PkeyCtrl test. * @precon Create the context of the rsa algorithm, set the private key(n, d) and set the different saltLen to pss. */ /* BEGIN_CASE */ void SDV_CRYPTO_RSA_CTRL_API_TC003(Hex *n, Hex *d, int isProvider) { CRYPT_EAL_PkeyPrv prvkey = {0}; int32_t pssSaltLen = CRYPT_RSA_SALTLEN_TYPE_HASHLEN; int32_t pssMdId = CRYPT_MD_SHA256; int32_t pssMgfId = CRYPT_MD_SHA256; int32_t saltLen = 0; BSL_Param pssParam[4] = { {CRYPT_PARAM_RSA_MD_ID, BSL_PARAM_TYPE_INT32, &pssMdId, sizeof(pssMdId), 0}, {CRYPT_PARAM_RSA_MGF1_ID, BSL_PARAM_TYPE_INT32, &pssMgfId, sizeof(pssMgfId), 0}, {CRYPT_PARAM_RSA_SALTLEN, BSL_PARAM_TYPE_INT32, &pssSaltLen, sizeof(pssSaltLen), 0}, BSL_PARAM_END}; CRYPT_EAL_PkeyCtx *pkey = NULL; SetRsaPrvKey(&prvkey, n->x, n->len, d->x, d->len); TestMemInit(); pkey = TestPkeyNewCtx(NULL, CRYPT_PKEY_RSA, CRYPT_EAL_PKEY_KEYMGMT_OPERATE, "provider=default", isProvider); ASSERT_TRUE(pkey != NULL); ASSERT_EQ(CRYPT_EAL_PkeySetPrv(pkey, &prvkey), CRYPT_SUCCESS); ASSERT_EQ(CRYPT_EAL_PkeyCtrl(pkey, CRYPT_CTRL_SET_RSA_EMSA_PSS, pssParam, 0), CRYPT_SUCCESS); ASSERT_EQ(CRYPT_EAL_PkeyCtrl(pkey, CRYPT_CTRL_GET_RSA_SALTLEN, &saltLen, sizeof(int32_t)), CRYPT_SUCCESS); ASSERT_EQ(saltLen, 32); // saltLen = MdSize(32) pssSaltLen = CRYPT_RSA_SALTLEN_TYPE_MAXLEN; pssParam[2].value = &pssSaltLen; // salt-len index = 2 ASSERT_EQ(CRYPT_EAL_PkeyCtrl(pkey, CRYPT_CTRL_SET_RSA_EMSA_PSS, pssParam, 0), CRYPT_SUCCESS); ASSERT_EQ(CRYPT_EAL_PkeyCtrl(pkey, CRYPT_CTRL_GET_RSA_SALTLEN, &saltLen, sizeof(int32_t)), CRYPT_SUCCESS); ASSERT_EQ(saltLen, CRYPT_EAL_PkeyGetKeyLen(pkey) - 32 - 2); // saltLen = keyBytes - MdSize(32) - 2 pssSaltLen = CRYPT_RSA_SALTLEN_TYPE_AUTOLEN; pssParam[2].value = &pssSaltLen; // salt-len index = 2 ASSERT_EQ(CRYPT_EAL_PkeyCtrl(pkey, CRYPT_CTRL_SET_RSA_EMSA_PSS, pssParam, 0), CRYPT_SUCCESS); ASSERT_EQ(CRYPT_EAL_PkeyCtrl(pkey, CRYPT_CTRL_GET_RSA_SALTLEN, &saltLen, sizeof(int32_t)), CRYPT_SUCCESS); ASSERT_EQ(saltLen, CRYPT_EAL_PkeyGetKeyLen(pkey) - 32 - 2); // saltLen = keyBytes - MdSize(32) - 2 EXIT: CRYPT_EAL_PkeyFreeCtx(pkey); } /* END_CASE */ int Compare_PubKey(CRYPT_EAL_PkeyPub *pubKey1, CRYPT_EAL_PkeyPub *pubKey2) { if (pubKey1->key.rsaPub.nLen != pubKey2->key.rsaPub.nLen || pubKey1->key.rsaPub.eLen != pubKey2->key.rsaPub.eLen) { return -1; // -1 indicates failure } if (memcmp(pubKey1->key.rsaPub.n, pubKey2->key.rsaPub.n, pubKey1->key.rsaPub.nLen) != 0 || memcmp(pubKey1->key.rsaPub.e, pubKey2->key.rsaPub.e, pubKey1->key.rsaPub.eLen) != 0) { return -1; // -1 indicates failure } return 0; } int Compare_PrvKey(CRYPT_EAL_PkeyPrv *prvKey1, CRYPT_EAL_PkeyPrv *prvKey2) { if (prvKey1->key.rsaPrv.dLen != prvKey2->key.rsaPrv.dLen || prvKey1->key.rsaPrv.nLen != prvKey2->key.rsaPrv.nLen || prvKey1->key.rsaPrv.pLen != prvKey2->key.rsaPrv.pLen || prvKey1->key.rsaPrv.qLen != prvKey2->key.rsaPrv.qLen) { return -1; // -1 indicates failure } if (memcmp(prvKey1->key.rsaPrv.d, prvKey2->key.rsaPrv.d, prvKey1->key.rsaPrv.dLen) != 0 || memcmp(prvKey1->key.rsaPrv.n, prvKey2->key.rsaPrv.n, prvKey1->key.rsaPrv.nLen) != 0 || memcmp(prvKey1->key.rsaPrv.p, prvKey2->key.rsaPrv.p, prvKey1->key.rsaPrv.pLen) != 0 || memcmp(prvKey1->key.rsaPrv.q, prvKey2->key.rsaPrv.q, prvKey1->key.rsaPrv.qLen) != 0) { return -1; // -1 indicates failure } return 0; } /** * @test SDV_CRYPTO_RSA_SET_KEY_API_TC001 * @title Rsa: Set the public key and private key multiple times. * @precon Create the contexts of the rsa algorithm and: * pkey1: Set paran and generate a key pair: test obtaining the key. * pkey2: Test set keys, and verify that the public and private keys can exist at the same time. * @brief * 1. pkey1: Get public key and get private key, expected result 1 * 2. pkey2: * (1) Set public key and set private key, expected result 1 * (2) Get public key, get private key and check private key, expected result 2 * (3) Set private key and set public key, expected result 3 * (4) Get private key, get public key and check public key, expected result 4 * @expect * 1. CRYPT_SUCCESS * 2. The obtained private key is equal to the set private key. * 3. CRYPT_SUCCESS * 4. The obtained public key is equal to the set public key. */ /* BEGIN_CASE */ void SDV_CRYPTO_RSA_SET_KEY_API_TC001(int isProvider) { uint8_t e[] = {1, 0, 1}; uint8_t pubE[600]; uint8_t pubN[600]; uint8_t prvD[600]; uint8_t prvN[600]; uint8_t prvP[600]; uint8_t prvQ[600]; CRYPT_EAL_PkeyPara para = {0}; CRYPT_EAL_PkeyPub pubKey = {0}; CRYPT_EAL_PkeyPrv prvKey = {0}; SetRsaPubKey(&pubKey, pubE, 600, pubN, 600); // 600 bytes > 1024 bits SetRsaPrvKey(&prvKey, prvN, 600, prvD, 600); prvKey.key.rsaPrv.p = prvP; prvKey.key.rsaPrv.pLen = 600; prvKey.key.rsaPrv.q = prvQ; prvKey.key.rsaPrv.qLen = 600; SetRsaPara(&para, e, 3, 1024); TestMemInit(); CRYPT_RandRegist(RandFunc); CRYPT_RandRegistEx(RandFuncEx); CRYPT_EAL_PkeyCtx *pkey1 = TestPkeyNewCtx(NULL, CRYPT_PKEY_RSA, CRYPT_EAL_PKEY_KEYMGMT_OPERATE, "provider=default", isProvider); CRYPT_EAL_PkeyCtx *pkey2 = TestPkeyNewCtx(NULL, CRYPT_PKEY_RSA, CRYPT_EAL_PKEY_KEYMGMT_OPERATE, "provider=default", isProvider); ASSERT_TRUE(pkey1 != NULL && pkey2 != NULL); /* pkey1 */ /* Generate a key pair. */ ASSERT_TRUE(CRYPT_EAL_PkeySetPara(pkey1, &para) == CRYPT_SUCCESS); ASSERT_EQ(CRYPT_EAL_PkeyGen(pkey1), CRYPT_SUCCESS); /* Get keys. */ ASSERT_EQ(CRYPT_EAL_PkeyGetPub(pkey1, &pubKey), CRYPT_SUCCESS); ASSERT_EQ(CRYPT_EAL_PkeyGetPrv(pkey1, &prvKey), CRYPT_SUCCESS); /* pkey2 */ /* Set public key and set private key. */ ASSERT_EQ(CRYPT_EAL_PkeySetPub(pkey2, &pubKey), CRYPT_SUCCESS); ASSERT_EQ(CRYPT_EAL_PkeySetPrv(pkey2, &prvKey), CRYPT_SUCCESS); /* Get public key, get private key and check private key.*/ SetRsaPubKey(&pubKey, pubE, 600, pubN, 600); ASSERT_EQ(CRYPT_EAL_PkeyGetPub(pkey2, &pubKey), CRYPT_SUCCESS); SetRsaPrvKey(&prvKey, prvN, 600, prvD, 600); prvKey.key.rsaPrv.p = prvP; prvKey.key.rsaPrv.pLen = 600; prvKey.key.rsaPrv.q = prvQ; prvKey.key.rsaPrv.qLen = 600; ASSERT_EQ(CRYPT_EAL_PkeyGetPrv(pkey2, &prvKey), CRYPT_SUCCESS); ASSERT_EQ(Compare_PrvKey(&prvKey, &prvKey), 0); /* Set private key and set public key. */ ASSERT_EQ(CRYPT_EAL_PkeyGetPrv(pkey2, &prvKey), CRYPT_SUCCESS); ASSERT_EQ(CRYPT_EAL_PkeySetPub(pkey2, &pubKey), CRYPT_SUCCESS); /* Get private key, get public key and check public key.*/ ASSERT_EQ(CRYPT_EAL_PkeyGetPrv(pkey2, &prvKey), CRYPT_SUCCESS); SetRsaPubKey(&pubKey, pubE, 600, pubN, 600); ASSERT_EQ(CRYPT_EAL_PkeyGetPub(pkey2, &pubKey), CRYPT_SUCCESS); ASSERT_EQ(Compare_PubKey(&pubKey, &pubKey), 0); EXIT: CRYPT_EAL_PkeyFreeCtx(pkey1); CRYPT_EAL_PkeyFreeCtx(pkey2); TestRandDeInit(); } /* END_CASE */ /** * @test SDV_CRYPTO_RSA_DUP_CTX_API_TC001 * @title RSA CRYPT_EAL_PkeyDupCtx test. * @precon Create the contexts of the rsa algorithm, set para and generate a key pair. * @brief * 1. Call the CRYPT_EAL_PkeyDupCtx mehod to dup rsa, expected result 1 * @expect * 1. Success. */ /* BEGIN_CASE */ void SDV_CRYPTO_RSA_DUP_CTX_API_TC001(Hex *e, int bits, int isProvider) { CRYPT_EAL_PkeyPara para = {0}; CRYPT_EAL_PkeyCtx *newPkey = NULL; CRYPT_EAL_PkeyCtx *pkey = NULL; SetRsaPara(&para, e->x, e->len, bits); TestMemInit(); CRYPT_RandRegist(RandFunc); CRYPT_RandRegistEx(RandFuncEx); pkey = TestPkeyNewCtx(NULL, CRYPT_PKEY_RSA, CRYPT_EAL_PKEY_KEYMGMT_OPERATE, "provider=default", isProvider); ASSERT_TRUE(pkey != NULL); ASSERT_EQ(CRYPT_EAL_PkeySetPara(pkey, &para), 0); ASSERT_EQ(CRYPT_EAL_PkeyGen(pkey), CRYPT_SUCCESS); CRYPT_RSA_Ctx *rsaCtx = (CRYPT_RSA_Ctx *)pkey->key; ASSERT_TRUE(rsaCtx != NULL); newPkey = CRYPT_EAL_PkeyDupCtx(pkey); ASSERT_TRUE(newPkey != NULL); ASSERT_EQ(newPkey->references.count, 1); CRYPT_RSA_Ctx *rsaCtx2 = (CRYPT_RSA_Ctx *)newPkey->key; ASSERT_TRUE(rsaCtx2 != NULL); ASSERT_COMPARE("rsa compare n", rsaCtx->prvKey->n->data, rsaCtx->prvKey->n->size * sizeof(BN_UINT), rsaCtx2->prvKey->n->data, rsaCtx2->prvKey->n->size * sizeof(BN_UINT)); ASSERT_COMPARE("rsa compare d", rsaCtx->prvKey->d->data, rsaCtx->prvKey->d->size * sizeof(BN_UINT), rsaCtx2->prvKey->d->data, rsaCtx2->prvKey->d->size * sizeof(BN_UINT)); EXIT: CRYPT_EAL_PkeyFreeCtx(pkey); CRYPT_EAL_PkeyFreeCtx(newPkey); TestRandDeInit(); } /* END_CASE */ /** * @test SDV_CRYPTO_RSA_CMP_API_TC001 * @title RSA: CRYPT_EAL_PkeyCmp invalid parameter test. * @precon para id and public key. * @brief * 1. Create the contexts(ctx1, ctx2) of the rsa algorithm, expected result 1 * 2. Call the CRYPT_EAL_PkeyCmp to compare ctx1 and ctx2, expected result 2 * 3. Set public key for ctx1, expected result 3 * 4. Call the CRYPT_EAL_PkeyCmp to compare ctx1 and ctx2, expected result 4 * 5. Set different public key for ctx2, expected result 5 * 6. Call the CRYPT_EAL_PkeyCmp to compare ctx1 and ctx2, expected result 6 * @expect * 1. Success, and contexts are not NULL. * 2. CRYPT_RSA_NO_KEY_INFO * 3. CRYPT_SUCCESS * 4. CRYPT_RSA_NO_KEY_INFO * 5. CRYPT_SUCCESS * 6. CRYPT_RSA_PUBKEY_NOT_EQUAL */ /* BEGIN_CASE */ void SDV_CRYPTO_RSA_CMP_API_TC001(Hex *n, Hex *e, int isProvider) { uint8_t tmpE[] = {1, 0, 1}; CRYPT_EAL_PkeyPub pub = {0}; SetRsaPubKey(&pub, n->x, n->len, e->x, e->len); TestMemInit(); CRYPT_EAL_PkeyCtx *ctx1 = TestPkeyNewCtx(NULL, CRYPT_PKEY_RSA, CRYPT_EAL_PKEY_KEYMGMT_OPERATE, "provider=default", isProvider); CRYPT_EAL_PkeyCtx *ctx2 = TestPkeyNewCtx(NULL, CRYPT_PKEY_RSA, CRYPT_EAL_PKEY_KEYMGMT_OPERATE, "provider=default", isProvider); ASSERT_TRUE(ctx1 != NULL && ctx2 != NULL); ASSERT_EQ(CRYPT_EAL_PkeyCmp(ctx1, ctx2), CRYPT_RSA_NO_KEY_INFO); // no key ASSERT_EQ(CRYPT_EAL_PkeySetPub(ctx1, &pub), CRYPT_SUCCESS); ASSERT_EQ(CRYPT_EAL_PkeyCmp(ctx1, ctx2), CRYPT_RSA_NO_KEY_INFO); // ctx2 no pubkey SetRsaPubKey(&pub, n->x, n->len, tmpE, 3); ASSERT_EQ(CRYPT_EAL_PkeySetPub(ctx2, &pub), CRYPT_SUCCESS); ASSERT_EQ(CRYPT_EAL_PkeyCmp(ctx1, ctx2), CRYPT_RSA_PUBKEY_NOT_EQUAL); EXIT: CRYPT_EAL_PkeyFreeCtx(ctx1); CRYPT_EAL_PkeyFreeCtx(ctx2); } /* END_CASE */ /** * @test SDV_CRYPTO_RSA_GET_SECURITY_BITS_FUNC_TC001 * @title RSA CRYPT_EAL_PkeyGetSecurityBits test. * @precon nan * @brief * 1. Create the context of the rsa algorithm, expected result 1 * 2. Set public key, expected result 2 * 3. Call the CRYPT_EAL_PkeyVerify method and the parameter is correct, expected result 3 * @expect * 1. Success, and the context is not null. * 2. CRYPT_SUCCESS * 3. The return value is not 0. */ /* BEGIN_CASE */ void SDV_CRYPTO_RSA_GET_SECURITY_BITS_FUNC_TC001(Hex *n, Hex *e, int securityBits, int isProvider) { CRYPT_EAL_PkeyCtx *pkey = NULL; CRYPT_EAL_PkeyPub pub = {0}; SetRsaPubKey(&pub, n->x, n->len, e->x, e->len); TestMemInit(); pkey = TestPkeyNewCtx(NULL, CRYPT_PKEY_RSA, CRYPT_EAL_PKEY_KEYMGMT_OPERATE, "provider=default", isProvider); ASSERT_TRUE(pkey != NULL); ASSERT_EQ(CRYPT_EAL_PkeySetPub(pkey, &pub), CRYPT_SUCCESS); ASSERT_EQ(CRYPT_EAL_PkeyGetSecurityBits(pkey), securityBits); EXIT: CRYPT_EAL_PkeyFreeCtx(pkey); } /* END_CASE */ #define RSA_TEST_REFERENCE_COUNT 10000 static void *RsaTestAtomic(void *arg) { CRYPT_EAL_PkeyCtx *pkey = (CRYPT_EAL_PkeyCtx *)arg; int ref = 0; for (int i = 0; i < RSA_TEST_REFERENCE_COUNT; i++) { ASSERT_EQ(CRYPT_EAL_PkeyCtrl(pkey, CRYPT_CTRL_UP_REFERENCES, &ref, sizeof(int)), CRYPT_SUCCESS); CRYPT_RSA_Ctx *ctx = (CRYPT_RSA_Ctx *)pkey->key; ASSERT_EQ(CRYPT_RSA_GetBits(ctx), 2048); // RSA2048 CRYPT_RSA_FreeCtx(ctx); } EXIT: return NULL; } static int32_t pthreadRWLockNew(BSL_SAL_ThreadLockHandle *lock) { pthread_rwlock_t *newLock; newLock = (pthread_rwlock_t *)BSL_SAL_Malloc(sizeof(pthread_rwlock_t)); if (newLock == NULL) { return BSL_MALLOC_FAIL; } if (pthread_rwlock_init(newLock, NULL) != 0) { return BSL_SAL_ERR_UNKNOWN; } *lock = newLock; return BSL_SUCCESS; } static void pthreadRWLockFree(BSL_SAL_ThreadLockHandle lock) { pthread_rwlock_destroy((pthread_rwlock_t *)lock); BSL_SAL_FREE(lock); } static int32_t pthreadRWLockReadLock(BSL_SAL_ThreadLockHandle lock) { if (lock == NULL) { return BSL_SAL_ERR_BAD_PARAM; } if (pthread_rwlock_rdlock((pthread_rwlock_t *)lock) != 0) { return BSL_SAL_ERR_UNKNOWN; } return BSL_SUCCESS; } static int32_t pthreadRWLockWriteLock(BSL_SAL_ThreadLockHandle lock) { if (lock == NULL) { return BSL_SAL_ERR_BAD_PARAM; } if (pthread_rwlock_wrlock((pthread_rwlock_t *)lock) != 0) { return BSL_SAL_ERR_UNKNOWN; } return BSL_SUCCESS; } static int32_t pthreadRWLockUnlock(BSL_SAL_ThreadLockHandle lock) { if (lock == NULL) { return BSL_SAL_ERR_BAD_PARAM; } if (pthread_rwlock_unlock((pthread_rwlock_t *)lock) != 0) { return BSL_SAL_ERR_UNKNOWN; } return BSL_SUCCESS; } static uint64_t pthreadGetId(void) { return (uint64_t)pthread_self(); } /** * @test SDV_CRYPTO_RSA_REFERENCES_API_TC001 * @title Multi-threaded reference counting test. * @precon Create the context of the rsa algorithm, set the private key(n, d). * @brief * 1. Create multiple threads to use ctx at the same time. * 2. Check whether the CTX is finally released. * @expect * 1. The reference counting is as expected. * 2. The memory is released successfully, and no memory leakage occurs. */ /* BEGIN_CASE */ void SDV_CRYPTO_RSA_REFERENCES_API_TC001(Hex *n, Hex *d, int isProvider) { BSL_ERR_Init(); pthread_t pid1; pthread_t pid2; CRYPT_EAL_PkeyPrv prvkey = {0}; CRYPT_EAL_PkeyCtx *pkey = NULL; CRYPT_EAL_PkeyCtx *pkey1 = NULL; CRYPT_EAL_PkeyCtx *pkey2 = NULL; SetRsaPrvKey(&prvkey, n->x, n->len, d->x, d->len); TestMemInit(); ASSERT_TRUE(BSL_SAL_CallBack_Ctrl(BSL_SAL_THREAD_LOCK_NEW_CB_FUNC, pthreadRWLockNew) == BSL_SUCCESS); ASSERT_TRUE(BSL_SAL_CallBack_Ctrl(BSL_SAL_THREAD_LOCK_FREE_CB_FUNC, pthreadRWLockFree) == BSL_SUCCESS); ASSERT_TRUE(BSL_SAL_CallBack_Ctrl(BSL_SAL_THREAD_LOCK_READ_LOCK_CB_FUNC, pthreadRWLockReadLock) == BSL_SUCCESS); ASSERT_TRUE(BSL_SAL_CallBack_Ctrl(BSL_SAL_THREAD_LOCK_WRITE_LOCK_CB_FUNC, pthreadRWLockWriteLock) == BSL_SUCCESS); ASSERT_TRUE(BSL_SAL_CallBack_Ctrl(BSL_SAL_THREAD_LOCK_UNLOCK_CB_FUNC, pthreadRWLockUnlock) == BSL_SUCCESS); ASSERT_TRUE(BSL_SAL_CallBack_Ctrl(BSL_SAL_THREAD_GET_ID_CB_FUNC, pthreadGetId) == BSL_SUCCESS); pkey = TestPkeyNewCtx(NULL, CRYPT_PKEY_RSA, CRYPT_EAL_PKEY_KEYMGMT_OPERATE, "provider=default", isProvider); ASSERT_TRUE(pkey != NULL); ASSERT_EQ(pkey->references.count, 1); ASSERT_TRUE(CRYPT_EAL_PkeySetPrv(pkey, &prvkey) == CRYPT_SUCCESS); pkey1 = pkey; ASSERT_TRUE(CRYPT_EAL_PkeyUpRef(pkey1) == CRYPT_SUCCESS); pkey2 = pkey; ASSERT_TRUE(CRYPT_EAL_PkeyUpRef(pkey2) == CRYPT_SUCCESS); ASSERT_EQ(pkey->references.count, 3); // The pkey is referenced three times. pthread_create(&pid1, NULL, RsaTestAtomic, (void *)pkey1); pthread_create(&pid2, NULL, RsaTestAtomic, (void *)pkey2); pthread_join(pid1, NULL); // Wait for all child threads to end. pthread_join(pid2, NULL); CRYPT_EAL_PkeyFreeCtx(pkey1); CRYPT_EAL_PkeyFreeCtx(pkey2); ASSERT_EQ(pkey->references.count, 1); CRYPT_RSA_Ctx *ctx = (CRYPT_RSA_Ctx *)pkey->key; ASSERT_EQ(ctx->references.count, 1); EXIT: CRYPT_EAL_PkeyFreeCtx(pkey); } /* END_CASE */ /** * @test SDV_CRYPTO_RSA_GET_KEY_BITS_FUNC_TC001 * @title RSA: get key bits. * @brief * 1. Create a context of the RSA algorithm, expected result 1 * 2. Get key bits, expected result 2 * @expect * 1. Success, and context is not NULL. * 2. Equal to keyBits. */ /* BEGIN_CASE */ void SDV_CRYPTO_RSA_GET_KEY_BITS_FUNC_TC001(int id, int keyBits, int isProvider) { uint8_t e3[] = {1, 0, 1}; CRYPT_EAL_PkeyPara para = {0}; para.id = id; para.para.rsaPara.e = e3; para.para.rsaPara.eLen = 3; // 3 is valid. para.para.rsaPara.bits = 1024; // 1024 is valid. CRYPT_EAL_PkeyCtx *pkey = TestPkeyNewCtx(NULL, id, CRYPT_EAL_PKEY_KEYMGMT_OPERATE, "provider=default", isProvider); ASSERT_TRUE(pkey != NULL); ASSERT_TRUE_AND_LOG("1k key", CRYPT_EAL_PkeySetPara(pkey, &para) == 0); ASSERT_TRUE(CRYPT_EAL_PkeyGetKeyBits(pkey) == (uint32_t)keyBits); EXIT: CRYPT_EAL_PkeyFreeCtx(pkey); } /* END_CASE */ static int32_t STUB_Gcd(BN_BigNum *r, const BN_BigNum *a, const BN_BigNum *b, BN_Optimizer *opt) { (void)a; (void)b; (void)opt; BN_BigNum *val = BN_Create(1); val->data[0] = 2; val->sign = false; BN_Copy(r, val); BN_Destroy(val); return CRYPT_SUCCESS; } /** * @test SDV_CRYPTO_RSA_NOR_KEYGEN_FAIL_TC001 * @title RSA: Normal Key Generation Failure Test * @brief * 1. Create a context of the RSA algorithm, expected result 1 * 2. Generate a key pair, expected result 2 * @expect * 1. CRYPT_SUCCESS * 2. CRYPT_RSA_NOR_KEYGEN_FAIL */ /* BEGIN_CASE */ void SDV_CRYPTO_RSA_NOR_KEYGEN_FAIL_TC001(int isProvider) { uint8_t e[] = {1, 0, 1}; CRYPT_EAL_PkeyPara para = {0}; CRYPT_EAL_PkeyCtx *pkey = NULL; TestMemInit(); STUB_Init(); FuncStubInfo tmpRpInfo = {0}; SetRsaPara(&para, e, 3, 1024); pkey = TestPkeyNewCtx(NULL, CRYPT_PKEY_RSA, CRYPT_EAL_PKEY_KEYMGMT_OPERATE, "provider=default", isProvider); ASSERT_TRUE(pkey != NULL); ASSERT_EQ(CRYPT_EAL_PkeySetPara(pkey, &para), CRYPT_SUCCESS); STUB_Replace(&tmpRpInfo, BN_Gcd, STUB_Gcd); ASSERT_EQ(CRYPT_EAL_PkeyGen(pkey), CRYPT_RSA_NOR_KEYGEN_FAIL); STUB_Reset(&tmpRpInfo); ASSERT_EQ(CRYPT_EAL_PkeyGen(pkey), CRYPT_SUCCESS); EXIT: CRYPT_EAL_PkeyFreeCtx(pkey); STUB_Reset(&tmpRpInfo); } /* END_CASE */ /** * @test SDV_CRYPTO_RSA_SEED_KEYGEN_TC001 * @title RSA: Deterministic Seed Key Generation Test * @precon Two RSA key generation contexts with the same seed value * @brief * 1. Create two RSA key pairs using the seed. * 2. Compare if the two key pairs are identical. * 3. Compare if the p and q of the two key pairs meet expectations. * @expect * 1. CRYPT_SUCCESS * 2. The two key pairs are identical. * 3. The p and q of the two key pairs meet expectations. */ /* BEGIN_CASE */ void SDV_CRYPTO_RSA_SEED_KEYGEN_TC001(Hex *xp, Hex *xp1, Hex *xp2, Hex *xq, Hex *xq1, Hex *xq2, Hex *p, Hex *q, int isProvider) { #ifdef HITLS_CRYPTO_ACVP_TESTS TestMemInit(); uint8_t e[] = {1, 0, 1}; uint32_t bits = 1024; uint8_t prvD1[600]; uint8_t prvN1[600]; uint8_t prvP1[600]; uint8_t prvQ1[600]; uint8_t prvD2[600]; uint8_t prvN2[600]; uint8_t prvP2[600]; uint8_t prvQ2[600]; // Initialize two key contexts CRYPT_EAL_PkeyCtx *pkey1 = NULL; CRYPT_EAL_PkeyCtx *pkey2 = NULL; // Initialize two identical parameter structures BSL_Param param[] = { {CRYPT_PARAM_RSA_E, BSL_PARAM_TYPE_OCTETS, e, 3, 0}, {CRYPT_PARAM_RSA_BITS, BSL_PARAM_TYPE_UINT32, &bits, sizeof(bits), 0}, {CRYPT_PARAM_RSA_XP, BSL_PARAM_TYPE_OCTETS, xp->x, xp->len, 0}, {CRYPT_PARAM_RSA_XP1, BSL_PARAM_TYPE_OCTETS, xp1->x, xp1->len, 0}, {CRYPT_PARAM_RSA_XP2, BSL_PARAM_TYPE_OCTETS, xp2->x, xp2->len, 0}, {CRYPT_PARAM_RSA_XQ, BSL_PARAM_TYPE_OCTETS, xq->x, xq->len, 0}, {CRYPT_PARAM_RSA_XQ1, BSL_PARAM_TYPE_OCTETS, xq1->x, xq1->len, 0}, {CRYPT_PARAM_RSA_XQ2, BSL_PARAM_TYPE_OCTETS, xq2->x, xq2->len, 0}, BSL_PARAM_END }; // Create the first context and generate the key pkey1 = TestPkeyNewCtx(NULL, CRYPT_PKEY_RSA, CRYPT_EAL_PKEY_KEYMGMT_OPERATE, "provider=default", isProvider); ASSERT_TRUE(pkey1 != NULL); ASSERT_EQ(CRYPT_EAL_PkeySetParaEx(pkey1, param), CRYPT_SUCCESS); ASSERT_EQ(CRYPT_EAL_PkeyGen(pkey1), CRYPT_SUCCESS); // Create the second context and generate the key pkey2 = TestPkeyNewCtx(NULL, CRYPT_PKEY_RSA, CRYPT_EAL_PKEY_KEYMGMT_OPERATE, "provider=default", isProvider); ASSERT_TRUE(pkey2 != NULL); ASSERT_EQ(CRYPT_EAL_PkeySetParaEx(pkey2, param), CRYPT_SUCCESS); ASSERT_EQ(CRYPT_EAL_PkeyGen(pkey2), CRYPT_SUCCESS); // Get private keys CRYPT_EAL_PkeyPrv prvKey1 = {0}; CRYPT_EAL_PkeyPrv prvKey2 = {0}; SetRsaPrvKey(&prvKey1, prvN1, sizeof(prvN1), prvD1, sizeof(prvD1)); SetRsaPrvKey(&prvKey2, prvN2, sizeof(prvN2), prvD2, sizeof(prvD2)); prvKey1.key.rsaPrv.p = prvP1; prvKey1.key.rsaPrv.pLen = sizeof(prvP1); prvKey1.key.rsaPrv.q = prvQ1; prvKey1.key.rsaPrv.qLen = sizeof(prvQ1); prvKey2.key.rsaPrv.p = prvP2; prvKey2.key.rsaPrv.pLen = sizeof(prvP2); prvKey2.key.rsaPrv.q = prvQ2; prvKey2.key.rsaPrv.qLen = sizeof(prvQ2); ASSERT_EQ(CRYPT_EAL_PkeyGetPrv(pkey1, &prvKey1), CRYPT_SUCCESS); ASSERT_EQ(CRYPT_EAL_PkeyGetPrv(pkey2, &prvKey2), CRYPT_SUCCESS); // Verify if the two keys are identical ASSERT_EQ(Compare_PrvKey(&prvKey1, &prvKey2), 0); // Verify if p and q are as expected ASSERT_EQ(memcmp(prvKey1.key.rsaPrv.p, p->x, p->len), 0); ASSERT_EQ(memcmp(prvKey1.key.rsaPrv.q, q->x, q->len), 0); EXIT: CRYPT_EAL_PkeyFreeCtx(pkey1); CRYPT_EAL_PkeyFreeCtx(pkey2); #else (void)xp; (void)xp1; (void)xp2; (void)xq; (void)xq1; (void)xq2; (void)p; (void)q; (void)isProvider; #endif } /* END_CASE */ /** * @test SDV_CRYPTO_RSA_CHECK_KEYPAIR_INVALID_TC001 * @brief * invalid input test and no p, q check */ /* BEGIN_CASE */ void SDV_CRYPTO_RSA_CHECK_KEYPAIR_INVALID_TC001(Hex *n, Hex *d, int isProvider) { #if !defined(HITLS_CRYPTO_RSA_CHECK) (void)n; (void)d; (void)isProvider; SKIP_TEST(); #else uint8_t e[] = {1, 0, 1}; TestMemInit(); ASSERT_EQ(TestRandInit(), CRYPT_SUCCESS); CRYPT_EAL_PkeyPub pubKey = {0}; CRYPT_EAL_PkeyPrv prvKey = {0}; CRYPT_EAL_PkeyCtx *pkey1 = TestPkeyNewCtx(NULL, CRYPT_PKEY_RSA, CRYPT_EAL_PKEY_KEYMGMT_OPERATE, "provider=default", isProvider); CRYPT_EAL_PkeyCtx *pkey2 = TestPkeyNewCtx(NULL, CRYPT_PKEY_RSA, CRYPT_EAL_PKEY_KEYMGMT_OPERATE, "provider=default", isProvider); ASSERT_TRUE(pkey1 != NULL); ASSERT_TRUE(pkey2 != NULL); SetRsaPrvKey(&prvKey, n->x, n->len, d->x, d->len); SetRsaPubKey(&pubKey, n->x, n->len, e, 3); ASSERT_EQ(CRYPT_EAL_PkeyPairCheck(NULL, pkey1), CRYPT_NULL_INPUT); ASSERT_EQ(CRYPT_EAL_PkeyPairCheck(pkey1, NULL), CRYPT_NULL_INPUT); ASSERT_EQ(CRYPT_EAL_PkeySetPub(pkey1, &pubKey), CRYPT_SUCCESS); ASSERT_EQ(CRYPT_EAL_PkeySetPrv(pkey2, &prvKey), CRYPT_SUCCESS); ASSERT_EQ(CRYPT_EAL_PkeyPairCheck(pkey2, pkey2), CRYPT_RSA_ERR_NO_PUBKEY_INFO); ASSERT_EQ(CRYPT_EAL_PkeyPairCheck(pkey1, pkey1), CRYPT_RSA_ERR_NO_PRVKEY_INFO); ASSERT_EQ(CRYPT_EAL_PkeyPairCheck(pkey1, pkey2), CRYPT_RSA_KEYPAIRWISE_CONSISTENCY_FAILURE); // recover p q failed. EXIT: CRYPT_EAL_PkeyFreeCtx(pkey1); CRYPT_EAL_PkeyFreeCtx(pkey2); TestRandDeInit(); #endif } /* END_CASE */ /** * @test SDV_CRYPTO_RSA_CHECK_KEYPAIR_TC001 * @brief * Create a RSA key pairs to check the key pair consistency and prv key, check crt param. */ /* BEGIN_CASE */ void SDV_CRYPTO_RSA_CHECK_KEYPAIR_TC001(int bits, int isProvider) { #if !defined(HITLS_CRYPTO_RSA_CHECK) (void)bits; (void)isProvider; SKIP_TEST(); #else uint8_t e[] = {1, 0, 1}; CRYPT_EAL_PkeyPara para = {0}; SetRsaPara(&para, e, 3, bits); // Valid parameters: elen = 3 TestMemInit(); ASSERT_EQ(TestRandInit(), CRYPT_SUCCESS); CRYPT_EAL_PkeyCtx *pkey = TestPkeyNewCtx(NULL, CRYPT_PKEY_RSA, CRYPT_EAL_PKEY_KEYMGMT_OPERATE, "provider=default", isProvider); ASSERT_TRUE(pkey != NULL); ASSERT_TRUE(CRYPT_EAL_PkeySetPara(pkey, &para) == CRYPT_SUCCESS); ASSERT_EQ(CRYPT_EAL_PkeyGen(pkey), CRYPT_SUCCESS); // check ctr ASSERT_EQ(CRYPT_EAL_PkeyPairCheck(pkey, pkey), CRYPT_SUCCESS); ASSERT_EQ(CRYPT_EAL_PkeyPrvCheck(pkey), CRYPT_SUCCESS); EXIT: CRYPT_EAL_PkeyFreeCtx(pkey); TestRandDeInit(); #endif } /* END_CASE */ /** * @test SDV_CRYPTO_RSA_CHECK_KEYPAIR_TC002 * @brief * check p, q mode in rsa key pair. including right vector and wrong vector. */ /* BEGIN_CASE */ void SDV_CRYPTO_RSA_CHECK_KEYPAIR_TC002(Hex *p, Hex *q, Hex *n, Hex *d, int isProvider, int expect) { #if !defined(HITLS_CRYPTO_RSA_CHECK) (void)p; (void)q; (void)n; (void)d; (void)isProvider; (void)expect; SKIP_TEST(); #else TestMemInit(); uint8_t e[] = {1, 0, 1}; CRYPT_EAL_PkeyPub pubKey = {0}; CRYPT_EAL_PkeyPrv prvKey = {0}; int expectRet = expect == 0 ? CRYPT_SUCCESS : CRYPT_RSA_KEYPAIRWISE_CONSISTENCY_FAILURE; CRYPT_EAL_PkeyCtx *pkey1 = TestPkeyNewCtx(NULL, CRYPT_PKEY_RSA, CRYPT_EAL_PKEY_KEYMGMT_OPERATE, "provider=default", isProvider); CRYPT_EAL_PkeyCtx *pkey2 = TestPkeyNewCtx(NULL, CRYPT_PKEY_RSA, CRYPT_EAL_PKEY_KEYMGMT_OPERATE, "provider=default", isProvider); ASSERT_TRUE(pkey1 != NULL); ASSERT_TRUE(pkey2 != NULL); ASSERT_EQ(TestRandInit(), CRYPT_SUCCESS); SetRsaPrvKey(&prvKey, n->x, n->len, d->x, d->len); prvKey.key.rsaPrv.p = p->x; prvKey.key.rsaPrv.pLen = p->len; prvKey.key.rsaPrv.q = q->x; prvKey.key.rsaPrv.qLen = q->len; SetRsaPubKey(&pubKey, n->x, n->len, e, 3); ASSERT_EQ(CRYPT_EAL_PkeySetPub(pkey1, &pubKey), CRYPT_SUCCESS); ASSERT_EQ(CRYPT_EAL_PkeySetPrv(pkey2, &prvKey), CRYPT_SUCCESS); ASSERT_EQ(CRYPT_EAL_PkeyPairCheck(pkey1, pkey2), expectRet); ASSERT_EQ(CRYPT_EAL_PkeyPrvCheck(pkey2), CRYPT_SUCCESS); EXIT: CRYPT_EAL_PkeyFreeCtx(pkey1); CRYPT_EAL_PkeyFreeCtx(pkey2); TestRandDeInit(); #endif } /* END_CASE */ /** * @test SDV_CRYPTO_RSA_CHECK_KEYPAIR_TC003 * @brief * Create a RSA key pairs to check the key pair consistency and prv key, check recover p q. */ /* BEGIN_CASE */ void SDV_CRYPTO_RSA_CHECK_KEYPAIR_TC003(int bits, int isProvider) { #if !defined(HITLS_CRYPTO_RSA_CHECK) (void)bits; (void)isProvider; SKIP_TEST(); #else uint8_t e[] = {1, 0, 1}; CRYPT_EAL_PkeyPara para = {0}; CRYPT_EAL_PkeyPub pubKey = {0}; CRYPT_EAL_PkeyPrv prvKey = {0}; SetRsaPara(&para, e, 3, bits); // Valid parameters: elen = 3 TestMemInit(); uint8_t pubE[600]; uint8_t pubN[600]; uint8_t pubD[600]; SetRsaPubKey(&pubKey, pubN, 600, pubE, 600); SetRsaPrvKey(&prvKey, pubN, 600, pubD, 600); CRYPT_EAL_PkeyCtx *pkey = TestPkeyNewCtx(NULL, CRYPT_PKEY_RSA, CRYPT_EAL_PKEY_KEYMGMT_OPERATE, "provider=default", isProvider); CRYPT_EAL_PkeyCtx *pubCtx = TestPkeyNewCtx(NULL, CRYPT_PKEY_RSA, CRYPT_EAL_PKEY_KEYMGMT_OPERATE, "provider=default", isProvider); CRYPT_EAL_PkeyCtx *prvCtx = TestPkeyNewCtx(NULL, CRYPT_PKEY_RSA, CRYPT_EAL_PKEY_KEYMGMT_OPERATE, "provider=default", isProvider); ASSERT_TRUE(pkey != NULL); ASSERT_TRUE(pubCtx != NULL); ASSERT_TRUE(prvCtx != NULL); ASSERT_TRUE(CRYPT_EAL_PkeySetPara(pkey, &para) == CRYPT_SUCCESS); ASSERT_EQ(TestRandInit(), CRYPT_SUCCESS); ASSERT_EQ(CRYPT_EAL_PkeyGen(pkey), CRYPT_SUCCESS); ASSERT_EQ(CRYPT_EAL_PkeyGetPub(pkey, &pubKey), CRYPT_SUCCESS); ASSERT_EQ(CRYPT_EAL_PkeyGetPrv(pkey, &prvKey), CRYPT_SUCCESS); ASSERT_EQ(CRYPT_EAL_PkeySetPub(pubCtx, &pubKey), CRYPT_SUCCESS); ASSERT_EQ(CRYPT_EAL_PkeySetPrv(prvCtx, &prvKey), CRYPT_SUCCESS); ASSERT_EQ(CRYPT_EAL_PkeyPrvCheck(pkey), CRYPT_SUCCESS); ASSERT_EQ(CRYPT_EAL_PkeyPairCheck(pubCtx, prvCtx), CRYPT_SUCCESS); EXIT: CRYPT_EAL_PkeyFreeCtx(pkey); CRYPT_EAL_PkeyFreeCtx(pubCtx); CRYPT_EAL_PkeyFreeCtx(prvCtx); TestRandDeInit(); #endif } /* END_CASE */ /** * @test SDV_CRYPTO_RSA_CHECK_KEYPAIR_TC004 * @title RSA: Deterministic Seed Key Generation Test * @precon Two RSA key generation contexts with the same seed value * @brief * 1. Create two RSA key pairs using the seed. * 2. Compare if the two key pairs are identical. * 3. Compare if the p and q of the two key pairs meet expectations. * @expect * 1. CRYPT_SUCCESS * 2. The two key pairs are identical. * 3. The p and q of the two key pairs meet expectations. */ /* BEGIN_CASE */ void SDV_CRYPTO_RSA_CHECK_KEYPAIR_TC004(int bits, int isProvider) { #if !defined(HITLS_CRYPTO_RSA_CHECK) (void)bits; (void)isProvider; SKIP_TEST(); #else TestMemInit(); CRYPT_EAL_PkeyPub pubKey = {0}; CRYPT_EAL_PkeyPrv prvKey = {0}; CRYPT_EAL_PkeyPara para = {0}; uint8_t e[] = {1, 0, 1}; uint8_t prvD[600]; uint8_t prvP[600]; uint8_t prvQ[600]; uint8_t prvN[600]; uint8_t prvDp[600]; uint8_t prvDq[600]; uint8_t prvQInv[600]; uint8_t wrong[600] = {1}; SetRsaPara(&para, e, 3, bits); // Valid parameters: elen = 3 prvKey.id = CRYPT_PKEY_RSA; pubKey.id = CRYPT_PKEY_RSA; prvKey.key.rsaPrv.p = prvP; prvKey.key.rsaPrv.pLen = sizeof(prvP); prvKey.key.rsaPrv.q = prvQ; prvKey.key.rsaPrv.qLen = sizeof(prvQ); prvKey.key.rsaPrv.d = prvD; prvKey.key.rsaPrv.dLen = sizeof(prvD); prvKey.key.rsaPrv.n = prvN; prvKey.key.rsaPrv.nLen = sizeof(prvN); prvKey.key.rsaPrv.dQ = prvDq; prvKey.key.rsaPrv.dQLen = sizeof(prvDq); prvKey.key.rsaPrv.dP = prvDp; prvKey.key.rsaPrv.dPLen = sizeof(prvDp); prvKey.key.rsaPrv.e = e; prvKey.key.rsaPrv.eLen = sizeof(e); prvKey.key.rsaPrv.qInv = prvQInv; prvKey.key.rsaPrv.qInvLen = sizeof(prvQInv); pubKey.key.rsaPub.e = e; pubKey.key.rsaPub.eLen = sizeof(e); pubKey.key.rsaPub.n = prvN; pubKey.key.rsaPub.nLen = sizeof(prvN); ASSERT_EQ(TestRandInit(), CRYPT_SUCCESS); CRYPT_EAL_PkeyCtx *pkey = TestPkeyNewCtx(NULL, CRYPT_PKEY_RSA, CRYPT_EAL_PKEY_KEYMGMT_OPERATE, "provider=default", isProvider); CRYPT_EAL_PkeyCtx *pubCtx = TestPkeyNewCtx(NULL, CRYPT_PKEY_RSA, CRYPT_EAL_PKEY_KEYMGMT_OPERATE, "provider=default", isProvider); CRYPT_EAL_PkeyCtx *prvCtx = TestPkeyNewCtx(NULL, CRYPT_PKEY_RSA, CRYPT_EAL_PKEY_KEYMGMT_OPERATE, "provider=default", isProvider); ASSERT_TRUE(pkey != NULL); ASSERT_TRUE(pubCtx != NULL); ASSERT_TRUE(prvCtx != NULL); ASSERT_TRUE(CRYPT_EAL_PkeySetPara(pkey, &para) == CRYPT_SUCCESS); ASSERT_EQ(CRYPT_EAL_PkeyGen(pkey), CRYPT_SUCCESS); ASSERT_EQ(CRYPT_EAL_PkeyGetPub(pkey, &pubKey), CRYPT_SUCCESS); ASSERT_EQ(CRYPT_EAL_PkeyGetPrv(pkey, &prvKey), CRYPT_SUCCESS); ASSERT_EQ(CRYPT_EAL_PkeySetPub(pubCtx, &pubKey), CRYPT_SUCCESS); ASSERT_EQ(CRYPT_EAL_PkeySetPrv(prvCtx, &prvKey), CRYPT_SUCCESS); ASSERT_EQ(CRYPT_EAL_PkeyPrvCheck(prvCtx), CRYPT_SUCCESS); ASSERT_EQ(CRYPT_EAL_PkeyPairCheck(pubCtx, prvCtx), CRYPT_SUCCESS); prvKey.key.rsaPrv.dQ = wrong; ASSERT_EQ(CRYPT_EAL_PkeySetPrv(prvCtx, &prvKey), CRYPT_SUCCESS); ASSERT_EQ(CRYPT_EAL_PkeyPairCheck(pubCtx, prvCtx), CRYPT_RSA_KEYPAIRWISE_CONSISTENCY_FAILURE); prvKey.key.rsaPrv.dQ = prvDq; prvKey.key.rsaPrv.dP = wrong; ASSERT_EQ(CRYPT_EAL_PkeySetPrv(prvCtx, &prvKey), CRYPT_SUCCESS); ASSERT_EQ(CRYPT_EAL_PkeyPairCheck(pubCtx, prvCtx), CRYPT_RSA_KEYPAIRWISE_CONSISTENCY_FAILURE); prvKey.key.rsaPrv.dP = prvDp; prvKey.key.rsaPrv.qInv = wrong; ASSERT_EQ(CRYPT_EAL_PkeySetPrv(prvCtx, &prvKey), CRYPT_SUCCESS); ASSERT_EQ(CRYPT_EAL_PkeyPairCheck(pubCtx, prvCtx), CRYPT_RSA_KEYPAIRWISE_CONSISTENCY_FAILURE); prvKey.key.rsaPrv.qInv = prvQInv; prvKey.key.rsaPrv.d = wrong; ASSERT_EQ(CRYPT_EAL_PkeySetPrv(prvCtx, &prvKey), CRYPT_SUCCESS); ASSERT_EQ(CRYPT_EAL_PkeyPairCheck(pubCtx, prvCtx), CRYPT_RSA_KEYPAIRWISE_CONSISTENCY_FAILURE); prvKey.key.rsaPrv.d = prvD; prvKey.key.rsaPrv.p = wrong; ASSERT_EQ(CRYPT_EAL_PkeySetPrv(prvCtx, &prvKey), CRYPT_SUCCESS); ASSERT_EQ(CRYPT_EAL_PkeyPairCheck(pubCtx, prvCtx), CRYPT_RSA_KEYPAIRWISE_CONSISTENCY_FAILURE); prvKey.key.rsaPrv.p = prvP; prvKey.key.rsaPrv.q = wrong; ASSERT_EQ(CRYPT_EAL_PkeySetPrv(prvCtx, &prvKey), CRYPT_SUCCESS); ASSERT_EQ(CRYPT_EAL_PkeyPairCheck(pubCtx, prvCtx), CRYPT_RSA_KEYPAIRWISE_CONSISTENCY_FAILURE); prvKey.key.rsaPrv.q = prvQ; prvKey.key.rsaPrv.e = wrong; ASSERT_EQ(CRYPT_EAL_PkeySetPrv(prvCtx, &prvKey), CRYPT_SUCCESS); ASSERT_EQ(CRYPT_EAL_PkeyPairCheck(pubCtx, prvCtx), CRYPT_RSA_KEYPAIRWISE_CONSISTENCY_FAILURE); EXIT: CRYPT_EAL_PkeyFreeCtx(pkey); CRYPT_EAL_PkeyFreeCtx(pubCtx); CRYPT_EAL_PkeyFreeCtx(prvCtx); TestRandDeInit(); #endif } /* END_CASE */ /** * @test SDV_CRYPTO_RSA_CHECK_PRV_TC001 * @brief * Create a RSA key pairs to check the prv key. */ /* BEGIN_CASE */ void SDV_CRYPTO_RSA_CHECK_PRV_TC001(int bits, int isProvider) { #if !defined(HITLS_CRYPTO_RSA_CHECK) (void)bits; (void)isProvider; SKIP_TEST(); #else uint8_t e[] = {1, 0, 1}; CRYPT_EAL_PkeyPara para = {0}; BN_BigNum *n = NULL; BN_BigNum *d = NULL; CRYPT_RSA_Ctx *ctx = NULL; BN_BigNum *zero = BN_Create(0); SetRsaPara(&para, e, 3, bits); TestMemInit(); ASSERT_EQ(TestRandInit(), CRYPT_SUCCESS); CRYPT_EAL_PkeyCtx *pkey = TestPkeyNewCtx(NULL, CRYPT_PKEY_RSA, CRYPT_EAL_PKEY_KEYMGMT_OPERATE, "provider=default", isProvider); ASSERT_TRUE(pkey != NULL); ASSERT_TRUE(CRYPT_EAL_PkeySetPara(pkey, &para) == CRYPT_SUCCESS); ASSERT_EQ(CRYPT_EAL_PkeyPrvCheck(NULL), CRYPT_NULL_INPUT); ASSERT_EQ(CRYPT_EAL_PkeyPrvCheck(pkey), CRYPT_RSA_ERR_NO_PRVKEY_INFO); ASSERT_EQ(CRYPT_EAL_PkeyGen(pkey), CRYPT_SUCCESS); ASSERT_EQ(CRYPT_EAL_PkeyPrvCheck(pkey), CRYPT_SUCCESS); ctx = (CRYPT_RSA_Ctx *)pkey->key; n = ctx->prvKey->n; d = ctx->prvKey->d; ctx->prvKey->n = NULL; ASSERT_EQ(CRYPT_EAL_PkeyPrvCheck(pkey), CRYPT_RSA_ERR_NO_PRVKEY_INFO); ctx->prvKey->n = zero; ASSERT_EQ(CRYPT_EAL_PkeyPrvCheck(pkey), CRYPT_RSA_ERR_INVALID_PRVKEY); ctx->prvKey->n = n; ctx->prvKey->d = ctx->prvKey->n; ASSERT_EQ(CRYPT_EAL_PkeyPrvCheck(pkey), CRYPT_RSA_ERR_INVALID_PRVKEY); ctx->prvKey->d = d; EXIT: CRYPT_EAL_PkeyFreeCtx(pkey); BN_Destroy(zero); TestRandDeInit(); #endif } /* END_CASE */
2301_79861745/bench_create
testcode/sdv/testcase/crypto/rsa/test_suite_sdv_eal_rsa_api.c
C
unknown
73,400
/* * This file is part of the openHiTLS project. * * openHiTLS is licensed under the Mulan PSL v2. * You can use this software according to the terms and conditions of the Mulan PSL v2. * You may obtain a copy of Mulan PSL v2 at: * * http://license.coscl.org.cn/MulanPSL2 * * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, * EITHER EXPRESS 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 test_suite_sdv_eal_rsa */ /* BEGIN_HEADER */ #include <stdint.h> #include "bsl_params.h" #include "crypt_params_key.h" /* END_HEADER */ #define CRYPT_EAL_PKEY_KEYMGMT_OPERATE 0 static bool NeedPadSkip(int padMode) { switch (padMode) { #ifdef HITLS_CRYPTO_RSAES_OAEP case CRYPT_CTRL_SET_RSA_RSAES_OAEP: return false; #endif #ifdef HITLS_CRYPTO_RSAES_PKCSV15 case CRYPT_CTRL_SET_RSA_RSAES_PKCSV15: return false; #endif #ifdef HITLS_CRYPTO_RSAES_PKCSV15_TLS case CRYPT_CTRL_SET_RSA_RSAES_PKCSV15_TLS: return false; #endif #ifdef HITLS_CRYPTO_RSA_NO_PAD case CRYPT_CTRL_SET_RSA_PADDING: return false; #endif default: return true; } } /** * @test SDV_CRYPTO_RSA_CRYPT_FUNC_TC001 * @title RSA: public key encryption and private key * @precon Vectors: a rsa key pair. * @brief * 1. Create the context(pkey) of the rsa algorithm, expected result 1 * 2. Initialize the DRBG. * 3. Set private key and padding mode, expected result 2 * 4. Call the CRYPT_EAL_PkeyDecrypt to decrypt ciphertext, expected result 3 * 5. Compare the decrypted output with the expected output, expected result 4 * 6. Set public key and padding mode, expected result 5 * 7. Call the CRYPT_EAL_PkeyEncrypt to encrypt plaintext, expected result 6 * 8. Check the length of output data, expected result 7 * 9. Call the CRYPT_EAL_PkeyDecrypt to decrypt the output data of step 6, expected result 8 * 10. Compare the output data of step 8 with the output data of step 6, expected result 9 * @expect * 1. Success, and context is not NULL. * 2-3. CRYPT_SUCCESS * 4. Both are the same. * 5-6. CRYPT_SUCCESS * 7. It is equal to ciphertext->len. * 8. CRYPT_SUCCESS * 9. Both are the same. */ /* BEGIN_CASE */ void SDV_CRYPTO_RSA_CRYPT_FUNC_TC001( int keyLen, int padMode, int hashId, Hex *n, Hex *e, Hex *d, Hex *plaintext, Hex *ciphertext, int isProvider) { if (NeedPadSkip(padMode) || IsMdAlgDisabled(hashId)) { SKIP_TEST(); } int paraSize; void *paraPtr; CRYPT_EAL_PkeyPrv prvkey = {0}; CRYPT_EAL_PkeyPub pubkey = {0}; CRYPT_EAL_PkeyCtx *pkey = NULL; BSL_Param oaepParam[3] = { {CRYPT_PARAM_RSA_MD_ID, BSL_PARAM_TYPE_INT32, &hashId, sizeof(hashId), 0}, {CRYPT_PARAM_RSA_MGF1_ID, BSL_PARAM_TYPE_INT32, &hashId, sizeof(hashId), 0}, BSL_PARAM_END}; int32_t pkcsv15 = hashId; #ifdef HITLS_CRYPTO_RSA_DECRYPT uint8_t pt[MAX_CIPHERTEXT_LEN] = {0}; uint32_t ptLen = MAX_CIPHERTEXT_LEN; #endif #ifdef HITLS_CRYPTO_RSA_ENCRYPT uint8_t ct[MAX_CIPHERTEXT_LEN] = {0}; uint32_t ctLen = MAX_CIPHERTEXT_LEN; #endif int32_t noPad = CRYPT_RSA_NO_PAD; SetRsaPrvKey(&prvkey, n->x, n->len, d->x, d->len); SetRsaPubKey(&pubkey, n->x, n->len, e->x, e->len); if (padMode == CRYPT_CTRL_SET_RSA_RSAES_OAEP) { paraSize = 0; paraPtr = oaepParam; } else if (padMode == CRYPT_CTRL_SET_RSA_RSAES_PKCSV15) { paraSize = sizeof(pkcsv15); paraPtr = &pkcsv15; } else if (padMode == CRYPT_CTRL_SET_RSA_PADDING) { paraSize = sizeof(noPad); paraPtr = &noPad; } ASSERT_TRUE(ciphertext->len == KEYLEN_IN_BYTES((uint32_t)keyLen)); TestMemInit(); pkey = TestPkeyNewCtx(NULL, CRYPT_PKEY_RSA, CRYPT_EAL_PKEY_KEYMGMT_OPERATE + CRYPT_EAL_PKEY_CIPHER_OPERATE, "provider=default", isProvider); ASSERT_TRUE(pkey != NULL); #ifdef HITLS_CRYPTO_DRBG if (padMode != CRYPT_CTRL_SET_RSA_PADDING) { CRYPT_RandRegist(RandFunc); CRYPT_RandRegistEx(RandFuncEx); } #endif #ifdef HITLS_CRYPTO_RSA_DECRYPT /* HiTLS private key decrypts the data. */ ASSERT_EQ(CRYPT_EAL_PkeySetPrv(pkey, &prvkey), CRYPT_SUCCESS); ASSERT_EQ(CRYPT_EAL_PkeyCtrl(pkey, padMode, paraPtr, paraSize), CRYPT_SUCCESS); ASSERT_EQ(CRYPT_EAL_PkeyDecrypt(pkey, ciphertext->x, ciphertext->len, pt, &ptLen), CRYPT_SUCCESS); ASSERT_EQ(ptLen, plaintext->len); ASSERT_EQ(memcmp(pt, plaintext->x, ptLen), 0); #endif #ifdef HITLS_CRYPTO_RSA_ENCRYPT /* HiTLS public key encrypt */ ASSERT_EQ(CRYPT_EAL_PkeySetPub(pkey, &pubkey), CRYPT_SUCCESS); ASSERT_EQ(CRYPT_EAL_PkeyCtrl(pkey, padMode, paraPtr, paraSize), CRYPT_SUCCESS); ASSERT_EQ(CRYPT_EAL_PkeyEncrypt(pkey, plaintext->x, plaintext->len, ct, &ctLen), CRYPT_SUCCESS); ASSERT_EQ(ctLen, ciphertext->len); #endif #if defined(HITLS_CRYPTO_RSA_DECRYPT) && defined(HITLS_CRYPTO_RSA_ENCRYPT) /* HiTLS private key decrypt */ ASSERT_EQ(CRYPT_EAL_PkeyDecrypt(pkey, ct, ctLen, pt, &ptLen), CRYPT_SUCCESS); ASSERT_EQ(ptLen, plaintext->len); ASSERT_EQ(memcmp(pt, plaintext->x, ptLen), 0); #endif EXIT: #ifdef HITLS_CRYPTO_DRBG CRYPT_EAL_RandDeinit(); #endif CRYPT_EAL_PkeyFreeCtx(pkey); } /* END_CASE */ /** * @test SDV_CRYPTO_RSA_CRYPT_FUNC_TC002 * @title RSA EAL abnormal test: The encryption and decryption padding modes do not match. * @precon Vectors: a rsa key pair, plaintext * @brief * 1. Create the context(pkey) of the rsa algorithm, expected result 1 * 2. Initialize the DRBG. * 3. Set public key, and set padding mode to OAEP, expected result 2 * 4. Call the CRYPT_EAL_PkeyEncrypt to encrypt plaintext, expected result 3 * 5. Set private key, and set padding mode to PKCSV15, expected result 4 * 6. Call the CRYPT_EAL_PkeyDecrypt to decrypt the output of step 4, expected result 5 * 7. Set private key, and set padding mode to OAEP, expected result 6 * 8. Call the CRYPT_EAL_PkeyDecrypt to decrypt the output of step 4, expected result 7 * 9. Compare the output data of step 8 with plaintext, expected result 8 * @expect * 1. Success, and context is not NULL. * 2-4. CRYPT_SUCCESS * 5. CRYPT_RSA_NOR_VERIFY_FAIL * 6-7. CRYPT_SUCCESS * 8. Both are the same. */ /* BEGIN_CASE */ void SDV_CRYPTO_RSA_CRYPT_FUNC_TC002(Hex *n, Hex *e, Hex *d, Hex *plaintext, int isProvider) { TestMemInit(); uint8_t ct[MAX_CIPHERTEXT_LEN] = {0}; uint8_t pt[MAX_CIPHERTEXT_LEN] = {0}; uint32_t msgLen = MAX_CIPHERTEXT_LEN; CRYPT_EAL_PkeyCtx *pkey = NULL; CRYPT_EAL_PkeyPrv prvkey = {0}; CRYPT_EAL_PkeyPub pubkey = {0}; int32_t hashId = CRYPT_MD_SHA1; BSL_Param oaepParam[3] = { {CRYPT_PARAM_RSA_MD_ID, BSL_PARAM_TYPE_INT32, &hashId, sizeof(hashId), 0}, {CRYPT_PARAM_RSA_MGF1_ID, BSL_PARAM_TYPE_INT32, &hashId, sizeof(hashId), 0}, BSL_PARAM_END}; int32_t pkcsv15 = CRYPT_MD_SHA1; SetRsaPrvKey(&prvkey, n->x, n->len, d->x, d->len); SetRsaPubKey(&pubkey, n->x, n->len, e->x, e->len); pkey = TestPkeyNewCtx(NULL, CRYPT_PKEY_RSA, CRYPT_EAL_PKEY_KEYMGMT_OPERATE + CRYPT_EAL_PKEY_CIPHER_OPERATE, "provider=default", isProvider); ASSERT_TRUE(pkey != NULL); #ifdef HITLS_CRYPTO_DRBG CRYPT_RandRegist(RandFunc); CRYPT_RandRegistEx(RandFuncEx); #endif /* HiTLS public key encrypt: OAEP */ ASSERT_TRUE(CRYPT_EAL_PkeySetPub(pkey, &pubkey) == CRYPT_SUCCESS); ASSERT_TRUE(CRYPT_EAL_PkeyCtrl(pkey, CRYPT_CTRL_SET_RSA_RSAES_OAEP, oaepParam, 0) == CRYPT_SUCCESS); ASSERT_TRUE(CRYPT_EAL_PkeyEncrypt(pkey, plaintext->x, plaintext->len, ct, &msgLen) == CRYPT_SUCCESS); /* HiTLS private key encrypt: PKCSV15 */ ASSERT_TRUE(CRYPT_EAL_PkeySetPrv(pkey, &prvkey) == CRYPT_SUCCESS); ASSERT_TRUE(CRYPT_EAL_PkeyCtrl(pkey, CRYPT_CTRL_SET_RSA_RSAES_PKCSV15, &pkcsv15, sizeof(pkcsv15)) == CRYPT_SUCCESS); ASSERT_TRUE(CRYPT_EAL_PkeyDecrypt(pkey, ct, msgLen, pt, &msgLen) == CRYPT_RSA_NOR_VERIFY_FAIL); /* HiTLS private key encrypt: OAEP */ ASSERT_TRUE(CRYPT_EAL_PkeyCtrl(pkey, CRYPT_CTRL_SET_RSA_RSAES_OAEP, oaepParam, 0) == CRYPT_SUCCESS); ASSERT_TRUE(CRYPT_EAL_PkeyDecrypt(pkey, ct, msgLen, pt, &msgLen) == CRYPT_SUCCESS); ASSERT_TRUE(msgLen == plaintext->len); ASSERT_TRUE(memcmp(pt, plaintext->x, msgLen) == 0); EXIT: #ifdef HITLS_CRYPTO_DRBG CRYPT_EAL_RandDeinit(); #endif CRYPT_EAL_PkeyFreeCtx(pkey); } /* END_CASE */ /** * @test SDV_CRYPTO_RSA_CRYPT_FUNC_TC003 * @title RSA: Label test for OAP encryption and decryption * @precon Vectors: a rsa key pair, plaintext and label. * @brief * 1. Create the context(pkey) of the rsa algorithm, expected result 1 * 2. Initialize the DRBG. * 3. Set public key and private key, expected result 2 * 4. Set padding type to OAEP and set oaep-label, expected result 3 * 5. Call the CRYPT_EAL_PkeyEncrypt to encrypt plaintext, expected result 4 * 6. Call the CRYPT_EAL_PkeyDecrypt to decrypt the output of step 6, expected result 5 * 7. Compare the output data of step 6 with plaintext, expected result 6 * 8. Call the CRYPT_EAL_PkeyCopyCtx to copy pkey, expected result 7 * 9. Call the CRYPT_EAL_PkeyEncrypt to encrypt plaintext, expected result 8 * 10. Call the CRYPT_EAL_PkeyDecrypt to decrypt the output of step 8, expected result 9 * @expect * 1. Success, and context is not NULL. * 2-5. CRYPT_SUCCESS * 6. Both are the same. * 7-9. CRYPT_SUCCESS */ /* BEGIN_CASE */ void SDV_CRYPTO_RSA_CRYPT_FUNC_TC003(Hex *n, Hex *e, Hex *d, Hex *plaintext, Hex *label, int isProvider) { #if !defined(HITLS_CRYPTO_SHA2) || !defined(HITLS_CRYPTO_RSA_ENCRYPT) || !defined(HITLS_CRYPTO_RSA_DECRYPT) || \ !defined(HITLS_CRYPTO_RSAES_OAEP) SKIP_TEST(); #endif uint8_t ct[MAX_CIPHERTEXT_LEN] = {0}; uint8_t pt[MAX_CIPHERTEXT_LEN] = {0}; uint32_t msgLen = MAX_CIPHERTEXT_LEN; CRYPT_EAL_PkeyCtx *pkey = NULL; CRYPT_EAL_PkeyCtx *cpyCtx = NULL; CRYPT_EAL_PkeyPrv prvkey = {0}; CRYPT_EAL_PkeyPub pubkey = {0}; int32_t hashId = CRYPT_MD_SHA256; BSL_Param oaepParam[3] = { {CRYPT_PARAM_RSA_MD_ID, BSL_PARAM_TYPE_INT32, &hashId, sizeof(hashId), 0}, {CRYPT_PARAM_RSA_MGF1_ID, BSL_PARAM_TYPE_INT32, &hashId, sizeof(hashId), 0}, BSL_PARAM_END}; SetRsaPubKey(&pubkey, n->x, n->len, e->x, e->len); SetRsaPrvKey(&prvkey, n->x, n->len, d->x, d->len); TestMemInit(); pkey = TestPkeyNewCtx(NULL, CRYPT_PKEY_RSA, CRYPT_EAL_PKEY_KEYMGMT_OPERATE + CRYPT_EAL_PKEY_CIPHER_OPERATE, "provider=default", isProvider); ASSERT_TRUE(pkey != NULL); #ifdef HITLS_CRYPTO_DRBG CRYPT_RandRegist(RandFunc); CRYPT_RandRegistEx(RandFuncEx); #endif /* HiTLS pubenc, prvdec */ ASSERT_TRUE(CRYPT_EAL_PkeySetPub(pkey, &pubkey) == CRYPT_SUCCESS); ASSERT_TRUE(CRYPT_EAL_PkeySetPrv(pkey, &prvkey) == CRYPT_SUCCESS); ASSERT_EQ(CRYPT_EAL_PkeyCtrl(pkey, CRYPT_CTRL_SET_RSA_RSAES_OAEP, oaepParam, 0), CRYPT_SUCCESS); ASSERT_EQ(CRYPT_EAL_PkeyCtrl(pkey, CRYPT_CTRL_SET_RSA_OAEP_LABEL, label->x, label->len), CRYPT_SUCCESS); ASSERT_EQ(CRYPT_EAL_PkeyEncrypt(pkey, plaintext->x, plaintext->len, ct, &msgLen), CRYPT_SUCCESS); ASSERT_EQ(CRYPT_EAL_PkeyDecrypt(pkey, ct, msgLen, pt, &msgLen), CRYPT_SUCCESS); ASSERT_TRUE(msgLen == plaintext->len); ASSERT_TRUE(memcmp(pt, plaintext->x, msgLen) == 0); /* HiTLS copy ctx, pubenc, prvdec */ cpyCtx = TestPkeyNewCtx(NULL, CRYPT_PKEY_RSA, CRYPT_EAL_PKEY_KEYMGMT_OPERATE + CRYPT_EAL_PKEY_SIGN_OPERATE, "provider=default", isProvider); ASSERT_TRUE(cpyCtx != NULL); ASSERT_EQ(CRYPT_EAL_PkeyCopyCtx(cpyCtx, pkey), CRYPT_SUCCESS); msgLen = MAX_CIPHERTEXT_LEN; ASSERT_TRUE(CRYPT_EAL_PkeyEncrypt(cpyCtx, plaintext->x, plaintext->len, ct, &msgLen) == CRYPT_SUCCESS); ASSERT_TRUE(CRYPT_EAL_PkeyDecrypt(cpyCtx, ct, msgLen, pt, &msgLen) == CRYPT_SUCCESS); EXIT: #ifdef HITLS_CRYPTO_DRBG CRYPT_EAL_RandDeinit(); #endif CRYPT_EAL_PkeyFreeCtx(pkey); CRYPT_EAL_PkeyFreeCtx(cpyCtx); } /* END_CASE */
2301_79861745/bench_create
testcode/sdv/testcase/crypto/rsa/test_suite_sdv_eal_rsa_encrypt_decrypt.c
C
unknown
12,277
/* * This file is part of the openHiTLS project. * * openHiTLS is licensed under the Mulan PSL v2. * You can use this software according to the terms and conditions of the Mulan PSL v2. * You may obtain a copy of Mulan PSL v2 at: * * http://license.coscl.org.cn/MulanPSL2 * * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. * See the Mulan PSL v2 for more details. */ /* INCLUDE_BASE test_suite_sdv_eal_rsa */ /* BEGIN_HEADER */ #include <unistd.h> #include <stdlib.h> #include <pthread.h> #include "bsl_errno.h" #include "crypt_eal_md.h" #include "bsl_params.h" #include "crypt_params_key.h" #include "crypt_bn.h" /* END_HEADER */ #define CRYPT_EAL_PKEY_KEYMGMT_OPERATE 0 int MD_Data(CRYPT_MD_AlgId mdId, Hex *msgIn, Hex *mdOut) { uint32_t outLen; CRYPT_EAL_MdCTX *mdCtx = NULL; uint32_t mdOutLen = CRYPT_EAL_MdGetDigestSize(mdId); ASSERT_TRUE(mdOutLen != 0); mdOut->x = (uint8_t *)malloc(mdOutLen); ASSERT_TRUE(mdOut->x != NULL); mdOut->len = mdOutLen; outLen = mdOutLen; mdCtx = CRYPT_EAL_MdNewCtx(mdId); ASSERT_TRUE_AND_LOG("CRYPT_EAL_MdNewCtx", mdCtx != NULL); ASSERT_TRUE_AND_LOG("CRYPT_EAL_MdInit", CRYPT_EAL_MdInit(mdCtx) == 0); ASSERT_TRUE_AND_LOG("CRYPT_EAL_MdUpdate", CRYPT_EAL_MdUpdate(mdCtx, msgIn->x, msgIn->len) == 0); ASSERT_TRUE_AND_LOG("CRYPT_EAL_MdFinal", CRYPT_EAL_MdFinal(mdCtx, mdOut->x, &outLen) == 0); mdOut->len = outLen; CRYPT_EAL_MdFreeCtx(mdCtx); return SUCCESS; EXIT: CRYPT_EAL_MdFreeCtx(mdCtx); free(mdOut->x); mdOut->x = NULL; return FAIL; } /** * @test SDV_CRYPTO_RSA_SIGN_API_TC001 * @title RSA CRYPT_EAL_PkeySign: Wrong parameters. * @precon Create the context of the rsa algorithm, set private key and set padding type to pkcsv15: * @brief * 1. Call the CRYPT_EAL_PkeySetPrv method: * (1) pkey = null, expected result 1. * (2) data = null, dataLen = 0, expected result 2. * (3) data = null, dataLen != 0, expected result 3. * (4) data != null, dataLen = 0, expected result 4. * (5) sign = null, signLen != 0, expected result 5. * (6) sign != null, signLen = 0, expected result 6. * (7) sign != null, signLen == NULL, expected result 7. * 2. Call the CRYPT_EAL_PkeySetPrv method with incorrect hash id, expected result 8: * CRYPT_MD_MD5, CRYPT_MD_SHA1, CRYPT_MD_SM3, CRYPT_MD_MAX * @expect * 1. CRYPT_NULL_INPUT * 2. CRYPT_SUCCESS * 3. CRYPT_NULL_INPUT * 4. CRYPT_SUCCESS * 5. CRYPT_NULL_INPUT * 6. CRYPT_RSA_BUFF_LEN_NOT_ENOUGH * 7. CRYPT_NULL_INPUT * 8. Return CRYPT_RSA_ERR_ALGID or CRYPT_EAL_ERR_ALGID */ /* BEGIN_CASE */ void SDV_CRYPTO_RSA_SIGN_API_TC001(Hex *n, Hex *d, int isProvider) { int32_t ret; CRYPT_EAL_PkeyCtx *pkeyCtx = NULL; CRYPT_EAL_PkeyPrv privaKey = {0}; uint8_t *data = NULL; uint8_t *sign = NULL; uint32_t signLen = d->len + 1; uint32_t dataLen = signLen; int32_t pkcsv15 = CRYPT_MD_SHA224; CRYPT_MD_AlgId errIdList[] = {CRYPT_MD_MD5, CRYPT_MD_SHA1, CRYPT_MD_SM3, CRYPT_MD_MAX}; /* Malloc signature buffer */ sign = (uint8_t *)malloc(signLen); data = (uint8_t *)malloc(signLen); ASSERT_TRUE(sign != NULL && data != NULL); SetRsaPrvKey(&privaKey, n->x, n->len, d->x, d->len); TestMemInit(); pkeyCtx = TestPkeyNewCtx(NULL, CRYPT_PKEY_RSA, CRYPT_EAL_PKEY_KEYMGMT_OPERATE + CRYPT_EAL_PKEY_SIGN_OPERATE, "provider=default", isProvider); ASSERT_TRUE(pkeyCtx != NULL); ASSERT_EQ(CRYPT_EAL_PkeySetPrv(pkeyCtx, &privaKey), CRYPT_SUCCESS); ASSERT_EQ(CRYPT_EAL_PkeyCtrl(pkeyCtx, CRYPT_CTRL_SET_RSA_EMSA_PKCSV15, &pkcsv15, sizeof(pkcsv15)), CRYPT_SUCCESS); ASSERT_EQ(CRYPT_EAL_PkeySign(NULL, CRYPT_MD_SHA224, data, dataLen, sign, &signLen), CRYPT_NULL_INPUT); ASSERT_EQ(CRYPT_EAL_PkeySign(pkeyCtx, CRYPT_MD_SHA224, NULL, 0, sign, &signLen), CRYPT_SUCCESS); ASSERT_EQ(CRYPT_EAL_PkeySign(pkeyCtx, CRYPT_MD_SHA224, NULL, dataLen, sign, &signLen), CRYPT_NULL_INPUT); ASSERT_EQ(CRYPT_EAL_PkeySign(pkeyCtx, CRYPT_MD_SHA224, data, 0, sign, &signLen), CRYPT_SUCCESS); ASSERT_EQ(CRYPT_EAL_PkeySign(pkeyCtx, CRYPT_MD_SHA224, data, dataLen, NULL, &signLen), CRYPT_NULL_INPUT); ASSERT_EQ(CRYPT_EAL_PkeySign(pkeyCtx, CRYPT_MD_SHA224, data, dataLen, sign, NULL), CRYPT_NULL_INPUT); signLen = 0; ASSERT_EQ( CRYPT_EAL_PkeySign(pkeyCtx, CRYPT_MD_SHA224, data, dataLen, sign, &signLen), CRYPT_RSA_BUFF_LEN_NOT_ENOUGH); signLen = dataLen; for (int i = 0; i < (int)(sizeof(errIdList) / sizeof(CRYPT_MD_AlgId)); i++) { ret = CRYPT_EAL_PkeySign(pkeyCtx, errIdList[i], data, dataLen, sign, &signLen); ASSERT_TRUE(ret == CRYPT_RSA_ERR_ALGID || ret == CRYPT_EAL_ERR_ALGID); } EXIT: CRYPT_EAL_PkeyFreeCtx(pkeyCtx); free(data); free(sign); } /* END_CASE */ /** * @test SDV_CRYPTO_RSA_SIGN_PKCSV15_FUNC_TC001 * @title RSA EAL layer signature function test: PKCSV15, sha224 * @precon nan * @brief * 1. Create the context(pkeyCtx) of the rsa algorithm, expected result 1 * 2. Set the private key for pkeyCtx, expected result 2 * 3. Set the padding algorithm to PKCS15 and set the hash value to SHA224, expected result 3 * 4. Call the CRYPT_EAL_PkeySign method with invalid mdId, expected result 4 * 5. Call the CRYPT_EAL_PkeySign method to compute signature, expected result 5 * @expect * 1. Success, and context is not NULL. * 2-3. CRYPT_SUCCESS * 4. CRYPT_EAL_ERR_ALGID * 5. CRYPT_SUCCESS */ /* BEGIN_CASE */ void SDV_CRYPTO_RSA_SIGN_PKCSV15_FUNC_TC001(Hex *n, Hex *d, Hex *msg, Hex *sign, int isProvider) { CRYPT_EAL_PkeyCtx *pkeyCtx = NULL; CRYPT_EAL_PkeyPrv privaKey = {0}; uint8_t *signdata = NULL; uint32_t signLen = sign->len; int32_t pkcsv15 = CRYPT_MD_SHA224; /* Malloc signature buffer */ signdata = (uint8_t *)malloc(signLen); ASSERT_TRUE(signdata != NULL); SetRsaPrvKey(&privaKey, n->x, n->len, d->x, d->len); TestMemInit(); pkeyCtx = TestPkeyNewCtx(NULL, CRYPT_PKEY_RSA, CRYPT_EAL_PKEY_KEYMGMT_OPERATE + CRYPT_EAL_PKEY_SIGN_OPERATE, "provider=default", isProvider); ASSERT_TRUE(pkeyCtx != NULL); ASSERT_EQ(CRYPT_EAL_PkeySetPrv(pkeyCtx, &privaKey), CRYPT_SUCCESS); ASSERT_EQ(CRYPT_EAL_PkeyCtrl(pkeyCtx, CRYPT_CTRL_SET_RSA_EMSA_PKCSV15, &pkcsv15, sizeof(pkcsv15)), CRYPT_SUCCESS); ASSERT_EQ(CRYPT_EAL_PkeySign(pkeyCtx, CRYPT_MD_SHA224, msg->x, msg->len, signdata, &signLen), CRYPT_SUCCESS); EXIT: CRYPT_EAL_PkeyFreeCtx(pkeyCtx); free(signdata); } /* END_CASE */ /** * @test SDV_CRYPTO_RSA_SIGN_PKCSV15_FUNC_TC002 * @title RSA EAL layer signature function test: PKCSV15 * @precon nan * @brief * 1. Create the context(pkeyCtx) of the rsa algorithm, expected result 1 * 2. Set the private key for pkeyCtx, expected result 2 * 3. Set the padding algorithm to PKCS15 and set the hash value to SHA2, expected result 3 * 4. Call the CRYPT_EAL_PkeySign method to compute signature, expected result 4 * 5. Compare the signature result and the signature vector., expected result 5 * @expect * 1. Success, and context is not NULL. * 2. CRYPT_SUCCESS * 3. CRYPT_SUCCESS * 4. CRYPT_SUCCESS * 5. Both are the same. */ /* BEGIN_CASE */ void SDV_CRYPTO_RSA_SIGN_PKCSV15_FUNC_TC002(int mdId, Hex *n, Hex *d, Hex *msg, Hex *sign, int isProvider) { #if !defined(HITLS_CRYPTO_RSA_SIGN) || !defined(HITLS_CRYPTO_RSA_EMSA_PKCSV15) SKIP_TEST(); #endif if (IsMdAlgDisabled(mdId)) { SKIP_TEST(); } CRYPT_EAL_PkeyCtx *pkeyCtx = NULL; CRYPT_EAL_PkeyPrv privaKey = {0}; int32_t pkcsv15 = mdId; uint8_t *signdata = NULL; uint32_t signLen; SetRsaPrvKey(&privaKey, n->x, n->len, d->x, d->len); TestMemInit(); pkeyCtx = TestPkeyNewCtx(NULL, CRYPT_PKEY_RSA, CRYPT_EAL_PKEY_KEYMGMT_OPERATE + CRYPT_EAL_PKEY_SIGN_OPERATE, "provider=default", isProvider); ASSERT_TRUE(pkeyCtx != NULL); ASSERT_EQ(CRYPT_EAL_PkeySetPrv(pkeyCtx, &privaKey), CRYPT_SUCCESS); ASSERT_EQ(CRYPT_EAL_PkeyCtrl(pkeyCtx, CRYPT_CTRL_SET_RSA_EMSA_PKCSV15, &pkcsv15, sizeof(pkcsv15)), 0); /* Malloc signature buffer */ signLen = CRYPT_EAL_PkeyGetSignLen(pkeyCtx); ASSERT_EQ(signLen, sign->len); signdata = (uint8_t *)malloc(signLen); ASSERT_TRUE(signdata != NULL); ASSERT_EQ(CRYPT_EAL_PkeySign(pkeyCtx, mdId, msg->x, msg->len, signdata, &signLen), CRYPT_SUCCESS); ASSERT_COMPARE("CRYPT_EAL_PkeySign Compare", sign->x, sign->len, signdata, signLen); EXIT: CRYPT_EAL_PkeyFreeCtx(pkeyCtx); free(signdata); } /* END_CASE */ /** * @test SDV_CRYPTO_RSA_SIGN_PSS_FUNC_TC001 * @title RSA EAL layer signature function test: Pss * @precon nan * @brief * 1. Create the context(pkeyCtx) of the rsa algorithm, expected result 1 * 2. Set the private key for pkeyCtx, expected result 2 * 3. Set the padding algorithm to PKCS15 and set the hash value to SHA2, expected result 3 * 4. Call the CRYPT_EAL_PkeySign method to compute signature, expected result 4 * 5. Compare the signature result and the signature vector., expected result 5 * @expect * 1. Success, and context is not NULL. * 2-4. CRYPT_SUCCESS * 5. Both are the same. */ /* BEGIN_CASE */ void SDV_CRYPTO_RSA_SIGN_PSS_FUNC_TC001(int mdId, Hex *n, Hex *d, Hex *msg, Hex *sign, Hex *salt, int isProvider) { #if !defined(HITLS_CRYPTO_RSA_SIGN) || !defined(HITLS_CRYPTO_RSA_EMSA_PSS) SKIP_TEST(); #endif if (IsMdAlgDisabled(mdId)) { SKIP_TEST(); } int i; CRYPT_EAL_PkeyCtx *pkeyCtx = NULL; CRYPT_EAL_PkeyPrv privaKey = {0}; BSL_Param pssParam[4] = { {CRYPT_PARAM_RSA_MD_ID, BSL_PARAM_TYPE_INT32, &mdId, sizeof(mdId), 0}, {CRYPT_PARAM_RSA_MGF1_ID, BSL_PARAM_TYPE_INT32, &mdId, sizeof(mdId), 0}, {CRYPT_PARAM_RSA_SALTLEN, BSL_PARAM_TYPE_INT32, &salt->len, sizeof(salt->len), 0}, BSL_PARAM_END}; uint8_t *signdata = NULL; uint32_t signLen = sign->len; SetRsaPrvKey(&privaKey, n->x, n->len, d->x, d->len); /* Malloc signature buffer */ signdata = (uint8_t *)malloc(signLen); ASSERT_TRUE(signdata != NULL); TestMemInit(); pkeyCtx = TestPkeyNewCtx(NULL, CRYPT_PKEY_RSA, CRYPT_EAL_PKEY_KEYMGMT_OPERATE + CRYPT_EAL_PKEY_SIGN_OPERATE, "provider=default", isProvider); ASSERT_TRUE(pkeyCtx != NULL); ASSERT_EQ(CRYPT_EAL_PkeySetPrv(pkeyCtx, &privaKey), CRYPT_SUCCESS); ASSERT_EQ(CRYPT_EAL_PkeyCtrl(pkeyCtx, CRYPT_CTRL_SET_RSA_EMSA_PSS, pssParam, 0), CRYPT_SUCCESS); /* Repeat signature 2 times. */ for (i = 0; i < 2; i++) { if (salt->len != 0) { ASSERT_EQ(CRYPT_EAL_PkeyCtrl(pkeyCtx, CRYPT_CTRL_SET_RSA_SALT, salt->x, salt->len), CRYPT_SUCCESS); } ASSERT_EQ(CRYPT_EAL_PkeySign(pkeyCtx, mdId, msg->x, msg->len, signdata, &signLen), CRYPT_SUCCESS); ASSERT_COMPARE("Compare Sign Data", signdata, signLen, sign->x, sign->len); signLen = sign->len; } EXIT: CRYPT_EAL_PkeyFreeCtx(pkeyCtx); free(signdata); } /* END_CASE */ /** * @test SDV_CRYPTO_RSA_SIGN_PSS_FUNC_TC002 * @title RSA EAL layer signature function test: Pss with different salt lengths. * @precon nan * @brief * 1. Create the context(pkeyCtx) of the rsa algorithm, expected result 1 * 2. Initialize the DRBG, expected result 2 * 3. Set the private key for pkeyCtx, expected result 3 * 4. Set the padding algorithm to PSS and set the hash value to SHA2, expected result 4 * 5. Call the CRYPT_EAL_PkeySign method to compute signature, expected result 5 * @expect * 1. Success, and context is not NULL. * 2-5. CRYPT_SUCCESS */ /* BEGIN_CASE */ void SDV_CRYPTO_RSA_SIGN_PSS_FUNC_TC002(int mdId, Hex *n, Hex *d, Hex *msg, int saltLen, int isProvider) { #if !defined(HITLS_CRYPTO_RSA_SIGN) || !defined(HITLS_CRYPTO_RSA_EMSA_PSS) || !defined(HITLS_CRYPTO_DRBG) SKIP_TEST(); #endif if (IsMdAlgDisabled(mdId)) { SKIP_TEST(); } CRYPT_EAL_PkeyCtx *pkeyCtx = NULL; CRYPT_EAL_PkeyPrv privaKey = {0}; uint8_t *signdata = NULL; uint32_t signLen; BSL_Param pssParam[4] = { {CRYPT_PARAM_RSA_MD_ID, BSL_PARAM_TYPE_INT32, &mdId, sizeof(mdId), 0}, {CRYPT_PARAM_RSA_MGF1_ID, BSL_PARAM_TYPE_INT32, &mdId, sizeof(mdId), 0}, {CRYPT_PARAM_RSA_SALTLEN, BSL_PARAM_TYPE_INT32, &saltLen, sizeof(saltLen), 0}, BSL_PARAM_END}; SetRsaPrvKey(&privaKey, n->x, n->len, d->x, d->len); TestMemInit(); pkeyCtx = TestPkeyNewCtx(NULL, CRYPT_PKEY_RSA, CRYPT_EAL_PKEY_KEYMGMT_OPERATE + CRYPT_EAL_PKEY_SIGN_OPERATE, "provider=default", isProvider); ASSERT_TRUE(pkeyCtx != NULL); ASSERT_EQ(CRYPT_EAL_PkeySetPrv(pkeyCtx, &privaKey), CRYPT_SUCCESS); #ifdef HITLS_CRYPTO_DRBG ASSERT_EQ(TestRandInit(), CRYPT_SUCCESS); #endif ASSERT_EQ(CRYPT_EAL_PkeyCtrl(pkeyCtx, CRYPT_CTRL_SET_RSA_EMSA_PSS, pssParam, 0), CRYPT_SUCCESS); /* Malloc signature buffer */ signLen = CRYPT_EAL_PkeyGetSignLen(pkeyCtx); ASSERT_TRUE(signLen != 0); signdata = (uint8_t *)malloc(signLen); ASSERT_TRUE(signdata != NULL); ASSERT_EQ(CRYPT_EAL_PkeySign(pkeyCtx, mdId, msg->x, msg->len, signdata, &signLen), CRYPT_SUCCESS); EXIT: #ifdef HITLS_CRYPTO_DRBG TestRandDeInit(); #endif CRYPT_EAL_PkeyFreeCtx(pkeyCtx); free(signdata); } /* END_CASE */ /** * @test SDV_CRYPTO_RSA_SIGN_PSS_FUNC_TC003 * @title RSA EAL layer signature function test: Do not set the salt length of PSS. * @precon Vectors: private key, msg. * @brief * 1. Create the context(pkeyCtx) of the rsa algorithm, expected result 1 * 2. Set the private key for pkeyCtx, expected result 2 * 3. Initialize the DRBG, expected result 3 * 4. Set the padding algorithm to PSS, saltLen is 0 | -1 | -2, expected result 4 * 5. Call the CRYPT_EAL_PkeySign method to compute signature, expected result 5 * @expect * 1. Success, and context is not NULL. * 2-4. CRYPT_SUCCESS */ /* BEGIN_CASE */ void SDV_CRYPTO_RSA_SIGN_PSS_FUNC_TC003(Hex *n, Hex *d, Hex *msg, int saltLen, int isProvider) { CRYPT_EAL_PkeyCtx *pkeyCtx = NULL; CRYPT_EAL_PkeyPrv privaKey = {0}; uint8_t *signdata = NULL; uint32_t signLen; int32_t mdId = CRYPT_MD_SHA224; BSL_Param pssParam[4] = { {CRYPT_PARAM_RSA_MD_ID, BSL_PARAM_TYPE_INT32, &mdId, sizeof(mdId), 0}, {CRYPT_PARAM_RSA_MGF1_ID, BSL_PARAM_TYPE_INT32, &mdId, sizeof(mdId), 0}, {CRYPT_PARAM_RSA_SALTLEN, BSL_PARAM_TYPE_INT32, &saltLen, sizeof(saltLen), 0}, BSL_PARAM_END}; SetRsaPrvKey(&privaKey, n->x, n->len, d->x, d->len); TestMemInit(); pkeyCtx = TestPkeyNewCtx(NULL, CRYPT_PKEY_RSA, CRYPT_EAL_PKEY_KEYMGMT_OPERATE + CRYPT_EAL_PKEY_SIGN_OPERATE, "provider=default", isProvider); ASSERT_TRUE(pkeyCtx != NULL); ASSERT_EQ(CRYPT_EAL_PkeySetPrv(pkeyCtx, &privaKey), CRYPT_SUCCESS); #ifdef HITLS_CRYPTO_DRBG ASSERT_EQ(TestRandInit(), CRYPT_SUCCESS); #endif ASSERT_EQ(CRYPT_EAL_PkeyCtrl(pkeyCtx, CRYPT_CTRL_SET_RSA_EMSA_PSS, pssParam, 0), CRYPT_SUCCESS); /* Malloc signature buffer */ signLen = CRYPT_EAL_PkeyGetSignLen(pkeyCtx); ASSERT_TRUE(signLen != 0); signdata = (uint8_t *)malloc(signLen); ASSERT_TRUE(signdata != NULL); ASSERT_EQ(CRYPT_EAL_PkeySign(pkeyCtx, CRYPT_MD_SHA224, msg->x, msg->len, signdata, &signLen), CRYPT_SUCCESS); EXIT: #ifdef HITLS_CRYPTO_DRBG TestRandDeInit(); #endif CRYPT_EAL_PkeyFreeCtx(pkeyCtx); free(signdata); } /* END_CASE */ /** * @test SDV_CRYPTO_RSA_GEN_SIGN_VERIFY_PKCSV15_FUNC_TC001 * @title RSA EAL sign/verify and signData/verifyData:PKCSV15, sha256 * @precon * @brief * 1. Create the context(pkeyCtx) of the rsa algorithm, expected result 1 * 2. Call the CRYPT_EAL_PkeySetPara, where bits are: 1024/2048/4096, expected result 2 * 3. Initialize the DRBG, expected result 3 * 4. Call the CRYPT_EAL_PkeyGen to generate a key pair, expected result 4 * 5. Call the CRYPT_EAL_PkeyGen to generate a key pair again, expected result 5 * 6. Set padding type to pkcsv15, expected result 6 * 7. Call the CRYPT_EAL_PkeySign method and use pkey to sign a piece of data, expected result 7 * 8. Call the CRYPT_EAL_PkeyVerify method and use pkey to verify the signed data, expected result 8 * 9. Call the CRYPT_EAL_PkeySignData method and use pkey to sign a piece of hash data, expected result 9 * 10. Call the CRYPT_EAL_PkeyVerifyData method and use pkey to verify the signed data, expected result 10 * 11. Allocate the memory for the CRYPT_EAL_PkeyCtx, named cpyCtx, expected result 11 * 12. Call the CRYPT_EAL_PkeyCopyCtx to copy pkeyCtx, expected result 12 * 13. Call the CRYPT_EAL_PkeySignData method and use cpyCtx to sign a piece of data, expected result 13 * 14. Call the CRYPT_EAL_PkeyVerifyData method and use cpyCtx to verify the signed data, expected result 14 * @expect * 1. Success, and context is not NULL. * 2-10. CRYPT_SUCCESS * 11. Success. * 12-14. CRYPT_SUCCESS */ /* BEGIN_CASE */ void SDV_CRYPTO_RSA_GEN_SIGN_VERIFY_PKCSV15_FUNC_TC001(int bits, int isProvider) { #ifndef HITLS_CRYPTO_SHA256 SKIP_TEST(); #endif uint32_t signLen = (bits + 7) >> 3; // keybytes == (keyBits + 7) >> 3 */ int mdId = CRYPT_MD_SHA256; uint8_t data[500] = {0}; const uint32_t dataLen = sizeof(data); uint8_t hash[32]; // SHA256 digest length: 32 const uint32_t hashLen = sizeof(hash); uint8_t e[] = {1, 0, 1}; CRYPT_EAL_PkeyCtx *pkey = NULL; CRYPT_EAL_PkeyCtx *cpyCtx = NULL; int32_t pkcsv15 = mdId; CRYPT_EAL_PkeyPara para = {0}; SetRsaPara(&para, e, 3, bits); uint8_t *sign = malloc(signLen); ASSERT_TRUE_AND_LOG("Malloc Sign Buffer", sign != NULL); TestMemInit(); pkey = TestPkeyNewCtx(NULL, CRYPT_PKEY_RSA, CRYPT_EAL_PKEY_KEYMGMT_OPERATE + CRYPT_EAL_PKEY_SIGN_OPERATE, "provider=default", isProvider); ASSERT_TRUE(pkey != NULL); ASSERT_EQ(CRYPT_EAL_PkeySetPara(pkey, &para), CRYPT_SUCCESS); #ifdef HITLS_CRYPTO_DRBG ASSERT_EQ(TestRandInit(), CRYPT_SUCCESS); #endif ASSERT_EQ(CRYPT_EAL_PkeyGen(pkey), CRYPT_SUCCESS); ASSERT_EQ(CRYPT_EAL_PkeyGen(pkey), CRYPT_SUCCESS); ASSERT_EQ(CRYPT_EAL_PkeyCtrl(pkey, CRYPT_CTRL_SET_RSA_EMSA_PKCSV15, &pkcsv15, sizeof(pkcsv15)), CRYPT_SUCCESS); ASSERT_EQ(CRYPT_EAL_PkeySign(pkey, mdId, data, dataLen, sign, &signLen), CRYPT_SUCCESS); ASSERT_EQ(CRYPT_EAL_PkeyVerify(pkey, mdId, data, dataLen, sign, signLen), CRYPT_SUCCESS); signLen = (bits + 7) >> 3; // keybytes == (keyBits + 7) >> 3 */ memset_s(hash, sizeof(hash), 'A', sizeof(hash)); ASSERT_EQ(CRYPT_EAL_PkeySignData(pkey, hash, hashLen, sign, &signLen), CRYPT_SUCCESS); ASSERT_EQ(CRYPT_EAL_PkeyVerifyData(pkey, hash, hashLen, sign, signLen), CRYPT_SUCCESS); cpyCtx = TestPkeyNewCtx(NULL, CRYPT_PKEY_RSA, CRYPT_EAL_PKEY_KEYMGMT_OPERATE + CRYPT_EAL_PKEY_SIGN_OPERATE, "provider=default", isProvider); ASSERT_TRUE(cpyCtx != NULL); ASSERT_EQ(CRYPT_EAL_PkeyCopyCtx(cpyCtx, pkey), CRYPT_SUCCESS); signLen = (bits + 7) >> 3; ASSERT_EQ(CRYPT_EAL_PkeySign(cpyCtx, mdId, data, dataLen, sign, &signLen), CRYPT_SUCCESS); ASSERT_EQ(CRYPT_EAL_PkeyVerify(cpyCtx, mdId, data, dataLen, sign, signLen), CRYPT_SUCCESS); EXIT: #ifdef HITLS_CRYPTO_DRBG TestRandDeInit(); #endif CRYPT_EAL_PkeyFreeCtx(pkey); CRYPT_EAL_PkeyFreeCtx(cpyCtx); free(sign); } /* END_CASE */ /** * @test SDV_CRYPTO_RSA_GEN_SIGN_VERIFY_PSS_FUNC_TC001 * @title RSA EAL signData/verifyData: pss, sha256, saltLen=32bytes * @precon * @brief * 1. Create the context(pkeyCtx) of the rsa algorithm, expected result 1 * 2. Call the CRYPT_EAL_PkeySetPara, where bits is 1025, expected result 2 * 3. Initialize the DRBG, expected result 3 * 4. Call the CRYPT_EAL_PkeyGen to generate a key pair, expected result 4 * 5. Set padding type to pkcsv15 and set salt(32 bytes), expected result 5 * 6. Call the CRYPT_EAL_PkeySignData method and use pkey to sign a piece of data, expected result 6 * 7. Call the CRYPT_EAL_PkeyVerifyData method and use pkey to verify the signed data, expected result 7 * 8. Allocate the memory for the CRYPT_EAL_PkeyCtx, named cpyCtx, expected result 8 * 9. Call the CRYPT_EAL_PkeyCopyCtx to copy pkeyCtx, expected result 9 * 10. Call the CRYPT_EAL_PkeySignData method and use cpyCtx to sign a piece of data, expected result 10 * 11. Call the CRYPT_EAL_PkeyVerifyData method and use cpyCtx to verify the signed data, expected result 11 * @expect * 1. Success, and context is not NULL. * 2-7. CRYPT_SUCCESS * 8. Success. * 9-11. CRYPT_SUCCESS */ /* BEGIN_CASE */ void SDV_CRYPTO_RSA_GEN_SIGN_VERIFY_PSS_FUNC_TC001(int bits, int isProvider) { #ifndef HITLS_CRYPTO_SHA256 SKIP_TEST(); #endif CRYPT_EAL_PkeyCtx *pkey = NULL; CRYPT_EAL_PkeyCtx *cpyCtx = NULL; int32_t mdId = CRYPT_MD_SHA256; int32_t saltLen = 32; BSL_Param pssParam[4] = { {CRYPT_PARAM_RSA_MD_ID, BSL_PARAM_TYPE_INT32, &mdId, sizeof(mdId), 0}, {CRYPT_PARAM_RSA_MGF1_ID, BSL_PARAM_TYPE_INT32, &mdId, sizeof(mdId), 0}, {CRYPT_PARAM_RSA_SALTLEN, BSL_PARAM_TYPE_INT32, &saltLen, sizeof(saltLen), 0}, BSL_PARAM_END}; CRYPT_EAL_PkeyPara para = {0}; uint8_t e[] = {1, 0, 1}; uint8_t salt[100]; uint32_t signLen = (bits + 7) >> 3; // keybytes == (keyBits + 7) >> 3 */ uint8_t hash[32]; // SHA256 digest length 32 const uint32_t hashLen = sizeof(hash); memset_s(hash, sizeof(hash), 'A', sizeof(hash)); (void)memset_s(salt, sizeof(salt), 'A', sizeof(salt)); uint8_t *sign = malloc(signLen); ASSERT_TRUE(sign != NULL); SetRsaPara(&para, e, 3, bits); TestMemInit(); pkey = TestPkeyNewCtx(NULL, CRYPT_PKEY_RSA, CRYPT_EAL_PKEY_KEYMGMT_OPERATE + CRYPT_EAL_PKEY_SIGN_OPERATE, "provider=default", isProvider); ASSERT_TRUE(pkey != NULL); ASSERT_EQ(CRYPT_EAL_PkeySetPara(pkey, &para), CRYPT_SUCCESS); #ifdef HITLS_CRYPTO_DRBG ASSERT_EQ(TestRandInit(), CRYPT_SUCCESS); #endif ASSERT_EQ(CRYPT_EAL_PkeyGen(pkey), CRYPT_SUCCESS); ASSERT_TRUE_AND_LOG("Malloc Sign Buffer", sign != NULL); ASSERT_EQ(CRYPT_EAL_PkeyCtrl(pkey, CRYPT_CTRL_SET_RSA_EMSA_PSS, pssParam, 0), CRYPT_SUCCESS); ASSERT_EQ(CRYPT_EAL_PkeyCtrl(pkey, CRYPT_CTRL_SET_RSA_SALT, (uint8_t *)salt, 32), CRYPT_SUCCESS); ASSERT_EQ(CRYPT_EAL_PkeySignData(pkey, hash, hashLen, sign, &signLen), CRYPT_SUCCESS); ASSERT_EQ(CRYPT_EAL_PkeyVerifyData(pkey, hash, hashLen, sign, signLen), CRYPT_SUCCESS); cpyCtx = TestPkeyNewCtx(NULL, CRYPT_PKEY_RSA, CRYPT_EAL_PKEY_KEYMGMT_OPERATE + CRYPT_EAL_PKEY_SIGN_OPERATE, "provider=default", isProvider); ASSERT_TRUE(cpyCtx != NULL); ASSERT_EQ(CRYPT_EAL_PkeyCopyCtx(cpyCtx, pkey), CRYPT_SUCCESS); ASSERT_EQ(CRYPT_EAL_PkeyCtrl(cpyCtx, CRYPT_CTRL_SET_RSA_SALT, (uint8_t *)salt, 32), CRYPT_SUCCESS); ASSERT_EQ(CRYPT_EAL_PkeySignData(cpyCtx, hash, hashLen, sign, &signLen), CRYPT_SUCCESS); ASSERT_EQ(CRYPT_EAL_PkeyVerifyData(cpyCtx, hash, hashLen, sign, signLen), CRYPT_SUCCESS); EXIT: #ifdef HITLS_CRYPTO_DRBG TestRandDeInit(); #endif CRYPT_EAL_PkeyFreeCtx(pkey); CRYPT_EAL_PkeyFreeCtx(cpyCtx); free(sign); } /* END_CASE */ /** * @test SDV_CRYPTO_RSA_GEN_SIGN_VERIFY_PKCSV15_FUNC_TC002 * @title RSA EAL sign/verify:Generate a key pair, set pubKey, PKCSV15, sha256 * @precon * @brief * 1. Create the contexts(pkey, pkey2) of the rsa algorithm, expected result 1 * 2. Set para for pkey and pkey2, expected result 2 * 3. Initialize the DRBG, expected result 3 * 4. Call the CRYPT_EAL_PkeyGen to generate a key pair, expected result 4 * 5. Get public key from pkey, expected result 5 * 6. Set public key for pkey2, expected result 6 * 7. Set padding type to pkcsv15 for pkey and pkey2, expected result 7 * 8. Call the CRYPT_EAL_PkeySign method and use pkey to sign a piece of data, expected result8 * 9. Call the CRYPT_EAL_PkeyVerify method and use pkey2 to verify the signed data, expected result 9 * @expect * 1. Success, and context is not NULL. * 2-9. CRYPT_SUCCESS */ /* BEGIN_CASE */ void SDV_CRYPTO_RSA_GEN_SIGN_VERIFY_PKCSV15_FUNC_TC002(int isProvider) { CRYPT_EAL_PkeyCtx *pkey = NULL; CRYPT_EAL_PkeyCtx *pkey2 = NULL; CRYPT_EAL_PkeyPara para = {0}; CRYPT_EAL_PkeyPub pubKey = {0}; int32_t pkcsv15 = CRYPT_MD_SHA256; uint8_t pubN[600]; uint8_t pubE[600]; uint8_t e[] = {1, 0, 1}; uint8_t sign[200]; uint32_t signLen = 200; // 200bytes is greater than 1024 bits. uint8_t data[500] = {0}; const uint32_t dataLen = 500; SetRsaPara(&para, e, 3, 1024); SetRsaPubKey(&pubKey, pubN, 600, pubE, 600); TestMemInit(); pkey = TestPkeyNewCtx(NULL, CRYPT_PKEY_RSA, CRYPT_EAL_PKEY_KEYMGMT_OPERATE + CRYPT_EAL_PKEY_SIGN_OPERATE, "provider=default", isProvider); pkey2 = TestPkeyNewCtx(NULL, CRYPT_PKEY_RSA, CRYPT_EAL_PKEY_KEYMGMT_OPERATE + CRYPT_EAL_PKEY_SIGN_OPERATE, "provider=default", isProvider); ASSERT_TRUE(pkey != NULL && pkey2 != NULL); ASSERT_EQ(CRYPT_EAL_PkeySetPara(pkey, &para), CRYPT_SUCCESS); ASSERT_EQ(CRYPT_EAL_PkeySetPara(pkey2, &para), CRYPT_SUCCESS); #ifdef HITLS_CRYPTO_DRBG ASSERT_EQ(TestRandInit(), CRYPT_SUCCESS); #endif ASSERT_EQ(CRYPT_EAL_PkeyGen(pkey), CRYPT_SUCCESS); ASSERT_EQ(CRYPT_EAL_PkeyGetPub(pkey, &pubKey), CRYPT_SUCCESS); ASSERT_EQ(CRYPT_EAL_PkeySetPub(pkey2, &pubKey), CRYPT_SUCCESS); ASSERT_EQ(CRYPT_EAL_PkeyCtrl(pkey, CRYPT_CTRL_SET_RSA_EMSA_PKCSV15, &pkcsv15, sizeof(pkcsv15)), CRYPT_SUCCESS); ASSERT_EQ(CRYPT_EAL_PkeyCtrl(pkey2, CRYPT_CTRL_SET_RSA_EMSA_PKCSV15, &pkcsv15, sizeof(pkcsv15)), CRYPT_SUCCESS); ASSERT_EQ(CRYPT_EAL_PkeySign(pkey, CRYPT_MD_SHA256, data, dataLen, sign, &signLen), CRYPT_SUCCESS); ASSERT_EQ(CRYPT_EAL_PkeyVerify(pkey2, CRYPT_MD_SHA256, data, dataLen, sign, signLen), CRYPT_SUCCESS); EXIT: #ifdef HITLS_CRYPTO_DRBG TestRandDeInit(); #endif CRYPT_EAL_PkeyFreeCtx(pkey); CRYPT_EAL_PkeyFreeCtx(pkey2); } /* END_CASE */ /** * @test SDV_CRYPTO_RSA_GEN_SIGN_VERIFY_PKCSV15_FUNC_TC003 * @title RSA EAL sign/verify:Generate a key pair, set prvKey, PKCSV15, sha256 * @precon * @brief * 1. Create the contexts(pkey, pkey2) of the rsa algorithm, expected result 1 * 2. Set para for pkey and pkey2, expected result 2 * 3. Initialize the DRBG, expected result 3 * 4. Call the CRYPT_EAL_PkeyGen to generate a key pair, expected result 4 * 5. Get private key from pkey, expected result 5 * 6. Set private key for pkey2, expected result 6 * 7. Set padding type to pkcsv15 for pkey and pkey2, expected result 7 * 8. Call the CRYPT_EAL_PkeySign method and use pkey2 to sign a piece of data, expected result8 * 9. Call the CRYPT_EAL_PkeyVerify method and use pkey to verify the signed data, expected result 9 * @expect * 1. Success, and context is not NULL. * 2-9. CRYPT_SUCCESS */ /* BEGIN_CASE */ void SDV_CRYPTO_RSA_GEN_SIGN_VERIFY_PKCSV15_FUNC_TC003(int isProvider) { CRYPT_EAL_PkeyCtx *pkey = NULL; CRYPT_EAL_PkeyCtx *pkey2 = NULL; CRYPT_EAL_PkeyPara para = {0}; CRYPT_EAL_PkeyPrv prvKey = {0}; int32_t pkcsv15 = CRYPT_MD_SHA256; uint8_t prvD[600]; uint8_t prvN[600]; uint8_t prvP[600]; uint8_t prvQ[600]; uint8_t e[] = {1, 0, 1}; uint8_t sign[600]; uint32_t signLen = 600; // 600bytes > 1024bits uint8_t data[500] = {0}; uint32_t dataLen = sizeof(data); SetRsaPara(&para, e, 3, 1024); prvKey.id = CRYPT_PKEY_RSA; prvKey.key.rsaPrv.d = prvD; prvKey.key.rsaPrv.dLen = 600; // 600bytes > 1024bits prvKey.key.rsaPrv.n = prvN; prvKey.key.rsaPrv.nLen = 600; // 600bytes > 1024bits prvKey.key.rsaPrv.p = prvP; prvKey.key.rsaPrv.pLen = 600; // 600bytes > 1024bits prvKey.key.rsaPrv.q = prvQ; prvKey.key.rsaPrv.qLen = 600; // 600bytes > 1024bits prvKey.key.rsaPrv.dP = NULL; prvKey.key.rsaPrv.dPLen = 0; prvKey.key.rsaPrv.dQ = NULL; prvKey.key.rsaPrv.dQLen = 0; prvKey.key.rsaPrv.qInv = NULL; prvKey.key.rsaPrv.qInvLen = 0; TestMemInit(); pkey = TestPkeyNewCtx(NULL, CRYPT_PKEY_RSA, CRYPT_EAL_PKEY_KEYMGMT_OPERATE + CRYPT_EAL_PKEY_SIGN_OPERATE, "provider=default", isProvider); pkey2 = TestPkeyNewCtx(NULL, CRYPT_PKEY_RSA, CRYPT_EAL_PKEY_KEYMGMT_OPERATE + CRYPT_EAL_PKEY_SIGN_OPERATE, "provider=default", isProvider); ASSERT_TRUE(pkey != NULL && pkey2 != NULL); ASSERT_EQ(CRYPT_EAL_PkeySetPara(pkey, &para), CRYPT_SUCCESS); ASSERT_EQ(CRYPT_EAL_PkeySetPara(pkey2, &para), CRYPT_SUCCESS); #ifdef HITLS_CRYPTO_DRBG ASSERT_EQ(TestRandInit(), CRYPT_SUCCESS); #endif ASSERT_EQ(CRYPT_EAL_PkeyGen(pkey), CRYPT_SUCCESS); ASSERT_EQ(CRYPT_EAL_PkeyGetPrv(pkey, &prvKey), CRYPT_SUCCESS); ASSERT_EQ(CRYPT_EAL_PkeySetPrv(pkey2, &prvKey), CRYPT_SUCCESS); ASSERT_EQ(CRYPT_EAL_PkeyCtrl(pkey, CRYPT_CTRL_SET_RSA_EMSA_PKCSV15, &pkcsv15, sizeof(pkcsv15)), CRYPT_SUCCESS); ASSERT_EQ(CRYPT_EAL_PkeyCtrl(pkey2, CRYPT_CTRL_SET_RSA_EMSA_PKCSV15, &pkcsv15, sizeof(pkcsv15)), CRYPT_SUCCESS); ASSERT_EQ(CRYPT_EAL_PkeySign(pkey2, CRYPT_MD_SHA256, data, dataLen, sign, &signLen), CRYPT_SUCCESS); ASSERT_EQ(CRYPT_EAL_PkeyVerify(pkey, CRYPT_MD_SHA256, data, dataLen, sign, signLen), CRYPT_SUCCESS); EXIT: #ifdef HITLS_CRYPTO_DRBG TestRandDeInit(); #endif CRYPT_EAL_PkeyFreeCtx(pkey); CRYPT_EAL_PkeyFreeCtx(pkey2); } /* END_CASE */ /** * @test SDV_CRYPTO_RSA_VERIFY_PKCSV15_FUNC_TC001 * @title Rsa verify-PKCS15 * @precon * @brief * 1. Create the context(pkeyCtx) of the rsa algorithm, expected result 1 * 2. Set public key for pkeyCtx, expected result 2 * 3. Set padding type to pkcsv15 for pkeyCtx, expected result 3 * 4. Call the CRYPT_EAL_PkeyVerify method and use pkeyCtx to verify the signed data, expected result 4 * 5. Calculate the hash value of msg, expected result 5 * 6. Call the CRYPT_EAL_PkeyVerifyData method and use pkeyCtx to verify the signed data, expected result 6 * @expect * 1. Success, and context is not NULL. * 2-3. CRYPT_SUCCESS * 4. Reutrn CRYPT_SUCCESS when expect is 0, otherwise return CRYPT_RSA_NOR_VERIFY_FAIL. * 5. SUCCESS * 6. Reutrn CRYPT_SUCCESS when expect is 0, otherwise return CRYPT_RSA_NOR_VERIFY_FAIL. */ /* BEGIN_CASE */ void SDV_CRYPTO_RSA_VERIFY_PKCSV15_FUNC_TC001( int mdAlgId, Hex *n, Hex *e, Hex *msg, Hex *sign, int expect, int isProvider) { #if !defined(HITLS_CRYPTO_RSA_VERIFY) || !defined(HITLS_CRYPTO_RSA_EMSA_PKCSV15) SKIP_TEST(); #endif if (IsMdAlgDisabled(mdAlgId)) { SKIP_TEST(); } int ret; CRYPT_EAL_PkeyCtx *pkeyCtx = NULL; CRYPT_EAL_PkeyPub publicKey = {0}; int32_t pkcsv15 = mdAlgId; Hex mdOut = {0}; TestMemInit(); pkeyCtx = TestPkeyNewCtx(NULL, CRYPT_PKEY_RSA, CRYPT_EAL_PKEY_KEYMGMT_OPERATE + CRYPT_EAL_PKEY_SIGN_OPERATE, "provider=default", isProvider); ASSERT_TRUE(pkeyCtx != NULL); /* Set the public key.*/ SetRsaPubKey(&publicKey, n->x, n->len, e->x, e->len); ASSERT_EQ(CRYPT_EAL_PkeySetPub(pkeyCtx, &publicKey), CRYPT_SUCCESS); /* Set padding. */ ASSERT_EQ(CRYPT_EAL_PkeyCtrl(pkeyCtx, CRYPT_CTRL_SET_RSA_EMSA_PKCSV15, &pkcsv15, sizeof(pkcsv15)), CRYPT_SUCCESS); ret = CRYPT_EAL_PkeyVerify(pkeyCtx, mdAlgId, msg->x, msg->len, sign->x, sign->len); if (expect == SUCCESS) { ASSERT_EQ(ret, CRYPT_SUCCESS); } else { ASSERT_EQ(ret, CRYPT_RSA_NOR_VERIFY_FAIL); } ASSERT_TRUE(MD_Data(mdAlgId, msg, &mdOut) == SUCCESS); ret = CRYPT_EAL_PkeyVerifyData(pkeyCtx, mdOut.x, mdOut.len, sign->x, sign->len); if (expect == SUCCESS) { ASSERT_EQ(ret, CRYPT_SUCCESS); } else { ASSERT_EQ(ret, CRYPT_RSA_NOR_VERIFY_FAIL); } ret = CRYPT_EAL_PkeyVerifyData(NULL, mdOut.x, mdOut.len, sign->x, sign->len); ASSERT_TRUE_AND_LOG("CRYPT_EAL_PkeyVerifyData", ret != CRYPT_SUCCESS); EXIT: CRYPT_EAL_PkeyFreeCtx(pkeyCtx); free(mdOut.x); } /* END_CASE */ /** * @test SDV_CRYPTO_RSA_VERIFY_PSS_FUNC_TC001 * @title Rsa verify-PSS * @precon * @brief * 1. Create the context(pkeyCtx) of the rsa algorithm, expected result 1 * 2. Set public key for pkeyCtx, expected result 2 * 3. Set padding type to PSS for pkeyCtx, expected result 3 * 4. Call the CRYPT_EAL_PkeyVerify method and use pkeyCtx to verify the signed data, expected result 4 * 5. Calculate the hash value of msg, expected result 5 * 6. Call the CRYPT_EAL_PkeyVerifyData method and use pkeyCtx to verify the signed data, expected result 6 * @expect * 1. Success, and context is not NULL. * 2-3. CRYPT_SUCCESS * 4. Reutrn CRYPT_SUCCESS when expect is 0, otherwise return CRYPT_RSA_NOR_VERIFY_FAIL. * 5. SUCCESS * 6. Reutrn CRYPT_SUCCESS when expect is 0, otherwise return CRYPT_RSA_NOR_VERIFY_FAIL. */ /* BEGIN_CASE */ void SDV_CRYPTO_RSA_VERIFY_PSS_FUNC_TC001( int mdAlgId, Hex *n, Hex *e, Hex *salt, Hex *msg, Hex *sign, int expect, int isProvider) { #if !defined(HITLS_CRYPTO_RSA_VERIFY) || !defined(HITLS_CRYPTO_RSA_EMSA_PSS) SKIP_TEST(); #endif if (IsMdAlgDisabled(mdAlgId)) { SKIP_TEST(); } int ret; CRYPT_EAL_PkeyCtx *pkeyCtx = NULL; CRYPT_EAL_PkeyPub publicKey = {0}; 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, &salt->len, sizeof(salt->len), 0}, BSL_PARAM_END}; Hex mdOut = {0}; TestMemInit(); pkeyCtx = TestPkeyNewCtx(NULL, CRYPT_PKEY_RSA, CRYPT_EAL_PKEY_KEYMGMT_OPERATE + CRYPT_EAL_PKEY_SIGN_OPERATE, "provider=default", isProvider); ASSERT_TRUE(pkeyCtx != NULL); /* Set the public key.*/ SetRsaPubKey(&publicKey, n->x, n->len, e->x, e->len); ASSERT_EQ(CRYPT_EAL_PkeySetPub(pkeyCtx, &publicKey), CRYPT_SUCCESS); /* Set padding. */ ASSERT_EQ(CRYPT_EAL_PkeyCtrl(pkeyCtx, CRYPT_CTRL_SET_RSA_EMSA_PSS, pssParam, 0), CRYPT_SUCCESS); ret = CRYPT_EAL_PkeyVerify(pkeyCtx, mdAlgId, msg->x, msg->len, sign->x, sign->len); if (expect == SUCCESS) { ASSERT_EQ(ret, CRYPT_SUCCESS); } else { ASSERT_EQ(ret, CRYPT_RSA_NOR_VERIFY_FAIL); } ASSERT_TRUE(MD_Data(mdAlgId, msg, &mdOut) == SUCCESS); ret = CRYPT_EAL_PkeyVerifyData(pkeyCtx, mdOut.x, mdOut.len, sign->x, sign->len); if (expect == SUCCESS) { ASSERT_EQ(ret, CRYPT_SUCCESS); } else { ASSERT_EQ(ret, CRYPT_RSA_NOR_VERIFY_FAIL); } EXIT: CRYPT_EAL_PkeyFreeCtx(pkeyCtx); if (mdOut.x != NULL) { free(mdOut.x); } } /* END_CASE */ /** * @test SDV_CRYPTO_RSA_VERIFY_PSS_FUNC_TC002 * @title RSA verify PSS: saltLen is CRYPT_RSA_SALTLEN_TYPE_AUTOLEN * @precon * @brief * 1. Create the context(pkeyCtx) of the rsa algorithm, expected result 1 * 2. Set public key for pkeyCtx, expected result 2 * 3. Set padding type to PSS(saltLen is CRYPT_RSA_SALTLEN_TYPE_AUTOLEN) for pkeyCtx, expected result 3 * 4. Call the CRYPT_EAL_PkeyVerify method and use pkeyCtx to verify the signed data, expected result 4 * 5. Calculate the hash value of msg, expected result 5 * 6. Call the CRYPT_EAL_PkeyVerifyData method and use pkeyCtx to verify the signed data, expected result 6 * @expect * 1. Success, and context is not NULL. * 2-6. CRYPT_SUCCESS */ /* BEGIN_CASE */ void SDV_CRYPTO_RSA_VERIFY_PSS_FUNC_TC002(int mdAlgId, Hex *n, Hex *e, Hex *msg, Hex *sign, int isProvider) { if (IsMdAlgDisabled(mdAlgId)) { SKIP_TEST(); } CRYPT_EAL_PkeyCtx *pkeyCtx = NULL; CRYPT_EAL_PkeyPub publicKey = {0}; uint32_t signLen = CRYPT_RSA_SALTLEN_TYPE_AUTOLEN; 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, &signLen, sizeof(signLen), 0}, BSL_PARAM_END}; TestMemInit(); pkeyCtx = TestPkeyNewCtx(NULL, CRYPT_PKEY_RSA, CRYPT_EAL_PKEY_KEYMGMT_OPERATE + CRYPT_EAL_PKEY_SIGN_OPERATE, "provider=default", isProvider); ASSERT_TRUE(pkeyCtx != NULL); /* Set the public key.*/ SetRsaPubKey(&publicKey, n->x, n->len, e->x, e->len); ASSERT_EQ(CRYPT_EAL_PkeySetPub(pkeyCtx, &publicKey), CRYPT_SUCCESS); /* Set padding. */ ASSERT_EQ(CRYPT_EAL_PkeyCtrl(pkeyCtx, CRYPT_CTRL_SET_RSA_EMSA_PSS, pssParam, 0), CRYPT_SUCCESS); ASSERT_EQ(CRYPT_EAL_PkeyVerify(pkeyCtx, mdAlgId, msg->x, msg->len, sign->x, sign->len), CRYPT_SUCCESS); EXIT: CRYPT_EAL_PkeyFreeCtx(pkeyCtx); } /* END_CASE */ /** * @test SDV_CRYPTO_RSA_BLINDING_FUNC_TC001 * @title RSA EAL sign and verify with blinding. * @precon nan * @brief * 1. Create the context(pkeyCtx) of the rsa algorithm, expected result 1 * 2. Set para, expected result 2 * 3. Initialize the DRBG, expected result 3 * 4. Call the CRYPT_EAL_PkeyGen to generate a key pair, expected result 4 * 5. Set CRYPT_RSA_BLINDING flag, expected result 5 * 6. Set padding type, expected result 6 * 7. Sign with HiTLS, expected result 7 * 8. Verify with HiTLS, expected result 8 * @expect * 1. Success, and context is not NULL. * 2-8. CRYPT_SUCCESS. */ /* BEGIN_CASE */ void SDV_CRYPTO_RSA_BLINDING_FUNC_TC001(int keyLen, int hashId, int padMode, Hex *msg, int saltLen, int isProvider) { TestMemInit(); if (IsMdAlgDisabled(hashId)) { SKIP_TEST(); } uint8_t sign[MAX_CIPHERTEXT_LEN] = {0}; uint32_t dataLen = MAX_CIPHERTEXT_LEN; uint8_t e[] = {1, 0, 1}; CRYPT_EAL_PkeyCtx *pkey = NULL; CRYPT_EAL_PkeyCtx *newCtx = NULL; CRYPT_EAL_PkeyPara para = {0}; BSL_Param pssParam[4] = { {CRYPT_PARAM_RSA_MD_ID, BSL_PARAM_TYPE_INT32, &hashId, sizeof(hashId), 0}, {CRYPT_PARAM_RSA_MGF1_ID, BSL_PARAM_TYPE_INT32, &hashId, sizeof(hashId), 0}, {CRYPT_PARAM_RSA_SALTLEN, BSL_PARAM_TYPE_INT32, &saltLen, sizeof(saltLen), 0}, BSL_PARAM_END}; int paraSize; void *paraPtr; SetRsaPara(&para, e, 3, keyLen); int32_t pkcsv15 = hashId; if (padMode == CRYPT_CTRL_SET_RSA_EMSA_PSS) { paraSize = 0; paraPtr = pssParam; } else if (padMode == CRYPT_CTRL_SET_RSA_EMSA_PKCSV15) { paraSize = sizeof(pkcsv15); paraPtr = &pkcsv15; } pkey = TestPkeyNewCtx(NULL, CRYPT_PKEY_RSA, CRYPT_EAL_PKEY_KEYMGMT_OPERATE + CRYPT_EAL_PKEY_SIGN_OPERATE, "provider=default", isProvider); ASSERT_TRUE(pkey != NULL); ASSERT_EQ(CRYPT_EAL_PkeySetPara(pkey, &para), CRYPT_SUCCESS); #ifdef HITLS_CRYPTO_DRBG ASSERT_EQ(TestRandInit(), CRYPT_SUCCESS); #endif ASSERT_EQ(CRYPT_EAL_PkeyGen(pkey), CRYPT_SUCCESS); ASSERT_TRUE(CRYPT_EAL_PkeyCtrl(pkey, padMode, paraPtr, paraSize) == CRYPT_SUCCESS); uint32_t flag = CRYPT_RSA_BLINDING; ASSERT_TRUE(CRYPT_EAL_PkeyCtrl(pkey, CRYPT_CTRL_SET_RSA_FLAG, (void *)&flag, sizeof(uint32_t)) == CRYPT_SUCCESS); /* private key signature */ ASSERT_TRUE(CRYPT_EAL_PkeySign(pkey, hashId, msg->x, msg->len, sign, &dataLen) == CRYPT_SUCCESS); /* public key verify */ ASSERT_TRUE(CRYPT_EAL_PkeyVerify(pkey, hashId, msg->x, msg->len, sign, dataLen) == CRYPT_SUCCESS); newCtx = CRYPT_EAL_PkeyDupCtx(pkey); ASSERT_TRUE(newCtx != NULL); ASSERT_EQ(CRYPT_EAL_PkeySign(newCtx, hashId, msg->x, msg->len, sign, &dataLen), CRYPT_SUCCESS); EXIT: #ifdef HITLS_CRYPTO_DRBG TestRandDeInit(); #endif CRYPT_EAL_PkeyFreeCtx(pkey); CRYPT_EAL_PkeyFreeCtx(newCtx); } /* END_CASE */ /** * @test SDV_CRYPTO_RSA_BLINDING_FUNC_TC002 * @title RSA: Pkcsv15, Blinding, Signature. * @precon nan * @brief * 1. Create the context of the rsa algorithm, expected result 1 * 2. Set private key, EMSA_PKCSV15 and CRYPT_RSA_BLINDING flag, expected result 2 * 3. Initialize the drbg, expected result 3 * 4. Signature, expected result 4 * 5. Dup the context, and sign with new context, expected result 5 * @expect * 1. Success, and context is not NULL. * 2-4. CRYPT_SUCCESS. * 5. Success. */ /* BEGIN_CASE */ void SDV_CRYPTO_RSA_BLINDING_FUNC_TC002(int mdId, Hex *p, Hex *q, Hex *n, Hex *d, Hex *msg, int isProvider) { CRYPT_EAL_PkeyCtx *ctx = NULL; CRYPT_EAL_PkeyCtx *newCtx = NULL; CRYPT_EAL_PkeyPrv prv = {0}; uint8_t *signdata = NULL; uint32_t signLen; uint32_t flag = CRYPT_RSA_BLINDING; int32_t pkcsv15 = mdId; SetRsaPrvKey(&prv, n->x, n->len, d->x, d->len); prv.key.rsaPrv.p = p->x; prv.key.rsaPrv.pLen = p->len; prv.key.rsaPrv.q = q->x; prv.key.rsaPrv.qLen = q->len; TestMemInit(); #ifdef HITLS_CRYPTO_DRBG ASSERT_EQ(TestRandInit(), CRYPT_SUCCESS); // Random numbers need to be generated during blinding. #endif ctx = TestPkeyNewCtx(NULL, CRYPT_PKEY_RSA, CRYPT_EAL_PKEY_KEYMGMT_OPERATE + CRYPT_EAL_PKEY_SIGN_OPERATE, "provider=default", isProvider); ASSERT_TRUE(ctx != NULL); ASSERT_EQ(CRYPT_EAL_PkeySetPrv(ctx, &prv), CRYPT_SUCCESS); ASSERT_EQ(CRYPT_EAL_PkeyCtrl(ctx, CRYPT_CTRL_SET_RSA_EMSA_PKCSV15, &pkcsv15, sizeof(pkcsv15)), CRYPT_SUCCESS); ASSERT_TRUE(CRYPT_EAL_PkeyCtrl(ctx, CRYPT_CTRL_SET_RSA_FLAG, (void *)&flag, sizeof(uint32_t)) == CRYPT_SUCCESS); /* Malloc signature buffer */ signLen = CRYPT_EAL_PkeyGetSignLen(ctx); signdata = (uint8_t *)calloc(1u, signLen); ASSERT_TRUE(signdata != NULL); ASSERT_EQ(CRYPT_EAL_PkeySign(ctx, mdId, msg->x, msg->len, signdata, &signLen), CRYPT_SUCCESS); newCtx = CRYPT_EAL_PkeyDupCtx(ctx); ASSERT_TRUE(newCtx != NULL); ASSERT_EQ(CRYPT_EAL_PkeySign(newCtx, mdId, msg->x, msg->len, signdata, &signLen), CRYPT_SUCCESS); EXIT: CRYPT_EAL_PkeyFreeCtx(ctx); CRYPT_EAL_PkeyFreeCtx(newCtx); free(signdata); #ifdef HITLS_CRYPTO_DRBG TestRandDeInit(); #endif } /* END_CASE */ /** * @test SDV_CRYPTO_RSA_KEY_PAIR_CHECK_FUNC_TC001 * @title RSA: key pair check. * @precon Registering memory-related functions. * @brief * 1. Create two contexts(pubCtx, prvCtx) of the rsa algorithm, expected result 1 * 2. Set public key for pubCtx, expected result 2 * 3. Set private key for prvCtx, expected result 3 * 4. Check whether the public key matches the private key, expected result 4 * @expect * 1. Success, and contexts are not NULL. * 2. CRYPT_SUCCESS * 3. CRYPT_SUCCESS * 4. Return CRYPT_SUCCESS when expect is 1, CRYPT_RSA_NOR_VERIFY_FAIL otherwise. */ /* BEGIN_CASE */ void SDV_CRYPTO_RSA_KEY_PAIR_CHECK_FUNC_TC001(Hex *n, Hex *e, Hex *d, int expect, int isProvider) { #if !defined(HITLS_CRYPTO_RSA_CHECK) (void)n; (void)e; (void)d; (void)expect; (void)isProvider; SKIP_TEST(); #else #ifdef HITLS_CRYPTO_DRBG ASSERT_EQ(TestRandInit(), CRYPT_SUCCESS); #endif CRYPT_EAL_PkeyCtx *pubCtx = NULL; CRYPT_EAL_PkeyCtx *prvCtx = NULL; CRYPT_EAL_PkeyPub pubKey = {0}; CRYPT_EAL_PkeyPrv prvKey = {0}; int expectRet = expect == 1 ? CRYPT_SUCCESS : CRYPT_RSA_KEYPAIRWISE_CONSISTENCY_FAILURE; SetRsaPubKey(&pubKey, n->x, n->len, e->x, e->len); SetRsaPrvKey(&prvKey, n->x, n->len, d->x, d->len); TestMemInit(); pubCtx = TestPkeyNewCtx(NULL, CRYPT_PKEY_RSA, CRYPT_EAL_PKEY_KEYMGMT_OPERATE + CRYPT_EAL_PKEY_SIGN_OPERATE, "provider=default", isProvider); prvCtx = TestPkeyNewCtx(NULL, CRYPT_PKEY_RSA, CRYPT_EAL_PKEY_KEYMGMT_OPERATE + CRYPT_EAL_PKEY_SIGN_OPERATE, "provider=default", isProvider); ASSERT_TRUE(pubCtx != NULL && prvCtx != NULL); ASSERT_EQ(CRYPT_EAL_PkeySetPub(pubCtx, &pubKey), CRYPT_SUCCESS); ASSERT_EQ(CRYPT_EAL_PkeySetPrv(prvCtx, &prvKey), CRYPT_SUCCESS); ASSERT_EQ(CRYPT_EAL_PkeyPairCheck(pubCtx, prvCtx), expectRet); EXIT: CRYPT_EAL_PkeyFreeCtx(pubCtx); CRYPT_EAL_PkeyFreeCtx(prvCtx); #ifdef HITLS_CRYPTO_DRBG TestRandDeInit(); #endif #endif // HITLS_CRYPTO_RSA_CHECK } /* END_CASE */ /** * @test SDV_CRYPTO_RSA_RSABSSA_BLINDING_FUNC_TC001 * @title RSA: Blind signature basic functionality test * @precon Registering memory-related functions * @brief * 1. Create RSA context and generate key pair * 2. Set PSS parameters and blind signature flag * 3. Perform blind operation on message * 4. Sign the blinded message with private key * 5. Unblind the signature * 6. Verify the unblinded signature with public key * 7. Dup the context, and sign-verify with new context * @expect * All operations return CRYPT_SUCCESS */ /* BEGIN_CASE */ void SDV_CRYPTO_RSA_RSABSSA_BLINDING_FUNC_TC001(int mdId, Hex *n, Hex *e, Hex *d, Hex *msg, int saltLen, int isProvider) { #ifndef HITLS_CRYPTO_RSA_BSSA SKIP_TEST(); #endif if (IsMdAlgDisabled(mdId)) { SKIP_TEST(); } TestMemInit(); uint8_t sign[MAX_CIPHERTEXT_LEN] = {0}; uint32_t signLen = MAX_CIPHERTEXT_LEN; CRYPT_EAL_PkeyCtx *newCtx = NULL; CRYPT_EAL_PkeyCtx *pkey = NULL; #ifdef HITLS_CRYPTO_RSA_SIGN uint8_t blindMsg[MAX_CIPHERTEXT_LEN] = {0}; uint32_t blindMsgLen = MAX_CIPHERTEXT_LEN; #endif #ifdef HITLS_CRYPTO_RSA_VERIFY uint8_t unBlindSig[MAX_CIPHERTEXT_LEN] = {0}; uint32_t unBlindSigLen = MAX_CIPHERTEXT_LEN; #endif CRYPT_EAL_PkeyPub pubKey = {0}; CRYPT_EAL_PkeyPrv prvKey = {0}; SetRsaPubKey(&pubKey, n->x, n->len, e->x, e->len); SetRsaPrvKey(&prvKey, n->x, n->len, d->x, d->len); BSL_Param pssParam[4] = { {CRYPT_PARAM_RSA_MD_ID, BSL_PARAM_TYPE_INT32, &mdId, sizeof(mdId), 0}, {CRYPT_PARAM_RSA_MGF1_ID, BSL_PARAM_TYPE_INT32, &mdId, sizeof(mdId), 0}, {CRYPT_PARAM_RSA_SALTLEN, BSL_PARAM_TYPE_INT32, &saltLen, sizeof(saltLen), 0}, BSL_PARAM_END}; pkey = TestPkeyNewCtx(NULL, CRYPT_PKEY_RSA, CRYPT_EAL_PKEY_KEYMGMT_OPERATE + CRYPT_EAL_PKEY_SIGN_OPERATE, "provider=default", isProvider); ASSERT_TRUE(pkey != NULL); #ifdef HITLS_CRYPTO_DRBG ASSERT_EQ(TestRandInit(), CRYPT_SUCCESS); #endif ASSERT_EQ(CRYPT_EAL_PkeySetPub(pkey, &pubKey), CRYPT_SUCCESS); ASSERT_EQ(CRYPT_EAL_PkeySetPrv(pkey, &prvKey), CRYPT_SUCCESS); ASSERT_EQ(CRYPT_EAL_PkeyCtrl(pkey, CRYPT_CTRL_SET_RSA_EMSA_PSS, &pssParam, 0), CRYPT_SUCCESS); uint32_t flag = CRYPT_RSA_BSSA; ASSERT_TRUE(CRYPT_EAL_PkeyCtrl(pkey, CRYPT_CTRL_SET_RSA_FLAG, (void *)&flag, sizeof(uint32_t)) == CRYPT_SUCCESS); #ifdef HITLS_CRYPTO_RSA_SIGN ASSERT_TRUE(CRYPT_EAL_PkeyBlind(pkey, mdId, msg->x, msg->len, blindMsg, &blindMsgLen) == CRYPT_SUCCESS); /* private key signature */ ASSERT_TRUE(CRYPT_EAL_PkeySignData(pkey, blindMsg, blindMsgLen, sign, &signLen) == CRYPT_SUCCESS); #endif #ifdef HITLS_CRYPTO_RSA_VERIFY ASSERT_TRUE(CRYPT_EAL_PkeyUnBlind(pkey, sign, signLen, unBlindSig, &unBlindSigLen) == CRYPT_SUCCESS); /* public key verify */ ASSERT_TRUE(CRYPT_EAL_PkeyVerify(pkey, mdId, msg->x, msg->len, unBlindSig, unBlindSigLen) == CRYPT_SUCCESS); #endif newCtx = CRYPT_EAL_PkeyDupCtx(pkey); // dup ctx ASSERT_TRUE(newCtx != NULL); #ifdef HITLS_CRYPTO_RSA_SIGN ASSERT_TRUE(CRYPT_EAL_PkeySignData(newCtx, blindMsg, blindMsgLen, sign, &signLen) == CRYPT_SUCCESS); #endif #ifdef HITLS_CRYPTO_VERIFY ASSERT_TRUE(CRYPT_EAL_PkeyVerify(newCtx, mdId, msg->x, msg->len, unBlindSig, unBlindSigLen) == CRYPT_SUCCESS); #endif EXIT: #ifdef HITLS_CRYPTO_DRBG TestRandDeInit(); #endif CRYPT_EAL_PkeyFreeCtx(pkey); CRYPT_EAL_PkeyFreeCtx(newCtx); } /* END_CASE */ /** * @test SDV_CRYPTO_RSA_RSABSSA_BLINDING_FUNC_TC002 * @title RSA: Blind signature with known test vectors * @precon Registering memory-related functions * @brief * 1. Initialize RSA context with known key pairs * 2. Set PSS parameters and blind signature parameters * 3. Verify blind factor computation * 4. Perform blind signature operation with test vectors * 5. Compare results with expected values * @expect * 1. All operations return CRYPT_SUCCESS * 2. All computed values match the test vectors */ /* BEGIN_CASE */ void SDV_CRYPTO_RSA_RSABSSA_BLINDING_FUNC_TC002(Hex *e, Hex *nBuff, Hex *d, Hex *prepared_msg, Hex *salt, Hex *invBuf, Hex *blindMsgBuf, Hex *blindSigBuf, Hex *sigBuf, int isStub) { #ifndef HITLS_CRYPTO_RSA_BSSA SKIP_TEST(); #endif (void)sigBuf; TestMemInit(); uint32_t ret; uint8_t sign[MAX_CIPHERTEXT_LEN] = {0}; uint32_t signLen = MAX_CIPHERTEXT_LEN; uint8_t blindMsg[MAX_CIPHERTEXT_LEN] = {0}; uint32_t blindMsgLen = MAX_CIPHERTEXT_LEN; #ifdef HITLS_CRYPTO_VERIFY uint8_t unBlindSig[MAX_CIPHERTEXT_LEN] = {0}; uint32_t unBlindSigLen = MAX_CIPHERTEXT_LEN; #endif uint8_t rBuf[MAX_CIPHERTEXT_LEN] = {0}; uint32_t rBufLen = MAX_CIPHERTEXT_LEN; BN_BigNum *invN = NULL; BN_BigNum *inv = BN_Create(0); BN_BigNum *n = BN_Create(0); BN_BigNum *r = BN_Create(0); BN_Optimizer *opt = BN_OptimizerCreate(); ASSERT_NE(inv, NULL); ASSERT_NE(n, NULL); ASSERT_NE(r, NULL); ASSERT_NE(opt, NULL); ret = BN_Bin2Bn(n, nBuff->x, nBuff->len); ASSERT_EQ(ret, CRYPT_SUCCESS); ret = BN_Bin2Bn(inv, invBuf->x, invBuf->len); ASSERT_EQ(ret, CRYPT_SUCCESS); ret = BN_ModInv(r, inv, n, opt); ASSERT_EQ(ret, CRYPT_SUCCESS); ret = BN_Bn2Bin(r, rBuf, &rBufLen); ASSERT_EQ(ret, CRYPT_SUCCESS); CRYPT_EAL_PkeyCtx *pkey = NULL; CRYPT_MD_AlgId mdId = CRYPT_MD_SHA384; uint32_t saltLen = salt->len; BSL_Param pssParam[4] = { {CRYPT_PARAM_RSA_MD_ID, BSL_PARAM_TYPE_INT32, &mdId, sizeof(mdId), 0}, {CRYPT_PARAM_RSA_MGF1_ID, BSL_PARAM_TYPE_INT32, &mdId, sizeof(mdId), 0}, {CRYPT_PARAM_RSA_SALTLEN, BSL_PARAM_TYPE_INT32, &saltLen, sizeof(saltLen), 0}, BSL_PARAM_END}; pkey = CRYPT_EAL_PkeyNewCtx(CRYPT_PKEY_RSA); ASSERT_TRUE(pkey != NULL); CRYPT_EAL_PkeyPrv priKey = {0}; CRYPT_EAL_PkeyPub pubKey = {0}; SetRsaPubKey(&pubKey, nBuff->x, nBuff->len, e->x, e->len); SetRsaPrvKey(&priKey, nBuff->x, nBuff->len, d->x, d->len); ASSERT_EQ(CRYPT_EAL_PkeySetPub(pkey, &pubKey), CRYPT_SUCCESS); ASSERT_EQ(CRYPT_EAL_PkeySetPrv(pkey, &priKey), CRYPT_SUCCESS); #ifdef HITLS_CRYPTO_DRBG if (isStub) { CRYPT_RandRegist(STUB_ReplaceRandom); CRYPT_RandRegistEx(STUB_ReplaceRandomEx); } else { ASSERT_EQ(TestRandInit(), CRYPT_SUCCESS); } #endif // set pss param. ASSERT_TRUE(CRYPT_EAL_PkeyCtrl(pkey, CRYPT_CTRL_SET_RSA_EMSA_PSS, &pssParam, 0) == CRYPT_SUCCESS); if (salt->len != 0) { ASSERT_TRUE(CRYPT_EAL_PkeyCtrl(pkey, CRYPT_CTRL_SET_RSA_SALT, salt->x, salt->len) == CRYPT_SUCCESS); } if (isStub) { memcpy_s(g_RandBuf, TMP_BUFF_LEN, rBuf, rBufLen); } else { ASSERT_TRUE(CRYPT_EAL_PkeyCtrl(pkey, CRYPT_CTRL_SET_RSA_BSSA_FACTOR_R, rBuf, rBufLen) == CRYPT_SUCCESS); } uint32_t flag = CRYPT_RSA_BSSA; ASSERT_TRUE(CRYPT_EAL_PkeyCtrl(pkey, CRYPT_CTRL_SET_RSA_FLAG, (void *)&flag, sizeof(uint32_t)) == CRYPT_SUCCESS); ASSERT_TRUE(CRYPT_EAL_PkeyBlind(pkey, CRYPT_MD_SHA384, prepared_msg->x, prepared_msg->len, blindMsg, &blindMsgLen) == CRYPT_SUCCESS); ret = memcmp(blindMsgBuf->x, blindMsg, blindMsgBuf->len); ASSERT_EQ(ret, 0); ASSERT_EQ(blindMsgBuf->len, blindMsgLen); ASSERT_TRUE(CRYPT_EAL_PkeySignData(pkey, blindMsg, blindMsgLen, sign, &signLen) == CRYPT_SUCCESS); ret = memcmp(blindSigBuf->x, sign, blindSigBuf->len); ASSERT_EQ(ret, 0); ASSERT_EQ(blindSigBuf->len, signLen); #ifdef HITLS_CRYPTO_VERIFY ASSERT_TRUE(CRYPT_EAL_PkeyUnBlind(pkey, sign, signLen, unBlindSig, &unBlindSigLen) == CRYPT_SUCCESS); ret = memcmp(sigBuf->x, unBlindSig, sigBuf->len); ASSERT_EQ(ret, 0); ASSERT_EQ(sigBuf->len, unBlindSigLen); ASSERT_TRUE(CRYPT_EAL_PkeyVerify(pkey, CRYPT_MD_SHA384, prepared_msg->x, prepared_msg->len, unBlindSig, unBlindSigLen) == CRYPT_SUCCESS); #endif EXIT: #ifdef HITLS_CRYPTO_DRBG TestRandDeInit(); #endif CRYPT_EAL_PkeyFreeCtx(pkey); BN_OptimizerDestroy(opt); BN_Destroy(inv); BN_Destroy(n); BN_Destroy(r); BN_Destroy(invN); } /* END_CASE */ /** * @test SDV_CRYPTO_RSA_RSABSSA_BLINDING_INVALID_PARAM_TC001 * @title RSA: Blind signature invalid parameter test * @precon Registering memory-related functions * @brief * 1. Test null pointer handling: * - Test PkeyBlind/PkeyUnBlind with NULL context * - Test PkeyBlind/PkeyUnBlind with NULL input/output buffers * - Test PkeyBlind/PkeyUnBlind with NULL length pointers * 2. Test unsupported algorithm: * - Test blind operations with ECDH key context * 3. Test RSA context without key information: * - Test blind operations before setting key parameters * 4. Test buffer size validation: * - Test with insufficient output buffer size * 5. Test padding configuration: * - Test blind operations without setting padding * - Test with mismatched hash algorithm (SHA256 vs SHA384) * 6. Test blind parameter controls: * - Test NULL and invalid parameters for BSSA controls * - Test getting blind factor inverse without setting output buffer. * @expect * - CRYPT_NULL_INPUT for null pointer parameters * - CRYPT_EAL_ALG_NOT_SUPPORT for unsupported algorithms * - CRYPT_RSA_NO_KEY_INFO when key info missing * - CRYPT_RSA_BUFF_LEN_NOT_ENOUGH for small buffers * - CRYPT_RSA_PADDING_NOT_SUPPORTED for invalid padding * - CRYPT_RSA_ERR_MD_ALGID for mismatched hash * - CRYPT_INVALID_ARG for invalid blind parameters * - CRYPT_RSA_ERR_NO_BLIND_INFO when blind factor not set */ /* BEGIN_CASE */ void SDV_CRYPTO_RSA_RSABSSA_BLINDING_INVALID_PARAM_TC001(void) { TestMemInit(); uint8_t msg[] = "test message"; uint32_t msgLen = strlen((char *)msg); uint8_t blindMsg[MAX_CIPHERTEXT_LEN] = {0}; uint32_t blindMsgLen = MAX_CIPHERTEXT_LEN; CRYPT_EAL_PkeyCtx *pkey = NULL; uint8_t unBlindSig[MAX_CIPHERTEXT_LEN] = {0}; uint32_t unBlindSigLen = MAX_CIPHERTEXT_LEN; uint8_t sign[MAX_CIPHERTEXT_LEN] = {0}; uint32_t signLen = MAX_CIPHERTEXT_LEN; uint32_t smallLen = 16; // Test null pointer parameters ASSERT_TRUE(CRYPT_EAL_PkeyBlind(NULL, CRYPT_MD_SHA384, msg, msgLen, blindMsg, &blindMsgLen) == CRYPT_NULL_INPUT); ASSERT_TRUE(CRYPT_EAL_PkeyUnBlind(NULL, sign, signLen, unBlindSig, &unBlindSigLen) == CRYPT_NULL_INPUT); // gen key pkey = CRYPT_EAL_PkeyNewCtx(CRYPT_PKEY_ECDH); ASSERT_TRUE(pkey != NULL); ASSERT_TRUE(CRYPT_EAL_PkeyBlind(pkey, CRYPT_MD_SHA384, msg, msgLen, blindMsg, NULL) == CRYPT_EAL_ALG_NOT_SUPPORT); ASSERT_TRUE(CRYPT_EAL_PkeyUnBlind(pkey, sign, signLen, unBlindSig, &unBlindSigLen) == CRYPT_EAL_ALG_NOT_SUPPORT); CRYPT_EAL_PkeyFreeCtx(pkey); pkey = CRYPT_EAL_PkeyNewCtx(CRYPT_PKEY_RSA); ASSERT_TRUE(pkey != NULL); CRYPT_EAL_PkeyPara para = {0}; uint8_t e[] = {1, 0, 1}; SetRsaPara(&para, e, 3, 1024); // set key param ASSERT_EQ(CRYPT_EAL_PkeySetPara(pkey, &para), CRYPT_SUCCESS); #ifdef HITLS_CRYPTO_DRBG ASSERT_EQ(TestRandInit(), CRYPT_SUCCESS); #endif // Test input null ASSERT_TRUE(CRYPT_EAL_PkeyBlind(pkey, CRYPT_MD_SHA384, NULL, msgLen, blindMsg, &blindMsgLen) == CRYPT_NULL_INPUT); ASSERT_TRUE(CRYPT_EAL_PkeyBlind(pkey, CRYPT_MD_SHA384, msg, msgLen, NULL, &blindMsgLen) == CRYPT_NULL_INPUT); ASSERT_TRUE(CRYPT_EAL_PkeyBlind(pkey, CRYPT_MD_SHA384, msg, msgLen, blindMsg, NULL) == CRYPT_NULL_INPUT); ASSERT_TRUE(CRYPT_EAL_PkeyUnBlind(pkey, NULL, signLen, unBlindSig, &unBlindSigLen) == CRYPT_NULL_INPUT); ASSERT_TRUE(CRYPT_EAL_PkeyUnBlind(pkey, sign, signLen, NULL, &unBlindSigLen) == CRYPT_NULL_INPUT); ASSERT_TRUE(CRYPT_EAL_PkeyUnBlind(pkey, sign, signLen, unBlindSig, NULL) == CRYPT_NULL_INPUT); // Test no key info. ASSERT_TRUE(CRYPT_EAL_PkeyBlind(pkey, CRYPT_MD_SHA384, msg, msgLen, blindMsg, &smallLen) == CRYPT_RSA_ERR_NO_PUBKEY_INFO); ASSERT_TRUE(CRYPT_EAL_PkeyUnBlind(pkey, sign, signLen, unBlindSig, &unBlindSigLen) == CRYPT_RSA_ERR_NO_PUBKEY_INFO); ASSERT_EQ(CRYPT_EAL_PkeyGen(pkey), CRYPT_SUCCESS); // Output buff is not enough. ASSERT_TRUE(CRYPT_EAL_PkeyBlind(pkey, CRYPT_MD_SHA384, msg, msgLen, blindMsg, &smallLen) == CRYPT_RSA_BUFF_LEN_NOT_ENOUGH); ASSERT_TRUE(CRYPT_EAL_PkeyUnBlind(pkey, msg, msgLen, unBlindSig, &smallLen) == CRYPT_RSA_BUFF_LEN_NOT_ENOUGH); // pad type is wrong. ASSERT_TRUE(CRYPT_EAL_PkeyBlind(pkey, CRYPT_MD_SHA384, msg, msgLen, blindMsg, &blindMsgLen) == CRYPT_RSA_PADDING_NOT_SUPPORTED); ASSERT_TRUE(CRYPT_EAL_PkeyUnBlind(pkey, msg, msgLen, unBlindSig, &unBlindSigLen) == CRYPT_RSA_PADDING_NOT_SUPPORTED); CRYPT_MD_AlgId mdId = CRYPT_MD_SHA384; uint32_t saltLen = 0; BSL_Param pssParam[4] = { {CRYPT_PARAM_RSA_MD_ID, BSL_PARAM_TYPE_INT32, &mdId, sizeof(mdId), 0}, {CRYPT_PARAM_RSA_MGF1_ID, BSL_PARAM_TYPE_INT32, &mdId, sizeof(mdId), 0}, {CRYPT_PARAM_RSA_SALTLEN, BSL_PARAM_TYPE_INT32, &saltLen, sizeof(saltLen), 0}, BSL_PARAM_END}; ASSERT_TRUE(CRYPT_EAL_PkeyCtrl(pkey, CRYPT_CTRL_SET_RSA_EMSA_PSS, &pssParam, 0) == CRYPT_SUCCESS); ASSERT_TRUE(CRYPT_EAL_PkeyBlind(pkey, CRYPT_MD_SHA256, msg, msgLen, blindMsg, &unBlindSigLen) == CRYPT_RSA_ERR_MD_ALGID); uint8_t rBufTest[128] = {1}; // due to key bits = 1024 uint8_t rBufTest1[128] = {0}; // due to key bits = 1024 uint32_t rBufTestLen = 128; ASSERT_TRUE(CRYPT_EAL_PkeyCtrl(pkey, CRYPT_CTRL_SET_RSA_BSSA_FACTOR_R, NULL, 0) == CRYPT_NULL_INPUT); ASSERT_TRUE(CRYPT_EAL_PkeyCtrl(pkey, CRYPT_CTRL_SET_RSA_BSSA_FACTOR_R, rBufTest, rBufTestLen) == CRYPT_SUCCESS); // repeated set ASSERT_TRUE(CRYPT_EAL_PkeyCtrl(pkey, CRYPT_CTRL_SET_RSA_BSSA_FACTOR_R, rBufTest, rBufTestLen) == CRYPT_SUCCESS); ASSERT_TRUE(CRYPT_EAL_PkeyCtrl(pkey, CRYPT_CTRL_SET_RSA_BSSA_FACTOR_R, rBufTest1, rBufTestLen) == CRYPT_RSA_ERR_BSSA_PARAM); EXIT: CRYPT_EAL_PkeyFreeCtx(pkey); } /* END_CASE */
2301_79861745/bench_create
testcode/sdv/testcase/crypto/rsa/test_suite_sdv_eal_rsa_sign_verify.c
C
unknown
58,667
/* * This file is part of the openHiTLS project. * * openHiTLS is licensed under the Mulan PSL v2. * You can use this software according to the terms and conditions of the Mulan PSL v2. * You may obtain a copy of Mulan PSL v2 at: * * http://license.coscl.org.cn/MulanPSL2 * * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. * See the Mulan PSL v2 for more details. */ /* BEGIN_HEADER */ #include "securec.h" #include "crypt_eal_kdf.h" #include "crypt_errno.h" #include "bsl_sal.h" #include "crypt_pbkdf2.h" #include "bsl_params.h" #include "crypt_params_key.h" /* END_HEADER */ #define DATA_LEN (16) /** * @test SDV_CRYPT_EAL_KDF_SCRYPT_API_TC001 * @title Scrypt interface test. * @precon nan * @brief * 1.Normal parameter test,the key and salt can be empty, expected result 1. * 2.Abnormal parameter test,about the restriction, see the function declaration, expected result 2. * @expect * 1.Return CRYPT_SUCCESS. * 2.The results are as expected. */ /* BEGIN_CASE */ void SDV_CRYPT_EAL_KDF_SCRYPT_API_TC001(void) { TestMemInit(); uint32_t keyLen = DATA_LEN; uint8_t key[DATA_LEN]; uint32_t saltLen = DATA_LEN; uint8_t salt[DATA_LEN]; uint32_t N = DATA_LEN; uint32_t r = DATA_LEN; uint32_t p = DATA_LEN; uint32_t outLen = DATA_LEN; uint8_t out[DATA_LEN]; CRYPT_EAL_KdfCTX *ctx = CRYPT_EAL_KdfNewCtx(CRYPT_KDF_SCRYPT); ASSERT_TRUE(ctx != NULL); BSL_Param params[6] = {{0}, {0}, {0}, {0}, {0}, BSL_PARAM_END}; ASSERT_EQ(BSL_PARAM_InitValue(&params[0], CRYPT_PARAM_KDF_PASSWORD, BSL_PARAM_TYPE_OCTETS, key, keyLen), CRYPT_SUCCESS); ASSERT_EQ(BSL_PARAM_InitValue(&params[1], CRYPT_PARAM_KDF_SALT, BSL_PARAM_TYPE_OCTETS, salt, saltLen), CRYPT_SUCCESS); ASSERT_EQ(BSL_PARAM_InitValue(&params[2], CRYPT_PARAM_KDF_N, BSL_PARAM_TYPE_UINT32, &N, sizeof(N)), CRYPT_SUCCESS); ASSERT_EQ(BSL_PARAM_InitValue(&params[3], CRYPT_PARAM_KDF_R, BSL_PARAM_TYPE_UINT32, &r, sizeof(r)), CRYPT_SUCCESS); ASSERT_EQ(BSL_PARAM_InitValue(&params[4], CRYPT_PARAM_KDF_P, BSL_PARAM_TYPE_UINT32, &p, sizeof(p)), CRYPT_SUCCESS); ASSERT_EQ(CRYPT_EAL_KdfSetParam(ctx, params), CRYPT_SUCCESS); ASSERT_EQ(CRYPT_EAL_KdfDerive(ctx, out, outLen), CRYPT_SUCCESS); ASSERT_EQ(BSL_PARAM_InitValue(&params[0], CRYPT_PARAM_KDF_PASSWORD, BSL_PARAM_TYPE_OCTETS, NULL, 0), CRYPT_SUCCESS); ASSERT_EQ(CRYPT_EAL_KdfSetParam(ctx, params), CRYPT_SUCCESS); ASSERT_EQ(CRYPT_EAL_KdfDerive(ctx, out, outLen), CRYPT_SUCCESS); ASSERT_EQ(BSL_PARAM_InitValue(&params[1], CRYPT_PARAM_KDF_SALT, BSL_PARAM_TYPE_OCTETS, NULL, 0), CRYPT_SUCCESS); ASSERT_EQ(CRYPT_EAL_KdfSetParam(ctx, params), CRYPT_SUCCESS); ASSERT_EQ(CRYPT_EAL_KdfDerive(ctx, out, outLen), CRYPT_SUCCESS); N = 0; ASSERT_EQ(BSL_PARAM_InitValue(&params[2], CRYPT_PARAM_KDF_N, BSL_PARAM_TYPE_UINT32, &N, sizeof(N)), CRYPT_SUCCESS); ASSERT_EQ(CRYPT_EAL_KdfSetParam(ctx, params), CRYPT_SCRYPT_PARAM_ERROR); N = 3; ASSERT_EQ(BSL_PARAM_InitValue(&params[2], CRYPT_PARAM_KDF_N, BSL_PARAM_TYPE_UINT32, &N, sizeof(N)), CRYPT_SUCCESS); ASSERT_EQ(CRYPT_EAL_KdfSetParam(ctx, params), CRYPT_SCRYPT_PARAM_ERROR); N = 6; ASSERT_EQ(BSL_PARAM_InitValue(&params[2], CRYPT_PARAM_KDF_N, BSL_PARAM_TYPE_UINT32, &N, sizeof(N)), CRYPT_SUCCESS); ASSERT_EQ(CRYPT_EAL_KdfSetParam(ctx, params), CRYPT_SCRYPT_PARAM_ERROR); N = 65538; ASSERT_EQ(BSL_PARAM_InitValue(&params[2], CRYPT_PARAM_KDF_N, BSL_PARAM_TYPE_UINT32, &N, sizeof(N)), CRYPT_SUCCESS); ASSERT_EQ(CRYPT_EAL_KdfSetParam(ctx, params), CRYPT_SCRYPT_PARAM_ERROR); N = 4; ASSERT_EQ(BSL_PARAM_InitValue(&params[2], CRYPT_PARAM_KDF_N, BSL_PARAM_TYPE_UINT32, &N, sizeof(N)), CRYPT_SUCCESS); ASSERT_EQ(CRYPT_EAL_KdfSetParam(ctx, params), CRYPT_SUCCESS); ASSERT_EQ(CRYPT_EAL_KdfDerive(ctx, out, outLen), CRYPT_SUCCESS); N = DATA_LEN; ASSERT_EQ(BSL_PARAM_InitValue(&params[2], CRYPT_PARAM_KDF_N, BSL_PARAM_TYPE_UINT32, &N, sizeof(N)), CRYPT_SUCCESS); ASSERT_EQ(CRYPT_EAL_KdfSetParam(ctx, params), CRYPT_SUCCESS); r = 0; ASSERT_EQ(BSL_PARAM_InitValue(&params[3], CRYPT_PARAM_KDF_R, BSL_PARAM_TYPE_UINT32, &r, sizeof(r)), CRYPT_SUCCESS); ASSERT_EQ(CRYPT_EAL_KdfSetParam(ctx, params), CRYPT_SCRYPT_PARAM_ERROR); r = DATA_LEN; ASSERT_EQ(BSL_PARAM_InitValue(&params[3], CRYPT_PARAM_KDF_R, BSL_PARAM_TYPE_UINT32, &r, sizeof(r)), CRYPT_SUCCESS); ASSERT_EQ(CRYPT_EAL_KdfSetParam(ctx, params), CRYPT_SUCCESS); ASSERT_EQ(CRYPT_EAL_KdfDerive(ctx, out, outLen), CRYPT_SUCCESS); p = 0; ASSERT_EQ(BSL_PARAM_InitValue(&params[4], CRYPT_PARAM_KDF_P, BSL_PARAM_TYPE_UINT32, &p, sizeof(p)), CRYPT_SUCCESS); ASSERT_EQ(CRYPT_EAL_KdfSetParam(ctx, params), CRYPT_SCRYPT_PARAM_ERROR); p = DATA_LEN; ASSERT_EQ(BSL_PARAM_InitValue(&params[4], CRYPT_PARAM_KDF_P, BSL_PARAM_TYPE_UINT32, &p, sizeof(p)), CRYPT_SUCCESS); ASSERT_EQ(CRYPT_EAL_KdfSetParam(ctx, params), CRYPT_SUCCESS); ASSERT_EQ(CRYPT_EAL_KdfDerive(ctx, out, outLen), CRYPT_SUCCESS); ASSERT_EQ(CRYPT_EAL_KdfDerive(ctx, NULL, outLen), CRYPT_SCRYPT_PARAM_ERROR); ASSERT_EQ(CRYPT_EAL_KdfDerive(ctx, out, 0), CRYPT_SCRYPT_PARAM_ERROR); ASSERT_EQ(CRYPT_EAL_KdfDeInitCtx(ctx), CRYPT_SUCCESS); EXIT: CRYPT_EAL_KdfFreeCtx(ctx); } /* END_CASE */ /** * @test SDV_CRYPT_EAL_KDF_SCRYPT_API_TC002 * @title Parameters N, r, and p of the CRYPT_EAL_Scrypt interface test. * @precon nan * @brief * 1.Abnormal parameter test,about the restriction, see the function declaration, expected result 1. * @expect * 1.The results are as expected,See Note. */ /* BEGIN_CASE */ void SDV_CRYPT_EAL_KDF_SCRYPT_API_TC002(void) { // Parameter limitation: // N < 2^(128 * r / 8) // p <= ((2^32-1) * 32) / (128 * r). Equivalent to r * p <= 2^30 - 1 // p * 128 * r < UINT32_MAX // 32 * r * N * sizeof(uint32_t) < UINT32_MAX => N < ((UINT32_MAX / 128) / r) // UINT32_MAX 0xffffffffU /* 4294967295U */ TestMemInit(); uint32_t keyLen = DATA_LEN; uint8_t key[DATA_LEN]; uint32_t saltLen = DATA_LEN; uint8_t salt[DATA_LEN]; uint32_t N = DATA_LEN; uint32_t r = DATA_LEN; uint32_t p = DATA_LEN; uint32_t outLen = DATA_LEN; uint8_t out[DATA_LEN]; CRYPT_EAL_KdfCTX *ctx = CRYPT_EAL_KdfNewCtx(CRYPT_KDF_SCRYPT); ASSERT_TRUE(ctx != NULL); BSL_Param params[6] = {{0}, {0}, {0}, {0}, {0}, BSL_PARAM_END}; ASSERT_EQ(BSL_PARAM_InitValue(&params[0], CRYPT_PARAM_KDF_PASSWORD, BSL_PARAM_TYPE_OCTETS, key, keyLen), CRYPT_SUCCESS); ASSERT_EQ(BSL_PARAM_InitValue(&params[1], CRYPT_PARAM_KDF_SALT, BSL_PARAM_TYPE_OCTETS, salt, saltLen), CRYPT_SUCCESS); ASSERT_EQ(BSL_PARAM_InitValue(&params[2], CRYPT_PARAM_KDF_N, BSL_PARAM_TYPE_UINT32, &N, sizeof(N)), CRYPT_SUCCESS); ASSERT_EQ(BSL_PARAM_InitValue(&params[3], CRYPT_PARAM_KDF_R, BSL_PARAM_TYPE_UINT32, &r, sizeof(r)), CRYPT_SUCCESS); ASSERT_EQ(BSL_PARAM_InitValue(&params[4], CRYPT_PARAM_KDF_P, BSL_PARAM_TYPE_UINT32, &p, sizeof(p)), CRYPT_SUCCESS); ASSERT_EQ(CRYPT_EAL_KdfSetParam(ctx, params), CRYPT_SUCCESS); ASSERT_EQ(CRYPT_EAL_KdfDerive(ctx, out, outLen), CRYPT_SUCCESS); // N is 2^16 = 65536, r is 1,Not satisfied N < 2^(128 * r / 8) N = 65536; ASSERT_EQ(BSL_PARAM_InitValue(&params[2], CRYPT_PARAM_KDF_N, BSL_PARAM_TYPE_UINT32, &N, sizeof(N)), CRYPT_SUCCESS); r = 1; ASSERT_EQ(BSL_PARAM_InitValue(&params[3], CRYPT_PARAM_KDF_R, BSL_PARAM_TYPE_UINT32, &r, sizeof(r)), CRYPT_SUCCESS); ASSERT_EQ(CRYPT_EAL_KdfSetParam(ctx, params), CRYPT_SUCCESS); ASSERT_EQ(CRYPT_EAL_KdfDerive(ctx, out, outLen), CRYPT_SCRYPT_PARAM_ERROR); // N is 2^15 = 32768, r is 1,satisfied N < 2^(128 * r / 8) N = 32768; ASSERT_EQ(BSL_PARAM_InitValue(&params[2], CRYPT_PARAM_KDF_N, BSL_PARAM_TYPE_UINT32, &N, sizeof(N)), CRYPT_SUCCESS); r = 1; ASSERT_EQ(BSL_PARAM_InitValue(&params[3], CRYPT_PARAM_KDF_R, BSL_PARAM_TYPE_UINT32, &r, sizeof(r)), CRYPT_SUCCESS); ASSERT_EQ(CRYPT_EAL_KdfSetParam(ctx, params), CRYPT_SUCCESS); ASSERT_EQ(CRYPT_EAL_KdfDerive(ctx, out, outLen), CRYPT_SUCCESS); // r = 2^16 = 65536, N = 2^9 = 512, Not satisfied N < ((UINT32_MAX / 128) / r) N = 512; ASSERT_EQ(BSL_PARAM_InitValue(&params[2], CRYPT_PARAM_KDF_N, BSL_PARAM_TYPE_UINT32, &N, sizeof(N)), CRYPT_SUCCESS); r = 65536; ASSERT_EQ(BSL_PARAM_InitValue(&params[3], CRYPT_PARAM_KDF_R, BSL_PARAM_TYPE_UINT32, &r, sizeof(r)), CRYPT_SUCCESS); ASSERT_EQ(CRYPT_EAL_KdfSetParam(ctx, params), CRYPT_SUCCESS); ASSERT_EQ(CRYPT_EAL_KdfDerive(ctx, out, outLen), CRYPT_SCRYPT_PARAM_ERROR); N = DATA_LEN; ASSERT_EQ(BSL_PARAM_InitValue(&params[2], CRYPT_PARAM_KDF_N, BSL_PARAM_TYPE_UINT32, &N, sizeof(N)), CRYPT_SUCCESS); ASSERT_EQ(CRYPT_EAL_KdfSetParam(ctx, params), CRYPT_SUCCESS); // r is 2^16 = 65536, p is 2^16 = 65536, Not satisfied p <= ((2^32-1) * 32) / (128 * r) r = 65536; ASSERT_EQ(BSL_PARAM_InitValue(&params[3], CRYPT_PARAM_KDF_R, BSL_PARAM_TYPE_UINT32, &r, sizeof(r)), CRYPT_SUCCESS); p = 65536; ASSERT_EQ(BSL_PARAM_InitValue(&params[4], CRYPT_PARAM_KDF_P, BSL_PARAM_TYPE_UINT32, &p, sizeof(p)), CRYPT_SUCCESS); ASSERT_EQ(CRYPT_EAL_KdfSetParam(ctx, params), CRYPT_SUCCESS); ASSERT_EQ(CRYPT_EAL_KdfDerive(ctx, out, outLen), CRYPT_SCRYPT_PARAM_ERROR); // r = 2^16 = 65536, p = 2^14 = 16384, Not satisfied r * p <= 2^30 - 1 r = 65536; ASSERT_EQ(BSL_PARAM_InitValue(&params[3], CRYPT_PARAM_KDF_R, BSL_PARAM_TYPE_UINT32, &r, sizeof(r)), CRYPT_SUCCESS); p = 16384; ASSERT_EQ(BSL_PARAM_InitValue(&params[4], CRYPT_PARAM_KDF_P, BSL_PARAM_TYPE_UINT32, &p, sizeof(p)), CRYPT_SUCCESS); ASSERT_EQ(CRYPT_EAL_KdfDerive(ctx, out, outLen), CRYPT_SCRYPT_PARAM_ERROR); // r = 2^16 = 65536, p = 2^9 = 512, Not satisfied p * 128 * r < UINT32_MAX r = 65536; ASSERT_EQ(BSL_PARAM_InitValue(&params[3], CRYPT_PARAM_KDF_R, BSL_PARAM_TYPE_UINT32, &r, sizeof(r)), CRYPT_SUCCESS); p = 512; ASSERT_EQ(BSL_PARAM_InitValue(&params[4], CRYPT_PARAM_KDF_P, BSL_PARAM_TYPE_UINT32, &p, sizeof(p)), CRYPT_SUCCESS); ASSERT_EQ(CRYPT_EAL_KdfSetParam(ctx, params), CRYPT_SUCCESS); ASSERT_EQ(CRYPT_EAL_KdfDerive(ctx, out, outLen), CRYPT_SCRYPT_PARAM_ERROR); // r = 2^8 = 256, p = 2^22 = 4194304, Not satisfied r * p <= 2^30 - 1 r = 256; ASSERT_EQ(BSL_PARAM_InitValue(&params[3], CRYPT_PARAM_KDF_R, BSL_PARAM_TYPE_UINT32, &r, sizeof(r)), CRYPT_SUCCESS); p = 4194304; ASSERT_EQ(BSL_PARAM_InitValue(&params[4], CRYPT_PARAM_KDF_P, BSL_PARAM_TYPE_UINT32, &p, sizeof(p)), CRYPT_SUCCESS); ASSERT_EQ(CRYPT_EAL_KdfSetParam(ctx, params), CRYPT_SUCCESS); ASSERT_EQ(CRYPT_EAL_KdfDerive(ctx, out, outLen), CRYPT_SCRYPT_PARAM_ERROR); // r = 2^4 = 16, p = 2^26 = 67108864, Not satisfied r * p <= 2^30 - 1 r = 16; ASSERT_EQ(BSL_PARAM_InitValue(&params[3], CRYPT_PARAM_KDF_R, BSL_PARAM_TYPE_UINT32, &r, sizeof(r)), CRYPT_SUCCESS); p = 67108864; ASSERT_EQ(BSL_PARAM_InitValue(&params[4], CRYPT_PARAM_KDF_P, BSL_PARAM_TYPE_UINT32, &p, sizeof(p)), CRYPT_SUCCESS); ASSERT_EQ(CRYPT_EAL_KdfSetParam(ctx, params), CRYPT_SUCCESS); ASSERT_EQ(CRYPT_EAL_KdfDerive(ctx, out, outLen), CRYPT_SCRYPT_PARAM_ERROR); // r = 2^4 = 16, p = 2^21 = 2097152, Not satisfied p * 128 * r < UINT32_MAX r = 16; ASSERT_EQ(BSL_PARAM_InitValue(&params[3], CRYPT_PARAM_KDF_R, BSL_PARAM_TYPE_UINT32, &r, sizeof(r)), CRYPT_SUCCESS); p = 2097152; ASSERT_EQ(BSL_PARAM_InitValue(&params[4], CRYPT_PARAM_KDF_P, BSL_PARAM_TYPE_UINT32, &p, sizeof(p)), CRYPT_SUCCESS); ASSERT_EQ(CRYPT_EAL_KdfSetParam(ctx, params), CRYPT_SUCCESS); ASSERT_EQ(CRYPT_EAL_KdfDerive(ctx, out, outLen), CRYPT_SCRYPT_PARAM_ERROR); EXIT: CRYPT_EAL_KdfFreeCtx(ctx); } /* END_CASE */ /** * @test SDV_CRYPT_EAL_KDF_SCRYPT_FUN_TC001 * @title Scrypt vector test. * @precon nan * @brief * 1.Calculate the output using the given parameters, expected result 1. * 2.Compare the calculated result with the standard value, expected result 2. * @expect * 1.Calculation succeeded.. * 2.The results are the same. */ /* BEGIN_CASE */ void SDV_CRYPT_EAL_KDF_SCRYPT_FUN_TC001(Hex *key, Hex *salt, int N, int r, int p, Hex *result) { TestMemInit(); uint32_t outLen = result->len; uint8_t *out = malloc(outLen * sizeof(uint8_t)); ASSERT_TRUE(out != NULL); CRYPT_EAL_KdfCTX *ctx = CRYPT_EAL_KdfNewCtx(CRYPT_KDF_SCRYPT); ASSERT_TRUE(ctx != NULL); BSL_Param params[6] = {{0}, {0}, {0}, {0}, {0}, BSL_PARAM_END}; ASSERT_EQ(BSL_PARAM_InitValue(&params[0], CRYPT_PARAM_KDF_PASSWORD, BSL_PARAM_TYPE_OCTETS, key->x, key->len), CRYPT_SUCCESS); ASSERT_EQ(BSL_PARAM_InitValue(&params[1], CRYPT_PARAM_KDF_SALT, BSL_PARAM_TYPE_OCTETS, salt->x, salt->len), CRYPT_SUCCESS); ASSERT_EQ(BSL_PARAM_InitValue(&params[2], CRYPT_PARAM_KDF_N, BSL_PARAM_TYPE_UINT32, &N, sizeof(N)), CRYPT_SUCCESS); ASSERT_EQ(BSL_PARAM_InitValue(&params[3], CRYPT_PARAM_KDF_R, BSL_PARAM_TYPE_UINT32, &r, sizeof(r)), CRYPT_SUCCESS); ASSERT_EQ(BSL_PARAM_InitValue(&params[4], CRYPT_PARAM_KDF_P, BSL_PARAM_TYPE_UINT32, &p, sizeof(p)), CRYPT_SUCCESS); ASSERT_EQ(CRYPT_EAL_KdfSetParam(ctx, params), CRYPT_SUCCESS); ASSERT_EQ(CRYPT_EAL_KdfDerive(ctx, out, outLen), CRYPT_SUCCESS); ASSERT_COMPARE("result cmp", out, outLen, result->x, result->len); EXIT: if (out != NULL) { free(out); } CRYPT_EAL_KdfFreeCtx(ctx); } /* END_CASE */ /** * @test SDV_CRYPTO_SCRYPT_DEFAULT_PROVIDER_FUNC_TC001 * @title Default provider testing * @precon nan * @brief * Load the default provider and use the test vector to test its correctness */ /* BEGIN_CASE */ void SDV_CRYPTO_SCRYPT_DEFAULT_PROVIDER_FUNC_TC001(Hex *key, Hex *salt, int N, int r, int p, Hex *result) { TestMemInit(); uint32_t outLen = result->len; uint8_t *out = malloc(outLen * sizeof(uint8_t)); ASSERT_TRUE(out != NULL); CRYPT_EAL_KdfCTX *ctx = NULL; #ifdef HITLS_CRYPTO_PROVIDER ctx = CRYPT_EAL_ProviderKdfNewCtx(NULL, CRYPT_KDF_SCRYPT, "provider=default"); #else ctx = CRYPT_EAL_KdfNewCtx(CRYPT_KDF_SCRYPT); #endif ASSERT_TRUE(ctx != NULL); BSL_Param params[6] = {{0}, {0}, {0}, {0}, {0}, BSL_PARAM_END}; ASSERT_EQ(BSL_PARAM_InitValue(&params[0], CRYPT_PARAM_KDF_PASSWORD, BSL_PARAM_TYPE_OCTETS, key->x, key->len), CRYPT_SUCCESS); ASSERT_EQ(BSL_PARAM_InitValue(&params[1], CRYPT_PARAM_KDF_SALT, BSL_PARAM_TYPE_OCTETS, salt->x, salt->len), CRYPT_SUCCESS); ASSERT_EQ(BSL_PARAM_InitValue(&params[2], CRYPT_PARAM_KDF_N, BSL_PARAM_TYPE_UINT32, &N, sizeof(N)), CRYPT_SUCCESS); ASSERT_EQ(BSL_PARAM_InitValue(&params[3], CRYPT_PARAM_KDF_R, BSL_PARAM_TYPE_UINT32, &r, sizeof(r)), CRYPT_SUCCESS); ASSERT_EQ(BSL_PARAM_InitValue(&params[4], CRYPT_PARAM_KDF_P, BSL_PARAM_TYPE_UINT32, &p, sizeof(p)), CRYPT_SUCCESS); ASSERT_EQ(CRYPT_EAL_KdfSetParam(ctx, params), CRYPT_SUCCESS); ASSERT_EQ(CRYPT_EAL_KdfDerive(ctx, out, outLen), CRYPT_SUCCESS); ASSERT_COMPARE("result cmp", out, outLen, result->x, result->len); EXIT: if (out != NULL) { free(out); } CRYPT_EAL_KdfFreeCtx(ctx); } /* END_CASE */ /** * @test SDV_CRYPT_EAL_KDF_SCRYPT_FUN_TC002 * @title Data tests that may exceed the boundaries. * @precon nan * @brief * 1. Use parameters that will go out of bounds, Call func CRYPT_EAL_KdfDerive. * @expect * 1.return value is CRYPT_SCRYPT_PARAM_ERROR. */ /* BEGIN_CASE */ void SDV_CRYPT_EAL_KDF_SCRYPT_FUN_TC002(int testN, int testR, int testP) { TestMemInit(); uint32_t keyLen = DATA_LEN; uint8_t key[DATA_LEN]; uint32_t saltLen = DATA_LEN; uint8_t salt[DATA_LEN]; uint32_t N = testN; uint32_t r = testR; uint32_t p = testP; uint32_t outLen = DATA_LEN; uint8_t out[DATA_LEN]; CRYPT_EAL_KdfCTX *ctx = CRYPT_EAL_KdfNewCtx(CRYPT_KDF_SCRYPT); ASSERT_TRUE(ctx != NULL); BSL_Param params[6] = {{0}, {0}, {0}, {0}, {0}, BSL_PARAM_END}; ASSERT_EQ(BSL_PARAM_InitValue(&params[0], CRYPT_PARAM_KDF_PASSWORD, BSL_PARAM_TYPE_OCTETS, key, keyLen), CRYPT_SUCCESS); ASSERT_EQ(BSL_PARAM_InitValue(&params[1], CRYPT_PARAM_KDF_SALT, BSL_PARAM_TYPE_OCTETS, salt, saltLen), CRYPT_SUCCESS); ASSERT_EQ(BSL_PARAM_InitValue(&params[2], CRYPT_PARAM_KDF_N, BSL_PARAM_TYPE_UINT32, &N, sizeof(N)), CRYPT_SUCCESS); ASSERT_EQ(BSL_PARAM_InitValue(&params[3], CRYPT_PARAM_KDF_R, BSL_PARAM_TYPE_UINT32, &r, sizeof(r)), CRYPT_SUCCESS); ASSERT_EQ(BSL_PARAM_InitValue(&params[4], CRYPT_PARAM_KDF_P, BSL_PARAM_TYPE_UINT32, &p, sizeof(p)), CRYPT_SUCCESS); ASSERT_EQ(CRYPT_EAL_KdfSetParam(ctx, params), CRYPT_SUCCESS); ASSERT_EQ(CRYPT_EAL_KdfDerive(ctx, out, outLen), CRYPT_SCRYPT_PARAM_ERROR); EXIT: CRYPT_EAL_KdfFreeCtx(ctx); } /* END_CASE */
2301_79861745/bench_create
testcode/sdv/testcase/crypto/scrypt/test_suite_sdv_eal_kdf_scrypt.c
C
unknown
17,393
/* * This file is part of the openHiTLS project. * * openHiTLS is licensed under the Mulan PSL v2. * You can use this software according to the terms and conditions of the Mulan PSL v2. * You may obtain a copy of Mulan PSL v2 at: * * http://license.coscl.org.cn/MulanPSL2 * * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, * EITHER EXPRESS 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 <pthread.h> #include "securec.h" #include "eal_md_local.h" #include "crypt_eal_md.h" #include "crypt_errno.h" #include "bsl_sal.h" /* END_HEADER */ #define SHA1_DIGEST_LEN (20) #define DATA_MAX_LEN (65538) typedef struct { uint8_t *data; uint8_t *hash; uint32_t dataLen; uint32_t hashLen; } ThreadParameter; void MultiThreadTest(void *arg) { ThreadParameter *threadParameter = (ThreadParameter *)arg; uint32_t outLen = SHA1_DIGEST_LEN; uint8_t out[SHA1_DIGEST_LEN]; CRYPT_EAL_MdCTX *ctx = NULL; ctx = CRYPT_EAL_MdNewCtx(CRYPT_MD_SHA1); ASSERT_TRUE(ctx != NULL); for (uint32_t i = 0; i < 10; i++) { ASSERT_EQ(CRYPT_EAL_MdInit(ctx), CRYPT_SUCCESS); ASSERT_EQ(CRYPT_EAL_MdUpdate(ctx, threadParameter->data, threadParameter->dataLen), CRYPT_SUCCESS); ASSERT_EQ(CRYPT_EAL_MdFinal(ctx, out, &outLen), CRYPT_SUCCESS); ASSERT_COMPARE("hash result cmp", out, outLen, threadParameter->hash, threadParameter->hashLen); } EXIT: CRYPT_EAL_MdFreeCtx(ctx); } /** * @test SDV_CRYPT_EAL_SHA1_API_TC001 * @title Initialization interface test * @precon nan * @brief * 1.Call CRYPT_EAL_MdInit and enter NULL, expected result 1. * 2.Call CRYPT_EAL_MdNewCtx create ctx, expected result 2. * 3.Call CRYPT_EAL_MdInit and use the correct ID. expected result 3. * @expect * 1.Initialization failed, return CRYPT_NULL_INPUT * 2.The ctx is created successfully. * 3.Initialization successful, return CRYPT_SUCCESS. */ /* BEGIN_CASE */ void SDV_CRYPT_EAL_SHA1_API_TC001(void) { TestMemInit(); CRYPT_EAL_MdCTX *ctx = CRYPT_EAL_MdNewCtx(CRYPT_MD_MAX);; ASSERT_TRUE(ctx == NULL); ASSERT_EQ(CRYPT_EAL_MdInit(NULL), CRYPT_NULL_INPUT); ctx = CRYPT_EAL_MdNewCtx(CRYPT_MD_SHA1);; ASSERT_TRUE(ctx != NULL); ASSERT_EQ(CRYPT_EAL_MdInit(ctx), CRYPT_SUCCESS); EXIT: CRYPT_EAL_MdFreeCtx(ctx); } /* END_CASE */ /** * @test SDV_CRYPT_EAL_SHA1_API_TC002 * @title CRYPT_EAL_MdUpdate and CRYPT_EAL_MdFinal test * @precon nan * @brief * 1.Call CRYPT_EAL_MdDeinit the null CTX, expected result 1. * 2.Invoke the CRYPT_EAL_MdNewCtx to create a CTX, expected result 2. * 3.Call CRYPT_EAL_MdUpdate and CRYPT_EAL_MdFinal before initialization, expected result 3 is obtained. * 4.Initialize the CTX and transfer null pointers to CRYPT_EAL_MdUpdate and CRYPT_EAL_MdFinal. expected result 4. * 5.Invoke CRYPT_EAL_MdUpdate and CRYPT_EAL_MdFinal normally, expected result 5. * 6.Call CRYPT_EAL_MdDeinit the CTX, expected result 6. * @expect * 1.Return CRYPT_NULL_INPUT * 2.Successful, ctx is returned. * 3.Return CRYPT_EAL_ERR_STATE * 4.Return CRYPT_NULL_INPUT * 5.Return CRYPT_SUCCESS * 6.Return CRYPT_SUCCESS */ /* BEGIN_CASE */ void SDV_CRYPT_EAL_SHA1_API_TC002(void) { TestMemInit(); CRYPT_EAL_MdCTX *ctx = NULL; const uint32_t dataLen = SHA1_DIGEST_LEN; uint8_t data[SHA1_DIGEST_LEN]; uint32_t digestLen = SHA1_DIGEST_LEN; uint8_t out[SHA1_DIGEST_LEN]; ASSERT_EQ(CRYPT_EAL_MdDeinit(ctx), CRYPT_NULL_INPUT); ctx = CRYPT_EAL_MdNewCtx(CRYPT_MD_SHA1); ASSERT_TRUE(ctx != NULL); ASSERT_EQ(CRYPT_EAL_MdUpdate(ctx, data, dataLen), CRYPT_EAL_ERR_STATE); ASSERT_EQ(CRYPT_EAL_MdFinal(ctx, out, &digestLen), CRYPT_EAL_ERR_STATE); ASSERT_EQ(CRYPT_EAL_MdInit(ctx), CRYPT_SUCCESS); ASSERT_EQ(CRYPT_EAL_MdUpdate(NULL, data, dataLen), CRYPT_NULL_INPUT); ASSERT_EQ(CRYPT_EAL_MdUpdate(ctx, NULL, dataLen), CRYPT_NULL_INPUT); ASSERT_EQ(CRYPT_EAL_MdUpdate(ctx, data, 0), CRYPT_SUCCESS); ASSERT_EQ(CRYPT_EAL_MdUpdate(ctx, data, dataLen), CRYPT_SUCCESS); ASSERT_EQ(CRYPT_EAL_MdFinal(NULL, out, &digestLen), CRYPT_NULL_INPUT); ASSERT_EQ(CRYPT_EAL_MdFinal(ctx, NULL, &digestLen), CRYPT_NULL_INPUT); digestLen = SHA1_DIGEST_LEN - 1; ASSERT_EQ(CRYPT_EAL_MdFinal(ctx, out, &digestLen), CRYPT_SHA1_OUT_BUFF_LEN_NOT_ENOUGH); digestLen = SHA1_DIGEST_LEN; ASSERT_EQ(CRYPT_EAL_MdFinal(ctx, out, &digestLen), CRYPT_SUCCESS); ASSERT_EQ(CRYPT_EAL_MdDeinit(ctx), CRYPT_SUCCESS); ASSERT_EQ(ctx->state, CRYPT_MD_STATE_NEW); EXIT: CRYPT_EAL_MdFreeCtx(ctx); } /* END_CASE */ /** * @test SDV_CRYPT_EAL_SHA1_API_TC003 * @title Repeated hash calculation test * @precon nan * @brief * 1.Call CRYPT_EAL_MdNewCtx to create a CTX, expected result 1. * 2.Calculate the hash, expected result 2. * 3.Calculate the hash again, expected result 3. * 4.Calculate the hash again, expected result 4. * 5.Call CRYPT_EAL_MdFinal again, expected result 5. * 6.Call CRYPT_EAL_Md to calculate the hash value, expected result 6. * @expect * 1.Successful, ctx is returned. * 2.Obtains the hash of an empty string. * 3.Obtains the hash of data * 4.Obtains the hash of an empty string. * 5.Return CRYPT_EAL_ERR_STATE. * 6.Obtains the expected hash of data */ /* BEGIN_CASE */ void SDV_CRYPT_EAL_SHA1_API_TC003(Hex *hash1, Hex *data2, Hex *hash2, Hex *hash3) { TestMemInit(); CRYPT_EAL_MdCTX *ctx = NULL; uint32_t digestLen = SHA1_DIGEST_LEN; uint8_t out[SHA1_DIGEST_LEN]; ctx = CRYPT_EAL_MdNewCtx(CRYPT_MD_SHA1); ASSERT_TRUE(ctx != NULL); // Hash calculation for the first time. ASSERT_TRUE(CRYPT_EAL_MdInit(ctx) == CRYPT_SUCCESS); ASSERT_TRUE(CRYPT_EAL_MdFinal(ctx, out, &digestLen) == CRYPT_SUCCESS); ASSERT_COMPARE("hash1 result cmp", out, digestLen, hash1->x, hash1->len); // Hash calculation for the second time. ASSERT_TRUE(CRYPT_EAL_MdInit(ctx) == CRYPT_SUCCESS); ASSERT_TRUE(CRYPT_EAL_MdUpdate(ctx, data2->x, data2->len) == CRYPT_SUCCESS); ASSERT_TRUE(CRYPT_EAL_MdFinal(ctx, out, &digestLen) == CRYPT_SUCCESS); ASSERT_COMPARE("hash2 result cmp", out, digestLen, hash2->x, hash2->len); // Hash calculation for the third time. ASSERT_TRUE(CRYPT_EAL_MdInit(ctx) == CRYPT_SUCCESS); ASSERT_TRUE(CRYPT_EAL_MdFinal(ctx, out, &digestLen) == CRYPT_SUCCESS); ASSERT_COMPARE("hash3 result cmp", out, digestLen, hash3->x, hash3->len); ASSERT_TRUE(CRYPT_EAL_MdFinal(ctx, out, &digestLen) == CRYPT_EAL_ERR_STATE); ASSERT_EQ(CRYPT_EAL_Md(CRYPT_MD_SHA1, data2->x, data2->len, out, &digestLen), CRYPT_SUCCESS); ASSERT_COMPARE("hash2 result cmp", out, digestLen, hash2->x, hash2->len); EXIT: CRYPT_EAL_MdFreeCtx(ctx); } /* END_CASE */ /** * @test SDV_CRYPT_EAL_SHA1_API_TC004 * @title To test the function of obtaining the digest length of the hash algorithm. * @precon nan * @brief * 1.Call CRYPT_EAL_MdGetDigestSize,the input parameter ID is invalid, expected result 1. * 2.Call CRYPT_EAL_MdGetDigestSize, Using CRYPT_MD_SHA1, expected result 2. * @expect * 1.Failed, return 0. * 2.Success, return SHA1_DIGEST_LEN. */ /* BEGIN_CASE */ void SDV_CRYPT_EAL_SHA1_API_TC004(void) { ASSERT_EQ(CRYPT_EAL_MdGetDigestSize(CRYPT_MD_MAX), 0); ASSERT_EQ(CRYPT_EAL_MdGetDigestSize(CRYPT_MD_SHA1), SHA1_DIGEST_LEN); EXIT: return; } /* END_CASE */ /** * @test SDV_CRYPT_EAL_SHA1_FUN_TC001 * @title Perform the vector test to check whether the calculation result is consistent with the standard output. * @precon nan * @brief * 1.Calculate the hash of each group of data, expected result 1. * 2.Compare the result to the expected value, expected result 2. * @expect * 1.Hash calculation succeeded. * 2.The results are as expected. */ /* BEGIN_CASE */ void SDV_CRYPT_EAL_SHA1_FUN_TC001(Hex *data, Hex *hash) { TestMemInit(); CRYPT_EAL_MdCTX *ctx = NULL; uint32_t digestLen = SHA1_DIGEST_LEN; uint8_t out[SHA1_DIGEST_LEN]; ctx = CRYPT_EAL_MdNewCtx(CRYPT_MD_SHA1); ASSERT_TRUE(ctx != NULL); ASSERT_EQ(CRYPT_EAL_MdInit(ctx), CRYPT_SUCCESS); ASSERT_EQ(CRYPT_EAL_MdUpdate(ctx, data->x, data->len), CRYPT_SUCCESS); ASSERT_EQ(CRYPT_EAL_MdFinal(ctx, out, &digestLen), CRYPT_SUCCESS); ASSERT_COMPARE("hash result cmp", out, digestLen, hash->x, hash->len); EXIT: CRYPT_EAL_MdFreeCtx(ctx); } /* END_CASE */ /** * @test SDV_CRYPT_EAL_SHA1_FUN_TC002 * @title Test multi-thread hash calculation. * @precon nan * @brief * 1.Create two threads and calculate the hash, expected result 1. * 2.Compare the result to the expected value, expected result 2. * @expect * 1.Hash calculation succeeded. * 2.The results are as expected. */ /* BEGIN_CASE */ void SDV_CRYPT_EAL_SHA1_FUN_TC002(Hex *data, Hex *hash) { int ret; TestMemInit(); const uint32_t threadNum = 2; pthread_t thrd[2]; ThreadParameter arg[2] = { {data->x, hash->x, data->len, hash->len}, {data->x, hash->x, data->len, hash->len} }; for (uint32_t i = 0; i < threadNum; i++) { ret = pthread_create(&thrd[i], NULL, (void *)MultiThreadTest, &arg[i]); ASSERT_TRUE(ret == 0); } for (uint32_t i = 0; i < threadNum; i++) { pthread_join(thrd[i], NULL); } EXIT: return; } /* END_CASE */ /** * @test SDV_CRYPT_EAL_SHA1_FUN_TC003 * @title Hash calculation for multiple updates,comparison with standard results. * @precon nan * @brief * 1.Call CRYPT_EAL_MdNewCtx to create a ctx and initialize, expected result 1. * 2.Call CRYPT_EAL_MdUpdate to calculate the hash of a data segmentxpected result 2. * 3.Call CRYPT_EAL_MdUpdate to calculate the next data segmentxpected result 3. * 4.Call CRYPT_EAL_MdUpdate to calculate the next data segmentxpected result 4. * 5.Call CRYPT_EAL_MdFinal get the result, expected result 5. * @expect * 1.Successful * 2.Successful * 3.Successful * 4.Successful * 5.The results are as expected. */ /* BEGIN_CASE */ void SDV_CRYPT_EAL_SHA1_FUN_TC003(Hex *plain_text1, Hex *plain_text2, Hex *plain_text3, Hex *hash) { unsigned char output[SHA1_DIGEST_LEN]; uint32_t outLen = SHA1_DIGEST_LEN; TestMemInit(); CRYPT_EAL_MdCTX *ctx = CRYPT_EAL_MdNewCtx(CRYPT_MD_SHA1); ASSERT_TRUE(ctx != NULL); ASSERT_EQ(CRYPT_EAL_MdInit(ctx), CRYPT_SUCCESS); ASSERT_EQ(CRYPT_EAL_MdUpdate(ctx, plain_text1->x, plain_text1->len), CRYPT_SUCCESS); ASSERT_EQ(CRYPT_EAL_MdUpdate(ctx, plain_text2->x, plain_text2->len), CRYPT_SUCCESS); ASSERT_EQ(CRYPT_EAL_MdUpdate(ctx, plain_text3->x, plain_text3->len), CRYPT_SUCCESS); ASSERT_EQ(CRYPT_EAL_MdFinal(ctx, output, &outLen), CRYPT_SUCCESS); ASSERT_COMPARE("sha1", output, outLen, hash->x, hash->len); EXIT: CRYPT_EAL_MdFreeCtx(ctx); } /* END_CASE */ /** * @test SDV_CRYPTO_SHA1_COPY_CTX_FUNC_TC001 * @title SHA1 copy ctx function test. * @precon nan * @brief * 1. Create the context ctx of md algorithm, expected result 1 * 2. Call to CRYPT_EAL_MdCopyCtx method to copy ctx, expected result 2 * 2. Call to CRYPT_EAL_MdCopyCtx method to copy a null ctx, expected result 3 * 3. Calculate the hash of msg, and compare the calculated result with hash vector, expected result 4 * 4. Call to CRYPT_EAL_MdDupCtx method to copy ctx, expected result 5 * 3. Calculate the hash of msg, and compare the calculated result with hash vector, expected result 6 * @expect * 1. Success, the context is not null. * 2. CRYPT_SUCCESS * 3. CRYPT_NULL_INPUT * 4. Success, the context is not null. * 5. CRYPT_SUCCESS * 6. Success, the hashs are the same. */ /* BEGIN_CASE */ void SDV_CRYPTO_SHA1_COPY_CTX_FUNC_TC001(int id, Hex *msg, Hex *hash) { TestMemInit(); CRYPT_EAL_MdCTX *cpyCtx = NULL; CRYPT_EAL_MdCTX *dupCtx = NULL; CRYPT_EAL_MdCTX *ctx = CRYPT_EAL_MdNewCtx(id); ASSERT_TRUE(ctx != NULL); uint8_t output[SHA1_DIGEST_LEN]; uint32_t outLen = SHA1_DIGEST_LEN; dupCtx=CRYPT_EAL_MdDupCtx(cpyCtx); ASSERT_TRUE(dupCtx == NULL); ASSERT_EQ(CRYPT_MD_MAX, CRYPT_EAL_MdGetId(dupCtx)); ASSERT_EQ(CRYPT_EAL_MdCopyCtx(cpyCtx, ctx), CRYPT_NULL_INPUT); cpyCtx = CRYPT_EAL_MdNewCtx(id); ASSERT_TRUE(cpyCtx != NULL); ASSERT_TRUE(dupCtx == NULL); ASSERT_EQ(CRYPT_EAL_MdCopyCtx(cpyCtx, dupCtx), CRYPT_NULL_INPUT); ASSERT_EQ(CRYPT_EAL_MdCopyCtx(cpyCtx, ctx), CRYPT_SUCCESS); ASSERT_EQ(CRYPT_EAL_MdInit(cpyCtx), CRYPT_SUCCESS); ASSERT_EQ(CRYPT_EAL_MdUpdate(cpyCtx, msg->x, msg->len), CRYPT_SUCCESS); ASSERT_EQ(CRYPT_EAL_MdFinal(cpyCtx, output, &outLen), CRYPT_SUCCESS); ASSERT_EQ(id, cpyCtx->id); ASSERT_EQ(memcmp(output, hash->x, hash->len), 0); dupCtx=CRYPT_EAL_MdDupCtx(ctx); ASSERT_TRUE(dupCtx != NULL); ASSERT_EQ(CRYPT_EAL_MdInit(dupCtx), CRYPT_SUCCESS); ASSERT_EQ(CRYPT_EAL_MdUpdate(dupCtx, msg->x, msg->len), CRYPT_SUCCESS); ASSERT_EQ(CRYPT_EAL_MdFinal(dupCtx, output, &outLen), CRYPT_SUCCESS); ASSERT_EQ(id, CRYPT_EAL_MdGetId(dupCtx)); ASSERT_EQ(memcmp(output, hash->x, hash->len), 0); EXIT: CRYPT_EAL_MdFreeCtx(ctx); CRYPT_EAL_MdFreeCtx(cpyCtx); CRYPT_EAL_MdFreeCtx(dupCtx); } /* END_CASE */ /** * @test SDV_CRYPT_EAL_SHA1_FUN_TC004 * @title Default provider testing * @precon nan * @brief * Load the default provider and use the test vector to test its correctness */ /* BEGIN_CASE */ void SDV_CRYPT_EAL_SHA1_FUN_TC004(int id, Hex *msg, Hex *hash) { TestMemInit(); uint8_t output[SHA1_DIGEST_LEN]; uint32_t outLen = SHA1_DIGEST_LEN; CRYPT_EAL_MdCTX *ctx = NULL; #ifdef HITLS_CRYPTO_PROVIDER ctx = CRYPT_EAL_ProviderMdNewCtx(NULL, id, "provider=default"); #else (void)id; ctx = CRYPT_EAL_MdNewCtx(id); #endif ASSERT_TRUE(ctx != NULL); ASSERT_EQ(CRYPT_EAL_MdInit(ctx), CRYPT_SUCCESS); ASSERT_EQ(CRYPT_EAL_MdUpdate(ctx, msg->x, msg->len), CRYPT_SUCCESS); ASSERT_EQ(CRYPT_EAL_MdFinal(ctx, output, &outLen), CRYPT_SUCCESS); ASSERT_EQ(memcmp(output, hash->x, hash->len), 0); EXIT: CRYPT_EAL_MdFreeCtx(ctx); } /* END_CASE */
2301_79861745/bench_create
testcode/sdv/testcase/crypto/sha1/test_suite_sdv_eal_md_sha1.c
C
unknown
14,377
/* * This file is part of the openHiTLS project. * * openHiTLS is licensed under the Mulan PSL v2. * You can use this software according to the terms and conditions of the Mulan PSL v2. * You may obtain a copy of Mulan PSL v2 at: * * http://license.coscl.org.cn/MulanPSL2 * * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, * EITHER EXPRESS 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 <pthread.h> #include "eal_md_local.h" #include "crypt_eal_md.h" #include "crypt_errno.h" #include "bsl_sal.h" /* END_HEADER */ // 100 is greater than the digest length of all SHA algorithms. #define SHA2_OUTPUT_MAXSIZE 100 typedef struct { uint8_t *data; uint8_t *hash; uint32_t dataLen; uint32_t hashLen; CRYPT_MD_AlgId id; } ThreadParameter; void Sha2MultiThreadTest(void *arg) { ThreadParameter *threadParameter = (ThreadParameter *)arg; uint32_t outLen = SHA2_OUTPUT_MAXSIZE; uint8_t out[SHA2_OUTPUT_MAXSIZE]; CRYPT_EAL_MdCTX *ctx = NULL; ctx = CRYPT_EAL_MdNewCtx(threadParameter->id); ASSERT_TRUE(ctx != NULL); for (uint32_t i = 0; i < 10; i++) { // Repeat 10 times ASSERT_EQ(CRYPT_EAL_MdInit(ctx), CRYPT_SUCCESS); ASSERT_EQ(CRYPT_EAL_MdUpdate(ctx, threadParameter->data, threadParameter->dataLen), CRYPT_SUCCESS); ASSERT_EQ(CRYPT_EAL_MdFinal(ctx, out, &outLen), CRYPT_SUCCESS); ASSERT_COMPARE("hash result cmp", out, outLen, threadParameter->hash, threadParameter->hashLen); } EXIT: CRYPT_EAL_MdFreeCtx(ctx); } /** * @test SDV_CRYPT_EAL_SHA2_API_TC001 * @title Create sha2 context test. * @precon nan * @brief * 1.Create context with invalid id, expected result 1. * 2.Create context using CRYPT_MD_SHA224 CRYPT_MD_SHA256 CRYPT_MD_SHA384 CRYPT_MD_SHA512, expected result 2. * @expect * 1.The result is NULL. * 2.Create successful. */ /* BEGIN_CASE */ void SDV_CRYPT_EAL_SHA2_API_TC001(void) { TestMemInit(); CRYPT_EAL_MdCTX *ctx = NULL; ctx = CRYPT_EAL_MdNewCtx(-1); ASSERT_TRUE(ctx == NULL); ctx = CRYPT_EAL_MdNewCtx(CRYPT_MD_MAX); ASSERT_TRUE(ctx == NULL); ctx = CRYPT_EAL_MdNewCtx(CRYPT_MD_SHA224); ASSERT_TRUE(ctx != NULL); CRYPT_EAL_MdFreeCtx(ctx); ctx = CRYPT_EAL_MdNewCtx(CRYPT_MD_SHA256); ASSERT_TRUE(ctx != NULL); CRYPT_EAL_MdFreeCtx(ctx); ctx = CRYPT_EAL_MdNewCtx(CRYPT_MD_SHA384); ASSERT_TRUE(ctx != NULL); CRYPT_EAL_MdFreeCtx(ctx); ctx = CRYPT_EAL_MdNewCtx(CRYPT_MD_SHA512); ASSERT_TRUE(ctx != NULL); EXIT: CRYPT_EAL_MdFreeCtx(ctx); } /* END_CASE */ /** * @test SDV_CRYPT_EAL_SHA2_API_TC002 * @title SHA2 get the digest length test. * @precon nan * @brief * 1.Call CRYPT_EAL_MdGetDigestSize to get the digest length, expected result 1. * @expect * 1.The value is the same as expected. */ /* BEGIN_CASE */ void SDV_CRYPT_EAL_SHA2_API_TC002(void) { ASSERT_EQ(CRYPT_EAL_MdGetDigestSize(-1), 0); ASSERT_EQ(CRYPT_EAL_MdGetDigestSize(CRYPT_MD_MAX), 0); // The length of the SHA224 digest is 28 characters. ASSERT_EQ(CRYPT_EAL_MdGetDigestSize(CRYPT_MD_SHA224), 28); // The length of the SHA256 digest is 32 characters. ASSERT_EQ(CRYPT_EAL_MdGetDigestSize(CRYPT_MD_SHA256), 32); // The length of the SHA384 digest is 48 characters. ASSERT_EQ(CRYPT_EAL_MdGetDigestSize(CRYPT_MD_SHA384), 48); // The length of the SHA512 digest is 64 characters. ASSERT_EQ(CRYPT_EAL_MdGetDigestSize(CRYPT_MD_SHA512), 64); EXIT: return; } /* END_CASE */ /** * @test SDV_CRYPT_EAL_SHA2_API_TC003 * @title update and final test. * @precon nan * @brief * 1.Call CRYPT_EAL_MdDeinit the null CTX, expected result 1. * 2.Call CRYPT_EAL_MdNewCtx create the CTX, expected result 2. * 3.Call CRYPT_EAL_MdUpdate and CRYPT_EAL_MdFinal before initialization, expected result 3. * 4.Call CRYPT_EAL_MdUpdate and CRYPT_EAL_MdFinal use null pointer, expected result 4. * 5.Call CRYPT_EAL_MdUpdate and CRYPT_EAL_MdFinal normally, expected result 5. * 6.Call CRYPT_EAL_MdDeinit the CTX, expected result 6. * @expect * 1.Return CRYPT_NULL_INPUT * 2.Create successful. * 3.Return CRYPT_EAL_ERR_STATE. * 4.Return CRYPT_NULL_INPUT. * 5.Successful. * 6.Return CRYPT_SUCCESS */ /* BEGIN_CASE */ void SDV_CRYPT_EAL_SHA2_API_TC003(int id) { TestMemInit(); CRYPT_EAL_MdCTX *ctx = NULL; ASSERT_EQ(CRYPT_EAL_MdDeinit(ctx), CRYPT_NULL_INPUT); ctx = CRYPT_EAL_MdNewCtx(id); ASSERT_TRUE(ctx != NULL); uint8_t input[SHA2_OUTPUT_MAXSIZE]; const uint32_t inLen = SHA2_OUTPUT_MAXSIZE; uint8_t out[SHA2_OUTPUT_MAXSIZE]; uint32_t validOutLen = CRYPT_EAL_MdGetDigestSize(id); uint32_t invalidOutLen = validOutLen - 1; ASSERT_EQ(CRYPT_EAL_MdUpdate(ctx, input, inLen), CRYPT_EAL_ERR_STATE); ASSERT_EQ(CRYPT_EAL_MdFinal(ctx, out, &validOutLen), CRYPT_EAL_ERR_STATE); ASSERT_EQ(CRYPT_EAL_MdInit(ctx), CRYPT_SUCCESS); ASSERT_EQ(CRYPT_EAL_MdUpdate(NULL, input, inLen), CRYPT_NULL_INPUT); ASSERT_EQ(CRYPT_EAL_MdUpdate(ctx, NULL, inLen), CRYPT_NULL_INPUT); ASSERT_EQ(CRYPT_EAL_MdUpdate(ctx, input, inLen), CRYPT_SUCCESS); ASSERT_EQ(CRYPT_EAL_MdFinal(NULL, out, &validOutLen), CRYPT_NULL_INPUT); ASSERT_EQ(CRYPT_EAL_MdFinal(ctx, NULL, &validOutLen), CRYPT_NULL_INPUT); ASSERT_EQ(CRYPT_EAL_MdFinal(ctx, out, NULL), CRYPT_NULL_INPUT); ASSERT_EQ(CRYPT_EAL_MdFinal(ctx, out, &invalidOutLen), CRYPT_SHA2_OUT_BUFF_LEN_NOT_ENOUGH); ASSERT_EQ(CRYPT_EAL_MdFinal(ctx, out, &validOutLen), CRYPT_SUCCESS); ASSERT_EQ(CRYPT_EAL_MdGetId(ctx), id); ASSERT_EQ(CRYPT_EAL_MdDeinit(ctx), CRYPT_SUCCESS); ASSERT_EQ(CRYPT_EAL_MdIsValidAlgId(id), true); ASSERT_EQ(CRYPT_EAL_MdDeinit(ctx), CRYPT_SUCCESS); ASSERT_EQ(ctx->state, CRYPT_MD_STATE_NEW); EXIT: CRYPT_EAL_MdFreeCtx(ctx); } /* END_CASE */ /** * @test SDV_CRYPT_EAL_MD_SHA2_FUNC_TC001 * @title Split the data and update test. * @precon nan * @brief * 1.Create two ctx and initialize them, expected result 1. * 2.Use ctx1 to update data 100 times, expected result 2. * 3.Use ctx2 to update all data at once, expected result 3. * 4.Compare two outputs, expected result 4. * @expect * 1.Successful. * 2.Successful. * 3.Successful. * 4.The results are the same. */ /* BEGIN_CASE */ void SDV_CRYPT_EAL_MD_SHA2_FUNC_TC001(int id) { if (IsMdAlgDisabled(id)) { SKIP_TEST(); } TestMemInit(); CRYPT_EAL_MdCTX *ctx1 = NULL; CRYPT_EAL_MdCTX *ctx2 = NULL; ctx1 = CRYPT_EAL_MdNewCtx(id); ASSERT_TRUE(ctx1 != NULL); ctx2 = CRYPT_EAL_MdNewCtx(id); ASSERT_TRUE(ctx2 != NULL); // 100! = 5050 uint8_t input[5050]; uint32_t inLenTotal = 0; uint32_t inLenBase; uint8_t out1[SHA2_OUTPUT_MAXSIZE]; uint8_t out2[SHA2_OUTPUT_MAXSIZE]; uint32_t outLen = CRYPT_EAL_MdGetDigestSize(id); ASSERT_EQ(CRYPT_EAL_MdInit(ctx1), CRYPT_SUCCESS); ASSERT_EQ(CRYPT_EAL_MdInit(ctx2), CRYPT_SUCCESS); for (inLenBase = 1; inLenBase <= 100; inLenBase++) { ASSERT_EQ(CRYPT_EAL_MdUpdate(ctx1, input + inLenTotal, inLenBase), CRYPT_SUCCESS); inLenTotal += inLenBase; } ASSERT_EQ(CRYPT_EAL_MdFinal(ctx1, out1, &outLen), CRYPT_SUCCESS); outLen = CRYPT_EAL_MdGetDigestSize(id); ASSERT_EQ(CRYPT_EAL_MdUpdate(ctx2, input, inLenTotal), CRYPT_SUCCESS); ASSERT_EQ(CRYPT_EAL_MdFinal(ctx2, out2, &outLen), CRYPT_SUCCESS); outLen = CRYPT_EAL_MdGetDigestSize(id); ASSERT_COMPARE("sha2", out1, outLen, out2, outLen); EXIT: CRYPT_EAL_MdFreeCtx(ctx1); CRYPT_EAL_MdFreeCtx(ctx2); } /* END_CASE */ /** * @test SDV_CRYPT_EAL_MD_SHA2_FUNC_TC002 * @title Empty string test. * @precon nan * @brief * 1.Create ctx and initialize it, expected result 1. * 2.Call CRYPT_EAL_MdFinal to get the output, expected result 2. * 3.Compare output and vectors, expected result 3. * @expect * 1.Successful. * 2.Successful. * 3.The results are the same. */ /* BEGIN_CASE */ void SDV_CRYPT_EAL_MD_SHA2_FUNC_TC002(int id, Hex *digest) { TestMemInit(); CRYPT_EAL_MdCTX *ctx = NULL; ctx = CRYPT_EAL_MdNewCtx(id); ASSERT_TRUE(ctx != NULL); uint8_t out[SHA2_OUTPUT_MAXSIZE]; uint32_t outLen = CRYPT_EAL_MdGetDigestSize(id); ASSERT_EQ(CRYPT_EAL_MdInit(ctx), CRYPT_SUCCESS); ASSERT_EQ(CRYPT_EAL_MdFinal(ctx, out, &outLen), CRYPT_SUCCESS); ASSERT_COMPARE("sha2", out, outLen, digest->x, digest->len); EXIT: CRYPT_EAL_MdFreeCtx(ctx); } /* END_CASE */ /** * @test SDV_CRYPT_EAL_MD_SHA2_FUNC_TC003 * @title standard vector test. * @precon nan * @brief * 1.Calculate the hash of the data and compare it with the standard vector, expected result 1. * 2.Call CRYPT_EAL_Md to calculate the hash of the data and compare it with the standard vector, expected result 2. * @expect * 1.The results are the same. * 2.The results are the same. */ /* BEGIN_CASE */ void SDV_CRYPT_EAL_MD_SHA2_FUNC_TC003(int algId, Hex *in, Hex *digest) { if (IsMdAlgDisabled(algId)) { SKIP_TEST(); } TestMemInit(); CRYPT_EAL_MdCTX *ctx = NULL; uint8_t out[SHA2_OUTPUT_MAXSIZE]; uint32_t outLen = CRYPT_EAL_MdGetDigestSize(algId); ctx = CRYPT_EAL_MdNewCtx(algId); ASSERT_TRUE(ctx != NULL); ASSERT_EQ(CRYPT_EAL_MdInit(ctx), CRYPT_SUCCESS); ASSERT_EQ(CRYPT_EAL_MdUpdate(ctx, in->x, in->len), CRYPT_SUCCESS); ASSERT_EQ(CRYPT_EAL_MdFinal(ctx, out, &outLen), CRYPT_SUCCESS); ASSERT_COMPARE("sha2", out, outLen, digest->x, digest->len); ASSERT_EQ(CRYPT_EAL_Md(algId, in->x, in->len, out, &outLen), CRYPT_SUCCESS); ASSERT_COMPARE("sha2", out, outLen, digest->x, digest->len); EXIT: CRYPT_EAL_MdFreeCtx(ctx); } /* END_CASE */ /** * @test SDV_CRYPT_EAL_MD_SHA2_FUNC_TC004 * @title Hash calculation for multiple updates,comparison with standard results. * @precon nan * @brief * 1.Call CRYPT_EAL_MdNewCtx to create a ctx and initialize, expected result 1. * 2.Call CRYPT_EAL_MdUpdate to calculate the hash of a data segmentxpected result 2. * 3.Call CRYPT_EAL_MdUpdate to calculate the next data segmentxpected result 3. * 4.Call CRYPT_EAL_MdUpdate to calculate the next data segmentxpected result 4. * 5.Call CRYPT_EAL_MdFinal get the result, expected result 5. * @expect * 1.Successful * 2.Successful * 3.Successful * 4.Successful * 5.The results are as expected. */ /* BEGIN_CASE */ void SDV_CRYPT_EAL_MD_SHA2_FUNC_TC004(int algId, Hex *plain_text1, Hex *plain_text2, Hex *plain_text3, Hex *hash) { // 100 is greater than the digest length of all SHA algorithms. unsigned char output[SHA2_OUTPUT_MAXSIZE]; uint32_t outLen = SHA2_OUTPUT_MAXSIZE; TestMemInit(); CRYPT_EAL_MdCTX *ctx = CRYPT_EAL_MdNewCtx(algId); ASSERT_TRUE(ctx != NULL); ASSERT_EQ(CRYPT_EAL_MdInit(ctx), CRYPT_SUCCESS); ASSERT_EQ(CRYPT_EAL_MdUpdate(ctx, plain_text1->x, plain_text1->len), CRYPT_SUCCESS); ASSERT_EQ(CRYPT_EAL_MdUpdate(ctx, plain_text2->x, plain_text2->len), CRYPT_SUCCESS); ASSERT_EQ(CRYPT_EAL_MdUpdate(ctx, plain_text3->x, plain_text3->len), CRYPT_SUCCESS); ASSERT_EQ(CRYPT_EAL_MdFinal(ctx, output, &outLen), CRYPT_SUCCESS); ASSERT_COMPARE("sha2", output, outLen, hash->x, hash->len); EXIT: CRYPT_EAL_MdFreeCtx(ctx); } /* END_CASE */ /** * @test SDV_CRYPT_EAL_MD_SHA2_FUNC_TC005 * @title Test multi-thread hash calculation. * @precon nan * @brief * 1.Create two threads and calculate the hash, expected result 1. * 2.Compare the result to the expected value, expected result 2. * @expect * 1.Hash calculation succeeded. * 2.The results are as expected. */ /* BEGIN_CASE */ void SDV_CRYPT_EAL_MD_SHA2_FUNC_TC005(int algId, Hex *data, Hex *hash) { int ret; TestMemInit(); const uint32_t threadNum = 2; pthread_t thrd[2]; ThreadParameter arg[2] = { {data->x, hash->x, data->len, hash->len, algId}, {data->x, hash->x, data->len, hash->len, algId} }; for (uint32_t i = 0; i < threadNum; i++) { ret = pthread_create(&thrd[i], NULL, (void *)Sha2MultiThreadTest, &arg[i]); ASSERT_EQ(ret, 0); } for (uint32_t i = 0; i < threadNum; i++) { pthread_join(thrd[i], NULL); } EXIT: return; } /* END_CASE */ /** * @test SDV_CRYPTO_SHA2_COPY_CTX_FUNC_TC001 * @title SHA2 copy ctx function test. * @precon nan * @brief * 1. Create the context ctx of md algorithm, expected result 1 * 2. Call to CRYPT_EAL_MdCopyCtx method to copy ctx, expected result 2 * 2. Call to CRYPT_EAL_MdCopyCtx method to copy a null ctx, expected result 3 * 3. Calculate the hash of msg, and compare the calculated result with hash vector, expected result 4 * 4. Call to CRYPT_EAL_MdDupCtx method to copy ctx, expected result 5 * 3. Calculate the hash of msg, and compare the calculated result with hash vector, expected result 6 * @expect * 1. Success, the context is not null. * 2. CRYPT_SUCCESS * 3. CRYPT_NULL_INPUT * 4. Success, the context is not null. * 5. CRYPT_SUCCESS * 6. Success, the hashs are the same. */ /* BEGIN_CASE */ void SDV_CRYPTO_SHA2_COPY_CTX_FUNC_TC001(int id, Hex *msg, Hex *hash) { if (IsMdAlgDisabled(id)) { SKIP_TEST(); } TestMemInit(); CRYPT_EAL_MdCTX *cpyCtx = NULL; CRYPT_EAL_MdCTX *dupCtx = NULL; CRYPT_EAL_MdCTX *ctx = CRYPT_EAL_MdNewCtx(id); ASSERT_TRUE(ctx != NULL); uint8_t output[SHA2_OUTPUT_MAXSIZE]; uint32_t outLen = SHA2_OUTPUT_MAXSIZE; dupCtx=CRYPT_EAL_MdDupCtx(cpyCtx); ASSERT_TRUE(dupCtx == NULL); ASSERT_EQ(CRYPT_MD_MAX, CRYPT_EAL_MdGetId(dupCtx)); ASSERT_EQ(CRYPT_EAL_MdCopyCtx(cpyCtx, ctx), CRYPT_NULL_INPUT); cpyCtx = CRYPT_EAL_MdNewCtx(id); ASSERT_TRUE(cpyCtx != NULL); ASSERT_TRUE(dupCtx == NULL); ASSERT_EQ(CRYPT_EAL_MdCopyCtx(cpyCtx, dupCtx), CRYPT_NULL_INPUT); ASSERT_EQ(CRYPT_EAL_MdCopyCtx(cpyCtx, ctx), CRYPT_SUCCESS); ASSERT_EQ(CRYPT_EAL_MdInit(cpyCtx), CRYPT_SUCCESS); ASSERT_EQ(CRYPT_EAL_MdUpdate(cpyCtx, msg->x, msg->len), CRYPT_SUCCESS); ASSERT_EQ(CRYPT_EAL_MdFinal(cpyCtx, output, &outLen), CRYPT_SUCCESS); ASSERT_EQ(id, cpyCtx->id); ASSERT_EQ(memcmp(output, hash->x, hash->len), 0); dupCtx=CRYPT_EAL_MdDupCtx(ctx); ASSERT_TRUE(dupCtx != NULL); ASSERT_EQ(CRYPT_EAL_MdInit(dupCtx), CRYPT_SUCCESS); ASSERT_EQ(CRYPT_EAL_MdUpdate(dupCtx, msg->x, msg->len), CRYPT_SUCCESS); ASSERT_EQ(CRYPT_EAL_MdFinal(dupCtx, output, &outLen), CRYPT_SUCCESS); ASSERT_EQ(id, CRYPT_EAL_MdGetId(dupCtx)); ASSERT_EQ(memcmp(output, hash->x, hash->len), 0); EXIT: CRYPT_EAL_MdFreeCtx(ctx); CRYPT_EAL_MdFreeCtx(cpyCtx); CRYPT_EAL_MdFreeCtx(dupCtx); } /* END_CASE */ /** * @test SDV_CRYPTO_SHA2_DEFAULT_PROVIDER_FUNC_TC001 * @title Default provider testing * @precon nan * @brief * Load the default provider and use the test vector to test its correctness */ /* BEGIN_CASE */ void SDV_CRYPTO_SHA2_DEFAULT_PROVIDER_FUNC_TC001(int id, Hex *msg, Hex *hash) { TestMemInit(); CRYPT_EAL_MdCTX *ctx = NULL; #ifdef HITLS_CRYPTO_PROVIDER ctx = CRYPT_EAL_ProviderMdNewCtx(NULL, id, "provider=default"); #else ctx = CRYPT_EAL_MdNewCtx(id); #endif ASSERT_TRUE(ctx != NULL); uint8_t output[SHA2_OUTPUT_MAXSIZE]; uint32_t outLen = SHA2_OUTPUT_MAXSIZE; ASSERT_EQ(CRYPT_EAL_MdInit(ctx), CRYPT_SUCCESS); ASSERT_EQ(CRYPT_EAL_MdUpdate(ctx, msg->x, msg->len), CRYPT_SUCCESS); ASSERT_EQ(CRYPT_EAL_MdFinal(ctx, output, &outLen), CRYPT_SUCCESS); ASSERT_EQ(memcmp(output, hash->x, hash->len), 0); EXIT: CRYPT_EAL_MdFreeCtx(ctx); } /* END_CASE */
2301_79861745/bench_create
testcode/sdv/testcase/crypto/sha2/test_suite_sdv_eal_md_sha2.c
C
unknown
15,895
/* * This file is part of the openHiTLS project. * * openHiTLS is licensed under the Mulan PSL v2. * You can use this software according to the terms and conditions of the Mulan PSL v2. * You may obtain a copy of Mulan PSL v2 at: * * http://license.coscl.org.cn/MulanPSL2 * * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. * See the Mulan PSL v2 for more details. */ /* BEGIN_HEADER */ #include <pthread.h> #include "crypt_eal_md.h" #include "bsl_sal.h" #include "eal_md_local.h" #include "crypt_algid.h" #include "crypt_errno.h" #include "crypt_sha3.h" #include "securec.h" /* END_HEADER */ // 100 is greater than the digest length of all SHA algorithms. #define SHA3_OUTPUT_MAXSIZE 100 typedef struct { uint8_t *data; uint8_t *hash; uint32_t dataLen; uint32_t hashLen; CRYPT_MD_AlgId id; } ThreadParameter; void Sha3MultiThreadTest(void *arg) { ThreadParameter *threadParameter = (ThreadParameter *)arg; uint32_t outLen = SHA3_OUTPUT_MAXSIZE; uint8_t out[SHA3_OUTPUT_MAXSIZE]; CRYPT_EAL_MdCTX *ctx = NULL; ctx = CRYPT_EAL_MdNewCtx(threadParameter->id); ASSERT_TRUE(ctx != NULL); for (uint32_t i = 0; i < 10; i++) { ASSERT_TRUE(CRYPT_EAL_MdInit(ctx) == CRYPT_SUCCESS); ASSERT_TRUE(CRYPT_EAL_MdUpdate(ctx, threadParameter->data, threadParameter->dataLen) == CRYPT_SUCCESS); ASSERT_TRUE(CRYPT_EAL_MdFinal(ctx, out, &outLen) == CRYPT_SUCCESS); ASSERT_COMPARE("hash result cmp", out, outLen, threadParameter->hash, threadParameter->hashLen); } EXIT: CRYPT_EAL_MdFreeCtx(ctx); } /** * @test SDV_CRYPT_EAL_SHA3_API_TC001 * @title SHA3 get the digest length test. * @precon nan * @brief * Call CRYPT_EAL_MdGetDigestSize to get the digest length. * @expect * The results are correct. * */ /* BEGIN_CASE */ void SDV_CRYPT_EAL_SHA3_API_TC001(void) { // The length of the SHA3_224 digest is 28. ASSERT_EQ(CRYPT_EAL_MdGetDigestSize(CRYPT_MD_SHA3_224), 28); // The length of the SHA3_256 digest is 32. ASSERT_EQ(CRYPT_EAL_MdGetDigestSize(CRYPT_MD_SHA3_256), 32); // The length of the SHA3_384 digest is 48. ASSERT_EQ(CRYPT_EAL_MdGetDigestSize(CRYPT_MD_SHA3_384), 48); // The length of the SHA3_512 digest is 64. ASSERT_EQ(CRYPT_EAL_MdGetDigestSize(CRYPT_MD_SHA3_512), 64); // The length of the SHAKE128 digest is 0. ASSERT_EQ(CRYPT_EAL_MdGetDigestSize(CRYPT_MD_SHAKE128), 0); // The length of the SHAKE256 digest is 0. ASSERT_EQ(CRYPT_EAL_MdGetDigestSize(CRYPT_MD_SHAKE256), 0); EXIT: return; } /* END_CASE */ /** * @test SDV_CRYPT_EAL_SHA3_API_TC002 * @title update and final test. * @precon nan * @brief * 1.Call CRYPT_EAL_MdDeinit the null CTX, expected result 1. * 2.Call CRYPT_EAL_MdNewCtx create the CTX, expected result 2. * 3.Call CRYPT_EAL_MdUpdate and CRYPT_EAL_MdFinal before initialization, expected result 3. * 4.Call CRYPT_EAL_MdUpdate and CRYPT_EAL_MdFinal use null pointer, expected result 4. * 5.Call CRYPT_EAL_MdUpdate and CRYPT_EAL_MdFinal normally, expected result 5. * 6.Call CRYPT_EAL_MdDeinit the CTX, expected result 6. * @expect * 1.Return CRYPT_NULL_INPUT * 2.Create successful. * 3.Return CRYPT_EAL_ERR_STATE. * 4.Return CRYPT_NULL_INPUT. * 5.Successful. * 6.Return CRYPT_SUCCESS */ /* BEGIN_CASE */ void SDV_CRYPT_EAL_SHA3_API_TC002(int algId) { TestMemInit(); CRYPT_EAL_MdCTX *sha3Ctx = NULL; ASSERT_EQ(CRYPT_EAL_MdDeinit(sha3Ctx), CRYPT_NULL_INPUT); uint8_t data[10] = {0x0e}; uint32_t dataLen = 1; uint8_t output[SHA3_OUTPUT_MAXSIZE]; uint32_t outLen = SHA3_OUTPUT_MAXSIZE; sha3Ctx = CRYPT_EAL_MdNewCtx(algId); ASSERT_TRUE(sha3Ctx != NULL); ASSERT_EQ(CRYPT_EAL_MdUpdate(sha3Ctx, data, dataLen), CRYPT_EAL_ERR_STATE); ASSERT_EQ(CRYPT_EAL_MdFinal(sha3Ctx, output, &outLen), CRYPT_EAL_ERR_STATE); ASSERT_EQ(CRYPT_EAL_MdInit(sha3Ctx), CRYPT_SUCCESS); ASSERT_EQ(CRYPT_EAL_MdUpdate(NULL, data, dataLen), CRYPT_NULL_INPUT); ASSERT_EQ(CRYPT_EAL_MdUpdate(sha3Ctx, NULL, dataLen), CRYPT_NULL_INPUT); ASSERT_EQ(CRYPT_EAL_MdUpdate(sha3Ctx, data, dataLen), CRYPT_SUCCESS); ASSERT_EQ(CRYPT_EAL_MdFinal(NULL, output, &outLen), CRYPT_NULL_INPUT); ASSERT_EQ(CRYPT_EAL_MdFinal(sha3Ctx, NULL, &outLen), CRYPT_NULL_INPUT); ASSERT_EQ(CRYPT_EAL_MdFinal(sha3Ctx, output, NULL), CRYPT_NULL_INPUT); outLen = CRYPT_EAL_MdGetDigestSize(algId) - 1; ASSERT_EQ(CRYPT_EAL_MdFinal(sha3Ctx, output, &outLen), CRYPT_SHA3_OUT_BUFF_LEN_NOT_ENOUGH); outLen = CRYPT_EAL_MdGetDigestSize(algId); ASSERT_EQ(CRYPT_EAL_MdFinal(sha3Ctx, output, &outLen), CRYPT_SUCCESS); ASSERT_EQ(CRYPT_EAL_MdGetId(sha3Ctx), algId); ASSERT_EQ(CRYPT_EAL_MdDeinit(sha3Ctx), CRYPT_SUCCESS); EXIT: CRYPT_EAL_MdFreeCtx(sha3Ctx); } /* END_CASE */ /** * @test SDV_CRYPT_EAL_SHA3_FUNC_TC001 * @title Split the data and update test. * @precon nan * @brief * 1.Create two ctx and initialize them, expected result 1. * 2.Use ctx1 to update data 100 times, expected result 2. * 3.Use ctx2 to update all data at once, expected result 3. * 4.Compare two outputs, expected result 4. * @expect * 1.Successful. * 2.Successful. * 3.Successful. * 4.The results are the same. */ /* BEGIN_CASE */ void SDV_CRYPT_EAL_SHA3_FUNC_TC001(int algId) { TestMemInit(); CRYPT_EAL_MdCTX *ctx1 = NULL; CRYPT_EAL_MdCTX *ctx2 = NULL; ctx1 = CRYPT_EAL_MdNewCtx(algId); ASSERT_TRUE(ctx1 != NULL); ctx2 = CRYPT_EAL_MdNewCtx(algId); ASSERT_TRUE(ctx2 != NULL); // 100! = 5050 uint8_t input[5050]; uint32_t inLenTotal = 0; uint32_t inLenBase; uint8_t out1[SHA3_OUTPUT_MAXSIZE]; // 100 is greater than the digest length of all SHA algorithms. uint8_t out2[SHA3_OUTPUT_MAXSIZE]; uint32_t outLen = CRYPT_EAL_MdGetDigestSize(algId); ASSERT_EQ(CRYPT_EAL_MdInit(ctx1), CRYPT_SUCCESS); ASSERT_EQ(CRYPT_EAL_MdInit(ctx2), CRYPT_SUCCESS); // update 100 times. for (inLenBase = 1; inLenBase <= 100; inLenBase++) { ASSERT_EQ(CRYPT_EAL_MdUpdate(ctx1, input + inLenTotal, inLenBase), CRYPT_SUCCESS); inLenTotal += inLenBase; } ASSERT_EQ(CRYPT_EAL_MdFinal(ctx1, out1, &outLen), CRYPT_SUCCESS); outLen = CRYPT_EAL_MdGetDigestSize(algId); ASSERT_EQ(CRYPT_EAL_MdUpdate(ctx2, input, inLenTotal), CRYPT_SUCCESS); ASSERT_EQ(CRYPT_EAL_MdFinal(ctx2, out2, &outLen), CRYPT_SUCCESS); outLen = CRYPT_EAL_MdGetDigestSize(algId); ASSERT_EQ(memcmp(out1, out2, outLen), 0); EXIT: CRYPT_EAL_MdFreeCtx(ctx1); CRYPT_EAL_MdFreeCtx(ctx2); } /* END_CASE */ /** * @test SDV_CRYPT_EAL_SHA3_FUNC_TC002 * @title Test multi-thread hash calculation. * @precon nan * @brief * 1.Create two threads and calculate the hash, expected result 1. * 2.Compare the result to the expected value, expected result 2. * @expect * 1.Hash calculation succeeded. * 2.The results are as expected. */ /* BEGIN_CASE */ void SDV_CRYPT_EAL_SHA3_FUNC_TC002(int algId, Hex *data, Hex *hash) { int ret; TestMemInit(); const uint32_t threadNum = 2; pthread_t thrd[2]; ThreadParameter arg[2] = { {data->x, hash->x, data->len, hash->len, algId}, {data->x, hash->x, data->len, hash->len, algId} }; for (uint32_t i = 0; i < threadNum; i++) { ret = pthread_create(&thrd[i], NULL, (void *)Sha3MultiThreadTest, &arg[i]); ASSERT_TRUE(ret == 0); } for (uint32_t i = 0; i < threadNum; i++) { pthread_join(thrd[i], NULL); } EXIT: return; } /* END_CASE */ /** * @test SDV_CRYPT_EAL_SHA3_FUNC_TC003 * @title Standard vector test. * @precon nan * @brief * 1.Calculate the hash of the data and compare it with the standard vector, expected result 1. * 2.Call CRYPT_EAL_Md to calculate the hash value, expected result 2. * @expect * 1.The results are the same. * 2.The results are the same. */ /* BEGIN_CASE */ void SDV_CRYPT_EAL_SHA3_FUNC_TC003(int algId, Hex *in, Hex *digest) { TestMemInit(); CRYPT_EAL_MdCTX *ctx = NULL; uint8_t out[SHA3_OUTPUT_MAXSIZE]; uint32_t outLen = SHA3_OUTPUT_MAXSIZE; ctx = CRYPT_EAL_MdNewCtx(algId); ASSERT_TRUE(ctx != NULL); ASSERT_EQ(CRYPT_EAL_MdInit(ctx), CRYPT_SUCCESS); ASSERT_EQ(CRYPT_EAL_MdUpdate(ctx, in->x, in->len), CRYPT_SUCCESS); ASSERT_EQ(CRYPT_EAL_MdFinal(ctx, out, &outLen), CRYPT_SUCCESS); ASSERT_EQ(outLen, digest->len); ASSERT_EQ(memcmp(out, digest->x, digest->len), 0); ASSERT_EQ(CRYPT_EAL_Md(algId, in->x, in->len, out, &outLen), CRYPT_SUCCESS); ASSERT_EQ(memcmp(out, digest->x, digest->len), 0); EXIT: CRYPT_EAL_MdFreeCtx(ctx); } /* END_CASE */ /** * @test SDV_CRYPT_EAL_SHA3_FUNC_TC004 * @title Standard vector test of the SHAKE algorithm. * @precon nan * @brief * Calculate the hash of the data and compare it with the standard vector. * @expect * The results are the same. */ /* BEGIN_CASE */ void SDV_CRYPT_EAL_SHA3_FUNC_TC004(int algId, Hex *in, Hex *digest) { TestMemInit(); CRYPT_EAL_MdCTX *ctx = NULL; uint8_t out[SHA3_OUTPUT_MAXSIZE]; uint32_t outLen = SHA3_OUTPUT_MAXSIZE; ctx = CRYPT_EAL_MdNewCtx(algId); ASSERT_TRUE(ctx != NULL); ASSERT_EQ(CRYPT_EAL_MdInit(ctx), CRYPT_SUCCESS); ASSERT_EQ(CRYPT_EAL_MdUpdate(ctx, in->x, in->len), CRYPT_SUCCESS); ASSERT_EQ(CRYPT_EAL_MdFinal(ctx, out, &outLen), CRYPT_SUCCESS); ASSERT_EQ(memcmp(out, digest->x, digest->len), 0); EXIT: CRYPT_EAL_MdFreeCtx(ctx); } /* END_CASE */ /** * @test SDV_CRYPT_EAL_SHA3_FUNC_TC005 * @title Standard vector test of the SHAKE algorithm. * @precon nan * @brief * Calculate the hash of the data and compare it with the standard vector. * @expect * The results are the same. */ /* BEGIN_CASE */ void SDV_CRYPT_EAL_SHA3_FUNC_TC005(int algId, Hex *in, Hex *digest, int isProvider) { TestMemInit(); CRYPT_EAL_MdCTX *ctx = NULL; uint8_t out[SHA3_OUTPUT_MAXSIZE]; uint32_t outLen = SHA3_OUTPUT_MAXSIZE; #ifdef HITLS_CRYPTO_PROVIDER if (isProvider) { ctx = CRYPT_EAL_ProviderMdNewCtx(NULL, algId, "provider=default"); } else #endif { (void)isProvider; ctx = CRYPT_EAL_MdNewCtx(algId); } ASSERT_TRUE(ctx != NULL); ASSERT_EQ(CRYPT_EAL_MdInit(ctx), CRYPT_SUCCESS); ASSERT_EQ(CRYPT_EAL_MdUpdate(ctx, in->x, in->len), CRYPT_SUCCESS); ASSERT_EQ(CRYPT_EAL_MdSqueeze(ctx, out, outLen), CRYPT_SUCCESS); ASSERT_EQ(memcmp(out, digest->x, digest->len), 0); EXIT: CRYPT_EAL_MdFreeCtx(ctx); } /* END_CASE */ /** * @test SDV_CRYPT_EAL_SHA3_FUNC_TC006 * @title Standard vector test of the SHAKE algorithm. * @precon nan * @brief * Calculate the hash of the data and compare it with the standard vector. * @expect * The results are the same. */ /* BEGIN_CASE */ void SDV_CRYPT_EAL_SHA3_FUNC_TC006(int algId, Hex *in, int outLen, Hex *digest, int isProvider) { TestMemInit(); CRYPT_EAL_MdCTX *ctx = NULL; int32_t squeezeLen = digest->len / 3; uint8_t *out = malloc(outLen); ASSERT_TRUE(out != NULL); #ifdef HITLS_CRYPTO_PROVIDER if (isProvider) { ctx = CRYPT_EAL_ProviderMdNewCtx(NULL, algId, "provider=default"); } else #endif { (void)isProvider; ctx = CRYPT_EAL_MdNewCtx(algId); } ASSERT_TRUE(ctx != NULL); ASSERT_EQ(CRYPT_EAL_MdInit(ctx), CRYPT_SUCCESS); ASSERT_EQ(CRYPT_EAL_MdUpdate(ctx, in->x, in->len), CRYPT_SUCCESS); ASSERT_EQ(CRYPT_EAL_MdSqueeze(ctx, out, squeezeLen), CRYPT_SUCCESS); ASSERT_EQ(CRYPT_EAL_MdSqueeze(ctx, out + squeezeLen, squeezeLen), CRYPT_SUCCESS); ASSERT_EQ(CRYPT_EAL_MdSqueeze(ctx, out + squeezeLen * 2, squeezeLen), CRYPT_SUCCESS); ASSERT_EQ(CRYPT_EAL_MdSqueeze(ctx, out + squeezeLen * 3, outLen - squeezeLen * 3), CRYPT_SUCCESS); ASSERT_EQ(memcmp(out, digest->x, digest->len), 0); EXIT: free(out); CRYPT_EAL_MdFreeCtx(ctx); } /* END_CASE */ /** * @test SDV_CRYPTO_SHA3_COPY_CTX_FUNC_TC001 * @title SHA3 copy ctx function test. * @precon nan * @brief * 1. Create the context ctx of md algorithm, expected result 1 * 2. Call to CRYPT_EAL_MdCopyCtx method to copy ctx, expected result 2 * 2. Call to CRYPT_EAL_MdCopyCtx method to copy a null ctx, expected result 3 * 3. Calculate the hash of msg, and compare the calculated result with hash vector, expected result 4 * 4. Call to CRYPT_EAL_MdDupCtx method to copy ctx, expected result 5 * 3. Calculate the hash of msg, and compare the calculated result with hash vector, expected result 6 * @expect * 1. Success, the context is not null. * 2. CRYPT_SUCCESS * 3. CRYPT_NULL_INPUT * 4. Success, the context is not null. * 5. CRYPT_SUCCESS * 6. Success, the hashs are the same. */ /* BEGIN_CASE */ void SDV_CRYPTO_SHA3_COPY_CTX_FUNC_TC001(int id, Hex *msg, Hex *hash) { TestMemInit(); CRYPT_EAL_MdCTX *cpyCtx = NULL; CRYPT_EAL_MdCTX *dupCtx = NULL; CRYPT_EAL_MdCTX *ctx = CRYPT_EAL_MdNewCtx(id); ASSERT_TRUE(ctx != NULL); uint8_t output[SHA3_OUTPUT_MAXSIZE]; uint32_t outLen = SHA3_OUTPUT_MAXSIZE; dupCtx=CRYPT_EAL_MdDupCtx(cpyCtx); ASSERT_TRUE(dupCtx == NULL); ASSERT_EQ(CRYPT_MD_MAX, CRYPT_EAL_MdGetId(dupCtx)); cpyCtx = CRYPT_EAL_MdNewCtx(id); ASSERT_TRUE(cpyCtx != NULL); ASSERT_TRUE(dupCtx == NULL); ASSERT_EQ(CRYPT_EAL_MdCopyCtx(cpyCtx, dupCtx), CRYPT_NULL_INPUT); ASSERT_EQ(CRYPT_EAL_MdCopyCtx(cpyCtx, ctx), CRYPT_SUCCESS); ASSERT_EQ(CRYPT_EAL_MdInit(cpyCtx), CRYPT_SUCCESS); ASSERT_EQ(CRYPT_EAL_MdUpdate(cpyCtx, msg->x, msg->len), CRYPT_SUCCESS); ASSERT_EQ(CRYPT_EAL_MdFinal(cpyCtx, output, &outLen), CRYPT_SUCCESS); ASSERT_EQ(id, cpyCtx->id); if (ctx->id != CRYPT_MD_SHAKE128 && ctx->id != CRYPT_MD_SHAKE256) { ASSERT_TRUE(outLen == hash->len); } ASSERT_EQ(memcmp(output, hash->x, hash->len), 0); dupCtx=CRYPT_EAL_MdDupCtx(ctx); ASSERT_TRUE(dupCtx != NULL); ASSERT_EQ(CRYPT_EAL_MdInit(dupCtx), CRYPT_SUCCESS); ASSERT_EQ(CRYPT_EAL_MdUpdate(dupCtx, msg->x, msg->len), CRYPT_SUCCESS); ASSERT_EQ(CRYPT_EAL_MdFinal(dupCtx, output, &outLen), CRYPT_SUCCESS); ASSERT_EQ(id, CRYPT_EAL_MdGetId(dupCtx)); ASSERT_EQ(memcmp(output, hash->x, hash->len), 0); EXIT: CRYPT_EAL_MdFreeCtx(ctx); CRYPT_EAL_MdFreeCtx(cpyCtx); CRYPT_EAL_MdFreeCtx(dupCtx); } /* END_CASE */ /** * @test SDV_CRYPTO_SHA3_DEFAULT_PROVIDER_FUNC_TC001 * @title Default provider testing * @precon nan * @brief * Load the default provider and use the test vector to test its correctness */ /* BEGIN_CASE */ void SDV_CRYPTO_SHA3_DEFAULT_PROVIDER_FUNC_TC001(int id, Hex *msg, Hex *hash) { TestMemInit(); CRYPT_EAL_MdCTX *ctx = NULL; #ifdef HITLS_CRYPTO_PROVIDER ctx = CRYPT_EAL_ProviderMdNewCtx(NULL, id, "provider=default"); #else ctx = CRYPT_EAL_MdNewCtx(id); #endif ASSERT_TRUE(ctx != NULL); uint8_t output[SHA3_OUTPUT_MAXSIZE]; uint32_t outLen = SHA3_OUTPUT_MAXSIZE; ASSERT_EQ(CRYPT_EAL_MdInit(ctx), CRYPT_SUCCESS); ASSERT_EQ(CRYPT_EAL_MdUpdate(ctx, msg->x, msg->len), CRYPT_SUCCESS); ASSERT_EQ(CRYPT_EAL_MdFinal(ctx, output, &outLen), CRYPT_SUCCESS); ASSERT_EQ(memcmp(output, hash->x, hash->len), 0); EXIT: CRYPT_EAL_MdFreeCtx(ctx); } /* END_CASE */ /** * @test SDV_CRYPT_EAL_SHA3_FUNC_TC007 * @title Standard vector test of the SHAKE algorithm. * @precon nan * @brief * Calculate the hash of the data and compare it with the standard vector. * @expect * The results are the same. */ /* BEGIN_CASE */ void SDV_CRYPT_EAL_SHA3_FUNC_TC007(int algId, int outLen, Hex *in, Hex *digest) { TestMemInit(); CRYPT_EAL_MdCTX *ctx = NULL; int32_t squeezeLen = 130; uint32_t tmpLen = outLen; uint8_t *out1 = malloc(outLen); uint8_t *out2 = malloc(outLen); ASSERT_TRUE(out1 != NULL && out2 != NULL); ctx = CRYPT_EAL_MdNewCtx(algId); ASSERT_TRUE(ctx != NULL); ASSERT_EQ(CRYPT_EAL_MdInit(ctx), CRYPT_SUCCESS); ASSERT_EQ(CRYPT_EAL_MdUpdate(ctx, in->x, in->len), CRYPT_SUCCESS); ASSERT_EQ(CRYPT_EAL_MdSqueeze(ctx, out1, squeezeLen), CRYPT_SUCCESS); ASSERT_EQ(CRYPT_EAL_MdSqueeze(ctx, out1 + squeezeLen, outLen - squeezeLen), CRYPT_SUCCESS); CRYPT_EAL_MdFreeCtx(ctx); ctx = CRYPT_EAL_MdNewCtx(algId); ASSERT_TRUE(ctx != NULL); ASSERT_EQ(CRYPT_EAL_MdInit(ctx), CRYPT_SUCCESS); ASSERT_EQ(CRYPT_EAL_MdUpdate(ctx, in->x, in->len), CRYPT_SUCCESS); ASSERT_EQ(CRYPT_EAL_MdFinal(ctx, out2, &tmpLen), CRYPT_SUCCESS); ASSERT_EQ(memcmp(out1, out2, outLen), 0); ASSERT_EQ(memcmp(out1, digest->x, digest->len), 0); EXIT: free(out1); free(out2); CRYPT_EAL_MdFreeCtx(ctx); } /* END_CASE */
2301_79861745/bench_create
testcode/sdv/testcase/crypto/sha3/test_suite_sdv_eal_md_sha3.c
C
unknown
16,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 "eal_mac_local.h" #include <limits.h> #include <pthread.h> #include "crypt_siphash.h" #include "securec.h" #include "crypt_eal_mac.h" #include "crypt_errno.h" #include "bsl_sal.h" #define DATA_MAX_LEN (65538) // siphash_update(key, data), data update len < DATA_MAX_LEN 2^16 = 65536 /* END_HEADER */ /* @ * @test SDV_CRYPT_EAL_SIPHASH_API_TC001 * @spec - * @title Impact of the algorithm ID on the new interface_valid algorithm ID and invalid algorithm ID * @precon nan * @brief 1. Invoke the new interface with the input parameter CRYPT_MAC_SIPHASH_SHA1. Expected result 1 is obtained. 2. Invoke the new interface with the input parameter CRYPT_MAC_SIPHASH64. Expected result 2 is obtained. 3. Invoke the new interface with the input parameter CRYPT_MAC_SIPHASH128. Expected result 3 is obtained. 4. Invoke the new interface with the input parameter CRYPT_MAC_MAX. Expected result 7 is obtained. * @expect 1. If the operation is successful, the CRYPT_EAL_MacCtx pointer is returned. 2. If the operation is successful, the CRYPT_EAL_MacCtx pointer is returned. 3. If the operation is successful, the CRYPT_EAL_MacCtx pointer is returned. 4. If the operation fails, NULL is returned. * @prior Level 1 * @auto TRUE @ */ /* BEGIN_CASE */ void SDV_CRYPT_EAL_SIPHASH_API_TC001(void) { TestMemInit(); CRYPT_EAL_MacCtx *ctx = CRYPT_EAL_MacNewCtx(CRYPT_MAC_SIPHASH64); ASSERT_TRUE(ctx != NULL); CRYPT_EAL_MacFreeCtx(ctx); ctx = CRYPT_EAL_MacNewCtx(CRYPT_MAC_SIPHASH128); ASSERT_TRUE(ctx != NULL); EXIT: CRYPT_EAL_MacFreeCtx(ctx); } /* END_CASE */ /* @ * @test SDV_CRYPT_EAL_SIPHASH_API_TC002 * @spec - * @title Impact of Input Parameters on the Init Interface (Valid and Invalid Input Parameters) * @precon nan * @brief 1. Invoke the new interface. Expected result 1 is obtained. 2. Invoke the init interface and set ctx to NULL. Expected result 2 is obtained. 3. Invoke the init interface with key set to NULL and len set to a value other than 0. Expected result 3 is obtained. 4. Invoke the init interface with key set to NULL and len set to 0. Expected result 4 is obtained. 5. Invoke the init interface. The key is not NULL and the len is 0. Expected result 5 is obtained. 6. Invoke the init interface and ensure that the input parameters are normal. Expected result 6 is obtained. * @expect 1. If the new operation is successful, the CRYPT_EAL_MacCtx pointer is returned. 2. If the init operation fails, CRYPT_NULL_INPUT is returned. 3. If the init operation fails, CRYPT_NULL_INPUT is returned. 4. If the init operation fails, CRYPT_INVALID_ARG is returned. 5. If the init operation fails, CRYPT_INVALID_ARG is returned. 6. If the init operation is successful, CRYPT_SUCCESS is returned. * @prior Level 1 * @auto TRUE @ */ /* BEGIN_CASE */ void SDV_CRYPT_EAL_SIPHASH_API_TC002(int algId) { TestMemInit(); uint8_t key[SIPHASH_KEY_SIZE]; CRYPT_EAL_MacCtx *ctx = CRYPT_EAL_MacNewCtx(algId); ASSERT_TRUE(ctx != NULL); ASSERT_TRUE(CRYPT_EAL_MacInit(NULL, key, SIPHASH_KEY_SIZE) == CRYPT_NULL_INPUT); ASSERT_TRUE(CRYPT_EAL_MacInit(ctx, NULL, SIPHASH_KEY_SIZE) == CRYPT_NULL_INPUT); ASSERT_TRUE(CRYPT_EAL_MacInit(ctx, NULL, 0) == CRYPT_NULL_INPUT); ASSERT_TRUE(CRYPT_EAL_MacInit(ctx, key, 0) == CRYPT_INVALID_ARG); ASSERT_TRUE(CRYPT_EAL_MacInit(ctx, key, SIPHASH_KEY_SIZE) == CRYPT_SUCCESS); EXIT: CRYPT_EAL_MacFreeCtx(ctx); } /* END_CASE */ /* @ * @test SDV_CRYPT_EAL_SIPHASH_API_TC003 * @spec - * @title Impact of the ctx status on the init interface * @precon nan * @brief 1. Invoke the new interface. Expected result 1 is obtained. 2. Invoke the init interface. Expected result 2 is obtained. 3. Invoke the init interface repeatedly. Expected result 3 is obtained. 4. Invoke the update interface. Expected result 4 is obtained. 5. Invoke the init interface. Expected result 5 is obtained. 6. Invoke the final interface. Expected result 6 is obtained. 7. Invoke the init interface. Expected result 7 is obtained. 8. Invoke the deinit interface. Expected result 8 is obtained. 9. Invoke the init interface. Expected result 9 is obtained. 10. Invoke the reinit interface. Expected result 10 is obtained. 11. Invoke the init interface. Expected result 11 is obtained. * @expect 1. If the new operation is successful, the CRYPT_EAL_MacCtx pointer is returned. 2. If the init operation is successful, CRYPT_SUCCESS is returned. 3. If the init operation is successful, CRYPT_SUCCESS is returned. 4. If the update is successful, CRYPT_SUCCESS is returned. 5. If the init operation is successful, CRYPT_SUCCESS is returned. 6. If the final operation is successful, CRYPT_SUCCESS is returned. 7. If the init operation is successful, CRYPT_SUCCESS is returned. 8. 9. If the init operation is successful, CRYPT_SUCCESS is returned. 10. The reinit operation is successful and CRYPT_SUCCESS is returned. 11. If the init operation is successful, CRYPT_SUCCESS is returned. * @prior Level 1 * @auto TRUE @ */ /* BEGIN_CASE */ void SDV_CRYPT_EAL_SIPHASH_API_TC003(int algId) { TestMemInit(); uint8_t key[SIPHASH_KEY_SIZE]; uint32_t macLen = TestGetMacLen(algId); uint8_t mac[macLen]; uint8_t message[] = "e1476ccebc8fd7a5f5d1b944bd488bafa08caa713795f87e0364227b473b1cd5d83d0c72ce4ebab3e187"; CRYPT_EAL_MacCtx *ctx = CRYPT_EAL_MacNewCtx(algId); ASSERT_TRUE(ctx != NULL); ASSERT_TRUE(CRYPT_EAL_MacInit(ctx, key, SIPHASH_KEY_SIZE) == CRYPT_SUCCESS); ASSERT_TRUE(CRYPT_EAL_MacInit(ctx, key, SIPHASH_KEY_SIZE) == CRYPT_SUCCESS); ASSERT_TRUE(CRYPT_EAL_MacUpdate(ctx, message, sizeof(message)) == CRYPT_SUCCESS); ASSERT_TRUE(CRYPT_EAL_MacInit(ctx, key, SIPHASH_KEY_SIZE) == CRYPT_SUCCESS); ASSERT_TRUE(CRYPT_EAL_MacFinal(ctx, mac, &macLen) == CRYPT_SUCCESS); ASSERT_TRUE(CRYPT_EAL_MacInit(ctx, key, SIPHASH_KEY_SIZE) == CRYPT_SUCCESS); CRYPT_EAL_MacDeinit(ctx); ASSERT_TRUE(CRYPT_EAL_MacInit(ctx, key, SIPHASH_KEY_SIZE) == CRYPT_SUCCESS); ASSERT_TRUE(CRYPT_EAL_MacReinit(ctx) == CRYPT_SUCCESS); ASSERT_TRUE(CRYPT_EAL_MacInit(ctx, key, SIPHASH_KEY_SIZE) == CRYPT_SUCCESS); EXIT: CRYPT_EAL_MacFreeCtx(ctx); } /* END_CASE */ /* @ * @test SDV_CRYPT_EAL_SIPHASH_API_TC004 * @spec - * @title Impact of Input Parameters on the Update Interface (Valid and Invalid Input Parameters) * @precon nan * @brief 1. Invoke the new interface. Expected result 1 is obtained. 2. Invoke the init interface. Expected result 2 is obtained. 3. Invoke the update interface and set ctx to NULL. Expected result 3 is obtained. 4. Invoke the update interface. Set in to NULL and len to a value other than 0. Expected result 4 is obtained. 5. Invoke the update interface. Set in to a value other than NULL and len to 0. Expected result 5 is obtained. 6. Invoke the update interface. Set in to NULL and len to 0. Expected result 6 is obtained. 7. Invoke the update interface and ensure that the input parameters are correct. Expected result 7 is obtained. * @expect 1. If the new operation is successful, the CRYPT_EAL_MacCtx pointer is returned. 2. If the init operation is successful, CRYPT_SUCCESS is returned. 3. If the update fails, CRYPT_NULL_INPUT is returned. 4. If the update fails, CRYPT_NULL_INPUT is returned. 5. If the update is successful, CRYPT_SUCCESS is returned. 6. If the update is successful, CRYPT_SUCCESS is returned. 7. If the update is successful, CRYPT_SUCCESS is returned. * @prior Level 1 * @auto TRUE @ */ /* BEGIN_CASE */ void SDV_CRYPT_EAL_SIPHASH_API_TC004(int algId) { TestMemInit(); uint8_t key[SIPHASH_KEY_SIZE]; uint8_t message[] = "e1476ccebc8fd7a5f5d1b944bd488bafa08caa713795f87e0364227b473b1cd5d83d0c72ce4ebab3e187"; CRYPT_EAL_MacCtx *ctx = CRYPT_EAL_MacNewCtx(algId); ASSERT_TRUE(ctx != NULL); ASSERT_TRUE(CRYPT_EAL_MacInit(ctx, key, SIPHASH_KEY_SIZE) == CRYPT_SUCCESS); ASSERT_TRUE(CRYPT_EAL_MacUpdate(NULL, message, sizeof(message)) == CRYPT_NULL_INPUT); ASSERT_TRUE(CRYPT_EAL_MacUpdate(ctx, NULL, sizeof(message)) == CRYPT_NULL_INPUT); ASSERT_TRUE(CRYPT_EAL_MacUpdate(ctx, message, 0) == CRYPT_SUCCESS); ASSERT_TRUE(CRYPT_EAL_MacUpdate(ctx, NULL, 0) == CRYPT_SUCCESS); ASSERT_TRUE(CRYPT_EAL_MacUpdate(ctx, message, sizeof(message)) == CRYPT_SUCCESS); EXIT: CRYPT_EAL_MacFreeCtx(ctx); } /* END_CASE */ /* @ * @test SDV_CRYPT_EAL_SIPHASH_API_TC005 * @spec - * @title Impact of CTX status transition on the update interface_different CTX status * @precon nan * @brief 1. Invoke the new interface. Expected result 1 is obtained. 2. Invoke the update interface. Expected result 2 is obtained. 3. Invoke the init interface. Expected result 3 is obtained. 4. Invoke the update interface. Expected result 4 is obtained. 5. Invoke the final interface. Expected result 5 is obtained. 6. Invoke the update interface. Expected result 6 is obtained. 7. Invoke the update interface repeatedly. Expected result 7 is obtained. 8. Invoke the deinit interface. Expected result 8 is obtained. 9. Invoke the update interface. Expected result 9 is obtained. 10. Invoke the final interface. Expected result 10 is obtained. 11. Invoke the init interface. Expected result 11 is obtained. 12. Invoke the update interface. Expected result 12 is obtained. 13. Invoke the reinit interface. Expected result 13 is obtained. 14. Invoke the update interface. Expected result 14 is obtained. 15. Invoke the update interface repeatedly. (Expected result 15) * @expect 1. If the new operation is successful, the CRYPT_EAL_MacCtx pointer is returned. 2. If the update fails, CRYPT_EAL_ERR_STATE is returned. 3. If the init operation is successful, CRYPT_SUCCESS is returned. 4. If the update is successful, CRYPT_SUCCESS is returned. 5. If the final operation is successful, CRYPT_SUCCESS is returned. 6. If the update fails, CRYPT_EAL_ERR_STATE is returned. 7. If the update fails, CRYPT_EAL_ERR_STATE is returned. 8. 9. If the update fails, CRYPT_EAL_ERR_STATE is returned. 10. If the final operation is successful, CRYPT_EAL_ERR_STATE is returned. 11. If the init operation is successful, CRYPT_SUCCESS is returned. 12. If the update is successful, CRYPT_SUCCESS is returned. 13. The reinit operation is successful and CRYPT_SUCCESS is returned. 14. If the update is successful, CRYPT_SUCCESS is returned. 15. If the update is successful, CRYPT_SUCCESS is returned. * @prior Level 1 * @auto TRUE @ */ /* BEGIN_CASE */ void SDV_CRYPT_EAL_SIPHASH_API_TC005(int algId) { TestMemInit(); uint8_t key[SIPHASH_KEY_SIZE]; uint32_t macLen = TestGetMacLen(algId); uint8_t mac[macLen]; uint8_t message[] = "e1476ccebc8fd7a5f5d1b944bd488bafa08caa713795f87e0364227b473b1cd5d83d0c72ce4ebab3e187"; CRYPT_EAL_MacCtx *ctx = CRYPT_EAL_MacNewCtx(algId); ASSERT_TRUE(ctx != NULL); ASSERT_TRUE(CRYPT_EAL_MacUpdate(ctx, message, sizeof(message)) == CRYPT_EAL_ERR_STATE); ASSERT_TRUE(CRYPT_EAL_MacInit(ctx, key, SIPHASH_KEY_SIZE) == CRYPT_SUCCESS); ASSERT_TRUE(CRYPT_EAL_MacUpdate(ctx, message, sizeof(message)) == CRYPT_SUCCESS); ASSERT_TRUE(CRYPT_EAL_MacFinal(ctx, mac, &macLen) == CRYPT_SUCCESS); ASSERT_TRUE(CRYPT_EAL_MacUpdate(ctx, message, sizeof(message)) == CRYPT_EAL_ERR_STATE); ASSERT_TRUE(CRYPT_EAL_MacUpdate(ctx, message, sizeof(message)) == CRYPT_EAL_ERR_STATE); CRYPT_EAL_MacDeinit(ctx); ASSERT_TRUE(CRYPT_EAL_MacUpdate(ctx, message, sizeof(message)) == CRYPT_EAL_ERR_STATE); ASSERT_TRUE(CRYPT_EAL_MacFinal(ctx, mac, &macLen) == CRYPT_EAL_ERR_STATE); ASSERT_TRUE(CRYPT_EAL_MacInit(ctx, key, SIPHASH_KEY_SIZE) == CRYPT_SUCCESS); ASSERT_TRUE(CRYPT_EAL_MacUpdate(ctx, message, sizeof(message)) == CRYPT_SUCCESS); ASSERT_TRUE(CRYPT_EAL_MacReinit(ctx) == CRYPT_SUCCESS); ASSERT_TRUE(CRYPT_EAL_MacUpdate(ctx, message, sizeof(message)) == CRYPT_SUCCESS); ASSERT_TRUE(CRYPT_EAL_MacUpdate(ctx, message, sizeof(message)) == CRYPT_SUCCESS); EXIT: CRYPT_EAL_MacFreeCtx(ctx); } /* END_CASE */ /* @ * @test SDV_CRYPT_EAL_SIPHASH_API_TC006 * @spec - * @title Impact of input parameters on the final interface: valid and invalid input parameters * @precon nan * @brief 1. Invoke the new interface. Expected result 1 is obtained. 2. Invoke the init interface. Expected result 2 is obtained. 3. Invoke the final interface and set ctx to NULL. Expected result 3 is obtained. 4. Invoke the final interface and set the value of out to NULL. Expected result 4 is obtained. 5. Invoke the final interface and set len to NULL. Expected result 5 is obtained. 6. Invoke the final interface. The value of len is less than the MAC data length. Expected result 6 is obtained. 7. Invoke the final interface. The value of len is greater than the MAC data length. Expected result 7 is obtained. 8. Invoke the init interface. Expected result 8 is obtained. 9. Invoke the final interface. The input parameters are normal. Expected result 9 is obtained. * @expect 1. If the new operation is successful, the CRYPT_EAL_MacCtx pointer is returned. 2. If the init operation is successful, CRYPT_SUCCESS is returned. 3. If the final operation fails, CRYPT_NULL_INPUT is returned. 4. If the final operation fails, CRYPT_NULL_INPUT is returned. 5. If the final operation fails, CRYPT_NULL_INPUT is returned. 6. If the final operation fails, CRYPT_SIPHASH_OUT_BUFF_LEN_NOT_ENOUGH is returned. 7. If the final operation is successful, CRYPT_SUCCESS is returned. 8. If the init operation is successful, CRYPT_SUCCESS is returned. 9. If the final operation is successful, CRYPT_SUCCESS is returned. * @prior Level 1 * @auto TRUE @ */ /* BEGIN_CASE */ void SDV_CRYPT_EAL_SIPHASH_API_TC006(int algId) { TestMemInit(); uint8_t key[SIPHASH_KEY_SIZE]; uint32_t macLen = TestGetMacLen(algId); uint8_t mac[macLen]; CRYPT_EAL_MacCtx *ctx = CRYPT_EAL_MacNewCtx(algId); ASSERT_TRUE(ctx != NULL); ASSERT_TRUE(CRYPT_EAL_MacInit(ctx, key, SIPHASH_KEY_SIZE) == CRYPT_SUCCESS); ASSERT_TRUE(CRYPT_EAL_MacFinal(NULL, mac, &macLen) == CRYPT_NULL_INPUT); ASSERT_TRUE(CRYPT_EAL_MacFinal(ctx, NULL, &macLen) == CRYPT_NULL_INPUT); ASSERT_TRUE(CRYPT_EAL_MacFinal(ctx, mac, NULL) == CRYPT_NULL_INPUT); macLen = TestGetMacLen(algId) - 1; ASSERT_TRUE(CRYPT_EAL_MacFinal(ctx, mac, &macLen) == CRYPT_SIPHASH_OUT_BUFF_LEN_NOT_ENOUGH); macLen = TestGetMacLen(algId) + 1; ASSERT_TRUE(CRYPT_EAL_MacFinal(ctx, mac, &macLen) == CRYPT_SUCCESS); ASSERT_TRUE(CRYPT_EAL_MacInit(ctx, key, SIPHASH_KEY_SIZE) == CRYPT_SUCCESS); ASSERT_TRUE(CRYPT_EAL_MacFinal(ctx, mac, &macLen) == CRYPT_SUCCESS); EXIT: CRYPT_EAL_MacFreeCtx(ctx); } /* END_CASE */ /* @ * @test SDV_CRYPT_EAL_SIPHASH_API_TC007 * @spec - * @title Impact of CTX status transition on the final interface_different CTX status * @precon nan * @brief 1. Invoke the new interface. Expected result 1 is obtained. 2. Invoke the final interface. Expected result 2 is obtained. 3. Repeat the final interface. Expected result 3 is obtained. 4. Invoke the update interface. Expected result 4 is obtained. 5. Invoke the init interface. Expected result 5 is obtained. 6. Invoke the final interface. Expected result 6 is obtained. 7. Invoke the init interface. Expected result 7 is obtained. 8. Invoke the update interface. Expected result 8 is obtained. 9. Invoke the final interface. Expected result 9 is obtained. 10. Invoke the deinit interface. Expected result 10 is obtained. 11. Invoke the final interface. Expected result 11 is obtained. 12. Invoke the init interface. Expected result 12 is obtained. 13. Invoke the reinit interface. Expected result 13 is obtained. 14. Invoke the final interface. Expected result 14 is obtained. 15. Invoke the final interface repeatedly. Expected result 15 is obtained. * @expect 1. If the new operation is successful, the CRYPT_EAL_MacCtx pointer is returned. 2. If the final operation fails, CRYPT_EAL_ERR_STATE is returned. 3. If the final operation fails, CRYPT_EAL_ERR_STATE is returned. 4. If the update fails, YPT_EAL_ERR_STATE is returned. 5. If the init operation is successful, CRYPT_SUCCESS is returned. 6. If the final operation is successful, CRYPT_SUCCESS is returned. 7. If the init operation is successful, CRYPT_SUCCESS is returned. 8. If the update is successful, CRYPT_SUCCESS is returned. 9. If the final operation is successful, CRYPT_SUCCESS is returned. 10. 11. If the final operation fails, CRYPT_EAL_ERR_STATE is returned. 12. If the init operation is successful, CRYPT_SUCCESS is returned. 13. The reinit operation is successful and CRYPT_SUCCESS is returned. 14. If the final operation is successful, CRYPT_SUCCESS is returned. 15. If the final operation fails, RYPT_EAL_ERR_STATE is returned. * @prior Level 1 * @auto TRUE @ */ /* BEGIN_CASE */ void SDV_CRYPT_EAL_SIPHASH_API_TC007(int algId, Hex *key1, Hex *key2, Hex *data2) { TestMemInit(); uint32_t macLen = TestGetMacLen(algId); uint8_t mac[macLen]; CRYPT_EAL_MacCtx *ctx = CRYPT_EAL_MacNewCtx(algId); ASSERT_TRUE(ctx != NULL); ASSERT_TRUE(CRYPT_EAL_MacFinal(ctx, mac, &macLen) == CRYPT_EAL_ERR_STATE); ASSERT_TRUE(CRYPT_EAL_MacFinal(ctx, mac, &macLen) == CRYPT_EAL_ERR_STATE); ASSERT_TRUE(CRYPT_EAL_MacUpdate(ctx, data2->x, data2->len) == CRYPT_EAL_ERR_STATE); ASSERT_TRUE(key1->len == SIPHASH_KEY_SIZE); ASSERT_TRUE(CRYPT_EAL_MacInit(ctx, key1->x, key1->len) == CRYPT_SUCCESS); ASSERT_TRUE(CRYPT_EAL_MacFinal(ctx, mac, &macLen) == CRYPT_SUCCESS); ASSERT_TRUE(key2->len == SIPHASH_KEY_SIZE); ASSERT_TRUE(CRYPT_EAL_MacInit(ctx, key2->x, key2->len) == CRYPT_SUCCESS); ASSERT_TRUE(CRYPT_EAL_MacUpdate(ctx, data2->x, data2->len) == CRYPT_SUCCESS); ASSERT_TRUE(CRYPT_EAL_MacFinal(ctx, mac, &macLen) == CRYPT_SUCCESS); CRYPT_EAL_MacDeinit(ctx); ASSERT_TRUE(CRYPT_EAL_MacFinal(ctx, mac, &macLen) == CRYPT_EAL_ERR_STATE); ASSERT_TRUE(CRYPT_EAL_MacInit(ctx, key2->x, key2->len) == CRYPT_SUCCESS); ASSERT_TRUE(CRYPT_EAL_MacReinit(ctx) == CRYPT_SUCCESS); ASSERT_TRUE(CRYPT_EAL_MacFinal(ctx, mac, &macLen) == CRYPT_SUCCESS); ASSERT_TRUE(CRYPT_EAL_MacFinal(ctx, mac, &macLen) == CRYPT_EAL_ERR_STATE); EXIT: CRYPT_EAL_MacFreeCtx(ctx); } /* END_CASE */ /* @ * @test SDV_CRYPT_EAL_SIPHASH_API_TC008 * @spec - * @title Impact of input parameters on the getMacLen interface: valid and invalid input parameters * @precon nan * @brief 1. Invoke the new interface. Expected result 1 is obtained. 2. Invoke the init interface. Expected result 2 is obtained. 3. Invoke the getLen interface and set the input parameter to NULL. Expected result 3 is obtained. 4. Invoke the getLen interface and set normal input parameters. Expected result 4 is obtained. * @expect 1. If the new operation is successful, the CRYPT_EAL_MacCtx pointer is returned. 2. If the init operation is successful, CRYPT_SUCCESS is returned. 3. If the operation fails, 0 is returned. 4. If the operation is successful, the MAC length corresponding to the context is returned. * @prior Level 1 * @auto TRUE @ */ /* BEGIN_CASE */ void SDV_CRYPT_EAL_SIPHASH_API_TC008(int algId) { TestMemInit(); uint8_t key[SIPHASH_KEY_SIZE]; CRYPT_EAL_MacCtx *ctx = CRYPT_EAL_MacNewCtx(algId); ASSERT_TRUE(CRYPT_EAL_MacInit(ctx, key, SIPHASH_KEY_SIZE) == CRYPT_SUCCESS); ASSERT_TRUE(CRYPT_EAL_GetMacLen(NULL) == 0); ASSERT_TRUE(CRYPT_EAL_GetMacLen(ctx) == TestGetMacLen(algId)); uint32_t result = 0; ASSERT_TRUE(CRYPT_EAL_MacCtrl(ctx, CRYPT_CTRL_GET_MACLEN, &result, sizeof(uint32_t)) == CRYPT_SUCCESS); ASSERT_TRUE(result == TestGetMacLen(algId)); EXIT: CRYPT_EAL_MacFreeCtx(ctx); } /* END_CASE */ /* @ * @test SDV_CRYPT_EAL_SIPHASH_API_TC009 * @spec - * @title Impact of the CTX state on the getMacLen interface_Impact of the CTX state on the interface * @precon nan * @brief 1. Invoke the new interface. Expected result 1 is obtained. 2. Invoke the getLen interface. Expected result 2 is obtained. 3. Invoke the init interface. Expected result 3 is obtained. 4. Invoke the getLen interface. Expected result 4 is obtained. 5. Invoke the update interface. Expected result 5 is obtained. 6. Invoke the getLen interface. Expected result 6 is obtained. 7. Invoke the final interface. Expected result 7 is obtained. 8. Invoke the getLen interface. Expected result 8 is obtained. 9. Invoke the deinit interface. Expected result 9 is obtained. 10. Invoke the getLen interface. Expected result 10 is obtained. 11. Invoke the reinit interface. Expected result 11 is obtained. 12. Invoke the getLen interface. Expected result 12 is obtained. * @expect 1. If the new operation is successful, the CRYPT_EAL_MacCtx pointer is returned. 2. If the operation is successful, the MAC length corresponding to the context is returned. 3. If the init operation is successful, CRYPT_SUCCESS is returned. 4. If the operation is successful, the MAC length corresponding to the context is returned. 5. The update is successful and CRYPT_SUCCESS is returned. 6. If the operation is successful, the MAC length corresponding to the context is returned. 7. If the final operation is successful, CRYPT_SUCCESS is returned. 8. If the operation is successful, the MAC address length corresponding to the context is returned. 9. 10. If the operation is successful, the MAC address length corresponding to the context is returned. 11. If reinit fails, CRYPT_EAL_ERR_STATE is returned. 12. If the operation is successful, the MAC length corresponding to the context is returned. * @prior Level 1 * @auto TRUE @ */ /* BEGIN_CASE */ void SDV_CRYPT_EAL_SIPHASH_API_TC009(int algId) { TestMemInit(); uint8_t key[SIPHASH_KEY_SIZE]; uint32_t macLen = TestGetMacLen(algId); uint8_t mac[macLen]; uint8_t data[] = "5f81bd275320d97416e5e50d5d185d5542a157778b2d05521f27805b925e4f187d06829a2efd407ba11691"; uint32_t dataLen = sizeof(data); CRYPT_EAL_MacCtx *ctx = CRYPT_EAL_MacNewCtx(algId); ASSERT_TRUE(ctx != NULL); ASSERT_TRUE(CRYPT_EAL_GetMacLen(ctx) == TestGetMacLen(algId)); ASSERT_TRUE(CRYPT_EAL_MacInit(ctx, key, SIPHASH_KEY_SIZE) == CRYPT_SUCCESS); ASSERT_TRUE(CRYPT_EAL_GetMacLen(ctx) == TestGetMacLen(algId)); ASSERT_TRUE(CRYPT_EAL_MacUpdate(ctx, data, dataLen) == CRYPT_SUCCESS); ASSERT_TRUE(CRYPT_EAL_GetMacLen(ctx) == TestGetMacLen(algId)); ASSERT_TRUE(CRYPT_EAL_MacFinal(ctx, mac, &macLen) == CRYPT_SUCCESS); ASSERT_TRUE(CRYPT_EAL_GetMacLen(ctx) == TestGetMacLen(algId)); CRYPT_EAL_MacDeinit(ctx); ASSERT_TRUE(CRYPT_EAL_GetMacLen(ctx) == TestGetMacLen(algId)); ASSERT_TRUE(CRYPT_EAL_MacFinal(ctx, mac, &macLen) == CRYPT_EAL_ERR_STATE); ASSERT_TRUE(CRYPT_EAL_GetMacLen(ctx) == TestGetMacLen(algId)); EXIT: CRYPT_EAL_MacFreeCtx(ctx); } /* END_CASE */ /* @ * @test SDV_CRYPT_EAL_SIPHASH_API_TC010 * @spec - * @title Deinit Interface Test_Deinit Interface Test * @precon nan * @brief 1. Invoke the new interface. Expected result 1 is obtained. 2. Invoke the init interface. Expected result 2 is obtained. 3. Invoke the deinit interface. Expected result 3 is obtained. 4. Invoke the deinit interface repeatedly. Expected result 4 is obtained. 5. Invoke the init interface. Expected result 5 is obtained. * @expect 1. If the new operation is successful, the CRYPT_EAL_MacCtx pointer is returned. 2. If the init operation is successful, CRYPT_SUCCESS is returned. 3. 4. 5. If the init operation is successful, CRYPT_SUCCESS is returned. * @prior Level 1 * @auto TRUE @ */ /* BEGIN_CASE */ void SDV_CRYPT_EAL_SIPHASH_API_TC010(int algId) { TestMemInit(); uint8_t key[SIPHASH_KEY_SIZE]; CRYPT_EAL_MacCtx *ctx = CRYPT_EAL_MacNewCtx(algId); ASSERT_TRUE(ctx != NULL); ASSERT_TRUE(CRYPT_EAL_MacInit(ctx, key, SIPHASH_KEY_SIZE) == CRYPT_SUCCESS); CRYPT_EAL_MacDeinit(ctx); CRYPT_EAL_MacDeinit(ctx); ASSERT_TRUE(CRYPT_EAL_MacInit(ctx, key, SIPHASH_KEY_SIZE) == CRYPT_SUCCESS); CRYPT_EAL_MacDeinit(NULL); EXIT: CRYPT_EAL_MacFreeCtx(ctx); } /* END_CASE */ /* @ * @test SDV_CRYPT_EAL_SIPHASH_API_TC011 * @spec - * @title Impact of Input Parameters on the Reinit Interface (Valid and Invalid Input Parameters) * @precon nan * @brief 1. Invoke the new interface. Expected result 1 is obtained. 2. Invoke the init interface. Expected result 2 is obtained. 3. Invoke the reinit interface. The value of ctx is NULL. Expected result 3 is obtained. 4. Invoke the reinit interface. The value of ctx is not NUL. Expected result 4 is obtained. * @expect 1. If the new operation is successful, the CRYPT_EAL_MacCtx pointer is returned. 2. If the init operation is successful, CRYPT_SUCCESS is returned. 3. If the init operation fails, CRYPT_NULL_INPUT is returned. 4. The reinit operation is successful and CRYPT_SUCCESS is returned. * @prior Level 1 * @auto TRUE @ */ /* BEGIN_CASE */ void SDV_CRYPT_EAL_SIPHASH_API_TC011(int algId) { TestMemInit(); uint8_t key[SIPHASH_KEY_SIZE]; CRYPT_EAL_MacCtx *ctx = CRYPT_EAL_MacNewCtx(algId); ASSERT_TRUE(ctx != NULL); ASSERT_TRUE(CRYPT_EAL_MacInit(ctx, key, SIPHASH_KEY_SIZE) == CRYPT_SUCCESS); ASSERT_TRUE(CRYPT_EAL_MacReinit(NULL) == CRYPT_NULL_INPUT); ASSERT_TRUE(CRYPT_EAL_MacReinit(ctx) == CRYPT_SUCCESS); EXIT: CRYPT_EAL_MacFreeCtx(ctx); } /* END_CASE */ /* @ * @test SDV_CRYPT_EAL_SIPHASH_API_TC012 * @spec - * @title Impact of CTX status transition on the reinit interface_different CTX status * @precon nan * @brief 1. Invoke the new interface. Expected result 1 is obtained. 2. Invoke the reinit interface. Expected result 2 is obtained. 3. Invoke the reinit interface repeatedly. Expected result 3 is obtained. 4. Invoke the init interface. Expected result 4 is obtained. 5. Invoke the reinit interface. Expected result 5 is obtained. 6. Invoke the reinit interface repeatedly. Expected result 6 is obtained. 7. Invoke the update interface. Expected result 7 is obtained. 8. Invoke the reinit interface. Expected result 8 is obtained. 9. Invoke the final interface. Expected result 9 is obtained. 10. Invoke the reinit interface. Expected result 10 is obtained. 11. Invoke the deinit interface. Expected result 11 is obtained. 12. Invoke the reinit interface. Expected result 12 is obtained. * @expect 1. If the new operation is successful, the CRYPT_EAL_MacCtx pointer is returned. 2. If the reinit operation fails, CRYPT_EAL_ERR_STATE is returned. 3. If the reinit operation fails, CRYPT_EAL_ERR_STATE is returned. 4. If the init operation is successful, CRYPT_SUCCESS is returned. 5. The reinit operation is successful, and CRYPT_SUCCESS is returned. 6. The reinit operation is successful and CRYPT_SUCCESS is returned. 7. The update is successful and CRYPT_SUCCESS is returned. 8. The reinit operation is successful and CRYPT_SUCCESS is returned. 9. If the final operation is successful, CRYPT_SUCCESS is returned. 10. The reinit operation is successful, and CRYPT_SUCCESS is returned. 11. 12. If reinit fails, CRYPT_EAL_ERR_STATE is returned. * @prior Level 1 * @auto TRUE @ */ /* BEGIN_CASE */ void SDV_CRYPT_EAL_SIPHASH_API_TC012(int algId) { TestMemInit(); uint8_t key[SIPHASH_KEY_SIZE]; uint32_t macLen = TestGetMacLen(algId); uint8_t mac[macLen]; uint8_t data[] = "9c520b111bb008086c5815f450a6b7b6daec0925c4b0c8cf99f9f9ddb6198000a379fcb62527d7c361ccbda2597deecdd" "055850abc6a17251c08577b"; uint32_t dataLen = sizeof(data); CRYPT_EAL_MacCtx *ctx = CRYPT_EAL_MacNewCtx(algId); ASSERT_TRUE(ctx != NULL); ASSERT_TRUE(CRYPT_EAL_MacReinit(ctx) == CRYPT_EAL_ERR_STATE); ASSERT_TRUE(CRYPT_EAL_MacReinit(ctx) == CRYPT_EAL_ERR_STATE); ASSERT_TRUE(CRYPT_EAL_MacInit(ctx, key, SIPHASH_KEY_SIZE) == CRYPT_SUCCESS); ASSERT_TRUE(CRYPT_EAL_MacReinit(ctx) == CRYPT_SUCCESS); ASSERT_TRUE(CRYPT_EAL_MacReinit(ctx) == CRYPT_SUCCESS); ASSERT_TRUE(CRYPT_EAL_MacUpdate(ctx, data, dataLen) == CRYPT_SUCCESS); ASSERT_TRUE(CRYPT_EAL_MacReinit(ctx) == CRYPT_SUCCESS); ASSERT_TRUE(CRYPT_EAL_MacFinal(ctx, mac, &macLen) == CRYPT_SUCCESS); ASSERT_TRUE(CRYPT_EAL_MacReinit(ctx) == CRYPT_SUCCESS); CRYPT_EAL_MacDeinit(ctx); ASSERT_TRUE(CRYPT_EAL_MacReinit(ctx) == CRYPT_EAL_ERR_STATE); EXIT: CRYPT_EAL_MacFreeCtx(ctx); } /* END_CASE */ /** * @test SDV_CRYPT_EAL_SIPHASH_FUN_TC005 * @title Impact of calculating the siphash MAC address when the plaintext data is all 0, all f, and null * @precon nan * @brief * 1. Invoke the new interface. The expected result is successful. * 2. Invoke the init interface. The expected result is successful. * 3. Invoke the update interface. The expected result is successful. * 4. Invoke the final interface. The expected result is successful. */ /* BEGIN_CASE */ void SDV_CRYPT_EAL_SIPHASH_FUN_TC005(int algId, Hex *key, Hex *data) { TestMemInit(); uint32_t macLen = TestGetMacLen(algId); uint8_t mac[macLen]; CRYPT_EAL_MacCtx *ctx = CRYPT_EAL_MacNewCtx(algId); ASSERT_TRUE(ctx != NULL); ASSERT_TRUE(key->len == SIPHASH_KEY_SIZE); ASSERT_EQ(CRYPT_EAL_MacInit(ctx, key->x, key->len), CRYPT_SUCCESS); ASSERT_EQ(CRYPT_EAL_MacUpdate(ctx, NULL, 0), CRYPT_SUCCESS); ASSERT_EQ(CRYPT_EAL_MacUpdate(ctx, data->x, data->len), CRYPT_SUCCESS); ASSERT_EQ(CRYPT_EAL_MacFinal(ctx, mac, &macLen), CRYPT_SUCCESS); EXIT: CRYPT_EAL_MacFreeCtx(ctx); } /* END_CASE */ /** * @test SDV_CRYPT_EAL_SIPHASH_SAMEADDR_FUNC_TC001 * @title SIPHASH in/out test * @precon nan * @brief * 1. Use the EAL-layer interface to perform SIPHASH calculation. All input and output addresses are the same. * Expected result 1 is obtained. * @expect * 1. The calculation is successful, and the result is consistent with the MAC vector. */ /* BEGIN_CASE */ void SDV_CRYPT_EAL_SIPHASH_SAMEADDR_FUNC_TC001(int algId, Hex *key, Hex *data, Hex *mac) { TestMacSameAddr(algId, key, data, mac); } /* END_CASE */ /** * @test SDV_CRYPT_EAL_SIPHASH_ADDR_NOT_ALIGN_FUNC_TC001 * @title SIPHASH non-address alignment test * @precon nan * @brief * 1. Use the EAL layer interface to perform SIPHASH calculation. All buffer addresses are not aligned. * Expected result 1 is obtained. * @expect * 1. The calculation is successful, and the result is consistent with the MAC vector. */ /* BEGIN_CASE */ void SDV_CRYPT_EAL_SIPHASH_ADDR_NOT_ALIGN_FUNC_TC001(int algId, Hex *key, Hex *data, Hex *mac) { TestMacAddrNotAlign(algId, key, data, mac); } /* END_CASE */
2301_79861745/bench_create
testcode/sdv/testcase/crypto/siphash/test_suite_sdv_eal_mac_siphash.c
C
unknown
30,976
/* * This file is part of the openHiTLS project. * * openHiTLS is licensed under the Mulan PSL v2. * You can use this software according to the terms and conditions of the Mulan PSL v2. * You may obtain a copy of Mulan PSL v2 at: * * http://license.coscl.org.cn/MulanPSL2 * * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, * EITHER EXPRESS 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 <stdio.h> #include <string.h> #include "securec.h" #include "bsl_err.h" #include "bsl_sal.h" #include "crypt_errno.h" #include "crypt_algid.h" #include "crypt_eal_pkey.h" #include "crypt_util_rand.h" #include "crypt_bn.h" #include "eal_pkey_local.h" #include "stub_replace.h" #include "test.h" /* END_HEADER */ uint32_t g_stubRandCounter = 0; uint8_t **g_stubRand = NULL; uint32_t *g_stubRandLen = NULL; void RandInjectionInit() { g_stubRandCounter = 0; g_stubRand = NULL; g_stubRandLen = NULL; } void RandInjectionSet(uint8_t **rand, uint32_t *len) { g_stubRand = rand; g_stubRandLen = len; } int32_t RandInjection(uint8_t *rand, uint32_t randLen) { (void)memcpy_s(rand, randLen, g_stubRand[g_stubRandCounter], randLen); g_stubRandCounter++; return CRYPT_SUCCESS; } int32_t RandInjectionEx(void *libCtx, uint8_t *rand, uint32_t randLen) { (void)libCtx; return RandInjection(rand, randLen); } /* BEGIN_CASE */ void SDV_CRYPTO_SLH_DSA_API_NEW_TC001(void) { TestMemInit(); CRYPT_EAL_PkeyCtx *pkey = NULL; pkey = CRYPT_EAL_PkeyNewCtx(CRYPT_PKEY_SLH_DSA); ASSERT_TRUE(pkey != NULL); EXIT: CRYPT_EAL_PkeyFreeCtx(pkey); return; } /* END_CASE */ /* BEGIN_CASE */ void SDV_CRYPTO_SLH_DSA_API_CTRL_TC001(void) { TestMemInit(); CRYPT_EAL_PkeyCtx *pkey = NULL; pkey = CRYPT_EAL_PkeyNewCtx(CRYPT_PKEY_SLH_DSA); ASSERT_TRUE(pkey != NULL); ASSERT_TRUE(CRYPT_EAL_PkeyCtrl(pkey, CRYPT_CTRL_SET_CTX_INFO, NULL, 0) == CRYPT_INVALID_ARG); uint8_t context[128] = {0}; ASSERT_TRUE(CRYPT_EAL_PkeyCtrl(pkey, CRYPT_CTRL_SET_CTX_INFO, context, sizeof(context)) == CRYPT_SUCCESS); ASSERT_TRUE(CRYPT_EAL_PkeyCtrl(pkey, CRYPT_CTRL_SET_PREHASH_FLAG, NULL, 0) == CRYPT_INVALID_ARG); int32_t preHash = 1; ASSERT_TRUE(CRYPT_EAL_PkeyCtrl(pkey, CRYPT_CTRL_SET_PREHASH_FLAG, &preHash, sizeof(preHash)) == CRYPT_SUCCESS); EXIT: CRYPT_EAL_PkeyFreeCtx(pkey); return; } /* END_CASE */ /* BEGIN_CASE */ void SDV_CRYPTO_SLH_DSA_GENKEY_TC001(int isProvider) { TestMemInit(); TestRandInit(); CRYPT_EAL_PkeyCtx *pkey = NULL; #ifdef HITLS_CRYPTO_PROVIDER if (isProvider == 1) { pkey = CRYPT_EAL_ProviderPkeyNewCtx(NULL, CRYPT_PKEY_SLH_DSA, CRYPT_EAL_PKEY_SIGN_OPERATE, "provider=default"); } else #endif { (void)isProvider; pkey = CRYPT_EAL_PkeyNewCtx(CRYPT_PKEY_SLH_DSA); } ASSERT_TRUE(pkey != NULL); ASSERT_TRUE(CRYPT_EAL_PkeyCtrl(pkey, CRYPT_CTRL_SET_PARA_BY_ID, NULL, 0) == CRYPT_INVALID_ARG); ASSERT_TRUE(CRYPT_EAL_PkeyGen(pkey) == CRYPT_SLHDSA_ERR_INVALID_ALGID); CRYPT_PKEY_ParaId algId = CRYPT_SLH_DSA_SHA2_128S; ASSERT_TRUE(CRYPT_EAL_PkeyCtrl(pkey, CRYPT_CTRL_SET_PARA_BY_ID, (void *)&algId, sizeof(algId)) == CRYPT_SUCCESS); ASSERT_TRUE(CRYPT_EAL_PkeyGen(pkey) == CRYPT_SUCCESS); EXIT: CRYPT_EAL_PkeyFreeCtx(pkey); TestRandDeInit(); return; } /* END_CASE */ /* BEGIN_CASE */ void SDV_CRYPTO_SLH_DSA_GETSET_KEY_TC001(void) { TestMemInit(); TestRandInit(); CRYPT_EAL_PkeyCtx *pkey = NULL; pkey = CRYPT_EAL_PkeyNewCtx(CRYPT_PKEY_SLH_DSA); ASSERT_TRUE(pkey != NULL); int32_t algId = CRYPT_SLH_DSA_SHA2_128S; ASSERT_EQ(CRYPT_EAL_PkeySetParaById(pkey, algId), CRYPT_SUCCESS); CRYPT_EAL_PkeyPub pub; uint8_t pubSeed[32] = {0}; uint8_t pubRoot[32] = {0}; (void)memset_s(&pub, sizeof(CRYPT_EAL_PkeyPub), 0, sizeof(CRYPT_EAL_PkeyPub)); pub.id = CRYPT_PKEY_SLH_DSA; ASSERT_EQ(CRYPT_EAL_PkeyGetPub(pkey, &pub), CRYPT_NULL_INPUT); ASSERT_EQ(CRYPT_EAL_PkeySetPub(pkey, &pub), CRYPT_NULL_INPUT); pub.key.slhDsaPub.seed = pubSeed; pub.key.slhDsaPub.root = pubRoot; pub.key.slhDsaPub.len = sizeof(pubSeed); ASSERT_EQ(CRYPT_EAL_PkeyGetPub(pkey, &pub), CRYPT_SLHDSA_ERR_INVALID_KEYLEN); ASSERT_EQ(CRYPT_EAL_PkeySetPub(pkey, &pub), CRYPT_SLHDSA_ERR_INVALID_KEYLEN); CRYPT_EAL_PkeyPrv prv; uint8_t prvSeed[32] = {0}; uint8_t prvPrf[32] = {0}; (void)memset_s(&prv, sizeof(CRYPT_EAL_PkeyPrv), 0, sizeof(CRYPT_EAL_PkeyPrv)); prv.id = CRYPT_PKEY_SLH_DSA; ASSERT_EQ(CRYPT_EAL_PkeyGetPrv(pkey, &prv), CRYPT_NULL_INPUT); ASSERT_EQ(CRYPT_EAL_PkeySetPrv(pkey, &prv), CRYPT_NULL_INPUT); prv.key.slhDsaPrv.seed = prvSeed; prv.key.slhDsaPrv.prf = prvPrf; prv.key.slhDsaPrv.pub.seed = pubSeed; prv.key.slhDsaPrv.pub.root = pubRoot; prv.key.slhDsaPrv.pub.len = sizeof(pubSeed); ASSERT_EQ(CRYPT_EAL_PkeyGetPrv(pkey, &prv), CRYPT_SLHDSA_ERR_INVALID_KEYLEN); ASSERT_EQ(CRYPT_EAL_PkeySetPrv(pkey, &prv), CRYPT_SLHDSA_ERR_INVALID_KEYLEN); EXIT: CRYPT_EAL_PkeyFreeCtx(pkey); TestRandDeInit(); return; } /* END_CASE */ /* BEGIN_CASE */ void SDV_CRYPTO_SLH_DSA_GETSET_KEY_TC002(void) { TestMemInit(); TestRandInit(); CRYPT_EAL_PkeyCtx *pkey = NULL; pkey = CRYPT_EAL_PkeyNewCtx(CRYPT_PKEY_SLH_DSA); ASSERT_TRUE(pkey != NULL); int32_t algId = CRYPT_SLH_DSA_SHA2_128S; ASSERT_EQ(CRYPT_EAL_PkeySetParaById(pkey, algId), CRYPT_SUCCESS); ASSERT_TRUE(CRYPT_EAL_PkeyGen(pkey) == CRYPT_SUCCESS); CRYPT_EAL_PkeyPub pub; uint8_t pubSeed[32] = {0}; uint8_t pubRoot[32] = {0}; (void)memset_s(&pub, sizeof(CRYPT_EAL_PkeyPub), 0, sizeof(CRYPT_EAL_PkeyPub)); pub.id = CRYPT_PKEY_SLH_DSA; pub.key.slhDsaPub.seed = pubSeed; pub.key.slhDsaPub.root = pubRoot; pub.key.slhDsaPub.len = 16; ASSERT_EQ(CRYPT_EAL_PkeyGetPub(pkey, &pub), CRYPT_SUCCESS); ASSERT_EQ(CRYPT_EAL_PkeySetPub(pkey, &pub), CRYPT_SUCCESS); CRYPT_EAL_PkeyPrv prv; uint8_t prvSeed[32] = {0}; uint8_t prvPrf[32] = {0}; (void)memset_s(&prv, sizeof(CRYPT_EAL_PkeyPrv), 0, sizeof(CRYPT_EAL_PkeyPrv)); prv.id = CRYPT_PKEY_SLH_DSA; prv.key.slhDsaPrv.seed = prvSeed; prv.key.slhDsaPrv.prf = prvPrf; prv.key.slhDsaPrv.pub.seed = pubSeed; prv.key.slhDsaPrv.pub.root = pubRoot; prv.key.slhDsaPrv.pub.len = 16; ASSERT_EQ(CRYPT_EAL_PkeyGetPrv(pkey, &prv), CRYPT_SUCCESS); ASSERT_EQ(CRYPT_EAL_PkeySetPrv(pkey, &prv), CRYPT_SUCCESS); EXIT: CRYPT_EAL_PkeyFreeCtx(pkey); TestRandDeInit(); return; } /* END_CASE */ /* BEGIN_CASE */ void SDV_CRYPTO_SLH_DSA_GENKEY_KAT_TC001(int id, Hex *key, Hex *root) { TestMemInit(); CRYPT_EAL_PkeyCtx *pkey = NULL; pkey = CRYPT_EAL_PkeyNewCtx(CRYPT_PKEY_SLH_DSA); ASSERT_TRUE(pkey != NULL); int32_t algId = id; ASSERT_EQ(CRYPT_EAL_PkeySetParaById(pkey, algId), CRYPT_SUCCESS); uint32_t keyLen = 0; ASSERT_EQ(CRYPT_EAL_PkeyCtrl(pkey, CRYPT_CTRL_GET_SLH_DSA_KEY_LEN, (void *)&keyLen, sizeof(keyLen)), CRYPT_SUCCESS); RandInjectionInit(); uint8_t *stubRand[3] = {key->x, key->x + keyLen, key->x + keyLen * 2}; uint32_t stubRandLen[3] = {keyLen, keyLen, keyLen}; RandInjectionSet(stubRand, stubRandLen); CRYPT_RandRegist(RandInjection); CRYPT_RandRegistEx(RandInjectionEx); ASSERT_TRUE(CRYPT_EAL_PkeyGen(pkey) == CRYPT_SUCCESS); uint8_t pubSeed[32] = {0}; uint8_t pubRoot[32] = {0}; CRYPT_EAL_PkeyPub pubOut; (void)memset_s(&pubOut, sizeof(CRYPT_EAL_PkeyPub), 0, sizeof(CRYPT_EAL_PkeyPub)); pubOut.id = CRYPT_PKEY_SLH_DSA; pubOut.key.slhDsaPub.seed = pubSeed; pubOut.key.slhDsaPub.root = pubRoot; pubOut.key.slhDsaPub.len = keyLen; ASSERT_EQ(CRYPT_EAL_PkeyGetPub(pkey, &pubOut), CRYPT_SUCCESS); ASSERT_EQ(memcmp(pubOut.key.slhDsaPub.seed, root->x, keyLen), 0); ASSERT_EQ(memcmp(pubOut.key.slhDsaPub.root, root->x + keyLen, keyLen), 0); EXIT: CRYPT_EAL_PkeyFreeCtx(pkey); return; } /* END_CASE */ // determinstic and no pre-hashed signature generation /* BEGIN_CASE */ void SDV_CRYPTO_SLH_DSA_SIGN_KAT_TC001(int id, Hex *key, Hex *addrand, Hex *msg, Hex *context, Hex *sig) { (void)key; (void)addrand; (void)msg; (void)context; (void)sig; TestMemInit(); CRYPT_EAL_PkeyCtx *pkey = NULL; pkey = CRYPT_EAL_PkeyNewCtx(CRYPT_PKEY_SLH_DSA); ASSERT_TRUE(pkey != NULL); int32_t algId = id; ASSERT_EQ(CRYPT_EAL_PkeySetParaById(pkey, algId), CRYPT_SUCCESS); uint32_t keyLen = 0; ASSERT_EQ(CRYPT_EAL_PkeyCtrl(pkey, CRYPT_CTRL_GET_SLH_DSA_KEY_LEN, (void *)&keyLen, sizeof(keyLen)), CRYPT_SUCCESS); if (addrand->len == 0) { int32_t isDeterministic = 1; ASSERT_EQ(CRYPT_EAL_PkeyCtrl(pkey, CRYPT_CTRL_SET_DETERMINISTIC_FLAG, (void *)&isDeterministic, sizeof(isDeterministic)), CRYPT_SUCCESS); } else { ASSERT_EQ(CRYPT_EAL_PkeyCtrl(pkey, CRYPT_CTRL_SET_SLH_DSA_ADDRAND, (void *)addrand->x, addrand->len), CRYPT_SUCCESS); } CRYPT_EAL_PkeyPrv prv; (void)memset_s(&prv, sizeof(CRYPT_EAL_PkeyPrv), 0, sizeof(CRYPT_EAL_PkeyPrv)); prv.id = CRYPT_PKEY_SLH_DSA; prv.key.slhDsaPrv.seed = key->x; prv.key.slhDsaPrv.prf = key->x + keyLen; prv.key.slhDsaPrv.pub.seed = key->x + keyLen * 2; prv.key.slhDsaPrv.pub.root = key->x + keyLen * 3; prv.key.slhDsaPrv.pub.len = keyLen; ASSERT_EQ(CRYPT_EAL_PkeySetPrv(pkey, &prv), CRYPT_SUCCESS); if (context->len != 0) { ASSERT_EQ(CRYPT_EAL_PkeyCtrl(pkey, CRYPT_CTRL_SET_CTX_INFO, context->x, context->len), CRYPT_SUCCESS); } uint8_t sigOut[50000] = {0}; uint32_t sigOutLen = sizeof(sigOut); ASSERT_EQ(CRYPT_EAL_PkeySign(pkey, CRYPT_MD_SHA256, msg->x, msg->len, sigOut, &sigOutLen), CRYPT_SUCCESS); ASSERT_TRUE(sigOutLen == sig->len); ASSERT_TRUE(memcmp(sigOut, sig->x, sigOutLen) == 0); EXIT: CRYPT_EAL_PkeyFreeCtx(pkey); return; } /* END_CASE */ // sign pre-hashed msg /* BEGIN_CASE */ void SDV_CRYPTO_SLH_DSA_SIGN_KAT_TC002(int id, Hex *key, Hex *addrand, Hex *msg, Hex *context, int preHashId, Hex *sig) { TestMemInit(); CRYPT_EAL_PkeyCtx *pkey = NULL; pkey = CRYPT_EAL_PkeyNewCtx(CRYPT_PKEY_SLH_DSA); ASSERT_TRUE(pkey != NULL); int32_t algId = id; ASSERT_EQ(CRYPT_EAL_PkeySetParaById(pkey, algId), CRYPT_SUCCESS); uint32_t keyLen = 0; ASSERT_EQ(CRYPT_EAL_PkeyCtrl(pkey, CRYPT_CTRL_GET_SLH_DSA_KEY_LEN, (void *)&keyLen, sizeof(keyLen)), CRYPT_SUCCESS); if (addrand->len == 0) { int32_t isDeterministic = 1; ASSERT_EQ(CRYPT_EAL_PkeyCtrl(pkey, CRYPT_CTRL_SET_DETERMINISTIC_FLAG, (void *)&isDeterministic, sizeof(isDeterministic)), CRYPT_SUCCESS); } else { ASSERT_EQ(CRYPT_EAL_PkeyCtrl(pkey, CRYPT_CTRL_SET_SLH_DSA_ADDRAND, (void *)addrand->x, addrand->len), CRYPT_SUCCESS); } int32_t prehash = 1; ASSERT_EQ(CRYPT_EAL_PkeyCtrl(pkey, CRYPT_CTRL_SET_PREHASH_FLAG, (void *)&prehash, sizeof(prehash)), CRYPT_SUCCESS); CRYPT_EAL_PkeyPrv prv; (void)memset_s(&prv, sizeof(CRYPT_EAL_PkeyPrv), 0, sizeof(CRYPT_EAL_PkeyPrv)); prv.id = CRYPT_PKEY_SLH_DSA; prv.key.slhDsaPrv.seed = key->x; prv.key.slhDsaPrv.prf = key->x + keyLen; prv.key.slhDsaPrv.pub.seed = key->x + keyLen * 2; prv.key.slhDsaPrv.pub.root = key->x + keyLen * 3; prv.key.slhDsaPrv.pub.len = keyLen; ASSERT_EQ(CRYPT_EAL_PkeySetPrv(pkey, &prv), CRYPT_SUCCESS); if (context->len != 0) { ASSERT_EQ(CRYPT_EAL_PkeyCtrl(pkey, CRYPT_CTRL_SET_CTX_INFO, context->x, context->len), CRYPT_SUCCESS); } uint8_t sigOut[50000] = {0}; uint32_t sigOutLen = sizeof(sigOut); ASSERT_EQ(CRYPT_EAL_PkeySign(pkey, preHashId, msg->x, msg->len, sigOut, &sigOutLen), CRYPT_SUCCESS); ASSERT_TRUE(sigOutLen == sig->len); ASSERT_TRUE(memcmp(sigOut, sig->x, sigOutLen) == 0); EXIT: CRYPT_EAL_PkeyFreeCtx(pkey); return; } /* END_CASE */ /* @ * @test SDV_CRYPTO_SLH_DSA_CHECK_KEYPAIR_TC001 * @spec - * @title Key generation and check key pair @ */ /* BEGIN_CASE */ void SDV_CRYPTO_SLH_DSA_CHECK_KEYPAIR_TC001(int algId) { #if !defined(HITLS_CRYPTO_SLH_DSA_CHECK) (void)algId; SKIP_TEST(); #else TestMemInit(); TestRandInit(); CRYPT_EAL_PkeyCtx *pkey = NULL; CRYPT_EAL_PkeyCtx *pubKey = NULL; CRYPT_EAL_PkeyCtx *prvKey = NULL; uint32_t keyLen = 0; #ifdef HITLS_CRYPTO_PROVIDER pkey = CRYPT_EAL_ProviderPkeyNewCtx(NULL, CRYPT_PKEY_SLH_DSA, CRYPT_EAL_PKEY_SIGN_OPERATE, "provider=default"); pubKey = CRYPT_EAL_ProviderPkeyNewCtx(NULL, CRYPT_PKEY_SLH_DSA, CRYPT_EAL_PKEY_SIGN_OPERATE, "provider=default"); prvKey = CRYPT_EAL_ProviderPkeyNewCtx(NULL, CRYPT_PKEY_SLH_DSA, CRYPT_EAL_PKEY_SIGN_OPERATE, "provider=default"); #else pkey = CRYPT_EAL_PkeyNewCtx(CRYPT_PKEY_SLH_DSA); pubKey = CRYPT_EAL_PkeyNewCtx(CRYPT_PKEY_SLH_DSA); prvKey = CRYPT_EAL_PkeyNewCtx(CRYPT_PKEY_SLH_DSA); #endif ASSERT_TRUE(pkey != NULL); ASSERT_TRUE(pubKey != NULL); ASSERT_TRUE(prvKey != NULL); ASSERT_EQ(CRYPT_EAL_PkeySetParaById(pkey, algId), CRYPT_SUCCESS); ASSERT_EQ(CRYPT_EAL_PkeySetParaById(pubKey, algId), CRYPT_SUCCESS); ASSERT_EQ(CRYPT_EAL_PkeySetParaById(prvKey, algId), CRYPT_SUCCESS); ASSERT_EQ(CRYPT_EAL_PkeyCtrl(pkey, CRYPT_CTRL_GET_SLH_DSA_KEY_LEN, (void *)&keyLen, sizeof(keyLen)), CRYPT_SUCCESS); ASSERT_TRUE(CRYPT_EAL_PkeyGen(pkey) == CRYPT_SUCCESS); ASSERT_EQ(CRYPT_EAL_PkeyPairCheck(pkey, pkey), CRYPT_SUCCESS); CRYPT_EAL_PkeyPub pub; uint8_t pubSeed[32] = {0}; uint8_t pubRoot[32] = {0}; pub.id = CRYPT_PKEY_SLH_DSA; pub.key.slhDsaPub.seed = pubSeed; pub.key.slhDsaPub.root = pubRoot; pub.key.slhDsaPub.len = keyLen; ASSERT_EQ(CRYPT_EAL_PkeyGetPub(pkey, &pub), CRYPT_SUCCESS); ASSERT_EQ(CRYPT_EAL_PkeySetPub(pubKey, &pub), CRYPT_SUCCESS); CRYPT_EAL_PkeyPrv prv; uint8_t prvSeed[32] = {0}; uint8_t prvPrf[32] = {0}; (void)memset_s(&prv, sizeof(CRYPT_EAL_PkeyPrv), 0, sizeof(CRYPT_EAL_PkeyPrv)); prv.id = CRYPT_PKEY_SLH_DSA; prv.key.slhDsaPrv.seed = prvSeed; prv.key.slhDsaPrv.prf = prvPrf; prv.key.slhDsaPrv.pub.seed = pubSeed; prv.key.slhDsaPrv.pub.root = pubRoot; prv.key.slhDsaPrv.pub.len = keyLen; ASSERT_EQ(CRYPT_EAL_PkeyGetPrv(pkey, &prv), CRYPT_SUCCESS); ASSERT_EQ(CRYPT_EAL_PkeySetPrv(prvKey, &prv), CRYPT_SUCCESS); ASSERT_EQ(CRYPT_EAL_PkeyPairCheck(prvKey, prvKey), CRYPT_SLHDSA_ERR_NO_PUBKEY); ASSERT_EQ(CRYPT_EAL_PkeyPairCheck(pubKey, pubKey), CRYPT_SLHDSA_ERR_NO_PRVKEY); ASSERT_EQ(CRYPT_EAL_PkeyPairCheck(pubKey, prvKey), CRYPT_SUCCESS); EXIT: CRYPT_EAL_PkeyFreeCtx(pkey); CRYPT_EAL_PkeyFreeCtx(pubKey); CRYPT_EAL_PkeyFreeCtx(prvKey); TestRandDeInit(); return; #endif } /* END_CASE */ /* @ * @test SDV_CRYPTO_SLH_DSA_CHECK_KEYPAIR_TC002 * @spec - * @title Key generation and check key pair @ */ /* BEGIN_CASE */ void SDV_CRYPTO_SLH_DSA_CHECK_KEYPAIR_TC002(void) { #if !defined(HITLS_CRYPTO_SLH_DSA_CHECK) SKIP_TEST(); #else TestMemInit(); TestRandInit(); int32_t algId1 = CRYPT_SLH_DSA_SHA2_128S; int32_t algId2 = CRYPT_SLH_DSA_SHAKE_192S; CRYPT_EAL_PkeyCtx *ctx1 = NULL; CRYPT_EAL_PkeyCtx *ctx2 = NULL; CRYPT_EAL_PkeyCtx *ctx3 = NULL; #ifdef HITLS_CRYPTO_PROVIDER ctx1 = CRYPT_EAL_ProviderPkeyNewCtx(NULL, CRYPT_PKEY_SLH_DSA, CRYPT_EAL_PKEY_SIGN_OPERATE, "provider=default"); ctx2 = CRYPT_EAL_ProviderPkeyNewCtx(NULL, CRYPT_PKEY_SLH_DSA, CRYPT_EAL_PKEY_SIGN_OPERATE, "provider=default"); ctx3 = CRYPT_EAL_ProviderPkeyNewCtx(NULL, CRYPT_PKEY_SLH_DSA, CRYPT_EAL_PKEY_SIGN_OPERATE, "provider=default"); #else ctx1 = CRYPT_EAL_PkeyNewCtx(CRYPT_PKEY_SLH_DSA); ctx2 = CRYPT_EAL_PkeyNewCtx(CRYPT_PKEY_SLH_DSA); ctx3 = CRYPT_EAL_PkeyNewCtx(CRYPT_PKEY_SLH_DSA); #endif ASSERT_TRUE(ctx1 != NULL); ASSERT_TRUE(ctx2 != NULL); ASSERT_TRUE(ctx3 != NULL); ASSERT_EQ(CRYPT_EAL_PkeyPairCheck(NULL, NULL), CRYPT_NULL_INPUT); ASSERT_EQ(CRYPT_EAL_PkeyPairCheck(ctx1, ctx2), CRYPT_SLHDSA_ERR_INVALID_ALGID); // different key-info ASSERT_EQ(CRYPT_EAL_PkeySetParaById(ctx1, algId1), CRYPT_SUCCESS); ASSERT_EQ(CRYPT_EAL_PkeySetParaById(ctx2, algId1), CRYPT_SUCCESS); ASSERT_EQ(CRYPT_EAL_PkeySetParaById(ctx3, algId2), CRYPT_SUCCESS); ASSERT_EQ(CRYPT_EAL_PkeyGen(ctx1), CRYPT_SUCCESS); ASSERT_EQ(CRYPT_EAL_PkeyGen(ctx2), CRYPT_SUCCESS); ASSERT_EQ(CRYPT_EAL_PkeyPairCheck(ctx1, ctx1), CRYPT_SUCCESS); ASSERT_EQ(CRYPT_EAL_PkeyPairCheck(ctx2, ctx2), CRYPT_SUCCESS); ASSERT_EQ(CRYPT_EAL_PkeyPairCheck(ctx1, ctx2), CRYPT_SLHDSA_PAIRWISE_CHECK_FAIL); EXIT: CRYPT_EAL_PkeyFreeCtx(ctx1); CRYPT_EAL_PkeyFreeCtx(ctx2); CRYPT_EAL_PkeyFreeCtx(ctx3); TestRandDeInit(); return; #endif } /* END_CASE */ /* @ * @test SDV_CRYPTO_SLH_DSA_CHECK_PRVKEY_TC001 * @spec - * @title Key generation and check prv key @ */ /* BEGIN_CASE */ void SDV_CRYPTO_SLH_DSA_CHECK_PRVKEY_TC001(int type) { #if !defined(HITLS_CRYPTO_SLH_DSA_CHECK) (void)type; SKIP_TEST(); #else TestMemInit(); TestRandInit(); CRYPT_EAL_PkeyCtx *ctx = NULL; CRYPT_EAL_PkeyCtx *prvCtx = NULL; CRYPT_EAL_PkeyPrv prv = { 0 }; uint32_t keyLen = 0; #ifdef HITLS_CRYPTO_PROVIDER ctx = CRYPT_EAL_ProviderPkeyNewCtx(NULL, CRYPT_PKEY_SLH_DSA, CRYPT_EAL_PKEY_SIGN_OPERATE, "provider=default"); prvCtx = CRYPT_EAL_ProviderPkeyNewCtx(NULL, CRYPT_PKEY_SLH_DSA, CRYPT_EAL_PKEY_SIGN_OPERATE, "provider=default"); #else ctx = CRYPT_EAL_PkeyNewCtx(CRYPT_PKEY_SLH_DSA); prvCtx = CRYPT_EAL_PkeyNewCtx(CRYPT_PKEY_SLH_DSA); #endif ASSERT_TRUE(ctx != NULL); ASSERT_TRUE(prvCtx != NULL); uint32_t val = (uint32_t)type; ASSERT_EQ(CRYPT_EAL_PkeySetParaById(ctx, val), CRYPT_SUCCESS); ASSERT_EQ(CRYPT_EAL_PkeyPrvCheck(NULL), CRYPT_NULL_INPUT); ASSERT_EQ(CRYPT_EAL_PkeyPrvCheck(prvCtx), CRYPT_SLHDSA_ERR_INVALID_ALGID); ASSERT_EQ(CRYPT_EAL_PkeySetParaById(prvCtx, val), CRYPT_SUCCESS); ASSERT_EQ(CRYPT_EAL_PkeyCtrl(ctx, CRYPT_CTRL_GET_SLH_DSA_KEY_LEN, &keyLen, sizeof(keyLen)), CRYPT_SUCCESS); uint8_t prvSeed[32] = {0}; uint8_t prvPrf[32] = {0}; uint8_t pubSeed[32] = {0}; uint8_t pubRoot[32] = {0}; (void)memset_s(&prv, sizeof(CRYPT_EAL_PkeyPrv), 0, sizeof(CRYPT_EAL_PkeyPrv)); prv.id = CRYPT_PKEY_SLH_DSA; prv.key.slhDsaPrv.seed = prvSeed; prv.key.slhDsaPrv.prf = prvPrf; prv.key.slhDsaPrv.pub.seed = pubSeed; prv.key.slhDsaPrv.pub.root = pubRoot; prv.key.slhDsaPrv.pub.len = keyLen; ASSERT_EQ(CRYPT_EAL_PkeyGen(ctx), CRYPT_SUCCESS); ASSERT_EQ(CRYPT_EAL_PkeyPrvCheck(ctx), CRYPT_SUCCESS); ASSERT_EQ(CRYPT_EAL_PkeyGetPrv(ctx, &prv), CRYPT_SUCCESS); ASSERT_EQ(CRYPT_EAL_PkeyPrvCheck(prvCtx), CRYPT_SLHDSA_ERR_NO_PRVKEY); // not set prv key. ASSERT_EQ(CRYPT_EAL_PkeySetPrv(prvCtx, &prv), CRYPT_SUCCESS); ASSERT_EQ(CRYPT_EAL_PkeyPrvCheck(prvCtx), CRYPT_SUCCESS); EXIT: CRYPT_EAL_PkeyFreeCtx(ctx); CRYPT_EAL_PkeyFreeCtx(prvCtx); TestRandDeInit(); return; #endif } /* END_CASE */
2301_79861745/bench_create
testcode/sdv/testcase/crypto/slh_dsa/test_suite_sdv_eal_slh_dsa.c
C
unknown
19,436
/* * This file is part of the openHiTLS project. * * openHiTLS is licensed under the Mulan PSL v2. * You can use this software according to the terms and conditions of the Mulan PSL v2. * You may obtain a copy of Mulan PSL v2 at: * * http://license.coscl.org.cn/MulanPSL2 * * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, * EITHER EXPRESS 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 <stdio.h> #include <string.h> #include "securec.h" #include "bsl_err.h" #include "bsl_sal.h" #include "crypt_errno.h" #include "crypt_eal_pkey.h" #include "crypt_util_rand.h" #include "crypt_bn.h" #include "eal_pkey_local.h" #include "stub_replace.h" #include "test.h" /* END_HEADER */ /* BEGIN_CASE */ void SDV_CRYPTO_SLH_DSA_VERIFY_KAT_TC001(int id, Hex *key, Hex *addrand, Hex *msg, Hex *context, Hex *sig, int result) { TestMemInit(); CRYPT_EAL_PkeyCtx *pkey = NULL; pkey = CRYPT_EAL_PkeyNewCtx(CRYPT_PKEY_SLH_DSA); ASSERT_TRUE(pkey != NULL); int32_t algId = id; ASSERT_EQ(CRYPT_EAL_PkeySetParaById(pkey, algId), CRYPT_SUCCESS); uint32_t keyLen = 0; ASSERT_EQ(CRYPT_EAL_PkeyCtrl(pkey, CRYPT_CTRL_GET_SLH_DSA_KEY_LEN, (void *)&keyLen, sizeof(keyLen)), CRYPT_SUCCESS); if (addrand->len == 0) { int32_t isDeterministic = 1; ASSERT_EQ(CRYPT_EAL_PkeyCtrl(pkey, CRYPT_CTRL_SET_DETERMINISTIC_FLAG, (void *)&isDeterministic, sizeof(isDeterministic)), CRYPT_SUCCESS); } else { ASSERT_EQ(CRYPT_EAL_PkeyCtrl(pkey, CRYPT_CTRL_SET_SLH_DSA_ADDRAND, (void *)addrand->x, addrand->len), CRYPT_SUCCESS); } CRYPT_EAL_PkeyPrv prv; (void)memset_s(&prv, sizeof(CRYPT_EAL_PkeyPrv), 0, sizeof(CRYPT_EAL_PkeyPrv)); prv.id = CRYPT_PKEY_SLH_DSA; prv.key.slhDsaPrv.seed = key->x; prv.key.slhDsaPrv.prf = key->x + keyLen; prv.key.slhDsaPrv.pub.seed = key->x + keyLen * 2; prv.key.slhDsaPrv.pub.root = key->x + keyLen * 3; prv.key.slhDsaPrv.pub.len = keyLen; ASSERT_EQ(CRYPT_EAL_PkeySetPrv(pkey, &prv), CRYPT_SUCCESS); if (context->len != 0) { ASSERT_EQ(CRYPT_EAL_PkeyCtrl(pkey, CRYPT_CTRL_SET_CTX_INFO, context->x, context->len), CRYPT_SUCCESS); } ASSERT_EQ(CRYPT_EAL_PkeyVerify(pkey, CRYPT_MD_SHA256, msg->x, msg->len, sig->x, sig->len), result); EXIT: CRYPT_EAL_PkeyFreeCtx(pkey); return; } /* END_CASE */ /* BEGIN_CASE */ void SDV_CRYPTO_SLH_DSA_VERIFY_PREHASHED_KAT_TC001(int id, Hex *key, Hex *addrand, Hex *msg, Hex *context, int hashId, Hex *sig, int result) { TestMemInit(); CRYPT_EAL_PkeyCtx *pkey = NULL; pkey = CRYPT_EAL_PkeyNewCtx(CRYPT_PKEY_SLH_DSA); ASSERT_TRUE(pkey != NULL); int32_t algId = id; ASSERT_EQ(CRYPT_EAL_PkeySetParaById(pkey, algId), CRYPT_SUCCESS); uint32_t keyLen = 0; ASSERT_EQ(CRYPT_EAL_PkeyCtrl(pkey, CRYPT_CTRL_GET_SLH_DSA_KEY_LEN, (void *)&keyLen, sizeof(keyLen)), CRYPT_SUCCESS); if (addrand->len == 0) { int32_t isDeterministic = 1; ASSERT_EQ(CRYPT_EAL_PkeyCtrl(pkey, CRYPT_CTRL_SET_DETERMINISTIC_FLAG, (void *)&isDeterministic, sizeof(isDeterministic)), CRYPT_SUCCESS); } else { ASSERT_EQ(CRYPT_EAL_PkeyCtrl(pkey, CRYPT_CTRL_SET_SLH_DSA_ADDRAND, (void *)addrand->x, addrand->len), CRYPT_SUCCESS); } int32_t prehash = 1; ASSERT_EQ(CRYPT_EAL_PkeyCtrl(pkey, CRYPT_CTRL_SET_PREHASH_FLAG, (void *)&prehash, sizeof(prehash)), CRYPT_SUCCESS); CRYPT_EAL_PkeyPrv prv; (void)memset_s(&prv, sizeof(CRYPT_EAL_PkeyPrv), 0, sizeof(CRYPT_EAL_PkeyPrv)); prv.id = CRYPT_PKEY_SLH_DSA; prv.key.slhDsaPrv.seed = key->x; prv.key.slhDsaPrv.prf = key->x + keyLen; prv.key.slhDsaPrv.pub.seed = key->x + keyLen * 2; prv.key.slhDsaPrv.pub.root = key->x + keyLen * 3; prv.key.slhDsaPrv.pub.len = keyLen; ASSERT_EQ(CRYPT_EAL_PkeySetPrv(pkey, &prv), CRYPT_SUCCESS); if (context->len != 0) { ASSERT_EQ(CRYPT_EAL_PkeyCtrl(pkey, CRYPT_CTRL_SET_CTX_INFO, context->x, context->len), CRYPT_SUCCESS); } ASSERT_EQ(CRYPT_EAL_PkeyVerify(pkey, hashId, msg->x, msg->len, sig->x, sig->len), result); EXIT: CRYPT_EAL_PkeyFreeCtx(pkey); return; } /* END_CASE */
2301_79861745/bench_create
testcode/sdv/testcase/crypto/slh_dsa/test_suite_sdv_eal_slh_dsa1.c
C
unknown
4,459
/* * This file is part of the openHiTLS project. * * openHiTLS is licensed under the Mulan PSL v2. * You can use this software according to the terms and conditions of the Mulan PSL v2. * You may obtain a copy of Mulan PSL v2 at: * * http://license.coscl.org.cn/MulanPSL2 * * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. * See the Mulan PSL v2 for more details. */ #include "crypt_bn.h" #include "bsl_sal.h" #include "crypt_algid.h" #include "crypt_types.h" #include "crypt_eal_pkey.h" #include "crypt_errno.h" #include "stub_replace.h" #include "crypt_eal_rand.h" #include "securec.h" #include "crypt_util_rand.h" #include "crypt_encode_internal.h" #include "crypt_dsa.h" #define ERR_BAD_RAND 1 #define RAND_BUF_LEN 2048 #define UINT8_MAX_NUM 255 uint8_t g_RandOutput[RAND_BUF_LEN]; uint32_t g_RandBufLen = 0; int32_t RandFunc(uint8_t *randNum, uint32_t randLen) { for (uint32_t i = 0; i < randLen; i++) { randNum[i] = (uint8_t)(rand() % UINT8_MAX_NUM); } return 0; } int32_t RandFuncEx(void *libCtx, uint8_t *randNum, uint32_t randLen) { (void)libCtx; for (uint32_t i = 0; i < randLen; i++) { randNum[i] = (uint8_t)(rand() % UINT8_MAX_NUM); } return 0; } int32_t SetFakeRandOutput(uint8_t *in, uint32_t inLen) { g_RandBufLen = inLen; return memcpy_s(g_RandOutput, sizeof(g_RandOutput), in, inLen); } int32_t FakeRandFunc(uint8_t *randNum, uint32_t randLen) { if (randLen > RAND_BUF_LEN) { return ERR_BAD_RAND; } return memcpy_s(randNum, randLen, g_RandOutput, randLen); } int32_t FakeRandFuncEx(void *libCtx, uint8_t *randNum, uint32_t randLen) { (void)libCtx; if (randLen > RAND_BUF_LEN) { return ERR_BAD_RAND; } return memcpy_s(randNum, randLen, g_RandOutput, randLen); } int32_t STUB_RandRangeK(void *libCtx, BN_BigNum *r, const BN_BigNum *p) { (void)p; (void)libCtx; BN_Bin2Bn(r, g_RandOutput, g_RandBufLen); return CRYPT_SUCCESS; } void SetSm2PubKey(CRYPT_EAL_PkeyPub *pub, uint8_t *key, uint32_t len) { pub->id = CRYPT_PKEY_SM2; pub->key.eccPub.data = key; pub->key.eccPub.len = len; } void SetSm2PrvKey(CRYPT_EAL_PkeyPrv *prv, uint8_t *key, uint32_t len) { prv->id = CRYPT_PKEY_SM2; prv->key.eccPrv.data = key; prv->key.eccPrv.len = len; }
2301_79861745/bench_create
testcode/sdv/testcase/crypto/sm2/test_suite_sdv_eal_sm2.base.c
C
unknown
2,475
/* * This file is part of the openHiTLS project. * * openHiTLS is licensed under the Mulan PSL v2. * You can use this software according to the terms and conditions of the Mulan PSL v2. * You may obtain a copy of Mulan PSL v2 at: * * http://license.coscl.org.cn/MulanPSL2 * * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, * EITHER EXPRESS 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 test_suite_sdv_eal_sm2 */ /* BEGIN_HEADER */ #include "crypt_local_types.h" #include "crypt_sm2.h" #include "crypt_encode_internal.h" #define MAX_PLAIN_TEXT_LEN 2048 #define CIPHER_TEXT_EXTRA_LEN 97 #define CRYPT_EAL_PKEY_KEYMGMT_OPERATE 0 #define SM3_MD_SIZE 32 #define SM2_POINT_SINGLE_COORDINATE_LEN 32 #define SM2_POINT_COORDINATE_LEN 65 /* END_HEADER */ /** * @test SDV_CRYPTO_SM2_ENC_API_TC001 * @title SM2 CRYPT_EAL_PkeyEncrypt: Test the validity of input parameters. * @precon Vector: public key. * @brief * 1. Init the DRBG and create the context of the SM2 algorithm, expected result 1 * 2. Call the CRYPT_EAL_PkeyEncrypt method, where all parameters are valid, expected result 2 * 3. Set public key, expected result 3 * 4. Call the CRYPT_EAL_PkeyEncrypt method: * (1) data = NULL, dataLen != 0, expected result 4 * (2) data = NULL, dataLen = 0, expected result 5 * (3) output = NULL, outLen != 0, expected result 6 * (4) outLen = NULL, expected result 7 * (5) outLen is not enough(less than 32+97), expected result 8 * (6) all parameters are valid, expected result 9 * @expect * 1. Success, and context is not NULL. * 2. CRYPT_SM2_NO_PUBKEY * 3. CRYPT_SUCCESS * 4-7. CRYPT_NULL_INPUT * 8. CRYPT_SM2_BUFF_LEN_NOT_ENOUGH * 9. CRYPT_SUCCESS */ /* BEGIN_CASE */ void SDV_CRYPTO_SM2_ENC_API_TC001(Hex *pubKey, int isProvider) { uint8_t plainText[32]; uint8_t cipherText[141]; // 32 + 97 + 12 uint32_t outLen = sizeof(cipherText); CRYPT_EAL_PkeyPub pub = {0}; SetSm2PubKey(&pub, pubKey->x, pubKey->len); TestMemInit(); CRYPT_RandRegist(RandFunc); CRYPT_RandRegistEx(RandFuncEx); CRYPT_EAL_PkeyCtx *ctx = TestPkeyNewCtx(NULL, CRYPT_PKEY_SM2, CRYPT_EAL_PKEY_KEYMGMT_OPERATE + CRYPT_EAL_PKEY_CIPHER_OPERATE, "provider=default", isProvider); ASSERT_TRUE(ctx != NULL); ASSERT_TRUE(CRYPT_EAL_PkeyEncrypt(ctx, plainText, sizeof(plainText), cipherText, &outLen) == CRYPT_SM2_NO_PUBKEY); ASSERT_TRUE(CRYPT_EAL_PkeySetPub(ctx, &pub) == CRYPT_SUCCESS); ASSERT_TRUE(CRYPT_EAL_PkeyEncrypt(ctx, NULL, sizeof(plainText), cipherText, &outLen) == CRYPT_NULL_INPUT); ASSERT_TRUE(CRYPT_EAL_PkeyEncrypt(ctx, NULL, 0, cipherText, &outLen) == CRYPT_NULL_INPUT); ASSERT_TRUE(CRYPT_EAL_PkeyEncrypt(ctx, plainText, sizeof(plainText), NULL, &outLen) == CRYPT_NULL_INPUT); ASSERT_TRUE(CRYPT_EAL_PkeyEncrypt(ctx, plainText, sizeof(plainText), cipherText, NULL) == CRYPT_NULL_INPUT); outLen = sizeof(cipherText) - 12; ASSERT_TRUE( CRYPT_EAL_PkeyEncrypt(ctx, plainText, sizeof(plainText), cipherText, &outLen) == CRYPT_SM2_BUFF_LEN_NOT_ENOUGH); outLen = sizeof(cipherText); ASSERT_TRUE(CRYPT_EAL_PkeyEncrypt(ctx, plainText, sizeof(plainText), cipherText, &outLen) == CRYPT_SUCCESS); EXIT: CRYPT_EAL_PkeyFreeCtx(ctx); CRYPT_RandRegist(NULL); CRYPT_RandRegistEx(NULL); } /* END_CASE */ /** * @test SDV_CRYPTO_SM2_ENC_API_TC002 * @title SM2: CRYPT_EAL_PkeyEncrypt test: Random number error. * @precon Vertor: public key. * @brief * 1. Create the context of the SM2 algorithm, expected result 1. * 2. Set public key, expected result 2. * 3. Call the CRYPT_EAL_PkeyEncrypt method, where all parameters are valid, expected result 3. * 4. Register wrong rand method: FakeRandFunc(The random number it generated is 0), expected result 4. * 5. Call the CRYPT_EAL_PkeyEncrypt method, where all parameters are valid, expected result 5. * 6. Register correct rand method and Call the CRYPT_EAL_PkeyEncrypt method to signature, expected result 6. * @expect * 1. Success, and context is not NULL. * 2. CRYPT_SUCCESS * 3. CRYPT_NO_REGIST_RAND * 4. CRYPT_SUCCESS * 5. CRYPT_SM2_ERR_TRY_CNT. * 6. CRYPT_SUCCESS */ /* BEGIN_CASE */ void SDV_CRYPTO_SM2_ENC_API_TC002(Hex *pubKey, int isProvider) { uint8_t plainText[32]; uint8_t cipherText[141]; // 32 + 97 + 12 uint32_t outLen = sizeof(cipherText); uint8_t zero[100] = {0}; CRYPT_EAL_PkeyPub pub = {0}; SetSm2PubKey(&pub, pubKey->x, pubKey->len); TestMemInit(); CRYPT_EAL_PkeyCtx *ctx = TestPkeyNewCtx(NULL, CRYPT_PKEY_SM2, CRYPT_EAL_PKEY_KEYMGMT_OPERATE + CRYPT_EAL_PKEY_CIPHER_OPERATE, "provider=default", isProvider); ASSERT_TRUE(ctx != NULL); ASSERT_TRUE(CRYPT_EAL_PkeySetPub(ctx, &pub) == CRYPT_SUCCESS); ASSERT_TRUE(CRYPT_EAL_PkeyEncrypt(ctx, plainText, sizeof(plainText), cipherText, &outLen) == CRYPT_NO_REGIST_RAND); CRYPT_RandRegist(FakeRandFunc); CRYPT_RandRegistEx(FakeRandFuncEx); ASSERT_TRUE(SetFakeRandOutput(zero, sizeof(zero)) == CRYPT_SUCCESS); ASSERT_TRUE(CRYPT_EAL_PkeyEncrypt(ctx, plainText, sizeof(plainText), cipherText, &outLen) == CRYPT_SM2_ERR_TRY_CNT); CRYPT_RandRegist(RandFunc); CRYPT_RandRegistEx(RandFuncEx); ASSERT_TRUE(CRYPT_EAL_PkeyEncrypt(ctx, plainText, sizeof(plainText), cipherText, &outLen) == CRYPT_SUCCESS); EXIT: CRYPT_EAL_PkeyFreeCtx(ctx); CRYPT_RandRegist(NULL); CRYPT_RandRegistEx(NULL); } /* END_CASE */ /** * @test SDV_CRYPTO_SM2_DEC_API_TC001 * @title SM2 CRYPT_EAL_PkeyDecrypt: Test the validity of input parameters. * @precon Vector: private key, ciphertext. * @brief * 1. Create the context of the SM2 algorithm, expected result 1 * 2. Call the CRYPT_EAL_PkeyDecrypt method, where all parameters are valid, expected result 2 * 3. Set private key, expected result 3 * 4. Call the CRYPT_EAL_PkeyDecrypt method: * (1) data = NULL, dataLen != 0, expected result 4 * (2) output = NULL, outLen != 0, expected result 5 * (3) outLen = NULL, expected result 6 * (4) data = NULL, dataLen = 0, expected result 7 * (5) the length of ciphertext is too long, expected result 8 * (6) all parameters are valid, expected result 9 * @expect * 1. Success, and context is not NULL. * 2. CRYPT_SM2_NO_PRVKEY * 3. CRYPT_SUCCESS * 4-7. CRYPT_NULL_INPUT * 8. CRYPT_SM2_BUFF_LEN_NOT_ENOUGH * 9. CRYPT_SUCCESS */ /* BEGIN_CASE */ void SDV_CRYPTO_SM2_DEC_API_TC001(Hex *prvKey, Hex *cipherText, int isProvider) { uint8_t plainText[MAX_PLAIN_TEXT_LEN]; uint32_t outLen = cipherText->len; CRYPT_EAL_PkeyPrv prv = {0}; SetSm2PrvKey(&prv, prvKey->x, prvKey->len); TestRandInit(); TestMemInit(); CRYPT_EAL_PkeyCtx *ctx = TestPkeyNewCtx(NULL, CRYPT_PKEY_SM2, CRYPT_EAL_PKEY_KEYMGMT_OPERATE + CRYPT_EAL_PKEY_CIPHER_OPERATE, "provider=default", isProvider); ASSERT_TRUE(ctx != NULL); ASSERT_TRUE(CRYPT_EAL_PkeyDecrypt(ctx, cipherText->x, cipherText->len, plainText, &outLen) == CRYPT_SM2_NO_PRVKEY); ASSERT_TRUE(CRYPT_EAL_PkeySetPrv(ctx, &prv) == CRYPT_SUCCESS); ASSERT_TRUE(CRYPT_EAL_PkeyDecrypt(ctx, NULL, cipherText->len, plainText, &outLen) == CRYPT_NULL_INPUT); ASSERT_TRUE(CRYPT_EAL_PkeyDecrypt(ctx, cipherText->x, cipherText->len, NULL, &outLen) == CRYPT_NULL_INPUT); ASSERT_TRUE(CRYPT_EAL_PkeyDecrypt(ctx, cipherText->x, cipherText->len, plainText, NULL) == CRYPT_NULL_INPUT); ASSERT_TRUE(CRYPT_EAL_PkeyDecrypt(ctx, NULL, 0, plainText, &outLen) == CRYPT_NULL_INPUT); outLen = 1; ASSERT_TRUE(CRYPT_EAL_PkeyDecrypt(ctx, cipherText->x, cipherText->len, plainText, &outLen) == CRYPT_SM2_BUFF_LEN_NOT_ENOUGH); outLen = cipherText->len; ASSERT_EQ(CRYPT_EAL_PkeyDecrypt(ctx, cipherText->x, cipherText->len, plainText, &outLen), CRYPT_SUCCESS); EXIT: CRYPT_EAL_PkeyFreeCtx(ctx); TestRandDeInit(); } /* END_CASE */ /** * @test SDV_CRYPTO_SM2_CTRL_API_TC001 * @title SM2 CRYPT_EAL_PkeyCtrl test. * @precon nan * @brief * 1. Create the context of the SM2 algorithm, expected result 1 * 2. Call the CRYPT_EAL_PkeyCtrl to set sm2 hash method, expected result 2 * 2. Call the CRYPT_EAL_PkeyCtrl, opt is CRYPT_CTRL_UP_REFERENCES, len is 0, expected result 3 * @expect * 1. Success, and context is not NULL. * 2. CRYPT_ECC_PKEY_ERR_UNSUPPORTED_CTRL_OPTION * 3. CRYPT_NULL_INPUT */ /* BEGIN_CASE */ void SDV_CRYPTO_SM2_CTRL_API_TC001(int isProvider) { uint32_t ref = 1; TestMemInit(); CRYPT_EAL_PkeyCtx *ctx = TestPkeyNewCtx(NULL, CRYPT_PKEY_SM2, CRYPT_EAL_PKEY_KEYMGMT_OPERATE + CRYPT_EAL_PKEY_CIPHER_OPERATE, "provider=default", isProvider); ASSERT_TRUE(ctx != NULL); EAL_MdMethod hashMethod = {0}; ASSERT_TRUE(CRYPT_EAL_PkeyCtrl(ctx, CRYPT_CTRL_SET_RSA_EMSA_PKCSV15, &hashMethod, sizeof(EAL_MdMethod)) == CRYPT_ECC_PKEY_ERR_UNSUPPORTED_CTRL_OPTION); ASSERT_EQ(CRYPT_EAL_PkeyCtrl(ctx, CRYPT_CTRL_UP_REFERENCES, &ref, 0), CRYPT_NULL_INPUT); EXIT: CRYPT_EAL_PkeyFreeCtx(ctx); } /* END_CASE */ /** * @test SDV_CRYPTO_SM2_ENC_FUNC_TC001 * @title SM2: public key encryption. * @precon Vectors: public key, plaintext, generate random number k, ciphertext. * @brief * 1. Create the context of the SM2 algorithm, expected result 1 * 2. Set public key, expected result 2 * 3. Take over random numbers, mock BN_RandRange to generate k * 4. Call the CRYPT_EAL_PkeyEncrypt to encrypt plaintext, expected result 3 * 5. Compare the encryption result with the ciphertext vector, expected result 4 * @expect * 1. Success, and context is not NULL. * 2-3. CRYPT_SUCCESS * 4. Both are the same. */ /* BEGIN_CASE */ void SDV_CRYPTO_SM2_ENC_FUNC_TC001(Hex *pubKey, Hex *plain, Hex *k, Hex *cipher, int isProvider) { FuncStubInfo tmpRpInfo; uint8_t cipherText[MAX_PLAIN_TEXT_LEN + CIPHER_TEXT_EXTRA_LEN] = {0}; uint8_t decodeText[MAX_PLAIN_TEXT_LEN + CIPHER_TEXT_EXTRA_LEN] = {0}; uint32_t decodeLen = sizeof(decodeText); uint32_t outLen = sizeof(cipherText); CRYPT_EAL_PkeyPub pub = {0}; SetSm2PubKey(&pub, pubKey->x, pubKey->len); TestMemInit(); CRYPT_EAL_PkeyCtx *ctx = TestPkeyNewCtx(NULL, CRYPT_PKEY_SM2, CRYPT_EAL_PKEY_KEYMGMT_OPERATE + CRYPT_EAL_PKEY_CIPHER_OPERATE, "provider=default", isProvider); ASSERT_TRUE(ctx != NULL); ASSERT_EQ(CRYPT_EAL_PkeySetPub(ctx, &pub), CRYPT_SUCCESS); STUB_Init(); ASSERT_TRUE(SetFakeRandOutput(k->x, k->len) == CRYPT_SUCCESS); STUB_Replace(&tmpRpInfo, BN_RandRangeEx, STUB_RandRangeK); ASSERT_TRUE(CRYPT_EAL_PkeyEncrypt(ctx, plain->x, plain->len, cipherText, &outLen) == CRYPT_SUCCESS); CRYPT_SM2_EncryptData encData = { .x = decodeText + 1, .xLen = SM2_POINT_SINGLE_COORDINATE_LEN, .y = decodeText + SM2_POINT_SINGLE_COORDINATE_LEN + 1, .yLen = SM2_POINT_SINGLE_COORDINATE_LEN, .hash = decodeText + SM2_POINT_COORDINATE_LEN, .hashLen = SM3_MD_SIZE, .cipher = decodeText + SM2_POINT_COORDINATE_LEN + SM3_MD_SIZE, .cipherLen = decodeLen - SM2_POINT_COORDINATE_LEN - SM3_MD_SIZE - 1 }; ASSERT_TRUE(CRYPT_EAL_DecodeSm2EncryptData(cipherText, outLen, &encData) == CRYPT_SUCCESS); decodeText[0] = 0x04; ASSERT_EQ(encData.xLen + encData.yLen + encData.hashLen + encData.cipherLen + 1, cipher->len); ASSERT_TRUE(memcmp(decodeText, cipher->x, cipher->len) == 0); EXIT: CRYPT_EAL_PkeyFreeCtx(ctx); STUB_Reset(&tmpRpInfo); } /* END_CASE */ /** * @test SDV_CRYPTO_SM2_DEC_FUNC_TC001 * @title SM2: private key decryption. * @precon Vectors: private key, plaintext, ciphertext. * @brief * 1. Create the context of the SM2 algorithm, expected result 1 * 2. Set private key, expected result 2 * 3. Call the CRYPT_EAL_PkeyDecrypt to decrypt ciphertext, expected result 3 * 4. Compare the decryption result with the ciphertext vector, expected result 4 * @expect * 1. Success, and context is not NULL. * 2-3. CRYPT_SUCCESS * 4. Both are the same. */ /* BEGIN_CASE */ void SDV_CRYPTO_SM2_DEC_FUNC_TC001(Hex *prvKey, Hex *plain, Hex *cipher, int isProvider) { CRYPT_RandRegist(RandFunc); CRYPT_RandRegistEx(RandFuncEx); uint8_t plainText[MAX_PLAIN_TEXT_LEN] = {0}; uint32_t outLen = sizeof(plainText); uint8_t encodeText[MAX_PLAIN_TEXT_LEN + 20] = {0}; uint32_t encodeLen = MAX_PLAIN_TEXT_LEN + 20; CRYPT_EAL_PkeyPrv prv = {0}; SetSm2PrvKey(&prv, prvKey->x, prvKey->len); TestMemInit(); CRYPT_EAL_PkeyCtx *ctx = TestPkeyNewCtx(NULL, CRYPT_PKEY_SM2, CRYPT_EAL_PKEY_KEYMGMT_OPERATE + CRYPT_EAL_PKEY_CIPHER_OPERATE, "provider=default", isProvider); ASSERT_TRUE(ctx != NULL); ASSERT_TRUE(CRYPT_EAL_PkeySetPrv(ctx, &prv) == CRYPT_SUCCESS); CRYPT_SM2_EncryptData encData = { .x = cipher->x + 1, .xLen = SM2_POINT_SINGLE_COORDINATE_LEN, .y = cipher->x + SM2_POINT_SINGLE_COORDINATE_LEN + 1, .yLen = SM2_POINT_SINGLE_COORDINATE_LEN, .hash = cipher->x + SM2_POINT_COORDINATE_LEN, .hashLen = SM3_MD_SIZE, .cipher = cipher->x + SM2_POINT_COORDINATE_LEN + SM3_MD_SIZE, .cipherLen = cipher->len - SM2_POINT_COORDINATE_LEN - SM3_MD_SIZE }; ASSERT_EQ(CRYPT_EAL_EncodeSm2EncryptData(&encData, encodeText, &encodeLen), CRYPT_SUCCESS); ASSERT_EQ(CRYPT_EAL_PkeyDecrypt(ctx, encodeText, encodeLen, plainText, &outLen), CRYPT_SUCCESS); ASSERT_TRUE(outLen == plain->len); ASSERT_TRUE(memcmp(plainText, plain->x, plain->len) == 0); EXIT: CRYPT_RandRegist(NULL); CRYPT_RandRegistEx(NULL); CRYPT_EAL_PkeyFreeCtx(ctx); } /* END_CASE */ /** * @test SDV_CRYPTO_SM2_DECOCDE_Sm2CipherText * @title SM2: decode * @brief test SM2 ciphertext decoding */ /* BEGIN_CASE */ void SDV_CRYPTO_SM2_DECOCDE_Sm2CipherText(Hex *cipher) { ECC_Para *para = NULL; ECC_Point *c1 = NULL; uint8_t *decode = BSL_SAL_Calloc(1u, cipher->len); ASSERT_TRUE(decode != NULL); // Add uncompressed point identifier decode[0] = 0x04; CRYPT_SM2_EncryptData encData = { .x = decode + 1, // Reserve one byte for '04' .xLen = SM2_POINT_SINGLE_COORDINATE_LEN, .y = decode + SM2_POINT_SINGLE_COORDINATE_LEN + 1, .yLen = SM2_POINT_SINGLE_COORDINATE_LEN, .hash = decode + SM2_POINT_COORDINATE_LEN, .hashLen = SM3_MD_SIZE, .cipher = decode + SM2_POINT_COORDINATE_LEN + SM3_MD_SIZE, .cipherLen = cipher->len - SM2_POINT_COORDINATE_LEN - SM3_MD_SIZE }; int32_t ret = CRYPT_EAL_DecodeSm2EncryptData(cipher->x, cipher->len, &encData); ASSERT_EQ(ret, CRYPT_SUCCESS); para = ECC_NewPara(CRYPT_ECC_SM2); ASSERT_TRUE(para != NULL); c1 = ECC_NewPoint(para); ASSERT_TRUE(c1 != NULL); ASSERT_EQ(ECC_DecodePoint(para, c1, decode, SM2_POINT_COORDINATE_LEN), CRYPT_SUCCESS); EXIT: BSL_SAL_Free(decode); ECC_FreePoint(c1); ECC_FreePara(para); } /* END_CASE */ /** * @test SDV_CRYPTO_SM2_DEC_FUNC_TC002 * @title SM2: Private key decryption failure scenario. * @precon Vectors: private key, ciphertext. * @brief * 1. Create the context of the SM2 algorithm, expected result 1 * 2. Set private key, expected result 2 * 3. Call the CRYPT_EAL_PkeyDecrypt to decrypt ciphertext, expected result 3 * @expect * 1. Success, and context is not NULL. * 2. CRYPT_SUCCESS * 3. Failure. */ /* BEGIN_CASE */ void SDV_CRYPTO_SM2_DEC_FUNC_TC002(Hex *prvKey, Hex *cipher, int isProvider) { TestMemInit(); uint8_t plainText[MAX_PLAIN_TEXT_LEN]; uint32_t outLen = sizeof(plainText); CRYPT_EAL_PkeyPrv prv = {0}; SetSm2PrvKey(&prv, prvKey->x, prvKey->len); CRYPT_EAL_PkeyCtx *ctx = TestPkeyNewCtx(NULL, CRYPT_PKEY_SM2, CRYPT_EAL_PKEY_KEYMGMT_OPERATE + CRYPT_EAL_PKEY_CIPHER_OPERATE, "provider=default", isProvider); ASSERT_TRUE(ctx != NULL); ASSERT_TRUE(CRYPT_EAL_PkeySetPrv(ctx, &prv) == CRYPT_SUCCESS); /* Different error codes are returned for different phases. */ ASSERT_TRUE(CRYPT_EAL_PkeyDecrypt(ctx, cipher->x, cipher->len, plainText, &outLen) != CRYPT_SUCCESS); EXIT: CRYPT_EAL_PkeyFreeCtx(ctx); } /* END_CASE */ /** * @test SDV_CRYPTO_SM2_GEN_CRYPT_FUNC_TC001 * @title SM2: Generate key pair, encryption, decryption. * @precon Vector: plaintext. * @brief * 1. Create the context of the SM2 algorithm, expected result 1 * 2. Initialize the DRBG. * 3. Call the CRYPT_EAL_PkeyGen to generate a key pair, expected result 2 * 4. Call the CRYPT_EAL_PkeyEncrypt to encrypt plaintext, expected result 3 * 5. Call the CRYPT_EAL_PkeyDecrypt to decrypt ciphertext, expected result 4 * 6. Compare the decryption result with the plaintext vector, expected result 5 * @expect * 1. Success, and context is not NULL. * 2-4. CRYPT_SUCCESS * 5. Both are the same. */ /* BEGIN_CASE */ void SDV_CRYPTO_SM2_GEN_CRYPT_FUNC_TC001(Hex *msg, int isProvider) { uint8_t cipherText[MAX_PLAIN_TEXT_LEN + CIPHER_TEXT_EXTRA_LEN]; uint8_t plainText[MAX_PLAIN_TEXT_LEN]; uint32_t ctLen = sizeof(cipherText); uint32_t ptLen = sizeof(plainText); TestMemInit(); CRYPT_EAL_PkeyCtx *ctx = TestPkeyNewCtx(NULL, CRYPT_PKEY_SM2, CRYPT_EAL_PKEY_KEYMGMT_OPERATE + CRYPT_EAL_PKEY_CIPHER_OPERATE, "provider=default", isProvider); ASSERT_TRUE(ctx != NULL); CRYPT_RandRegist(RandFunc); CRYPT_RandRegistEx(RandFuncEx); ASSERT_TRUE(CRYPT_EAL_PkeyGen(ctx) == CRYPT_SUCCESS); ASSERT_TRUE(CRYPT_EAL_PkeyEncrypt(ctx, msg->x, msg->len, cipherText, &ctLen) == CRYPT_SUCCESS); ASSERT_TRUE(CRYPT_EAL_PkeyDecrypt(ctx, cipherText, ctLen, plainText, &ptLen) == CRYPT_SUCCESS); ASSERT_TRUE(ptLen == msg->len); ASSERT_TRUE(memcmp(plainText, msg->x, msg->len) == 0); EXIT: CRYPT_RandRegist(NULL); CRYPT_RandRegistEx(NULL); CRYPT_EAL_PkeyFreeCtx(ctx); } /* END_CASE */ /** * @test SDV_CRYPTO_SM2_GEN_CRYPT_FUNC_TC002 * @title SM2: The input and output parameters address are the same. * @precon Vector: plaintext. * @brief * 1. Create the context of the SM2 algorithm, expected result 1 * 2. Initialize the DRBG. * 3. Call the CRYPT_EAL_PkeyGen to generate a key pair, expected result 2 * 4. Call the CRYPT_EAL_PkeyEncrypt, and the input and output parameters address are the same, expected result 3 * 5. Call the CRYPT_EAL_PkeyDecrypt, and the input and output parameters address are the same, expected result 4 * 6. Compare the decryption result with the plaintext vector, expected result 5 * @expect * 1. Success, and context is not NULL. * 2-4. CRYPT_SUCCESS * 5. Both are the same. */ /* BEGIN_CASE */ void SDV_CRYPTO_SM2_GEN_CRYPT_FUNC_TC002(Hex *msg, int isProvider) { uint8_t buf[MAX_PLAIN_TEXT_LEN + CIPHER_TEXT_EXTRA_LEN]; uint32_t ctLen = sizeof(buf); uint32_t ptLen = sizeof(buf); ASSERT_TRUE(memcpy_s(buf, ptLen, msg->x, msg->len) == CRYPT_SUCCESS); TestMemInit(); CRYPT_EAL_PkeyCtx *ctx = TestPkeyNewCtx(NULL, CRYPT_PKEY_SM2, CRYPT_EAL_PKEY_KEYMGMT_OPERATE + CRYPT_EAL_PKEY_CIPHER_OPERATE, "provider=default", isProvider); ASSERT_TRUE(ctx != NULL); CRYPT_RandRegist(RandFunc); CRYPT_RandRegistEx(RandFuncEx); ASSERT_TRUE(CRYPT_EAL_PkeyGen(ctx) == CRYPT_SUCCESS); ASSERT_TRUE(CRYPT_EAL_PkeyEncrypt(ctx, buf, msg->len, buf, &ctLen) == CRYPT_SUCCESS); ASSERT_TRUE(CRYPT_EAL_PkeyDecrypt(ctx, buf, ctLen, buf, &ptLen) == CRYPT_SUCCESS); ASSERT_TRUE(ptLen == msg->len); ASSERT_TRUE(memcmp(buf, msg->x, msg->len) == 0); EXIT: CRYPT_RandRegist(NULL); CRYPT_RandRegistEx(NULL); CRYPT_EAL_PkeyFreeCtx(ctx); } /* END_CASE */ /** * @test SDV_CRYPTO_SM2_CMP_FUNC_TC001 * @title SM2: The input and output parameters address are the same. * @precon Vector: private key and public key. * @brief * 1. Create the contexts(ctx1, ctx2) of the SM2 algorithm, expected result 1 * 2. Call the CRYPT_EAL_PkeyCmp to compare ctx1 and ctx2, expected result 2 * 3. Set public key for ctx1, expected result 3 * 4. Call the CRYPT_EAL_PkeyCmp to compare ctx1 and ctx2, expected result 4 * 5. Set public key for ctx2, expected result 5 * 6. Call the CRYPT_EAL_PkeyCmp to compare ctx1 and ctx2, expected result 6 * @expect * 1. Success, and contexts are not NULL. * 2. CRYPT_ECC_KEY_PUBKEY_NOT_EQUAL * 3. CRYPT_SUCCESS * 4. CRYPT_ECC_KEY_PUBKEY_NOT_EQUAL * 5-6. CRYPT_SUCCESS */ /* BEGIN_CASE */ void SDV_CRYPTO_SM2_CMP_FUNC_TC001(Hex *pubKey, int isProvider) { CRYPT_EAL_PkeyPub pub = {0}; SetSm2PubKey(&pub, pubKey->x, pubKey->len); TestMemInit(); CRYPT_EAL_PkeyCtx *ctx1 = TestPkeyNewCtx(NULL, CRYPT_PKEY_SM2, CRYPT_EAL_PKEY_KEYMGMT_OPERATE + CRYPT_EAL_PKEY_CIPHER_OPERATE, "provider=default", isProvider); CRYPT_EAL_PkeyCtx *ctx2 = TestPkeyNewCtx(NULL, CRYPT_PKEY_SM2, CRYPT_EAL_PKEY_KEYMGMT_OPERATE + CRYPT_EAL_PKEY_CIPHER_OPERATE, "provider=default", isProvider); ASSERT_TRUE(ctx1 != NULL && ctx2 != NULL); ASSERT_EQ(CRYPT_EAL_PkeyCmp(ctx1, ctx2), CRYPT_ECC_KEY_PUBKEY_NOT_EQUAL); ASSERT_EQ(CRYPT_EAL_PkeySetPub(ctx1, &pub), CRYPT_SUCCESS); ASSERT_EQ(CRYPT_EAL_PkeyCmp(ctx1, ctx2), CRYPT_ECC_KEY_PUBKEY_NOT_EQUAL); ASSERT_EQ(CRYPT_EAL_PkeySetPub(ctx2, &pub), CRYPT_SUCCESS); ASSERT_EQ(CRYPT_EAL_PkeyCmp(ctx1, ctx2), CRYPT_SUCCESS); EXIT: CRYPT_EAL_PkeyFreeCtx(ctx1); CRYPT_EAL_PkeyFreeCtx(ctx2); } /* END_CASE */ /** * @test SDV_CRYPTO_SM2_ENC_DECODE_FUNC_TC001 * @title SM2: for testing sm2 ciphertext decode. * @precon Vector: SM2 ciphertext. * @brief * 1. Call the CRYPT_EAL_DecodeSm2EncryptData to decode the SM2 ciphertext * @expect * 1. CRYPT_SUCCESS */ /* BEGIN_CASE */ void SDV_CRYPTO_SM2_ENC_DECODE_FUNC_TC001(Hex *cipher) { uint8_t decode[MAX_PLAIN_TEXT_LEN] = {0}; uint32_t decodelen = MAX_PLAIN_TEXT_LEN; CRYPT_SM2_EncryptData encData = { .x = decode, .xLen = SM2_POINT_SINGLE_COORDINATE_LEN, .y = decode + SM2_POINT_SINGLE_COORDINATE_LEN, .yLen = SM2_POINT_SINGLE_COORDINATE_LEN, .hash = decode + SM2_POINT_COORDINATE_LEN, .hashLen = SM3_MD_SIZE, .cipher = decode + SM2_POINT_COORDINATE_LEN + SM3_MD_SIZE, .cipherLen = decodelen - SM2_POINT_COORDINATE_LEN - SM3_MD_SIZE }; ASSERT_EQ(CRYPT_EAL_DecodeSm2EncryptData(cipher->x, cipher->len, &encData), CRYPT_SUCCESS); EXIT: return; } /* END_CASE */
2301_79861745/bench_create
testcode/sdv/testcase/crypto/sm2/test_suite_sdv_eal_sm2_crypt.c
C
unknown
22,857
/* * This file is part of the openHiTLS project. * * openHiTLS is licensed under the Mulan PSL v2. * You can use this software according to the terms and conditions of the Mulan PSL v2. * You may obtain a copy of Mulan PSL v2 at: * * http://license.coscl.org.cn/MulanPSL2 * * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, * EITHER EXPRESS 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 test_suite_sdv_eal_sm2 */ /* BEGIN_HEADER */ #include "eal_pkey_local.h" /* END_HEADER */ #define CRYPT_EAL_PKEY_KEYMGMT_OPERATE 0 /** * @test SDV_CRYPTO_SM2_EXCHANGE_API_TC001 * @title SM2: CRYPT_EAL_PkeyComputeShareKey Test: R is not set. * @precon Test Vectors for SM2: public key, private key * @brief * 1. Init the Drbg and create two contexts(ctx1, ctx2) of the SM2 algorithm, expected result 1. * 2. ctx1: set userId, server, private key and generate r, expected result 2. * 3. ctx2: set userId and public key, expected result 3. * 4. Call the CRYPT_EAL_PkeyComputeShareKey method, expected result 4. * @expect * 1. Success, and two contexts are not NULL. * 2-3. CRYPT_SUCCESS * 4. CRYPT_SM2_R_NOT_SET */ /* BEGIN_CASE */ void SDV_CRYPTO_SM2_EXCHANGE_API_TC001(Hex *prvKey, Hex *pubKey, int isProvider) { uint8_t userId[10] = {0}; uint8_t localR[65]; int32_t server = 1; uint8_t out[64]; uint32_t outLen = sizeof(out); CRYPT_EAL_PkeyPrv prv = {0}; CRYPT_EAL_PkeyPub pub = {0}; TestMemInit(); CRYPT_RandRegist(RandFunc); CRYPT_RandRegistEx(RandFuncEx); CRYPT_EAL_PkeyCtx *ctx1 = TestPkeyNewCtx(NULL, CRYPT_PKEY_SM2, CRYPT_EAL_PKEY_KEYMGMT_OPERATE + CRYPT_EAL_PKEY_EXCH_OPERATE, "provider=default", isProvider); CRYPT_EAL_PkeyCtx *ctx2 = TestPkeyNewCtx(NULL, CRYPT_PKEY_SM2, CRYPT_EAL_PKEY_KEYMGMT_OPERATE + CRYPT_EAL_PKEY_EXCH_OPERATE, "provider=default", isProvider); ASSERT_TRUE(ctx1 != NULL); ASSERT_TRUE(ctx2 != NULL); SetSm2PrvKey(&prv, prvKey->x, prvKey->len); SetSm2PubKey(&pub, pubKey->x, pubKey->len); ASSERT_TRUE(CRYPT_EAL_PkeyCtrl(ctx1, CRYPT_CTRL_SET_SM2_USER_ID, userId, sizeof(userId)) == CRYPT_SUCCESS); ASSERT_TRUE(CRYPT_EAL_PkeyCtrl(ctx1, CRYPT_CTRL_SET_SM2_SERVER, &server, sizeof(int32_t)) == CRYPT_SUCCESS); ASSERT_TRUE(CRYPT_EAL_PkeyCtrl(ctx1, CRYPT_CTRL_GENE_SM2_R, localR, sizeof(localR)) == CRYPT_SUCCESS); ASSERT_TRUE(CRYPT_EAL_PkeySetPrv(ctx1, &prv) == CRYPT_SUCCESS); ASSERT_TRUE(CRYPT_EAL_PkeyCtrl(ctx2, CRYPT_CTRL_SET_SM2_USER_ID, userId, sizeof(userId)) == CRYPT_SUCCESS); ASSERT_TRUE(CRYPT_EAL_PkeySetPub(ctx2, &pub) == CRYPT_SUCCESS); ASSERT_TRUE(CRYPT_EAL_PkeyComputeShareKey(ctx1, ctx2, out, &outLen) == CRYPT_SM2_R_NOT_SET); EXIT: CRYPT_EAL_PkeyFreeCtx(ctx1); CRYPT_EAL_PkeyFreeCtx(ctx2); CRYPT_RandRegist(NULL); CRYPT_RandRegistEx(NULL); } /* END_CASE */ /** * @test SDV_CRYPTO_SM2_EXCHANGE_API_TC002 * @title SM2: CRYPT_EAL_PkeyComputeShareKey Test: R is not generate. * @precon Test Vectors for SM2: public key, private key, R. * @brief * 1. Init the Drbg and create two contexts(ctx1, ctx2) of the SM2 algorithm, expected result 1. * 2. ctx1: set userId, server and private key, expected result 2. * 3. ctx2: set userId, R and public key, expected result 3. * 4. Call the CRYPT_EAL_PkeyComputeShareKey method, expected result 4. * @expect * 1. Success, and two contexts are not NULL. * 2-3. CRYPT_SUCCESS * 4. CRYPT_SM2_R_NOT_SET */ /* BEGIN_CASE */ void SDV_CRYPTO_SM2_EXCHANGE_API_TC002(Hex *prvKey, Hex *pubKey, Hex *R, int isProvider) { TestMemInit(); CRYPT_RandRegist(RandFunc); CRYPT_RandRegistEx(RandFuncEx); uint8_t userId[10] = {0}; int32_t server = 1; uint8_t out[64]; uint32_t outLen = sizeof(out); CRYPT_EAL_PkeyPrv prv = {0}; CRYPT_EAL_PkeyPub pub = {0}; CRYPT_EAL_PkeyCtx *ctx1 = TestPkeyNewCtx(NULL, CRYPT_PKEY_SM2, CRYPT_EAL_PKEY_KEYMGMT_OPERATE + CRYPT_EAL_PKEY_EXCH_OPERATE, "provider=default", isProvider); CRYPT_EAL_PkeyCtx *ctx2 = TestPkeyNewCtx(NULL, CRYPT_PKEY_SM2, CRYPT_EAL_PKEY_KEYMGMT_OPERATE + CRYPT_EAL_PKEY_EXCH_OPERATE, "provider=default", isProvider); ASSERT_TRUE(ctx1 != NULL); ASSERT_TRUE(ctx2 != NULL); SetSm2PrvKey(&prv, prvKey->x, prvKey->len); SetSm2PubKey(&pub, pubKey->x, pubKey->len); ASSERT_TRUE(CRYPT_EAL_PkeyCtrl(ctx1, CRYPT_CTRL_SET_SM2_USER_ID, userId, sizeof(userId)) == CRYPT_SUCCESS); ASSERT_TRUE(CRYPT_EAL_PkeyCtrl(ctx1, CRYPT_CTRL_SET_SM2_SERVER, &server, sizeof(int32_t)) == CRYPT_SUCCESS); ASSERT_TRUE(CRYPT_EAL_PkeySetPrv(ctx1, &prv) == CRYPT_SUCCESS); ASSERT_TRUE(CRYPT_EAL_PkeyCtrl(ctx2, CRYPT_CTRL_SET_SM2_USER_ID, userId, sizeof(userId)) == CRYPT_SUCCESS); ASSERT_TRUE(CRYPT_EAL_PkeyCtrl(ctx2, CRYPT_CTRL_SET_SM2_R, R->x, R->len) == CRYPT_SUCCESS); ASSERT_TRUE(CRYPT_EAL_PkeySetPub(ctx2, &pub) == CRYPT_SUCCESS); ASSERT_TRUE(CRYPT_EAL_PkeyComputeShareKey(ctx1, ctx2, out, &outLen) == CRYPT_SM2_R_NOT_SET); EXIT: CRYPT_EAL_PkeyFreeCtx(ctx1); CRYPT_EAL_PkeyFreeCtx(ctx2); CRYPT_RandRegist(NULL); CRYPT_RandRegistEx(NULL); } /* END_CASE */ /** * @test SDV_CRYPTO_SM2_EXCHANGE_API_TC003 * @title SM2: CRYPT_EAL_PkeyComputeShareKey Test: UserId is not set at the local end. * @precon Test Vectors for SM2: public key, private key, R. * @brief * 1. Init the Drbg and create two contexts(ctx1, ctx2) of the SM2 algorithm, expected result 1. * 2. ctx1: set server, private key and generate r, expected result 2. * 3. ctx2: set userId, R and public key, expected result 3. * @expect * 1. Success, and two contexts are not NULL. * 2-3. CRYPT_SUCCESS */ /* BEGIN_CASE */ void SDV_CRYPTO_SM2_EXCHANGE_API_TC003(Hex *prvKey, Hex *pubKey, Hex *R, int isProvider) { uint8_t userId[10] = {0}; int32_t server = 1; uint8_t localR[65]; CRYPT_EAL_PkeyPrv prv = {0}; CRYPT_EAL_PkeyPub pub = {0}; TestMemInit(); CRYPT_RandRegist(RandFunc); CRYPT_RandRegistEx(RandFuncEx); CRYPT_EAL_PkeyCtx *ctx1 = TestPkeyNewCtx(NULL, CRYPT_PKEY_SM2, CRYPT_EAL_PKEY_KEYMGMT_OPERATE + CRYPT_EAL_PKEY_EXCH_OPERATE, "provider=default", isProvider); CRYPT_EAL_PkeyCtx *ctx2 = TestPkeyNewCtx(NULL, CRYPT_PKEY_SM2, CRYPT_EAL_PKEY_KEYMGMT_OPERATE + CRYPT_EAL_PKEY_EXCH_OPERATE, "provider=default", isProvider); ASSERT_TRUE(ctx1 != NULL); ASSERT_TRUE(ctx2 != NULL); SetSm2PrvKey(&prv, prvKey->x, prvKey->len); SetSm2PubKey(&pub, pubKey->x, pubKey->len); ASSERT_TRUE(CRYPT_EAL_PkeyCtrl(ctx1, CRYPT_CTRL_SET_SM2_SERVER, &server, sizeof(int32_t)) == CRYPT_SUCCESS); ASSERT_TRUE(CRYPT_EAL_PkeyCtrl(ctx1, CRYPT_CTRL_GENE_SM2_R, localR, sizeof(localR)) == CRYPT_SUCCESS); ASSERT_TRUE(CRYPT_EAL_PkeySetPrv(ctx1, &prv) == CRYPT_SUCCESS); ASSERT_TRUE(CRYPT_EAL_PkeyCtrl(ctx2, CRYPT_CTRL_SET_SM2_USER_ID, userId, sizeof(userId)) == CRYPT_SUCCESS); ASSERT_TRUE(CRYPT_EAL_PkeyCtrl(ctx2, CRYPT_CTRL_SET_SM2_R, R->x, R->len) == CRYPT_SUCCESS); ASSERT_TRUE(CRYPT_EAL_PkeySetPub(ctx2, &pub) == CRYPT_SUCCESS); EXIT: CRYPT_EAL_PkeyFreeCtx(ctx1); CRYPT_EAL_PkeyFreeCtx(ctx2); CRYPT_RandRegist(NULL); CRYPT_RandRegistEx(NULL); } /* END_CASE */ /** * @test SDV_CRYPTO_SM2_EXCHANGE_API_TC004 * @title SM2: CRYPT_EAL_PkeyComputeShareKey Test: UserId is not set at the peer end. * @precon Test Vectors for SM2: public key, private key, R. * @brief * 1. Init the Drbg and create two contexts(ctx1, ctx2) of the SM2 algorithm, expected result 1. * 2. ctx1: set userId, server, private key and generate r, expected result 2. * 3. ctx2: set R and public key, expected result 3. * @expect * 1. Success, and two contexts are not NULL. * 2-3. CRYPT_SUCCESS */ /* BEGIN_CASE */ void SDV_CRYPTO_SM2_EXCHANGE_API_TC004(Hex *prvKey, Hex *pubKey, Hex *R, int isProvider) { TestMemInit(); CRYPT_RandRegist(RandFunc); CRYPT_RandRegistEx(RandFuncEx); uint8_t userId[10] = {0}; int32_t server = 1; uint8_t localR[65]; CRYPT_EAL_PkeyPrv prv = {0}; CRYPT_EAL_PkeyPub pub = {0}; CRYPT_EAL_PkeyCtx *ctx1 = TestPkeyNewCtx(NULL, CRYPT_PKEY_SM2, CRYPT_EAL_PKEY_KEYMGMT_OPERATE + CRYPT_EAL_PKEY_EXCH_OPERATE, "provider=default", isProvider); CRYPT_EAL_PkeyCtx *ctx2 = TestPkeyNewCtx(NULL, CRYPT_PKEY_SM2, CRYPT_EAL_PKEY_KEYMGMT_OPERATE + CRYPT_EAL_PKEY_EXCH_OPERATE, "provider=default", isProvider); ASSERT_TRUE(ctx1 != NULL); ASSERT_TRUE(ctx2 != NULL); SetSm2PrvKey(&prv, prvKey->x, prvKey->len); SetSm2PubKey(&pub, pubKey->x, pubKey->len); ASSERT_TRUE(CRYPT_EAL_PkeyCtrl(ctx1, CRYPT_CTRL_SET_SM2_USER_ID, userId, sizeof(userId)) == CRYPT_SUCCESS); ASSERT_TRUE(CRYPT_EAL_PkeyCtrl(ctx1, CRYPT_CTRL_SET_SM2_SERVER, &server, sizeof(int32_t)) == CRYPT_SUCCESS); ASSERT_TRUE(CRYPT_EAL_PkeyCtrl(ctx1, CRYPT_CTRL_GENE_SM2_R, localR, sizeof(localR)) == CRYPT_SUCCESS); ASSERT_TRUE(CRYPT_EAL_PkeySetPrv(ctx1, &prv) == CRYPT_SUCCESS); ASSERT_TRUE(CRYPT_EAL_PkeyCtrl(ctx2, CRYPT_CTRL_SET_SM2_R, R->x, R->len) == CRYPT_SUCCESS); ASSERT_TRUE(CRYPT_EAL_PkeySetPub(ctx2, &pub) == CRYPT_SUCCESS); EXIT: CRYPT_EAL_PkeyFreeCtx(ctx1); CRYPT_EAL_PkeyFreeCtx(ctx2); CRYPT_RandRegist(NULL); CRYPT_RandRegistEx(NULL); } /* END_CASE */ /** * @test SDV_CRYPTO_SM2_EXCHANGE_API_TC005 * @title SM2: CRYPT_EAL_PkeyComputeShareKey Test: UserId is not set at the peer end. * @precon Test Vectors for SM2: public key, private key, R. * @brief * 1. Init the Drbg and create two contexts(ctx1, ctx2) of the SM2 algorithm, expected result 1. * 2. ctx1: set userId, server, private key and generate r, expected result 2. * 3. ctx2: set R, server and public key, expected result 3. * 4. Call the CRYPT_EAL_PkeyComputeShareKey method, expected result 4. * 5. Set client and generate R for ctx1, set client for ctx2, expected result 5. * 6. Call the CRYPT_EAL_PkeyComputeShareKey method, expected result 6. * @expect * 1. Success, and two contexts are not NULL. * 2-6. CRYPT_SUCCESS */ /* BEGIN_CASE */ void SDV_CRYPTO_SM2_EXCHANGE_API_TC005(Hex *prvKey, Hex *pubKey, Hex *R, int isProvider) { uint8_t userId[10] = {0}; int32_t server = 1; uint8_t out[64]; uint8_t localR[65]; uint32_t outLen = sizeof(out); CRYPT_EAL_PkeyPrv prv = {0}; CRYPT_EAL_PkeyPub pub = {0}; TestMemInit(); CRYPT_RandRegist(RandFunc); CRYPT_RandRegistEx(RandFuncEx); CRYPT_EAL_PkeyCtx *ctx1 = TestPkeyNewCtx(NULL, CRYPT_PKEY_SM2, CRYPT_EAL_PKEY_KEYMGMT_OPERATE + CRYPT_EAL_PKEY_EXCH_OPERATE, "provider=default", isProvider); CRYPT_EAL_PkeyCtx *ctx2 = TestPkeyNewCtx(NULL, CRYPT_PKEY_SM2, CRYPT_EAL_PKEY_KEYMGMT_OPERATE + CRYPT_EAL_PKEY_EXCH_OPERATE, "provider=default", isProvider); ASSERT_TRUE(ctx1 != NULL); ASSERT_TRUE(ctx2 != NULL); SetSm2PrvKey(&prv, prvKey->x, prvKey->len); SetSm2PubKey(&pub, pubKey->x, pubKey->len); ASSERT_TRUE(CRYPT_EAL_PkeyCtrl(ctx1, CRYPT_CTRL_SET_SM2_USER_ID, userId, sizeof(userId)) == CRYPT_SUCCESS); ASSERT_TRUE(CRYPT_EAL_PkeyCtrl(ctx1, CRYPT_CTRL_SET_SM2_SERVER, &server, sizeof(int32_t)) == CRYPT_SUCCESS); ASSERT_TRUE(CRYPT_EAL_PkeyCtrl(ctx1, CRYPT_CTRL_GENE_SM2_R, localR, sizeof(localR)) == CRYPT_SUCCESS); ASSERT_TRUE(CRYPT_EAL_PkeySetPrv(ctx1, &prv) == CRYPT_SUCCESS); ASSERT_TRUE(CRYPT_EAL_PkeyCtrl(ctx2, CRYPT_CTRL_SET_SM2_USER_ID, userId, sizeof(userId)) == CRYPT_SUCCESS); ASSERT_TRUE(CRYPT_EAL_PkeyCtrl(ctx2, CRYPT_CTRL_SET_SM2_SERVER, &server, sizeof(int32_t)) == CRYPT_SUCCESS); ASSERT_TRUE(CRYPT_EAL_PkeyCtrl(ctx2, CRYPT_CTRL_SET_SM2_R, R->x, R->len) == CRYPT_SUCCESS); ASSERT_TRUE(CRYPT_EAL_PkeySetPub(ctx2, &pub) == CRYPT_SUCCESS); ASSERT_TRUE(CRYPT_EAL_PkeyComputeShareKey(ctx1, ctx2, out, &outLen) == CRYPT_SUCCESS); server = 0; ASSERT_TRUE(CRYPT_EAL_PkeyCtrl(ctx1, CRYPT_CTRL_SET_SM2_SERVER, &server, sizeof(int32_t)) == CRYPT_SUCCESS); ASSERT_TRUE(CRYPT_EAL_PkeyCtrl(ctx1, CRYPT_CTRL_GENE_SM2_R, localR, sizeof(localR)) == CRYPT_SUCCESS); ASSERT_TRUE(CRYPT_EAL_PkeyCtrl(ctx2, CRYPT_CTRL_SET_SM2_SERVER, &server, sizeof(int32_t)) == CRYPT_SUCCESS); ASSERT_TRUE(CRYPT_EAL_PkeyComputeShareKey(ctx1, ctx2, out, &outLen) == CRYPT_SUCCESS); EXIT: CRYPT_EAL_PkeyFreeCtx(ctx1); CRYPT_EAL_PkeyFreeCtx(ctx2); CRYPT_RandRegist(NULL); CRYPT_RandRegistEx(NULL); } /* END_CASE */ /** * @test SDV_CRYPTO_SM2_EXCHANGE_API_TC006 * @title SM2: CRYPT_EAL_PkeyComputeShareKey Test: Test the validity of input parameters. * @precon Test Vectors for SM2: public key, private key, R. * @brief * 1. Init the Drbg and create two contexts(ctx1, ctx2) of the SM2 algorithm, expected result 1. * 2. ctx1: set userId, server, private key and generate r, expected result 2. * 3. ctx2: set userId, R and public key, expected result 3. * 4. Call the CRYPT_EAL_PkeyComputeShareKey method: * (1) ctx1 = NULL, expected result 4. * (2) ctx2 = NULL, expected result 5. * (3) out = NULL, expected result 6. * (4) outLen = NULL, expected result 7. * (5) outLen = 0, expected result 8. * @expect * 1. Success, and two contexts are not NULL. * 2-3. CRYPT_SUCCESS * 4. CRYPT_NULL_INPUT */ /* BEGIN_CASE */ void SDV_CRYPTO_SM2_EXCHANGE_API_TC006(Hex *prvKey, Hex *pubKey, Hex *R, int isProvider) { uint8_t userId[10] = {0}; int32_t server = 1; uint8_t out[64]; uint8_t localR[65]; uint32_t outLen = sizeof(out); CRYPT_EAL_PkeyPrv prv = {0}; CRYPT_EAL_PkeyPub pub = {0}; TestMemInit(); CRYPT_RandRegist(RandFunc); CRYPT_RandRegistEx(RandFuncEx); CRYPT_EAL_PkeyCtx *ctx1 = TestPkeyNewCtx(NULL, CRYPT_PKEY_SM2, CRYPT_EAL_PKEY_KEYMGMT_OPERATE + CRYPT_EAL_PKEY_EXCH_OPERATE, "provider=default", isProvider); CRYPT_EAL_PkeyCtx *ctx2 = TestPkeyNewCtx(NULL, CRYPT_PKEY_SM2, CRYPT_EAL_PKEY_KEYMGMT_OPERATE + CRYPT_EAL_PKEY_EXCH_OPERATE, "provider=default", isProvider); ASSERT_TRUE(ctx1 != NULL); ASSERT_TRUE(ctx2 != NULL); SetSm2PrvKey(&prv, prvKey->x, prvKey->len); SetSm2PubKey(&pub, pubKey->x, pubKey->len); ASSERT_TRUE(CRYPT_EAL_PkeyCtrl(ctx1, CRYPT_CTRL_SET_SM2_USER_ID, userId, sizeof(userId)) == CRYPT_SUCCESS); ASSERT_TRUE(CRYPT_EAL_PkeyCtrl(ctx1, CRYPT_CTRL_SET_SM2_SERVER, &server, sizeof(int32_t)) == CRYPT_SUCCESS); ASSERT_TRUE(CRYPT_EAL_PkeyCtrl(ctx1, CRYPT_CTRL_GENE_SM2_R, localR, sizeof(localR)) == CRYPT_SUCCESS); ASSERT_TRUE(CRYPT_EAL_PkeySetPrv(ctx1, &prv) == CRYPT_SUCCESS); ASSERT_TRUE(CRYPT_EAL_PkeyCtrl(ctx2, CRYPT_CTRL_SET_SM2_USER_ID, userId, sizeof(userId)) == CRYPT_SUCCESS); ASSERT_TRUE(CRYPT_EAL_PkeyCtrl(ctx2, CRYPT_CTRL_SET_SM2_R, R->x, R->len) == CRYPT_SUCCESS); ASSERT_TRUE(CRYPT_EAL_PkeySetPub(ctx2, &pub) == CRYPT_SUCCESS); ASSERT_TRUE(CRYPT_EAL_PkeyComputeShareKey(NULL, ctx2, out, &outLen) == CRYPT_NULL_INPUT); ASSERT_TRUE(CRYPT_EAL_PkeyComputeShareKey(ctx1, NULL, out, &outLen) == CRYPT_NULL_INPUT); ASSERT_TRUE(CRYPT_EAL_PkeyComputeShareKey(ctx1, ctx2, NULL, &outLen) == CRYPT_NULL_INPUT); ASSERT_TRUE(CRYPT_EAL_PkeyComputeShareKey(ctx1, ctx2, out, NULL) == CRYPT_NULL_INPUT); outLen = 0; ASSERT_TRUE(CRYPT_EAL_PkeyComputeShareKey(ctx1, ctx2, out, &outLen) == CRYPT_NULL_INPUT); EXIT: CRYPT_EAL_PkeyFreeCtx(ctx1); CRYPT_EAL_PkeyFreeCtx(ctx2); CRYPT_RandRegist(NULL); CRYPT_RandRegistEx(NULL); } /* END_CASE */ /** * @test SDV_CRYPTO_SM2_EXCHANGE_API_TC007 * @title SM2: CRYPT_EAL_PkeyComputeShareKey Test: Test the validity of input parameters. * @precon Test Vectors for SM2: public key, private key, R. * @brief * 1. Init the Drbg and create two contexts(ctx1, ctx2) of the SM2 algorithm, expected result 1. * 2. ctx1: set userId, server, private key and generate r, expected result 2. * 3. ctx2: set userId, R and private key, expected result 3. * 4. Call the CRYPT_EAL_PkeyComputeShareKey method, expected result 4. * 5. Set public key for ctx1 and ctx2, expected result 5. * 6. Generate R for ctx1, expected result 6. * 7. Call the CRYPT_EAL_PkeyComputeShareKey method, expected result 7. * @expect * 1. Success, and two contexts are not NULL. * 2-3. CRYPT_SUCCESS * 4. CRYPT_SM2_ERR_EMPTY_KEY * 5-7. CRYPT_SUCCESS */ /* BEGIN_CASE */ void SDV_CRYPTO_SM2_EXCHANGE_API_TC007(Hex *prvKey, Hex *pubKey, Hex *R, int isProvider) { TestMemInit(); CRYPT_RandRegist(RandFunc); CRYPT_RandRegistEx(RandFuncEx); uint8_t userId[10] = {0}; int32_t server = 1; uint8_t out[64]; uint8_t localR[65]; uint32_t outLen = sizeof(out); CRYPT_EAL_PkeyPrv prv = {0}; CRYPT_EAL_PkeyPub pub = {0}; CRYPT_EAL_PkeyCtx *ctx1 = TestPkeyNewCtx(NULL, CRYPT_PKEY_SM2, CRYPT_EAL_PKEY_KEYMGMT_OPERATE + CRYPT_EAL_PKEY_EXCH_OPERATE, "provider=default", isProvider); CRYPT_EAL_PkeyCtx *ctx2 = TestPkeyNewCtx(NULL, CRYPT_PKEY_SM2, CRYPT_EAL_PKEY_KEYMGMT_OPERATE + CRYPT_EAL_PKEY_EXCH_OPERATE, "provider=default", isProvider); ASSERT_TRUE(ctx1 != NULL); ASSERT_TRUE(ctx2 != NULL); SetSm2PrvKey(&prv, prvKey->x, prvKey->len); SetSm2PubKey(&pub, pubKey->x, pubKey->len); ASSERT_TRUE(CRYPT_EAL_PkeyCtrl(ctx1, CRYPT_CTRL_SET_SM2_USER_ID, userId, sizeof(userId)) == CRYPT_SUCCESS); ASSERT_TRUE(CRYPT_EAL_PkeyCtrl(ctx1, CRYPT_CTRL_SET_SM2_SERVER, &server, sizeof(int32_t)) == CRYPT_SUCCESS); ASSERT_TRUE(CRYPT_EAL_PkeyCtrl(ctx1, CRYPT_CTRL_GENE_SM2_R, localR, sizeof(localR)) == CRYPT_SUCCESS); ASSERT_TRUE(CRYPT_EAL_PkeySetPrv(ctx1, &prv) == CRYPT_SUCCESS); ASSERT_TRUE(CRYPT_EAL_PkeyCtrl(ctx2, CRYPT_CTRL_SET_SM2_USER_ID, userId, sizeof(userId)) == CRYPT_SUCCESS); ASSERT_TRUE(CRYPT_EAL_PkeyCtrl(ctx2, CRYPT_CTRL_SET_SM2_R, R->x, R->len) == CRYPT_SUCCESS); ASSERT_TRUE(CRYPT_EAL_PkeySetPrv(ctx2, &prv) == CRYPT_SUCCESS); ASSERT_TRUE(CRYPT_EAL_PkeyComputeShareKey(ctx1, ctx2, out, &outLen) == CRYPT_SM2_ERR_EMPTY_KEY); ASSERT_TRUE(CRYPT_EAL_PkeySetPub(ctx1, &pub) == CRYPT_SUCCESS); ASSERT_TRUE(CRYPT_EAL_PkeySetPub(ctx2, &pub) == CRYPT_SUCCESS); ASSERT_TRUE(CRYPT_EAL_PkeyCtrl(ctx1, CRYPT_CTRL_GENE_SM2_R, localR, sizeof(localR)) == CRYPT_SUCCESS); ASSERT_TRUE(CRYPT_EAL_PkeyComputeShareKey(ctx1, ctx2, out, &outLen) == CRYPT_SUCCESS); EXIT: CRYPT_EAL_PkeyFreeCtx(ctx1); CRYPT_EAL_PkeyFreeCtx(ctx2); CRYPT_RandRegist(NULL); CRYPT_RandRegistEx(NULL); } /* END_CASE */ /** * @test SDV_CRYPTO_SM2_CTRL_API_TC001 * @title SM2 CRYPT_EAL_PkeyCtrl: Test generate R and get R. * @precon nan * @brief * 1. Create the context of the SM2 algorithm, expected result 1 * 2. Call the CRYPT_EAL_PkeyCtrl, and all parameters are valid, expected result 2 * 3. Set the error random number method so that it returns zero, expected result 3 * 4. Call the CRYPT_EAL_PkeyCtrl, and all parameters are valid, expected result 4 * 5. Set the correct random number method. * 6. Call the CRYPT_EAL_PkeyCtrl, opt = CRYPT_CTRL_GENE_SM2_R: * (1) val = null, and other parameters are valid, expected result 5 * (2) val = null, len = 0, and other parameters are valid, expected result 6 * (3) val != null, len is not enough, and other parameters are valid, expected result 7 * @expect * 1. Success, and context is not NULL. * 2. CRYPT_NO_REGIST_RAND * 3. CRYPT_SUCCESS * 4. CRYPT_SM2_ERR_TRY_CNT * 5-6. CRYPT_NULL_INPUT * 7. CRYPT_ECC_BUFF_LEN_NOT_ENOUGH */ /* BEGIN_CASE */ void SDV_CRYPTO_SM2_CTRL_API_TC001(int isProvider) { uint8_t localR[65]; uint8_t zero[RAND_BUF_LEN] = {0}; TestMemInit(); CRYPT_EAL_PkeyCtx *ctx = TestPkeyNewCtx(NULL, CRYPT_PKEY_SM2, CRYPT_EAL_PKEY_KEYMGMT_OPERATE + CRYPT_EAL_PKEY_EXCH_OPERATE, "provider=default", isProvider); ASSERT_TRUE(ctx != NULL); ASSERT_TRUE(CRYPT_EAL_PkeyCtrl(ctx, CRYPT_CTRL_GENE_SM2_R, localR, sizeof(localR)) == CRYPT_NO_REGIST_RAND); CRYPT_RandRegist(FakeRandFunc); CRYPT_RandRegistEx(FakeRandFuncEx); ASSERT_TRUE(SetFakeRandOutput(zero, sizeof(zero)) == CRYPT_SUCCESS); ASSERT_TRUE(CRYPT_EAL_PkeyCtrl(ctx, CRYPT_CTRL_GENE_SM2_R, localR, sizeof(localR)) == CRYPT_SM2_ERR_TRY_CNT); CRYPT_RandRegist(RandFunc); CRYPT_RandRegistEx(RandFuncEx); ASSERT_TRUE(CRYPT_EAL_PkeyCtrl(ctx, CRYPT_CTRL_GENE_SM2_R, NULL, sizeof(localR)) == CRYPT_NULL_INPUT); ASSERT_TRUE(CRYPT_EAL_PkeyCtrl(ctx, CRYPT_CTRL_GENE_SM2_R, NULL, 0) == CRYPT_NULL_INPUT); ASSERT_TRUE( CRYPT_EAL_PkeyCtrl(ctx, CRYPT_CTRL_GENE_SM2_R, localR, sizeof(localR) - 1) == CRYPT_ECC_BUFF_LEN_NOT_ENOUGH); EXIT: CRYPT_EAL_PkeyFreeCtx(ctx); CRYPT_RandRegist(NULL); CRYPT_RandRegistEx(NULL); } /* END_CASE */ /** * @test SDV_CRYPTO_SM2_CTRL_API_TC002 * @title SM2 CRYPT_EAL_PkeyCtrl: Test Set R. * @precon vector: valid R. * @brief * 1. Create the context of the SM2 algorithm, expected result 1 * 2. Call the CRYPT_EAL_PkeyCtrl, opt = CRYPT_CTRL_SET_SM2_R: * (1) val = null, and other parameters are valid, expected result 2 * (2) val = null, len = 0, and other parameters are valid, expected result 3 * (3) val != null, len = R->len - 1, and other parameters are valid, expected result 4 * (4) val != null, len = R->len + 1, and other parameters are valid, expected result 5 * (5) val is 0 and the length is 65 bytes, and other parameters are valid, expected result 6 * (6) and other parameters are valid, expected result 7 * @expect * 1. Success, and context is not NULL. * 2-3. CRYPT_NULL_INPUT * 4-6. CRYPT_ECC_ERR_POINT_CODE * 7. CRYPT_SUCCESS */ /* BEGIN_CASE */ void SDV_CRYPTO_SM2_CTRL_API_TC002(Hex *R, int isProvider) { uint8_t zero[65] = {0}; TestMemInit(); CRYPT_EAL_PkeyCtx *ctx = TestPkeyNewCtx(NULL, CRYPT_PKEY_SM2, CRYPT_EAL_PKEY_KEYMGMT_OPERATE + CRYPT_EAL_PKEY_EXCH_OPERATE, "provider=default", isProvider); ASSERT_TRUE(ctx != NULL); ASSERT_TRUE(CRYPT_EAL_PkeyCtrl(ctx, CRYPT_CTRL_SET_SM2_R, NULL, R->len) == CRYPT_NULL_INPUT); ASSERT_TRUE(CRYPT_EAL_PkeyCtrl(ctx, CRYPT_CTRL_SET_SM2_R, NULL, 0) == CRYPT_NULL_INPUT); ASSERT_TRUE(CRYPT_EAL_PkeyCtrl(ctx, CRYPT_CTRL_SET_SM2_R, R->x, R->len - 1) == CRYPT_ECC_ERR_POINT_CODE); ASSERT_TRUE(CRYPT_EAL_PkeyCtrl(ctx, CRYPT_CTRL_SET_SM2_R, R->x, R->len + 1) == CRYPT_ECC_ERR_POINT_CODE); ASSERT_TRUE(CRYPT_EAL_PkeyCtrl(ctx, CRYPT_CTRL_SET_SM2_R, zero, sizeof(zero)) == CRYPT_ECC_ERR_POINT_CODE); ASSERT_TRUE(CRYPT_EAL_PkeyCtrl(ctx, CRYPT_CTRL_SET_SM2_R, R->x, R->len) == CRYPT_SUCCESS); EXIT: CRYPT_EAL_PkeyFreeCtx(ctx); } /* END_CASE */ /** * @test SDV_CRYPTO_SM2_CTRL_API_TC003 * @title SM2 CRYPT_EAL_PkeyCtrl: Test set sm2 server/client. * @precon nan * @brief * 1. Create the context of the SM2 algorithm, expected result 1 * 2. Call the CRYPT_EAL_PkeyCtrl, opt = CRYPT_CTRL_SET_SM2_SERVER: * (1) val = null, and other parameters are valid, expected result 2 * (2) val = null, len = 0, and other parameters are valid, expected result 3 * (3) val(type is uint32_t, value is 2), len is 4, and other parameters are valid, expected result 4 * (4) val(type is uint32_t, value is 0xffffffff), len is 4, and other parameters are valid, expected result 5 * (5) val(type is uint8_t, value is 0), len is 1, and other parameters are valid, expected result 6 * @expect * 1. Success, and context is not NULL. * 2-3. CRYPT_NULL_INPUT * 4-5. CRYPT_SM2_INVALID_SERVER_TYPE * 6. CRYPT_SM2_ERR_CTRL_LEN */ /* BEGIN_CASE */ void SDV_CRYPTO_SM2_CTRL_API_TC003(int isProvider) { TestMemInit(); CRYPT_EAL_PkeyCtx *ctx = TestPkeyNewCtx(NULL, CRYPT_PKEY_SM2, CRYPT_EAL_PKEY_KEYMGMT_OPERATE + CRYPT_EAL_PKEY_EXCH_OPERATE, "provider=default", isProvider); ASSERT_TRUE(ctx != NULL); uint32_t server = 1; uint8_t badServer = 1; ASSERT_TRUE(CRYPT_EAL_PkeyCtrl(ctx, CRYPT_CTRL_SET_SM2_SERVER, NULL, sizeof(uint32_t)) == CRYPT_NULL_INPUT); ASSERT_TRUE(CRYPT_EAL_PkeyCtrl(ctx, CRYPT_CTRL_SET_SM2_SERVER, NULL, 0) == CRYPT_NULL_INPUT); server = 2; ASSERT_TRUE( CRYPT_EAL_PkeyCtrl(ctx, CRYPT_CTRL_SET_SM2_SERVER, &server, sizeof(uint32_t)) == CRYPT_SM2_INVALID_SERVER_TYPE); server = 0xffffffff; ASSERT_TRUE( CRYPT_EAL_PkeyCtrl(ctx, CRYPT_CTRL_SET_SM2_SERVER, &server, sizeof(uint32_t)) == CRYPT_SM2_INVALID_SERVER_TYPE); ASSERT_TRUE( CRYPT_EAL_PkeyCtrl(ctx, CRYPT_CTRL_SET_SM2_SERVER, &badServer, sizeof(uint8_t)) == CRYPT_SM2_ERR_CTRL_LEN); EXIT: CRYPT_EAL_PkeyFreeCtx(ctx); } /* END_CASE */ /** * @test SDV_CRYPTO_SM2_EXCHANGE_FUNC_TC001 * @title SM2 EAL key exchange. * @precon Vectors: * server: The value 1 indicates the initiator, and the value 0 indicates the responder. * User 1: private key, generate random number r, userId1 * User 2: public key, R, userId2 * @brief * 1. Create two contexts(ctx1, ctx2) of the SM2 algorithm, expected result 1 * 2. Set userId1 and server for ctx1, expected result 2 * 3. Mock BN_RandRange to generate r, expected result 3 * 4. ctx1 generate r, expected result 4 * 5. Set userId2 and R for ctx2, expected result 5 * 6. Set private key for ctx1, expected result 6 * 7. Set public key for ctx2, expected result 7 * 8. Compute the shared key, expected result 8 * 9. Compare the output shared secret and shared secret vector, expected result 9 * 10. Duplicate ctx1 and ctx2, expected result 10 * 11. dupCtx1 generate r, expected result 11 * 12. Set R for dupCtx2, expected result 12 * 13. Compute share secret with duplicated contexts, expected result 13 * 14. Compare the output shared secret and shared secret vector, expected result 14 * @expect * 1. Success, and two contexts are not NULL. * 2-8. CRYPT_SUCCESS * 9. The two shared secrets are the same. * 10. Success, and two contexts are not NULL. * 11-13. Success, and two contexts are not NULL. * 14. The two shared secrets are the same. */ /* BEGIN_CASE */ void SDV_CRYPTO_SM2_EXCHANGE_FUNC_TC001( Hex *prvKey, Hex *pubKey, Hex *r, Hex *R, Hex *shareKey, Hex *userId1, Hex *userId2, int server, int isProvider) { uint8_t out[500]; uint8_t localR[65]; uint32_t outLen = shareKey->len; FuncStubInfo tmpRpInfo; CRYPT_EAL_PkeyPrv prv = {0}; CRYPT_EAL_PkeyPub pub = {0}; CRYPT_EAL_PkeyCtx *dupCtx1 = NULL; CRYPT_EAL_PkeyCtx *dupCtx2 = NULL; SetSm2PrvKey(&prv, prvKey->x, prvKey->len); SetSm2PubKey(&pub, pubKey->x, pubKey->len); TestMemInit(); CRYPT_EAL_PkeyCtx *ctx1 = TestPkeyNewCtx(NULL, CRYPT_PKEY_SM2, CRYPT_EAL_PKEY_KEYMGMT_OPERATE + CRYPT_EAL_PKEY_EXCH_OPERATE, "provider=default", isProvider); CRYPT_EAL_PkeyCtx *ctx2 = TestPkeyNewCtx(NULL, CRYPT_PKEY_SM2, CRYPT_EAL_PKEY_KEYMGMT_OPERATE + CRYPT_EAL_PKEY_EXCH_OPERATE, "provider=default", isProvider); ASSERT_TRUE(ctx2 != NULL); ASSERT_TRUE(ctx1 != NULL); ASSERT_TRUE(CRYPT_EAL_PkeyCtrl(ctx1, CRYPT_CTRL_SET_SM2_USER_ID, userId1->x, userId1->len) == CRYPT_SUCCESS); ASSERT_TRUE(CRYPT_EAL_PkeyCtrl(ctx1, CRYPT_CTRL_SET_SM2_SERVER, &server, sizeof(int32_t)) == CRYPT_SUCCESS); STUB_Init(); STUB_Replace(&tmpRpInfo, BN_RandRangeEx, STUB_RandRangeK); ASSERT_TRUE(SetFakeRandOutput(r->x, r->len) == CRYPT_SUCCESS); ASSERT_TRUE(CRYPT_EAL_PkeyCtrl(ctx1, CRYPT_CTRL_GENE_SM2_R, localR, sizeof(localR)) == CRYPT_SUCCESS); ASSERT_TRUE(CRYPT_EAL_PkeyCtrl(ctx2, CRYPT_CTRL_SET_SM2_USER_ID, userId2->x, userId2->len) == CRYPT_SUCCESS); ASSERT_TRUE(CRYPT_EAL_PkeyCtrl(ctx2, CRYPT_CTRL_SET_SM2_R, R->x, R->len) == CRYPT_SUCCESS); ASSERT_TRUE(CRYPT_EAL_PkeySetPrv(ctx1, &prv) == CRYPT_SUCCESS); ASSERT_TRUE(CRYPT_EAL_PkeySetPub(ctx2, &pub) == CRYPT_SUCCESS); ASSERT_TRUE(CRYPT_EAL_PkeyComputeShareKey(ctx1, ctx2, out, &outLen) == CRYPT_SUCCESS); ASSERT_TRUE(outLen == shareKey->len); ASSERT_TRUE(memcmp(out, shareKey->x, shareKey->len) == 0); dupCtx1 = CRYPT_EAL_PkeyDupCtx(ctx1); dupCtx2 = CRYPT_EAL_PkeyDupCtx(ctx2); ASSERT_TRUE(dupCtx1 != NULL && dupCtx2 != NULL); ASSERT_TRUE(CRYPT_EAL_PkeyCtrl(dupCtx1, CRYPT_CTRL_GENE_SM2_R, localR, sizeof(localR)) == CRYPT_SUCCESS); ASSERT_TRUE(CRYPT_EAL_PkeyCtrl(dupCtx2, CRYPT_CTRL_SET_SM2_R, R->x, R->len) == CRYPT_SUCCESS); ASSERT_EQ(CRYPT_EAL_PkeyComputeShareKey(dupCtx1, dupCtx2, out, &outLen), CRYPT_SUCCESS); EXIT: STUB_Reset(&tmpRpInfo); CRYPT_EAL_PkeyFreeCtx(ctx1); CRYPT_EAL_PkeyFreeCtx(ctx2); CRYPT_EAL_PkeyFreeCtx(dupCtx1); CRYPT_EAL_PkeyFreeCtx(dupCtx2); } /* END_CASE */ /** * @test SDV_CRYPTO_SM2_EXCHANGE_FUNC_TC002 * @title SM2 EAL key exchange. * @precon Vectors: * server: The value 1 indicates the initiator, and the value 0 indicates the responder. * User 1: public key and private key, generate random number r, userId1 * User 2: public key and private key, R, userId2 * @brief * 1. Create two contexts(ctx1, ctx2) of the SM2 algorithm, expected result 1 * 2. Set userId1 and server for ctx1, expected result 2 * 3. Mock BN_RandRange to generate r, expected result 3 * 4. ctx1 generate r, expected result 4 * 5. Set userId2 and R for ctx2, expected result 5 * 6. Set public key and private key for ctx1, expected result 6 * 7. Set public key and private key for ctx2, expected result 7 * 8. Compute the shared key, expected result 8 * 9. Compare the output shared secret and shared secret vector, expected result 9 * @expect * 1. Success, and two contexts are not NULL. * 2-8. CRYPT_SUCCESS * 9. The two shared secrets are the same. */ /* BEGIN_CASE */ void SDV_CRYPTO_SM2_EXCHANGE_FUNC_TC002(Hex *prvKey1, Hex *pubKey2, Hex *prvKey2, Hex *pubKey1, Hex *r, Hex *R, Hex *shareKey, Hex *userId1, Hex *userId2, int server, int isProvider) { uint8_t out[500]; uint8_t localR[65]; uint8_t badId[10] = {0}; uint32_t outLen = shareKey->len; FuncStubInfo tmpRpInfo; CRYPT_EAL_PkeyPrv prv1 = {0}; CRYPT_EAL_PkeyPub pub2 = {0}; CRYPT_EAL_PkeyPrv prv2 = {0}; CRYPT_EAL_PkeyPub pub1 = {0}; SetSm2PrvKey(&prv1, prvKey1->x, prvKey1->len); SetSm2PubKey(&pub2, pubKey2->x, pubKey2->len); SetSm2PrvKey(&prv2, prvKey2->x, prvKey2->len); SetSm2PubKey(&pub1, pubKey1->x, pubKey1->len); TestMemInit(); CRYPT_EAL_PkeyCtx *ctx1 = TestPkeyNewCtx(NULL, CRYPT_PKEY_SM2, CRYPT_EAL_PKEY_KEYMGMT_OPERATE + CRYPT_EAL_PKEY_EXCH_OPERATE, "provider=default", isProvider); CRYPT_EAL_PkeyCtx *ctx2 = TestPkeyNewCtx(NULL, CRYPT_PKEY_SM2, CRYPT_EAL_PKEY_KEYMGMT_OPERATE + CRYPT_EAL_PKEY_EXCH_OPERATE, "provider=default", isProvider); ASSERT_TRUE(ctx1 != NULL); ASSERT_TRUE(ctx2 != NULL); ASSERT_TRUE(CRYPT_EAL_PkeyCtrl(ctx1, CRYPT_CTRL_SET_SM2_USER_ID, badId, sizeof(badId)) == CRYPT_SUCCESS); ASSERT_TRUE(CRYPT_EAL_PkeyCtrl(ctx1, CRYPT_CTRL_SET_SM2_USER_ID, userId1->x, userId1->len) == CRYPT_SUCCESS); ASSERT_TRUE(CRYPT_EAL_PkeyCtrl(ctx1, CRYPT_CTRL_SET_SM2_SERVER, &server, sizeof(int32_t)) == CRYPT_SUCCESS); STUB_Init(); STUB_Replace(&tmpRpInfo, BN_RandRangeEx, STUB_RandRangeK); ASSERT_TRUE(SetFakeRandOutput(r->x, r->len) == CRYPT_SUCCESS); ASSERT_TRUE(CRYPT_EAL_PkeyCtrl(ctx1, CRYPT_CTRL_GENE_SM2_R, localR, sizeof(localR)) == CRYPT_SUCCESS); ASSERT_TRUE(CRYPT_EAL_PkeyCtrl(ctx2, CRYPT_CTRL_SET_SM2_USER_ID, badId, sizeof(badId)) == CRYPT_SUCCESS); ASSERT_TRUE(CRYPT_EAL_PkeyCtrl(ctx2, CRYPT_CTRL_SET_SM2_USER_ID, userId2->x, userId2->len) == CRYPT_SUCCESS); ASSERT_TRUE(CRYPT_EAL_PkeyCtrl(ctx2, CRYPT_CTRL_SET_SM2_R, R->x, R->len) == CRYPT_SUCCESS); ASSERT_TRUE(CRYPT_EAL_PkeySetPub(ctx1, &pub1) == CRYPT_SUCCESS); ASSERT_TRUE(CRYPT_EAL_PkeySetPrv(ctx2, &prv2) == CRYPT_SUCCESS); ASSERT_TRUE(CRYPT_EAL_PkeySetPrv(ctx1, &prv1) == CRYPT_SUCCESS); ASSERT_TRUE(CRYPT_EAL_PkeySetPub(ctx2, &pub2) == CRYPT_SUCCESS); ASSERT_TRUE(CRYPT_EAL_PkeyComputeShareKey(ctx1, ctx2, out, &outLen) == CRYPT_SUCCESS); ASSERT_TRUE(outLen == shareKey->len); ASSERT_TRUE(memcmp(out, shareKey->x, shareKey->len) == 0); EXIT: STUB_Reset(&tmpRpInfo); CRYPT_EAL_PkeyFreeCtx(ctx1); CRYPT_EAL_PkeyFreeCtx(ctx2); } /* END_CASE */ /** * @test SDV_CRYPTO_SM2_EXCHANGE_FUNC_TC003 * @title SM2: Generate a key pair for key exchange. * @precon nan * @brief * 1. Create four contexts(selfCtx1, peerCtx1, selfCtx2, peerCtx2) of the SM2 algorithm, expected result 1 * 2. Init the DRBG, expected result 2. * 3. Set pkg for selfCtx1 and selfCtx2, expected result 3 * 4. Call the CRYPT_EAL_PkeyGen to generate a key pair for selfCtx1, expected result 4 * 5. Call the CRYPT_EAL_PkeyGen to generate a key pair for selfCtx2, expected result 5 * 6. Get the public key from selfCtx2 and set it to peerCtx2, expected result 6 * 7. Get the public key from selfCtx1 and set it to peerCtx1, expected result 7 * 8. Set userId and server for selfCtx1 and selfCtx2, expected result 8 * 9. selfCtx1 and selfCtx2 genenrate r, expected result 9 * 10. Set userId and r for peerCtx1 and peerCtx2, expected result 10 * 11. Compute the shared key from the privite value in selfCtx1 and the public vlaue in peerCtx1, expected result 11 * 12. Compute the shared key from the privite value in selfCtx2 and the public vlaue in peerCtx2, expected result 12 * 13. Compare the shared keys computed in the preceding two steps, expected result 13 * @expect * 1. Success, and contexts are not NULL. * 2. Success. * 3-12. CRYPT_SUCCESS. * 13. The two shared keys are the same. */ /* BEGIN_CASE */ void SDV_CRYPTO_SM2_EXCHANGE_FUNC_TC003(int pkg, int isProvider) { uint8_t userId1[10]; uint8_t userId2[10]; uint8_t out1[500]; uint8_t out2[500]; uint8_t localR1[65]; uint8_t localR2[65]; uint32_t outLen = sizeof(out1); int32_t server = 1; int32_t client = 0; (void)memset_s(userId1, sizeof(userId1), 'A', sizeof(userId1)); (void)memset_s(userId2, sizeof(userId2), 'B', sizeof(userId2)); uint8_t pubKey1[65]; uint8_t pubKey2[65]; CRYPT_EAL_PkeyPub pub1, pub2; SetSm2PubKey(&pub1, pubKey1, sizeof(pubKey1)); SetSm2PubKey(&pub2, pubKey2, sizeof(pubKey2)); TestMemInit(); CRYPT_EAL_PkeyCtx *selfCtx1 = TestPkeyNewCtx(NULL, CRYPT_PKEY_SM2, CRYPT_EAL_PKEY_KEYMGMT_OPERATE + CRYPT_EAL_PKEY_EXCH_OPERATE, "provider=default", isProvider); CRYPT_EAL_PkeyCtx *selfCtx2 = TestPkeyNewCtx(NULL, CRYPT_PKEY_SM2, CRYPT_EAL_PKEY_KEYMGMT_OPERATE + CRYPT_EAL_PKEY_EXCH_OPERATE, "provider=default", isProvider); CRYPT_EAL_PkeyCtx *peerCtx1 = TestPkeyNewCtx(NULL, CRYPT_PKEY_SM2, CRYPT_EAL_PKEY_KEYMGMT_OPERATE + CRYPT_EAL_PKEY_EXCH_OPERATE, "provider=default", isProvider); CRYPT_EAL_PkeyCtx *peerCtx2 = TestPkeyNewCtx(NULL, CRYPT_PKEY_SM2, CRYPT_EAL_PKEY_KEYMGMT_OPERATE + CRYPT_EAL_PKEY_EXCH_OPERATE, "provider=default", isProvider); ASSERT_TRUE(peerCtx1 != NULL); ASSERT_TRUE(selfCtx2 != NULL); ASSERT_TRUE(selfCtx1 != NULL); ASSERT_TRUE(peerCtx2 != NULL); CRYPT_RandRegist(RandFunc); CRYPT_RandRegistEx(RandFuncEx); ASSERT_TRUE(CRYPT_EAL_PkeyCtrl(selfCtx1, CRYPT_CTRL_SET_SM2_PKG, &pkg, sizeof(pkg)) == CRYPT_SUCCESS); ASSERT_TRUE(CRYPT_EAL_PkeyCtrl(selfCtx2, CRYPT_CTRL_SET_SM2_PKG, &pkg, sizeof(pkg)) == CRYPT_SUCCESS); ASSERT_TRUE(CRYPT_EAL_PkeyGen(selfCtx1) == CRYPT_SUCCESS); ASSERT_TRUE(CRYPT_EAL_PkeyGen(selfCtx2) == CRYPT_SUCCESS); ASSERT_TRUE(CRYPT_EAL_PkeyGetPub(selfCtx1, &pub1) == CRYPT_SUCCESS); ASSERT_TRUE(CRYPT_EAL_PkeyGetPub(selfCtx2, &pub2) == CRYPT_SUCCESS); ASSERT_TRUE(CRYPT_EAL_PkeySetPub(peerCtx1, &pub2) == CRYPT_SUCCESS); ASSERT_TRUE(CRYPT_EAL_PkeySetPub(peerCtx2, &pub1) == CRYPT_SUCCESS); ASSERT_TRUE(CRYPT_EAL_PkeyCtrl(selfCtx1, CRYPT_CTRL_SET_SM2_USER_ID, userId1, sizeof(userId1)) == CRYPT_SUCCESS); ASSERT_TRUE(CRYPT_EAL_PkeyCtrl(selfCtx1, CRYPT_CTRL_SET_SM2_SERVER, &server, sizeof(int32_t)) == CRYPT_SUCCESS); ASSERT_TRUE(CRYPT_EAL_PkeyCtrl(selfCtx1, CRYPT_CTRL_GENE_SM2_R, localR1, sizeof(localR1)) == CRYPT_SUCCESS); ASSERT_TRUE(CRYPT_EAL_PkeyCtrl(selfCtx2, CRYPT_CTRL_SET_SM2_USER_ID, userId2, sizeof(userId2)) == CRYPT_SUCCESS); ASSERT_TRUE(CRYPT_EAL_PkeyCtrl(selfCtx2, CRYPT_CTRL_SET_SM2_SERVER, &client, sizeof(int32_t)) == CRYPT_SUCCESS); ASSERT_TRUE(CRYPT_EAL_PkeyCtrl(selfCtx2, CRYPT_CTRL_GENE_SM2_R, localR2, sizeof(localR2)) == CRYPT_SUCCESS); ASSERT_TRUE(CRYPT_EAL_PkeyCtrl(peerCtx1, CRYPT_CTRL_SET_SM2_R, localR2, sizeof(localR2)) == CRYPT_SUCCESS); ASSERT_TRUE(CRYPT_EAL_PkeyCtrl(peerCtx1, CRYPT_CTRL_SET_SM2_USER_ID, userId2, sizeof(userId2)) == CRYPT_SUCCESS); ASSERT_TRUE(CRYPT_EAL_PkeyCtrl(peerCtx2, CRYPT_CTRL_SET_SM2_R, localR1, sizeof(localR1)) == CRYPT_SUCCESS); ASSERT_TRUE(CRYPT_EAL_PkeyCtrl(peerCtx2, CRYPT_CTRL_SET_SM2_USER_ID, userId1, sizeof(userId1)) == CRYPT_SUCCESS); ASSERT_TRUE(CRYPT_EAL_PkeyComputeShareKey(selfCtx1, peerCtx1, out1, &outLen) == CRYPT_SUCCESS); ASSERT_TRUE(CRYPT_EAL_PkeyComputeShareKey(selfCtx2, peerCtx2, out2, &outLen) == CRYPT_SUCCESS); ASSERT_TRUE(memcmp(out1, out2, outLen) == 0); EXIT: CRYPT_RandRegist(NULL); CRYPT_RandRegistEx(NULL); CRYPT_EAL_PkeyFreeCtx(selfCtx1); CRYPT_EAL_PkeyFreeCtx(selfCtx2); CRYPT_EAL_PkeyFreeCtx(peerCtx1); CRYPT_EAL_PkeyFreeCtx(peerCtx2); } /* END_CASE */ /** * @test SDV_CRYPTO_SM2_EXCHANGE_FUNC_TC004 * @title SM2 EAL key exchange: Default identity (server). * @precon Vectors: * User 1: private key, generate random number r, userId1 * User 2: public key, R, userId2 * @brief * 1. Create two contexts(ctx1, ctx2) of the SM2 algorithm, expected result 1 * 2. Set userId1 for ctx1, expected result 2 * 3. Mock BN_RandRange to generate r, expected result 3 * 4. ctx1 generate r, expected result 4 * 5. Set userId2 and R for ctx2, expected result 5 * 6. Set private key for ctx1, expected result 6 * 7. Set public key for ctx2, expected result 7 * 8. Compute the shared key, expected result 8 * 9. Compare the output shared secret and shared secret vector, expected result 9 * 10. Copy ctx1 and ctx2, expected result 10 * 11. cpyCtx1 generate r, expected result 11 * 12. Set R for cpyCtx2, expected result 12 * 13. Compute share secret with duplicated contexts, expected result 13 * 14. Compare the output shared secret and shared secret vector, expected result 14 * @expect * 1. Success, and two contexts are not NULL. * 2-8. CRYPT_SUCCESS * 9. The two shared secrets are the same. * 10. Success, and two contexts are not NULL. * 11-13. Success, and two contexts are not NULL. * 14. The two shared secrets are the same. */ /* BEGIN_CASE */ void SDV_CRYPTO_SM2_EXCHANGE_FUNC_TC004( Hex *prvKey, Hex *pubKey, Hex *r, Hex *R, Hex *shareKey, Hex *userId1, Hex *userId2, int isProvider) { uint8_t out[500]; uint8_t localR[65]; uint32_t outLen = shareKey->len; FuncStubInfo tmpRpInfo; CRYPT_EAL_PkeyPrv prv = {0}; CRYPT_EAL_PkeyPub pub = {0}; CRYPT_EAL_PkeyCtx *cpyCtx1 = NULL; CRYPT_EAL_PkeyCtx *cpyCtx2 = NULL; SetSm2PrvKey(&prv, prvKey->x, prvKey->len); SetSm2PubKey(&pub, pubKey->x, pubKey->len); TestMemInit(); CRYPT_EAL_PkeyCtx *ctx1 = TestPkeyNewCtx(NULL, CRYPT_PKEY_SM2, CRYPT_EAL_PKEY_KEYMGMT_OPERATE + CRYPT_EAL_PKEY_EXCH_OPERATE, "provider=default", isProvider); CRYPT_EAL_PkeyCtx *ctx2 = TestPkeyNewCtx(NULL, CRYPT_PKEY_SM2, CRYPT_EAL_PKEY_KEYMGMT_OPERATE + CRYPT_EAL_PKEY_EXCH_OPERATE, "provider=default", isProvider); ASSERT_TRUE(ctx1 != NULL && ctx2 != NULL); ASSERT_TRUE(CRYPT_EAL_PkeyCtrl(ctx1, CRYPT_CTRL_SET_SM2_USER_ID, userId1->x, userId1->len) == CRYPT_SUCCESS); STUB_Init(); STUB_Replace(&tmpRpInfo, BN_RandRangeEx, STUB_RandRangeK); ASSERT_TRUE(SetFakeRandOutput(r->x, r->len) == CRYPT_SUCCESS); ASSERT_TRUE(CRYPT_EAL_PkeyCtrl(ctx1, CRYPT_CTRL_GENE_SM2_R, localR, sizeof(localR)) == CRYPT_SUCCESS); ASSERT_TRUE(CRYPT_EAL_PkeyCtrl(ctx2, CRYPT_CTRL_SET_SM2_USER_ID, userId2->x, userId2->len) == CRYPT_SUCCESS); ASSERT_TRUE(CRYPT_EAL_PkeyCtrl(ctx2, CRYPT_CTRL_SET_SM2_R, R->x, R->len) == CRYPT_SUCCESS); ASSERT_TRUE(CRYPT_EAL_PkeySetPrv(ctx1, &prv) == CRYPT_SUCCESS); ASSERT_TRUE(CRYPT_EAL_PkeySetPub(ctx2, &pub) == CRYPT_SUCCESS); ASSERT_TRUE(CRYPT_EAL_PkeyComputeShareKey(ctx1, ctx2, out, &outLen) == CRYPT_SUCCESS); ASSERT_TRUE(outLen == shareKey->len); ASSERT_TRUE(memcmp(out, shareKey->x, shareKey->len) == 0); cpyCtx1 = TestPkeyNewCtx(NULL, CRYPT_PKEY_SM2, CRYPT_EAL_PKEY_KEYMGMT_OPERATE + CRYPT_EAL_PKEY_EXCH_OPERATE, "provider=default", isProvider); cpyCtx2 = TestPkeyNewCtx(NULL, CRYPT_PKEY_SM2, CRYPT_EAL_PKEY_KEYMGMT_OPERATE + CRYPT_EAL_PKEY_EXCH_OPERATE, "provider=default", isProvider); ASSERT_TRUE(cpyCtx1 != NULL && cpyCtx2 != NULL); ASSERT_EQ(CRYPT_EAL_PkeyCopyCtx(cpyCtx1, ctx1), CRYPT_SUCCESS); ASSERT_EQ(CRYPT_EAL_PkeyCtrl(cpyCtx1, CRYPT_CTRL_GENE_SM2_R, localR, sizeof(localR)), CRYPT_SUCCESS); ASSERT_EQ(CRYPT_EAL_PkeyCopyCtx(cpyCtx2, ctx2), CRYPT_SUCCESS); ASSERT_EQ(CRYPT_EAL_PkeyCtrl(cpyCtx2, CRYPT_CTRL_SET_SM2_R, R->x, R->len), CRYPT_SUCCESS); ASSERT_EQ(CRYPT_EAL_PkeyComputeShareKey(cpyCtx1, cpyCtx2, out, &outLen), CRYPT_SUCCESS); ASSERT_TRUE(outLen == shareKey->len); ASSERT_TRUE(memcmp(out, shareKey->x, shareKey->len) == 0); EXIT: STUB_Reset(&tmpRpInfo); CRYPT_EAL_PkeyFreeCtx(ctx1); CRYPT_EAL_PkeyFreeCtx(ctx2); CRYPT_EAL_PkeyFreeCtx(cpyCtx1); CRYPT_EAL_PkeyFreeCtx(cpyCtx2); } /* END_CASE */ /** * @test SDV_CRYPTO_SM2_EXCHANGE_CHECK_TC001 * @title SM2 EAL key exchange check. * @precon Vectors: * server: The value 1 indicates the initiator, and the value 0 indicates the responder. * User 1: private key, generate random number r, userId1, optional term S * User 2: public key , R, userId2, optional term S * @brief * 1. Create two contexts(ctx1, ctx2) of the SM2 algorithm, expected result 1 * 2. Call the CRYPT_EAL_PkeyCtrl method, opt = CRYPT_CTRL_SM2_DO_CHECK, expected result 2 * 3. Set userId1 and server for ctx1, expected result 3 * 4. Mock BN_RandRange to generate r, expected result 4 * 5. ctx1 generate r, expected result 5 * 6. Set userId2 and R for ctx2, expected result 6 * 7. Set private key for ctx1, expected result 7 * 8. Set public key key for ctx2, expected resul 8 * 9. Compute the shared key, expected result 9 * 10. Compare the output shared secret and shared secret vector, expected result 10 * 11. Call the CRYPT_EAL_PkeyCtrl method: * (1) opt = CRYPT_CTRL_SM2_DO_CHECK val len not equal to SM3_MD_SIZE, expected result 11 * (2) opt = CRYPT_CTRL_GET_SM2_SEND_CHECK, val len not equal to SM3_MD_SIZE, expected result 12 * (3) opt = CRYPT_CTRL_GET_SM2_SEND_CHECK, and Other parameters are valid, expected result 13 * 12. Compare the output of step 11.(3) and selfS vector, expected result 14 * 13. Call the CRYPT_EAL_PkeyCtrl method, opt = CRYPT_CTRL_SM2_DO_CHECK, expected result 15 * @expect * 1. Success, and two contexts are not NULL. * 2. CRYPT_SM2_ERR_S_NOT_SET * 3-9. CRYPT_SUCCESS * 10. The two shared secrets are the same. * 11. CRYPT_SM2_ERR_DATA_LEN * 12. CRYPT_SM2_BUFF_LEN_NOT_ENOUGH * 13. CRYPT_SUCCESS * 14. Both are the same. * 15. CRYPT_SUCCESS */ /* BEGIN_CASE */ void SDV_CRYPTO_SM2_EXCHANGE_CHECK_TC001(Hex *prvKey, Hex *pubKey, Hex *r, Hex *R, Hex *shareKey, Hex *userId1, Hex *userId2, int server, Hex *peerS, Hex *selfS, int isProvider) { uint8_t out[500]; uint8_t localR[65]; uint32_t outLen = shareKey->len; FuncStubInfo tmpRpInfo; uint8_t val[selfS->len]; CRYPT_EAL_PkeyPrv prv = {0}; CRYPT_EAL_PkeyPub pub = {0}; SetSm2PrvKey(&prv, prvKey->x, prvKey->len); SetSm2PubKey(&pub, pubKey->x, pubKey->len); TestMemInit(); CRYPT_EAL_PkeyCtx *ctx1 = TestPkeyNewCtx(NULL, CRYPT_PKEY_SM2, CRYPT_EAL_PKEY_KEYMGMT_OPERATE + CRYPT_EAL_PKEY_EXCH_OPERATE, "provider=default", isProvider); CRYPT_EAL_PkeyCtx *ctx2 = TestPkeyNewCtx(NULL, CRYPT_PKEY_SM2, CRYPT_EAL_PKEY_KEYMGMT_OPERATE + CRYPT_EAL_PKEY_EXCH_OPERATE, "provider=default", isProvider); ASSERT_TRUE(ctx2 != NULL); ASSERT_TRUE(ctx1 != NULL); ASSERT_TRUE(CRYPT_EAL_PkeyCtrl(ctx1, CRYPT_CTRL_SM2_DO_CHECK, peerS->x, peerS->len) == CRYPT_SM2_ERR_S_NOT_SET); ASSERT_TRUE(CRYPT_EAL_PkeyCtrl(ctx1, CRYPT_CTRL_SET_SM2_USER_ID, userId1->x, userId1->len) == CRYPT_SUCCESS); ASSERT_TRUE(CRYPT_EAL_PkeyCtrl(ctx1, CRYPT_CTRL_SET_SM2_SERVER, &server, sizeof(int32_t)) == CRYPT_SUCCESS); STUB_Init(); STUB_Replace(&tmpRpInfo, BN_RandRangeEx, STUB_RandRangeK); ASSERT_TRUE(SetFakeRandOutput(r->x, r->len) == CRYPT_SUCCESS); ASSERT_TRUE(CRYPT_EAL_PkeyCtrl(ctx1, CRYPT_CTRL_GENE_SM2_R, localR, sizeof(localR)) == CRYPT_SUCCESS); ASSERT_TRUE(CRYPT_EAL_PkeyCtrl(ctx2, CRYPT_CTRL_SET_SM2_USER_ID, userId2->x, userId2->len) == CRYPT_SUCCESS); ASSERT_TRUE(CRYPT_EAL_PkeyCtrl(ctx2, CRYPT_CTRL_SET_SM2_R, R->x, R->len) == CRYPT_SUCCESS); ASSERT_TRUE(CRYPT_EAL_PkeySetPrv(ctx1, &prv) == CRYPT_SUCCESS); ASSERT_TRUE(CRYPT_EAL_PkeySetPub(ctx2, &pub) == CRYPT_SUCCESS); ASSERT_TRUE(CRYPT_EAL_PkeyComputeShareKey(ctx1, ctx2, out, &outLen) == CRYPT_SUCCESS); ASSERT_TRUE(outLen == shareKey->len); ASSERT_TRUE(memcmp(out, shareKey->x, shareKey->len) == 0); ASSERT_TRUE(CRYPT_EAL_PkeyCtrl(ctx1, CRYPT_CTRL_SM2_DO_CHECK, peerS->x, peerS->len - 1) == CRYPT_SM2_ERR_DATA_LEN); ASSERT_TRUE( CRYPT_EAL_PkeyCtrl(ctx1, CRYPT_CTRL_GET_SM2_SEND_CHECK, val, selfS->len - 1) == CRYPT_SM2_BUFF_LEN_NOT_ENOUGH); ASSERT_TRUE(CRYPT_EAL_PkeyCtrl(ctx1, CRYPT_CTRL_GET_SM2_SEND_CHECK, val, selfS->len) == CRYPT_SUCCESS); ASSERT_TRUE(memcmp(val, selfS->x, selfS->len) == 0); ASSERT_TRUE(CRYPT_EAL_PkeyCtrl(ctx1, CRYPT_CTRL_SM2_DO_CHECK, peerS->x, peerS->len) == CRYPT_SUCCESS); EXIT: STUB_Reset(&tmpRpInfo); CRYPT_EAL_PkeyFreeCtx(ctx1); CRYPT_EAL_PkeyFreeCtx(ctx2); } /* END_CASE */
2301_79861745/bench_create
testcode/sdv/testcase/crypto/sm2/test_suite_sdv_eal_sm2_exchange.c
C
unknown
46,796
/* * This file is part of the openHiTLS project. * * openHiTLS is licensed under the Mulan PSL v2. * You can use this software according to the terms and conditions of the Mulan PSL v2. * You may obtain a copy of Mulan PSL v2 at: * * http://license.coscl.org.cn/MulanPSL2 * * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, * EITHER EXPRESS 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 test_suite_sdv_eal_sm2 */ /* BEGIN_HEADER */ #include "crypt_eal_pkey.h" #include "eal_pkey_local.h" #include "crypt_sm2.h" #include "sm2_local.h" #define SM2_SIGN_MAX_LEN 74 #define SM2_PRVKEY_MAX_LEN 32 #define SM2_PUBKEY_LEN 65 #define CRYPT_EAL_PKEY_KEYMGMT_OPERATE 0 /* END_HEADER */ /** * @test SDV_CRYPTO_SM2_GET_PUB_API_TC001 * @title SM2 CRYPT_EAL_PkeyGetPub: Test the validity of parameters. * @precon Prepare valid public key. * @brief * 1. Create the context of the sm2 algorithm, expected result 1 * 2. Set the valid public key, expected result 2 * 3. Call the CRYPT_EAL_PkeyGetPub method to set public key: * (1) pub.data = NULL, expected result 3 * (2) pub.len is invalid (pubKey.len - 1), expected result 4 * (3) all parameters are valid, expected result 5 * (4) pub.len = prvKey.len + 1, expected result 6 * 4. Compare the getted key and vector, expected result 7 * @expect * 1. Success, and the context is not NULL. * 2. CRYPT_SUCCESS * 3. CRYPT_NULL_INPUT * 4. CRYPT_ECC_BUFF_LEN_NOT_ENOUGH * 5. CRYPT_SUCCESS * 6. CRYPT_SUCCESS * 7. Both are the same. */ /* BEGIN_CASE */ void SDV_CRYPTO_SM2_GET_PUB_API_TC001(Hex *pubKey, int isProvider) { TestMemInit(); uint8_t buf[SM2_PUBKEY_LEN]; CRYPT_EAL_PkeyCtx *ctx = TestPkeyNewCtx(NULL, CRYPT_PKEY_SM2, CRYPT_EAL_PKEY_KEYMGMT_OPERATE + CRYPT_EAL_PKEY_SIGN_OPERATE, "provider=default", isProvider); ASSERT_TRUE(ctx != NULL); CRYPT_EAL_PkeyPub pub, pubOut; SetSm2PubKey(&pub, pubKey->x, pubKey->len); SetSm2PubKey(&pubOut, NULL, sizeof(buf)); ASSERT_TRUE(CRYPT_EAL_PkeySetPub(ctx, &pub) == CRYPT_SUCCESS); ASSERT_TRUE_AND_LOG("NULL pubKey buffer", CRYPT_EAL_PkeyGetPub(ctx, &pubOut) == CRYPT_NULL_INPUT); pubOut.key.eccPub.data = buf; pubOut.key.eccPub.len = sizeof(buf) - 1; ASSERT_TRUE_AND_LOG("64 len pubKey buffer", CRYPT_EAL_PkeyGetPub(ctx, &pubOut) == CRYPT_ECC_BUFF_LEN_NOT_ENOUGH); pubOut.key.eccPub.data = buf; pubOut.key.eccPub.len = sizeof(buf); ASSERT_TRUE(CRYPT_EAL_PkeyGetPub(ctx, &pubOut) == CRYPT_SUCCESS); pubOut.key.eccPub.data = buf; pubOut.key.eccPub.len = sizeof(buf) + 1; ASSERT_TRUE(CRYPT_EAL_PkeyGetPub(ctx, &pubOut) == CRYPT_SUCCESS); ASSERT_TRUE(pubOut.key.eccPub.len == SM2_PUBKEY_LEN); ASSERT_TRUE(memcmp(buf, pubKey->x, pubKey->len) == 0); EXIT: CRYPT_EAL_PkeyFreeCtx(ctx); } /* END_CASE */ /** * @test SDV_CRYPTO_SM2_GET_PRV_API_TC001 * @title SM2 CRYPT_EAL_PkeyGetPrv: Test the validity of parameters. * @precon Prepare valid private key. * @brief * 1. Create the context of the sm2 algorithm, expected result 1 * 2. Set the valid private key, expected result 2 * 3. Call the CRYPT_EAL_PkeyGetPrv method to set private key: * (1) prv.data = NULL, expected result 3 * (2) prv.len is invalid (prvKey.len - 1), expected result 4 * (3) all parameters are valid, expected result 5 * (4) prv.len = prvKey.len + 1, expected result 6 * 4. Compare the getted key and vector, expected result 7 * @expect * 1. Success, and the context is not NULL. * 2. CRYPT_SUCCESS * 3. CRYPT_NULL_INPUT * 4. CRYPT_BN_BUFF_LEN_NOT_ENOUGH * 5. CRYPT_SUCCESS * 6. CRYPT_SUCCESS * 7. Both are the same. */ /* BEGIN_CASE */ void SDV_CRYPTO_SM2_GET_PRV_API_TC001(Hex *prvKey, int isProvider) { TestMemInit(); uint8_t buf[SM2_PRVKEY_MAX_LEN]; CRYPT_EAL_PkeyCtx *ctx = TestPkeyNewCtx(NULL, CRYPT_PKEY_SM2, CRYPT_EAL_PKEY_KEYMGMT_OPERATE + CRYPT_EAL_PKEY_SIGN_OPERATE, "provider=default", isProvider); ASSERT_TRUE(ctx != NULL); CRYPT_EAL_PkeyPrv prv, prvOut; SetSm2PrvKey(&prv, prvKey->x, prvKey->len); SetSm2PrvKey(&prvOut, NULL, prvKey->len); ASSERT_TRUE(CRYPT_EAL_PkeySetPrv(ctx, &prv) == CRYPT_SUCCESS); ASSERT_TRUE(CRYPT_EAL_PkeyGetPrv(ctx, &prvOut) == CRYPT_NULL_INPUT); prvOut.key.eccPrv.data = buf; prvOut.key.eccPrv.len = prvKey->len - 1; ASSERT_TRUE(CRYPT_EAL_PkeyGetPrv(ctx, &prvOut) == CRYPT_BN_BUFF_LEN_NOT_ENOUGH); prvOut.key.eccPrv.data = buf; prvOut.key.eccPrv.len = prvKey->len; ASSERT_TRUE(CRYPT_EAL_PkeyGetPrv(ctx, &prvOut) == CRYPT_SUCCESS); prvOut.key.eccPrv.data = buf; prvOut.key.eccPrv.len = prvKey->len + 1; ASSERT_TRUE(CRYPT_EAL_PkeyGetPrv(ctx, &prvOut) == CRYPT_SUCCESS); ASSERT_TRUE(prvOut.key.eccPrv.len == prvKey->len); ASSERT_TRUE(memcmp(buf, prvKey->x, prvKey->len) == 0); EXIT: CRYPT_EAL_PkeyFreeCtx(ctx); } /* END_CASE */ /** * @test SDV_CRYPTO_SM2_SET_PUB_API_TC001 * @title SM2 CRYPT_EAL_PkeySetPub: Test the validity of parameters. * @precon Prepare valid public key. * @brief * 1. Create the context of the sm2 algorithm, expected result 1 * 2. Call the CRYPT_EAL_PkeySetPrv method to set private key: * (1) pub.len is invalid (pubKey.len - 1), expected result 2 * (2) pub.len is invalid (pubKey.len + 1), expected result 3 * (3) public key is all 0x00, expected result 4 * (4) ctx.id != pub.id, expected result 5 * @expect * 1. Success, and the context is not NULL. * 2-4. CRYPT_ECC_ERR_POINT_CODE * 5. CRYPT_EAL_ERR_ALGID */ /* BEGIN_CASE */ void SDV_CRYPTO_SM2_SET_PUB_API_TC001(Hex *pubKey, int isProvider) { TestMemInit(); CRYPT_EAL_PkeyCtx *ctx = TestPkeyNewCtx(NULL, CRYPT_PKEY_SM2, CRYPT_EAL_PKEY_KEYMGMT_OPERATE + CRYPT_EAL_PKEY_SIGN_OPERATE, "provider=default", isProvider); ASSERT_TRUE(ctx != NULL); CRYPT_EAL_PkeyPub pub = {0}; uint8_t zero[SM2_PUBKEY_LEN] = {0}; SetSm2PubKey(&pub, pubKey->x, pubKey->len - 1); ASSERT_TRUE(CRYPT_EAL_PkeySetPub(ctx, &pub) == CRYPT_ECC_ERR_POINT_CODE); pub.key.eccPub.len = pubKey->len + 1; ASSERT_TRUE(CRYPT_EAL_PkeySetPub(ctx, &pub) == CRYPT_ECC_ERR_POINT_CODE); pub.key.eccPub.len = pubKey->len; pub.key.eccPub.data = zero; ASSERT_TRUE(CRYPT_EAL_PkeySetPub(ctx, &pub) == CRYPT_ECC_ERR_POINT_CODE); pub.id = CRYPT_PKEY_ED25519; ASSERT_TRUE(CRYPT_EAL_PkeySetPub(ctx, &pub) == CRYPT_EAL_ERR_ALGID); EXIT: CRYPT_EAL_PkeyFreeCtx(ctx); } /* END_CASE */ /** * @test SDV_CRYPTO_SM2_SET_PRV_API_TC001 * @title SM2 CRYPT_EAL_PkeySetPrv: Test the validity of parameters. * @precon Prepare valid private key. * @brief * 1. Create the context of the sm2 algorithm, expected result 1 * 2. Call the CRYPT_EAL_PkeySetPrv method to set private key: * (1) prv.len is invalid (prvKey.len + 1), expected result 2 * (2) private key is all 0x00, expected result 2 * (3) private key is all 0xFF, expected result 2 * (4) value of private key == order(curve_sm2) - 1, expected result 2 * (5) ctx id is wrong, expected result 3 * @expect * 1. Success, and the context is not NULL. * 2. CRYPT_ECC_PKEY_ERR_INVALID_PRIVATE_KEY * 3. CRYPT_EAL_ERR_ALGID */ /* BEGIN_CASE */ void SDV_CRYPTO_SM2_SET_PRV_API_TC001(Hex *prvKey, int isProvider) { uint8_t zero[SM2_PRVKEY_MAX_LEN] = {0}; uint8_t fullF[SM2_PRVKEY_MAX_LEN]; uint8_t prvKeyCopy[SM2_PRVKEY_MAX_LEN + 1] = {0}; CRYPT_EAL_PkeyPrv prv = {0}; (void)memset_s(fullF, sizeof(fullF), 0xff, sizeof(fullF)); TestMemInit(); CRYPT_EAL_PkeyCtx *ctx = TestPkeyNewCtx(NULL, CRYPT_PKEY_SM2, CRYPT_EAL_PKEY_KEYMGMT_OPERATE + CRYPT_EAL_PKEY_SIGN_OPERATE, "provider=default", isProvider); ASSERT_TRUE(ctx != NULL); ASSERT_TRUE(memcpy_s(prvKeyCopy, SM2_PRVKEY_MAX_LEN + 1, prvKey->x, prvKey->len) == CRYPT_SUCCESS); SetSm2PrvKey(&prv, prvKeyCopy, prvKey->len + 1); ASSERT_TRUE_AND_LOG("invalid prv len", CRYPT_EAL_PkeySetPrv(ctx, &prv) == CRYPT_ECC_PKEY_ERR_INVALID_PRIVATE_KEY); prv.key.eccPrv.len = prvKey->len; prv.key.eccPrv.data = zero; ASSERT_TRUE_AND_LOG("zero data key", CRYPT_EAL_PkeySetPrv(ctx, &prv) == CRYPT_ECC_PKEY_ERR_INVALID_PRIVATE_KEY); prv.key.eccPrv.data = fullF; ASSERT_TRUE_AND_LOG("full 1 key", CRYPT_EAL_PkeySetPrv(ctx, &prv) == CRYPT_ECC_PKEY_ERR_INVALID_PRIVATE_KEY); prv.id = CRYPT_PKEY_SM2; prv.key.eccPrv.data = prvKey->x; prv.key.eccPrv.len = prvKey->len; ASSERT_TRUE(CRYPT_EAL_PkeySetPrv(ctx, &prv) == CRYPT_ECC_PKEY_ERR_INVALID_PRIVATE_KEY); prv.id = CRYPT_PKEY_ED25519; prv.key.eccPrv.data = prvKey->x; ASSERT_TRUE(CRYPT_EAL_PkeySetPrv(ctx, &prv) == CRYPT_EAL_ERR_ALGID); EXIT: CRYPT_EAL_PkeyFreeCtx(ctx); } /* END_CASE */ /** * @test SDV_CRYPTO_SM2_GET_SIGN_LEN_API_TC001 * @title SM2: CRYPT_EAL_PkeyGetSignLen test. * @precon nan * @brief * 1. Create the context of the sm2 algorithm, expected result 1. * 2. Call the CRYPT_EAL_PkeyGetSignLen method, where pkey is NULL, expected result 2. * 3. Call the CRYPT_EAL_PkeyGetSignLen method, where pkey is valid, expected result 3. * @expect * 1. Success, and context is not NULL. * 2. Reutrn 0. * 3. Return SM2_SIGN_MAX_LEN(72) */ /* BEGIN_CASE */ void SDV_CRYPTO_SM2_GET_SIGN_LEN_API_TC001(int isProvider) { TestMemInit(); CRYPT_EAL_PkeyCtx *ctx = TestPkeyNewCtx(NULL, CRYPT_PKEY_SM2, CRYPT_EAL_PKEY_KEYMGMT_OPERATE + CRYPT_EAL_PKEY_SIGN_OPERATE, "provider=default", isProvider); ASSERT_TRUE(ctx != NULL); ASSERT_TRUE(CRYPT_EAL_PkeyGetSignLen(NULL) == 0); ASSERT_EQ(CRYPT_EAL_PkeyGetSignLen(ctx), SM2_SIGN_MAX_LEN); EXIT: CRYPT_EAL_PkeyFreeCtx(ctx); } /* END_CASE */ /** * @test SDV_CRYPTO_SM2_GET_KEY_LEN_API_TC001 * @title SM2: CRYPT_EAL_PkeyGetKeyLen test. * @precon nan * @brief * 1. Create the context of the sm2 algorithm, expected result 1. * 2. Call the CRYPT_EAL_PkeyGetKeyLen method, where pkey is NULL, expected result 2. * 3. Call the CRYPT_EAL_PkeyGetKeyLen method, where pkey is valid, expected result 3. * @expect * 1. Success, and context is not NULL. * 2. Reutrn 0. * 3. Return SM2_PUBKEY_LEN(65) */ /* BEGIN_CASE */ void SDV_CRYPTO_SM2_GET_KEY_LEN_API_TC001(int isProvider) { TestMemInit(); CRYPT_EAL_PkeyCtx *ctx = TestPkeyNewCtx(NULL, CRYPT_PKEY_SM2, CRYPT_EAL_PKEY_KEYMGMT_OPERATE + CRYPT_EAL_PKEY_SIGN_OPERATE, "provider=default", isProvider); ASSERT_TRUE(ctx != NULL); ASSERT_TRUE(CRYPT_EAL_PkeyGetKeyLen(NULL) == 0); ASSERT_TRUE(CRYPT_EAL_PkeyGetKeyLen(ctx) == SM2_PUBKEY_LEN); EXIT: CRYPT_EAL_PkeyFreeCtx(ctx); } /* END_CASE */ /** * @test SDV_CRYPTO_SM2_GEN_API_TC001 * @title SM2: CRYPT_EAL_PkeyGen test. * @precon nan * @brief * 1. Create the context(pkey) of the sm2 algorithm, expected result 1. * 2. Call the CRYPT_EAL_PkeyGen method, expected result 2 * 3. Register wrong rand method: FakeRandFunc(The random number it generated is 0), expected result 3 * 4. Call the CRYPT_EAL_PkeyGen method, expected result 4 * @expect * 1. Success, and context is not NULL. * 2. CRYPT_NO_REGIST_RAND * 3. CRYPT_ECC_PKEY_ERR_TRY_CNT */ /* BEGIN_CASE */ void SDV_CRYPTO_SM2_GEN_API_TC001(int isProvider) { TestMemInit(); uint8_t zero[RAND_BUF_LEN] = {0}; CRYPT_EAL_PkeyCtx *ctx = TestPkeyNewCtx(NULL, CRYPT_PKEY_SM2, CRYPT_EAL_PKEY_KEYMGMT_OPERATE + CRYPT_EAL_PKEY_SIGN_OPERATE, "provider=default", isProvider); ASSERT_TRUE(ctx != NULL); ASSERT_TRUE(CRYPT_EAL_PkeyGen(ctx) == CRYPT_NO_REGIST_RAND); ASSERT_TRUE(SetFakeRandOutput(zero, sizeof(zero)) == CRYPT_SUCCESS); CRYPT_RandRegist(FakeRandFunc); CRYPT_RandRegistEx(FakeRandFuncEx); ASSERT_TRUE(CRYPT_EAL_PkeyGen(ctx) == CRYPT_ECC_PKEY_ERR_TRY_CNT); CRYPT_RandRegist(RandFunc); CRYPT_RandRegistEx(RandFuncEx); ASSERT_TRUE(CRYPT_EAL_PkeyGen(ctx) == CRYPT_SUCCESS); EXIT: CRYPT_EAL_PkeyFreeCtx(ctx); CRYPT_RandRegist(NULL); CRYPT_RandRegistEx(NULL); } /* END_CASE */ /** * @test SDV_CRYPTO_SM2_SIGN_API_TC001 * @title SM2: CRYPT_EAL_PkeySign test. * @precon Vertor: private key. * @brief * 1. Init the DRBG. * 2. Create the context of the SM2 algorithm, expected result 1. * 3. Call the CRYPT_EAL_PkeyCtrl method to set userId, expected result 2. * 4. Call the CRYPT_EAL_PkeySign method, where all parameters are valid, expected result 3. * 5. Free the context and create a new context of the SM2 algorithm, expected result 4. * 6. Call the CRYPT_EAL_PkeySetPrv method to set private key, expected result 5. * 7. Call the CRYPT_EAL_PkeyCtrl method to set userId, expected result 6. * 8. Call the CRYPT_EAL_PkeySign method, where other parameters are valid, but: * (1) signLen is not enough, expected result 7 * (2) sign = NULL, signLen != 0, expected result 8 * (3) msg = NULL, msgLen != 0, expected result 9 * (4) msg = NULL, msgLen = 0, expected result 10 * (5) mdId != CRYPT_MD_SM3, msg = NULL, msgLen = 0, expected result 11 * @expect * 1. Success, and context is not NULL. * 2. CRYPT_SUCCESS * 3. CRYPT_SM2_NO_PRVKEY * 4. Success, and context is not NULL. * 5. CRYPT_SUCCESS * 6. CRYPT_SUCCESS * 7. CRYPT_SM2_BUFF_LEN_NOT_ENOUGH * 8-9. CRYPT_NULL_INPUT * 10. CRYPT_SUCCESS * 11. CRYPT_EAL_ERR_ALGID */ /* BEGIN_CASE */ void SDV_CRYPTO_SM2_SIGN_API_TC001(Hex *prvKey, int isProvider) { uint8_t userId[SM2_PRVKEY_MAX_LEN] = {0}; // legal id uint8_t msg[SM2_PRVKEY_MAX_LEN] = {0}; uint8_t signBuf[SM2_SIGN_MAX_LEN]; uint32_t signLen = sizeof(signBuf); CRYPT_EAL_PkeyPrv prv = {0}; SetSm2PrvKey(&prv, prvKey->x, prvKey->len); TestMemInit(); CRYPT_RandRegist(RandFunc); CRYPT_EAL_PkeyCtx *ctx = TestPkeyNewCtx(NULL, CRYPT_PKEY_SM2, CRYPT_EAL_PKEY_KEYMGMT_OPERATE + CRYPT_EAL_PKEY_SIGN_OPERATE, "provider=default", isProvider); ASSERT_TRUE(ctx != NULL); ASSERT_TRUE(CRYPT_EAL_PkeyCtrl(ctx, CRYPT_CTRL_SET_SM2_USER_ID, userId, sizeof(userId)) == CRYPT_SUCCESS); ASSERT_TRUE(CRYPT_EAL_PkeySign(ctx, CRYPT_MD_SM3, msg, sizeof(msg), signBuf, &signLen) == CRYPT_SM2_NO_PRVKEY); CRYPT_EAL_PkeyFreeCtx(ctx); ctx = CRYPT_EAL_PkeyNewCtx(CRYPT_PKEY_SM2); ASSERT_TRUE(ctx != NULL); ASSERT_TRUE(CRYPT_EAL_PkeySetPrv(ctx, &prv) == CRYPT_SUCCESS); ASSERT_TRUE(CRYPT_EAL_PkeyCtrl(ctx, CRYPT_CTRL_SET_SM2_USER_ID, userId, sizeof(userId)) == CRYPT_SUCCESS); signLen -= 1; ASSERT_TRUE( CRYPT_EAL_PkeySign(ctx, CRYPT_MD_SM3, msg, sizeof(msg), signBuf, &signLen) == CRYPT_SM2_BUFF_LEN_NOT_ENOUGH); signLen = sizeof(signBuf); ASSERT_TRUE(CRYPT_EAL_PkeySign(ctx, CRYPT_MD_SM3, msg, sizeof(msg), NULL, &signLen) == CRYPT_NULL_INPUT); ASSERT_TRUE(CRYPT_EAL_PkeySign(ctx, CRYPT_MD_SM3, NULL, sizeof(msg), signBuf, &signLen) == CRYPT_NULL_INPUT); ASSERT_TRUE(CRYPT_EAL_PkeySign(ctx, CRYPT_MD_SM3, NULL, 0, signBuf, &signLen) == CRYPT_SUCCESS); ASSERT_TRUE(CRYPT_EAL_PkeySign(ctx, CRYPT_MD_SHA256, NULL, 0, signBuf, &signLen) == CRYPT_EAL_ERR_ALGID); EXIT: CRYPT_EAL_PkeyFreeCtx(ctx); CRYPT_RandRegist(NULL); CRYPT_RandRegistEx(NULL); } /* END_CASE */ /** * @test SDV_CRYPTO_SM2_SIGN_DATA_API_TC001 * @title SM2: CRYPT_EAL_PkeySignData test. * @precon Vertor: private key. * @brief * 1. Create the context of the SM2 algorithm, expected result 1. * 2. Set userId and private key, expected result 2. * 3. Call the CRYPT_EAL_PkeySignData method, where all parameters are valid, expected result 3. * @expect * 1. Success, and context is not NULL. * 2. CRYPT_SUCCESS * 3. CRYPT_EAL_ALG_NOT_SUPPORT */ /* BEGIN_CASE */ void SDV_CRYPTO_SM2_SIGN_DATA_API_TC001(Hex *prvKey, int isProvider) { uint8_t userId[SM2_PRVKEY_MAX_LEN] = {0}; // legal id uint8_t msg[SM2_PRVKEY_MAX_LEN] = {0}; uint8_t signBuf[SM2_SIGN_MAX_LEN]; uint32_t signLen = sizeof(signBuf); CRYPT_EAL_PkeyPrv prv = {0}; SetSm2PrvKey(&prv, prvKey->x, prvKey->len); TestMemInit(); CRYPT_RandRegist(RandFunc); CRYPT_EAL_PkeyCtx *ctx = TestPkeyNewCtx(NULL, CRYPT_PKEY_SM2, CRYPT_EAL_PKEY_KEYMGMT_OPERATE + CRYPT_EAL_PKEY_SIGN_OPERATE, "provider=default", isProvider); ASSERT_TRUE(ctx != NULL); ASSERT_TRUE(CRYPT_EAL_PkeyCtrl(ctx, CRYPT_CTRL_SET_SM2_USER_ID, userId, sizeof(userId)) == CRYPT_SUCCESS); ASSERT_TRUE(CRYPT_EAL_PkeySetPrv(ctx, &prv) == CRYPT_SUCCESS); ASSERT_TRUE(CRYPT_EAL_PkeySignData(ctx, msg, sizeof(msg), signBuf, &signLen) == CRYPT_EAL_ALG_NOT_SUPPORT); EXIT: CRYPT_EAL_PkeyFreeCtx(ctx); CRYPT_RandRegist(NULL); CRYPT_RandRegistEx(NULL); } /* END_CASE */ /** * @test SDV_CRYPTO_SM2_SIGN_API_TC002 * @title SM2: CRYPT_EAL_PkeySign test: Random number error. * @precon Vertor: private key. * @brief * 1. Create the context of the SM2 algorithm, expected result 1. * 2. Set userId and private key, expected result 2. * 3. Call the CRYPT_EAL_PkeySign method, where all parameters are valid, expected result 3. * 4. Register wrong rand method: FakeRandFunc(The random number it generated is 0), expected result 4. * 5. Call the CRYPT_EAL_PkeySign method, where all parameters are valid, expected result 5. * 6. Register correct rand method and Call the CRYPT_EAL_PkeySign method to signature, expected result 6. * @expect * 1. Success, and context is not NULL. * 2. CRYPT_SUCCESS * 3. CRYPT_NO_REGIST_RAND * 4. CRYPT_SUCCESS * 5. CRYPT_SM2_ERR_TRY_CNT or CRYPT_ECC_POINT_BLIND_WITH_ZERO * 6. CRYPT_SUCCESS */ /* BEGIN_CASE */ void SDV_CRYPTO_SM2_SIGN_API_TC002(Hex *prvKey, int isProvider) { uint8_t zero[RAND_BUF_LEN] = {0}; uint8_t userId[SM2_PRVKEY_MAX_LEN] = {0}; // legal id uint8_t signBuf[SM2_SIGN_MAX_LEN]; uint32_t signLen = sizeof(signBuf); CRYPT_EAL_PkeyPrv prv = {0}; SetSm2PrvKey(&prv, prvKey->x, prvKey->len); TestMemInit(); CRYPT_EAL_PkeyCtx *ctx = TestPkeyNewCtx(NULL, CRYPT_PKEY_SM2, CRYPT_EAL_PKEY_KEYMGMT_OPERATE + CRYPT_EAL_PKEY_SIGN_OPERATE, "provider=default", isProvider); ASSERT_TRUE(ctx != NULL); ASSERT_TRUE(CRYPT_EAL_PkeyCtrl(ctx, CRYPT_CTRL_SET_SM2_USER_ID, userId, sizeof(userId)) == CRYPT_SUCCESS); ASSERT_TRUE(CRYPT_EAL_PkeySetPrv(ctx, &prv) == CRYPT_SUCCESS); ASSERT_TRUE(CRYPT_EAL_PkeySign(ctx, CRYPT_MD_SM3, NULL, 0, signBuf, &signLen) == CRYPT_NO_REGIST_RAND); ASSERT_TRUE(SetFakeRandOutput(zero, sizeof(zero)) == CRYPT_SUCCESS); CRYPT_RandRegist(FakeRandFunc); CRYPT_RandRegistEx(FakeRandFuncEx); int32_t ret = CRYPT_EAL_PkeySign(ctx, CRYPT_MD_SM3, NULL, 0, signBuf, &signLen); /* When assembly is enabled, the error code is CRYPT_SM2_ERR_TRY_CNT. Otherwise, the error code is * CRYPT_ECC_POINT_BLIND_WITH_ZERO. */ ASSERT_TRUE(ret == CRYPT_SM2_ERR_TRY_CNT || ret == CRYPT_ECC_POINT_BLIND_WITH_ZERO); CRYPT_RandRegist(RandFunc); CRYPT_RandRegistEx(RandFuncEx); ASSERT_TRUE(CRYPT_EAL_PkeySign(ctx, CRYPT_MD_SM3, NULL, 0, signBuf, &signLen) == CRYPT_SUCCESS); EXIT: CRYPT_EAL_PkeyFreeCtx(ctx); CRYPT_RandRegist(NULL); CRYPT_RandRegistEx(NULL); } /* END_CASE */ /** * @test SDV_CRYPTO_SM2_VERIFY_API_TC001 * @title SM2: CRYPT_EAL_PkeyVerify test. * @precon Vectors: public key, userId, msg, signature. * @brief * 1. Create the context of the SM2 algorithm, expected result 1. * 2. Call the CRYPT_EAL_PkeyCtrl method to set userId, expected result 2. * 3. Call the CRYPT_EAL_PkeyVerify method, where all parameters are valid, expected result 3. * 4. Free the context and create a new context of the SM2 algorithm, expected result 4. * 5. Set public key, expected result 5. * 6. Set userId, expected result 6. * 7. Call the CRYPT_EAL_PkeyVerify method: * (1) signLen is invalid: sign->len - 1 or sign->len + 1, expected result 7 * (3) msg = NULL, msgLen != 0, expected result 8 * (2) sign = NULL, signLen != 0, expected result 9 * (4) all parameters are valid, expected result 10 * (5) mdId != CRYPT_MD_SM3, expected result 11 * @expect * 1. Success, and context is not NULL. * 2. CRYPT_SUCCESS * 3. CRYPT_SM2_NO_PUBKEY * 4. Success, and context is not NULL. * 5. CRYPT_SUCCESS * 6. CRYPT_SUCCESS * 7. CRYPT_DSA_DECODE_FAIL * 8-9. CRYPT_NULL_INPUT * 10. CRYPT_SUCCESS * 11. CRYPT_EAL_ERR_ALGID */ /* BEGIN_CASE */ void SDV_CRYPTO_SM2_VERIFY_API_TC001(Hex *pubKey, Hex *userId, Hex *msg, Hex *sign, int isProvider) { CRYPT_EAL_PkeyPub pub = {0}; uint8_t bigSign[SM2_SIGN_MAX_LEN + 1] = {0}; SetSm2PubKey(&pub, pubKey->x, pubKey->len); TestMemInit(); CRYPT_EAL_PkeyCtx *ctx = TestPkeyNewCtx(NULL, CRYPT_PKEY_SM2, CRYPT_EAL_PKEY_KEYMGMT_OPERATE + CRYPT_EAL_PKEY_SIGN_OPERATE, "provider=default", isProvider); ASSERT_TRUE(ctx != NULL); ASSERT_TRUE(CRYPT_EAL_PkeyCtrl(ctx, CRYPT_CTRL_SET_SM2_USER_ID, userId->x, userId->len) == CRYPT_SUCCESS); ASSERT_TRUE(CRYPT_EAL_PkeyVerify(ctx, CRYPT_MD_SM3, msg->x, msg->len, sign->x, sign->len) == CRYPT_SM2_NO_PUBKEY); CRYPT_EAL_PkeyFreeCtx(ctx); ctx = CRYPT_EAL_PkeyNewCtx(CRYPT_PKEY_SM2); ASSERT_TRUE(ctx != NULL); ASSERT_TRUE(memcpy_s(bigSign, SM2_SIGN_MAX_LEN + 1, sign->x, sign->len) == CRYPT_SUCCESS); ASSERT_TRUE(CRYPT_EAL_PkeySetPub(ctx, &pub) == CRYPT_SUCCESS); ASSERT_TRUE(CRYPT_EAL_PkeyCtrl(ctx, CRYPT_CTRL_SET_SM2_USER_ID, userId->x, userId->len) == CRYPT_SUCCESS); ASSERT_EQ(CRYPT_EAL_PkeyVerify(ctx, CRYPT_MD_SM3, msg->x, msg->len, sign->x, sign->len - 1), BSL_ASN1_ERR_DECODE_LEN); ASSERT_EQ(CRYPT_EAL_PkeyVerify(ctx, CRYPT_MD_SM3, msg->x, msg->len, bigSign, SM2_SIGN_MAX_LEN + 1), CRYPT_DECODE_ASN1_BUFF_FAILED); ASSERT_TRUE(CRYPT_EAL_PkeyVerify(ctx, CRYPT_MD_SM3, NULL, msg->len, sign->x, sign->len) == CRYPT_NULL_INPUT); ASSERT_TRUE(CRYPT_EAL_PkeyVerify(ctx, CRYPT_MD_SM3, msg->x, msg->len, NULL, sign->len) == CRYPT_NULL_INPUT); ASSERT_TRUE(CRYPT_EAL_PkeyVerify(ctx, CRYPT_MD_SM3, msg->x, msg->len, sign->x, sign->len) == CRYPT_SUCCESS); ASSERT_TRUE( CRYPT_EAL_PkeyVerify(ctx, CRYPT_MD_SHA256, msg->x, msg->len, sign->x, sign->len) == CRYPT_EAL_ERR_ALGID); EXIT: CRYPT_EAL_PkeyFreeCtx(ctx); } /* END_CASE */ /** * @test SDV_CRYPTO_SM2_CTRL_API_TC001 * @title SM2 CRYPT_EAL_PkeyCtrl: Test set user id. * @precon vector: valid R. * @brief * 1. Create the context of the SM2 algorithm, expected result 1 * 2. Call the CRYPT_EAL_PkeyCtrl, opt = CRYPT_CTRL_SET_SM2_USER_ID: * (1) userId = null, idLen = 8191, and other parameters are valid, expected result 2 * (2) userId = null, idLen = 0, and other parameters are valid, expected result 3 * (3) userId != null, idLen = 8192, and other parameters are valid, expected result 4 * (4) userId != null, idLen = 8191, and other parameters are valid, expected result 5 * (5) userId != null, idLen = 1, and other parameters are valid, expected result 6 * @expect * 1. Success, and context is not NULL. * 2. CRYPT_NULL_INPUT * 3-4. CRYPT_ECC_PKEY_ERR_CTRL_LEN * 5-6. CRYPT_SUCCESS */ /* BEGIN_CASE */ void SDV_CRYPTO_SM2_CTRL_API_TC001(int isProvider) { uint8_t userId[8192] = {0}; // max id len 8191, plus one for test uint32_t idLen = sizeof(userId) - 1; TestMemInit(); CRYPT_EAL_PkeyCtx *ctx = TestPkeyNewCtx(NULL, CRYPT_PKEY_SM2, CRYPT_EAL_PKEY_KEYMGMT_OPERATE + CRYPT_EAL_PKEY_SIGN_OPERATE, "provider=default", isProvider); ASSERT_TRUE(ctx != NULL); ASSERT_TRUE(CRYPT_EAL_PkeyCtrl(ctx, CRYPT_CTRL_SET_SM2_USER_ID, NULL, idLen) == CRYPT_NULL_INPUT); ASSERT_TRUE(CRYPT_EAL_PkeyCtrl(ctx, CRYPT_CTRL_SET_SM2_USER_ID, userId, 0) == CRYPT_ECC_PKEY_ERR_CTRL_LEN); ASSERT_TRUE(CRYPT_EAL_PkeyCtrl(ctx, CRYPT_CTRL_SET_SM2_USER_ID, userId, idLen + 1) == CRYPT_ECC_PKEY_ERR_CTRL_LEN); ASSERT_TRUE(CRYPT_EAL_PkeyCtrl(ctx, CRYPT_CTRL_SET_SM2_USER_ID, userId, idLen) == CRYPT_SUCCESS); ASSERT_TRUE(CRYPT_EAL_PkeyCtrl(ctx, CRYPT_CTRL_SET_SM2_USER_ID, userId, 1) == CRYPT_SUCCESS); EXIT: CRYPT_EAL_PkeyFreeCtx(ctx); } /* END_CASE */ /** * @test SDV_CRYPTO_SM2_SIGN_FUNC_TC001 * @title ED25519 signature test: set the key or duplicate the context, and sign. * @precon private key, userId, random number k, msg, signature. * @brief * 1. Create the context(ctx) of the sm2 algorithm, expected result 1 * 2. Set the userId and private key for ctx, expected result 2 * 3. Mock BN_RandRange to generate k, expected result 3 * 4. Call the CRYPT_EAL_PkeySign method to compute signature, expected result 4 * 5. Compare the signgures of HiTLS and vector, expected result 5 * 6. Call the CRYPT_EAL_PkeyDupCtx method to dup sm2 context, expected result 6 * 7. Call the CRYPT_EAL_PkeySign method to compute signature, expected result 7 * 8. Compare the signgures of HiTLS and vector, expected result 8 * @expect * 1. Success, and context is not NULL. * 2-4. CRYPT_SUCCESS * 5. Both are the same. * 6. Success, and context is not NULL. * 7. CRYPT_SUCCESS * 8. Both are the same. */ /* BEGIN_CASE */ void SDV_CRYPTO_SM2_SIGN_FUNC_TC001(Hex *prvKey, Hex *userId, Hex *k, Hex *msg, Hex *sign, int isProvider) { uint8_t signBuf[100]; uint32_t signLen = sizeof(signBuf); FuncStubInfo tmpRpInfo = {0}; CRYPT_EAL_PkeyCtx *dupCtx = NULL; CRYPT_EAL_PkeyPrv prv = {0}; SetSm2PrvKey(&prv, prvKey->x, prvKey->len); TestMemInit(); CRYPT_EAL_PkeyCtx *ctx = TestPkeyNewCtx(NULL, CRYPT_PKEY_SM2, CRYPT_EAL_PKEY_KEYMGMT_OPERATE + CRYPT_EAL_PKEY_SIGN_OPERATE, "provider=default", isProvider); ASSERT_TRUE(ctx != NULL); ASSERT_TRUE(CRYPT_EAL_PkeyCtrl(ctx, CRYPT_CTRL_SET_SM2_USER_ID, userId->x, userId->len) == CRYPT_SUCCESS); ASSERT_TRUE(CRYPT_EAL_PkeySetPrv(ctx, &prv) == CRYPT_SUCCESS); ASSERT_TRUE(SetFakeRandOutput(k->x, k->len) == CRYPT_SUCCESS); STUB_Init(); STUB_Replace(&tmpRpInfo, BN_RandRangeEx, STUB_RandRangeK); ASSERT_TRUE(CRYPT_EAL_PkeySign(ctx, CRYPT_MD_SM3, msg->x, msg->len, signBuf, &signLen) == CRYPT_SUCCESS); ASSERT_TRUE(signLen == sign->len); ASSERT_TRUE(memcmp(signBuf, sign->x, sign->len) == 0); dupCtx = CRYPT_EAL_PkeyDupCtx(ctx); ASSERT_TRUE(dupCtx != NULL); signLen = sizeof(signBuf); ASSERT_EQ(CRYPT_EAL_PkeySign(dupCtx, CRYPT_MD_SM3, msg->x, msg->len, signBuf, &signLen), CRYPT_SUCCESS); ASSERT_EQ(signLen, sign->len); ASSERT_TRUE(memcmp(signBuf, sign->x, sign->len) == 0); EXIT: STUB_Reset(&tmpRpInfo); CRYPT_EAL_PkeyFreeCtx(ctx); CRYPT_EAL_PkeyFreeCtx(dupCtx); } /* END_CASE */ /** * @test SDV_CRYPTO_SM2_SIGN_FUNC_TC002 * @title SM2 EAL layer signature function test. * @precon prvKeyTmp, private key, userId, random number k, msg, signature. * @brief * 1. Create the context(ctx) of the sm2 algorithm, expected result 1 * 2. Repeatedly set the userId and private key of ctx, expected result 2 * 3. Mock BN_RandRange to generate k, expected result 3 * 4. Call the CRYPT_EAL_PkeySign method to compute signature, expected result 4 * 5. Compare the signgures of HiTLS and vector, expected result 5 * @expect * 1. Success, and context is not NULL. * 2-4. CRYPT_SUCCESS * 5. Both are the same. */ /* BEGIN_CASE */ void SDV_CRYPTO_SM2_SIGN_FUNC_TC002( Hex *prvKeyTmp, Hex *prvKey, Hex *userId, Hex *k, Hex *msg, Hex *sign, int isProvider) { uint8_t signBuf[100]; uint8_t userIdBuf[100] = {0}; uint32_t signLen = sizeof(signBuf); FuncStubInfo tmpRpInfo = {0}; CRYPT_EAL_PkeyPrv prv = {0}; SetSm2PrvKey(&prv, prvKeyTmp->x, prvKeyTmp->len); TestMemInit(); CRYPT_EAL_PkeyCtx *ctx = TestPkeyNewCtx(NULL, CRYPT_PKEY_SM2, CRYPT_EAL_PKEY_KEYMGMT_OPERATE + CRYPT_EAL_PKEY_SIGN_OPERATE, "provider=default", isProvider); ASSERT_TRUE(ctx != NULL); ASSERT_TRUE(CRYPT_EAL_PkeyCtrl(ctx, CRYPT_CTRL_SET_SM2_USER_ID, userIdBuf, sizeof(userIdBuf)) == CRYPT_SUCCESS); ASSERT_TRUE(CRYPT_EAL_PkeyCtrl(ctx, CRYPT_CTRL_SET_SM2_USER_ID, userId->x, userId->len) == CRYPT_SUCCESS); ASSERT_TRUE(CRYPT_EAL_PkeySetPrv(ctx, &prv) == CRYPT_SUCCESS); prv.key.eccPrv.data = prvKey->x; prv.key.eccPrv.len = prvKey->len; ASSERT_TRUE(CRYPT_EAL_PkeySetPrv(ctx, &prv) == CRYPT_SUCCESS); ASSERT_TRUE(SetFakeRandOutput(k->x, k->len) == CRYPT_SUCCESS); STUB_Init(); STUB_Replace(&tmpRpInfo, BN_RandRangeEx, STUB_RandRangeK); ASSERT_TRUE(CRYPT_EAL_PkeySign(ctx, CRYPT_MD_SM3, msg->x, msg->len, signBuf, &signLen) == CRYPT_SUCCESS); ASSERT_TRUE(signLen == sign->len); ASSERT_TRUE(memcmp(signBuf, sign->x, sign->len) == 0); EXIT: STUB_Reset(&tmpRpInfo); CRYPT_EAL_PkeyFreeCtx(ctx); } /* END_CASE */ /** * @test SDV_CRYPTO_SM2_VERIFY_FUNC_TC001 * @title SM2 verify test: set public key or duplicate the context, and verify. * @precon public key, userId, msg, signature. * @brief * 1. Create the context(ctx) of the sm2 algorithm, expected result 1 * 2. Set the userId and public key of ctx, expected result 2 * 3. Call the CRYPT_EAL_PkeyVerify method to verify, expected result 3 * 4. Call the CRYPT_EAL_PkeyDupCtx method to dup sm2 context, expected result 4 * 5. Call the CRYPT_EAL_PkeyVerify method to verify, expected result 5 * @expect * 1. Success, and context is not NULL. * 2-3. CRYPT_SUCCESS * 4. Success, and context is not NULL. * 5. CRYPT_SUCCESS */ /* BEGIN_CASE */ void SDV_CRYPTO_SM2_VERIFY_FUNC_TC001(Hex *pubKey, Hex *userId, Hex *msg, Hex *sign, int isProvider) { TestMemInit(); CRYPT_EAL_PkeyCtx *ctx = TestPkeyNewCtx(NULL, CRYPT_PKEY_SM2, CRYPT_EAL_PKEY_KEYMGMT_OPERATE + CRYPT_EAL_PKEY_SIGN_OPERATE, "provider=default", isProvider); ASSERT_TRUE(ctx != NULL); CRYPT_EAL_PkeyPub pub = {0}; SetSm2PubKey(&pub, pubKey->x, pubKey->len); ASSERT_TRUE(CRYPT_EAL_PkeyCtrl(ctx, CRYPT_CTRL_SET_SM2_USER_ID, userId->x, userId->len) == CRYPT_SUCCESS); ASSERT_TRUE(CRYPT_EAL_PkeySetPub(ctx, &pub) == CRYPT_SUCCESS); ASSERT_TRUE(CRYPT_EAL_PkeyVerify(ctx, CRYPT_MD_SM3, msg->x, msg->len, sign->x, sign->len) == CRYPT_SUCCESS); CRYPT_EAL_PkeyCtx *dupCtx = CRYPT_EAL_PkeyDupCtx(ctx); ASSERT_TRUE(dupCtx != NULL); ASSERT_TRUE(CRYPT_EAL_PkeyVerify(dupCtx, CRYPT_MD_SM3, msg->x, msg->len, sign->x, sign->len) == CRYPT_SUCCESS); EXIT: CRYPT_EAL_PkeyFreeCtx(ctx); CRYPT_EAL_PkeyFreeCtx(dupCtx); } /* END_CASE */ /** * @test SDV_CRYPTO_SM2_VERIFY_FUNC_TC002 * @title SM2 verify test: Repeatedly set public key, and verify. * @precon public key, userId, msg, signature. * @brief * 1. Create the context(ctx) of the sm2 algorithm, expected result 1 * 2. Repeatedly set the userId and public key of ctx, expected result 2 * 3. Call the CRYPT_EAL_PkeyVerify method to verify, expected result 3 * @expect * 1. Success, and context is not NULL. * 2-3. CRYPT_SUCCESS */ /* BEGIN_CASE */ void SDV_CRYPTO_SM2_VERIFY_FUNC_TC002( Hex *pubKeyTmp, Hex *pubKey, Hex *userId, Hex *msg, Hex *sign, int isProvider) { TestMemInit(); CRYPT_EAL_PkeyCtx *ctx = TestPkeyNewCtx(NULL, CRYPT_PKEY_SM2, CRYPT_EAL_PKEY_KEYMGMT_OPERATE + CRYPT_EAL_PKEY_SIGN_OPERATE, "provider=default", isProvider); ASSERT_TRUE(ctx != NULL); CRYPT_EAL_PkeyPub pub = {0}; SetSm2PubKey(&pub, pubKeyTmp->x, pubKeyTmp->len); ASSERT_TRUE(CRYPT_EAL_PkeyCtrl(ctx, CRYPT_CTRL_SET_SM2_USER_ID, userId->x, userId->len) == CRYPT_SUCCESS); ASSERT_TRUE(CRYPT_EAL_PkeySetPub(ctx, &pub) == CRYPT_SUCCESS); pub.key.eccPub.data = pubKey->x; pub.key.eccPub.len = pubKey->len; ASSERT_TRUE(CRYPT_EAL_PkeySetPub(ctx, &pub) == CRYPT_SUCCESS); ASSERT_TRUE(CRYPT_EAL_PkeyVerify(ctx, CRYPT_MD_SM3, msg->x, msg->len, sign->x, sign->len) == CRYPT_SUCCESS); EXIT: CRYPT_EAL_PkeyFreeCtx(ctx); } /* END_CASE */ /** * @test SDV_CRYPTO_SM2_SIGN_VERIFY_FUNC_TC001 * @title SM2: Generate a key pair for signature and verify. * @precon nan * @brief * 1. Create the context(ctx) of the sm2 algorithm, expected result 1 * 2. Initialize the DRBG, expected result 2 * 3. Call the CRYPT_EAL_PkeyGen to generate a key pair, expected result 3 * 4. Set the userId for ctx, expected result 4 * 5. Call the CRYPT_EAL_PkeySign method to compute signature, expected result 5 * 6. Call the CRYPT_EAL_PkeyVerify method to verify signature, expected result 6 * 7. Call the CRYPT_EAL_PkeyDupCtx method to dup sm2 context, expected result 7 * 8. Call the CRYPT_EAL_PkeySign method to compute signature, expected result 8 * 9. Call the CRYPT_EAL_PkeyVerify method to verify signature, expected result 9 * 10. Call the CRYPT_EAL_PkeyCpyCtx method to dup sm2 context, expected result 10 * 11. Call the CRYPT_EAL_PkeySign method to compute signature, expected result 11 * 12. Call the CRYPT_EAL_PkeyVerify method to verify signature, expected result 12 * @expect * 1. Success, and context is not NULL. * 2-6. CRYPT_SUCCESS * 7. Success, and context is not NULL. * 8-12. CRYPT_SUCCESS */ /* BEGIN_CASE */ void SDV_CRYPTO_SM2_SIGN_VERIFY_FUNC_TC001(int isProvider) { uint8_t userId[SM2_PRVKEY_MAX_LEN] = {0}; // legal id uint8_t signBuf[SM2_SIGN_MAX_LEN]; uint8_t msg[SM2_PRVKEY_MAX_LEN] = {0}; uint32_t signLen = sizeof(signBuf); CRYPT_EAL_PkeyCtx *dupCtx = NULL; CRYPT_EAL_PkeyCtx *cpyCtx = NULL; TestMemInit(); CRYPT_EAL_PkeyCtx *ctx = TestPkeyNewCtx(NULL, CRYPT_PKEY_SM2, CRYPT_EAL_PKEY_KEYMGMT_OPERATE + CRYPT_EAL_PKEY_SIGN_OPERATE, "provider=default", isProvider); ASSERT_TRUE(ctx != NULL); CRYPT_RandRegist(RandFunc); CRYPT_RandRegistEx(RandFuncEx); ASSERT_TRUE(CRYPT_EAL_PkeyGen(ctx) == CRYPT_SUCCESS); ASSERT_TRUE(CRYPT_EAL_PkeyCtrl(ctx, CRYPT_CTRL_SET_SM2_USER_ID, userId, sizeof(userId)) == CRYPT_SUCCESS); ASSERT_TRUE(CRYPT_EAL_PkeySign(ctx, CRYPT_MD_SM3, msg, sizeof(msg), signBuf, &signLen) == CRYPT_SUCCESS); ASSERT_TRUE(CRYPT_EAL_PkeyVerify(ctx, CRYPT_MD_SM3, msg, sizeof(msg), signBuf, signLen) == CRYPT_SUCCESS); dupCtx = CRYPT_EAL_PkeyDupCtx(ctx); ASSERT_TRUE(dupCtx != NULL); ASSERT_EQ(dupCtx->references.count, 1); signLen = sizeof(signBuf); ASSERT_EQ(CRYPT_EAL_PkeySign(dupCtx, CRYPT_MD_SM3, msg, sizeof(msg), signBuf, &signLen), CRYPT_SUCCESS); ASSERT_TRUE(CRYPT_EAL_PkeyVerify(dupCtx, CRYPT_MD_SM3, msg, sizeof(msg), signBuf, signLen) == CRYPT_SUCCESS); cpyCtx = TestPkeyNewCtx(NULL, CRYPT_PKEY_SM2, CRYPT_EAL_PKEY_KEYMGMT_OPERATE + CRYPT_EAL_PKEY_SIGN_OPERATE, "provider=default", isProvider); ASSERT_TRUE(cpyCtx != NULL); ASSERT_EQ(CRYPT_EAL_PkeyCopyCtx(cpyCtx, ctx), CRYPT_SUCCESS); signLen = sizeof(signBuf); ASSERT_EQ(CRYPT_EAL_PkeySign(cpyCtx, CRYPT_MD_SM3, msg, sizeof(msg), signBuf, &signLen), CRYPT_SUCCESS); ASSERT_EQ(CRYPT_EAL_PkeyVerify(cpyCtx, CRYPT_MD_SM3, msg, sizeof(msg), signBuf, signLen), CRYPT_SUCCESS); EXIT: CRYPT_EAL_PkeyFreeCtx(ctx); CRYPT_EAL_PkeyFreeCtx(dupCtx); CRYPT_EAL_PkeyFreeCtx(cpyCtx); CRYPT_RandRegist(NULL); CRYPT_RandRegistEx(NULL); } /* END_CASE */ /** * @test SDV_CRYPTO_SM2_VERIFY_FUNC_TC003 * @title SM2: Test verification failure scenario. * @precon public key, userId, msg, signature, one of the vectors is wrong. * @brief * 1. Create the context(ctx) of the sm2 algorithm, expected result 1 * 2. Repeatedly set the userId and public key of ctx, expected result 2 * 3. Call the CRYPT_EAL_PkeyVerify method to verify, expected result 3 * @expect * 1. Success, and context is not NULL. * 2-3. Not CRYPT_SUCCESS. */ /* BEGIN_CASE */ void SDV_CRYPTO_SM2_VERIFY_FUNC_TC003(Hex *pubKey, Hex *userId, Hex *msg, Hex *sign, int isProvider) { CRYPT_EAL_PkeyPub pub = {0}; SetSm2PubKey(&pub, pubKey->x, pubKey->len); TestMemInit(); CRYPT_EAL_PkeyCtx *ctx = TestPkeyNewCtx(NULL, CRYPT_PKEY_SM2, CRYPT_EAL_PKEY_KEYMGMT_OPERATE + CRYPT_EAL_PKEY_SIGN_OPERATE, "provider=default", isProvider); ASSERT_TRUE(ctx != NULL); ASSERT_TRUE(CRYPT_EAL_PkeyCtrl(ctx, CRYPT_CTRL_SET_SM2_USER_ID, userId->x, userId->len) == CRYPT_SUCCESS); ASSERT_TRUE(CRYPT_EAL_PkeySetPub(ctx, &pub) == CRYPT_SUCCESS); // Different errors will return different error codes. ASSERT_TRUE(CRYPT_EAL_PkeyVerify(ctx, CRYPT_MD_SM3, msg->x, msg->len, sign->x, sign->len) != CRYPT_SUCCESS); EXIT: CRYPT_EAL_PkeyFreeCtx(ctx); } /* END_CASE */ /** * @test SDV_CRYPTO_SM2_SIGN_VERIFY_FUNC_TC002 * @title SM2: The private/public key is not cleaned up when setting the public/private key. * @precon public key, userId, msg, signature, one of the vectors is wrong. * @brief * 1. Create the context(ctx) of the sm2 algorithm, expected result 1 * 2. Repeatedly set the userId, public key and private key of ctx, expected result 2 * 3. Call the CRYPT_EAL_PkeySign method to signature, expected result 3 * 4. Call the CRYPT_EAL_PkeyVerify method to verify, expected result 4 * @expect * 1. Success, and context is not NULL. * 2-4. CRYPT_SUCCESS. */ /* BEGIN_CASE */ void SDV_CRYPTO_SM2_SIGN_VERIFY_FUNC_TC002(Hex *pubKey, Hex *prvKey, int isProvider) { TestMemInit(); uint8_t userId[SM2_PRVKEY_MAX_LEN] = {0}; // legal id uint8_t signBuf[SM2_SIGN_MAX_LEN]; uint8_t msg[SM2_PRVKEY_MAX_LEN] = {0}; uint32_t signLen = sizeof(signBuf); CRYPT_EAL_PkeyPub pub = {0}; CRYPT_EAL_PkeyPrv prv = {0}; SetSm2PubKey(&pub, pubKey->x, pubKey->len); SetSm2PrvKey(&prv, prvKey->x, prvKey->len); CRYPT_RandRegist(RandFunc); CRYPT_RandRegistEx(RandFuncEx); CRYPT_EAL_PkeyCtx *ctx = TestPkeyNewCtx(NULL, CRYPT_PKEY_SM2, CRYPT_EAL_PKEY_KEYMGMT_OPERATE + CRYPT_EAL_PKEY_SIGN_OPERATE, "provider=default", isProvider); ASSERT_TRUE(ctx != NULL); ASSERT_TRUE(CRYPT_EAL_PkeySetPrv(ctx, &prv) == CRYPT_SUCCESS); ASSERT_TRUE(CRYPT_EAL_PkeySetPub(ctx, &pub) == CRYPT_SUCCESS); ASSERT_TRUE(CRYPT_EAL_PkeyCtrl(ctx, CRYPT_CTRL_SET_SM2_USER_ID, userId, sizeof(userId)) == CRYPT_SUCCESS); ASSERT_TRUE(CRYPT_EAL_PkeySign(ctx, CRYPT_MD_SM3, msg, sizeof(msg), signBuf, &signLen) == CRYPT_SUCCESS); ASSERT_TRUE(CRYPT_EAL_PkeyVerify(ctx, CRYPT_MD_SM3, msg, sizeof(msg), signBuf, signLen) == CRYPT_SUCCESS); EXIT: CRYPT_EAL_PkeyFreeCtx(ctx); } /* END_CASE */ /** * @test SDV_CRYPTO_SM2_KEY_PAIR_CHECK_FUNC_TC001 * @title SM2: key pair check. * @precon Registering memory-related functions. * @brief * 1. Create two contexts(pubCtx, prvCtx) of the sm2 algorithm, expected result 1 * 2. Set public key for pubCtx, expected result 2 * 3. Set private key for prvCtx, expected result 3 * 4. Set userId for pubCtx and prvCtx, expected result 4 * 5. Init the drbg, expected result 5 * 6. Check whether the public key matches the private key, expected result 6 * @expect * 1. Success, and contexts are not NULL. * 2-5. CRYPT_SUCCESS * 6. Return CRYPT_SUCCESS when expect is 1, CRYPT_SM2_VERIFY_FAIL otherwise. */ /* BEGIN_CASE */ void SDV_CRYPTO_SM2_KEY_PAIR_CHECK_FUNC_TC001(Hex *pubKey, Hex *prvKey, Hex *userId, int expect, int isProvider) { #if !defined(HITLS_CRYPTO_SM2_CHECK) (void)pubKey; (void)prvKey; (void)userId; (void)expect; (void)isProvider; SKIP_TEST(); #else CRYPT_EAL_PkeyCtx *pubCtx = NULL; CRYPT_EAL_PkeyCtx *prvCtx = NULL; CRYPT_EAL_PkeyPub pub = {0}; CRYPT_EAL_PkeyPrv prv = {0}; int expectRet = expect == 1 ? CRYPT_SUCCESS : CRYPT_SM2_PAIRWISE_CHECK_FAIL; SetSm2PubKey(&pub, pubKey->x, pubKey->len); SetSm2PrvKey(&prv, prvKey->x, prvKey->len); TestMemInit(); pubCtx = TestPkeyNewCtx(NULL, CRYPT_PKEY_SM2, CRYPT_EAL_PKEY_KEYMGMT_OPERATE + CRYPT_EAL_PKEY_SIGN_OPERATE, "provider=default", isProvider); prvCtx = TestPkeyNewCtx(NULL, CRYPT_PKEY_SM2, CRYPT_EAL_PKEY_KEYMGMT_OPERATE + CRYPT_EAL_PKEY_SIGN_OPERATE, "provider=default", isProvider); ASSERT_TRUE(pubCtx != NULL && prvCtx != NULL); ASSERT_EQ(CRYPT_EAL_PkeySetPub(pubCtx, &pub), CRYPT_SUCCESS); ASSERT_EQ(CRYPT_EAL_PkeySetPrv(prvCtx, &prv), CRYPT_SUCCESS); ASSERT_TRUE(CRYPT_EAL_PkeyCtrl(pubCtx, CRYPT_CTRL_SET_SM2_USER_ID, userId, sizeof(userId)) == CRYPT_SUCCESS); ASSERT_TRUE(CRYPT_EAL_PkeyCtrl(prvCtx, CRYPT_CTRL_SET_SM2_USER_ID, userId, sizeof(userId)) == CRYPT_SUCCESS); ASSERT_EQ(TestRandInit(), CRYPT_SUCCESS); ASSERT_EQ(CRYPT_EAL_PkeyPairCheck(pubCtx, prvCtx), expectRet); EXIT: TestRandDeInit(); CRYPT_EAL_PkeyFreeCtx(pubCtx); CRYPT_EAL_PkeyFreeCtx(prvCtx); #endif } /* END_CASE */ /** * @test SDV_CRYPTO_SM2_GET_KEY_BITS_FUNC_TC001 * @title SM2: get key bits. * @brief * 1. Create a context of the SM2 algorithm, expected result 1 * 2. Get key bits, expected result 2 * @expect * 1. Success, and context is not NULL. * 2. Equal to keyBits. */ /* BEGIN_CASE */ void SDV_CRYPTO_SM2_GET_KEY_BITS_FUNC_TC001(int id, int keyBits, int isProvider) { CRYPT_EAL_PkeyCtx *pkey = TestPkeyNewCtx(NULL, id, CRYPT_EAL_PKEY_KEYMGMT_OPERATE + CRYPT_EAL_PKEY_SIGN_OPERATE, "provider=default", isProvider); ASSERT_TRUE(pkey != NULL); ASSERT_TRUE(CRYPT_EAL_PkeyGetKeyBits(pkey) == (uint32_t)keyBits); EXIT: CRYPT_EAL_PkeyFreeCtx(pkey); } /* END_CASE */ /** * @test SDV_CRYPTO_SM2_CHECK_KEYPAIR_FUNC_TC001 * @title SM2 CRYPT_EAL_PkeyPairCheck test. */ /* BEGIN_CASE */ void SDV_CRYPTO_SM2_CHECK_KEYPAIR_FUNC_TC001(int isProvider) { #if !defined(HITLS_CRYPTO_SM2_CHECK) (void)isProvider; SKIP_TEST(); #else TestMemInit(); uint8_t wrong[100] = {1}; CRYPT_EAL_PkeyPub sm2PubKey = {0}; CRYPT_EAL_PkeyPrv sm2PrvKey = {0}; uint8_t pubKeyVector[100]; uint32_t pubKeyVectorLen = sizeof(pubKeyVector); uint8_t prvKeyVector[100]; uint32_t prvKeyVectorLen = sizeof(prvKeyVector); CRYPT_EAL_PkeyCtx *pkey = TestPkeyNewCtx(NULL, CRYPT_PKEY_SM2, CRYPT_EAL_PKEY_KEYMGMT_OPERATE, "provider=default", isProvider); CRYPT_EAL_PkeyCtx *pubCtx = TestPkeyNewCtx(NULL, CRYPT_PKEY_SM2, CRYPT_EAL_PKEY_KEYMGMT_OPERATE, "provider=default", isProvider); CRYPT_EAL_PkeyCtx *prvCtx = TestPkeyNewCtx(NULL, CRYPT_PKEY_SM2, CRYPT_EAL_PKEY_KEYMGMT_OPERATE, "provider=default", isProvider); ASSERT_TRUE(pkey != NULL); ASSERT_TRUE(pubCtx != NULL); ASSERT_TRUE(prvCtx != NULL); ASSERT_EQ(TestRandInit(), CRYPT_SUCCESS); SetSm2PubKey(&sm2PubKey, pubKeyVector, pubKeyVectorLen); SetSm2PrvKey(&sm2PrvKey, prvKeyVector, prvKeyVectorLen); ASSERT_EQ(CRYPT_EAL_PkeyGen(pkey), CRYPT_SUCCESS); ASSERT_EQ(CRYPT_EAL_PkeyPairCheck(pkey, pkey), CRYPT_SUCCESS); ASSERT_EQ(CRYPT_EAL_PkeyPrvCheck(pkey), CRYPT_SUCCESS); ASSERT_EQ(CRYPT_EAL_PkeyGetPub(pkey, &sm2PubKey), CRYPT_SUCCESS); ASSERT_EQ(CRYPT_EAL_PkeyGetPrv(pkey, &sm2PrvKey), CRYPT_SUCCESS); ASSERT_EQ(CRYPT_EAL_PkeySetPub(pubCtx, &sm2PubKey), CRYPT_SUCCESS); ASSERT_EQ(CRYPT_EAL_PkeySetPrv(prvCtx, &sm2PrvKey), CRYPT_SUCCESS); ASSERT_EQ(CRYPT_EAL_PkeyPairCheck(pubCtx, prvCtx), CRYPT_SUCCESS); sm2PrvKey.key.eccPrv.data = wrong; ASSERT_EQ(CRYPT_EAL_PkeySetPrv(prvCtx, &sm2PrvKey), CRYPT_SUCCESS); ASSERT_EQ(CRYPT_EAL_PkeyPairCheck(pubCtx, prvCtx), CRYPT_SM2_PAIRWISE_CHECK_FAIL); EXIT: TestRandDeInit(); CRYPT_EAL_PkeyFreeCtx(pkey); CRYPT_EAL_PkeyFreeCtx(pubCtx); CRYPT_EAL_PkeyFreeCtx(prvCtx); #endif } /* END_CASE */ /** * @test SDV_CRYPTO_SM2_CHECK_PRVKEY_FUNC_TC001 * @title SM2 CRYPT_EAL_PkeyPrvCheck test. */ /* BEGIN_CASE */ void SDV_CRYPTO_SM2_CHECK_PRVKEY_FUNC_TC001(int isProvider) { #if !defined(HITLS_CRYPTO_SM2_CHECK) (void)isProvider; SKIP_TEST(); #else TestMemInit(); CRYPT_EAL_PkeyPrv sm2PrvKey = {0}; CRYPT_SM2_Ctx *ctx = NULL; BN_BigNum *n = NULL; BN_BigNum *prvKey = NULL; uint8_t prvKeyVector[100]; uint32_t prvKeyVectorLen = sizeof(prvKeyVector); CRYPT_EAL_PkeyCtx *pkey = TestPkeyNewCtx(NULL, CRYPT_PKEY_SM2, CRYPT_EAL_PKEY_KEYMGMT_OPERATE, "provider=default", isProvider); CRYPT_EAL_PkeyCtx *prvCtx = TestPkeyNewCtx(NULL, CRYPT_PKEY_SM2, CRYPT_EAL_PKEY_KEYMGMT_OPERATE, "provider=default", isProvider); ASSERT_TRUE(pkey != NULL); ASSERT_TRUE(prvCtx != NULL); ASSERT_EQ(TestRandInit(), CRYPT_SUCCESS); SetSm2PrvKey(&sm2PrvKey, prvKeyVector, prvKeyVectorLen); ASSERT_EQ(CRYPT_EAL_PkeyPrvCheck(NULL), CRYPT_NULL_INPUT); ASSERT_EQ(CRYPT_EAL_PkeyPrvCheck(pkey), CRYPT_ECC_PKEY_ERR_EMPTY_KEY); ASSERT_EQ(CRYPT_EAL_PkeyGen(pkey), CRYPT_SUCCESS); ASSERT_EQ(CRYPT_EAL_PkeyPrvCheck(pkey), CRYPT_SUCCESS); ctx = (CRYPT_SM2_Ctx *)pkey->key; prvKey = ctx->pkey->prvkey; n = ECC_GetParaN(ctx->pkey->para); (void)BN_Copy(prvKey, n); // key = n ASSERT_EQ(CRYPT_EAL_PkeyPrvCheck(pkey), CRYPT_SM2_INVALID_PRVKEY); (void)BN_SubLimb(prvKey, prvKey, 1); // key = n - 1 ASSERT_EQ(CRYPT_EAL_PkeyPrvCheck(pkey), CRYPT_SM2_INVALID_PRVKEY); (void)BN_SubLimb(prvKey, prvKey, 1); // key = n - 2 ASSERT_EQ(CRYPT_EAL_PkeyPrvCheck(pkey), CRYPT_SUCCESS); (void)BN_Zeroize(prvKey); // key = 0 ASSERT_EQ(CRYPT_EAL_PkeyPrvCheck(pkey), CRYPT_SM2_INVALID_PRVKEY); EXIT: TestRandDeInit(); CRYPT_EAL_PkeyFreeCtx(pkey); CRYPT_EAL_PkeyFreeCtx(prvCtx); BN_Destroy(n); #endif } /* END_CASE */
2301_79861745/bench_create
testcode/sdv/testcase/crypto/sm2/test_suite_sdv_eal_sm2_sign.c
C
unknown
45,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 <pthread.h> #include "crypt_eal_md.h" #include "bsl_sal.h" #include "eal_md_local.h" #include "crypt_algid.h" #include "crypt_errno.h" #include "securec.h" /* END_HEADER */ typedef struct { uint8_t *data; uint8_t *hash; uint32_t dataLen; uint32_t hashLen; } ThreadParameter; void MultiThreadTest(void *arg) { ThreadParameter *threadParameter = (ThreadParameter *)arg; uint8_t out[32]; uint32_t outLen = sizeof(out); CRYPT_EAL_MdCTX *ctx = NULL; ctx = CRYPT_EAL_MdNewCtx(CRYPT_MD_SM3); ASSERT_TRUE(ctx != NULL); for (uint32_t i = 0; i < 10; i++) { ASSERT_EQ(CRYPT_EAL_MdInit(ctx), CRYPT_SUCCESS); ASSERT_EQ(CRYPT_EAL_MdUpdate(ctx, threadParameter->data, threadParameter->dataLen), CRYPT_SUCCESS); ASSERT_EQ(CRYPT_EAL_MdFinal(ctx, out, &outLen), CRYPT_SUCCESS); ASSERT_COMPARE("hash result cmp", out, outLen, threadParameter->hash, threadParameter->hashLen); } EXIT: CRYPT_EAL_MdFreeCtx(ctx); } /** * @test SDV_CRYPT_EAL_SM3_API_TC001 * @title CRYPT_EAL_MdUpdate and CRYPT_EAL_MdFinal test * @precon nan * @brief * 1.Call CRYPT_EAL_MdDeinit the null CTX, expected result 1. * 2.Invoke the CRYPT_EAL_MdNewCtx to create a CTX, expected result 2. * 3.Call CRYPT_EAL_MdUpdate and CRYPT_EAL_MdFinal before initialization, expected result 3 is obtained. * 4.Initialize the CTX and transfer null pointers to CRYPT_EAL_MdUpdate and CRYPT_EAL_MdFinal. expected result 4. * 5.Invoke CRYPT_EAL_MdUpdate and CRYPT_EAL_MdFinal normally, expected result 5. * 6.Call CRYPT_EAL_MdDeinit the CTX, expected result 6. * @expect * 1.Return CRYPT_NULL_INPUT * 2.Successful, ctx is returned. * 3.Return CRYPT_EAL_ERR_STATE * 4.Return CRYPT_NULL_INPUT * 5.Return CRYPT_SUCCESS * 6.Return CRYPT_SUCCESS */ /* BEGIN_CASE */ void SDV_CRYPT_EAL_SM3_API_TC001(void) { TestMemInit(); uint8_t input[100]; // Any length, for example, 100 bytes. uint32_t inLen = sizeof(input); uint8_t out[32]; // SM3 digest length is 32. uint32_t outLen = sizeof(out); uint32_t badOutLen = outLen - 1; uint32_t longOutLen = outLen + 1; ASSERT_EQ(CRYPT_EAL_MdGetDigestSize(CRYPT_MD_SM3), outLen); CRYPT_EAL_MdCTX *ctx = NULL; ASSERT_EQ(CRYPT_EAL_MdDeinit(ctx), CRYPT_NULL_INPUT); ctx = CRYPT_EAL_MdNewCtx(CRYPT_MD_SM3); ASSERT_TRUE(ctx != NULL); ASSERT_EQ(CRYPT_EAL_MdFinal(ctx, out, &outLen), CRYPT_EAL_ERR_STATE); ASSERT_EQ(CRYPT_EAL_MdUpdate(ctx, input, inLen), CRYPT_EAL_ERR_STATE); ASSERT_EQ(CRYPT_EAL_MdInit(ctx), CRYPT_SUCCESS); ASSERT_EQ(CRYPT_EAL_MdUpdate(NULL, input, inLen), CRYPT_NULL_INPUT); ASSERT_EQ(CRYPT_EAL_MdUpdate(ctx, NULL, inLen), CRYPT_NULL_INPUT); // Hash counting can be performed on empty strings. ASSERT_EQ(CRYPT_EAL_MdUpdate(ctx, input, 0), CRYPT_SUCCESS); ASSERT_EQ(CRYPT_EAL_MdUpdate(ctx, NULL, 0), CRYPT_SUCCESS); ASSERT_EQ(CRYPT_EAL_MdUpdate(ctx, input, inLen), CRYPT_SUCCESS); ASSERT_EQ(CRYPT_EAL_MdFinal(ctx, NULL, &outLen), CRYPT_NULL_INPUT); ASSERT_EQ(CRYPT_EAL_MdFinal(NULL, out, &outLen), CRYPT_NULL_INPUT); ASSERT_EQ(CRYPT_EAL_MdFinal(ctx, out, NULL), CRYPT_NULL_INPUT); ASSERT_EQ(CRYPT_EAL_MdFinal(ctx, out, &badOutLen), CRYPT_SM3_OUT_BUFF_LEN_NOT_ENOUGH); ASSERT_EQ(CRYPT_EAL_MdFinal(ctx, out, &outLen), CRYPT_SUCCESS); ASSERT_EQ(CRYPT_EAL_MdInit(ctx), CRYPT_SUCCESS); ASSERT_EQ(CRYPT_EAL_MdUpdate(ctx, input, inLen), CRYPT_SUCCESS); ASSERT_EQ(CRYPT_EAL_MdFinal(ctx, out, &longOutLen), CRYPT_SUCCESS); ASSERT_EQ(CRYPT_EAL_MdGetId(ctx), CRYPT_MD_SM3); ASSERT_EQ(CRYPT_EAL_MdDeinit(ctx), CRYPT_SUCCESS); EXIT: CRYPT_EAL_MdFreeCtx(ctx); } /* END_CASE */ /** * @test SDV_CRYPT_EAL_SM3_FUNC_TC001 * @title CRYPT_EAL_MdFinal test without update. * @precon nan * @brief * 1.Call CRYPT_EAL_MdNewCtx to create ctx, expected result 1. * 2.Call CRYPT_EAL_MdFinal get results. expected result 2. * 3.Compare with expected results. expected result 3. * @expect * 1.The ctx is created successful. * 2.Successful. * 2.Consistent with expected results. */ /* BEGIN_CASE */ void SDV_CRYPT_EAL_SM3_FUNC_TC001(Hex *hash) { TestMemInit(); uint8_t out[32]; // SM3 digest length is 32. uint32_t outLen = sizeof(out); CRYPT_EAL_MdCTX *ctx = CRYPT_EAL_MdNewCtx(CRYPT_MD_SM3); ASSERT_TRUE(ctx != NULL); ASSERT_EQ(CRYPT_EAL_MdInit(ctx), CRYPT_SUCCESS); ASSERT_EQ(CRYPT_EAL_MdFinal(ctx, out, &outLen), CRYPT_SUCCESS); ASSERT_EQ(outLen, 32); ASSERT_EQ(memcmp(out, hash->x, hash->len), 0); EXIT: CRYPT_EAL_MdFreeCtx(ctx); } /* END_CASE */ /** * @test SDV_CRYPT_EAL_SM3_FUNC_TC002 * @title Perform the vector test to check whether the calculation result is consistent with the standard output. * @precon nan * @brief * 1.Calculate the hash of each group of data, expected result 1. * 2.Compare the result to the expected value, expected result 2. * 6.Call CRYPT_EAL_Md to calculate the hash value, expected result 3. * @expect * 1.Hash calculation succeeded. * 2.The results are as expected. * 3.Obtains the expected hash of data */ /* BEGIN_CASE */ void SDV_CRYPT_EAL_SM3_FUNC_TC002(Hex *data, Hex *hash) { TestMemInit(); uint8_t out[32]; // SM3 digest length is 32 uint32_t outLen = sizeof(out); CRYPT_EAL_MdCTX *ctx = NULL; ctx = CRYPT_EAL_MdNewCtx(CRYPT_MD_SM3); ASSERT_TRUE(ctx != NULL); ASSERT_EQ(CRYPT_EAL_MdInit(ctx), CRYPT_SUCCESS); ASSERT_EQ(CRYPT_EAL_MdUpdate(ctx, data->x, data->len), CRYPT_SUCCESS); ASSERT_EQ(CRYPT_EAL_MdFinal(ctx, out, &outLen), CRYPT_SUCCESS); ASSERT_EQ(outLen, 32); ASSERT_EQ(memcmp(out, hash->x, hash->len), 0); ASSERT_EQ(CRYPT_EAL_Md(CRYPT_MD_SM3, data->x, data->len, out, &outLen), CRYPT_SUCCESS); ASSERT_EQ(memcmp(out, hash->x, hash->len), 0); EXIT: CRYPT_EAL_MdFreeCtx(ctx); } /* END_CASE */ /** * @test SDV_CRYPT_EAL_SM3_FUNC_TC003 * @title Hash calculation for multiple updates,comparison with standard results. * @precon nan * @brief * 1.Call CRYPT_EAL_MdNewCtx to create a ctx and initialize, expected result 1. * 2.Call CRYPT_EAL_MdUpdate to calculate the hash of a data segmentxpected result 2. * 3.Call CRYPT_EAL_MdUpdate to calculate the next data segmentxpected result 3. * 4.Call CRYPT_EAL_MdUpdate to calculate the next data segmentxpected result 4. * 5.Call CRYPT_EAL_MdFinal get the result, expected result 5. * @expect * 1.Successful * 2.Successful * 3.Successful * 4.Successful * 5.The results are as expected. */ /* BEGIN_CASE */ void SDV_CRYPT_EAL_SM3_FUNC_TC003(Hex *data1, Hex *data2, Hex *data3, Hex *hash) { TestMemInit(); uint8_t out[32]; // 32 is sm3 hash size uint32_t outLen = sizeof(out); CRYPT_EAL_MdCTX *ctx = NULL; ctx = CRYPT_EAL_MdNewCtx(CRYPT_MD_SM3); ASSERT_TRUE(ctx != NULL); ASSERT_EQ(CRYPT_EAL_MdInit(ctx), CRYPT_SUCCESS); ASSERT_EQ(CRYPT_EAL_MdUpdate(ctx, data1->x, data1->len), CRYPT_SUCCESS); ASSERT_EQ(CRYPT_EAL_MdUpdate(ctx, data2->x, data2->len), CRYPT_SUCCESS); ASSERT_EQ(CRYPT_EAL_MdUpdate(ctx, data3->x, data3->len), CRYPT_SUCCESS); ASSERT_EQ(CRYPT_EAL_MdFinal(ctx, out, &outLen), CRYPT_SUCCESS); ASSERT_EQ(outLen, 32); ASSERT_EQ(memcmp(out, hash->x, hash->len), 0); EXIT: CRYPT_EAL_MdFreeCtx(ctx); } /* END_CASE */ /** * @test SDV_CRYPT_EAL_MD_SHA2_FUNC_TC001 * @title Split the data and update test. * @precon nan * @brief * 1.Create two ctx and initialize them, expected result 1. * 2.Use ctx1 to update data 100 times, expected result 2. * 3.Use ctx2 to update all data at once, expected result 3. * 4.Compare two outputs, expected result 4. * @expect * 1.Successful. * 2.Successful. * 3.Successful. * 4.The results are the same. */ /* BEGIN_CASE */ void SDV_CRYPT_EAL_SM3_FUNC_TC004(void) { TestMemInit(); CRYPT_EAL_MdCTX *ctx1 = NULL; CRYPT_EAL_MdCTX *ctx2 = NULL; ctx1 = CRYPT_EAL_MdNewCtx(CRYPT_MD_SM3); ASSERT_TRUE(ctx1 != NULL); ctx2 = CRYPT_EAL_MdNewCtx(CRYPT_MD_SM3); ASSERT_TRUE(ctx2 != NULL); // 100! = 5050 uint8_t input[5050]; uint32_t inLenTotal = 0; uint32_t inLenBase; uint8_t out1[100]; uint8_t out2[100]; uint32_t outLen = CRYPT_EAL_MdGetDigestSize(CRYPT_MD_SM3); ASSERT_EQ(CRYPT_EAL_MdInit(ctx1), CRYPT_SUCCESS); ASSERT_EQ(CRYPT_EAL_MdInit(ctx2), CRYPT_SUCCESS); for (inLenBase = 1; inLenBase <= 100; inLenBase++) { ASSERT_EQ(CRYPT_EAL_MdUpdate(ctx1, input + inLenTotal, inLenBase), CRYPT_SUCCESS); inLenTotal += inLenBase; } ASSERT_EQ(CRYPT_EAL_MdFinal(ctx1, out1, &outLen), CRYPT_SUCCESS); outLen = CRYPT_EAL_MdGetDigestSize(CRYPT_MD_SM3); ASSERT_EQ(CRYPT_EAL_MdUpdate(ctx2, input, inLenTotal), CRYPT_SUCCESS); ASSERT_EQ(CRYPT_EAL_MdFinal(ctx2, out2, &outLen), CRYPT_SUCCESS); outLen = CRYPT_EAL_MdGetDigestSize(CRYPT_MD_SM3); ASSERT_EQ(memcmp(out1, out2, outLen), CRYPT_SUCCESS); EXIT: CRYPT_EAL_MdFreeCtx(ctx1); CRYPT_EAL_MdFreeCtx(ctx2); } /* END_CASE */ /** * @test SDV_CRYPTO_SM3_COPY_CTX_FUNC_TC001 * @title MD5 copy ctx function test. * @precon nan * @brief * 1. Create the context ctx of md algorithm, expected result 1 * 2. Call to CRYPT_EAL_MdCopyCtx method to copy ctx, expected result 2 * 2. Call to CRYPT_EAL_MdCopyCtx method to copy a null ctx, expected result 3 * 3. Calculate the hash of msg, and compare the calculated result with hash vector, expected result 4 * 4. Call to CRYPT_EAL_MdDupCtx method to copy ctx, expected result 5 * 3. Calculate the hash of msg, and compare the calculated result with hash vector, expected result 6 * @expect * 1. Success, the context is not null. * 2. CRYPT_SUCCESS * 3. CRYPT_NULL_INPUT * 4. Success, the context is not null. * 5. CRYPT_SUCCESS * 6. Success, the hashs are the same. */ /* BEGIN_CASE */ void SDV_CRYPTO_SM3_COPY_CTX_FUNC_TC001(int id, Hex *msg, Hex *hash) { TestMemInit(); CRYPT_EAL_MdCTX *cpyCtx = NULL; CRYPT_EAL_MdCTX *dupCtx = NULL; CRYPT_EAL_MdCTX *ctx = CRYPT_EAL_MdNewCtx(id); ASSERT_TRUE(ctx != NULL); uint8_t output[32]; // SM3 digest length is 32 uint32_t outLen = sizeof(output); dupCtx=CRYPT_EAL_MdDupCtx(cpyCtx); ASSERT_TRUE(dupCtx == NULL); ASSERT_EQ(CRYPT_MD_MAX, CRYPT_EAL_MdGetId(dupCtx)); cpyCtx = CRYPT_EAL_MdNewCtx(id); ASSERT_TRUE(cpyCtx != NULL); ASSERT_TRUE(dupCtx == NULL); ASSERT_EQ(CRYPT_EAL_MdCopyCtx(cpyCtx, dupCtx), CRYPT_NULL_INPUT); ASSERT_EQ(CRYPT_EAL_MdCopyCtx(cpyCtx, ctx), CRYPT_SUCCESS); ASSERT_EQ(CRYPT_EAL_MdInit(cpyCtx), CRYPT_SUCCESS); ASSERT_EQ(CRYPT_EAL_MdUpdate(cpyCtx, msg->x, msg->len), CRYPT_SUCCESS); ASSERT_EQ(CRYPT_EAL_MdFinal(cpyCtx, output, &outLen), CRYPT_SUCCESS); ASSERT_EQ(id, cpyCtx->id); ASSERT_EQ(memcmp(output, hash->x, hash->len), 0); dupCtx=CRYPT_EAL_MdDupCtx(ctx); ASSERT_TRUE(dupCtx != NULL); ASSERT_EQ(CRYPT_EAL_MdInit(dupCtx), CRYPT_SUCCESS); ASSERT_EQ(CRYPT_EAL_MdUpdate(dupCtx, msg->x, msg->len), CRYPT_SUCCESS); ASSERT_EQ(CRYPT_EAL_MdFinal(dupCtx, output, &outLen), CRYPT_SUCCESS); ASSERT_EQ(id, CRYPT_EAL_MdGetId(dupCtx)); ASSERT_EQ(memcmp(output, hash->x, hash->len), 0); EXIT: CRYPT_EAL_MdFreeCtx(ctx); CRYPT_EAL_MdFreeCtx(cpyCtx); CRYPT_EAL_MdFreeCtx(dupCtx); } /* END_CASE */ /** * @test SDV_CRYPTO_SM3_DEFAULT_PROVIDER_FUNC_TC001 * @title Default provider testing * @precon nan * @brief * Load the default provider and use the test vector to test its correctness */ /* BEGIN_CASE */ void SDV_CRYPTO_SM3_DEFAULT_PROVIDER_FUNC_TC001(int id, Hex *msg, Hex *hash) { TestMemInit(); CRYPT_EAL_MdCTX *ctx = NULL; #ifdef HITLS_CRYPTO_PROVIDER ctx = CRYPT_EAL_ProviderMdNewCtx(NULL, id, "provider=default"); #else ctx = CRYPT_EAL_MdNewCtx(id); #endif ASSERT_TRUE(ctx != NULL); uint8_t output[32]; // SM3 digest length is 32 uint32_t outLen = sizeof(output); ASSERT_EQ(CRYPT_EAL_MdInit(ctx), CRYPT_SUCCESS); ASSERT_EQ(CRYPT_EAL_MdUpdate(ctx, msg->x, msg->len), CRYPT_SUCCESS); ASSERT_EQ(CRYPT_EAL_MdFinal(ctx, output, &outLen), CRYPT_SUCCESS); ASSERT_EQ(memcmp(output, hash->x, hash->len), 0); EXIT: CRYPT_EAL_MdFreeCtx(ctx); } /* END_CASE */ /** * @test SDV_CRYPT_EAL_MD_SM3_FUNC_TC001 * @title Test multi-thread hash calculation. * @precon nan * @brief * 1.Create two threads and calculate the hash, expected result 1. * 2.Compare the result to the expected value, expected result 2. * @expect * 1.Hash calculation succeeded. * 2.The results are as expected. */ /* BEGIN_CASE */ void SDV_CRYPT_EAL_MD_SM3_FUNC_TC001(Hex *data, Hex *hash) { int ret; TestMemInit(); const uint32_t threadNum = 2; pthread_t thrd[2]; ThreadParameter arg[2] = { {data->x, hash->x, data->len, hash->len}, {data->x, hash->x, data->len, hash->len} }; for (uint32_t i = 0; i < threadNum; i++) { ret = pthread_create(&thrd[i], NULL, (void *)MultiThreadTest, &arg[i]); ASSERT_TRUE(ret == 0); } for (uint32_t i = 0; i < threadNum; i++) { pthread_join(thrd[i], NULL); } EXIT: return; } /* END_CASE */
2301_79861745/bench_create
testcode/sdv/testcase/crypto/sm3/test_suite_sdv_eal_sm3.c
C
unknown
13,952
/* * This file is part of the openHiTLS project. * * openHiTLS is licensed under the Mulan PSL v2. * You can use this software according to the terms and conditions of the Mulan PSL v2. * You may obtain a copy of Mulan PSL v2 at: * * http://license.coscl.org.cn/MulanPSL2 * * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, * EITHER EXPRESS 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_errno.h" #include "crypt_eal_cipher.h" #include "bsl_sal.h" #include "pthread.h" #include "securec.h" #include "eal_cipher_local.h" #define BLOCKSIZE 16 #define KEYSIZE 32 #define MAXSIZE 1024 #define MAX_OUTPUT 5000 #define MAX_DATASZIE 20000 /* END_HEADER */ static int SetPadding(int isSetPadding, CRYPT_EAL_CipherCtx *ctxEnc, int padding) { if (isSetPadding == 1) { return CRYPT_EAL_CipherSetPadding(ctxEnc, padding); } return CRYPT_SUCCESS; } static int Sm4CipherFinal( int algId, CRYPT_EAL_CipherCtx *ctx, uint8_t *outTmp, uint32_t *finLen) { if (algId != CRYPT_CIPHER_SM4_GCM) { return CRYPT_EAL_CipherFinal(ctx, outTmp, finLen); } *finLen = 0; return CRYPT_SUCCESS; } /** * @test SDV_CRYPTO_SM4_INIT_API_TC001 * @title Impact of IV validity on algorithm module initialization Test * @precon Registering memory-related functions. * @brief * 1.Create the context ctx. Expected result 1 is obtained. * 2.Call the Init interface, ctx is not NULL, iv is NULL, ivLen is 0, and key is normal value. Expected result 2 is obtained. * 3.Call the Init interface, ctx is not NULL, iv is not NULL, ivLen is 0, and key is normal value. Expected result 3 is obtained. * 4.Call the Init interface, ctx is not NULL, iv is not NULL, ivLen is 15, and key is normal value. Expected result 4 is obtained. * 5.Call the Init interface, ctx is not NULL, iv is not NULL, ivLen is 17, and key is normal value. Expected result 5 is obtained. * @expect * 1.The creation is successful and the ctx is not empty. * 2.Failed. * 3.Failed. * 4.Failed except for the GCM algorithm. * 5.Failed except for the GCM algorithm. */ /* BEGIN_CASE */ void SDV_CRYPTO_SM4_INIT_API_TC001(int id, Hex *key, Hex *iv) { TestMemInit(); int32_t ret; CRYPT_EAL_CipherCtx *ctx = CRYPT_EAL_CipherNewCtx(id); ASSERT_TRUE(ctx != NULL); ret = CRYPT_EAL_CipherInit(ctx, key->x, key->len, NULL, 0, true); ASSERT_TRUE(ret != CRYPT_SUCCESS); ret = CRYPT_EAL_CipherInit(ctx, key->x, key->len, iv->x, 0, true); ASSERT_TRUE(ret != CRYPT_SUCCESS); ret = CRYPT_EAL_CipherInit(ctx, key->x, key->len, iv->x, BLOCKSIZE - 1, true); if (id == CRYPT_CIPHER_SM4_GCM) { ASSERT_TRUE(ret == CRYPT_SUCCESS); } else { ASSERT_TRUE(ret != CRYPT_SUCCESS); } if (id == CRYPT_CIPHER_SM4_GCM) { ret = CRYPT_EAL_CipherInit(ctx, key->x, key->len, iv->x, BLOCKSIZE, true); ASSERT_TRUE(ret == CRYPT_SUCCESS); } else { ret = CRYPT_EAL_CipherInit(ctx, key->x, key->len, iv->x, BLOCKSIZE + 1, true); ASSERT_TRUE(ret != CRYPT_SUCCESS); } EXIT: CRYPT_EAL_CipherFreeCtx(ctx); } /* END_CASE */ /** * @test SDV_CRYPTO_SM4_INIT_API_TC002 * @title Impact of input parameters on the CRYPT_EAL_CipherInit interface Test * @precon Registering memory-related functions. * @brief * 1.Create the context ctx with CRYPT_CIPHER_SM4_XTS. Expected result 1 is obtained. * 2.Call the Init interface, ctx is NULL. Expected result 2 is obtained. * 3.Call the Init interface, ctx is not NULL, key is NULL. Expected result 3 is obtained. * 4.Call the Init interface, ctx is not NULL, key is not NULL, iv is NULL. Expected result 4 is obtained. * 5.Call the Init interface, ctx, key and iv is not NULL, keyLen is less than or greater than 32 bytes. Expected result 5 is obtained. * 6.Call the Init interface, ctx, key and iv is not NULL, keyLen is 32 bytes and the previous and next 16 bytes are the same. Expected result 6 is obtained. * 7.Call the Init interface, ctx, key and iv is not NULL, ivLen is less than or greater than 16 bytes. Expected result 7 is obtained. * @expect * 1.The creation is successful and the ctx is not empty. * 2.Initialization failed. * 3.Initialization failed. * 4.Initialization failed. * 5.Initialization failed. * 6.Initialization failed. * 7.Initialization failed. */ /* BEGIN_CASE */ void SDV_CRYPTO_SM4_INIT_API_TC002(Hex *key, Hex *iv, int enc) { uint8_t unsafe_key[KEYSIZE] = {0}; TestMemInit(); int32_t ret; CRYPT_EAL_CipherCtx *ctx = CRYPT_EAL_CipherNewCtx(CRYPT_CIPHER_SM4_XTS); ASSERT_TRUE(ctx != NULL); ret = CRYPT_EAL_CipherInit(NULL, key->x, key->len, iv->x, iv->len, enc); ASSERT_TRUE(ret == CRYPT_NULL_INPUT); ret = CRYPT_EAL_CipherInit(ctx, NULL, key->len, iv->x, iv->len, enc); ASSERT_TRUE(ret == CRYPT_NULL_INPUT); ret = CRYPT_EAL_CipherInit(ctx, key->x, key->len, NULL, iv->len, enc); ASSERT_TRUE(ret == CRYPT_NULL_INPUT); ret = CRYPT_EAL_CipherInit(ctx, key->x, 0, iv->x, iv->len, enc); ASSERT_TRUE(ret != CRYPT_SUCCESS); ret = CRYPT_EAL_CipherInit(ctx, key->x, 1, iv->x, iv->len, enc); ASSERT_TRUE(ret != CRYPT_SUCCESS); ret = CRYPT_EAL_CipherInit(ctx, key->x, 16, iv->x, iv->len, enc); ASSERT_TRUE(ret != CRYPT_SUCCESS); ret = CRYPT_EAL_CipherInit(ctx, key->x, 33, iv->x, iv->len, enc); ASSERT_TRUE(ret != CRYPT_SUCCESS); ret = CRYPT_EAL_CipherInit(ctx, key->x, key->len, iv->x, iv->len, enc); ASSERT_TRUE(ret == CRYPT_SUCCESS); ret = CRYPT_EAL_CipherInit(ctx, unsafe_key, KEYSIZE, iv->x, iv->len, true); ASSERT_TRUE(ret != CRYPT_SUCCESS); ret = CRYPT_EAL_CipherInit(ctx, unsafe_key, KEYSIZE, iv->x, iv->len, false); ASSERT_TRUE(ret != CRYPT_SUCCESS); ASSERT_EQ(CRYPT_EAL_CipherInit(ctx, key->x, key->len, iv->x, 0, enc), CRYPT_MODES_IVLEN_ERROR); ASSERT_EQ(CRYPT_EAL_CipherInit(ctx, key->x, key->len, iv->x, 1, enc), CRYPT_MODES_IVLEN_ERROR); ASSERT_EQ(CRYPT_EAL_CipherInit(ctx, key->x, key->len, iv->x, 15, enc), CRYPT_MODES_IVLEN_ERROR); ASSERT_EQ(CRYPT_EAL_CipherInit(ctx, key->x, key->len, iv->x, 17, enc), CRYPT_MODES_IVLEN_ERROR); ret = CRYPT_EAL_CipherInit(ctx, key->x, key->len, iv->x, iv->len, enc); ASSERT_TRUE(ret == CRYPT_SUCCESS); EXIT: CRYPT_EAL_CipherDeinit(ctx); CRYPT_EAL_CipherFreeCtx(ctx); } /* END_CASE */ /** * @test SDV_CRYPTO_SM4_INIT_API_TC003 * @title Impact of key validity on algorithm module initialization Test * @precon Registering memory-related functions. * @brief * 1.Create the context ctx. Expected result 1 is obtained. * 2.Call the Init interface, ctx is NULL. Expected result 2 is obtained. * 3.Call the Init interface, ctx is not NULL, key is NULL, keyLen is 0. Expected result 3 is obtained. * 4.Call the Init interface, ctx is not NULL, key is not NULL, keyLen is 0. Expected result 4 is obtained. * 5.Call the Init interface, ctx is not NULL, key is not NULL, keyLen is 15. Expected result 5 is obtained. * 6.Call the Init interface, ctx is not NULL, key is not NULL, keyLen is 17. Expected result 6 is obtained. * @expect * 1.The creation is successful and the ctx is not empty. * 2.Initialization failed. * 3.Initialization failed. * 4.Initialization failed. * 5.Initialization failed. * 6.Initialization failed. */ /* BEGIN_CASE */ void SDV_CRYPTO_SM4_INIT_API_TC003(int id, Hex *key, Hex *iv) { TestMemInit(); int32_t ret; CRYPT_EAL_CipherCtx *ctx = CRYPT_EAL_CipherNewCtx(id); ASSERT_TRUE(ctx != NULL); ret = CRYPT_EAL_CipherInit(NULL, key->x, key->len, iv->x, iv->len, true); ASSERT_TRUE(ret == CRYPT_NULL_INPUT); ret = CRYPT_EAL_CipherInit(ctx, NULL, 0, iv->x, iv->len, true); ASSERT_TRUE(ret != CRYPT_SUCCESS); ret = CRYPT_EAL_CipherInit(ctx, key->x, 0, iv->x, iv->len, true); ASSERT_TRUE(ret != CRYPT_SUCCESS); ret = CRYPT_EAL_CipherInit(ctx, key->x, BLOCKSIZE - 1, iv->x, iv->len, true); ASSERT_TRUE(ret != CRYPT_SUCCESS); ret = CRYPT_EAL_CipherInit(ctx, key->x, BLOCKSIZE + 1, iv->x, iv->len, true); ASSERT_TRUE(ret != CRYPT_SUCCESS); EXIT: CRYPT_EAL_CipherFreeCtx(ctx); } /* END_CASE */ /** * @test SDV_CRYPTO_SM4_DEINIT_API_TC001 * @title Impact of input parameters on the CRYPT_EAL_CipherDeinit interface Test * @precon Registering memory-related functions. * @brief * 1.Create the context ctx. Expected result 1 is obtained. * 2.Call the Deinit interface, ctx is NULL. Expected result 2 is obtained. * 3.Call the Deinit interface. All parameters are normal. Expected result 3 is obtained. * @expect * 1.The creation is successful and the ctx is not empty. * 2.The function is executed successfully. * 3.The function is executed successfully. */ /* BEGIN_CASE */ void SDV_CRYPTO_SM4_DEINIT_API_TC001(int id) { TestMemInit(); CRYPT_EAL_CipherCtx *ctx = CRYPT_EAL_CipherNewCtx(id); ASSERT_TRUE(ctx != NULL); CRYPT_EAL_CipherDeinit(ctx); CRYPT_EAL_CipherDeinit(NULL); EXIT: CRYPT_EAL_CipherDeinit(ctx); CRYPT_EAL_CipherFreeCtx(ctx); } /* END_CASE */ /** * @test SDV_CRYPTO_SM4_REINIT_API_TC001 * @title CRYPT_EAL_CipherReinit for iv Test * @precon Registering memory-related functions. * @brief * 1.Create the context ctx. Expected result 1 is obtained. * 2.Call the Reinit interface. Expected result 2 is obtained. * 3.Call the Init interface. Expected result 3 is obtained. * 4.Call the Reinit interface, ctx is NULL, iv is not NULL, ivLen is not 0. Expected result 4 is obtained. * 5.Call the Reinit interface, ctx is not NULL, iv is NULL, ivLen is not 0. Expected result 5 is obtained. * 6.Call the Reinit interface, ctx is not NULL, iv is not NULL, ivLen is 0. Expected result 6 is obtained. * @expect * 1.The creation is successful and the ctx is not empty. * 2.Failed. Return CRYPT_EAL_ERR_STATE. * 3.The init is successful and return CRYPT_SUCCESS. * 4.Failed. Return CRYPT_NULL_INPUT. * 5.Failed. Return CRYPT_NULL_INPUT. * 6.Failed. Return CRYPT_NULL_INPUT/CRYPT_MODES_IVLEN_ERROR. */ /* BEGIN_CASE */ void SDV_CRYPTO_SM4_REINIT_API_TC001(int id, Hex *key, Hex *iv) { TestMemInit(); int32_t ret; CRYPT_EAL_CipherCtx *ctx = CRYPT_EAL_CipherNewCtx(id); ASSERT_TRUE(ctx != NULL); ret = CRYPT_EAL_CipherReinit(ctx, iv->x, iv->len); ASSERT_TRUE(ret == CRYPT_EAL_ERR_STATE); ASSERT_EQ(CRYPT_EAL_CipherInit(ctx, key->x, key->len, iv->x, iv->len, true), CRYPT_SUCCESS); ret = CRYPT_EAL_CipherReinit(NULL, iv->x, iv->len); ASSERT_TRUE(ret == CRYPT_NULL_INPUT); ret = CRYPT_EAL_CipherReinit(ctx, NULL, iv->len); ASSERT_TRUE(ret == CRYPT_NULL_INPUT); ret = CRYPT_EAL_CipherReinit(ctx, iv->x, 0); if (id == CRYPT_CIPHER_SM4_GCM) { ASSERT_TRUE(ret == CRYPT_NULL_INPUT); } else { ASSERT_TRUE(ret == CRYPT_MODES_IVLEN_ERROR); } EXIT: CRYPT_EAL_CipherDeinit(ctx); CRYPT_EAL_CipherFreeCtx(ctx); } /* END_CASE */ /** * @test SDV_CRYPTO_SM4_UPDATE_API_TC001 * @title Impact of input parameters on the CRYPT_EAL_CipherUpdate interface Test * @precon Registering memory-related functions. * @brief * 1.Create the context ctx. Expected result 1 is obtained. * 2.Call the Init interface. Expected result 2 is obtained. * 3.Call the Update interface, ctx is NULL. Expected result 3 is obtained. * 4.Call the Update interface, ctx is not NULL, in is NULL. Expected result 4 is obtained. * 5.Call the Update interface, ctx is not NULL, in is not NULL, out is NULL. Expected result 5 is obtained. * 6.Call the Update interface, ctx, in, out is NULL, inLen is 1. Expected result 6 is obtained. * 7.Call the Update interface, ctx, in, out is NULL, outLen is NULL. Expected result 7 is obtained. * @expect * 1.The creation is successful and the ctx is not empty. * 2.The init is successful and return CRYPT_SUCCESS. * 3.Failed. Return CRYPT_NULL_INPUT. * 4.Failed. Return CRYPT_NULL_INPUT. * 5.Failed. Return CRYPT_NULL_INPUT. * 6.Failed When is the XTS algorithm. * 7.Failed. Return CRYPT_NULL_INPUT. */ /* BEGIN_CASE */ void SDV_CRYPTO_SM4_UPDATE_API_TC001(int id, Hex *key, Hex *iv, Hex *in, int enc) { TestMemInit(); int32_t ret; uint8_t out[BLOCKSIZE * 32] = {0}; uint32_t len = BLOCKSIZE * 32; CRYPT_EAL_CipherCtx *ctx = CRYPT_EAL_CipherNewCtx(id); ASSERT_TRUE(ctx != NULL); ret = CRYPT_EAL_CipherInit(ctx, key->x, key->len, iv->x, iv->len, enc); ASSERT_TRUE(ret == CRYPT_SUCCESS); len = BLOCKSIZE * 32; ret = CRYPT_EAL_CipherUpdate(NULL, in->x, in->len, out, &len); ASSERT_TRUE(ret == CRYPT_NULL_INPUT); len = BLOCKSIZE * 32; ret = CRYPT_EAL_CipherUpdate(ctx, NULL, in->len, out, &len); ASSERT_TRUE(ret == CRYPT_NULL_INPUT); len = BLOCKSIZE * 32; ret = CRYPT_EAL_CipherUpdate(ctx, in->x, in->len, NULL, &len); ASSERT_TRUE(ret == CRYPT_NULL_INPUT); len = BLOCKSIZE * 32; ret = CRYPT_EAL_CipherUpdate(ctx, in->x, 0, out, &len); ASSERT_TRUE(ret == CRYPT_SUCCESS); len = BLOCKSIZE * 32; ret = CRYPT_EAL_CipherUpdate(ctx, in->x, 1, out, &len); if (id == CRYPT_CIPHER_SM4_XTS) { ASSERT_TRUE(ret != CRYPT_SUCCESS); } else { ASSERT_TRUE(ret == CRYPT_SUCCESS); } ret = CRYPT_EAL_CipherUpdate(ctx, in->x, in->len, out, NULL); ASSERT_TRUE(ret == CRYPT_NULL_INPUT); len = BLOCKSIZE * 32; ret = CRYPT_EAL_CipherUpdate(ctx, in->x, in->len, out, &len); ASSERT_TRUE(ret == CRYPT_SUCCESS); ASSERT_TRUE(len == in->len); EXIT: CRYPT_EAL_CipherDeinit(ctx); CRYPT_EAL_CipherFreeCtx(ctx); } /* END_CASE */ /** * @test SDV_CRYPTO_SM4_CTRL_API_TC001 * @title Impact of the setting type on the Ctrl setting parameters Test * @precon Registering memory-related functions. * @brief * 1.Create the context ctx. Expected result 1 is obtained. * 2.Call the Init interface, iv is IV1. Expected result 2 is obtained. * 3.Call the Ctrl interface to get iv. Expected result 3 is obtained. * 4.Call the Update interface to encrypt, inLen is 15. Expected result 4 is obtained. * 5.Call the Ctrl interface to get iv. Expected result 5 is obtained. * 6.Call the Update interface to encrypt, inLen is 1. Expected result 6 is obtained. * 7.Call the Ctrl interface to get iv, record as IV2. Expected result 7 is obtained. * 8.Call the Update interface to encrypt, inLen is 16. Expected result 8 is obtained. * 9.Call the Ctrl interface to get iv. Expected result 9 is obtained. * @expect * 1.The creation is successful and the ctx is not empty. * 2.The init is successful and return CRYPT_SUCCESS. * 3.Iv value is equal to IV1. * 4.Success. Return CRYPT_SUCCESS. * 5.Iv value is equal to IV1. * 6.Success. Return CRYPT_SUCCESS. * 7.Iv value is not equal to IV1. * 8.Success. Return CRYPT_SUCCESS. * 9.Iv value is not equal to IV2. */ /* BEGIN_CASE */ void SDV_CRYPTO_SM4_CTRL_API_TC001(Hex *key, Hex *iv, Hex *msg) { TestMemInit(); int32_t ret; uint8_t iv1[BLOCKSIZE] = {0}; uint8_t iv2[BLOCKSIZE] = {0}; const uint32_t len = BLOCKSIZE; uint8_t out[MAXSIZE] = {0}; uint32_t outlen = MAXSIZE; CRYPT_EAL_CipherCtx *ctx = CRYPT_EAL_CipherNewCtx(CRYPT_CIPHER_SM4_CBC); ASSERT_TRUE(ctx != NULL); ret = CRYPT_EAL_CipherInit(ctx, key->x, key->len, iv->x, iv->len, true); ASSERT_TRUE(ret == CRYPT_SUCCESS); ASSERT_EQ(CRYPT_EAL_CipherCtrl(ctx, CRYPT_CTRL_SET_AAD, iv->x, iv->len), CRYPT_MODES_CTRL_TYPE_ERROR); ret = CRYPT_EAL_CipherCtrl(ctx, CRYPT_CTRL_GET_IV, iv1, len); ASSERT_TRUE(ret == CRYPT_SUCCESS); ASSERT_TRUE(memcmp(iv1, iv->x, iv->len) == 0); (void)memset_s(iv1, BLOCKSIZE, 0, BLOCKSIZE); ret = CRYPT_EAL_CipherUpdate(ctx, msg->x, BLOCKSIZE - 1, out, &outlen); ASSERT_TRUE(ret == CRYPT_SUCCESS); ret = CRYPT_EAL_CipherCtrl(ctx, CRYPT_CTRL_GET_IV, iv1, len); ASSERT_TRUE(ret == CRYPT_SUCCESS); ASSERT_TRUE(memcmp(iv1, iv->x, iv->len) == 0); (void)memset_s(iv1, BLOCKSIZE, 0, BLOCKSIZE); outlen = MAXSIZE; ret = CRYPT_EAL_CipherUpdate(ctx, msg->x, 1, out, &outlen); ASSERT_TRUE(ret == CRYPT_SUCCESS); ret = CRYPT_EAL_CipherCtrl(ctx, CRYPT_CTRL_GET_IV, iv1, len); ASSERT_TRUE(ret == CRYPT_SUCCESS); ASSERT_TRUE(memcmp(iv1, iv->x, iv->len) != 0); outlen = MAXSIZE; ret = CRYPT_EAL_CipherUpdate(ctx, msg->x, BLOCKSIZE, out, &outlen); ASSERT_TRUE(ret == CRYPT_SUCCESS); ret = CRYPT_EAL_CipherCtrl(ctx, CRYPT_CTRL_GET_IV, iv2, len); ASSERT_TRUE(ret == CRYPT_SUCCESS); ASSERT_TRUE(memcmp(iv2, iv1, BLOCKSIZE) != 0); EXIT: CRYPT_EAL_CipherFreeCtx(ctx); } /* END_CASE */ /** * @test SDV_CRYPTO_SM4_CTRL_API_TC003 * @title Impact of input parameters on the CRYPT_EAL_CipherCtrl interface Test * @precon Registering memory-related functions. * @brief * 1.Create the context ctx. Expected result 1 is obtained. * 2.Call the Init interface. Expected result 2 is obtained. * 3.Call the Ctrl interface, ctx is not NULL, type is get iv, other parameters are normal. Expected result 3 is obtained. * 4.Call the Ctrl interface, ctx is not NULL, type is get blocksize, other parameters are normal. Expected result 4 is obtained. * 5.Call the Ctrl interface, ctx is not NULL, type is get iv, data is NULL, len is 16. Expected result 5 is obtained. * 6.Call the Ctrl interface, ctx is not NULL, type is get iv, data is not NULL, len is 0. Expected result 6 is obtained. * 7.Call the Ctrl interface, ctx is not NULL, type is get blocksize, data is not NULL, len is 0. Expected result 7 is obtained. * 8.Call the Ctrl interface, ctx is not NULL, type is invalid value. Expected result 8 is obtained. * @expect * 1.The creation is successful and the ctx is not empty. * 2.The init is successful and return CRYPT_SUCCESS. * 3.Success. Return CRYPT_SUCCESS. * 4.Success. Return CRYPT_SUCCESS. * 5.Failed. Return CRYPT_NULL_INPUT. * 6.Failed. Return CRYPT_MODE_ERR_INPUT_LEN. * 7.Failed. Return CRYPT_MODE_ERR_INPUT_LEN. * 8.Failed. CRYPT_MODES_METHODS_NOT_SUPPORT. */ /* BEGIN_CASE */ void SDV_CRYPTO_SM4_CTRL_API_TC003(Hex *key, Hex *iv) { TestMemInit(); int32_t ret; uint8_t *ivGet[BLOCKSIZE] = {0}; const uint32_t len = BLOCKSIZE; uint32_t blockSizeGet = 0; CRYPT_EAL_CipherCtx *ctx = CRYPT_EAL_CipherNewCtx(CRYPT_CIPHER_SM4_XTS); ASSERT_TRUE(ctx != NULL); ret = CRYPT_EAL_CipherInit(ctx, key->x, key->len, iv->x, iv->len, true); ASSERT_TRUE(ret == CRYPT_SUCCESS); ret = CRYPT_EAL_CipherCtrl(ctx, CRYPT_CTRL_GET_IV, ivGet, len); ASSERT_TRUE(ret == CRYPT_SUCCESS); ret = CRYPT_EAL_CipherCtrl(ctx, CRYPT_CTRL_GET_BLOCKSIZE, (uint8_t *)&blockSizeGet, sizeof(uint32_t)); ASSERT_TRUE(blockSizeGet == 1); ASSERT_TRUE(ret == CRYPT_SUCCESS); ret = CRYPT_EAL_CipherCtrl(ctx, CRYPT_CTRL_GET_IV, NULL, len); ASSERT_TRUE(ret == CRYPT_NULL_INPUT); ASSERT_EQ(CRYPT_EAL_CipherCtrl(ctx, CRYPT_CTRL_GET_IV, ivGet, 0), CRYPT_MODE_ERR_INPUT_LEN); ASSERT_EQ(CRYPT_EAL_CipherCtrl(ctx, CRYPT_CTRL_GET_BLOCKSIZE, (uint8_t *)&blockSizeGet, 0), CRYPT_MODE_ERR_INPUT_LEN); ASSERT_EQ(CRYPT_EAL_CipherCtrl(ctx, CRYPT_CTRL_MAX, iv->x, iv->len), CRYPT_MODES_CTRL_TYPE_ERROR); EXIT: CRYPT_EAL_CipherDeinit(ctx); CRYPT_EAL_CipherFreeCtx(ctx); } /* END_CASE */ /** * @test SDV_CRYPTO_SM4_ENCRYPT_FUNC_TC001 * @title Call Final interface without call Update interface Test. * @precon Registering memory-related functions. * @brief * 1.Create the context ctx. Expected result 1 is obtained. * 2.Call the Init interface. Expected result 2 is obtained. * 3.Set the following padding algorithm CRYPT_PADDING_PKCS7 CRYPT_PADDING_PKCS5 CRYPT_PADDING_X923 CRYPT_PADDING_ISO7816 CRYPT_PADDING_ZEROS. Expected result 3 is obtained. * 4.Call the Final interface. Expected result 4 is obtained. * 5.Use the SM4 decryption handle to call the Update interface with the ciphertext. Expected result 5 is obtained. * 6.Call the Final interface. Expected result 6 is obtained. * @expect * 1.The creation is successful and the ctx is not empty. * 2.The init is successful, return CRYPT_SUCCESS. * 3.Succeeded in setting the padding algorithm. * 4.The ciphertext is consistent with the test vector. * 5.The update is successful, return CRYPT_SUCCESS. * 6.The plaintext is consistent with the test vector. */ /* BEGIN_CASE */ void SDV_CRYPTO_SM4_ENCRYPT_FUNC_TC001(int id, Hex *key, Hex *iv, int padding, int isSetPadding) { TestMemInit(); int32_t ret; uint8_t outTmp[MAXSIZE] = {0}; uint8_t result[MAXSIZE] = {0}; uint32_t totalLen = 0; uint32_t decLen = MAXSIZE; uint32_t len = MAXSIZE; CRYPT_EAL_CipherCtx *ctxEnc = NULL; CRYPT_EAL_CipherCtx *ctxDec = NULL; ctxEnc = CRYPT_EAL_CipherNewCtx(id); ASSERT_TRUE(ctxEnc != NULL); ret = SetPadding(isSetPadding, ctxEnc, padding); ASSERT_TRUE(ret == CRYPT_SUCCESS); ret = CRYPT_EAL_CipherInit(ctxEnc, key->x, key->len, iv->x, iv->len, true); ASSERT_TRUE(ret == CRYPT_SUCCESS); ret = CRYPT_EAL_CipherFinal(ctxEnc, outTmp, &len); ASSERT_TRUE(ret == CRYPT_SUCCESS); ctxDec = CRYPT_EAL_CipherNewCtx(id); ASSERT_TRUE(ctxDec != NULL); ret = CRYPT_EAL_CipherInit(ctxDec, key->x, key->len, iv->x, iv->len, false); ASSERT_TRUE(ret == CRYPT_SUCCESS); ret = SetPadding(isSetPadding, ctxDec, padding); ASSERT_TRUE(ret == CRYPT_SUCCESS); ret = CRYPT_EAL_CipherUpdate(ctxDec, outTmp, len, result, &decLen); ASSERT_TRUE(ret == CRYPT_SUCCESS); totalLen += decLen; decLen = MAXSIZE - totalLen; ret = CRYPT_EAL_CipherFinal(ctxDec, result + totalLen, &decLen); ASSERT_TRUE(ret == CRYPT_SUCCESS); EXIT: CRYPT_EAL_CipherFreeCtx(ctxEnc); CRYPT_EAL_CipherFreeCtx(ctxDec); } /* END_CASE */ /** * @test SDV_CRYPTO_SM4_ENCRYPT_FUNC_TC002 * @title Encryption and decryption with setting padding algorithm Test * @precon Registering memory-related functions. * @brief * 1.Create the context ctx. Expected result 1 is obtained. * 2.Call the Init interface. Expected result 2 is obtained. * 3.Set the following padding algorithm CRYPT_PADDING_PKCS7 CRYPT_PADDING_PKCS5 CRYPT_PADDING_X923 CRYPT_PADDING_ISO7816 CRYPT_PADDING_ZEROS. Expected result 3 is obtained. * 4.Call the Update interface. Expected result 4 is obtained. * 5.Call the Final interface. Expected result 5 is obtained. * 6.Use the SM4 decryption handle to call the Update interface with the ciphertext. Expected result 6 is obtained. * 7.Call the Final interface. Expected result 7 is obtained. * @expect * 1.The creation is successful and the ctx is not empty. * 2.The init is successful and return CRYPT_SUCCESS. * 3.Succeeded in setting the padding algorithm. * 4.The update is successful and return CRYPT_SUCCESS. * 5.The ciphertext is consistent with the test vector. * 6.The update is successful and return CRYPT_SUCCESS. * 7.The plaintext is consistent with the test vector. */ /* BEGIN_CASE */ void SDV_CRYPTO_SM4_ENCRYPT_FUNC_TC002(int algId, Hex *key, Hex *iv, int inLen, int padding) { TestMemInit(); uint8_t input[MAXSIZE] = {0}; uint8_t outTmp[MAXSIZE] = {0}; uint8_t result[MAXSIZE] = {0}; uint32_t totalLen = 0; uint32_t leftLen = MAXSIZE; uint32_t len = MAXSIZE; (void)memset_s(outTmp, MAXSIZE, 0xAA, MAXSIZE); (void)memset_s(input, MAXSIZE, 0xAA, MAXSIZE); CRYPT_EAL_CipherCtx *ctxEnc = NULL; CRYPT_EAL_CipherCtx *ctxDec = NULL; ASSERT_TRUE(inLen <= MAXSIZE); ctxEnc = CRYPT_EAL_CipherNewCtx(algId); ASSERT_TRUE(ctxEnc != NULL); ASSERT_EQ(CRYPT_EAL_CipherInit(ctxEnc, key->x, key->len, iv->x, iv->len, true), CRYPT_SUCCESS); ASSERT_EQ(CRYPT_EAL_CipherSetPadding(ctxEnc, padding), CRYPT_SUCCESS); ASSERT_EQ(CRYPT_EAL_CipherUpdate(ctxEnc, input, inLen, outTmp, &len), CRYPT_SUCCESS); totalLen += len; leftLen -= len; ASSERT_EQ(CRYPT_EAL_CipherFinal(ctxEnc, outTmp + totalLen, &leftLen), CRYPT_SUCCESS); totalLen += leftLen; len = MAXSIZE; leftLen = MAXSIZE; ctxDec = CRYPT_EAL_CipherNewCtx(algId); ASSERT_TRUE(ctxDec != NULL); ASSERT_EQ(CRYPT_EAL_CipherInit(ctxDec, key->x, key->len, iv->x, iv->len, false), CRYPT_SUCCESS); ASSERT_EQ(CRYPT_EAL_CipherSetPadding(ctxDec, padding), CRYPT_SUCCESS); ASSERT_EQ(CRYPT_EAL_CipherUpdate(ctxDec, outTmp, totalLen, result, &len), CRYPT_SUCCESS); leftLen -= len; ASSERT_EQ(CRYPT_EAL_CipherFinal(ctxDec, result + len, &leftLen), CRYPT_SUCCESS); ASSERT_TRUE(memcmp(input, result, inLen) == 0); EXIT: CRYPT_EAL_CipherFreeCtx(ctxEnc); CRYPT_EAL_CipherFreeCtx(ctxDec); } /* END_CASE */ /** * @test SDV_CRYPTO_SM4_ENCRYPT_FUNC_TC003 * @title Input data of different lengths encryption Test * @precon Registering memory-related functions. * @brief * 1.Create the context ctx. Expected result 1 is obtained. * 2.Call the Init interface. Expected result 2 is obtained. * 3.Call the Update interface. Expected result 3 is obtained. * @expect * 1.The creation is successful and the ctx is not empty. * 2.The init is successful, return CRYPT_SUCCESS. * 3.The update is successful, return CRYPT_SUCCESS. */ /* BEGIN_CASE */ void SDV_CRYPTO_SM4_ENCRYPT_FUNC_TC003(int isProvider, int id, Hex *key, Hex *plainText, Hex *cipherText, Hex *iv) { if (IsSm4AlgDisabled(id)) { SKIP_TEST(); } TestMemInit(); uint8_t out[MAXSIZE] = {0}; uint32_t len = plainText->len; CRYPT_EAL_CipherCtx *ctx = TestCipherNewCtx(NULL, id, "provider=default", isProvider); ASSERT_TRUE(ctx != NULL); ASSERT_EQ(CRYPT_EAL_CipherInit(ctx, key->x, key->len, iv->x, iv->len, true), CRYPT_SUCCESS); ASSERT_EQ(CRYPT_EAL_CipherUpdate(ctx, plainText->x, plainText->len, out, &len), CRYPT_SUCCESS); ASSERT_TRUE(memcmp(out, cipherText->x, len) == 0); EXIT: CRYPT_EAL_CipherFreeCtx(ctx); } /* END_CASE */ /** * @test SDV_CRYPTO_SM4_ENCRYPT_FUNC_TC004 * @title Input data of different lengths decryption Test * @precon Registering memory-related functions. * @brief * 1.Create the context ctx. Expected result 1 is obtained. * 2.Call the Init interface. Expected result 2 is obtained. * 3.Call the Update interface. Expected result 3 is obtained. * @expect * 1.The creation is successful and the ctx is not empty. * 2.The init is successful, return CRYPT_SUCCESS. * 3.The update is successful, return CRYPT_SUCCESS. */ /* BEGIN_CASE */ void SDV_CRYPTO_SM4_ENCRYPT_FUNC_TC004(int isProvider, int id, Hex *key, Hex *plainText, Hex *cipherText, Hex *iv) { if (IsSm4AlgDisabled(id)) { SKIP_TEST(); } TestMemInit(); int32_t ret; uint8_t out[MAXSIZE] = {0}; uint32_t len = cipherText->len; CRYPT_EAL_CipherCtx *ctx = TestCipherNewCtx(NULL, id, "provider=default", isProvider); ASSERT_TRUE(ctx != NULL); ret = CRYPT_EAL_CipherInit(ctx, key->x, key->len, iv->x, iv->len, false); ASSERT_TRUE(ret == CRYPT_SUCCESS); ret = CRYPT_EAL_CipherUpdate(ctx, cipherText->x, cipherText->len, out, &len); ASSERT_TRUE(ret == CRYPT_SUCCESS); ASSERT_TRUE(memcmp(out, plainText->x, len) == 0); EXIT: CRYPT_EAL_CipherFreeCtx(ctx); } /* END_CASE */ /** * @test SDV_CRYPTO_SM4_MULTI_UPDATE_TC001 * @title Multi update encryption and decryption * @precon Registering memory-related functions. * @brief * 1.Create the context ctx. Expected result 1 is obtained. * 2.Call the Init interface. Expected result 2 is obtained. * 3.Call the Update interface with plaintext for multi times. Expected result 3 is obtained. * 4.Call the Final interface. Expected result 4 is obtained. * 5.Use the SM4 decryption handle to call the Update interface with the ciphertext. Expected result 5 is obtained. * 6.Call the Final interface. Expected result 6 is obtained. * @expect * 1.The creation is successful and the ctx is not empty. * 2.The init is successful, return CRYPT_SUCCESS. * 3.The update is successful, return CRYPT_SUCCESS. * 4.The final is successful, return CRYPT_SUCCESS. The cipher result is consistent with the test vector. * 5.The update is successful, return CRYPT_SUCCESS. * 6.The final is successful, return CRYPT_SUCCESS. The plain result is consistent with the test vector. */ /* BEGIN_CASE */ void SDV_CRYPTO_SM4_MULTI_UPDATE_TC001(int algId, Hex *key, Hex *iv, Hex *in, int updateTimes, int padding, int isSetPadding) { TestMemInit(); int32_t ret; uint8_t outTmp[MAXSIZE * 4] = {0}; uint8_t result[MAXSIZE * 4] = {0}; uint32_t totalLen = 0; uint32_t leftLen = MAXSIZE * 4; uint32_t len = MAXSIZE * 4; CRYPT_EAL_CipherCtx *ctxEnc = NULL; CRYPT_EAL_CipherCtx *ctxDec = NULL; ctxEnc = CRYPT_EAL_CipherNewCtx(algId); ASSERT_TRUE(ctxEnc != NULL); ret = SetPadding(isSetPadding, ctxEnc, padding); ASSERT_TRUE(ret == CRYPT_SUCCESS); ret = CRYPT_EAL_CipherInit(ctxEnc, key->x, key->len, iv->x, iv->len, true); ASSERT_TRUE(ret == CRYPT_SUCCESS); ret = SetPadding(isSetPadding, ctxEnc, padding); ASSERT_TRUE(ret == CRYPT_SUCCESS); for (int i = 0; i < updateTimes; i++) { ret = CRYPT_EAL_CipherUpdate(ctxEnc, in->x, in->len, outTmp + totalLen, &len); ASSERT_TRUE(ret == CRYPT_SUCCESS); totalLen += len; leftLen -= len; len = leftLen; } if (algId != CRYPT_CIPHER_SM4_GCM) { ret = CRYPT_EAL_CipherFinal(ctxEnc, outTmp + totalLen, &leftLen); } ASSERT_TRUE(ret == CRYPT_SUCCESS); totalLen += leftLen; len = MAXSIZE * 4; leftLen = MAXSIZE * 4; ctxDec = CRYPT_EAL_CipherNewCtx(algId); ASSERT_TRUE(ctxDec != NULL); ret = CRYPT_EAL_CipherInit(ctxDec, key->x, key->len, iv->x, iv->len, false); ASSERT_TRUE(ret == CRYPT_SUCCESS); ret = SetPadding(isSetPadding, ctxEnc, padding); ASSERT_TRUE(ret == CRYPT_SUCCESS); ret = CRYPT_EAL_CipherUpdate(ctxDec, outTmp, totalLen, result, &len); leftLen -= len; ASSERT_TRUE(ret == CRYPT_SUCCESS); if (algId != CRYPT_CIPHER_SM4_GCM) { ret = CRYPT_EAL_CipherFinal(ctxDec, result + len, &leftLen); } ASSERT_TRUE(ret == CRYPT_SUCCESS); ASSERT_TRUE(memcmp(in->x, result, in->len) == 0); ASSERT_TRUE(memcmp(in->x, result + in->len, in->len) == 0); EXIT: CRYPT_EAL_CipherFreeCtx(ctxEnc); CRYPT_EAL_CipherFreeCtx(ctxDec); } /* END_CASE */ /** * @test SDV_CRYPTO_SM4_MULTI_UPDATE_TC002 * @title Multi update with different data length in encryption and decryption * @precon Registering memory-related functions. * @brief * 1.Create the context ctx. Expected result 1 is obtained. * 2.Call the Init interface. Expected result 2 is obtained. * 3.Call the Update interface with plaintext for 5 times. The length of the first, third, and fifth plaintext is 15 bytes. * The length of the second and fourth plaintexts is 16 bytes. Expected result 3 is obtained. * 4.Call the Final interface. Expected result 4 is obtained. * 5.Use the SM4 decryption handle to call the Update interface with the ciphertext. Expected result 5 is obtained. * 6.Call the Final interface. Expected result 6 is obtained. * @expect * 1.The creation is successful and the ctx is not empty. * 2.The init is successful, return CRYPT_SUCCESS. * 3.The update is successful, return CRYPT_SUCCESS. * 4.The final is successful, return CRYPT_SUCCESS. The cipher result is consistent with the test vector. * 5.The update is successful, return CRYPT_SUCCESS. * 6.The final is successful, return CRYPT_SUCCESS. The plain result is consistent with the test vector. */ /* BEGIN_CASE */ void SDV_CRYPTO_SM4_MULTI_UPDATE_TC002(int algId, Hex *key, Hex *iv, Hex *in, int padding, int isSetPadding) { TestMemInit(); int32_t ret; uint8_t outTmp[MAXSIZE] = {0}; uint8_t result[MAXSIZE] = {0}; uint32_t totalLen = 0; uint32_t leftLen = MAXSIZE; uint32_t len = MAXSIZE; CRYPT_EAL_CipherCtx *ctxEnc = NULL; CRYPT_EAL_CipherCtx *ctxDec = NULL; ASSERT_TRUE(in->len >= BLOCKSIZE); ctxEnc = CRYPT_EAL_CipherNewCtx(algId); ASSERT_TRUE(ctxEnc != NULL); ret = SetPadding(isSetPadding, ctxEnc, padding); ASSERT_TRUE(ret == CRYPT_SUCCESS); ret = CRYPT_EAL_CipherInit(ctxEnc, key->x, key->len, iv->x, iv->len, true); ASSERT_TRUE(ret == CRYPT_SUCCESS); ret = SetPadding(isSetPadding, ctxEnc, padding); ASSERT_TRUE(ret == CRYPT_SUCCESS); for (uint32_t i = 0; i < 2; i++) { // 15bytes + 16bytes, run two times. ret = CRYPT_EAL_CipherUpdate(ctxEnc, in->x, BLOCKSIZE - 1, outTmp + totalLen, &len); ASSERT_TRUE(ret == CRYPT_SUCCESS); totalLen += len; leftLen -= len; len = leftLen; ret = CRYPT_EAL_CipherUpdate(ctxEnc, in->x, BLOCKSIZE, outTmp + totalLen, &len); ASSERT_TRUE(ret == CRYPT_SUCCESS); totalLen += len; leftLen -= len; len = leftLen; } ret = CRYPT_EAL_CipherUpdate(ctxEnc, in->x, BLOCKSIZE - 1, outTmp + totalLen, &len); ASSERT_TRUE(ret == CRYPT_SUCCESS); totalLen += len; leftLen -= len; len = leftLen; if (algId != CRYPT_CIPHER_SM4_GCM) { ret = CRYPT_EAL_CipherFinal(ctxEnc, outTmp + totalLen, &leftLen); } ASSERT_TRUE(ret == CRYPT_SUCCESS); totalLen += leftLen; len = MAXSIZE; leftLen = MAXSIZE; ctxDec = CRYPT_EAL_CipherNewCtx(algId); ASSERT_TRUE(ctxDec != NULL); ret = CRYPT_EAL_CipherInit(ctxDec, key->x, key->len, iv->x, iv->len, false); ASSERT_TRUE(ret == CRYPT_SUCCESS); ret = SetPadding(isSetPadding, ctxEnc, padding); ASSERT_TRUE(ret == CRYPT_SUCCESS); ret = CRYPT_EAL_CipherUpdate(ctxDec, outTmp, totalLen, result, &len); leftLen -= len; ASSERT_TRUE(ret == CRYPT_SUCCESS); if (algId != CRYPT_CIPHER_SM4_GCM) { ret = CRYPT_EAL_CipherFinal(ctxDec, result + len, &leftLen); } ASSERT_TRUE(ret == CRYPT_SUCCESS); ASSERT_TRUE(memcmp(in->x, result, BLOCKSIZE - 1) == 0); ASSERT_TRUE(memcmp(in->x, result + BLOCKSIZE - 1, BLOCKSIZE) == 0); EXIT: CRYPT_EAL_CipherFreeCtx(ctxEnc); CRYPT_EAL_CipherFreeCtx(ctxDec); } /* END_CASE */ /** * @test SDV_CRYPTO_SM4_CTRL_API_TC004 * @title Obtaining the IV through the Ctrl interface Test in encryption * @precon Registering memory-related functions. * @brief * 1.Call the init interface to set the IV and call interface to obtain the IV. Expected result 1 is obtained. * @expect * 1.The two IVs are consistent. */ /* BEGIN_CASE */ void SDV_CRYPTO_SM4_CTRL_API_TC004(int id, Hex *key, Hex *iv) { TestMemInit(); int32_t ret; uint8_t niv[BLOCKSIZE] = {0}; CRYPT_EAL_CipherCtx *ctx = CRYPT_EAL_CipherNewCtx(id); ASSERT_TRUE(ctx != NULL); ret = CRYPT_EAL_CipherInit(ctx, key->x, key->len, iv->x, iv->len, true); ASSERT_TRUE(ret == CRYPT_SUCCESS); ret = CRYPT_EAL_CipherCtrl(ctx, CRYPT_CTRL_GET_IV, niv, iv->len); ASSERT_TRUE(memcmp(niv, iv->x, iv->len) == 0); EXIT: CRYPT_EAL_CipherFreeCtx(ctx); } /* END_CASE */ /** * @test SDV_CRYPTO_SM4_CTRL_API_TC005 * @title Obtaining the IV through the Ctrl interface Test in decryption * @precon Registering memory-related functions. * @brief * 1.Call the init interface to set the IV and call interface to obtain the IV. Expected result 1 is obtained. * @expect * 1.The two IVs are consistent. */ /* BEGIN_CASE */ void SDV_CRYPTO_SM4_CTRL_API_TC005(int id, Hex *key, Hex *iv) { TestMemInit(); int32_t ret; uint8_t niv[BLOCKSIZE] = {0}; CRYPT_EAL_CipherCtx *ctx = CRYPT_EAL_CipherNewCtx(id); ASSERT_TRUE(ctx != NULL); ret = CRYPT_EAL_CipherInit(ctx, key->x, key->len, iv->x, iv->len, false); ASSERT_TRUE(ret == CRYPT_SUCCESS); ret = CRYPT_EAL_CipherCtrl(ctx, CRYPT_CTRL_GET_IV, niv, iv->len); ASSERT_TRUE(memcmp(niv, iv->x, iv->len) == 0); EXIT: CRYPT_EAL_CipherFreeCtx(ctx); } /* END_CASE */ /** * @test SDV_CRYPTO_SM4_REINIT_API_TC002 * @title Impact of input parameter validity on the iv reset interface Test * @precon Registering memory-related functions. * @brief * 1.Create the context ctx. Expected result 1 is obtained. * 2.Call the Init interface, iv is NULL, iv len is 0. Expected result 2 is obtained. * 3.Call the Reinit interface, iv is NULL, iv len is 0. Expected result 3 is obtained. * 4.Call the Reinit interface, iv is not NULL, iv len is 0. Expected result 4 is obtained. * 5.Call the Reinit interface, iv is not NULL, iv len is 15. Expected result 5 is obtained. * 6.Call the Reinit interface, iv is not NULL, iv len is 17. Expected result 6 is obtained. * @expect * 1.The creation is successful and the ctx is not empty. * 2.The init is successful and return CRYPT_SUCCESS. * 3.The interface returns a failure. * 4.The interface returns a failure. * 5.The interface returns a failure. * 6.The interface returns a failure. */ /* BEGIN_CASE */ void SDV_CRYPTO_SM4_REINIT_API_TC002(int algId, Hex *key, Hex *iv) { TestMemInit(); int32_t ret; CRYPT_EAL_CipherCtx *ctx = CRYPT_EAL_CipherNewCtx(algId); ASSERT_TRUE(ctx != NULL); ret = CRYPT_EAL_CipherInit(ctx, key->x, key->len, NULL, 0, true); ASSERT_TRUE(ret != CRYPT_SUCCESS); ret = CRYPT_EAL_CipherReinit(ctx, NULL, 0); ASSERT_TRUE(ret != CRYPT_SUCCESS); ret = CRYPT_EAL_CipherReinit(ctx, iv->x, 0); ASSERT_TRUE(ret != CRYPT_SUCCESS); ret = CRYPT_EAL_CipherReinit(ctx, iv->x, BLOCKSIZE - 1); ASSERT_TRUE(ret != CRYPT_SUCCESS); ret = CRYPT_EAL_CipherReinit(ctx, iv->x, BLOCKSIZE + 1); ASSERT_TRUE(ret != CRYPT_SUCCESS); EXIT: CRYPT_EAL_CipherFreeCtx(ctx); } /* END_CASE */ /** * @test SDV_CRYPTO_SM4_ENCRYPT_FUNC_TC005 * @title Data encryption and decryption after reinit Test * @precon Registering memory-related functions. * @brief * 1.Create the context ctx. Expected result 1 is obtained. * 2.Call the Init interface. Expected result 2 is obtained. * 3.Call the Update interface. Expected result 3 is obtained. * 4.Call the Reinit interface. Expected result 4 is obtained. * 5.Call the Update interface. Expected result 5 is obtained. * 6.Call the Reinit interface. Expected result 6 is obtained. * 7.Call the Update interface. Expected result 7 is obtained. * @expect * 1.The creation is successful and the ctx is not empty. * 2.The init is successful and return CRYPT_SUCCESS. * 3.Success. The ciphertext is as expected. * 4.The reinit is successful and return CRYPT_SUCCESS. * 5.Success. The ciphertext is as expected. * 6.The reinit is successful and return CRYPT_SUCCESS. * 7.Success. The ciphertext is as expected. */ /* BEGIN_CASE */ void SDV_CRYPTO_SM4_ENCRYPT_FUNC_TC005(int isProvider, Hex *key, Hex *in1, Hex *out1, Hex *iv1, Hex *in2, Hex *out2, Hex *iv2, int enc) { TestMemInit(); int32_t ret; uint8_t outTmp[MAXSIZE] = {0}; uint32_t len = MAXSIZE; CRYPT_EAL_CipherCtx *ctx = TestCipherNewCtx(NULL, CRYPT_CIPHER_SM4_XTS, "provider=default", isProvider); ASSERT_TRUE(ctx != NULL); ret = CRYPT_EAL_CipherInit(ctx, key->x, key->len, iv1->x, iv1->len, enc); ASSERT_TRUE(ret == CRYPT_SUCCESS); ret = CRYPT_EAL_CipherUpdate(ctx, in1->x, in1->len, outTmp, &len); ASSERT_TRUE(ret == CRYPT_SUCCESS); ASSERT_TRUE(memcmp(outTmp, out1->x, out1->len) == 0); (void)memset_s(outTmp, MAXSIZE, 0, MAXSIZE); len = MAXSIZE; ret = CRYPT_EAL_CipherReinit(ctx, iv2->x, iv2->len); ASSERT_TRUE(ret == CRYPT_SUCCESS); ret = CRYPT_EAL_CipherUpdate(ctx, in2->x, in2->len, outTmp, &len); ASSERT_TRUE(ret == CRYPT_SUCCESS); ASSERT_TRUE(memcmp(outTmp, out2->x, out2->len) == 0); (void)memset_s(outTmp, MAXSIZE, 0, MAXSIZE); len = MAXSIZE; ret = CRYPT_EAL_CipherReinit(ctx, iv1->x, iv1->len); ASSERT_TRUE(ret == CRYPT_SUCCESS); ret = CRYPT_EAL_CipherUpdate(ctx, in1->x, in1->len, outTmp, &len); ASSERT_TRUE(ret == CRYPT_SUCCESS); ASSERT_TRUE(memcmp(outTmp, out1->x, out1->len) == 0); EXIT: CRYPT_EAL_CipherFreeCtx(ctx); } /* END_CASE */ typedef struct { int algId; uint8_t *key; uint32_t keyLen; uint8_t *iv; uint32_t ivLen; uint8_t *in; uint32_t inLen; uint8_t *out; uint32_t outLen; int enc; } TestVector; void SM4_MultiThreadTest(void *arg) { TestVector *pTestVector = (TestVector *)arg; int32_t ret; uint8_t outTmp[MAXSIZE] = {0}; uint32_t len = MAXSIZE; CRYPT_EAL_CipherCtx *ctx = CRYPT_EAL_CipherNewCtx(pTestVector->algId); ASSERT_TRUE(ctx != NULL); ret = CRYPT_EAL_CipherInit(ctx, pTestVector->key, pTestVector->keyLen, pTestVector->iv, pTestVector->ivLen, pTestVector->enc); ASSERT_TRUE(ret == CRYPT_SUCCESS); ret = CRYPT_EAL_CipherUpdate(ctx, pTestVector->in, pTestVector->inLen, outTmp, &len); ASSERT_TRUE(ret == CRYPT_SUCCESS); ASSERT_TRUE(memcmp(outTmp, pTestVector->out, pTestVector->outLen) == 0); EXIT: CRYPT_EAL_CipherDeinit(ctx); CRYPT_EAL_CipherFreeCtx(ctx); } /** * @test SDV_CRYPTO_SM4_MULTI_THREAD_TC001 * @title Multi-thread Test * @precon Registering memory-related functions. * @brief * 1.Start three threads. Expected result 1 is obtained. * 2.Call the eal interface in the thread for encryption. Expected result 2 is obtained. * 3.Call the eal interface in the thread for decryption. Expected result 2 is obtained. * @expect * 1.Success. * 2.The encryption is successful. The ciphertext and tag are the same as the vector. * 3.The decryption is successful. The plaintext and tag are consistent with the vector. */ /* BEGIN_CASE */ void SDV_CRYPTO_SM4_MULTI_THREAD_TC001(int algId, Hex *key, Hex *in, Hex *out, Hex *iv, int enc) { #define THREAD_NUM 3 TestMemInit(); int32_t ret; pthread_t thrd[THREAD_NUM]; TestVector testVt = { .algId = algId, .key = key->x, .keyLen = key->len, .iv = iv->x, .ivLen = iv->len, .in = in->x, .inLen = in->len, .out = out->x, .outLen = out->len, .enc = enc }; for (uint32_t i = 0; i < THREAD_NUM; i++) { ret = pthread_create(&thrd[i], NULL, (void *)SM4_MultiThreadTest, &testVt); ASSERT_TRUE(ret == 0); } for (uint32_t i = 0; i < THREAD_NUM; i++) { pthread_join(thrd[i], NULL); } EXIT: return; } /* END_CASE */ /** * @test SDV_CRYPTO_SM4_ENCRYPT_FUNC_TC006 * @title Impact of the msg with no padding on the Update interface Test * @precon Registering memory-related functions. * @brief * 1.Create the context ctx. Expected result 1 is obtained. * 2.Call the Init interface. Expected result 2 is obtained. * 3.Call the Update interface with plain len is 17. Expected result 3 is obtained. * 4.Call the Final interface. Expected result 4 is obtained. * @expect * 1.The creation is successful and the ctx is not empty. * 2.The init is successful and return CRYPT_SUCCESS. * 3.The Update is successful. * 4.The Final is failed. */ /* BEGIN_CASE */ void SDV_CRYPTO_SM4_ENCRYPT_FUNC_TC006(int id, Hex *key, Hex *iv, Hex *msg, int enc) { TestMemInit(); int32_t ret; uint8_t out[MAX_OUTPUT] = {0}; uint32_t outlen = MAX_OUTPUT; CRYPT_EAL_CipherCtx *ctx = CRYPT_EAL_CipherNewCtx(id); ASSERT_TRUE(ctx != NULL); ASSERT_TRUE(msg->len == BLOCKSIZE + 1); ret = CRYPT_EAL_CipherInit(ctx, key->x, key->len, iv->x, iv->len, enc); ASSERT_TRUE(ret == CRYPT_SUCCESS); ret = CRYPT_EAL_CipherUpdate(ctx, msg->x, msg->len, out, &outlen); ASSERT_TRUE(ret == CRYPT_SUCCESS); outlen = MAX_OUTPUT; ret = CRYPT_EAL_CipherFinal(ctx, out, &outlen); ASSERT_TRUE(ret != CRYPT_SUCCESS); EXIT: CRYPT_EAL_CipherFreeCtx(ctx); } /* END_CASE */ /** * @test SDV_CRYPTO_SM4_ENCRYPT_FUNC_TC007 * @title Update 0 message length Test * @precon Registering memory-related functions. * @brief * 1.Create the context ctx. Expected result 1 is obtained. * 2.Call the Init interface. Expected result 2 is obtained. * 3.Call the Update interface, data is NULL, dataLen is 0. Expected result 3 is obtained. * 4.Call the Final interface. Expected result 4 is obtained. * @expect * 1.The creation is successful and the ctx is not empty. * 2.The init is successful, return CRYPT_SUCCESS. * 3.The Update is successful. * 4.The outlen is consistent with expect. */ /* BEGIN_CASE */ void SDV_CRYPTO_SM4_ENCRYPT_FUNC_TC007(int id, Hex *key, Hex *iv, int enc) { TestMemInit(); int32_t ret; uint8_t out[MAX_OUTPUT] = {0}; uint32_t outlen = MAX_OUTPUT; CRYPT_EAL_CipherCtx *ctx = CRYPT_EAL_CipherNewCtx(id); ASSERT_TRUE(ctx != NULL); ret = CRYPT_EAL_CipherInit(ctx, key->x, key->len, iv->x, iv->len, enc); ASSERT_TRUE(ret == CRYPT_SUCCESS); ret = CRYPT_EAL_CipherUpdate(ctx, NULL, 0, out, &outlen); ASSERT_TRUE(ret == CRYPT_SUCCESS); if (id != CRYPT_CIPHER_SM4_GCM) { outlen = MAX_OUTPUT; ret = CRYPT_EAL_CipherFinal(ctx, out, &outlen); ASSERT_TRUE(ret == CRYPT_SUCCESS); } ASSERT_TRUE(outlen == 0); EXIT: CRYPT_EAL_CipherFreeCtx(ctx); } /* END_CASE */ /** * @test SDV_CRYPTO_SM4_ENCRYPT_FUNC_TC008 * @title Impact of updating IV on encryption and decryption Test * @precon Registering memory-related functions. * @brief * 1.Create the context ctx. Expected result 1 is obtained. * 2.Call the Init interface. Expected result 2 is obtained. * 3.Call the Update interface. Expected result 3 is obtained. * 4.Call the Final interface. Expected result 4 is obtained. * 5.Call the Reinit interface to update iv. Expected result 5 is obtained. * 6.Call the Update interface. Expected result 6 is obtained. * 7.Call the Final interface. Expected result 7 is obtained. * @expect * 1.The creation is successful and the ctx is not empty. * 2.The init is successful, return CRYPT_SUCCESS. * 3.The update is successful, return CRYPT_SUCCESS. * 4.The final is successful, return CRYPT_SUCCESS. The result is consistent with the test vector. * 5.The reinit is successful, return CRYPT_SUCCESS. * 6.The update is successful, return CRYPT_SUCCESS. * 7.The final is successful, return CRYPT_SUCCESS. The result is consistent with the test vector. */ /* BEGIN_CASE */ void SDV_CRYPTO_SM4_ENCRYPT_FUNC_TC008(int isProvider, int algId, Hex *key, Hex *iv, Hex *in, Hex *out, int enc) { TestMemInit(); int32_t ret; uint8_t outTmp[MAX_OUTPUT] = {0}; uint32_t len = MAX_OUTPUT; uint32_t finLen; CRYPT_EAL_CipherCtx *ctx = TestCipherNewCtx(NULL, algId, "provider=default", isProvider); ASSERT_TRUE(ctx != NULL); ret = CRYPT_EAL_CipherInit(ctx, key->x, key->len, iv->x, iv->len, enc); ASSERT_TRUE(ret == CRYPT_SUCCESS); ret = CRYPT_EAL_CipherUpdate(ctx, in->x, in->len, outTmp, &len); ASSERT_TRUE(ret == CRYPT_SUCCESS); finLen = MAX_OUTPUT - len; ret = Sm4CipherFinal(algId, ctx, outTmp + len, &finLen); ASSERT_TRUE(ret == CRYPT_SUCCESS); ASSERT_COMPARE("Cipher compare", out->x, out->len, outTmp, len + finLen); (void)memset_s(outTmp, MAX_OUTPUT, 0, MAX_OUTPUT); len = MAX_OUTPUT; ret = CRYPT_EAL_CipherReinit(ctx, iv->x, iv->len); ASSERT_TRUE(ret == CRYPT_SUCCESS); ret = CRYPT_EAL_CipherUpdate(ctx, in->x, in->len, outTmp, &len); ASSERT_TRUE(ret == CRYPT_SUCCESS); finLen = MAX_OUTPUT - len; ret = Sm4CipherFinal(algId, ctx, outTmp + len, &finLen); ASSERT_TRUE(ret == CRYPT_SUCCESS); ASSERT_COMPARE("Cipher compare", out->x, out->len, outTmp, len + finLen); EXIT: CRYPT_EAL_CipherFreeCtx(ctx); } /* END_CASE */ /** * @test SDV_CRYPTO_SM4_ENCRYPT_FUNC_TC009 * @title Impact of updating IV and Key on encryption and decryption Test * @precon Registering memory-related functions. * @brief * 1.Create the context ctx. Expected result 1 is obtained. * 2.Call the Init interface. Expected result 2 is obtained. * 3.Call the Update interface. Expected result 3 is obtained. * 4.Call the Final interface. Expected result 4 is obtained. * 5.Call the Init interface to update iv and key. Expected result 5 is obtained. * 6.Call the Update interface. Expected result 6 is obtained. * 7.Call the Final interface. Expected result 7 is obtained. * @expect * 1.The creation is successful and the ctx is not empty. * 2.The init is successful, return CRYPT_SUCCESS. * 3.The update is successful, return CRYPT_SUCCESS. * 4.The final is successful, return CRYPT_SUCCESS. The result is consistent with the test vector. * 5.The Init is successful, return CRYPT_SUCCESS. * 6.The update is successful, return CRYPT_SUCCESS. * 7.The final is successful, return CRYPT_SUCCESS. The result is consistent with the test vector. */ /* BEGIN_CASE */ void SDV_CRYPTO_SM4_ENCRYPT_FUNC_TC009(int isProvider, int algId, Hex *key, Hex *iv, Hex *in, Hex *out, int enc) { TestMemInit(); int32_t ret; uint8_t outTmp[MAX_OUTPUT] = {0}; uint32_t len = MAX_OUTPUT; uint32_t finLen; CRYPT_EAL_CipherCtx *ctx = TestCipherNewCtx(NULL, algId, "provider=default", isProvider); ASSERT_TRUE(ctx != NULL); ret = CRYPT_EAL_CipherInit(ctx, key->x, key->len, iv->x, iv->len, enc); ASSERT_TRUE(ret == CRYPT_SUCCESS); ret = CRYPT_EAL_CipherUpdate(ctx, in->x, in->len, outTmp, &len); ASSERT_TRUE(ret == CRYPT_SUCCESS); finLen = MAX_OUTPUT - len; ret = Sm4CipherFinal(algId, ctx, outTmp + len, &finLen); ASSERT_TRUE(ret == CRYPT_SUCCESS); ASSERT_TRUE(memcmp(outTmp, out->x, out->len) == 0); (void)memset_s(outTmp, MAX_OUTPUT, 0, MAX_OUTPUT); len = MAX_OUTPUT; ret = CRYPT_EAL_CipherInit(ctx, key->x, key->len, iv->x, iv->len, enc); ASSERT_TRUE(ret == CRYPT_SUCCESS); ret = CRYPT_EAL_CipherUpdate(ctx, in->x, in->len, outTmp, &len); ASSERT_TRUE(ret == CRYPT_SUCCESS); finLen = MAX_OUTPUT - len; ret = Sm4CipherFinal(algId, ctx, outTmp + len, &finLen); ASSERT_TRUE(ret == CRYPT_SUCCESS); ASSERT_TRUE(memcmp(outTmp, out->x, out->len) == 0); EXIT: CRYPT_EAL_CipherFreeCtx(ctx); } /* END_CASE */ /** * @test SDV_CRYPTO_SM4_ENCRYPT_FUNC_TC010 * @title Impact of the padding algorithm on encryption and decryption Test * @precon Registering memory-related functions. * @brief * 1.Create the context ctx. Expected result 1 is obtained. * 2.Call the Init interface. Expected result 2 is obtained. * 3.Call the set padding interface with CRYPT_PADDING_PKCS7, CRYPT_PADDING_PKCS5, CRYPT_PADDING_X923 * CRYPT_PADDING_ISO7816, CRYPT_PADDING_ZEROS, CRYPT_PADDING_NONE. Expected result 3 is obtained. * 4.Call the Update interface. Expected result 4 is obtained. * 5.Call the Final interface. Expected result 5 is obtained. * 6.Use the SM4 decryption handle to call the Update interface with the ciphertext. Expected result 6 is obtained. * 7.Call the Final interface. Expected result 7 is obtained. * @expect * 1.The creation is successful and the ctx is not empty. * 2.The init is successful, return CRYPT_SUCCESS. * 3.The setting is successful, return CRYPT_SUCCESS. * 4.The update is successful, return CRYPT_SUCCESS. * 5.The final is successful, return CRYPT_SUCCESS. * 6.The update is successful, return CRYPT_SUCCESS. * 7.The final is successful, and the plaintext is consistent with the origin data. */ /* BEGIN_CASE */ void SDV_CRYPTO_SM4_ENCRYPT_FUNC_TC010(int algId, Hex *key, Hex *iv, int inLen, int padding) { TestMemInit(); int32_t ret; uint8_t input[MAX_DATASZIE] = {0}; uint8_t outTmp[MAX_DATASZIE] = {0}; uint8_t result[MAX_DATASZIE] = {0}; uint32_t totalLen = 0; uint32_t leftLen = MAX_DATASZIE; uint32_t len = MAX_DATASZIE; (void)memset_s(outTmp, MAX_DATASZIE, 0xAA, MAX_DATASZIE); (void)memset_s(input, MAX_DATASZIE, 0xAA, MAX_DATASZIE); CRYPT_EAL_CipherCtx *ctxEnc = NULL; CRYPT_EAL_CipherCtx *ctxDec = NULL; ASSERT_TRUE(inLen <= MAX_DATASZIE); ctxEnc = CRYPT_EAL_CipherNewCtx(algId); ASSERT_TRUE(ctxEnc != NULL); ret = CRYPT_EAL_CipherInit(ctxEnc, key->x, key->len, iv->x, iv->len, true); ASSERT_TRUE(ret == CRYPT_SUCCESS); ret = CRYPT_EAL_CipherSetPadding(ctxEnc, padding); ASSERT_TRUE(ret == CRYPT_SUCCESS); ret = CRYPT_EAL_CipherUpdate(ctxEnc, input, inLen, outTmp, &len); ASSERT_TRUE(ret == CRYPT_SUCCESS); totalLen += len; leftLen -= len; ret = CRYPT_EAL_CipherFinal(ctxEnc, outTmp + totalLen, &leftLen); ASSERT_TRUE(ret == CRYPT_SUCCESS); totalLen += leftLen; len = MAX_DATASZIE; leftLen = MAX_DATASZIE; ctxDec = CRYPT_EAL_CipherNewCtx(algId); ASSERT_TRUE(ctxDec != NULL); ret = CRYPT_EAL_CipherInit(ctxDec, key->x, key->len, iv->x, iv->len, false); ASSERT_TRUE(ret == CRYPT_SUCCESS); ret = CRYPT_EAL_CipherSetPadding(ctxDec, padding); ASSERT_TRUE(ret == CRYPT_SUCCESS); ret = CRYPT_EAL_CipherUpdate(ctxDec, outTmp, totalLen, result, &len); ASSERT_TRUE(ret == CRYPT_SUCCESS); leftLen -= len; ret = CRYPT_EAL_CipherFinal(ctxDec, result + len, &leftLen); ASSERT_TRUE(ret == CRYPT_SUCCESS); ASSERT_TRUE(memcmp(input, result, inLen) == 0); EXIT: CRYPT_EAL_CipherFreeCtx(ctxEnc); CRYPT_EAL_CipherFreeCtx(ctxDec); } /* END_CASE */ /** * @test SDV_CRYPTO_SM4_ENCRYPT_FUNC_TC011 * @title The input and output start addresses are the same Test * @precon Registering memory-related functions. * @brief * 1.Create the context ctx. Expected result 1 is obtained. * 2.Call the Init interface. Expected result 2 is obtained. * 3.Call the set padding interface. Expected result 3 is obtained. * 4.Call the Update interface with the input and output buff are same. Expected result 4 is obtained. * 5.Call the Final interface. Expected result 5 is obtained. * 6.Use the SM4 decryption handle to call the Update interface with the ciphertext. Expected result 6 is obtained. * 7.Call the Final interface. Expected result 7 is obtained. * @expect * 1.The creation is successful and the ctx is not empty. * 2.The init is successful, return CRYPT_SUCCESS. * 3.The setting is successful, return CRYPT_SUCCESS. * 4.The update is successful, return CRYPT_SUCCESS. * 5.The final is successful, return CRYPT_SUCCESS. * 6.The update is successful, return CRYPT_SUCCESS. * 7.The final is successful, and the plaintext is consistent with the origin data. */ /* BEGIN_CASE */ void SDV_CRYPTO_SM4_ENCRYPT_FUNC_TC011(int algId, Hex *key, Hex *iv, int inLen, int padding, int isSetPadding) { TestMemInit(); int32_t ret; uint8_t input[MAX_DATASZIE] = {0}; uint8_t outTmp[MAX_DATASZIE] = {0}; uint8_t result[MAX_DATASZIE] = {0}; uint32_t totalLen = 0; uint32_t leftLen = MAX_DATASZIE; uint32_t len = MAX_DATASZIE; (void)memset_s(outTmp, MAX_DATASZIE, 0xAA, MAX_DATASZIE); (void)memset_s(input, MAX_DATASZIE, 0xAA, MAX_DATASZIE); CRYPT_EAL_CipherCtx *ctxEnc = NULL; CRYPT_EAL_CipherCtx *ctxDec = NULL; ASSERT_TRUE(inLen <= MAX_DATASZIE); ctxEnc = CRYPT_EAL_CipherNewCtx(algId); ASSERT_TRUE(ctxEnc != NULL); ret = SetPadding(isSetPadding, ctxEnc, padding); ASSERT_TRUE(ret == CRYPT_SUCCESS); ret = CRYPT_EAL_CipherInit(ctxEnc, key->x, key->len, iv->x, iv->len, true); ASSERT_TRUE(ret == CRYPT_SUCCESS); ret = SetPadding(isSetPadding, ctxEnc, padding); ASSERT_TRUE(ret == CRYPT_SUCCESS); ret = CRYPT_EAL_CipherUpdate(ctxEnc, outTmp, inLen, outTmp, &len); ASSERT_TRUE(ret == CRYPT_SUCCESS); totalLen += len; leftLen -= len; if (algId != CRYPT_CIPHER_SM4_GCM) { ret = CRYPT_EAL_CipherFinal(ctxEnc, outTmp + totalLen, &leftLen); ASSERT_TRUE(ret == CRYPT_SUCCESS); totalLen += leftLen; } len = MAX_OUTPUT; leftLen = MAX_OUTPUT; ctxDec = CRYPT_EAL_CipherNewCtx(algId); ASSERT_TRUE(ctxDec != NULL); ret = CRYPT_EAL_CipherInit(ctxDec, key->x, key->len, iv->x, iv->len, false); ASSERT_TRUE(ret == CRYPT_SUCCESS); ret = SetPadding(isSetPadding, ctxDec, padding); ASSERT_TRUE(ret == CRYPT_SUCCESS); ret = CRYPT_EAL_CipherUpdate(ctxDec, outTmp, totalLen, result, &len); ASSERT_TRUE(ret == CRYPT_SUCCESS); leftLen -= len; ret = Sm4CipherFinal(algId, ctxDec, result + len, &leftLen); ASSERT_TRUE(ret == CRYPT_SUCCESS); ASSERT_TRUE(memcmp(input, result, inLen) == 0); EXIT: CRYPT_EAL_CipherFreeCtx(ctxEnc); CRYPT_EAL_CipherFreeCtx(ctxDec); } /* END_CASE */ /** * @test SDV_CRYPTO_SM4_ENCRYPT_FUNC_TC012 * @title Impact of the key and iv of all 0s/all Fs on encryption and decryption Test * @precon Registering memory-related functions. * @brief * 1.Create the context ctx. Expected result 1 is obtained. * 2.Call the Init interface, with key and iv of all 0s/all Fs. Expected result 2 is obtained. * 3.Call the Update interface. Expected result 3 is obtained. * 4.Call the Final interface. Expected result 4 is obtained. * @expect * 1.The creation is successful and the ctx is not empty. * 2.The init is successful, return CRYPT_SUCCESS. * 3.The update is successful, return CRYPT_SUCCESS. * 4.The final is successful, and the result is consistent with expect. */ /* BEGIN_CASE */ void SDV_CRYPTO_SM4_ENCRYPT_FUNC_TC012(int algId, Hex *key, Hex *iv, Hex *in, Hex *out, int enc) { TestMemInit(); int32_t ret; uint8_t outTmp[MAX_OUTPUT] = {0}; uint32_t len = MAX_OUTPUT; uint32_t totalLen = 0; CRYPT_EAL_CipherCtx *ctx = CRYPT_EAL_CipherNewCtx(algId); ASSERT_TRUE(ctx != NULL); ret = CRYPT_EAL_CipherInit(ctx, key->x, key->len, iv->x, iv->len, enc); ASSERT_TRUE(ret == CRYPT_SUCCESS); ret = CRYPT_EAL_CipherUpdate(ctx, in->x, in->len, outTmp, &len); ASSERT_TRUE(ret == CRYPT_SUCCESS); totalLen += len; len = MAX_OUTPUT - len; if (algId != CRYPT_CIPHER_SM4_GCM){ ret = CRYPT_EAL_CipherFinal(ctx, outTmp + totalLen, &len); totalLen += len; ASSERT_TRUE(totalLen == out->len); ASSERT_TRUE(ret == CRYPT_SUCCESS); } ASSERT_TRUE(memcmp(outTmp, out->x, out->len) == 0); EXIT: CRYPT_EAL_CipherFreeCtx(ctx); } /* END_CASE */ /** * @test SDV_CRYPTO_SM4_ENCRYPT_FUNC_TC013 * @title SM4-GCM encryption full vector test * @precon Registering memory-related functions. * @brief * 1.Call the Init interface. Expected result 1 is obtained. * 2.Call the Ctrl interface to set parameters. Expected result 2 is obtained. * 3.Call the update interface to update message. Expected result 3 is obtained. * 4.Call the Ctrl interface to get tag. Expected result 4 is obtained. * 5.Compare the ciphertext data. Expected result 5 is obtained. * 6.Compare the tag data. Expected result 6 is obtained. * @expect * 1.The init is successful, return CRYPT_SUCCESS. * 2.The setting is successful, return CRYPT_SUCCESS. * 3.The update is successful, return CRYPT_SUCCESS. * 4.The getting is successful, return CRYPT_SUCCESS. * 5.Ciphertext is consistent with the test vector. * 6.Tag is consistent with the test vector. */ /* BEGIN_CASE */ void SDV_CRYPTO_SM4_ENCRYPT_FUNC_TC013(Hex *key, Hex *iv, Hex *aad, Hex *pt, Hex *ct, Hex *tag, int enc) { TestMemInit(); CRYPT_EAL_CipherCtx *ctx = NULL; uint8_t *outTag = NULL; uint8_t *out = NULL; uint32_t tagLen = tag->len; uint32_t outLen; if (ct->len > 0) { out = (uint8_t *)BSL_SAL_Malloc(ct->len * sizeof(uint8_t)); outLen = ct->len * sizeof(uint8_t); ASSERT_TRUE(out != NULL); } else { out = (uint8_t *)BSL_SAL_Malloc(1 * sizeof(uint8_t)); outLen = 1 * sizeof(uint8_t); ASSERT_TRUE(out != NULL); } ctx = CRYPT_EAL_CipherNewCtx(CRYPT_CIPHER_SM4_GCM); ASSERT_TRUE(ctx != NULL); ASSERT_TRUE(CRYPT_EAL_CipherInit(ctx, key->x, key->len, iv->x, iv->len, enc) == CRYPT_SUCCESS); ASSERT_TRUE(CRYPT_EAL_CipherCtrl(ctx, CRYPT_CTRL_SET_TAGLEN, &tagLen, sizeof(tagLen)) == CRYPT_SUCCESS); ASSERT_TRUE(CRYPT_EAL_CipherCtrl(ctx, CRYPT_CTRL_SET_AAD, aad->x, aad->len) == CRYPT_SUCCESS); ASSERT_TRUE(CRYPT_EAL_CipherUpdate(ctx, pt->x, pt->len, (uint8_t *)out, &outLen) == CRYPT_SUCCESS); outTag = (uint8_t *)BSL_SAL_Malloc(sizeof(uint8_t) * tagLen); ASSERT_TRUE(outTag != NULL); ASSERT_TRUE(CRYPT_EAL_CipherCtrl(ctx, CRYPT_CTRL_GET_TAG, (uint8_t *)outTag, tagLen) == CRYPT_SUCCESS); if (ct->x != NULL) { ASSERT_TRUE(memcmp(out, ct->x, ct->len) == 0); } ASSERT_COMPARE("Compare Tag", outTag, tagLen, tag->x, tag->len); EXIT: CRYPT_EAL_CipherFreeCtx(ctx); free(out); free(outTag); } /* END_CASE */ /** * @test SDV_CRYPTO_SM4_ENCRYPT_FUNC_TC014 * @title Encryption in different padding modes Test * @precon Registering memory-related functions. * @brief * 1.Create the context ctx. Expected result 1 is obtained. * 2.Call the Init interface. Expected result 2 is obtained. * 3.Call SetPadding interface setting padding mode to CRYPT_PADDING_ISO7816, * CRYPT_PADDING_X923, CRYPT_PADDING_PKCS7. Expected result 3 is obtained. * 4.Call the Update interface. Expected result 4 is obtained. * 5.Call the Final interface. Expected result 5 is obtained. * 6.Call the init, update, and final interfaces to decrypt and verifiy the result. * @expect * 1.The creation is successful and the ctx is not empty. * 2.The init is successful, return CRYPT_SUCCESS. * 3.The setting is successful, return CRYPT_SUCCESS. * 4.The update is successful, return CRYPT_SUCCESS. * 5.The final is successful, return CRYPT_SUCCESS. * 6.The verification is successful, return CRYPT_SUCCESS. */ /* BEGIN_CASE */ void SDV_CRYPTO_SM4_ENCRYPT_FUNC_TC014(int isProvider, int algId, Hex *key, Hex *iv, Hex *in, Hex *out, int padding) { TestMemInit(); int32_t ret; uint8_t outTmp[MAX_OUTPUT] = {0}; uint32_t totalLen = 0; uint32_t leftLen = MAX_OUTPUT; uint32_t len = MAX_OUTPUT; CRYPT_EAL_CipherCtx *ctxEnc = TestCipherNewCtx(NULL, algId, "provider=default", isProvider); ASSERT_TRUE(ctxEnc != NULL); ret = CRYPT_EAL_CipherInit(ctxEnc, key->x, key->len, iv->x, iv->len, true); ASSERT_TRUE(ret == CRYPT_SUCCESS); ret = CRYPT_EAL_CipherSetPadding(ctxEnc, padding); ASSERT_TRUE(ret == CRYPT_SUCCESS); ret = CRYPT_EAL_CipherUpdate(ctxEnc, in->x, in->len, outTmp, &len); ASSERT_TRUE(ret == CRYPT_SUCCESS); totalLen += len; leftLen = leftLen - len; ret = CRYPT_EAL_CipherFinal(ctxEnc, outTmp + len, &leftLen); ASSERT_TRUE(ret == CRYPT_SUCCESS); totalLen += leftLen; ASSERT_TRUE(totalLen == out->len); ASSERT_TRUE(memcmp(out->x, outTmp, out->len) == 0); EXIT: CRYPT_EAL_CipherDeinit(ctxEnc); CRYPT_EAL_CipherFreeCtx(ctxEnc); } /* END_CASE */ /** * @test SDV_CRYPTO_SM4_ENCRYPT_FUNC_TC015 * @title Decryption in different padding modes Test * @precon Registering memory-related functions. * @brief * 1.Create the context ctx. Expected result 1 is obtained. * 2.Call the Init interface. Expected result 2 is obtained. * 3.Call SetPadding interface setting padding mode to CRYPT_PADDING_ISO7816, * CRYPT_PADDING_X923, CRYPT_PADDING_PKCS7. Expected result 3 is obtained. * 4.Call the Update interface. Expected result 4 is obtained. * 5.Call the Final interface. Expected result 5 is obtained. * 6.Call the init, update, and final interfaces to decrypt and verifiy the result. * @expect * 1.The creation is successful and the ctx is not empty. * 2.The init is successful, return CRYPT_SUCCESS. * 3.The setting is successful, return CRYPT_SUCCESS. * 4.The update is successful, return CRYPT_SUCCESS. * 5.The final is successful, return CRYPT_SUCCESS. * 6.The verification is successful, return CRYPT_SUCCESS. */ /* BEGIN_CASE */ void SDV_CRYPTO_SM4_ENCRYPT_FUNC_TC015(int isProvider, int algId, Hex *key, Hex *iv, Hex *in, Hex *out, int padding) { TestMemInit(); uint8_t result[MAX_OUTPUT] = {0}; uint32_t totalLen = 0; uint32_t leftLen = MAX_OUTPUT; uint32_t len = MAX_OUTPUT; CRYPT_EAL_CipherCtx *ctxDec = NULL; len = MAX_OUTPUT; leftLen = MAX_OUTPUT; ctxDec = TestCipherNewCtx(NULL, algId, "provider=default", isProvider); ASSERT_TRUE(ctxDec != NULL); ASSERT_EQ(CRYPT_EAL_CipherInit(ctxDec, key->x, key->len, iv->x, iv->len, false), CRYPT_SUCCESS); ASSERT_EQ(CRYPT_EAL_CipherSetPadding(ctxDec, padding), CRYPT_SUCCESS); ASSERT_EQ(CRYPT_EAL_CipherUpdate(ctxDec, in->x, in->len, result, &len), CRYPT_SUCCESS); totalLen += len; leftLen = leftLen - len; ASSERT_EQ(CRYPT_EAL_CipherFinal(ctxDec, result + len, &leftLen), CRYPT_SUCCESS); totalLen += leftLen; ASSERT_TRUE(totalLen == out->len); ASSERT_TRUE(memcmp(out->x, result, out->len) == 0); EXIT: CRYPT_EAL_CipherDeinit(ctxDec); CRYPT_EAL_CipherFreeCtx(ctxDec); } /* END_CASE */
2301_79861745/bench_create
testcode/sdv/testcase/crypto/sm4/test_suite_sdv_eal_sm4.c
C
unknown
65,643
/* * This file is part of the openHiTLS project. * * openHiTLS is licensed under the Mulan PSL v2. * You can use this software according to the terms and conditions of the Mulan PSL v2. * You may obtain a copy of Mulan PSL v2 at: * * http://license.coscl.org.cn/MulanPSL2 * * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, * EITHER EXPRESS 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 <stdio.h> #include <string.h> #include "securec.h" #include "bsl_err.h" #include "bsl_sal.h" #include "crypt_errno.h" #include "crypt_algid.h" #include "crypt_eal_pkey.h" #include "crypt_util_rand.h" #include "crypt_bn.h" #include "eal_pkey_local.h" #include "stub_replace.h" #include "test.h" /* END_HEADER */ uint32_t g_stubRandCounter = 0; uint8_t **g_stubRand = NULL; uint32_t *g_stubRandLen = NULL; void RandInjectionInit() { g_stubRandCounter = 0; g_stubRand = NULL; g_stubRandLen = NULL; } void RandInjectionSet(uint8_t **rand, uint32_t *len) { g_stubRand = rand; g_stubRandLen = len; } int32_t RandInjection(uint8_t *rand, uint32_t randLen) { (void)memcpy_s(rand, randLen, g_stubRand[g_stubRandCounter], randLen); g_stubRandCounter++; return CRYPT_SUCCESS; } int32_t RandInjectionEx(void *libCtx, uint8_t *rand, uint32_t randLen) { (void)libCtx; return RandInjection(rand, randLen); } /* BEGIN_CASE */ void SDV_CRYPTO_XMSS_API_NEW_TC001(void) { TestMemInit(); CRYPT_EAL_PkeyCtx *pkey = NULL; pkey = CRYPT_EAL_PkeyNewCtx(CRYPT_PKEY_XMSS); ASSERT_TRUE(pkey != NULL); EXIT: CRYPT_EAL_PkeyFreeCtx(pkey); return; } /* END_CASE */ /* BEGIN_CASE */ void SDV_CRYPTO_XMSS_GENKEY_TC001(int isProvider) { TestMemInit(); TestRandInit(); CRYPT_EAL_PkeyCtx *pkey = NULL; #ifdef HITLS_CRYPTO_PROVIDER if (isProvider == 1) { pkey = CRYPT_EAL_ProviderPkeyNewCtx(NULL, CRYPT_PKEY_XMSS, CRYPT_EAL_PKEY_SIGN_OPERATE, "provider=default"); } else #endif { (void)isProvider; pkey = CRYPT_EAL_PkeyNewCtx(CRYPT_PKEY_XMSS); } ASSERT_TRUE(pkey != NULL); ASSERT_TRUE(CRYPT_EAL_PkeyCtrl(pkey, CRYPT_CTRL_SET_PARA_BY_ID, NULL, 0) == CRYPT_INVALID_ARG); ASSERT_TRUE(CRYPT_EAL_PkeyGen(pkey) == CRYPT_XMSS_ERR_INVALID_ALGID); CRYPT_PKEY_ParaId algId = CRYPT_XMSS_SHA2_10_256; ASSERT_TRUE(CRYPT_EAL_PkeyCtrl(pkey, CRYPT_CTRL_SET_PARA_BY_ID, (void *)&algId, sizeof(algId)) == CRYPT_SUCCESS); ASSERT_TRUE(CRYPT_EAL_PkeyGen(pkey) == CRYPT_SUCCESS); EXIT: CRYPT_EAL_PkeyFreeCtx(pkey); return; } /* END_CASE */ /* BEGIN_CASE */ void SDV_CRYPTO_XMSS_GETSET_KEY_TC001(void) { TestMemInit(); TestRandInit(); CRYPT_EAL_PkeyCtx *pkey = NULL; pkey = CRYPT_EAL_PkeyNewCtx(CRYPT_PKEY_XMSS); ASSERT_TRUE(pkey != NULL); int32_t algId = CRYPT_XMSS_SHA2_10_256; ASSERT_EQ(CRYPT_EAL_PkeySetParaById(pkey, algId), CRYPT_SUCCESS); CRYPT_EAL_PkeyPub pub; uint8_t pubSeed[32] = {0}; uint8_t pubRoot[32] = {0}; (void)memset_s(&pub, sizeof(CRYPT_EAL_PkeyPub), 0, sizeof(CRYPT_EAL_PkeyPub)); pub.id = CRYPT_PKEY_XMSS; ASSERT_EQ(CRYPT_EAL_PkeyGetPub(pkey, &pub), CRYPT_NULL_INPUT); ASSERT_EQ(CRYPT_EAL_PkeySetPub(pkey, &pub), CRYPT_NULL_INPUT); pub.key.xmssPub.seed = pubSeed; pub.key.xmssPub.root = pubRoot; pub.key.xmssPub.len = 16; ASSERT_EQ(CRYPT_EAL_PkeyGetPub(pkey, &pub), CRYPT_XMSS_ERR_INVALID_KEYLEN); ASSERT_EQ(CRYPT_EAL_PkeySetPub(pkey, &pub), CRYPT_XMSS_ERR_INVALID_KEYLEN); CRYPT_EAL_PkeyPrv prv; uint8_t prvSeed[32] = {0}; uint8_t prvPrf[32] = {0}; uint64_t index = 0; (void)memset_s(&prv, sizeof(CRYPT_EAL_PkeyPrv), 0, sizeof(CRYPT_EAL_PkeyPrv)); prv.id = CRYPT_PKEY_XMSS; ASSERT_EQ(CRYPT_EAL_PkeyGetPrv(pkey, &prv), CRYPT_NULL_INPUT); ASSERT_EQ(CRYPT_EAL_PkeySetPrv(pkey, &prv), CRYPT_NULL_INPUT); prv.key.xmssPrv.index = index; prv.key.xmssPrv.seed = prvSeed; prv.key.xmssPrv.prf = prvPrf; prv.key.xmssPrv.pub.seed = pubSeed; prv.key.xmssPrv.pub.root = pubRoot; prv.key.xmssPrv.pub.len = 16; ASSERT_EQ(CRYPT_EAL_PkeyGetPrv(pkey, &prv), CRYPT_XMSS_ERR_INVALID_KEYLEN); ASSERT_EQ(CRYPT_EAL_PkeySetPrv(pkey, &prv), CRYPT_XMSS_ERR_INVALID_KEYLEN); EXIT: CRYPT_EAL_PkeyFreeCtx(pkey); return; } /* END_CASE */ /* BEGIN_CASE */ void SDV_CRYPTO_XMSS_GETSET_KEY_TC002(void) { TestMemInit(); TestRandInit(); CRYPT_EAL_PkeyCtx *pkey = NULL; pkey = CRYPT_EAL_PkeyNewCtx(CRYPT_PKEY_XMSS); ASSERT_TRUE(pkey != NULL); int32_t algId = CRYPT_XMSS_SHA2_10_256; ASSERT_EQ(CRYPT_EAL_PkeySetParaById(pkey, algId), CRYPT_SUCCESS); ASSERT_TRUE(CRYPT_EAL_PkeyGen(pkey) == CRYPT_SUCCESS); CRYPT_EAL_PkeyPub pub; uint8_t pubSeed[32] = {0}; uint8_t pubRoot[32] = {0}; (void)memset_s(&pub, sizeof(CRYPT_EAL_PkeyPub), 0, sizeof(CRYPT_EAL_PkeyPub)); pub.id = CRYPT_PKEY_XMSS; pub.key.xmssPub.seed = pubSeed; pub.key.xmssPub.root = pubRoot; pub.key.xmssPub.len = 32; ASSERT_EQ(CRYPT_EAL_PkeyGetPub(pkey, &pub), CRYPT_SUCCESS); ASSERT_EQ(CRYPT_EAL_PkeySetPub(pkey, &pub), CRYPT_SUCCESS); CRYPT_EAL_PkeyPrv prv; uint8_t prvSeed[32] = {0}; uint8_t prvPrf[32] = {0}; uint64_t index = 0; (void)memset_s(&prv, sizeof(CRYPT_EAL_PkeyPrv), 0, sizeof(CRYPT_EAL_PkeyPrv)); prv.id = CRYPT_PKEY_XMSS; prv.key.xmssPrv.index = index; prv.key.xmssPrv.seed = prvSeed; prv.key.xmssPrv.prf = prvPrf; prv.key.xmssPrv.pub.seed = pubSeed; prv.key.xmssPrv.pub.root = pubRoot; prv.key.xmssPrv.pub.len = 32; ASSERT_EQ(CRYPT_EAL_PkeyGetPrv(pkey, &prv), CRYPT_SUCCESS); ASSERT_EQ(CRYPT_EAL_PkeySetPrv(pkey, &prv), CRYPT_SUCCESS); EXIT: CRYPT_EAL_PkeyFreeCtx(pkey); return; } /* END_CASE */ /* BEGIN_CASE */ void SDV_CRYPTO_XMSS_GENKEY_KAT_TC001(int id, Hex *key, Hex *root) { TestMemInit(); CRYPT_EAL_PkeyCtx *pkey = NULL; pkey = CRYPT_EAL_PkeyNewCtx(CRYPT_PKEY_XMSS); ASSERT_TRUE(pkey != NULL); int32_t algId = id; ASSERT_EQ(CRYPT_EAL_PkeySetParaById(pkey, algId), CRYPT_SUCCESS); uint32_t keyLen = 0; ASSERT_EQ(CRYPT_EAL_PkeyCtrl(pkey, CRYPT_CTRL_GET_XMSS_KEY_LEN, (void *)&keyLen, sizeof(keyLen)), CRYPT_SUCCESS); RandInjectionInit(); uint8_t *stubRand[3] = {key->x, key->x + keyLen, key->x + keyLen * 2}; uint32_t stubRandLen[3] = {keyLen, keyLen, keyLen}; RandInjectionSet(stubRand, stubRandLen); CRYPT_RandRegist(RandInjection); CRYPT_RandRegistEx(RandInjectionEx); ASSERT_TRUE(CRYPT_EAL_PkeyGen(pkey) == CRYPT_SUCCESS); uint8_t pubSeed[64] = {0}; uint8_t pubRoot[64] = {0}; CRYPT_EAL_PkeyPub pubOut; (void)memset_s(&pubOut, sizeof(CRYPT_EAL_PkeyPub), 0, sizeof(CRYPT_EAL_PkeyPub)); pubOut.id = CRYPT_PKEY_XMSS; pubOut.key.xmssPub.seed = pubSeed; pubOut.key.xmssPub.root = pubRoot; pubOut.key.xmssPub.len = keyLen; ASSERT_EQ(CRYPT_EAL_PkeyGetPub(pkey, &pubOut), CRYPT_SUCCESS); ASSERT_EQ(memcmp(pubOut.key.xmssPub.seed, root->x, keyLen), 0); ASSERT_EQ(memcmp(pubOut.key.xmssPub.root, root->x + keyLen, keyLen), 0); EXIT: CRYPT_EAL_PkeyFreeCtx(pkey); return; } /* END_CASE */ /* BEGIN_CASE */ void SDV_CRYPTO_XMSS_SIGN_KAT_TC001(int id, int index, Hex *key, Hex *msg, Hex *sig, int result) { (void)key; (void)msg; (void)sig; TestMemInit(); CRYPT_EAL_PkeyCtx *pkey = NULL; pkey = CRYPT_EAL_PkeyNewCtx(CRYPT_PKEY_XMSS); ASSERT_TRUE(pkey != NULL); int32_t algId = id; ASSERT_EQ(CRYPT_EAL_PkeySetParaById(pkey, algId), CRYPT_SUCCESS); uint32_t keyLen = 0; ASSERT_EQ(CRYPT_EAL_PkeyCtrl(pkey, CRYPT_CTRL_GET_XMSS_KEY_LEN, (void *)&keyLen, sizeof(keyLen)), CRYPT_SUCCESS); CRYPT_EAL_PkeyPrv prv; (void)memset_s(&prv, sizeof(CRYPT_EAL_PkeyPrv), 0, sizeof(CRYPT_EAL_PkeyPrv)); prv.id = CRYPT_PKEY_XMSS; prv.key.xmssPrv.index = index; prv.key.xmssPrv.seed = key->x; prv.key.xmssPrv.prf = key->x + keyLen; prv.key.xmssPrv.pub.seed = key->x + keyLen * 2; prv.key.xmssPrv.pub.root = key->x + keyLen * 3; prv.key.xmssPrv.pub.len = keyLen; ASSERT_EQ(CRYPT_EAL_PkeySetPrv(pkey, &prv), CRYPT_SUCCESS); uint8_t sigOut[50000] = {0}; uint32_t sigOutLen = sizeof(sigOut); ASSERT_EQ(CRYPT_EAL_PkeySign(pkey, 0, msg->x, msg->len, sigOut, &sigOutLen), result); if (result == CRYPT_SUCCESS) { ASSERT_TRUE(sigOutLen == sig->len); ASSERT_TRUE(memcmp(sigOut, sig->x, sigOutLen) == 0); } EXIT: CRYPT_EAL_PkeyFreeCtx(pkey); return; } /* END_CASE */ /* BEGIN_CASE */ void SDV_CRYPTO_XMSS_VERIFY_KAT_TC001(int id, Hex *key, Hex *msg, Hex *sig, int result) { TestMemInit(); CRYPT_EAL_PkeyCtx *pkey = NULL; pkey = CRYPT_EAL_PkeyNewCtx(CRYPT_PKEY_XMSS); ASSERT_TRUE(pkey != NULL); int32_t algId = id; ASSERT_EQ(CRYPT_EAL_PkeySetParaById(pkey, algId), CRYPT_SUCCESS); uint32_t keyLen = 0; ASSERT_EQ(CRYPT_EAL_PkeyCtrl(pkey, CRYPT_CTRL_GET_XMSS_KEY_LEN, (void *)&keyLen, sizeof(keyLen)), CRYPT_SUCCESS); CRYPT_EAL_PkeyPub pub; (void)memset_s(&pub, sizeof(CRYPT_EAL_PkeyPub), 0, sizeof(CRYPT_EAL_PkeyPub)); pub.id = CRYPT_PKEY_XMSS; pub.key.xmssPub.seed = key->x; pub.key.xmssPub.root = key->x + keyLen; pub.key.xmssPub.len = keyLen; ASSERT_EQ(CRYPT_EAL_PkeySetPub(pkey, &pub), CRYPT_SUCCESS); ASSERT_EQ(CRYPT_EAL_PkeyVerify(pkey, 0, msg->x, msg->len, sig->x, sig->len), result); EXIT: CRYPT_EAL_PkeyFreeCtx(pkey); return; } /* END_CASE */
2301_79861745/bench_create
testcode/sdv/testcase/crypto/xmss/test_suite_sdv_eal_xmss.c
C
unknown
9,685
/* * This file is part of the openHiTLS project. * * openHiTLS is licensed under the Mulan PSL v2. * You can use this software according to the terms and conditions of the Mulan PSL v2. * You may obtain a copy of Mulan PSL v2 at: * * http://license.coscl.org.cn/MulanPSL2 * * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, * EITHER EXPRESS 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 "bsl_sal.h" #include "securec.h" #include "stub_replace.h" #include "hitls_pki_cert.h" #include "hitls_pki_csr.h" #include "hitls_pki_errno.h" #include "bsl_types.h" #include "bsl_log.h" #include "hitls_cert_local.h" #include "bsl_init.h" #include "bsl_obj_internal.h" #include "sal_time.h" #include "sal_file.h" #include "crypt_encode_decode_key.h" #include "crypt_eal_codecs.h" #include "hitls_x509_local.h" #include "stub_replace.h" /* END_HEADER */ /* BEGIN_CASE */ void SDV_X509_CERT_PARSE_FUNC_TC001(int format, char *path) { TestMemInit(); BSL_GLOBAL_Init(); HITLS_X509_Cert *cert = NULL; int32_t ret = HITLS_X509_CertParseFile(format, path, &cert); ASSERT_EQ(ret, HITLS_PKI_SUCCESS); EXIT: HITLS_X509_CertFree(cert); BSL_GLOBAL_DeInit(); } /* END_CASE */ /* BEGIN_CASE */ void SDV_X509_CERT_PARSE_VERSION_FUNC_TC001(char *path, int version) { HITLS_X509_Cert *cert = NULL; ASSERT_EQ(HITLS_X509_CertParseFile(BSL_FORMAT_ASN1, path, &cert), HITLS_PKI_SUCCESS); ASSERT_EQ(cert->tbs.version, version); EXIT: HITLS_X509_CertFree(cert); } /* END_CASE */ /* BEGIN_CASE */ void SDV_X509_CERT_PARSE_SERIALNUM_FUNC_TC001(char *path, Hex *serialNum) { HITLS_X509_Cert *cert = NULL; ASSERT_EQ(HITLS_X509_CertParseFile(BSL_FORMAT_ASN1, path, &cert), HITLS_PKI_SUCCESS); ASSERT_EQ(cert->tbs.serialNum.tag, 2); ASSERT_COMPARE("serialNum", cert->tbs.serialNum.buff, cert->tbs.serialNum.len, serialNum->x, serialNum->len); EXIT: HITLS_X509_CertFree(cert); } /* END_CASE */ /* BEGIN_CASE */ void SDV_X509_CERT_PARSE_TBS_SIGNALG_FUNC_TC001(char *path, int signAlg, int rsaPssHash, int rsaPssMgf1, int rsaPssSaltLen) { HITLS_X509_Cert *cert = NULL; ASSERT_EQ(HITLS_X509_CertParseFile(BSL_FORMAT_ASN1, path, &cert), HITLS_PKI_SUCCESS); ASSERT_EQ(cert->tbs.signAlgId.algId, signAlg); ASSERT_EQ(cert->tbs.signAlgId.rsaPssParam.mdId, rsaPssHash); ASSERT_EQ(cert->tbs.signAlgId.rsaPssParam.mgfId, rsaPssMgf1); ASSERT_EQ(cert->tbs.signAlgId.rsaPssParam.saltLen, rsaPssSaltLen); EXIT: HITLS_X509_CertFree(cert); } /* END_CASE */ /* BEGIN_CASE */ void SDV_X509_CERT_PARSE_ISSUERNAME_FUNC_TC001(char *path, int count, Hex *type1, int tag1, Hex *value1, Hex *type2, int tag2, Hex *value2, Hex *type3, int tag3, Hex *value3, Hex *type4, int tag4, Hex *value4, Hex *type5, int tag5, Hex *value5, Hex *type6, int tag6, Hex *value6) { HITLS_X509_Cert *cert = NULL; ASSERT_EQ(HITLS_X509_CertParseFile(BSL_FORMAT_ASN1, path, &cert), HITLS_PKI_SUCCESS); BSL_ASN1_Buffer expAsan1Arr[] = { {6, type1->len, type1->x}, {(uint8_t)tag1, value1->len, value1->x}, {6, type2->len, type2->x}, {(uint8_t)tag2, value2->len, value2->x}, {6, type3->len, type3->x}, {(uint8_t)tag3, value3->len, value3->x}, {6, type4->len, type4->x}, {(uint8_t)tag4, value4->len, value4->x}, {6, type5->len, type5->x}, {(uint8_t)tag5, value5->len, value5->x}, {6, type6->len, type6->x}, {(uint8_t)tag6, value6->len, value6->x}, }; ASSERT_EQ(BSL_LIST_COUNT(cert->tbs.issuerName), count); HITLS_X509_NameNode **nameNode = NULL; nameNode = BSL_LIST_First(cert->tbs.issuerName); for (int i = 0; i < count; i += 2) { ASSERT_NE((*nameNode), NULL); ASSERT_EQ((*nameNode)->layer, 1); ASSERT_EQ((*nameNode)->nameType.tag, 0); ASSERT_EQ((*nameNode)->nameType.buff, NULL); ASSERT_EQ((*nameNode)->nameType.len, 0); ASSERT_EQ((*nameNode)->nameValue.tag, 0); ASSERT_EQ((*nameNode)->nameValue.buff, NULL); ASSERT_EQ((*nameNode)->nameValue.len, 0); nameNode = BSL_LIST_Next(cert->tbs.issuerName); ASSERT_NE((*nameNode), NULL); ASSERT_EQ((*nameNode)->layer, 2); ASSERT_EQ((*nameNode)->nameType.tag, expAsan1Arr[i].tag); ASSERT_COMPARE("nameType", (*nameNode)->nameType.buff, (*nameNode)->nameType.len, expAsan1Arr[i].buff, expAsan1Arr[i].len); ASSERT_EQ((*nameNode)->nameValue.tag, expAsan1Arr[i + 1].tag); ASSERT_COMPARE("nameVlaue", (*nameNode)->nameValue.buff, (*nameNode)->nameValue.len, expAsan1Arr[i + 1].buff, expAsan1Arr[i + 1].len); nameNode = BSL_LIST_Next(cert->tbs.issuerName); } EXIT: HITLS_X509_CertFree(cert); } /* END_CASE */ /* BEGIN_CASE */ void SDV_X509_CERT_PARSE_ISSUERNAME_FUNC_TC002(char *path, int count, Hex *type1, int tag1, Hex *value1) { HITLS_X509_Cert *cert = NULL; ASSERT_EQ(HITLS_X509_CertParseFile(BSL_FORMAT_ASN1, path, &cert), HITLS_PKI_SUCCESS); BSL_ASN1_Buffer expAsan1Arr[] = { {6, type1->len, type1->x}, {(uint8_t)tag1, value1->len, value1->x} }; ASSERT_EQ(BSL_LIST_COUNT(cert->tbs.issuerName), count); HITLS_X509_NameNode **nameNode = NULL; nameNode = BSL_LIST_First(cert->tbs.issuerName); for (int i = 0; i < count; i += 2) { ASSERT_NE((*nameNode), NULL); ASSERT_EQ((*nameNode)->layer, 1); ASSERT_EQ((*nameNode)->nameType.tag, 0); ASSERT_EQ((*nameNode)->nameType.buff, NULL); ASSERT_EQ((*nameNode)->nameType.len, 0); ASSERT_EQ((*nameNode)->nameValue.tag, 0); ASSERT_EQ((*nameNode)->nameValue.buff, NULL); ASSERT_EQ((*nameNode)->nameValue.len, 0); nameNode = BSL_LIST_Next(cert->tbs.issuerName); ASSERT_NE((*nameNode), NULL); ASSERT_EQ((*nameNode)->layer, 2); ASSERT_EQ((*nameNode)->nameType.tag, expAsan1Arr[i].tag); ASSERT_COMPARE("nameType", (*nameNode)->nameType.buff, (*nameNode)->nameType.len, expAsan1Arr[i].buff, expAsan1Arr[i].len); ASSERT_EQ((*nameNode)->nameValue.tag, expAsan1Arr[i + 1].tag); ASSERT_COMPARE("nameVlaue", (*nameNode)->nameValue.buff, (*nameNode)->nameValue.len, expAsan1Arr[i + 1].buff, expAsan1Arr[i + 1].len); nameNode = BSL_LIST_Next(cert->tbs.issuerName); } EXIT: HITLS_X509_CertFree(cert); } /* END_CASE */ /* BEGIN_CASE */ void SDV_X509_CERT_PARSE_ISSUERNAME_FUNC_TC003(char *path, int count, Hex *type1, int tag1, Hex *value1, Hex *type2, int tag2, Hex *value2, Hex *type3, int tag3, Hex *value3, Hex *type4, int tag4, Hex *value4, Hex *type5, int tag5, Hex *value5) { HITLS_X509_Cert *cert = NULL; ASSERT_EQ(HITLS_X509_CertParseFile(BSL_FORMAT_ASN1, path, &cert), HITLS_PKI_SUCCESS); BSL_ASN1_Buffer expAsan1Arr[] = { {6, type1->len, type1->x}, {(uint8_t)tag1, value1->len, value1->x}, {6, type2->len, type2->x}, {(uint8_t)tag2, value2->len, value2->x}, {6, type3->len, type3->x}, {(uint8_t)tag3, value3->len, value3->x}, {6, type4->len, type4->x}, {(uint8_t)tag4, value4->len, value4->x}, {6, type5->len, type5->x}, {(uint8_t)tag5, value5->len, value5->x} }; ASSERT_EQ(BSL_LIST_COUNT(cert->tbs.issuerName), count); HITLS_X509_NameNode **nameNode = NULL; nameNode = BSL_LIST_First(cert->tbs.issuerName); for (int i = 0; i < count; i += 2) { ASSERT_NE((*nameNode), NULL); ASSERT_EQ((*nameNode)->layer, 1); ASSERT_EQ((*nameNode)->nameType.tag, 0); ASSERT_EQ((*nameNode)->nameType.buff, NULL); ASSERT_EQ((*nameNode)->nameType.len, 0); ASSERT_EQ((*nameNode)->nameValue.tag, 0); ASSERT_EQ((*nameNode)->nameValue.buff, NULL); ASSERT_EQ((*nameNode)->nameValue.len, 0); nameNode = BSL_LIST_Next(cert->tbs.issuerName); ASSERT_NE((*nameNode), NULL); ASSERT_EQ((*nameNode)->layer, 2); ASSERT_EQ((*nameNode)->nameType.tag, expAsan1Arr[i].tag); ASSERT_COMPARE("nameType", (*nameNode)->nameType.buff, (*nameNode)->nameType.len, expAsan1Arr[i].buff, expAsan1Arr[i].len); ASSERT_EQ((*nameNode)->nameValue.tag, expAsan1Arr[i + 1].tag); ASSERT_COMPARE("nameVlaue", (*nameNode)->nameValue.buff, (*nameNode)->nameValue.len, expAsan1Arr[i + 1].buff, expAsan1Arr[i + 1].len); nameNode = BSL_LIST_Next(cert->tbs.issuerName); } EXIT: HITLS_X509_CertFree(cert); } /* END_CASE */ /* BEGIN_CASE */ void SDV_X509_CERT_PARSE_TIME_FUNC_TC001(char *path) { HITLS_X509_Cert *cert = NULL; ASSERT_EQ(HITLS_X509_CertParseFile(BSL_FORMAT_ASN1, path, &cert), HITLS_X509_ERR_CHECK_TAG); EXIT: HITLS_X509_CertFree(cert); BSL_GLOBAL_DeInit(); } /* END_CASE */ /* BEGIN_CASE */ void SDV_X509_CERT_PARSE_START_TIME_FUNC_TC001(char *path, int year, int month, int day, int hour, int minute, int second) { HITLS_X509_Cert *cert = NULL; ASSERT_EQ(HITLS_X509_CertParseFile(BSL_FORMAT_ASN1, path, &cert), HITLS_PKI_SUCCESS); ASSERT_EQ(cert->tbs.validTime.start.year, year); ASSERT_EQ(cert->tbs.validTime.start.month, month); ASSERT_EQ(cert->tbs.validTime.start.day, day); ASSERT_EQ(cert->tbs.validTime.start.hour, hour); ASSERT_EQ(cert->tbs.validTime.start.minute, minute); ASSERT_EQ(cert->tbs.validTime.start.second, second); EXIT: HITLS_X509_CertFree(cert); } /* END_CASE */ /* BEGIN_CASE */ void SDV_X509_CERTPEM_PARSE_START_TIME_FUNC_TC001(char *path, int year, int month, int day, int hour, int minute, int second) { HITLS_X509_Cert *cert = NULL; ASSERT_EQ(HITLS_X509_CertParseFile(BSL_FORMAT_PEM, path, &cert), HITLS_PKI_SUCCESS); ASSERT_EQ(cert->tbs.validTime.start.year, year); ASSERT_EQ(cert->tbs.validTime.start.month, month); ASSERT_EQ(cert->tbs.validTime.start.day, day); ASSERT_EQ(cert->tbs.validTime.start.hour, hour); ASSERT_EQ(cert->tbs.validTime.start.minute, minute); ASSERT_EQ(cert->tbs.validTime.start.second, second); EXIT: HITLS_X509_CertFree(cert); } /* END_CASE */ /* BEGIN_CASE */ void SDV_X509_CERTPEM_PARSE_END_TIME_FUNC_TC001(char *path, int year, int month, int day, int hour, int minute, int second) { HITLS_X509_Cert *cert = NULL; ASSERT_EQ(HITLS_X509_CertParseFile(BSL_FORMAT_PEM, path, &cert), HITLS_PKI_SUCCESS); ASSERT_EQ(cert->tbs.validTime.end.year, year); ASSERT_EQ(cert->tbs.validTime.end.month, month); ASSERT_EQ(cert->tbs.validTime.end.day, day); ASSERT_EQ(cert->tbs.validTime.end.hour, hour); ASSERT_EQ(cert->tbs.validTime.end.minute, minute); ASSERT_EQ(cert->tbs.validTime.end.second, second); EXIT: HITLS_X509_CertFree(cert); } /* END_CASE */ /* BEGIN_CASE */ void SDV_X509_CERT_PARSE_END_TIME_FUNC_TC001(char *path, int year, int month, int day, int hour, int minute, int second) { HITLS_X509_Cert *cert = NULL; ASSERT_EQ(HITLS_X509_CertParseFile(BSL_FORMAT_ASN1, path, &cert), HITLS_PKI_SUCCESS); ASSERT_EQ(cert->tbs.validTime.end.year, year); ASSERT_EQ(cert->tbs.validTime.end.month, month); ASSERT_EQ(cert->tbs.validTime.end.day, day); ASSERT_EQ(cert->tbs.validTime.end.hour, hour); ASSERT_EQ(cert->tbs.validTime.end.minute, minute); ASSERT_EQ(cert->tbs.validTime.end.second, second); EXIT: HITLS_X509_CertFree(cert); } /* END_CASE */ /* BEGIN_CASE */ void SDV_X509_CERT_PARSE_SUBJECTNAME_FUNC_TC001(char *path, int count, Hex *type1, int tag1, Hex *value1, Hex *type2, int tag2, Hex *value2, Hex *type3, int tag3, Hex *value3, Hex *type4, int tag4, Hex *value4, Hex *type5, int tag5, Hex *value5, Hex *type6, int tag6, Hex *value6) { HITLS_X509_Cert *cert = NULL; ASSERT_EQ(HITLS_X509_CertParseFile(BSL_FORMAT_ASN1, path, &cert), HITLS_PKI_SUCCESS); BSL_ASN1_Buffer expAsan1Arr[] = { {6, type1->len, type1->x}, {(uint8_t)tag1, value1->len, value1->x}, {6, type2->len, type2->x}, {(uint8_t)tag2, value2->len, value2->x}, {6, type3->len, type3->x}, {(uint8_t)tag3, value3->len, value3->x}, {6, type4->len, type4->x}, {(uint8_t)tag4, value4->len, value4->x}, {6, type5->len, type5->x}, {(uint8_t)tag5, value5->len, value5->x}, {6, type6->len, type6->x}, {(uint8_t)tag6, value6->len, value6->x}, }; ASSERT_EQ(BSL_LIST_COUNT(cert->tbs.subjectName), count); HITLS_X509_NameNode **nameNode = NULL; nameNode = BSL_LIST_First(cert->tbs.subjectName); for (int i = 0; i < count; i += 2) { ASSERT_NE((*nameNode), NULL); ASSERT_EQ((*nameNode)->layer, 1); ASSERT_EQ((*nameNode)->nameType.tag, 0); ASSERT_EQ((*nameNode)->nameType.buff, NULL); ASSERT_EQ((*nameNode)->nameType.len, 0); ASSERT_EQ((*nameNode)->nameValue.tag, 0); ASSERT_EQ((*nameNode)->nameValue.buff, NULL); ASSERT_EQ((*nameNode)->nameValue.len, 0); nameNode = BSL_LIST_Next(cert->tbs.subjectName); ASSERT_NE((*nameNode), NULL); ASSERT_EQ((*nameNode)->layer, 2); ASSERT_EQ((*nameNode)->nameType.tag, expAsan1Arr[i].tag); ASSERT_COMPARE("nameType", (*nameNode)->nameType.buff, (*nameNode)->nameType.len, expAsan1Arr[i].buff, expAsan1Arr[i].len); ASSERT_EQ((*nameNode)->nameValue.tag, expAsan1Arr[i + 1].tag); ASSERT_COMPARE("nameVlaue", (*nameNode)->nameValue.buff, (*nameNode)->nameValue.len, expAsan1Arr[i + 1].buff, expAsan1Arr[i + 1].len); nameNode = BSL_LIST_Next(cert->tbs.subjectName); } EXIT: HITLS_X509_CertFree(cert); } /* END_CASE */ /* BEGIN_CASE */ void SDV_X509_CERT_PARSE_SUBJECTNAME_FUNC_TC002(char *path, int count, Hex *type1, int tag1, Hex *value1) { HITLS_X509_Cert *cert = NULL; ASSERT_EQ(HITLS_X509_CertParseFile(BSL_FORMAT_ASN1, path, &cert), HITLS_PKI_SUCCESS); BSL_ASN1_Buffer expAsan1Arr[] = { {6, type1->len, type1->x}, {(uint8_t)tag1, value1->len, value1->x} }; ASSERT_EQ(BSL_LIST_COUNT(cert->tbs.subjectName), count); HITLS_X509_NameNode **nameNode = NULL; nameNode = BSL_LIST_First(cert->tbs.subjectName); for (int i = 0; i < count; i += 2) { ASSERT_NE((*nameNode), NULL); ASSERT_EQ((*nameNode)->layer, 1); ASSERT_EQ((*nameNode)->nameType.tag, 0); ASSERT_EQ((*nameNode)->nameType.buff, NULL); ASSERT_EQ((*nameNode)->nameType.len, 0); ASSERT_EQ((*nameNode)->nameValue.tag, 0); ASSERT_EQ((*nameNode)->nameValue.buff, NULL); ASSERT_EQ((*nameNode)->nameValue.len, 0); nameNode = BSL_LIST_Next(cert->tbs.subjectName); ASSERT_NE((*nameNode), NULL); ASSERT_EQ((*nameNode)->layer, 2); ASSERT_EQ((*nameNode)->nameType.tag, expAsan1Arr[i].tag); ASSERT_COMPARE("nameType", (*nameNode)->nameType.buff, (*nameNode)->nameType.len, expAsan1Arr[i].buff, expAsan1Arr[i].len); ASSERT_EQ((*nameNode)->nameValue.tag, expAsan1Arr[i + 1].tag); ASSERT_COMPARE("nameVlaue", (*nameNode)->nameValue.buff, (*nameNode)->nameValue.len, expAsan1Arr[i + 1].buff, expAsan1Arr[i + 1].len); nameNode = BSL_LIST_Next(cert->tbs.subjectName); } EXIT: HITLS_X509_CertFree(cert); } /* END_CASE */ /* BEGIN_CASE */ void SDV_X509_CERT_PARSE_SUBJECTNAME_FUNC_TC003(char *path, int count, Hex *type1, int tag1, Hex *value1, Hex *type2, int tag2, Hex *value2, Hex *type3, int tag3, Hex *value3, Hex *type4, int tag4, Hex *value4, Hex *type5, int tag5, Hex *value5) { HITLS_X509_Cert *cert = NULL; ASSERT_EQ(HITLS_X509_CertParseFile(BSL_FORMAT_ASN1, path, &cert), HITLS_PKI_SUCCESS); BSL_ASN1_Buffer expAsan1Arr[] = { {6, type1->len, type1->x}, {(uint8_t)tag1, value1->len, value1->x}, {6, type2->len, type2->x}, {(uint8_t)tag2, value2->len, value2->x}, {6, type3->len, type3->x}, {(uint8_t)tag3, value3->len, value3->x}, {6, type4->len, type4->x}, {(uint8_t)tag4, value4->len, value4->x}, {6, type5->len, type5->x}, {(uint8_t)tag5, value5->len, value5->x} }; ASSERT_EQ(BSL_LIST_COUNT(cert->tbs.subjectName), count); HITLS_X509_NameNode **nameNode = NULL; nameNode = BSL_LIST_First(cert->tbs.subjectName); for (int i = 0; i < count; i += 2) { ASSERT_NE((*nameNode), NULL); ASSERT_EQ((*nameNode)->layer, 1); ASSERT_EQ((*nameNode)->nameType.tag, 0); ASSERT_EQ((*nameNode)->nameType.buff, NULL); ASSERT_EQ((*nameNode)->nameType.len, 0); ASSERT_EQ((*nameNode)->nameValue.tag, 0); ASSERT_EQ((*nameNode)->nameValue.buff, NULL); ASSERT_EQ((*nameNode)->nameValue.len, 0); nameNode = BSL_LIST_Next(cert->tbs.subjectName); ASSERT_NE((*nameNode), NULL); ASSERT_EQ((*nameNode)->layer, 2); ASSERT_EQ((*nameNode)->nameType.tag, expAsan1Arr[i].tag); ASSERT_COMPARE("nameType", (*nameNode)->nameType.buff, (*nameNode)->nameType.len, expAsan1Arr[i].buff, expAsan1Arr[i].len); ASSERT_EQ((*nameNode)->nameValue.tag, expAsan1Arr[i + 1].tag); ASSERT_COMPARE("nameVlaue", (*nameNode)->nameValue.buff, (*nameNode)->nameValue.len, expAsan1Arr[i + 1].buff, expAsan1Arr[i + 1].len); nameNode = BSL_LIST_Next(cert->tbs.subjectName); } EXIT: HITLS_X509_CertFree(cert); } /* END_CASE */ /* BEGIN_CASE */ void SDV_X509_CERT_CTRL_FUNC_TC001(char *path, int expRawDataLen, int expSignAlg, int expSignMdAlg, int expKuDigitailSign, int expKuCertSign, int expKuKeyAgreement, int expKeyUsage) { HITLS_X509_Cert *cert = NULL; uint32_t keyUsage = 0; ASSERT_EQ(HITLS_X509_CertParseFile(BSL_FORMAT_ASN1, path, &cert), HITLS_PKI_SUCCESS); int32_t rawDataLen; ASSERT_EQ(HITLS_X509_CertCtrl(cert, HITLS_X509_GET_ENCODELEN, &rawDataLen, sizeof(rawDataLen)), HITLS_PKI_SUCCESS); ASSERT_EQ(rawDataLen, expRawDataLen); uint8_t *rawData = NULL; ASSERT_EQ(HITLS_X509_CertCtrl(cert, HITLS_X509_GET_ENCODE, &rawData, 0), HITLS_PKI_SUCCESS); ASSERT_NE(rawData, NULL); void *ealKey = NULL; ASSERT_EQ(HITLS_X509_CertCtrl(cert, HITLS_X509_GET_PUBKEY, &ealKey, 0), HITLS_PKI_SUCCESS); ASSERT_NE(ealKey, NULL); CRYPT_EAL_PkeyFreeCtx(ealKey); int32_t alg = 0; int32_t mdAlg = 0; ASSERT_EQ(HITLS_X509_CertCtrl(cert, HITLS_X509_GET_SIGNALG, &alg, sizeof(alg)), HITLS_PKI_SUCCESS); ASSERT_EQ(alg, expSignAlg); ASSERT_EQ(HITLS_X509_CertCtrl(cert, HITLS_X509_GET_SIGN_MDALG, &mdAlg, sizeof(mdAlg) - 1), HITLS_X509_ERR_INVALID_PARAM); ASSERT_EQ(HITLS_X509_CertCtrl(cert, HITLS_X509_GET_SIGN_MDALG, &mdAlg, sizeof(mdAlg)), HITLS_PKI_SUCCESS); ASSERT_EQ(mdAlg, expSignMdAlg); int32_t ref = 0; ASSERT_EQ(HITLS_X509_CertCtrl(cert, HITLS_X509_REF_UP, &ref, sizeof(ref)), HITLS_PKI_SUCCESS); ASSERT_EQ(ref, 2); HITLS_X509_CertFree(cert); ASSERT_EQ(HITLS_X509_CertCtrl(cert, HITLS_X509_EXT_GET_KUSAGE, &keyUsage, sizeof(keyUsage)), HITLS_PKI_SUCCESS); ASSERT_EQ(keyUsage, expKeyUsage); if (expKeyUsage != HITLS_X509_EXT_KU_NONE) { ASSERT_EQ((keyUsage & HITLS_X509_EXT_KU_DIGITAL_SIGN) != 0, expKuDigitailSign); ASSERT_EQ((keyUsage & HITLS_X509_EXT_KU_KEY_CERT_SIGN) != 0, expKuCertSign); ASSERT_EQ((keyUsage & HITLS_X509_EXT_KU_KEY_AGREEMENT) != 0, expKuKeyAgreement); } EXIT: HITLS_X509_CertFree(cert); } /* END_CASE */ /* BEGIN_CASE */ void SDV_X509_CERT_CTRL_FUNC_TC002(char *path, char *expectedSerialNum, char *expectedSubjectName, char *expectedIssueName, char *expectedBeforeTime, char *expectedAfterTime) { HITLS_X509_Cert *cert = NULL; BSL_Buffer subjectName = { NULL, 0 }; BSL_Buffer issuerName = { NULL, 0 }; BSL_Buffer serialNum = { NULL, 0 }; BSL_Buffer beforeTime = { NULL, 0 }; BSL_Buffer afterTime = { NULL, 0 }; ASSERT_EQ(HITLS_X509_CertParseFile(BSL_FORMAT_ASN1, path, &cert), HITLS_PKI_SUCCESS); ASSERT_EQ(HITLS_X509_CertCtrl(cert, HITLS_X509_GET_SUBJECT_DN_STR, &subjectName, sizeof(BSL_Buffer)), 0); ASSERT_NE(subjectName.data, NULL); ASSERT_EQ(subjectName.dataLen, strlen(expectedSubjectName)); ASSERT_EQ(strcmp((char *)subjectName.data, expectedSubjectName), 0); ASSERT_EQ(HITLS_X509_CertCtrl(cert, HITLS_X509_GET_ISSUER_DN_STR, &issuerName, sizeof(BSL_Buffer)), 0); ASSERT_NE(issuerName.data, NULL); ASSERT_EQ(issuerName.dataLen, strlen(expectedIssueName)); ASSERT_EQ(strcmp((char *)issuerName.data, expectedIssueName), 0); ASSERT_EQ(HITLS_X509_CertCtrl(cert, HITLS_X509_GET_SERIALNUM_STR, &serialNum, sizeof(BSL_Buffer)), 0); ASSERT_NE(serialNum.data, NULL); ASSERT_EQ(serialNum.dataLen, strlen(expectedSerialNum)); ASSERT_EQ(strcmp((char *)serialNum.data, expectedSerialNum), 0); ASSERT_EQ(HITLS_X509_CertCtrl(cert, HITLS_X509_GET_BEFORE_TIME_STR, &beforeTime, sizeof(BSL_Buffer)), 0); ASSERT_NE(beforeTime.data, NULL); ASSERT_EQ(beforeTime.dataLen, strlen(expectedBeforeTime)); ASSERT_EQ(strcmp((char *)beforeTime.data, expectedBeforeTime), 0); ASSERT_EQ(HITLS_X509_CertCtrl(cert, HITLS_X509_GET_AFTER_TIME_STR, &afterTime, sizeof(BSL_Buffer)), 0); ASSERT_NE(afterTime.data, NULL); ASSERT_EQ (afterTime.dataLen, strlen(expectedAfterTime)); ASSERT_EQ(strcmp((char *)afterTime.data, expectedAfterTime), 0); EXIT: HITLS_X509_CertFree(cert); BSL_SAL_FREE(subjectName.data); BSL_SAL_FREE(issuerName.data); BSL_SAL_FREE(serialNum.data); BSL_SAL_FREE(beforeTime.data); BSL_SAL_FREE(afterTime.data); } /* END_CASE */ // subkey /* BEGIN_CASE */ void SDV_X509_CERT_PARSE_PUBKEY_FUNC_TC001(char *path, char *path2) { HITLS_X509_Cert *cert = NULL; HITLS_X509_Cert *cert2 = NULL; ASSERT_EQ(HITLS_X509_CertParseFile(BSL_FORMAT_ASN1, path, &cert), HITLS_PKI_SUCCESS); ASSERT_EQ(HITLS_X509_CertParseFile(BSL_FORMAT_ASN1, path2, &cert2), HITLS_PKI_SUCCESS); ASSERT_EQ(HITLS_X509_CheckSignature(cert2->tbs.ealPubKey, cert->tbs.tbsRawData, cert->tbs.tbsRawDataLen, &cert->signAlgId, &cert->signature), HITLS_PKI_SUCCESS); EXIT: HITLS_X509_CertFree(cert); HITLS_X509_CertFree(cert2); } /* END_CASE */ /* BEGIN_CASE */ void SDV_X509_CERT_DUP_FUNC_TC001(char *path, int expSignAlg, int expKuDigitailSign, int expKuCertSign, int expKuKeyAgreement, int expKeyUsage) { uint32_t keyUsage = 0; HITLS_X509_Cert *cert = NULL; HITLS_X509_Cert *dest = NULL; ASSERT_EQ(HITLS_X509_CertParseFile(BSL_FORMAT_ASN1, path, &cert), HITLS_PKI_SUCCESS); dest = HITLS_X509_CertDup(cert); ASSERT_NE(dest, NULL); int32_t alg = 0; ASSERT_EQ(HITLS_X509_CertCtrl(dest, HITLS_X509_GET_SIGNALG, &alg, sizeof(alg)), HITLS_PKI_SUCCESS); ASSERT_EQ(alg, expSignAlg); ASSERT_EQ(HITLS_X509_CertCtrl(cert, HITLS_X509_EXT_GET_KUSAGE, &keyUsage, sizeof(keyUsage)), HITLS_PKI_SUCCESS); ASSERT_EQ(keyUsage, expKeyUsage); if (expKeyUsage != HITLS_X509_EXT_KU_NONE) { ASSERT_EQ((keyUsage & HITLS_X509_EXT_KU_DIGITAL_SIGN) != 0, expKuDigitailSign); ASSERT_EQ((keyUsage & HITLS_X509_EXT_KU_KEY_CERT_SIGN) != 0, expKuCertSign); ASSERT_EQ((keyUsage & HITLS_X509_EXT_KU_KEY_AGREEMENT) != 0, expKuKeyAgreement); } EXIT: HITLS_X509_CertFree(cert); HITLS_X509_CertFree(dest); } /* END_CASE */ /* BEGIN_CASE */ void SDV_X509_CERT_PARSE_EXT_ERROR_TC001(char *path, int ret) { HITLS_X509_Cert *cert = NULL; ASSERT_EQ(HITLS_X509_CertParseFile(BSL_FORMAT_ASN1, path, &cert), ret); EXIT: HITLS_X509_CertFree(cert); } /* END_CASE */ /* BEGIN_CASE */ void SDV_X509_CERT_PARSE_EXTENSIONS_FUNC_TC001(char *path, int extNum, int isCA, int maxPathLen, int keyUsage, int cid1, Hex *oid1, int cr1, Hex *val1, int cid2, Hex *oid2, int cr2, Hex *val2, int cid3, Hex *oid3, int cr3, Hex *val3) { HITLS_X509_Cert *cert = NULL; HITLS_X509_ExtEntry **node = NULL; ASSERT_EQ(HITLS_X509_CertParseFile(BSL_FORMAT_ASN1, path, &cert), HITLS_PKI_SUCCESS); HITLS_X509_CertExt *certExt = (HITLS_X509_CertExt *)cert->tbs.ext.extData; ASSERT_EQ(certExt->isCa, isCA); ASSERT_EQ(certExt->maxPathLen, maxPathLen); ASSERT_EQ(certExt->keyUsage, keyUsage); ASSERT_EQ(BSL_LIST_COUNT(cert->tbs.ext.extList), extNum); HITLS_X509_ExtEntry arr[] = { {cid1, {BSL_ASN1_TAG_OBJECT_ID, oid1->len, oid1->x}, cr1, {BSL_ASN1_TAG_OCTETSTRING, val1->len, val1->x}}, {cid2, {BSL_ASN1_TAG_OBJECT_ID, oid2->len, oid2->x}, cr2, {BSL_ASN1_TAG_OCTETSTRING, val2->len, val2->x}}, {cid3, {BSL_ASN1_TAG_OBJECT_ID, oid3->len, oid3->x}, cr3, {BSL_ASN1_TAG_OCTETSTRING, val3->len, val3->x}}, }; node = BSL_LIST_First(cert->tbs.ext.extList); for (int i = 0; i < 3; i++) { // Check the first 3 extensions ASSERT_NE((*node), NULL); ASSERT_EQ((*node)->critical, arr[i].critical); ASSERT_EQ((*node)->extnId.tag, arr[i].extnId.tag); ASSERT_COMPARE("oid", (*node)->extnId.buff, (*node)->extnId.len, arr[i].extnId.buff, arr[i].extnId.len); ASSERT_EQ((*node)->extnValue.tag, arr[i].extnValue.tag); ASSERT_COMPARE( "value", (*node)->extnValue.buff, (*node)->extnValue.len, arr[i].extnValue.buff, arr[i].extnValue.len); node = BSL_LIST_Next(cert->tbs.ext.extList); } EXIT: HITLS_X509_CertFree(cert); } /* END_CASE */ // sign alg /* BEGIN_CASE */ void SDV_X509_CERT_PARSE_SIGNALG_FUNC_TC001(char *path, int signAlg, int rsaPssHash, int rsaPssMgf1, int rsaPssSaltLen) { HITLS_X509_Cert *cert = NULL; ASSERT_EQ(HITLS_X509_CertParseFile(BSL_FORMAT_ASN1, path, &cert), HITLS_PKI_SUCCESS); ASSERT_EQ(cert->signAlgId.algId, signAlg); ASSERT_EQ(cert->signAlgId.rsaPssParam.mdId, rsaPssHash); ASSERT_EQ(cert->signAlgId.rsaPssParam.mgfId, rsaPssMgf1); ASSERT_EQ(cert->signAlgId.rsaPssParam.saltLen, rsaPssSaltLen); EXIT: HITLS_X509_CertFree(cert); } /* END_CASE */ // signature /* BEGIN_CASE */ void SDV_X509_CERT_PARSE_SIGNATURE_FUNC_TC001(char *path, Hex *buff, int unusedBits) { HITLS_X509_Cert *cert = NULL; ASSERT_EQ(HITLS_X509_CertParseFile(BSL_FORMAT_ASN1, path, &cert), HITLS_PKI_SUCCESS); ASSERT_EQ(cert->signature.len, buff->len); ASSERT_COMPARE("signature", cert->signature.buff, cert->signature.len, buff->x, buff->len); ASSERT_EQ(cert->signature.unusedBits, unusedBits); EXIT: HITLS_X509_CertFree(cert); } /* END_CASE */ /* BEGIN_CASE */ void SDV_X509_MUL_CERT_PARSE_FUNC_TC001(int format, char *path, int certNum) { TestMemInit(); HITLS_X509_List *list = NULL; int32_t ret = HITLS_X509_CertParseBundleFile(format, path, &list); ASSERT_EQ(ret, HITLS_PKI_SUCCESS); ASSERT_EQ(BSL_LIST_COUNT(list), certNum); EXIT: BSL_LIST_FREE(list, (BSL_LIST_PFUNC_FREE)HITLS_X509_CertFree); } /* END_CASE */ /* BEGIN_CASE */ void SDV_X509_CERT_PARSE_BUNDLE_BUFF_FUNC_TC001(int format, char *path, int certNum) { TestMemInit(); HITLS_X509_List *list = NULL; BSL_Buffer encodeData = {0}; // Read certificate bundle file into buffer ASSERT_EQ(BSL_SAL_ReadFile(path, &encodeData.data, &encodeData.dataLen), BSL_SUCCESS); // Parse certificates from buffer ASSERT_EQ(HITLS_X509_CertParseBundleBuff(format, &encodeData, &list), HITLS_PKI_SUCCESS); ASSERT_EQ(BSL_LIST_COUNT(list), certNum); EXIT: BSL_LIST_FREE(list, (BSL_LIST_PFUNC_FREE)HITLS_X509_CertFree); BSL_SAL_Free(encodeData.data); } /* END_CASE */ /* BEGIN_CASE */ void SDV_X509_PROVIDER_CERT_PARSE_BUNDLE_BUFF_FUNC_TC001(char *format, char *path, int certNum) { TestMemInit(); HITLS_X509_List *list = NULL; BSL_Buffer encodeData = {0}; // Read certificate bundle file into buffer ASSERT_EQ(BSL_SAL_ReadFile(path, &encodeData.data, &encodeData.dataLen), BSL_SUCCESS); // Parse certificates from buffer using provider mechanism ASSERT_EQ(HITLS_X509_ProviderCertParseBundleBuff(NULL, NULL, format, &encodeData, &list), HITLS_PKI_SUCCESS); ASSERT_EQ(BSL_LIST_COUNT(list), certNum); EXIT: BSL_LIST_FREE(list, (BSL_LIST_PFUNC_FREE)HITLS_X509_CertFree); BSL_SAL_Free(encodeData.data); } /* END_CASE */ /* BEGIN_CASE */ void SDV_X509_CERT_SET_VERIOSN_FUNC_TC001(void) { TestMemInit(); HITLS_X509_Cert *cert = HITLS_X509_CertNew(); ASSERT_NE(cert, NULL); ASSERT_EQ(cert->tbs.version, HITLS_X509_VERSION_1); int32_t version = HITLS_X509_VERSION_2; ASSERT_EQ(HITLS_X509_CertCtrl(cert, HITLS_X509_SET_VERSION, &version, sizeof(int32_t)), HITLS_PKI_SUCCESS); ASSERT_EQ(cert->tbs.version, version); version = HITLS_X509_VERSION_3; ASSERT_EQ(HITLS_X509_CertCtrl(cert, HITLS_X509_SET_VERSION, &version, sizeof(int32_t)), HITLS_PKI_SUCCESS); ASSERT_EQ(cert->tbs.version, version); // valLen ASSERT_EQ(HITLS_X509_CertCtrl(cert, HITLS_X509_SET_VERSION, &version, 1), HITLS_X509_ERR_INVALID_PARAM); // val version = HITLS_X509_VERSION_3 + 1; ASSERT_EQ(HITLS_X509_CertCtrl(cert, HITLS_X509_SET_VERSION, &version, sizeof(int32_t)), HITLS_X509_ERR_INVALID_PARAM); EXIT: HITLS_X509_CertFree(cert); } /* END_CASE */ /* BEGIN_CASE */ void SDV_X509_CERT_SET_SERIAL_FUNC_TC001(Hex *serial) { TestMemInit(); uint8_t *val = serial->x; uint32_t valLen = serial->len; HITLS_X509_Cert *cert = HITLS_X509_CertNew(); ASSERT_NE(cert, NULL); ASSERT_EQ(cert->tbs.serialNum.len, 0); ASSERT_EQ(HITLS_X509_CertCtrl(cert, HITLS_X509_SET_SERIALNUM, val, 0), HITLS_X509_ERR_CERT_INVALID_SERIAL_NUM); ASSERT_EQ(HITLS_X509_CertCtrl(cert, HITLS_X509_SET_SERIALNUM, val, valLen), HITLS_PKI_SUCCESS); ASSERT_EQ(cert->tbs.serialNum.len, valLen); ASSERT_COMPARE("serial", cert->tbs.serialNum.buff, valLen, val, valLen); EXIT: HITLS_X509_CertFree(cert); } /* END_CASE */ /* BEGIN_CASE */ void SDV_X509_CERT_SET_TIME_FUNC_TC001(void) { TestMemInit(); BSL_TIME time = {2024, 8, 22, 1, 1, 0, 1, 0}; HITLS_X509_Cert *cert = HITLS_X509_CertNew(); ASSERT_NE(cert, NULL); ASSERT_EQ(cert->tbs.validTime.flag, 0); ASSERT_EQ(HITLS_X509_CertCtrl(cert, HITLS_X509_SET_BEFORE_TIME, &time, 0), HITLS_X509_ERR_INVALID_PARAM); ASSERT_EQ(HITLS_X509_CertCtrl(cert, HITLS_X509_SET_BEFORE_TIME, &time, sizeof(BSL_TIME)), HITLS_PKI_SUCCESS); ASSERT_TRUE((cert->tbs.validTime.flag & BSL_TIME_BEFORE_SET) != 0); ASSERT_EQ(BSL_SAL_DateTimeCompare(&cert->tbs.validTime.start, &time, NULL), BSL_TIME_CMP_EQUAL); ASSERT_EQ(HITLS_X509_CertCtrl(cert, HITLS_X509_SET_AFTER_TIME, &time, sizeof(BSL_TIME)), HITLS_PKI_SUCCESS); ASSERT_TRUE((cert->tbs.validTime.flag & BSL_TIME_AFTER_SET) != 0); ASSERT_EQ(BSL_SAL_DateTimeCompare(&cert->tbs.validTime.end, &time, NULL), BSL_TIME_CMP_EQUAL); EXIT: HITLS_X509_CertFree(cert); } /* END_CASE */ /* BEGIN_CASE */ void SDV_X509_ENCODE_CERT_EXT_TC001(char *path, Hex *expectExt) { TestMemInit(); BSL_GLOBAL_Init(); HITLS_X509_Cert *cert = NULL; BSL_ASN1_Buffer ext = {0}; ASSERT_EQ(HITLS_X509_CertParseFile(BSL_FORMAT_ASN1, path, &cert), HITLS_PKI_SUCCESS); uint8_t tag = 0xA3; ASSERT_EQ(HITLS_X509_EncodeExt(tag, cert->tbs.ext.extList, &ext), HITLS_PKI_SUCCESS); ASSERT_EQ(ext.len, expectExt->len); if (expectExt->len != 0) { ASSERT_EQ(ext.tag, tag); ASSERT_COMPARE("extensions", ext.buff, ext.len, expectExt->x, expectExt->len); } EXIT: HITLS_X509_CertFree(cert); BSL_SAL_Free(ext.buff); BSL_GLOBAL_DeInit(); } /* END_CASE */ /* BEGIN_CASE */ void SDV_X509_CERT_GEN_BUFF_API_TC001(void) { TestMemInit(); BSL_GLOBAL_Init(); BSL_Buffer buff = {0}; HITLS_X509_Cert *cert = HITLS_X509_CertNew(); ASSERT_NE(cert, NULL); ASSERT_EQ(HITLS_X509_CertGenBuff(BSL_FORMAT_UNKNOWN, cert, &buff), HITLS_X509_ERR_INVALID_PARAM); ASSERT_EQ(HITLS_X509_CertGenBuff(BSL_FORMAT_ASN1, NULL, &buff), HITLS_X509_ERR_INVALID_PARAM); ASSERT_EQ(HITLS_X509_CertGenBuff(BSL_FORMAT_ASN1, cert, NULL), HITLS_X509_ERR_INVALID_PARAM); cert->tbs.version = HITLS_X509_VERSION_1; cert->tbs.ext.extList->count = 1; ASSERT_EQ(HITLS_X509_CertGenBuff(BSL_FORMAT_ASN1, cert, &buff), HITLS_X509_ERR_CERT_NOT_SIGNED); EXIT: HITLS_X509_CertFree(cert); BSL_GLOBAL_DeInit(); } /* END_CASE */ /* BEGIN_CASE */ void SDV_X509_CERT_GEN_FILE_API_TC001(char *destPath) { TestMemInit(); HITLS_X509_Cert *cert = HITLS_X509_CertNew(); ASSERT_TRUE(cert != NULL); ASSERT_EQ(HITLS_X509_CertGenFile(BSL_FORMAT_UNKNOWN, cert, destPath), HITLS_X509_ERR_INVALID_PARAM); ASSERT_EQ(HITLS_X509_CertGenFile(BSL_FORMAT_ASN1, NULL, destPath), HITLS_X509_ERR_INVALID_PARAM); ASSERT_EQ(HITLS_X509_CertGenFile(BSL_FORMAT_ASN1, cert, NULL), HITLS_X509_ERR_INVALID_PARAM); EXIT: HITLS_X509_CertFree(cert); } /* END_CASE */ /* BEGIN_CASE */ void SDV_X509_CERT_SIGN_API_TC001(void) { HITLS_X509_Cert *cert = NULL; CRYPT_EAL_PkeyCtx *prvKey = NULL; HITLS_X509_SignAlgParam algParam = {0}; cert = HITLS_X509_CertNew(); ASSERT_NE(cert, NULL); prvKey = CRYPT_EAL_PkeyNewCtx(CRYPT_PKEY_RSA); ASSERT_NE(prvKey, NULL); // Test null parameters ASSERT_EQ(HITLS_X509_CertSign(BSL_CID_SHA256, NULL, &algParam, cert), HITLS_X509_ERR_INVALID_PARAM); ASSERT_EQ(HITLS_X509_CertSign(BSL_CID_SHA256, prvKey, &algParam, NULL), HITLS_X509_ERR_INVALID_PARAM); EXIT: HITLS_X509_CertFree(cert); CRYPT_EAL_PkeyFreeCtx(prvKey); } /* END_CASE */ /* BEGIN_CASE */ void SDV_X509_CERT_FORMAT_CONVERT_FUNC_TC001(char *inCert, int inForm, char *outCert, int outForm) { TestRandInit(); HITLS_X509_Cert *cert = NULL; BSL_Buffer encodeCert = {0}; BSL_Buffer expectCert = {0}; ASSERT_EQ(HITLS_X509_CertParseFile(inForm, inCert, &cert), 0); ASSERT_EQ(BSL_SAL_ReadFile(outCert, &expectCert.data, &expectCert.dataLen), 0); ASSERT_EQ(HITLS_X509_CertGenBuff(outForm, cert, &encodeCert), 0); ASSERT_COMPARE("Format convert", expectCert.data, expectCert.dataLen, encodeCert.data, encodeCert.dataLen); EXIT: HITLS_X509_CertFree(cert); BSL_SAL_Free(expectCert.data); BSL_SAL_Free(encodeCert.data); } /* END_CASE */ static int32_t SetCert(HITLS_X509_Cert *raw, HITLS_X509_Cert *new) { int32_t ret = 1; ASSERT_EQ(HITLS_X509_CertCtrl(new, HITLS_X509_SET_VERSION, &raw->tbs.version, sizeof(int32_t)), 0); ASSERT_EQ(HITLS_X509_CertCtrl(new, HITLS_X509_SET_SERIALNUM, raw->tbs.serialNum.buff, raw->tbs.serialNum.len), 0); ASSERT_EQ(HITLS_X509_CertCtrl(new, HITLS_X509_SET_BEFORE_TIME, &raw->tbs.validTime.start, sizeof(BSL_TIME)), 0); ASSERT_EQ(HITLS_X509_CertCtrl(new, HITLS_X509_SET_AFTER_TIME, &raw->tbs.validTime.end, sizeof(BSL_TIME)), 0); ASSERT_EQ(HITLS_X509_CertCtrl(new, HITLS_X509_SET_PUBKEY, raw->tbs.ealPubKey, sizeof(void *)), 0); BslList *rawSubject = NULL; ASSERT_EQ(HITLS_X509_CertCtrl(raw, HITLS_X509_GET_SUBJECT_DN, &rawSubject, sizeof(BslList *)), 0); ASSERT_EQ(HITLS_X509_CertCtrl(new, HITLS_X509_SET_SUBJECT_DN, rawSubject, sizeof(BslList)), 0); BslList *rawIssuer = NULL; ASSERT_EQ(HITLS_X509_CertCtrl(raw, HITLS_X509_GET_ISSUER_DN, &rawIssuer, sizeof(BslList *)), 0); ASSERT_EQ(HITLS_X509_CertCtrl(new, HITLS_X509_SET_ISSUER_DN, rawIssuer, sizeof(BslList)), 0); ret = 0; EXIT: return ret; } /* BEGIN_CASE */ void SDV_X509_CERT_SETANDGEN_TC001(char *derCertPath, char *privPath, int keyType, int pkeyId, int pad, int mdId, int mgfId, int saltLen) { HITLS_X509_Cert *raw = NULL; HITLS_X509_Cert *new = NULL; HITLS_X509_Cert *parse = NULL; CRYPT_EAL_PkeyCtx *privKey = NULL; BSL_Buffer encodeRaw = {0}; BSL_Buffer encodeNew = {0}; BslList *tmp = NULL; HITLS_X509_SignAlgParam algParam = {0}; HITLS_X509_SignAlgParam *algParamPtr = NULL; memset_s(&algParam, sizeof(HITLS_X509_SignAlgParam), 0, sizeof(HITLS_X509_SignAlgParam)); if (pad == 0) { algParamPtr = NULL; } else if (pad == CRYPT_EMSA_PSS) { algParam.algId = BSL_CID_RSASSAPSS; algParam.rsaPss.mdId = mdId; algParam.rsaPss.mgfId = mgfId; algParam.rsaPss.saltLen = saltLen; algParamPtr = &algParam; } TestMemInit(); TestRandInit(); ASSERT_EQ(CRYPT_EAL_PriKeyParseFile(BSL_FORMAT_ASN1, keyType, privPath, NULL, &privKey), 0); ASSERT_EQ(BSL_SAL_ReadFile(derCertPath, &encodeRaw.data, &encodeRaw.dataLen), 0); ASSERT_EQ(HITLS_X509_CertParseBuff(BSL_FORMAT_ASN1, &encodeRaw, &raw), 0); // generate new cert new = HITLS_X509_CertNew(); ASSERT_TRUE(new != NULL); ASSERT_EQ(SetCert(raw, new), 0); // Skip extension settings, directly use the extensions from raw certificate tmp = new->tbs.ext.extList; new->tbs.ext.extList = raw->tbs.ext.extList; ASSERT_EQ(HITLS_X509_CertSign(mdId, privKey, algParamPtr, new), 0); ASSERT_EQ(HITLS_X509_CertGenBuff(BSL_FORMAT_ASN1, new, &encodeNew), 0); if (pkeyId == CRYPT_PKEY_RSA && pad == CRYPT_EMSA_PKCSV15) { ASSERT_COMPARE("Gen cert", encodeNew.data, encodeNew.dataLen, encodeRaw.data, encodeRaw.dataLen); } EXIT: HITLS_X509_CertFree(raw); BSL_SAL_Free(encodeRaw.data); if (tmp != NULL) { new->tbs.ext.extList = tmp; } HITLS_X509_CertFree(new); HITLS_X509_CertFree(parse); CRYPT_EAL_PkeyFreeCtx(privKey); BSL_SAL_Free(encodeNew.data); } /* END_CASE */ /* BEGIN_CASE */ void SDV_X509_CERT_GEN_PROCESS_TC001(char *derCertPath, char *privPath, int keyType, int mdId) { HITLS_X509_Cert *cert = NULL; CRYPT_EAL_PkeyCtx *privKey = NULL; int32_t ver = 0; BSL_Buffer encodeCert = {0}; TestMemInit(); ASSERT_EQ(CRYPT_EAL_PriKeyParseFile(BSL_FORMAT_ASN1, keyType, privPath, NULL, &privKey), 0); ASSERT_EQ(HITLS_X509_CertParseFile(BSL_FORMAT_ASN1, derCertPath, &cert), HITLS_PKI_SUCCESS); /* Cannot repeat parse */ ASSERT_EQ(HITLS_X509_CertParseFile(BSL_FORMAT_ASN1, derCertPath, &cert), HITLS_X509_ERR_INVALID_PARAM); /* Sign with invalid parameters */ ASSERT_EQ(HITLS_X509_CertSign(mdId, privKey, NULL, NULL), HITLS_X509_ERR_INVALID_PARAM); /* Cannot sign after parsing */ ASSERT_EQ(HITLS_X509_CertSign(mdId, privKey, NULL, cert), HITLS_X509_ERR_SIGN_AFTER_PARSE); /* Cannot set after parsing */ ASSERT_EQ(HITLS_X509_CertCtrl(cert, HITLS_X509_SET_VERSION, &ver, sizeof(int32_t)), HITLS_X509_ERR_SET_AFTER_PARSE); /* Generate cert after parsing is allowed. */ ASSERT_EQ(HITLS_X509_CertGenBuff(BSL_FORMAT_ASN1, cert, &encodeCert), 0); BSL_SAL_Free(encodeCert.data); encodeCert.data = NULL; encodeCert.dataLen = 0; /* Repeat generate is allowed. */ ASSERT_EQ(HITLS_X509_CertGenBuff(BSL_FORMAT_ASN1, cert, &encodeCert), 0); EXIT: CRYPT_EAL_PkeyFreeCtx(privKey); HITLS_X509_CertFree(cert); BSL_SAL_Free(encodeCert.data); } /* END_CASE */ /* BEGIN_CASE */ void SDV_X509_CERT_GEN_PROCESS_TC002(char *csrPath, char *privPath, int keyType, int mdId, Hex *serial) { HITLS_X509_Csr *csr = NULL; HITLS_X509_Cert *cert = NULL; CRYPT_EAL_PkeyCtx *privKey = NULL; CRYPT_EAL_PkeyCtx *pubKey = NULL; uint8_t md[64] = {0}; // 64 : max md len uint32_t mdLen = 64; // 64 : max md len BslList *tmp = NULL; BSL_TIME beforeTime = {2024, 8, 22, 1, 1, 0, 1, 0}; BSL_TIME afterTime = {2050, 8, 22, 1, 1, 0, 1, 0}; BSL_Buffer encodeCert = {0}; TestMemInit(); ASSERT_EQ(CRYPT_EAL_PriKeyParseFile(BSL_FORMAT_ASN1, keyType, privPath, NULL, &privKey), 0); ASSERT_EQ(HITLS_X509_CsrParseFile(BSL_FORMAT_ASN1, csrPath, &csr), HITLS_PKI_SUCCESS); cert = HITLS_X509_CertNew(); ASSERT_TRUE(cert != NULL); /* Cannot parse after new */ ASSERT_EQ(HITLS_X509_CertParseBuff(BSL_FORMAT_ASN1, &encodeCert, &cert), HITLS_X509_ERR_INVALID_PARAM); /* Cannot digest before signing */ ASSERT_EQ(HITLS_X509_CertDigest(cert, mdId, md, &mdLen), HITLS_X509_ERR_CERT_NOT_SIGNED); /* Cannot generate before signing */ ASSERT_EQ(HITLS_X509_CertGenBuff(BSL_FORMAT_ASN1, cert, &encodeCert), HITLS_X509_ERR_CERT_NOT_SIGNED); /* Invalid parameters */ ASSERT_EQ(HITLS_X509_CertSign(mdId, privKey, NULL, NULL), HITLS_X509_ERR_INVALID_PARAM); /* Cannot sign before setting serial number */ ASSERT_EQ(HITLS_X509_CertSign(mdId, privKey, NULL, cert), HITLS_X509_ERR_CERT_INVALID_SERIAL_NUM); ASSERT_EQ(HITLS_X509_CertCtrl(cert, HITLS_X509_SET_SERIALNUM, serial->x, serial->len), 0); /* Cannot sign before setting issuer and subject */ ASSERT_EQ(HITLS_X509_CertSign(mdId, privKey, NULL, cert), HITLS_X509_ERR_CERT_INVALID_DN); ASSERT_EQ(HITLS_X509_CsrCtrl(csr, HITLS_X509_GET_SUBJECT_DN, &tmp, sizeof(BslList *)), 0); ASSERT_EQ(HITLS_X509_CertCtrl(cert, HITLS_X509_SET_SUBJECT_DN, tmp, sizeof(BslList)), 0); ASSERT_EQ(HITLS_X509_CertSign(mdId, privKey, NULL, cert), HITLS_X509_ERR_CERT_INVALID_DN); ASSERT_EQ(HITLS_X509_CertCtrl(cert, HITLS_X509_SET_ISSUER_DN, tmp, sizeof(BslList)), 0); /* Cannot sign before setting after time and before time */ ASSERT_EQ(HITLS_X509_CertSign(mdId, privKey, NULL, cert), HITLS_X509_ERR_CERT_INVALID_TIME); ASSERT_EQ(HITLS_X509_CertCtrl(cert, HITLS_X509_SET_BEFORE_TIME, &beforeTime, sizeof(BSL_TIME)), 0); ASSERT_EQ(HITLS_X509_CertSign(mdId, privKey, NULL, cert), HITLS_X509_ERR_CERT_INVALID_TIME); /* Before time is later than after time */ afterTime.year = beforeTime.year - 1; ASSERT_EQ(HITLS_X509_CertCtrl(cert, HITLS_X509_SET_AFTER_TIME, &afterTime, sizeof(BSL_TIME)), 0); ASSERT_EQ(HITLS_X509_CertSign(mdId, privKey, NULL, cert), HITLS_X509_ERR_CERT_START_TIME_LATER); afterTime.year = beforeTime.year + 1; ASSERT_EQ(HITLS_X509_CertCtrl(cert, HITLS_X509_SET_AFTER_TIME, &afterTime, sizeof(BSL_TIME)), 0); /* Cannot sign before setting public key */ ASSERT_EQ(HITLS_X509_CertSign(mdId, privKey, NULL, cert), HITLS_X509_ERR_CERT_INVALID_PUBKEY); /* Set public key */ ASSERT_EQ(HITLS_X509_CsrCtrl(csr, HITLS_X509_GET_PUBKEY, &pubKey, 0), 0); ASSERT_EQ(HITLS_X509_CertCtrl(cert, HITLS_X509_SET_PUBKEY, pubKey, 0), 0); /* Cannot generate before signing */ ASSERT_EQ(HITLS_X509_CertGenBuff(BSL_FORMAT_ASN1, cert, &encodeCert), HITLS_X509_ERR_CERT_NOT_SIGNED); /* Repeat sign is allowed. */ ASSERT_EQ(HITLS_X509_CertSign(mdId, privKey, NULL, cert), 0); ASSERT_EQ(HITLS_X509_CertSign(mdId, privKey, NULL, cert), 0); /* Cannot parse after signing */ ASSERT_EQ(HITLS_X509_CertParseBuff(BSL_FORMAT_ASN1, &encodeCert, &cert), HITLS_X509_ERR_INVALID_PARAM); /* Sing after generating is allowed. */ ASSERT_EQ(HITLS_X509_CertSign(mdId, privKey, NULL, cert), 0); /* Repeat digest is allowed. */ ASSERT_EQ(HITLS_X509_CertDigest(cert, mdId, md, &mdLen), 0); ASSERT_EQ(HITLS_X509_CertDigest(cert, mdId, md, &mdLen), 0); /* Repeat generate is allowed. */ ASSERT_EQ(HITLS_X509_CertGenBuff(BSL_FORMAT_ASN1, cert, &encodeCert), 0); BSL_SAL_Free(encodeCert.data); encodeCert.data = NULL; encodeCert.dataLen = 0; ASSERT_EQ(HITLS_X509_CertGenBuff(BSL_FORMAT_ASN1, cert, &encodeCert), 0); /* Cannot parse after generating */ ASSERT_EQ(HITLS_X509_CertParseBuff(BSL_FORMAT_ASN1, &encodeCert, &cert), HITLS_X509_ERR_INVALID_PARAM); EXIT: CRYPT_EAL_PkeyFreeCtx(privKey); CRYPT_EAL_PkeyFreeCtx(pubKey); HITLS_X509_CsrFree(csr); HITLS_X509_CertFree(cert); BSL_SAL_Free(encodeCert.data); } /* END_CASE */ /* BEGIN_CASE */ void SDV_X509_CERT_DIGEST_API_TC001(char *inCert, int inForm, int mdId) { TestRandInit(); HITLS_X509_Cert *cert = NULL; uint8_t md[64] = {0}; // 64 : max md len uint32_t mdLen = 64; // 64 : max md len ASSERT_EQ(HITLS_X509_CertParseFile(inForm, inCert, &cert), 0); /* Invalid parameters */ ASSERT_EQ(HITLS_X509_CertDigest(NULL, mdId, md, &mdLen), HITLS_X509_ERR_INVALID_PARAM); ASSERT_EQ(HITLS_X509_CertDigest(cert, mdId, NULL, &mdLen), HITLS_X509_ERR_INVALID_PARAM); ASSERT_EQ(HITLS_X509_CertDigest(cert, mdId, md, NULL), HITLS_X509_ERR_INVALID_PARAM); EXIT: HITLS_X509_CertFree(cert); } /* END_CASE */ /* BEGIN_CASE */ void SDV_X509_CERT_DIGEST_FUNC_TC001(char *inCert, int inForm, int mdId, Hex *expect) { TestRandInit(); BSL_Buffer encodeRaw = {0}; BSL_Buffer encodeNew = {0}; HITLS_X509_Cert *cert = NULL; uint8_t md[64] = {0}; // 64 : max md len uint32_t mdLen = 64; // 64 : max md len ASSERT_EQ(BSL_SAL_ReadFile(inCert, &encodeRaw.data, &encodeRaw.dataLen), 0); ASSERT_EQ(HITLS_X509_CertParseBuff(inForm, &encodeRaw, &cert), 0); ASSERT_EQ(HITLS_X509_CertDigest(cert, mdId, md, &mdLen), 0); ASSERT_COMPARE("cert digest", expect->x, expect->len, md, mdLen); ASSERT_EQ(HITLS_X509_CertGenBuff(inForm, cert, &encodeNew), 0); ASSERT_COMPARE("digest then gen", encodeRaw.data, encodeRaw.dataLen, encodeNew.data, encodeNew.dataLen); EXIT: HITLS_X509_CertFree(cert); BSL_SAL_Free(encodeRaw.data); BSL_SAL_Free(encodeNew.data); } /* END_CASE */ /* BEGIN_CASE */ void SDV_X509_CERT_SET_CSR_EXT_FUNC_TC001(int inForm, char *inCsr, int ret, Hex *expect) { TestRandInit(); BSL_ASN1_Buffer encodeExt = {0}; HITLS_X509_Csr *csr = NULL; HITLS_X509_Cert *cert = HITLS_X509_CertNew(); ASSERT_NE(cert, NULL); ASSERT_EQ(HITLS_X509_CsrParseFile(inForm, inCsr, &csr), 0); ASSERT_EQ(HITLS_X509_CertCtrl(cert, HITLS_X509_SET_CSR_EXT, csr, 0), ret); ASSERT_EQ(HITLS_X509_EncodeExt(0, cert->tbs.ext.extList, &encodeExt), 0); if (expect->len != 0) { ASSERT_TRUE((cert->tbs.ext.flag & HITLS_X509_EXT_FLAG_PARSE) == 0); ASSERT_TRUE((cert->tbs.ext.flag & HITLS_X509_EXT_FLAG_GEN) != 0); ASSERT_COMPARE("Csr ext", encodeExt.buff, encodeExt.len, expect->x, expect->len); } EXIT: HITLS_X509_CertFree(cert); HITLS_X509_CsrFree(csr); BSL_SAL_Free(encodeExt.buff); } /* END_CASE */ extern int32_t HITLS_X509_ParseCertTbs(BSL_ASN1_Buffer *asnArr, HITLS_X509_Cert *cert); static int32_t STUB_HITLS_X509_ParseCertTbs(BSL_ASN1_Buffer *asnArr, HITLS_X509_Cert *cert) { (void)asnArr; (void)cert; return BSL_MALLOC_FAIL; } /* BEGIN_CASE */ void SDV_X509_CERT_INVALIED_TEST_TC001(int format, char *path) { TestMemInit(); FuncStubInfo tmpRpInfo = {0}; STUB_Init(); ASSERT_TRUE(STUB_Replace(&tmpRpInfo, HITLS_X509_ParseCertTbs, STUB_HITLS_X509_ParseCertTbs) == 0); HITLS_X509_Cert *cert = NULL; ASSERT_NE(HITLS_X509_CertParseFile(format, path, &cert), HITLS_PKI_SUCCESS); EXIT: STUB_Reset(&tmpRpInfo); HITLS_X509_CertFree(cert); } /* END_CASE */
2301_79861745/bench_create
testcode/sdv/testcase/pki/cert/test_suite_sdv_x509_cert.c
C
unknown
46,810
/* * This file is part of the openHiTLS project. * * openHiTLS is licensed under the Mulan PSL v2. * You can use this software according to the terms and conditions of the Mulan PSL v2. * You may obtain a copy of Mulan PSL v2 at: * * http://license.coscl.org.cn/MulanPSL2 * * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. * See the Mulan PSL v2 for more details. */ /* BEGIN_HEADER */ #include "bsl_sal.h" #include "securec.h" #include "bsl_types.h" #include "bsl_log.h" #include "sal_file.h" #include "bsl_init.h" #include "crypt_encode_decode_key.h" #include "crypt_eal_codecs.h" #include "crypt_eal_rand.h" #include "crypt_errno.h" #include "hitls_cms_local.h" #include "hitls_pki_errno.h" /* END_HEADER */ /** * For test parse p7-encryptData of wrong conditions. */ /* BEGIN_CASE */ void SDV_CMS_PARSE_ENCRYPTEDDATA_TC001(Hex *buff) { BSL_Buffer output = {0}; char *pwd = "123456"; uint32_t pwdlen = strlen(pwd); int32_t ret = CRYPT_EAL_ParseAsn1PKCS7EncryptedData(NULL, NULL, (BSL_Buffer *)buff, (const uint8_t *)pwd, pwdlen, &output); ASSERT_EQ(ret, HITLS_PKI_SUCCESS); BSL_SAL_Free(output.data); output.data = NULL; ret = CRYPT_EAL_ParseAsn1PKCS7EncryptedData(NULL, NULL, NULL, (const uint8_t *)pwd, pwdlen, &output); ASSERT_EQ(ret, CRYPT_NULL_INPUT); ret = CRYPT_EAL_ParseAsn1PKCS7EncryptedData(NULL, NULL, (BSL_Buffer *)buff, NULL, pwdlen, &output); ASSERT_EQ(ret, CRYPT_NULL_INPUT); ret = CRYPT_EAL_ParseAsn1PKCS7EncryptedData(NULL, NULL, (BSL_Buffer *)buff, (const uint8_t *)pwd, pwdlen, NULL); ASSERT_EQ(ret, CRYPT_NULL_INPUT); ret = CRYPT_EAL_ParseAsn1PKCS7EncryptedData(NULL, NULL, (BSL_Buffer *)buff, (const uint8_t *)pwd, 8192, &output); ASSERT_EQ(ret, CRYPT_INVALID_ARG); char *pwd1 = "123456@123"; ret = CRYPT_EAL_ParseAsn1PKCS7EncryptedData(NULL, NULL, (BSL_Buffer *)buff, (const uint8_t *)pwd1, strlen(pwd1), &output); ASSERT_EQ(ret, CRYPT_EAL_CIPHER_DATA_ERROR); char *pwd2 = ""; ret = CRYPT_EAL_ParseAsn1PKCS7EncryptedData(NULL, NULL, (BSL_Buffer *)buff, (const uint8_t *)pwd2, strlen(pwd2), &output); ASSERT_EQ(ret, CRYPT_EAL_CIPHER_DATA_ERROR); (void)memset_s(buff->x + buff->len - 20, 16, 0, 16); // modify the ciphertext, 16 and 20 are random number. ret = CRYPT_EAL_ParseAsn1PKCS7EncryptedData(NULL, NULL, (BSL_Buffer *)buff, (const uint8_t *)pwd, pwdlen, &output); ASSERT_EQ(ret, CRYPT_EAL_CIPHER_DATA_ERROR); EXIT: return; } /* END_CASE */ /** * For test parse p7-encryptData of right conditions. */ /* BEGIN_CASE */ void SDV_CMS_PARSE_ENCRYPTEDDATA_TC002(Hex *buff) { BSL_Buffer output = {0}; char *pwd = "123456"; uint32_t pwdlen = strlen(pwd); int32_t ret = CRYPT_EAL_ParseAsn1PKCS7EncryptedData(NULL, NULL, (BSL_Buffer *)buff, (const uint8_t *)pwd, pwdlen, &output); ASSERT_EQ(ret, HITLS_PKI_SUCCESS); EXIT: BSL_SAL_Free(output.data); return; } /* END_CASE */ /** * For test parse p7-DigestInfo of wrong conditions. */ /* BEGIN_CASE */ void SDV_CMS_PARSE_DIGESTINFO_TC001(Hex *buff, int alg, Hex *digest) { BSL_Buffer output = {0}; BslCid cid = BSL_CID_UNKNOWN; int32_t ret = HITLS_CMS_ParseDigestInfo(NULL, &cid, &output); ASSERT_EQ(ret, HITLS_CMS_ERR_NULL_POINTER); ret = HITLS_CMS_ParseDigestInfo((BSL_Buffer *)buff, &cid, NULL); ASSERT_EQ(ret, HITLS_CMS_ERR_NULL_POINTER); ret = HITLS_CMS_ParseDigestInfo((BSL_Buffer *)buff, &cid, &output); ASSERT_EQ(ret, HITLS_PKI_SUCCESS); ASSERT_EQ(alg, cid); ASSERT_EQ(memcmp(output.data, digest->x, digest->len), 0); EXIT: BSL_SAL_Free(output.data); return; } /* END_CASE */ /** * For test parse p7-DigestInfo of right conditions. */ /* BEGIN_CASE */ void SDV_CMS_PARSE_DIGESTINFO_TC002(Hex *buff, int alg, Hex *digest) { BSL_Buffer output = {0}; BslCid cid = BSL_CID_UNKNOWN; int32_t ret = HITLS_CMS_ParseDigestInfo((BSL_Buffer *)buff, &cid, &output); ASSERT_EQ(ret, HITLS_PKI_SUCCESS); ASSERT_EQ(alg, cid); ASSERT_EQ(memcmp(output.data, digest->x, digest->len), 0); EXIT: BSL_SAL_Free(output.data); return; } /* END_CASE */ /** * For test encode p7-encryptData. */ /* BEGIN_CASE */ void SDV_CMS_ENCODE_ENCRYPTEDDATA_TC001(Hex *buff) { BSL_Buffer data = {buff->x, buff->len}; BSL_Buffer output = {0}; BSL_Buffer verify = {0}; char *pwd = "123456"; CRYPT_Pbkdf2Param param = {0}; param.pbesId = BSL_CID_PBES2; param.pbkdfId = BSL_CID_PBKDF2; param.hmacId = CRYPT_MAC_HMAC_SHA256; param.symId = CRYPT_CIPHER_AES256_CBC; param.pwd = (uint8_t *)pwd; param.pwdLen = strlen(pwd); param.saltLen = 16; param.itCnt = 2048; CRYPT_EncodeParam paramEx = {CRYPT_DERIVE_PBKDF2, &param}; ASSERT_EQ(TestRandInit(), HITLS_PKI_SUCCESS); int32_t ret = CRYPT_EAL_EncodePKCS7EncryptDataBuff(NULL, NULL, NULL, NULL, NULL); ASSERT_EQ(ret, CRYPT_NULL_INPUT); ret = CRYPT_EAL_EncodePKCS7EncryptDataBuff(NULL, NULL, &data, NULL, NULL); ASSERT_EQ(ret, CRYPT_NULL_INPUT); ret = CRYPT_EAL_EncodePKCS7EncryptDataBuff(NULL, NULL, &data, &paramEx, NULL); ASSERT_EQ(ret, CRYPT_NULL_INPUT); param.hmacId = CRYPT_MAC_MAX; ret = CRYPT_EAL_EncodePKCS7EncryptDataBuff(NULL, NULL, &data, &paramEx, &output); ASSERT_EQ(ret, CRYPT_ERR_ALGID); param.hmacId = CRYPT_MAC_HMAC_SHA256; ret = CRYPT_EAL_EncodePKCS7EncryptDataBuff(NULL, NULL, &data, &paramEx, &output); ASSERT_EQ(ret, HITLS_PKI_SUCCESS); ret = CRYPT_EAL_ParseAsn1PKCS7EncryptedData(NULL, NULL, &output, (const uint8_t *)pwd, strlen(pwd), &verify); ASSERT_EQ(ret, HITLS_PKI_SUCCESS); ASSERT_COMPARE("encode p7-encryptData", data.data, data.dataLen, verify.data, verify.dataLen); EXIT: TestRandDeInit(); BSL_SAL_FREE(verify.data); BSL_SAL_FREE(output.data); return; } /* END_CASE */ /** * For test encode p7-DigestInfo. */ /* BEGIN_CASE */ void SDV_CMS_ENCODE_DIGESTINFO_TC001() { BSL_Buffer input = {0}; BSL_Buffer output = {0}; BslCid cid = 0; BSL_Buffer digest = {0}; int32_t ret = HITLS_CMS_EncodeDigestInfoBuff(BSL_CID_MD5, NULL, NULL); ASSERT_EQ(ret, HITLS_CMS_ERR_NULL_POINTER); ret = HITLS_CMS_EncodeDigestInfoBuff(BSL_CID_MD5, &input, NULL); ASSERT_EQ(ret, HITLS_CMS_ERR_NULL_POINTER); input.dataLen = 1; ret = HITLS_CMS_EncodeDigestInfoBuff(BSL_CID_MD5, &input, &output); ASSERT_EQ(ret, HITLS_CMS_ERR_NULL_POINTER); input.dataLen = 0; ret = HITLS_CMS_EncodeDigestInfoBuff(BSL_CID_MD5, &input, &output); ASSERT_EQ(ret, HITLS_PKI_SUCCESS); ret = HITLS_CMS_ParseDigestInfo(&output, &cid, &digest); ASSERT_EQ(ret, HITLS_CMS_ERR_INVALID_DATA); BSL_SAL_FREE(output.data); input.data = (uint8_t *)"123456"; input.dataLen = 6; ret = HITLS_CMS_EncodeDigestInfoBuff(BSL_CID_MD5, &input, &output); ASSERT_EQ(ret, HITLS_PKI_SUCCESS); ret = HITLS_CMS_ParseDigestInfo(&output, &cid, &digest); ASSERT_EQ(ret, HITLS_PKI_SUCCESS); ASSERT_EQ(cid, BSL_CID_MD5); EXIT: BSL_SAL_FREE(digest.data); BSL_SAL_FREE(output.data); return; } /* END_CASE */ /** * For test encode p7-DigestInfo vector. */ /* BEGIN_CASE */ void SDV_CMS_ENCODE_DIGESTINFO_TC002(int algid, Hex *in) { BSL_Buffer input = {in->x, in->len}; BSL_Buffer output = {0}; BslCid cid = 0; BSL_Buffer digest = {0}; int32_t ret = HITLS_CMS_EncodeDigestInfoBuff(algid, &input, &output); ASSERT_EQ(ret, HITLS_PKI_SUCCESS); ret = HITLS_CMS_ParseDigestInfo(&output, &cid, &digest); ASSERT_EQ(ret, HITLS_PKI_SUCCESS); ASSERT_EQ(cid, algid); EXIT: BSL_SAL_FREE(digest.data); BSL_SAL_FREE(output.data); return; } /* END_CASE */
2301_79861745/bench_create
testcode/sdv/testcase/pki/cms/test_suite_sdv_cms.c
C
unknown
7,913
/* * This file is part of the openHiTLS project. * * openHiTLS is licensed under the Mulan PSL v2. * You can use this software according to the terms and conditions of the Mulan PSL v2. * You may obtain a copy of Mulan PSL v2 at: * * http://license.coscl.org.cn/MulanPSL2 * * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, * EITHER EXPRESS 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 "bsl_sal.h" #include "securec.h" #include "hitls_error.h" #include "hitls_pki_cert.h" #include "hitls_pki_utils.h" #include "hitls_pki_errno.h" #include "hitls_x509_verify.h" #include "bsl_types.h" #include "bsl_log.h" #include "hitls_cert_local.h" #include "hitls_crl_local.h" #include "bsl_init.h" #include "bsl_obj_internal.h" #include "bsl_uio.h" #include "crypt_errno.h" #include "crypt_eal_codecs.h" #include "crypt_eal_rand.h" #include "hitls_x509_local.h" #include "hitls_print_local.h" #include "bsl_params.h" #include "crypt_params_key.h" #define MAX_BUFF_SIZE 4096 #define PATH_MAX_LEN 4096 #define PWD_MAX_LEN 4096 /* END_HEADER */ static void FreeListData(void *data) { (void)data; return; } static void FreeSanListData(void *data) { TestMemInit(); BSL_GLOBAL_Init(); HITLS_X509_GeneralName *name = (HITLS_X509_GeneralName *)data; if (name->type == HITLS_X509_GN_DNNAME) { HITLS_X509_DnListFree((BslList *)name->value.data); } } static int32_t TestSignCb(int32_t mdId, CRYPT_EAL_PkeyCtx *prvKey, HITLS_X509_Asn1AlgId *signAlgId, void *obj) { (void)signAlgId; uint32_t signLen = CRYPT_EAL_PkeyGetSignLen(prvKey); uint8_t *sign = (uint8_t *)BSL_SAL_Malloc(signLen); if (sign == NULL) { return BSL_MALLOC_FAIL; } uint8_t *data = (uint8_t *)obj; int32_t ret = CRYPT_EAL_PkeySign(prvKey, mdId, data, 1, sign, &signLen); BSL_SAL_Free(sign); return ret; } /* BEGIN_CASE */ void SDV_HITLS_X509_FreeStoreCtx_TC001(void) { TestMemInit(); BSL_GLOBAL_Init(); HITLS_X509_StoreCtxFree(NULL); } /* END_CASE */ /* BEGIN_CASE */ void SDV_HITLS_X509_CtrlStoreCtx_TC001(void) { TestMemInit(); BSL_GLOBAL_Init(); ASSERT_EQ(HITLS_X509_StoreCtxCtrl(NULL, 0, NULL, 0), HITLS_X509_ERR_INVALID_PARAM); HITLS_X509_StoreCtx storeCtx = {0}; ASSERT_EQ(HITLS_X509_StoreCtxCtrl(&storeCtx, 0, NULL, 0), HITLS_X509_ERR_INVALID_PARAM); EXIT: BSL_GLOBAL_DeInit(); } /* END_CASE */ /* BEGIN_CASE */ void SDV_HITLS_X509_VerifyCert_TC001(void) { TestMemInit(); BSL_GLOBAL_Init(); ASSERT_EQ(HITLS_X509_CertVerify(NULL, NULL), HITLS_X509_ERR_INVALID_PARAM); HITLS_X509_StoreCtx storeCtx = {0}; ASSERT_EQ(HITLS_X509_CertVerify(&storeCtx, NULL), HITLS_X509_ERR_INVALID_PARAM); EXIT: BSL_GLOBAL_DeInit(); } /* END_CASE */ /* BEGIN_CASE */ void SDV_HITLS_X509_BuildCertChain_TC001(void) { TestMemInit(); BSL_GLOBAL_Init(); ASSERT_EQ(HITLS_X509_CertChainBuild(NULL, false, NULL, NULL), HITLS_X509_ERR_INVALID_PARAM); HITLS_X509_StoreCtx storeCtx = {0}; ASSERT_EQ(HITLS_X509_CertChainBuild(&storeCtx, false, NULL, NULL), HITLS_X509_ERR_INVALID_PARAM); HITLS_X509_Cert cert = {0}; ASSERT_EQ(HITLS_X509_CertChainBuild(&storeCtx, false, &cert, NULL), HITLS_X509_ERR_INVALID_PARAM); EXIT: BSL_GLOBAL_DeInit(); } /* END_CASE */ /* BEGIN_CASE */ void SDV_HITLS_X509_FreeCert_TC001(void) { TestMemInit(); BSL_GLOBAL_Init(); HITLS_X509_CertFree(NULL); } /* END_CASE */ /* BEGIN_CASE */ void SDV_HITLS_X509_ParseBuffCert_TC001(void) { TestMemInit(); HITLS_X509_Cert *cert = NULL; uint8_t buffData[10] = {0}; BSL_GLOBAL_Init(); ASSERT_EQ(HITLS_X509_CertParseBuff(0, NULL, NULL), HITLS_X509_ERR_INVALID_PARAM); BSL_Buffer buff = {0}; ASSERT_EQ(HITLS_X509_CertParseBuff(0, &buff, NULL), HITLS_X509_ERR_INVALID_PARAM); buff.data = buffData; ASSERT_EQ(HITLS_X509_CertParseBuff(0, &buff, NULL), HITLS_X509_ERR_INVALID_PARAM); buff.dataLen = 1; ASSERT_EQ(HITLS_X509_CertParseBuff(0, &buff, NULL), HITLS_X509_ERR_INVALID_PARAM); ASSERT_EQ(HITLS_X509_CertParseBuff(0xff, &buff, &cert), HITLS_X509_ERR_FORMAT_UNSUPPORT); EXIT: BSL_GLOBAL_DeInit(); } /* END_CASE */ /* BEGIN_CASE */ void SDV_HITLS_X509_ParseFileCert_TC001(void) { TestMemInit(); BSL_GLOBAL_Init(); ASSERT_EQ(HITLS_X509_CertParseFile(BSL_FORMAT_ASN1, NULL, NULL), BSL_NULL_INPUT); ASSERT_EQ(HITLS_X509_CertParseFile(BSL_FORMAT_ASN1, "../testdata/cert/asn1/nist384ca.crt", NULL), HITLS_X509_ERR_INVALID_PARAM); EXIT: BSL_GLOBAL_DeInit(); } /* END_CASE */ /* BEGIN_CASE */ void SDV_HITLS_X509_CtrlCert_TC001(void) { TestMemInit(); BSL_GLOBAL_Init(); ASSERT_EQ(HITLS_X509_CertCtrl(NULL, 0xff, NULL, 0), HITLS_X509_ERR_INVALID_PARAM); HITLS_X509_Cert cert = {0}; ASSERT_EQ(HITLS_X509_CertCtrl(&cert, 0x7fffffff, NULL, 0), HITLS_X509_ERR_INVALID_PARAM); ASSERT_EQ(HITLS_X509_CertCtrl(&cert, HITLS_X509_GET_ENCODELEN, NULL, 0), HITLS_X509_ERR_INVALID_PARAM); ASSERT_EQ(HITLS_X509_CertCtrl(&cert, HITLS_X509_GET_ENCODELEN, &cert, 0), HITLS_X509_ERR_INVALID_PARAM); ASSERT_EQ(HITLS_X509_CertCtrl(&cert, HITLS_X509_GET_ENCODE, NULL, 0), HITLS_X509_ERR_INVALID_PARAM); ASSERT_EQ(HITLS_X509_CertCtrl(&cert, HITLS_X509_GET_PUBKEY, NULL, 0), HITLS_X509_ERR_INVALID_PARAM); ASSERT_EQ(HITLS_X509_CertCtrl(&cert, HITLS_X509_GET_PUBKEY, &cert, 0), CRYPT_NULL_INPUT); ASSERT_EQ(HITLS_X509_CertCtrl(&cert, HITLS_X509_GET_SIGNALG, NULL, 0), HITLS_X509_ERR_INVALID_PARAM); ASSERT_EQ(HITLS_X509_CertCtrl(&cert, HITLS_X509_GET_SIGNALG, &cert, 0), HITLS_X509_ERR_INVALID_PARAM); ASSERT_EQ(HITLS_X509_CertCtrl(&cert, HITLS_X509_GET_SIGN_MDALG, NULL, 0), HITLS_X509_ERR_INVALID_PARAM); ASSERT_EQ(HITLS_X509_CertCtrl(&cert, HITLS_X509_GET_SIGN_MDALG, &cert, 0), HITLS_X509_ERR_INVALID_PARAM); ASSERT_EQ(HITLS_X509_CertCtrl(&cert, HITLS_X509_REF_UP, NULL, 0), HITLS_X509_ERR_INVALID_PARAM); ASSERT_EQ(HITLS_X509_CertCtrl(&cert, HITLS_X509_REF_UP, &cert, 0), HITLS_X509_ERR_INVALID_PARAM); ASSERT_EQ(HITLS_X509_CertCtrl(&cert, HITLS_X509_GET_SUBJECT_DN_STR, NULL, 0), HITLS_X509_ERR_INVALID_PARAM); ASSERT_EQ(HITLS_X509_CertCtrl(&cert, HITLS_X509_GET_ISSUER_DN_STR, NULL, 0), HITLS_X509_ERR_INVALID_PARAM); ASSERT_EQ(HITLS_X509_CertCtrl(&cert, HITLS_X509_GET_SERIALNUM, NULL, 0), HITLS_X509_ERR_INVALID_PARAM); ASSERT_EQ(HITLS_X509_CertCtrl(&cert, HITLS_X509_GET_BEFORE_TIME_STR, NULL, 0), HITLS_X509_ERR_INVALID_PARAM); ASSERT_EQ(HITLS_X509_CertCtrl(&cert, HITLS_X509_GET_AFTER_TIME_STR, NULL, 0), HITLS_X509_ERR_INVALID_PARAM); ASSERT_EQ(HITLS_X509_CertCtrl(&cert, HITLS_X509_EXT_GET_KUSAGE, NULL, 0), HITLS_X509_ERR_INVALID_PARAM); ASSERT_EQ(HITLS_X509_CertCtrl(&cert, HITLS_X509_EXT_GET_KUSAGE, &cert, 0), HITLS_X509_ERR_INVALID_PARAM); EXIT: BSL_GLOBAL_DeInit(); } /* END_CASE */ /* BEGIN_CASE */ void SDV_HITLS_X509_DupCert_TC001(void) { TestMemInit(); BSL_GLOBAL_Init(); HITLS_X509_Cert src = {0}; ASSERT_EQ(HITLS_X509_CertDup(NULL), NULL); ASSERT_EQ(HITLS_X509_CertDup(&src), NULL); EXIT: BSL_GLOBAL_DeInit(); } /* END_CASE */ /* BEGIN_CASE */ void SDV_HITLS_X509_FreeCrl_TC001(void) { HITLS_X509_CrlFree(NULL); } /* END_CASE */ /* BEGIN_CASE */ void SDV_HITLS_X509_CtrlCrl_TC001(void) { TestMemInit(); BSL_GLOBAL_Init(); ASSERT_EQ(HITLS_X509_CrlCtrl(NULL, 0xff, NULL, 0), HITLS_X509_ERR_INVALID_PARAM); HITLS_X509_Crl crl = {0}; ASSERT_EQ(HITLS_X509_CrlCtrl(&crl, 0xff, NULL, 0), HITLS_X509_ERR_INVALID_PARAM); ASSERT_EQ(HITLS_X509_CrlCtrl(&crl, HITLS_X509_REF_UP, NULL, 0), HITLS_X509_ERR_INVALID_PARAM); ASSERT_EQ(HITLS_X509_CrlCtrl(&crl, HITLS_X509_REF_UP, &crl, 0), HITLS_X509_ERR_INVALID_PARAM); EXIT: BSL_GLOBAL_DeInit(); } /* END_CASE */ /* BEGIN_CASE */ void SDV_HITLS_X509_ParseBuffCrl_TC001(void) { TestMemInit(); HITLS_X509_Crl *crl = NULL; uint8_t buffData[10] = {0}; BSL_GLOBAL_Init(); ASSERT_EQ(HITLS_X509_CrlParseBuff(0, NULL, NULL), HITLS_X509_ERR_INVALID_PARAM); BSL_Buffer buff = {0}; ASSERT_EQ(HITLS_X509_CrlParseBuff(0, &buff, NULL), HITLS_X509_ERR_INVALID_PARAM); buff.data = buffData; ASSERT_EQ(HITLS_X509_CrlParseBuff(0, &buff, NULL), HITLS_X509_ERR_INVALID_PARAM); buff.dataLen = 1; ASSERT_EQ(HITLS_X509_CrlParseBuff(0, &buff, NULL), HITLS_X509_ERR_INVALID_PARAM); ASSERT_EQ(HITLS_X509_CrlParseBuff(0xff, &buff, &crl), HITLS_X509_ERR_FORMAT_UNSUPPORT); EXIT: BSL_GLOBAL_DeInit(); } /* END_CASE */ /* BEGIN_CASE */ // todo void SDV_HITLS_X509_ParseFileCrl_TC001(void) { TestMemInit(); BSL_GLOBAL_Init(); ASSERT_EQ(HITLS_X509_CrlParseFile(BSL_FORMAT_ASN1, NULL, NULL), BSL_NULL_INPUT); ASSERT_EQ(HITLS_X509_CrlParseFile(BSL_FORMAT_ASN1, "../testdata/cert/asn1/ca-1-rsa-sha256-v2.der", NULL), HITLS_X509_ERR_INVALID_PARAM); EXIT: BSL_GLOBAL_DeInit(); } /* END_CASE */ /* BEGIN_CASE */ void SDV_CRYPT_EAL_ParseBuffPubKey_TC001(void) { TestMemInit(); BSL_GLOBAL_Init(); BSL_Buffer buff = {0}; CRYPT_EAL_PkeyCtx *pkey = NULL; ASSERT_EQ(CRYPT_EAL_DecodeBuffKey(0, 0xff, &buff, NULL, 0, &pkey), CRYPT_DECODE_NO_SUPPORT_TYPE); ASSERT_EQ(CRYPT_EAL_DecodeBuffKey(0, CRYPT_PUBKEY_SUBKEY, NULL, NULL, 0, &pkey), CRYPT_INVALID_ARG); ASSERT_EQ(CRYPT_EAL_DecodeBuffKey(0, CRYPT_PUBKEY_RSA, NULL, NULL, 0, &pkey), CRYPT_INVALID_ARG); ASSERT_EQ(CRYPT_EAL_DecodeBuffKey(0, CRYPT_PUBKEY_SUBKEY, &buff, NULL, 0, NULL), CRYPT_INVALID_ARG); ASSERT_EQ(CRYPT_EAL_DecodeBuffKey(0, CRYPT_PUBKEY_RSA, &buff, NULL, 0, NULL), CRYPT_INVALID_ARG); ASSERT_EQ(CRYPT_EAL_DecodeBuffKey(0, CRYPT_PUBKEY_SUBKEY, &buff, NULL, 0, &pkey), CRYPT_INVALID_ARG); ASSERT_EQ(CRYPT_EAL_DecodeBuffKey(0, CRYPT_PUBKEY_RSA, &buff, NULL, 0, &pkey), CRYPT_INVALID_ARG); EXIT: BSL_GLOBAL_DeInit(); } /* END_CASE */ /* BEGIN_CASE */ void SDV_CRYPT_EAL_ParseFilePubKey_TC001(void) { TestMemInit(); BSL_GLOBAL_Init(); ASSERT_EQ(CRYPT_EAL_DecodeFileKey(0xff, 0, NULL, NULL, 0, NULL), CRYPT_INVALID_ARG); ASSERT_EQ(CRYPT_EAL_DecodeFileKey(BSL_FORMAT_ASN1, CRYPT_PUBKEY_SUBKEY, NULL, NULL, 0, NULL), CRYPT_INVALID_ARG); ASSERT_EQ(CRYPT_EAL_DecodeFileKey(BSL_FORMAT_ASN1, CRYPT_PUBKEY_SUBKEY, "../testdata/cert/asn1/prime256v1pub.der", NULL, 0, NULL), CRYPT_INVALID_ARG); ASSERT_EQ(CRYPT_EAL_DecodeFileKey(BSL_FORMAT_ASN1, CRYPT_PUBKEY_RSA, NULL, NULL, 0, NULL), CRYPT_INVALID_ARG); ASSERT_EQ(CRYPT_EAL_DecodeFileKey(BSL_FORMAT_ASN1, CRYPT_PUBKEY_RSA, "../testdata/cert/asn1/rsa2048pub_pkcs1.der", NULL, 0, NULL), CRYPT_INVALID_ARG); EXIT: BSL_GLOBAL_DeInit(); } /* END_CASE */ /* BEGIN_CASE */ void SDV_CRYPT_EAL_ParseBuffPriKey_TC001(void) { TestMemInit(); BSL_GLOBAL_Init(); BSL_Buffer buff = {0}; uint8_t pwd = 0; CRYPT_EAL_PkeyCtx *key = NULL; ASSERT_EQ(CRYPT_EAL_DecodeBuffKey(0, 0xff, &buff, &pwd, 0, &key), CRYPT_DECODE_NO_SUPPORT_TYPE); ASSERT_EQ(CRYPT_EAL_DecodeBuffKey(0, CRYPT_PRIKEY_ECC, NULL, &pwd, 0, &key), CRYPT_INVALID_ARG); ASSERT_EQ(CRYPT_EAL_DecodeBuffKey(0, CRYPT_PRIKEY_RSA, NULL, &pwd, 0, &key), CRYPT_INVALID_ARG); ASSERT_EQ(CRYPT_EAL_DecodeBuffKey(0, CRYPT_PRIKEY_PKCS8_UNENCRYPT, NULL, &pwd, 0, &key), CRYPT_INVALID_ARG); ASSERT_EQ(CRYPT_EAL_DecodeBuffKey(0, CRYPT_PRIKEY_PKCS8_ENCRYPT, NULL, &pwd, 0, &key), CRYPT_INVALID_ARG); ASSERT_EQ(CRYPT_EAL_DecodeBuffKey(0, CRYPT_PRIKEY_ECC, &buff, NULL, 0, &key), CRYPT_INVALID_ARG); ASSERT_EQ(CRYPT_EAL_DecodeBuffKey(0, CRYPT_PRIKEY_RSA, &buff, NULL, 0, &key), CRYPT_INVALID_ARG); ASSERT_EQ(CRYPT_EAL_DecodeBuffKey(0, CRYPT_PRIKEY_PKCS8_UNENCRYPT, &buff, NULL, 0, &key), CRYPT_INVALID_ARG); ASSERT_EQ(CRYPT_EAL_DecodeBuffKey(0, CRYPT_PRIKEY_PKCS8_ENCRYPT, &buff, NULL, 0, &key), CRYPT_INVALID_ARG); ASSERT_EQ(CRYPT_EAL_DecodeBuffKey(0, CRYPT_PRIKEY_ECC, &buff, &pwd, 0, NULL), CRYPT_INVALID_ARG); ASSERT_EQ(CRYPT_EAL_DecodeBuffKey(0, CRYPT_PRIKEY_RSA, &buff, &pwd, 0, NULL), CRYPT_INVALID_ARG); ASSERT_EQ(CRYPT_EAL_DecodeBuffKey(0, CRYPT_PRIKEY_PKCS8_UNENCRYPT, &buff, &pwd, 0, NULL), CRYPT_INVALID_ARG); ASSERT_EQ(CRYPT_EAL_DecodeBuffKey(0, CRYPT_PRIKEY_PKCS8_ENCRYPT, &buff, &pwd, 0, NULL), CRYPT_INVALID_ARG); ASSERT_EQ(CRYPT_EAL_DecodeBuffKey(0, CRYPT_PRIKEY_ECC, &buff, &pwd, 0, &key), CRYPT_INVALID_ARG); ASSERT_EQ(CRYPT_EAL_DecodeBuffKey(0, CRYPT_PRIKEY_RSA, &buff, &pwd, 0, &key), CRYPT_INVALID_ARG); ASSERT_EQ(CRYPT_EAL_DecodeBuffKey(0, CRYPT_PRIKEY_PKCS8_UNENCRYPT, &buff, &pwd, 0, &key), CRYPT_INVALID_ARG); ASSERT_EQ(CRYPT_EAL_DecodeBuffKey(0, CRYPT_PRIKEY_PKCS8_ENCRYPT, &buff, &pwd, 0, &key), CRYPT_INVALID_ARG); EXIT: BSL_GLOBAL_DeInit(); } /* END_CASE */ /* BEGIN_CASE */ void SDV_CRYPT_EAL_ParseFilePriKey_TC001(void) { TestMemInit(); BSL_GLOBAL_Init(); ASSERT_EQ(CRYPT_EAL_DecodeFileKey(0xff, 0, NULL, NULL, 0, NULL), CRYPT_INVALID_ARG); ASSERT_EQ(CRYPT_EAL_DecodeFileKey(BSL_FORMAT_ASN1, CRYPT_PRIKEY_ECC, NULL, NULL, 0, NULL), CRYPT_INVALID_ARG); ASSERT_EQ(CRYPT_EAL_DecodeFileKey(BSL_FORMAT_ASN1, CRYPT_PRIKEY_ECC, "../testdata/cert/asn1/prime256v1.der", NULL, 0, NULL), CRYPT_INVALID_ARG); ASSERT_EQ(CRYPT_EAL_DecodeFileKey(BSL_FORMAT_ASN1, CRYPT_PRIKEY_RSA, NULL, NULL, 0, NULL), CRYPT_INVALID_ARG); ASSERT_EQ(CRYPT_EAL_DecodeFileKey(BSL_FORMAT_ASN1, CRYPT_PRIKEY_RSA, "../testdata/cert/asn1/rsa2048key_pkcs1.der", NULL, 0, NULL), CRYPT_INVALID_ARG); ASSERT_EQ(CRYPT_EAL_DecodeFileKey(BSL_FORMAT_ASN1, CRYPT_PRIKEY_PKCS8_UNENCRYPT, NULL, NULL, 0, NULL), CRYPT_INVALID_ARG); ASSERT_EQ(CRYPT_EAL_DecodeFileKey(BSL_FORMAT_ASN1, CRYPT_PRIKEY_PKCS8_UNENCRYPT, "../testdata/cert/asn1/prime256v1_pkcs8.der", NULL, 0, NULL), CRYPT_INVALID_ARG); ASSERT_EQ(CRYPT_EAL_DecodeFileKey(BSL_FORMAT_ASN1, CRYPT_PRIKEY_PKCS8_ENCRYPT, NULL, NULL, 0, NULL), CRYPT_INVALID_ARG); ASSERT_EQ(CRYPT_EAL_DecodeFileKey(BSL_FORMAT_ASN1, CRYPT_PRIKEY_PKCS8_ENCRYPT, "../testdata/cert/asn1/prime256v1_pkcs8_enc.der", NULL, 0, NULL), CRYPT_INVALID_ARG); EXIT: BSL_GLOBAL_DeInit(); } /* END_CASE */ /* BEGIN_CASE */ void SDV_CRYPT_EAL_ParseFilePriKeyFormat_TC001(int format, int type, char *path) { TestMemInit(); BSL_GLOBAL_Init(); CRYPT_EAL_PkeyCtx *key = NULL; ASSERT_EQ(CRYPT_EAL_DecodeFileKey(format, type, path, NULL, 0, &key), CRYPT_SUCCESS); EXIT: CRYPT_EAL_PkeyFreeCtx(key); BSL_GLOBAL_DeInit(); } /* END_CASE */ /* BEGIN_CASE */ void SDV_CRYPT_EAL_ParseFilePubKeyFormat_TC001(int format, int type, char *path) { TestMemInit(); BSL_GLOBAL_Init(); CRYPT_EAL_PkeyCtx *key = NULL; ASSERT_EQ(CRYPT_EAL_DecodeFileKey(format, type, path, NULL, 0, &key), CRYPT_SUCCESS); EXIT: CRYPT_EAL_PkeyFreeCtx(key); BSL_GLOBAL_DeInit(); } /* END_CASE */ /* BEGIN_CASE */ void SDV_X509_EncodeNameList_TC001(int format, char *certPath, Hex *expect) { HITLS_X509_Cert *cert = NULL; BSL_ASN1_Buffer name = {0}; TestMemInit(); BSL_GLOBAL_Init(); ASSERT_EQ(HITLS_X509_CertParseFile(format, certPath, &cert), 0); ASSERT_EQ(HITLS_X509_EncodeNameList(cert->tbs.issuerName, &name), 0); ASSERT_COMPARE("Encode names", name.buff, name.len, expect->x, expect->len); EXIT: HITLS_X509_CertFree(cert); BSL_SAL_Free(name.buff); BSL_GLOBAL_DeInit(); } /* END_CASE */ /* BEGIN_CASE */ void SDV_X509_EXT_SetBCons_TC001(void) { TestMemInit(); BSL_GLOBAL_Init(); HITLS_X509_Cert *cert = HITLS_X509_CertNew(); ASSERT_NE(cert, NULL); HITLS_X509_Ext *ext = &cert->tbs.ext; HITLS_X509_CertExt *certExt = (HITLS_X509_CertExt *)ext->extData; ASSERT_EQ(certExt->extFlags, 0); ASSERT_EQ(certExt->isCa, false); ASSERT_EQ(certExt->maxPathLen, -1); HITLS_X509_ExtBCons bCons = {true, true, 1}; ASSERT_EQ(HITLS_X509_ExtCtrl(ext, HITLS_X509_EXT_SET_BCONS, &bCons, 0), HITLS_X509_ERR_EXT_UNSUPPORT); ASSERT_EQ(HITLS_X509_CertCtrl(cert, HITLS_X509_EXT_SET_BCONS, &bCons, 0), HITLS_X509_ERR_INVALID_PARAM); ASSERT_EQ(HITLS_X509_CertCtrl(cert, HITLS_X509_EXT_SET_BCONS, &bCons, sizeof(HITLS_X509_ExtBCons)), 0); ASSERT_EQ(BSL_LIST_COUNT(ext->extList), 1); ASSERT_NE(certExt->extFlags & HITLS_X509_EXT_FLAG_BCONS, 0); ASSERT_EQ(certExt->isCa, true); ASSERT_EQ(certExt->maxPathLen, 1); EXIT: HITLS_X509_CertFree(cert); BSL_GLOBAL_DeInit(); } /* END_CASE */ /* BEGIN_CASE */ void SDV_X509_EXT_SetAkiSki_TC001(Hex *kid) { TestMemInit(); BSL_GLOBAL_Init(); HITLS_X509_Cert *cert = HITLS_X509_CertNew(); ASSERT_NE(cert, NULL); HITLS_X509_Ext *ext = &cert->tbs.ext; HITLS_X509_ExtAki aki = {true, {kid->x, kid->len}, NULL, {0}}; HITLS_X509_ExtSki ski = {true, {kid->x, kid->len}}; ASSERT_EQ(HITLS_X509_CertCtrl(cert, HITLS_X509_EXT_SET_SKI, &ski, 0), HITLS_X509_ERR_INVALID_PARAM); ASSERT_EQ(HITLS_X509_CertCtrl(cert, HITLS_X509_EXT_SET_AKI, &aki, 0), HITLS_X509_ERR_INVALID_PARAM); aki.kid.dataLen = 0; ASSERT_EQ(HITLS_X509_CertCtrl(cert, HITLS_X509_EXT_SET_AKI, &aki, sizeof(HITLS_X509_ExtAki)), HITLS_X509_ERR_EXT_KID); aki.kid.dataLen = kid->len; ski.kid.dataLen = 0; ASSERT_EQ(HITLS_X509_CertCtrl(cert, HITLS_X509_EXT_SET_SKI, &ski, sizeof(HITLS_X509_ExtSki)), HITLS_X509_ERR_EXT_KID); ski.kid.dataLen = kid->len; ASSERT_EQ(HITLS_X509_CertCtrl(cert, HITLS_X509_EXT_SET_AKI, &aki, sizeof(HITLS_X509_ExtAki)), 0); ASSERT_EQ(BSL_LIST_COUNT(ext->extList), 1); ASSERT_EQ(HITLS_X509_CertCtrl(cert, HITLS_X509_EXT_SET_SKI, &ski, sizeof(HITLS_X509_ExtSki)), 0); ASSERT_NE(ext->flag & HITLS_X509_EXT_FLAG_GEN, 0); ASSERT_EQ(BSL_LIST_COUNT(ext->extList), 1 + 1); EXIT: HITLS_X509_CertFree(cert); BSL_GLOBAL_DeInit(); } /* END_CASE */ /* BEGIN_CASE */ void SDV_X509_EXT_SetKeyUsage_TC001(void) { TestMemInit(); BSL_GLOBAL_Init(); HITLS_X509_Cert *cert = HITLS_X509_CertNew(); ASSERT_NE(cert, NULL); HITLS_X509_Ext *ext = &cert->tbs.ext; HITLS_X509_CertExt *certExt = (HITLS_X509_CertExt *)ext->extData; ASSERT_EQ(certExt->keyUsage, 0); HITLS_X509_ExtKeyUsage ku = {true, 0}; ASSERT_EQ(HITLS_X509_CertCtrl(cert, HITLS_X509_EXT_SET_KUSAGE, &ku, 0), HITLS_X509_ERR_INVALID_PARAM); ASSERT_EQ(HITLS_X509_CertCtrl(cert, HITLS_X509_EXT_SET_KUSAGE, &ku, sizeof(HITLS_X509_ExtKeyUsage)), HITLS_X509_ERR_EXT_KU); ku.keyUsage = HITLS_X509_EXT_KU_DIGITAL_SIGN | HITLS_X509_EXT_KU_NON_REPUDIATION | HITLS_X509_EXT_KU_KEY_ENCIPHERMENT | HITLS_X509_EXT_KU_DATA_ENCIPHERMENT | HITLS_X509_EXT_KU_KEY_AGREEMENT | HITLS_X509_EXT_KU_KEY_CERT_SIGN | HITLS_X509_EXT_KU_CRL_SIGN | HITLS_X509_EXT_KU_ENCIPHER_ONLY | HITLS_X509_EXT_KU_DECIPHER_ONLY; ku.keyUsage = ~ku.keyUsage; ASSERT_EQ(HITLS_X509_CertCtrl(cert, HITLS_X509_EXT_SET_KUSAGE, &ku, sizeof(HITLS_X509_ExtKeyUsage)), HITLS_X509_ERR_EXT_KU); ku.keyUsage = ~ku.keyUsage; ASSERT_EQ(HITLS_X509_CertCtrl(cert, HITLS_X509_EXT_SET_KUSAGE, &ku, sizeof(HITLS_X509_ExtKeyUsage)), 0); ASSERT_EQ(BSL_LIST_COUNT(ext->extList), 1); ASSERT_NE(certExt->extFlags & HITLS_X509_EXT_FLAG_KUSAGE, 0); ASSERT_NE(ext->flag & HITLS_X509_EXT_FLAG_GEN, 0); EXIT: HITLS_X509_CertFree(cert); BSL_GLOBAL_DeInit(); } /* END_CASE */ /* BEGIN_CASE */ void SDV_X509_EXT_SetExtendKeyUsage_TC001(void) { TestMemInit(); BSL_GLOBAL_Init(); HITLS_X509_Cert *cert = HITLS_X509_CertNew(); ASSERT_NE(cert, NULL); BslList *oidList = BSL_LIST_New(sizeof(BSL_Buffer)); ASSERT_NE(oidList, NULL); HITLS_X509_Ext *ext = &cert->tbs.ext; HITLS_X509_ExtExKeyUsage exku = {true, NULL}; ASSERT_EQ(HITLS_X509_CertCtrl(cert, HITLS_X509_EXT_SET_EXKUSAGE, &exku, 0), HITLS_X509_ERR_INVALID_PARAM); // error: list is null ASSERT_EQ(HITLS_X509_CertCtrl(cert, HITLS_X509_EXT_SET_EXKUSAGE, &exku, sizeof(HITLS_X509_ExtExKeyUsage)), HITLS_X509_ERR_EXT_EXTENDED_KU); // werror: list is empty exku.oidList = oidList; ASSERT_EQ(HITLS_X509_CertCtrl(cert, HITLS_X509_EXT_SET_EXKUSAGE, &exku, sizeof(HITLS_X509_ExtExKeyUsage)), HITLS_X509_ERR_EXT_EXTENDED_KU); // error: oid is null BSL_Buffer emptyOid = {0}; ASSERT_EQ(BSL_LIST_AddElement(oidList, &emptyOid, BSL_LIST_POS_END), 0); ASSERT_EQ(HITLS_X509_CertCtrl(cert, HITLS_X509_EXT_SET_EXKUSAGE, &exku, sizeof(HITLS_X509_ExtExKeyUsage)), HITLS_X509_ERR_EXT_EXTENDED_KU_ELE); BSL_LIST_DeleteAll(oidList, FreeListData); // success: normal oid BslOidString *oid = BSL_OBJ_GetOID(BSL_CID_KP_SERVERAUTH); ASSERT_NE(oid, NULL); BSL_Buffer oidBuff = {(uint8_t *)oid->octs, oid->octetLen}; ASSERT_EQ(BSL_LIST_AddElement(oidList, &oidBuff, BSL_LIST_POS_END), 0); ASSERT_EQ(HITLS_X509_CertCtrl(cert, HITLS_X509_EXT_SET_EXKUSAGE, &exku, sizeof(HITLS_X509_ExtExKeyUsage)), 0); ASSERT_NE(ext->flag & HITLS_X509_EXT_FLAG_GEN, 0); EXIT: HITLS_X509_CertFree(cert); BSL_LIST_FREE(oidList, FreeListData); BSL_GLOBAL_DeInit(); } /* END_CASE */ /* BEGIN_CASE */ void SDV_X509_EXT_SetSan_TC001(void) { TestMemInit(); BSL_GLOBAL_Init(); HITLS_X509_Cert *cert = HITLS_X509_CertNew(); ASSERT_NE(cert, NULL); BslList *list = BSL_LIST_New(sizeof(HITLS_X509_GeneralName)); ASSERT_NE(list, NULL); HITLS_X509_Ext *ext = &cert->tbs.ext; HITLS_X509_ExtSan san = {true, NULL}; ASSERT_EQ(HITLS_X509_CertCtrl(cert, HITLS_X509_EXT_SET_SAN, &san, 0), HITLS_X509_ERR_INVALID_PARAM); // error: list is null ASSERT_EQ(HITLS_X509_CertCtrl(cert, HITLS_X509_EXT_SET_SAN, &san, sizeof(HITLS_X509_ExtSan)), HITLS_X509_ERR_EXT_SAN); // error: list is empty san.names = list; ASSERT_EQ(HITLS_X509_CertCtrl(cert, HITLS_X509_EXT_SET_SAN, &san, sizeof(HITLS_X509_ExtSan)), HITLS_X509_ERR_EXT_SAN); // error: list data content is null HITLS_X509_GeneralName empty = {0}; ASSERT_EQ(BSL_LIST_AddElement(list, &empty, BSL_LIST_POS_END), 0); ASSERT_EQ(HITLS_X509_CertCtrl(cert, HITLS_X509_EXT_SET_SAN, &san, sizeof(HITLS_X509_ExtSan)), HITLS_X509_ERR_EXT_SAN_ELE); BSL_LIST_DeleteAll(list, FreeListData); // error: name type char *email = "test@a.com"; HITLS_X509_GeneralName errType = {HITLS_X509_GN_IP + 1, {(uint8_t *)email, (uint32_t)strlen(email)}}; ASSERT_EQ(BSL_LIST_AddElement(list, &errType, BSL_LIST_POS_END), 0); ASSERT_EQ(HITLS_X509_CertCtrl(cert, HITLS_X509_EXT_SET_SAN, &san, sizeof(HITLS_X509_ExtSan)), HITLS_X509_ERR_EXT_GN_UNSUPPORT); BSL_LIST_DeleteAll(list, FreeListData); // success HITLS_X509_GeneralName nomal = {HITLS_X509_GN_EMAIL, {(uint8_t *)email, (uint32_t)strlen(email)}}; ASSERT_EQ(BSL_LIST_AddElement(list, &nomal, BSL_LIST_POS_END), 0); ASSERT_EQ(HITLS_X509_CertCtrl(cert, HITLS_X509_EXT_SET_SAN, &san, sizeof(HITLS_X509_ExtSan)), 0); ASSERT_NE(ext->flag & HITLS_X509_EXT_FLAG_GEN, 0); EXIT: HITLS_X509_CertFree(cert); BSL_LIST_FREE(list, FreeListData); BSL_GLOBAL_DeInit(); } /* END_CASE */ /* BEGIN_CASE */ void SDV_X509_EXT_EncodeBCons_TC001(int critical, int isCa, int maxPathLen, Hex *expect) { TestMemInit(); BSL_GLOBAL_Init(); int8_t tag = BSL_ASN1_TAG_CONSTRUCTED | BSL_ASN1_TAG_SEQUENCE; HITLS_X509_ExtBCons bCons = {critical, isCa, maxPathLen}; BSL_ASN1_Buffer encode = {0}; HITLS_X509_Cert *cert = HITLS_X509_CertNew(); ASSERT_NE(cert, NULL); ASSERT_EQ(HITLS_X509_CertCtrl(cert, HITLS_X509_EXT_SET_BCONS, &bCons, sizeof(HITLS_X509_ExtBCons)), 0); ASSERT_EQ(HITLS_X509_EncodeExt(tag, cert->tbs.ext.extList, &encode), HITLS_PKI_SUCCESS); ASSERT_EQ(encode.len, expect->len); ASSERT_COMPARE("Ext: bCons", encode.buff, encode.len, expect->x, expect->len); EXIT: HITLS_X509_CertFree(cert); BSL_SAL_Free(encode.buff); BSL_GLOBAL_DeInit(); } /* END_CASE */ /* BEGIN_CASE */ void SDV_X509_EXT_EncodeExtendKeyUsage_TC001(int critical, Hex *oid1, Hex *oid2, Hex *expect) { TestMemInit(); BSL_GLOBAL_Init(); int8_t tag = BSL_ASN1_TAG_CONSTRUCTED | BSL_ASN1_TAG_SEQUENCE; BSL_ASN1_Buffer encode = {0}; HITLS_X509_ExtExKeyUsage exku = {critical, NULL}; HITLS_X509_Cert *cert = HITLS_X509_CertNew(); ASSERT_NE(cert, NULL); exku.oidList = BSL_LIST_New(sizeof(BSL_Buffer)); ASSERT_NE(exku.oidList, NULL); ASSERT_EQ(BSL_LIST_AddElement(exku.oidList, oid1, BSL_LIST_POS_END), 0); ASSERT_EQ(BSL_LIST_AddElement(exku.oidList, oid2, BSL_LIST_POS_END), 0); ASSERT_EQ(HITLS_X509_CertCtrl(cert, HITLS_X509_EXT_SET_EXKUSAGE, &exku, sizeof(HITLS_X509_ExtExKeyUsage)), 0); ASSERT_EQ(HITLS_X509_EncodeExt(tag, cert->tbs.ext.extList, &encode), HITLS_PKI_SUCCESS); ASSERT_EQ(encode.len, expect->len); ASSERT_COMPARE("Ext: extendKeyUsage", encode.buff, encode.len, expect->x, expect->len); EXIT: HITLS_X509_CertFree(cert); BSL_LIST_DeleteAll(exku.oidList, FreeListData); BSL_SAL_Free(exku.oidList); BSL_SAL_Free(encode.buff); BSL_GLOBAL_DeInit(); } /* END_CASE */ /* BEGIN_CASE */ void SDV_X509_AddDnName_TC001(int unknownCid, int cid, Hex *oid, Hex *value) { TestMemInit(); BSL_GLOBAL_Init(); BslList *list = BSL_LIST_New(1); ASSERT_TRUE(list != NULL); HITLS_X509_DN unknownName[1] = {{unknownCid, value->x, value->len}}; HITLS_X509_DN dnName[1] = {{cid, value->x, value->len}}; HITLS_X509_DN dnNullName[1] = {{cid, NULL, value->len}}; HITLS_X509_DN dnZeroLenName[1] = {{cid, value->x, 0}}; ASSERT_EQ(HITLS_X509_AddDnName(list, unknownName, 1), HITLS_X509_ERR_SET_DNNAME_UNKNOWN); ASSERT_EQ(HITLS_X509_AddDnName(list, dnName, 0), HITLS_X509_ERR_INVALID_PARAM); ASSERT_EQ(HITLS_X509_AddDnName(list, NULL, 0), HITLS_X509_ERR_INVALID_PARAM); ASSERT_EQ(HITLS_X509_AddDnName(list, dnNullName, 1), HITLS_X509_ERR_INVALID_PARAM); ASSERT_EQ(HITLS_X509_AddDnName(list, dnZeroLenName, 1), HITLS_X509_ERR_INVALID_PARAM); ASSERT_EQ(HITLS_X509_AddDnName(list, dnName, 1), HITLS_PKI_SUCCESS); ASSERT_EQ(BSL_LIST_COUNT(list), 2); // layer 1 and layer 2 HITLS_X509_NameNode **node = BSL_LIST_First(list); ASSERT_EQ((*node)->layer, 1); // layer 1 ASSERT_EQ((*node)->nameType.tag, 0); ASSERT_EQ((*node)->nameType.buff, NULL); ASSERT_EQ((*node)->nameType.len, 0); ASSERT_EQ((*node)->nameValue.tag, 0); ASSERT_EQ((*node)->nameValue.buff, NULL); ASSERT_EQ((*node)->nameValue.len, 0); node = BSL_LIST_Next(list); ASSERT_EQ((*node)->layer, 2); // layer 2 ASSERT_EQ((*node)->nameType.tag, BSL_ASN1_TAG_OBJECT_ID); ASSERT_COMPARE("nameOid", (*node)->nameType.buff, (*node)->nameType.len, oid->x, oid->len); ASSERT_EQ((*node)->nameValue.tag, BSL_ASN1_TAG_UTF8STRING); ASSERT_COMPARE("nameValue", (*node)->nameValue.buff, (*node)->nameValue.len, value->x, value->len); /* subject name can add repeat name */ ASSERT_EQ(HITLS_X509_AddDnName(list, dnName, 1), HITLS_PKI_SUCCESS); list->count = 100; // 100: the max number of name type. ASSERT_EQ(HITLS_X509_AddDnName(list, dnName, 1), HITLS_X509_ERR_SET_DNNAME_TOOMUCH); EXIT: BSL_LIST_FREE(list, (BSL_LIST_PFUNC_FREE)HITLS_X509_FreeNameNode); BSL_GLOBAL_DeInit(); } /* END_CASE */ /* BEGIN_CASE */ void SDV_X509_EXT_EncodeSan_TC001(int critical, int type1, int type2, int type3, int type4, int dirCid1, int dirCid2, Hex *value, Hex *expect) { TestMemInit(); BSL_GLOBAL_Init(); int8_t tag = BSL_ASN1_TAG_CONSTRUCTED | BSL_ASN1_TAG_SEQUENCE; BSL_ASN1_Buffer encode = {0}; HITLS_X509_ExtSan san = {critical, NULL}; HITLS_X509_Cert *cert = HITLS_X509_CertNew(); ASSERT_NE(cert, NULL); san.names = BSL_LIST_New(sizeof(BSL_Buffer)); ASSERT_NE(san.names, NULL); // Generate san BslList *dirNames = HITLS_X509_DnListNew(); ASSERT_NE(dirNames, NULL); HITLS_X509_DN dnName1[1] = {{(BslCid)dirCid1, value->x, value->len}}; HITLS_X509_DN dnName2[1] = {{(BslCid)dirCid2, value->x, value->len}}; ASSERT_EQ(HITLS_X509_AddDnName(dirNames, dnName1, 1), 0); ASSERT_EQ(HITLS_X509_AddDnName(dirNames, dnName2, 1), 0); HITLS_X509_GeneralName names[] = { {type1, {value->x, value->len}}, {type2, {value->x, value->len}}, {type3, {value->x, value->len}}, {type4, {value->x, value->len}}, {HITLS_X509_GN_DNNAME, {(uint8_t *)dirNames, sizeof(BslList *)}}, }; for (uint32_t i = 0; i < sizeof(names) / sizeof(names[0]); i++) { ASSERT_EQ(BSL_LIST_AddElement(san.names, &names[i], BSL_LIST_POS_END), 0); } // set san and encode ext ASSERT_EQ(HITLS_X509_CertCtrl(cert, HITLS_X509_EXT_SET_SAN, &san, sizeof(HITLS_X509_ExtSan)), 0); ASSERT_EQ(HITLS_X509_EncodeExt(tag, cert->tbs.ext.extList, &encode), HITLS_PKI_SUCCESS); ASSERT_EQ(encode.len, expect->len); ASSERT_COMPARE("Ext: san", encode.buff, encode.len, expect->x, expect->len); EXIT: HITLS_X509_CertFree(cert); BSL_LIST_DeleteAll(san.names, FreeSanListData); BSL_SAL_Free(san.names); BSL_SAL_Free(encode.buff); BSL_GLOBAL_DeInit(); } /* END_CASE */ /* BEGIN_CASE */ void SDV_X509_EXT_EncodeKeyUsage_TC001(int critical, int usage, Hex *expect) { TestMemInit(); BSL_GLOBAL_Init(); int8_t tag = BSL_ASN1_TAG_CONSTRUCTED | BSL_ASN1_TAG_SEQUENCE; HITLS_X509_ExtKeyUsage ku = {critical, usage}; BSL_ASN1_Buffer encode = {0}; HITLS_X509_Cert *cert = HITLS_X509_CertNew(); ASSERT_NE(cert, NULL); ASSERT_EQ(HITLS_X509_CertCtrl(cert, HITLS_X509_EXT_SET_KUSAGE, &ku, sizeof(HITLS_X509_ExtKeyUsage)), 0); ASSERT_EQ(HITLS_X509_EncodeExt(tag, cert->tbs.ext.extList, &encode), HITLS_PKI_SUCCESS); ASSERT_EQ(encode.len, expect->len); ASSERT_COMPARE("Ext: keyUsage", encode.buff, encode.len, expect->x, expect->len); EXIT: HITLS_X509_CertFree(cert); BSL_SAL_Free(encode.buff); BSL_GLOBAL_DeInit(); } /* END_CASE */ /* BEGIN_CASE */ void SDV_X509_EXT_EncodeAKiSki_TC001(int critical1, int critical2, Hex *kid1, Hex *kid2, Hex *expect) { TestMemInit(); BSL_GLOBAL_Init(); int8_t tag = BSL_ASN1_TAG_CONSTRUCTED | BSL_ASN1_TAG_SEQUENCE; HITLS_X509_ExtAki aki = {critical1, {kid1->x, kid1->len}, NULL, {0}}; HITLS_X509_ExtSki ski = {critical2, {kid2->x, kid2->len}}; BSL_ASN1_Buffer encode = {0}; HITLS_X509_Cert *cert = HITLS_X509_CertNew(); ASSERT_NE(cert, NULL); ASSERT_EQ(HITLS_X509_CertCtrl(cert, HITLS_X509_EXT_SET_SKI, &ski, sizeof(HITLS_X509_ExtSki)), 0); ASSERT_EQ(HITLS_X509_CertCtrl(cert, HITLS_X509_EXT_SET_AKI, &aki, sizeof(HITLS_X509_ExtAki)), 0); ASSERT_EQ(HITLS_X509_EncodeExt(tag, cert->tbs.ext.extList, &encode), HITLS_PKI_SUCCESS); ASSERT_EQ(encode.len, expect->len); ASSERT_COMPARE("Ext:aki ski", encode.buff, encode.len, expect->x, expect->len); EXIT: HITLS_X509_CertFree(cert); BSL_SAL_Free(encode.buff); BSL_GLOBAL_DeInit(); } /* END_CASE */ typedef struct { int32_t type; Hex *value; } TestGeneralNameMap; /* BEGIN_CASE */ void SDV_X509_EXT_ParseGeneralNames_TC001(Hex *encode, Hex *ip, Hex *uri, Hex *rfc822, Hex *regId, Hex *dns) { TestGeneralNameMap map[] = { {HITLS_X509_GN_DNNAME, NULL}, {HITLS_X509_GN_IP, ip}, {HITLS_X509_GN_URI, uri}, {HITLS_X509_GN_OTHER, NULL}, {HITLS_X509_GN_EMAIL, rfc822}, {HITLS_X509_GN_RID, regId}, {HITLS_X509_GN_DNS, dns}, }; TestMemInit(); BslList *list = BSL_LIST_New(sizeof(HITLS_X509_GeneralName)); ASSERT_NE(list, NULL); ASSERT_EQ(HITLS_X509_ParseGeneralNames(encode->x, encode->len, list), HITLS_PKI_SUCCESS); ASSERT_EQ(BSL_LIST_COUNT(list), sizeof(map) / sizeof(map[0])); HITLS_X509_GeneralName *name = NULL; uint32_t idx = 0; for (name = BSL_LIST_GET_FIRST(list); name != NULL; name = BSL_LIST_GET_NEXT(list), idx++) { ASSERT_EQ(name->type, map[idx].type); if (map[idx].value != NULL) { ASSERT_COMPARE("gn", name->value.data, name->value.dataLen, map[idx].value->x, map[idx].value->len); } } EXIT: HITLS_X509_ClearGeneralNames(list); BSL_SAL_Free(list); } /* END_CASE */ /* BEGIN_CASE */ void SDV_X509_EXT_ParseGeneralNames_Error_TC001(Hex *encode, int ret) { BSL_GLOBAL_Init(); TestMemInit(); BslList *list = BSL_LIST_New(sizeof(HITLS_X509_GeneralName)); ASSERT_NE(list, NULL); ASSERT_EQ(HITLS_X509_ParseGeneralNames(encode->x, encode->len, list), ret); EXIT: BSL_SAL_Free(list); BSL_GLOBAL_DeInit(); } /* END_CASE */ /* BEGIN_CASE */ void SDV_X509_EXT_ParseSki_TC001(Hex *encode, int ret, Hex *kid) { BSL_GLOBAL_Init(); TestMemInit(); HITLS_X509_ExtSki ski = {0}; HITLS_X509_ExtEntry entry = {BSL_CID_CE_SUBJECTKEYIDENTIFIER, {0}, true, {0, encode->len, encode->x}}; ASSERT_EQ(HITLS_X509_ParseSubjectKeyId(&entry, &ski), ret); if (ret == 0) { ASSERT_EQ(ski.critical, entry.critical); ASSERT_COMPARE("Subject kid", kid->x, kid->len, ski.kid.data, ski.kid.dataLen); } EXIT: BSL_GLOBAL_DeInit(); } /* END_CASE */ /* BEGIN_CASE */ void SDV_X509_EXT_ParseExtendedKu_TC001(Hex *encode, Hex *ku1, Hex *ku2, Hex *ku3) { BSL_GLOBAL_Init(); TestMemInit(); Hex *values[] = {ku1, ku2, ku3}; uint32_t cnt = sizeof(values) / sizeof(values[0]); HITLS_X509_ExtExKeyUsage exku = {0}; HITLS_X509_ExtEntry entry = {BSL_CID_CE_EXTKEYUSAGE, {0}, true, {0, encode->len, encode->x}}; ASSERT_EQ(HITLS_X509_ParseExtendedKeyUsage(&entry, &exku), 0); ASSERT_EQ(exku.critical, entry.critical); ASSERT_EQ(BSL_LIST_COUNT(exku.oidList), cnt); uint32_t idx = 0; for (BSL_Buffer *data = BSL_LIST_GET_FIRST(exku.oidList); data != NULL; data = BSL_LIST_GET_NEXT(exku.oidList)) { ASSERT_COMPARE("Extended key usage", values[idx]->x, values[idx]->len, data->data, data->dataLen); idx++; } EXIT: HITLS_X509_ClearExtendedKeyUsage(&exku); BSL_GLOBAL_DeInit(); } /* END_CASE */ /* BEGIN_CASE */ void SDV_X509_EXT_ParseAki_TC001(Hex *encode, Hex *kid, Hex *serial, int nameCnt) { HITLS_X509_ExtAki aki = {0}; HITLS_X509_ExtEntry entry = {BSL_CID_CE_AUTHORITYKEYIDENTIFIER, {0}, true, {0, encode->len, encode->x}}; TestMemInit(); ASSERT_EQ(HITLS_X509_ParseAuthorityKeyId(&entry, &aki), 0); ASSERT_EQ(aki.critical, entry.critical); ASSERT_COMPARE("kid", aki.kid.data, aki.kid.dataLen, kid->x, kid->len); ASSERT_COMPARE("serial", aki.serialNum.data, aki.serialNum.dataLen, serial->x, serial->len); ASSERT_EQ(BSL_LIST_COUNT(aki.issuerName), nameCnt); EXIT: HITLS_X509_ClearAuthorityKeyId(&aki); } /* END_CASE */ /* BEGIN_CASE */ void SDV_X509_EXT_ParseSan_TC001(Hex *encode, int ret, int gnNameCnt, int gnType1, int gnType2, Hex *rfc822, Hex *dnType, Hex *dnValue) { HITLS_X509_ExtSan san = {0}; HITLS_X509_ExtEntry entry = {BSL_CID_CE_SUBJECTALTNAME, {0}, true, {0, encode->len, encode->x}}; HITLS_X509_GeneralName *gnName = NULL; BslList *dirNameList = NULL; HITLS_X509_NameNode *dirName = NULL; TestMemInit(); ASSERT_EQ(HITLS_X509_ParseSubjectAltName(&entry, &san), ret); if (ret == 0) { ASSERT_EQ(san.critical, entry.critical); ASSERT_EQ(BSL_LIST_COUNT(san.names), gnNameCnt); gnName = BSL_LIST_GET_FIRST(san.names); ASSERT_EQ(gnName->type, gnType1); ASSERT_COMPARE("gnName 1", rfc822->x, rfc822->len, gnName->value.data, gnName->value.dataLen); gnName = BSL_LIST_GET_NEXT(san.names); ASSERT_EQ(gnName->type, gnType2); dirNameList = (BslList *)gnName->value.data; ASSERT_EQ(BSL_LIST_COUNT(dirNameList), 1 + 1); // layer 1 and layer 2 dirName = BSL_LIST_GET_FIRST(dirNameList); // layer 1 dirName = BSL_LIST_GET_NEXT(dirNameList); // layer 2 ASSERT_COMPARE("dnname type", dirName->nameType.buff, dirName->nameType.len, dnType->x, dnType->len); ASSERT_COMPARE("dnname value", dirName->nameValue.buff, dirName->nameValue.len, dnValue->x, dnValue->len); } EXIT: HITLS_X509_ClearSubjectAltName(&san); } /* END_CASE */ /* BEGIN_CASE */ void SDV_X509_EXT_GetSki_TC001(Hex *encode, int ret, int critical, Hex *kid) { TestMemInit(); BSL_ASN1_Buffer asnExt = {BSL_ASN1_CLASS_CTX_SPECIFIC | BSL_ASN1_TAG_CONSTRUCTED, encode->len, encode->x}; bool getIsExist; HITLS_X509_ExtSki ski = {0}; HITLS_X509_Ext *ext = HITLS_X509_ExtNew(HITLS_X509_EXT_TYPE_CSR); ASSERT_NE(ext, NULL); ASSERT_EQ(HITLS_X509_ParseExt(&asnExt, ext), 0); ASSERT_EQ(HITLS_X509_ExtCtrl(ext, HITLS_X509_EXT_CHECK_SKI, &getIsExist, sizeof(bool)), 0); ASSERT_EQ(getIsExist, ret == HITLS_PKI_SUCCESS); ASSERT_EQ(HITLS_X509_ExtCtrl(ext, HITLS_X509_EXT_GET_SKI, &ski, sizeof(HITLS_X509_ExtSki)), ret); ASSERT_EQ(ski.critical, critical); ASSERT_COMPARE("Get ski", ski.kid.data, ski.kid.dataLen, kid->x, kid->len); EXIT: HITLS_X509_ExtFree(ext); } /* END_CASE */ /* BEGIN_CASE */ void SDV_HITLS_X509_ExtParamCheck_TC001(void) { TestMemInit(); BSL_GLOBAL_Init(); ASSERT_EQ(HITLS_X509_ExtNew(HITLS_X509_EXT_TYPE_CERT), NULL); ASSERT_EQ(HITLS_X509_ExtNew(HITLS_X509_EXT_TYPE_CRL), NULL); HITLS_X509_Ext *ext = HITLS_X509_ExtNew(HITLS_X509_EXT_TYPE_CSR); ASSERT_NE(ext, NULL); HITLS_X509_ExtFree(ext); EXIT: BSL_GLOBAL_DeInit(); } /* END_CASE */ /* BEGIN_CASE */ void SDV_X509_SIGN_Api_TC001(void) { CRYPT_EAL_PkeyCtx *prvKey = NULL; uint8_t obj = 1; TestMemInit(); prvKey = CRYPT_EAL_PkeyNewCtx(CRYPT_PKEY_RSA); ASSERT_NE(prvKey, NULL); ASSERT_EQ(HITLS_X509_Sign(CRYPT_MD_SHA3_384, prvKey, NULL, &obj, TestSignCb), HITLS_X509_ERR_HASHID); ASSERT_EQ(HITLS_X509_Sign(CRYPT_MD_SHA384, prvKey, NULL, &obj, TestSignCb), BSL_MALLOC_FAIL); EXIT: CRYPT_EAL_PkeyFreeCtx(prvKey); } /* END_CASE */ /* BEGIN_CASE */ void SDV_X509_SIGN_Func_TC001(char *keyPath, int keyFormat, int keyType, int mdId, int pad, int hashId, int mgfId, int saltLen, int ret) { CRYPT_EAL_PkeyCtx *prvKey = NULL; HITLS_X509_SignAlgParam algParam = {0}; HITLS_X509_SignAlgParam *algParamPtr = NULL; uint8_t obj = 1; if (pad == 0) { algParamPtr = NULL; } else if (pad == CRYPT_EMSA_PSS) { algParam.algId = BSL_CID_RSASSAPSS; algParam.rsaPss.mdId = hashId; algParam.rsaPss.mgfId = mgfId; algParam.rsaPss.saltLen = saltLen; algParamPtr = &algParam; } TestMemInit(); TestRandInit(); ASSERT_EQ(CRYPT_EAL_DecodeFileKey(keyFormat, keyType, keyPath, NULL, 0, &prvKey), 0); ASSERT_EQ(HITLS_X509_Sign(mdId, prvKey, algParamPtr, &obj, TestSignCb), ret); EXIT: CRYPT_EAL_PkeyFreeCtx(prvKey); TestRandDeInit(); } /* END_CASE */ /* BEGIN_CASE */ void SDV_X509_SIGN_Func_TC002(void) { CRYPT_EAL_PkeyCtx *prvKey = NULL; HITLS_X509_SignAlgParam algParam = {0}; uint8_t obj = 1; CRYPT_RsaPadType pad = CRYPT_EMSA_PKCSV15; CRYPT_EAL_PkeyPara para = {0}; uint8_t e[] = {1, 0, 1}; para.id = CRYPT_PKEY_RSA; para.para.rsaPara.e = e; para.para.rsaPara.eLen = 3; para.para.rsaPara.bits = 1024; TestMemInit(); TestRandInit(); prvKey = CRYPT_EAL_PkeyNewCtx(CRYPT_PKEY_RSA); ASSERT_NE(prvKey, NULL); ASSERT_EQ(CRYPT_EAL_PkeySetPara(prvKey, &para), CRYPT_SUCCESS); ASSERT_EQ(CRYPT_EAL_PkeyGen(prvKey), 0); ASSERT_EQ(CRYPT_EAL_PkeyCtrl(prvKey, CRYPT_CTRL_SET_RSA_PADDING, &pad, sizeof(CRYPT_RsaPadType)), 0); ASSERT_EQ(HITLS_X509_Sign(CRYPT_MD_SHA224, prvKey, NULL, &obj, TestSignCb), 0); ASSERT_EQ(HITLS_X509_Sign(CRYPT_MD_SHA224, prvKey, &algParam, &obj, TestSignCb), HITLS_X509_ERR_SIGN_PARAM); pad = CRYPT_EMSA_PSS; ASSERT_EQ(CRYPT_EAL_PkeyCtrl(prvKey, CRYPT_CTRL_SET_RSA_PADDING, &pad, sizeof(CRYPT_RsaPadType)), 0); ASSERT_EQ(HITLS_X509_Sign(CRYPT_MD_SHA224, prvKey, NULL, &obj, TestSignCb), 0); CRYPT_RSA_PssPara pssPara = {1, CRYPT_MD_SHA256, CRYPT_MD_SHA256}; BSL_Param pssParam[4] = { {CRYPT_PARAM_RSA_MD_ID, BSL_PARAM_TYPE_INT32, &pssPara.mdId, sizeof(pssPara.mdId), 0}, {CRYPT_PARAM_RSA_MGF1_ID, BSL_PARAM_TYPE_INT32, &pssPara.mgfId, sizeof(pssPara.mgfId), 0}, {CRYPT_PARAM_RSA_SALTLEN, BSL_PARAM_TYPE_INT32, &pssPara.saltLen, sizeof(pssPara.saltLen), 0}, BSL_PARAM_END}; ASSERT_EQ(CRYPT_EAL_PkeyCtrl(prvKey, CRYPT_CTRL_SET_RSA_EMSA_PSS, pssParam, 0), 0); ASSERT_EQ(HITLS_X509_Sign(CRYPT_MD_SHA224, prvKey, NULL, &obj, TestSignCb), HITLS_X509_ERR_MD_NOT_MATCH); ASSERT_EQ(HITLS_X509_Sign(CRYPT_MD_SHA256, prvKey, NULL, &obj, TestSignCb), 0); EXIT: CRYPT_EAL_PkeyFreeCtx(prvKey); TestRandDeInit(); } /* END_CASE */ /* BEGIN_CASE */ void SDV_HITLS_X509_PrintCtrl_TC001(void) { TestMemInit(); BSL_UIO *uio = BSL_UIO_New(BSL_UIO_BufferMethod()); ASSERT_NE(uio, NULL); uint32_t flag = 0; BslList list = {0}; ASSERT_EQ(HITLS_PKI_PrintCtrl(0xff, NULL, 0, NULL), HITLS_X509_ERR_INVALID_PARAM); ASSERT_EQ(HITLS_PKI_PrintCtrl(HITLS_PKI_SET_PRINT_FLAG, NULL, 0, NULL), HITLS_X509_ERR_INVALID_PARAM); ASSERT_EQ(HITLS_PKI_PrintCtrl(HITLS_PKI_SET_PRINT_FLAG, &flag, 0, NULL), HITLS_X509_ERR_INVALID_PARAM); ASSERT_EQ(HITLS_PKI_PrintCtrl(HITLS_PKI_PRINT_DNNAME, NULL, sizeof(BslList), uio), HITLS_X509_ERR_INVALID_PARAM); ASSERT_EQ(HITLS_PKI_PrintCtrl(HITLS_PKI_PRINT_DNNAME, &list, sizeof(BslList), NULL), HITLS_X509_ERR_INVALID_PARAM); ASSERT_EQ(HITLS_PKI_PrintCtrl(HITLS_PKI_PRINT_DNNAME, &list, 0, uio), HITLS_X509_ERR_INVALID_PARAM); EXIT: BSL_UIO_Free(uio); return; } /* END_CASE */ static int32_t ReadFile(const char *filePath, uint8_t *buff, uint32_t buffLen, uint32_t *outLen) { FILE *fp = NULL; int32_t ret = -1; fp = fopen(filePath, "rb"); if (fp == NULL) { return ret; } if (fseek(fp, 0, SEEK_END) != 0) { goto EXIT; } long fileSize = ftell(fp); if (fileSize < 0 || (uint32_t)fileSize > buffLen) { goto EXIT; } rewind(fp); size_t readSize = fread(buff, 1, fileSize, fp); if (readSize != (size_t)fileSize) { goto EXIT; } *outLen = (uint32_t)fileSize; ret = 0; EXIT: (void)fclose(fp); return ret; } static int32_t PrintBuffTest(int cmd, BSL_Buffer *data, char *log, Hex *expect, bool isExpectFile) { int32_t ret = -1; uint8_t dnBuf[MAX_BUFF_SIZE] = {}; uint32_t dnBufLen = sizeof(dnBuf); uint8_t expectBuf[MAX_BUFF_SIZE] = {}; uint32_t expectBufLen = sizeof(expectBuf); BSL_UIO *uio = BSL_UIO_New(BSL_UIO_MemMethod()); ASSERT_NE(uio, NULL); ASSERT_EQ(HITLS_PKI_PrintCtrl(cmd, data->data, data->dataLen, uio), HITLS_PKI_SUCCESS); ASSERT_EQ(BSL_UIO_Read(uio, dnBuf, MAX_BUFF_SIZE, &dnBufLen), 0); if (isExpectFile) { ASSERT_EQ(ReadFile((char *)expect->x, expectBuf, MAX_BUFF_SIZE, &expectBufLen), 0); ASSERT_COMPARE(log, expectBuf, expectBufLen, dnBuf, dnBufLen - 1); // Ignore line break differences } else { ASSERT_COMPARE(log, expect->x, expect->len, dnBuf, dnBufLen - 1); // Ignore line break differences } ret = 0; EXIT: BSL_UIO_Free(uio); return ret; } /* BEGIN_CASE */ void SDV_HITLS_X509_PrintDn_TC002(char *certPath, int format, int printFlag, char *expect, Hex *multiExpect) { TestMemInit(); HITLS_X509_Cert *cert = NULL; BslList *rawIssuer = NULL; Hex expectName = {}; if (printFlag == HITLS_PKI_PRINT_DN_MULTILINE) { expectName.x = multiExpect->x; expectName.len = multiExpect->len; } else { expectName.x = (uint8_t *)expect; expectName.len = strlen(expect); } ASSERT_EQ(HITLS_X509_CertParseFile(format, certPath, &cert), HITLS_PKI_SUCCESS); ASSERT_NE(cert, NULL); ASSERT_EQ(HITLS_X509_CertCtrl(cert, HITLS_X509_GET_ISSUER_DN, &rawIssuer, sizeof(BslList *)), HITLS_PKI_SUCCESS); BSL_Buffer data = {(uint8_t *)rawIssuer, sizeof(BslList)}; ASSERT_EQ(HITLS_PKI_PrintCtrl(HITLS_PKI_SET_PRINT_FLAG, &printFlag, sizeof(int), NULL), HITLS_PKI_SUCCESS); ASSERT_EQ(PrintBuffTest(HITLS_PKI_PRINT_DNNAME, &data, "Print Distinguish name", &expectName, false), 0); EXIT: HITLS_X509_CertFree(cert); } /* END_CASE */ /* BEGIN_CASE */ void SDV_CRYPT_EAL_DecodeBuffKey_Ex_TC001(void) { #ifndef HITLS_CRYPTO_PROVIDER SKIP_TEST(); #else TestMemInit(); BSL_GLOBAL_Init(); CRYPT_EAL_PkeyCtx *key = NULL; BSL_Buffer encode = {0}; BSL_Buffer pwd = {0}; uint8_t data[10] = {0}; uint8_t pwdData[10] = {0}; // Test NULL parameters ASSERT_EQ(CRYPT_EAL_ProviderDecodeBuffKey(NULL, NULL, BSL_CID_UNKNOWN, "ASN1", "PUBKEY_RSA", NULL, NULL, NULL), CRYPT_INVALID_ARG); ASSERT_EQ(CRYPT_EAL_ProviderDecodeBuffKey(NULL, NULL, BSL_CID_UNKNOWN, "ASN1", "PUBKEY_RSA", &encode, NULL, NULL), CRYPT_INVALID_ARG); // Test invalid encode buffer ASSERT_EQ(CRYPT_EAL_ProviderDecodeBuffKey(NULL, NULL, BSL_CID_UNKNOWN, "ASN1", "PUBKEY_RSA", &encode, &pwd, &key), CRYPT_INVALID_ARG); encode.data = data; ASSERT_EQ(CRYPT_EAL_ProviderDecodeBuffKey(NULL, NULL, BSL_CID_UNKNOWN, "ASN1", "PUBKEY_RSA", &encode, &pwd, &key), CRYPT_INVALID_ARG); // Test invalid format encode.dataLen = sizeof(data); ASSERT_EQ(CRYPT_EAL_ProviderDecodeBuffKey(NULL, NULL, BSL_CID_UNKNOWN, "UNKNOWN_FORMAT", "PUBKEY_RSA", &encode, &pwd, &key), CRYPT_DECODE_ERR_NO_USABLE_DECODER); // Test invalid type ASSERT_EQ(CRYPT_EAL_ProviderDecodeBuffKey(NULL, NULL, BSL_CID_UNKNOWN, "ASN1", "UNKNOWN_TYPE", &encode, &pwd, &key), CRYPT_DECODE_ERR_NO_USABLE_DECODER); // Test invalid password buffer for encrypted private key pwd.data = pwdData; pwd.dataLen = PWD_MAX_LEN + 1; ASSERT_EQ(CRYPT_EAL_ProviderDecodeBuffKey(NULL, NULL, BSL_CID_UNKNOWN, "ASN1", "PRIKEY_PKCS8_ENCRYPT", &encode, &pwd, &key), CRYPT_INVALID_ARG); // Test NULL password data with non-zero length pwd.data = NULL; pwd.dataLen = 10; ASSERT_EQ(CRYPT_EAL_ProviderDecodeBuffKey(NULL, NULL, BSL_CID_UNKNOWN, "ASN1", "PRIKEY_PKCS8_ENCRYPT", &encode, &pwd, &key), CRYPT_INVALID_ARG); EXIT: BSL_GLOBAL_DeInit(); #endif } /* END_CASE */ /* BEGIN_CASE */ void SDV_CRYPT_EAL_DecodeFileKey_Ex_TC001(void) { #ifndef HITLS_CRYPTO_PROVIDER SKIP_TEST(); #else TestMemInit(); BSL_GLOBAL_Init(); CRYPT_EAL_PkeyCtx *key = NULL; BSL_Buffer pwd = {0}; uint8_t pwdData[10] = {0}; // Test NULL parameters ASSERT_EQ(CRYPT_EAL_ProviderDecodeFileKey(NULL, NULL, CRYPT_PKEY_RSA, "ASN1", "PUBKEY_RSA", NULL, NULL, NULL), CRYPT_INVALID_ARG); // Test invalid path char longPath[PATH_MAX_LEN + 2] = {0}; memset(longPath, 'a', PATH_MAX_LEN + 1); ASSERT_EQ(CRYPT_EAL_ProviderDecodeFileKey(NULL, NULL, CRYPT_PKEY_RSA, "ASN1", "PUBKEY_RSA", longPath, &pwd, &key), CRYPT_INVALID_ARG); // Test invalid format ASSERT_EQ(CRYPT_EAL_ProviderDecodeFileKey(NULL, NULL, CRYPT_PKEY_RSA, "UNKNOWN_FORMAT", "PUBKEY_RSA", "../testdata/cert/asn1/rsa2048pub_pkcs1.der", &pwd, &key), CRYPT_DECODE_NO_SUPPORT_FORMAT); // Test invalid type ASSERT_EQ(CRYPT_EAL_ProviderDecodeFileKey(NULL, NULL, CRYPT_PKEY_RSA, "ASN1", "UNKNOWN_TYPE", "../testdata/cert/asn1/rsa2048pub_pkcs1.der", &pwd, &key), CRYPT_DECODE_NO_SUPPORT_TYPE); // Test invalid password buffer for encrypted private key pwd.data = pwdData; pwd.dataLen = PWD_MAX_LEN + 1; ASSERT_EQ(CRYPT_EAL_ProviderDecodeFileKey(NULL, NULL, CRYPT_PKEY_RSA, "ASN1", "PRIKEY_PKCS8_ENCRYPT", "../testdata/cert/asn1/prime256v1_pkcs8_enc.der", &pwd, &key), CRYPT_INVALID_ARG); // Test NULL password data with non-zero length pwd.data = NULL; pwd.dataLen = 10; ASSERT_EQ(CRYPT_EAL_ProviderDecodeFileKey(NULL, NULL, CRYPT_PKEY_ECDSA, "ASN1", "PRIKEY_PKCS8_ENCRYPT", "../testdata/cert/asn1/prime256v1_pkcs8_enc.der", &pwd, &key), CRYPT_INVALID_ARG); EXIT: BSL_GLOBAL_DeInit(); #endif } /* END_CASE */ /* BEGIN_CASE */ void SDV_HITLS_X509_PrintCrl_TC001(char *certPath, int format, int printFlag, char *expectFile) { TestMemInit(); HITLS_X509_Crl *crl = NULL; int32_t *version = NULL; Hex expect = { (uint8_t *)expectFile, 0}; ASSERT_EQ(HITLS_X509_CrlParseFile(format, certPath, &crl), HITLS_PKI_SUCCESS); ASSERT_NE(crl, NULL); ASSERT_EQ(HITLS_X509_CrlCtrl(crl, HITLS_X509_GET_VERSION, &version, sizeof(int32_t)), HITLS_PKI_SUCCESS); BSL_Buffer data = {(uint8_t *)crl, sizeof(HITLS_X509_Crl *)}; ASSERT_EQ(HITLS_PKI_PrintCtrl(HITLS_PKI_SET_PRINT_FLAG, &printFlag, sizeof(int), NULL), HITLS_PKI_SUCCESS); ASSERT_EQ(PrintBuffTest(HITLS_PKI_PRINT_CRL, &data, "Print crl file", &expect, true), 0); EXIT: HITLS_X509_CrlFree(crl); } /* END_CASE */
2301_79861745/bench_create
testcode/sdv/testcase/pki/common/test_suite_sdv_common.c
C
unknown
49,180
/* * This file is part of the openHiTLS project. * * openHiTLS is licensed under the Mulan PSL v2. * You can use this software according to the terms and conditions of the Mulan PSL v2. * You may obtain a copy of Mulan PSL v2 at: * * http://license.coscl.org.cn/MulanPSL2 * * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, * EITHER EXPRESS 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 <stdbool.h> #include "securec.h" #include "bsl_sal.h" #include "bsl_list.h" #include "bsl_obj.h" #include "bsl_types.h" #include "crypt_errno.h" #include "crypt_types.h" #include "crypt_params_key.h" #include "crypt_eal_pkey.h" #include "crypt_eal_codecs.h" #include "crypt_eal_rand.h" #include "crypt_util_rand.h" #include "hitls_pki_cert.h" #include "hitls_pki_crl.h" #include "hitls_pki_csr.h" #include "hitls_pki_errno.h" #include "hitls_pki_types.h" #include "hitls_pki_utils.h" #include "hitls_x509_verify.h" /* END_HEADER */ static inline void UnusedParam1(int param1, int param2, int param3) { (void)param1; (void)param2; (void)param3; } static inline void UnusedParam2(int param1, int param2, void *param3) { (void)param1; (void)param2; (void)param3; } static bool PkiSkipTest(int32_t algId, int32_t format) { #ifndef HITLS_BSL_PEM if (format == BSL_FORMAT_PEM) { return true; } #else (void)format; #endif switch (algId) { #ifdef HITLS_CRYPTO_RSA case CRYPT_PKEY_RSA: case BSL_CID_RSASSAPSS: return false; #endif #ifdef HITLS_CRYPTO_ECDSA case CRYPT_PKEY_ECDSA: return false; #endif #ifdef HITLS_CRYPTO_SM2 case CRYPT_PKEY_SM2: return false; #endif #ifdef HITLS_CRYPTO_ED25519 case CRYPT_PKEY_ED25519: return false; #endif default: return true; } } #ifdef HITLS_CRYPTO_KEY_ENCODE #ifdef HITLS_CRYPTO_RSA static int32_t SetRsaPara(CRYPT_EAL_PkeyCtx *pkey) { uint8_t e[] = {1, 0, 1}; // RSA public exponent CRYPT_EAL_PkeyPara para = {0}; para.id = CRYPT_PKEY_RSA; para.para.rsaPara.e = e; para.para.rsaPara.eLen = 3; // public exponent length = 3 para.para.rsaPara.bits = 2048; return CRYPT_EAL_PkeySetPara(pkey, &para); } static int32_t SetRsaPssPara(CRYPT_EAL_PkeyCtx *pkey) { int32_t mdId = CRYPT_MD_SHA256; int32_t saltLen = 20; // 20 bytes salt BSL_Param pssParam[4] = { {CRYPT_PARAM_RSA_MD_ID, BSL_PARAM_TYPE_INT32, &mdId, sizeof(mdId), 0}, {CRYPT_PARAM_RSA_MGF1_ID, BSL_PARAM_TYPE_INT32, &mdId, sizeof(mdId), 0}, {CRYPT_PARAM_RSA_SALTLEN, BSL_PARAM_TYPE_INT32, &saltLen, sizeof(saltLen), 0}, BSL_PARAM_END}; return CRYPT_EAL_PkeyCtrl(pkey, CRYPT_CTRL_SET_RSA_EMSA_PSS, pssParam, 0); } #endif // HITLS_CRYPT_RSA static CRYPT_EAL_PkeyCtx *GenKey(int32_t algId, int32_t curveId) { CRYPT_EAL_PkeyCtx *pkey = CRYPT_EAL_PkeyNewCtx(algId == BSL_CID_RSASSAPSS ? BSL_CID_RSA : algId); ASSERT_NE(pkey, NULL); if (algId == CRYPT_PKEY_ECDSA) { ASSERT_EQ(CRYPT_EAL_PkeySetParaById(pkey, curveId), CRYPT_SUCCESS); } #ifdef HITLS_CRYPTO_RSA if (algId == CRYPT_PKEY_RSA) { ASSERT_EQ(SetRsaPara(pkey), CRYPT_SUCCESS); } if (algId == BSL_CID_RSASSAPSS) { ASSERT_EQ(SetRsaPara(pkey), CRYPT_SUCCESS); ASSERT_EQ(SetRsaPssPara(pkey), CRYPT_SUCCESS); } #endif ASSERT_EQ(CRYPT_EAL_PkeyGen(pkey), CRYPT_SUCCESS); return pkey; EXIT: CRYPT_EAL_PkeyFreeCtx(pkey); return NULL; } /** * Generate DER/PEM public/private key: rsa, ecc, sm2, ed25519 */ static int32_t TestEncodeKey(int32_t algId, int32_t type, int32_t curveId, char *path) { BSL_Buffer encode = {0}; int32_t ret = CRYPT_MEM_ALLOC_FAIL; CRYPT_EAL_PkeyCtx *pkey = GenKey(algId, curveId); ASSERT_NE(pkey, NULL); #ifdef HITLS_BSL_SAL_FILE if (path != NULL) { ASSERT_EQ(CRYPT_EAL_EncodeFileKey(pkey, NULL, BSL_FORMAT_ASN1, type, path), CRYPT_SUCCESS); } #ifdef HITLS_BSL_PEM if (path != NULL) { ASSERT_EQ(CRYPT_EAL_EncodeFileKey(pkey, NULL, BSL_FORMAT_PEM, type, path), CRYPT_SUCCESS); } #endif #else (void)path; #endif ASSERT_EQ(CRYPT_EAL_EncodeBuffKey(pkey, NULL, BSL_FORMAT_ASN1, type, &encode), CRYPT_SUCCESS); BSL_SAL_FREE(encode.data); #ifdef HITLS_BSL_PEM ASSERT_EQ(CRYPT_EAL_EncodeBuffKey(pkey, NULL, BSL_FORMAT_PEM, type, &encode), CRYPT_SUCCESS); BSL_SAL_FREE(encode.data); #endif ret = CRYPT_SUCCESS; EXIT: CRYPT_EAL_PkeyFreeCtx(pkey); return ret; } #endif // HITLS_CRYPTO_KEY_ENCODE #if defined(HITLS_PKI_X509_CRL_GEN) || defined(HITLS_PKI_X509_CSR_GEN) || defined(HITLS_PKI_X509_CRT_GEN) static char g_sm2DefaultUserid[] = "1234567812345678"; static void SetSignParam(int32_t algId, int32_t mdId, HITLS_X509_SignAlgParam *algParam, CRYPT_RSA_PssPara *pssParam) { if (algId == BSL_CID_RSASSAPSS) { algParam->algId = BSL_CID_RSASSAPSS; pssParam->mdId = mdId; pssParam->mgfId = mdId; pssParam->saltLen = 20; // 20 bytes salt algParam->rsaPss = *pssParam; } if (algId == BSL_CID_SM2DSA) { algParam->algId = BSL_CID_SM2DSAWITHSM3; algParam->sm2UserId.data = (uint8_t *)g_sm2DefaultUserid; algParam->sm2UserId.dataLen = (uint32_t)strlen(g_sm2DefaultUserid); } } #endif #if defined(HITLS_PKI_X509_CRL_GEN) || defined(HITLS_PKI_X509_CRT_GEN) static BslList* GenDNList(void) { HITLS_X509_DN dnName1[1] = {{BSL_CID_AT_COMMONNAME, (uint8_t *)"OH", 2}}; HITLS_X509_DN dnName2[1] = {{BSL_CID_AT_COUNTRYNAME, (uint8_t *)"CN", 2}}; BslList *dirNames = HITLS_X509_DnListNew(); ASSERT_NE(dirNames, NULL); ASSERT_EQ(HITLS_X509_AddDnName(dirNames, dnName1, 1), HITLS_PKI_SUCCESS); ASSERT_EQ(HITLS_X509_AddDnName(dirNames, dnName2, 1), HITLS_PKI_SUCCESS); return dirNames; EXIT: HITLS_X509_DnListFree(dirNames); return NULL; } static BslList* GenGeneralNameList(void) { char *str = "test"; HITLS_X509_GeneralName *email = NULL; HITLS_X509_GeneralName *dns = NULL; HITLS_X509_GeneralName *dname = NULL; HITLS_X509_GeneralName *uri = NULL; HITLS_X509_GeneralName *ip = NULL; BslList *names = BSL_LIST_New(sizeof(HITLS_X509_GeneralName)); ASSERT_NE(names, NULL); email = BSL_SAL_Malloc(sizeof(HITLS_X509_GeneralName)); dns = BSL_SAL_Malloc(sizeof(HITLS_X509_GeneralName)); dname = BSL_SAL_Malloc(sizeof(HITLS_X509_GeneralName)); uri = BSL_SAL_Malloc(sizeof(HITLS_X509_GeneralName)); ip = BSL_SAL_Malloc(sizeof(HITLS_X509_GeneralName)); ASSERT_TRUE(email != NULL && dns != NULL && dname != NULL && uri != NULL && ip != NULL); email->type = HITLS_X509_GN_EMAIL; dns->type = HITLS_X509_GN_DNS; uri->type = HITLS_X509_GN_URI; dname->type = HITLS_X509_GN_DNNAME; ip->type = HITLS_X509_GN_IP; email->value.dataLen = strlen(str); dns->value.dataLen = strlen(str); uri->value.dataLen = strlen(str); dname->value.dataLen = sizeof(BslList *); ip->value.dataLen = strlen(str); email->value.data = BSL_SAL_Dump(str, strlen(str)); dns->value.data = BSL_SAL_Dump(str, strlen(str)); uri->value.data = BSL_SAL_Dump(str, strlen(str)); dname->value.data = (uint8_t *)GenDNList(); ip->value.data = BSL_SAL_Dump(str, strlen(str)); ASSERT_TRUE(email->value.data != NULL && dns->value.data != NULL && uri->value.data != NULL && dname->value.data != NULL && ip->value.data != NULL); ASSERT_EQ(BSL_LIST_AddElement(names, email, BSL_LIST_POS_END), 0); ASSERT_EQ(BSL_LIST_AddElement(names, dns, BSL_LIST_POS_END), 0); ASSERT_EQ(BSL_LIST_AddElement(names, uri, BSL_LIST_POS_END), 0); ASSERT_EQ(BSL_LIST_AddElement(names, dname, BSL_LIST_POS_END), 0); ASSERT_EQ(BSL_LIST_AddElement(names, ip, BSL_LIST_POS_END), 0); return names; EXIT: HITLS_X509_FreeGeneralName(email); HITLS_X509_FreeGeneralName(dns); HITLS_X509_FreeGeneralName(dname); HITLS_X509_FreeGeneralName(uri); HITLS_X509_FreeGeneralName(ip); BSL_LIST_FREE(names, (BSL_LIST_PFUNC_FREE)HITLS_X509_FreeGeneralName); return NULL; } #endif #ifdef HITLS_PKI_X509_CRL_GEN static int32_t SetCrlEntry(HITLS_X509_Crl *crl) { int32_t ret = 1; BSL_TIME revokeTime = {2030, 1, 1, 0, 0, 0, 0, 0}; uint8_t serialNum[4] = {0x11, 0x22, 0x33, 0x44}; HITLS_X509_RevokeExtReason reason = {0, 1}; // keyCompromise BSL_TIME invalidTime = revokeTime; HITLS_X509_RevokeExtTime invalidTimeExt = {false, invalidTime}; HITLS_X509_CrlEntry *entry = HITLS_X509_CrlEntryNew(); ASSERT_NE(entry, NULL); ASSERT_EQ(HITLS_X509_CrlEntryCtrl(entry, HITLS_X509_CRL_SET_REVOKED_SERIALNUM, serialNum, sizeof(serialNum)),0); ASSERT_EQ(HITLS_X509_CrlEntryCtrl(entry, HITLS_X509_CRL_SET_REVOKED_REVOKE_TIME, &revokeTime, sizeof(BSL_TIME)),0); ASSERT_EQ(HITLS_X509_CrlEntryCtrl(entry, HITLS_X509_CRL_SET_REVOKED_REASON, &reason, sizeof(HITLS_X509_RevokeExtReason)), 0); ASSERT_EQ(HITLS_X509_CrlEntryCtrl(entry, HITLS_X509_CRL_SET_REVOKED_INVALID_TIME, &invalidTimeExt, sizeof(HITLS_X509_RevokeExtTime)), 0); HITLS_X509_RevokeExtCertIssuer certIssuer = {true, NULL}; certIssuer.issuerName = GenGeneralNameList(); ASSERT_EQ(HITLS_X509_CrlEntryCtrl(entry, HITLS_X509_CRL_SET_REVOKED_CERTISSUER, &certIssuer, sizeof(HITLS_X509_ExtSan)), 0); ASSERT_EQ(HITLS_X509_CrlCtrl(crl, HITLS_X509_CRL_ADD_REVOKED_CERT, entry, 0), 0); ret = 0; EXIT: HITLS_X509_CrlEntryFree(entry); BSL_LIST_FREE(certIssuer.issuerName, (BSL_LIST_PFUNC_FREE)HITLS_X509_FreeGeneralName); return ret; } #endif // HITLS_PKI_X509_CRL_GEN #ifdef HITLS_PKI_X509_CSR_GEN static int32_t FillExt(HITLS_X509_Ext *ext) { HITLS_X509_ExtBCons bCons = {true, false, 1}; HITLS_X509_ExtKeyUsage ku = {true, HITLS_X509_EXT_KU_DIGITAL_SIGN | HITLS_X509_EXT_KU_NON_REPUDIATION}; ASSERT_EQ(HITLS_X509_ExtCtrl(ext, HITLS_X509_EXT_SET_KUSAGE, &ku, sizeof(HITLS_X509_ExtKeyUsage)), 0); ASSERT_EQ(HITLS_X509_ExtCtrl(ext, HITLS_X509_EXT_SET_BCONS, &bCons, sizeof(HITLS_X509_ExtBCons)), 0); return 0; EXIT: return 1; } #endif // HITLS_PKI_X509_CSR_GEN #ifdef HITLS_PKI_X509_CRT_GEN static void FreeListData(void *data) { (void)data; return; } static int32_t SetCertExt(HITLS_X509_Cert *cert) { int32_t ret = 1; uint8_t kid[] = {0x11, 0x22, 0x33, 0x44, 0x55, 0x66, 0x77, 0x88}; HITLS_X509_ExtBCons bCons = {true, true, 1}; HITLS_X509_ExtKeyUsage ku = {true, HITLS_X509_EXT_KU_DIGITAL_SIGN | HITLS_X509_EXT_KU_NON_REPUDIATION}; HITLS_X509_ExtAki aki = {true, {kid, sizeof(kid)}, NULL, {0}}; HITLS_X509_ExtSki ski = {true, {kid, sizeof(kid)}}; HITLS_X509_ExtExKeyUsage exku = {true, NULL}; HITLS_X509_ExtSan san = {true, NULL}; BSL_Buffer oidBuff = {0}; BslOidString *oid = NULL; BslList *oidList = BSL_LIST_New(sizeof(BSL_Buffer)); ASSERT_TRUE(oidList != NULL); oid = BSL_OBJ_GetOID(BSL_CID_KP_SERVERAUTH); ASSERT_NE(oid, NULL); oidBuff.data = (uint8_t *)oid->octs; oidBuff.dataLen = oid->octetLen; ASSERT_EQ(BSL_LIST_AddElement(oidList, &oidBuff, BSL_LIST_POS_END), 0); ASSERT_EQ(HITLS_X509_CertCtrl(cert, HITLS_X509_EXT_SET_BCONS, &bCons, sizeof(HITLS_X509_ExtBCons)), 0); ASSERT_EQ(HITLS_X509_CertCtrl(cert, HITLS_X509_EXT_SET_KUSAGE, &ku, sizeof(HITLS_X509_ExtKeyUsage)), 0); ASSERT_EQ(HITLS_X509_CertCtrl(cert, HITLS_X509_EXT_SET_SKI, &ski, sizeof(HITLS_X509_ExtSki)), 0); ASSERT_EQ(HITLS_X509_CertCtrl(cert, HITLS_X509_EXT_SET_AKI, &aki, sizeof(HITLS_X509_ExtAki)), 0); exku.oidList = oidList; ASSERT_EQ(HITLS_X509_CertCtrl(cert, HITLS_X509_EXT_SET_EXKUSAGE, &exku, sizeof(HITLS_X509_ExtExKeyUsage)), 0); san.names = GenGeneralNameList(); ASSERT_EQ(HITLS_X509_CertCtrl(cert, HITLS_X509_EXT_SET_SAN, &san, sizeof(HITLS_X509_ExtSan)), 0); ret = 0; EXIT: BSL_LIST_FREE(oidList, (BSL_LIST_PFUNC_FREE)FreeListData); BSL_LIST_FREE(san.names, (BSL_LIST_PFUNC_FREE)HITLS_X509_FreeGeneralName); return ret; } #endif // HITLS_PKI_X509_CRT_GEN /* BEGIN_CASE */ void SDV_PKI_GEN_KEY_TC001(int algId, int type, int curveId) { #ifdef HITLS_CRYPTO_KEY_ENCODE if (PkiSkipTest(algId, BSL_FORMAT_ASN1)) { SKIP_TEST(); } char *path = "tmp.key"; TestMemInit(); ASSERT_EQ(TestRandInit(), CRYPT_SUCCESS); ASSERT_EQ(TestEncodeKey(algId, type, curveId, path), CRYPT_SUCCESS); EXIT: TestRandDeInit(); remove(path); #else UnusedParam1(algId, type, curveId); SKIP_TEST(); #endif } /* END_CASE */ /* BEGIN_CASE */ void SDV_PKI_GEN_ENCKEY_TC001(int algId, int curveId, int symId, Hex *pwd) { #if defined(HITLS_CRYPTO_KEY_ENCODE) && defined(HITLS_CRYPTO_KEY_EPKI) if (PkiSkipTest(algId, BSL_FORMAT_ASN1)) { SKIP_TEST(); } CRYPT_Pbkdf2Param param = { .pbesId = BSL_CID_PBES2, .pbkdfId = BSL_CID_PBKDF2, .hmacId = CRYPT_MAC_HMAC_SHA256, .symId = symId, .pwd = pwd->x, .pwdLen = pwd->len, .saltLen = 16, .itCnt = 2000, }; CRYPT_EncodeParam paramEx = {CRYPT_DERIVE_PBKDF2, &param}; CRYPT_EAL_PkeyCtx *pkey = NULL; BSL_Buffer encode = {0}; TestMemInit(); ASSERT_EQ(TestRandInit(), CRYPT_SUCCESS); pkey = GenKey(algId, curveId); ASSERT_NE(pkey, NULL); ASSERT_EQ(CRYPT_EAL_EncodeBuffKey(pkey, &paramEx, BSL_FORMAT_ASN1, CRYPT_PRIKEY_PKCS8_ENCRYPT, &encode), 0); EXIT: TestRandDeInit(); CRYPT_EAL_PkeyFreeCtx(pkey); BSL_SAL_FREE(encode.data); #else (void)algId; (void)curveId; (void)symId; (void)pwd; SKIP_TEST(); #endif } /* END_CASE */ /* BEGIN_CASE */ void SDV_PKI_PARSE_KEY_FILE_TC001(int algId, int format, int type, char *path) { #if defined(HITLS_BSL_SAL_FILE) && defined(HITLS_CRYPTO_KEY_DECODE) if (PkiSkipTest(algId, format)) { SKIP_TEST(); } CRYPT_EAL_PkeyCtx *pkey = NULL; TestMemInit(); ASSERT_EQ(CRYPT_EAL_DecodeFileKey(format, type, path, NULL, 0, &pkey), CRYPT_SUCCESS); ASSERT_NE(pkey, NULL); EXIT: CRYPT_EAL_PkeyFreeCtx(pkey); #else (void)algId; (void)format; (void)type; (void)path; SKIP_TEST(); #endif } /* END_CASE */ /* BEGIN_CASE */ void SDV_PKI_PARSE_ENCKEY_FILE_TC001(int algId, int format, int type, char *path, Hex *pass) { #if defined(HITLS_BSL_SAL_FILE) && defined(HITLS_CRYPTO_KEY_DECODE) && defined(HITLS_CRYPTO_KEY_EPKI) if (PkiSkipTest(algId, format)) { SKIP_TEST(); } CRYPT_EAL_PkeyCtx *pkey = NULL; TestMemInit(); ASSERT_EQ(CRYPT_EAL_DecodeFileKey(format, type, path, pass->x, pass->len, &pkey), CRYPT_SUCCESS); ASSERT_NE(pkey, NULL); EXIT: CRYPT_EAL_PkeyFreeCtx(pkey); #else (void)algId; (void)format; (void)type; (void)path; (void)pass; SKIP_TEST(); #endif } /* END_CASE */ /* BEGIN_CASE */ void SDV_PKI_PARSE_KEY_BUFF_TC001(int algId, int format, int type, Hex *encode) { #ifdef HITLS_CRYPTO_KEY_DECODE if (PkiSkipTest(algId, format)) { SKIP_TEST(); } CRYPT_EAL_PkeyCtx *pkey = NULL; TestMemInit(); ASSERT_EQ(CRYPT_EAL_DecodeBuffKey(format, type, (BSL_Buffer *)encode, NULL, 0, &pkey), CRYPT_SUCCESS); ASSERT_NE(pkey, NULL); EXIT: CRYPT_EAL_PkeyFreeCtx(pkey); #else (void)algId; (void)format; (void)type; (void)encode; SKIP_TEST(); #endif } /* END_CASE */ /* BEGIN_CASE */ void SDV_PKI_GEN_CRL_TC001(int algId, int hashId, int curveId) { #ifdef HITLS_PKI_X509_CRL_GEN if (PkiSkipTest(algId, BSL_FORMAT_ASN1)) { SKIP_TEST(); } char *path = "tmp.crl"; HITLS_X509_Crl *crl = NULL; uint32_t version = 1; BslList *issuer = NULL; BSL_TIME beforeTime = {2025, 1, 1, 0, 0, 0, 0, 0}; BSL_TIME afterTime = {2035, 1, 1, 0, 0, 0, 0, 0}; uint8_t crlNumber[1] = {0x11}; HITLS_X509_SignAlgParam algParam = {0}; CRYPT_RSA_PssPara pssParam = {0}; BSL_Buffer encode = {0}; HITLS_X509_ExtCrlNumber crlNumberExt = {false, {crlNumber, 1}}; ASSERT_EQ(TestRandInit(), CRYPT_SUCCESS); CRYPT_EAL_PkeyCtx *prvKey = GenKey(algId, curveId); ASSERT_NE(prvKey, NULL); crl = HITLS_X509_CrlNew(); ASSERT_NE(crl, NULL); issuer = GenDNList(); ASSERT_NE(issuer, NULL); ASSERT_EQ(HITLS_X509_CrlCtrl(crl, HITLS_X509_SET_ISSUER_DN, issuer, sizeof(BslList)), HITLS_PKI_SUCCESS); ASSERT_EQ(HITLS_X509_CrlCtrl(crl, HITLS_X509_SET_VERSION, &version, sizeof(version)), HITLS_PKI_SUCCESS); ASSERT_EQ(HITLS_X509_CrlCtrl(crl, HITLS_X509_SET_BEFORE_TIME, &beforeTime, sizeof(BSL_TIME)), HITLS_PKI_SUCCESS); ASSERT_EQ(HITLS_X509_CrlCtrl(crl, HITLS_X509_SET_AFTER_TIME, &afterTime, sizeof(BSL_TIME)), HITLS_PKI_SUCCESS); ASSERT_EQ(SetCrlEntry(crl), 0); ASSERT_EQ(HITLS_X509_CrlCtrl(crl, HITLS_X509_EXT_SET_CRLNUMBER, &crlNumberExt, sizeof(HITLS_X509_ExtCrlNumber)), 0); SetSignParam(algId, hashId, &algParam, &pssParam); if (algId == CRYPT_PKEY_RSA) { ASSERT_EQ(HITLS_X509_CrlSign(hashId, prvKey, NULL, crl), HITLS_PKI_SUCCESS); } else { ASSERT_EQ(HITLS_X509_CrlSign(hashId, prvKey, &algParam, crl), HITLS_PKI_SUCCESS); } #ifdef HITLS_BSL_SAL_FILE ASSERT_EQ(HITLS_X509_CrlGenFile(BSL_FORMAT_ASN1, crl, path), HITLS_PKI_SUCCESS); #ifdef HITLS_BSL_PEM ASSERT_EQ(HITLS_X509_CrlGenFile(BSL_FORMAT_PEM, crl, path), HITLS_PKI_SUCCESS); #endif #endif ASSERT_EQ(HITLS_X509_CrlGenBuff(BSL_FORMAT_ASN1, crl, &encode), 0); BSL_SAL_FREE(encode.data); #ifdef HITLS_BSL_PEM ASSERT_EQ(HITLS_X509_CrlGenBuff(BSL_FORMAT_PEM, crl, &encode), 0); BSL_SAL_FREE(encode.data); #endif EXIT: TestRandDeInit(); CRYPT_EAL_PkeyFreeCtx(prvKey); HITLS_X509_CrlFree(crl); HITLS_X509_DnListFree(issuer); remove(path); #else UnusedParam1(algId, hashId, curveId); SKIP_TEST(); #endif } /* END_CASE */ /* BEGIN_CASE */ void SDV_PKI_PARSE_CRL_FILE_TC001(int algId, int format, char *path) { #if defined(HITLS_PKI_X509_CRL_PARSE) && defined(HITLS_BSL_SAL_FILE) if (PkiSkipTest(algId, format)) { SKIP_TEST(); } HITLS_X509_Crl *crl = NULL; TestMemInit(); ASSERT_EQ(HITLS_X509_CrlParseFile(format, path, &crl), HITLS_PKI_SUCCESS); EXIT: HITLS_X509_CrlFree(crl); #else UnusedParam2(algId, format, path); SKIP_TEST(); #endif } /* END_CASE */ /* BEGIN_CASE */ void SDV_PKI_PARSE_CRL_BUFF_TC001(int algId, int format, Hex *encode) { #ifdef HITLS_PKI_X509_CRL_PARSE if (PkiSkipTest(algId, format)) { SKIP_TEST(); } HITLS_X509_Crl *crl = NULL; TestMemInit(); ASSERT_EQ(HITLS_X509_CrlParseBuff(format, (BSL_Buffer *)encode, &crl), HITLS_PKI_SUCCESS); EXIT: HITLS_X509_CrlFree(crl); #else UnusedParam2(algId, format, encode); SKIP_TEST(); #endif } /* END_CASE */ /* BEGIN_CASE */ void SDV_PKI_GEN_CSR_TC001(int algId, int hashId, int curveId) { #ifdef HITLS_PKI_X509_CSR_GEN if (PkiSkipTest(algId, BSL_FORMAT_ASN1)) { SKIP_TEST(); } char *path = "tmp.csr"; HITLS_X509_Csr *csr = NULL; BSL_Buffer encode = {0}; HITLS_X509_DN dnName1[1] = {{BSL_CID_AT_COMMONNAME, (uint8_t *)"OH", 2}}; HITLS_X509_DN dnName2[1] = {{BSL_CID_AT_COUNTRYNAME, (uint8_t *)"CN", 2}}; HITLS_X509_Attrs *attrs = NULL; HITLS_X509_Ext *ext = NULL; HITLS_X509_SignAlgParam algParam = {0}; CRYPT_RSA_PssPara pssParam = {0}; TestMemInit(); ASSERT_EQ(TestRandInit(), CRYPT_SUCCESS); CRYPT_EAL_PkeyCtx *key = GenKey(algId, curveId); ASSERT_NE(key, NULL); csr = HITLS_X509_CsrNew(); ASSERT_NE(csr, NULL); ext = HITLS_X509_ExtNew(HITLS_X509_EXT_TYPE_CSR); ASSERT_NE(ext, NULL); ASSERT_EQ(HITLS_X509_CsrCtrl(csr, HITLS_X509_SET_PUBKEY, key, 0), HITLS_PKI_SUCCESS); ASSERT_EQ(HITLS_X509_CsrCtrl(csr, HITLS_X509_ADD_SUBJECT_NAME, dnName1, 1), HITLS_PKI_SUCCESS); ASSERT_EQ(HITLS_X509_CsrCtrl(csr, HITLS_X509_ADD_SUBJECT_NAME, dnName2, 1), HITLS_PKI_SUCCESS); ASSERT_EQ(HITLS_X509_CsrCtrl(csr, HITLS_X509_CSR_GET_ATTRIBUTES, &attrs, sizeof(HITLS_X509_Attrs *)), 0); ASSERT_EQ(FillExt(ext), 0); ASSERT_EQ(HITLS_X509_AttrCtrl(attrs, HITLS_X509_ATTR_SET_REQUESTED_EXTENSIONS, ext, 0), 0); SetSignParam(algId, hashId, &algParam, &pssParam); if (algId == CRYPT_PKEY_RSA) { ASSERT_EQ(HITLS_X509_CsrSign(hashId, key, NULL, csr), HITLS_PKI_SUCCESS); } else { ASSERT_EQ(HITLS_X509_CsrSign(hashId, key, &algParam, csr), HITLS_PKI_SUCCESS); } #ifdef HITLS_BSL_SAL_FILE ASSERT_EQ(HITLS_X509_CsrGenFile(BSL_FORMAT_ASN1, csr, path), 0); #ifdef HITLS_BSL_PEM ASSERT_EQ(HITLS_X509_CsrGenFile(BSL_FORMAT_PEM, csr, path), 0); #endif #endif ASSERT_EQ(HITLS_X509_CsrGenBuff(BSL_FORMAT_ASN1, csr, &encode), 0); BSL_SAL_FREE(encode.data); #ifdef HITLS_BSL_PEM ASSERT_EQ(HITLS_X509_CsrGenBuff(BSL_FORMAT_PEM, csr, &encode), 0); BSL_SAL_FREE(encode.data); #endif EXIT: TestRandDeInit(); CRYPT_EAL_PkeyFreeCtx(key); HITLS_X509_CsrFree(csr); HITLS_X509_ExtFree(ext); remove(path); #else UnusedParam1(algId, hashId, curveId); SKIP_TEST(); #endif } /* END_CASE */ /* BEGIN_CASE */ void SDV_PKI_PARSE_CSR_FILE_TC001(int algId, int format, char *path) { #if defined(HITLS_PKI_X509_CSR_PARSE) && defined(HITLS_BSL_SAL_FILE) if (PkiSkipTest(algId, format)) { SKIP_TEST(); } HITLS_X509_Csr *csr = NULL; TestMemInit(); ASSERT_EQ(HITLS_X509_CsrParseFile(format, path, &csr), HITLS_PKI_SUCCESS); EXIT: HITLS_X509_CsrFree(csr); #else UnusedParam2(algId, format, path); SKIP_TEST(); #endif } /* END_CASE */ /* BEGIN_CASE */ void SDV_PKI_PARSE_CSR_BUFF_TC001(int algId, int format, Hex *encode) { #if defined(HITLS_PKI_X509_CSR_PARSE) if (PkiSkipTest(algId, format)) { SKIP_TEST(); } HITLS_X509_Csr *csr = NULL; TestMemInit(); ASSERT_EQ(HITLS_X509_CsrParseBuff(format, (BSL_Buffer *)encode, &csr), HITLS_PKI_SUCCESS); EXIT: HITLS_X509_CsrFree(csr); #else UnusedParam2(algId, format, encode); SKIP_TEST(); #endif } /* END_CASE */ /* BEGIN_CASE */ void SDV_PKI_GEN_CERT_TC001(int algId, int hashId, int curveId) { #ifdef HITLS_PKI_X509_CRT_GEN if (PkiSkipTest(algId, BSL_FORMAT_ASN1)) { SKIP_TEST(); } char *path = "tmp.cert"; HITLS_X509_Cert *cert = NULL; uint32_t version = 2; // v3 cert uint8_t serialNum[4] = {0x11, 0x22, 0x33, 0x44}; BSL_TIME beforeTime = {2025, 1, 1, 0, 0, 0, 0, 0}; BSL_TIME afterTime = {2035, 1, 1, 0, 0, 0, 0, 0}; BslList *dnList = NULL; HITLS_X509_SignAlgParam algParam = {0}; CRYPT_RSA_PssPara pssParam = {0}; BSL_Buffer encode = {0}; TestMemInit(); ASSERT_EQ(TestRandInit(), CRYPT_SUCCESS); CRYPT_EAL_PkeyCtx *key = GenKey(algId, curveId); ASSERT_NE(key, NULL); cert = HITLS_X509_CertNew(); ASSERT_NE(cert, NULL); // set cert info ASSERT_EQ(HITLS_X509_CertCtrl(cert, HITLS_X509_SET_VERSION, &version, sizeof(version)), HITLS_PKI_SUCCESS); ASSERT_EQ(HITLS_X509_CertCtrl(cert, HITLS_X509_SET_SERIALNUM, serialNum, sizeof(serialNum)), HITLS_PKI_SUCCESS); ASSERT_EQ(HITLS_X509_CertCtrl(cert, HITLS_X509_SET_BEFORE_TIME, &beforeTime, sizeof(BSL_TIME)), HITLS_PKI_SUCCESS); ASSERT_EQ(HITLS_X509_CertCtrl(cert, HITLS_X509_SET_AFTER_TIME, &afterTime, sizeof(BSL_TIME)), HITLS_PKI_SUCCESS); ASSERT_EQ(HITLS_X509_CertCtrl(cert, HITLS_X509_SET_PUBKEY, key, 0), HITLS_PKI_SUCCESS); dnList = GenDNList(); ASSERT_NE(dnList, NULL); ASSERT_EQ(HITLS_X509_CertCtrl(cert, HITLS_X509_SET_ISSUER_DN, dnList, sizeof(BslList)), HITLS_PKI_SUCCESS); ASSERT_EQ(HITLS_X509_CertCtrl(cert, HITLS_X509_SET_SUBJECT_DN, dnList, sizeof(BslList)), HITLS_PKI_SUCCESS); ASSERT_EQ(SetCertExt(cert), 0); // sign cert SetSignParam(algId, hashId, &algParam, &pssParam); if (algId == CRYPT_PKEY_RSA) { ASSERT_EQ(HITLS_X509_CertSign(hashId, key, NULL, cert), HITLS_PKI_SUCCESS); } else { ASSERT_EQ(HITLS_X509_CertSign(hashId, key, &algParam, cert), HITLS_PKI_SUCCESS); } // generate cert file #ifdef HITLS_BSL_SAL_FILE ASSERT_EQ(HITLS_X509_CertGenFile(BSL_FORMAT_ASN1, cert, path), HITLS_PKI_SUCCESS); #ifdef HITLS_BSL_PEM ASSERT_EQ(HITLS_X509_CertGenFile(BSL_FORMAT_PEM, cert, path), HITLS_PKI_SUCCESS); #endif #endif // generate cert buff ASSERT_EQ(HITLS_X509_CertGenBuff(BSL_FORMAT_ASN1, cert, &encode), 0); BSL_SAL_FREE(encode.data); #ifdef HITLS_BSL_PEM ASSERT_EQ(HITLS_X509_CertGenBuff(BSL_FORMAT_PEM, cert, &encode), 0); BSL_SAL_FREE(encode.data); #endif EXIT: TestRandDeInit(); CRYPT_EAL_PkeyFreeCtx(key); HITLS_X509_CertFree(cert); HITLS_X509_DnListFree(dnList); remove(path); #else UnusedParam1(algId, hashId, curveId); SKIP_TEST(); #endif } /* END_CASE */ /* BEGIN_CASE */ void SDV_PKI_PARSE_CERT_FILE_TC001(int algId, int format, char *path) { #if defined(HITLS_PKI_X509_CRT_PARSE) && defined(HITLS_BSL_SAL_FILE) if (PkiSkipTest(algId, format)) { SKIP_TEST(); } HITLS_X509_Cert *cert = NULL; TestMemInit(); ASSERT_EQ(HITLS_X509_CertParseFile(format, path, &cert), HITLS_PKI_SUCCESS); EXIT: HITLS_X509_CertFree(cert); #else UnusedParam2(algId, format, path); SKIP_TEST(); #endif } /* END_CASE */ /* BEGIN_CASE */ void SDV_PKI_PARSE_CERT_BUFF_TC001(int algId, int format, Hex *encode) { #ifdef HITLS_PKI_X509_CRT_PARSE if (PkiSkipTest(algId, format)) { SKIP_TEST(); } HITLS_X509_Cert *cert = NULL; TestMemInit(); ASSERT_EQ(HITLS_X509_CertParseBuff(format, (BSL_Buffer *)encode, &cert), HITLS_PKI_SUCCESS); EXIT: HITLS_X509_CertFree(cert); #else UnusedParam2(algId, format, encode); SKIP_TEST(); #endif } /* END_CASE */
2301_79861745/bench_create
testcode/sdv/testcase/pki/common/test_suite_sdv_x509.c
C
unknown
25,953
/* * This file is part of the openHiTLS project. * * openHiTLS is licensed under the Mulan PSL v2. * You can use this software according to the terms and conditions of the Mulan PSL v2. * You may obtain a copy of Mulan PSL v2 at: * * http://license.coscl.org.cn/MulanPSL2 * * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, * EITHER EXPRESS 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 "bsl_sal.h" #include "securec.h" #include "hitls_pki_crl.h" #include "hitls_pki_cert.h" #include "hitls_pki_errno.h" #include "bsl_types.h" #include "bsl_log.h" #include "bsl_obj.h" #include "crypt_encode_decode_key.h" #include "sal_file.h" #include "bsl_init.h" #include "crypt_errno.h" #include "hitls_crl_local.h" #include "hitls_cert_local.h" #include "stub_replace.h" #include "hitls_pki_utils.h" static char g_sm2DefaultUserid[] = "1234567812345678"; /* END_HEADER */ /* BEGIN_CASE */ void SDV_X509_CRL_PARSE_FUNC_TC001(int format, char *path) { TestMemInit(); BSL_GLOBAL_Init(); HITLS_X509_Crl *crl = NULL; ASSERT_EQ(HITLS_X509_CrlParseFile((int32_t)format, path, &crl), HITLS_PKI_SUCCESS); EXIT: HITLS_X509_CrlFree(crl); BSL_GLOBAL_DeInit(); } /* END_CASE */ /* BEGIN_CASE */ void SDV_X509_CRL_CTRL_FUNC_TC001(char *path) { HITLS_X509_Crl *crl = NULL; ASSERT_EQ(HITLS_X509_CrlParseFile(BSL_FORMAT_ASN1, path, &crl), HITLS_PKI_SUCCESS); int32_t ref = 0; ASSERT_EQ(HITLS_X509_CrlCtrl(crl, HITLS_X509_REF_UP, &ref, sizeof(ref)), HITLS_PKI_SUCCESS); ASSERT_EQ(ref, 2); HITLS_X509_CrlFree(crl); EXIT: HITLS_X509_CrlFree(crl); } /* END_CASE */ /* BEGIN_CASE */ void SDV_X509_CRL_PARSE_VERSION_FUNC_TC001(char *path, int version) { HITLS_X509_Crl *crl = NULL; ASSERT_EQ(HITLS_X509_CrlParseFile(BSL_FORMAT_ASN1, path, &crl), HITLS_PKI_SUCCESS); ASSERT_EQ(crl->tbs.version, version); EXIT: HITLS_X509_CrlFree(crl); } /* END_CASE */ /* BEGIN_CASE */ void SDV_X509_CRL_PARSE_TBS_SIGNALG_FUNC_TC001(char *path, int signAlg, int rsaPssHash, int rsaPssMgf1, int rsaPssSaltLen) { HITLS_X509_Crl *crl = NULL; ASSERT_EQ(HITLS_X509_CrlParseFile(BSL_FORMAT_ASN1, path, &crl), HITLS_PKI_SUCCESS); ASSERT_EQ(crl->tbs.signAlgId.algId, signAlg); ASSERT_EQ(crl->tbs.signAlgId.rsaPssParam.mdId, rsaPssHash); ASSERT_EQ(crl->tbs.signAlgId.rsaPssParam.mgfId, rsaPssMgf1); ASSERT_EQ(crl->tbs.signAlgId.rsaPssParam.saltLen, rsaPssSaltLen); EXIT: HITLS_X509_CrlFree(crl); } /* END_CASE */ /* BEGIN_CASE */ void SDV_X509_CRL_PARSE_ISSUERNAME_FUNC_TC001(char *path, int count, Hex *type1, int tag1, Hex *value1, Hex *type2, int tag2, Hex *value2, Hex *type3, int tag3, Hex *value3, Hex *type4, int tag4, Hex *value4, Hex *type5, int tag5, Hex *value5) { HITLS_X509_Crl *crl = NULL; ASSERT_EQ(HITLS_X509_CrlParseFile(BSL_FORMAT_ASN1, path, &crl), HITLS_PKI_SUCCESS); BSL_ASN1_Buffer expAsan1Arr[] = { {6, type1->len, type1->x}, {(uint8_t)tag1, value1->len, value1->x}, {6, type2->len, type2->x}, {(uint8_t)tag2, value2->len, value2->x}, {6, type3->len, type3->x}, {(uint8_t)tag3, value3->len, value3->x}, {6, type4->len, type4->x}, {(uint8_t)tag4, value4->len, value4->x}, {6, type5->len, type5->x}, {(uint8_t)tag5, value5->len, value5->x}, }; ASSERT_EQ(BSL_LIST_COUNT(crl->tbs.issuerName), count); HITLS_X509_NameNode **nameNode = NULL; nameNode = BSL_LIST_First(crl->tbs.issuerName); for (int i = 0; i < count; i += 2) { // Iteration with step=2 ASSERT_NE((*nameNode), NULL); ASSERT_EQ((*nameNode)->layer, 1); ASSERT_EQ((*nameNode)->nameType.tag, 0); ASSERT_EQ((*nameNode)->nameType.buff, NULL); ASSERT_EQ((*nameNode)->nameType.len, 0); ASSERT_EQ((*nameNode)->nameValue.tag, 0); ASSERT_EQ((*nameNode)->nameValue.buff, NULL); ASSERT_EQ((*nameNode)->nameValue.len, 0); nameNode = BSL_LIST_Next(crl->tbs.issuerName); ASSERT_NE((*nameNode), NULL); ASSERT_EQ((*nameNode)->layer, 2); ASSERT_EQ((*nameNode)->nameType.tag, expAsan1Arr[i].tag); ASSERT_COMPARE("nameType", (*nameNode)->nameType.buff, (*nameNode)->nameType.len, expAsan1Arr[i].buff, expAsan1Arr[i].len); ASSERT_EQ((*nameNode)->nameValue.tag, expAsan1Arr[i + 1].tag); ASSERT_COMPARE("nameVlaue", (*nameNode)->nameValue.buff, (*nameNode)->nameValue.len, expAsan1Arr[i + 1].buff, expAsan1Arr[i + 1].len); nameNode = BSL_LIST_Next(crl->tbs.issuerName); } EXIT: HITLS_X509_CrlFree(crl); } /* END_CASE */ /* BEGIN_CASE */ void SDV_X509_CRL_PARSE_REVOKED_FUNC_TC001(char *path) { HITLS_X509_Crl *crl = NULL; ASSERT_EQ(HITLS_X509_CrlParseFile(BSL_FORMAT_ASN1, path, &crl), BSL_SAL_ERR_FILE_LENGTH); EXIT: HITLS_X509_CrlFree(crl); } /* END_CASE */ /* BEGIN_CASE */ void SDV_X509_CRL_PARSE_REVOKED_FUNC_TC003(char *path, int count, int num, int tag1, Hex *value1, int year1, int month1, int day1, int hour1, int minute1, int second1) { HITLS_X509_Crl *crl = NULL; ASSERT_EQ(HITLS_X509_CrlParseFile(BSL_FORMAT_ASN1, path, &crl), HITLS_PKI_SUCCESS); ASSERT_EQ(BSL_LIST_COUNT(crl->tbs.revokedCerts), count); HITLS_X509_CrlEntry *nameNode = NULL; nameNode = BSL_LIST_GET_FIRST(crl->tbs.revokedCerts); for (int i = 1; i < num; i++) { nameNode = BSL_LIST_GET_NEXT(crl->tbs.revokedCerts); } ASSERT_EQ(nameNode->serialNumber.tag, tag1); ASSERT_COMPARE("", nameNode->serialNumber.buff, nameNode->serialNumber.len, value1->x, value1->len); ASSERT_EQ(nameNode->time.year, year1); ASSERT_EQ(nameNode->time.month, month1); ASSERT_EQ(nameNode->time.day, day1); ASSERT_EQ(nameNode->time.hour, hour1); ASSERT_EQ(nameNode->time.minute, minute1); ASSERT_EQ(nameNode->time.second, second1); EXIT: HITLS_X509_CrlFree(crl); } /* END_CASE */ /* BEGIN_CASE */ void SDV_X509_CRL_PARSE_TIME_FUNC_TC001(char *path) { HITLS_X509_Crl *crl = NULL; ASSERT_EQ(HITLS_X509_CrlParseFile(BSL_FORMAT_ASN1, path, &crl), HITLS_X509_ERR_CHECK_TAG); EXIT: HITLS_X509_CrlFree(crl); } /* END_CASE */ /* BEGIN_CASE */ void SDV_X509_CRL_PARSE_START_TIME_FUNC_TC001(char *path, int year, int month, int day, int hour, int minute, int second) { HITLS_X509_Crl *crl = NULL; ASSERT_EQ(HITLS_X509_CrlParseFile(BSL_FORMAT_ASN1, path, &crl), HITLS_PKI_SUCCESS); ASSERT_EQ(crl->tbs.validTime.start.year, year); ASSERT_EQ(crl->tbs.validTime.start.month, month); ASSERT_EQ(crl->tbs.validTime.start.day, day); ASSERT_EQ(crl->tbs.validTime.start.hour, hour); ASSERT_EQ(crl->tbs.validTime.start.minute, minute); ASSERT_EQ(crl->tbs.validTime.start.second, second); EXIT: HITLS_X509_CrlFree(crl); } /* END_CASE */ /* BEGIN_CASE */ void SDV_X509_CRL_PARSE_END_TIME_FUNC_TC001(char *path, int year, int month, int day, int hour, int minute, int second) { HITLS_X509_Crl *crl = NULL; ASSERT_EQ(HITLS_X509_CrlParseFile(BSL_FORMAT_ASN1, path, &crl), HITLS_PKI_SUCCESS); ASSERT_EQ(crl->tbs.validTime.end.year, year); ASSERT_EQ(crl->tbs.validTime.end.month, month); ASSERT_EQ(crl->tbs.validTime.end.day, day); ASSERT_EQ(crl->tbs.validTime.end.hour, hour); ASSERT_EQ(crl->tbs.validTime.end.minute, minute); ASSERT_EQ(crl->tbs.validTime.end.second, second); EXIT: HITLS_X509_CrlFree(crl); } /* END_CASE */ /* BEGIN_CASE */ void SDV_X509_CRL_PARSE_EXTENSIONS_FUNC_TC001(char *path, int tag1, Hex *value1, int tag2, Hex *value2) { HITLS_X509_Crl *crl = NULL; ASSERT_EQ(HITLS_X509_CrlParseFile(BSL_FORMAT_ASN1, path, &crl), HITLS_PKI_SUCCESS); ASSERT_EQ(BSL_LIST_COUNT(crl->tbs.crlExt.extList), 1); HITLS_X509_ExtEntry **nameNode = NULL; nameNode = BSL_LIST_First(crl->tbs.crlExt.extList); ASSERT_NE((*nameNode), NULL); ASSERT_EQ((*nameNode)->critical, 0); ASSERT_EQ((*nameNode)->extnId.tag, tag1); ASSERT_COMPARE("extnId", (*nameNode)->extnId.buff, (*nameNode)->extnId.len, value1->x, value1->len); ASSERT_EQ((*nameNode)->extnValue.tag, tag2); ASSERT_COMPARE("extnValue", (*nameNode)->extnValue.buff, (*nameNode)->extnValue.len, value2->x, value2->len); EXIT: HITLS_X509_CrlFree(crl); BSL_GLOBAL_DeInit(); } /* END_CASE */ /* BEGIN_CASE */ void SDV_X509_CRL_PARSE_SIGNALG_FUNC_TC001(char *path, int signAlg, int rsaPssHash, int rsaPssMgf1, int rsaPssSaltLen) { HITLS_X509_Crl *crl = NULL; ASSERT_EQ(HITLS_X509_CrlParseFile(BSL_FORMAT_ASN1, path, &crl), HITLS_PKI_SUCCESS); ASSERT_EQ(crl->signAlgId.algId, signAlg); ASSERT_EQ(crl->signAlgId.rsaPssParam.mdId, rsaPssHash); ASSERT_EQ(crl->signAlgId.rsaPssParam.mgfId, rsaPssMgf1); ASSERT_EQ(crl->signAlgId.rsaPssParam.saltLen, rsaPssSaltLen); EXIT: HITLS_X509_CrlFree(crl); } /* END_CASE */ /* BEGIN_CASE */ void SDV_X509_CRL_PARSE_SIGNATURE_FUNC_TC001(char *path, Hex *buff, int unusedBits) { HITLS_X509_Crl *crl = NULL; ASSERT_EQ(HITLS_X509_CrlParseFile(BSL_FORMAT_ASN1, path, &crl), HITLS_PKI_SUCCESS); ASSERT_EQ(crl->signature.len, buff->len); ASSERT_COMPARE("signature", crl->signature.buff, crl->signature.len, buff->x, buff->len); ASSERT_EQ(crl->signature.unusedBits, unusedBits); EXIT: HITLS_X509_CrlFree(crl); } /* END_CASE */ /* BEGIN_CASE */ void SDV_X509_MUL_CRL_PARSE_FUNC_TC001(int format, char *path, int crlNum) { BSL_GLOBAL_Init(); HITLS_X509_List *list = NULL; int32_t ret = HITLS_X509_CrlParseBundleFile(format, path, &list); ASSERT_EQ(ret, HITLS_PKI_SUCCESS); ASSERT_EQ(BSL_LIST_COUNT(list), crlNum); EXIT: BSL_LIST_FREE(list, (BSL_LIST_PFUNC_FREE)HITLS_X509_CrlFree); } /* END_CASE */ /* BEGIN_CASE */ void SDV_X509_CRL_Encode_TC001(int format, char *path) { BSL_GLOBAL_Init(); HITLS_X509_Crl *crl = NULL; BSL_Buffer encode = {0}; uint8_t *data = NULL; uint32_t dataLen = 0; int32_t ret = BSL_SAL_ReadFile(path, &data, &dataLen); ASSERT_EQ(ret, BSL_SUCCESS); BSL_Buffer ori = {data, dataLen}; ret = HITLS_X509_CrlParseBuff(format, &ori, &crl); ASSERT_EQ(ret, HITLS_PKI_SUCCESS); ret = HITLS_X509_CrlGenBuff(format, crl, &encode); ASSERT_EQ(ret, HITLS_PKI_SUCCESS); if (format == BSL_FORMAT_ASN1) { ASSERT_EQ(dataLen, encode.dataLen); } else { ASSERT_EQ(dataLen, strlen((char *)encode.data)); } ASSERT_EQ(memcmp(encode.data, data, dataLen), 0); EXIT: BSL_SAL_Free(data); HITLS_X509_CrlFree(crl); BSL_SAL_Free(encode.data); } /* END_CASE */ /* BEGIN_CASE */ void SDV_X509_CRL_EncodeParam_TC001(void) { BSL_GLOBAL_Init(); HITLS_X509_Crl *crl = NULL; BSL_Buffer encode = {0}; uint8_t *data = NULL; uint32_t dataLen = 0; ASSERT_EQ(BSL_SAL_ReadFile("../testdata/cert/pem/crl/crl_v2.pem", &data, &dataLen), BSL_SUCCESS); BSL_Buffer ori = {data, dataLen}; ASSERT_EQ(HITLS_X509_CrlParseBuff(BSL_FORMAT_PEM, &ori, &crl), HITLS_PKI_SUCCESS); ASSERT_EQ(HITLS_X509_CrlGenBuff(BSL_FORMAT_ASN1, NULL, &encode), HITLS_X509_ERR_INVALID_PARAM); ASSERT_EQ(HITLS_X509_CrlGenBuff(BSL_FORMAT_ASN1, crl, NULL), HITLS_X509_ERR_INVALID_PARAM); ASSERT_EQ(HITLS_X509_CrlGenBuff(BSL_FORMAT_UNKNOWN, crl, &encode), HITLS_X509_ERR_INVALID_PARAM); ASSERT_EQ(HITLS_X509_CrlGenBuff(BSL_FORMAT_ASN1, crl, &encode), 0); EXIT: BSL_SAL_Free(data); HITLS_X509_CrlFree(crl); BSL_SAL_Free(encode.data); } /* END_CASE */ /* BEGIN_CASE */ void SDV_X509_CRL_EncodeFile_TC001(int format, char *path) { BSL_GLOBAL_Init(); HITLS_X509_Crl *crl = NULL; uint8_t *data = NULL; uint32_t dataLen = 0; uint8_t *res = NULL; uint32_t resLen; int32_t ret = BSL_SAL_ReadFile(path, &data, &dataLen); ASSERT_EQ(ret, BSL_SUCCESS); BSL_Buffer ori = {data, dataLen}; ret = HITLS_X509_CrlParseBuff(format, &ori, &crl); ASSERT_EQ(ret, HITLS_PKI_SUCCESS); ret = HITLS_X509_CrlGenFile(format, crl, "res.crl"); ASSERT_EQ(ret, HITLS_PKI_SUCCESS); ASSERT_EQ(BSL_SAL_ReadFile("res.crl", &res, &resLen), BSL_SUCCESS); ASSERT_COMPARE("crl_file com", data, dataLen, res, resLen); EXIT: BSL_SAL_Free(data); HITLS_X509_CrlFree(crl); BSL_SAL_Free(res); } /* END_CASE */ /* BEGIN_CASE */ void SDV_X509_CRL_Check_TC001(char *capath, char *crlpath, int res) { BSL_GLOBAL_Init(); HITLS_X509_Crl *crl = NULL; HITLS_X509_Cert *cert = NULL; void *pubKey = NULL; ASSERT_EQ(HITLS_X509_CrlParseFile(BSL_FORMAT_UNKNOWN, crlpath, &crl), HITLS_PKI_SUCCESS); ASSERT_EQ(HITLS_X509_CertParseFile(BSL_FORMAT_UNKNOWN, capath, &cert), HITLS_PKI_SUCCESS); ASSERT_EQ(HITLS_X509_CertCtrl(cert, HITLS_X509_GET_PUBKEY, &pubKey, sizeof(void *)), HITLS_PKI_SUCCESS); ASSERT_EQ(HITLS_X509_CrlVerify(pubKey, crl), res); EXIT: CRYPT_EAL_PkeyFreeCtx(pubKey); HITLS_X509_CrlFree(crl); HITLS_X509_CertFree(cert); } /* END_CASE */ /* BEGIN_CASE */ void SDV_X509_CRL_CTRL_ParamCheck_TC001(void) { HITLS_X509_Crl *crl = NULL; BSL_TIME time = {0}; BSL_ASN1_List *issuer = NULL; uint32_t version = 1; // Test null pointer parameter ASSERT_EQ(HITLS_X509_CrlCtrl(NULL, HITLS_X509_SET_VERSION, &version, sizeof(version)), HITLS_X509_ERR_INVALID_PARAM); // Create a CRL object for subsequent tests crl = HITLS_X509_CrlNew(); ASSERT_NE(crl, NULL); // Test invalid command ASSERT_EQ(HITLS_X509_CrlCtrl(crl, 0x7FFFFFFF, &version, sizeof(version)), HITLS_X509_ERR_INVALID_PARAM); // Test null value pointer ASSERT_EQ(HITLS_X509_CrlCtrl(crl, HITLS_X509_SET_VERSION, NULL, sizeof(uint8_t)), HITLS_X509_ERR_INVALID_PARAM); // Test incorrect length for version parameter ASSERT_EQ(HITLS_X509_CrlCtrl(crl, HITLS_X509_SET_VERSION, &version, 0), HITLS_X509_ERR_INVALID_PARAM); // Test invalid version number version = 3; // Out of valid range ASSERT_EQ(HITLS_X509_CrlCtrl(crl, HITLS_X509_SET_VERSION, &version, sizeof(version)), HITLS_X509_ERR_INVALID_PARAM); // Test incorrect length for time parameter ASSERT_EQ(HITLS_X509_CrlCtrl(crl, HITLS_X509_SET_BEFORE_TIME, &time, sizeof(time) - 1), HITLS_X509_ERR_INVALID_PARAM); // Test incorrect length for issuer parameter ASSERT_EQ(HITLS_X509_CrlCtrl(crl, HITLS_X509_SET_ISSUER_DN, issuer, sizeof(BSL_ASN1_List) - 1), HITLS_X509_ERR_INVALID_PARAM); // Test empty buffer for get command ASSERT_EQ(HITLS_X509_CrlCtrl(crl, HITLS_X509_GET_VERSION, NULL, sizeof(version)), HITLS_X509_ERR_INVALID_PARAM); // Test incorrect buffer length for get command ASSERT_EQ(HITLS_X509_CrlCtrl(crl, HITLS_X509_GET_VERSION, &version, 0), HITLS_X509_ERR_INVALID_PARAM); // Test normal parameters - set version number version = 1; ASSERT_EQ(HITLS_X509_CrlCtrl(crl, HITLS_X509_SET_VERSION, &version, sizeof(version)), HITLS_PKI_SUCCESS); // Test normal parameters - get version number uint32_t getVersion = 0; ASSERT_EQ(HITLS_X509_CrlCtrl(crl, HITLS_X509_GET_VERSION, &getVersion, sizeof(getVersion)), HITLS_PKI_SUCCESS); ASSERT_EQ(getVersion, version); // Test normal parameters - set last update time ASSERT_EQ(BSL_SAL_SysTimeGet(&time), BSL_SUCCESS); ASSERT_EQ(HITLS_X509_CrlCtrl(crl, HITLS_X509_SET_BEFORE_TIME, &time, sizeof(time)), HITLS_PKI_SUCCESS); // Test normal parameters - get last update time BSL_TIME getTime = {0}; ASSERT_EQ(HITLS_X509_CrlCtrl(crl, HITLS_X509_GET_BEFORE_TIME, &getTime, sizeof(getTime)), HITLS_PKI_SUCCESS); ASSERT_EQ(memcmp(&getTime, &time, sizeof(BSL_TIME)), 0); EXIT: // Clean up resources HITLS_X509_CrlFree(crl); } /* END_CASE */ /* BEGIN_CASE */ void SDV_X509_CRL_CTRL_RevokedParamCheck_TC001(void) { HITLS_X509_CrlEntry *entry = NULL; BSL_TIME time = {0}; // Test HITLS_X509_CrlEntryNew entry = HITLS_X509_CrlEntryNew(); ASSERT_NE(entry, NULL); // Test HITLS_X509_CrlEntryCtrl with invalid command ASSERT_EQ(HITLS_X509_CrlEntryCtrl(entry, 0xFFFF, &time, sizeof(time)), HITLS_X509_ERR_INVALID_PARAM); // Test HITLS_X509_CrlEntryCtrl with NULL entry ASSERT_EQ(HITLS_X509_CrlEntryCtrl(NULL, HITLS_X509_CRL_GET_REVOKED_REVOKE_TIME, &time, sizeof(time)), HITLS_X509_ERR_INVALID_PARAM); // Test HITLS_X509_CrlEntryCtrl with NULL value pointer ASSERT_EQ(HITLS_X509_CrlEntryCtrl(entry, HITLS_X509_CRL_GET_REVOKED_REVOKE_TIME, NULL, sizeof(time)), HITLS_X509_ERR_INVALID_PARAM); // Test HITLS_X509_CrlEntryCtrl with invalid value length ASSERT_EQ(HITLS_X509_CrlEntryCtrl(entry, HITLS_X509_CRL_GET_REVOKED_REVOKE_TIME, &time, 0), HITLS_X509_ERR_INVALID_PARAM); // Test setting/getting revoke time ASSERT_EQ(BSL_SAL_SysTimeGet(&time), BSL_SUCCESS); ASSERT_EQ(HITLS_X509_CrlEntryCtrl(entry, HITLS_X509_CRL_SET_REVOKED_REVOKE_TIME, &time, sizeof(time)), HITLS_PKI_SUCCESS); BSL_TIME getTime = {0}; ASSERT_EQ(HITLS_X509_CrlEntryCtrl(entry, HITLS_X509_CRL_GET_REVOKED_REVOKE_TIME, &getTime, sizeof(getTime)), HITLS_PKI_SUCCESS); ASSERT_EQ(memcmp(&time, &getTime, sizeof(BSL_TIME)), 0); // Test setting/getting reason HITLS_X509_RevokeExtReason reasonExt = {false, 1}; ASSERT_EQ(HITLS_X509_CrlEntryCtrl(entry, HITLS_X509_CRL_SET_REVOKED_REASON, &reasonExt, sizeof(HITLS_X509_RevokeExtReason)), HITLS_PKI_SUCCESS); int32_t getReason = 0; ASSERT_EQ(HITLS_X509_CrlEntryCtrl(entry, HITLS_X509_CRL_GET_REVOKED_REASON, &getReason, sizeof(getReason)), HITLS_PKI_SUCCESS); ASSERT_EQ(reasonExt.reason, getReason); // Test setting/getting serial number uint8_t serial[] = {0x01, 0x02, 0x03, 0x04}; ASSERT_EQ(HITLS_X509_CrlEntryCtrl(entry, HITLS_X509_CRL_SET_REVOKED_SERIALNUM, serial, 4), HITLS_PKI_SUCCESS); BSL_Buffer getSerial = {0}; ASSERT_EQ(HITLS_X509_CrlEntryCtrl(entry, HITLS_X509_CRL_GET_REVOKED_SERIALNUM, &getSerial, sizeof(getSerial)), HITLS_PKI_SUCCESS); ASSERT_EQ(4, getSerial.dataLen); ASSERT_EQ(memcmp(serial, getSerial.data, getSerial.dataLen), 0); // Test HITLS_X509_CrlEntryFree with NULL HITLS_X509_CrlEntryFree(NULL); // Should not crash // Test HITLS_X509_CrlEntryFree with valid entry HITLS_X509_CrlEntryFree(entry); EXIT: return; } /* END_CASE */ /* BEGIN_CASE */ void SDV_X509_CRL_PARSE_REVOKEDLIST_FUNC_TC001(char *parh, int revokedNum) { HITLS_X509_Crl *crl = NULL; HITLS_X509_CrlEntry *entry = NULL; BslList *revokeList = NULL; BSL_TIME time = {0}; int32_t reason = 0; BSL_Buffer serialNum = {0}; ASSERT_EQ(HITLS_X509_CrlParseFile(BSL_FORMAT_PEM, parh, &crl), HITLS_PKI_SUCCESS); ASSERT_NE(crl, NULL); ASSERT_EQ(HITLS_X509_CrlCtrl(crl, HITLS_X509_GET_REVOKELIST, &revokeList, sizeof(BslList *)), HITLS_PKI_SUCCESS); ASSERT_NE(revokeList, NULL); ASSERT_EQ(BSL_LIST_COUNT(revokeList), revokedNum); for (entry = (HITLS_X509_CrlEntry *)BSL_LIST_GET_FIRST(revokeList); entry != NULL; entry = (HITLS_X509_CrlEntry *)BSL_LIST_GET_NEXT(revokeList)) { ASSERT_TRUE(entry->serialNumber.buff != NULL); ASSERT_EQ(HITLS_X509_CrlEntryCtrl(entry, HITLS_X509_CRL_GET_REVOKED_SERIALNUM, &serialNum, sizeof(BSL_Buffer)), HITLS_PKI_SUCCESS); ASSERT_TRUE(serialNum.dataLen > 0 && serialNum.dataLen <= 20); ASSERT_NE(serialNum.data, NULL); ASSERT_EQ(HITLS_X509_CrlEntryCtrl(entry, HITLS_X509_CRL_GET_REVOKED_REVOKE_TIME, &time, sizeof(BSL_TIME)), HITLS_PKI_SUCCESS); ASSERT_NE(time.year, 0); ASSERT_EQ(HITLS_X509_CrlEntryCtrl(entry, HITLS_X509_CRL_GET_REVOKED_REASON, &reason, sizeof(int32_t)), HITLS_PKI_SUCCESS); ASSERT_TRUE(reason >= 0 && reason <= 11); reason = 0; memset(&time, 0, sizeof(BSL_TIME)); memset(&serialNum, 0, sizeof(serialNum)); } EXIT: HITLS_X509_CrlFree(crl); } /* END_CASE */ /* BEGIN_CASE */ void SDV_X509_CRL_CTRL_GetFunc_TC001(void) { HITLS_X509_Crl *crl = NULL; uint32_t version = 0; BSL_TIME beforeTime = {0}; BSL_TIME afterTime = {0}; BslList *issuerDN = NULL; BslList *revokeList = NULL; // Parse the test CRL file ASSERT_EQ(HITLS_X509_CrlParseFile(BSL_FORMAT_PEM, "../testdata/cert/pem/crl/crl_v2.mul3.crl", &crl), HITLS_PKI_SUCCESS); ASSERT_NE(crl, NULL); // Test getting the version number ASSERT_EQ(HITLS_X509_CrlCtrl(crl, HITLS_X509_GET_VERSION, &version, sizeof(uint32_t)), HITLS_PKI_SUCCESS); // The CRL version should be 0 (v1) or 1 (v2) ASSERT_TRUE(version == 1); // Test getting the last update time ASSERT_EQ(HITLS_X509_CrlCtrl(crl, HITLS_X509_GET_BEFORE_TIME, &beforeTime, sizeof(BSL_TIME)), HITLS_PKI_SUCCESS); ASSERT_NE(beforeTime.year, 0); // Test getting the next update time ASSERT_EQ(HITLS_X509_CrlCtrl(crl, HITLS_X509_GET_AFTER_TIME, &afterTime, sizeof(BSL_TIME)), HITLS_PKI_SUCCESS); // The next update time should be later than the last update time ASSERT_TRUE(afterTime.month > beforeTime.month); // Test getting the issuer DN name ASSERT_EQ(HITLS_X509_CrlCtrl(crl, HITLS_X509_GET_ISSUER_DN, &issuerDN, sizeof(BslList *)), HITLS_PKI_SUCCESS); ASSERT_NE(issuerDN, NULL); ASSERT_NE(BSL_LIST_COUNT(issuerDN), 0); // Test getting extensions (using CRL Number as an example) ASSERT_NE(crl->tbs.crlExt.extList, NULL); ASSERT_EQ(crl->tbs.crlExt.type, HITLS_X509_EXT_TYPE_CRL); ASSERT_EQ(BSL_LIST_COUNT(crl->tbs.crlExt.extList), 1); // Test getting the revoke list ASSERT_EQ(HITLS_X509_CrlCtrl(crl, HITLS_X509_GET_REVOKELIST, &revokeList, sizeof(BslList *)), HITLS_PKI_SUCCESS); ASSERT_NE(revokeList, NULL); ASSERT_EQ(BSL_LIST_COUNT(revokeList), 3); EXIT: HITLS_X509_CrlFree(crl); } /* END_CASE */ /* BEGIN_CASE */ void SDV_X509_CRL_ExtCtrl_FuncTest_TC001(void) { uint8_t keyId[8] = {0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08}; uint8_t serialNum[4] = {0x11, 0x22, 0x33, 0x44}; HITLS_X509_Crl *crl = HITLS_X509_CrlNew(); ASSERT_NE(crl, NULL); // set CRL Number HITLS_X509_ExtCrlNumber crlNumberExt = {false, {serialNum, 4}}; ASSERT_EQ(HITLS_X509_CrlCtrl(crl, HITLS_X509_EXT_SET_CRLNUMBER, &crlNumberExt, sizeof(HITLS_X509_ExtCrlNumber)), HITLS_PKI_SUCCESS); HITLS_X509_ExtCrlNumber crlNumExt = {0}; ASSERT_EQ(HITLS_X509_CrlCtrl(crl, HITLS_X509_EXT_GET_CRLNUMBER, &crlNumExt, sizeof(HITLS_X509_ExtCrlNumber)), HITLS_PKI_SUCCESS); ASSERT_EQ(crlNumExt.critical, crlNumberExt.critical); ASSERT_EQ(crlNumExt.crlNumber.dataLen, crlNumberExt.crlNumber.dataLen); ASSERT_EQ(memcmp(crlNumExt.crlNumber.data, crlNumberExt.crlNumber.data, crlNumberExt.crlNumber.dataLen), 0); HITLS_X509_ExtAki aki = {false, {keyId, sizeof(keyId)}, NULL, {NULL, 0}}; ASSERT_EQ(HITLS_X509_CrlCtrl(crl, HITLS_X509_EXT_SET_AKI, &aki, sizeof(HITLS_X509_ExtAki)), HITLS_PKI_SUCCESS); HITLS_X509_ExtAki getaki = {0}; ASSERT_EQ(HITLS_X509_CrlCtrl(crl, HITLS_X509_EXT_GET_AKI, &getaki, sizeof(HITLS_X509_ExtAki)), HITLS_PKI_SUCCESS); ASSERT_EQ(getaki.critical, aki.critical); ASSERT_EQ(getaki.kid.dataLen, aki.kid.dataLen); ASSERT_EQ(memcmp(getaki.kid.data, aki.kid.data, aki.kid.dataLen), 0); EXIT: HITLS_X509_CrlFree(crl); } /* END_CASE */ /* BEGIN_CASE */ void SDV_X509_CRL_CTRL_SetFunc_TC001(char *capath) { uint8_t serialNum[4] = {0x11, 0x22, 0x33, 0x44}; BSL_TIME beforeTime = {0}; BSL_TIME afterTime = {0}; HITLS_X509_Cert *cert = NULL; HITLS_X509_Crl *crl = HITLS_X509_CrlNew(); ASSERT_EQ(HITLS_X509_CertParseFile(BSL_FORMAT_UNKNOWN, capath, &cert), HITLS_PKI_SUCCESS); ASSERT_NE(crl, NULL); uint32_t version = 1; ASSERT_EQ(HITLS_X509_CrlCtrl(crl, HITLS_X509_SET_VERSION, &version, sizeof(uint32_t)), HITLS_PKI_SUCCESS); BslList *issuerDN = NULL; ASSERT_EQ(HITLS_X509_CertCtrl(cert, HITLS_X509_GET_ISSUER_DN, &issuerDN, sizeof(BslList *)), HITLS_PKI_SUCCESS); ASSERT_NE(issuerDN, NULL); ASSERT_EQ(HITLS_X509_CrlCtrl(crl, HITLS_X509_SET_ISSUER_DN, issuerDN, sizeof(BslList)), HITLS_PKI_SUCCESS); ASSERT_EQ(BSL_SAL_SysTimeGet(&beforeTime), BSL_SUCCESS); ASSERT_EQ(HITLS_X509_CrlCtrl(crl, HITLS_X509_SET_BEFORE_TIME, &beforeTime, sizeof(BSL_TIME)), HITLS_PKI_SUCCESS); afterTime = beforeTime; afterTime.year += 1; ASSERT_EQ(HITLS_X509_CrlCtrl(crl, HITLS_X509_SET_AFTER_TIME, &afterTime, sizeof(BSL_TIME)), HITLS_PKI_SUCCESS); HITLS_X509_ExtSki ski = {0}; ASSERT_EQ(HITLS_X509_CertCtrl(cert, HITLS_X509_EXT_GET_SKI, &ski, sizeof(HITLS_X509_ExtSki)), HITLS_PKI_SUCCESS); ASSERT_TRUE(ski.kid.data != NULL); HITLS_X509_ExtAki aki = {false, {ski.kid.data, ski.kid.dataLen}, cert->tbs.issuerName, {cert->tbs.serialNum.buff, cert->tbs.serialNum.len}}; ASSERT_EQ(HITLS_X509_CrlCtrl(crl, HITLS_X509_EXT_SET_AKI, &aki, sizeof(HITLS_X509_ExtAki)), HITLS_PKI_SUCCESS); HITLS_X509_ExtCrlNumber crlNumberExt = {false, {serialNum, 4}}; ASSERT_EQ(HITLS_X509_CrlCtrl(crl, HITLS_X509_EXT_SET_CRLNUMBER, &crlNumberExt, sizeof(HITLS_X509_ExtCrlNumber)), HITLS_PKI_SUCCESS); EXIT: HITLS_X509_CertFree(cert); HITLS_X509_CrlFree(crl); } /* END_CASE */ /* BEGIN_CASE */ void SDV_X509_CRL_Sign_ParamCheck_TC001(void) { HITLS_X509_Crl *crl = NULL; CRYPT_EAL_PkeyCtx *prvKey = NULL; HITLS_X509_SignAlgParam algParam = {0}; // Create a basic CRL object TestMemInit(); crl = HITLS_X509_CrlNew(); ASSERT_NE(crl, NULL); prvKey = CRYPT_EAL_PkeyNewCtx(CRYPT_PKEY_RSA); ASSERT_NE(prvKey, NULL); // Test null parameters ASSERT_EQ(HITLS_X509_CrlSign(BSL_CID_SHA256, NULL, &algParam, crl), HITLS_X509_ERR_INVALID_PARAM); ASSERT_EQ(HITLS_X509_CrlSign(BSL_CID_SHA256, prvKey, &algParam, NULL), HITLS_X509_ERR_INVALID_PARAM); EXIT: HITLS_X509_CrlFree(crl); CRYPT_EAL_PkeyFreeCtx(prvKey); } /* END_CASE */ /* BEGIN_CASE */ void SDV_X509_CRL_Gen_Process_TC001(void) { HITLS_X509_Crl *crl = NULL; CRYPT_EAL_PkeyCtx *prvKey = NULL; HITLS_X509_SignAlgParam algParam = {0}; const char *keyPath = "../testdata/cert/asn1/rsa_cert/rsa_p1.key.der"; const char *crlPath = "../testdata/cert/asn1/rsa_crl/crl_v1.der"; uint32_t ver = 1; BSL_Buffer encodeCrl = {0}; BslList *tmp = NULL; ASSERT_EQ(CRYPT_EAL_PriKeyParseFile(BSL_FORMAT_ASN1, CRYPT_PRIKEY_RSA, keyPath, NULL, &prvKey), 0); ASSERT_EQ(HITLS_X509_CrlParseFile(BSL_FORMAT_ASN1, crlPath, &crl), HITLS_PKI_SUCCESS); /* Cannot repeat parse */ ASSERT_EQ(HITLS_X509_CrlParseFile(BSL_FORMAT_ASN1, crlPath, &crl), HITLS_X509_ERR_INVALID_PARAM); /* Cannot sign after parsing */ ASSERT_EQ(HITLS_X509_CrlSign(BSL_CID_SHA256, prvKey, &algParam, crl), HITLS_X509_ERR_SIGN_AFTER_PARSE); /* Cannot set after parsing */ ASSERT_EQ(HITLS_X509_CrlCtrl(crl, HITLS_X509_SET_VERSION, &ver, sizeof(uint32_t)), HITLS_X509_ERR_SET_AFTER_PARSE); ASSERT_EQ(HITLS_X509_CrlCtrl(crl, HITLS_X509_GET_ISSUER_DN, &tmp, sizeof(BslList *)), HITLS_PKI_SUCCESS); ASSERT_EQ(HITLS_X509_CrlCtrl(crl, HITLS_X509_SET_ISSUER_DN, tmp, 0), HITLS_X509_ERR_SET_AFTER_PARSE); /* Generate crl after parsing is allowed. */ ASSERT_EQ(HITLS_X509_CrlGenBuff(BSL_FORMAT_ASN1, crl, &encodeCrl), 0); BSL_SAL_Free(encodeCrl.data); encodeCrl.data = NULL; encodeCrl.dataLen = 0; /* Repeat generate is allowed. */ ASSERT_EQ(HITLS_X509_CrlGenBuff(BSL_FORMAT_ASN1, crl, &encodeCrl), 0); EXIT: HITLS_X509_CrlFree(crl); CRYPT_EAL_PkeyFreeCtx(prvKey); BSL_SAL_Free(encodeCrl.data); } /* END_CASE */ /* BEGIN_CASE */ void SDV_X509_CRL_Gen_Process_TC002(void) { HITLS_X509_Crl *crl = NULL; HITLS_X509_Cert *cert = NULL; CRYPT_EAL_PkeyCtx *prvKey = NULL; CRYPT_EAL_PkeyCtx *pubKey = NULL; const char *keyPath = "../testdata/cert/asn1/rsa_cert/rsa_p8.key.der"; const char *certPath = "../testdata/cert/asn1/rsa_cert/rsa_p8.crt.der"; uint32_t mdId = BSL_CID_SHA256; BSL_TIME thisUpdate = {2024, 8, 22, 1, 1, 0, 1, 0}; BSL_TIME nextUpdate = {2024, 8, 22, 1, 1, 0, 1, 0}; BslList *issuerDN = NULL; BSL_Buffer encodeCrl = {0}; TestMemInit(); ASSERT_EQ(CRYPT_EAL_PriKeyParseFile(BSL_FORMAT_ASN1, CRYPT_PRIKEY_PKCS8_UNENCRYPT, keyPath, NULL, &prvKey), 0); ASSERT_EQ(HITLS_X509_CertParseFile(BSL_FORMAT_ASN1, certPath, &cert), 0); crl = HITLS_X509_CrlNew(); ASSERT_NE(crl, NULL); /* Invalid parameters */ ASSERT_EQ(HITLS_X509_CrlSign(mdId, prvKey, NULL, NULL), HITLS_X509_ERR_INVALID_PARAM); /* Test Crl sign with invalid fields */ /* Set invalid version number */ crl->tbs.version = 2; // 2 is invalid ASSERT_EQ(HITLS_X509_CrlSign(mdId, prvKey, NULL, crl), HITLS_X509_ERR_CRL_INACCURACY_VERSION); /* Set invalid version number in extensions */ crl->tbs.version = 0; BslList *extList = crl->tbs.crlExt.extList; crl->tbs.crlExt.extList = cert->tbs.ext.extList; ASSERT_EQ(HITLS_X509_CrlSign(mdId, prvKey, NULL, crl), HITLS_X509_ERR_CRL_INACCURACY_VERSION); crl->tbs.crlExt.extList = extList; /* issuer name is empty */ ASSERT_EQ(HITLS_X509_CrlSign(mdId, prvKey, NULL, crl), HITLS_X509_ERR_CRL_ISSUER_EMPTY); ASSERT_EQ(HITLS_X509_CertCtrl(cert, HITLS_X509_GET_ISSUER_DN, &issuerDN, sizeof(BslList *)), 0); ASSERT_EQ(HITLS_X509_CrlCtrl(crl, HITLS_X509_SET_ISSUER_DN, issuerDN, sizeof(BslList)), 0); /* thisUpdate is not set */ ASSERT_EQ(HITLS_X509_CrlSign(mdId, prvKey, NULL, crl), HITLS_X509_ERR_CRL_THISUPDATE_UNEXIST); ASSERT_EQ(HITLS_X509_CrlCtrl(crl, HITLS_X509_SET_BEFORE_TIME, &thisUpdate, sizeof(BSL_TIME)), 0); /* nextUpdate is before thisUpdate */ nextUpdate.year = thisUpdate.year - 1; ASSERT_EQ(HITLS_X509_CrlCtrl(crl, HITLS_X509_SET_AFTER_TIME, &nextUpdate, sizeof(BSL_TIME)), 0); ASSERT_EQ(HITLS_X509_CrlSign(mdId, prvKey, NULL, crl), HITLS_X509_ERR_CRL_TIME_INVALID); nextUpdate.year = thisUpdate.year + 1; ASSERT_EQ(HITLS_X509_CrlCtrl(crl, HITLS_X509_SET_AFTER_TIME, &nextUpdate, sizeof(BSL_TIME)), 0); /* Cannot generate before signing */ ASSERT_EQ(HITLS_X509_CrlGenBuff(BSL_FORMAT_ASN1, crl, &encodeCrl), HITLS_X509_ERR_CRL_NOT_SIGNED); /* Cannot verify before signing */ ASSERT_EQ(HITLS_X509_CertCtrl(cert, HITLS_X509_GET_PUBKEY, &pubKey, sizeof(CRYPT_EAL_PkeyCtx *)), 0); ASSERT_EQ(HITLS_X509_CrlVerify(pubKey, crl), HITLS_X509_ERR_CRL_NOT_SIGNED); /* Repeat sign is allowed. */ ASSERT_EQ(HITLS_X509_CrlSign(mdId, prvKey, NULL, crl), 0); ASSERT_EQ(HITLS_X509_CrlSign(mdId, prvKey, NULL, crl), 0); /* Verify after signing is allowed. */ ASSERT_EQ(HITLS_X509_CrlVerify(pubKey, crl), 0); /* Cannot parse after signing */ ASSERT_EQ(HITLS_X509_CrlParseBuff(BSL_FORMAT_ASN1, &encodeCrl, &crl), HITLS_X509_ERR_INVALID_PARAM); /* Repeat generate is allowed. */ ASSERT_EQ(HITLS_X509_CrlGenBuff(BSL_FORMAT_ASN1, crl, &encodeCrl), 0); BSL_SAL_Free(encodeCrl.data); encodeCrl.data = NULL; encodeCrl.dataLen = 0; ASSERT_EQ(HITLS_X509_CrlGenBuff(BSL_FORMAT_ASN1, crl, &encodeCrl), 0); /* Sing after generating is allowed. */ ASSERT_EQ(HITLS_X509_CrlSign(mdId, prvKey, NULL, crl), 0); /* Verify after generating is allowed. */ ASSERT_EQ(HITLS_X509_CrlVerify(pubKey, crl), 0); /* Cannot parse after generating */ ASSERT_EQ(HITLS_X509_CrlParseBuff(BSL_FORMAT_ASN1, &encodeCrl, &crl), HITLS_X509_ERR_INVALID_PARAM); EXIT: HITLS_X509_CrlFree(crl); HITLS_X509_CertFree(cert); CRYPT_EAL_PkeyFreeCtx(prvKey); CRYPT_EAL_PkeyFreeCtx(pubKey); BSL_SAL_Free(encodeCrl.data); } /* END_CASE */ /* BEGIN_CASE */ void SDV_X509_CRL_Sign_AlgParamCheck_TC001(void) { HITLS_X509_Crl *crl = NULL; HITLS_X509_Cert *cert = NULL; HITLS_X509_SignAlgParam algParam = {0}; CRYPT_EAL_PkeyCtx *prvKey = NULL; const char *keyPath = "../testdata/cert/asn1/rsa_cert/rsa_p1.key.der"; const char *certPath = "../testdata/cert/asn1/rsa_cert/rsa_p8.crt.der"; BSL_TIME thisUpdate = {2024, 8, 22, 1, 1, 0, 1, 0}; BslList *issuerDN = NULL; TestMemInit(); ASSERT_EQ(CRYPT_EAL_PriKeyParseFile(BSL_FORMAT_ASN1, CRYPT_PRIKEY_RSA, keyPath, NULL, &prvKey), 0); ASSERT_EQ(HITLS_X509_CertParseFile(BSL_FORMAT_ASN1, certPath, &cert), 0); crl = HITLS_X509_CrlNew(); ASSERT_NE(crl, NULL); ASSERT_EQ(HITLS_X509_CertCtrl(cert, HITLS_X509_GET_ISSUER_DN, &issuerDN, sizeof(BslList *)), 0); ASSERT_EQ(HITLS_X509_CrlCtrl(crl, HITLS_X509_SET_ISSUER_DN, issuerDN, sizeof(BslList)), 0); ASSERT_EQ(HITLS_X509_CrlCtrl(crl, HITLS_X509_SET_BEFORE_TIME, &thisUpdate, sizeof(BSL_TIME)), 0); /* Test invalid mdId */ ASSERT_EQ(HITLS_X509_CrlSign(BSL_CID_SHAKE128, prvKey, &algParam, crl), HITLS_X509_ERR_HASHID); /* Test empty algParam */ ASSERT_EQ(HITLS_X509_CrlSign(BSL_CID_SHA256, prvKey, &algParam, crl), HITLS_X509_ERR_MD_NOT_MATCH); /* Test invalid mdId for RSA-PSS */ algParam.algId = BSL_CID_RSASSAPSS; ASSERT_EQ(HITLS_X509_CrlSign(BSL_CID_SHA256, prvKey, &algParam, crl), HITLS_X509_ERR_MD_NOT_MATCH); /* Test invalid mgfId for RSA-PSS */ algParam.rsaPss.mdId = (CRYPT_MD_AlgId)BSL_CID_SHA256; algParam.rsaPss.mgfId = (CRYPT_MD_AlgId)BSL_CID_UNKNOWN; algParam.rsaPss.saltLen = 32; ASSERT_EQ(HITLS_X509_CrlSign(BSL_CID_SHA256, prvKey, &algParam, crl), CRYPT_EAL_ERR_ALGID); EXIT: HITLS_X509_CrlFree(crl); HITLS_X509_CertFree(cert); CRYPT_EAL_PkeyFreeCtx(prvKey); } /* END_CASE */ #if defined(HITLS_PKI_X509_CRL_GEN) || defined(HITLS_PKI_X509_CRT_GEN) static BslList* GenDNList(void) { HITLS_X509_DN dnName1[1] = {{BSL_CID_AT_COMMONNAME, (uint8_t *)"OH", 2}}; HITLS_X509_DN dnName2[1] = {{BSL_CID_AT_COUNTRYNAME, (uint8_t *)"CN", 2}}; BslList *dirNames = HITLS_X509_DnListNew(); ASSERT_NE(dirNames, NULL); ASSERT_EQ(HITLS_X509_AddDnName(dirNames, dnName1, 1), HITLS_PKI_SUCCESS); ASSERT_EQ(HITLS_X509_AddDnName(dirNames, dnName2, 1), HITLS_PKI_SUCCESS); return dirNames; EXIT: HITLS_X509_DnListFree(dirNames); return NULL; } #endif static BslList* GenGeneralNameList(void) { char *str = "test"; HITLS_X509_GeneralName *email = NULL; HITLS_X509_GeneralName *dns = NULL; HITLS_X509_GeneralName *dname = NULL; HITLS_X509_GeneralName *uri = NULL; HITLS_X509_GeneralName *ip = NULL; BslList *names = BSL_LIST_New(sizeof(HITLS_X509_GeneralName)); ASSERT_NE(names, NULL); email = BSL_SAL_Malloc(sizeof(HITLS_X509_GeneralName)); dns = BSL_SAL_Malloc(sizeof(HITLS_X509_GeneralName)); dname = BSL_SAL_Malloc(sizeof(HITLS_X509_GeneralName)); uri = BSL_SAL_Malloc(sizeof(HITLS_X509_GeneralName)); ip = BSL_SAL_Malloc(sizeof(HITLS_X509_GeneralName)); ASSERT_TRUE(email != NULL && dns != NULL && dname != NULL && uri != NULL && ip != NULL); email->type = HITLS_X509_GN_EMAIL; dns->type = HITLS_X509_GN_DNS; uri->type = HITLS_X509_GN_URI; dname->type = HITLS_X509_GN_DNNAME; ip->type = HITLS_X509_GN_IP; email->value.dataLen = strlen(str); dns->value.dataLen = strlen(str); uri->value.dataLen = strlen(str); dname->value.dataLen = sizeof(BslList *); ip->value.dataLen = strlen(str); email->value.data = BSL_SAL_Dump(str, strlen(str)); dns->value.data = BSL_SAL_Dump(str, strlen(str)); uri->value.data = BSL_SAL_Dump(str, strlen(str)); dname->value.data = (uint8_t *)GenDNList(); ip->value.data = BSL_SAL_Dump(str, strlen(str)); ASSERT_TRUE(email->value.data != NULL && dns->value.data != NULL && uri->value.data != NULL && dname->value.data != NULL && ip->value.data != NULL); ASSERT_EQ(BSL_LIST_AddElement(names, email, BSL_LIST_POS_END), 0); ASSERT_EQ(BSL_LIST_AddElement(names, dns, BSL_LIST_POS_END), 0); ASSERT_EQ(BSL_LIST_AddElement(names, uri, BSL_LIST_POS_END), 0); ASSERT_EQ(BSL_LIST_AddElement(names, dname, BSL_LIST_POS_END), 0); ASSERT_EQ(BSL_LIST_AddElement(names, ip, BSL_LIST_POS_END), 0); return names; EXIT: HITLS_X509_FreeGeneralName(email); HITLS_X509_FreeGeneralName(dns); HITLS_X509_FreeGeneralName(dname); HITLS_X509_FreeGeneralName(uri); HITLS_X509_FreeGeneralName(ip); BSL_LIST_FREE(names, (BSL_LIST_PFUNC_FREE)HITLS_X509_FreeGeneralName); return NULL; } static int32_t SetCrlRevoked(HITLS_X509_Crl *crl, int8_t ser) { uint8_t serialNum[4] = {0x11, 0x22, 0x33, 0x44}; serialNum[3] = ser; HITLS_X509_CrlEntry *entry = HITLS_X509_CrlEntryNew(); ASSERT_NE(entry, NULL); ASSERT_EQ(HITLS_X509_CrlEntryCtrl(entry, HITLS_X509_CRL_SET_REVOKED_SERIALNUM, serialNum, sizeof(serialNum)), HITLS_PKI_SUCCESS); BSL_TIME revokeTime = {0}; ASSERT_EQ(BSL_SAL_SysTimeGet(&revokeTime), BSL_SUCCESS); ASSERT_EQ(HITLS_X509_CrlEntryCtrl(entry, HITLS_X509_CRL_SET_REVOKED_REVOKE_TIME, &revokeTime, sizeof(BSL_TIME)), HITLS_PKI_SUCCESS); HITLS_X509_RevokeExtReason reason = {0, 1}; // keyCompromise ASSERT_EQ(HITLS_X509_CrlEntryCtrl(entry, HITLS_X509_CRL_SET_REVOKED_REASON, &reason, sizeof(HITLS_X509_RevokeExtReason)), HITLS_PKI_SUCCESS); // Set invalid time (optional) BSL_TIME invalidTime = revokeTime; HITLS_X509_RevokeExtTime invalidTimeExt = {false, invalidTime}; ASSERT_EQ(HITLS_X509_CrlEntryCtrl(entry, HITLS_X509_CRL_SET_REVOKED_INVALID_TIME, &invalidTimeExt, sizeof(HITLS_X509_RevokeExtTime)), HITLS_PKI_SUCCESS); // Set certificate issuer (optional, only needed for indirect CRLs) HITLS_X509_RevokeExtCertIssuer certIssuer = {true, NULL}; certIssuer.issuerName = GenGeneralNameList(); ASSERT_EQ(HITLS_X509_CrlEntryCtrl(entry, HITLS_X509_CRL_SET_REVOKED_CERTISSUER, &certIssuer, sizeof(HITLS_X509_RevokeExtCertIssuer)), HITLS_PKI_SUCCESS); ASSERT_EQ(HITLS_X509_CrlCtrl(crl, HITLS_X509_CRL_ADD_REVOKED_CERT, entry, sizeof(HITLS_X509_CrlEntry)), HITLS_PKI_SUCCESS); HITLS_X509_CrlEntryFree(entry); BSL_LIST_FREE(certIssuer.issuerName, (BSL_LIST_PFUNC_FREE)HITLS_X509_FreeGeneralName); return HITLS_PKI_SUCCESS; EXIT: return -1; } /* BEGIN_CASE */ void SDV_X509_CRL_Sign_RevokedCheck_TC001(void) { HITLS_X509_Crl *crl = NULL; HITLS_X509_Cert *cert = NULL; CRYPT_EAL_PkeyCtx *prvKey = NULL; HITLS_X509_SignAlgParam algParam = {0}; HITLS_X509_CrlEntry *entry = NULL; BSL_TIME beforeTime = {0}; BSL_TIME afterTime = {0}; ASSERT_EQ(CRYPT_EAL_PriKeyParseFile(BSL_FORMAT_ASN1, CRYPT_PRIKEY_RSA, "../testdata/cert/asn1/rsa_cert/rsa_p1.key.der", NULL, &prvKey), 0); ASSERT_EQ(HITLS_X509_CertParseFile(BSL_FORMAT_ASN1, "../testdata/cert/asn1/rsa_cert/rsa_p1_v1.crt.der", &cert), HITLS_PKI_SUCCESS); // Create a basic CRL object and set necessary fields crl = HITLS_X509_CrlNew(); ASSERT_NE(crl, NULL); BslList *issueList = crl->tbs.issuerName; // Set basic fields (version, time, issuer, etc.) crl->tbs.version = 1; crl->tbs.issuerName = cert->tbs.subjectName; ASSERT_EQ(BSL_SAL_SysTimeGet(&beforeTime), BSL_SUCCESS); ASSERT_EQ(HITLS_X509_CrlCtrl(crl, HITLS_X509_SET_BEFORE_TIME, &beforeTime, sizeof(BSL_TIME)), HITLS_PKI_SUCCESS); afterTime = beforeTime; afterTime.year += 1; ASSERT_EQ(HITLS_X509_CrlCtrl(crl, HITLS_X509_SET_AFTER_TIME, &afterTime, sizeof(BSL_TIME)), HITLS_PKI_SUCCESS); ASSERT_EQ(SetCrlRevoked(crl, 1), HITLS_PKI_SUCCESS); entry = BSL_LIST_GET_FIRST(crl->tbs.revokedCerts); ASSERT_TRUE(entry != NULL); crl->tbs.version = 0; ASSERT_EQ(HITLS_X509_CrlSign(BSL_CID_SHA256, prvKey, &algParam, crl), HITLS_X509_ERR_CRL_INACCURACY_VERSION); crl->tbs.version = 1; uint8_t *serialNum = entry->serialNumber.buff; entry->serialNumber.buff = NULL; ASSERT_EQ(HITLS_X509_CrlSign(BSL_CID_SHA256, prvKey, &algParam, crl), HITLS_X509_ERR_CRL_ENTRY); entry->serialNumber.buff = serialNum; uint32_t year = entry->time.year; entry->time.year = 0; ASSERT_EQ(HITLS_X509_CrlSign(BSL_CID_SHA256, prvKey, &algParam, crl), HITLS_X509_ERR_CRL_TIME_INVALID); entry->time.year = year; EXIT: crl->tbs.issuerName = issueList; HITLS_X509_CrlFree(crl); HITLS_X509_CertFree(cert); CRYPT_EAL_PkeyFreeCtx(prvKey); } /* END_CASE */ static int32_t SetCrl(HITLS_X509_Crl *crl, HITLS_X509_Cert *cert, bool isV2) { BSL_TIME beforeTime = {0}; BSL_TIME afterTime = {0}; BslList *issuerDN = NULL; uint8_t crlNumber[1] = {0x01}; // Set CRL version (v2) uint32_t version = 1; ASSERT_EQ(HITLS_X509_CrlCtrl(crl, HITLS_X509_SET_VERSION, &version, sizeof(version)), HITLS_PKI_SUCCESS); // Set issuer DN from certificate ASSERT_EQ(HITLS_X509_CertCtrl(cert, HITLS_X509_GET_SUBJECT_DN, &issuerDN, sizeof(BslList *)), HITLS_PKI_SUCCESS); ASSERT_EQ(HITLS_X509_CrlCtrl(crl, HITLS_X509_SET_ISSUER_DN, issuerDN, sizeof(BslList)), HITLS_PKI_SUCCESS); // Set validity period ASSERT_EQ(BSL_SAL_SysTimeGet(&beforeTime), BSL_SUCCESS); ASSERT_EQ(HITLS_X509_CrlCtrl(crl, HITLS_X509_SET_BEFORE_TIME, &beforeTime, sizeof(BSL_TIME)), HITLS_PKI_SUCCESS); afterTime = beforeTime; afterTime.year += 1; ASSERT_EQ(HITLS_X509_CrlCtrl(crl, HITLS_X509_SET_AFTER_TIME, &afterTime, sizeof(BSL_TIME)), HITLS_PKI_SUCCESS); for (int i = 0; i < 3; i++) { ASSERT_EQ(SetCrlRevoked(crl, i), HITLS_PKI_SUCCESS); } if (isV2) { HITLS_X509_ExtSki ski = {0}; int32_t ret = HITLS_X509_CertCtrl(cert, HITLS_X509_EXT_GET_SKI, &ski, sizeof(HITLS_X509_ExtSki)); if (ret == HITLS_PKI_SUCCESS) { HITLS_X509_ExtAki aki = {false, {ski.kid.data, ski.kid.dataLen}, NULL, {NULL, 0}}; // Set SKI extension ASSERT_EQ(HITLS_X509_CrlCtrl(crl, HITLS_X509_EXT_SET_AKI, &aki, sizeof(HITLS_X509_ExtAki)), HITLS_PKI_SUCCESS); } // Set CRL Number extension HITLS_X509_ExtCrlNumber crlNumberExt = { false, // non-critical {crlNumber, sizeof(crlNumber)} }; ASSERT_EQ(HITLS_X509_CrlCtrl(crl, HITLS_X509_EXT_SET_CRLNUMBER, &crlNumberExt, sizeof(HITLS_X509_ExtCrlNumber)), HITLS_PKI_SUCCESS); } return HITLS_PKI_SUCCESS; EXIT: return -1; } /* BEGIN_CASE */ void SDV_X509_CRL_Sign_Func_TC001(char *cert, char *key, int keytype, int pad, int mdId, int isV2, char *tmp, int isUseSm2UserId) { HITLS_X509_Crl *crl = NULL; HITLS_X509_Crl *parseCrl = NULL; HITLS_X509_Cert *issuerCert = NULL; CRYPT_EAL_PkeyCtx *prvKey = NULL; HITLS_X509_SignAlgParam algParam = {0}; TestRandInit(); // Parse issuer certificate and private key ASSERT_EQ(HITLS_X509_CertParseFile(BSL_FORMAT_UNKNOWN, cert, &issuerCert), HITLS_PKI_SUCCESS); ASSERT_EQ(CRYPT_EAL_PriKeyParseFile(BSL_FORMAT_UNKNOWN, keytype, key, NULL, &prvKey), 0); // Create and initialize CRL crl = HITLS_X509_CrlNew(); ASSERT_NE(crl, NULL); ASSERT_EQ(SetCrl(crl, issuerCert, (bool)isV2), 0); // Set signature algorithm parameters if (pad == CRYPT_EMSA_PSS) { algParam.algId = BSL_CID_RSASSAPSS; CRYPT_RSA_PssPara pssParam = {0}; pssParam.mdId = mdId; pssParam.mgfId = mdId; pssParam.saltLen = 32; algParam.rsaPss = pssParam; } else if (isUseSm2UserId != 0) { algParam.algId = BSL_CID_SM2DSAWITHSM3; algParam.sm2UserId.data = (uint8_t *)g_sm2DefaultUserid; algParam.sm2UserId.dataLen = (uint32_t)strlen(g_sm2DefaultUserid); } if (pad == CRYPT_EMSA_PSS || isUseSm2UserId != 0) { ASSERT_EQ(HITLS_X509_CrlSign(mdId, prvKey, &algParam, crl), HITLS_PKI_SUCCESS); } else { ASSERT_EQ(HITLS_X509_CrlSign(mdId, prvKey, NULL, crl), HITLS_PKI_SUCCESS); } // Verify the signature is present ASSERT_NE(crl->signature.buff, NULL); ASSERT_NE(crl->signature.len, 0); ASSERT_EQ(HITLS_X509_CrlGenFile(BSL_FORMAT_ASN1, crl, tmp), HITLS_PKI_SUCCESS); ASSERT_EQ(HITLS_X509_CrlVerify(issuerCert->tbs.ealPubKey, crl), HITLS_PKI_SUCCESS); ASSERT_EQ(HITLS_X509_CrlParseFile(BSL_FORMAT_UNKNOWN, tmp, &parseCrl), HITLS_PKI_SUCCESS); ASSERT_NE(parseCrl, NULL); if (isUseSm2UserId != 0) { ASSERT_EQ(HITLS_X509_CrlCtrl(parseCrl, HITLS_X509_SET_VFY_SM2_USER_ID, g_sm2DefaultUserid, strlen(g_sm2DefaultUserid)), HITLS_PKI_SUCCESS); } ASSERT_EQ(HITLS_X509_CrlVerify(issuerCert->tbs.ealPubKey, parseCrl), HITLS_PKI_SUCCESS); EXIT: HITLS_X509_CrlFree(crl); HITLS_X509_CrlFree(parseCrl); HITLS_X509_CertFree(issuerCert); CRYPT_EAL_PkeyFreeCtx(prvKey); } /* END_CASE */ static int32_t STUB_HITLS_X509_ParseNameList(BSL_ASN1_Buffer *name, BSL_ASN1_List *list) { (void)name; (void)list; return BSL_MALLOC_FAIL; } /* BEGIN_CASE */ void SDV_X509_CRL_INVALIED_TEST_TC001(int format, char *path) { TestMemInit(); FuncStubInfo tmpRpInfo = {0}; STUB_Init(); ASSERT_TRUE(STUB_Replace(&tmpRpInfo, HITLS_X509_ParseNameList, STUB_HITLS_X509_ParseNameList) == 0); HITLS_X509_Crl *crl = NULL; ASSERT_NE(HITLS_X509_CrlParseFile((int32_t)format, path, &crl), HITLS_PKI_SUCCESS); EXIT: STUB_Reset(&tmpRpInfo); HITLS_X509_CrlFree(crl); } /* END_CASE */
2301_79861745/bench_create
testcode/sdv/testcase/pki/crl/test_suite_sdv_x509_crl.c
C
unknown
45,585
/* * This file is part of the openHiTLS project. * * openHiTLS is licensed under the Mulan PSL v2. * You can use this software according to the terms and conditions of the Mulan PSL v2. * You may obtain a copy of Mulan PSL v2 at: * * http://license.coscl.org.cn/MulanPSL2 * * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, * EITHER EXPRESS 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_csr_local.h" #include "hitls_pki_csr.h" #include "hitls_pki_utils.h" #include "bsl_list.h" #include "sal_file.h" #include "bsl_obj_internal.h" #include "hitls_pki_errno.h" #include "crypt_types.h" #include "crypt_errno.h" #include "crypt_encode_decode_key.h" #include "crypt_eal_codecs.h" #include "crypt_eal_rand.h" #include "eal_pkey_local.h" #include "bsl_list_internal.h" /* END_HEADER */ #define MAX_DATA_LEN 128 static char g_sm2DefaultUserid[] = "1234567812345678"; void *TestMallocErr(uint32_t len) { (void)len; return NULL; } static void *TestMalloc(uint32_t len) { return malloc((size_t)len); } static void TestMemInitErr() { BSL_SAL_CallBack_Ctrl(BSL_SAL_MEM_MALLOC, TestMallocErr); BSL_SAL_CallBack_Ctrl(BSL_SAL_MEM_FREE, free); } static void TestMemInitCorrect() { BSL_SAL_CallBack_Ctrl(BSL_SAL_MEM_MALLOC, TestMalloc); BSL_SAL_CallBack_Ctrl(BSL_SAL_MEM_FREE, free); } /* BEGIN_CASE */ void SDV_X509_CSR_New_FUNC_TC001(void) { TestMemInitErr(); HITLS_X509_Csr *csr = HITLS_X509_CsrNew(); ASSERT_EQ(csr, NULL); TestMemInitCorrect(); csr = HITLS_X509_CsrNew(); ASSERT_NE(csr, NULL); EXIT: HITLS_X509_CsrFree(csr); } /* END_CASE */ /* BEGIN_CASE */ void SDV_X509_CSR_Free_FUNC_TC001(void) { TestMemInit(); HITLS_X509_Csr *csr = HITLS_X509_CsrNew(); ASSERT_NE(csr, NULL); HITLS_X509_CsrFree(csr); HITLS_X509_CsrFree(NULL); EXIT: return; } /* END_CASE */ /** * parse csr file api test */ /* BEGIN_CASE */ void SDV_X509_CSR_PARSE_API_TC001(void) { TestMemInit(); HITLS_X509_Csr *csr = NULL; const char *path = "../testdata/cert/pem/csr/csr.pem"; ASSERT_NE(HITLS_X509_CsrParseFile(BSL_FORMAT_PEM, path, NULL), HITLS_PKI_SUCCESS); ASSERT_NE(HITLS_X509_CsrParseFile(BSL_FORMAT_UNKNOWN, path, &csr), HITLS_PKI_SUCCESS); ASSERT_NE(HITLS_X509_CsrParseFile(BSL_FORMAT_PEM, "/errPath/csr.pem", &csr), HITLS_PKI_SUCCESS); ASSERT_NE(HITLS_X509_CsrParseFile(BSL_FORMAT_PEM, NULL, &csr), HITLS_PKI_SUCCESS); /* the csr file don't have read permission */ EXIT: HITLS_X509_CsrFree(csr); } /* END_CASE */ /** * parse csr buffer api test */ /* BEGIN_CASE */ void SDV_X509_CSR_PARSE_API_TC002(void) { TestMemInit(); HITLS_X509_Csr *csr = NULL; uint8_t data[MAX_DATA_LEN] = {}; BSL_Buffer buffer = {data, sizeof(data)}; BSL_Buffer ori = {NULL, 0}; ASSERT_EQ(HITLS_X509_CsrParseBuff(BSL_FORMAT_ASN1, &buffer, NULL), HITLS_X509_ERR_INVALID_PARAM); ASSERT_EQ(HITLS_X509_CsrParseBuff(BSL_FORMAT_ASN1, NULL, NULL), HITLS_X509_ERR_INVALID_PARAM); ASSERT_EQ(HITLS_X509_CsrParseBuff(BSL_FORMAT_ASN1, &ori, &csr), HITLS_X509_ERR_INVALID_PARAM); ASSERT_EQ(HITLS_X509_CsrParseBuff(BSL_FORMAT_ASN1, &ori, &csr), HITLS_X509_ERR_INVALID_PARAM); ASSERT_EQ(HITLS_X509_CsrParseBuff(BSL_FORMAT_UNKNOWN, &buffer, &csr), HITLS_X509_ERR_FORMAT_UNSUPPORT); EXIT: return; } /* END_CASE */ /* BEGIN_CASE */ void SDV_X509_CSR_PARSE_FUNC_TC001(int format, char *path, int expRawDataLen, int expSignAlg, Hex *expectedSign, int expectUnusedbits, int isUseSm2UserId) { TestMemInit(); HITLS_X509_Csr *csr = NULL; uint32_t rawDataLen = 0; ASSERT_EQ(HITLS_X509_CsrParseFile(format, path, &csr), HITLS_PKI_SUCCESS); if (isUseSm2UserId != 0) { ASSERT_EQ(HITLS_X509_CsrCtrl(csr, HITLS_X509_SET_VFY_SM2_USER_ID, g_sm2DefaultUserid, strlen(g_sm2DefaultUserid)), HITLS_PKI_SUCCESS); } ASSERT_EQ(HITLS_X509_CsrVerify(csr), HITLS_PKI_SUCCESS); ASSERT_EQ(HITLS_X509_CsrCtrl(csr, HITLS_X509_GET_ENCODELEN, &rawDataLen, sizeof(rawDataLen)), 0); ASSERT_EQ(rawDataLen, expRawDataLen); uint8_t *rawData = NULL; ASSERT_EQ(HITLS_X509_CsrCtrl(csr, HITLS_X509_GET_ENCODE, &rawData, 0), HITLS_PKI_SUCCESS); ASSERT_NE(rawData, NULL); CRYPT_EAL_PkeyCtx *publicKey = NULL; ASSERT_EQ(HITLS_X509_CsrCtrl(csr, HITLS_X509_GET_PUBKEY, &publicKey, 0), HITLS_PKI_SUCCESS); ASSERT_NE(publicKey, NULL); CRYPT_EAL_PkeyFreeCtx(publicKey); int32_t alg = 0; ASSERT_EQ(HITLS_X509_CsrCtrl(csr, HITLS_X509_GET_SIGNALG, &alg, sizeof(alg)), HITLS_PKI_SUCCESS); ASSERT_EQ(alg, expSignAlg); int32_t ref = 0; ASSERT_EQ(HITLS_X509_CsrCtrl(csr, HITLS_X509_REF_UP, &ref, sizeof(ref)), HITLS_PKI_SUCCESS); ASSERT_EQ(ref, 2); HITLS_X509_CsrFree(csr); ASSERT_NE(csr->signature.buff, NULL); ASSERT_EQ(csr->signature.len, expectedSign->len); ASSERT_EQ(memcmp(csr->signature.buff, expectedSign->x, expectedSign->len), 0); ASSERT_EQ(csr->signature.unusedBits, expectUnusedbits); EXIT: HITLS_X509_CsrFree(csr); } /* END_CASE */ /** * Test parse csr: check subject name */ /* BEGIN_CASE */ void SDV_X509_CSR_PARSE_FUNC_TC002(int format, char *path, int expectedNum, char *dnType1, char *dnName1, char *dnType2, char *dnName2, char *dnType3, char *dnName3, char *dnType4, char *dnName4, char *dnType5, char *dnName5, char *dnType6, char *dnName6, char *dnType7, char *dnName7) { TestMemInit(); HITLS_X509_Csr *csr = NULL; ASSERT_EQ(HITLS_X509_CsrParseFile(format, path, &csr), HITLS_PKI_SUCCESS); BslList *rawSubject = NULL; ASSERT_EQ(HITLS_X509_CsrCtrl(csr, HITLS_X509_GET_SUBJECT_DN, &rawSubject, sizeof(BslList *)), 0); ASSERT_NE(rawSubject, NULL); int count = BSL_LIST_COUNT(rawSubject); ASSERT_EQ(count, expectedNum); char *dnTypes[7] = {dnType1, dnType2, dnType3, dnType4, dnType5, dnType6, dnType7}; char *dnName[7] = {dnName1, dnName2, dnName3, dnName4, dnName5, dnName6, dnName7}; HITLS_X509_NameNode *nameNode = BSL_LIST_GET_FIRST(rawSubject); for (int i = 0; i < count && count <= 14 && nameNode != NULL; i++, nameNode = BSL_LIST_GET_NEXT(rawSubject)) { if (nameNode->layer == 1) { continue; } BSL_ASN1_Buffer nameType = nameNode->nameType; BSL_ASN1_Buffer nameValue = nameNode->nameValue; BslOidString typeOid = { .octs = (char *)nameType.buff, .octetLen = nameType.len, }; const char *oidName = BSL_OBJ_GetOidNameFromOid(&typeOid); ASSERT_NE(oidName, NULL); ASSERT_EQ(strcmp(dnTypes[i / 2], oidName), 0); ASSERT_EQ(memcmp(dnName[i / 2], nameValue.buff, strlen(dnName[i / 2])), 0); } EXIT: HITLS_X509_CsrFree(csr); } /* END_CASE */ /** * Test parse csr: check the count of the attribute list */ /* BEGIN_CASE */ void SDV_X509_CSR_PARSE_FUNC_TC003(int format, char *path, int attrNum, int attrCid, Hex *attrValue) { TestMemInit(); HITLS_X509_Csr *csr = NULL; HITLS_X509_Attrs *rawAttrs = NULL; ASSERT_EQ(HITLS_X509_CsrParseFile(format, path, &csr), HITLS_PKI_SUCCESS); ASSERT_EQ(HITLS_X509_CsrCtrl(csr, HITLS_X509_CSR_GET_ATTRIBUTES, &rawAttrs, sizeof(HITLS_X509_Attrs *)), HITLS_PKI_SUCCESS); ASSERT_NE(rawAttrs, NULL); ASSERT_EQ(attrNum, BSL_LIST_COUNT(rawAttrs->list)); if (attrNum == 0) { goto EXIT; } HITLS_X509_AttrEntry *entry = BSL_LIST_GET_FIRST(rawAttrs->list); ASSERT_EQ(attrCid, entry->cid); BslOidString *oid = BSL_OBJ_GetOID(entry->cid); ASSERT_NE(oid, NULL); ASSERT_COMPARE("csr attr oid", entry->attrId.buff, entry->attrId.len, (uint8_t *)oid->octs, oid->octetLen); ASSERT_COMPARE("csr attr value", entry->attrValue.buff, entry->attrValue.len, attrValue->x, attrValue->len); EXIT: HITLS_X509_CsrFree(csr); } /* END_CASE */ /** * encode csr buffer api test */ /* BEGIN_CASE */ void SDV_X509_CSR_GEN_API_TC001(void) { TestMemInit(); HITLS_X509_Csr *csr = NULL; const char *path = "../testdata/cert/pem/csr/csr.pem"; const char *writePath = "../testdata/cert/pem/csr/genCsr.pem"; int32_t ret = HITLS_X509_CsrParseFile(BSL_FORMAT_PEM, path, &csr); ASSERT_EQ(ret, HITLS_PKI_SUCCESS); ASSERT_EQ(HITLS_X509_CsrGenFile(BSL_FORMAT_PEM, NULL, writePath), HITLS_X509_ERR_INVALID_PARAM); ASSERT_EQ(HITLS_X509_CsrGenFile(BSL_FORMAT_UNKNOWN, csr, writePath), HITLS_X509_ERR_FORMAT_UNSUPPORT); ASSERT_EQ(HITLS_X509_CsrGenFile(BSL_FORMAT_PEM, csr, NULL), HITLS_X509_ERR_INVALID_PARAM); ASSERT_NE(HITLS_X509_CsrGenFile(BSL_FORMAT_PEM, csr, "/errPath/csr.pem"), HITLS_PKI_SUCCESS); EXIT: HITLS_X509_CsrFree(csr); return; } /* END_CASE */ /** * encode csr buffer api test */ /* BEGIN_CASE */ void SDV_X509_CSR_GEN_API_TC002(void) { TestMemInit(); HITLS_X509_Csr *csr = HITLS_X509_CsrNew(); ASSERT_NE(csr, NULL); uint8_t data[MAX_DATA_LEN] = {}; BSL_Buffer buffer = {NULL, 0}; BSL_Buffer buffErr = {data, sizeof(data)}; ASSERT_EQ(HITLS_X509_CsrGenBuff(BSL_FORMAT_UNKNOWN, csr, &buffer), HITLS_X509_ERR_FORMAT_UNSUPPORT); ASSERT_EQ(HITLS_X509_CsrGenBuff(BSL_FORMAT_PEM, NULL, &buffer), HITLS_X509_ERR_INVALID_PARAM); ASSERT_EQ(HITLS_X509_CsrGenBuff(BSL_FORMAT_PEM, csr, NULL), HITLS_X509_ERR_INVALID_PARAM); ASSERT_EQ(HITLS_X509_CsrGenBuff(BSL_FORMAT_PEM, csr, &buffErr), HITLS_X509_ERR_INVALID_PARAM); EXIT: HITLS_X509_CsrFree(csr); return; } /* END_CASE */ /* BEGIN_CASE */ void SDV_X509_CSR_SIGN_API_TC001(void) { HITLS_X509_Csr *csr = NULL; CRYPT_EAL_PkeyCtx *prvKey = NULL; HITLS_X509_SignAlgParam algParam = {0}; TestMemInit(); csr = HITLS_X509_CsrNew(); ASSERT_NE(csr, NULL); prvKey = CRYPT_EAL_PkeyNewCtx(CRYPT_PKEY_RSA); ASSERT_NE(prvKey, NULL); // Test null parameters ASSERT_EQ(HITLS_X509_CsrSign(BSL_CID_SHA256, NULL, &algParam, csr), HITLS_X509_ERR_INVALID_PARAM); ASSERT_EQ(HITLS_X509_CsrSign(BSL_CID_SHA256, prvKey, &algParam, NULL), HITLS_X509_ERR_INVALID_PARAM); EXIT: HITLS_X509_CsrFree(csr); CRYPT_EAL_PkeyFreeCtx(prvKey); } /* END_CASE */ /** * 1. transform format */ /* BEGIN_CASE */ void SDV_X509_CSR_GEN_FUNC_TC001(int inFormat, char *csrPath, int outFormat) { TestMemInit(); TestRandInit(); HITLS_X509_Csr *csr = NULL; BSL_Buffer encode = {NULL, 0}; uint8_t *data = NULL; uint32_t dataLen = 0; BSL_Buffer asnEncode = {NULL, 0}; ASSERT_EQ(BSL_SAL_ReadFile(csrPath, &data, &dataLen), BSL_SUCCESS); BSL_Buffer ori = {data, dataLen}; ASSERT_EQ(HITLS_X509_CsrParseBuff(inFormat, &ori, &csr), HITLS_PKI_SUCCESS); ASSERT_EQ(HITLS_X509_CsrGenBuff(outFormat, csr, &encode), HITLS_PKI_SUCCESS); ASSERT_EQ(HITLS_X509_CsrCtrl(csr, HITLS_X509_GET_ENCODELEN, &asnEncode.dataLen, sizeof(asnEncode.dataLen)), HITLS_PKI_SUCCESS); ASSERT_EQ(HITLS_X509_CsrCtrl(csr, HITLS_X509_GET_ENCODE, &asnEncode.data, 0), HITLS_PKI_SUCCESS); ASSERT_EQ(HITLS_X509_CsrVerify(csr), HITLS_PKI_SUCCESS); if (inFormat == outFormat) { ASSERT_EQ(dataLen, encode.dataLen); ASSERT_EQ(memcmp(encode.data, data, dataLen), 0); } else if (inFormat == BSL_FORMAT_ASN1 && outFormat == BSL_FORMAT_PEM) { ASSERT_EQ(dataLen, asnEncode.dataLen); ASSERT_EQ(memcmp(asnEncode.data, data, dataLen), 0); } else { ASSERT_EQ(csr->rawDataLen, encode.dataLen); ASSERT_EQ(memcmp(encode.data, csr->rawData, encode.dataLen), 0); } EXIT: BSL_SAL_FREE(data); BSL_SAL_FREE(encode.data); HITLS_X509_CsrFree(csr); } /* END_CASE */ static void ResetCsrNameList(HITLS_X509_Csr *raw) { BslList *newSubject = NULL; (void)HITLS_X509_CsrCtrl(raw, HITLS_X509_GET_SUBJECT_DN, &newSubject, sizeof(BslList **)); newSubject->curr = NULL; newSubject->last = NULL; newSubject->first = NULL; newSubject->dataSize = sizeof(HITLS_X509_NameNode); newSubject->count = 0; } static void ResetCsrAttrsList(HITLS_X509_Csr *raw) { HITLS_X509_Attrs *newAttrs = NULL; (void)HITLS_X509_CsrCtrl(raw, HITLS_X509_CSR_GET_ATTRIBUTES, &newAttrs, sizeof(HITLS_X509_Attrs *)); newAttrs->list->curr = NULL; newAttrs->list->last = NULL; newAttrs->list->first = NULL; newAttrs->list->dataSize = sizeof(HITLS_X509_NameNode); newAttrs->list->count = 0; newAttrs->flag = 0; } static int32_t SetCsr(HITLS_X509_Csr *raw, HITLS_X509_Csr *new) { int32_t ret = 1; ASSERT_EQ(HITLS_X509_CsrCtrl(new, HITLS_X509_SET_PUBKEY, raw->reqInfo.ealPubKey, sizeof(CRYPT_EAL_PkeyCtx *)), 0); BslList *rawSubject = NULL; BslList *newSubject = NULL; ASSERT_EQ(HITLS_X509_CsrCtrl(raw, HITLS_X509_GET_SUBJECT_DN, &rawSubject, sizeof(BslList *)), 0); ASSERT_EQ(HITLS_X509_CsrCtrl(new, HITLS_X509_GET_SUBJECT_DN, &newSubject, sizeof(BslList *)), 0); ASSERT_NE(rawSubject, NULL); ASSERT_NE(newSubject, NULL); ASSERT_NE(BSL_LIST_Concat(newSubject, rawSubject), NULL); HITLS_X509_Attrs *rawAttrs = NULL; HITLS_X509_Attrs *newAttrs = NULL; ASSERT_EQ(HITLS_X509_CsrCtrl(raw, HITLS_X509_CSR_GET_ATTRIBUTES, &rawAttrs, sizeof(HITLS_X509_Attrs *)), 0); ASSERT_EQ(HITLS_X509_CsrCtrl(new, HITLS_X509_CSR_GET_ATTRIBUTES, &newAttrs, sizeof(HITLS_X509_Attrs *)), 0); ASSERT_NE(rawAttrs, NULL); ASSERT_NE(newAttrs, NULL); if (BSL_LIST_COUNT(rawAttrs->list) > 0) { ASSERT_NE(BSL_LIST_Concat(newAttrs->list, rawAttrs->list), NULL); } ret = 0; EXIT: return ret; } /** * 1. set subject name, private key, public key, mdId, padding * 2. generate csr * 3. compare the generated csr buff */ /* BEGIN_CASE */ void SDV_X509_CSR_GEN_FUNC_TC002(int csrFormat, char *csrPath, int keyFormat, char *privPath, int keyType, int pad, int mdId, int mgfId, int saltLen, int isUseSm2UserId) { TestMemInit(); TestRandInit(); HITLS_X509_Csr *raw = NULL; HITLS_X509_Csr *new = NULL; CRYPT_EAL_PkeyCtx *privKey = NULL; BSL_Buffer encode = {NULL, 0}; uint8_t *newCsrEncode = NULL; uint32_t newCsrEncodeLen = 0; uint8_t *rawCsrEncode = NULL; uint32_t rawCsrEncodeLen = 0; HITLS_X509_SignAlgParam algParam = {0}; HITLS_X509_SignAlgParam *algParamPtr = NULL; if (pad == CRYPT_EMSA_PSS) { algParam.algId = BSL_CID_RSASSAPSS; algParam.rsaPss.mdId = mdId; algParam.rsaPss.mgfId = mgfId; algParam.rsaPss.saltLen = saltLen; algParamPtr = &algParam; } else if (isUseSm2UserId != 0) { algParam.algId = BSL_CID_SM2DSAWITHSM3; algParam.sm2UserId.data = (uint8_t *)g_sm2DefaultUserid; algParam.sm2UserId.dataLen = (uint32_t)strlen(g_sm2DefaultUserid); algParamPtr = &algParam; } else { algParamPtr = NULL; } TestMemInit(); ASSERT_EQ(CRYPT_EAL_DecodeFileKey(keyFormat, keyType, privPath, NULL, 0, &privKey), HITLS_PKI_SUCCESS); ASSERT_EQ(HITLS_X509_CsrParseFile(csrFormat, csrPath, &raw), HITLS_PKI_SUCCESS); new = HITLS_X509_CsrNew(); ASSERT_NE(new, NULL); ASSERT_EQ(SetCsr(raw, new), 0); ASSERT_EQ(HITLS_X509_CsrSign(mdId, privKey, algParamPtr, new), HITLS_PKI_SUCCESS); ASSERT_EQ(HITLS_X509_CsrGenBuff(csrFormat, new, &encode), HITLS_PKI_SUCCESS); ASSERT_EQ(HITLS_X509_CsrVerify(new), HITLS_PKI_SUCCESS); ASSERT_EQ(HITLS_X509_CsrCtrl(new, HITLS_X509_GET_ENCODELEN, &newCsrEncodeLen, sizeof(newCsrEncodeLen)), HITLS_PKI_SUCCESS); ASSERT_EQ(HITLS_X509_CsrCtrl(new, HITLS_X509_GET_ENCODE, &newCsrEncode, 0), HITLS_PKI_SUCCESS); ASSERT_EQ(HITLS_X509_CsrCtrl(raw, HITLS_X509_GET_ENCODELEN, &rawCsrEncodeLen, sizeof(rawCsrEncodeLen)), HITLS_PKI_SUCCESS); ASSERT_EQ(HITLS_X509_CsrCtrl(raw, HITLS_X509_GET_ENCODE, &rawCsrEncode, 0), HITLS_PKI_SUCCESS); if (pad == CRYPT_EMSA_PSS || new->signAlgId.algId == (BslCid)BSL_CID_SM2DSAWITHSM3) { ASSERT_EQ(raw->reqInfo.reqInfoRawDataLen, new->reqInfo.reqInfoRawDataLen); ASSERT_EQ(memcmp(raw->reqInfo.reqInfoRawData, new->reqInfo.reqInfoRawData, raw->reqInfo.reqInfoRawDataLen), 0); } else { ASSERT_EQ(newCsrEncodeLen, rawCsrEncodeLen); ASSERT_EQ(memcmp(newCsrEncode, rawCsrEncode, rawCsrEncodeLen), 0); } EXIT: HITLS_X509_CsrFree(raw); ResetCsrNameList(new); ResetCsrAttrsList(new); HITLS_X509_CsrFree(new); BSL_SAL_FREE(encode.data); CRYPT_EAL_PkeyFreeCtx(privKey); } /* END_CASE */ /* BEGIN_CASE */ void SDV_X509_CSR_GEN_PROCESS_TC001(char *csrPath, int csrFormat, char *privPath, int keyFormat, int keyType) { HITLS_X509_Csr *csr = NULL; CRYPT_EAL_PkeyCtx *privKey = NULL; int mdId = CRYPT_MD_SHA256; BSL_Buffer encodeCsr = {NULL, 0}; TestMemInit(); ASSERT_EQ(CRYPT_EAL_PriKeyParseFile(keyFormat, keyType, privPath, NULL, &privKey), 0); ASSERT_EQ(HITLS_X509_CsrParseFile(csrFormat, csrPath, &csr), HITLS_PKI_SUCCESS); ASSERT_EQ(HITLS_X509_CsrSign(mdId, privKey, NULL, NULL), HITLS_X509_ERR_INVALID_PARAM); /* Cannot sign after parsing */ ASSERT_EQ(HITLS_X509_CsrSign(mdId, privKey, NULL, csr), HITLS_X509_ERR_SIGN_AFTER_PARSE); /* Cannot set after parsing */ ASSERT_EQ(HITLS_X509_CsrCtrl(csr, HITLS_X509_SET_PUBKEY, privKey, 0), HITLS_X509_ERR_SET_AFTER_PARSE); /* Generate csr after parsing is allowed. */ ASSERT_EQ(HITLS_X509_CsrGenBuff(BSL_FORMAT_ASN1, csr, &encodeCsr), 0); BSL_SAL_Free(encodeCsr.data); encodeCsr.data = NULL; encodeCsr.dataLen = 0; ASSERT_EQ(HITLS_X509_CsrGenBuff(BSL_FORMAT_ASN1, csr, &encodeCsr), 0); // Repeat generate is allowed. EXIT: CRYPT_EAL_PkeyFreeCtx(privKey); HITLS_X509_CsrFree(csr); BSL_SAL_Free(encodeCsr.data); } /* END_CASE */ /* BEGIN_CASE */ void SDV_X509_CSR_GEN_PROCESS_TC002(char *privPath, int keyFormat, int keyType) { HITLS_X509_Csr *new = NULL; CRYPT_EAL_PkeyCtx *key = NULL; BSL_Buffer encodeCsr = {0}; int mdId = CRYPT_MD_SHA256; HITLS_X509_DN dnName[1] = {{BSL_CID_AT_COUNTRYNAME, (uint8_t *)"CN", strlen("CN")}}; TestMemInit(); ASSERT_EQ(CRYPT_EAL_PriKeyParseFile(keyFormat, keyType, privPath, NULL, &key), 0); new = HITLS_X509_CsrNew(); ASSERT_TRUE(new != NULL); /* Cannot parse after new */ ASSERT_EQ(HITLS_X509_CsrParseBuff(BSL_FORMAT_ASN1, &encodeCsr, &new), HITLS_X509_ERR_INVALID_PARAM); /* Cannot generate before signing */ ASSERT_EQ(HITLS_X509_CsrGenBuff(BSL_FORMAT_ASN1, new, &encodeCsr), HITLS_X509_ERR_CSR_NOT_SIGNED); /* Invalid parameters */ ASSERT_EQ(HITLS_X509_CsrSign(mdId, key, NULL, NULL), HITLS_X509_ERR_INVALID_PARAM); /* Cannot sign before setting pubkey */ ASSERT_EQ(HITLS_X509_CsrSign(mdId, key, NULL, new), HITLS_X509_ERR_CSR_INVALID_PUBKEY); ASSERT_EQ(HITLS_X509_CsrCtrl(new, HITLS_X509_SET_PUBKEY, key, 0), 0); /* Cannot sign before setting subject name */ ASSERT_EQ(HITLS_X509_CsrSign(mdId, key, NULL, new), HITLS_X509_ERR_CSR_INVALID_SUBJECT_DN); ASSERT_EQ(HITLS_X509_CsrCtrl(new, HITLS_X509_ADD_SUBJECT_NAME, dnName, 1), 0); /* Repeat sign is allowed. */ ASSERT_EQ(HITLS_X509_CsrSign(mdId, key, NULL, new), 0); ASSERT_EQ(HITLS_X509_CsrSign(mdId, key, NULL, new), 0); /* Cannot parse after signing */ ASSERT_EQ(HITLS_X509_CsrParseBuff(BSL_FORMAT_ASN1, &encodeCsr, &new), HITLS_X509_ERR_INVALID_PARAM); /* Repeat generate is allowed. */ ASSERT_EQ(HITLS_X509_CsrGenBuff(BSL_FORMAT_ASN1, new, &encodeCsr), 0); BSL_SAL_Free(encodeCsr.data); encodeCsr.data = NULL; encodeCsr.dataLen = 0; ASSERT_EQ(HITLS_X509_CsrGenBuff(BSL_FORMAT_ASN1, new, &encodeCsr), 0); /* Sing after generating is allowed. */ ASSERT_EQ(HITLS_X509_CsrSign(mdId, key, NULL, new), 0); /* Cannot parse after generating */ ASSERT_EQ(HITLS_X509_CsrParseBuff(BSL_FORMAT_ASN1, &encodeCsr, &new), HITLS_X509_ERR_INVALID_PARAM); EXIT: CRYPT_EAL_PkeyFreeCtx(key); HITLS_X509_CsrFree(new); BSL_SAL_Free(encodeCsr.data); } /* END_CASE */ void SetRsaPara(CRYPT_EAL_PkeyPara *para, uint8_t *e, uint32_t eLen, uint32_t bits) { para->id = CRYPT_PKEY_RSA; para->para.rsaPara.e = e; para->para.rsaPara.eLen = eLen; para->para.rsaPara.bits = bits; } /** * 1. csr ctrl interface test */ /* BEGIN_CASE */ void SDV_X509_CSR_CTRL_SET_API_TC001(char *csrPath) { TestMemInit(); BSL_Buffer encodeRaw = { NULL, 0}; HITLS_X509_Csr *csr = NULL; uint8_t *csrEncode = NULL; uint32_t csrEncodeLen = 0; CRYPT_EAL_PkeyCtx *pkey = NULL; ASSERT_EQ(BSL_SAL_ReadFile(csrPath, &encodeRaw.data, &encodeRaw.dataLen), HITLS_PKI_SUCCESS); ASSERT_NE(encodeRaw.data, NULL); ASSERT_EQ(HITLS_X509_CsrParseBuff(BSL_FORMAT_ASN1, &encodeRaw, &csr), HITLS_PKI_SUCCESS); ASSERT_NE(HITLS_X509_CsrCtrl(NULL, HITLS_X509_GET_ENCODE, &csrEncode, 0), HITLS_PKI_SUCCESS); ASSERT_NE(HITLS_X509_CsrCtrl(csr, 0xFFFF, &csrEncode, 0), HITLS_PKI_SUCCESS); ASSERT_NE(HITLS_X509_CsrCtrl(csr, HITLS_X509_GET_ENCODE, NULL, 0), HITLS_PKI_SUCCESS); ASSERT_NE(HITLS_X509_CsrCtrl(csr, HITLS_X509_GET_ENCODELEN, NULL, 0), HITLS_PKI_SUCCESS); ASSERT_NE(HITLS_X509_CsrCtrl(NULL, HITLS_X509_GET_ENCODELEN, &csrEncodeLen, sizeof(csrEncodeLen)), HITLS_PKI_SUCCESS); ASSERT_NE(HITLS_X509_CsrCtrl(csr, HITLS_X509_GET_ENCODELEN, &csrEncodeLen, 0), HITLS_PKI_SUCCESS); int ref = 0; ASSERT_NE(HITLS_X509_CsrCtrl(csr, HITLS_X509_REF_UP, NULL, 0), HITLS_PKI_SUCCESS); ASSERT_NE(HITLS_X509_CsrCtrl(csr, HITLS_X509_REF_UP, &ref, 0), HITLS_PKI_SUCCESS); ASSERT_NE(HITLS_X509_CsrCtrl(csr, HITLS_X509_GET_PUBKEY, NULL, 0), HITLS_PKI_SUCCESS); ASSERT_NE(HITLS_X509_CsrCtrl(NULL, HITLS_X509_GET_PUBKEY, &pkey, 0), HITLS_PKI_SUCCESS); int32_t signAlg = 0; ASSERT_NE(HITLS_X509_CsrCtrl(csr, HITLS_X509_GET_SIGNALG, NULL, 0), HITLS_PKI_SUCCESS); ASSERT_NE(HITLS_X509_CsrCtrl(NULL, HITLS_X509_GET_SIGNALG, &signAlg, 0), HITLS_PKI_SUCCESS); ASSERT_NE(HITLS_X509_CsrCtrl(csr, HITLS_X509_GET_SIGNALG, &signAlg, 0), HITLS_PKI_SUCCESS); BslList *subjectName = 0; ASSERT_NE(HITLS_X509_CsrCtrl(csr, HITLS_X509_GET_SUBJECT_DN, NULL, 0), HITLS_PKI_SUCCESS); ASSERT_NE(HITLS_X509_CsrCtrl(NULL, HITLS_X509_GET_SUBJECT_DN, &subjectName, 0), HITLS_PKI_SUCCESS); ASSERT_NE(HITLS_X509_CsrCtrl(csr, HITLS_X509_GET_SUBJECT_DN, &subjectName, 0), HITLS_PKI_SUCCESS); HITLS_X509_Attrs attrs = {}; ASSERT_NE(HITLS_X509_CsrCtrl(csr, HITLS_X509_CSR_GET_ATTRIBUTES, NULL, 0), HITLS_PKI_SUCCESS); ASSERT_NE(HITLS_X509_CsrCtrl(NULL, HITLS_X509_CSR_GET_ATTRIBUTES, &attrs, 0), HITLS_PKI_SUCCESS); ASSERT_NE(HITLS_X509_CsrCtrl(csr, HITLS_X509_CSR_GET_ATTRIBUTES, &attrs, 0), HITLS_PKI_SUCCESS); EXIT: BSL_SAL_FREE(encodeRaw.data); HITLS_X509_CsrFree(csr); } /* END_CASE */ /** * 1. csr ctrl interface test */ /* BEGIN_CASE */ void SDV_X509_CSR_CTRL_SET_API_TC002(char *csrPath) { TestMemInit(); TestRandInit(); HITLS_X509_Csr *csr = NULL; CRYPT_EAL_PkeyCtx *rsaPkey = NULL; CRYPT_EAL_PkeyCtx *eccPkey = NULL; uint8_t e[] = {1, 0, 1}; int32_t ret = HITLS_X509_CsrParseFile(BSL_FORMAT_ASN1, csrPath, &csr); ASSERT_EQ(ret, HITLS_PKI_SUCCESS); rsaPkey = CRYPT_EAL_PkeyNewCtx(CRYPT_PKEY_RSA); ASSERT_NE(rsaPkey, NULL); CRYPT_EAL_PkeyPara rsaPara = {0}; SetRsaPara(&rsaPara, e, sizeof(e), 2048); // 2048 is rsa key bits ASSERT_EQ(CRYPT_EAL_PkeySetPara(rsaPkey, &rsaPara), CRYPT_SUCCESS); ASSERT_EQ(CRYPT_EAL_PkeyGen(rsaPkey), CRYPT_SUCCESS); ASSERT_NE(HITLS_X509_CsrCtrl(csr, HITLS_X509_SET_PUBKEY, NULL, 0), HITLS_PKI_SUCCESS); ASSERT_NE(HITLS_X509_CsrCtrl(NULL, HITLS_X509_SET_PUBKEY, rsaPkey, 0), HITLS_PKI_SUCCESS); EXIT: HITLS_X509_CsrFree(csr); CRYPT_EAL_PkeyFreeCtx(rsaPkey); CRYPT_EAL_PkeyFreeCtx(eccPkey); TestRandDeInit(); } /* END_CASE */ /** * 1. csr ctrl interface test */ /* BEGIN_CASE */ void SDV_X509_CSR_CTRL_FUNC_TC001(char *csrPath) { TestMemInit(); TestRandInit(); BSL_Buffer encodeRaw = { NULL, 0}; HITLS_X509_Csr *csr = NULL; uint8_t *csrEncode = NULL; uint32_t csrEncodeLen = 0; CRYPT_EAL_PkeyCtx *pkey = NULL; uint8_t e[] = {1, 0, 1}; HITLS_X509_Csr *newCsr = NULL; ASSERT_EQ(BSL_SAL_ReadFile(csrPath, &encodeRaw.data, &encodeRaw.dataLen), HITLS_PKI_SUCCESS); ASSERT_NE(encodeRaw.data, NULL); ASSERT_EQ(HITLS_X509_CsrParseBuff(BSL_FORMAT_ASN1, &encodeRaw, &csr), HITLS_PKI_SUCCESS); ASSERT_EQ(HITLS_X509_CsrCtrl(csr, HITLS_X509_GET_ENCODE, &csrEncode, 0), HITLS_PKI_SUCCESS); ASSERT_EQ(HITLS_X509_CsrCtrl(csr, HITLS_X509_GET_ENCODELEN, &csrEncodeLen, sizeof(csrEncodeLen)), HITLS_PKI_SUCCESS); ASSERT_EQ(csrEncodeLen, encodeRaw.dataLen); ASSERT_EQ(memcmp(encodeRaw.data, csrEncode, encodeRaw.dataLen), 0); int32_t ref = 0; ASSERT_EQ(HITLS_X509_CsrCtrl(csr, HITLS_X509_REF_UP, &ref, sizeof(ref)), HITLS_PKI_SUCCESS); ASSERT_EQ(ref, 2); HITLS_X509_CsrFree(csr); newCsr = HITLS_X509_CsrNew(); ASSERT_NE(newCsr, NULL); pkey = CRYPT_EAL_PkeyNewCtx(CRYPT_PKEY_RSA); ASSERT_NE(pkey, NULL); CRYPT_EAL_PkeyPara para = {0}; SetRsaPara(&para, e, sizeof(e), 2048); // 2048 is rsa key bits ASSERT_EQ(CRYPT_EAL_PkeySetPara(pkey, &para), CRYPT_SUCCESS); ASSERT_EQ(CRYPT_EAL_PkeyGen(pkey), CRYPT_SUCCESS); ASSERT_EQ(HITLS_X509_CsrCtrl(newCsr, HITLS_X509_SET_PUBKEY, pkey, 0), HITLS_PKI_SUCCESS); ASSERT_EQ(HITLS_X509_CsrCtrl(newCsr, HITLS_X509_GET_ENCODELEN, &csrEncodeLen, sizeof(csrEncodeLen)), HITLS_PKI_SUCCESS); EXIT: BSL_SAL_FREE(encodeRaw.data); HITLS_X509_CsrFree(csr); HITLS_X509_CsrFree(newCsr); CRYPT_EAL_PkeyFreeCtx(pkey); TestRandDeInit(); } /* END_CASE */ /* BEGIN_CASE */ void SDV_X509_CSR_AttrCtrl_API_TC001(void) { TestMemInit(); HITLS_X509_Ext *getExt = NULL; HITLS_X509_Ext *ext = HITLS_X509_ExtNew(HITLS_X509_EXT_TYPE_CSR); ASSERT_NE(ext, NULL); HITLS_X509_ExtKeyUsage ku = {0, HITLS_X509_EXT_KU_NON_REPUDIATION}; int32_t cmd = HITLS_X509_ATTR_SET_REQUESTED_EXTENSIONS; HITLS_X509_Attrs *attrs = NULL; HITLS_X509_Csr *csr = HITLS_X509_CsrNew(); ASSERT_NE(csr, NULL); ASSERT_EQ(HITLS_X509_ExtCtrl(ext, HITLS_X509_EXT_SET_KUSAGE, &ku, sizeof(HITLS_X509_ExtKeyUsage)), 0); ASSERT_EQ(HITLS_X509_CsrCtrl(csr, HITLS_X509_CSR_GET_ATTRIBUTES, &attrs, sizeof(HITLS_X509_Attrs *)), 0); // invalid param ASSERT_EQ(HITLS_X509_AttrCtrl(NULL, cmd, ext, 0), HITLS_X509_ERR_INVALID_PARAM); ASSERT_EQ(HITLS_X509_AttrCtrl(attrs, -1, ext, 0), HITLS_X509_ERR_INVALID_PARAM); ASSERT_EQ(HITLS_X509_AttrCtrl(attrs, cmd, NULL, 0), HITLS_X509_ERR_INVALID_PARAM); // encode ext failed ext->extList->count = 2; ASSERT_EQ(HITLS_X509_AttrCtrl(attrs, cmd, ext, 0), BSL_INVALID_ARG); ext->extList->count = 1; // success ASSERT_EQ(HITLS_X509_AttrCtrl(attrs, cmd, ext, 0), HITLS_PKI_SUCCESS); // repeat ASSERT_EQ(HITLS_X509_AttrCtrl(attrs, cmd, ext, 0), HITLS_X509_ERR_SET_ATTR_REPEAT); // get attr ASSERT_EQ(HITLS_X509_AttrCtrl(attrs, HITLS_X509_ATTR_GET_REQUESTED_EXTENSIONS, &getExt, sizeof(HITLS_X509_Ext *)), HITLS_PKI_SUCCESS); ASSERT_NE(getExt, NULL); HITLS_X509_CertExt *certExt = (HITLS_X509_CertExt *)getExt->extData; ASSERT_EQ(certExt->keyUsage, HITLS_X509_EXT_KU_NON_REPUDIATION); // not found X509_ExtFree(getExt, true); getExt = NULL; BSL_LIST_DeleteAll(attrs->list, (BSL_LIST_PFUNC_FREE)HITLS_X509_AttrEntryFree); ASSERT_EQ(HITLS_X509_AttrCtrl(attrs, HITLS_X509_ATTR_GET_REQUESTED_EXTENSIONS, &getExt, sizeof(HITLS_X509_Ext *)), HITLS_X509_ERR_ATTR_NOT_FOUND); EXIT: HITLS_X509_CsrFree(csr); HITLS_X509_ExtFree(ext); X509_ExtFree(getExt, true); } /* END_CASE */ /* BEGIN_CASE */ void SDV_X509_CSR_EncodeAttrList_FUNC_TC001(int critical1, int maxPath, int critical2, int keyUsage, Hex *expect) { TestMemInit(); HITLS_X509_Ext *ext = HITLS_X509_ExtNew(HITLS_X509_EXT_TYPE_CSR); ASSERT_NE(ext, NULL); HITLS_X509_Attrs *attrs = NULL; HITLS_X509_ExtBCons bCons = {critical1, false, maxPath}; HITLS_X509_ExtKeyUsage ku = {critical2, keyUsage}; BSL_ASN1_Buffer encode = {0}; HITLS_X509_Csr *csr = HITLS_X509_CsrNew(); ASSERT_NE(csr, NULL); ASSERT_EQ(HITLS_X509_CsrCtrl(csr, HITLS_X509_CSR_GET_ATTRIBUTES, &attrs, sizeof(HITLS_X509_Attrs *)), 0); ASSERT_NE(attrs, NULL); // Generate ext ASSERT_EQ(HITLS_X509_ExtCtrl(ext, HITLS_X509_EXT_SET_KUSAGE, &ku, sizeof(HITLS_X509_ExtKeyUsage)), 0); ASSERT_EQ(HITLS_X509_ExtCtrl(ext, HITLS_X509_EXT_SET_BCONS, &bCons, sizeof(HITLS_X509_ExtBCons)), 0); // Set ext into attr ASSERT_EQ(HITLS_X509_AttrCtrl(attrs, HITLS_X509_ATTR_SET_REQUESTED_EXTENSIONS, ext, 0), 0); // Test: Encode and check ASSERT_EQ(HITLS_X509_EncodeAttrList(1, attrs, NULL, &encode), 0); ASSERT_COMPARE("Encode attrs", expect->x, expect->len, encode.buff, encode.len); EXIT: HITLS_X509_CsrFree(csr); BSL_SAL_Free(encode.buff); HITLS_X509_ExtFree(ext); } /* END_CASE */ /* BEGIN_CASE */ void SDV_X509_CSR_EncodeAttrList_FUNC_TC002(void) { TestMemInit(); HITLS_X509_Ext *ext = HITLS_X509_ExtNew(HITLS_X509_EXT_TYPE_CSR); HITLS_X509_Attrs *attrs = NULL; HITLS_X509_ExtKeyUsage ku = {0, HITLS_X509_EXT_KU_NON_REPUDIATION}; BSL_ASN1_Buffer encode = {0}; HITLS_X509_Csr *csr = HITLS_X509_CsrNew(); ASSERT_NE(ext, NULL); ASSERT_NE(csr, NULL); ASSERT_EQ(HITLS_X509_CsrCtrl(csr, HITLS_X509_CSR_GET_ATTRIBUTES, &attrs, sizeof(HITLS_X509_Attrs *)), 0); ASSERT_NE(attrs->list, NULL); ASSERT_EQ(HITLS_X509_ExtCtrl(ext, HITLS_X509_EXT_SET_KUSAGE, &ku, sizeof(HITLS_X509_ExtKeyUsage)), 0); // Test 1: no attr ASSERT_EQ(HITLS_X509_EncodeAttrList(1, attrs, NULL, &encode), 0); ASSERT_EQ(encode.buff, NULL); ASSERT_EQ(encode.len, 0); // Test 2: encode attr entry failed attrs->list->count = 1; ASSERT_EQ(HITLS_X509_EncodeAttrList(1, attrs, NULL, &encode), BSL_INVALID_ARG); // Set ext into attr ASSERT_EQ(HITLS_X509_AttrCtrl(attrs, HITLS_X509_ATTR_SET_REQUESTED_EXTENSIONS, ext, 0), 0); // Test 3: encode list item failed ASSERT_EQ(HITLS_X509_EncodeAttrList(1, attrs, NULL, &encode), BSL_INVALID_ARG); EXIT: HITLS_X509_CsrFree(csr); HITLS_X509_ExtFree(ext); } /* END_CASE */ /* BEGIN_CASE */ void SDV_X509_CSR_ParseAttrList_FUNC_TC001(Hex *encode, int ret) { TestMemInit(); BSL_ASN1_Buffer attrsBuff = {0, encode->len, encode->x}; HITLS_X509_Attrs *attrs = NULL; HITLS_X509_Csr *csr = HITLS_X509_CsrNew(); csr->flag = 0x01; // HITLS_X509_CSR_PARSE_FLAG ASSERT_NE(csr, NULL); ASSERT_EQ(HITLS_X509_CsrCtrl(csr, HITLS_X509_CSR_GET_ATTRIBUTES, &attrs, sizeof(HITLS_X509_Attrs *)), 0); ASSERT_NE(attrs, NULL); attrsBuff.tag = BSL_ASN1_TAG_CONSTRUCTED | BSL_ASN1_TAG_SEQUENCE; ASSERT_EQ(HITLS_X509_ParseAttrList(&attrsBuff, attrs, NULL, NULL), ret); EXIT: HITLS_X509_CsrFree(csr); } /* END_CASE */ static void SetX509Dn(HITLS_X509_DN *dnName, int dnType, char *dnNameStr) { dnName->cid = (BslCid)dnType; dnName->data = (uint8_t *)dnNameStr; dnName->dataLen = strlen(dnNameStr); } static int32_t SetNewCsrInfo(HITLS_X509_Csr *new, CRYPT_EAL_PkeyCtx *key, int dnType1, char *dnName1, int dnType2, char *dnName2, int dnType3, char *dnName3) { int32_t ret = 1; ASSERT_EQ(HITLS_X509_CsrCtrl(new, HITLS_X509_SET_PUBKEY, key, sizeof(CRYPT_EAL_PkeyCtx *)), 0); HITLS_X509_DN dnName[3] = {0}; int dnTypes[3] = {dnType1, dnType2, dnType3}; char *dnNameStr[3] = {dnName1, dnName2, dnName3}; for (int i = 0; i < 3; i++) { SetX509Dn(&dnName[i], dnTypes[i], dnNameStr[i]); ASSERT_EQ(HITLS_X509_CsrCtrl(new, HITLS_X509_ADD_SUBJECT_NAME, &dnName[i], 1), HITLS_PKI_SUCCESS); } BslList *subjectName = 0; ASSERT_EQ(HITLS_X509_CsrCtrl(new, HITLS_X509_GET_SUBJECT_DN, &subjectName, sizeof(BslList *)), HITLS_PKI_SUCCESS); ASSERT_EQ(BSL_LIST_COUNT(subjectName), 6); ASSERT_EQ(HITLS_X509_CsrCtrl(new, HITLS_X509_ADD_SUBJECT_NAME, dnName, 3), HITLS_PKI_SUCCESS); ASSERT_EQ(BSL_LIST_COUNT(subjectName), 10); ret = 0; EXIT: return ret; } /* BEGIN_CASE */ void SDV_X509_CSR_AddSubjectName_FUNC_TC001(int keyFormat, int keyType, char *privPath, int mdId, int dnType1, char *dnName1, int dnType2, char *dnName2, int dnType3, char *dnName3, Hex *expectedReqInfo) { TestMemInit(); TestRandInit(); HITLS_X509_Csr *new = NULL; CRYPT_EAL_PkeyCtx *privKey = NULL; BSL_Buffer encode = {NULL, 0}; ASSERT_EQ(CRYPT_EAL_DecodeFileKey(keyFormat, keyType, privPath, NULL, 0, &privKey), HITLS_PKI_SUCCESS); new = HITLS_X509_CsrNew(); ASSERT_NE(new, NULL); ASSERT_EQ(SetNewCsrInfo(new, privKey, dnType1, dnName1, dnType2, dnName2, dnType3, dnName3), 0); ASSERT_EQ(HITLS_X509_CsrSign(mdId, privKey, NULL, new), HITLS_PKI_SUCCESS); ASSERT_EQ(HITLS_X509_CsrGenBuff(BSL_FORMAT_PEM, new, &encode), HITLS_PKI_SUCCESS); ASSERT_EQ(new->reqInfo.reqInfoRawDataLen, expectedReqInfo->len); ASSERT_EQ(memcmp(new->reqInfo.reqInfoRawData, expectedReqInfo->x, expectedReqInfo->len), 0); // error length HITLS_X509_DN dnNameErr[1] = {{BSL_CID_AT_COUNTRYNAME, (uint8_t *)"CNNN", strlen("CNNN")}}; ASSERT_EQ(HITLS_X509_CsrCtrl(new, HITLS_X509_ADD_SUBJECT_NAME, dnNameErr, 1), HITLS_X509_ERR_SET_DNNAME_INVALID_LEN); EXIT: HITLS_X509_CsrFree(new); BSL_SAL_FREE(encode.data); CRYPT_EAL_PkeyFreeCtx(privKey); } /* END_CASE */ /* BEGIN_CASE */ void SDV_X509_CSR_PARSE_FUNC_TC004(int format, char *path, int expectedRet) { TestMemInit(); HITLS_X509_Csr *csr = NULL; ASSERT_EQ(HITLS_X509_CsrParseFile(format, path, &csr), expectedRet); EXIT: HITLS_X509_CsrFree(csr); } /* END_CASE */
2301_79861745/bench_create
testcode/sdv/testcase/pki/csr/test_suite_sdv_x509_csr.c
C
unknown
34,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 "bsl_sal.h" #include "securec.h" #include "hitls_pki_pkcs12.h" #include "hitls_pki_errno.h" #include "bsl_types.h" #include "bsl_log.h" #include "sal_file.h" #include "bsl_init.h" #include "hitls_pkcs12_local.h" #include "hitls_crl_local.h" #include "hitls_cert_type.h" #include "hitls_cert_local.h" #include "bsl_types.h" #include "crypt_errno.h" #include "stub_replace.h" #include "bsl_list_internal.h" /* END_HEADER */ /** * For test parse safeBag-p8shroudkeyBag of correct data. */ /* BEGIN_CASE */ void SDV_PKCS12_PARSE_SAFEBAGS_OF_PKCS8SHROUDEDKEYBAG_TC001(int algId, Hex *buff, int keyBits) { #ifndef HITLS_PKI_PKCS12_PARSE (void)algId; (void)buff; (void)keyBits; SKIP_TEST(); #else BSL_Buffer safeContent = {0}; char *pwd = "123456"; uint32_t len = strlen(pwd); int32_t bits = 0; TestMemInit(); BSL_ASN1_List *bagLists = BSL_LIST_New(sizeof(HITLS_PKCS12_SafeBag)); HITLS_PKCS12 *p12 = HITLS_PKCS12_New(); ASSERT_NE(bagLists, NULL); ASSERT_NE(p12, NULL); // parse contentInfo int32_t ret = HITLS_PKCS12_ParseContentInfo(NULL, NULL, (BSL_Buffer *)buff, NULL, 0, &safeContent); ASSERT_EQ(ret, HITLS_PKI_SUCCESS); // get the safeBag of safeContents, and put in list. ret = HITLS_PKCS12_ParseAsn1AddList(&safeContent, bagLists, BSL_CID_SAFECONTENTSBAG); ASSERT_EQ(ret, HITLS_PKI_SUCCESS); // get key of the bagList. ret = HITLS_PKCS12_ParseSafeBagList(bagLists, (const uint8_t *)pwd, len, p12); ASSERT_EQ(ret, HITLS_PKI_SUCCESS); ASSERT_NE(p12->key->value.key, NULL); bits = CRYPT_EAL_PkeyGetKeyBits(p12->key->value.key); if (algId == CRYPT_PKEY_ECDSA) { ASSERT_EQ(((((keyBits - 1) / 8) + 1) * 2 + 1) * 8, bits); // cal len of pub } else if (algId == CRYPT_PKEY_RSA) { ASSERT_EQ(bits, keyBits); } EXIT: BSL_SAL_Free(safeContent.data); BSL_LIST_DeleteAll(bagLists, (BSL_LIST_PFUNC_FREE)HITLS_PKCS12_SafeBagFree); BSL_SAL_Free(bagLists); HITLS_PKCS12_Free(p12); #endif } /* END_CASE */ /** * For test parse safeBag-cert of correct data. */ /* BEGIN_CASE */ void SDV_PKCS12_PARSE_SAFEBAGS_OF_CERTBAGS_TC001(Hex *buff) { #ifndef HITLS_PKI_PKCS12_PARSE (void)buff; SKIP_TEST(); #else BSL_Buffer safeContent = {0}; HITLS_PKCS12 *p12 = NULL; BSL_ASN1_List *bagLists = BSL_LIST_New(sizeof(HITLS_PKCS12_SafeBag)); ASSERT_NE(bagLists, NULL); p12 = HITLS_PKCS12_New(); ASSERT_NE(p12, NULL); char *pwd = "123456"; uint32_t pwdlen = strlen(pwd); // parse contentInfo int32_t ret = HITLS_PKCS12_ParseContentInfo(NULL, NULL, (BSL_Buffer *)buff, (const uint8_t *)pwd, pwdlen, &safeContent); ASSERT_EQ(ret, HITLS_PKI_SUCCESS); // get the safeBag of safeContents, and put int list. ret = HITLS_PKCS12_ParseAsn1AddList(&safeContent, bagLists, BSL_CID_SAFECONTENTSBAG); ASSERT_EQ(ret, HITLS_PKI_SUCCESS); // get cert of the bagList. ret = HITLS_PKCS12_ParseSafeBagList(bagLists, NULL, 0, p12); ASSERT_EQ(ret, HITLS_PKI_SUCCESS); EXIT: BSL_SAL_Free(safeContent.data); BSL_LIST_DeleteAll(bagLists, (BSL_LIST_PFUNC_FREE)HITLS_PKCS12_SafeBagFree); HITLS_PKCS12_Free(p12); BSL_SAL_Free(bagLists); #endif } /* END_CASE */ /** * For test parse attributes of correct data. */ /* BEGIN_CASE */ void SDV_PKCS12_PARSE_SAFEBAGS_OF_ATTRIBUTE_TC001(Hex *buff, Hex *friendlyName, Hex *localKeyId) { #ifndef HITLS_PKI_PKCS12_PARSE (void)buff; (void)friendlyName; (void)localKeyId; SKIP_TEST(); #else HITLS_X509_Attrs *attrbutes = HITLS_X509_AttrsNew(); ASSERT_NE(attrbutes, NULL); BSL_ASN1_Buffer asn = { BSL_ASN1_TAG_CONSTRUCTED | BSL_ASN1_TAG_SET, buff->len, buff->x, }; int32_t ret = HITLS_PKCS12_ParseSafeBagAttr(&asn, attrbutes); ASSERT_EQ(ret, HITLS_PKI_SUCCESS); HITLS_PKCS12_SafeBagAttr *firstAttr = BSL_LIST_GET_FIRST(attrbutes->list); HITLS_PKCS12_SafeBagAttr *second = BSL_LIST_GET_NEXT(attrbutes->list); if (firstAttr->attrId == BSL_CID_FRIENDLYNAME) { BSL_ASN1_Buffer asn = {BSL_ASN1_TAG_BMPSTRING, (uint32_t)friendlyName->len, friendlyName->x}; BSL_ASN1_Buffer encode = {0}; ret = BSL_ASN1_DecodePrimitiveItem(&asn, &encode); ASSERT_EQ(ret, BSL_SUCCESS); ASSERT_COMPARE("friendly name", firstAttr->attrValue.data, firstAttr->attrValue.dataLen, encode.buff, encode.len); BSL_SAL_FREE(encode.buff); } if (firstAttr->attrId == BSL_CID_LOCALKEYID) { ASSERT_EQ(memcmp(firstAttr->attrValue.data, localKeyId->x, localKeyId->len), 0); } if (second == NULL) { ASSERT_EQ(friendlyName->len, 0); } else { if (second->attrId == BSL_CID_FRIENDLYNAME) { BSL_ASN1_Buffer asn = {BSL_ASN1_TAG_BMPSTRING, (uint32_t)friendlyName->len, friendlyName->x}; BSL_ASN1_Buffer encode = {0}; ret = BSL_ASN1_DecodePrimitiveItem(&asn, &encode); ASSERT_EQ(ret, BSL_SUCCESS); ASSERT_COMPARE("friendly name", firstAttr->attrValue.data, firstAttr->attrValue.dataLen, encode.buff, encode.len); BSL_SAL_FREE(encode.buff); } if (second->attrId == BSL_CID_LOCALKEYID) { ASSERT_EQ(memcmp(second->attrValue.data, localKeyId->x, localKeyId->len), 0); } } EXIT: HITLS_X509_AttrsFree(attrbutes, HITLS_PKCS12_AttributesFree); #endif } /* END_CASE */ /** * For test parse attributes in the incorrect condition. */ /* BEGIN_CASE */ void SDV_PKCS12_PARSE_SAFEBAGS_OF_ATTRIBUTE_TC002(Hex *buff) { #ifndef HITLS_PKI_PKCS12_PARSE (void)buff; SKIP_TEST(); #else HITLS_X509_Attrs *attrbutes = HITLS_X509_AttrsNew(); ASSERT_NE(attrbutes, NULL); BSL_ASN1_Buffer asn = { BSL_ASN1_TAG_CONSTRUCTED | BSL_ASN1_TAG_SET, 0, buff->x, }; int32_t ret = HITLS_PKCS12_ParseSafeBagAttr(&asn, attrbutes); ASSERT_EQ(ret, HITLS_PKI_SUCCESS); // bagAttributes are OPTIONAL asn.len = buff->len; ret = HITLS_PKCS12_ParseSafeBagAttr(&asn, attrbutes); ASSERT_EQ(ret, HITLS_PKI_SUCCESS); buff->x[4] = 0x00; // 4 is a random number. ret = HITLS_PKCS12_ParseSafeBagAttr(&asn, attrbutes); ASSERT_NE(ret, HITLS_PKI_SUCCESS); EXIT: HITLS_X509_AttrsFree(attrbutes, HITLS_PKCS12_AttributesFree); #endif } /* END_CASE */ /** * For test parse authSafedata of tampering Cert-info with encrypted data. */ /* BEGIN_CASE */ void SDV_PKCS12_PARSE_AUTHSAFE_TC001(Hex *wrongCert) { #ifndef HITLS_PKI_PKCS12_PARSE (void)wrongCert; SKIP_TEST(); #else char *pwd = "123456"; uint32_t pwdlen = strlen(pwd); // parse authSafe HITLS_PKCS12 *p12 = HITLS_PKCS12_New(); int32_t ret = HITLS_PKCS12_ParseAuthSafeData((BSL_Buffer *)wrongCert, (const uint8_t *)pwd, pwdlen, p12); ASSERT_NE(ret, HITLS_PKI_SUCCESS); char *pwd1 = "123456-789"; uint32_t pwdlen1 = strlen(pwd1); ret = HITLS_PKCS12_ParseAuthSafeData((BSL_Buffer *)wrongCert, (const uint8_t *)pwd1, pwdlen1, p12); ASSERT_EQ(ret, CRYPT_EAL_CIPHER_DATA_ERROR); char *pwd2 = ""; uint32_t pwdlen2 = strlen(pwd2); ret = HITLS_PKCS12_ParseAuthSafeData((BSL_Buffer *)wrongCert, (const uint8_t *)pwd2, pwdlen2, p12); ASSERT_EQ(ret, CRYPT_EAL_CIPHER_DATA_ERROR); EXIT: HITLS_PKCS12_Free(p12); #endif } /* END_CASE */ /** * For test parse authSafedata of correct data. */ /* BEGIN_CASE */ void SDV_PKCS12_PARSE_AUTHSAFE_TC002(Hex *buff) { #ifndef HITLS_PKI_PKCS12_PARSE (void)buff; SKIP_TEST(); #else HITLS_PKCS12 *p12 = HITLS_PKCS12_New(); char *pwd = "123456"; uint32_t pwdlen = strlen(pwd); // parse authSafe int32_t ret = HITLS_PKCS12_ParseAuthSafeData((BSL_Buffer *)buff, (const uint8_t *)pwd, pwdlen, p12); ASSERT_EQ(ret, HITLS_PKI_SUCCESS); ASSERT_NE(p12->key->value.key, NULL); ASSERT_NE(p12->entityCert->value.cert, NULL); EXIT: HITLS_PKCS12_Free(p12); #endif } /* END_CASE */ /** * For test parse 12 of macData parse. */ /* BEGIN_CASE */ void SDV_PKCS12_PARSE_MACDATA_TC001(Hex *buff, int alg, Hex *digest, Hex *salt, int iterations) { #ifndef HITLS_PKI_PKCS12_PARSE (void)buff; (void)alg; (void)digest; (void)salt; (void)iterations; SKIP_TEST(); #else HITLS_PKCS12_MacData *macData = HITLS_PKCS12_MacDataNew(); int32_t ret = HITLS_PKCS12_ParseMacData((BSL_Buffer *)buff, macData); ASSERT_EQ(ret, HITLS_PKI_SUCCESS); ASSERT_EQ(macData->alg, alg); ASSERT_EQ(macData->iteration, iterations); ASSERT_EQ(memcmp(macData->macSalt->data, salt->x, salt->len), 0); ASSERT_EQ(memcmp(macData->mac->data, digest->x, digest->len), 0); EXIT: HITLS_PKCS12_MacDataFree(macData); #endif } /* END_CASE */ /** * For test parse 12 of wrong macData parse. */ /* BEGIN_CASE */ void SDV_PKCS12_PARSE_MACDATA_TC002(Hex *buff) { #ifndef HITLS_PKI_PKCS12_PARSE (void)buff; SKIP_TEST(); #else HITLS_PKCS12_MacData *macData = HITLS_PKCS12_MacDataNew(); int32_t ret = HITLS_PKCS12_ParseMacData(NULL, macData); ASSERT_EQ(ret, HITLS_PKCS12_ERR_NULL_POINTER); ret = HITLS_PKCS12_ParseMacData((BSL_Buffer *)buff, macData); ASSERT_EQ(ret, HITLS_CMS_ERR_PARSE_TYPE); EXIT: HITLS_PKCS12_MacDataFree(macData); #endif } /* END_CASE */ /** * For test parse 12 of macData cal. */ /* BEGIN_CASE */ void SDV_PKCS12_CAL_MACDATA_TC001(Hex *initData, Hex *salt, int alg, int iter, Hex *mac) { TestMemInit(); HITLS_PKCS12 *p12 = HITLS_PKCS12_New(); ASSERT_NE(p12, NULL); BSL_Buffer output = {0}; HITLS_PKCS12_MacData *macData = p12->macData; macData->alg = alg; macData->macSalt->data = BSL_SAL_Dump(salt->x, salt->len); ASSERT_NE(macData->macSalt->data, NULL); macData->macSalt->dataLen = salt->len; macData->iteration = iter; char *pwdData = "123456"; uint32_t pwdlen = strlen(pwdData); BSL_Buffer pwd = {(uint8_t *)pwdData, pwdlen}; int32_t ret = HITLS_PKCS12_CalMac(p12, &pwd, (BSL_Buffer *)initData, &output); ASSERT_EQ(ret, HITLS_PKI_SUCCESS); ASSERT_EQ(memcmp(output.data, mac->x, mac->len), 0); EXIT: BSL_SAL_Free(output.data); HITLS_PKCS12_Free(p12); } /* END_CASE */ /** * For test cal key according to salt, alg, etc. */ /* BEGIN_CASE */ void SDV_PKCS12_CAL_KDF_TC001(Hex *pwd, Hex *salt, int alg, int iter, Hex *key) { TestMemInit(); HITLS_PKCS12 *p12 = HITLS_PKCS12_New(); ASSERT_NE(p12, NULL); HITLS_PKCS12_MacData *macData = p12->macData; macData->alg = alg; macData->macSalt->data = BSL_SAL_Dump(salt->x, salt->len); ASSERT_NE(macData->macSalt->data, NULL); macData->macSalt->dataLen = salt->len; macData->iteration = iter; uint8_t outData[64] = {0}; BSL_Buffer output = {outData, 64}; int32_t ret = HITLS_PKCS12_KDF(p12, pwd->x, pwd->len, HITLS_PKCS12_KDF_MACKEY_ID, &output); ASSERT_EQ(ret, HITLS_PKI_SUCCESS); ASSERT_EQ(memcmp(output.data, key->x, key->len), 0); EXIT: HITLS_PKCS12_Free(p12); return; } /* END_CASE */ /** * For test parse 12 of right conditions. */ /* BEGIN_CASE */ void SDV_PKCS12_PARSE_P12_TC001(Hex *encode, Hex *cert) { (void)cert; #ifndef HITLS_PKI_PKCS12_PARSE (void)encode; SKIP_TEST(); #else char *pwd = "123456"; BSL_Buffer encPwd; encPwd.data = (uint8_t *)pwd; encPwd.dataLen = strlen(pwd); BSL_Buffer encodeCert = {0}; HITLS_PKCS12 *p12 = NULL; HITLS_PKCS12_PwdParam param = { .encPwd = &encPwd, .macPwd = &encPwd, }; TestMemInit(); ASSERT_EQ(HITLS_PKCS12_ParseBuff(BSL_FORMAT_ASN1, (BSL_Buffer *)encode, &param, &p12, true), HITLS_PKI_SUCCESS); ASSERT_NE(p12->key->value.key, NULL); ASSERT_NE(p12->entityCert->value.cert, NULL); #ifdef HITLS_PKI_PKCS12_GEN ASSERT_EQ(HITLS_X509_CertGenBuff(BSL_FORMAT_ASN1, p12->entityCert->value.cert, &encodeCert), HITLS_PKI_SUCCESS); ASSERT_EQ(memcmp(encodeCert.data, cert->x, cert->len), 0); #endif EXIT: BSL_SAL_Free(encodeCert.data); HITLS_PKCS12_Free(p12); #endif } /* END_CASE */ /** * For test parse 12 of right conditions (no Mac). */ /* BEGIN_CASE */ void SDV_PKCS12_PARSE_P12_TC002(Hex *encode, Hex *cert) { (void)cert; #ifndef HITLS_PKI_PKCS12_PARSE (void)encode; SKIP_TEST(); #else char *pwd = "123456"; BSL_Buffer encPwd; encPwd.data = (uint8_t *)pwd; encPwd.dataLen = strlen(pwd); BSL_Buffer encodeCert = {0}; HITLS_PKCS12 *p12 = NULL; HITLS_PKCS12_PwdParam param = { .encPwd = &encPwd, }; TestMemInit(); ASSERT_NE(HITLS_PKCS12_ParseBuff(BSL_FORMAT_ASN1, (BSL_Buffer *)encode, &param, &p12, true), HITLS_PKI_SUCCESS); ASSERT_EQ(HITLS_PKCS12_ParseBuff(BSL_FORMAT_ASN1, (BSL_Buffer *)encode, &param, &p12, false), HITLS_PKI_SUCCESS); ASSERT_NE(p12->key->value.key, NULL); ASSERT_NE(p12->entityCert->value.cert, NULL); #ifdef HITLS_PKI_PKCS12_GEN ASSERT_EQ(HITLS_X509_CertGenBuff(BSL_FORMAT_ASN1, p12->entityCert->value.cert, &encodeCert), HITLS_PKI_SUCCESS); ASSERT_EQ(memcmp(encodeCert.data, cert->x, cert->len), 0); #endif EXIT: BSL_SAL_Free(encodeCert.data); HITLS_PKCS12_Free(p12); #endif } /* END_CASE */ /** * For test parse 12 of right conditions (different keys). */ /* BEGIN_CASE */ void SDV_PKCS12_PARSE_P12_TC003(char *path, char *pwd) { #if !defined(HITLS_PKI_PKCS12_PARSE) || !defined(HITLS_BSL_SAL_FILE) (void)path; (void)pwd; SKIP_TEST(); #else BSL_Buffer encPwd; encPwd.data = (uint8_t *)pwd; encPwd.dataLen = strlen(pwd); HITLS_PKCS12 *p12 = NULL; HITLS_PKCS12_PwdParam param = { .encPwd = &encPwd, .macPwd = &encPwd, }; TestMemInit(); int32_t ret = HITLS_PKCS12_ParseFile(BSL_FORMAT_ASN1, path, &param, &p12, true); ASSERT_EQ(ret, HITLS_PKI_SUCCESS); ASSERT_NE(p12->key->value.key, NULL); ASSERT_NE(p12->entityCert->value.cert, NULL); EXIT: HITLS_PKCS12_Free(p12); #endif } /* END_CASE */ /** * For test parse 12 of wrong conditions. */ /* BEGIN_CASE */ void SDV_PKCS12_PARSE_P12_WRONG_CONDITIONS_TC001(Hex *encode) { #ifndef HITLS_PKI_PKCS12_PARSE (void)encode; SKIP_TEST(); #else char *pwd1 = "1234567"; char *pwd2 = "1234567"; BSL_Buffer encPwd; encPwd.data = (uint8_t *)pwd1; encPwd.dataLen = strlen(pwd1); BSL_Buffer macPwd; macPwd.data = (uint8_t *)pwd2; macPwd.dataLen = strlen(pwd2); HITLS_PKCS12 *p12 = NULL; HITLS_PKCS12_PwdParam param = { .encPwd = &encPwd, .macPwd = &macPwd, }; TestMemInit(); int32_t ret = HITLS_PKCS12_ParseBuff(BSL_FORMAT_ASN1, NULL, &param, &p12, true); ASSERT_EQ(ret, HITLS_PKCS12_ERR_NULL_POINTER); ret = HITLS_PKCS12_ParseBuff(BSL_FORMAT_ASN1, (BSL_Buffer *)encode, NULL, &p12, true); ASSERT_EQ(ret, HITLS_PKCS12_ERR_NULL_POINTER); ret = HITLS_PKCS12_ParseBuff(BSL_FORMAT_ASN1, (BSL_Buffer *)encode, &param, NULL, true); ASSERT_EQ(ret, HITLS_PKCS12_ERR_NULL_POINTER); ret = HITLS_PKCS12_ParseBuff(BSL_FORMAT_ASN1, (BSL_Buffer *)encode, &param, &p12, true); ASSERT_EQ(ret, HITLS_PKCS12_ERR_VERIFY_FAIL); char *pwd3 = ""; macPwd.data = (uint8_t *)pwd3; macPwd.dataLen = strlen(pwd3); param.macPwd = &macPwd; ret = HITLS_PKCS12_ParseBuff(BSL_FORMAT_ASN1, (BSL_Buffer *)encode, &param, &p12, true); ASSERT_EQ(ret, HITLS_PKCS12_ERR_VERIFY_FAIL); param.macPwd = NULL; ret = HITLS_PKCS12_ParseBuff(BSL_FORMAT_ASN1, (BSL_Buffer *)encode, &param, &p12, true); ASSERT_EQ(ret, HITLS_PKCS12_ERR_VERIFY_FAIL); param.encPwd = NULL; ret = HITLS_PKCS12_ParseBuff(BSL_FORMAT_ASN1, (BSL_Buffer *)encode, &param, &p12, true); ASSERT_EQ(ret, HITLS_PKCS12_ERR_NULL_POINTER); char *pwd4 = "123456"; param.encPwd = &encPwd; macPwd.data = (uint8_t *)pwd4; macPwd.dataLen = strlen(pwd4); param.macPwd = &macPwd; ret = HITLS_PKCS12_ParseBuff(BSL_FORMAT_ASN1, (BSL_Buffer *)encode, &param, &p12, true); ASSERT_EQ(ret, CRYPT_EAL_CIPHER_DATA_ERROR); encPwd.data = (uint8_t *)pwd4; encPwd.dataLen = strlen(pwd4); ret = HITLS_PKCS12_ParseBuff(BSL_FORMAT_ASN1, (BSL_Buffer *)encode, &param, &p12, true); ASSERT_EQ(ret, HITLS_PKI_SUCCESS); ret = HITLS_PKCS12_ParseBuff(BSL_FORMAT_ASN1, (BSL_Buffer *)encode, &param, &p12, true); ASSERT_EQ(ret, HITLS_PKCS12_ERR_INVALID_PARAM); HITLS_PKCS12_Free(p12); p12 = NULL; encode->x[6] = 0x04; // Modify the version = 4. ret = HITLS_PKCS12_ParseBuff(BSL_FORMAT_ASN1, (BSL_Buffer *)encode, &param, &p12, true); ASSERT_EQ(ret, HITLS_PKCS12_ERR_INVALID_PFX); EXIT: HITLS_PKCS12_Free(p12); #endif } /* END_CASE */ /** * For test parse 12 of wrong p12-file. */ /* BEGIN_CASE */ void SDV_PKCS12_PARSE_P12_WRONG_P12FILE_TC001(Hex *encode) { #ifndef HITLS_PKI_PKCS12_PARSE (void)encode; SKIP_TEST(); #else char *pwd1 = "123456"; char *pwd2 = "123456"; BSL_Buffer encPwd; encPwd.data = (uint8_t *)pwd1; encPwd.dataLen = strlen(pwd1); BSL_Buffer macPwd; macPwd.data = (uint8_t *)pwd2; macPwd.dataLen = strlen(pwd2); HITLS_PKCS12_PwdParam param = { .encPwd = &encPwd, .macPwd = &macPwd, }; HITLS_PKCS12 *p12_1 = NULL; HITLS_PKCS12 *p12_2 = NULL; TestMemInit(); int32_t ret = HITLS_PKCS12_ParseBuff(BSL_FORMAT_ASN1, (BSL_Buffer *)encode, &param, &p12_1, true); ASSERT_EQ(ret, HITLS_PKI_SUCCESS); encode->x[encode->len - 2] = 0x04; // modify the iteration = 1024; ret = HITLS_PKCS12_ParseBuff(BSL_FORMAT_ASN1, (BSL_Buffer *)encode, &param, &p12_2, true); ASSERT_EQ(ret, HITLS_PKCS12_ERR_VERIFY_FAIL); encode->x[encode->len - 2] = 0x08; // recover the iteration = 2048; (void)memset_s(encode->x + 96, 16, 0, 16); // modify the contentInfo ret = HITLS_PKCS12_ParseBuff(BSL_FORMAT_ASN1, (BSL_Buffer *)encode, &param, &p12_2, true); ASSERT_EQ(ret, HITLS_PKCS12_ERR_VERIFY_FAIL); EXIT: HITLS_PKCS12_Free(p12_1); HITLS_PKCS12_Free(p12_2); #endif } /* END_CASE */ /** * For test parse 12 of wrong p12-file, which miss a part of data randomly. */ /* BEGIN_CASE */ void SDV_PKCS12_PARSE_P12_WRONG_P12FILE_TC002(Hex *encode) { #ifndef HITLS_PKI_PKCS12_PARSE (void)encode; SKIP_TEST(); #else char *pwd1 = "123456"; char *pwd2 = "123456"; BSL_Buffer encPwd; encPwd.data = (uint8_t *)pwd1; encPwd.dataLen = strlen(pwd1); BSL_Buffer macPwd; macPwd.data = (uint8_t *)pwd2; macPwd.dataLen = strlen(pwd2); HITLS_PKCS12_PwdParam param = { .encPwd = &encPwd, .macPwd = &macPwd, }; HITLS_PKCS12 *p12 = NULL; TestMemInit(); int32_t ret = HITLS_PKCS12_ParseBuff(BSL_FORMAT_ASN1, (BSL_Buffer *)encode, &param, &p12, true); ASSERT_NE(ret, HITLS_PKI_SUCCESS); ret = HITLS_PKCS12_ParseBuff(BSL_FORMAT_ASN1, (BSL_Buffer *)encode, &param, &p12, false); ASSERT_NE(ret, HITLS_PKI_SUCCESS); EXIT: HITLS_PKCS12_Free(p12); #endif } /* END_CASE */ /** * For test encode safeBag-p8shroudkeyBag of correct data. */ /* BEGIN_CASE */ void SDV_PKCS12_ENCODE_SAFEBAGS_OF_PKCS8SHROUDEDKEYBAG_TC001(Hex *buff) { #if !defined(HITLS_PKI_PKCS12_GEN) || !defined(HITLS_PKI_PKCS12_PARSE) (void)buff; SKIP_TEST(); #else TestMemInit(); ASSERT_EQ(TestRandInit(), 0); char *pwd = "123456"; uint32_t len = strlen(pwd); BSL_Buffer encode = {0}; BSL_ASN1_List *bagLists = BSL_LIST_New(sizeof(HITLS_PKCS12_SafeBag)); HITLS_PKCS12 *p12 = HITLS_PKCS12_New(); BSL_ASN1_List *list = BSL_LIST_New(sizeof(HITLS_PKCS12_Bag)); ASSERT_NE(bagLists, NULL); ASSERT_NE(p12, NULL); ASSERT_NE(list, NULL); // get the safeBag of safeContents, and put in list. int32_t ret = HITLS_PKCS12_ParseAsn1AddList((BSL_Buffer *)buff, bagLists, BSL_CID_SAFECONTENTSBAG); ASSERT_EQ(ret, HITLS_PKI_SUCCESS); // get key of the bagList. ret = HITLS_PKCS12_ParseSafeBagList(bagLists, (const uint8_t *)pwd, len, p12); ASSERT_EQ(ret, HITLS_PKI_SUCCESS); ASSERT_NE(p12->key->value.key, NULL); HITLS_PKCS12_Bag *bag = BSL_SAL_Malloc(sizeof(HITLS_PKCS12_Bag)); bag->attributes = p12->key->attributes; bag->value.key = p12->key->value.key; bag->id = BSL_CID_PKCS8SHROUDEDKEYBAG; ret = BSL_LIST_AddElement(list, bag, BSL_LIST_POS_END); ASSERT_EQ(ret, HITLS_PKI_SUCCESS); CRYPT_Pbkdf2Param param = {0}; param.pbesId = BSL_CID_PBES2; param.pbkdfId = BSL_CID_PBKDF2; param.hmacId = CRYPT_MAC_HMAC_SHA256; param.symId = CRYPT_CIPHER_AES256_CBC; param.pwd = (uint8_t *)pwd; param.saltLen = 16; param.pwdLen = len; param.itCnt = 2048; CRYPT_EncodeParam paramEx = {CRYPT_DERIVE_PBKDF2, &param}; ret = HITLS_PKCS12_EncodeAsn1List(p12, list, BSL_CID_PKCS8SHROUDEDKEYBAG, &paramEx, &encode); ASSERT_EQ(ret, HITLS_PKI_SUCCESS); ASSERT_EQ(encode.dataLen, buff->len); ret = memcmp(encode.data + encode.dataLen - 37, buff->x + buff->len - 37, 37); ASSERT_EQ(ret, 0); EXIT: BSL_SAL_Free(encode.data); BSL_LIST_DeleteAll(bagLists, (BSL_LIST_PFUNC_FREE)HITLS_PKCS12_SafeBagFree); BSL_SAL_Free(bagLists); BSL_LIST_FREE(list, NULL); HITLS_PKCS12_Free(p12); #endif } /* END_CASE */ /** * For test encode encrypted-safecontent. */ /* BEGIN_CASE */ void SDV_PKCS12_ENCODE_SAFEBAGS_OF_CERTBAGS_TC001(Hex *buff) { #if !defined(HITLS_PKI_PKCS12_GEN) || !defined(HITLS_PKI_PKCS12_PARSE) (void)buff; SKIP_TEST(); #else ASSERT_EQ(TestRandInit(), 0); BSL_Buffer encode = {0}; BSL_Buffer safeContent = {0}; BSL_Buffer output = {0}; BSL_ASN1_List *bagLists = BSL_LIST_New(sizeof(HITLS_PKCS12_SafeBag)); HITLS_PKCS12 *p12 = HITLS_PKCS12_New(); ASSERT_NE(bagLists, NULL); ASSERT_NE(p12, NULL); char *pwd = "123456"; uint32_t pwdlen = strlen(pwd); // parse contentInfo int32_t ret = HITLS_PKCS12_ParseContentInfo(NULL, NULL, (BSL_Buffer *)buff, (const uint8_t *)pwd, pwdlen, &safeContent); ASSERT_EQ(ret, HITLS_PKI_SUCCESS); // get the safeBag of safeContents, and put int list. ret = HITLS_PKCS12_ParseAsn1AddList(&safeContent, bagLists, BSL_CID_SAFECONTENTSBAG); ASSERT_EQ(ret, HITLS_PKI_SUCCESS); // get cert of the bagList. ret = HITLS_PKCS12_ParseSafeBagList(bagLists, NULL, 0, p12); ASSERT_EQ(ret, HITLS_PKI_SUCCESS); CRYPT_Pbkdf2Param param = {0}; param.pbesId = BSL_CID_PBES2; param.pbkdfId = BSL_CID_PBKDF2; param.hmacId = CRYPT_MAC_HMAC_SHA256; param.symId = CRYPT_CIPHER_AES256_CBC; param.pwd = (uint8_t *)pwd; param.saltLen = 16; param.pwdLen = pwdlen; param.itCnt = 2048; CRYPT_EncodeParam paramEx = {CRYPT_DERIVE_PBKDF2, &param}; ret = HITLS_PKCS12_EncodeAsn1List(p12, p12->certList, BSL_CID_CERTBAG, &paramEx, &encode); ASSERT_EQ(ret, HITLS_PKI_SUCCESS); ret = HITLS_PKCS12_EncodeContentInfo(NULL, NULL, &encode, BSL_CID_PKCS7_ENCRYPTEDDATA, &paramEx, &output); ASSERT_EQ(ret, HITLS_PKI_SUCCESS); ASSERT_EQ(output.dataLen, buff->len); ret = memcmp(output.data, buff->x, 69); ASSERT_EQ(ret, 0); EXIT: BSL_SAL_Free(safeContent.data); BSL_SAL_Free(encode.data); BSL_SAL_Free(output.data); BSL_LIST_DeleteAll(bagLists, (BSL_LIST_PFUNC_FREE)HITLS_PKCS12_SafeBagFree); HITLS_PKCS12_Free(p12); BSL_SAL_Free(bagLists); #endif } /* END_CASE */ /** * For test encode authSafedata of correct data. */ /* BEGIN_CASE */ void SDV_PKCS12_ENCODE_AUTHSAFE_TC001(Hex *buff) { #if !defined(HITLS_PKI_PKCS12_GEN) || !defined(HITLS_PKI_PKCS12_PARSE) (void)buff; SKIP_TEST(); #else ASSERT_EQ(TestRandInit(), 0); HITLS_PKCS12 *p12 = HITLS_PKCS12_New(); BSL_Buffer *encode1 = BSL_SAL_Calloc(1, sizeof(BSL_Buffer)); BSL_Buffer *encode2 = BSL_SAL_Calloc(1, sizeof(BSL_Buffer)); BSL_Buffer *encode3 = BSL_SAL_Calloc(1, sizeof(BSL_Buffer)); BSL_Buffer *encode4 = BSL_SAL_Calloc(1, sizeof(BSL_Buffer)); BSL_ASN1_List *list = BSL_LIST_New(sizeof(BSL_Buffer)); BSL_ASN1_List *keyList = BSL_LIST_New(sizeof(HITLS_PKCS12_Bag)); BSL_Buffer encode5 = {0}; HITLS_PKCS12_Bag *bagKey = NULL; ASSERT_NE(p12, NULL); ASSERT_NE(encode1, NULL); ASSERT_NE(encode2, NULL); ASSERT_NE(encode3, NULL); ASSERT_NE(encode4, NULL); ASSERT_NE(list, NULL); ASSERT_NE(keyList, NULL); char *pwd = "123456"; uint32_t pwdlen = strlen(pwd); // parse authSafe int32_t ret = HITLS_PKCS12_ParseAuthSafeData((BSL_Buffer *)buff, (const uint8_t *)pwd, pwdlen, p12); ASSERT_EQ(ret, HITLS_PKI_SUCCESS); ASSERT_NE(p12->key->value.key, NULL); ASSERT_NE(p12->entityCert->value.cert, NULL); CRYPT_Pbkdf2Param param = {0}; param.pbesId = BSL_CID_PBES2; param.pbkdfId = BSL_CID_PBKDF2; param.hmacId = CRYPT_MAC_HMAC_SHA256; param.symId = CRYPT_CIPHER_AES256_CBC; param.pwd = (uint8_t *)pwd; param.saltLen = 16; param.pwdLen = pwdlen; param.itCnt = 2048; CRYPT_EncodeParam paramEx = {CRYPT_DERIVE_PBKDF2, &param}; HITLS_PKCS12_Bag *bag = BSL_SAL_Calloc(1u, sizeof(HITLS_PKCS12_Bag)); bag->attributes = p12->entityCert->attributes; bag->value.cert = p12->entityCert->value.cert; bag->id = BSL_CID_CERTBAG; bag->type = BSL_CID_X509CERTIFICATE; ret = BSL_LIST_AddElement(p12->certList, bag, BSL_LIST_POS_BEGIN); ASSERT_EQ(ret, HITLS_PKI_SUCCESS); p12->entityCert->attributes = NULL; p12->entityCert->value.cert = NULL; ret = HITLS_PKCS12_EncodeAsn1List(p12, p12->certList, BSL_CID_CERTBAG, &paramEx, encode1); ASSERT_EQ(ret, HITLS_PKI_SUCCESS); ret = HITLS_PKCS12_EncodeContentInfo(NULL, NULL, encode1, BSL_CID_PKCS7_ENCRYPTEDDATA, &paramEx, encode2); ASSERT_EQ(ret, HITLS_PKI_SUCCESS); bagKey = BSL_SAL_Calloc(1u, sizeof(HITLS_PKCS12_Bag)); bagKey->attributes = p12->key->attributes; bagKey->value = p12->key->value; bagKey->id = BSL_CID_PKCS8SHROUDEDKEYBAG; ret = BSL_LIST_AddElement(keyList, bagKey, BSL_LIST_POS_END); ASSERT_EQ(ret, HITLS_PKI_SUCCESS); ret = HITLS_PKCS12_EncodeAsn1List(p12, keyList, BSL_CID_PKCS8SHROUDEDKEYBAG, &paramEx, encode3); ASSERT_EQ(ret, HITLS_PKI_SUCCESS); ret = HITLS_PKCS12_EncodeContentInfo(NULL, NULL, encode3, BSL_CID_PKCS7_SIMPLEDATA, &paramEx, encode4); ASSERT_EQ(ret, HITLS_PKI_SUCCESS); ret = BSL_LIST_AddElement(list, encode2, BSL_LIST_POS_END); ASSERT_EQ(ret, HITLS_PKI_SUCCESS); ret = BSL_LIST_AddElement(list, encode4, BSL_LIST_POS_END); ASSERT_EQ(ret, HITLS_PKI_SUCCESS); ret = HITLS_PKCS12_EncodeAsn1List(p12, list, BSL_CID_PKCS7_CONTENTINFO, &paramEx, &encode5); ASSERT_EQ(encode5.dataLen, buff->len); EXIT: BSL_SAL_Free(encode1->data); BSL_SAL_Free(encode2->data); BSL_SAL_Free(encode3->data); BSL_SAL_Free(encode4->data); BSL_SAL_Free(encode1); BSL_SAL_Free(encode3); BSL_SAL_Free(encode5.data); BSL_LIST_FREE(list, NULL); BSL_LIST_FREE(keyList, NULL); HITLS_PKCS12_Free(p12); #endif } /* END_CASE */ /** * For test encode authSafedata of correct data. */ /* BEGIN_CASE */ void SDV_PKCS12_ENCODE_MACDATA_TC001(Hex *buff, Hex *initData, Hex *expectData) { #if !defined(HITLS_PKI_PKCS12_GEN) || !defined(HITLS_PKI_PKCS12_PARSE) (void)buff; (void)initData; (void)expectData; SKIP_TEST(); #else ASSERT_EQ(TestRandInit(), 0); char *pwd = "123456"; BSL_Buffer encPwd; encPwd.data = (uint8_t *)pwd; encPwd.dataLen = strlen(pwd); BSL_Buffer output = {0}; BSL_Buffer output1 = {0}; HITLS_PKCS12 *p12 = NULL; HITLS_PKCS12 *p12_1 = NULL; HITLS_PKCS12_PwdParam param = { .encPwd = &encPwd, .macPwd = &encPwd, }; ASSERT_EQ(HITLS_PKCS12_ParseBuff(BSL_FORMAT_ASN1, (BSL_Buffer *)buff, &param, &p12, true), HITLS_PKI_SUCCESS); HITLS_PKCS12_KdfParam hmacParam = {0}; hmacParam.macId = CRYPT_MD_SHA224; hmacParam.pwd = (uint8_t *)pwd; hmacParam.saltLen = p12->macData->macSalt->dataLen; hmacParam.pwdLen = strlen(pwd); hmacParam.itCnt = 2048; HITLS_PKCS12_MacParam macParam = {.para = &hmacParam, .algId = BSL_CID_PKCS12KDF}; ASSERT_EQ(HITLS_PKCS12_EncodeMacData(p12, (BSL_Buffer *)initData, &macParam, &output), HITLS_PKI_SUCCESS); ASSERT_EQ(memcmp(output.data, expectData->x, expectData->len), 0); p12_1 = HITLS_PKCS12_New(); ASSERT_NE(p12_1, NULL); hmacParam.itCnt = 999; ASSERT_EQ(HITLS_PKCS12_EncodeMacData(p12_1, (BSL_Buffer *)initData, &macParam, &output), HITLS_PKCS12_ERR_INVALID_ITERATION); hmacParam.itCnt = 1024; hmacParam.saltLen = 0; ASSERT_EQ(HITLS_PKCS12_EncodeMacData(p12_1, (BSL_Buffer *)initData, &macParam, &output), HITLS_PKCS12_ERR_INVALID_SALTLEN); hmacParam.saltLen = 16; ASSERT_EQ(HITLS_PKCS12_EncodeMacData(p12_1, (BSL_Buffer *)initData, &macParam, &output1), HITLS_PKI_SUCCESS); EXIT: BSL_SAL_Free(output.data); BSL_SAL_Free(output1.data); HITLS_PKCS12_Free(p12); HITLS_PKCS12_Free(p12_1); #endif } /* END_CASE */ /** * For test encode P12 of correct data. */ /* BEGIN_CASE */ void SDV_PKCS12_ENCODE_P12_TC001(Hex *buff, Hex *cert) { #if !defined(HITLS_PKI_PKCS12_GEN) || !defined(HITLS_PKI_PKCS12_PARSE) (void)buff; (void)cert; SKIP_TEST(); #else char *pwd = "123456"; BSL_Buffer encPwd; encPwd.data = (uint8_t *)pwd; encPwd.dataLen = strlen(pwd); BSL_Buffer output = {0}; BSL_Buffer encodeCert1 = {0}; BSL_Buffer encodeCert2 = {0}; HITLS_PKCS12 *p12 = NULL; HITLS_PKCS12 *p12_1 = NULL; HITLS_PKCS12_PwdParam param = {.encPwd = &encPwd, .macPwd = &encPwd}; int32_t ret = HITLS_PKCS12_ParseBuff(BSL_FORMAT_ASN1, (BSL_Buffer *)buff, &param, &p12, true); ASSERT_EQ(ret, HITLS_PKI_SUCCESS); HITLS_PKCS12_EncodeParam encodeParam = {0}; CRYPT_Pbkdf2Param pbParam = {0}; pbParam.pbesId = BSL_CID_PBES2; pbParam.pbkdfId = BSL_CID_PBKDF2; pbParam.hmacId = CRYPT_MAC_HMAC_SHA256; pbParam.symId = CRYPT_CIPHER_AES256_CBC; pbParam.pwd = (uint8_t *)pwd; pbParam.saltLen = 16; pbParam.pwdLen = strlen(pwd); pbParam.itCnt = 2048; CRYPT_EncodeParam encParam = {CRYPT_DERIVE_PBKDF2, &pbParam}; encodeParam.encParam = encParam; HITLS_PKCS12_KdfParam macParam = {0}; macParam.macId = p12->macData->alg; macParam.pwd = (uint8_t *)pwd; macParam.saltLen = p12->macData->macSalt->dataLen; macParam.pwdLen = strlen(pwd); macParam.itCnt = 2048; HITLS_PKCS12_MacParam paramTest = {.para = &macParam, .algId = BSL_CID_PKCS12KDF}; encodeParam.macParam = paramTest; ASSERT_EQ(TestRandInit(), 0); ret = HITLS_PKCS12_GenBuff(BSL_FORMAT_ASN1, p12, &encodeParam, true, &output); ASSERT_EQ(ret, HITLS_PKI_SUCCESS); ASSERT_EQ(output.dataLen, buff->len); ret = HITLS_PKCS12_ParseBuff(BSL_FORMAT_ASN1, &output, &param, &p12_1, true); ASSERT_EQ(ret, HITLS_PKI_SUCCESS); ASSERT_NE(p12_1->key->value.key, NULL); ASSERT_NE(p12_1->entityCert->value.cert, NULL); ret = HITLS_X509_CertGenBuff(BSL_FORMAT_ASN1, p12->entityCert->value.cert, &encodeCert1); ASSERT_EQ(ret, HITLS_PKI_SUCCESS); ret = HITLS_X509_CertGenBuff(BSL_FORMAT_ASN1, p12_1->entityCert->value.cert, &encodeCert2); ASSERT_EQ(ret, HITLS_PKI_SUCCESS); ASSERT_EQ(memcmp(encodeCert1.data, encodeCert2.data, encodeCert1.dataLen), 0); ASSERT_EQ(memcmp(encodeCert1.data, cert->x, cert->len), 0); if (BSL_LIST_COUNT(p12->certList) > 0) { HITLS_PKCS12_Bag *node1 = BSL_LIST_GET_FIRST(p12->certList); BSL_Buffer encodeCert3 = {0}; ret = HITLS_X509_CertGenBuff(BSL_FORMAT_ASN1, node1->value.cert, &encodeCert3); ASSERT_EQ(ret, HITLS_PKI_SUCCESS); HITLS_PKCS12_Bag *node2 = BSL_LIST_GET_FIRST(p12_1->certList); BSL_Buffer encodeCert4 = {0}; ret = HITLS_X509_CertGenBuff(BSL_FORMAT_ASN1, node2->value.cert, &encodeCert4); ASSERT_EQ(ret, HITLS_PKI_SUCCESS); ASSERT_EQ(memcmp(encodeCert1.data, encodeCert2.data, encodeCert1.dataLen), 0); BSL_SAL_Free(encodeCert3.data); BSL_SAL_Free(encodeCert4.data); } EXIT: BSL_SAL_Free(output.data); BSL_SAL_Free(encodeCert1.data); BSL_SAL_Free(encodeCert2.data); HITLS_PKCS12_Free(p12); HITLS_PKCS12_Free(p12_1); #endif } /* END_CASE */ /** * For test encode P12 of correct data(no mac). */ /* BEGIN_CASE */ void SDV_PKCS12_ENCODE_P12_TC002(Hex *buff, Hex *cert) { #if !defined(HITLS_PKI_PKCS12_GEN) || !defined(HITLS_PKI_PKCS12_PARSE) (void)buff; (void)cert; SKIP_TEST(); #else ASSERT_EQ(TestRandInit(), 0); char *pwd = "123456"; BSL_Buffer encPwd; encPwd.data = (uint8_t *)pwd; encPwd.dataLen = strlen(pwd); BSL_Buffer output = {0}; BSL_Buffer encodeCert1 = {0}; BSL_Buffer encodeCert2 = {0}; HITLS_PKCS12 *p12 = NULL; HITLS_PKCS12 *p12_1 = NULL; HITLS_PKCS12_PwdParam param = { .encPwd = &encPwd, .macPwd = &encPwd, }; int32_t ret = HITLS_PKCS12_ParseBuff(BSL_FORMAT_ASN1, (BSL_Buffer *)buff, &param, &p12, false); ASSERT_EQ(ret, HITLS_PKI_SUCCESS); HITLS_PKCS12_EncodeParam encodeParam = {0}; CRYPT_Pbkdf2Param pbParam = {0}; pbParam.pbesId = BSL_CID_PBES2; pbParam.pbkdfId = BSL_CID_PBKDF2; pbParam.hmacId = CRYPT_MAC_HMAC_SHA256; pbParam.symId = CRYPT_CIPHER_AES256_CBC; pbParam.pwd = (uint8_t *)pwd; pbParam.saltLen = 16; pbParam.pwdLen = strlen(pwd); pbParam.itCnt = 2048; CRYPT_EncodeParam encParam = {CRYPT_DERIVE_PBKDF2, &pbParam}; encodeParam.encParam = encParam; HITLS_PKCS12_KdfParam macParam = {0}; macParam.macId = p12->macData->alg; macParam.pwd = (uint8_t *)pwd; macParam.saltLen = 8; macParam.pwdLen = strlen(pwd); macParam.itCnt = 2048; HITLS_PKCS12_MacParam paramTest = {.para = &macParam, .algId = BSL_CID_PKCS12KDF}; encodeParam.macParam = paramTest; ret = HITLS_PKCS12_GenBuff(BSL_FORMAT_ASN1, p12, &encodeParam, true, &output); ASSERT_NE(ret, HITLS_PKI_SUCCESS); ret = HITLS_PKCS12_GenBuff(BSL_FORMAT_ASN1, p12, &encodeParam, false, &output); ASSERT_EQ(ret, HITLS_PKI_SUCCESS); ASSERT_EQ(output.dataLen, buff->len); ret = HITLS_PKCS12_ParseBuff(BSL_FORMAT_ASN1, &output, &param, &p12_1, false); ASSERT_EQ(ret, HITLS_PKI_SUCCESS); ASSERT_NE(p12_1->key->value.key, NULL); ASSERT_NE(p12_1->entityCert->value.cert, NULL); ret = HITLS_X509_CertGenBuff(BSL_FORMAT_ASN1, p12->entityCert->value.cert, &encodeCert1); ASSERT_EQ(ret, HITLS_PKI_SUCCESS); ret = HITLS_X509_CertGenBuff(BSL_FORMAT_ASN1, p12_1->entityCert->value.cert, &encodeCert2); ASSERT_EQ(ret, HITLS_PKI_SUCCESS); ASSERT_EQ(memcmp(encodeCert1.data, encodeCert2.data, encodeCert1.dataLen), 0); ASSERT_EQ(memcmp(encodeCert1.data, cert->x, cert->len), 0); EXIT: BSL_SAL_Free(output.data); BSL_SAL_Free(encodeCert1.data); BSL_SAL_Free(encodeCert2.data); HITLS_PKCS12_Free(p12); HITLS_PKCS12_Free(p12_1); #endif } /* END_CASE */ /** * For test encode P12 of insufficient data. */ /* BEGIN_CASE */ void SDV_PKCS12_ENCODE_P12_TC003(Hex *buff) { #if !defined(HITLS_PKI_PKCS12_GEN) || !defined(HITLS_PKI_PKCS12_PARSE) (void)buff; SKIP_TEST(); #else ASSERT_EQ(TestRandInit(), 0); char *pwd = "123456"; BSL_Buffer encPwd; encPwd.data = (uint8_t *)pwd; encPwd.dataLen = strlen(pwd); HITLS_PKCS12_PwdParam param = { .encPwd = &encPwd, .macPwd = &encPwd, }; HITLS_PKCS12_EncodeParam encodeParam = {0}; CRYPT_Pbkdf2Param pbParam = {0}; pbParam.pbesId = BSL_CID_PBES2; pbParam.pbkdfId = BSL_CID_PBKDF2; pbParam.hmacId = CRYPT_MAC_HMAC_SHA256; pbParam.symId = CRYPT_CIPHER_AES256_CBC; pbParam.pwd = (uint8_t *)pwd; pbParam.saltLen = 16; pbParam.pwdLen = strlen(pwd); pbParam.itCnt = 2048; CRYPT_EncodeParam encParam = {CRYPT_DERIVE_PBKDF2, &pbParam}; encodeParam.encParam = encParam; BSL_Buffer output1 = {0}; BSL_Buffer output2 = {0}; BSL_Buffer output3 = {0}; BSL_Buffer output4 = {0}; BSL_Buffer output5 = {0}; BSL_Buffer output6 = {0}; HITLS_PKCS12 *p12 = HITLS_PKCS12_New(); ASSERT_NE(p12, NULL); // For test p12 has none data, isNeedMac = true. int32_t ret = HITLS_PKCS12_GenBuff(BSL_FORMAT_ASN1, p12, &encodeParam, false, &output1); ASSERT_EQ(ret, HITLS_PKCS12_ERR_NONE_DATA); // For test p12 has none data, isNeedMac = false. ret = HITLS_PKCS12_GenBuff(BSL_FORMAT_ASN1, p12, &encodeParam, true, &output1); ASSERT_EQ(ret, HITLS_PKCS12_ERR_NONE_DATA); HITLS_PKCS12_Free(p12); p12 = NULL; ret = HITLS_PKCS12_ParseBuff(BSL_FORMAT_ASN1, (BSL_Buffer *)buff, &param, &p12, true); ASSERT_EQ(ret, HITLS_PKI_SUCCESS); HITLS_PKCS12_KdfParam macParam = {0}; macParam.macId = p12->macData->alg; macParam.pwd = (uint8_t *)pwd; macParam.saltLen = 8; macParam.pwdLen = strlen(pwd); macParam.itCnt = 2048; HITLS_PKCS12_MacParam paramTest = {.para = &macParam, .algId = BSL_CID_PKCS12KDF}; encodeParam.macParam = paramTest; HITLS_PKCS12 p12_1 = {0}; // For test gen p12 of wrong input ret = HITLS_PKCS12_GenBuff(BSL_FORMAT_UNKNOWN, &p12_1, &encodeParam, true, &output1); ASSERT_EQ(ret, HITLS_PKCS12_ERR_FORMAT_UNSUPPORT); ret = HITLS_PKCS12_GenBuff(BSL_FORMAT_ASN1, &p12_1, NULL, true, &output1); ASSERT_EQ(ret, HITLS_PKCS12_ERR_NULL_POINTER); ret = HITLS_PKCS12_GenBuff(BSL_FORMAT_ASN1, &p12_1, &encodeParam, true, NULL); ASSERT_EQ(ret, HITLS_PKCS12_ERR_NULL_POINTER); (void)memcpy(&p12_1, p12, sizeof(HITLS_PKCS12)); CRYPT_EAL_PkeyCtx *temKey = p12_1.key->value.key; HITLS_X509_Cert *entityCert = p12_1.entityCert->value.cert; p12_1.key->value.key = NULL; p12_1.entityCert->value.cert = NULL; // test p12-encode of key and entityCert = NULL. ret = HITLS_PKCS12_GenBuff(BSL_FORMAT_ASN1, &p12_1, &encodeParam, true, &output1); ASSERT_EQ(ret, HITLS_PKI_SUCCESS); p12_1.key->value.key = NULL; // test p12-encode of key = NULL. ret = HITLS_PKCS12_GenBuff(BSL_FORMAT_ASN1, &p12_1, &encodeParam, true, &output2); ASSERT_EQ(ret, HITLS_PKI_SUCCESS); p12_1.key->value.key = temKey; p12_1.entityCert->value.cert = NULL; // test p12-encode of entityCert = NULL. ret = HITLS_PKCS12_GenBuff(BSL_FORMAT_ASN1, &p12_1, &encodeParam, true, &output3); ASSERT_EQ(ret, HITLS_PKI_SUCCESS); // test p12-encode of entityCert attribute = NULL. p12_1.entityCert->value.cert = entityCert; HITLS_X509_AttrsFree(p12_1.entityCert->attributes, HITLS_PKCS12_AttributesFree); p12_1.entityCert->attributes = NULL; ret = HITLS_PKCS12_GenBuff(BSL_FORMAT_ASN1, &p12_1, &encodeParam, true, &output4); ASSERT_EQ(ret, HITLS_PKI_SUCCESS); // test p12-encode of key attribute = NULL. HITLS_X509_AttrsFree(p12_1.key->attributes, HITLS_PKCS12_AttributesFree); p12_1.key->attributes = NULL; ret = HITLS_PKCS12_GenBuff(BSL_FORMAT_ASN1, &p12_1, &encodeParam, true, &output5); ASSERT_EQ(ret, HITLS_PKI_SUCCESS); BSL_LIST_DeleteAll(p12_1.certList, (BSL_LIST_PFUNC_FREE)HITLS_PKCS12_BagFree); // test p12-encode of key attribute = NULL. ret = HITLS_PKCS12_GenBuff(BSL_FORMAT_ASN1, &p12_1, &encodeParam, true, &output6); ASSERT_EQ(ret, HITLS_PKI_SUCCESS); EXIT: BSL_SAL_Free(output1.data); BSL_SAL_Free(output2.data); BSL_SAL_Free(output3.data); BSL_SAL_Free(output4.data); BSL_SAL_Free(output5.data); BSL_SAL_Free(output6.data); HITLS_PKCS12_Free(p12); #endif } /* END_CASE */ /** * For test gen p12-file of different password. */ /* BEGIN_CASE */ void SDV_PKCS12_ENCODE_P12_TC004(char *pkeyPath, char *certPath) { #if !defined(HITLS_PKI_PKCS12_GEN) || !defined(HITLS_BSL_SAL_FILE) || !defined(HITLS_CRYPTO_KEY_DECODE) (void)pkeyPath; (void)certPath; SKIP_TEST(); #else ASSERT_EQ(TestRandInit(), 0); CRYPT_EAL_PkeyCtx *pkey = NULL; HITLS_X509_Cert *enCert = NULL; HITLS_PKCS12_Bag *certBag = NULL; HITLS_PKCS12_Bag *keyBag = NULL; HITLS_PKCS12 *p12 = HITLS_PKCS12_New(); ASSERT_NE(p12, NULL); ASSERT_EQ(CRYPT_EAL_DecodeFileKey(BSL_FORMAT_ASN1, CRYPT_PRIKEY_PKCS8_UNENCRYPT, pkeyPath, NULL, 0, &pkey), 0); keyBag = HITLS_PKCS12_BagNew(BSL_CID_PKCS8SHROUDEDKEYBAG, 0, pkey); ASSERT_NE(keyBag, NULL); ASSERT_EQ(HITLS_X509_CertParseFile(BSL_FORMAT_ASN1, certPath, &enCert), HITLS_PKI_SUCCESS); certBag = HITLS_PKCS12_BagNew(BSL_CID_CERTBAG, BSL_CID_X509CERTIFICATE, enCert); ASSERT_NE(certBag, NULL); ASSERT_EQ(HITLS_PKCS12_Ctrl(p12, HITLS_PKCS12_SET_ENTITY_KEYBAG, keyBag, 0), HITLS_PKI_SUCCESS); ASSERT_EQ(HITLS_PKCS12_Ctrl(p12, HITLS_PKCS12_SET_ENTITY_CERTBAG, certBag, 0), HITLS_PKI_SUCCESS); HITLS_PKCS12_EncodeParam encodeParam = {0}; BSL_Buffer output = {0}; // While the encrypted data is null of cert and key ASSERT_EQ(HITLS_PKCS12_GenBuff(BSL_FORMAT_ASN1, p12, &encodeParam, false, &output), HITLS_PKCS12_ERR_NO_ENCRYPT_PARAM); ASSERT_EQ(HITLS_PKCS12_GenBuff(BSL_FORMAT_ASN1, p12, &encodeParam, true, &output), HITLS_PKCS12_ERR_NO_ENCRYPT_PARAM); char *pwd = "123456"; CRYPT_Pbkdf2Param pbParam = {0}; pbParam.pbesId = BSL_CID_PBES2; pbParam.pbkdfId = BSL_CID_PBKDF2; pbParam.hmacId = CRYPT_MAC_HMAC_SHA256; pbParam.symId = CRYPT_CIPHER_AES256_CBC; pbParam.pwd = (uint8_t *)pwd; pbParam.saltLen = 16; pbParam.pwdLen = strlen(pwd); pbParam.itCnt = 2048; CRYPT_EncodeParam encParam = {CRYPT_DERIVE_PBKDF2, &pbParam}; HITLS_PKCS12_KdfParam macParam = {0}; macParam.macId = BSL_CID_SHA256; macParam.pwd = (uint8_t *)pwd; macParam.saltLen = 8; macParam.pwdLen = strlen(pwd); macParam.itCnt = 2048; HITLS_PKCS12_MacParam paramTest = {.para = &macParam, .algId = BSL_CID_PKCS12KDF}; encodeParam.encParam = encParam; encodeParam.macParam = paramTest; ASSERT_EQ(HITLS_PKCS12_GenBuff(BSL_FORMAT_ASN1, p12, &encodeParam, false, &output), HITLS_PKI_SUCCESS); BSL_SAL_Free(output.data); output.data = NULL; paramTest.algId = BSL_CID_MAX; encodeParam.macParam = paramTest; ASSERT_EQ(HITLS_PKCS12_GenBuff(BSL_FORMAT_ASN1, p12, &encodeParam, true, &output), HITLS_PKCS12_ERR_INVALID_ALGO); paramTest.algId = BSL_CID_PKCS12KDF; paramTest.para = NULL; encodeParam.macParam = paramTest; ASSERT_EQ(HITLS_PKCS12_GenBuff(BSL_FORMAT_ASN1, p12, &encodeParam, true, &output), HITLS_PKCS12_ERR_NO_MAC_PARAM); EXIT: BSL_SAL_Free(output.data); HITLS_PKCS12_Free(p12); HITLS_X509_CertFree(enCert); CRYPT_EAL_PkeyFreeCtx(pkey); HITLS_PKCS12_BagFree(keyBag); HITLS_PKCS12_BagFree(certBag); #endif } /* END_CASE */ /** * For test gen and parse p12-file. */ /* BEGIN_CASE */ void SDV_PKCS12_GEN_PARSE_P12FILE_TC001(void) { #if !defined(HITLS_PKI_PKCS12_GEN) || !defined(HITLS_PKI_PKCS12_PARSE) SKIP_TEST(); #else ASSERT_EQ(TestRandInit(), 0); char *pwd = "123456"; BSL_Buffer encPwd; encPwd.data = (uint8_t *)pwd; encPwd.dataLen = strlen(pwd); HITLS_PKCS12 *p12 = NULL; HITLS_PKCS12 *p12_1 = NULL; HITLS_PKCS12_PwdParam param = { .encPwd = &encPwd, .macPwd = &encPwd, }; HITLS_PKCS12_EncodeParam encodeParam = {0}; CRYPT_Pbkdf2Param pbParam = {0}; pbParam.pbesId = BSL_CID_PBES2; pbParam.pbkdfId = BSL_CID_PBKDF2; pbParam.hmacId = CRYPT_MAC_HMAC_SHA256; pbParam.symId = CRYPT_CIPHER_AES256_CBC; pbParam.pwd = (uint8_t *)pwd; pbParam.saltLen = 16; pbParam.pwdLen = strlen(pwd); pbParam.itCnt = 2048; CRYPT_EncodeParam encParam = {CRYPT_DERIVE_PBKDF2, &pbParam}; encodeParam.encParam = encParam; const char *path = "../testdata/cert/asn1/pkcs12/chain.p12"; const char *writePath = "../testdata/cert/asn1/pkcs12/chain_cp.p12"; int32_t ret = HITLS_PKCS12_ParseFile(BSL_FORMAT_ASN1, NULL, &param, &p12, true); ASSERT_EQ(ret, HITLS_PKCS12_ERR_NULL_POINTER); ret = HITLS_PKCS12_ParseFile(BSL_FORMAT_ASN1, path, &param, &p12, true); ASSERT_EQ(ret, HITLS_PKI_SUCCESS); HITLS_PKCS12_KdfParam macParam = {0}; macParam.macId = p12->macData->alg; macParam.pwd = (uint8_t *)pwd; macParam.saltLen = 8; macParam.pwdLen = strlen(pwd); macParam.itCnt = 2048; HITLS_PKCS12_MacParam paramTest = {.para = &macParam, .algId = BSL_CID_PKCS12KDF}; encodeParam.macParam = paramTest; ret = HITLS_PKCS12_GenFile(BSL_FORMAT_ASN1, p12, &encodeParam, true, NULL); ASSERT_EQ(ret, HITLS_PKCS12_ERR_NULL_POINTER); ret = HITLS_PKCS12_GenFile(BSL_FORMAT_ASN1, p12, &encodeParam, true, writePath); ASSERT_EQ(ret, HITLS_PKI_SUCCESS); ret = HITLS_PKCS12_ParseFile(BSL_FORMAT_ASN1, writePath, &param, &p12_1, true); ASSERT_EQ(ret, HITLS_PKI_SUCCESS); EXIT: HITLS_PKCS12_Free(p12); HITLS_PKCS12_Free(p12_1); #endif } /* END_CASE */ /** * For test p12-ctrl. */ /* BEGIN_CASE */ void SDV_PKCS12_CTRL_TEST_TC001(char *pkeyPath, char *enCertPath, char *caCertPath) { #if !defined(HITLS_PKI_PKCS12_PARSE) || !defined(HITLS_PKI_PKCS12_GEN) (void)pkeyPath; (void)enCertPath; (void)caCertPath; SKIP_TEST(); #else TestMemInit(); ASSERT_EQ(TestRandInit(), 0); CRYPT_EAL_PkeyCtx *pkey = NULL; HITLS_X509_Cert *enCert = NULL; HITLS_X509_Cert *caCert = NULL; HITLS_X509_Cert *targetCert = NULL; CRYPT_EAL_PkeyCtx *targetKey = NULL; HITLS_PKCS12_Bag *caBag = NULL; HITLS_PKCS12_Bag *pkeyBag = NULL; HITLS_PKCS12_Bag *encertBag = NULL; HITLS_PKCS12_Bag *pkeyBagTmp = NULL; HITLS_PKCS12_Bag *encertBagTmp = NULL; HITLS_X509_Cert *tmpCert = NULL; CRYPT_EAL_PkeyCtx *tmpKey = NULL; int32_t mdId = CRYPT_MD_SHA1; HITLS_PKCS12 *p12 = HITLS_PKCS12_New(); ASSERT_NE(p12, NULL); int32_t ret = CRYPT_EAL_DecodeFileKey(BSL_FORMAT_ASN1, CRYPT_PRIKEY_PKCS8_UNENCRYPT, pkeyPath, NULL, 0, &pkey); ASSERT_EQ(ret, HITLS_PKI_SUCCESS); ret = HITLS_X509_CertParseFile(BSL_FORMAT_ASN1, enCertPath, &enCert); ASSERT_EQ(ret, HITLS_PKI_SUCCESS); ret = HITLS_X509_CertParseFile(BSL_FORMAT_ASN1, caCertPath, &caCert); ASSERT_EQ(ret, HITLS_PKI_SUCCESS); caBag = HITLS_PKCS12_BagNew(BSL_CID_CERTBAG, BSL_CID_X509CERTIFICATE, caCert); ASSERT_NE(caBag, NULL); pkeyBag = HITLS_PKCS12_BagNew(BSL_CID_PKCS8SHROUDEDKEYBAG, 0, pkey); ASSERT_NE(pkeyBag, NULL); encertBag = HITLS_PKCS12_BagNew(BSL_CID_CERTBAG, BSL_CID_X509CERTIFICATE, enCert); ASSERT_NE(encertBag, NULL); ret = HITLS_PKCS12_Ctrl(p12, HITLS_PKCS12_SET_ENTITY_KEYBAG, pkeyBag, 0); ASSERT_EQ(ret, HITLS_PKI_SUCCESS); ret = HITLS_PKCS12_Ctrl(p12, HITLS_PKCS12_SET_ENTITY_CERTBAG, encertBag, 0); ASSERT_EQ(ret, HITLS_PKI_SUCCESS); ret = HITLS_PKCS12_Ctrl(p12, HITLS_PKCS12_GET_ENTITY_CERT, &targetCert, 0); ASSERT_EQ(ret, HITLS_PKI_SUCCESS); ASSERT_NE(targetCert, NULL); ret = HITLS_PKCS12_Ctrl(p12, HITLS_PKCS12_GET_ENTITY_KEY, &targetKey, 0); ASSERT_EQ(ret, HITLS_PKI_SUCCESS); ASSERT_NE(targetKey, NULL); ret = HITLS_PKCS12_Ctrl(p12, HITLS_PKCS12_GEN_LOCALKEYID, &mdId, sizeof(CRYPT_MD_AlgId)); ASSERT_EQ(ret, HITLS_PKI_SUCCESS); ret = HITLS_PKCS12_Ctrl(p12, HITLS_PKCS12_GEN_LOCALKEYID, &mdId, 0); ASSERT_EQ(ret, HITLS_PKCS12_ERR_INVALID_PARAM); mdId = BSL_CID_MD4 - 1; ret = HITLS_PKCS12_Ctrl(p12, HITLS_PKCS12_GEN_LOCALKEYID, &mdId, sizeof(CRYPT_MD_AlgId)); ASSERT_EQ(ret, HITLS_PKCS12_ERR_INVALID_PARAM); ret = HITLS_PKCS12_Ctrl(p12, HITLS_PKCS12_ADD_CERTBAG, caBag, 0); ASSERT_EQ(ret, HITLS_PKI_SUCCESS); ASSERT_NE(p12->key->value.key, NULL); ASSERT_NE(p12->entityCert->value.cert, NULL); ASSERT_EQ(BSL_LIST_COUNT(p12->key->attributes->list), 1); ASSERT_EQ(BSL_LIST_COUNT(p12->entityCert->attributes->list), 1); ASSERT_EQ(BSL_LIST_COUNT(p12->certList), 1); // get bag from p12-ctx. ASSERT_EQ(HITLS_PKCS12_Ctrl(p12, HITLS_PKCS12_GET_ENTITY_CERTBAG, &encertBagTmp, 0), HITLS_PKI_SUCCESS); ASSERT_NE(encertBagTmp, NULL); ASSERT_EQ(HITLS_PKCS12_Ctrl(p12, HITLS_PKCS12_GET_ENTITY_KEYBAG, &pkeyBagTmp, 0), HITLS_PKI_SUCCESS); ASSERT_NE(pkeyBagTmp, NULL); // get value from bag. ASSERT_EQ(HITLS_PKCS12_BagCtrl(encertBagTmp, HITLS_PKCS12_BAG_GET_VALUE, &tmpCert, 0), HITLS_PKI_SUCCESS); ASSERT_EQ(tmpCert, p12->entityCert->value.cert); ASSERT_EQ(HITLS_PKCS12_BagCtrl(pkeyBagTmp, HITLS_PKCS12_BAG_GET_VALUE, &tmpKey, 0), HITLS_PKI_SUCCESS); ASSERT_EQ(tmpKey, p12->key->value.key); EXIT: HITLS_X509_CertFree(targetCert); CRYPT_EAL_PkeyFreeCtx(targetKey); HITLS_PKCS12_BagFree(pkeyBag); HITLS_PKCS12_BagFree(encertBag); HITLS_PKCS12_BagFree(caBag); CRYPT_EAL_PkeyFreeCtx(pkey); HITLS_PKCS12_Free(p12); HITLS_X509_CertFree(enCert); HITLS_X509_CertFree(caCert); HITLS_X509_CertFree(tmpCert); CRYPT_EAL_PkeyFreeCtx(tmpKey); HITLS_PKCS12_BagFree(encertBagTmp); HITLS_PKCS12_BagFree(pkeyBagTmp); #endif } /* END_CASE */ /** * For test p12-ctrl in invalid params. */ /* BEGIN_CASE */ void SDV_PKCS12_CTRL_TEST_TC002(char *enCertPath) { #if !defined(HITLS_PKI_PKCS12_PARSE) || !defined(HITLS_PKI_PKCS12_GEN) (void)enCertPath; SKIP_TEST(); #else HITLS_X509_Cert *enCert = NULL; HITLS_X509_Cert *target = NULL; HITLS_PKCS12_Bag *certBag = NULL; HITLS_PKCS12_Bag keyBag = {0}; HITLS_PKCS12_Bag *entityCertBag = NULL; HITLS_PKCS12 *p12 = HITLS_PKCS12_New(); ASSERT_NE(p12, NULL); int32_t mdId = CRYPT_MD_SHA1; int32_t ret = HITLS_PKCS12_Ctrl(NULL, HITLS_PKCS12_SET_ENTITY_KEYBAG, &keyBag, 0); // p12 == NULL. ASSERT_EQ(ret, HITLS_PKCS12_ERR_NULL_POINTER); ret = HITLS_PKCS12_Ctrl(p12, HITLS_PKCS12_SET_ENTITY_KEYBAG, NULL, 0); // keyBag == NULL. ASSERT_EQ(ret, HITLS_PKCS12_ERR_NULL_POINTER); ret = HITLS_PKCS12_Ctrl(p12, HITLS_PKCS12_GEN_LOCALKEYID - 1, &mdId, sizeof(CRYPT_MD_AlgId)); // cmd is invalid. ASSERT_EQ(ret, HITLS_PKCS12_ERR_INVALID_PARAM); ret = HITLS_PKCS12_Ctrl(p12, HITLS_PKCS12_GET_ENTITY_CERT, &target, 0); // no cert to obtain. ASSERT_EQ(ret, HITLS_PKCS12_ERR_NO_ENTITYCERT); ret = HITLS_PKCS12_Ctrl(p12, HITLS_PKCS12_GEN_LOCALKEYID, &mdId, sizeof(CRYPT_MD_AlgId)); // no key and cert ASSERT_EQ(ret, HITLS_PKCS12_ERR_NULL_POINTER); ret = HITLS_PKCS12_Ctrl(p12, HITLS_PKCS12_SET_ENTITY_CERTBAG, entityCertBag, 0); // enCertBag is invalid. ASSERT_EQ(ret, HITLS_PKCS12_ERR_NULL_POINTER); #if defined(HITLS_CRYPTO_KEY_DECODE) && defined(HITLS_BSL_SAL_FILE) ret = HITLS_X509_CertParseFile(BSL_FORMAT_ASN1, enCertPath, &enCert); ASSERT_EQ(ret, HITLS_PKI_SUCCESS); entityCertBag = HITLS_PKCS12_BagNew(BSL_CID_CERTBAG, BSL_CID_X509CERTIFICATE, enCert); ASSERT_NE(entityCertBag, NULL); ret = HITLS_PKCS12_Ctrl(p12, HITLS_PKCS12_SET_ENTITY_CERTBAG, entityCertBag, 0); ASSERT_EQ(ret, HITLS_PKI_SUCCESS); #else (void)enCertPath; SKIP_TEST(); #endif // no key to set localKeyId. p12->key = &keyBag; ret = HITLS_PKCS12_Ctrl(p12, HITLS_PKCS12_GEN_LOCALKEYID, &mdId, sizeof(CRYPT_MD_AlgId)); ASSERT_EQ(ret, HITLS_PKCS12_ERR_NO_PAIRED_CERT_AND_KEY); p12->key = NULL; ret = HITLS_PKCS12_Ctrl(p12, HITLS_PKCS12_ADD_CERTBAG, certBag, 0); // certBag is NULL. ASSERT_EQ(ret, HITLS_PKCS12_ERR_NULL_POINTER); keyBag.type = BSL_CID_PKCS8SHROUDEDKEYBAG; ret = HITLS_PKCS12_Ctrl(p12, HITLS_PKCS12_ADD_CERTBAG, &keyBag, 0); // certBag-type is wrong. ASSERT_EQ(ret, HITLS_PKCS12_ERR_INVALID_PARAM); EXIT: HITLS_PKCS12_Free(p12); HITLS_X509_CertFree(enCert); HITLS_PKCS12_BagFree(entityCertBag); #endif } /* END_CASE */ /** * For test p12-bag creat, set, and free. */ /* BEGIN_CASE */ void SDV_PKCS12_BAG_TEST_TC001(char *pkeyPath, char *certPath) { #if !defined(HITLS_PKI_PKCS12_PARSE) || !defined(HITLS_BSL_SAL_FILE) || !defined(HITLS_PKI_PKCS12_GEN) (void)pkeyPath; (void)certPath; SKIP_TEST(); #else CRYPT_EAL_PkeyCtx *pkey = NULL; HITLS_X509_Cert *enCert = NULL; HITLS_PKCS12_Bag *keyBag = NULL; HITLS_PKCS12_Bag *certBag = NULL; char *name = "friendlyName"; uint32_t nameLen = strlen(name); BSL_Buffer buffer = {.data = (uint8_t *)name, .dataLen = nameLen}; int32_t id = 0; int32_t type = 0; int32_t ret = CRYPT_EAL_DecodeFileKey(BSL_FORMAT_ASN1, CRYPT_PRIKEY_PKCS8_UNENCRYPT, pkeyPath, NULL, 0, &pkey); ASSERT_EQ(ret, HITLS_PKI_SUCCESS); keyBag = HITLS_PKCS12_BagNew(BSL_CID_PKCS8SHROUDEDKEYBAG, 0, pkey); ASSERT_NE(keyBag, NULL); ret = HITLS_X509_CertParseFile(BSL_FORMAT_ASN1, certPath, &enCert); ASSERT_EQ(ret, HITLS_PKI_SUCCESS); certBag = HITLS_PKCS12_BagNew(BSL_CID_CERTBAG, BSL_CID_X509CERTIFICATE, enCert); ASSERT_NE(certBag, NULL); ASSERT_EQ(HITLS_PKCS12_BagCtrl(NULL, HITLS_PKCS12_BAG_ADD_ATTR, &buffer, BSL_CID_FRIENDLYNAME), HITLS_PKCS12_ERR_NULL_POINTER); ASSERT_EQ(HITLS_PKCS12_BagCtrl(keyBag, HITLS_PKCS12_BAG_GET_ID, NULL, sizeof(uint32_t)), HITLS_PKCS12_ERR_NULL_POINTER); ASSERT_EQ(HITLS_PKCS12_BagCtrl(keyBag, HITLS_PKCS12_BAG_GET_TYPE, NULL, sizeof(uint32_t)), HITLS_PKCS12_ERR_NULL_POINTER); ASSERT_EQ(HITLS_PKCS12_BagCtrl(keyBag, HITLS_PKCS12_BAG_ADD_ATTR, &buffer, BSL_CID_FRIENDLYNAME), 0); ASSERT_EQ(HITLS_PKCS12_BagCtrl(certBag, HITLS_PKCS12_BAG_GET_ID, &id, sizeof(uint8_t)), HITLS_PKCS12_ERR_INVALID_PARAM); ASSERT_EQ(HITLS_PKCS12_BagCtrl(certBag, HITLS_PKCS12_BAG_GET_TYPE, &type, sizeof(uint8_t)), HITLS_PKCS12_ERR_INVALID_PARAM); ASSERT_EQ(HITLS_PKCS12_BagCtrl(certBag, HITLS_PKCS12_BAG_GET_ID, &id, sizeof(uint32_t)), 0); ASSERT_EQ(id, BSL_CID_CERTBAG); ASSERT_EQ(HITLS_PKCS12_BagCtrl(certBag, HITLS_PKCS12_BAG_GET_TYPE, &type, sizeof(uint32_t)), 0); ASSERT_EQ(type, BSL_CID_X509CERTIFICATE); ASSERT_EQ(HITLS_PKCS12_BagCtrl(certBag, HITLS_PKCS12_BAG_ADD_ATTR, &buffer, BSL_CID_FRIENDLYNAME), 0); EXIT: HITLS_PKCS12_BagFree(keyBag); HITLS_PKCS12_BagFree(certBag); CRYPT_EAL_PkeyFreeCtx(pkey); HITLS_X509_CertFree(enCert); #endif } /* END_CASE */ /** * For test p12-bag in invalid params. */ /* BEGIN_CASE */ void SDV_PKCS12_BAG_TEST_TC002(char *pkeyPath) { #if !defined(HITLS_CRYPTO_KEY_DECODE) || !defined(HITLS_BSL_SAL_FILE) || !defined(HITLS_PKI_PKCS12_GEN) (void)pkeyPath; SKIP_TEST(); #else CRYPT_EAL_PkeyCtx *pkey = NULL; HITLS_PKCS12_Bag *keyBag = NULL; BSL_Buffer buffer = {0}; int32_t ret = CRYPT_EAL_DecodeFileKey(BSL_FORMAT_ASN1, CRYPT_PRIKEY_PKCS8_UNENCRYPT, pkeyPath, NULL, 0, &pkey); ASSERT_EQ(ret, HITLS_PKI_SUCCESS); keyBag = HITLS_PKCS12_BagNew(BSL_CID_MAX, 0, pkey); // invalid bag-id. ASSERT_EQ(keyBag, NULL); keyBag = HITLS_PKCS12_BagNew(BSL_CID_PKCS8SHROUDEDKEYBAG, 0, pkey); ASSERT_NE(keyBag, NULL); ret = HITLS_PKCS12_BagCtrl(keyBag, HITLS_PKCS12_BAG_ADD_ATTR, NULL, BSL_CID_FRIENDLYNAME); // Attribute is null. ASSERT_EQ(ret, HITLS_PKCS12_ERR_NULL_POINTER); char *name = "friendlyName"; uint32_t nameLen = strlen(name); buffer.data = (uint8_t *)name; buffer.dataLen = nameLen; ret = HITLS_PKCS12_BagCtrl(NULL, HITLS_PKCS12_BAG_ADD_ATTR, &buffer, BSL_CID_FRIENDLYNAME); ASSERT_EQ(ret, HITLS_PKCS12_ERR_NULL_POINTER); ret = HITLS_PKCS12_BagCtrl(keyBag, HITLS_PKCS12_BAG_ADD_ATTR, &buffer, BSL_CID_EXTEND); ASSERT_EQ(ret, HITLS_PKCS12_ERR_INVALID_SAFEBAG_ATTRIBUTES); ret = HITLS_PKCS12_BagCtrl(keyBag, HITLS_PKCS12_BAG_ADD_ATTR, &buffer, BSL_CID_FRIENDLYNAME); ASSERT_EQ(ret, HITLS_PKI_SUCCESS); ret = HITLS_PKCS12_BagCtrl(keyBag, HITLS_PKCS12_BAG_ADD_ATTR, &buffer, BSL_CID_FRIENDLYNAME); ASSERT_EQ(ret, HITLS_X509_ERR_SET_ATTR_REPEAT); EXIT: HITLS_PKCS12_BagFree(keyBag); CRYPT_EAL_PkeyFreeCtx(pkey); #endif } /* END_CASE */ /** * For test p12-ctrl in invalid params of repeated attributes. */ /* BEGIN_CASE */ void SDV_PKCS12_BAG_TEST_TC003(char *pkeyPath, char *certPath) { #if !defined(HITLS_CRYPTO_KEY_DECODE) || !defined(HITLS_BSL_SAL_FILE) || !defined(HITLS_PKI_PKCS12_GEN) (void)pkeyPath; (void)certPath; SKIP_TEST(); #else CRYPT_EAL_PkeyCtx *pkey = NULL; HITLS_X509_Cert *enCert = NULL; HITLS_PKCS12_Bag *certBag = NULL; HITLS_PKCS12_Bag *keyBag = NULL; HITLS_PKCS12 *p12 = HITLS_PKCS12_New(); ASSERT_NE(p12, NULL); int32_t mdId = CRYPT_MD_SHA1; int32_t ret = CRYPT_EAL_DecodeFileKey(BSL_FORMAT_ASN1, CRYPT_PRIKEY_PKCS8_UNENCRYPT, pkeyPath, NULL, 0, &pkey); ASSERT_EQ(ret, HITLS_PKI_SUCCESS); keyBag = HITLS_PKCS12_BagNew(BSL_CID_PKCS8SHROUDEDKEYBAG, 0, pkey); ASSERT_NE(keyBag, NULL); ret = HITLS_X509_CertParseFile(BSL_FORMAT_ASN1, certPath, &enCert); ASSERT_EQ(ret, HITLS_PKI_SUCCESS); certBag = HITLS_PKCS12_BagNew(BSL_CID_CERTBAG, BSL_CID_X509CERTIFICATE, enCert); ASSERT_NE(certBag, NULL); uint8_t keyId[32] = {0}; uint32_t idLen = 32; BSL_Buffer attr = {.data = keyId, .dataLen = idLen}; ret = HITLS_PKCS12_BagCtrl(certBag, HITLS_PKCS12_BAG_ADD_ATTR, &attr, BSL_CID_LOCALKEYID); ASSERT_EQ(ret, HITLS_PKI_SUCCESS); ret = HITLS_PKCS12_Ctrl(p12, HITLS_PKCS12_SET_ENTITY_KEYBAG, keyBag, 0); ASSERT_EQ(ret, HITLS_PKI_SUCCESS); ret = HITLS_PKCS12_Ctrl(p12, HITLS_PKCS12_SET_ENTITY_KEYBAG, keyBag, 0); ASSERT_EQ(ret, HITLS_PKCS12_ERR_REPEATED_SET_KEY); // Repeat setting. ret = HITLS_PKCS12_Ctrl(p12, HITLS_PKCS12_SET_ENTITY_CERTBAG, certBag, 0); ASSERT_EQ(ret, HITLS_PKI_SUCCESS); ret = HITLS_PKCS12_Ctrl(p12, HITLS_PKCS12_SET_ENTITY_CERTBAG, certBag, 0); ASSERT_EQ(ret, HITLS_PKCS12_ERR_REPEATED_SET_ENTITYCERT); // Repeat setting. // The key bag has pushed the localKey-id attribute. ret = HITLS_PKCS12_Ctrl(p12, HITLS_PKCS12_GEN_LOCALKEYID, &mdId, sizeof(CRYPT_MD_AlgId)); ASSERT_EQ(ret, HITLS_X509_ERR_SET_ATTR_REPEAT); EXIT: HITLS_PKCS12_Free(p12); HITLS_X509_CertFree(enCert); CRYPT_EAL_PkeyFreeCtx(pkey); HITLS_PKCS12_BagFree(keyBag); HITLS_PKCS12_BagFree(certBag); #endif } /* END_CASE */ /** * For test generating a .p12 from reading buffer. */ /* BEGIN_CASE */ void SDV_PKCS12_GEN_FROM_DATA_TC001(char *pkeyPath, char *enCertPath, char *ca1CertPath, char *otherCertPath) { #ifndef HITLS_PKI_PKCS12_GEN (void)pkeyPath; (void)enCertPath; (void)ca1CertPath; (void)otherCertPath; SKIP_TEST(); #else TestMemInit(); ASSERT_EQ(TestRandInit(), 0); char *pwd = "123456"; CRYPT_Pbkdf2Param pbParam = {BSL_CID_PBES2, BSL_CID_PBKDF2, CRYPT_MAC_HMAC_SHA256, CRYPT_CIPHER_AES256_CBC, 16, (uint8_t *)pwd, strlen(pwd), 2048}; CRYPT_EncodeParam encParam = {CRYPT_DERIVE_PBKDF2, &pbParam}; HITLS_PKCS12_KdfParam macParam = {8, 2048, BSL_CID_SHA256, (uint8_t *)pwd, strlen(pwd)}; HITLS_PKCS12_MacParam paramTest = {.para = &macParam, .algId = BSL_CID_PKCS12KDF}; HITLS_PKCS12_EncodeParam encodeParam = {encParam, paramTest}; #ifdef HITLS_PKI_PKCS12_PARSE BSL_Buffer encPwd = {.data = (uint8_t *)pwd, .dataLen = strlen(pwd)}; HITLS_PKCS12_PwdParam pwdParam = {.encPwd = &encPwd, .macPwd = &encPwd}; #endif CRYPT_EAL_PkeyCtx *pkey = NULL; HITLS_X509_Cert *enCert = NULL; HITLS_X509_Cert *ca1Cert = NULL; HITLS_X509_Cert *otherCert = NULL; HITLS_PKCS12_Bag *pkeyBag = NULL; HITLS_PKCS12_Bag *encertBag = NULL; HITLS_PKCS12_Bag *ca1Bag = NULL; HITLS_PKCS12_Bag *otherCertBag = NULL; HITLS_X509_Cert *targetCert = NULL; CRYPT_EAL_PkeyCtx *targetKey = NULL; char *name = "entity"; uint32_t nameLen = strlen(name); BSL_Buffer buffer1 = {0}; buffer1.data = (uint8_t *)name; buffer1.dataLen = nameLen; char *name1 = "ca1"; uint32_t nameLen1 = strlen(name1); BSL_Buffer buffer2 = {0}; buffer2.data = (uint8_t *)name1; buffer2.dataLen = nameLen1; BSL_Buffer output = {0}; int32_t mdId = CRYPT_MD_SHA1; HITLS_PKCS12 *p12_1 = NULL; HITLS_PKCS12 *p12 = HITLS_PKCS12_New(); ASSERT_NE(p12, NULL); ASSERT_EQ(CRYPT_EAL_DecodeFileKey(BSL_FORMAT_ASN1, CRYPT_PRIKEY_PKCS8_UNENCRYPT, pkeyPath, NULL, 0, &pkey), 0); ASSERT_EQ(HITLS_X509_CertParseFile(BSL_FORMAT_ASN1, enCertPath, &enCert), HITLS_PKI_SUCCESS); ASSERT_EQ(HITLS_X509_CertParseFile(BSL_FORMAT_ASN1, ca1CertPath, &ca1Cert), HITLS_PKI_SUCCESS); ASSERT_EQ(HITLS_X509_CertParseFile(BSL_FORMAT_ASN1, otherCertPath, &otherCert), HITLS_PKI_SUCCESS); pkeyBag = HITLS_PKCS12_BagNew(BSL_CID_PKCS8SHROUDEDKEYBAG, 0, pkey); // new a key Bag ASSERT_NE(pkeyBag, NULL); ca1Bag = HITLS_PKCS12_BagNew(BSL_CID_CERTBAG, BSL_CID_X509CERTIFICATE, ca1Cert); // new a cert Bag ASSERT_NE(ca1Bag, NULL); encertBag = HITLS_PKCS12_BagNew(BSL_CID_CERTBAG, BSL_CID_X509CERTIFICATE, enCert); // new a cert Bag ASSERT_NE(encertBag, NULL); otherCertBag = HITLS_PKCS12_BagNew(BSL_CID_CERTBAG, BSL_CID_X509CERTIFICATE, otherCert); ASSERT_NE(otherCertBag, NULL); // Add a attribute to the keyBag. ASSERT_EQ(HITLS_PKCS12_BagCtrl(pkeyBag, HITLS_PKCS12_BAG_ADD_ATTR, &buffer1, BSL_CID_FRIENDLYNAME), 0); // Add a attribute to the certBag. ASSERT_EQ(HITLS_PKCS12_BagCtrl(encertBag, HITLS_PKCS12_BAG_ADD_ATTR, &buffer1, BSL_CID_FRIENDLYNAME), 0); ASSERT_EQ(HITLS_PKCS12_BagCtrl(ca1Bag, HITLS_PKCS12_BAG_ADD_ATTR, &buffer2, BSL_CID_FRIENDLYNAME), 0); // Set entity-key to p12. ASSERT_EQ(HITLS_PKCS12_Ctrl(p12, HITLS_PKCS12_SET_ENTITY_KEYBAG, pkeyBag, 0), 0); // Set entity-cert to p12. ASSERT_EQ(HITLS_PKCS12_Ctrl(p12, HITLS_PKCS12_SET_ENTITY_CERTBAG, encertBag, 0), 0); // Set ca-cert to p12. ASSERT_EQ(HITLS_PKCS12_Ctrl(p12, HITLS_PKCS12_ADD_CERTBAG, ca1Bag, 0), 0); // Set the second cert, which has no attr. ASSERT_EQ(HITLS_PKCS12_Ctrl(p12, HITLS_PKCS12_ADD_CERTBAG, otherCertBag, 0), 0); // Cal localKeyId to p12. ASSERT_EQ(HITLS_PKCS12_Ctrl(p12, HITLS_PKCS12_GEN_LOCALKEYID, &mdId, sizeof(CRYPT_MD_AlgId)), 0); ASSERT_EQ(HITLS_PKCS12_GenBuff(BSL_FORMAT_ASN1, p12, &encodeParam, true, &output), 0); #ifdef HITLS_PKI_PKCS12_PARSE ASSERT_EQ(HITLS_PKCS12_ParseBuff(BSL_FORMAT_ASN1, &output, &pwdParam, &p12_1, true), 0); // Attempt to get a entity-cert from p12 we parsed. ASSERT_EQ(HITLS_PKCS12_Ctrl(p12_1, HITLS_PKCS12_GET_ENTITY_CERT, &targetCert, 0), 0); ASSERT_NE(targetCert, NULL); ASSERT_EQ(HITLS_PKCS12_Ctrl(p12_1, HITLS_PKCS12_GET_ENTITY_KEY, &targetKey, 0), 0); // Attempt to get a entity-key. ASSERT_NE(targetKey, NULL); ASSERT_EQ(BSL_LIST_COUNT(p12_1->certList), 2); #endif EXIT: HITLS_X509_CertFree(targetCert); CRYPT_EAL_PkeyFreeCtx(targetKey); HITLS_PKCS12_BagFree(pkeyBag); HITLS_PKCS12_BagFree(encertBag); HITLS_PKCS12_BagFree(ca1Bag); HITLS_PKCS12_BagFree(otherCertBag); CRYPT_EAL_PkeyFreeCtx(pkey); HITLS_X509_CertFree(enCert); HITLS_X509_CertFree(ca1Cert); HITLS_X509_CertFree(otherCert); HITLS_PKCS12_Free(p12); HITLS_PKCS12_Free(p12_1); BSL_SAL_Free(output.data); #endif } /* END_CASE */ /** * For test generating a .p12, which including a secret-bag. */ /* BEGIN_CASE */ void SDV_PKCS12_GEN_SECRET_BAG_TC001(char *pkeyPath, char *certPath) { #if !defined(HITLS_CRYPTO_KEY_DECODE) || !defined(HITLS_BSL_SAL_FILE) || !defined(HITLS_PKI_PKCS12_GEN) SKIP_TEST(); #else TestMemInit(); ASSERT_EQ(TestRandInit(), 0); const char *writePath = "../testdata/cert/asn1/pkcs12/secret.p12"; CRYPT_EAL_PkeyCtx *pkey = NULL; HITLS_X509_Cert *enCert = NULL; HITLS_PKCS12_Bag *keyBag = NULL; HITLS_PKCS12_Bag *certBag = NULL; char *pwd = "123456"; // All adopt smX algorithms CRYPT_Pbkdf2Param pbParam = {BSL_CID_PBES2, BSL_CID_PBKDF2, CRYPT_MAC_HMAC_SM3, CRYPT_CIPHER_SM4_CBC, 16, (uint8_t *)pwd, strlen(pwd), 2048}; CRYPT_EncodeParam encParam = {CRYPT_DERIVE_PBKDF2, &pbParam}; HITLS_PKCS12_KdfParam macParam = {8, 2048, BSL_CID_SM3, (uint8_t *)pwd, strlen(pwd)}; HITLS_PKCS12_MacParam paramTest = {.para = &macParam, .algId = BSL_CID_PKCS12KDF}; HITLS_PKCS12_EncodeParam encodeParam = {encParam, paramTest}; BSL_Buffer encPwd = {.data = (uint8_t *)pwd, .dataLen = strlen(pwd)}; HITLS_PKCS12_PwdParam pwdParam = {.encPwd = &encPwd, .macPwd = &encPwd}; HITLS_PKCS12_Bag *secretBag = NULL; uint8_t secretData[20] = {1}; uint32_t secretDataLen = 20; BSL_Buffer secret = {.data = (uint8_t *)secretData, .dataLen = secretDataLen}; char *name = "secret"; uint32_t nameLen = strlen(name); BSL_Buffer friendlyName = {.data = (uint8_t *)name, .dataLen = nameLen}; BSL_Buffer output = {0}; HITLS_PKCS12 *p12_1 = NULL; HITLS_PKCS12 *p12 = HITLS_PKCS12_New(); ASSERT_NE(p12, NULL); secretBag = HITLS_PKCS12_BagNew(BSL_CID_SECRETBAG, BSL_CID_CE_EXTKEYUSAGE, &secret); ASSERT_NE(secretBag, NULL); ASSERT_EQ(CRYPT_EAL_DecodeFileKey(BSL_FORMAT_ASN1, CRYPT_PRIKEY_PKCS8_UNENCRYPT, pkeyPath, NULL, 0, &pkey), 0); ASSERT_EQ(HITLS_X509_CertParseFile(BSL_FORMAT_ASN1, certPath, &enCert), 0); keyBag = HITLS_PKCS12_BagNew(BSL_CID_PKCS8SHROUDEDKEYBAG, 0, pkey); ASSERT_NE(keyBag, NULL); certBag = HITLS_PKCS12_BagNew(BSL_CID_CERTBAG, BSL_CID_X509CERTIFICATE, enCert); ASSERT_NE(certBag, NULL); ASSERT_EQ(HITLS_PKCS12_Ctrl(p12, HITLS_PKCS12_SET_ENTITY_KEYBAG, keyBag, 0), 0); ASSERT_EQ(HITLS_PKCS12_Ctrl(p12, HITLS_PKCS12_SET_ENTITY_CERTBAG, certBag, 0), 0); // Add a attribute to the secretBag. ASSERT_EQ(HITLS_PKCS12_BagCtrl(secretBag, HITLS_PKCS12_BAG_ADD_ATTR, &friendlyName, BSL_CID_FRIENDLYNAME), 0); // Set the secretBag to p12. ASSERT_EQ(HITLS_PKCS12_Ctrl(p12, HITLS_PKCS12_ADD_SECRETBAG, secretBag, 0), 0); // no mac ASSERT_EQ(HITLS_PKCS12_GenBuff(BSL_FORMAT_ASN1, p12, &encodeParam, false, &output), 0); ASSERT_EQ(HITLS_PKCS12_ParseBuff(BSL_FORMAT_ASN1, &output, &pwdParam, &p12_1, false), HITLS_PKI_SUCCESS); BSL_SAL_FREE(output.data); HITLS_PKCS12_Free(p12_1); p12_1 = NULL; // with mac ASSERT_EQ(HITLS_PKCS12_GenBuff(BSL_FORMAT_ASN1, p12, &encodeParam, true, &output), 0); ASSERT_EQ(HITLS_PKCS12_ParseBuff(BSL_FORMAT_ASN1, &output, &pwdParam, &p12_1, true), HITLS_PKI_SUCCESS); HITLS_PKCS12_Free(p12_1); p12_1 = NULL; // no mac ASSERT_EQ(HITLS_PKCS12_GenFile(BSL_FORMAT_ASN1, p12, &encodeParam, false, writePath), HITLS_PKI_SUCCESS); ASSERT_EQ(HITLS_PKCS12_ParseFile(BSL_FORMAT_ASN1, writePath, &pwdParam, &p12_1, false), HITLS_PKI_SUCCESS); HITLS_PKCS12_Free(p12_1); p12_1 = NULL; // with mac ASSERT_EQ(HITLS_PKCS12_GenFile(BSL_FORMAT_ASN1, p12, &encodeParam, true, writePath), HITLS_PKI_SUCCESS); ASSERT_EQ(HITLS_PKCS12_ParseFile(BSL_FORMAT_ASN1, writePath, &pwdParam, &p12_1, true), HITLS_PKI_SUCCESS); EXIT: HITLS_X509_CertFree(enCert); CRYPT_EAL_PkeyFreeCtx(pkey); HITLS_PKCS12_BagFree(secretBag); HITLS_PKCS12_BagFree(keyBag); HITLS_PKCS12_BagFree(certBag); HITLS_PKCS12_Free(p12); HITLS_PKCS12_Free(p12_1); BSL_SAL_Free(output.data); #endif } /* END_CASE */ /** * For test bag-ctrl, including get-id, get-type, get-value in secret-bag. */ /* BEGIN_CASE */ void SDV_PKCS12_BAG_CTRL_TC001(void) { #if !defined(HITLS_CRYPTO_KEY_DECODE) || !defined(HITLS_BSL_SAL_FILE) || !defined(HITLS_PKI_PKCS12_GEN) SKIP_TEST(); #else TestMemInit(); ASSERT_EQ(TestRandInit(), 0); char *pwd = "123456"; CRYPT_Pbkdf2Param pbParam = {BSL_CID_PBES2, BSL_CID_PBKDF2, CRYPT_MAC_HMAC_SHA256, CRYPT_CIPHER_AES256_CBC, 16, (uint8_t *)pwd, strlen(pwd), 2048}; CRYPT_EncodeParam encParam = {CRYPT_DERIVE_PBKDF2, &pbParam}; HITLS_PKCS12_KdfParam macParam = {8, 2048, BSL_CID_SHA256, (uint8_t *)pwd, strlen(pwd)}; HITLS_PKCS12_MacParam paramTest = {.para = &macParam, .algId = BSL_CID_PKCS12KDF}; HITLS_PKCS12_EncodeParam encodeParam = {encParam, paramTest}; BSL_Buffer encPwd = {.data = (uint8_t *)pwd, .dataLen = strlen(pwd)}; HITLS_PKCS12_PwdParam pwdParam = {.encPwd = &encPwd, .macPwd = &encPwd}; uint32_t id; uint32_t type; BSL_ASN1_List *secretBags = NULL; HITLS_PKCS12_Bag *secretBag1 = NULL; HITLS_PKCS12_Bag *secretBag2 = NULL; uint8_t secretData1[20]; uint32_t secretDataLen1 = 20; (void)memset_s(secretData1, secretDataLen1, 'F', secretDataLen1); BSL_Buffer secret1 = {.data = (uint8_t *)secretData1, .dataLen = secretDataLen1}; uint8_t secretData2[30]; uint32_t secretDataLen2 = 30; (void)memset_s(secretData2, secretDataLen2, 'A', secretDataLen2); BSL_Buffer secret2 = {.data = (uint8_t *)secretData2, .dataLen = secretDataLen2}; uint8_t outputSecret[30] = {2}; uint32_t outputSecretLen = 30; BSL_Buffer outBuf = {.data = (uint8_t *)outputSecret, .dataLen = outputSecretLen}; char *name = "secret1"; // friendlyName of secretBag1 uint32_t nameLen = strlen(name); BSL_Buffer friendlyName1 = {.data = (uint8_t *)name, .dataLen = nameLen}; char *name2 = "secret2"; // friendlyName of secretBag2 uint32_t nameLen2 = strlen(name2); BSL_Buffer friendlyName2 = {.data = (uint8_t *)name2, .dataLen = nameLen2}; BSL_Buffer output = {0}; HITLS_PKCS12_Bag *tmpBag = NULL; HITLS_PKCS12 *p12 = HITLS_PKCS12_New(); ASSERT_NE(p12, NULL); HITLS_PKCS12 *p12_1 = NULL; secretBag1 = HITLS_PKCS12_BagNew(BSL_CID_SECRETBAG, BSL_CID_CE_EXTKEYUSAGE, &secret1); ASSERT_NE(secretBag1, NULL); secretBag2 = HITLS_PKCS12_BagNew(BSL_CID_SECRETBAG, BSL_CID_CE_KEYUSAGE, &secret2); ASSERT_NE(secretBag2, NULL); // Add a attribute to the secretBag. ASSERT_EQ(HITLS_PKCS12_BagCtrl(secretBag1, HITLS_PKCS12_BAG_ADD_ATTR, &friendlyName1, BSL_CID_FRIENDLYNAME), 0); ASSERT_EQ(HITLS_PKCS12_BagCtrl(secretBag2, HITLS_PKCS12_BAG_ADD_ATTR, &friendlyName2, BSL_CID_FRIENDLYNAME), 0); // Set the secretBag to p12. ASSERT_EQ(HITLS_PKCS12_Ctrl(p12, HITLS_PKCS12_ADD_SECRETBAG, secretBag1, 0), 0); ASSERT_EQ(HITLS_PKCS12_Ctrl(p12, HITLS_PKCS12_ADD_SECRETBAG, secretBag2, 0), 0); ASSERT_EQ(HITLS_PKCS12_GenBuff(BSL_FORMAT_ASN1, p12, &encodeParam, true, &output), 0); ASSERT_EQ(HITLS_PKCS12_ParseBuff(BSL_FORMAT_ASN1, &output, &pwdParam, &p12_1, true), HITLS_PKI_SUCCESS); ASSERT_EQ(HITLS_PKCS12_Ctrl(p12_1, HITLS_PKCS12_GET_SECRETBAGS, &secretBags, 0), 0); ASSERT_EQ(BSL_LIST_COUNT(secretBags), 2); tmpBag = BSL_LIST_GET_FIRST(secretBags); ASSERT_EQ(HITLS_PKCS12_BagCtrl(tmpBag, HITLS_PKCS12_BAG_GET_ID, &id, sizeof(uint32_t)), 0); ASSERT_EQ(id, BSL_CID_SECRETBAG); ASSERT_EQ(HITLS_PKCS12_BagCtrl(tmpBag, HITLS_PKCS12_BAG_GET_TYPE, &type, sizeof(uint32_t)), 0); ASSERT_EQ(type, BSL_CID_CE_EXTKEYUSAGE); ASSERT_EQ(HITLS_PKCS12_BagCtrl(tmpBag, HITLS_PKCS12_BAG_GET_VALUE, &outBuf, sizeof(BSL_Buffer)), 0); ASSERT_COMPARE("compare secret1", outBuf.data, outBuf.dataLen, secretData1, secretDataLen1); outBuf.dataLen = 30; // init len is 30. ASSERT_EQ(HITLS_PKCS12_BagCtrl(tmpBag, HITLS_PKCS12_BAG_GET_ATTR, &outBuf, BSL_CID_FRIENDLYNAME), 0); ASSERT_COMPARE("compare attr1", outBuf.data, outBuf.dataLen, name, nameLen); tmpBag = (HITLS_PKCS12_Bag *)BSL_LIST_GET_LAST(secretBags); ASSERT_EQ(HITLS_PKCS12_BagCtrl(tmpBag, HITLS_PKCS12_BAG_GET_ID, &id, sizeof(uint32_t)), 0); ASSERT_EQ(id, BSL_CID_SECRETBAG); ASSERT_EQ(HITLS_PKCS12_BagCtrl(tmpBag, HITLS_PKCS12_BAG_GET_TYPE, &type, sizeof(uint32_t)), 0); ASSERT_EQ(type, BSL_CID_CE_KEYUSAGE); outBuf.dataLen = 30; // init len is 30. ASSERT_EQ(HITLS_PKCS12_BagCtrl(tmpBag, HITLS_PKCS12_BAG_GET_ATTR, &outBuf, BSL_CID_FRIENDLYNAME), 0); ASSERT_COMPARE("compare attr2", outBuf.data, outBuf.dataLen, name2, nameLen2); outBuf.dataLen = 30; // init len is 30. ASSERT_EQ(HITLS_PKCS12_BagCtrl(tmpBag, HITLS_PKCS12_BAG_GET_VALUE, &outBuf, sizeof(BSL_Buffer)), 0); ASSERT_COMPARE("compare secret2", outBuf.data, outBuf.dataLen, secretData2, secretDataLen2); EXIT: HITLS_PKCS12_BagFree(secretBag1); HITLS_PKCS12_BagFree(secretBag2); HITLS_PKCS12_Free(p12); HITLS_PKCS12_Free(p12_1); BSL_SAL_Free(output.data); #endif } /* END_CASE */ /** * For test bag-ctrl, including get-id, get-type, get-value in cert-bag and key-bag. */ /* BEGIN_CASE */ void SDV_PKCS12_BAG_CTRL_TC002(char *pkeyPath, char *certPath) { #if !defined(HITLS_CRYPTO_KEY_DECODE) || !defined(HITLS_BSL_SAL_FILE) || !defined(HITLS_PKI_PKCS12_GEN) (void)pkeyPath; (void)certPath; SKIP_TEST(); #else CRYPT_EAL_PkeyCtx *pkey = NULL; HITLS_X509_Cert *enCert = NULL; HITLS_PKCS12_Bag *certBag = NULL; HITLS_PKCS12_Bag *keyBag = NULL; CRYPT_EAL_PkeyCtx *tmpKey = NULL; HITLS_X509_Cert *tmpCert = NULL; uint32_t id; uint32_t type; uint8_t keyId[32] = {0}; uint32_t idLen = 32; BSL_Buffer attr = {.data = keyId, .dataLen = idLen}; int32_t ret = CRYPT_EAL_DecodeFileKey(BSL_FORMAT_ASN1, CRYPT_PRIKEY_PKCS8_UNENCRYPT, pkeyPath, NULL, 0, &pkey); ASSERT_EQ(ret, HITLS_PKI_SUCCESS); keyBag = HITLS_PKCS12_BagNew(BSL_CID_PKCS8SHROUDEDKEYBAG, 0, pkey); ASSERT_NE(keyBag, NULL); ret = HITLS_X509_CertParseFile(BSL_FORMAT_ASN1, certPath, &enCert); ASSERT_EQ(ret, HITLS_PKI_SUCCESS); certBag = HITLS_PKCS12_BagNew(BSL_CID_CERTBAG, BSL_CID_X509CERTIFICATE, enCert); ASSERT_NE(certBag, NULL); ASSERT_EQ(HITLS_PKCS12_BagCtrl(certBag, HITLS_PKCS12_BAG_ADD_ATTR, &attr, BSL_CID_LOCALKEYID), 0); ASSERT_EQ(HITLS_PKCS12_BagCtrl(keyBag, HITLS_PKCS12_BAG_ADD_ATTR, &attr, BSL_CID_LOCALKEYID), 0); ASSERT_EQ(HITLS_PKCS12_BagCtrl(certBag, HITLS_PKCS12_BAG_GET_ID, &id, sizeof(uint32_t)), 0); ASSERT_EQ(id, BSL_CID_CERTBAG); ASSERT_EQ(HITLS_PKCS12_BagCtrl(certBag, HITLS_PKCS12_BAG_GET_TYPE, &type, sizeof(uint32_t)), 0); ASSERT_EQ(type, BSL_CID_X509CERTIFICATE); ASSERT_EQ(HITLS_PKCS12_BagCtrl(certBag, HITLS_PKCS12_BAG_GET_VALUE, NULL, 0), HITLS_PKCS12_ERR_NULL_POINTER); ASSERT_EQ(HITLS_PKCS12_BagCtrl(certBag, HITLS_PKCS12_BAG_GET_VALUE, &tmpCert, 0), 0); ASSERT_NE(tmpCert, NULL); ASSERT_EQ(HITLS_PKCS12_BagCtrl(keyBag, HITLS_PKCS12_BAG_GET_ID, &id, sizeof(uint32_t)), 0); ASSERT_EQ(id, BSL_CID_PKCS8SHROUDEDKEYBAG); ASSERT_EQ(HITLS_PKCS12_BagCtrl(keyBag, HITLS_PKCS12_BAG_GET_TYPE, &type, sizeof(uint32_t)), 0); ASSERT_EQ(type, 0); ASSERT_EQ(HITLS_PKCS12_BagCtrl(keyBag, HITLS_PKCS12_BAG_GET_VALUE, &tmpKey, 0), 0); ASSERT_NE(tmpKey, NULL); EXIT: HITLS_X509_CertFree(enCert); CRYPT_EAL_PkeyFreeCtx(pkey); HITLS_X509_CertFree(tmpCert); CRYPT_EAL_PkeyFreeCtx(tmpKey); HITLS_PKCS12_BagFree(keyBag); HITLS_PKCS12_BagFree(certBag); #endif } /* END_CASE */ /** * For test secret-bag with custom oid. */ /* BEGIN_CASE */ void SDV_PKCS12_BAG_CUSTOM_OID_TC001(void) { #if !defined(HITLS_CRYPTO_KEY_DECODE) || !defined(HITLS_BSL_SAL_FILE) || !defined(HITLS_PKI_PKCS12_GEN) SKIP_TEST(); #else TestMemInit(); ASSERT_EQ(TestRandInit(), 0); const char *writePath = "../testdata/cert/asn1/pkcs12/secret.p12"; HITLS_PKCS12_Bag *tmpBag = NULL; BSL_ASN1_List *secretBags = NULL; char *pwd = "123456"; // All adopt smX algorithms CRYPT_Pbkdf2Param pbParam = {BSL_CID_PBES2, BSL_CID_PBKDF2, CRYPT_MAC_HMAC_SM3, CRYPT_CIPHER_SM4_CBC, 16, (uint8_t *)pwd, strlen(pwd), 2048}; CRYPT_EncodeParam encParam = {CRYPT_DERIVE_PBKDF2, &pbParam}; HITLS_PKCS12_KdfParam macParam = {8, 2048, BSL_CID_SM3, (uint8_t *)pwd, strlen(pwd)}; HITLS_PKCS12_MacParam paramTest = {.para = &macParam, .algId = BSL_CID_PKCS12KDF}; HITLS_PKCS12_EncodeParam encodeParam = {encParam, paramTest}; BSL_Buffer encPwd = {.data = (uint8_t *)pwd, .dataLen = strlen(pwd)}; HITLS_PKCS12_PwdParam pwdParam = {.encPwd = &encPwd, .macPwd = &encPwd}; HITLS_PKCS12_Bag *secretBag = NULL; uint8_t secretData1[20]; uint32_t secretDataLen1 = 20; (void)memset_s(secretData1, secretDataLen1, 'F', secretDataLen1); BSL_Buffer secret = {.data = (uint8_t *)secretData1, .dataLen = secretDataLen1}; char *name = "secret"; uint32_t nameLen = strlen(name); BSL_Buffer friendlyName = {.data = (uint8_t *)name, .dataLen = nameLen}; BSL_Buffer output = {0}; uint32_t id; uint32_t type; char *oid = "\1\1\1\3\1"; int32_t ourCid = BSL_CID_MAX + 1; HITLS_PKCS12 *p12_1 = NULL; HITLS_PKCS12 *p12 = HITLS_PKCS12_New(); ASSERT_NE(p12, NULL); ASSERT_EQ(BSL_OBJ_Create(oid, (uint32_t)strlen(oid), "Our OID", ourCid), HITLS_PKI_SUCCESS); secretBag = HITLS_PKCS12_BagNew(BSL_CID_SECRETBAG, ourCid, &secret); ASSERT_NE(secretBag, NULL); ASSERT_EQ(HITLS_PKCS12_BagCtrl(secretBag, HITLS_PKCS12_BAG_GET_TYPE, &type, sizeof(uint32_t)), 0); ASSERT_EQ(type, ourCid); // Add a attribute to the secretBag. ASSERT_EQ(HITLS_PKCS12_BagCtrl(secretBag, HITLS_PKCS12_BAG_ADD_ATTR, &friendlyName, BSL_CID_FRIENDLYNAME), 0); // Set the secretBag to p12. ASSERT_EQ(HITLS_PKCS12_Ctrl(p12, HITLS_PKCS12_ADD_SECRETBAG, secretBag, 0), 0); // with mac ASSERT_EQ(HITLS_PKCS12_GenFile(BSL_FORMAT_ASN1, p12, &encodeParam, false, writePath), HITLS_PKI_SUCCESS); ASSERT_EQ(HITLS_PKCS12_ParseFile(BSL_FORMAT_ASN1, writePath, &pwdParam, &p12_1, false), HITLS_PKI_SUCCESS); ASSERT_EQ(HITLS_PKCS12_Ctrl(p12_1, HITLS_PKCS12_GET_SECRETBAGS, &secretBags, 0), 0); ASSERT_EQ(BSL_LIST_COUNT(secretBags), 1); tmpBag = BSL_LIST_GET_FIRST(secretBags); ASSERT_EQ(HITLS_PKCS12_BagCtrl(tmpBag, HITLS_PKCS12_BAG_GET_ID, &id, sizeof(uint32_t)), 0); ASSERT_EQ(id, BSL_CID_SECRETBAG); ASSERT_EQ(HITLS_PKCS12_BagCtrl(tmpBag, HITLS_PKCS12_BAG_GET_TYPE, &type, sizeof(uint32_t)), 0); ASSERT_EQ(type, ourCid); EXIT: HITLS_PKCS12_BagFree(secretBag); HITLS_PKCS12_Free(p12); HITLS_PKCS12_Free(p12_1); BSL_SAL_Free(output.data); #endif } /* END_CASE */ static int32_t STUB_HITLS_X509_AddListItemDefault1(void *item, uint32_t len, BSL_ASN1_List *list) { (void)item; (void)len; (void)list; return BSL_MALLOC_FAIL; } static int32_t marked = 0; static int32_t STUB_HITLS_X509_AddListItemDefault2(void *item, uint32_t len, BSL_ASN1_List *list) { if (marked < 2) { marked++; void *node = BSL_SAL_Malloc(len); if (node == NULL) { return BSL_MALLOC_FAIL; } (void)memcpy_s(node, len, item, len); return BSL_LIST_AddElement(list, node, BSL_LIST_POS_AFTER); } return BSL_MALLOC_FAIL; } /** * For test parse safeBag-cert in incorrect condition. */ /* BEGIN_CASE */ void SDV_PKCS12_PARSE_SAFEBAGS_INVALID_TC001(Hex *buff) { #ifndef HITLS_PKI_PKCS12_PARSE (void)buff; SKIP_TEST(); #else FuncStubInfo tmpRpInfo = {0}; BSL_Buffer safeContent = {0}; HITLS_PKCS12 *p12 = NULL; BSL_ASN1_List *bagLists = BSL_LIST_New(sizeof(HITLS_PKCS12_SafeBag)); ASSERT_NE(bagLists, NULL); p12 = HITLS_PKCS12_New(); ASSERT_NE(p12, NULL); char *pwd = "123456"; uint32_t pwdlen = strlen(pwd); // parse contentInfo int32_t ret = HITLS_PKCS12_ParseContentInfo(NULL, NULL, (BSL_Buffer *)buff, (const uint8_t *)pwd, pwdlen, &safeContent); ASSERT_EQ(ret, HITLS_PKI_SUCCESS); STUB_Init(); ASSERT_TRUE(STUB_Replace(&tmpRpInfo, HITLS_X509_AddListItemDefault, STUB_HITLS_X509_AddListItemDefault1) == 0); // get the safeBag of safeContents, and put int list. ret = HITLS_PKCS12_ParseAsn1AddList(&safeContent, bagLists, BSL_CID_SAFECONTENTSBAG); ASSERT_NE(ret, HITLS_PKI_SUCCESS); STUB_Reset(&tmpRpInfo); STUB_Init(); ASSERT_TRUE(STUB_Replace(&tmpRpInfo, HITLS_X509_AddListItemDefault, STUB_HITLS_X509_AddListItemDefault2) == 0); // get the safeBag of safeContents, and put int list. ret = HITLS_PKCS12_ParseAsn1AddList(&safeContent, bagLists, BSL_CID_SAFECONTENTSBAG); ASSERT_NE(ret, HITLS_PKI_SUCCESS); EXIT: marked = 0; BSL_SAL_Free(safeContent.data); BSL_LIST_DeleteAll(bagLists, (BSL_LIST_PFUNC_FREE)HITLS_PKCS12_SafeBagFree); HITLS_PKCS12_Free(p12); BSL_SAL_Free(bagLists); STUB_Reset(&tmpRpInfo); #endif } /* END_CASE */ static int32_t STUB_HITLS_PKCS12_ParseAsn1AddList(BSL_Buffer *encode, BSL_ASN1_List *list, uint32_t parseType) { (void)encode; (void)list; (void)parseType; return BSL_MALLOC_FAIL; } static int32_t STUB_HITLS_PKCS12_ParseContentInfo(HITLS_PKI_LibCtx *libCtx, const char *attrName, BSL_Buffer *encode, const uint8_t *password, uint32_t passLen, BSL_Buffer *data) { (void)libCtx; (void)attrName; (void)encode; (void)password; (void)passLen; (void)data; return BSL_MALLOC_FAIL; } static int32_t STUB_CRYPT_EAL_ProviderDecodeBuffKey(CRYPT_EAL_LibCtx *libCtx, const char *attrName, int32_t keyType, const char *format, const char *type, BSL_Buffer *encode, const BSL_Buffer *pwd, CRYPT_EAL_PkeyCtx **ealPKey) { (void)libCtx; (void)attrName; (void)keyType; (void)format; (void)type; (void)encode; (void)pwd; (void)ealPKey; return BSL_MALLOC_FAIL; } static HITLS_PKCS12_Bag *STUB_HITLS_PKCS12_BagNew(uint32_t bagId, uint32_t bagType, void *bagValue) { (void)bagId; (void)bagType; (void)bagValue; return NULL; } static int32_t STUB_HITLS_X509_CertParseBuff(int32_t format, const BSL_Buffer *encode, HITLS_X509_Cert **cert) { (void)format; (void)encode; (void)cert; return BSL_MALLOC_FAIL; } static int32_t test; static int32_t STUB_BSL_LIST_AddElement(BslList *pList, void *pData, BslListPosition enPosition) { if (marked <= test) { // It takes 53 triggers to prevent cert from entering p12 marked++; return (int32_t)BSL_LIST_AddElementInt(pList, pData, enPosition); } return BSL_MALLOC_FAIL; } #ifdef HITLS_CRYPTO_PROVIDER #define MAX_TRIGGERS 103 #else #define MAX_TRIGGERS 51 #endif /** * For test parse authSafe in incorrect condition. */ /* BEGIN_CASE */ void SDV_PKCS12_PARSE_AUTHSAFE_INVALID_TC001(Hex *buff) { #ifndef HITLS_PKI_PKCS12_PARSE (void)buff; SKIP_TEST(); #else FuncStubInfo tmpRpInfo = {0}; HITLS_PKCS12 *p12 = HITLS_PKCS12_New(); ASSERT_NE(p12, NULL); char *pwd = "123456"; uint32_t pwdlen = strlen(pwd); STUB_Init(); ASSERT_TRUE(STUB_Replace(&tmpRpInfo, HITLS_PKCS12_ParseAsn1AddList, STUB_HITLS_PKCS12_ParseAsn1AddList) == 0); ASSERT_NE(HITLS_PKCS12_ParseAuthSafeData((BSL_Buffer *)buff, (const uint8_t *)pwd, pwdlen, p12), HITLS_PKI_SUCCESS); STUB_Reset(&tmpRpInfo); STUB_Init(); ASSERT_TRUE(STUB_Replace(&tmpRpInfo, HITLS_PKCS12_ParseContentInfo, STUB_HITLS_PKCS12_ParseContentInfo) == 0); ASSERT_NE(HITLS_PKCS12_ParseAuthSafeData((BSL_Buffer *)buff, (const uint8_t *)pwd, pwdlen, p12), HITLS_PKI_SUCCESS); STUB_Reset(&tmpRpInfo); STUB_Init(); ASSERT_TRUE(STUB_Replace(&tmpRpInfo, HITLS_X509_AddListItemDefault, STUB_HITLS_X509_AddListItemDefault1) == 0); ASSERT_NE(HITLS_PKCS12_ParseAuthSafeData((BSL_Buffer *)buff, (const uint8_t *)pwd, pwdlen, p12), HITLS_PKI_SUCCESS); STUB_Reset(&tmpRpInfo); STUB_Init(); ASSERT_TRUE(STUB_Replace(&tmpRpInfo, HITLS_X509_AddListItemDefault, STUB_HITLS_X509_AddListItemDefault2) == 0); ASSERT_NE(HITLS_PKCS12_ParseAuthSafeData((BSL_Buffer *)buff, (const uint8_t *)pwd, pwdlen, p12), HITLS_PKI_SUCCESS); STUB_Reset(&tmpRpInfo); STUB_Init(); ASSERT_TRUE(STUB_Replace(&tmpRpInfo, HITLS_X509_AddListItemDefault, STUB_HITLS_X509_AddListItemDefault2) == 0); ASSERT_NE(HITLS_PKCS12_ParseAuthSafeData((BSL_Buffer *)buff, (const uint8_t *)pwd, pwdlen, p12), HITLS_PKI_SUCCESS); STUB_Reset(&tmpRpInfo); STUB_Init(); ASSERT_TRUE(STUB_Replace(&tmpRpInfo, CRYPT_EAL_ProviderDecodeBuffKey, STUB_CRYPT_EAL_ProviderDecodeBuffKey) == 0); ASSERT_NE(HITLS_PKCS12_ParseAuthSafeData((BSL_Buffer *)buff, (const uint8_t *)pwd, pwdlen, p12), HITLS_PKI_SUCCESS); STUB_Reset(&tmpRpInfo); STUB_Init(); ASSERT_TRUE(STUB_Replace(&tmpRpInfo, HITLS_X509_CertParseBuff, STUB_HITLS_X509_CertParseBuff) == 0); ASSERT_NE(HITLS_PKCS12_ParseAuthSafeData((BSL_Buffer *)buff, (const uint8_t *)pwd, pwdlen, p12), HITLS_PKI_SUCCESS); STUB_Reset(&tmpRpInfo); STUB_Init(); ASSERT_TRUE(STUB_Replace(&tmpRpInfo, HITLS_PKCS12_BagNew, STUB_HITLS_PKCS12_BagNew) == 0); ASSERT_NE(HITLS_PKCS12_ParseAuthSafeData((BSL_Buffer *)buff, (const uint8_t *)pwd, pwdlen, p12), HITLS_PKI_SUCCESS); STUB_Reset(&tmpRpInfo); STUB_Init(); test = MAX_TRIGGERS; // It takes fixed triggers to parse cert from entering p12 marked = 0; ASSERT_TRUE(STUB_Replace(&tmpRpInfo, BSL_LIST_AddElement, STUB_BSL_LIST_AddElement) == 0); HITLS_PKCS12_Free(p12); p12 = NULL; for (int i = MAX_TRIGGERS; i > 0; i--) { p12 = HITLS_PKCS12_New(); marked = 0; test--; ASSERT_NE(HITLS_PKCS12_ParseAuthSafeData((BSL_Buffer *)buff, (const uint8_t *)pwd, pwdlen, p12), HITLS_PKI_SUCCESS); HITLS_PKCS12_Free(p12); p12 = NULL; } EXIT: HITLS_PKCS12_Free(p12); STUB_Reset(&tmpRpInfo); #endif } /* END_CASE */
2301_79861745/bench_create
testcode/sdv/testcase/pki/pkcs12/test_suite_sdv_pkcs12.c
C
unknown
85,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. */ /* BEGIN_HEADER */ #include "bsl_sal.h" #include "securec.h" #include "hitls_pki_pkcs12.h" #include "hitls_pki_errno.h" #include "bsl_types.h" #include "bsl_log.h" #include "sal_file.h" #include "bsl_init.h" #include "hitls_pkcs12_local.h" #include "hitls_crl_local.h" #include "hitls_cert_type.h" #include "hitls_cert_local.h" #include "bsl_types.h" #include "crypt_errno.h" #include "stub_replace.h" #include "bsl_list_internal.h" #include "crypt_eal_rand.h" /* END_HEADER */ static int32_t SetCertBag(HITLS_PKCS12 *p12, HITLS_X509_Cert *cert) { HITLS_PKCS12_Bag *certBag = HITLS_PKCS12_BagNew(BSL_CID_CERTBAG, BSL_CID_X509CERTIFICATE, cert); // new a cert Bag ASSERT_NE(certBag, NULL); char *name = "I am a x509CertBag"; uint32_t nameLen = strlen(name); BSL_Buffer buffer = {0}; buffer.data = (uint8_t *)name; buffer.dataLen = nameLen; ASSERT_EQ(HITLS_PKCS12_BagCtrl(certBag, HITLS_PKCS12_BAG_ADD_ATTR, &buffer, BSL_CID_FRIENDLYNAME), 0); ASSERT_EQ(HITLS_PKCS12_Ctrl(p12, HITLS_PKCS12_ADD_CERTBAG, certBag, 0), 0); EXIT: HITLS_PKCS12_BagFree(certBag); return HITLS_PKI_SUCCESS; } static int32_t SetEntityCertBag(HITLS_PKCS12 *p12, HITLS_X509_Cert *cert) { HITLS_PKCS12_Bag *certBag = HITLS_PKCS12_BagNew(BSL_CID_CERTBAG, BSL_CID_X509CERTIFICATE, cert); // new a cert Bag ASSERT_NE(certBag, NULL); char *name = "I am a entity cert bag"; uint32_t nameLen = strlen(name); BSL_Buffer buffer = {0}; buffer.data = (uint8_t *)name; buffer.dataLen = nameLen; ASSERT_EQ(HITLS_PKCS12_BagCtrl(certBag, HITLS_PKCS12_BAG_ADD_ATTR, &buffer, BSL_CID_FRIENDLYNAME), 0); ASSERT_EQ(HITLS_PKCS12_Ctrl(p12, HITLS_PKCS12_SET_ENTITY_CERTBAG, certBag, 0), 0); EXIT: HITLS_PKCS12_BagFree(certBag); return HITLS_PKI_SUCCESS; } static int32_t SetEntityKeyBag(HITLS_PKCS12 *p12, CRYPT_EAL_PkeyCtx *cert) { HITLS_PKCS12_Bag *pkeyBag = HITLS_PKCS12_BagNew(BSL_CID_PKCS8SHROUDEDKEYBAG, 0, cert); // new a cert Bag ASSERT_NE(pkeyBag, NULL); char *name = "I am a p8 encrypted bag"; uint32_t nameLen = strlen(name); BSL_Buffer buffer = {0}; buffer.data = (uint8_t *)name; buffer.dataLen = nameLen; ASSERT_EQ(HITLS_PKCS12_BagCtrl(pkeyBag, HITLS_PKCS12_BAG_ADD_ATTR, &buffer, BSL_CID_FRIENDLYNAME), 0); ASSERT_EQ(HITLS_PKCS12_Ctrl(p12, HITLS_PKCS12_SET_ENTITY_KEYBAG, pkeyBag, 0), 0); EXIT: HITLS_PKCS12_BagFree(pkeyBag); return HITLS_PKI_SUCCESS; } static int32_t NewAndSetKeyBag(HITLS_PKCS12 *p12, int algId) { CRYPT_EAL_PkeyCtx *key = CRYPT_EAL_ProviderPkeyNewCtx(p12->libCtx, algId, 0, p12->attrName); ASSERT_NE(key, NULL); if (algId == BSL_CID_RSA) { CRYPT_EAL_PkeyPara para = {.id = CRYPT_PKEY_RSA}; uint8_t e[] = {1, 0, 1}; para.para.rsaPara.e = e; para.para.rsaPara.eLen = 3; para.para.rsaPara.bits = 1024; ASSERT_TRUE(CRYPT_EAL_PkeySetPara(key, &para) == CRYPT_SUCCESS); } ASSERT_EQ(CRYPT_EAL_PkeyGen(key), 0); HITLS_PKCS12_Bag *keyBag = HITLS_PKCS12_BagNew(BSL_CID_KEYBAG, 0, key); // new a key Bag ASSERT_NE(keyBag, NULL); char *name = "I am a keyBag"; uint32_t nameLen = strlen(name); BSL_Buffer buffer = {0}; buffer.data = (uint8_t *)name; buffer.dataLen = nameLen; ASSERT_EQ(HITLS_PKCS12_BagCtrl(keyBag, HITLS_PKCS12_BAG_ADD_ATTR, &buffer, BSL_CID_FRIENDLYNAME), 0); ASSERT_EQ(HITLS_PKCS12_Ctrl(p12, HITLS_PKCS12_ADD_KEYBAG, keyBag, 0), 0); EXIT: CRYPT_EAL_PkeyFreeCtx(key); HITLS_PKCS12_BagFree(keyBag); return HITLS_PKI_SUCCESS; } static int32_t NewAndSetSecretBag(HITLS_PKCS12 *p12) { char *secret = "this is the secret."; BSL_Buffer buffer = {0}; buffer.data = (uint8_t *)secret; buffer.dataLen = strlen(secret); // new a secret Bag HITLS_PKCS12_Bag *secretBag = HITLS_PKCS12_BagNew(BSL_CID_SECRETBAG, BSL_CID_PKCS7_SIMPLEDATA, &buffer); ASSERT_NE(secretBag, NULL); char *name = "I am an attribute of secretBag"; uint32_t nameLen = strlen(name); BSL_Buffer buffer2 = {0}; buffer2.data = (uint8_t *)name; buffer2.dataLen = nameLen; ASSERT_EQ(HITLS_PKCS12_BagCtrl(secretBag, HITLS_PKCS12_BAG_ADD_ATTR, &buffer2, BSL_CID_FRIENDLYNAME), 0); ASSERT_EQ(HITLS_PKCS12_Ctrl(p12, HITLS_PKCS12_ADD_SECRETBAG, secretBag, 0), 0); EXIT: HITLS_PKCS12_BagFree(secretBag); return HITLS_PKI_SUCCESS; } /** * For test generating a .p12 inlcuding keyBag, certBag, p8KeyBag and secretBag. */ /* BEGIN_CASE */ void SDV_PKCS12_GEN_KEYBAGS_TC001(char *pkeyPath, char *enCertPath, char *ca1CertPath, char *otherCertPath) { #ifndef HITLS_PKI_PKCS12_GEN (void)pkeyPath; (void)enCertPath; (void)ca1CertPath; (void)otherCertPath; SKIP_TEST(); #else TestMemInit(); ASSERT_EQ(TestRandInit(), 0); char *pwd = "123456"; CRYPT_Pbkdf2Param pbParam = {BSL_CID_PBES2, BSL_CID_PBKDF2, CRYPT_MAC_HMAC_SHA256, CRYPT_CIPHER_AES256_CBC, 16, (uint8_t *)pwd, strlen(pwd), 2048}; CRYPT_EncodeParam encParam = {CRYPT_DERIVE_PBKDF2, &pbParam}; HITLS_PKCS12_KdfParam macParam = {8, 2048, BSL_CID_SHA256, (uint8_t *)pwd, strlen(pwd)}; HITLS_PKCS12_MacParam paramTest = {.para = &macParam, .algId = BSL_CID_PKCS12KDF}; HITLS_PKCS12_EncodeParam encodeParam = {encParam, paramTest}; #ifdef HITLS_PKI_PKCS12_PARSE BSL_Buffer encPwd = {.data = (uint8_t *)pwd, .dataLen = strlen(pwd)}; HITLS_PKCS12_PwdParam pwdParam = {.encPwd = &encPwd, .macPwd = &encPwd}; #endif CRYPT_EAL_PkeyCtx *pkey = NULL; HITLS_X509_Cert *enCert = NULL; HITLS_X509_Cert *ca1Cert = NULL; HITLS_X509_Cert *otherCert = NULL; int32_t mdId = CRYPT_MD_SHA1; BSL_Buffer output = {0}; HITLS_PKCS12 *p12 = HITLS_PKCS12_New(); ASSERT_NE(p12, NULL); HITLS_PKCS12 *p12_1 = NULL; BSL_ASN1_List *certList = NULL; BSL_ASN1_List *keyList = NULL; BSL_ASN1_List *secretBags = NULL; ASSERT_EQ(CRYPT_EAL_DecodeFileKey(BSL_FORMAT_ASN1, CRYPT_PRIKEY_PKCS8_UNENCRYPT, pkeyPath, NULL, 0, &pkey), 0); ASSERT_EQ(HITLS_X509_CertParseFile(BSL_FORMAT_ASN1, enCertPath, &enCert), HITLS_PKI_SUCCESS); ASSERT_EQ(HITLS_X509_CertParseFile(BSL_FORMAT_ASN1, ca1CertPath, &ca1Cert), HITLS_PKI_SUCCESS); ASSERT_EQ(HITLS_X509_CertParseFile(BSL_FORMAT_ASN1, otherCertPath, &otherCert), HITLS_PKI_SUCCESS); // Add the entity cert to p12. ASSERT_EQ(SetEntityCertBag(p12, enCert), HITLS_PKI_SUCCESS); // Add the entity key to p12. ASSERT_EQ(SetEntityKeyBag(p12, pkey), HITLS_PKI_SUCCESS); // Add the ca cert to p12. ASSERT_EQ(SetCertBag(p12, ca1Cert), HITLS_PKI_SUCCESS); // Add the other cert to p12. ASSERT_EQ(SetCertBag(p12, otherCert), HITLS_PKI_SUCCESS); // Gen and add key bag to p12. ASSERT_EQ(NewAndSetKeyBag(p12, BSL_CID_RSA), HITLS_PKI_SUCCESS); ASSERT_EQ(NewAndSetKeyBag(p12, BSL_CID_ED25519), HITLS_PKI_SUCCESS); ASSERT_EQ(NewAndSetSecretBag(p12), HITLS_PKI_SUCCESS); ASSERT_EQ(HITLS_PKCS12_Ctrl(p12, HITLS_PKCS12_GEN_LOCALKEYID, &mdId, sizeof(CRYPT_MD_AlgId)), 0); // Gen a p12. ASSERT_EQ(HITLS_PKCS12_GenBuff(BSL_FORMAT_ASN1, p12, &encodeParam, true, &output), 0); #ifdef HITLS_PKI_PKCS12_PARSE ASSERT_EQ(HITLS_PKCS12_ParseBuff(BSL_FORMAT_ASN1, &output, &pwdParam, &p12_1, true), 0); ASSERT_EQ(HITLS_PKCS12_Ctrl(p12_1, HITLS_PKCS12_GET_CERTBAGS, &certList, 0), 0); ASSERT_EQ(HITLS_PKCS12_Ctrl(p12_1, HITLS_PKCS12_GET_KEYBAGS, &keyList, 0), 0); ASSERT_EQ(HITLS_PKCS12_Ctrl(p12_1, HITLS_PKCS12_GET_SECRETBAGS, &secretBags, 0), 0); ASSERT_EQ(BSL_LIST_COUNT(certList), 2); ASSERT_EQ(BSL_LIST_COUNT(keyList), 2); ASSERT_EQ(BSL_LIST_COUNT(secretBags), 1); ASSERT_NE(p12_1->entityCert, NULL); ASSERT_NE(p12_1->key, NULL); #endif certList = NULL; keyList = NULL; secretBags = NULL; BSL_SAL_FREE(output.data); output.dataLen = 0; ASSERT_EQ(HITLS_PKCS12_GenBuff(BSL_FORMAT_ASN1, p12, &encodeParam, false, &output), 0); HITLS_PKCS12_Free(p12_1); p12_1 = NULL; #ifdef HITLS_PKI_PKCS12_PARSE ASSERT_EQ(HITLS_PKCS12_ParseBuff(BSL_FORMAT_ASN1, &output, &pwdParam, &p12_1, false), 0); ASSERT_EQ(HITLS_PKCS12_Ctrl(p12_1, HITLS_PKCS12_GET_CERTBAGS, &certList, 0), 0); ASSERT_EQ(HITLS_PKCS12_Ctrl(p12_1, HITLS_PKCS12_GET_KEYBAGS, &keyList, 0), 0); ASSERT_EQ(HITLS_PKCS12_Ctrl(p12_1, HITLS_PKCS12_GET_SECRETBAGS, &secretBags, 0), 0); ASSERT_EQ(BSL_LIST_COUNT(certList), 2); ASSERT_EQ(BSL_LIST_COUNT(keyList), 2); ASSERT_EQ(BSL_LIST_COUNT(secretBags), 1); ASSERT_NE(p12_1->entityCert, NULL); ASSERT_NE(p12_1->key, NULL); #endif EXIT: CRYPT_EAL_PkeyFreeCtx(pkey); HITLS_X509_CertFree(enCert); HITLS_X509_CertFree(ca1Cert); HITLS_X509_CertFree(otherCert); HITLS_PKCS12_Free(p12); HITLS_PKCS12_Free(p12_1); BSL_SAL_Free(output.data); #endif } /* END_CASE */ /** * For test ctrl of get key bags from p12. */ /* BEGIN_CASE */ void SDV_PKCS12_CTRL_GET_KEYBAGS_TC001(void) { #ifndef HITLS_PKI_PKCS12_GEN SKIP_TEST(); #else TestMemInit(); ASSERT_EQ(TestRandInit(), 0); char *pwd = "123456"; CRYPT_Pbkdf2Param pbParam = {BSL_CID_PBES2, BSL_CID_PBKDF2, CRYPT_MAC_HMAC_SHA256, CRYPT_CIPHER_AES256_CBC, 16, (uint8_t *)pwd, strlen(pwd), 2048}; CRYPT_EncodeParam encParam = {CRYPT_DERIVE_PBKDF2, &pbParam}; HITLS_PKCS12_KdfParam macParam = {8, 2048, BSL_CID_SHA256, (uint8_t *)pwd, strlen(pwd)}; HITLS_PKCS12_MacParam paramTest = {.para = &macParam, .algId = BSL_CID_PKCS12KDF}; HITLS_PKCS12_EncodeParam encodeParam = {encParam, paramTest}; #ifdef HITLS_PKI_PKCS12_PARSE BSL_Buffer encPwd = {.data = (uint8_t *)pwd, .dataLen = strlen(pwd)}; HITLS_PKCS12_PwdParam pwdParam = {.encPwd = &encPwd, .macPwd = &encPwd}; #endif BSL_ASN1_List *keyList = NULL; BSL_Buffer output = {0}; HITLS_PKCS12 *p12 = HITLS_PKCS12_New(); ASSERT_NE(p12, NULL); HITLS_PKCS12 *p12_1 = NULL; HITLS_PKCS12_Bag *bag = NULL; uint8_t bufferValue[20] = {0}; // 20 bytes is enough for the attr value. uint32_t bufferValueLen = 20; int32_t id = 0; BSL_Buffer buffer = {.data = bufferValue, .dataLen = bufferValueLen}; char *attrName = "I am a keyBag"; CRYPT_EAL_PkeyCtx *key = NULL; ASSERT_EQ(NewAndSetKeyBag(p12, BSL_CID_RSA), HITLS_PKI_SUCCESS); ASSERT_EQ(NewAndSetKeyBag(p12, BSL_CID_ED25519), HITLS_PKI_SUCCESS); ASSERT_EQ(NewAndSetSecretBag(p12), HITLS_PKI_SUCCESS); // Gen a p12. ASSERT_EQ(HITLS_PKCS12_GenBuff(BSL_FORMAT_ASN1, p12, &encodeParam, true, &output), 0); #ifdef HITLS_PKI_PKCS12_PARSE ASSERT_EQ(HITLS_PKCS12_ParseBuff(BSL_FORMAT_ASN1, &output, &pwdParam, &p12_1, true), 0); ASSERT_EQ(HITLS_PKCS12_Ctrl(p12_1, HITLS_PKCS12_GET_KEYBAGS, &keyList, 0), 0); ASSERT_EQ(BSL_LIST_COUNT(keyList), 2); ASSERT_NE(keyList, NULL); bag = BSL_LIST_GET_FIRST(keyList); while (bag != NULL) { ASSERT_EQ(HITLS_PKCS12_BagCtrl(bag, HITLS_PKCS12_BAG_GET_VALUE, &key, 0), 0); ASSERT_NE(key, NULL); ASSERT_EQ(HITLS_PKCS12_BagCtrl(bag, HITLS_PKCS12_BAG_GET_ID, &id, sizeof(int32_t)), 0); ASSERT_EQ(id, BSL_CID_KEYBAG); ASSERT_EQ(HITLS_PKCS12_BagCtrl(bag, HITLS_PKCS12_BAG_GET_ATTR, &buffer, BSL_CID_FRIENDLYNAME), 0); ASSERT_COMPARE("compare key bag attr", buffer.data, buffer.dataLen, attrName, strlen(attrName)); ASSERT_EQ(HITLS_PKCS12_BagCtrl(bag, HITLS_PKCS12_BAG_GET_ATTR, &buffer, BSL_CID_LOCALKEYID), HITLS_PKCS12_ERR_NO_SAFEBAG_ATTRIBUTES); bag = BSL_LIST_GET_NEXT(keyList); CRYPT_EAL_PkeyFreeCtx(key); key = NULL; } #endif EXIT: HITLS_PKCS12_Free(p12); HITLS_PKCS12_Free(p12_1); BSL_SAL_Free(output.data); #endif } /* END_CASE */ /** * For test parse multi bags in p12, including certBag, keyBag, secretBag, p8ShroudedKeyBag. */ /* BEGIN_CASE */ void SDV_PKCS12_PARSE_MULBAG_TC001(Hex *mulBag, int hasMac) { #ifndef HITLS_PKI_PKCS12_PARSE (void)mulBag; (void)hasMac; SKIP_TEST(); #else char *pwd = "123456"; BSL_Buffer encPwd = {.data = (uint8_t *)pwd, .dataLen = strlen(pwd)}; HITLS_PKCS12_PwdParam pwdParam = {.encPwd = &encPwd, .macPwd = &encPwd}; HITLS_PKCS12 *p12 = NULL; BSL_Buffer buffer = {.data = (uint8_t *)mulBag->x, .dataLen = mulBag->len}; ASSERT_EQ(HITLS_PKCS12_ParseBuff(BSL_FORMAT_ASN1, &buffer, &pwdParam, &p12, hasMac == 1), 0); ASSERT_NE(BSL_LIST_COUNT(p12->certList), 0); ASSERT_NE(BSL_LIST_COUNT(p12->keyList), 0); ASSERT_NE(BSL_LIST_COUNT(p12->secretBags), 0); ASSERT_NE(p12->key, NULL); EXIT: HITLS_PKCS12_Free(p12); #endif } /* END_CASE */ #if defined(HITLS_CRYPTO_PROVIDER) && defined(HITLS_PKI_PKCS12_PARSE) && defined(HITLS_PKI_PKCS12_GEN) #define HITLS_P12_LIB_NAME "libprovider_load_p12.so" #define HITLS_P12_PROVIDER_ATTR "provider?=p12Load" #define HITLS_P12_PROVIDER_PATH "../../testcode/testdata/provider/path1" static CRYPT_EAL_LibCtx *P12_ProviderLoadWithDefault(void) { CRYPT_EAL_LibCtx *libCtx = CRYPT_EAL_LibCtxNew(); ASSERT_TRUE(libCtx != NULL); ASSERT_EQ(CRYPT_EAL_ProviderSetLoadPath(libCtx, HITLS_P12_PROVIDER_PATH), CRYPT_SUCCESS); ASSERT_EQ(CRYPT_EAL_ProviderLoad(libCtx, 0, HITLS_P12_LIB_NAME, NULL, NULL), CRYPT_SUCCESS); ASSERT_EQ(CRYPT_EAL_ProviderLoad(libCtx, 0, "default", NULL, NULL), CRYPT_SUCCESS); ASSERT_EQ(CRYPT_EAL_ProviderRandInitCtx(libCtx, CRYPT_RAND_SHA256, HITLS_P12_PROVIDER_ATTR, NULL, 0, NULL), CRYPT_SUCCESS); return libCtx; EXIT: CRYPT_EAL_LibCtxFree(libCtx); return NULL; } static int32_t STUB_HITLS_PKCS12_CalMac(HITLS_PKCS12 *p12, BSL_Buffer *pwd, BSL_Buffer *initData, BSL_Buffer *output) { (void)p12; (void)pwd; (void)initData; uint8_t *temp = BSL_SAL_Malloc(32); ASSERT_TRUE(temp != NULL); uint8_t outBuf[32] = {0xe3, 0x69, 0x5a, 0x9a, 0xfe, 0x27, 0x53, 0x4c, 0x95, 0x17, 0x67, 0xa2, 0x3f, 0x83, 0x9f, 0x94, 0x55, 0xb7, 0xf9, 0x00, 0x4b, 0xbc, 0x28, 0xbb, 0x9d, 0x59, 0x73, 0xbb, 0x91, 0xd0, 0x7c, 0x53}; memcpy(temp, outBuf, 32); output->data = temp; output->dataLen = 32; EXIT: return CRYPT_SUCCESS; } #endif /** * For test parse p12 with provider. */ /* BEGIN_CASE */ void SDV_PKCS12_PARSE_WITH_PROVIDER_TC001(Hex *mulBag) { #if !defined(HITLS_PKI_PKCS12_PARSE) || !defined(HITLS_CRYPTO_PROVIDER) (void)mulBag; SKIP_TEST(); #else CRYPT_EAL_LibCtx *libCtx = NULL; libCtx = P12_ProviderLoadWithDefault(); ASSERT_TRUE(libCtx != NULL); FuncStubInfo tmpRpInfo = {0}; char *pwd = "123456"; BSL_Buffer encPwd = {.data = (uint8_t *)pwd, .dataLen = strlen(pwd)}; HITLS_PKCS12_PwdParam pwdParam = {.encPwd = &encPwd, .macPwd = &encPwd}; HITLS_PKCS12 *p12 = NULL; BSL_Buffer buffer = {.data = (uint8_t *)mulBag->x, .dataLen = mulBag->len}; ASSERT_EQ(HITLS_PKCS12_ProviderParseBuff(libCtx, HITLS_P12_PROVIDER_ATTR, "ASN1", &buffer, &pwdParam, &p12, true), HITLS_PKCS12_ERR_VERIFY_FAIL); // mac has been installed. STUB_Init(); ASSERT_TRUE(STUB_Replace(&tmpRpInfo, HITLS_PKCS12_CalMac, STUB_HITLS_PKCS12_CalMac) == 0); ASSERT_EQ(HITLS_PKCS12_ProviderParseBuff(libCtx, HITLS_P12_PROVIDER_ATTR, "ASN1", &buffer, &pwdParam, &p12, true), HITLS_PKI_SUCCESS); ASSERT_NE(p12, NULL); ASSERT_NE(BSL_LIST_COUNT(p12->certList), 0); ASSERT_NE(BSL_LIST_COUNT(p12->keyList), 0); ASSERT_NE(BSL_LIST_COUNT(p12->secretBags), 0); ASSERT_NE(p12->key, NULL); EXIT: HITLS_PKCS12_Free(p12); CRYPT_EAL_RandDeinitEx(libCtx); CRYPT_EAL_LibCtxFree(libCtx); STUB_Reset(&tmpRpInfo); #endif } /* END_CASE */ /** * For test encode p12 with provider. */ /* BEGIN_CASE */ void SDV_PKCS12_ENCODE_WITH_PROVIDER_TC001(void) { #if !defined(HITLS_PKI_PKCS12_GEN) || !defined(HITLS_CRYPTO_PROVIDER) SKIP_TEST(); #else CRYPT_EAL_RandDeinit(); CRYPT_EAL_LibCtx *libCtx = NULL; libCtx = P12_ProviderLoadWithDefault(); ASSERT_TRUE(libCtx != NULL); BSL_Buffer output = {0}; char *pwd = "123456"; CRYPT_Pbkdf2Param pbParam = {BSL_CID_PBES2, BSL_CID_PBKDF2, CRYPT_MAC_HMAC_SM3, CRYPT_CIPHER_AES256_CBC, 16, (uint8_t *)pwd, strlen(pwd), 2048}; CRYPT_EncodeParam encParam = {CRYPT_DERIVE_PBKDF2, &pbParam}; HITLS_PKCS12_KdfParam macParam = {8, 2048, BSL_CID_SHA256, (uint8_t *)pwd, strlen(pwd)}; HITLS_PKCS12_MacParam paramTest = {.para = &macParam, .algId = BSL_CID_PKCS12KDF}; HITLS_PKCS12_EncodeParam encodeParam = {encParam, paramTest}; HITLS_PKCS12 *p12 = HITLS_PKCS12_ProviderNew(libCtx, HITLS_P12_PROVIDER_ATTR); ASSERT_EQ(NewAndSetKeyBag(p12, BSL_CID_RSA), HITLS_PKI_SUCCESS); ASSERT_EQ(HITLS_PKCS12_GenBuff(BSL_FORMAT_ASN1, p12, &encodeParam, true, &output), HITLS_PKI_SUCCESS); EXIT: BSL_SAL_Free(output.data); HITLS_PKCS12_Free(p12); CRYPT_EAL_RandDeinitEx(libCtx); CRYPT_EAL_LibCtxFree(libCtx); #endif } /* END_CASE */
2301_79861745/bench_create
testcode/sdv/testcase/pki/pkcs12/test_suite_sdv_pkcs12_util.c
C
unknown
17,489
/* * This file is part of the openHiTLS project. * * openHiTLS is licensed under the Mulan PSL v2. * You can use this software according to the terms and conditions of the Mulan PSL v2. * You may obtain a copy of Mulan PSL v2 at: * * http://license.coscl.org.cn/MulanPSL2 * * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, * EITHER EXPRESS 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 <string.h> #include <unistd.h> #include <stdlib.h> #include "bsl_sal.h" #include "securec.h" #include "bsl_types.h" #include "bsl_log.h" #include "bsl_init.h" #include "bsl_list.h" #include "hitls_pki_x509.h" #include "hitls_pki_errno.h" #include "hitls_x509_verify.h" #include "hitls_cert_local.h" #include "hitls_crl_local.h" #include "bsl_list_internal.h" #include "sal_atomic.h" #include "hitls_x509_verify.h" #include "crypt_eal_md.h" #include "crypt_errno.h" #include "bsl_uio.h" #include "hitls_pki_utils.h" #include "bsl_asn1.h" /* END_HEADER */ void HITLS_X509_FreeStoreCtxMock(HITLS_X509_StoreCtx *ctx) { if (ctx == NULL) { return; } int ret; (void)BSL_SAL_AtomicDownReferences(&ctx->references, &ret); if (ret > 0) { return; } if (ctx->store != NULL) { BSL_LIST_FREE(ctx->store, (BSL_LIST_PFUNC_FREE)HITLS_X509_CertFree); } if (ctx->crl != NULL) { BSL_LIST_FREE(ctx->crl, (BSL_LIST_PFUNC_FREE)HITLS_X509_CrlFree); } BSL_SAL_ReferencesFree(&ctx->references); BSL_SAL_Free(ctx); } HITLS_X509_StoreCtx *HITLS_X509_NewStoreCtxMock(void) { HITLS_X509_StoreCtx *ctx = (HITLS_X509_StoreCtx *)BSL_SAL_Malloc(sizeof(HITLS_X509_StoreCtx)); if (ctx == NULL) { return NULL; } (void)memset_s(ctx, sizeof(HITLS_X509_StoreCtx), 0, sizeof(HITLS_X509_StoreCtx)); ctx->store = BSL_LIST_New(sizeof(HITLS_X509_Cert *)); if (ctx->store == NULL) { BSL_SAL_Free(ctx); return NULL; } ctx->crl = BSL_LIST_New(sizeof(HITLS_X509_Crl *)); if (ctx->crl == NULL) { BSL_SAL_FREE(ctx->store); BSL_SAL_Free(ctx); return NULL; } ctx->verifyParam.maxDepth = 20; ctx->verifyParam.securityBits = 128; ctx->verifyParam.flags |= HITLS_X509_VFY_FLAG_CRL_ALL; ctx->verifyParam.flags |= HITLS_X509_VFY_FLAG_SECBITS; BSL_SAL_ReferencesInit(&(ctx->references)); return ctx; } static int32_t HITLS_BuildChain(BslList *list, int type, char *path1, char *path2, char *path3, char *path4, char *path5) { int32_t ret; char *path[] = {path1, path2, path3, path4, path5}; for (size_t i = 0; i < sizeof(path) / sizeof(path[0]); i++) { if (path[i] == NULL) { continue; } if (type == 0) { // cert HITLS_X509_Cert *cert = NULL; ret = HITLS_X509_CertParseFile(BSL_FORMAT_ASN1, path[i], &cert); if (ret != HITLS_PKI_SUCCESS) { return ret; } ret = BSL_LIST_AddElement(list, cert, BSL_LIST_POS_END); if (ret != BSL_SUCCESS) { return ret; } } else { // crl HITLS_X509_Crl *crl = NULL; ret = HITLS_X509_CrlParseFile(BSL_FORMAT_ASN1, path[i], &crl); if (ret != HITLS_PKI_SUCCESS) { return ret; } ret = BSL_LIST_AddElement(list, crl, BSL_LIST_POS_END); if (ret != BSL_SUCCESS) { return ret; } } } return ret; } /* BEGIN_CASE */ void SDV_X509_STORE_VFY_PARAM_EXR_FUNC_TC001(char *path1, char *path2, char *path3, int secBits, int exp) { int ret; TestMemInit(); HITLS_X509_StoreCtx *storeCtx = NULL; storeCtx = HITLS_X509_NewStoreCtxMock(); ASSERT_NE(storeCtx, NULL); storeCtx->verifyParam.securityBits = secBits; BslList *chain = BSL_LIST_New(sizeof(HITLS_X509_Cert *)); ASSERT_NE(chain, NULL); ret = HITLS_BuildChain(chain, 0, path1, path2, path3, NULL, NULL); ASSERT_EQ(ret, HITLS_PKI_SUCCESS); ret = HITLS_X509_VerifyParamAndExt(storeCtx, chain); ASSERT_EQ(ret, exp); EXIT: HITLS_X509_FreeStoreCtxMock(storeCtx); BSL_LIST_FREE(chain, (BSL_LIST_PFUNC_FREE)HITLS_X509_CertFree); } /* END_CASE */ /* BEGIN_CASE */ void SDV_X509_STORE_VFY_CRL_FUNC_TC001(int type, int expResult, char *path1, char *path2, char *path3, char *crl1, char *crl2) { int ret; TestMemInit(); HITLS_X509_StoreCtx *storeCtx = NULL; storeCtx = HITLS_X509_NewStoreCtxMock(); ASSERT_NE(storeCtx, NULL); if (type == 1) { storeCtx->verifyParam.flags ^= HITLS_X509_VFY_FLAG_CRL_ALL; storeCtx->verifyParam.flags |= HITLS_X509_VFY_FLAG_CRL_DEV; } BslList *chain = BSL_LIST_New(sizeof(HITLS_X509_Cert *)); ASSERT_NE(chain, NULL); ret = HITLS_BuildChain(chain, 0, path1, path2, path3, NULL, NULL); ASSERT_EQ(ret, HITLS_PKI_SUCCESS); ret = HITLS_BuildChain(storeCtx->crl, 1, crl1, crl2, NULL, NULL, NULL); ASSERT_EQ(ret, HITLS_PKI_SUCCESS); ret = HITLS_X509_VerifyCrl(storeCtx, chain); ASSERT_EQ(ret, expResult); EXIT: HITLS_X509_FreeStoreCtxMock(storeCtx); BSL_LIST_FREE(chain, (BSL_LIST_PFUNC_FREE)HITLS_X509_CertFree); } /* END_CASE */ /* BEGIN_CASE */ void SDV_X509_STORE_CTRL_FUNC_TC001(void) { HITLS_X509_StoreCtx *store = HITLS_X509_StoreCtxNew(); ASSERT_TRUE(store != NULL); int32_t val = 20; int32_t ret = HITLS_X509_StoreCtxCtrl(store, HITLS_X509_STORECTX_SET_PARAM_DEPTH, &val, sizeof(int32_t)); ASSERT_EQ(ret, HITLS_PKI_SUCCESS); ASSERT_EQ(store->verifyParam.maxDepth, val); ret = HITLS_X509_StoreCtxCtrl(store, HITLS_X509_STORECTX_SET_SECBITS, &val, sizeof(int32_t)); ASSERT_EQ(ret, HITLS_PKI_SUCCESS); ASSERT_EQ(store->verifyParam.securityBits, val); ASSERT_EQ(store->verifyParam.flags, HITLS_X509_VFY_FLAG_SECBITS); int64_t timeval = 55; ret = HITLS_X509_StoreCtxCtrl(store, HITLS_X509_STORECTX_SET_TIME, &timeval, sizeof(timeval)); ASSERT_EQ(ret, HITLS_PKI_SUCCESS); ASSERT_EQ(store->verifyParam.time, timeval); ASSERT_EQ(store->verifyParam.flags & HITLS_X509_VFY_FLAG_TIME, HITLS_X509_VFY_FLAG_TIME); timeval = HITLS_X509_VFY_FLAG_TIME; ret = HITLS_X509_StoreCtxCtrl(store, HITLS_X509_STORECTX_CLR_PARAM_FLAGS, &timeval, sizeof(timeval)); ASSERT_EQ(ret, HITLS_PKI_SUCCESS); ASSERT_EQ(store->verifyParam.flags & HITLS_X509_VFY_FLAG_TIME, 0); ASSERT_EQ(store->verifyParam.flags, HITLS_X509_VFY_FLAG_SECBITS); int ref; ret = HITLS_X509_StoreCtxCtrl(store, HITLS_X509_STORECTX_REF_UP, &ref, sizeof(int)); ASSERT_EQ(ret, HITLS_PKI_SUCCESS); ASSERT_EQ(ref, 2); HITLS_X509_StoreCtxFree(store); EXIT: HITLS_X509_StoreCtxFree(store); } /* END_CASE */ /* BEGIN_CASE */ void SDV_X509_STORE_CTRL_CERT_FUNC_TC002(void) { HITLS_X509_StoreCtx *store = HITLS_X509_StoreCtxNew(); HITLS_X509_Cert *cert = NULL; int32_t ret = HITLS_X509_CertParseFile(BSL_FORMAT_ASN1, "../testdata/cert/asn1/rsa2048ssa-pss.crt", &cert); ASSERT_EQ(ret, HITLS_PKI_SUCCESS); ASSERT_EQ(ret, HITLS_PKI_SUCCESS); ret = HITLS_X509_StoreCtxCtrl(store, HITLS_X509_STORECTX_DEEP_COPY_SET_CA, cert, sizeof(HITLS_X509_Cert)); ASSERT_EQ(ret, HITLS_PKI_SUCCESS); ASSERT_EQ(cert->references.count, 2); ASSERT_EQ(BSL_LIST_COUNT(store->store), 1); ret = HITLS_X509_StoreCtxCtrl(store, HITLS_X509_STORECTX_DEEP_COPY_SET_CA, cert, sizeof(HITLS_X509_Cert)); ASSERT_TRUE(ret != HITLS_PKI_SUCCESS); HITLS_X509_Crl *crl = NULL; ret = HITLS_X509_CrlParseFile(BSL_FORMAT_ASN1, "../testdata/cert/asn1/ca-empty-rsa-sha256-v2.der", &crl); ret = HITLS_X509_StoreCtxCtrl(store, HITLS_X509_STORECTX_SET_CRL, crl, sizeof(HITLS_X509_Crl)); ASSERT_EQ(ret, HITLS_PKI_SUCCESS); ASSERT_EQ(crl->references.count, 2); ASSERT_EQ(BSL_LIST_COUNT(store->crl), 1); ret = HITLS_X509_StoreCtxCtrl(store, HITLS_X509_STORECTX_SET_CRL, crl, sizeof(HITLS_X509_Crl)); ASSERT_TRUE(ret != HITLS_PKI_SUCCESS); EXIT: HITLS_X509_StoreCtxFree(store); HITLS_X509_CertFree(cert); HITLS_X509_CrlFree(crl); } /* END_CASE */ static int32_t HITLS_AddCertToStoreTest(char *path, HITLS_X509_StoreCtx *store, HITLS_X509_Cert **cert) { int32_t ret = HITLS_X509_CertParseFile(BSL_FORMAT_UNKNOWN, path, cert); if (ret != HITLS_PKI_SUCCESS) { return ret; } return HITLS_X509_StoreCtxCtrl(store, HITLS_X509_STORECTX_DEEP_COPY_SET_CA, *cert, sizeof(HITLS_X509_Cert)); } static int32_t HITLS_AddCrlToStoreTest(char *path, HITLS_X509_StoreCtx *store, HITLS_X509_Crl **crl) { int32_t ret = HITLS_X509_CrlParseFile(BSL_FORMAT_ASN1, path, crl); if (ret != HITLS_PKI_SUCCESS) { return ret; } return HITLS_X509_StoreCtxCtrl(store, HITLS_X509_STORECTX_SET_CRL, *crl, sizeof(HITLS_X509_Crl)); } /* BEGIN_CASE */ void SDV_X509_BUILD_CERT_CHAIN_FUNC_TC001(char *rootPath, char *caPath, char *cert, char *crlPath) { TestMemInit(); HITLS_X509_StoreCtx *store = HITLS_X509_StoreCtxNew(); ASSERT_TRUE(store != NULL); HITLS_X509_Cert *root = NULL; ASSERT_EQ(HITLS_AddCertToStoreTest(rootPath, store, &root), HITLS_PKI_SUCCESS); HITLS_X509_Cert *ca = NULL; ASSERT_EQ(HITLS_AddCertToStoreTest(caPath, store, &ca), HITLS_PKI_SUCCESS); HITLS_X509_Cert *entity = NULL; ASSERT_TRUE(HITLS_AddCertToStoreTest(cert, store, &entity) != HITLS_PKI_SUCCESS); HITLS_X509_Crl *crl = NULL; ASSERT_EQ(HITLS_AddCrlToStoreTest(crlPath, store, &crl), HITLS_PKI_SUCCESS); ASSERT_EQ(BSL_LIST_COUNT(store->crl), 1); ASSERT_EQ(BSL_LIST_COUNT(store->store), 2); HITLS_X509_List *chain = NULL; ASSERT_TRUE(HITLS_X509_CertChainBuild(store, false, entity, &chain) == HITLS_PKI_SUCCESS); ASSERT_EQ(BSL_LIST_COUNT(chain), 2); int64_t timeval = time(NULL); ASSERT_EQ(HITLS_X509_StoreCtxCtrl(store, HITLS_X509_STORECTX_SET_TIME, &timeval, sizeof(timeval)), 0); int64_t flag = HITLS_X509_VFY_FLAG_CRL_ALL; ASSERT_EQ(HITLS_X509_StoreCtxCtrl(store, HITLS_X509_STORECTX_CLR_PARAM_FLAGS, &flag, sizeof(flag)), 0); ASSERT_EQ(HITLS_X509_CertVerify(store, chain), HITLS_PKI_SUCCESS); EXIT: HITLS_X509_StoreCtxFree(store); HITLS_X509_CertFree(root); HITLS_X509_CertFree(ca); HITLS_X509_CertFree(entity); HITLS_X509_CrlFree(crl); BSL_LIST_FREE(chain, (BSL_LIST_PFUNC_FREE)HITLS_X509_CertFree); } /* END_CASE */ /* BEGIN_CASE */ void SDV_X509_BUILD_CERT_CHAIN_FUNC_TC002(void) { HITLS_X509_StoreCtx *store = HITLS_X509_StoreCtxNew(); ASSERT_TRUE(store != NULL); HITLS_X509_Cert *ca = NULL; int32_t ret = HITLS_AddCertToStoreTest("../testdata/cert/chain/rsa-pss-v3/inter.der", store, &ca); ASSERT_EQ(ret, HITLS_PKI_SUCCESS); HITLS_X509_Cert *entity = NULL; ret = HITLS_AddCertToStoreTest("../testdata/cert/chain/rsa-pss-v3/end.der", store, &entity); ASSERT_TRUE(ret != HITLS_PKI_SUCCESS); ASSERT_EQ(BSL_LIST_COUNT(store->store), 1); HITLS_X509_List *chain = NULL; ret = HITLS_X509_CertChainBuild(store, false, entity, &chain); ASSERT_TRUE(ret == HITLS_PKI_SUCCESS); BSL_LIST_FREE(chain, (BSL_LIST_PFUNC_FREE)HITLS_X509_CertFree); HITLS_X509_Cert *root = NULL; ret = HITLS_AddCertToStoreTest("../testdata/cert/chain/rsa-pss-v3/ca.der", store, &root); ASSERT_EQ(ret, HITLS_PKI_SUCCESS); ret = HITLS_X509_CertChainBuild(store, false, entity, &chain); ASSERT_EQ(ret, HITLS_PKI_SUCCESS); ASSERT_EQ(BSL_LIST_COUNT(chain), 2); int64_t timeval = time(NULL); ret = HITLS_X509_StoreCtxCtrl(store, HITLS_X509_STORECTX_SET_TIME, &timeval, sizeof(timeval)); ASSERT_EQ(ret, HITLS_PKI_SUCCESS); ASSERT_EQ(ret, HITLS_PKI_SUCCESS); ret = HITLS_X509_CertVerify(store, chain); ASSERT_EQ(ret, HITLS_PKI_SUCCESS); EXIT: HITLS_X509_StoreCtxFree(store); HITLS_X509_CertFree(root); HITLS_X509_CertFree(ca); HITLS_X509_CertFree(entity); BSL_LIST_FREE(chain, (BSL_LIST_PFUNC_FREE)HITLS_X509_CertFree); } /* END_CASE */ static int32_t X509_AddCertToChainTest(HITLS_X509_List *chain, HITLS_X509_Cert *cert) { int ref; int32_t ret = HITLS_X509_CertCtrl(cert, HITLS_X509_REF_UP, &ref, sizeof(int)); if (ret != HITLS_PKI_SUCCESS) { return ret; } ret = BSL_LIST_AddElement(chain, cert, BSL_LIST_POS_END); if (ret != HITLS_PKI_SUCCESS) { HITLS_X509_CertFree(cert); } return ret; } /* BEGIN_CASE */ void SDV_X509_BUILD_CERT_CHAIN_FUNC_TC003(void) { HITLS_X509_StoreCtx *store = HITLS_X509_StoreCtxNew(); ASSERT_TRUE(store != NULL); HITLS_X509_Cert *ca = NULL; HITLS_X509_Cert *root = NULL; int32_t ret = HITLS_X509_CertParseFile(BSL_FORMAT_ASN1, "../testdata/cert/chain/rsa-pss-v3/ca.der", &root); ASSERT_EQ(ret, HITLS_PKI_SUCCESS); ret = HITLS_AddCertToStoreTest("../testdata/cert/chain/rsa-pss-v3/inter.der", store, &ca); ASSERT_EQ(ret, HITLS_PKI_SUCCESS); HITLS_X509_Cert *entity = NULL; ret = HITLS_X509_CertParseFile(BSL_FORMAT_ASN1, "../testdata/cert/chain/rsa-pss-v3/end.der", &entity); ASSERT_EQ(BSL_LIST_COUNT(store->store), 1); HITLS_X509_List *chain = BSL_LIST_New(sizeof(HITLS_X509_Cert *)); ASSERT_TRUE(chain != NULL); ret = X509_AddCertToChainTest(chain, entity); ASSERT_EQ(ret, HITLS_PKI_SUCCESS); ret = X509_AddCertToChainTest(chain, ca); ASSERT_EQ(ret, HITLS_PKI_SUCCESS); ASSERT_EQ(ret, HITLS_PKI_SUCCESS); ret = HITLS_X509_CertVerify(store, chain); ASSERT_TRUE(ret != HITLS_PKI_SUCCESS); EXIT: HITLS_X509_StoreCtxFree(store); HITLS_X509_CertFree(root); HITLS_X509_CertFree(ca); HITLS_X509_CertFree(entity); BSL_LIST_FREE(chain, (BSL_LIST_PFUNC_FREE)HITLS_X509_CertFree); } /* END_CASE */ /* BEGIN_CASE */ void SDV_X509_BUILD_CERT_CHAIN_FUNC_TC004(void) { HITLS_X509_StoreCtx *store = HITLS_X509_StoreCtxNew(); ASSERT_TRUE(store != NULL); HITLS_X509_Cert *root = NULL; int32_t ret = HITLS_AddCertToStoreTest("../testdata/cert/chain/rsa-pss-v3/ca.der", store, &root); ASSERT_EQ(ret, HITLS_PKI_SUCCESS); ASSERT_EQ(BSL_LIST_COUNT(store->store), 1); HITLS_X509_List *chain = NULL; ret = HITLS_X509_CertChainBuild(store, false, root, &chain); ASSERT_EQ(ret, HITLS_PKI_SUCCESS); ASSERT_TRUE(chain != NULL); ASSERT_EQ(BSL_LIST_COUNT(chain), 1); ASSERT_EQ(ret, HITLS_PKI_SUCCESS); ret = HITLS_X509_CertVerify(store, chain); ASSERT_EQ(ret, HITLS_PKI_SUCCESS); EXIT: HITLS_X509_StoreCtxFree(store); HITLS_X509_CertFree(root); BSL_LIST_FREE(chain, (BSL_LIST_PFUNC_FREE)HITLS_X509_CertFree); } /* END_CASE */ /* BEGIN_CASE */ void SDV_X509_BUILD_CERT_CHAIN_FUNC_TC005(void) { HITLS_X509_StoreCtx *store = HITLS_X509_StoreCtxNew(); ASSERT_TRUE(store != NULL); HITLS_X509_Cert *root = NULL; int32_t ret = HITLS_X509_CertParseFile(BSL_FORMAT_ASN1, "../testdata/cert/chain/rsa-pss-v3/ca.der", &root); ASSERT_EQ(ret, HITLS_PKI_SUCCESS); ASSERT_EQ(BSL_LIST_COUNT(store->store), 0); HITLS_X509_List *chain = NULL; ret = HITLS_X509_CertChainBuild(store, false, root, &chain); ASSERT_EQ(ret, HITLS_PKI_SUCCESS); ASSERT_TRUE(chain != NULL); ASSERT_EQ(BSL_LIST_COUNT(chain), 1); ASSERT_EQ(ret, HITLS_PKI_SUCCESS); ret = HITLS_X509_CertVerify(store, chain); ASSERT_TRUE(ret != HITLS_PKI_SUCCESS); EXIT: HITLS_X509_StoreCtxFree(store); HITLS_X509_CertFree(root); BSL_LIST_FREE(chain, (BSL_LIST_PFUNC_FREE)HITLS_X509_CertFree); } /* END_CASE */ /* BEGIN_CASE */ void SDV_X509_BUILD_CERT_CHAIN_FUNC_TC006(void) { HITLS_X509_StoreCtx *store = HITLS_X509_StoreCtxNew(); ASSERT_TRUE(store != NULL); HITLS_X509_Cert *root = NULL; int32_t ret = HITLS_X509_CertParseFile(BSL_FORMAT_ASN1, "../testdata/cert/chain/rsa-pss-v3/ca.der", &root); ASSERT_EQ(ret, HITLS_PKI_SUCCESS); ASSERT_EQ(BSL_LIST_COUNT(store->store), 0); HITLS_X509_List *chain = NULL; ret = HITLS_X509_CertChainBuild(store, false, root, &chain); ASSERT_EQ(ret, HITLS_PKI_SUCCESS); ASSERT_TRUE(chain != NULL); ASSERT_EQ(BSL_LIST_COUNT(chain), 1); int64_t timeval = 5555; ret = HITLS_X509_StoreCtxCtrl(store, HITLS_X509_STORECTX_SET_TIME, &timeval, sizeof(timeval)); ASSERT_EQ(ret, HITLS_PKI_SUCCESS); ASSERT_EQ(ret, HITLS_PKI_SUCCESS); ret = HITLS_X509_CertVerify(store, chain); ASSERT_TRUE(ret != HITLS_PKI_SUCCESS); EXIT: HITLS_X509_StoreCtxFree(store); HITLS_X509_CertFree(root); BSL_LIST_FREE(chain, (BSL_LIST_PFUNC_FREE)HITLS_X509_CertFree); } /* END_CASE */ /* BEGIN_CASE */ void SDV_X509_BUILD_CERT_CHAIN_FUNC_TC007(void) { HITLS_X509_StoreCtx *store = HITLS_X509_StoreCtxNew(); ASSERT_TRUE(store != NULL); HITLS_X509_Cert *root = NULL; int32_t ret = HITLS_AddCertToStoreTest("../testdata/cert/chain/rsa-v3/rootca.der", store, &root); ASSERT_EQ(ret, HITLS_PKI_SUCCESS); HITLS_X509_Cert *ca = NULL; ret = HITLS_AddCertToStoreTest("../testdata/cert/chain/rsa-v3/ca.der", store, &ca); ASSERT_EQ(ret, HITLS_PKI_SUCCESS); HITLS_X509_Cert *entity = NULL; ret = HITLS_AddCertToStoreTest("../testdata/cert/chain/rsa-v3/cert.der", store, &entity); ASSERT_TRUE(ret != HITLS_PKI_SUCCESS); ASSERT_EQ(BSL_LIST_COUNT(store->store), 2); int32_t depth = 2; ret = HITLS_X509_StoreCtxCtrl(store, HITLS_X509_STORECTX_SET_PARAM_DEPTH, &depth, sizeof(depth)); ASSERT_EQ(ret, HITLS_PKI_SUCCESS); HITLS_X509_List *chain = NULL; ret = HITLS_X509_CertChainBuild(store, false, entity, &chain); ASSERT_TRUE(ret == HITLS_PKI_SUCCESS); BSL_LIST_FREE(chain, (BSL_LIST_PFUNC_FREE)HITLS_X509_CertFree); chain = BSL_LIST_New(sizeof(HITLS_X509_Cert *)); ASSERT_TRUE(chain != NULL); ret = X509_AddCertToChainTest(chain, entity); ASSERT_EQ(ret, HITLS_PKI_SUCCESS); int64_t timeval = time(NULL); ret = HITLS_X509_StoreCtxCtrl(store, HITLS_X509_STORECTX_SET_TIME, &timeval, sizeof(timeval)); ASSERT_EQ(ret, HITLS_PKI_SUCCESS); ASSERT_EQ(ret, HITLS_PKI_SUCCESS); ret = HITLS_X509_CertVerify(store, chain); ASSERT_TRUE(ret != HITLS_PKI_SUCCESS); EXIT: HITLS_X509_StoreCtxFree(store); HITLS_X509_CertFree(root); HITLS_X509_CertFree(ca); HITLS_X509_CertFree(entity); BSL_LIST_FREE(chain, (BSL_LIST_PFUNC_FREE)HITLS_X509_CertFree); } /* END_CASE */ /* BEGIN_CASE */ void SDV_X509_BUILD_CERT_CHAIN_FUNC_TC008(char *rootPath, char *caPath, char *cert, char *rootcrlpath, char *cacrlpath, int flag, int except) { TestMemInit(); HITLS_X509_StoreCtx *store = HITLS_X509_StoreCtxNew(); ASSERT_TRUE(store != NULL); HITLS_X509_Cert *root = NULL; int32_t ret = HITLS_AddCertToStoreTest(rootPath, store, &root); ASSERT_EQ(ret, HITLS_PKI_SUCCESS); HITLS_X509_Cert *ca = NULL; ret = HITLS_AddCertToStoreTest(caPath, store, &ca); ASSERT_EQ(ret, HITLS_PKI_SUCCESS); HITLS_X509_Cert *entity = NULL; ret = HITLS_AddCertToStoreTest(cert, store, &entity); ASSERT_TRUE(ret != HITLS_PKI_SUCCESS); ASSERT_EQ(BSL_LIST_COUNT(store->store), 2); HITLS_X509_Crl *rootcrl = NULL; if (strlen(rootcrlpath) != 0) { ret = HITLS_AddCrlToStoreTest(rootcrlpath, store, &rootcrl); ASSERT_EQ(ret, HITLS_PKI_SUCCESS); } HITLS_X509_Crl *cacrl = NULL; ret = HITLS_AddCrlToStoreTest(cacrlpath, store, &cacrl); ASSERT_EQ(ret, HITLS_PKI_SUCCESS); if (strlen(rootcrlpath) == 0) { ASSERT_EQ(BSL_LIST_COUNT(store->crl), 1); } else { ASSERT_EQ(BSL_LIST_COUNT(store->crl), 2); } int32_t depth = 3; ret = HITLS_X509_StoreCtxCtrl(store, HITLS_X509_STORECTX_SET_PARAM_DEPTH, &depth, sizeof(depth)); ASSERT_EQ(ret, HITLS_PKI_SUCCESS); HITLS_X509_List *chain = NULL; ret = HITLS_X509_CertChainBuild(store, false, entity, &chain); ASSERT_EQ(ret, HITLS_PKI_SUCCESS); ASSERT_EQ(ret, HITLS_PKI_SUCCESS); int64_t setFlag = (int64_t)flag; ret = HITLS_X509_StoreCtxCtrl(store, HITLS_X509_STORECTX_SET_PARAM_FLAGS, &setFlag, sizeof(int64_t)); ASSERT_EQ(ret, HITLS_PKI_SUCCESS); int64_t timeval = time(NULL); ret = HITLS_X509_StoreCtxCtrl(store, HITLS_X509_STORECTX_SET_TIME, &timeval, sizeof(timeval)); ASSERT_EQ(ret, HITLS_PKI_SUCCESS); ret = HITLS_X509_CertVerify(store, chain); ASSERT_TRUE(ret == except); EXIT: HITLS_X509_StoreCtxFree(store); HITLS_X509_CertFree(root); HITLS_X509_CertFree(ca); HITLS_X509_CertFree(entity); HITLS_X509_CrlFree(rootcrl); HITLS_X509_CrlFree(cacrl); BSL_LIST_FREE(chain, (BSL_LIST_PFUNC_FREE)HITLS_X509_CertFree); } /* END_CASE */ /* BEGIN_CASE */ void SDV_X509_BUILD_CERT_CHAIN_FUNC_TC009(void) { HITLS_X509_StoreCtx *store = HITLS_X509_StoreCtxNew(); ASSERT_TRUE(store != NULL); HITLS_X509_List *chain = BSL_LIST_New(sizeof(HITLS_X509_Cert *)); int32_t ret = HITLS_X509_CertVerify(store, chain); ASSERT_TRUE(ret != HITLS_PKI_SUCCESS); HITLS_X509_Cert *root = NULL; ret = HITLS_X509_CertParseFile(BSL_FORMAT_ASN1, "../testdata/cert/chain/rsa-pss-v3/ca.der", &root); ASSERT_EQ(ret, HITLS_PKI_SUCCESS); ret = X509_AddCertToChainTest(chain, root); ASSERT_EQ(ret, HITLS_PKI_SUCCESS); ret = BSL_LIST_AddElementInt(chain, NULL, BSL_LIST_POS_BEGIN); ASSERT_EQ(ret, HITLS_PKI_SUCCESS); ret = HITLS_X509_CertVerify(store, chain); ASSERT_TRUE(ret != HITLS_PKI_SUCCESS); EXIT: HITLS_X509_StoreCtxFree(store); HITLS_X509_CertFree(root); BSL_LIST_FREE(chain, (BSL_LIST_PFUNC_FREE)HITLS_X509_CertFree); } /* END_CASE */ /* BEGIN_CASE */ void SDV_X509_BUILD_CERT_CHAIN_WITH_ROOT_FUNC_TC001(void) { HITLS_X509_StoreCtx *store = HITLS_X509_StoreCtxNew(); ASSERT_TRUE(store != NULL); HITLS_X509_Cert *entity = NULL; int32_t ret = HITLS_AddCertToStoreTest("../testdata/cert/chain/rsa-v3/cert.der", store, &entity); ASSERT_TRUE(ret != HITLS_PKI_SUCCESS); ASSERT_EQ(BSL_LIST_COUNT(store->store), 0); HITLS_X509_Cert *ca = NULL; ret = HITLS_AddCertToStoreTest("../testdata/cert/chain/rsa-v3/ca.der", store, &ca); ASSERT_EQ(ret, HITLS_PKI_SUCCESS); ASSERT_EQ(BSL_LIST_COUNT(store->store), 1); HITLS_X509_List *chain = NULL; ret = HITLS_X509_CertChainBuild(store, true, entity, &chain); ASSERT_EQ(ret, HITLS_X509_ERR_ISSUE_CERT_NOT_FOUND); HITLS_X509_Cert *root = NULL; ret = HITLS_AddCertToStoreTest("../testdata/cert/chain/rsa-v3/rootca.der", store, &root); ASSERT_EQ(ret, HITLS_PKI_SUCCESS); ASSERT_EQ(BSL_LIST_COUNT(store->store), 2); ret = HITLS_X509_CertChainBuild(store, true, entity, &chain); ASSERT_EQ(ret, HITLS_PKI_SUCCESS); ASSERT_EQ(BSL_LIST_COUNT(chain), 3); EXIT: HITLS_X509_StoreCtxFree(store); HITLS_X509_CertFree(root); HITLS_X509_CertFree(ca); HITLS_X509_CertFree(entity); BSL_LIST_FREE(chain, (BSL_LIST_PFUNC_FREE)HITLS_X509_CertFree); } /* END_CASE */ /* BEGIN_CASE */ void SDV_X509_SM2_CERT_USERID_FUNC_TC001(char *caCertPath, char *interCertPath, char *entityCertPath, int isUseDefaultUserId) { TestMemInit(); TestRandInit(); HITLS_X509_Cert *entityCert = NULL; HITLS_X509_Cert *interCert = NULL; HITLS_X509_Cert *caCert = NULL; HITLS_X509_List *chain = NULL; char sm2DefaultUserid[] = "1234567812345678"; HITLS_X509_StoreCtx *storeCtx = HITLS_X509_StoreCtxNew(); ASSERT_NE(storeCtx, NULL); ASSERT_EQ(HITLS_AddCertToStoreTest(caCertPath, storeCtx, &caCert), 0); ASSERT_EQ(HITLS_AddCertToStoreTest(interCertPath, storeCtx, &interCert), 0); ASSERT_EQ(HITLS_X509_CertParseFile(BSL_FORMAT_UNKNOWN, entityCertPath, &entityCert), 0); ASSERT_EQ(BSL_LIST_COUNT(storeCtx->store), 2); if (isUseDefaultUserId != 0) { ASSERT_EQ(HITLS_X509_StoreCtxCtrl(storeCtx, HITLS_X509_STORECTX_SET_VFY_SM2_USERID, sm2DefaultUserid, strlen(sm2DefaultUserid)), 0); } ASSERT_EQ(HITLS_X509_CertChainBuild(storeCtx, false, entityCert, &chain), 0); ASSERT_EQ(HITLS_X509_CertVerify(storeCtx, chain), HITLS_PKI_SUCCESS); EXIT: HITLS_X509_StoreCtxFree(storeCtx); HITLS_X509_CertFree(entityCert); HITLS_X509_CertFree(interCert); HITLS_X509_CertFree(caCert); BSL_LIST_FREE(chain, (BSL_LIST_PFUNC_FREE)HITLS_X509_CertFree); } /* END_CASE */ /* BEGIN_CASE */ void SDV_X509_STORE_LOAD_CA_PATH_FUNC_TC001(void) { TestMemInit(); HITLS_X509_StoreCtx *storeCtx = HITLS_X509_StoreCtxNew(); ASSERT_NE(storeCtx, NULL); // Test adding additional CA path const char *testPath1 = "/usr/local/ssl/certs"; int32_t ret = HITLS_X509_StoreCtxCtrl(storeCtx, HITLS_X509_STORECTX_ADD_CA_PATH, (void *)testPath1, strlen(testPath1)); ASSERT_EQ(ret, HITLS_PKI_SUCCESS); ret = HITLS_X509_StoreCtxCtrl(NULL, HITLS_X509_STORECTX_ADD_CA_PATH, (void *)testPath1, strlen(testPath1)); ASSERT_EQ(ret, HITLS_X509_ERR_INVALID_PARAM); ret = HITLS_X509_StoreCtxCtrl(storeCtx, HITLS_X509_STORECTX_ADD_CA_PATH, NULL, strlen(testPath1)); ASSERT_EQ(ret, HITLS_X509_ERR_INVALID_PARAM); ret = HITLS_X509_StoreCtxCtrl(storeCtx, HITLS_X509_STORECTX_ADD_CA_PATH, (void *)testPath1, 0); ASSERT_EQ(ret, HITLS_X509_ERR_INVALID_PARAM); ret = HITLS_X509_StoreCtxCtrl(storeCtx, HITLS_X509_STORECTX_ADD_CA_PATH, (void *)testPath1, 4097); ASSERT_EQ(ret, HITLS_X509_ERR_INVALID_PARAM); EXIT: HITLS_X509_StoreCtxFree(storeCtx); } /* END_CASE */ /* BEGIN_CASE */ void SDV_X509_STORE_LOAD_CA_PATH_CHAIN_BUILD_TC001(void) { TestMemInit(); HITLS_X509_StoreCtx *storeCtx = HITLS_X509_StoreCtxNew(); ASSERT_NE(storeCtx, NULL); // Add additional CA paths const char *caPath = "../testdata/tls/certificate/pem/rsa_sha256"; int32_t ret = HITLS_X509_StoreCtxCtrl(storeCtx, HITLS_X509_STORECTX_ADD_CA_PATH, (void *)caPath, strlen(caPath)); ASSERT_EQ(ret, HITLS_PKI_SUCCESS); // Load the certificate to be verified const char *certToVerify = "../testdata/tls/certificate/pem/rsa_sha256/client.pem"; HITLS_X509_Cert *cert = NULL; ret = HITLS_X509_CertParseFile(BSL_FORMAT_PEM, certToVerify, &cert); ASSERT_EQ(ret, HITLS_PKI_SUCCESS); // Build certificate chain with on-demand CA loading from multiple paths HITLS_X509_List *chain = NULL; ret = HITLS_X509_CertChainBuild(storeCtx, true, cert, &chain); ASSERT_EQ(ret, HITLS_PKI_SUCCESS); ASSERT_NE(chain, NULL); uint32_t chainLength = BSL_LIST_COUNT(chain); ASSERT_TRUE(chainLength >= 1); // Verify the certificate chain ret = HITLS_X509_CertVerify(storeCtx, chain); printf("Certificate verification result: %d\n", ret); ASSERT_EQ(ret, HITLS_PKI_SUCCESS); BSL_LIST_FREE(chain, (BSL_LIST_PFUNC_FREE)HITLS_X509_CertFree); HITLS_X509_CertFree(cert); EXIT: HITLS_X509_StoreCtxFree(storeCtx); } /* END_CASE */ /* BEGIN_CASE */ void SDV_X509_STORE_LOAD_CA_PATH_CHAIN_BUILD_TC002(void) { TestMemInit(); HITLS_X509_StoreCtx *storeCtx = HITLS_X509_StoreCtxNew(); ASSERT_NE(storeCtx, NULL); // Add additional CA paths const char *caPath = "../testdata/tls/certificate/pem/ed25519"; int32_t ret = HITLS_X509_StoreCtxCtrl(storeCtx, HITLS_X509_STORECTX_ADD_CA_PATH, (void *)caPath, strlen(caPath)); ASSERT_EQ(ret, HITLS_PKI_SUCCESS); // Load the certificate to be verified const char *certToVerify = "../testdata/tls/certificate/pem/rsa_sha256/client.pem"; HITLS_X509_Cert *cert = NULL; ret = HITLS_X509_CertParseFile(BSL_FORMAT_PEM, certToVerify, &cert); ASSERT_EQ(ret, HITLS_PKI_SUCCESS); // Build certificate chain with on-demand CA loading from multiple paths HITLS_X509_List *chain = NULL; ret = HITLS_X509_CertChainBuild(storeCtx, true, cert, &chain); ASSERT_EQ(ret, HITLS_X509_ERR_ISSUE_CERT_NOT_FOUND); ASSERT_EQ(chain, NULL); HITLS_X509_CertFree(cert); EXIT: HITLS_X509_StoreCtxFree(storeCtx); } /* END_CASE */ /* BEGIN_CASE */ void SDV_X509_STORE_LOAD_CA_PATH_CHAIN_BUILD_TC003(void) { TestMemInit(); HITLS_X509_StoreCtx *storeCtx = HITLS_X509_StoreCtxNew(); ASSERT_NE(storeCtx, NULL); // Add additional CA paths const char *caPath = "../testdata/tls/certificate/pem/test_dir"; int32_t ret = HITLS_X509_StoreCtxCtrl(storeCtx, HITLS_X509_STORECTX_ADD_CA_PATH, (void *)caPath, strlen(caPath)); ASSERT_EQ(ret, HITLS_PKI_SUCCESS); // Load the certificate to be verified const char *certToVerify = "../testdata/tls/certificate/pem/rsa_sha256/client.pem"; HITLS_X509_Cert *cert = NULL; ret = HITLS_X509_CertParseFile(BSL_FORMAT_PEM, certToVerify, &cert); ASSERT_EQ(ret, HITLS_PKI_SUCCESS); // Build certificate chain with on-demand CA loading from multiple paths HITLS_X509_List *chain = NULL; ret = HITLS_X509_CertChainBuild(storeCtx, true, cert, &chain); ASSERT_EQ(ret, HITLS_PKI_SUCCESS); ASSERT_NE(chain, NULL); HITLS_X509_CertFree(cert); BSL_LIST_FREE(chain, (BSL_LIST_PFUNC_FREE)HITLS_X509_CertFree); EXIT: HITLS_X509_StoreCtxFree(storeCtx); } /* END_CASE */ /* BEGIN_CASE */ void SDV_X509_STORE_LOAD_CA_PATH_CHAIN_BUILD_TC004(void) { TestMemInit(); HITLS_X509_StoreCtx *storeCtx = HITLS_X509_StoreCtxNew(); ASSERT_NE(storeCtx, NULL); // Add additional CA paths const char *caPath = "../testdata/tls/certificate/pem/test_dir"; int32_t ret = HITLS_X509_StoreCtxCtrl(storeCtx, HITLS_X509_STORECTX_ADD_CA_PATH, (void *)caPath, strlen(caPath)); ASSERT_EQ(ret, HITLS_PKI_SUCCESS); // Load the certificate to be verified const char *certToVerify = "../testdata/tls/certificate/pem/ecdsa_sha256/client.pem"; HITLS_X509_Cert *cert = NULL; ret = HITLS_X509_CertParseFile(BSL_FORMAT_PEM, certToVerify, &cert); ASSERT_EQ(ret, HITLS_PKI_SUCCESS); // Build certificate chain with on-demand CA loading from multiple paths HITLS_X509_List *chain = NULL; ret = HITLS_X509_CertChainBuild(storeCtx, true, cert, &chain); ASSERT_EQ(ret, HITLS_PKI_SUCCESS); ASSERT_NE(chain, NULL); HITLS_X509_CertFree(cert); BSL_LIST_FREE(chain, (BSL_LIST_PFUNC_FREE)HITLS_X509_CertFree); EXIT: HITLS_X509_StoreCtxFree(storeCtx); } /* END_CASE */
2301_79861745/bench_create
testcode/sdv/testcase/pki/verify/test_suite_sdv_x509_vfy.c
C
unknown
30,479
/* * This file is part of the openHiTLS project. * * openHiTLS is licensed under the Mulan PSL v2. * You can use this software according to the terms and conditions of the Mulan PSL v2. * You may obtain a copy of Mulan PSL v2 at: * * http://license.coscl.org.cn/MulanPSL2 * * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. * See the Mulan PSL v2 for more details. */ /* BEGIN_HEADER */ #include <unistd.h> #include <semaphore.h> #include "hitls_build.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 "hitls.h" #include "frame_tls.h" #include "hitls_type.h" #include "test.h" /* END_HEADER */ #define READ_BUF_LEN_18K (18 * 1024) #define PORT 10088 bool SkipTlsTest(int connType, int version) { switch (version) { #ifdef HITLS_TLS_PROTO_TLS13 case TLS1_3: break; #endif #ifdef HITLS_TLS_PROTO_TLS12 case TLS1_2: break; #endif #ifdef HITLS_TLS_PROTO_DTLS12 case DTLS1_2: break; #endif #ifdef HITLS_TLS_PROTO_TLCP11 case TLCP1_1: break; #endif #ifdef HITLS_TLS_PROTO_DTLCP11 case DTLCP1_1: break; #endif #ifdef HITLS_TLS_PROTO_ALL case TLS_ALL: break; #endif default: return true; } switch (connType) { #ifdef HITLS_BSL_UIO_TCP case TCP: break; #endif #ifdef HITLS_BSL_UIO_UDP case UDP: break; #endif default: return true; } return false; } /* BEGIN_CASE */ void SDV_TLS_BASE_CONNECT_TC01(int connType, int version) { if (SkipTlsTest(connType, version)) { SKIP_TEST(); return; } 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, connType, PORT, true); ASSERT_TRUE(remoteProcess != NULL); if (version == TLCP1_1 || version == DTLCP1_1) { serverCtxConfig = HLT_NewCtxConfigTLCP(NULL, "SERVER", false); clientCtxConfig = HLT_NewCtxConfigTLCP(NULL, "CLIENT", true); } else { serverCtxConfig = HLT_NewCtxConfig(NULL, "SERVER"); clientCtxConfig = HLT_NewCtxConfig(NULL, "CLIENT"); } ASSERT_TRUE(serverCtxConfig != NULL); ASSERT_TRUE(clientCtxConfig != NULL); // Configure link information on the server. serverRes = HLT_ProcessTlsAccept(localProcess, version, serverCtxConfig, NULL); ASSERT_TRUE(serverRes != NULL); // Configure link information on the client. clientRes = HLT_ProcessTlsConnect(remoteProcess, version, 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(); } /* END_CASE */
2301_79861745/bench_create
testcode/sdv/testcase/tls/ciphersuite/test_suite_sdv_hlt_base_connect.c
C
unknown
3,611
/* * This file is part of the openHiTLS project. * * openHiTLS is licensed under the Mulan PSL v2. * You can use this software according to the terms and conditions of the Mulan PSL v2. * You may obtain a copy of Mulan PSL v2 at: * * http://license.coscl.org.cn/MulanPSL2 * * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. * See the Mulan PSL v2 for more details. */ /* 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 10086 int32_t g_testSecurityLevel = 0; void SetCert(HLT_Ctx_Config *ctxConfig, char *cert) { if (strncmp(cert, "RSA", strlen("RSA")) == 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(cert, "ECDSA", strlen("ECDSA")) == 0) { HLT_SetCertPath(ctxConfig, ECDSA_SHA_CA_PATH, ECDSA_SHA_CHAIN_PATH, ECDSA_SHA256_EE_PATH, ECDSA_SHA256_PRIV_PATH, "NULL", "NULL"); } } void SetGMCert(HLT_Ctx_Config *serverCtxConfig, HLT_Ctx_Config *clientCtxConfig, char *cert) { if (strncmp(cert, "SM2", strlen("SM2")) == 0) { HLT_SetCertPath(serverCtxConfig, SM2_VERIFY_PATH, SM2_CHAIN_PATH, SM2_SERVER_ENC_CERT_PATH, SM2_SERVER_ENC_KEY_PATH, SM2_SERVER_SIGN_CERT_PATH, SM2_SERVER_SIGN_KEY_PATH); HLT_SetCertPath(clientCtxConfig, SM2_VERIFY_PATH, SM2_CHAIN_PATH, SM2_CLIENT_ENC_CERT_PATH, SM2_CLIENT_ENC_KEY_PATH, SM2_CLIENT_SIGN_CERT_PATH, SM2_CLIENT_SIGN_KEY_PATH); } } char *HITLS_TLS13_Ciphersuite[] = { "HITLS_AES_128_GCM_SHA256", "HITLS_AES_256_GCM_SHA384", "HITLS_CHACHA20_POLY1305_SHA256", "HITLS_AES_128_CCM_SHA256", "HITLS_AES_128_CCM_8_SHA256", }; // RSA Authentication char *HITLS_RSA_Ciphersuite[] = { "HITLS_RSA_WITH_AES_128_CBC_SHA", "HITLS_RSA_WITH_AES_256_CBC_SHA", "HITLS_RSA_WITH_AES_128_CBC_SHA256", "HITLS_RSA_WITH_AES_256_CBC_SHA256", "HITLS_RSA_WITH_AES_128_GCM_SHA256", "HITLS_RSA_WITH_AES_256_GCM_SHA384", "HITLS_ECDHE_RSA_WITH_AES_128_CBC_SHA", "HITLS_ECDHE_RSA_WITH_AES_256_CBC_SHA", "HITLS_ECDHE_RSA_WITH_AES_128_CBC_SHA256", "HITLS_ECDHE_RSA_WITH_AES_256_CBC_SHA384", "HITLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256", "HITLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384", "HITLS_ECDHE_RSA_WITH_CHACHA20_POLY1305_SHA256", "HITLS_DHE_RSA_WITH_CHACHA20_POLY1305_SHA256", "HITLS_DHE_RSA_WITH_AES_128_CBC_SHA", "HITLS_DHE_RSA_WITH_AES_256_CBC_SHA", "HITLS_DHE_RSA_WITH_AES_128_CBC_SHA256", "HITLS_DHE_RSA_WITH_AES_256_CBC_SHA256", "HITLS_DHE_RSA_WITH_AES_128_GCM_SHA256", "HITLS_DHE_RSA_WITH_AES_256_GCM_SHA384", "HITLS_DHE_RSA_WITH_AES_128_CCM", "HITLS_DHE_RSA_WITH_AES_256_CCM", "HITLS_RSA_WITH_AES_256_CCM", "HITLS_RSA_WITH_AES_256_CCM_8", "HITLS_RSA_WITH_AES_128_CCM", "HITLS_RSA_WITH_AES_128_CCM_8", }; // ECDSA Authentication char *HITLS_ECDSA_Ciphersuite[] = { "HITLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA", "HITLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA", "HITLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA256", "HITLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA384", "HITLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256", "HITLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384", "HITLS_ECDHE_ECDSA_WITH_CHACHA20_POLY1305_SHA256", "HITLS_ECDHE_ECDSA_WITH_AES_128_CCM", "HITLS_ECDHE_ECDSA_WITH_AES_256_CCM", }; char *HITLS_ANON_Ciphersuite[] = { "HITLS_DH_ANON_WITH_AES_128_CBC_SHA", "HITLS_DH_ANON_WITH_AES_256_CBC_SHA", "HITLS_DH_ANON_WITH_AES_128_CBC_SHA256", "HITLS_DH_ANON_WITH_AES_256_CBC_SHA256", "HITLS_DH_ANON_WITH_AES_128_GCM_SHA256", "HITLS_DH_ANON_WITH_AES_256_GCM_SHA384", "HITLS_ECDH_ANON_WITH_AES_128_CBC_SHA", "HITLS_ECDH_ANON_WITH_AES_256_CBC_SHA", }; // PSK Authentication char *HITLS_PSK_Ciphersuite[] = { "HITLS_PSK_WITH_AES_128_CBC_SHA", "HITLS_PSK_WITH_AES_256_CBC_SHA", "HITLS_PSK_WITH_AES_128_GCM_SHA256", "HITLS_PSK_WITH_AES_256_GCM_SHA384", "HITLS_PSK_WITH_AES_128_CBC_SHA256", "HITLS_PSK_WITH_AES_256_CBC_SHA384", "HITLS_ECDHE_PSK_WITH_AES_128_CBC_SHA", "HITLS_ECDHE_PSK_WITH_AES_256_CBC_SHA", "HITLS_ECDHE_PSK_WITH_AES_128_CBC_SHA256", "HITLS_ECDHE_PSK_WITH_AES_256_CBC_SHA384", "HITLS_PSK_WITH_CHACHA20_POLY1305_SHA256", "HITLS_ECDHE_PSK_WITH_CHACHA20_POLY1305_SHA256", "HITLS_RSA_PSK_WITH_AES_128_CBC_SHA", "HITLS_RSA_PSK_WITH_AES_256_CBC_SHA", "HITLS_RSA_PSK_WITH_AES_128_GCM_SHA256", "HITLS_RSA_PSK_WITH_AES_256_GCM_SHA384", "HITLS_RSA_PSK_WITH_AES_128_CBC_SHA256", "HITLS_RSA_PSK_WITH_AES_256_CBC_SHA384", "HITLS_RSA_PSK_WITH_CHACHA20_POLY1305_SHA256", "HITLS_DHE_PSK_WITH_AES_128_CBC_SHA", "HITLS_DHE_PSK_WITH_AES_256_CBC_SHA", "HITLS_DHE_PSK_WITH_AES_128_GCM_SHA256", "HITLS_DHE_PSK_WITH_AES_256_GCM_SHA384", "HITLS_DHE_PSK_WITH_AES_128_CBC_SHA256", "HITLS_DHE_PSK_WITH_AES_256_CBC_SHA384", "HITLS_DHE_PSK_WITH_CHACHA20_POLY1305_SHA256", "HITLS_DHE_PSK_WITH_AES_128_CCM", "HITLS_DHE_PSK_WITH_AES_256_CCM", "HITLS_PSK_WITH_AES_256_CCM", "HITLS_ECDHE_PSK_WITH_AES_128_GCM_SHA256", "HITLS_ECDHE_PSK_WITH_AES_256_GCM_SHA384", "HITLS_ECDHE_PSK_WITH_AES_128_CCM_SHA256", }; char *HITLS_GM_Ciphersuite[] = { "HITLS_ECDHE_SM4_CBC_SM3", "HITLS_ECC_SM4_CBC_SM3", "HITLS_ECDHE_SM4_GCM_SM3", "HITLS_ECC_SM4_GCM_SM3", }; static void CONNECT(int version, int connType, char *Ciphersuite, int hasPsk, char *cert) { HLT_Process *localProcess = HLT_InitLocalProcess(HITLS); HLT_Process *remoteProcess = HLT_LinkRemoteProcess(HITLS, connType, PORT, true); ASSERT_TRUE(localProcess != NULL); ASSERT_TRUE(remoteProcess != NULL); HLT_Ctx_Config *serverCtxConfig = NULL; HLT_Ctx_Config *clientCtxConfig = NULL; if (version == TLCP1_1 || version == DTLCP1_1) { serverCtxConfig = HLT_NewCtxConfigTLCP(NULL, "SERVER", false); clientCtxConfig = HLT_NewCtxConfigTLCP(NULL, "CLIENT", true); } else { serverCtxConfig = HLT_NewCtxConfig(NULL, "SERVER"); clientCtxConfig = HLT_NewCtxConfig(NULL, "CLIENT"); } ASSERT_TRUE(serverCtxConfig != NULL); ASSERT_TRUE(clientCtxConfig != NULL); uint8_t psk[] = "12121212121212"; if (hasPsk) { memcpy_s(serverCtxConfig->psk, PSK_MAX_LEN, psk, sizeof(psk)); memcpy_s(clientCtxConfig->psk, PSK_MAX_LEN, psk, sizeof(psk)); } serverCtxConfig->securitylevel = g_testSecurityLevel; clientCtxConfig->securitylevel = g_testSecurityLevel; if (version == TLCP1_1 || version == DTLCP1_1) { SetGMCert(serverCtxConfig, clientCtxConfig, cert); } else { SetCert(serverCtxConfig, cert); SetCert(clientCtxConfig, cert); } HLT_SetCipherSuites(serverCtxConfig, Ciphersuite); HLT_SetCipherSuites(clientCtxConfig, Ciphersuite); HLT_Tls_Res *serverRes = HLT_ProcessTlsAccept(localProcess, version, serverCtxConfig, NULL); ASSERT_TRUE(serverRes != NULL); HLT_Tls_Res *clientRes = HLT_ProcessTlsConnect(remoteProcess, version, 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(); } /* BEGIN_CASE */ void SDV_TLS_TLS13_CIPHER_SUITE(void) { for (uint16_t i = 0; i < sizeof(HITLS_TLS13_Ciphersuite) / sizeof(HITLS_TLS13_Ciphersuite[0]); i++) { CONNECT(TLS1_3, TCP, HITLS_TLS13_Ciphersuite[i], 0, "RSA"); } } /* END_CASE */ /* BEGIN_CASE */ void SDV_TLS_RSA_CIPHER_SUITE(void) { for (uint16_t i = 0; i < sizeof(HITLS_RSA_Ciphersuite) / sizeof(HITLS_RSA_Ciphersuite[0]); i++) { SUB_PROC_BEGIN(continue); CONNECT(TLS1_2, TCP, HITLS_RSA_Ciphersuite[i], 0, "RSA"); if (IsEnableSctpAuth()) { CONNECT(DTLS1_2, SCTP, HITLS_RSA_Ciphersuite[i], 0, "RSA"); } CONNECT(DTLS1_2, UDP, HITLS_RSA_Ciphersuite[i], 0, "RSA"); SUB_PROC_END(); } SUB_PROC_WAIT(sizeof(HITLS_RSA_Ciphersuite) / sizeof(HITLS_RSA_Ciphersuite[0])); } /* END_CASE */ /* BEGIN_CASE */ void SDV_TLS_ECDSA_CIPHER_SUITE(void) { for (uint16_t i = 0; i < sizeof(HITLS_ECDSA_Ciphersuite) / sizeof(HITLS_ECDSA_Ciphersuite[0]); i++) { SUB_PROC_BEGIN(continue); CONNECT(TLS1_2, TCP, HITLS_ECDSA_Ciphersuite[i], 0, "ECDSA"); if (IsEnableSctpAuth()) { CONNECT(DTLS1_2, SCTP, HITLS_ECDSA_Ciphersuite[i], 0, "ECDSA"); } CONNECT(DTLS1_2, UDP, HITLS_ECDSA_Ciphersuite[i], 0, "ECDSA"); SUB_PROC_END(); } SUB_PROC_WAIT(sizeof(HITLS_ECDSA_Ciphersuite) / sizeof(HITLS_ECDSA_Ciphersuite[0])); } /* END_CASE */ /* BEGIN_CASE */ void SDV_TLS_PSK_CIPHER_SUITE(void) { for (uint16_t i = 0; i < sizeof(HITLS_PSK_Ciphersuite) / sizeof(HITLS_PSK_Ciphersuite[0]); i++) { SUB_PROC_BEGIN(continue); CONNECT(TLS1_2, TCP, HITLS_PSK_Ciphersuite[i], 1, "RSA"); if (IsEnableSctpAuth()) { CONNECT(DTLS1_2, SCTP, HITLS_PSK_Ciphersuite[i], 1, "RSA"); } CONNECT(DTLS1_2, UDP, HITLS_PSK_Ciphersuite[i], 1, "RSA"); SUB_PROC_END(); } SUB_PROC_WAIT(sizeof(HITLS_PSK_Ciphersuite) / sizeof(HITLS_PSK_Ciphersuite[0])); } /* END_CASE */ /* BEGIN_CASE */ void SDV_TLS_ANON_CIPHER_SUITE(void) { for (uint16_t i = 0; i < sizeof(HITLS_ANON_Ciphersuite) / sizeof(HITLS_ANON_Ciphersuite[0]); i++) { SUB_PROC_BEGIN(continue); CONNECT(TLS1_2, TCP, HITLS_ANON_Ciphersuite[i], 0, "RSA"); if (IsEnableSctpAuth()) { CONNECT(DTLS1_2, SCTP, HITLS_ANON_Ciphersuite[i], 0, "RSA"); } CONNECT(DTLS1_2, UDP, HITLS_ANON_Ciphersuite[i], 0, "RSA"); SUB_PROC_END(); } SUB_PROC_WAIT(sizeof(HITLS_ANON_Ciphersuite) / sizeof(HITLS_ANON_Ciphersuite[0])); } /* END_CASE */ /* BEGIN_CASE */ void SDV_TLS_GM_CIPHER_SUITE(void) { for (uint16_t i = 0; i < sizeof(HITLS_GM_Ciphersuite) / sizeof(HITLS_GM_Ciphersuite[0]); i++) { SUB_PROC_BEGIN(continue); CONNECT(TLCP1_1, TCP, HITLS_GM_Ciphersuite[i], 0, "SM2"); if (IsEnableSctpAuth()) { CONNECT(DTLCP1_1, SCTP, HITLS_GM_Ciphersuite[i], 0, "SM2"); } SUB_PROC_END(); } SUB_PROC_WAIT(sizeof(HITLS_GM_Ciphersuite) / sizeof(HITLS_GM_Ciphersuite[0])); } /* END_CASE */
2301_79861745/bench_create
testcode/sdv/testcase/tls/ciphersuite/test_suite_sdv_hlt_ciphersuite.c
C
unknown
11,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. */ /* 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 10086 int32_t g_testSecurityLevel = 0; void SetCert(HLT_Ctx_Config *ctxConfig, char *cert) { if (strncmp(cert, "ECDSA-384", strlen("ECDSA-384")) == 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(cert, "ECDSA-512", strlen("ECDSA-512")) == 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(cert, "ECDSA", strlen("ECDSA")) == 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(cert, "RSAE", strlen("RSAE")) == 0) { HLT_SetCertPath(ctxConfig, RSAPSS_RSAE_CA_PATH, RSAPSS_RSAE_CHAIN_PATH, RSAPSS_RSAE_EE_PATH, RSAPSS_RSAE_PRIV_PATH, "NULL", "NULL"); } else if (strncmp(cert, "RSAPSS", strlen("RSAPSS")) == 0) { HLT_SetCertPath(ctxConfig, RSAPSS_SHA256_CA_PATH, RSAPSS_SHA256_CHAIN_PATH, RSAPSS_SHA256_EE_PATH, RSAPSS_SHA256_PRIV_PATH, "NULL", "NULL"); } else if (strncmp(cert, "RSA", strlen("RSA")) == 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(cert, "ED25519", strlen("ED25519")) == 0) { HLT_SetCertPath(ctxConfig, ED25519_SHA512_CA_PATH, ED25519_SHA512_CHAIN_PATH, ED25519_SHA512_EE_PATH, ED25519_SHA512_PRIV_PATH, "NULL", "NULL"); } } void SetGMCert(HLT_Ctx_Config *serverCtxConfig, HLT_Ctx_Config *clientCtxConfig, char *cert) { if (strncmp(cert, "SM2", strlen("SM2")) == 0) { HLT_SetCertPath(serverCtxConfig, SM2_VERIFY_PATH, SM2_CHAIN_PATH, SM2_SERVER_ENC_CERT_PATH, SM2_SERVER_ENC_KEY_PATH, SM2_SERVER_SIGN_CERT_PATH, SM2_SERVER_SIGN_KEY_PATH); HLT_SetCertPath(clientCtxConfig, SM2_VERIFY_PATH, SM2_CHAIN_PATH, SM2_CLIENT_ENC_CERT_PATH, SM2_CLIENT_ENC_KEY_PATH, SM2_CLIENT_SIGN_CERT_PATH, SM2_CLIENT_SIGN_KEY_PATH); } } char *HITLS_Groups[] = { "HITLS_EC_GROUP_BRAINPOOLP256R1", "HITLS_EC_GROUP_BRAINPOOLP384R1", "HITLS_EC_GROUP_BRAINPOOLP512R1", "HITLS_EC_GROUP_SECP256R1", "HITLS_EC_GROUP_SECP384R1", "HITLS_EC_GROUP_SECP521R1", "HITLS_EC_GROUP_CURVE25519", "HITLS_FF_DHE_2048", "HITLS_FF_DHE_3072", "HITLS_FF_DHE_4096", "HITLS_FF_DHE_6144", "HITLS_FF_DHE_8192", }; char *HITLS_Signatures[] = { "CERT_SIG_SCHEME_RSA_PKCS1_SHA1", "CERT_SIG_SCHEME_RSA_PKCS1_SHA224", "CERT_SIG_SCHEME_RSA_PKCS1_SHA256", "CERT_SIG_SCHEME_RSA_PKCS1_SHA384", "CERT_SIG_SCHEME_RSA_PKCS1_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_PSS_PSS_SHA256", "CERT_SIG_SCHEME_RSA_PSS_PSS_SHA384", "CERT_SIG_SCHEME_RSA_PSS_PSS_SHA512", "CERT_SIG_SCHEME_ECDSA_SHA1", "CERT_SIG_SCHEME_ECDSA_SHA224", "CERT_SIG_SCHEME_ECDSA_SECP256R1_SHA256", "CERT_SIG_SCHEME_ECDSA_SECP384R1_SHA384", "CERT_SIG_SCHEME_ECDSA_SECP521R1_SHA512", }; static void CONNECT(int version, int connType, char *Ciphersuite, char *groups, char *signature, int hasPsk, char *cert) { HLT_Process *localProcess = HLT_InitLocalProcess(HITLS); HLT_Process *remoteProcess = HLT_LinkRemoteProcess(HITLS, connType, PORT, true); ASSERT_TRUE(localProcess != NULL); ASSERT_TRUE(remoteProcess != NULL); HLT_Ctx_Config *serverCtxConfig = NULL; HLT_Ctx_Config *clientCtxConfig = NULL; if (version == TLCP1_1 || version == DTLCP1_1) { serverCtxConfig = HLT_NewCtxConfigTLCP(NULL, "SERVER", false); clientCtxConfig = HLT_NewCtxConfigTLCP(NULL, "CLIENT", true); } else { serverCtxConfig = HLT_NewCtxConfig(NULL, "SERVER"); clientCtxConfig = HLT_NewCtxConfig(NULL, "CLIENT"); } ASSERT_TRUE(serverCtxConfig != NULL); ASSERT_TRUE(clientCtxConfig != NULL); uint8_t psk[] = "12121212121212"; if (hasPsk) { memcpy_s(serverCtxConfig->psk, PSK_MAX_LEN, psk, sizeof(psk)); memcpy_s(clientCtxConfig->psk, PSK_MAX_LEN, psk, sizeof(psk)); } serverCtxConfig->securitylevel = g_testSecurityLevel; clientCtxConfig->securitylevel = g_testSecurityLevel; if (version == TLCP1_1 || version == DTLCP1_1) { SetGMCert(serverCtxConfig, clientCtxConfig, cert); } else { SetCert(serverCtxConfig, cert); SetCert(clientCtxConfig, cert); } HLT_SetCipherSuites(serverCtxConfig, Ciphersuite); HLT_SetCipherSuites(clientCtxConfig, Ciphersuite); HLT_SetGroups(clientCtxConfig, groups); HLT_SetGroups(serverCtxConfig, groups); HLT_SetSignature(clientCtxConfig, signature); HLT_SetSignature(serverCtxConfig, signature); HLT_Tls_Res *serverRes = HLT_ProcessTlsAccept(localProcess, version, serverCtxConfig, NULL); ASSERT_TRUE(serverRes != NULL); HLT_Tls_Res *clientRes = HLT_ProcessTlsConnect(remoteProcess, version, 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(); } static void CONNECT_V12(char *Ciphersuite, char *groups, char *signature, int hasPsk, char *cert) { CONNECT(TLS1_2, TCP, Ciphersuite, groups, signature, hasPsk, cert); if (IsEnableSctpAuth()) { CONNECT(DTLS1_2, SCTP, Ciphersuite, groups, signature, hasPsk, cert); } CONNECT(DTLS1_2, UDP, Ciphersuite, groups, signature, hasPsk, cert); } /* BEGIN_CASE */ void SDV_TLS_13_GROUP(void) { for (uint16_t i = 3; i < sizeof(HITLS_Groups) / sizeof(HITLS_Groups[0]); i++) { CONNECT(TLS1_3, TCP, "HITLS_AES_256_GCM_SHA384", HITLS_Groups[i], NULL, 0, "RSA"); } } /* END_CASE */ /* BEGIN_CASE */ void SDV_TLS_12_GROUP(char *groups) { CONNECT_V12("HITLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256", groups, "CERT_SIG_SCHEME_RSA_PKCS1_SHA256", 0, "RSA"); } /* END_CASE */ /* tls12 dtls12 "CERT_SIG_SCHEME_ECDSA_SHA1", "CERT_SIG_SCHEME_ECDSA_SHA224", "CERT_SIG_SCHEME_ECDSA_SECP256R1_SHA256", "CERT_SIG_SCHEME_ECDSA_SECP384R1_SHA384", "CERT_SIG_SCHEME_ECDSA_SECP521R1_SHA512", */ /* BEGIN_CASE */ void SDV_TLS_ECDSA_SIGNATURE(char *signature) { CONNECT_V12("HITLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA256", "HITLS_EC_GROUP_SECP256R1", signature, 0, "ECDSA"); } /* END_CASE */ /* tls12 dtls12 "CERT_SIG_SCHEME_RSA_PKCS1_SHA1", "CERT_SIG_SCHEME_RSA_PKCS1_SHA224", "CERT_SIG_SCHEME_RSA_PKCS1_SHA256", "CERT_SIG_SCHEME_RSA_PKCS1_SHA384", "CERT_SIG_SCHEME_RSA_PKCS1_SHA512", "CERT_SIG_SCHEME_RSA_PSS_RSAE_SHA256", "CERT_SIG_SCHEME_RSA_PSS_RSAE_SHA384", "CERT_SIG_SCHEME_RSA_PSS_RSAE_SHA512", */ /* BEGIN_CASE */ void SDV_TLS_RSA_SIGNATURE(char *signature) { CONNECT_V12("HITLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256", "HITLS_EC_GROUP_SECP256R1", signature, 0, "RSAE"); } /* END_CASE */ /* tls12 dtls12 tls13 "CERT_SIG_SCHEME_RSA_PSS_PSS_SHA256", "CERT_SIG_SCHEME_RSA_PSS_PSS_SHA384", "CERT_SIG_SCHEME_RSA_PSS_PSS_SHA512", */ /* BEGIN_CASE */ void SDV_TLS_RSAPSS_SIGNATURE(char *signature) { CONNECT(TLS1_3, TCP, "HITLS_AES_256_GCM_SHA384", "HITLS_EC_GROUP_SECP256R1", signature, 0, "RSAPSS"); CONNECT_V12("HITLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256", "HITLS_EC_GROUP_SECP256R1", signature, 0, "RSAPSS"); } /* END_CASE */ /* tls13 "CERT_SIG_SCHEME_RSA_PSS_RSAE_SHA256", "CERT_SIG_SCHEME_RSA_PSS_RSAE_SHA384", "CERT_SIG_SCHEME_RSA_PSS_RSAE_SHA512", */ /* BEGIN_CASE */ void SDV_TLS13_RSA_SIGNATURE(char *signature) { CONNECT(TLS1_3, TCP, "HITLS_AES_256_GCM_SHA384", "HITLS_EC_GROUP_SECP256R1", signature, 0, "RSA"); } /* END_CASE */ /* tls13 "CERT_SIG_SCHEME_ECDSA_SECP256R1_SHA256", "CERT_SIG_SCHEME_ECDSA_SECP384R1_SHA384", "CERT_SIG_SCHEME_ECDSA_SECP521R1_SHA512", */ /* BEGIN_CASE */ void SDV_TLS13_ECDSA_SIGNATURE(char *signature, char *cert) { CONNECT(TLS1_3, TCP, "HITLS_AES_256_GCM_SHA384", "HITLS_EC_GROUP_SECP256R1", signature, 0, cert); } /* END_CASE */ /* tls13 "CERT_SIG_SCHEME_ED25519" */ /* BEGIN_CASE */ void SDV_TLS13_EDDSA_SIGNATURE(char *signature) { CONNECT(TLS1_3, TCP, "HITLS_AES_256_GCM_SHA384", "HITLS_EC_GROUP_CURVE25519", signature, 0, "ED25519"); } /* END_CASE */
2301_79861745/bench_create
testcode/sdv/testcase/tls/ciphersuite/test_suite_sdv_hlt_group_signature.c
C
unknown
9,720
/* * This file is part of the openHiTLS project. * * openHiTLS is licensed under the Mulan PSL v2. * You can use this software according to the terms and conditions of the Mulan PSL v2. * You may obtain a copy of Mulan PSL v2 at: * * http://license.coscl.org.cn/MulanPSL2 * * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, * EITHER EXPRESS 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 "crypt_util_rand.h" #include "hitls.h" #include "frame_tls.h" #include "hitls_type.h" /* END_HEADER */ #define READ_BUF_LEN_18K (18 * 1024) #define PORT 10088 /* BEGIN_CASE */ void SDV_TLS_TLCP_CIPHER_SUITE_TC01(char *cipherSuiteType) { 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); // Configure link information on the server. HLT_Ctx_Config *serverCtxConfig = HLT_NewCtxConfigTLCP(NULL, "SERVER", false); ASSERT_TRUE(serverCtxConfig != NULL); HLT_SetCipherSuites(serverCtxConfig, cipherSuiteType); serverCtxConfig->isSupportClientVerify = true; serverCtxConfig->needCheckKeyUsage = true; // The server listens on the TLS link. serverRes = HLT_ProcessTlsAccept(remoteProcess, TLCP1_1, serverCtxConfig, NULL); ASSERT_TRUE(serverRes != NULL); // Configure link information on the client. HLT_Ctx_Config *clientCtxConfig = HLT_NewCtxConfigTLCP(NULL, "CLIENT", true); ASSERT_TRUE(clientCtxConfig != NULL); HLT_SetCipherSuites(clientCtxConfig, cipherSuiteType); // Set up a TLCP link on the client. clientRes = HLT_ProcessTlsConnect(localProcess, TLCP1_1, 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(); } /* END_CASE */
2301_79861745/bench_create
testcode/sdv/testcase/tls/ciphersuite/test_suite_sdv_hlt_tlcp_ciphersuite.c
C
unknown
2,713
/* * This file is part of the openHiTLS project. * * openHiTLS is licensed under the Mulan PSL v2. * You can use this software according to the terms and conditions of the Mulan PSL v2. * You may obtain a copy of Mulan PSL v2 at: * * http://license.coscl.org.cn/MulanPSL2 * * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, * EITHER EXPRESS 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 <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 "recv_process.h" #include "stub_replace.h" #include "stub_crypt.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 "rec_wrapper.h" #include "process.h" #include "pthread.h" #include "unistd.h" #include "rec_header.h" #include "bsl_log.h" #include "cert_callback.h" #define BUF_SIZE_DTO_TEST 18432 int32_t g_uiPort = 18887; #define PARSEMSGHEADER_LEN 13 #define ILLEGAL_VALUE 0xFF #define HASH_EXDATA_LEN_ERROR 23 #define SIGNATURE_ALGORITHMS 0x04, 0x03 #define READ_BUF_SIZE (18 * 1024) #define TEMP_DATA_LEN 1024 #define REC_DTLS_RECORD_HEADER_LEN 13 #define BUF_TOOLONG_LEN ((1 << 14) + 1) typedef struct { HITLS_Config *config; FRAME_LinkObj *client; FRAME_LinkObj *server; HITLS_HandshakeState state; bool isClient; bool isSupportExtendMasterSecret; bool isSupportClientVerify; bool isSupportNoClientCert; bool isSupportRenegotiation; } HandshakeTestInfo; int32_t StatusPark(HandshakeTestInfo *testInfo, int uioType) { testInfo->client = FRAME_CreateTLCPLink(testInfo->config, uioType, true); if (testInfo->client == NULL) { return HITLS_INTERNAL_EXCEPTION; } testInfo->server = FRAME_CreateTLCPLink(testInfo->config, uioType, false); if (testInfo->server == NULL) { return HITLS_INTERNAL_EXCEPTION; } 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, int uioType) { FRAME_Init(); testInfo->config = HITLS_CFG_NewDTLCPConfig(); 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, uioType); } int32_t DefaultCfgStatusParkWithSuite(HandshakeTestInfo *testInfo) { FRAME_Init(); testInfo->config = HITLS_CFG_NewDTLCPConfig(); if (testInfo->config == NULL) { return HITLS_INTERNAL_EXCEPTION; } HITLS_CFG_SetCheckKeyUsage(testInfo->config, false); uint16_t cipherSuits[] = {HITLS_ECDHE_SM4_CBC_SM3,HITLS_ECC_SM4_CBC_SM3}; 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, BSL_UIO_UDP); } int32_t SendHelloReqWithIndex(HITLS_Ctx *ctx, uint8_t index) { int32_t ret; uint8_t buf[DTLS_HS_MSG_HEADER_SIZE] = {0u}; buf[5] = index; size_t len = DTLS_HS_MSG_HEADER_SIZE; ret = REC_Write(ctx, REC_TYPE_HANDSHAKE, buf, len); return ret; } 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; } uint32_t parseLen = 0; if (ParserTotalRecord(link, &frameMsg, buffer, len, &parseLen) != HITLS_SUCCESS) { return HITLS_INTERNAL_EXCEPTION; } 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; } static int32_t GetDisorderClientFinished1(FRAME_LinkObj *client, uint8_t *data, uint32_t len, uint32_t *usedLen) { int32_t ret; uint32_t readLen = 0; uint32_t offset = 0; (void)HITLS_Connect(client->ssl); ret = FRAME_TransportSendMsg(client->io, &data[offset], len - offset, &readLen); if (readLen == 0 || ret != HITLS_SUCCESS) { return HITLS_INTERNAL_EXCEPTION; } offset += readLen; (void)HITLS_Connect(client->ssl); ret = FRAME_TransportSendMsg(client->io, &data[offset], len - offset, &readLen); if (readLen == 0 || ret != HITLS_SUCCESS) { return HITLS_INTERNAL_EXCEPTION; } offset += readLen; uint8_t tmpData[TEMP_DATA_LEN] = {0}; uint32_t tmpLen = sizeof(tmpData); (void)HITLS_Connect(client->ssl); ret = FRAME_TransportSendMsg(client->io, tmpData, tmpLen, &readLen); if (readLen == 0 || ret != HITLS_SUCCESS) { return HITLS_INTERNAL_EXCEPTION; } tmpLen = readLen; (void)HITLS_Connect(client->ssl); ret = FRAME_TransportSendMsg(client->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; } static int32_t GetDisorderServerFinished(FRAME_LinkObj *server, uint8_t *data, uint32_t len, uint32_t *usedLen) { int32_t ret; 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); 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; } static int32_t AppWrite(HITLS_Ctx *ctx) { int32_t ret; uint8_t writeBuf[] = "GET HTTP 1.0"; uint32_t len = strlen((char *)writeBuf); do { uint32_t writeLen; ret = HITLS_Write(ctx, writeBuf, len, &writeLen); } while (ret == HITLS_REC_NORMAL_RECV_BUF_EMPTY || ret == HITLS_REC_NORMAL_IO_BUSY); return ret; } static int32_t GetDisorderServerFinish_AppData(FRAME_LinkObj *server, uint8_t *data, uint32_t len, uint32_t *usedLen) { int32_t ret; uint32_t readLen = 0; uint32_t offset = 0; uint8_t ccs[TEMP_DATA_LEN] = {0}; uint32_t ccsLen = sizeof(ccs); (void)HITLS_Accept(server->ssl); ret = FRAME_TransportSendMsg(server->io, ccs, ccsLen, &readLen); if (readLen == 0 || ret != HITLS_SUCCESS) { return HITLS_INTERNAL_EXCEPTION; } ccsLen = readLen; uint8_t finished[TEMP_DATA_LEN] = {0}; uint32_t finishedLen = sizeof(finished); (void)HITLS_Accept(server->ssl); ret = FRAME_TransportSendMsg(server->io, finished, finishedLen, &readLen); if (readLen == 0 || ret != HITLS_SUCCESS) { return HITLS_INTERNAL_EXCEPTION; } finishedLen = readLen; uint8_t app[TEMP_DATA_LEN] = {0}; uint32_t appLen = sizeof(finished); ret = AppWrite(server->ssl); if (ret != HITLS_SUCCESS) { return ret; } ret = FRAME_TransportSendMsg(server->io, app, appLen, &readLen); if (readLen == 0 || ret != HITLS_SUCCESS) { return HITLS_INTERNAL_EXCEPTION; } appLen = readLen; if (memcpy_s(&data[offset], len - offset, ccs, ccsLen) != EOK) { return HITLS_MEMCPY_FAIL; } offset += ccsLen; if (memcpy_s(&data[offset], len - offset, app, appLen) != EOK) { return HITLS_MEMCPY_FAIL; } offset += appLen; if (memcpy_s(&data[offset], len - offset, finished, finishedLen) != EOK) { return HITLS_MEMCPY_FAIL; } offset += finishedLen; *usedLen = offset; return HITLS_SUCCESS; } int32_t DefaultCfgStatusPark1(HandshakeTestInfo *testInfo) { FRAME_Init(); testInfo->config = HITLS_CFG_NewDTLCPConfig(); if (testInfo->config == NULL) { return HITLS_INTERNAL_EXCEPTION; } HITLS_CFG_SetCheckKeyUsage(testInfo->config, false); uint16_t groups[] = {HITLS_EC_GROUP_SM2}; HITLS_CFG_SetGroups(testInfo->config, groups, sizeof(groups) / sizeof(uint16_t)); uint16_t signAlgs[] = {CERT_SIG_SCHEME_SM2_SM3}; HITLS_CFG_SetSignature(testInfo->config, signAlgs, sizeof(signAlgs) / sizeof(uint16_t)); HITLS_CFG_SetClientVerifySupport(testInfo->config, testInfo->isSupportClientVerify); HITLS_CFG_SetNoClientCertSupport(testInfo->config, false); HITLS_CFG_SetExtenedMasterSecretSupport(testInfo->config, true); return StatusPark(testInfo, BSL_UIO_UDP); } static int32_t GetRepeatsApp(FRAME_LinkObj *obj, uint8_t *data, uint32_t *usedLen) { int32_t ret; uint32_t readLen = 0; uint32_t offset = 0; uint8_t app[TEMP_DATA_LEN] = {0}; uint32_t appLen = sizeof(app); ret = AppWrite(obj->ssl); if (ret != HITLS_SUCCESS) { return ret; } ret = FRAME_TransportSendMsg(obj->io, app, appLen, &readLen); if (readLen == 0 || ret != HITLS_SUCCESS) { return HITLS_INTERNAL_EXCEPTION; } appLen = readLen; if (memcpy_s(&data[offset], TEMP_DATA_LEN, app, appLen) != EOK) { return HITLS_MEMCPY_FAIL; } offset += appLen; if (memcpy_s(&data[offset], TEMP_DATA_LEN - offset, app, appLen) != EOK) { return HITLS_MEMCPY_FAIL; } offset += appLen; *usedLen = offset; return HITLS_SUCCESS; } static int32_t GetDisorderApp(FRAME_LinkObj *obj, uint8_t *data, uint32_t *usedLen) { int32_t ret; uint32_t readLen = 0; uint32_t offset = 0; uint8_t app1[TEMP_DATA_LEN] = {0}; uint32_t app1Len = sizeof(app1); ret = AppWrite(obj->ssl); if (ret != HITLS_SUCCESS) { return ret; } ret = FRAME_TransportSendMsg(obj->io, app1, app1Len, &readLen); if (readLen == 0 || ret != HITLS_SUCCESS) { return HITLS_INTERNAL_EXCEPTION; } app1Len = readLen; uint8_t app2[TEMP_DATA_LEN] = {0}; uint32_t app2Len = sizeof(app2); ret = AppWrite(obj->ssl); if (ret != HITLS_SUCCESS) { return ret; } ret = FRAME_TransportSendMsg(obj->io, app2, app2Len, &readLen); if (readLen == 0 || ret != HITLS_SUCCESS) { return HITLS_INTERNAL_EXCEPTION; } app2Len = readLen; if (memcpy_s(&data[offset], TEMP_DATA_LEN, app2, app2Len) != EOK) { return HITLS_MEMCPY_FAIL; } offset += app2Len; if (memcpy_s(&data[offset], TEMP_DATA_LEN - offset, app1, app1Len) != EOK) { return HITLS_MEMCPY_FAIL; } offset += app1Len; *usedLen = offset; return HITLS_SUCCESS; }
2301_79861745/bench_create
testcode/sdv/testcase/tls/consistency/dtlcp/test_suite_sdv_frame_dtlcp_consistency.base.c
C
unknown
12,719
/* * This file is part of the openHiTLS project. * * openHiTLS is licensed under the Mulan PSL v2. * You can use this software according to the terms and conditions of the Mulan PSL v2. * You may obtain a copy of Mulan PSL v2 at: * * http://license.coscl.org.cn/MulanPSL2 * * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, * EITHER EXPRESS 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_sdv_frame_dtlcp_consistency */ /* END_HEADER */ /* @ * @test UT_TLS_DTLCP_CONSISTENCY_RFC6347_FINISH_TC001 * @spec - * @titleThe client receives a FINISH message and the CCS message is out of order. * @precon nan * @brief 1. Initialize the client and server based on the default configuration. Expected result 1. * 2. The client initiates a connection request and constructs the scenario where the FINISH message and CCS message are out of order. That is, the client processes the FINISH message and then processes the CCS message. After the processing, the client continues to establish a connection. Expected result 2 is displayed. * @expect 1: The initialization is successful. * 2: The client waits to receive the FINISH message. * @prior Level 1 * @auto TRUE @ */ /* BEGIN_CASE */ void UT_TLS_DTLCP_CONSISTENCY_RFC6347_FINISH_TC001(void) { HandshakeTestInfo testInfo = {0}; testInfo.isClient = false; testInfo.state = TRY_SEND_CHANGE_CIPHER_SPEC; ASSERT_TRUE(DefaultCfgStatusPark(&testInfo, BSL_UIO_UDP) == HITLS_SUCCESS); uint8_t data[MAX_RECORD_LENTH] = {0}; uint32_t len = MAX_RECORD_LENTH; ASSERT_TRUE(GetDisorderServerFinished(testInfo.server, data, len, &len) == HITLS_SUCCESS); FrameUioUserData *ioUserData = BSL_UIO_GetUserData(testInfo.client->io); ASSERT_TRUE(ioUserData->recMsg.len == 0); ASSERT_TRUE(FRAME_TransportRecMsg(testInfo.client->io, data, len) == HITLS_SUCCESS); (void)HITLS_Connect(testInfo.client->ssl); ASSERT_EQ(testInfo.client->ssl->state, CM_STATE_TRANSPORTING); EXIT: HITLS_CFG_FreeConfig(testInfo.config); FRAME_FreeLink(testInfo.client); FRAME_FreeLink(testInfo.server); FRAME_DeRegCryptMethod(); } /* END_CASE */ /* @ * @test UT_TLS_DTLS_CONSISTENCY_RFC6347_FINISH_TC002 * @spec - * @titleThe server receives a FINISH message and the CCS message is out of order. * @precon nan * @brief 1. Initialize the client and server based on the default configuration. Expected result 1. * 2. The client initiates a connection request and constructs the scenario where the FINISH message and CCS message are out of order. That is, the server processes the FINISH message and then processes the CCS message. After the processing, the server continues to establish a connection. Expected result 2 is displayed. * @expect 1: The initialization is successful. * 2: The server is waiting to receive the FINISH message. * @prior Level 1 * @auto TRUE @ */ /* BEGIN_CASE */ void UT_TLS_DTLCP_CONSISTENCY_RFC6347_FINISH_TC002(void) { FRAME_Msg frameMsg = {0}; FRAME_Type frameType = {0}; HandshakeTestInfo testInfo = {0}; testInfo.isClient = true; testInfo.state = TRY_SEND_CLIENT_KEY_EXCHANGE; ASSERT_TRUE(DefaultCfgStatusPark(&testInfo, BSL_UIO_UDP) == HITLS_SUCCESS); uint8_t data[MAX_RECORD_LENTH] = {0}; uint32_t len = MAX_RECORD_LENTH; ASSERT_TRUE(GetDisorderClientFinished1(testInfo.client, data, len, &len) == HITLS_SUCCESS); FrameUioUserData *ioUserData = BSL_UIO_GetUserData(testInfo.server->io); ASSERT_TRUE(ioUserData->recMsg.len == 0); ASSERT_TRUE(FRAME_TransportRecMsg(testInfo.server->io, data, len) == HITLS_SUCCESS); (void)HITLS_Accept(testInfo.server->ssl); ASSERT_EQ(testInfo.server->ssl->state, CM_STATE_HANDSHAKING); ASSERT_EQ(testInfo.server->ssl->hsCtx->state, TRY_SEND_CHANGE_CIPHER_SPEC); 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_DTLCP_CONSISTENCY_RFC6347_FINISH_TC003 * @spec - * @titleThe client receives a FINISH message and the APP message is out of order. * @precon nan * @brief 1. Initialize the client and server using the default configuration. Expected result 1. * 2. The client initiates a connection request and constructs the scenario where the FINISH message and APP message are out of order. That is, the client processes the APP message first, processes the FINISH message, and then continues to establish a connection. Expected result 2. * @expect 1: Initialization succeeded. * 2: The connection between the client and server is successfully established. * @prior Level 1 * @auto TRUE @ */ /* BEGIN_CASE */ void UT_TLS_DTLCP_CONSISTENCY_RFC6347_FINISH_TC003(void) { HandshakeTestInfo testInfo = {0}; testInfo.isClient = false; testInfo.state = TRY_SEND_CHANGE_CIPHER_SPEC; ASSERT_TRUE(DefaultCfgStatusPark(&testInfo, BSL_UIO_UDP) == HITLS_SUCCESS); uint8_t data[MAX_RECORD_LENTH] = {0}; uint32_t len = MAX_RECORD_LENTH; ASSERT_TRUE(GetDisorderServerFinish_AppData(testInfo.server, data, len, &len) == HITLS_SUCCESS); FrameUioUserData *ioUserData = BSL_UIO_GetUserData(testInfo.client->io); ASSERT_TRUE(ioUserData->recMsg.len == 0); ASSERT_TRUE(FRAME_TransportRecMsg(testInfo.client->io, data, len) == HITLS_SUCCESS); (void)HITLS_Connect(testInfo.client->ssl); ASSERT_TRUE(testInfo.client->ssl->state == CM_STATE_TRANSPORTING); ASSERT_TRUE(HITLS_Read(testInfo.client->ssl, data, MAX_RECORD_LENTH, &len) == HITLS_SUCCESS); EXIT: HITLS_CFG_FreeConfig(testInfo.config); FRAME_FreeLink(testInfo.client); FRAME_FreeLink(testInfo.server); FRAME_DeRegCryptMethod(); } /* END_CASE */ /* @ * @test UT_TLS_DTLCP_CONSISTENCY_RFC6347_DISORDER_TC001 * @spec - * @titleThe server receives out-of-order APP messages. * @precon nan * @brief 1. Initialize the configuration on the client and server. Expected result 1. * 2. Initiate a connection application by using DTLCP. Expected result 2. * 3. Construct an app message whose SN is 2 and send it to the server. When the server invokes HiTLS_Read, expected result 3. * 4. Construct an app message whose SN is 1 and send it to the server. When the server invokes HiTLS_Read, expected result 4. * @expect 1: Initializing the configuration succeeded. * 2: The DTLCP connection is successfully created. * 3: The interface returns a success response. * 4: The interface returns a success response. * @prior Level 1 * @auto TRUE @ */ /* BEGIN_CASE */ void UT_TLS_DTLCP_CONSISTENCY_RFC6347_DISORDER_TC001(void) { HandshakeTestInfo testInfo = {0}; testInfo.isClient = true; testInfo.state = HS_STATE_BUTT; ASSERT_EQ(DefaultCfgStatusPark1(&testInfo), HITLS_SUCCESS); uint8_t data[MAX_RECORD_LENTH] = {0}; uint32_t len = MAX_RECORD_LENTH; ASSERT_TRUE(GetDisorderApp(testInfo.client, data, &len) == HITLS_SUCCESS); FrameUioUserData *ioUserData = BSL_UIO_GetUserData(testInfo.server->io); ASSERT_TRUE(ioUserData->recMsg.len == 0); ASSERT_TRUE(FRAME_TransportRecMsg(testInfo.server->io, data, len) == HITLS_SUCCESS); uint8_t app1Data[MAX_RECORD_LENTH] = {0}; uint32_t app1Len = MAX_RECORD_LENTH; ASSERT_TRUE(HITLS_Read(testInfo.server->ssl, app1Data, MAX_RECORD_LENTH, &app1Len) == HITLS_SUCCESS); uint8_t app2Data[MAX_RECORD_LENTH] = {0}; uint32_t app2Len = MAX_RECORD_LENTH; ASSERT_TRUE(HITLS_Read(testInfo.server->ssl, app2Data, MAX_RECORD_LENTH, &app2Len) == HITLS_SUCCESS); ASSERT_EQ(app1Len, app2Len); ASSERT_EQ(memcmp(app1Data, app2Data, app2Len), 0); EXIT: HITLS_CFG_FreeConfig(testInfo.config); FRAME_FreeLink(testInfo.client); FRAME_FreeLink(testInfo.server); FRAME_DeRegCryptMethod(); } /* END_CASE */ /* @ * @test UT_TLS_DTLCP_CONSISTENCY_RFC6347_DISORDER_TC002 * @spec - * @titleThe client receives out-of-order APP messages. * @precon nan * @brief 1. Initialize the configuration on the client and server. Expected result 1. * 2. Initiate a connection request using DTLCP. Expected result 2. * 3. Construct an app message whose sequence number is 2 and send it to the client. When the client invokes HiTLS_Read, expected result 3. * 4. Construct an app message whose sequence number is 1 and send it to the client. When the client invokes HiTLS_Read, expected result 4. * @expect 1: Initializing the configuration succeeded. * 2: The DTLCP connection is successfully created. * 3: The interface returns a success response. * 4: The interface returns a success response. * @prior Level 1 * @auto TRUE @ */ /* BEGIN_CASE */ void UT_TLS_DTLCP_CONSISTENCY_RFC6347_DISORDER_TC002(void) { HandshakeTestInfo testInfo = {0}; testInfo.isClient = false; testInfo.state = HS_STATE_BUTT; ASSERT_EQ(DefaultCfgStatusPark1(&testInfo), HITLS_SUCCESS); uint8_t data[MAX_RECORD_LENTH] = {0}; uint32_t len = MAX_RECORD_LENTH; ASSERT_TRUE(GetDisorderApp(testInfo.server, data, &len) == HITLS_SUCCESS); FrameUioUserData *ioUserData = BSL_UIO_GetUserData(testInfo.client->io); ASSERT_TRUE(ioUserData->recMsg.len == 0); ASSERT_TRUE(FRAME_TransportRecMsg(testInfo.client->io, data, len) == HITLS_SUCCESS); uint8_t app1Data[MAX_RECORD_LENTH] = {0}; uint32_t app1Len = MAX_RECORD_LENTH; ASSERT_TRUE(HITLS_Read(testInfo.client->ssl, app1Data, MAX_RECORD_LENTH, &app1Len) == HITLS_SUCCESS); uint8_t app2Data[MAX_RECORD_LENTH] = {0}; uint32_t app2Len = MAX_RECORD_LENTH; ASSERT_TRUE(HITLS_Read(testInfo.client->ssl, app2Data, MAX_RECORD_LENTH, &app2Len) == HITLS_SUCCESS); ASSERT_EQ(app1Len, app2Len); ASSERT_EQ(memcmp(app1Data, app2Data, app1Len), 0); EXIT: HITLS_CFG_FreeConfig(testInfo.config); FRAME_FreeLink(testInfo.client); FRAME_FreeLink(testInfo.server); FRAME_DeRegCryptMethod(); } /* END_CASE */ /* @ * @test UT_TLS_DTLCP_CONSISTENCY_RFC6347_APPDATA_TC001 * @spec - * @title The server receives duplicate APP messages. * @precon nan * @brief 1. Initialize the configuration on the client and server. Expected result 1. * 2. Initiate a connection application by using DTLCP. Expected result 2. * 3. Construct an app message whose SN is 1 and send it to the server. When the server invokes HiTLS_Read, expected result 3. * 4. Construct the app message whose SN is 1 and send it to the server. When the server invokes HiTLS_Read, expected result 4. * 5. The server constructs data and sends it to the client. When the client invokes HiTLS_Read, expected result 5. * @expect 1: Initializing the configuration succeeded. * 2: The DTLCP connection is successfully created. * 3: The interface returns a success response. * 4: The interface returns a success response. * 5: The interface returns a success response. * @prior Level 1 * @auto TRUE @ */ /* BEGIN_CASE */ void UT_TLS_DTLCP_CONSISTENCY_RFC6347_APPDATA_TC001(void) { HandshakeTestInfo testInfo = {0}; testInfo.isClient = true; testInfo.state = HS_STATE_BUTT; ASSERT_EQ(DefaultCfgStatusPark1(&testInfo), HITLS_SUCCESS); uint8_t data[MAX_RECORD_LENTH] = {0}; uint32_t len = MAX_RECORD_LENTH; ASSERT_TRUE(GetRepeatsApp(testInfo.client, data, &len) == HITLS_SUCCESS); FrameUioUserData *ioUserData = BSL_UIO_GetUserData(testInfo.server->io); ASSERT_TRUE(ioUserData->recMsg.len == 0); ASSERT_TRUE(FRAME_TransportRecMsg(testInfo.server->io, data, len) == HITLS_SUCCESS); ASSERT_TRUE(HITLS_Read(testInfo.server->ssl, data, MAX_RECORD_LENTH, &len) == HITLS_SUCCESS); ASSERT_EQ(HITLS_Read(testInfo.server->ssl, data, MAX_RECORD_LENTH, &len), HITLS_REC_NORMAL_RECV_BUF_EMPTY); uint8_t writeData[] = {"abcd1234"}; uint32_t writeLen = strlen("abcd1234"); uint8_t readData[MAX_RECORD_LENTH] = {0}; uint32_t readLen = MAX_RECORD_LENTH; uint8_t tmpData[MAX_RECORD_LENTH]; uint32_t tmpLen; uint32_t sendNum; ASSERT_TRUE(HITLS_Write(testInfo.server->ssl, writeData, writeLen, &sendNum) == HITLS_SUCCESS); ASSERT_TRUE(FRAME_TransportSendMsg(testInfo.server->io, tmpData, MAX_RECORD_LENTH, &tmpLen) == HITLS_SUCCESS); ASSERT_TRUE(FRAME_TransportRecMsg(testInfo.client->io, tmpData, tmpLen) == HITLS_SUCCESS); ASSERT_EQ(HITLS_Read(testInfo.client->ssl, readData, MAX_RECORD_LENTH, &readLen), HITLS_SUCCESS); ASSERT_EQ(readLen, writeLen); ASSERT_EQ(memcmp(writeData, readData, readLen), 0); EXIT: HITLS_CFG_FreeConfig(testInfo.config); FRAME_FreeLink(testInfo.client); FRAME_FreeLink(testInfo.server); FRAME_DeRegCryptMethod(); } /* END_CASE */ /* @ * @test UT_TLS_DTLCP_CONSISTENCY_RFC6347_APPDATA_TC002 * @spec - * @titleThe client receives duplicate APP messages. * @precon nan * @brief 1. Initialize the configuration on the client and server. Expected result 1. * 2. Initiate a connection application by using DTLCP. Expected result 2. * 3. Construct an app message whose sequence number is 1 and send the message to the client. When the client invokes HiTLS_Read, expected result 3. * 4. Construct an app message with the sequence number being 1 and send it to the client. When the client invokes HiTLS_Read, expected result 4. * 5. The server constructs data and sends it to the client. When the client invokes HiTLS_Read, expected result 5. * @expect 1: Initializing the configuration succeeded. * 2: The DTLCP connection is successfully created. * 3: The interface returns a success response. * 4: The interface returns a success response. * 5: The interface returns a success response. * @prior Level 1 * @auto TRUE @ */ /* BEGIN_CASE */ void UT_TLS_DTLCP_CONSISTENCY_RFC6347_APPDATA_TC002(void) { HandshakeTestInfo testInfo = {0}; testInfo.isClient = false; testInfo.state = HS_STATE_BUTT; ASSERT_EQ(DefaultCfgStatusPark1(&testInfo), HITLS_SUCCESS); uint8_t data[MAX_RECORD_LENTH] = {0}; uint32_t len = MAX_RECORD_LENTH; ASSERT_TRUE(GetRepeatsApp(testInfo.server, data, &len) == HITLS_SUCCESS); FrameUioUserData *ioUserData = BSL_UIO_GetUserData(testInfo.client->io); ASSERT_TRUE(ioUserData->recMsg.len == 0); ASSERT_TRUE(FRAME_TransportRecMsg(testInfo.client->io, data, len) == HITLS_SUCCESS); ASSERT_TRUE(HITLS_Read(testInfo.client->ssl, data, MAX_RECORD_LENTH, &len) == HITLS_SUCCESS); ASSERT_EQ(HITLS_Read(testInfo.client->ssl, data, MAX_RECORD_LENTH, &len), HITLS_REC_NORMAL_RECV_BUF_EMPTY); uint8_t writeData[] = {"abcd1234"}; uint32_t writeLen = strlen("abcd1234"); uint8_t readData[MAX_RECORD_LENTH] = {0}; uint32_t readLen = MAX_RECORD_LENTH; uint8_t tmpData[MAX_RECORD_LENTH]; uint32_t tmpLen; uint32_t sendNum; ASSERT_TRUE(HITLS_Write(testInfo.server->ssl, writeData, writeLen, &sendNum) == HITLS_SUCCESS); ASSERT_TRUE(FRAME_TransportSendMsg(testInfo.server->io, tmpData, MAX_RECORD_LENTH, &tmpLen) == HITLS_SUCCESS); ASSERT_TRUE(FRAME_TransportRecMsg(testInfo.client->io, tmpData, tmpLen) == HITLS_SUCCESS); ASSERT_EQ(HITLS_Read(testInfo.client->ssl, readData, MAX_RECORD_LENTH, &readLen), HITLS_SUCCESS); ASSERT_EQ(readLen, writeLen); ASSERT_EQ(memcmp(writeData, readData, readLen), 0); EXIT: HITLS_CFG_FreeConfig(testInfo.config); FRAME_FreeLink(testInfo.client); FRAME_FreeLink(testInfo.server); FRAME_DeRegCryptMethod(); } /* END_CASE */ /* @ * @test UT_TLS_DTLCP_CONSISTENCY_RFC6347_CLIENT_HELLO_TC001 * @spec - * @title The server receives a Client Hello packet after the connection is established. * @precon nan * @brief 1. Initialize the client and server based on the default configuration. Expected result 1. * 2. The client initiates a connection request. Expected result 2. * 3. Construct a Client Hello packet and send it to the server. The server invokes HiTLS_Read to receive the packet. Expected result 3. * 4. The client invokes HiTLS_Write to send data to the server, and the server invokes HiTLS_Read to read data. (Expected result 4) * @expect 1: Initialization succeeded. * 2: The connection between the client and server is successfully established. * 3: The HiTLS_Read returns an error code, indicating that the receiving buffer is empty. * 4: The data read by the server is consistent with the data sent by the client. * @prior Level 1 * @auto TRUE @ */ /* BEGIN_CASE */ void UT_TLS_DTLCP_CONSISTENCY_RFC6347_CLIENT_HELLO_TC001(void) { HandshakeTestInfo testInfo = {0}; FRAME_Msg frameMsg = {0}; FRAME_Type frameType = {0}; testInfo.isClient = true; testInfo.state = HS_STATE_BUTT; ASSERT_EQ(DefaultCfgStatusPark1(&testInfo), HITLS_SUCCESS); frameType.versionType = HITLS_VERSION_TLCP_DTLCP11; frameType.recordType = REC_TYPE_HANDSHAKE; frameType.handshakeType = CLIENT_HELLO; frameType.keyExType = HITLS_KEY_EXCH_ECDHE; frameType.transportType = BSL_UIO_UDP; 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); ASSERT_TRUE(REC_Write(testInfo.client->ssl, REC_TYPE_HANDSHAKE, &sendBuf[REC_DTLS_RECORD_HEADER_LEN], sendLen - REC_DTLS_RECORD_HEADER_LEN) == HITLS_SUCCESS); ASSERT_TRUE(FRAME_TrasferMsgBetweenLink(testInfo.client, testInfo.server) == HITLS_SUCCESS); uint8_t data[MAX_RECORD_LENTH] = {0}; uint32_t len = MAX_RECORD_LENTH; ASSERT_TRUE(testInfo.server->ssl != NULL); ASSERT_EQ(HITLS_Read(testInfo.server->ssl, data, MAX_RECORD_LENTH, &len), HITLS_REC_NORMAL_RECV_BUF_EMPTY); uint8_t writeData[] = {"abcd1234"}; uint32_t writeLen = strlen("abcd1234"); uint8_t readData[MAX_RECORD_LENTH] = {0}; uint32_t readLen = MAX_RECORD_LENTH; uint8_t tmpData[MAX_RECORD_LENTH]; uint32_t tmpLen; uint32_t sendNum; ASSERT_EQ(HITLS_Write(testInfo.client->ssl, writeData, writeLen, &sendNum), HITLS_SUCCESS); ASSERT_TRUE(FRAME_TransportSendMsg(testInfo.client->io, tmpData, MAX_RECORD_LENTH, &tmpLen) == HITLS_SUCCESS); ASSERT_TRUE(FRAME_TransportRecMsg(testInfo.server->io, tmpData, tmpLen) == HITLS_SUCCESS); ASSERT_EQ(HITLS_Read(testInfo.server->ssl, readData, MAX_RECORD_LENTH, &readLen), HITLS_SUCCESS); ASSERT_EQ(readLen, writeLen); ASSERT_EQ(memcmp(writeData, readData, readLen), 0); EXIT: HITLS_CFG_FreeConfig(testInfo.config); FRAME_CleanMsg(&frameType, &frameMsg); FRAME_FreeLink(testInfo.client); FRAME_FreeLink(testInfo.server); FRAME_DeRegCryptMethod(); } /* END_CASE */ /* @ * @test UT_TLS_DTLCP_CONSISTENCY_RFC8422_ECPOINT_TC001 * @spec - * @titleThe client receives an abnormal dot format field. * @precon nan * @brief 1. The client and server use the default initialization. Expected result 1. * 2. The client initiates a connection request. When the client wants to read the Server Hello message, * Modify the Elliptic curves point formats field, change the group supported by the field to 0x01, and send the field to the client. Expected result 2. * @expect 1. Initialization succeeded. * 2. The client sends a FATAL ALERT with the description of ALERT_ELLEGAL_PARAMETER. * @prior Level 1 * @auto TRUE @ */ /* BEGIN_CASE */ void UT_TLS_DTLCP_CONSISTENCY_RFC8422_ECPOINT_TC001(void) { HandshakeTestInfo testInfo = {0}; testInfo.state = TRY_RECV_SERVER_HELLO; testInfo.isSupportExtendMasterSecret = true; testInfo.isClient = true; ASSERT_TRUE(DefaultCfgStatusPark(&testInfo, BSL_UIO_UDP) == 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_TLCP_DTLCP11; frameType.recordType = REC_TYPE_HANDSHAKE; frameType.handshakeType = SERVER_HELLO; frameType.keyExType = HITLS_KEY_EXCH_ECDHE; frameType.transportType = BSL_UIO_UDP; ASSERT_TRUE(FRAME_ParseMsg(&frameType, recvBuf, recvLen, &frameMsg, &parseLen) == HITLS_SUCCESS); uint8_t Gdata[] = { 0x01 }; FRAME_ServerHelloMsg *serverMsg = &frameMsg.body.hsMsg.body.serverHello; serverMsg->pointFormats.exState = INITIAL_FIELD; ASSERT_TRUE(FRAME_ModifyMsgInteger(HS_EX_TYPE_POINT_FORMATS, &(serverMsg->pointFormats.exType)) == HITLS_SUCCESS); serverMsg->pointFormats.exLen.state = INITIAL_FIELD; ASSERT_TRUE(FRAME_ModifyMsgArray8(Gdata, sizeof(Gdata)/sizeof(uint8_t), &(serverMsg->pointFormats.exData), &(serverMsg->pointFormats.exDataLen)) == 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); 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); ASSERT_EQ(HITLS_Connect(testInfo.client->ssl), HITLS_MSG_HANDLE_UNSUPPORT_POINT_FORMAT); 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_TRUE(alertMsg->alertDescription.data == ALERT_ILLEGAL_PARAMETER); 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_DTLCP_CONSISTENCY_RFC8422_EXTENSION_MISS_TC001 * @spec - * @title The server receives a Client Hello packet that does not carry the group or dot format. * @precon nan * @brief 1. Configure the HITLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384 cipher suite on the client and initialize the cipher suite on the server by default. Expected result 1. * 2. When the client initiates a connection request and the server is about to read ClientHello, * Delete the supported_groups and ec_point_formats fields from the packet. Expected result 2. * @expect 1. Initialization succeeded. * 2. The server sends a Server Hello packet with the HITLS_ECDHE_SM4_CBC_SM3 algorithm suite. * @prior Level 1 * @auto TRUE @ */ /* BEGIN_CASE */ void UT_TLS_DTLCP_CONSISTENCY_RFC8422_EXTENSION_MISS_TC001(void) { HandshakeTestInfo testInfo = {0}; testInfo.state = TRY_RECV_CLIENT_HELLO; testInfo.isSupportExtendMasterSecret = true; testInfo.isClient = false; ASSERT_TRUE(DefaultCfgStatusPark(&testInfo, BSL_UIO_UDP) == 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; FRAME_Msg frameMsg = {0}; FRAME_Type frameType = {0}; frameType.versionType = HITLS_VERSION_TLCP_DTLCP11; frameType.recordType = REC_TYPE_HANDSHAKE; frameType.handshakeType = CLIENT_HELLO; frameType.keyExType = HITLS_KEY_EXCH_ECDHE; frameType.transportType = BSL_UIO_UDP; ASSERT_TRUE(FRAME_ParseMsg(&frameType, recvBuf, recvLen, &frameMsg, &parseLen) == HITLS_SUCCESS); FRAME_ClientHelloMsg *clientMsg = &frameMsg.body.hsMsg.body.clientHello; clientMsg->supportedGroups.exState = MISSING_FIELD; clientMsg->pointFormats.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(testInfo.server->io, sendBuf, sendLen) == HITLS_SUCCESS); FRAME_CleanMsg(&frameType, &frameMsg); memset_s(&frameMsg, sizeof(frameMsg), 0, sizeof(frameMsg)); CONN_Deinit(testInfo.server->ssl); ASSERT_TRUE(testInfo.server->ssl != NULL); ASSERT_EQ(HITLS_Accept(testInfo.server->ssl), HITLS_REC_NORMAL_IO_BUSY); 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_HANDSHAKE; ASSERT_TRUE(FRAME_ParseMsg(&frameType, sndBuf, sndLen, &frameMsg, &parseLen) == HITLS_SUCCESS); ASSERT_TRUE(frameMsg.recType.data == REC_TYPE_HANDSHAKE); ASSERT_TRUE(frameMsg.body.hsMsg.type.data == SERVER_HELLO); FRAME_ServerHelloMsg *serverMsg = &frameMsg.body.hsMsg.body.serverHello; ASSERT_EQ(serverMsg->cipherSuite.data, HITLS_ECDHE_SM4_CBC_SM3); EXIT: FRAME_CleanMsg(&frameType, &frameMsg); HITLS_CFG_FreeConfig(testInfo.config); FRAME_FreeLink(testInfo.client); FRAME_FreeLink(testInfo.server); FRAME_DeRegCryptMethod(); } /* END_CASE */ /* when receive alert between finish and ccs, dtlcp should cache it*/ /* BEGIN_CASE */ void UT_DTLCP_RFC6347_RECV_ALERT_AFTER_CCS_TC001() { FRAME_Init(); HITLS_Config *tlsConfig = HITLS_CFG_NewDTLCPConfig(); ASSERT_TRUE(tlsConfig != NULL); FRAME_LinkObj *client = FRAME_CreateTLCPLink(tlsConfig, BSL_UIO_UDP, true); FRAME_LinkObj *server = FRAME_CreateTLCPLink(tlsConfig, BSL_UIO_UDP, false); client->needStopBeforeRecvCCS = true; server->needStopBeforeRecvCCS = true; 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); // client receive ccs, wait to receive finish ASSERT_EQ(HITLS_Connect(clientTlsCtx), HITLS_REC_NORMAL_RECV_BUF_EMPTY); uint8_t alertdata[2] = {0x02, 0x0a}; ASSERT_EQ(REC_Write(serverTlsCtx, REC_TYPE_ALERT, alertdata, sizeof(alertdata)), HITLS_SUCCESS); ASSERT_TRUE(FRAME_TrasferMsgBetweenLink(server, client) == HITLS_SUCCESS); // client cache the alert, wait to receive finish ASSERT_EQ(HITLS_Connect(clientTlsCtx), HITLS_REC_NORMAL_RECV_BUF_EMPTY); ASSERT_TRUE(clientTlsCtx->state == CM_STATE_HANDSHAKING); // server send finish, handshake success ASSERT_EQ(HITLS_Accept(serverTlsCtx), HITLS_SUCCESS); ASSERT_TRUE(FRAME_TrasferMsgBetweenLink(server, client) == HITLS_SUCCESS); // client receive finish, handshake success ASSERT_EQ(HITLS_Connect(clientTlsCtx), HITLS_SUCCESS); ASSERT_TRUE(clientTlsCtx->state == CM_STATE_TRANSPORTING); // client read cached alert uint8_t readBuf[READ_BUF_SIZE] = {0}; uint32_t readLen = 0; ASSERT_EQ(HITLS_Read(clientTlsCtx, readBuf, READ_BUF_SIZE, &readLen), 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_DTLCP_CONSISTENCY_RFC6347_TC001 * @spec - * @title The client receives a Hello Request message which msg seq is not 0. * @precon nan * @brief 1. Use the default configuration items to configure the client and server. Expected result 1. * 2. After the client finished handshake, the client receives a Hello Request message. Expected result 2. * @expect 1. The initialization is successful. * 2. The client igore the message. * @prior Level 1 * @auto TRUE @ */ /* BEGIN_CASE */ void UT_TLS_DTLCP_CONSISTENCY_RFC6347_TC001() { FRAME_Init(); HITLS_Config *tlsConfig = HITLS_CFG_NewDTLCPConfig(); tlsConfig->isSupportRenegotiation = true; ASSERT_TRUE(tlsConfig != NULL); FRAME_LinkObj *client = FRAME_CreateTLCPLink(tlsConfig, BSL_UIO_UDP, true); FRAME_LinkObj *server = FRAME_CreateTLCPLink(tlsConfig, BSL_UIO_UDP, false); 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, HS_STATE_BUTT) == HITLS_SUCCESS); uint8_t buf[DTLS_HS_MSG_HEADER_SIZE] = {0u}; buf[5] = 1; size_t len = DTLS_HS_MSG_HEADER_SIZE; REC_Write(serverTlsCtx, REC_TYPE_HANDSHAKE, buf, len); ASSERT_EQ(FRAME_TrasferMsgBetweenLink(server, client), HITLS_SUCCESS); uint8_t readData[MAX_RECORD_LENTH] = {0}; uint32_t readLen = MAX_RECORD_LENTH; ASSERT_EQ(HITLS_Read(clientTlsCtx, readData, MAX_RECORD_LENTH, &readLen), HITLS_REC_NORMAL_RECV_BUF_EMPTY); EXIT: HITLS_CFG_FreeConfig(tlsConfig); FRAME_FreeLink(client); FRAME_FreeLink(server); } /* END_CASE */
2301_79861745/bench_create
testcode/sdv/testcase/tls/consistency/dtlcp/test_suite_sdv_frame_dtlcp_consistency.c
C
unknown
29,185
/* * This file is part of the openHiTLS project. * * openHiTLS is licensed under the Mulan PSL v2. * You can use this software according to the terms and conditions of the Mulan PSL v2. * You may obtain a copy of Mulan PSL v2 at: * * http://license.coscl.org.cn/MulanPSL2 * * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, * EITHER EXPRESS 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 <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 "recv_process.h" #include "stub_replace.h" #include "stub_crypt.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 "rec_wrapper.h" #include "process.h" #include "pthread.h" #include "unistd.h" #include "rec_header.h" #include "bsl_log.h" #include "cert_callback.h" #include "bsl_uio.h" #include "uio_abstraction.h" /* END_HEADER */ #define BUF_SIZE_DTO_TEST 18432 void Hello(void *ssl) { const char *writeBuf = "Hello world"; ASSERT_TRUE(HLT_TlsWrite(ssl, (uint8_t *)writeBuf, strlen(writeBuf)) == 0); EXIT: return; } /** * @test SDV_TLS_DTLCP_HANDSHAKE_FUNC_TC001 * @spec - * @title Check whether DTLCP over SCTP can handshake successfully. * @precon nan * @brief * 1. Use the default configuration items to configure the client and server. Expected result 1. * 2. A DTLCP over SCTP connection is established between the client and server. Expected result 2. * 3. Construct a app message and send it to the client. Check the server ret. Expected result 3. * @expect * 1. The initialization is successful. * 2. The connection is set up successfully. * 3. The server ret is HITLS_SUCCESS. * @prior Level 1 * @auto TRUE @ */ /* BEGIN_CASE */ void SDV_TLS_DTLCP_HANDSHAKE_FUNC_TC001(int connType) { if (connType == SCTP && !IsEnableSctpAuth()) { return; } bool certverifyflag = 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, connType, 16790, true); ASSERT_TRUE(remoteProcess != NULL); HLT_Ctx_Config *serverCtxConfig = HLT_NewCtxConfigTLCP(NULL, "SERVER", false); ASSERT_TRUE(serverCtxConfig != NULL); serverCtxConfig->isSupportClientVerify = certverifyflag; serverRes = HLT_ProcessTlsAccept(localProcess, DTLCP1_1, serverCtxConfig, NULL); ASSERT_TRUE(serverRes != NULL); HLT_Ctx_Config *clientCtxConfig = HLT_NewCtxConfigTLCP(NULL, "CLIENT", true); ASSERT_TRUE(clientCtxConfig != NULL); clientCtxConfig->isSupportClientVerify = certverifyflag; clientRes = HLT_ProcessTlsConnect(remoteProcess, DTLCP1_1, clientCtxConfig, NULL); ASSERT_TRUE(clientRes != NULL); ASSERT_TRUE(HLT_GetTlsAcceptResult(serverRes) == 0); ASSERT_EQ(HLT_ProcessTlsWrite(localProcess, serverRes, (uint8_t *)"Hello World", strlen("Hello World")), HITLS_SUCCESS); uint8_t readBuf[1024] = {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_FreeAllProcess(); } /* END_CASE */ /* * @ * @test SDV_TLS_DTLCP_CONSISTENCY_RFC5246_UNEXPETED_REORD_TYPE_TC001 * @Specifications- * @Title1. Construct a scenario where renegotiation messages and application messages are sent at the same time. * It is expected that the server processes renegotiation messages first. * @preconan * @short * @ Previous Level 1 * @autotrue @ */ /* BEGIN_CASE */ void SDV_TLS_DTLCP_CONSISTENCY_RFC5246_UNEXPETED_REORD_TYPE_TC001() { int version = TLS1_2; int connType = TCP; int32_t serverConfigId = 0; Process *localProcess = NULL; Process *remoteProcess = NULL; HLT_FD sockFd = {0}; HITLS_Session *session = NULL; TLS_TYPE local = HITLS; TLS_TYPE remote = HITLS; localProcess = HLT_InitLocalProcess(local); ASSERT_TRUE(localProcess != NULL); remoteProcess = HLT_CreateRemoteProcess(remote); ASSERT_TRUE(remoteProcess != NULL); void *clientConfig = HLT_TlsNewCtx(version); ASSERT_TRUE(clientConfig != NULL); HLT_Ctx_Config *clientCtxConfig = HLT_NewCtxConfig(NULL, "CLIENT"); HLT_SetRenegotiationSupport(clientCtxConfig, true); HLT_Ctx_Config *serverCtxConfig = HLT_NewCtxConfig(NULL, "SERVER"); HLT_SetRenegotiationSupport(serverCtxConfig, true); HLT_SetClientRenegotiateSupport(serverCtxConfig, true); #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); DataChannelParam channelParam; channelParam.port = 1666; 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); ASSERT_TRUE(HITLS_Renegotiate(clientSsl) == HITLS_SUCCESS); const char *writeBuf = "Hello world"; pthread_t thrd; ASSERT_TRUE(pthread_create(&thrd, NULL, (void *)Hello, clientSsl) == 0); sleep(2); uint8_t readBuf[BUF_SIZE_DTO_TEST] = {0}; uint32_t readLen; ASSERT_TRUE(memset_s(readBuf, BUF_SIZE_DTO_TEST, 0, BUF_SIZE_DTO_TEST) == EOK); ASSERT_TRUE(HLT_RpcTlsRead(remoteProcess, serverSslId, readBuf, BUF_SIZE_DTO_TEST, &readLen) == 0); pthread_join(thrd, NULL); 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); EXIT: ClearWrapper(); HLT_CleanFrameHandle(); HITLS_SESS_Free(session); HLT_FreeAllProcess(); } /* END_CASE */
2301_79861745/bench_create
testcode/sdv/testcase/tls/consistency/dtlcp/test_suite_sdv_hlt_dtlcp_consistency.c
C
unknown
7,869
/* * This file is part of the openHiTLS project. * * openHiTLS is licensed under the Mulan PSL v2. * You can use this software according to the terms and conditions of the Mulan PSL v2. * You may obtain a copy of Mulan PSL v2 at: * * http://license.coscl.org.cn/MulanPSL2 * * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, * EITHER EXPRESS 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 <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 "recv_process.h" #include "stub_replace.h" #include "stub_crypt.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 "rec_wrapper.h" #include "process.h" #include "pthread.h" #include "unistd.h" #include "rec_header.h" #include "bsl_log.h" #include "cert_callback.h" #define BUF_SIZE_DTO_TEST 18432 int32_t g_uiPort = 18887; #define PARSEMSGHEADER_LEN 13 #define ILLEGAL_VALUE 0xFF #define HASH_EXDATA_LEN_ERROR 23 #define SIGNATURE_ALGORITHMS 0x04, 0x03 #define READ_BUF_SIZE (18 * 1024) #define TEMP_DATA_LEN 1024 #define REC_DTLS_RECORD_HEADER_LEN 13 #define BUF_TOOLONG_LEN ((1 << 14) + 1) typedef struct { HITLS_Config *config; FRAME_LinkObj *client; FRAME_LinkObj *server; HITLS_HandshakeState state; bool isClient; bool isSupportExtendMasterSecret; bool isSupportClientVerify; bool isSupportNoClientCert; } HandshakeTestInfo; int32_t StatusPark(HandshakeTestInfo *testInfo, int uioType) { int ret; testInfo->client = FRAME_CreateLink(testInfo->config, uioType); if (testInfo->client == NULL) { return HITLS_INTERNAL_EXCEPTION; } testInfo->server = FRAME_CreateLink(testInfo->config, uioType); if (testInfo->server == NULL) { return HITLS_INTERNAL_EXCEPTION; } ret = FRAME_CreateConnection(testInfo->client, testInfo->server, testInfo->isClient, testInfo->state); if (ret != HITLS_SUCCESS) { return ret; } return HITLS_SUCCESS; } int32_t DefaultCfgStatusPark(HandshakeTestInfo *testInfo, int uioType) { FRAME_Init(); // FRAME_RegCryptMethod(); // stub all crypto functions testInfo->config = HITLS_CFG_NewDTLS12Config(); if (testInfo->config == NULL) { return HITLS_INTERNAL_EXCEPTION; } HITLS_CFG_SetCheckKeyUsage(testInfo->config, false); HITLS_CFG_SetDtlsCookieExchangeSupport(testInfo->config, false); testInfo->config->isSupportExtendMasterSecret = testInfo->isSupportExtendMasterSecret; testInfo->config->isSupportClientVerify = testInfo->isSupportClientVerify; testInfo->config->isSupportNoClientCert = testInfo->isSupportNoClientCert; return StatusPark(testInfo, uioType); } int32_t DefaultCfgStatusParkWithSuite(HandshakeTestInfo *testInfo, int uioType) { FRAME_Init(); testInfo->config = HITLS_CFG_NewDTLS12Config(); if (testInfo->config == NULL) { return HITLS_INTERNAL_EXCEPTION; } HITLS_CFG_SetCheckKeyUsage(testInfo->config, false); uint16_t cipherSuits[] = {HITLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384}; 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, uioType); } int32_t SendHelloReqWithIndex(HITLS_Ctx *ctx, uint8_t index) { uint8_t buf[DTLS_HS_MSG_HEADER_SIZE] = {0u}; buf[5] = index; size_t len = DTLS_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; } uint32_t parseLen = 0; if (ParserTotalRecord(link, &frameMsg, buffer, len, &parseLen) != HITLS_SUCCESS) { return HITLS_INTERNAL_EXCEPTION; } 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; } static int32_t GetDisorderClientFinished(FRAME_LinkObj *client, uint8_t *data, uint32_t len, uint32_t *usedLen) { int32_t ret; uint32_t readLen = 0; uint32_t offset = 0; (void)HITLS_Connect(client->ssl); ret = FRAME_TransportSendMsg(client->io, &data[offset], len - offset, &readLen); if (readLen == 0 || ret != HITLS_SUCCESS) { return HITLS_INTERNAL_EXCEPTION; } offset += readLen; uint8_t tmpData[TEMP_DATA_LEN] = {0}; uint32_t tmpLen = sizeof(tmpData); (void)HITLS_Connect(client->ssl); ret = FRAME_TransportSendMsg(client->io, tmpData, tmpLen, &readLen); if (readLen == 0 || ret != HITLS_SUCCESS) { return HITLS_INTERNAL_EXCEPTION; } tmpLen = readLen; (void)HITLS_Connect(client->ssl); ret = FRAME_TransportSendMsg(client->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; } static int32_t GetDisorderServerFinished(FRAME_LinkObj *server, uint8_t *data, uint32_t len, uint32_t *usedLen) { int32_t ret; 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); 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; } static int32_t AppWrite(HITLS_Ctx *ctx) { int32_t ret; uint8_t writeBuf[] = "GET HTTP 1.0"; uint32_t len = strlen((char *)writeBuf); do { uint32_t writeLen; ret = HITLS_Write(ctx, writeBuf, len, &writeLen); } while (ret == HITLS_REC_NORMAL_RECV_BUF_EMPTY || ret == HITLS_REC_NORMAL_IO_BUSY); return ret; } static int32_t GetDisorderClientFinished_AppData(FRAME_LinkObj *client, uint8_t *data, uint32_t len, uint32_t *usedLen) { int32_t ret; uint32_t readLen = 0; uint32_t offset = 0; uint8_t app[TEMP_DATA_LEN] = {0}; uint32_t appLen = sizeof(app); uint8_t finished[TEMP_DATA_LEN] = {0}; uint32_t finishedLen = sizeof(finished); (void)HITLS_Connect(client->ssl); ret = FRAME_TransportSendMsg(client->io, finished, finishedLen, &readLen); if (readLen == 0 || ret != HITLS_SUCCESS) { return HITLS_INTERNAL_EXCEPTION; } finishedLen = readLen; appLen=finishedLen; if (memcpy_s(app, appLen, finished, finishedLen) != EOK) { return HITLS_INTERNAL_EXCEPTION; } app[0] = 23; if (memcpy_s(&data[offset], len - offset, app, appLen) != EOK) { return HITLS_MEMCPY_FAIL; } offset += appLen; if (memcpy_s(&data[offset], len - offset, finished, finishedLen) != EOK) { return HITLS_MEMCPY_FAIL; } offset += finishedLen; *usedLen = offset; return HITLS_SUCCESS; } static int32_t GetDisorderServerFinish_AppData(FRAME_LinkObj *server, uint8_t *data, uint32_t len, uint32_t *usedLen) { int32_t ret; uint32_t readLen = 0; uint32_t offset = 0; uint8_t ccs[TEMP_DATA_LEN] = {0}; uint32_t ccsLen = sizeof(ccs); (void)HITLS_Accept(server->ssl); ret = FRAME_TransportSendMsg(server->io, ccs, ccsLen, &readLen); if (readLen == 0 || ret != HITLS_SUCCESS) { return HITLS_INTERNAL_EXCEPTION; } ccsLen = readLen; uint8_t finished[TEMP_DATA_LEN] = {0}; uint32_t finishedLen = sizeof(finished); (void)HITLS_Accept(server->ssl); ret = FRAME_TransportSendMsg(server->io, finished, finishedLen, &readLen); if (readLen == 0 || ret != HITLS_SUCCESS) { return HITLS_INTERNAL_EXCEPTION; } finishedLen = readLen; uint8_t app[TEMP_DATA_LEN] = {0}; uint32_t appLen = sizeof(finished); ret = AppWrite(server->ssl); if (ret != HITLS_SUCCESS) { return ret; } ret = FRAME_TransportSendMsg(server->io, app, appLen, &readLen); if (readLen == 0 || ret != HITLS_SUCCESS) { return HITLS_INTERNAL_EXCEPTION; } appLen = readLen; if (memcpy_s(&data[offset], len - offset, ccs, ccsLen) != EOK) { return HITLS_MEMCPY_FAIL; } offset += ccsLen; if (memcpy_s(&data[offset], len - offset, app, appLen) != EOK) { return HITLS_MEMCPY_FAIL; } offset += appLen; if (memcpy_s(&data[offset], len - offset, finished, finishedLen) != EOK) { return HITLS_MEMCPY_FAIL; } offset += finishedLen; *usedLen = offset; return HITLS_SUCCESS; } int32_t DefaultCfgStatusPark1(HandshakeTestInfo *testInfo, int uioType) { FRAME_Init(); testInfo->config = HITLS_CFG_NewDTLS12Config(); 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)); HITLS_CFG_SetClientVerifySupport(testInfo->config, testInfo->isSupportClientVerify); HITLS_CFG_SetNoClientCertSupport(testInfo->config, false); HITLS_CFG_SetExtenedMasterSecretSupport(testInfo->config, true); return StatusPark(testInfo, uioType); } static int32_t GetRepeatsApp(FRAME_LinkObj *obj, uint8_t *data, uint32_t *usedLen) { int32_t ret; uint32_t readLen = 0; uint32_t offset = 0; uint8_t app[TEMP_DATA_LEN] = {0}; uint32_t appLen = sizeof(app); ret = AppWrite(obj->ssl); if (ret != HITLS_SUCCESS) { return ret; } ret = FRAME_TransportSendMsg(obj->io, app, appLen, &readLen); if (readLen == 0 || ret != HITLS_SUCCESS) { return HITLS_INTERNAL_EXCEPTION; } appLen = readLen; if (memcpy_s(&data[offset], TEMP_DATA_LEN, app, appLen) != EOK) { return HITLS_MEMCPY_FAIL; } offset += appLen; if (memcpy_s(&data[offset], TEMP_DATA_LEN - offset, app, appLen) != EOK) { return HITLS_MEMCPY_FAIL; } offset += appLen; *usedLen = offset; return HITLS_SUCCESS; } static int32_t GetDisorderApp(FRAME_LinkObj *obj, uint8_t *data, uint32_t *usedLen) { int32_t ret; uint32_t readLen = 0; uint32_t offset = 0; uint8_t app1[TEMP_DATA_LEN] = {0}; uint32_t app1Len = sizeof(app1); ret = AppWrite(obj->ssl); if (ret != HITLS_SUCCESS) { return ret; } ret = FRAME_TransportSendMsg(obj->io, app1, app1Len, &readLen); if (readLen == 0 || ret != HITLS_SUCCESS) { return HITLS_INTERNAL_EXCEPTION; } app1Len = readLen; uint8_t app2[TEMP_DATA_LEN] = {0}; uint32_t app2Len = sizeof(app2); ret = AppWrite(obj->ssl); if (ret != HITLS_SUCCESS) { return ret; } ret = FRAME_TransportSendMsg(obj->io, app2, app2Len, &readLen); if (readLen == 0 || ret != HITLS_SUCCESS) { return HITLS_INTERNAL_EXCEPTION; } app2Len = readLen; if (memcpy_s(&data[offset], TEMP_DATA_LEN, app2, app2Len) != EOK) { return HITLS_MEMCPY_FAIL; } offset += app2Len; if (memcpy_s(&data[offset], TEMP_DATA_LEN - offset, app1, app1Len) != EOK) { return HITLS_MEMCPY_FAIL; } offset += app1Len; *usedLen = offset; return HITLS_SUCCESS; }
2301_79861745/bench_create
testcode/sdv/testcase/tls/consistency/dtls12/test_suite_sdv_frame_dtls12_consistency.base.c
C
unknown
13,558
/* * This file is part of the openHiTLS project. * * openHiTLS is licensed under the Mulan PSL v2. * You can use this software according to the terms and conditions of the Mulan PSL v2. * You may obtain a copy of Mulan PSL v2 at: * * http://license.coscl.org.cn/MulanPSL2 * * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, * EITHER EXPRESS 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 "hs_cookie.h" /* INCLUDE_BASE test_suite_sdv_frame_dtls12_consistency */ /* END_HEADER */ /* @ * @test UT_TLS_DTLS_CONSISTENCY_RFC5246_UNEXPETED_REORD_TYPE_TC001 * @spec - * @titleThe client and server receive the client Hello message after the connection establishment is complete. * @precon nan * @brief * 1. Use the default configuration items to configure the client and server. Expected result 1. * 2. A DTLS over SCTP connection is established between the client and server. Expected result 2. * 3. Construct a Client Hello message and send it to the client. Check the client status. Expected result 3. * 4. Construct a Client Hello message and send it to the server. Check the server status. Expected result 4. * @expect * 1. The initialization is successful. * 2. The connection is set up successfully. * 3. The client status is CM_STATE_TRANSPORTING. * 4. The server is in the CM_STATE_TRANSPORTING state. * @prior Level 1 * @auto TRUE @ */ /* BEGIN_CASE */ void UT_TLS_DTLS_CONSISTENCY_RFC5246_UNEXPETED_REORD_TYPE_TC001(void) { HandshakeTestInfo testInfo = {0}; FRAME_Msg frameMsg = {0}; FRAME_Type frameType = {0}; testInfo.state = HS_STATE_BUTT; testInfo.isClient = false; testInfo.isSupportExtendMasterSecret = true; ASSERT_TRUE(DefaultCfgStatusParkWithSuite(&testInfo, BSL_UIO_UDP) == HITLS_SUCCESS); frameType.versionType = HITLS_VERSION_DTLS12; frameType.recordType = REC_TYPE_HANDSHAKE; frameType.handshakeType = CLIENT_HELLO; frameType.keyExType = HITLS_KEY_EXCH_ECDHE; frameType.transportType = BSL_UIO_UDP; 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); FrameUioUserData *ioUserData = BSL_UIO_GetUserData(testInfo.server->io); ioUserData->recMsg.len = 0; ASSERT_TRUE(FRAME_TransportRecMsg(testInfo.server->io, sendBuf, sendLen) == HITLS_SUCCESS); uint8_t data[1024] = {0}; uint32_t dataSize = 0; ASSERT_TRUE(testInfo.server->ssl != NULL); HITLS_Read(testInfo.server->ssl, data, sizeof(data), &dataSize); ASSERT_TRUE(testInfo.server->ssl->state == CM_STATE_TRANSPORTING); ASSERT_TRUE(dataSize == 0); ioUserData = BSL_UIO_GetUserData(testInfo.client->io); ioUserData->recMsg.len = 0; ASSERT_TRUE(FRAME_TransportRecMsg(testInfo.client->io, sendBuf, sendLen) == HITLS_SUCCESS); dataSize = 0 ; ASSERT_TRUE(testInfo.client->ssl != NULL); HITLS_Read(testInfo.client->ssl, data, sizeof(data), &dataSize); ASSERT_TRUE(testInfo.client->ssl->state == CM_STATE_TRANSPORTING); ASSERT_TRUE(dataSize == 0); 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_DTLS_CONSISTENCY_RFC5246_SEQ_NUMBER_TC001 * @spec - * @title Check whether the seq number of the record layer complies with the RFC specifications during the handshake. * @precon nan * @brief 1. Use the default configuration items to configure the client and server. Expected result 1. * 2. The client initiates a connection establishment request. When the client sends a CLIENT_HELLO message, the client checks the sequence number at the Reocrd layer. Expected result 2. * @expect 1. The initialization is successful. * 2. The sequence number is 0. * @prior Level 1 * @auto TRUE @ */ /* BEGIN_CASE */ void UT_TLS_DTLS_CONSISTENCY_RFC5246_SEQ_NUMBER_TC001(int uioType) { HandshakeTestInfo testInfo = {0}; FRAME_Msg frameMsg = {0}; FRAME_Type frameType = {0}; testInfo.isSupportExtendMasterSecret = true; testInfo.state = TRY_RECV_CLIENT_HELLO; testInfo.isClient = false; ASSERT_TRUE(DefaultCfgStatusPark(&testInfo, uioType) == 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_DTLS12; frameType.recordType = REC_TYPE_HANDSHAKE; frameType.handshakeType = CLIENT_HELLO; frameType.keyExType = HITLS_KEY_EXCH_ECDHE; frameType.transportType = uioType; ASSERT_TRUE(FRAME_ParseMsg(&frameType, recvBuf, recvLen, &frameMsg, &parseLen) == HITLS_SUCCESS); ASSERT_TRUE(parseLen == recvLen); ASSERT_TRUE(frameMsg.body.hsMsg.sequence.data == 0); 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_DTLS_CONSISTENCY_RFC5246_SEQ_NUMBER_TC002 * @spec - * @title Check whether the sequence number of the record layer during the handshake complies with the RFC specification. * @precon nan * @brief 1. Use the default configuration items to configure the client and server. Expected result 1. * 2. The server continuously establishes a connection. After receiving the client Hello message, the server sends a Server Hello message and checks the sequence number at the Record layer. Expected result 2. * @expect 1. The initialization is successful. * 2. The sequence number is 0. * @prior Level 1 * @auto TRUE @ */ /* BEGIN_CASE */ void UT_TLS_DTLS_CONSISTENCY_RFC5246_SEQ_NUMBER_TC002(int uioType) { RegDefaultMemCallback(); HandshakeTestInfo testInfo = {0}; FRAME_Msg frameMsg = {0}; FRAME_Type frameType = {0}; testInfo.isSupportExtendMasterSecret = true; testInfo.state = TRY_RECV_SERVER_HELLO; testInfo.isClient = true; ASSERT_TRUE(DefaultCfgStatusPark(&testInfo, uioType) == 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_DTLS12; frameType.recordType = REC_TYPE_HANDSHAKE; frameType.handshakeType = SERVER_HELLO; frameType.keyExType = HITLS_KEY_EXCH_ECDHE; frameType.transportType = uioType; ASSERT_TRUE(FRAME_ParseMsg(&frameType, recvBuf, recvLen, &frameMsg, &parseLen) == HITLS_SUCCESS); ASSERT_TRUE(parseLen == recvLen); ASSERT_TRUE(frameMsg.body.hsMsg.sequence.data == 0); 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_DTLS_CONSISTENCY_RFC5246_SEQ_NUMBER_TC003 * @spec - * @title Check whether the sequence number at the record layer complies with the RFC specification during the handshake. * @precon nan * @brief 1. Use the default configuration items to configure the client and server. Expected result 1. * 2. When the client sends a FINISH message during continuous connection establishment, check whether the sequence number in the record header is. Expected result 2. 3. When the server sends a FINISH message during continuous connection establishment, check the sequence number in the message. Expected result 3. * @expect 1. The initialization is successful. * 2. The sequence number is 0. 3. The sequence number is 0. * @prior Level 1 * @auto TRUE @ */ /* BEGIN_CASE */ void UT_TLS_DTLS_CONSISTENCY_RFC5246_SEQ_NUMBER_TC003(int uioType) { RegDefaultMemCallback(); HandshakeTestInfo testInfo = {0}; FRAME_Msg frameMsg = {0}; FRAME_Type frameType = {0}; testInfo.isSupportExtendMasterSecret = true; testInfo.state = TRY_RECV_FINISH; testInfo.isClient = false; ASSERT_EQ(DefaultCfgStatusPark(&testInfo, uioType), 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_DTLS12; frameType.keyExType = HITLS_KEY_EXCH_ECDHE; frameType.transportType = uioType; ASSERT_TRUE(FRAME_ParseMsgHeader(&frameType, recvBuf, recvLen, &frameMsg, &parseLen) == HITLS_SUCCESS); ASSERT_TRUE(parseLen == PARSEMSGHEADER_LEN); ASSERT_TRUE(frameMsg.body.hsMsg.sequence.data == 0); ASSERT_TRUE(FRAME_CreateConnection(testInfo.client, testInfo.server, true, TRY_RECV_FINISH) == HITLS_SUCCESS); FrameUioUserData *ioUserData_1 = BSL_UIO_GetUserData(testInfo.client->io); uint8_t *recvBuf_1 = ioUserData_1->recMsg.msg; uint32_t recvLen_1 = ioUserData_1->recMsg.len; ASSERT_TRUE(recvLen != 0); uint32_t parseLen_1 = 0; FRAME_Msg frameMsg_1 = {0}; FRAME_Type frameType_1 = {0}; frameType_1.versionType = HITLS_VERSION_DTLS12; frameType_1.keyExType = HITLS_KEY_EXCH_ECDHE; frameType_1.transportType = uioType; ASSERT_TRUE(FRAME_ParseMsgHeader(&frameType_1, recvBuf_1, recvLen_1, &frameMsg_1, &parseLen_1) == HITLS_SUCCESS); ASSERT_TRUE(parseLen_1 == PARSEMSGHEADER_LEN); ASSERT_TRUE(frameMsg_1.body.hsMsg.sequence.data == 0); EXIT: FRAME_CleanMsg(&frameType, &frameMsg); FRAME_CleanMsg(&frameType_1, &frameMsg_1); HITLS_CFG_FreeConfig(testInfo.config); FRAME_FreeLink(testInfo.client); FRAME_FreeLink(testInfo.server); FRAME_DeRegCryptMethod(); } /* END_CASE */ /* @ * @test UT_TLS_DTLS_CONSISTENCY_RFC5246_MSGLENGTH_TOOLONG_TC001 * @spec - * @titleThe client sends a Client Certificate 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. * 2. The client initiates a DTLS connection creation request. When the client needs to send a Client Certificate message, the two fields are modified as follows: Certificates Length is 2 ^ 14 + 1 Certificates are changed to 2 ^ 14 + 1 byte buffer. After the modification is complete, send the modification to the server. Expected result 2. 3. When the server receives the Client Certificate message, check the value returned by the HITLS_Accept interface. Expected result 3. * @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_DTLS_CONSISTENCY_RFC5246_MSGLENGTH_TOOLONG_TC001(int uioType) { HandshakeTestInfo testInfo = {0}; testInfo.state = TRY_RECV_CERTIFICATE; testInfo.isSupportExtendMasterSecret = true; testInfo.isClient = false; testInfo.isSupportClientVerify = true; ASSERT_TRUE(DefaultCfgStatusPark(&testInfo, uioType) == 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; FRAME_Msg frameMsg = {0}; FRAME_Type frameType = {0}; frameType.versionType = HITLS_VERSION_DTLS12; frameType.recordType = REC_TYPE_HANDSHAKE; frameType.handshakeType = CERTIFICATE; frameType.keyExType = HITLS_KEY_EXCH_ECDHE; frameType.transportType = uioType; ASSERT_TRUE(FRAME_ParseMsg(&frameType, recvBuf, recvLen, &frameMsg, &parseLen) == HITLS_SUCCESS); 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.certificate.certItem->cert.data); frameMsg.body.hsMsg.body.certificate.certItem->cert.data = certDataTemp; frameMsg.body.hsMsg.body.certificate.certItem->cert.size = BUF_TOOLONG_LEN; frameMsg.body.hsMsg.body.certificate.certItem->cert.state = ASSIGNED_FIELD; frameMsg.body.hsMsg.body.certificate.certItem->certLen.data = BUF_TOOLONG_LEN; frameMsg.body.hsMsg.body.certificate.certItem->certLen.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); 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); ASSERT_EQ(HITLS_Accept(testInfo.server->ssl), HITLS_REC_NORMAL_RECV_BUF_EMPTY); ASSERT_TRUE(testInfo.server->ssl->hsCtx->state == TRY_RECV_CERTIFICATE); 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_DTLS_CONSISTENCY_RFC5246_MSGLENGTH_TOOLONG_TC002 * @spec - * @title The server sends a Server Certificate 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. * 2. The client initiates a DTLS connection creation request. When the server needs to send a Server Certificate message, the server modifies the following two fields: Certificates Length is 2 ^ 14 + 1 Certificates are changed to 2 ^ 14 + 1 byte buffer. After the modification is complete, send the modification to the server. Expected result 2. 3. When the client receives the Server Certificate message, check the value returned by the HITLS_Connect interface. Expected result 3. * @expect 1. The initialization is successful. * 2. The field is successfully modified and sent to the client. 3. The return value of the HITLS_Connect interface is HITLS_REC_NORMAL_RECV_BUF_EMPTY. * @prior Level 1 * @auto TRUE @ */ /* BEGIN_CASE */ void UT_TLS_DTLS_CONSISTENCY_RFC5246_MSGLENGTH_TOOLONG_TC002(int uioType) { HandshakeTestInfo testInfo = {0}; testInfo.state = TRY_RECV_CERTIFICATE; testInfo.isClient = true; testInfo.isSupportExtendMasterSecret = true; testInfo.isSupportClientVerify = true; ASSERT_TRUE(DefaultCfgStatusPark(&testInfo, uioType) == 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_DTLS12; frameType.recordType = REC_TYPE_HANDSHAKE; frameType.handshakeType = CERTIFICATE; frameType.keyExType = HITLS_KEY_EXCH_ECDHE; frameType.transportType = uioType; ASSERT_TRUE(FRAME_ParseMsg(&frameType, recvBuf, recvLen, &frameMsg, &parseLen) == HITLS_SUCCESS); 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.certificate.certItem->cert.data); frameMsg.body.hsMsg.body.certificate.certItem->cert.data = certDataTemp; frameMsg.body.hsMsg.body.certificate.certItem->cert.size = BUF_TOOLONG_LEN; frameMsg.body.hsMsg.body.certificate.certItem->cert.state = ASSIGNED_FIELD; frameMsg.body.hsMsg.body.certificate.certItem->certLen.data = BUF_TOOLONG_LEN; frameMsg.body.hsMsg.body.certificate.certItem->certLen.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); 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); ASSERT_EQ(HITLS_Connect(testInfo.client->ssl), HITLS_REC_NORMAL_RECV_BUF_EMPTY); ASSERT_TRUE(testInfo.client->ssl->hsCtx->state == TRY_RECV_CERTIFICATE); 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_DTLS_CONSISTENCY_RFC5246_MSGLENGTH_TOOLONG_TC003 * @spec - * @titleThe 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. * 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. 3. When the server receives the Change Cipher Spec message, check the value returned by the HITLS_Accept interface. Expected result 3. * @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_DTLS_CONSISTENCY_RFC5246_MSGLENGTH_TOOLONG_TC003(int uioType) { HandshakeTestInfo testInfo = {0}; testInfo.state = TRY_RECV_CLIENT_KEY_EXCHANGE; testInfo.isClient = false; testInfo.isSupportExtendMasterSecret = true; testInfo.isSupportClientVerify = true; ASSERT_TRUE(DefaultCfgStatusPark(&testInfo, uioType) == HITLS_SUCCESS); ASSERT_EQ(HITLS_Accept(testInfo.server->ssl), HITLS_REC_NORMAL_RECV_BUF_EMPTY); FRAME_Msg frameMsg = {0}; FRAME_Type frameType = {0}; frameType.versionType = HITLS_VERSION_DTLS12; frameType.recordType = REC_TYPE_CHANGE_CIPHER_SPEC; frameType.transportType = uioType; ASSERT_TRUE(FRAME_GetDefaultMsg(&frameType, &frameMsg) == HITLS_SUCCESS); 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); ASSERT_EQ(HITLS_Accept(testInfo.server->ssl), HITLS_REC_NORMAL_RECV_BUF_EMPTY); ASSERT_TRUE(testInfo.server->ssl->hsCtx->state == TRY_RECV_CERTIFICATE_VERIFY); bool isCcsRecv = testInfo.server->ssl->method.isRecvCCS(testInfo.server->ssl); ASSERT_TRUE(isCcsRecv == false); 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_DTLS_CONSISTENCY_RFC5246_MSGLENGTH_ZERO_TC001 * @spec - * @title The server receives a Client Hello message with a length of zero. * @precon nan * @brief 1. Use the default configuration items to configure the client and server. Expected result 1. * 2. The client initiates a DTLS over SCTP connection request, constructs a Client Hello message with zero length, and sends the message to the server. Expected result 2. * @expect 1. The initialization is successful. * 2. The server sends the ALERT message. The level is ALERT_ LEVEL_FATAL, and the description is ALERT_DECODE_ERROR. * @prior Level 1 * @auto TRUE @ */ /* BEGIN_CASE */ void UT_TLS_DTLS_CONSISTENCY_RFC5246_MSGLENGTH_ZERO_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(&testInfo, BSL_UIO_UDP) == 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_DTLS12; frameType.recordType = REC_TYPE_HANDSHAKE; frameType.handshakeType = CLIENT_HELLO; frameType.keyExType = HITLS_KEY_EXCH_ECDHE; frameType.transportType = BSL_UIO_UDP; ASSERT_TRUE(FRAME_ParseMsg(&frameType, recvBuf, recvLen, &frameMsg, &parseLen) == HITLS_SUCCESS); FRAME_ClientHelloMsg *clientMsg = &frameMsg.body.hsMsg.body.clientHello; clientMsg->extensionState = MISSING_FIELD; clientMsg->version.state = MISSING_FIELD; clientMsg->randomValue.state = MISSING_FIELD; clientMsg->sessionIdSize.state = MISSING_FIELD; clientMsg->sessionId.state = MISSING_FIELD; clientMsg->cookiedLen.state = MISSING_FIELD; clientMsg->cookie.state = MISSING_FIELD; clientMsg->cipherSuitesSize.state = MISSING_FIELD; clientMsg->cipherSuites.state = MISSING_FIELD; clientMsg->compressionMethodsLen.state = MISSING_FIELD; clientMsg->compressionMethods.state = 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(testInfo.server->io, sendBuf, sendLen) == HITLS_SUCCESS); FRAME_CleanMsg(&frameType, &frameMsg); memset_s(&frameMsg, sizeof(frameMsg), 0, sizeof(frameMsg)); CONN_Deinit(testInfo.server->ssl); ASSERT_TRUE(testInfo.server->ssl != NULL); ASSERT_EQ(HITLS_Accept(testInfo.server->ssl), HITLS_PARSE_INVALID_MSG_LEN); 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_TRUE(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_DTLS_CONSISTENCY_RFC5246_MSGLENGTH_ZERO_TC002 * @spec - * @titleThe client receives a Server Hello message with a length of zero. * @precon nan * @brief 1. Use the default configuration items to configure the client and server. Expected result 1. * 2. The client initiates a DTLS over SCTP connection request. After sending a Client Hello message, the client constructs a zero-length Server Hello message and sends it to the client. Expected result 2. * @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. * @prior Level 1 * @auto TRUE @ */ /* BEGIN_CASE */ void UT_TLS_DTLS_CONSISTENCY_RFC5246_MSGLENGTH_ZERO_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(&testInfo, BSL_UIO_UDP) == 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_DTLS12; frameType.recordType = REC_TYPE_HANDSHAKE; frameType.handshakeType = SERVER_HELLO; frameType.keyExType = HITLS_KEY_EXCH_ECDHE; frameType.transportType = BSL_UIO_UDP; ASSERT_TRUE(FRAME_ParseMsg(&frameType, recvBuf, recvLen, &frameMsg, &parseLen) == HITLS_SUCCESS); FRAME_ServerHelloMsg *serverMsg = &frameMsg.body.hsMsg.body.serverHello; serverMsg->version.state = MISSING_FIELD; serverMsg->randomValue.state = MISSING_FIELD; serverMsg->sessionIdSize.state = MISSING_FIELD; serverMsg->sessionId.state = MISSING_FIELD; serverMsg->cipherSuite.state = MISSING_FIELD; serverMsg->compressionMethod.state = MISSING_FIELD; serverMsg->extensionLen.state = MISSING_FIELD; serverMsg->pointFormats.exState = MISSING_FIELD; serverMsg->extendedMasterSecret.exState = MISSING_FIELD; serverMsg->secRenego.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(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); ASSERT_EQ(HITLS_Connect(testInfo.client->ssl), HITLS_PARSE_INVALID_MSG_LEN); 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_TRUE(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_DTLS_CONSISTENCY_RFC5246_MSGLENGTH_ZERO_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. * 2. The client initiates a DTLS over SCTP connection request. After receiving the Server Hello message, the client constructs a zero-length Certificate message and sends it to the client. Expected result 2. * @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. * @prior Level 1 * @auto TRUE @ */ /* BEGIN_CASE */ void UT_TLS_DTLS_CONSISTENCY_RFC5246_MSGLENGTH_ZERO_TC003(void) { HandshakeTestInfo testInfo = {0}; FRAME_Msg frameMsg = {0}; FRAME_Type frameType = {0}; testInfo.state = TRY_RECV_CERTIFICATE; testInfo.isSupportExtendMasterSecret = true; testInfo.isClient = true; ASSERT_TRUE(DefaultCfgStatusParkWithSuite(&testInfo, BSL_UIO_UDP) == 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_DTLS12; frameType.recordType = REC_TYPE_HANDSHAKE; frameType.handshakeType = CERTIFICATE; frameType.keyExType = HITLS_KEY_EXCH_ECDHE; frameType.transportType = BSL_UIO_UDP; ASSERT_TRUE(FRAME_ParseMsg(&frameType, recvBuf, recvLen, &frameMsg, &parseLen) == HITLS_SUCCESS); FRAME_CertificateMsg *certifiMsg = &frameMsg.body.hsMsg.body.certificate; certifiMsg->certsLen.state = MISSING_FIELD; certifiMsg->certItem->state = 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(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); ASSERT_EQ(HITLS_Connect(testInfo.client->ssl), HITLS_PARSE_INVALID_MSG_LEN); 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_TRUE(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_DTLS_CONSISTENCY_RFC5246_MSGLENGTH_ZERO_TC004 * @spec - * @titleThe client receives a Server Key Exchange message whose length is zero. * @precon nan * @brief 1. Use the default configuration items to configure the client and server. Expected result 1. * 2. The client initiates a DTLS over SCTP connection request. After receiving the Certificate message, the client constructs a Server Key Exchange message with zero length and sends the message to the client. Expected result 2. * @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. * @prior Level 1 * @auto TRUE @ */ /* BEGIN_CASE */ void UT_TLS_DTLS_CONSISTENCY_RFC5246_MSGLENGTH_ZERO_TC004(void) { HandshakeTestInfo testInfo = {0}; FRAME_Msg frameMsg = {0}; FRAME_Type frameType = {0}; testInfo.state = TRY_RECV_SERVER_KEY_EXCHANGE; testInfo.isSupportExtendMasterSecret = true; testInfo.isClient = true; ASSERT_TRUE(DefaultCfgStatusParkWithSuite(&testInfo, BSL_UIO_UDP) == 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_DTLS12; frameType.recordType = REC_TYPE_HANDSHAKE; frameType.handshakeType = SERVER_KEY_EXCHANGE; frameType.keyExType = HITLS_KEY_EXCH_ECDHE; frameType.transportType = BSL_UIO_UDP; ASSERT_TRUE(FRAME_ParseMsg(&frameType, recvBuf, recvLen, &frameMsg, &parseLen) == HITLS_SUCCESS); FRAME_ServerKeyExchangeMsg *serverKeyExMsg = &frameMsg.body.hsMsg.body.serverKeyExchange; serverKeyExMsg->keyEx.ecdh.curveType.state = MISSING_FIELD; serverKeyExMsg->keyEx.ecdh.namedcurve.state = MISSING_FIELD; serverKeyExMsg->keyEx.ecdh.pubKeySize.state = MISSING_FIELD; serverKeyExMsg->keyEx.ecdh.pubKey.state = MISSING_FIELD; serverKeyExMsg->keyEx.ecdh.signAlgorithm.state = MISSING_FIELD; serverKeyExMsg->keyEx.ecdh.signSize.state = MISSING_FIELD; serverKeyExMsg->keyEx.ecdh.signData.state = 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(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); ASSERT_EQ(HITLS_Connect(testInfo.client->ssl), HITLS_PARSE_INVALID_MSG_LEN); 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_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_DTLS_CONSISTENCY_RFC5246_MSGLENGTH_ZERO_TC005 * @spec - * @titleThe server receives a Client Key Exchange message with zero length. * @precon nan * @brief 1. Use the default configuration items to configure the client and server. Expected result 1. * 2. The client initiates a DTLS over SCTP connection request. After the server sends a Server Hello Done message, the server constructs a Client Key Exchange message with zero length and sends the message to the server. Expected result 2. * @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. * @prior Level 1 * @auto TRUE @ */ /* BEGIN_CASE */ void UT_TLS_DTLS_CONSISTENCY_RFC5246_MSGLENGTH_ZERO_TC005(void) { HandshakeTestInfo testInfo = {0}; FRAME_Msg frameMsg = {0}; FRAME_Type frameType = {0}; testInfo.state = TRY_RECV_CLIENT_KEY_EXCHANGE; testInfo.isSupportExtendMasterSecret = true; testInfo.isClient = false; ASSERT_TRUE(DefaultCfgStatusParkWithSuite(&testInfo, BSL_UIO_UDP) == 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_DTLS12; frameType.recordType = REC_TYPE_HANDSHAKE; frameType.handshakeType = CLIENT_KEY_EXCHANGE; frameType.keyExType = HITLS_KEY_EXCH_ECDHE; frameType.transportType = BSL_UIO_UDP; ASSERT_TRUE(FRAME_ParseMsg(&frameType, recvBuf, recvLen, &frameMsg, &parseLen) == HITLS_SUCCESS); FRAME_ClientKeyExchangeMsg *clientKeyExMsg = &frameMsg.body.hsMsg.body.clientKeyExchange; clientKeyExMsg->pubKey.state = MISSING_FIELD; clientKeyExMsg->pubKeySize.state = 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(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); ASSERT_EQ(HITLS_Accept(testInfo.server->ssl), HITLS_PARSE_INVALID_MSG_LEN); 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_TRUE(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_DTLS_CONSISTENCY_RFC5246_MSGLENGTH_ZERO_TC006 * @spec - * @title The server receives a Change Cipher Spec message with zero length. * @precon nan * @brief 1. Use the default configuration items to configure the client and server. Expected result 1. * 2. The client initiates a DTLS over SCTP connection request. After receiving the Client Key Exchange message, the server constructs a Change Cipher Spec message with zero length and sends it to the server. Expected result 2. * @expect 1. The initialization is successful. * 2. The server receives the message, which is HITLS_REC_NORMAL_RECV_BUF_EMPTY. * @prior Level 1 * @auto TRUE @ */ /* BEGIN_CASE */ void UT_TLS_DTLS_CONSISTENCY_RFC5246_MSGLENGTH_ZERO_TC006(void) { HandshakeTestInfo testInfo = {0}; testInfo.state = TRY_RECV_CLIENT_KEY_EXCHANGE; testInfo.isSupportExtendMasterSecret = true; testInfo.isClient = false; ASSERT_TRUE(DefaultCfgStatusParkWithSuite(&testInfo, BSL_UIO_UDP) == HITLS_SUCCESS); ASSERT_TRUE(testInfo.server->ssl != NULL); ASSERT_EQ(HITLS_Accept(testInfo.server->ssl), HITLS_REC_NORMAL_RECV_BUF_EMPTY); FRAME_Msg frameMsg1 = {0}; FRAME_Type frameType1 = {0}; frameType1.versionType = HITLS_VERSION_DTLS12; frameType1.recordType = REC_TYPE_CHANGE_CIPHER_SPEC; frameType1.transportType = BSL_UIO_UDP; ASSERT_TRUE(FRAME_GetDefaultMsg(&frameType1, &frameMsg1) == HITLS_SUCCESS); FRAME_CcsMsg *CcsMidMsg = &frameMsg1.body.ccsMsg; CcsMidMsg->ccsType.state = MISSING_FIELD; CcsMidMsg->extra.state = MISSING_FIELD; uint32_t sendLen = MAX_RECORD_LENTH; uint8_t sendBuf[MAX_RECORD_LENTH] = {0}; ASSERT_TRUE(FRAME_PackMsg(&frameType1, &frameMsg1, sendBuf, sendLen, &sendLen) == HITLS_SUCCESS); FrameUioUserData *ioUserData1 = BSL_UIO_GetUserData(testInfo.server->io); ioUserData1->recMsg.len = 0; ASSERT_TRUE(FRAME_TransportRecMsg(testInfo.server->io, sendBuf, sendLen) == HITLS_SUCCESS); ASSERT_TRUE(testInfo.server->ssl != NULL); ASSERT_EQ(HITLS_Accept(testInfo.server->ssl), HITLS_REC_NORMAL_RECV_BUF_EMPTY); EXIT: FRAME_CleanMsg(&frameType1, &frameMsg1); HITLS_CFG_FreeConfig(testInfo.config); FRAME_FreeLink(testInfo.client); FRAME_FreeLink(testInfo.server); FRAME_DeRegCryptMethod(); } /* END_CASE */ /* @ * @test UT_TLS_DTLS_CONSISTENCY_RFC5246_MSGLENGTH_ZERO_TC007 * @spec - * @titleThe client receives a Change Cipher Spec message with zero length. * @precon nan * @brief 1. Use the default configuration items to configure the client and server. Expected result 1. * 2. The client initiates a DTLS over SCTP connection request. After the client sends a Finish message, it constructs a Change Cipher Spec message with zero length and sends the message to the client. Expected result 2. * @expect 1. The initialization is successful. * 2. The client receives the message, which is HITLS_REC_NORMAL_RECV_BUF_EMPTY. * @prior Level 1 * @auto TRUE @ */ /* BEGIN_CASE */ void UT_TLS_DTLS_CONSISTENCY_RFC5246_MSGLENGTH_ZERO_TC007(void) { HandshakeTestInfo testInfo = {0}; testInfo.state = TRY_SEND_FINISH; testInfo.isSupportExtendMasterSecret = true; testInfo.isClient = true; ASSERT_TRUE(DefaultCfgStatusParkWithSuite(&testInfo, BSL_UIO_UDP) == HITLS_SUCCESS); ASSERT_TRUE(testInfo.server->ssl != NULL); ASSERT_EQ(HITLS_Connect(testInfo.server->ssl), HITLS_REC_NORMAL_RECV_BUF_EMPTY); FRAME_Msg frameMsg1 = {0}; FRAME_Type frameType1 = {0}; frameType1.versionType = HITLS_VERSION_DTLS12; frameType1.recordType = REC_TYPE_CHANGE_CIPHER_SPEC; frameType1.transportType = BSL_UIO_UDP; ASSERT_TRUE(FRAME_GetDefaultMsg(&frameType1, &frameMsg1) == HITLS_SUCCESS); FRAME_CcsMsg *CcsMidMsg = &frameMsg1.body.ccsMsg; CcsMidMsg->ccsType.state = MISSING_FIELD; CcsMidMsg->extra.state = MISSING_FIELD; uint32_t sendLen = MAX_RECORD_LENTH; uint8_t sendBuf[MAX_RECORD_LENTH] = {0}; ASSERT_TRUE(FRAME_PackMsg(&frameType1, &frameMsg1, sendBuf, sendLen, &sendLen) == HITLS_SUCCESS); FrameUioUserData *ioUserData1 = BSL_UIO_GetUserData(testInfo.client->io); ioUserData1->recMsg.len = 0; ASSERT_TRUE(FRAME_TransportRecMsg(testInfo.client->io, sendBuf, sendLen) == HITLS_SUCCESS); ASSERT_TRUE(testInfo.client->ssl != NULL); ASSERT_EQ(HITLS_Connect(testInfo.client->ssl), HITLS_REC_NORMAL_RECV_BUF_EMPTY); EXIT: FRAME_CleanMsg(&frameType1, &frameMsg1); HITLS_CFG_FreeConfig(testInfo.config); FRAME_FreeLink(testInfo.client); FRAME_FreeLink(testInfo.server); FRAME_DeRegCryptMethod(); } /* END_CASE */ /* @ * @test UT_TLS_DTLS_CONSISTENCY_RFC5246_COMPRESSED_TC001 * @spec - * @titleThe server receives a Client Hello message in which the compression field is set to 1. * @precon nan * @brief 1. Use the default configuration items to configure the client and server. Expected result 1. * 2. When the server expects to receive the Client Hello packet, the server constructs the Client Hello packet with the compressed field value being 1. Check the behavior of the server. Expected result 2. * @expect 1. The initialization is successful. * 2. The server sends an ALERT message. The ALERT level is ALERT_LEVEL_FATAL and the description is ALERT_DECODE_ERROR. * @prior Level 1 * @auto TRUE @ */ /* BEGIN_CASE */ void UT_TLS_DTLS_CONSISTENCY_RFC5246_COMPRESSED_TC001(int uioType) { 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(DefaultCfgStatusPark(&testInfo, uioType) == 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_DTLS12; frameType.recordType = REC_TYPE_HANDSHAKE; frameType.handshakeType = CLIENT_HELLO; frameType.keyExType = HITLS_KEY_EXCH_ECDHE; frameType.transportType = uioType; ASSERT_TRUE(FRAME_ParseMsg(&frameType, recvBuf, recvLen, &frameMsg, &parseLen) == HITLS_SUCCESS); FRAME_ClientHelloMsg *clientMsg = &frameMsg.body.hsMsg.body.clientHello; *(clientMsg->compressionMethods.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(testInfo.server->io, sendBuf, sendLen) == HITLS_SUCCESS); FRAME_CleanMsg(&frameType, &frameMsg); memset_s(&frameMsg, sizeof(frameMsg), 0, sizeof(frameMsg)); CONN_Deinit(testInfo.server->ssl); ASSERT_TRUE(testInfo.server->ssl != NULL); ASSERT_EQ(HITLS_Accept(testInfo.server->ssl), HITLS_MSG_HANDLE_INVALID_COMPRESSION_METHOD); 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.handshakeType = SERVER_HELLO; 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_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_DTLS_CONSISTENCY_RFC5246_COMPRESSED_TC002 * @spec - * @titleThe client receives a Server Hello message in which the compressed field value is 1. * @precon nan * @brief 1. Use the default configuration items to configure the client and server. Expected result 1. * 2. After sending the Client Hello packet, the client constructs a Server Hello packet with the compressed field value being 1. Check the behavior of the client. Expected result 2. * @expect 1. The initialization is successful. * 2. The client sends the ALERT message. The ALERT level is ALERT_LEVEL_FATAL and the description is ALERT_ILLEGAL_PARAMETER. * @prior Level 1 * @auto TRUE @ */ /* BEGIN_CASE */ void UT_TLS_DTLS_CONSISTENCY_RFC5246_COMPRESSED_TC002(int uioType) { 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(DefaultCfgStatusPark(&testInfo, uioType) == 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_DTLS12; frameType.recordType = REC_TYPE_HANDSHAKE; frameType.handshakeType = SERVER_HELLO; frameType.keyExType = HITLS_KEY_EXCH_ECDHE; frameType.transportType = uioType; ASSERT_TRUE(FRAME_ParseMsg(&frameType, recvBuf, recvLen, &frameMsg, &parseLen) == HITLS_SUCCESS); FRAME_ServerHelloMsg *serverMsg = &frameMsg.body.hsMsg.body.serverHello; serverMsg->compressionMethod.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(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); ASSERT_EQ(HITLS_Connect(testInfo.client->ssl), HITLS_PARSE_COMPRESSION_METHOD_ERR); 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_ILLEGAL_PARAMETER); 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_DTLS_CONSISTENCY_RFC5246_CIPHER_TC001 * @spec - * @title Check whether the cipher suite selected on the server complies with the RFC. * @precon nan * @brief 1. Use the default configuration items to configure the client and server. Expected result 1. * 2. When the client initiates a DTLS over SCTP connection application, the server modifies the algorithm suite field in the Client Hello packet when the server expects to receive the Client Hello packet, Change the value to 0x00b6, 0x00b7, 0xffff, or 0xc030, and send the modification to the server. Expected result 2. * @expect 1. The initialization is successful. * 2. The server sends the Server Hello message, and the algorithm suite field is 0xc030. * @prior Level 1 * @auto TRUE @ */ /* BEGIN_CASE */ void UT_TLS_DTLS_CONSISTENCY_RFC5246_CIPHER_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(DefaultCfgStatusPark(&testInfo, BSL_UIO_UDP) == 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_DTLS12; frameType.recordType = REC_TYPE_HANDSHAKE; frameType.handshakeType = CLIENT_HELLO; frameType.keyExType = HITLS_KEY_EXCH_ECDHE; frameType.transportType = BSL_UIO_UDP; ASSERT_TRUE(FRAME_ParseMsg(&frameType, recvBuf, recvLen, &frameMsg, &parseLen) == HITLS_SUCCESS); uint16_t suite[] = {0x00B6, 0x00B7, ILLEGAL_VALUE, HITLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384}; FRAME_ClientHelloMsg *clientMsg = &frameMsg.body.hsMsg.body.clientHello; ASSERT_TRUE(FRAME_ModifyMsgArray16(suite, sizeof(suite)/sizeof(uint16_t), &(clientMsg->cipherSuites), &(clientMsg->cipherSuitesSize)) == 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); 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)); CONN_Deinit(testInfo.server->ssl); ASSERT_TRUE(testInfo.server->ssl != NULL); ASSERT_EQ(HITLS_Accept(testInfo.server->ssl), HITLS_REC_NORMAL_IO_BUSY); 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.handshakeType = SERVER_HELLO; ASSERT_TRUE(FRAME_ParseMsg(&frameType, sndBuf, sndLen, &frameMsg, &parseLen) == HITLS_SUCCESS); ASSERT_EQ(frameMsg.body.hsMsg.body.serverHello.cipherSuite.data, HITLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384); 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_DTLS_CONSISTENCY_RFC5246_CIPHER_TC002 * @spec - * @titleHow to handle unexpected cipher suites received by the client? * @precon nan * @brief 1. Use the default configuration items to configure the client and server. Expected result 1. * 2. When the client initiates a DTLS over SCTP connection request, the client constructs a Server Hello packet after sending the Client Hello message, Change the value of the cipher suite field to 0xff and send the modified value to the client. Expected result 2. * @expect 1. The initialization is successful. * 2. The client sends an ALERT message. The ALERT level is ALERT_LEVEL_FATAL and the description is ALERT_ILLEGAL_PARAMETER. * @prior Level 1 * @auto TRUE @ */ /* BEGIN_CASE */ void UT_TLS_DTLS_CONSISTENCY_RFC5246_CIPHER_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(DefaultCfgStatusPark(&testInfo, BSL_UIO_UDP) == 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_DTLS12; frameType.recordType = REC_TYPE_HANDSHAKE; frameType.handshakeType = SERVER_HELLO; frameType.keyExType = HITLS_KEY_EXCH_ECDHE; frameType.transportType = BSL_UIO_UDP; ASSERT_TRUE(FRAME_ParseMsg(&frameType, recvBuf, recvLen, &frameMsg, &parseLen) == HITLS_SUCCESS); FRAME_ServerHelloMsg *serverMsg = &frameMsg.body.hsMsg.body.serverHello; serverMsg->cipherSuite.data = ILLEGAL_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)); CONN_Deinit(testInfo.server->ssl); ASSERT_TRUE(testInfo.client->ssl != NULL); ASSERT_EQ(HITLS_Connect(testInfo.client->ssl), HITLS_MSG_HANDLE_CIPHER_SUITE_ERR); 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_TRUE(alertMsg->alertDescription.data == ALERT_ILLEGAL_PARAMETER); 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_DTLS_CONSISTENCY_RFC5246_SIGNATURE_TC001 * @spec - * @title The server receives a Client Hello packet without the Signature Algorithms field. * @precon nan * @brief 1. Use the default configuration items to configure the client and server. Expected result 1. * 2. When the client initiates a DTLS over SCTP connection request and the server expects to receive the Client Hello packet, Delete the signature field from the Client Hello packet and send the packet to the server after the packet is modified. Expected result 2. * @expect 1. The initialization is successful. * 2. The server sends the Server Hello message. * @prior Level 1 * @auto TRUE @ */ /* BEGIN_CASE */ void UT_TLS_DTLS_CONSISTENCY_RFC5246_SIGNATURE_TC001(void) { HandshakeTestInfo testInfo = {0}; FRAME_Msg frameMsg = {0}; FRAME_Type frameType = {0}; testInfo.state = TRY_RECV_CLIENT_HELLO; testInfo.isClient = false; testInfo.isSupportExtendMasterSecret = true; testInfo.isSupportClientVerify = true; ASSERT_TRUE(DefaultCfgStatusPark(&testInfo, BSL_UIO_UDP) == 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_DTLS12; frameType.recordType = REC_TYPE_HANDSHAKE; frameType.handshakeType = CLIENT_HELLO; frameType.keyExType = HITLS_KEY_EXCH_ECDHE; frameType.transportType = BSL_UIO_UDP; ASSERT_TRUE(FRAME_ParseMsg(&frameType, recvBuf, recvLen, &frameMsg, &parseLen) == HITLS_SUCCESS); ASSERT_TRUE(frameMsg.body.hsMsg.type.data == CLIENT_HELLO); frameMsg.body.hsMsg.body.clientHello.signatureAlgorithms.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 = 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)); CONN_Deinit(testInfo.server->ssl); ASSERT_TRUE(testInfo.server->ssl != NULL); ASSERT_EQ(HITLS_Accept(testInfo.server->ssl), HITLS_REC_NORMAL_IO_BUSY); 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; ASSERT_TRUE(FRAME_ParseMsg(&frameType, sndBuf, sndLen, &frameMsg, &parseLen) == HITLS_SUCCESS); ASSERT_EQ(frameMsg.recType.data, REC_TYPE_HANDSHAKE); ASSERT_EQ(frameMsg.body.hsMsg.type.data, SERVER_HELLO); 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_DTLS_CONSISTENCY_RFC5246_SIGNATURE_TC002 * @spec - * @titleThe client receives the Server Hello packet carrying the Signature Algorithms field. * @precon nan * @brief 1. Use the default configuration items to configure the client and server. Expected result 1. * 2. When the client initiates a DTLS over SCTP connection application, the client constructs a Server Hello packet after sending the Client Hello message, Add the Signature Algorithms field and set its value to 0x0403. Modify the field and send it to the client. Expected result 2. * @expect 1. The initialization is successful. * 2. The client sends the ALERT message. The ALERT level is ALERT_LEVEL_FATAL and the description is ALERT_UNSUPPORTED_EXTENSION. * @prior Level 1 * @auto TRUE @ */ /* BEGIN_CASE */ void UT_TLS_DTLS_CONSISTENCY_RFC5246_SIGNATURE_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(DefaultCfgStatusPark(&testInfo, BSL_UIO_UDP) == 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_DTLS12; frameType.recordType = REC_TYPE_HANDSHAKE; frameType.handshakeType = SERVER_HELLO; frameType.keyExType = HITLS_KEY_EXCH_ECDHE; frameType.transportType = BSL_UIO_UDP; ASSERT_TRUE(FRAME_ParseMsg(&frameType, recvBuf, recvLen, &frameMsg, &parseLen) == HITLS_SUCCESS); FRAME_ServerHelloMsg *serverMsg = &frameMsg.body.hsMsg.body.serverHello; serverMsg->secRenego.exState = INITIAL_FIELD; ASSERT_TRUE(FRAME_ModifyMsgInteger(HS_EX_TYPE_SIGNATURE_ALGORITHMS, &(serverMsg->secRenego.exType)) == HITLS_SUCCESS); serverMsg->secRenego.exLen.state = INITIAL_FIELD; uint8_t Signature[] = {SIGNATURE_ALGORITHMS}; ASSERT_TRUE(FRAME_ModifyMsgArray8(Signature, sizeof(Signature), &(serverMsg->secRenego.exData), &(serverMsg->secRenego.exDataLen)) == 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); 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); ASSERT_EQ(HITLS_Connect(testInfo.client->ssl), HITLS_PARSE_UNSUPPORTED_EXTENSION); 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_UNSUPPORTED_EXTENSION); 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_DTLS_CONSISTENCY_RFC5246_SIGNATURE_TC003 * @spec - * @titleThe server receives a client Hello message with abnormal signature hash fields. * @precon nan * @brief 1. Use the default configuration items to configure the client and server. Expected result 1. * 2. The client initiates a connection request, constructs an abnormal Client Hello packet, that is, the signature hash field is not in pairs, and sends the packet to the server. * @expect 1. The initialization is successful. * 2. After the server receives the Client Hello message, the HiTLS_ACCEPT interface returns a failure message and the server sends an ALERT message. The ALERT level is ALERT_ LEVEL_FATAL and the description is ALERT_DECODE_ERROR. * @prior Level 1 * @auto TRUE @ */ /* BEGIN_CASE */ void UT_TLS_DTLS_CONSISTENCY_RFC5246_SIGNATURE_TC003(int uioType) { 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(DefaultCfgStatusPark(&testInfo, uioType) == 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_DTLS12; frameType.recordType = REC_TYPE_HANDSHAKE; frameType.handshakeType = CLIENT_HELLO; frameType.keyExType = HITLS_KEY_EXCH_ECDHE; frameType.transportType = uioType; ASSERT_TRUE(FRAME_ParseMsg(&frameType, recvBuf, recvLen, &frameMsg, &parseLen) == HITLS_SUCCESS); FRAME_ClientHelloMsg *clientMsg = &frameMsg.body.hsMsg.body.clientHello; clientMsg->signatureAlgorithms.exDataLen.data = HASH_EXDATA_LEN_ERROR ; 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)); CONN_Deinit(testInfo.server->ssl); ASSERT_TRUE(testInfo.server->ssl != NULL); ASSERT_EQ(HITLS_Accept(testInfo.server->ssl), HITLS_PARSE_INVALID_MSG_LEN); 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.handshakeType = SERVER_HELLO; 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_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_DTLS_CONSISTENCY_RFC5246_SIGNATURE_TC004 * @spec - * @title The server receives the Client Hello packet carrying the Signature Algorithms field. * @precon nan * @brief 1. Use the default configuration items to configure the client and server. Expected result 1. * 2. When the client initiates a DTLS over SCTP connection request, after the client sends the Client Hello message, Modify the signature algorithm field by adding an invalid field value and observe the client behavior. Expected result 2. * @expect 1. The initialization is successful. * 2. The server sends the ALERT message. The ALERT level is ALERT_LEVEL_FATAL and the description is ALERT_HANDSHAKE_FAILURE. * @prior Level 1 * @auto TRUE @ */ /* BEGIN_CASE */ void UT_TLS_DTLS_CONSISTENCY_RFC5246_SIGNATURE_TC004(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(DefaultCfgStatusPark(&testInfo, BSL_UIO_UDP) == 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_DTLS12; frameType.recordType = REC_TYPE_HANDSHAKE; frameType.handshakeType = CLIENT_HELLO; frameType.keyExType = HITLS_KEY_EXCH_ECDHE; frameType.transportType = BSL_UIO_UDP; ASSERT_TRUE(FRAME_ParseMsg(&frameType, recvBuf, recvLen, &frameMsg, &parseLen) == HITLS_SUCCESS); FRAME_ClientHelloMsg *clientMsg = &frameMsg.body.hsMsg.body.clientHello; uint16_t Signature[] = {ILLEGAL_VALUE}; ASSERT_TRUE(FRAME_ModifyMsgArray16(Signature, sizeof(Signature)/sizeof(uint16_t), &(clientMsg->signatureAlgorithms.exData), &(clientMsg->signatureAlgorithms.exDataLen)) == 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); 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)); CONN_Deinit(testInfo.server->ssl); ASSERT_TRUE(testInfo.server->ssl != NULL); ASSERT_EQ(HITLS_Accept(testInfo.server->ssl), HITLS_MSG_HANDLE_CIPHER_SUITE_ERR); 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_TRUE(alertMsg->alertDescription.data == ALERT_HANDSHAKE_FAILURE); 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_DTLS_CONSISTENCY_RFC5246_SIGNATURE_TC005 * @spec - * @titleThe client receives the Server Hello packet carrying the Signature Algorithms field. * @precon nan * @brief 1. Use the default configuration items to configure the client and server. Expected result 1. * 2. When the client initiates a DTLS over SCTP connection application, the client constructs a Server Hello packet after sending the Client Hello message, Modify the signature algorithm field by adding an invalid field value and observe the client behavior. Expected result 2. * @expect 1. The initialization is successful. * 2. The client sends the ALERT message. The ALERT level is ALERT_LEVEL_FATAL and the description is ALERT_UNSUPPORTED_EXTENSION. * @prior Level 1 * @auto TRUE @ */ /* BEGIN_CASE */ void UT_TLS_DTLS_CONSISTENCY_RFC5246_SIGNATURE_TC005(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(DefaultCfgStatusPark(&testInfo, BSL_UIO_UDP) == 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_DTLS12; frameType.recordType = REC_TYPE_HANDSHAKE; frameType.handshakeType = SERVER_HELLO; frameType.keyExType = HITLS_KEY_EXCH_ECDHE; frameType.transportType = BSL_UIO_UDP; ASSERT_TRUE(FRAME_ParseMsg(&frameType, recvBuf, recvLen, &frameMsg, &parseLen) == HITLS_SUCCESS); FRAME_ServerHelloMsg *serverMsg = &frameMsg.body.hsMsg.body.serverHello; serverMsg->secRenego.exState = INITIAL_FIELD; ASSERT_TRUE(FRAME_ModifyMsgInteger(HS_EX_TYPE_SIGNATURE_ALGORITHMS, &(serverMsg->secRenego.exType)) == HITLS_SUCCESS); serverMsg->secRenego.exLen.state = INITIAL_FIELD; uint8_t Signature[] = {ILLEGAL_VALUE}; ASSERT_TRUE(FRAME_ModifyMsgArray8(Signature, sizeof(Signature), &(serverMsg->secRenego.exData), &(serverMsg->secRenego.exDataLen)) == 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); 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); ASSERT_EQ(HITLS_Connect(testInfo.client->ssl), HITLS_PARSE_UNSUPPORTED_EXTENSION); 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_UNSUPPORTED_EXTENSION); 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_DTLS_CONSISTENCY_RFC5246_SIGNATURE_TC007 * @spec - * @titleThe client sends a Client Hello message in which the signature field is removed. * @precon nan * @brief 1. Use the default initialization mode on the client and server. Expected result 1. * 2. The client initiates a connection establishment request, deletes the signature field in the client Hello message, and sends the message to the server. Expected result 2. * @expect 1. The initialization is successful. * 2. The server continues to establish a connection. The connection is successfully established. * @prior Level 1 * @auto TRUE @ */ /* BEGIN_CASE */ void UT_TLS_DTLS_CONSISTENCY_RFC5246_SIGNATURE_TC007(int uioType) { 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(DefaultCfgStatusPark(&testInfo, uioType) == 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_DTLS12; frameType.recordType = REC_TYPE_HANDSHAKE; frameType.handshakeType = CLIENT_HELLO; frameType.keyExType = HITLS_KEY_EXCH_ECDHE; frameType.transportType = uioType; ASSERT_TRUE(FRAME_ParseMsg(&frameType, recvBuf, recvLen, &frameMsg, &parseLen) == HITLS_SUCCESS); FRAME_ClientHelloMsg *clientMsg = &frameMsg.body.hsMsg.body.clientHello; clientMsg->signatureAlgorithms.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(testInfo.server->io, sendBuf, sendLen) == HITLS_SUCCESS); FRAME_CleanMsg(&frameType, &frameMsg); memset_s(&frameMsg, sizeof(frameMsg), 0, sizeof(frameMsg)); CONN_Deinit(testInfo.server->ssl); ASSERT_TRUE(testInfo.server->ssl != NULL); ASSERT_EQ(HITLS_Accept(testInfo.server->ssl), HITLS_REC_NORMAL_IO_BUSY); 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.handshakeType = SERVER_HELLO; ASSERT_TRUE(FRAME_ParseMsg(&frameType, sndBuf, sndLen, &frameMsg, &parseLen) == HITLS_SUCCESS); ASSERT_TRUE(frameMsg.recType.data == REC_TYPE_HANDSHAKE); 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_DTLS_CONSISTENCY_RFC5246_CERTIFICATE_TC003 * @spec - * @title The server receives an unexpected Client Certificate message. * @precon nan * @brief 1. Use the default configuration items to configure the client and server. Expected result 1. * 2. The client initiates a DTLS connection application. After sending the Server Hello Done message, the server constructs a Client Certificate message and sends it to the server. Expected result 2. * @expect 1. The initialization is successful. * 2. The server sends the ALERT message. The ALERT level is ALERT_ LEVEL_FATAL and the description is ALERT_UNEXPECTED_MESSAGE. * @prior Level 1 * @auto TRUE @ */ /* BEGIN_CASE */ void UT_TLS_DTLS_CONSISTENCY_RFC5246_CERTIFICATE_TC003(int uioType) { HandshakeTestInfo testInfo = {0}; FRAME_Msg frameMsg = {0}; FRAME_Type frameType = {0}; testInfo.state = TRY_RECV_CLIENT_KEY_EXCHANGE; testInfo.isClient = false; testInfo.isSupportExtendMasterSecret = true; testInfo.isSupportClientVerify = false; ASSERT_TRUE(DefaultCfgStatusPark(&testInfo, uioType) == HITLS_SUCCESS); frameType.versionType = HITLS_VERSION_DTLS12; frameType.recordType = REC_TYPE_HANDSHAKE; frameType.handshakeType = CERTIFICATE; frameType.keyExType = HITLS_KEY_EXCH_ECDHE; frameType.transportType = uioType; 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); 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); ASSERT_EQ(HITLS_Accept(testInfo.server->ssl), HITLS_MSG_HANDLE_UNEXPECTED_MESSAGE); 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; 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_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); FRAME_DeRegCryptMethod(); } /* END_CASE */ /* @ * @test UT_TLS_DTLS_CONSISTENCY_RFC5246_VERSION_TC001 * @spec - * @titleThe server receives the client hello message of DTLS1.0. * @precon nan * @brief 1. Retain the default configuration on the client and server, and enable peer verification on the server. Expected result 1. * 2. When the server is in the TRY_RECV_CLIENT_HELLO state, change the negotiated version number field in the client hello message to DTLS1.0. Then, check the server behavior. * @expect 1. The initialization is successful. * 2. The server sends a FATAL ALERT, and the description of the ALERT is ALERT_PROTOCOL_VERSION. * @prior Level 1 * @auto TRUE @ */ /* BEGIN_CASE */ void UT_TLS_DTLS_CONSISTENCY_RFC5246_VERSION_TC001(int uioType) { 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(DefaultCfgStatusPark(&testInfo, uioType) == 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_DTLS12; frameType.recordType = REC_TYPE_HANDSHAKE; frameType.handshakeType = CLIENT_HELLO; frameType.keyExType = HITLS_KEY_EXCH_ECDHE; frameType.transportType = uioType; ASSERT_TRUE(FRAME_ParseMsg(&frameType, recvBuf, recvLen, &frameMsg, &parseLen) == HITLS_SUCCESS); FRAME_ClientHelloMsg *clientMsg = &frameMsg.body.hsMsg.body.clientHello; clientMsg->version.data = HITLS_VERSION_DTLS10; clientMsg->version.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); 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)); CONN_Deinit(testInfo.server->ssl); ASSERT_TRUE(testInfo.server->ssl != NULL); ASSERT_EQ(HITLS_Accept(testInfo.server->ssl), HITLS_MSG_HANDLE_UNSUPPORT_VERSION); 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.handshakeType = SERVER_HELLO; 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_PROTOCOL_VERSION); 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_DTLS_CONSISTENCY_RFC5246_HELLO_REQUEST_TC001 * @spec - * @titleThe client receives a Hello Request message during startup. * @precon nan * @brief 1. Use the default configuration on the client and server, and enable peer verification on the server. Expected result 1. * 2. When the client starts, the client receives a Hello Request message. Expected result 2. 3. Continue to complete connection establishment and send and receive messages. (Expected result 3) * @expect 1. The initialization is successful. * 2. The client can process the packet normally. 3. The message is sent and received successfully. * @prior Level 1 * @auto TRUE @ */ /* BEGIN_CASE */ void UT_TLS_DTLS_CONSISTENCY_RFC5246_HELLO_REQUEST_TC001(int uioType) { HandshakeTestInfo testInfo = {0}; testInfo.state = TLS_IDLE; testInfo.isSupportExtendMasterSecret = true; testInfo.isClient = true; FRAME_Init(); testInfo.config = HITLS_CFG_NewDTLS12Config(); ASSERT_TRUE(testInfo.config != NULL); uint16_t cipherSuits[] = {HITLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384}; 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; testInfo.client = FRAME_CreateLink(testInfo.config, uioType); ASSERT_TRUE(testInfo.client != NULL); testInfo.server = FRAME_CreateLink(testInfo.config, uioType); ASSERT_TRUE(testInfo.server != NULL); ASSERT_EQ(HITLS_Accept(testInfo.server->ssl), HITLS_REC_NORMAL_RECV_BUF_EMPTY); ASSERT_TRUE(SendHelloReqWithIndex(testInfo.server->ssl, 0) == HITLS_SUCCESS); testInfo.server->ssl->hsCtx->nextSendSeq++; ASSERT_TRUE(FRAME_TrasferMsgBetweenLink(testInfo.server, testInfo.client) == HITLS_SUCCESS); ASSERT_TRUE(testInfo.client->ssl != NULL); ASSERT_EQ(HITLS_Connect(testInfo.client->ssl), HITLS_REC_NORMAL_RECV_BUF_EMPTY); ASSERT_EQ(FRAME_CreateConnection(testInfo.client, testInfo.server, true, HS_STATE_BUTT), HITLS_SUCCESS); HITLS_Ctx *clientTlsCtx = FRAME_GetTlsCtx(testInfo.client); ASSERT_EQ(clientTlsCtx->state, CM_STATE_TRANSPORTING); uint8_t writeData[] = {"abcd1234"}; uint32_t writeLen = strlen("abcd1234"); uint8_t readData[MAX_RECORD_LENTH] = {0}; uint32_t readLen = MAX_RECORD_LENTH; uint32_t sendNum; ASSERT_EQ(HITLS_Write(testInfo.server->ssl, writeData, writeLen, &sendNum), HITLS_SUCCESS); ASSERT_EQ(FRAME_TrasferMsgBetweenLink(testInfo.server, testInfo.client), HITLS_SUCCESS); ASSERT_EQ(HITLS_Read(testInfo.client->ssl, readData, MAX_RECORD_LENTH, &readLen), HITLS_SUCCESS); ASSERT_EQ(readLen, writeLen); ASSERT_EQ(memcmp(writeData, readData, readLen), 0); EXIT: HITLS_CFG_FreeConfig(testInfo.config); FRAME_FreeLink(testInfo.client); FRAME_FreeLink(testInfo.server); } /* END_CASE */ /* @ * @test UT_TLS_DTLS_CONSISTENCY_RFC5246_HELLO_REQUEST_TC002 * @spec - * @titleThe client receives a Hello Request message after sending a Client Hello message. * @precon nan * @brief 1. Use the default configuration items to configure the client and server. Expected result 11. * 2. After the client sends a Client Hello message, the client receives a Hello Request message. Expected result 2. 3. Continue to establish a connection and send and receive messages. (Expected result 3) * @expect 1. The initialization is successful. * 2. The client can process the packet normally. 3. The message is sent and received successfully. * @prior Level 1 * @auto TRUE @ */ /* BEGIN_CASE */ void UT_TLS_DTLS_CONSISTENCY_RFC5246_HELLO_REQUEST_TC002(int uioType) { HandshakeTestInfo testInfo = {0}; testInfo.state = TRY_SEND_CLIENT_HELLO; testInfo.isSupportExtendMasterSecret = true; testInfo.isClient = true; ASSERT_TRUE(DefaultCfgStatusParkWithSuite(&testInfo, uioType) == HITLS_SUCCESS); CONN_Deinit(testInfo.client->ssl); ASSERT_TRUE(testInfo.client->ssl != NULL); ASSERT_EQ(HITLS_Connect(testInfo.client->ssl), HITLS_REC_NORMAL_RECV_BUF_EMPTY); ASSERT_TRUE(FRAME_TrasferMsgBetweenLink(testInfo.client, testInfo.server) == HITLS_SUCCESS); ASSERT_TRUE(SendHelloReqWithIndex(testInfo.server->ssl, 0) == HITLS_SUCCESS); ASSERT_TRUE(FRAME_TrasferMsgBetweenLink(testInfo.server, testInfo.client) == HITLS_SUCCESS); ASSERT_TRUE(testInfo.client->ssl != NULL); ASSERT_EQ(HITLS_Connect(testInfo.client->ssl), HITLS_REC_NORMAL_RECV_BUF_EMPTY); HITLS_Ctx *clientTlsCtx = FRAME_GetTlsCtx(testInfo.client); ASSERT_EQ(clientTlsCtx->state, CM_STATE_HANDSHAKING); ASSERT_EQ(clientTlsCtx->hsCtx->state, TRY_RECV_SERVER_HELLO); EXIT: HITLS_CFG_FreeConfig(testInfo.config); FRAME_FreeLink(testInfo.client); FRAME_FreeLink(testInfo.server); FRAME_DeRegCryptMethod(); } /* END_CASE */ /* @ * @test UT_TLS_DTLS_CONSISTENCY_RFC5246_HELLO_REQUEST_TC003 * @spec - * @titleThe server receives a Hello Request message after sending a Server Hello Done message. * @precon nan * @brief 1. Use the default configuration items to configure the client and server. Expected result 11. * 2. After sending a Server Hello Done message, the server receives a Hello Request message. Expected result 2. * @expect 1. The initialization is successful. * 2. The server sends an ALERT message with the description of ALERT_UNEXPECTED_MESSAGE. * @prior Level 1 * @auto TRUE @ */ /* BEGIN_CASE */ void UT_TLS_DTLS_CONSISTENCY_RFC5246_HELLO_REQUEST_TC003(int uioType) { HandshakeTestInfo testInfo = {0}; FRAME_Msg frameMsg = {0}; FRAME_Type frameType = {0}; testInfo.state = TRY_SEND_SERVER_HELLO_DONE; testInfo.isSupportExtendMasterSecret = true; testInfo.isClient = false; ASSERT_TRUE(DefaultCfgStatusParkWithSuite(&testInfo, uioType) == HITLS_SUCCESS); ASSERT_TRUE(testInfo.server->ssl != NULL); ASSERT_EQ(HITLS_Accept(testInfo.server->ssl), HITLS_REC_NORMAL_RECV_BUF_EMPTY); ASSERT_TRUE(FRAME_TrasferMsgBetweenLink(testInfo.server, testInfo.client) == HITLS_SUCCESS); ASSERT_TRUE(SendHelloReqWithIndex(testInfo.client->ssl, 1) == HITLS_SUCCESS); ASSERT_TRUE(FRAME_TrasferMsgBetweenLink(testInfo.client, testInfo.server) == HITLS_SUCCESS); ASSERT_TRUE(testInfo.server->ssl != NULL); ASSERT_EQ(HITLS_Accept(testInfo.server->ssl), HITLS_MSG_HANDLE_UNEXPECTED_MESSAGE); FrameUioUserData *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; frameType.versionType = HITLS_VERSION_DTLS12; frameType.recordType = REC_TYPE_ALERT; frameType.transportType = uioType; 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_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); FRAME_DeRegCryptMethod(); } /* END_CASE */ /* @ * @test UT_TLS_DTLS_CONSISTENCY_RFC5246_HELLO_REQUEST_TC004 * @spec - * @titleThe client receives a Hello Request message after sending a FINISH message. * @precon nan * @brief 1. Use the default configuration items to configure the client and server. Expected result 11. * 2. After the client sends a FINISH message, the client receives a Hello Request message. Expected result 2. * @expect 1. The initialization is successful. * 2. The client can process the packet normally. * @prior Level 1 * @auto TRUE @ */ /* BEGIN_CASE */ void UT_TLS_DTLS_CONSISTENCY_RFC5246_HELLO_REQUEST_TC004(int uioType) { HandshakeTestInfo testInfo = {0}; testInfo.state = TRY_SEND_FINISH; testInfo.isSupportExtendMasterSecret = true; testInfo.isClient = true; ASSERT_TRUE(DefaultCfgStatusParkWithSuite(&testInfo, uioType) == HITLS_SUCCESS); ASSERT_TRUE(testInfo.client->ssl != NULL); ASSERT_EQ(HITLS_Connect(testInfo.client->ssl), HITLS_REC_NORMAL_RECV_BUF_EMPTY); ASSERT_TRUE(FRAME_TrasferMsgBetweenLink(testInfo.client, testInfo.server) == HITLS_SUCCESS); ASSERT_TRUE(SendHelloReqWithIndex(testInfo.server->ssl, 4) == HITLS_SUCCESS); ASSERT_TRUE(FRAME_TrasferMsgBetweenLink(testInfo.server, testInfo.client) == HITLS_SUCCESS); ASSERT_TRUE(testInfo.client->ssl != NULL); ASSERT_EQ(HITLS_Connect(testInfo.client->ssl), HITLS_REC_NORMAL_RECV_BUF_EMPTY); HITLS_Ctx *clientTlsCtx = FRAME_GetTlsCtx(testInfo.client); ASSERT_EQ(clientTlsCtx->state, CM_STATE_HANDSHAKING); ASSERT_EQ(clientTlsCtx->hsCtx->state, TRY_RECV_NEW_SESSION_TICKET); EXIT: HITLS_CFG_FreeConfig(testInfo.config); FRAME_FreeLink(testInfo.client); FRAME_FreeLink(testInfo.server); FRAME_DeRegCryptMethod(); } /* END_CASE */ /* @ * @test UT_TLS_DTLS_CONSISTENCY_RFC5246_HELLO_REQUEST_TC005 * @spec - * @titleThe server receives a Hello Request message after sending a FINISH message. * @precon nan * @brief 1. Use the default configuration items to configure the client and server. Expected result 11. * 2. After the server sends a FINISH message, the server receives a Hello Request message. Expected result 2. * @expect 1. The initialization is successful. * 2. The server can process the packet normally. * @prior Level 1 * @auto TRUE @ */ /* BEGIN_CASE */ void UT_TLS_DTLS_CONSISTENCY_RFC5246_HELLO_REQUEST_TC005(int uioType) { HandshakeTestInfo testInfo = {0}; testInfo.state = TRY_SEND_FINISH; testInfo.isSupportExtendMasterSecret = true; testInfo.isClient = false; ASSERT_TRUE(DefaultCfgStatusParkWithSuite(&testInfo, uioType) == HITLS_SUCCESS); ASSERT_TRUE(testInfo.server->ssl != NULL); ASSERT_EQ(HITLS_Accept(testInfo.server->ssl), HITLS_SUCCESS); ASSERT_TRUE(FRAME_TrasferMsgBetweenLink(testInfo.server, testInfo.client) == HITLS_SUCCESS); ASSERT_TRUE(testInfo.client->ssl != NULL); ASSERT_EQ(HITLS_Connect(testInfo.client->ssl), HITLS_SUCCESS); ASSERT_TRUE(SendHelloReqWithIndex(testInfo.client->ssl, 1) == HITLS_SUCCESS); ASSERT_TRUE(FRAME_TrasferMsgBetweenLink(testInfo.client, testInfo.server) == HITLS_SUCCESS); ASSERT_TRUE(testInfo.server->ssl != NULL); ASSERT_EQ(HITLS_Accept(testInfo.server->ssl), HITLS_SUCCESS); uint8_t readBuf[READ_BUF_SIZE] = {0}; uint32_t readLen = 0; ASSERT_EQ(HITLS_Read(testInfo.server->ssl, readBuf, READ_BUF_SIZE, &readLen), HITLS_MSG_HANDLE_UNEXPECTED_MESSAGE); HITLS_Ctx *serverTlsCtx = FRAME_GetTlsCtx(testInfo.server); ASSERT_EQ(serverTlsCtx->state, CM_STATE_ALERTED); EXIT: HITLS_CFG_FreeConfig(testInfo.config); FRAME_FreeLink(testInfo.client); FRAME_FreeLink(testInfo.server); FRAME_DeRegCryptMethod(); } /* END_CASE */ /* @ * @test UT_TLS_DTLS_CONSISTENCY_RFC5246_HELLO_REQUEST_TC006 * @spec - * @titleThe client receives the Hello Request message after the connection establishment is complete. * @precon nan * @brief 1. Use the default configuration items to configure the client and server. Expected result 11. * 2. After the connection is established on the client, the client receives a Hello Request message. Expected result 2. 3. The server writes a message and the client receives the message. (Expected result 3) * @expect 1. The initialization is successful. * 2. The server can process the packet normally. 3. The client receives the message correctly. * @prior Level 1 * @auto TRUE @ */ /* BEGIN_CASE */ void UT_TLS_DTLS_CONSISTENCY_RFC5246_HELLO_REQUEST_TC006(int uioType) { HandshakeTestInfo testInfo = {0}; testInfo.state = HS_STATE_BUTT; testInfo.isSupportExtendMasterSecret = true; testInfo.isClient = true; ASSERT_TRUE(DefaultCfgStatusParkWithSuite(&testInfo, uioType) == HITLS_SUCCESS); ASSERT_TRUE(SendHelloReqWithIndex(testInfo.server->ssl, 1) == HITLS_SUCCESS); ASSERT_TRUE(FRAME_TrasferMsgBetweenLink(testInfo.server, testInfo.client) == HITLS_SUCCESS); 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_NORMAL_RECV_BUF_EMPTY); uint8_t writeData[] = {"abcd1234"}; uint32_t writeLen = strlen("abcd1234"); uint8_t readData[MAX_RECORD_LENTH] = {0}; readLen = MAX_RECORD_LENTH; uint32_t sendNum; ASSERT_EQ(HITLS_Write(testInfo.server->ssl, writeData, writeLen, &sendNum), HITLS_SUCCESS); ASSERT_EQ(FRAME_TrasferMsgBetweenLink(testInfo.server, testInfo.client), HITLS_SUCCESS); ASSERT_EQ(HITLS_Read(testInfo.client->ssl, readData, MAX_RECORD_LENTH, &readLen), HITLS_SUCCESS); ASSERT_EQ(readLen, writeLen); ASSERT_EQ(memcmp(writeData, readData, readLen), 0); EXIT: HITLS_CFG_FreeConfig(testInfo.config); FRAME_FreeLink(testInfo.client); FRAME_FreeLink(testInfo.server); FRAME_DeRegCryptMethod(); } /* END_CASE */ /* @ * @test UT_TLS_DTLS_CONSISTENCY_RFC5246_HELLO_REQUEST_TC007 * @spec - * @titleThe server receives a Hello Request message during startup. * @precon nan * @brief 1. Use the default configuration items to configure the client and server. Expected result 1. * 2. When the server starts, the Hello Request message is received. Expected result 2. * @expect 1. The initialization is successful. * 2. The server sends an ALERT. The description is ALERT_UNEXPECTED_MESSAGE. * @prior Level 1 * @auto TRUE @ */ /* BEGIN_CASE */ void UT_TLS_DTLS_CONSISTENCY_RFC5246_HELLO_REQUEST_TC007(int uioType) { HandshakeTestInfo testInfo = {0}; FRAME_Msg frameMsg = {0}; FRAME_Type frameType = {0}; testInfo.state = TLS_IDLE; testInfo.isSupportExtendMasterSecret = true; testInfo.isClient = false; HandshakeTestInfo testInfo1 = {0}; testInfo1.state = TLS_IDLE; FRAME_Init(); testInfo.config = HITLS_CFG_NewDTLS12Config(); ASSERT_TRUE(testInfo.config != NULL); uint16_t cipherSuits[] = {HITLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384}; 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; testInfo.client = FRAME_CreateLink(testInfo.config, uioType); ASSERT_TRUE(testInfo.client != NULL); testInfo.server = FRAME_CreateLink(testInfo.config, uioType); ASSERT_TRUE(testInfo.server != NULL); testInfo1.server = FRAME_CreateLink(testInfo.config, uioType); ASSERT_TRUE(testInfo1.server != NULL); ASSERT_EQ(HITLS_Connect(testInfo.client->ssl), HITLS_REC_NORMAL_RECV_BUF_EMPTY); ASSERT_TRUE(FRAME_TrasferMsgBetweenLink(testInfo.client, testInfo1.server) == HITLS_SUCCESS); ASSERT_TRUE(SendHelloReqWithIndex(testInfo.client->ssl, 0) == HITLS_SUCCESS); ASSERT_TRUE(FRAME_TrasferMsgBetweenLink(testInfo.client, testInfo.server) == HITLS_SUCCESS); ASSERT_TRUE(testInfo.server->ssl != NULL); ASSERT_EQ(HITLS_Accept(testInfo.server->ssl), HITLS_MSG_HANDLE_UNEXPECTED_MESSAGE); ASSERT_TRUE(testInfo.server->ssl->state == CM_STATE_ALERTED); EXIT: FRAME_CleanMsg(&frameType, &frameMsg); HITLS_CFG_FreeConfig(testInfo.config); FRAME_FreeLink(testInfo.client); FRAME_FreeLink(testInfo.server); HITLS_CFG_FreeConfig(testInfo1.config); FRAME_FreeLink(testInfo1.server); } /* END_CASE */ /* @ * @test UT_TLS_DTLS_CONSISTENCY_RFC6347_FINISH_TC001 * @spec - * @titleThe client receives a FINISH message and the CCS message is out of order. * @precon nan * @brief 1. Initialize the client and server based on the default configuration. Expected result 1. * 2. The client initiates a connection request and constructs the scenario where the FINISH message and CCS message are out of order. That is, the client processes the FINISH message and then processes the CCS message. After the processing, the client continues to establish a connection. Expected result 2 is displayed. * @expect 1: The initialization is successful. * 2: The client waits to receive the FINISH message. * @prior Level 1 * @auto TRUE @ */ /* BEGIN_CASE */ void UT_TLS_DTLS_CONSISTENCY_RFC6347_FINISH_TC001(void) { HandshakeTestInfo testInfo = {0}; testInfo.isClient = false; testInfo.state = TRY_SEND_CHANGE_CIPHER_SPEC; ASSERT_TRUE(DefaultCfgStatusPark(&testInfo, BSL_UIO_UDP) == HITLS_SUCCESS); uint8_t data[MAX_RECORD_LENTH] = {0}; uint32_t len = MAX_RECORD_LENTH; ASSERT_TRUE(GetDisorderServerFinished(testInfo.server, data, len, &len) == HITLS_SUCCESS); FrameUioUserData *ioUserData = BSL_UIO_GetUserData(testInfo.client->io); ASSERT_TRUE(ioUserData->recMsg.len == 0); ASSERT_TRUE(FRAME_TransportRecMsg(testInfo.client->io, data, len) == HITLS_SUCCESS); (void)HITLS_Connect(testInfo.client->ssl); ASSERT_EQ(testInfo.client->ssl->state, CM_STATE_TRANSPORTING); EXIT: HITLS_CFG_FreeConfig(testInfo.config); FRAME_FreeLink(testInfo.client); FRAME_FreeLink(testInfo.server); FRAME_DeRegCryptMethod(); } /* END_CASE */ /* @ * @test UT_TLS_DTLS_CONSISTENCY_RFC6347_FINISH_TC002 * @spec - * @titleThe server receives a FINISH message and the CCS message is out of order. * @precon nan * @brief 1. Initialize the client and server based on the default configuration. Expected result 1. * 2. The client initiates a connection request and constructs the scenario where the FINISH message and CCS message are out of order. That is, the server processes the FINISH message and then processes the CCS message. After the processing, the server continues to establish a connection. Expected result 2 is displayed. * @expect 1: The initialization is successful. * 2: The server is waiting to receive the FINISH message. * @prior Level 1 * @auto TRUE @ */ /* BEGIN_CASE */ void UT_TLS_DTLS_CONSISTENCY_RFC6347_FINISH_TC002(void) { FRAME_Msg frameMsg = {0}; FRAME_Type frameType = {0}; HandshakeTestInfo testInfo = {0}; testInfo.isClient = true; testInfo.state = TRY_SEND_CLIENT_KEY_EXCHANGE; ASSERT_TRUE(DefaultCfgStatusPark(&testInfo, BSL_UIO_UDP) == HITLS_SUCCESS); uint8_t data[MAX_RECORD_LENTH] = {0}; uint32_t len = MAX_RECORD_LENTH; ASSERT_TRUE(GetDisorderClientFinished(testInfo.client, data, len, &len) == HITLS_SUCCESS); FrameUioUserData *ioUserData = BSL_UIO_GetUserData(testInfo.server->io); ASSERT_TRUE(ioUserData->recMsg.len == 0); ASSERT_TRUE(FRAME_TransportRecMsg(testInfo.server->io, data, len) == HITLS_SUCCESS); (void)HITLS_Accept(testInfo.server->ssl); ASSERT_EQ(testInfo.server->ssl->state, CM_STATE_HANDSHAKING); ASSERT_EQ(testInfo.server->ssl->hsCtx->state, TRY_SEND_CHANGE_CIPHER_SPEC); 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_DTLS_CONSISTENCY_RFC6347_FINISH_TC003 * @spec - * @titleThe client receives a FINISH message and the APP message is out of order. * @precon nan * @brief 1. Initialize the client and server using the default configuration. Expected result 1. * 2. The client initiates a connection request and constructs the scenario where the FINISH message and APP message are out of order. That is, the client processes the APP message first, processes the FINISH message, and then continues to establish a connection. Expected result 2. * @expect 1: Initialization succeeded. * 2: The connection between the client and server is successfully established. * @prior Level 1 * @auto TRUE @ */ /* BEGIN_CASE */ void UT_TLS_DTLS_CONSISTENCY_RFC6347_FINISH_TC003(int uioType) { HandshakeTestInfo testInfo = {0}; testInfo.isClient = false; testInfo.state = TRY_SEND_CHANGE_CIPHER_SPEC; ASSERT_TRUE(DefaultCfgStatusPark(&testInfo, uioType) == HITLS_SUCCESS); uint8_t data[MAX_RECORD_LENTH] = {0}; uint32_t len = MAX_RECORD_LENTH; ASSERT_TRUE(GetDisorderServerFinish_AppData(testInfo.server, data, len, &len) == HITLS_SUCCESS); FrameUioUserData *ioUserData = BSL_UIO_GetUserData(testInfo.client->io); ASSERT_TRUE(ioUserData->recMsg.len == 0); ASSERT_TRUE(FRAME_TransportRecMsg(testInfo.client->io, data, len) == HITLS_SUCCESS); (void)HITLS_Connect(testInfo.client->ssl); ASSERT_TRUE(testInfo.client->ssl->state == CM_STATE_TRANSPORTING); ASSERT_TRUE(HITLS_Read(testInfo.client->ssl, data, MAX_RECORD_LENTH, &len) == HITLS_SUCCESS); EXIT: HITLS_CFG_FreeConfig(testInfo.config); FRAME_FreeLink(testInfo.client); FRAME_FreeLink(testInfo.server); FRAME_DeRegCryptMethod(); } /* END_CASE */ /* @ * @test UT_TLS_DTLS_CONSISTENCY_RFC6347_FINISH_TC004 * @spec - * @titleThe server receives a FINISH message and the APP message is out of order. * @precon nan * @brief 1. Initialize the client and server using the default configuration. Expected result 1. * 2. The client initiates a connection request and constructs the scenario where the FINISH message and APP message are out of order. That is, the server processes the APP message first, processes the FINISH message, and then continues to establish a connection. Expected result 2 is displayed. * 3. After the connection is established, the client sends data to the server, and the server receives the data. (Expected result 3) * @expect 1: Initialization succeeded. * 2: The connection between the client and server is successfully established. * 3: Data received by the server is consistent with data sent by the client. * @prior Level 1 * @auto TRUE @ */ /* BEGIN_CASE */ void UT_TLS_DTLS_CONSISTENCY_RFC6347_FINISH_TC004(int uioType) { HandshakeTestInfo testInfo = {0}; testInfo.isClient = true; testInfo.state = TRY_SEND_FINISH; ASSERT_TRUE(DefaultCfgStatusPark(&testInfo, uioType) == HITLS_SUCCESS); uint8_t data[MAX_RECORD_LENTH] = {0}; uint32_t len = MAX_RECORD_LENTH; ASSERT_TRUE(GetDisorderClientFinished_AppData(testInfo.client, data, len, &len) == HITLS_SUCCESS); FrameUioUserData *ioUserData = BSL_UIO_GetUserData(testInfo.server->io); ASSERT_TRUE(ioUserData->recMsg.len == 0); ASSERT_TRUE(FRAME_TransportRecMsg(testInfo.server->io, data, len) == HITLS_SUCCESS); (void)HITLS_Accept(testInfo.server->ssl); ASSERT_EQ(testInfo.server->ssl->state, CM_STATE_HANDSHAKING); ASSERT_EQ(FRAME_TrasferMsgBetweenLink(testInfo.server, testInfo.client), HITLS_SUCCESS); (void)HITLS_Connect(testInfo.client->ssl); (void)HITLS_Accept(testInfo.server->ssl); ASSERT_EQ(testInfo.server->ssl->state, CM_STATE_HANDSHAKING); ASSERT_EQ(FRAME_TrasferMsgBetweenLink(testInfo.server, testInfo.client), HITLS_SUCCESS); (void)HITLS_Connect(testInfo.client->ssl); FRAME_RegCryptMethod(); if (uioType == BSL_UIO_UDP) { // anti-replay ASSERT_TRUE(HITLS_Read(testInfo.server->ssl, data, MAX_RECORD_LENTH, &len) == HITLS_REC_NORMAL_RECV_BUF_EMPTY); } else { ASSERT_TRUE(HITLS_Read(testInfo.server->ssl, data, MAX_RECORD_LENTH, &len) == HITLS_SUCCESS); } ASSERT_EQ(FRAME_TrasferMsgBetweenLink(testInfo.server, testInfo.client), HITLS_SUCCESS); (void)HITLS_Connect(testInfo.client->ssl); uint8_t writeData[] = {"abcd1234"}; uint32_t writeLen = strlen("abcd1234"); uint8_t readData[MAX_RECORD_LENTH] = {0}; uint32_t readLen = MAX_RECORD_LENTH; uint32_t sendNum; ASSERT_EQ(HITLS_Write(testInfo.server->ssl, writeData, writeLen, &sendNum), HITLS_SUCCESS); ASSERT_EQ(FRAME_TrasferMsgBetweenLink(testInfo.server, testInfo.client), HITLS_SUCCESS); ASSERT_EQ(HITLS_Read(testInfo.client->ssl, readData, MAX_RECORD_LENTH, &readLen), HITLS_SUCCESS); ASSERT_EQ(readLen, writeLen); ASSERT_EQ(memcmp(writeData, readData, readLen), 0); EXIT: HITLS_CFG_FreeConfig(testInfo.config); FRAME_FreeLink(testInfo.client); FRAME_FreeLink(testInfo.server); FRAME_DeRegCryptMethod(); } /* END_CASE */ /* @ * @test UT_TLS_DTLS_CONSISTENCY_RFC6347_DISORDER_TC001 * @spec - * @titleThe server receives out-of-order APP messages. * @precon nan * @brief 1. Initialize the configuration on the client and server. Expected result 1. * 2. Initiate a connection application by using DTLS. Expected result 2. * 3. Construct an app message whose SN is 2 and send it to the server. When the server invokes HiTLS_Read, expected result 3. * 4. Construct an app message whose SN is 1 and send it to the server. When the server invokes HiTLS_Read, expected result 4. * @expect 1: Initializing the configuration succeeded. * 2: The DTLS connection is successfully created. * 3: The interface returns a success response. * 4: The interface returns a success response. * @prior Level 1 * @auto TRUE @ */ /* BEGIN_CASE */ void UT_TLS_DTLS_CONSISTENCY_RFC6347_DISORDER_TC001(int uioType) { HandshakeTestInfo testInfo = {0}; testInfo.isClient = true; testInfo.state = HS_STATE_BUTT; ASSERT_EQ(DefaultCfgStatusPark1(&testInfo, uioType), HITLS_SUCCESS); uint8_t data[MAX_RECORD_LENTH] = {0}; uint32_t len = MAX_RECORD_LENTH; ASSERT_TRUE(GetDisorderApp(testInfo.client, data, &len) == HITLS_SUCCESS); FrameUioUserData *ioUserData = BSL_UIO_GetUserData(testInfo.server->io); ASSERT_TRUE(ioUserData->recMsg.len == 0); ASSERT_TRUE(FRAME_TransportRecMsg(testInfo.server->io, data, len) == HITLS_SUCCESS); uint8_t app1Data[MAX_RECORD_LENTH] = {0}; uint32_t app1Len = MAX_RECORD_LENTH; ASSERT_TRUE(HITLS_Read(testInfo.server->ssl, app1Data, MAX_RECORD_LENTH, &app1Len) == HITLS_SUCCESS); uint8_t app2Data[MAX_RECORD_LENTH] = {0}; uint32_t app2Len = MAX_RECORD_LENTH; ASSERT_TRUE(HITLS_Read(testInfo.server->ssl, app2Data, MAX_RECORD_LENTH, &app2Len) == HITLS_SUCCESS); ASSERT_EQ(app1Len, app2Len); ASSERT_EQ(memcmp(app1Data, app2Data, app2Len), 0); EXIT: HITLS_CFG_FreeConfig(testInfo.config); FRAME_FreeLink(testInfo.client); FRAME_FreeLink(testInfo.server); FRAME_DeRegCryptMethod(); } /* END_CASE */ /* @ * @test UT_TLS_DTLS_CONSISTENCY_RFC6347_DISORDER_TC002 * @spec - * @titleThe client receives out-of-order APP messages. * @precon nan * @brief 1. Initialize the configuration on the client and server. Expected result 1. * 2. Initiate a connection request using DTLS. Expected result 2. * 3. Construct an app message whose sequence number is 2 and send it to the client. When the client invokes HiTLS_Read, expected result 3. * 4. Construct an app message whose sequence number is 1 and send it to the client. When the client invokes HiTLS_Read, expected result 4. * @expect 1: Initializing the configuration succeeded. * 2: The DTLS connection is successfully created. * 3: The interface returns a success response. * 4: The interface returns a success response. * @prior Level 1 * @auto TRUE @ */ /* BEGIN_CASE */ void UT_TLS_DTLS_CONSISTENCY_RFC6347_DISORDER_TC002(int uioType) { HandshakeTestInfo testInfo = {0}; testInfo.isClient = false; testInfo.state = HS_STATE_BUTT; ASSERT_EQ(DefaultCfgStatusPark1(&testInfo, uioType), HITLS_SUCCESS); uint8_t data[MAX_RECORD_LENTH] = {0}; uint32_t len = MAX_RECORD_LENTH; ASSERT_TRUE(GetDisorderApp(testInfo.server, data, &len) == HITLS_SUCCESS); FrameUioUserData *ioUserData = BSL_UIO_GetUserData(testInfo.client->io); ASSERT_TRUE(ioUserData->recMsg.len == 0); ASSERT_TRUE(FRAME_TransportRecMsg(testInfo.client->io, data, len) == HITLS_SUCCESS); uint8_t app1Data[MAX_RECORD_LENTH] = {0}; uint32_t app1Len = MAX_RECORD_LENTH; ASSERT_TRUE(HITLS_Read(testInfo.client->ssl, app1Data, MAX_RECORD_LENTH, &app1Len) == HITLS_SUCCESS); uint8_t app2Data[MAX_RECORD_LENTH] = {0}; uint32_t app2Len = MAX_RECORD_LENTH; ASSERT_TRUE(HITLS_Read(testInfo.client->ssl, app2Data, MAX_RECORD_LENTH, &app2Len) == HITLS_SUCCESS); ASSERT_EQ(app1Len, app2Len); ASSERT_EQ(memcmp(app1Data, app2Data, app1Len), 0); EXIT: HITLS_CFG_FreeConfig(testInfo.config); FRAME_FreeLink(testInfo.client); FRAME_FreeLink(testInfo.server); FRAME_DeRegCryptMethod(); } /* END_CASE */ /* @ * @test UT_TLS_DTLS_CONSISTENCY_RFC6347_APPDATA_TC001 * @spec - * @title The server receives duplicate APP messages. * @precon nan * @brief 1. Initialize the configuration on the client and server. Expected result 1. * 2. Initiate a connection application by using DTLS. Expected result 2. * 3. Construct an app message whose SN is 1 and send it to the server. When the server invokes HiTLS_Read, expected result 3. * 4. Construct the app message whose SN is 1 and send it to the server. When the server invokes HiTLS_Read, expected result 4. * 5. The server constructs data and sends it to the client. When the client invokes HiTLS_Read, expected result 5. * @expect 1: Initializing the configuration succeeded. * 2: The DTLS connection is successfully created. * 3: The interface returns a success response. * 4: The interface returns a success response. * 5: The interface returns a success response. * @prior Level 1 * @auto TRUE @ */ /* BEGIN_CASE */ void UT_TLS_DTLS_CONSISTENCY_RFC6347_APPDATA_TC001(int uioType) { HandshakeTestInfo testInfo = {0}; testInfo.isClient = true; testInfo.state = HS_STATE_BUTT; ASSERT_EQ(DefaultCfgStatusPark1(&testInfo, uioType), HITLS_SUCCESS); uint8_t data[MAX_RECORD_LENTH] = {0}; uint32_t len = MAX_RECORD_LENTH; ASSERT_TRUE(GetRepeatsApp(testInfo.client, data, &len) == HITLS_SUCCESS); FrameUioUserData *ioUserData = BSL_UIO_GetUserData(testInfo.server->io); ASSERT_TRUE(ioUserData->recMsg.len == 0); ASSERT_TRUE(FRAME_TransportRecMsg(testInfo.server->io, data, len) == HITLS_SUCCESS); ASSERT_TRUE(HITLS_Read(testInfo.server->ssl, data, MAX_RECORD_LENTH, &len) == HITLS_SUCCESS); if (uioType == BSL_UIO_UDP) { // anti-replay ASSERT_TRUE(HITLS_Read(testInfo.server->ssl, data, MAX_RECORD_LENTH, &len) == HITLS_REC_NORMAL_RECV_BUF_EMPTY); } else { ASSERT_TRUE(HITLS_Read(testInfo.server->ssl, data, MAX_RECORD_LENTH, &len) == HITLS_SUCCESS); } uint8_t writeData[] = {"abcd1234"}; uint32_t writeLen = strlen("abcd1234"); uint8_t readData[MAX_RECORD_LENTH] = {0}; uint32_t readLen = MAX_RECORD_LENTH; uint8_t tmpData[MAX_RECORD_LENTH]; uint32_t tmpLen; uint32_t sendNum; ASSERT_TRUE(HITLS_Write(testInfo.server->ssl, writeData, writeLen, &sendNum) == HITLS_SUCCESS); ASSERT_TRUE(FRAME_TransportSendMsg(testInfo.server->io, tmpData, MAX_RECORD_LENTH, &tmpLen) == HITLS_SUCCESS); ASSERT_TRUE(FRAME_TransportRecMsg(testInfo.client->io, tmpData, tmpLen) == HITLS_SUCCESS); ASSERT_EQ(HITLS_Read(testInfo.client->ssl, readData, MAX_RECORD_LENTH, &readLen), HITLS_SUCCESS); ASSERT_EQ(readLen, writeLen); ASSERT_EQ(memcmp(writeData, readData, readLen), 0); EXIT: HITLS_CFG_FreeConfig(testInfo.config); FRAME_FreeLink(testInfo.client); FRAME_FreeLink(testInfo.server); FRAME_DeRegCryptMethod(); } /* END_CASE */ /* @ * @test UT_TLS_DTLS_CONSISTENCY_RFC6347_APPDATA_TC002 * @spec - * @titleThe client receives duplicate APP messages. * @precon nan * @brief 1. Initialize the configuration on the client and server. Expected result 1. * 2. Initiate a connection application by using DTLS. Expected result 2. * 3. Construct an app message whose sequence number is 1 and send the message to the client. When the client invokes HiTLS_Read, expected result 3. * 4. Construct an app message with the sequence number being 1 and send it to the client. When the client invokes HiTLS_Read, expected result 4. * 5. The server constructs data and sends it to the client. When the client invokes HiTLS_Read, expected result 5. * @expect 1: Initializing the configuration succeeded. * 2: The DTLS connection is successfully created. * 3: The interface returns a success response. * 4: The interface returns a success response. * 5: The interface returns a success response. * @prior Level 1 * @auto TRUE @ */ /* BEGIN_CASE */ void UT_TLS_DTLS_CONSISTENCY_RFC6347_APPDATA_TC002(int uioType) { HandshakeTestInfo testInfo = {0}; testInfo.isClient = false; testInfo.state = HS_STATE_BUTT; ASSERT_EQ(DefaultCfgStatusPark1(&testInfo, uioType), HITLS_SUCCESS); uint8_t data[MAX_RECORD_LENTH] = {0}; uint32_t len = MAX_RECORD_LENTH; ASSERT_TRUE(GetRepeatsApp(testInfo.server, data, &len) == HITLS_SUCCESS); FrameUioUserData *ioUserData = BSL_UIO_GetUserData(testInfo.client->io); ASSERT_TRUE(ioUserData->recMsg.len == 0); ASSERT_TRUE(FRAME_TransportRecMsg(testInfo.client->io, data, len) == HITLS_SUCCESS); ASSERT_TRUE(HITLS_Read(testInfo.client->ssl, data, MAX_RECORD_LENTH, &len) == HITLS_SUCCESS); ASSERT_EQ(HITLS_Read(testInfo.client->ssl, data, MAX_RECORD_LENTH, &len), HITLS_REC_NORMAL_RECV_BUF_EMPTY); uint8_t writeData[] = {"abcd1234"}; uint32_t writeLen = strlen("abcd1234"); uint8_t readData[MAX_RECORD_LENTH] = {0}; uint32_t readLen = MAX_RECORD_LENTH; uint8_t tmpData[MAX_RECORD_LENTH]; uint32_t tmpLen; uint32_t sendNum; ASSERT_TRUE(HITLS_Write(testInfo.server->ssl, writeData, writeLen, &sendNum) == HITLS_SUCCESS); ASSERT_TRUE(FRAME_TransportSendMsg(testInfo.server->io, tmpData, MAX_RECORD_LENTH, &tmpLen) == HITLS_SUCCESS); ASSERT_TRUE(FRAME_TransportRecMsg(testInfo.client->io, tmpData, tmpLen) == HITLS_SUCCESS); ASSERT_EQ(HITLS_Read(testInfo.client->ssl, readData, MAX_RECORD_LENTH, &readLen), HITLS_SUCCESS); ASSERT_EQ(readLen, writeLen); ASSERT_EQ(memcmp(writeData, readData, readLen), 0); EXIT: HITLS_CFG_FreeConfig(testInfo.config); FRAME_FreeLink(testInfo.client); FRAME_FreeLink(testInfo.server); FRAME_DeRegCryptMethod(); } /* END_CASE */ /* @ * @test UT_TLS_DTLS_CONSISTENCY_RFC6347_CLIENT_HELLO_TC001 * @spec - * @title The server receives a Client Hello packet after the connection is established. * @precon nan * @brief 1. Initialize the client and server based on the default configuration. Expected result 1. * 2. The client initiates a connection request. Expected result 2. * 3. Construct a Client Hello packet and send it to the server. The server invokes HiTLS_Read to receive the packet. Expected result 3. * 4. The client invokes HiTLS_Write to send data to the server, and the server invokes HiTLS_Read to read data. (Expected result 4) * @expect 1: Initialization succeeded. * 2: The connection between the client and server is successfully established. * 3: The HiTLS_Read returns an error code, indicating that the receiving buffer is empty. * 4: The data read by the server is consistent with the data sent by the client. * @prior Level 1 * @auto TRUE @ */ /* BEGIN_CASE */ void UT_TLS_DTLS_CONSISTENCY_RFC6347_CLIENT_HELLO_TC001(int uioType) { HandshakeTestInfo testInfo = {0}; FRAME_Msg frameMsg = {0}; FRAME_Type frameType = {0}; testInfo.isClient = true; testInfo.state = HS_STATE_BUTT; ASSERT_EQ(DefaultCfgStatusPark1(&testInfo, uioType), HITLS_SUCCESS); frameType.versionType = HITLS_VERSION_DTLS12; frameType.recordType = REC_TYPE_HANDSHAKE; frameType.handshakeType = CLIENT_HELLO; frameType.keyExType = HITLS_KEY_EXCH_ECDHE; frameType.transportType = BSL_UIO_UDP; 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); ASSERT_TRUE(REC_Write(testInfo.client->ssl, REC_TYPE_HANDSHAKE, &sendBuf[REC_DTLS_RECORD_HEADER_LEN], sendLen - REC_DTLS_RECORD_HEADER_LEN) == HITLS_SUCCESS); ASSERT_TRUE(FRAME_TrasferMsgBetweenLink(testInfo.client, testInfo.server) == HITLS_SUCCESS); uint8_t data[MAX_RECORD_LENTH] = {0}; uint32_t len = MAX_RECORD_LENTH; ASSERT_TRUE(testInfo.server->ssl != NULL); ASSERT_EQ(HITLS_Read(testInfo.server->ssl, data, MAX_RECORD_LENTH, &len), HITLS_REC_NORMAL_RECV_BUF_EMPTY); uint8_t writeData[] = {"abcd1234"}; uint32_t writeLen = strlen("abcd1234"); uint8_t readData[MAX_RECORD_LENTH] = {0}; uint32_t readLen = MAX_RECORD_LENTH; uint8_t tmpData[MAX_RECORD_LENTH]; uint32_t tmpLen; uint32_t sendNum; ASSERT_EQ(HITLS_Write(testInfo.client->ssl, writeData, writeLen, &sendNum), HITLS_SUCCESS); ASSERT_TRUE(FRAME_TransportSendMsg(testInfo.client->io, tmpData, MAX_RECORD_LENTH, &tmpLen) == HITLS_SUCCESS); ASSERT_TRUE(FRAME_TransportRecMsg(testInfo.server->io, tmpData, tmpLen) == HITLS_SUCCESS); ASSERT_EQ(HITLS_Read(testInfo.server->ssl, readData, MAX_RECORD_LENTH, &readLen), HITLS_SUCCESS); ASSERT_EQ(readLen, writeLen); ASSERT_EQ(memcmp(writeData, readData, readLen), 0); EXIT: HITLS_CFG_FreeConfig(testInfo.config); FRAME_CleanMsg(&frameType, &frameMsg); FRAME_FreeLink(testInfo.client); FRAME_FreeLink(testInfo.server); FRAME_DeRegCryptMethod(); } /* END_CASE */ static bool cookie_generate_success = true; static int32_t UT_CookieGenerateCb(HITLS_Ctx *ctx, uint8_t *cookie, uint32_t *cookie_len) { (void)ctx; (void)cookie; if (cookie_generate_success) { *cookie_len = DTLS_COOKIE_LEN; } return cookie_generate_success; } static bool cookie_valid = true; static int32_t UT_CookieVerifyCb(HITLS_Ctx *ctx, const uint8_t *cookie, uint32_t cookie_len) { (void)ctx; (void)cookie; (void)cookie_len; return cookie_valid; } int32_t HS_CheckCookie_Stub(TLS_Ctx *ctx, const ClientHelloMsg *clientHello, bool *isCookieValid) { *isCookieValid = false; /* If the client does not send the cookie, the verification is not required */ if (clientHello->cookie == NULL) { return HITLS_SUCCESS; } if (ctx->globalConfig->appVerifyCookieCb == NULL) { return HITLS_UNREGISTERED_CALLBACK; } HITLS_AppVerifyCookieCb cookieCb = ctx->globalConfig->appVerifyCookieCb; int32_t isValid = cookieCb(ctx, clientHello->cookie, clientHello->cookieLen); if (isValid != HITLS_COOKIE_VERIFY_ERROR) { *isCookieValid = true; } return HITLS_SUCCESS; } int32_t HS_CalcCookie_Stub(TLS_Ctx *ctx, const ClientHelloMsg *clientHello, uint8_t *cookie, uint32_t *cookieLen) { (void)clientHello; if (ctx->globalConfig->appGenCookieCb == NULL) { return HITLS_UNREGISTERED_CALLBACK; } int32_t returnVal = ctx->globalConfig->appGenCookieCb(ctx, cookie, cookieLen); if (returnVal == HITLS_COOKIE_GENERATE_ERROR) { return HITLS_MSG_HANDLE_COOKIE_ERR; } return HITLS_SUCCESS; } /* @ * @test UT_TLS_DTLS_CONSISTENCY_RFC6347_HELLO_VERIFY_REQ_TC001 * @spec - * @title The server doesn't set appGenCookieCb or appVerifyCookieCb. * @precon nan * @brief 1. Configure option isSupportDtlsCookieExchange is on. Leave appGenCookieCb or appVerifyCookieCb blank. Check whether server and client can handshake successfully. Expected result 1. * @expect 1. The link fails to be set up. * @prior Level 1 * @auto TRUE @ */ /* BEGIN_CASE */ void UT_TLS_DTLS_CONSISTENCY_RFC6347_HELLO_VERIFY_REQ_TC001(int setGenerateCb, int setVerifyCb) { FRAME_Init(); HITLS_Config *tlsConfig = HITLS_CFG_NewDTLS12Config(); ASSERT_TRUE(tlsConfig != NULL); FRAME_LinkObj *client = FRAME_CreateLink(tlsConfig, BSL_UIO_UDP); FRAME_LinkObj *server = FRAME_CreateLink(tlsConfig, BSL_UIO_UDP); ASSERT_TRUE(client != NULL); ASSERT_TRUE(server != NULL); STUB_Init(); FuncStubInfo stubInfo = {0}; HITLS_Ctx *serverTlsCtx = FRAME_GetTlsCtx(server); serverTlsCtx->config.tlsConfig.isSupportDtlsCookieExchange = true; if (setGenerateCb) { serverTlsCtx->globalConfig->appGenCookieCb = UT_CookieGenerateCb; STUB_Replace(&stubInfo, HS_CheckCookie, HS_CheckCookie_Stub); } if (setVerifyCb) { serverTlsCtx->globalConfig->appVerifyCookieCb = UT_CookieVerifyCb; STUB_Replace(&stubInfo, HS_CalcCookie, HS_CalcCookie_Stub); } ASSERT_TRUE(FRAME_CreateConnection(client, server, true, HS_STATE_BUTT) == HITLS_UNREGISTERED_CALLBACK); EXIT: STUB_Reset(&stubInfo); HITLS_CFG_FreeConfig(tlsConfig); FRAME_FreeLink(client); FRAME_FreeLink(server); } /* END_CASE */ /* @ * @test UT_TLS_DTLS_CONSISTENCY_RFC6347_HELLO_VERIFY_REQ_TC002 * @spec - * @title The server fails to generate cookie. * @precon nan * @brief 1. Configure option isSupportDtlsCookieExchange is on. Configure appGenCookieCb and appVerifyCookieCb. appGenCookieCb always return false. Check whether server and client can handshake successfully. Expected result 1. * @expect 1. The link fails to be set up. * @prior Level 1 * @auto TRUE @ */ /* BEGIN_CASE */ void UT_TLS_DTLS_CONSISTENCY_RFC6347_HELLO_VERIFY_REQ_TC002(void) { FRAME_Init(); HITLS_Config *tlsConfig = HITLS_CFG_NewDTLS12Config(); ASSERT_TRUE(tlsConfig != NULL); FRAME_LinkObj *client = FRAME_CreateLink(tlsConfig, BSL_UIO_UDP); FRAME_LinkObj *server = FRAME_CreateLink(tlsConfig, BSL_UIO_UDP); ASSERT_TRUE(client != NULL); ASSERT_TRUE(server != NULL); HITLS_Ctx *serverTlsCtx = FRAME_GetTlsCtx(server); serverTlsCtx->config.tlsConfig.isSupportDtlsCookieExchange = true; serverTlsCtx->globalConfig->appGenCookieCb = UT_CookieGenerateCb; serverTlsCtx->globalConfig->appVerifyCookieCb = UT_CookieVerifyCb; cookie_generate_success = false; ASSERT_TRUE(FRAME_CreateConnection(client, server, true, HS_STATE_BUTT) == HITLS_MSG_HANDLE_COOKIE_ERR); EXIT: HITLS_CFG_FreeConfig(tlsConfig); FRAME_FreeLink(client); FRAME_FreeLink(server); } /* END_CASE */ /* @ * @test UT_TLS_DTLS_CONSISTENCY_RFC6347_HELLO_VERIFY_REQ_TC003 * @spec - * @title The server receives a Client Hello packet with invalid cookie when isSupportDtlsCookieExchange is on. * @precon nan * @brief 1. Configure option isSupportDtlsCookieExchange is on. Configure appGenCookieCb and appVerifyCookieCb. appGenCookieCb always return true and appVerifyCookieCb always return false. Check whether server and client can handshake successfully. Expected result 1. * @expect 1: The link fails to be set up. * @prior Level 1 * @auto TRUE @ */ /* BEGIN_CASE */ void UT_TLS_DTLS_CONSISTENCY_RFC6347_HELLO_VERIFY_REQ_TC003(void) { FRAME_Init(); HITLS_Config *tlsConfig = HITLS_CFG_NewDTLS12Config(); ASSERT_TRUE(tlsConfig != NULL); FRAME_LinkObj *client = FRAME_CreateLink(tlsConfig, BSL_UIO_UDP); FRAME_LinkObj *server = FRAME_CreateLink(tlsConfig, BSL_UIO_UDP); ASSERT_TRUE(client != NULL); ASSERT_TRUE(server != NULL); HITLS_Ctx *serverTlsCtx = FRAME_GetTlsCtx(server); serverTlsCtx->config.tlsConfig.isSupportDtlsCookieExchange = true; serverTlsCtx->globalConfig->appGenCookieCb = UT_CookieGenerateCb; serverTlsCtx->globalConfig->appVerifyCookieCb = UT_CookieVerifyCb; cookie_generate_success = true; cookie_valid = false; ASSERT_TRUE(FRAME_CreateConnection(client, server, true, HS_STATE_BUTT) == HITLS_INTERNAL_EXCEPTION); EXIT: HITLS_CFG_FreeConfig(tlsConfig); FRAME_FreeLink(client); FRAME_FreeLink(server); } /* END_CASE */ /* @ * @test UT_TLS_DTLS_CONSISTENCY_RFC6347_HELLO_VERIFY_REQ_TC003 * @spec - * @title The server receives a Client Hello packet with valid cookie when isSupportDtlsCookieExchange is on. * @precon nan * @brief 1. Configure option isSupportDtlsCookieExchange is on. Configure appGenCookieCb and appVerifyCookieCb. appGenCookieCb always return true and appVerifyCookieCb always return true. Check whether server and client can handshake successfully. Expected result 1. * @expect 1: The link is set up successfully. * @prior Level 1 * @auto TRUE @ */ /* BEGIN_CASE */ void UT_TLS_DTLS_CONSISTENCY_RFC6347_HELLO_VERIFY_REQ_TC004(void) { FRAME_Init(); HITLS_Config *tlsConfig = HITLS_CFG_NewDTLS12Config(); ASSERT_TRUE(tlsConfig != NULL); FRAME_LinkObj *client = FRAME_CreateLink(tlsConfig, BSL_UIO_UDP); FRAME_LinkObj *server = FRAME_CreateLink(tlsConfig, BSL_UIO_UDP); ASSERT_TRUE(client != NULL); ASSERT_TRUE(server != NULL); HITLS_Ctx *serverTlsCtx = FRAME_GetTlsCtx(server); serverTlsCtx->config.tlsConfig.isSupportDtlsCookieExchange = true; serverTlsCtx->globalConfig->appGenCookieCb = UT_CookieGenerateCb; serverTlsCtx->globalConfig->appVerifyCookieCb = UT_CookieVerifyCb; cookie_generate_success = true; cookie_valid = true; 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 */ /* @ * @test UT_TLS_DTLS_CONSISTENCY_RFC8422_ECPOINT_TC001 * @spec - * @titleThe client receives an abnormal dot format field. * @precon nan * @brief 1. The client and server use the default initialization. Expected result 1. * 2. The client initiates a connection request. When the client wants to read the Server Hello message, * Modify the Elliptic curves point formats field, change the group supported by the field to 0x01, and send the field to the client. Expected result 2. * @expect 1. Initialization succeeded. * 2. The client sends a FATAL ALERT with the description of ALERT_ELLEGAL_PARAMETER. * @prior Level 1 * @auto TRUE @ */ /* BEGIN_CASE */ void UT_TLS_DTLS_CONSISTENCY_RFC8422_ECPOINT_TC001(void) { HandshakeTestInfo testInfo = {0}; testInfo.state = TRY_RECV_SERVER_HELLO; testInfo.isSupportExtendMasterSecret = true; testInfo.isClient = true; ASSERT_TRUE(DefaultCfgStatusPark(&testInfo, BSL_UIO_UDP) == 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_DTLS12; frameType.recordType = REC_TYPE_HANDSHAKE; frameType.handshakeType = SERVER_HELLO; frameType.keyExType = HITLS_KEY_EXCH_ECDHE; frameType.transportType = BSL_UIO_UDP; ASSERT_TRUE(FRAME_ParseMsg(&frameType, recvBuf, recvLen, &frameMsg, &parseLen) == HITLS_SUCCESS); uint8_t Gdata[] = { 0x01 }; FRAME_ServerHelloMsg *serverMsg = &frameMsg.body.hsMsg.body.serverHello; serverMsg->pointFormats.exState = INITIAL_FIELD; ASSERT_TRUE(FRAME_ModifyMsgInteger(HS_EX_TYPE_POINT_FORMATS, &(serverMsg->pointFormats.exType)) == HITLS_SUCCESS); serverMsg->pointFormats.exLen.state = INITIAL_FIELD; ASSERT_TRUE(FRAME_ModifyMsgArray8(Gdata, sizeof(Gdata)/sizeof(uint8_t), &(serverMsg->pointFormats.exData), &(serverMsg->pointFormats.exDataLen)) == 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); 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); ASSERT_EQ(HITLS_Connect(testInfo.client->ssl), HITLS_MSG_HANDLE_UNSUPPORT_POINT_FORMAT); 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_TRUE(alertMsg->alertDescription.data == ALERT_ILLEGAL_PARAMETER); 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_DTLS_CONSISTENCY_RFC8422_EXTENSION_MISS_TC001 * @spec - * @title The server receives a Client Hello packet that does not carry the group or dot format. * @precon nan * @brief 1. Configure the HITLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384 cipher suite on the client and initialize the cipher suite on the server by default. Expected result 1. * 2. When the client initiates a connection request and the server is about to read ClientHello, * Delete the supported_groups and ec_point_formats fields from the packet. Expected result 2. * @expect 1. Initialization succeeded. * 2. The server sends a Server Hello packet with the HITLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384 algorithm suite. * @prior Level 1 * @auto TRUE @ */ /* BEGIN_CASE */ void UT_TLS_DTLS_CONSISTENCY_RFC8422_EXTENSION_MISS_TC001(void) { HandshakeTestInfo testInfo = {0}; testInfo.state = TRY_RECV_CLIENT_HELLO; testInfo.isSupportExtendMasterSecret = true; testInfo.isClient = false; ASSERT_TRUE(DefaultCfgStatusPark(&testInfo, BSL_UIO_UDP) == 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; FRAME_Msg frameMsg = {0}; FRAME_Type frameType = {0}; frameType.versionType = HITLS_VERSION_DTLS12; frameType.recordType = REC_TYPE_HANDSHAKE; frameType.handshakeType = CLIENT_HELLO; frameType.keyExType = HITLS_KEY_EXCH_ECDHE; frameType.transportType = BSL_UIO_UDP; ASSERT_TRUE(FRAME_ParseMsg(&frameType, recvBuf, recvLen, &frameMsg, &parseLen) == HITLS_SUCCESS); FRAME_ClientHelloMsg *clientMsg = &frameMsg.body.hsMsg.body.clientHello; clientMsg->supportedGroups.exState = MISSING_FIELD; clientMsg->pointFormats.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(testInfo.server->io, sendBuf, sendLen) == HITLS_SUCCESS); FRAME_CleanMsg(&frameType, &frameMsg); memset_s(&frameMsg, sizeof(frameMsg), 0, sizeof(frameMsg)); CONN_Deinit(testInfo.server->ssl); ASSERT_TRUE(testInfo.server->ssl != NULL); ASSERT_EQ(HITLS_Accept(testInfo.server->ssl), HITLS_REC_NORMAL_IO_BUSY); 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_HANDSHAKE; ASSERT_TRUE(FRAME_ParseMsg(&frameType, sndBuf, sndLen, &frameMsg, &parseLen) == HITLS_SUCCESS); ASSERT_TRUE(frameMsg.recType.data == REC_TYPE_HANDSHAKE); ASSERT_TRUE(frameMsg.body.hsMsg.type.data == SERVER_HELLO); FRAME_ServerHelloMsg *serverMsg = &frameMsg.body.hsMsg.body.serverHello; ASSERT_EQ(serverMsg->cipherSuite.data, HITLS_DHE_RSA_WITH_AES_256_GCM_SHA384); EXIT: FRAME_CleanMsg(&frameType, &frameMsg); HITLS_CFG_FreeConfig(testInfo.config); FRAME_FreeLink(testInfo.client); FRAME_FreeLink(testInfo.server); FRAME_DeRegCryptMethod(); } /* END_CASE */ /* when receive alert between finish and ccs, dtls12 should cache it*/ /* BEGIN_CASE */ void UT_DTLS_RFC6347_RECV_ALERT_AFTER_CCS_TC001(int uioType) { FRAME_Init(); HITLS_Config *tlsConfig = HITLS_CFG_NewDTLSConfig(); ASSERT_TRUE(tlsConfig != NULL); FRAME_LinkObj *client = FRAME_CreateLink(tlsConfig, uioType); FRAME_LinkObj *server = FRAME_CreateLink(tlsConfig, uioType); client->needStopBeforeRecvCCS = true; server->needStopBeforeRecvCCS = true; 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); // client receive ccs, wait to receive finish ASSERT_EQ(HITLS_Connect(clientTlsCtx), HITLS_REC_NORMAL_RECV_BUF_EMPTY); uint8_t alertdata[2] = {0x02, 0x0a}; ASSERT_EQ(REC_Write(serverTlsCtx, REC_TYPE_ALERT, alertdata, sizeof(alertdata)), HITLS_SUCCESS); ASSERT_TRUE(FRAME_TrasferMsgBetweenLink(server, client) == HITLS_SUCCESS); // client cache the alert, wait to receive finish ASSERT_EQ(HITLS_Connect(clientTlsCtx), HITLS_REC_NORMAL_RECV_BUF_EMPTY); ASSERT_TRUE(clientTlsCtx->state == CM_STATE_HANDSHAKING); // server send finish, handshake success ASSERT_EQ(HITLS_Accept(serverTlsCtx), HITLS_SUCCESS); ASSERT_TRUE(FRAME_TrasferMsgBetweenLink(server, client) == HITLS_SUCCESS); // client receive finish, handshake success ASSERT_EQ(HITLS_Connect(clientTlsCtx), HITLS_SUCCESS); ASSERT_TRUE(clientTlsCtx->state == CM_STATE_TRANSPORTING); // client read cached alert uint8_t readBuf[READ_BUF_SIZE] = {0}; uint32_t readLen = 0; ASSERT_EQ(HITLS_Read(clientTlsCtx, readBuf, READ_BUF_SIZE, &readLen), 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_DTLS_CONSISTENCY_RFC6347_TC001 * @spec - * @title The client receives a Hello Request message which msg seq is not 0. * @precon nan * @brief 1. Use the default configuration items to configure the client and server. Expected result 1. * 2. After the client finished handshake, the client receives a Hello Request message. Expected result 2. * @expect 1. The initialization is successful. * 2. The client igore the message. * @prior Level 1 * @auto TRUE @ */ /* BEGIN_CASE */ void UT_TLS_DTLS_CONSISTENCY_RFC6347_TC001() { FRAME_Init(); HITLS_Config *tlsConfig = HITLS_CFG_NewDTLS12Config(); tlsConfig->isSupportRenegotiation = true; ASSERT_TRUE(tlsConfig != NULL); FRAME_LinkObj *client = FRAME_CreateLink(tlsConfig, BSL_UIO_UDP); FRAME_LinkObj *server = FRAME_CreateLink(tlsConfig, BSL_UIO_UDP); 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, HS_STATE_BUTT) == HITLS_SUCCESS); uint8_t buf[DTLS_HS_MSG_HEADER_SIZE] = {0u}; buf[5] = 1; size_t len = DTLS_HS_MSG_HEADER_SIZE; REC_Write(serverTlsCtx, REC_TYPE_HANDSHAKE, buf, len); ASSERT_EQ(FRAME_TrasferMsgBetweenLink(server, client), HITLS_SUCCESS); uint8_t readData[MAX_RECORD_LENTH] = {0}; uint32_t readLen = MAX_RECORD_LENTH; ASSERT_EQ(HITLS_Read(clientTlsCtx, readData, MAX_RECORD_LENTH, &readLen), HITLS_REC_NORMAL_RECV_BUF_EMPTY); EXIT: HITLS_CFG_FreeConfig(tlsConfig); FRAME_FreeLink(client); FRAME_FreeLink(server); } /* END_CASE */ /* @ * @test UT_TLS_DTLS_CONSISTENCY_RETRANSMIT_TC001 * @spec - * @title When testing the behavior of the client preparing to receive messages, querying the remaining timeout time, selecting whether to sleep, and then retransmitting the message * @precon nan * @brief 1. Use the default configuration items to configure the client and server. Expected result 1. * 2. Stop the client in the TRY1 RECV_SERVER HELLO or TRY1 RECV_FINISH state. Expected result 2. * 3. Obtain the remaining timeout period. Expected result 3. * 4. Choose sleep mode and then resend the message. Expected result 4. * 5. Do not sleep, and then retransmit the message. Expected result 5. * @expect 1. The initialization is successful. * 2. return success. * 3. return success. * 4. expecting the message to be successfully retransmit. * 5. expecting to return HITLS_MSG_HANDLE_DTLS_RETRANSMIT_NOT_TIMEOUT. * @prior Level 1 * @auto TRUE @ */ /* BEGIN_CASE */ void UT_TLS_DTLS_CONSISTENCY_RETRANSMIT_TC001(int isNeedSleep, int clientState) { FRAME_Init(); HITLS_Config *tlsConfig = HITLS_CFG_NewDTLS12Config(); tlsConfig->isSupportRenegotiation = true; ASSERT_TRUE(tlsConfig != NULL); FRAME_LinkObj *client = FRAME_CreateLink(tlsConfig, BSL_UIO_UDP); FRAME_LinkObj *server = FRAME_CreateLink(tlsConfig, BSL_UIO_UDP); ASSERT_TRUE(client != NULL); ASSERT_TRUE(server != NULL); ASSERT_TRUE(FRAME_CreateConnection(client, server, true, clientState) == HITLS_SUCCESS); uint64_t timeout = 0; int32_t ret = HITLS_DtlsGetTimeout(client->ssl, &timeout); ASSERT_TRUE(ret == HITLS_SUCCESS); if (isNeedSleep) { sleep(2); // the sleep time is greater than the timeout period, the retransmission operation is triggered ret = HITLS_DtlsProcessTimeout(client->ssl); // When there are multiple messages, retransmission will be blocked, so it will be busy. // If there is only one message, it will be successfully sent. if (ret == HITLS_REC_NORMAL_IO_BUSY) { ret = FRAME_TrasferMsgBetweenLink(client, server); } ASSERT_EQ(ret, HITLS_SUCCESS); } else { ret = HITLS_DtlsProcessTimeout(client->ssl); ASSERT_TRUE(ret == HITLS_MSG_HANDLE_DTLS_RETRANSMIT_NOT_TIMEOUT); } EXIT: HITLS_CFG_FreeConfig(tlsConfig); FRAME_FreeLink(client); FRAME_FreeLink(server); } /* END_CASE */
2301_79861745/bench_create
testcode/sdv/testcase/tls/consistency/dtls12/test_suite_sdv_frame_dtls12_consistency.c
C
unknown
138,478
/* * This file is part of the openHiTLS project. * * openHiTLS is licensed under the Mulan PSL v2. * You can use this software according to the terms and conditions of the Mulan PSL v2. * You may obtain a copy of Mulan PSL v2 at: * * http://license.coscl.org.cn/MulanPSL2 * * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, * EITHER EXPRESS 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 <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 "recv_process.h" #include "stub_replace.h" #include "stub_crypt.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 "rec_wrapper.h" #include "process.h" #include "pthread.h" #include "unistd.h" #include "rec_header.h" #include "bsl_log.h" #include "cert_callback.h" #include "bsl_uio.h" #include "uio_abstraction.h" #include "record.h" /* END_HEADER */ #define REC_DTLS_RECORD_HEADER_LEN 13 #define BUF_SIZE_DTO_TEST 18432 void Hello(void *ssl) { const char *writeBuf = "Hello world"; ASSERT_TRUE(HLT_TlsWrite(ssl, (uint8_t *)writeBuf, strlen(writeBuf)) == 0); EXIT: return; } /* * @ * @test SDV_TLS_DTLS_CONSISTENCY_RFC5246_UNEXPETED_REORD_TYPE_TC001 * @Specifications- * @Title1. Construct a scenario where renegotiation messages and application messages are sent at the same time. It is expected that the server processes renegotiation messages first. * @preconan * @short * @ Previous Level 1 * @autotrue @ */ /* BEGIN_CASE */ void SDV_TLS_DTLS_CONSISTENCY_RFC5246_UNEXPETED_REORD_TYPE_TC001() { int version = TLS1_2; int connType = TCP; Process *localProcess = NULL; Process *remoteProcess = NULL; HLT_FD sockFd = {0}; HITLS_Session *session = NULL; TLS_TYPE local = HITLS; TLS_TYPE remote = HITLS; int32_t serverConfigId = 0; localProcess = HLT_InitLocalProcess(local); ASSERT_TRUE(localProcess != NULL); remoteProcess = HLT_CreateRemoteProcess(remote); ASSERT_TRUE(remoteProcess != NULL); void *clientConfig = HLT_TlsNewCtx(version); ASSERT_TRUE(clientConfig != NULL); HLT_Ctx_Config *clientCtxConfig = HLT_NewCtxConfig(NULL, "CLIENT"); HLT_SetRenegotiationSupport(clientCtxConfig, true); HLT_Ctx_Config *serverCtxConfig = HLT_NewCtxConfig(NULL, "SERVER"); HLT_SetRenegotiationSupport(serverCtxConfig, true); #ifdef HITLS_TLS_FEATURE_PROVIDER serverConfigId = HLT_RpcProviderTlsNewCtx(remoteProcess, version, false, NULL, NULL, NULL, 0, NULL); #else serverConfigId = HLT_RpcTlsNewCtx(remoteProcess, version, false); #endif HLT_SetClientRenegotiateSupport(serverCtxConfig, true); ASSERT_TRUE(HLT_TlsSetCtx(clientConfig, clientCtxConfig) == 0); ASSERT_TRUE(HLT_RpcTlsSetCtx(remoteProcess, serverConfigId, serverCtxConfig) == 0); DataChannelParam channelParam; channelParam.port = 1666; 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); ASSERT_TRUE(HITLS_Renegotiate(clientSsl) == HITLS_SUCCESS); const char *writeBuf = "Hello world"; pthread_t thrd; ASSERT_TRUE(pthread_create(&thrd, NULL, (void *)Hello, clientSsl) == 0); sleep(2); uint8_t readBuf[BUF_SIZE_DTO_TEST] = {0}; uint32_t readLen; ASSERT_TRUE(memset_s(readBuf, BUF_SIZE_DTO_TEST, 0, BUF_SIZE_DTO_TEST) == EOK); ASSERT_TRUE(HLT_RpcTlsRead(remoteProcess, serverSslId, readBuf, BUF_SIZE_DTO_TEST, &readLen) == 0); pthread_join(thrd, NULL); 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); EXIT: ClearWrapper(); HLT_CleanFrameHandle(); HITLS_SESS_Free(session); HLT_FreeAllProcess(); } /* END_CASE */ static void Test_CertificateParse001(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_DTLS12; FRAME_Msg frameMsg = { 0 }; frameMsg.recType.data = REC_TYPE_HANDSHAKE; frameMsg.length.data = *len; frameMsg.recVersion.data = HITLS_VERSION_DTLS12; uint32_t parseLen = 0; FRAME_ParseMsgBody(&frameType, data, *len, &frameMsg, &parseLen); ASSERT_EQ(frameMsg.body.hsMsg.type.data, SERVER_HELLO_DONE); int *t = (int*)user; if (*t == 0) { // Change the sequence number to 20 data[5] = 20; } (*t)++; EXIT: FRAME_CleanMsg(&frameType, &frameMsg); return; } static uint32_t DtlsTimerCallBack(HITLS_Ctx *ctx, uint32_t us) { (void)ctx; (void)us; return 1000000; // timeout value is 1 second. } /* @ * @test SDV_TLS_DTLS_CONSISTENCY_RFC6347_MTU_TC001 * @title Multiple timeout retransmissions result in a decrease in MTU * @precon nan * @brief 1. Establish a link using UDP with dtls12 and construct timeout retransmission three times. Expected result 1 is obtained. * @expect 1. MTU reduced from 1472 to 548 @ */ /* BEGIN_CASE */ void SDV_TLS_DTLS_CONSISTENCY_RFC6347_MTU_TC001() { int32_t port = 18888; HLT_Process *localProcess = HLT_InitLocalProcess(HITLS); HLT_Process *remoteProcess = HLT_LinkRemoteProcess(HITLS, UDP, port, true); ASSERT_TRUE(localProcess != NULL); ASSERT_TRUE(remoteProcess != NULL); HLT_Ctx_Config *serverCtxConfig = NULL; HLT_Ctx_Config *clientCtxConfig = NULL; serverCtxConfig = HLT_NewCtxConfig(NULL, "SERVER"); clientCtxConfig = HLT_NewCtxConfig(NULL, "CLIENT"); ASSERT_TRUE(serverCtxConfig != NULL); ASSERT_TRUE(clientCtxConfig != NULL); int32_t user = 0; RecWrapper wrapper = { TRY_SEND_SERVER_HELLO_DONE, REC_TYPE_HANDSHAKE, false, &user, Test_CertificateParse001 }; RegisterWrapper(wrapper); HLT_Tls_Res *tlsRes = HLT_ProcessTlsInit(localProcess, DTLS1_2, serverCtxConfig, NULL); ASSERT_TRUE(tlsRes != NULL); HITLS_SetDtlsTimerCb(tlsRes->ssl, DtlsTimerCallBack); (void)HLT_TlsAccept(tlsRes->ssl); HITLS_Ctx *ctx = tlsRes->ssl; HITLS_SetNoQueryMtu(ctx, false); ASSERT_EQ(ctx->config.pmtu, 1472); HLT_Tls_Res *clientRes = HLT_ProcessTlsConnect(remoteProcess, DTLS1_2, clientCtxConfig, NULL); ASSERT_TRUE(clientRes == NULL); ASSERT_EQ(ctx->config.pmtu, 548); EXIT: ClearWrapper(); HLT_FreeAllProcess(); } /* END_CASE */ int32_t STUB_REC_Write(TLS_Ctx *ctx, REC_Type recordType, const uint8_t *data, uint32_t num) { static int32_t count = 0; if (data[0] == CERTIFICATE && count == 0) { int32_t hsFragmentLength = BSL_ByteToUint24(&data[DTLS_HS_FRAGMENT_LEN_ADDR]); int32_t fragmentLength = hsFragmentLength + DTLS_HS_MSG_HEADER_SIZE + REC_DTLS_RECORD_HEADER_LEN; // On the third retransmission, the message length became 548 ASSERT_EQ(fragmentLength, 548); count++; } return ctx->recCtx->recWrite(ctx, recordType, data, num); EXIT: return -1; } static void Test_Timeout001(HITLS_Ctx *ctx, uint8_t *data, uint32_t *len, uint32_t bufSize, void *user) { (void)data; (void)len; (void)bufSize; (void)user; sleep(1); ASSERT_EQ(HITLS_DtlsProcessTimeout(ctx), HITLS_SUCCESS); sleep(2); ASSERT_EQ(HITLS_DtlsProcessTimeout(ctx), HITLS_SUCCESS); FuncStubInfo stubInfo = {0}; STUB_Replace(&stubInfo, REC_Write, STUB_REC_Write); sleep(4); ASSERT_EQ(HITLS_DtlsProcessTimeout(ctx), HITLS_SUCCESS); EXIT: STUB_Reset(&stubInfo); return; } /* @ * @test SDV_TLS_DTLS_CONSISTENCY_RFC6347_MTU_TC002 * @title Multiple timeout retransmissions result in a decrease in MTU * @precon nan * @brief 1. Establish a link using UDP with dtls12 and construct timeout retransmission three times. Expected result 1 is obtained. * @expect 1. MTU reduced from 1472 to 548. On the third retransmission, the message length became 548 @ */ /* BEGIN_CASE */ void SDV_TLS_DTLS_CONSISTENCY_RFC6347_MTU_TC002() { HLT_ConfigTimeOut("10"); int32_t port = 18888; HLT_Process *localProcess = HLT_InitLocalProcess(HITLS); HLT_Process *remoteProcess = HLT_LinkRemoteProcess(HITLS, UDP, port, true); ASSERT_TRUE(localProcess != NULL); ASSERT_TRUE(remoteProcess != NULL); HLT_Ctx_Config *serverCtxConfig = NULL; HLT_Ctx_Config *clientCtxConfig = NULL; serverCtxConfig = HLT_NewCtxConfig(NULL, "SERVER"); clientCtxConfig = HLT_NewCtxConfig(NULL, "CLIENT"); ASSERT_TRUE(serverCtxConfig != NULL); ASSERT_TRUE(clientCtxConfig != NULL); RecWrapper wrapper = {TRY_RECV_CLIENT_KEY_EXCHANGE, REC_TYPE_HANDSHAKE, true, NULL, Test_Timeout001}; RegisterWrapper(wrapper); HLT_Tls_Res *serverRes = HLT_ProcessTlsAccept(localProcess, DTLS1_2, serverCtxConfig, NULL); ASSERT_TRUE(serverRes != NULL); HLT_Tls_Res *clientRes = HLT_ProcessTlsConnect(remoteProcess, DTLS1_2, clientCtxConfig, NULL); ASSERT_TRUE(clientRes != NULL); ASSERT_TRUE(HLT_GetTlsAcceptResult(serverRes) == 0); uint8_t readData[REC_MAX_PLAIN_LENGTH] = {0}; uint32_t readLen = REC_MAX_PLAIN_LENGTH; ASSERT_EQ(HLT_ProcessTlsWrite(localProcess, serverRes, (uint8_t *)"Hello World", strlen("Hello World")), 0); ASSERT_EQ(HLT_ProcessTlsRead(remoteProcess, clientRes, readData, readLen, &readLen), 0); ASSERT_EQ(readLen, strlen("Hello World")); ASSERT_EQ(memcmp("Hello World", readData, readLen), 0); EXIT: ClearWrapper(); HLT_FreeAllProcess(); } /* END_CASE */
2301_79861745/bench_create
testcode/sdv/testcase/tls/consistency/dtls12/test_suite_sdv_hlt_dtls12_consistency.c
C
unknown
11,386
/* * This file is part of the openHiTLS project. * * openHiTLS is licensed under the Mulan PSL v2. * You can use this software according to the terms and conditions of the Mulan PSL v2. * You may obtain a copy of Mulan PSL v2 at: * * http://license.coscl.org.cn/MulanPSL2 * * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, * EITHER EXPRESS 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 <unistd.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 "session_type.h" #include "hitls_type.h" #include "pack.h" #include "send_process.h" #include "frame_tls.h" #include "frame_link.h" #include "frame_io.h" #include "uio_base.h" #include "simulate_io.h" #include "parser_frame_msg.h" #include "pack_frame_msg.h" #include "cert.h" #include "app.h" #include "hlt.h" #include "alert.h" #include "securec.h" #include "record.h" #include "rec_write.h" #include "rec_read.h" #include "rec_wrapper.h" #include "hitls_crypt_init.h" #include "conn_init.h" #include "cert_callback.h" #include "change_cipher_spec.h" #include "common_func.h" #include "crypt_default.h" #include "stub_crypt.h" #ifdef HITLS_TLS_FEATURE_PROVIDER #include "hitls_crypt.h" #endif #define PORT 11111 #define TEMP_DATA_LEN 1024 /* Length of a single message. */ #define MAX_BUF_LEN (20 * 1024) #define READ_BUF_SIZE (18 * 1024) /* Maximum length of the read message buffer */ #define ALERT_BODY_LEN 2u #define REC_CONN_SEQ_SIZE 8u /* SN size */ #define GetEpochSeq(epoch, seq) (((uint64_t)(epoch) << 48) | (seq)) #define BUF_TOOLONG_LEN ((1 << 14) + 1) typedef struct { uint16_t version; BSL_UIO_TransportType uioType; HITLS_Config *config; FRAME_LinkObj *client; FRAME_LinkObj *server; HITLS_Session *clientSession; /* session set to the client, used for session recovery. */ } ResumeTestInfo; typedef struct { int connectExpect; // Expected connect result int acceptExpect; // Expected accept result ALERT_Level expectLevel; // Expected alert level ALERT_Description expectDescription; // Expected alert description of the tested end } TestExpect; 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; uint16_t GetCipherSuite(const char *cipherSuite) { if (strcmp(cipherSuite, "HITLS_ECDHE_SM4_CBC_SM3") == 0) { return HITLS_ECDHE_SM4_CBC_SM3; } if (strcmp(cipherSuite, "HITLS_ECC_SM4_CBC_SM3") == 0) { return HITLS_ECC_SM4_CBC_SM3; } return 0; } 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; } int32_t GenerateEccPremasterSecret(TLS_Ctx *ctx); int32_t RecordDecryptPrepare( TLS_Ctx *ctx, uint16_t version, REC_Type recordType, REC_TextInput *cryptMsg); int32_t RecConnDecrypt( TLS_Ctx *ctx, RecConnState *state, const REC_TextInput *cryptMsg, uint8_t *data, uint32_t *dataLen); int32_t STUB_GenerateEccPremasterSecret(TLS_Ctx *ctx) { uint32_t offset; HS_Ctx *hsCtx = ctx->hsCtx; KeyExchCtx *kxCtx = hsCtx->kxCtx; uint8_t *premasterSecret = kxCtx->keyExchParam.ecc.preMasterSecret; /* The first two bytes are the latest version supported by the client.*/ /* Change the version number and construct an exception. */ BSL_Uint16ToByte(0x0505, premasterSecret); offset = sizeof(uint16_t); /* 46 bytes secure random number */ #ifdef HITLS_TLS_FEATURE_PROVIDER return HITLS_CRYPT_RandbytesEx(NULL, &premasterSecret[offset], MASTER_SECRET_LEN - offset); #else return CRYPT_DEFAULT_RandomBytes(&premasterSecret[offset], MASTER_SECRET_LEN - offset); #endif } int32_t STUB_TlsRecordRead(TLS_Ctx *ctx, REC_Type recordType, uint8_t *data, uint32_t *readLen, uint32_t num) { int32_t ret; (void)recordType; (void)readLen; RecConnState *state = ctx->recCtx->readStates.currentState; uint16_t version = ctx->negotiatedInfo.version; REC_TextInput encryptedMsg = {0}; ret = RecordDecryptPrepare(ctx, version, recordType, &encryptedMsg); if (ret != HITLS_SUCCESS) { return ret; } uint32_t dataLen = num; ASSERT_EQ(encryptedMsg.textLen, num); ret = RecConnDecrypt(ctx, state, &encryptedMsg, data, &dataLen); EXIT: return ret; } int32_t StatusGMPark(HandshakeTestInfo *testInfo) { testInfo->client = FRAME_CreateTLCPLink(testInfo->config, BSL_UIO_TCP, true); if (testInfo->client == NULL) { return HITLS_INTERNAL_EXCEPTION; } testInfo->server = FRAME_CreateTLCPLink(testInfo->config, BSL_UIO_TCP, false); if (testInfo->server == NULL) { return HITLS_INTERNAL_EXCEPTION; } 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(); testInfo->config = HITLS_CFG_NewTLCPConfig(); 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 StatusGMPark(testInfo); } int32_t DefaultCfgStatusParkWithSuite(HandshakeTestInfo *testInfo) { FRAME_Init(); testInfo->config = HITLS_CFG_NewTLCPConfig(); if (testInfo->config == NULL) { return HITLS_INTERNAL_EXCEPTION; } HITLS_CFG_SetCheckKeyUsage(testInfo->config, false); uint16_t cipherSuits[] = {HITLS_ECDHE_SM4_CBC_SM3}; 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 StatusGMPark(testInfo); } 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; }
2301_79861745/bench_create
testcode/sdv/testcase/tls/consistency/tlcp/test_suite_sdv_frame_tlcp_consistency.base.c
C
unknown
7,359
/* * This file is part of the openHiTLS project. * * openHiTLS is licensed under the Mulan PSL v2. * You can use this software according to the terms and conditions of the Mulan PSL v2. * You may obtain a copy of Mulan PSL v2 at: * * http://license.coscl.org.cn/MulanPSL2 * * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. * See the Mulan PSL v2 for more details. */ /* BEGIN_HEADER */ /* INCLUDE_BASE test_suite_sdv_frame_tlcp_consistency */ /* END_HEADER */ /* @ * @test UT_TLS_TLCP_CONSISTENCY_UNEXPECT_RECORDTYPE_TC001 * @title After initialization, the server receives a CCS message after sending the serverhellodone message and return * an alert message. * @precon nan * @brief 1. Use the default configuration on the client and server. Expected result 1. * 2. During the handshake, after sending the Server Hello Done message, the server * constructs a CCS message and sends it to the server. Expected result 2. * @expect 1. The initialization is successful. * 2. The server sends the ALERT_UNEXPECTED_MESSAGE message. @ */ /* BEGIN_CASE */ void UT_TLS_TLCP_CONSISTENCY_UNEXPECT_RECORDTYPE_TC001(void) { HandshakeTestInfo testInfo = { 0 }; testInfo.state = TRY_RECV_CLIENT_KEY_EXCHANGE; testInfo.isClient = false; ASSERT_TRUE(DefaultCfgStatusParkWithSuite(&testInfo) == HITLS_SUCCESS); FRAME_Msg frameMsg = { 0 }; FRAME_Type frameType = { 0 }; frameType.versionType = HITLS_VERSION_TLCP_DTLCP11; frameType.recordType = REC_TYPE_CHANGE_CIPHER_SPEC; 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); 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); 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; 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_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); FRAME_DeRegCryptMethod(); } /* END_CASE */ /* @ * @test UT_TLS_TLCP_CONSISTENCY_UNEXPECT_RECORDTYPE_TC002 * @title After initialization, the client receives a CCS message after sending a client hello message and returns an * alert message * @precon nan * @brief 1. Use the default configuration on the client and server. Expected result 1. * 2. During the handshake, after sending the client hello message, constructs a CCS message and sends it to the * client. Expected result 2. * @expect 1. The initialization is successful. * 2. The client sends the ALERT_UNEXPECTED_MESSAGE message. @ */ /* BEGIN_CASE */ void UT_TLS_TLCP_CONSISTENCY_UNEXPECT_RECORDTYPE_TC002(void) { HandshakeTestInfo testInfo = { 0 }; testInfo.state = TRY_RECV_SERVER_HELLO; testInfo.isClient = true; ASSERT_TRUE(DefaultCfgStatusPark(&testInfo) == HITLS_SUCCESS); FRAME_Msg frameMsg = { 0 }; FRAME_Type frameType = { 0 }; frameType.versionType = HITLS_VERSION_TLCP_DTLCP11; frameType.recordType = REC_TYPE_CHANGE_CIPHER_SPEC; 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); 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); 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_TRUE(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); FRAME_DeRegCryptMethod(); } /* END_CASE */ /* @ * @test UT_TLS_TLCP_CONSISTENCY_UNEXPECT_RECORDTYPE_TC003 * @title During connection establishment, the client receives the serverhello message after sending the CCS message and * expects to return an alert message. * @precon nan * @brief 1. Use the default configuration on the client and server. Expected result 1. * 2. During the handshake, after client sending the CCS, constructs a serverhello message and sends it to the * client. Expected result 2. * @expect 1. The initialization is successful. * 2. The client sends the ALERT_UNEXPECTED_MESSAGE message. @ */ /* BEGIN_CASE */ void UT_TLS_TLCP_CONSISTENCY_UNEXPECT_RECORDTYPE_TC003(void) { HandshakeTestInfo testInfo = { 0 }; testInfo.state = TRY_SEND_CHANGE_CIPHER_SPEC; testInfo.isClient = true; ASSERT_TRUE(DefaultCfgStatusParkWithSuite(&testInfo) == HITLS_SUCCESS); testInfo.client->ssl->hsCtx->state = TRY_RECV_FINISH; FRAME_Msg frameMsg = { 0 }; FRAME_Type frameType = { 0 }; frameType.versionType = HITLS_VERSION_TLCP_DTLCP11; frameType.recordType = REC_TYPE_HANDSHAKE; frameType.handshakeType = SERVER_HELLO; frameType.keyExType = HITLS_KEY_EXCH_ECDHE; ASSERT_EQ(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); 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); ASSERT_EQ(HITLS_Connect(testInfo.client->ssl), HITLS_MSG_HANDLE_UNEXPECTED_MESSAGE); 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_TRUE(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); FRAME_DeRegCryptMethod(); } /* END_CASE */ /* @ * @test UT_TLS_TLCP_CONSISTENCY_UNEXPECT_RECORDTYPE_TC004 * @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. Expected result 1. * 2. Durintg the handshake, When the client is in the TRY_RECV_SERVER_HELLO state, construct an APP data message * and send it to the client. Expected result 2. * @expect 1. The initialization is successful. * 2. The client sends the ALERT_UNEXPECTED_MESSAGE message. @ */ /* BEGIN_CASE */ void UT_TLS_TLCP_CONSISTENCY_UNEXPECT_RECORDTYPE_TC004(void) { FRAME_Msg frameMsg = { 0 }; FRAME_Type frameType = { 0 }; HandshakeTestInfo testInfo = { 0 }; FRAME_Init(); testInfo.config = HITLS_CFG_NewTLCPConfig(); ASSERT_TRUE(testInfo.config != NULL); testInfo.client = FRAME_CreateTLCPLink(testInfo.config, BSL_UIO_TCP, true); ASSERT_TRUE(testInfo.client != NULL); testInfo.server = FRAME_CreateTLCPLink(testInfo.config, BSL_UIO_TCP, false); ASSERT_TRUE(testInfo.server != NULL); ASSERT_TRUE(testInfo.client->ssl->state == CM_STATE_IDLE); uint8_t appdata[] = {0x17, 0x01, 0x01, 0x00, 0x02, 0x01, 0x01}; FrameUioUserData *ioUserData = BSL_UIO_GetUserData(testInfo.client->io); uint8_t data[MAX_RECORD_LENTH] = {0}; uint32_t len = MAX_RECORD_LENTH; 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_IO_BUSY); ASSERT_TRUE(FRAME_TrasferMsgBetweenLink(testInfo.client, testInfo.server) == HITLS_SUCCESS); ASSERT_TRUE(testInfo.client->ssl->state == CM_STATE_ALERTING); ASSERT_EQ(HITLS_Connect(testInfo.client->ssl), HITLS_CM_LINK_FATAL_ALERTED); ASSERT_TRUE(testInfo.client->ssl->state == CM_STATE_ALERTED); 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); 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_TLCP_CONSISTENCY_UNEXPECT_RECORDTYPE_TC005 * @title After the connection is established, the client receives the serverhello message after 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. Expected result 1. * 2. The client initiates a TLS conncetion request. After the handshake succeeds, constructs a serverhello * message and sends it to the client. Expected result 2. * @expect 1. The initialization is successful. * 2. The client sends the ALERT_UNEXPECTED_MESSAGE message. @ */ /* BEGIN_CASE */ void UT_TLS_TLCP_CONSISTENCY_UNEXPECT_RECORDTYPE_TC005(void) { FRAME_Init(); HITLS_Config *config = NULL; FRAME_LinkObj *client = NULL; FRAME_LinkObj *server = NULL; FRAME_Msg recvframeMsg = { 0 }; config = HITLS_CFG_NewTLCPConfig(); ASSERT_TRUE(config != NULL); client = FRAME_CreateTLCPLink(config, BSL_UIO_TCP, true); ASSERT_TRUE(client != NULL); server = FRAME_CreateTLCPLink(config, BSL_UIO_TCP, false); ASSERT_TRUE(server != NULL); ASSERT_EQ(FRAME_CreateConnection(client, server, true, HS_STATE_BUTT), HITLS_SUCCESS); ASSERT_TRUE(client->ssl->state == CM_STATE_TRANSPORTING); FRAME_Msg frameMsg = { 0 }; FRAME_Type frameType = { 0 }; SetFrameType(&frameType, HITLS_VERSION_TLCP_DTLCP11, REC_TYPE_HANDSHAKE, SERVER_HELLO, HITLS_KEY_EXCH_ECDHE); ASSERT_TRUE(FRAME_GetDefaultMsg(&frameType, &frameMsg) == HITLS_SUCCESS); /* Reassembly */ uint32_t sendLen = MAX_RECORD_LENTH; uint8_t sendBuf[MAX_RECORD_LENTH] = {0}; ASSERT_TRUE(FRAME_PackMsg(&frameType, &frameMsg, sendBuf, sendLen, &sendLen) == HITLS_SUCCESS); ASSERT_TRUE(FRAME_TransportRecMsg(client->io, sendBuf, sendLen) == HITLS_SUCCESS); FRAME_CleanMsg(&frameType, &frameMsg); memset_s(&frameMsg, sizeof(frameMsg), 0, sizeof(frameMsg)); uint8_t readBuf[READ_BUF_SIZE] = {0}; uint32_t readLen = 0; ASSERT_EQ(HITLS_Read(client->ssl, readBuf, READ_BUF_SIZE, &readLen), HITLS_REC_BAD_RECORD_MAC); 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; ASSERT_EQ(FRAME_ParseMsgHeader(&frameType, sndBuf, sndLen, &frameMsg, &parseLen), 0); ASSERT_TRUE(frameMsg.recType.data == REC_TYPE_ALERT); EXIT: CleanRecordBody(&recvframeMsg); HITLS_CFG_FreeConfig(config); FRAME_FreeLink(client); FRAME_FreeLink(server); } /* END_CASE */ /* @ * @test UT_TLS_TLCP_CONSISTENCY_UNEXPECT_RECORDTYPE_TC006 * @title After the link is established, renegotiation is not enabled. The server receives the client keyexchange message * and is expected to return an alert message. * @precon nan * @brief 1. Use the default configuration on the client and server. Expected result 1. * 2. After the client initiates a TLS link request. After the handshake succeeds, construct a clientkeyexchange * message and send it to the server. Expected result 2. * @expect 1. The initialization is successful. * 2. The server sends the ALERT_UNEXPECTED_MESSAGE message. @ */ /* BEGIN_CASE */ void UT_TLS_TLCP_CONSISTENCY_UNEXPECT_RECORDTYPE_TC006(void) { FRAME_Init(); HITLS_Config *config = NULL; FRAME_LinkObj *client = NULL; FRAME_LinkObj *server = NULL; FRAME_Msg recvframeMsg = { 0 }; config = HITLS_CFG_NewTLCPConfig(); ASSERT_TRUE(config != NULL); client = FRAME_CreateTLCPLink(config, BSL_UIO_TCP, true); ASSERT_TRUE(client != NULL); server = FRAME_CreateTLCPLink(config, BSL_UIO_TCP, false); ASSERT_TRUE(server != NULL); ASSERT_EQ(FRAME_CreateConnection(client, server, true, HS_STATE_BUTT), HITLS_SUCCESS); ASSERT_TRUE(client->ssl->state == CM_STATE_TRANSPORTING); uint8_t data[5] = {0x10, 0x00, 0x00, 0x01, 0x01}; ASSERT_EQ(REC_Write(client->ssl, 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_EQ(HITLS_Read(server->ssl, readBuf, READ_BUF_SIZE, &readLen), HITLS_MSG_HANDLE_UNEXPECTED_MESSAGE); 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: CleanRecordBody(&recvframeMsg); HITLS_CFG_FreeConfig(config); FRAME_FreeLink(client); FRAME_FreeLink(server); } /* END_CASE */ /* @ * @test UT_TLS_TLCP_CONSISTENCY_UNEXPECT_RECORDTYPE_TC007 * @title After initialization, construct an app message and send it to the server. Expected alert is returned. * @precon nan * @brief 1. Use the default configuration on the client and server. Expected result 1. * 2. When the client initiates a TLS link application request in the RECV_CLIENT_HELLO message on the server, * construct an APP message and send it to the server. Expected result 2. * @expect 1. The initialization is successful. * 2. The server sends the ALERT_UNEXPECTED_MESSAGE message. @ */ /* BEGIN_CASE */ void UT_TLS_TLCP_CONSISTENCY_UNEXPECT_RECORDTYPE_TC007(void) { FRAME_Msg frameMsg = { 0 }; FRAME_Type frameType = { 0 }; HandshakeTestInfo testInfo = { 0 }; FRAME_Init(); testInfo.config = HITLS_CFG_NewTLCPConfig(); ASSERT_TRUE(testInfo.config != NULL); testInfo.client = FRAME_CreateTLCPLink(testInfo.config, BSL_UIO_TCP, true); ASSERT_TRUE(testInfo.client != NULL); testInfo.server = FRAME_CreateTLCPLink(testInfo.config, BSL_UIO_TCP, false); ASSERT_TRUE(testInfo.server != NULL); ASSERT_TRUE(testInfo.server->ssl->state == CM_STATE_IDLE); 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, 0x01, 0x01, 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; 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_TLCP_CONSISTENCY_UNKNOW_RECORDTYPE_TC01 * @spec 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. * If an unrecognized record type is received, ignore it. * @title There are only four types of record layers. * @precon nan * @brief 1. Use the default configuration on the client and server. Expected result 1. * 2. When the client is in TRY_RECV_SERVER_HELLO state,receives the serverhello message whose recordType is 99, * Expected result 2. * @expect 1. The initialization is successful. * 2. The client sends the ALERT_UNEXPECTED_MESSAGE message. @ */ /* BEGIN_CASE */ void UT_TLS_TLCP_CONSISTENCY_UNKNOW_RECORDTYPE_TC01(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, TRY_RECV_SERVER_HELLO), HITLS_SUCCESS); FrameUioUserData *ioClientData = BSL_UIO_GetUserData(client->io); ioClientData->recMsg.msg[0] = 0x99u; ASSERT_EQ(HITLS_Connect(client->ssl), 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_TLCP_CONSISTENCY_UNKNOW_RECORDTYPE_TC02 * @spec 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 de-assigned in addition to the Content Type values assigned for the types * described above. * If an unrecognized record type is received, ignore it. * @title There are only four types of record layers. * @precon nan * @brief 1. Use the default configuration on the client and server. Expected result 1. * 2. After the connection is established, the client receives abnormal messages (recordType: 99) after receiving * the app data. Expected result 2. * @expect 1. The initialization is successful. * 2. The client sends the ALERT_UNEXPECTED_MESSAGE message. @ */ /* BEGIN_CASE */ void UT_TLS_TLCP_CONSISTENCY_UNKNOW_RECORDTYPE_TC02(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(server->ssl, dataBuf, sizeof(dataBuf), &writeLen), HITLS_SUCCESS); ASSERT_TRUE(FRAME_TrasferMsgBetweenLink(server, client) == HITLS_SUCCESS); FrameUioUserData *ioClientData = BSL_UIO_GetUserData(client->io); ioClientData->recMsg.msg[0] = 0x99u; ASSERT_EQ(HITLS_Read(client->ssl, readBuf, READ_BUF_SIZE, &readbytes), 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_TLCP_CONSISTENCY_UNKNOW_RECORDTYPE_TC03 * @spec 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. * If an unrecognized record type is received, ignore it. * @title There are only four types of record layers. * @precon nan * @brief 1. Use the default configuration on the client and server. Expected result 1. * 2. When the server is in TRY_RECV_CLIENT_HELLO state, the server receives the client hello message whose * recordType is 99. Expected result 2. * @expect 1. The initialization is successful. * 2. The server sends the ALERT_UNEXPECTED_MESSAGE message. @ */ /* BEGIN_CASE */ void UT_TLS_TLCP_CONSISTENCY_UNKNOW_RECORDTYPE_TC03(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, false, TRY_RECV_CLIENT_HELLO), HITLS_SUCCESS); FrameUioUserData *ioServerData = BSL_UIO_GetUserData(server->io); ioServerData->recMsg.msg[0] = 0x99u; 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_TLCP_CONSISTENCY_UNKNOW_RECORDTYPE_TC04 * @spec 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. * If an unrecognized record type is received, ignore it. * @title There are only four types of record layers. * @precon nan * @brief 1. Use the default configuration on the client and server. Expected result 1. * 2. After the connection is established, the server receives abnormal messages (recordType: 99) after receiving * the app data. Expected result 2. * @expect 1. The initialization is successful. * 2. The server sends the ALERT_UNEXPECTED_MESSAGE message. @ */ /* BEGIN_CASE */ void UT_TLS_TLCP_CONSISTENCY_UNKNOW_RECORDTYPE_TC04(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_TLCP_CONSISTENCY_UNEXPECT_HANDSHAKEMSG_TC001 * @title An unexpected message is received when the client is in the TRY_RECV_CERTIFICATIONATE state during the * handshake. * @precon nan * @brief 1. Use the default configuration items to configure the client and server. Expected result 1. * 2. When the client is in the TRY_RECV_CERTIFICATIONATE state, construct a Server Hello message and send it to * the client. Expected result 2. * @expect 1. The initialization is successful. * 2. After receiving the Server Hello message, the client sends an ALERT. The level is ALERT_LEVEL_FATAL and * the description is ALERT_UNEXPECTED_MESSAGE. @ */ /* BEGIN_CASE */ void UT_TLS_TLCP_CONSISTENCY_UNEXPECT_HANDSHAKEMSG_TC001(int version) { FRAME_Init(); HITLS_Config *config = NULL; FRAME_LinkObj *client = NULL; FRAME_LinkObj *server = NULL; config = HITLS_CFG_NewTLCPConfig(); ASSERT_TRUE(config != NULL); config->isSupportExtendMasterSecret = true; config->isSupportClientVerify = true; config->isSupportNoClientCert = false; config->isSupportRenegotiation = true; client = FRAME_CreateTLCPLink(config, BSL_UIO_TCP, true); server = FRAME_CreateTLCPLink(config, BSL_UIO_TCP, false); ASSERT_EQ(FRAME_CreateConnection(client, server, true, TRY_RECV_CERTIFICATE), HITLS_SUCCESS); FRAME_Msg frameMsg = { 0 }; FRAME_Type frameType = { 0 }; frameType.versionType = version; frameType.recordType = REC_TYPE_HANDSHAKE; frameType.handshakeType = SERVER_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); FrameUioUserData *ioUserData = BSL_UIO_GetUserData(client->io); 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_TRUE(client->ssl != NULL); ASSERT_EQ(HITLS_Connect(client->ssl), HITLS_MSG_HANDLE_UNEXPECTED_MESSAGE); 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; 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_TRUE(alertMsg->alertDescription.data == ALERT_UNEXPECTED_MESSAGE); EXIT: FRAME_CleanMsg(&frameType, &frameMsg); HITLS_CFG_FreeConfig(config); FRAME_FreeLink(client); FRAME_FreeLink(server); } /* END_CASE */ /* @ * @test UT_TLS_TLCP_CONSISTENCY_UNEXPECT_HANDSHAKEMSG_TC002 * @title An unexpected message is received when the client is in the TRY_RECV_SERVER_KEY_EXCHANGE state during the * handshake. * @precon nan * @brief 1. Use the default configuration items to configure the client and server. Expected result 1. * 2. When the client is in the TRY_RECV_SERVER_KEY_EXCHANGE state, construct a Server Hello message and send it * to the client. Expected result 2. * @expect 1. The initialization is successful. * 2. After receiving the Server Hello message, the client sends an ALERT message. The level is ALERT_Level_FATAL * and the description is ALERT_UNEXPECTED_MESSAGE. @ */ /* BEGIN_CASE */ void UT_TLS_TLCP_CONSISTENCY_UNEXPECT_HANDSHAKEMSG_TC002(int version) { FRAME_Init(); HITLS_Config *config = NULL; FRAME_LinkObj *client = NULL; FRAME_LinkObj *server = NULL; config = HITLS_CFG_NewTLCPConfig(); ASSERT_TRUE(config != NULL); config->isSupportExtendMasterSecret = true; config->isSupportClientVerify = true; config->isSupportNoClientCert = false; config->isSupportRenegotiation = true; client = FRAME_CreateTLCPLink(config, BSL_UIO_TCP, true); server = FRAME_CreateTLCPLink(config, BSL_UIO_TCP, false); ASSERT_EQ(FRAME_CreateConnection(client, server, true, TRY_RECV_SERVER_KEY_EXCHANGE), HITLS_SUCCESS); FRAME_Msg frameMsg = { 0 }; FRAME_Type frameType = { 0 }; frameType.versionType = version; frameType.recordType = REC_TYPE_HANDSHAKE; frameType.handshakeType = SERVER_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); FrameUioUserData *ioUserData = BSL_UIO_GetUserData(client->io); 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_TRUE(client->ssl != NULL); ASSERT_EQ(HITLS_Connect(client->ssl), HITLS_MSG_HANDLE_UNEXPECTED_MESSAGE); 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; 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_TRUE(alertMsg->alertDescription.data == ALERT_UNEXPECTED_MESSAGE); EXIT: FRAME_CleanMsg(&frameType, &frameMsg); HITLS_CFG_FreeConfig(config); FRAME_FreeLink(client); FRAME_FreeLink(server); } /* END_CASE */ /* @ * @test UT_TLS_TLCP_CONSISTENCY_UNEXPECT_HANDSHAKEMSG_TC003 * @title An unexpected message is received when the client is in the TRY_RECV_SERVER_HELLO_DONE state during the * handshake. * @precon nan * @brief 1. Use the default configuration items to configure the client and server. Expected result 1. * 2. When the client is in the TRY_RECV_SERVER_HELLO_DONE state, construct a Server Hello message and send it to * the client. Expected result 2. * @expect 1. The initialization is successful. * 2. After receiving the Server Hello message, the client sends an ALERT message. The level is ALERT_LEVEL_FATAL * and the description is ALERT_UNEXPECTED_MESSAGE. @ */ /* BEGIN_CASE */ void UT_TLS_TLCP_CONSISTENCY_UNEXPECT_HANDSHAKEMSG_TC003(int version) { FRAME_Init(); HITLS_Config *config = NULL; FRAME_LinkObj *client = NULL; FRAME_LinkObj *server = NULL; config = HITLS_CFG_NewTLCPConfig(); ASSERT_TRUE(config != NULL); config->isSupportExtendMasterSecret = true; config->isSupportClientVerify = true; config->isSupportNoClientCert = false; config->isSupportRenegotiation = true; client = FRAME_CreateTLCPLink(config, BSL_UIO_TCP, true); server = FRAME_CreateTLCPLink(config, BSL_UIO_TCP, false); ASSERT_EQ(FRAME_CreateConnection(client, server, true, TRY_RECV_SERVER_HELLO_DONE), HITLS_SUCCESS); FRAME_Msg frameMsg = { 0 }; FRAME_Type frameType = { 0 }; frameType.versionType = version; frameType.recordType = REC_TYPE_HANDSHAKE; frameType.handshakeType = SERVER_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); FrameUioUserData *ioUserData = BSL_UIO_GetUserData(client->io); 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_TRUE(client->ssl != NULL); ASSERT_EQ(HITLS_Connect(client->ssl), HITLS_MSG_HANDLE_UNEXPECTED_MESSAGE); 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; 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_TRUE(alertMsg->alertDescription.data == ALERT_UNEXPECTED_MESSAGE); EXIT: FRAME_CleanMsg(&frameType, &frameMsg); HITLS_CFG_FreeConfig(config); FRAME_FreeLink(client); FRAME_FreeLink(server); } /* END_CASE */ /* @ * @test UT_TLS_TLCP_CONSISTENCY_UNEXPECT_HANDSHAKEMSG_TC004 * @title An unexpected message is received when the client is in the TRY_RECV_FINISH state during the handshake. * @precon nan * @brief 1. Use the default configuration items to configure the client and server. Expected result 1. * 2. When the client is in the TRY_RECV_FINISH state, construct a Server Hello message and send it to the client Expected result 2. * @expect 1. The initialization is successful. * 2. After receiving the Server Hello message, the client sends an ALERT message. The level is ALERT_LEVEL_FATAL * and the description is ALERT_UNEXPECTED_MESSAGE. @ */ /* BEGIN_CASE */ void UT_TLS_TLCP_CONSISTENCY_UNEXPECT_HANDSHAKEMSG_TC004(void) { FRAME_Init(); HITLS_Config *config = NULL; FRAME_LinkObj *client = NULL; FRAME_LinkObj *server = NULL; config = HITLS_CFG_NewTLCPConfig(); client = FRAME_CreateTLCPLink(config, BSL_UIO_TCP, true); server = FRAME_CreateTLCPLink(config, BSL_UIO_TCP, false); HITLS_Ctx *clientTlsCtx = FRAME_GetTlsCtx(client); ASSERT_TRUE(clientTlsCtx->state == CM_STATE_IDLE); ASSERT_EQ(FRAME_CreateConnection(client, server, true, TRY_RECV_SERVER_HELLO), HITLS_SUCCESS); FrameUioUserData *ioUserData = BSL_UIO_GetUserData(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(client, server, true, HS_STATE_BUTT), HITLS_SUCCESS); ASSERT_TRUE(clientTlsCtx->state == CM_STATE_TRANSPORTING); REC_Write(server->ssl, REC_TYPE_HANDSHAKE, sndMsg.msg, sndMsg.len); ASSERT_EQ(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_MSG_HANDLE_UNEXPECTED_MESSAGE); 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(config); FRAME_FreeLink(client); FRAME_FreeLink(server); } /* END_CASE */ /* @ * @test UT_TLS_TLCP_CONSISTENCY_UNEXPECT_HANDSHAKEMSG_TC005 * @title An unexpected message is received when the client is in the TRY_RECV_CERTIFICATE_REQUEST state during the * handshake. * @precon nan * @brief 1. Use the default configuration items to configure the client and server. Expected result 1. * 2. When the client is in the TRY_RECV_CERTIFICATE_REQUEST state, construct a Server Hello message and send it to the client. Expected result 2. * @expect 1. The initialization is successful. * 2. After receiving the Server Hello message, the client sends an ALERT message. The level is ALERT_LEVEL_FATAL * and the description is ALERT_UNEXPECTED_MESSAGE. @ */ /* BEGIN_CASE */ void UT_TLS_TLCP_CONSISTENCY_UNEXPECT_HANDSHAKEMSG_TC005(int version) { FRAME_Init(); HITLS_Config *config = NULL; FRAME_LinkObj *client = NULL; FRAME_LinkObj *server = NULL; config = HITLS_CFG_NewTLCPConfig(); ASSERT_TRUE(config != NULL); client = FRAME_CreateTLCPLink(config, BSL_UIO_TCP, true); server = FRAME_CreateTLCPLink(config, BSL_UIO_TCP, false); ASSERT_EQ(FRAME_CreateConnection(client, server, true, TRY_RECV_CERTIFICATE_REQUEST), HITLS_SUCCESS); FRAME_Msg frameMsg = { 0 }; FRAME_Type frameType = { 0 }; frameType.versionType = version; frameType.recordType = REC_TYPE_HANDSHAKE; frameType.handshakeType = SERVER_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); FrameUioUserData *ioUserData = BSL_UIO_GetUserData(client->io); 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_TRUE(client->ssl != NULL); ASSERT_EQ(HITLS_Connect(client->ssl), HITLS_MSG_HANDLE_UNEXPECTED_MESSAGE); 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; 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_TRUE(alertMsg->alertDescription.data == ALERT_UNEXPECTED_MESSAGE); EXIT: FRAME_CleanMsg(&frameType, &frameMsg); HITLS_CFG_FreeConfig(config); FRAME_FreeLink(client); FRAME_FreeLink(server); } /* END_CASE */ /* @ * @test UT_TLS_TLCP_CONSISTENCY_UNEXPECT_HANDSHAKEMSG_TC006 * @title An unexpected message is received when the client is in the TRY_RECV_NEW_SESSION_TICKET state during the * handshake. * @precon nan * @brief 1. Use the default configuration items to configure the client and server. Expected result 1. * 2. When the client is in the TRY_RECV_NEW_SESSION_TICKET state, construct a Server Hello message and send it * to the client. Expected result 2. * @expect 1. The initialization is successful. * 2. After receiving the Server Hello message, the client sends an ALERT message. The level is ALERT_LEVEL_FATAL * and the description is ALERT_UNEXPECTED_MESSAGE. @ */ /* BEGIN_CASE */ void UT_TLS_TLCP_CONSISTENCY_UNEXPECT_HANDSHAKEMSG_TC006(int version) { FRAME_Init(); FRAME_Msg frameMsg = { 0 }; FRAME_Type frameType = { 0 }; HITLS_Config *config = NULL; FRAME_LinkObj *client = NULL; FRAME_LinkObj *server = NULL; config = HITLS_CFG_NewTLCPConfig(); ASSERT_TRUE(config != NULL); client = FRAME_CreateTLCPLink(config, BSL_UIO_TCP, true); server = FRAME_CreateTLCPLink(config, BSL_UIO_TCP, false); ASSERT_EQ(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); client->ssl->hsCtx->state = TRY_RECV_NEW_SESSION_TICKET; uint32_t parseLen = 0; frameType.versionType = version; 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); 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_TRUE(client->ssl != NULL); ASSERT_EQ(HITLS_Connect(client->ssl), HITLS_MSG_HANDLE_UNEXPECTED_MESSAGE); ioUserData = BSL_UIO_GetUserData(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_UNEXPECTED_MESSAGE); EXIT: FRAME_CleanMsg(&frameType, &frameMsg); HITLS_CFG_FreeConfig(config); FRAME_FreeLink(client); FRAME_FreeLink(server); } /* END_CASE */ /* @ * @test UT_TLS_TLCP_CONSISTENCY_UNEXPECT_HANDSHAKEMSG_TC007 * @title An unexpected message is received when the server is in the TRY_RECV_CLIENT_HELLO state during the handshake. * @precon nan * @brief 1. Use the default configuration items to configure the client and server. Expected result 1 is obtained. * 2. When the server is in the TRY_RECV_CLIENT_HELLO state, construct a CLIENT_KEY_EXCHANGE message and send it * to the server. Expected result 2 is obtained. * @expect 1. The initialization is successful. * 2. After receiving the CLIENT_KEY_EXCHANGE message, the server sends an ALERT message. The level is * ALERT_Level_FATAL and the description is ALERT_UNEXPECTED_MESSAGE. @ */ /* BEGIN_CASE */ void UT_TLS_TLCP_CONSISTENCY_UNEXPECT_HANDSHAKEMSG_TC007(int version) { FRAME_Init(); FRAME_Msg frameMsg = { 0 }; FRAME_Type frameType = { 0 }; HITLS_Config *config = NULL; FRAME_LinkObj *client = NULL; FRAME_LinkObj *server = NULL; config = HITLS_CFG_NewTLCPConfig(); ASSERT_TRUE(config != NULL); config->isSupportExtendMasterSecret = true; config->isSupportClientVerify = true; config->isSupportNoClientCert = false; config->isSupportRenegotiation = true; client = FRAME_CreateTLCPLink(config, BSL_UIO_TCP, true); server = FRAME_CreateTLCPLink(config, BSL_UIO_TCP, false); ASSERT_EQ(FRAME_CreateConnection(client, server, false, TRY_RECV_CLIENT_KEY_EXCHANGE), 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); server->ssl->hsCtx->state = TRY_RECV_CLIENT_HELLO; uint32_t parseLen = 0; frameType.versionType = version; frameType.recordType = REC_TYPE_HANDSHAKE; frameType.handshakeType = CLIENT_KEY_EXCHANGE; frameType.keyExType = 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); 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_MSG_HANDLE_UNEXPECTED_MESSAGE); ioUserData = BSL_UIO_GetUserData(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_UNEXPECTED_MESSAGE); EXIT: FRAME_CleanMsg(&frameType, &frameMsg); HITLS_CFG_FreeConfig(config); FRAME_FreeLink(client); FRAME_FreeLink(server); } /* END_CASE */ /* @ * @test UT_TLS_TLCP_CONSISTENCY_UNEXPECT_HANDSHAKEMSG_TC008 * @title An unexpected message is received when the server is in the TRY_RECV_CERTIFICATIONATE state during the * handshake. * @precon nan * @brief 1. Use the default configuration items to configure the client and server. Expected result 1. * 2. When the server is in the TRY_RECV_CERTIFICATIONATE state, construct a CLIENT_KEY_EXCHANGE message and send * it to the server. Expected result 2. * @expect 1. The initialization is successful. * 2. After receiving the CLIENT_KEY_EXCHANGE message, the server sends an ALERT message. The level is * ALERT_Level_FATAL and the description is ALERT_UNEXPECTED_MESSAGE. @ */ /* BEGIN_CASE */ void UT_TLS_TLCP_CONSISTENCY_UNEXPECT_HANDSHAKEMSG_TC008(int version) { FRAME_Init(); FRAME_Msg frameMsg = { 0 }; FRAME_Type frameType = { 0 }; HITLS_Config *config = NULL; FRAME_LinkObj *client = NULL; FRAME_LinkObj *server = NULL; config = HITLS_CFG_NewTLCPConfig(); ASSERT_TRUE(config != NULL); config->isSupportExtendMasterSecret = true; config->isSupportClientVerify = true; config->isSupportNoClientCert = false; config->isSupportRenegotiation = true; client = FRAME_CreateTLCPLink(config, BSL_UIO_TCP, true); server = FRAME_CreateTLCPLink(config, BSL_UIO_TCP, false); ASSERT_EQ(FRAME_CreateConnection(client, server, false, TRY_RECV_CLIENT_KEY_EXCHANGE), 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); server->ssl->hsCtx->state = TRY_RECV_CERTIFICATE; uint32_t parseLen = 0; frameType.versionType = version; frameType.recordType = REC_TYPE_HANDSHAKE; frameType.handshakeType = CLIENT_KEY_EXCHANGE; frameType.keyExType = 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); 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_MSG_HANDLE_UNEXPECTED_MESSAGE); ioUserData = BSL_UIO_GetUserData(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_UNEXPECTED_MESSAGE); EXIT: FRAME_CleanMsg(&frameType, &frameMsg); HITLS_CFG_FreeConfig(config); FRAME_FreeLink(client); FRAME_FreeLink(server); } /* END_CASE */ /* @ * @test UT_TLS_TLCP_CONSISTENCY_UNEXPECT_HANDSHAKEMSG_TC009 * @title An unexpected message is received when the server is in the TRY_RECV_CLIENT_KEY_EXCHANGE state during the * handshake. * @precon nan * @brief 1. Use the default configuration items to configure the client and server. Expected result 1. * 2. When the server is in the TRY_RECV_CLIENT_KEY_EXCHANGE state, construct a SERVER_HELLO message and send it * to the server. Expected result 2. * @expect 1. The initialization is successful. * 2. After receiving the SERVER_HELLO message, the server sends an ALERT message. The level is ALERT_Level_FATAL * and the description is ALERT_UNEXPECTED_MESSAGE. @ */ /* BEGIN_CASE */ void UT_TLS_TLCP_CONSISTENCY_UNEXPECT_HANDSHAKEMSG_TC009(int version) { FRAME_Init(); FRAME_Msg frameMsg = { 0 }; FRAME_Type frameType = { 0 }; HITLS_Config *config = NULL; FRAME_LinkObj *client = NULL; FRAME_LinkObj *server = NULL; config = HITLS_CFG_NewTLCPConfig(); ASSERT_TRUE(config != NULL); config->isSupportExtendMasterSecret = true; config->isSupportClientVerify = true; config->isSupportNoClientCert = false; config->isSupportRenegotiation = true; client = FRAME_CreateTLCPLink(config, BSL_UIO_TCP, true); server = FRAME_CreateTLCPLink(config, BSL_UIO_TCP, false); ASSERT_EQ(FRAME_CreateConnection(client, server, false, TRY_RECV_CERTIFICATE), 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); server->ssl->hsCtx->state = TRY_RECV_CLIENT_KEY_EXCHANGE; uint32_t parseLen = 0; frameType.versionType = version; frameType.recordType = REC_TYPE_HANDSHAKE; frameType.handshakeType = CERTIFICATE; frameType.keyExType = 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); 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_MSG_HANDLE_UNEXPECTED_MESSAGE); ioUserData = BSL_UIO_GetUserData(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_UNEXPECTED_MESSAGE); EXIT: FRAME_CleanMsg(&frameType, &frameMsg); HITLS_CFG_FreeConfig(config); FRAME_FreeLink(client); FRAME_FreeLink(server); } /* END_CASE */ /* @ * @test UT_TLS_TLCP_CONSISTENCY_UNEXPECT_HANDSHAKEMSG_TC010 * @title An unexpected message is received when the server is in the TRY_RECV_CERTIFICATIONATE_VERIFY state during the * handshake. * @precon nan * @brief 1. Use the default configuration items to configure the client and server. Expected result 1. * 2. When the server is in the TRY_RECV_CERTIFICATIONATE_VERIFY state, construct a CLIENT_KEY_EXCHANGE message * and send it to the server. Expected result 2. * @expect 1. The initialization is successful. * 2. After receiving the CLIENT_KEY_EXCHANGE message, the server sends an ALERT message. The level is * ALERT_Level_FATAL and the description is ALERT_UNEXPECTED_MESSAGE. @ */ /* BEGIN_CASE */ void UT_TLS_TLCP_CONSISTENCY_UNEXPECT_HANDSHAKEMSG_TC010(int version) { FRAME_Init(); FRAME_Msg frameMsg = { 0 }; FRAME_Type frameType = { 0 }; HITLS_Config *config = NULL; FRAME_LinkObj *client = NULL; FRAME_LinkObj *server = NULL; config = HITLS_CFG_NewTLCPConfig(); ASSERT_TRUE(config != NULL); config->isSupportExtendMasterSecret = true; config->isSupportClientVerify = true; config->isSupportNoClientCert = false; config->isSupportRenegotiation = true; client = FRAME_CreateTLCPLink(config, BSL_UIO_TCP, true); server = FRAME_CreateTLCPLink(config, BSL_UIO_TCP, false); ASSERT_EQ(FRAME_CreateConnection(client, server, false, TRY_RECV_CLIENT_KEY_EXCHANGE), 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); server->ssl->hsCtx->state = TRY_RECV_CERTIFICATE_VERIFY; uint32_t parseLen = 0; frameType.versionType = version; frameType.recordType = REC_TYPE_HANDSHAKE; frameType.handshakeType = CLIENT_KEY_EXCHANGE; frameType.keyExType = 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); 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_MSG_HANDLE_UNEXPECTED_MESSAGE); ioUserData = BSL_UIO_GetUserData(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_UNEXPECTED_MESSAGE); EXIT: FRAME_CleanMsg(&frameType, &frameMsg); HITLS_CFG_FreeConfig(config); FRAME_FreeLink(client); FRAME_FreeLink(server); } /* END_CASE */ /* @ * @test UT_TLS_TLCP_CONSISTENCY_UNEXPECT_HANDSHAKEMSG_TC011 * @title An unexpected message is received when the server is in the TRY_RECV_FINISH state during the handshake. * @precon nan * @brief 1. Use the default configuration items to configure the client and server. Expected result 1. * 2. When the server is in the TRY_RECV_FINISH state, construct a CLIENT_KEY_EXCHANGE message and send it to the server. Expected result 2. * @expect 1. The initialization is successful. * 2. After receiving the CLIENT_KEY_EXCHANGE message, the server sends an ALERT message. The level is * ALERT_Level_FATAL and the description is ALERT_UNEXPECTED_MESSAGE. @ */ /* BEGIN_CASE */ void UT_TLS_TLCP_CONSISTENCY_UNEXPECT_HANDSHAKEMSG_TC011(int version) { FRAME_Init(); FRAME_Msg frameMsg = { 0 }; FRAME_Type frameType = { 0 }; HITLS_Config *config = NULL; FRAME_LinkObj *client = NULL; FRAME_LinkObj *server = NULL; config = HITLS_CFG_NewTLCPConfig(); ASSERT_TRUE(config != NULL); config->isSupportExtendMasterSecret = true; config->isSupportClientVerify = true; config->isSupportNoClientCert = false; config->isSupportRenegotiation = true; client = FRAME_CreateTLCPLink(config, BSL_UIO_TCP, true); server = FRAME_CreateTLCPLink(config, BSL_UIO_TCP, false); ASSERT_EQ(FRAME_CreateConnection(client, server, false, TRY_RECV_CLIENT_KEY_EXCHANGE), 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); server->ssl->hsCtx->state = TRY_RECV_FINISH; uint32_t parseLen = 0; frameType.versionType = version; frameType.recordType = REC_TYPE_HANDSHAKE; frameType.handshakeType = CLIENT_KEY_EXCHANGE; frameType.keyExType = 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); 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_MSG_HANDLE_UNEXPECTED_MESSAGE); ioUserData = BSL_UIO_GetUserData(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_UNEXPECTED_MESSAGE); EXIT: FRAME_CleanMsg(&frameType, &frameMsg); HITLS_CFG_FreeConfig(config); FRAME_FreeLink(client); FRAME_FreeLink(server); } /* END_CASE */ /* @ * @test UT_TLS_TLCP_CONSISTENCY_UNEXPECT_HANDSHAKEMSG_TC012 * @title An unexpected message is received when the client is in the TRY_RECV_SERVER_HELLO state during the handshake. * @precon nan * @brief 1. Use the default configuration items to configure the client and server. Expected result 1 is obtained. * 2. When the client is in the TRY_RECV_SERVER_HELLO state, construct a Server Hello Done message and send it to * the client. Expected result 2 is obtained. * @expect 1. The initialization is successful. * 2. After receiving the Server Hello Done message, the client sends an ALERT. The level is ALERT_Level_FATAL * and the description is ALERT_UNEXPECTED_MESSAGE. @ */ /* BEGIN_CASE */ void UT_TLS_TLCP_CONSISTENCY_UNEXPECT_HANDSHAKEMSG_TC012(int version) { FRAME_Init(); HITLS_Config *config = NULL; FRAME_LinkObj *client = NULL; FRAME_LinkObj *server = NULL; config = HITLS_CFG_NewTLCPConfig(); ASSERT_TRUE(config != NULL); config->isSupportExtendMasterSecret = true; config->isSupportClientVerify = true; config->isSupportNoClientCert = true; config->isSupportRenegotiation = true; client = FRAME_CreateTLCPLink(config, BSL_UIO_TCP, true); server = FRAME_CreateTLCPLink(config, BSL_UIO_TCP, false); ASSERT_EQ(FRAME_CreateConnection(client, server, true, TRY_RECV_SERVER_HELLO), HITLS_SUCCESS); FRAME_Msg parsedSHdone = { 0 }; FRAME_Type frameType = { 0 }; SetFrameType(&frameType, version, REC_TYPE_HANDSHAKE, SERVER_HELLO_DONE, HITLS_KEY_EXCH_ECDHE); ASSERT_TRUE(FRAME_GetDefaultMsg(&frameType, &parsedSHdone) == HITLS_SUCCESS); uint32_t sendLen = MAX_RECORD_LENTH; uint8_t sendBuf[MAX_RECORD_LENTH] = {0}; ASSERT_TRUE(FRAME_PackMsg(&frameType, &parsedSHdone, sendBuf, sendLen, &sendLen) == HITLS_SUCCESS); FrameUioUserData *ioUserData = BSL_UIO_GetUserData(client->io); ioUserData->recMsg.len = 0; ASSERT_TRUE(FRAME_TransportRecMsg(client->io, sendBuf, sendLen) == HITLS_SUCCESS); FRAME_CleanMsg(&frameType, &parsedSHdone); ASSERT_TRUE(client->ssl != NULL); ASSERT_EQ(HITLS_Connect(client->ssl), HITLS_MSG_HANDLE_UNEXPECTED_MESSAGE); 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; frameType.recordType = REC_TYPE_ALERT; ASSERT_TRUE(FRAME_ParseMsg(&frameType, sndBuf, sndLen, &parsedSHdone, &parseLen) == HITLS_SUCCESS); ASSERT_TRUE(parsedSHdone.recType.data == REC_TYPE_ALERT); FRAME_AlertMsg *alertMsg = &parsedSHdone.body.alertMsg; ASSERT_TRUE(alertMsg->alertLevel.data == ALERT_LEVEL_FATAL); ASSERT_TRUE(alertMsg->alertDescription.data == ALERT_UNEXPECTED_MESSAGE); EXIT: FRAME_CleanMsg(&frameType, &parsedSHdone); HITLS_CFG_FreeConfig(config); FRAME_FreeLink(client); FRAME_FreeLink(server); } /* END_CASE */ /* @ * @test UT_TLS_TLCP_CONSISTENCY_MSGLENGTH_TOOLONG_TC001 * @title The client sends a Client Certificate message with the length of 2 ^ 14 + 1 bytes. * @precon nan * @brief 1. Use the default configuration items to configure the client and server. Expected result 1. * 2. The client initiates a connection creation request. When the client needs to send the Client Certificate * message, the two fields are modified as follows: * Certificates Length is 2 ^ 14 + 1 * Certificates are changed to 2 ^ 14 + 1 bytes buffer. * After the modification is complete, send the message to the server. Expected result 2. * 3. When the server receives the Client Certificate message, check the value returned by the HITLS_Accept * interface. Expected result 3. * @expect 1. The initialization is successful. * 2. The field is successfully modified and sent to the client. * 3. The value returned by the HITLS_Accept interface is HITLS_REC_RECORD_OVERFLOW. @ */ /* BEGIN_CASE */ void UT_TLS_TLCP_CONSISTENCY_MSGLENGTH_TOOLONG_TC001(void) { HandshakeTestInfo testInfo = {0}; testInfo.state = TRY_RECV_CERTIFICATE; testInfo.isClient = false; ASSERT_TRUE(DefaultCfgStatusPark(&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; FRAME_Msg frameMsg = {0}; FRAME_Type frameType = {0}; frameType.versionType = HITLS_VERSION_TLCP_DTLCP11; frameType.recordType = REC_TYPE_HANDSHAKE; frameType.handshakeType = CERTIFICATE; frameType.keyExType = HITLS_KEY_EXCH_ECDHE; ASSERT_TRUE(FRAME_ParseMsg(&frameType, recvBuf, recvLen, &frameMsg, &parseLen) == HITLS_SUCCESS); 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.certificate.certItem->cert.data); frameMsg.body.hsMsg.body.certificate.certItem->cert.data = certDataTemp; frameMsg.body.hsMsg.body.certificate.certItem->cert.size = BUF_TOOLONG_LEN; frameMsg.body.hsMsg.body.certificate.certItem->cert.state = ASSIGNED_FIELD; frameMsg.body.hsMsg.body.certificate.certItem->certLen.data = BUF_TOOLONG_LEN; frameMsg.body.hsMsg.body.certificate.certItem->certLen.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); 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); ASSERT_EQ(HITLS_Accept(testInfo.server->ssl), HITLS_REC_RECORD_OVERFLOW); ASSERT_TRUE(testInfo.server->ssl->hsCtx->state == TRY_RECV_CERTIFICATE); 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_TLCP_CONSISTENCY_MSGLENGTH_TOOLONG_TC002 * @title The server sends a Server Certificate message with the length of 2 ^ 14 + 1 bytes. * @precon nan * @brief 1. Use the default configuration items to configure the client and server. Expected result 1. * 2. The client initiates a connection creation request. When the server needs to send a Server Certificate * message, the two fields are modified as follows: * Certificates Length is 2 ^ 14 + 1 * Certificates are changed to 2 ^ 14 + 1 bytes buffer. * After the modification is complete, send the modification to the server. Expected result 2. * 3. When the client receives the Server Certificate message, check the value returned by the HITLS_Connect * interface. Expected result 3. * @expect 1. The initialization is successful. * 2. The field is successfully modified and sent to the client. * 3. The value returned by the HITLS_Connect interface is HITLS_REC_RECORD_OVERFLOW. @ */ /* BEGIN_CASE */ void UT_TLS_TLCP_CONSISTENCY_MSGLENGTH_TOOLONG_TC002(void) { HandshakeTestInfo testInfo = {0}; testInfo.state = TRY_RECV_CERTIFICATE; testInfo.isClient = true; ASSERT_TRUE(DefaultCfgStatusPark(&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; FRAME_Msg frameMsg = {0}; FRAME_Type frameType = {0}; frameType.versionType = HITLS_VERSION_TLCP_DTLCP11; frameType.recordType = REC_TYPE_HANDSHAKE; frameType.handshakeType = CERTIFICATE; frameType.keyExType = HITLS_KEY_EXCH_ECDHE; ASSERT_TRUE(FRAME_ParseMsg(&frameType, recvBuf, recvLen, &frameMsg, &parseLen) == HITLS_SUCCESS); 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.certificate.certItem->cert.data); frameMsg.body.hsMsg.body.certificate.certItem->cert.data = certDataTemp; frameMsg.body.hsMsg.body.certificate.certItem->cert.size = BUF_TOOLONG_LEN; frameMsg.body.hsMsg.body.certificate.certItem->cert.state = ASSIGNED_FIELD; frameMsg.body.hsMsg.body.certificate.certItem->certLen.data = BUF_TOOLONG_LEN; frameMsg.body.hsMsg.body.certificate.certItem->certLen.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); 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); ASSERT_EQ(HITLS_Connect(testInfo.client->ssl), HITLS_REC_RECORD_OVERFLOW); ASSERT_TRUE(testInfo.client->ssl->hsCtx->state == TRY_RECV_CERTIFICATE); 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_TLCP_CONSISTENCY_MSGLENGTH_TOOLONG_TC003 * @title The client sends a Change Cipher Spec message with the length of 2 ^ 14 + 1 bytes. * @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 link creation request. When the client needs to send a Change Cipher Spec message, * modify one 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 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 server. * 3. The value returned by the HITLS_Accept interface is HITLS_REC_RECORD_OVERFLOW. @ */ /* BEGIN_CASE */ void UT_TLS_TLCP_CONSISTENCY_MSGLENGTH_TOOLONG_TC003(void) { HandshakeTestInfo testInfo = {0}; testInfo.state = TRY_RECV_CLIENT_KEY_EXCHANGE; testInfo.isClient = false; ASSERT_TRUE(DefaultCfgStatusPark(&testInfo) == HITLS_SUCCESS); ASSERT_EQ(HITLS_Accept(testInfo.server->ssl), HITLS_REC_NORMAL_RECV_BUF_EMPTY); FRAME_Msg frameMsg = {0}; FRAME_Type frameType = {0}; frameType.versionType = HITLS_VERSION_TLCP_DTLCP11; frameType.recordType = REC_TYPE_CHANGE_CIPHER_SPEC; ASSERT_TRUE(FRAME_GetDefaultMsg(&frameType, &frameMsg) == HITLS_SUCCESS); 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); ASSERT_EQ(HITLS_Accept(testInfo.server->ssl), HITLS_REC_RECORD_OVERFLOW); ASSERT_TRUE(testInfo.server->ssl->hsCtx->state == TRY_RECV_CERTIFICATE_VERIFY); bool isCcsRecv = testInfo.server->ssl->method.isRecvCCS(testInfo.server->ssl); ASSERT_TRUE(isCcsRecv == false); 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_TLCP_CONSISTENCY_MSGLENGTH_TOOLONG_TC004 * @title The server sends a Change Cipher Spec message with the length of 2 ^ 14 + 1 bytes. * @precon nan * @brief 1. Use the default configuration items to configure the client and server. Expected result 1. * 2. The server initiates a link creation request. When the server needs to send a Change Cipher Spec message, * modify one field as follows: Length is 2 ^ 14 + 1. After the modification, the modification is sent to the * server. Expected result 2. * 3. When the client receives the Change Cipher Spec message, check the value returned by the HITLS_Accept * interface. Expected result 3. * @expect 1. The initialization is successful. * 2. The field is successfully modified and sent to the client. * 3. The value returned by the HITLS_Accept interface is HITLS_REC_RECORD_OVERFLOW. @ */ /* BEGIN_CASE */ void UT_TLS_TLCP_CONSISTENCY_MSGLENGTH_TOOLONG_TC004(void) { HandshakeTestInfo testInfo = {0}; testInfo.state = TRY_SEND_FINISH; testInfo.isClient = true; ASSERT_TRUE(DefaultCfgStatusPark(&testInfo) == HITLS_SUCCESS); ASSERT_TRUE(testInfo.server->ssl != NULL); ASSERT_EQ(HITLS_Connect(testInfo.server->ssl), HITLS_REC_NORMAL_RECV_BUF_EMPTY); FRAME_Msg frameMsg1 = {0}; FRAME_Type frameType1 = {0}; frameType1.versionType = HITLS_VERSION_TLCP_DTLCP11; frameType1.recordType = REC_TYPE_CHANGE_CIPHER_SPEC; ASSERT_TRUE(FRAME_GetDefaultMsg(&frameType1, &frameMsg1) == HITLS_SUCCESS); uint8_t *certDataTemp = (uint8_t *)BSL_SAL_Calloc(1, (uint32_t)BUF_TOOLONG_LEN); ASSERT_TRUE(certDataTemp != NULL); BSL_SAL_FREE(frameMsg1.body.ccsMsg.extra.data); frameMsg1.body.ccsMsg.extra.data = certDataTemp; frameMsg1.body.ccsMsg.extra.size = BUF_TOOLONG_LEN; frameMsg1.body.ccsMsg.extra.state = ASSIGNED_FIELD; uint32_t sendLen = MAX_RECORD_LENTH; uint8_t sendBuf[MAX_RECORD_LENTH] = {0}; ASSERT_TRUE(FRAME_PackMsg(&frameType1, &frameMsg1, sendBuf, sendLen, &sendLen) == HITLS_SUCCESS); ASSERT_TRUE(testInfo.client->ssl != NULL); ASSERT_EQ(HITLS_Connect(testInfo.client->ssl), HITLS_REC_NORMAL_RECV_BUF_EMPTY); ASSERT_TRUE(FRAME_TrasferMsgBetweenLink(testInfo.client, testInfo.server) == HITLS_SUCCESS); FrameUioUserData *ioUserData1 = BSL_UIO_GetUserData(testInfo.client->io); ioUserData1->recMsg.len = 0; ASSERT_TRUE(FRAME_TransportRecMsg(testInfo.client->io, sendBuf, sendLen) == HITLS_SUCCESS); FRAME_CleanMsg(&frameType1, &frameMsg1); memset_s(&frameMsg1, sizeof(frameMsg1), 0, sizeof(frameMsg1)); ASSERT_EQ(HITLS_Connect(testInfo.client->ssl), HITLS_REC_RECORD_OVERFLOW); EXIT: FRAME_CleanMsg(&frameType1, &frameMsg1); HITLS_CFG_FreeConfig(testInfo.config); FRAME_FreeLink(testInfo.client); FRAME_FreeLink(testInfo.server); FRAME_DeRegCryptMethod(); } /* END_CASE */ /* @ * @test UT_TLS_TLCP_CONSISTENCY_CIPHERTEXT_TOOLONG_TC001 * @title A too long cipher text app message is sent by client or server. * @precon nan * @brief 1. Use the default configuration items to configure the client and server. Expected result 1. * 2. When the client is in transporting state, the server sends a message whose ciphertext length is 2 ^ 14 + * 2048. Expected result 2. * 3. When the server is in transporting state, the client sends a message whose ciphertext length is 2 ^ 14 + * 2048. Expected result 3. * 4. When the server is in transporting state, the client sends a message whose ciphertext length is 2 ^ 14 + * 2049. Expected result 4. * 5. When the client is in transporting state, the server sends a message whose ciphertext length is 2 ^ 14 + * 2049. Expected result 5. * @expect 1. The initialization is successful. * 2. The message can be decrypted. * 3. The message can be decrypted. * 4. The server send an alert message. * 5. The client send an alert message. @ */ /* BEGIN_CASE */ void UT_TLS_TLCP_CONSISTENCY_CIPHERTEXT_TOOLONG_TC001(int isClient, int ptLen, int ctLen) { FRAME_Init(); STUB_Init(); FuncStubInfo stubInfo = {0}; HITLS_Config *config = HITLS_CFG_NewTLCPConfig(); ASSERT_TRUE(config != NULL); FRAME_LinkObj *client = FRAME_CreateTLCPLink(config, BSL_UIO_TCP, true); FRAME_LinkObj *server = FRAME_CreateTLCPLink(config, BSL_UIO_TCP, false); FRAME_LinkObj *sender = NULL; FRAME_LinkObj *receiver = NULL; ASSERT_TRUE(client != NULL); ASSERT_TRUE(server != NULL); if (isClient) { sender = client; receiver = server; } else { sender = server; receiver = client; } ASSERT_EQ(FRAME_CreateConnection(client, server, true, HS_STATE_BUTT), HITLS_SUCCESS); ASSERT_TRUE(client->ssl->state == CM_STATE_TRANSPORTING); uint8_t readBuf[MAX_BUF_LEN] = {0}; uint32_t readLen = 0; uint8_t sendBuf[MAX_BUF_LEN] = {0}; (void)memset_s(sendBuf + 5, REC_MAX_CIPHER_TEXT_LEN + 1, 9, REC_MAX_CIPHER_TEXT_LEN + 1); RecBufFree(sender->ssl->recCtx->outBuf); sender->ssl->recCtx->outBuf = RecBufNew(MAX_BUF_LEN); RecBufFree(receiver->ssl->recCtx->inBuf); receiver->ssl->recCtx->inBuf = RecBufNew(MAX_BUF_LEN); ASSERT_EQ(TlsRecordWrite(sender->ssl, REC_TYPE_APP, sendBuf, ptLen), HITLS_SUCCESS); ASSERT_EQ(FRAME_TrasferMsgBetweenLink(sender, receiver), HITLS_SUCCESS); STUB_Replace(&stubInfo, TlsRecordRead, STUB_TlsRecordRead); int32_t ret = ctLen > 18432 ? HITLS_REC_RECORD_OVERFLOW : HITLS_SUCCESS; ASSERT_EQ(TlsRecordRead(receiver->ssl, REC_TYPE_APP, readBuf, &readLen, ctLen), ret); EXIT: HITLS_CFG_FreeConfig(config); FRAME_FreeLink(sender); FRAME_FreeLink(receiver); STUB_Reset(&stubInfo); } /* END_CASE */ /* @ * @test UT_TLS_TLCP_CONSISTENCY_NONZERO_MESSAGELEN_TC001 * @title Test the scenario where the message parameter is unacceptable. * @precon nan * @spec 1. After receiving the servehellodone message from the server, the client verifies whether the server * certificate is valid and the servehello message from the server. Indicates whether the message parameter * is acceptable. If acceptable, the client continues the handshake process. Otherwise, a HandShakeFailure * critical alarm is sent. * @brief 1. After receiving the servehellodone message from the server, the client verifies whether the server * certificate is valid and the servehello message from the server. Expected result 1. * @expect 1. During the first connection setup, the client receives a servehellodone message from the server. The * message length is not 0. The expected handshake fails. @ */ /* BEGIN_CASE */ void UT_TLS_TLCP_CONSISTENCY_NONZERO_MESSAGELEN_TC001() { FRAME_Init(); HITLS_Config *tlsConfig = NULL; FRAME_LinkObj *client = NULL; FRAME_LinkObj *server = NULL; FRAME_Msg frameMsg = { 0 }; FRAME_Type frameType = { 0 }; tlsConfig = HITLS_CFG_NewTLCPConfig(); ASSERT_TRUE(tlsConfig != NULL); client = FRAME_CreateTLCPLink(tlsConfig, BSL_UIO_TCP, true); ASSERT_TRUE(client != NULL); server = FRAME_CreateTLCPLink(tlsConfig, BSL_UIO_TCP, false); ASSERT_TRUE(server != NULL); int32_t ret; ret = FRAME_CreateConnection(client, server, true, TRY_RECV_SERVER_HELLO_DONE); ASSERT_EQ(ret, 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); uint32_t parseLen = 0; frameType.versionType = HITLS_VERSION_TLCP_DTLCP11; frameType.recordType = REC_TYPE_HANDSHAKE; frameType.handshakeType = SERVER_HELLO_DONE; frameType.keyExType = HITLS_KEY_EXCH_ECDHE; ASSERT_TRUE(FRAME_ParseMsg(&frameType, recvBuf, recvLen, &frameMsg, &parseLen) == HITLS_SUCCESS); FRAME_ServerHelloDoneMsg *serverHelloDone = &frameMsg.body.hsMsg.body.serverHelloDone; uint8_t extra[1] = {0}; FRAME_ModifyMsgArray8(extra, 1, &serverHelloDone->extra, NULL); 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_TRUE(client->ssl != NULL); ASSERT_EQ(HITLS_Connect(client->ssl), HITLS_PARSE_EXCESSIVE_MESSAGE_SIZE); EXIT: HITLS_CFG_FreeConfig(tlsConfig); FRAME_FreeLink(client); FRAME_FreeLink(server); } /* END_CASE */ /* @ * @test UT_TLS_TLCP_CONSISTENCY_SEQ_NUM_TC001 * @title Check whether the sequence number of the read/write status in the FINISH message sent by the server/client is 1. * @precon nan * @brief 1. Configure the client/server to stay in the TRY_SEND_FINISH state. Expected result 1. * 2. Connect the server and client once and send the message. Expected result 2. 3. Obtain the messages sent by the server or client. Expected result 3. 4. Parse the message sent by the local end into the hs_msg structure. Expected result 4. 5. Check the sequence number in the sent message. Expected result 5. 6. Enable the local end to transmit data to the peer end. Expected result 6. 7. Obtain the messages received by the peer end. Expected result 7. 8. Parse the message received by the peer end into the hs_msg structure. Expected result 8. 9. Check the sequence number in the received message. Expected result 9. * @expect 1. The initialization is successful. * 2. If the server is successfully connected, the client returns NORMAL_RECV_BUF_EMPTY. 3. The sending length is not null. 4. The parsing is successful and the message header length is fixed to 5 bytes. 5. The serial number is 1. 6. The transmission is successful. 7. The received length is not empty. 8. The parsing succeeds and the message header length is fixed to 5 bytes. 9. The serial number is 1. @ */ /* BEGIN_CASE */ void UT_TLS_TLCP_CONSISTENCY_SEQ_NUM_TC001(int isClient) { HandshakeTestInfo testInfo = { 0 }; testInfo.isSupportExtendMasterSecret = true; testInfo.state = TRY_SEND_FINISH; testInfo.isClient = isClient; ASSERT_TRUE(DefaultCfgStatusPark(&testInfo) == HITLS_SUCCESS); if (isClient) { ASSERT_TRUE(HITLS_Connect(testInfo.client->ssl) == HITLS_REC_NORMAL_RECV_BUF_EMPTY); } else { ASSERT_TRUE(HITLS_Accept(testInfo.server->ssl) == HITLS_SUCCESS); } HITLS_Ctx *localSsl = isClient ? testInfo.client->ssl : testInfo.server->ssl; ASSERT_TRUE(localSsl->recCtx->writeStates.currentState->seq == 1); if (isClient) { ASSERT_TRUE(FRAME_TrasferMsgBetweenLink(testInfo.client, testInfo.server) == HITLS_SUCCESS); } else { ASSERT_TRUE(FRAME_TrasferMsgBetweenLink(testInfo.server, testInfo.client) == HITLS_SUCCESS); } HITLS_Ctx *remoteSsl = isClient ? testInfo.server->ssl : testInfo.client->ssl; if (!isClient) { ASSERT_TRUE(HITLS_Connect(testInfo.client->ssl) == HITLS_SUCCESS); } else { ASSERT_TRUE(HITLS_Accept(testInfo.server->ssl) == HITLS_REC_NORMAL_IO_BUSY); } ASSERT_TRUE(remoteSsl->recCtx->readStates.currentState->seq == 1); EXIT: HITLS_CFG_FreeConfig(testInfo.config); FRAME_FreeLink(testInfo.client); FRAME_FreeLink(testInfo.server); FRAME_DeRegCryptMethod(); } /* END_CASE */ /* @ * @test UT_TLS_TLCP_CONSISTENCY_SEQ_NUM_TC002 * @title Check whether the sequence number of the read/write sequence in the APP message sent by the server/client is 2. * @precon nan * @brief 1. Configure the status of the client/server to the successful handshake. Expected result 1. * 2. Check the server/client connection status. Expected result 2. 3. Randomly generate 32-byte data. Expected result 3. 4. Write app data. Expected result 4. 5. Obtain data from the I/O sent by the local end and parse the header and content. Expected result 5. 6. Check the sequence number in the sent message. Expected result 6. 7. Perform I/O data transmission from the local end to the peer end. Expected result 7. 8. Obtain data from the received I/O from the peer end and parse the header and content. Expected result 8. 9. Check the sequence number in the received message. Expected result 9. * @expect 1. The initialization is successful. * 2. The link status is Transferring. 3. The generation is successful. 4. The writing is successful. 5. The parsing is successful and the value of RecordType is REC_TYPE_APP. 6. The SN is 2. 7. The transmission is successful. 8. The parsing is successful and the value of RecordType is REC_TYPE_APP. 9. The SN is 2. @ */ /* BEGIN_CASE */ void UT_TLS_TLCP_CONSISTENCY_SEQ_NUM_TC002(int isClient) { HandshakeTestInfo testInfo = { 0 }; testInfo.isSupportExtendMasterSecret = true; testInfo.state = HS_STATE_BUTT; testInfo.isClient = isClient; ASSERT_TRUE(DefaultCfgStatusPark(&testInfo) == HITLS_SUCCESS); ASSERT_TRUE(testInfo.client->ssl->state == CM_STATE_TRANSPORTING); ASSERT_TRUE(testInfo.server->ssl->state == CM_STATE_TRANSPORTING); uint8_t transportData[REC_CONN_SEQ_SIZE * 4] = {0}; uint32_t transportDataLen = sizeof(transportData) / sizeof(uint8_t); ASSERT_EQ(RandBytes(transportData, transportDataLen), HITLS_SUCCESS); HITLS_Ctx *localSsl = isClient ? testInfo.client->ssl : testInfo.server->ssl; uint32_t writeLen; ASSERT_EQ(APP_Write(localSsl, transportData, transportDataLen, &writeLen), HITLS_SUCCESS); ASSERT_EQ(localSsl->recCtx->writeStates.currentState->seq , 2); if (isClient) { ASSERT_TRUE(FRAME_TrasferMsgBetweenLink(testInfo.client, testInfo.server) == HITLS_SUCCESS); } else { ASSERT_TRUE(FRAME_TrasferMsgBetweenLink(testInfo.server, testInfo.client) == HITLS_SUCCESS); } HITLS_Ctx *remoteSsl = isClient ? testInfo.server->ssl : testInfo.client->ssl; uint8_t readBuf[READ_BUF_SIZE] = {0}; uint32_t readLen = 0; ASSERT_EQ(APP_Read(remoteSsl, readBuf, READ_BUF_SIZE, &readLen), HITLS_SUCCESS); ASSERT_EQ(remoteSsl->recCtx->readStates.currentState->seq , 2); EXIT: HITLS_CFG_FreeConfig(testInfo.config); FRAME_FreeLink(testInfo.client); FRAME_FreeLink(testInfo.server); FRAME_DeRegCryptMethod(); } /* END_CASE */
2301_79861745/bench_create
testcode/sdv/testcase/tls/consistency/tlcp/test_suite_sdv_frame_tlcp_consistency_1.c
C
unknown
91,392
/* * This file is part of the openHiTLS project. * * openHiTLS is licensed under the Mulan PSL v2. * You can use this software according to the terms and conditions of the Mulan PSL v2. * You may obtain a copy of Mulan PSL v2 at: * * http://license.coscl.org.cn/MulanPSL2 * * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, * EITHER EXPRESS 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_sdv_frame_tlcp_consistency */ /* END_HEADER */ /* @ * @test UT_TLS_TLCP_CONSISTENCY_RESUME_TC003 * @title Enable the session restoration function at both ends. If the session ID is obtained after the link is successfully established, a fatal alert is sent. The session ID fails to be used to restore the session. * @precon nan * @brief 1. Use the default configuration items to configure the client and server. * Enable the session restoration function at both ends. Expected result 1. * 2. Obtaine the session ID and a fatal alert is sent. The session ID fails to be used to restore the session. * Expected result 2. * @expect 1. The initialization is successful. * 2. Expected handshake failure @ */ /* BEGIN_CASE */ void UT_TLS_TLCP_CONSISTENCY_RESUME_TC003() { FRAME_Init(); HITLS_Config *config = NULL; FRAME_LinkObj *client = NULL; FRAME_LinkObj *server = NULL; config = HITLS_CFG_NewTLCPConfig(); client = FRAME_CreateTLCPLink(config, BSL_UIO_TCP, true); server = FRAME_CreateTLCPLink(config, BSL_UIO_TCP, false); ASSERT_EQ(FRAME_CreateConnection(client, server, false, HS_STATE_BUTT), HITLS_SUCCESS); HITLS_Session *clientSession = HITLS_GetDupSession(client->ssl); FRAME_FreeLink(client); FRAME_FreeLink(server); client = FRAME_CreateTLCPLink(config, BSL_UIO_TCP, true); HITLS_SetSession(client->ssl, clientSession); server = FRAME_CreateTLCPLink(config, BSL_UIO_TCP, false); ASSERT_EQ(FRAME_CreateConnection(client, server, false, TRY_SEND_FINISH), HITLS_SUCCESS); client->ssl->method.sendAlert(client->ssl, ALERT_LEVEL_FATAL, ALERT_DECRYPT_ERROR); ASSERT_NE(FRAME_CreateConnection(client, server, false, HS_STATE_BUTT), HITLS_SUCCESS); FRAME_FreeLink(client); FRAME_FreeLink(server); client = FRAME_CreateTLCPLink(config, BSL_UIO_TCP, true); HITLS_SetSession(client->ssl, clientSession); server = FRAME_CreateTLCPLink(config, BSL_UIO_TCP, false); 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); ClearWrapper(); HITLS_SESS_Free(clientSession); } /* END_CASE */ /* @ * @test UT_TLS_TLCP_CONSISTENCY_RESUME_TC004 * @title Set the client and server support session recovery. After the first connection is established, the session ID is obtained. Create two connection. The client and server are the same as those in the last session. Use the same session ID to restore the session. If the session on one link fails, check whether the data communication on the other link is blocked. It is expected that the link is not blocked. * @precon nan * @brief 1. Use the default configuration items to configure the client and server. * Enable the session restoration function at both ends. Expected result 1. * 2. Use the default configuration items to configure two new client and server. * The client and server are the same as those in the last session. Expected result 1. * 3. Use the obtained session ID to restore one session and send a alert. Expected result 2. * 4. Use the obtained session ID to restore another session. Expected result 3. * @expect 1. The initialization is successful. * 2. Expected handshake failure. * 3. Restore the session successfully. @ */ /* BEGIN_CASE */ void UT_TLS_TLCP_CONSISTENCY_RESUME_TC004() { FRAME_Init(); HITLS_Config *config = NULL; FRAME_LinkObj *client = NULL; FRAME_LinkObj *server = NULL; FRAME_LinkObj *clientResume = NULL; FRAME_LinkObj *serverResume = NULL; config = HITLS_CFG_NewTLCPConfig(); client = FRAME_CreateTLCPLink(config, BSL_UIO_TCP, true); server = FRAME_CreateTLCPLink(config, BSL_UIO_TCP, false); ASSERT_EQ(FRAME_CreateConnection(client, server, false, HS_STATE_BUTT), HITLS_SUCCESS); HITLS_Session *clientSession = HITLS_GetDupSession(client->ssl); FRAME_FreeLink(client); FRAME_FreeLink(server); client = FRAME_CreateTLCPLink(config, BSL_UIO_TCP, true); server = FRAME_CreateTLCPLink(config, BSL_UIO_TCP, false); HITLS_SetSession(client->ssl, clientSession); ASSERT_EQ(FRAME_CreateConnection(client, server, false, TRY_SEND_FINISH), HITLS_SUCCESS); clientResume = FRAME_CreateTLCPLink(config, BSL_UIO_TCP, true); serverResume = FRAME_CreateTLCPLink(config, BSL_UIO_TCP, false); HITLS_SetSession(clientResume->ssl, clientSession); ASSERT_EQ(FRAME_CreateConnection(clientResume, serverResume, false, TRY_SEND_FINISH), HITLS_SUCCESS); client->ssl->method.sendAlert(client->ssl, ALERT_LEVEL_FATAL, ALERT_DECRYPT_ERROR); ASSERT_NE(FRAME_CreateConnection(client, server, false, HS_STATE_BUTT), HITLS_SUCCESS); FRAME_FreeLink(client); FRAME_FreeLink(server); ASSERT_EQ(FRAME_CreateConnection(clientResume, serverResume, false, HS_STATE_BUTT), HITLS_SUCCESS); uint8_t isReused = 0; ASSERT_EQ(HITLS_IsSessionReused(clientResume->ssl, &isReused), HITLS_SUCCESS); ASSERT_EQ(isReused, 1); EXIT: HITLS_CFG_FreeConfig(config); FRAME_FreeLink(clientResume); FRAME_FreeLink(serverResume); ClearWrapper(); HITLS_SESS_Free(clientSession); } /* END_CASE */ /* @ * @test UT_TLS_TLCP_CONSISTENCY_RESUME_TC005 * @title Set the client and server support session recovery. After the first connection is established, the session ID * is obtained. Apply for two links. The client and server are the same as those in the last session. Use the same * session ID to restore the session. If the session on one link times out, check whether the data communication * on the other link is blocked. If the data communication on the other link is not blocked, the data * communication on the other link is not blocked. * @precon nan * @brief 1. Use the default configuration items to configure the client and server. * Enable the session restoration function at both ends. Expected result 1. * 2. Use the default configuration items to configure two new client and server. * The client and server are the same as those in the last session. Expected result 1. * 3. Use the obtained session ID to restore one session and sleep to cause a session to time out. * Expected result 2. * 4. Use the obtained session ID to restore another session. Expected result 3. * @expect 1. The initialization is successful. * 2. Establish the connection but restore the session failed. * 3. Establish the connection and restore the session successfully. @ */ /* BEGIN_CASE */ void UT_TLS_TLCP_CONSISTENCY_RESUME_TC005() { FRAME_Init(); HITLS_Config *config = NULL; FRAME_LinkObj *client = NULL; FRAME_LinkObj *server = NULL; FRAME_LinkObj *clientResume = NULL; FRAME_LinkObj *serverResume = NULL; config = HITLS_CFG_NewTLCPConfig(); const uint64_t timeout = 5u; HITLS_CFG_SetSessionTimeout(config, timeout); client = FRAME_CreateTLCPLink(config, BSL_UIO_TCP, true); server = FRAME_CreateTLCPLink(config, BSL_UIO_TCP, false); ASSERT_EQ(FRAME_CreateConnection(client, server, false, HS_STATE_BUTT), HITLS_SUCCESS); HITLS_Session *clientSession = HITLS_GetDupSession(client->ssl); FRAME_FreeLink(client); FRAME_FreeLink(server); client = FRAME_CreateTLCPLink(config, BSL_UIO_TCP, true); server = FRAME_CreateTLCPLink(config, BSL_UIO_TCP, false); HITLS_SetSession(client->ssl, clientSession); ASSERT_EQ(FRAME_CreateConnection(client, server, false, TRY_SEND_FINISH), HITLS_SUCCESS); clientResume = FRAME_CreateTLCPLink(config, BSL_UIO_TCP, true); serverResume = FRAME_CreateTLCPLink(config, BSL_UIO_TCP, false); HITLS_SetSession(clientResume->ssl, clientSession); sleep(timeout); ASSERT_EQ(FRAME_CreateConnection(clientResume, serverResume, false, HS_STATE_BUTT), HITLS_SUCCESS); ASSERT_EQ(FRAME_CreateConnection(client, server, false, HS_STATE_BUTT), HITLS_SUCCESS); uint8_t isReused = 0; ASSERT_EQ(HITLS_IsSessionReused(clientResume->ssl, &isReused), HITLS_SUCCESS); ASSERT_EQ(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); FRAME_FreeLink(clientResume); FRAME_FreeLink(serverResume); ClearWrapper(); HITLS_SESS_Free(clientSession); } /* END_CASE */ /* @ * @test UT_TLS_TLCP_CONSISTENCY_RESUME_TC006 * @title Enable the session recovery function at both ends. The link is successfully established. The setting of the * session_id expires. The session fails to be restored. * @precon nan * @brief 1. Set the client and server support session recovery. Establishe the first connection. Expected result 1. * 2. Set the session_id expired, restore the session. Expected result 2. * @expect 1. The expected handshake is successful. * 2. The session is not recovered. @ */ /* BEGIN_CASE */ void UT_TLS_TLCP_CONSISTENCY_RESUME_TC006() { FRAME_Init(); HITLS_Config *config = NULL; FRAME_LinkObj *client = NULL; FRAME_LinkObj *server = NULL; config = HITLS_CFG_NewTLCPConfig(); const uint64_t timeout = 5u; HITLS_CFG_SetSessionTimeout(config, timeout); client = FRAME_CreateTLCPLink(config, BSL_UIO_TCP, true); server = FRAME_CreateTLCPLink(config, BSL_UIO_TCP, false); ASSERT_EQ(FRAME_CreateConnection(client, server, false, HS_STATE_BUTT), HITLS_SUCCESS); HITLS_Session *clientSession = HITLS_GetDupSession(client->ssl); FRAME_FreeLink(client); FRAME_FreeLink(server); client = FRAME_CreateTLCPLink(config, BSL_UIO_TCP, true); server = FRAME_CreateTLCPLink(config, BSL_UIO_TCP, false); HITLS_SetSession(client->ssl, clientSession); sleep(timeout); 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); ClearWrapper(); HITLS_SESS_Free(clientSession); } /* END_CASE */ /* @ * @test UT_TLS_TLCP_CONSISTENCY_RESUME_TC007 * @title When a link is established for the first time, the clienthello message on the client contains the session_id * field that is not empty and is in the connection state. If the session ID on the server is not found in the * cache, the first connection setup process is triggered. * @precon nan * @brief 1. Create the TLCP links on the client and server again, set the obtained session as the session on the * client, and check whether the session is reused. Expected result 1. * @expect 1. The expected handshake is successful, but the session is not recovered. @ */ /* BEGIN_CASE */ void UT_TLS_TLCP_CONSISTENCY_RESUME_TC007() { FRAME_Init(); HITLS_Config *config = NULL; FRAME_LinkObj *client = NULL; FRAME_LinkObj *server = NULL; config = HITLS_CFG_NewTLCPConfig(); client = FRAME_CreateTLCPLink(config, BSL_UIO_TCP, true); server = FRAME_CreateTLCPLink(config, BSL_UIO_TCP, false); ASSERT_EQ(FRAME_CreateConnection(client, server, false, HS_STATE_BUTT), HITLS_SUCCESS); HITLS_Session *clientSession = HITLS_GetDupSession(client->ssl); FRAME_FreeLink(client); FRAME_FreeLink(server); HITLS_CFG_FreeConfig(config); config = HITLS_CFG_NewTLCPConfig(); client = FRAME_CreateTLCPLink(config, BSL_UIO_TCP, true); server = FRAME_CreateTLCPLink(config, BSL_UIO_TCP, false); HITLS_SetSession(client->ssl, clientSession); 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); ClearWrapper(); HITLS_SESS_Free(clientSession); } /* END_CASE */
2301_79861745/bench_create
testcode/sdv/testcase/tls/consistency/tlcp/test_suite_sdv_frame_tlcp_consistency_2.c
C
unknown
12,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_BASE test_suite_sdv_frame_tlcp_consistency */ /* END_HEADER */ static void Test_MisSessionId(HITLS_Ctx *ctx, uint8_t *data, uint32_t *len, uint32_t bufSize, void *user) { if (*(bool *)user) { return; } *(bool *)user = true; (void)ctx; (void)bufSize; (void)user; FRAME_Type frameType = { 0 }; frameType.versionType = HITLS_VERSION_TLCP_DTLCP11; frameType.keyExType = HITLS_KEY_EXCH_ECDHE; FRAME_Msg frameMsg = { 0 }; frameMsg.recType.data = REC_TYPE_HANDSHAKE; frameMsg.length.data = *len; frameMsg.recVersion.data = HITLS_VERSION_TLCP_DTLCP11; uint32_t parseLen = 0; FRAME_ParseMsgBody(&frameType, data, *len, &frameMsg, &parseLen); ASSERT_EQ(frameMsg.body.hsMsg.type.data, SERVER_HELLO); ASSERT_EQ(parseLen, *len); frameMsg.body.hsMsg.body.serverHello.sessionId.state = MISSING_FIELD; FRAME_PackRecordBody(&frameType, &frameMsg, data, bufSize, len); EXIT: frameType.keyExType = HITLS_KEY_EXCH_ECDHE; FRAME_CleanMsg(&frameType, &frameMsg); return; } /* @ * @test UT_TLS_TLCP_CONSISTENCY_SESSIONID_MISS_TC001 * @title During session recovery, the server deletes session_id after sending the server hello message. The expected * session recovery fails and the connection is interrupted. * @precon nan * @brief 1. The client hello and server hello messages are followed by authentication and key exchange. Including * server certificate, server key exchange, client certificate, and client key exchange. Expected result 1. * @expect 1. The expected handshake fails. @ */ /* BEGIN_CASE */ void UT_TLS_TLCP_CONSISTENCY_SESSIONID_MISS_TC001() { FRAME_Init(); HITLS_Config *config = NULL; FRAME_LinkObj *client = NULL; FRAME_LinkObj *server = NULL; bool isModify = false; config = HITLS_CFG_NewTLCPConfig(); client = FRAME_CreateTLCPLink(config, BSL_UIO_TCP, true); server = FRAME_CreateTLCPLink(config, BSL_UIO_TCP, false); ASSERT_EQ(FRAME_CreateConnection(client, server, false, HS_STATE_BUTT), HITLS_SUCCESS); HITLS_Session *clientSession = HITLS_GetDupSession(client->ssl); FRAME_FreeLink(client); FRAME_FreeLink(server); client = FRAME_CreateTLCPLink(config, BSL_UIO_TCP, true); HITLS_SetSession(client->ssl, clientSession); server = FRAME_CreateTLCPLink(config, BSL_UIO_TCP, false); RecWrapper wrapper = { TRY_SEND_SERVER_HELLO, REC_TYPE_HANDSHAKE, false, &isModify, Test_MisSessionId }; RegisterWrapper(wrapper); ASSERT_NE(FRAME_CreateConnection(client, server, false, HS_STATE_BUTT), HITLS_SUCCESS); EXIT: HITLS_CFG_FreeConfig(config); FRAME_FreeLink(client); FRAME_FreeLink(server); ClearWrapper(); HITLS_SESS_Free(clientSession); } /* END_CASE */ static void Test_DiffServerKeyEx(HITLS_Ctx *ctx, uint8_t *data, uint32_t *len, uint32_t bufSize, void *user) { if (*(bool *)user) { return; } *(bool *)user = true; (void)ctx; (void)bufSize; (void)user; FRAME_Type frameType = { 0 }; frameType.versionType = HITLS_VERSION_TLCP_DTLCP11; frameType.keyExType = HITLS_KEY_EXCH_ECDHE; FRAME_Msg frameMsg = { 0 }; frameMsg.recType.data = REC_TYPE_HANDSHAKE; frameMsg.length.data = *len; frameMsg.recVersion.data = HITLS_VERSION_TLCP_DTLCP11; uint32_t parseLen = 0; FRAME_ParseMsgBody(&frameType, data, *len, &frameMsg, &parseLen); ASSERT_EQ(frameMsg.body.hsMsg.type.data, SERVER_KEY_EXCHANGE); ASSERT_EQ(parseLen, *len); frameType.keyExType = HITLS_KEY_EXCH_ECC; FRAME_PackRecordBody(&frameType, &frameMsg, data, bufSize, len); EXIT: frameType.keyExType = HITLS_KEY_EXCH_ECDHE; FRAME_CleanMsg(&frameType, &frameMsg); return; } /* @ * @test UT_TLS_TLCP_CONSISTENCY_KEY_EXCHANGE_TC001 * @title After the client sends a certificate, the key exchange message sent by the client is different from the * negotiated key exchange algorithm. As a result, the link fails to be established. * @precon nan * @brief 1. After the client sends a certificate, the key exchange message sent by the client must be consistent with * the negotiated key exchange algorithm. Expected result 1. * @expect 1. The expected handshake fails. @ */ /* BEGIN_CASE */ void UT_TLS_TLCP_CONSISTENCY_KEY_EXCHANGE_TC001() { FRAME_Init(); HITLS_Config *config = NULL; FRAME_LinkObj *client; FRAME_LinkObj *server; bool isModify = false; RecWrapper wrapper = { TRY_SEND_SERVER_KEY_EXCHANGE, REC_TYPE_HANDSHAKE, false, &isModify, Test_DiffServerKeyEx }; RegisterWrapper(wrapper); config = HITLS_CFG_NewTLCPConfig(); client = FRAME_CreateTLCPLink(config, BSL_UIO_TCP, true); server = FRAME_CreateTLCPLink(config, BSL_UIO_TCP, false); ASSERT_NE(FRAME_CreateConnection(client, server, false, HS_STATE_BUTT), HITLS_SUCCESS); EXIT: HITLS_CFG_FreeConfig(config); FRAME_FreeLink(client); FRAME_FreeLink(server); ClearWrapper(); } /* END_CASE */ /* @ * @test UT_TLS_TLCP_CONSISTENCY_CLIENTKXCH_VERSIONERR_TC001 * @title Test when the value of Client_Version on the server does not match that on the client. * @precon nan * @spec 1. "Client_Version: version number supported by the client. The server checks whether the value matches the * value sent in the hello message from the client. random 46-byte random number" * @brief 1. The server checks whether the Client_Version matches the value sent in the hello message from the client. * Expected result 1. * @expect 1. If the Client_Version of PreMasterSecret in the ClientKeyExChange message received by the server is * different from the ClientHello message, the server reports an alarm indicating that the decryption fails * and the handshake fails. @ */ /* BEGIN_CASE */ void UT_TLS_TLCP_CONSISTENCY_CLIENTKXCH_VERSIONERR_TC001(char *cipherSuite) { FRAME_Init(); STUB_Init(); RegDefaultMemCallback(); HITLS_Config *tlsConfig = NULL; FRAME_LinkObj *client = NULL; FRAME_LinkObj *server = NULL; tlsConfig = HITLS_CFG_NewTLCPConfig(); ASSERT_TRUE(tlsConfig != NULL); uint16_t toSetCipherSuite = GetCipherSuite(cipherSuite); HITLS_CFG_SetCipherSuites(tlsConfig, &toSetCipherSuite, 1); client = FRAME_CreateTLCPLink(tlsConfig, BSL_UIO_TCP, true); ASSERT_TRUE(client != NULL); server = FRAME_CreateTLCPLink(tlsConfig, BSL_UIO_TCP, false); ASSERT_TRUE(server != NULL); FuncStubInfo stubInfo = {0}; STUB_Replace(&stubInfo, GenerateEccPremasterSecret, STUB_GenerateEccPremasterSecret); int32_t ret = FRAME_CreateConnection(client, server, false, TRY_RECV_FINISH); ASSERT_EQ(ret, HITLS_SUCCESS); ASSERT_EQ(HITLS_Accept(server->ssl), HITLS_REC_BAD_RECORD_MAC); ALERT_Info alertInfo = { 0 }; ALERT_GetInfo(server->ssl, &alertInfo); ASSERT_EQ(alertInfo.description, ALERT_BAD_RECORD_MAC); EXIT: HITLS_CFG_FreeConfig(tlsConfig); FRAME_FreeLink(client); FRAME_FreeLink(server); STUB_Reset(&stubInfo); } /* END_CASE */ /* @ * @test UT_TLS_TLCP_CONSISTENCY_CERTFICATE_TC001 * @title Violation of the rule that the signature certificate is before the encryption certificate is after, and * check the result. * @precon nan * @spec 1. Server certificate: signature certificate is placed before the encryption certificate. * @brief 1. Signature certificate before encryption certificate. Expected result 1. * @expect 1. After the signature certificate encrypts the certificate after the server sends the certificate, * the client reports an error indicating that the certificate verification fails and the handshake fails. @ */ /* BEGIN_CASE */ void UT_TLS_TLCP_CONSISTENCY_CERTFICATE_TC001() { FRAME_Init(); HITLS_Config *tlsConfig = NULL; FRAME_LinkObj *client = NULL; FRAME_LinkObj *server = NULL; FRAME_CertInfo certInfo = { "sm2/ca.der", "sm2/inter.der", "sm2/sign.der", "sm2/enc.der", "sm2/sign.key.der", "sm2/enc.key.der", }; tlsConfig = HITLS_CFG_NewTLCPConfig(); ASSERT_TRUE(tlsConfig != NULL); client = FRAME_CreateLinkWithCert(tlsConfig, BSL_UIO_TCP, &certInfo); ASSERT_TRUE(client != NULL); server = FRAME_CreateLinkWithCert(tlsConfig, BSL_UIO_TCP, &certInfo); ASSERT_TRUE(server != NULL); int32_t ret; ret = FRAME_CreateConnection(client, server, true, HS_STATE_BUTT); ASSERT_EQ(ret, HITLS_CERT_ERR_KEYUSAGE); EXIT: HITLS_CFG_FreeConfig(tlsConfig); FRAME_FreeLink(client); FRAME_FreeLink(server); } /* END_CASE */ static void TEST_SendUnexpectCertificateVerifyMsg(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 = CERTIFICATE_VERIFY; FRAME_Init(); FRAME_GetDefaultMsg(frameType, &newFrameMsg); HLT_TlsRegCallback(HITLS_CALLBACK_DEFAULT); // recovery callback frameType->handshakeType = hsTypeTmp; frameType->recordType = recTypeTmp; FRAME_CleanMsg(frameType, frameMsg); frameType->recordType = REC_TYPE_HANDSHAKE; frameType->handshakeType = CERTIFICATE_VERIFY; frameType->keyExType = HITLS_KEY_EXCH_ECDHE; if (memcpy_s(msg, sizeof(FRAME_Msg), &newFrameMsg, sizeof(newFrameMsg)) != EOK) { Print("TEST_SendUnexpectCertificateMsg memcpy_s Error!"); } } static void TEST_UnexpectMsg(HLT_FrameHandle *frameHandle, TestExpect *testExpect, bool isSupportClientVerify) { HLT_Tls_Res *serverRes = NULL; HLT_Tls_Res *clientRes = NULL; HLT_Process *localProcess = NULL; HLT_Process *remoteProcess = NULL; HLT_Ctx_Config *serverConfig = NULL; ALERT_Info alertInfo = {0}; localProcess = HLT_InitLocalProcess(HITLS); ASSERT_TRUE(localProcess != NULL); remoteProcess = HLT_LinkRemoteProcess(HITLS, TCP, PORT, true); ASSERT_TRUE(remoteProcess != NULL); serverConfig = HLT_NewCtxConfigTLCP(NULL, "SERVER", false); ASSERT_TRUE(serverConfig != NULL); if (isSupportClientVerify) { ASSERT_TRUE(HLT_SetClientVerifySupport(serverConfig, isSupportClientVerify) == 0); } HLT_Ctx_Config *clientConfig = HLT_NewCtxConfigTLCP(NULL, "CLIENT", true); ASSERT_TRUE(clientConfig != NULL); ASSERT_TRUE(HLT_SetClientVerifySupport(clientConfig, isSupportClientVerify) == 0); serverRes = HLT_ProcessTlsAccept(remoteProcess, TLCP1_1, serverConfig, NULL); ASSERT_TRUE(serverRes != NULL); // Client Initialization clientRes = HLT_ProcessTlsInit(localProcess, TLCP1_1, clientConfig, NULL); ASSERT_TRUE(clientRes != NULL); ASSERT_TRUE(frameHandle != NULL); frameHandle->ctx = clientRes->ssl; HLT_SetFrameHandle(frameHandle); ASSERT_EQ(HLT_TlsConnect(clientRes->ssl), testExpect->connectExpect); HLT_CleanFrameHandle(); ALERT_GetInfo(clientRes->ssl, &alertInfo); ASSERT_TRUE(alertInfo.level == testExpect->expectLevel); ASSERT_EQ(alertInfo.description, testExpect->expectDescription); ASSERT_EQ(HLT_RpcGetTlsAcceptResult(serverRes->acceptId), testExpect->acceptExpect); EXIT: HLT_CleanFrameHandle(); HLT_FreeAllProcess(); } /* @ * @test UT_TLS_TLCP_CONSISTENCY_CERTFICATE_TC002 * @title The server receives the certificate verify message when receiving the certificate. * @precon nan * @brief 1. Configure dual-end verification. Expected result 1. * 2. Set the client callback type to certificate and replace it with certificate verify. Expected result 2. * @expect 1. Expected success. * 2. Expected server to return alert. @ */ /* BEGIN_CASE */ void UT_TLS_TLCP_CONSISTENCY_CERTFICATE_TC002() { TestExpect testExpect = {0}; testExpect.acceptExpect = HITLS_MSG_HANDLE_UNEXPECTED_MESSAGE; testExpect.expectLevel = ALERT_LEVEL_FATAL; testExpect.expectDescription = ALERT_UNEXPECTED_MESSAGE; testExpect.connectExpect = HITLS_REC_NORMAL_RECV_UNEXPECT_MSG; HLT_FrameHandle frameHandle = {0}; frameHandle.frameCallBack = TEST_SendUnexpectCertificateVerifyMsg; frameHandle.expectHsType = CERTIFICATE; frameHandle.expectReType = REC_TYPE_HANDSHAKE; frameHandle.ioState = EXP_NONE; frameHandle.pointType = POINT_SEND; frameHandle.userData = NULL; TEST_UnexpectMsg(&frameHandle, &testExpect, true); } /* END_CASE */ /* @ * @test UT_TLS_TLCP_CONSISTENCY_CERTFICATE_TC003 * @title Dual-end verification. The server receives the CERTIFICATION_VERIFY message when expecting to receive the * CLIENT_KEY_EXCHANGE message. * @precon nan * @brief 1. Configure unidirectional authentication. Expected result 1. * 2. Set the client callback mode to send certificate verify. Expected result 2. * @expect 1. Expected success. * 2. Expected server to return alert. @ */ /* BEGIN_CASE */ void UT_TLS_TLCP_CONSISTENCY_CERTFICATE_TC003() { TestExpect testExpect = {0}; testExpect.acceptExpect = HITLS_MSG_HANDLE_UNEXPECTED_MESSAGE; testExpect.expectLevel = ALERT_LEVEL_FATAL; testExpect.expectDescription = ALERT_UNEXPECTED_MESSAGE; testExpect.connectExpect = HITLS_REC_NORMAL_RECV_UNEXPECT_MSG; HLT_FrameHandle frameHandle = {0}; frameHandle.frameCallBack = TEST_SendUnexpectCertificateVerifyMsg; frameHandle.expectHsType = CLIENT_KEY_EXCHANGE; frameHandle.expectReType = REC_TYPE_HANDSHAKE; frameHandle.ioState = EXP_NONE; frameHandle.pointType = POINT_SEND; frameHandle.userData = NULL; TEST_UnexpectMsg(&frameHandle, &testExpect, true); } /* END_CASE */ // Replace the message to be sent with the CERTIFICATE. static 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 negotiation handshake messages. 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; frameType->transportType = BSL_UIO_TCP; if (memcpy_s(msg, sizeof(FRAME_Msg), &newFrameMsg, sizeof(newFrameMsg)) != EOK) { Print("TEST_SendUnexpectCertificateMsg memcpy_s Error!"); } } /* @ * @test UT_TLS_TLCP_CONSISTENCY_CERTFICATE_TC004 * @title Single-end verification, indicating that the server receives the CERTIFICATION message. * @precon nan * @brief 1. Configure unidirectional authentication. Expected result 1. * 2. Set the client severhello done callback mode to send certificate verify. Expected result 2. * @expect 1. Expected success. * 2. Expected server to return alert. @ */ /* BEGIN_CASE */ void UT_TLS_TLCP_CONSISTENCY_CERTFICATE_TC004() { TestExpect testExpect = {0}; testExpect.acceptExpect = HITLS_MSG_HANDLE_UNEXPECTED_MESSAGE; testExpect.expectLevel = ALERT_LEVEL_FATAL; testExpect.expectDescription = ALERT_UNEXPECTED_MESSAGE; testExpect.connectExpect = HITLS_REC_NORMAL_RECV_UNEXPECT_MSG; HLT_FrameHandle frameHandle = {0}; frameHandle.frameCallBack = TEST_SendUnexpectCertificateMsg; frameHandle.expectHsType = CLIENT_KEY_EXCHANGE; frameHandle.expectReType = REC_TYPE_HANDSHAKE; frameHandle.ioState = EXP_NONE; frameHandle.pointType = POINT_SEND; frameHandle.userData = NULL; TEST_UnexpectMsg(&frameHandle, &testExpect, false); } /* END_CASE */ static void Test_ErrCertVerify(HITLS_Ctx *ctx, uint8_t *data, uint32_t *len, uint32_t bufSize, void *user) { if (*(bool *)user) { return; } *(bool *)user = true; (void)ctx; (void)bufSize; (void)user; FRAME_Type frameType = { 0 }; frameType.versionType = HITLS_VERSION_TLCP_DTLCP11; frameType.keyExType = HITLS_KEY_EXCH_ECDHE; frameType.transportType = BSL_UIO_TCP; FRAME_Msg frameMsg = { 0 }; frameMsg.recType.data = REC_TYPE_HANDSHAKE; frameMsg.length.data = *len; frameMsg.recVersion.data = HITLS_VERSION_TLCP_DTLCP11; frameMsg.transportType = BSL_UIO_TCP; uint32_t parseLen = 0; FRAME_ParseMsgBody(&frameType, data, *len, &frameMsg, &parseLen); ASSERT_EQ(frameMsg.body.hsMsg.type.data, CERTIFICATE_VERIFY); ASSERT_EQ(parseLen, *len); frameMsg.body.hsMsg.body.certificateVerify.sign.data[0]++; FRAME_PackRecordBody(&frameType, &frameMsg, data, bufSize, len); EXIT: frameType.keyExType = HITLS_KEY_EXCH_ECDHE; FRAME_CleanMsg(&frameType, &frameMsg); return; } /* @ * @test UT_TLS_TLCP_CONSISTENCY_CERTFICATE_TC005 * @title Bidirectional verification. After the client sends a certificate, the certificate verify message contains * an incorrect digital signature or does not contain a digital signature. As a result, the link fails to be * established. * @precon nan * @brief 1. Start a handshake. Expected result 1 * 2. Modify the certificate verify message. Expected result 2 * @expect 1. Return success * 2. Handshake fails @ */ /* BEGIN_CASE */ void UT_TLS_TLCP_CONSISTENCY_CERTFICATE_TC005() { FRAME_Init(); HITLS_Config *config = NULL; FRAME_LinkObj *client; FRAME_LinkObj *server; bool isModify = false; RecWrapper wrapper = { TRY_SEND_CERTIFICATE_VERIFY, REC_TYPE_HANDSHAKE, false, &isModify, Test_ErrCertVerify }; RegisterWrapper(wrapper); config = HITLS_CFG_NewTLCPConfig(); client = FRAME_CreateTLCPLink(config, BSL_UIO_TCP, true); server = FRAME_CreateTLCPLink(config, BSL_UIO_TCP, false); ASSERT_NE(FRAME_CreateConnection(client, server, false, HS_STATE_BUTT), HITLS_SUCCESS); EXIT: HITLS_CFG_FreeConfig(config); FRAME_FreeLink(client); FRAME_FreeLink(server); ClearWrapper(); } /* END_CASE */ /* @ * @test UT_TLS_TLCP_CONSISTENCY_CERTFICATE_TC006 * @title Bidirectional verification. After the client sends a certificate, the certificate verify message contains * an incorrect digital signature or does not contain a digital signature. As a result, the link fails to be * established. * @precon nan * @brief 1. Start a handshake and set the ciphersuite to HITLS_ECC_SM4_CBC_SM3, Expected result 1 * 2. Modify the certificate verify message. Expected result 2 * @expect 1. Return success * 2. Handshake fails @ */ /* BEGIN_CASE */ void UT_TLS_TLCP_CONSISTENCY_CERTFICATE_TC006() { FRAME_Init(); HITLS_Config *config = NULL; FRAME_LinkObj *client; FRAME_LinkObj *server; bool isModify = false; RecWrapper wrapper = { TRY_SEND_CERTIFICATE_VERIFY, REC_TYPE_HANDSHAKE, false, &isModify, Test_ErrCertVerify }; RegisterWrapper(wrapper); uint16_t cipherSuite = HITLS_ECC_SM4_CBC_SM3; HITLS_CFG_SetCipherSuites(config, &cipherSuite, sizeof(cipherSuite) / sizeof(uint16_t)); config = HITLS_CFG_NewTLCPConfig(); client = FRAME_CreateTLCPLink(config, BSL_UIO_TCP, true); server = FRAME_CreateTLCPLink(config, BSL_UIO_TCP, false); ASSERT_NE(FRAME_CreateConnection(client, server, false, HS_STATE_BUTT), HITLS_SUCCESS); EXIT: HITLS_CFG_FreeConfig(config); FRAME_FreeLink(client); FRAME_FreeLink(server); ClearWrapper(); } /* END_CASE */ static int32_t SendCcs(HITLS_Ctx *ctx, uint8_t *data, uint8_t len) { /** Write records. */ return REC_Write(ctx, REC_TYPE_CHANGE_CIPHER_SPEC, data, len); } /* @ * @test UT_TLS_TLCP_CONSISTENCY_CCS_TC006 * @title 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 * @precon nan * @brief 1. Establish a connection. Expected result 1 * 2. Send a CCS message to client. Expected result 2 * 3. Send a CCS message to server. Expected result 3 * @expect 1. Return success * 2. client send ALERT_UNEXPECTED_MESSAGE alert * 3. server send ALERT_UNEXPECTED_MESSAGE alert @ */ /* BEGIN_CASE */ void UT_TLS_TLCP_CONSISTENCY_CCS_TC006(int isClient) { FRAME_Init(); HITLS_Config *tlsConfig = HITLS_CFG_NewTLCPConfig(); ASSERT_TRUE(tlsConfig != NULL); uint16_t toSetCipherSuite = GetCipherSuite("HITLS_ECDHE_SM4_CBC_SM3"); HITLS_CFG_SetCipherSuites(tlsConfig, &toSetCipherSuite, 1); 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_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); 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); 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 */ static void Test_Finish_Len_TooLong(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_TLCP_DTLCP11; FRAME_Msg frameMsg = { 0 }; frameMsg.recType.data = REC_TYPE_HANDSHAKE; frameMsg.length.data = *len; frameMsg.recVersion.data = HITLS_VERSION_TLCP_DTLCP11; uint32_t parseLen = 0; FRAME_ParseMsgBody(&frameType, data, *len, &frameMsg, &parseLen); ASSERT_EQ(parseLen, *len); ASSERT_EQ(frameMsg.body.hsMsg.type.data, FINISHED); ASSERT_EQ(frameMsg.body.hsMsg.body.finished.verifyData.size, 12); // in RFC5246, length of verifyData is always 12. frameMsg.body.hsMsg.body.finished.verifyData.state = ASSIGNED_FIELD; frameMsg.body.hsMsg.body.finished.verifyData.data[0] = 0x00; FRAME_PackRecordBody(&frameType, &frameMsg, data, bufSize, len); EXIT: FRAME_CleanMsg(&frameType, &frameMsg); return; } static void Test_Finish_Len_TooLong_client(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_TLCP_DTLCP11; FRAME_Msg frameMsg = { 0 }; frameMsg.recType.data = REC_TYPE_HANDSHAKE; frameMsg.length.data = *len; frameMsg.recVersion.data = HITLS_VERSION_TLCP_DTLCP11; uint32_t parseLen = 0; FRAME_ParseMsgBody(&frameType, data, *len, &frameMsg, &parseLen); ASSERT_EQ(parseLen, *len); ASSERT_EQ(frameMsg.body.hsMsg.type.data, FINISHED); ASSERT_EQ(frameMsg.body.hsMsg.body.finished.verifyData.size, 12); // in RFC5246, length of verifyData is always 12. if (ctx->isClient==true) { frameMsg.body.hsMsg.body.finished.verifyData.state = ASSIGNED_FIELD; frameMsg.body.hsMsg.body.finished.verifyData.data[0] += 1; } FRAME_PackRecordBody(&frameType, &frameMsg, data, bufSize, len); EXIT: FRAME_CleanMsg(&frameType, &frameMsg); return; } /* @ * @test UT_TLS_TLCP_CONSISTENCY_ERROR_FINISH_001 * @title An unexpected message is received when the server is in the TRY_RECV_FINISH state during the handshake. * @precon nan * @brief 1. Use the default configuration items to configure the client and server. Expected result 1. * 2. Construct a CLIENT_KEY_EXCHANGE message and send it to the server. Expected result 2. * @expect 1. The initialization is successful. * 2. After receiving the CLIENT_KEY_EXCHANGE message, the server sends an ALERT message. The level is * ALERT_Level_FATAL and the description is ALERT_UNEXPECTED_MESSAGE. @ */ /* BEGIN_CASE */ void UT_TLS_TLCP_CONSISTENCY_ERROR_FINISH_001(void) { FRAME_Init(); ResumeTestInfo testInfo = {0}; testInfo.version = HITLS_VERSION_TLCP_DTLCP11; testInfo.uioType = BSL_UIO_TCP; RecWrapper wrapper = { TRY_SEND_FINISH, REC_TYPE_HANDSHAKE, false, NULL, Test_Finish_Len_TooLong, }; RegisterWrapper(wrapper); testInfo.config = HITLS_CFG_NewTLCPConfig(); ASSERT_TRUE(testInfo.config != NULL); testInfo.client = FRAME_CreateTLCPLink(testInfo.config, testInfo.uioType, true); ASSERT_TRUE(testInfo.client != NULL); testInfo.server = FRAME_CreateTLCPLink(testInfo.config, testInfo.uioType, false); ASSERT_TRUE(testInfo.server != NULL); ASSERT_EQ(FRAME_CreateConnection(testInfo.client, testInfo.server, true, HS_STATE_BUTT), HITLS_MSG_HANDLE_VERIFY_FINISHED_FAIL); EXIT: ClearWrapper(); HITLS_CFG_FreeConfig(testInfo.config); FRAME_FreeLink(testInfo.client); FRAME_FreeLink(testInfo.server); } /* END_CASE */ /* @ * @test UT_TLS_TLCP_CONSISTENCY_ERROR_FINISH_002 * @title An unexpected message is received when the server is in the TRY_RECV_FINISH state during the handshake. * @precon nan * @brief 1. Use the default configuration items to configure the client and server. Expected result 1. * 2. Construct a CLIENT_KEY_EXCHANGE message and send it to the server. Expected result 2. * @expect 1. The initialization is successful. * 2. After receiving the CLIENT_KEY_EXCHANGE message, the server sends an ALERT message. The level is * ALERT_Level_FATAL and the description is ALERT_UNEXPECTED_MESSAGE. @ */ /* BEGIN_CASE */ void UT_TLS_TLCP_CONSISTENCY_ERROR_FINISH_002(void) { FRAME_Init(); ResumeTestInfo testInfo = {0}; testInfo.version = HITLS_VERSION_TLCP_DTLCP11; testInfo.uioType = BSL_UIO_TCP; RecWrapper wrapper = { TRY_SEND_FINISH, REC_TYPE_HANDSHAKE, false, NULL, Test_Finish_Len_TooLong_client, }; RegisterWrapper(wrapper); testInfo.config = HITLS_CFG_NewTLCPConfig(); ASSERT_TRUE(testInfo.config != NULL); testInfo.client = FRAME_CreateTLCPLink(testInfo.config, testInfo.uioType, true); ASSERT_TRUE(testInfo.client != NULL); testInfo.server = FRAME_CreateTLCPLink(testInfo.config, testInfo.uioType, false); ASSERT_TRUE(testInfo.server != NULL); ASSERT_EQ(FRAME_CreateConnection(testInfo.client, testInfo.server, true, HS_STATE_BUTT), HITLS_MSG_HANDLE_VERIFY_FINISHED_FAIL); EXIT: ClearWrapper(); HITLS_CFG_FreeConfig(testInfo.config); FRAME_FreeLink(testInfo.client); FRAME_FreeLink(testInfo.server); } /* END_CASE */ static int32_t GetDisorderServerCertAndKeyExchMsg(FRAME_LinkObj *server, uint8_t *data, uint32_t len, uint32_t *usedLen) { uint32_t readLen = 0; uint32_t offset = 0; uint8_t tmpData[READ_BUF_SIZE] = {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_TLCP_CONSISTENCY_DISORDER_TC001 * @title Configure dual-ended verification and construct abnormal scenarios. * @precon nan * @spec The server should send a server certificate message to the client, which always follows the server hello * message. If the selected cipher suite uses the RSA, ECC, or ECDHE algorithm, the message contains the * signature certificate and encryption certificate of the server. * @brief 1. Configure dual-end verification and construct an abnormal scenario. After the serverhello message is sent, * the sequence of the certificate message and serverkeyexchange message is changed. Expected result 1. * @expect 1. Client returns an unexpected alert message. @ */ /* BEGIN_CASE */ void UT_TLS_TLCP_CONSISTENCY_DISORDER_TC001(void) { FRAME_Init(); HITLS_Config *tlsConfig = NULL; FRAME_LinkObj *client = NULL; FRAME_LinkObj *server = NULL; tlsConfig = HITLS_CFG_NewTLCPConfig(); ASSERT_TRUE(tlsConfig != NULL); client = FRAME_CreateTLCPLink(tlsConfig, BSL_UIO_TCP, true); ASSERT_TRUE(client != NULL); server = FRAME_CreateTLCPLink(tlsConfig, BSL_UIO_TCP, false); ASSERT_TRUE(server != NULL); ASSERT_EQ(FRAME_CreateConnection(client, server, false, TRY_SEND_CERTIFICATE), HITLS_SUCCESS); ASSERT_TRUE(client->ssl->state == CM_STATE_HANDSHAKING); ASSERT_EQ(client->ssl->hsCtx->state, TRY_RECV_CERTIFICATE); uint8_t data[MAX_RECORD_LENTH] = {0}; uint32_t len = MAX_RECORD_LENTH; ASSERT_TRUE(GetDisorderServerCertAndKeyExchMsg(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_MSG_HANDLE_UNEXPECTED_MESSAGE); 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(tlsConfig); FRAME_FreeLink(client); FRAME_FreeLink(server); } /* END_CASE */ /* @ * @test UT_TLS_TLCP_CONSISTENCY_DISORDER_TC002 * @title During the handshake, the client receives the CCS when the client is receiving the clientkeyexchange. * @precon nan * @brief 1. Configure the single-end authentication. After the server sends the serverhellodone message, the client * stops in the try send client key exchange state. Expected result 1. * 2. Construct an unexpected CCS message and send it to the server. Expected result 2. * @expect 1. The initialization succeeds. * 2. The connection fails to be established and the server returns an unexpected message. @ */ /* BEGIN_CASE */ void UT_TLS_TLCP_CONSISTENCY_DISORDER_TC002(void) { FRAME_Init(); HITLS_Config *tlsConfig = HITLS_CFG_NewTLCPConfig(); ASSERT_TRUE(tlsConfig != NULL); uint16_t toSetCipherSuite = GetCipherSuite("HITLS_ECC_SM4_CBC_SM3"); HITLS_CFG_SetCipherSuites(tlsConfig, &toSetCipherSuite, 1); 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_TRUE(FRAME_CreateConnection(client, server, false, TRY_RECV_CLIENT_KEY_EXCHANGE) == HITLS_SUCCESS); uint32_t sendLen = 6; uint8_t sendBuf[6] = {0x14, 0x01, 0x01, 0x00, 0x01, 0x01}; FrameUioUserData *ioUserData = BSL_UIO_GetUserData(server->io); ioUserData->recMsg.len = 0; ASSERT_TRUE(FRAME_TransportRecMsg(server->io, sendBuf, sendLen) == HITLS_SUCCESS); ASSERT_TRUE(server->ssl != NULL); ASSERT_EQ(HITLS_Accept(server->ssl), HITLS_REC_NORMAL_RECV_UNEXPECT_MSG); ASSERT_TRUE(server->ssl->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_TLS_TLCP_CONSISTENCY_DISORDER_TC003 * @title During the handshake, the clientkeyexchange message is received when the client status is receiving the * certificate. * @precon nan * @brief 1. Configure dual-end authentication. After the server sends a serverhellodone message, the client stops in * the try send certificate state. Expected result 1. * 2. Construct an unexpected clientkeyexchange message and send the message to the server. Expected result 2. * @expect 1. The initialization succeeds. * 2. The connection fails to be established and the server returns an unexpected message. @ */ /* BEGIN_CASE */ void UT_TLS_TLCP_CONSISTENCY_DISORDER_TC003(void) { FRAME_Init(); HITLS_Config *tlsConfig = HITLS_CFG_NewTLCPConfig(); ASSERT_TRUE(tlsConfig != NULL); uint16_t toSetCipherSuite = GetCipherSuite("HITLS_ECDHE_SM4_CBC_SM3"); HITLS_CFG_SetCipherSuites(tlsConfig, &toSetCipherSuite, 1); 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_TRUE(FRAME_CreateConnection(client, server, false, TRY_RECV_CERTIFICATE) == HITLS_SUCCESS); FRAME_Msg frameMsg = {0}; FRAME_Type frameType = {0}; frameType.versionType = HITLS_VERSION_TLCP_DTLCP11; frameType.recordType = REC_TYPE_HANDSHAKE; frameType.handshakeType = CLIENT_KEY_EXCHANGE; 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); FrameUioUserData *ioUserData = BSL_UIO_GetUserData(server->io); 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_MSG_HANDLE_UNEXPECTED_MESSAGE); 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; 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_TRUE(alertMsg->alertDescription.data == ALERT_UNEXPECTED_MESSAGE); EXIT: FRAME_CleanMsg(&frameType, &frameMsg); HITLS_CFG_FreeConfig(tlsConfig); FRAME_FreeLink(client); FRAME_FreeLink(server); } /* END_CASE */ static int32_t STUB_APP_Write_Fatal(TLS_Ctx *ctx, const uint8_t *data, uint32_t dataLen, uint32_t *writeLen) { (void)data; (void)dataLen; (void)writeLen; ctx->method.sendAlert(ctx, ALERT_LEVEL_FATAL, ALERT_UNEXPECTED_MESSAGE); return HITLS_INTERNAL_EXCEPTION; } /* @ * @test UT_TLS_TLCP_CONSISTENCY_FATAL_ALERT_TC003 * @title Session processing in the case of critical alarms. * @precon nan * @spec When a critical alarm is sent or received, both parties should immediately close the connection and discard * the session ID and key of the incorrect connection. The connection closed by the critical alarm cannot be * reused. * @brief 1. Sending a fatal alert. Expected result 1. * 2. The server sends a fatal alert, the session information is used for the next connection. * Expected result 2. * @expect 1. The server fails to send data and receive data. * 2. The connection fails to be established. @ */ /* BEGIN_CASE */ void UT_TLS_TLCP_CONSISTENCY_FATAL_ALERT_TC003(char *cipherSuite, int isResume) { FRAME_Init(); HITLS_Config *tlsConfig = NULL; FRAME_LinkObj *client = NULL; FRAME_LinkObj *server = NULL; tlsConfig = HITLS_CFG_NewTLCPConfig(); ASSERT_TRUE(tlsConfig != NULL); uint16_t toSetCipherSuite = GetCipherSuite(cipherSuite); HITLS_CFG_SetCipherSuites(tlsConfig, &toSetCipherSuite, 1); client = FRAME_CreateTLCPLink(tlsConfig, BSL_UIO_TCP, true); ASSERT_TRUE(client != NULL); server = FRAME_CreateTLCPLink(tlsConfig, BSL_UIO_TCP, false); ASSERT_TRUE(server != NULL); int32_t ret = FRAME_CreateConnection(client, server, true, HS_STATE_BUTT); ASSERT_EQ(ret, HITLS_SUCCESS); FuncStubInfo tmpRpInfo = { 0 }; uint8_t readBuf[READ_BUF_SIZE] = {0}; HITLS_Session *Newsession = NULL; HITLS_Session *serverSession = NULL; uint32_t readLen = 0; uint8_t data[] = "Hello World"; STUB_Replace(&tmpRpInfo, APP_Write, STUB_APP_Write_Fatal); uint32_t writeLen; ASSERT_EQ(HITLS_Write(server->ssl, data, sizeof(data), &writeLen), HITLS_INTERNAL_EXCEPTION); STUB_Reset(&tmpRpInfo); ASSERT_TRUE(server->ssl->state == CM_STATE_ALERTED); if (isResume == 1) { serverSession = HITLS_GetDupSession(server->ssl); ASSERT_TRUE(serverSession != NULL); FRAME_FreeLink(client); client = NULL; FRAME_FreeLink(server); server = NULL; client = FRAME_CreateTLCPLink(tlsConfig, BSL_UIO_TCP, true); ASSERT_TRUE(client != NULL); server = FRAME_CreateTLCPLink(tlsConfig, BSL_UIO_TCP, false); ASSERT_TRUE(server != NULL); ASSERT_EQ(HITLS_SetSession(client->ssl, serverSession), 0); ASSERT_EQ(FRAME_CreateConnection(client, server, false, HS_STATE_BUTT), HITLS_SUCCESS); Newsession = HITLS_GetDupSession(client->ssl); ASSERT_TRUE(memcmp(serverSession->sessionId, Newsession->sessionId, HITLS_SESSION_ID_MAX_SIZE) != 0); } else { ASSERT_TRUE(HITLS_Write(server->ssl, data, sizeof(data), &writeLen) == HITLS_CM_LINK_FATAL_ALERTED); ASSERT_EQ(HITLS_Read(server->ssl, readBuf, READ_BUF_SIZE, &readLen), HITLS_CM_LINK_FATAL_ALERTED); } ASSERT_TRUE(HITLS_Close(client->ssl) == HITLS_SUCCESS); ASSERT_TRUE(client->ssl->state == CM_STATE_CLOSED); EXIT: HITLS_SESS_Free(Newsession); HITLS_SESS_Free(serverSession); HITLS_CFG_FreeConfig(tlsConfig); FRAME_FreeLink(client); FRAME_FreeLink(server); } /* END_CASE */ /* @ * @test UT_TLS_TLCP_CONSISTENCY_CLOSE_NOTIFY_TC001 * @title Close the link and check whether the close_notify alarm is sent. * @precon nan * @brief 1. Establish a connection between the client and server. Expected result 1. * 2. The client closes the link, obtains the message sent by the client, and checks whether the message is a * close_notify message. Expected result 2. * 3. The server obtains the received message and checks whether the message is a close_notify message. * Expected result 3. * @expect 1. The link is successfully established. * 2. The client sends a close_notify message. * 3. The server receives the close_notify message. @ */ /* BEGIN_CASE */ void UT_TLS_TLCP_CONSISTENCY_CLOSE_NOTIFY_TC001(void) { FRAME_Init(); HITLS_Config *tlsConfig = HITLS_CFG_NewTLCPConfig(); ASSERT_TRUE(tlsConfig != NULL); uint16_t toSetCipherSuite = GetCipherSuite("HITLS_ECDHE_SM4_CBC_SM3"); HITLS_CFG_SetCipherSuites(tlsConfig, &toSetCipherSuite, 1); 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_TRUE(FRAME_CreateConnection(client, server, true, TRY_RECV_SERVER_KEY_EXCHANGE) == HITLS_SUCCESS); 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(tlsConfig); FRAME_FreeLink(client); FRAME_FreeLink(server); } /* END_CASE */ /* @ * @test UT_TLS_TLCP_CONSISTENCY_CLOSE_NOTIFY_TC002 * @title Close the link and check whether the close_notify alarm is sent. * @precon nan * @brief 1. Establish a link between the client and server. Expected result 1. * 2. The client closes the link, obtains the message sent by the client, and checks whether the message is a * close_notify message. Expected result 2. * 3. The server processes the message received by the server, obtains the message to be sent after processing, * and checks whether the message is a close_notify message. Expected result 3. * @expect 1. The link is successfully established. * 2. The client sends a close_notify message. * 3. The server sends a close_notify message. @ */ /* BEGIN_CASE */ void UT_TLS_TLCP_CONSISTENCY_CLOSE_NOTIFY_TC002(void) { FRAME_Init(); HITLS_Config *tlsConfig = HITLS_CFG_NewTLCPConfig(); ASSERT_TRUE(tlsConfig != NULL); uint16_t toSetCipherSuite = GetCipherSuite("HITLS_ECDHE_SM4_CBC_SM3"); HITLS_CFG_SetCipherSuites(tlsConfig, &toSetCipherSuite, 1); 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_TRUE(FRAME_CreateConnection(client, server, true, TRY_RECV_SERVER_KEY_EXCHANGE) == HITLS_SUCCESS); 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_REC_NORMAL_IO_BUSY); serverioUserData->sndMsg.len = 0; ASSERT_EQ(HITLS_Accept(server->ssl), HITLS_CM_LINK_FATAL_ALERTED); FRAME_Msg serverframeMsg1 = {0}; uint8_t *serverbuffer1 = serverioUserData->sndMsg.msg; uint32_t serverreadLen1 = serverioUserData->sndMsg.len; uint32_t serverparseLen1 = 0; ret = ParserTotalRecord(server, &serverframeMsg1, serverbuffer1, serverreadLen1, &serverparseLen1); ASSERT_TRUE(ret == HITLS_SUCCESS); ASSERT_TRUE(serverframeMsg1.type == REC_TYPE_ALERT && serverframeMsg1.bodyLen == ALERT_BODY_LEN); ASSERT_TRUE(serverframeMsg1.body.alertMsg.level == ALERT_LEVEL_WARNING && serverframeMsg1.body.alertMsg.description == ALERT_CLOSE_NOTIFY); EXIT: HITLS_CFG_FreeConfig(tlsConfig); FRAME_FreeLink(client); FRAME_FreeLink(server); } /* END_CASE */ /* @ * @test UT_TLS_TLCP_CONSISTENCY_CLOSE_NOTIFY_TC003 * @title Close the link and check whether the close_notify alarm is sent. * @precon nan * @brief 1. Establish a connection between the client and server. Expected result 1. * 2. The server closes the link, obtains the message sent by the server, * and checks whether the message is a close_notify message. Expected result 2. * 3. Obtain the received message and check whether the message is a close_notify message. Expected result 3. * @expect 1. The link is successfully established. * 2. The server sends a close_notify message. * 3. The client receives the close_notify message. @ */ /* BEGIN_CASE */ void UT_TLS_TLCP_CONSISTENCY_CLOSE_NOTIFY_TC003(void) { FRAME_Init(); HITLS_Config *tlsConfig = HITLS_CFG_NewTLCPConfig(); ASSERT_TRUE(tlsConfig != NULL); uint16_t toSetCipherSuite = GetCipherSuite("HITLS_ECDHE_SM4_CBC_SM3"); HITLS_CFG_SetCipherSuites(tlsConfig, &toSetCipherSuite, 1); 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_TRUE(FRAME_CreateConnection(client, server, false, TRY_SEND_CERTIFICATE) == HITLS_SUCCESS); 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(tlsConfig); FRAME_FreeLink(client); FRAME_FreeLink(server); } /* END_CASE */ /* @ * @test UT_TLS_TLCP_CONSISTENCY_CLOSE_NOTIFY_TC004 * @title Close the link and check whether the close_notify alarm is sent. * @precon nan * @brief 1. Establish a link between the client and server. Expected result 1. * 2. The server closes the link, obtains the message sent by the server, * and checks whether the message is a close_notify message. Expected result 2. * 3. The client processes the received message, obtains the message to be sent after processing, * and checks whether the message is a close_notify message. Expected result 3. * @expect 1. The link is successfully established. * 2. The client sends a close_notify message. * 3. The server sends a close_notify message. @ */ /* BEGIN_CASE */ void UT_TLS_TLCP_CONSISTENCY_CLOSE_NOTIFY_TC004(void) { FRAME_Init(); HITLS_Config *tlsConfig = HITLS_CFG_NewTLCPConfig(); ASSERT_TRUE(tlsConfig != NULL); uint16_t toSetCipherSuite = GetCipherSuite("HITLS_ECDHE_SM4_CBC_SM3"); HITLS_CFG_SetCipherSuites(tlsConfig, &toSetCipherSuite, 1); 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_TRUE(FRAME_CreateConnection(client, server, true, TRY_SEND_FINISH) == HITLS_SUCCESS); 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); FrameUioUserData *clientioUserData = BSL_UIO_GetUserData(client->io); clientioUserData->recMsg.len = 0; ASSERT_TRUE(FRAME_TrasferMsgBetweenLink(server, client) == HITLS_SUCCESS); 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); ASSERT_TRUE(client->ssl != NULL); clientioUserData->sndMsg.len = 0; ASSERT_EQ(HITLS_Connect(client->ssl), HITLS_REC_NORMAL_IO_BUSY); clientioUserData->sndMsg.len = 0; ASSERT_EQ(HITLS_Connect(client->ssl), HITLS_CM_LINK_FATAL_ALERTED); FRAME_Msg clientframeMsg1 = {0}; uint8_t *clientbuffer1 = clientioUserData->sndMsg.msg; uint32_t clientreadLen1 = clientioUserData->sndMsg.len; uint32_t clientparseLen1 = 0; ret = ParserTotalRecord(client, &clientframeMsg1, clientbuffer1, clientreadLen1, &clientparseLen1); ASSERT_TRUE(ret == HITLS_SUCCESS); ASSERT_TRUE(clientframeMsg1.type == REC_TYPE_ALERT); ALERT_Info alert = { 0 }; ALERT_GetInfo(client->ssl, &alert); ASSERT_EQ(alert.level, ALERT_LEVEL_WARNING); ASSERT_EQ(alert.description, ALERT_CLOSE_NOTIFY); EXIT: HITLS_CFG_FreeConfig(tlsConfig); FRAME_FreeLink(client); FRAME_FreeLink(server); } /* END_CASE */ /* @ * @test UT_TLS_TLCP_CONSISTENCY_AMEND_APPDATA_TC001 * @title Modify the app message received by the client, modify the encrypted data, inject the message, * and observe the response from the client. * @precon nan * @spec "AEADEncrypted = AEAD-Encrypt(write_ key, nonce, plaintext, additional data) To decrypt and verify, * the cryptographic algorithm uses the key, random number, additional_data and AEADEncrypted values are used * as inputs. The output is plaintext or an error indicating a decryption failure. There is no additional * integrity check. I.e.: TLSCompressed. fragment= AEAD-Decrypt (write_key, nonce,AEADEncrypted, * additional_data) A fatal bad_record_mac warning should be generated if decryption fails. See Appendix A for * the GCM Authenticated Encryption Mode." * @brief 1. Set up a link, read and write data, modify the app message received by the client, modify the encrypted * data, and perform message injection. Observe the response from the client. Expected result 1. * 2. Set up a link, read and write data, modify the app message received by the server, modify the encrypted * data, and perform message injection. Observe the response of the server. Expected result 2. * @expect 1. The bad_record_mac alert is sent. * 2. The bad_record_mac alert is sent. @ */ /* BEGIN_CASE */ void UT_TLS_TLCP_CONSISTENCY_AMEND_APPDATA_TC001(char *cipherSuite, int isClient) { FRAME_Init(); HITLS_Config *tlsConfig = HITLS_CFG_NewTLCPConfig(); ASSERT_TRUE(tlsConfig != NULL); uint16_t toSetCipherSuite = GetCipherSuite(cipherSuite); HITLS_CFG_SetCipherSuites(tlsConfig, &toSetCipherSuite, 1); FRAME_LinkObj *client = FRAME_CreateTLCPLink(tlsConfig, BSL_UIO_TCP, true); ASSERT_TRUE(client != NULL); FRAME_LinkObj *server = FRAME_CreateTLCPLink(tlsConfig, BSL_UIO_TCP, false); ASSERT_TRUE(server != NULL); ASSERT_EQ(FRAME_CreateConnection(client, server, true, HS_STATE_BUTT), HITLS_SUCCESS); FRAME_LinkObj *recver = isClient ? client : server; FRAME_LinkObj *sender = isClient ? server : client; uint8_t data[] = "Hello World"; uint8_t readBuf[READ_BUF_SIZE] = {0}; uint32_t readLen = 0; uint32_t writeLen = 0; ASSERT_EQ(HITLS_Write(sender->ssl, data, sizeof(data), &writeLen), HITLS_SUCCESS); ASSERT_TRUE(FRAME_TrasferMsgBetweenLink(sender, recver) == HITLS_SUCCESS); FRAME_Msg frameMsg = { 0 }; FRAME_Type frameType = { 0 }; FrameUioUserData *ioUserData = BSL_UIO_GetUserData(recver->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_TLCP_DTLCP11; frameType.recordType = REC_TYPE_APP; frameType.keyExType = HITLS_KEY_EXCH_ECDHE; ASSERT_TRUE(FRAME_ParseMsg(&frameType, recvBuf, recvLen, &frameMsg, &parseLen) == HITLS_SUCCESS); FRAME_AppMsg *appMsg = &frameMsg.body.appMsg; uint8_t appData[] = "123"; appMsg->appData.state = ASSIGNED_FIELD; ASSERT_EQ(memcpy_s(appMsg->appData.data, appMsg->appData.size, "123", sizeof(appData)), 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(recver->io, sendBuf, sendLen) == HITLS_SUCCESS); FRAME_CleanMsg(&frameType, &frameMsg); memset_s(&frameMsg, sizeof(frameMsg), 0, sizeof(frameMsg)); ASSERT_EQ(HITLS_Read(recver->ssl, readBuf, READ_BUF_SIZE, &readLen), HITLS_REC_BAD_RECORD_MAC); ALERT_Info alertInfo = { 0 }; ALERT_GetInfo(recver->ssl, &alertInfo); ASSERT_EQ(alertInfo.description, ALERT_BAD_RECORD_MAC); ASSERT_TRUE(HITLS_Close(client->ssl) == HITLS_SUCCESS); ASSERT_TRUE(client->ssl->state == CM_STATE_CLOSED); EXIT: HITLS_CFG_FreeConfig(tlsConfig); FRAME_FreeLink(client); FRAME_FreeLink(server); } /* END_CASE */ /* @ * @test UT_FRAME_FUNC_TLCP_CERT_MISMATCH_TC001 * @title After receiving the servehellodone message from the server, the client checks whether the server certificate * is valid and whether the parameters in the servehello message are acceptable. * @precon nan * @spec After receiving the servehellodone message from the server, the client verifies whether the server * certificate is valid and whether the server's servehello message parameters are acceptable. If acceptable, * the client continues the handshake process. Otherwise, a HandShakeFailure fatal alarm is sent. * @brief 1. Set the algorithm suite to ECDHE_SM4_CBC_SM3 on the client and server, and load the RSA certificate to * the server. Expected result 1. * 2. Set the algorithm suite to ECC_SM4_CBC_SM3 on the client and server, and load the RSA certificate to * the server. Expected result 2. * @expect 1. The server fails to negotiate the cipher suite (the certificate and cipher suite do not match). * 2. The server fails to negotiate the cipher suite (the certificate and cipher suite do not match). @ */ /* BEGIN_CASE */ void UT_FRAME_FUNC_TLCP_CERT_MISMATCH_TC001(char *cipherSuite) { FRAME_Init(); HITLS_Config *tlsConfig = NULL; FRAME_LinkObj *client = NULL; FRAME_LinkObj *server = NULL; FRAME_CertInfo certInfo = { "sm2/ca.der", "sm2/inter.der", "rsa_sha256/server.der", "sm2/sign.der", "rsa_sha256/server.key.der", "sm2/sign.key.der", }; tlsConfig = HITLS_CFG_NewTLCPConfig(); ASSERT_TRUE(tlsConfig != NULL); uint16_t toSetCipherSuite = GetCipherSuite(cipherSuite); HITLS_CFG_SetCipherSuites(tlsConfig, &toSetCipherSuite, 1); client = FRAME_CreateLinkWithCert(tlsConfig, BSL_UIO_TCP, &certInfo); ASSERT_TRUE(client != NULL); server = FRAME_CreateLinkWithCert(tlsConfig, BSL_UIO_TCP, &certInfo); ASSERT_TRUE(server != NULL); ASSERT_EQ(FRAME_CreateConnection(client, server, true, HS_STATE_BUTT), HITLS_MSG_HANDLE_CIPHER_SUITE_ERR); ALERT_Info alertInfo = { 0 }; ALERT_GetInfo(server->ssl, &alertInfo); ASSERT_EQ(alertInfo.description, ALERT_HANDSHAKE_FAILURE); EXIT: HITLS_CFG_FreeConfig(tlsConfig); FRAME_FreeLink(client); FRAME_FreeLink(server); } /* END_CASE */ /* @ * @test UT_TLS_TLCP_CONSISTENCY_KEYUSAGE_TC001 * @title The encryption certificate does not have a keyusage extension, and check the result. * @precon nan * @brief 1. Use the default configuration on the client and server,Server setting encryption certificate without * keyusage extension. Expected result 1. * 2. Start a handshake. Expected result 2. * @expect 1. The initialization is successful. * 2. The client sends the ALERT_BAD_CERTIFICATE message. @ */ /* BEGIN_CASE */ void UT_TLS_TLCP_CONSISTENCY_KEYUSAGE_TC001() { FRAME_Init(); HITLS_Config *tlsConfig = NULL; FRAME_LinkObj *client = NULL; FRAME_LinkObj *server = NULL; FRAME_CertInfo certInfo = { "sm2_cert/root.der", "sm2_cert/intCa.der", "sm2_cert/server_enc_no_keyusage.der", "sm2_cert/server_sign.der", "sm2_cert/server_enc_no_keyusage.key.der", "sm2_cert/server_sign.key.der", }; tlsConfig = HITLS_CFG_NewTLCPConfig(); ASSERT_TRUE(tlsConfig != NULL); client = FRAME_CreateLinkWithCert(tlsConfig, BSL_UIO_TCP, &certInfo); ASSERT_TRUE(client != NULL); server = FRAME_CreateLinkWithCert(tlsConfig, BSL_UIO_TCP, &certInfo); ASSERT_TRUE(server != NULL); int32_t ret = FRAME_CreateConnection(client, server, true, HS_STATE_BUTT); ASSERT_EQ(ret, HITLS_CERT_ERR_EXP_CERT); 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_BAD_CERTIFICATE); EXIT: HITLS_CFG_FreeConfig(tlsConfig); FRAME_FreeLink(client); FRAME_FreeLink(server); } /* END_CASE */ /* @ * @test UT_TLS_TLCP_CONSISTENCY_KEYUSAGE_TC002 * @title The signing certificate does not have a keyusage extension, and check the result. * @precon nan * @brief 1. Use the default configuration on the client and server,Server setting signing certificate without * keyusage extension. Expected result 1. * 2. Start a handshake. Expected result 2. * @expect 1. The initialization is successful. * 2. The client sends the ALERT_BAD_CERTIFICATE message. @ */ /* BEGIN_CASE */ void UT_TLS_TLCP_CONSISTENCY_KEYUSAGE_TC002() { FRAME_Init(); HITLS_Config *tlsConfig = NULL; FRAME_LinkObj *client = NULL; FRAME_LinkObj *server = NULL; FRAME_CertInfo certInfo = { "sm2_cert/root.der", "sm2_cert/intCa.der", "sm2_cert/server_enc.der", "sm2_cert/server_sign_no_keyusage.der", "sm2_cert/server_enc.key.der", "sm2_cert/server_sign_no_keyusage.key.der", }; tlsConfig = HITLS_CFG_NewTLCPConfig(); ASSERT_TRUE(tlsConfig != NULL); client = FRAME_CreateLinkWithCert(tlsConfig, BSL_UIO_TCP, &certInfo); ASSERT_TRUE(client != NULL); server = FRAME_CreateLinkWithCert(tlsConfig, BSL_UIO_TCP, &certInfo); ASSERT_TRUE(server != NULL); int32_t ret = FRAME_CreateConnection(client, server, true, HS_STATE_BUTT); ASSERT_EQ(ret, HITLS_CERT_ERR_KEYUSAGE); 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_BAD_CERTIFICATE); EXIT: HITLS_CFG_FreeConfig(tlsConfig); FRAME_FreeLink(client); FRAME_FreeLink(server); } /* END_CASE */ /* @ * @test UT_TLS_TLCP_CONSISTENCY_KEYUSAGE_TC003 * @title The signature certificate has an incorrect keyusage extension, and check the result. * @precon nan * @brief 1. Use the default configuration on the client and server,The server's signature certificate contains an * incorrect keyusage extension. Expected result 1. * 2. Start a handshake. Expected result 2. * @expect 1. The initialization is successful. * 2. The client sends the ALERT_BAD_CERTIFICATE message. @ */ /* BEGIN_CASE */ void UT_TLS_TLCP_CONSISTENCY_KEYUSAGE_TC003() { FRAME_Init(); HITLS_Config *tlsConfig = NULL; FRAME_LinkObj *client = NULL; FRAME_LinkObj *server = NULL; FRAME_CertInfo certInfo = { "sm2_cert/root.der", "sm2_cert/intCa.der", "sm2_cert/server_enc.der", "sm2_cert/client_sign_err_keyusage.der", "sm2_cert/server_enc.key.der", "sm2_cert/client_sign_err_keyusage.key.der", }; tlsConfig = HITLS_CFG_NewTLCPConfig(); ASSERT_TRUE(tlsConfig != NULL); client = FRAME_CreateLinkWithCert(tlsConfig, BSL_UIO_TCP, &certInfo); ASSERT_TRUE(client != NULL); server = FRAME_CreateLinkWithCert(tlsConfig, BSL_UIO_TCP, &certInfo); ASSERT_TRUE(server != NULL); int32_t ret = FRAME_CreateConnection(client, server, true, HS_STATE_BUTT); ASSERT_EQ(ret, HITLS_CERT_ERR_KEYUSAGE); 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_BAD_CERTIFICATE); EXIT: HITLS_CFG_FreeConfig(tlsConfig); FRAME_FreeLink(client); FRAME_FreeLink(server); } /* END_CASE */ /* @ * @test UT_TLS_TLCP_CONSISTENCY_KEYUSAGE_TC004 * @title The encryption certificate has an incorrect keyusage extension, and check the result. * @precon nan * @brief 1. Use the default configuration on the client and server,The server's encryption certificate contains an * incorrect keyusage extension. Expected result 1. * 2. Start a handshake. Expected result 2. * @expect 1. The initialization is successful. * 2. The client sends the ALERT_BAD_CERTIFICATE message. @ */ /* BEGIN_CASE */ void UT_TLS_TLCP_CONSISTENCY_KEYUSAGE_TC004() { FRAME_Init(); HITLS_Config *tlsConfig = NULL; FRAME_LinkObj *client = NULL; FRAME_LinkObj *server = NULL; FRAME_CertInfo certInfo = { "sm2_cert/root.der", "sm2_cert/intCa.der", "sm2_cert/client_enc_err_keyusage.der", "sm2_cert/server_sign.der", "sm2_cert/client_enc_err_keyusage.key.der", "sm2_cert/server_sign.key.der", }; tlsConfig = HITLS_CFG_NewTLCPConfig(); ASSERT_TRUE(tlsConfig != NULL); client = FRAME_CreateLinkWithCert(tlsConfig, BSL_UIO_TCP, &certInfo); ASSERT_TRUE(client != NULL); server = FRAME_CreateLinkWithCert(tlsConfig, BSL_UIO_TCP, &certInfo); ASSERT_TRUE(server != NULL); int32_t ret = FRAME_CreateConnection(client, server, true, HS_STATE_BUTT); ASSERT_EQ(ret, HITLS_CERT_ERR_EXP_CERT); 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_BAD_CERTIFICATE); EXIT: HITLS_CFG_FreeConfig(tlsConfig); FRAME_FreeLink(client); FRAME_FreeLink(server); } /* END_CASE */
2301_79861745/bench_create
testcode/sdv/testcase/tls/consistency/tlcp/test_suite_sdv_frame_tlcp_consistency_3.c
C
unknown
69,427
/* * This file is part of the openHiTLS project. * * openHiTLS is licensed under the Mulan PSL v2. * You can use this software according to the terms and conditions of the Mulan PSL v2. * You may obtain a copy of Mulan PSL v2 at: * * http://license.coscl.org.cn/MulanPSL2 * * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, * EITHER EXPRESS 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 "hs_ctx.h" #include "pack.h" #include "process.h" #include "session_type.h" #include "hitls_type.h" #include "send_process.h" #include "frame_tls.h" #include "frame_link.h" #include "frame_io.h" #include "uio_base.h" #include "simulate_io.h" #include "parser_frame_msg.h" #include "cert.h" #include "app.h" #include "hlt.h" #include "alert.h" #include "securec.h" #include "record.h" #include "rec_wrapper.h" #include "conn_init.h" #include "cert_callback.h" #include "change_cipher_spec.h" #include "common_func.h" #include "crypt_util_rand.h" /* END_HEADER */ static uint32_t g_uiPort = 16888; #define READ_BUF_SIZE (18 * 1024) /* Maximum length of the read message buffer */ #define REC_CONN_SEQ_SIZE 8u /* SN size */ #define PORT 11111 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; /* For CCS test, stop at TRY_RECV_FINISH stage before CCS message is received. */ } HandshakeTestInfo; int32_t GetSessionCacheMode(HLT_Ctx_Config* config) { return config->setSessionCache; } /* @ * @test SDV_TLS_TLCP_CONSISTENCY_RESUME_FUNC_TC001 * @title Modify the resume flag on the client. Resumption fails * @precon nan * @brief 1. Establish the connection. Expected result 1 2. Perform the first handshake, obtain and save the session. Expected result 2 3. Modify the resume flag and resume the session. Expected result 3 * @expect 1. Return success 2. The handshake is complete and obtain the session successfully 3. Resumption fails @ */ /* BEGIN_CASE */ void SDV_TLS_TLCP_CONSISTENCY_RESUME_FUNC_TC001(int version, int connType) { Process *localProcess = NULL; Process *remoteProcess = NULL; int32_t cachemode = 0; HLT_FD sockFd = {0}; int cnt = 1; int32_t serverConfigId = 0; HITLS_Session *session = NULL; const char *writeBuf = "Hello world"; uint8_t readBuf[READ_BUF_SIZE] = {0}; uint32_t readLen; 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_NewCtxConfigTLCP(NULL, "CLIENT", true); HLT_Ctx_Config *serverCtxConfig = HLT_NewCtxConfigTLCP(NULL, "SERVER", false); 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 cachemode = GetSessionCacheMode(clientCtxConfig); ASSERT_EQ(cachemode , HITLS_SESS_CACHE_SERVER); ASSERT_TRUE(HLT_TlsSetCtx(clientConfig, clientCtxConfig) == 0); ASSERT_TRUE(HLT_RpcTlsSetCtx(remoteProcess, serverConfigId, serverCtxConfig) == 0); do { DataChannelParam channelParam; channelParam.port = PORT; 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) { SESS_Disable(session); ASSERT_TRUE(HITLS_SESS_IsResumable(session) == false); 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, 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); if (cnt == 2) { HITLS_Session *Newsession = NULL; Newsession = HITLS_GetDupSession(clientSsl); ASSERT_TRUE(memcmp(session->sessionId, Newsession->sessionId, HITLS_SESSION_ID_MAX_SIZE) != 0); HITLS_SESS_Free(Newsession); } else { session = HITLS_GetDupSession(clientSsl); ASSERT_TRUE(session != NULL); ASSERT_TRUE(HITLS_SESS_IsResumable(session) == true); } cnt++; } while (cnt <= 2); EXIT: HITLS_SESS_Free(session); HLT_FreeAllProcess(); } /* END_CASE */ /* @ * @test SDV_TLS_TLCP_CONSISTENCY_RESUME_FUNC_TC002 * @title During session resumption, set none cipher suite. The resumption fails * @precon nan * @brief 1. Establish a connection. Expected result 1 2. Perform the first handshake, obtain and save the session. Expected result 2 3. During session resumption, do not set the cipher suite and resume the session. Expected result 3 * @expect 1. Return success 2. The handshake is complete and obtain the session successfully 3. Failed to resume the session. @ */ /* BEGIN_CASE */ void SDV_TLS_TLCP_CONSISTENCY_RESUME_FUNC_TC002(int version, int connType) { Process *localProcess = NULL; Process *remoteProcess = NULL; HLT_FD sockFd = {0}; int cnt = 1; int32_t serverConfigId = 0; HITLS_Session *session = NULL; const char *writeBuf = "Hello world"; uint8_t readBuf[READ_BUF_SIZE] = {0}; uint32_t readLen; uint16_t sess_Ciphersuite; 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_NewCtxConfigTLCP(NULL, "CLIENT", true); HLT_Ctx_Config *serverCtxConfig = HLT_NewCtxConfigTLCP(NULL, "SERVER", 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 = PORT; 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 ) { HITLS_SESS_GetCipherSuite(session, &sess_Ciphersuite); ASSERT_TRUE(HITLS_SESS_SetCipherSuite(session, 0) == HITLS_SUCCESS); ASSERT_TRUE(HITLS_SetSession(clientSsl, session) == HITLS_SUCCESS); ASSERT_EQ(HLT_TlsConnect(clientSsl), HITLS_MSG_HANDLE_ILLEGAL_CIPHER_SUITE); } 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); if (cnt == 1) { session = HITLS_GetDupSession(clientSsl); ASSERT_TRUE(session != NULL); ASSERT_TRUE(HITLS_SESS_IsResumable(session) == true); } cnt++; } while (cnt < 3); EXIT: HITLS_SESS_Free(session); HLT_FreeAllProcess(); } /* END_CASE */ /* @ * @test SDV_TLS_TLCP_CONSISTENCY_RESUME_FUNC_TC003 * @title Session resume succeed * @precon nan * @brief 1. Establish the connection. Expected result 1 2. Perform the first handshake, obtain and save the session. Expected result 2 3. The client carries the session ID for first connection establishment and resumes the session. The server sends the same session ID in the hello message. Expected result 3 * @expect 1. Return success 2. The handshake is complete and obtain the session successfully 3. The session is resumed successfully @ */ /* BEGIN_CASE */ void SDV_TLS_TLCP_CONSISTENCY_RESUME_FUNC_TC003(int version, int connType) { Process *localProcess = NULL; Process *remoteProcess = NULL; HLT_FD sockFd = {0}; int cnt = 1; int32_t serverConfigId = 0; HITLS_Session *session = NULL; const char *writeBuf = "Hello world"; uint8_t readBuf[READ_BUF_SIZE] = {0}; uint32_t readLen; 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_NewCtxConfigTLCP(NULL, "CLIENT", true); HLT_Ctx_Config *serverCtxConfig = HLT_NewCtxConfigTLCP(NULL, "SERVER", 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 = PORT; 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_EQ(HLT_TlsConnect(clientSsl), HITLS_SUCCESS); uint8_t isReused = 0; ASSERT_TRUE(HITLS_IsSessionReused(clientSsl, &isReused) == HITLS_SUCCESS); ASSERT_TRUE(isReused == 1); } 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); if (cnt == 1) { session = HITLS_GetDupSession(clientSsl); ASSERT_TRUE(session != NULL); ASSERT_TRUE(HITLS_SESS_IsResumable(session) == true); } cnt++; } while (cnt < 3); EXIT: HITLS_SESS_Free(session); HLT_FreeAllProcess(); } /* END_CASE */ /* @ * @test SDV_TLS_TLCP_CONSISTENCY_RESUME_FUNC_TC004 * @title Use same session to resume two connections * @precon nan * @brief 1. Establish the connection. Expected result 1 2. Perform the first handshake, obtain and save the session. Expected result 2 3. Use same session to resume two different connections at the same time. Expected result 3 * @expect 1. Return success 2. The handshake is complete and obtain the session successfully 3. The session is resumed successfully on both connections at the same time @ */ /* BEGIN_CASE */ void SDV_TLS_TLCP_CONSISTENCY_RESUME_FUNC_TC004(int version, int connType) { Process *localProcess = NULL; Process *remoteProcess = NULL; HLT_FD sockFd = {0}; HLT_FD sockFd2 = {0}; int count = 1; int32_t serverConfigId = 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); void *clientConfig2 = HLT_TlsNewCtx(version); ASSERT_TRUE(clientConfig != NULL); ASSERT_TRUE(clientConfig2 != NULL); HLT_Ctx_Config *clientCtxConfig = HLT_NewCtxConfigTLCP(NULL, "CLIENT", true); HLT_Ctx_Config *clientCtxConfig2 = HLT_NewCtxConfigTLCP(NULL, "CLIENT", true); HLT_Ctx_Config *serverCtxConfig = HLT_NewCtxConfigTLCP(NULL, "SERVER", 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_TlsSetCtx(clientConfig2, clientCtxConfig2) == 0); ASSERT_TRUE(HLT_RpcTlsSetCtx(remoteProcess, serverConfigId, serverCtxConfig) == 0); do { if (session != NULL) { DataChannelParam channelParam2; channelParam2.port = PORT; channelParam2.type = connType; channelParam2.isBlock = true; sockFd2 = HLT_CreateDataChannel(localProcess, remoteProcess, channelParam2); ASSERT_TRUE((sockFd2.srcFd > 0) && (sockFd2.peerFd > 0)); remoteProcess->connType = connType; localProcess->connType = connType; remoteProcess->connFd = sockFd2.peerFd; localProcess->connFd = sockFd2.srcFd; 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(clientConfig2); 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); HITLS_Session *Newsession = HITLS_GetDupSession(clientSsl); ASSERT_TRUE(Newsession != NULL); ASSERT_TRUE(memcmp(session->sessionId, Newsession->sessionId, HITLS_SESSION_ID_MAX_SIZE) == 0); HITLS_SESS_Free(Newsession); } DataChannelParam channelParam; channelParam.port = PORT; 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; 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); 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); HITLS_SESS_Free(session); session = HITLS_GetDupSession(clientSsl); ASSERT_TRUE(session != NULL); ASSERT_TRUE(HITLS_SESS_IsResumable(session) == true); if (count == 2) { uint8_t isReused = 0; ASSERT_TRUE(HITLS_IsSessionReused(clientSsl, &isReused) == HITLS_SUCCESS); ASSERT_TRUE(isReused == 1); } count++; } while (count <= 2); EXIT: HITLS_SESS_Free(session); HLT_FreeAllProcess(); } /* END_CASE */ /* @ * @test SDV_TLS_TLCP_CONSISTENCY_RESUME_FUNC_TC005 * @title Multiple connections can be established using the same session * @precon nan * @brief 1. Establish the connection. Expected result 1 2. Perform the first handshake, obtain and save the session. Expected result 2 3. Use same session to resume three connections. Expected result 3 * @expect 1. Return success 2. The handshake is complete and obtain the session successfully 3. The sessions are all resumed successfully @ */ /* BEGIN_CASE */ void SDV_TLS_TLCP_CONSISTENCY_RESUME_FUNC_TC005(int version, int connType) { Process *localProcess = NULL; Process *remoteProcess = NULL; int32_t cachemode = 0; HLT_FD sockFd = {0}; int cnt = 1; int32_t serverConfigId = 0; HITLS_Session *session = NULL; const char *writeBuf = "Hello world"; uint8_t readBuf[READ_BUF_SIZE] = {0}; uint32_t readLen; 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_NewCtxConfigTLCP(NULL, "CLIENT", true); HLT_Ctx_Config *serverCtxConfig = HLT_NewCtxConfigTLCP(NULL, "SERVER", 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 cachemode = GetSessionCacheMode(clientCtxConfig); ASSERT_EQ(cachemode , HITLS_SESS_CACHE_SERVER); ASSERT_TRUE(HLT_TlsSetCtx(clientConfig, clientCtxConfig) == 0); ASSERT_TRUE(HLT_RpcTlsSetCtx(remoteProcess, serverConfigId, serverCtxConfig) == 0); do { DataChannelParam channelParam; channelParam.port = PORT; 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); 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); if (cnt != 1) { HITLS_Session *Newsession = NULL; Newsession = HITLS_GetDupSession(clientSsl); ASSERT_TRUE(memcmp(session->sessionId, Newsession->sessionId, HITLS_SESSION_ID_MAX_SIZE) == 0); HITLS_SESS_Free(Newsession); } else { session = HITLS_GetDupSession(clientSsl); ASSERT_TRUE(session != NULL); ASSERT_TRUE(HITLS_SESS_IsResumable(session) == true); } cnt++; } while (cnt <= 4); EXIT: HITLS_SESS_Free(session); HLT_FreeAllProcess(); } /* END_CASE */ /* @ * @test SDV_TLS_TLCP_CONSISTENCY_RESUME_FUNC_TC006 * @title Modify the session ID on the client. Resumption fails * @precon nan * @brief 1. Establish the connection. Expected result 1 2. Perform the first handshake, obtain and save the session. Expected result 2 3. Modify the session ID and resume the session. Expected result 3 * @expect 1. Return success 2. The handshake is complete and obtain the session successfully 3. Resumption fails @ */ /* BEGIN_CASE */ void SDV_TLS_TLCP_CONSISTENCY_RESUME_FUNC_TC006(int version, int connType) { Process *localProcess = NULL; Process *remoteProcess = NULL; int32_t cachemode = 0; HLT_FD sockFd = {0}; int cnt = 1; int32_t serverConfigId = 0; HITLS_Session *session = NULL; const char *writeBuf = "Hello world"; uint8_t readBuf[READ_BUF_SIZE] = {0}; uint32_t readLen; 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_NewCtxConfigTLCP(NULL, "CLIENT", true); HLT_Ctx_Config *serverCtxConfig = HLT_NewCtxConfigTLCP(NULL, "SERVER", 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 cachemode = GetSessionCacheMode(clientCtxConfig); ASSERT_EQ(cachemode , HITLS_SESS_CACHE_SERVER); ASSERT_TRUE(HLT_TlsSetCtx(clientConfig, clientCtxConfig) == 0); ASSERT_TRUE(HLT_RpcTlsSetCtx(remoteProcess, serverConfigId, serverCtxConfig) == 0); do { DataChannelParam channelParam; channelParam.port = PORT; 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) { session->sessionId[0] -= 1; 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, 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); if (cnt == 2) { HITLS_Session *Newsession = NULL; Newsession = HITLS_GetDupSession(clientSsl); ASSERT_TRUE(memcmp(session->sessionId, Newsession->sessionId, HITLS_SESSION_ID_MAX_SIZE) != 0); HITLS_SESS_Free(Newsession); } else { session = HITLS_GetDupSession(clientSsl); ASSERT_TRUE(session != NULL); ASSERT_TRUE(HITLS_SESS_IsResumable(session) == true); } cnt++; } while (cnt <= 2); EXIT: HITLS_SESS_Free(session); HLT_FreeAllProcess(); } /* END_CASE */ /* @ * @test SDV_TLS_TLCP_CONSISTENCY_RESUME_FUNC_TC007 * @title Modify the session cipher suite on the client. Resumption fails * @precon nan * @brief 1. Establish the connection. Expected result 1 2. Perform the first handshake, obtain and save the session. Expected result 2 3. Modify the session cipher suite and resume the session. Expected result 3 * @expect 1. Return success 2. The handshake is complete and obtain the session successfully 3. Resumption fails @ */ /* BEGIN_CASE */ void SDV_TLS_TLCP_CONSISTENCY_RESUME_FUNC_TC007(int version, int connType) { Process *localProcess = NULL; Process *remoteProcess = NULL; int32_t cachemode = 0; HLT_FD sockFd = {0}; int cnt = 1; int32_t serverConfigId = 0; HITLS_Session *session = NULL; const char *writeBuf = "Hello world"; uint8_t readBuf[READ_BUF_SIZE] = {0}; uint32_t readLen; uint16_t sess_Ciphersuite; 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_NewCtxConfigTLCP(NULL, "CLIENT", true); HLT_Ctx_Config *serverCtxConfig = HLT_NewCtxConfigTLCP(NULL, "SERVER", 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 cachemode = GetSessionCacheMode(clientCtxConfig); ASSERT_EQ(cachemode , HITLS_SESS_CACHE_SERVER); ASSERT_TRUE(HLT_TlsSetCtx(clientConfig, clientCtxConfig) == 0); ASSERT_TRUE(HLT_RpcTlsSetCtx(remoteProcess, serverConfigId, serverCtxConfig) == 0); do { DataChannelParam channelParam; channelParam.port = PORT; 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 (cnt == 1) { 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); } else { HITLS_SESS_GetCipherSuite(session, &sess_Ciphersuite); if(sess_Ciphersuite == HITLS_ECC_SM4_CBC_SM3) { ASSERT_TRUE(HITLS_SESS_SetCipherSuite(session, HITLS_ECDHE_SM4_CBC_SM3) == HITLS_SUCCESS); } else { ASSERT_TRUE(HITLS_SESS_SetCipherSuite(session, HITLS_ECC_SM4_CBC_SM3) == HITLS_SUCCESS); } ASSERT_TRUE(HITLS_SetSession(clientSsl, session) == HITLS_SUCCESS); ASSERT_TRUE(HLT_TlsConnect(clientSsl) == HITLS_MSG_HANDLE_ILLEGAL_CIPHER_SUITE); } cnt++; } while (cnt <= 2); EXIT: HITLS_SESS_Free(session); HLT_FreeAllProcess(); } /* END_CASE */ /* @ * @test SDV_TLS_TLCP_CONSISTENCY_RESUME_FUNC_TC008 * @title Modify the session master key on the client. Resumption fails * @precon nan * @brief 1. Establish the connection. Expected result 1 2. Perform the first handshake, obtain and save the session. Expected result 2 3. Modify the session master key and resume the session. Expected result 3 * @expect 1. Return success 2. The handshake is complete and obtain the session successfully 3. Resumption fails @ */ /* BEGIN_CASE */ void SDV_TLS_TLCP_CONSISTENCY_RESUME_FUNC_TC008(int version, int connType) { Process *localProcess = NULL; Process *remoteProcess = NULL; int32_t cachemode = 0; HLT_FD sockFd = {0}; int cnt = 1; int32_t serverConfigId = 0; HITLS_Session *session = NULL; const char *writeBuf = "Hello world"; uint8_t readBuf[READ_BUF_SIZE] = {0}; uint32_t readLen; 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_NewCtxConfigTLCP(NULL, "CLIENT", true); HLT_Ctx_Config *serverCtxConfig = HLT_NewCtxConfigTLCP(NULL, "SERVER", 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 cachemode = GetSessionCacheMode(clientCtxConfig); ASSERT_EQ(cachemode , HITLS_SESS_CACHE_SERVER); ASSERT_TRUE(HLT_TlsSetCtx(clientConfig, clientCtxConfig) == 0); ASSERT_TRUE(HLT_RpcTlsSetCtx(remoteProcess, serverConfigId, serverCtxConfig) == 0); do { if (session != NULL) { session->masterKey[0] -= 1; ASSERT_TRUE(HLT_TlsSetCtx(clientConfig, clientCtxConfig) == 0); } DataChannelParam channelParam; channelParam.port = PORT; 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 (cnt == 1) { 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); } else { ASSERT_TRUE(HITLS_SetSession(clientSsl, session) == HITLS_SUCCESS); ASSERT_EQ(HLT_TlsConnect(clientSsl), HITLS_REC_BAD_RECORD_MAC); } cnt++; } while (cnt <= 2); EXIT: HITLS_SESS_Free(session); HLT_FreeAllProcess(); } /* END_CASE */ /* BEGIN_CASE */ void SDV_TLS_TLCP_CONSISTENCY_TRANSPORT_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, PORT, true); ASSERT_TRUE(remoteProcess != NULL); HLT_Ctx_Config *serverCtxConfig = HLT_NewCtxConfigTLCP(NULL, "SERVER", false); ASSERT_TRUE(serverCtxConfig != NULL); serverRes = HLT_ProcessTlsAccept(localProcess, TLCP1_1, serverCtxConfig, NULL); ASSERT_TRUE(serverRes != NULL); HLT_Ctx_Config *clientCtxConfig = HLT_NewCtxConfigTLCP(NULL, "CLIENT", true); ASSERT_TRUE(clientCtxConfig != NULL); clientRes = HLT_ProcessTlsConnect(remoteProcess, TLCP1_1, clientCtxConfig, NULL); ASSERT_TRUE(clientRes != NULL); ASSERT_TRUE(HLT_GetTlsAcceptResult(serverRes) == 0); uint8_t writeBuf[READ_BUF_SIZE] = {0}; ASSERT_TRUE(HLT_ProcessTlsWrite(localProcess, serverRes, writeBuf, 16384) == 0); uint8_t readBuf[READ_BUF_SIZE] = {0}; uint32_t readLen; ASSERT_TRUE(HLT_ProcessTlsRead(remoteProcess, clientRes, readBuf, READ_BUF_SIZE, &readLen) == 0); ASSERT_TRUE(readLen == 16384); EXIT: HLT_FreeAllProcess(); } /* END_CASE */ /* @ * @test SDV_TLS_TLCP_CONSISTENCY_RESUME_FUNC_TC009 * @title set the session cache mode on the client server. try to Resumption * @precon nan * @brief 1. Configure the session cache mode establish the connection. Expected result 1 2. Perform the first handshake, obtain and save the session. Expected result 2 3. Try resume the session. Expected result 3 * @expect 1. Return success 2. The handshake is complete and obtain the session successfully 3. HITLS_SESS_CACHE_NO and HITLS_SESS_CACHE_CLIENT resumption fails, otherwise successful @ */ /* BEGIN_CASE */ void SDV_TLS_TLCP_CONSISTENCY_RESUME_FUNC_TC009(int mode) { Process *localProcess = NULL; Process *remoteProcess = NULL; HLT_FD sockFd = {0}; int cnt = 1; int32_t serverConfigId = 0; HITLS_Session *session = NULL; const char *writeBuf = "Hello world"; uint8_t readBuf[READ_BUF_SIZE] = {0}; uint32_t readLen; localProcess = HLT_InitLocalProcess(HITLS); ASSERT_TRUE(localProcess != NULL); remoteProcess = HLT_CreateRemoteProcess(HITLS); ASSERT_TRUE(remoteProcess != NULL); void *clientConfig = HLT_TlsNewCtx(TLCP1_1); ASSERT_TRUE(clientConfig != NULL); HLT_Ctx_Config *clientCtxConfig = HLT_NewCtxConfigTLCP(NULL, "CLIENT", true); HLT_Ctx_Config *serverCtxConfig = HLT_NewCtxConfigTLCP(NULL, "SERVER", false); #ifdef HITLS_TLS_FEATURE_PROVIDER serverConfigId = HLT_RpcProviderTlsNewCtx(remoteProcess, TLCP1_1, false, serverCtxConfig->providerPath, serverCtxConfig->providerNames, serverCtxConfig->providerLibFmts, serverCtxConfig->providerCnt, serverCtxConfig->attrName); #else serverConfigId = HLT_RpcTlsNewCtx(remoteProcess, TLCP1_1, false); #endif HLT_SetSessionCacheMode(clientCtxConfig, mode); HLT_SetSessionCacheMode(serverCtxConfig, mode); ASSERT_TRUE(HLT_TlsSetCtx(clientConfig, clientCtxConfig) == 0); ASSERT_TRUE(HLT_RpcTlsSetCtx(remoteProcess, serverConfigId, serverCtxConfig) == 0); do{ 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; 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; 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 = TCP; HLT_TlsSetSsl(clientSsl, clientSslConfig); if (session != NULL) { ASSERT_TRUE(HITLS_SetSession(clientSsl, session) == HITLS_SUCCESS); } ASSERT_EQ(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); if (cnt == 2) { if (mode == HITLS_SESS_CACHE_NO || mode == HITLS_SESS_CACHE_CLIENT){ uint8_t isReused = -1; HITLS_IsSessionReused(clientSsl, &isReused); ASSERT_TRUE(isReused == 0); } else { uint8_t isReused = -1; HITLS_IsSessionReused(clientSsl, &isReused); ASSERT_TRUE(isReused == 1); } } else { session = HITLS_GetDupSession(clientSsl); ASSERT_TRUE(session != NULL); }cnt++; }while(cnt < 3); EXIT: HITLS_SESS_Free(session); HLT_FreeAllProcess(); } /* END_CASE */ #define ALERT_BODY_LEN 2u /* Alert data length */ 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. */ return REC_Write(ctx, REC_TYPE_ALERT, data, ALERT_BODY_LEN); } /* BEGIN_CASE */ void SDV_TLS_TLCP1_1_LEVEL_UNKNOWN_ALERT_TC001(void) { FRAME_Init(); HITLS_Config *tlsConfig = HITLS_CFG_NewTLCPConfig(); ASSERT_TRUE(tlsConfig != NULL); tlsConfig->isSupportClientVerify = true; 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); ASSERT_TRUE(FRAME_CreateConnection(client, server, true, TRY_SEND_CLIENT_KEY_EXCHANGE) == HITLS_SUCCESS); ASSERT_TRUE(SendAlert(client->ssl, ALERT_LEVEL_UNKNOWN, ALERT_NO_RENEGOTIATION) == 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_ILLEGAL_PARAMETER); EXIT: HITLS_CFG_FreeConfig(tlsConfig); FRAME_FreeLink(client); FRAME_FreeLink(server); } /* END_CASE */ /* BEGIN_CASE */ void SDV_TLS_TLCP1_1_LEVEL_UNKNOWN_ALERT_TC002(void) { FRAME_Init(); HITLS_Config *tlsConfig = HITLS_CFG_NewTLCPConfig(); ASSERT_TRUE(tlsConfig != NULL); tlsConfig->isSupportClientVerify = true; 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); ASSERT_TRUE(FRAME_CreateConnection(client, server, false, TRY_SEND_SERVER_HELLO) == HITLS_SUCCESS); ASSERT_TRUE(SendAlert(server->ssl, ALERT_LEVEL_UNKNOWN, ALERT_DECODE_ERROR) == HITLS_SUCCESS); ASSERT_EQ(FRAME_CreateConnection(client, server, true, HS_STATE_BUTT), HITLS_REC_NORMAL_RECV_UNEXPECT_MSG); HITLS_Ctx *Ctx = FRAME_GetTlsCtx(client); ALERT_Info alert = { 0 }; ALERT_GetInfo(Ctx, &alert); ASSERT_EQ(alert.level, ALERT_LEVEL_FATAL); ASSERT_EQ(alert.description, ALERT_ILLEGAL_PARAMETER); EXIT: HITLS_CFG_FreeConfig(tlsConfig); FRAME_FreeLink(client); FRAME_FreeLink(server); } /* END_CASE */ /* @ * @test SDV_TLS_TLCP1_1_TRANSPORT_FUNC_TC01 * @title decrypt the app data with length 16384. * @precon nan * @brief 1. Establish the connection. Expected result 1 2. Perform the a handshake. Expected result 2 3. Send the app data with length 16384. Expected result 3 * @expect 1. Return success 2. The handshake is complete 3. The app data is decrypted successfully @ */ /* BEGIN_CASE */ void SDV_TLS_TLCP1_1_TRANSPORT_FUNC_TC01(void) { 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, g_uiPort, true); ASSERT_TRUE(remoteProcess != NULL); HLT_Ctx_Config *serverCtxConfig = HLT_NewCtxConfigTLCP(NULL, "SERVER", false); ASSERT_TRUE(serverCtxConfig != NULL); serverRes = HLT_ProcessTlsAccept(localProcess, TLCP1_1, serverCtxConfig, NULL); ASSERT_TRUE(serverRes != NULL); HLT_Ctx_Config *clientCtxConfig = HLT_NewCtxConfigTLCP(NULL, "CLIENT", true); ASSERT_TRUE(clientCtxConfig != NULL); clientRes = HLT_ProcessTlsConnect(remoteProcess, TLCP1_1, clientCtxConfig, NULL); ASSERT_TRUE(clientRes != NULL); ASSERT_TRUE(HLT_GetTlsAcceptResult(serverRes) == 0); uint8_t writeBuf[READ_BUF_SIZE] = {0}; ASSERT_TRUE(HLT_ProcessTlsWrite(localProcess, serverRes, writeBuf, 16384) == 0); uint8_t readBuf[READ_BUF_SIZE] = {0}; uint32_t readLen; ASSERT_TRUE(HLT_ProcessTlsRead(remoteProcess, clientRes, readBuf, READ_BUF_SIZE, &readLen) == 0); ASSERT_TRUE(readLen == 16384); EXIT: HLT_FreeAllProcess(); } /* END_CASE */ static void TEST_Client_SessionidLength_TooLong(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_TLCP_DTLCP11; FRAME_Msg frameMsg = {0}; frameMsg.recType.data = REC_TYPE_HANDSHAKE; frameMsg.length.data = *len; frameMsg.recVersion.data = HITLS_VERSION_TLCP_DTLCP11; 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 = 33; BSL_SAL_Free(clientMsg->sessionId.data); clientMsg->sessionId.data = BSL_SAL_Calloc(33, sizeof(uint8_t)); clientMsg->sessionId.size = 0; clientMsg->sessionId.state = ASSIGNED_FIELD; const uint8_t sessionId_temp[33] = { 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 SDV_TLS_TLCP1_1_RESUME_FAILED_TC001 * @title test wrong session id length client hello. * @precon nan * @brief 1. Establish the connection. Expected result 1 2. Client send a client hello with wrong session id length. Expected result 2 * @expect 1. Return success 2. Server return HITLS_PARSE_INVALID_MSG_LEN error @ */ /* BEGIN_CASE */ void SDV_TLS_TLCP1_1_RESUME_FAILED_TC001(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_NewCtxConfigTLCP(NULL, "SERVER", false); ASSERT_TRUE(serverConfig != NULL); clientConfig = HLT_NewCtxConfigTLCP(NULL, "CLIENT", true); ASSERT_TRUE(clientConfig != NULL); RecWrapper wrapper = { TRY_SEND_CLIENT_HELLO, REC_TYPE_HANDSHAKE, false, NULL, TEST_Client_SessionidLength_TooLong }; RegisterWrapper(wrapper); serverRes = HLT_ProcessTlsAccept(remoteProcess, TLCP1_1, serverConfig, NULL); ASSERT_TRUE(serverRes != NULL); clientRes = HLT_ProcessTlsConnect(localProcess, TLCP1_1, clientConfig, NULL); ASSERT_TRUE(clientRes == NULL); ASSERT_EQ(HLT_GetTlsAcceptResult(serverRes) , HITLS_PARSE_INVALID_MSG_LEN); EXIT: ClearWrapper(); HLT_FreeAllProcess(); } /* END_CASE */
2301_79861745/bench_create
testcode/sdv/testcase/tls/consistency/tlcp/test_suite_sdv_hlt_tlcp_consistency.c
C
unknown
55,410
/* * This file is part of the openHiTLS project. * * openHiTLS is licensed under the Mulan PSL v2. * You can use this software according to the terms and conditions of the Mulan PSL v2. * You may obtain a copy of Mulan PSL v2 at: * * http://license.coscl.org.cn/MulanPSL2 * * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, * EITHER EXPRESS 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 "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 "cert_callback.h" #include "change_cipher_spec.h" #include "common_func.h" #include "uio_base.h" #include "hs.h" #include "stub_crypt.h" /* END_HEADER */ /* @ * @test UT_TLS_TLS12_RFC5246_CONSISTENCY_RECV_ZEROLENGTH_MSG_TC001 * @title Verify that the server receives a 0-length Client Hello message and the expected alert is returned. * @precon nan * @brief 1. Create a config and client link, and construct a 0-length client hello message. * Expected result 1 is obtained. * 2. The server invokes the HITLS_Accept interface. (Expected result 2) * @expect 1. A success message is returned. * 2. A failure message is returned. @ */ /* BEGIN_CASE */ void UT_TLS_TLS12_RFC5246_CONSISTENCY_RECV_ZEROLENGTH_MSG_TC001(void) { // Create a config and client link, and construct a 0-length client hello message. 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(&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_TLS12; 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->extensionState = MISSING_FIELD; clientMsg->version.state = MISSING_FIELD; clientMsg->randomValue.state = MISSING_FIELD; clientMsg->sessionIdSize.state = MISSING_FIELD; clientMsg->sessionId.state = MISSING_FIELD; clientMsg->cookiedLen.state = MISSING_FIELD; clientMsg->cookie.state = MISSING_FIELD; clientMsg->cipherSuitesSize.state = MISSING_FIELD; clientMsg->cipherSuites.state = MISSING_FIELD; clientMsg->compressionMethodsLen.state = MISSING_FIELD; clientMsg->compressionMethods.state = 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(testInfo.server->io, sendBuf, sendLen) == HITLS_SUCCESS); FRAME_CleanMsg(&frameType, &frameMsg); memset_s(&frameMsg, sizeof(frameMsg), 0, sizeof(frameMsg)); // The server invokes the HITLS_Accept interface. ASSERT_TRUE(testInfo.server->ssl != NULL); ASSERT_EQ(HITLS_Accept(testInfo.server->ssl), HITLS_PARSE_INVALID_MSG_LEN); 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); 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_TLS12_RFC5246_CONSISTENCY_RECV_ZEROLENGTH_MSG_TC002 * @title Verify that the client receives a serverhello message with a length of 0 and the expected alert is returned. * @precon nan * @brief 1. Create a config and server link, and construct a 0-length server hello message. * 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_TLS12_RFC5246_CONSISTENCY_RECV_ZEROLENGTH_MSG_TC002(void) { // Create a config and server link, and construct a 0-length server hello message. 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(&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_TLS12; 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; serverMsg->version.state = MISSING_FIELD; serverMsg->randomValue.state = MISSING_FIELD; serverMsg->sessionIdSize.state = MISSING_FIELD; serverMsg->sessionId.state = MISSING_FIELD; serverMsg->cipherSuite.state = MISSING_FIELD; serverMsg->compressionMethod.state = MISSING_FIELD; serverMsg->extensionLen.state = MISSING_FIELD; serverMsg->pointFormats.exState = MISSING_FIELD; serverMsg->extendedMasterSecret.exState = MISSING_FIELD; serverMsg->secRenego.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(testInfo.client->io, sendBuf, sendLen) == HITLS_SUCCESS); FRAME_CleanMsg(&frameType, &frameMsg); memset_s(&frameMsg, sizeof(frameMsg), 0, sizeof(frameMsg)); /* The client invokes the HITLS_Connect interface. */ ASSERT_TRUE(testInfo.client->ssl != NULL); ASSERT_EQ(HITLS_Connect(testInfo.client->ssl), HITLS_PARSE_INVALID_MSG_LEN); 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); 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_TLS12_RFC5246_CONSISTENCY_RECV_ZEROLENGTH_MSG_TC003 * @title The client receives a Certificate message with a length of zero. * @precon nan * @brief 1. Use the default configuration items to configure the client and server. Expected result 1 is obtained * 2. Construct a zero-length Certificate 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 with the level of ALERT_Level_FATAL and description of ALERT_DECODE_ERROR @ */ /* BEGIN_CASE */ void UT_TLS_TLS12_RFC5246_CONSISTENCY_RECV_ZEROLENGTH_MSG_TC003(void) { // Use the default configuration items to configure the client and server. HandshakeTestInfo testInfo = { 0 }; FRAME_Msg frameMsg = { 0 }; FRAME_Type frameType = { 0 }; testInfo.state = TRY_RECV_CERTIFICATE; testInfo.isSupportExtendMasterSecret = true; testInfo.isClient = true; ASSERT_TRUE(DefaultCfgStatusParkWithSuite(&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_TLS12; frameType.recordType = REC_TYPE_HANDSHAKE; frameType.handshakeType = CERTIFICATE; frameType.keyExType = HITLS_KEY_EXCH_ECDHE; ASSERT_TRUE(FRAME_ParseMsg(&frameType, recvBuf, recvLen, &frameMsg, &parseLen) == HITLS_SUCCESS); /* Construct a zero-length Certificate message and send it to the client. */ FRAME_CertificateMsg *certifiMsg = &frameMsg.body.hsMsg.body.certificate; certifiMsg->certsLen.state = MISSING_FIELD; certifiMsg->certItem->state = 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(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); ASSERT_EQ(HITLS_Connect(testInfo.client->ssl), HITLS_PARSE_INVALID_MSG_LEN); 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); 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_TLS12_RFC5246_CONSISTENCY_RECV_ZEROLENGTH_MSG_TC004 * @title The client receives a Server Key Exchange message whose length is 0. * @precon nan * @brief 1. Use the default configuration items to configure the client and server. Expected result 1 is obtained * 2. Construct a zero-length Server Key Exchange 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. The level is ALERT_LEVEL_FATAL and the description is ALERT_DECODE_ERROR @ */ /* BEGIN_CASE */ void UT_TLS_TLS12_RFC5246_CONSISTENCY_RECV_ZEROLENGTH_MSG_TC004(void) { // Use the default configuration items to configure the client and server. HandshakeTestInfo testInfo = { 0 }; FRAME_Msg frameMsg = { 0 }; FRAME_Type frameType = { 0 }; testInfo.state = TRY_RECV_SERVER_KEY_EXCHANGE; testInfo.isSupportExtendMasterSecret = true; testInfo.isClient = true; ASSERT_TRUE(DefaultCfgStatusParkWithSuite(&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_TLS12; frameType.recordType = REC_TYPE_HANDSHAKE; frameType.handshakeType = SERVER_KEY_EXCHANGE; frameType.keyExType = HITLS_KEY_EXCH_ECDHE; ASSERT_TRUE(FRAME_ParseMsg(&frameType, recvBuf, recvLen, &frameMsg, &parseLen) == HITLS_SUCCESS); /* Construct a zero-length Server Key Exchange message and send it to the client. */ FRAME_ServerKeyExchangeMsg *serverKeyExMsg = &frameMsg.body.hsMsg.body.serverKeyExchange; serverKeyExMsg->keyEx.ecdh.curveType.state = MISSING_FIELD; serverKeyExMsg->keyEx.ecdh.namedcurve.state = MISSING_FIELD; serverKeyExMsg->keyEx.ecdh.pubKeySize.state = MISSING_FIELD; serverKeyExMsg->keyEx.ecdh.pubKey.state = MISSING_FIELD; serverKeyExMsg->keyEx.ecdh.signAlgorithm.state = MISSING_FIELD; serverKeyExMsg->keyEx.ecdh.signSize.state = MISSING_FIELD; serverKeyExMsg->keyEx.ecdh.signData.state = 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(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); ASSERT_EQ(HITLS_Connect(testInfo.client->ssl), HITLS_PARSE_INVALID_MSG_LEN); 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); 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_TLS12_RFC5246_CONSISTENCY_RECV_ZEROLENGTH_MSG_TC005 * @title The server receives a Client Key Exchange 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. Construct a zero-length Client Key Exchange message and send it to the server. * Expected result 2 is obtained. * @expect 1. The initialization is successful. * 2. The server sends an ALERT message. The level is ALERT_LEVEL_FATAL and the description is ALERT_DECODE_ERROR @ */ /* BEGIN_CASE */ void UT_TLS_TLS12_RFC5246_CONSISTENCY_RECV_ZEROLENGTH_MSG_TC005(void) { // Use the default configuration items to configure the client and server. HandshakeTestInfo testInfo = { 0 }; FRAME_Msg frameMsg = { 0 }; FRAME_Type frameType = { 0 }; testInfo.state = TRY_RECV_CLIENT_KEY_EXCHANGE; testInfo.isSupportExtendMasterSecret = true; testInfo.isClient = false; ASSERT_TRUE(DefaultCfgStatusParkWithSuite(&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_TLS12; frameType.recordType = REC_TYPE_HANDSHAKE; frameType.handshakeType = CLIENT_KEY_EXCHANGE; frameType.keyExType = HITLS_KEY_EXCH_ECDHE; ASSERT_TRUE(FRAME_ParseMsg(&frameType, recvBuf, recvLen, &frameMsg, &parseLen) == HITLS_SUCCESS); // Construct a zero-length Client Key Exchange message and send it to the server. FRAME_ClientKeyExchangeMsg *clientKeyExMsg = &frameMsg.body.hsMsg.body.clientKeyExchange; clientKeyExMsg->pubKey.state = MISSING_FIELD; clientKeyExMsg->pubKeySize.state = 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(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); ASSERT_EQ(HITLS_Accept(testInfo.server->ssl), HITLS_PARSE_INVALID_MSG_LEN); 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); 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_TLS12_RFC5246_CONSISTENCY_RECV_ZEROLENGTH_MSG_TC006 * @title The server receives a Change Cipher Spec 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. Construct a Change Cipher Spec message with zero length and send it to the server. * Expected result 2 is obtained. * @expect 1. The initialization is successful. * 2. The server sends an ALERT message. @ */ /* BEGIN_CASE */ void UT_TLS_TLS12_RFC5246_CONSISTENCY_RECV_ZEROLENGTH_MSG_TC006(void) { // Use the default configuration items to configure the client and server. HandshakeTestInfo testInfo = { 0 }; testInfo.state = TRY_RECV_CERTIFICATE_VERIFY; testInfo.isSupportExtendMasterSecret = true; testInfo.isSupportClientVerify = true; testInfo.isSupportNoClientCert = false; testInfo.isClient = false; ASSERT_TRUE(DefaultCfgStatusParkWithSuite(&testInfo) == HITLS_SUCCESS); ASSERT_TRUE(testInfo.server->ssl != NULL); ASSERT_EQ(HITLS_Accept(testInfo.server->ssl), HITLS_REC_NORMAL_RECV_BUF_EMPTY); FRAME_Msg frameMsg1 = { 0 }; FRAME_Type frameType1 = { 0 }; frameType1.versionType = HITLS_VERSION_TLS12; frameType1.recordType = REC_TYPE_CHANGE_CIPHER_SPEC; frameType1.keyExType = HITLS_KEY_EXCH_ECDHE; ASSERT_TRUE(FRAME_GetDefaultMsg(&frameType1, &frameMsg1) == HITLS_SUCCESS); // Construct a Change Cipher Spec message with zero length and send it to the server. FRAME_CcsMsg *CcsMidMsg = &frameMsg1.body.ccsMsg; CcsMidMsg->ccsType.state = MISSING_FIELD; CcsMidMsg->extra.state = MISSING_FIELD; CcsMidMsg->extra.size = MISSING_FIELD; uint32_t sendLen = MAX_RECORD_LENTH; uint8_t sendBuf[MAX_RECORD_LENTH] = {0}; ASSERT_TRUE(FRAME_PackMsg(&frameType1, &frameMsg1, sendBuf, sendLen, &sendLen) == HITLS_SUCCESS); FrameUioUserData *ioUserData1 = BSL_UIO_GetUserData(testInfo.server->io); ioUserData1->recMsg.len = 0; ASSERT_TRUE(FRAME_TransportRecMsg(testInfo.server->io, sendBuf, sendLen) == HITLS_SUCCESS); FRAME_CleanMsg(&frameType1, &frameMsg1); memset_s(&frameMsg1, sizeof(frameMsg1), 0, sizeof(frameMsg1)); ASSERT_TRUE(testInfo.server->ssl != NULL); ASSERT_EQ(HITLS_Accept(testInfo.server->ssl), HITLS_REC_NORMAL_RECV_BUF_EMPTY); EXIT: FRAME_CleanMsg(&frameType1, &frameMsg1); HITLS_CFG_FreeConfig(testInfo.config); FRAME_FreeLink(testInfo.client); FRAME_FreeLink(testInfo.server); FRAME_DeRegCryptMethod(); } /* END_CASE */ /* @ * @test UT_TLS_TLS12_RFC5246_CONSISTENCY_RECV_ZEROLENGTH_MSG_TC007 * @title The client receives a Change Cipher Spec message with a length of 0 and the data is encrypted. * @precon nan * @brief 1. Use the default configuration items to configure the client and server. Expected result 1 is obtained * 2. Construct a Change Cipher Spec 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 an ALERT message. @ */ /* BEGIN_CASE */ void UT_TLS_TLS12_RFC5246_CONSISTENCY_RECV_ZEROLENGTH_MSG_TC007(void) { // Use the default configuration items to configure the client and server. HandshakeTestInfo testInfo = { 0 }; testInfo.state = TRY_RECV_NEW_SESSION_TICKET; testInfo.isSupportExtendMasterSecret = true; testInfo.isSupportClientVerify = true; testInfo.isSupportNoClientCert = false; testInfo.isClient = true; ASSERT_TRUE(DefaultCfgStatusParkWithSuite(&testInfo) == HITLS_SUCCESS); ASSERT_TRUE(testInfo.client->ssl != NULL); ASSERT_EQ(HITLS_Connect(testInfo.client->ssl), HITLS_REC_NORMAL_RECV_BUF_EMPTY); FRAME_Msg frameMsg1 = { 0 }; FRAME_Type frameType1 = { 0 }; frameType1.versionType = HITLS_VERSION_TLS12; frameType1.recordType = REC_TYPE_CHANGE_CIPHER_SPEC; frameType1.keyExType = HITLS_KEY_EXCH_ECDHE; ASSERT_TRUE(FRAME_GetDefaultMsg(&frameType1, &frameMsg1) == HITLS_SUCCESS); // Construct a Change Cipher Spec message with zero length and send it to the client. FRAME_CcsMsg *CcsMidMsg = &frameMsg1.body.ccsMsg; CcsMidMsg->ccsType.state = MISSING_FIELD; CcsMidMsg->extra.state = MISSING_FIELD; CcsMidMsg->extra.size = MISSING_FIELD; uint32_t sendLen = MAX_RECORD_LENTH; uint8_t sendBuf[MAX_RECORD_LENTH] = {0}; ASSERT_TRUE(FRAME_PackMsg(&frameType1, &frameMsg1, sendBuf, sendLen, &sendLen) == HITLS_SUCCESS); FrameUioUserData *ioUserData1 = BSL_UIO_GetUserData(testInfo.client->io); ioUserData1->recMsg.len = 0; ASSERT_TRUE(FRAME_TransportRecMsg(testInfo.client->io, sendBuf, sendLen) == HITLS_SUCCESS); FRAME_CleanMsg(&frameType1, &frameMsg1); memset_s(&frameMsg1, sizeof(frameMsg1), 0, sizeof(frameMsg1)); ASSERT_TRUE(testInfo.client->ssl != NULL); ASSERT_EQ(HITLS_Connect(testInfo.client->ssl), HITLS_REC_NORMAL_RECV_BUF_EMPTY); FRAME_AlertMsg *alertMsg = &frameMsg1.body.alertMsg; ASSERT_EQ(alertMsg->alertLevel.data , 0); ASSERT_EQ(alertMsg->alertDescription.data , ALERT_CLOSE_NOTIFY); EXIT: FRAME_CleanMsg(&frameType1, &frameMsg1); HITLS_CFG_FreeConfig(testInfo.config); FRAME_FreeLink(testInfo.client); FRAME_FreeLink(testInfo.server); FRAME_DeRegCryptMethod(); } /* END_CASE */ /* @ * @test UT_TLS_TLS12_RFC5246_CONSISTENCY_RECV_ZEROLENGTH_MSG_TC008 * @title The client receives a SERVER_HELLO_DONE message whose length is 0 and expects to return an alert message * @precon nan * @brief 1. Use the default configuration items to configure the client and server. Expected result 1 is obtained * 2. Construct a SERVER_HELLO_DONE message with a 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 @ */ /* BEGIN_CASE */ void UT_TLS_TLS12_RFC5246_CONSISTENCY_RECV_ZEROLENGTH_MSG_TC008(void) { // Use the default configuration items to configure the client and server. HandshakeTestInfo testInfo = { 0 }; FRAME_Msg frameMsg = { 0 }; FRAME_Type frameType = { 0 }; testInfo.state = TRY_RECV_SERVER_HELLO_DONE; testInfo.isSupportExtendMasterSecret = true; testInfo.isSupportClientVerify = true; testInfo.isSupportNoClientCert = false; testInfo.isClient = true; ASSERT_TRUE(DefaultCfgStatusParkWithSuite(&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_TLS12; frameType.recordType = REC_TYPE_HANDSHAKE; frameType.handshakeType = SERVER_HELLO_DONE; frameType.keyExType = HITLS_KEY_EXCH_ECDHE; ASSERT_TRUE(FRAME_ParseMsg(&frameType, recvBuf, recvLen, &frameMsg, &parseLen) == HITLS_SUCCESS); // Construct a SERVER_HELLO_DONE message with a zero length, and send the message to the client. FRAME_ServerHelloDoneMsg *serverHelloDone = &frameMsg.body.hsMsg.body.serverHelloDone; serverHelloDone->extra.state = 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(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); ASSERT_EQ(HITLS_Accept(testInfo.server->ssl), HITLS_MSG_HANDLE_UNEXPECTED_MESSAGE); 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); 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_TLS12_RFC5246_CONSISTENCY_HANDSHAKE_UNEXPECTMSG_TC001 * @title An unexpected message is received when the client is in the TRY_RECV_CERTIFICATIONATE * state during the handshake. * @precon nan * @brief 1. Use the default configuration items to configure the client and server. Expected result 1 is obtained. * 2. Construct a Server Hello message and send it to the client. Expected result 2 is obtained. * @expect 1. The initialization is successful. * 2. After receiving the Server Hello message, the client sends an ALERT message. * The level is ALERT_LEVEL_FATAL and the description is ALERT_UNEXPECTED_MESSAGE. @ */ /* BEGIN_CASE */ void UT_TLS_TLS12_RFC5246_CONSISTENCY_HANDSHAKE_UNEXPECTMSG_TC001(void) { // Use the default configuration items to configure the client and server. HandshakeTestInfo testInfo = { 0 }; testInfo.state = TRY_RECV_SERVER_HELLO; testInfo.isClient = true; testInfo.isSupportExtendMasterSecret = true; testInfo.isSupportClientVerify = true; testInfo.isSupportNoClientCert = false; ASSERT_TRUE(DefaultCfgStatusPark(&testInfo) == HITLS_SUCCESS); // Construct a Server Hello message and send it to the client. FRAME_Msg parsedSHdone = { 0 }; FRAME_Type frameType = { 0 }; SetFrameType(&frameType, HITLS_VERSION_TLS12, REC_TYPE_HANDSHAKE, SERVER_HELLO_DONE, HITLS_KEY_EXCH_ECDHE); ASSERT_TRUE(FRAME_GetDefaultMsg(&frameType, &parsedSHdone) == HITLS_SUCCESS); uint32_t sendLen = MAX_RECORD_LENTH; uint8_t sendBuf[MAX_RECORD_LENTH] = {0}; ASSERT_TRUE(FRAME_PackMsg(&frameType, &parsedSHdone, 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, &parsedSHdone); ASSERT_TRUE(testInfo.client->ssl != NULL); ASSERT_EQ(HITLS_Connect(testInfo.client->ssl), HITLS_MSG_HANDLE_UNEXPECTED_MESSAGE); 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, &parsedSHdone, &parseLen) == HITLS_SUCCESS); ASSERT_TRUE(parsedSHdone.recType.data == REC_TYPE_ALERT); FRAME_AlertMsg *alertMsg = &parsedSHdone.body.alertMsg; ASSERT_TRUE(alertMsg->alertLevel.data == ALERT_LEVEL_FATAL); ASSERT_TRUE(alertMsg->alertDescription.data == ALERT_UNEXPECTED_MESSAGE); EXIT: FRAME_CleanMsg(&frameType, &parsedSHdone); HITLS_CFG_FreeConfig(testInfo.config); FRAME_FreeLink(testInfo.client); FRAME_FreeLink(testInfo.server); FRAME_DeRegCryptMethod(); } /* END_CASE */ /* @ * @test UT_TLS_TLS12_RFC5246_CONSISTENCY_HANDSHAKE_UNEXPECTMSG_TC002 * @title An unexpected message is received when the client is in the TRY_RECV_CERTIFICATIONATE state * during the handshake. * @precon nan * @brief 1. Use the default configuration items to configure the client and server. Expected result 1 is obtained. * 2. Construct a Server Hello message and send it to the client. Expected result 2 is obtained. * @expect 1. The initialization is successful. * 2. After receiving the Server Hello message, the client sends an ALERT message. * The level is ALERT_LEVEL_FATAL and the description is ALERT_UNEXPECTED_MESSAGE. @ */ /* BEGIN_CASE */ void UT_TLS_TLS12_RFC5246_CONSISTENCY_HANDSHAKE_UNEXPECTMSG_TC002(void) { // Use the default configuration items to configure the client and server. HandshakeTestInfo testInfo = { 0 }; testInfo.state = TRY_RECV_CERTIFICATE; testInfo.isClient = true; testInfo.isSupportExtendMasterSecret = true; testInfo.isSupportClientVerify = true; testInfo.isSupportNoClientCert = false; ASSERT_TRUE(DefaultCfgStatusPark(&testInfo) == HITLS_SUCCESS); // Construct a Server Hello message and send it to the client. FRAME_Msg frameMsg = { 0 }; FRAME_Type frameType = { 0 }; frameType.versionType = HITLS_VERSION_TLS12; frameType.recordType = REC_TYPE_HANDSHAKE; frameType.handshakeType = SERVER_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); 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); ASSERT_EQ(HITLS_Connect(testInfo.client->ssl), HITLS_MSG_HANDLE_UNEXPECTED_MESSAGE); 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_TRUE(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); FRAME_DeRegCryptMethod(); } /* END_CASE */ /* @ * @test UT_TLS_TLS12_RFC5246_CONSISTENCY_HANDSHAKE_UNEXPECTMSG_TC003 * @title An unexpected message is received when the client is in the TRY_RECV_SERVER_KEY_EXCHANGE state * during the handshake. * @precon nan * @brief 1. Use the default configuration items to configure the client and server. Expected result 1 is obtained. * 2. Construct a Server Hello message and send it to the client. Expected result 2 is obtained. * @expect 1. The initialization is successful. * 2. After receiving the Server Hello message, the client sends an ALERT message. * The level is ALERT_LEVEL_FATAL and the description is ALERT_UNEXPECTED_MESSAGE. @ */ /* BEGIN_CASE */ void UT_TLS_TLS12_RFC5246_CONSISTENCY_HANDSHAKE_UNEXPECTMSG_TC003(void) { // Use the default configuration items to configure the client and server. HandshakeTestInfo testInfo = { 0 }; testInfo.state = TRY_RECV_SERVER_KEY_EXCHANGE; testInfo.isClient = true; testInfo.isSupportExtendMasterSecret = true; testInfo.isSupportClientVerify = true; testInfo.isSupportNoClientCert = false; ASSERT_TRUE(DefaultCfgStatusPark(&testInfo) == HITLS_SUCCESS); // Construct a Server Hello message and send it to the client. FRAME_Msg frameMsg = { 0 }; FRAME_Type frameType = { 0 }; frameType.versionType = HITLS_VERSION_TLS12; frameType.recordType = REC_TYPE_HANDSHAKE; frameType.handshakeType = SERVER_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); 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); ASSERT_EQ(HITLS_Connect(testInfo.client->ssl), HITLS_MSG_HANDLE_UNEXPECTED_MESSAGE); 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_TRUE(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); FRAME_DeRegCryptMethod(); } /* END_CASE */ /* @ * @test UT_TLS_TLS12_RFC5246_CONSISTENCY_HANDSHAKE_UNEXPECTMSG_TC004 * @title An unexpected message is received when the client is in the TRY_RECV_SERVER_HELLO_DONE state * during the handshake. * @precon nan * @brief 1. Use the default configuration items to configure the client and server. Expected result 1 is obtained. * 2. Construct a Server Hello message and send it to the client. Expected result 2 is obtained. * @expect 1. The initialization is successful. * 2. After receiving the Server Hello message, the client sends an ALERT message. The level is * ALERT_LEVEL_FATAL and the description is ALERT_UNEXPECTED_MESSAGE. @ */ /* BEGIN_CASE */ void UT_TLS_TLS12_RFC5246_CONSISTENCY_HANDSHAKE_UNEXPECTMSG_TC004(void) { // Use the default configuration items to configure the client and server. HandshakeTestInfo testInfo = { 0 }; testInfo.state = TRY_RECV_SERVER_HELLO_DONE; testInfo.isClient = true; testInfo.isSupportExtendMasterSecret = true; testInfo.isSupportClientVerify = true; testInfo.isSupportNoClientCert = false; ASSERT_TRUE(DefaultCfgStatusPark(&testInfo) == HITLS_SUCCESS); // Construct a Server Hello message and send it to the client. FRAME_Msg frameMsg = { 0 }; FRAME_Type frameType = { 0 }; frameType.versionType = HITLS_VERSION_TLS12; frameType.recordType = REC_TYPE_HANDSHAKE; frameType.handshakeType = SERVER_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); 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); ASSERT_EQ(HITLS_Connect(testInfo.client->ssl), HITLS_MSG_HANDLE_UNEXPECTED_MESSAGE); 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_TRUE(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); FRAME_DeRegCryptMethod(); } /* END_CASE */ /* @ * @test UT_TLS_TLS12_RFC5246_CONSISTENCY_HANDSHAKE_UNEXPECTMSG_TC005 * @title An unexpected message is received when the client is in the TRY_RECV_FINISH state during the handshake. * @precon nan * @brief 1. Use the default configuration items to configure the client and server. Expected result 1 is obtained. * 2. Construct a Server Hello message and send it to the client. Expected result 2 is obtained. * @expect 1. The initialization is successful. * 2. After receiving the Server Hello message, the client sends an ALERT message. * The level is ALERT_Level_FATAL and the description is ALERT_UNEXPECTED_MESSAGE. @ */ /* BEGIN_CASE */ void UT_TLS_TLS12_RFC5246_CONSISTENCY_HANDSHAKE_UNEXPECTMSG_TC005(void) { // Use the default configuration items to configure the client and server. // Construct a Server Hello message and send it to the client. HandshakeTestInfo testInfo = { 0 }; FRAME_Msg parsedAlert = { 0 }; testInfo.state = TRY_RECV_SERVER_HELLO; testInfo.isClient = true; ASSERT_TRUE(DefaultCfgStatusPark(&testInfo) == HITLS_SUCCESS); testInfo.client->ssl->hsCtx->state = TRY_RECV_FINISH; ASSERT_EQ(HITLS_Connect(testInfo.client->ssl), HITLS_MSG_HANDLE_UNEXPECTED_MESSAGE); FrameUioUserData *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; 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_UNEXPECTED_MESSAGE); EXIT: FRAME_CleanNonHsRecord(REC_TYPE_ALERT, &parsedAlert); HITLS_CFG_FreeConfig(testInfo.config); FRAME_FreeLink(testInfo.client); FRAME_FreeLink(testInfo.server); FRAME_DeRegCryptMethod(); } /* END_CASE */ /* @ * @test UT_TLS_TLS12_RFC5246_CONSISTENCY_HANDSHAKE_UNEXPECTMSG_TC006 * @title An unexpected message is received when the client is in the TRY_RECV_CERTIFICATE_REQUEST * state during the handshake. * @precon nan * @brief 1. Use the default configuration items to configure the client and server. Expected result 1 is obtained. * 2. Construct a Server Hello message and send it to the client. Expected result 2 is obtained. * @expect 1. The initialization is successful. * 2. After receiving the Server Hello message, the client sends an ALERT. * The level is ALERT_LEVEL_FATAL and the description is ALERT_UNEXPECTED_MESSAGE. @ */ /* BEGIN_CASE */ void UT_TLS_TLS12_RFC5246_CONSISTENCY_HANDSHAKE_UNEXPECTMSG_TC006(void) { // Use the default configuration items to configure the client and server. HandshakeTestInfo testInfo = { 0 }; testInfo.state = TRY_RECV_CERTIFICATE_REQUEST; testInfo.isClient = true; testInfo.isSupportExtendMasterSecret = true; testInfo.isSupportClientVerify = true; testInfo.isSupportNoClientCert = false; ASSERT_TRUE(DefaultCfgStatusPark(&testInfo) == HITLS_SUCCESS); // Construct a Server Hello message and send it to the client. FRAME_Msg frameMsg = { 0 }; FRAME_Type frameType = { 0 }; frameType.versionType = HITLS_VERSION_TLS12; frameType.recordType = REC_TYPE_HANDSHAKE; frameType.handshakeType = SERVER_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); 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); ASSERT_EQ(HITLS_Connect(testInfo.client->ssl), HITLS_MSG_HANDLE_UNEXPECTED_MESSAGE); 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_TRUE(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); FRAME_DeRegCryptMethod(); } /* END_CASE */ /* @ * @test UT_TLS_TLS12_RFC5246_CONSISTENCY_HANDSHAKE_UNEXPECTMSG_TC007 * @title An unexpected message is received when the client is in the TRY_RECV_NEW_SESSION_TICKET state * during the handshake. * @precon nan * @brief 1. Use the default configuration items to configure the client and server. Expected result 1 is obtained. * 2. Construct a Server Hello message and send it to the client. Expected result 2 is obtained. * @expect 1. The initialization is successful. * 2. After receiving the Server Hello message, the client sends an ALERT message. * The level is ALERT_Level_FATAL and the description is ALERT_UNEXPECTED_MESSAGE. @ */ /* BEGIN_CASE */ void UT_TLS_TLS12_RFC5246_CONSISTENCY_HANDSHAKE_UNEXPECTMSG_TC007(void) { // Use the default configuration items to configure the client and server. HandshakeTestInfo testInfo = { 0 }; FRAME_Msg frameMsg = { 0 }; FRAME_Type frameType = { 0 }; testInfo.state = TRY_RECV_SERVER_HELLO; testInfo.isSupportExtendMasterSecret = true; testInfo.isClient = true; testInfo.isSupportClientVerify = true; testInfo.isSupportNoClientCert = false; ASSERT_TRUE(DefaultCfgStatusPark(&testInfo) == HITLS_SUCCESS); // Construct a Server Hello message and send it to the client. FrameUioUserData *ioUserData = BSL_UIO_GetUserData(testInfo.client->io); uint8_t *recvBuf = ioUserData->recMsg.msg; uint32_t recvLen = ioUserData->recMsg.len; ASSERT_TRUE(recvLen != 0); testInfo.client->ssl->hsCtx->state = TRY_RECV_NEW_SESSION_TICKET; uint32_t parseLen = 0; frameType.versionType = HITLS_VERSION_TLS12; 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); 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); ASSERT_EQ(HITLS_Connect(testInfo.client->ssl), HITLS_MSG_HANDLE_UNEXPECTED_MESSAGE); 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_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_TLS12_RFC5246_CONSISTENCY_HANDSHAKE_UNEXPECTMSG_TC008 * @title An unexpected message is received when the server is in the TRY_RECV_CLIENT_HELLO state during the handshake. * @precon nan * @brief 1. Use the default configuration items to configure the client and server. Expected result 1 is obtained. * 2. Construct a CLIENT_KEY_EXCHANGE message and send it to the server. Expected result 2 is obtained. * @expect 1. The initialization is successful. * 2. After receiving the CLIENT_KEY_EXCHANGE message, the server sends an ALERT. * The level is ALERT_Level_FATAL and the description is ALERT_UNEXPECTED_MESSAGE. @ */ /* BEGIN_CASE */ void UT_TLS_TLS12_RFC5246_CONSISTENCY_HANDSHAKE_UNEXPECTMSG_TC008(void) { /* Use the default configuration items to configure the client and server. */ HandshakeTestInfo testInfo = { 0 }; FRAME_Msg frameMsg = { 0 }; FRAME_Type frameType = { 0 }; testInfo.state = TRY_RECV_CLIENT_KEY_EXCHANGE; testInfo.isSupportExtendMasterSecret = true; testInfo.isClient = false; testInfo.isSupportClientVerify = true; testInfo.isSupportNoClientCert = false; ASSERT_TRUE(DefaultCfgStatusPark(&testInfo) == HITLS_SUCCESS); /* Construct a CLIENT_KEY_EXCHANGE message and send it to the server. */ FrameUioUserData *ioUserData = BSL_UIO_GetUserData(testInfo.server->io); uint8_t *recvBuf = ioUserData->recMsg.msg; uint32_t recvLen = ioUserData->recMsg.len; ASSERT_TRUE(recvLen != 0); testInfo.server->ssl->hsCtx->state = TRY_RECV_CLIENT_HELLO; uint32_t parseLen = 0; frameType.versionType = HITLS_VERSION_TLS12; frameType.recordType = REC_TYPE_HANDSHAKE; frameType.handshakeType = CLIENT_KEY_EXCHANGE; frameType.keyExType = 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); 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); ASSERT_EQ(HITLS_Accept(testInfo.server->ssl), HITLS_MSG_HANDLE_UNEXPECTED_MESSAGE); 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_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_TLS12_RFC5246_CONSISTENCY_HANDSHAKE_UNEXPECTMSG_TC009 * @title An unexpected message is received when the server is in the TRY_RECV_CERTIFICATIONATE * state during the handshake. * @precon nan * @brief 1. Use the default configuration items to configure the client and server. Expected result 1 is obtained. * 2. Construct a CLIENT_KEY_EXCHANGE message and send it to the server. Expected result 2 is obtained. * @expect 1. The initialization is successful. * 2. After receiving the CLIENT_KEY_EXCHANGE message, the server sends an ALERT message. The level is * ALERT_Level_FATAL and the description is ALERT_UNEXPECTED_MESSAGE. @ */ /* BEGIN_CASE */ void UT_TLS_TLS12_RFC5246_CONSISTENCY_HANDSHAKE_UNEXPECTMSG_TC009(void) { /* Use the default configuration items to configure the client and server. */ HandshakeTestInfo testInfo = { 0 }; FRAME_Msg frameMsg = { 0 }; FRAME_Type frameType = { 0 }; testInfo.state = TRY_RECV_CLIENT_KEY_EXCHANGE; testInfo.isSupportExtendMasterSecret = true; testInfo.isClient = false; testInfo.isSupportClientVerify = true; testInfo.isSupportNoClientCert = false; ASSERT_TRUE(DefaultCfgStatusPark(&testInfo) == HITLS_SUCCESS); /* Construct a CLIENT_KEY_EXCHANGE message and send it to the server. */ FrameUioUserData *ioUserData = BSL_UIO_GetUserData(testInfo.server->io); uint8_t *recvBuf = ioUserData->recMsg.msg; uint32_t recvLen = ioUserData->recMsg.len; ASSERT_TRUE(recvLen != 0); testInfo.server->ssl->hsCtx->state = TRY_RECV_CERTIFICATE; uint32_t parseLen = 0; frameType.versionType = HITLS_VERSION_TLS12; frameType.recordType = REC_TYPE_HANDSHAKE; frameType.handshakeType = CLIENT_KEY_EXCHANGE; frameType.keyExType = 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); 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); ASSERT_EQ(HITLS_Accept(testInfo.server->ssl), HITLS_MSG_HANDLE_UNEXPECTED_MESSAGE); 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_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_TLS12_RFC5246_CONSISTENCY_HANDSHAKE_UNEXPECTMSG_TC010 * @title An unexpected message is received when the server is in TRY_RECV_CLIENT_KEY_EXCHANGE state during the * handshake. * @precon nan * @brief 1. Use the default configuration items to configure the client and server. Expected result 1 is obtained. * 2. Construct a SERVER_HELLO message and send it to the server. Expected result 2 is obtained. * @expect 1. The initialization is successful. * 2. After receiving the SERVER_HELLO message, the server sends an ALERT. The level is ALERT_Level_FATAL and the * description is ALERT_UNEXPECTED_MESSAGE. @ */ /* BEGIN_CASE */ void UT_TLS_TLS12_RFC5246_CONSISTENCY_HANDSHAKE_UNEXPECTMSG_TC010(void) { /* Use the default configuration items to configure the client and server. */ HandshakeTestInfo testInfo = { 0 }; FRAME_Msg frameMsg = { 0 }; FRAME_Type frameType = { 0 }; testInfo.state = TRY_RECV_CERTIFICATE; testInfo.isSupportExtendMasterSecret = true; testInfo.isClient = false; testInfo.isSupportClientVerify = true; testInfo.isSupportNoClientCert = false; ASSERT_TRUE(DefaultCfgStatusPark(&testInfo) == HITLS_SUCCESS); /* Construct a SERVER_HELLO message and send it to the server. */ FrameUioUserData *ioUserData = BSL_UIO_GetUserData(testInfo.server->io); uint8_t *recvBuf = ioUserData->recMsg.msg; uint32_t recvLen = ioUserData->recMsg.len; ASSERT_TRUE(recvLen != 0); testInfo.server->ssl->hsCtx->state = TRY_RECV_CLIENT_KEY_EXCHANGE; uint32_t parseLen = 0; frameType.versionType = HITLS_VERSION_TLS12; frameType.recordType = REC_TYPE_HANDSHAKE; frameType.handshakeType = CERTIFICATE; frameType.keyExType = 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); 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); ASSERT_EQ(HITLS_Accept(testInfo.server->ssl), HITLS_MSG_HANDLE_UNEXPECTED_MESSAGE); 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_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_TLS12_RFC5246_CONSISTENCY_HANDSHAKE_UNEXPECTMSG_TC011 * @title An unexpected message is received when the server is in the TRY_RECV_CERTIFICATIONATE_VERIFY state during the * handshake. * @precon nan * @brief 1. Use the default configuration items to configure the client and server. Expected result 1 is obtained. * 2. Construct a CLIENT_KEY_EXCHANGE message and send it to the server. Expected result 2 is obtained. * @expect 1. The initialization is successful. * 2. After receiving the CLIENT_KEY_EXCHANGE message, the server sends an ALERT message. The level is * ALERT_Level_FATAL and the description is ALERT_UNEXPECTED_MESSAGE. @ */ /* BEGIN_CASE */ void UT_TLS_TLS12_RFC5246_CONSISTENCY_HANDSHAKE_UNEXPECTMSG_TC011(void) { /* Use the default configuration items to configure the client and server. */ HandshakeTestInfo testInfo = { 0 }; FRAME_Msg frameMsg = { 0 }; FRAME_Type frameType = { 0 }; testInfo.state = TRY_RECV_CLIENT_KEY_EXCHANGE; testInfo.isSupportExtendMasterSecret = true; testInfo.isClient = false; testInfo.isSupportClientVerify = true; testInfo.isSupportNoClientCert = false; ASSERT_TRUE(DefaultCfgStatusPark(&testInfo) == HITLS_SUCCESS); /* Construct a CLIENT_KEY_EXCHANGE message and send it to the server. */ FrameUioUserData *ioUserData = BSL_UIO_GetUserData(testInfo.server->io); uint8_t *recvBuf = ioUserData->recMsg.msg; uint32_t recvLen = ioUserData->recMsg.len; ASSERT_TRUE(recvLen != 0); testInfo.server->ssl->hsCtx->state = TRY_RECV_CERTIFICATE_VERIFY; uint32_t parseLen = 0; frameType.versionType = HITLS_VERSION_TLS12; frameType.recordType = REC_TYPE_HANDSHAKE; frameType.handshakeType = CLIENT_KEY_EXCHANGE; frameType.keyExType = 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); 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); ASSERT_EQ(HITLS_Accept(testInfo.server->ssl), HITLS_MSG_HANDLE_UNEXPECTED_MESSAGE); 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_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_TLS12_RFC5246_CONSISTENCY_HANDSHAKE_UNEXPECTMSG_TC012 * @title An unexpected message is received when the server is in the TRY_RECV_FINISH state during the handshake. * @precon nan * @brief 1. Use the default configuration items to configure the client and server. Expected result 1 is obtained. * 2. Construct a CLIENT_KEY_EXCHANGE message and send it to the server. Expected result 2 is obtained. * @expect 1. The initialization is successful. * 2. After receiving the CLIENT_KEY_EXCHANGE message, the server sends an ALERT message. The level is ALERT_Level_FATAL and the description is ALERT_UNEXPECTED_MESSAGE. @ */ /* BEGIN_CASE */ void UT_TLS_TLS12_RFC5246_CONSISTENCY_HANDSHAKE_UNEXPECTMSG_TC012(void) { /* Use the default configuration items to configure the client and server. */ HandshakeTestInfo testInfo = { 0 }; FRAME_Msg frameMsg = { 0 }; FRAME_Type frameType = { 0 }; testInfo.state = TRY_RECV_CLIENT_KEY_EXCHANGE; testInfo.isSupportExtendMasterSecret = true; testInfo.isClient = false; testInfo.isSupportClientVerify = true; testInfo.isSupportNoClientCert = false; ASSERT_TRUE(DefaultCfgStatusPark(&testInfo) == HITLS_SUCCESS); /* Construct a CLIENT_KEY_EXCHANGE message and send it to the server. */ FrameUioUserData *ioUserData = BSL_UIO_GetUserData(testInfo.server->io); uint8_t *recvBuf = ioUserData->recMsg.msg; uint32_t recvLen = ioUserData->recMsg.len; ASSERT_TRUE(recvLen != 0); testInfo.server->ssl->hsCtx->state = TRY_RECV_FINISH; uint32_t parseLen = 0; frameType.versionType = HITLS_VERSION_TLS12; frameType.recordType = REC_TYPE_HANDSHAKE; frameType.handshakeType = CLIENT_KEY_EXCHANGE; frameType.keyExType = 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); 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); ASSERT_EQ(HITLS_Accept(testInfo.server->ssl), HITLS_MSG_HANDLE_UNEXPECTED_MESSAGE); 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_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_TLS12_RFC5246_CONSISTENCY_AEAD_EXPLICIT_IV_LENGTH_TC001 * @title The client and server establish a connection. Check whether the sequence number in the APP message is * contained in the record-layer message. * @precon nan * @brief 1. Use the default configuration items to configure the client and server. Expected result 1 is obtained. * 2. A TLS over TCP link is established between the client and server. Expected result 2 is obtained. * 3. Randomly generate a 32-bit transmission data. Expected result 3 is obtained. * 4. Randomly generate a serial number. Expected result 4 is obtained. * 5. Write app data to the server. * 6. Data transmission at the record layer. * 7. Check the changes before and after the sequence number is sent. * 8. Record layer data receiving. * @expect 1. The initialization is successful. * 2. The link is set up successfully. * 3. The generation is successful. * 4. The generation is successful. * 5. The writing is successful. * 6. Transmission is successful. * 7. After the sending, the seqNum is increased by 1. * 8. The data length and data content are verified successfully. @ */ /* BEGIN_CASE */ void UT_TLS_TLS12_RFC5246_CONSISTENCY_AEAD_EXPLICIT_IV_LENGTH_TC001() { /* Use the default configuration items to configure the client and server. */ FRAME_Msg frameMsg = { 0 }; FRAME_Type frameType = { 0 }; HandshakeTestInfo testInfo = { 0 }; testInfo.state = HS_STATE_BUTT; ASSERT_TRUE(DefaultCfgStatusPark(&testInfo) == HITLS_SUCCESS); /* A TLS over TCP link is established between the client and server. */ ASSERT_TRUE(FRAME_CreateConnection(testInfo.client, testInfo.server, false, HS_STATE_BUTT) == HITLS_SUCCESS); ASSERT_TRUE(testInfo.server->ssl != NULL); ASSERT_TRUE(testInfo.server->ssl->state == CM_STATE_TRANSPORTING); /* Randomly generate a 32-bit transmission data. */ uint8_t transportData[REC_CONN_SEQ_SIZE * 4] = {0}; uint32_t transportDataLen = sizeof(transportData) / sizeof(uint8_t); ASSERT_EQ(RandBytes(transportData, transportDataLen), HITLS_SUCCESS); /* Randomly generate a serial number. */ uint8_t randSeq[REC_CONN_SEQ_SIZE] = {0}; ASSERT_EQ(RandBytes(randSeq, REC_CONN_SEQ_SIZE), HITLS_SUCCESS); REC_Ctx *recCtx = (REC_Ctx *)testInfo.server->ssl->recCtx; recCtx->writeStates.currentState->seq = BSL_ByteToUint64(randSeq); uint64_t sequenceNumber = recCtx->writeStates.currentState->seq; uint8_t seq[REC_CONN_SEQ_SIZE] = {0}; BSL_Uint64ToByte(sequenceNumber, seq); /* Write app data to the server. */ uint32_t writeLen; int32_t ret = APP_Write(testInfo.server->ssl, transportData, transportDataLen, &writeLen); ASSERT_TRUE(ret == HITLS_SUCCESS); /* Data transmission at the record layer. */ uint8_t tmpData[MAX_RECORD_LENTH] = {0}; uint32_t tmpLen; ASSERT_TRUE(FRAME_TransportSendMsg(testInfo.server->io, tmpData, MAX_RECORD_LENTH, &tmpLen) == HITLS_SUCCESS); /* Check the changes before and after the sequence number is sent. */ recCtx = (REC_Ctx *)testInfo.server->ssl->recCtx; uint64_t sequenceNumberAfterSend = recCtx->writeStates.currentState->seq; ASSERT_EQ(sequenceNumberAfterSend, sequenceNumber + 1); /* Record layer data receiving. */ ASSERT_TRUE(FRAME_TransportRecMsg(testInfo.client->io, tmpData, tmpLen) == HITLS_SUCCESS); const int32_t AEAD_TAG_LEN = 16u; ASSERT_EQ(tmpLen, REC_TLS_RECORD_HEADER_LEN + REC_CONN_SEQ_SIZE + transportDataLen + AEAD_TAG_LEN); ASSERT_TRUE(memcmp(tmpData + REC_TLS_RECORD_HEADER_LEN, seq, REC_CONN_SEQ_SIZE) == 0); 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_TLS12_RFC5246_CONSISTENCY_READ_PENDING_STATE_TC001 * @title Observe the changes in the status of the record layer before and after the client receives the CCS message. * @precon nan * @brief 1. Use the default configuration items to configure the client to stop the client in the TRY_RECV_FINISH state. Expected result 1 is obtained. * 2. Record the states at the record layer that the client reads. Expected result 2 is obtained. * 3. Reconnect the client. Expected result 3 is obtained. * 4. Check the states at the record layer after the client is reconnected. Expected result 4 is obtained. * @expect 1. The initialization is successful. * 2. The outdatedState field is empty. * 3. The return value for reconnection is HITLS_REC_NORMAL_RECV_BUF_EMPTY. * 4. OutdatedState is the previous currentState. * currentState is the previous pendingState. * The pendingState field is empty. @ */ /* BEGIN_CASE */ void UT_TLS_TLS12_RFC5246_CONSISTENCY_READ_PENDING_STATE_TC001() { /* Use the default configuration items to configure the client to stop the client in the TRY_RECV_FINISH state. */ HandshakeTestInfo testInfo = { 0 }; testInfo.isClient = true; testInfo.state = TRY_RECV_FINISH; testInfo.needStopBeforeRecvCCS = true; ASSERT_TRUE(DefaultCfgStatusPark(&testInfo) == HITLS_SUCCESS); /* Record the states at the record layer that the client reads. */ RecConnStates *readStates = (RecConnStates *)&(testInfo.client->ssl->recCtx->readStates); RecConnState *oldOutdatedState = readStates->outdatedState; RecConnState *oldCurrentState = readStates->currentState; RecConnState *oldPendingState = readStates->pendingState; ASSERT_TRUE(oldOutdatedState == NULL); // Reconnect the client. ASSERT_EQ(HITLS_Connect(testInfo.client->ssl), HITLS_REC_NORMAL_RECV_BUF_EMPTY); /* Check the states at the record layer after the client is reconnected. */ RecConnState *newOutdatedState = readStates->outdatedState; RecConnState *newCurrentState = readStates->currentState; RecConnState *newPendingState = readStates->pendingState; ASSERT_TRUE(newOutdatedState == oldCurrentState); ASSERT_TRUE(newCurrentState == oldPendingState); ASSERT_TRUE(newPendingState == NULL); EXIT: HITLS_CFG_FreeConfig(testInfo.config); FRAME_FreeLink(testInfo.client); FRAME_FreeLink(testInfo.server); FRAME_DeRegCryptMethod(); } /* END_CASE */ /* @ * @test UT_TLS_TLS12_RFC5246_CONSISTENCY_READ_PENDING_STATE_TC002 * @title Check the status change of the record layer before and after the server receives the CCS message. * @precon nan * @brief 1. Use the default configuration items to set the server to the TRY_RECV_FINISH state. Expected result 1 is obtained. * 2. Record the states of the record layer that the client reads. Expected result 2 is obtained. * 3. Reconnect the server. Expected result 3 is obtained. * 4. Check the states at the record layer after the client is reconnected. Expected result 4 is obtained. * @expect 1. The initialization is successful. * 2. OutdatedState is empty. * 3. The return value for reconnection is HITLS_REC_NORMAL_RECV_BUF_EMPTY. * 4. OutdatedState is the previous currentState. * currentState is the previous pendingState. * The pendingState field is empty. @ */ /* BEGIN_CASE */ void UT_TLS_TLS12_RFC5246_CONSISTENCY_READ_PENDING_STATE_TC002() { /* Use the default configuration items to set the server to the TRY_RECV_FINISH state. */ HandshakeTestInfo testInfo = { 0 }; testInfo.isClient = false; testInfo.state = TRY_RECV_FINISH; testInfo.needStopBeforeRecvCCS = true; ASSERT_TRUE(DefaultCfgStatusPark(&testInfo) == HITLS_SUCCESS); /* Record the states of the record layer that the client reads. */ RecConnStates *readStates = (RecConnStates *)&(testInfo.server->ssl->recCtx->readStates); RecConnState *oldOutdatedState = readStates->outdatedState; RecConnState *oldCurrentState = readStates->currentState; RecConnState *oldPendingState = readStates->pendingState; ASSERT_TRUE(oldOutdatedState == NULL); // Reconnect the server. ASSERT_EQ(HITLS_Accept(testInfo.server->ssl), HITLS_REC_NORMAL_RECV_BUF_EMPTY); /* Check the states at the record layer after the client is reconnected. */ RecConnState *newOutdatedState = readStates->outdatedState; RecConnState *newCurrentState = readStates->currentState; RecConnState *newPendingState = readStates->pendingState; ASSERT_TRUE(newOutdatedState == oldCurrentState); ASSERT_TRUE(newCurrentState == oldPendingState); ASSERT_TRUE(newPendingState == NULL); EXIT: HITLS_CFG_FreeConfig(testInfo.config); FRAME_FreeLink(testInfo.client); FRAME_FreeLink(testInfo.server); FRAME_DeRegCryptMethod(); } /* END_CASE */ /* @ * @test UT_TLS_TLS12_RFC5246_CONSISTENCY_WRITE_PENDING_STATE_TC001 * @title Observe the change of the write record layer status before and after the client sends the CCS message. * @precon nan * @brief 1. Use the default configuration items to set the server to the TRY_RECV_FINISH state. Expected result 1 is obtained. * 2. Record the states of the client write record layer. Expected result 2 is obtained. * 3. Reconnect the server. Expected result 3 is obtained. * 4. Check the states of the write record layer after the client is reconnected. Expected result 4 is obtained. * @expect 1. The initialization is successful. * 2. The outdatedState field is empty. * 3. The return value for reconnection is HITLS_REC_NORMAL_IO_BUSY. * 4. OutdatedState is the previous currentState. * currentState is the previous pendingState. * The pendingState field is empty. @ */ /* BEGIN_CASE */ void UT_TLS_TLS12_RFC5246_CONSISTENCY_WRITE_PENDING_STATE_TC001() { /* Use the default configuration items to set the server to the TRY_RECV_FINISH state. */ HandshakeTestInfo testInfo = { 0 }; testInfo.isClient = true; testInfo.state = TRY_SEND_CHANGE_CIPHER_SPEC; testInfo.needStopBeforeRecvCCS = true; ASSERT_TRUE(DefaultCfgStatusPark(&testInfo) == HITLS_SUCCESS); /* Record the states of the client write record layer. */ RecConnStates *writeStates = (RecConnStates *)&(testInfo.client->ssl->recCtx->writeStates); RecConnState *oldOutdatedState = writeStates->outdatedState; RecConnState *oldCurrentState = writeStates->currentState; RecConnState *oldPendingState = writeStates->pendingState; ASSERT_TRUE(oldOutdatedState == NULL); // Reconnect the server. ASSERT_EQ(HITLS_Connect(testInfo.client->ssl), HITLS_REC_NORMAL_IO_BUSY); /* Check the states of the write record layer after the client is reconnected. */ RecConnState *newOutdatedState = writeStates->outdatedState; RecConnState *newCurrentState = writeStates->currentState; RecConnState *newPendingState = writeStates->pendingState; ASSERT_TRUE(newOutdatedState == oldCurrentState); ASSERT_TRUE(newCurrentState == oldPendingState); ASSERT_TRUE(newPendingState == NULL); EXIT: HITLS_CFG_FreeConfig(testInfo.config); FRAME_FreeLink(testInfo.client); FRAME_FreeLink(testInfo.server); FRAME_DeRegCryptMethod(); } /* END_CASE */ /* @ * @test UT_TLS_TLS12_RFC5246_CONSISTENCY_WRITE_PENDING_STATE_TC002 * @title Observe the change of the write record layer status before and after the server sends the CCS message. * @precon nan * @brief 1. Use the default configuration items to configure the server to stop the server in the TRY_RECV_FINISH state. Expected result 1 is obtained. * 2. Record the states at the write record layer on the client. Expected result 2 is obtained. * 3. Reconnect the server. Expected result 3 is obtained. * 4. Check the states of the write record layer after the client is reconnected. Expected result 4 is obtained. * @expect 1. The initialization is successful. * 2. The outdatedState field is empty. * 3. The return value for reconnection is HITLS_REC_NORMAL_IO_BUSY. * 4. OutdatedState is the previous currentState. * currentState is the previous pendingState. * The pendingState field is empty. @ */ /* BEGIN_CASE */ void UT_TLS_TLS12_RFC5246_CONSISTENCY_WRITE_PENDING_STATE_TC002() { /* Use the default configuration items to configure the server to stop the server in the TRY_RECV_FINISH state. */ HandshakeTestInfo testInfo = { 0 }; testInfo.isClient = false; testInfo.state = TRY_SEND_CHANGE_CIPHER_SPEC; testInfo.needStopBeforeRecvCCS = true; ASSERT_TRUE(DefaultCfgStatusPark(&testInfo) == HITLS_SUCCESS); /* Record the states at the write record layer on the client. */ RecConnStates *writeStates = (RecConnStates *)&(testInfo.server->ssl->recCtx->writeStates); RecConnState *oldOutdatedState = writeStates->outdatedState; RecConnState *oldCurrentState = writeStates->currentState; RecConnState *oldPendingState = writeStates->pendingState; ASSERT_TRUE(oldOutdatedState == NULL); // Reconnect the server. ASSERT_EQ(HITLS_Accept(testInfo.server->ssl), HITLS_REC_NORMAL_IO_BUSY); /* Check the states of the write record layer after the client is reconnected. */ RecConnState *newOutdatedState = writeStates->outdatedState; RecConnState *newCurrentState = writeStates->currentState; RecConnState *newPendingState = writeStates->pendingState; ASSERT_TRUE(newOutdatedState == oldCurrentState); ASSERT_TRUE(newCurrentState == oldPendingState); ASSERT_TRUE(newPendingState == NULL); EXIT: HITLS_CFG_FreeConfig(testInfo.config); FRAME_FreeLink(testInfo.client); FRAME_FreeLink(testInfo.server); FRAME_DeRegCryptMethod(); } /* END_CASE */ /* @ * @test UT_TLS_TLS12_RFC5246_CONSISTENCY_RENEGOTIATION_MASTEKEY_TC001 * @title Check whether the master key changes before and after the client initiates renegotiation. * @precon nan * @brief 1. Use the default configuration items to configure the server so that the connection is successfully established. Expected result 1 is obtained. * 2. Simulate link establishment and check the TLS_Ctx and CM_State on both ends. Expected result 2 is obtained. * 3. Obtain the current session from the client. Expected result 3 is obtained. * 4. Obtain the masterKey from the session ID of the client. Expected result 4 is obtained. * 5. The server sends a Hello Request message. Expected result 5 is obtained. * 6. Reconnect the client and retransmit data on the server. Expected result 6 is obtained. * 7. Obtain the new masterKey based on the client session ID and compare it with the old masterKey. Expected result 7 is obtained. * @expect 1. The initialization is successful. * 2. The link is set up successfully. TLS_Ctx is not empty and CM_State is Transporting. * 3. The session is not empty. * 4. Obtained successfully. * 5. The message is sent successfully. * 6. The connection is successful. * 7. The data is obtained successfully and the comparison is consistent. @ */ /* BEGIN_CASE */ void UT_TLS_TLS12_RFC5246_CONSISTENCY_RENEGOTIATION_MASTEKEY_TC001() { /* Use the default configuration items to configure the server so that the connection is successfully established. */ HandshakeTestInfo testInfo = { 0 }; testInfo.isClient = true; testInfo.isSupportRenegotiation = true; testInfo.state = HS_STATE_BUTT; ASSERT_TRUE(DefaultCfgStatusPark(&testInfo) == HITLS_SUCCESS); /* Simulate link establishment and check the TLS_Ctx and CM_State on both ends. */ ASSERT_TRUE(testInfo.server->ssl != NULL); ASSERT_TRUE(testInfo.client->ssl != NULL); ASSERT_TRUE(testInfo.server->ssl->state == CM_STATE_TRANSPORTING); ASSERT_TRUE(testInfo.client->ssl->state == CM_STATE_TRANSPORTING); /* Obtain the current session from the client. */ HITLS_Session *session = HITLS_GetDupSession(testInfo.client->ssl); ASSERT_TRUE(session != NULL); /* Obtain the masterKey from the session ID of the client. */ uint8_t masterkey1[MAX_MASTER_KEY_SIZE] = {0}; uint32_t masterkey1Len = MAX_MASTER_KEY_SIZE; ASSERT_TRUE(HITLS_SESS_GetMasterKey(session, masterkey1, &masterkey1Len) == HITLS_SUCCESS); /* The server sends a Hello Request message. */ ASSERT_TRUE(HITLS_Renegotiate(testInfo.server->ssl) == HITLS_SUCCESS); ASSERT_TRUE(HITLS_Accept(testInfo.server->ssl) == HITLS_SUCCESS); ASSERT_TRUE(FRAME_TrasferMsgBetweenLink(testInfo.server, testInfo.client) == HITLS_SUCCESS); /* Reconnect the client and retransmit data on the server. */ ASSERT_TRUE(testInfo.client->ssl != NULL); 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_NORMAL_RECV_BUF_EMPTY); ASSERT_TRUE(testInfo.client->ssl->state == CM_STATE_RENEGOTIATION); ASSERT_EQ(FRAME_CreateRenegotiationState(testInfo.client, testInfo.server, true, HS_STATE_BUTT), HITLS_SUCCESS); ASSERT_EQ(testInfo.client->ssl->state, CM_STATE_TRANSPORTING); /* Obtain the new masterKey based on the client session ID and compare it with the old masterKey. */ uint8_t masterkey2[MAX_MASTER_KEY_SIZE] = {0}; uint32_t masterkey2Len = MAX_MASTER_KEY_SIZE; HITLS_Session *session2 = HITLS_GetDupSession(testInfo.client->ssl); uint32_t masterkeylen = HITLS_SESS_GetMasterKeyLen(session2); ASSERT_TRUE(HITLS_SESS_GetMasterKey(session2, masterkey2, &masterkey2Len) == HITLS_SUCCESS); ASSERT_TRUE(memcmp(masterkey1, masterkey2, masterkeylen) != 0); EXIT: HITLS_CFG_FreeConfig(testInfo.config); HITLS_SESS_Free(session); HITLS_SESS_Free(session2); FRAME_FreeLink(testInfo.client); FRAME_FreeLink(testInfo.server); FRAME_DeRegCryptMethod(); } /* END_CASE */ /* @ * @test UT_TLS_TLS12_RFC5246_CONSISTENCY_SEQ_NUM_TC001 * @title Check whether the sequence number in the record layer in the FINISH message sent by the server or client is 0. * @precon nan * @brief 1. Configure the client/server to stay in the TRY_SEND_FINISH state. Expected result 1 is obtained. * 2. Connect the server and client once and send the message. Expected result 2 is obtained. * 3. Obtain the messages sent by the server or client. Expected result 3 is obtained. * 4. Parse the message sent by the local end into the hs_msg structure. Expected result 4 is obtained. * 5. Check the sequence number in the sent message. Expected result 5 is obtained. * 6. Enable the local end to transmit data to the peer end. Expected result 6 is obtained. * 7. Obtain the messages received by the peer end. Expected result 7 is obtained. * 8. Parse the message received by the peer end into the hs_msg structure. Expected result 8 is obtained. * 9. Check the sequence number in the received message. Expected result 5 is obtained. * @expect 1. The initialization is successful. * 2. If the server is successfully connected, the client returns NORMAL_RECV_BUF_EMPTY. * 3. The sending length is not null. * 4. The parsing is successful, and the message header length is fixed to 5 bytes (TLS1.2). * 5. The serial number is zero. * 6. The transmission is successful. * 7. The received length is not empty. * 8. The parsing succeeds and the message header length is fixed to 5 bytes (TLS1.2). * 9. The serial number is zero. @ */ /* BEGIN_CASE */ void UT_TLS_TLS12_RFC5246_CONSISTENCY_SEQ_NUM_TC001(int isClient) { /* Configure the client/server to stay in the TRY_SEND_FINISH state. */ HandshakeTestInfo testInfo = { 0 }; testInfo.isSupportExtendMasterSecret = true; testInfo.state = TRY_SEND_FINISH; testInfo.isClient = isClient; ASSERT_TRUE(DefaultCfgStatusPark(&testInfo) == HITLS_SUCCESS); /* Connect the server and client once and send the message. */ if (isClient) { ASSERT_TRUE(HITLS_Connect(testInfo.client->ssl) == HITLS_REC_NORMAL_RECV_BUF_EMPTY); } else { ASSERT_TRUE(HITLS_Accept(testInfo.server->ssl) == HITLS_SUCCESS); } /* Obtain the messages sent by the server or client. */ BSL_UIO *sendIo = isClient ? testInfo.client->io : testInfo.server->io; FrameUioUserData *ioUserData = BSL_UIO_GetUserData(sendIo); uint8_t *sendBuf = ioUserData->sndMsg.msg; uint32_t sendLen = ioUserData->sndMsg.len; ASSERT_TRUE(sendLen != 0); /* Parse the message sent by the local end into the hs_msg structure. */ uint32_t parseLen = 0; FRAME_Msg frameMsg = { 0 }; FRAME_Type frameType = { 0 }; frameType.versionType = HITLS_VERSION_TLS12; frameType.keyExType = HITLS_KEY_EXCH_ECDHE; ASSERT_TRUE(FRAME_ParseMsgHeader(&frameType, sendBuf, sendLen, &frameMsg, &parseLen) == HITLS_SUCCESS); ASSERT_TRUE(parseLen == REC_TLS_RECORD_HEADER_LEN); /* Check the sequence number in the sent message. */ uint8_t seqBuf[REC_CONN_SEQ_SIZE] = {0}; ASSERT_TRUE(memcpy_s(seqBuf, sendLen, sendBuf + REC_TLS_RECORD_HEADER_LEN, REC_CONN_SEQ_SIZE) == 0); uint64_t seq = BSL_ByteToUint64(seqBuf); ASSERT_EQ(seq, 0u); /* Enable the local end to transmit data to the peer end. */ if (isClient) { ASSERT_TRUE(FRAME_TrasferMsgBetweenLink(testInfo.client, testInfo.server) == HITLS_SUCCESS); } else { ASSERT_TRUE(FRAME_TrasferMsgBetweenLink(testInfo.server, testInfo.client) == HITLS_SUCCESS); } /* Obtain the messages received by the peer end. */ BSL_UIO *recvIo = isClient ? testInfo.server->io : testInfo.client->io; FrameUioUserData *ioUserData2 = BSL_UIO_GetUserData(recvIo); uint8_t *recvBuf = ioUserData2->recMsg.msg; uint32_t recvLen = ioUserData2->recMsg.len; ASSERT_TRUE(recvLen != 0); /* Parse the message received by the peer end into the hs_msg structure. */ uint32_t parseLen2 = 0; FRAME_Msg frameMsg2 = { 0 }; FRAME_Type frameType2 = { 0 }; frameType2.versionType = HITLS_VERSION_TLS12; frameType2.keyExType = HITLS_KEY_EXCH_ECDHE; ASSERT_TRUE(FRAME_ParseMsgHeader(&frameType2, recvBuf, recvLen, &frameMsg2, &parseLen2) == HITLS_SUCCESS); ASSERT_TRUE(parseLen2 == REC_TLS_RECORD_HEADER_LEN); /* Check the sequence number in the received message. */ ASSERT_TRUE(memset_s(seqBuf, REC_CONN_SEQ_SIZE, 0, REC_CONN_SEQ_SIZE) == 0); ASSERT_TRUE(memcpy_s(seqBuf, recvLen, recvBuf + REC_TLS_RECORD_HEADER_LEN, REC_CONN_SEQ_SIZE) == 0); uint64_t seq2 = BSL_ByteToUint64(seqBuf); ASSERT_EQ(seq2, 0u); EXIT: FRAME_CleanMsg(&frameType, &frameMsg); FRAME_CleanMsg(&frameType2, &frameMsg2); HITLS_CFG_FreeConfig(testInfo.config); FRAME_FreeLink(testInfo.client); FRAME_FreeLink(testInfo.server); FRAME_DeRegCryptMethod(); } /* END_CASE */ /* @ * @test UT_TLS_TLS12_RFC5246_CONSISTENCY_SEQ_NUM_TC002 * @title Check whether the sequence number in the record layer in the FINISH message sent by the server/client is 0. * @precon nan * @brief 1. Configure the client/server to the status that the handshake is successful. Expected result 1 is obtained. * 2. Check the server/client connection status. Expected result 2 is obtained. * 3. Randomly generate 32 bytes of data to be transmitted. Expected result 3 is obtained. * 4. Write app data. Expected result 4 is obtained. 5. Obtain data from the I/O sent by the local end and parse the header and content. Expected result 5 is obtained. 6. Check the sequence number in the sent message. Expected result 6 is obtained. 7. Perform I/O data transmission from the local end to the peer end. Expected result 7 is obtained. 8. Obtain data from the received I/O from the peer end and parse the header and content. Expected result 8 is obtained. 9. Check the sequence number in the received message. Expected result 9 is obtained. * @expect 1. The initialization is successful. * 2. The link status is Transferring. 3. The generation is successful. 4. The writing is successful. 5. The parsing is successful, and the value of RecordType is REC_TYPE_APP. 6. The SN is 1. 7. The transmission is successful. 8. The parsing is successful, and the value of RecordType is REC_TYPE_APP. 9. The serial number is 1. @ */ /* BEGIN_CASE */ void UT_TLS_TLS12_RFC5246_CONSISTENCY_SEQ_NUM_TC002(int isClient) { /* Configure the client/server to the status that the handshake is successful. */ HandshakeTestInfo testInfo = { 0 }; testInfo.isSupportExtendMasterSecret = true; testInfo.state = HS_STATE_BUTT; testInfo.isClient = isClient; ASSERT_TRUE(DefaultCfgStatusPark(&testInfo) == HITLS_SUCCESS); /* Check the server/client connection status. */ ASSERT_TRUE(testInfo.client->ssl->state == CM_STATE_TRANSPORTING); ASSERT_TRUE(testInfo.server->ssl->state == CM_STATE_TRANSPORTING); /* Randomly generate 32 bytes of data to be transmitted. */ uint8_t transportData[REC_CONN_SEQ_SIZE * 4] = {0}; uint32_t transportDataLen = sizeof(transportData) / sizeof(uint8_t); ASSERT_EQ(RandBytes(transportData, transportDataLen), HITLS_SUCCESS); /* Write app data. */ HITLS_Ctx *localSsl = isClient ? testInfo.client->ssl : testInfo.server->ssl; uint32_t writeLen; ASSERT_EQ(APP_Write(localSsl, transportData, transportDataLen, &writeLen), HITLS_SUCCESS); /* Obtain data from the I/O sent by the local end and parse the header and content. */ BSL_UIO *sendIo = isClient ? testInfo.client->io : testInfo.server->io; FrameUioUserData *ioUserData = BSL_UIO_GetUserData(sendIo); uint8_t *sendBuf = ioUserData->sndMsg.msg; uint32_t sendLen = ioUserData->sndMsg.len; ASSERT_TRUE(sendLen != 0); uint32_t parseLen = 0; FRAME_Msg frameMsg = { 0 }; FRAME_Type frameType = { 0 }; frameType.versionType = HITLS_VERSION_TLS12; frameType.keyExType = HITLS_KEY_EXCH_ECDHE; ASSERT_TRUE(FRAME_ParseMsgHeader(&frameType, sendBuf, sendLen, &frameMsg, &parseLen) == HITLS_SUCCESS); ASSERT_TRUE(parseLen == REC_TLS_RECORD_HEADER_LEN); ASSERT_TRUE(FRAME_ParseMsgBody(&frameType, sendBuf + parseLen, sendLen, &frameMsg, &parseLen) == HITLS_SUCCESS); ASSERT_EQ(frameType.recordType, REC_TYPE_APP); /* Check the sequence number in the sent message. */ uint8_t seqBuf[REC_CONN_SEQ_SIZE] = {0}; ASSERT_TRUE(memcpy_s(seqBuf, sendLen, sendBuf + REC_TLS_RECORD_HEADER_LEN, REC_CONN_SEQ_SIZE) == 0); uint64_t seq = BSL_ByteToUint64(seqBuf); ASSERT_EQ(seq, 1u); /* Perform I/O data transmission from the local end to the peer end. */ if (isClient) { ASSERT_TRUE(FRAME_TrasferMsgBetweenLink(testInfo.client, testInfo.server) == HITLS_SUCCESS); } else { ASSERT_TRUE(FRAME_TrasferMsgBetweenLink(testInfo.server, testInfo.client) == HITLS_SUCCESS); } /* Obtain data from the received I/O from the peer end and parse the header and content. */ BSL_UIO *recvIo = isClient ? testInfo.server->io : testInfo.client->io; FrameUioUserData *ioUserData2 = BSL_UIO_GetUserData(recvIo); uint8_t *recvBuf = ioUserData2->recMsg.msg; uint32_t recvLen = ioUserData2->recMsg.len; ASSERT_TRUE(recvLen != 0); uint32_t parseLen2 = 0; FRAME_Msg frameMsg2 = { 0 }; FRAME_Type frameType2 = { 0 }; frameType2.versionType = HITLS_VERSION_TLS12; frameType2.keyExType = HITLS_KEY_EXCH_ECDHE; ASSERT_TRUE(FRAME_ParseMsgHeader(&frameType2, recvBuf, recvLen, &frameMsg2, &parseLen2) == HITLS_SUCCESS); ASSERT_TRUE(parseLen2 == REC_TLS_RECORD_HEADER_LEN); ASSERT_TRUE(FRAME_ParseMsgBody(&frameType2, recvBuf + parseLen2, recvLen, &frameMsg2, &parseLen2) == HITLS_SUCCESS); ASSERT_EQ(frameType.recordType, REC_TYPE_APP); /* Check the sequence number in the received message. */ ASSERT_TRUE(memset_s(seqBuf, REC_CONN_SEQ_SIZE, 0, REC_CONN_SEQ_SIZE) == 0); ASSERT_TRUE(memcpy_s(seqBuf, recvLen, recvBuf + REC_TLS_RECORD_HEADER_LEN, REC_CONN_SEQ_SIZE) == 0); uint64_t seq2 = BSL_ByteToUint64(seqBuf); ASSERT_EQ(seq2, 1u); EXIT: FRAME_CleanMsg(&frameType, &frameMsg); FRAME_CleanMsg(&frameType2, &frameMsg2); HITLS_CFG_FreeConfig(testInfo.config); FRAME_FreeLink(testInfo.client); FRAME_FreeLink(testInfo.server); FRAME_DeRegCryptMethod(); } /* END_CASE */ /* @ * @test UT_TLS_TLS12_RFC5246_CONSISTENCY_UNEXPECT_RECODETYPE_TC001 * @title After initialization, the server receives a CCS message after sending the serverhellodone message and expects 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 link application. After sending the Server Hello Done message, the server constructs a CCS message and sends it to the server. Expected result 2 is obtained. * @expect 1. The initialization is successful. * 2. The server sends an ALERT message. @ */ /* BEGIN_CASE */ void UT_TLS_TLS12_RFC5246_CONSISTENCY_UNEXPECT_RECODETYPE_TC001(void) { /* Use the default configuration on the client and server, and disable peer verification on the server. */ HandshakeTestInfo testInfo = { 0 }; testInfo.state = TRY_RECV_CLIENT_KEY_EXCHANGE; testInfo.isClient = false; testInfo.isSupportExtendMasterSecret = true; testInfo.isSupportClientVerify = false; ASSERT_TRUE(DefaultCfgStatusPark(&testInfo) == HITLS_SUCCESS); FRAME_Msg frameMsg = { 0 }; FRAME_Type frameType = { 0 }; frameType.versionType = HITLS_VERSION_TLS12; frameType.recordType = REC_TYPE_CHANGE_CIPHER_SPEC; 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); 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)); /* The client initiates a TLS link application. After sending the Server Hello Done message, the server constructs a * CCS message and sends it to the server. */ 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; 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_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); FRAME_DeRegCryptMethod(); } /* END_CASE */ /* @ * @test UT_TLS_TLS12_RFC5246_CONSISTENCY_UNEXPECT_RECODETYPE_TC002 * @title After initialization, the client receives a CCS message after sending a client hello message and expects 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 link application. After sending the client hello message, the client constructs a CCS 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_TLS12_RFC5246_CONSISTENCY_UNEXPECT_RECODETYPE_TC002(void) { /* Use the default configuration on the client and server, and disable peer verification on the server. */ HandshakeTestInfo testInfo = { 0 }; testInfo.state = TRY_RECV_SERVER_HELLO; testInfo.isClient = true; testInfo.isSupportExtendMasterSecret = true; testInfo.isSupportClientVerify = false; ASSERT_TRUE(DefaultCfgStatusPark(&testInfo) == HITLS_SUCCESS); FRAME_Msg frameMsg = { 0 }; FRAME_Type frameType = { 0 }; frameType.versionType = HITLS_VERSION_TLS12; frameType.recordType = REC_TYPE_CHANGE_CIPHER_SPEC; 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); 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)); /* The client initiates a TLS link application. After sending the client hello message, the client constructs a CCS * message and sends it to the client. */ 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_TRUE(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); FRAME_DeRegCryptMethod(); } /* END_CASE */ /* @ * @test UT_TLS_TLS12_RFC5246_CONSISTENCY_UNEXPECT_RECODETYPE_TC003 * @title During link establishment, the client receives the serverhello message after sending the CCS and expects 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 link application. After sending the CCS, the client 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_TLS12_RFC5246_CONSISTENCY_UNEXPECT_RECODETYPE_TC003(void) { /* Use the default configuration on the client and server, and disable peer verification on the server. */ HandshakeTestInfo testInfo = { 0 }; testInfo.state = TRY_SEND_CHANGE_CIPHER_SPEC; testInfo.isClient = true; testInfo.isSupportExtendMasterSecret = true; testInfo.isSupportClientVerify = false; testInfo.isSupportNoClientCert = false; ASSERT_TRUE(DefaultCfgStatusParkWithSuite(&testInfo) == HITLS_SUCCESS); testInfo.client->ssl->hsCtx->state = TRY_RECV_FINISH; FRAME_Msg frameMsg = { 0 }; FRAME_Type frameType = { 0 }; frameType.versionType = HITLS_VERSION_TLS12; frameType.recordType = REC_TYPE_HANDSHAKE; frameType.handshakeType = SERVER_HELLO; frameType.keyExType = HITLS_KEY_EXCH_ECDHE; ASSERT_EQ(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); 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)); /* The client initiates a TLS link application. After sending the CCS, the client constructs a serverhello message * and sends it to the client. */ ASSERT_TRUE(testInfo.client->ssl != NULL); ASSERT_EQ(HITLS_Connect(testInfo.client->ssl), HITLS_MSG_HANDLE_UNEXPECTED_MESSAGE); 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_TRUE(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); FRAME_DeRegCryptMethod(); } /* END_CASE */ /* @ * @test UT_TLS_TLS12_RFC5246_CONSISTENCY_UNEXPECT_RECODETYPE_TC004 * @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 the peer end verification function on the server. Expected result 1 is obtained. * 2. When the client initiates a TLS link application request, construct an APP message and send it to the client in the RECV_SERVER_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_TLS12_RFC5246_CONSISTENCY_UNEXPECT_RECODETYPE_TC004(void) { /* Use the default configuration on the client and server, and disable the peer end verification function on the * server. */ FRAME_Msg frameMsg = { 0 }; FRAME_Type frameType = { 0 }; HandshakeTestInfo testInfo = { 0 }; testInfo.isClient = true; testInfo.state = TRY_RECV_SERVER_HELLO; testInfo.isSupportClientVerify = false; ASSERT_TRUE(DefaultCfgStatusParkWithSuite(&testInfo) == 0); 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); /* When the client initiates a TLS link application request, construct an APP message and send it to the client in * the RECV_SERVER_HELLO message. */ 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); FRAME_DeRegCryptMethod(); } /* END_CASE */ /* @ * @test UT_TLS_TLS12_RFC5246_CONSISTENCY_UNEXPECT_RECODETYPE_TC005 * @title After the link is set up, 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 link request. After the handshake succeeds, construct a serverhello 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_TLS12_RFC5246_CONSISTENCY_UNEXPECT_RECODETYPE_TC005(void) { /* Use the default configuration on the client and server, and disable peer verification on the server. */ FRAME_Init(); HITLS_Config *config = NULL; FRAME_LinkObj *client = NULL; FRAME_LinkObj *server = NULL; FRAME_Msg recvframeMsg = { 0 }; config = HITLS_CFG_NewTLS12Config(); 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, 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 initiates a TLS link request. After the handshake succeeds, construct a serverhello message and send * it to the client. */ ASSERT_EQ(FRAME_CreateConnection(client, server, true, HS_STATE_BUTT), HITLS_SUCCESS); ASSERT_TRUE(clientTlsCtx->state == CM_STATE_TRANSPORTING); FRAME_Msg frameMsg = { 0 }; FRAME_Type frameType = { 0 }; SetFrameType(&frameType, HITLS_VERSION_TLS12, REC_TYPE_HANDSHAKE, SERVER_HELLO, 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); ASSERT_TRUE(FRAME_TransportRecMsg(client->io, sendBuf, sendLen) == HITLS_SUCCESS); FRAME_CleanMsg(&frameType, &frameMsg); memset_s(&frameMsg, sizeof(frameMsg), 0, sizeof(frameMsg)); uint8_t readBuf[READ_BUF_SIZE] = {0}; uint32_t readLen = 0; ASSERT_EQ(HITLS_Read(client->ssl, readBuf, READ_BUF_SIZE, &readLen), HITLS_REC_BAD_RECORD_MAC); 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; ASSERT_EQ(FRAME_ParseMsgHeader(&frameType, sndBuf, sndLen, &frameMsg, &parseLen), 0); ASSERT_TRUE(frameMsg.recType.data == REC_TYPE_ALERT); EXIT: CleanRecordBody(&recvframeMsg); HITLS_CFG_FreeConfig(config); FRAME_FreeLink(client); FRAME_FreeLink(server); } /* END_CASE */ /* @ * @test UT_TLS_TLS12_RFC5246_CONSISTENCY_UNEXPECT_RECODETYPE_TC006 * @title After the link is established, renegotiation is not enabled. The server receives a client hello message and is expected to return an alert message. * @precon nan * @brief 1. Use the default configuration on the client and server. Expected result 1 is obtained. * 2. After the client initiates a TLS link request and handshakes successfully, construct a client hello message and send it to the server. Expected result 2 is displayed. * @expect 1. The initialization is successful. * 2. The server sends an ALERT message. @ */ /* BEGIN_CASE */ void UT_TLS_TLS12_RFC5246_CONSISTENCY_UNEXPECT_RECODETYPE_TC006(void) { /* Use the default configuration on the client and server. */ FRAME_Init(); HITLS_Config *config = NULL; FRAME_LinkObj *client = NULL; FRAME_LinkObj *server = NULL; FRAME_Msg recvframeMsg = { 0 }; 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_Ctx *clientTlsCtx = FRAME_GetTlsCtx(client); ASSERT_TRUE(clientTlsCtx->state == CM_STATE_IDLE); /* After the client initiates a TLS link request and handshakes successfully, construct a client hello message and * send it to the server. */ ASSERT_EQ(FRAME_CreateConnection(client, server, true, HS_STATE_BUTT), HITLS_SUCCESS); ASSERT_TRUE(clientTlsCtx->state == CM_STATE_TRANSPORTING); FRAME_Msg frameMsg = { 0 }; FRAME_Type frameType = { 0 }; SetFrameType(&frameType, HITLS_VERSION_TLS12, REC_TYPE_HANDSHAKE, CLIENT_HELLO, 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); ASSERT_TRUE(FRAME_TransportRecMsg(server->io, sendBuf, sendLen) == HITLS_SUCCESS); FRAME_CleanMsg(&frameType, &frameMsg); memset_s(&frameMsg, sizeof(frameMsg), 0, sizeof(frameMsg)); uint8_t readBuf[READ_BUF_SIZE] = {0}; uint32_t readLen = 0; ASSERT_EQ(HITLS_Read(server->ssl, readBuf, READ_BUF_SIZE, &readLen), HITLS_REC_INVALID_PROTOCOL_VERSION); 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; ASSERT_EQ(FRAME_ParseMsgHeader(&frameType, sndBuf, sndLen, &frameMsg, &parseLen), 0); ASSERT_TRUE(frameMsg.recType.data == REC_TYPE_ALERT); EXIT: CleanRecordBody(&recvframeMsg); HITLS_CFG_FreeConfig(config); FRAME_FreeLink(client); FRAME_FreeLink(server); } /* END_CASE */ /* @ * @test UT_TLS_TLS12_RFC5246_CONSISTENCY_UNEXPECT_RECODETYPE_TC007 * @title After initialization, 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 link 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 an ALERT message. @ */ /* BEGIN_CASE */ void UT_TLS_TLS12_RFC5246_CONSISTENCY_UNEXPECT_RECODETYPE_TC007(void) { /* Use the default configuration on the client and server, and disable the peer end verification function on the * server. Expected result 1 is obtained. */ FRAME_Msg parsedAlert = { 0 }; HandshakeTestInfo testInfo = { 0 }; testInfo.isClient = false; testInfo.state = TRY_RECV_CLIENT_HELLO; testInfo.isSupportClientVerify = false; ASSERT_TRUE(DefaultCfgStatusParkWithSuite(&testInfo) == 0); 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); /* When the client initiates a TLS link application request, construct an APP message and send it to the server in * the RECV_CLIENT_HELLO message on the server. */ 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); FRAME_DeRegCryptMethod(); } /* END_CASE */ /* @ * @test UT_TLS_TLS12_RFC5246_CONSISTENCY_HANDSHAKE_RECV_APPDATA_TC001 * @title Before the first handshake, no app message is received. * @precon nan * @brief During the first handshake, the client/server receives the app message when expecting to receive the finish message. The expected handshake fails and the handshake is interrupted. * @expect 1. Return a failure message and interrupt the handshake. @ */ /* BEGIN_CASE */ void UT_TLS_TLS12_RFC5246_CONSISTENCY_HANDSHAKE_RECV_APPDATA_TC001(int isClient) { FRAME_Msg frameMsg = { 0 }; FRAME_Type frameType = { 0 }; HandshakeTestInfo testInfo = { 0 }; testInfo.isClient = isClient; testInfo.state = TRY_RECV_FINISH; testInfo.isSupportClientVerify = true; ASSERT_TRUE(DefaultCfgStatusParkWithSuite(&testInfo) == 0); FrameUioUserData *ioUserData = isClient ? BSL_UIO_GetUserData(testInfo.client->io) : BSL_UIO_GetUserData(testInfo.server->io); uint8_t data[MAX_RECORD_LENTH] = {0}; /* application data record header construction 17 - type is 0x17 (application data) 03 03 - protocol version is "3,3" (TLS 1.2) 00 02 - 2 bytes of application data follows */ uint8_t appdataRecordHeader[] = {0x17, 0x03, 0x03, 0x00, 0x02, 0x01, 0x01}; ASSERT_EQ(memcpy_s(data, MAX_RECORD_LENTH, appdataRecordHeader, sizeof(appdataRecordHeader)), EOK); ASSERT_EQ(memcpy_s(data + sizeof(appdataRecordHeader), MAX_RECORD_LENTH - sizeof(appdataRecordHeader), ioUserData->recMsg.msg, ioUserData->recMsg.len), EOK); uint32_t constructLen = ioUserData->recMsg.len + sizeof(appdataRecordHeader); ASSERT_EQ(memcpy_s(ioUserData->recMsg.msg, MAX_RECORD_LENTH, data, constructLen), EOK); ioUserData->recMsg.len = constructLen; /* During the first handshake, the client/server receives the app message when expecting to receive the finish * message. */ ASSERT_EQ(FRAME_CreateConnection(testInfo.client, testInfo.server, isClient, HS_STATE_BUTT), HITLS_REC_BAD_RECORD_MAC); 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_TLS12_RFC5246_CONSISTENCY_HELLO_REQUEST_TC001 * @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. @ */ /* BEGIN_CASE */ void UT_TLS_TLS12_RFC5246_CONSISTENCY_HELLO_REQUEST_TC001(void) { HandshakeTestInfo testInfo = { 0 }; testInfo.state = TLS_IDLE; testInfo.isSupportExtendMasterSecret = true; testInfo.isClient = true; FRAME_Init(); /* Use the configuration items to configure the client and server. */ testInfo.config = HITLS_CFG_NewTLS12Config(); ASSERT_TRUE(testInfo.config != NULL); uint16_t cipherSuits[] = {HITLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384}; 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; 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); ASSERT_EQ(HITLS_Accept(testInfo.server->ssl), HITLS_REC_NORMAL_RECV_BUF_EMPTY); // Construct a HelloRequest message and send it to the client. ASSERT_TRUE(SendHelloReq(testInfo.server->ssl) == HITLS_SUCCESS); ASSERT_TRUE(FRAME_TrasferMsgBetweenLink(testInfo.server, testInfo.client) == HITLS_SUCCESS); ASSERT_TRUE(testInfo.client->ssl != NULL); ASSERT_EQ(HITLS_Connect(testInfo.client->ssl), HITLS_REC_NORMAL_RECV_BUF_EMPTY); ASSERT_TRUE(testInfo.client->ssl->hsCtx->state == TRY_RECV_SERVER_HELLO); EXIT: HITLS_CFG_FreeConfig(testInfo.config); FRAME_FreeLink(testInfo.client); FRAME_FreeLink(testInfo.server); } /* END_CASE */ /* @ * @test UT_TLS_TLS12_RFC5246_CONSISTENCY_HELLO_REQUEST_TC002 * @title The server sends a Hello Request message after the client sends the client hello message. * @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. @ */ /* BEGIN_CASE */ void UT_TLS_TLS12_RFC5246_CONSISTENCY_HELLO_REQUEST_TC002(void) { /* Use the configuration items to configure the client and server. */ HandshakeTestInfo testInfo = { 0 }; testInfo.state = TRY_SEND_CLIENT_HELLO; testInfo.isSupportExtendMasterSecret = true; testInfo.isClient = true; ASSERT_TRUE(DefaultCfgStatusParkWithSuite(&testInfo) == HITLS_SUCCESS); ASSERT_TRUE(testInfo.client->ssl != NULL); ASSERT_EQ(HITLS_Connect(testInfo.client->ssl), HITLS_REC_NORMAL_RECV_BUF_EMPTY); ASSERT_TRUE(FRAME_TrasferMsgBetweenLink(testInfo.client, testInfo.server) == HITLS_SUCCESS); /* Construct a HelloRequest message and send it to the client. */ ASSERT_TRUE(SendHelloReq(testInfo.server->ssl) == HITLS_SUCCESS); ASSERT_TRUE(FRAME_TrasferMsgBetweenLink(testInfo.server, testInfo.client) == HITLS_SUCCESS); ASSERT_TRUE(testInfo.client->ssl != NULL); ASSERT_EQ(HITLS_Connect(testInfo.client->ssl), HITLS_REC_NORMAL_RECV_BUF_EMPTY); HITLS_Ctx *clientTlsCtx = FRAME_GetTlsCtx(testInfo.client); ASSERT_EQ(clientTlsCtx->state, CM_STATE_HANDSHAKING); ASSERT_EQ(clientTlsCtx->hsCtx->state, TRY_RECV_SERVER_HELLO); EXIT: HITLS_CFG_FreeConfig(testInfo.config); FRAME_FreeLink(testInfo.client); FRAME_FreeLink(testInfo.server); FRAME_DeRegCryptMethod(); } /* END_CASE */ /* @ * @test UT_TLS_TLS12_RFC5246_CONSISTENCY_HELLO_REQUEST_TC003 * @title The server sends a Hello Request message when preparing to send CCS messages. * @precon nan * @brief 1. Use configuration items to configure the client and server. Expected result 1 is obtained. * 2. The client invokes HITLS_Connect in the Try_SEND_FINISH phase. Expected result 2 is obtained. * 3. Construct a HelloRequest message and send it to the client. The client invokes HITLS_Connect to receive the message. Expected result 3 is obtained. * @expect 1. The initialization is successful. * 2. The client sends a FINISH message, changes the status to TRY_RECV_NEW_SESSION_TICKET, and returns HITLS_REC_NORMAL_RECV_BUF_EMPTY. * 3. After receiving the HelloRequest message, the client ignores the message and stays in the TRY_RECV_NEW_SESSION_TICKET state. @ */ /* BEGIN_CASE */ void UT_TLS_TLS12_RFC5246_CONSISTENCY_HELLO_REQUEST_TC003(void) { /* Use configuration items to configure the client and server. */ HandshakeTestInfo testInfo = { 0 }; testInfo.state = TRY_SEND_FINISH; testInfo.isSupportExtendMasterSecret = true; testInfo.isClient = true; ASSERT_TRUE(DefaultCfgStatusParkWithSuite(&testInfo) == HITLS_SUCCESS); /* The client invokes HITLS_Connect in the Try_SEND_FINISH phase. */ ASSERT_TRUE(testInfo.client->ssl != NULL); ASSERT_EQ(HITLS_Connect(testInfo.client->ssl), HITLS_REC_NORMAL_RECV_BUF_EMPTY); ASSERT_TRUE(FRAME_TrasferMsgBetweenLink(testInfo.client, testInfo.server) == HITLS_SUCCESS); /* Construct a HelloRequest message and send it to the client. The client invokes HITLS_Connect to receive the * message. */ ASSERT_TRUE(SendHelloReq(testInfo.server->ssl) == HITLS_SUCCESS); ASSERT_TRUE(FRAME_TrasferMsgBetweenLink(testInfo.server, testInfo.client) == HITLS_SUCCESS); ASSERT_TRUE(testInfo.client->ssl != NULL); ASSERT_EQ(HITLS_Connect(testInfo.client->ssl), HITLS_REC_NORMAL_RECV_BUF_EMPTY); HITLS_Ctx *clientTlsCtx = FRAME_GetTlsCtx(testInfo.client); ASSERT_EQ(clientTlsCtx->state, CM_STATE_HANDSHAKING); ASSERT_EQ(clientTlsCtx->hsCtx->state, TRY_RECV_NEW_SESSION_TICKET); EXIT: HITLS_CFG_FreeConfig(testInfo.config); FRAME_FreeLink(testInfo.client); FRAME_FreeLink(testInfo.server); FRAME_DeRegCryptMethod(); } /* END_CASE */ /* @ * @test UT_TLS_TLS12_RFC5246_CONSISTENCY_HELLO_REQUEST_TC004 * @title The server sends a hello request when the link status is CM_STATE_TRANSPORTING. * @precon nan * @brief 1. Use the configuration items to configure the client and server. Expected result 1 is obtained. * 2. The server sends a hello request to the client. Expected result 2 is obtained. * @expect 1. The initialization is successful. * 2. The client sends the ALERT_NO_RENEGOTIATION message successfully, but the client can continue sending and receiving data. @ */ /* BEGIN_CASE */ void UT_TLS_TLS12_RFC5246_CONSISTENCY_HELLO_REQUEST_TC004(void) { FRAME_Init(); HITLS_Config *config = NULL; FRAME_LinkObj *client = NULL; FRAME_LinkObj *server = NULL; FRAME_Msg recvframeMsg = { 0 }; /* Use the configuration items to configure the client and server. */ 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_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(clientTlsCtx->state == CM_STATE_TRANSPORTING); /* The server sends a hello request to the client. */ ASSERT_TRUE(SendHelloReq(server->ssl) == HITLS_SUCCESS); ASSERT_TRUE(FRAME_TrasferMsgBetweenLink(server, client) == HITLS_SUCCESS); uint8_t readBuf[READ_BUF_SIZE] = {0}; uint32_t readLen = 0; FrameUioUserData *ioUserData = BSL_UIO_GetUserData(client->io); ioUserData->sndMsg.len = 1; ASSERT_TRUE(HITLS_Read(clientTlsCtx, readBuf, READ_BUF_SIZE, &readLen) == HITLS_REC_NORMAL_IO_BUSY); ASSERT_TRUE(clientTlsCtx->state == CM_STATE_ALERTING); ioUserData->sndMsg.len = 0; ASSERT_EQ(HITLS_Read(clientTlsCtx, readBuf, READ_BUF_SIZE, &readLen), HITLS_REC_NORMAL_RECV_BUF_EMPTY); ASSERT_TRUE(clientTlsCtx->state == CM_STATE_TRANSPORTING); ASSERT_TRUE(FRAME_TrasferMsgBetweenLink(client, server) == HITLS_SUCCESS); ASSERT_EQ(HITLS_Read(server->ssl, readBuf, READ_BUF_SIZE, &readLen), HITLS_REC_NORMAL_RECV_BUF_EMPTY); ASSERT_TRUE(server->ssl->state == CM_STATE_TRANSPORTING); uint8_t data[] = "Hello World"; uint32_t writeLen; ASSERT_EQ(HITLS_Write(server->ssl, data, sizeof(data), &writeLen), HITLS_SUCCESS); ASSERT_TRUE(FRAME_TrasferMsgBetweenLink(server, client) == HITLS_SUCCESS); ASSERT_TRUE(HITLS_Read(clientTlsCtx, readBuf, READ_BUF_SIZE, &readLen) == HITLS_SUCCESS); ASSERT_TRUE(readLen == sizeof(data) && memcmp(data, readBuf, readLen) == 0); ASSERT_TRUE(HITLS_Close(clientTlsCtx) == HITLS_SUCCESS); ASSERT_TRUE(clientTlsCtx->state == CM_STATE_CLOSED); EXIT: CleanRecordBody(&recvframeMsg); HITLS_CFG_FreeConfig(config); FRAME_FreeLink(client); FRAME_FreeLink(server); } /* END_CASE */ /* @ * @test UT_TLS_TLS12_RFC5246_CONSISTENCY_HELLO_REQUEST_TC005 * @title The server sends a hello request when the link status is CM_STATE_RENEGOTIATION. * @precon nan * @brief 1. Use the configuration items to configure the client and server to support renegotiation. Expected result 1 is displayed. * 2. After the link is established, the client sends a Hello Request message. The client receives the renegotiation request message and is in the renegotiation state. At this time, the server sends a Hello Request message again. Expected result 2 is obtained. * @expect 1. The initialization is successful. * 2. The expected message is sent successfully but is ignored. @ */ /* BEGIN_CASE */ void UT_TLS_TLS12_RFC5246_CONSISTENCY_HELLO_REQUEST_TC005(void) { FRAME_Init(); HITLS_Config *config = NULL; FRAME_LinkObj *client = NULL; FRAME_LinkObj *server = NULL; FRAME_Msg recvframeMsg = { 0 }; /* Use the configuration items to configure the client and server to support renegotiation. */ config = HITLS_CFG_NewTLS12Config(); ASSERT_TRUE(config != NULL); 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); ASSERT_TRUE(clientTlsCtx->state == CM_STATE_IDLE); ASSERT_TRUE(FRAME_CreateConnection(client, server, true, HS_STATE_BUTT) == HITLS_SUCCESS); ASSERT_TRUE(clientTlsCtx->state == CM_STATE_TRANSPORTING); /* After the link is established, the client sends a Hello Request message. The client receives the renegotiation * request message and is in the renegotiation state. At this time, the server sends a Hello Request message again. */ ASSERT_TRUE(SendHelloReq(server->ssl) == HITLS_SUCCESS); ASSERT_TRUE(FRAME_TrasferMsgBetweenLink(server, client) == HITLS_SUCCESS); uint8_t readBuf[READ_BUF_SIZE] = {0}; uint32_t readLen = 0; FrameUioUserData *ioUserData = BSL_UIO_GetUserData(client->io); ioUserData->sndMsg.len = 1; ASSERT_TRUE(HITLS_Read(clientTlsCtx, readBuf, READ_BUF_SIZE, &readLen) == HITLS_REC_NORMAL_IO_BUSY); ASSERT_EQ(clientTlsCtx->state, CM_STATE_RENEGOTIATION); ioUserData->sndMsg.len = 0; ASSERT_EQ(HITLS_Read(clientTlsCtx, readBuf, READ_BUF_SIZE, &readLen), HITLS_REC_NORMAL_RECV_BUF_EMPTY); ASSERT_EQ(clientTlsCtx->state, CM_STATE_RENEGOTIATION); ASSERT_TRUE(client->ssl->hsCtx->state = TRY_SEND_CLIENT_HELLO); ASSERT_TRUE(SendHelloReq(server->ssl) == HITLS_SUCCESS); ASSERT_TRUE(FRAME_TrasferMsgBetweenLink(server, client) == HITLS_SUCCESS); ASSERT_EQ(HITLS_Connect(client->ssl), HITLS_REC_NORMAL_IO_BUSY); ASSERT_TRUE(client->ssl->hsCtx->state = TRY_RECV_SERVER_HELLO); EXIT: CleanRecordBody(&recvframeMsg); HITLS_CFG_FreeConfig(config); FRAME_FreeLink(client); FRAME_FreeLink(server); } /* END_CASE */ /* @ * @test UT_TLS_TLS12_RFC5246_CONSISTENCY_HELLO_REQUEST_TC006 * @title Enable the client and server to support renegotiation. After the connection between the client and server is established, the client and server send a Hello Request message. * @precon nan * @brief 1. Configure the client and server to support renegotiation. Expected result 1 is displayed. * 2. After the link is established, the server sends the Hello Request message successfully. * @expect 1. The initialization is successful. * 2. The client enters the renegotiation state and sends client hello. @ */ /* BEGIN_CASE */ void UT_TLS_TLS12_RFC5246_CONSISTENCY_HELLO_REQUEST_TC006(void) { FRAME_Init(); HITLS_Config *config = NULL; FRAME_LinkObj *client = NULL; FRAME_LinkObj *server = NULL; FRAME_Msg recvframeMsg = { 0 }; /* Configure the client and server to support renegotiation. */ config = HITLS_CFG_NewTLS12Config(); 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); ASSERT_TRUE(clientTlsCtx->state == CM_STATE_IDLE); ASSERT_TRUE(FRAME_CreateConnection(client, server, true, HS_STATE_BUTT) == HITLS_SUCCESS); ASSERT_TRUE(clientTlsCtx->state == CM_STATE_TRANSPORTING); /* After the link is established, the server sends the Hello Request message successfully. */ ASSERT_TRUE(SendHelloReq(server->ssl) == HITLS_SUCCESS); ASSERT_TRUE(FRAME_TrasferMsgBetweenLink(server, client) == HITLS_SUCCESS); uint8_t readBuf[READ_BUF_SIZE] = {0}; uint32_t readLen = 0; FrameUioUserData *ioUserData = BSL_UIO_GetUserData(client->io); ioUserData->sndMsg.len = 1; ASSERT_TRUE(HITLS_Read(clientTlsCtx, readBuf, READ_BUF_SIZE, &readLen) == HITLS_REC_NORMAL_IO_BUSY); ASSERT_EQ(clientTlsCtx->state, CM_STATE_RENEGOTIATION); ioUserData->sndMsg.len = 0; ASSERT_EQ(HITLS_Read(clientTlsCtx, readBuf, READ_BUF_SIZE, &readLen), HITLS_REC_NORMAL_RECV_BUF_EMPTY); ASSERT_EQ(clientTlsCtx->state, CM_STATE_RENEGOTIATION); ASSERT_TRUE(client->ssl->hsCtx->state = TRY_SEND_CLIENT_HELLO); EXIT: CleanRecordBody(&recvframeMsg); HITLS_CFG_FreeConfig(config); FRAME_FreeLink(client); FRAME_FreeLink(server); } /* END_CASE */ /* @ * @test UT_TLS_TLS12_RFC5246_CONSISTENCY_HELLO_REQUEST_TC007 * @title The server receives a Hello Request message after sending the server hello done message. * @precon nan * @brief 1. Use the default configuration items to configure the client and server. Expected result 1 is obtained. * 2. After sending a Server Hello Done message, the server receives a Hello Request message. Expected result 2 is obtained. * @expect 1. The initialization is successful. * 2. The server sends an ALERT. The level is ALERT_LEVEL_FATAL, and the description is ALERT_UNEXPECTED_MESSAGE. @ */ /* BEGIN_CASE */ void UT_TLS_TLS12_RFC5246_CONSISTENCY_HELLO_REQUEST_TC007(void) { /* Use the default configuration items to configure the client and server. */ HandshakeTestInfo testInfo = { 0 }; FRAME_Msg parsedAlert = { 0 }; testInfo.state = TRY_SEND_SERVER_HELLO_DONE; testInfo.isSupportExtendMasterSecret = true; testInfo.isClient = false; ASSERT_TRUE(DefaultCfgStatusParkWithSuite(&testInfo) == HITLS_SUCCESS); ASSERT_TRUE(testInfo.server->ssl != NULL); ASSERT_EQ(HITLS_Accept(testInfo.server->ssl), HITLS_REC_NORMAL_RECV_BUF_EMPTY); ASSERT_TRUE(FRAME_TrasferMsgBetweenLink(testInfo.server, testInfo.client) == HITLS_SUCCESS); /* After sending a Server Hello Done message, the server receives a Hello Request message. */ ASSERT_TRUE(SendHelloReq(testInfo.client->ssl) == HITLS_SUCCESS); ASSERT_TRUE(FRAME_TrasferMsgBetweenLink(testInfo.client, testInfo.server) == HITLS_SUCCESS); ASSERT_TRUE(testInfo.server->ssl != NULL); ASSERT_EQ(HITLS_Accept(testInfo.server->ssl), HITLS_MSG_HANDLE_UNEXPECTED_MESSAGE); FrameUioUserData *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_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_UNEXPECTED_MESSAGE); EXIT: FRAME_CleanNonHsRecord(REC_TYPE_ALERT, &parsedAlert); HITLS_CFG_FreeConfig(testInfo.config); FRAME_FreeLink(testInfo.client); FRAME_FreeLink(testInfo.server); FRAME_DeRegCryptMethod(); } /* END_CASE */ /* @ * @test UT_TLS_TLS12_RFC5246_CONSISTENCY_HELLO_REQUEST_TC008 * @title The server sends a Hello Request message after sending the finish message. The renegotiation is successful. The server sends a Hello Request message again. The renegotiation is successful. * @precon nan * @brief 1. Configure the client and server to support renegotiation. Expected result 1 is displayed. * 2. Send a Hello Request message after the server sends a finish message. Expected result 2 is obtained. * 3. The server sends a Hello Request message again. Expected result 3 is obtained. * @expect 1. The initialization is successful. * 2. The renegotiation succeeds. * 3. The client ignores the Hello Request message and continues the renegotiation. @ */ /* BEGIN_CASE */ void UT_TLS_TLS12_RFC5246_CONSISTENCY_HELLO_REQUEST_TC008(void) { HandshakeTestInfo testInfo = { 0 }; testInfo.state = TRY_RECV_FINISH; testInfo.isSupportExtendMasterSecret = true; testInfo.isClient = true; FRAME_Init(); /* Configure the client and server to support renegotiation. */ testInfo.config = HITLS_CFG_NewTLS12Config(); ASSERT_TRUE(testInfo.config != NULL); testInfo.config->isSupportExtendMasterSecret = testInfo.isSupportExtendMasterSecret; testInfo.config->isSupportClientVerify = testInfo.isSupportClientVerify; testInfo.config->isSupportNoClientCert = testInfo.isSupportNoClientCert; testInfo.config->isSupportRenegotiation = true; 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); ASSERT_TRUE(FRAME_CreateConnection(testInfo.client, testInfo.server, testInfo.isClient, testInfo.state) == HITLS_SUCCESS); ASSERT_TRUE(testInfo.client->ssl != NULL); ASSERT_EQ(HITLS_Connect(testInfo.client->ssl), HITLS_SUCCESS); HITLS_Ctx *clientTlsCtx = FRAME_GetTlsCtx(testInfo.client); ASSERT_EQ(clientTlsCtx->state, CM_STATE_TRANSPORTING); /* Send a Hello Request message after the server sends a finish message. */ ASSERT_TRUE(SendHelloReq(testInfo.server->ssl) == HITLS_SUCCESS); ASSERT_TRUE(FRAME_TrasferMsgBetweenLink(testInfo.server, testInfo.client) == HITLS_SUCCESS); uint8_t readBuf[READ_BUF_SIZE] = {0}; uint32_t readLen = 0; FrameUioUserData *ioUserData = BSL_UIO_GetUserData(testInfo.client->io); ioUserData->sndMsg.len = 1; ASSERT_TRUE(HITLS_Read(clientTlsCtx, readBuf, READ_BUF_SIZE, &readLen) == HITLS_REC_NORMAL_IO_BUSY); ASSERT_EQ(clientTlsCtx->state, CM_STATE_RENEGOTIATION); ASSERT_TRUE(testInfo.client->ssl->hsCtx->state = TRY_SEND_CLIENT_HELLO); /* The server sends a Hello Request message again. */ ASSERT_TRUE(SendHelloReq(testInfo.server->ssl) == HITLS_SUCCESS); ASSERT_TRUE(FRAME_TrasferMsgBetweenLink(testInfo.server, testInfo.client) == HITLS_SUCCESS); ASSERT_EQ(HITLS_Connect(testInfo.client->ssl), HITLS_REC_NORMAL_IO_BUSY); ASSERT_TRUE(testInfo.client->ssl->hsCtx->state = TRY_RECV_SERVER_HELLO); EXIT: HITLS_CFG_FreeConfig(testInfo.config); FRAME_FreeLink(testInfo.client); FRAME_FreeLink(testInfo.server); } /* END_CASE */ /* @ * @test UT_TLS_TLS12_RFC5246_CONSISTENCY_CLIENT_HELLO_VERSION_TC001 * @title Check the TLS protocol version carried in the clientHello message. * @precon nan * @brief 1. Use configuration items to configure the client and server. Set the maximum version number of the client to TLS1.2 and the minimum version number to TLS1.1. Expected result 1 is obtained. * 2. Obtain and parse the client Hello message. Expected result 2 is obtained. * @expect 1. The initialization is successful. * 2. The protocol version carried in the client Hello message is TLS1.2. @ */ /* BEGIN_CASE */ void UT_TLS_TLS12_RFC5246_CONSISTENCY_CLIENT_HELLO_VERSION_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; testInfo.isSupportClientVerify = true; testInfo.isSupportNoClientCert = false; FRAME_Init(); /* Use configuration items to configure the client and server. Set the maximum version number of the client to * TLS1.2 and the minimum version number to TLS1.1. */ testInfo.config = HITLS_CFG_NewTLS12Config(); ASSERT_TRUE(testInfo.config != NULL); testInfo.config->isSupportExtendMasterSecret = testInfo.isSupportExtendMasterSecret; testInfo.config->isSupportClientVerify = testInfo.isSupportClientVerify; testInfo.config->isSupportNoClientCert = testInfo.isSupportNoClientCert; testInfo.config->minVersion = HITLS_VERSION_TLS11; testInfo.client = FRAME_CreateLink(testInfo.config, BSL_UIO_TCP); ASSERT_TRUE(testInfo.client != NULL); testInfo.config->minVersion = HITLS_VERSION_TLS12; testInfo.server = FRAME_CreateLink(testInfo.config, BSL_UIO_TCP); ASSERT_TRUE(testInfo.server != NULL); ASSERT_TRUE(FRAME_CreateConnection(testInfo.client, testInfo.server, testInfo.isClient, testInfo.state) == HITLS_SUCCESS); /* Obtain and parse the client Hello message. */ FrameUioUserData *ioUserData = BSL_UIO_GetUserData(testInfo.server->io); uint8_t *recvBuf = ioUserData->recMsg.msg; uint32_t recvLen = ioUserData->recMsg.len; uint32_t parseLen = 0; frameType.versionType = HITLS_VERSION_TLS12; 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; ASSERT_TRUE(clientMsg->version.data == HITLS_VERSION_TLS12); EXIT: FRAME_CleanMsg(&frameType, &frameMsg); HITLS_CFG_FreeConfig(testInfo.config); FRAME_FreeLink(testInfo.client); FRAME_FreeLink(testInfo.server); } /* END_CASE */ /* @ * @test UT_TLS_TLS12_RFC5246_CONSISTENCY_NOT_SUPPORT_SERVER_VERSION_TC001 * @title The client does not support the version selected by the server. * @precon nan * @brief 1. Use the configuration items to configure the client and server. Expected result 1 is obtained. * 2. After receiving the Server Hello message, the client changes the TLS version field in the serverhello message to DTLS1.2 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. The level is ALERT_ LEVEL_FATAL and the description is ALERT_PROTOCOL_VERSION. @ */ /* BEGIN_CASE */ void UT_TLS_TLS12_RFC5246_CONSISTENCY_NOT_SUPPORT_SERVER_VERSION_TC001(void) { /* Use the configuration items to configure the client and server. */ 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(DefaultCfgStatusPark(&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; SetFrameType(&frameType, HITLS_VERSION_TLS12, REC_TYPE_HANDSHAKE, SERVER_HELLO, HITLS_KEY_EXCH_ECDHE); ASSERT_TRUE(FRAME_ParseMsg(&frameType, recvBuf, recvLen, &frameMsg, &parseLen) == HITLS_SUCCESS); /* After receiving the Server Hello message, the client changes the TLS version field in the serverhello message to * DTLS1.2 and sends the message to the client. */ FRAME_ServerHelloMsg *serverMsg = &frameMsg.body.hsMsg.body.serverHello; serverMsg->version.data = HITLS_VERSION_DTLS12; 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); ASSERT_EQ(HITLS_Connect(testInfo.client->ssl), HITLS_MSG_HANDLE_UNSUPPORT_VERSION); 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_TRUE(alertMsg->alertDescription.data == ALERT_PROTOCOL_VERSION); 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_TLS12_RFC5246_CONSISTENCY_SERVER_CHOSE_VERSION_TC001 * @title Check the TLS protocol version carried in the serverHello message. * @brief 1. Use the configuration items to configure the client and server. Set the maximum version number of the client to TLS1.3 and the minimum version number to TLS1.1, * Set the maximum version number of the server to TLS1.2 and the minimum version number to TLS1.1. Expected result 1 is obtained. * 2. Obtain and parse the server Hello message. Expected result 2 is obtained. * @expect 1. The initialization is successful. * 2. The protocol version carried in the server Hello message is TLS1.2. @ */ /* BEGIN_CASE */ void UT_TLS_TLS12_RFC5246_CONSISTENCY_SERVER_CHOSE_VERSION_TC001(void) { /* Use the configuration items to configure the client and server. Set the maximum version number of the client to TLS1.3 and the minimum version number to TLS1.1; Set the maximum version number of the server to TLS1.2 and the minimum version number to TLS1.1. */ HandshakeTestInfo testInfo = { 0 }; FRAME_Msg frameMsg = { 0 }; FRAME_Type frameType = { 0 }; testInfo.state = TRY_RECV_SERVER_HELLO; testInfo.isSupportExtendMasterSecret = true; testInfo.isClient = true; testInfo.isSupportClientVerify = true; testInfo.isSupportNoClientCert = false; FRAME_Init(); testInfo.config = HITLS_CFG_NewTLSConfig(); ASSERT_TRUE(testInfo.config != NULL); testInfo.config->isSupportExtendMasterSecret = testInfo.isSupportExtendMasterSecret; testInfo.config->isSupportClientVerify = testInfo.isSupportClientVerify; testInfo.config->isSupportNoClientCert = testInfo.isSupportNoClientCert; testInfo.config->maxVersion = HITLS_VERSION_TLS13; testInfo.config->minVersion = HITLS_VERSION_TLS11; testInfo.client = FRAME_CreateLink(testInfo.config, BSL_UIO_TCP); ASSERT_TRUE(testInfo.client != NULL); testInfo.config->maxVersion = HITLS_VERSION_TLS12; testInfo.config->minVersion = HITLS_VERSION_TLS11; testInfo.server = FRAME_CreateLink(testInfo.config, BSL_UIO_TCP); ASSERT_TRUE(testInfo.server != NULL); ASSERT_TRUE(FRAME_CreateConnection(testInfo.client, testInfo.server, testInfo.isClient, testInfo.state) == HITLS_SUCCESS); /* Obtain and parse the server Hello message. */ FrameUioUserData *ioUserData = BSL_UIO_GetUserData(testInfo.client->io); uint8_t *recvBuf = ioUserData->recMsg.msg; uint32_t recvLen = ioUserData->recMsg.len; uint32_t parseLen = 0; frameType.versionType = HITLS_VERSION_TLS12; 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->version.data == HITLS_VERSION_TLS12); EXIT: FRAME_CleanMsg(&frameType, &frameMsg); HITLS_CFG_FreeConfig(testInfo.config); FRAME_FreeLink(testInfo.client); FRAME_FreeLink(testInfo.server); } /* END_CASE */ /* @ * @test UT_TLS_TLS12_RFC5246_CONSISTENCY_DEFAULT_SIGNATURE_EXTENSION_TC001 * @title HITLS If no signature algorithm is specified, select the default algorithm and check whether the extension is carried. * @precon nan * @brief 1. Use the configuration items to configure the client and server. Expected result 1 is obtained. * 2. Check whether the client Clienet Hello message carries the signature algorithm extension. * @expect 1. The initialization is successful. * 2. Expected carrying expansion @ */ /* BEGIN_CASE */ void UT_TLS_TLS12_RFC5246_CONSISTENCY_DEFAULT_SIGNATURE_EXTENSION_TC001(void) { /* Use the configuration items to configure the client and server. */ 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(DefaultCfgStatusPark(&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_TLS12; 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); /* Check whether the client Clienet Hello message carries the signature algorithm extension. */ FRAME_ClientHelloMsg *clientMsg = &frameMsg.body.hsMsg.body.clientHello; ASSERT_TRUE(clientMsg->signatureAlgorithms.exState == INITIAL_FIELD); ASSERT_TRUE(&frameMsg.body.handshakeMsg.body.clientHello.extension.flag.haveSignatureAlgorithms); 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_TLS12_RFC5246_CONSISTENCY_CLIENT_HELLO_WITHOUT_SIGNATURE_TC001 * @title Default processing logic of the signature algorithm * @precon nan * @brief 1. Use configuration items to configure the client and server, and set the client and service cipher suite to HITLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256. Expected result 1 is obtained. * 2. Modify the client hello message so that the message does not carry the signature algorithm extension. Then, the link is established. Expected result 2 is obtained. * @expect 1. The initialization is successful. * 2. The signature algorithm in the server key exchange message sent by the server is CERT_SIG_SCHEME_ECDSA_SHA1. @ */ /* BEGIN_CASE */ void UT_TLS_TLS12_RFC5246_CONSISTENCY_CLIENT_HELLO_WITHOUT_SIGNATURE_TC001(void) { /* Use configuration items to configure the client and server, and set the client and service cipher suite to * HITLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256. */ HandshakeTestInfo testInfo = { 0 }; FRAME_Msg frameMsg = { 0 }; FRAME_Type frameType = { 0 }; testInfo.state = TRY_RECV_CLIENT_HELLO; testInfo.isSupportExtendMasterSecret = true; testInfo.isClient = false; FRAME_Init(); testInfo.config = HITLS_CFG_NewTLS12Config(); ASSERT_TRUE(testInfo.config != NULL); uint16_t cipherSuite[] = {HITLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256}; ASSERT_EQ(HITLS_CFG_SetCipherSuites(testInfo.config, cipherSuite, sizeof(cipherSuite) / sizeof(uint16_t)), HITLS_SUCCESS); testInfo.config->isSupportExtendMasterSecret = testInfo.isSupportExtendMasterSecret; testInfo.config->isSupportClientVerify = testInfo.isSupportClientVerify; testInfo.config->isSupportNoClientCert = testInfo.isSupportNoClientCert; ASSERT_TRUE(StatusPark(&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_TLS12; 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); /* Modify the client hello message so that the message does not carry the signature algorithm extension. Then, the * link is established. */ FRAME_ClientHelloMsg *clientMsg = &frameMsg.body.hsMsg.body.clientHello; clientMsg->signatureAlgorithms.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(testInfo.server->io, sendBuf, sendLen) == HITLS_SUCCESS); FRAME_CleanMsg(&frameType, &frameMsg); memset_s(&frameMsg, sizeof(frameMsg), 0, sizeof(frameMsg)); testInfo.state = TRY_RECV_SERVER_KEY_EXCHANGE; testInfo.isClient = true; ASSERT_EQ(FRAME_CreateConnection(testInfo.client, testInfo.server, testInfo.isClient, testInfo.state), HITLS_SUCCESS); ASSERT_EQ(testInfo.client->ssl->hsCtx->state, TRY_RECV_SERVER_KEY_EXCHANGE); FrameUioUserData *ioUserData2 = BSL_UIO_GetUserData(testInfo.client->io); uint8_t *recvBuf2 = ioUserData2->recMsg.msg; uint32_t recvLen2 = ioUserData2->recMsg.len; ASSERT_TRUE(recvLen != 0); frameType.versionType = HITLS_VERSION_TLS12; frameType.recordType = REC_TYPE_HANDSHAKE; frameType.handshakeType = SERVER_KEY_EXCHANGE; frameType.keyExType = HITLS_KEY_EXCH_ECDHE; ASSERT_TRUE(FRAME_ParseMsg(&frameType, recvBuf2, recvLen2, &frameMsg, &parseLen) == HITLS_SUCCESS); FRAME_ServerKeyExchangeMsg *serverMsg = &frameMsg.body.hsMsg.body.serverKeyExchange; ASSERT_EQ(serverMsg->keyEx.ecdh.signAlgorithm.data, CERT_SIG_SCHEME_ECDSA_SHA1); EXIT: FRAME_CleanMsg(&frameType, &frameMsg); HITLS_CFG_FreeConfig(testInfo.config); FRAME_FreeLink(testInfo.client); FRAME_FreeLink(testInfo.server); } /* END_CASE */ /* @ * @test UT_TLS_TLS12_RFC5246_CONSISTENCY_CLIENT_HELLO_WITHOUT_SIGNATURE_TC002 * @title Default processing logic of the signature algorithm * @precon nan * @brief 1. Use the configuration items to configure the client and server, and set the client and service cipher suite to HITLS_ECDHE_RSA_WITH_AES_128_CBC_SHA. Expected result 1 is obtained. * 2. Modify the client hello message so that the message does not carry the signature algorithm extension. Then, the link is established. Expected result 2 is obtained. * @expect 1. The initialization is successful. * 2. The signature algorithm in the server keyexchange message sent by the server is CERT_SIG_SCHEME_RSA_PKCS1_SHA1. @ */ /* BEGIN_CASE */ void UT_TLS_TLS12_RFC5246_CONSISTENCY_CLIENT_HELLO_WITHOUT_SIGNATURE_TC002(void) { /* Use the configuration items to configure the client and server, and set the client and service cipher suite to * HITLS_ECDHE_RSA_WITH_AES_128_CBC_SHA. */ HandshakeTestInfo testInfo = { 0 }; FRAME_Msg frameMsg = { 0 }; FRAME_Type frameType = { 0 }; testInfo.state = TRY_RECV_CLIENT_HELLO; testInfo.isSupportExtendMasterSecret = true; testInfo.isClient = false; FRAME_Init(); testInfo.config = HITLS_CFG_NewTLS12Config(); ASSERT_TRUE(testInfo.config != NULL); uint16_t cipherSuite[] = {HITLS_ECDHE_RSA_WITH_AES_128_CBC_SHA}; ASSERT_EQ(HITLS_CFG_SetCipherSuites(testInfo.config, cipherSuite, sizeof(cipherSuite) / sizeof(uint16_t)), HITLS_SUCCESS); testInfo.config->isSupportExtendMasterSecret = testInfo.isSupportExtendMasterSecret; testInfo.config->isSupportClientVerify = testInfo.isSupportClientVerify; testInfo.config->isSupportNoClientCert = testInfo.isSupportNoClientCert; ASSERT_TRUE(StatusPark(&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_TLS12; 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); /* Modify the client hello message so that the message does not carry the signature algorithm extension. Then, the * link is established. */ FRAME_ClientHelloMsg *clientMsg = &frameMsg.body.hsMsg.body.clientHello; clientMsg->signatureAlgorithms.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(testInfo.server->io, sendBuf, sendLen) == HITLS_SUCCESS); FRAME_CleanMsg(&frameType, &frameMsg); memset_s(&frameMsg, sizeof(frameMsg), 0, sizeof(frameMsg)); testInfo.state = TRY_RECV_SERVER_KEY_EXCHANGE; testInfo.isClient = true; ASSERT_EQ(FRAME_CreateConnection(testInfo.client, testInfo.server, testInfo.isClient, testInfo.state), HITLS_SUCCESS); ASSERT_EQ(testInfo.client->ssl->hsCtx->state, TRY_RECV_SERVER_KEY_EXCHANGE); FrameUioUserData *ioUserData2 = BSL_UIO_GetUserData(testInfo.client->io); uint8_t *recvBuf2 = ioUserData2->recMsg.msg; uint32_t recvLen2 = ioUserData2->recMsg.len; ASSERT_TRUE(recvLen != 0); frameType.versionType = HITLS_VERSION_TLS12; frameType.recordType = REC_TYPE_HANDSHAKE; frameType.handshakeType = SERVER_KEY_EXCHANGE; frameType.keyExType = HITLS_KEY_EXCH_ECDHE; ASSERT_TRUE(FRAME_ParseMsg(&frameType, recvBuf2, recvLen2, &frameMsg, &parseLen) == HITLS_SUCCESS); FRAME_ServerKeyExchangeMsg *serverMsg = &frameMsg.body.hsMsg.body.serverKeyExchange; ASSERT_EQ(serverMsg->keyEx.ecdh.signAlgorithm.data, CERT_SIG_SCHEME_RSA_PKCS1_SHA1); EXIT: FRAME_CleanMsg(&frameType, &frameMsg); HITLS_CFG_FreeConfig(testInfo.config); FRAME_FreeLink(testInfo.client); FRAME_FreeLink(testInfo.server); } /* END_CASE */ /* @ * @test UT_TLS_TLS12_RFC5246_CONSISTENCY_RECODE_VERSION_TC001 * @title server can receive any version field in the recordheader of the client hello. * @precon nan * @brief 1. Use the default configuration items to configure the client and server. Expected result 1 is obtained. * 2. Change the version field in the recod header of the client hello message to 0x03ff. * @expect 1. The initialization is successful. * 2. The server can process the message normally and enter the next state. @ */ /* BEGIN_CASE */ void UT_TLS_TLS12_RFC5246_CONSISTENCY_RECODE_VERSION_TC001(void) { /* Use the default configuration items to configure the client and server. */ HandshakeTestInfo testInfo = { 0 }; FRAME_Msg frameMsg = { 0 }; FRAME_Type frameType = { 0 }; testInfo.state = TRY_RECV_CLIENT_HELLO; testInfo.isSupportExtendMasterSecret = true; testInfo.isClient = false; testInfo.isSupportClientVerify = true; testInfo.isSupportNoClientCert = false; FRAME_Init(); testInfo.config = HITLS_CFG_NewTLS12Config(); ASSERT_TRUE(testInfo.config != NULL); 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; ASSERT_TRUE(StatusPark(&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_TLS12; 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); ASSERT_TRUE(parseLen != 5); ASSERT_TRUE(FRAME_ParseMsgHeader(&frameType, recvBuf, recvLen, &frameMsg, &parseLen) == HITLS_SUCCESS); ASSERT_TRUE(parseLen == 5); /* Change the version field in the recod header of the client hello message to 0x03ff. */ frameMsg.recVersion.data = 0x0300; 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, recvBuf, recvLen) == HITLS_SUCCESS); FRAME_CleanMsg(&frameType, &frameMsg); memset_s(&frameMsg, sizeof(frameMsg), 0, sizeof(frameMsg)); ASSERT_TRUE(testInfo.server->ssl != NULL); ASSERT_EQ(HITLS_Accept(testInfo.server->ssl), HITLS_REC_NORMAL_IO_BUSY); ASSERT_EQ(testInfo.server->ssl->hsCtx->state, TRY_SEND_CERTIFICATE); EXIT: FRAME_CleanMsg(&frameType, &frameMsg); HITLS_CFG_FreeConfig(testInfo.config); FRAME_FreeLink(testInfo.client); FRAME_FreeLink(testInfo.server); } /* END_CASE */ /* @ * @test UT_TLS_TLS12_RFC5246_CONSISTENCY_RECODE_VERSION_TC002 * @title server can receive any version field in the recordheader of the client hello. * @precon nan * @brief 1. Use the default configuration items to configure the client and server. Expected result 1 is obtained. * 2. Change the version field in the recod header of the client hello message to 0x03ff. * @expect 1. The initialization is successful. * 2. The server can process the message normally and enter the next state. @ */ /* BEGIN_CASE */ void UT_TLS_TLS12_RFC5246_CONSISTENCY_RECODE_VERSION_TC002(void) { /* Use the default configuration items to configure the client and server. */ HandshakeTestInfo testInfo = { 0 }; FRAME_Msg frameMsg = { 0 }; FRAME_Type frameType = { 0 }; testInfo.state = TRY_RECV_CLIENT_HELLO; testInfo.isSupportExtendMasterSecret = true; testInfo.isClient = false; testInfo.isSupportClientVerify = true; testInfo.isSupportNoClientCert = false; FRAME_Init(); testInfo.config = HITLS_CFG_NewTLS12Config(); ASSERT_TRUE(testInfo.config != NULL); 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; ASSERT_TRUE(StatusPark(&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_TLS12; 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); ASSERT_TRUE(parseLen != 5); ASSERT_TRUE(FRAME_ParseMsgHeader(&frameType, recvBuf, recvLen, &frameMsg, &parseLen) == HITLS_SUCCESS); ASSERT_TRUE(parseLen == 5); /* Change the version field in the recod header of the client hello message to 0x03ff. */ frameMsg.recVersion.data = 0x03ff; 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, recvBuf, recvLen) == HITLS_SUCCESS); FRAME_CleanMsg(&frameType, &frameMsg); memset_s(&frameMsg, sizeof(frameMsg), 0, sizeof(frameMsg)); ASSERT_TRUE(testInfo.server->ssl != NULL); ASSERT_EQ(HITLS_Accept(testInfo.server->ssl), HITLS_REC_NORMAL_IO_BUSY); ASSERT_EQ(testInfo.server->ssl->hsCtx->state, TRY_SEND_CERTIFICATE); EXIT: FRAME_CleanMsg(&frameType, &frameMsg); HITLS_CFG_FreeConfig(testInfo.config); FRAME_FreeLink(testInfo.client); FRAME_FreeLink(testInfo.server); } /* END_CASE */ /* @ * @test UT_TLS_TLS12_RFC5246_CONSISTENCY_RECODE_VERSION_TC003 * @title server can receive any version field in the recordheader of the client hello message. * @precon nan * @brief 1. Use the default configuration items to configure the client and server. Expected result 1 is obtained. * 2. Change the version field in the recod header of the client hello message to 0x0399. * @expect 1. The initialization is successful. * 2. The server can process the message normally and enter the next state. @ */ /* BEGIN_CASE */ void UT_TLS_TLS12_RFC5246_CONSISTENCY_RECODE_VERSION_TC003(void) { /* Use the default configuration items to configure the client and server. */ HandshakeTestInfo testInfo = { 0 }; FRAME_Msg frameMsg = { 0 }; FRAME_Type frameType = { 0 }; testInfo.state = TRY_RECV_CLIENT_HELLO; testInfo.isSupportExtendMasterSecret = true; testInfo.isClient = false; testInfo.isSupportClientVerify = true; testInfo.isSupportNoClientCert = false; FRAME_Init(); testInfo.config = HITLS_CFG_NewTLS12Config(); ASSERT_TRUE(testInfo.config != NULL); 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; ASSERT_TRUE(StatusPark(&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; SetFrameType(&frameType, HITLS_VERSION_TLS12, REC_TYPE_HANDSHAKE, CLIENT_HELLO, HITLS_KEY_EXCH_ECDHE); ASSERT_TRUE(FRAME_ParseMsg(&frameType, recvBuf, recvLen, &frameMsg, &parseLen) == HITLS_SUCCESS); // The record length must be greater than or equal to 5 bytes. ASSERT_TRUE(parseLen >= 5); ASSERT_TRUE(FRAME_ParseTLSRecordHeader(recvBuf, recvLen, &frameMsg, &parseLen) == HITLS_SUCCESS); // The length of the record header must be 5 bytes. ASSERT_TRUE(parseLen == 5); /* Change the version field in the recod header of the client hello message to 0x0399. */ frameMsg.recVersion.data = 0x0399; 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, recvBuf, recvLen) == HITLS_SUCCESS); FRAME_CleanMsg(&frameType, &frameMsg); memset_s(&frameMsg, sizeof(frameMsg), 0, sizeof(frameMsg)); ASSERT_TRUE(testInfo.server->ssl != NULL); ASSERT_EQ(HITLS_Accept(testInfo.server->ssl), HITLS_REC_NORMAL_IO_BUSY); ASSERT_EQ(testInfo.server->ssl->hsCtx->state, TRY_SEND_CERTIFICATE); EXIT: FRAME_CleanMsg(&frameType, &frameMsg); HITLS_CFG_FreeConfig(testInfo.config); FRAME_FreeLink(testInfo.client); FRAME_FreeLink(testInfo.server); } /* END_CASE */ /* Define a new structure, Construct the SH message with the signatureAlgorithms extension added, Actually, the SH message should not contain the signatureAlgorithms. */ typedef struct { FRAME_Integer version; /* Version number */ FRAME_Array8 randomValue; /* Random number */ FRAME_Integer sessionIdSize; /* session ID length */ FRAME_Array8 sessionId; /* session ID */ FRAME_Integer cipherSuite; /* Cipher suite */ FRAME_Integer compressionMethod; /* Compression method */ FRAME_Integer extensionLen; /* Total length of the extension. */ FRAME_HsExtArray8 pointFormats; /* dot format */ FRAME_HsExtArray8 extendedMasterSecret; /* extended master key */ FRAME_HsExtArray8 secRenego; /* security renegotiation */ FRAME_HsExtArray8 sessionTicket; /* sessionTicket */ FRAME_HsExtArray16 signatureAlgorithms; /* algorithm signature */ } FRAME_ServerHelloMsg_WithSignatureAlgorithms; void SetServerHelloMsgWithSignatureAlgorithms(FRAME_ServerHelloMsg_WithSignatureAlgorithms *destMsg, const FRAME_ServerHelloMsg *serverMsg) { destMsg->version = serverMsg->version; destMsg->randomValue = serverMsg->randomValue; destMsg->sessionIdSize = serverMsg->sessionIdSize; destMsg->sessionId = serverMsg->sessionId; destMsg->cipherSuite = serverMsg->cipherSuite; destMsg->compressionMethod = serverMsg->compressionMethod; destMsg->extensionLen = serverMsg->extensionLen; destMsg->pointFormats = serverMsg->pointFormats; destMsg->extendedMasterSecret = serverMsg->extendedMasterSecret; destMsg->secRenego = serverMsg->secRenego; destMsg->sessionTicket = serverMsg->sessionTicket; } /* @ * @test UT_TLS_TLS12_RFC5246_CONSISTENCY_SERVER_HELLO_ADD_SIGNATURE_TC001 * @title The server attempts to send the signatureAlgorithms extension. * @precon nan * @brief 1. Use the configuration items to configure the client and server, and obtain the clientHello and serverHello respectively. Expected result 1 is obtained. * 2. Define a new structure, load the serverHello into the new structure, add the signatureAlgorithms extension from the clientHello, and send the extension to the client. * @expect 1. The initialization is successful. * 2. The client sends an ALERT message. The level is ALERT_ LEVEL_FATAL and the description is ALERT_UNSUPPORTED_EXTENSION. @ */ /* BEGIN_CASE */ void UT_TLS_TLS12_RFC5246_CONSISTENCY_SERVER_HELLO_ADD_SIGNATURE_TC001(void) { /* Use the configuration items to configure the client and server, and obtain the clientHello and serverHello * respectively. */ HandshakeTestInfo testInfo = { 0 }; testInfo.state = TRY_RECV_SERVER_HELLO; testInfo.isClient = true; ASSERT_TRUE(DefaultCfgStatusPark(&testInfo) == HITLS_SUCCESS); FrameUioUserData *ioUserData_c = BSL_UIO_GetUserData(testInfo.client->io); uint8_t *recvSHbuf = ioUserData_c->recMsg.msg; uint32_t recvSHbufLen = ioUserData_c->recMsg.len; ASSERT_TRUE(recvSHbufLen != 0); uint32_t parsedSHlen = 0; FRAME_Msg parsedSH = { 0 }; FRAME_Type frameType = { 0 }; SetFrameType(&frameType, HITLS_VERSION_TLS12, REC_TYPE_HANDSHAKE, SERVER_HELLO, HITLS_KEY_EXCH_ECDHE); ASSERT_TRUE(FRAME_ParseMsg(&frameType, recvSHbuf, recvSHbufLen, &parsedSH, &parsedSHlen) == HITLS_SUCCESS); HandshakeTestInfo testInfo2 = { 0 }; testInfo2.state = TRY_RECV_CLIENT_HELLO; testInfo2.isClient = false; ASSERT_TRUE(DefaultCfgStatusPark(&testInfo2) == HITLS_SUCCESS); FrameUioUserData *ioUserData_s = BSL_UIO_GetUserData(testInfo2.server->io); uint8_t *recvCHbuf = ioUserData_s->recMsg.msg; uint32_t recvCHbufLen = ioUserData_s->recMsg.len; ASSERT_TRUE(recvCHbufLen != 0); /* Define a new structure, load the serverHello into the new structure, add the signatureAlgorithms extension from * the clientHello, and send the extension to the client. */ uint32_t parsedCHlen = 0; FRAME_Msg parsedCH = { 0 }; FRAME_Type frameType2 = { 0 }; SetFrameType(&frameType2, HITLS_VERSION_TLS12, REC_TYPE_HANDSHAKE, CLIENT_HELLO, HITLS_KEY_EXCH_ECDHE); ASSERT_TRUE(FRAME_ParseMsg(&frameType2, recvCHbuf, recvCHbufLen, &parsedCH, &parsedCHlen) == HITLS_SUCCESS); FRAME_ClientHelloMsg *chMsg = &parsedCH.body.hsMsg.body.clientHello; ASSERT_TRUE(chMsg->signatureAlgorithms.exState == INITIAL_FIELD); FRAME_ServerHelloMsg *shMsg = &parsedSH.body.hsMsg.body.serverHello; FRAME_ServerHelloMsg_WithSignatureAlgorithms shWithSigAlgExt; SetServerHelloMsgWithSignatureAlgorithms(&shWithSigAlgExt, shMsg); uint32_t sigAlgNum = chMsg->signatureAlgorithms.exData.size; uint16_t *chSigAlgData = chMsg->signatureAlgorithms.exData.data; uint32_t chSigAlgDataSize = sigAlgNum * sizeof(uint16_t); memcpy_s(&shWithSigAlgExt.signatureAlgorithms, sizeof(FRAME_HsExtArray16), &(chMsg->signatureAlgorithms), sizeof(FRAME_HsExtArray16)); shWithSigAlgExt.signatureAlgorithms.exData.data = calloc(sigAlgNum, sizeof(uint16_t)); memcpy_s(shWithSigAlgExt.signatureAlgorithms.exData.data, chSigAlgDataSize, chSigAlgData, chSigAlgDataSize); memcpy_s(&parsedSH.body.hsMsg.body.serverHello, sizeof(FRAME_ServerHelloMsg_WithSignatureAlgorithms), &shWithSigAlgExt, sizeof(FRAME_ServerHelloMsg_WithSignatureAlgorithms)); 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_c->recMsg.len = 0; ASSERT_TRUE(FRAME_TransportRecMsg(testInfo.client->io, sendBuf, sendLen) == HITLS_SUCCESS); ASSERT_EQ(HITLS_Connect(testInfo.client->ssl), HITLS_PARSE_UNSUPPORTED_EXTENSION); ioUserData_c = BSL_UIO_GetUserData(testInfo.client->io); uint8_t *sndBuf_c = ioUserData_c->sndMsg.msg; uint32_t sndBufLen_c = ioUserData_c->sndMsg.len; ASSERT_TRUE(sndBufLen_c != 0); uint32_t parsedAlertLen = 0; FRAME_Msg parsedAlert = { 0 }; ASSERT_TRUE(FRAME_ParseTLSNonHsRecord(sndBuf_c, sndBufLen_c, &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_TRUE(alertMsg->alertDescription.data == ALERT_UNSUPPORTED_EXTENSION); EXIT: FRAME_CleanMsg(&frameType, &parsedSH); FRAME_CleanMsg(&frameType2, &parsedCH); FRAME_CleanNonHsRecord(REC_TYPE_ALERT, &parsedAlert); FRAME_FreeLink(testInfo.client); FRAME_FreeLink(testInfo.server); HITLS_CFG_FreeConfig(testInfo.config); FRAME_FreeLink(testInfo2.client); FRAME_FreeLink(testInfo2.server); HITLS_CFG_FreeConfig(testInfo2.config); FRAME_DeRegCryptMethod(); } /* END_CASE */ void Test_RenegoWrapperFunc(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); ASSERT_EQ(parseLen, *len); ASSERT_EQ(frameMsg.body.hsMsg.body.clientHello.secRenego.exState, INITIAL_FIELD); EXIT: FRAME_CleanMsg(&frameType, &frameMsg); return; } void Test_RenegoRemoveExtension(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); ASSERT_EQ(parseLen, *len); frameMsg.body.hsMsg.body.clientHello.secRenego.exState = MISSING_FIELD; FRAME_PackRecordBody(&frameType, &frameMsg, data, bufSize, len); EXIT: FRAME_CleanMsg(&frameType, &frameMsg); return; } int32_t g_writeRet; uint32_t g_writeLen; bool g_isUseWriteLen; uint8_t g_writeBuf[REC_TLS_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_TLS_RECORD_HEADER_LEN + REC_MAX_CIPHER_TEXT_LEN + 1]; 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); BSL_UIO_SetInit(uio, 1); 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; } #define BUFFER_SIZE 128 #define UT_AEAD_NONCE_SIZE 12u /* AEAD nonce is fixed to 12. */ #define UT_AEAD_TAG_LENGTH 16 ALERT_Level g_alertLevel; ALERT_Description g_alertDescription; void STUB_SendAlert(const TLS_Ctx *ctx, ALERT_Level level, ALERT_Description description) { (void)ctx; g_alertLevel = level; g_alertDescription = description; return; } typedef struct { REC_Type type; uint16_t version; uint64_t epochSeq; uint16_t bodyLen; uint8_t *body; } RecordMsg; 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 recovery. */ } ResumeTestInfo; static uint8_t *g_sessionId; static uint32_t g_sessionIdSize; int32_t NewConfig(ResumeTestInfo *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) { return HITLS_INTERNAL_EXCEPTION; } HITLS_CFG_SetClientVerifySupport(testInfo->config, true); HITLS_CFG_SetCheckKeyUsage(testInfo->config, false); 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); HITLS_CFG_SetPskClientCallback(testInfo->config, (HITLS_PskClientCb)ExampleClientCb); return HITLS_SUCCESS; } static void FreeLink(ResumeTestInfo *testInfo) { /* Release resources. */ FRAME_FreeLink(testInfo->client); testInfo->client = NULL; FRAME_FreeLink(testInfo->server); testInfo->server = NULL; } int32_t GetSessionId(ResumeTestInfo *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; } /* Save the sessionId in the serverhello. */ FRAME_ServerHelloMsg *serverHello = &recvframeMsg.body.hsMsg.body.serverHello; g_sessionIdSize = serverHello->sessionIdSize.data; g_sessionId = BSL_SAL_Dump(serverHello->sessionId.data, g_sessionIdSize); FRAME_CleanMsg(&frameType, &recvframeMsg); return HITLS_SUCCESS; } int32_t FirstHandshake(ResumeTestInfo *testInfo) { 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; } int32_t ret = 0; ret = FRAME_CreateConnection(testInfo->client, testInfo->server, true, TRY_RECV_SERVER_HELLO); if (ret != HITLS_SUCCESS) { return ret; } /* Obtain the session ID for the first connection setup. */ 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; } /* User data transmission */ 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); FreeLink(testInfo); return HITLS_SUCCESS; } int32_t CmpClientHelloSessionId(ResumeTestInfo *testInfo) { FRAME_Type frameType = { 0 }; /* Obtain the client hello message received by the server. */ FrameUioUserData *ioUserData = BSL_UIO_GetUserData(testInfo->server->io); uint8_t *recMsg = ioUserData->recMsg.msg; uint32_t recMsgLen = ioUserData->recMsg.len; uint32_t parseLen = 0; FRAME_Msg frameMsg = { 0 }; frameType.versionType = testInfo->version; frameType.recordType = REC_TYPE_HANDSHAKE; frameType.handshakeType = CLIENT_HELLO; frameType.keyExType = HITLS_KEY_EXCH_ECDHE; int32_t ret = FRAME_ParseMsg(&frameType, recMsg, recMsgLen, &frameMsg, &parseLen); if (ret != HITLS_SUCCESS) { return ret; } /* Compare the sessionId in the client hello with the saved sessionId. */ FRAME_ClientHelloMsg *clienHello = &frameMsg.body.hsMsg.body.clientHello; if (clienHello->sessionIdSize.data != g_sessionIdSize) { return HITLS_INTERNAL_EXCEPTION; } if (memcmp(clienHello->sessionId.data, g_sessionId, g_sessionIdSize) != 0) { return HITLS_INTERNAL_EXCEPTION; } FRAME_CleanMsg(&frameType, &frameMsg); CONN_Deinit(testInfo->server->ssl); HITLS_Accept(testInfo->server->ssl); FRAME_TrasferMsgBetweenLink(testInfo->server, testInfo->client); return HITLS_SUCCESS; } int32_t CmpSessionId(ResumeTestInfo *testInfo) { FRAME_Type frameType = { 0 }; FRAME_Msg recvframeMsg = { 0 }; /* Obtain the server hello message received by the client. */ 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; /* Parse the server hello message. */ uint32_t parseLen = 0; int32_t ret = FRAME_ParseMsg(&frameType, recMsg, recMsgLen, &recvframeMsg, &parseLen); if (ret != HITLS_SUCCESS) { return ret; } /* Check whether the received serverhello message is consistent with the saved one. */ FRAME_ServerHelloMsg *serverHello = &recvframeMsg.body.hsMsg.body.serverHello; if (serverHello->sessionIdSize.data != g_sessionIdSize) { FRAME_CleanMsg(&frameType, &recvframeMsg); return HITLS_INTERNAL_EXCEPTION; } if (memcmp(serverHello->sessionId.data, g_sessionId, g_sessionIdSize) != 0) { FRAME_CleanMsg(&frameType, &recvframeMsg); return HITLS_INTERNAL_EXCEPTION; } FRAME_CleanMsg(&frameType, &recvframeMsg); return HITLS_SUCCESS; } int32_t TryResumeBySessionId(ResumeTestInfo *testInfo) { int32_t ret; testInfo->client = FRAME_CreateLink(testInfo->config, testInfo->uioType); if (testInfo->client == NULL) { return HITLS_INTERNAL_EXCEPTION; } if (testInfo->clientSession != NULL) { 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; } ret = FRAME_CreateConnection(testInfo->client, testInfo->server, false, TRY_RECV_CLIENT_HELLO); if (ret != HITLS_SUCCESS) { return ret; } ret = CmpClientHelloSessionId(testInfo); if (ret != HITLS_SUCCESS) { return ret; } ret = CmpSessionId(testInfo); if (ret != HITLS_SUCCESS) { return ret; } ret = FRAME_CreateConnection(testInfo->client, testInfo->server, true, HS_STATE_BUTT); if (ret != HITLS_SUCCESS) { return ret; } /* User data transmission */ 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; } return HITLS_Read(testInfo->client->ssl, readBuf, READ_BUF_SIZE, &readLen); } int32_t TryResumeByTheUsingSessionId(ResumeTestInfo *testInfo) { int32_t ret; testInfo->client = FRAME_CreateLink(testInfo->config, testInfo->uioType); if (testInfo->client == NULL) { return HITLS_INTERNAL_EXCEPTION; } if (testInfo->clientSession != NULL) { 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; } ret = FRAME_CreateConnection(testInfo->client, testInfo->server, false, TRY_RECV_CLIENT_HELLO); if (ret != HITLS_SUCCESS) { return ret; } ret = CmpClientHelloSessionId(testInfo); if (ret != HITLS_SUCCESS) { return ret; } ret = CmpSessionId(testInfo); if (ret != HITLS_SUCCESS) { return HITLS_MSG_HANDLE_ILLEGAL_SESSION_ID; } return HITLS_SUCCESS; } /* @ * @test UT_TLS_TLS12_RFC5246_CONSISTENCY_MULTILINK_RESUME_ALERT_TC001 * @title Test the scenario where the session recovers. * @precon nan * @brief 1. First handshake between the client and server. Save the session ID. Expected result 1 is obtained. 2. Obtain the client session and set the session to the client that performs the next handshake. Expected result 2 is obtained. 3. Perform the second handshake between the client and server. Expected result 3 is obtained. 4. Use the same session ID on the client and server to restore the session. Expected result 4 is obtained. * @expect 1. A success message is returned. 2. A success message is returned. 3. The session is restored successfully. 4. The session fails. @ */ /* BEGIN_CASE */ void UT_TLS_TLS12_RFC5246_CONSISTENCY_MULTILINK_RESUME_ALERT_TC001(int uioType, int version) { g_sessionId = NULL; g_sessionIdSize = 0; FRAME_Init(); ResumeTestInfo testInfo01 = { 0 }; testInfo01.version = (uint16_t)version; testInfo01.uioType = (BSL_UIO_TransportType)uioType; /* First handshake between the client and server. Save the session ID. */ ASSERT_EQ(NewConfig(&testInfo01), HITLS_SUCCESS); HITLS_CFG_SetSessionTicketSupport(testInfo01.config, false); ASSERT_EQ(FirstHandshake(&testInfo01), HITLS_SUCCESS); /* Obtain the client session and set the session to the client that performs the next handshake. */ ASSERT_TRUE(testInfo01.clientSession != NULL); ASSERT_EQ(TryResumeBySessionId(&testInfo01), HITLS_SUCCESS); ResumeTestInfo testInfo02 = { 0 }; testInfo02.version = (uint16_t)version; testInfo02.uioType = (BSL_UIO_TransportType)uioType; /* Perform the second handshake between the client and server. */ ASSERT_EQ(NewConfig(&testInfo02), HITLS_SUCCESS); HITLS_CFG_SetSessionTicketSupport(testInfo02.config, false); /* Use the same session ID on the client and server to restore the session. */ testInfo02.clientSession = testInfo01.clientSession; ASSERT_EQ(TryResumeByTheUsingSessionId(&testInfo02), HITLS_MSG_HANDLE_ILLEGAL_SESSION_ID); ASSERT_TRUE(testInfo02.clientSession != NULL); EXIT: FreeLink(&testInfo01); FreeLink(&testInfo02); BSL_SAL_FREE(g_sessionId); HITLS_CFG_FreeConfig(testInfo01.config); FRAME_FreeLink(testInfo01.client); FRAME_FreeLink(testInfo01.server); HITLS_SESS_Free(testInfo01.clientSession); HITLS_CFG_FreeConfig(testInfo02.config); FRAME_FreeLink(testInfo02.client); FRAME_FreeLink(testInfo02.server); } /* END_CASE */ /* @ * @test UT_TLS_TLS12_RFC5246_CONSISTENCY_CLOSE_NOTIFY_TC001 * @title Close the link and check whether the close_notify alarm is sent. * @precon nan * @brief 1. Establish a connection between the client and server. Expected result 1 is obtained. * 2. The client closes the link, obtains the message sent by the client, and checks whether the message is a close_notify message. (Expected result 2) * 3. The server obtains the received message and checks whether the message is a close_notify message. (Expected result 3) * @expect 1. The link is successfully established. * 2. The client sends a close_notify message. * 3. The server receives the close_notify message. @ */ /* BEGIN_CASE */ void UT_TLS_TLS12_RFC5246_CONSISTENCY_CLOSE_NOTIFY_TC001(void) { FRAME_Init(); HITLS_Config *config = NULL; FRAME_LinkObj *client = NULL; FRAME_LinkObj *server = NULL; config = HITLS_CFG_NewTLS12Config(); 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)); /* Establish a connection between the client and server. */ 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_SERVER_KEY_EXCHANGE) == HITLS_SUCCESS); ASSERT_TRUE(clientTlsCtx->hsCtx->state == TRY_RECV_SERVER_KEY_EXCHANGE); ASSERT_TRUE(clientTlsCtx->state == CM_STATE_HANDSHAKING); /* The client closes the link, obtains the message sent by the client, and checks whether the message is a * close_notify message. */ 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); /* The server obtains the received message and checks whether the message is a close_notify message. */ 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_TLS12_RFC5246_CONSISTENCY_CLOSE_NOTIFY_TC002 * @title Close the link and check whether the close_notify alarm is sent. * @precon nan * @brief 1. Establish a connection between the client and server. Expected result 1 is obtained. * 2. Close the link on the client, obtain the message sent by the client, and check whether the message is a close_notify message. (Expected result 2) * 3. The server processes the message received by the server, obtains the message to be sent after processing, and checks whether the message is a close_notify message. (Expected result 3) * @expect 1. The link is successfully established. * 2. The client sends a close_notify message. * 3. The server sends a close_notify message. @ */ /* BEGIN_CASE */ void UT_TLS_TLS12_RFC5246_CONSISTENCY_CLOSE_NOTIFY_TC002(void) { FRAME_Init(); HITLS_Config *config = NULL; FRAME_LinkObj *client = NULL; FRAME_LinkObj *server = NULL; config = HITLS_CFG_NewTLS12Config(); 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)); /* Establish a connection between the client and server. */ 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_SERVER_KEY_EXCHANGE) == HITLS_SUCCESS); ASSERT_TRUE(clientTlsCtx->hsCtx->state == TRY_RECV_SERVER_KEY_EXCHANGE); ASSERT_TRUE(clientTlsCtx->state == CM_STATE_HANDSHAKING); /* Close the link on the client, obtain the message sent by the client, and check whether the message is a * close_notify message. */ 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); /* The server processes the message received by the server, obtains the message to be sent after processing, and * checks whether the message is a close_notify message. */ 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 serverframeMsg1 = { 0 }; uint8_t *serverbuffer1 = serverioUserData->sndMsg.msg; uint32_t serverreadLen1 = serverioUserData->sndMsg.len; uint32_t serverparseLen1 = 0; ret = ParserTotalRecord(server, &serverframeMsg1, serverbuffer1, serverreadLen1, &serverparseLen1); ASSERT_TRUE(ret == HITLS_SUCCESS); ASSERT_TRUE(serverframeMsg1.type == REC_TYPE_ALERT && serverframeMsg1.bodyLen == ALERT_BODY_LEN); ASSERT_TRUE(serverframeMsg1.body.alertMsg.level == ALERT_LEVEL_WARNING && serverframeMsg1.body.alertMsg.description == ALERT_CLOSE_NOTIFY); EXIT: HITLS_CFG_FreeConfig(config); FRAME_FreeLink(client); FRAME_FreeLink(server); } /* END_CASE */ /* @ * @test UT_TLS_TLS12_RFC5246_CONSISTENCY_CLOSE_NOTIFY_TC003 * @title Close the link and check whether the close_notify alarm is sent. * @precon nan * @brief 1. Establish a connection between the client and server. Expected result 1 is obtained. * 2. The server closes the link, obtains the message sent by the server, and checks whether the message is a close_notify message. (Expected result 2) * 3. Obtain the received message and check whether the message is a close_notify message. (Expected result 3) * @expect 1. The link is successfully established. * 2. The server sends a close_notify message. * 3. The client receives the close_notify message. @ */ /* BEGIN_CASE */ void UT_TLS_TLS12_RFC5246_CONSISTENCY_CLOSE_NOTIFY_TC003(void) { FRAME_Init(); HITLS_Config *config = NULL; FRAME_LinkObj *client = NULL; FRAME_LinkObj *server = NULL; config = HITLS_CFG_NewTLS12Config(); 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)); /* Establish a connection between the client and server. */ 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); /* The server closes the link, obtains the message sent by the server, and checks whether the message is a * close_notify message. */ 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); /* Obtain the received message and check whether the message is a close_notify message. */ 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_TLS12_RFC5246_CONSISTENCY_CLOSE_NOTIFY_TC004 * @title Close the link and check whether the close_notify alarm is sent. * @precon nan * @brief 1. Establish a link between the client and server. Expected result 1 is obtained. * 2. The server closes the link, obtains the message sent by the server, and checks whether the message is a close_notify message. (Expected result 2) * 3. The client processes the received message, obtains the message to be sent after processing, and checks whether the message is a close_notify message. (Expected result 3) * @expect 1. The link is successfully established. * 2. The client sends a close_notify message. * 3. The server sends a close_notify message. @ */ /* BEGIN_CASE */ void UT_TLS_TLS12_RFC5246_CONSISTENCY_CLOSE_NOTIFY_TC004(void) { FRAME_Init(); HITLS_Config *config = NULL; FRAME_LinkObj *client = NULL; FRAME_LinkObj *server = NULL; config = HITLS_CFG_NewTLS12Config(); 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)); /* Establish a link between the client and server. */ 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_SEND_CLIENT_KEY_EXCHANGE) == HITLS_SUCCESS); ASSERT_TRUE(clientTlsCtx->hsCtx->state == TRY_SEND_CLIENT_KEY_EXCHANGE); ASSERT_TRUE(serverTlsCtx->hsCtx->state == TRY_RECV_CLIENT_KEY_EXCHANGE); ASSERT_TRUE(clientTlsCtx->state == CM_STATE_HANDSHAKING); ASSERT_TRUE(serverTlsCtx->state == CM_STATE_HANDSHAKING); /* The server closes the link, obtains the message sent by the server, and checks whether the message is a * close_notify message. */ 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); FrameUioUserData *clientioUserData = BSL_UIO_GetUserData(client->io); clientioUserData->recMsg.len = 0; ASSERT_TRUE(FRAME_TrasferMsgBetweenLink(server, client) == HITLS_SUCCESS); /* The client processes the received message, obtains the message to be sent after processing, and checks whether * the message is a close_notify message. */ 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); ASSERT_TRUE(client->ssl != NULL); clientioUserData->sndMsg.len = 0; ASSERT_EQ(HITLS_Connect(client->ssl), HITLS_REC_NORMAL_IO_BUSY); clientioUserData->sndMsg.len = 0; ASSERT_EQ(HITLS_Connect(client->ssl), HITLS_REC_NORMAL_IO_BUSY); clientioUserData->sndMsg.len = 0; ASSERT_EQ(HITLS_Connect(client->ssl), HITLS_REC_NORMAL_IO_BUSY); clientioUserData->sndMsg.len = 0; ASSERT_EQ(HITLS_Connect(client->ssl), HITLS_CM_LINK_FATAL_ALERTED); FRAME_Msg clientframeMsg1 = { 0 }; uint8_t *clientbuffer1 = clientioUserData->sndMsg.msg; uint32_t clientreadLen1 = clientioUserData->sndMsg.len; uint32_t clientparseLen1 = 0; ret = ParserTotalRecord(client, &clientframeMsg1, clientbuffer1, clientreadLen1, &clientparseLen1); ASSERT_TRUE(ret == HITLS_SUCCESS); ASSERT_TRUE(clientframeMsg1.type == REC_TYPE_ALERT); ASSERT_TRUE(clientframeMsg1.body.alertMsg.description == ALERT_CLOSE_NOTIFY); EXIT: HITLS_CFG_FreeConfig(config); FRAME_FreeLink(client); FRAME_FreeLink(server); } /* END_CASE */ /* @ * @test UT_TLS_TLS12_RFC5246_CONSISTENCY_CM_CLOSE_SEND_ALERT_TC001 * @title Disable the link abnormally and check whether the two ends send an alert. * @precon nan * @brief 1. Establish a link between the client and server, and the client is disabling the link. Expected result 1 is obtained. * 2. Enable the client to send a critical alarm. Obtain the received message from the server and check whether the message is an alert message. Expected result 2 is obtained. * @expect 1. The link is successfully established and the client is in the closed state. * 2. Check the alert message on the server. @ */ /* BEGIN_CASE */ void UT_TLS_TLS12_RFC5246_CONSISTENCY_CM_CLOSE_SEND_ALERT_TC001(void) { HandshakeTestInfo testInfo = { 0 }; testInfo.state = TRY_RECV_SERVER_HELLO; testInfo.isClient = true; testInfo.isSupportExtendMasterSecret = true; testInfo.isSupportClientVerify = true; testInfo.isSupportNoClientCert = false; ASSERT_TRUE(DefaultCfgStatusPark(&testInfo) == HITLS_SUCCESS); /* Establish a link between the client and server, and the client is disabling the link. */ FRAME_Msg parsedSHdone = { 0 }; FRAME_Type frameType = { 0 }; SetFrameType(&frameType, HITLS_VERSION_TLS12, REC_TYPE_HANDSHAKE, SERVER_HELLO_DONE, HITLS_KEY_EXCH_ECDHE); ASSERT_TRUE(FRAME_GetDefaultMsg(&frameType, &parsedSHdone) == HITLS_SUCCESS); uint32_t sendLen = MAX_RECORD_LENTH; uint8_t sendBuf[MAX_RECORD_LENTH] = {0}; ASSERT_TRUE(FRAME_PackMsg(&frameType, &parsedSHdone, 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, &parsedSHdone); ASSERT_TRUE(testInfo.client->ssl != NULL); ASSERT_EQ(HITLS_Connect(testInfo.client->ssl), HITLS_MSG_HANDLE_UNEXPECTED_MESSAGE); 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, &parsedSHdone, &parseLen) == HITLS_SUCCESS); ASSERT_TRUE(parsedSHdone.recType.data == REC_TYPE_ALERT); FRAME_AlertMsg *alertMsg = &parsedSHdone.body.alertMsg; ASSERT_TRUE(alertMsg->alertLevel.data == ALERT_LEVEL_FATAL); ASSERT_TRUE(alertMsg->alertDescription.data == ALERT_UNEXPECTED_MESSAGE); // Enable the client to send a critical alarm. Obtain the received message from the server and check whether the // message is an alert message. ASSERT_TRUE(FRAME_TrasferMsgBetweenLink(testInfo.client, testInfo.server) == HITLS_SUCCESS); FrameUioUserData *clientioUserData = BSL_UIO_GetUserData(testInfo.server->io); FRAME_Msg clientframeMsg = { 0 }; uint8_t *clientbuffer = clientioUserData->recMsg.msg; uint32_t clientreadLen = clientioUserData->recMsg.len; uint32_t clientparseLen = 0; int32_t ret = ParserTotalRecord(testInfo.server, &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_FATAL && clientframeMsg.body.alertMsg.description == ALERT_UNEXPECTED_MESSAGE); EXIT: FRAME_CleanMsg(&frameType, &parsedSHdone); HITLS_CFG_FreeConfig(testInfo.config); FRAME_FreeLink(testInfo.client); FRAME_FreeLink(testInfo.server); FRAME_DeRegCryptMethod(); } /* END_CASE */ /* @ * @test UT_TLS_TLS12_RFC5246_CONSISTENCY_CM_CLOSE_SEND_ALERT_TC002 * @title Abnormally close the link and check whether the two ends send an alert. * @precon nan * @brief 1. Establish a link between the client and server. The client is in the link disabling state. Expected result 1 is obtained. * 2. Enable the client to send a critical alarm, obtain the received message from the server, and check whether the message is an alert message. Expected result 2 is obtained. * @expect 1. The link is successfully established and the client is in the closed state. * 2. Check the alert message on the server. @ */ /* BEGIN_CASE */ void UT_TLS_TLS12_RFC5246_CONSISTENCY_CM_CLOSE_SEND_ALERT_TC002(void) { HandshakeTestInfo testInfo = { 0 }; testInfo.state = TRY_RECV_CLIENT_KEY_EXCHANGE; testInfo.isClient = false; testInfo.isSupportExtendMasterSecret = true; testInfo.isSupportClientVerify = false; ASSERT_TRUE(DefaultCfgStatusPark(&testInfo) == HITLS_SUCCESS); /* Establish a link between the client and server. The client is in the link disabling state. */ FRAME_Msg frameMsg = { 0 }; FRAME_Type frameType = { 0 }; frameType.versionType = HITLS_VERSION_TLS12; frameType.recordType = REC_TYPE_CHANGE_CIPHER_SPEC; 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); 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); 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; 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_TRUE(alertMsg->alertDescription.data == ALERT_UNEXPECTED_MESSAGE); // Enable the client to send a critical alarm, obtain the received message from the server, and check whether the // message is an alert message. ASSERT_TRUE(FRAME_TrasferMsgBetweenLink(testInfo.server, testInfo.client) == HITLS_SUCCESS); FrameUioUserData *clientioUserData = BSL_UIO_GetUserData(testInfo.client->io); FRAME_Msg clientframeMsg = { 0 }; uint8_t *clientbuffer = clientioUserData->recMsg.msg; uint32_t clientreadLen = clientioUserData->recMsg.len; uint32_t clientparseLen = 0; int32_t ret = ParserTotalRecord(testInfo.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_FATAL && clientframeMsg.body.alertMsg.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_TLS12_RFC5246_CONSISTENCY_RECV_NO_CERTIFICATE_RESERVED_ALERT_TC001 * @title The client receives the NO_CERTIFICATIONATE_RESERVED alarm. * @precon nan * @brief 1. Use the default configuration items to configure the client and server. Expected result 1 is obtained. * 2. When the client stops receiving server hello, the server sends the NO_CERTIFICATIONATE_RESERVED alarm and observe the response from the client. * @expect 1. The initialization is successful. * 2. The client ignores the message. The client should not receive the message. @ */ /* BEGIN_CASE */ void UT_TLS_TLS12_RFC5246_CONSISTENCY_RECV_NO_CERTIFICATE_RESERVED_ALERT_TC001(void) { FRAME_Init(); HITLS_Config *config = NULL; FRAME_LinkObj *client = NULL; FRAME_LinkObj *server = NULL; FRAME_Msg recvframeMsg = { 0 }; FRAME_Msg sndframeMsg = { 0 }; /* Use the default configuration items to configure the client and server. */ config = HITLS_CFG_NewTLS12Config(); 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, 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_SERVER_HELLO) == HITLS_SUCCESS); ASSERT_TRUE(clientTlsCtx->hsCtx->state == TRY_RECV_SERVER_HELLO); ASSERT_TRUE(clientTlsCtx->state == CM_STATE_HANDSHAKING); /* When the client stops receiving server hello, the server sends the NO_CERTIFICATIONATE_RESERVED alarm and observe * the response from the client. */ recvframeMsg.type = REC_TYPE_ALERT; recvframeMsg.version = HITLS_VERSION_TLS12; recvframeMsg.bodyLen = ALERT_BODY_LEN; recvframeMsg.epochSeq = GetEpochSeq(0, 5); recvframeMsg.body.alertMsg.level = ALERT_LEVEL_WARNING; recvframeMsg.body.alertMsg.description = ALERT_NO_CERTIFICATE_RESERVED; ASSERT_TRUE(PackFrameMsg(&recvframeMsg) == HITLS_SUCCESS); FrameUioUserData *ioUserData = BSL_UIO_GetUserData(client->io); ioUserData->recMsg.len = 0; ASSERT_TRUE(FRAME_TransportRecMsg(client->io, recvframeMsg.buffer, recvframeMsg.len) == HITLS_SUCCESS); ioUserData->sndMsg.len = 0; ASSERT_TRUE(HITLS_Connect(clientTlsCtx) == HITLS_REC_NORMAL_RECV_BUF_EMPTY); EXIT: CleanRecordBody(&recvframeMsg); CleanRecordBody(&sndframeMsg); HITLS_CFG_FreeConfig(config); FRAME_FreeLink(client); FRAME_FreeLink(server); } /* END_CASE */ /* @ * @test UT_TLS_TLS12_RFC5246_CONSISTENCY_RECV_NO_CERTIFICATE_RESERVED_ALERT_TC002 * @title The client receives the NO_CERTIFICATIONATE_RESERVED alarm. * @precon nan * @brief 1. Use the default configuration items to configure the client and server. Expected result 1 is obtained. * 2. When the server stops receiving the client keyexchange, the client sends the no_certificate_RESERVED alarm and observe the message returned by the server. * @expect 1. The initialization is successful. * 2. The server ignores the message. The message cannot be received. @ */ /* BEGIN_CASE */ void UT_TLS_TLS12_RFC5246_CONSISTENCY_RECV_NO_CERTIFICATE_RESERVED_ALERT_TC002(void) { FRAME_Init(); HITLS_Config *config = NULL; FRAME_LinkObj *client = NULL; FRAME_LinkObj *server = NULL; FRAME_Msg recvframeMsg = { 0 }; FRAME_Msg sndframeMsg = { 0 }; /* Use the default configuration items to configure the client and server. */ config = HITLS_CFG_NewTLS12Config(); 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, 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); /* When the server stops receiving the client keyexchange, the client sends the no_certificate_RESERVED alarm and * observe the message returned by the server. */ ASSERT_TRUE(FRAME_CreateConnection(client, server, false, TRY_RECV_CLIENT_KEY_EXCHANGE) == HITLS_SUCCESS); ASSERT_TRUE(clientTlsCtx->state == CM_STATE_HANDSHAKING); ASSERT_TRUE(serverTlsCtx->state == CM_STATE_HANDSHAKING); recvframeMsg.type = REC_TYPE_ALERT; recvframeMsg.version = HITLS_VERSION_TLS12; recvframeMsg.bodyLen = ALERT_BODY_LEN; recvframeMsg.epochSeq = GetEpochSeq(0, 5); recvframeMsg.body.alertMsg.level = ALERT_LEVEL_WARNING; recvframeMsg.body.alertMsg.description = ALERT_NO_CERTIFICATE_RESERVED; ASSERT_TRUE(PackFrameMsg(&recvframeMsg) == HITLS_SUCCESS); FrameUioUserData *ioUserData = BSL_UIO_GetUserData(server->io); ioUserData->recMsg.len = 0; ASSERT_TRUE(FRAME_TransportRecMsg(server->io, recvframeMsg.buffer, recvframeMsg.len) == HITLS_SUCCESS); ioUserData->sndMsg.len = 0; ASSERT_TRUE(HITLS_Accept(serverTlsCtx) == HITLS_REC_NORMAL_RECV_BUF_EMPTY); EXIT: CleanRecordBody(&recvframeMsg); CleanRecordBody(&sndframeMsg); HITLS_CFG_FreeConfig(config); FRAME_FreeLink(client); FRAME_FreeLink(server); } /* END_CASE */ /* @ * @test UT_TLS_TLS12_RFC5246_CONSISTENCY_RECV_EXPORT_RESTRICTION_RESERVED_ALERT_TC001 * @title The client receives an ERROR_RESTRICTION_RESERVED alarm. * @precon nan * @brief 1. Use the default configuration items to configure the client and server. Expected result 1 is obtained. * 2. When the client stops receiving server hello, the server sends the export_restriction_RESERVED alarm. * @expect 1. The initialization is successful. * 2. The client ignores the message. The client should not receive the message. @ */ /* BEGIN_CASE */ void UT_TLS_TLS12_RFC5246_CONSISTENCY_RECV_EXPORT_RESTRICTION_RESERVED_ALERT_TC001(void) { FRAME_Init(); HITLS_Config *config = NULL; FRAME_LinkObj *client = NULL; FRAME_LinkObj *server = NULL; FRAME_Msg recvframeMsg = { 0 }; FRAME_Msg sndframeMsg = { 0 }; /* Use the default configuration items to configure the client and server. */ config = HITLS_CFG_NewTLS12Config(); 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, 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); /* When the client stops receiving server hello, the server sends the export_restriction_RESERVED alarm. */ ASSERT_TRUE(FRAME_CreateConnection(client, server, true, TRY_RECV_SERVER_HELLO) == HITLS_SUCCESS); ASSERT_TRUE(clientTlsCtx->hsCtx->state == TRY_RECV_SERVER_HELLO); ASSERT_TRUE(clientTlsCtx->state == CM_STATE_HANDSHAKING); recvframeMsg.type = REC_TYPE_ALERT; recvframeMsg.version = HITLS_VERSION_TLS12; recvframeMsg.bodyLen = ALERT_BODY_LEN; recvframeMsg.epochSeq = GetEpochSeq(0, 5); recvframeMsg.body.alertMsg.level = ALERT_LEVEL_WARNING; recvframeMsg.body.alertMsg.description = ALERT_EXPORT_RESTRICTION_RESERVED; ASSERT_TRUE(PackFrameMsg(&recvframeMsg) == HITLS_SUCCESS); FrameUioUserData *ioUserData = BSL_UIO_GetUserData(client->io); ioUserData->recMsg.len = 0; ASSERT_TRUE(FRAME_TransportRecMsg(client->io, recvframeMsg.buffer, recvframeMsg.len) == HITLS_SUCCESS); ioUserData->sndMsg.len = 0; ASSERT_TRUE(HITLS_Connect(clientTlsCtx) == HITLS_REC_NORMAL_RECV_BUF_EMPTY); EXIT: CleanRecordBody(&recvframeMsg); CleanRecordBody(&sndframeMsg); HITLS_CFG_FreeConfig(config); FRAME_FreeLink(client); FRAME_FreeLink(server); } /* END_CASE */ /* @ * @test UT_TLS_TLS12_RFC5246_CONSISTENCY_RECV_EXPORT_RESTRICTION_RESERVED_ALERT_TC002 * @title The client receives an ERROR_RESTRICTION_RESERVED alarm. * @precon nan * @brief 1. Use the default configuration items to configure the client and server. Expected result 1 is obtained. * 2. When the server receives the client keyexchange, the client sends the export_restriction_RESERVED alarm, Check the message returned by the server. Expected result 2 is obtained. * @expect 1. The initialization is successful. * 2. The server ignores the message. The message cannot be received. @ */ /* BEGIN_CASE */ void UT_TLS_TLS12_RFC5246_CONSISTENCY_RECV_EXPORT_RESTRICTION_RESERVED_ALERT_TC002(void) { FRAME_Init(); HITLS_Config *config = NULL; FRAME_LinkObj *client = NULL; FRAME_LinkObj *server = NULL; FRAME_Msg recvframeMsg = { 0 }; FRAME_Msg sndframeMsg = { 0 }; /* Use the default configuration items to configure the client and server. */ config = HITLS_CFG_NewTLS12Config(); 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, 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); /* When the server receives the client keyexchange, the client sends the export_restriction_RESERVED alarm, check * the message returned by the server. */ ASSERT_TRUE(FRAME_CreateConnection(client, server, false, TRY_RECV_CLIENT_KEY_EXCHANGE) == HITLS_SUCCESS); ASSERT_TRUE(clientTlsCtx->state == CM_STATE_HANDSHAKING); recvframeMsg.type = REC_TYPE_ALERT; recvframeMsg.version = HITLS_VERSION_TLS12; recvframeMsg.bodyLen = ALERT_BODY_LEN; recvframeMsg.epochSeq = GetEpochSeq(0, 5); recvframeMsg.body.alertMsg.level = ALERT_LEVEL_WARNING; recvframeMsg.body.alertMsg.description = ALERT_EXPORT_RESTRICTION_RESERVED; ASSERT_TRUE(PackFrameMsg(&recvframeMsg) == HITLS_SUCCESS); FrameUioUserData *ioUserData = BSL_UIO_GetUserData(server->io); ioUserData->recMsg.len = 0; ASSERT_TRUE(FRAME_TransportRecMsg(server->io, recvframeMsg.buffer, recvframeMsg.len) == HITLS_SUCCESS); ioUserData->sndMsg.len = 0; ASSERT_TRUE(HITLS_Accept(serverTlsCtx) == HITLS_REC_NORMAL_RECV_BUF_EMPTY); EXIT: CleanRecordBody(&recvframeMsg); CleanRecordBody(&sndframeMsg); HITLS_CFG_FreeConfig(config); FRAME_FreeLink(client); FRAME_FreeLink(server); } /* END_CASE */ /* @ * @test UT_TLS1_2_RFC5246_SERVER_CHOSE_VERSION_TC002 * @spec - * @title Check the TLS protocol version carried in the serverHello message. * @brief 1. Use the configuration items to configure the client and server. Change the record version in client hello * to 0x0305 Expected result 1 is obtained. * 2. Obtain and parse the server Hello message. Expected result 2 is obtained. * @expect 1. The initialization is successful. * 2. The protocol version carried in the server Hello message is TLS1.2. * @prior Level 1 * @auto TRUE @ */ /* BEGIN_CASE */ void UT_TLS1_2_RFC5246_SERVER_CHOSE_VERSION_TC002(void) { FRAME_Init(); HITLS_Config *tlsConfig = HITLS_CFG_NewTLS12Config(); ASSERT_TRUE(tlsConfig != NULL); FRAME_LinkObj *client = FRAME_CreateLink(tlsConfig, BSL_UIO_TCP); FRAME_LinkObj *server = FRAME_CreateLink(tlsConfig, BSL_UIO_TCP); HITLS_Ctx *clientTlsCtx = FRAME_GetTlsCtx(client); HITLS_Ctx *serverTlsCtx = FRAME_GetTlsCtx(server); 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; recvBuf[2] = 0x05; ASSERT_EQ(HITLS_Accept(serverTlsCtx), HITLS_REC_NORMAL_IO_BUSY); FRAME_Msg frameMsg = { 0 }; FRAME_Type frameType = { 0 }; uint8_t *sndBuf = ioUserData->sndMsg.msg; uint32_t sndLen = ioUserData->sndMsg.len; uint32_t parseLen = 0; frameType.versionType = HITLS_VERSION_TLS12; 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); FRAME_ServerHelloMsg *serverMsg = &frameMsg.body.hsMsg.body.serverHello; ASSERT_TRUE(serverMsg->version.data == HITLS_VERSION_TLS12); EXIT: HITLS_CFG_FreeConfig(tlsConfig); FRAME_FreeLink(client); FRAME_FreeLink(server); FRAME_CleanMsg(&frameType, &frameMsg); } /* END_CASE */ /* @ * @test UT_TLS_TLS1_2_RFC5246_RENEGOTIATION_RECV_APP_TC001 * @spec - * @title The client receives app after renegotiate request * @precon nan * @brief 1. The client receives app after sending renegotiate request client hello * @expect 1.clien read app message success * @prior Level 1 * @auto TRUE @ */ /* BEGIN_CASE */ void UT_TLS_TLS1_2_RFC5246_RENEGOTIATION_RECV_APP_TC001() { FRAME_Init(); HITLS_Config *tlsConfig = HITLS_CFG_NewTLS12Config(); HITLS_CFG_SetRenegotiationSupport(tlsConfig, 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, HS_STATE_BUTT) == HITLS_SUCCESS); ASSERT_TRUE(HITLS_Renegotiate(clientTlsCtx) == HITLS_SUCCESS); ASSERT_TRUE(HITLS_Connect(clientTlsCtx) == HITLS_REC_NORMAL_RECV_BUF_EMPTY); ASSERT_TRUE(clientTlsCtx->state == CM_STATE_RENEGOTIATION); uint8_t data[] = "Hello World"; uint32_t len; HITLS_Write(server->ssl, data, sizeof(data), &len); ASSERT_TRUE(FRAME_TrasferMsgBetweenLink(server, client) == HITLS_SUCCESS); uint8_t readBuf[READ_BUF_SIZE] = {0}; uint32_t readLen = 0; ASSERT_TRUE(HITLS_Read(clientTlsCtx, readBuf, READ_BUF_SIZE, &readLen) == HITLS_SUCCESS); ASSERT_TRUE(readLen == sizeof(data) && memcmp(data, readBuf, readLen) == 0); EXIT: FRAME_FreeLink(client); FRAME_FreeLink(server); HITLS_CFG_FreeConfig(tlsConfig); } /* END_CASE */ /* @ * @test UT_TLS_TLS1_2_RFC5246_SEND_DATA_BEWTEEN_CCS_AND_FINISH * @spec - * @title The client receives a alert bewteen ccs and finish * @precon nan * @brief 1. Use the configuration items to configure the client and server. Expected result 1 is obtained. * 2. Server send a alert message bewteen ccs and finish. Expected result 2 is obtained. * @expect 1. The initialization is successful. * 2. Client return HITLS_REC_ERR_DATA_BETWEEN_CCS_AND_FINISHED * @prior Level 1 * @auto TRUE @ */ /* BEGIN_CASE */ void UT_TLS_TLS1_2_RFC5246_SEND_DATA_BEWTEEN_CCS_AND_FINISH(void) { FRAME_Init(); HITLS_Config *config = HITLS_CFG_NewTLS12Config(); FRAME_LinkObj *client = FRAME_CreateLink(config, BSL_UIO_TCP); FRAME_LinkObj *server = FRAME_CreateLink(config, BSL_UIO_TCP); ASSERT_EQ(FRAME_CreateConnection(client, server, false, TRY_SEND_FINISH), HITLS_SUCCESS); FrameUioUserData *ioUserData = BSL_UIO_GetUserData(server->io); ioUserData->sndMsg.len = 0; server->ssl->method.sendAlert(server->ssl, ALERT_LEVEL_FATAL, ALERT_CERTIFICATE_EXPIRED); ALERT_Flush(server->ssl); ASSERT_EQ(FRAME_TrasferMsgBetweenLink(server, client), HITLS_SUCCESS); ASSERT_EQ(HITLS_Connect(client->ssl), HITLS_REC_ERR_DATA_BETWEEN_CCS_AND_FINISHED); EXIT: HITLS_CFG_FreeConfig(config); FRAME_FreeLink(client); FRAME_FreeLink(server); } /* END_CASE */ /* @ * @test UT_TLS_TLS1_2_RFC5246_Fragmented_Msg_FUNC_TC001 * @spec - * @title The client receives a Fragmented_Msg during handshake * @precon nan * @brief 1. Use the configuration items to configure the client and server. Expected result 1 is obtained. * 2. Server send a Fragmented_Msg during handshake. Expected result 2 is obtained. * @expect 1. The initialization is successful. * 2. Client return HITLS_REC_ERR_DATA_BETWEEN_CCS_AND_FINISHED * @prior Level 1 * @auto TRUE @ */ // To test whether fragmented messages can be received correctly. Test REC_TlsReadNbytes /* BEGIN_CASE */ void UT_TLS_TLS1_2_RFC5246_Fragmented_Msg_FUNC_TC001(void) { FRAME_Init(); HITLS_Config *config = HITLS_CFG_NewTLS12Config(); ASSERT_TRUE(config != NULL); FRAME_LinkObj *client = FRAME_CreateLink(config, BSL_UIO_TCP); FRAME_LinkObj *server = FRAME_CreateLink(config, BSL_UIO_TCP); ASSERT_TRUE(client != NULL); ASSERT_TRUE(server != NULL); int32_t ret = HITLS_Connect(client->ssl); ASSERT_TRUE(ret == HITLS_REC_NORMAL_RECV_BUF_EMPTY); ASSERT_TRUE(client->ssl->hsCtx->state == TRY_RECV_SERVER_HELLO); ret = HITLS_Accept(server->ssl); ASSERT_TRUE(ret == HITLS_REC_NORMAL_RECV_BUF_EMPTY); ASSERT_TRUE(server->ssl->hsCtx->state == TRY_RECV_CLIENT_HELLO); FrameUioUserData *ioUserData = BSL_UIO_GetUserData(client->io); uint8_t data[MAX_RECORD_LENTH] = {0}; uint32_t dataLen = MAX_RECORD_LENTH; ASSERT_EQ(memcpy_s(data, MAX_RECORD_LENTH, ioUserData->sndMsg.msg, ioUserData->sndMsg.len), 0); dataLen = ioUserData->sndMsg.len; uint32_t msglength = BSL_ByteToUint16(&data[3]); uint32_t msgLen = (msglength - 1) / 2; uint32_t len = 5 + msgLen; uint8_t recorddata1[] = {0x16, 0x03, 0x03, 0x00, 0x46}; BSL_Uint16ToByte((uint16_t)msgLen, &recorddata1[3]); ASSERT_EQ(memcpy_s(ioUserData->sndMsg.msg, MAX_RECORD_LENTH, data, len), 0); ASSERT_EQ(memcpy_s(ioUserData->sndMsg.msg, MAX_RECORD_LENTH, recorddata1, sizeof(recorddata1)), 0); uint8_t recorddata2[] = {0x16, 0x03, 0x03, 0x00, 0x53}; msgLen = dataLen - len; BSL_Uint16ToByte((uint16_t)msgLen, &recorddata2[3]); ASSERT_EQ(memcpy_s(ioUserData->sndMsg.msg + len, MAX_RECORD_LENTH - len, recorddata2, sizeof(recorddata2)), 0); ioUserData->sndMsg.len = len + 5; ASSERT_EQ(memcpy_s(ioUserData->sndMsg.msg + ioUserData->sndMsg.len, MAX_RECORD_LENTH - len, data + len, dataLen - len), 0); ioUserData->sndMsg.len += dataLen - len; ret = HITLS_Connect(client->ssl); ASSERT_TRUE(FRAME_TrasferMsgBetweenLink(client, server) == HITLS_SUCCESS); ret = HITLS_Accept(server->ssl); ASSERT_TRUE(ret == HITLS_REC_NORMAL_IO_BUSY); ret = HITLS_Accept(server->ssl); ASSERT_TRUE(ret == HITLS_REC_NORMAL_IO_BUSY); ASSERT_EQ(FRAME_CreateConnection(client, server, true, HS_STATE_BUTT), HITLS_SUCCESS); ASSERT_TRUE(client->ssl->state == CM_STATE_TRANSPORTING); EXIT: HITLS_CFG_FreeConfig(config); FRAME_FreeLink(client); FRAME_FreeLink(server); } /* END_CASE */ /* @ * @test UT_TLS_TLS1_2_RFC5246_READ_AFTER_CLOSE_TC001 * @spec - * @title There is no alert during the handshake. When the handshake is halfway through, call close to break the chain, * and then call hitls_read to read the plaintext app message. It is expected that the read message failed. * @precon nan * @brief 1. Use the default configuration items to configure the client and server. Expected result 1 is obtained. * 2. Stop the handshake state at TRY_RECV_SERVER_HELLO, expected result 2. * 3. Call the hitls_close interface to break the chain, expected result 3. * 4. Construct plaintext app message, call hitls_read to read, expected result 4. * @expect 1. The initialization is successful. * 2. Return successful. * 3. Return successful. * 4. Reading message failed. * @prior Level 1 * @auto TRUE @ */ /* BEGIN_CASE */ void UT_TLS_TLS1_2_RFC5246_READ_AFTER_CLOSE_TC001() { FRAME_Init(); HITLS_Config *tlsConfig = HITLS_CFG_NewTLS12Config(); 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); ASSERT_TRUE(FRAME_CreateConnection(client, server, true, TRY_RECV_SERVER_HELLO) == HITLS_SUCCESS); ASSERT_TRUE(HITLS_Close(clientTlsCtx) == HITLS_SUCCESS); FrameUioUserData *ioUserData = BSL_UIO_GetUserData(client->io); uint8_t data[] = {0x17, 0x03, 0x03, 0x00, 0x0b, 0x48, 0x65, 0x6c, 0x6c, 0x6f, 0x20, 0x57, 0x6f, 0x72, 0x6c, 0x64}; memcpy_s(ioUserData->recMsg.msg, MAX_RECORD_LENTH, data, sizeof(data)); ioUserData->recMsg.len = sizeof(data); uint8_t readBuf[READ_BUF_SIZE] = {0}; uint32_t readLen = 0; ASSERT_EQ(HITLS_Read(clientTlsCtx, readBuf, READ_BUF_SIZE, &readLen), HITLS_CM_LINK_CLOSED); ASSERT_TRUE(readLen == 0); EXIT: FRAME_FreeLink(client); FRAME_FreeLink(server); HITLS_CFG_FreeConfig(tlsConfig); } /* END_CASE */ /* @ * @test UT_TLS_TLS1_2_RFC5246_READ_AFTER_CLOSE_TC002 * @spec - * @title A fatal alert occurred during the handshake process. Call close to break the chain, * and then call hitls_read to read the plaintext app message. It is expected that the read message failed. * @precon nan * @brief 1. Use the default configuration items to configure the client and server. Expected result 1 is obtained. * 2. Certificate and algorithm set do not match, establish connection, expected result 2. * 3. Call the hitls_close interface to break the chain, expected result 3. * 4. Construct plaintext app message, call hitls_read to read, expected result 4. * @expect 1. The initialization is successful. * 2. Send a fatal alert, ALERT_BAD_CERTIFICATE. * 3. Return successful. * 4. Reading message failed. * @prior Level 1 * @auto TRUE @ */ /* BEGIN_CASE */ void UT_TLS_TLS1_2_RFC5246_READ_AFTER_CLOSE_TC002() { FRAME_Init(); HITLS_Config *tlsConfig = HITLS_CFG_NewTLS12Config(); ASSERT_TRUE(tlsConfig != NULL); uint16_t cipherSuits[] = {HITLS_RSA_WITH_AES_128_CBC_SHA256}; HITLS_CFG_SetCipherSuites(tlsConfig, cipherSuits, sizeof(cipherSuits) / sizeof(uint16_t)); FRAME_CertInfo certInfo = { "rsa_sha512/root.der", "rsa_sha512/intca.der", "rsa_sha512/usageKeyEncipher.der", 0, "rsa_sha512/usageKeyEncipher.key.der", 0, }; FRAME_LinkObj *client = FRAME_CreateLink(tlsConfig, BSL_UIO_TCP); FRAME_LinkObj *server = FRAME_CreateLinkWithCert(tlsConfig, BSL_UIO_TCP, &certInfo); ASSERT_TRUE(client != NULL); ASSERT_TRUE(server != NULL); HITLS_Ctx *clientTlsCtx = FRAME_GetTlsCtx(client); clientTlsCtx->config.tlsConfig.needCheckKeyUsage = true; ASSERT_EQ(FRAME_CreateConnection(client, server, true, HS_STATE_BUTT), HITLS_CERT_ERR_KEYUSAGE); ALERT_Info alertInfo = { 0 }; ALERT_GetInfo(client->ssl, &alertInfo); ASSERT_EQ(alertInfo.level, ALERT_LEVEL_FATAL); ASSERT_EQ(alertInfo.description, ALERT_UNSUPPORTED_CERTIFICATE); ASSERT_TRUE(HITLS_Close(clientTlsCtx) == HITLS_SUCCESS); FrameUioUserData *ioUserData = BSL_UIO_GetUserData(client->io); uint8_t data[] = {0x17, 0x03, 0x03, 0x00, 0x0b, 0x48, 0x65, 0x6c, 0x6c, 0x6f, 0x20, 0x57, 0x6f, 0x72, 0x6c, 0x64}; memcpy_s(ioUserData->recMsg.msg, MAX_RECORD_LENTH, data, sizeof(data)); ioUserData->recMsg.len = sizeof(data); uint8_t readBuf[READ_BUF_SIZE] = {0}; uint32_t readLen = 0; ASSERT_EQ(HITLS_Read(clientTlsCtx, readBuf, READ_BUF_SIZE, &readLen), HITLS_CM_LINK_CLOSED); ASSERT_TRUE(readLen == 0); EXIT: FRAME_FreeLink(client); FRAME_FreeLink(server); HITLS_CFG_FreeConfig(tlsConfig); } /* END_CASE */ int32_t STUB_HS_DoHandshake_Warning(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_NO_CERTIFICATE_RESERVED); return HITLS_INTERNAL_EXCEPTION; } static int32_t UioWriteException(BSL_UIO *uio, const void *buf, uint32_t len, uint32_t *writeLen) { (void)uio; (void)buf; (void)len; (void)writeLen; return BSL_UIO_IO_EXCEPTION; } /* @ * @test UT_TLS_TLS1_2_RFC5246_READ_AFTER_CLOSE_TC003 * @spec - * @title During the handshake process, a warning alert occurred, and the construction of the alert failed to send. The * status then changed to alerting, call close to break the chain, and then call hitls_read to read the plaintext app * message. It is expected that the read message failed. * @precon nan * @brief 1. Use the default configuration items to configure the client and server. Expected result 1 is obtained. * 2. Suspend the sending of warning alerts, expected result 2. * 3. Call the hitls_close interface to break the chain, expected result 3. * 4. Construct plaintext app message, call hitls_read to read, expected result 4. * @expect 1. The initialization is successful. * 2. The status then changed to alerting. * 3. Return successful. * 4. Reading message failed. * @prior Level 1 * @auto TRUE @ */ /* BEGIN_CASE */ void UT_TLS_TLS1_2_RFC5246_READ_AFTER_CLOSE_TC003() { FRAME_Init(); HITLS_Config *tlsConfig = HITLS_CFG_NewTLS12Config(); HITLS_CFG_SetRenegotiationSupport(tlsConfig, 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, true, TRY_RECV_SERVER_KEY_EXCHANGE) == HITLS_SUCCESS); FuncStubInfo tmpRpInfo = { 0 }; STUB_Init(); STUB_Replace(&tmpRpInfo, HS_DoHandshake, STUB_HS_DoHandshake_Warning); BSL_UIO *uio = HITLS_GetReadUio(clientTlsCtx); BSL_UIO_Method *method = (BSL_UIO_Method *)BSL_UIO_GetMethod(uio); ASSERT_EQ(BSL_UIO_SetMethod(method, BSL_UIO_WRITE_CB, UioWriteException), BSL_SUCCESS); ASSERT_TRUE(HITLS_Connect(clientTlsCtx) == HITLS_REC_ERR_IO_EXCEPTION); ASSERT_TRUE(clientTlsCtx->state == CM_STATE_ALERTING); ASSERT_EQ(BSL_UIO_SetMethod(method, BSL_UIO_WRITE_CB, FRAME_Write), BSL_SUCCESS); ASSERT_TRUE(HITLS_Close(clientTlsCtx) == HITLS_REC_NORMAL_IO_BUSY); ASSERT_EQ(FRAME_TrasferMsgBetweenLink(client, server), HITLS_SUCCESS); ASSERT_TRUE(HITLS_Close(clientTlsCtx) == HITLS_SUCCESS); ASSERT_TRUE(clientTlsCtx->state == CM_STATE_CLOSED); FrameUioUserData *ioUserData = BSL_UIO_GetUserData(client->io); uint8_t data[] = {0x17, 0x03, 0x03, 0x00, 0x0b, 0x48, 0x65, 0x6c, 0x6c, 0x6f, 0x20, 0x57, 0x6f, 0x72, 0x6c, 0x64}; memcpy_s(ioUserData->recMsg.msg, MAX_RECORD_LENTH, data, sizeof(data)); ioUserData->recMsg.len = sizeof(data); uint8_t readBuf[READ_BUF_SIZE] = {0}; uint32_t readLen = 0; ASSERT_EQ(HITLS_Read(clientTlsCtx, readBuf, READ_BUF_SIZE, &readLen), HITLS_CM_LINK_CLOSED); ASSERT_TRUE(readLen == 0); EXIT: STUB_Reset(&tmpRpInfo); FRAME_FreeLink(client); FRAME_FreeLink(server); HITLS_CFG_FreeConfig(tlsConfig); } /* END_CASE */ /* @ * @test UT_TLS_TLS1_2_RFC5246_CLIENT_HELLO_ENCRYPT_THEN_MAC_TC001 * @spec - * @title Check the encrypt then mac extension carried in the clientHello message. * @precon nan * @brief 1. Use configuration items to configure the client and server. Expected result 1 is obtained. * 2. Obtain and parse the client Hello message. Expected result 2 is obtained. * @expect 1. The initialization is successful. * 2. The encrypt then mac extension carried in the client Hello message. * @prior Level 1 * @auto TRUE @ */ /* BEGIN_CASE */ void UT_TLS_TLS1_2_RFC5246_CLIENT_HELLO_ENCRYPT_THEN_MAC_TC001(void) { HandshakeTestInfo testInfo = { 0 }; FRAME_Msg frameMsg = { 0 }; FRAME_Type frameType = { 0 }; testInfo.state = TRY_RECV_CLIENT_HELLO; FRAME_Init(); /* Use configuration items to configure the client and server. */ testInfo.config = HITLS_CFG_NewTLS12Config(); ASSERT_TRUE(testInfo.config != NULL); testInfo.client = FRAME_CreateLink(testInfo.config, BSL_UIO_TCP); ASSERT_TRUE(testInfo.client != NULL); ASSERT_EQ(testInfo.client->ssl->config.tlsConfig.isEncryptThenMac, 1); testInfo.server = FRAME_CreateLink(testInfo.config, BSL_UIO_TCP); ASSERT_TRUE(testInfo.server != NULL); ASSERT_EQ(testInfo.server->ssl->config.tlsConfig.isEncryptThenMac, 1); ASSERT_TRUE(FRAME_CreateConnection(testInfo.client, testInfo.server, testInfo.isClient, testInfo.state) == HITLS_SUCCESS); /* Obtain and parse the client Hello message. */ FrameUioUserData *ioUserData = BSL_UIO_GetUserData(testInfo.server->io); uint8_t *recvBuf = ioUserData->recMsg.msg; uint32_t recvLen = ioUserData->recMsg.len; uint32_t parseLen = 0; frameType.versionType = HITLS_VERSION_TLS12; 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; ASSERT_EQ(clientMsg->encryptThenMac.exType.data, HS_EX_TYPE_ENCRYPT_THEN_MAC); EXIT: FRAME_CleanMsg(&frameType, &frameMsg); HITLS_CFG_FreeConfig(testInfo.config); FRAME_FreeLink(testInfo.client); FRAME_FreeLink(testInfo.server); } /* END_CASE */ /* @ * @test UT_TLS_TLS1_2_RFC5246_CLIENT_PSK_FUNC_TC001 * @spec - * @title Client configured with PSK ciphersuite, without PSK callback, clienthello failed to be sent. * @precon nan * @brief 1. Use the default configuration items to configure the client and server. Expected result 1 is obtained. * 2. Set PSK ciphersuite, expected result 2 * 3. Call HITLS_Connect to start handshake, expected result 3 * @expect 1. The initialization is successful. * 2. Return success. * 3. Clienthello send failed, return HITLS_PACK_CLIENT_CIPHER_SUITE_ERR * @prior Level 1 * @auto TRUE @ */ /* BEGIN_CASE */ void UT_TLS_TLS1_2_RFC5246_CLIENT_PSK_FUNC_TC001() { FRAME_Init(); HITLS_Config *config = HITLS_CFG_NewTLS12Config(); ASSERT_TRUE(config != NULL); uint16_t cipherSuits[] = {HITLS_RSA_PSK_WITH_AES_128_CBC_SHA}; HITLS_CFG_SetCipherSuites(config, cipherSuits, sizeof(cipherSuits) / sizeof(uint16_t)); 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(HITLS_Connect(client->ssl), HITLS_PACK_CLIENT_CIPHER_SUITE_ERR); ASSERT_TRUE(client->ssl->hsCtx->state == TRY_SEND_CLIENT_HELLO); EXIT: HITLS_CFG_FreeConfig(config); FRAME_FreeLink(client); FRAME_FreeLink(server); } /* END_CASE */ /* @ * @test UT_TLS_TLS1_2_RFC5246_CLIENT_PSK_FUNC_TC002 * @spec - * @title Client configured with PSK ciphersuite, with PSK callback, server use default config and with PSK callback * configured. Handshake will success. * @precon nan * @brief 1. Use the default configuration items to configure the client and server. Expected result 1 * 2. Set PSK ciphersuite to client and set psk callback to both client and server, expected result 2 * 3. Start handshake, expected result 3 * @expect 1. The initialization is successful. * 2. Return success. * 3. Handshake success. * @prior Level 1 * @auto TRUE @ */ /* BEGIN_CASE */ void UT_TLS_TLS1_2_RFC5246_CLIENT_PSK_FUNC_TC002() { FRAME_Init(); HITLS_Config *c_config = HITLS_CFG_NewTLS12Config(); ASSERT_TRUE(c_config != NULL); HITLS_Config *s_config = HITLS_CFG_NewTLS12Config(); ASSERT_TRUE(s_config != NULL); ASSERT_TRUE(HITLS_CFG_SetPskClientCallback(c_config, ExampleClientCb) == 0); ASSERT_TRUE(HITLS_CFG_SetPskServerCallback(s_config, ExampleServerCb) == 0); uint16_t cipherSuits[] = {HITLS_RSA_PSK_WITH_AES_128_CBC_SHA}; HITLS_CFG_SetCipherSuites(c_config, cipherSuits, sizeof(cipherSuits) / sizeof(uint16_t)); 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); EXIT: HITLS_CFG_FreeConfig(c_config); HITLS_CFG_FreeConfig(s_config); FRAME_FreeLink(client); FRAME_FreeLink(server); } /* END_CASE */
2301_79861745/bench_create
testcode/sdv/testcase/tls/consistency/tls12/test_suite_sdv_frame_tls12_consistency_rfc5246.c
C
unknown
247,867
/* * This file is part of the openHiTLS project. * * openHiTLS is licensed under the Mulan PSL v2. * You can use this software according to the terms and conditions of the Mulan PSL v2. * You may obtain a copy of Mulan PSL v2 at: * * http://license.coscl.org.cn/MulanPSL2 * * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, * EITHER EXPRESS 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 "hitls.h" #include "hitls_config.h" #include "hitls_error.h" #include "bsl_uio.h" #include "bsl_sal.h" #include "tls.h" #include "cert.h" #include "securec.h" #include "frame_msg.h" #include "alert.h" #include "bsl_list.h" #include "app_ctx.h" #include "hs_kx.c" #include "common_func.h" #include "stub_crypt.h" /* END_HEADER */ #define g_uiPort 45678 #define PREMASTERSECRETLEN 1534 /* @ * @test UT_TLS_TLS12_RFC5246_CONSISTENCY_HANDSHAKE_SEND_CERTFICATE_TC001 rfc 5246 table row 51 * @title If the server has sent a CertificateRequest message, the client must send a certificate message. * @precon nan * @brief 1. Use the default configuration items to configure the client and server, and enable the dual-end verification. Expected result 1 is obtained. * 2. The client initiates a TLS over TCP link request. After the server receives the CertificateRequest message, expected result 2 is obtained. * @expect 1. The initialization is successful. * 2. The client is in the TRY_SEND_CLIENT_KEY_EXCHANGE state, and the server is in the TRY_RECV_CERTIFICATIONATE state. @ */ /* BEGIN_CASE */ void UT_TLS_TLS12_RFC5246_CONSISTENCY_HANDSHAKE_SEND_CERTFICATE_TC001(void) { /* Use the default configuration items to configure the client and server, and enable the dual-end verification. */ HandshakeTestInfo testInfo = { 0 }; FRAME_Msg frameMsg = { 0 }; FRAME_Type frameType = { 0 }; testInfo.state = TRY_SEND_SERVER_HELLO_DONE; testInfo.isSupportExtendMasterSecret = true; testInfo.isSupportClientVerify = true; testInfo.isSupportNoClientCert = false; testInfo.isClient = false; ASSERT_TRUE(DefaultCfgStatusParkWithSuite(&testInfo) == HITLS_SUCCESS); frameType.versionType = HITLS_VERSION_TLS12; frameType.recordType = REC_TYPE_HANDSHAKE; frameType.handshakeType = SERVER_HELLO_DONE; 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); ASSERT_TRUE(FRAME_TransportRecMsg(testInfo.client->io, sendBuf, sendLen) == HITLS_SUCCESS); // The client initiates a TLS over TCP link request. ASSERT_EQ(HITLS_Connect(testInfo.client->ssl), HITLS_REC_NORMAL_IO_BUSY); ASSERT_EQ(testInfo.client->ssl->hsCtx->state, TRY_SEND_CLIENT_KEY_EXCHANGE); uint32_t readLen = 0; uint8_t tmp1[MAX_RECORD_LENTH] = {0}; uint32_t tmp1Len = sizeof(tmp1); ASSERT_TRUE(FRAME_TransportSendMsg(testInfo.client->io, tmp1, tmp1Len, &readLen) == HITLS_SUCCESS); ASSERT_EQ(HITLS_Accept(testInfo.server->ssl), HITLS_REC_NORMAL_RECV_BUF_EMPTY); uint8_t tmp2[MAX_RECORD_LENTH] = {0}; uint32_t tmp2Len = sizeof(tmp2); ASSERT_TRUE(FRAME_TransportRecMsg(testInfo.client->io, tmp2, tmp2Len) == HITLS_SUCCESS); ASSERT_TRUE(testInfo.server->ssl->hsCtx->state == TRY_RECV_CERTIFICATE); 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_TLS12_RFC5246_CONSISTENCY_SIGNATION_NOT_SUITABLE_CERT_TC002 * @title During dual-end verification, the server signature algorithm does not match the certificate signature algorithm. As a result, the link fails to be established. * @precon nan * @brief 1. Configure dual-end verification. Set the signature algorithm to RSA_PKCS1_SHA256, cipher suite to RSA, certificate to RSA, and certificate signature to ECDSA_SHA256 on the server. Expected result 1 is obtained. * @expect 1. The link fails to be set up. @ */ /* BEGIN_CASE */ void UT_TLS_TLS12_RFC5246_CONSISTENCY_SIGNATION_NOT_SUITABLE_CERT_TC002(void) { FRAME_Init(); HITLS_Config *config = HITLS_CFG_NewTLS12Config(); ASSERT_TRUE(config != NULL); // 1. Configure dual-end verification. Set the signature algorithm to RSA_PKCS1_SHA256, cipher suite to RSA, certificate to RSA, and certificate signature to ECDSA_SHA256 on the server. uint16_t signAlgs[] = {CERT_SIG_SCHEME_RSA_PKCS1_SHA256}; uint32_t signAlgsSize = sizeof(signAlgs) / sizeof(uint16_t); HITLS_CFG_SetSignature(config, signAlgs, signAlgsSize); HITLS_CFG_SetClientVerifySupport(config, true); uint16_t cipherSuites[] = {HITLS_RSA_WITH_AES_128_GCM_SHA256}; HITLS_CFG_SetCipherSuites(config, cipherSuites, sizeof(cipherSuites) / sizeof(uint16_t)); FRAME_CertInfo certInfoServer = { "ecdsa/ca-nist521.der", "rsa_sha/inter-3072.der", "rsa_sha/end-sha256.der", 0, "rsa_sha/end-sha256.key.der", 0, }; FRAME_CertInfo certInfoClient = { "rsa_sha/ca-3072.der", "ecdsa/inter-nist521.der", "ecdsa/end256-sha256.der", 0, "ecdsa/end256-sha256.key.der", 0, }; FRAME_LinkObj *server = FRAME_CreateLinkWithCert(config, BSL_UIO_TCP, &certInfoServer); ASSERT_TRUE(server != NULL); FRAME_LinkObj *client = FRAME_CreateLinkWithCert(config, BSL_UIO_TCP, &certInfoClient); ASSERT_TRUE(client != NULL); ASSERT_EQ(FRAME_CreateConnection(client, server, true, HS_STATE_BUTT), HITLS_CERT_ERR_VERIFY_CERT_CHAIN); EXIT: HITLS_CFG_FreeConfig(config); FRAME_FreeLink(client); FRAME_FreeLink(server); } /* END_CASE */ /** @ * @test UT_TLS_TLS12_RFC5246_CONSISTENCY_CERTFICATE_VERITY_FAIL_TC003 * @title During dual-end verification, the intermediate certificate is incorrectly configured on the client. As a result, the verification on the server fails. * @precon nan * @brief 1. Configure dual-ended authentication. Configure a correct terminal certificate and an incorrect intermediate certificate on the client. Configure a correct certificate chain on the server. Check whether the server fails the authentication. Expected result 1 is obtained. * @expect 1. The link fails to be set up. @ */ /* BEGIN_CASE */ void UT_TLS_TLS12_RFC5246_CONSISTENCY_CERTFICATE_VERITY_FAIL_TC003(void) { FRAME_Init(); HITLS_Config *config = HITLS_CFG_NewTLS12Config(); ASSERT_TRUE(config != NULL); HITLS_CFG_SetClientVerifySupport(config, true); // 1. Configure dual-ended authentication. Configure a correct terminal certificate and an incorrect intermediate certificate on the client. Configure a correct certificate chain on the server. Check whether the server fails the authentication. FRAME_CertInfo certInfoClient = { "ecdsa/ca-nist521.der", "rsa_sha/inter-3072.der", "ecdsa/end256-sha256.der", 0, "ecdsa/end256-sha256.key.der", 0, }; FRAME_CertInfo certInfoServer = { "ecdsa/ca-nist521.der", "ecdsa/inter-nist521.der", "ecdsa/end256-sha256.der", 0, "ecdsa/end256-sha256.key.der", 0, }; FRAME_LinkObj *client = FRAME_CreateLinkWithCert(config, BSL_UIO_TCP, &certInfoClient); ASSERT_TRUE(client != NULL); FRAME_LinkObj *server = FRAME_CreateLinkWithCert(config, BSL_UIO_TCP, &certInfoServer); ASSERT_TRUE(server != NULL); ASSERT_EQ(FRAME_CreateConnection(client, server, true, HS_STATE_BUTT), HITLS_CERT_ERR_VERIFY_CERT_CHAIN); EXIT: HITLS_CFG_FreeConfig(config); FRAME_FreeLink(client); FRAME_FreeLink(server); } /* END_CASE */ /** @ * @test UT_TLS_TLS12_RFC5246_CONSISTENCY_NEGOTIATE_SIGNATION_FAIL_TC001 * @title Link setup failed because the signature algorithm does not match. * @precon nan * @brief 1. Set the client signature algorithm to ECDSA_SECP256R1_SHA256 and the server certificate signature algorithm to RSA_SHA256. Expected result 1 is obtained. * @expect 1. The link fails to be set up. @ */ /* BEGIN_CASE */ void UT_TLS_TLS12_RFC5246_CONSISTENCY_NEGOTIATE_SIGNATION_FAIL_TC001(void) { FRAME_Init(); HITLS_Config *config = HITLS_CFG_NewTLS12Config(); ASSERT_TRUE(config != NULL); uint16_t signAlgs[] = {CERT_SIG_SCHEME_ECDSA_SECP256R1_SHA256}; uint32_t signAlgsSize = sizeof(signAlgs) / 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", 0, "rsa_sha/end-sha256.key.der", 0, }; FRAME_LinkObj *client = FRAME_CreateLinkWithCert(config, BSL_UIO_TCP, &certInfo); ASSERT_TRUE(client != NULL); FRAME_LinkObj *server = FRAME_CreateLinkWithCert(config, BSL_UIO_TCP, &certInfo); ASSERT_TRUE(server != NULL); // 1. Set the client signature algorithm to ECDSA_SECP256R1_SHA256 and the server certificate signature algorithm to RSA_SHA256. ASSERT_TRUE(HITLS_SetSigalgsList(client->ssl, signAlgs, signAlgsSize) == HITLS_SUCCESS); ASSERT_EQ(FRAME_CreateConnection(client, server, true, HS_STATE_BUTT), HITLS_MSG_HANDLE_CIPHER_SUITE_ERR); EXIT: HITLS_CFG_FreeConfig(config); FRAME_FreeLink(client); FRAME_FreeLink(server); } /* END_CASE */ /** @ * @test UT_TLS_TLS12_RFC5246_CONSISTENCY_SIGNATION_NOT_SUITABLE_CERT_TC001 * @title The certificate signature algorithm does not match the signature algorithm set on the client. As a result, the link fails to be established. * @precon nan * @brief 1. Set the signature algorithm to RSA_PKCS1_SHA256 on the client, cipher suite to RSA, certificate to RSA, server signature algorithm to RSA_PKCS1_SHA256, and certificate signature algorithm to ECDSA_SHA256. Expected Certificate Verification Failure (Failed to Select a Certificate on the Server) * @expect 1. The link fails to be set up. @ */ /* BEGIN_CASE */ void UT_TLS_TLS12_RFC5246_CONSISTENCY_SIGNATION_NOT_SUITABLE_CERT_TC001(void) { FRAME_Init(); HITLS_Config *config = HITLS_CFG_NewTLS12Config(); ASSERT_TRUE(config != NULL); // 1. Set the signature algorithm to RSA_PKCS1_SHA256 on the client, cipher suite to RSA, certificate to RSA, // server signature algorithm to RSA_PKCS1_SHA256, and certificate signature algorithm to ECDSA_SHA256. uint16_t signAlgs[] = {CERT_SIG_SCHEME_RSA_PKCS1_SHA256}; uint32_t signAlgsSize = sizeof(signAlgs) / sizeof(uint16_t); HITLS_CFG_SetSignature(config, signAlgs, signAlgsSize); HITLS_CFG_SetClientVerifySupport(config, true); uint16_t cipherSuites[] = {HITLS_RSA_WITH_AES_128_GCM_SHA256}; HITLS_CFG_SetCipherSuites(config, cipherSuites, sizeof(cipherSuites) / sizeof(uint16_t)); FRAME_CertInfo certInfoClient = { "ecdsa/ca-nist521.der", "rsa_sha/inter-3072.der", "rsa_sha/end-sha256.der", 0, "rsa_sha/end-sha256.key.der", 0, }; FRAME_CertInfo certInfoServer = { "rsa_sha/ca-3072.der", "ecdsa/inter-nist521.der", "ecdsa/end256-sha256.der", 0, "ecdsa/end256-sha256.key.der", 0, }; FRAME_LinkObj *client = FRAME_CreateLinkWithCert(config, BSL_UIO_TCP, &certInfoClient); ASSERT_TRUE(client != NULL); FRAME_LinkObj *server = FRAME_CreateLinkWithCert(config, BSL_UIO_TCP, &certInfoServer); ASSERT_TRUE(server != NULL); ASSERT_EQ(FRAME_CreateConnection(client, server, true, HS_STATE_BUTT), HITLS_CERT_ERR_VERIFY_CERT_CHAIN); EXIT: HITLS_CFG_FreeConfig(config); FRAME_FreeLink(client); FRAME_FreeLink(server); } /* END_CASE */ /** @ * @test UT_TLS_TLS12_RFC5246_CONSISTENCY_CERTFICATE_VERITY_FAIL_TC004 * @title During dual-end authentication, the client certificate is out of order, and the link fails to be established. * @precon nan * @brief 1. Configure dual-end verification. Configure the first certificate on the client as an intermediate certificate and the second certificate as a terminal certificate. Configure a correct certificate chain on the server. Check whether the verification fails on the server. Expected result 1 is obtained. * @expect 1. The link fails to be set up. @ */ /* BEGIN_CASE */ void UT_TLS_TLS12_RFC5246_CONSISTENCY_CERTFICATE_VERITY_FAIL_TC004(void) { FRAME_Init(); HITLS_Config *config = HITLS_CFG_NewTLS12Config(); ASSERT_TRUE(config != NULL); HITLS_CFG_SetClientVerifySupport(config, 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_EQ(FRAME_CreateConnection(client, server, true, TRY_RECV_CERTIFICATE), 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); uint32_t parseLen = 0; FRAME_Msg frameMsg = {0}; FRAME_Type frameType = {0}; frameType.versionType = HITLS_VERSION_TLS12; frameType.recordType = REC_TYPE_HANDSHAKE; frameType.handshakeType = CERTIFICATE; frameType.keyExType = HITLS_KEY_EXCH_ECDHE; ASSERT_TRUE(FRAME_ParseMsg(&frameType, recvBuf, recvLen, &frameMsg, &parseLen) == HITLS_SUCCESS); // Change the certificate sequence. The intermediate certificate is used first, and then the device certificate is used. // 1. Configure dual-end authentication. Configure the first certificate on the client as an intermediate // certificate, and the second certificate as a terminal certificate. Configure a correct certificate chain on the server. frameMsg.body.hsMsg.body.certificate.certItem->cert.state = ASSIGNED_FIELD; frameMsg.body.hsMsg.body.certificate.certItem->certLen.state = ASSIGNED_FIELD; struct FrameCertItem_ *tmp = frameMsg.body.hsMsg.body.certificate.certItem->next; frameMsg.body.hsMsg.body.certificate.certItem->next = tmp->next; // a->c tmp->next = frameMsg.body.hsMsg.body.certificate.certItem; // b -> a frameMsg.body.hsMsg.body.certificate.certItem = tmp; 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 = BSL_UIO_GetUserData(client->io); 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(FRAME_CreateConnection(client, server, true, HS_STATE_BUTT), HITLS_PARSE_VERIFY_SIGN_FAIL); EXIT: FRAME_CleanMsg(&frameType, &frameMsg); HITLS_CFG_FreeConfig(config); FRAME_FreeLink(client); FRAME_FreeLink(server); } /* END_CASE */ static int32_t STUB_SAL_CERT_KeyDecrypt_Fail(const HITLS_CipherParameters *cipher, const uint8_t *in, uint32_t inLen, uint8_t *out, uint32_t *outLen) { (void)cipher; (void)in; (void)inLen; (void)out; (void)outLen; return HITLS_CRYPT_ERR_DECRYPT; } /** @ * @test UT_TLS_TLS12_RFC5246_CONSISTENCY_DECRYPT_FAIL_TC005 * @title After the premasterkey to be received by the server is modified, the connection fails to be established. * @precon nan * @brief 1. Configure the RSA cipher suite. When the server receives the premasterkey, change the value of the premasterkey and construct a decryption failure scenario. It is expected that CCS messages are sent normally and the link fails to be established. Expected result 1 is obtained. * @expect 1. The link fails to be set up. @ */ /* BEGIN_CASE */ void UT_TLS_TLS12_RFC5246_CONSISTENCY_DECRYPT_FAIL_TC005(void) { FRAME_Init(); HITLS_Config *config = HITLS_CFG_NewTLS12Config(); ASSERT_TRUE(config != NULL); HITLS_CFG_SetClientVerifySupport(config, true); // 1.Configure the RSA cipher suite. Change the value of the premasterkey when the server receives the premasterkey. // Construct a decryption failure scenario. The CCS message is expected to be sent normally. uint16_t cipherSuits[] = {HITLS_RSA_WITH_AES_128_GCM_SHA256}; HITLS_CFG_SetCipherSuites(config, cipherSuits, sizeof(cipherSuits) / sizeof(uint16_t)); 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, TRY_RECV_CLIENT_KEY_EXCHANGE), HITLS_SUCCESS); STUB_Init(); FuncStubInfo tmpStubInfo; STUB_Replace(&tmpStubInfo, SAL_CERT_KeyDecrypt, STUB_SAL_CERT_KeyDecrypt_Fail); ASSERT_EQ(HITLS_Accept(server->ssl), HITLS_REC_NORMAL_RECV_BUF_EMPTY); STUB_Reset(&tmpStubInfo); ASSERT_EQ(FRAME_CreateConnection(client, server, false, HS_STATE_BUTT), HITLS_REC_BAD_RECORD_MAC); ALERT_Info alertInfo = { 0 }; ALERT_GetInfo(server->ssl, &alertInfo); ASSERT_EQ(alertInfo.level, ALERT_LEVEL_FATAL); ASSERT_EQ(alertInfo.description, ALERT_BAD_RECORD_MAC); EXIT: HITLS_CFG_FreeConfig(config); FRAME_FreeLink(client); FRAME_FreeLink(server); } /* END_CASE */ /** @ * @test UT_TLS_TLS12_RFC5246_CONSISTENCY_KEYUSAGE_CERT_TC003 * @title The certificate carries the correct keyuage extension, and the link is successfully established. * @precon nan * @brief 1. Configure the server certificate with the keyuage extension and support digitalSignature. The link is successfully established. Expected result 1 is obtained. * @expect 1. The link is set up successfully. @ */ /* BEGIN_CASE */ void UT_TLS_TLS12_RFC5246_CONSISTENCY_KEYUSAGE_CERT_TC003(void) { FRAME_Init(); HITLS_Config *config = HITLS_CFG_NewTLS12Config(); ASSERT_TRUE(config != NULL); HITLS_CFG_SetClientVerifySupport(config, true); // 1. Set the server certificate with the keyuage extension and support digitalSignature. 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, true, HS_STATE_BUTT), HITLS_SUCCESS); EXIT: HITLS_CFG_FreeConfig(config); FRAME_FreeLink(client); FRAME_FreeLink(server); } /* END_CASE */ /** @ * @test UT_TLS_TLS12_RFC5246_CONSISTENCY_RENEGOTIATION_UNSUPPORTED_TC001 * @title Invoke the hitls_connect/hitls_accept interface to initiate renegotiation. The peer end does not support renegotiation. * @precon nan * @brief 1. Invoke the hitls_renegotiate interface to initiate renegotiation. Expected result 1 is obtained. 2. Invoke the hitls_connect/hitls_accept interface to initiate renegotiation. The peer end does not support renegotiation. Expected result 2 is obtained. * @expect 1. The link enters the renegotiation state. 2. The peer end returns a warning alert. @ */ /* BEGIN_CASE */ void UT_TLS_TLS12_RFC5246_CONSISTENCY_RENEGOTIATION_UNSUPPORTED_TC001() { FRAME_Init(); HITLS_Config *config = HITLS_CFG_NewTLS12Config(); 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); HITLS_SetClientRenegotiateSupport(server->ssl, true); ASSERT_TRUE(FRAME_CreateConnection(client, server, false, HS_STATE_BUTT) == HITLS_SUCCESS); ASSERT_TRUE(server->ssl->state == CM_STATE_TRANSPORTING); ASSERT_TRUE(client->ssl->state == CM_STATE_TRANSPORTING); HITLS_SetRenegotiationSupport(client->ssl, true); // 1. Invoke the hitls_renegotiate interface to initiate renegotiation. ASSERT_TRUE(HITLS_Renegotiate(client->ssl) == HITLS_SUCCESS); // Invoke the hitls_connect/hitls_accept interface to initiate renegotiation. The peer end does not support renegotiation. ASSERT_TRUE(HITLS_Connect(client->ssl) == HITLS_REC_NORMAL_RECV_BUF_EMPTY); ASSERT_EQ(client->ssl->state, CM_STATE_RENEGOTIATION); 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_REC_NORMAL_RECV_BUF_EMPTY); // Send a warning alert and ALERT_NO_RENEGOTIATION message. After receiving the message, the peer send fatal alert. ASSERT_TRUE(FRAME_TrasferMsgBetweenLink(server, client) == HITLS_SUCCESS); ASSERT_EQ(HITLS_Connect(client->ssl), HITLS_REC_NORMAL_RECV_UNEXPECT_MSG); ASSERT_EQ(client->ssl->state, CM_STATE_ALERTED); EXIT: HITLS_CFG_FreeConfig(config); FRAME_FreeLink(client); FRAME_FreeLink(server); } /* END_CASE */ static int32_t Stub_GenPremasterSecretFromEcdhe(TLS_Ctx *ctx, uint8_t *preMasterSecret, uint32_t *preMasterSecretLen) { int32_t ret = SAL_CRYPT_CalcEcdhSharedSecret(LIBCTX_FROM_CTX(ctx), ATTRIBUTE_FROM_CTX(ctx), ctx->hsCtx->kxCtx->key, ctx->hsCtx->kxCtx->peerPubkey, ctx->hsCtx->kxCtx->pubKeyLen, preMasterSecret, preMasterSecretLen); *preMasterSecretLen = PREMASTERSECRETLEN; return ret; } /** @ * @test UT_TLS_TLS12_RFC5246_CONSISTENCY_ECDHE_PSK_TC001 * @title After the premasterkey to be received by the server is modified, the connection fails to be established. * @precon nan * @brief 1. Configure the PSK cipher suite. When generating the premasterkey, change the preMasterSecretLen parameter of GenPremasterSecretFromEcdhe to 1534 to reach the maximum value of the secret and check whether it is out of bounds. * @expect 1. The link success. @ */ /* BEGIN_CASE */ void UT_TLS_TLS12_RFC5246_CONSISTENCY_ECDHE_PSK_TC001(void) { FRAME_Init(); HITLS_Config *config = HITLS_CFG_NewTLS12Config(); ASSERT_TRUE(config != NULL); uint16_t cipherSuits[] = {HITLS_ECDHE_PSK_WITH_AES_128_CBC_SHA}; ASSERT_TRUE( HITLS_CFG_SetCipherSuites(config, cipherSuits, sizeof(cipherSuits) / sizeof(uint16_t)) == HITLS_SUCCESS); ASSERT_TRUE(HITLS_CFG_SetPskClientCallback(config, ExampleClientCb) == HITLS_SUCCESS); ASSERT_TRUE(HITLS_CFG_SetPskServerCallback(config, ExampleServerCb) == 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); STUB_Init(); FuncStubInfo tmpStubInfo; STUB_Replace(&tmpStubInfo, GenPremasterSecretFromEcdhe, Stub_GenPremasterSecretFromEcdhe); ASSERT_EQ(FRAME_CreateConnection(client, server, false, HS_STATE_BUTT), HITLS_SUCCESS); EXIT: STUB_Reset(&tmpStubInfo); HITLS_CFG_FreeConfig(config); FRAME_FreeLink(client); FRAME_FreeLink(server); } /* END_CASE */ /** @ * @test UT_TLS_TLS12_RFC5246_RSA_REMASTER_TC001 * @title After the premasterkey to be received by the server is modified, the connection fails to be established. * @precon nan * @brief 1. Configure the RSA cipher suite. When the server receives the premasterkey, change the value of the premasterkey and construct a decryption failure scenario. It is expected that CCS messages are sent normally and the link fails to be established. Expected result 1 is obtained. * @expect 1. The link fails to be set up. @ */ /* BEGIN_CASE */ void UT_TLS_TLS12_RFC5246_RSA_REMASTER_TC001(int rsaEncryptLen) { FRAME_Init(); HITLS_Config *config = HITLS_CFG_NewTLS12Config(); ASSERT_TRUE(config != NULL); HITLS_CFG_SetClientVerifySupport(config, false); // 1.Configure the RSA cipher suite. Change the value of the premasterkey when the server receives the premasterkey. // Construct a decryption failure scenario. The CCS message is expected to be sent normally. uint16_t cipherSuits[] = {HITLS_RSA_WITH_AES_128_GCM_SHA256}; HITLS_CFG_SetCipherSuites(config, cipherSuits, sizeof(cipherSuits) / sizeof(uint16_t)); 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, TRY_RECV_CLIENT_KEY_EXCHANGE), 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); uint32_t parseLen = 0; FRAME_Msg frameMsg = {0}; FRAME_Type frameType = {0}; frameType.versionType = HITLS_VERSION_TLS12; frameType.recordType = REC_TYPE_HANDSHAKE; frameType.handshakeType = CLIENT_KEY_EXCHANGE; frameType.keyExType = HITLS_KEY_EXCH_RSA; ASSERT_TRUE(FRAME_ParseMsg(&frameType, recvBuf, recvLen, &frameMsg, &parseLen) == HITLS_SUCCESS); frameMsg.body.hsMsg.body.clientKeyExchange.pubKeySize.data = rsaEncryptLen; BSL_SAL_FREE(frameMsg.body.hsMsg.body.clientKeyExchange.pubKey.data); frameMsg.body.hsMsg.body.clientKeyExchange.pubKey.data = BSL_SAL_Calloc(1,rsaEncryptLen); frameMsg.body.hsMsg.body.clientKeyExchange.pubKey.size = rsaEncryptLen; uint32_t sendLen = MAX_RECORD_LENTH; ASSERT_TRUE(FRAME_PackMsg(&frameType, &frameMsg, recvBuf, sendLen, &sendLen) == HITLS_SUCCESS); ioUserData->recMsg.len = sendLen; HITLS_Accept(server->ssl); ASSERT_EQ(FRAME_CreateConnection(client, server, false, HS_STATE_BUTT), HITLS_REC_BAD_RECORD_MAC); ALERT_Info alertInfo = { 0 }; ALERT_GetInfo(server->ssl, &alertInfo); ASSERT_EQ(alertInfo.level, ALERT_LEVEL_FATAL); ASSERT_EQ(alertInfo.description, ALERT_BAD_RECORD_MAC); EXIT: FRAME_CleanMsg(&frameType, &frameMsg); HITLS_CFG_FreeConfig(config); FRAME_FreeLink(client); FRAME_FreeLink(server); } /* END_CASE */ /** @ * @test UT_TLS_TLS12_RFC5246_CONSISTENCY_KEYUSAGE_CERT_TC004 * @title The certificate without keyuage extension, and the link is successfully established. * @precon nan * @brief 1. Configure the server certificate without keyuage extension and support CheckKeyUsage. The link is successfully established. Expected result 1 is obtained. * @expect 1. The link is set up successfully. @ */ /* BEGIN_CASE */ void UT_TLS_TLS12_RFC5246_CONSISTENCY_KEYUSAGE_CERT_TC004(int isCheckKeyUsage) { FRAME_Init(); HITLS_Config *config = HITLS_CFG_NewTLS12Config(); ASSERT_TRUE(config != NULL); uint16_t cipherSuits[] = {HITLS_RSA_WITH_AES_128_CBC_SHA256}; ASSERT_TRUE( HITLS_CFG_SetCipherSuites(config, cipherSuits, sizeof(cipherSuits) / sizeof(uint16_t)) == HITLS_SUCCESS); HITLS_CFG_SetClientVerifySupport(config, true); FRAME_CertInfo certInfoClient = { "rsa_sha256/ca.der", "rsa_sha256/inter.der", "rsa_sha256/client.der", 0, "rsa_sha256/client.key.der", 0, }; FRAME_CertInfo certInfoServer = { "rsa_sha256/ca.der", "rsa_sha256/inter.der", "rsa_sha256/server.der", 0, "rsa_sha256/server.key.der", 0, }; FRAME_LinkObj *client = FRAME_CreateLinkWithCert(config, BSL_UIO_TCP, &certInfoClient); ASSERT_TRUE(client != NULL); FRAME_LinkObj *server = FRAME_CreateLinkWithCert(config, BSL_UIO_TCP, &certInfoServer); ASSERT_TRUE(server != NULL); if (isCheckKeyUsage) { HITLS_SetCheckKeyUsage(client->ssl, true); } else { HITLS_SetCheckKeyUsage(client->ssl, false); } 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_TLS12_RFC5246_CONSISTENCY_EXTRA_CHAIN_CERT_TC001 * @title Set the intermediate certificates separately to the extra_chain and the chain, where the correct intermediate certificate is stored in the extra_chain and the incorrect intermediate certificate is stored in the chain, proving that the priority of the chain is higher than that of extra_chain. * @precon nan * @brief 1. Use the default configuration items to configure the client and server. Expected result 1 is obtained. 2. Analyze valid and invalid intermediate certificates separately. Expected result 2 is obtained. 3. Set valid intermediate certificates to extra_chain and invalid intermediate certificates to chain. Expected result 3 is obtained. 4. Continue to establish the link. Expected result 4 is obtained. * @expect 1. The initialization is successful. 2. The parsing was successful. 3. Successfully set up. 4. establish the link failed, returned HITLS_CERT_ERR_VERIFY_CERT_CHAIN, proving that the priority of the chain is higher than extra_chain. @ */ /* BEGIN_CASE */ void UT_TLS_TLS12_RFC5246_CONSISTENCY_EXTRA_CHAIN_CERT_TC001() { FRAME_Init(); HITLS_Config *config_c = HITLS_CFG_NewTLS12Config(); ASSERT_TRUE(config_c != NULL); HITLS_Config *config_s = HITLS_CFG_NewTLS12Config(); ASSERT_TRUE(config_s != NULL); HITLS_CFG_SetVerifyNoneSupport(config_c, false); char invalidIntCaFile[] = "../testdata/tls/certificate/der/ecdsa_sha256/inter.der"; char validIntCaFile[] = "../testdata/tls/certificate/der/rsa_sha256/inter.der"; HITLS_CERT_X509 *invalidIntCa = HITLS_CFG_ParseCert(config_s, (const uint8_t *)invalidIntCaFile, strlen(invalidIntCaFile) + 1, TLS_PARSE_TYPE_FILE, TLS_PARSE_FORMAT_ASN1); HITLS_CERT_X509 *validIntCa = HITLS_CFG_ParseCert(config_s, (const uint8_t *)validIntCaFile, strlen(validIntCaFile) + 1, TLS_PARSE_TYPE_FILE, TLS_PARSE_FORMAT_ASN1); ASSERT_TRUE(invalidIntCa != NULL); ASSERT_TRUE(validIntCa != NULL); FRAME_CertInfo certInfoClient = { "rsa_sha256/ca.der", 0, "rsa_sha256/client.der", 0, "rsa_sha256/client.key.der", 0, }; FRAME_CertInfo certInfoServer = { "rsa_sha256/ca.der", 0, "rsa_sha256/server.der", 0, "rsa_sha256/server.key.der", 0, }; FRAME_LinkObj *client = FRAME_CreateLinkWithCert(config_c, BSL_UIO_TCP, &certInfoClient); ASSERT_TRUE(client != NULL); FRAME_LinkObj *server = FRAME_CreateLinkWithCert(config_s, BSL_UIO_TCP, &certInfoServer); ASSERT_TRUE(server != NULL); ASSERT_TRUE(HITLS_CFG_AddChainCert(&server->ssl->config.tlsConfig, invalidIntCa, false) == HITLS_SUCCESS); ASSERT_TRUE(HITLS_CFG_AddExtraChainCert(&server->ssl->config.tlsConfig, validIntCa) == HITLS_SUCCESS); HITLS_CERT_Chain *extraChainCert = HITLS_CFG_GetExtraChainCerts(&server->ssl->config.tlsConfig); ASSERT_TRUE(extraChainCert->count == 1); ASSERT_TRUE(extraChainCert != NULL); ASSERT_EQ(FRAME_CreateConnection(client, server, true, HS_STATE_BUTT), HITLS_CERT_ERR_VERIFY_CERT_CHAIN); EXIT: HITLS_CFG_FreeConfig(config_c); HITLS_CFG_FreeConfig(config_s); FRAME_FreeLink(client); FRAME_FreeLink(server); } /* END_CASE */ /** @ * @test UT_TLS_TLS12_RFC5246_CONSISTENCY_EXTRA_CHAIN_CERT_TC002 * @title Set the intermediate certificates separately to the extra_chain and store, where the correct intermediate certificate is stored in the extra_chain and the incorrect intermediate certificate is stored in the store, proving that the priority of extra_chain is higher than that of the store. * @precon nan * @brief 1. Use the default configuration items to configure the client and server. Expected result 1 is obtained. 2. Analyze valid and invalid intermediate certificates separately Expected result 2 is obtained. 3. Set valid intermediate certificates to extra_chain and invalid intermediate certificates to store. Expected result 3 is obtained. 4. Continue to establish the link. Expected result 4 is obtained. * @expect 1. The initialization is successful. 2. The parsing was successful. 3. Successfully set up. 4. The link is set up successfullyl, returns HITLS_SUCCESS, proving that extra_chain has a higher priority than store. @ */ /* BEGIN_CASE */ void UT_TLS_TLS12_RFC5246_CONSISTENCY_EXTRA_CHAIN_CERT_TC002() { FRAME_Init(); HITLS_Config *config_c = HITLS_CFG_NewTLS12Config(); ASSERT_TRUE(config_c != NULL); HITLS_Config *config_s = HITLS_CFG_NewTLS12Config(); ASSERT_TRUE(config_s != NULL); HITLS_CFG_SetVerifyNoneSupport(config_c, false); char validIntCaFile[] = "../testdata/tls/certificate/der/rsa_sha256/inter.der"; HITLS_CERT_X509 *validIntCa = HITLS_CFG_ParseCert(config_s, (const uint8_t *)validIntCaFile, strlen(validIntCaFile) + 1, TLS_PARSE_TYPE_FILE, TLS_PARSE_FORMAT_ASN1); ASSERT_TRUE(validIntCa != NULL); FRAME_CertInfo certInfoClient = { "rsa_sha256/ca.der", 0, "rsa_sha256/client.der", 0, "rsa_sha256/client.key.der", 0, }; FRAME_CertInfo certInfoServer = { "rsa_sha256/ca.der", "ecdsa_sha256/inter.der", "rsa_sha256/server.der", 0, "rsa_sha256/server.key.der", 0, }; FRAME_LinkObj *client = FRAME_CreateLinkWithCert(config_c, BSL_UIO_TCP, &certInfoClient); ASSERT_TRUE(client != NULL); FRAME_LinkObj *server = FRAME_CreateLinkWithCert(config_s, BSL_UIO_TCP, &certInfoServer); ASSERT_TRUE(server != NULL); ASSERT_TRUE(HITLS_CFG_AddExtraChainCert(&server->ssl->config.tlsConfig, validIntCa) == HITLS_SUCCESS); HITLS_CERT_Chain *extraChainCert = HITLS_CFG_GetExtraChainCerts(&server->ssl->config.tlsConfig); ASSERT_TRUE(extraChainCert->count == 1); ASSERT_TRUE(extraChainCert != 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_TLS12_RFC5246_CONSISTENCY_BUILD_CERT_CHAIN_TC001 * @title * @precon Set up a certificate chain from the chain, but there is no certificate in the chain chain. There is a certificate in the store, and it is expected that the connection will be successfully established. * @brief 1. Use the default configuration items to configure the client and server. Expected result 1 is obtained. 2. Load the intermediate certificate into the store. Expected result 2 is obtained. 3. Call the HITLS_CFG_BuildCertChain function to group the certificate chain, set the flag to HITLS_SBILD_CHAIN_LAGCHECK . Expected result 3 is obtained. 4. Continue to establish the link. Expected result 4 is obtained. * @expect 1. The initialization is successful. 2. Successfully set up. 3. Return success. 4. The link is set up successfullyl, returns HITLS_SUCCESS. @ */ /* BEGIN_CASE */ void UT_TLS_TLS12_RFC5246_CONSISTENCY_BUILD_CERT_CHAIN_TC001() { #ifdef HITLS_TLS_CONFIG_CERT_BUILD_CHAIN FRAME_Init(); HITLS_Config *config_c = HITLS_CFG_NewTLS12Config(); ASSERT_TRUE(config_c != NULL); HITLS_Config *config_s = HITLS_CFG_NewTLS12Config(); ASSERT_TRUE(config_s != NULL); HITLS_CFG_SetVerifyNoneSupport(config_c, false); FRAME_CertInfo certInfoClient = { "rsa_sha256/ca.der", "rsa_sha256/inter.der", "rsa_sha256/client.der", 0, "rsa_sha256/client.key.der", 0, }; FRAME_CertInfo certInfoServer = { "rsa_sha256/ca.der", "rsa_sha256/inter.der", "rsa_sha256/server.der", 0, "rsa_sha256/server.key.der", 0, }; FRAME_LinkObj *client = FRAME_CreateLinkWithCert(config_c, BSL_UIO_TCP, &certInfoClient); ASSERT_TRUE(client != NULL); FRAME_LinkObj *server = FRAME_CreateLinkWithCert(config_s, BSL_UIO_TCP, &certInfoServer); ASSERT_TRUE(server != NULL); ASSERT_TRUE(HITLS_CFG_BuildCertChain(&server->ssl->config.tlsConfig, HITLS_BUILD_CHAIN_FLAG_CHECK) == HITLS_SUCCESS); 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); #endif } /* END_CASE */ /** @ * @test UT_TLS_TLS12_RFC5246_CONSISTENCY_BUILD_CERT_CHAIN_TC002 * @title Set up a certificate chain from the store, but there is no certificate in the store. There is a certificate in the chain, and it is expected that the chain will be empty after the chain is formed, resulting in a connection failure. * @precon nan * @brief 1. Use the default configuration items to configure the client and server. Expected result 1 is obtained. 2. Set the intermediate certificate to the chain, but there are no certificates in the Cert_store and Chain_store. Expected result 2 is obtained. 3. Call HITLS_CFG_BuildCertChain to group the certificate chain and set the flag to 0. Expected result 3 is obtained. 4. Continue to establish the link. Expected result 4 is obtained. * @expect 1. The initialization is successful. 2. Successfully set up. 3. Return success. 4. Failed to establish connection. @ */ /* BEGIN_CASE */ void UT_TLS_TLS12_RFC5246_CONSISTENCY_BUILD_CERT_CHAIN_TC002() { #ifdef HITLS_TLS_CONFIG_CERT_BUILD_CHAIN FRAME_Init(); HITLS_Config *config_c = HITLS_CFG_NewTLS12Config(); ASSERT_TRUE(config_c != NULL); HITLS_Config *config_s = HITLS_CFG_NewTLS12Config(); ASSERT_TRUE(config_s != NULL); HITLS_CFG_SetVerifyNoneSupport(config_c, false); char rootCaFile[] = "../testdata/tls/certificate/der/rsa_sha256/ca.der"; char intCaFile[] = "../testdata/tls/certificate/der/rsa_sha256/inter.der"; HITLS_CERT_X509 *rootCa = HITLS_CFG_ParseCert(config_s, (const uint8_t *)rootCaFile, strlen(rootCaFile) + 1, TLS_PARSE_TYPE_FILE, TLS_PARSE_FORMAT_ASN1); ASSERT_TRUE(rootCa != NULL); HITLS_CERT_X509 *intCa = HITLS_CFG_ParseCert(config_s, (const uint8_t *)intCaFile, strlen(intCaFile) + 1, TLS_PARSE_TYPE_FILE, TLS_PARSE_FORMAT_ASN1); ASSERT_TRUE(intCa != NULL); HITLS_CERT_Store *store = SAL_CERT_StoreNew(config_s->certMgrCtx); ASSERT_TRUE(store != NULL); SAL_CERT_StoreCtrl(config_s, store, CERT_STORE_CTRL_ADD_CERT_LIST, rootCa, NULL); HITLS_CFG_SetVerifyStore(config_s, store, 0); FRAME_CertInfo certInfoClient = { "rsa_sha256/ca.der", 0, "rsa_sha256/server.der", 0, "rsa_sha256/server.key.der", 0, }; FRAME_CertInfo certInfoServer = { 0, 0, "rsa_sha256/server.der", 0, "rsa_sha256/server.key.der", 0, }; FRAME_LinkObj *client = FRAME_CreateLinkWithCert(config_c, BSL_UIO_TCP, &certInfoClient); ASSERT_TRUE(client != NULL); FRAME_LinkObj *server = FRAME_CreateLinkWithCert(config_s, BSL_UIO_TCP, &certInfoServer); ASSERT_TRUE(server != NULL); ASSERT_TRUE(HITLS_CFG_AddChainCert(&server->ssl->config.tlsConfig, intCa, false) == HITLS_SUCCESS); ASSERT_TRUE(HITLS_CFG_BuildCertChain(&server->ssl->config.tlsConfig, 0) == HITLS_SUCCESS); ASSERT_EQ(FRAME_CreateConnection(client, server, true, HS_STATE_BUTT), HITLS_CERT_ERR_VERIFY_CERT_CHAIN); EXIT: HITLS_CFG_FreeConfig(config_c); HITLS_CFG_FreeConfig(config_s); FRAME_FreeLink(client); FRAME_FreeLink(server); #endif } /* END_CASE */ /** @ * @test UT_TLS_TLS12_RFC5246_CONSISTENCY_BUILD_CERT_CHAIN_TC003 * @title Set up a certificate chain from the chain, where there are multiple certificates and unrelated certificates. It is expected that after the chain is formed, only the certificates that make up the certificate chain will be present, and the connection will be successfully established. * @precon nan * @brief 1. Use the default configuration items to configure the client and server. Expected result 1 is obtained. 2. Load 2 different intermediate certificates into the chain, and there is only 1 available intermediate certificate. Expected result 2 is obtained. 3. Call the HITLS_CFG_BuildCertChain function to group the certificate chain, set the flag to HITLS_SBILD_CHAIN_LAGCHECK , Obtain the number of certificates in the chain after the chain is formed. Expected result 3 is obtained. 4. Continue to establish the link. Expected result 4 is obtained. * @expect 1. The initialization is successful. 2. The parsing was successful. 3. Obtaining only one certificate in the chain. 4. The link is set up successfullyl, returns HITLS_SUCCESS. @ */ /* BEGIN_CASE */ void UT_TLS_TLS12_RFC5246_CONSISTENCY_BUILD_CERT_CHAIN_TC003() { #ifdef HITLS_TLS_CONFIG_CERT_BUILD_CHAIN FRAME_Init(); HITLS_Config *config_c = HITLS_CFG_NewTLS12Config(); ASSERT_TRUE(config_c != NULL); HITLS_Config *config_s = HITLS_CFG_NewTLS12Config(); ASSERT_TRUE(config_s != NULL); HITLS_CFG_SetVerifyNoneSupport(config_c, false); char intCaFile1[] = "../testdata/tls/certificate/der/rsa_sha256/inter.der"; HITLS_CERT_X509 *intCa1 = HITLS_CFG_ParseCert(config_s, (const uint8_t *)intCaFile1, strlen(intCaFile1) + 1, TLS_PARSE_TYPE_FILE, TLS_PARSE_FORMAT_ASN1); ASSERT_TRUE(intCa1 != NULL); char intCaFile2[] = "../testdata/tls/certificate/der/ecdsa_sha256/inter.der"; HITLS_CERT_X509 *intCa2 = HITLS_CFG_ParseCert(config_s, (const uint8_t *)intCaFile2, strlen(intCaFile2) + 1, TLS_PARSE_TYPE_FILE, TLS_PARSE_FORMAT_ASN1); ASSERT_TRUE(intCa2 != NULL); FRAME_CertInfo certInfoClient = { "rsa_sha256/ca.der", 0, "rsa_sha256/server.der", 0, "rsa_sha256/server.key.der", 0, }; FRAME_CertInfo certInfoServer = { "rsa_sha256/ca.der", 0, "rsa_sha256/server.der", 0, "rsa_sha256/server.key.der", 0, }; FRAME_LinkObj *client = FRAME_CreateLinkWithCert(config_c, BSL_UIO_TCP, &certInfoClient); ASSERT_TRUE(client != NULL); FRAME_LinkObj *server = FRAME_CreateLinkWithCert(config_s, BSL_UIO_TCP, &certInfoServer); ASSERT_TRUE(server != NULL); ASSERT_TRUE(HITLS_CFG_AddChainCert(&server->ssl->config.tlsConfig, intCa1, false) == HITLS_SUCCESS); ASSERT_TRUE(HITLS_CFG_AddChainCert(&server->ssl->config.tlsConfig, intCa2, false) == HITLS_SUCCESS); HITLS_CERT_Chain *chainCertList = HITLS_CFG_GetChainCerts(&server->ssl->config.tlsConfig); ASSERT_EQ(BSL_LIST_COUNT(chainCertList), 2); ASSERT_TRUE(HITLS_CFG_BuildCertChain(&server->ssl->config.tlsConfig, HITLS_BUILD_CHAIN_FLAG_CHECK) == HITLS_SUCCESS); chainCertList = HITLS_CFG_GetChainCerts(&server->ssl->config.tlsConfig); ASSERT_EQ(BSL_LIST_COUNT(chainCertList), 1); 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); #endif } /* END_CASE */ /** @ * @test UT_TLS_TLS12_RFC5246_CONSISTENCY_BUILD_CERT_CHAIN_TC004 * @title Set the flag to HITLS_BUILD_CHAIN_FLAG_NO_ROOT, and set both the intermediate certificate and the root * certificate to the certificate store. It is expected that the root certificate will not appear in the certificate * chain after the completion of the chain assembly. * @precon nan * @brief 1. Use the default configuration items to configure the client and server. Expected result 1 is obtained. 2. Load the root certificate and intermediate certificate into CertStore. Expected result 2 is obtained. 3. Call the HITLS_BuildCertChain function to group the certificate chain, set the flag to HITLS_BUILD_CHAIN_FLAG_NO_ROOT , Obtain the number of certificates in the chain after the chain is formed. Expected result 3 is obtained. 4. Continue to establish the link. Expected result 4 is obtained. * @expect 1. The initialization is successful. 2. The parsing was successful. 3. Obtaining only one certificate in the chain. 4. The link is set up successfully, returns HITLS_SUCCESS. @ */ /* BEGIN_CASE */ void UT_TLS_TLS12_RFC5246_CONSISTENCY_BUILD_CERT_CHAIN_TC004() { #ifdef HITLS_TLS_CONFIG_CERT_BUILD_CHAIN FRAME_Init(); HITLS_Config *config_c = HITLS_CFG_NewTLS12Config(); ASSERT_TRUE(config_c != NULL); HITLS_Config *config_s = HITLS_CFG_NewTLS12Config(); ASSERT_TRUE(config_s != NULL); HITLS_CFG_SetVerifyNoneSupport(config_c, false); char intCaFile[] = "../testdata/tls/certificate/der/rsa_sha256/inter.der"; HITLS_CERT_X509 *intCa = HITLS_CFG_ParseCert(config_s, (const uint8_t *)intCaFile, strlen(intCaFile) + 1, TLS_PARSE_TYPE_FILE, TLS_PARSE_FORMAT_ASN1); ASSERT_TRUE(intCa != NULL); FRAME_CertInfo certInfoClient = { "rsa_sha256/ca.der", 0, "rsa_sha256/server.der", 0, "rsa_sha256/server.key.der", 0, }; FRAME_CertInfo certInfoServer = { "rsa_sha256/ca.der", 0, "rsa_sha256/server.der", 0, "rsa_sha256/server.key.der", 0, }; FRAME_LinkObj *client = FRAME_CreateLinkWithCert(config_c, BSL_UIO_TCP, &certInfoClient); ASSERT_TRUE(client != NULL); FRAME_LinkObj *server = FRAME_CreateLinkWithCert(config_s, BSL_UIO_TCP, &certInfoServer); ASSERT_TRUE(server != NULL); HITLS_CERT_Store *store = HITLS_CFG_GetCertStore(&server->ssl->config.tlsConfig); ASSERT_TRUE(store != NULL); SAL_CERT_StoreCtrl(&server->ssl->config.tlsConfig, store, CERT_STORE_CTRL_ADD_CERT_LIST, intCa, NULL); ASSERT_TRUE(HITLS_BuildCertChain(server->ssl, HITLS_BUILD_CHAIN_FLAG_NO_ROOT) == HITLS_SUCCESS); HITLS_CERT_Chain *chainCertList = HITLS_CFG_GetChainCerts(&server->ssl->config.tlsConfig); ASSERT_EQ(BSL_LIST_COUNT(chainCertList), 1); 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); #endif } /* END_CASE */ /** * @test UT_TLS_TLS12_RFC5246_CONSISTENCY_VERIFY_CHAIN_TC001 * @title Verify the certificate chain in three ways: from a file, from a directory, and from a single CA certificate. * @precon nan * @brief 1. Use the default configuration items to configure the client and server. Expected result 1 is obtained. * 2. Load the certificate chain from a file. Expected result 2 is obtained. * 3. Continue to establish the link. Expected result 3 is obtained. * @expect 1. The initialization is successful. * 2. The parsing was successful. * 3. The link is set up successfully, returns HITLS_SUCCESS. */ /* BEGIN_CASE */ void UT_TLS_TLS12_RFC5246_CONSISTENCY_VERIFY_CHAIN_TC001() { FRAME_Init(); HITLS_Config *config_c = HITLS_CFG_NewTLS12Config(); ASSERT_TRUE(config_c != NULL); HITLS_Config *config_s = HITLS_CFG_NewTLS12Config(); ASSERT_TRUE(config_s != NULL); HITLS_CFG_SetClientVerifySupport(config_s, true); FRAME_CertInfo certInfoClient = { "rsa_sha256/ca.der", 0, 0, 0, 0, 0, }; FRAME_CertInfo certInfoServer = { "rsa_sha256/ca.der", "rsa_sha256/inter.der", "rsa_sha256/client.der", 0, "rsa_sha256/client.key.der", 0, }; const char *path = "../testdata/tls/certificate/pem/rsa_sha256/cert_chain.pem"; int32_t ret = HITLS_CFG_UseCertificateChainFile(config_c, path); ASSERT_TRUE(ret == HITLS_SUCCESS); const char *keyPath = "../testdata/tls/certificate/pem/rsa_sha256/client.key.pem"; HITLS_CFG_LoadKeyFile(config_c, keyPath, TLS_PARSE_FORMAT_PEM); ASSERT_TRUE(ret == HITLS_SUCCESS); FRAME_LinkObj *client = FRAME_CreateLinkWithCert(config_c, BSL_UIO_TCP, &certInfoClient); ASSERT_TRUE(client != NULL); FRAME_LinkObj *server = FRAME_CreateLinkWithCert(config_s, BSL_UIO_TCP, &certInfoServer); 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_TLS12_RFC5246_CONSISTENCY_VERIFY_CHAIN_TC002 * @title Verify the certificate chain in three ways: from a file, from a directory, and from a single CA certificate. * @precon nan * @brief 1. Use the default configuration items to configure the client and server. Expected result 1 is obtained. * 2. Load the certificate chain from a directory. Expected result 2 is obtained. * 3. Continue to establish the link. Expected result 3 is obtained. * @expect 1. The initialization is successful. * 2. The parsing was successful. * 3. The link is set up successfully, returns HITLS_SUCCESS. */ /* BEGIN_CASE */ void UT_TLS_TLS12_RFC5246_CONSISTENCY_VERIFY_CHAIN_TC002() { FRAME_Init(); HITLS_Config *config_c = HITLS_CFG_NewTLS12Config(); ASSERT_TRUE(config_c != NULL); HITLS_Config *config_s = HITLS_CFG_NewTLS12Config(); ASSERT_TRUE(config_s != NULL); HITLS_CFG_SetClientVerifySupport(config_s, true); FRAME_CertInfo certInfoClient = { 0, 0, "rsa_sha256/client.der", 0, "rsa_sha256/client.key.der", 0, }; FRAME_CertInfo certInfoServer = { "rsa_sha256/ca.der", "rsa_sha256/inter.der", "rsa_sha256/client.der", 0, "rsa_sha256/client.key.der", 0, }; const char *path = "../testdata/tls/certificate/pem/rsa_sha256"; int32_t ret = HITLS_CFG_LoadVerifyDir(config_c, path); ASSERT_TRUE(ret == HITLS_SUCCESS); FRAME_LinkObj *client = FRAME_CreateLinkWithCert(config_c, BSL_UIO_TCP, &certInfoClient); ASSERT_TRUE(client != NULL); FRAME_LinkObj *server = FRAME_CreateLinkWithCert(config_s, BSL_UIO_TCP, &certInfoServer); 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_TLS12_RFC5246_CONSISTENCY_VERIFY_CHAIN_TC003 * @title Verify the certificate chain in three ways: from a file, from a directory, and from a single CA certificate. * @precon nan * @brief 1. Use the default configuration items to configure the client and server. Expected result 1 is obtained. * 2. Load the certificate chain from a single CA certificate. Expected result 2 is obtained. * 3. Continue to establish the link. Expected result 3 is obtained. * @expect 1. The initialization is successful. * 2. The parsing was successful. * 3. The link is set up successfully, returns HITLS_SUCCESS. */ /* BEGIN_CASE */ void UT_TLS_TLS12_RFC5246_CONSISTENCY_VERIFY_CHAIN_TC003() { FRAME_Init(); HITLS_Config *config_c = HITLS_CFG_NewTLS12Config(); ASSERT_TRUE(config_c != NULL); HITLS_Config *config_s = HITLS_CFG_NewTLS12Config(); ASSERT_TRUE(config_s != NULL); HITLS_CFG_SetClientVerifySupport(config_s, true); FRAME_CertInfo certInfoClient = { 0, "rsa_sha256/inter.der", "rsa_sha256/client.der", 0, "rsa_sha256/client.key.der", 0, }; FRAME_CertInfo certInfoServer = { "rsa_sha256/ca.der", "rsa_sha256/inter.der", "rsa_sha256/client.der", 0, "rsa_sha256/client.key.der", 0, }; const char *caPath = "../testdata/tls/certificate/pem/rsa_sha256/ca.pem"; int32_t ret = HITLS_CFG_LoadVerifyFile(config_c, caPath); ASSERT_TRUE(ret == HITLS_SUCCESS); FRAME_LinkObj *client = FRAME_CreateLinkWithCert(config_c, BSL_UIO_TCP, &certInfoClient); ASSERT_TRUE(client != NULL); FRAME_LinkObj *server = FRAME_CreateLinkWithCert(config_s, BSL_UIO_TCP, &certInfoServer); 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 */
2301_79861745/bench_create
testcode/sdv/testcase/tls/consistency/tls12/test_suite_sdv_frame_tls12_consistency_rfc5246_cert.c
C
unknown
52,685
/* * This file is part of the openHiTLS project. * * openHiTLS is licensed under the Mulan PSL v2. * You can use this software according to the terms and conditions of the Mulan PSL v2. * You may obtain a copy of Mulan PSL v2 at: * * http://license.coscl.org.cn/MulanPSL2 * * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, * EITHER EXPRESS 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 "process.h" #include "securec.h" #include "hitls_error.h" #include "frame_tls.h" #include "frame_link.h" #include "frame_io.h" #include "bsl_sal.h" #include "simulate_io.h" #include "tls.h" #include "hs_ctx.h" #include "hlt.h" #include "alert.h" #include "session_type.h" #include "process.h" #include "hitls_type.h" #include "rec.h" #include "hs_msg.h" #include "hs_extensions.h" #include "frame_msg.h" #include "stub_crypt.h" /* END_HEADER */ #define BUF_TOOLONG_LEN ((1 << 14) + 1) 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 isServerExtendMasterSecret; } HandshakeTestInfo; int32_t StatusPark(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; } /*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 DefaultCfgStatusPark(HandshakeTestInfo *testInfo) { FRAME_Init(); /* Construct the configuration. */ testInfo->config = HITLS_CFG_NewTLS12Config(); if (testInfo->config == NULL) { return HITLS_INTERNAL_EXCEPTION; } 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->isSupportRenegotiation = testInfo->isSupportRenegotiation; return StatusPark(testInfo); } /* @ * @test UT_TLS_TLS12_RFC5246_CONSISTENCY_MSGLENGTH_TOOLONG_TC001 * @title The client sends a Client Certificate 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. The client initiates a DTLS link creation request. When the client needs to send a Client Certificate message, the two fields are modified as follows: Certificates Length is 2 ^ 14 + 1 Certificates are changed to 2 ^ 14 + 1 byte buffer. After the modification is complete, send the modification to the server. Expected result 2 is obtained. 3. When the server receives the Client Certificate 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_TLS12_RFC5246_CONSISTENCY_MSGLENGTH_TOOLONG_TC001(void) { HandshakeTestInfo testInfo = {0}; testInfo.state = TRY_RECV_CERTIFICATE; testInfo.isSupportExtendMasterSecret = true; testInfo.isClient = false; testInfo.isSupportClientVerify = true; ASSERT_TRUE(DefaultCfgStatusPark(&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; FRAME_Msg frameMsg = {0}; FRAME_Type frameType = {0}; frameType.versionType = HITLS_VERSION_TLS12; frameType.recordType = REC_TYPE_HANDSHAKE; frameType.handshakeType = CERTIFICATE; frameType.keyExType = HITLS_KEY_EXCH_ECDHE; ASSERT_TRUE(FRAME_ParseMsg(&frameType, recvBuf, recvLen, &frameMsg, &parseLen) == HITLS_SUCCESS); 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.certificate.certItem->cert.data); frameMsg.body.hsMsg.body.certificate.certItem->cert.data = certDataTemp; frameMsg.body.hsMsg.body.certificate.certItem->cert.size = BUF_TOOLONG_LEN; frameMsg.body.hsMsg.body.certificate.certItem->cert.state = ASSIGNED_FIELD; frameMsg.body.hsMsg.body.certificate.certItem->certLen.data = BUF_TOOLONG_LEN; frameMsg.body.hsMsg.body.certificate.certItem->certLen.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); 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); ASSERT_EQ(HITLS_Accept(testInfo.server->ssl), HITLS_REC_RECORD_OVERFLOW); ASSERT_TRUE(testInfo.server->ssl->hsCtx->state == TRY_RECV_CERTIFICATE); 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_TLS12_RFC5246_CONSISTENCY_MSGLENGTH_TOOLONG_TC002 * @title The server sends a Server Certificate 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. The client initiates a DTLS link creation request. When the server needs to send a Server Certificate message, the server modifies the following two fields: Certificates Length is 2 ^ 14 + 1 Certificates are changed to 2 ^ 14 + 1 byte buffer. After the modification is complete, send the modification to the server. Expected result 2 is obtained. 3. When the client receives the Server Certificate message, check the value returned by the HITLS_Connect 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_Connect interface is HITLS_REC_NORMAL_RECV_BUF_EMPTY. @ */ /* BEGIN_CASE */ void UT_TLS_TLS12_RFC5246_CONSISTENCY_MSGLENGTH_TOOLONG_TC002(void) { HandshakeTestInfo testInfo = {0}; testInfo.state = TRY_RECV_CERTIFICATE; testInfo.isClient = true; testInfo.isSupportExtendMasterSecret = true; testInfo.isSupportClientVerify = true; ASSERT_TRUE(DefaultCfgStatusPark(&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; FRAME_Msg frameMsg = {0}; FRAME_Type frameType = {0}; frameType.versionType = HITLS_VERSION_TLS12; frameType.recordType = REC_TYPE_HANDSHAKE; frameType.handshakeType = CERTIFICATE; frameType.keyExType = HITLS_KEY_EXCH_ECDHE; ASSERT_TRUE(FRAME_ParseMsg(&frameType, recvBuf, recvLen, &frameMsg, &parseLen) == HITLS_SUCCESS); 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.certificate.certItem->cert.data); frameMsg.body.hsMsg.body.certificate.certItem->cert.data = certDataTemp; frameMsg.body.hsMsg.body.certificate.certItem->cert.size = BUF_TOOLONG_LEN; frameMsg.body.hsMsg.body.certificate.certItem->cert.state = ASSIGNED_FIELD; frameMsg.body.hsMsg.body.certificate.certItem->certLen.data = BUF_TOOLONG_LEN; frameMsg.body.hsMsg.body.certificate.certItem->certLen.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); 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); ASSERT_EQ(HITLS_Connect(testInfo.client->ssl), HITLS_REC_RECORD_OVERFLOW); ASSERT_TRUE(testInfo.client->ssl->hsCtx->state == TRY_RECV_CERTIFICATE); 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_TLS12_RFC5246_CONSISTENCY_MSGLENGTH_TOOLONG_TC003 * @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 link 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_TLS12_RFC5246_CONSISTENCY_MSGLENGTH_TOOLONG_TC003(void) { HandshakeTestInfo testInfo = {0}; testInfo.state = TRY_RECV_CLIENT_KEY_EXCHANGE; testInfo.isClient = false; testInfo.isSupportExtendMasterSecret = true; testInfo.isSupportClientVerify = true; ASSERT_TRUE(DefaultCfgStatusPark(&testInfo) == HITLS_SUCCESS); ASSERT_EQ(HITLS_Accept(testInfo.server->ssl), HITLS_REC_NORMAL_RECV_BUF_EMPTY); FRAME_Msg frameMsg = {0}; FRAME_Type frameType = {0}; frameType.versionType = HITLS_VERSION_TLS12; frameType.recordType = REC_TYPE_CHANGE_CIPHER_SPEC; ASSERT_TRUE(FRAME_GetDefaultMsg(&frameType, &frameMsg) == HITLS_SUCCESS); 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); ASSERT_EQ(HITLS_Accept(testInfo.server->ssl), HITLS_REC_RECORD_OVERFLOW); ASSERT_TRUE(testInfo.server->ssl->hsCtx->state == TRY_RECV_CERTIFICATE_VERIFY); bool isCcsRecv = testInfo.server->ssl->method.isRecvCCS(testInfo.server->ssl); ASSERT_TRUE(isCcsRecv == false); 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_TLS12_RFC5246_CONSISTENCY_MSGLENGTH_TOOLONG_TC004 * @title The client receives a Change Cipher Spec message with a length of 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 DTLS over SCTP link request. After sending a Finish message, the client constructs a Change Cipher Spec message with a zero length and sends the message to the client. Expected result 2 is obtained. * @expect 1. The initialization is successful. 2. The client receives the message, which is HITLS_REC_NORMAL_RECV_BUF_EMPTY. @ */ /* BEGIN_CASE */ void UT_TLS_TLS12_RFC5246_CONSISTENCY_MSGLENGTH_TOOLONG_TC004(void) { HandshakeTestInfo testInfo = {0}; testInfo.state = TRY_SEND_FINISH; testInfo.isSupportExtendMasterSecret = true; testInfo.isClient = true; ASSERT_TRUE(DefaultCfgStatusPark(&testInfo) == HITLS_SUCCESS); ASSERT_TRUE(testInfo.client->ssl != NULL); ASSERT_EQ(HITLS_Connect(testInfo.client->ssl), HITLS_REC_NORMAL_RECV_BUF_EMPTY); ASSERT_TRUE(FRAME_TrasferMsgBetweenLink(testInfo.client, testInfo.server) == HITLS_SUCCESS); FRAME_Msg frameMsg1 = {0}; FRAME_Type frameType1 = {0}; frameType1.versionType = HITLS_VERSION_TLS12; frameType1.recordType = REC_TYPE_CHANGE_CIPHER_SPEC; ASSERT_TRUE(FRAME_GetDefaultMsg(&frameType1, &frameMsg1) == HITLS_SUCCESS); uint8_t *certDataTemp = (uint8_t *)BSL_SAL_Calloc(1, (uint32_t)BUF_TOOLONG_LEN); ASSERT_TRUE(certDataTemp != NULL); BSL_SAL_FREE(frameMsg1.body.ccsMsg.extra.data); frameMsg1.body.ccsMsg.extra.data = certDataTemp; frameMsg1.body.ccsMsg.extra.size = BUF_TOOLONG_LEN; frameMsg1.body.ccsMsg.extra.state = ASSIGNED_FIELD; uint32_t sendLen = MAX_RECORD_LENTH; uint8_t sendBuf[MAX_RECORD_LENTH] = {0}; ASSERT_TRUE(FRAME_PackMsg(&frameType1, &frameMsg1, sendBuf, sendLen, &sendLen) == HITLS_SUCCESS); FrameUioUserData *ioUserData1 = BSL_UIO_GetUserData(testInfo.client->io); ioUserData1->recMsg.len = 0; ASSERT_TRUE(FRAME_TransportRecMsg(testInfo.client->io, sendBuf, sendLen) == HITLS_SUCCESS); FRAME_CleanMsg(&frameType1, &frameMsg1); memset_s(&frameMsg1, sizeof(frameMsg1), 0, sizeof(frameMsg1)); ASSERT_TRUE(testInfo.client->ssl != NULL); ASSERT_EQ(HITLS_Connect(testInfo.client->ssl), HITLS_REC_RECORD_OVERFLOW); ASSERT_EQ(testInfo.client->ssl->hsCtx->state, TRY_RECV_NEW_SESSION_TICKET); bool isCcsRecv = testInfo.client->ssl->method.isRecvCCS(testInfo.client->ssl); ASSERT_TRUE(isCcsRecv == false); EXIT: FRAME_CleanMsg(&frameType1, &frameMsg1); HITLS_CFG_FreeConfig(testInfo.config); FRAME_FreeLink(testInfo.client); FRAME_FreeLink(testInfo.server); FRAME_DeRegCryptMethod(); } /* END_CASE */ int32_t StatusPark1(HandshakeTestInfo *testInfo) { 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; } 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(); testInfo->config = HITLS_CFG_NewTLS12Config(); if (testInfo->config == NULL) { return HITLS_INTERNAL_EXCEPTION; } 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->isSupportRenegotiation = testInfo->isSupportRenegotiation; return StatusPark1(testInfo); } /* @ * @test UT_TLS_TLS12_RFC7627_CONSISTENCY_EXTENDED_MASTER_SECRET_TC001 * @title The client does not forcibly verify the master key extension. The server supports the master key extension. The extended information in client hello and server hello is carried. * @precon nan * @brief 1. Use the default configuration items to configure the client and server, and configure the client not to forcibly verify the master key extension. The server supports this function. Expected result 1 is obtained. 2. When the client continuously sets up a link, the server receives the CLIENT_HELLO message and checks whether the extension of the master key is carried. Expected result 2 is obtained. 3. When the client receives the SERVER_HELLO message, check whether the message carries the master key extension. Expected result 2 is obtained. 4. Continue to establish the link. Expected result 3 is obtained. * @expect 1. The initialization is successful. 2. The master key extension is expected to be carried. 3. Expected Master Key Extension 4. The link is set up successfully. @ */ /* BEGIN_CASE */ void UT_TLS_TLS12_RFC7627_CONSISTENCY_EXTENDED_MASTER_SECRET_TC001(void) { HandshakeTestInfo testInfo = {0}; FRAME_Msg frameMsg = {0}; FRAME_Type frameType = {0}; FRAME_Msg frameMsg1 = {0}; FRAME_Type frameType1 = {0}; testInfo.isServerExtendMasterSecret = true; testInfo.state = TRY_RECV_CLIENT_HELLO; testInfo.isClient = false; ASSERT_TRUE(DefaultCfgStatusPark1(&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_TLS12; frameType.keyExType = HITLS_KEY_EXCH_ECDHE; ASSERT_TRUE(FRAME_ParseMsg(&frameType, recvBuf, recvLen, &frameMsg, &parseLen) == HITLS_SUCCESS); ASSERT_EQ(frameMsg.body.hsMsg.body.clientHello.extendedMasterSecret.exState , INITIAL_FIELD); FRAME_FreeLink(testInfo.client); FRAME_FreeLink(testInfo.server); HITLS_CFG_FreeConfig(testInfo.config); testInfo.state = TRY_RECV_SERVER_HELLO; testInfo.isClient = true; ASSERT_TRUE(DefaultCfgStatusPark1(&testInfo) == HITLS_SUCCESS); FrameUioUserData *ioUserData1 = BSL_UIO_GetUserData(testInfo.client->io); uint8_t *recvBuf1 = ioUserData1->recMsg.msg; uint32_t recvLen1 = ioUserData1->recMsg.len; ASSERT_TRUE(recvLen1 != 0); frameType1.versionType = HITLS_VERSION_TLS12; frameType1.keyExType = HITLS_KEY_EXCH_ECDHE; ASSERT_TRUE(FRAME_ParseMsg(&frameType1, recvBuf1, recvLen1, &frameMsg1, &parseLen) == HITLS_SUCCESS); ASSERT_EQ(frameMsg1.body.hsMsg.body.serverHello.extendedMasterSecret.exState , INITIAL_FIELD); FRAME_FreeLink(testInfo.client); FRAME_FreeLink(testInfo.server); HITLS_CFG_FreeConfig(testInfo.config); testInfo.state = HS_STATE_BUTT; ASSERT_TRUE(DefaultCfgStatusPark1(&testInfo) == HITLS_SUCCESS); EXIT: FRAME_CleanMsg(&frameType, &frameMsg); FRAME_CleanMsg(&frameType1, &frameMsg1); HITLS_CFG_FreeConfig(testInfo.config); FRAME_FreeLink(testInfo.client); FRAME_FreeLink(testInfo.server); FRAME_DeRegCryptMethod(); } /* END_CASE */ /* @ * @test UT_TLS_TLS12_RFC7627_CONSISTENCY_EXTENDED_MASTER_SECRET_TC002 * @title The client supports the extension of the key for strong verification, but the server does not. The clienthello carries the extension of the master key, and the serverhello carries the extension of the master key. The link is successfully established. * @precon nan * @brief 1. Use the default configuration items to configure the client and server, and configure the client to forcibly verify the master key extension. The server does not support the extension. Expected result 1 is displayed. 2. When the client is continuously establishing a link, the server receives the Client_Hello message and checks whether the client_Hello message carries the master key extension. Expected result 2 is obtained. 3. When the client receives the SERVER_HELLO message, check whether the message carries the master key extension. Expected result 3 is obtained. 4. Continue to establish the link. Expected result 4 is obtained. * @expect 1. The initialization is successful. 2. Expected to carry the master key extension. 3. The master key extension is expected to be carried. 4. The link is set up successfully. @ */ /* BEGIN_CASE */ void UT_TLS_TLS12_RFC7627_CONSISTENCY_EXTENDED_MASTER_SECRET_TC002(void) { FRAME_Msg frameMsg = {0}; FRAME_Type frameType = {0}; FRAME_Msg frameMsg1 = {0}; FRAME_Type frameType1 = {0}; FRAME_Init(); HITLS_Config *c_config = HITLS_CFG_NewTLS12Config(); ASSERT_TRUE(c_config != NULL); HITLS_Config *s_config = HITLS_CFG_NewTLS12Config(); ASSERT_TRUE(s_config != NULL); HITLS_CFG_SetExtenedMasterSecretSupport(c_config, true); HITLS_CFG_SetExtenedMasterSecretSupport(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, 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); uint32_t parseLen = 0; frameType.versionType = HITLS_VERSION_TLS12; frameType.keyExType = HITLS_KEY_EXCH_ECDHE; ASSERT_TRUE(FRAME_ParseMsg(&frameType, recvBuf, recvLen, &frameMsg, &parseLen) == HITLS_SUCCESS); ASSERT_TRUE(frameMsg.body.hsMsg.body.clientHello.extendedMasterSecret.exState == INITIAL_FIELD); HITLS_Accept(server->ssl); FRAME_TrasferMsgBetweenLink(server, client); ASSERT_EQ(FRAME_CreateConnection(client, server, true, TRY_RECV_SERVER_HELLO) , HITLS_SUCCESS); FrameUioUserData *ioUserData1 = BSL_UIO_GetUserData(client->io); uint8_t *recvBuf1 = ioUserData1->recMsg.msg; uint32_t recvLen1 = ioUserData1->recMsg.len; ASSERT_TRUE(recvLen1 != 0); uint32_t parseLen1 = 0; frameType1.versionType = HITLS_VERSION_TLS12; frameType1.keyExType = HITLS_KEY_EXCH_ECDHE; ASSERT_TRUE(FRAME_ParseMsg(&frameType1, recvBuf1, recvLen1, &frameMsg1, &parseLen1) == HITLS_SUCCESS); ASSERT_TRUE(frameMsg1.body.hsMsg.body.serverHello.extendedMasterSecret.exState == INITIAL_FIELD); ASSERT_EQ(FRAME_CreateConnection(client, server, true, HS_STATE_BUTT) , HITLS_SUCCESS); EXIT: FRAME_CleanMsg(&frameType, &frameMsg); FRAME_CleanMsg(&frameType1, &frameMsg1); HITLS_CFG_FreeConfig(c_config); HITLS_CFG_FreeConfig(s_config); FRAME_FreeLink(client); FRAME_FreeLink(server); } /* END_CASE */ /* @ * @test UT_TLS_TLS12_RFC7627_CONSISTENCY_EXTENDED_MASTER_SECRET_TC004 * @title The client and server support master key extension. The client hello message carries master key extension and the server hello message carries master key extension. The link is successfully established. * @precon nan * @brief 1. Use the default configuration items to configure the client and server to support master key extension. (Expected result 1) 2. When the client continuously sets up a link, the server checks whether the client_hello message carries the master key extension when receiving the CLIENT_HELLO message. Expected result 2 is obtained. 3. When the client receives the SERVER_HELLO message, check whether the message carries the master key extension. Expected result 3 is obtained. 4. Continue to establish the link. Expected result 4 is obtained. * @expect 1. The initialization is successful. 2. Expected to carry the master key extension. 3. The master key extension is expected to be carried. 4. The link is set up successfully. @ */ /* BEGIN_CASE */ void UT_TLS_TLS12_RFC7627_CONSISTENCY_EXTENDED_MASTER_SECRET_TC004(void) { HandshakeTestInfo testInfo = {0}; FRAME_Msg frameMsg = {0}; FRAME_Type frameType = {0}; FRAME_Msg frameMsg1 = {0}; FRAME_Type frameType1 = {0}; testInfo.isSupportExtendMasterSecret = true; testInfo.state = TRY_RECV_CLIENT_HELLO; testInfo.isClient = false; ASSERT_TRUE(DefaultCfgStatusPark(&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_TLS12; frameType.keyExType = HITLS_KEY_EXCH_ECDHE; ASSERT_TRUE(FRAME_ParseMsg(&frameType, recvBuf, recvLen, &frameMsg, &parseLen) == HITLS_SUCCESS); ASSERT_TRUE(frameMsg.body.hsMsg.body.clientHello.extendedMasterSecret.exState == INITIAL_FIELD); HITLS_CFG_FreeConfig(testInfo.config); FRAME_FreeLink(testInfo.client); FRAME_FreeLink(testInfo.server); testInfo.state = TRY_RECV_SERVER_HELLO; testInfo.isClient = true; ASSERT_TRUE(DefaultCfgStatusPark(&testInfo) == HITLS_SUCCESS); FrameUioUserData *ioUserData1 = BSL_UIO_GetUserData(testInfo.client->io); uint8_t *recvBuf1 = ioUserData1->recMsg.msg; uint32_t recvLen1 = ioUserData1->recMsg.len; ASSERT_TRUE(recvLen1 != 0); frameType1.versionType = HITLS_VERSION_TLS12; frameType1.keyExType = HITLS_KEY_EXCH_ECDHE; ASSERT_TRUE(FRAME_ParseMsg(&frameType1, recvBuf1, recvLen1, &frameMsg1, &parseLen) == HITLS_SUCCESS); ASSERT_TRUE(frameMsg1.body.hsMsg.body.serverHello.extendedMasterSecret.exState == INITIAL_FIELD); HITLS_CFG_FreeConfig(testInfo.config); FRAME_FreeLink(testInfo.client); FRAME_FreeLink(testInfo.server); testInfo.state = HS_STATE_BUTT; ASSERT_TRUE(DefaultCfgStatusPark(&testInfo) == HITLS_SUCCESS); EXIT: FRAME_CleanMsg(&frameType, &frameMsg); FRAME_CleanMsg(&frameType1, &frameMsg1); HITLS_CFG_FreeConfig(testInfo.config); FRAME_FreeLink(testInfo.client); FRAME_FreeLink(testInfo.server); FRAME_DeRegCryptMethod(); } /* END_CASE */ int32_t StatusPark2(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; } if (FRAME_CreateConnection(testInfo->client, testInfo->server, testInfo->isClient, testInfo->state) != HITLS_SUCCESS) { return HITLS_INTERNAL_EXCEPTION; } return HITLS_SUCCESS; }
2301_79861745/bench_create
testcode/sdv/testcase/tls/consistency/tls12/test_suite_sdv_frame_tls12_consistency_rfc5246_extensions.c
C
unknown
28,510
/* * This file is part of the openHiTLS project. * * openHiTLS is licensed under the Mulan PSL v2. * You can use this software according to the terms and conditions of the Mulan PSL v2. * You may obtain a copy of Mulan PSL v2 at: * * http://license.coscl.org.cn/MulanPSL2 * * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, * EITHER EXPRESS 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 test_suite_tls12_consistency_rfc5246_malformed_msg */ /* BEGIN_HEADER */ #include "hitls_error.h" #include "tls.h" #include "rec.h" #include "hs_msg.h" #include "hs_ctx.h" #include "hs_extensions.h" #include "frame_msg.h" #include "pack_msg.h" #include "stub_crypt.h" /* END_HEADER */ /* @ * @test UT_TLS_TLS12_RFC5246_CONSISTENCY_RECV_ZEROLENGTH_MSG_TC009 * @title record layer allows the sending of the APPdata message with the length of zero. * @precon nan * @brief 1. Establish a link. After the link is established, construct an Appdata message with zero length and send it to the server. Then, send an APPdata message with data to the server. Expected result 1 is obtained. * @expect 1. Expected success @ */ /* BEGIN_CASE */ void UT_TLS_TLS12_RFC5246_CONSISTENCY_RECV_ZEROLENGTH_MSG_TC009(int messageLen) { FRAME_Init(); HITLS_Config *config = NULL; FRAME_LinkObj *client = NULL; FRAME_LinkObj *server = NULL; ASSERT_EQ(TlsCtxNew(BSL_UIO_TCP), HITLS_SUCCESS); ASSERT_EQ(REC_Init(g_tlsCtx), HITLS_SUCCESS); /* 1. Establish a link. After the link is established, construct an Appdata message with zero length and send it to * the server. Then, send an APPdata message with data to the server. */ config = HITLS_CFG_NewTLS12Config(); 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, 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(FRAME_CreateConnection(client, server, true, HS_STATE_BUTT) == HITLS_SUCCESS); ASSERT_TRUE(clientTlsCtx->state == CM_STATE_TRANSPORTING); uint8_t data[REC_MAX_CIPHER_TEXT_LEN]; ASSERT_EQ(REC_Write(clientTlsCtx, REC_TYPE_APP, data, messageLen), HITLS_SUCCESS); EXIT: TlsCtxFree(); HITLS_CFG_FreeConfig(config); FRAME_FreeLink(client); FRAME_FreeLink(server); } /* END_CASE */ /* @ * @test UT_TLS_TLS12_RFC5246_CONSISTENCY_RECV_ZEROLENGTH_MSG_TC010 * @title record layer allows the sending of the APPdata message with the length of zero. * @precon nan * @brief 1. Establish a link. After the link 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. Expected result 1 is obtained. * @expect 1. Expected success @ */ /* BEGIN_CASE */ void UT_TLS_TLS12_RFC5246_CONSISTENCY_RECV_ZEROLENGTH_MSG_TC010(int messageLen) { FRAME_Init(); HITLS_Config *config = NULL; FRAME_LinkObj *client = NULL; FRAME_LinkObj *server = NULL; ASSERT_EQ(TlsCtxNew(BSL_UIO_TCP), HITLS_SUCCESS); ASSERT_EQ(REC_Init(g_tlsCtx), HITLS_SUCCESS); /* 1. Establish a link. After the link 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. */ config = HITLS_CFG_NewTLS12Config(); 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, BSL_UIO_TCP); ASSERT_TRUE(client != NULL); server = FRAME_CreateLink(config, BSL_UIO_TCP); ASSERT_TRUE(server != NULL); HITLS_Ctx *serverTlsCtx = FRAME_GetTlsCtx(server); ASSERT_TRUE(FRAME_CreateConnection(client, server, true, HS_STATE_BUTT) == HITLS_SUCCESS); ASSERT_TRUE(serverTlsCtx->state == CM_STATE_TRANSPORTING); uint8_t data[REC_MAX_CIPHER_TEXT_LEN]; ASSERT_EQ(REC_Write(serverTlsCtx, REC_TYPE_APP, data, messageLen), HITLS_SUCCESS); EXIT: TlsCtxFree(); HITLS_CFG_FreeConfig(config); FRAME_FreeLink(client); FRAME_FreeLink(server); } /* END_CASE */ /* @ * @test UT_TLS_TLS12_RFC5246_CONSISTENCY_MISS_CLIENT_KEYEXCHANGE_TC001 * @title During the handshake, the client receives the CCS when the client is in the TRY_RECV_FINISH state. * @precon nan * @brief 1. Configure the single-end authentication. After the server sends the serverhellodone message, the client stops in the try send client key exchange state. Expected result 1 2. Construct an unexpected CCS message and send it to the server. Expected result 2 is obtained. * @expect 1. The initialization is successful. 2. The connection fails to be established and the server returns an unexpected message. @ */ /* BEGIN_CASE */ void UT_TLS_TLS12_RFC5246_CONSISTENCY_MISS_CLIENT_KEYEXCHANGE_TC001(void) { HandshakeTestInfo testInfo = {0}; FRAME_Msg frameMsg = {0}; FRAME_Type frameType = {0}; /* 1. Configure the single-end authentication. After the server sends the serverhellodone message, the client * stops in the try send client key exchange state. */ testInfo.state = TRY_SEND_CLIENT_KEY_EXCHANGE; testInfo.isSupportExtendMasterSecret = true; testInfo.isClient = true; testInfo.isSupportClientVerify = false; testInfo.isSupportNoClientCert = false; testInfo.needStopBeforeRecvCCS = true; ASSERT_TRUE(DefaultCfgStatusPark(&testInfo) == HITLS_SUCCESS); // 2. Construct an unexpected CCS message and send it to the server. frameType.versionType = HITLS_VERSION_TLS12; frameType.recordType = REC_TYPE_CHANGE_CIPHER_SPEC; 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); 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); 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; 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_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); FRAME_DeRegCryptMethod(); } /* END_CASE */ // To test whether fragmented messages can be received correctly. Test REC_TlsReadNbytes /* BEGIN_CASE */ void UT_TLS_TLS12_RFC5246_CONSISTENCY_FRAGMENTED_MSG_TC001(void) { FRAME_Init(); HITLS_Config *config = HITLS_CFG_NewTLS12Config(); ASSERT_TRUE(config != NULL); FRAME_LinkObj *client = FRAME_CreateLink(config, BSL_UIO_TCP); FRAME_LinkObj *server = FRAME_CreateLink(config, BSL_UIO_TCP); ASSERT_TRUE(client != NULL); ASSERT_TRUE(server != NULL); int32_t ret = HITLS_Connect(client->ssl); ASSERT_TRUE(ret == HITLS_REC_NORMAL_RECV_BUF_EMPTY); ASSERT_TRUE(client->ssl->hsCtx->state == TRY_RECV_SERVER_HELLO); ret = HITLS_Accept(server->ssl); ASSERT_TRUE(ret == HITLS_REC_NORMAL_RECV_BUF_EMPTY); ASSERT_TRUE(server->ssl->hsCtx->state == TRY_RECV_CLIENT_HELLO); // Handshake messages are divided into two records, and the two records are read separately. FrameUioUserData *ioUserData = BSL_UIO_GetUserData(client->io); uint8_t data[MAX_RECORD_LENTH] = {0}; uint32_t dataLen = MAX_RECORD_LENTH; ASSERT_EQ(memcpy_s(data, MAX_RECORD_LENTH, ioUserData->sndMsg.msg, ioUserData->sndMsg.len), 0); dataLen = ioUserData->sndMsg.len; uint32_t msglength = BSL_ByteToUint16(&data[3]); uint32_t msgLen = (msglength - 1) / 2; uint32_t len = 5 + msgLen; // record + handshakemsg // Send the first segment of packets. eg.163 = (5 + 70) + 5 +83 uint8_t recorddata1[] = {0x16, 0x03, 0x03, 0x00, 0x46}; // The last two bytes of the first five bytes of the length of bodylen are modified. BSL_Uint16ToByte((uint16_t)msgLen, &recorddata1[3]); ASSERT_EQ(memcpy_s(ioUserData->sndMsg.msg, MAX_RECORD_LENTH, data, len), 0); ASSERT_EQ(memcpy_s(ioUserData->sndMsg.msg, MAX_RECORD_LENTH, recorddata1, sizeof(recorddata1)), 0); // Send the second segment of packets. eg.163 = 5 + 70 + (5 +83) uint8_t recorddata2[] = {0x16, 0x03, 0x03, 0x00, 0x53}; msgLen = dataLen - len; BSL_Uint16ToByte((uint16_t)msgLen, &recorddata2[3]); ASSERT_EQ(memcpy_s(ioUserData->sndMsg.msg + len, MAX_RECORD_LENTH - len, recorddata2, sizeof(recorddata2)), 0); ioUserData->sndMsg.len = len + 5; ASSERT_EQ(memcpy_s(ioUserData->sndMsg.msg + ioUserData->sndMsg.len, MAX_RECORD_LENTH - len, data + len, dataLen - len), 0); ioUserData->sndMsg.len += dataLen - len; ret = HITLS_Connect(client->ssl); ASSERT_TRUE(FRAME_TrasferMsgBetweenLink(client, server) == HITLS_SUCCESS); ret = HITLS_Accept(server->ssl); ASSERT_EQ(ret, HITLS_REC_NORMAL_IO_BUSY); ASSERT_EQ(FRAME_CreateConnection(client, server, true, HS_STATE_BUTT), HITLS_SUCCESS); ASSERT_TRUE(client->ssl->state == CM_STATE_TRANSPORTING); EXIT: HITLS_CFG_FreeConfig(config); FRAME_FreeLink(client); FRAME_FreeLink(server); } /* END_CASE */
2301_79861745/bench_create
testcode/sdv/testcase/tls/consistency/tls12/test_suite_sdv_frame_tls12_consistency_rfc5246_malformed_msg.c
C
unknown
10,528
/* * This file is part of the openHiTLS project. * * openHiTLS is licensed under the Mulan PSL v2. * You can use this software according to the terms and conditions of the Mulan PSL v2. * You may obtain a copy of Mulan PSL v2 at: * * http://license.coscl.org.cn/MulanPSL2 * * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, * EITHER EXPRESS 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 <stdio.h> #include "process.h" #include "securec.h" #include "hitls_error.h" #include "frame_tls.h" #include "frame_link.h" #include "frame_io.h" #include "bsl_sal.h" #include "simulate_io.h" #include "tls.h" #include "hs_ctx.h" #include "hlt.h" #include "alert.h" #include "session_type.h" #include "hitls_type.h" #include "rec.h" #include "hs_msg.h" #include "hs_extensions.h" #include "frame_msg.h" #include "stub_replace.h" #include "hitls.h" #include "hitls_config.h" #include "bsl_uio.h" #include "pack.h" #include "send_process.h" #include "parser_frame_msg.h" #include "cert.h" #include "rec_wrapper.h" #include "conn_init.h" #include "cert_callback.h" #include "change_cipher_spec.h" #include "common_func.h" #include "uio_base.h" #include "stub_crypt.h" #define READ_BUF_SIZE (18 * 1024) /* END_HEADER */ 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 isServerExtendMasterSecret; } 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; } if (FRAME_CreateConnection(testInfo->client, testInfo->server, testInfo->isClient, testInfo->state) != HITLS_SUCCESS) { return HITLS_INTERNAL_EXCEPTION; } return HITLS_SUCCESS; } static void Test_ServerHelloHaveSecRenego(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); ASSERT_EQ(frameMsg.body.hsMsg.body.serverHello.secRenego.exState, 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; } int32_t DefaultCfgStatusPark(HandshakeTestInfo *testInfo) { FRAME_Init(); 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 StatusPark1(HandshakeTestInfo *testInfo) { 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; } 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(); testInfo->config = HITLS_CFG_NewTLS12Config(); if (testInfo->config == NULL) { return HITLS_INTERNAL_EXCEPTION; } 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->isSupportRenegotiation = testInfo->isSupportRenegotiation; return StatusPark1(testInfo); } void Test_RenegoWrapperFunc(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); ASSERT_EQ(parseLen, *len); ASSERT_EQ(frameMsg.body.hsMsg.body.clientHello.secRenego.exState, INITIAL_FIELD); EXIT: FRAME_CleanMsg(&frameType, &frameMsg); return; } void Test_RenegoRemoveExtension(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); ASSERT_EQ(parseLen, *len); frameMsg.body.hsMsg.body.clientHello.secRenego.exState = MISSING_FIELD; FRAME_PackRecordBody(&frameType, &frameMsg, data, bufSize, len); EXIT: FRAME_CleanMsg(&frameType, &frameMsg); return; } /** @ * @test UT_TLS_TLS12_RFC5746_CONSISTENCY_EXTENDED_RENEGOTIATION_FUNC_TC001 * @titleThe client carries the renegotiation algorithm suite but does not carry the renegotiation extension. * @precon nan * @brief 1. Use the default configuration items to configure the client and server. Expected result 1 is obtained. * 2. During continuous link setup, the server checks whether the renegotiation algorithm suite is contained and * whether the renegotiation extension is carried when receiving the CLIENT_HELLO message. * Expected result 2 is obtained. * @expect 1. The initialization is successful. * 2. The renegotiation algorithm suite is expected to be carried, but the renegotiation extension is not * carried. @ */ /* BEGIN_CASE */ void UT_TLS_TLS12_RFC5746_CONSISTENCY_EXTENDED_RENEGOTIATION_FUNC_TC001(void) { HandshakeTestInfo testInfo = {0}; FRAME_Msg frameMsg = {0}; FRAME_Type frameType = {0}; testInfo.isSupportExtendMasterSecret = true; testInfo.isSupportRenegotiation = true; testInfo.state = TRY_RECV_CLIENT_HELLO; testInfo.isClient = false; ASSERT_TRUE(DefaultCfgStatusPark(&testInfo) == HITLS_SUCCESS); int FlagScsv = 0; 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_TLS12; frameType.keyExType = HITLS_KEY_EXCH_ECDHE; ASSERT_TRUE(FRAME_ParseMsg(&frameType, recvBuf, recvLen, &frameMsg, &parseLen) == HITLS_SUCCESS); for (int i = 0; i < (int)frameMsg.body.hsMsg.body.clientHello.cipherSuites.size; i++) { if (frameMsg.body.hsMsg.body.clientHello.cipherSuites.data[i] == 255) { FlagScsv = 1; } } ASSERT_TRUE(FlagScsv == 1); ASSERT_TRUE(frameMsg.body.hsMsg.body.clientHello.secRenego.exState == MISSING_FIELD); 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_TLS12_RFC5746_CONSISTENCY_EXTENDED_RENEGOTIATION_FUNC_TC003 * @title Enable the client and server to support renegotiation. Change the length of the renegotiated_connection field * in the server hello message to a non-zero value. Check whether the connection is successfully established. * @precon nan * @brief 1. The client and server support renegotiation and connection establishment. Change the length of the * renegotiated_connection field in the server hello message to a non-zero value. Then, the connection * is established. Expected result 1 is obtained. * @expect 1. The connection fails to be set up and an ALERT_HANDSHAKE_FAILURE message is sent. @ */ /* BEGIN_CASE */ void UT_TLS_TLS12_RFC5746_CONSISTENCY_EXTENDED_RENEGOTIATION_FUNC_TC003(void) { HandshakeTestInfo testInfo = {0}; FRAME_Msg frameMsg = {0}; FRAME_Type frameType = {0}; testInfo.state = TRY_RECV_SERVER_HELLO; testInfo.isSupportRenegotiation = true; testInfo.isClient = true; ASSERT_TRUE(DefaultCfgStatusPark(&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_TLS12; 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->secRenego.exDataLen.data == 0u); serverMsg->secRenego.exDataLen.data = 1u; 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); ASSERT_EQ(HITLS_Connect(testInfo.client->ssl), HITLS_PARSE_INVALID_MSG_LEN); 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); /* The connection fails to be set up and an ALERT_HANDSHAKE_FAILURE message is sent. */ 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_TLS12_RFC5746_CONSISTENCY_EXTENDED_RENEGOTIATION_FUNC_TC002 * @titleThe server does not support renegotiation. The serverhello message carries the renegotiation extension. * @precon nan * @brief * 1. Use the default configuration items to configure the client and server. Expected result 1 is obtained. * 2. When the client receives a SERVER_HELLO message during continuous link establishment, the client checks whether * the message carries the renegotiation extension. Expected result 2 is obtained. * @expect * 1. The initialization is successful. * 2. The renegotiation extension is expected to be carried. @ */ /* BEGIN_CASE */ void UT_TLS_TLS12_RFC5746_CONSISTENCY_EXTENDED_RENEGOTIATION_FUNC_TC002(void) { FRAME_Init(); HandshakeTestInfo testInfo = {0}; FRAME_Msg frameMsg = {0}; FRAME_Type frameType = {0}; testInfo.isSupportRenegotiation = false; testInfo.config = HITLS_CFG_NewTLS12Config(); ASSERT_TRUE(testInfo.config != NULL); testInfo.server = FRAME_CreateLink(testInfo.config, BSL_UIO_TCP); ASSERT_TRUE(testInfo.server != NULL); testInfo.client = FRAME_CreateLink(testInfo.config, BSL_UIO_TCP); ASSERT_TRUE(testInfo.client != NULL); 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 *recvBuf = ioUserData->recMsg.msg; uint32_t recvLen = ioUserData->recMsg.len; ASSERT_TRUE(recvLen != 0); uint32_t parseLen = 0; frameType.versionType = HITLS_VERSION_TLS12; frameType.keyExType = HITLS_KEY_EXCH_ECDHE; ASSERT_TRUE(FRAME_ParseMsg(&frameType, recvBuf, recvLen, &frameMsg, &parseLen) == HITLS_SUCCESS); ASSERT_TRUE(frameMsg.body.hsMsg.body.serverHello.secRenego.exLen.data != 0); HITLS_CFG_FreeConfig(testInfo.config); FRAME_FreeLink(testInfo.client); FRAME_FreeLink(testInfo.server); testInfo.state = HS_STATE_BUTT; ASSERT_TRUE(DefaultCfgStatusPark1(&testInfo) == HITLS_SUCCESS); EXIT: FRAME_CleanMsg(&frameType, &frameMsg); HITLS_CFG_FreeConfig(testInfo.config); FRAME_FreeLink(testInfo.client); FRAME_FreeLink(testInfo.server); } /* END_CASE */ /** @ * @test UT_TLS_TLS12_RFC5746_CONSISTENCY_EXTENDED_RENEGOTIATION_FUNC_TC009 * @title Renegotiation flag condition * @precon nan * @brief 1. The client and server support renegotiation and connection establishment. Before receiving the client hello * message, the server disables security renegotiation. Expected result 1 is displayed. * 2. After the server receives the client hello message, enable the security renegotiation on the server. * Expected result 2 is displayed. * @expect 1. The isSecureRenegotiation is false. * 2. The isSecureRenegotiation is true. @ */ /* BEGIN_CASE */ void UT_TLS_TLS12_RFC5746_CONSISTENCY_EXTENDED_RENEGOTIATION_FUNC_TC009(void) { FRAME_Init(); HITLS_Config *config = NULL; FRAME_LinkObj *client = NULL; FRAME_LinkObj *server = NULL; config = HITLS_CFG_NewTLS12Config(); 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); ASSERT_TRUE(FRAME_CreateConnection(client, server, false, TRY_RECV_CLIENT_HELLO) == HITLS_SUCCESS); ASSERT_TRUE(server->ssl->negotiatedInfo.isSecureRenegotiation == false); FRAME_LinkObj *client1 = FRAME_CreateLink(config, BSL_UIO_TCP); ASSERT_TRUE(client != NULL); FRAME_LinkObj *server1 = FRAME_CreateLink(config, BSL_UIO_TCP); ASSERT_TRUE(server != NULL); ASSERT_EQ(FRAME_CreateConnection(client1, server1, true, HS_STATE_BUTT), HITLS_SUCCESS); ASSERT_TRUE(server1->ssl->negotiatedInfo.isSecureRenegotiation == true); EXIT: HITLS_CFG_FreeConfig(config); FRAME_FreeLink(client1); FRAME_FreeLink(server1); FRAME_FreeLink(client); FRAME_FreeLink(server); FRAME_DeRegCryptMethod(); } /* END_CASE */ /** @ * @test UT_TLS_TLS12_RFC5746_CONSISTENCY_EXTENDED_RENEGOTIATION_FUNC_TC013 * @title Configure the client and server to support renegotiation. After the first handshake is complete, a * renegotiation request is initiated. When the client sends a client hello message, * Modify the message and delete the renegotiation_info extension. The server is expected to return an alert * after receiving the message. * @precon nan * @brief 1. The client and server support renegotiation and connection establishment. Start renegotiation. The expected * connection establishment is successful. * @expect 1. When the client sends the client hello message, modify the message and remove the renegotiation_info * extension. As a result, the expected connection establishment fails. @ */ /* BEGIN_CASE */ void UT_TLS_TLS12_RFC5746_CONSISTENCY_EXTENDED_RENEGOTIATION_FUNC_TC013(void) { FRAME_Init(); HITLS_Config *config = NULL; FRAME_LinkObj *client = NULL; FRAME_LinkObj *server = NULL; /* The client and server support renegotiation and connection establishment. Start renegotiation. */ config = HITLS_CFG_NewTLS12Config(); 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); 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(clientTlsCtx->state == CM_STATE_TRANSPORTING); uint8_t verifyData[MAX_DIGEST_SIZE] = {0}; uint32_t verifyDataSize = 0; ASSERT_TRUE( HITLS_GetFinishVerifyData(client->ssl, verifyData, sizeof(verifyData), &verifyDataSize) == HITLS_SUCCESS); RecWrapper wrapper = {TRY_RECV_CLIENT_HELLO, REC_TYPE_HANDSHAKE, true, NULL, Test_RenegoRemoveExtension}; RegisterWrapper(wrapper); ASSERT_TRUE(HITLS_Renegotiate(serverTlsCtx) == HITLS_SUCCESS); ASSERT_TRUE(HITLS_Renegotiate(clientTlsCtx) == HITLS_SUCCESS); ASSERT_TRUE(FRAME_CreateConnection(client, server, false, HS_STATE_BUTT) != HITLS_SUCCESS); EXIT: ClearWrapper(); HITLS_CFG_FreeConfig(config); FRAME_FreeLink(client); FRAME_FreeLink(server); } /* END_CASE */ /** @ * @test UT_TLS_TLS12_RFC5746_CONSISTENCY_EXTENDED_RENEGOTIATION_FUNC_TC005 * @title The client and server support renegotiation and connection establishment. Start renegotiation. Check whether * the serverhello contains the renegotiation extension. Check whether the connection is successfully * established and verify the negotiation behavior. * @precon nan * @brief 1. The client and server support renegotiation and connection establishment. Start renegotiation. Expected * result 1 is obtained. * @expect 1. Modify the cipher suite in the client hello, add the SCSV, and check whether the connection is successfully * set up. Expected result 2 is obtained. @ */ /* BEGIN_CASE */ void UT_TLS_TLS12_RFC5746_CONSISTENCY_EXTENDED_RENEGOTIATION_FUNC_TC005(void) { FRAME_Init(); HITLS_Config *config = NULL; FRAME_LinkObj *client = NULL; FRAME_LinkObj *server = NULL; /* The client and server support renegotiation and connection establishment. Start renegotiation. */ config = HITLS_CFG_NewTLS12Config(); 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); 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(clientTlsCtx->state == CM_STATE_TRANSPORTING); uint8_t verifyData[MAX_DIGEST_SIZE] = {0}; uint32_t verifyDataSize = 0; ASSERT_TRUE( HITLS_GetFinishVerifyData(client->ssl, verifyData, sizeof(verifyData), &verifyDataSize) == HITLS_SUCCESS); RecWrapper wrapper = {TRY_RECV_CLIENT_HELLO, REC_TYPE_HANDSHAKE, true, NULL, Test_RenegoWrapperFunc}; RegisterWrapper(wrapper); ASSERT_TRUE(HITLS_Renegotiate(serverTlsCtx) == HITLS_SUCCESS); ASSERT_TRUE(HITLS_Renegotiate(clientTlsCtx) == HITLS_SUCCESS); ASSERT_TRUE(FRAME_CreateRenegotiationState(client, server, false, HS_STATE_BUTT) == HITLS_SUCCESS); EXIT: ClearWrapper(); HITLS_CFG_FreeConfig(config); FRAME_FreeLink(client); FRAME_FreeLink(server); } /* END_CASE */ /** @ * @test UT_TLS_TLS12_RFC5746_CONSISTENCY_EXTENDED_RENEGOTIATION_FUNC_TC010 * @title Configure the client and server to support renegotiation and connection establishment. The * renegotiated_connection field in the client hello extension received by the server is not 0. * @precon nan * @brief 1. Configure the client and server to support renegotiation and establish a connection. Expected result 1 is * obtained. * 2. Modify the client hello message received by the server. Modify the renegotiated_connection field extended * by the (HS_EX_TYPE_RENEGOTIATION_INFO) to ensure that the length of the field is not 0. * @expect 1. The initialization is successful. * 2. The server sends the ALERT message. The level is ALERT_LEVEL_FATAL and the description is * ALERT_HANDSHAKE_FAILURE. @ */ /* BEGIN_CASE */ void UT_TLS_TLS12_RFC5746_CONSISTENCY_EXTENDED_RENEGOTIATION_FUNC_TC010(void) { /* Configure the client and server to support renegotiation and establish a connection. */ HandshakeTestInfo testInfo = {0}; FRAME_Msg frameMsg = {0}; FRAME_Type frameType = {0}; testInfo.state = TRY_RECV_CLIENT_HELLO; testInfo.isSupportRenegotiation = true; testInfo.isClient = false; ASSERT_TRUE(DefaultCfgStatusPark(&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_TLS12; 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); /* Modify the client hello message received by the server. Modify the renegotiated_connection field extended by the * (HS_EX_TYPE_RENEGOTIATION_INFO) to ensure that the length of the field is not 0. */ FRAME_ClientHelloMsg *clientMsg = &frameMsg.body.hsMsg.body.clientHello; ASSERT_TRUE(clientMsg->secRenego.exDataLen.data == 0u); clientMsg->secRenego.exState = INITIAL_FIELD; clientMsg->secRenego.exType.state = INITIAL_FIELD; clientMsg->secRenego.exType.data = 0xFF01u; clientMsg->secRenego.exLen.state = INITIAL_FIELD; clientMsg->secRenego.exLen.data = 2; clientMsg->secRenego.exDataLen.state = INITIAL_FIELD; clientMsg->secRenego.exDataLen.data = 1u; clientMsg->secRenego.exData.state = INITIAL_FIELD; clientMsg->secRenego.exData.size = 1; clientMsg->secRenego.exData.data = BSL_SAL_Calloc(1, sizeof(uint8_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(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); ASSERT_TRUE(HITLS_Accept(testInfo.server->ssl) == HITLS_MSG_HANDLE_RENEGOTIATION_FAIL); 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); FRAME_AlertMsg *alertMsg = &frameMsg.body.alertMsg; ASSERT_TRUE(alertMsg->alertLevel.data == ALERT_LEVEL_FATAL); ASSERT_TRUE(alertMsg->alertDescription.data == ALERT_HANDSHAKE_FAILURE); 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_TLS12_RFC5746_CONSISTENCY_EXTENDED_RENEGOTIATION_FUNC_TC011 * @title The client and server support renegotiation and connection establishment. Check whether the serverhello * contains the renegotiation extension. Check whether the connection is successfully established and verify the * negotiation behavior. * @precon nan * @brief 1. If the client and server support renegotiation and connection establishment, check the serverhello message * that contains the renegotiation extension, and check whether the connection establishment is successful. * (Expected result 1) * @expect 1. Modify the cipher suite in the client hello, add the SCSV, and check whether the connection is successfully * set up. Expected result 2 is obtained. @ */ /* BEGIN_CASE */ void UT_TLS_TLS12_RFC5746_CONSISTENCY_EXTENDED_RENEGOTIATION_FUNC_TC011(void) { FRAME_Init(); HITLS_Config *config = NULL; FRAME_LinkObj *client = NULL; FRAME_LinkObj *server = NULL; /* If the client and server support renegotiation and connection establishment, check the serverhello message that * contains the renegotiation extension, and check whether the connection establishment is successful. */ config = HITLS_CFG_NewTLS12Config(); 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); ASSERT_EQ(clientTlsCtx->state, CM_STATE_IDLE); HITLS_Ctx *serverTlsCtx = FRAME_GetTlsCtx(server); ASSERT_TRUE(serverTlsCtx->state == CM_STATE_IDLE); /* Modify the cipher suite in the client hello, add the SCSV, and check whether the connection is successfully set * up. */ RecWrapper wrapper = {TRY_SEND_SERVER_HELLO, REC_TYPE_HANDSHAKE, false, NULL, Test_ServerHelloHaveSecRenego}; RegisterWrapper(wrapper); ASSERT_TRUE(FRAME_CreateConnection(client, server, false, HS_STATE_BUTT) == HITLS_SUCCESS); EXIT: ClearWrapper(); HITLS_CFG_FreeConfig(config); FRAME_FreeLink(client); FRAME_FreeLink(server); } /* END_CASE */ static void Test_ClientHello_SecRenego(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); FRAME_ClientHelloMsg *clientMsg = &frameMsg.body.hsMsg.body.clientHello; ASSERT_EQ(clientMsg->secRenego.exState, INITIAL_FIELD); ASSERT_TRUE( clientMsg->cipherSuites.data[clientMsg->cipherSuitesSize.data / 2 - 1] != TLS_EMPTY_RENEGOTIATION_INFO_SCSV); ASSERT_EQ(parseLen, *len); FRAME_PackRecordBody(&frameType, &frameMsg, data, bufSize, len); EXIT: FRAME_CleanMsg(&frameType, &frameMsg); return; } /** @ * @test UT_TLS_TLS12_RFC5746_CONSISTENCY_EXTENDED_RENEGOTIATION_FUNC_TC004 * @title The client and server support renegotiation and connection establishment. Check whether the clienthello * contains the renegotiation extension. Check whether the connection is successfully established and verify the * negotiation behavior. * @precon nan * @brief 1. Enable the client to support renegotiation and connection establishment. Initiate renegotiation and check * whether the client hello contains secure Renegotiation extension and whether the cipher suite list contains * the SCSV cipher suite. * @expect 1. The client hello message contain the secure Renegotiation extension but does not contain the SCSV cipher * suite. @ */ /* BEGIN_CASE */ void UT_TLS_TLS12_RFC5746_CONSISTENCY_EXTENDED_RENEGOTIATION_FUNC_TC004(void) { FRAME_Init(); HITLS_Config *config = NULL; FRAME_LinkObj *client = NULL; FRAME_LinkObj *server = NULL; /* If the client and server support renegotiation and connection establishment, check the clienthello message that * contains the renegotiation extension, and check whether the connection establishment is successful. */ config = HITLS_CFG_NewTLS12Config(); 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); ASSERT_EQ(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, HS_STATE_BUTT) == HITLS_SUCCESS); RecWrapper wrapper = {TRY_SEND_CLIENT_HELLO, REC_TYPE_HANDSHAKE, false, NULL, Test_ClientHello_SecRenego}; RegisterWrapper(wrapper); ASSERT_TRUE(FRAME_CreateConnection(client, server, false, HS_STATE_BUTT) == HITLS_SUCCESS); EXIT: ClearWrapper(); HITLS_CFG_FreeConfig(config); FRAME_FreeLink(client); FRAME_FreeLink(server); } /* END_CASE */ static void Test_ModifyServerHello_Secrenegotiation1( 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->secRenego.exData.data[0] = serverMsg->secRenego.exData.data[0] + 1; FRAME_PackRecordBody(&frameType, &frameMsg, data, bufSize, len); EXIT: FRAME_CleanMsg(&frameType, &frameMsg); return; } static void Test_ModifyServerHello_Secrenegotiation2( 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->secRenego.exData.data[serverMsg->secRenego.exData.size - 1] = serverMsg->secRenego.exData.data[serverMsg->secRenego.exData.size - 1] + 1; FRAME_PackRecordBody(&frameType, &frameMsg, data, bufSize, len); EXIT: FRAME_CleanMsg(&frameType, &frameMsg); return; } /** @ * @test UT_TLS_TLS12_RFC5746_CONSISTENCY_EXTENDED_RENEGOTIATION_FUNC_TC007 * @title HITLS_GetRenegotiationState Interface Verification * @precon nan * @brief Configure the client and server to support renegotiation and connection establishment. * Initiate renegotiation, modify the first part of renegotiated_connection in the server hello message, * and check whether the connection is set up successfully. * @expect * create connection failed @ */ /* BEGIN_CASE */ void UT_TLS_TLS12_RFC5746_CONSISTENCY_EXTENDED_RENEGOTIATION_FUNC_TC007(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); RecWrapper wrapper = { TRY_SEND_SERVER_HELLO, REC_TYPE_HANDSHAKE, false, NULL, Test_ModifyServerHello_Secrenegotiation1}; RegisterWrapper(wrapper); ASSERT_EQ(FRAME_CreateRenegotiationState(client, server, false, HS_STATE_BUTT), HITLS_MSG_HANDLE_RENEGOTIATION_FAIL); EXIT: ClearWrapper(); HITLS_CFG_FreeConfig(config); FRAME_FreeLink(client); FRAME_FreeLink(server); } /* END_CASE */ /** @ * @test UT_TLS_TLS12_RFC5746_CONSISTENCY_EXTENDED_RENEGOTIATION_FUNC_TC008 * @spec - * @title HITLS_GetRenegotiationState Interface Verification * @precon nan * @brief Configure the client and server to support renegotiation and connection establishment. * Initiate renegotiation, modify the last part of renegotiated_connection in the server hello message, * and check whether the connection is set up successfully. * @expect * create connection failed @ */ /* BEGIN_CASE */ void UT_TLS_TLS12_RFC5746_CONSISTENCY_EXTENDED_RENEGOTIATION_FUNC_TC008(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); RecWrapper wrapper = { TRY_SEND_SERVER_HELLO, REC_TYPE_HANDSHAKE, false, NULL, Test_ModifyServerHello_Secrenegotiation2}; RegisterWrapper(wrapper); ASSERT_EQ(FRAME_CreateRenegotiationState(client, server, false, HS_STATE_BUTT), HITLS_MSG_HANDLE_RENEGOTIATION_FAIL); EXIT: ClearWrapper(); HITLS_CFG_FreeConfig(config); FRAME_FreeLink(client); FRAME_FreeLink(server); } /* END_CASE */ static void Test_ModifyServerHello_Secrenegotiation3( 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->secRenego.exState = MISSING_FIELD; FRAME_PackRecordBody(&frameType, &frameMsg, data, bufSize, len); EXIT: FRAME_CleanMsg(&frameType, &frameMsg); return; } /** @ * @test UT_TLS_TLS12_RFC5746_CONSISTENCY_EXTENDED_RENEGOTIATION_FUNC_TC006 * @title HITLS_GetRenegotiationState Interface Verification * @precon nan * @brief Configure the client to support renegotiation and the server to support renegotiation and connection * establishment. Start renegotiation, construct a server hello message that does not contain the extension, * and check whether the connection is successfully set up. * @expect * The server hello message does not contain the Secrenegotiation extension, and the connection fails to be established @ */ /* BEGIN_CASE */ void UT_TLS_TLS12_RFC5746_CONSISTENCY_EXTENDED_RENEGOTIATION_FUNC_TC006(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); RecWrapper wrapper = { TRY_SEND_SERVER_HELLO, REC_TYPE_HANDSHAKE, false, NULL, Test_ModifyServerHello_Secrenegotiation3}; RegisterWrapper(wrapper); ASSERT_EQ(FRAME_CreateRenegotiationState(client, server, false, HS_STATE_BUTT), HITLS_MSG_HANDLE_RENEGOTIATION_FAIL); 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_HANDSHAKE_FAILURE); EXIT: ClearWrapper(); HITLS_CFG_FreeConfig(config); FRAME_FreeLink(client); FRAME_FreeLink(server); } /* END_CASE */ static void Test_ModifyClientHello_Secrenegotiation1( 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, CLIENT_HELLO); FRAME_ClientHelloMsg *clientMsg = &frameMsg.body.hsMsg.body.clientHello; clientMsg->secRenego.exData.data[0] = clientMsg->secRenego.exData.data[0] + 1; FRAME_PackRecordBody(&frameType, &frameMsg, data, bufSize, len); EXIT: FRAME_CleanMsg(&frameType, &frameMsg); return; } /** @ * @test UT_TLS_TLS12_RFC5746_CONSISTENCY_EXTENDED_RENEGOTIATION_FUNC_TC0014 * @title The value of client_verify_data in the client hello message does not match the actual value * in the renegotiation state. * @precon nan * @brief * Configure the client and server to support renegotiation. * After the first handshake is complete, initiate a renegotiation request. * When the client sends a client hello message, * modify the value of client_verify_data in the renegotiation_info extension. * @expect * The server returns an alert message after receiving the message. @ */ /* BEGIN_CASE */ void UT_TLS_TLS12_RFC5746_CONSISTENCY_EXTENDED_RENEGOTIATION_FUNC_TC0014(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); HITLS_SetClientRenegotiateSupport(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); RecWrapper wrapper = { TRY_SEND_CLIENT_HELLO, REC_TYPE_HANDSHAKE, false, NULL, Test_ModifyClientHello_Secrenegotiation1}; RegisterWrapper(wrapper); ASSERT_TRUE(HITLS_Connect(client->ssl) == HITLS_REC_NORMAL_RECV_BUF_EMPTY); 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_MSG_HANDLE_RENEGOTIATION_FAIL); 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_HANDSHAKE_FAILURE); EXIT: ClearWrapper(); HITLS_CFG_FreeConfig(config); FRAME_FreeLink(client); FRAME_FreeLink(server); } /* END_CASE */ static void Test_ModifyServerHello_No_client_verify_data( 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->secRenego.exData.size = 0; serverMsg->secRenego.exDataLen.data = 0; FRAME_PackRecordBody(&frameType, &frameMsg, data, bufSize, len); EXIT: FRAME_CleanMsg(&frameType, &frameMsg); return; } /** @ * @test UT_TLS_TLS12_RFC5746_CONSISTENCY_EXTENDED_RENEGOTIATION_FUNC_TC0015 * @title The client_verify_data and server_verify_data fields of the client hello message are lost in the renegotiation state. * @precon nan * @brief * Configure the client and server to support renegotiation. * After the first handshake is complete, initiate a renegotiation request. * When the server sends a server hello message, * delete the values of client_verify_data and server_verify_data from the renegotiation_info extension. * @expect * The client returns an alert message after receiving the message. @ */ /* BEGIN_CASE */ void UT_TLS_TLS12_RFC5746_CONSISTENCY_EXTENDED_RENEGOTIATION_FUNC_TC0015(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); RecWrapper wrapper = { TRY_SEND_SERVER_HELLO, REC_TYPE_HANDSHAKE, false, NULL, Test_ModifyServerHello_No_client_verify_data}; RegisterWrapper(wrapper); ASSERT_EQ(FRAME_CreateRenegotiationState(client, server, false, HS_STATE_BUTT), HITLS_MSG_HANDLE_RENEGOTIATION_FAIL); 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_HANDSHAKE_FAILURE); EXIT: ClearWrapper(); HITLS_CFG_FreeConfig(config); FRAME_FreeLink(client); FRAME_FreeLink(server); } /* END_CASE */ static void Test_ClientHelloHaveSecRenego(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); FRAME_ClientHelloMsg *clientMsg = &frameMsg.body.hsMsg.body.clientHello; ASSERT_EQ(clientMsg->secRenego.exState, INITIAL_FIELD); clientMsg->cipherSuites.data[clientMsg->cipherSuitesSize.data / 2 - 1] = TLS_EMPTY_RENEGOTIATION_INFO_SCSV; ASSERT_EQ(parseLen, *len); FRAME_PackRecordBody(&frameType, &frameMsg, data, bufSize, len); EXIT: FRAME_CleanMsg(&frameType, &frameMsg); return; } /** @ * @test UT_TLS_TLS12_RFC5746_CONSISTENCY_EXTENDED_RENEGOTIATION_FUNC_TC0012 * @title In the renegotiation state, the client hello message carries the SCSV. * @precon nan * @brief * Configure the client and server to support renegotiation. After the first handshake is complete, * initiate a renegotiation request. When the client sends a client hello message, modify the cipher suite and add SCSV. * After receiving the message, the server is expected to return an alert message. * @expect * The client returns an alert message after receiving the message. @ */ /* BEGIN_CASE */ void UT_TLS_TLS12_RFC5746_CONSISTENCY_EXTENDED_RENEGOTIATION_FUNC_TC0012(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); HITLS_SetClientRenegotiateSupport(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); RecWrapper wrapper = {TRY_SEND_CLIENT_HELLO, REC_TYPE_HANDSHAKE, false, NULL, Test_ClientHelloHaveSecRenego}; RegisterWrapper(wrapper); ASSERT_TRUE(HITLS_Connect(client->ssl) == HITLS_REC_NORMAL_RECV_BUF_EMPTY); 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_MSG_HANDLE_RENEGOTIATION_FAIL); 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_HANDSHAKE_FAILURE); EXIT: ClearWrapper(); HITLS_CFG_FreeConfig(config); FRAME_FreeLink(client); FRAME_FreeLink(server); } /* END_CASE */
2301_79861745/bench_create
testcode/sdv/testcase/tls/consistency/tls12/test_suite_sdv_frame_tls12_consistency_rfc5746.c
C
unknown
50,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_tls12_consistency_rfc5246 */ #include "securec.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 "conn_init.h" /* END_HEADER */ #define g_uiPort 12121 /** @ * @test UT_TLS_TLS12_RFC8422_CONSISTENCY_ECDHE_LOSE_POINT_FUNC_TC001 * @title clienthello does not carry the point format extension. * @precon nan * @brief Set the ECC cipher suite. Before the server receives the client hello message, the point format extension is * removed. It is expected that the negotiation is normal and the client can receive the server hello done * message. * @expect 1. The connection is set up normally and the client can receive the server hello done message. @ */ /* BEGIN_CASE */ void UT_TLS_TLS12_RFC8422_CONSISTENCY_ECDHE_LOSE_POINT_FUNC_TC001(void) { FRAME_Msg frameMsg = {0}; FRAME_Type frameType = {0}; HandshakeTestInfo testInfo = {0}; testInfo.isClient = false; testInfo.state = TRY_RECV_CLIENT_HELLO; testInfo.isSupportClientVerify = true; ASSERT_TRUE(DefaultCfgStatusParkWithSuite(&testInfo) == 0); FrameUioUserData *ioUserData = BSL_UIO_GetUserData(testInfo.server->io); uint32_t parseLen = 0; FRAME_ParseMsg(&frameType, ioUserData->recMsg.msg, ioUserData->recMsg.len, &frameMsg, &parseLen); /* Set the ECC cipher suite. Before the server receives the client hello message, the point format extension is * removed. */ frameMsg.body.hsMsg.body.clientHello.pointFormats.exState = MISSING_FIELD; FRAME_PackMsg(&frameType, &frameMsg, ioUserData->recMsg.msg, MAX_RECORD_LENTH, &parseLen); ioUserData->recMsg.len = parseLen; FRAME_CleanMsg(&frameType, &frameMsg); memset_s(&frameMsg, sizeof(frameMsg), 0, sizeof(frameMsg)); // the client can receive the server hello done message. ASSERT_TRUE( FRAME_CreateConnection(testInfo.client, testInfo.server, true, TRY_RECV_SERVER_HELLO_DONE) == HITLS_SUCCESS); EXIT: FRAME_CleanMsg(&frameType, &frameMsg); HITLS_CFG_FreeConfig(testInfo.config); FRAME_FreeLink(testInfo.client); FRAME_FreeLink(testInfo.server); FRAME_DeRegCryptMethod(); } /* END_CASE */
2301_79861745/bench_create
testcode/sdv/testcase/tls/consistency/tls12/test_suite_sdv_frame_tls12_consistency_rfc8422.c
C
unknown
3,010
/* * This file is part of the openHiTLS project. * * openHiTLS is licensed under the Mulan PSL v2. * You can use this software according to the terms and conditions of the Mulan PSL v2. * You may obtain a copy of Mulan PSL v2 at: * * http://license.coscl.org.cn/MulanPSL2 * * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, * EITHER EXPRESS 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 */ /* END_HEADER */ static void TestFrameClientChangeCompressMethod(void *msg, void *userData) { (void)msg; (void)userData; FRAME_Msg *frameMsg = (FRAME_Msg *)msg; FRAME_ClientHelloMsg *clientHello = &frameMsg->body.hsMsg.body.clientHello; clientHello->compressionMethods.state = ASSIGNED_FIELD; *clientHello->compressionMethods.data = 1; } /* @ * @test SDV_TLS_TLS12_RFC5246_CONSISTENCY_ERRO_COMPRESSION_FRAGMENT_TC001 * @title The record layer does not support compression. * @precon nan * @brief 1. When the client sends a client hello message, the compression flag is changed to 1. As a result, the connection fails to be established. * @expect 1. Link establishment fails. @ */ /* BEGIN_CASE */ void SDV_TLS_TLS12_RFC5246_CONSISTENCY_ERRO_COMPRESSION_FRAGMENT_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_RSA_PKCS1_SHA256"); HLT_SetClientVerifySupport(serverCtxConfig, true); clientCtxConfig = HLT_NewCtxConfig(NULL, "CLIENT"); ASSERT_TRUE(clientCtxConfig != NULL); TestSetCertPath(clientCtxConfig, "CERT_SIG_SCHEME_RSA_PKCS1_SHA256"); 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(remoteProcess, TLS1_2, serverCtxConfig, NULL); ASSERT_TRUE(serverRes != NULL); // When the client sends a client hello message, the compression flag is changed to 1. clientRes = HLT_ProcessTlsInit(localProcess, TLS1_2, clientCtxConfig, NULL); HLT_FrameHandle frameHandle = { .ctx = clientRes->ssl, .frameCallBack = TestFrameClientChangeCompressMethod, .userData = NULL, .expectHsType = CLIENT_HELLO, .expectReType = REC_TYPE_HANDSHAKE, .ioState = EXP_NONE, .pointType = POINT_SEND, }; ASSERT_TRUE(HLT_SetFrameHandle(&frameHandle) == HITLS_SUCCESS); int ret = HLT_TlsConnect(clientRes->ssl); ASSERT_TRUE(ret != 0); EXIT: HLT_FreeAllProcess(); HLT_CleanFrameHandle(); } /* END_CASE */ static void TestFrameServerChangeCompressMethod(void *msg, void *userData) { (void)msg; (void)userData; FRAME_Msg *frameMsg = (FRAME_Msg *)msg; FRAME_ServerHelloMsg *serverHello = &frameMsg->body.hsMsg.body.serverHello; serverHello->compressionMethod.state = ASSIGNED_FIELD; serverHello->compressionMethod.data = 1; } /* @ * @test SDV_TLS_TLS12_RFC5246_CONSISTENCY_ERRO_COMPRESSION_FRAGMENT_TC002 * @title The record layer does not support compression. * @precon nan * @brief 1. When the server sends the serverhello message, the compression flag is changed to 1, and the client is expected to send the alert message. * @expect 1. A failure message is returned. @ */ /* BEGIN_CASE */ void SDV_TLS_TLS12_RFC5246_CONSISTENCY_ERRO_COMPRESSION_FRAGMENT_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); TestSetCertPath(clientCtxConfig, "CERT_SIG_SCHEME_RSA_PKCS1_SHA256"); HLT_SetClientVerifySupport(clientCtxConfig, true); HLT_SetCipherSuites(clientCtxConfig, "HITLS_RSA_WITH_AES_256_CBC_SHA"); HLT_SetSignature(clientCtxConfig, "CERT_SIG_SCHEME_RSA_PKCS1_SHA256"); /* When the server sends the serverhello message, the compression flag is changed to 1. */ serverRes = HLT_ProcessTlsAccept(localProcess, TLS1_2, serverCtxConfig, NULL); ASSERT_TRUE(serverRes != NULL); HLT_FrameHandle frameHandle = { .ctx = serverRes->ssl, .frameCallBack = TestFrameServerChangeCompressMethod, .userData = NULL, .expectHsType = SERVER_HELLO, .expectReType = REC_TYPE_HANDSHAKE, .ioState = EXP_NONE, .pointType = POINT_SEND, }; ASSERT_TRUE(HLT_SetFrameHandle(&frameHandle) == HITLS_SUCCESS); clientRes = HLT_ProcessTlsConnect(remoteProcess, TLS1_2, clientCtxConfig, NULL); ASSERT_TRUE(clientRes == NULL); EXIT: HLT_FreeAllProcess(); HLT_CleanFrameHandle(); } /* END_CASE */ /* @ * @test SDV_TLS_TLS12_RFC5246_CONSISTENCY_CERTFICATE_VERITY_FAIL_TC008 * @title two-way authentication: The certificate configured on the client does not match the signature algorithm supported by the server. As a result, the client fails to load the certificate. * @precon nan * @brief Set the dual-end authentication, the signature algorithm supported by the server to DSA_SHA224, and the client certificate to RSA. The expected certificate loading failure occurs on the client. * @expect 1. The link is set up successfully. * 2. Link establishment failure. @ */ /* BEGIN_CASE */ void SDV_TLS_TLS12_RFC5246_CONSISTENCY_CERTFICATE_VERITY_FAIL_TC008(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); /* Set the dual-end authentication, the signature algorithm supported by the server to DSA_SHA224, and the client * certificate to RSA. */ TestSetCertPath(serverCtxConfig, "CERT_SIG_SCHEME_RSA_PKCS1_SHA256"); HLT_SetClientVerifySupport(serverCtxConfig, true); HLT_SetSignature(serverCtxConfig, "CERT_SIG_SCHEME_DSA_SHA224"); clientCtxConfig = HLT_NewCtxConfig(NULL, "CLIENT"); ASSERT_TRUE(clientCtxConfig != NULL); TestSetCertPath(clientCtxConfig, "CERT_SIG_SCHEME_RSA_PKCS1_SHA256"); HLT_SetClientVerifySupport(serverCtxConfig, true); HLT_SetCipherSuites(clientCtxConfig, "HITLS_RSA_WITH_AES_128_GCM_SHA256"); HLT_SetSignature(clientCtxConfig, "CERT_SIG_SCHEME_RSA_PKCS1_SHA256"); serverRes = HLT_ProcessTlsAccept(remoteProcess, TLS1_2, serverCtxConfig, NULL); ASSERT_TRUE(serverRes != NULL); clientRes = HLT_ProcessTlsInit(localProcess, TLS1_2, clientCtxConfig, NULL); ASSERT_TRUE(clientRes != NULL); int ret = HLT_TlsConnect(clientRes->ssl); ASSERT_TRUE(ret != 0); EXIT: HLT_FreeAllProcess(); HLT_CleanFrameHandle(); } /* END_CASE */ int32_t SendKeyupdate_Err(HITLS_Ctx *ctx) { /** Initialize the message buffer. */ uint8_t buf[5] = {KEY_UPDATE, 0x00, 0x00, 0x01, 0x01}; size_t len = 5; /** Write records. */ return REC_Write(ctx, REC_TYPE_HANDSHAKE, buf, len); } /* tls12 receive keyupdate message during transporting*/ /* BEGIN_CASE */ void SDV_TLS_TLS12_RFC5246_CONSISTENCY_RECV_KEYUPDATE_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); clientCtxConfig = HLT_NewCtxConfig(NULL, "CLIENT"); ASSERT_TRUE(clientCtxConfig != NULL); clientCtxConfig->isSupportExtendMasterSecret=true; serverCtxConfig->isSupportExtendMasterSecret=true; serverCtxConfig->isSupportSessionTicket=true; clientCtxConfig->isSupportSessionTicket=true; 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(remoteProcess, clientRes, (uint8_t *)"Hello World", strlen("Hello World")) == 0); uint8_t readBuf2[READ_BUF_LEN_18K] = {0}; uint32_t readLen2= 0; ASSERT_EQ(HLT_ProcessTlsRead(localProcess, serverRes, readBuf2, READ_BUF_LEN_18K, &readLen2) , 0); ASSERT_TRUE(HLT_ProcessTlsWrite(localProcess, serverRes, (uint8_t *)"Hello World", strlen("Hello World")) == 0); ASSERT_EQ(HLT_ProcessTlsRead(remoteProcess, clientRes, readBuf2, READ_BUF_LEN_18K, &readLen2) , 0); HITLS_Ctx *serverCtx = (HITLS_Ctx *)serverRes->ssl; ASSERT_TRUE(serverCtx->state == CM_STATE_TRANSPORTING); ASSERT_EQ(SendKeyupdate_Err(serverRes->ssl) , HITLS_SUCCESS); uint8_t readBuf[READ_BUF_LEN_18K] = {0}; uint32_t readLen= 0; ASSERT_EQ(HLT_ProcessTlsRead(remoteProcess, clientRes, readBuf, READ_BUF_LEN_18K, &readLen) , HITLS_REC_NORMAL_RECV_UNEXPECT_MSG); ASSERT_EQ(HLT_ProcessTlsRead(localProcess, serverRes, readBuf, READ_BUF_LEN_18K, &readLen) , HITLS_REC_NORMAL_RECV_UNEXPECT_MSG); ALERT_Info info = { 0 }; ALERT_GetInfo(serverRes->ssl, &info); ASSERT_EQ(info.flag, ALERT_FLAG_RECV); ASSERT_EQ(info.level, ALERT_LEVEL_FATAL); ASSERT_EQ(info.description, ALERT_UNEXPECTED_MESSAGE); EXIT: HLT_FreeAllProcess(); HLT_CleanFrameHandle(); } /* END_CASE */ int32_t SendNEW_SESSION_TICKET_Err(HITLS_Ctx *ctx) { /** Initialize the message buffer. */ uint8_t buf[32] = {NEW_SESSION_TICKET,0,0,0x1c,0x20,0xc1,}; size_t len = 32; /** Write records. */ return REC_Write(ctx, REC_TYPE_HANDSHAKE, buf, len); } /* tls12 receive NST message during transporting*/ /* BEGIN_CASE */ void SDV_TLS_TLS12_RFC5246_CONSISTENCY_RECV_NST_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); clientCtxConfig = HLT_NewCtxConfig(NULL, "CLIENT"); ASSERT_TRUE(clientCtxConfig != NULL); clientCtxConfig->isSupportExtendMasterSecret=true; serverCtxConfig->isSupportExtendMasterSecret=true; serverCtxConfig->isSupportSessionTicket=true; clientCtxConfig->isSupportSessionTicket=true; 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(remoteProcess, clientRes, (uint8_t *)"Hello World", strlen("Hello World")) == 0); uint8_t readBuf2[READ_BUF_LEN_18K] = {0}; uint32_t readLen2= 0; ASSERT_EQ(HLT_ProcessTlsRead(localProcess, serverRes, readBuf2, READ_BUF_LEN_18K, &readLen2) , 0); ASSERT_TRUE(HLT_ProcessTlsWrite(localProcess, serverRes, (uint8_t *)"Hello World", strlen("Hello World")) == 0); ASSERT_EQ(HLT_ProcessTlsRead(remoteProcess, clientRes, readBuf2, READ_BUF_LEN_18K, &readLen2) , 0); HITLS_Ctx *serverCtx = (HITLS_Ctx *)serverRes->ssl; ASSERT_TRUE(serverCtx->state == CM_STATE_TRANSPORTING); ASSERT_EQ(SendNEW_SESSION_TICKET_Err(serverRes->ssl) , HITLS_SUCCESS); uint8_t readBuf[READ_BUF_LEN_18K] = {0}; uint32_t readLen= 0; ASSERT_EQ(HLT_ProcessTlsRead(remoteProcess, clientRes, readBuf, READ_BUF_LEN_18K, &readLen) , HITLS_REC_NORMAL_RECV_UNEXPECT_MSG); ASSERT_EQ(HLT_ProcessTlsRead(localProcess, serverRes, readBuf, READ_BUF_LEN_18K, &readLen) , HITLS_REC_NORMAL_RECV_UNEXPECT_MSG); ALERT_Info info = { 0 }; ALERT_GetInfo(serverRes->ssl, &info); ASSERT_EQ(info.flag, ALERT_FLAG_RECV); ASSERT_EQ(info.level, ALERT_LEVEL_FATAL); ASSERT_EQ(info.description, ALERT_UNEXPECTED_MESSAGE); EXIT: HLT_FreeAllProcess(); HLT_CleanFrameHandle(); } /* END_CASE */ /* BEGIN_CASE */ void SDV_TLS_TLS12_StateTrans_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); clientCtxConfig = HLT_NewCtxConfig(NULL, "CLIENT"); ASSERT_TRUE(clientCtxConfig != NULL); clientCtxConfig->isSupportExtendMasterSecret=true; serverCtxConfig->isSupportExtendMasterSecret=true; serverCtxConfig->isSupportSessionTicket=true; clientCtxConfig->isSupportSessionTicket=true; 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(remoteProcess, clientRes, (uint8_t *)"Hello World", strlen("Hello World")) == 0); uint8_t readBuf2[READ_BUF_LEN_18K] = {0}; uint32_t readLen2= 0; ASSERT_EQ(HLT_ProcessTlsRead(localProcess, serverRes, readBuf2, READ_BUF_LEN_18K, &readLen2) , 0); ASSERT_TRUE(HLT_ProcessTlsWrite(localProcess, serverRes, (uint8_t *)"Hello World", strlen("Hello World")) == 0); ASSERT_EQ(HLT_ProcessTlsRead(remoteProcess, clientRes, readBuf2, READ_BUF_LEN_18K, &readLen2) , 0); HITLS_Ctx *serverCtx = (HITLS_Ctx *)serverRes->ssl; ASSERT_TRUE(serverCtx->state == CM_STATE_TRANSPORTING); ASSERT_EQ(SendKeyupdate_Err(serverRes->ssl) , HITLS_SUCCESS); uint8_t readBuf[READ_BUF_LEN_18K] = {0}; uint32_t readLen= 0; ASSERT_EQ(HLT_ProcessTlsRead(remoteProcess, clientRes, readBuf, READ_BUF_LEN_18K, &readLen) , HITLS_REC_NORMAL_RECV_UNEXPECT_MSG); ASSERT_EQ(HLT_ProcessTlsRead(localProcess, serverRes, readBuf, READ_BUF_LEN_18K, &readLen) , HITLS_REC_NORMAL_RECV_UNEXPECT_MSG); ALERT_Info info = { 0 }; ALERT_GetInfo(serverRes->ssl, &info); ASSERT_EQ(info.flag, ALERT_FLAG_RECV); ASSERT_EQ(info.level, ALERT_LEVEL_FATAL); ASSERT_EQ(info.description, ALERT_UNEXPECTED_MESSAGE); EXIT: HLT_FreeAllProcess(); HLT_CleanFrameHandle(); } /* END_CASE */ static void MalformedCipherSuiteLenCallback_01(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_ClientHelloMsg *clientHello = &frameMsg->body.hsMsg.body.clientHello; clientHello->cipherSuitesSize.data = 1000; clientHello->cipherSuitesSize.state = ASSIGNED_FIELD; EXIT: return; } void ClientSendMalformedCipherSuiteLenMsg(HLT_FrameHandle *handle, TestPara *testPara) { HLT_Process *localProcess = HLT_InitLocalProcess(HITLS); ASSERT_TRUE(localProcess != NULL); HLT_Process *remoteProcess = HLT_LinkRemoteProcess(HITLS, TCP, 16384, false); ASSERT_TRUE(remoteProcess != NULL); // The remote server listens on the TLS connection. HLT_Ctx_Config *serverConfig = HLT_NewCtxConfig(NULL, "SERVER"); ASSERT_TRUE(serverConfig != NULL); ASSERT_TRUE(HLT_SetClientVerifySupport(serverConfig, testPara->isSupportClientVerify) == 0); serverConfig->isSupportExtendMasterSecret = false; 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); serverConfig->isSupportExtendMasterSecret = false; 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 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); } ALERT_Info alertInfo = { 0 }; ALERT_GetInfo(clientRes->ssl, &alertInfo); ASSERT_EQ(alertInfo.level, ALERT_LEVEL_FATAL); ASSERT_EQ(alertInfo.description, testPara->expectDescription); EXIT: HLT_CleanFrameHandle(); HLT_FreeAllProcess(); return; } /** @ * @test SDV_TLS1_2_RFC5246_MALFORMED_CIPHER_SUITE_LEN_FUN_TC001 * @spec - * @title The length of the cipher suite in the sent ClientHello message is greater than the specific content length_cipher suites length * @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. * @prior Level 1 * @auto TRUE @ */ /* BEGIN_CASE */ void SDV_TLS_TLS12_RFC5246_MALFORMED_CIPHER_SUITE_LEN_FUN_TC001() { 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; /* 2. Obtain the message, modify the field content, and send the message. */ handle.frameCallBack = MalformedCipherSuiteLenCallback_01; TestPara testPara = {0}; testPara.port = g_uiPort; /* 4. Check the status of the test. */ testPara.expectHsState = TRY_RECV_SERVER_HELLO; /* 3. Check the status of the tested */ testPara.expectDescription = ALERT_DECODE_ERROR; ClientSendMalformedCipherSuiteLenMsg(&handle, &testPara); return; } /* END_CASE */ static void TEST_Server_check_etm_ext(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_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; ASSERT_EQ(serverMsg->encryptThenMac.exType.data, HS_EX_TYPE_ENCRYPT_THEN_MAC); EXIT: FRAME_CleanMsg(&frameType, &frameMsg); return; } /* @ * @test SDV_TLS_TLS1_2_RFC5246_HANDSHAKE_FUNC_TC001 * @spec - * @title Test link establishment when the tls1.2 client cipher suite does not match the certificate. * @precon nan * @brief 1. Configure the ecdhe_ecdsa cipher suite, certificate, and RSA certificate chain on the server. Expected result 1 is obtained. 2. Configure the RSA certificate and ecdsa certificate chain on the client. Expected result 2 is obtained. 3. Establish a link between the two ends. Expected result 3 is obtained. 4. Read and write data. Expected result 4 is obtained. * @expect 1. A success message is returned. 2. A success message is returned. 3. A success message is returned. 4. Return a success message. * @prior Level 1 * @auto TRUE @ */ /* BEGIN_CASE */ void SDV_TLS_TLS1_2_RFC5246_HANDSHAKE_FUNC_TC001() { 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); // Configure the ecdhe_ecdsa cipher suite, certificate, and RSA certificate chain on the server. HLT_SetCertPath(serverCtxConfig, RSA_SHA_CA_PATH, RSA_SHA_CHAIN_PATH, ECDSA_SHA256_EE_PATH, ECDSA_SHA256_PRIV_PATH, "NULL", "NULL"); HLT_SetClientVerifySupport(serverCtxConfig, true); HLT_SetNoClientCertSupport(serverCtxConfig, false); HLT_SetCipherSuites(serverCtxConfig, "HITLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA"); HLT_Ctx_Config *clientCtxConfig = HLT_NewCtxConfig(NULL, "CLIENT"); ASSERT_TRUE(clientCtxConfig != NULL); // Configure the RSA certificate and ecdsa certificate chain on the client. HLT_SetCertPath(clientCtxConfig, ECDSA_SHA_CA_PATH, ECDSA_SHA_CHAIN_PATH, RSA_SHA1_EE_PATH, RSA_SHA1_PRIV_PATH, "NULL", "NULL"); RecWrapper wrapper = { TRY_SEND_SERVER_HELLO, REC_TYPE_HANDSHAKE, false, NULL, TEST_Server_check_etm_ext }; RegisterWrapper(wrapper); // Establish a link between the two ends. 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); // Read and write data. 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, sizeof(readBuf), &readLen) == 0); ASSERT_TRUE(readLen == strlen("Hello World")); ASSERT_TRUE(memcmp("Hello World", readBuf, readLen) == 0); EXIT: ClearWrapper(); HLT_FreeAllProcess(); } /* END_CASE */
2301_79861745/bench_create
testcode/sdv/testcase/tls/consistency/tls12/test_suite_sdv_hlt_tls12_consistency_rfc5246.c
C
unknown
24,590
/* * This file is part of the openHiTLS project. * * openHiTLS is licensed under the Mulan PSL v2. * You can use this software according to the terms and conditions of the Mulan PSL v2. * You may obtain a copy of Mulan PSL v2 at: * * http://license.coscl.org.cn/MulanPSL2 * * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, * EITHER EXPRESS 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 */ /* END_HEADER */ /* @ * @test SDV_TLS_TLS12_RFC5246_CONSISTENCY_CIPHER_SUITE_NOT_SUITABLE_CERT_TC001 * @title The public key algorithm used to verify the server terminal certificate must match the algorithm suite. * @precon nan * @brief 1. Create a config file, configure the server certificate as the ECDSA public key, and configure the ECDHE_RSA algorithm suite in the hello message on the client. 2. The client invokes the HITLS_Connect interface. (Expected result 1) * @expect 1. A failure message is returned. @ */ /* BEGIN_CASE */ void SDV_TLS_TLS12_RFC5246_CONSISTENCY_CIPHER_SUITE_NOT_SUITABLE_CERT_TC001(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, false); ASSERT_TRUE(remoteProcess != NULL); // Create a config file, configure the server certificate as the ECDSA public key, and configure the ECDHE_RSA algorithm suite in the hello message on the client. HLT_Ctx_Config *serverCtxConfig = HLT_NewCtxConfig(NULL, "SERVER"); ASSERT_TRUE(serverCtxConfig != NULL); TestSetCertPath(serverCtxConfig, "CERT_SIG_SCHEME_ECDSA_SECP256R1_SHA256"); serverRes = HLT_ProcessTlsAccept(localProcess, TLS1_2, serverCtxConfig, NULL); ASSERT_TRUE(serverRes != NULL); // failed in HLT_Ctx_Config *clientCtxConfig = HLT_NewCtxConfig(NULL, "CLIENT"); ASSERT_TRUE(clientCtxConfig != NULL); TestSetCertPath(clientCtxConfig, "CERT_SIG_SCHEME_RSA_PKCS1_SHA256"); HLT_SetGroups(clientCtxConfig, "HITLS_EC_GROUP_SECP256R1"); HLT_SetCipherSuites(clientCtxConfig, "HITLS_ECDHE_RSA_WITH_AES_128_CBC_SHA256"); HLT_SetSignature(clientCtxConfig, "CERT_SIG_SCHEME_RSA_PKCS1_SHA256"); // The client invokes the HITLS_Connect interface. clientRes = HLT_ProcessTlsConnect(remoteProcess, TLS1_2, clientCtxConfig, NULL); ASSERT_TRUE(clientRes == NULL); EXIT: HLT_FreeAllProcess(); return; } /* END_CASE */ /* @ * @test SDV_TLS_TLS12_RFC5246_CONSISTENCY_CLIENT_NOTSET_CERT_TC001 * @title The certificate chain sent by the server does not contain the root certificate. * @precon nan * @brief If no certificate is set on the client and the server sends a complete certificate chain, * link establishment fails. * @expect 1. A failure message is returned. @ */ /* BEGIN_CASE */ void SDV_TLS_TLS12_RFC5246_CONSISTENCY_CLIENT_NOTSET_CERT_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_RSA_PKCS1_SHA256"); clientCtxConfig = HLT_NewCtxConfig(NULL, "CLIENT"); ASSERT_TRUE(clientCtxConfig != NULL); HLT_SetCipherSuites(clientCtxConfig, "HITLS_RSA_WITH_AES_256_CBC_SHA"); HLT_SetSignature(clientCtxConfig, "CERT_SIG_SCHEME_RSA_PKCS1_SHA256"); serverRes = HLT_ProcessTlsAccept(localProcess, TLS1_2, serverCtxConfig, NULL); ASSERT_TRUE(serverRes != NULL); /* If no certificate is set on the client and the server sends a complete certificate chain,link establishment * fails. */ clientRes = HLT_ProcessTlsConnect(remoteProcess, TLS1_2, clientCtxConfig, NULL); ASSERT_TRUE(clientRes == NULL); EXIT: HLT_FreeAllProcess(); } /* END_CASE */ /* @ * @test SDV_TLS_TLS12_RFC5246_CONSISTENCY_SERVER_WITHOUT_ROOT_CERT_TC001 * @title The certificate chain sent by the server does not contain the root certificate. * @precon nan * @brief Set the root certificate and send a certificate chain that does not contain the root certificate. * The link is successfully set up. * @expect 1. Return a success message. @ */ /* BEGIN_CASE */ void SDV_TLS_TLS12_RFC5246_CONSISTENCY_SERVER_WITHOUT_ROOT_CERT_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_RSA_PKCS1_SHA256"); HLT_SetClientVerifySupport(serverCtxConfig, true); // Set the root certificate and send a certificate chain that does not contain the root certificate. clientCtxConfig = HLT_NewCtxConfig(NULL, "CLIENT"); ASSERT_TRUE(clientCtxConfig != NULL); TestSetCertPath(clientCtxConfig, "CERT_SIG_SCHEME_RSA_PKCS1_SHA256"); 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_2, serverCtxConfig, NULL); ASSERT_TRUE(serverRes != NULL); clientRes = HLT_ProcessTlsConnect(remoteProcess, TLS1_2, clientCtxConfig, NULL); ASSERT_TRUE(clientRes != NULL); EXIT: HLT_FreeAllProcess(); } /* END_CASE */ /* @ * @test SDV_TLS_TLS12_RFC5246_CONSISTENCY_CLIENT_SET_ERRO_ROOT_CERT_TC001 * @title The certificate chain sent by the server does not contain the root certificate. * @precon nan * @brief The root certificate is incorrectly set on the client. As a result, the link fails to be established. * @expect 1. A failure message is returned. @ */ /* BEGIN_CASE */ void SDV_TLS_TLS12_RFC5246_CONSISTENCY_CLIENT_SET_ERRO_ROOT_CERT_TC001(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, false); ASSERT_TRUE(remoteProcess != NULL); HLT_Ctx_Config *serverCtxConfig = HLT_NewCtxConfig(NULL, "SERVER"); ASSERT_TRUE(serverCtxConfig != NULL); TestSetCertPath(serverCtxConfig, "CERT_SIG_SCHEME_RSA_PKCS1_SHA256"); serverRes = HLT_ProcessTlsAccept(localProcess, TLS1_2, serverCtxConfig, NULL); ASSERT_TRUE(serverRes != NULL); // The root certificate is incorrectly set on the client. HLT_Ctx_Config *clientCtxConfig = HLT_NewCtxConfig(NULL, "CLIENT"); ASSERT_TRUE(clientCtxConfig != NULL); HLT_SetCertPath(clientCtxConfig, "rsa_sha512/otherRoot.crt", "rsa_sha512/otherInter.crt", "rsa_sha512/otherInter2.crt", "rsa_sha512/otherInter2.key", "NULL", "NULL"); HLT_SetCipherSuites(clientCtxConfig, "HITLS_RSA_WITH_AES_256_CBC_SHA"); HLT_SetSignature(clientCtxConfig, "CERT_SIG_SCHEME_RSA_PKCS1_SHA256"); clientRes = HLT_ProcessTlsConnect(remoteProcess, TLS1_2, clientCtxConfig, NULL); ASSERT_TRUE(clientRes == NULL); EXIT: HLT_FreeAllProcess(); return; } /* END_CASE */ /** * Configure the certificate signature as CERT_SIG_SCHEME_RSA_PKCS1_SHA256. * Set the algorithm suite to HITLS_DHE_DSS_WITH_AES_128_GCM_SHA256. * The signature type in the cipher suite does not match that in the certificate, * Expected link establishment failure, as shown in the log. * select certificate fail * have no suitable cert * can not find a appropriate cipher suite */ /* BEGIN_CASE */ void SDV_TLS_TLS12_RFC5246_CONSISTENCY_CIPHERSUITE_SIG_MATCH_CERT_SIG_TC002() { 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, false); ASSERT_TRUE(remoteProcess != NULL); HLT_Ctx_Config *serverCtxConfig = HLT_NewCtxConfig(NULL, "SERVER"); ASSERT_TRUE(serverCtxConfig != 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"); HLT_SetCipherSuites(serverCtxConfig, "HITLS_DHE_RSA_WITH_AES_128_GCM_SHA256"); serverRes = HLT_ProcessTlsAccept(remoteProcess, TLS1_2, serverCtxConfig, NULL); ASSERT_TRUE(serverRes != NULL); HLT_Ctx_Config *clientCtxConfig = HLT_NewCtxConfig(NULL, "CLIENT"); ASSERT_TRUE(clientCtxConfig != NULL); HLT_SetCertPath(clientCtxConfig, "rsa_sha256/ca.der:rsa_sha256/inter.der", "NULL", "NULL", "NULL", "NULL", "NULL"); // Set the algorithm suite to HITLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA. HLT_SetCipherSuites(clientCtxConfig, "HITLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA"); clientRes = HLT_ProcessTlsConnect(localProcess, TLS1_2, clientCtxConfig, NULL); ASSERT_TRUE(clientRes == NULL); EXIT: HLT_FreeAllProcess(); } /* END_CASE */ /* @ * @test SDV_TLS_TLS12_RFC5246_CONSISTENCY_KEYUSAGE_CERT_TC001 * @title The keyusage extension of the server certificate does not contain the keyEncipherment usage. * As a result, the link fails to be established. * @precon nan * @brief 1. Set the server certificate to an RSA certificate that contains the keyusage extension, The extension does not contain the keyEncipherment usage. The negotiation cipher suite is the RSA cipher suite. Expected result 1 is obtained. * @expect 1. connection setup failed @ */ /* BEGIN_CASE */ void SDV_TLS_TLS12_RFC5246_CONSISTENCY_KEYUSAGE_CERT_TC001() { 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, false); ASSERT_TRUE(remoteProcess != NULL); HLT_Ctx_Config *serverCtxConfig = HLT_NewCtxConfig(NULL, "SERVER"); ASSERT_TRUE(serverCtxConfig != NULL); HLT_SetCertPath(serverCtxConfig, "rsa_sha512/root.der", "rsa_sha512/intca.der", "rsa_sha512/usageKeyEncipher.der", "rsa_sha512/usageKeyEncipher.key.der", "NULL", "NULL"); HLT_SetCipherSuites(serverCtxConfig, "HITLS_RSA_WITH_AES_256_GCM_SHA384"); serverRes = HLT_ProcessTlsAccept(remoteProcess, TLS1_2, serverCtxConfig, NULL); ASSERT_TRUE(serverRes != NULL); HLT_Ctx_Config *clientCtxConfig = HLT_NewCtxConfig(NULL, "CLIENT"); ASSERT_TRUE(clientCtxConfig != NULL); HLT_SetCertPath(clientCtxConfig, "rsa_sha512/root.der", "rsa_sha512/intca.der", "rsa_sha512/server.der", "rsa_sha512/server.key.der", "NULL", "NULL"); clientCtxConfig->needCheckKeyUsage = true; clientRes = HLT_ProcessTlsConnect(localProcess, TLS1_2, clientCtxConfig, NULL); ASSERT_TRUE(clientRes == NULL); EXIT: HLT_FreeAllProcess(); } /* END_CASE */ /* @ * @test SDV_TLS_TLS12_RFC5246_CONSISTENCY_KEYUSAGE_CERT_TC002 * @title Failed to set up the link because the keyuage extension does not match. * @precon nan * @brief 1. Configure the server certificate with the keyuage extension and do not support digitalSignature. Expected result 1 is obtained. * @expect 1. connection setup failed @ */ /* BEGIN_CASE */ void SDV_TLS_TLS12_RFC5246_CONSISTENCY_KEYUSAGE_CERT_TC002() { 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, false); ASSERT_TRUE(remoteProcess != NULL); HLT_Ctx_Config *serverCtxConfig = HLT_NewCtxConfig(NULL, "SERVER"); ASSERT_TRUE(serverCtxConfig != NULL); HLT_SetCertPath(serverCtxConfig, "rsa_sha512/root.der", "rsa_sha512/intca.der", "rsa_sha512/usagedigitalSign.der", "rsa_sha512/usagedigitalSign.key.der", "NULL", "NULL"); serverRes = HLT_ProcessTlsAccept(remoteProcess, TLS1_2, serverCtxConfig, NULL); ASSERT_TRUE(serverRes != NULL); HLT_Ctx_Config *clientCtxConfig = HLT_NewCtxConfig(NULL, "CLIENT"); ASSERT_TRUE(clientCtxConfig != NULL); HLT_SetCertPath(clientCtxConfig, "rsa_sha512/root.der", "rsa_sha512/intca.der", "rsa_sha512/server.der", "rsa_sha512/server.key.der", "NULL", "NULL"); clientCtxConfig->needCheckKeyUsage = true; clientRes = HLT_ProcessTlsConnect(localProcess, TLS1_2, clientCtxConfig, NULL); ASSERT_TRUE(clientRes == NULL); EXIT: HLT_FreeAllProcess(); } /* END_CASE */
2301_79861745/bench_create
testcode/sdv/testcase/tls/consistency/tls12/test_suite_sdv_hlt_tls12_consistency_rfc5246_cert.c
C
unknown
13,772
/* * This file is part of the openHiTLS project. * * openHiTLS is licensed under the Mulan PSL v2. * You can use this software according to the terms and conditions of the Mulan PSL v2. * You may obtain a copy of Mulan PSL v2 at: * * http://license.coscl.org.cn/MulanPSL2 * * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, * EITHER EXPRESS 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 "process.h" #include "securec.h" #include "hitls_error.h" #include "frame_tls.h" #include "frame_link.h" #include "frame_io.h" #include "bsl_sal.h" #include "simulate_io.h" #include "tls.h" #include "hs_ctx.h" #include "hlt.h" #include "alert.h" #include "session_type.h" #include "process.h" #include "hitls_type.h" #include "rec.h" #include "hs_msg.h" #include "hs_extensions.h" #include "frame_msg.h" /* END_HEADER */ #define PORT 19800 #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 MAX_PROTOCOL_LEN1 65536 #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" 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 on the test end bool isSupportClientVerify; bool isSupportExtendMasterSecret; bool isSupportRenegotiation; bool isSupportSessionTicket; bool isSupportDhCipherSuites; bool isSupportSni; bool isSupportAlpn; bool isExpectRet; int expectRet; // Expected return value. isExpectRet 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 not specified, 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; 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 isServerExtendMasterSecret; } HandshakeTestInfo; 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_LEN1) { 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; } /* The local server initiates a link 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 link. 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 packets. handle->ctx = serverRes->ssl; ASSERT_TRUE(HLT_SetFrameHandle(handle) == 0); //Set up a TLS link 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); serverConfig->isSupportSessionTicket = testPara->isSupportSessionTicket; ASSERT_TRUE(HLT_SetClientVerifySupport(serverConfig, testPara->isSupportClientVerify) == 0); ASSERT_TRUE(HLT_SetRenegotiationSupport(serverConfig, testPara->isSupportRenegotiation) == 0); if (testPara->isSupportSni) { ASSERT_TRUE(HLT_SetServerNameCb(serverConfig, "ExampleSNICb") == 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"); } 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 packets. handle->ctx = serverRes->ssl; ASSERT_TRUE(HLT_SetFrameHandle(handle) == 0); //Set up a TLS link on the remote client. clientConfig = HLT_NewCtxConfig(NULL, "CLIENT"); ASSERT_TRUE(clientConfig != NULL); ASSERT_TRUE(HLT_SetExtenedMasterSecretSupport(clientConfig, testPara->isSupportExtendMasterSecret) == 0); ASSERT_TRUE(HLT_SetRenegotiationSupport(clientConfig, testPara->isSupportRenegotiation) == 0); clientConfig->isSupportSessionTicket = testPara->isSupportSessionTicket; if (testPara->isSupportSni) { ASSERT_TRUE(HLT_SetServerName(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); } 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 end. 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 link. serverConfig = HLT_NewCtxConfig(NULL, "SERVER"); ASSERT_TRUE(serverConfig != NULL); 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); serverConfig->isSupportSessionTicket = testPara->isSupportSessionTicket; ASSERT_TRUE(HLT_SetRenegotiationSupport(serverConfig, testPara->isSupportRenegotiation) == 0); if (testPara->isSupportSni) { ASSERT_TRUE(HLT_SetServerNameCb(serverConfig, "ExampleSNICb") == 0); ASSERT_TRUE(HLT_SetServerNameArg(serverConfig, "ExampleSNIArg") == 0); } if (testPara->isSupportAlpn) { ASSERT_TRUE(HLT_SetAlpnProtosSelectCb(serverConfig, "ExampleAlpnCb", "ExampleAlpnData") == 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); } 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_SetRenegotiationSupport(clientConfig, testPara->isSupportRenegotiation) == 0); clientConfig->isSupportSessionTicket = testPara->isSupportSessionTicket; if (testPara->isSupportSni) { ASSERT_TRUE(HLT_SetServerName(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 packets. handle->ctx = clientRes->ssl; ASSERT_TRUE(HLT_SetFrameHandle(handle) == 0); //Set up a link and wait until the local end is complete. ASSERT_TRUE(HLT_TlsConnect(clientRes->ssl) != 0); //Wait the remote end. 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; } static int SetCertPath(HLT_Ctx_Config *ctxConfig, const char *certStr, bool isServer) { int ret; char caCertPath[50] = {0}; char chainCertPath[30] = {0}; char eeCertPath[30] = {0}; char privKeyPath[30] = {0}; 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 int SetCertPath1(HLT_Ctx_Config *ctxConfig, const char *certStr, const char *certStr1, bool isServer) { int ret; char caCertPath[50] = {0}; char chainCertPath[30] = {0}; char eeCertPath[30] = {0}; char privKeyPath[30] = {0}; ret = sprintf_s(caCertPath, sizeof(caCertPath), ROOT_DER, certStr1, certStr1); 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 GetDefaultPointFormats(FRAME_HsExtArray8 *exField) { exField->exState = INITIAL_FIELD; exField->exType.state = INITIAL_FIELD; exField->exType.data = HS_EX_TYPE_POINT_FORMATS; uint8_t data[] = {0}; FRAME_ModifyMsgArray8(data, sizeof(data), &exField->exData, &exField->exDataLen); exField->exLen.state = INITIAL_FIELD; exField->exLen.data = exField->exDataLen.data + sizeof(uint8_t); } static void MalformedServerHelloMsgCallback001(void *msg, void *userData) { // ServerHello exception: Duplicate point format 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; GetDefaultPointFormats(&serverHello->pointFormats); serverHello->pointFormats.exState = DUPLICATE_FIELD; EXIT: return; } /* @ * @test SDV_TLS_TLS12_RFC5246_CONSISTENCY_REPEAT_EXTENSION_TC010 * @title extension_serverhello point format extension duplicate * @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 is obtained. 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_RFC5246_CONSISTENCY_REPEAT_EXTENSION_TC010(void) { HLT_FrameHandle handle = {0}; handle.userData = (void*)&handle; handle.pointType = POINT_SEND; handle.expectReType = REC_TYPE_HANDSHAKE; // Message type to be modified handle.expectHsType = SERVER_HELLO; // Handshake message type to be modified handle.frameCallBack = MalformedServerHelloMsgCallback001; // reconstruction callback TestPara testPara = {0}; testPara.port = PORT; testPara.isSupportExtendMasterSecret = true; testPara.expectHsState = TRY_RECV_CLIENT_KEY_EXCHANGE; testPara.expectDescription = ALERT_ILLEGAL_PARAMETER; ServerSendMalformedRecordHeaderMsg(&handle, &testPara); return; } /* END_CASE */ static void MalformedServerHelloMsgCallback002(void *msg, void *userData) { // ServerHello exception: The extended master key extension is duplicate 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 = DUPLICATE_FIELD; EXIT: return; } /* @ * @test SDV_TLS_TLS12_RFC5246_CONSISTENCY_REPEAT_EXTENSION_TC011 * @title extension_serverHello extension master key extension duplicate * @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_RFC5246_CONSISTENCY_REPEAT_EXTENSION_TC011(void) { HLT_FrameHandle handle = {0}; handle.userData = (void*)&handle; handle.pointType = POINT_SEND; handle.expectReType = REC_TYPE_HANDSHAKE; handle.expectHsType = SERVER_HELLO; handle.frameCallBack = MalformedServerHelloMsgCallback002; TestPara testPara = {0}; testPara.port = PORT; testPara.isSupportExtendMasterSecret = true; testPara.expectHsState = TRY_RECV_CLIENT_KEY_EXCHANGE; testPara.expectDescription = ALERT_ILLEGAL_PARAMETER; ServerSendMalformedRecordHeaderMsg(&handle, &testPara); return; } /* END_CASE */ static void MalformedServerHelloMsgCallback003(void *msg, void *userData) { // ServerHello exception: The extended renegotiation extension is repeated. 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->secRenego.exState = DUPLICATE_FIELD; EXIT: return; } /* @ * @test SDV_TLS_TLS12_RFC5246_CONSISTENCY_REPEAT_EXTENSION_TC012 * @title extension_serverHello renegotiation extension duplicate * @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 test end is alerted. @ */ /* BEGIN_CASE */ void SDV_TLS_TLS12_RFC5246_CONSISTENCY_REPEAT_EXTENSION_TC012(void) { HLT_FrameHandle handle = {0}; handle.userData = (void*)&handle; handle.pointType = POINT_SEND; handle.expectReType = REC_TYPE_HANDSHAKE; handle.expectHsType = SERVER_HELLO; handle.frameCallBack = MalformedServerHelloMsgCallback003; TestPara testPara = {0}; testPara.port = PORT; testPara.isSupportExtendMasterSecret = true; testPara.isSupportRenegotiation = true; testPara.expectHsState = TRY_RECV_CLIENT_KEY_EXCHANGE; testPara.expectDescription = ALERT_ILLEGAL_PARAMETER; ServerSendMalformedRecordHeaderMsg(&handle, &testPara); return; } /* END_CASE */ static void MalformedServerHelloMsgCallback004(void *msg, void *userData) { // ServerHello exception: Duplicate sessionticket 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->sessionTicket.exState = DUPLICATE_FIELD; EXIT: return; } /* @ * @test SDV_TLS_TLS12_RFC5246_CONSISTENCY_REPEAT_EXTENSION_TC013 * @title extension_serverHello sessionticket extension duplicate * @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 is obtained. 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 test end is alerted. @ */ /* BEGIN_CASE */ void SDV_TLS_TLS12_RFC5246_CONSISTENCY_REPEAT_EXTENSION_TC013(void) { HLT_FrameHandle handle = {0}; handle.userData = (void*)&handle; handle.pointType = POINT_SEND; handle.expectReType = REC_TYPE_HANDSHAKE; handle.expectHsType = SERVER_HELLO; handle.frameCallBack = MalformedServerHelloMsgCallback004; TestPara testPara = {0}; testPara.port = PORT; testPara.isSupportExtendMasterSecret = true; testPara.isSupportSessionTicket = true; testPara.expectHsState = TRY_RECV_CLIENT_KEY_EXCHANGE; testPara.expectDescription = ALERT_ILLEGAL_PARAMETER; ServerSendMalformedRecordHeaderMsg(&handle, &testPara); return; } /* END_CASE */ static void MalformedServerHelloMsgCallback005(void *msg, void *userData) { // serverHello exception: The serverName extension is duplicate. 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->serverName.exState = DUPLICATE_FIELD; EXIT: return; } /* @ * @test SDV_TLS_TLS12_RFC5246_CONSISTENCY_REPEAT_EXTENSION_TC014 * @title extension_serverHello servername extension duplicate * @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 is obtained. 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 in the alerted state. 4. The status of the tested end is alerted. @ */ /* BEGIN_CASE */ void SDV_TLS_TLS12_RFC5246_CONSISTENCY_REPEAT_EXTENSION_TC014(void) { HLT_FrameHandle handle = {0}; handle.userData = (void*)&handle; handle.pointType = POINT_SEND; handle.expectReType = REC_TYPE_HANDSHAKE; handle.expectHsType = SERVER_HELLO; handle.frameCallBack = MalformedServerHelloMsgCallback005; TestPara testPara = {0}; testPara.port = PORT; testPara.isSupportExtendMasterSecret = true; testPara.isSupportSni = true; testPara.expectHsState = TRY_RECV_CLIENT_KEY_EXCHANGE; testPara.expectDescription = ALERT_ILLEGAL_PARAMETER; ServerSendMalformedRecordHeaderMsg(&handle, &testPara); return; } /* END_CASE */ static void MalformedServerHelloMsgCallback006(void *msg, void *userData) { // ServerHello exception: The alpn extension is duplicate. 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->alpn.exState = DUPLICATE_FIELD; EXIT: return; } /* @ * @test SDV_TLS_TLS12_RFC5246_CONSISTENCY_REPEAT_EXTENSION_TC014 * @title extension_serverHello Alpn extension duplicate * @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 is obtained. 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_RFC5246_CONSISTENCY_REPEAT_EXTENSION_TC009(void) { HLT_FrameHandle handle = {0}; handle.userData = (void*)&handle; handle.pointType = POINT_SEND; handle.expectReType = REC_TYPE_HANDSHAKE; handle.expectHsType = SERVER_HELLO; handle.frameCallBack = MalformedServerHelloMsgCallback006; TestPara testPara = {0}; testPara.port = PORT; testPara.isSupportExtendMasterSecret = true; testPara.isSupportAlpn = true; testPara.expectHsState = TRY_RECV_CLIENT_KEY_EXCHANGE; testPara.expectDescription = ALERT_ILLEGAL_PARAMETER; ServerSendMalformedRecordHeaderMsg(&handle, &testPara); return; } /* END_CASE */ static void MalformedClientHelloMsgCallback002(void *msg, void *userData) { // ClientHello exception: The format extension of the sent ClientHello message is duplicate. 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.exState = DUPLICATE_FIELD; EXIT: return; } /* @ * @test SDV_TLS_TLS12_RFC5246_CONSISTENCY_REPEAT_EXTENSION_TC002 * @title The point format extension of the ClientHello message is duplicate * @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_RFC5246_CONSISTENCY_REPEAT_EXTENSION_TC002(void) { HLT_FrameHandle handle = {0}; handle.pointType = POINT_SEND; handle.userData = (void *)&handle; handle.expectReType = REC_TYPE_HANDSHAKE; handle.expectHsType = CLIENT_HELLO; handle.frameCallBack = MalformedClientHelloMsgCallback002; TestPara testPara = {0}; testPara.port = PORT; testPara.expectHsState = TRY_RECV_SERVER_HELLO; testPara.expectDescription = ALERT_ILLEGAL_PARAMETER; ClientSendMalformedRecordHeaderMsg(&handle, &testPara); return; } /* END_CASE */ static void MalformedClientHelloMsgCallback003(void *msg, void *userData) { // ClientHello exception: The signature algorithm extension of the sent ClientHello message is duplicate. 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->signatureAlgorithms.exState = DUPLICATE_FIELD; EXIT: return; } /* @ * @test SDV_TLS_TLS12_RFC5246_CONSISTENCY_REPEAT_EXTENSION_TC003 * @title The signature algorithm extension for the clientHello message sent by the client is duplicate._Signature algorithm extension * @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, indicating that 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_RFC5246_CONSISTENCY_REPEAT_EXTENSION_TC003(void) { HLT_FrameHandle handle = {0}; handle.pointType = POINT_SEND; handle.userData = (void *)&handle; handle.expectReType = REC_TYPE_HANDSHAKE; handle.expectHsType = CLIENT_HELLO; handle.frameCallBack = MalformedClientHelloMsgCallback003; TestPara testPara = {0}; testPara.port = PORT; testPara.expectHsState = TRY_RECV_SERVER_HELLO; testPara.expectDescription = ALERT_ILLEGAL_PARAMETER; ClientSendMalformedRecordHeaderMsg(&handle, &testPara); return; } /* END_CASE */ static void MalformedClientHelloMsgCallback004(void *msg, void *userData) { // ClientHello exception: The sent ClientHello message supports group extension repetition. 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 = DUPLICATE_FIELD; EXIT: return; } /* @ * @test SDV_TLS_TLS12_RFC5246_CONSISTENCY_REPEAT_EXTENSION_TC004 * @title The clientHello message sent by the client supports group extension repetition._Group extension is supported. * @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, indicating that 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_RFC5246_CONSISTENCY_REPEAT_EXTENSION_TC004(void) { HLT_FrameHandle handle = {0}; handle.pointType = POINT_SEND; handle.userData = (void *)&handle; handle.expectReType = REC_TYPE_HANDSHAKE; handle.expectHsType = CLIENT_HELLO; handle.frameCallBack = MalformedClientHelloMsgCallback004; TestPara testPara = {0}; testPara.port = PORT; testPara.expectHsState = TRY_RECV_SERVER_HELLO; testPara.expectDescription = ALERT_ILLEGAL_PARAMETER; ClientSendMalformedRecordHeaderMsg(&handle, &testPara); return; } /* END_CASE */ static void MalformedClientHelloMsgCallback005(void *msg, void *userData) { // ClientHello exception: The extended master key extension in the sent ClientHello message is duplicate. 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->extendedMasterSecret.exState = DUPLICATE_FIELD; EXIT: return; } /* @ * @test SDV_TLS_TLS12_RFC5246_CONSISTENCY_REPEAT_EXTENSION_TC005 * @title Extended master key for the clientHello message that is sent repeatedly_Extended master key * @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, indicating that 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_RFC5246_CONSISTENCY_REPEAT_EXTENSION_TC005(void) { HLT_FrameHandle handle = {0}; handle.pointType = POINT_SEND; handle.userData = (void *)&handle; handle.expectReType = REC_TYPE_HANDSHAKE; handle.expectHsType = CLIENT_HELLO; handle.frameCallBack = MalformedClientHelloMsgCallback005; TestPara testPara = {0}; testPara.port = PORT; testPara.expectHsState = TRY_RECV_SERVER_HELLO; testPara.expectDescription = ALERT_ILLEGAL_PARAMETER; testPara.isSupportExtendMasterSecret = true; ClientSendMalformedRecordHeaderMsg(&handle, &testPara); return; } /* END_CASE */ static void MalformedClientHelloMsgCallback006(void *msg, void *userData) { // ClientHello exception: The extended sessionticket extension of the clientHello message is duplicate. 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->sessionTicket.exState = DUPLICATE_FIELD; EXIT: return; } /* @ * @test SDV_TLS_TLS12_RFC5246_CONSISTENCY_REPEAT_EXTENSION_TC006 * @title The sessionticket extension for the clientHello message sent by the client is duplicate. * @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, indicating that 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_RFC5246_CONSISTENCY_REPEAT_EXTENSION_TC006(void) { HLT_FrameHandle handle = {0}; handle.pointType = POINT_SEND; handle.userData = (void *)&handle; handle.expectReType = REC_TYPE_HANDSHAKE; handle.expectHsType = CLIENT_HELLO; handle.frameCallBack = MalformedClientHelloMsgCallback006; TestPara testPara = {0}; testPara.port = PORT; testPara.expectHsState = TRY_RECV_SERVER_HELLO; testPara.expectDescription = ALERT_ILLEGAL_PARAMETER; testPara.isSupportExtendMasterSecret = true; testPara.isSupportSessionTicket = true; ClientSendMalformedRecordHeaderMsg(&handle, &testPara); return; } /* END_CASE */ // ClientHello exception: The extension servername of the clientHello message is duplicate. static void MalformedClientHelloMsgCallback007(void *msg, void *userData) { // ClientHello exception: The extension servername of the clientHello message is duplicate. 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->serverName.exState = DUPLICATE_FIELD; clientHello->serverName.exLen.state = INITIAL_FIELD; clientHello->serverName.exDataLen.state = INITIAL_FIELD; FRAME_ModifyMsgInteger(HS_EX_TYPE_SERVER_NAME, &clientHello->serverName.exType); uint8_t uu[13] = {0x00, 0x00, 0x09, 0x75, 0x61, 0x77, 0x65, 0x69, 0x2e, 0x63, 0x6F, 0x6d}; FRAME_ModifyMsgArray8(uu, sizeof(uu)-1, &clientHello->serverName.exData, &clientHello->serverName.exDataLen); EXIT: return; } /* @ * @test SDV_TLS_TLS12_RFC5246_CONSISTENCY_REPEAT_EXTENSION_TC007 * @title The servername extension of the clientHello message is duplicate _servername. * @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, indicating that 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_RFC5246_CONSISTENCY_REPEAT_EXTENSION_TC007(void) { HLT_FrameHandle handle = {0}; handle.pointType = POINT_SEND; handle.userData = (void *)&handle; handle.expectReType = REC_TYPE_HANDSHAKE; handle.expectHsType = CLIENT_HELLO; handle.frameCallBack = MalformedClientHelloMsgCallback007; TestPara testPara = {0}; testPara.port = PORT; testPara.expectHsState = TRY_RECV_SERVER_HELLO; testPara.expectDescription = ALERT_ILLEGAL_PARAMETER; testPara.isSupportExtendMasterSecret = true; testPara.isSupportSni = true; ClientSendMalformedRecordHeaderMsg(&handle, &testPara); return; } /* END_CASE */ // ClientHello exception: The extended alpn extension of the clientHello message is duplicate. static void MalformedClientHelloMsgCallback008(void *msg, void *userData) { // ClientHello exception: The extended alpn extension of the clientHello message is duplicate. 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->alpn.exState = DUPLICATE_FIELD; EXIT: return; } /* @ * @test SDV_TLS_TLS12_RFC5246_CONSISTENCY_REPEAT_EXTENSION_TC008 * @title The alpn extension of the clientHello message is repeated _alpn. * @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, indicating that 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_RFC5246_CONSISTENCY_REPEAT_EXTENSION_TC008(void) { HLT_FrameHandle handle = {0}; handle.pointType = POINT_SEND; handle.userData = (void *)&handle; handle.expectReType = REC_TYPE_HANDSHAKE; handle.expectHsType = CLIENT_HELLO; handle.frameCallBack = MalformedClientHelloMsgCallback008; TestPara testPara = {0}; testPara.port = PORT; testPara.expectHsState = TRY_RECV_SERVER_HELLO; testPara.expectDescription = ALERT_ILLEGAL_PARAMETER; testPara.isSupportExtendMasterSecret = true; testPara.isSupportAlpn = true; ClientSendMalformedRecordHeaderMsg(&handle, &testPara); return; } /* END_CASE */ /* @ * @test SDV_TLS_TLS12_RFC5246_CONSISTENCY_RESUME_TAKE_EXTENSION_TC001 * @title The sessionticket field is carried during the first connection setup. The extended field is not carried during the session recovery. The expected result is that the session recovery fails and the handshake is performed again. * @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. Enable the session ticket function and initiate link establishment. Expected result 2 is obtained. 3. Configure the client not to support sessionticket during session restoration. Expected result 3 is obtained. * @expect 1. A success message is returned. 2. The link is successfully established. 3. If the session fails to be restored, a new link is established. @ */ /* BEGIN_CASE */ void SDV_TLS_TLS12_RFC5246_CONSISTENCY_RESUME_TAKE_EXTENSION_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[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"); 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 ASSERT_TRUE(HLT_TlsSetCtx(clientConfig, clientCtxConfig) == 0); ASSERT_TRUE(HLT_RpcTlsSetCtx(remoteProcess, serverConfigId, serverCtxConfig) == 0); do { if (cnt == 2) { clientCtxConfig->isSupportSessionTicket = false; ASSERT_TRUE(HLT_TlsSetCtx(clientConfig, clientCtxConfig) == 0); } DataChannelParam channelParam; channelParam.port = PORT; 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(clientCtxConfig->isSupportSessionTicket == false); ASSERT_TRUE(HITLS_SetSession(clientSsl, session) == HITLS_SUCCESS); 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); 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); EXIT: HITLS_SESS_Free(session); HLT_FreeAllProcess(); } /* END_CASE */ /* @ * @test SDV_TLS_TLS12_RFC5246_CONSISTENCY_RESUME_TAKE_EXTENSION_TC002 * @title The sessionticket field is not carried during the first connection setup. The extended field is carried during session recovery. The expected result is that the session recovery fails and the handshake is performed again. * @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. Disable the session ticket function and initiate link establishment. Expected result 2 is obtained. 3. Configure the client to support sessionticket during session restoration. Expected result 3 is obtained. * @expect 1. A success message is returned. 2. The link is set up successfully. 3. The session is restored successfully. @ */ /* BEGIN_CASE */ void SDV_TLS_TLS12_RFC5246_CONSISTENCY_RESUME_TAKE_EXTENSION_TC002(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"); clientCtxConfig->isSupportSessionTicket = false; clientCtxConfig->isSupportRenegotiation = false; HLT_Ctx_Config *serverCtxConfig = HLT_NewCtxConfig(NULL, "SERVER"); serverCtxConfig->isSupportSessionTicket = false; 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 { if (cnt == 2) { clientCtxConfig->isSupportSessionTicket = true; ASSERT_TRUE(HLT_TlsSetCtx(clientConfig, clientCtxConfig) == 0); } DataChannelParam channelParam; channelParam.port = PORT; 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(clientCtxConfig->isSupportSessionTicket == true); ASSERT_TRUE(HITLS_SetSession(clientSsl, session) == HITLS_SUCCESS); 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); 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: HITLS_SESS_Free(session); HLT_FreeAllProcess(); } /* END_CASE */ /* @ * @test SDV_TLS_TLS12_RFC5246_CONSISTENCY_RESUME_TAKE_EXTENSION_TC003 * @title Renegotiation is carried in the first link setup message, and this extended field is not carried in the session recovery message. The expected result is that the session recovery is successful. * @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. Enable renegotiation and initiate link establishment. Expected result 2 is obtained. 3. Configure the client not to support renegotiation during session restoration. Expected result 3 is obtained. * @expect 1. A success message is returned. 2. The link is set up successfully. 3. The session is restored successfully. @ */ /* BEGIN_CASE */ void SDV_TLS_TLS12_RFC5246_CONSISTENCY_RESUME_TAKE_EXTENSION_TC003(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"); clientCtxConfig->isSupportSessionTicket = false; clientCtxConfig->isSupportRenegotiation = true; HLT_Ctx_Config *serverCtxConfig = HLT_NewCtxConfig(NULL, "SERVER"); serverCtxConfig->isSupportSessionTicket = false; serverCtxConfig->isSupportRenegotiation = true; #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 (cnt == 2) { clientCtxConfig->isSupportRenegotiation = false; ASSERT_TRUE(HLT_TlsSetCtx(clientConfig, clientCtxConfig) == 0); } DataChannelParam channelParam; channelParam.port = PORT; 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); } 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: HITLS_SESS_Free(session); HLT_FreeAllProcess(); } /* END_CASE */ /* @ * @test SDV_TLS_TLS12_RFC5246_CONSISTENCY_RESUME_TAKE_EXTENSION_TC004 * @title The first link establishment does not carry the renegotiation IE, and the session recovery IE carries the extended field. The expected result is that the session recovery is successful. * @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. Disable renegotiation and initiate link establishment. Expected result 2 is obtained. 3. Configure the client to support renegotiation during session restoration. Expected result 3 is obtained. * @expect 1. A success message is returned. 2. The link is set up successfully. 3. The session is restored successfully. @ */ /* BEGIN_CASE */ void SDV_TLS_TLS12_RFC5246_CONSISTENCY_RESUME_TAKE_EXTENSION_TC004(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"); clientCtxConfig->isSupportSessionTicket = false; clientCtxConfig->isSupportRenegotiation = false; HLT_Ctx_Config *serverCtxConfig = HLT_NewCtxConfig(NULL, "SERVER"); serverCtxConfig->isSupportSessionTicket = false; 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 { if (cnt == 2) { clientCtxConfig->isSupportRenegotiation = true; ASSERT_TRUE(HLT_TlsSetCtx(clientConfig, clientCtxConfig) == 0); } DataChannelParam channelParam; channelParam.port = PORT; 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); } 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: HITLS_SESS_Free(session); HLT_FreeAllProcess(); } /* END_CASE */ /* @ * @test SDV_TLS_TLS12_RFC5246_CONSISTENCY_NEGOTIATE_CIPHERSUITE_TC001 * @title The handshake fails because different cipher suites are configured on the client and server. * @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. Configure different cipher suites on the client and server and initiate link establishment. (Expected result 2) * @expect 1. A success message is returned. 2. The link fails to be established. @ */ /* BEGIN_CASE */ void SDV_TLS_TLS12_RFC5246_CONSISTENCY_NEGOTIATE_CIPHERSUITE_TC001(int version, int connType) { bool certverifyflag = false; 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, connType, PORT, true); ASSERT_TRUE(remoteProcess != NULL); HLT_Ctx_Config *serverCtxConfig = HLT_NewCtxConfig(NULL, "SERVER"); ASSERT_TRUE(serverCtxConfig != NULL); SetCertPath(serverCtxConfig, "ecdsa_sha256", true); HLT_SetCipherSuites(serverCtxConfig, "HITLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384"); serverCtxConfig->isSupportClientVerify = certverifyflag; 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_SetCipherSuites(clientCtxConfig, "HITLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256"); clientCtxConfig->isSupportClientVerify = certverifyflag; clientRes = HLT_ProcessTlsInit(remoteProcess, version, clientCtxConfig, NULL); ASSERT_TRUE(clientRes != NULL); ASSERT_EQ(HLT_RpcTlsConnect(remoteProcess, clientRes->sslId), HITLS_REC_NORMAL_RECV_UNEXPECT_MSG); ASSERT_TRUE(HLT_GetTlsAcceptResult(serverRes) != 0); EXIT: HLT_CleanFrameHandle(); HLT_FreeAllProcess(); } /* END_CASE */ /* @ * @test SDV_TLS_TLS12_RFC5246_CONSISTENCY_NEGOTIATE_CIPHERSUITE_TC003 * @title The RSA and ECDSA cipher suites are configured on the client and server, and the ECDSA certificate is configured. The handshake is successful. * @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. Configure the RSA and ECDSA cipher suites and ECDSA certificates on the client and server, and initiate link establishment. (Expected result 2) * @expect 1. A success message is returned. 2. Link establishment fails. @ */ /* BEGIN_CASE */ void SDV_TLS_TLS12_RFC5246_CONSISTENCY_NEGOTIATE_CIPHERSUITE_TC003(int version, int connType) { bool certverifyflag = false; 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, connType, PORT, true); ASSERT_TRUE(remoteProcess != NULL); HLT_Ctx_Config *serverCtxConfig = HLT_NewCtxConfig(NULL, "SERVER"); ASSERT_TRUE(serverCtxConfig != NULL); SetCertPath(serverCtxConfig, "ecdsa_sha256", true); HLT_SetCipherSuites(serverCtxConfig, "HITLS_RSA_WITH_AES_128_CBC_SHA256:HITLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA256"); serverCtxConfig->isSupportClientVerify = certverifyflag; 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_SetCipherSuites(clientCtxConfig, "HITLS_RSA_WITH_AES_128_CBC_SHA256:HITLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA256"); clientCtxConfig->isSupportClientVerify = certverifyflag; 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 */ void MalformedClientHellocallback001(void *msg, void *userData) { // ClientHello is abnormal. ClientHello modifies the algorithm suite. 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; /* Modify the structure. */ uint16_t suite[] = {0x00fe, HITLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256}; ASSERT_TRUE(FRAME_ModifyMsgArray16(suite, sizeof(suite)/sizeof(uint16_t), &(clientHello->cipherSuites), &(clientHello->cipherSuitesSize)) == HITLS_SUCCESS); EXIT: return; } /* @ * @test SDV_TLS_TLS12_RFC5246_CONSISTENCY_NEGOTIATE_CIPHERSUITE_TC002 * @title The client and server set incorrect and correct cipher suites. The handshake succeeds. * @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. Configure different cipher suites on the client and server and initiate link establishment. (Expected result 2) * @expect 1. A success message is returned. 2. A link is established normally. An error is reported during hash check. @ */ /* BEGIN_CASE */ void SDV_TLS_TLS12_RFC5246_CONSISTENCY_NEGOTIATE_CIPHERSUITE_TC002(int version, int connType) { bool certverifyflag = false; HLT_Tls_Res *serverRes = NULL; HLT_Tls_Res *clientRes = NULL; Process *localProcess = NULL; Process *remoteProcess = NULL; HLT_FD sockFd = {0}; localProcess = HLT_InitLocalProcess(HITLS); ASSERT_TRUE(localProcess != NULL); remoteProcess = HLT_CreateRemoteProcess(HITLS); ASSERT_TRUE(remoteProcess != NULL); DataChannelParam channelParam = {0}; channelParam.port = PORT; channelParam.type = connType; channelParam.isBlock = true; sockFd = HLT_CreateDataChannel(localProcess, remoteProcess, channelParam); ASSERT_TRUE(sockFd.srcFd > 0); ASSERT_TRUE(sockFd.peerFd > 0); remoteProcess->connFd = sockFd.peerFd; remoteProcess->connType = connType; localProcess->connFd = sockFd.srcFd; localProcess->connType = connType; HLT_Ctx_Config *serverCtxConfig = HLT_NewCtxConfig(NULL, "SERVER"); ASSERT_TRUE(serverCtxConfig != NULL); SetCertPath(serverCtxConfig, "ecdsa_sha256", true); HLT_SetCipherSuites(serverCtxConfig, "HITLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256"); serverCtxConfig->isSupportClientVerify = certverifyflag; serverRes = HLT_ProcessTlsAccept(remoteProcess, version, serverCtxConfig, NULL); ASSERT_TRUE(serverRes != NULL); HLT_Ctx_Config *clientCtxConfig = HLT_NewCtxConfig(NULL, "CLIENT"); ASSERT_TRUE(clientCtxConfig != NULL); HLT_SetLegacyRenegotiateSupport(clientCtxConfig, true); SetCertPath(clientCtxConfig, "ecdsa_sha256", false); HLT_SetCipherSuites(clientCtxConfig, "HITLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256"); clientCtxConfig->isSupportClientVerify = certverifyflag; clientRes = HLT_ProcessTlsInit(localProcess, version, clientCtxConfig, NULL); ASSERT_TRUE(clientRes != NULL); HLT_FrameHandle handle = {0}; handle.ctx = clientRes->ssl; handle.userData = (void*)&handle; handle.pointType = POINT_SEND; handle.expectReType = REC_TYPE_HANDSHAKE; handle.expectHsType = CLIENT_HELLO; handle.frameCallBack = MalformedClientHellocallback001; ASSERT_TRUE(HLT_SetFrameHandle(&handle) == HITLS_SUCCESS); ASSERT_EQ(HLT_TlsConnect(clientRes->ssl), HITLS_REC_NORMAL_RECV_UNEXPECT_MSG); ASSERT_EQ(HLT_GetTlsAcceptResult(serverRes), HITLS_REC_BAD_RECORD_MAC); EXIT: HLT_CleanFrameHandle(); HLT_FreeAllProcess(); } /* END_CASE */ void MalformedServerHellocallback001(void *msg, void *userData) { // ServerHello packet: Check the serverHello algorithm suite. 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; /* Determine algorithm suite */ ASSERT_EQ(serverHello->cipherSuite.data, 0x6d); EXIT: return; } /* @ * @test SDV_TLS_TLS12_RFC5246_CONSISTENCY_NEGOTIATE_CIPHERSUITE_TC004 * @title Set insecure and secure cipher suites on the client and server, set the ECDSA certificate, and select the secure cipher suite as expected. * @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. Configure insecure and secure cipher suites on the client and server, configure the ECDSA certificate, and initiate link establishment. (Expected result 2) * @expect 1. A success message is returned. 2. The link is successfully established and the security algorithm suite is selected. @ */ /* BEGIN_CASE */ void SDV_TLS_TLS12_RFC5246_CONSISTENCY_NEGOTIATE_CIPHERSUITE_TC004(int version, int connType) { bool certverifyflag = false; HLT_Tls_Res *serverRes = NULL; HLT_Tls_Res *clientRes = NULL; Process *localProcess = NULL; Process *remoteProcess = NULL; HLT_FD sockFd = {0}; localProcess = HLT_InitLocalProcess(HITLS); ASSERT_TRUE(localProcess != NULL); remoteProcess = HLT_CreateRemoteProcess(HITLS); ASSERT_TRUE(remoteProcess != NULL); DataChannelParam channelParam = {0}; channelParam.port = PORT; channelParam.type = connType; channelParam.isBlock = true; sockFd = HLT_CreateDataChannel(localProcess, remoteProcess, channelParam); ASSERT_TRUE(sockFd.srcFd > 0); ASSERT_TRUE(sockFd.peerFd > 0); remoteProcess->connFd = sockFd.peerFd; remoteProcess->connType = connType; localProcess->connFd = sockFd.srcFd; localProcess->connType = connType; HLT_Ctx_Config *serverCtxConfig = HLT_NewCtxConfig(NULL, "SERVER"); ASSERT_TRUE(serverCtxConfig != NULL); SetCertPath(serverCtxConfig, "ecdsa_sha256", true); HLT_SetCipherSuites(serverCtxConfig, "HITLS_DH_ANON_WITH_AES_256_CBC_SHA256:HITLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA256"); serverCtxConfig->isSupportClientVerify = certverifyflag; serverRes = HLT_ProcessTlsAccept(remoteProcess, 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_SetCipherSuites(clientCtxConfig, "HITLS_DH_ANON_WITH_AES_256_CBC_SHA256:HITLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA256"); clientCtxConfig->isSupportClientVerify = certverifyflag; clientRes = HLT_ProcessTlsInit(localProcess, version, clientCtxConfig, NULL); ASSERT_TRUE(clientRes != NULL); ASSERT_EQ(HLT_TlsConnect(clientRes->ssl), HITLS_SUCCESS); ASSERT_EQ(HLT_GetTlsAcceptResult(serverRes), HITLS_SUCCESS); ASSERT_EQ(((HITLS_Ctx *)clientRes->ssl)->negotiatedInfo.cipherSuiteInfo.cipherSuite, HITLS_DH_ANON_WITH_AES_256_CBC_SHA256); EXIT: HLT_CleanFrameHandle(); HLT_FreeAllProcess(); } /* END_CASE */ //The clientHello is abnormal. The extended servername length of the clientHello message is smaller than the actual length. static void MalformedClientHelloMsgCallback009(void *msg, void *userData) { //The clientHello is abnormal. The extended servername length of the clientHello message is smaller than the actual length. 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->serverName.exState = INITIAL_FIELD; clientHello->serverName.exLen.state = ASSIGNED_FIELD; clientHello->serverName.exDataLen.state = INITIAL_FIELD; FRAME_ModifyMsgInteger(HS_EX_TYPE_SERVER_NAME, &clientHello->serverName.exType); uint8_t uu[13] = {0x00, 0x00, 0x09, 0x75, 0x61, 0x77, 0x65, 0x69, 0x2e, 0x63, 0x6F, 0x6d}; FRAME_ModifyMsgArray8(uu, sizeof(uu)-1, &clientHello->serverName.exData, &clientHello->serverName.exDataLen); clientHello->serverName.exLen.data--; clientHello->serverName.exLen.data--; EXIT: return; } /* @ * @test SDV_TLS_TLS12_RFC5246_CONSISTENCY_REPEAT_EXTENSION_TC007 * @title The extended length of the servername in the clientHello message is smaller than the actual length. * @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_RFC5246_CONSISTENCY_MALFORMED_CLIENT_HELLO_MSG_FUN_TC048(void) { HLT_FrameHandle handle = {0}; handle.pointType = POINT_SEND; handle.userData = (void *)&handle; handle.expectReType = REC_TYPE_HANDSHAKE; handle.expectHsType = CLIENT_HELLO; handle.frameCallBack = MalformedClientHelloMsgCallback009; TestPara testPara = {0}; testPara.port = PORT; testPara.expectHsState = TRY_RECV_SERVER_HELLO; testPara.expectDescription = ALERT_DECODE_ERROR; testPara.isSupportExtendMasterSecret = true; testPara.isSupportSni = true; ClientSendMalformedRecordHeaderMsg(&handle, &testPara); return; } /* END_CASE */ //The clientHello message is abnormal. The extended servername length of the clientHello message is greater than the actual length. static void MalformedClientHelloMsgCallback010(void *msg, void *userData) { //The clientHello message is abnormal. The extended servername length of the clientHello message is greater than the actual length. 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->serverName.exState = INITIAL_FIELD; clientHello->serverName.exLen.state = ASSIGNED_FIELD; clientHello->serverName.exDataLen.state = INITIAL_FIELD; FRAME_ModifyMsgInteger(HS_EX_TYPE_SERVER_NAME, &clientHello->serverName.exType); uint8_t uu[13] = {0x00, 0x00, 0x09, 0x75, 0x61, 0x77, 0x65, 0x69, 0x2e, 0x63, 0x6F, 0x6d}; FRAME_ModifyMsgArray8(uu, sizeof(uu)-1, &clientHello->serverName.exData, &clientHello->serverName.exDataLen); clientHello->serverName.exLen.data++; clientHello->serverName.exLen.data++; EXIT: return; } /* @ * @test SDV_TLS_TLS12_RFC5246_CONSISTENCY_REPEAT_EXTENSION_TC007 * @title The extended length of the servername in the clientHello message is greater than the actual length. * @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_RFC5246_CONSISTENCY_MALFORMED_CLIENT_HELLO_MSG_FUN_TC047(void) { HLT_FrameHandle handle = {0}; handle.pointType = POINT_SEND; handle.userData = (void *)&handle; handle.expectReType = REC_TYPE_HANDSHAKE; handle.expectHsType = CLIENT_HELLO; handle.frameCallBack = MalformedClientHelloMsgCallback010; TestPara testPara = {0}; testPara.port = PORT; testPara.expectHsState = TRY_RECV_SERVER_HELLO; testPara.expectDescription = ALERT_DECODE_ERROR; testPara.isSupportExtendMasterSecret = true; testPara.isSupportSni = true; ClientSendMalformedRecordHeaderMsg(&handle, &testPara); return; } /* END_CASE */ // ClientHello exception: The extended length of the servername in the clientHello message is 0 and the content is not null. static void MalformedClientHelloMsgCallback011(void *msg, void *userData) { // ClientHello exception: The length of the extended servername in the clientHello message is 0 and the content is not null. 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->serverName.exState = INITIAL_FIELD; clientHello->serverName.exLen.state = ASSIGNED_FIELD; clientHello->serverName.exDataLen.state = INITIAL_FIELD; FRAME_ModifyMsgInteger(HS_EX_TYPE_SERVER_NAME, &clientHello->serverName.exType); uint8_t uu[4] = {0x00, 0x00, 0x01,0x01}; FRAME_ModifyMsgArray8(uu, sizeof(uu)-1, &clientHello->serverName.exData, &clientHello->serverName.exDataLen); clientHello->serverName.exLen.data = 0; clientHello->serverName.exDataLen.data = 0; EXIT: return; } /* @ * @test SDV_TLS_TLS12_RFC5246_CONSISTENCY_REPEAT_EXTENSION_TC007 * @title The extended length of the servername in the clientHello message is 0 and the content is not null. * @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_RFC5246_CONSISTENCY_MALFORMED_CLIENT_HELLO_MSG_FUN_TC046(void) { HLT_FrameHandle handle = {0}; handle.pointType = POINT_SEND; handle.userData = (void *)&handle; handle.expectReType = REC_TYPE_HANDSHAKE; handle.expectHsType = CLIENT_HELLO; handle.frameCallBack = MalformedClientHelloMsgCallback011; TestPara testPara = {0}; testPara.port = PORT; testPara.expectHsState = TRY_RECV_SERVER_HELLO; testPara.expectDescription = ALERT_DECODE_ERROR; testPara.isSupportExtendMasterSecret = true; testPara.isSupportSni = true; ClientSendMalformedRecordHeaderMsg(&handle, &testPara); return; } /* END_CASE */ //The clientHello is abnormal. The extended length of the servername in the clientHello message is 0. The content is empty. static void MalformedClientHelloMsgCallback012(void *msg, void *userData) { //The clientHello is abnormal. The extended length of the servername in the clientHello message is 0. The content is empty. 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->serverName.exState = INITIAL_FIELD; clientHello->serverName.exLen.state = ASSIGNED_FIELD; clientHello->serverName.exDataLen.state = MISSING_FIELD; clientHello->serverName.exData.state = MISSING_FIELD; FRAME_ModifyMsgInteger(HS_EX_TYPE_SERVER_NAME, &clientHello->serverName.exType); clientHello->serverName.exLen.data = 0; EXIT: return; } /* @ * @test SDV_TLS_TLS12_RFC5246_CONSISTENCY_REPEAT_EXTENSION_TC007 * @title The extended length of the servername in the clientHello message is 0. The content is empty. * @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_RFC5246_CONSISTENCY_MALFORMED_CLIENT_HELLO_MSG_FUN_TC045(void) { HLT_FrameHandle handle = {0}; handle.pointType = POINT_SEND; handle.userData = (void *)&handle; handle.expectReType = REC_TYPE_HANDSHAKE; handle.expectHsType = CLIENT_HELLO; handle.frameCallBack = MalformedClientHelloMsgCallback012; TestPara testPara = {0}; testPara.port = PORT; testPara.expectHsState = TRY_RECV_SERVER_HELLO; testPara.expectDescription = ALERT_DECODE_ERROR; testPara.isSupportExtendMasterSecret = true; testPara.isSupportSni = true; ClientSendMalformedRecordHeaderMsg(&handle, &testPara); return; } /* END_CASE */ /* @ * @test SDV_TLS_TLS12_RFC5246_CONSISTENCY_CIPHERSUITE_NOT_SUITABLE_CERT_TC003 * @title When dual-end authentication is configured, the cipher suite is set to RSA, the RSA certificate is set on the server, and the ECDSA certificate is set on the client, the link fails to be established. * @precon nan * @brief 1. Use the default configuration items to configure the client and server, set the cipher suite to RSA, set the RSA certificate on the server, and set the ECDSA certificate on the client. Expected result 1 is obtained. 2. Initiate a link establishment request. Expected result 2 is obtained. * @expect 1. The initialization is successful. 2. Link establishment fails. @ */ /* BEGIN_CASE */ void SDV_TLS_TLS12_RFC5246_CONSISTENCY_CIPHERSUITE_NOT_SUITABLE_CERT_TC003(int version, int connType) { bool certverifyflag = 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, connType, PORT, true); ASSERT_TRUE(remoteProcess != NULL); HLT_Ctx_Config *serverCtxConfig = HLT_NewCtxConfig(NULL, "SERVER"); ASSERT_TRUE(serverCtxConfig != NULL); SetCertPath1(serverCtxConfig, "rsa_sha256", "ecdsa_sha256", true); HLT_SetCipherSuites(serverCtxConfig, "HITLS_DHE_RSA_WITH_AES_256_CBC_SHA256"); serverCtxConfig->isSupportClientVerify = certverifyflag; serverRes = HLT_ProcessTlsAccept(localProcess, version, serverCtxConfig, NULL); ASSERT_TRUE(serverRes != NULL); HLT_Ctx_Config *clientCtxConfig = HLT_NewCtxConfig(NULL, "CLIENT"); ASSERT_TRUE(clientCtxConfig != NULL); SetCertPath1(clientCtxConfig, "ecdsa_sha256", "rsa_sha256", false); HLT_SetCipherSuites(clientCtxConfig, "HITLS_DHE_RSA_WITH_AES_256_CBC_SHA256"); clientCtxConfig->isSupportClientVerify = certverifyflag; clientRes = HLT_ProcessTlsInit(remoteProcess, version, clientCtxConfig, NULL); ASSERT_TRUE(clientRes != NULL); ASSERT_EQ(HLT_RpcTlsConnect(remoteProcess, clientRes->sslId), HITLS_REC_NORMAL_RECV_UNEXPECT_MSG); ASSERT_TRUE(HLT_GetTlsAcceptResult(serverRes) == 0); EXIT: HLT_CleanFrameHandle(); HLT_FreeAllProcess(); } /* END_CASE */ /* @ * @test SDV_TLS_TLS12_RFC5246_CONSISTENCY_MULTILINK_RESUME_ALERT_TC002 * @title Apply for establishing and disconnecting a link between the client and server, apply for two links, and use the session ID of the previous session to restore the session. The restoration is expected to be successful. * @precon nan * @brief 1. Apply for establishing and disconnecting a link between the client and server. 2. Apply for two links and use the session ID of the previous session to restore the session. The restoration is expected to be successful. * @expect 1. The link is successfully established. 2. The restoration is successful. @ */ /* BEGIN_CASE */ void SDV_TLS_TLS12_RFC5246_CONSISTENCY_MULTILINK_RESUME_ALERT_TC002(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; 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); void *clientConfig2 = HLT_TlsNewCtx(version); ASSERT_TRUE(clientConfig != NULL); ASSERT_TRUE(clientConfig2 != NULL); HLT_Ctx_Config *clientCtxConfig = HLT_NewCtxConfig(NULL, "CLIENT"); HLT_Ctx_Config *clientCtxConfig2 = 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_TlsSetCtx(clientConfig2, clientCtxConfig2) == 0); ASSERT_TRUE(HLT_RpcTlsSetCtx(remoteProcess, serverConfigId, serverCtxConfig) == 0); do { if (session != NULL) { DataChannelParam channelParam2; channelParam2.port = PORT; channelParam2.type = connType; channelParam2.isBlock = true; sockFd2 = HLT_CreateDataChannel(localProcess, remoteProcess, channelParam2); ASSERT_TRUE((sockFd2.srcFd > 0) && (sockFd2.peerFd > 0)); remoteProcess->connType = connType; localProcess->connType = connType; remoteProcess->connFd = sockFd2.peerFd; localProcess->connFd = sockFd2.srcFd; int32_t serverSslId2 = HLT_RpcTlsNewSsl(remoteProcess, serverConfigId); 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 *clientSsl2 = HLT_TlsNewSsl(clientConfig2); ASSERT_TRUE(clientSsl2 != NULL); HLT_Ssl_Config *clientSslConfig2; clientSslConfig2 = HLT_NewSslConfig(NULL); ASSERT_TRUE(clientSslConfig2 != NULL); clientSslConfig2->sockFd = localProcess->connFd; clientSslConfig2->connType = connType; HLT_TlsSetSsl(clientSsl2, clientSslConfig2); ASSERT_TRUE(HITLS_SetSession(clientSsl2, session) == HITLS_SUCCESS); ASSERT_TRUE(HLT_TlsConnect(clientSsl2) == 0); HITLS_Session *Newsession = HITLS_GetDupSession(clientSsl2); ASSERT_TRUE(Newsession != NULL); ASSERT_TRUE(memcmp(session->sessionId, Newsession->sessionId, HITLS_SESSION_ID_MAX_SIZE) == 0); HITLS_SESS_Free(Newsession); } DataChannelParam channelParam; channelParam.port = PORT; 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; 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); 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); HITLS_SESS_Free(session); session = HITLS_GetDupSession(clientSsl); ASSERT_TRUE(session != NULL); ASSERT_TRUE(HITLS_SESS_IsResumable(session) == true); cunt++; } while (cunt <= 2); EXIT: HITLS_SESS_Free(session); HLT_FreeAllProcess(); } /* END_CASE */
2301_79861745/bench_create
testcode/sdv/testcase/tls/consistency/tls12/test_suite_sdv_hlt_tls12_consistency_rfc5246_extensions.c
C
unknown
94,967
/* * This file is part of the openHiTLS project. * * openHiTLS is licensed under the Mulan PSL v2. * You can use this software according to the terms and conditions of the Mulan PSL v2. * You may obtain a copy of Mulan PSL v2 at: * * http://license.coscl.org.cn/MulanPSL2 * * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. * See the Mulan PSL v2 for more details. */ /* INCLUDE_BASE test_suite_tls12_consistency_rfc5246_malformed_msg */ /* BEGIN_HEADER */ #include "hitls_error.h" #include "tls.h" #include "rec.h" #include "hs_msg.h" #include "hs_ctx.h" #include "hs_extensions.h" #include "frame_msg.h" /* END_HEADER */ // Replace the message to be sent with the CERTIFICATION_VERIFY message. void TEST_SendUnexpectCertificateVerifyMsg(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 = CERTIFICATE_VERIFY; FRAME_Init(); // Callback for changing the certificate algorithm, which is used to generate negotiation handshake // messages. FRAME_GetDefaultMsg(frameType, &newFrameMsg); HLT_TlsRegCallback(HITLS_CALLBACK_DEFAULT); // recovery callback // Release the original msg. frameType->handshakeType = hsTypeTmp; frameType->recordType = recTypeTmp; FRAME_CleanMsg(frameType, frameMsg); // Change message. frameType->recordType = REC_TYPE_HANDSHAKE; frameType->handshakeType = CERTIFICATE_VERIFY; frameType->keyExType = HITLS_KEY_EXCH_ECDHE; if (memcpy_s(msg, sizeof(FRAME_Msg), &newFrameMsg, sizeof(newFrameMsg)) != EOK) { Print("TEST_SendUnexpectCertificateMsg memcpy_s Error!"); } } static void MalformedClientHelloMsgCallback_01(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_ClientHelloMsg *clientHello = &frameMsg->body.hsMsg.body.clientHello; clientHello->version.state = SET_LEN_TO_ONE_BYTE; clientHello->randomValue.state = MISSING_FIELD; clientHello->sessionIdSize.state = MISSING_FIELD; clientHello->sessionId.state = MISSING_FIELD; clientHello->cookiedLen.state = MISSING_FIELD; clientHello->cookie.state = MISSING_FIELD; clientHello->cipherSuitesSize.state = MISSING_FIELD; clientHello->cipherSuites.state = MISSING_FIELD; clientHello->compressionMethodsLen.state = MISSING_FIELD; clientHello->compressionMethods.state = MISSING_FIELD; clientHello->extensionState = MISSING_FIELD; EXIT: return; } /* @ * @test SDV_TLS_TLS12_RFC5246_CONSISTENCY_MALFORMED_CLIENT_HELLO_MSG_FUN_TC001 * @title version field only one byte _version * @precon nan * @brief 1. The server stops receiving client information. 1. ClientHello exception: The version field in the constructed message to be sent contains only one byte and cannot be decoded. Expected result 1 is obtained. * @expect 1. The processing result is HITLS_PARSE_INVALID_MSG_LEN. @ */ /* BEGIN_CASE */ void SDV_TLS_TLS12_RFC5246_CONSISTENCY_MALFORMED_CLIENT_HELLO_MSG_FUN_TC001(void) { HLT_FrameHandle handle = {0}; handle.pointType = POINT_SEND; handle.userData = (void *)&handle; handle.expectReType = REC_TYPE_HANDSHAKE; handle.expectHsType = CLIENT_HELLO; /* 1. The server stops receiving client information. 1. ClientHello exception: The version field in the constructed * message to be sent contains only one byte and cannot be decoded. */ handle.frameCallBack = MalformedClientHelloMsgCallback_01; TestPara testPara = {0}; testPara.port = PORT; testPara.expectHsState = TRY_RECV_SERVER_HELLO; testPara.expectDescription = ALERT_DECODE_ERROR; testPara.isExpectRet = true; testPara.expectRet = HITLS_PARSE_INVALID_MSG_LEN; ClientSendMalformedRecordHeaderMsg(&handle, &testPara); return; } /* END_CASE */ static void MalformedClientHelloMsgCallback_02(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_ClientHelloMsg *clientHello = &frameMsg->body.hsMsg.body.clientHello; clientHello->randomValue.size = 1; clientHello->randomValue.state = ASSIGNED_FIELD; clientHello->sessionIdSize.state = MISSING_FIELD; clientHello->sessionId.state = MISSING_FIELD; clientHello->cookiedLen.state = MISSING_FIELD; clientHello->cookie.state = MISSING_FIELD; clientHello->cipherSuitesSize.state = MISSING_FIELD; clientHello->cipherSuites.state = MISSING_FIELD; clientHello->compressionMethodsLen.state = MISSING_FIELD; clientHello->compressionMethods.state = MISSING_FIELD; clientHello->extensionState = MISSING_FIELD; EXIT: return; } /* @ * @test SDV_TLS_TLS12_RFC5246_CONSISTENCY_MALFORMED_CLIENT_HELLO_MSG_FUN_TC002 * @title random Less than 32 bytes_random * @precon nan * @brief 1. The server stops receiving client hello messages. Expected result 1 is obtained. 2. Modify the client to send the client hello message and change the random field to only one byte. Expected result 2 is obtained. 3. The server continues to establish a link. (Expected result 3) * @expect 1. Success 2. Success 3. Return a failure message. @ */ /* BEGIN_CASE */ void SDV_TLS_TLS12_RFC5246_CONSISTENCY_MALFORMED_CLIENT_HELLO_MSG_FUN_TC002(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; /* 2. Modify the client to send the client hello message and change the random field to only one byte. */ handle.frameCallBack = MalformedClientHelloMsgCallback_02; TestPara testPara = {0}; testPara.port = PORT; testPara.expectHsState = TRY_RECV_SERVER_HELLO; testPara.expectDescription = ALERT_DECODE_ERROR; testPara.isExpectRet = true; testPara.expectRet = HITLS_PARSE_INVALID_MSG_LEN; /* 3. The server continues to establish a link. */ ClientSendMalformedRecordHeaderMsg(&handle, &testPara); return; } /* END_CASE */ static void MalformedClientHelloMsgCallback_03(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_ClientHelloMsg *clientHello = &frameMsg->body.hsMsg.body.clientHello; uint8_t sessionId[MAX_SESSION_ID_SIZE] = {0}; ASSERT_TRUE(FRAME_ModifyMsgArray8(sessionId, MAX_SESSION_ID_SIZE, &clientHello->sessionId, NULL) == HITLS_SUCCESS); clientHello->sessionIdSize.data = 0u; EXIT: return; } /* @ * @test SDV_TLS_TLS12_RFC5246_CONSISTENCY_MALFORMED_CLIENT_HELLO_MSG_FUN_TC003 * @titleThe session ID length of the clientHello message is 0 but the content is not null. _session ID length * @precon nan * @brief 1. The tested functions as the client, and the tested functions as the server. Expected result 1 is obtained. 2. Obtain the message, modify the field content, and send the message. Expected result 2 is obtained. 3. Check the status of the tested. Expected result 3 is obtained. 4. Check the status of the test. 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_RFC5246_CONSISTENCY_MALFORMED_CLIENT_HELLO_MSG_FUN_TC003(void) { HLT_FrameHandle handle = {0}; handle.pointType = POINT_SEND; handle.userData = (void *)&handle; handle.expectReType = REC_TYPE_HANDSHAKE; /* 1. The tested functions as the client, and the tested functions as the server. */ handle.expectHsType = CLIENT_HELLO; /* 2. Obtain the message, modify the field content, and send the message. */ handle.frameCallBack = MalformedClientHelloMsgCallback_03; TestPara testPara = {0}; testPara.port = PORT; /* 4. The status of the test end is alerted, and the handshake status is ready to receive the serverHello message. */ testPara.expectHsState = TRY_RECV_SERVER_HELLO; /* 3. Check the status of the tested. */ testPara.expectDescription = ALERT_ILLEGAL_PARAMETER; ClientSendMalformedRecordHeaderMsg(&handle, &testPara); return; } /* END_CASE */ static void MalformedClientHelloMsgCallback_04(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_ClientHelloMsg *clientHello = &frameMsg->body.hsMsg.body.clientHello; uint8_t sessionId[MIN_SESSION_ID_SIZE - 1] = {0}; FRAME_ModifyMsgArray8(sessionId, sizeof(sessionId), &clientHello->sessionId, &clientHello->sessionIdSize); EXIT: return; } /* @ * @test SDV_TLS_TLS12_RFC5246_CONSISTENCY_MALFORMED_CLIENT_HELLO_MSG_FUN_TC004 * @title The length of the session ID in the clientHello message is smaller than the minimum length_session ID length * @precon nan * @brief 1. The tested functions as the client, and the tested 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. Expected result 3 is obtained. 4. Check the status of the test. 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_RFC5246_CONSISTENCY_MALFORMED_CLIENT_HELLO_MSG_FUN_TC004(void) { HLT_FrameHandle handle = {0}; handle.pointType = POINT_SEND; handle.userData = (void *)&handle; handle.expectReType = REC_TYPE_HANDSHAKE; /* 1. The tested functions as the client, and the tested functions as the server. */ handle.expectHsType = CLIENT_HELLO; /* 2. Obtain the message, modify the field content, and send the message. */ handle.frameCallBack = MalformedClientHelloMsgCallback_04; TestPara testPara = {0}; testPara.port = PORT; /* 4. Check the status of the test. */ testPara.expectHsState = TRY_RECV_SERVER_HELLO; /* 3.Check the status of the tested. */ testPara.expectDescription = ALERT_DECODE_ERROR; ClientSendMalformedRecordHeaderMsg(&handle, &testPara); return; } /* END_CASE */ static void MalformedClientHelloMsgCallback_05(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_ClientHelloMsg *clientHello = &frameMsg->body.hsMsg.body.clientHello; uint8_t sessionId[MAX_SESSION_ID_SIZE + 1] = {0}; FRAME_ModifyMsgArray8(sessionId, sizeof(sessionId), &clientHello->sessionId, &clientHello->sessionIdSize); EXIT: return; } /* @ * @test SDV_TLS_TLS12_RFC5246_CONSISTENCY_MALFORMED_CLIENT_HELLO_MSG_FUN_TC005 * @title The length of the session ID in the clientHello message exceeds the maximum length_session ID length * @precon nan * @brief 1. The tested functions as the client, and the tested 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. Expected result 3 is obtained. 4. Check the status of the test. 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_RFC5246_CONSISTENCY_MALFORMED_CLIENT_HELLO_MSG_FUN_TC005(void) { HLT_FrameHandle handle = {0}; handle.pointType = POINT_SEND; handle.userData = (void *)&handle; handle.expectReType = REC_TYPE_HANDSHAKE; /* 1. The tested functions as the client, and the tested functions as the server. */ handle.expectHsType = CLIENT_HELLO; /* 2. Obtain the message, modify the field content, and send the message. */ handle.frameCallBack = MalformedClientHelloMsgCallback_05; TestPara testPara = {0}; testPara.port = PORT; /* 3. Check the status of the test. */ testPara.expectHsState = TRY_RECV_SERVER_HELLO; /* 4. Check the status of the tested. */ testPara.expectDescription = ALERT_DECODE_ERROR; ClientSendMalformedRecordHeaderMsg(&handle, &testPara); return; } /* END_CASE */ static void MalformedClientHelloMsgCallback_06(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_ClientHelloMsg *clientHello = &frameMsg->body.hsMsg.body.clientHello; clientHello->cipherSuitesSize.data = 0; clientHello->cipherSuites.state = MISSING_FIELD; EXIT: return; } /* @ * @test SDV_TLS_TLS12_RFC5246_CONSISTENCY_MALFORMED_CLIENT_HELLO_MSG_FUN_TC006 * @title The length of the cipher suite in the clientHello message is 0 and the content is empty. _cipher suites length * @precon nan * @brief 1. The tested functions as the client, and the tested 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. Expected result 3 is obtained. 4. Check the status of the test. 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 test end is alerted, and the handshake status is ready to receive the serverHello message. @ */ /* BEGIN_CASE */ void SDV_TLS_TLS12_RFC5246_CONSISTENCY_MALFORMED_CLIENT_HELLO_MSG_FUN_TC006(void) { HLT_FrameHandle handle = {0}; handle.pointType = POINT_SEND; handle.userData = (void *)&handle; handle.expectReType = REC_TYPE_HANDSHAKE; /* 1. The tested functions as the client, and the tested functions as the server. */ handle.expectHsType = CLIENT_HELLO; /* 2. Obtain the message, modify the field content, and send the message. */ handle.frameCallBack = MalformedClientHelloMsgCallback_06; TestPara testPara = {0}; testPara.port = PORT; /* 4. Check the status of the test. */ testPara.expectHsState = TRY_RECV_SERVER_HELLO; /* 3. Check the status of the tested. */ testPara.expectDescription = ALERT_ILLEGAL_PARAMETER; ClientSendMalformedRecordHeaderMsg(&handle, &testPara); return; } /* END_CASE */ static void MalformedClientHelloMsgCallback_07(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_ClientHelloMsg *clientHello = &frameMsg->body.hsMsg.body.clientHello; clientHello->serverName.exState = INITIAL_FIELD; clientHello->serverName.exLen.state = ASSIGNED_FIELD; clientHello->serverName.exDataLen.state = INITIAL_FIELD; FRAME_ModifyMsgInteger(HS_EX_TYPE_SERVER_NAME, &clientHello->serverName.exType); uint8_t rawData[13] = {0x00, 0x00, 0x09, 0x75, 0x61, 0x77, 0x65, 0x69, 0x2e, 0x63, 0x6F, 0x6d}; FRAME_ModifyMsgArray8( rawData, sizeof(rawData) - 1, &clientHello->serverName.exData, &clientHello->serverName.exDataLen); clientHello->serverName.exLen.data -= 2; EXIT: return; } /* @ * @test SDV_TLS_TLS12_RFC5246_CONSISTENCY_MALFORMED_CLIENT_HELLO_MSG_FUN_TC007 * @title The length of the cipher suites in the clientHello message sent is an odd number_cipher suites length * @precon nan * @brief 1. The tested functions as the client, and the tested 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. Expected result 3 is obtained. 4. Check the status of the test. Expected result 4 is obtained. * @expect 1. A success message is returned. 2. A success message is returned. 3. The tested returns an alert message, and the status is alerted. 4. The status of the test is alerted, and the handshake status is ready to receive the serverHello message. @ */ /* BEGIN_CASE */ void SDV_TLS_TLS12_RFC5246_CONSISTENCY_MALFORMED_CLIENT_HELLO_MSG_FUN_TC007(void) { HLT_FrameHandle handle = {0}; handle.pointType = POINT_SEND; handle.userData = (void *)&handle; handle.expectReType = REC_TYPE_HANDSHAKE; /* 1. The tested functions as the client, and the tested functions as the server. */ handle.expectHsType = CLIENT_HELLO; /* 2. Obtain the message, modify the field content, and send the message. */ handle.frameCallBack = MalformedClientHelloMsgCallback_07; TestPara testPara = {0}; testPara.port = PORT; /* 4. Check the status of the test. */ testPara.expectHsState = TRY_RECV_SERVER_HELLO; /* 3. Check the status of the tested. */ testPara.expectDescription = ALERT_DECODE_ERROR; ClientSendMalformedRecordHeaderMsg(&handle, &testPara); return; } /* END_CASE */ static void MalformedClientHelloMsgCallback_08(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_ClientHelloMsg *clientHello = &frameMsg->body.hsMsg.body.clientHello; clientHello->cipherSuitesSize.data = 0; EXIT: return; } /* @ * @test SDV_HITLS_TEST_DTLS_MALFORMED_CLIENT_HELLO_MSG_FUN_TC010 * @title The length of the cipher suite in the clientHello message is 0 but the content is not null. _cipher suites length * @precon nan * @brief 1. The tested functions as the client, and the tested 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. Expected result 3 is obtained. 4. Check the status of the test. Expected result 4 is obtained. * @expect 1. A success message is returned. 2. A success message is returned. 3. The tested returns an alert message, indicating that the status is alerted. 4. The status of the test is alerted, and the handshake status is ready to receive the serverHello message. @ */ /* BEGIN_CASE */ void SDV_TLS_TLS12_RFC5246_CONSISTENCY_MALFORMED_CLIENT_HELLO_MSG_FUN_TC008(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; /* 2. Obtain the message, modify the field content, and send the message. */ handle.frameCallBack = MalformedClientHelloMsgCallback_08; TestPara testPara = {0}; testPara.port = PORT; /* 4. Check the status of the test. */ testPara.expectHsState = TRY_RECV_SERVER_HELLO; /* 3. Check the status of the tested. */ testPara.expectDescription = ALERT_ILLEGAL_PARAMETER; ClientSendMalformedRecordHeaderMsg(&handle, &testPara); return; } /* END_CASE */ static void MalformedClientHelloMsgCallback_09(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_ClientHelloMsg *clientHello = &frameMsg->body.hsMsg.body.clientHello; clientHello->cipherSuites.state = MISSING_FIELD; EXIT: return; } /* @ * @test SDV_TLS_TLS12_RFC5246_CONSISTENCY_MALFORMED_CLIENT_HELLO_MSG_FUN_TC009 * @title The length of the cipher suite in the clientHello message is not 0 but the content is empty. _cipher suites length * @precon nan * @brief 1. The tested functions as the client, and the tested 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. Expected result 3 is obtained. 4. Check the status of the test. Expected result 4 is obtained. * @expect 1. A success message is returned. 2. A success message is returned. 3. The tested returns an alert message, and the status is alerted. 4. The status of the test is alerted, and the handshake status is ready to receive the serverHello message. @ */ /* BEGIN_CASE */ void SDV_TLS_TLS12_RFC5246_CONSISTENCY_MALFORMED_CLIENT_HELLO_MSG_FUN_TC009(void) { HLT_FrameHandle handle = {0}; handle.pointType = POINT_SEND; handle.userData = (void *)&handle; handle.expectReType = REC_TYPE_HANDSHAKE; /* 1. The tested functions as the client, and the tested functions as the server. */ handle.expectHsType = CLIENT_HELLO; /* 2. Obtain the message, modify the field content, and send the message. */ handle.frameCallBack = MalformedClientHelloMsgCallback_09; TestPara testPara = {0}; testPara.port = PORT; /* 4. Check the status of the test. */ testPara.expectHsState = TRY_RECV_SERVER_HELLO; /* 3. Check the status of the tested. */ testPara.expectDescription = ALERT_DECODE_ERROR; ClientSendMalformedRecordHeaderMsg(&handle, &testPara); return; } /* END_CASE */ static void MalformedClientHelloMsgCallback_10(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_ClientHelloMsg *clientHello = &frameMsg->body.hsMsg.body.clientHello; clientHello->cipherSuitesSize.data -= sizeof(uint16_t); EXIT: return; } /* @ * @test SDV_TLS_TLS12_RFC5246_CONSISTENCY_MALFORMED_CLIENT_HELLO_MSG_FUN_TC010 * @title The length of the cipher suite in the sent clientHello message is less than the specific content length_cipher suites length * @precon nan * @brief 1. The tested functions as the client, and the tested 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. Expected result 3 is obtained. 4. Check the status of the test. Expected result 4 is obtained. * @expect 1. A success message is returned. 2. A success message is returned. 3. The tested returns an alert message, and the status is alerted. 4. The status of the test is alerted, and the handshake status is ready to receive the serverHello message. @ */ /* BEGIN_CASE */ void SDV_TLS_TLS12_RFC5246_CONSISTENCY_MALFORMED_CLIENT_HELLO_MSG_FUN_TC010(void) { HLT_FrameHandle handle = {0}; handle.pointType = POINT_SEND; handle.userData = (void *)&handle; handle.expectReType = REC_TYPE_HANDSHAKE; /* 1. The tested functions as the client, and the tested functions as the server. */ handle.expectHsType = CLIENT_HELLO; /* 2. Obtain the message, modify the field content, and send the message. */ handle.frameCallBack = MalformedClientHelloMsgCallback_10; TestPara testPara = {0}; testPara.port = PORT; /* 4. Check the status of the test. */ testPara.expectHsState = TRY_RECV_SERVER_HELLO; /* 3. Check the status of the tested. */ testPara.expectDescription = ALERT_DECODE_ERROR; ClientSendMalformedRecordHeaderMsg(&handle, &testPara); return; } /* END_CASE */ static void MalformedClientHelloMsgCallback_11(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_ClientHelloMsg *clientHello = &frameMsg->body.hsMsg.body.clientHello; clientHello->cipherSuitesSize.data += sizeof(uint16_t); EXIT: return; } /* @ * @test SDV_TLS_TLS12_RFC5246_CONSISTENCY_MALFORMED_CLIENT_HELLO_MSG_FUN_TC011 * @title The length of the cipher suite in the sent ClientHello message is greater than the specific content length_cipher suites length * @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_RFC5246_CONSISTENCY_MALFORMED_CLIENT_HELLO_MSG_FUN_TC011(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; /* 2. Obtain the message, modify the field content, and send the message. */ handle.frameCallBack = MalformedClientHelloMsgCallback_11; TestPara testPara = {0}; testPara.port = PORT; /* 4. Check the status of the test. */ testPara.expectHsState = TRY_RECV_SERVER_HELLO; /* 3. Check the status of the tested */ testPara.expectDescription = ALERT_DECODE_ERROR; ClientSendMalformedRecordHeaderMsg(&handle, &testPara); return; } /* END_CASE */ static void MalformedClientHelloMsgCallback_12(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_ClientHelloMsg *clientHello = &frameMsg->body.hsMsg.body.clientHello; clientHello->compressionMethodsLen.data = 0; clientHello->compressionMethods.state = MISSING_FIELD; EXIT: return; } /* @ * @test SDV_TLS_TLS12_RFC5246_CONSISTENCY_MALFORMED_CLIENT_HELLO_MSG_FUN_TC012 * @title The length of the compression list of the sent ClientHello message is 0 and the content is empty. _compression methods length * @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, indicating that 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_RFC5246_CONSISTENCY_MALFORMED_CLIENT_HELLO_MSG_FUN_TC012(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; /* 2. Obtain the message, modify the field content, and send the message. */ handle.frameCallBack = MalformedClientHelloMsgCallback_12; TestPara testPara = {0}; testPara.port = PORT; /* 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 MalformedClientHelloMsgCallback_13(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_ClientHelloMsg *clientHello = &frameMsg->body.hsMsg.body.clientHello; uint8_t compressionMethods[] = {0, 1}; FRAME_ModifyMsgArray8(compressionMethods, sizeof(compressionMethods), &clientHello->compressionMethods, &clientHello->compressionMethodsLen); clientHello->compressionMethodsLen.data--; EXIT: return; } /* @ * @test SDV_TLS_TLS12_RFC5246_CONSISTENCY_MALFORMED_CLIENT_HELLO_MSG_FUN_TC013 * @title The length of the compression list in the sent ClientHello message is less than the content length_compression methods length * @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, indicating that 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_RFC5246_CONSISTENCY_MALFORMED_CLIENT_HELLO_MSG_FUN_TC013(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; /* 2. Obtain the message, modify the field content, and send the message. */ handle.frameCallBack = MalformedClientHelloMsgCallback_13; TestPara testPara = {0}; testPara.port = PORT; /* 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 MalformedClientHelloMsgCallback_14(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_ClientHelloMsg *clientHello = &frameMsg->body.hsMsg.body.clientHello; uint8_t compressionMethods[] = {0}; FRAME_ModifyMsgArray8(compressionMethods, sizeof(compressionMethods), &clientHello->compressionMethods, &clientHello->compressionMethodsLen); clientHello->compressionMethodsLen.data++; EXIT: return; } /* @ * @test SDV_TLS_TLS12_RFC5246_CONSISTENCY_MALFORMED_CLIENT_HELLO_MSG_FUN_TC014 * @title The length of the compression list in the sent ClientHello message is greater than the content length_compression methods length * @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, indicating that 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_RFC5246_CONSISTENCY_MALFORMED_CLIENT_HELLO_MSG_FUN_TC014(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; /* 2. Obtain the message, modify the field content, and send the message. */ handle.frameCallBack = MalformedClientHelloMsgCallback_14; TestPara testPara = {0}; testPara.port = PORT; /* 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 MalformedClientHelloMsgCallback_15(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_ClientHelloMsg *clientHello = &frameMsg->body.hsMsg.body.clientHello; uint8_t compressionMethods[] = {1}; FRAME_ModifyMsgArray8(compressionMethods, sizeof(compressionMethods), &clientHello->compressionMethods, &clientHello->compressionMethodsLen); EXIT: return; } /* @ * @test SDV_TLS_TLS12_RFC5246_CONSISTENCY_MALFORMED_CLIENT_HELLO_MSG_FUN_TC015 * @title The compression list of clientHello messages sent by the client does not contain compression algorithm _compression methods length * @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_RFC5246_CONSISTENCY_MALFORMED_CLIENT_HELLO_MSG_FUN_TC015(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; /* 2. Obtain the message, modify the field content, and send the message. */ handle.frameCallBack = MalformedClientHelloMsgCallback_15; TestPara testPara = {0}; testPara.port = PORT; // 4. Check the status of the test. testPara.expectHsState = TRY_RECV_SERVER_HELLO; /* 3. Check the status of the tested . */ testPara.expectDescription = ALERT_DECODE_ERROR; ClientSendMalformedRecordHeaderMsg(&handle, &testPara); return; } /* END_CASE */ static void MalformedClientHelloMsgCallback_16(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_ClientHelloMsg *clientHello = &frameMsg->body.hsMsg.body.clientHello; clientHello->extensionLen.state = ASSIGNED_FIELD; clientHello->extensionLen.data--; EXIT: return; } /* @ * @test SDV_TLS_TLS12_RFC5246_CONSISTENCY_MALFORMED_CLIENT_HELLO_MSG_FUN_TC016 * @title The extended length of the clientHello message sent by the client is smaller than the actual message length_Total extended length * @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_RFC5246_CONSISTENCY_MALFORMED_CLIENT_HELLO_MSG_FUN_TC016(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; /* 2. Obtain the message, modify the field content, and send the message. */ handle.frameCallBack = MalformedClientHelloMsgCallback_16; TestPara testPara = {0}; testPara.port = PORT; // 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 MalformedClientHelloMsgCallback_17(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_ClientHelloMsg *clientHello = &frameMsg->body.hsMsg.body.clientHello; clientHello->extensionLen.state = ASSIGNED_FIELD; clientHello->extensionLen.data++; EXIT: return; } /* @ * @test SDV_TLS_TLS12_RFC5246_CONSISTENCY_MALFORMED_CLIENT_HELLO_MSG_FUN_TC017 * @title The extended length of the clientHello message sent by the client is greater than the actual message length_Total extended length * @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_RFC5246_CONSISTENCY_MALFORMED_CLIENT_HELLO_MSG_FUN_TC017(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; /* 2. Obtain the message, modify the field content, and send the message. */ handle.frameCallBack = MalformedClientHelloMsgCallback_17; TestPara testPara = {0}; testPara.port = PORT; // 4. Check the status of the test. testPara.expectHsState = TRY_RECV_SERVER_HELLO; // 3. Check the status of the tested. testPara.expectDescription = ALERT_DECODE_ERROR; ClientSendMalformedRecordHeaderMsg(&handle, &testPara); return; } /* END_CASE */ static void MalformedClientHelloMsgCallback_18(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_ClientHelloMsg *clientHello = &frameMsg->body.hsMsg.body.clientHello; clientHello->pointFormats.exLen.state = ASSIGNED_FIELD; clientHello->pointFormats.exLen.data--; EXIT: return; } /* @ * @test SDV_TLS_TLS12_RFC5246_CONSISTENCY_MALFORMED_CLIENT_HELLO_MSG_FUN_TC018 * @title The extended length of the sent ClientHello message point format is smaller than the actual length_Extended point format * @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, indicating that the status is alerted. 4. The status of the test end is alerted, and the handshake status is ready to receive the serverHello message. * prior Level 1 * @auto TRUE @ */ /* BEGIN_CASE */ void SDV_TLS_TLS12_RFC5246_CONSISTENCY_MALFORMED_CLIENT_HELLO_MSG_FUN_TC018(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; /* 2. Obtain the message, modify the field content, and send the message. */ handle.frameCallBack = MalformedClientHelloMsgCallback_18; TestPara testPara = {0}; testPara.port = PORT; // 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 MalformedClientHelloMsgCallback_19(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_ClientHelloMsg *clientHello = &frameMsg->body.hsMsg.body.clientHello; clientHello->pointFormats.exLen.state = ASSIGNED_FIELD; clientHello->pointFormats.exLen.data++; EXIT: return; } /* @ * @test SDV_TLS_TLS12_RFC5246_CONSISTENCY_MALFORMED_CLIENT_HELLO_MSG_FUN_TC019 * @title The extended length of the sent ClientHello message point format is greater than the actual length_Extended point format * @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, indicating that 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_RFC5246_CONSISTENCY_MALFORMED_CLIENT_HELLO_MSG_FUN_TC019(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; /* 2. Obtain the message, modify the field content, and send the message. */ handle.frameCallBack = MalformedClientHelloMsgCallback_19; TestPara testPara = {0}; testPara.port = PORT; // 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 MalformedClientHelloMsgCallback_20(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_ClientHelloMsg *clientHello = &frameMsg->body.hsMsg.body.clientHello; clientHello->pointFormats.exDataLen.data = 0; clientHello->pointFormats.exData.state = MISSING_FIELD; EXIT: return; } /* @ * @test SDV_TLS_TLS12_RFC5246_CONSISTENCY_MALFORMED_CLIENT_HELLO_MSG_FUN_TC020 * @title The length of the sent ClientHello message is 0 and the content is empty. _ The dot format is extended * @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_RFC5246_CONSISTENCY_MALFORMED_CLIENT_HELLO_MSG_FUN_TC020(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; /* 2. Obtain the message, modify the field content, and send the message. */ handle.frameCallBack = MalformedClientHelloMsgCallback_20; TestPara testPara = {0}; testPara.port = PORT; // 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 MalformedClientHelloMsgCallback_21(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_ClientHelloMsg *clientHello = &frameMsg->body.hsMsg.body.clientHello; clientHello->pointFormats.exDataLen.data = 1; clientHello->pointFormats.exData.state = MISSING_FIELD; EXIT: return; } /* @ * @test SDV_TLS_TLS12_RFC5246_CONSISTENCY_MALFORMED_CLIENT_HELLO_MSG_FUN_TC021 * @title The length of the point format of the clientHello message is not 0 and the content is null. _ The point format is extended * @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_RFC5246_CONSISTENCY_MALFORMED_CLIENT_HELLO_MSG_FUN_TC021(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; /* 2. Obtain the message, modify the field content, and send the message. */ handle.frameCallBack = MalformedClientHelloMsgCallback_21; TestPara testPara = {0}; testPara.port = PORT; // 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 MalformedClientHelloMsgCallback_22(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_ClientHelloMsg *clientHello = &frameMsg->body.hsMsg.body.clientHello; clientHello->supportedGroups.exLen.data -= sizeof(uint16_t); clientHello->supportedGroups.exLen.state = ASSIGNED_FIELD; EXIT: return; } /* @ * @test SDV_TLS_TLS12_RFC5246_CONSISTENCY_MALFORMED_CLIENT_HELLO_MSG_FUN_TC022 * @title The length of the clientHello message that supports group extension is smaller than the actual length_Group extension is supported * @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_RFC5246_CONSISTENCY_MALFORMED_CLIENT_HELLO_MSG_FUN_TC022(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; /* 2. Obtain the message, modify the field content, and send the message. */ handle.frameCallBack = MalformedClientHelloMsgCallback_22; TestPara testPara = {0}; testPara.port = PORT; // 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 MalformedClientHelloMsgCallback_23(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_ClientHelloMsg *clientHello = &frameMsg->body.hsMsg.body.clientHello; clientHello->supportedGroups.exLen.data += sizeof(uint16_t); clientHello->supportedGroups.exLen.state = ASSIGNED_FIELD; EXIT: return; } /* @ * @test SDV_TLS_TLS12_RFC5246_CONSISTENCY_MALFORMED_CLIENT_HELLO_MSG_FUN_TC023 * @title The length of the clientHello message that supports group extension is greater than the actual length._Group extension is supported * @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, indicating that 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_RFC5246_CONSISTENCY_MALFORMED_CLIENT_HELLO_MSG_FUN_TC023(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; /* 2. Obtain the message, modify the field content, and send the message. */ handle.frameCallBack = MalformedClientHelloMsgCallback_23; TestPara testPara = {0}; testPara.port = PORT; // 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 MalformedClientHelloMsgCallback_24(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_ClientHelloMsg *clientHello = &frameMsg->body.hsMsg.body.clientHello; clientHello->supportedGroups.exDataLen.data--; EXIT: return; } /* @ * @test SDV_TLS_TLS12_RFC5246_CONSISTENCY_MALFORMED_CLIENT_HELLO_MSG_FUN_TC024 * @title The clientHello message sent by the client supports the odd number of group lengths._Group extension is supported * @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, indicating that 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_RFC5246_CONSISTENCY_MALFORMED_CLIENT_HELLO_MSG_FUN_TC024(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; /* 2. Obtain the message, modify the field content, and send the message. */ handle.frameCallBack = MalformedClientHelloMsgCallback_24; TestPara testPara = {0}; testPara.port = PORT; // 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 MalformedClientHelloMsgCallback_25(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_ClientHelloMsg *clientHello = &frameMsg->body.hsMsg.body.clientHello; clientHello->supportedGroups.exDataLen.data = 0; clientHello->supportedGroups.exData.state = MISSING_FIELD; EXIT: return; } /* @ * @test SDV_TLS_TLS12_RFC5246_CONSISTENCY_MALFORMED_CLIENT_HELLO_MSG_FUN_TC025 * @title The clientHello message can contain 0 characters and cannot contain any characters._Group extension is supported. * @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_RFC5246_CONSISTENCY_MALFORMED_CLIENT_HELLO_MSG_FUN_TC025(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; /* 2. Obtain the message, modify the field content, and send the message. */ handle.frameCallBack = MalformedClientHelloMsgCallback_25; TestPara testPara = {0}; testPara.port = PORT; // 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 MalformedClientHelloMsgCallback_26(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_ClientHelloMsg *clientHello = &frameMsg->body.hsMsg.body.clientHello; clientHello->signatureAlgorithms.exLen.state = ASSIGNED_FIELD; clientHello->signatureAlgorithms.exLen.data -= sizeof(uint16_t); EXIT: return; } /* @ * @test SDV_TLS_TLS12_RFC5246_CONSISTENCY_MALFORMED_CLIENT_HELLO_MSG_FUN_TC026 * @title The extended signature algorithm length of the clientHello message is less than the actual length_signature algorithm extension * @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_RFC5246_CONSISTENCY_MALFORMED_CLIENT_HELLO_MSG_FUN_TC026(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; /* 2. Obtain the message, modify the field content, and send the message. */ handle.frameCallBack = MalformedClientHelloMsgCallback_26; TestPara testPara = {0}; testPara.port = PORT; // 4. Check the status of the test. testPara.expectHsState = TRY_RECV_SERVER_HELLO; // 3. Check the status of the tested. testPara.expectDescription = ALERT_DECODE_ERROR; ClientSendMalformedRecordHeaderMsg(&handle, &testPara); return; } /* END_CASE */ static void MalformedClientHelloMsgCallback_27(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_ClientHelloMsg *clientHello = &frameMsg->body.hsMsg.body.clientHello; clientHello->signatureAlgorithms.exLen.state = ASSIGNED_FIELD; clientHello->signatureAlgorithms.exLen.data += sizeof(uint16_t); EXIT: return; } /* @ * @test SDV_TLS_TLS12_RFC5246_CONSISTENCY_MALFORMED_CLIENT_HELLO_MSG_FUN_TC027 * @title The extended signature algorithm length of the clientHello message is greater than the actual length_signature algorithm extension * @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_RFC5246_CONSISTENCY_MALFORMED_CLIENT_HELLO_MSG_FUN_TC027(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; /* 2. Obtain the message, modify the field content, and send the message. */ handle.frameCallBack = MalformedClientHelloMsgCallback_27; TestPara testPara = {0}; testPara.port = PORT; // 4. Check the status of the test. testPara.expectHsState = TRY_RECV_SERVER_HELLO; // 3. Check the status of the tested. testPara.expectDescription = ALERT_DECODE_ERROR; ClientSendMalformedRecordHeaderMsg(&handle, &testPara); return; } /* END_CASE */ static void MalformedClientHelloMsgCallback_28(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_ClientHelloMsg *clientHello = &frameMsg->body.hsMsg.body.clientHello; clientHello->signatureAlgorithms.exDataLen.data--; EXIT: return; } /* @ * @test SDV_TLS_TLS12_RFC5246_CONSISTENCY_MALFORMED_CLIENT_HELLO_MSG_FUN_TC028 * @title The signature algorithm length of the clientHello message sent by the client is an odd number_signature algorithm extension * @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, indicating that 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_RFC5246_CONSISTENCY_MALFORMED_CLIENT_HELLO_MSG_FUN_TC028(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; /* 2. Obtain the message, modify the field content, and send the message. */ handle.frameCallBack = MalformedClientHelloMsgCallback_28; TestPara testPara = {0}; testPara.port = PORT; // 4. Check the status of the test. testPara.expectHsState = TRY_RECV_SERVER_HELLO; // 3. Check the status of the tested. testPara.expectDescription = ALERT_DECODE_ERROR; ClientSendMalformedRecordHeaderMsg(&handle, &testPara); return; } /* END_CASE */ static void MalformedClientHelloMsgCallback_29(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_ClientHelloMsg *clientHello = &frameMsg->body.hsMsg.body.clientHello; clientHello->signatureAlgorithms.exDataLen.data = 0; clientHello->signatureAlgorithms.exData.state = MISSING_FIELD; EXIT: return; } /* @ * @test SDV_TLS_TLS12_RFC5246_CONSISTENCY_MALFORMED_CLIENT_HELLO_MSG_FUN_TC029 * @title The signature algorithm length of the clientHello message is 0 and the content is empty_signature algorithm extension * @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 is obtained. 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_RFC5246_CONSISTENCY_MALFORMED_CLIENT_HELLO_MSG_FUN_TC029(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; /* 2. Obtain the message, modify the field content, and send the message. */ handle.frameCallBack = MalformedClientHelloMsgCallback_29; TestPara testPara = {0}; testPara.port = PORT; // 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 MalformedClientHelloMsgCallback_30(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_ClientHelloMsg *clientHello = &frameMsg->body.hsMsg.body.clientHello; uint8_t extendedMasterSecret[] = {0}; FRAME_ModifyMsgArray8(extendedMasterSecret, sizeof(extendedMasterSecret), &clientHello->extendedMasterSecret.exData, NULL); EXIT: return; } /* @ * @test SDV_TLS_TLS12_RFC5246_CONSISTENCY_MALFORMED_CLIENT_HELLO_MSG_FUN_TC030 * @title The length of the extended master key in the clientHello message is not 0_Extended master key * @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, indicating that 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_RFC5246_CONSISTENCY_MALFORMED_CLIENT_HELLO_MSG_FUN_TC030(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; /* 2. Obtain the message, modify the field content, and send the message. */ handle.frameCallBack = MalformedClientHelloMsgCallback_30; TestPara testPara = {0}; testPara.port = PORT; // 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; testPara.isSupportExtendMasterSecret = true; ClientSendMalformedRecordHeaderMsg(&handle, &testPara); return; } /* END_CASE */ static void MalformedClientHelloMsgCallback_31(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_ClientHelloMsg *clientHello = &frameMsg->body.hsMsg.body.clientHello; clientHello->sessionTicket.exDataLen.state = ASSIGNED_FIELD; clientHello->sessionTicket.exDataLen.data--; EXIT: return; } /* @ * @test SDV_TLS_TLS12_RFC5246_CONSISTENCY_MALFORMED_CLIENT_HELLO_MSG_FUN_TC031 * @title The SessionTicket extension length of the clientHello message sent by the client is smaller than the actual length. * @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_RFC5246_CONSISTENCY_MALFORMED_CLIENT_HELLO_MSG_FUN_TC031(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; /* 2. Obtain the message, modify the field content, and send the message. */ handle.frameCallBack = MalformedClientHelloMsgCallback_31; TestPara testPara = {0}; testPara.isSupportSessionTicket = 1; testPara.port = PORT; // 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 MalformedClientHelloMsgCallback_32(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_ClientHelloMsg *clientHello = &frameMsg->body.hsMsg.body.clientHello; clientHello->sessionTicket.exDataLen.state = ASSIGNED_FIELD; clientHello->sessionTicket.exDataLen.data++; EXIT: return; } /* @ * @test SDV_TLS_TLS12_RFC5246_CONSISTENCY_MALFORMED_CLIENT_HELLO_MSG_FUN_TC032 * @title The SessionTicket length of the clientHello message is greater than the actual length. * @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 in the alerted state. 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_RFC5246_CONSISTENCY_MALFORMED_CLIENT_HELLO_MSG_FUN_TC032(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; /* 2. Obtain the message, modify the field content, and send the message. */ handle.frameCallBack = MalformedClientHelloMsgCallback_32; TestPara testPara = {0}; testPara.isSupportSessionTicket = 1; testPara.port = PORT; // 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 MalformedClientHelloMsgCallback_33(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_ClientHelloMsg *clientHello = &frameMsg->body.hsMsg.body.clientHello; clientHello->sessionTicket.exDataLen.data = 1; clientHello->sessionTicket.exDataLen.state = SET_LEN_TO_ONE_BYTE; clientHello->sessionTicket.exData.state = MISSING_FIELD; EXIT: return; } /* @ * @test SDV_TLS_TLS12_RFC5246_CONSISTENCY_MALFORMED_CLIENT_HELLO_MSG_FUN_TC033 * @title The SessionTicket length of the clientHello message is not zero and the content is empty. * @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, indicating that 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_RFC5246_CONSISTENCY_MALFORMED_CLIENT_HELLO_MSG_FUN_TC033(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; /* 2. Obtain the message, modify the field content, and send the message. */ handle.frameCallBack = MalformedClientHelloMsgCallback_33; TestPara testPara = {0}; testPara.isSupportSessionTicket = 1; testPara.port = PORT; // 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 MalformedClientHelloMsgCallback_34(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_ClientHelloMsg *clientHello = &frameMsg->body.hsMsg.body.clientHello; clientHello->serverName.exState = INITIAL_FIELD; clientHello->serverName.exLen.state = ASSIGNED_FIELD; clientHello->serverName.exDataLen.state = INITIAL_FIELD; FRAME_ModifyMsgInteger(HS_EX_TYPE_SERVER_NAME, &clientHello->serverName.exType); uint8_t rawData[13] = {0x00, 0x00, 0x09, 0x75, 0x61, 0x77, 0x65, 0x69, 0x2e, 0x63, 0x6F, 0x6d}; FRAME_ModifyMsgArray8( rawData, sizeof(rawData) - 1, &clientHello->serverName.exData, &clientHello->serverName.exDataLen); clientHello->serverName.exLen.data -= 2; EXIT: return; } /* @ * @test SDV_TLS_TLS12_RFC5246_CONSISTENCY_MALFORMED_CLIENT_HELLO_MSG_FUN_TC034 * @title The extended length of the servername in the clientHello message is smaller than the actual length. * @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 tested end.Expected result 4 is obtained. * @expect 1. A success message is returned. 2. A success message is returned. 3. The tested end returns alert, and the status is alert. 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_RFC5246_CONSISTENCY_MALFORMED_CLIENT_HELLO_MSG_FUN_TC034(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; /* 2. Obtain the message, modify the field content, and send the message. */ handle.frameCallBack = MalformedClientHelloMsgCallback_34; TestPara testPara = {0}; testPara.port = PORT; // 4. Check the status of the tested end. testPara.expectHsState = TRY_RECV_SERVER_HELLO; // 3. Check the status of the tested end. testPara.expectDescription = ALERT_DECODE_ERROR; testPara.isSupportExtendMasterSecret = true; ClientSendMalformedRecordHeaderMsg(&handle, &testPara); return; } /* END_CASE */ static void MalformedClientHelloMsgCallback_35(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_ClientHelloMsg *clientHello = &frameMsg->body.hsMsg.body.clientHello; clientHello->serverName.exState = INITIAL_FIELD; clientHello->serverName.exLen.state = ASSIGNED_FIELD; clientHello->serverName.exDataLen.state = INITIAL_FIELD; FRAME_ModifyMsgInteger(HS_EX_TYPE_SERVER_NAME, &clientHello->serverName.exType); uint8_t rawData[13] = {0x00, 0x00, 0x09, 0x75, 0x61, 0x77, 0x65, 0x69, 0x2e, 0x63, 0x6F, 0x6d}; FRAME_ModifyMsgArray8( rawData, sizeof(rawData) - 1, &clientHello->serverName.exData, &clientHello->serverName.exDataLen); clientHello->serverName.exLen.data += 2; EXIT: return; } /* @ * @test SDV_TLS_TLS12_RFC5246_CONSISTENCY_MALFORMED_CLIENT_HELLO_MSG_FUN_TC035 * @title The extended length of the servername in the clientHello message is greater than the actual length. * @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 tested end.Expected result 4 is obtained. * @expect 1. A success message is returned. 2. A success message is returned. 3. The tested end returns alert, and the status is alert. 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_RFC5246_CONSISTENCY_MALFORMED_CLIENT_HELLO_MSG_FUN_TC035(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; /* 2. Obtain the message, modify the field content, and send the message. */ handle.frameCallBack = MalformedClientHelloMsgCallback_35; TestPara testPara = {0}; testPara.port = PORT; // 4. Check the status of the tested end. testPara.expectHsState = TRY_RECV_SERVER_HELLO; // 3. Check the status of the tested end. testPara.expectDescription = ALERT_DECODE_ERROR; testPara.isSupportExtendMasterSecret = true; ClientSendMalformedRecordHeaderMsg(&handle, &testPara); return; } /* END_CASE */ static void MalformedClientHelloMsgCallback_36(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_ClientHelloMsg *clientHello = &frameMsg->body.hsMsg.body.clientHello; clientHello->serverName.exState = INITIAL_FIELD; clientHello->serverName.exLen.state = ASSIGNED_FIELD; clientHello->serverName.exDataLen.state = INITIAL_FIELD; FRAME_ModifyMsgInteger(HS_EX_TYPE_SERVER_NAME, &clientHello->serverName.exType); uint8_t rawData[4] = {0x00, 0x00, 0x01, 0x01}; FRAME_ModifyMsgArray8( rawData, sizeof(rawData) - 1, &clientHello->serverName.exData, &clientHello->serverName.exDataLen); clientHello->serverName.exLen.data = 0; clientHello->serverName.exDataLen.data = 0; EXIT: return; } /* @ * @test SDV_TLS_TLS12_RFC5246_CONSISTENCY_MALFORMED_CLIENT_HELLO_MSG_FUN_TC036 * @title The extended length of the servername in the clientHello message is 0 and the content is not null. * @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 tested end.Expected result 4 is obtained. * @expect 1. A success message is returned. 2. A success message is returned. 3. The tested end returns alert, and the status is alert. 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_RFC5246_CONSISTENCY_MALFORMED_CLIENT_HELLO_MSG_FUN_TC036(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; /* 2. Obtain the message, modify the field content, and send the message. */ handle.frameCallBack = MalformedClientHelloMsgCallback_36; TestPara testPara = {0}; testPara.port = PORT; // 4. Check the status of the tested end. testPara.expectHsState = TRY_RECV_SERVER_HELLO; // 3. Check the status of the tested end. testPara.expectDescription = ALERT_DECODE_ERROR; testPara.isSupportExtendMasterSecret = true; ClientSendMalformedRecordHeaderMsg(&handle, &testPara); return; } /* END_CASE */ static void MalformedClientHelloMsgCallback_37(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_ClientHelloMsg *clientHello = &frameMsg->body.hsMsg.body.clientHello; clientHello->serverName.exState = INITIAL_FIELD; clientHello->serverName.exLen.state = ASSIGNED_FIELD; clientHello->serverName.exDataLen.state = MISSING_FIELD; clientHello->serverName.exData.state = MISSING_FIELD; FRAME_ModifyMsgInteger(HS_EX_TYPE_SERVER_NAME, &clientHello->serverName.exType); clientHello->serverName.exLen.data = 0; EXIT: return; } /* @ * @test SDV_TLS_TLS12_RFC5246_CONSISTENCY_MALFORMED_CLIENT_HELLO_MSG_FUN_TC037 * @title The length of the servername extension in the clientHello message is 0 and the content is empty. * @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 tested end.Expected result 4 is obtained. * @expect 1. A success message is returned. 2. A success message is returned. 3. The tested end returns alert, and the status is alert. 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_RFC5246_CONSISTENCY_MALFORMED_CLIENT_HELLO_MSG_FUN_TC037(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; /* 2. Obtain the message, modify the field content, and send the message. */ handle.frameCallBack = MalformedClientHelloMsgCallback_37; TestPara testPara = {0}; testPara.port = PORT; // 4. Check the status of the tested end. testPara.expectHsState = TRY_RECV_SERVER_HELLO; // 3. Check the status of the tested end. testPara.expectDescription = ALERT_DECODE_ERROR; testPara.isSupportExtendMasterSecret = true; ClientSendMalformedRecordHeaderMsg(&handle, &testPara); return; } /* END_CASE */ static void MalformedClientHelloMsgCallback_38(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_ClientHelloMsg *clientHello = &frameMsg->body.hsMsg.body.clientHello; clientHello->alpn.exState = INITIAL_FIELD; clientHello->alpn.exLen.state = ASSIGNED_FIELD; clientHello->alpn.exDataLen.state = INITIAL_FIELD; FRAME_ModifyMsgInteger(HS_EX_TYPE_APP_LAYER_PROTOCOLS, &clientHello->alpn.exType); uint8_t rawData[13] = {0x00, 0x00, 0x09, 0x75, 0x61, 0x77, 0x65, 0x69, 0x2e, 0x63, 0x6F, 0x6d}; FRAME_ModifyMsgArray8(rawData, sizeof(rawData) - 1, &clientHello->alpn.exData, &clientHello->alpn.exDataLen); clientHello->alpn.exLen.data -= 2; EXIT: return; } /* @ * @test SDV_TLS_TLS12_RFC5246_CONSISTENCY_MALFORMED_CLIENT_HELLO_MSG_FUN_TC038 * @title The extended length of the servername in the clientHello message is smaller than the actual length. * @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 tested end. Expected result 4 is obtained. * @expect 1. A success message is returned. 2. A success message is returned. 3. The tested end returns alert, and the status is alert. 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_RFC5246_CONSISTENCY_MALFORMED_CLIENT_HELLO_MSG_FUN_TC038(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; /* 2. Obtain the message, modify the field content, and send the message. */ handle.frameCallBack = MalformedClientHelloMsgCallback_38; TestPara testPara = {0}; testPara.port = PORT; // 4. Check the status of the tested end. testPara.expectHsState = TRY_RECV_SERVER_HELLO; // 3. Check the status of the tested end. testPara.expectDescription = ALERT_DECODE_ERROR; testPara.isSupportExtendMasterSecret = true; testPara.isSupportALPN = true; ClientSendMalformedRecordHeaderMsg(&handle, &testPara); return; } /* END_CASE */ static void MalformedClientHelloMsgCallback_39(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_ClientHelloMsg *clientHello = &frameMsg->body.hsMsg.body.clientHello; clientHello->alpn.exState = INITIAL_FIELD; clientHello->alpn.exLen.state = ASSIGNED_FIELD; clientHello->alpn.exDataLen.state = INITIAL_FIELD; FRAME_ModifyMsgInteger(HS_EX_TYPE_APP_LAYER_PROTOCOLS, &clientHello->alpn.exType); uint8_t rawData[13] = {0x00, 0x00, 0x09, 0x75, 0x61, 0x77, 0x65, 0x69, 0x2e, 0x63, 0x6F, 0x6d}; FRAME_ModifyMsgArray8(rawData, sizeof(rawData) - 1, &clientHello->alpn.exData, &clientHello->alpn.exDataLen); clientHello->alpn.exLen.data += 2; EXIT: return; } /* @ * @test SDV_TLS_TLS12_RFC5246_CONSISTENCY_MALFORMED_CLIENT_HELLO_MSG_FUN_TC039 * @title The extended length of the servername in the clientHello message is greater than the actual length. * @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. Return a success message. 2. Return a success message. 3. Return an alert message. The status of the tested end is alert. 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_RFC5246_CONSISTENCY_MALFORMED_CLIENT_HELLO_MSG_FUN_TC039(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; /* 2. Obtain the message, modify the field content, and send the message. */ handle.frameCallBack = MalformedClientHelloMsgCallback_39; TestPara testPara = {0}; testPara.port = PORT; // 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; testPara.isSupportExtendMasterSecret = true; testPara.isSupportALPN = true; ClientSendMalformedRecordHeaderMsg(&handle, &testPara); return; } /* END_CASE */ static void MalformedClientHelloMsgCallback_40(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_ClientHelloMsg *clientHello = &frameMsg->body.hsMsg.body.clientHello; clientHello->alpn.exState = INITIAL_FIELD; clientHello->alpn.exLen.state = ASSIGNED_FIELD; clientHello->alpn.exDataLen.state = INITIAL_FIELD; FRAME_ModifyMsgInteger(HS_EX_TYPE_APP_LAYER_PROTOCOLS, &clientHello->alpn.exType); uint8_t rawData[4] = {0x02, 0x02, 0x01, 0x01}; FRAME_ModifyMsgArray8(rawData, sizeof(rawData) - 1, &clientHello->alpn.exData, &clientHello->alpn.exDataLen); clientHello->alpn.exLen.data = 0; clientHello->alpn.exDataLen.data = 0; EXIT: return; } /* @ * @test SDV_TLS_TLS12_RFC5246_CONSISTENCY_MALFORMED_CLIENT_HELLO_MSG_FUN_TC040 * @title The extended length of the servername in the clientHello message is 0 and the content is not null. * @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 alert, and the status is alert. 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_RFC5246_CONSISTENCY_MALFORMED_CLIENT_HELLO_MSG_FUN_TC040(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; /* 2. Obtain the message, modify the field content, and send the message. */ handle.frameCallBack = MalformedClientHelloMsgCallback_40; TestPara testPara = {0}; testPara.port = PORT; // 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; testPara.isSupportExtendMasterSecret = true; testPara.isSupportALPN = true; ClientSendMalformedRecordHeaderMsg(&handle, &testPara); return; } /* END_CASE */ static void MalformedClientHelloMsgCallback_41(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_ClientHelloMsg *clientHello = &frameMsg->body.hsMsg.body.clientHello; clientHello->alpn.exState = INITIAL_FIELD; clientHello->alpn.exLen.state = ASSIGNED_FIELD; clientHello->alpn.exDataLen.state = MISSING_FIELD; clientHello->alpn.exData.state = MISSING_FIELD; FRAME_ModifyMsgInteger(HS_EX_TYPE_SERVER_NAME, &clientHello->alpn.exType); clientHello->alpn.exLen.data = 0; EXIT: return; } /* @ * @test SDV_TLS_TLS12_RFC5246_CONSISTENCY_MALFORMED_CLIENT_HELLO_MSG_FUN_TC041 * @title The extended length of the servername in the clientHello message is 0. The content is empty. * @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 tested end. Expected result 4 is obtained. * @expect 1. A success message is returned. 2. A success message is returned. 3. The tested end returns alert, and the status is alert. 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_RFC5246_CONSISTENCY_MALFORMED_CLIENT_HELLO_MSG_FUN_TC041(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; // 2. Obtain the message, modify the field content, and send the message. handle.frameCallBack = MalformedClientHelloMsgCallback_41; TestPara testPara = {0}; testPara.port = PORT; // 4. Check the status of the tested end. testPara.expectHsState = TRY_RECV_SERVER_HELLO; // 3. Check the status of the tested end. testPara.expectDescription = ALERT_DECODE_ERROR; testPara.isSupportExtendMasterSecret = true; testPara.isSupportALPN = true; ClientSendMalformedRecordHeaderMsg(&handle, &testPara); return; } /* END_CASE */ static void MalformedClientHelloMsgCallback_42(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_ClientHelloMsg *clientHello = &frameMsg->body.hsMsg.body.clientHello; clientHello->extendedMasterSecret.exType.data = 0xFFFFu; EXIT: return; } /* @ * @test SDV_TLS_TLS12_RFC5246_CONSISTENCY_MALFORMED_CLIENT_HELLO_MSG_FUN_TC042 * @title The sent ClientHello message contains an unrecognized extension type _ extension type * @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. Capture the message, modify the field content, and send the message. Expected result 2 is obtained. 3. Check the status of the tested end. Expected result 3 is obtained. 4. Check the status of the tested end. Expected result 4 is obtained. * @expect 1. A success message is returned. 2. A success message is returned. 3. The tested end returns alert 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_RFC5246_CONSISTENCY_MALFORMED_CLIENT_HELLO_MSG_FUN_TC042(void) { HLT_FrameHandle handle = {0}; handle.pointType = POINT_SEND; handle.userData = (void *)&handle; handle.expectReType = REC_TYPE_HANDSHAKE; handle.expectHsType = CLIENT_HELLO; handle.frameCallBack = MalformedClientHelloMsgCallback_42; TestPara testPara = {0}; testPara.port = PORT; testPara.expectHsState = TRY_RECV_FINISH; testPara.expectDescription = ALERT_DECRYPT_ERROR; testPara.isSupportExtendMasterSecret = false; ClientSendMalformedRecordHeaderMsg(&handle, &testPara); return; } /* END_CASE */ static void MalformedClientHelloMsgCallback_43(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_ClientHelloMsg *clientHello = &frameMsg->body.hsMsg.body.clientHello; clientHello->extensionState = MISSING_FIELD; clientHello->pointFormats.exState = MISSING_FIELD; clientHello->supportedGroups.exState = MISSING_FIELD; clientHello->signatureAlgorithms.exState = MISSING_FIELD; clientHello->extendedMasterSecret.exState = MISSING_FIELD; clientHello->secRenego.exState = MISSING_FIELD; EXIT: return; } /* @ * @test SDV_TLS_TLS12_RFC5246_CONSISTENCY_MALFORMED_CLIENT_HELLO_MSG_FUN_TC043 * @title The sent ClientHello message does not contain any extension type. * @precon nan * @brief 1. The server stops receiving client hello messages. Expected result 1 is obtained. 2. Configure the client to send a client hello message without any extension type. Expected result 2 is obtained. 3. The server continues to establish a link. Expected result 3 is obtained. * @expect 1. Success 2. Success 3. Success @ */ /* BEGIN_CASE */ void SDV_TLS_TLS12_RFC5246_CONSISTENCY_MALFORMED_CLIENT_HELLO_MSG_FUN_TC043(void) { HLT_FrameHandle handle = {0}; handle.pointType = POINT_SEND; handle.userData = (void *)&handle; handle.expectReType = REC_TYPE_HANDSHAKE; handle.expectHsType = CLIENT_HELLO; handle.frameCallBack = MalformedClientHelloMsgCallback_43; TestPara testPara = {0}; testPara.port = PORT; testPara.expectHsState = TRY_RECV_SERVER_HELLO; testPara.expectDescription = ALERT_HANDSHAKE_FAILURE; testPara.isExpectRet = true; testPara.expectRet = HITLS_MSG_HANDLE_CIPHER_SUITE_ERR; ClientSendMalformedRecordHeaderMsg(&handle, &testPara); return; } /* END_CASE */ static void TEST_UnexpectMsg(HLT_FrameHandle *frameHandle, TestExpect *testExpect, bool isSupportClientVerify) { HLT_Tls_Res *serverRes = NULL; HLT_Tls_Res *clientRes = NULL; HLT_Process *localProcess = NULL; HLT_Process *remoteProcess = NULL; HLT_Ctx_Config *serverConfig = NULL; ALERT_Info alertInfo = {0}; localProcess = HLT_InitLocalProcess(HITLS); ASSERT_TRUE(localProcess != NULL); remoteProcess = HLT_LinkRemoteProcess(HITLS, TCP, PORT, true); ASSERT_TRUE(remoteProcess != NULL); serverConfig = HLT_NewCtxConfigTLCP(NULL, "SERVER", false); ASSERT_TRUE(serverConfig != NULL); if (isSupportClientVerify) { ASSERT_TRUE(HLT_SetClientVerifySupport(serverConfig, isSupportClientVerify) == 0); } HLT_Ctx_Config *clientConfig = HLT_NewCtxConfigTLCP(NULL, "CLIENT", true); ASSERT_TRUE(clientConfig != NULL); ASSERT_TRUE(HLT_SetClientVerifySupport(clientConfig, isSupportClientVerify) == 0); serverRes = HLT_ProcessTlsAccept(remoteProcess, TLCP1_1, serverConfig, NULL); ASSERT_TRUE(serverRes != NULL); // Client Initialization clientRes = HLT_ProcessTlsInit(localProcess, TLCP1_1, clientConfig, NULL); ASSERT_TRUE(clientRes != NULL); ASSERT_TRUE(frameHandle != NULL); frameHandle->ctx = clientRes->ssl; HLT_SetFrameHandle(frameHandle); ASSERT_EQ(HLT_TlsConnect(clientRes->ssl), testExpect->connectExpect); HLT_CleanFrameHandle(); ALERT_GetInfo(clientRes->ssl, &alertInfo); ASSERT_TRUE(alertInfo.level == testExpect->expectLevel); ASSERT_EQ(alertInfo.description, testExpect->expectDescription); ASSERT_EQ(HLT_RpcGetTlsAcceptResult(serverRes->acceptId), testExpect->acceptExpect); EXIT: HLT_CleanFrameHandle(); HLT_FreeAllProcess(); } /* @ * @test SDV_TLS_TLS12_RFC5246_CONSISTENCY_CERTFICATE_VERITY_FAIL_TC006 * @titleThe client does not send the certificate. Instead, the client sends the certificate. * @precon nan * @brief 1. Configure dual-end verification. Expected result 1 is obtained. 2. Set the client severhello done callback to send certificate verify. * @expect 1. Expected success 2. Expected server to return alert @ */ /* BEGIN_CASE */ void SDV_TLS_TLS12_RFC5246_CONSISTENCY_CERTFICATE_VERITY_FAIL_TC006() { // 1. Configure dual-end verification. TestExpect testExpect = {0}; testExpect.acceptExpect = HITLS_MSG_HANDLE_UNEXPECTED_MESSAGE; testExpect.expectLevel = ALERT_LEVEL_FATAL; testExpect.expectDescription = ALERT_UNEXPECTED_MESSAGE; testExpect.connectExpect = HITLS_REC_NORMAL_RECV_UNEXPECT_MSG; HLT_FrameHandle frameHandle = {0}; // 2. Set the client severhello done callback to send certificate verify. frameHandle.frameCallBack = TEST_SendUnexpectClientKeyExchangeMsg; frameHandle.expectHsType = CERTIFICATE; frameHandle.expectReType = REC_TYPE_HANDSHAKE; frameHandle.ioState = EXP_NONE; frameHandle.pointType = POINT_SEND; frameHandle.userData = NULL; TEST_UnexpectMsg(&frameHandle, &testExpect, true); return; } /* END_CASE */ /* @ * @test SDV_TLS_TLS12_RFC5246_CONSISTENCY_CLIENT_SEND_CERTFICATE_VERITY_TC001 * @title The client does not send the certificate. Instead, the client sends the certificate. * @precon nan * @brief 1. Configure unidirectional authentication. Expected result 1 is obtained. 2. Set the client severhello done callback to send certificate verify. * @expect 1. Expected success 2. Expected server to return alert @ */ /* BEGIN_CASE */ void SDV_TLS_TLS12_RFC5246_CONSISTENCY_CLIENT_SEND_CERTFICATE_VERITY_TC001() { // 1. Configure unidirectional authentication. TestExpect testExpect = {0}; testExpect.acceptExpect = HITLS_MSG_HANDLE_UNEXPECTED_MESSAGE; testExpect.expectLevel = ALERT_LEVEL_FATAL; testExpect.expectDescription = ALERT_UNEXPECTED_MESSAGE; testExpect.connectExpect = HITLS_REC_NORMAL_RECV_UNEXPECT_MSG; HLT_FrameHandle frameHandle = {0}; // 2. Set the client severhello done callback to send certificate verify. frameHandle.frameCallBack = TEST_SendUnexpectCertificateMsg; frameHandle.expectHsType = CLIENT_KEY_EXCHANGE; frameHandle.expectReType = REC_TYPE_HANDSHAKE; frameHandle.ioState = EXP_NONE; frameHandle.pointType = POINT_SEND; frameHandle.userData = NULL; TEST_UnexpectMsg(&frameHandle, &testExpect, false); return; } /* END_CASE */ /* @ * @test SDV_TLS_TLS12_RFC5246_CONSISTENCY_CERTFICATE_VERITY_FAIL_TC007 * @title The client does not send the certificate. Instead, the client sends the certificate. * @precon nan * @brief 1. Configure unidirectional authentication. Expected result 1 is obtained. 2. Set the client severhello done callback to send certificate verify. * @expect 1. Expected success 2. Expected server to return alert @ */ /* BEGIN_CASE */ void SDV_TLS_TLS12_RFC5246_CONSISTENCY_CERTFICATE_VERITY_FAIL_TC007() { // 1. Configure unidirectional authentication. TestExpect testExpect = {0}; testExpect.acceptExpect = HITLS_MSG_HANDLE_UNEXPECTED_MESSAGE; testExpect.expectLevel = ALERT_LEVEL_FATAL; testExpect.expectDescription = ALERT_UNEXPECTED_MESSAGE; testExpect.connectExpect = HITLS_REC_NORMAL_RECV_UNEXPECT_MSG; HLT_FrameHandle frameHandle = {0}; // 2. Set the client severhello done callback to send certificate verify. frameHandle.frameCallBack = TEST_SendUnexpectCertificateVerifyMsg; frameHandle.expectHsType = CLIENT_KEY_EXCHANGE; frameHandle.expectReType = REC_TYPE_HANDSHAKE; frameHandle.ioState = EXP_NONE; frameHandle.pointType = POINT_SEND; frameHandle.userData = NULL; TEST_UnexpectMsg(&frameHandle, &testExpect, true); return; } /* END_CASE */ /* BEGIN_CASE */ void SDV_TLS_TLS12_RFC5246_CONSISTENCY_SUPPORT_GROUP_TC001(void) { 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(); s_config = HITLS_CFG_NewTLS12Config(); ASSERT_TRUE(c_config != NULL); ASSERT_TRUE(s_config != NULL); uint16_t cipherSuite = HITLS_ECDH_ANON_WITH_AES_128_CBC_SHA; ASSERT_TRUE(HITLS_CFG_SetCipherSuites(c_config, &cipherSuite, 1) == HITLS_SUCCESS); ASSERT_TRUE(HITLS_CFG_SetCipherSuites(s_config, &cipherSuite, 1) == HITLS_SUCCESS); client = FRAME_CreateLink(c_config, BSL_UIO_TCP); ASSERT_TRUE(client != NULL); client->ssl->config.tlsConfig.groupsSize = 0; server = FRAME_CreateLink(s_config, BSL_UIO_TCP); ASSERT_TRUE(server != NULL); ASSERT_TRUE(FRAME_CreateConnection(client, server, true, HS_STATE_BUTT) == HITLS_MSG_HANDLE_CIPHER_SUITE_ERR); EXIT: HITLS_CFG_FreeConfig(c_config); HITLS_CFG_FreeConfig(s_config); FRAME_FreeLink(client); FRAME_FreeLink(server); } /* END_CASE */ void ClientSendMalformedCipherSuiteLenMsg(HLT_FrameHandle *handle, TestPara *testPara) { HLT_Process *localProcess = HLT_InitLocalProcess(HITLS); ASSERT_TRUE(localProcess != NULL); HLT_Process *remoteProcess = HLT_LinkRemoteProcess((HITLS), TCP, 16384, false); ASSERT_TRUE(remoteProcess != NULL); // The remote server listens on the TLS connection. HLT_Ctx_Config *serverConfig = HLT_NewCtxConfig(NULL, "SERVER"); ASSERT_TRUE(serverConfig != NULL); ASSERT_TRUE(HLT_SetClientVerifySupport(serverConfig, testPara->isSupportClientVerify) == 0); serverConfig->isSupportExtendMasterSecret = false; 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); serverConfig->isSupportExtendMasterSecret = false; 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 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); } ALERT_Info alertInfo = { 0 }; ALERT_GetInfo(clientRes->ssl, &alertInfo); ASSERT_EQ(alertInfo.level, ALERT_LEVEL_FATAL); ASSERT_EQ(alertInfo.description, testPara->expectDescription); EXIT: HLT_CleanFrameHandle(); HLT_FreeAllProcess(); return; } static void MalformedCipherSuiteLenCallback_01(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_ClientHelloMsg *clientHello = &frameMsg->body.hsMsg.body.clientHello; clientHello->cipherSuitesSize.data = 1000; clientHello->cipherSuitesSize.state = ASSIGNED_FIELD; EXIT: return; } /** @ * @test SDV_TLS1_2_RFC5246_MALFORMED_CIPHER_SUITE_LEN_FUN_TC001 * @spec - * @title The length of the cipher suite in the sent ClientHello message is greater than the specific content length_cipher suites length * @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. * @prior Level 1 * @auto TRUE @ */ /* BEGIN_CASE */ void SDV_TLS1_2_RFC5246_MALFORMED_CIPHER_SUITE_LEN_FUN_TC001() { 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; /* 2. Obtain the message, modify the field content, and send the message. */ handle.frameCallBack = MalformedCipherSuiteLenCallback_01; TestPara testPara = {0}; testPara.port = PORT; /* 4. Check the status of the test. */ testPara.expectHsState = TRY_RECV_SERVER_HELLO; /* 3. Check the status of the tested */ testPara.expectDescription = ALERT_DECODE_ERROR; ClientSendMalformedCipherSuiteLenMsg(&handle, &testPara); return; } /* END_CASE */
2301_79861745/bench_create
testcode/sdv/testcase/tls/consistency/tls12/test_suite_sdv_hlt_tls12_consistency_rfc5246_malformed_msg.c
C
unknown
115,247
/* * This file is part of the openHiTLS project. * * openHiTLS is licensed under the Mulan PSL v2. * You can use this software according to the terms and conditions of the Mulan PSL v2. * You may obtain a copy of Mulan PSL v2 at: * * http://license.coscl.org.cn/MulanPSL2 * * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, * EITHER EXPRESS 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 */
2301_79861745/bench_create
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 */
2301_79861745/bench_create
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; }
2301_79861745/bench_create
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!"); } }
2301_79861745/bench_create
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 */
2301_79861745/bench_create
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 */
2301_79861745/bench_create
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 */
2301_79861745/bench_create
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 */
2301_79861745/bench_create
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 */
2301_79861745/bench_create
testcode/sdv/testcase/tls/consistency/tls13/test_suite_sdv_frame_tls13_consistency_rfc8446_extensions_1.c
C
unknown
100,938