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