• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * This file is part of the openHiTLS project.
3  *
4  * openHiTLS is licensed under the Mulan PSL v2.
5  * You can use this software according to the terms and conditions of the Mulan PSL v2.
6  * You may obtain a copy of Mulan PSL v2 at:
7  *
8  *     http://license.coscl.org.cn/MulanPSL2
9  *
10  * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
11  * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
12  * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
13  * See the Mulan PSL v2 for more details.
14  */
15 #include "hitls_build.h"
16 #ifdef HITLS_TLS_HOST_CLIENT
17 #include <string.h>
18 #include "securec.h"
19 #include "tls_binlog_id.h"
20 #include "bsl_log_internal.h"
21 #include "bsl_log.h"
22 #include "bsl_err_internal.h"
23 #include "bsl_sal.h"
24 #include "crypt.h"
25 #include "bsl_uio.h"
26 #include "hitls_error.h"
27 #include "hitls_session.h"
28 #include "hitls.h"
29 #include "hs_ctx.h"
30 #include "hs_common.h"
31 #include "hs_dtls_timer.h"
32 #include "hs_verify.h"
33 #include "pack.h"
34 #include "send_process.h"
35 #include "session_mgr.h"
36 #include "bsl_bytes.h"
37 #include "config_type.h"
38 
39 
40 #if defined(HITLS_TLS_PROTO_TLS_BASIC) || defined(HITLS_TLS_PROTO_DTLS12)
41 #ifdef HITLS_TLS_FEATURE_SESSION
42 /* Check whether the resume function is supported */
ClientPrepareSession(TLS_Ctx * ctx)43 static int32_t ClientPrepareSession(TLS_Ctx *ctx)
44 {
45     HS_Ctx *hsCtx = (HS_Ctx *)ctx->hsCtx;
46 
47     /* If the session cannot be resumed during renegotiation, delete the session */
48     if (ctx->negotiatedInfo.isRenegotiation && !ctx->config.tlsConfig.isResumptionOnRenego) {
49         HITLS_SESS_Free(ctx->session);
50         ctx->session = NULL;
51     }
52 
53     if (ctx->session != NULL) {
54         uint64_t curTime = (uint64_t)BSL_SAL_CurrentSysTimeGet();
55         if (!SESS_CheckValidity(ctx->session, curTime)) {
56             HITLS_SESS_Free(ctx->session);
57             ctx->session = NULL;
58         }
59     }
60 
61     if (ctx->session != NULL) {
62         uint8_t haveExtMasterSecret = 0;
63         HITLS_SESS_GetHaveExtMasterSecret(ctx->session, &haveExtMasterSecret);
64         if (haveExtMasterSecret == 0 && ctx->config.tlsConfig.isSupportExtendMasterSecret) {
65             HITLS_SESS_Free(ctx->session);
66             ctx->session = NULL;
67             return HITLS_SUCCESS;
68         }
69         hsCtx->sessionId = (uint8_t *)BSL_SAL_Calloc(1u, HITLS_SESSION_ID_MAX_SIZE);
70         if (hsCtx->sessionId == NULL) {
71             HITLS_SESS_Free(ctx->session);
72             ctx->session = NULL;
73             BSL_ERR_PUSH_ERROR(HITLS_MEMALLOC_FAIL);
74             BSL_LOG_BINLOG_FIXLEN(BINLOG_ID15624, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN,
75                 "session Id malloc fail.", 0, 0, 0, 0);
76             return HITLS_MEMALLOC_FAIL;
77         }
78 
79         hsCtx->sessionIdSize = HITLS_SESSION_ID_MAX_SIZE;
80         int32_t ret = HITLS_SESS_GetSessionId(ctx->session, hsCtx->sessionId, &hsCtx->sessionIdSize);
81         if (ret != HITLS_SUCCESS) {
82             BSL_SAL_FREE(hsCtx->sessionId);
83             HITLS_SESS_Free(ctx->session);
84             ctx->session = NULL;
85             return ret;
86         }
87     }
88 
89     return HITLS_SUCCESS;
90 }
91 #endif /* HITLS_TLS_FEATURE_SESSION */
ClientChangeStateAfterSendClientHello(TLS_Ctx * ctx)92 static int32_t ClientChangeStateAfterSendClientHello(TLS_Ctx *ctx)
93 {
94 #if defined(HITLS_TLS_PROTO_DTLS12) && defined(HITLS_BSL_UIO_UDP)
95     int32_t ret = HS_StartTimer(ctx);
96     if (ret != HITLS_SUCCESS) {
97         return ret;
98     }
99 #endif
100 #ifdef HITLS_TLS_FEATURE_SESSION
101     if (ctx->session != NULL && IS_SUPPORT_DATAGRAM(ctx->config.tlsConfig.originVersionMask)) {
102         /* In the DTLS scenario, enable the receiving of CCS messages to prevent CCS message disorder during session
103          * resumption */
104         ctx->method.ctrlCCS(ctx, CCS_CMD_RECV_READY);
105     }
106 #endif /* HITLS_TLS_FEATURE_SESSION */
107     /* TLS and DTLS over SCTP do not need to process the hello_verify_request message */
108     return HS_ChangeState(ctx, TRY_RECV_SERVER_HELLO);
109 }
110 
ClientSendClientHelloProcess(TLS_Ctx * ctx)111 int32_t ClientSendClientHelloProcess(TLS_Ctx *ctx)
112 {
113     int32_t ret = HITLS_SUCCESS;
114     /* Obtain client information */
115     HS_Ctx *hsCtx = (HS_Ctx *)ctx->hsCtx;
116 
117     /* Determine whether the message needs to be packed */
118     if (hsCtx->msgLen == 0) {
119         /* If HelloVerifyRequest is used, the initial ClientHello and
120            HelloVerifyRequest are not included in the calculation of the
121            handshake_messages (for the CertificateVerify message) and
122            verify_data (for the Finished message). */
123         ret = VERIFY_Init(hsCtx);
124         if (ret != HITLS_SUCCESS) {
125             BSL_LOG_BINLOG_FIXLEN(BINLOG_ID17107, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN,
126                 "VERIFY_Init fail", 0, 0, 0, 0);
127             return ret;
128         }
129 
130         /* 1. For DTLS, the Hello Verify Request message may be received. If the Client Hello message is sent for the
131          * second time, the random and session of the previous session can be used directly. If the value of cookieSize
132          * is not 0, the Hello Verify Request message is received.
133          * 2. In the renegotiation state, the random and session need to be obtained again */
134         if ((ctx->negotiatedInfo.cookieSize == 0) || (ctx->negotiatedInfo.isRenegotiation)) {
135 #ifdef HITLS_TLS_FEATURE_SESSION
136             ret = ClientPrepareSession(ctx);
137             if (ret != HITLS_SUCCESS) {
138                 return ret;
139             }
140 #endif /* HITLS_TLS_FEATURE_SESSION */
141             ret = SAL_CRYPT_Rand(LIBCTX_FROM_CTX(ctx), hsCtx->clientRandom, HS_RANDOM_SIZE);
142             if (ret != HITLS_SUCCESS) {
143                 BSL_LOG_BINLOG_FIXLEN(BINLOG_ID15625, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN,
144                     "generate random value fail.", 0, 0, 0, 0);
145                 return ret;
146             }
147         }
148 
149         ctx->negotiatedInfo.clientVersion = ctx->config.tlsConfig.maxVersion;
150         ret = HS_PackMsg(ctx, CLIENT_HELLO, hsCtx->msgBuf, hsCtx->bufferLen, &hsCtx->msgLen);
151         if (ret != HITLS_SUCCESS) {
152             BSL_LOG_BINLOG_FIXLEN(BINLOG_ID15626, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN,
153                 "pack client hello fail.", 0, 0, 0, 0);
154             return ret;
155         }
156     }
157 
158     ret = HS_SendMsg(ctx);
159     if (ret != HITLS_SUCCESS) {
160         return ret;
161     }
162 
163     BSL_LOG_BINLOG_FIXLEN(BINLOG_ID15627, BSL_LOG_LEVEL_INFO, BSL_LOG_BINLOG_TYPE_RUN,
164         "send client hello success.", 0, 0, 0, 0);
165 
166     return ClientChangeStateAfterSendClientHello(ctx);
167 }
168 #endif /* HITLS_TLS_PROTO_TLS_BASIC || HITLS_TLS_PROTO_DTLS12 */
169 
170 #ifdef HITLS_TLS_PROTO_TLS13
Tls13SelectGroup(TLS_Ctx * ctx,uint16_t * firstGroup,uint16_t * secondGroup)171 static bool Tls13SelectGroup(TLS_Ctx *ctx, uint16_t *firstGroup, uint16_t *secondGroup)
172 {
173     TLS_Config *tlsConfig = &ctx->config.tlsConfig;
174     uint16_t version = (ctx->negotiatedInfo.version == 0) ?
175         ctx->config.tlsConfig.maxVersion : ctx->negotiatedInfo.version;
176     bool isFirstGroupKem = false;
177     uint16_t group1 = HITLS_NAMED_GROUP_BUTT;
178     uint16_t group2 = HITLS_NAMED_GROUP_BUTT;
179     for (uint32_t i = 0; i < tlsConfig->groupsSize; ++i) {
180         const TLS_GroupInfo *groupInfo = ConfigGetGroupInfo(&ctx->config.tlsConfig, tlsConfig->groups[i]);
181         if (groupInfo == NULL) {
182             continue;
183         }
184         if (GroupConformToVersion(ctx, version, tlsConfig->groups[i])) {
185             if (group1 == HITLS_NAMED_GROUP_BUTT) {
186                 group1 = tlsConfig->groups[i];
187                 isFirstGroupKem = groupInfo->isKem;
188                 continue;
189             /* Prepare one KEM and one KEX keyshare */
190             } else if (isFirstGroupKem != groupInfo->isKem) {
191                 group2 = tlsConfig->groups[i];
192                 break;
193             }
194         }
195     }
196     if (group1 == HITLS_NAMED_GROUP_BUTT) {
197         return false;
198     }
199     *firstGroup = group1;
200     *secondGroup = group2;
201     return true;
202 }
203 
Tls13ClientGenKeyPair(TLS_Ctx * ctx,KeyExchCtx * kxCtx,uint16_t firstGroup,uint16_t secondGroup)204 static int32_t Tls13ClientGenKeyPair(TLS_Ctx *ctx, KeyExchCtx *kxCtx, uint16_t firstGroup, uint16_t secondGroup)
205 {
206     HITLS_ECParameters curveParams = {
207         .type = HITLS_EC_CURVE_TYPE_NAMED_CURVE,
208         .param.namedcurve = firstGroup,
209     };
210 
211     // ecdhe and dhe groups can invoke the same interface to generate keys.
212     HITLS_CRYPT_Key *key = SAL_CRYPT_GenEcdhKeyPair(ctx, &curveParams);
213     if (key == NULL) {
214         BSL_ERR_PUSH_ERROR(HITLS_CRYPT_ERR_ENCODE_ECDH_KEY);
215         BSL_LOG_BINLOG_FIXLEN(BINLOG_ID15629, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN,
216             "server generate key share key pair error.", 0, 0, 0, 0);
217         return HITLS_CRYPT_ERR_ENCODE_ECDH_KEY;
218     }
219     if (kxCtx->key != NULL) {
220         SAL_CRYPT_FreeEcdhKey(kxCtx->key);
221     }
222     kxCtx->key = key;
223     if (kxCtx->secondKey != NULL) {
224         SAL_CRYPT_FreeEcdhKey(kxCtx->secondKey);
225         kxCtx->secondKey = NULL;
226     }
227     if (secondGroup != HITLS_NAMED_GROUP_BUTT) {
228         curveParams.param.namedcurve = secondGroup;
229         HITLS_CRYPT_Key *secondKey = SAL_CRYPT_GenEcdhKeyPair(ctx, &curveParams);
230         if (secondKey == NULL) {
231             BSL_ERR_PUSH_ERROR(HITLS_CRYPT_ERR_ENCODE_ECDH_KEY);
232             BSL_LOG_BINLOG_FIXLEN(BINLOG_ID15629, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN,
233                 "server generate key share key pair error.", 0, 0, 0, 0);
234             return HITLS_CRYPT_ERR_ENCODE_ECDH_KEY;
235         }
236         kxCtx->secondKey = secondKey;
237     }
238     return HITLS_SUCCESS;
239 }
240 
Tls13ClientPrepareKeyShare(TLS_Ctx * ctx,uint32_t tls13BasicKeyExMode)241 static int32_t Tls13ClientPrepareKeyShare(TLS_Ctx *ctx, uint32_t tls13BasicKeyExMode)
242 {
243     TLS_Config *tlsConfig = &ctx->config.tlsConfig;
244     // Certificate authentication and PSK with DHE authentication require key share
245     uint32_t needKeyShareMode = TLS13_KE_MODE_PSK_WITH_DHE | TLS13_CERT_AUTH_WITH_DHE;
246     if ((tls13BasicKeyExMode & needKeyShareMode) == 0) {
247         return HITLS_SUCCESS;
248     }
249 
250     if (tlsConfig->groups == NULL) {
251         BSL_ERR_PUSH_ERROR(HITLS_INTERNAL_EXCEPTION);
252         BSL_LOG_BINLOG_FIXLEN(BINLOG_ID15628, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN,
253             "tlsConfig->groups is null when prepare key share.", 0, 0, 0, 0);
254         return HITLS_INTERNAL_EXCEPTION;
255     }
256 
257     uint16_t firstGroup = HITLS_NAMED_GROUP_BUTT;
258     uint16_t secondGroup = HITLS_NAMED_GROUP_BUTT;
259     /* The keyShare has passed the verification when receiving the HRR */
260     KeyShareParam *share = &ctx->hsCtx->kxCtx->keyExchParam.share;
261     if (ctx->hsCtx->haveHrr) {
262         /* If the value of group is not updated in the hello retry request, the system directly returns */
263         if (share->group == ctx->negotiatedInfo.negotiatedGroup ||
264             share->secondGroup == ctx->negotiatedInfo.negotiatedGroup) {
265             return HITLS_SUCCESS;
266         }
267 
268         /* If the value of group is updated, use the updated group */
269         firstGroup = ctx->negotiatedInfo.negotiatedGroup;
270         secondGroup = HITLS_NAMED_GROUP_BUTT;
271     } else {
272         if (!Tls13SelectGroup(ctx, &firstGroup, &secondGroup)) {
273             BSL_LOG_BINLOG_FIXLEN(BINLOG_ID17109, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN,
274                 "SelectGroup fail", 0, 0, 0, 0);
275             return HITLS_MSG_HANDLE_ILLEGAL_SELECTED_GROUP;
276         }
277         /* Send the client hello message for the first time and fill in the group in the key share extension */
278     }
279     share->group = firstGroup;
280     share->secondGroup = secondGroup;
281     return Tls13ClientGenKeyPair(ctx, ctx->hsCtx->kxCtx, firstGroup, secondGroup);
282 }
283 
Tls13ClientPrepareSession(TLS_Ctx * ctx)284 static int32_t Tls13ClientPrepareSession(TLS_Ctx *ctx)
285 {
286     int32_t ret = HITLS_SUCCESS;
287     HS_Ctx *hsCtx = (HS_Ctx *)ctx->hsCtx;
288 
289     hsCtx->sessionId = (uint8_t *)BSL_SAL_Calloc(1u, HITLS_SESSION_ID_MAX_SIZE);
290     if (hsCtx->sessionId == NULL) {
291         BSL_ERR_PUSH_ERROR(HITLS_MEMALLOC_FAIL);
292         BSL_LOG_BINLOG_FIXLEN(BINLOG_ID15630, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN,
293             "session Id malloc fail.", 0, 0, 0, 0);
294         return HITLS_MEMALLOC_FAIL;
295     }
296     ret = SAL_CRYPT_Rand(LIBCTX_FROM_CTX(ctx), hsCtx->sessionId, HITLS_SESSION_ID_MAX_SIZE);
297     if (ret != HITLS_SUCCESS) {
298         BSL_SAL_FREE(hsCtx->sessionId);
299         BSL_LOG_BINLOG_FIXLEN(BINLOG_ID15631, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN,
300             "generate random session Id fail.", 0, 0, 0, 0);
301         return ret;
302     }
303     hsCtx->sessionIdSize = HITLS_SESSION_ID_MAX_SIZE;
304 
305     return HITLS_SUCCESS;
306 }
307 
CreatePskSession(TLS_Ctx * ctx,uint8_t * id,uint32_t idLen,HITLS_Session ** pskSession)308 int32_t CreatePskSession(TLS_Ctx *ctx, uint8_t *id, uint32_t idLen, HITLS_Session **pskSession)
309 {
310     if (ctx == NULL || pskSession == NULL) {
311         BSL_LOG_BINLOG_FIXLEN(BINLOG_ID17110, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "input null", 0, 0, 0, 0);
312         return HITLS_NULL_INPUT;
313     }
314 
315     if (ctx->config.tlsConfig.pskClientCb == NULL) {
316         return HITLS_SUCCESS;
317     }
318 
319     uint8_t psk[HS_PSK_MAX_LEN] = {0};
320     uint32_t pskLen = ctx->config.tlsConfig.pskClientCb(ctx, NULL, id, idLen, psk, HS_PSK_MAX_LEN);
321     if (pskLen == 0) {
322         return HITLS_SUCCESS;
323     }
324     if (pskLen > HS_PSK_MAX_LEN) {
325         BSL_LOG_BINLOG_FIXLEN(BINLOG_ID17111, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "pskLen err", 0, 0, 0, 0);
326         memset_s(psk, HS_PSK_MAX_LEN, 0, HS_PSK_MAX_LEN);
327         return HITLS_MSG_HANDLE_ILLEGAL_PSK_LEN;
328     }
329 
330     HITLS_Session *sess = HITLS_SESS_New();
331     if (sess == NULL) {
332         BSL_LOG_BINLOG_FIXLEN(BINLOG_ID17112, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "sess new fail", 0, 0, 0, 0);
333         memset_s(psk, HS_PSK_MAX_LEN, 0, HS_PSK_MAX_LEN);
334         return HITLS_MEMALLOC_FAIL;
335     }
336 
337     HITLS_SESS_SetMasterKey(sess, psk, pskLen);
338     HITLS_SESS_SetCipherSuite(sess, HITLS_AES_128_GCM_SHA256);
339     HITLS_SESS_SetProtocolVersion(sess, HITLS_VERSION_TLS13);
340     *pskSession = sess;
341     memset_s(psk, HS_PSK_MAX_LEN, 0, HS_PSK_MAX_LEN);
342     return HITLS_SUCCESS;
343 }
344 
IsTls13SessionValid(HITLS_HashAlgo hashAlgo,HITLS_Session * session,uint16_t * tls13CipherSuites,uint32_t tls13cipherSuitesSize)345 static bool IsTls13SessionValid(HITLS_HashAlgo hashAlgo, HITLS_Session* session, uint16_t *tls13CipherSuites,
346     uint32_t tls13cipherSuitesSize)
347 {
348     uint16_t version = 0;
349     HITLS_SESS_GetProtocolVersion(session, &version);
350     if (version != HITLS_VERSION_TLS13) {
351         return false;
352     }
353     uint16_t cipherSuite = 0;
354     CipherSuiteInfo cipherInfo = {0};
355     (void)HITLS_SESS_GetCipherSuite(session, &cipherSuite); // only null input cause error
356     int32_t ret = CFG_GetCipherSuiteInfo(cipherSuite, &cipherInfo);
357     if (ret != HITLS_SUCCESS) {
358         BSL_LOG_BINLOG_FIXLEN(BINLOG_ID17113, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN,
359             "GetCipherSuiteInfo fail", 0, 0, 0, 0);
360         return false;
361     }
362     if (hashAlgo != HITLS_HASH_BUTT) {
363         return (hashAlgo == cipherInfo.hashAlg);
364     }
365     if (tls13CipherSuites != NULL) {
366         for (uint32_t i = 0; i < tls13cipherSuitesSize; i++) {
367             CipherSuiteInfo configCipher = {0};
368             ret = CFG_GetCipherSuiteInfo(tls13CipherSuites[i], &configCipher);
369             if (ret == HITLS_SUCCESS && configCipher.hashAlg == cipherInfo.hashAlg) {
370                 return true;
371             }
372         }
373     }
374     return false;
375 }
376 
ConstructUserPsk(HITLS_Session * sessoin,const uint8_t * identity,uint32_t identityLen,uint8_t curIndex)377 static UserPskList *ConstructUserPsk(HITLS_Session *sessoin, const uint8_t *identity, uint32_t identityLen,
378     uint8_t curIndex)
379 {
380     if (identityLen > HS_PSK_IDENTITY_MAX_LEN || sessoin == NULL) {
381         BSL_LOG_BINLOG_FIXLEN(BINLOG_ID17114, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN,
382             "identityLen err or sessoin NULL", 0, 0, 0, 0);
383         return NULL;
384     }
385     UserPskList *userPsk = BSL_SAL_Calloc(1, sizeof(UserPskList));
386     if (userPsk == NULL) {
387         BSL_LOG_BINLOG_FIXLEN(BINLOG_ID17115, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "Calloc fail", 0, 0, 0, 0);
388         return NULL;
389     }
390     userPsk->pskSession = HITLS_SESS_Dup(sessoin);
391     userPsk->identity = BSL_SAL_Calloc(1, identityLen);
392     if (userPsk->identity == NULL) {
393         BSL_LOG_BINLOG_FIXLEN(BINLOG_ID17116, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "Calloc fail", 0, 0, 0, 0);
394         BSL_SAL_FREE(userPsk);
395         return NULL;
396     }
397     (void)memcpy_s(userPsk->identity, identityLen, identity, identityLen);
398     userPsk->identityLen = identityLen;
399     userPsk->num = curIndex;
400     return userPsk;
401 }
402 
Tls13ClientPreparePSK(TLS_Ctx * ctx)403 static int32_t Tls13ClientPreparePSK(TLS_Ctx *ctx)
404 {
405     int32_t ret = 0;
406     HS_Ctx *hsCtx = ctx->hsCtx;
407     HITLS_HashAlgo hashAlgo = hsCtx->haveHrr ? ctx->negotiatedInfo.cipherSuiteInfo.hashAlg : HITLS_HASH_BUTT;
408     uint8_t identity[HS_PSK_IDENTITY_MAX_LEN + 1] = {0};
409     const uint8_t *id = NULL;
410     uint32_t idLen = 0;
411     HITLS_Session *pskSession = NULL;
412     UserPskList *userPsk = NULL;
413 
414     /* Obtain the resume psk information from the session */
415     HITLS_SESS_Free(hsCtx->kxCtx->pskInfo13.resumeSession);
416     hsCtx->kxCtx->pskInfo13.resumeSession = NULL;
417     if (HITLS_SESS_HasTicket(ctx->session) &&
418         IsTls13SessionValid(hashAlgo, ctx->session, ctx->config.tlsConfig.tls13CipherSuites,
419                             ctx->config.tlsConfig.tls13cipherSuitesSize) &&
420         SESS_CheckValidity(ctx->session, (uint64_t)BSL_SAL_CurrentSysTimeGet())) {
421         hsCtx->kxCtx->pskInfo13.resumeSession = HITLS_SESS_Dup(ctx->session);
422     }
423 
424     uint8_t index = (hsCtx->kxCtx->pskInfo13.resumeSession == NULL) ? 0 : 1;
425     if (ctx->config.tlsConfig.pskUseSessionCb != NULL) {
426         ret = ctx->config.tlsConfig.pskUseSessionCb(ctx, hashAlgo, &id, &idLen, &pskSession);
427         if (ret != HITLS_PSK_USE_SESSION_CB_SUCCESS) {
428             BSL_LOG_BINLOG_FIXLEN(BINLOG_ID17117, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN,
429                 "pskUseSessionCb fail, ret %d", ret, 0, 0, 0);
430             return HITLS_MSG_HANDLE_PSK_USE_SESSION_FAIL;
431         }
432     }
433 
434     if (pskSession == NULL) {
435         // use 1.2 psk callback default hashalgo == sha256
436         ret = CreatePskSession(ctx, identity, HS_PSK_IDENTITY_MAX_LEN, &pskSession);
437         if (ret != HITLS_SUCCESS) {
438             return ret;
439         }
440         id = identity;
441         idLen = (uint32_t)strlen((char *)identity);
442     }
443 
444     if (pskSession != NULL && IsTls13SessionValid(hashAlgo, pskSession, ctx->config.tlsConfig.tls13CipherSuites,
445                                                   ctx->config.tlsConfig.tls13cipherSuitesSize)) {
446         userPsk = ConstructUserPsk(pskSession, id, idLen, index);
447     }
448     HITLS_SESS_Free(pskSession);
449     pskSession = NULL;
450 
451     if (ctx->hsCtx->kxCtx->pskInfo13.userPskSess != NULL) {
452         BSL_SAL_FREE(ctx->hsCtx->kxCtx->pskInfo13.userPskSess->identity);
453         HITLS_SESS_Free(ctx->hsCtx->kxCtx->pskInfo13.userPskSess->pskSession);
454         BSL_SAL_FREE(ctx->hsCtx->kxCtx->pskInfo13.userPskSess);
455     }
456     ctx->hsCtx->kxCtx->pskInfo13.userPskSess = userPsk;
457     return HITLS_SUCCESS;
458 }
459 
Tls13ClientHelloPrepare(TLS_Ctx * ctx)460 int32_t Tls13ClientHelloPrepare(TLS_Ctx *ctx)
461 {
462     int32_t ret = HITLS_SUCCESS;
463     HS_Ctx *hsCtx = ctx->hsCtx;
464     /* After receiving the hello retry request message, the client needs to send the second clientHello. In this case,
465      * the following initialization is not required */
466     if (hsCtx->haveHrr == false) {
467         ret = VERIFY_Init(hsCtx);
468         if (ret != HITLS_SUCCESS) {
469             return RETURN_ERROR_NUMBER_PROCESS(ret, BINLOG_ID17118, "VERIFY_Init fail");
470         }
471 
472         ret = SAL_CRYPT_Rand(LIBCTX_FROM_CTX(ctx), hsCtx->clientRandom, HS_RANDOM_SIZE);
473         if (ret != HITLS_SUCCESS) {
474             return RETURN_ERROR_NUMBER_PROCESS(ret, BINLOG_ID15632, "generate random value fail");
475         }
476 
477         /* In section 4.1.2 of RFC8446, a random session ID is required in middlebox mode. In nomiddlebox mode, the
478          * session ID is empty */
479         ret = Tls13ClientPrepareSession(ctx);
480         if (ret != HITLS_SUCCESS) {
481             return ret;
482         }
483     } else {
484         /* If the middlebox is used, a CCS message must be sent before the second clientHello message is sent */
485         ret = ctx->method.sendCCS(ctx);
486         if (ret != HITLS_SUCCESS) {
487             return ret;
488         }
489     }
490     ret = Tls13ClientPreparePSK(ctx);
491     if (ret != HITLS_SUCCESS) {
492         ctx->method.sendAlert(ctx, ALERT_LEVEL_FATAL, ALERT_INTERNAL_ERROR);
493         return ret;
494     }
495 
496     uint32_t tls13BasicKeyExMode = 0;
497     PskInfo13 *pskInfo = &ctx->hsCtx->kxCtx->pskInfo13;
498     if (pskInfo->resumeSession != NULL || pskInfo->userPskSess != NULL) {
499         tls13BasicKeyExMode |= ctx->config.tlsConfig.keyExchMode; // keyExchMode must not be 0
500     }
501 
502     if (ctx->config.tlsConfig.signAlgorithmsSize != 0) { // base cert auth
503         tls13BasicKeyExMode |= TLS13_CERT_AUTH_WITH_DHE;
504     }
505 
506     /* Prepare the key share extension. The keyshares in two clientHello messages are different. Therefore,
507      * both the keyshares must be prepared */
508     ret = Tls13ClientPrepareKeyShare(ctx, tls13BasicKeyExMode);
509     if (ret != HITLS_SUCCESS) {
510         ctx->method.sendAlert(ctx, ALERT_LEVEL_FATAL, ALERT_INTERNAL_ERROR);
511         return ret;
512     }
513 
514     if (tls13BasicKeyExMode == 0) {
515         return RETURN_ERROR_NUMBER_PROCESS(HITLS_CONFIG_INVALID_SET, BINLOG_ID16140,
516             "tls config err: can not decide tls13BasicKeyExMode");
517     }
518     ctx->negotiatedInfo.tls13BasicKeyExMode = tls13BasicKeyExMode;
519 
520     return HITLS_SUCCESS;
521 }
522 
GetBindersOffset(const TLS_Ctx * ctx)523 static uint32_t GetBindersOffset(const TLS_Ctx *ctx)
524 {
525     uint32_t ret = sizeof(uint16_t);
526     PskInfo13 *pskInfo = &ctx->hsCtx->kxCtx->pskInfo13;
527     uint32_t binderLen = 0;
528     if (pskInfo->resumeSession != NULL) {
529         HITLS_HashAlgo hashAlg = HITLS_HASH_BUTT;
530         binderLen = HS_GetBinderLen(pskInfo->resumeSession, &hashAlg);  // Success guaranteed by the context
531         ret += binderLen + sizeof(uint8_t);
532     }
533     if (pskInfo->userPskSess != NULL) {
534         HITLS_HashAlgo hashAlg = HITLS_HASH_BUTT;
535         binderLen = HS_GetBinderLen(pskInfo->userPskSess->pskSession, &hashAlg);  // Success guaranteed by the context
536         ret += binderLen + sizeof(uint8_t);
537     }
538     return ret;
539 }
540 
PackClientPreSharedKeyBinders(const TLS_Ctx * ctx,uint8_t * buf,uint32_t bufLen)541 static int32_t PackClientPreSharedKeyBinders(const TLS_Ctx *ctx, uint8_t *buf, uint32_t bufLen)
542 {
543     uint32_t trucatedLen = (bufLen - GetBindersOffset(ctx));
544     buf = buf + trucatedLen;
545     PskInfo13 *pskInfo = &ctx->hsCtx->kxCtx->pskInfo13;
546     uint32_t offset = sizeof(uint16_t); // skip binders len
547     uint8_t psk[HS_PSK_MAX_LEN] = {0};
548     uint32_t pskLen = HS_PSK_MAX_LEN;
549     uint32_t binderLen = 0;
550     int32_t ret = HITLS_SUCCESS;
551     if (pskInfo->resumeSession != NULL) {
552         HITLS_HashAlgo hashAlg = HITLS_HASH_BUTT;
553         binderLen = HS_GetBinderLen(pskInfo->resumeSession, &hashAlg);  // Success guaranteed by the context
554         buf[offset] = binderLen;
555         offset++;
556         ret = HITLS_SESS_GetMasterKey(pskInfo->resumeSession, psk, &pskLen);
557         if (ret != HITLS_SUCCESS) {
558             return ret;
559         }
560         ret = VERIFY_CalcPskBinder(ctx, hashAlg, false, psk, pskLen,
561             ctx->hsCtx->msgBuf, trucatedLen, &buf[offset], binderLen);
562         BSL_SAL_CleanseData(psk, HS_PSK_MAX_LEN);
563         if (ret != HITLS_SUCCESS) {
564             return ret;
565         }
566         offset += binderLen;
567     }
568 
569     if (pskInfo->userPskSess != NULL) {
570         HITLS_HashAlgo hashAlg = HITLS_HASH_BUTT;
571         pskLen = HS_PSK_MAX_LEN;
572         binderLen = HS_GetBinderLen(pskInfo->userPskSess->pskSession, &hashAlg);  // context is guaranteed to succeed
573         buf[offset] = (uint8_t)binderLen;
574         offset++;
575         ret = HITLS_SESS_GetMasterKey(pskInfo->userPskSess->pskSession, psk, &pskLen);
576         if (ret != HITLS_SUCCESS) {
577             return ret;
578         }
579         ret = VERIFY_CalcPskBinder(ctx, hashAlg, true, psk, pskLen,
580             ctx->hsCtx->msgBuf, trucatedLen, &buf[offset], binderLen);
581         BSL_SAL_CleanseData(psk, HS_PSK_MAX_LEN);
582         if (ret != HITLS_SUCCESS) {
583             return ret;
584         }
585         offset += binderLen;
586     }
587 
588     BSL_Uint16ToByte((uint16_t)(offset - sizeof(uint16_t)), &buf[0]); // pack binder len
589     return HITLS_SUCCESS;
590 }
591 
Tls13ClientSendClientHelloProcess(TLS_Ctx * ctx)592 int32_t Tls13ClientSendClientHelloProcess(TLS_Ctx *ctx)
593 {
594     int32_t ret = HITLS_SUCCESS;
595     HS_Ctx *hsCtx = ctx->hsCtx;
596 
597     /* Determine whether the message needs to be packed */
598     if (hsCtx->msgLen == 0) {
599         ret = Tls13ClientHelloPrepare(ctx);
600         if (ret != HITLS_SUCCESS) {
601             return ret;
602         }
603 
604         ctx->negotiatedInfo.clientVersion = HITLS_VERSION_TLS12;
605         /* The packed message is placed in the hsCtx->msgBuf. The length of the packed message is hsCtx->msgLen,
606          * including the CH message header and body */
607         ret = HS_PackMsg(ctx, CLIENT_HELLO, hsCtx->msgBuf, hsCtx->bufferLen, &hsCtx->msgLen);
608         if (ret != HITLS_SUCCESS) {
609             BSL_LOG_BINLOG_FIXLEN(BINLOG_ID15633, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN,
610                 "pack tls1.3 client hello fail.", 0, 0, 0, 0);
611             return ret;
612         }
613 
614         if (hsCtx->extFlag.havePreShareKey == true) {
615             /* Calculate the binder */
616             ret = PackClientPreSharedKeyBinders(ctx, hsCtx->msgBuf, hsCtx->msgLen);
617             if (ret != HITLS_SUCCESS) {
618                 return ret;
619             }
620         }
621 #ifdef HITLS_TLS_FEATURE_PHA
622         if (hsCtx->extFlag.havePostHsAuth && ctx->phaState == PHA_NONE) {
623             ctx->phaState = PHA_EXTENSION;
624         }
625 #endif /* HITLS_TLS_FEATURE_PHA */
626     }
627 
628     if (!ctx->method.isRecvCCS(ctx)) {
629         /* Unencrypted CCS can be received after the first ClientHello is sent or received according to RFC 8446 */
630         ctx->method.ctrlCCS(ctx, CCS_CMD_RECV_READY);
631     }
632 
633     ret = HS_SendMsg(ctx);
634     if (ret != HITLS_SUCCESS) {
635         return ret;
636     }
637 
638     BSL_LOG_BINLOG_FIXLEN(BINLOG_ID15634, BSL_LOG_LEVEL_INFO, BSL_LOG_BINLOG_TYPE_RUN,
639         "send tls1.3 client hello success.", 0, 0, 0, 0);
640 
641     return HS_ChangeState(ctx, TRY_RECV_SERVER_HELLO);
642 }
643 #endif /* HITLS_TLS_PROTO_TLS13 */
644 #endif /* HITLS_TLS_HOST_CLIENT */