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