• 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_SERVER
17 #include "securec.h"
18 #include "tls_binlog_id.h"
19 #include "bsl_log_internal.h"
20 #include "bsl_log.h"
21 #include "bsl_sal.h"
22 #include "bsl_err_internal.h"
23 #include "hitls.h"
24 #include "hitls_error.h"
25 #include "hitls_sni.h"
26 #include "hitls_alpn.h"
27 #include "hitls_security.h"
28 #include "bsl_uio.h"
29 #include "alert.h"
30 #include "session_mgr.h"
31 #ifdef HITLS_TLS_FEATURE_SECURITY
32 #include "security.h"
33 #endif
34 #include "sni.h"
35 #include "hs_ctx.h"
36 #include "hs.h"
37 #include "hs_common.h"
38 #include "hs_extensions.h"
39 #include "hs_verify.h"
40 #include "cert_mgr_ctx.h"
41 #include "record.h"
42 #include "hs_cookie.h"
43 #ifdef HITLS_TLS_PROTO_TLS13
44 #if defined(HITLS_TLS_FEATURE_SESSION) || defined(HITLS_TLS_FEATURE_PSK)
45 #define HS_MAX_BINDER_SIZE 64
46 #endif
47 #endif
48 #ifdef HITLS_TLS_PROTO_DTLS12
49 #define COOKIE_GEN_SUCCESS    1
50 #define COOKIE_GEN_ERROR      0
51 #define COOKIE_VERIFY_SUCCESS 1
52 #define COOKIE_VERIFY_ERROR   0
53 #endif
54 #ifdef HITLS_TLS_SUITE_KX_ECDHE
55 /**
56 * @brief Check the extension of the client hello point format.
57 *
58 * @param clientHello [IN] client hello packet
59 *
60 * @retval HITLS_SUCCESS succeeded.
61 * @retval HITLS_MSG_HANDLE_UNSUPPORT_POINT_FORMAT Unsupported point format
62 */
ServerCheckPointFormats(const ClientHelloMsg * clientHello)63 static int32_t ServerCheckPointFormats(const ClientHelloMsg *clientHello)
64 {
65     /* Point format extension not received */
66     if (!clientHello->extension.flag.havePointFormats) {
67         return HITLS_SUCCESS;
68     }
69     /* Traverse the list of point formats */
70     for (uint32_t i = 0u; i < clientHello->extension.content.pointFormatsSize; i++) {
71         /* The point format list contains uncompressed (0) */
72         if (clientHello->extension.content.pointFormats[i] == 0u) {
73             return HITLS_SUCCESS;
74         }
75     }
76 
77     BSL_ERR_PUSH_ERROR(HITLS_MSG_HANDLE_UNSUPPORT_POINT_FORMAT);
78     BSL_LOG_BINLOG_FIXLEN(BINLOG_ID15210, BSL_LOG_LEVEL_INFO, BSL_LOG_BINLOG_TYPE_RUN,
79         "the point format extension in client hello is unsupported.", 0, 0, 0, 0);
80     return HITLS_MSG_HANDLE_UNSUPPORT_POINT_FORMAT;
81 }
82 
FindSupportedCurves(const TLS_Ctx * ctx,const uint16_t * perferenceGroups,uint32_t index)83 static uint16_t FindSupportedCurves(const TLS_Ctx *ctx, const uint16_t *perferenceGroups, uint32_t index)
84 {
85     /* Support group security check */
86 #ifdef HITLS_TLS_FEATURE_SECURITY
87     int32_t id = (int32_t)perferenceGroups[index];
88     int32_t ret = SECURITY_SslCheck(ctx, HITLS_SECURITY_SECOP_CURVE_SHARED, 0, id, NULL);
89     if (ret != SECURITY_SUCCESS || !GroupConformToVersion(ctx, ctx->negotiatedInfo.version, perferenceGroups[index])) {
90 #else
91     if (!GroupConformToVersion(ctx, ctx->negotiatedInfo.version, perferenceGroups[index])) {
92 #endif /* HITLS_TLS_FEATURE_SECURITY */
93         return 0;
94     }
95 
96     return perferenceGroups[index];
97 }
98 
99 /**
100 * @brief Select elliptic curve
101 *
102 * @param ctx [IN] TLS context
103 * @param clientHello [IN] Client Hello packet
104 *
105 * @return Return curveID. If the value is 0, the supported curve is not found.
106 */
107 static uint16_t ServerSelectCurveId(const TLS_Ctx *ctx, const ClientHelloMsg *clientHello)
108 {
109     uint32_t perferenceGroupsSize = 0;
110     uint32_t normalGroupsSize = 0;
111     uint16_t *perferenceGroups = NULL;
112     uint16_t *normalGroups = NULL;
113     if (ctx->config.tlsConfig.isSupportServerPreference) {
114         perferenceGroupsSize = ctx->config.tlsConfig.groupsSize;
115         normalGroupsSize = clientHello->extension.content.supportedGroupsSize;
116         perferenceGroups = ctx->config.tlsConfig.groups;
117         normalGroups = clientHello->extension.content.supportedGroups;
118     } else {
119         perferenceGroupsSize = clientHello->extension.content.supportedGroupsSize;
120         normalGroupsSize = ctx->config.tlsConfig.groupsSize;
121         perferenceGroups = clientHello->extension.content.supportedGroups;
122         normalGroups = ctx->config.tlsConfig.groups;
123     }
124 
125     /* Find supported curves */
126     for (uint32_t i = 0u; i < perferenceGroupsSize; i++) {
127         for (uint32_t j = 0u; j < normalGroupsSize; j++) {
128             if (perferenceGroups[i] != normalGroups[j]) {
129                 continue;
130             }
131             uint16_t curve = FindSupportedCurves(ctx, perferenceGroups, i);
132             if (curve == 0) {
133                 continue;
134             }
135             return curve;
136         }
137     }
138 
139     BSL_ERR_PUSH_ERROR(HITLS_MSG_HANDLE_UNSUPPORT_NAMED_CURVE);
140     BSL_LOG_BINLOG_FIXLEN(BINLOG_ID15211, BSL_LOG_LEVEL_INFO, BSL_LOG_BINLOG_TYPE_RUN,
141         "the curve id in client hello is unsupported.", 0, 0, 0, 0);
142     return 0;
143 }
144 #endif /* HITLS_TLS_SUITE_KX_ECDHE */
145 /**
146 * @brief Select a proper certificate based on the TLS cipher suite.
147 *
148 * @param ctx [IN] TLS context
149 * @param clientHello [IN] Client Hello packet
150 * @param cipherInfo [IN] TLS cipher suite
151 *
152 * @retval HITLS_SUCCESS succeeded.
153 * @retval HITLS_MEMALLOC_FAIL Memory application failed.
154 */
155 static int32_t HsServerSelectCert(TLS_Ctx *ctx, const ClientHelloMsg *clientHello, const CipherSuiteInfo *cipherInfo)
156 {
157     uint16_t signHashAlgo = cipherInfo->signScheme;
158     CERT_ExpectInfo expectCertInfo = {0};
159     expectCertInfo.certType = CFG_GetCertTypeByCipherSuite(cipherInfo->cipherSuite);
160 
161     /* For TLCP1.1, ignore the signature extension of client hello */
162     if (clientHello->extension.content.signatureAlgorithms != NULL &&
163         (ctx->negotiatedInfo.version != HITLS_VERSION_TLCP_DTLCP11)) {
164         expectCertInfo.signSchemeList = clientHello->extension.content.signatureAlgorithms;
165         expectCertInfo.signSchemeNum = clientHello->extension.content.signatureAlgorithmsSize;
166     } else {
167         expectCertInfo.signSchemeList = &signHashAlgo;
168         expectCertInfo.signSchemeNum = 1u;
169     }
170     /* The ECDSA certificate must match the supported_groups and ec_point_format extensions */
171     expectCertInfo.ellipticCurveList = clientHello->extension.content.supportedGroups;
172     expectCertInfo.ellipticCurveNum = clientHello->extension.content.supportedGroupsSize;
173     /* Only the uncompressed format is supported */
174     uint8_t pointFormat = HITLS_POINT_FORMAT_UNCOMPRESSED;
175     expectCertInfo.ecPointFormatList = &pointFormat;
176     expectCertInfo.ecPointFormatNum = 1u;
177 
178     return SAL_CERT_SelectCertByInfo(ctx, &expectCertInfo);
179 }
180 
181 #ifdef HITLS_TLS_SUITE_KX_ECDHE
182 
183 #ifdef HITLS_TLS_PROTO_TLCP11
184 static bool CheckLocalContainCurveType(const uint16_t *groups, uint32_t groupsSize, uint16_t exp)
185 {
186     for (uint32_t i = 0; i < groupsSize; ++i) {
187         if (groups[i] == exp) {
188             return true;
189         }
190     }
191     return false;
192 }
193 #endif
194 /**
195 * @brief Process the ECDHE cipher suite.
196 *
197 * @param ctx [IN] TLS context
198 * @param clientHello [IN] Client Hello packet
199 * @param cipherSuiteInfo [OUT] Cipher suite information
200 *
201 * @retval HITLS_SUCCESS succeeded.
202 * @retval HITLS_MSG_HANDLE_UNSUPPORT_CIPHER_SUITE Unsupported cipher suites
203 */
204 static int32_t ProcessEcdheCipherSuite(TLS_Ctx *ctx, const ClientHelloMsg *clientHello)
205 {
206     /* If the curve id is not set, ECDHE cannot be used. */
207     if ((ctx->config.tlsConfig.groupsSize == 0u) || (ctx->config.tlsConfig.groups == NULL)) {
208         BSL_LOG_BINLOG_FIXLEN(BINLOG_ID15212, BSL_LOG_LEVEL_INFO, BSL_LOG_BINLOG_TYPE_RUN,
209             "can not used ecdhe whitout curve id.", 0, 0, 0, 0);
210         return HITLS_MSG_HANDLE_UNSUPPORT_CIPHER_SUITE;
211     }
212 #ifdef HITLS_TLS_PROTO_TLCP11
213     if (ctx->negotiatedInfo.version == HITLS_VERSION_TLCP_DTLCP11) {
214         if (CheckLocalContainCurveType(ctx->config.tlsConfig.groups,
215             ctx->config.tlsConfig.groupsSize, HITLS_EC_GROUP_SM2) != true) {
216             BSL_LOG_BINLOG_FIXLEN(BINLOG_ID16231, BSL_LOG_LEVEL_INFO, BSL_LOG_BINLOG_TYPE_RUN,
217                 "TLCP need sm2 curve.", 0, 0, 0, 0);
218             return HITLS_MSG_HANDLE_UNSUPPORT_CIPHER_SUITE;
219         }
220         ctx->hsCtx->kxCtx->keyExchParam.ecdh.curveParams.type = HITLS_EC_CURVE_TYPE_NAMED_CURVE;
221         ctx->hsCtx->kxCtx->keyExchParam.ecdh.curveParams.param.namedcurve = HITLS_EC_GROUP_SM2;
222         return HITLS_SUCCESS; /* TLCP negotiation does not focus on extended information. */
223     }
224 #endif
225     /* Check the Point format extension of the clientHello. This extension is not included in the TLCP */
226     int32_t ret = ServerCheckPointFormats(clientHello);
227     if (ret != HITLS_SUCCESS) {
228         BSL_LOG_BINLOG_FIXLEN(BINLOG_ID15213, BSL_LOG_LEVEL_INFO, BSL_LOG_BINLOG_TYPE_RUN,
229             "server check client hello point formats fail.", 0, 0, 0, 0);
230         return HITLS_MSG_HANDLE_UNSUPPORT_CIPHER_SUITE;
231     }
232 
233     uint16_t selectedEcCurveId =
234 #ifdef HITLS_TLS_PROTO_TLS13
235         ctx->hsCtx->haveHrr ? ctx->negotiatedInfo.negotiatedGroup :
236 #endif
237         ServerSelectCurveId(ctx, clientHello);
238     if (selectedEcCurveId == 0) {
239         BSL_LOG_BINLOG_FIXLEN(BINLOG_ID15214, BSL_LOG_LEVEL_INFO, BSL_LOG_BINLOG_TYPE_RUN,
240             "server select curve id fail.", 0, 0, 0, 0);
241         return HITLS_MSG_HANDLE_UNSUPPORT_CIPHER_SUITE;
242     }
243 #ifdef HITLS_TLS_PROTO_TLS13
244     if (ctx->negotiatedInfo.version == HITLS_VERSION_TLS13) {
245         ctx->hsCtx->kxCtx->keyExchParam.share.group = selectedEcCurveId;
246     } else
247 #endif /* HITLS_TLS_PROTO_TLS13 */
248     {
249         ctx->hsCtx->kxCtx->keyExchParam.ecdh.curveParams.type = HITLS_EC_CURVE_TYPE_NAMED_CURVE;
250         ctx->hsCtx->kxCtx->keyExchParam.ecdh.curveParams.param.namedcurve = selectedEcCurveId;
251     }
252 
253     ctx->negotiatedInfo.negotiatedGroup = selectedEcCurveId;
254     return HITLS_SUCCESS;
255 }
256 #endif /* HITLS_TLS_SUITE_KX_ECDHE */
257 /**
258 * @brief Check whether the server supports the cipher suite.
259 *
260 * @param ctx [IN] TLS context
261 * @param clientHello [IN] client hello packet
262 * @param cipher [IN] cipher suite ID
263 *
264 * @retval HITLS_SUCCESS succeeded.
265 * @retval HITLS_MEMCPY_FAIL Memory Copy Failure
266 * @retval HITLS_MSG_HANDLE_UNSUPPORT_CIPHER_SUITE Unsupported cipher suites
267 */
268 static int32_t ServerNegotiateCipher(TLS_Ctx *ctx, const ClientHelloMsg *clientHello, uint16_t cipher)
269 {
270     CipherSuiteInfo cipherSuiteInfo = {0};
271     int32_t ret = 0;
272 
273     ret = CFG_GetCipherSuiteInfo(cipher, &cipherSuiteInfo);
274     if (ret != HITLS_SUCCESS) {
275         BSL_LOG_BINLOG_FIXLEN(BINLOG_ID15215, BSL_LOG_LEVEL_INFO, BSL_LOG_BINLOG_TYPE_RUN,
276             "get cipher suite info fail when processing client hello.", 0, 0, 0, 0);
277         return HITLS_MSG_HANDLE_UNSUPPORT_CIPHER_SUITE;
278     }
279 
280     /* If the key exchange algorithm is not PSK, DHE_PSK, or ECDHE_PSK, select a certificate. */
281     if (IsNeedCertPrepare(&cipherSuiteInfo) == true) {
282         if (HsServerSelectCert(ctx, clientHello, &cipherSuiteInfo) != HITLS_SUCCESS) {
283             /* No proper certificate */
284             BSL_LOG_BINLOG_FIXLEN(BINLOG_ID15216, BSL_LOG_LEVEL_INFO, BSL_LOG_BINLOG_TYPE_RUN,
285                 "have no suitable cert.", 0, 0, 0, 0);
286             return HITLS_MSG_HANDLE_ERR_NO_SERVER_CERTIFICATE;
287         }
288     }
289 
290     switch (cipherSuiteInfo.kxAlg) {
291 #ifdef HITLS_TLS_SUITE_KX_ECDHE
292         case HITLS_KEY_EXCH_ECDHE: /* the ECDHE of TLCP is also in this branch */
293         case HITLS_KEY_EXCH_ECDHE_PSK:
294             /* The ECC cipher suite needs to process the supported_groups and ec_point_formats extensions */
295             ret = ProcessEcdheCipherSuite(ctx, clientHello);
296             break;
297 #endif /* HITLS_TLS_SUITE_KX_ECDHE */
298         case HITLS_KEY_EXCH_DHE:
299         case HITLS_KEY_EXCH_DHE_PSK:
300         case HITLS_KEY_EXCH_RSA:
301 #ifdef HITLS_TLS_PROTO_TLCP11
302         case HITLS_KEY_EXCH_ECC:
303 #endif
304         case HITLS_KEY_EXCH_PSK:
305         case HITLS_KEY_EXCH_RSA_PSK:
306             ret = HITLS_SUCCESS;
307             break;
308         default:
309             ret = HITLS_MSG_HANDLE_UNSUPPORT_CIPHER_SUITE;
310     }
311     if (ret != HITLS_SUCCESS) {
312         BSL_LOG_BINLOG_FIXLEN(BINLOG_ID15217, BSL_LOG_LEVEL_INFO, BSL_LOG_BINLOG_TYPE_RUN,
313             "server process ecdhe cipher suite fail. kxAlg is %d", cipherSuiteInfo.kxAlg, 0, 0, 0);
314         return ret;
315     }
316 
317     ctx->hsCtx->kxCtx->keyExchAlgo = cipherSuiteInfo.kxAlg;
318     (void)memcpy_s(&ctx->negotiatedInfo.cipherSuiteInfo, sizeof(CipherSuiteInfo),
319                    &cipherSuiteInfo, sizeof(CipherSuiteInfo));
320     return ret;
321 }
322 #ifdef HITLS_TLS_PROTO_TLS13
323 static int32_t Tls13ServerNegotiateCipher(TLS_Ctx *ctx, const ClientHelloMsg *clientHello, uint16_t cipher)
324 {
325     (void)clientHello;
326     int32_t ret = 0;
327     CipherSuiteInfo cipherSuiteInfo = {0};
328 
329     ret = CFG_GetCipherSuiteInfo(cipher, &cipherSuiteInfo);
330     if (ret != HITLS_SUCCESS) {
331         BSL_LOG_BINLOG_FIXLEN(BINLOG_ID15218, BSL_LOG_LEVEL_INFO, BSL_LOG_BINLOG_TYPE_RUN,
332             "get cipher suite info fail when processing client hello.", 0, 0, 0, 0);
333         return HITLS_MSG_HANDLE_UNSUPPORT_CIPHER_SUITE;
334     }
335 
336     (void)memcpy_s(&ctx->negotiatedInfo.cipherSuiteInfo, sizeof(CipherSuiteInfo),
337         &cipherSuiteInfo, sizeof(CipherSuiteInfo));
338     return HITLS_SUCCESS;
339 }
340 #endif /* HITLS_TLS_PROTO_TLS13 */
341 static int32_t CheckCipherSuite(TLS_Ctx *ctx, const ClientHelloMsg *clientHello, uint16_t cipherSuite)
342 {
343     if (!IsCipherSuiteAllowed(ctx, cipherSuite)) {
344         BSL_LOG_BINLOG_FIXLEN(BINLOG_ID17046, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN,
345             "No proper cipher suite", 0, 0, 0, 0);
346         return HITLS_CONFIG_UNSUPPORT_CIPHER_SUITE;
347     }
348     int32_t ret = 0;
349 #ifdef HITLS_TLS_PROTO_TLS13
350     if (ctx->negotiatedInfo.version == HITLS_VERSION_TLS13) {
351         ret = Tls13ServerNegotiateCipher(ctx, clientHello, cipherSuite);
352     } else
353 #endif /* HITLS_TLS_PROTO_TLS13 */
354     {
355         ret = ServerNegotiateCipher(ctx, clientHello, cipherSuite);
356     }
357     if (ret != HITLS_SUCCESS) {
358         return ret;
359     }
360     /* Check the security level of ciphersuites */
361     CipherSuiteInfo *cipherSuiteInfo = &ctx->negotiatedInfo.cipherSuiteInfo;
362 #ifdef HITLS_TLS_FEATURE_SECURITY
363     ret = SECURITY_SslCheck((HITLS_Ctx *)ctx, HITLS_SECURITY_SECOP_CIPHER_SHARED, 0, 0, (void *)cipherSuiteInfo);
364     if (ret != SECURITY_SUCCESS) {
365         ctx->hsCtx->kxCtx->keyExchAlgo = HITLS_KEY_EXCH_NULL;
366         (void)memset_s(&ctx->hsCtx->kxCtx->keyExchParam, sizeof(ctx->hsCtx->kxCtx->keyExchParam),
367             0, sizeof(ctx->hsCtx->kxCtx->keyExchParam));
368         BSL_LOG_BINLOG_FIXLEN(BINLOG_ID17047, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN,
369             "SslCheck fail, ret %d", ret, 0, 0, 0);
370         BSL_ERR_PUSH_ERROR(HITLS_MSG_HANDLE_UNSECURE_CIPHER_SUITE);
371         return HITLS_MSG_HANDLE_UNSECURE_CIPHER_SUITE;
372     }
373 #endif /* HITLS_TLS_FEATURE_SECURITY */
374     BSL_LOG_BINLOG_FIXLEN(BINLOG_ID15221, BSL_LOG_LEVEL_INFO, BSL_LOG_BINLOG_TYPE_RUN, "chosen ciphersuite 0x%04x",
375         cipherSuiteInfo->cipherSuite, 0, 0, 0);
376     BSL_LOG_BINLOG_VARLEN(BINLOG_ID15894, BSL_LOG_LEVEL_INFO, BSL_LOG_BINLOG_TYPE_RUN, "chosen ciphersuite: %s",
377         cipherSuiteInfo->name);
378 
379     return HITLS_SUCCESS;
380 }
381 
382 // Select the cipher suite.
383 int32_t ServerSelectCipherSuite(TLS_Ctx *ctx, const ClientHelloMsg *clientHello)
384 {
385     /* Obtain server information */
386     uint16_t *cfgCipherSuites = ctx->config.tlsConfig.cipherSuites;
387     uint32_t cfgCipherSuitesSize = ctx->config.tlsConfig.cipherSuitesSize;
388     if (ctx->negotiatedInfo.version == HITLS_VERSION_TLS13) {
389         cfgCipherSuites = ctx->config.tlsConfig.tls13CipherSuites;
390         cfgCipherSuitesSize = ctx->config.tlsConfig.tls13cipherSuitesSize;
391     }
392 
393     const uint16_t *preferenceCipherSuites = clientHello->cipherSuites;
394     uint16_t preferenceCipherSuitesSize = clientHello->cipherSuitesSize;
395     const uint16_t *normalCipherSuites = cfgCipherSuites;
396     uint16_t normalCipherSuitesSize = (uint16_t)cfgCipherSuitesSize;
397 
398     if (ctx->config.tlsConfig.isSupportServerPreference) {
399         preferenceCipherSuites = cfgCipherSuites;
400         preferenceCipherSuitesSize = (uint16_t)cfgCipherSuitesSize;
401         normalCipherSuites = clientHello->cipherSuites;
402         normalCipherSuitesSize = clientHello->cipherSuitesSize;
403     }
404 
405     /* Select the supported cipher suite. If the cipher suite is found, return success */
406     for (uint16_t i = 0u; i < preferenceCipherSuitesSize; i++) {
407         for (uint32_t j = 0u; j < normalCipherSuitesSize; j++) {
408             if (normalCipherSuites[j] != preferenceCipherSuites[i]) {
409                 continue;
410             }
411             if (CheckCipherSuite(ctx, clientHello, normalCipherSuites[j]) != HITLS_SUCCESS) {
412                 break;
413             }
414             return HITLS_SUCCESS;
415         }
416     }
417 
418     BSL_ERR_PUSH_ERROR(HITLS_MSG_HANDLE_CIPHER_SUITE_ERR);
419     BSL_LOG_BINLOG_FIXLEN(BINLOG_ID15222, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN,
420         "can not find a appropriate cipher suite.", 0, 0, 0, 0);
421     ctx->method.sendAlert(ctx, ALERT_LEVEL_FATAL, ALERT_HANDSHAKE_FAILURE);
422     return HITLS_MSG_HANDLE_CIPHER_SUITE_ERR;
423 }
424 
425 #if defined(HITLS_TLS_PROTO_TLS_BASIC) || defined(HITLS_TLS_PROTO_DTLS12)
426 /**
427  * @brief Select the negotiation version based on the client Hello packet.
428  *
429  * @param ctx [IN] TLS context
430  * @param clientHello [IN] client Hello packet
431  *
432  * @retval HITLS_SUCCESS succeeded.
433  * @retval HITLS_MSG_HANDLE_UNSUPPORT_VERSION Unsupported version number
434  */
435 static int32_t ServerSelectNegoVersion(TLS_Ctx *ctx, const ClientHelloMsg *clientHello)
436 {
437     uint16_t legacyVersion = clientHello->version;
438     if (legacyVersion > HITLS_VERSION_TLS13 && !IS_SUPPORT_DATAGRAM(ctx->config.tlsConfig.originVersionMask)) {
439         legacyVersion = HITLS_VERSION_TLS12;
440     }
441     /* Check whether DTLS is used */
442     if (IS_SUPPORT_DATAGRAM(ctx->config.tlsConfig.originVersionMask) &&
443         !IS_SUPPORT_TLCP(ctx->config.tlsConfig.originVersionMask)) {
444         if (legacyVersion > ctx->config.tlsConfig.minVersion) {
445             /** The DTLS version supported by the client is too early and the negotiation cannot be continued */
446             if (TLS_IS_FIRST_HANDSHAKE(ctx)) {
447                 ctx->negotiatedInfo.version = legacyVersion;
448             }
449             BSL_ERR_PUSH_ERROR(HITLS_MSG_HANDLE_UNSUPPORT_VERSION);
450             BSL_LOG_BINLOG_FIXLEN(BINLOG_ID15223, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN,
451                 "client want a unsupported protocol version 0x%02x.", legacyVersion, 0, 0, 0);
452             ctx->method.sendAlert(ctx, ALERT_LEVEL_FATAL, ALERT_PROTOCOL_VERSION);
453             return HITLS_MSG_HANDLE_UNSUPPORT_VERSION;
454         }
455         /** Continue the version negotiation and obtain the earlier DTLS version between the latest versions of the
456          * client and server */
457         if (legacyVersion < ctx->config.tlsConfig.maxVersion) {
458             ctx->negotiatedInfo.version = ctx->config.tlsConfig.maxVersion;
459             BSL_LOG_BINLOG_FIXLEN(BINLOG_ID15224, BSL_LOG_LEVEL_INFO, BSL_LOG_BINLOG_TYPE_RUN,
460                 "client want a unsupported protocol version 0x%02x.", legacyVersion, 0, 0, 0);
461         } else {
462             ctx->negotiatedInfo.version = legacyVersion;
463         }
464     } else {
465         if (legacyVersion < ctx->config.tlsConfig.minVersion) {
466             if (TLS_IS_FIRST_HANDSHAKE(ctx)) {
467                 ctx->negotiatedInfo.version = legacyVersion;
468             }
469             /* The TLS version supported by the client is too early and cannot be negotiated */
470             BSL_ERR_PUSH_ERROR(HITLS_MSG_HANDLE_UNSUPPORT_VERSION);
471             BSL_LOG_BINLOG_FIXLEN(BINLOG_ID15225, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN,
472                 "client version = 0x%02x, min version = 0x%02x.",
473                 legacyVersion, ctx->config.tlsConfig.minVersion, 0, 0);
474             ctx->method.sendAlert(ctx, ALERT_LEVEL_FATAL, ALERT_PROTOCOL_VERSION);
475             return HITLS_MSG_HANDLE_UNSUPPORT_VERSION;
476         }
477         /* Continue the version negotiation. Obtain the earlier version between the latest versions of the client and
478          * server */
479         if (legacyVersion > ctx->config.tlsConfig.maxVersion) {
480             ctx->negotiatedInfo.version = ctx->config.tlsConfig.maxVersion;
481             BSL_LOG_BINLOG_FIXLEN(BINLOG_ID15226, BSL_LOG_LEVEL_INFO, BSL_LOG_BINLOG_TYPE_RUN,
482                 "client version = 0x%02x, max version = 0x%02x.",
483                 legacyVersion, ctx->config.tlsConfig.maxVersion, 0, 0);
484         } else {
485             ctx->negotiatedInfo.version = legacyVersion;
486         }
487     }
488 #ifdef HITLS_TLS_FEATURE_SECURITY
489     int32_t ret = 0;
490     /* Version security check */
491     ret = SECURITY_SslCheck((HITLS_Ctx *)ctx, HITLS_SECURITY_SECOP_VERSION, 0, ctx->negotiatedInfo.version, NULL);
492     if (ret != SECURITY_SUCCESS) {
493         BSL_ERR_PUSH_ERROR(HITLS_MSG_HANDLE_UNSECURE_VERSION);
494         return RETURN_ALERT_PROCESS(ctx, HITLS_MSG_HANDLE_UNSECURE_VERSION, BINLOG_ID17048,
495             "SslCheck fail", ALERT_INSUFFICIENT_SECURITY);
496     }
497 #endif /* HITLS_TLS_FEATURE_SECURITY */
498     return HITLS_SUCCESS;
499 }
500 #endif /* HITLS_TLS_PROTO_TLS_BASIC || HITLS_TLS_PROTO_DTLS12 */
501 
502 #ifdef HITLS_TLS_FEATURE_ALPN
503 static int32_t ServerSelectAlpnProtocol(TLS_Ctx *ctx, const ClientHelloMsg *clientHello)
504 {
505     uint8_t *alpnSelected = NULL;
506     uint8_t alpnSelectedLen = 0u;
507 
508     /* If the callback is empty, the server does not have the ALPN processing capability. In this case, return success
509      */
510     if (ctx->globalConfig != NULL && ctx->globalConfig->alpnSelectCb != NULL) {
511         int32_t alpnCbRet = ctx->globalConfig->alpnSelectCb(ctx, &alpnSelected, &alpnSelectedLen,
512             clientHello->extension.content.alpnList, clientHello->extension.content.alpnListSize,
513             ctx->globalConfig->alpnUserData);
514         if (alpnCbRet == HITLS_ALPN_ERR_OK) {
515             uint8_t *alpnSelectedTmp = (uint8_t *)BSL_SAL_Calloc(alpnSelectedLen + 1, sizeof(uint8_t));
516             if (alpnSelectedTmp == NULL) {
517                 BSL_ERR_PUSH_ERROR(HITLS_MEMALLOC_FAIL);
518                 BSL_LOG_BINLOG_FIXLEN(BINLOG_ID15227, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN,
519                     "server malloc alpn buffer failed.", 0, 0, 0, 0);
520                 ctx->method.sendAlert(ctx, ALERT_LEVEL_FATAL, ALERT_INTERNAL_ERROR);
521                 return HITLS_MEMALLOC_FAIL;
522             }
523             if (memcpy_s(alpnSelectedTmp, alpnSelectedLen + 1, alpnSelected, alpnSelectedLen) != EOK) {
524                 BSL_SAL_FREE(alpnSelectedTmp);
525                 BSL_ERR_PUSH_ERROR(HITLS_MEMCPY_FAIL);
526                 BSL_LOG_BINLOG_FIXLEN(BINLOG_ID16031, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN,
527                     "server copy selected alpn failed.", 0, 0, 0, 0);
528                 ctx->method.sendAlert(ctx, ALERT_LEVEL_FATAL, ALERT_INTERNAL_ERROR);
529                 return HITLS_MEMCPY_FAIL;
530             }
531             BSL_SAL_FREE(ctx->negotiatedInfo.alpnSelected);
532             ctx->negotiatedInfo.alpnSelected = alpnSelectedTmp;
533             ctx->negotiatedInfo.alpnSelectedSize = alpnSelectedLen;
534 
535             BSL_LOG_BINLOG_VARLEN(BINLOG_ID15228, BSL_LOG_LEVEL_INFO, BSL_LOG_BINLOG_TYPE_RUN,
536                 "select ALPN protocol: %s.", ctx->negotiatedInfo.alpnSelected);
537             /* Based on RFC7301, if the server cannot match the application layer protocol in the client alpn list, it
538              * sends a fatal alert to the peer end.
539              * If the returned value is not HITLS_ALPN_ERR_NOACK, the system sends a fatal alert message to the peer
540              */
541         } else if (alpnCbRet != HITLS_ALPN_ERR_NOACK) {
542             BSL_ERR_PUSH_ERROR(HITLS_MSG_HANDLE_ALPN_PROTOCOL_NO_MATCH);
543             BSL_LOG_BINLOG_FIXLEN(BINLOG_ID15229, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN,
544                 "server invoke alpn select cb error.", 0, 0, 0, 0);
545             ctx->method.sendAlert(ctx, ALERT_LEVEL_FATAL, ALERT_NO_APPLICATION_PROTOCOL);
546             return HITLS_MSG_HANDLE_ALPN_PROTOCOL_NO_MATCH;
547         }
548     }
549 
550     return HITLS_SUCCESS;
551 }
552 #endif /* HITLS_TLS_FEATURE_ALPN */
553 #ifdef HITLS_TLS_FEATURE_SNI
554 static int32_t ServerDealServerName(TLS_Ctx *ctx, const ClientHelloMsg *clientHello)
555 {
556     int32_t ret = 0;
557     int32_t alert = ALERT_UNRECOGNIZED_NAME;
558     uint32_t serverNameSize = clientHello->extension.content.serverNameSize;
559 
560     if (clientHello->extension.flag.haveServerName == false) {
561         return HITLS_SUCCESS;
562     }
563 
564     BSL_SAL_FREE(ctx->hsCtx->serverName);
565     ctx->hsCtx->serverName = (uint8_t *)BSL_SAL_Dump(clientHello->extension.content.serverName,
566         serverNameSize * sizeof(uint8_t));
567 
568     if (ctx->hsCtx->serverName == NULL) {
569         BSL_ERR_PUSH_ERROR(HITLS_MEMCPY_FAIL);
570         BSL_LOG_BINLOG_FIXLEN(BINLOG_ID15230, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN,
571             "server_name malloc fail when parse extensions msg.", 0, 0, 0, 0);
572         return HITLS_MEMCPY_FAIL;
573     }
574 
575     ctx->hsCtx->serverNameSize = serverNameSize;
576 
577     /* The product does not have the registered server_name callback processing function */
578     if (ctx->globalConfig == NULL || ctx->globalConfig->sniDealCb == NULL) {
579         /* Rejected, but continued handshake */
580         ctx->negotiatedInfo.isSniStateOK = false;
581         BSL_LOG_BINLOG_FIXLEN(BINLOG_ID15231, BSL_LOG_LEVEL_INFO, BSL_LOG_BINLOG_TYPE_RUN,
582             "server did not set sni callback, but continue handshake", 0, 0, 0, 0);
583         return HITLS_SUCCESS;
584     }
585 
586     /* Execute the product callback function */
587     ret = ctx->globalConfig->sniDealCb(ctx, &alert, ctx->globalConfig->sniArg);
588     switch (ret) {
589         case HITLS_ACCEPT_SNI_ERR_OK:
590             ctx->negotiatedInfo.isSniStateOK = true;
591             BSL_LOG_BINLOG_FIXLEN(BINLOG_ID15232, BSL_LOG_LEVEL_INFO, BSL_LOG_BINLOG_TYPE_RUN,
592                 "server accept server_name from client hello msg ", 0, 0, 0, 0);
593             break;
594         case HITLS_ACCEPT_SNI_ERR_NOACK:
595             ctx->negotiatedInfo.isSniStateOK = false;
596             BSL_LOG_BINLOG_FIXLEN(BINLOG_ID15233, BSL_LOG_LEVEL_WARN, BSL_LOG_BINLOG_TYPE_RUN,
597                 "server did not accept server_name from client hello msg, but continue handshake", 0, 0, 0, 0);
598             break;
599         case HITLS_ACCEPT_SNI_ERR_ALERT_FATAL:
600         default:
601             BSL_LOG_BINLOG_FIXLEN(BINLOG_ID15234, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN,
602                 "server did not accept server_name from client hello msg, stop handshake",
603                 0, 0, 0, 0);
604             ctx->negotiatedInfo.isSniStateOK = false;
605             ctx->method.sendAlert(ctx, ALERT_LEVEL_FATAL, ALERT_UNRECOGNIZED_NAME);
606             return  HITLS_MSG_HANDLE_SNI_UNRECOGNIZED_NAME;
607     }
608 
609     return HITLS_SUCCESS;
610 }
611 #endif /* HITLS_TLS_FEATURE_SNI */
612 
613 static int32_t ProcessClientHelloExt(TLS_Ctx *ctx, const ClientHelloMsg *clientHello, bool isNeedSendHrr)
614 {
615     (void)ctx;
616     (void)clientHello;
617     (void)isNeedSendHrr;
618     int32_t ret = HITLS_SUCCESS;
619     ret = HS_CheckReceivedExtension(
620         ctx, CLIENT_HELLO, clientHello->extensionTypeMask, HS_EX_TYPE_TLS_ALLOWED_OF_CLIENT_HELLO);
621     if (ret != HITLS_SUCCESS) {
622         return ret;
623     }
624 #ifdef HITLS_TLS_FEATURE_SNI
625     /* The message contains a server_name extension with the length greater than 0 */
626     ret = ServerDealServerName(ctx, clientHello);
627     if (ret != HITLS_SUCCESS) {
628         return ret;
629     }
630 #endif /* HITLS_TLS_FEATURE_SNI */
631 #ifdef HITLS_TLS_FEATURE_ALPN
632     if (clientHello->extension.flag.haveAlpn && !isNeedSendHrr && ctx->state == CM_STATE_HANDSHAKING) {
633         ret = ServerSelectAlpnProtocol(ctx, clientHello);
634         if (ret != HITLS_SUCCESS) {
635             BSL_LOG_BINLOG_FIXLEN(BINLOG_ID17049, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN,
636                 "ServerSelectAlpnProtocol fail", 0, 0, 0, 0);
637             /* Logs have been recorded internally */
638             return ret;
639         }
640     }
641 #endif /* HITLS_TLS_FEATURE_ALPN */
642     return ret;
643 }
644 
645 #ifdef HITLS_TLS_FEATURE_SESSION
646 /* Validate the session ID ctx. */
647 bool ServerCmpSessionIdCtx(TLS_Ctx *ctx, HITLS_Session *sess)
648 {
649 #ifdef HITLS_TLS_FEATURE_SESSION_ID
650     uint8_t sessionIdCtx[HITLS_SESSION_ID_CTX_MAX_SIZE];
651     uint32_t sessionIdCtxSize = HITLS_SESSION_ID_CTX_MAX_SIZE;
652 
653     if (HITLS_SESS_GetSessionIdCtx(sess, sessionIdCtx, &sessionIdCtxSize) != HITLS_SUCCESS) {
654         return false;
655     }
656 
657     /* The session ID ctx length is not equal to configured value. */
658     if (sessionIdCtxSize != ctx->config.tlsConfig.sessionIdCtxSize) {
659         return false;
660     }
661 
662     /* The session ID ctx is not equal to configured value. */
663     if (sessionIdCtxSize != 0 && memcmp(sessionIdCtx, ctx->config.tlsConfig.sessionIdCtx, sessionIdCtxSize) != 0) {
664         return false;
665     }
666 #endif /* HITLS_TLS_FEATURE_SESSION_ID */
667     (void)ctx;
668     (void)sess;
669     return true;
670 }
671 #endif /* HITLS_TLS_FEATURE_SESSION */
672 
673 #if defined(HITLS_TLS_PROTO_TLS_BASIC) || defined(HITLS_TLS_PROTO_DTLS12)
674 #ifdef HITLS_TLS_FEATURE_RENEGOTIATION
675 static void CheckRenegotiate(TLS_Ctx *ctx)
676 {
677     /* For the server, sending a Hello Request message is not considered as renegotiation. The server enters the
678      * renegotiation state only after receiving a Hello message from the client. A non-zero version number
679      * indicates that a handshake has been performed, in which case, the client hello process enters the
680      * renegotiation state again. */
681     if (ctx->negotiatedInfo.version != 0u) {
682         ctx->negotiatedInfo.isRenegotiation = true;  // enters the renegotiation state.
683     }
684     return;
685 }
686 #endif /* HITLS_TLS_FEATURE_RENEGOTIATION */
687 #ifdef HITLS_TLS_FEATURE_SESSION
688 #ifdef HITLS_TLS_FEATURE_ALPN
689 static int32_t DealResumeAlpnEx(TLS_Ctx *ctx, const ClientHelloMsg *clientHello)
690 {
691     if (clientHello->extension.flag.haveAlpn && ctx->state == CM_STATE_HANDSHAKING) {
692         return ServerSelectAlpnProtocol(ctx, clientHello);
693     }
694     return HITLS_SUCCESS;
695 }
696 #endif /* HITLS_TLS_FEATURE_ALPN */
697 #ifdef HITLS_TLS_FEATURE_SNI
698 static int32_t DealResumeServerName(TLS_Ctx *ctx, const ClientHelloMsg *clientHello,
699     uint32_t serverNameSize, uint8_t *serverName)
700 {
701     /* Continue processing only when the TLS protocol version <=TLS1.2 */
702     if (ctx->negotiatedInfo.version >= HITLS_VERSION_TLS13 && ctx->negotiatedInfo.version != HITLS_VERSION_DTLS12) {
703         return HITLS_SUCCESS;
704     }
705     if (ctx->globalConfig != NULL && ctx->globalConfig->sniDealCb == NULL && serverNameSize == 0) {
706         ctx->negotiatedInfo.isSniStateOK = false;
707         return HITLS_SUCCESS;
708     }
709 
710     if (serverName != NULL && serverNameSize != 0 && clientHello->extension.flag.haveServerName == false) {
711         BSL_LOG_BINLOG_VARLEN(BINLOG_ID16119, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN,
712             "during session resumption, session server name is [%s]", (char *)serverName);
713         BSL_LOG_BINLOG_FIXLEN(BINLOG_ID16120, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN,
714             "There is no server name in client hello msg.", 0, 0, 0, 0);
715         ctx->negotiatedInfo.isSniStateOK = false;
716         return  HITLS_MSG_HANDLE_SNI_UNRECOGNIZED_NAME;
717     }
718 
719     /* Compare the extended value of client hello server_name and the value of server_name in the session during session
720      * resumption */
721     if (clientHello->extension.content.serverNameSize != serverNameSize ||
722         SNI_StrcaseCmp((char *)clientHello->extension.content.serverName, (char *)serverName) != 0) {
723         BSL_LOG_BINLOG_VARLEN(BINLOG_ID15235,
724             BSL_LOG_LEVEL_ERR,
725             BSL_LOG_BINLOG_TYPE_RUN,
726             "during session resume ,session servername is [%s]",
727             (char *)serverName);
728         BSL_LOG_BINLOG_VARLEN(BINLOG_ID15254, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN,
729             "server did not accept server_name [%s] from client hello msg",
730             (char *)clientHello->extension.content.serverName);
731         ctx->negotiatedInfo.isSniStateOK = false;
732         return  HITLS_MSG_HANDLE_SNI_UNRECOGNIZED_NAME;
733     }
734 
735     BSL_LOG_BINLOG_FIXLEN(BINLOG_ID15236, BSL_LOG_LEVEL_INFO, BSL_LOG_BINLOG_TYPE_RUN,
736         "during session resume, server accept server_name [%s] from client hello msg.", (char *)serverName, 0, 0, 0);
737 
738     return HITLS_SUCCESS;
739 }
740 
741 static int32_t ServerCheckResumeSni(TLS_Ctx *ctx, const ClientHelloMsg *clientHello, HITLS_Session **sess)
742 {
743     if (*sess == NULL || ctx->config.tlsConfig.maxVersion == HITLS_VERSION_TLCP_DTLCP11) {
744         return HITLS_SUCCESS;
745     }
746     int32_t ret = HITLS_SUCCESS;
747     uint8_t *serverName = NULL;
748     uint32_t serverNameSize = 0;
749 
750     SESS_GetHostName(*sess, &serverNameSize, &serverName);
751 
752     /* During session recovery, the server processes the server_name extension in the ClientHello */
753     ret = DealResumeServerName(ctx, clientHello, serverNameSize, serverName);
754     if (ret != HITLS_SUCCESS) {
755         HITLS_SESS_Free(*sess);
756         *sess = NULL;
757     }
758     return HITLS_SUCCESS;
759 }
760 #endif /* HITLS_TLS_FEATURE_SNI */
761 
762 int32_t ServerCheckResumeCipherSuite(const ClientHelloMsg *clientHello, uint16_t cipherSuite)
763 {
764     for (uint16_t i = 0u; i < clientHello->cipherSuitesSize; i++) {
765         if (cipherSuite == clientHello->cipherSuites[i]) {
766             return HITLS_SUCCESS;
767         }
768     }
769 
770     BSL_LOG_BINLOG_FIXLEN(BINLOG_ID15237, BSL_LOG_LEVEL_DEBUG, BSL_LOG_BINLOG_TYPE_RUN,
771         "Client's cipher suites do not match resume cipher suite.", 0, 0, 0, 0);
772     return HITLS_MSG_HANDLE_ILLEGAL_CIPHER_SUITE;
773 }
774 
775 static int32_t ServerCheckResumeParam(TLS_Ctx *ctx, const ClientHelloMsg *clientHello)
776 {
777     int32_t ret = HITLS_SUCCESS;
778     uint16_t version = 0;
779     uint16_t cipherSuite = 0;
780     HITLS_Session *sess = ctx->session;
781     HITLS_SESS_GetProtocolVersion(sess, &version);
782     HITLS_SESS_GetCipherSuite(sess, &cipherSuite);
783 
784     if (ServerCmpSessionIdCtx(ctx, sess) != true) {
785         BSL_LOG_BINLOG_FIXLEN(BINLOG_ID15886, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN,
786             "Resuming Sessions: session id ctx is inconsistent.", 0, 0, 0, 0);
787         ctx->method.sendAlert(ctx, ALERT_LEVEL_FATAL, ALERT_ILLEGAL_PARAMETER);
788         return HITLS_MSG_HANDLE_SESSION_ID_CTX_ILLEGAL;
789     }
790 
791     if (ctx->negotiatedInfo.version != version) {
792         BSL_LOG_BINLOG_FIXLEN(BINLOG_ID15887, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN,
793             "Resuming Sessions: version is inconsistent.", 0, 0, 0, 0);
794         ctx->method.sendAlert(ctx, ALERT_LEVEL_FATAL, ALERT_PROTOCOL_VERSION);
795         return HITLS_MSG_HANDLE_ILLEGAL_VERSION;
796     }
797 
798     ret = ServerCheckResumeCipherSuite(clientHello, cipherSuite);
799     if (ret != HITLS_SUCCESS) {
800         ctx->method.sendAlert(ctx, ALERT_LEVEL_FATAL, ALERT_ILLEGAL_PARAMETER);
801         return ret;
802     }
803 
804     ret = CFG_GetCipherSuiteInfo(cipherSuite, &ctx->negotiatedInfo.cipherSuiteInfo);
805     if (ret != HITLS_SUCCESS) {
806         BSL_LOG_BINLOG_FIXLEN(BINLOG_ID17050, BSL_LOG_LEVEL_INFO, BSL_LOG_BINLOG_TYPE_RUN,
807             "GetCipherSuiteInfo fail", 0, 0, 0, 0);
808         ctx->method.sendAlert(ctx, ALERT_LEVEL_FATAL, ALERT_INTERNAL_ERROR);
809         return ret;
810     }
811 
812 #ifdef HITLS_TLS_FEATURE_ALPN
813     /* During session resumption, the server processes the ALPN extension in the ClientHello message */
814     return DealResumeAlpnEx(ctx, clientHello);
815 #else
816     return HITLS_SUCCESS;
817 #endif /* HITLS_TLS_FEATURE_ALPN */
818 }
819 
820 /*
821     rfc7627 5.3
822     If a server receives a ClientHello for an abbreviated handshake
823 offering to resume a known previous session, it behaves as follows:
824 --------------------------------------------------------------------------------------------------------
825 | original session | abbreviated handshake  |                     Server behavior                        |
826 | :-------------: | :--------------------: | :---------------------------------------------------------:|
827 |      true       |          true          |                 SH with ems, agree resume                  |
828 |      true       |         false          |                     abort handshake                        |
829 |      false      |          true          |            disagre resume, full handshake                  |
830 |      false      |         false          | depend cnf: abort handshake(true) / agree resume (false)   |
831 */
832 static int32_t ResumeCheckExtendedMasterScret(TLS_Ctx *ctx, const ClientHelloMsg *clientHello, HITLS_Session **sess)
833 {
834     if (*sess == NULL || ctx->config.tlsConfig.maxVersion == HITLS_VERSION_TLCP_DTLCP11) {
835         return HITLS_SUCCESS;
836     }
837     (void)clientHello;
838     uint8_t haveExtMasterSecret = false;
839     HITLS_SESS_GetHaveExtMasterSecret(*sess, &haveExtMasterSecret);
840     if (haveExtMasterSecret != 0) {
841         if (!clientHello->extension.flag.haveExtendedMasterSecret) {
842             BSL_LOG_BINLOG_FIXLEN(BINLOG_ID17051, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN,
843                 "ExtendedMasterSecret err", 0, 0, 0, 0);
844             ctx->method.sendAlert(ctx, ALERT_LEVEL_FATAL, ALERT_HANDSHAKE_FAILURE);
845             return HITLS_MSG_HANDLE_INVALID_EXTENDED_MASTER_SECRET;
846         }
847         ctx->negotiatedInfo.isExtendedMasterSecret = true;
848     } else {
849         if (clientHello->extension.flag.haveExtendedMasterSecret) {
850             HITLS_SESS_Free(*sess);
851             *sess = NULL;
852         } else if (ctx->config.tlsConfig.isSupportExtendMasterSecret) {
853             BSL_LOG_BINLOG_FIXLEN(BINLOG_ID17052, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN,
854                 "ExtendedMasterSecret err", 0, 0, 0, 0);
855             ctx->method.sendAlert(ctx, ALERT_LEVEL_FATAL, ALERT_HANDSHAKE_FAILURE);
856             return HITLS_MSG_HANDLE_INVALID_EXTENDED_MASTER_SECRET;
857         }
858         ctx->negotiatedInfo.isExtendedMasterSecret = clientHello->extension.flag.haveExtendedMasterSecret;
859     }
860 #ifdef HITLS_TLS_FEATURE_SNI
861     return ServerCheckResumeSni(ctx, clientHello, sess);
862 #else
863     return HITLS_SUCCESS;
864 #endif /* HITLS_TLS_FEATURE_SNI */
865 }
866 #ifdef HITLS_TLS_FEATURE_SESSION_TICKET
867 static int32_t ServerCheckResumeTicket(TLS_Ctx *ctx, const ClientHelloMsg *clientHello)
868 {
869     TLS_SessionMgr *sessMgr = ctx->config.tlsConfig.sessMgr;
870     HITLS_Session *sess = NULL;
871     uint8_t *ticketBuf = clientHello->extension.content.ticket;
872     uint32_t ticketBufSize = clientHello->extension.content.ticketSize;
873     bool isTicketExpect = false;
874     int32_t ret = SESSMGR_DecryptSessionTicket(LIBCTX_FROM_CTX(ctx), ATTRIBUTE_FROM_CTX(ctx),
875         sessMgr, &sess, ticketBuf, ticketBufSize, &isTicketExpect);
876     if (ret != HITLS_SUCCESS) {
877         BSL_LOG_BINLOG_FIXLEN(BINLOG_ID16045, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN,
878             "SESSMGR_DecryptSessionTicket return fail when process client hello.", 0, 0, 0, 0);
879         ctx->method.sendAlert(ctx, ALERT_LEVEL_FATAL, ALERT_INTERNAL_ERROR);
880         return ret;
881     }
882     ctx->negotiatedInfo.isTicket = isTicketExpect;
883     ret = ResumeCheckExtendedMasterScret(ctx, clientHello, &sess);
884     if (ret != HITLS_SUCCESS) {
885         HITLS_SESS_Free(sess);
886         sess = NULL;
887         return ret;
888     }
889     if (sess != NULL) {
890         /* Check whether the session is valid */
891         if (SESS_CheckValidity(sess, (uint64_t)BSL_SAL_CurrentSysTimeGet()) == false) {
892             /* If the session is invalid, a message is returned and the session is not resume. The complete connection
893              * is established */
894             ctx->negotiatedInfo.isTicket = true;
895             HITLS_SESS_Free(sess);
896             return HITLS_SUCCESS;
897         }
898         HITLS_SESS_Free(ctx->session);
899         ctx->session = sess;
900         ctx->negotiatedInfo.isResume = true;
901         /* If the session is resumed and the session ID of the clientHello is not empty, the session ID needs to be
902          * filled in the serverHello and returned */
903         HITLS_SESS_SetSessionId(ctx->session, clientHello->sessionId, clientHello->sessionIdSize);
904     }
905     return HITLS_SUCCESS;
906 }
907 #endif /* HITLS_TLS_FEATURE_SESSION_TICKET */
908 /* Check whether the resume function is supported */
909 static int32_t ServerCheckResume(TLS_Ctx *ctx, const ClientHelloMsg *clientHello)
910 {
911     ctx->negotiatedInfo.isResume = false;
912     ctx->negotiatedInfo.isTicket = false;
913     /* If session resumption is not allowed in the renegotiation state, return */
914     if (ctx->negotiatedInfo.isRenegotiation && !ctx->config.tlsConfig.isResumptionOnRenego) {
915         return HITLS_SUCCESS;
916     }
917     /* Obtain the session resumption information */
918     TLS_SessionMgr *sessMgr = ctx->config.tlsConfig.sessMgr;
919     /* Create a null session handle */
920     HITLS_Session *sess = NULL;
921     uint32_t ticketBufSize = clientHello->extension.content.ticketSize;
922     bool supportTicket = IsTicketSupport(ctx);
923     /* rfc5077 3.4 If a ticket is presented by the client, the server
924     MUST NOT attempt to use the Session ID in the ClientHello for stateful
925     session resumption. */
926     if (ticketBufSize == 0u) {
927         if (supportTicket && clientHello->extension.flag.haveTicket) {
928             ctx->negotiatedInfo.isTicket = true;
929         }
930         sess = HITLS_SESS_Dup(SESSMGR_Find(sessMgr, clientHello->sessionId, clientHello->sessionIdSize));
931         int32_t ret = ResumeCheckExtendedMasterScret(ctx, clientHello, &sess);
932         if (ret != HITLS_SUCCESS) {
933             BSL_LOG_BINLOG_FIXLEN(BINLOG_ID17053, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN,
934                 "ResumeCheckExtendedMasterScret fail", 0, 0, 0, 0);
935             HITLS_SESS_Free(sess);
936             sess = NULL;
937             return ret;
938         }
939         if (sess != NULL) {
940             /* Update session handle information */
941             HITLS_SESS_Free(ctx->session);
942             ctx->session = sess; // has ensured that it will not fail
943             sess = NULL;
944             ctx->negotiatedInfo.isResume = true;
945         }
946         return HITLS_SUCCESS;
947     }
948 #ifdef HITLS_TLS_FEATURE_SESSION_TICKET
949     if (supportTicket) {
950         return ServerCheckResumeTicket(ctx, clientHello);
951     }
952 #endif /* HITLS_TLS_FEATURE_SESSION_TICKET */
953     return HITLS_SUCCESS;
954 }
955 #endif /* HITLS_TLS_FEATURE_SESSION */
956 static int32_t ServerCheckRenegoInfoDuringFirstHandshake(TLS_Ctx *ctx, const ClientHelloMsg *clientHello)
957 {
958     /* If the peer does not support security renegotiation, the system returns */
959     if (!clientHello->haveEmptyRenegoScsvCipher && !clientHello->extension.flag.haveSecRenego) {
960         return HITLS_SUCCESS;
961     }
962 
963     /* For the first handshake, if the security renegotiation information is not empty, a failure message is returned */
964     if (clientHello->extension.content.secRenegoInfoSize != 0) {
965         BSL_ERR_PUSH_ERROR(HITLS_MSG_HANDLE_RENEGOTIATION_FAIL);
966         BSL_LOG_BINLOG_FIXLEN(BINLOG_ID15889, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN,
967             "secRenegoInfoSize should be 0 in server initial handhsake.", 0, 0, 0, 0);
968         ctx->method.sendAlert(ctx, ALERT_LEVEL_FATAL, ALERT_HANDSHAKE_FAILURE);
969         return HITLS_MSG_HANDLE_RENEGOTIATION_FAIL;
970     }
971 
972     /* Setting the Support for Security Renegotiation */
973     ctx->negotiatedInfo.isSecureRenegotiation = true;
974     return HITLS_SUCCESS;
975 }
976 
977 #ifdef HITLS_TLS_FEATURE_RENEGOTIATION
978 static int32_t ServerCheckRenegoInfoDuringRenegotiation(TLS_Ctx *ctx, const ClientHelloMsg *clientHello)
979 {
980     /* If the renegotiation status contains the SCSV cipher suite, a failure message is returned */
981     if (clientHello->haveEmptyRenegoScsvCipher) {
982         BSL_ERR_PUSH_ERROR(HITLS_MSG_HANDLE_RENEGOTIATION_FAIL);
983         BSL_LOG_BINLOG_FIXLEN(BINLOG_ID15890, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN,
984             "SCSV cipher should not be in server secure renegotiation.", 0, 0, 0, 0);
985         ctx->method.sendAlert(ctx, ALERT_LEVEL_FATAL, ALERT_HANDSHAKE_FAILURE);
986         return HITLS_MSG_HANDLE_RENEGOTIATION_FAIL;
987     }
988 
989     /* Verify the security renegotiation information */
990     if (clientHello->extension.content.secRenegoInfoSize != ctx->negotiatedInfo.clientVerifyDataSize) {
991         BSL_ERR_PUSH_ERROR(HITLS_MSG_HANDLE_RENEGOTIATION_FAIL);
992         BSL_LOG_BINLOG_FIXLEN(BINLOG_ID15891, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN,
993             "secRenegoInfoSize verify failed during server renegotiation.", 0, 0, 0, 0);
994         ctx->method.sendAlert(ctx, ALERT_LEVEL_FATAL, ALERT_HANDSHAKE_FAILURE);
995         return HITLS_MSG_HANDLE_RENEGOTIATION_FAIL;
996     }
997     if (memcmp(clientHello->extension.content.secRenegoInfo, ctx->negotiatedInfo.clientVerifyData,
998         ctx->negotiatedInfo.clientVerifyDataSize) != 0) {
999         BSL_ERR_PUSH_ERROR(HITLS_MSG_HANDLE_RENEGOTIATION_FAIL);
1000         BSL_LOG_BINLOG_FIXLEN(BINLOG_ID15892, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN,
1001             "secRenegoInfo verify failed during server renegotiation.", 0, 0, 0, 0);
1002         ctx->method.sendAlert(ctx, ALERT_LEVEL_FATAL, ALERT_HANDSHAKE_FAILURE);
1003         return HITLS_MSG_HANDLE_RENEGOTIATION_FAIL;
1004     }
1005 
1006     return HITLS_SUCCESS;
1007 }
1008 #endif /* HITLS_TLS_FEATURE_RENEGOTIATION */
1009 static int32_t ServerCheckAndProcessRenegoInfo(TLS_Ctx *ctx, const ClientHelloMsg *clientHello)
1010 {
1011     /* Not in the renegotiation state */
1012     if (!ctx->negotiatedInfo.isRenegotiation) {
1013         return ServerCheckRenegoInfoDuringFirstHandshake(ctx, clientHello);
1014     }
1015 #ifdef HITLS_TLS_FEATURE_RENEGOTIATION
1016     /* in the renegotiation state */
1017     return ServerCheckRenegoInfoDuringRenegotiation(ctx, clientHello);
1018 #else
1019     return HITLS_SUCCESS;
1020 #endif /* HITLS_TLS_FEATURE_RENEGOTIATION */
1021 }
1022 #ifdef HITLS_TLS_FEATURE_ETM
1023 static int32_t ServerCheckEncryptThenMac(TLS_Ctx *ctx, const ClientHelloMsg *clientHello)
1024 {
1025     bool haveEncryptThenMac = clientHello->extension.flag.haveEncryptThenMac;
1026     /* Renegotiation cannot be downgraded from EncryptThenMac to MacThenEncrypt */
1027     if (ctx->negotiatedInfo.isRenegotiation && ctx->negotiatedInfo.isEncryptThenMac && !haveEncryptThenMac) {
1028         BSL_ERR_PUSH_ERROR(HITLS_MSG_HANDLE_ENCRYPT_THEN_MAC_ERR);
1029         BSL_LOG_BINLOG_FIXLEN(BINLOG_ID15919, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN,
1030             "regotiation should not change encrypt then mac to mac then encrypt.", 0, 0, 0, 0);
1031         ctx->method.sendAlert(ctx, ALERT_LEVEL_FATAL, ALERT_HANDSHAKE_FAILURE);
1032         return HITLS_MSG_HANDLE_ENCRYPT_THEN_MAC_ERR;
1033     }
1034 
1035     /* If EncryptThenMac is not configured, a success message is returned. */
1036     if (!ctx->config.tlsConfig.isEncryptThenMac) {
1037         return HITLS_SUCCESS;
1038     }
1039 
1040     /* TLS 1.3 does not need to negotiate this expansion. */
1041     if (ctx->negotiatedInfo.version == HITLS_VERSION_TLS13) {
1042         return HITLS_SUCCESS;
1043     }
1044 
1045     /* Only the CBC cipher suite has the EncryptThenMac setting. */
1046     if (haveEncryptThenMac && ctx->negotiatedInfo.cipherSuiteInfo.cipherType == HITLS_CBC_CIPHER) {
1047         ctx->negotiatedInfo.isEncryptThenMac = true;
1048     } else {
1049         ctx->negotiatedInfo.isEncryptThenMac = false;
1050     }
1051 
1052     return HITLS_SUCCESS;
1053 }
1054 #endif /* HITLS_TLS_FEATURE_ETM */
1055 
1056 static int32_t ServerSelectCipherSuiteInfo(TLS_Ctx *ctx, const ClientHelloMsg *clientHello)
1057 {
1058     int32_t ret = ServerSelectCipherSuite(ctx, clientHello);
1059     if (ret != HITLS_SUCCESS) {
1060         BSL_LOG_BINLOG_FIXLEN(BINLOG_ID15239, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN,
1061             "server select cipher suite fail.", 0, 0, 0, 0);
1062         return ret;
1063     }
1064 #ifdef HITLS_TLS_FEATURE_ETM
1065     /* Select the encryption mode (EncryptThenMac/MacThenEncrypt) */
1066     ret = ServerCheckEncryptThenMac(ctx, clientHello);
1067     if (ret != HITLS_SUCCESS) {
1068         return ret;
1069     }
1070 #endif /* HITLS_TLS_FEATURE_ETM */
1071 
1072     return HITLS_SUCCESS;
1073 }
1074 
1075 static int32_t ServerProcessClientHelloExt(TLS_Ctx *ctx, const ClientHelloMsg *clientHello)
1076 {
1077     int32_t ret = HITLS_SUCCESS;
1078     (void)ret;
1079     (void)clientHello;
1080     (void)ctx;
1081     /* Sets the extended master key flag */
1082     if (ctx->negotiatedInfo.version > HITLS_VERSION_SSL30 && ctx->config.tlsConfig.isSupportExtendMasterSecret &&
1083         !clientHello->extension.flag.haveExtendedMasterSecret) {
1084         BSL_LOG_BINLOG_FIXLEN(BINLOG_ID16196, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN,
1085             "The peer does not support the extended master key.", 0, 0, 0, 0);
1086         ctx->method.sendAlert(ctx, ALERT_LEVEL_FATAL, ALERT_HANDSHAKE_FAILURE);
1087         return HITLS_MSG_HANDLE_INVALID_EXTENDED_MASTER_SECRET;
1088     }
1089     ctx->negotiatedInfo.isExtendedMasterSecret = clientHello->extension.flag.haveExtendedMasterSecret;
1090 
1091     return ProcessClientHelloExt(ctx, clientHello, false);
1092 }
1093 
1094 static int32_t ServerCheckVersionDowngrade(TLS_Ctx *ctx, const ClientHelloMsg *clientHello)
1095 {
1096     if (!clientHello->haveFallBackScsvCipher) {
1097         return HITLS_SUCCESS;
1098     }
1099     if (IS_SUPPORT_DATAGRAM(ctx->config.tlsConfig.originVersionMask) &&
1100         !IS_SUPPORT_TLCP(ctx->config.tlsConfig.originVersionMask)) {
1101         if (ctx->negotiatedInfo.version > ctx->config.tlsConfig.maxVersion) {
1102             BSL_LOG_BINLOG_FIXLEN(BINLOG_ID15339, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN,
1103                 "dtls server supports a higher protocol version.", 0, 0, 0, 0);
1104             ctx->method.sendAlert(ctx, ALERT_LEVEL_FATAL, ALERT_INAPPROPRIATE_FALLBACK);
1105             return HITLS_MSG_HANDLE_ERR_INAPPROPRIATE_FALLBACK;
1106         }
1107         return HITLS_SUCCESS;
1108     }
1109 
1110     if (ctx->negotiatedInfo.version < ctx->config.tlsConfig.maxVersion) {
1111         BSL_LOG_BINLOG_FIXLEN(BINLOG_ID15335, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN,
1112             "server supports a higher protocol version.", 0, 0, 0, 0);
1113         ctx->method.sendAlert(ctx, ALERT_LEVEL_FATAL, ALERT_INAPPROPRIATE_FALLBACK);
1114         return HITLS_MSG_HANDLE_ERR_INAPPROPRIATE_FALLBACK;
1115     }
1116 
1117     return HITLS_SUCCESS;
1118 }
1119 
1120 // Check client Hello messages
1121 static int32_t ServerCheckAndProcessClientHello(TLS_Ctx *ctx, const ClientHelloMsg *clientHello)
1122 {
1123     /* Obtain the server information */
1124     HS_Ctx *hsCtx = (HS_Ctx *)ctx->hsCtx;
1125 
1126     /* Negotiated version */
1127     int32_t ret = ServerSelectNegoVersion(ctx, clientHello);
1128     if (ret != HITLS_SUCCESS) {
1129         BSL_LOG_BINLOG_FIXLEN(BINLOG_ID15238, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN,
1130             "server select negotiated version fail.", 0, 0, 0, 0);
1131         return ret;
1132     }
1133 
1134     ret = ServerCheckVersionDowngrade(ctx, clientHello);
1135     if (ret != HITLS_SUCCESS) {
1136         return ret;
1137     }
1138 
1139     /* Copy random numbers */
1140     (void)memcpy_s(hsCtx->clientRandom, HS_RANDOM_SIZE, clientHello->randomValue, HS_RANDOM_SIZE);
1141     ret = ServerCheckAndProcessRenegoInfo(ctx, clientHello);
1142     if (ret != HITLS_SUCCESS) {
1143         return ret;
1144     }
1145 #ifdef HITLS_TLS_FEATURE_SESSION
1146     ret = ServerCheckResume(ctx, clientHello);
1147     if (ret != HITLS_SUCCESS) {
1148         return ret;
1149     }
1150 
1151     if (ctx->negotiatedInfo.isResume) {
1152         return ServerCheckResumeParam(ctx, clientHello);
1153     }
1154 #endif /* HITLS_TLS_FEATURE_SESSION */
1155     ret = ServerSelectCipherSuiteInfo(ctx, clientHello);
1156     if (ret != HITLS_SUCCESS) {
1157         return ret;
1158     }
1159     /* TLCP does not pay attention to the extension */
1160 #ifdef HITLS_TLS_PROTO_TLCP11
1161     if (ctx->negotiatedInfo.version == HITLS_VERSION_TLCP_DTLCP11) {
1162         return HITLS_SUCCESS;
1163     }
1164 #endif
1165     return ServerProcessClientHelloExt(ctx, clientHello);
1166 }
1167 #endif /* HITLS_TLS_PROTO_TLS_BASIC || HITLS_TLS_PROTO_DTLS12 */
1168 
1169 #ifdef HITLS_TLS_FEATURE_SNI
1170 static int32_t ClientHelloCbCheck(TLS_Ctx *ctx)
1171 {
1172     int32_t ret;
1173     int32_t alert = ALERT_INTERNAL_ERROR;
1174     const TLS_Config *tlsConfig = ctx->globalConfig;
1175     if (tlsConfig != NULL && tlsConfig->clientHelloCb != NULL) {
1176         ret = tlsConfig->clientHelloCb(ctx, &alert, tlsConfig->clientHelloCbArg);
1177         if (ret != HITLS_CONTINUE_HANDHSAKE) {
1178             BSL_ERR_PUSH_ERROR(HITLS_CLIENT_HELLO_CHECK_ERROR);
1179             BSL_LOG_BINLOG_FIXLEN(BINLOG_ID15240, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN,
1180                 "The result of ClientHello callback is %d, and the reason is %d.", ret, alert, 0, 0);
1181             if (alert >= ALERT_CLOSE_NOTIFY && alert <= ALERT_UNKNOWN) {
1182                 ctx->method.sendAlert(ctx, ALERT_LEVEL_FATAL, alert);
1183             }
1184             return HITLS_CLIENT_HELLO_CHECK_ERROR;
1185         }
1186     }
1187     return HITLS_SUCCESS;
1188 }
1189 #endif /* HITLS_TLS_FEATURE_SNI */
1190 
1191 #ifdef HITLS_TLS_PROTO_TLS_BASIC
1192 int32_t Tls12ServerRecvClientHelloProcess(TLS_Ctx *ctx, const HS_Msg *msg)
1193 {
1194     int32_t ret = HITLS_SUCCESS;
1195     const ClientHelloMsg *clientHello = &msg->body.clientHello;
1196 #ifdef HITLS_TLS_FEATURE_RENEGOTIATION
1197     CheckRenegotiate(ctx);
1198 #endif /* HITLS_TLS_FEATURE_RENEGOTIATION */
1199 #ifdef HITLS_TLS_FEATURE_SNI
1200     /* Perform the ClientHello callback. The pause handshake status is not considered */
1201     ret = ClientHelloCbCheck(ctx);
1202     if (ret != HITLS_SUCCESS) {
1203         return ret;
1204     }
1205 #endif /* HITLS_TLS_FEATURE_SNI */
1206     /* Process the client Hello message */
1207     ret = ServerCheckAndProcessClientHello(ctx, clientHello);
1208     if (ret != HITLS_SUCCESS) {
1209         BSL_LOG_BINLOG_FIXLEN(BINLOG_ID17055, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN,
1210             "CheckAndProcessClientHello fail.", 0, 0, 0, 0);
1211         return ret;
1212     }
1213 
1214     if (ctx->state == CM_STATE_RENEGOTIATION && !ctx->userRenego) {
1215         ctx->negotiatedInfo.isRenegotiation = true; /* Start renegotiation */
1216         ctx->negotiatedInfo.renegotiationNum++;
1217     }
1218     return HS_ChangeState(ctx, TRY_SEND_SERVER_HELLO);
1219 }
1220 #endif /* HITLS_TLS_PROTO_TLS_BASIC */
1221 
1222 #if defined(HITLS_TLS_PROTO_DTLS12) && defined(HITLS_BSL_UIO_UDP)
1223 static int32_t PrepareDtlsCookie(TLS_Ctx *ctx, const ClientHelloMsg *clientHello)
1224 {
1225     int32_t ret;
1226     uint8_t cookie[TLS_HS_MAX_COOKIE_SIZE] = {0};
1227     uint32_t cookieSize = TLS_HS_MAX_COOKIE_SIZE;
1228     ret = HS_CalcCookie(ctx, clientHello, cookie, &cookieSize);
1229     if (ret != HITLS_SUCCESS) {
1230         BSL_LOG_BINLOG_FIXLEN(BINLOG_ID15241, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN,
1231             "calc cookie fail when process client hello.", 0, 0, 0, 0);
1232         ctx->method.sendAlert(ctx, ALERT_LEVEL_FATAL, ALERT_INTERNAL_ERROR);
1233         return ret;
1234     }
1235     BSL_SAL_FREE(ctx->negotiatedInfo.cookie); // Releasing the Old Cookie
1236     ctx->negotiatedInfo.cookie = (uint8_t *)BSL_SAL_Dump(cookie, cookieSize);
1237     if (ctx->negotiatedInfo.cookie == NULL) {
1238         BSL_ERR_PUSH_ERROR(HITLS_MEMALLOC_FAIL);
1239         BSL_LOG_BINLOG_FIXLEN(BINLOG_ID15242, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN,
1240             "malloc cookie fail when process client hello.", 0, 0, 0, 0);
1241         ctx->method.sendAlert(ctx, ALERT_LEVEL_FATAL, ALERT_INTERNAL_ERROR);
1242         return HITLS_MEMALLOC_FAIL;
1243     }
1244     ctx->negotiatedInfo.cookieSize = (uint32_t)cookieSize;
1245     return HITLS_SUCCESS;
1246 }
1247 #endif /* HITLS_TLS_PROTO_DTLS12 && HITLS_BSL_UIO_UDP */
1248 
1249 // The server processes the DTLS client hello message.
1250 #ifdef HITLS_TLS_PROTO_DTLS12
1251 int32_t DtlsServerRecvClientHelloProcess(TLS_Ctx *ctx, const HS_Msg *msg)
1252 {
1253     int32_t ret;
1254     const ClientHelloMsg *clientHello = &msg->body.clientHello;
1255 #ifdef HITLS_TLS_FEATURE_RENEGOTIATION
1256     CheckRenegotiate(ctx);
1257 #endif /* HITLS_TLS_FEATURE_RENEGOTIATION */
1258 #ifdef HITLS_BSL_UIO_UDP
1259     if (!BSL_UIO_GetUioChainTransportType(ctx->uio, BSL_UIO_SCTP)) {
1260         bool isCookieValid = false;
1261         ret = HS_CheckCookie(ctx, clientHello, &isCookieValid);
1262         if (ret != HITLS_SUCCESS) {
1263             BSL_LOG_BINLOG_FIXLEN(BINLOG_ID15243, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN,
1264                 "HS_CheckCookie fail when process client hello.", 0, 0, 0, 0);
1265             ctx->method.sendAlert(ctx, ALERT_LEVEL_FATAL, ALERT_INTERNAL_ERROR);
1266             return ret;
1267         }
1268         /* If the cookie fails to be verified, send a hello verify request */
1269         if (!isCookieValid) {
1270             /* During DTLS renegotiation, if the cookie verification fails, an alert message is sent. If the cookie is
1271              * empty, the hello verify request is sent */
1272             if ((clientHello->cookieLen != 0u) && (ctx->negotiatedInfo.isRenegotiation)) {
1273                 BSL_ERR_PUSH_ERROR(HITLS_MSG_VERIFY_COOKIE_ERR);
1274                 BSL_LOG_BINLOG_FIXLEN(BINLOG_ID15911, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN,
1275                     "client hello cookie verify fail during renegotiation.", 0, 0, 0, 0);
1276                 ctx->method.sendAlert(ctx, ALERT_LEVEL_FATAL, ALERT_HANDSHAKE_FAILURE);
1277                 return HITLS_MSG_VERIFY_COOKIE_ERR;
1278             }
1279             ret = PrepareDtlsCookie(ctx, clientHello);
1280             if (ret != HITLS_SUCCESS) {
1281                 return ret;
1282             }
1283             return HS_ChangeState(ctx, TRY_SEND_HELLO_VERIFY_REQUEST);
1284         }
1285     }
1286 #endif /* HITLS_BSL_UIO_UDP */
1287 #ifdef HITLS_TLS_FEATURE_SNI
1288     /* Perform the ClientHello callback. The pause handshake status is not considered */
1289     ret = ClientHelloCbCheck(ctx);
1290     if (ret != HITLS_SUCCESS) {
1291         return ret;
1292     }
1293 #endif /* HITLS_TLS_FEATURE_SNI */
1294     /* Process the client Hello message */
1295     ret = ServerCheckAndProcessClientHello(ctx, clientHello);
1296     if (ret != HITLS_SUCCESS) {
1297         BSL_LOG_BINLOG_FIXLEN(BINLOG_ID15244, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN,
1298             "server process clientHello fail.", 0, 0, 0, 0);
1299         return ret;
1300     }
1301     if (ctx->state == CM_STATE_RENEGOTIATION && !ctx->userRenego) {
1302         ctx->negotiatedInfo.isRenegotiation = true; /* Start renegotiation */
1303         ctx->negotiatedInfo.renegotiationNum++;
1304     }
1305     return HS_ChangeState(ctx, TRY_SEND_SERVER_HELLO);
1306 }
1307 #endif
1308 
1309 #ifdef HITLS_TLS_PROTO_TLS13
1310 
1311 static uint32_t GetClientKeMode(const ExtensionContent *extension)
1312 {
1313     uint32_t clientKeMode = 0;
1314     for (uint32_t i = 0; i < extension->keModesSize; i++) {
1315         /* Ignore the received keMode of other types */
1316         if (extension->keModes[i] == PSK_KE) {
1317             clientKeMode |= TLS13_KE_MODE_PSK_ONLY;
1318         } else if (extension->keModes[i] == PSK_DHE_KE) {
1319             clientKeMode |= TLS13_KE_MODE_PSK_WITH_DHE;
1320         }
1321     }
1322     return clientKeMode;
1323 }
1324 
1325 static bool CheckClientHelloKeyShareValid(const ClientHelloMsg *clientHello, uint16_t keyShareGroup)
1326 {
1327     for (uint32_t i = 0; i < clientHello->extension.content.supportedGroupsSize; i++) {
1328         if (keyShareGroup == clientHello->extension.content.supportedGroups[i]) {
1329             return true;
1330         }
1331     }
1332     return false;
1333 }
1334 
1335 static int32_t ServerCheckKeyShare(TLS_Ctx *ctx, const ClientHelloMsg *clientHello)
1336 {
1337     /* Prerequisite. If the PSK is not negotiated or the PSK requires dhe, a handshake failure message needs to be
1338      * reported if the keyshare does not exist */
1339     if (clientHello->extension.flag.haveKeyShare == false || clientHello->extension.content.supportedGroupsSize == 0u ||
1340         ProcessEcdheCipherSuite(ctx, clientHello) != HITLS_SUCCESS) {
1341         BSL_ERR_PUSH_ERROR(HITLS_MSG_HANDLE_HANDSHAKE_FAILURE);
1342         BSL_LOG_BINLOG_FIXLEN(BINLOG_ID16137, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN,
1343             "unable to negotiate a supported set of parameters.", 0, 0, 0, 0);
1344         ctx->method.sendAlert(ctx, ALERT_LEVEL_FATAL, ALERT_HANDSHAKE_FAILURE);
1345         return HITLS_MSG_HANDLE_HANDSHAKE_FAILURE;
1346     }
1347 
1348     /* ProcessEcdheCipherSuite returns a success response. There must be a public group */
1349     KeyShareParam *keyShare = &ctx->hsCtx->kxCtx->keyExchParam.share;
1350     uint16_t selectGroup = keyShare->group;
1351     KeyShare *cache = clientHello->extension.content.keyShare;
1352     /*  rfc8446 4.2.8 Otherwise, when sending the new ClientHello, the client MUST
1353         replace the original "key_share" extension with one containing only a
1354         new KeyShareEntry for the group indicated in the selected_group field
1355         of the triggering HelloRetryRequest. */
1356     if (ctx->hsCtx->haveHrr) {
1357         if (cache == NULL || cache->head.next != cache->head.prev || // parse must contain elements.
1358             LIST_ENTRY(cache->head.next, KeyShare, head)->group != selectGroup) {
1359             BSL_ERR_PUSH_ERROR(HITLS_MSG_HANDLE_ILLEGAL_SELECTED_GROUP);
1360             BSL_LOG_BINLOG_FIXLEN(BINLOG_ID16164, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN,
1361                 "hrr client hello key Share error.", 0, 0, 0, 0);
1362             ctx->method.sendAlert(ctx, ALERT_LEVEL_FATAL, ALERT_ILLEGAL_PARAMETER);
1363             return HITLS_MSG_HANDLE_ILLEGAL_SELECTED_GROUP;
1364         }
1365     }
1366     return HITLS_SUCCESS;
1367 }
1368 
1369 static int32_t Tls13ServerProcessKeyShare(TLS_Ctx *ctx, const ClientHelloMsg *clientHello, bool *isNeedSendHrr)
1370 {
1371     /* Prerequisite. If the PSK is not negotiated or the PSK requires dhe, a handshake failure message needs to be
1372      * reported if the keyshare does not exist */
1373     int32_t ret = ServerCheckKeyShare(ctx, clientHello);
1374     if (ret != HITLS_SUCCESS) {
1375         return ret;
1376     }
1377     /* ServerCheckKeyShare returns a success response. There must be a public group */
1378     KeyShareParam *keyShare = &ctx->hsCtx->kxCtx->keyExchParam.share;
1379     uint16_t selectGroup = keyShare->group;
1380     ListHead *node = NULL;
1381     ListHead *tmpNode = NULL;
1382     KeyShare *cur = NULL;
1383     KeyShare *cache = clientHello->extension.content.keyShare;
1384     if (cache == NULL) {
1385         /* According to section 4.2.8 in RFC8446, if the client requests HelloRetryRequest, keyShare can be empty */
1386         *isNeedSendHrr = true;
1387         return HITLS_SUCCESS;
1388     }
1389 
1390     LIST_FOR_EACH_ITEM_SAFE(node, tmpNode, &(cache->head)) {
1391         cur = LIST_ENTRY(node, KeyShare, head);
1392         /*  rfc8446 4.2.8 Clients MUST NOT offer any KeyShareEntry values
1393             for groups not listed in the client's "supported_groups" extension.
1394             Servers MAY check for violations of these rules and abort the
1395             handshake with an "illegal_parameter" alert if one is violated. */
1396         if (!CheckClientHelloKeyShareValid(clientHello, cur->group)) {
1397             BSL_ERR_PUSH_ERROR(HITLS_MSG_HANDLE_ILLEGAL_SELECTED_GROUP);
1398             BSL_LOG_BINLOG_FIXLEN(BINLOG_ID16138, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN,
1399                 "The group in the keyshare does not exist in the support group extension.", 0, 0, 0, 0);
1400             ctx->method.sendAlert(ctx, ALERT_LEVEL_FATAL, ALERT_ILLEGAL_PARAMETER);
1401             return HITLS_MSG_HANDLE_ILLEGAL_SELECTED_GROUP;
1402         }
1403         if (cur->group != selectGroup) {
1404             continue;
1405         }
1406 
1407         *isNeedSendHrr = false;
1408         /* Obtain the peer public key */
1409         ctx->hsCtx->kxCtx->pubKeyLen = cur->keyExchangeSize;
1410         if (SAL_CRYPT_GetCryptLength(ctx, HITLS_CRYPT_INFO_CMD_GET_PUBLIC_KEY_LEN, keyShare->group) !=
1411             ctx->hsCtx->kxCtx->pubKeyLen) {
1412             BSL_ERR_PUSH_ERROR(HITLS_MSG_HANDLE_ILLEGAL_SELECTED_GROUP);
1413             BSL_LOG_BINLOG_FIXLEN(BINLOG_ID16189, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN,
1414                 "invalid keyShare length.", 0, 0, 0, 0);
1415             ctx->method.sendAlert(ctx, ALERT_LEVEL_FATAL, ALERT_ILLEGAL_PARAMETER);
1416             return HITLS_MSG_HANDLE_ILLEGAL_SELECTED_GROUP;
1417         }
1418         BSL_SAL_FREE(ctx->hsCtx->kxCtx->peerPubkey);
1419         ctx->hsCtx->kxCtx->peerPubkey = BSL_SAL_Dump(cur->keyExchange, cur->keyExchangeSize);
1420         if (ctx->hsCtx->kxCtx->peerPubkey == NULL) {
1421             BSL_ERR_PUSH_ERROR(HITLS_MEMALLOC_FAIL);
1422             BSL_LOG_BINLOG_FIXLEN(BINLOG_ID15245, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN,
1423                 "malloc peerPubkey fail when process client key share.", 0, 0, 0, 0);
1424             return HITLS_MEMALLOC_FAIL;
1425         }
1426 
1427         ctx->negotiatedInfo.negotiatedGroup = selectGroup;
1428         return HITLS_SUCCESS;
1429     }
1430 
1431     /* If the server selects a group that does not exist in the keyshare, the server needs to send a hello retry request
1432      */
1433     *isNeedSendHrr = true;
1434     return HITLS_SUCCESS;
1435 }
1436 #if defined(HITLS_TLS_FEATURE_SESSION) || defined(HITLS_TLS_FEATURE_PSK)
1437 
1438 static int32_t GetPskFromSession(TLS_Ctx *ctx, HITLS_Session *pskSession, uint8_t *psk, uint32_t pskLen,
1439     uint32_t *usedLen)
1440 {
1441     /* The session is available and the PSK is obtained */
1442     uint32_t tmpLen = pskLen;
1443     int32_t ret = HITLS_SESS_GetMasterKey(pskSession, psk, &tmpLen);
1444     if (ret != HITLS_SUCCESS) {
1445         /* An internal error occurs and cannot be continued. A failure message is returned and an alert message is sent
1446          */
1447         ctx->method.sendAlert(ctx, ALERT_LEVEL_FATAL, ALERT_INTERNAL_ERROR);
1448         return ret;
1449     }
1450 
1451     *usedLen = tmpLen;
1452     return HITLS_SUCCESS;
1453 }
1454 
1455 #ifdef HITLS_TLS_FEATURE_PSK
1456 static int32_t PskFindSession(TLS_Ctx *ctx, const uint8_t *id, uint32_t idLen, HITLS_Session **pskSession)
1457 {
1458     if (ctx->config.tlsConfig.pskFindSessionCb == NULL) {
1459         /* No callback is set */
1460         return HITLS_SUCCESS;
1461     }
1462 
1463     int32_t ret = ctx->config.tlsConfig.pskFindSessionCb(ctx, id, idLen, pskSession);
1464     if (ret != HITLS_PSK_FIND_SESSION_CB_SUCCESS) {
1465         /* Internal error, cannot continue */
1466         ctx->method.sendAlert(ctx, ALERT_LEVEL_FATAL, ALERT_INTERNAL_ERROR);
1467         return HITLS_MSG_HANDLE_PSK_FIND_SESSION_FAIL;
1468     }
1469     return HITLS_SUCCESS;
1470 }
1471 
1472 static int32_t GetPskByIdentity(TLS_Ctx *ctx, const uint8_t *id, uint32_t idLen, uint8_t *psk, uint32_t *pskLen)
1473 {
1474     if (ctx->config.tlsConfig.pskServerCb == NULL) {
1475         *pskLen = 0;
1476         return HITLS_SUCCESS;
1477     }
1478 
1479     uint8_t *strId = BSL_SAL_Calloc(1u, idLen + 1);
1480     if (strId == NULL) {
1481         BSL_LOG_BINLOG_FIXLEN(BINLOG_ID17056, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "Calloc fail", 0, 0, 0, 0);
1482         ctx->method.sendAlert(ctx, ALERT_LEVEL_FATAL, ALERT_INTERNAL_ERROR);
1483         return HITLS_MEMALLOC_FAIL;
1484     }
1485     (void)memcpy_s(strId, idLen + 1, id, idLen);
1486     strId[idLen] = '\0';
1487 
1488     uint32_t usedLen = ctx->config.tlsConfig.pskServerCb(ctx, strId, psk, *pskLen);
1489     BSL_SAL_FREE(strId);
1490     if (usedLen > HS_PSK_MAX_LEN) {
1491         BSL_LOG_BINLOG_FIXLEN(BINLOG_ID17057, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "usedLen err", 0, 0, 0, 0);
1492         ctx->method.sendAlert(ctx, ALERT_LEVEL_FATAL, ALERT_INTERNAL_ERROR);
1493         return HITLS_MSG_HANDLE_ILLEGAL_PSK_LEN;
1494     }
1495 
1496     *pskLen = usedLen;
1497     return HITLS_SUCCESS;
1498 }
1499 #endif /* HITLS_TLS_FEATURE_PSK */
1500 
1501 static int32_t Tls13ServerSetPskInfo(TLS_Ctx *ctx, uint8_t *psk, uint32_t pskLen, uint16_t index)
1502 {
1503     PskInfo13 *pskInfo13 = &ctx->hsCtx->kxCtx->pskInfo13;
1504     BSL_SAL_FREE(pskInfo13->psk);
1505     pskInfo13->psk = BSL_SAL_Dump(psk, pskLen);
1506     if (pskInfo13->psk == NULL) {
1507         BSL_LOG_BINLOG_FIXLEN(BINLOG_ID17058, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "Dump fail", 0, 0, 0, 0);
1508         ctx->method.sendAlert(ctx, ALERT_LEVEL_FATAL, ALERT_INTERNAL_ERROR);
1509         return HITLS_MEMALLOC_FAIL;
1510     }
1511     pskInfo13->pskLen = pskLen;
1512     pskInfo13->selectIndex = index;
1513     return HITLS_SUCCESS;
1514 }
1515 
1516 static bool IsPSKValid(TLS_Ctx *ctx, HITLS_Session *pskSession)
1517 {
1518     uint16_t version, cipherSuite;
1519     HITLS_SESS_GetProtocolVersion(pskSession, &version);
1520     if (version != HITLS_VERSION_TLS13) {
1521         return false;
1522     }
1523 
1524     HITLS_SESS_GetCipherSuite(pskSession, &cipherSuite);
1525     CipherSuiteInfo cipherInfo = {0};
1526     int32_t ret = CFG_GetCipherSuiteInfo(cipherSuite, &cipherInfo);
1527     if (ret != HITLS_SUCCESS) {
1528         BSL_LOG_BINLOG_FIXLEN(BINLOG_ID17059, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN,
1529             "GetCipherSuiteInfo fail", 0, 0, 0, 0);
1530         return false;
1531     }
1532 
1533     if (cipherInfo.hashAlg != ctx->negotiatedInfo.cipherSuiteInfo.hashAlg) {
1534         return false;
1535     }
1536 
1537     return true;
1538 }
1539 
1540 static int32_t TLS13ServerProcessTicket(TLS_Ctx *ctx, PreSharedKey *cur,
1541     uint8_t *psk, uint32_t *pskLen)
1542 {
1543     const uint8_t *ticket = cur->identity;
1544     uint32_t ticketLen = cur->identitySize;
1545     bool isTicketExcept = 0;
1546     HITLS_Session *pskSession = NULL;
1547 
1548     int32_t ret = SESSMGR_DecryptSessionTicket(LIBCTX_FROM_CTX(ctx), ATTRIBUTE_FROM_CTX(ctx),
1549         ctx->config.tlsConfig.sessMgr, &pskSession, ticket, ticketLen, &isTicketExcept);
1550     if (ret != HITLS_SUCCESS) {
1551         BSL_LOG_BINLOG_FIXLEN(BINLOG_ID16048, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN,
1552             "Decrypt Ticket fail when processing client hello.", 0, 0, 0, 0);
1553         ctx->method.sendAlert(ctx, ALERT_LEVEL_FATAL, ALERT_INTERNAL_ERROR);
1554         return ret;
1555     }
1556 
1557     /* Do not resume the session. TLS1.3 does not need to check isTicketExceptt */
1558     if (pskSession == NULL) {
1559         *pskLen = 0;
1560         return HITLS_SUCCESS;
1561     }
1562 
1563     /* Check whether the session is valid */
1564     if (!IsPSKValid(ctx, pskSession) ||
1565         !SESS_CheckValidity(pskSession, (uint64_t)BSL_SAL_CurrentSysTimeGet())) {
1566         /* Do not resume the session */
1567         *pskLen = 0;
1568         HITLS_SESS_Free(pskSession);
1569         return HITLS_SUCCESS;
1570     }
1571 
1572     if (ServerCmpSessionIdCtx(ctx, pskSession) != true) {
1573         BSL_LOG_BINLOG_FIXLEN(BINLOG_ID16075, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN,
1574             "TLS1.3 Resuming Session: session id ctx is inconsistent.", 0, 0, 0, 0);
1575         ctx->method.sendAlert(ctx, ALERT_LEVEL_FATAL, ALERT_ILLEGAL_PARAMETER);
1576         HITLS_SESS_Free(pskSession);
1577         return HITLS_MSG_HANDLE_SESSION_ID_CTX_ILLEGAL;
1578     }
1579 
1580     ret = GetPskFromSession(ctx, pskSession, psk, *pskLen, pskLen);
1581     if (ret != HITLS_SUCCESS) {
1582         HITLS_SESS_Free(pskSession);
1583         return ret;
1584     }
1585 
1586     if (*pskLen == 0) {
1587         HITLS_SESS_Free(pskSession);
1588         return HITLS_SUCCESS;
1589     }
1590 
1591     HITLS_SESS_Free(ctx->session);
1592     ctx->session = pskSession;
1593     ctx->negotiatedInfo.isResume = true;
1594     return HITLS_SUCCESS;
1595 }
1596 
1597 static int32_t ServerFindPsk(TLS_Ctx *ctx, PreSharedKey *cur,
1598     uint8_t *psk, uint32_t *pskLen)
1599 {
1600     int32_t ret = HITLS_SUCCESS;
1601     ctx->negotiatedInfo.isResume = false;
1602 #ifdef HITLS_TLS_FEATURE_PSK
1603     const uint8_t *identity = cur->identity;
1604     uint32_t identitySize = cur->identitySize;
1605     uint32_t pskSize = *pskLen;
1606     HITLS_Session *pskSession = NULL;
1607     ret = PskFindSession(ctx, identity, identitySize, &pskSession);
1608     if (ret != HITLS_SUCCESS) {
1609         return ret;
1610     }
1611 
1612     /* TLS 1.3 processing */
1613     if (pskSession != NULL) {
1614         /* In TLS1.3, pskSession is transferred by the user. Check the corresponding version and cipher suite */
1615         if (IsPSKValid(ctx, pskSession) == false) {
1616             HITLS_SESS_Free(pskSession); /* Unsuitable sessions are released. */
1617             *pskLen = 0;
1618             return HITLS_SUCCESS;
1619         }
1620 
1621         ret = GetPskFromSession(ctx, pskSession, psk, pskSize, pskLen);
1622         HITLS_SESS_Free(pskSession); /* After the session is used, the session is released. */
1623         return ret;
1624     }
1625 
1626     /*
1627      * By default, the hash algorithm used by the pskSession cipher suite is SHA_256.
1628      * In this case, you only need to check whether the hash algorithm of the negotiated cipher suite is SHA_256.
1629      */
1630     if (ctx->negotiatedInfo.cipherSuiteInfo.hashAlg == HITLS_HASH_SHA_256) {
1631         ret = GetPskByIdentity(ctx, identity, identitySize, psk, &pskSize);
1632         if (ret != HITLS_SUCCESS) {
1633             /* An internal error occurs and the process cannot be continued. An error code is returned */
1634             return ret;
1635         }
1636         if (pskSize > 0u) {
1637             *pskLen = pskSize;
1638             return HITLS_SUCCESS;
1639         }
1640     }
1641 #endif /* HITLS_TLS_FEATURE_PSK */
1642 #ifdef HITLS_TLS_FEATURE_SESSION_TICKET
1643     /* Try to decrypt the ticket for session resumption */
1644     ret = TLS13ServerProcessTicket(ctx, cur, psk, pskLen);
1645 #else
1646     if (ret == HITLS_SUCCESS && *pskLen != 0) {
1647         *pskLen = 0;
1648         return HITLS_SUCCESS;
1649     }
1650 #endif
1651     return ret;
1652 }
1653 
1654 int32_t CompareBinder(TLS_Ctx *ctx, const PreSharedKey *pskNode, uint8_t *psk, uint32_t pskLen,
1655     uint32_t truncateHelloLen)
1656 {
1657     int32_t ret;
1658     uint8_t *recvBinder = pskNode->binder;
1659     uint32_t recvBinderLen = pskNode->binderSize;
1660     HITLS_HashAlgo hashAlg = ctx->negotiatedInfo.cipherSuiteInfo.hashAlg;
1661     bool isExternalPsk = !(ctx->negotiatedInfo.isResume);
1662     uint8_t computedBinder[HS_MAX_BINDER_SIZE] = {0};
1663 
1664     uint32_t binderLen = HS_GetBinderLen(NULL, &hashAlg);
1665     if (binderLen == 0 || binderLen != recvBinderLen || binderLen > HS_MAX_BINDER_SIZE) {
1666         BSL_LOG_BINLOG_FIXLEN(BINLOG_ID17060, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN,
1667             "binderLen err", 0, 0, 0, 0);
1668         return HITLS_INTERNAL_EXCEPTION;
1669     }
1670 
1671     ret = VERIFY_CalcPskBinder(ctx, hashAlg, isExternalPsk, psk, pskLen, ctx->hsCtx->msgBuf, truncateHelloLen,
1672         computedBinder, binderLen);
1673     if (ret != HITLS_SUCCESS) {
1674         return ret;
1675     }
1676     ret = memcmp(computedBinder, recvBinder, binderLen);
1677     if (ret != 0) {
1678         BSL_LOG_BINLOG_FIXLEN(BINLOG_ID17061, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN,
1679             "memcmp fail, ret %d", ret, 0, 0, 0);
1680         return HITLS_INTERNAL_EXCEPTION;
1681     }
1682     return ret;
1683 }
1684 
1685 /* Prior to accepting PSK key establishment, the server MUST validate the corresponding binder value (see
1686 Section 4.2.11.2 below). If this value is not present or does not validate, the server MUST abort the handshake. Servers
1687 SHOULD NOT attempt to validate multiple binders; rather, they SHOULD select a single PSK and validate solely the binder
1688 that corresponds to that PSK.
1689 */
1690 static int32_t ServerSelectPskAndCheckBinder(TLS_Ctx *ctx, const ClientHelloMsg *clientHello)
1691 {
1692     int32_t ret = HITLS_SUCCESS;
1693     uint16_t index = 0;
1694 
1695     uint8_t psk[HS_PSK_MAX_LEN] = {0};
1696 
1697     ListHead *node = NULL;
1698     ListHead *tmpNode = NULL;
1699     PreSharedKey *cur = NULL;
1700     PreSharedKey *offeredPsks = clientHello->extension.content.preSharedKey;
1701 
1702     LIST_FOR_EACH_ITEM_SAFE(node, tmpNode, &(offeredPsks->pskNode))
1703     {
1704         uint32_t pskLen = HS_PSK_MAX_LEN;
1705         cur = LIST_ENTRY(node, PreSharedKey, pskNode);
1706 
1707         ret = ServerFindPsk(ctx, cur, psk, &pskLen);
1708         if (ret != HITLS_SUCCESS) {
1709             return ret;
1710         }
1711 
1712         if (pskLen == 0) {
1713             index++;
1714             /* The corresponding psk cannot be found. Search for the next psk */
1715             continue;
1716         }
1717         /* An available psk is found */
1718         ret = Tls13ServerSetPskInfo(ctx, psk, pskLen, index);
1719         if (ret != HITLS_SUCCESS) {
1720             (void)memset_s(psk, HS_PSK_MAX_LEN, 0, HS_PSK_MAX_LEN); /* Clear sensitive memory */
1721             return ret;
1722         }
1723         ret = CompareBinder(ctx, cur, psk, pskLen, clientHello->truncateHelloLen);
1724         (void)memset_s(psk, HS_PSK_MAX_LEN, 0, HS_PSK_MAX_LEN); /* Clear sensitive memory */
1725         if (ret != HITLS_SUCCESS) {
1726             /* RFC8446 Section 6.2:decrypt_error:  A handshake (not record layer) cryptographic
1727                 operation failed, including being unable to correctly verify a
1728                 signature or validate a Finished message or a PSK binder. */
1729             ctx->method.sendAlert(ctx, ALERT_LEVEL_FATAL, ALERT_DECRYPT_ERROR);
1730             return ret;
1731         }
1732         cur->isValid = true;
1733         break;
1734     }
1735     return ret;
1736 }
1737 #endif
1738 static int32_t Tls13ServerSetSessionId(TLS_Ctx *ctx, const uint8_t *sessionId, uint32_t sessionIdSize)
1739 {
1740     if (sessionIdSize == 0) {
1741         ctx->hsCtx->sessionIdSize = sessionIdSize;
1742         return HITLS_SUCCESS;
1743     }
1744 
1745     uint8_t *tmpSession = BSL_SAL_Dump(sessionId, sessionIdSize);
1746     if (tmpSession == NULL) {
1747         BSL_ERR_PUSH_ERROR(HITLS_MEMALLOC_FAIL);
1748         BSL_LOG_BINLOG_FIXLEN(BINLOG_ID15248, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN,
1749             "malloc sessionId fail when process client hello.", 0, 0, 0, 0);
1750         ctx->method.sendAlert(ctx, ALERT_LEVEL_FATAL, ALERT_INTERNAL_ERROR);
1751         return HITLS_MEMALLOC_FAIL;
1752     }
1753     BSL_SAL_FREE(ctx->hsCtx->sessionId); // Clearing old memory
1754     ctx->hsCtx->sessionId = tmpSession;
1755     ctx->hsCtx->sessionIdSize = sessionIdSize;
1756     return HITLS_SUCCESS;
1757 }
1758 
1759 static int32_t Tls13ServerCheckClientHelloExtension(TLS_Ctx *ctx, const ClientHelloMsg *clientHello)
1760 {
1761     do {
1762         /* If not containing a "pre_shared_key" extension, it MUST contain
1763         both a "signature_algorithms" extension and a "supported_groups"
1764         extension. */
1765         if ((!clientHello->extension.flag.havePreShareKey) && (!clientHello->extension.flag.haveSignatureAlgorithms ||
1766             !clientHello->extension.flag.haveSupportedGroups)) {
1767             break;
1768         }
1769 
1770         /* If containing a "supported_groups" extension, it MUST also contain
1771         a "key_share" extension, and vice versa. */
1772         if ((clientHello->extension.flag.haveSupportedGroups && !clientHello->extension.flag.haveKeyShare) ||
1773             (!clientHello->extension.flag.haveSupportedGroups && clientHello->extension.flag.haveKeyShare)) {
1774             break;
1775         }
1776 
1777         /* A client MUST provide a "psk_key_exchange_modes" extension if it
1778             offers a "pre_shared_key" extension. */
1779         if (clientHello->extension.flag.havePreShareKey && !clientHello->extension.flag.havePskExMode) {
1780             break;
1781         }
1782 
1783         // with psk && psk mode is dhe && without keyshare
1784         uint32_t clientKeMode = GetClientKeMode(&clientHello->extension.content);
1785         if (clientHello->extension.flag.havePreShareKey &&
1786             (clientKeMode & TLS13_KE_MODE_PSK_WITH_DHE) == TLS13_KE_MODE_PSK_WITH_DHE &&
1787             !clientHello->extension.flag.haveKeyShare) {
1788             break;
1789         }
1790         return HITLS_SUCCESS;
1791     } while (false);
1792     BSL_ERR_PUSH_ERROR(HITLS_MSG_HANDLE_MISSING_EXTENSION);
1793     BSL_LOG_BINLOG_FIXLEN(BINLOG_ID16139, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN,
1794         "invalid client hello: missing extension.", 0, 0, 0, 0);
1795     ctx->method.sendAlert(ctx, ALERT_LEVEL_FATAL, ALERT_MISSING_EXTENSION);
1796     return HITLS_MSG_HANDLE_MISSING_EXTENSION;
1797 }
1798 
1799 static int32_t Tls13ServerCheckSecondClientHello(TLS_Ctx *ctx, ClientHelloMsg *clientHello)
1800 {
1801     if (ctx->hsCtx->haveHrr) {
1802         if (ctx->hsCtx->firstClientHello->cipherSuitesSize != clientHello->cipherSuitesSize ||
1803             memcmp(ctx->hsCtx->firstClientHello->cipherSuites, clientHello->cipherSuites,
1804             clientHello->cipherSuitesSize * sizeof(uint16_t)) != 0) {
1805             BSL_LOG_BINLOG_FIXLEN(BINLOG_ID17062, BSL_LOG_LEVEL_DEBUG, BSL_LOG_BINLOG_TYPE_RUN,
1806                 "Server's cipher suites do not match client's cipher suite.", 0, 0, 0, 0);
1807             ctx->method.sendAlert(ctx, ALERT_LEVEL_FATAL, ALERT_ILLEGAL_PARAMETER);
1808             return HITLS_MSG_HANDLE_ILLEGAL_CIPHER_SUITE;
1809         }
1810         return HITLS_SUCCESS;
1811     }
1812     if (ctx->hsCtx->firstClientHello != NULL) {
1813         BSL_LOG_BINLOG_FIXLEN(BINLOG_ID17063, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN,
1814             "internal exception occurs", 0, 0, 0, 0);
1815         ctx->method.sendAlert(ctx, ALERT_LEVEL_FATAL, ALERT_INTERNAL_ERROR);
1816         return HITLS_INTERNAL_EXCEPTION;
1817     }
1818     ctx->hsCtx->firstClientHello = (ClientHelloMsg *)BSL_SAL_Dump(clientHello, sizeof(ClientHelloMsg));
1819     if (ctx->hsCtx->firstClientHello == NULL) {
1820         BSL_ERR_PUSH_ERROR(HITLS_MEMALLOC_FAIL);
1821         BSL_LOG_BINLOG_FIXLEN(BINLOG_ID16147, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "clientHello malloc fail.", 0,
1822             0, 0, 0);
1823         return HITLS_MEMALLOC_FAIL;
1824     }
1825     clientHello->refCnt = 1;
1826     return HITLS_SUCCESS;
1827 }
1828 static int32_t Tls13ServerCheckCompressionMethods(TLS_Ctx *ctx, const ClientHelloMsg *clientHello)
1829 {
1830     if (clientHello->compressionMethodsSize != 1u) {
1831         BSL_ERR_PUSH_ERROR(HITLS_MSG_HANDLE_INVALID_COMPRESSION_METHOD);
1832         BSL_LOG_BINLOG_FIXLEN(BINLOG_ID16162, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN,
1833             "the compression length of client hello is incorrect.", 0, 0, 0, 0);
1834         ctx->method.sendAlert(ctx, ALERT_LEVEL_FATAL, ALERT_ILLEGAL_PARAMETER);
1835         return HITLS_MSG_HANDLE_INVALID_COMPRESSION_METHOD;
1836     }
1837 
1838     /* If the compression method list contains no compression, return success */
1839     // If the compression method contains no compression (0), a parsing success message is returne
1840     if (clientHello->compressionMethods[0] == 0u) {
1841         return HITLS_SUCCESS;
1842     }
1843     BSL_ERR_PUSH_ERROR(HITLS_MSG_HANDLE_INVALID_COMPRESSION_METHOD);
1844     BSL_LOG_BINLOG_FIXLEN(BINLOG_ID16163, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN,
1845         "can not find a appropriate compression method in client hello.", 0, 0, 0, 0);
1846     ctx->method.sendAlert(ctx, ALERT_LEVEL_FATAL, ALERT_ILLEGAL_PARAMETER);
1847     return HITLS_MSG_HANDLE_INVALID_COMPRESSION_METHOD;
1848 }
1849 
1850 static int32_t Tls13ServerBasicCheckClientHello(TLS_Ctx *ctx, ClientHelloMsg *clientHello)
1851 {
1852     int32_t ret = Tls13ServerCheckSecondClientHello(ctx, clientHello);
1853     if (ret != HITLS_SUCCESS) {
1854         return ret;
1855     }
1856 
1857     /* Set the negotiated version number */
1858     ctx->negotiatedInfo.version = HITLS_VERSION_TLS13;
1859 
1860     ret = Tls13ServerCheckCompressionMethods(ctx, clientHello);
1861     if (ret != HITLS_SUCCESS) {
1862         return ret;
1863     }
1864     /* Copy random numbers */
1865     ret = memcpy_s(ctx->hsCtx->clientRandom, HS_RANDOM_SIZE, clientHello->randomValue, HS_RANDOM_SIZE);
1866     if (ret != EOK) {
1867         return ret;
1868     }
1869 
1870     /* Copy the session ID */
1871     ret = Tls13ServerSetSessionId(ctx, clientHello->sessionId, clientHello->sessionIdSize);
1872     if (ret != HITLS_SUCCESS) {
1873         return ret;
1874     }
1875 
1876     return ServerSelectCipherSuite(ctx, clientHello);
1877 }
1878 
1879 static int32_t Tls13ServerSelectCert(TLS_Ctx *ctx, const ClientHelloMsg *clientHello)
1880 {
1881     /* If a PSK exists, no certificate needs to be sent regardless of whether the PSK is psk_only or psk_with_dhe */
1882     if (ctx->hsCtx->kxCtx->pskInfo13.psk != NULL) {
1883         return HITLS_SUCCESS;
1884     }
1885 
1886     /* rfc 8446 4.2.3. If the client does not provide the signature algorithm extension, an alert message must be sent.
1887      */
1888     if (clientHello->extension.content.signatureAlgorithms == NULL) {
1889         BSL_LOG_BINLOG_FIXLEN(BINLOG_ID17065, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN,
1890             "miss signatureAlgorithms extension", 0, 0, 0, 0);
1891         ctx->method.sendAlert(ctx, ALERT_LEVEL_FATAL, ALERT_MISSING_EXTENSION);
1892         return HITLS_MSG_HANDLE_MISSING_EXTENSION;
1893     }
1894 
1895     CERT_ExpectInfo expectCertInfo = {0};
1896     expectCertInfo.certType = CERT_TYPE_UNKNOWN; /* Do not specify the certificate type */
1897     expectCertInfo.signSchemeList = clientHello->extension.content.signatureAlgorithms;
1898     expectCertInfo.signSchemeNum = clientHello->extension.content.signatureAlgorithmsSize;
1899 
1900     /* Only the uncompressed format is supported */
1901     uint8_t pointFormat = HITLS_POINT_FORMAT_UNCOMPRESSED;
1902     expectCertInfo.ecPointFormatList = &pointFormat;
1903     expectCertInfo.ecPointFormatNum = 1u;
1904 
1905     int32_t ret =  SAL_CERT_SelectCertByInfo(ctx, &expectCertInfo);
1906     if (ret != HITLS_SUCCESS) {
1907         /* No proper certificate */
1908         BSL_LOG_BINLOG_FIXLEN(BINLOG_ID15219, BSL_LOG_LEVEL_INFO, BSL_LOG_BINLOG_TYPE_RUN,
1909             "have no suitable cert. ret %d", ret, 0, 0, 0);
1910         ctx->method.sendAlert(ctx, ALERT_LEVEL_FATAL, ALERT_HANDSHAKE_FAILURE);
1911         return HITLS_MSG_HANDLE_ERR_NO_SERVER_CERTIFICATE;
1912     }
1913     return HITLS_SUCCESS;
1914 }
1915 
1916 static int32_t Tls13ServerCheckClientHello(TLS_Ctx *ctx, ClientHelloMsg *clientHello, bool *isNeedSendHrr)
1917 {
1918     uint32_t selectKeMode = 0;
1919 
1920     int32_t ret = Tls13ServerBasicCheckClientHello(ctx, clientHello);
1921     if (ret != HITLS_SUCCESS) {
1922         return ret;
1923     }
1924 
1925     /* rfc8446 9.2.  Mandatory-to-Implement Extensions */
1926     ret = Tls13ServerCheckClientHelloExtension(ctx, clientHello);
1927     if (ret != HITLS_SUCCESS) {
1928         return ret;
1929     }
1930 
1931     uint32_t clientKeMode = GetClientKeMode(&clientHello->extension.content);
1932     selectKeMode = clientKeMode & ctx->config.tlsConfig.keyExchMode;
1933 #if defined(HITLS_TLS_FEATURE_SESSION) || defined(HITLS_TLS_FEATURE_PSK)
1934     if (clientHello->extension.flag.havePreShareKey && selectKeMode != 0) {
1935         /* calculate the binder value and compare it with the received binder value. */
1936         ret = ServerSelectPskAndCheckBinder(ctx, clientHello);
1937         if (ret != HITLS_SUCCESS) {
1938             BSL_ERR_PUSH_ERROR(HITLS_MSG_HANDLE_PSK_INVALID);
1939             BSL_LOG_BINLOG_FIXLEN(BINLOG_ID15940, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN,
1940                 "ServerSelectPskAndCheckBinder failed. ret %d", ret, 0, 0, 0);
1941             return HITLS_MSG_HANDLE_PSK_INVALID;
1942         }
1943     }
1944 #endif
1945     if (ctx->hsCtx->kxCtx->pskInfo13.psk == NULL ||
1946         (selectKeMode & TLS13_KE_MODE_PSK_WITH_DHE) == TLS13_KE_MODE_PSK_WITH_DHE) {
1947         ret = Tls13ServerProcessKeyShare(ctx, clientHello, isNeedSendHrr);
1948         /* The group has been selected during the cipher suite selection. Therefore, the keyshare can be processed here
1949          */
1950         if (ret != HITLS_SUCCESS) {
1951             return ret;
1952         }
1953     }
1954     ret = ProcessClientHelloExt(ctx, clientHello, (*isNeedSendHrr));
1955     if (ret != HITLS_SUCCESS) {
1956         return ret;
1957     }
1958     return Tls13ServerSelectCert(ctx, clientHello);
1959 }
1960 
1961 static int32_t CheckVersion(TLS_Ctx *ctx, uint16_t version, uint16_t minVersion, uint16_t maxVersion, uint16_t *selectVersion)
1962 {
1963     if (version >= HITLS_VERSION_TLS13 && !IS_SUPPORT_DATAGRAM(ctx->config.tlsConfig.originVersionMask)) {
1964         version = HITLS_VERSION_TLS12;
1965     }
1966 #ifdef HITLS_TLS_PROTO_TLCP11
1967     if (((version > HITLS_VERSION_SSL30) || (version == HITLS_VERSION_TLCP_DTLCP11)) &&
1968 #else
1969     if ((version > HITLS_VERSION_SSL30) &&
1970 #endif /* HITLS_TLS_PROTO_TLCP11 */
1971         (minVersion <= version) && (version <= maxVersion)) {
1972         *selectVersion = version;
1973         return HITLS_SUCCESS;
1974     }
1975     BSL_LOG_BINLOG_FIXLEN(BINLOG_ID17066, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN,
1976         "negotiate version fail", 0, 0, 0, 0);
1977     return HITLS_MSG_HANDLE_UNSUPPORT_VERSION;
1978 }
1979 
1980 bool IsTls13KeyExchAvailable(TLS_Ctx *ctx)
1981 {
1982     TLS_Config *config = &ctx->config.tlsConfig;
1983     CERT_MgrCtx *certMgrCtx = config->certMgrCtx;
1984 #ifdef HITLS_TLS_FEATURE_PSK
1985     if (config->pskServerCb != NULL) {
1986         return true;
1987     }
1988 
1989     if (config->pskFindSessionCb != NULL) {
1990         return true;
1991     }
1992 #endif /* HITLS_TLS_FEATURE_PSK */
1993     /* The PSK is not used. The certificate must be set */
1994     BSL_HASH_Hash *certPairs = certMgrCtx->certPairs;
1995     BSL_HASH_Iterator it = BSL_HASH_IterBegin(certPairs);
1996     while (it != BSL_HASH_IterEnd(certPairs)) {
1997         uint32_t keyType = (uint32_t)BSL_HASH_HashIterKey(certPairs, it);
1998         if (keyType == TLS_CERT_KEY_TYPE_DSA) {
1999              /* in TLS1.3, Do not use the DSA certificate. */
2000             it = BSL_HASH_IterNext(certPairs, it);
2001             continue;
2002         }
2003         CERT_Pair *certPair = (CERT_Pair *)BSL_HASH_IterValue(certPairs, it);
2004         if (certPair != NULL && certPair->cert != NULL && certPair->privateKey != NULL) {
2005             return true;
2006         }
2007         it = BSL_HASH_IterNext(certPairs, it);
2008     }
2009     return false;
2010 }
2011 
2012 static int32_t SelectVersion(TLS_Ctx *ctx, const ClientHelloMsg *clientHello, uint16_t minVersion, uint16_t maxVersion,
2013     uint16_t *selectVersion)
2014 {
2015     int32_t ret;
2016     uint16_t version = clientHello->version;
2017 
2018     /**
2019      * According to rfc8446 section 4.2.1 if the ClientHello does not have the supportedVersions extension,
2020      * Then the server must negotiate TLS 1.2 or earlier as specified in rfc5246.
2021      */
2022     if (clientHello->extension.content.supportedVersionsCount == 0) {
2023         ret = CheckVersion(ctx, version, minVersion, maxVersion, selectVersion);
2024         if (ret != HITLS_SUCCESS) {
2025             BSL_ERR_PUSH_ERROR(HITLS_MSG_HANDLE_UNSUPPORT_VERSION);
2026             BSL_LOG_BINLOG_FIXLEN(BINLOG_ID16134, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN,
2027                 "server cannot negotiate a version.", 0, 0, 0, 0);
2028             ctx->method.sendAlert(ctx, ALERT_LEVEL_FATAL, ALERT_PROTOCOL_VERSION);
2029         }
2030         return ret;
2031     }
2032 
2033     /* If the received message is not an earlier version, the version byte in the tls1.3 must be 0x0303 according to
2034      * section 4.1.2 in RFC 8446 */
2035     if (version != HITLS_VERSION_TLS12) {
2036         BSL_ERR_PUSH_ERROR(HITLS_MSG_HANDLE_UNSUPPORT_VERSION);
2037         BSL_LOG_BINLOG_FIXLEN(BINLOG_ID15249, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN,
2038             "illegal client legacy_version(0x%02x).", version, 0, 0, 0);
2039         ctx->method.sendAlert(ctx, ALERT_LEVEL_FATAL, ALERT_PROTOCOL_VERSION);
2040         return HITLS_MSG_HANDLE_UNSUPPORT_VERSION;
2041     }
2042 
2043     /* Find the supported version in the extended field supportedVersions. */
2044     for (version = maxVersion; version >= minVersion; version--) {
2045         for (int i = 0; i < clientHello->extension.content.supportedVersionsCount; i++) {
2046             if (clientHello->extension.content.supportedVersions[i] != version) {
2047                 continue;
2048             }
2049             if (((version == HITLS_VERSION_TLS13) && (!IsTls13KeyExchAvailable(ctx))) ||
2050                 (version <= HITLS_VERSION_SSL30)) {
2051                 /* TLS1.3 must have an available PSK or certificate, and TLS1.3 cannot negotiate SSL versions earlier
2052                  * than SSL3.0. */
2053                 continue;
2054             }
2055             /* rfc8446 4.2.1 The server must be ready to receive ClientHello that contains the supportedVersions
2056              * extension but does not contain 0x0304 in the version list, Therefore, if a matching version is found,
2057              * even if the version is an earlier version, the system directly returns */
2058             *selectVersion = version;
2059             return HITLS_SUCCESS;
2060         }
2061     }
2062 
2063     BSL_ERR_PUSH_ERROR(HITLS_MSG_HANDLE_UNSUPPORT_VERSION);
2064     BSL_LOG_BINLOG_FIXLEN(BINLOG_ID15250, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN,
2065         "server cannot negotiate a version.", 0, 0, 0, 0);
2066     ctx->method.sendAlert(ctx, ALERT_LEVEL_FATAL, ALERT_PROTOCOL_VERSION);
2067     return HITLS_MSG_HANDLE_UNSUPPORT_VERSION;
2068 }
2069 
2070 static int32_t UpdateServerBaseKeyExMode(TLS_Ctx *ctx)
2071 {
2072     uint32_t tls13BasicKeyExMode = 0;
2073     KeyExchCtx *kxCtx = ctx->hsCtx->kxCtx;
2074     if (kxCtx->pskInfo13.psk != NULL && kxCtx->peerPubkey != NULL) {
2075         tls13BasicKeyExMode = TLS13_KE_MODE_PSK_WITH_DHE;
2076     } else if (kxCtx->pskInfo13.psk != NULL) {
2077         tls13BasicKeyExMode = TLS13_KE_MODE_PSK_ONLY;
2078     } else if (kxCtx->peerPubkey != NULL) {
2079         tls13BasicKeyExMode = TLS13_CERT_AUTH_WITH_DHE;
2080     } else {
2081         BSL_LOG_BINLOG_FIXLEN(BINLOG_ID17067, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN,
2082             "psk and peerPubkey are null", 0, 0, 0, 0);
2083         // kxCtx->pskInfo13.psk == NULL && kxCtx->peerPubkey == NULL 由Tls13ServerCheckClientHello保证不会在此出现
2084         BSL_ERR_PUSH_ERROR(HITLS_INTERNAL_EXCEPTION);
2085         return HITLS_INTERNAL_EXCEPTION;
2086     }
2087     ctx->negotiatedInfo.tls13BasicKeyExMode = tls13BasicKeyExMode;
2088     return HITLS_SUCCESS;
2089 }
2090 
2091 static int32_t Tls13ServerProcessClientHello(TLS_Ctx *ctx, HS_Msg *msg)
2092 {
2093     int32_t ret = HITLS_SUCCESS;
2094     ClientHelloMsg *clientHello = &msg->body.clientHello;
2095 
2096     /* An unencrypted CCS may be received after sending or receiving the first ClientHello according to RFC 8446 */
2097     ctx->method.ctrlCCS(ctx, CCS_CMD_RECV_READY);
2098 
2099     bool isNeedSendHrr = false;
2100     /* Processing Client Hello Packets */
2101     ret = Tls13ServerCheckClientHello(ctx, clientHello, &isNeedSendHrr);
2102     if (ret != HITLS_SUCCESS) {
2103         return ret;
2104     }
2105 
2106     if (isNeedSendHrr) {
2107         return HS_ChangeState(ctx, TRY_SEND_HELLO_RETRY_REQUEST);
2108     }
2109     ret = UpdateServerBaseKeyExMode(ctx);
2110     if (ret != HITLS_SUCCESS) {
2111         return ret;
2112     }
2113 #ifdef HITLS_TLS_FEATURE_PHA
2114     TLS_Config *tlsConfig = &ctx->config.tlsConfig;
2115     if (ctx->phaState == PHA_NONE && tlsConfig->isSupportClientVerify && tlsConfig->isSupportPostHandshakeAuth &&
2116         msg->body.clientHello.extension.flag.havePostHsAuth) {
2117         ctx->phaState = PHA_EXTENSION;
2118     }
2119 #endif /* HITLS_TLS_FEATURE_PHA */
2120     return HS_ChangeState(ctx, TRY_SEND_SERVER_HELLO);
2121 }
2122 
2123 int32_t Tls13ServerRecvClientHelloProcess(TLS_Ctx *ctx, HS_Msg *msg)
2124 {
2125     int32_t ret = 0;
2126     uint16_t selectedVersion = 0;
2127     ClientHelloMsg *clientHello = &msg->body.clientHello;
2128     TLS_Config *tlsConfig = &ctx->config.tlsConfig;
2129 #ifdef HITLS_TLS_FEATURE_SNI
2130     /* Perform the ClientHello callback. The pause handshake status is not considered */
2131     ret = ClientHelloCbCheck(ctx);
2132     if (ret != HITLS_SUCCESS) {
2133         return ret;
2134     }
2135 #endif /* HITLS_TLS_FEATURE_SNI */
2136     ret = SelectVersion(ctx, clientHello, tlsConfig->minVersion, tlsConfig->maxVersion, &selectedVersion);
2137     if (ret != HITLS_SUCCESS) {
2138         return ret;
2139     }
2140 
2141     /* If the TLS version is earlier than 1.3, the ServerHello.version parameter must be set on the server and the
2142      * supported_versions extension cannot be sent */
2143     clientHello->version = selectedVersion;
2144 
2145     switch (selectedVersion) {
2146 #ifdef HITLS_TLS_PROTO_TLS_BASIC
2147         case HITLS_VERSION_TLS12:
2148             BSL_LOG_BINLOG_FIXLEN(BINLOG_ID15251, BSL_LOG_LEVEL_INFO, BSL_LOG_BINLOG_TYPE_RUN,
2149                 "tls1.3 server receive a 0x%x clientHello.", selectedVersion, 0, 0, 0);
2150             return Tls12ServerRecvClientHelloProcess(ctx, msg);
2151 #endif /* HITLS_TLS_PROTO_TLS_BASIC */
2152         case HITLS_VERSION_TLS13:
2153             return Tls13ServerProcessClientHello(ctx, msg);
2154         default:
2155             break;
2156     }
2157     BSL_ERR_PUSH_ERROR(HITLS_MSG_HANDLE_UNSUPPORT_VERSION);
2158     BSL_LOG_BINLOG_FIXLEN(BINLOG_ID15252, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN,
2159         "server select an unsupported version.", 0, 0, 0, 0);
2160     return HITLS_MSG_HANDLE_UNSUPPORT_VERSION;
2161 }
2162 #endif /* HITLS_TLS_PROTO_TLS13 */
2163 #endif /* HITLS_TLS_HOST_SERVER */
2164