1/*
2 *  TLS client-side functions
3 *
4 *  Copyright The Mbed TLS Contributors
5 *  SPDX-License-Identifier: Apache-2.0 OR GPL-2.0-or-later
6 */
7
8#include "common.h"
9
10#if defined(MBEDTLS_SSL_CLI_C) && defined(MBEDTLS_SSL_PROTO_TLS1_2)
11
12#include "mbedtls/platform.h"
13
14#include "mbedtls/ssl.h"
15#include "ssl_client.h"
16#include "ssl_misc.h"
17#include "debug_internal.h"
18#include "mbedtls/error.h"
19#include "mbedtls/constant_time.h"
20
21#if defined(MBEDTLS_USE_PSA_CRYPTO)
22#include "psa_util_internal.h"
23#include "psa/crypto.h"
24#if defined(MBEDTLS_KEY_EXCHANGE_ECDHE_PSK_ENABLED)
25/* Define a local translating function to save code size by not using too many
26 * arguments in each translating place. */
27static int local_err_translation(psa_status_t status)
28{
29    return psa_status_to_mbedtls(status, psa_to_ssl_errors,
30                                 ARRAY_LENGTH(psa_to_ssl_errors),
31                                 psa_generic_status_to_mbedtls);
32}
33#define PSA_TO_MBEDTLS_ERR(status) local_err_translation(status)
34#endif /* MBEDTLS_KEY_EXCHANGE_ECDHE_PSK_ENABLED */
35#endif /* MBEDTLS_USE_PSA_CRYPTO */
36
37#include <string.h>
38
39#include <stdint.h>
40
41#if defined(MBEDTLS_HAVE_TIME)
42#include "mbedtls/platform_time.h"
43#endif
44
45#if defined(MBEDTLS_SSL_SESSION_TICKETS)
46#include "mbedtls/platform_util.h"
47#endif
48
49#if defined(MBEDTLS_SSL_RENEGOTIATION)
50MBEDTLS_CHECK_RETURN_CRITICAL
51static int ssl_write_renegotiation_ext(mbedtls_ssl_context *ssl,
52                                       unsigned char *buf,
53                                       const unsigned char *end,
54                                       size_t *olen)
55{
56    unsigned char *p = buf;
57
58    *olen = 0;
59
60    /* We're always including a TLS_EMPTY_RENEGOTIATION_INFO_SCSV in the
61     * initial ClientHello, in which case also adding the renegotiation
62     * info extension is NOT RECOMMENDED as per RFC 5746 Section 3.4. */
63    if (ssl->renego_status != MBEDTLS_SSL_RENEGOTIATION_IN_PROGRESS) {
64        return 0;
65    }
66
67    MBEDTLS_SSL_DEBUG_MSG(3,
68                          ("client hello, adding renegotiation extension"));
69
70    MBEDTLS_SSL_CHK_BUF_PTR(p, end, 5 + ssl->verify_data_len);
71
72    /*
73     * Secure renegotiation
74     */
75    MBEDTLS_PUT_UINT16_BE(MBEDTLS_TLS_EXT_RENEGOTIATION_INFO, p, 0);
76    p += 2;
77
78    *p++ = 0x00;
79    *p++ = MBEDTLS_BYTE_0(ssl->verify_data_len + 1);
80    *p++ = MBEDTLS_BYTE_0(ssl->verify_data_len);
81
82    memcpy(p, ssl->own_verify_data, ssl->verify_data_len);
83
84    *olen = 5 + ssl->verify_data_len;
85
86    return 0;
87}
88#endif /* MBEDTLS_SSL_RENEGOTIATION */
89
90#if defined(MBEDTLS_KEY_EXCHANGE_SOME_ECDH_OR_ECDHE_1_2_ENABLED) || \
91    defined(MBEDTLS_KEY_EXCHANGE_ECDSA_CERT_REQ_ALLOWED_ENABLED) || \
92    defined(MBEDTLS_KEY_EXCHANGE_ECJPAKE_ENABLED)
93
94MBEDTLS_CHECK_RETURN_CRITICAL
95static int ssl_write_supported_point_formats_ext(mbedtls_ssl_context *ssl,
96                                                 unsigned char *buf,
97                                                 const unsigned char *end,
98                                                 size_t *olen)
99{
100    unsigned char *p = buf;
101    (void) ssl; /* ssl used for debugging only */
102
103    *olen = 0;
104
105    MBEDTLS_SSL_DEBUG_MSG(3,
106                          ("client hello, adding supported_point_formats extension"));
107    MBEDTLS_SSL_CHK_BUF_PTR(p, end, 6);
108
109    MBEDTLS_PUT_UINT16_BE(MBEDTLS_TLS_EXT_SUPPORTED_POINT_FORMATS, p, 0);
110    p += 2;
111
112    *p++ = 0x00;
113    *p++ = 2;
114
115    *p++ = 1;
116    *p++ = MBEDTLS_ECP_PF_UNCOMPRESSED;
117
118    *olen = 6;
119
120    return 0;
121}
122#endif /* MBEDTLS_KEY_EXCHANGE_SOME_ECDH_OR_ECDHE_1_2_ENABLED ||
123          MBEDTLS_KEY_EXCHANGE_ECDSA_CERT_REQ_ALLOWED_ENABLED ||
124          MBEDTLS_KEY_EXCHANGE_ECJPAKE_ENABLED */
125
126#if defined(MBEDTLS_KEY_EXCHANGE_ECJPAKE_ENABLED)
127MBEDTLS_CHECK_RETURN_CRITICAL
128static int ssl_write_ecjpake_kkpp_ext(mbedtls_ssl_context *ssl,
129                                      unsigned char *buf,
130                                      const unsigned char *end,
131                                      size_t *olen)
132{
133    int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
134    unsigned char *p = buf;
135    size_t kkpp_len = 0;
136
137    *olen = 0;
138
139    /* Skip costly extension if we can't use EC J-PAKE anyway */
140#if defined(MBEDTLS_USE_PSA_CRYPTO)
141    if (ssl->handshake->psa_pake_ctx_is_ok != 1) {
142        return 0;
143    }
144#else
145    if (mbedtls_ecjpake_check(&ssl->handshake->ecjpake_ctx) != 0) {
146        return 0;
147    }
148#endif /* MBEDTLS_USE_PSA_CRYPTO */
149
150    MBEDTLS_SSL_DEBUG_MSG(3,
151                          ("client hello, adding ecjpake_kkpp extension"));
152
153    MBEDTLS_SSL_CHK_BUF_PTR(p, end, 4);
154
155    MBEDTLS_PUT_UINT16_BE(MBEDTLS_TLS_EXT_ECJPAKE_KKPP, p, 0);
156    p += 2;
157
158    /*
159     * We may need to send ClientHello multiple times for Hello verification.
160     * We don't want to compute fresh values every time (both for performance
161     * and consistency reasons), so cache the extension content.
162     */
163    if (ssl->handshake->ecjpake_cache == NULL ||
164        ssl->handshake->ecjpake_cache_len == 0) {
165        MBEDTLS_SSL_DEBUG_MSG(3, ("generating new ecjpake parameters"));
166
167#if defined(MBEDTLS_USE_PSA_CRYPTO)
168        ret = mbedtls_psa_ecjpake_write_round(&ssl->handshake->psa_pake_ctx,
169                                              p + 2, end - p - 2, &kkpp_len,
170                                              MBEDTLS_ECJPAKE_ROUND_ONE);
171        if (ret != 0) {
172            psa_destroy_key(ssl->handshake->psa_pake_password);
173            psa_pake_abort(&ssl->handshake->psa_pake_ctx);
174            MBEDTLS_SSL_DEBUG_RET(1, "psa_pake_output", ret);
175            return ret;
176        }
177#else
178        ret = mbedtls_ecjpake_write_round_one(&ssl->handshake->ecjpake_ctx,
179                                              p + 2, end - p - 2, &kkpp_len,
180                                              ssl->conf->f_rng, ssl->conf->p_rng);
181        if (ret != 0) {
182            MBEDTLS_SSL_DEBUG_RET(1,
183                                  "mbedtls_ecjpake_write_round_one", ret);
184            return ret;
185        }
186#endif /* MBEDTLS_USE_PSA_CRYPTO */
187
188        ssl->handshake->ecjpake_cache = mbedtls_calloc(1, kkpp_len);
189        if (ssl->handshake->ecjpake_cache == NULL) {
190            MBEDTLS_SSL_DEBUG_MSG(1, ("allocation failed"));
191            return MBEDTLS_ERR_SSL_ALLOC_FAILED;
192        }
193
194        memcpy(ssl->handshake->ecjpake_cache, p + 2, kkpp_len);
195        ssl->handshake->ecjpake_cache_len = kkpp_len;
196    } else {
197        MBEDTLS_SSL_DEBUG_MSG(3, ("re-using cached ecjpake parameters"));
198
199        kkpp_len = ssl->handshake->ecjpake_cache_len;
200        MBEDTLS_SSL_CHK_BUF_PTR(p + 2, end, kkpp_len);
201
202        memcpy(p + 2, ssl->handshake->ecjpake_cache, kkpp_len);
203    }
204
205    MBEDTLS_PUT_UINT16_BE(kkpp_len, p, 0);
206    p += 2;
207
208    *olen = kkpp_len + 4;
209
210    return 0;
211}
212#endif /* MBEDTLS_KEY_EXCHANGE_ECJPAKE_ENABLED */
213
214#if defined(MBEDTLS_SSL_DTLS_CONNECTION_ID)
215MBEDTLS_CHECK_RETURN_CRITICAL
216static int ssl_write_cid_ext(mbedtls_ssl_context *ssl,
217                             unsigned char *buf,
218                             const unsigned char *end,
219                             size_t *olen)
220{
221    unsigned char *p = buf;
222    size_t ext_len;
223
224    /*
225     *   struct {
226     *      opaque cid<0..2^8-1>;
227     *   } ConnectionId;
228     */
229
230    *olen = 0;
231    if (ssl->conf->transport != MBEDTLS_SSL_TRANSPORT_DATAGRAM ||
232        ssl->negotiate_cid == MBEDTLS_SSL_CID_DISABLED) {
233        return 0;
234    }
235    MBEDTLS_SSL_DEBUG_MSG(3, ("client hello, adding CID extension"));
236
237    /* ssl->own_cid_len is at most MBEDTLS_SSL_CID_IN_LEN_MAX
238     * which is at most 255, so the increment cannot overflow. */
239    MBEDTLS_SSL_CHK_BUF_PTR(p, end, (unsigned) (ssl->own_cid_len + 5));
240
241    /* Add extension ID + size */
242    MBEDTLS_PUT_UINT16_BE(MBEDTLS_TLS_EXT_CID, p, 0);
243    p += 2;
244    ext_len = (size_t) ssl->own_cid_len + 1;
245    MBEDTLS_PUT_UINT16_BE(ext_len, p, 0);
246    p += 2;
247
248    *p++ = (uint8_t) ssl->own_cid_len;
249    memcpy(p, ssl->own_cid, ssl->own_cid_len);
250
251    *olen = ssl->own_cid_len + 5;
252
253    return 0;
254}
255#endif /* MBEDTLS_SSL_DTLS_CONNECTION_ID */
256
257#if defined(MBEDTLS_SSL_MAX_FRAGMENT_LENGTH)
258MBEDTLS_CHECK_RETURN_CRITICAL
259static int ssl_write_max_fragment_length_ext(mbedtls_ssl_context *ssl,
260                                             unsigned char *buf,
261                                             const unsigned char *end,
262                                             size_t *olen)
263{
264    unsigned char *p = buf;
265
266    *olen = 0;
267
268    if (ssl->conf->mfl_code == MBEDTLS_SSL_MAX_FRAG_LEN_NONE) {
269        return 0;
270    }
271
272    MBEDTLS_SSL_DEBUG_MSG(3,
273                          ("client hello, adding max_fragment_length extension"));
274
275    MBEDTLS_SSL_CHK_BUF_PTR(p, end, 5);
276
277    MBEDTLS_PUT_UINT16_BE(MBEDTLS_TLS_EXT_MAX_FRAGMENT_LENGTH, p, 0);
278    p += 2;
279
280    *p++ = 0x00;
281    *p++ = 1;
282
283    *p++ = ssl->conf->mfl_code;
284
285    *olen = 5;
286
287    return 0;
288}
289#endif /* MBEDTLS_SSL_MAX_FRAGMENT_LENGTH */
290
291#if defined(MBEDTLS_SSL_ENCRYPT_THEN_MAC)
292MBEDTLS_CHECK_RETURN_CRITICAL
293static int ssl_write_encrypt_then_mac_ext(mbedtls_ssl_context *ssl,
294                                          unsigned char *buf,
295                                          const unsigned char *end,
296                                          size_t *olen)
297{
298    unsigned char *p = buf;
299
300    *olen = 0;
301
302    if (ssl->conf->encrypt_then_mac == MBEDTLS_SSL_ETM_DISABLED) {
303        return 0;
304    }
305
306    MBEDTLS_SSL_DEBUG_MSG(3,
307                          ("client hello, adding encrypt_then_mac extension"));
308
309    MBEDTLS_SSL_CHK_BUF_PTR(p, end, 4);
310
311    MBEDTLS_PUT_UINT16_BE(MBEDTLS_TLS_EXT_ENCRYPT_THEN_MAC, p, 0);
312    p += 2;
313
314    *p++ = 0x00;
315    *p++ = 0x00;
316
317    *olen = 4;
318
319    return 0;
320}
321#endif /* MBEDTLS_SSL_ENCRYPT_THEN_MAC */
322
323#if defined(MBEDTLS_SSL_EXTENDED_MASTER_SECRET)
324MBEDTLS_CHECK_RETURN_CRITICAL
325static int ssl_write_extended_ms_ext(mbedtls_ssl_context *ssl,
326                                     unsigned char *buf,
327                                     const unsigned char *end,
328                                     size_t *olen)
329{
330    unsigned char *p = buf;
331
332    *olen = 0;
333
334    if (ssl->conf->extended_ms == MBEDTLS_SSL_EXTENDED_MS_DISABLED) {
335        return 0;
336    }
337
338    MBEDTLS_SSL_DEBUG_MSG(3,
339                          ("client hello, adding extended_master_secret extension"));
340
341    MBEDTLS_SSL_CHK_BUF_PTR(p, end, 4);
342
343    MBEDTLS_PUT_UINT16_BE(MBEDTLS_TLS_EXT_EXTENDED_MASTER_SECRET, p, 0);
344    p += 2;
345
346    *p++ = 0x00;
347    *p++ = 0x00;
348
349    *olen = 4;
350
351    return 0;
352}
353#endif /* MBEDTLS_SSL_EXTENDED_MASTER_SECRET */
354
355#if defined(MBEDTLS_SSL_SESSION_TICKETS)
356MBEDTLS_CHECK_RETURN_CRITICAL
357static int ssl_write_session_ticket_ext(mbedtls_ssl_context *ssl,
358                                        unsigned char *buf,
359                                        const unsigned char *end,
360                                        size_t *olen)
361{
362    unsigned char *p = buf;
363    size_t tlen = ssl->session_negotiate->ticket_len;
364
365    *olen = 0;
366
367    if (ssl->conf->session_tickets == MBEDTLS_SSL_SESSION_TICKETS_DISABLED) {
368        return 0;
369    }
370
371    MBEDTLS_SSL_DEBUG_MSG(3,
372                          ("client hello, adding session ticket extension"));
373
374    /* The addition is safe here since the ticket length is 16 bit. */
375    MBEDTLS_SSL_CHK_BUF_PTR(p, end, 4 + tlen);
376
377    MBEDTLS_PUT_UINT16_BE(MBEDTLS_TLS_EXT_SESSION_TICKET, p, 0);
378    p += 2;
379
380    MBEDTLS_PUT_UINT16_BE(tlen, p, 0);
381    p += 2;
382
383    *olen = 4;
384
385    if (ssl->session_negotiate->ticket == NULL || tlen == 0) {
386        return 0;
387    }
388
389    MBEDTLS_SSL_DEBUG_MSG(3,
390                          ("sending session ticket of length %" MBEDTLS_PRINTF_SIZET, tlen));
391
392    memcpy(p, ssl->session_negotiate->ticket, tlen);
393
394    *olen += tlen;
395
396    return 0;
397}
398#endif /* MBEDTLS_SSL_SESSION_TICKETS */
399
400#if defined(MBEDTLS_SSL_DTLS_SRTP)
401MBEDTLS_CHECK_RETURN_CRITICAL
402static int ssl_write_use_srtp_ext(mbedtls_ssl_context *ssl,
403                                  unsigned char *buf,
404                                  const unsigned char *end,
405                                  size_t *olen)
406{
407    unsigned char *p = buf;
408    size_t protection_profiles_index = 0, ext_len = 0;
409    uint16_t mki_len = 0, profile_value = 0;
410
411    *olen = 0;
412
413    if ((ssl->conf->transport != MBEDTLS_SSL_TRANSPORT_DATAGRAM) ||
414        (ssl->conf->dtls_srtp_profile_list == NULL) ||
415        (ssl->conf->dtls_srtp_profile_list_len == 0)) {
416        return 0;
417    }
418
419    /* RFC 5764 section 4.1.1
420     * uint8 SRTPProtectionProfile[2];
421     *
422     * struct {
423     *   SRTPProtectionProfiles SRTPProtectionProfiles;
424     *   opaque srtp_mki<0..255>;
425     * } UseSRTPData;
426     * SRTPProtectionProfile SRTPProtectionProfiles<2..2^16-1>;
427     */
428    if (ssl->conf->dtls_srtp_mki_support == MBEDTLS_SSL_DTLS_SRTP_MKI_SUPPORTED) {
429        mki_len = ssl->dtls_srtp_info.mki_len;
430    }
431    /* Extension length = 2 bytes for profiles length,
432     *                    ssl->conf->dtls_srtp_profile_list_len * 2 (each profile is 2 bytes length ),
433     *                    1 byte for srtp_mki vector length and the mki_len value
434     */
435    ext_len = 2 + 2 * (ssl->conf->dtls_srtp_profile_list_len) + 1 + mki_len;
436
437    MBEDTLS_SSL_DEBUG_MSG(3, ("client hello, adding use_srtp extension"));
438
439    /* Check there is room in the buffer for the extension + 4 bytes
440     * - the extension tag (2 bytes)
441     * - the extension length (2 bytes)
442     */
443    MBEDTLS_SSL_CHK_BUF_PTR(p, end, ext_len + 4);
444
445    MBEDTLS_PUT_UINT16_BE(MBEDTLS_TLS_EXT_USE_SRTP, p, 0);
446    p += 2;
447
448    MBEDTLS_PUT_UINT16_BE(ext_len, p, 0);
449    p += 2;
450
451    /* protection profile length: 2*(ssl->conf->dtls_srtp_profile_list_len) */
452    /* micro-optimization:
453     * the list size is limited to MBEDTLS_TLS_SRTP_MAX_PROFILE_LIST_LENGTH
454     * which is lower than 127, so the upper byte of the length is always 0
455     * For the documentation, the more generic code is left in comments
456     * *p++ = (unsigned char)( ( ( 2 * ssl->conf->dtls_srtp_profile_list_len )
457     *                        >> 8 ) & 0xFF );
458     */
459    *p++ = 0;
460    *p++ = MBEDTLS_BYTE_0(2 * ssl->conf->dtls_srtp_profile_list_len);
461
462    for (protection_profiles_index = 0;
463         protection_profiles_index < ssl->conf->dtls_srtp_profile_list_len;
464         protection_profiles_index++) {
465        profile_value = mbedtls_ssl_check_srtp_profile_value
466                            (ssl->conf->dtls_srtp_profile_list[protection_profiles_index]);
467        if (profile_value != MBEDTLS_TLS_SRTP_UNSET) {
468            MBEDTLS_SSL_DEBUG_MSG(3, ("ssl_write_use_srtp_ext, add profile: %04x",
469                                      profile_value));
470            MBEDTLS_PUT_UINT16_BE(profile_value, p, 0);
471            p += 2;
472        } else {
473            /*
474             * Note: we shall never arrive here as protection profiles
475             * is checked by mbedtls_ssl_conf_dtls_srtp_protection_profiles function
476             */
477            MBEDTLS_SSL_DEBUG_MSG(3,
478                                  ("client hello, "
479                                   "illegal DTLS-SRTP protection profile %d",
480                                   ssl->conf->dtls_srtp_profile_list[protection_profiles_index]
481                                  ));
482            return MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
483        }
484    }
485
486    *p++ = mki_len & 0xFF;
487
488    if (mki_len != 0) {
489        memcpy(p, ssl->dtls_srtp_info.mki_value, mki_len);
490        /*
491         * Increment p to point to the current position.
492         */
493        p += mki_len;
494        MBEDTLS_SSL_DEBUG_BUF(3, "sending mki",  ssl->dtls_srtp_info.mki_value,
495                              ssl->dtls_srtp_info.mki_len);
496    }
497
498    /*
499     * total extension length: extension type (2 bytes)
500     *                         + extension length (2 bytes)
501     *                         + protection profile length (2 bytes)
502     *                         + 2 * number of protection profiles
503     *                         + srtp_mki vector length(1 byte)
504     *                         + mki value
505     */
506    *olen = p - buf;
507
508    return 0;
509}
510#endif /* MBEDTLS_SSL_DTLS_SRTP */
511
512int mbedtls_ssl_tls12_write_client_hello_exts(mbedtls_ssl_context *ssl,
513                                              unsigned char *buf,
514                                              const unsigned char *end,
515                                              int uses_ec,
516                                              size_t *out_len)
517{
518    int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
519    unsigned char *p = buf;
520    size_t ext_len = 0;
521
522    (void) ssl;
523    (void) end;
524    (void) uses_ec;
525    (void) ret;
526    (void) ext_len;
527
528    *out_len = 0;
529
530    /* Note that TLS_EMPTY_RENEGOTIATION_INFO_SCSV is always added
531     * even if MBEDTLS_SSL_RENEGOTIATION is not defined. */
532#if defined(MBEDTLS_SSL_RENEGOTIATION)
533    if ((ret = ssl_write_renegotiation_ext(ssl, p, end, &ext_len)) != 0) {
534        MBEDTLS_SSL_DEBUG_RET(1, "ssl_write_renegotiation_ext", ret);
535        return ret;
536    }
537    p += ext_len;
538#endif
539
540#if defined(MBEDTLS_KEY_EXCHANGE_SOME_ECDH_OR_ECDHE_1_2_ENABLED) || \
541    defined(MBEDTLS_KEY_EXCHANGE_ECDSA_CERT_REQ_ALLOWED_ENABLED) || \
542    defined(MBEDTLS_KEY_EXCHANGE_ECJPAKE_ENABLED)
543    if (uses_ec) {
544        if ((ret = ssl_write_supported_point_formats_ext(ssl, p, end,
545                                                         &ext_len)) != 0) {
546            MBEDTLS_SSL_DEBUG_RET(1, "ssl_write_supported_point_formats_ext", ret);
547            return ret;
548        }
549        p += ext_len;
550    }
551#endif
552
553#if defined(MBEDTLS_KEY_EXCHANGE_ECJPAKE_ENABLED)
554    if ((ret = ssl_write_ecjpake_kkpp_ext(ssl, p, end, &ext_len)) != 0) {
555        MBEDTLS_SSL_DEBUG_RET(1, "ssl_write_ecjpake_kkpp_ext", ret);
556        return ret;
557    }
558    p += ext_len;
559#endif
560
561#if defined(MBEDTLS_SSL_DTLS_CONNECTION_ID)
562    if ((ret = ssl_write_cid_ext(ssl, p, end, &ext_len)) != 0) {
563        MBEDTLS_SSL_DEBUG_RET(1, "ssl_write_cid_ext", ret);
564        return ret;
565    }
566    p += ext_len;
567#endif /* MBEDTLS_SSL_DTLS_CONNECTION_ID */
568
569#if defined(MBEDTLS_SSL_MAX_FRAGMENT_LENGTH)
570    if ((ret = ssl_write_max_fragment_length_ext(ssl, p, end,
571                                                 &ext_len)) != 0) {
572        MBEDTLS_SSL_DEBUG_RET(1, "ssl_write_max_fragment_length_ext", ret);
573        return ret;
574    }
575    p += ext_len;
576#endif
577
578#if defined(MBEDTLS_SSL_ENCRYPT_THEN_MAC)
579    if ((ret = ssl_write_encrypt_then_mac_ext(ssl, p, end, &ext_len)) != 0) {
580        MBEDTLS_SSL_DEBUG_RET(1, "ssl_write_encrypt_then_mac_ext", ret);
581        return ret;
582    }
583    p += ext_len;
584#endif
585
586#if defined(MBEDTLS_SSL_EXTENDED_MASTER_SECRET)
587    if ((ret = ssl_write_extended_ms_ext(ssl, p, end, &ext_len)) != 0) {
588        MBEDTLS_SSL_DEBUG_RET(1, "ssl_write_extended_ms_ext", ret);
589        return ret;
590    }
591    p += ext_len;
592#endif
593
594#if defined(MBEDTLS_SSL_DTLS_SRTP)
595    if ((ret = ssl_write_use_srtp_ext(ssl, p, end, &ext_len)) != 0) {
596        MBEDTLS_SSL_DEBUG_RET(1, "ssl_write_use_srtp_ext", ret);
597        return ret;
598    }
599    p += ext_len;
600#endif
601
602#if defined(MBEDTLS_SSL_SESSION_TICKETS)
603    if ((ret = ssl_write_session_ticket_ext(ssl, p, end, &ext_len)) != 0) {
604        MBEDTLS_SSL_DEBUG_RET(1, "ssl_write_session_ticket_ext", ret);
605        return ret;
606    }
607    p += ext_len;
608#endif
609
610    *out_len = (size_t) (p - buf);
611
612    return 0;
613}
614
615MBEDTLS_CHECK_RETURN_CRITICAL
616static int ssl_parse_renegotiation_info(mbedtls_ssl_context *ssl,
617                                        const unsigned char *buf,
618                                        size_t len)
619{
620#if defined(MBEDTLS_SSL_RENEGOTIATION)
621    if (ssl->renego_status != MBEDTLS_SSL_INITIAL_HANDSHAKE) {
622        /* Check verify-data in constant-time. The length OTOH is no secret */
623        if (len    != 1 + ssl->verify_data_len * 2 ||
624            buf[0] !=     ssl->verify_data_len * 2 ||
625            mbedtls_ct_memcmp(buf + 1,
626                              ssl->own_verify_data, ssl->verify_data_len) != 0 ||
627            mbedtls_ct_memcmp(buf + 1 + ssl->verify_data_len,
628                              ssl->peer_verify_data, ssl->verify_data_len) != 0) {
629            MBEDTLS_SSL_DEBUG_MSG(1, ("non-matching renegotiation info"));
630            mbedtls_ssl_send_alert_message(
631                ssl,
632                MBEDTLS_SSL_ALERT_LEVEL_FATAL,
633                MBEDTLS_SSL_ALERT_MSG_HANDSHAKE_FAILURE);
634            return MBEDTLS_ERR_SSL_HANDSHAKE_FAILURE;
635        }
636    } else
637#endif /* MBEDTLS_SSL_RENEGOTIATION */
638    {
639        if (len != 1 || buf[0] != 0x00) {
640            MBEDTLS_SSL_DEBUG_MSG(1,
641                                  ("non-zero length renegotiation info"));
642            mbedtls_ssl_send_alert_message(
643                ssl,
644                MBEDTLS_SSL_ALERT_LEVEL_FATAL,
645                MBEDTLS_SSL_ALERT_MSG_HANDSHAKE_FAILURE);
646            return MBEDTLS_ERR_SSL_HANDSHAKE_FAILURE;
647        }
648
649        ssl->secure_renegotiation = MBEDTLS_SSL_SECURE_RENEGOTIATION;
650    }
651
652    return 0;
653}
654
655#if defined(MBEDTLS_SSL_MAX_FRAGMENT_LENGTH)
656MBEDTLS_CHECK_RETURN_CRITICAL
657static int ssl_parse_max_fragment_length_ext(mbedtls_ssl_context *ssl,
658                                             const unsigned char *buf,
659                                             size_t len)
660{
661    /*
662     * server should use the extension only if we did,
663     * and if so the server's value should match ours (and len is always 1)
664     */
665    if (ssl->conf->mfl_code == MBEDTLS_SSL_MAX_FRAG_LEN_NONE ||
666        len != 1 ||
667        buf[0] != ssl->conf->mfl_code) {
668        MBEDTLS_SSL_DEBUG_MSG(1,
669                              ("non-matching max fragment length extension"));
670        mbedtls_ssl_send_alert_message(
671            ssl,
672            MBEDTLS_SSL_ALERT_LEVEL_FATAL,
673            MBEDTLS_SSL_ALERT_MSG_ILLEGAL_PARAMETER);
674        return MBEDTLS_ERR_SSL_ILLEGAL_PARAMETER;
675    }
676
677    return 0;
678}
679#endif /* MBEDTLS_SSL_MAX_FRAGMENT_LENGTH */
680
681#if defined(MBEDTLS_SSL_DTLS_CONNECTION_ID)
682MBEDTLS_CHECK_RETURN_CRITICAL
683static int ssl_parse_cid_ext(mbedtls_ssl_context *ssl,
684                             const unsigned char *buf,
685                             size_t len)
686{
687    size_t peer_cid_len;
688
689    if ( /* CID extension only makes sense in DTLS */
690        ssl->conf->transport != MBEDTLS_SSL_TRANSPORT_DATAGRAM ||
691        /* The server must only send the CID extension if we have offered it. */
692        ssl->negotiate_cid == MBEDTLS_SSL_CID_DISABLED) {
693        MBEDTLS_SSL_DEBUG_MSG(1, ("CID extension unexpected"));
694        mbedtls_ssl_send_alert_message(ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,
695                                       MBEDTLS_SSL_ALERT_MSG_UNSUPPORTED_EXT);
696        return MBEDTLS_ERR_SSL_UNSUPPORTED_EXTENSION;
697    }
698
699    if (len == 0) {
700        MBEDTLS_SSL_DEBUG_MSG(1, ("CID extension invalid"));
701        mbedtls_ssl_send_alert_message(ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,
702                                       MBEDTLS_SSL_ALERT_MSG_DECODE_ERROR);
703        return MBEDTLS_ERR_SSL_DECODE_ERROR;
704    }
705
706    peer_cid_len = *buf++;
707    len--;
708
709    if (peer_cid_len > MBEDTLS_SSL_CID_OUT_LEN_MAX) {
710        MBEDTLS_SSL_DEBUG_MSG(1, ("CID extension invalid"));
711        mbedtls_ssl_send_alert_message(ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,
712                                       MBEDTLS_SSL_ALERT_MSG_ILLEGAL_PARAMETER);
713        return MBEDTLS_ERR_SSL_ILLEGAL_PARAMETER;
714    }
715
716    if (len != peer_cid_len) {
717        MBEDTLS_SSL_DEBUG_MSG(1, ("CID extension invalid"));
718        mbedtls_ssl_send_alert_message(ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,
719                                       MBEDTLS_SSL_ALERT_MSG_DECODE_ERROR);
720        return MBEDTLS_ERR_SSL_DECODE_ERROR;
721    }
722
723    ssl->handshake->cid_in_use = MBEDTLS_SSL_CID_ENABLED;
724    ssl->handshake->peer_cid_len = (uint8_t) peer_cid_len;
725    memcpy(ssl->handshake->peer_cid, buf, peer_cid_len);
726
727    MBEDTLS_SSL_DEBUG_MSG(3, ("Use of CID extension negotiated"));
728    MBEDTLS_SSL_DEBUG_BUF(3, "Server CID", buf, peer_cid_len);
729
730    return 0;
731}
732#endif /* MBEDTLS_SSL_DTLS_CONNECTION_ID */
733
734#if defined(MBEDTLS_SSL_ENCRYPT_THEN_MAC)
735MBEDTLS_CHECK_RETURN_CRITICAL
736static int ssl_parse_encrypt_then_mac_ext(mbedtls_ssl_context *ssl,
737                                          const unsigned char *buf,
738                                          size_t len)
739{
740    if (ssl->conf->encrypt_then_mac == MBEDTLS_SSL_ETM_DISABLED ||
741        len != 0) {
742        MBEDTLS_SSL_DEBUG_MSG(1,
743                              ("non-matching encrypt-then-MAC extension"));
744        mbedtls_ssl_send_alert_message(
745            ssl,
746            MBEDTLS_SSL_ALERT_LEVEL_FATAL,
747            MBEDTLS_SSL_ALERT_MSG_UNSUPPORTED_EXT);
748        return MBEDTLS_ERR_SSL_UNSUPPORTED_EXTENSION;
749    }
750
751    ((void) buf);
752
753    ssl->session_negotiate->encrypt_then_mac = MBEDTLS_SSL_ETM_ENABLED;
754
755    return 0;
756}
757#endif /* MBEDTLS_SSL_ENCRYPT_THEN_MAC */
758
759#if defined(MBEDTLS_SSL_EXTENDED_MASTER_SECRET)
760MBEDTLS_CHECK_RETURN_CRITICAL
761static int ssl_parse_extended_ms_ext(mbedtls_ssl_context *ssl,
762                                     const unsigned char *buf,
763                                     size_t len)
764{
765    if (ssl->conf->extended_ms == MBEDTLS_SSL_EXTENDED_MS_DISABLED ||
766        len != 0) {
767        MBEDTLS_SSL_DEBUG_MSG(1,
768                              ("non-matching extended master secret extension"));
769        mbedtls_ssl_send_alert_message(
770            ssl,
771            MBEDTLS_SSL_ALERT_LEVEL_FATAL,
772            MBEDTLS_SSL_ALERT_MSG_UNSUPPORTED_EXT);
773        return MBEDTLS_ERR_SSL_UNSUPPORTED_EXTENSION;
774    }
775
776    ((void) buf);
777
778    ssl->handshake->extended_ms = MBEDTLS_SSL_EXTENDED_MS_ENABLED;
779
780    return 0;
781}
782#endif /* MBEDTLS_SSL_EXTENDED_MASTER_SECRET */
783
784#if defined(MBEDTLS_SSL_SESSION_TICKETS)
785MBEDTLS_CHECK_RETURN_CRITICAL
786static int ssl_parse_session_ticket_ext(mbedtls_ssl_context *ssl,
787                                        const unsigned char *buf,
788                                        size_t len)
789{
790    if (ssl->conf->session_tickets == MBEDTLS_SSL_SESSION_TICKETS_DISABLED ||
791        len != 0) {
792        MBEDTLS_SSL_DEBUG_MSG(1,
793                              ("non-matching session ticket extension"));
794        mbedtls_ssl_send_alert_message(
795            ssl,
796            MBEDTLS_SSL_ALERT_LEVEL_FATAL,
797            MBEDTLS_SSL_ALERT_MSG_UNSUPPORTED_EXT);
798        return MBEDTLS_ERR_SSL_UNSUPPORTED_EXTENSION;
799    }
800
801    ((void) buf);
802
803    ssl->handshake->new_session_ticket = 1;
804
805    return 0;
806}
807#endif /* MBEDTLS_SSL_SESSION_TICKETS */
808
809#if defined(MBEDTLS_KEY_EXCHANGE_SOME_ECDH_OR_ECDHE_1_2_ENABLED) || \
810    defined(MBEDTLS_KEY_EXCHANGE_ECDSA_CERT_REQ_ALLOWED_ENABLED) || \
811    defined(MBEDTLS_KEY_EXCHANGE_ECJPAKE_ENABLED)
812MBEDTLS_CHECK_RETURN_CRITICAL
813static int ssl_parse_supported_point_formats_ext(mbedtls_ssl_context *ssl,
814                                                 const unsigned char *buf,
815                                                 size_t len)
816{
817    size_t list_size;
818    const unsigned char *p;
819
820    if (len == 0 || (size_t) (buf[0] + 1) != len) {
821        MBEDTLS_SSL_DEBUG_MSG(1, ("bad server hello message"));
822        mbedtls_ssl_send_alert_message(ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,
823                                       MBEDTLS_SSL_ALERT_MSG_DECODE_ERROR);
824        return MBEDTLS_ERR_SSL_DECODE_ERROR;
825    }
826    list_size = buf[0];
827
828    p = buf + 1;
829    while (list_size > 0) {
830        if (p[0] == MBEDTLS_ECP_PF_UNCOMPRESSED ||
831            p[0] == MBEDTLS_ECP_PF_COMPRESSED) {
832#if !defined(MBEDTLS_USE_PSA_CRYPTO) && \
833            defined(MBEDTLS_KEY_EXCHANGE_SOME_ECDH_OR_ECDHE_1_2_ENABLED)
834            ssl->handshake->ecdh_ctx.point_format = p[0];
835#endif /* !MBEDTLS_USE_PSA_CRYPTO && MBEDTLS_KEY_EXCHANGE_SOME_ECDH_OR_ECDHE_1_2_ENABLED */
836#if !defined(MBEDTLS_USE_PSA_CRYPTO) &&                             \
837            defined(MBEDTLS_KEY_EXCHANGE_ECJPAKE_ENABLED)
838            mbedtls_ecjpake_set_point_format(&ssl->handshake->ecjpake_ctx,
839                                             p[0]);
840#endif /* !MBEDTLS_USE_PSA_CRYPTO && MBEDTLS_KEY_EXCHANGE_ECJPAKE_ENABLED */
841            MBEDTLS_SSL_DEBUG_MSG(4, ("point format selected: %d", p[0]));
842            return 0;
843        }
844
845        list_size--;
846        p++;
847    }
848
849    MBEDTLS_SSL_DEBUG_MSG(1, ("no point format in common"));
850    mbedtls_ssl_send_alert_message(ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,
851                                   MBEDTLS_SSL_ALERT_MSG_HANDSHAKE_FAILURE);
852    return MBEDTLS_ERR_SSL_HANDSHAKE_FAILURE;
853}
854#endif /* MBEDTLS_KEY_EXCHANGE_SOME_ECDH_OR_ECDHE_1_2_ENABLED ||
855          MBEDTLS_KEY_EXCHANGE_ECDSA_CERT_REQ_ALLOWED_ENABLED ||
856          MBEDTLS_KEY_EXCHANGE_ECJPAKE_ENABLED */
857
858#if defined(MBEDTLS_KEY_EXCHANGE_ECJPAKE_ENABLED)
859MBEDTLS_CHECK_RETURN_CRITICAL
860static int ssl_parse_ecjpake_kkpp(mbedtls_ssl_context *ssl,
861                                  const unsigned char *buf,
862                                  size_t len)
863{
864    int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
865
866    if (ssl->handshake->ciphersuite_info->key_exchange !=
867        MBEDTLS_KEY_EXCHANGE_ECJPAKE) {
868        MBEDTLS_SSL_DEBUG_MSG(3, ("skip ecjpake kkpp extension"));
869        return 0;
870    }
871
872    /* If we got here, we no longer need our cached extension */
873    mbedtls_free(ssl->handshake->ecjpake_cache);
874    ssl->handshake->ecjpake_cache = NULL;
875    ssl->handshake->ecjpake_cache_len = 0;
876
877#if defined(MBEDTLS_USE_PSA_CRYPTO)
878    if ((ret = mbedtls_psa_ecjpake_read_round(
879             &ssl->handshake->psa_pake_ctx, buf, len,
880             MBEDTLS_ECJPAKE_ROUND_ONE)) != 0) {
881        psa_destroy_key(ssl->handshake->psa_pake_password);
882        psa_pake_abort(&ssl->handshake->psa_pake_ctx);
883
884        MBEDTLS_SSL_DEBUG_RET(1, "psa_pake_input round one", ret);
885        mbedtls_ssl_send_alert_message(
886            ssl,
887            MBEDTLS_SSL_ALERT_LEVEL_FATAL,
888            MBEDTLS_SSL_ALERT_MSG_HANDSHAKE_FAILURE);
889        return ret;
890    }
891
892    return 0;
893#else
894    if ((ret = mbedtls_ecjpake_read_round_one(&ssl->handshake->ecjpake_ctx,
895                                              buf, len)) != 0) {
896        MBEDTLS_SSL_DEBUG_RET(1, "mbedtls_ecjpake_read_round_one", ret);
897        mbedtls_ssl_send_alert_message(
898            ssl,
899            MBEDTLS_SSL_ALERT_LEVEL_FATAL,
900            MBEDTLS_SSL_ALERT_MSG_HANDSHAKE_FAILURE);
901        return ret;
902    }
903
904    return 0;
905#endif /* MBEDTLS_USE_PSA_CRYPTO */
906}
907#endif /* MBEDTLS_KEY_EXCHANGE_ECJPAKE_ENABLED */
908
909#if defined(MBEDTLS_SSL_ALPN)
910MBEDTLS_CHECK_RETURN_CRITICAL
911static int ssl_parse_alpn_ext(mbedtls_ssl_context *ssl,
912                              const unsigned char *buf, size_t len)
913{
914    size_t list_len, name_len;
915    const char **p;
916
917    /* If we didn't send it, the server shouldn't send it */
918    if (ssl->conf->alpn_list == NULL) {
919        MBEDTLS_SSL_DEBUG_MSG(1, ("non-matching ALPN extension"));
920        mbedtls_ssl_send_alert_message(
921            ssl,
922            MBEDTLS_SSL_ALERT_LEVEL_FATAL,
923            MBEDTLS_SSL_ALERT_MSG_UNSUPPORTED_EXT);
924        return MBEDTLS_ERR_SSL_UNSUPPORTED_EXTENSION;
925    }
926
927    /*
928     * opaque ProtocolName<1..2^8-1>;
929     *
930     * struct {
931     *     ProtocolName protocol_name_list<2..2^16-1>
932     * } ProtocolNameList;
933     *
934     * the "ProtocolNameList" MUST contain exactly one "ProtocolName"
935     */
936
937    /* Min length is 2 (list_len) + 1 (name_len) + 1 (name) */
938    if (len < 4) {
939        mbedtls_ssl_send_alert_message(ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,
940                                       MBEDTLS_SSL_ALERT_MSG_DECODE_ERROR);
941        return MBEDTLS_ERR_SSL_DECODE_ERROR;
942    }
943
944    list_len = MBEDTLS_GET_UINT16_BE(buf, 0);
945    if (list_len != len - 2) {
946        mbedtls_ssl_send_alert_message(ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,
947                                       MBEDTLS_SSL_ALERT_MSG_DECODE_ERROR);
948        return MBEDTLS_ERR_SSL_DECODE_ERROR;
949    }
950
951    name_len = buf[2];
952    if (name_len != list_len - 1) {
953        mbedtls_ssl_send_alert_message(ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,
954                                       MBEDTLS_SSL_ALERT_MSG_DECODE_ERROR);
955        return MBEDTLS_ERR_SSL_DECODE_ERROR;
956    }
957
958    /* Check that the server chosen protocol was in our list and save it */
959    for (p = ssl->conf->alpn_list; *p != NULL; p++) {
960        if (name_len == strlen(*p) &&
961            memcmp(buf + 3, *p, name_len) == 0) {
962            ssl->alpn_chosen = *p;
963            return 0;
964        }
965    }
966
967    MBEDTLS_SSL_DEBUG_MSG(1, ("ALPN extension: no matching protocol"));
968    mbedtls_ssl_send_alert_message(ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,
969                                   MBEDTLS_SSL_ALERT_MSG_HANDSHAKE_FAILURE);
970    return MBEDTLS_ERR_SSL_HANDSHAKE_FAILURE;
971}
972#endif /* MBEDTLS_SSL_ALPN */
973
974#if defined(MBEDTLS_SSL_DTLS_SRTP)
975MBEDTLS_CHECK_RETURN_CRITICAL
976static int ssl_parse_use_srtp_ext(mbedtls_ssl_context *ssl,
977                                  const unsigned char *buf,
978                                  size_t len)
979{
980    mbedtls_ssl_srtp_profile server_protection = MBEDTLS_TLS_SRTP_UNSET;
981    size_t i, mki_len = 0;
982    uint16_t server_protection_profile_value = 0;
983
984    /* If use_srtp is not configured, just ignore the extension */
985    if ((ssl->conf->transport != MBEDTLS_SSL_TRANSPORT_DATAGRAM) ||
986        (ssl->conf->dtls_srtp_profile_list == NULL) ||
987        (ssl->conf->dtls_srtp_profile_list_len == 0)) {
988        return 0;
989    }
990
991    /* RFC 5764 section 4.1.1
992     * uint8 SRTPProtectionProfile[2];
993     *
994     * struct {
995     *   SRTPProtectionProfiles SRTPProtectionProfiles;
996     *   opaque srtp_mki<0..255>;
997     * } UseSRTPData;
998
999     * SRTPProtectionProfile SRTPProtectionProfiles<2..2^16-1>;
1000     *
1001     */
1002    if (ssl->conf->dtls_srtp_mki_support == MBEDTLS_SSL_DTLS_SRTP_MKI_SUPPORTED) {
1003        mki_len = ssl->dtls_srtp_info.mki_len;
1004    }
1005
1006    /*
1007     * Length is 5 + optional mki_value : one protection profile length (2 bytes)
1008     *                                      + protection profile (2 bytes)
1009     *                                      + mki_len(1 byte)
1010     *                                      and optional srtp_mki
1011     */
1012    if ((len < 5) || (len != (buf[4] + 5u))) {
1013        return MBEDTLS_ERR_SSL_DECODE_ERROR;
1014    }
1015
1016    /*
1017     * get the server protection profile
1018     */
1019
1020    /*
1021     * protection profile length must be 0x0002 as we must have only
1022     * one protection profile in server Hello
1023     */
1024    if ((buf[0] != 0) || (buf[1] != 2)) {
1025        return MBEDTLS_ERR_SSL_DECODE_ERROR;
1026    }
1027
1028    server_protection_profile_value = (buf[2] << 8) | buf[3];
1029    server_protection = mbedtls_ssl_check_srtp_profile_value(
1030        server_protection_profile_value);
1031    if (server_protection != MBEDTLS_TLS_SRTP_UNSET) {
1032        MBEDTLS_SSL_DEBUG_MSG(3, ("found srtp profile: %s",
1033                                  mbedtls_ssl_get_srtp_profile_as_string(
1034                                      server_protection)));
1035    }
1036
1037    ssl->dtls_srtp_info.chosen_dtls_srtp_profile = MBEDTLS_TLS_SRTP_UNSET;
1038
1039    /*
1040     * Check we have the server profile in our list
1041     */
1042    for (i = 0; i < ssl->conf->dtls_srtp_profile_list_len; i++) {
1043        if (server_protection == ssl->conf->dtls_srtp_profile_list[i]) {
1044            ssl->dtls_srtp_info.chosen_dtls_srtp_profile = ssl->conf->dtls_srtp_profile_list[i];
1045            MBEDTLS_SSL_DEBUG_MSG(3, ("selected srtp profile: %s",
1046                                      mbedtls_ssl_get_srtp_profile_as_string(
1047                                          server_protection)));
1048            break;
1049        }
1050    }
1051
1052    /* If no match was found : server problem, it shall never answer with incompatible profile */
1053    if (ssl->dtls_srtp_info.chosen_dtls_srtp_profile == MBEDTLS_TLS_SRTP_UNSET) {
1054        mbedtls_ssl_send_alert_message(ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,
1055                                       MBEDTLS_SSL_ALERT_MSG_HANDSHAKE_FAILURE);
1056        return MBEDTLS_ERR_SSL_HANDSHAKE_FAILURE;
1057    }
1058
1059    /* If server does not use mki in its reply, make sure the client won't keep
1060     * one as negotiated */
1061    if (len == 5) {
1062        ssl->dtls_srtp_info.mki_len = 0;
1063    }
1064
1065    /*
1066     * RFC5764:
1067     *  If the client detects a nonzero-length MKI in the server's response
1068     *  that is different than the one the client offered, then the client
1069     *  MUST abort the handshake and SHOULD send an invalid_parameter alert.
1070     */
1071    if (len > 5  && (buf[4] != mki_len ||
1072                     (memcmp(ssl->dtls_srtp_info.mki_value, &buf[5], mki_len)))) {
1073        mbedtls_ssl_send_alert_message(ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,
1074                                       MBEDTLS_SSL_ALERT_MSG_ILLEGAL_PARAMETER);
1075        return MBEDTLS_ERR_SSL_ILLEGAL_PARAMETER;
1076    }
1077#if defined(MBEDTLS_DEBUG_C)
1078    if (len > 5) {
1079        MBEDTLS_SSL_DEBUG_BUF(3, "received mki", ssl->dtls_srtp_info.mki_value,
1080                              ssl->dtls_srtp_info.mki_len);
1081    }
1082#endif
1083    return 0;
1084}
1085#endif /* MBEDTLS_SSL_DTLS_SRTP */
1086
1087/*
1088 * Parse HelloVerifyRequest.  Only called after verifying the HS type.
1089 */
1090#if defined(MBEDTLS_SSL_PROTO_DTLS)
1091MBEDTLS_CHECK_RETURN_CRITICAL
1092static int ssl_parse_hello_verify_request(mbedtls_ssl_context *ssl)
1093{
1094    int ret = MBEDTLS_ERR_SSL_FEATURE_UNAVAILABLE;
1095    const unsigned char *p = ssl->in_msg + mbedtls_ssl_hs_hdr_len(ssl);
1096    uint16_t dtls_legacy_version;
1097
1098#if !defined(MBEDTLS_SSL_PROTO_TLS1_3)
1099    uint8_t cookie_len;
1100#else
1101    uint16_t cookie_len;
1102#endif
1103
1104    MBEDTLS_SSL_DEBUG_MSG(2, ("=> parse hello verify request"));
1105
1106    /* Check that there is enough room for:
1107     * - 2 bytes of version
1108     * - 1 byte of cookie_len
1109     */
1110    if (mbedtls_ssl_hs_hdr_len(ssl) + 3 > ssl->in_msglen) {
1111        MBEDTLS_SSL_DEBUG_MSG(1,
1112                              ("incoming HelloVerifyRequest message is too short"));
1113        mbedtls_ssl_send_alert_message(ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,
1114                                       MBEDTLS_SSL_ALERT_MSG_DECODE_ERROR);
1115        return MBEDTLS_ERR_SSL_DECODE_ERROR;
1116    }
1117
1118    /*
1119     * struct {
1120     *   ProtocolVersion server_version;
1121     *   opaque cookie<0..2^8-1>;
1122     * } HelloVerifyRequest;
1123     */
1124    MBEDTLS_SSL_DEBUG_BUF(3, "server version", p, 2);
1125    dtls_legacy_version = MBEDTLS_GET_UINT16_BE(p, 0);
1126    p += 2;
1127
1128    /*
1129     * Since the RFC is not clear on this point, accept DTLS 1.0 (0xfeff)
1130     * The DTLS 1.3 (current draft) renames ProtocolVersion server_version to
1131     * legacy_version and locks the value of legacy_version to 0xfefd (DTLS 1.2)
1132     */
1133    if (dtls_legacy_version != 0xfefd && dtls_legacy_version != 0xfeff) {
1134        MBEDTLS_SSL_DEBUG_MSG(1, ("bad server version"));
1135
1136        mbedtls_ssl_send_alert_message(ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,
1137                                       MBEDTLS_SSL_ALERT_MSG_PROTOCOL_VERSION);
1138
1139        return MBEDTLS_ERR_SSL_BAD_PROTOCOL_VERSION;
1140    }
1141
1142    cookie_len = *p++;
1143    if ((ssl->in_msg + ssl->in_msglen) - p < cookie_len) {
1144        MBEDTLS_SSL_DEBUG_MSG(1,
1145                              ("cookie length does not match incoming message size"));
1146        mbedtls_ssl_send_alert_message(ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,
1147                                       MBEDTLS_SSL_ALERT_MSG_DECODE_ERROR);
1148        return MBEDTLS_ERR_SSL_DECODE_ERROR;
1149    }
1150    MBEDTLS_SSL_DEBUG_BUF(3, "cookie", p, cookie_len);
1151
1152    mbedtls_free(ssl->handshake->cookie);
1153
1154    ssl->handshake->cookie = mbedtls_calloc(1, cookie_len);
1155    if (ssl->handshake->cookie  == NULL) {
1156        MBEDTLS_SSL_DEBUG_MSG(1, ("alloc failed (%d bytes)", cookie_len));
1157        return MBEDTLS_ERR_SSL_ALLOC_FAILED;
1158    }
1159
1160    memcpy(ssl->handshake->cookie, p, cookie_len);
1161    ssl->handshake->cookie_len = cookie_len;
1162
1163    /* Start over at ClientHello */
1164    ssl->state = MBEDTLS_SSL_CLIENT_HELLO;
1165    ret = mbedtls_ssl_reset_checksum(ssl);
1166    if (0 != ret) {
1167        MBEDTLS_SSL_DEBUG_RET(1, ("mbedtls_ssl_reset_checksum"), ret);
1168        return ret;
1169    }
1170
1171    mbedtls_ssl_recv_flight_completed(ssl);
1172
1173    MBEDTLS_SSL_DEBUG_MSG(2, ("<= parse hello verify request"));
1174
1175    return 0;
1176}
1177#endif /* MBEDTLS_SSL_PROTO_DTLS */
1178
1179MBEDTLS_CHECK_RETURN_CRITICAL
1180static int ssl_parse_server_hello(mbedtls_ssl_context *ssl)
1181{
1182    int ret, i;
1183    size_t n;
1184    size_t ext_len;
1185    unsigned char *buf, *ext;
1186    unsigned char comp;
1187#if defined(MBEDTLS_SSL_RENEGOTIATION)
1188    int renegotiation_info_seen = 0;
1189#endif
1190    int handshake_failure = 0;
1191    const mbedtls_ssl_ciphersuite_t *suite_info;
1192
1193    MBEDTLS_SSL_DEBUG_MSG(2, ("=> parse server hello"));
1194
1195    if ((ret = mbedtls_ssl_read_record(ssl, 1)) != 0) {
1196        /* No alert on a read error. */
1197        MBEDTLS_SSL_DEBUG_RET(1, "mbedtls_ssl_read_record", ret);
1198        return ret;
1199    }
1200
1201    buf = ssl->in_msg;
1202
1203    if (ssl->in_msgtype != MBEDTLS_SSL_MSG_HANDSHAKE) {
1204#if defined(MBEDTLS_SSL_RENEGOTIATION)
1205        if (ssl->renego_status == MBEDTLS_SSL_RENEGOTIATION_IN_PROGRESS) {
1206            ssl->renego_records_seen++;
1207
1208            if (ssl->conf->renego_max_records >= 0 &&
1209                ssl->renego_records_seen > ssl->conf->renego_max_records) {
1210                MBEDTLS_SSL_DEBUG_MSG(1,
1211                                      ("renegotiation requested, but not honored by server"));
1212                return MBEDTLS_ERR_SSL_UNEXPECTED_MESSAGE;
1213            }
1214
1215            MBEDTLS_SSL_DEBUG_MSG(1,
1216                                  ("non-handshake message during renegotiation"));
1217
1218            ssl->keep_current_message = 1;
1219            return MBEDTLS_ERR_SSL_WAITING_SERVER_HELLO_RENEGO;
1220        }
1221#endif /* MBEDTLS_SSL_RENEGOTIATION */
1222
1223        MBEDTLS_SSL_DEBUG_MSG(1, ("bad server hello message"));
1224        mbedtls_ssl_send_alert_message(
1225            ssl,
1226            MBEDTLS_SSL_ALERT_LEVEL_FATAL,
1227            MBEDTLS_SSL_ALERT_MSG_UNEXPECTED_MESSAGE);
1228        return MBEDTLS_ERR_SSL_UNEXPECTED_MESSAGE;
1229    }
1230
1231#if defined(MBEDTLS_SSL_PROTO_DTLS)
1232    if (ssl->conf->transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM) {
1233        if (buf[0] == MBEDTLS_SSL_HS_HELLO_VERIFY_REQUEST) {
1234            MBEDTLS_SSL_DEBUG_MSG(2, ("received hello verify request"));
1235            MBEDTLS_SSL_DEBUG_MSG(2, ("<= parse server hello"));
1236            return ssl_parse_hello_verify_request(ssl);
1237        } else {
1238            /* We made it through the verification process */
1239            mbedtls_free(ssl->handshake->cookie);
1240            ssl->handshake->cookie = NULL;
1241            ssl->handshake->cookie_len = 0;
1242        }
1243    }
1244#endif /* MBEDTLS_SSL_PROTO_DTLS */
1245
1246    if (ssl->in_hslen < 38 + mbedtls_ssl_hs_hdr_len(ssl) ||
1247        buf[0] != MBEDTLS_SSL_HS_SERVER_HELLO) {
1248        MBEDTLS_SSL_DEBUG_MSG(1, ("bad server hello message"));
1249        mbedtls_ssl_send_alert_message(ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,
1250                                       MBEDTLS_SSL_ALERT_MSG_DECODE_ERROR);
1251        return MBEDTLS_ERR_SSL_DECODE_ERROR;
1252    }
1253
1254    /*
1255     *  0   .  1    server_version
1256     *  2   . 33    random (maybe including 4 bytes of Unix time)
1257     * 34   . 34    session_id length = n
1258     * 35   . 34+n  session_id
1259     * 35+n . 36+n  cipher_suite
1260     * 37+n . 37+n  compression_method
1261     *
1262     * 38+n . 39+n  extensions length (optional)
1263     * 40+n .  ..   extensions
1264     */
1265    buf += mbedtls_ssl_hs_hdr_len(ssl);
1266
1267    MBEDTLS_SSL_DEBUG_BUF(3, "server hello, version", buf, 2);
1268    ssl->tls_version = (mbedtls_ssl_protocol_version) mbedtls_ssl_read_version(buf,
1269                                                                               ssl->conf->transport);
1270    ssl->session_negotiate->tls_version = ssl->tls_version;
1271    ssl->session_negotiate->endpoint = ssl->conf->endpoint;
1272
1273    if (ssl->tls_version < ssl->conf->min_tls_version ||
1274        ssl->tls_version > ssl->conf->max_tls_version) {
1275        MBEDTLS_SSL_DEBUG_MSG(1,
1276                              (
1277                                  "server version out of bounds -  min: [0x%x], server: [0x%x], max: [0x%x]",
1278                                  (unsigned) ssl->conf->min_tls_version,
1279                                  (unsigned) ssl->tls_version,
1280                                  (unsigned) ssl->conf->max_tls_version));
1281
1282        mbedtls_ssl_send_alert_message(ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,
1283                                       MBEDTLS_SSL_ALERT_MSG_PROTOCOL_VERSION);
1284
1285        return MBEDTLS_ERR_SSL_BAD_PROTOCOL_VERSION;
1286    }
1287
1288    MBEDTLS_SSL_DEBUG_MSG(3, ("server hello, current time: %lu",
1289                              ((unsigned long) buf[2] << 24) |
1290                              ((unsigned long) buf[3] << 16) |
1291                              ((unsigned long) buf[4] <<  8) |
1292                              ((unsigned long) buf[5])));
1293
1294    memcpy(ssl->handshake->randbytes + 32, buf + 2, 32);
1295
1296    n = buf[34];
1297
1298    MBEDTLS_SSL_DEBUG_BUF(3,   "server hello, random bytes", buf + 2, 32);
1299
1300    if (n > 32) {
1301        MBEDTLS_SSL_DEBUG_MSG(1, ("bad server hello message"));
1302        mbedtls_ssl_send_alert_message(ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,
1303                                       MBEDTLS_SSL_ALERT_MSG_DECODE_ERROR);
1304        return MBEDTLS_ERR_SSL_DECODE_ERROR;
1305    }
1306
1307    if (ssl->in_hslen > mbedtls_ssl_hs_hdr_len(ssl) + 39 + n) {
1308        ext_len = MBEDTLS_GET_UINT16_BE(buf, 38 + n);
1309
1310        if ((ext_len > 0 && ext_len < 4) ||
1311            ssl->in_hslen != mbedtls_ssl_hs_hdr_len(ssl) + 40 + n + ext_len) {
1312            MBEDTLS_SSL_DEBUG_MSG(1, ("bad server hello message"));
1313            mbedtls_ssl_send_alert_message(
1314                ssl,
1315                MBEDTLS_SSL_ALERT_LEVEL_FATAL,
1316                MBEDTLS_SSL_ALERT_MSG_DECODE_ERROR);
1317            return MBEDTLS_ERR_SSL_DECODE_ERROR;
1318        }
1319    } else if (ssl->in_hslen == mbedtls_ssl_hs_hdr_len(ssl) + 38 + n) {
1320        ext_len = 0;
1321    } else {
1322        MBEDTLS_SSL_DEBUG_MSG(1, ("bad server hello message"));
1323        mbedtls_ssl_send_alert_message(ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,
1324                                       MBEDTLS_SSL_ALERT_MSG_DECODE_ERROR);
1325        return MBEDTLS_ERR_SSL_DECODE_ERROR;
1326    }
1327
1328    /* ciphersuite (used later) */
1329    i = (int) MBEDTLS_GET_UINT16_BE(buf, n + 35);
1330
1331    /*
1332     * Read and check compression
1333     */
1334    comp = buf[37 + n];
1335
1336    if (comp != MBEDTLS_SSL_COMPRESS_NULL) {
1337        MBEDTLS_SSL_DEBUG_MSG(1,
1338                              ("server hello, bad compression: %d", comp));
1339        mbedtls_ssl_send_alert_message(
1340            ssl,
1341            MBEDTLS_SSL_ALERT_LEVEL_FATAL,
1342            MBEDTLS_SSL_ALERT_MSG_ILLEGAL_PARAMETER);
1343        return MBEDTLS_ERR_SSL_FEATURE_UNAVAILABLE;
1344    }
1345
1346    /*
1347     * Initialize update checksum functions
1348     */
1349    ssl->handshake->ciphersuite_info = mbedtls_ssl_ciphersuite_from_id(i);
1350    if (ssl->handshake->ciphersuite_info == NULL) {
1351        MBEDTLS_SSL_DEBUG_MSG(1,
1352                              ("ciphersuite info for %04x not found", (unsigned int) i));
1353        mbedtls_ssl_send_alert_message(ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,
1354                                       MBEDTLS_SSL_ALERT_MSG_INTERNAL_ERROR);
1355        return MBEDTLS_ERR_SSL_BAD_INPUT_DATA;
1356    }
1357
1358    mbedtls_ssl_optimize_checksum(ssl, ssl->handshake->ciphersuite_info);
1359
1360    MBEDTLS_SSL_DEBUG_MSG(3, ("server hello, session id len.: %" MBEDTLS_PRINTF_SIZET, n));
1361    MBEDTLS_SSL_DEBUG_BUF(3,   "server hello, session id", buf + 35, n);
1362
1363    /*
1364     * Check if the session can be resumed
1365     */
1366    if (ssl->handshake->resume == 0 || n == 0 ||
1367#if defined(MBEDTLS_SSL_RENEGOTIATION)
1368        ssl->renego_status != MBEDTLS_SSL_INITIAL_HANDSHAKE ||
1369#endif
1370        ssl->session_negotiate->ciphersuite != i ||
1371        ssl->session_negotiate->id_len != n ||
1372        memcmp(ssl->session_negotiate->id, buf + 35, n) != 0) {
1373        ssl->state++;
1374        ssl->handshake->resume = 0;
1375#if defined(MBEDTLS_HAVE_TIME)
1376        ssl->session_negotiate->start = mbedtls_time(NULL);
1377#endif
1378        ssl->session_negotiate->ciphersuite = i;
1379        ssl->session_negotiate->id_len = n;
1380        memcpy(ssl->session_negotiate->id, buf + 35, n);
1381    } else {
1382        ssl->state = MBEDTLS_SSL_SERVER_CHANGE_CIPHER_SPEC;
1383    }
1384
1385    MBEDTLS_SSL_DEBUG_MSG(3, ("%s session has been resumed",
1386                              ssl->handshake->resume ? "a" : "no"));
1387
1388    MBEDTLS_SSL_DEBUG_MSG(3, ("server hello, chosen ciphersuite: %04x", (unsigned) i));
1389    MBEDTLS_SSL_DEBUG_MSG(3, ("server hello, compress alg.: %d",
1390                              buf[37 + n]));
1391
1392    /*
1393     * Perform cipher suite validation in same way as in ssl_write_client_hello.
1394     */
1395    i = 0;
1396    while (1) {
1397        if (ssl->conf->ciphersuite_list[i] == 0) {
1398            MBEDTLS_SSL_DEBUG_MSG(1, ("bad server hello message"));
1399            mbedtls_ssl_send_alert_message(
1400                ssl,
1401                MBEDTLS_SSL_ALERT_LEVEL_FATAL,
1402                MBEDTLS_SSL_ALERT_MSG_ILLEGAL_PARAMETER);
1403            return MBEDTLS_ERR_SSL_ILLEGAL_PARAMETER;
1404        }
1405
1406        if (ssl->conf->ciphersuite_list[i++] ==
1407            ssl->session_negotiate->ciphersuite) {
1408            break;
1409        }
1410    }
1411
1412    suite_info = mbedtls_ssl_ciphersuite_from_id(
1413        ssl->session_negotiate->ciphersuite);
1414    if (mbedtls_ssl_validate_ciphersuite(ssl, suite_info, ssl->tls_version,
1415                                         ssl->tls_version) != 0) {
1416        MBEDTLS_SSL_DEBUG_MSG(1, ("bad server hello message"));
1417        mbedtls_ssl_send_alert_message(
1418            ssl,
1419            MBEDTLS_SSL_ALERT_LEVEL_FATAL,
1420            MBEDTLS_SSL_ALERT_MSG_HANDSHAKE_FAILURE);
1421        return MBEDTLS_ERR_SSL_HANDSHAKE_FAILURE;
1422    }
1423
1424    MBEDTLS_SSL_DEBUG_MSG(3,
1425                          ("server hello, chosen ciphersuite: %s", suite_info->name));
1426
1427#if defined(MBEDTLS_SSL_ECP_RESTARTABLE_ENABLED)
1428    if (suite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_ECDHE_ECDSA &&
1429        ssl->tls_version == MBEDTLS_SSL_VERSION_TLS1_2) {
1430        ssl->handshake->ecrs_enabled = 1;
1431    }
1432#endif
1433
1434    if (comp != MBEDTLS_SSL_COMPRESS_NULL) {
1435        MBEDTLS_SSL_DEBUG_MSG(1, ("bad server hello message"));
1436        mbedtls_ssl_send_alert_message(
1437            ssl,
1438            MBEDTLS_SSL_ALERT_LEVEL_FATAL,
1439            MBEDTLS_SSL_ALERT_MSG_ILLEGAL_PARAMETER);
1440        return MBEDTLS_ERR_SSL_ILLEGAL_PARAMETER;
1441    }
1442
1443    ext = buf + 40 + n;
1444
1445    MBEDTLS_SSL_DEBUG_MSG(2,
1446                          ("server hello, total extension length: %" MBEDTLS_PRINTF_SIZET,
1447                           ext_len));
1448
1449    while (ext_len) {
1450        unsigned int ext_id   = MBEDTLS_GET_UINT16_BE(ext, 0);
1451        unsigned int ext_size = MBEDTLS_GET_UINT16_BE(ext, 2);
1452
1453        if (ext_size + 4 > ext_len) {
1454            MBEDTLS_SSL_DEBUG_MSG(1, ("bad server hello message"));
1455            mbedtls_ssl_send_alert_message(
1456                ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,
1457                MBEDTLS_SSL_ALERT_MSG_DECODE_ERROR);
1458            return MBEDTLS_ERR_SSL_DECODE_ERROR;
1459        }
1460
1461        switch (ext_id) {
1462            case MBEDTLS_TLS_EXT_RENEGOTIATION_INFO:
1463                MBEDTLS_SSL_DEBUG_MSG(3, ("found renegotiation extension"));
1464#if defined(MBEDTLS_SSL_RENEGOTIATION)
1465                renegotiation_info_seen = 1;
1466#endif
1467
1468                if ((ret = ssl_parse_renegotiation_info(ssl, ext + 4,
1469                                                        ext_size)) != 0) {
1470                    return ret;
1471                }
1472
1473                break;
1474
1475#if defined(MBEDTLS_SSL_MAX_FRAGMENT_LENGTH)
1476            case MBEDTLS_TLS_EXT_MAX_FRAGMENT_LENGTH:
1477                MBEDTLS_SSL_DEBUG_MSG(3,
1478                                      ("found max_fragment_length extension"));
1479
1480                if ((ret = ssl_parse_max_fragment_length_ext(ssl,
1481                                                             ext + 4, ext_size)) != 0) {
1482                    return ret;
1483                }
1484
1485                break;
1486#endif /* MBEDTLS_SSL_MAX_FRAGMENT_LENGTH */
1487
1488#if defined(MBEDTLS_SSL_DTLS_CONNECTION_ID)
1489            case MBEDTLS_TLS_EXT_CID:
1490                MBEDTLS_SSL_DEBUG_MSG(3, ("found CID extension"));
1491
1492                if ((ret = ssl_parse_cid_ext(ssl,
1493                                             ext + 4,
1494                                             ext_size)) != 0) {
1495                    return ret;
1496                }
1497
1498                break;
1499#endif /* MBEDTLS_SSL_DTLS_CONNECTION_ID */
1500
1501#if defined(MBEDTLS_SSL_ENCRYPT_THEN_MAC)
1502            case MBEDTLS_TLS_EXT_ENCRYPT_THEN_MAC:
1503                MBEDTLS_SSL_DEBUG_MSG(3, ("found encrypt_then_mac extension"));
1504
1505                if ((ret = ssl_parse_encrypt_then_mac_ext(ssl,
1506                                                          ext + 4, ext_size)) != 0) {
1507                    return ret;
1508                }
1509
1510                break;
1511#endif /* MBEDTLS_SSL_ENCRYPT_THEN_MAC */
1512
1513#if defined(MBEDTLS_SSL_EXTENDED_MASTER_SECRET)
1514            case MBEDTLS_TLS_EXT_EXTENDED_MASTER_SECRET:
1515                MBEDTLS_SSL_DEBUG_MSG(3,
1516                                      ("found extended_master_secret extension"));
1517
1518                if ((ret = ssl_parse_extended_ms_ext(ssl,
1519                                                     ext + 4, ext_size)) != 0) {
1520                    return ret;
1521                }
1522
1523                break;
1524#endif /* MBEDTLS_SSL_EXTENDED_MASTER_SECRET */
1525
1526#if defined(MBEDTLS_SSL_SESSION_TICKETS)
1527            case MBEDTLS_TLS_EXT_SESSION_TICKET:
1528                MBEDTLS_SSL_DEBUG_MSG(3, ("found session_ticket extension"));
1529
1530                if ((ret = ssl_parse_session_ticket_ext(ssl,
1531                                                        ext + 4, ext_size)) != 0) {
1532                    return ret;
1533                }
1534
1535                break;
1536#endif /* MBEDTLS_SSL_SESSION_TICKETS */
1537
1538#if defined(MBEDTLS_KEY_EXCHANGE_SOME_ECDH_OR_ECDHE_1_2_ENABLED) || \
1539                defined(MBEDTLS_KEY_EXCHANGE_ECDSA_CERT_REQ_ALLOWED_ENABLED) || \
1540                defined(MBEDTLS_KEY_EXCHANGE_ECJPAKE_ENABLED)
1541            case MBEDTLS_TLS_EXT_SUPPORTED_POINT_FORMATS:
1542                MBEDTLS_SSL_DEBUG_MSG(3,
1543                                      ("found supported_point_formats extension"));
1544
1545                if ((ret = ssl_parse_supported_point_formats_ext(ssl,
1546                                                                 ext + 4, ext_size)) != 0) {
1547                    return ret;
1548                }
1549
1550                break;
1551#endif /* MBEDTLS_KEY_EXCHANGE_SOME_ECDH_OR_ECDHE_1_2_ENABLED ||
1552          MBEDTLS_KEY_EXCHANGE_ECDSA_CERT_REQ_ALLOWED_ENABLED ||
1553          MBEDTLS_KEY_EXCHANGE_ECJPAKE_ENABLED */
1554
1555#if defined(MBEDTLS_KEY_EXCHANGE_ECJPAKE_ENABLED)
1556            case MBEDTLS_TLS_EXT_ECJPAKE_KKPP:
1557                MBEDTLS_SSL_DEBUG_MSG(3, ("found ecjpake_kkpp extension"));
1558
1559                if ((ret = ssl_parse_ecjpake_kkpp(ssl,
1560                                                  ext + 4, ext_size)) != 0) {
1561                    return ret;
1562                }
1563
1564                break;
1565#endif /* MBEDTLS_KEY_EXCHANGE_ECJPAKE_ENABLED */
1566
1567#if defined(MBEDTLS_SSL_ALPN)
1568            case MBEDTLS_TLS_EXT_ALPN:
1569                MBEDTLS_SSL_DEBUG_MSG(3, ("found alpn extension"));
1570
1571                if ((ret = ssl_parse_alpn_ext(ssl, ext + 4, ext_size)) != 0) {
1572                    return ret;
1573                }
1574
1575                break;
1576#endif /* MBEDTLS_SSL_ALPN */
1577
1578#if defined(MBEDTLS_SSL_DTLS_SRTP)
1579            case MBEDTLS_TLS_EXT_USE_SRTP:
1580                MBEDTLS_SSL_DEBUG_MSG(3, ("found use_srtp extension"));
1581
1582                if ((ret = ssl_parse_use_srtp_ext(ssl, ext + 4, ext_size)) != 0) {
1583                    return ret;
1584                }
1585
1586                break;
1587#endif /* MBEDTLS_SSL_DTLS_SRTP */
1588
1589            default:
1590                MBEDTLS_SSL_DEBUG_MSG(3,
1591                                      ("unknown extension found: %u (ignoring)", ext_id));
1592        }
1593
1594        ext_len -= 4 + ext_size;
1595        ext += 4 + ext_size;
1596
1597        if (ext_len > 0 && ext_len < 4) {
1598            MBEDTLS_SSL_DEBUG_MSG(1, ("bad server hello message"));
1599            return MBEDTLS_ERR_SSL_DECODE_ERROR;
1600        }
1601    }
1602
1603    /*
1604     * mbedtls_ssl_derive_keys() has to be called after the parsing of the
1605     * extensions. It sets the transform data for the resumed session which in
1606     * case of DTLS includes the server CID extracted from the CID extension.
1607     */
1608    if (ssl->handshake->resume) {
1609        if ((ret = mbedtls_ssl_derive_keys(ssl)) != 0) {
1610            MBEDTLS_SSL_DEBUG_RET(1, "mbedtls_ssl_derive_keys", ret);
1611            mbedtls_ssl_send_alert_message(
1612                ssl,
1613                MBEDTLS_SSL_ALERT_LEVEL_FATAL,
1614                MBEDTLS_SSL_ALERT_MSG_INTERNAL_ERROR);
1615            return ret;
1616        }
1617    }
1618
1619    /*
1620     * Renegotiation security checks
1621     */
1622    if (ssl->secure_renegotiation == MBEDTLS_SSL_LEGACY_RENEGOTIATION &&
1623        ssl->conf->allow_legacy_renegotiation ==
1624        MBEDTLS_SSL_LEGACY_BREAK_HANDSHAKE) {
1625        MBEDTLS_SSL_DEBUG_MSG(1,
1626                              ("legacy renegotiation, breaking off handshake"));
1627        handshake_failure = 1;
1628    }
1629#if defined(MBEDTLS_SSL_RENEGOTIATION)
1630    else if (ssl->renego_status == MBEDTLS_SSL_RENEGOTIATION_IN_PROGRESS &&
1631             ssl->secure_renegotiation == MBEDTLS_SSL_SECURE_RENEGOTIATION &&
1632             renegotiation_info_seen == 0) {
1633        MBEDTLS_SSL_DEBUG_MSG(1,
1634                              ("renegotiation_info extension missing (secure)"));
1635        handshake_failure = 1;
1636    } else if (ssl->renego_status == MBEDTLS_SSL_RENEGOTIATION_IN_PROGRESS &&
1637               ssl->secure_renegotiation == MBEDTLS_SSL_LEGACY_RENEGOTIATION &&
1638               ssl->conf->allow_legacy_renegotiation ==
1639               MBEDTLS_SSL_LEGACY_NO_RENEGOTIATION) {
1640        MBEDTLS_SSL_DEBUG_MSG(1, ("legacy renegotiation not allowed"));
1641        handshake_failure = 1;
1642    } else if (ssl->renego_status == MBEDTLS_SSL_RENEGOTIATION_IN_PROGRESS &&
1643               ssl->secure_renegotiation == MBEDTLS_SSL_LEGACY_RENEGOTIATION &&
1644               renegotiation_info_seen == 1) {
1645        MBEDTLS_SSL_DEBUG_MSG(1,
1646                              ("renegotiation_info extension present (legacy)"));
1647        handshake_failure = 1;
1648    }
1649#endif /* MBEDTLS_SSL_RENEGOTIATION */
1650
1651    if (handshake_failure == 1) {
1652        mbedtls_ssl_send_alert_message(
1653            ssl,
1654            MBEDTLS_SSL_ALERT_LEVEL_FATAL,
1655            MBEDTLS_SSL_ALERT_MSG_HANDSHAKE_FAILURE);
1656        return MBEDTLS_ERR_SSL_HANDSHAKE_FAILURE;
1657    }
1658
1659    MBEDTLS_SSL_DEBUG_MSG(2, ("<= parse server hello"));
1660
1661    return 0;
1662}
1663
1664#if defined(MBEDTLS_KEY_EXCHANGE_DHE_RSA_ENABLED) ||                       \
1665    defined(MBEDTLS_KEY_EXCHANGE_DHE_PSK_ENABLED)
1666MBEDTLS_CHECK_RETURN_CRITICAL
1667static int ssl_parse_server_dh_params(mbedtls_ssl_context *ssl,
1668                                      unsigned char **p,
1669                                      unsigned char *end)
1670{
1671    int ret = MBEDTLS_ERR_SSL_FEATURE_UNAVAILABLE;
1672    size_t dhm_actual_bitlen;
1673
1674    /*
1675     * Ephemeral DH parameters:
1676     *
1677     * struct {
1678     *     opaque dh_p<1..2^16-1>;
1679     *     opaque dh_g<1..2^16-1>;
1680     *     opaque dh_Ys<1..2^16-1>;
1681     * } ServerDHParams;
1682     */
1683    if ((ret = mbedtls_dhm_read_params(&ssl->handshake->dhm_ctx,
1684                                       p, end)) != 0) {
1685        MBEDTLS_SSL_DEBUG_RET(2, ("mbedtls_dhm_read_params"), ret);
1686        return ret;
1687    }
1688
1689    dhm_actual_bitlen = mbedtls_dhm_get_bitlen(&ssl->handshake->dhm_ctx);
1690    if (dhm_actual_bitlen < ssl->conf->dhm_min_bitlen) {
1691        MBEDTLS_SSL_DEBUG_MSG(1, ("DHM prime too short: %" MBEDTLS_PRINTF_SIZET " < %u",
1692                                  dhm_actual_bitlen,
1693                                  ssl->conf->dhm_min_bitlen));
1694        return MBEDTLS_ERR_SSL_HANDSHAKE_FAILURE;
1695    }
1696
1697    MBEDTLS_SSL_DEBUG_MPI(3, "DHM: P ", &ssl->handshake->dhm_ctx.P);
1698    MBEDTLS_SSL_DEBUG_MPI(3, "DHM: G ", &ssl->handshake->dhm_ctx.G);
1699    MBEDTLS_SSL_DEBUG_MPI(3, "DHM: GY", &ssl->handshake->dhm_ctx.GY);
1700
1701    return ret;
1702}
1703#endif /* MBEDTLS_KEY_EXCHANGE_DHE_RSA_ENABLED ||
1704          MBEDTLS_KEY_EXCHANGE_DHE_PSK_ENABLED */
1705
1706#if defined(MBEDTLS_USE_PSA_CRYPTO)
1707#if defined(MBEDTLS_KEY_EXCHANGE_ECDHE_RSA_ENABLED)   ||   \
1708    defined(MBEDTLS_KEY_EXCHANGE_ECDHE_PSK_ENABLED)   ||   \
1709    defined(MBEDTLS_KEY_EXCHANGE_ECDHE_ECDSA_ENABLED)
1710MBEDTLS_CHECK_RETURN_CRITICAL
1711static int ssl_parse_server_ecdh_params(mbedtls_ssl_context *ssl,
1712                                        unsigned char **p,
1713                                        unsigned char *end)
1714{
1715    uint16_t tls_id;
1716    size_t ecpoint_len;
1717    mbedtls_ssl_handshake_params *handshake = ssl->handshake;
1718    psa_key_type_t key_type = PSA_KEY_TYPE_NONE;
1719    size_t ec_bits = 0;
1720
1721    /*
1722     * struct {
1723     *     ECParameters curve_params;
1724     *     ECPoint      public;
1725     * } ServerECDHParams;
1726     *
1727     *  1       curve_type (must be "named_curve")
1728     *  2..3    NamedCurve
1729     *  4       ECPoint.len
1730     *  5+      ECPoint contents
1731     */
1732    if (end - *p < 4) {
1733        return MBEDTLS_ERR_SSL_DECODE_ERROR;
1734    }
1735
1736    /* First byte is curve_type; only named_curve is handled */
1737    if (*(*p)++ != MBEDTLS_ECP_TLS_NAMED_CURVE) {
1738        return MBEDTLS_ERR_SSL_HANDSHAKE_FAILURE;
1739    }
1740
1741    /* Next two bytes are the namedcurve value */
1742    tls_id = MBEDTLS_GET_UINT16_BE(*p, 0);
1743    *p += 2;
1744
1745    /* Check it's a curve we offered */
1746    if (mbedtls_ssl_check_curve_tls_id(ssl, tls_id) != 0) {
1747        MBEDTLS_SSL_DEBUG_MSG(2,
1748                              ("bad server key exchange message (ECDHE curve): %u",
1749                               (unsigned) tls_id));
1750        return MBEDTLS_ERR_SSL_HANDSHAKE_FAILURE;
1751    }
1752
1753    /* Convert EC's TLS ID to PSA key type. */
1754    if (mbedtls_ssl_get_psa_curve_info_from_tls_id(tls_id, &key_type,
1755                                                   &ec_bits) == PSA_ERROR_NOT_SUPPORTED) {
1756        return MBEDTLS_ERR_SSL_HANDSHAKE_FAILURE;
1757    }
1758    handshake->xxdh_psa_type = key_type;
1759    handshake->xxdh_psa_bits = ec_bits;
1760
1761    /* Keep a copy of the peer's public key */
1762    ecpoint_len = *(*p)++;
1763    if ((size_t) (end - *p) < ecpoint_len) {
1764        return MBEDTLS_ERR_SSL_DECODE_ERROR;
1765    }
1766
1767    if (ecpoint_len > sizeof(handshake->xxdh_psa_peerkey)) {
1768        return MBEDTLS_ERR_SSL_HANDSHAKE_FAILURE;
1769    }
1770
1771    memcpy(handshake->xxdh_psa_peerkey, *p, ecpoint_len);
1772    handshake->xxdh_psa_peerkey_len = ecpoint_len;
1773    *p += ecpoint_len;
1774
1775    return 0;
1776}
1777#endif /* MBEDTLS_KEY_EXCHANGE_ECDHE_RSA_ENABLED   ||
1778          MBEDTLS_KEY_EXCHANGE_ECDHE_PSK_ENABLED   ||
1779          MBEDTLS_KEY_EXCHANGE_ECDHE_ECDSA_ENABLED */
1780#else
1781#if defined(MBEDTLS_KEY_EXCHANGE_ECDHE_RSA_ENABLED)   ||   \
1782    defined(MBEDTLS_KEY_EXCHANGE_ECDH_RSA_ENABLED)    ||   \
1783    defined(MBEDTLS_KEY_EXCHANGE_ECDHE_PSK_ENABLED)   ||   \
1784    defined(MBEDTLS_KEY_EXCHANGE_ECDHE_ECDSA_ENABLED) ||   \
1785    defined(MBEDTLS_KEY_EXCHANGE_ECDH_ECDSA_ENABLED)
1786MBEDTLS_CHECK_RETURN_CRITICAL
1787static int ssl_check_server_ecdh_params(const mbedtls_ssl_context *ssl)
1788{
1789    uint16_t tls_id;
1790    mbedtls_ecp_group_id grp_id;
1791#if defined(MBEDTLS_ECDH_LEGACY_CONTEXT)
1792    grp_id = ssl->handshake->ecdh_ctx.grp.id;
1793#else
1794    grp_id = ssl->handshake->ecdh_ctx.grp_id;
1795#endif
1796
1797    tls_id = mbedtls_ssl_get_tls_id_from_ecp_group_id(grp_id);
1798    if (tls_id == 0) {
1799        MBEDTLS_SSL_DEBUG_MSG(1, ("should never happen"));
1800        return MBEDTLS_ERR_SSL_INTERNAL_ERROR;
1801    }
1802
1803    MBEDTLS_SSL_DEBUG_MSG(2, ("ECDH curve: %s",
1804                              mbedtls_ssl_get_curve_name_from_tls_id(tls_id)));
1805
1806    if (mbedtls_ssl_check_curve(ssl, grp_id) != 0) {
1807        return -1;
1808    }
1809
1810    MBEDTLS_SSL_DEBUG_ECDH(3, &ssl->handshake->ecdh_ctx,
1811                           MBEDTLS_DEBUG_ECDH_QP);
1812
1813    return 0;
1814}
1815
1816#endif /* MBEDTLS_KEY_EXCHANGE_ECDHE_RSA_ENABLED   ||
1817          MBEDTLS_KEY_EXCHANGE_ECDH_RSA_ENABLED    ||
1818          MBEDTLS_KEY_EXCHANGE_ECDHE_PSK_ENABLED   ||
1819          MBEDTLS_KEY_EXCHANGE_ECDHE_ECDSA_ENABLED ||
1820          MBEDTLS_KEY_EXCHANGE_ECDH_ECDSA_ENABLED */
1821
1822#if defined(MBEDTLS_KEY_EXCHANGE_ECDHE_RSA_ENABLED) ||     \
1823    defined(MBEDTLS_KEY_EXCHANGE_ECDHE_PSK_ENABLED) ||     \
1824    defined(MBEDTLS_KEY_EXCHANGE_ECDHE_ECDSA_ENABLED)
1825MBEDTLS_CHECK_RETURN_CRITICAL
1826static int ssl_parse_server_ecdh_params(mbedtls_ssl_context *ssl,
1827                                        unsigned char **p,
1828                                        unsigned char *end)
1829{
1830    int ret = MBEDTLS_ERR_SSL_FEATURE_UNAVAILABLE;
1831
1832    /*
1833     * Ephemeral ECDH parameters:
1834     *
1835     * struct {
1836     *     ECParameters curve_params;
1837     *     ECPoint      public;
1838     * } ServerECDHParams;
1839     */
1840    if ((ret = mbedtls_ecdh_read_params(&ssl->handshake->ecdh_ctx,
1841                                        (const unsigned char **) p, end)) != 0) {
1842        MBEDTLS_SSL_DEBUG_RET(1, ("mbedtls_ecdh_read_params"), ret);
1843#if defined(MBEDTLS_SSL_ECP_RESTARTABLE_ENABLED)
1844        if (ret == MBEDTLS_ERR_ECP_IN_PROGRESS) {
1845            ret = MBEDTLS_ERR_SSL_CRYPTO_IN_PROGRESS;
1846        }
1847#endif
1848        return ret;
1849    }
1850
1851    if (ssl_check_server_ecdh_params(ssl) != 0) {
1852        MBEDTLS_SSL_DEBUG_MSG(1,
1853                              ("bad server key exchange message (ECDHE curve)"));
1854        return MBEDTLS_ERR_SSL_HANDSHAKE_FAILURE;
1855    }
1856
1857    return ret;
1858}
1859#endif /* MBEDTLS_KEY_EXCHANGE_ECDHE_RSA_ENABLED || \
1860          MBEDTLS_KEY_EXCHANGE_ECDHE_PSK_ENABLED || \
1861          MBEDTLS_KEY_EXCHANGE_ECDHE_ECDSA_ENABLED */
1862#endif /* !MBEDTLS_USE_PSA_CRYPTO */
1863#if defined(MBEDTLS_KEY_EXCHANGE_SOME_PSK_ENABLED)
1864MBEDTLS_CHECK_RETURN_CRITICAL
1865static int ssl_parse_server_psk_hint(mbedtls_ssl_context *ssl,
1866                                     unsigned char **p,
1867                                     unsigned char *end)
1868{
1869    int ret = MBEDTLS_ERR_SSL_FEATURE_UNAVAILABLE;
1870    uint16_t  len;
1871    ((void) ssl);
1872
1873    /*
1874     * PSK parameters:
1875     *
1876     * opaque psk_identity_hint<0..2^16-1>;
1877     */
1878    if (end - (*p) < 2) {
1879        MBEDTLS_SSL_DEBUG_MSG(1,
1880                              ("bad server key exchange message (psk_identity_hint length)"));
1881        return MBEDTLS_ERR_SSL_DECODE_ERROR;
1882    }
1883    len = MBEDTLS_GET_UINT16_BE(*p, 0);
1884    *p += 2;
1885
1886    if (end - (*p) < len) {
1887        MBEDTLS_SSL_DEBUG_MSG(1,
1888                              ("bad server key exchange message (psk_identity_hint length)"));
1889        return MBEDTLS_ERR_SSL_DECODE_ERROR;
1890    }
1891
1892    /*
1893     * Note: we currently ignore the PSK identity hint, as we only allow one
1894     * PSK to be provisioned on the client. This could be changed later if
1895     * someone needs that feature.
1896     */
1897    *p += len;
1898    ret = 0;
1899
1900    return ret;
1901}
1902#endif /* MBEDTLS_KEY_EXCHANGE_SOME_PSK_ENABLED */
1903
1904#if defined(MBEDTLS_KEY_EXCHANGE_RSA_ENABLED) ||                           \
1905    defined(MBEDTLS_KEY_EXCHANGE_RSA_PSK_ENABLED)
1906/*
1907 * Generate a pre-master secret and encrypt it with the server's RSA key
1908 */
1909MBEDTLS_CHECK_RETURN_CRITICAL
1910static int ssl_write_encrypted_pms(mbedtls_ssl_context *ssl,
1911                                   size_t offset, size_t *olen,
1912                                   size_t pms_offset)
1913{
1914    int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
1915    size_t len_bytes = 2;
1916    unsigned char *p = ssl->handshake->premaster + pms_offset;
1917    mbedtls_pk_context *peer_pk;
1918
1919    if (offset + len_bytes > MBEDTLS_SSL_OUT_CONTENT_LEN) {
1920        MBEDTLS_SSL_DEBUG_MSG(1, ("buffer too small for encrypted pms"));
1921        return MBEDTLS_ERR_SSL_BUFFER_TOO_SMALL;
1922    }
1923
1924    /*
1925     * Generate (part of) the pre-master as
1926     *  struct {
1927     *      ProtocolVersion client_version;
1928     *      opaque random[46];
1929     *  } PreMasterSecret;
1930     */
1931    mbedtls_ssl_write_version(p, ssl->conf->transport,
1932                              MBEDTLS_SSL_VERSION_TLS1_2);
1933
1934    if ((ret = ssl->conf->f_rng(ssl->conf->p_rng, p + 2, 46)) != 0) {
1935        MBEDTLS_SSL_DEBUG_RET(1, "f_rng", ret);
1936        return ret;
1937    }
1938
1939    ssl->handshake->pmslen = 48;
1940
1941#if !defined(MBEDTLS_SSL_KEEP_PEER_CERTIFICATE)
1942    peer_pk = &ssl->handshake->peer_pubkey;
1943#else /* !MBEDTLS_SSL_KEEP_PEER_CERTIFICATE */
1944    if (ssl->session_negotiate->peer_cert == NULL) {
1945        /* Should never happen */
1946        MBEDTLS_SSL_DEBUG_MSG(1, ("should never happen"));
1947        return MBEDTLS_ERR_SSL_INTERNAL_ERROR;
1948    }
1949    peer_pk = &ssl->session_negotiate->peer_cert->pk;
1950#endif /* MBEDTLS_SSL_KEEP_PEER_CERTIFICATE */
1951
1952    /*
1953     * Now write it out, encrypted
1954     */
1955    if (!mbedtls_pk_can_do(peer_pk, MBEDTLS_PK_RSA)) {
1956        MBEDTLS_SSL_DEBUG_MSG(1, ("certificate key type mismatch"));
1957        return MBEDTLS_ERR_SSL_PK_TYPE_MISMATCH;
1958    }
1959
1960    if ((ret = mbedtls_pk_encrypt(peer_pk,
1961                                  p, ssl->handshake->pmslen,
1962                                  ssl->out_msg + offset + len_bytes, olen,
1963                                  MBEDTLS_SSL_OUT_CONTENT_LEN - offset - len_bytes,
1964                                  ssl->conf->f_rng, ssl->conf->p_rng)) != 0) {
1965        MBEDTLS_SSL_DEBUG_RET(1, "mbedtls_rsa_pkcs1_encrypt", ret);
1966        return ret;
1967    }
1968
1969    if (len_bytes == 2) {
1970        MBEDTLS_PUT_UINT16_BE(*olen, ssl->out_msg, offset);
1971        *olen += 2;
1972    }
1973
1974#if !defined(MBEDTLS_SSL_KEEP_PEER_CERTIFICATE)
1975    /* We don't need the peer's public key anymore. Free it. */
1976    mbedtls_pk_free(peer_pk);
1977#endif /* !MBEDTLS_SSL_KEEP_PEER_CERTIFICATE */
1978    return 0;
1979}
1980#endif /* MBEDTLS_KEY_EXCHANGE_RSA_ENABLED ||
1981          MBEDTLS_KEY_EXCHANGE_RSA_PSK_ENABLED */
1982
1983#if defined(MBEDTLS_KEY_EXCHANGE_ECDH_RSA_ENABLED) || \
1984    defined(MBEDTLS_KEY_EXCHANGE_ECDH_ECDSA_ENABLED)
1985MBEDTLS_CHECK_RETURN_CRITICAL
1986static int ssl_get_ecdh_params_from_cert(mbedtls_ssl_context *ssl)
1987{
1988    int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
1989    mbedtls_pk_context *peer_pk;
1990
1991#if !defined(MBEDTLS_SSL_KEEP_PEER_CERTIFICATE)
1992    peer_pk = &ssl->handshake->peer_pubkey;
1993#else /* !MBEDTLS_SSL_KEEP_PEER_CERTIFICATE */
1994    if (ssl->session_negotiate->peer_cert == NULL) {
1995        /* Should never happen */
1996        MBEDTLS_SSL_DEBUG_MSG(1, ("should never happen"));
1997        return MBEDTLS_ERR_SSL_INTERNAL_ERROR;
1998    }
1999    peer_pk = &ssl->session_negotiate->peer_cert->pk;
2000#endif /* MBEDTLS_SSL_KEEP_PEER_CERTIFICATE */
2001
2002    /* This is a public key, so it can't be opaque, so can_do() is a good
2003     * enough check to ensure pk_ec() is safe to use below. */
2004    if (!mbedtls_pk_can_do(peer_pk, MBEDTLS_PK_ECKEY)) {
2005        MBEDTLS_SSL_DEBUG_MSG(1, ("server key not ECDH capable"));
2006        return MBEDTLS_ERR_SSL_PK_TYPE_MISMATCH;
2007    }
2008
2009#if !defined(MBEDTLS_PK_USE_PSA_EC_DATA)
2010    const mbedtls_ecp_keypair *peer_key = mbedtls_pk_ec_ro(*peer_pk);
2011#endif /* !defined(MBEDTLS_PK_USE_PSA_EC_DATA) */
2012
2013#if defined(MBEDTLS_USE_PSA_CRYPTO)
2014    uint16_t tls_id = 0;
2015    psa_key_type_t key_type = PSA_KEY_TYPE_NONE;
2016    mbedtls_ecp_group_id grp_id = mbedtls_pk_get_ec_group_id(peer_pk);
2017
2018    if (mbedtls_ssl_check_curve(ssl, grp_id) != 0) {
2019        MBEDTLS_SSL_DEBUG_MSG(1, ("bad server certificate (ECDH curve)"));
2020        return MBEDTLS_ERR_SSL_BAD_CERTIFICATE;
2021    }
2022
2023    tls_id = mbedtls_ssl_get_tls_id_from_ecp_group_id(grp_id);
2024    if (tls_id == 0) {
2025        MBEDTLS_SSL_DEBUG_MSG(1, ("ECC group %u not suported",
2026                                  grp_id));
2027        return MBEDTLS_ERR_SSL_ILLEGAL_PARAMETER;
2028    }
2029
2030    /* If the above conversion to TLS ID was fine, then also this one will be,
2031       so there is no need to check the return value here */
2032    mbedtls_ssl_get_psa_curve_info_from_tls_id(tls_id, &key_type,
2033                                               &ssl->handshake->xxdh_psa_bits);
2034
2035    ssl->handshake->xxdh_psa_type = key_type;
2036
2037    /* Store peer's public key in psa format. */
2038#if defined(MBEDTLS_PK_USE_PSA_EC_DATA)
2039    memcpy(ssl->handshake->xxdh_psa_peerkey, peer_pk->pub_raw, peer_pk->pub_raw_len);
2040    ssl->handshake->xxdh_psa_peerkey_len = peer_pk->pub_raw_len;
2041    ret = 0;
2042#else /* MBEDTLS_PK_USE_PSA_EC_DATA */
2043    size_t olen = 0;
2044    ret = mbedtls_ecp_point_write_binary(&peer_key->grp, &peer_key->Q,
2045                                         MBEDTLS_ECP_PF_UNCOMPRESSED, &olen,
2046                                         ssl->handshake->xxdh_psa_peerkey,
2047                                         sizeof(ssl->handshake->xxdh_psa_peerkey));
2048
2049    if (ret != 0) {
2050        MBEDTLS_SSL_DEBUG_RET(1, ("mbedtls_ecp_point_write_binary"), ret);
2051        return ret;
2052    }
2053    ssl->handshake->xxdh_psa_peerkey_len = olen;
2054#endif /* MBEDTLS_PK_USE_PSA_EC_DATA */
2055#else /* MBEDTLS_USE_PSA_CRYPTO */
2056    if ((ret = mbedtls_ecdh_get_params(&ssl->handshake->ecdh_ctx, peer_key,
2057                                       MBEDTLS_ECDH_THEIRS)) != 0) {
2058        MBEDTLS_SSL_DEBUG_RET(1, ("mbedtls_ecdh_get_params"), ret);
2059        return ret;
2060    }
2061
2062    if (ssl_check_server_ecdh_params(ssl) != 0) {
2063        MBEDTLS_SSL_DEBUG_MSG(1, ("bad server certificate (ECDH curve)"));
2064        return MBEDTLS_ERR_SSL_BAD_CERTIFICATE;
2065    }
2066#endif /* MBEDTLS_USE_PSA_CRYPTO */
2067#if !defined(MBEDTLS_SSL_KEEP_PEER_CERTIFICATE)
2068    /* We don't need the peer's public key anymore. Free it,
2069     * so that more RAM is available for upcoming expensive
2070     * operations like ECDHE. */
2071    mbedtls_pk_free(peer_pk);
2072#endif /* !MBEDTLS_SSL_KEEP_PEER_CERTIFICATE */
2073
2074    return ret;
2075}
2076#endif /* MBEDTLS_KEY_EXCHANGE_ECDH_RSA_ENABLED) ||
2077          MBEDTLS_KEY_EXCHANGE_ECDH_ECDSA_ENABLED */
2078
2079MBEDTLS_CHECK_RETURN_CRITICAL
2080static int ssl_parse_server_key_exchange(mbedtls_ssl_context *ssl)
2081{
2082    int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
2083    const mbedtls_ssl_ciphersuite_t *ciphersuite_info =
2084        ssl->handshake->ciphersuite_info;
2085    unsigned char *p = NULL, *end = NULL;
2086
2087    MBEDTLS_SSL_DEBUG_MSG(2, ("=> parse server key exchange"));
2088
2089#if defined(MBEDTLS_KEY_EXCHANGE_RSA_ENABLED)
2090    if (ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_RSA) {
2091        MBEDTLS_SSL_DEBUG_MSG(2, ("<= skip parse server key exchange"));
2092        ssl->state++;
2093        return 0;
2094    }
2095    ((void) p);
2096    ((void) end);
2097#endif
2098
2099#if defined(MBEDTLS_KEY_EXCHANGE_ECDH_RSA_ENABLED) || \
2100    defined(MBEDTLS_KEY_EXCHANGE_ECDH_ECDSA_ENABLED)
2101    if (ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_ECDH_RSA ||
2102        ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_ECDH_ECDSA) {
2103        if ((ret = ssl_get_ecdh_params_from_cert(ssl)) != 0) {
2104            MBEDTLS_SSL_DEBUG_RET(1, "ssl_get_ecdh_params_from_cert", ret);
2105            mbedtls_ssl_send_alert_message(
2106                ssl,
2107                MBEDTLS_SSL_ALERT_LEVEL_FATAL,
2108                MBEDTLS_SSL_ALERT_MSG_HANDSHAKE_FAILURE);
2109            return ret;
2110        }
2111
2112        MBEDTLS_SSL_DEBUG_MSG(2, ("<= skip parse server key exchange"));
2113        ssl->state++;
2114        return 0;
2115    }
2116    ((void) p);
2117    ((void) end);
2118#endif /* MBEDTLS_KEY_EXCHANGE_ECDH_RSA_ENABLED ||
2119          MBEDTLS_KEY_EXCHANGE_ECDH_ECDSA_ENABLED */
2120
2121#if defined(MBEDTLS_SSL_ECP_RESTARTABLE_ENABLED)
2122    if (ssl->handshake->ecrs_enabled &&
2123        ssl->handshake->ecrs_state == ssl_ecrs_ske_start_processing) {
2124        goto start_processing;
2125    }
2126#endif
2127
2128    if ((ret = mbedtls_ssl_read_record(ssl, 1)) != 0) {
2129        MBEDTLS_SSL_DEBUG_RET(1, "mbedtls_ssl_read_record", ret);
2130        return ret;
2131    }
2132
2133    if (ssl->in_msgtype != MBEDTLS_SSL_MSG_HANDSHAKE) {
2134        MBEDTLS_SSL_DEBUG_MSG(1, ("bad server key exchange message"));
2135        mbedtls_ssl_send_alert_message(
2136            ssl,
2137            MBEDTLS_SSL_ALERT_LEVEL_FATAL,
2138            MBEDTLS_SSL_ALERT_MSG_UNEXPECTED_MESSAGE);
2139        return MBEDTLS_ERR_SSL_UNEXPECTED_MESSAGE;
2140    }
2141
2142    /*
2143     * ServerKeyExchange may be skipped with PSK and RSA-PSK when the server
2144     * doesn't use a psk_identity_hint
2145     */
2146    if (ssl->in_msg[0] != MBEDTLS_SSL_HS_SERVER_KEY_EXCHANGE) {
2147        if (ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_PSK ||
2148            ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_RSA_PSK) {
2149            /* Current message is probably either
2150             * CertificateRequest or ServerHelloDone */
2151            ssl->keep_current_message = 1;
2152            goto exit;
2153        }
2154
2155        MBEDTLS_SSL_DEBUG_MSG(1,
2156                              ("server key exchange message must not be skipped"));
2157        mbedtls_ssl_send_alert_message(
2158            ssl,
2159            MBEDTLS_SSL_ALERT_LEVEL_FATAL,
2160            MBEDTLS_SSL_ALERT_MSG_UNEXPECTED_MESSAGE);
2161
2162        return MBEDTLS_ERR_SSL_UNEXPECTED_MESSAGE;
2163    }
2164
2165#if defined(MBEDTLS_SSL_ECP_RESTARTABLE_ENABLED)
2166    if (ssl->handshake->ecrs_enabled) {
2167        ssl->handshake->ecrs_state = ssl_ecrs_ske_start_processing;
2168    }
2169
2170start_processing:
2171#endif
2172    p   = ssl->in_msg + mbedtls_ssl_hs_hdr_len(ssl);
2173    end = ssl->in_msg + ssl->in_hslen;
2174    MBEDTLS_SSL_DEBUG_BUF(3,   "server key exchange", p, (size_t) (end - p));
2175
2176#if defined(MBEDTLS_KEY_EXCHANGE_SOME_PSK_ENABLED)
2177    if (ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_PSK ||
2178        ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_RSA_PSK ||
2179        ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_DHE_PSK ||
2180        ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_ECDHE_PSK) {
2181        if (ssl_parse_server_psk_hint(ssl, &p, end) != 0) {
2182            MBEDTLS_SSL_DEBUG_MSG(1, ("bad server key exchange message"));
2183            mbedtls_ssl_send_alert_message(
2184                ssl,
2185                MBEDTLS_SSL_ALERT_LEVEL_FATAL,
2186                MBEDTLS_SSL_ALERT_MSG_DECODE_ERROR);
2187            return MBEDTLS_ERR_SSL_DECODE_ERROR;
2188        }
2189    } /* FALLTHROUGH */
2190#endif /* MBEDTLS_KEY_EXCHANGE_SOME_PSK_ENABLED */
2191
2192#if defined(MBEDTLS_KEY_EXCHANGE_PSK_ENABLED) ||                       \
2193    defined(MBEDTLS_KEY_EXCHANGE_RSA_PSK_ENABLED)
2194    if (ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_PSK ||
2195        ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_RSA_PSK) {
2196        ; /* nothing more to do */
2197    } else
2198#endif /* MBEDTLS_KEY_EXCHANGE_PSK_ENABLED ||
2199          MBEDTLS_KEY_EXCHANGE_RSA_PSK_ENABLED */
2200#if defined(MBEDTLS_KEY_EXCHANGE_DHE_RSA_ENABLED) ||                       \
2201    defined(MBEDTLS_KEY_EXCHANGE_DHE_PSK_ENABLED)
2202    if (ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_DHE_RSA ||
2203        ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_DHE_PSK) {
2204        if (ssl_parse_server_dh_params(ssl, &p, end) != 0) {
2205            MBEDTLS_SSL_DEBUG_MSG(1, ("bad server key exchange message"));
2206            mbedtls_ssl_send_alert_message(
2207                ssl,
2208                MBEDTLS_SSL_ALERT_LEVEL_FATAL,
2209                MBEDTLS_SSL_ALERT_MSG_ILLEGAL_PARAMETER);
2210            return MBEDTLS_ERR_SSL_ILLEGAL_PARAMETER;
2211        }
2212    } else
2213#endif /* MBEDTLS_KEY_EXCHANGE_DHE_RSA_ENABLED ||
2214          MBEDTLS_KEY_EXCHANGE_DHE_PSK_ENABLED */
2215#if defined(MBEDTLS_KEY_EXCHANGE_ECDHE_RSA_ENABLED) ||     \
2216    defined(MBEDTLS_KEY_EXCHANGE_ECDHE_PSK_ENABLED) ||     \
2217    defined(MBEDTLS_KEY_EXCHANGE_ECDHE_ECDSA_ENABLED)
2218    if (ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_ECDHE_RSA ||
2219        ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_ECDHE_PSK ||
2220        ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_ECDHE_ECDSA) {
2221        if (ssl_parse_server_ecdh_params(ssl, &p, end) != 0) {
2222            MBEDTLS_SSL_DEBUG_MSG(1, ("bad server key exchange message"));
2223            mbedtls_ssl_send_alert_message(
2224                ssl,
2225                MBEDTLS_SSL_ALERT_LEVEL_FATAL,
2226                MBEDTLS_SSL_ALERT_MSG_ILLEGAL_PARAMETER);
2227            return MBEDTLS_ERR_SSL_ILLEGAL_PARAMETER;
2228        }
2229    } else
2230#endif /* MBEDTLS_KEY_EXCHANGE_ECDHE_RSA_ENABLED ||
2231          MBEDTLS_KEY_EXCHANGE_ECDHE_PSK_ENABLED ||
2232          MBEDTLS_KEY_EXCHANGE_ECDHE_ECDSA_ENABLED */
2233#if defined(MBEDTLS_KEY_EXCHANGE_ECJPAKE_ENABLED)
2234    if (ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_ECJPAKE) {
2235#if defined(MBEDTLS_USE_PSA_CRYPTO)
2236        /*
2237         * The first 3 bytes are:
2238         * [0] MBEDTLS_ECP_TLS_NAMED_CURVE
2239         * [1, 2] elliptic curve's TLS ID
2240         *
2241         * However since we only support secp256r1 for now, we check only
2242         * that TLS ID here
2243         */
2244        uint16_t read_tls_id = MBEDTLS_GET_UINT16_BE(p, 1);
2245        uint16_t exp_tls_id = mbedtls_ssl_get_tls_id_from_ecp_group_id(
2246            MBEDTLS_ECP_DP_SECP256R1);
2247
2248        if (exp_tls_id == 0) {
2249            return MBEDTLS_ERR_SSL_FEATURE_UNAVAILABLE;
2250        }
2251
2252        if ((*p != MBEDTLS_ECP_TLS_NAMED_CURVE) ||
2253            (read_tls_id != exp_tls_id)) {
2254            return MBEDTLS_ERR_SSL_ILLEGAL_PARAMETER;
2255        }
2256
2257        p += 3;
2258
2259        if ((ret = mbedtls_psa_ecjpake_read_round(
2260                 &ssl->handshake->psa_pake_ctx, p, end - p,
2261                 MBEDTLS_ECJPAKE_ROUND_TWO)) != 0) {
2262            psa_destroy_key(ssl->handshake->psa_pake_password);
2263            psa_pake_abort(&ssl->handshake->psa_pake_ctx);
2264
2265            MBEDTLS_SSL_DEBUG_RET(1, "psa_pake_input round two", ret);
2266            mbedtls_ssl_send_alert_message(
2267                ssl,
2268                MBEDTLS_SSL_ALERT_LEVEL_FATAL,
2269                MBEDTLS_SSL_ALERT_MSG_HANDSHAKE_FAILURE);
2270            return MBEDTLS_ERR_SSL_HANDSHAKE_FAILURE;
2271        }
2272#else
2273        ret = mbedtls_ecjpake_read_round_two(&ssl->handshake->ecjpake_ctx,
2274                                             p, end - p);
2275        if (ret != 0) {
2276            MBEDTLS_SSL_DEBUG_RET(1, "mbedtls_ecjpake_read_round_two", ret);
2277            mbedtls_ssl_send_alert_message(
2278                ssl,
2279                MBEDTLS_SSL_ALERT_LEVEL_FATAL,
2280                MBEDTLS_SSL_ALERT_MSG_HANDSHAKE_FAILURE);
2281            return MBEDTLS_ERR_SSL_HANDSHAKE_FAILURE;
2282        }
2283#endif /* MBEDTLS_USE_PSA_CRYPTO */
2284    } else
2285#endif /* MBEDTLS_KEY_EXCHANGE_ECJPAKE_ENABLED */
2286    {
2287        MBEDTLS_SSL_DEBUG_MSG(1, ("should never happen"));
2288        return MBEDTLS_ERR_SSL_INTERNAL_ERROR;
2289    }
2290
2291#if defined(MBEDTLS_KEY_EXCHANGE_WITH_SERVER_SIGNATURE_ENABLED)
2292    if (mbedtls_ssl_ciphersuite_uses_server_signature(ciphersuite_info)) {
2293        size_t sig_len, hashlen;
2294        unsigned char hash[MBEDTLS_MD_MAX_SIZE];
2295
2296        mbedtls_md_type_t md_alg = MBEDTLS_MD_NONE;
2297        mbedtls_pk_type_t pk_alg = MBEDTLS_PK_NONE;
2298        unsigned char *params = ssl->in_msg + mbedtls_ssl_hs_hdr_len(ssl);
2299        size_t params_len = (size_t) (p - params);
2300        void *rs_ctx = NULL;
2301        uint16_t sig_alg;
2302
2303        mbedtls_pk_context *peer_pk;
2304
2305#if !defined(MBEDTLS_SSL_KEEP_PEER_CERTIFICATE)
2306        peer_pk = &ssl->handshake->peer_pubkey;
2307#else /* !MBEDTLS_SSL_KEEP_PEER_CERTIFICATE */
2308        if (ssl->session_negotiate->peer_cert == NULL) {
2309            /* Should never happen */
2310            MBEDTLS_SSL_DEBUG_MSG(1, ("should never happen"));
2311            return MBEDTLS_ERR_SSL_INTERNAL_ERROR;
2312        }
2313        peer_pk = &ssl->session_negotiate->peer_cert->pk;
2314#endif /* MBEDTLS_SSL_KEEP_PEER_CERTIFICATE */
2315
2316        /*
2317         * Handle the digitally-signed structure
2318         */
2319        MBEDTLS_SSL_CHK_BUF_READ_PTR(p, end, 2);
2320        sig_alg = MBEDTLS_GET_UINT16_BE(p, 0);
2321        if (mbedtls_ssl_get_pk_type_and_md_alg_from_sig_alg(
2322                sig_alg, &pk_alg, &md_alg) != 0 &&
2323            !mbedtls_ssl_sig_alg_is_offered(ssl, sig_alg) &&
2324            !mbedtls_ssl_sig_alg_is_supported(ssl, sig_alg)) {
2325            MBEDTLS_SSL_DEBUG_MSG(1,
2326                                  ("bad server key exchange message"));
2327            mbedtls_ssl_send_alert_message(
2328                ssl,
2329                MBEDTLS_SSL_ALERT_LEVEL_FATAL,
2330                MBEDTLS_SSL_ALERT_MSG_ILLEGAL_PARAMETER);
2331            return MBEDTLS_ERR_SSL_ILLEGAL_PARAMETER;
2332        }
2333        p += 2;
2334
2335        if (!mbedtls_pk_can_do(peer_pk, pk_alg)) {
2336            MBEDTLS_SSL_DEBUG_MSG(1,
2337                                  ("bad server key exchange message"));
2338            mbedtls_ssl_send_alert_message(
2339                ssl,
2340                MBEDTLS_SSL_ALERT_LEVEL_FATAL,
2341                MBEDTLS_SSL_ALERT_MSG_ILLEGAL_PARAMETER);
2342            return MBEDTLS_ERR_SSL_ILLEGAL_PARAMETER;
2343        }
2344
2345        /*
2346         * Read signature
2347         */
2348
2349        if (p > end - 2) {
2350            MBEDTLS_SSL_DEBUG_MSG(1, ("bad server key exchange message"));
2351            mbedtls_ssl_send_alert_message(
2352                ssl,
2353                MBEDTLS_SSL_ALERT_LEVEL_FATAL,
2354                MBEDTLS_SSL_ALERT_MSG_DECODE_ERROR);
2355            return MBEDTLS_ERR_SSL_DECODE_ERROR;
2356        }
2357        sig_len = MBEDTLS_GET_UINT16_BE(p, 0);
2358        p += 2;
2359
2360        if (p != end - sig_len) {
2361            MBEDTLS_SSL_DEBUG_MSG(1, ("bad server key exchange message"));
2362            mbedtls_ssl_send_alert_message(
2363                ssl,
2364                MBEDTLS_SSL_ALERT_LEVEL_FATAL,
2365                MBEDTLS_SSL_ALERT_MSG_DECODE_ERROR);
2366            return MBEDTLS_ERR_SSL_DECODE_ERROR;
2367        }
2368
2369        MBEDTLS_SSL_DEBUG_BUF(3, "signature", p, sig_len);
2370
2371        /*
2372         * Compute the hash that has been signed
2373         */
2374        if (md_alg != MBEDTLS_MD_NONE) {
2375            ret = mbedtls_ssl_get_key_exchange_md_tls1_2(ssl, hash, &hashlen,
2376                                                         params, params_len,
2377                                                         md_alg);
2378            if (ret != 0) {
2379                return ret;
2380            }
2381        } else {
2382            MBEDTLS_SSL_DEBUG_MSG(1, ("should never happen"));
2383            return MBEDTLS_ERR_SSL_INTERNAL_ERROR;
2384        }
2385
2386        MBEDTLS_SSL_DEBUG_BUF(3, "parameters hash", hash, hashlen);
2387
2388        /*
2389         * Verify signature
2390         */
2391        if (!mbedtls_pk_can_do(peer_pk, pk_alg)) {
2392            MBEDTLS_SSL_DEBUG_MSG(1, ("bad server key exchange message"));
2393            mbedtls_ssl_send_alert_message(
2394                ssl,
2395                MBEDTLS_SSL_ALERT_LEVEL_FATAL,
2396                MBEDTLS_SSL_ALERT_MSG_HANDSHAKE_FAILURE);
2397            return MBEDTLS_ERR_SSL_PK_TYPE_MISMATCH;
2398        }
2399
2400#if defined(MBEDTLS_SSL_ECP_RESTARTABLE_ENABLED)
2401        if (ssl->handshake->ecrs_enabled) {
2402            rs_ctx = &ssl->handshake->ecrs_ctx.pk;
2403        }
2404#endif
2405
2406#if defined(MBEDTLS_X509_RSASSA_PSS_SUPPORT)
2407        if (pk_alg == MBEDTLS_PK_RSASSA_PSS) {
2408            mbedtls_pk_rsassa_pss_options rsassa_pss_options;
2409            rsassa_pss_options.mgf1_hash_id = md_alg;
2410            rsassa_pss_options.expected_salt_len =
2411                mbedtls_md_get_size_from_type(md_alg);
2412            if (rsassa_pss_options.expected_salt_len == 0) {
2413                return MBEDTLS_ERR_SSL_INTERNAL_ERROR;
2414            }
2415
2416            ret = mbedtls_pk_verify_ext(pk_alg, &rsassa_pss_options,
2417                                        peer_pk,
2418                                        md_alg, hash, hashlen,
2419                                        p, sig_len);
2420        } else
2421#endif /* MBEDTLS_X509_RSASSA_PSS_SUPPORT */
2422        ret = mbedtls_pk_verify_restartable(peer_pk,
2423                                            md_alg, hash, hashlen, p, sig_len, rs_ctx);
2424
2425        if (ret != 0) {
2426            int send_alert_msg = 1;
2427#if defined(MBEDTLS_SSL_ECP_RESTARTABLE_ENABLED)
2428            send_alert_msg = (ret != MBEDTLS_ERR_ECP_IN_PROGRESS);
2429#endif
2430            if (send_alert_msg) {
2431                mbedtls_ssl_send_alert_message(
2432                    ssl,
2433                    MBEDTLS_SSL_ALERT_LEVEL_FATAL,
2434                    MBEDTLS_SSL_ALERT_MSG_DECRYPT_ERROR);
2435            }
2436            MBEDTLS_SSL_DEBUG_RET(1, "mbedtls_pk_verify", ret);
2437#if defined(MBEDTLS_SSL_ECP_RESTARTABLE_ENABLED)
2438            if (ret == MBEDTLS_ERR_ECP_IN_PROGRESS) {
2439                ret = MBEDTLS_ERR_SSL_CRYPTO_IN_PROGRESS;
2440            }
2441#endif
2442            return ret;
2443        }
2444
2445#if !defined(MBEDTLS_SSL_KEEP_PEER_CERTIFICATE)
2446        /* We don't need the peer's public key anymore. Free it,
2447         * so that more RAM is available for upcoming expensive
2448         * operations like ECDHE. */
2449        mbedtls_pk_free(peer_pk);
2450#endif /* !MBEDTLS_SSL_KEEP_PEER_CERTIFICATE */
2451    }
2452#endif /* MBEDTLS_KEY_EXCHANGE_WITH_SERVER_SIGNATURE_ENABLED */
2453
2454exit:
2455    ssl->state++;
2456
2457    MBEDTLS_SSL_DEBUG_MSG(2, ("<= parse server key exchange"));
2458
2459    return 0;
2460}
2461
2462#if !defined(MBEDTLS_KEY_EXCHANGE_CERT_REQ_ALLOWED_ENABLED)
2463MBEDTLS_CHECK_RETURN_CRITICAL
2464static int ssl_parse_certificate_request(mbedtls_ssl_context *ssl)
2465{
2466    const mbedtls_ssl_ciphersuite_t *ciphersuite_info =
2467        ssl->handshake->ciphersuite_info;
2468
2469    MBEDTLS_SSL_DEBUG_MSG(2, ("=> parse certificate request"));
2470
2471    if (!mbedtls_ssl_ciphersuite_cert_req_allowed(ciphersuite_info)) {
2472        MBEDTLS_SSL_DEBUG_MSG(2, ("<= skip parse certificate request"));
2473        ssl->state++;
2474        return 0;
2475    }
2476
2477    MBEDTLS_SSL_DEBUG_MSG(1, ("should never happen"));
2478    return MBEDTLS_ERR_SSL_INTERNAL_ERROR;
2479}
2480#else /* MBEDTLS_KEY_EXCHANGE_CERT_REQ_ALLOWED_ENABLED */
2481MBEDTLS_CHECK_RETURN_CRITICAL
2482static int ssl_parse_certificate_request(mbedtls_ssl_context *ssl)
2483{
2484    int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
2485    unsigned char *buf;
2486    size_t n = 0;
2487    size_t cert_type_len = 0, dn_len = 0;
2488    const mbedtls_ssl_ciphersuite_t *ciphersuite_info =
2489        ssl->handshake->ciphersuite_info;
2490    size_t sig_alg_len;
2491#if defined(MBEDTLS_DEBUG_C)
2492    unsigned char *sig_alg;
2493    unsigned char *dn;
2494#endif
2495
2496    MBEDTLS_SSL_DEBUG_MSG(2, ("=> parse certificate request"));
2497
2498    if (!mbedtls_ssl_ciphersuite_cert_req_allowed(ciphersuite_info)) {
2499        MBEDTLS_SSL_DEBUG_MSG(2, ("<= skip parse certificate request"));
2500        ssl->state++;
2501        return 0;
2502    }
2503
2504    if ((ret = mbedtls_ssl_read_record(ssl, 1)) != 0) {
2505        MBEDTLS_SSL_DEBUG_RET(1, "mbedtls_ssl_read_record", ret);
2506        return ret;
2507    }
2508
2509    if (ssl->in_msgtype != MBEDTLS_SSL_MSG_HANDSHAKE) {
2510        MBEDTLS_SSL_DEBUG_MSG(1, ("bad certificate request message"));
2511        mbedtls_ssl_send_alert_message(
2512            ssl,
2513            MBEDTLS_SSL_ALERT_LEVEL_FATAL,
2514            MBEDTLS_SSL_ALERT_MSG_UNEXPECTED_MESSAGE);
2515        return MBEDTLS_ERR_SSL_UNEXPECTED_MESSAGE;
2516    }
2517
2518    ssl->state++;
2519    ssl->handshake->client_auth =
2520        (ssl->in_msg[0] == MBEDTLS_SSL_HS_CERTIFICATE_REQUEST);
2521
2522    MBEDTLS_SSL_DEBUG_MSG(3, ("got %s certificate request",
2523                              ssl->handshake->client_auth ? "a" : "no"));
2524
2525    if (ssl->handshake->client_auth == 0) {
2526        /* Current message is probably the ServerHelloDone */
2527        ssl->keep_current_message = 1;
2528        goto exit;
2529    }
2530
2531    /*
2532     *  struct {
2533     *      ClientCertificateType certificate_types<1..2^8-1>;
2534     *      SignatureAndHashAlgorithm
2535     *        supported_signature_algorithms<2^16-1>; -- TLS 1.2 only
2536     *      DistinguishedName certificate_authorities<0..2^16-1>;
2537     *  } CertificateRequest;
2538     *
2539     *  Since we only support a single certificate on clients, let's just
2540     *  ignore all the information that's supposed to help us pick a
2541     *  certificate.
2542     *
2543     *  We could check that our certificate matches the request, and bail out
2544     *  if it doesn't, but it's simpler to just send the certificate anyway,
2545     *  and give the server the opportunity to decide if it should terminate
2546     *  the connection when it doesn't like our certificate.
2547     *
2548     *  Same goes for the hash in TLS 1.2's signature_algorithms: at this
2549     *  point we only have one hash available (see comments in
2550     *  write_certificate_verify), so let's just use what we have.
2551     *
2552     *  However, we still minimally parse the message to check it is at least
2553     *  superficially sane.
2554     */
2555    buf = ssl->in_msg;
2556
2557    /* certificate_types */
2558    if (ssl->in_hslen <= mbedtls_ssl_hs_hdr_len(ssl)) {
2559        MBEDTLS_SSL_DEBUG_MSG(1, ("bad certificate request message"));
2560        mbedtls_ssl_send_alert_message(ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,
2561                                       MBEDTLS_SSL_ALERT_MSG_DECODE_ERROR);
2562        return MBEDTLS_ERR_SSL_DECODE_ERROR;
2563    }
2564    cert_type_len = buf[mbedtls_ssl_hs_hdr_len(ssl)];
2565    n = cert_type_len;
2566
2567    /*
2568     * In the subsequent code there are two paths that read from buf:
2569     *     * the length of the signature algorithms field (if minor version of
2570     *       SSL is 3),
2571     *     * distinguished name length otherwise.
2572     * Both reach at most the index:
2573     *    ...hdr_len + 2 + n,
2574     * therefore the buffer length at this point must be greater than that
2575     * regardless of the actual code path.
2576     */
2577    if (ssl->in_hslen <= mbedtls_ssl_hs_hdr_len(ssl) + 2 + n) {
2578        MBEDTLS_SSL_DEBUG_MSG(1, ("bad certificate request message"));
2579        mbedtls_ssl_send_alert_message(ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,
2580                                       MBEDTLS_SSL_ALERT_MSG_DECODE_ERROR);
2581        return MBEDTLS_ERR_SSL_DECODE_ERROR;
2582    }
2583
2584    /* supported_signature_algorithms */
2585    sig_alg_len = MBEDTLS_GET_UINT16_BE(buf, mbedtls_ssl_hs_hdr_len(ssl) + 1 + n);
2586
2587    /*
2588     * The furthest access in buf is in the loop few lines below:
2589     *     sig_alg[i + 1],
2590     * where:
2591     *     sig_alg = buf + ...hdr_len + 3 + n,
2592     *     max(i) = sig_alg_len - 1.
2593     * Therefore the furthest access is:
2594     *     buf[...hdr_len + 3 + n + sig_alg_len - 1 + 1],
2595     * which reduces to:
2596     *     buf[...hdr_len + 3 + n + sig_alg_len],
2597     * which is one less than we need the buf to be.
2598     */
2599    if (ssl->in_hslen <= mbedtls_ssl_hs_hdr_len(ssl) + 3 + n + sig_alg_len) {
2600        MBEDTLS_SSL_DEBUG_MSG(1, ("bad certificate request message"));
2601        mbedtls_ssl_send_alert_message(
2602            ssl,
2603            MBEDTLS_SSL_ALERT_LEVEL_FATAL,
2604            MBEDTLS_SSL_ALERT_MSG_DECODE_ERROR);
2605        return MBEDTLS_ERR_SSL_DECODE_ERROR;
2606    }
2607
2608#if defined(MBEDTLS_DEBUG_C)
2609    sig_alg = buf + mbedtls_ssl_hs_hdr_len(ssl) + 3 + n;
2610    for (size_t i = 0; i < sig_alg_len; i += 2) {
2611        MBEDTLS_SSL_DEBUG_MSG(3,
2612                              ("Supported Signature Algorithm found: %02x %02x",
2613                               sig_alg[i], sig_alg[i + 1]));
2614    }
2615#endif
2616
2617    n += 2 + sig_alg_len;
2618
2619    /* certificate_authorities */
2620    dn_len = MBEDTLS_GET_UINT16_BE(buf, mbedtls_ssl_hs_hdr_len(ssl) + 1 + n);
2621
2622    n += dn_len;
2623    if (ssl->in_hslen != mbedtls_ssl_hs_hdr_len(ssl) + 3 + n) {
2624        MBEDTLS_SSL_DEBUG_MSG(1, ("bad certificate request message"));
2625        mbedtls_ssl_send_alert_message(ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,
2626                                       MBEDTLS_SSL_ALERT_MSG_DECODE_ERROR);
2627        return MBEDTLS_ERR_SSL_DECODE_ERROR;
2628    }
2629
2630#if defined(MBEDTLS_DEBUG_C)
2631    dn = buf + mbedtls_ssl_hs_hdr_len(ssl) + 3 + n - dn_len;
2632    for (size_t i = 0, dni_len = 0; i < dn_len; i += 2 + dni_len) {
2633        unsigned char *p = dn + i + 2;
2634        mbedtls_x509_name name;
2635        size_t asn1_len;
2636        char s[MBEDTLS_X509_MAX_DN_NAME_SIZE];
2637        memset(&name, 0, sizeof(name));
2638        dni_len = MBEDTLS_GET_UINT16_BE(dn + i, 0);
2639        if (dni_len > dn_len - i - 2 ||
2640            mbedtls_asn1_get_tag(&p, p + dni_len, &asn1_len,
2641                                 MBEDTLS_ASN1_CONSTRUCTED | MBEDTLS_ASN1_SEQUENCE) != 0 ||
2642            mbedtls_x509_get_name(&p, p + asn1_len, &name) != 0) {
2643            MBEDTLS_SSL_DEBUG_MSG(1, ("bad certificate request message"));
2644            mbedtls_ssl_send_alert_message(
2645                ssl,
2646                MBEDTLS_SSL_ALERT_LEVEL_FATAL,
2647                MBEDTLS_SSL_ALERT_MSG_DECODE_ERROR);
2648            return MBEDTLS_ERR_SSL_DECODE_ERROR;
2649        }
2650        MBEDTLS_SSL_DEBUG_MSG(3,
2651                              ("DN hint: %.*s",
2652                               mbedtls_x509_dn_gets(s, sizeof(s), &name), s));
2653        mbedtls_asn1_free_named_data_list_shallow(name.next);
2654    }
2655#endif
2656
2657exit:
2658    MBEDTLS_SSL_DEBUG_MSG(2, ("<= parse certificate request"));
2659
2660    return 0;
2661}
2662#endif /* MBEDTLS_KEY_EXCHANGE_CERT_REQ_ALLOWED_ENABLED */
2663
2664MBEDTLS_CHECK_RETURN_CRITICAL
2665static int ssl_parse_server_hello_done(mbedtls_ssl_context *ssl)
2666{
2667    int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
2668
2669    MBEDTLS_SSL_DEBUG_MSG(2, ("=> parse server hello done"));
2670
2671    if ((ret = mbedtls_ssl_read_record(ssl, 1)) != 0) {
2672        MBEDTLS_SSL_DEBUG_RET(1, "mbedtls_ssl_read_record", ret);
2673        return ret;
2674    }
2675
2676    if (ssl->in_msgtype != MBEDTLS_SSL_MSG_HANDSHAKE) {
2677        MBEDTLS_SSL_DEBUG_MSG(1, ("bad server hello done message"));
2678        return MBEDTLS_ERR_SSL_UNEXPECTED_MESSAGE;
2679    }
2680
2681    if (ssl->in_hslen  != mbedtls_ssl_hs_hdr_len(ssl) ||
2682        ssl->in_msg[0] != MBEDTLS_SSL_HS_SERVER_HELLO_DONE) {
2683        MBEDTLS_SSL_DEBUG_MSG(1, ("bad server hello done message"));
2684        mbedtls_ssl_send_alert_message(ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,
2685                                       MBEDTLS_SSL_ALERT_MSG_DECODE_ERROR);
2686        return MBEDTLS_ERR_SSL_DECODE_ERROR;
2687    }
2688
2689    ssl->state++;
2690
2691#if defined(MBEDTLS_SSL_PROTO_DTLS)
2692    if (ssl->conf->transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM) {
2693        mbedtls_ssl_recv_flight_completed(ssl);
2694    }
2695#endif
2696
2697    MBEDTLS_SSL_DEBUG_MSG(2, ("<= parse server hello done"));
2698
2699    return 0;
2700}
2701
2702MBEDTLS_CHECK_RETURN_CRITICAL
2703static int ssl_write_client_key_exchange(mbedtls_ssl_context *ssl)
2704{
2705    int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
2706
2707    size_t header_len;
2708    size_t content_len;
2709    const mbedtls_ssl_ciphersuite_t *ciphersuite_info =
2710        ssl->handshake->ciphersuite_info;
2711
2712    MBEDTLS_SSL_DEBUG_MSG(2, ("=> write client key exchange"));
2713
2714#if defined(MBEDTLS_KEY_EXCHANGE_DHE_RSA_ENABLED)
2715    if (ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_DHE_RSA) {
2716        /*
2717         * DHM key exchange -- send G^X mod P
2718         */
2719        content_len = mbedtls_dhm_get_len(&ssl->handshake->dhm_ctx);
2720
2721        MBEDTLS_PUT_UINT16_BE(content_len, ssl->out_msg, 4);
2722        header_len = 6;
2723
2724        ret = mbedtls_dhm_make_public(&ssl->handshake->dhm_ctx,
2725                                      (int) mbedtls_dhm_get_len(&ssl->handshake->dhm_ctx),
2726                                      &ssl->out_msg[header_len], content_len,
2727                                      ssl->conf->f_rng, ssl->conf->p_rng);
2728        if (ret != 0) {
2729            MBEDTLS_SSL_DEBUG_RET(1, "mbedtls_dhm_make_public", ret);
2730            return ret;
2731        }
2732
2733        MBEDTLS_SSL_DEBUG_MPI(3, "DHM: X ", &ssl->handshake->dhm_ctx.X);
2734        MBEDTLS_SSL_DEBUG_MPI(3, "DHM: GX", &ssl->handshake->dhm_ctx.GX);
2735
2736        if ((ret = mbedtls_dhm_calc_secret(&ssl->handshake->dhm_ctx,
2737                                           ssl->handshake->premaster,
2738                                           MBEDTLS_PREMASTER_SIZE,
2739                                           &ssl->handshake->pmslen,
2740                                           ssl->conf->f_rng, ssl->conf->p_rng)) != 0) {
2741            MBEDTLS_SSL_DEBUG_RET(1, "mbedtls_dhm_calc_secret", ret);
2742            return ret;
2743        }
2744
2745        MBEDTLS_SSL_DEBUG_MPI(3, "DHM: K ", &ssl->handshake->dhm_ctx.K);
2746    } else
2747#endif /* MBEDTLS_KEY_EXCHANGE_DHE_RSA_ENABLED */
2748#if defined(MBEDTLS_KEY_EXCHANGE_ECDHE_RSA_ENABLED) ||                     \
2749    defined(MBEDTLS_KEY_EXCHANGE_ECDHE_ECDSA_ENABLED) ||                   \
2750    defined(MBEDTLS_KEY_EXCHANGE_ECDH_RSA_ENABLED) ||                      \
2751    defined(MBEDTLS_KEY_EXCHANGE_ECDH_ECDSA_ENABLED)
2752    if (ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_ECDHE_RSA ||
2753        ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_ECDHE_ECDSA ||
2754        ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_ECDH_RSA ||
2755        ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_ECDH_ECDSA) {
2756#if defined(MBEDTLS_USE_PSA_CRYPTO)
2757        psa_status_t status = PSA_ERROR_CORRUPTION_DETECTED;
2758        psa_status_t destruction_status = PSA_ERROR_CORRUPTION_DETECTED;
2759        psa_key_attributes_t key_attributes;
2760
2761        mbedtls_ssl_handshake_params *handshake = ssl->handshake;
2762
2763        header_len = 4;
2764
2765        MBEDTLS_SSL_DEBUG_MSG(1, ("Perform PSA-based ECDH computation."));
2766
2767        /*
2768         * Generate EC private key for ECDHE exchange.
2769         */
2770
2771        /* The master secret is obtained from the shared ECDH secret by
2772         * applying the TLS 1.2 PRF with a specific salt and label. While
2773         * the PSA Crypto API encourages combining key agreement schemes
2774         * such as ECDH with fixed KDFs such as TLS 1.2 PRF, it does not
2775         * yet support the provisioning of salt + label to the KDF.
2776         * For the time being, we therefore need to split the computation
2777         * of the ECDH secret and the application of the TLS 1.2 PRF. */
2778        key_attributes = psa_key_attributes_init();
2779        psa_set_key_usage_flags(&key_attributes, PSA_KEY_USAGE_DERIVE);
2780        psa_set_key_algorithm(&key_attributes, PSA_ALG_ECDH);
2781        psa_set_key_type(&key_attributes, handshake->xxdh_psa_type);
2782        psa_set_key_bits(&key_attributes, handshake->xxdh_psa_bits);
2783
2784        /* Generate ECDH private key. */
2785        status = psa_generate_key(&key_attributes,
2786                                  &handshake->xxdh_psa_privkey);
2787        if (status != PSA_SUCCESS) {
2788            return MBEDTLS_ERR_SSL_HW_ACCEL_FAILED;
2789        }
2790
2791        /* Export the public part of the ECDH private key from PSA.
2792         * The export format is an ECPoint structure as expected by TLS,
2793         * but we just need to add a length byte before that. */
2794        unsigned char *own_pubkey = ssl->out_msg + header_len + 1;
2795        unsigned char *end = ssl->out_msg + MBEDTLS_SSL_OUT_CONTENT_LEN;
2796        size_t own_pubkey_max_len = (size_t) (end - own_pubkey);
2797        size_t own_pubkey_len;
2798
2799        status = psa_export_public_key(handshake->xxdh_psa_privkey,
2800                                       own_pubkey, own_pubkey_max_len,
2801                                       &own_pubkey_len);
2802        if (status != PSA_SUCCESS) {
2803            psa_destroy_key(handshake->xxdh_psa_privkey);
2804            handshake->xxdh_psa_privkey = MBEDTLS_SVC_KEY_ID_INIT;
2805            return MBEDTLS_ERR_SSL_HW_ACCEL_FAILED;
2806        }
2807
2808        ssl->out_msg[header_len] = (unsigned char) own_pubkey_len;
2809        content_len = own_pubkey_len + 1;
2810
2811        /* The ECDH secret is the premaster secret used for key derivation. */
2812
2813        /* Compute ECDH shared secret. */
2814        status = psa_raw_key_agreement(PSA_ALG_ECDH,
2815                                       handshake->xxdh_psa_privkey,
2816                                       handshake->xxdh_psa_peerkey,
2817                                       handshake->xxdh_psa_peerkey_len,
2818                                       ssl->handshake->premaster,
2819                                       sizeof(ssl->handshake->premaster),
2820                                       &ssl->handshake->pmslen);
2821
2822        destruction_status = psa_destroy_key(handshake->xxdh_psa_privkey);
2823        handshake->xxdh_psa_privkey = MBEDTLS_SVC_KEY_ID_INIT;
2824
2825        if (status != PSA_SUCCESS || destruction_status != PSA_SUCCESS) {
2826            return MBEDTLS_ERR_SSL_HW_ACCEL_FAILED;
2827        }
2828#else
2829        /*
2830         * ECDH key exchange -- send client public value
2831         */
2832        header_len = 4;
2833
2834#if defined(MBEDTLS_SSL_ECP_RESTARTABLE_ENABLED)
2835        if (ssl->handshake->ecrs_enabled) {
2836            if (ssl->handshake->ecrs_state == ssl_ecrs_cke_ecdh_calc_secret) {
2837                goto ecdh_calc_secret;
2838            }
2839
2840            mbedtls_ecdh_enable_restart(&ssl->handshake->ecdh_ctx);
2841        }
2842#endif
2843
2844        ret = mbedtls_ecdh_make_public(&ssl->handshake->ecdh_ctx,
2845                                       &content_len,
2846                                       &ssl->out_msg[header_len], 1000,
2847                                       ssl->conf->f_rng, ssl->conf->p_rng);
2848        if (ret != 0) {
2849            MBEDTLS_SSL_DEBUG_RET(1, "mbedtls_ecdh_make_public", ret);
2850#if defined(MBEDTLS_SSL_ECP_RESTARTABLE_ENABLED)
2851            if (ret == MBEDTLS_ERR_ECP_IN_PROGRESS) {
2852                ret = MBEDTLS_ERR_SSL_CRYPTO_IN_PROGRESS;
2853            }
2854#endif
2855            return ret;
2856        }
2857
2858        MBEDTLS_SSL_DEBUG_ECDH(3, &ssl->handshake->ecdh_ctx,
2859                               MBEDTLS_DEBUG_ECDH_Q);
2860
2861#if defined(MBEDTLS_SSL_ECP_RESTARTABLE_ENABLED)
2862        if (ssl->handshake->ecrs_enabled) {
2863            ssl->handshake->ecrs_n = content_len;
2864            ssl->handshake->ecrs_state = ssl_ecrs_cke_ecdh_calc_secret;
2865        }
2866
2867ecdh_calc_secret:
2868        if (ssl->handshake->ecrs_enabled) {
2869            content_len = ssl->handshake->ecrs_n;
2870        }
2871#endif
2872        if ((ret = mbedtls_ecdh_calc_secret(&ssl->handshake->ecdh_ctx,
2873                                            &ssl->handshake->pmslen,
2874                                            ssl->handshake->premaster,
2875                                            MBEDTLS_MPI_MAX_SIZE,
2876                                            ssl->conf->f_rng, ssl->conf->p_rng)) != 0) {
2877            MBEDTLS_SSL_DEBUG_RET(1, "mbedtls_ecdh_calc_secret", ret);
2878#if defined(MBEDTLS_SSL_ECP_RESTARTABLE_ENABLED)
2879            if (ret == MBEDTLS_ERR_ECP_IN_PROGRESS) {
2880                ret = MBEDTLS_ERR_SSL_CRYPTO_IN_PROGRESS;
2881            }
2882#endif
2883            return ret;
2884        }
2885
2886        MBEDTLS_SSL_DEBUG_ECDH(3, &ssl->handshake->ecdh_ctx,
2887                               MBEDTLS_DEBUG_ECDH_Z);
2888#endif /* MBEDTLS_USE_PSA_CRYPTO */
2889    } else
2890#endif /* MBEDTLS_KEY_EXCHANGE_ECDHE_RSA_ENABLED ||
2891          MBEDTLS_KEY_EXCHANGE_ECDHE_ECDSA_ENABLED ||
2892          MBEDTLS_KEY_EXCHANGE_ECDH_RSA_ENABLED ||
2893          MBEDTLS_KEY_EXCHANGE_ECDH_ECDSA_ENABLED */
2894#if defined(MBEDTLS_USE_PSA_CRYPTO) &&                           \
2895    defined(MBEDTLS_KEY_EXCHANGE_ECDHE_PSK_ENABLED)
2896    if (ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_ECDHE_PSK) {
2897        psa_status_t status = PSA_ERROR_CORRUPTION_DETECTED;
2898        psa_status_t destruction_status = PSA_ERROR_CORRUPTION_DETECTED;
2899        psa_key_attributes_t key_attributes;
2900
2901        mbedtls_ssl_handshake_params *handshake = ssl->handshake;
2902
2903        /*
2904         * opaque psk_identity<0..2^16-1>;
2905         */
2906        if (mbedtls_ssl_conf_has_static_psk(ssl->conf) == 0) {
2907            /* We don't offer PSK suites if we don't have a PSK,
2908             * and we check that the server's choice is among the
2909             * ciphersuites we offered, so this should never happen. */
2910            return MBEDTLS_ERR_SSL_INTERNAL_ERROR;
2911        }
2912
2913        /* uint16 to store content length */
2914        const size_t content_len_size = 2;
2915
2916        header_len = 4;
2917
2918        if (header_len + content_len_size + ssl->conf->psk_identity_len
2919            > MBEDTLS_SSL_OUT_CONTENT_LEN) {
2920            MBEDTLS_SSL_DEBUG_MSG(1,
2921                                  ("psk identity too long or SSL buffer too short"));
2922            return MBEDTLS_ERR_SSL_BUFFER_TOO_SMALL;
2923        }
2924
2925        unsigned char *p = ssl->out_msg + header_len;
2926
2927        *p++ = MBEDTLS_BYTE_1(ssl->conf->psk_identity_len);
2928        *p++ = MBEDTLS_BYTE_0(ssl->conf->psk_identity_len);
2929        header_len += content_len_size;
2930
2931        memcpy(p, ssl->conf->psk_identity,
2932               ssl->conf->psk_identity_len);
2933        p += ssl->conf->psk_identity_len;
2934
2935        header_len += ssl->conf->psk_identity_len;
2936
2937        MBEDTLS_SSL_DEBUG_MSG(1, ("Perform PSA-based ECDH computation."));
2938
2939        /*
2940         * Generate EC private key for ECDHE exchange.
2941         */
2942
2943        /* The master secret is obtained from the shared ECDH secret by
2944         * applying the TLS 1.2 PRF with a specific salt and label. While
2945         * the PSA Crypto API encourages combining key agreement schemes
2946         * such as ECDH with fixed KDFs such as TLS 1.2 PRF, it does not
2947         * yet support the provisioning of salt + label to the KDF.
2948         * For the time being, we therefore need to split the computation
2949         * of the ECDH secret and the application of the TLS 1.2 PRF. */
2950        key_attributes = psa_key_attributes_init();
2951        psa_set_key_usage_flags(&key_attributes, PSA_KEY_USAGE_DERIVE);
2952        psa_set_key_algorithm(&key_attributes, PSA_ALG_ECDH);
2953        psa_set_key_type(&key_attributes, handshake->xxdh_psa_type);
2954        psa_set_key_bits(&key_attributes, handshake->xxdh_psa_bits);
2955
2956        /* Generate ECDH private key. */
2957        status = psa_generate_key(&key_attributes,
2958                                  &handshake->xxdh_psa_privkey);
2959        if (status != PSA_SUCCESS) {
2960            return PSA_TO_MBEDTLS_ERR(status);
2961        }
2962
2963        /* Export the public part of the ECDH private key from PSA.
2964         * The export format is an ECPoint structure as expected by TLS,
2965         * but we just need to add a length byte before that. */
2966        unsigned char *own_pubkey = p + 1;
2967        unsigned char *end = ssl->out_msg + MBEDTLS_SSL_OUT_CONTENT_LEN;
2968        size_t own_pubkey_max_len = (size_t) (end - own_pubkey);
2969        size_t own_pubkey_len = 0;
2970
2971        status = psa_export_public_key(handshake->xxdh_psa_privkey,
2972                                       own_pubkey, own_pubkey_max_len,
2973                                       &own_pubkey_len);
2974        if (status != PSA_SUCCESS) {
2975            psa_destroy_key(handshake->xxdh_psa_privkey);
2976            handshake->xxdh_psa_privkey = MBEDTLS_SVC_KEY_ID_INIT;
2977            return PSA_TO_MBEDTLS_ERR(status);
2978        }
2979
2980        *p = (unsigned char) own_pubkey_len;
2981        content_len = own_pubkey_len + 1;
2982
2983        /* As RFC 5489 section 2, the premaster secret is formed as follows:
2984         * - a uint16 containing the length (in octets) of the ECDH computation
2985         * - the octet string produced by the ECDH computation
2986         * - a uint16 containing the length (in octets) of the PSK
2987         * - the PSK itself
2988         */
2989        unsigned char *pms = ssl->handshake->premaster;
2990        const unsigned char * const pms_end = pms +
2991                                              sizeof(ssl->handshake->premaster);
2992        /* uint16 to store length (in octets) of the ECDH computation */
2993        const size_t zlen_size = 2;
2994        size_t zlen = 0;
2995
2996        /* Perform ECDH computation after the uint16 reserved for the length */
2997        status = psa_raw_key_agreement(PSA_ALG_ECDH,
2998                                       handshake->xxdh_psa_privkey,
2999                                       handshake->xxdh_psa_peerkey,
3000                                       handshake->xxdh_psa_peerkey_len,
3001                                       pms + zlen_size,
3002                                       pms_end - (pms + zlen_size),
3003                                       &zlen);
3004
3005        destruction_status = psa_destroy_key(handshake->xxdh_psa_privkey);
3006        handshake->xxdh_psa_privkey = MBEDTLS_SVC_KEY_ID_INIT;
3007
3008        if (status != PSA_SUCCESS) {
3009            return PSA_TO_MBEDTLS_ERR(status);
3010        } else if (destruction_status != PSA_SUCCESS) {
3011            return PSA_TO_MBEDTLS_ERR(destruction_status);
3012        }
3013
3014        /* Write the ECDH computation length before the ECDH computation */
3015        MBEDTLS_PUT_UINT16_BE(zlen, pms, 0);
3016        pms += zlen_size + zlen;
3017    } else
3018#endif /* MBEDTLS_USE_PSA_CRYPTO &&
3019          MBEDTLS_KEY_EXCHANGE_ECDHE_PSK_ENABLED */
3020#if defined(MBEDTLS_KEY_EXCHANGE_SOME_PSK_ENABLED)
3021    if (mbedtls_ssl_ciphersuite_uses_psk(ciphersuite_info)) {
3022        /*
3023         * opaque psk_identity<0..2^16-1>;
3024         */
3025        if (mbedtls_ssl_conf_has_static_psk(ssl->conf) == 0) {
3026            /* We don't offer PSK suites if we don't have a PSK,
3027             * and we check that the server's choice is among the
3028             * ciphersuites we offered, so this should never happen. */
3029            return MBEDTLS_ERR_SSL_INTERNAL_ERROR;
3030        }
3031
3032        header_len = 4;
3033        content_len = ssl->conf->psk_identity_len;
3034
3035        if (header_len + 2 + content_len > MBEDTLS_SSL_OUT_CONTENT_LEN) {
3036            MBEDTLS_SSL_DEBUG_MSG(1,
3037                                  ("psk identity too long or SSL buffer too short"));
3038            return MBEDTLS_ERR_SSL_BUFFER_TOO_SMALL;
3039        }
3040
3041        ssl->out_msg[header_len++] = MBEDTLS_BYTE_1(content_len);
3042        ssl->out_msg[header_len++] = MBEDTLS_BYTE_0(content_len);
3043
3044        memcpy(ssl->out_msg + header_len,
3045               ssl->conf->psk_identity,
3046               ssl->conf->psk_identity_len);
3047        header_len += ssl->conf->psk_identity_len;
3048
3049#if defined(MBEDTLS_KEY_EXCHANGE_PSK_ENABLED)
3050        if (ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_PSK) {
3051            content_len = 0;
3052        } else
3053#endif
3054#if defined(MBEDTLS_KEY_EXCHANGE_RSA_PSK_ENABLED)
3055        if (ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_RSA_PSK) {
3056            if ((ret = ssl_write_encrypted_pms(ssl, header_len,
3057                                               &content_len, 2)) != 0) {
3058                return ret;
3059            }
3060        } else
3061#endif
3062#if defined(MBEDTLS_KEY_EXCHANGE_DHE_PSK_ENABLED)
3063        if (ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_DHE_PSK) {
3064            /*
3065             * ClientDiffieHellmanPublic public (DHM send G^X mod P)
3066             */
3067            content_len = mbedtls_dhm_get_len(&ssl->handshake->dhm_ctx);
3068
3069            if (header_len + 2 + content_len >
3070                MBEDTLS_SSL_OUT_CONTENT_LEN) {
3071                MBEDTLS_SSL_DEBUG_MSG(1,
3072                                      ("psk identity or DHM size too long or SSL buffer too short"));
3073                return MBEDTLS_ERR_SSL_BUFFER_TOO_SMALL;
3074            }
3075
3076            ssl->out_msg[header_len++] = MBEDTLS_BYTE_1(content_len);
3077            ssl->out_msg[header_len++] = MBEDTLS_BYTE_0(content_len);
3078
3079            ret = mbedtls_dhm_make_public(&ssl->handshake->dhm_ctx,
3080                                          (int) mbedtls_dhm_get_len(&ssl->handshake->dhm_ctx),
3081                                          &ssl->out_msg[header_len], content_len,
3082                                          ssl->conf->f_rng, ssl->conf->p_rng);
3083            if (ret != 0) {
3084                MBEDTLS_SSL_DEBUG_RET(1, "mbedtls_dhm_make_public", ret);
3085                return ret;
3086            }
3087
3088#if defined(MBEDTLS_USE_PSA_CRYPTO)
3089            unsigned char *pms = ssl->handshake->premaster;
3090            unsigned char *pms_end = pms + sizeof(ssl->handshake->premaster);
3091            size_t pms_len;
3092
3093            /* Write length only when we know the actual value */
3094            if ((ret = mbedtls_dhm_calc_secret(&ssl->handshake->dhm_ctx,
3095                                               pms + 2, pms_end - (pms + 2), &pms_len,
3096                                               ssl->conf->f_rng, ssl->conf->p_rng)) != 0) {
3097                MBEDTLS_SSL_DEBUG_RET(1, "mbedtls_dhm_calc_secret", ret);
3098                return ret;
3099            }
3100            MBEDTLS_PUT_UINT16_BE(pms_len, pms, 0);
3101            pms += 2 + pms_len;
3102
3103            MBEDTLS_SSL_DEBUG_MPI(3, "DHM: K ", &ssl->handshake->dhm_ctx.K);
3104#endif
3105        } else
3106#endif /* MBEDTLS_KEY_EXCHANGE_DHE_PSK_ENABLED */
3107#if !defined(MBEDTLS_USE_PSA_CRYPTO) &&                             \
3108        defined(MBEDTLS_KEY_EXCHANGE_ECDHE_PSK_ENABLED)
3109        if (ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_ECDHE_PSK) {
3110            /*
3111             * ClientECDiffieHellmanPublic public;
3112             */
3113            ret = mbedtls_ecdh_make_public(&ssl->handshake->ecdh_ctx,
3114                                           &content_len,
3115                                           &ssl->out_msg[header_len],
3116                                           MBEDTLS_SSL_OUT_CONTENT_LEN - header_len,
3117                                           ssl->conf->f_rng, ssl->conf->p_rng);
3118            if (ret != 0) {
3119                MBEDTLS_SSL_DEBUG_RET(1, "mbedtls_ecdh_make_public", ret);
3120                return ret;
3121            }
3122
3123            MBEDTLS_SSL_DEBUG_ECDH(3, &ssl->handshake->ecdh_ctx,
3124                                   MBEDTLS_DEBUG_ECDH_Q);
3125        } else
3126#endif /* !MBEDTLS_USE_PSA_CRYPTO && MBEDTLS_KEY_EXCHANGE_ECDHE_PSK_ENABLED */
3127        {
3128            MBEDTLS_SSL_DEBUG_MSG(1, ("should never happen"));
3129            return MBEDTLS_ERR_SSL_INTERNAL_ERROR;
3130        }
3131
3132#if !defined(MBEDTLS_USE_PSA_CRYPTO)
3133        if ((ret = mbedtls_ssl_psk_derive_premaster(ssl,
3134                                                    (mbedtls_key_exchange_type_t) ciphersuite_info->
3135                                                    key_exchange)) != 0) {
3136            MBEDTLS_SSL_DEBUG_RET(1,
3137                                  "mbedtls_ssl_psk_derive_premaster", ret);
3138            return ret;
3139        }
3140#endif /* !MBEDTLS_USE_PSA_CRYPTO */
3141    } else
3142#endif /* MBEDTLS_KEY_EXCHANGE_SOME_PSK_ENABLED */
3143#if defined(MBEDTLS_KEY_EXCHANGE_RSA_ENABLED)
3144    if (ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_RSA) {
3145        header_len = 4;
3146        if ((ret = ssl_write_encrypted_pms(ssl, header_len,
3147                                           &content_len, 0)) != 0) {
3148            return ret;
3149        }
3150    } else
3151#endif /* MBEDTLS_KEY_EXCHANGE_RSA_ENABLED */
3152#if defined(MBEDTLS_KEY_EXCHANGE_ECJPAKE_ENABLED)
3153    if (ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_ECJPAKE) {
3154        header_len = 4;
3155
3156#if defined(MBEDTLS_USE_PSA_CRYPTO)
3157        unsigned char *out_p = ssl->out_msg + header_len;
3158        unsigned char *end_p = ssl->out_msg + MBEDTLS_SSL_OUT_CONTENT_LEN -
3159                               header_len;
3160        ret = mbedtls_psa_ecjpake_write_round(&ssl->handshake->psa_pake_ctx,
3161                                              out_p, end_p - out_p, &content_len,
3162                                              MBEDTLS_ECJPAKE_ROUND_TWO);
3163        if (ret != 0) {
3164            psa_destroy_key(ssl->handshake->psa_pake_password);
3165            psa_pake_abort(&ssl->handshake->psa_pake_ctx);
3166            MBEDTLS_SSL_DEBUG_RET(1, "psa_pake_output", ret);
3167            return ret;
3168        }
3169#else
3170        ret = mbedtls_ecjpake_write_round_two(&ssl->handshake->ecjpake_ctx,
3171                                              ssl->out_msg + header_len,
3172                                              MBEDTLS_SSL_OUT_CONTENT_LEN - header_len,
3173                                              &content_len,
3174                                              ssl->conf->f_rng, ssl->conf->p_rng);
3175        if (ret != 0) {
3176            MBEDTLS_SSL_DEBUG_RET(1, "mbedtls_ecjpake_write_round_two", ret);
3177            return ret;
3178        }
3179
3180        ret = mbedtls_ecjpake_derive_secret(&ssl->handshake->ecjpake_ctx,
3181                                            ssl->handshake->premaster, 32, &ssl->handshake->pmslen,
3182                                            ssl->conf->f_rng, ssl->conf->p_rng);
3183        if (ret != 0) {
3184            MBEDTLS_SSL_DEBUG_RET(1, "mbedtls_ecjpake_derive_secret", ret);
3185            return ret;
3186        }
3187#endif /* MBEDTLS_USE_PSA_CRYPTO */
3188    } else
3189#endif /* MBEDTLS_KEY_EXCHANGE_RSA_ENABLED */
3190    {
3191        ((void) ciphersuite_info);
3192        MBEDTLS_SSL_DEBUG_MSG(1, ("should never happen"));
3193        return MBEDTLS_ERR_SSL_INTERNAL_ERROR;
3194    }
3195
3196    ssl->out_msglen  = header_len + content_len;
3197    ssl->out_msgtype = MBEDTLS_SSL_MSG_HANDSHAKE;
3198    ssl->out_msg[0]  = MBEDTLS_SSL_HS_CLIENT_KEY_EXCHANGE;
3199
3200    ssl->state++;
3201
3202    if ((ret = mbedtls_ssl_write_handshake_msg(ssl)) != 0) {
3203        MBEDTLS_SSL_DEBUG_RET(1, "mbedtls_ssl_write_handshake_msg", ret);
3204        return ret;
3205    }
3206
3207    MBEDTLS_SSL_DEBUG_MSG(2, ("<= write client key exchange"));
3208
3209    return 0;
3210}
3211
3212#if !defined(MBEDTLS_KEY_EXCHANGE_CERT_REQ_ALLOWED_ENABLED)
3213MBEDTLS_CHECK_RETURN_CRITICAL
3214static int ssl_write_certificate_verify(mbedtls_ssl_context *ssl)
3215{
3216    const mbedtls_ssl_ciphersuite_t *ciphersuite_info =
3217        ssl->handshake->ciphersuite_info;
3218    int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
3219
3220    MBEDTLS_SSL_DEBUG_MSG(2, ("=> write certificate verify"));
3221
3222    if ((ret = mbedtls_ssl_derive_keys(ssl)) != 0) {
3223        MBEDTLS_SSL_DEBUG_RET(1, "mbedtls_ssl_derive_keys", ret);
3224        return ret;
3225    }
3226
3227    if (!mbedtls_ssl_ciphersuite_cert_req_allowed(ciphersuite_info)) {
3228        MBEDTLS_SSL_DEBUG_MSG(2, ("<= skip write certificate verify"));
3229        ssl->state++;
3230        return 0;
3231    }
3232
3233    MBEDTLS_SSL_DEBUG_MSG(1, ("should never happen"));
3234    return MBEDTLS_ERR_SSL_INTERNAL_ERROR;
3235}
3236#else /* !MBEDTLS_KEY_EXCHANGE_CERT_REQ_ALLOWED_ENABLED */
3237MBEDTLS_CHECK_RETURN_CRITICAL
3238static int ssl_write_certificate_verify(mbedtls_ssl_context *ssl)
3239{
3240    int ret = MBEDTLS_ERR_SSL_FEATURE_UNAVAILABLE;
3241    const mbedtls_ssl_ciphersuite_t *ciphersuite_info =
3242        ssl->handshake->ciphersuite_info;
3243    size_t n = 0, offset = 0;
3244    unsigned char hash[48];
3245    unsigned char *hash_start = hash;
3246    mbedtls_md_type_t md_alg = MBEDTLS_MD_NONE;
3247    size_t hashlen;
3248    void *rs_ctx = NULL;
3249#if defined(MBEDTLS_SSL_VARIABLE_BUFFER_LENGTH)
3250    size_t out_buf_len = ssl->out_buf_len - (size_t) (ssl->out_msg - ssl->out_buf);
3251#else
3252    size_t out_buf_len = MBEDTLS_SSL_OUT_BUFFER_LEN - (size_t) (ssl->out_msg - ssl->out_buf);
3253#endif
3254
3255    MBEDTLS_SSL_DEBUG_MSG(2, ("=> write certificate verify"));
3256
3257#if defined(MBEDTLS_SSL_ECP_RESTARTABLE_ENABLED)
3258    if (ssl->handshake->ecrs_enabled &&
3259        ssl->handshake->ecrs_state == ssl_ecrs_crt_vrfy_sign) {
3260        goto sign;
3261    }
3262#endif
3263
3264    if ((ret = mbedtls_ssl_derive_keys(ssl)) != 0) {
3265        MBEDTLS_SSL_DEBUG_RET(1, "mbedtls_ssl_derive_keys", ret);
3266        return ret;
3267    }
3268
3269    if (!mbedtls_ssl_ciphersuite_cert_req_allowed(ciphersuite_info)) {
3270        MBEDTLS_SSL_DEBUG_MSG(2, ("<= skip write certificate verify"));
3271        ssl->state++;
3272        return 0;
3273    }
3274
3275    if (ssl->handshake->client_auth == 0 ||
3276        mbedtls_ssl_own_cert(ssl) == NULL) {
3277        MBEDTLS_SSL_DEBUG_MSG(2, ("<= skip write certificate verify"));
3278        ssl->state++;
3279        return 0;
3280    }
3281
3282    if (mbedtls_ssl_own_key(ssl) == NULL) {
3283        MBEDTLS_SSL_DEBUG_MSG(1, ("got no private key for certificate"));
3284        return MBEDTLS_ERR_SSL_PRIVATE_KEY_REQUIRED;
3285    }
3286
3287    /*
3288     * Make a signature of the handshake digests
3289     */
3290#if defined(MBEDTLS_SSL_ECP_RESTARTABLE_ENABLED)
3291    if (ssl->handshake->ecrs_enabled) {
3292        ssl->handshake->ecrs_state = ssl_ecrs_crt_vrfy_sign;
3293    }
3294
3295sign:
3296#endif
3297
3298    ret = ssl->handshake->calc_verify(ssl, hash, &hashlen);
3299    if (0 != ret) {
3300        MBEDTLS_SSL_DEBUG_RET(1, ("calc_verify"), ret);
3301        return ret;
3302    }
3303
3304    /*
3305     * digitally-signed struct {
3306     *     opaque handshake_messages[handshake_messages_length];
3307     * };
3308     *
3309     * Taking shortcut here. We assume that the server always allows the
3310     * PRF Hash function and has sent it in the allowed signature
3311     * algorithms list received in the Certificate Request message.
3312     *
3313     * Until we encounter a server that does not, we will take this
3314     * shortcut.
3315     *
3316     * Reason: Otherwise we should have running hashes for SHA512 and
3317     *         SHA224 in order to satisfy 'weird' needs from the server
3318     *         side.
3319     */
3320    if (ssl->handshake->ciphersuite_info->mac == MBEDTLS_MD_SHA384) {
3321        md_alg = MBEDTLS_MD_SHA384;
3322        ssl->out_msg[4] = MBEDTLS_SSL_HASH_SHA384;
3323    } else {
3324        md_alg = MBEDTLS_MD_SHA256;
3325        ssl->out_msg[4] = MBEDTLS_SSL_HASH_SHA256;
3326    }
3327    ssl->out_msg[5] = mbedtls_ssl_sig_from_pk(mbedtls_ssl_own_key(ssl));
3328
3329    /* Info from md_alg will be used instead */
3330    hashlen = 0;
3331    offset = 2;
3332
3333#if defined(MBEDTLS_SSL_ECP_RESTARTABLE_ENABLED)
3334    if (ssl->handshake->ecrs_enabled) {
3335        rs_ctx = &ssl->handshake->ecrs_ctx.pk;
3336    }
3337#endif
3338
3339    if ((ret = mbedtls_pk_sign_restartable(mbedtls_ssl_own_key(ssl),
3340                                           md_alg, hash_start, hashlen,
3341                                           ssl->out_msg + 6 + offset,
3342                                           out_buf_len - 6 - offset,
3343                                           &n,
3344                                           ssl->conf->f_rng, ssl->conf->p_rng, rs_ctx)) != 0) {
3345        MBEDTLS_SSL_DEBUG_RET(1, "mbedtls_pk_sign", ret);
3346#if defined(MBEDTLS_SSL_ECP_RESTARTABLE_ENABLED)
3347        if (ret == MBEDTLS_ERR_ECP_IN_PROGRESS) {
3348            ret = MBEDTLS_ERR_SSL_CRYPTO_IN_PROGRESS;
3349        }
3350#endif
3351        return ret;
3352    }
3353
3354    MBEDTLS_PUT_UINT16_BE(n, ssl->out_msg, offset + 4);
3355
3356    ssl->out_msglen  = 6 + n + offset;
3357    ssl->out_msgtype = MBEDTLS_SSL_MSG_HANDSHAKE;
3358    ssl->out_msg[0]  = MBEDTLS_SSL_HS_CERTIFICATE_VERIFY;
3359
3360    ssl->state++;
3361
3362    if ((ret = mbedtls_ssl_write_handshake_msg(ssl)) != 0) {
3363        MBEDTLS_SSL_DEBUG_RET(1, "mbedtls_ssl_write_handshake_msg", ret);
3364        return ret;
3365    }
3366
3367    MBEDTLS_SSL_DEBUG_MSG(2, ("<= write certificate verify"));
3368
3369    return ret;
3370}
3371#endif /* MBEDTLS_KEY_EXCHANGE_CERT_REQ_ALLOWED_ENABLED */
3372
3373#if defined(MBEDTLS_SSL_SESSION_TICKETS)
3374MBEDTLS_CHECK_RETURN_CRITICAL
3375static int ssl_parse_new_session_ticket(mbedtls_ssl_context *ssl)
3376{
3377    int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
3378    uint32_t lifetime;
3379    size_t ticket_len;
3380    unsigned char *ticket;
3381    const unsigned char *msg;
3382
3383    MBEDTLS_SSL_DEBUG_MSG(2, ("=> parse new session ticket"));
3384
3385    if ((ret = mbedtls_ssl_read_record(ssl, 1)) != 0) {
3386        MBEDTLS_SSL_DEBUG_RET(1, "mbedtls_ssl_read_record", ret);
3387        return ret;
3388    }
3389
3390    if (ssl->in_msgtype != MBEDTLS_SSL_MSG_HANDSHAKE) {
3391        MBEDTLS_SSL_DEBUG_MSG(1, ("bad new session ticket message"));
3392        mbedtls_ssl_send_alert_message(
3393            ssl,
3394            MBEDTLS_SSL_ALERT_LEVEL_FATAL,
3395            MBEDTLS_SSL_ALERT_MSG_UNEXPECTED_MESSAGE);
3396        return MBEDTLS_ERR_SSL_UNEXPECTED_MESSAGE;
3397    }
3398
3399    /*
3400     * struct {
3401     *     uint32 ticket_lifetime_hint;
3402     *     opaque ticket<0..2^16-1>;
3403     * } NewSessionTicket;
3404     *
3405     * 0  .  3   ticket_lifetime_hint
3406     * 4  .  5   ticket_len (n)
3407     * 6  .  5+n ticket content
3408     */
3409    if (ssl->in_msg[0] != MBEDTLS_SSL_HS_NEW_SESSION_TICKET ||
3410        ssl->in_hslen < 6 + mbedtls_ssl_hs_hdr_len(ssl)) {
3411        MBEDTLS_SSL_DEBUG_MSG(1, ("bad new session ticket message"));
3412        mbedtls_ssl_send_alert_message(ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,
3413                                       MBEDTLS_SSL_ALERT_MSG_DECODE_ERROR);
3414        return MBEDTLS_ERR_SSL_DECODE_ERROR;
3415    }
3416
3417    msg = ssl->in_msg + mbedtls_ssl_hs_hdr_len(ssl);
3418
3419    lifetime = MBEDTLS_GET_UINT32_BE(msg, 0);
3420
3421    ticket_len = MBEDTLS_GET_UINT16_BE(msg, 4);
3422
3423    if (ticket_len + 6 + mbedtls_ssl_hs_hdr_len(ssl) != ssl->in_hslen) {
3424        MBEDTLS_SSL_DEBUG_MSG(1, ("bad new session ticket message"));
3425        mbedtls_ssl_send_alert_message(ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,
3426                                       MBEDTLS_SSL_ALERT_MSG_DECODE_ERROR);
3427        return MBEDTLS_ERR_SSL_DECODE_ERROR;
3428    }
3429
3430    MBEDTLS_SSL_DEBUG_MSG(3, ("ticket length: %" MBEDTLS_PRINTF_SIZET, ticket_len));
3431
3432    /* We're not waiting for a NewSessionTicket message any more */
3433    ssl->handshake->new_session_ticket = 0;
3434    ssl->state = MBEDTLS_SSL_SERVER_CHANGE_CIPHER_SPEC;
3435
3436    /*
3437     * Zero-length ticket means the server changed his mind and doesn't want
3438     * to send a ticket after all, so just forget it
3439     */
3440    if (ticket_len == 0) {
3441        return 0;
3442    }
3443
3444    if (ssl->session != NULL && ssl->session->ticket != NULL) {
3445        mbedtls_zeroize_and_free(ssl->session->ticket,
3446                                 ssl->session->ticket_len);
3447        ssl->session->ticket = NULL;
3448        ssl->session->ticket_len = 0;
3449    }
3450
3451    mbedtls_zeroize_and_free(ssl->session_negotiate->ticket,
3452                             ssl->session_negotiate->ticket_len);
3453    ssl->session_negotiate->ticket = NULL;
3454    ssl->session_negotiate->ticket_len = 0;
3455
3456    if ((ticket = mbedtls_calloc(1, ticket_len)) == NULL) {
3457        MBEDTLS_SSL_DEBUG_MSG(1, ("ticket alloc failed"));
3458        mbedtls_ssl_send_alert_message(ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,
3459                                       MBEDTLS_SSL_ALERT_MSG_INTERNAL_ERROR);
3460        return MBEDTLS_ERR_SSL_ALLOC_FAILED;
3461    }
3462
3463    memcpy(ticket, msg + 6, ticket_len);
3464
3465    ssl->session_negotiate->ticket = ticket;
3466    ssl->session_negotiate->ticket_len = ticket_len;
3467    ssl->session_negotiate->ticket_lifetime = lifetime;
3468
3469    /*
3470     * RFC 5077 section 3.4:
3471     * "If the client receives a session ticket from the server, then it
3472     * discards any Session ID that was sent in the ServerHello."
3473     */
3474    MBEDTLS_SSL_DEBUG_MSG(3, ("ticket in use, discarding session id"));
3475    ssl->session_negotiate->id_len = 0;
3476
3477    MBEDTLS_SSL_DEBUG_MSG(2, ("<= parse new session ticket"));
3478
3479    return 0;
3480}
3481#endif /* MBEDTLS_SSL_SESSION_TICKETS */
3482
3483/*
3484 * SSL handshake -- client side -- single step
3485 */
3486int mbedtls_ssl_handshake_client_step(mbedtls_ssl_context *ssl)
3487{
3488    int ret = 0;
3489
3490    /* Change state now, so that it is right in mbedtls_ssl_read_record(), used
3491     * by DTLS for dropping out-of-sequence ChangeCipherSpec records */
3492#if defined(MBEDTLS_SSL_SESSION_TICKETS)
3493    if (ssl->state == MBEDTLS_SSL_SERVER_CHANGE_CIPHER_SPEC &&
3494        ssl->handshake->new_session_ticket != 0) {
3495        ssl->state = MBEDTLS_SSL_NEW_SESSION_TICKET;
3496    }
3497#endif
3498
3499    switch (ssl->state) {
3500        case MBEDTLS_SSL_HELLO_REQUEST:
3501            ssl->state = MBEDTLS_SSL_CLIENT_HELLO;
3502            break;
3503
3504        /*
3505         *  ==>   ClientHello
3506         */
3507        case MBEDTLS_SSL_CLIENT_HELLO:
3508            ret = mbedtls_ssl_write_client_hello(ssl);
3509            break;
3510
3511        /*
3512         *  <==   ServerHello
3513         *        Certificate
3514         *      ( ServerKeyExchange  )
3515         *      ( CertificateRequest )
3516         *        ServerHelloDone
3517         */
3518        case MBEDTLS_SSL_SERVER_HELLO:
3519            ret = ssl_parse_server_hello(ssl);
3520            break;
3521
3522        case MBEDTLS_SSL_SERVER_CERTIFICATE:
3523            ret = mbedtls_ssl_parse_certificate(ssl);
3524            break;
3525
3526        case MBEDTLS_SSL_SERVER_KEY_EXCHANGE:
3527            ret = ssl_parse_server_key_exchange(ssl);
3528            break;
3529
3530        case MBEDTLS_SSL_CERTIFICATE_REQUEST:
3531            ret = ssl_parse_certificate_request(ssl);
3532            break;
3533
3534        case MBEDTLS_SSL_SERVER_HELLO_DONE:
3535            ret = ssl_parse_server_hello_done(ssl);
3536            break;
3537
3538        /*
3539         *  ==> ( Certificate/Alert  )
3540         *        ClientKeyExchange
3541         *      ( CertificateVerify  )
3542         *        ChangeCipherSpec
3543         *        Finished
3544         */
3545        case MBEDTLS_SSL_CLIENT_CERTIFICATE:
3546            ret = mbedtls_ssl_write_certificate(ssl);
3547            break;
3548
3549        case MBEDTLS_SSL_CLIENT_KEY_EXCHANGE:
3550            ret = ssl_write_client_key_exchange(ssl);
3551            break;
3552
3553        case MBEDTLS_SSL_CERTIFICATE_VERIFY:
3554            ret = ssl_write_certificate_verify(ssl);
3555            break;
3556
3557        case MBEDTLS_SSL_CLIENT_CHANGE_CIPHER_SPEC:
3558            ret = mbedtls_ssl_write_change_cipher_spec(ssl);
3559            break;
3560
3561        case MBEDTLS_SSL_CLIENT_FINISHED:
3562            ret = mbedtls_ssl_write_finished(ssl);
3563            break;
3564
3565            /*
3566             *  <==   ( NewSessionTicket )
3567             *        ChangeCipherSpec
3568             *        Finished
3569             */
3570#if defined(MBEDTLS_SSL_SESSION_TICKETS)
3571        case MBEDTLS_SSL_NEW_SESSION_TICKET:
3572            ret = ssl_parse_new_session_ticket(ssl);
3573            break;
3574#endif
3575
3576        case MBEDTLS_SSL_SERVER_CHANGE_CIPHER_SPEC:
3577            ret = mbedtls_ssl_parse_change_cipher_spec(ssl);
3578            break;
3579
3580        case MBEDTLS_SSL_SERVER_FINISHED:
3581            ret = mbedtls_ssl_parse_finished(ssl);
3582            break;
3583
3584        case MBEDTLS_SSL_FLUSH_BUFFERS:
3585            MBEDTLS_SSL_DEBUG_MSG(2, ("handshake: done"));
3586            ssl->state = MBEDTLS_SSL_HANDSHAKE_WRAPUP;
3587            break;
3588
3589        case MBEDTLS_SSL_HANDSHAKE_WRAPUP:
3590            mbedtls_ssl_handshake_wrapup(ssl);
3591            break;
3592
3593        default:
3594            MBEDTLS_SSL_DEBUG_MSG(1, ("invalid state %d", ssl->state));
3595            return MBEDTLS_ERR_SSL_BAD_INPUT_DATA;
3596    }
3597
3598    return ret;
3599}
3600
3601#endif /* MBEDTLS_SSL_CLI_C && MBEDTLS_SSL_PROTO_TLS1_2 */
3602