65b9d3b3d440e53bfe4cbc23795352a06c6bb6e4
[openssl.git] / ssl / statem / extensions_srvr.c
1 /*
2  * Copyright 2016-2018 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 #include "internal/cryptlib.h"
14
15 #define COOKIE_STATE_FORMAT_VERSION     0
16
17 /*
18  * 2 bytes for packet length, 2 bytes for format version, 2 bytes for
19  * protocol version, 2 bytes for group id, 2 bytes for cipher id, 1 byte for
20  * key_share present flag, 4 bytes for timestamp, 2 bytes for the hashlen,
21  * EVP_MAX_MD_SIZE for transcript hash, 1 byte for app cookie length, app cookie
22  * length bytes, SHA256_DIGEST_LENGTH bytes for the HMAC of the whole thing.
23  */
24 #define MAX_COOKIE_SIZE (2 + 2 + 2 + 2 + 2 + 1 + 4 + 2 + EVP_MAX_MD_SIZE + 1 \
25                          + SSL_COOKIE_LENGTH + SHA256_DIGEST_LENGTH)
26
27 /*
28  * Message header + 2 bytes for protocol version + number of random bytes +
29  * + 1 byte for legacy session id length + number of bytes in legacy session id
30  * + 2 bytes for ciphersuite + 1 byte for legacy compression
31  * + 2 bytes for extension block length + 6 bytes for key_share extension
32  * + 4 bytes for cookie extension header + the number of bytes in the cookie
33  */
34 #define MAX_HRR_SIZE    (SSL3_HM_HEADER_LENGTH + 2 + SSL3_RANDOM_SIZE + 1 \
35                          + SSL_MAX_SSL_SESSION_ID_LENGTH + 2 + 1 + 2 + 6 + 4 \
36                          + MAX_COOKIE_SIZE)
37
38 /*
39  * Parse the client's renegotiation binding and abort if it's not right
40  */
41 int tls_parse_ctos_renegotiate(SSL *s, PACKET *pkt, unsigned int context,
42                                X509 *x, size_t chainidx)
43 {
44     unsigned int ilen;
45     const unsigned char *data;
46
47     /* Parse the length byte */
48     if (!PACKET_get_1(pkt, &ilen)
49         || !PACKET_get_bytes(pkt, &data, ilen)) {
50         SSLfatal(s, SSL_AD_DECODE_ERROR, SSL_F_TLS_PARSE_CTOS_RENEGOTIATE,
51                  SSL_R_RENEGOTIATION_ENCODING_ERR);
52         return 0;
53     }
54
55     /* Check that the extension matches */
56     if (ilen != s->s3->previous_client_finished_len) {
57         SSLfatal(s, SSL_AD_HANDSHAKE_FAILURE, SSL_F_TLS_PARSE_CTOS_RENEGOTIATE,
58                  SSL_R_RENEGOTIATION_MISMATCH);
59         return 0;
60     }
61
62     if (memcmp(data, s->s3->previous_client_finished,
63                s->s3->previous_client_finished_len)) {
64         SSLfatal(s, SSL_AD_HANDSHAKE_FAILURE, SSL_F_TLS_PARSE_CTOS_RENEGOTIATE,
65                  SSL_R_RENEGOTIATION_MISMATCH);
66         return 0;
67     }
68
69     s->s3->send_connection_binding = 1;
70
71     return 1;
72 }
73
74 /*-
75  * The servername extension is treated as follows:
76  *
77  * - Only the hostname type is supported with a maximum length of 255.
78  * - The servername is rejected if too long or if it contains zeros,
79  *   in which case an fatal alert is generated.
80  * - The servername field is maintained together with the session cache.
81  * - When a session is resumed, the servername call back invoked in order
82  *   to allow the application to position itself to the right context.
83  * - The servername is acknowledged if it is new for a session or when
84  *   it is identical to a previously used for the same session.
85  *   Applications can control the behaviour.  They can at any time
86  *   set a 'desirable' servername for a new SSL object. This can be the
87  *   case for example with HTTPS when a Host: header field is received and
88  *   a renegotiation is requested. In this case, a possible servername
89  *   presented in the new client hello is only acknowledged if it matches
90  *   the value of the Host: field.
91  * - Applications must  use SSL_OP_NO_SESSION_RESUMPTION_ON_RENEGOTIATION
92  *   if they provide for changing an explicit servername context for the
93  *   session, i.e. when the session has been established with a servername
94  *   extension.
95  * - On session reconnect, the servername extension may be absent.
96  */
97 int tls_parse_ctos_server_name(SSL *s, PACKET *pkt, unsigned int context,
98                                X509 *x, size_t chainidx)
99 {
100     unsigned int servname_type;
101     PACKET sni, hostname;
102
103     if (!PACKET_as_length_prefixed_2(pkt, &sni)
104         /* ServerNameList must be at least 1 byte long. */
105         || PACKET_remaining(&sni) == 0) {
106         SSLfatal(s, SSL_AD_DECODE_ERROR, SSL_F_TLS_PARSE_CTOS_SERVER_NAME,
107                  SSL_R_BAD_EXTENSION);
108         return 0;
109     }
110
111     /*
112      * Although the intent was for server_name to be extensible, RFC 4366
113      * was not clear about it; and so OpenSSL among other implementations,
114      * always and only allows a 'host_name' name types.
115      * RFC 6066 corrected the mistake but adding new name types
116      * is nevertheless no longer feasible, so act as if no other
117      * SNI types can exist, to simplify parsing.
118      *
119      * Also note that the RFC permits only one SNI value per type,
120      * i.e., we can only have a single hostname.
121      */
122     if (!PACKET_get_1(&sni, &servname_type)
123         || servname_type != TLSEXT_NAMETYPE_host_name
124         || !PACKET_as_length_prefixed_2(&sni, &hostname)) {
125         SSLfatal(s, SSL_AD_DECODE_ERROR, SSL_F_TLS_PARSE_CTOS_SERVER_NAME,
126                  SSL_R_BAD_EXTENSION);
127         return 0;
128     }
129
130     if (!s->hit) {
131         if (PACKET_remaining(&hostname) > TLSEXT_MAXLEN_host_name) {
132             SSLfatal(s, SSL_AD_UNRECOGNIZED_NAME,
133                      SSL_F_TLS_PARSE_CTOS_SERVER_NAME,
134                      SSL_R_BAD_EXTENSION);
135             return 0;
136         }
137
138         if (PACKET_contains_zero_byte(&hostname)) {
139             SSLfatal(s, SSL_AD_UNRECOGNIZED_NAME,
140                      SSL_F_TLS_PARSE_CTOS_SERVER_NAME,
141                      SSL_R_BAD_EXTENSION);
142             return 0;
143         }
144
145         OPENSSL_free(s->session->ext.hostname);
146         s->session->ext.hostname = NULL;
147         if (!PACKET_strndup(&hostname, &s->session->ext.hostname)) {
148             SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_F_TLS_PARSE_CTOS_SERVER_NAME,
149                      ERR_R_INTERNAL_ERROR);
150             return 0;
151         }
152
153         s->servername_done = 1;
154     } else {
155         /*
156          * TODO(openssl-team): if the SNI doesn't match, we MUST
157          * fall back to a full handshake.
158          */
159         s->servername_done = s->session->ext.hostname
160             && PACKET_equal(&hostname, s->session->ext.hostname,
161                             strlen(s->session->ext.hostname));
162
163         if (!s->servername_done && s->session->ext.hostname != NULL)
164             s->ext.early_data_ok = 0;
165     }
166
167     return 1;
168 }
169
170 int tls_parse_ctos_maxfragmentlen(SSL *s, PACKET *pkt, unsigned int context,
171                                   X509 *x, size_t chainidx)
172 {
173     unsigned int value;
174
175     if (PACKET_remaining(pkt) != 1 || !PACKET_get_1(pkt, &value)) {
176         SSLfatal(s, SSL_AD_DECODE_ERROR, SSL_F_TLS_PARSE_CTOS_MAXFRAGMENTLEN,
177                  SSL_R_BAD_EXTENSION);
178         return 0;
179     }
180
181     /* Received |value| should be a valid max-fragment-length code. */
182     if (!IS_MAX_FRAGMENT_LENGTH_EXT_VALID(value)) {
183         SSLfatal(s, SSL_AD_ILLEGAL_PARAMETER,
184                  SSL_F_TLS_PARSE_CTOS_MAXFRAGMENTLEN,
185                  SSL_R_SSL3_EXT_INVALID_MAX_FRAGMENT_LENGTH);
186         return 0;
187     }
188
189     /*
190      * RFC 6066:  The negotiated length applies for the duration of the session
191      * including session resumptions.
192      * We should receive the same code as in resumed session !
193      */
194     if (s->hit && s->session->ext.max_fragment_len_mode != value) {
195         SSLfatal(s, SSL_AD_ILLEGAL_PARAMETER,
196                  SSL_F_TLS_PARSE_CTOS_MAXFRAGMENTLEN,
197                  SSL_R_SSL3_EXT_INVALID_MAX_FRAGMENT_LENGTH);
198         return 0;
199     }
200
201     /*
202      * Store it in session, so it'll become binding for us
203      * and we'll include it in a next Server Hello.
204      */
205     s->session->ext.max_fragment_len_mode = value;
206     return 1;
207 }
208
209 #ifndef OPENSSL_NO_SRP
210 int tls_parse_ctos_srp(SSL *s, PACKET *pkt, unsigned int context, X509 *x,
211                        size_t chainidx)
212 {
213     PACKET srp_I;
214
215     if (!PACKET_as_length_prefixed_1(pkt, &srp_I)
216             || PACKET_contains_zero_byte(&srp_I)) {
217         SSLfatal(s, SSL_AD_DECODE_ERROR,
218                  SSL_F_TLS_PARSE_CTOS_SRP,
219                  SSL_R_BAD_EXTENSION);
220         return 0;
221     }
222
223     /*
224      * TODO(openssl-team): currently, we re-authenticate the user
225      * upon resumption. Instead, we MUST ignore the login.
226      */
227     if (!PACKET_strndup(&srp_I, &s->srp_ctx.login)) {
228         SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_F_TLS_PARSE_CTOS_SRP,
229                  ERR_R_INTERNAL_ERROR);
230         return 0;
231     }
232
233     return 1;
234 }
235 #endif
236
237 #ifndef OPENSSL_NO_EC
238 int tls_parse_ctos_ec_pt_formats(SSL *s, PACKET *pkt, unsigned int context,
239                                  X509 *x, size_t chainidx)
240 {
241     PACKET ec_point_format_list;
242
243     if (!PACKET_as_length_prefixed_1(pkt, &ec_point_format_list)
244         || PACKET_remaining(&ec_point_format_list) == 0) {
245         SSLfatal(s, SSL_AD_DECODE_ERROR, SSL_F_TLS_PARSE_CTOS_EC_PT_FORMATS,
246                  SSL_R_BAD_EXTENSION);
247         return 0;
248     }
249
250     if (!s->hit) {
251         if (!PACKET_memdup(&ec_point_format_list,
252                            &s->session->ext.ecpointformats,
253                            &s->session->ext.ecpointformats_len)) {
254             SSLfatal(s, SSL_AD_INTERNAL_ERROR,
255                      SSL_F_TLS_PARSE_CTOS_EC_PT_FORMATS, ERR_R_INTERNAL_ERROR);
256             return 0;
257         }
258     }
259
260     return 1;
261 }
262 #endif                          /* OPENSSL_NO_EC */
263
264 int tls_parse_ctos_session_ticket(SSL *s, PACKET *pkt, unsigned int context,
265                                   X509 *x, size_t chainidx)
266 {
267     if (s->ext.session_ticket_cb &&
268             !s->ext.session_ticket_cb(s, PACKET_data(pkt),
269                                   PACKET_remaining(pkt),
270                                   s->ext.session_ticket_cb_arg)) {
271         SSLfatal(s, SSL_AD_INTERNAL_ERROR,
272                  SSL_F_TLS_PARSE_CTOS_SESSION_TICKET, ERR_R_INTERNAL_ERROR);
273         return 0;
274     }
275
276     return 1;
277 }
278
279 int tls_parse_ctos_sig_algs_cert(SSL *s, PACKET *pkt, unsigned int context,
280                                  X509 *x, size_t chainidx)
281 {
282     PACKET supported_sig_algs;
283
284     if (!PACKET_as_length_prefixed_2(pkt, &supported_sig_algs)
285             || PACKET_remaining(&supported_sig_algs) == 0) {
286         SSLfatal(s, SSL_AD_DECODE_ERROR,
287                  SSL_F_TLS_PARSE_CTOS_SIG_ALGS_CERT, SSL_R_BAD_EXTENSION);
288         return 0;
289     }
290
291     if (!s->hit && !tls1_save_sigalgs(s, &supported_sig_algs, 1)) {
292         SSLfatal(s, SSL_AD_DECODE_ERROR,
293                  SSL_F_TLS_PARSE_CTOS_SIG_ALGS_CERT, SSL_R_BAD_EXTENSION);
294         return 0;
295     }
296
297     return 1;
298 }
299
300 int tls_parse_ctos_sig_algs(SSL *s, PACKET *pkt, unsigned int context, X509 *x,
301                             size_t chainidx)
302 {
303     PACKET supported_sig_algs;
304
305     if (!PACKET_as_length_prefixed_2(pkt, &supported_sig_algs)
306             || PACKET_remaining(&supported_sig_algs) == 0) {
307         SSLfatal(s, SSL_AD_DECODE_ERROR,
308                  SSL_F_TLS_PARSE_CTOS_SIG_ALGS, SSL_R_BAD_EXTENSION);
309         return 0;
310     }
311
312     if (!s->hit && !tls1_save_sigalgs(s, &supported_sig_algs, 0)) {
313         SSLfatal(s, SSL_AD_DECODE_ERROR,
314                  SSL_F_TLS_PARSE_CTOS_SIG_ALGS, SSL_R_BAD_EXTENSION);
315         return 0;
316     }
317
318     return 1;
319 }
320
321 #ifndef OPENSSL_NO_OCSP
322 int tls_parse_ctos_status_request(SSL *s, PACKET *pkt, unsigned int context,
323                                   X509 *x, size_t chainidx)
324 {
325     PACKET responder_id_list, exts;
326
327     /* We ignore this in a resumption handshake */
328     if (s->hit)
329         return 1;
330
331     /* Not defined if we get one of these in a client Certificate */
332     if (x != NULL)
333         return 1;
334
335     if (!PACKET_get_1(pkt, (unsigned int *)&s->ext.status_type)) {
336         SSLfatal(s, SSL_AD_DECODE_ERROR,
337                  SSL_F_TLS_PARSE_CTOS_STATUS_REQUEST, SSL_R_BAD_EXTENSION);
338         return 0;
339     }
340
341     if (s->ext.status_type != TLSEXT_STATUSTYPE_ocsp) {
342         /*
343          * We don't know what to do with any other type so ignore it.
344          */
345         s->ext.status_type = TLSEXT_STATUSTYPE_nothing;
346         return 1;
347     }
348
349     if (!PACKET_get_length_prefixed_2 (pkt, &responder_id_list)) {
350         SSLfatal(s, SSL_AD_DECODE_ERROR,
351                  SSL_F_TLS_PARSE_CTOS_STATUS_REQUEST, SSL_R_BAD_EXTENSION);
352         return 0;
353     }
354
355     /*
356      * We remove any OCSP_RESPIDs from a previous handshake
357      * to prevent unbounded memory growth - CVE-2016-6304
358      */
359     sk_OCSP_RESPID_pop_free(s->ext.ocsp.ids, OCSP_RESPID_free);
360     if (PACKET_remaining(&responder_id_list) > 0) {
361         s->ext.ocsp.ids = sk_OCSP_RESPID_new_null();
362         if (s->ext.ocsp.ids == NULL) {
363             SSLfatal(s, SSL_AD_INTERNAL_ERROR,
364                      SSL_F_TLS_PARSE_CTOS_STATUS_REQUEST, ERR_R_MALLOC_FAILURE);
365             return 0;
366         }
367     } else {
368         s->ext.ocsp.ids = NULL;
369     }
370
371     while (PACKET_remaining(&responder_id_list) > 0) {
372         OCSP_RESPID *id;
373         PACKET responder_id;
374         const unsigned char *id_data;
375
376         if (!PACKET_get_length_prefixed_2(&responder_id_list, &responder_id)
377                 || PACKET_remaining(&responder_id) == 0) {
378             SSLfatal(s, SSL_AD_DECODE_ERROR,
379                      SSL_F_TLS_PARSE_CTOS_STATUS_REQUEST, SSL_R_BAD_EXTENSION);
380             return 0;
381         }
382
383         id_data = PACKET_data(&responder_id);
384         /* TODO(size_t): Convert d2i_* to size_t */
385         id = d2i_OCSP_RESPID(NULL, &id_data,
386                              (int)PACKET_remaining(&responder_id));
387         if (id == NULL) {
388             SSLfatal(s, SSL_AD_DECODE_ERROR,
389                      SSL_F_TLS_PARSE_CTOS_STATUS_REQUEST, SSL_R_BAD_EXTENSION);
390             return 0;
391         }
392
393         if (id_data != PACKET_end(&responder_id)) {
394             OCSP_RESPID_free(id);
395             SSLfatal(s, SSL_AD_DECODE_ERROR,
396                      SSL_F_TLS_PARSE_CTOS_STATUS_REQUEST, SSL_R_BAD_EXTENSION);
397
398             return 0;
399         }
400
401         if (!sk_OCSP_RESPID_push(s->ext.ocsp.ids, id)) {
402             OCSP_RESPID_free(id);
403             SSLfatal(s, SSL_AD_INTERNAL_ERROR,
404                      SSL_F_TLS_PARSE_CTOS_STATUS_REQUEST, ERR_R_INTERNAL_ERROR);
405
406             return 0;
407         }
408     }
409
410     /* Read in request_extensions */
411     if (!PACKET_as_length_prefixed_2(pkt, &exts)) {
412         SSLfatal(s, SSL_AD_DECODE_ERROR,
413                  SSL_F_TLS_PARSE_CTOS_STATUS_REQUEST, SSL_R_BAD_EXTENSION);
414         return 0;
415     }
416
417     if (PACKET_remaining(&exts) > 0) {
418         const unsigned char *ext_data = PACKET_data(&exts);
419
420         sk_X509_EXTENSION_pop_free(s->ext.ocsp.exts,
421                                    X509_EXTENSION_free);
422         s->ext.ocsp.exts =
423             d2i_X509_EXTENSIONS(NULL, &ext_data, (int)PACKET_remaining(&exts));
424         if (s->ext.ocsp.exts == NULL || ext_data != PACKET_end(&exts)) {
425             SSLfatal(s, SSL_AD_DECODE_ERROR,
426                      SSL_F_TLS_PARSE_CTOS_STATUS_REQUEST, SSL_R_BAD_EXTENSION);
427             return 0;
428         }
429     }
430
431     return 1;
432 }
433 #endif
434
435 #ifndef OPENSSL_NO_NEXTPROTONEG
436 int tls_parse_ctos_npn(SSL *s, PACKET *pkt, unsigned int context, X509 *x,
437                        size_t chainidx)
438 {
439     /*
440      * We shouldn't accept this extension on a
441      * renegotiation.
442      */
443     if (SSL_IS_FIRST_HANDSHAKE(s))
444         s->s3->npn_seen = 1;
445
446     return 1;
447 }
448 #endif
449
450 /*
451  * Save the ALPN extension in a ClientHello.|pkt| holds the contents of the ALPN
452  * extension, not including type and length. Returns: 1 on success, 0 on error.
453  */
454 int tls_parse_ctos_alpn(SSL *s, PACKET *pkt, unsigned int context, X509 *x,
455                         size_t chainidx)
456 {
457     PACKET protocol_list, save_protocol_list, protocol;
458
459     if (!SSL_IS_FIRST_HANDSHAKE(s))
460         return 1;
461
462     if (!PACKET_as_length_prefixed_2(pkt, &protocol_list)
463         || PACKET_remaining(&protocol_list) < 2) {
464         SSLfatal(s, SSL_AD_DECODE_ERROR, SSL_F_TLS_PARSE_CTOS_ALPN,
465                  SSL_R_BAD_EXTENSION);
466         return 0;
467     }
468
469     save_protocol_list = protocol_list;
470     do {
471         /* Protocol names can't be empty. */
472         if (!PACKET_get_length_prefixed_1(&protocol_list, &protocol)
473                 || PACKET_remaining(&protocol) == 0) {
474             SSLfatal(s, SSL_AD_DECODE_ERROR, SSL_F_TLS_PARSE_CTOS_ALPN,
475                      SSL_R_BAD_EXTENSION);
476             return 0;
477         }
478     } while (PACKET_remaining(&protocol_list) != 0);
479
480     OPENSSL_free(s->s3->alpn_proposed);
481     s->s3->alpn_proposed = NULL;
482     s->s3->alpn_proposed_len = 0;
483     if (!PACKET_memdup(&save_protocol_list,
484                        &s->s3->alpn_proposed, &s->s3->alpn_proposed_len)) {
485         SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_F_TLS_PARSE_CTOS_ALPN,
486                  ERR_R_INTERNAL_ERROR);
487         return 0;
488     }
489
490     return 1;
491 }
492
493 #ifndef OPENSSL_NO_SRTP
494 int tls_parse_ctos_use_srtp(SSL *s, PACKET *pkt, unsigned int context, X509 *x,
495                             size_t chainidx)
496 {
497     STACK_OF(SRTP_PROTECTION_PROFILE) *srvr;
498     unsigned int ct, mki_len, id;
499     int i, srtp_pref;
500     PACKET subpkt;
501
502     /* Ignore this if we have no SRTP profiles */
503     if (SSL_get_srtp_profiles(s) == NULL)
504         return 1;
505
506     /* Pull off the length of the cipher suite list  and check it is even */
507     if (!PACKET_get_net_2(pkt, &ct) || (ct & 1) != 0
508             || !PACKET_get_sub_packet(pkt, &subpkt, ct)) {
509         SSLfatal(s, SSL_AD_DECODE_ERROR, SSL_F_TLS_PARSE_CTOS_USE_SRTP,
510                SSL_R_BAD_SRTP_PROTECTION_PROFILE_LIST);
511         return 0;
512     }
513
514     srvr = SSL_get_srtp_profiles(s);
515     s->srtp_profile = NULL;
516     /* Search all profiles for a match initially */
517     srtp_pref = sk_SRTP_PROTECTION_PROFILE_num(srvr);
518
519     while (PACKET_remaining(&subpkt)) {
520         if (!PACKET_get_net_2(&subpkt, &id)) {
521             SSLfatal(s, SSL_AD_DECODE_ERROR, SSL_F_TLS_PARSE_CTOS_USE_SRTP,
522                      SSL_R_BAD_SRTP_PROTECTION_PROFILE_LIST);
523             return 0;
524         }
525
526         /*
527          * Only look for match in profiles of higher preference than
528          * current match.
529          * If no profiles have been have been configured then this
530          * does nothing.
531          */
532         for (i = 0; i < srtp_pref; i++) {
533             SRTP_PROTECTION_PROFILE *sprof =
534                 sk_SRTP_PROTECTION_PROFILE_value(srvr, i);
535
536             if (sprof->id == id) {
537                 s->srtp_profile = sprof;
538                 srtp_pref = i;
539                 break;
540             }
541         }
542     }
543
544     /* Now extract the MKI value as a sanity check, but discard it for now */
545     if (!PACKET_get_1(pkt, &mki_len)) {
546         SSLfatal(s, SSL_AD_DECODE_ERROR, SSL_F_TLS_PARSE_CTOS_USE_SRTP,
547                  SSL_R_BAD_SRTP_PROTECTION_PROFILE_LIST);
548         return 0;
549     }
550
551     if (!PACKET_forward(pkt, mki_len)
552         || PACKET_remaining(pkt)) {
553         SSLfatal(s, SSL_AD_DECODE_ERROR, SSL_F_TLS_PARSE_CTOS_USE_SRTP,
554                  SSL_R_BAD_SRTP_MKI_VALUE);
555         return 0;
556     }
557
558     return 1;
559 }
560 #endif
561
562 int tls_parse_ctos_etm(SSL *s, PACKET *pkt, unsigned int context, X509 *x,
563                        size_t chainidx)
564 {
565     if (!(s->options & SSL_OP_NO_ENCRYPT_THEN_MAC))
566         s->ext.use_etm = 1;
567
568     return 1;
569 }
570
571 /*
572  * Process a psk_kex_modes extension received in the ClientHello. |pkt| contains
573  * the raw PACKET data for the extension. Returns 1 on success or 0 on failure.
574  */
575 int tls_parse_ctos_psk_kex_modes(SSL *s, PACKET *pkt, unsigned int context,
576                                  X509 *x, size_t chainidx)
577 {
578 #ifndef OPENSSL_NO_TLS1_3
579     PACKET psk_kex_modes;
580     unsigned int mode;
581
582     if (!PACKET_as_length_prefixed_1(pkt, &psk_kex_modes)
583             || PACKET_remaining(&psk_kex_modes) == 0) {
584         SSLfatal(s, SSL_AD_DECODE_ERROR, SSL_F_TLS_PARSE_CTOS_PSK_KEX_MODES,
585                  SSL_R_BAD_EXTENSION);
586         return 0;
587     }
588
589     while (PACKET_get_1(&psk_kex_modes, &mode)) {
590         if (mode == TLSEXT_KEX_MODE_KE_DHE)
591             s->ext.psk_kex_mode |= TLSEXT_KEX_MODE_FLAG_KE_DHE;
592         else if (mode == TLSEXT_KEX_MODE_KE
593                 && (s->options & SSL_OP_ALLOW_NO_DHE_KEX) != 0)
594             s->ext.psk_kex_mode |= TLSEXT_KEX_MODE_FLAG_KE;
595     }
596 #endif
597
598     return 1;
599 }
600
601 /*
602  * Process a key_share extension received in the ClientHello. |pkt| contains
603  * the raw PACKET data for the extension. Returns 1 on success or 0 on failure.
604  */
605 int tls_parse_ctos_key_share(SSL *s, PACKET *pkt, unsigned int context, X509 *x,
606                              size_t chainidx)
607 {
608 #ifndef OPENSSL_NO_TLS1_3
609     unsigned int group_id;
610     PACKET key_share_list, encoded_pt;
611     const uint16_t *clntgroups, *srvrgroups;
612     size_t clnt_num_groups, srvr_num_groups;
613     int found = 0;
614
615     if (s->hit && (s->ext.psk_kex_mode & TLSEXT_KEX_MODE_FLAG_KE_DHE) == 0)
616         return 1;
617
618     /* Sanity check */
619     if (s->s3->peer_tmp != NULL) {
620         SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_F_TLS_PARSE_CTOS_KEY_SHARE,
621                  ERR_R_INTERNAL_ERROR);
622         return 0;
623     }
624
625     if (!PACKET_as_length_prefixed_2(pkt, &key_share_list)) {
626         SSLfatal(s, SSL_AD_DECODE_ERROR, SSL_F_TLS_PARSE_CTOS_KEY_SHARE,
627                  SSL_R_LENGTH_MISMATCH);
628         return 0;
629     }
630
631     /* Get our list of supported groups */
632     tls1_get_supported_groups(s, &srvrgroups, &srvr_num_groups);
633     /* Get the clients list of supported groups. */
634     tls1_get_peer_groups(s, &clntgroups, &clnt_num_groups);
635     if (clnt_num_groups == 0) {
636         /*
637          * This can only happen if the supported_groups extension was not sent,
638          * because we verify that the length is non-zero when we process that
639          * extension.
640          */
641         SSLfatal(s, SSL_AD_MISSING_EXTENSION, SSL_F_TLS_PARSE_CTOS_KEY_SHARE,
642                  SSL_R_MISSING_SUPPORTED_GROUPS_EXTENSION);
643         return 0;
644     }
645
646     if (s->s3->group_id != 0 && PACKET_remaining(&key_share_list) == 0) {
647         /*
648          * If we set a group_id already, then we must have sent an HRR
649          * requesting a new key_share. If we haven't got one then that is an
650          * error
651          */
652         SSLfatal(s, SSL_AD_ILLEGAL_PARAMETER, SSL_F_TLS_PARSE_CTOS_KEY_SHARE,
653                  SSL_R_BAD_KEY_SHARE);
654         return 0;
655     }
656
657     while (PACKET_remaining(&key_share_list) > 0) {
658         if (!PACKET_get_net_2(&key_share_list, &group_id)
659                 || !PACKET_get_length_prefixed_2(&key_share_list, &encoded_pt)
660                 || PACKET_remaining(&encoded_pt) == 0) {
661             SSLfatal(s, SSL_AD_DECODE_ERROR, SSL_F_TLS_PARSE_CTOS_KEY_SHARE,
662                      SSL_R_LENGTH_MISMATCH);
663             return 0;
664         }
665
666         /*
667          * If we already found a suitable key_share we loop through the
668          * rest to verify the structure, but don't process them.
669          */
670         if (found)
671             continue;
672
673         /*
674          * If we sent an HRR then the key_share sent back MUST be for the group
675          * we requested, and must be the only key_share sent.
676          */
677         if (s->s3->group_id != 0
678                 && (group_id != s->s3->group_id
679                     || PACKET_remaining(&key_share_list) != 0)) {
680             SSLfatal(s, SSL_AD_ILLEGAL_PARAMETER,
681                      SSL_F_TLS_PARSE_CTOS_KEY_SHARE, SSL_R_BAD_KEY_SHARE);
682             return 0;
683         }
684
685         /* Check if this share is in supported_groups sent from client */
686         if (!check_in_list(s, group_id, clntgroups, clnt_num_groups, 0)) {
687             SSLfatal(s, SSL_AD_ILLEGAL_PARAMETER,
688                      SSL_F_TLS_PARSE_CTOS_KEY_SHARE, SSL_R_BAD_KEY_SHARE);
689             return 0;
690         }
691
692         /* Check if this share is for a group we can use */
693         if (!check_in_list(s, group_id, srvrgroups, srvr_num_groups, 1)) {
694             /* Share not suitable */
695             continue;
696         }
697
698         if ((s->s3->peer_tmp = ssl_generate_param_group(group_id)) == NULL) {
699             SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_F_TLS_PARSE_CTOS_KEY_SHARE,
700                    SSL_R_UNABLE_TO_FIND_ECDH_PARAMETERS);
701             return 0;
702         }
703
704         s->s3->group_id = group_id;
705
706         if (!EVP_PKEY_set1_tls_encodedpoint(s->s3->peer_tmp,
707                 PACKET_data(&encoded_pt),
708                 PACKET_remaining(&encoded_pt))) {
709             SSLfatal(s, SSL_AD_ILLEGAL_PARAMETER,
710                      SSL_F_TLS_PARSE_CTOS_KEY_SHARE, SSL_R_BAD_ECPOINT);
711             return 0;
712         }
713
714         found = 1;
715     }
716 #endif
717
718     return 1;
719 }
720
721 int tls_parse_ctos_cookie(SSL *s, PACKET *pkt, unsigned int context, X509 *x,
722                           size_t chainidx)
723 {
724     unsigned int format, version, key_share, group_id;
725     EVP_MD_CTX *hctx;
726     EVP_PKEY *pkey;
727     PACKET cookie, raw, chhash, appcookie;
728     WPACKET hrrpkt;
729     const unsigned char *data, *mdin, *ciphdata;
730     unsigned char hmac[SHA256_DIGEST_LENGTH];
731     unsigned char hrr[MAX_HRR_SIZE];
732     size_t rawlen, hmaclen, hrrlen, ciphlen;
733     unsigned long tm, now;
734
735     /* Ignore any cookie if we're not set up to verify it */
736     if (s->ctx->verify_stateless_cookie_cb == NULL
737             || (s->s3->flags & TLS1_FLAGS_STATELESS) == 0)
738         return 1;
739
740     if (!PACKET_as_length_prefixed_2(pkt, &cookie)) {
741         SSLfatal(s, SSL_AD_DECODE_ERROR, SSL_F_TLS_PARSE_CTOS_COOKIE,
742                  SSL_R_LENGTH_MISMATCH);
743         return 0;
744     }
745
746     raw = cookie;
747     data = PACKET_data(&raw);
748     rawlen = PACKET_remaining(&raw);
749     if (rawlen < SHA256_DIGEST_LENGTH
750             || !PACKET_forward(&raw, rawlen - SHA256_DIGEST_LENGTH)) {
751         SSLfatal(s, SSL_AD_DECODE_ERROR, SSL_F_TLS_PARSE_CTOS_COOKIE,
752                  SSL_R_LENGTH_MISMATCH);
753         return 0;
754     }
755     mdin = PACKET_data(&raw);
756
757     /* Verify the HMAC of the cookie */
758     hctx = EVP_MD_CTX_create();
759     pkey = EVP_PKEY_new_raw_private_key(EVP_PKEY_HMAC, NULL,
760                                         s->session_ctx->ext.cookie_hmac_key,
761                                         sizeof(s->session_ctx->ext
762                                                .cookie_hmac_key));
763     if (hctx == NULL || pkey == NULL) {
764         EVP_MD_CTX_free(hctx);
765         EVP_PKEY_free(pkey);
766         SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_F_TLS_PARSE_CTOS_COOKIE,
767                  ERR_R_MALLOC_FAILURE);
768         return 0;
769     }
770
771     hmaclen = SHA256_DIGEST_LENGTH;
772     if (EVP_DigestSignInit(hctx, NULL, EVP_sha256(), NULL, pkey) <= 0
773             || EVP_DigestSign(hctx, hmac, &hmaclen, data,
774                               rawlen - SHA256_DIGEST_LENGTH) <= 0
775             || hmaclen != SHA256_DIGEST_LENGTH) {
776         EVP_MD_CTX_free(hctx);
777         EVP_PKEY_free(pkey);
778         SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_F_TLS_PARSE_CTOS_COOKIE,
779                  ERR_R_INTERNAL_ERROR);
780         return 0;
781     }
782
783     EVP_MD_CTX_free(hctx);
784     EVP_PKEY_free(pkey);
785
786     if (CRYPTO_memcmp(hmac, mdin, SHA256_DIGEST_LENGTH) != 0) {
787         SSLfatal(s, SSL_AD_ILLEGAL_PARAMETER, SSL_F_TLS_PARSE_CTOS_COOKIE,
788                  SSL_R_COOKIE_MISMATCH);
789         return 0;
790     }
791
792     if (!PACKET_get_net_2(&cookie, &format)) {
793         SSLfatal(s, SSL_AD_DECODE_ERROR, SSL_F_TLS_PARSE_CTOS_COOKIE,
794                  SSL_R_LENGTH_MISMATCH);
795         return 0;
796     }
797     /* Check the cookie format is something we recognise. Ignore it if not */
798     if (format != COOKIE_STATE_FORMAT_VERSION)
799         return 1;
800
801     /*
802      * The rest of these checks really shouldn't fail since we have verified the
803      * HMAC above.
804      */
805
806     /* Check the version number is sane */
807     if (!PACKET_get_net_2(&cookie, &version)) {
808         SSLfatal(s, SSL_AD_DECODE_ERROR, SSL_F_TLS_PARSE_CTOS_COOKIE,
809                  SSL_R_LENGTH_MISMATCH);
810         return 0;
811     }
812     if (version != TLS1_3_VERSION) {
813         SSLfatal(s, SSL_AD_ILLEGAL_PARAMETER, SSL_F_TLS_PARSE_CTOS_COOKIE,
814                  SSL_R_BAD_PROTOCOL_VERSION_NUMBER);
815         return 0;
816     }
817
818     if (!PACKET_get_net_2(&cookie, &group_id)) {
819         SSLfatal(s, SSL_AD_DECODE_ERROR, SSL_F_TLS_PARSE_CTOS_COOKIE,
820                  SSL_R_LENGTH_MISMATCH);
821         return 0;
822     }
823
824     ciphdata = PACKET_data(&cookie);
825     if (!PACKET_forward(&cookie, 2)) {
826         SSLfatal(s, SSL_AD_DECODE_ERROR, SSL_F_TLS_PARSE_CTOS_COOKIE,
827                  SSL_R_LENGTH_MISMATCH);
828         return 0;
829     }
830     if (group_id != s->s3->group_id
831             || s->s3->tmp.new_cipher
832                != ssl_get_cipher_by_char(s, ciphdata, 0)) {
833         /*
834          * We chose a different cipher or group id this time around to what is
835          * in the cookie. Something must have changed.
836          */
837         SSLfatal(s, SSL_AD_ILLEGAL_PARAMETER, SSL_F_TLS_PARSE_CTOS_COOKIE,
838                  SSL_R_BAD_CIPHER);
839         return 0;
840     }
841
842     if (!PACKET_get_1(&cookie, &key_share)
843             || !PACKET_get_net_4(&cookie, &tm)
844             || !PACKET_get_length_prefixed_2(&cookie, &chhash)
845             || !PACKET_get_length_prefixed_1(&cookie, &appcookie)
846             || PACKET_remaining(&cookie) != SHA256_DIGEST_LENGTH) {
847         SSLfatal(s, SSL_AD_DECODE_ERROR, SSL_F_TLS_PARSE_CTOS_COOKIE,
848                  SSL_R_LENGTH_MISMATCH);
849         return 0;
850     }
851
852     /* We tolerate a cookie age of up to 10 minutes (= 60 * 10 seconds) */
853     now = (unsigned long)time(NULL);
854     if (tm > now || (now - tm) > 600) {
855         /* Cookie is stale. Ignore it */
856         return 1;
857     }
858
859     /* Verify the app cookie */
860     if (s->ctx->verify_stateless_cookie_cb(s, PACKET_data(&appcookie),
861                                      PACKET_remaining(&appcookie)) == 0) {
862         SSLfatal(s, SSL_AD_ILLEGAL_PARAMETER, SSL_F_TLS_PARSE_CTOS_COOKIE,
863                  SSL_R_COOKIE_MISMATCH);
864         return 0;
865     }
866
867     /*
868      * Reconstruct the HRR that we would have sent in response to the original
869      * ClientHello so we can add it to the transcript hash.
870      * Note: This won't work with custom HRR extensions
871      */
872     if (!WPACKET_init_static_len(&hrrpkt, hrr, sizeof(hrr), 0)) {
873         SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_F_TLS_PARSE_CTOS_COOKIE,
874                  ERR_R_INTERNAL_ERROR);
875         return 0;
876     }
877     if (!WPACKET_put_bytes_u8(&hrrpkt, SSL3_MT_SERVER_HELLO)
878             || !WPACKET_start_sub_packet_u24(&hrrpkt)
879             || !WPACKET_put_bytes_u16(&hrrpkt, TLS1_2_VERSION)
880             || !WPACKET_memcpy(&hrrpkt, hrrrandom, SSL3_RANDOM_SIZE)
881             || !WPACKET_sub_memcpy_u8(&hrrpkt, s->tmp_session_id,
882                                       s->tmp_session_id_len)
883             || !s->method->put_cipher_by_char(s->s3->tmp.new_cipher, &hrrpkt,
884                                               &ciphlen)
885             || !WPACKET_put_bytes_u8(&hrrpkt, 0)
886             || !WPACKET_start_sub_packet_u16(&hrrpkt)) {
887         WPACKET_cleanup(&hrrpkt);
888         SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_F_TLS_PARSE_CTOS_COOKIE,
889                  ERR_R_INTERNAL_ERROR);
890         return 0;
891     }
892     if (!WPACKET_put_bytes_u16(&hrrpkt, TLSEXT_TYPE_supported_versions)
893             || !WPACKET_start_sub_packet_u16(&hrrpkt)
894                /* TODO(TLS1.3): Fix this before release */
895             || !WPACKET_put_bytes_u16(&hrrpkt, s->version_draft)
896             || !WPACKET_close(&hrrpkt)) {
897         WPACKET_cleanup(&hrrpkt);
898         SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_F_TLS_PARSE_CTOS_COOKIE,
899                  ERR_R_INTERNAL_ERROR);
900         return 0;
901     }
902     if (key_share) {
903         if (!WPACKET_put_bytes_u16(&hrrpkt, TLSEXT_TYPE_key_share)
904                 || !WPACKET_start_sub_packet_u16(&hrrpkt)
905                 || !WPACKET_put_bytes_u16(&hrrpkt, s->s3->group_id)
906                 || !WPACKET_close(&hrrpkt)) {
907             WPACKET_cleanup(&hrrpkt);
908             SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_F_TLS_PARSE_CTOS_COOKIE,
909                      ERR_R_INTERNAL_ERROR);
910             return 0;
911         }
912     }
913     if (!WPACKET_put_bytes_u16(&hrrpkt, TLSEXT_TYPE_cookie)
914             || !WPACKET_start_sub_packet_u16(&hrrpkt)
915             || !WPACKET_sub_memcpy_u16(&hrrpkt, data, rawlen)
916             || !WPACKET_close(&hrrpkt) /* cookie extension */
917             || !WPACKET_close(&hrrpkt) /* extension block */
918             || !WPACKET_close(&hrrpkt) /* message */
919             || !WPACKET_get_total_written(&hrrpkt, &hrrlen)
920             || !WPACKET_finish(&hrrpkt)) {
921         WPACKET_cleanup(&hrrpkt);
922         SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_F_TLS_PARSE_CTOS_COOKIE,
923                  ERR_R_INTERNAL_ERROR);
924         return 0;
925     }
926
927     /* Reconstruct the transcript hash */
928     if (!create_synthetic_message_hash(s, PACKET_data(&chhash),
929                                        PACKET_remaining(&chhash), hrr,
930                                        hrrlen)) {
931         /* SSLfatal() already called */
932         return 0;
933     }
934
935     /* Act as if this ClientHello came after a HelloRetryRequest */
936     s->hello_retry_request = 1;
937
938     s->ext.cookieok = 1;
939
940     return 1;
941 }
942
943 #ifndef OPENSSL_NO_EC
944 int tls_parse_ctos_supported_groups(SSL *s, PACKET *pkt, unsigned int context,
945                                     X509 *x, size_t chainidx)
946 {
947     PACKET supported_groups_list;
948
949     /* Each group is 2 bytes and we must have at least 1. */
950     if (!PACKET_as_length_prefixed_2(pkt, &supported_groups_list)
951             || PACKET_remaining(&supported_groups_list) == 0
952             || (PACKET_remaining(&supported_groups_list) % 2) != 0) {
953         SSLfatal(s, SSL_AD_DECODE_ERROR,
954                  SSL_F_TLS_PARSE_CTOS_SUPPORTED_GROUPS, SSL_R_BAD_EXTENSION);
955         return 0;
956     }
957
958     if (!s->hit || SSL_IS_TLS13(s)) {
959         OPENSSL_free(s->session->ext.supportedgroups);
960         s->session->ext.supportedgroups = NULL;
961         s->session->ext.supportedgroups_len = 0;
962         if (!tls1_save_u16(&supported_groups_list,
963                            &s->session->ext.supportedgroups,
964                            &s->session->ext.supportedgroups_len)) {
965             SSLfatal(s, SSL_AD_INTERNAL_ERROR,
966                      SSL_F_TLS_PARSE_CTOS_SUPPORTED_GROUPS,
967                      ERR_R_INTERNAL_ERROR);
968             return 0;
969         }
970     }
971
972     return 1;
973 }
974 #endif
975
976 int tls_parse_ctos_ems(SSL *s, PACKET *pkt, unsigned int context, X509 *x,
977                        size_t chainidx)
978 {
979     /* The extension must always be empty */
980     if (PACKET_remaining(pkt) != 0) {
981         SSLfatal(s, SSL_AD_DECODE_ERROR,
982                  SSL_F_TLS_PARSE_CTOS_EMS, SSL_R_BAD_EXTENSION);
983         return 0;
984     }
985
986     s->s3->flags |= TLS1_FLAGS_RECEIVED_EXTMS;
987
988     return 1;
989 }
990
991
992 int tls_parse_ctos_early_data(SSL *s, PACKET *pkt, unsigned int context,
993                               X509 *x, size_t chainidx)
994 {
995     if (PACKET_remaining(pkt) != 0) {
996         SSLfatal(s, SSL_AD_DECODE_ERROR,
997                  SSL_F_TLS_PARSE_CTOS_EARLY_DATA, SSL_R_BAD_EXTENSION);
998         return 0;
999     }
1000
1001     if (s->hello_retry_request != SSL_HRR_NONE) {
1002         SSLfatal(s, SSL_AD_ILLEGAL_PARAMETER,
1003                  SSL_F_TLS_PARSE_CTOS_EARLY_DATA, SSL_R_BAD_EXTENSION);
1004         return 0;
1005     }
1006
1007     return 1;
1008 }
1009
1010 int tls_parse_ctos_psk(SSL *s, PACKET *pkt, unsigned int context, X509 *x,
1011                        size_t chainidx)
1012 {
1013     PACKET identities, binders, binder;
1014     size_t binderoffset, hashsize;
1015     SSL_SESSION *sess = NULL;
1016     unsigned int id, i, ext = 0;
1017     const EVP_MD *md = NULL;
1018
1019     /*
1020      * If we have no PSK kex mode that we recognise then we can't resume so
1021      * ignore this extension
1022      */
1023     if ((s->ext.psk_kex_mode
1024             & (TLSEXT_KEX_MODE_FLAG_KE | TLSEXT_KEX_MODE_FLAG_KE_DHE)) == 0)
1025         return 1;
1026
1027     if (!PACKET_get_length_prefixed_2(pkt, &identities)) {
1028         SSLfatal(s, SSL_AD_DECODE_ERROR,
1029                  SSL_F_TLS_PARSE_CTOS_PSK, SSL_R_BAD_EXTENSION);
1030         return 0;
1031     }
1032
1033     s->ext.ticket_expected = 0;
1034     for (id = 0; PACKET_remaining(&identities) != 0; id++) {
1035         PACKET identity;
1036         unsigned long ticket_agel;
1037         size_t idlen;
1038
1039         if (!PACKET_get_length_prefixed_2(&identities, &identity)
1040                 || !PACKET_get_net_4(&identities, &ticket_agel)) {
1041             SSLfatal(s, SSL_AD_DECODE_ERROR,
1042                      SSL_F_TLS_PARSE_CTOS_PSK, SSL_R_BAD_EXTENSION);
1043             return 0;
1044         }
1045
1046         idlen = PACKET_remaining(&identity);
1047         if (s->psk_find_session_cb != NULL
1048                 && !s->psk_find_session_cb(s, PACKET_data(&identity), idlen,
1049                                            &sess)) {
1050             SSLfatal(s, SSL_AD_INTERNAL_ERROR,
1051                      SSL_F_TLS_PARSE_CTOS_PSK, SSL_R_BAD_EXTENSION);
1052             return 0;
1053         }
1054
1055 #ifndef OPENSSL_NO_PSK
1056         if(sess == NULL
1057                 && s->psk_server_callback != NULL
1058                 && idlen <= PSK_MAX_IDENTITY_LEN) {
1059             char *pskid = NULL;
1060             unsigned char pskdata[PSK_MAX_PSK_LEN];
1061             unsigned int pskdatalen;
1062
1063             if (!PACKET_strndup(&identity, &pskid)) {
1064                 SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_F_TLS_PARSE_CTOS_PSK,
1065                          ERR_R_INTERNAL_ERROR);
1066                 return 0;
1067             }
1068             pskdatalen = s->psk_server_callback(s, pskid, pskdata,
1069                                                 sizeof(pskdata));
1070             OPENSSL_free(pskid);
1071             if (pskdatalen > PSK_MAX_PSK_LEN) {
1072                 SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_F_TLS_PARSE_CTOS_PSK,
1073                          ERR_R_INTERNAL_ERROR);
1074                 return 0;
1075             } else if (pskdatalen > 0) {
1076                 const SSL_CIPHER *cipher;
1077                 const unsigned char tls13_aes128gcmsha256_id[] = { 0x13, 0x01 };
1078
1079                 /*
1080                  * We found a PSK using an old style callback. We don't know
1081                  * the digest so we default to SHA256 as per the TLSv1.3 spec
1082                  */
1083                 cipher = SSL_CIPHER_find(s, tls13_aes128gcmsha256_id);
1084                 if (cipher == NULL) {
1085                     OPENSSL_cleanse(pskdata, pskdatalen);
1086                     SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_F_TLS_PARSE_CTOS_PSK,
1087                              ERR_R_INTERNAL_ERROR);
1088                     return 0;
1089                 }
1090
1091                 sess = SSL_SESSION_new();
1092                 if (sess == NULL
1093                         || !SSL_SESSION_set1_master_key(sess, pskdata,
1094                                                         pskdatalen)
1095                         || !SSL_SESSION_set_cipher(sess, cipher)
1096                         || !SSL_SESSION_set_protocol_version(sess,
1097                                                              TLS1_3_VERSION)) {
1098                     OPENSSL_cleanse(pskdata, pskdatalen);
1099                     SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_F_TLS_PARSE_CTOS_PSK,
1100                              ERR_R_INTERNAL_ERROR);
1101                     goto err;
1102                 }
1103                 OPENSSL_cleanse(pskdata, pskdatalen);
1104             }
1105         }
1106 #endif /* OPENSSL_NO_PSK */
1107
1108         if (sess != NULL) {
1109             /* We found a PSK */
1110             SSL_SESSION *sesstmp = ssl_session_dup(sess, 0);
1111
1112             if (sesstmp == NULL) {
1113                 SSLfatal(s, SSL_AD_INTERNAL_ERROR,
1114                          SSL_F_TLS_PARSE_CTOS_PSK, ERR_R_INTERNAL_ERROR);
1115                 return 0;
1116             }
1117             SSL_SESSION_free(sess);
1118             sess = sesstmp;
1119
1120             /*
1121              * We've just been told to use this session for this context so
1122              * make sure the sid_ctx matches up.
1123              */
1124             memcpy(sess->sid_ctx, s->sid_ctx, s->sid_ctx_length);
1125             sess->sid_ctx_length = s->sid_ctx_length;
1126             ext = 1;
1127             if (id == 0)
1128                 s->ext.early_data_ok = 1;
1129         } else {
1130             uint32_t ticket_age = 0, now, agesec, agems;
1131             int ret;
1132
1133             ret = tls_decrypt_ticket(s, PACKET_data(&identity),
1134                                      PACKET_remaining(&identity), NULL, 0,
1135                                      &sess);
1136
1137             if (ret == SSL_TICKET_EMPTY) {
1138                 SSLfatal(s, SSL_AD_DECODE_ERROR, SSL_F_TLS_PARSE_CTOS_PSK,
1139                          SSL_R_BAD_EXTENSION);
1140                 return 0;
1141             }
1142
1143             if (ret == SSL_TICKET_FATAL_ERR_MALLOC
1144                     || ret == SSL_TICKET_FATAL_ERR_OTHER) {
1145                 SSLfatal(s, SSL_AD_INTERNAL_ERROR,
1146                          SSL_F_TLS_PARSE_CTOS_PSK, ERR_R_INTERNAL_ERROR);
1147                 return 0;
1148             }
1149             if (ret == SSL_TICKET_NONE || ret == SSL_TICKET_NO_DECRYPT)
1150                 continue;
1151
1152             /* Check for replay */
1153             if (s->max_early_data > 0
1154                     && !SSL_CTX_remove_session(s->session_ctx, sess)) {
1155                 SSL_SESSION_free(sess);
1156                 sess = NULL;
1157                 continue;
1158             }
1159
1160             ticket_age = (uint32_t)ticket_agel;
1161             now = (uint32_t)time(NULL);
1162             agesec = now - (uint32_t)sess->time;
1163             agems = agesec * (uint32_t)1000;
1164             ticket_age -= sess->ext.tick_age_add;
1165
1166             /*
1167              * For simplicity we do our age calculations in seconds. If the
1168              * client does it in ms then it could appear that their ticket age
1169              * is longer than ours (our ticket age calculation should always be
1170              * slightly longer than the client's due to the network latency).
1171              * Therefore we add 1000ms to our age calculation to adjust for
1172              * rounding errors.
1173              */
1174             if (id == 0
1175                     && sess->timeout >= (long)agesec
1176                     && agems / (uint32_t)1000 == agesec
1177                     && ticket_age <= agems + 1000
1178                     && ticket_age + TICKET_AGE_ALLOWANCE >= agems + 1000) {
1179                 /*
1180                  * Ticket age is within tolerance and not expired. We allow it
1181                  * for early data
1182                  */
1183                 s->ext.early_data_ok = 1;
1184             }
1185         }
1186
1187         md = ssl_md(sess->cipher->algorithm2);
1188         if (md != ssl_md(s->s3->tmp.new_cipher->algorithm2)) {
1189             /* The ciphersuite is not compatible with this session. */
1190             SSL_SESSION_free(sess);
1191             sess = NULL;
1192             s->ext.early_data_ok = 0;
1193             continue;
1194         }
1195         break;
1196     }
1197
1198     if (sess == NULL)
1199         return 1;
1200
1201     binderoffset = PACKET_data(pkt) - (const unsigned char *)s->init_buf->data;
1202     hashsize = EVP_MD_size(md);
1203
1204     if (!PACKET_get_length_prefixed_2(pkt, &binders)) {
1205         SSLfatal(s, SSL_AD_DECODE_ERROR, SSL_F_TLS_PARSE_CTOS_PSK,
1206                  SSL_R_BAD_EXTENSION);
1207         goto err;
1208     }
1209
1210     for (i = 0; i <= id; i++) {
1211         if (!PACKET_get_length_prefixed_1(&binders, &binder)) {
1212             SSLfatal(s, SSL_AD_DECODE_ERROR, SSL_F_TLS_PARSE_CTOS_PSK,
1213                      SSL_R_BAD_EXTENSION);
1214             goto err;
1215         }
1216     }
1217
1218     if (PACKET_remaining(&binder) != hashsize) {
1219         SSLfatal(s, SSL_AD_DECODE_ERROR, SSL_F_TLS_PARSE_CTOS_PSK,
1220                  SSL_R_BAD_EXTENSION);
1221         goto err;
1222     }
1223     if (tls_psk_do_binder(s, md, (const unsigned char *)s->init_buf->data,
1224                           binderoffset, PACKET_data(&binder), NULL, sess, 0,
1225                           ext) != 1) {
1226         /* SSLfatal() already called */
1227         goto err;
1228     }
1229
1230     sess->ext.tick_identity = id;
1231
1232     SSL_SESSION_free(s->session);
1233     s->session = sess;
1234     return 1;
1235 err:
1236     SSL_SESSION_free(sess);
1237     return 0;
1238 }
1239
1240 int tls_parse_ctos_post_handshake_auth(SSL *s, PACKET *pkt, unsigned int context,
1241                                        X509 *x, size_t chainidx)
1242 {
1243     if (PACKET_remaining(pkt) != 0) {
1244         SSLfatal(s, SSL_AD_DECODE_ERROR, SSL_F_TLS_PARSE_CTOS_POST_HANDSHAKE_AUTH,
1245                  SSL_R_POST_HANDSHAKE_AUTH_ENCODING_ERR);
1246         return 0;
1247     }
1248
1249     s->post_handshake_auth = SSL_PHA_EXT_RECEIVED;
1250
1251     return 1;
1252 }
1253
1254 /*
1255  * Add the server's renegotiation binding
1256  */
1257 EXT_RETURN tls_construct_stoc_renegotiate(SSL *s, WPACKET *pkt,
1258                                           unsigned int context, X509 *x,
1259                                           size_t chainidx)
1260 {
1261     if (!s->s3->send_connection_binding)
1262         return EXT_RETURN_NOT_SENT;
1263
1264     /* Still add this even if SSL_OP_NO_RENEGOTIATION is set */
1265     if (!WPACKET_put_bytes_u16(pkt, TLSEXT_TYPE_renegotiate)
1266             || !WPACKET_start_sub_packet_u16(pkt)
1267             || !WPACKET_start_sub_packet_u8(pkt)
1268             || !WPACKET_memcpy(pkt, s->s3->previous_client_finished,
1269                                s->s3->previous_client_finished_len)
1270             || !WPACKET_memcpy(pkt, s->s3->previous_server_finished,
1271                                s->s3->previous_server_finished_len)
1272             || !WPACKET_close(pkt)
1273             || !WPACKET_close(pkt)) {
1274         SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_F_TLS_CONSTRUCT_STOC_RENEGOTIATE,
1275                  ERR_R_INTERNAL_ERROR);
1276         return EXT_RETURN_FAIL;
1277     }
1278
1279     return EXT_RETURN_SENT;
1280 }
1281
1282 EXT_RETURN tls_construct_stoc_server_name(SSL *s, WPACKET *pkt,
1283                                           unsigned int context, X509 *x,
1284                                           size_t chainidx)
1285 {
1286     if (s->hit || s->servername_done != 1
1287             || s->session->ext.hostname == NULL)
1288         return EXT_RETURN_NOT_SENT;
1289
1290     if (!WPACKET_put_bytes_u16(pkt, TLSEXT_TYPE_server_name)
1291             || !WPACKET_put_bytes_u16(pkt, 0)) {
1292         SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_F_TLS_CONSTRUCT_STOC_SERVER_NAME,
1293                  ERR_R_INTERNAL_ERROR);
1294         return EXT_RETURN_FAIL;
1295     }
1296
1297     return EXT_RETURN_SENT;
1298 }
1299
1300 /* Add/include the server's max fragment len extension into ServerHello */
1301 EXT_RETURN tls_construct_stoc_maxfragmentlen(SSL *s, WPACKET *pkt,
1302                                              unsigned int context, X509 *x,
1303                                              size_t chainidx)
1304 {
1305     if (!USE_MAX_FRAGMENT_LENGTH_EXT(s->session))
1306         return EXT_RETURN_NOT_SENT;
1307
1308     /*-
1309      * 4 bytes for this extension type and extension length
1310      * 1 byte for the Max Fragment Length code value.
1311      */
1312     if (!WPACKET_put_bytes_u16(pkt, TLSEXT_TYPE_max_fragment_length)
1313         || !WPACKET_start_sub_packet_u16(pkt)
1314         || !WPACKET_put_bytes_u8(pkt, s->session->ext.max_fragment_len_mode)
1315         || !WPACKET_close(pkt)) {
1316         SSLfatal(s, SSL_AD_INTERNAL_ERROR,
1317                  SSL_F_TLS_CONSTRUCT_STOC_MAXFRAGMENTLEN, ERR_R_INTERNAL_ERROR);
1318         return EXT_RETURN_FAIL;
1319     }
1320
1321     return EXT_RETURN_SENT;
1322 }
1323
1324 #ifndef OPENSSL_NO_EC
1325 EXT_RETURN tls_construct_stoc_ec_pt_formats(SSL *s, WPACKET *pkt,
1326                                             unsigned int context, X509 *x,
1327                                             size_t chainidx)
1328 {
1329     unsigned long alg_k = s->s3->tmp.new_cipher->algorithm_mkey;
1330     unsigned long alg_a = s->s3->tmp.new_cipher->algorithm_auth;
1331     int using_ecc = ((alg_k & SSL_kECDHE) || (alg_a & SSL_aECDSA))
1332                     && (s->session->ext.ecpointformats != NULL);
1333     const unsigned char *plist;
1334     size_t plistlen;
1335
1336     if (!using_ecc)
1337         return EXT_RETURN_NOT_SENT;
1338
1339     tls1_get_formatlist(s, &plist, &plistlen);
1340     if (!WPACKET_put_bytes_u16(pkt, TLSEXT_TYPE_ec_point_formats)
1341             || !WPACKET_start_sub_packet_u16(pkt)
1342             || !WPACKET_sub_memcpy_u8(pkt, plist, plistlen)
1343             || !WPACKET_close(pkt)) {
1344         SSLfatal(s, SSL_AD_INTERNAL_ERROR,
1345                  SSL_F_TLS_CONSTRUCT_STOC_EC_PT_FORMATS, ERR_R_INTERNAL_ERROR);
1346         return EXT_RETURN_FAIL;
1347     }
1348
1349     return EXT_RETURN_SENT;
1350 }
1351 #endif
1352
1353 #ifndef OPENSSL_NO_EC
1354 EXT_RETURN tls_construct_stoc_supported_groups(SSL *s, WPACKET *pkt,
1355                                                unsigned int context, X509 *x,
1356                                                size_t chainidx)
1357 {
1358     const uint16_t *groups;
1359     size_t numgroups, i, first = 1;
1360
1361     /* s->s3->group_id is non zero if we accepted a key_share */
1362     if (s->s3->group_id == 0)
1363         return EXT_RETURN_NOT_SENT;
1364
1365     /* Get our list of supported groups */
1366     tls1_get_supported_groups(s, &groups, &numgroups);
1367     if (numgroups == 0) {
1368         SSLfatal(s, SSL_AD_INTERNAL_ERROR,
1369                  SSL_F_TLS_CONSTRUCT_STOC_SUPPORTED_GROUPS, ERR_R_INTERNAL_ERROR);
1370         return EXT_RETURN_FAIL;
1371     }
1372
1373     /* Copy group ID if supported */
1374     for (i = 0; i < numgroups; i++) {
1375         uint16_t group = groups[i];
1376
1377         if (tls_curve_allowed(s, group, SSL_SECOP_CURVE_SUPPORTED)) {
1378             if (first) {
1379                 /*
1380                  * Check if the client is already using our preferred group. If
1381                  * so we don't need to add this extension
1382                  */
1383                 if (s->s3->group_id == group)
1384                     return EXT_RETURN_NOT_SENT;
1385
1386                 /* Add extension header */
1387                 if (!WPACKET_put_bytes_u16(pkt, TLSEXT_TYPE_supported_groups)
1388                            /* Sub-packet for supported_groups extension */
1389                         || !WPACKET_start_sub_packet_u16(pkt)
1390                         || !WPACKET_start_sub_packet_u16(pkt)) {
1391                     SSLfatal(s, SSL_AD_INTERNAL_ERROR,
1392                              SSL_F_TLS_CONSTRUCT_STOC_SUPPORTED_GROUPS,
1393                              ERR_R_INTERNAL_ERROR);
1394                     return EXT_RETURN_FAIL;
1395                 }
1396
1397                 first = 0;
1398             }
1399             if (!WPACKET_put_bytes_u16(pkt, group)) {
1400                     SSLfatal(s, SSL_AD_INTERNAL_ERROR,
1401                              SSL_F_TLS_CONSTRUCT_STOC_SUPPORTED_GROUPS,
1402                              ERR_R_INTERNAL_ERROR);
1403                     return EXT_RETURN_FAIL;
1404                 }
1405         }
1406     }
1407
1408     if (!WPACKET_close(pkt) || !WPACKET_close(pkt)) {
1409         SSLfatal(s, SSL_AD_INTERNAL_ERROR,
1410                  SSL_F_TLS_CONSTRUCT_STOC_SUPPORTED_GROUPS,
1411                  ERR_R_INTERNAL_ERROR);
1412         return EXT_RETURN_FAIL;
1413     }
1414
1415     return EXT_RETURN_SENT;
1416 }
1417 #endif
1418
1419 EXT_RETURN tls_construct_stoc_session_ticket(SSL *s, WPACKET *pkt,
1420                                              unsigned int context, X509 *x,
1421                                              size_t chainidx)
1422 {
1423     if (!s->ext.ticket_expected || !tls_use_ticket(s)) {
1424         s->ext.ticket_expected = 0;
1425         return EXT_RETURN_NOT_SENT;
1426     }
1427
1428     if (!WPACKET_put_bytes_u16(pkt, TLSEXT_TYPE_session_ticket)
1429             || !WPACKET_put_bytes_u16(pkt, 0)) {
1430         SSLfatal(s, SSL_AD_INTERNAL_ERROR,
1431                  SSL_F_TLS_CONSTRUCT_STOC_SESSION_TICKET, ERR_R_INTERNAL_ERROR);
1432         return EXT_RETURN_FAIL;
1433     }
1434
1435     return EXT_RETURN_SENT;
1436 }
1437
1438 #ifndef OPENSSL_NO_OCSP
1439 EXT_RETURN tls_construct_stoc_status_request(SSL *s, WPACKET *pkt,
1440                                              unsigned int context, X509 *x,
1441                                              size_t chainidx)
1442 {
1443     if (!s->ext.status_expected)
1444         return EXT_RETURN_NOT_SENT;
1445
1446     if (SSL_IS_TLS13(s) && chainidx != 0)
1447         return EXT_RETURN_NOT_SENT;
1448
1449     if (!WPACKET_put_bytes_u16(pkt, TLSEXT_TYPE_status_request)
1450             || !WPACKET_start_sub_packet_u16(pkt)) {
1451         SSLfatal(s, SSL_AD_INTERNAL_ERROR,
1452                  SSL_F_TLS_CONSTRUCT_STOC_STATUS_REQUEST, ERR_R_INTERNAL_ERROR);
1453         return EXT_RETURN_FAIL;
1454     }
1455
1456     /*
1457      * In TLSv1.3 we include the certificate status itself. In <= TLSv1.2 we
1458      * send back an empty extension, with the certificate status appearing as a
1459      * separate message
1460      */
1461     if (SSL_IS_TLS13(s) && !tls_construct_cert_status_body(s, pkt)) {
1462        /* SSLfatal() already called */
1463        return EXT_RETURN_FAIL;
1464     }
1465     if (!WPACKET_close(pkt)) {
1466         SSLfatal(s, SSL_AD_INTERNAL_ERROR,
1467                  SSL_F_TLS_CONSTRUCT_STOC_STATUS_REQUEST, ERR_R_INTERNAL_ERROR);
1468         return EXT_RETURN_FAIL;
1469     }
1470
1471     return EXT_RETURN_SENT;
1472 }
1473 #endif
1474
1475 #ifndef OPENSSL_NO_NEXTPROTONEG
1476 EXT_RETURN tls_construct_stoc_next_proto_neg(SSL *s, WPACKET *pkt,
1477                                              unsigned int context, X509 *x,
1478                                              size_t chainidx)
1479 {
1480     const unsigned char *npa;
1481     unsigned int npalen;
1482     int ret;
1483     int npn_seen = s->s3->npn_seen;
1484
1485     s->s3->npn_seen = 0;
1486     if (!npn_seen || s->ctx->ext.npn_advertised_cb == NULL)
1487         return EXT_RETURN_NOT_SENT;
1488
1489     ret = s->ctx->ext.npn_advertised_cb(s, &npa, &npalen,
1490                                         s->ctx->ext.npn_advertised_cb_arg);
1491     if (ret == SSL_TLSEXT_ERR_OK) {
1492         if (!WPACKET_put_bytes_u16(pkt, TLSEXT_TYPE_next_proto_neg)
1493                 || !WPACKET_sub_memcpy_u16(pkt, npa, npalen)) {
1494             SSLfatal(s, SSL_AD_INTERNAL_ERROR,
1495                      SSL_F_TLS_CONSTRUCT_STOC_NEXT_PROTO_NEG,
1496                      ERR_R_INTERNAL_ERROR);
1497             return EXT_RETURN_FAIL;
1498         }
1499         s->s3->npn_seen = 1;
1500     }
1501
1502     return EXT_RETURN_SENT;
1503 }
1504 #endif
1505
1506 EXT_RETURN tls_construct_stoc_alpn(SSL *s, WPACKET *pkt, unsigned int context,
1507                                    X509 *x, size_t chainidx)
1508 {
1509     if (s->s3->alpn_selected == NULL)
1510         return EXT_RETURN_NOT_SENT;
1511
1512     if (!WPACKET_put_bytes_u16(pkt,
1513                 TLSEXT_TYPE_application_layer_protocol_negotiation)
1514             || !WPACKET_start_sub_packet_u16(pkt)
1515             || !WPACKET_start_sub_packet_u16(pkt)
1516             || !WPACKET_sub_memcpy_u8(pkt, s->s3->alpn_selected,
1517                                       s->s3->alpn_selected_len)
1518             || !WPACKET_close(pkt)
1519             || !WPACKET_close(pkt)) {
1520         SSLfatal(s, SSL_AD_INTERNAL_ERROR,
1521                  SSL_F_TLS_CONSTRUCT_STOC_ALPN, ERR_R_INTERNAL_ERROR);
1522         return EXT_RETURN_FAIL;
1523     }
1524
1525     return EXT_RETURN_SENT;
1526 }
1527
1528 #ifndef OPENSSL_NO_SRTP
1529 EXT_RETURN tls_construct_stoc_use_srtp(SSL *s, WPACKET *pkt,
1530                                        unsigned int context, X509 *x,
1531                                        size_t chainidx)
1532 {
1533     if (s->srtp_profile == NULL)
1534         return EXT_RETURN_NOT_SENT;
1535
1536     if (!WPACKET_put_bytes_u16(pkt, TLSEXT_TYPE_use_srtp)
1537             || !WPACKET_start_sub_packet_u16(pkt)
1538             || !WPACKET_put_bytes_u16(pkt, 2)
1539             || !WPACKET_put_bytes_u16(pkt, s->srtp_profile->id)
1540             || !WPACKET_put_bytes_u8(pkt, 0)
1541             || !WPACKET_close(pkt)) {
1542         SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_F_TLS_CONSTRUCT_STOC_USE_SRTP,
1543                  ERR_R_INTERNAL_ERROR);
1544         return EXT_RETURN_FAIL;
1545     }
1546
1547     return EXT_RETURN_SENT;
1548 }
1549 #endif
1550
1551 EXT_RETURN tls_construct_stoc_etm(SSL *s, WPACKET *pkt, unsigned int context,
1552                                   X509 *x, size_t chainidx)
1553 {
1554     if (!s->ext.use_etm)
1555         return EXT_RETURN_NOT_SENT;
1556
1557     /*
1558      * Don't use encrypt_then_mac if AEAD or RC4 might want to disable
1559      * for other cases too.
1560      */
1561     if (s->s3->tmp.new_cipher->algorithm_mac == SSL_AEAD
1562         || s->s3->tmp.new_cipher->algorithm_enc == SSL_RC4
1563         || s->s3->tmp.new_cipher->algorithm_enc == SSL_eGOST2814789CNT
1564         || s->s3->tmp.new_cipher->algorithm_enc == SSL_eGOST2814789CNT12) {
1565         s->ext.use_etm = 0;
1566         return EXT_RETURN_NOT_SENT;
1567     }
1568
1569     if (!WPACKET_put_bytes_u16(pkt, TLSEXT_TYPE_encrypt_then_mac)
1570             || !WPACKET_put_bytes_u16(pkt, 0)) {
1571         SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_F_TLS_CONSTRUCT_STOC_ETM,
1572                  ERR_R_INTERNAL_ERROR);
1573         return EXT_RETURN_FAIL;
1574     }
1575
1576     return EXT_RETURN_SENT;
1577 }
1578
1579 EXT_RETURN tls_construct_stoc_ems(SSL *s, WPACKET *pkt, unsigned int context,
1580                                   X509 *x, size_t chainidx)
1581 {
1582     if ((s->s3->flags & TLS1_FLAGS_RECEIVED_EXTMS) == 0)
1583         return EXT_RETURN_NOT_SENT;
1584
1585     if (!WPACKET_put_bytes_u16(pkt, TLSEXT_TYPE_extended_master_secret)
1586             || !WPACKET_put_bytes_u16(pkt, 0)) {
1587         SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_F_TLS_CONSTRUCT_STOC_EMS,
1588                  ERR_R_INTERNAL_ERROR);
1589         return EXT_RETURN_FAIL;
1590     }
1591
1592     return EXT_RETURN_SENT;
1593 }
1594
1595 EXT_RETURN tls_construct_stoc_supported_versions(SSL *s, WPACKET *pkt,
1596                                                  unsigned int context, X509 *x,
1597                                                  size_t chainidx)
1598 {
1599     if (!ossl_assert(SSL_IS_TLS13(s))) {
1600         SSLfatal(s, SSL_AD_INTERNAL_ERROR,
1601                  SSL_F_TLS_CONSTRUCT_STOC_SUPPORTED_VERSIONS,
1602                  ERR_R_INTERNAL_ERROR);
1603         return EXT_RETURN_FAIL;
1604     }
1605
1606     if (!WPACKET_put_bytes_u16(pkt, TLSEXT_TYPE_supported_versions)
1607             || !WPACKET_start_sub_packet_u16(pkt)
1608                 /* TODO(TLS1.3): Update to remove the TLSv1.3 draft indicator */
1609             || !WPACKET_put_bytes_u16(pkt, s->version_draft)
1610             || !WPACKET_close(pkt)) {
1611         SSLfatal(s, SSL_AD_INTERNAL_ERROR,
1612                  SSL_F_TLS_CONSTRUCT_STOC_SUPPORTED_VERSIONS,
1613                  ERR_R_INTERNAL_ERROR);
1614         return EXT_RETURN_FAIL;
1615     }
1616
1617     return EXT_RETURN_SENT;
1618 }
1619
1620 EXT_RETURN tls_construct_stoc_key_share(SSL *s, WPACKET *pkt,
1621                                         unsigned int context, X509 *x,
1622                                         size_t chainidx)
1623 {
1624 #ifndef OPENSSL_NO_TLS1_3
1625     unsigned char *encodedPoint;
1626     size_t encoded_pt_len = 0;
1627     EVP_PKEY *ckey = s->s3->peer_tmp, *skey = NULL;
1628
1629     if (s->hello_retry_request == SSL_HRR_PENDING) {
1630         if (ckey != NULL) {
1631             /* Original key_share was acceptable so don't ask for another one */
1632             return EXT_RETURN_NOT_SENT;
1633         }
1634         if (!WPACKET_put_bytes_u16(pkt, TLSEXT_TYPE_key_share)
1635                 || !WPACKET_start_sub_packet_u16(pkt)
1636                 || !WPACKET_put_bytes_u16(pkt, s->s3->group_id)
1637                 || !WPACKET_close(pkt)) {
1638             SSLfatal(s, SSL_AD_INTERNAL_ERROR,
1639                      SSL_F_TLS_CONSTRUCT_STOC_KEY_SHARE,
1640                      ERR_R_INTERNAL_ERROR);
1641             return EXT_RETURN_FAIL;
1642         }
1643
1644         return EXT_RETURN_SENT;
1645     }
1646
1647     if (ckey == NULL) {
1648         /* No key_share received from client - must be resuming */
1649         if (!s->hit || !tls13_generate_handshake_secret(s, NULL, 0)) {
1650             SSLfatal(s, SSL_AD_INTERNAL_ERROR,
1651                      SSL_F_TLS_CONSTRUCT_STOC_KEY_SHARE, ERR_R_INTERNAL_ERROR);
1652             return EXT_RETURN_FAIL;
1653         }
1654         return EXT_RETURN_NOT_SENT;
1655     }
1656
1657     if (!WPACKET_put_bytes_u16(pkt, TLSEXT_TYPE_key_share)
1658             || !WPACKET_start_sub_packet_u16(pkt)
1659             || !WPACKET_put_bytes_u16(pkt, s->s3->group_id)) {
1660         SSLfatal(s, SSL_AD_INTERNAL_ERROR,
1661                  SSL_F_TLS_CONSTRUCT_STOC_KEY_SHARE, ERR_R_INTERNAL_ERROR);
1662         return EXT_RETURN_FAIL;
1663     }
1664
1665     skey = ssl_generate_pkey(ckey);
1666     if (skey == NULL) {
1667         SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_F_TLS_CONSTRUCT_STOC_KEY_SHARE,
1668                  ERR_R_MALLOC_FAILURE);
1669         return EXT_RETURN_FAIL;
1670     }
1671
1672     /* Generate encoding of server key */
1673     encoded_pt_len = EVP_PKEY_get1_tls_encodedpoint(skey, &encodedPoint);
1674     if (encoded_pt_len == 0) {
1675         SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_F_TLS_CONSTRUCT_STOC_KEY_SHARE,
1676                  ERR_R_EC_LIB);
1677         EVP_PKEY_free(skey);
1678         return EXT_RETURN_FAIL;
1679     }
1680
1681     if (!WPACKET_sub_memcpy_u16(pkt, encodedPoint, encoded_pt_len)
1682             || !WPACKET_close(pkt)) {
1683         SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_F_TLS_CONSTRUCT_STOC_KEY_SHARE,
1684                  ERR_R_INTERNAL_ERROR);
1685         EVP_PKEY_free(skey);
1686         OPENSSL_free(encodedPoint);
1687         return EXT_RETURN_FAIL;
1688     }
1689     OPENSSL_free(encodedPoint);
1690
1691     /* This causes the crypto state to be updated based on the derived keys */
1692     s->s3->tmp.pkey = skey;
1693     if (ssl_derive(s, skey, ckey, 1) == 0) {
1694         /* SSLfatal() already called */
1695         return EXT_RETURN_FAIL;
1696     }
1697 #endif
1698
1699     return EXT_RETURN_SENT;
1700 }
1701
1702 EXT_RETURN tls_construct_stoc_cookie(SSL *s, WPACKET *pkt, unsigned int context,
1703                                      X509 *x, size_t chainidx)
1704 {
1705     unsigned char *hashval1, *hashval2, *appcookie1, *appcookie2, *cookie;
1706     unsigned char *hmac, *hmac2;
1707     size_t startlen, ciphlen, totcookielen, hashlen, hmaclen, appcookielen;
1708     EVP_MD_CTX *hctx;
1709     EVP_PKEY *pkey;
1710     int ret = EXT_RETURN_FAIL;
1711
1712     if ((s->s3->flags & TLS1_FLAGS_STATELESS) == 0)
1713         return EXT_RETURN_NOT_SENT;
1714
1715     if (s->ctx->gen_stateless_cookie_cb == NULL) {
1716         SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_F_TLS_CONSTRUCT_STOC_COOKIE,
1717                  SSL_R_NO_COOKIE_CALLBACK_SET);
1718         return EXT_RETURN_FAIL;
1719     }
1720
1721     if (!WPACKET_put_bytes_u16(pkt, TLSEXT_TYPE_cookie)
1722             || !WPACKET_start_sub_packet_u16(pkt)
1723             || !WPACKET_start_sub_packet_u16(pkt)
1724             || !WPACKET_get_total_written(pkt, &startlen)
1725             || !WPACKET_reserve_bytes(pkt, MAX_COOKIE_SIZE, &cookie)
1726             || !WPACKET_put_bytes_u16(pkt, COOKIE_STATE_FORMAT_VERSION)
1727             || !WPACKET_put_bytes_u16(pkt, TLS1_3_VERSION)
1728             || !WPACKET_put_bytes_u16(pkt, s->s3->group_id)
1729             || !s->method->put_cipher_by_char(s->s3->tmp.new_cipher, pkt,
1730                                               &ciphlen)
1731                /* Is there a key_share extension present in this HRR? */
1732             || !WPACKET_put_bytes_u8(pkt, s->s3->peer_tmp == NULL)
1733             || !WPACKET_put_bytes_u32(pkt, (unsigned int)time(NULL))
1734             || !WPACKET_start_sub_packet_u16(pkt)
1735             || !WPACKET_reserve_bytes(pkt, EVP_MAX_MD_SIZE, &hashval1)) {
1736         SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_F_TLS_CONSTRUCT_STOC_COOKIE,
1737                  ERR_R_INTERNAL_ERROR);
1738         return EXT_RETURN_FAIL;
1739     }
1740
1741     /*
1742      * Get the hash of the initial ClientHello. ssl_handshake_hash() operates
1743      * on raw buffers, so we first reserve sufficient bytes (above) and then
1744      * subsequently allocate them (below)
1745      */
1746     if (!ssl3_digest_cached_records(s, 0)
1747             || !ssl_handshake_hash(s, hashval1, EVP_MAX_MD_SIZE, &hashlen)) {
1748         /* SSLfatal() already called */
1749         return EXT_RETURN_FAIL;
1750     }
1751
1752     if (!WPACKET_allocate_bytes(pkt, hashlen, &hashval2)
1753             || !ossl_assert(hashval1 == hashval2)
1754             || !WPACKET_close(pkt)
1755             || !WPACKET_start_sub_packet_u8(pkt)
1756             || !WPACKET_reserve_bytes(pkt, SSL_COOKIE_LENGTH, &appcookie1)) {
1757         SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_F_TLS_CONSTRUCT_STOC_COOKIE,
1758                  ERR_R_INTERNAL_ERROR);
1759         return EXT_RETURN_FAIL;
1760     }
1761
1762     /* Generate the application cookie */
1763     if (s->ctx->gen_stateless_cookie_cb(s, appcookie1, &appcookielen) == 0) {
1764         SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_F_TLS_CONSTRUCT_STOC_COOKIE,
1765                  SSL_R_COOKIE_GEN_CALLBACK_FAILURE);
1766         return EXT_RETURN_FAIL;
1767     }
1768
1769     if (!WPACKET_allocate_bytes(pkt, appcookielen, &appcookie2)
1770             || !ossl_assert(appcookie1 == appcookie2)
1771             || !WPACKET_close(pkt)
1772             || !WPACKET_get_total_written(pkt, &totcookielen)
1773             || !WPACKET_reserve_bytes(pkt, SHA256_DIGEST_LENGTH, &hmac)) {
1774         SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_F_TLS_CONSTRUCT_STOC_COOKIE,
1775                  ERR_R_INTERNAL_ERROR);
1776         return EXT_RETURN_FAIL;
1777     }
1778     hmaclen = SHA256_DIGEST_LENGTH;
1779
1780     totcookielen -= startlen;
1781     if (!ossl_assert(totcookielen <= MAX_COOKIE_SIZE - SHA256_DIGEST_LENGTH)) {
1782         SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_F_TLS_CONSTRUCT_STOC_COOKIE,
1783                  ERR_R_INTERNAL_ERROR);
1784         return EXT_RETURN_FAIL;
1785     }
1786
1787     /* HMAC the cookie */
1788     hctx = EVP_MD_CTX_create();
1789     pkey = EVP_PKEY_new_raw_private_key(EVP_PKEY_HMAC, NULL,
1790                                         s->session_ctx->ext.cookie_hmac_key,
1791                                         sizeof(s->session_ctx->ext
1792                                                .cookie_hmac_key));
1793     if (hctx == NULL || pkey == NULL) {
1794         SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_F_TLS_CONSTRUCT_STOC_COOKIE,
1795                  ERR_R_MALLOC_FAILURE);
1796         goto err;
1797     }
1798
1799     if (EVP_DigestSignInit(hctx, NULL, EVP_sha256(), NULL, pkey) <= 0
1800             || EVP_DigestSign(hctx, hmac, &hmaclen, cookie,
1801                               totcookielen) <= 0) {
1802         SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_F_TLS_CONSTRUCT_STOC_COOKIE,
1803                  ERR_R_INTERNAL_ERROR);
1804         goto err;
1805     }
1806
1807     if (!ossl_assert(totcookielen + hmaclen <= MAX_COOKIE_SIZE)) {
1808         SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_F_TLS_CONSTRUCT_STOC_COOKIE,
1809                  ERR_R_INTERNAL_ERROR);
1810         goto err;
1811     }
1812
1813     if (!WPACKET_allocate_bytes(pkt, hmaclen, &hmac2)
1814             || !ossl_assert(hmac == hmac2)
1815             || !ossl_assert(cookie == hmac - totcookielen)
1816             || !WPACKET_close(pkt)
1817             || !WPACKET_close(pkt)) {
1818         SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_F_TLS_CONSTRUCT_STOC_COOKIE,
1819                  ERR_R_INTERNAL_ERROR);
1820         goto err;
1821     }
1822
1823     ret = EXT_RETURN_SENT;
1824
1825  err:
1826     EVP_MD_CTX_free(hctx);
1827     EVP_PKEY_free(pkey);
1828     return ret;
1829 }
1830
1831 EXT_RETURN tls_construct_stoc_cryptopro_bug(SSL *s, WPACKET *pkt,
1832                                             unsigned int context, X509 *x,
1833                                             size_t chainidx)
1834 {
1835     const unsigned char cryptopro_ext[36] = {
1836         0xfd, 0xe8,         /* 65000 */
1837         0x00, 0x20,         /* 32 bytes length */
1838         0x30, 0x1e, 0x30, 0x08, 0x06, 0x06, 0x2a, 0x85,
1839         0x03, 0x02, 0x02, 0x09, 0x30, 0x08, 0x06, 0x06,
1840         0x2a, 0x85, 0x03, 0x02, 0x02, 0x16, 0x30, 0x08,
1841         0x06, 0x06, 0x2a, 0x85, 0x03, 0x02, 0x02, 0x17
1842     };
1843
1844     if (((s->s3->tmp.new_cipher->id & 0xFFFF) != 0x80
1845          && (s->s3->tmp.new_cipher->id & 0xFFFF) != 0x81)
1846             || (SSL_get_options(s) & SSL_OP_CRYPTOPRO_TLSEXT_BUG) == 0)
1847         return EXT_RETURN_NOT_SENT;
1848
1849     if (!WPACKET_memcpy(pkt, cryptopro_ext, sizeof(cryptopro_ext))) {
1850         SSLfatal(s, SSL_AD_INTERNAL_ERROR,
1851                  SSL_F_TLS_CONSTRUCT_STOC_CRYPTOPRO_BUG, ERR_R_INTERNAL_ERROR);
1852         return EXT_RETURN_FAIL;
1853     }
1854
1855     return EXT_RETURN_SENT;
1856 }
1857
1858 EXT_RETURN tls_construct_stoc_early_data(SSL *s, WPACKET *pkt,
1859                                          unsigned int context, X509 *x,
1860                                          size_t chainidx)
1861 {
1862     if (context == SSL_EXT_TLS1_3_NEW_SESSION_TICKET) {
1863         if (s->max_early_data == 0)
1864             return EXT_RETURN_NOT_SENT;
1865
1866         if (!WPACKET_put_bytes_u16(pkt, TLSEXT_TYPE_early_data)
1867                 || !WPACKET_start_sub_packet_u16(pkt)
1868                 || !WPACKET_put_bytes_u32(pkt, s->max_early_data)
1869                 || !WPACKET_close(pkt)) {
1870             SSLfatal(s, SSL_AD_INTERNAL_ERROR,
1871                      SSL_F_TLS_CONSTRUCT_STOC_EARLY_DATA, ERR_R_INTERNAL_ERROR);
1872             return EXT_RETURN_FAIL;
1873         }
1874
1875         return EXT_RETURN_SENT;
1876     }
1877
1878     if (s->ext.early_data != SSL_EARLY_DATA_ACCEPTED)
1879         return EXT_RETURN_NOT_SENT;
1880
1881     if (!WPACKET_put_bytes_u16(pkt, TLSEXT_TYPE_early_data)
1882             || !WPACKET_start_sub_packet_u16(pkt)
1883             || !WPACKET_close(pkt)) {
1884         SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_F_TLS_CONSTRUCT_STOC_EARLY_DATA,
1885                  ERR_R_INTERNAL_ERROR);
1886         return EXT_RETURN_FAIL;
1887     }
1888
1889     return EXT_RETURN_SENT;
1890 }
1891
1892 EXT_RETURN tls_construct_stoc_psk(SSL *s, WPACKET *pkt, unsigned int context,
1893                                   X509 *x, size_t chainidx)
1894 {
1895     if (!s->hit)
1896         return EXT_RETURN_NOT_SENT;
1897
1898     if (!WPACKET_put_bytes_u16(pkt, TLSEXT_TYPE_psk)
1899             || !WPACKET_start_sub_packet_u16(pkt)
1900             || !WPACKET_put_bytes_u16(pkt, s->session->ext.tick_identity)
1901             || !WPACKET_close(pkt)) {
1902         SSLfatal(s, SSL_AD_INTERNAL_ERROR,
1903                  SSL_F_TLS_CONSTRUCT_STOC_PSK, ERR_R_INTERNAL_ERROR);
1904         return EXT_RETURN_FAIL;
1905     }
1906
1907     return EXT_RETURN_SENT;
1908 }