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