• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  *  SSLv3/TLSv1 server-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_SRV_C)
11 
12 #include "mbedtls/platform.h"
13 
14 #include "mbedtls/ssl.h"
15 #include "mbedtls/ssl_internal.h"
16 #include "mbedtls/debug.h"
17 #include "mbedtls/error.h"
18 #include "mbedtls/platform_util.h"
19 #include "constant_time_internal.h"
20 #include "mbedtls/constant_time.h"
21 
22 #include <string.h>
23 
24 #if defined(MBEDTLS_ECP_C)
25 #include "mbedtls/ecp.h"
26 #endif
27 
28 #if defined(MBEDTLS_HAVE_TIME)
29 #include "mbedtls/platform_time.h"
30 #endif
31 
32 #if defined(MBEDTLS_SSL_DTLS_HELLO_VERIFY)
mbedtls_ssl_set_client_transport_id(mbedtls_ssl_context * ssl,const unsigned char * info,size_t ilen)33 int mbedtls_ssl_set_client_transport_id(mbedtls_ssl_context *ssl,
34                                         const unsigned char *info,
35                                         size_t ilen)
36 {
37     if (ssl->conf->endpoint != MBEDTLS_SSL_IS_SERVER) {
38         return MBEDTLS_ERR_SSL_BAD_INPUT_DATA;
39     }
40 
41     mbedtls_free(ssl->cli_id);
42 
43     if ((ssl->cli_id = mbedtls_calloc(1, ilen)) == NULL) {
44         return MBEDTLS_ERR_SSL_ALLOC_FAILED;
45     }
46 
47     memcpy(ssl->cli_id, info, ilen);
48     ssl->cli_id_len = ilen;
49 
50     return 0;
51 }
52 
mbedtls_ssl_conf_dtls_cookies(mbedtls_ssl_config * conf,mbedtls_ssl_cookie_write_t * f_cookie_write,mbedtls_ssl_cookie_check_t * f_cookie_check,void * p_cookie)53 void mbedtls_ssl_conf_dtls_cookies(mbedtls_ssl_config *conf,
54                                    mbedtls_ssl_cookie_write_t *f_cookie_write,
55                                    mbedtls_ssl_cookie_check_t *f_cookie_check,
56                                    void *p_cookie)
57 {
58     conf->f_cookie_write = f_cookie_write;
59     conf->f_cookie_check = f_cookie_check;
60     conf->p_cookie       = p_cookie;
61 }
62 #endif /* MBEDTLS_SSL_DTLS_HELLO_VERIFY */
63 
64 #if defined(MBEDTLS_SSL_SERVER_NAME_INDICATION)
65 MBEDTLS_CHECK_RETURN_CRITICAL
ssl_parse_servername_ext(mbedtls_ssl_context * ssl,const unsigned char * buf,size_t len)66 static int ssl_parse_servername_ext(mbedtls_ssl_context *ssl,
67                                     const unsigned char *buf,
68                                     size_t len)
69 {
70     int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
71     size_t servername_list_size, hostname_len;
72     const unsigned char *p;
73 
74     MBEDTLS_SSL_DEBUG_MSG(3, ("parse ServerName extension"));
75 
76     if (len < 2) {
77         MBEDTLS_SSL_DEBUG_MSG(1, ("bad client hello message"));
78         mbedtls_ssl_send_alert_message(ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,
79                                        MBEDTLS_SSL_ALERT_MSG_DECODE_ERROR);
80         return MBEDTLS_ERR_SSL_BAD_HS_CLIENT_HELLO;
81     }
82     servername_list_size = ((buf[0] << 8) | (buf[1]));
83     if (servername_list_size + 2 != len) {
84         MBEDTLS_SSL_DEBUG_MSG(1, ("bad client hello message"));
85         mbedtls_ssl_send_alert_message(ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,
86                                        MBEDTLS_SSL_ALERT_MSG_DECODE_ERROR);
87         return MBEDTLS_ERR_SSL_BAD_HS_CLIENT_HELLO;
88     }
89 
90     p = buf + 2;
91     while (servername_list_size > 2) {
92         hostname_len = ((p[1] << 8) | p[2]);
93         if (hostname_len + 3 > servername_list_size) {
94             MBEDTLS_SSL_DEBUG_MSG(1, ("bad client hello message"));
95             mbedtls_ssl_send_alert_message(ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,
96                                            MBEDTLS_SSL_ALERT_MSG_DECODE_ERROR);
97             return MBEDTLS_ERR_SSL_BAD_HS_CLIENT_HELLO;
98         }
99 
100         if (p[0] == MBEDTLS_TLS_EXT_SERVERNAME_HOSTNAME) {
101             ret = ssl->conf->f_sni(ssl->conf->p_sni,
102                                    ssl, p + 3, hostname_len);
103             if (ret != 0) {
104                 MBEDTLS_SSL_DEBUG_RET(1, "ssl_sni_wrapper", ret);
105                 mbedtls_ssl_send_alert_message(ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,
106                                                MBEDTLS_SSL_ALERT_MSG_UNRECOGNIZED_NAME);
107                 return MBEDTLS_ERR_SSL_BAD_HS_CLIENT_HELLO;
108             }
109             return 0;
110         }
111 
112         servername_list_size -= hostname_len + 3;
113         p += hostname_len + 3;
114     }
115 
116     if (servername_list_size != 0) {
117         MBEDTLS_SSL_DEBUG_MSG(1, ("bad client hello message"));
118         mbedtls_ssl_send_alert_message(ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,
119                                        MBEDTLS_SSL_ALERT_MSG_ILLEGAL_PARAMETER);
120         return MBEDTLS_ERR_SSL_BAD_HS_CLIENT_HELLO;
121     }
122 
123     return 0;
124 }
125 #endif /* MBEDTLS_SSL_SERVER_NAME_INDICATION */
126 
127 #if defined(MBEDTLS_KEY_EXCHANGE_SOME_PSK_ENABLED)
128 MBEDTLS_CHECK_RETURN_CRITICAL
ssl_conf_has_psk_or_cb(mbedtls_ssl_config const * conf)129 static int ssl_conf_has_psk_or_cb(mbedtls_ssl_config const *conf)
130 {
131     if (conf->f_psk != NULL) {
132         return 1;
133     }
134 
135     if (conf->psk_identity_len == 0 || conf->psk_identity == NULL) {
136         return 0;
137     }
138 
139     if (conf->psk != NULL && conf->psk_len != 0) {
140         return 1;
141     }
142 
143 #if defined(MBEDTLS_USE_PSA_CRYPTO)
144     if (!mbedtls_svc_key_id_is_null(conf->psk_opaque)) {
145         return 1;
146     }
147 #endif /* MBEDTLS_USE_PSA_CRYPTO */
148 
149     return 0;
150 }
151 
152 #if defined(MBEDTLS_USE_PSA_CRYPTO)
153 MBEDTLS_CHECK_RETURN_CRITICAL
ssl_use_opaque_psk(mbedtls_ssl_context const * ssl)154 static int ssl_use_opaque_psk(mbedtls_ssl_context const *ssl)
155 {
156     if (ssl->conf->f_psk != NULL) {
157         /* If we've used a callback to select the PSK,
158          * the static configuration is irrelevant. */
159 
160         if (!mbedtls_svc_key_id_is_null(ssl->handshake->psk_opaque)) {
161             return 1;
162         }
163 
164         return 0;
165     }
166 
167     if (!mbedtls_svc_key_id_is_null(ssl->conf->psk_opaque)) {
168         return 1;
169     }
170 
171     return 0;
172 }
173 #endif /* MBEDTLS_USE_PSA_CRYPTO */
174 #endif /* MBEDTLS_KEY_EXCHANGE_SOME_PSK_ENABLED */
175 
176 MBEDTLS_CHECK_RETURN_CRITICAL
ssl_parse_renegotiation_info(mbedtls_ssl_context * ssl,const unsigned char * buf,size_t len)177 static int ssl_parse_renegotiation_info(mbedtls_ssl_context *ssl,
178                                         const unsigned char *buf,
179                                         size_t len)
180 {
181 #if defined(MBEDTLS_SSL_RENEGOTIATION)
182     if (ssl->renego_status != MBEDTLS_SSL_INITIAL_HANDSHAKE) {
183         /* Check verify-data in constant-time. The length OTOH is no secret */
184         if (len    != 1 + ssl->verify_data_len ||
185             buf[0] !=     ssl->verify_data_len ||
186             mbedtls_ct_memcmp(buf + 1, ssl->peer_verify_data,
187                               ssl->verify_data_len) != 0) {
188             MBEDTLS_SSL_DEBUG_MSG(1, ("non-matching renegotiation info"));
189             mbedtls_ssl_send_alert_message(ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,
190                                            MBEDTLS_SSL_ALERT_MSG_HANDSHAKE_FAILURE);
191             return MBEDTLS_ERR_SSL_BAD_HS_CLIENT_HELLO;
192         }
193     } else
194 #endif /* MBEDTLS_SSL_RENEGOTIATION */
195     {
196         if (len != 1 || buf[0] != 0x0) {
197             MBEDTLS_SSL_DEBUG_MSG(1, ("non-zero length renegotiation info"));
198             mbedtls_ssl_send_alert_message(ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,
199                                            MBEDTLS_SSL_ALERT_MSG_HANDSHAKE_FAILURE);
200             return MBEDTLS_ERR_SSL_BAD_HS_CLIENT_HELLO;
201         }
202 
203         ssl->secure_renegotiation = MBEDTLS_SSL_SECURE_RENEGOTIATION;
204     }
205 
206     return 0;
207 }
208 
209 #if defined(MBEDTLS_SSL_PROTO_TLS1_2) && \
210     defined(MBEDTLS_KEY_EXCHANGE_WITH_CERT_ENABLED)
211 
212 /*
213  * Status of the implementation of signature-algorithms extension:
214  *
215  * Currently, we are only considering the signature-algorithm extension
216  * to pick a ciphersuite which allows us to send the ServerKeyExchange
217  * message with a signature-hash combination that the user allows.
218  *
219  * We do *not* check whether all certificates in our certificate
220  * chain are signed with an allowed signature-hash pair.
221  * This needs to be done at a later stage.
222  *
223  */
224 MBEDTLS_CHECK_RETURN_CRITICAL
ssl_parse_signature_algorithms_ext(mbedtls_ssl_context * ssl,const unsigned char * buf,size_t len)225 static int ssl_parse_signature_algorithms_ext(mbedtls_ssl_context *ssl,
226                                               const unsigned char *buf,
227                                               size_t len)
228 {
229     size_t sig_alg_list_size;
230 
231     const unsigned char *p;
232     const unsigned char *end = buf + len;
233 
234     mbedtls_md_type_t md_cur;
235     mbedtls_pk_type_t sig_cur;
236 
237     if (len < 2) {
238         MBEDTLS_SSL_DEBUG_MSG(1, ("bad client hello message"));
239         mbedtls_ssl_send_alert_message(ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,
240                                        MBEDTLS_SSL_ALERT_MSG_DECODE_ERROR);
241         return MBEDTLS_ERR_SSL_BAD_HS_CLIENT_HELLO;
242     }
243     sig_alg_list_size = ((buf[0] << 8) | (buf[1]));
244     if (sig_alg_list_size + 2 != len ||
245         sig_alg_list_size % 2 != 0) {
246         MBEDTLS_SSL_DEBUG_MSG(1, ("bad client hello message"));
247         mbedtls_ssl_send_alert_message(ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,
248                                        MBEDTLS_SSL_ALERT_MSG_DECODE_ERROR);
249         return MBEDTLS_ERR_SSL_BAD_HS_CLIENT_HELLO;
250     }
251 
252     /* Currently we only guarantee signing the ServerKeyExchange message according
253      * to the constraints specified in this extension (see above), so it suffices
254      * to remember only one suitable hash for each possible signature algorithm.
255      *
256      * This will change when we also consider certificate signatures,
257      * in which case we will need to remember the whole signature-hash
258      * pair list from the extension.
259      */
260 
261     for (p = buf + 2; p < end; p += 2) {
262         /* Silently ignore unknown signature or hash algorithms. */
263 
264         if ((sig_cur = mbedtls_ssl_pk_alg_from_sig(p[1])) == MBEDTLS_PK_NONE) {
265             MBEDTLS_SSL_DEBUG_MSG(3, ("client hello v3, signature_algorithm ext"
266                                       " unknown sig alg encoding %d", p[1]));
267             continue;
268         }
269 
270         /* Check if we support the hash the user proposes */
271         md_cur = mbedtls_ssl_md_alg_from_hash(p[0]);
272         if (md_cur == MBEDTLS_MD_NONE) {
273             MBEDTLS_SSL_DEBUG_MSG(3, ("client hello v3, signature_algorithm ext:"
274                                       " unknown hash alg encoding %d", p[0]));
275             continue;
276         }
277 
278         if (mbedtls_ssl_check_sig_hash(ssl, md_cur) == 0) {
279             mbedtls_ssl_sig_hash_set_add(&ssl->handshake->hash_algs, sig_cur, md_cur);
280             MBEDTLS_SSL_DEBUG_MSG(3, ("client hello v3, signature_algorithm ext:"
281                                       " match sig %u and hash %u",
282                                       (unsigned) sig_cur, (unsigned) md_cur));
283         } else {
284             MBEDTLS_SSL_DEBUG_MSG(3, ("client hello v3, signature_algorithm ext: "
285                                       "hash alg %u not supported", (unsigned) md_cur));
286         }
287     }
288 
289     return 0;
290 }
291 #endif /* MBEDTLS_SSL_PROTO_TLS1_2 &&
292           MBEDTLS_KEY_EXCHANGE_WITH_CERT_ENABLED */
293 
294 #if defined(MBEDTLS_ECDH_C) || defined(MBEDTLS_ECDSA_C) || \
295     defined(MBEDTLS_KEY_EXCHANGE_ECJPAKE_ENABLED)
296 MBEDTLS_CHECK_RETURN_CRITICAL
ssl_parse_supported_elliptic_curves(mbedtls_ssl_context * ssl,const unsigned char * buf,size_t len)297 static int ssl_parse_supported_elliptic_curves(mbedtls_ssl_context *ssl,
298                                                const unsigned char *buf,
299                                                size_t len)
300 {
301     size_t list_size, our_size;
302     const unsigned char *p;
303     const mbedtls_ecp_curve_info *curve_info, **curves;
304 
305     if (len < 2) {
306         MBEDTLS_SSL_DEBUG_MSG(1, ("bad client hello message"));
307         mbedtls_ssl_send_alert_message(ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,
308                                        MBEDTLS_SSL_ALERT_MSG_DECODE_ERROR);
309         return MBEDTLS_ERR_SSL_BAD_HS_CLIENT_HELLO;
310     }
311     list_size = ((buf[0] << 8) | (buf[1]));
312     if (list_size + 2 != len ||
313         list_size % 2 != 0) {
314         MBEDTLS_SSL_DEBUG_MSG(1, ("bad client hello message"));
315         mbedtls_ssl_send_alert_message(ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,
316                                        MBEDTLS_SSL_ALERT_MSG_DECODE_ERROR);
317         return MBEDTLS_ERR_SSL_BAD_HS_CLIENT_HELLO;
318     }
319 
320     /* Should never happen unless client duplicates the extension */
321     if (ssl->handshake->curves != NULL) {
322         MBEDTLS_SSL_DEBUG_MSG(1, ("bad client hello message"));
323         mbedtls_ssl_send_alert_message(ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,
324                                        MBEDTLS_SSL_ALERT_MSG_DECODE_ERROR);
325         return MBEDTLS_ERR_SSL_BAD_HS_CLIENT_HELLO;
326     }
327 
328     /* Don't allow our peer to make us allocate too much memory,
329      * and leave room for a final 0 */
330     our_size = list_size / 2 + 1;
331     if (our_size > MBEDTLS_ECP_DP_MAX) {
332         our_size = MBEDTLS_ECP_DP_MAX;
333     }
334 
335     if ((curves = mbedtls_calloc(our_size, sizeof(*curves))) == NULL) {
336         mbedtls_ssl_send_alert_message(ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,
337                                        MBEDTLS_SSL_ALERT_MSG_INTERNAL_ERROR);
338         return MBEDTLS_ERR_SSL_ALLOC_FAILED;
339     }
340 
341     ssl->handshake->curves = curves;
342 
343     p = buf + 2;
344     while (list_size > 0 && our_size > 1) {
345         curve_info = mbedtls_ecp_curve_info_from_tls_id((p[0] << 8) | p[1]);
346 
347         if (curve_info != NULL) {
348             *curves++ = curve_info;
349             our_size--;
350         }
351 
352         list_size -= 2;
353         p += 2;
354     }
355 
356     return 0;
357 }
358 
359 MBEDTLS_CHECK_RETURN_CRITICAL
ssl_parse_supported_point_formats(mbedtls_ssl_context * ssl,const unsigned char * buf,size_t len)360 static int ssl_parse_supported_point_formats(mbedtls_ssl_context *ssl,
361                                              const unsigned char *buf,
362                                              size_t len)
363 {
364     size_t list_size;
365     const unsigned char *p;
366 
367     if (len == 0 || (size_t) (buf[0] + 1) != len) {
368         MBEDTLS_SSL_DEBUG_MSG(1, ("bad client hello message"));
369         mbedtls_ssl_send_alert_message(ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,
370                                        MBEDTLS_SSL_ALERT_MSG_DECODE_ERROR);
371         return MBEDTLS_ERR_SSL_BAD_HS_CLIENT_HELLO;
372     }
373     list_size = buf[0];
374 
375     p = buf + 1;
376     while (list_size > 0) {
377         if (p[0] == MBEDTLS_ECP_PF_UNCOMPRESSED ||
378             p[0] == MBEDTLS_ECP_PF_COMPRESSED) {
379 #if defined(MBEDTLS_ECDH_C) || defined(MBEDTLS_ECDSA_C)
380             ssl->handshake->ecdh_ctx.point_format = p[0];
381 #endif
382 #if defined(MBEDTLS_KEY_EXCHANGE_ECJPAKE_ENABLED)
383             ssl->handshake->ecjpake_ctx.point_format = p[0];
384 #endif
385             MBEDTLS_SSL_DEBUG_MSG(4, ("point format selected: %d", p[0]));
386             return 0;
387         }
388 
389         list_size--;
390         p++;
391     }
392 
393     return 0;
394 }
395 #endif /* MBEDTLS_ECDH_C || MBEDTLS_ECDSA_C ||
396           MBEDTLS_KEY_EXCHANGE_ECJPAKE_ENABLED */
397 
398 #if defined(MBEDTLS_KEY_EXCHANGE_ECJPAKE_ENABLED)
399 MBEDTLS_CHECK_RETURN_CRITICAL
ssl_parse_ecjpake_kkpp(mbedtls_ssl_context * ssl,const unsigned char * buf,size_t len)400 static int ssl_parse_ecjpake_kkpp(mbedtls_ssl_context *ssl,
401                                   const unsigned char *buf,
402                                   size_t len)
403 {
404     int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
405 
406     if (mbedtls_ecjpake_check(&ssl->handshake->ecjpake_ctx) != 0) {
407         MBEDTLS_SSL_DEBUG_MSG(3, ("skip ecjpake kkpp extension"));
408         return 0;
409     }
410 
411     if ((ret = mbedtls_ecjpake_read_round_one(&ssl->handshake->ecjpake_ctx,
412                                               buf, len)) != 0) {
413         MBEDTLS_SSL_DEBUG_RET(1, "mbedtls_ecjpake_read_round_one", ret);
414         mbedtls_ssl_send_alert_message(ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,
415                                        MBEDTLS_SSL_ALERT_MSG_ILLEGAL_PARAMETER);
416         return ret;
417     }
418 
419     /* Only mark the extension as OK when we're sure it is */
420     ssl->handshake->cli_exts |= MBEDTLS_TLS_EXT_ECJPAKE_KKPP_OK;
421 
422     return 0;
423 }
424 #endif /* MBEDTLS_KEY_EXCHANGE_ECJPAKE_ENABLED */
425 
426 #if defined(MBEDTLS_SSL_MAX_FRAGMENT_LENGTH)
427 MBEDTLS_CHECK_RETURN_CRITICAL
ssl_parse_max_fragment_length_ext(mbedtls_ssl_context * ssl,const unsigned char * buf,size_t len)428 static int ssl_parse_max_fragment_length_ext(mbedtls_ssl_context *ssl,
429                                              const unsigned char *buf,
430                                              size_t len)
431 {
432     if (len != 1 || buf[0] >= MBEDTLS_SSL_MAX_FRAG_LEN_INVALID) {
433         MBEDTLS_SSL_DEBUG_MSG(1, ("bad client hello message"));
434         mbedtls_ssl_send_alert_message(ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,
435                                        MBEDTLS_SSL_ALERT_MSG_ILLEGAL_PARAMETER);
436         return MBEDTLS_ERR_SSL_BAD_HS_CLIENT_HELLO;
437     }
438 
439     ssl->session_negotiate->mfl_code = buf[0];
440 
441     return 0;
442 }
443 #endif /* MBEDTLS_SSL_MAX_FRAGMENT_LENGTH */
444 
445 #if defined(MBEDTLS_SSL_DTLS_CONNECTION_ID)
446 MBEDTLS_CHECK_RETURN_CRITICAL
ssl_parse_cid_ext(mbedtls_ssl_context * ssl,const unsigned char * buf,size_t len)447 static int ssl_parse_cid_ext(mbedtls_ssl_context *ssl,
448                              const unsigned char *buf,
449                              size_t len)
450 {
451     size_t peer_cid_len;
452 
453     /* CID extension only makes sense in DTLS */
454     if (ssl->conf->transport != MBEDTLS_SSL_TRANSPORT_DATAGRAM) {
455         MBEDTLS_SSL_DEBUG_MSG(1, ("bad client hello message"));
456         mbedtls_ssl_send_alert_message(ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,
457                                        MBEDTLS_SSL_ALERT_MSG_ILLEGAL_PARAMETER);
458         return MBEDTLS_ERR_SSL_BAD_HS_CLIENT_HELLO;
459     }
460 
461     /*
462      * Quoting draft-ietf-tls-dtls-connection-id-05
463      * https://tools.ietf.org/html/draft-ietf-tls-dtls-connection-id-05
464      *
465      *   struct {
466      *      opaque cid<0..2^8-1>;
467      *   } ConnectionId;
468      */
469 
470     if (len < 1) {
471         MBEDTLS_SSL_DEBUG_MSG(1, ("bad client hello message"));
472         mbedtls_ssl_send_alert_message(ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,
473                                        MBEDTLS_SSL_ALERT_MSG_ILLEGAL_PARAMETER);
474         return MBEDTLS_ERR_SSL_BAD_HS_CLIENT_HELLO;
475     }
476 
477     peer_cid_len = *buf++;
478     len--;
479 
480     if (len != peer_cid_len) {
481         MBEDTLS_SSL_DEBUG_MSG(1, ("bad client hello message"));
482         mbedtls_ssl_send_alert_message(ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,
483                                        MBEDTLS_SSL_ALERT_MSG_ILLEGAL_PARAMETER);
484         return MBEDTLS_ERR_SSL_BAD_HS_CLIENT_HELLO;
485     }
486 
487     /* Ignore CID if the user has disabled its use. */
488     if (ssl->negotiate_cid == MBEDTLS_SSL_CID_DISABLED) {
489         /* Leave ssl->handshake->cid_in_use in its default
490          * value of MBEDTLS_SSL_CID_DISABLED. */
491         MBEDTLS_SSL_DEBUG_MSG(3, ("Client sent CID extension, but CID disabled"));
492         return 0;
493     }
494 
495     if (peer_cid_len > MBEDTLS_SSL_CID_OUT_LEN_MAX) {
496         MBEDTLS_SSL_DEBUG_MSG(1, ("bad client hello message"));
497         mbedtls_ssl_send_alert_message(ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,
498                                        MBEDTLS_SSL_ALERT_MSG_ILLEGAL_PARAMETER);
499         return MBEDTLS_ERR_SSL_BAD_HS_CLIENT_HELLO;
500     }
501 
502     ssl->handshake->cid_in_use = MBEDTLS_SSL_CID_ENABLED;
503     ssl->handshake->peer_cid_len = (uint8_t) peer_cid_len;
504     memcpy(ssl->handshake->peer_cid, buf, peer_cid_len);
505 
506     MBEDTLS_SSL_DEBUG_MSG(3, ("Use of CID extension negotiated"));
507     MBEDTLS_SSL_DEBUG_BUF(3, "Client CID", buf, peer_cid_len);
508 
509     return 0;
510 }
511 #endif /* MBEDTLS_SSL_DTLS_CONNECTION_ID */
512 
513 #if defined(MBEDTLS_SSL_TRUNCATED_HMAC)
514 MBEDTLS_CHECK_RETURN_CRITICAL
ssl_parse_truncated_hmac_ext(mbedtls_ssl_context * ssl,const unsigned char * buf,size_t len)515 static int ssl_parse_truncated_hmac_ext(mbedtls_ssl_context *ssl,
516                                         const unsigned char *buf,
517                                         size_t len)
518 {
519     if (len != 0) {
520         MBEDTLS_SSL_DEBUG_MSG(1, ("bad client hello message"));
521         mbedtls_ssl_send_alert_message(ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,
522                                        MBEDTLS_SSL_ALERT_MSG_DECODE_ERROR);
523         return MBEDTLS_ERR_SSL_BAD_HS_CLIENT_HELLO;
524     }
525 
526     ((void) buf);
527 
528     if (ssl->conf->trunc_hmac == MBEDTLS_SSL_TRUNC_HMAC_ENABLED) {
529         ssl->session_negotiate->trunc_hmac = MBEDTLS_SSL_TRUNC_HMAC_ENABLED;
530     }
531 
532     return 0;
533 }
534 #endif /* MBEDTLS_SSL_TRUNCATED_HMAC */
535 
536 #if defined(MBEDTLS_SSL_ENCRYPT_THEN_MAC)
537 MBEDTLS_CHECK_RETURN_CRITICAL
ssl_parse_encrypt_then_mac_ext(mbedtls_ssl_context * ssl,const unsigned char * buf,size_t len)538 static int ssl_parse_encrypt_then_mac_ext(mbedtls_ssl_context *ssl,
539                                           const unsigned char *buf,
540                                           size_t len)
541 {
542     if (len != 0) {
543         MBEDTLS_SSL_DEBUG_MSG(1, ("bad client hello message"));
544         mbedtls_ssl_send_alert_message(ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,
545                                        MBEDTLS_SSL_ALERT_MSG_DECODE_ERROR);
546         return MBEDTLS_ERR_SSL_BAD_HS_CLIENT_HELLO;
547     }
548 
549     ((void) buf);
550 
551     if (ssl->conf->encrypt_then_mac == MBEDTLS_SSL_ETM_ENABLED &&
552         ssl->minor_ver != MBEDTLS_SSL_MINOR_VERSION_0) {
553         ssl->session_negotiate->encrypt_then_mac = MBEDTLS_SSL_ETM_ENABLED;
554     }
555 
556     return 0;
557 }
558 #endif /* MBEDTLS_SSL_ENCRYPT_THEN_MAC */
559 
560 #if defined(MBEDTLS_SSL_EXTENDED_MASTER_SECRET)
561 MBEDTLS_CHECK_RETURN_CRITICAL
ssl_parse_extended_ms_ext(mbedtls_ssl_context * ssl,const unsigned char * buf,size_t len)562 static int ssl_parse_extended_ms_ext(mbedtls_ssl_context *ssl,
563                                      const unsigned char *buf,
564                                      size_t len)
565 {
566     if (len != 0) {
567         MBEDTLS_SSL_DEBUG_MSG(1, ("bad client hello message"));
568         mbedtls_ssl_send_alert_message(ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,
569                                        MBEDTLS_SSL_ALERT_MSG_DECODE_ERROR);
570         return MBEDTLS_ERR_SSL_BAD_HS_CLIENT_HELLO;
571     }
572 
573     ((void) buf);
574 
575     if (ssl->conf->extended_ms == MBEDTLS_SSL_EXTENDED_MS_ENABLED &&
576         ssl->minor_ver != MBEDTLS_SSL_MINOR_VERSION_0) {
577         ssl->handshake->extended_ms = MBEDTLS_SSL_EXTENDED_MS_ENABLED;
578     }
579 
580     return 0;
581 }
582 #endif /* MBEDTLS_SSL_EXTENDED_MASTER_SECRET */
583 
584 #if defined(MBEDTLS_SSL_SESSION_TICKETS)
585 MBEDTLS_CHECK_RETURN_CRITICAL
ssl_parse_session_ticket_ext(mbedtls_ssl_context * ssl,unsigned char * buf,size_t len)586 static int ssl_parse_session_ticket_ext(mbedtls_ssl_context *ssl,
587                                         unsigned char *buf,
588                                         size_t len)
589 {
590     int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
591     mbedtls_ssl_session session;
592 
593     mbedtls_ssl_session_init(&session);
594 
595     if (ssl->conf->f_ticket_parse == NULL ||
596         ssl->conf->f_ticket_write == NULL) {
597         return 0;
598     }
599 
600     /* Remember the client asked us to send a new ticket */
601     ssl->handshake->new_session_ticket = 1;
602 
603     MBEDTLS_SSL_DEBUG_MSG(3, ("ticket length: %" MBEDTLS_PRINTF_SIZET, len));
604 
605     if (len == 0) {
606         return 0;
607     }
608 
609 #if defined(MBEDTLS_SSL_RENEGOTIATION)
610     if (ssl->renego_status != MBEDTLS_SSL_INITIAL_HANDSHAKE) {
611         MBEDTLS_SSL_DEBUG_MSG(3, ("ticket rejected: renegotiating"));
612         return 0;
613     }
614 #endif /* MBEDTLS_SSL_RENEGOTIATION */
615 
616     /*
617      * Failures are ok: just ignore the ticket and proceed.
618      */
619     if ((ret = ssl->conf->f_ticket_parse(ssl->conf->p_ticket, &session,
620                                          buf, len)) != 0) {
621         mbedtls_ssl_session_free(&session);
622 
623         if (ret == MBEDTLS_ERR_SSL_INVALID_MAC) {
624             MBEDTLS_SSL_DEBUG_MSG(3, ("ticket is not authentic"));
625         } else if (ret == MBEDTLS_ERR_SSL_SESSION_TICKET_EXPIRED) {
626             MBEDTLS_SSL_DEBUG_MSG(3, ("ticket is expired"));
627         } else {
628             MBEDTLS_SSL_DEBUG_RET(1, "mbedtls_ssl_ticket_parse", ret);
629         }
630 
631         return 0;
632     }
633 
634     /*
635      * Keep the session ID sent by the client, since we MUST send it back to
636      * inform them we're accepting the ticket  (RFC 5077 section 3.4)
637      */
638     session.id_len = ssl->session_negotiate->id_len;
639     memcpy(&session.id, ssl->session_negotiate->id, session.id_len);
640 
641     mbedtls_ssl_session_free(ssl->session_negotiate);
642     memcpy(ssl->session_negotiate, &session, sizeof(mbedtls_ssl_session));
643 
644     /* Zeroize instead of free as we copied the content */
645     mbedtls_platform_zeroize(&session, sizeof(mbedtls_ssl_session));
646 
647     MBEDTLS_SSL_DEBUG_MSG(3, ("session successfully restored from ticket"));
648 
649     ssl->handshake->resume = 1;
650 
651     /* Don't send a new ticket after all, this one is OK */
652     ssl->handshake->new_session_ticket = 0;
653 
654     return 0;
655 }
656 #endif /* MBEDTLS_SSL_SESSION_TICKETS */
657 
658 #if defined(MBEDTLS_SSL_ALPN)
659 MBEDTLS_CHECK_RETURN_CRITICAL
ssl_parse_alpn_ext(mbedtls_ssl_context * ssl,const unsigned char * buf,size_t len)660 static int ssl_parse_alpn_ext(mbedtls_ssl_context *ssl,
661                               const unsigned char *buf, size_t len)
662 {
663     size_t list_len, cur_len, ours_len;
664     const unsigned char *theirs, *start, *end;
665     const char **ours;
666 
667     /* If ALPN not configured, just ignore the extension */
668     if (ssl->conf->alpn_list == NULL) {
669         return 0;
670     }
671 
672     /*
673      * opaque ProtocolName<1..2^8-1>;
674      *
675      * struct {
676      *     ProtocolName protocol_name_list<2..2^16-1>
677      * } ProtocolNameList;
678      */
679 
680     /* Min length is 2 (list_len) + 1 (name_len) + 1 (name) */
681     if (len < 4) {
682         mbedtls_ssl_send_alert_message(ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,
683                                        MBEDTLS_SSL_ALERT_MSG_DECODE_ERROR);
684         return MBEDTLS_ERR_SSL_BAD_HS_CLIENT_HELLO;
685     }
686 
687     list_len = (buf[0] << 8) | buf[1];
688     if (list_len != len - 2) {
689         mbedtls_ssl_send_alert_message(ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,
690                                        MBEDTLS_SSL_ALERT_MSG_DECODE_ERROR);
691         return MBEDTLS_ERR_SSL_BAD_HS_CLIENT_HELLO;
692     }
693 
694     /*
695      * Validate peer's list (lengths)
696      */
697     start = buf + 2;
698     end = buf + len;
699     for (theirs = start; theirs != end; theirs += cur_len) {
700         cur_len = *theirs++;
701 
702         /* Current identifier must fit in list */
703         if (cur_len > (size_t) (end - theirs)) {
704             mbedtls_ssl_send_alert_message(ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,
705                                            MBEDTLS_SSL_ALERT_MSG_DECODE_ERROR);
706             return MBEDTLS_ERR_SSL_BAD_HS_CLIENT_HELLO;
707         }
708 
709         /* Empty strings MUST NOT be included */
710         if (cur_len == 0) {
711             mbedtls_ssl_send_alert_message(ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,
712                                            MBEDTLS_SSL_ALERT_MSG_ILLEGAL_PARAMETER);
713             return MBEDTLS_ERR_SSL_BAD_HS_CLIENT_HELLO;
714         }
715     }
716 
717     /*
718      * Use our order of preference
719      */
720     for (ours = ssl->conf->alpn_list; *ours != NULL; ours++) {
721         ours_len = strlen(*ours);
722         for (theirs = start; theirs != end; theirs += cur_len) {
723             cur_len = *theirs++;
724 
725             if (cur_len == ours_len &&
726                 memcmp(theirs, *ours, cur_len) == 0) {
727                 ssl->alpn_chosen = *ours;
728                 return 0;
729             }
730         }
731     }
732 
733     /* If we get there, no match was found */
734     mbedtls_ssl_send_alert_message(ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,
735                                    MBEDTLS_SSL_ALERT_MSG_NO_APPLICATION_PROTOCOL);
736     return MBEDTLS_ERR_SSL_BAD_HS_CLIENT_HELLO;
737 }
738 #endif /* MBEDTLS_SSL_ALPN */
739 
740 #if defined(MBEDTLS_SSL_DTLS_SRTP)
741 MBEDTLS_CHECK_RETURN_CRITICAL
ssl_parse_use_srtp_ext(mbedtls_ssl_context * ssl,const unsigned char * buf,size_t len)742 static int ssl_parse_use_srtp_ext(mbedtls_ssl_context *ssl,
743                                   const unsigned char *buf,
744                                   size_t len)
745 {
746     mbedtls_ssl_srtp_profile client_protection = MBEDTLS_TLS_SRTP_UNSET;
747     size_t i, j;
748     size_t profile_length;
749     uint16_t mki_length;
750     /*! 2 bytes for profile length and 1 byte for mki len */
751     const size_t size_of_lengths = 3;
752 
753     /* If use_srtp is not configured, just ignore the extension */
754     if ((ssl->conf->transport != MBEDTLS_SSL_TRANSPORT_DATAGRAM) ||
755         (ssl->conf->dtls_srtp_profile_list == NULL) ||
756         (ssl->conf->dtls_srtp_profile_list_len == 0)) {
757         return 0;
758     }
759 
760     /* RFC5764 section 4.1.1
761      * uint8 SRTPProtectionProfile[2];
762      *
763      * struct {
764      *   SRTPProtectionProfiles SRTPProtectionProfiles;
765      *   opaque srtp_mki<0..255>;
766      * } UseSRTPData;
767 
768      * SRTPProtectionProfile SRTPProtectionProfiles<2..2^16-1>;
769      */
770 
771     /*
772      * Min length is 5: at least one protection profile(2 bytes)
773      *                  and length(2 bytes) + srtp_mki length(1 byte)
774      * Check here that we have at least 2 bytes of protection profiles length
775      * and one of srtp_mki length
776      */
777     if (len < size_of_lengths) {
778         mbedtls_ssl_send_alert_message(ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,
779                                        MBEDTLS_SSL_ALERT_MSG_HANDSHAKE_FAILURE);
780         return MBEDTLS_ERR_SSL_BAD_HS_CLIENT_HELLO;
781     }
782 
783     ssl->dtls_srtp_info.chosen_dtls_srtp_profile = MBEDTLS_TLS_SRTP_UNSET;
784 
785     /* first 2 bytes are protection profile length(in bytes) */
786     profile_length = (buf[0] << 8) | buf[1];
787     buf += 2;
788 
789     /* The profile length cannot be bigger than input buffer size - lengths fields */
790     if (profile_length > len - size_of_lengths ||
791         profile_length % 2 != 0) { /* profiles are 2 bytes long, so the length must be even */
792         mbedtls_ssl_send_alert_message(ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,
793                                        MBEDTLS_SSL_ALERT_MSG_HANDSHAKE_FAILURE);
794         return MBEDTLS_ERR_SSL_BAD_HS_CLIENT_HELLO;
795     }
796     /*
797      * parse the extension list values are defined in
798      * http://www.iana.org/assignments/srtp-protection/srtp-protection.xhtml
799      */
800     for (j = 0; j < profile_length; j += 2) {
801         uint16_t protection_profile_value = buf[j] << 8 | buf[j + 1];
802         client_protection = mbedtls_ssl_check_srtp_profile_value(protection_profile_value);
803 
804         if (client_protection != MBEDTLS_TLS_SRTP_UNSET) {
805             MBEDTLS_SSL_DEBUG_MSG(3, ("found srtp profile: %s",
806                                       mbedtls_ssl_get_srtp_profile_as_string(
807                                           client_protection)));
808         } else {
809             continue;
810         }
811         /* check if suggested profile is in our list */
812         for (i = 0; i < ssl->conf->dtls_srtp_profile_list_len; i++) {
813             if (client_protection == ssl->conf->dtls_srtp_profile_list[i]) {
814                 ssl->dtls_srtp_info.chosen_dtls_srtp_profile = ssl->conf->dtls_srtp_profile_list[i];
815                 MBEDTLS_SSL_DEBUG_MSG(3, ("selected srtp profile: %s",
816                                           mbedtls_ssl_get_srtp_profile_as_string(
817                                               client_protection)));
818                 break;
819             }
820         }
821         if (ssl->dtls_srtp_info.chosen_dtls_srtp_profile != MBEDTLS_TLS_SRTP_UNSET) {
822             break;
823         }
824     }
825     buf += profile_length; /* buf points to the mki length */
826     mki_length = *buf;
827     buf++;
828 
829     if (mki_length > MBEDTLS_TLS_SRTP_MAX_MKI_LENGTH ||
830         mki_length + profile_length + size_of_lengths != len) {
831         mbedtls_ssl_send_alert_message(ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,
832                                        MBEDTLS_SSL_ALERT_MSG_HANDSHAKE_FAILURE);
833         return MBEDTLS_ERR_SSL_BAD_HS_CLIENT_HELLO;
834     }
835 
836     /* Parse the mki only if present and mki is supported locally */
837     if (ssl->conf->dtls_srtp_mki_support == MBEDTLS_SSL_DTLS_SRTP_MKI_SUPPORTED &&
838         mki_length > 0) {
839         ssl->dtls_srtp_info.mki_len = mki_length;
840 
841         memcpy(ssl->dtls_srtp_info.mki_value, buf, mki_length);
842 
843         MBEDTLS_SSL_DEBUG_BUF(3, "using mki",  ssl->dtls_srtp_info.mki_value,
844                               ssl->dtls_srtp_info.mki_len);
845     }
846 
847     return 0;
848 }
849 #endif /* MBEDTLS_SSL_DTLS_SRTP */
850 
851 /*
852  * Auxiliary functions for ServerHello parsing and related actions
853  */
854 
855 #if defined(MBEDTLS_X509_CRT_PARSE_C)
856 /*
857  * Return 0 if the given key uses one of the acceptable curves, -1 otherwise
858  */
859 #if defined(MBEDTLS_ECDSA_C)
860 MBEDTLS_CHECK_RETURN_CRITICAL
ssl_check_key_curve(mbedtls_pk_context * pk,const mbedtls_ecp_curve_info ** curves)861 static int ssl_check_key_curve(mbedtls_pk_context *pk,
862                                const mbedtls_ecp_curve_info **curves)
863 {
864     const mbedtls_ecp_curve_info **crv = curves;
865     mbedtls_ecp_group_id grp_id = mbedtls_pk_ec(*pk)->grp.id;
866 
867     while (*crv != NULL) {
868         if ((*crv)->grp_id == grp_id) {
869             return 0;
870         }
871         crv++;
872     }
873 
874     return -1;
875 }
876 #endif /* MBEDTLS_ECDSA_C */
877 
878 /*
879  * Try picking a certificate for this ciphersuite,
880  * return 0 on success and -1 on failure.
881  */
882 MBEDTLS_CHECK_RETURN_CRITICAL
ssl_pick_cert(mbedtls_ssl_context * ssl,const mbedtls_ssl_ciphersuite_t * ciphersuite_info)883 static int ssl_pick_cert(mbedtls_ssl_context *ssl,
884                          const mbedtls_ssl_ciphersuite_t *ciphersuite_info)
885 {
886     mbedtls_ssl_key_cert *cur, *list, *fallback = NULL;
887     mbedtls_pk_type_t pk_alg =
888         mbedtls_ssl_get_ciphersuite_sig_pk_alg(ciphersuite_info);
889     uint32_t flags;
890 
891 #if defined(MBEDTLS_SSL_SERVER_NAME_INDICATION)
892     if (ssl->handshake->sni_key_cert != NULL) {
893         list = ssl->handshake->sni_key_cert;
894     } else
895 #endif
896     list = ssl->conf->key_cert;
897 
898     if (pk_alg == MBEDTLS_PK_NONE) {
899         return 0;
900     }
901 
902     MBEDTLS_SSL_DEBUG_MSG(3, ("ciphersuite requires certificate"));
903 
904     if (list == NULL) {
905         MBEDTLS_SSL_DEBUG_MSG(3, ("server has no certificate"));
906         return -1;
907     }
908 
909     for (cur = list; cur != NULL; cur = cur->next) {
910         flags = 0;
911         MBEDTLS_SSL_DEBUG_CRT(3, "candidate certificate chain, certificate",
912                               cur->cert);
913 
914         if (!mbedtls_pk_can_do(&cur->cert->pk, pk_alg)) {
915             MBEDTLS_SSL_DEBUG_MSG(3, ("certificate mismatch: key type"));
916             continue;
917         }
918 
919         /*
920          * This avoids sending the client a cert it'll reject based on
921          * keyUsage or other extensions.
922          *
923          * It also allows the user to provision different certificates for
924          * different uses based on keyUsage, eg if they want to avoid signing
925          * and decrypting with the same RSA key.
926          */
927         if (mbedtls_ssl_check_cert_usage(cur->cert, ciphersuite_info,
928                                          MBEDTLS_SSL_IS_SERVER, &flags) != 0) {
929             MBEDTLS_SSL_DEBUG_MSG(3, ("certificate mismatch: "
930                                       "(extended) key usage extension"));
931             continue;
932         }
933 
934 #if defined(MBEDTLS_ECDSA_C)
935         if (pk_alg == MBEDTLS_PK_ECDSA &&
936             ssl_check_key_curve(&cur->cert->pk, ssl->handshake->curves) != 0) {
937             MBEDTLS_SSL_DEBUG_MSG(3, ("certificate mismatch: elliptic curve"));
938             continue;
939         }
940 #endif
941 
942         /*
943          * Try to select a SHA-1 certificate for pre-1.2 clients, but still
944          * present them a SHA-higher cert rather than failing if it's the only
945          * one we got that satisfies the other conditions.
946          */
947         if (ssl->minor_ver < MBEDTLS_SSL_MINOR_VERSION_3 &&
948             cur->cert->sig_md != MBEDTLS_MD_SHA1) {
949             if (fallback == NULL) {
950                 fallback = cur;
951             }
952             {
953                 MBEDTLS_SSL_DEBUG_MSG(3, ("certificate not preferred: "
954                                           "sha-2 with pre-TLS 1.2 client"));
955                 continue;
956             }
957         }
958 
959         /* If we get there, we got a winner */
960         break;
961     }
962 
963     if (cur == NULL) {
964         cur = fallback;
965     }
966 
967     /* Do not update ssl->handshake->key_cert unless there is a match */
968     if (cur != NULL) {
969         ssl->handshake->key_cert = cur;
970         MBEDTLS_SSL_DEBUG_CRT(3, "selected certificate chain, certificate",
971                               ssl->handshake->key_cert->cert);
972         return 0;
973     }
974 
975     return -1;
976 }
977 #endif /* MBEDTLS_X509_CRT_PARSE_C */
978 
979 /*
980  * Check if a given ciphersuite is suitable for use with our config/keys/etc
981  * Sets ciphersuite_info only if the suite matches.
982  */
983 MBEDTLS_CHECK_RETURN_CRITICAL
ssl_ciphersuite_match(mbedtls_ssl_context * ssl,int suite_id,const mbedtls_ssl_ciphersuite_t ** ciphersuite_info)984 static int ssl_ciphersuite_match(mbedtls_ssl_context *ssl, int suite_id,
985                                  const mbedtls_ssl_ciphersuite_t **ciphersuite_info)
986 {
987     const mbedtls_ssl_ciphersuite_t *suite_info;
988 
989 #if defined(MBEDTLS_SSL_PROTO_TLS1_2) && \
990     defined(MBEDTLS_KEY_EXCHANGE_WITH_CERT_ENABLED)
991     mbedtls_pk_type_t sig_type;
992 #endif
993 
994     suite_info = mbedtls_ssl_ciphersuite_from_id(suite_id);
995     if (suite_info == NULL) {
996         MBEDTLS_SSL_DEBUG_MSG(1, ("should never happen"));
997         return MBEDTLS_ERR_SSL_INTERNAL_ERROR;
998     }
999 
1000     MBEDTLS_SSL_DEBUG_MSG(3, ("trying ciphersuite: %#04x (%s)",
1001                               (unsigned int) suite_id, suite_info->name));
1002 
1003     if (suite_info->min_minor_ver > ssl->minor_ver ||
1004         suite_info->max_minor_ver < ssl->minor_ver) {
1005         MBEDTLS_SSL_DEBUG_MSG(3, ("ciphersuite mismatch: version"));
1006         return 0;
1007     }
1008 
1009 #if defined(MBEDTLS_SSL_PROTO_DTLS)
1010     if (ssl->conf->transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM &&
1011         (suite_info->flags & MBEDTLS_CIPHERSUITE_NODTLS)) {
1012         return 0;
1013     }
1014 #endif
1015 
1016 #if defined(MBEDTLS_ARC4_C)
1017     if (ssl->conf->arc4_disabled == MBEDTLS_SSL_ARC4_DISABLED &&
1018         suite_info->cipher == MBEDTLS_CIPHER_ARC4_128) {
1019         MBEDTLS_SSL_DEBUG_MSG(3, ("ciphersuite mismatch: rc4"));
1020         return 0;
1021     }
1022 #endif
1023 
1024 #if defined(MBEDTLS_KEY_EXCHANGE_ECJPAKE_ENABLED)
1025     if (suite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_ECJPAKE &&
1026         (ssl->handshake->cli_exts & MBEDTLS_TLS_EXT_ECJPAKE_KKPP_OK) == 0) {
1027         MBEDTLS_SSL_DEBUG_MSG(3, ("ciphersuite mismatch: ecjpake "
1028                                   "not configured or ext missing"));
1029         return 0;
1030     }
1031 #endif
1032 
1033 
1034 #if defined(MBEDTLS_ECDH_C) || defined(MBEDTLS_ECDSA_C)
1035     if (mbedtls_ssl_ciphersuite_uses_ec(suite_info) &&
1036         (ssl->handshake->curves == NULL ||
1037          ssl->handshake->curves[0] == NULL)) {
1038         MBEDTLS_SSL_DEBUG_MSG(3, ("ciphersuite mismatch: "
1039                                   "no common elliptic curve"));
1040         return 0;
1041     }
1042 #endif
1043 
1044 #if defined(MBEDTLS_KEY_EXCHANGE_SOME_PSK_ENABLED)
1045     /* If the ciphersuite requires a pre-shared key and we don't
1046      * have one, skip it now rather than failing later */
1047     if (mbedtls_ssl_ciphersuite_uses_psk(suite_info) &&
1048         ssl_conf_has_psk_or_cb(ssl->conf) == 0) {
1049         MBEDTLS_SSL_DEBUG_MSG(3, ("ciphersuite mismatch: no pre-shared key"));
1050         return 0;
1051     }
1052 #endif
1053 
1054 #if defined(MBEDTLS_SSL_PROTO_TLS1_2) && \
1055     defined(MBEDTLS_KEY_EXCHANGE_WITH_CERT_ENABLED)
1056     /* If the ciphersuite requires signing, check whether
1057      * a suitable hash algorithm is present. */
1058     if (ssl->minor_ver == MBEDTLS_SSL_MINOR_VERSION_3) {
1059         sig_type = mbedtls_ssl_get_ciphersuite_sig_alg(suite_info);
1060         if (sig_type != MBEDTLS_PK_NONE &&
1061             mbedtls_ssl_sig_hash_set_find(&ssl->handshake->hash_algs,
1062                                           sig_type) == MBEDTLS_MD_NONE) {
1063             MBEDTLS_SSL_DEBUG_MSG(3, ("ciphersuite mismatch: no suitable hash algorithm "
1064                                       "for signature algorithm %u", (unsigned) sig_type));
1065             return 0;
1066         }
1067     }
1068 
1069 #endif /* MBEDTLS_SSL_PROTO_TLS1_2 &&
1070           MBEDTLS_KEY_EXCHANGE_WITH_CERT_ENABLED */
1071 
1072 #if defined(MBEDTLS_X509_CRT_PARSE_C)
1073     /*
1074      * Final check: if ciphersuite requires us to have a
1075      * certificate/key of a particular type:
1076      * - select the appropriate certificate if we have one, or
1077      * - try the next ciphersuite if we don't
1078      * This must be done last since we modify the key_cert list.
1079      */
1080     if (ssl_pick_cert(ssl, suite_info) != 0) {
1081         MBEDTLS_SSL_DEBUG_MSG(3, ("ciphersuite mismatch: "
1082                                   "no suitable certificate"));
1083         return 0;
1084     }
1085 #endif
1086 
1087     *ciphersuite_info = suite_info;
1088     return 0;
1089 }
1090 
1091 #if defined(MBEDTLS_SSL_SRV_SUPPORT_SSLV2_CLIENT_HELLO)
1092 MBEDTLS_CHECK_RETURN_CRITICAL
ssl_parse_client_hello_v2(mbedtls_ssl_context * ssl)1093 static int ssl_parse_client_hello_v2(mbedtls_ssl_context *ssl)
1094 {
1095     int ret, got_common_suite;
1096     unsigned int i, j;
1097     size_t n;
1098     unsigned int ciph_len, sess_len, chal_len;
1099     unsigned char *buf, *p;
1100     const int *ciphersuites;
1101     const mbedtls_ssl_ciphersuite_t *ciphersuite_info;
1102 
1103     MBEDTLS_SSL_DEBUG_MSG(2, ("=> parse client hello v2"));
1104 
1105 #if defined(MBEDTLS_SSL_RENEGOTIATION)
1106     if (ssl->renego_status != MBEDTLS_SSL_INITIAL_HANDSHAKE) {
1107         MBEDTLS_SSL_DEBUG_MSG(1, ("client hello v2 illegal for renegotiation"));
1108         mbedtls_ssl_send_alert_message(ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,
1109                                        MBEDTLS_SSL_ALERT_MSG_HANDSHAKE_FAILURE);
1110         return MBEDTLS_ERR_SSL_BAD_HS_CLIENT_HELLO;
1111     }
1112 #endif /* MBEDTLS_SSL_RENEGOTIATION */
1113 
1114     buf = ssl->in_hdr;
1115 
1116     MBEDTLS_SSL_DEBUG_BUF(4, "record header", buf, 5);
1117 
1118     MBEDTLS_SSL_DEBUG_MSG(3, ("client hello v2, message type: %d",
1119                               buf[2]));
1120     MBEDTLS_SSL_DEBUG_MSG(3, ("client hello v2, message len.: %d",
1121                               ((buf[0] & 0x7F) << 8) | buf[1]));
1122     MBEDTLS_SSL_DEBUG_MSG(3, ("client hello v2, max. version: [%d:%d]",
1123                               buf[3], buf[4]));
1124 
1125     /*
1126      * SSLv2 Client Hello
1127      *
1128      * Record layer:
1129      *     0  .   1   message length
1130      *
1131      * SSL layer:
1132      *     2  .   2   message type
1133      *     3  .   4   protocol version
1134      */
1135     if (buf[2] != MBEDTLS_SSL_HS_CLIENT_HELLO ||
1136         buf[3] != MBEDTLS_SSL_MAJOR_VERSION_3) {
1137         MBEDTLS_SSL_DEBUG_MSG(1, ("bad client hello message"));
1138         return MBEDTLS_ERR_SSL_BAD_HS_CLIENT_HELLO;
1139     }
1140 
1141     n = ((buf[0] << 8) | buf[1]) & 0x7FFF;
1142 
1143     if (n < 17 || n > 512) {
1144         MBEDTLS_SSL_DEBUG_MSG(1, ("bad client hello message"));
1145         return MBEDTLS_ERR_SSL_BAD_HS_CLIENT_HELLO;
1146     }
1147 
1148     ssl->major_ver = MBEDTLS_SSL_MAJOR_VERSION_3;
1149     ssl->minor_ver = (buf[4] <= ssl->conf->max_minor_ver)
1150                      ? buf[4]  : ssl->conf->max_minor_ver;
1151 
1152     if (ssl->minor_ver < ssl->conf->min_minor_ver) {
1153         MBEDTLS_SSL_DEBUG_MSG(1, ("client only supports ssl smaller than minimum"
1154                                   " [%d:%d] < [%d:%d]",
1155                                   ssl->major_ver, ssl->minor_ver,
1156                                   ssl->conf->min_major_ver, ssl->conf->min_minor_ver));
1157 
1158         mbedtls_ssl_send_alert_message(ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,
1159                                        MBEDTLS_SSL_ALERT_MSG_PROTOCOL_VERSION);
1160         return MBEDTLS_ERR_SSL_BAD_HS_PROTOCOL_VERSION;
1161     }
1162 
1163     ssl->handshake->max_major_ver = buf[3];
1164     ssl->handshake->max_minor_ver = buf[4];
1165 
1166     if ((ret = mbedtls_ssl_fetch_input(ssl, 2 + n)) != 0) {
1167         MBEDTLS_SSL_DEBUG_RET(1, "mbedtls_ssl_fetch_input", ret);
1168         return ret;
1169     }
1170 
1171     ssl->handshake->update_checksum(ssl, buf + 2, n);
1172 
1173     buf = ssl->in_msg;
1174     n = ssl->in_left - 5;
1175 
1176     /*
1177      *    0  .   1   ciphersuitelist length
1178      *    2  .   3   session id length
1179      *    4  .   5   challenge length
1180      *    6  .  ..   ciphersuitelist
1181      *   ..  .  ..   session id
1182      *   ..  .  ..   challenge
1183      */
1184     MBEDTLS_SSL_DEBUG_BUF(4, "record contents", buf, n);
1185 
1186     ciph_len = (buf[0] << 8) | buf[1];
1187     sess_len = (buf[2] << 8) | buf[3];
1188     chal_len = (buf[4] << 8) | buf[5];
1189 
1190     MBEDTLS_SSL_DEBUG_MSG(3, ("ciph_len: %u, sess_len: %u, chal_len: %u",
1191                               ciph_len, sess_len, chal_len));
1192 
1193     /*
1194      * Make sure each parameter length is valid
1195      */
1196     if (ciph_len < 3 || (ciph_len % 3) != 0) {
1197         MBEDTLS_SSL_DEBUG_MSG(1, ("bad client hello message"));
1198         return MBEDTLS_ERR_SSL_BAD_HS_CLIENT_HELLO;
1199     }
1200 
1201     if (sess_len > 32) {
1202         MBEDTLS_SSL_DEBUG_MSG(1, ("bad client hello message"));
1203         return MBEDTLS_ERR_SSL_BAD_HS_CLIENT_HELLO;
1204     }
1205 
1206     if (chal_len < 8 || chal_len > 32) {
1207         MBEDTLS_SSL_DEBUG_MSG(1, ("bad client hello message"));
1208         return MBEDTLS_ERR_SSL_BAD_HS_CLIENT_HELLO;
1209     }
1210 
1211     if (n != 6 + ciph_len + sess_len + chal_len) {
1212         MBEDTLS_SSL_DEBUG_MSG(1, ("bad client hello message"));
1213         return MBEDTLS_ERR_SSL_BAD_HS_CLIENT_HELLO;
1214     }
1215 
1216     MBEDTLS_SSL_DEBUG_BUF(3, "client hello, ciphersuitelist",
1217                           buf + 6, ciph_len);
1218     MBEDTLS_SSL_DEBUG_BUF(3, "client hello, session id",
1219                           buf + 6 + ciph_len, sess_len);
1220     MBEDTLS_SSL_DEBUG_BUF(3, "client hello, challenge",
1221                           buf + 6 + ciph_len + sess_len, chal_len);
1222 
1223     p = buf + 6 + ciph_len;
1224     ssl->session_negotiate->id_len = sess_len;
1225     memset(ssl->session_negotiate->id, 0,
1226            sizeof(ssl->session_negotiate->id));
1227     memcpy(ssl->session_negotiate->id, p, ssl->session_negotiate->id_len);
1228 
1229     p += sess_len;
1230     memset(ssl->handshake->randbytes, 0, 64);
1231     memcpy(ssl->handshake->randbytes + 32 - chal_len, p, chal_len);
1232 
1233     /*
1234      * Check for TLS_EMPTY_RENEGOTIATION_INFO_SCSV
1235      */
1236     for (i = 0, p = buf + 6; i < ciph_len; i += 3, p += 3) {
1237         if (p[0] == 0 && p[1] == 0 && p[2] == MBEDTLS_SSL_EMPTY_RENEGOTIATION_INFO) {
1238             MBEDTLS_SSL_DEBUG_MSG(3, ("received TLS_EMPTY_RENEGOTIATION_INFO "));
1239 #if defined(MBEDTLS_SSL_RENEGOTIATION)
1240             if (ssl->renego_status == MBEDTLS_SSL_RENEGOTIATION_IN_PROGRESS) {
1241                 MBEDTLS_SSL_DEBUG_MSG(1, ("received RENEGOTIATION SCSV "
1242                                           "during renegotiation"));
1243 
1244                 mbedtls_ssl_send_alert_message(ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,
1245                                                MBEDTLS_SSL_ALERT_MSG_HANDSHAKE_FAILURE);
1246                 return MBEDTLS_ERR_SSL_BAD_HS_CLIENT_HELLO;
1247             }
1248 #endif /* MBEDTLS_SSL_RENEGOTIATION */
1249             ssl->secure_renegotiation = MBEDTLS_SSL_SECURE_RENEGOTIATION;
1250             break;
1251         }
1252     }
1253 
1254 #if defined(MBEDTLS_SSL_FALLBACK_SCSV)
1255     for (i = 0, p = buf + 6; i < ciph_len; i += 3, p += 3) {
1256         if (p[0] == 0 &&
1257             MBEDTLS_GET_UINT16_BE(p, 1) != MBEDTLS_SSL_FALLBACK_SCSV_VALUE) {
1258             MBEDTLS_SSL_DEBUG_MSG(3, ("received FALLBACK_SCSV"));
1259 
1260             if (ssl->minor_ver < ssl->conf->max_minor_ver) {
1261                 MBEDTLS_SSL_DEBUG_MSG(1, ("inapropriate fallback"));
1262 
1263                 mbedtls_ssl_send_alert_message(ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,
1264                                                MBEDTLS_SSL_ALERT_MSG_INAPROPRIATE_FALLBACK);
1265 
1266                 return MBEDTLS_ERR_SSL_BAD_HS_CLIENT_HELLO;
1267             }
1268 
1269             break;
1270         }
1271     }
1272 #endif /* MBEDTLS_SSL_FALLBACK_SCSV */
1273 
1274     got_common_suite = 0;
1275     ciphersuites = ssl->conf->ciphersuite_list[ssl->minor_ver];
1276     ciphersuite_info = NULL;
1277 #if defined(MBEDTLS_SSL_SRV_RESPECT_CLIENT_PREFERENCE)
1278     for (j = 0, p = buf + 6; j < ciph_len; j += 3, p += 3) {
1279         for (i = 0; ciphersuites[i] != 0; i++) {
1280             if (p[0] != 0 ||
1281                 MBEDTLS_GET_UINT16_BE(p, 1) != ciphersuites[i]) {
1282                 continue;
1283             }
1284 
1285             got_common_suite = 1;
1286 
1287             if ((ret = ssl_ciphersuite_match(ssl, ciphersuites[i],
1288                                              &ciphersuite_info)) != 0) {
1289                 return ret;
1290             }
1291 
1292             if (ciphersuite_info != NULL) {
1293                 goto have_ciphersuite_v2;
1294             }
1295         }
1296     }
1297 #else
1298     for (i = 0; ciphersuites[i] != 0; i++) {
1299         for (j = 0, p = buf + 6; j < ciph_len; j += 3, p += 3) {
1300             if (p[0] != 0 ||
1301                 MBEDTLS_GET_UINT16_BE(p, 1) != ciphersuites[i]) {
1302                 continue;
1303             }
1304 
1305             got_common_suite = 1;
1306 
1307             if ((ret = ssl_ciphersuite_match(ssl, ciphersuites[i],
1308                                              &ciphersuite_info)) != 0) {
1309                 return ret;
1310             }
1311 
1312             if (ciphersuite_info != NULL) {
1313                 goto have_ciphersuite_v2;
1314             }
1315         }
1316     }
1317 #endif
1318 
1319     if (got_common_suite) {
1320         MBEDTLS_SSL_DEBUG_MSG(1, ("got ciphersuites in common, "
1321                                   "but none of them usable"));
1322         return MBEDTLS_ERR_SSL_NO_USABLE_CIPHERSUITE;
1323     } else {
1324         MBEDTLS_SSL_DEBUG_MSG(1, ("got no ciphersuites in common"));
1325         return MBEDTLS_ERR_SSL_NO_CIPHER_CHOSEN;
1326     }
1327 
1328 have_ciphersuite_v2:
1329     MBEDTLS_SSL_DEBUG_MSG(2, ("selected ciphersuite: %s", ciphersuite_info->name));
1330 
1331     ssl->session_negotiate->ciphersuite = ciphersuites[i];
1332     ssl->handshake->ciphersuite_info = ciphersuite_info;
1333 
1334     /*
1335      * SSLv2 Client Hello relevant renegotiation security checks
1336      */
1337     if (ssl->secure_renegotiation == MBEDTLS_SSL_LEGACY_RENEGOTIATION &&
1338         ssl->conf->allow_legacy_renegotiation == MBEDTLS_SSL_LEGACY_BREAK_HANDSHAKE) {
1339         MBEDTLS_SSL_DEBUG_MSG(1, ("legacy renegotiation, breaking off handshake"));
1340         mbedtls_ssl_send_alert_message(ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,
1341                                        MBEDTLS_SSL_ALERT_MSG_HANDSHAKE_FAILURE);
1342         return MBEDTLS_ERR_SSL_BAD_HS_CLIENT_HELLO;
1343     }
1344 
1345     ssl->in_left = 0;
1346     ssl->state++;
1347 
1348     MBEDTLS_SSL_DEBUG_MSG(2, ("<= parse client hello v2"));
1349 
1350     return 0;
1351 }
1352 #endif /* MBEDTLS_SSL_SRV_SUPPORT_SSLV2_CLIENT_HELLO */
1353 
1354 /* This function doesn't alert on errors that happen early during
1355    ClientHello parsing because they might indicate that the client is
1356    not talking SSL/TLS at all and would not understand our alert. */
1357 MBEDTLS_CHECK_RETURN_CRITICAL
ssl_parse_client_hello(mbedtls_ssl_context * ssl)1358 static int ssl_parse_client_hello(mbedtls_ssl_context *ssl)
1359 {
1360     int ret, got_common_suite;
1361     size_t i, j;
1362     size_t ciph_offset, comp_offset, ext_offset;
1363     size_t msg_len, ciph_len, sess_len, comp_len, ext_len;
1364 #if defined(MBEDTLS_SSL_PROTO_DTLS)
1365     size_t cookie_offset, cookie_len;
1366 #endif
1367     unsigned char *buf, *p, *ext;
1368 #if defined(MBEDTLS_SSL_RENEGOTIATION)
1369     int renegotiation_info_seen = 0;
1370 #endif
1371     int handshake_failure = 0;
1372     const int *ciphersuites;
1373     const mbedtls_ssl_ciphersuite_t *ciphersuite_info;
1374     int major, minor;
1375 
1376     /* If there is no signature-algorithm extension present,
1377      * we need to fall back to the default values for allowed
1378      * signature-hash pairs. */
1379 #if defined(MBEDTLS_SSL_PROTO_TLS1_2) && \
1380     defined(MBEDTLS_KEY_EXCHANGE_WITH_CERT_ENABLED)
1381     int sig_hash_alg_ext_present = 0;
1382 #endif /* MBEDTLS_SSL_PROTO_TLS1_2 &&
1383           MBEDTLS_KEY_EXCHANGE_WITH_CERT_ENABLED */
1384 
1385     MBEDTLS_SSL_DEBUG_MSG(2, ("=> parse client hello"));
1386 
1387     int renegotiating = 0;
1388 #if defined(MBEDTLS_SSL_DTLS_ANTI_REPLAY)
1389 read_record_header:
1390 #endif
1391     /*
1392      * If renegotiating, then the input was read with mbedtls_ssl_read_record(),
1393      * otherwise read it ourselves manually in order to support SSLv2
1394      * ClientHello, which doesn't use the same record layer format.
1395      */
1396 #if defined(MBEDTLS_SSL_RENEGOTIATION)
1397     if (ssl->renego_status != MBEDTLS_SSL_INITIAL_HANDSHAKE) {
1398         renegotiating = 1;
1399     }
1400 #endif
1401     if (!renegotiating) {
1402         if ((ret = mbedtls_ssl_fetch_input(ssl, 5)) != 0) {
1403             /* No alert on a read error. */
1404             MBEDTLS_SSL_DEBUG_RET(1, "mbedtls_ssl_fetch_input", ret);
1405             return ret;
1406         }
1407     }
1408 
1409     buf = ssl->in_hdr;
1410 
1411 #if defined(MBEDTLS_SSL_SRV_SUPPORT_SSLV2_CLIENT_HELLO)
1412     int is_dtls = 0;
1413 #if defined(MBEDTLS_SSL_PROTO_DTLS)
1414     if (ssl->conf->transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM) {
1415         is_dtls = 1;
1416     }
1417 #endif
1418     if (!is_dtls) {
1419         if ((buf[0] & 0x80) != 0) {
1420             return ssl_parse_client_hello_v2(ssl);
1421         }
1422     }
1423 #endif
1424 
1425     MBEDTLS_SSL_DEBUG_BUF(4, "record header", buf, mbedtls_ssl_in_hdr_len(ssl));
1426 
1427     /*
1428      * SSLv3/TLS Client Hello
1429      *
1430      * Record layer:
1431      *     0  .   0   message type
1432      *     1  .   2   protocol version
1433      *     3  .   11  DTLS: epoch + record sequence number
1434      *     3  .   4   message length
1435      */
1436     MBEDTLS_SSL_DEBUG_MSG(3, ("client hello v3, message type: %d",
1437                               buf[0]));
1438 
1439     if (buf[0] != MBEDTLS_SSL_MSG_HANDSHAKE) {
1440         MBEDTLS_SSL_DEBUG_MSG(1, ("bad client hello message"));
1441         return MBEDTLS_ERR_SSL_BAD_HS_CLIENT_HELLO;
1442     }
1443 
1444     MBEDTLS_SSL_DEBUG_MSG(3, ("client hello v3, message len.: %d",
1445                               (ssl->in_len[0] << 8) | ssl->in_len[1]));
1446 
1447     MBEDTLS_SSL_DEBUG_MSG(3, ("client hello v3, protocol version: [%d:%d]",
1448                               buf[1], buf[2]));
1449 
1450     mbedtls_ssl_read_version(&major, &minor, ssl->conf->transport, buf + 1);
1451 
1452     /* According to RFC 5246 Appendix E.1, the version here is typically
1453      * "{03,00}, the lowest version number supported by the client, [or] the
1454      * value of ClientHello.client_version", so the only meaningful check here
1455      * is the major version shouldn't be less than 3 */
1456     if (major < MBEDTLS_SSL_MAJOR_VERSION_3) {
1457         MBEDTLS_SSL_DEBUG_MSG(1, ("bad client hello message"));
1458         return MBEDTLS_ERR_SSL_BAD_HS_CLIENT_HELLO;
1459     }
1460 
1461     /* For DTLS if this is the initial handshake, remember the client sequence
1462      * number to use it in our next message (RFC 6347 4.2.1) */
1463 #if defined(MBEDTLS_SSL_PROTO_DTLS)
1464     if (ssl->conf->transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM
1465 #if defined(MBEDTLS_SSL_RENEGOTIATION)
1466         && ssl->renego_status == MBEDTLS_SSL_INITIAL_HANDSHAKE
1467 #endif
1468         ) {
1469         /* Epoch should be 0 for initial handshakes */
1470         if (ssl->in_ctr[0] != 0 || ssl->in_ctr[1] != 0) {
1471             MBEDTLS_SSL_DEBUG_MSG(1, ("bad client hello message"));
1472             return MBEDTLS_ERR_SSL_BAD_HS_CLIENT_HELLO;
1473         }
1474 
1475         memcpy(ssl->cur_out_ctr + 2, ssl->in_ctr + 2, 6);
1476 
1477 #if defined(MBEDTLS_SSL_DTLS_ANTI_REPLAY)
1478         if (mbedtls_ssl_dtls_replay_check(ssl) != 0) {
1479             MBEDTLS_SSL_DEBUG_MSG(1, ("replayed record, discarding"));
1480             ssl->next_record_offset = 0;
1481             ssl->in_left = 0;
1482             goto read_record_header;
1483         }
1484 
1485         /* No MAC to check yet, so we can update right now */
1486         mbedtls_ssl_dtls_replay_update(ssl);
1487 #endif
1488     }
1489 #endif /* MBEDTLS_SSL_PROTO_DTLS */
1490 
1491     msg_len = (ssl->in_len[0] << 8) | ssl->in_len[1];
1492 
1493 #if defined(MBEDTLS_SSL_RENEGOTIATION)
1494     if (ssl->renego_status != MBEDTLS_SSL_INITIAL_HANDSHAKE) {
1495         /* Set by mbedtls_ssl_read_record() */
1496         msg_len = ssl->in_hslen;
1497     } else
1498 #endif
1499     {
1500         if (msg_len > MBEDTLS_SSL_IN_CONTENT_LEN) {
1501             MBEDTLS_SSL_DEBUG_MSG(1, ("bad client hello message"));
1502             return MBEDTLS_ERR_SSL_BAD_HS_CLIENT_HELLO;
1503         }
1504 
1505         if ((ret = mbedtls_ssl_fetch_input(ssl,
1506                                            mbedtls_ssl_in_hdr_len(ssl) + msg_len)) != 0) {
1507             MBEDTLS_SSL_DEBUG_RET(1, "mbedtls_ssl_fetch_input", ret);
1508             return ret;
1509         }
1510 
1511         /* Done reading this record, get ready for the next one */
1512 #if defined(MBEDTLS_SSL_PROTO_DTLS)
1513         if (ssl->conf->transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM) {
1514             ssl->next_record_offset = msg_len + mbedtls_ssl_in_hdr_len(ssl);
1515         } else
1516 #endif
1517         ssl->in_left = 0;
1518     }
1519 
1520     buf = ssl->in_msg;
1521 
1522     MBEDTLS_SSL_DEBUG_BUF(4, "record contents", buf, msg_len);
1523 
1524     ssl->handshake->update_checksum(ssl, buf, msg_len);
1525 
1526     /*
1527      * Handshake layer:
1528      *     0  .   0   handshake type
1529      *     1  .   3   handshake length
1530      *     4  .   5   DTLS only: message sequence number
1531      *     6  .   8   DTLS only: fragment offset
1532      *     9  .  11   DTLS only: fragment length
1533      */
1534     if (msg_len < mbedtls_ssl_hs_hdr_len(ssl)) {
1535         MBEDTLS_SSL_DEBUG_MSG(1, ("bad client hello message"));
1536         return MBEDTLS_ERR_SSL_BAD_HS_CLIENT_HELLO;
1537     }
1538 
1539     MBEDTLS_SSL_DEBUG_MSG(3, ("client hello v3, handshake type: %d", buf[0]));
1540 
1541     if (buf[0] != MBEDTLS_SSL_HS_CLIENT_HELLO) {
1542         MBEDTLS_SSL_DEBUG_MSG(1, ("bad client hello message"));
1543         return MBEDTLS_ERR_SSL_BAD_HS_CLIENT_HELLO;
1544     }
1545 
1546     MBEDTLS_SSL_DEBUG_MSG(3, ("client hello v3, handshake len.: %d",
1547                               (buf[1] << 16) | (buf[2] << 8) | buf[3]));
1548 
1549     if (buf[1] != 0) {
1550         MBEDTLS_SSL_DEBUG_MSG(1, ("bad client hello message: %u != 0",
1551                                   (unsigned) buf[1]));
1552         return MBEDTLS_ERR_SSL_BAD_HS_CLIENT_HELLO;
1553     }
1554     /* We don't support fragmentation of ClientHello (yet?) */
1555     if (msg_len != mbedtls_ssl_hs_hdr_len(ssl) + ((buf[2] << 8) | buf[3])) {
1556         MBEDTLS_SSL_DEBUG_MSG(1, ("bad client hello message: %u != %u + %u",
1557                                   (unsigned) msg_len,
1558                                   (unsigned) mbedtls_ssl_hs_hdr_len(ssl),
1559                                   (unsigned) (buf[2] << 8) | buf[3]));
1560         return MBEDTLS_ERR_SSL_BAD_HS_CLIENT_HELLO;
1561     }
1562 
1563 #if defined(MBEDTLS_SSL_PROTO_DTLS)
1564     if (ssl->conf->transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM) {
1565         /*
1566          * Copy the client's handshake message_seq on initial handshakes,
1567          * check sequence number on renego.
1568          */
1569 #if defined(MBEDTLS_SSL_RENEGOTIATION)
1570         if (ssl->renego_status == MBEDTLS_SSL_RENEGOTIATION_IN_PROGRESS) {
1571             /* This couldn't be done in ssl_prepare_handshake_record() */
1572             unsigned int cli_msg_seq = (ssl->in_msg[4] << 8) |
1573                                        ssl->in_msg[5];
1574 
1575             if (cli_msg_seq != ssl->handshake->in_msg_seq) {
1576                 MBEDTLS_SSL_DEBUG_MSG(1, ("bad client hello message_seq: "
1577                                           "%u (expected %u)", cli_msg_seq,
1578                                           ssl->handshake->in_msg_seq));
1579                 return MBEDTLS_ERR_SSL_BAD_HS_CLIENT_HELLO;
1580             }
1581 
1582             ssl->handshake->in_msg_seq++;
1583         } else
1584 #endif
1585         {
1586             unsigned int cli_msg_seq = (ssl->in_msg[4] << 8) |
1587                                        ssl->in_msg[5];
1588             ssl->handshake->out_msg_seq = cli_msg_seq;
1589             ssl->handshake->in_msg_seq  = cli_msg_seq + 1;
1590         }
1591 
1592         /*
1593          * For now we don't support fragmentation, so make sure
1594          * fragment_offset == 0 and fragment_length == length
1595          */
1596         MBEDTLS_SSL_DEBUG_MSG(
1597             4, ("fragment_offset=%u fragment_length=%u length=%u",
1598                 (unsigned) (ssl->in_msg[6] << 16 | ssl->in_msg[7] << 8 | ssl->in_msg[8]),
1599                 (unsigned) (ssl->in_msg[9] << 16 | ssl->in_msg[10] << 8 | ssl->in_msg[11]),
1600                 (unsigned) (ssl->in_msg[1] << 16 | ssl->in_msg[2] << 8 | ssl->in_msg[3])));
1601         if (ssl->in_msg[6] != 0 || ssl->in_msg[7] != 0 || ssl->in_msg[8] != 0 ||
1602             memcmp(ssl->in_msg + 1, ssl->in_msg + 9, 3) != 0) {
1603             MBEDTLS_SSL_DEBUG_MSG(1, ("ClientHello fragmentation not supported"));
1604             return MBEDTLS_ERR_SSL_FEATURE_UNAVAILABLE;
1605         }
1606     }
1607 #endif /* MBEDTLS_SSL_PROTO_DTLS */
1608 
1609     buf += mbedtls_ssl_hs_hdr_len(ssl);
1610     msg_len -= mbedtls_ssl_hs_hdr_len(ssl);
1611 
1612     /*
1613      * ClientHello layer:
1614      *     0  .   1   protocol version
1615      *     2  .  33   random bytes (starting with 4 bytes of Unix time)
1616      *    34  .  35   session id length (1 byte)
1617      *    35  . 34+x  session id
1618      *   35+x . 35+x  DTLS only: cookie length (1 byte)
1619      *   36+x .  ..   DTLS only: cookie
1620      *    ..  .  ..   ciphersuite list length (2 bytes)
1621      *    ..  .  ..   ciphersuite list
1622      *    ..  .  ..   compression alg. list length (1 byte)
1623      *    ..  .  ..   compression alg. list
1624      *    ..  .  ..   extensions length (2 bytes, optional)
1625      *    ..  .  ..   extensions (optional)
1626      */
1627 
1628     /*
1629      * Minimal length (with everything empty and extensions omitted) is
1630      * 2 + 32 + 1 + 2 + 1 = 38 bytes. Check that first, so that we can
1631      * read at least up to session id length without worrying.
1632      */
1633     if (msg_len < 38) {
1634         MBEDTLS_SSL_DEBUG_MSG(1, ("bad client hello message"));
1635         return MBEDTLS_ERR_SSL_BAD_HS_CLIENT_HELLO;
1636     }
1637 
1638     /*
1639      * Check and save the protocol version
1640      */
1641     MBEDTLS_SSL_DEBUG_BUF(3, "client hello, version", buf, 2);
1642 
1643     mbedtls_ssl_read_version(&ssl->major_ver, &ssl->minor_ver,
1644                              ssl->conf->transport, buf);
1645 
1646     ssl->handshake->max_major_ver = ssl->major_ver;
1647     ssl->handshake->max_minor_ver = ssl->minor_ver;
1648 
1649     if (ssl->major_ver < ssl->conf->min_major_ver ||
1650         ssl->minor_ver < ssl->conf->min_minor_ver) {
1651         MBEDTLS_SSL_DEBUG_MSG(1, ("client only supports ssl smaller than minimum"
1652                                   " [%d:%d] < [%d:%d]",
1653                                   ssl->major_ver, ssl->minor_ver,
1654                                   ssl->conf->min_major_ver, ssl->conf->min_minor_ver));
1655         mbedtls_ssl_send_alert_message(ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,
1656                                        MBEDTLS_SSL_ALERT_MSG_PROTOCOL_VERSION);
1657         return MBEDTLS_ERR_SSL_BAD_HS_PROTOCOL_VERSION;
1658     }
1659 
1660     if (ssl->major_ver > ssl->conf->max_major_ver) {
1661         ssl->major_ver = ssl->conf->max_major_ver;
1662         ssl->minor_ver = ssl->conf->max_minor_ver;
1663     } else if (ssl->minor_ver > ssl->conf->max_minor_ver) {
1664         ssl->minor_ver = ssl->conf->max_minor_ver;
1665     }
1666 
1667     /*
1668      * Save client random (inc. Unix time)
1669      */
1670     MBEDTLS_SSL_DEBUG_BUF(3, "client hello, random bytes", buf + 2, 32);
1671 
1672     memcpy(ssl->handshake->randbytes, buf + 2, 32);
1673 
1674     /*
1675      * Check the session ID length and save session ID
1676      */
1677     sess_len = buf[34];
1678 
1679     if (sess_len > sizeof(ssl->session_negotiate->id) ||
1680         sess_len + 34 + 2 > msg_len) { /* 2 for cipherlist length field */
1681         MBEDTLS_SSL_DEBUG_MSG(1, ("bad client hello message"));
1682         mbedtls_ssl_send_alert_message(ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,
1683                                        MBEDTLS_SSL_ALERT_MSG_DECODE_ERROR);
1684         return MBEDTLS_ERR_SSL_BAD_HS_CLIENT_HELLO;
1685     }
1686 
1687     MBEDTLS_SSL_DEBUG_BUF(3, "client hello, session id", buf + 35, sess_len);
1688 
1689     ssl->session_negotiate->id_len = sess_len;
1690     memset(ssl->session_negotiate->id, 0,
1691            sizeof(ssl->session_negotiate->id));
1692     memcpy(ssl->session_negotiate->id, buf + 35,
1693            ssl->session_negotiate->id_len);
1694 
1695     /*
1696      * Check the cookie length and content
1697      */
1698 #if defined(MBEDTLS_SSL_PROTO_DTLS)
1699     if (ssl->conf->transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM) {
1700         cookie_offset = 35 + sess_len;
1701         cookie_len = buf[cookie_offset];
1702 
1703         if (cookie_offset + 1 + cookie_len + 2 > msg_len) {
1704             MBEDTLS_SSL_DEBUG_MSG(1, ("bad client hello message"));
1705             mbedtls_ssl_send_alert_message(ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,
1706                                            MBEDTLS_SSL_ALERT_MSG_PROTOCOL_VERSION);
1707             return MBEDTLS_ERR_SSL_BAD_HS_CLIENT_HELLO;
1708         }
1709 
1710         MBEDTLS_SSL_DEBUG_BUF(3, "client hello, cookie",
1711                               buf + cookie_offset + 1, cookie_len);
1712 
1713 #if defined(MBEDTLS_SSL_DTLS_HELLO_VERIFY)
1714         if (ssl->conf->f_cookie_check != NULL
1715 #if defined(MBEDTLS_SSL_RENEGOTIATION)
1716             && ssl->renego_status == MBEDTLS_SSL_INITIAL_HANDSHAKE
1717 #endif
1718             ) {
1719             if (ssl->conf->f_cookie_check(ssl->conf->p_cookie,
1720                                           buf + cookie_offset + 1, cookie_len,
1721                                           ssl->cli_id, ssl->cli_id_len) != 0) {
1722                 MBEDTLS_SSL_DEBUG_MSG(2, ("cookie verification failed"));
1723                 ssl->handshake->verify_cookie_len = 1;
1724             } else {
1725                 MBEDTLS_SSL_DEBUG_MSG(2, ("cookie verification passed"));
1726                 ssl->handshake->verify_cookie_len = 0;
1727             }
1728         } else
1729 #endif /* MBEDTLS_SSL_DTLS_HELLO_VERIFY */
1730         {
1731             /* We know we didn't send a cookie, so it should be empty */
1732             if (cookie_len != 0) {
1733                 /* This may be an attacker's probe, so don't send an alert */
1734                 MBEDTLS_SSL_DEBUG_MSG(1, ("bad client hello message"));
1735                 return MBEDTLS_ERR_SSL_BAD_HS_CLIENT_HELLO;
1736             }
1737 
1738             MBEDTLS_SSL_DEBUG_MSG(2, ("cookie verification skipped"));
1739         }
1740 
1741         /*
1742          * Check the ciphersuitelist length (will be parsed later)
1743          */
1744         ciph_offset = cookie_offset + 1 + cookie_len;
1745     } else
1746 #endif /* MBEDTLS_SSL_PROTO_DTLS */
1747     ciph_offset = 35 + sess_len;
1748 
1749     ciph_len = (buf[ciph_offset + 0] << 8)
1750                | (buf[ciph_offset + 1]);
1751 
1752     if (ciph_len < 2 ||
1753         ciph_len + 2 + ciph_offset + 1 > msg_len || /* 1 for comp. alg. len */
1754         (ciph_len % 2) != 0) {
1755         MBEDTLS_SSL_DEBUG_MSG(1, ("bad client hello message"));
1756         mbedtls_ssl_send_alert_message(ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,
1757                                        MBEDTLS_SSL_ALERT_MSG_DECODE_ERROR);
1758         return MBEDTLS_ERR_SSL_BAD_HS_CLIENT_HELLO;
1759     }
1760 
1761     MBEDTLS_SSL_DEBUG_BUF(3, "client hello, ciphersuitelist",
1762                           buf + ciph_offset + 2,  ciph_len);
1763 
1764     /*
1765      * Check the compression algorithms length and pick one
1766      */
1767     comp_offset = ciph_offset + 2 + ciph_len;
1768 
1769     comp_len = buf[comp_offset];
1770 
1771     if (comp_len < 1 ||
1772         comp_len > 16 ||
1773         comp_len + comp_offset + 1 > msg_len) {
1774         MBEDTLS_SSL_DEBUG_MSG(1, ("bad client hello message"));
1775         mbedtls_ssl_send_alert_message(ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,
1776                                        MBEDTLS_SSL_ALERT_MSG_DECODE_ERROR);
1777         return MBEDTLS_ERR_SSL_BAD_HS_CLIENT_HELLO;
1778     }
1779 
1780     MBEDTLS_SSL_DEBUG_BUF(3, "client hello, compression",
1781                           buf + comp_offset + 1, comp_len);
1782 
1783     ssl->session_negotiate->compression = MBEDTLS_SSL_COMPRESS_NULL;
1784 #if defined(MBEDTLS_ZLIB_SUPPORT)
1785     for (i = 0; i < comp_len; ++i) {
1786         if (buf[comp_offset + 1 + i] == MBEDTLS_SSL_COMPRESS_DEFLATE) {
1787             ssl->session_negotiate->compression = MBEDTLS_SSL_COMPRESS_DEFLATE;
1788             break;
1789         }
1790     }
1791 #endif
1792 
1793     /* See comments in ssl_write_client_hello() */
1794 #if defined(MBEDTLS_SSL_PROTO_DTLS)
1795     if (ssl->conf->transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM) {
1796         ssl->session_negotiate->compression = MBEDTLS_SSL_COMPRESS_NULL;
1797     }
1798 #endif
1799 
1800     /* Do not parse the extensions if the protocol is SSLv3 */
1801 #if defined(MBEDTLS_SSL_PROTO_SSL3)
1802     if ((ssl->major_ver != 3) || (ssl->minor_ver != 0)) {
1803 #endif
1804     /*
1805      * Check the extension length
1806      */
1807     ext_offset = comp_offset + 1 + comp_len;
1808     if (msg_len > ext_offset) {
1809         if (msg_len < ext_offset + 2) {
1810             MBEDTLS_SSL_DEBUG_MSG(1, ("bad client hello message"));
1811             mbedtls_ssl_send_alert_message(ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,
1812                                            MBEDTLS_SSL_ALERT_MSG_DECODE_ERROR);
1813             return MBEDTLS_ERR_SSL_BAD_HS_CLIENT_HELLO;
1814         }
1815 
1816         ext_len = (buf[ext_offset + 0] << 8)
1817                   | (buf[ext_offset + 1]);
1818 
1819         if (msg_len != ext_offset + 2 + ext_len) {
1820             MBEDTLS_SSL_DEBUG_MSG(1, ("bad client hello message"));
1821             mbedtls_ssl_send_alert_message(ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,
1822                                            MBEDTLS_SSL_ALERT_MSG_DECODE_ERROR);
1823             return MBEDTLS_ERR_SSL_BAD_HS_CLIENT_HELLO;
1824         }
1825     } else {
1826         ext_len = 0;
1827     }
1828 
1829     ext = buf + ext_offset + 2;
1830     MBEDTLS_SSL_DEBUG_BUF(3, "client hello extensions", ext, ext_len);
1831 
1832     while (ext_len != 0) {
1833         unsigned int ext_id;
1834         unsigned int ext_size;
1835         if (ext_len < 4) {
1836             MBEDTLS_SSL_DEBUG_MSG(1, ("bad client hello message"));
1837             mbedtls_ssl_send_alert_message(ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,
1838                                            MBEDTLS_SSL_ALERT_MSG_DECODE_ERROR);
1839             return MBEDTLS_ERR_SSL_BAD_HS_CLIENT_HELLO;
1840         }
1841         ext_id   = ((ext[0] <<  8) | (ext[1]));
1842         ext_size = ((ext[2] <<  8) | (ext[3]));
1843 
1844         if (ext_size + 4 > ext_len) {
1845             MBEDTLS_SSL_DEBUG_MSG(1, ("bad client hello message"));
1846             mbedtls_ssl_send_alert_message(ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,
1847                                            MBEDTLS_SSL_ALERT_MSG_DECODE_ERROR);
1848             return MBEDTLS_ERR_SSL_BAD_HS_CLIENT_HELLO;
1849         }
1850         switch (ext_id) {
1851 #if defined(MBEDTLS_SSL_SERVER_NAME_INDICATION)
1852             case MBEDTLS_TLS_EXT_SERVERNAME:
1853                 MBEDTLS_SSL_DEBUG_MSG(3, ("found ServerName extension"));
1854                 if (ssl->conf->f_sni == NULL) {
1855                     break;
1856                 }
1857 
1858                 ret = ssl_parse_servername_ext(ssl, ext + 4, ext_size);
1859                 if (ret != 0) {
1860                     return ret;
1861                 }
1862                 break;
1863 #endif /* MBEDTLS_SSL_SERVER_NAME_INDICATION */
1864 
1865             case MBEDTLS_TLS_EXT_RENEGOTIATION_INFO:
1866                 MBEDTLS_SSL_DEBUG_MSG(3, ("found renegotiation extension"));
1867 #if defined(MBEDTLS_SSL_RENEGOTIATION)
1868                 renegotiation_info_seen = 1;
1869 #endif
1870 
1871                 ret = ssl_parse_renegotiation_info(ssl, ext + 4, ext_size);
1872                 if (ret != 0) {
1873                     return ret;
1874                 }
1875                 break;
1876 
1877 #if defined(MBEDTLS_SSL_PROTO_TLS1_2) && \
1878                 defined(MBEDTLS_KEY_EXCHANGE_WITH_CERT_ENABLED)
1879             case MBEDTLS_TLS_EXT_SIG_ALG:
1880                 MBEDTLS_SSL_DEBUG_MSG(3, ("found signature_algorithms extension"));
1881 
1882                 ret = ssl_parse_signature_algorithms_ext(ssl, ext + 4, ext_size);
1883                 if (ret != 0) {
1884                     return ret;
1885                 }
1886 
1887                 sig_hash_alg_ext_present = 1;
1888                 break;
1889 #endif /* MBEDTLS_SSL_PROTO_TLS1_2 &&
1890           MBEDTLS_KEY_EXCHANGE_WITH_CERT_ENABLED */
1891 
1892 #if defined(MBEDTLS_ECDH_C) || defined(MBEDTLS_ECDSA_C) || \
1893                 defined(MBEDTLS_KEY_EXCHANGE_ECJPAKE_ENABLED)
1894             case MBEDTLS_TLS_EXT_SUPPORTED_ELLIPTIC_CURVES:
1895                 MBEDTLS_SSL_DEBUG_MSG(3, ("found supported elliptic curves extension"));
1896 
1897                 ret = ssl_parse_supported_elliptic_curves(ssl, ext + 4, ext_size);
1898                 if (ret != 0) {
1899                     return ret;
1900                 }
1901                 break;
1902 
1903             case MBEDTLS_TLS_EXT_SUPPORTED_POINT_FORMATS:
1904                 MBEDTLS_SSL_DEBUG_MSG(3, ("found supported point formats extension"));
1905                 ssl->handshake->cli_exts |= MBEDTLS_TLS_EXT_SUPPORTED_POINT_FORMATS_PRESENT;
1906 
1907                 ret = ssl_parse_supported_point_formats(ssl, ext + 4, ext_size);
1908                 if (ret != 0) {
1909                     return ret;
1910                 }
1911                 break;
1912 #endif /* MBEDTLS_ECDH_C || MBEDTLS_ECDSA_C ||
1913           MBEDTLS_KEY_EXCHANGE_ECJPAKE_ENABLED */
1914 
1915 #if defined(MBEDTLS_KEY_EXCHANGE_ECJPAKE_ENABLED)
1916             case MBEDTLS_TLS_EXT_ECJPAKE_KKPP:
1917                 MBEDTLS_SSL_DEBUG_MSG(3, ("found ecjpake kkpp extension"));
1918 
1919                 ret = ssl_parse_ecjpake_kkpp(ssl, ext + 4, ext_size);
1920                 if (ret != 0) {
1921                     return ret;
1922                 }
1923                 break;
1924 #endif /* MBEDTLS_KEY_EXCHANGE_ECJPAKE_ENABLED */
1925 
1926 #if defined(MBEDTLS_SSL_MAX_FRAGMENT_LENGTH)
1927             case MBEDTLS_TLS_EXT_MAX_FRAGMENT_LENGTH:
1928                 MBEDTLS_SSL_DEBUG_MSG(3, ("found max fragment length extension"));
1929 
1930                 ret = ssl_parse_max_fragment_length_ext(ssl, ext + 4, ext_size);
1931                 if (ret != 0) {
1932                     return ret;
1933                 }
1934                 break;
1935 #endif /* MBEDTLS_SSL_MAX_FRAGMENT_LENGTH */
1936 
1937 #if defined(MBEDTLS_SSL_TRUNCATED_HMAC)
1938             case MBEDTLS_TLS_EXT_TRUNCATED_HMAC:
1939                 MBEDTLS_SSL_DEBUG_MSG(3, ("found truncated hmac extension"));
1940 
1941                 ret = ssl_parse_truncated_hmac_ext(ssl, ext + 4, ext_size);
1942                 if (ret != 0) {
1943                     return ret;
1944                 }
1945                 break;
1946 #endif /* MBEDTLS_SSL_TRUNCATED_HMAC */
1947 
1948 #if defined(MBEDTLS_SSL_DTLS_CONNECTION_ID)
1949             case MBEDTLS_TLS_EXT_CID:
1950                 MBEDTLS_SSL_DEBUG_MSG(3, ("found CID extension"));
1951 
1952                 ret = ssl_parse_cid_ext(ssl, ext + 4, ext_size);
1953                 if (ret != 0) {
1954                     return ret;
1955                 }
1956                 break;
1957 #endif /* MBEDTLS_SSL_TRUNCATED_HMAC */
1958 
1959 #if defined(MBEDTLS_SSL_ENCRYPT_THEN_MAC)
1960             case MBEDTLS_TLS_EXT_ENCRYPT_THEN_MAC:
1961                 MBEDTLS_SSL_DEBUG_MSG(3, ("found encrypt then mac extension"));
1962 
1963                 ret = ssl_parse_encrypt_then_mac_ext(ssl, ext + 4, ext_size);
1964                 if (ret != 0) {
1965                     return ret;
1966                 }
1967                 break;
1968 #endif /* MBEDTLS_SSL_ENCRYPT_THEN_MAC */
1969 
1970 #if defined(MBEDTLS_SSL_EXTENDED_MASTER_SECRET)
1971             case MBEDTLS_TLS_EXT_EXTENDED_MASTER_SECRET:
1972                 MBEDTLS_SSL_DEBUG_MSG(3, ("found extended master secret extension"));
1973 
1974                 ret = ssl_parse_extended_ms_ext(ssl, ext + 4, ext_size);
1975                 if (ret != 0) {
1976                     return ret;
1977                 }
1978                 break;
1979 #endif /* MBEDTLS_SSL_EXTENDED_MASTER_SECRET */
1980 
1981 #if defined(MBEDTLS_SSL_SESSION_TICKETS)
1982             case MBEDTLS_TLS_EXT_SESSION_TICKET:
1983                 MBEDTLS_SSL_DEBUG_MSG(3, ("found session ticket extension"));
1984 
1985                 ret = ssl_parse_session_ticket_ext(ssl, ext + 4, ext_size);
1986                 if (ret != 0) {
1987                     return ret;
1988                 }
1989                 break;
1990 #endif /* MBEDTLS_SSL_SESSION_TICKETS */
1991 
1992 #if defined(MBEDTLS_SSL_ALPN)
1993             case MBEDTLS_TLS_EXT_ALPN:
1994                 MBEDTLS_SSL_DEBUG_MSG(3, ("found alpn extension"));
1995 
1996                 ret = ssl_parse_alpn_ext(ssl, ext + 4, ext_size);
1997                 if (ret != 0) {
1998                     return ret;
1999                 }
2000                 break;
2001 #endif /* MBEDTLS_SSL_SESSION_TICKETS */
2002 
2003 #if defined(MBEDTLS_SSL_DTLS_SRTP)
2004             case MBEDTLS_TLS_EXT_USE_SRTP:
2005                 MBEDTLS_SSL_DEBUG_MSG(3, ("found use_srtp extension"));
2006 
2007                 ret = ssl_parse_use_srtp_ext(ssl, ext + 4, ext_size);
2008                 if (ret != 0) {
2009                     return ret;
2010                 }
2011                 break;
2012 #endif /* MBEDTLS_SSL_DTLS_SRTP */
2013 
2014             default:
2015                 MBEDTLS_SSL_DEBUG_MSG(3, ("unknown extension found: %u (ignoring)",
2016                                           ext_id));
2017         }
2018 
2019         ext_len -= 4 + ext_size;
2020         ext += 4 + ext_size;
2021     }
2022 #if defined(MBEDTLS_SSL_PROTO_SSL3)
2023 }
2024 #endif
2025 
2026 #if defined(MBEDTLS_SSL_FALLBACK_SCSV)
2027     for (i = 0, p = buf + ciph_offset + 2; i < ciph_len; i += 2, p += 2) {
2028         if (MBEDTLS_GET_UINT16_BE(p, 0) == MBEDTLS_SSL_FALLBACK_SCSV_VALUE) {
2029             MBEDTLS_SSL_DEBUG_MSG(2, ("received FALLBACK_SCSV"));
2030 
2031             if (ssl->minor_ver < ssl->conf->max_minor_ver) {
2032                 MBEDTLS_SSL_DEBUG_MSG(1, ("inapropriate fallback"));
2033 
2034                 mbedtls_ssl_send_alert_message(ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,
2035                                                MBEDTLS_SSL_ALERT_MSG_INAPROPRIATE_FALLBACK);
2036 
2037                 return MBEDTLS_ERR_SSL_BAD_HS_CLIENT_HELLO;
2038             }
2039 
2040             break;
2041         }
2042     }
2043 #endif /* MBEDTLS_SSL_FALLBACK_SCSV */
2044 
2045 #if defined(MBEDTLS_SSL_PROTO_TLS1_2) && \
2046     defined(MBEDTLS_KEY_EXCHANGE_WITH_CERT_ENABLED)
2047 
2048     /*
2049      * Try to fall back to default hash SHA1 if the client
2050      * hasn't provided any preferred signature-hash combinations.
2051      */
2052     if (sig_hash_alg_ext_present == 0) {
2053         mbedtls_md_type_t md_default = MBEDTLS_MD_SHA1;
2054 
2055         if (mbedtls_ssl_check_sig_hash(ssl, md_default) != 0) {
2056             md_default = MBEDTLS_MD_NONE;
2057         }
2058 
2059         mbedtls_ssl_sig_hash_set_const_hash(&ssl->handshake->hash_algs, md_default);
2060     }
2061 
2062 #endif /* MBEDTLS_SSL_PROTO_TLS1_2 &&
2063           MBEDTLS_KEY_EXCHANGE_WITH_CERT_ENABLED */
2064 
2065     /*
2066      * Check for TLS_EMPTY_RENEGOTIATION_INFO_SCSV
2067      */
2068     for (i = 0, p = buf + ciph_offset + 2; i < ciph_len; i += 2, p += 2) {
2069         if (p[0] == 0 && p[1] == MBEDTLS_SSL_EMPTY_RENEGOTIATION_INFO) {
2070             MBEDTLS_SSL_DEBUG_MSG(3, ("received TLS_EMPTY_RENEGOTIATION_INFO "));
2071 #if defined(MBEDTLS_SSL_RENEGOTIATION)
2072             if (ssl->renego_status == MBEDTLS_SSL_RENEGOTIATION_IN_PROGRESS) {
2073                 MBEDTLS_SSL_DEBUG_MSG(1, ("received RENEGOTIATION SCSV "
2074                                           "during renegotiation"));
2075                 mbedtls_ssl_send_alert_message(ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,
2076                                                MBEDTLS_SSL_ALERT_MSG_HANDSHAKE_FAILURE);
2077                 return MBEDTLS_ERR_SSL_BAD_HS_CLIENT_HELLO;
2078             }
2079 #endif
2080             ssl->secure_renegotiation = MBEDTLS_SSL_SECURE_RENEGOTIATION;
2081             break;
2082         }
2083     }
2084 
2085     /*
2086      * Renegotiation security checks
2087      */
2088     if (ssl->secure_renegotiation != MBEDTLS_SSL_SECURE_RENEGOTIATION &&
2089         ssl->conf->allow_legacy_renegotiation == MBEDTLS_SSL_LEGACY_BREAK_HANDSHAKE) {
2090         MBEDTLS_SSL_DEBUG_MSG(1, ("legacy renegotiation, breaking off handshake"));
2091         handshake_failure = 1;
2092     }
2093 #if defined(MBEDTLS_SSL_RENEGOTIATION)
2094     else if (ssl->renego_status == MBEDTLS_SSL_RENEGOTIATION_IN_PROGRESS &&
2095              ssl->secure_renegotiation == MBEDTLS_SSL_SECURE_RENEGOTIATION &&
2096              renegotiation_info_seen == 0) {
2097         MBEDTLS_SSL_DEBUG_MSG(1, ("renegotiation_info extension missing (secure)"));
2098         handshake_failure = 1;
2099     } else if (ssl->renego_status == MBEDTLS_SSL_RENEGOTIATION_IN_PROGRESS &&
2100                ssl->secure_renegotiation == MBEDTLS_SSL_LEGACY_RENEGOTIATION &&
2101                ssl->conf->allow_legacy_renegotiation == MBEDTLS_SSL_LEGACY_NO_RENEGOTIATION) {
2102         MBEDTLS_SSL_DEBUG_MSG(1, ("legacy renegotiation not allowed"));
2103         handshake_failure = 1;
2104     } else if (ssl->renego_status == MBEDTLS_SSL_RENEGOTIATION_IN_PROGRESS &&
2105                ssl->secure_renegotiation == MBEDTLS_SSL_LEGACY_RENEGOTIATION &&
2106                renegotiation_info_seen == 1) {
2107         MBEDTLS_SSL_DEBUG_MSG(1, ("renegotiation_info extension present (legacy)"));
2108         handshake_failure = 1;
2109     }
2110 #endif /* MBEDTLS_SSL_RENEGOTIATION */
2111 
2112     if (handshake_failure == 1) {
2113         mbedtls_ssl_send_alert_message(ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,
2114                                        MBEDTLS_SSL_ALERT_MSG_HANDSHAKE_FAILURE);
2115         return MBEDTLS_ERR_SSL_BAD_HS_CLIENT_HELLO;
2116     }
2117 
2118     /*
2119      * Search for a matching ciphersuite
2120      * (At the end because we need information from the EC-based extensions
2121      * and certificate from the SNI callback triggered by the SNI extension.)
2122      */
2123     got_common_suite = 0;
2124     ciphersuites = ssl->conf->ciphersuite_list[ssl->minor_ver];
2125     ciphersuite_info = NULL;
2126 #if defined(MBEDTLS_SSL_SRV_RESPECT_CLIENT_PREFERENCE)
2127     for (j = 0, p = buf + ciph_offset + 2; j < ciph_len; j += 2, p += 2) {
2128         for (i = 0; ciphersuites[i] != 0; i++) {
2129             if (MBEDTLS_GET_UINT16_BE(p, 0) != ciphersuites[i]) {
2130                 continue;
2131             }
2132 
2133             got_common_suite = 1;
2134 
2135             if ((ret = ssl_ciphersuite_match(ssl, ciphersuites[i],
2136                                              &ciphersuite_info)) != 0) {
2137                 return ret;
2138             }
2139 
2140             if (ciphersuite_info != NULL) {
2141                 goto have_ciphersuite;
2142             }
2143         }
2144     }
2145 #else
2146     for (i = 0; ciphersuites[i] != 0; i++) {
2147         for (j = 0, p = buf + ciph_offset + 2; j < ciph_len; j += 2, p += 2) {
2148             if (MBEDTLS_GET_UINT16_BE(p, 0) != ciphersuites[i]) {
2149                 continue;
2150             }
2151 
2152             got_common_suite = 1;
2153 
2154             if ((ret = ssl_ciphersuite_match(ssl, ciphersuites[i],
2155                                              &ciphersuite_info)) != 0) {
2156                 return ret;
2157             }
2158 
2159             if (ciphersuite_info != NULL) {
2160                 goto have_ciphersuite;
2161             }
2162         }
2163     }
2164 #endif
2165 
2166     if (got_common_suite) {
2167         MBEDTLS_SSL_DEBUG_MSG(1, ("got ciphersuites in common, "
2168                                   "but none of them usable"));
2169         mbedtls_ssl_send_alert_message(ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,
2170                                        MBEDTLS_SSL_ALERT_MSG_HANDSHAKE_FAILURE);
2171         return MBEDTLS_ERR_SSL_NO_USABLE_CIPHERSUITE;
2172     } else {
2173         MBEDTLS_SSL_DEBUG_MSG(1, ("got no ciphersuites in common"));
2174         mbedtls_ssl_send_alert_message(ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,
2175                                        MBEDTLS_SSL_ALERT_MSG_HANDSHAKE_FAILURE);
2176         return MBEDTLS_ERR_SSL_NO_CIPHER_CHOSEN;
2177     }
2178 
2179 have_ciphersuite:
2180     MBEDTLS_SSL_DEBUG_MSG(2, ("selected ciphersuite: %s", ciphersuite_info->name));
2181 
2182     ssl->session_negotiate->ciphersuite = ciphersuites[i];
2183     ssl->handshake->ciphersuite_info = ciphersuite_info;
2184 
2185     ssl->state++;
2186 
2187 #if defined(MBEDTLS_SSL_PROTO_DTLS)
2188     if (ssl->conf->transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM) {
2189         mbedtls_ssl_recv_flight_completed(ssl);
2190     }
2191 #endif
2192 
2193     /* Debugging-only output for testsuite */
2194 #if defined(MBEDTLS_DEBUG_C)                         && \
2195     defined(MBEDTLS_SSL_PROTO_TLS1_2)                && \
2196     defined(MBEDTLS_KEY_EXCHANGE_WITH_CERT_ENABLED)
2197     if (ssl->minor_ver == MBEDTLS_SSL_MINOR_VERSION_3) {
2198         mbedtls_pk_type_t sig_alg = mbedtls_ssl_get_ciphersuite_sig_alg(ciphersuite_info);
2199         if (sig_alg != MBEDTLS_PK_NONE) {
2200             mbedtls_md_type_t md_alg = mbedtls_ssl_sig_hash_set_find(&ssl->handshake->hash_algs,
2201                                                                      sig_alg);
2202             MBEDTLS_SSL_DEBUG_MSG(3, ("client hello v3, signature_algorithm ext: %d",
2203                                       mbedtls_ssl_hash_from_md_alg(md_alg)));
2204         } else {
2205             MBEDTLS_SSL_DEBUG_MSG(3, ("no hash algorithm for signature algorithm "
2206                                       "%u - should not happen", (unsigned) sig_alg));
2207         }
2208     }
2209 #endif
2210 
2211     MBEDTLS_SSL_DEBUG_MSG(2, ("<= parse client hello"));
2212 
2213     return 0;
2214 }
2215 
2216 #if defined(MBEDTLS_SSL_TRUNCATED_HMAC)
ssl_write_truncated_hmac_ext(mbedtls_ssl_context * ssl,unsigned char * buf,size_t * olen)2217 static void ssl_write_truncated_hmac_ext(mbedtls_ssl_context *ssl,
2218                                          unsigned char *buf,
2219                                          size_t *olen)
2220 {
2221     unsigned char *p = buf;
2222 
2223     if (ssl->session_negotiate->trunc_hmac == MBEDTLS_SSL_TRUNC_HMAC_DISABLED) {
2224         *olen = 0;
2225         return;
2226     }
2227 
2228     MBEDTLS_SSL_DEBUG_MSG(3, ("server hello, adding truncated hmac extension"));
2229 
2230     MBEDTLS_PUT_UINT16_BE(MBEDTLS_TLS_EXT_TRUNCATED_HMAC, p, 0);
2231     p += 2;
2232 
2233     *p++ = 0x00;
2234     *p++ = 0x00;
2235 
2236     *olen = 4;
2237 }
2238 #endif /* MBEDTLS_SSL_TRUNCATED_HMAC */
2239 
2240 #if defined(MBEDTLS_SSL_DTLS_CONNECTION_ID)
ssl_write_cid_ext(mbedtls_ssl_context * ssl,unsigned char * buf,size_t * olen)2241 static void ssl_write_cid_ext(mbedtls_ssl_context *ssl,
2242                               unsigned char *buf,
2243                               size_t *olen)
2244 {
2245     unsigned char *p = buf;
2246     size_t ext_len;
2247     const unsigned char *end = ssl->out_msg + MBEDTLS_SSL_OUT_CONTENT_LEN;
2248 
2249     *olen = 0;
2250 
2251     /* Skip writing the extension if we don't want to use it or if
2252      * the client hasn't offered it. */
2253     if (ssl->handshake->cid_in_use == MBEDTLS_SSL_CID_DISABLED) {
2254         return;
2255     }
2256 
2257     /* ssl->own_cid_len is at most MBEDTLS_SSL_CID_IN_LEN_MAX
2258      * which is at most 255, so the increment cannot overflow. */
2259     if (end < p || (size_t) (end - p) < (unsigned) (ssl->own_cid_len + 5)) {
2260         MBEDTLS_SSL_DEBUG_MSG(1, ("buffer too small"));
2261         return;
2262     }
2263 
2264     MBEDTLS_SSL_DEBUG_MSG(3, ("server hello, adding CID extension"));
2265 
2266     /*
2267      * Quoting draft-ietf-tls-dtls-connection-id-05
2268      * https://tools.ietf.org/html/draft-ietf-tls-dtls-connection-id-05
2269      *
2270      *   struct {
2271      *      opaque cid<0..2^8-1>;
2272      *   } ConnectionId;
2273      */
2274     MBEDTLS_PUT_UINT16_BE(MBEDTLS_TLS_EXT_CID, p, 0);
2275     p += 2;
2276     ext_len = (size_t) ssl->own_cid_len + 1;
2277     MBEDTLS_PUT_UINT16_BE(ext_len, p, 0);
2278     p += 2;
2279 
2280     *p++ = (uint8_t) ssl->own_cid_len;
2281     memcpy(p, ssl->own_cid, ssl->own_cid_len);
2282 
2283     *olen = ssl->own_cid_len + 5;
2284 }
2285 #endif /* MBEDTLS_SSL_DTLS_CONNECTION_ID */
2286 
2287 #if defined(MBEDTLS_SSL_ENCRYPT_THEN_MAC)
ssl_write_encrypt_then_mac_ext(mbedtls_ssl_context * ssl,unsigned char * buf,size_t * olen)2288 static void ssl_write_encrypt_then_mac_ext(mbedtls_ssl_context *ssl,
2289                                            unsigned char *buf,
2290                                            size_t *olen)
2291 {
2292     unsigned char *p = buf;
2293     const mbedtls_ssl_ciphersuite_t *suite = NULL;
2294     const mbedtls_cipher_info_t *cipher = NULL;
2295 
2296     if (ssl->minor_ver == MBEDTLS_SSL_MINOR_VERSION_0) {
2297         ssl->session_negotiate->encrypt_then_mac = MBEDTLS_SSL_ETM_DISABLED;
2298     }
2299 
2300     /*
2301      * RFC 7366: "If a server receives an encrypt-then-MAC request extension
2302      * from a client and then selects a stream or Authenticated Encryption
2303      * with Associated Data (AEAD) ciphersuite, it MUST NOT send an
2304      * encrypt-then-MAC response extension back to the client."
2305      */
2306     if ((suite = mbedtls_ssl_ciphersuite_from_id(
2307              ssl->session_negotiate->ciphersuite)) == NULL ||
2308         (cipher = mbedtls_cipher_info_from_type(suite->cipher)) == NULL ||
2309         cipher->mode != MBEDTLS_MODE_CBC) {
2310         ssl->session_negotiate->encrypt_then_mac = MBEDTLS_SSL_ETM_DISABLED;
2311     }
2312 
2313     if (ssl->session_negotiate->encrypt_then_mac == MBEDTLS_SSL_ETM_DISABLED) {
2314         *olen = 0;
2315         return;
2316     }
2317 
2318     MBEDTLS_SSL_DEBUG_MSG(3, ("server hello, adding encrypt then mac extension"));
2319 
2320     MBEDTLS_PUT_UINT16_BE(MBEDTLS_TLS_EXT_ENCRYPT_THEN_MAC, p, 0);
2321     p += 2;
2322 
2323     *p++ = 0x00;
2324     *p++ = 0x00;
2325 
2326     *olen = 4;
2327 }
2328 #endif /* MBEDTLS_SSL_ENCRYPT_THEN_MAC */
2329 
2330 #if defined(MBEDTLS_SSL_EXTENDED_MASTER_SECRET)
ssl_write_extended_ms_ext(mbedtls_ssl_context * ssl,unsigned char * buf,size_t * olen)2331 static void ssl_write_extended_ms_ext(mbedtls_ssl_context *ssl,
2332                                       unsigned char *buf,
2333                                       size_t *olen)
2334 {
2335     unsigned char *p = buf;
2336 
2337     if (ssl->handshake->extended_ms == MBEDTLS_SSL_EXTENDED_MS_DISABLED ||
2338         ssl->minor_ver == MBEDTLS_SSL_MINOR_VERSION_0) {
2339         *olen = 0;
2340         return;
2341     }
2342 
2343     MBEDTLS_SSL_DEBUG_MSG(3, ("server hello, adding extended master secret "
2344                               "extension"));
2345 
2346     MBEDTLS_PUT_UINT16_BE(MBEDTLS_TLS_EXT_EXTENDED_MASTER_SECRET, p, 0);
2347     p += 2;
2348 
2349     *p++ = 0x00;
2350     *p++ = 0x00;
2351 
2352     *olen = 4;
2353 }
2354 #endif /* MBEDTLS_SSL_EXTENDED_MASTER_SECRET */
2355 
2356 #if defined(MBEDTLS_SSL_SESSION_TICKETS)
ssl_write_session_ticket_ext(mbedtls_ssl_context * ssl,unsigned char * buf,size_t * olen)2357 static void ssl_write_session_ticket_ext(mbedtls_ssl_context *ssl,
2358                                          unsigned char *buf,
2359                                          size_t *olen)
2360 {
2361     unsigned char *p = buf;
2362 
2363     if (ssl->handshake->new_session_ticket == 0) {
2364         *olen = 0;
2365         return;
2366     }
2367 
2368     MBEDTLS_SSL_DEBUG_MSG(3, ("server hello, adding session ticket extension"));
2369 
2370     MBEDTLS_PUT_UINT16_BE(MBEDTLS_TLS_EXT_SESSION_TICKET, p, 0);
2371     p += 2;
2372 
2373     *p++ = 0x00;
2374     *p++ = 0x00;
2375 
2376     *olen = 4;
2377 }
2378 #endif /* MBEDTLS_SSL_SESSION_TICKETS */
2379 
ssl_write_renegotiation_ext(mbedtls_ssl_context * ssl,unsigned char * buf,size_t * olen)2380 static void ssl_write_renegotiation_ext(mbedtls_ssl_context *ssl,
2381                                         unsigned char *buf,
2382                                         size_t *olen)
2383 {
2384     unsigned char *p = buf;
2385 
2386     if (ssl->secure_renegotiation != MBEDTLS_SSL_SECURE_RENEGOTIATION) {
2387         *olen = 0;
2388         return;
2389     }
2390 
2391     MBEDTLS_SSL_DEBUG_MSG(3, ("server hello, secure renegotiation extension"));
2392 
2393     MBEDTLS_PUT_UINT16_BE(MBEDTLS_TLS_EXT_RENEGOTIATION_INFO, p, 0);
2394     p += 2;
2395 
2396 #if defined(MBEDTLS_SSL_RENEGOTIATION)
2397     if (ssl->renego_status != MBEDTLS_SSL_INITIAL_HANDSHAKE) {
2398         *p++ = 0x00;
2399         *p++ = (ssl->verify_data_len * 2 + 1) & 0xFF;
2400         *p++ = ssl->verify_data_len * 2 & 0xFF;
2401 
2402         memcpy(p, ssl->peer_verify_data, ssl->verify_data_len);
2403         p += ssl->verify_data_len;
2404         memcpy(p, ssl->own_verify_data, ssl->verify_data_len);
2405         p += ssl->verify_data_len;
2406     } else
2407 #endif /* MBEDTLS_SSL_RENEGOTIATION */
2408     {
2409         *p++ = 0x00;
2410         *p++ = 0x01;
2411         *p++ = 0x00;
2412     }
2413 
2414     *olen = p - buf;
2415 }
2416 
2417 #if defined(MBEDTLS_SSL_MAX_FRAGMENT_LENGTH)
ssl_write_max_fragment_length_ext(mbedtls_ssl_context * ssl,unsigned char * buf,size_t * olen)2418 static void ssl_write_max_fragment_length_ext(mbedtls_ssl_context *ssl,
2419                                               unsigned char *buf,
2420                                               size_t *olen)
2421 {
2422     unsigned char *p = buf;
2423 
2424     if (ssl->session_negotiate->mfl_code == MBEDTLS_SSL_MAX_FRAG_LEN_NONE) {
2425         *olen = 0;
2426         return;
2427     }
2428 
2429     MBEDTLS_SSL_DEBUG_MSG(3, ("server hello, max_fragment_length extension"));
2430 
2431     MBEDTLS_PUT_UINT16_BE(MBEDTLS_TLS_EXT_MAX_FRAGMENT_LENGTH, p, 0);
2432     p += 2;
2433 
2434     *p++ = 0x00;
2435     *p++ = 1;
2436 
2437     *p++ = ssl->session_negotiate->mfl_code;
2438 
2439     *olen = 5;
2440 }
2441 #endif /* MBEDTLS_SSL_MAX_FRAGMENT_LENGTH */
2442 
2443 #if defined(MBEDTLS_ECDH_C) || defined(MBEDTLS_ECDSA_C) || \
2444     defined(MBEDTLS_KEY_EXCHANGE_ECJPAKE_ENABLED)
ssl_write_supported_point_formats_ext(mbedtls_ssl_context * ssl,unsigned char * buf,size_t * olen)2445 static void ssl_write_supported_point_formats_ext(mbedtls_ssl_context *ssl,
2446                                                   unsigned char *buf,
2447                                                   size_t *olen)
2448 {
2449     unsigned char *p = buf;
2450     ((void) ssl);
2451 
2452     if ((ssl->handshake->cli_exts &
2453          MBEDTLS_TLS_EXT_SUPPORTED_POINT_FORMATS_PRESENT) == 0) {
2454         *olen = 0;
2455         return;
2456     }
2457 
2458     MBEDTLS_SSL_DEBUG_MSG(3, ("server hello, supported_point_formats extension"));
2459 
2460     MBEDTLS_PUT_UINT16_BE(MBEDTLS_TLS_EXT_SUPPORTED_POINT_FORMATS, p, 0);
2461     p += 2;
2462 
2463     *p++ = 0x00;
2464     *p++ = 2;
2465 
2466     *p++ = 1;
2467     *p++ = MBEDTLS_ECP_PF_UNCOMPRESSED;
2468 
2469     *olen = 6;
2470 }
2471 #endif /* MBEDTLS_ECDH_C || MBEDTLS_ECDSA_C || MBEDTLS_KEY_EXCHANGE_ECJPAKE_ENABLED */
2472 
2473 #if defined(MBEDTLS_KEY_EXCHANGE_ECJPAKE_ENABLED)
ssl_write_ecjpake_kkpp_ext(mbedtls_ssl_context * ssl,unsigned char * buf,size_t * olen)2474 static void ssl_write_ecjpake_kkpp_ext(mbedtls_ssl_context *ssl,
2475                                        unsigned char *buf,
2476                                        size_t *olen)
2477 {
2478     int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
2479     unsigned char *p = buf;
2480     const unsigned char *end = ssl->out_msg + MBEDTLS_SSL_OUT_CONTENT_LEN;
2481     size_t kkpp_len;
2482 
2483     *olen = 0;
2484 
2485     /* Skip costly computation if not needed */
2486     if (ssl->handshake->ciphersuite_info->key_exchange !=
2487         MBEDTLS_KEY_EXCHANGE_ECJPAKE) {
2488         return;
2489     }
2490 
2491     MBEDTLS_SSL_DEBUG_MSG(3, ("server hello, ecjpake kkpp extension"));
2492 
2493     if (end - p < 4) {
2494         MBEDTLS_SSL_DEBUG_MSG(1, ("buffer too small"));
2495         return;
2496     }
2497 
2498     MBEDTLS_PUT_UINT16_BE(MBEDTLS_TLS_EXT_ECJPAKE_KKPP, p, 0);
2499     p += 2;
2500 
2501     ret = mbedtls_ecjpake_write_round_one(&ssl->handshake->ecjpake_ctx,
2502                                           p + 2, end - p - 2, &kkpp_len,
2503                                           ssl->conf->f_rng, ssl->conf->p_rng);
2504     if (ret != 0) {
2505         MBEDTLS_SSL_DEBUG_RET(1, "mbedtls_ecjpake_write_round_one", ret);
2506         return;
2507     }
2508 
2509     MBEDTLS_PUT_UINT16_BE(kkpp_len, p, 0);
2510     p += 2;
2511 
2512     *olen = kkpp_len + 4;
2513 }
2514 #endif /* MBEDTLS_KEY_EXCHANGE_ECJPAKE_ENABLED */
2515 
2516 #if defined(MBEDTLS_SSL_ALPN)
ssl_write_alpn_ext(mbedtls_ssl_context * ssl,unsigned char * buf,size_t * olen)2517 static void ssl_write_alpn_ext(mbedtls_ssl_context *ssl,
2518                                unsigned char *buf, size_t *olen)
2519 {
2520     if (ssl->alpn_chosen == NULL) {
2521         *olen = 0;
2522         return;
2523     }
2524 
2525     MBEDTLS_SSL_DEBUG_MSG(3, ("server hello, adding alpn extension"));
2526 
2527     /*
2528      * 0 . 1    ext identifier
2529      * 2 . 3    ext length
2530      * 4 . 5    protocol list length
2531      * 6 . 6    protocol name length
2532      * 7 . 7+n  protocol name
2533      */
2534     MBEDTLS_PUT_UINT16_BE(MBEDTLS_TLS_EXT_ALPN, buf, 0);
2535 
2536     *olen = 7 + strlen(ssl->alpn_chosen);
2537 
2538     MBEDTLS_PUT_UINT16_BE(*olen - 4, buf, 2);
2539 
2540     MBEDTLS_PUT_UINT16_BE(*olen - 6, buf, 4);
2541 
2542     buf[6] = MBEDTLS_BYTE_0(*olen - 7);
2543 
2544     memcpy(buf + 7, ssl->alpn_chosen, *olen - 7);
2545 }
2546 #endif /* MBEDTLS_ECDH_C || MBEDTLS_ECDSA_C */
2547 
2548 #if defined(MBEDTLS_SSL_DTLS_SRTP) && defined(MBEDTLS_SSL_PROTO_DTLS)
ssl_write_use_srtp_ext(mbedtls_ssl_context * ssl,unsigned char * buf,size_t * olen)2549 static void ssl_write_use_srtp_ext(mbedtls_ssl_context *ssl,
2550                                    unsigned char *buf,
2551                                    size_t *olen)
2552 {
2553     size_t mki_len = 0, ext_len = 0;
2554     uint16_t profile_value = 0;
2555     const unsigned char *end = ssl->out_msg + MBEDTLS_SSL_OUT_CONTENT_LEN;
2556 
2557     *olen = 0;
2558 
2559     if ((ssl->conf->transport != MBEDTLS_SSL_TRANSPORT_DATAGRAM) ||
2560         (ssl->dtls_srtp_info.chosen_dtls_srtp_profile == MBEDTLS_TLS_SRTP_UNSET)) {
2561         return;
2562     }
2563 
2564     MBEDTLS_SSL_DEBUG_MSG(3, ("server hello, adding use_srtp extension"));
2565 
2566     if (ssl->conf->dtls_srtp_mki_support == MBEDTLS_SSL_DTLS_SRTP_MKI_SUPPORTED) {
2567         mki_len = ssl->dtls_srtp_info.mki_len;
2568     }
2569 
2570     /* The extension total size is 9 bytes :
2571      * - 2 bytes for the extension tag
2572      * - 2 bytes for the total size
2573      * - 2 bytes for the protection profile length
2574      * - 2 bytes for the protection profile
2575      * - 1 byte for the mki length
2576      * +  the actual mki length
2577      * Check we have enough room in the output buffer */
2578     if ((size_t) (end - buf) < mki_len + 9) {
2579         MBEDTLS_SSL_DEBUG_MSG(1, ("buffer too small"));
2580         return;
2581     }
2582 
2583     /* extension */
2584     MBEDTLS_PUT_UINT16_BE(MBEDTLS_TLS_EXT_USE_SRTP, buf, 0);
2585     /*
2586      * total length 5 and mki value: only one profile(2 bytes)
2587      *              and length(2 bytes) and srtp_mki  )
2588      */
2589     ext_len = 5 + mki_len;
2590     MBEDTLS_PUT_UINT16_BE(ext_len, buf, 2);
2591 
2592     /* protection profile length: 2 */
2593     buf[4] = 0x00;
2594     buf[5] = 0x02;
2595     profile_value = mbedtls_ssl_check_srtp_profile_value(
2596         ssl->dtls_srtp_info.chosen_dtls_srtp_profile);
2597     if (profile_value != MBEDTLS_TLS_SRTP_UNSET) {
2598         MBEDTLS_PUT_UINT16_BE(profile_value, buf, 6);
2599     } else {
2600         MBEDTLS_SSL_DEBUG_MSG(1, ("use_srtp extension invalid profile"));
2601         return;
2602     }
2603 
2604     buf[8] = mki_len & 0xFF;
2605     memcpy(&buf[9], ssl->dtls_srtp_info.mki_value, mki_len);
2606 
2607     *olen = 9 + mki_len;
2608 }
2609 #endif /* MBEDTLS_SSL_DTLS_SRTP */
2610 
2611 #if defined(MBEDTLS_SSL_DTLS_HELLO_VERIFY)
2612 MBEDTLS_CHECK_RETURN_CRITICAL
ssl_write_hello_verify_request(mbedtls_ssl_context * ssl)2613 static int ssl_write_hello_verify_request(mbedtls_ssl_context *ssl)
2614 {
2615     int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
2616     unsigned char *p = ssl->out_msg + 4;
2617     unsigned char *cookie_len_byte;
2618 
2619     MBEDTLS_SSL_DEBUG_MSG(2, ("=> write hello verify request"));
2620 
2621     /*
2622      * struct {
2623      *   ProtocolVersion server_version;
2624      *   opaque cookie<0..2^8-1>;
2625      * } HelloVerifyRequest;
2626      */
2627 
2628     /* The RFC is not clear on this point, but sending the actual negotiated
2629      * version looks like the most interoperable thing to do. */
2630     mbedtls_ssl_write_version(ssl->major_ver, ssl->minor_ver,
2631                               ssl->conf->transport, p);
2632     MBEDTLS_SSL_DEBUG_BUF(3, "server version", p, 2);
2633     p += 2;
2634 
2635     /* If we get here, f_cookie_check is not null */
2636     if (ssl->conf->f_cookie_write == NULL) {
2637         MBEDTLS_SSL_DEBUG_MSG(1, ("inconsistent cookie callbacks"));
2638         return MBEDTLS_ERR_SSL_INTERNAL_ERROR;
2639     }
2640 
2641     /* Skip length byte until we know the length */
2642     cookie_len_byte = p++;
2643 
2644     if ((ret = ssl->conf->f_cookie_write(ssl->conf->p_cookie,
2645                                          &p, ssl->out_buf + MBEDTLS_SSL_OUT_BUFFER_LEN,
2646                                          ssl->cli_id, ssl->cli_id_len)) != 0) {
2647         MBEDTLS_SSL_DEBUG_RET(1, "f_cookie_write", ret);
2648         return ret;
2649     }
2650 
2651     *cookie_len_byte = (unsigned char) (p - (cookie_len_byte + 1));
2652 
2653     MBEDTLS_SSL_DEBUG_BUF(3, "cookie sent", cookie_len_byte + 1, *cookie_len_byte);
2654 
2655     ssl->out_msglen  = p - ssl->out_msg;
2656     ssl->out_msgtype = MBEDTLS_SSL_MSG_HANDSHAKE;
2657     ssl->out_msg[0]  = MBEDTLS_SSL_HS_HELLO_VERIFY_REQUEST;
2658 
2659     ssl->state = MBEDTLS_SSL_SERVER_HELLO_VERIFY_REQUEST_SENT;
2660 
2661     if ((ret = mbedtls_ssl_write_handshake_msg(ssl)) != 0) {
2662         MBEDTLS_SSL_DEBUG_RET(1, "mbedtls_ssl_write_handshake_msg", ret);
2663         return ret;
2664     }
2665 
2666 #if defined(MBEDTLS_SSL_PROTO_DTLS)
2667     if (ssl->conf->transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM &&
2668         (ret = mbedtls_ssl_flight_transmit(ssl)) != 0) {
2669         MBEDTLS_SSL_DEBUG_RET(1, "mbedtls_ssl_flight_transmit", ret);
2670         return ret;
2671     }
2672 #endif /* MBEDTLS_SSL_PROTO_DTLS */
2673 
2674     MBEDTLS_SSL_DEBUG_MSG(2, ("<= write hello verify request"));
2675 
2676     return 0;
2677 }
2678 #endif /* MBEDTLS_SSL_DTLS_HELLO_VERIFY */
2679 
ssl_handle_id_based_session_resumption(mbedtls_ssl_context * ssl)2680 static void ssl_handle_id_based_session_resumption(mbedtls_ssl_context *ssl)
2681 {
2682     int ret;
2683     mbedtls_ssl_session session_tmp;
2684     mbedtls_ssl_session * const session = ssl->session_negotiate;
2685 
2686     /* Resume is 0  by default, see ssl_handshake_init().
2687      * It may be already set to 1 by ssl_parse_session_ticket_ext(). */
2688     if (ssl->handshake->resume == 1) {
2689         return;
2690     }
2691     if (session->id_len == 0) {
2692         return;
2693     }
2694     if (ssl->conf->f_get_cache == NULL) {
2695         return;
2696     }
2697 #if defined(MBEDTLS_SSL_RENEGOTIATION)
2698     if (ssl->renego_status != MBEDTLS_SSL_INITIAL_HANDSHAKE) {
2699         return;
2700     }
2701 #endif
2702 
2703     mbedtls_ssl_session_init(&session_tmp);
2704 
2705     session_tmp.id_len = session->id_len;
2706     memcpy(session_tmp.id, session->id, session->id_len);
2707 
2708     ret = ssl->conf->f_get_cache(ssl->conf->p_cache,
2709                                  &session_tmp);
2710     if (ret != 0) {
2711         goto exit;
2712     }
2713 
2714     if (session->ciphersuite != session_tmp.ciphersuite ||
2715         session->compression != session_tmp.compression) {
2716         /* Mismatch between cached and negotiated session */
2717         goto exit;
2718     }
2719 
2720     /* Move semantics */
2721     mbedtls_ssl_session_free(session);
2722     *session = session_tmp;
2723     memset(&session_tmp, 0, sizeof(session_tmp));
2724 
2725     MBEDTLS_SSL_DEBUG_MSG(3, ("session successfully restored from cache"));
2726     ssl->handshake->resume = 1;
2727 
2728 exit:
2729 
2730     mbedtls_ssl_session_free(&session_tmp);
2731 }
2732 
2733 MBEDTLS_CHECK_RETURN_CRITICAL
ssl_write_server_hello(mbedtls_ssl_context * ssl)2734 static int ssl_write_server_hello(mbedtls_ssl_context *ssl)
2735 {
2736 #if defined(MBEDTLS_HAVE_TIME)
2737     mbedtls_time_t t;
2738 #endif
2739     int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
2740     size_t olen, ext_len = 0, n;
2741     unsigned char *buf, *p;
2742 
2743     MBEDTLS_SSL_DEBUG_MSG(2, ("=> write server hello"));
2744 
2745 #if defined(MBEDTLS_SSL_DTLS_HELLO_VERIFY)
2746     if (ssl->conf->transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM &&
2747         ssl->handshake->verify_cookie_len != 0) {
2748         MBEDTLS_SSL_DEBUG_MSG(2, ("client hello was not authenticated"));
2749         MBEDTLS_SSL_DEBUG_MSG(2, ("<= write server hello"));
2750 
2751         return ssl_write_hello_verify_request(ssl);
2752     }
2753 #endif /* MBEDTLS_SSL_DTLS_HELLO_VERIFY */
2754 
2755     if (ssl->conf->f_rng == NULL) {
2756         MBEDTLS_SSL_DEBUG_MSG(1, ("no RNG provided"));
2757         return MBEDTLS_ERR_SSL_NO_RNG;
2758     }
2759 
2760     /*
2761      *     0  .   0   handshake type
2762      *     1  .   3   handshake length
2763      *     4  .   5   protocol version
2764      *     6  .   9   UNIX time()
2765      *    10  .  37   random bytes
2766      */
2767     buf = ssl->out_msg;
2768     p = buf + 4;
2769 
2770     mbedtls_ssl_write_version(ssl->major_ver, ssl->minor_ver,
2771                               ssl->conf->transport, p);
2772     p += 2;
2773 
2774     MBEDTLS_SSL_DEBUG_MSG(3, ("server hello, chosen version: [%d:%d]",
2775                               buf[4], buf[5]));
2776 
2777 #if defined(MBEDTLS_HAVE_TIME)
2778     t = mbedtls_time(NULL);
2779     MBEDTLS_PUT_UINT32_BE(t, p, 0);
2780     p += 4;
2781 
2782     MBEDTLS_SSL_DEBUG_MSG(3, ("server hello, current time: %" MBEDTLS_PRINTF_LONGLONG,
2783                               (long long) t));
2784 #else
2785     if ((ret = ssl->conf->f_rng(ssl->conf->p_rng, p, 4)) != 0) {
2786         return ret;
2787     }
2788 
2789     p += 4;
2790 #endif /* MBEDTLS_HAVE_TIME */
2791 
2792     if ((ret = ssl->conf->f_rng(ssl->conf->p_rng, p, 28)) != 0) {
2793         return ret;
2794     }
2795 
2796     p += 28;
2797 
2798     memcpy(ssl->handshake->randbytes + 32, buf + 6, 32);
2799 
2800     MBEDTLS_SSL_DEBUG_BUF(3, "server hello, random bytes", buf + 6, 32);
2801 
2802     ssl_handle_id_based_session_resumption(ssl);
2803 
2804     if (ssl->handshake->resume == 0) {
2805         /*
2806          * New session, create a new session id,
2807          * unless we're about to issue a session ticket
2808          */
2809         ssl->state++;
2810 
2811 #if defined(MBEDTLS_HAVE_TIME)
2812         ssl->session_negotiate->start = mbedtls_time(NULL);
2813 #endif
2814 
2815 #if defined(MBEDTLS_SSL_SESSION_TICKETS)
2816         if (ssl->handshake->new_session_ticket != 0) {
2817             ssl->session_negotiate->id_len = n = 0;
2818             memset(ssl->session_negotiate->id, 0, 32);
2819         } else
2820 #endif /* MBEDTLS_SSL_SESSION_TICKETS */
2821         {
2822             ssl->session_negotiate->id_len = n = 32;
2823             if ((ret = ssl->conf->f_rng(ssl->conf->p_rng, ssl->session_negotiate->id,
2824                                         n)) != 0) {
2825                 return ret;
2826             }
2827         }
2828     } else {
2829         /*
2830          * Resuming a session
2831          */
2832         n = ssl->session_negotiate->id_len;
2833         ssl->state = MBEDTLS_SSL_SERVER_CHANGE_CIPHER_SPEC;
2834 
2835         if ((ret = mbedtls_ssl_derive_keys(ssl)) != 0) {
2836             MBEDTLS_SSL_DEBUG_RET(1, "mbedtls_ssl_derive_keys", ret);
2837             return ret;
2838         }
2839     }
2840 
2841     /*
2842      *    38  .  38     session id length
2843      *    39  . 38+n    session id
2844      *   39+n . 40+n    chosen ciphersuite
2845      *   41+n . 41+n    chosen compression alg.
2846      *   42+n . 43+n    extensions length
2847      *   44+n . 43+n+m  extensions
2848      */
2849     *p++ = (unsigned char) ssl->session_negotiate->id_len;
2850     memcpy(p, ssl->session_negotiate->id, ssl->session_negotiate->id_len);
2851     p += ssl->session_negotiate->id_len;
2852 
2853     MBEDTLS_SSL_DEBUG_MSG(3, ("server hello, session id len.: %" MBEDTLS_PRINTF_SIZET, n));
2854     MBEDTLS_SSL_DEBUG_BUF(3,   "server hello, session id", buf + 39, n);
2855     MBEDTLS_SSL_DEBUG_MSG(3, ("%s session has been resumed",
2856                               ssl->handshake->resume ? "a" : "no"));
2857 
2858     MBEDTLS_PUT_UINT16_BE(ssl->session_negotiate->ciphersuite, p, 0);
2859     p += 2;
2860     *p++ = MBEDTLS_BYTE_0(ssl->session_negotiate->compression);
2861 
2862     MBEDTLS_SSL_DEBUG_MSG(3, ("server hello, chosen ciphersuite: %s",
2863                               mbedtls_ssl_get_ciphersuite_name(ssl->session_negotiate->ciphersuite)));
2864     MBEDTLS_SSL_DEBUG_MSG(3, ("server hello, compress alg.: 0x%02X",
2865                               (unsigned int) ssl->session_negotiate->compression));
2866 
2867     /* Do not write the extensions if the protocol is SSLv3 */
2868 #if defined(MBEDTLS_SSL_PROTO_SSL3)
2869     if ((ssl->major_ver != 3) || (ssl->minor_ver != 0)) {
2870 #endif
2871 
2872     /*
2873      *  First write extensions, then the total length
2874      */
2875     ssl_write_renegotiation_ext(ssl, p + 2 + ext_len, &olen);
2876     ext_len += olen;
2877 
2878 #if defined(MBEDTLS_SSL_MAX_FRAGMENT_LENGTH)
2879     ssl_write_max_fragment_length_ext(ssl, p + 2 + ext_len, &olen);
2880     ext_len += olen;
2881 #endif
2882 
2883 #if defined(MBEDTLS_SSL_TRUNCATED_HMAC)
2884     ssl_write_truncated_hmac_ext(ssl, p + 2 + ext_len, &olen);
2885     ext_len += olen;
2886 #endif
2887 
2888 #if defined(MBEDTLS_SSL_DTLS_CONNECTION_ID)
2889     ssl_write_cid_ext(ssl, p + 2 + ext_len, &olen);
2890     ext_len += olen;
2891 #endif
2892 
2893 #if defined(MBEDTLS_SSL_ENCRYPT_THEN_MAC)
2894     ssl_write_encrypt_then_mac_ext(ssl, p + 2 + ext_len, &olen);
2895     ext_len += olen;
2896 #endif
2897 
2898 #if defined(MBEDTLS_SSL_EXTENDED_MASTER_SECRET)
2899     ssl_write_extended_ms_ext(ssl, p + 2 + ext_len, &olen);
2900     ext_len += olen;
2901 #endif
2902 
2903 #if defined(MBEDTLS_SSL_SESSION_TICKETS)
2904     ssl_write_session_ticket_ext(ssl, p + 2 + ext_len, &olen);
2905     ext_len += olen;
2906 #endif
2907 
2908 #if defined(MBEDTLS_ECDH_C) || defined(MBEDTLS_ECDSA_C) || \
2909     defined(MBEDTLS_KEY_EXCHANGE_ECJPAKE_ENABLED)
2910     if (mbedtls_ssl_ciphersuite_uses_ec(
2911             mbedtls_ssl_ciphersuite_from_id(ssl->session_negotiate->ciphersuite))) {
2912         ssl_write_supported_point_formats_ext(ssl, p + 2 + ext_len, &olen);
2913         ext_len += olen;
2914     }
2915 #endif
2916 
2917 #if defined(MBEDTLS_KEY_EXCHANGE_ECJPAKE_ENABLED)
2918     ssl_write_ecjpake_kkpp_ext(ssl, p + 2 + ext_len, &olen);
2919     ext_len += olen;
2920 #endif
2921 
2922 #if defined(MBEDTLS_SSL_ALPN)
2923     ssl_write_alpn_ext(ssl, p + 2 + ext_len, &olen);
2924     ext_len += olen;
2925 #endif
2926 
2927 #if defined(MBEDTLS_SSL_DTLS_SRTP)
2928     ssl_write_use_srtp_ext(ssl, p + 2 + ext_len, &olen);
2929     ext_len += olen;
2930 #endif
2931 
2932     MBEDTLS_SSL_DEBUG_MSG(3, ("server hello, total extension length: %" MBEDTLS_PRINTF_SIZET,
2933                               ext_len));
2934 
2935     if (ext_len > 0) {
2936         MBEDTLS_PUT_UINT16_BE(ext_len, p, 0);
2937         p += 2 + ext_len;
2938     }
2939 
2940 #if defined(MBEDTLS_SSL_PROTO_SSL3)
2941 }
2942 #endif
2943 
2944     ssl->out_msglen  = p - buf;
2945     ssl->out_msgtype = MBEDTLS_SSL_MSG_HANDSHAKE;
2946     ssl->out_msg[0]  = MBEDTLS_SSL_HS_SERVER_HELLO;
2947 
2948     ret = mbedtls_ssl_write_handshake_msg(ssl);
2949 
2950     MBEDTLS_SSL_DEBUG_MSG(2, ("<= write server hello"));
2951 
2952     return ret;
2953 }
2954 
2955 #if !defined(MBEDTLS_KEY_EXCHANGE_CERT_REQ_ALLOWED_ENABLED)
2956 MBEDTLS_CHECK_RETURN_CRITICAL
ssl_write_certificate_request(mbedtls_ssl_context * ssl)2957 static int ssl_write_certificate_request(mbedtls_ssl_context *ssl)
2958 {
2959     const mbedtls_ssl_ciphersuite_t *ciphersuite_info =
2960         ssl->handshake->ciphersuite_info;
2961 
2962     MBEDTLS_SSL_DEBUG_MSG(2, ("=> write certificate request"));
2963 
2964     if (!mbedtls_ssl_ciphersuite_cert_req_allowed(ciphersuite_info)) {
2965         MBEDTLS_SSL_DEBUG_MSG(2, ("<= skip write certificate request"));
2966         ssl->state++;
2967         return 0;
2968     }
2969 
2970     MBEDTLS_SSL_DEBUG_MSG(1, ("should never happen"));
2971     return MBEDTLS_ERR_SSL_INTERNAL_ERROR;
2972 }
2973 #else /* !MBEDTLS_KEY_EXCHANGE_CERT_REQ_ALLOWED_ENABLED */
2974 MBEDTLS_CHECK_RETURN_CRITICAL
ssl_write_certificate_request(mbedtls_ssl_context * ssl)2975 static int ssl_write_certificate_request(mbedtls_ssl_context *ssl)
2976 {
2977     int ret = MBEDTLS_ERR_SSL_FEATURE_UNAVAILABLE;
2978     const mbedtls_ssl_ciphersuite_t *ciphersuite_info =
2979         ssl->handshake->ciphersuite_info;
2980     uint16_t dn_size, total_dn_size; /* excluding length bytes */
2981     size_t ct_len, sa_len; /* including length bytes */
2982     unsigned char *buf, *p;
2983     const unsigned char * const end = ssl->out_msg + MBEDTLS_SSL_OUT_CONTENT_LEN;
2984     const mbedtls_x509_crt *crt;
2985     int authmode;
2986 
2987     MBEDTLS_SSL_DEBUG_MSG(2, ("=> write certificate request"));
2988 
2989     ssl->state++;
2990 
2991 #if defined(MBEDTLS_SSL_SERVER_NAME_INDICATION)
2992     if (ssl->handshake->sni_authmode != MBEDTLS_SSL_VERIFY_UNSET) {
2993         authmode = ssl->handshake->sni_authmode;
2994     } else
2995 #endif
2996     authmode = ssl->conf->authmode;
2997 
2998     if (!mbedtls_ssl_ciphersuite_cert_req_allowed(ciphersuite_info) ||
2999         authmode == MBEDTLS_SSL_VERIFY_NONE) {
3000         MBEDTLS_SSL_DEBUG_MSG(2, ("<= skip write certificate request"));
3001         return 0;
3002     }
3003 
3004     /*
3005      *     0  .   0   handshake type
3006      *     1  .   3   handshake length
3007      *     4  .   4   cert type count
3008      *     5  .. m-1  cert types
3009      *     m  .. m+1  sig alg length (TLS 1.2 only)
3010      *    m+1 .. n-1  SignatureAndHashAlgorithms (TLS 1.2 only)
3011      *     n  .. n+1  length of all DNs
3012      *    n+2 .. n+3  length of DN 1
3013      *    n+4 .. ...  Distinguished Name #1
3014      *    ... .. ...  length of DN 2, etc.
3015      */
3016     buf = ssl->out_msg;
3017     p = buf + 4;
3018 
3019     /*
3020      * Supported certificate types
3021      *
3022      *     ClientCertificateType certificate_types<1..2^8-1>;
3023      *     enum { (255) } ClientCertificateType;
3024      */
3025     ct_len = 0;
3026 
3027 #if defined(MBEDTLS_RSA_C)
3028     p[1 + ct_len++] = MBEDTLS_SSL_CERT_TYPE_RSA_SIGN;
3029 #endif
3030 #if defined(MBEDTLS_ECDSA_C)
3031     p[1 + ct_len++] = MBEDTLS_SSL_CERT_TYPE_ECDSA_SIGN;
3032 #endif
3033 
3034     p[0] = (unsigned char) ct_len++;
3035     p += ct_len;
3036 
3037     sa_len = 0;
3038 #if defined(MBEDTLS_SSL_PROTO_TLS1_2)
3039     /*
3040      * Add signature_algorithms for verify (TLS 1.2)
3041      *
3042      *     SignatureAndHashAlgorithm supported_signature_algorithms<2..2^16-2>;
3043      *
3044      *     struct {
3045      *           HashAlgorithm hash;
3046      *           SignatureAlgorithm signature;
3047      *     } SignatureAndHashAlgorithm;
3048      *
3049      *     enum { (255) } HashAlgorithm;
3050      *     enum { (255) } SignatureAlgorithm;
3051      */
3052     if (ssl->minor_ver == MBEDTLS_SSL_MINOR_VERSION_3) {
3053         const int *cur;
3054 
3055         /*
3056          * Supported signature algorithms
3057          */
3058         for (cur = ssl->conf->sig_hashes; *cur != MBEDTLS_MD_NONE; cur++) {
3059             unsigned char hash = mbedtls_ssl_hash_from_md_alg(*cur);
3060 
3061             if (MBEDTLS_SSL_HASH_NONE == hash || mbedtls_ssl_set_calc_verify_md(ssl, hash)) {
3062                 continue;
3063             }
3064 
3065 #if defined(MBEDTLS_RSA_C)
3066             p[2 + sa_len++] = hash;
3067             p[2 + sa_len++] = MBEDTLS_SSL_SIG_RSA;
3068 #endif
3069 #if defined(MBEDTLS_ECDSA_C)
3070             p[2 + sa_len++] = hash;
3071             p[2 + sa_len++] = MBEDTLS_SSL_SIG_ECDSA;
3072 #endif
3073         }
3074 
3075         MBEDTLS_PUT_UINT16_BE(sa_len, p, 0);
3076         sa_len += 2;
3077         p += sa_len;
3078     }
3079 #endif /* MBEDTLS_SSL_PROTO_TLS1_2 */
3080 
3081     /*
3082      * DistinguishedName certificate_authorities<0..2^16-1>;
3083      * opaque DistinguishedName<1..2^16-1>;
3084      */
3085     p += 2;
3086 
3087     total_dn_size = 0;
3088 
3089     if (ssl->conf->cert_req_ca_list ==  MBEDTLS_SSL_CERT_REQ_CA_LIST_ENABLED) {
3090         /* NOTE: If trusted certificates are provisioned
3091          *       via a CA callback (configured through
3092          *       `mbedtls_ssl_conf_ca_cb()`, then the
3093          *       CertificateRequest is currently left empty. */
3094 
3095 #if defined(MBEDTLS_SSL_SERVER_NAME_INDICATION)
3096         if (ssl->handshake->sni_ca_chain != NULL) {
3097             crt = ssl->handshake->sni_ca_chain;
3098         } else
3099 #endif
3100         crt = ssl->conf->ca_chain;
3101 
3102         while (crt != NULL && crt->version != 0) {
3103             /* It follows from RFC 5280 A.1 that this length
3104              * can be represented in at most 11 bits. */
3105             dn_size = (uint16_t) crt->subject_raw.len;
3106 
3107             if (end < p || (size_t) (end - p) < 2 + (size_t) dn_size) {
3108                 MBEDTLS_SSL_DEBUG_MSG(1, ("skipping CAs: buffer too short"));
3109                 break;
3110             }
3111 
3112             MBEDTLS_PUT_UINT16_BE(dn_size, p, 0);
3113             p += 2;
3114             memcpy(p, crt->subject_raw.p, dn_size);
3115             p += dn_size;
3116 
3117             MBEDTLS_SSL_DEBUG_BUF(3, "requested DN", p - dn_size, dn_size);
3118 
3119             total_dn_size += 2 + dn_size;
3120             crt = crt->next;
3121         }
3122     }
3123 
3124     ssl->out_msglen  = p - buf;
3125     ssl->out_msgtype = MBEDTLS_SSL_MSG_HANDSHAKE;
3126     ssl->out_msg[0]  = MBEDTLS_SSL_HS_CERTIFICATE_REQUEST;
3127     MBEDTLS_PUT_UINT16_BE(total_dn_size, ssl->out_msg, 4 + ct_len + sa_len);
3128 
3129     ret = mbedtls_ssl_write_handshake_msg(ssl);
3130 
3131     MBEDTLS_SSL_DEBUG_MSG(2, ("<= write certificate request"));
3132 
3133     return ret;
3134 }
3135 #endif /* MBEDTLS_KEY_EXCHANGE_CERT_REQ_ALLOWED_ENABLED */
3136 
3137 #if defined(MBEDTLS_KEY_EXCHANGE_ECDH_RSA_ENABLED) || \
3138     defined(MBEDTLS_KEY_EXCHANGE_ECDH_ECDSA_ENABLED)
3139 MBEDTLS_CHECK_RETURN_CRITICAL
ssl_get_ecdh_params_from_cert(mbedtls_ssl_context * ssl)3140 static int ssl_get_ecdh_params_from_cert(mbedtls_ssl_context *ssl)
3141 {
3142     int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
3143     mbedtls_pk_context *own_key = mbedtls_ssl_own_key(ssl);
3144 
3145     /* Check if the key is a transparent ECDH key.
3146      * This also ensures that it is safe to call mbedtls_pk_ec(). */
3147     if (mbedtls_pk_get_type(own_key) != MBEDTLS_PK_ECKEY &&
3148         mbedtls_pk_get_type(own_key) != MBEDTLS_PK_ECKEY_DH) {
3149         MBEDTLS_SSL_DEBUG_MSG(1, ("server key not ECDH capable"));
3150         return MBEDTLS_ERR_SSL_PK_TYPE_MISMATCH;
3151     }
3152 
3153     if ((ret = mbedtls_ecdh_get_params(&ssl->handshake->ecdh_ctx,
3154                                        mbedtls_pk_ec(*own_key),
3155                                        MBEDTLS_ECDH_OURS)) != 0) {
3156         MBEDTLS_SSL_DEBUG_RET(1, ("mbedtls_ecdh_get_params"), ret);
3157         return ret;
3158     }
3159 
3160     return 0;
3161 }
3162 #endif /* MBEDTLS_KEY_EXCHANGE_ECDH_RSA_ENABLED) ||
3163           MBEDTLS_KEY_EXCHANGE_ECDH_ECDSA_ENABLED */
3164 
3165 #if defined(MBEDTLS_KEY_EXCHANGE_WITH_SERVER_SIGNATURE_ENABLED) && \
3166     defined(MBEDTLS_SSL_ASYNC_PRIVATE)
3167 MBEDTLS_CHECK_RETURN_CRITICAL
ssl_resume_server_key_exchange(mbedtls_ssl_context * ssl,size_t * signature_len)3168 static int ssl_resume_server_key_exchange(mbedtls_ssl_context *ssl,
3169                                           size_t *signature_len)
3170 {
3171     /* Append the signature to ssl->out_msg, leaving 2 bytes for the
3172      * signature length which will be added in ssl_write_server_key_exchange
3173      * after the call to ssl_prepare_server_key_exchange.
3174      * ssl_write_server_key_exchange also takes care of incrementing
3175      * ssl->out_msglen. */
3176     unsigned char *sig_start = ssl->out_msg + ssl->out_msglen + 2;
3177     size_t sig_max_len = (ssl->out_buf + MBEDTLS_SSL_OUT_CONTENT_LEN
3178                           - sig_start);
3179     int ret = ssl->conf->f_async_resume(ssl,
3180                                         sig_start, signature_len, sig_max_len);
3181     if (ret != MBEDTLS_ERR_SSL_ASYNC_IN_PROGRESS) {
3182         ssl->handshake->async_in_progress = 0;
3183         mbedtls_ssl_set_async_operation_data(ssl, NULL);
3184     }
3185     MBEDTLS_SSL_DEBUG_RET(2, "ssl_resume_server_key_exchange", ret);
3186     return ret;
3187 }
3188 #endif /* defined(MBEDTLS_KEY_EXCHANGE_WITH_SERVER_SIGNATURE_ENABLED) &&
3189           defined(MBEDTLS_SSL_ASYNC_PRIVATE) */
3190 
3191 /* Prepare the ServerKeyExchange message, up to and including
3192  * calculating the signature if any, but excluding formatting the
3193  * signature and sending the message. */
3194 MBEDTLS_CHECK_RETURN_CRITICAL
ssl_prepare_server_key_exchange(mbedtls_ssl_context * ssl,size_t * signature_len)3195 static int ssl_prepare_server_key_exchange(mbedtls_ssl_context *ssl,
3196                                            size_t *signature_len)
3197 {
3198     const mbedtls_ssl_ciphersuite_t *ciphersuite_info =
3199         ssl->handshake->ciphersuite_info;
3200 
3201 #if defined(MBEDTLS_KEY_EXCHANGE_SOME_PFS_ENABLED)
3202 #if defined(MBEDTLS_KEY_EXCHANGE_WITH_SERVER_SIGNATURE_ENABLED)
3203     unsigned char *dig_signed = NULL;
3204 #endif /* MBEDTLS_KEY_EXCHANGE_WITH_SERVER_SIGNATURE_ENABLED */
3205 #endif /* MBEDTLS_KEY_EXCHANGE_SOME_PFS_ENABLED */
3206 
3207     (void) ciphersuite_info; /* unused in some configurations */
3208 #if !defined(MBEDTLS_KEY_EXCHANGE_WITH_SERVER_SIGNATURE_ENABLED)
3209     (void) signature_len;
3210 #endif /* MBEDTLS_KEY_EXCHANGE_WITH_SERVER_SIGNATURE_ENABLED */
3211 
3212     ssl->out_msglen = 4; /* header (type:1, length:3) to be written later */
3213 
3214     /*
3215      *
3216      * Part 1: Provide key exchange parameters for chosen ciphersuite.
3217      *
3218      */
3219 
3220     /*
3221      * - ECJPAKE key exchanges
3222      */
3223 #if defined(MBEDTLS_KEY_EXCHANGE_ECJPAKE_ENABLED)
3224     if (ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_ECJPAKE) {
3225         int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
3226         size_t len = 0;
3227 
3228         ret = mbedtls_ecjpake_write_round_two(
3229             &ssl->handshake->ecjpake_ctx,
3230             ssl->out_msg + ssl->out_msglen,
3231             MBEDTLS_SSL_OUT_CONTENT_LEN - ssl->out_msglen, &len,
3232             ssl->conf->f_rng, ssl->conf->p_rng);
3233         if (ret != 0) {
3234             MBEDTLS_SSL_DEBUG_RET(1, "mbedtls_ecjpake_write_round_two", ret);
3235             return ret;
3236         }
3237 
3238         ssl->out_msglen += len;
3239     }
3240 #endif /* MBEDTLS_KEY_EXCHANGE_ECJPAKE_ENABLED */
3241 
3242     /*
3243      * For (EC)DHE key exchanges with PSK, parameters are prefixed by support
3244      * identity hint (RFC 4279, Sec. 3). Until someone needs this feature,
3245      * we use empty support identity hints here.
3246      **/
3247 #if defined(MBEDTLS_KEY_EXCHANGE_DHE_PSK_ENABLED)   || \
3248     defined(MBEDTLS_KEY_EXCHANGE_ECDHE_PSK_ENABLED)
3249     if (ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_DHE_PSK ||
3250         ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_ECDHE_PSK) {
3251         ssl->out_msg[ssl->out_msglen++] = 0x00;
3252         ssl->out_msg[ssl->out_msglen++] = 0x00;
3253     }
3254 #endif /* MBEDTLS_KEY_EXCHANGE_DHE_PSK_ENABLED ||
3255           MBEDTLS_KEY_EXCHANGE_ECDHE_PSK_ENABLED */
3256 
3257     /*
3258      * - DHE key exchanges
3259      */
3260 #if defined(MBEDTLS_KEY_EXCHANGE_SOME_DHE_ENABLED)
3261     if (mbedtls_ssl_ciphersuite_uses_dhe(ciphersuite_info)) {
3262         int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
3263         size_t len = 0;
3264 
3265         if (ssl->conf->dhm_P.p == NULL || ssl->conf->dhm_G.p == NULL) {
3266             MBEDTLS_SSL_DEBUG_MSG(1, ("no DH parameters set"));
3267             return MBEDTLS_ERR_SSL_BAD_INPUT_DATA;
3268         }
3269 
3270         /*
3271          * Ephemeral DH parameters:
3272          *
3273          * struct {
3274          *     opaque dh_p<1..2^16-1>;
3275          *     opaque dh_g<1..2^16-1>;
3276          *     opaque dh_Ys<1..2^16-1>;
3277          * } ServerDHParams;
3278          */
3279         if ((ret = mbedtls_dhm_set_group(&ssl->handshake->dhm_ctx,
3280                                          &ssl->conf->dhm_P,
3281                                          &ssl->conf->dhm_G)) != 0) {
3282             MBEDTLS_SSL_DEBUG_RET(1, "mbedtls_dhm_set_group", ret);
3283             return ret;
3284         }
3285 
3286         if ((ret = mbedtls_dhm_make_params(
3287                  &ssl->handshake->dhm_ctx,
3288                  (int) mbedtls_mpi_size(&ssl->handshake->dhm_ctx.P),
3289                  ssl->out_msg + ssl->out_msglen, &len,
3290                  ssl->conf->f_rng, ssl->conf->p_rng)) != 0) {
3291             MBEDTLS_SSL_DEBUG_RET(1, "mbedtls_dhm_make_params", ret);
3292             return ret;
3293         }
3294 
3295 #if defined(MBEDTLS_KEY_EXCHANGE_WITH_SERVER_SIGNATURE_ENABLED)
3296         dig_signed = ssl->out_msg + ssl->out_msglen;
3297 #endif
3298 
3299         ssl->out_msglen += len;
3300 
3301         MBEDTLS_SSL_DEBUG_MPI(3, "DHM: X ", &ssl->handshake->dhm_ctx.X);
3302         MBEDTLS_SSL_DEBUG_MPI(3, "DHM: P ", &ssl->handshake->dhm_ctx.P);
3303         MBEDTLS_SSL_DEBUG_MPI(3, "DHM: G ", &ssl->handshake->dhm_ctx.G);
3304         MBEDTLS_SSL_DEBUG_MPI(3, "DHM: GX", &ssl->handshake->dhm_ctx.GX);
3305     }
3306 #endif /* MBEDTLS_KEY_EXCHANGE_SOME_DHE_ENABLED */
3307 
3308     /*
3309      * - ECDHE key exchanges
3310      */
3311 #if defined(MBEDTLS_KEY_EXCHANGE_SOME_ECDHE_ENABLED)
3312     if (mbedtls_ssl_ciphersuite_uses_ecdhe(ciphersuite_info)) {
3313         /*
3314          * Ephemeral ECDH parameters:
3315          *
3316          * struct {
3317          *     ECParameters curve_params;
3318          *     ECPoint      public;
3319          * } ServerECDHParams;
3320          */
3321         const mbedtls_ecp_curve_info **curve = NULL;
3322         const mbedtls_ecp_group_id *gid;
3323         int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
3324         size_t len = 0;
3325 
3326         /* Match our preference list against the offered curves */
3327         for (gid = ssl->conf->curve_list; *gid != MBEDTLS_ECP_DP_NONE; gid++) {
3328             for (curve = ssl->handshake->curves; *curve != NULL; curve++) {
3329                 if ((*curve)->grp_id == *gid) {
3330                     goto curve_matching_done;
3331                 }
3332             }
3333         }
3334 
3335 curve_matching_done:
3336         if (curve == NULL || *curve == NULL) {
3337             MBEDTLS_SSL_DEBUG_MSG(1, ("no matching curve for ECDHE"));
3338             return MBEDTLS_ERR_SSL_NO_CIPHER_CHOSEN;
3339         }
3340 
3341         MBEDTLS_SSL_DEBUG_MSG(2, ("ECDHE curve: %s", (*curve)->name));
3342 
3343         if ((ret = mbedtls_ecdh_setup(&ssl->handshake->ecdh_ctx,
3344                                       (*curve)->grp_id)) != 0) {
3345             MBEDTLS_SSL_DEBUG_RET(1, "mbedtls_ecp_group_load", ret);
3346             return ret;
3347         }
3348 
3349         if ((ret = mbedtls_ecdh_make_params(
3350                  &ssl->handshake->ecdh_ctx, &len,
3351                  ssl->out_msg + ssl->out_msglen,
3352                  MBEDTLS_SSL_OUT_CONTENT_LEN - ssl->out_msglen,
3353                  ssl->conf->f_rng, ssl->conf->p_rng)) != 0) {
3354             MBEDTLS_SSL_DEBUG_RET(1, "mbedtls_ecdh_make_params", ret);
3355             return ret;
3356         }
3357 
3358 #if defined(MBEDTLS_KEY_EXCHANGE_WITH_SERVER_SIGNATURE_ENABLED)
3359         dig_signed = ssl->out_msg + ssl->out_msglen;
3360 #endif
3361 
3362         ssl->out_msglen += len;
3363 
3364         MBEDTLS_SSL_DEBUG_ECDH(3, &ssl->handshake->ecdh_ctx,
3365                                MBEDTLS_DEBUG_ECDH_Q);
3366     }
3367 #endif /* MBEDTLS_KEY_EXCHANGE_SOME_ECDHE_ENABLED */
3368 
3369     /*
3370      *
3371      * Part 2: For key exchanges involving the server signing the
3372      *         exchange parameters, compute and add the signature here.
3373      *
3374      */
3375 #if defined(MBEDTLS_KEY_EXCHANGE_WITH_SERVER_SIGNATURE_ENABLED)
3376     if (mbedtls_ssl_ciphersuite_uses_server_signature(ciphersuite_info)) {
3377         size_t dig_signed_len = ssl->out_msg + ssl->out_msglen - dig_signed;
3378         size_t hashlen = 0;
3379 #if defined(MBEDTLS_USE_PSA_CRYPTO)
3380         unsigned char hash[PSA_HASH_MAX_SIZE];
3381 #else
3382         unsigned char hash[MBEDTLS_MD_MAX_SIZE];
3383 #endif
3384         int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
3385 
3386         /*
3387          * 2.1: Choose hash algorithm:
3388          * A: For TLS 1.2, obey signature-hash-algorithm extension
3389          *    to choose appropriate hash.
3390          * B: For SSL3, TLS1.0, TLS1.1 and ECDHE_ECDSA, use SHA1
3391          *    (RFC 4492, Sec. 5.4)
3392          * C: Otherwise, use MD5 + SHA1 (RFC 4346, Sec. 7.4.3)
3393          */
3394 
3395         mbedtls_md_type_t md_alg;
3396 
3397 #if defined(MBEDTLS_SSL_PROTO_TLS1_2)
3398         mbedtls_pk_type_t sig_alg =
3399             mbedtls_ssl_get_ciphersuite_sig_pk_alg(ciphersuite_info);
3400         if (ssl->minor_ver == MBEDTLS_SSL_MINOR_VERSION_3) {
3401             /* A: For TLS 1.2, obey signature-hash-algorithm extension
3402              *    (RFC 5246, Sec. 7.4.1.4.1). */
3403             if (sig_alg == MBEDTLS_PK_NONE ||
3404                 (md_alg = mbedtls_ssl_sig_hash_set_find(&ssl->handshake->hash_algs,
3405                                                         sig_alg)) == MBEDTLS_MD_NONE) {
3406                 MBEDTLS_SSL_DEBUG_MSG(1, ("should never happen"));
3407                 /* (... because we choose a cipher suite
3408                  *      only if there is a matching hash.) */
3409                 return MBEDTLS_ERR_SSL_INTERNAL_ERROR;
3410             }
3411         } else
3412 #endif /* MBEDTLS_SSL_PROTO_TLS1_2 */
3413 #if defined(MBEDTLS_SSL_PROTO_SSL3) || defined(MBEDTLS_SSL_PROTO_TLS1) || \
3414         defined(MBEDTLS_SSL_PROTO_TLS1_1)
3415         if (ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_ECDHE_ECDSA) {
3416             /* B: Default hash SHA1 */
3417             md_alg = MBEDTLS_MD_SHA1;
3418         } else
3419 #endif /* MBEDTLS_SSL_PROTO_SSL3 || MBEDTLS_SSL_PROTO_TLS1 || \
3420           MBEDTLS_SSL_PROTO_TLS1_1 */
3421         {
3422             /* C: MD5 + SHA1 */
3423             md_alg = MBEDTLS_MD_NONE;
3424         }
3425 
3426         MBEDTLS_SSL_DEBUG_MSG(3, ("pick hash algorithm %u for signing", (unsigned) md_alg));
3427 
3428         /*
3429          * 2.2: Compute the hash to be signed
3430          */
3431 #if defined(MBEDTLS_SSL_PROTO_SSL3) || defined(MBEDTLS_SSL_PROTO_TLS1) || \
3432         defined(MBEDTLS_SSL_PROTO_TLS1_1)
3433         if (md_alg == MBEDTLS_MD_NONE) {
3434             hashlen = 36;
3435             ret = mbedtls_ssl_get_key_exchange_md_ssl_tls(ssl, hash,
3436                                                           dig_signed,
3437                                                           dig_signed_len);
3438             if (ret != 0) {
3439                 return ret;
3440             }
3441         } else
3442 #endif /* MBEDTLS_SSL_PROTO_SSL3 || MBEDTLS_SSL_PROTO_TLS1 || \
3443           MBEDTLS_SSL_PROTO_TLS1_1 */
3444 #if defined(MBEDTLS_SSL_PROTO_TLS1) || defined(MBEDTLS_SSL_PROTO_TLS1_1) || \
3445         defined(MBEDTLS_SSL_PROTO_TLS1_2)
3446         if (md_alg != MBEDTLS_MD_NONE) {
3447             ret = mbedtls_ssl_get_key_exchange_md_tls1_2(ssl, hash, &hashlen,
3448                                                          dig_signed,
3449                                                          dig_signed_len,
3450                                                          md_alg);
3451             if (ret != 0) {
3452                 return ret;
3453             }
3454         } else
3455 #endif /* MBEDTLS_SSL_PROTO_TLS1 || MBEDTLS_SSL_PROTO_TLS1_1 || \
3456           MBEDTLS_SSL_PROTO_TLS1_2 */
3457         {
3458             MBEDTLS_SSL_DEBUG_MSG(1, ("should never happen"));
3459             return MBEDTLS_ERR_SSL_INTERNAL_ERROR;
3460         }
3461 
3462         MBEDTLS_SSL_DEBUG_BUF(3, "parameters hash", hash, hashlen);
3463 
3464         /*
3465          * 2.3: Compute and add the signature
3466          */
3467 #if defined(MBEDTLS_SSL_PROTO_TLS1_2)
3468         if (ssl->minor_ver == MBEDTLS_SSL_MINOR_VERSION_3) {
3469             /*
3470              * For TLS 1.2, we need to specify signature and hash algorithm
3471              * explicitly through a prefix to the signature.
3472              *
3473              * struct {
3474              *    HashAlgorithm hash;
3475              *    SignatureAlgorithm signature;
3476              * } SignatureAndHashAlgorithm;
3477              *
3478              * struct {
3479              *    SignatureAndHashAlgorithm algorithm;
3480              *    opaque signature<0..2^16-1>;
3481              * } DigitallySigned;
3482              *
3483              */
3484 
3485             ssl->out_msg[ssl->out_msglen++] =
3486                 mbedtls_ssl_hash_from_md_alg(md_alg);
3487             ssl->out_msg[ssl->out_msglen++] =
3488                 mbedtls_ssl_sig_from_pk_alg(sig_alg);
3489         }
3490 #endif /* MBEDTLS_SSL_PROTO_TLS1_2 */
3491 
3492 #if defined(MBEDTLS_SSL_ASYNC_PRIVATE)
3493         if (ssl->conf->f_async_sign_start != NULL) {
3494             ret = ssl->conf->f_async_sign_start(ssl,
3495                                                 mbedtls_ssl_own_cert(ssl),
3496                                                 md_alg, hash, hashlen);
3497             switch (ret) {
3498                 case MBEDTLS_ERR_SSL_HW_ACCEL_FALLTHROUGH:
3499                     /* act as if f_async_sign was null */
3500                     break;
3501                 case 0:
3502                     ssl->handshake->async_in_progress = 1;
3503                     return ssl_resume_server_key_exchange(ssl, signature_len);
3504                 case MBEDTLS_ERR_SSL_ASYNC_IN_PROGRESS:
3505                     ssl->handshake->async_in_progress = 1;
3506                     return MBEDTLS_ERR_SSL_ASYNC_IN_PROGRESS;
3507                 default:
3508                     MBEDTLS_SSL_DEBUG_RET(1, "f_async_sign_start", ret);
3509                     return ret;
3510             }
3511         }
3512 #endif /* MBEDTLS_SSL_ASYNC_PRIVATE */
3513 
3514         if (mbedtls_ssl_own_key(ssl) == NULL) {
3515             MBEDTLS_SSL_DEBUG_MSG(1, ("got no private key"));
3516             return MBEDTLS_ERR_SSL_PRIVATE_KEY_REQUIRED;
3517         }
3518 
3519         /* Append the signature to ssl->out_msg, leaving 2 bytes for the
3520          * signature length which will be added in ssl_write_server_key_exchange
3521          * after the call to ssl_prepare_server_key_exchange.
3522          * ssl_write_server_key_exchange also takes care of incrementing
3523          * ssl->out_msglen. */
3524         if ((ret = mbedtls_pk_sign(mbedtls_ssl_own_key(ssl),
3525                                    md_alg, hash, hashlen,
3526                                    ssl->out_msg + ssl->out_msglen + 2,
3527                                    signature_len,
3528                                    ssl->conf->f_rng,
3529                                    ssl->conf->p_rng)) != 0) {
3530             MBEDTLS_SSL_DEBUG_RET(1, "mbedtls_pk_sign", ret);
3531             return ret;
3532         }
3533     }
3534 #endif /* MBEDTLS_KEY_EXCHANGE_WITH_SERVER_SIGNATURE_ENABLED */
3535 
3536     return 0;
3537 }
3538 
3539 /* Prepare the ServerKeyExchange message and send it. For ciphersuites
3540  * that do not include a ServerKeyExchange message, do nothing. Either
3541  * way, if successful, move on to the next step in the SSL state
3542  * machine. */
3543 MBEDTLS_CHECK_RETURN_CRITICAL
ssl_write_server_key_exchange(mbedtls_ssl_context * ssl)3544 static int ssl_write_server_key_exchange(mbedtls_ssl_context *ssl)
3545 {
3546     int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
3547     size_t signature_len = 0;
3548 #if defined(MBEDTLS_KEY_EXCHANGE_SOME_NON_PFS_ENABLED)
3549     const mbedtls_ssl_ciphersuite_t *ciphersuite_info =
3550         ssl->handshake->ciphersuite_info;
3551 #endif /* MBEDTLS_KEY_EXCHANGE_SOME_NON_PFS_ENABLED */
3552 
3553     MBEDTLS_SSL_DEBUG_MSG(2, ("=> write server key exchange"));
3554 
3555 #if defined(MBEDTLS_KEY_EXCHANGE_SOME_NON_PFS_ENABLED)
3556     /* Extract static ECDH parameters and abort if ServerKeyExchange
3557      * is not needed. */
3558     if (mbedtls_ssl_ciphersuite_no_pfs(ciphersuite_info)) {
3559         /* For suites involving ECDH, extract DH parameters
3560          * from certificate at this point. */
3561 #if defined(MBEDTLS_KEY_EXCHANGE_SOME_ECDH_ENABLED)
3562         if (mbedtls_ssl_ciphersuite_uses_ecdh(ciphersuite_info)) {
3563             ret = ssl_get_ecdh_params_from_cert(ssl);
3564             if (ret != 0) {
3565                 MBEDTLS_SSL_DEBUG_RET(1, "ssl_get_ecdh_params_from_cert", ret);
3566                 return ret;
3567             }
3568         }
3569 #endif /* MBEDTLS_KEY_EXCHANGE_SOME_ECDH_ENABLED */
3570 
3571         /* Key exchanges not involving ephemeral keys don't use
3572          * ServerKeyExchange, so end here. */
3573         MBEDTLS_SSL_DEBUG_MSG(2, ("<= skip write server key exchange"));
3574         ssl->state++;
3575         return 0;
3576     }
3577 #endif /* MBEDTLS_KEY_EXCHANGE_SOME_NON_PFS_ENABLED */
3578 
3579 #if defined(MBEDTLS_KEY_EXCHANGE_WITH_SERVER_SIGNATURE_ENABLED) && \
3580     defined(MBEDTLS_SSL_ASYNC_PRIVATE)
3581     /* If we have already prepared the message and there is an ongoing
3582      * signature operation, resume signing. */
3583     if (ssl->handshake->async_in_progress != 0) {
3584         MBEDTLS_SSL_DEBUG_MSG(2, ("resuming signature operation"));
3585         ret = ssl_resume_server_key_exchange(ssl, &signature_len);
3586     } else
3587 #endif /* defined(MBEDTLS_KEY_EXCHANGE_WITH_SERVER_SIGNATURE_ENABLED) &&
3588           defined(MBEDTLS_SSL_ASYNC_PRIVATE) */
3589     {
3590         /* ServerKeyExchange is needed. Prepare the message. */
3591         ret = ssl_prepare_server_key_exchange(ssl, &signature_len);
3592     }
3593 
3594     if (ret != 0) {
3595         /* If we're starting to write a new message, set ssl->out_msglen
3596          * to 0. But if we're resuming after an asynchronous message,
3597          * out_msglen is the amount of data written so far and mst be
3598          * preserved. */
3599         if (ret == MBEDTLS_ERR_SSL_ASYNC_IN_PROGRESS) {
3600             MBEDTLS_SSL_DEBUG_MSG(2, ("<= write server key exchange (pending)"));
3601         } else {
3602             ssl->out_msglen = 0;
3603         }
3604         return ret;
3605     }
3606 
3607     /* If there is a signature, write its length.
3608      * ssl_prepare_server_key_exchange already wrote the signature
3609      * itself at its proper place in the output buffer. */
3610 #if defined(MBEDTLS_KEY_EXCHANGE_WITH_SERVER_SIGNATURE_ENABLED)
3611     if (signature_len != 0) {
3612         ssl->out_msg[ssl->out_msglen++] = MBEDTLS_BYTE_1(signature_len);
3613         ssl->out_msg[ssl->out_msglen++] = MBEDTLS_BYTE_0(signature_len);
3614 
3615         MBEDTLS_SSL_DEBUG_BUF(3, "my signature",
3616                               ssl->out_msg + ssl->out_msglen,
3617                               signature_len);
3618 
3619         /* Skip over the already-written signature */
3620         ssl->out_msglen += signature_len;
3621     }
3622 #endif /* MBEDTLS_KEY_EXCHANGE_WITH_SERVER_SIGNATURE_ENABLED */
3623 
3624     /* Add header and send. */
3625     ssl->out_msgtype = MBEDTLS_SSL_MSG_HANDSHAKE;
3626     ssl->out_msg[0]  = MBEDTLS_SSL_HS_SERVER_KEY_EXCHANGE;
3627 
3628     ssl->state++;
3629 
3630     if ((ret = mbedtls_ssl_write_handshake_msg(ssl)) != 0) {
3631         MBEDTLS_SSL_DEBUG_RET(1, "mbedtls_ssl_write_handshake_msg", ret);
3632         return ret;
3633     }
3634 
3635     MBEDTLS_SSL_DEBUG_MSG(2, ("<= write server key exchange"));
3636     return 0;
3637 }
3638 
3639 MBEDTLS_CHECK_RETURN_CRITICAL
ssl_write_server_hello_done(mbedtls_ssl_context * ssl)3640 static int ssl_write_server_hello_done(mbedtls_ssl_context *ssl)
3641 {
3642     int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
3643 
3644     MBEDTLS_SSL_DEBUG_MSG(2, ("=> write server hello done"));
3645 
3646     ssl->out_msglen  = 4;
3647     ssl->out_msgtype = MBEDTLS_SSL_MSG_HANDSHAKE;
3648     ssl->out_msg[0]  = MBEDTLS_SSL_HS_SERVER_HELLO_DONE;
3649 
3650     ssl->state++;
3651 
3652 #if defined(MBEDTLS_SSL_PROTO_DTLS)
3653     if (ssl->conf->transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM) {
3654         mbedtls_ssl_send_flight_completed(ssl);
3655     }
3656 #endif
3657 
3658     if ((ret = mbedtls_ssl_write_handshake_msg(ssl)) != 0) {
3659         MBEDTLS_SSL_DEBUG_RET(1, "mbedtls_ssl_write_handshake_msg", ret);
3660         return ret;
3661     }
3662 
3663 #if defined(MBEDTLS_SSL_PROTO_DTLS)
3664     if (ssl->conf->transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM &&
3665         (ret = mbedtls_ssl_flight_transmit(ssl)) != 0) {
3666         MBEDTLS_SSL_DEBUG_RET(1, "mbedtls_ssl_flight_transmit", ret);
3667         return ret;
3668     }
3669 #endif /* MBEDTLS_SSL_PROTO_DTLS */
3670 
3671     MBEDTLS_SSL_DEBUG_MSG(2, ("<= write server hello done"));
3672 
3673     return 0;
3674 }
3675 
3676 #if defined(MBEDTLS_KEY_EXCHANGE_DHE_RSA_ENABLED) ||                       \
3677     defined(MBEDTLS_KEY_EXCHANGE_DHE_PSK_ENABLED)
3678 MBEDTLS_CHECK_RETURN_CRITICAL
ssl_parse_client_dh_public(mbedtls_ssl_context * ssl,unsigned char ** p,const unsigned char * end)3679 static int ssl_parse_client_dh_public(mbedtls_ssl_context *ssl, unsigned char **p,
3680                                       const unsigned char *end)
3681 {
3682     int ret = MBEDTLS_ERR_SSL_FEATURE_UNAVAILABLE;
3683     size_t n;
3684 
3685     /*
3686      * Receive G^Y mod P, premaster = (G^Y)^X mod P
3687      */
3688     if (*p + 2 > end) {
3689         MBEDTLS_SSL_DEBUG_MSG(1, ("bad client key exchange message"));
3690         return MBEDTLS_ERR_SSL_BAD_HS_CLIENT_KEY_EXCHANGE;
3691     }
3692 
3693     n = ((*p)[0] << 8) | (*p)[1];
3694     *p += 2;
3695 
3696     if (*p + n > end) {
3697         MBEDTLS_SSL_DEBUG_MSG(1, ("bad client key exchange message"));
3698         return MBEDTLS_ERR_SSL_BAD_HS_CLIENT_KEY_EXCHANGE;
3699     }
3700 
3701     if ((ret = mbedtls_dhm_read_public(&ssl->handshake->dhm_ctx, *p, n)) != 0) {
3702         MBEDTLS_SSL_DEBUG_RET(1, "mbedtls_dhm_read_public", ret);
3703         return MBEDTLS_ERR_SSL_BAD_HS_CLIENT_KEY_EXCHANGE_RP;
3704     }
3705 
3706     *p += n;
3707 
3708     MBEDTLS_SSL_DEBUG_MPI(3, "DHM: GY", &ssl->handshake->dhm_ctx.GY);
3709 
3710     return ret;
3711 }
3712 #endif /* MBEDTLS_KEY_EXCHANGE_DHE_RSA_ENABLED ||
3713           MBEDTLS_KEY_EXCHANGE_DHE_PSK_ENABLED */
3714 
3715 #if defined(MBEDTLS_KEY_EXCHANGE_RSA_ENABLED) ||                           \
3716     defined(MBEDTLS_KEY_EXCHANGE_RSA_PSK_ENABLED)
3717 
3718 #if defined(MBEDTLS_SSL_ASYNC_PRIVATE)
3719 MBEDTLS_CHECK_RETURN_CRITICAL
ssl_resume_decrypt_pms(mbedtls_ssl_context * ssl,unsigned char * peer_pms,size_t * peer_pmslen,size_t peer_pmssize)3720 static int ssl_resume_decrypt_pms(mbedtls_ssl_context *ssl,
3721                                   unsigned char *peer_pms,
3722                                   size_t *peer_pmslen,
3723                                   size_t peer_pmssize)
3724 {
3725     int ret = ssl->conf->f_async_resume(ssl,
3726                                         peer_pms, peer_pmslen, peer_pmssize);
3727     if (ret != MBEDTLS_ERR_SSL_ASYNC_IN_PROGRESS) {
3728         ssl->handshake->async_in_progress = 0;
3729         mbedtls_ssl_set_async_operation_data(ssl, NULL);
3730     }
3731     MBEDTLS_SSL_DEBUG_RET(2, "ssl_decrypt_encrypted_pms", ret);
3732     return ret;
3733 }
3734 #endif /* MBEDTLS_SSL_ASYNC_PRIVATE */
3735 
3736 MBEDTLS_CHECK_RETURN_CRITICAL
ssl_decrypt_encrypted_pms(mbedtls_ssl_context * ssl,const unsigned char * p,const unsigned char * end,unsigned char * peer_pms,size_t * peer_pmslen,size_t peer_pmssize)3737 static int ssl_decrypt_encrypted_pms(mbedtls_ssl_context *ssl,
3738                                      const unsigned char *p,
3739                                      const unsigned char *end,
3740                                      unsigned char *peer_pms,
3741                                      size_t *peer_pmslen,
3742                                      size_t peer_pmssize)
3743 {
3744     int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
3745 
3746     mbedtls_x509_crt *own_cert = mbedtls_ssl_own_cert(ssl);
3747     if (own_cert == NULL) {
3748         MBEDTLS_SSL_DEBUG_MSG(1, ("got no local certificate"));
3749         return MBEDTLS_ERR_SSL_NO_CLIENT_CERTIFICATE;
3750     }
3751     mbedtls_pk_context *public_key = &own_cert->pk;
3752     mbedtls_pk_context *private_key = mbedtls_ssl_own_key(ssl);
3753     size_t len = mbedtls_pk_get_len(public_key);
3754 
3755 #if defined(MBEDTLS_SSL_ASYNC_PRIVATE)
3756     /* If we have already started decoding the message and there is an ongoing
3757      * decryption operation, resume signing. */
3758     if (ssl->handshake->async_in_progress != 0) {
3759         MBEDTLS_SSL_DEBUG_MSG(2, ("resuming decryption operation"));
3760         return ssl_resume_decrypt_pms(ssl,
3761                                       peer_pms, peer_pmslen, peer_pmssize);
3762     }
3763 #endif /* MBEDTLS_SSL_ASYNC_PRIVATE */
3764 
3765     /*
3766      * Prepare to decrypt the premaster using own private RSA key
3767      */
3768 #if defined(MBEDTLS_SSL_PROTO_TLS1) || defined(MBEDTLS_SSL_PROTO_TLS1_1) || \
3769     defined(MBEDTLS_SSL_PROTO_TLS1_2)
3770     if (ssl->minor_ver != MBEDTLS_SSL_MINOR_VERSION_0) {
3771         if (p + 2 > end) {
3772             MBEDTLS_SSL_DEBUG_MSG(1, ("bad client key exchange message"));
3773             return MBEDTLS_ERR_SSL_BAD_HS_CLIENT_KEY_EXCHANGE;
3774         }
3775         if (*p++ != MBEDTLS_BYTE_1(len) ||
3776             *p++ != MBEDTLS_BYTE_0(len)) {
3777             MBEDTLS_SSL_DEBUG_MSG(1, ("bad client key exchange message"));
3778             return MBEDTLS_ERR_SSL_BAD_HS_CLIENT_KEY_EXCHANGE;
3779         }
3780     }
3781 #endif
3782 
3783     if (p + len != end) {
3784         MBEDTLS_SSL_DEBUG_MSG(1, ("bad client key exchange message"));
3785         return MBEDTLS_ERR_SSL_BAD_HS_CLIENT_KEY_EXCHANGE;
3786     }
3787 
3788     /*
3789      * Decrypt the premaster secret
3790      */
3791 #if defined(MBEDTLS_SSL_ASYNC_PRIVATE)
3792     if (ssl->conf->f_async_decrypt_start != NULL) {
3793         ret = ssl->conf->f_async_decrypt_start(ssl,
3794                                                mbedtls_ssl_own_cert(ssl),
3795                                                p, len);
3796         switch (ret) {
3797             case MBEDTLS_ERR_SSL_HW_ACCEL_FALLTHROUGH:
3798                 /* act as if f_async_decrypt_start was null */
3799                 break;
3800             case 0:
3801                 ssl->handshake->async_in_progress = 1;
3802                 return ssl_resume_decrypt_pms(ssl,
3803                                               peer_pms,
3804                                               peer_pmslen,
3805                                               peer_pmssize);
3806             case MBEDTLS_ERR_SSL_ASYNC_IN_PROGRESS:
3807                 ssl->handshake->async_in_progress = 1;
3808                 return MBEDTLS_ERR_SSL_ASYNC_IN_PROGRESS;
3809             default:
3810                 MBEDTLS_SSL_DEBUG_RET(1, "f_async_decrypt_start", ret);
3811                 return ret;
3812         }
3813     }
3814 #endif /* MBEDTLS_SSL_ASYNC_PRIVATE */
3815 
3816     if (!mbedtls_pk_can_do(private_key, MBEDTLS_PK_RSA)) {
3817         MBEDTLS_SSL_DEBUG_MSG(1, ("got no RSA private key"));
3818         return MBEDTLS_ERR_SSL_PRIVATE_KEY_REQUIRED;
3819     }
3820 
3821     ret = mbedtls_pk_decrypt(private_key, p, len,
3822                              peer_pms, peer_pmslen, peer_pmssize,
3823                              ssl->conf->f_rng, ssl->conf->p_rng);
3824     return ret;
3825 }
3826 
3827 MBEDTLS_CHECK_RETURN_CRITICAL
ssl_parse_encrypted_pms(mbedtls_ssl_context * ssl,const unsigned char * p,const unsigned char * end,size_t pms_offset)3828 static int ssl_parse_encrypted_pms(mbedtls_ssl_context *ssl,
3829                                    const unsigned char *p,
3830                                    const unsigned char *end,
3831                                    size_t pms_offset)
3832 {
3833     int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
3834     unsigned char *pms = ssl->handshake->premaster + pms_offset;
3835     unsigned char ver[2];
3836     unsigned char fake_pms[48], peer_pms[48];
3837     unsigned char mask;
3838     size_t i, peer_pmslen;
3839     unsigned int diff;
3840 
3841     /* In case of a failure in decryption, the decryption may write less than
3842      * 2 bytes of output, but we always read the first two bytes. It doesn't
3843      * matter in the end because diff will be nonzero in that case due to
3844      * ret being nonzero, and we only care whether diff is 0.
3845      * But do initialize peer_pms and peer_pmslen for robustness anyway. This
3846      * also makes memory analyzers happy (don't access uninitialized memory,
3847      * even if it's an unsigned char). */
3848     peer_pms[0] = peer_pms[1] = ~0;
3849     peer_pmslen = 0;
3850 
3851     ret = ssl_decrypt_encrypted_pms(ssl, p, end,
3852                                     peer_pms,
3853                                     &peer_pmslen,
3854                                     sizeof(peer_pms));
3855 
3856 #if defined(MBEDTLS_SSL_ASYNC_PRIVATE)
3857     if (ret == MBEDTLS_ERR_SSL_ASYNC_IN_PROGRESS) {
3858         return ret;
3859     }
3860 #endif /* MBEDTLS_SSL_ASYNC_PRIVATE */
3861 
3862     mbedtls_ssl_write_version(ssl->handshake->max_major_ver,
3863                               ssl->handshake->max_minor_ver,
3864                               ssl->conf->transport, ver);
3865 
3866     /* Avoid data-dependent branches while checking for invalid
3867      * padding, to protect against timing-based Bleichenbacher-type
3868      * attacks. */
3869     diff  = (unsigned int) ret;
3870     diff |= peer_pmslen ^ 48;
3871     diff |= peer_pms[0] ^ ver[0];
3872     diff |= peer_pms[1] ^ ver[1];
3873 
3874     /* mask = diff ? 0xff : 0x00 using bit operations to avoid branches */
3875     mask = mbedtls_ct_uint_mask(diff);
3876 
3877     /*
3878      * Protection against Bleichenbacher's attack: invalid PKCS#1 v1.5 padding
3879      * must not cause the connection to end immediately; instead, send a
3880      * bad_record_mac later in the handshake.
3881      * To protect against timing-based variants of the attack, we must
3882      * not have any branch that depends on whether the decryption was
3883      * successful. In particular, always generate the fake premaster secret,
3884      * regardless of whether it will ultimately influence the output or not.
3885      */
3886     ret = ssl->conf->f_rng(ssl->conf->p_rng, fake_pms, sizeof(fake_pms));
3887     if (ret != 0) {
3888         /* It's ok to abort on an RNG failure, since this does not reveal
3889          * anything about the RSA decryption. */
3890         return ret;
3891     }
3892 
3893 #if defined(MBEDTLS_SSL_DEBUG_ALL)
3894     if (diff != 0) {
3895         MBEDTLS_SSL_DEBUG_MSG(1, ("bad client key exchange message"));
3896     }
3897 #endif
3898 
3899     if (sizeof(ssl->handshake->premaster) < pms_offset ||
3900         sizeof(ssl->handshake->premaster) - pms_offset < 48) {
3901         MBEDTLS_SSL_DEBUG_MSG(1, ("should never happen"));
3902         return MBEDTLS_ERR_SSL_INTERNAL_ERROR;
3903     }
3904     ssl->handshake->pmslen = 48;
3905 
3906     /* Set pms to either the true or the fake PMS, without
3907      * data-dependent branches. */
3908     for (i = 0; i < ssl->handshake->pmslen; i++) {
3909         pms[i] = (mask & fake_pms[i]) | ((~mask) & peer_pms[i]);
3910     }
3911 
3912     return 0;
3913 }
3914 #endif /* MBEDTLS_KEY_EXCHANGE_RSA_ENABLED ||
3915           MBEDTLS_KEY_EXCHANGE_RSA_PSK_ENABLED */
3916 
3917 #if defined(MBEDTLS_KEY_EXCHANGE_SOME_PSK_ENABLED)
3918 MBEDTLS_CHECK_RETURN_CRITICAL
ssl_parse_client_psk_identity(mbedtls_ssl_context * ssl,unsigned char ** p,const unsigned char * end)3919 static int ssl_parse_client_psk_identity(mbedtls_ssl_context *ssl, unsigned char **p,
3920                                          const unsigned char *end)
3921 {
3922     int ret = 0;
3923     uint16_t n;
3924 
3925     if (ssl_conf_has_psk_or_cb(ssl->conf) == 0) {
3926         MBEDTLS_SSL_DEBUG_MSG(1, ("got no pre-shared key"));
3927         return MBEDTLS_ERR_SSL_PRIVATE_KEY_REQUIRED;
3928     }
3929 
3930     /*
3931      * Receive client pre-shared key identity name
3932      */
3933     if (end - *p < 2) {
3934         MBEDTLS_SSL_DEBUG_MSG(1, ("bad client key exchange message"));
3935         return MBEDTLS_ERR_SSL_BAD_HS_CLIENT_KEY_EXCHANGE;
3936     }
3937 
3938     n = ((*p)[0] << 8) | (*p)[1];
3939     *p += 2;
3940 
3941     if (n == 0 || n > end - *p) {
3942         MBEDTLS_SSL_DEBUG_MSG(1, ("bad client key exchange message"));
3943         return MBEDTLS_ERR_SSL_BAD_HS_CLIENT_KEY_EXCHANGE;
3944     }
3945 
3946     if (ssl->conf->f_psk != NULL) {
3947         if (ssl->conf->f_psk(ssl->conf->p_psk, ssl, *p, n) != 0) {
3948             ret = MBEDTLS_ERR_SSL_UNKNOWN_IDENTITY;
3949         }
3950     } else {
3951         /* Identity is not a big secret since clients send it in the clear,
3952          * but treat it carefully anyway, just in case */
3953         if (n != ssl->conf->psk_identity_len ||
3954             mbedtls_ct_memcmp(ssl->conf->psk_identity, *p, n) != 0) {
3955             ret = MBEDTLS_ERR_SSL_UNKNOWN_IDENTITY;
3956         }
3957     }
3958 
3959     if (ret == MBEDTLS_ERR_SSL_UNKNOWN_IDENTITY) {
3960         MBEDTLS_SSL_DEBUG_BUF(3, "Unknown PSK identity", *p, n);
3961         mbedtls_ssl_send_alert_message(ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,
3962                                        MBEDTLS_SSL_ALERT_MSG_UNKNOWN_PSK_IDENTITY);
3963         return MBEDTLS_ERR_SSL_UNKNOWN_IDENTITY;
3964     }
3965 
3966     *p += n;
3967 
3968     return 0;
3969 }
3970 #endif /* MBEDTLS_KEY_EXCHANGE_SOME_PSK_ENABLED */
3971 
3972 MBEDTLS_CHECK_RETURN_CRITICAL
ssl_parse_client_key_exchange(mbedtls_ssl_context * ssl)3973 static int ssl_parse_client_key_exchange(mbedtls_ssl_context *ssl)
3974 {
3975     int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
3976     const mbedtls_ssl_ciphersuite_t *ciphersuite_info;
3977     unsigned char *p, *end;
3978 
3979     ciphersuite_info = ssl->handshake->ciphersuite_info;
3980 
3981     MBEDTLS_SSL_DEBUG_MSG(2, ("=> parse client key exchange"));
3982 
3983 #if defined(MBEDTLS_SSL_ASYNC_PRIVATE) && \
3984     (defined(MBEDTLS_KEY_EXCHANGE_RSA_ENABLED) || \
3985     defined(MBEDTLS_KEY_EXCHANGE_RSA_PSK_ENABLED))
3986     if ((ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_RSA_PSK ||
3987          ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_RSA) &&
3988         (ssl->handshake->async_in_progress != 0)) {
3989         /* We've already read a record and there is an asynchronous
3990          * operation in progress to decrypt it. So skip reading the
3991          * record. */
3992         MBEDTLS_SSL_DEBUG_MSG(3, ("will resume decryption of previously-read record"));
3993     } else
3994 #endif
3995     if ((ret = mbedtls_ssl_read_record(ssl, 1)) != 0) {
3996         MBEDTLS_SSL_DEBUG_RET(1, "mbedtls_ssl_read_record", ret);
3997         return ret;
3998     }
3999 
4000     p = ssl->in_msg + mbedtls_ssl_hs_hdr_len(ssl);
4001     end = ssl->in_msg + ssl->in_hslen;
4002 
4003     if (ssl->in_msgtype != MBEDTLS_SSL_MSG_HANDSHAKE) {
4004         MBEDTLS_SSL_DEBUG_MSG(1, ("bad client key exchange message"));
4005         return MBEDTLS_ERR_SSL_BAD_HS_CLIENT_KEY_EXCHANGE;
4006     }
4007 
4008     if (ssl->in_msg[0] != MBEDTLS_SSL_HS_CLIENT_KEY_EXCHANGE) {
4009         MBEDTLS_SSL_DEBUG_MSG(1, ("bad client key exchange message"));
4010         return MBEDTLS_ERR_SSL_BAD_HS_CLIENT_KEY_EXCHANGE;
4011     }
4012 
4013 #if defined(MBEDTLS_KEY_EXCHANGE_DHE_RSA_ENABLED)
4014     if (ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_DHE_RSA) {
4015         if ((ret = ssl_parse_client_dh_public(ssl, &p, end)) != 0) {
4016             MBEDTLS_SSL_DEBUG_RET(1, ("ssl_parse_client_dh_public"), ret);
4017             return ret;
4018         }
4019 
4020         if (p != end) {
4021             MBEDTLS_SSL_DEBUG_MSG(1, ("bad client key exchange"));
4022             return MBEDTLS_ERR_SSL_BAD_HS_CLIENT_KEY_EXCHANGE;
4023         }
4024 
4025         if ((ret = mbedtls_dhm_calc_secret(&ssl->handshake->dhm_ctx,
4026                                            ssl->handshake->premaster,
4027                                            MBEDTLS_PREMASTER_SIZE,
4028                                            &ssl->handshake->pmslen,
4029                                            ssl->conf->f_rng, ssl->conf->p_rng)) != 0) {
4030             MBEDTLS_SSL_DEBUG_RET(1, "mbedtls_dhm_calc_secret", ret);
4031             return MBEDTLS_ERR_SSL_BAD_HS_CLIENT_KEY_EXCHANGE_CS;
4032         }
4033 
4034         MBEDTLS_SSL_DEBUG_MPI(3, "DHM: K ", &ssl->handshake->dhm_ctx.K);
4035     } else
4036 #endif /* MBEDTLS_KEY_EXCHANGE_DHE_RSA_ENABLED */
4037 #if defined(MBEDTLS_KEY_EXCHANGE_ECDHE_RSA_ENABLED) ||                     \
4038     defined(MBEDTLS_KEY_EXCHANGE_ECDHE_ECDSA_ENABLED) ||                   \
4039     defined(MBEDTLS_KEY_EXCHANGE_ECDH_RSA_ENABLED) ||                      \
4040     defined(MBEDTLS_KEY_EXCHANGE_ECDH_ECDSA_ENABLED)
4041     if (ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_ECDHE_RSA ||
4042         ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_ECDHE_ECDSA ||
4043         ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_ECDH_RSA ||
4044         ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_ECDH_ECDSA) {
4045         if ((ret = mbedtls_ecdh_read_public(&ssl->handshake->ecdh_ctx,
4046                                             p, end - p)) != 0) {
4047             MBEDTLS_SSL_DEBUG_RET(1, "mbedtls_ecdh_read_public", ret);
4048             return MBEDTLS_ERR_SSL_BAD_HS_CLIENT_KEY_EXCHANGE_RP;
4049         }
4050 
4051         MBEDTLS_SSL_DEBUG_ECDH(3, &ssl->handshake->ecdh_ctx,
4052                                MBEDTLS_DEBUG_ECDH_QP);
4053 
4054         if ((ret = mbedtls_ecdh_calc_secret(&ssl->handshake->ecdh_ctx,
4055                                             &ssl->handshake->pmslen,
4056                                             ssl->handshake->premaster,
4057                                             MBEDTLS_MPI_MAX_SIZE,
4058                                             ssl->conf->f_rng, ssl->conf->p_rng)) != 0) {
4059             MBEDTLS_SSL_DEBUG_RET(1, "mbedtls_ecdh_calc_secret", ret);
4060             return MBEDTLS_ERR_SSL_BAD_HS_CLIENT_KEY_EXCHANGE_CS;
4061         }
4062 
4063         MBEDTLS_SSL_DEBUG_ECDH(3, &ssl->handshake->ecdh_ctx,
4064                                MBEDTLS_DEBUG_ECDH_Z);
4065     } else
4066 #endif /* MBEDTLS_KEY_EXCHANGE_ECDHE_RSA_ENABLED ||
4067           MBEDTLS_KEY_EXCHANGE_ECDHE_ECDSA_ENABLED ||
4068           MBEDTLS_KEY_EXCHANGE_ECDH_RSA_ENABLED ||
4069           MBEDTLS_KEY_EXCHANGE_ECDH_ECDSA_ENABLED */
4070 #if defined(MBEDTLS_KEY_EXCHANGE_PSK_ENABLED)
4071     if (ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_PSK) {
4072         if ((ret = ssl_parse_client_psk_identity(ssl, &p, end)) != 0) {
4073             MBEDTLS_SSL_DEBUG_RET(1, ("ssl_parse_client_psk_identity"), ret);
4074             return ret;
4075         }
4076 
4077         if (p != end) {
4078             MBEDTLS_SSL_DEBUG_MSG(1, ("bad client key exchange"));
4079             return MBEDTLS_ERR_SSL_BAD_HS_CLIENT_KEY_EXCHANGE;
4080         }
4081 
4082 #if defined(MBEDTLS_USE_PSA_CRYPTO)
4083         /* For opaque PSKs, we perform the PSK-to-MS derivation automatically
4084          * and skip the intermediate PMS. */
4085         if (ssl_use_opaque_psk(ssl) == 1) {
4086             MBEDTLS_SSL_DEBUG_MSG(1, ("skip PMS generation for opaque PSK"));
4087         } else
4088 #endif /* MBEDTLS_USE_PSA_CRYPTO */
4089         if ((ret = mbedtls_ssl_psk_derive_premaster(ssl,
4090                                                     ciphersuite_info->key_exchange)) != 0) {
4091             MBEDTLS_SSL_DEBUG_RET(1, "mbedtls_ssl_psk_derive_premaster", ret);
4092             return ret;
4093         }
4094     } else
4095 #endif /* MBEDTLS_KEY_EXCHANGE_PSK_ENABLED */
4096 #if defined(MBEDTLS_KEY_EXCHANGE_RSA_PSK_ENABLED)
4097     if (ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_RSA_PSK) {
4098 #if defined(MBEDTLS_SSL_ASYNC_PRIVATE)
4099         if (ssl->handshake->async_in_progress != 0) {
4100             /* There is an asynchronous operation in progress to
4101              * decrypt the encrypted premaster secret, so skip
4102              * directly to resuming this operation. */
4103             MBEDTLS_SSL_DEBUG_MSG(3, ("PSK identity already parsed"));
4104             /* Update p to skip the PSK identity. ssl_parse_encrypted_pms
4105              * won't actually use it, but maintain p anyway for robustness. */
4106             p += ssl->conf->psk_identity_len + 2;
4107         } else
4108 #endif /* MBEDTLS_SSL_ASYNC_PRIVATE */
4109         if ((ret = ssl_parse_client_psk_identity(ssl, &p, end)) != 0) {
4110             MBEDTLS_SSL_DEBUG_RET(1, ("ssl_parse_client_psk_identity"), ret);
4111             return ret;
4112         }
4113 
4114 #if defined(MBEDTLS_USE_PSA_CRYPTO)
4115         /* Opaque PSKs are currently only supported for PSK-only. */
4116         if (ssl_use_opaque_psk(ssl) == 1) {
4117             MBEDTLS_SSL_DEBUG_MSG(1, ("opaque PSK not supported with RSA-PSK"));
4118             return MBEDTLS_ERR_SSL_FEATURE_UNAVAILABLE;
4119         }
4120 #endif
4121 
4122         if ((ret = ssl_parse_encrypted_pms(ssl, p, end, 2)) != 0) {
4123             MBEDTLS_SSL_DEBUG_RET(1, ("ssl_parse_encrypted_pms"), ret);
4124             return ret;
4125         }
4126 
4127         if ((ret = mbedtls_ssl_psk_derive_premaster(ssl,
4128                                                     ciphersuite_info->key_exchange)) != 0) {
4129             MBEDTLS_SSL_DEBUG_RET(1, "mbedtls_ssl_psk_derive_premaster", ret);
4130             return ret;
4131         }
4132     } else
4133 #endif /* MBEDTLS_KEY_EXCHANGE_RSA_PSK_ENABLED */
4134 #if defined(MBEDTLS_KEY_EXCHANGE_DHE_PSK_ENABLED)
4135     if (ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_DHE_PSK) {
4136         if ((ret = ssl_parse_client_psk_identity(ssl, &p, end)) != 0) {
4137             MBEDTLS_SSL_DEBUG_RET(1, ("ssl_parse_client_psk_identity"), ret);
4138             return ret;
4139         }
4140         if ((ret = ssl_parse_client_dh_public(ssl, &p, end)) != 0) {
4141             MBEDTLS_SSL_DEBUG_RET(1, ("ssl_parse_client_dh_public"), ret);
4142             return ret;
4143         }
4144 
4145 #if defined(MBEDTLS_USE_PSA_CRYPTO)
4146         /* Opaque PSKs are currently only supported for PSK-only. */
4147         if (ssl_use_opaque_psk(ssl) == 1) {
4148             MBEDTLS_SSL_DEBUG_MSG(1, ("opaque PSK not supported with DHE-PSK"));
4149             return MBEDTLS_ERR_SSL_FEATURE_UNAVAILABLE;
4150         }
4151 #endif
4152 
4153         if (p != end) {
4154             MBEDTLS_SSL_DEBUG_MSG(1, ("bad client key exchange"));
4155             return MBEDTLS_ERR_SSL_BAD_HS_CLIENT_KEY_EXCHANGE;
4156         }
4157 
4158         if ((ret = mbedtls_ssl_psk_derive_premaster(ssl,
4159                                                     ciphersuite_info->key_exchange)) != 0) {
4160             MBEDTLS_SSL_DEBUG_RET(1, "mbedtls_ssl_psk_derive_premaster", ret);
4161             return ret;
4162         }
4163     } else
4164 #endif /* MBEDTLS_KEY_EXCHANGE_DHE_PSK_ENABLED */
4165 #if defined(MBEDTLS_KEY_EXCHANGE_ECDHE_PSK_ENABLED)
4166     if (ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_ECDHE_PSK) {
4167         if ((ret = ssl_parse_client_psk_identity(ssl, &p, end)) != 0) {
4168             MBEDTLS_SSL_DEBUG_RET(1, ("ssl_parse_client_psk_identity"), ret);
4169             return ret;
4170         }
4171 
4172         if ((ret = mbedtls_ecdh_read_public(&ssl->handshake->ecdh_ctx,
4173                                             p, end - p)) != 0) {
4174             MBEDTLS_SSL_DEBUG_RET(1, "mbedtls_ecdh_read_public", ret);
4175             return MBEDTLS_ERR_SSL_BAD_HS_CLIENT_KEY_EXCHANGE_RP;
4176         }
4177 
4178 #if defined(MBEDTLS_USE_PSA_CRYPTO)
4179         /* Opaque PSKs are currently only supported for PSK-only. */
4180         if (ssl_use_opaque_psk(ssl) == 1) {
4181             MBEDTLS_SSL_DEBUG_MSG(1, ("opaque PSK not supported with ECDHE-PSK"));
4182             return MBEDTLS_ERR_SSL_FEATURE_UNAVAILABLE;
4183         }
4184 #endif
4185 
4186         MBEDTLS_SSL_DEBUG_ECDH(3, &ssl->handshake->ecdh_ctx,
4187                                MBEDTLS_DEBUG_ECDH_QP);
4188 
4189         if ((ret = mbedtls_ssl_psk_derive_premaster(ssl,
4190                                                     ciphersuite_info->key_exchange)) != 0) {
4191             MBEDTLS_SSL_DEBUG_RET(1, "mbedtls_ssl_psk_derive_premaster", ret);
4192             return ret;
4193         }
4194     } else
4195 #endif /* MBEDTLS_KEY_EXCHANGE_ECDHE_PSK_ENABLED */
4196 #if defined(MBEDTLS_KEY_EXCHANGE_RSA_ENABLED)
4197     if (ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_RSA) {
4198         if ((ret = ssl_parse_encrypted_pms(ssl, p, end, 0)) != 0) {
4199             MBEDTLS_SSL_DEBUG_RET(1, ("ssl_parse_parse_encrypted_pms_secret"), ret);
4200             return ret;
4201         }
4202     } else
4203 #endif /* MBEDTLS_KEY_EXCHANGE_RSA_ENABLED */
4204 #if defined(MBEDTLS_KEY_EXCHANGE_ECJPAKE_ENABLED)
4205     if (ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_ECJPAKE) {
4206         ret = mbedtls_ecjpake_read_round_two(&ssl->handshake->ecjpake_ctx,
4207                                              p, end - p);
4208         if (ret != 0) {
4209             MBEDTLS_SSL_DEBUG_RET(1, "mbedtls_ecjpake_read_round_two", ret);
4210             return MBEDTLS_ERR_SSL_BAD_HS_SERVER_KEY_EXCHANGE;
4211         }
4212 
4213         ret = mbedtls_ecjpake_derive_secret(&ssl->handshake->ecjpake_ctx,
4214                                             ssl->handshake->premaster, 32, &ssl->handshake->pmslen,
4215                                             ssl->conf->f_rng, ssl->conf->p_rng);
4216         if (ret != 0) {
4217             MBEDTLS_SSL_DEBUG_RET(1, "mbedtls_ecjpake_derive_secret", ret);
4218             return ret;
4219         }
4220     } else
4221 #endif /* MBEDTLS_KEY_EXCHANGE_ECJPAKE_ENABLED */
4222     {
4223         MBEDTLS_SSL_DEBUG_MSG(1, ("should never happen"));
4224         return MBEDTLS_ERR_SSL_INTERNAL_ERROR;
4225     }
4226 
4227     if ((ret = mbedtls_ssl_derive_keys(ssl)) != 0) {
4228         MBEDTLS_SSL_DEBUG_RET(1, "mbedtls_ssl_derive_keys", ret);
4229         return ret;
4230     }
4231 
4232     ssl->state++;
4233 
4234     MBEDTLS_SSL_DEBUG_MSG(2, ("<= parse client key exchange"));
4235 
4236     return 0;
4237 }
4238 
4239 #if !defined(MBEDTLS_KEY_EXCHANGE_CERT_REQ_ALLOWED_ENABLED)
4240 MBEDTLS_CHECK_RETURN_CRITICAL
ssl_parse_certificate_verify(mbedtls_ssl_context * ssl)4241 static int ssl_parse_certificate_verify(mbedtls_ssl_context *ssl)
4242 {
4243     const mbedtls_ssl_ciphersuite_t *ciphersuite_info =
4244         ssl->handshake->ciphersuite_info;
4245 
4246     MBEDTLS_SSL_DEBUG_MSG(2, ("=> parse certificate verify"));
4247 
4248     if (!mbedtls_ssl_ciphersuite_cert_req_allowed(ciphersuite_info)) {
4249         MBEDTLS_SSL_DEBUG_MSG(2, ("<= skip parse certificate verify"));
4250         ssl->state++;
4251         return 0;
4252     }
4253 
4254     MBEDTLS_SSL_DEBUG_MSG(1, ("should never happen"));
4255     return MBEDTLS_ERR_SSL_INTERNAL_ERROR;
4256 }
4257 #else /* !MBEDTLS_KEY_EXCHANGE_CERT_REQ_ALLOWED_ENABLED */
4258 MBEDTLS_CHECK_RETURN_CRITICAL
ssl_parse_certificate_verify(mbedtls_ssl_context * ssl)4259 static int ssl_parse_certificate_verify(mbedtls_ssl_context *ssl)
4260 {
4261     int ret = MBEDTLS_ERR_SSL_FEATURE_UNAVAILABLE;
4262     size_t i, sig_len;
4263     unsigned char hash[48];
4264     unsigned char *hash_start = hash;
4265     size_t hashlen;
4266 #if defined(MBEDTLS_SSL_PROTO_TLS1_2)
4267     mbedtls_pk_type_t pk_alg;
4268 #endif
4269     mbedtls_md_type_t md_alg;
4270     const mbedtls_ssl_ciphersuite_t *ciphersuite_info =
4271         ssl->handshake->ciphersuite_info;
4272     mbedtls_pk_context *peer_pk;
4273 
4274     MBEDTLS_SSL_DEBUG_MSG(2, ("=> parse certificate verify"));
4275 
4276     if (!mbedtls_ssl_ciphersuite_cert_req_allowed(ciphersuite_info)) {
4277         MBEDTLS_SSL_DEBUG_MSG(2, ("<= skip parse certificate verify"));
4278         ssl->state++;
4279         return 0;
4280     }
4281 
4282 #if defined(MBEDTLS_SSL_KEEP_PEER_CERTIFICATE)
4283     if (ssl->session_negotiate->peer_cert == NULL) {
4284         MBEDTLS_SSL_DEBUG_MSG(2, ("<= skip parse certificate verify"));
4285         ssl->state++;
4286         return 0;
4287     }
4288 #else /* MBEDTLS_SSL_KEEP_PEER_CERTIFICATE */
4289     if (ssl->session_negotiate->peer_cert_digest == NULL) {
4290         MBEDTLS_SSL_DEBUG_MSG(2, ("<= skip parse certificate verify"));
4291         ssl->state++;
4292         return 0;
4293     }
4294 #endif /* !MBEDTLS_SSL_KEEP_PEER_CERTIFICATE */
4295 
4296     /* Read the message without adding it to the checksum */
4297     ret = mbedtls_ssl_read_record(ssl, 0 /* no checksum update */);
4298     if (0 != ret) {
4299         MBEDTLS_SSL_DEBUG_RET(1, ("mbedtls_ssl_read_record"), ret);
4300         return ret;
4301     }
4302 
4303     ssl->state++;
4304 
4305     /* Process the message contents */
4306     if (ssl->in_msgtype != MBEDTLS_SSL_MSG_HANDSHAKE ||
4307         ssl->in_msg[0] != MBEDTLS_SSL_HS_CERTIFICATE_VERIFY) {
4308         MBEDTLS_SSL_DEBUG_MSG(1, ("bad certificate verify message"));
4309         return MBEDTLS_ERR_SSL_BAD_HS_CERTIFICATE_VERIFY;
4310     }
4311 
4312     i = mbedtls_ssl_hs_hdr_len(ssl);
4313 
4314 #if !defined(MBEDTLS_SSL_KEEP_PEER_CERTIFICATE)
4315     peer_pk = &ssl->handshake->peer_pubkey;
4316 #else /* !MBEDTLS_SSL_KEEP_PEER_CERTIFICATE */
4317     if (ssl->session_negotiate->peer_cert == NULL) {
4318         /* Should never happen */
4319         return MBEDTLS_ERR_SSL_INTERNAL_ERROR;
4320     }
4321     peer_pk = &ssl->session_negotiate->peer_cert->pk;
4322 #endif /* MBEDTLS_SSL_KEEP_PEER_CERTIFICATE */
4323 
4324     /*
4325      *  struct {
4326      *     SignatureAndHashAlgorithm algorithm; -- TLS 1.2 only
4327      *     opaque signature<0..2^16-1>;
4328      *  } DigitallySigned;
4329      */
4330 #if defined(MBEDTLS_SSL_PROTO_SSL3) || defined(MBEDTLS_SSL_PROTO_TLS1) || \
4331     defined(MBEDTLS_SSL_PROTO_TLS1_1)
4332     if (ssl->minor_ver != MBEDTLS_SSL_MINOR_VERSION_3) {
4333         md_alg = MBEDTLS_MD_NONE;
4334         hashlen = 36;
4335 
4336         /* For ECDSA, use SHA-1, not MD-5 + SHA-1 */
4337         if (mbedtls_pk_can_do(peer_pk, MBEDTLS_PK_ECDSA)) {
4338             hash_start += 16;
4339             hashlen -= 16;
4340             md_alg = MBEDTLS_MD_SHA1;
4341         }
4342     } else
4343 #endif /* MBEDTLS_SSL_PROTO_SSL3 || MBEDTLS_SSL_PROTO_TLS1 ||
4344           MBEDTLS_SSL_PROTO_TLS1_1 */
4345 #if defined(MBEDTLS_SSL_PROTO_TLS1_2)
4346     if (ssl->minor_ver == MBEDTLS_SSL_MINOR_VERSION_3) {
4347         if (i + 2 > ssl->in_hslen) {
4348             MBEDTLS_SSL_DEBUG_MSG(1, ("bad certificate verify message"));
4349             return MBEDTLS_ERR_SSL_BAD_HS_CERTIFICATE_VERIFY;
4350         }
4351 
4352         /*
4353          * Hash
4354          */
4355         md_alg = mbedtls_ssl_md_alg_from_hash(ssl->in_msg[i]);
4356 
4357         if (md_alg == MBEDTLS_MD_NONE || mbedtls_ssl_set_calc_verify_md(ssl, ssl->in_msg[i])) {
4358             MBEDTLS_SSL_DEBUG_MSG(1, ("peer not adhering to requested sig_alg"
4359                                       " for verify message"));
4360             return MBEDTLS_ERR_SSL_BAD_HS_CERTIFICATE_VERIFY;
4361         }
4362 
4363 #if !defined(MBEDTLS_MD_SHA1)
4364         if (MBEDTLS_MD_SHA1 == md_alg) {
4365             hash_start += 16;
4366         }
4367 #endif
4368 
4369         /* Info from md_alg will be used instead */
4370         hashlen = 0;
4371 
4372         i++;
4373 
4374         /*
4375          * Signature
4376          */
4377         if ((pk_alg = mbedtls_ssl_pk_alg_from_sig(ssl->in_msg[i]))
4378             == MBEDTLS_PK_NONE) {
4379             MBEDTLS_SSL_DEBUG_MSG(1, ("peer not adhering to requested sig_alg"
4380                                       " for verify message"));
4381             return MBEDTLS_ERR_SSL_BAD_HS_CERTIFICATE_VERIFY;
4382         }
4383 
4384         /*
4385          * Check the certificate's key type matches the signature alg
4386          */
4387         if (!mbedtls_pk_can_do(peer_pk, pk_alg)) {
4388             MBEDTLS_SSL_DEBUG_MSG(1, ("sig_alg doesn't match cert key"));
4389             return MBEDTLS_ERR_SSL_BAD_HS_CERTIFICATE_VERIFY;
4390         }
4391 
4392         i++;
4393     } else
4394 #endif /* MBEDTLS_SSL_PROTO_TLS1_2 */
4395     {
4396         MBEDTLS_SSL_DEBUG_MSG(1, ("should never happen"));
4397         return MBEDTLS_ERR_SSL_INTERNAL_ERROR;
4398     }
4399 
4400     if (i + 2 > ssl->in_hslen) {
4401         MBEDTLS_SSL_DEBUG_MSG(1, ("bad certificate verify message"));
4402         return MBEDTLS_ERR_SSL_BAD_HS_CERTIFICATE_VERIFY;
4403     }
4404 
4405     sig_len = (ssl->in_msg[i] << 8) | ssl->in_msg[i+1];
4406     i += 2;
4407 
4408     if (i + sig_len != ssl->in_hslen) {
4409         MBEDTLS_SSL_DEBUG_MSG(1, ("bad certificate verify message"));
4410         return MBEDTLS_ERR_SSL_BAD_HS_CERTIFICATE_VERIFY;
4411     }
4412 
4413     /* Calculate hash and verify signature */
4414     {
4415         size_t dummy_hlen;
4416         ssl->handshake->calc_verify(ssl, hash, &dummy_hlen);
4417     }
4418 
4419     if ((ret = mbedtls_pk_verify(peer_pk,
4420                                  md_alg, hash_start, hashlen,
4421                                  ssl->in_msg + i, sig_len)) != 0) {
4422         MBEDTLS_SSL_DEBUG_RET(1, "mbedtls_pk_verify", ret);
4423         return ret;
4424     }
4425 
4426     mbedtls_ssl_update_handshake_status(ssl);
4427 
4428     MBEDTLS_SSL_DEBUG_MSG(2, ("<= parse certificate verify"));
4429 
4430     return ret;
4431 }
4432 #endif /* MBEDTLS_KEY_EXCHANGE_CERT_REQ_ALLOWED_ENABLED */
4433 
4434 #if defined(MBEDTLS_SSL_SESSION_TICKETS)
4435 MBEDTLS_CHECK_RETURN_CRITICAL
ssl_write_new_session_ticket(mbedtls_ssl_context * ssl)4436 static int ssl_write_new_session_ticket(mbedtls_ssl_context *ssl)
4437 {
4438     int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
4439     size_t tlen;
4440     uint32_t lifetime;
4441 
4442     MBEDTLS_SSL_DEBUG_MSG(2, ("=> write new session ticket"));
4443 
4444     ssl->out_msgtype = MBEDTLS_SSL_MSG_HANDSHAKE;
4445     ssl->out_msg[0]  = MBEDTLS_SSL_HS_NEW_SESSION_TICKET;
4446 
4447     /*
4448      * struct {
4449      *     uint32 ticket_lifetime_hint;
4450      *     opaque ticket<0..2^16-1>;
4451      * } NewSessionTicket;
4452      *
4453      * 4  .  7   ticket_lifetime_hint (0 = unspecified)
4454      * 8  .  9   ticket_len (n)
4455      * 10 .  9+n ticket content
4456      */
4457 
4458     if ((ret = ssl->conf->f_ticket_write(ssl->conf->p_ticket,
4459                                          ssl->session_negotiate,
4460                                          ssl->out_msg + 10,
4461                                          ssl->out_msg + MBEDTLS_SSL_OUT_CONTENT_LEN,
4462                                          &tlen, &lifetime)) != 0) {
4463         MBEDTLS_SSL_DEBUG_RET(1, "mbedtls_ssl_ticket_write", ret);
4464         tlen = 0;
4465     }
4466 
4467     MBEDTLS_PUT_UINT32_BE(lifetime, ssl->out_msg, 4);
4468     MBEDTLS_PUT_UINT16_BE(tlen, ssl->out_msg, 8);
4469     ssl->out_msglen = 10 + tlen;
4470 
4471     /*
4472      * Morally equivalent to updating ssl->state, but NewSessionTicket and
4473      * ChangeCipherSpec share the same state.
4474      */
4475     ssl->handshake->new_session_ticket = 0;
4476 
4477     if ((ret = mbedtls_ssl_write_handshake_msg(ssl)) != 0) {
4478         MBEDTLS_SSL_DEBUG_RET(1, "mbedtls_ssl_write_handshake_msg", ret);
4479         return ret;
4480     }
4481 
4482     MBEDTLS_SSL_DEBUG_MSG(2, ("<= write new session ticket"));
4483 
4484     return 0;
4485 }
4486 #endif /* MBEDTLS_SSL_SESSION_TICKETS */
4487 
4488 /*
4489  * SSL handshake -- server side -- single step
4490  */
mbedtls_ssl_handshake_server_step(mbedtls_ssl_context * ssl)4491 int mbedtls_ssl_handshake_server_step(mbedtls_ssl_context *ssl)
4492 {
4493     int ret = 0;
4494 
4495     if (ssl->state == MBEDTLS_SSL_HANDSHAKE_OVER || ssl->handshake == NULL) {
4496         return MBEDTLS_ERR_SSL_BAD_INPUT_DATA;
4497     }
4498 
4499     MBEDTLS_SSL_DEBUG_MSG(2, ("server state: %d", ssl->state));
4500 
4501     if ((ret = mbedtls_ssl_flush_output(ssl)) != 0) {
4502         return ret;
4503     }
4504 
4505 #if defined(MBEDTLS_SSL_PROTO_DTLS)
4506     if (ssl->conf->transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM &&
4507         ssl->handshake->retransmit_state == MBEDTLS_SSL_RETRANS_SENDING) {
4508         if ((ret = mbedtls_ssl_flight_transmit(ssl)) != 0) {
4509             return ret;
4510         }
4511     }
4512 #endif /* MBEDTLS_SSL_PROTO_DTLS */
4513 
4514     switch (ssl->state) {
4515         case MBEDTLS_SSL_HELLO_REQUEST:
4516             ssl->state = MBEDTLS_SSL_CLIENT_HELLO;
4517             break;
4518 
4519         /*
4520          *  <==   ClientHello
4521          */
4522         case MBEDTLS_SSL_CLIENT_HELLO:
4523             ret = ssl_parse_client_hello(ssl);
4524             break;
4525 
4526 #if defined(MBEDTLS_SSL_PROTO_DTLS)
4527         case MBEDTLS_SSL_SERVER_HELLO_VERIFY_REQUEST_SENT:
4528             return MBEDTLS_ERR_SSL_HELLO_VERIFY_REQUIRED;
4529 #endif
4530 
4531         /*
4532          *  ==>   ServerHello
4533          *        Certificate
4534          *      ( ServerKeyExchange  )
4535          *      ( CertificateRequest )
4536          *        ServerHelloDone
4537          */
4538         case MBEDTLS_SSL_SERVER_HELLO:
4539             ret = ssl_write_server_hello(ssl);
4540             break;
4541 
4542         case MBEDTLS_SSL_SERVER_CERTIFICATE:
4543             ret = mbedtls_ssl_write_certificate(ssl);
4544             break;
4545 
4546         case MBEDTLS_SSL_SERVER_KEY_EXCHANGE:
4547             ret = ssl_write_server_key_exchange(ssl);
4548             break;
4549 
4550         case MBEDTLS_SSL_CERTIFICATE_REQUEST:
4551             ret = ssl_write_certificate_request(ssl);
4552             break;
4553 
4554         case MBEDTLS_SSL_SERVER_HELLO_DONE:
4555             ret = ssl_write_server_hello_done(ssl);
4556             break;
4557 
4558         /*
4559          *  <== ( Certificate/Alert  )
4560          *        ClientKeyExchange
4561          *      ( CertificateVerify  )
4562          *        ChangeCipherSpec
4563          *        Finished
4564          */
4565         case MBEDTLS_SSL_CLIENT_CERTIFICATE:
4566             ret = mbedtls_ssl_parse_certificate(ssl);
4567             break;
4568 
4569         case MBEDTLS_SSL_CLIENT_KEY_EXCHANGE:
4570             ret = ssl_parse_client_key_exchange(ssl);
4571             break;
4572 
4573         case MBEDTLS_SSL_CERTIFICATE_VERIFY:
4574             ret = ssl_parse_certificate_verify(ssl);
4575             break;
4576 
4577         case MBEDTLS_SSL_CLIENT_CHANGE_CIPHER_SPEC:
4578             ret = mbedtls_ssl_parse_change_cipher_spec(ssl);
4579             break;
4580 
4581         case MBEDTLS_SSL_CLIENT_FINISHED:
4582             ret = mbedtls_ssl_parse_finished(ssl);
4583             break;
4584 
4585         /*
4586          *  ==> ( NewSessionTicket )
4587          *        ChangeCipherSpec
4588          *        Finished
4589          */
4590         case MBEDTLS_SSL_SERVER_CHANGE_CIPHER_SPEC:
4591 #if defined(MBEDTLS_SSL_SESSION_TICKETS)
4592             if (ssl->handshake->new_session_ticket != 0) {
4593                 ret = ssl_write_new_session_ticket(ssl);
4594             } else
4595 #endif
4596             ret = mbedtls_ssl_write_change_cipher_spec(ssl);
4597             break;
4598 
4599         case MBEDTLS_SSL_SERVER_FINISHED:
4600             ret = mbedtls_ssl_write_finished(ssl);
4601             break;
4602 
4603         case MBEDTLS_SSL_FLUSH_BUFFERS:
4604             MBEDTLS_SSL_DEBUG_MSG(2, ("handshake: done"));
4605             ssl->state = MBEDTLS_SSL_HANDSHAKE_WRAPUP;
4606             break;
4607 
4608         case MBEDTLS_SSL_HANDSHAKE_WRAPUP:
4609             mbedtls_ssl_handshake_wrapup(ssl);
4610             break;
4611 
4612         default:
4613             MBEDTLS_SSL_DEBUG_MSG(1, ("invalid state %d", ssl->state));
4614             return MBEDTLS_ERR_SSL_BAD_INPUT_DATA;
4615     }
4616 
4617     return ret;
4618 }
4619 #endif /* MBEDTLS_SSL_SRV_C */
4620