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