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