f7b799030dab83f822f8bdebd85caf48de2e1d46
[openssl.git] / ssl / statem / extensions_srvr.c
1 /*
2  * Copyright 2016 The OpenSSL Project Authors. All Rights Reserved.
3  *
4  * Licensed under the OpenSSL license (the "License").  You may not use
5  * this file except in compliance with the License.  You can obtain a copy
6  * in the file LICENSE in the source distribution or at
7  * https://www.openssl.org/source/license.html
8  */
9
10 #include <openssl/ocsp.h>
11 #include "../ssl_locl.h"
12 #include "statem_locl.h"
13
14 /*
15  * Parse the client's renegotiation binding and abort if it's not right
16  */
17 int tls_parse_ctos_renegotiate(SSL *s, PACKET *pkt, unsigned int context,
18                                X509 *x, size_t chainidx, int *al)
19 {
20     unsigned int ilen;
21     const unsigned char *data;
22
23     /* Parse the length byte */
24     if (!PACKET_get_1(pkt, &ilen)
25         || !PACKET_get_bytes(pkt, &data, ilen)) {
26         SSLerr(SSL_F_TLS_PARSE_CTOS_RENEGOTIATE,
27                SSL_R_RENEGOTIATION_ENCODING_ERR);
28         *al = SSL_AD_ILLEGAL_PARAMETER;
29         return 0;
30     }
31
32     /* Check that the extension matches */
33     if (ilen != s->s3->previous_client_finished_len) {
34         SSLerr(SSL_F_TLS_PARSE_CTOS_RENEGOTIATE,
35                SSL_R_RENEGOTIATION_MISMATCH);
36         *al = SSL_AD_HANDSHAKE_FAILURE;
37         return 0;
38     }
39
40     if (memcmp(data, s->s3->previous_client_finished,
41                s->s3->previous_client_finished_len)) {
42         SSLerr(SSL_F_TLS_PARSE_CTOS_RENEGOTIATE,
43                SSL_R_RENEGOTIATION_MISMATCH);
44         *al = SSL_AD_HANDSHAKE_FAILURE;
45         return 0;
46     }
47
48     s->s3->send_connection_binding = 1;
49
50     return 1;
51 }
52
53 /*-
54  * The servername extension is treated as follows:
55  *
56  * - Only the hostname type is supported with a maximum length of 255.
57  * - The servername is rejected if too long or if it contains zeros,
58  *   in which case an fatal alert is generated.
59  * - The servername field is maintained together with the session cache.
60  * - When a session is resumed, the servername call back invoked in order
61  *   to allow the application to position itself to the right context.
62  * - The servername is acknowledged if it is new for a session or when
63  *   it is identical to a previously used for the same session.
64  *   Applications can control the behaviour.  They can at any time
65  *   set a 'desirable' servername for a new SSL object. This can be the
66  *   case for example with HTTPS when a Host: header field is received and
67  *   a renegotiation is requested. In this case, a possible servername
68  *   presented in the new client hello is only acknowledged if it matches
69  *   the value of the Host: field.
70  * - Applications must  use SSL_OP_NO_SESSION_RESUMPTION_ON_RENEGOTIATION
71  *   if they provide for changing an explicit servername context for the
72  *   session, i.e. when the session has been established with a servername
73  *   extension.
74  * - On session reconnect, the servername extension may be absent.
75  */
76 int tls_parse_ctos_server_name(SSL *s, PACKET *pkt, unsigned int context,
77                                X509 *x, size_t chainidx, int *al)
78 {
79     unsigned int servname_type;
80     PACKET sni, hostname;
81
82     if (!PACKET_as_length_prefixed_2(pkt, &sni)
83         /* ServerNameList must be at least 1 byte long. */
84         || PACKET_remaining(&sni) == 0) {
85         *al = SSL_AD_DECODE_ERROR;
86         return 0;
87     }
88
89     /*
90      * Although the server_name extension was intended to be
91      * extensible to new name types, RFC 4366 defined the
92      * syntax inextensibly and OpenSSL 1.0.x parses it as
93      * such.
94      * RFC 6066 corrected the mistake but adding new name types
95      * is nevertheless no longer feasible, so act as if no other
96      * SNI types can exist, to simplify parsing.
97      *
98      * Also note that the RFC permits only one SNI value per type,
99      * i.e., we can only have a single hostname.
100      */
101     if (!PACKET_get_1(&sni, &servname_type)
102         || servname_type != TLSEXT_NAMETYPE_host_name
103         || !PACKET_as_length_prefixed_2(&sni, &hostname)) {
104         *al = SSL_AD_DECODE_ERROR;
105         return 0;
106     }
107
108     if (!s->hit) {
109         if (PACKET_remaining(&hostname) > TLSEXT_MAXLEN_host_name) {
110             *al = TLS1_AD_UNRECOGNIZED_NAME;
111             return 0;
112         }
113
114         if (PACKET_contains_zero_byte(&hostname)) {
115             *al = TLS1_AD_UNRECOGNIZED_NAME;
116             return 0;
117         }
118
119         OPENSSL_free(s->session->ext.hostname);
120         s->session->ext.hostname = NULL;
121         if (!PACKET_strndup(&hostname, &s->session->ext.hostname)) {
122             *al = TLS1_AD_INTERNAL_ERROR;
123             return 0;
124         }
125
126         s->servername_done = 1;
127     } else {
128         /*
129          * TODO(openssl-team): if the SNI doesn't match, we MUST
130          * fall back to a full handshake.
131          */
132         s->servername_done = s->session->ext.hostname
133             && PACKET_equal(&hostname, s->session->ext.hostname,
134                             strlen(s->session->ext.hostname));
135     }
136
137     return 1;
138 }
139
140 #ifndef OPENSSL_NO_SRP
141 int tls_parse_ctos_srp(SSL *s, PACKET *pkt, unsigned int context, X509 *x,
142                        size_t chainidx, int *al)
143 {
144     PACKET srp_I;
145
146     if (!PACKET_as_length_prefixed_1(pkt, &srp_I)
147             || PACKET_contains_zero_byte(&srp_I)) {
148         *al = SSL_AD_DECODE_ERROR;
149         return 0;
150     }
151
152     /*
153      * TODO(openssl-team): currently, we re-authenticate the user
154      * upon resumption. Instead, we MUST ignore the login.
155      */
156     if (!PACKET_strndup(&srp_I, &s->srp_ctx.login)) {
157         *al = TLS1_AD_INTERNAL_ERROR;
158         return 0;
159     }
160
161     return 1;
162 }
163 #endif
164
165 #ifndef OPENSSL_NO_EC
166 int tls_parse_ctos_ec_pt_formats(SSL *s, PACKET *pkt, unsigned int context,
167                                  X509 *x, size_t chainidx, int *al)
168 {
169     PACKET ec_point_format_list;
170
171     if (!PACKET_as_length_prefixed_1(pkt, &ec_point_format_list)
172         || PACKET_remaining(&ec_point_format_list) == 0) {
173         *al = SSL_AD_DECODE_ERROR;
174         return 0;
175     }
176
177     if (!s->hit) {
178         if (!PACKET_memdup(&ec_point_format_list,
179                            &s->session->ext.ecpointformats,
180                            &s->session->ext.ecpointformats_len)) {
181             *al = TLS1_AD_INTERNAL_ERROR;
182             return 0;
183         }
184     }
185
186     return 1;
187 }
188 #endif                          /* OPENSSL_NO_EC */
189
190 int tls_parse_ctos_session_ticket(SSL *s, PACKET *pkt, unsigned int context,
191                                   X509 *x, size_t chainidx, int *al)
192 {
193     if (s->ext.session_ticket_cb &&
194             !s->ext.session_ticket_cb(s, PACKET_data(pkt),
195                                   PACKET_remaining(pkt),
196                                   s->ext.session_ticket_cb_arg)) {
197         *al = TLS1_AD_INTERNAL_ERROR;
198         return 0;
199     }
200
201     return 1;
202 }
203
204 int tls_parse_ctos_sig_algs(SSL *s, PACKET *pkt, unsigned int context, X509 *x,
205                             size_t chainidx, int *al)
206 {
207     PACKET supported_sig_algs;
208
209     if (!PACKET_as_length_prefixed_2(pkt, &supported_sig_algs)
210             || PACKET_remaining(&supported_sig_algs) == 0) {
211         *al = SSL_AD_DECODE_ERROR;
212         return 0;
213     }
214
215     if (!s->hit && !tls1_save_sigalgs(s, &supported_sig_algs)) {
216         *al = TLS1_AD_DECODE_ERROR;
217         return 0;
218     }
219
220     return 1;
221 }
222
223 #ifndef OPENSSL_NO_OCSP
224 int tls_parse_ctos_status_request(SSL *s, PACKET *pkt, unsigned int context,
225                                   X509 *x, size_t chainidx, int *al)
226 {
227     PACKET responder_id_list, exts;
228
229     /* Not defined if we get one of these in a client Certificate */
230     if (x != NULL)
231         return 1;
232
233     if (!PACKET_get_1(pkt, (unsigned int *)&s->ext.status_type)) {
234         *al = SSL_AD_DECODE_ERROR;
235         return 0;
236     }
237
238     if (s->ext.status_type != TLSEXT_STATUSTYPE_ocsp) {
239         /*
240          * We don't know what to do with any other type so ignore it.
241          */
242         s->ext.status_type = TLSEXT_STATUSTYPE_nothing;
243         return 1;
244     }
245
246     if (!PACKET_get_length_prefixed_2 (pkt, &responder_id_list)) {
247         *al = SSL_AD_DECODE_ERROR;
248         return 0;
249     }
250
251     /*
252      * We remove any OCSP_RESPIDs from a previous handshake
253      * to prevent unbounded memory growth - CVE-2016-6304
254      */
255     sk_OCSP_RESPID_pop_free(s->ext.ocsp.ids, OCSP_RESPID_free);
256     if (PACKET_remaining(&responder_id_list) > 0) {
257         s->ext.ocsp.ids = sk_OCSP_RESPID_new_null();
258         if (s->ext.ocsp.ids == NULL) {
259             *al = SSL_AD_INTERNAL_ERROR;
260             return 0;
261         }
262     } else {
263         s->ext.ocsp.ids = NULL;
264     }
265
266     while (PACKET_remaining(&responder_id_list) > 0) {
267         OCSP_RESPID *id;
268         PACKET responder_id;
269         const unsigned char *id_data;
270
271         if (!PACKET_get_length_prefixed_2(&responder_id_list, &responder_id)
272                 || PACKET_remaining(&responder_id) == 0) {
273             *al = SSL_AD_DECODE_ERROR;
274             return 0;
275         }
276
277         id_data = PACKET_data(&responder_id);
278         /* TODO(size_t): Convert d2i_* to size_t */
279         id = d2i_OCSP_RESPID(NULL, &id_data,
280                              (int)PACKET_remaining(&responder_id));
281         if (id == NULL) {
282             *al = SSL_AD_DECODE_ERROR;
283             return 0;
284         }
285
286         if (id_data != PACKET_end(&responder_id)) {
287             OCSP_RESPID_free(id);
288             *al = SSL_AD_DECODE_ERROR;
289             return 0;
290         }
291
292         if (!sk_OCSP_RESPID_push(s->ext.ocsp.ids, id)) {
293             OCSP_RESPID_free(id);
294             *al = SSL_AD_INTERNAL_ERROR;
295             return 0;
296         }
297     }
298
299     /* Read in request_extensions */
300     if (!PACKET_as_length_prefixed_2(pkt, &exts)) {
301         *al = SSL_AD_DECODE_ERROR;
302         return 0;
303     }
304
305     if (PACKET_remaining(&exts) > 0) {
306         const unsigned char *ext_data = PACKET_data(&exts);
307
308         sk_X509_EXTENSION_pop_free(s->ext.ocsp.exts,
309                                    X509_EXTENSION_free);
310         s->ext.ocsp.exts =
311             d2i_X509_EXTENSIONS(NULL, &ext_data, (int)PACKET_remaining(&exts));
312         if (s->ext.ocsp.exts == NULL || ext_data != PACKET_end(&exts)) {
313             *al = SSL_AD_DECODE_ERROR;
314             return 0;
315         }
316     }
317
318     return 1;
319 }
320 #endif
321
322 #ifndef OPENSSL_NO_NEXTPROTONEG
323 int tls_parse_ctos_npn(SSL *s, PACKET *pkt, unsigned int context, X509 *x,
324                        size_t chainidx, int *al)
325 {
326     /*
327      * We shouldn't accept this extension on a
328      * renegotiation.
329      */
330     if (SSL_IS_FIRST_HANDSHAKE(s))
331         s->s3->npn_seen = 1;
332
333     return 1;
334 }
335 #endif
336
337 /*
338  * Save the ALPN extension in a ClientHello.|pkt| holds the contents of the ALPN
339  * extension, not including type and length. |al| is a pointer to the alert
340  * value to send in the event of a failure. Returns: 1 on success, 0 on error.
341  */
342 int tls_parse_ctos_alpn(SSL *s, PACKET *pkt, unsigned int context, X509 *x,
343                         size_t chainidx, int *al)
344 {
345     PACKET protocol_list, save_protocol_list, protocol;
346
347     if (!SSL_IS_FIRST_HANDSHAKE(s))
348         return 1;
349
350     if (!PACKET_as_length_prefixed_2(pkt, &protocol_list)
351         || PACKET_remaining(&protocol_list) < 2) {
352         *al = SSL_AD_DECODE_ERROR;
353         return 0;
354     }
355
356     save_protocol_list = protocol_list;
357     do {
358         /* Protocol names can't be empty. */
359         if (!PACKET_get_length_prefixed_1(&protocol_list, &protocol)
360                 || PACKET_remaining(&protocol) == 0) {
361             *al = SSL_AD_DECODE_ERROR;
362             return 0;
363         }
364     } while (PACKET_remaining(&protocol_list) != 0);
365
366     OPENSSL_free(s->s3->alpn_proposed);
367     s->s3->alpn_proposed = NULL;
368     s->s3->alpn_proposed_len = 0;
369     if (!PACKET_memdup(&save_protocol_list,
370                        &s->s3->alpn_proposed, &s->s3->alpn_proposed_len)) {
371         *al = TLS1_AD_INTERNAL_ERROR;
372         return 0;
373     }
374
375     return 1;
376 }
377
378 #ifndef OPENSSL_NO_SRTP
379 int tls_parse_ctos_use_srtp(SSL *s, PACKET *pkt, unsigned int context, X509 *x,
380                             size_t chainidx, int *al)
381 {
382     STACK_OF(SRTP_PROTECTION_PROFILE) *srvr;
383     unsigned int ct, mki_len, id;
384     int i, srtp_pref;
385     PACKET subpkt;
386
387     /* Ignore this if we have no SRTP profiles */
388     if (SSL_get_srtp_profiles(s) == NULL)
389         return 1;
390
391     /* Pull off the length of the cipher suite list  and check it is even */
392     if (!PACKET_get_net_2(pkt, &ct) || (ct & 1) != 0
393             || !PACKET_get_sub_packet(pkt, &subpkt, ct)) {
394         SSLerr(SSL_F_TLS_PARSE_CTOS_USE_SRTP,
395                SSL_R_BAD_SRTP_PROTECTION_PROFILE_LIST);
396         *al = SSL_AD_DECODE_ERROR;
397         return 0;
398     }
399
400     srvr = SSL_get_srtp_profiles(s);
401     s->srtp_profile = NULL;
402     /* Search all profiles for a match initially */
403     srtp_pref = sk_SRTP_PROTECTION_PROFILE_num(srvr);
404
405     while (PACKET_remaining(&subpkt)) {
406         if (!PACKET_get_net_2(&subpkt, &id)) {
407             SSLerr(SSL_F_TLS_PARSE_CTOS_USE_SRTP,
408                    SSL_R_BAD_SRTP_PROTECTION_PROFILE_LIST);
409             *al = SSL_AD_DECODE_ERROR;
410             return 0;
411         }
412
413         /*
414          * Only look for match in profiles of higher preference than
415          * current match.
416          * If no profiles have been have been configured then this
417          * does nothing.
418          */
419         for (i = 0; i < srtp_pref; i++) {
420             SRTP_PROTECTION_PROFILE *sprof =
421                 sk_SRTP_PROTECTION_PROFILE_value(srvr, i);
422
423             if (sprof->id == id) {
424                 s->srtp_profile = sprof;
425                 srtp_pref = i;
426                 break;
427             }
428         }
429     }
430
431     /* Now extract the MKI value as a sanity check, but discard it for now */
432     if (!PACKET_get_1(pkt, &mki_len)) {
433         SSLerr(SSL_F_TLS_PARSE_CTOS_USE_SRTP,
434                SSL_R_BAD_SRTP_PROTECTION_PROFILE_LIST);
435         *al = SSL_AD_DECODE_ERROR;
436         return 0;
437     }
438
439     if (!PACKET_forward(pkt, mki_len)
440         || PACKET_remaining(pkt)) {
441         SSLerr(SSL_F_TLS_PARSE_CTOS_USE_SRTP, SSL_R_BAD_SRTP_MKI_VALUE);
442         *al = SSL_AD_DECODE_ERROR;
443         return 0;
444     }
445
446     return 1;
447 }
448 #endif
449
450 int tls_parse_ctos_etm(SSL *s, PACKET *pkt, unsigned int context, X509 *x,
451                        size_t chainidx, int *al)
452 {
453     if (!(s->options & SSL_OP_NO_ENCRYPT_THEN_MAC))
454         s->s3->flags |= TLS1_FLAGS_ENCRYPT_THEN_MAC;
455
456     return 1;
457 }
458
459 /*
460  * Checks a list of |groups| to determine if the |group_id| is in it. If it is
461  * and |checkallow| is 1 then additionally check if the group is allowed to be
462  * used. Returns 1 if the group is in the list (and allowed if |checkallow| is
463  * 1) or 0 otherwise.
464  */
465 #ifndef OPENSSL_NO_TLS1_3
466 static int check_in_list(SSL *s, unsigned int group_id,
467                          const unsigned char *groups, size_t num_groups,
468                          int checkallow)
469 {
470     size_t i;
471
472     if (groups == NULL || num_groups == 0)
473         return 0;
474
475     for (i = 0; i < num_groups; i++, groups += 2) {
476         unsigned int share_id = (groups[0] << 8) | (groups[1]);
477
478         if (group_id == share_id
479                 && (!checkallow
480                     || tls_curve_allowed(s, groups, SSL_SECOP_CURVE_CHECK))) {
481             break;
482         }
483     }
484
485     /* If i == num_groups then not in the list */
486     return i < num_groups;
487 }
488 #endif
489
490 /*
491  * Process a psk_kex_modes extension received in the ClientHello. |pkt| contains
492  * the raw PACKET data for the extension. Returns 1 on success or 0 on failure.
493  * If a failure occurs then |*al| is set to an appropriate alert value.
494  */
495 int tls_parse_ctos_psk_kex_modes(SSL *s, PACKET *pkt, unsigned int context,
496                                  X509 *x, size_t chainidx, int *al)
497 {
498 #ifndef OPENSSL_NO_TLS1_3
499     PACKET psk_kex_modes;
500     unsigned int mode;
501
502     if (!PACKET_as_length_prefixed_1(pkt, &psk_kex_modes)
503             || PACKET_remaining(&psk_kex_modes) == 0) {
504         *al = SSL_AD_DECODE_ERROR;
505         return 0;
506     }
507
508     while (PACKET_get_1(&psk_kex_modes, &mode)) {
509         if (mode == TLSEXT_KEX_MODE_KE_DHE)
510             s->ext.psk_kex_mode |= TLSEXT_KEX_MODE_FLAG_KE_DHE;
511         else if (mode == TLSEXT_KEX_MODE_KE)
512             s->ext.psk_kex_mode |= TLSEXT_KEX_MODE_FLAG_KE;
513     }
514 #endif
515
516     return 1;
517 }
518
519 /*
520  * Process a key_share extension received in the ClientHello. |pkt| contains
521  * the raw PACKET data for the extension. Returns 1 on success or 0 on failure.
522  * If a failure occurs then |*al| is set to an appropriate alert value.
523  */
524 int tls_parse_ctos_key_share(SSL *s, PACKET *pkt, unsigned int context, X509 *x,
525                              size_t chainidx, int *al)
526 {
527 #ifndef OPENSSL_NO_TLS1_3
528     unsigned int group_id;
529     PACKET key_share_list, encoded_pt;
530     const unsigned char *clntcurves, *srvrcurves;
531     size_t clnt_num_curves, srvr_num_curves;
532     int group_nid, found = 0;
533     unsigned int curve_flags;
534
535     if (s->hit && (s->ext.psk_kex_mode & TLSEXT_KEX_MODE_FLAG_KE_DHE) == 0)
536         return 1;
537
538     /* Sanity check */
539     if (s->s3->peer_tmp != NULL) {
540         *al = SSL_AD_INTERNAL_ERROR;
541         SSLerr(SSL_F_TLS_PARSE_CTOS_KEY_SHARE, ERR_R_INTERNAL_ERROR);
542         return 0;
543     }
544
545     if (!PACKET_as_length_prefixed_2(pkt, &key_share_list)) {
546         *al = SSL_AD_HANDSHAKE_FAILURE;
547         SSLerr(SSL_F_TLS_PARSE_CTOS_KEY_SHARE, SSL_R_LENGTH_MISMATCH);
548         return 0;
549     }
550
551     /* Get our list of supported curves */
552     if (!tls1_get_curvelist(s, 0, &srvrcurves, &srvr_num_curves)) {
553         *al = SSL_AD_INTERNAL_ERROR;
554         SSLerr(SSL_F_TLS_PARSE_CTOS_KEY_SHARE, ERR_R_INTERNAL_ERROR);
555         return 0;
556     }
557
558     /*
559      * Get the clients list of supported curves.
560      * TODO(TLS1.3): We should validate that we actually received
561      * supported_groups!
562      */
563     if (!tls1_get_curvelist(s, 1, &clntcurves, &clnt_num_curves)) {
564         *al = SSL_AD_INTERNAL_ERROR;
565         SSLerr(SSL_F_TLS_PARSE_CTOS_KEY_SHARE, ERR_R_INTERNAL_ERROR);
566         return 0;
567     }
568
569     while (PACKET_remaining(&key_share_list) > 0) {
570         if (!PACKET_get_net_2(&key_share_list, &group_id)
571                 || !PACKET_get_length_prefixed_2(&key_share_list, &encoded_pt)
572                 || PACKET_remaining(&encoded_pt) == 0) {
573             *al = SSL_AD_HANDSHAKE_FAILURE;
574             SSLerr(SSL_F_TLS_PARSE_CTOS_KEY_SHARE,
575                    SSL_R_LENGTH_MISMATCH);
576             return 0;
577         }
578
579         /*
580          * If we already found a suitable key_share we loop through the
581          * rest to verify the structure, but don't process them.
582          */
583         if (found)
584             continue;
585
586         /* Check if this share is in supported_groups sent from client */
587         if (!check_in_list(s, group_id, clntcurves, clnt_num_curves, 0)) {
588             *al = SSL_AD_HANDSHAKE_FAILURE;
589             SSLerr(SSL_F_TLS_PARSE_CTOS_KEY_SHARE, SSL_R_BAD_KEY_SHARE);
590             return 0;
591         }
592
593         /* Check if this share is for a group we can use */
594         if (!check_in_list(s, group_id, srvrcurves, srvr_num_curves, 1)) {
595             /* Share not suitable */
596             continue;
597         }
598
599         group_nid = tls1_ec_curve_id2nid(group_id, &curve_flags);
600
601         if (group_nid == 0) {
602             *al = SSL_AD_INTERNAL_ERROR;
603             SSLerr(SSL_F_TLS_PARSE_CTOS_KEY_SHARE,
604                    SSL_R_UNABLE_TO_FIND_ECDH_PARAMETERS);
605             return 0;
606         }
607
608         if ((curve_flags & TLS_CURVE_TYPE) == TLS_CURVE_CUSTOM) {
609             /* Can happen for some curves, e.g. X25519 */
610             EVP_PKEY *key = EVP_PKEY_new();
611
612             if (key == NULL || !EVP_PKEY_set_type(key, group_nid)) {
613                 *al = SSL_AD_INTERNAL_ERROR;
614                 SSLerr(SSL_F_TLS_PARSE_CTOS_KEY_SHARE, ERR_R_EVP_LIB);
615                 EVP_PKEY_free(key);
616                 return 0;
617             }
618             s->s3->peer_tmp = key;
619         } else {
620             /* Set up EVP_PKEY with named curve as parameters */
621             EVP_PKEY_CTX *pctx = EVP_PKEY_CTX_new_id(EVP_PKEY_EC, NULL);
622
623             if (pctx == NULL
624                     || EVP_PKEY_paramgen_init(pctx) <= 0
625                     || EVP_PKEY_CTX_set_ec_paramgen_curve_nid(pctx,
626                                                               group_nid) <= 0
627                     || EVP_PKEY_paramgen(pctx, &s->s3->peer_tmp) <= 0) {
628                 *al = SSL_AD_INTERNAL_ERROR;
629                 SSLerr(SSL_F_TLS_PARSE_CTOS_KEY_SHARE, ERR_R_EVP_LIB);
630                 EVP_PKEY_CTX_free(pctx);
631                 return 0;
632             }
633             EVP_PKEY_CTX_free(pctx);
634             pctx = NULL;
635         }
636         s->s3->group_id = group_id;
637
638         if (!EVP_PKEY_set1_tls_encodedpoint(s->s3->peer_tmp,
639                 PACKET_data(&encoded_pt),
640                 PACKET_remaining(&encoded_pt))) {
641             *al = SSL_AD_DECODE_ERROR;
642             SSLerr(SSL_F_TLS_PARSE_CTOS_KEY_SHARE, SSL_R_BAD_ECPOINT);
643             return 0;
644         }
645
646         found = 1;
647     }
648 #endif
649
650     return 1;
651 }
652
653 #ifndef OPENSSL_NO_EC
654 int tls_parse_ctos_supported_groups(SSL *s, PACKET *pkt, unsigned int context,
655                                     X509 *x, size_t chainidx, int *al)
656 {
657     PACKET supported_groups_list;
658
659     /* Each group is 2 bytes and we must have at least 1. */
660     if (!PACKET_as_length_prefixed_2(pkt, &supported_groups_list)
661             || PACKET_remaining(&supported_groups_list) == 0
662             || (PACKET_remaining(&supported_groups_list) % 2) != 0) {
663         *al = SSL_AD_DECODE_ERROR;
664         return 0;
665     }
666
667     OPENSSL_free(s->session->ext.supportedgroups);
668     s->session->ext.supportedgroups = NULL;
669     s->session->ext.supportedgroups_len = 0;
670     if (!PACKET_memdup(&supported_groups_list,
671                        &s->session->ext.supportedgroups,
672                        &s->session->ext.supportedgroups_len)) {
673         *al = SSL_AD_DECODE_ERROR;
674         return 0;
675     }
676
677     return 1;
678 }
679 #endif
680
681 int tls_parse_ctos_ems(SSL *s, PACKET *pkt, unsigned int context, X509 *x,
682                        size_t chainidx, int *al)
683 {
684     /* The extension must always be empty */
685     if (PACKET_remaining(pkt) != 0) {
686         *al = SSL_AD_DECODE_ERROR;
687         return 0;
688     }
689
690     s->s3->flags |= TLS1_FLAGS_RECEIVED_EXTMS;
691
692     return 1;
693 }
694
695 int tls_parse_ctos_psk(SSL *s, PACKET *pkt, unsigned int context, X509 *x,
696                        size_t chainidx, int *al)
697 {
698     PACKET identities, binders, binder;
699     size_t binderoffset, hashsize;
700     SSL_SESSION *sess = NULL;
701     unsigned int id, i;
702     const EVP_MD *md = NULL;
703
704     /*
705      * If we have no PSK kex mode that we recognise then we can't resume so
706      * ignore this extension
707      */
708     if ((s->ext.psk_kex_mode
709             & (TLSEXT_KEX_MODE_FLAG_KE | TLSEXT_KEX_MODE_FLAG_KE_DHE)) == 0)
710         return 1;
711
712     if (!PACKET_get_length_prefixed_2(pkt, &identities)) {
713         *al = SSL_AD_DECODE_ERROR;
714         return 0;
715     }
716
717     for (id = 0; PACKET_remaining(&identities) != 0; id++) {
718         PACKET identity;
719         unsigned long ticket_age;
720         int ret;
721
722         if (!PACKET_get_length_prefixed_2(&identities, &identity)
723                 || !PACKET_get_net_4(&identities, &ticket_age)) {
724             *al = SSL_AD_DECODE_ERROR;
725             return 0;
726         }
727
728         /* TODO(TLS1.3): Should we validate the ticket age? */
729
730         ret = tls_decrypt_ticket(s, PACKET_data(&identity),
731                                  PACKET_remaining(&identity), NULL, 0, &sess);
732         if (ret == TICKET_FATAL_ERR_MALLOC || ret == TICKET_FATAL_ERR_OTHER) {
733             *al = SSL_AD_INTERNAL_ERROR;
734             return 0;
735         }
736         if (ret == TICKET_NO_DECRYPT)
737             continue;
738
739         md = ssl_md(sess->cipher->algorithm2);
740         if (md == NULL) {
741             /*
742              * Don't recognise this cipher so we can't use the session.
743              * Ignore it
744              */
745             SSL_SESSION_free(sess);
746             sess = NULL;
747             continue;
748         }
749
750         /*
751          * TODO(TLS1.3): Somehow we need to handle the case of a ticket renewal.
752          * Ignored for now
753          */
754
755         break;
756     }
757
758     if (sess == NULL)
759         return 1;
760
761     binderoffset = PACKET_data(pkt) - (const unsigned char *)s->init_buf->data;
762     hashsize = EVP_MD_size(md);
763
764     if (!PACKET_get_length_prefixed_2(pkt, &binders)) {
765         *al = SSL_AD_DECODE_ERROR;
766         goto err;
767     }
768
769     for (i = 0; i <= id; i++) {
770         if (!PACKET_get_length_prefixed_1(&binders, &binder)) {
771             *al = SSL_AD_DECODE_ERROR;
772             goto err;
773         }
774     }
775
776     if (PACKET_remaining(&binder) != hashsize
777             || tls_psk_do_binder(s, md,
778                                  (const unsigned char *)s->init_buf->data,
779                                  binderoffset, PACKET_data(&binder), NULL,
780                                  sess, 0) != 1) {
781         *al = SSL_AD_DECODE_ERROR;
782         SSLerr(SSL_F_TLS_PARSE_CTOS_PSK, ERR_R_INTERNAL_ERROR);
783         goto err;
784     }
785
786     sess->ext.tick_identity = id;
787     SSL_SESSION_free(s->session);
788     s->session = sess;
789     return 1;
790 err:
791     return 0;
792 }
793
794 /*
795  * Add the server's renegotiation binding
796  */
797 int tls_construct_stoc_renegotiate(SSL *s, WPACKET *pkt, unsigned int context,
798                                    X509 *x, size_t chainidx, int *al)
799 {
800     if (!s->s3->send_connection_binding)
801         return 1;
802
803     if (!WPACKET_put_bytes_u16(pkt, TLSEXT_TYPE_renegotiate)
804             || !WPACKET_start_sub_packet_u16(pkt)
805             || !WPACKET_start_sub_packet_u8(pkt)
806             || !WPACKET_memcpy(pkt, s->s3->previous_client_finished,
807                                s->s3->previous_client_finished_len)
808             || !WPACKET_memcpy(pkt, s->s3->previous_server_finished,
809                                s->s3->previous_server_finished_len)
810             || !WPACKET_close(pkt)
811             || !WPACKET_close(pkt)) {
812         SSLerr(SSL_F_TLS_CONSTRUCT_STOC_RENEGOTIATE, ERR_R_INTERNAL_ERROR);
813         return 0;
814     }
815
816     return 1;
817 }
818
819 int tls_construct_stoc_server_name(SSL *s, WPACKET *pkt, unsigned int context,
820                                    X509 *x, size_t chainidx, int *al)
821 {
822     if (s->hit || s->servername_done != 1
823             || s->session->ext.hostname == NULL)
824         return 1;
825
826     if (!WPACKET_put_bytes_u16(pkt, TLSEXT_TYPE_server_name)
827             || !WPACKET_put_bytes_u16(pkt, 0)) {
828         SSLerr(SSL_F_TLS_CONSTRUCT_STOC_SERVER_NAME, ERR_R_INTERNAL_ERROR);
829         return 0;
830     }
831
832     return 1;
833 }
834
835 #ifndef OPENSSL_NO_EC
836 int tls_construct_stoc_ec_pt_formats(SSL *s, WPACKET *pkt, unsigned int context,
837                                      X509 *x, size_t chainidx, int *al)
838 {
839     unsigned long alg_k = s->s3->tmp.new_cipher->algorithm_mkey;
840     unsigned long alg_a = s->s3->tmp.new_cipher->algorithm_auth;
841     int using_ecc = ((alg_k & SSL_kECDHE) || (alg_a & SSL_aECDSA))
842                     && (s->session->ext.ecpointformats != NULL);
843     const unsigned char *plist;
844     size_t plistlen;
845
846     if (!using_ecc)
847         return 1;
848
849     tls1_get_formatlist(s, &plist, &plistlen);
850     if (!WPACKET_put_bytes_u16(pkt, TLSEXT_TYPE_ec_point_formats)
851             || !WPACKET_start_sub_packet_u16(pkt)
852             || !WPACKET_sub_memcpy_u8(pkt, plist, plistlen)
853             || !WPACKET_close(pkt)) {
854         SSLerr(SSL_F_TLS_CONSTRUCT_STOC_EC_PT_FORMATS, ERR_R_INTERNAL_ERROR);
855         return 0;
856     }
857
858     return 1;
859 }
860 #endif
861
862 int tls_construct_stoc_session_ticket(SSL *s, WPACKET *pkt,
863                                       unsigned int context, X509 *x,
864                                       size_t chainidx, int *al)
865 {
866     if (!s->ext.ticket_expected || !tls_use_ticket(s)) {
867         s->ext.ticket_expected = 0;
868         return 1;
869     }
870
871     if (!WPACKET_put_bytes_u16(pkt, TLSEXT_TYPE_session_ticket)
872             || !WPACKET_put_bytes_u16(pkt, 0)) {
873         SSLerr(SSL_F_TLS_CONSTRUCT_STOC_SESSION_TICKET, ERR_R_INTERNAL_ERROR);
874         return 0;
875     }
876
877     return 1;
878 }
879
880 #ifndef OPENSSL_NO_OCSP
881 int tls_construct_stoc_status_request(SSL *s, WPACKET *pkt,
882                                       unsigned int context, X509 *x,
883                                       size_t chainidx, int *al)
884 {
885     if (!s->ext.status_expected)
886         return 1;
887
888     if (SSL_IS_TLS13(s) && chainidx != 0)
889         return 1;
890
891     if (!WPACKET_put_bytes_u16(pkt, TLSEXT_TYPE_status_request)
892             || !WPACKET_start_sub_packet_u16(pkt)) {
893         SSLerr(SSL_F_TLS_CONSTRUCT_STOC_STATUS_REQUEST, ERR_R_INTERNAL_ERROR);
894         return 0;
895     }
896
897     /*
898      * In TLSv1.3 we include the certificate status itself. In <= TLSv1.2 we
899      * send back an empty extension, with the certificate status appearing as a
900      * separate message
901      */
902     if ((SSL_IS_TLS13(s) && !tls_construct_cert_status_body(s, pkt))
903             || !WPACKET_close(pkt)) {
904         SSLerr(SSL_F_TLS_CONSTRUCT_STOC_STATUS_REQUEST, ERR_R_INTERNAL_ERROR);
905         return 0;
906     }
907
908     return 1;
909 }
910 #endif
911
912 #ifndef OPENSSL_NO_NEXTPROTONEG
913 int tls_construct_stoc_next_proto_neg(SSL *s, WPACKET *pkt,
914                                       unsigned int context, X509 *x,
915                                       size_t chainidx, int *al)
916 {
917     const unsigned char *npa;
918     unsigned int npalen;
919     int ret;
920     int npn_seen = s->s3->npn_seen;
921
922     s->s3->npn_seen = 0;
923     if (!npn_seen || s->ctx->ext.npn_advertised_cb == NULL)
924         return 1;
925
926     ret = s->ctx->ext.npn_advertised_cb(s, &npa, &npalen,
927                                         s->ctx->ext.npn_advertised_cb_arg);
928     if (ret == SSL_TLSEXT_ERR_OK) {
929         if (!WPACKET_put_bytes_u16(pkt, TLSEXT_TYPE_next_proto_neg)
930                 || !WPACKET_sub_memcpy_u16(pkt, npa, npalen)) {
931             SSLerr(SSL_F_TLS_CONSTRUCT_STOC_NEXT_PROTO_NEG,
932                    ERR_R_INTERNAL_ERROR);
933             return 0;
934         }
935         s->s3->npn_seen = 1;
936     }
937
938     return 1;
939 }
940 #endif
941
942 int tls_construct_stoc_alpn(SSL *s, WPACKET *pkt, unsigned int context, X509 *x,
943                             size_t chainidx, int *al)
944 {
945     if (s->s3->alpn_selected == NULL)
946         return 1;
947
948     if (!WPACKET_put_bytes_u16(pkt,
949                 TLSEXT_TYPE_application_layer_protocol_negotiation)
950             || !WPACKET_start_sub_packet_u16(pkt)
951             || !WPACKET_start_sub_packet_u16(pkt)
952             || !WPACKET_sub_memcpy_u8(pkt, s->s3->alpn_selected,
953                                       s->s3->alpn_selected_len)
954             || !WPACKET_close(pkt)
955             || !WPACKET_close(pkt)) {
956         SSLerr(SSL_F_TLS_CONSTRUCT_STOC_ALPN, ERR_R_INTERNAL_ERROR);
957         return 0;
958     }
959
960     return 1;
961 }
962
963 #ifndef OPENSSL_NO_SRTP
964 int tls_construct_stoc_use_srtp(SSL *s, WPACKET *pkt, unsigned int context,
965                                 X509 *x, size_t chainidx, int *al)
966 {
967     if (s->srtp_profile == NULL)
968         return 1;
969
970     if (!WPACKET_put_bytes_u16(pkt, TLSEXT_TYPE_use_srtp)
971             || !WPACKET_start_sub_packet_u16(pkt)
972             || !WPACKET_put_bytes_u16(pkt, 2)
973             || !WPACKET_put_bytes_u16(pkt, s->srtp_profile->id)
974             || !WPACKET_put_bytes_u8(pkt, 0)
975             || !WPACKET_close(pkt)) {
976         SSLerr(SSL_F_TLS_CONSTRUCT_STOC_USE_SRTP, ERR_R_INTERNAL_ERROR);
977         return 0;
978     }
979
980     return 1;
981 }
982 #endif
983
984 int tls_construct_stoc_etm(SSL *s, WPACKET *pkt, unsigned int context, X509 *x,
985                            size_t chainidx, int *al)
986 {
987     if ((s->s3->flags & TLS1_FLAGS_ENCRYPT_THEN_MAC) == 0)
988         return 1;
989
990     /*
991      * Don't use encrypt_then_mac if AEAD or RC4 might want to disable
992      * for other cases too.
993      */
994     if (s->s3->tmp.new_cipher->algorithm_mac == SSL_AEAD
995         || s->s3->tmp.new_cipher->algorithm_enc == SSL_RC4
996         || s->s3->tmp.new_cipher->algorithm_enc == SSL_eGOST2814789CNT
997         || s->s3->tmp.new_cipher->algorithm_enc == SSL_eGOST2814789CNT12) {
998         s->s3->flags &= ~TLS1_FLAGS_ENCRYPT_THEN_MAC;
999         return 1;
1000     }
1001
1002     if (!WPACKET_put_bytes_u16(pkt, TLSEXT_TYPE_encrypt_then_mac)
1003             || !WPACKET_put_bytes_u16(pkt, 0)) {
1004         SSLerr(SSL_F_TLS_CONSTRUCT_STOC_ETM, ERR_R_INTERNAL_ERROR);
1005         return 0;
1006     }
1007
1008     return 1;
1009 }
1010
1011 int tls_construct_stoc_ems(SSL *s, WPACKET *pkt, unsigned int context, X509 *x,
1012                            size_t chainidx, int *al)
1013 {
1014     if ((s->s3->flags & TLS1_FLAGS_RECEIVED_EXTMS) == 0)
1015         return 1;
1016
1017     if (!WPACKET_put_bytes_u16(pkt, TLSEXT_TYPE_extended_master_secret)
1018             || !WPACKET_put_bytes_u16(pkt, 0)) {
1019         SSLerr(SSL_F_TLS_CONSTRUCT_STOC_EMS, ERR_R_INTERNAL_ERROR);
1020         return 0;
1021     }
1022
1023     return 1;
1024 }
1025
1026 int tls_construct_stoc_key_share(SSL *s, WPACKET *pkt, unsigned int context,
1027                                  X509 *x, size_t chainidx, int *al)
1028 {
1029 #ifndef OPENSSL_NO_TLS1_3
1030     unsigned char *encodedPoint;
1031     size_t encoded_pt_len = 0;
1032     EVP_PKEY *ckey = s->s3->peer_tmp, *skey = NULL;
1033
1034     if (ckey == NULL) {
1035         /* No key_share received from client */
1036         if (s->hello_retry_request) {
1037             const unsigned char *pcurves, *pcurvestmp, *clntcurves;
1038             size_t num_curves, clnt_num_curves, i;
1039
1040             /* Get the clients list of supported groups. */
1041             if (!tls1_get_curvelist(s, 1, &clntcurves, &clnt_num_curves)) {
1042                 *al = SSL_AD_INTERNAL_ERROR;
1043                 SSLerr(SSL_F_TLS_CONSTRUCT_STOC_KEY_SHARE,
1044                        ERR_R_INTERNAL_ERROR);
1045                 return 0;
1046             }
1047
1048             /* Get our list of available groups */
1049             if (!tls1_get_curvelist(s, 0, &pcurves, &num_curves)) {
1050                 SSLerr(SSL_F_TLS_CONSTRUCT_STOC_KEY_SHARE,
1051                        ERR_R_INTERNAL_ERROR);
1052                 return 0;
1053             }
1054
1055             if (!WPACKET_put_bytes_u16(pkt, TLSEXT_TYPE_key_share)
1056                     || !WPACKET_start_sub_packet_u16(pkt)) {
1057                 SSLerr(SSL_F_TLS_CONSTRUCT_STOC_KEY_SHARE,
1058                        ERR_R_INTERNAL_ERROR);
1059                 return 0;
1060             }
1061
1062             /* Find first group we allow that is also in client's list */
1063             for (i = 0, pcurvestmp = pcurves; i < num_curves;
1064                  i++, pcurvestmp += 2) {
1065                 unsigned int group_id = pcurvestmp[0] << 8 | pcurvestmp[1];
1066
1067                 if (check_in_list(s, group_id, clntcurves, clnt_num_curves,
1068                                   1)) {
1069                     if (!WPACKET_put_bytes_u16(pkt, group_id)) {
1070                         SSLerr(SSL_F_TLS_CONSTRUCT_STOC_KEY_SHARE,
1071                                ERR_R_INTERNAL_ERROR);
1072                         return 0;
1073                     }
1074                     break;
1075                 }
1076             }
1077             if (i == num_curves) {
1078                 /* No common groups */
1079                 *al = SSL_AD_HANDSHAKE_FAILURE;
1080                 SSLerr(SSL_F_TLS_CONSTRUCT_STOC_KEY_SHARE,
1081                        SSL_R_NO_SHARED_GROUPS);
1082                 return 0;
1083             }
1084             if (!WPACKET_close(pkt)) {
1085                 SSLerr(SSL_F_TLS_CONSTRUCT_STOC_KEY_SHARE,
1086                        ERR_R_INTERNAL_ERROR);
1087                 return 0;
1088             }
1089
1090             return 1;
1091         }
1092
1093         /* Must be resuming. */
1094         if (!s->hit || !tls13_generate_handshake_secret(s, NULL, 0)) {
1095             *al = SSL_AD_INTERNAL_ERROR;
1096             SSLerr(SSL_F_TLS_CONSTRUCT_STOC_KEY_SHARE, ERR_R_INTERNAL_ERROR);
1097             return 0;
1098         }
1099         return 1;
1100     }
1101
1102     if (!WPACKET_put_bytes_u16(pkt, TLSEXT_TYPE_key_share)
1103             || !WPACKET_start_sub_packet_u16(pkt)
1104             || !WPACKET_put_bytes_u16(pkt, s->s3->group_id)) {
1105         SSLerr(SSL_F_TLS_CONSTRUCT_STOC_KEY_SHARE, ERR_R_INTERNAL_ERROR);
1106         return 0;
1107     }
1108
1109     skey = ssl_generate_pkey(ckey);
1110     if (skey == NULL) {
1111         SSLerr(SSL_F_TLS_CONSTRUCT_STOC_KEY_SHARE, ERR_R_MALLOC_FAILURE);
1112         return 0;
1113     }
1114
1115     /* Generate encoding of server key */
1116     encoded_pt_len = EVP_PKEY_get1_tls_encodedpoint(skey, &encodedPoint);
1117     if (encoded_pt_len == 0) {
1118         SSLerr(SSL_F_TLS_CONSTRUCT_STOC_KEY_SHARE, ERR_R_EC_LIB);
1119         EVP_PKEY_free(skey);
1120         return 0;
1121     }
1122
1123     if (!WPACKET_sub_memcpy_u16(pkt, encodedPoint, encoded_pt_len)
1124             || !WPACKET_close(pkt)) {
1125         SSLerr(SSL_F_TLS_CONSTRUCT_STOC_KEY_SHARE, ERR_R_INTERNAL_ERROR);
1126         EVP_PKEY_free(skey);
1127         OPENSSL_free(encodedPoint);
1128         return 0;
1129     }
1130     OPENSSL_free(encodedPoint);
1131
1132     /* This causes the crypto state to be updated based on the derived keys */
1133     s->s3->tmp.pkey = skey;
1134     if (ssl_derive(s, skey, ckey, 1) == 0) {
1135         SSLerr(SSL_F_TLS_CONSTRUCT_STOC_KEY_SHARE, ERR_R_INTERNAL_ERROR);
1136         return 0;
1137     }
1138 #endif
1139
1140     return 1;
1141 }
1142
1143 int tls_construct_stoc_cryptopro_bug(SSL *s, WPACKET *pkt, unsigned int context,
1144                                      X509 *x, size_t chainidx, int *al)
1145 {
1146     const unsigned char cryptopro_ext[36] = {
1147         0xfd, 0xe8,         /* 65000 */
1148         0x00, 0x20,         /* 32 bytes length */
1149         0x30, 0x1e, 0x30, 0x08, 0x06, 0x06, 0x2a, 0x85,
1150         0x03, 0x02, 0x02, 0x09, 0x30, 0x08, 0x06, 0x06,
1151         0x2a, 0x85, 0x03, 0x02, 0x02, 0x16, 0x30, 0x08,
1152         0x06, 0x06, 0x2a, 0x85, 0x03, 0x02, 0x02, 0x17
1153     };
1154
1155     if (((s->s3->tmp.new_cipher->id & 0xFFFF) != 0x80
1156          && (s->s3->tmp.new_cipher->id & 0xFFFF) != 0x81)
1157             || (SSL_get_options(s) & SSL_OP_CRYPTOPRO_TLSEXT_BUG) == 0)
1158         return 1;
1159
1160     if (!WPACKET_memcpy(pkt, cryptopro_ext, sizeof(cryptopro_ext))) {
1161         SSLerr(SSL_F_TLS_CONSTRUCT_STOC_CRYPTOPRO_BUG, ERR_R_INTERNAL_ERROR);
1162         return 0;
1163     }
1164
1165     return 1;
1166 }
1167
1168 int tls_construct_stoc_psk(SSL *s, WPACKET *pkt, unsigned int context, X509 *x,
1169                            size_t chainidx, int *al)
1170 {
1171     if (!s->hit)
1172         return 1;
1173
1174     if (!WPACKET_put_bytes_u16(pkt, TLSEXT_TYPE_psk)
1175             || !WPACKET_start_sub_packet_u16(pkt)
1176             || !WPACKET_put_bytes_u16(pkt, s->session->ext.tick_identity)
1177             || !WPACKET_close(pkt)) {
1178         SSLerr(SSL_F_TLS_CONSTRUCT_STOC_PSK, ERR_R_INTERNAL_ERROR);
1179         return 0;
1180     }
1181
1182     return 1;
1183 }