Improve testing of stateful tickets
[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 #ifndef OPENSSL_NO_TLS1_3
725     unsigned int format, version, key_share, group_id;
726     EVP_MD_CTX *hctx;
727     EVP_PKEY *pkey;
728     PACKET cookie, raw, chhash, appcookie;
729     WPACKET hrrpkt;
730     const unsigned char *data, *mdin, *ciphdata;
731     unsigned char hmac[SHA256_DIGEST_LENGTH];
732     unsigned char hrr[MAX_HRR_SIZE];
733     size_t rawlen, hmaclen, hrrlen, ciphlen;
734     unsigned long tm, now;
735
736     /* Ignore any cookie if we're not set up to verify it */
737     if (s->ctx->verify_stateless_cookie_cb == NULL
738             || (s->s3->flags & TLS1_FLAGS_STATELESS) == 0)
739         return 1;
740
741     if (!PACKET_as_length_prefixed_2(pkt, &cookie)) {
742         SSLfatal(s, SSL_AD_DECODE_ERROR, SSL_F_TLS_PARSE_CTOS_COOKIE,
743                  SSL_R_LENGTH_MISMATCH);
744         return 0;
745     }
746
747     raw = cookie;
748     data = PACKET_data(&raw);
749     rawlen = PACKET_remaining(&raw);
750     if (rawlen < SHA256_DIGEST_LENGTH
751             || !PACKET_forward(&raw, rawlen - SHA256_DIGEST_LENGTH)) {
752         SSLfatal(s, SSL_AD_DECODE_ERROR, SSL_F_TLS_PARSE_CTOS_COOKIE,
753                  SSL_R_LENGTH_MISMATCH);
754         return 0;
755     }
756     mdin = PACKET_data(&raw);
757
758     /* Verify the HMAC of the cookie */
759     hctx = EVP_MD_CTX_create();
760     pkey = EVP_PKEY_new_raw_private_key(EVP_PKEY_HMAC, NULL,
761                                         s->session_ctx->ext.cookie_hmac_key,
762                                         sizeof(s->session_ctx->ext
763                                                .cookie_hmac_key));
764     if (hctx == NULL || pkey == NULL) {
765         EVP_MD_CTX_free(hctx);
766         EVP_PKEY_free(pkey);
767         SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_F_TLS_PARSE_CTOS_COOKIE,
768                  ERR_R_MALLOC_FAILURE);
769         return 0;
770     }
771
772     hmaclen = SHA256_DIGEST_LENGTH;
773     if (EVP_DigestSignInit(hctx, NULL, EVP_sha256(), NULL, pkey) <= 0
774             || EVP_DigestSign(hctx, hmac, &hmaclen, data,
775                               rawlen - SHA256_DIGEST_LENGTH) <= 0
776             || hmaclen != SHA256_DIGEST_LENGTH) {
777         EVP_MD_CTX_free(hctx);
778         EVP_PKEY_free(pkey);
779         SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_F_TLS_PARSE_CTOS_COOKIE,
780                  ERR_R_INTERNAL_ERROR);
781         return 0;
782     }
783
784     EVP_MD_CTX_free(hctx);
785     EVP_PKEY_free(pkey);
786
787     if (CRYPTO_memcmp(hmac, mdin, SHA256_DIGEST_LENGTH) != 0) {
788         SSLfatal(s, SSL_AD_ILLEGAL_PARAMETER, SSL_F_TLS_PARSE_CTOS_COOKIE,
789                  SSL_R_COOKIE_MISMATCH);
790         return 0;
791     }
792
793     if (!PACKET_get_net_2(&cookie, &format)) {
794         SSLfatal(s, SSL_AD_DECODE_ERROR, SSL_F_TLS_PARSE_CTOS_COOKIE,
795                  SSL_R_LENGTH_MISMATCH);
796         return 0;
797     }
798     /* Check the cookie format is something we recognise. Ignore it if not */
799     if (format != COOKIE_STATE_FORMAT_VERSION)
800         return 1;
801
802     /*
803      * The rest of these checks really shouldn't fail since we have verified the
804      * HMAC above.
805      */
806
807     /* Check the version number is sane */
808     if (!PACKET_get_net_2(&cookie, &version)) {
809         SSLfatal(s, SSL_AD_DECODE_ERROR, SSL_F_TLS_PARSE_CTOS_COOKIE,
810                  SSL_R_LENGTH_MISMATCH);
811         return 0;
812     }
813     if (version != TLS1_3_VERSION) {
814         SSLfatal(s, SSL_AD_ILLEGAL_PARAMETER, SSL_F_TLS_PARSE_CTOS_COOKIE,
815                  SSL_R_BAD_PROTOCOL_VERSION_NUMBER);
816         return 0;
817     }
818
819     if (!PACKET_get_net_2(&cookie, &group_id)) {
820         SSLfatal(s, SSL_AD_DECODE_ERROR, SSL_F_TLS_PARSE_CTOS_COOKIE,
821                  SSL_R_LENGTH_MISMATCH);
822         return 0;
823     }
824
825     ciphdata = PACKET_data(&cookie);
826     if (!PACKET_forward(&cookie, 2)) {
827         SSLfatal(s, SSL_AD_DECODE_ERROR, SSL_F_TLS_PARSE_CTOS_COOKIE,
828                  SSL_R_LENGTH_MISMATCH);
829         return 0;
830     }
831     if (group_id != s->s3->group_id
832             || s->s3->tmp.new_cipher
833                != ssl_get_cipher_by_char(s, ciphdata, 0)) {
834         /*
835          * We chose a different cipher or group id this time around to what is
836          * in the cookie. Something must have changed.
837          */
838         SSLfatal(s, SSL_AD_ILLEGAL_PARAMETER, SSL_F_TLS_PARSE_CTOS_COOKIE,
839                  SSL_R_BAD_CIPHER);
840         return 0;
841     }
842
843     if (!PACKET_get_1(&cookie, &key_share)
844             || !PACKET_get_net_4(&cookie, &tm)
845             || !PACKET_get_length_prefixed_2(&cookie, &chhash)
846             || !PACKET_get_length_prefixed_1(&cookie, &appcookie)
847             || PACKET_remaining(&cookie) != SHA256_DIGEST_LENGTH) {
848         SSLfatal(s, SSL_AD_DECODE_ERROR, SSL_F_TLS_PARSE_CTOS_COOKIE,
849                  SSL_R_LENGTH_MISMATCH);
850         return 0;
851     }
852
853     /* We tolerate a cookie age of up to 10 minutes (= 60 * 10 seconds) */
854     now = (unsigned long)time(NULL);
855     if (tm > now || (now - tm) > 600) {
856         /* Cookie is stale. Ignore it */
857         return 1;
858     }
859
860     /* Verify the app cookie */
861     if (s->ctx->verify_stateless_cookie_cb(s, PACKET_data(&appcookie),
862                                      PACKET_remaining(&appcookie)) == 0) {
863         SSLfatal(s, SSL_AD_ILLEGAL_PARAMETER, SSL_F_TLS_PARSE_CTOS_COOKIE,
864                  SSL_R_COOKIE_MISMATCH);
865         return 0;
866     }
867
868     /*
869      * Reconstruct the HRR that we would have sent in response to the original
870      * ClientHello so we can add it to the transcript hash.
871      * Note: This won't work with custom HRR extensions
872      */
873     if (!WPACKET_init_static_len(&hrrpkt, hrr, sizeof(hrr), 0)) {
874         SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_F_TLS_PARSE_CTOS_COOKIE,
875                  ERR_R_INTERNAL_ERROR);
876         return 0;
877     }
878     if (!WPACKET_put_bytes_u8(&hrrpkt, SSL3_MT_SERVER_HELLO)
879             || !WPACKET_start_sub_packet_u24(&hrrpkt)
880             || !WPACKET_put_bytes_u16(&hrrpkt, TLS1_2_VERSION)
881             || !WPACKET_memcpy(&hrrpkt, hrrrandom, SSL3_RANDOM_SIZE)
882             || !WPACKET_sub_memcpy_u8(&hrrpkt, s->tmp_session_id,
883                                       s->tmp_session_id_len)
884             || !s->method->put_cipher_by_char(s->s3->tmp.new_cipher, &hrrpkt,
885                                               &ciphlen)
886             || !WPACKET_put_bytes_u8(&hrrpkt, 0)
887             || !WPACKET_start_sub_packet_u16(&hrrpkt)) {
888         WPACKET_cleanup(&hrrpkt);
889         SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_F_TLS_PARSE_CTOS_COOKIE,
890                  ERR_R_INTERNAL_ERROR);
891         return 0;
892     }
893     if (!WPACKET_put_bytes_u16(&hrrpkt, TLSEXT_TYPE_supported_versions)
894             || !WPACKET_start_sub_packet_u16(&hrrpkt)
895                /* TODO(TLS1.3): Fix this before release */
896             || !WPACKET_put_bytes_u16(&hrrpkt, s->version_draft)
897             || !WPACKET_close(&hrrpkt)) {
898         WPACKET_cleanup(&hrrpkt);
899         SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_F_TLS_PARSE_CTOS_COOKIE,
900                  ERR_R_INTERNAL_ERROR);
901         return 0;
902     }
903     if (key_share) {
904         if (!WPACKET_put_bytes_u16(&hrrpkt, TLSEXT_TYPE_key_share)
905                 || !WPACKET_start_sub_packet_u16(&hrrpkt)
906                 || !WPACKET_put_bytes_u16(&hrrpkt, s->s3->group_id)
907                 || !WPACKET_close(&hrrpkt)) {
908             WPACKET_cleanup(&hrrpkt);
909             SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_F_TLS_PARSE_CTOS_COOKIE,
910                      ERR_R_INTERNAL_ERROR);
911             return 0;
912         }
913     }
914     if (!WPACKET_put_bytes_u16(&hrrpkt, TLSEXT_TYPE_cookie)
915             || !WPACKET_start_sub_packet_u16(&hrrpkt)
916             || !WPACKET_sub_memcpy_u16(&hrrpkt, data, rawlen)
917             || !WPACKET_close(&hrrpkt) /* cookie extension */
918             || !WPACKET_close(&hrrpkt) /* extension block */
919             || !WPACKET_close(&hrrpkt) /* message */
920             || !WPACKET_get_total_written(&hrrpkt, &hrrlen)
921             || !WPACKET_finish(&hrrpkt)) {
922         WPACKET_cleanup(&hrrpkt);
923         SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_F_TLS_PARSE_CTOS_COOKIE,
924                  ERR_R_INTERNAL_ERROR);
925         return 0;
926     }
927
928     /* Reconstruct the transcript hash */
929     if (!create_synthetic_message_hash(s, PACKET_data(&chhash),
930                                        PACKET_remaining(&chhash), hrr,
931                                        hrrlen)) {
932         /* SSLfatal() already called */
933         return 0;
934     }
935
936     /* Act as if this ClientHello came after a HelloRetryRequest */
937     s->hello_retry_request = 1;
938
939     s->ext.cookieok = 1;
940 #endif
941
942     return 1;
943 }
944
945 #ifndef OPENSSL_NO_EC
946 int tls_parse_ctos_supported_groups(SSL *s, PACKET *pkt, unsigned int context,
947                                     X509 *x, size_t chainidx)
948 {
949     PACKET supported_groups_list;
950
951     /* Each group is 2 bytes and we must have at least 1. */
952     if (!PACKET_as_length_prefixed_2(pkt, &supported_groups_list)
953             || PACKET_remaining(&supported_groups_list) == 0
954             || (PACKET_remaining(&supported_groups_list) % 2) != 0) {
955         SSLfatal(s, SSL_AD_DECODE_ERROR,
956                  SSL_F_TLS_PARSE_CTOS_SUPPORTED_GROUPS, SSL_R_BAD_EXTENSION);
957         return 0;
958     }
959
960     if (!s->hit || SSL_IS_TLS13(s)) {
961         OPENSSL_free(s->session->ext.supportedgroups);
962         s->session->ext.supportedgroups = NULL;
963         s->session->ext.supportedgroups_len = 0;
964         if (!tls1_save_u16(&supported_groups_list,
965                            &s->session->ext.supportedgroups,
966                            &s->session->ext.supportedgroups_len)) {
967             SSLfatal(s, SSL_AD_INTERNAL_ERROR,
968                      SSL_F_TLS_PARSE_CTOS_SUPPORTED_GROUPS,
969                      ERR_R_INTERNAL_ERROR);
970             return 0;
971         }
972     }
973
974     return 1;
975 }
976 #endif
977
978 int tls_parse_ctos_ems(SSL *s, PACKET *pkt, unsigned int context, X509 *x,
979                        size_t chainidx)
980 {
981     /* The extension must always be empty */
982     if (PACKET_remaining(pkt) != 0) {
983         SSLfatal(s, SSL_AD_DECODE_ERROR,
984                  SSL_F_TLS_PARSE_CTOS_EMS, SSL_R_BAD_EXTENSION);
985         return 0;
986     }
987
988     s->s3->flags |= TLS1_FLAGS_RECEIVED_EXTMS;
989
990     return 1;
991 }
992
993
994 int tls_parse_ctos_early_data(SSL *s, PACKET *pkt, unsigned int context,
995                               X509 *x, size_t chainidx)
996 {
997     if (PACKET_remaining(pkt) != 0) {
998         SSLfatal(s, SSL_AD_DECODE_ERROR,
999                  SSL_F_TLS_PARSE_CTOS_EARLY_DATA, SSL_R_BAD_EXTENSION);
1000         return 0;
1001     }
1002
1003     if (s->hello_retry_request != SSL_HRR_NONE) {
1004         SSLfatal(s, SSL_AD_ILLEGAL_PARAMETER,
1005                  SSL_F_TLS_PARSE_CTOS_EARLY_DATA, SSL_R_BAD_EXTENSION);
1006         return 0;
1007     }
1008
1009     return 1;
1010 }
1011
1012 static SSL_TICKET_STATUS tls_get_stateful_ticket(SSL *s, PACKET *tick,
1013                                                  SSL_SESSION **sess)
1014 {
1015     SSL_SESSION *tmpsess = NULL;
1016
1017     switch (PACKET_remaining(tick)) {
1018         case 0:
1019             return SSL_TICKET_EMPTY;
1020
1021         case SSL_MAX_SSL_SESSION_ID_LENGTH:
1022             break;
1023
1024         default:
1025             return SSL_TICKET_NO_DECRYPT;
1026     }
1027
1028     tmpsess = lookup_sess_in_cache(s, PACKET_data(tick),
1029                                    SSL_MAX_SSL_SESSION_ID_LENGTH);
1030
1031     if (tmpsess == NULL)
1032         return SSL_TICKET_NO_DECRYPT;
1033
1034     s->ext.ticket_expected = 1;
1035     *sess = tmpsess;
1036     return SSL_TICKET_SUCCESS;
1037 }
1038
1039 int tls_parse_ctos_psk(SSL *s, PACKET *pkt, unsigned int context, X509 *x,
1040                        size_t chainidx)
1041 {
1042     PACKET identities, binders, binder;
1043     size_t binderoffset, hashsize;
1044     SSL_SESSION *sess = NULL;
1045     unsigned int id, i, ext = 0;
1046     const EVP_MD *md = NULL;
1047
1048     /*
1049      * If we have no PSK kex mode that we recognise then we can't resume so
1050      * ignore this extension
1051      */
1052     if ((s->ext.psk_kex_mode
1053             & (TLSEXT_KEX_MODE_FLAG_KE | TLSEXT_KEX_MODE_FLAG_KE_DHE)) == 0)
1054         return 1;
1055
1056     if (!PACKET_get_length_prefixed_2(pkt, &identities)) {
1057         SSLfatal(s, SSL_AD_DECODE_ERROR,
1058                  SSL_F_TLS_PARSE_CTOS_PSK, SSL_R_BAD_EXTENSION);
1059         return 0;
1060     }
1061
1062     s->ext.ticket_expected = 0;
1063     for (id = 0; PACKET_remaining(&identities) != 0; id++) {
1064         PACKET identity;
1065         unsigned long ticket_agel;
1066         size_t idlen;
1067
1068         if (!PACKET_get_length_prefixed_2(&identities, &identity)
1069                 || !PACKET_get_net_4(&identities, &ticket_agel)) {
1070             SSLfatal(s, SSL_AD_DECODE_ERROR,
1071                      SSL_F_TLS_PARSE_CTOS_PSK, SSL_R_BAD_EXTENSION);
1072             return 0;
1073         }
1074
1075         idlen = PACKET_remaining(&identity);
1076         if (s->psk_find_session_cb != NULL
1077                 && !s->psk_find_session_cb(s, PACKET_data(&identity), idlen,
1078                                            &sess)) {
1079             SSLfatal(s, SSL_AD_INTERNAL_ERROR,
1080                      SSL_F_TLS_PARSE_CTOS_PSK, SSL_R_BAD_EXTENSION);
1081             return 0;
1082         }
1083
1084 #ifndef OPENSSL_NO_PSK
1085         if(sess == NULL
1086                 && s->psk_server_callback != NULL
1087                 && idlen <= PSK_MAX_IDENTITY_LEN) {
1088             char *pskid = NULL;
1089             unsigned char pskdata[PSK_MAX_PSK_LEN];
1090             unsigned int pskdatalen;
1091
1092             if (!PACKET_strndup(&identity, &pskid)) {
1093                 SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_F_TLS_PARSE_CTOS_PSK,
1094                          ERR_R_INTERNAL_ERROR);
1095                 return 0;
1096             }
1097             pskdatalen = s->psk_server_callback(s, pskid, pskdata,
1098                                                 sizeof(pskdata));
1099             OPENSSL_free(pskid);
1100             if (pskdatalen > PSK_MAX_PSK_LEN) {
1101                 SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_F_TLS_PARSE_CTOS_PSK,
1102                          ERR_R_INTERNAL_ERROR);
1103                 return 0;
1104             } else if (pskdatalen > 0) {
1105                 const SSL_CIPHER *cipher;
1106                 const unsigned char tls13_aes128gcmsha256_id[] = { 0x13, 0x01 };
1107
1108                 /*
1109                  * We found a PSK using an old style callback. We don't know
1110                  * the digest so we default to SHA256 as per the TLSv1.3 spec
1111                  */
1112                 cipher = SSL_CIPHER_find(s, tls13_aes128gcmsha256_id);
1113                 if (cipher == NULL) {
1114                     OPENSSL_cleanse(pskdata, pskdatalen);
1115                     SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_F_TLS_PARSE_CTOS_PSK,
1116                              ERR_R_INTERNAL_ERROR);
1117                     return 0;
1118                 }
1119
1120                 sess = SSL_SESSION_new();
1121                 if (sess == NULL
1122                         || !SSL_SESSION_set1_master_key(sess, pskdata,
1123                                                         pskdatalen)
1124                         || !SSL_SESSION_set_cipher(sess, cipher)
1125                         || !SSL_SESSION_set_protocol_version(sess,
1126                                                              TLS1_3_VERSION)) {
1127                     OPENSSL_cleanse(pskdata, pskdatalen);
1128                     SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_F_TLS_PARSE_CTOS_PSK,
1129                              ERR_R_INTERNAL_ERROR);
1130                     goto err;
1131                 }
1132                 OPENSSL_cleanse(pskdata, pskdatalen);
1133             }
1134         }
1135 #endif /* OPENSSL_NO_PSK */
1136
1137         if (sess != NULL) {
1138             /* We found a PSK */
1139             SSL_SESSION *sesstmp = ssl_session_dup(sess, 0);
1140
1141             if (sesstmp == NULL) {
1142                 SSLfatal(s, SSL_AD_INTERNAL_ERROR,
1143                          SSL_F_TLS_PARSE_CTOS_PSK, ERR_R_INTERNAL_ERROR);
1144                 return 0;
1145             }
1146             SSL_SESSION_free(sess);
1147             sess = sesstmp;
1148
1149             /*
1150              * We've just been told to use this session for this context so
1151              * make sure the sid_ctx matches up.
1152              */
1153             memcpy(sess->sid_ctx, s->sid_ctx, s->sid_ctx_length);
1154             sess->sid_ctx_length = s->sid_ctx_length;
1155             ext = 1;
1156             if (id == 0)
1157                 s->ext.early_data_ok = 1;
1158         } else {
1159             uint32_t ticket_age = 0, now, agesec, agems;
1160             int ret;
1161
1162             /*
1163              * If we are using anti-replay protection then we behave as if
1164              * SSL_OP_NO_TICKET is set - we are caching tickets anyway so there
1165              * is no point in using full stateless tickets.
1166              */
1167             if ((s->options & SSL_OP_NO_TICKET) != 0
1168                     || (s->max_early_data > 0
1169                         && (s->options & SSL_OP_NO_ANTI_REPLAY) == 0))
1170                 ret = tls_get_stateful_ticket(s, &identity, &sess);
1171             else
1172                 ret = tls_decrypt_ticket(s, PACKET_data(&identity),
1173                                          PACKET_remaining(&identity), NULL, 0,
1174                                          &sess);
1175
1176             if (ret == SSL_TICKET_EMPTY) {
1177                 SSLfatal(s, SSL_AD_DECODE_ERROR, SSL_F_TLS_PARSE_CTOS_PSK,
1178                          SSL_R_BAD_EXTENSION);
1179                 return 0;
1180             }
1181
1182             if (ret == SSL_TICKET_FATAL_ERR_MALLOC
1183                     || ret == SSL_TICKET_FATAL_ERR_OTHER) {
1184                 SSLfatal(s, SSL_AD_INTERNAL_ERROR,
1185                          SSL_F_TLS_PARSE_CTOS_PSK, ERR_R_INTERNAL_ERROR);
1186                 return 0;
1187             }
1188             if (ret == SSL_TICKET_NONE || ret == SSL_TICKET_NO_DECRYPT)
1189                 continue;
1190
1191             /* Check for replay */
1192             if (s->max_early_data > 0
1193                     && (s->options & SSL_OP_NO_ANTI_REPLAY) == 0
1194                     && !SSL_CTX_remove_session(s->session_ctx, sess)) {
1195                 SSL_SESSION_free(sess);
1196                 sess = NULL;
1197                 continue;
1198             }
1199
1200             ticket_age = (uint32_t)ticket_agel;
1201             now = (uint32_t)time(NULL);
1202             agesec = now - (uint32_t)sess->time;
1203             agems = agesec * (uint32_t)1000;
1204             ticket_age -= sess->ext.tick_age_add;
1205
1206             /*
1207              * For simplicity we do our age calculations in seconds. If the
1208              * client does it in ms then it could appear that their ticket age
1209              * is longer than ours (our ticket age calculation should always be
1210              * slightly longer than the client's due to the network latency).
1211              * Therefore we add 1000ms to our age calculation to adjust for
1212              * rounding errors.
1213              */
1214             if (id == 0
1215                     && sess->timeout >= (long)agesec
1216                     && agems / (uint32_t)1000 == agesec
1217                     && ticket_age <= agems + 1000
1218                     && ticket_age + TICKET_AGE_ALLOWANCE >= agems + 1000) {
1219                 /*
1220                  * Ticket age is within tolerance and not expired. We allow it
1221                  * for early data
1222                  */
1223                 s->ext.early_data_ok = 1;
1224             }
1225         }
1226
1227         md = ssl_md(sess->cipher->algorithm2);
1228         if (md != ssl_md(s->s3->tmp.new_cipher->algorithm2)) {
1229             /* The ciphersuite is not compatible with this session. */
1230             SSL_SESSION_free(sess);
1231             sess = NULL;
1232             s->ext.early_data_ok = 0;
1233             continue;
1234         }
1235         break;
1236     }
1237
1238     if (sess == NULL)
1239         return 1;
1240
1241     binderoffset = PACKET_data(pkt) - (const unsigned char *)s->init_buf->data;
1242     hashsize = EVP_MD_size(md);
1243
1244     if (!PACKET_get_length_prefixed_2(pkt, &binders)) {
1245         SSLfatal(s, SSL_AD_DECODE_ERROR, SSL_F_TLS_PARSE_CTOS_PSK,
1246                  SSL_R_BAD_EXTENSION);
1247         goto err;
1248     }
1249
1250     for (i = 0; i <= id; i++) {
1251         if (!PACKET_get_length_prefixed_1(&binders, &binder)) {
1252             SSLfatal(s, SSL_AD_DECODE_ERROR, SSL_F_TLS_PARSE_CTOS_PSK,
1253                      SSL_R_BAD_EXTENSION);
1254             goto err;
1255         }
1256     }
1257
1258     if (PACKET_remaining(&binder) != hashsize) {
1259         SSLfatal(s, SSL_AD_DECODE_ERROR, SSL_F_TLS_PARSE_CTOS_PSK,
1260                  SSL_R_BAD_EXTENSION);
1261         goto err;
1262     }
1263     if (tls_psk_do_binder(s, md, (const unsigned char *)s->init_buf->data,
1264                           binderoffset, PACKET_data(&binder), NULL, sess, 0,
1265                           ext) != 1) {
1266         /* SSLfatal() already called */
1267         goto err;
1268     }
1269
1270     sess->ext.tick_identity = id;
1271
1272     SSL_SESSION_free(s->session);
1273     s->session = sess;
1274     return 1;
1275 err:
1276     SSL_SESSION_free(sess);
1277     return 0;
1278 }
1279
1280 int tls_parse_ctos_post_handshake_auth(SSL *s, PACKET *pkt, unsigned int context,
1281                                        X509 *x, size_t chainidx)
1282 {
1283     if (PACKET_remaining(pkt) != 0) {
1284         SSLfatal(s, SSL_AD_DECODE_ERROR, SSL_F_TLS_PARSE_CTOS_POST_HANDSHAKE_AUTH,
1285                  SSL_R_POST_HANDSHAKE_AUTH_ENCODING_ERR);
1286         return 0;
1287     }
1288
1289     s->post_handshake_auth = SSL_PHA_EXT_RECEIVED;
1290
1291     return 1;
1292 }
1293
1294 /*
1295  * Add the server's renegotiation binding
1296  */
1297 EXT_RETURN tls_construct_stoc_renegotiate(SSL *s, WPACKET *pkt,
1298                                           unsigned int context, X509 *x,
1299                                           size_t chainidx)
1300 {
1301     if (!s->s3->send_connection_binding)
1302         return EXT_RETURN_NOT_SENT;
1303
1304     /* Still add this even if SSL_OP_NO_RENEGOTIATION is set */
1305     if (!WPACKET_put_bytes_u16(pkt, TLSEXT_TYPE_renegotiate)
1306             || !WPACKET_start_sub_packet_u16(pkt)
1307             || !WPACKET_start_sub_packet_u8(pkt)
1308             || !WPACKET_memcpy(pkt, s->s3->previous_client_finished,
1309                                s->s3->previous_client_finished_len)
1310             || !WPACKET_memcpy(pkt, s->s3->previous_server_finished,
1311                                s->s3->previous_server_finished_len)
1312             || !WPACKET_close(pkt)
1313             || !WPACKET_close(pkt)) {
1314         SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_F_TLS_CONSTRUCT_STOC_RENEGOTIATE,
1315                  ERR_R_INTERNAL_ERROR);
1316         return EXT_RETURN_FAIL;
1317     }
1318
1319     return EXT_RETURN_SENT;
1320 }
1321
1322 EXT_RETURN tls_construct_stoc_server_name(SSL *s, WPACKET *pkt,
1323                                           unsigned int context, X509 *x,
1324                                           size_t chainidx)
1325 {
1326     if (s->hit || s->servername_done != 1
1327             || s->session->ext.hostname == NULL)
1328         return EXT_RETURN_NOT_SENT;
1329
1330     if (!WPACKET_put_bytes_u16(pkt, TLSEXT_TYPE_server_name)
1331             || !WPACKET_put_bytes_u16(pkt, 0)) {
1332         SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_F_TLS_CONSTRUCT_STOC_SERVER_NAME,
1333                  ERR_R_INTERNAL_ERROR);
1334         return EXT_RETURN_FAIL;
1335     }
1336
1337     return EXT_RETURN_SENT;
1338 }
1339
1340 /* Add/include the server's max fragment len extension into ServerHello */
1341 EXT_RETURN tls_construct_stoc_maxfragmentlen(SSL *s, WPACKET *pkt,
1342                                              unsigned int context, X509 *x,
1343                                              size_t chainidx)
1344 {
1345     if (!USE_MAX_FRAGMENT_LENGTH_EXT(s->session))
1346         return EXT_RETURN_NOT_SENT;
1347
1348     /*-
1349      * 4 bytes for this extension type and extension length
1350      * 1 byte for the Max Fragment Length code value.
1351      */
1352     if (!WPACKET_put_bytes_u16(pkt, TLSEXT_TYPE_max_fragment_length)
1353         || !WPACKET_start_sub_packet_u16(pkt)
1354         || !WPACKET_put_bytes_u8(pkt, s->session->ext.max_fragment_len_mode)
1355         || !WPACKET_close(pkt)) {
1356         SSLfatal(s, SSL_AD_INTERNAL_ERROR,
1357                  SSL_F_TLS_CONSTRUCT_STOC_MAXFRAGMENTLEN, ERR_R_INTERNAL_ERROR);
1358         return EXT_RETURN_FAIL;
1359     }
1360
1361     return EXT_RETURN_SENT;
1362 }
1363
1364 #ifndef OPENSSL_NO_EC
1365 EXT_RETURN tls_construct_stoc_ec_pt_formats(SSL *s, WPACKET *pkt,
1366                                             unsigned int context, X509 *x,
1367                                             size_t chainidx)
1368 {
1369     unsigned long alg_k = s->s3->tmp.new_cipher->algorithm_mkey;
1370     unsigned long alg_a = s->s3->tmp.new_cipher->algorithm_auth;
1371     int using_ecc = ((alg_k & SSL_kECDHE) || (alg_a & SSL_aECDSA))
1372                     && (s->session->ext.ecpointformats != NULL);
1373     const unsigned char *plist;
1374     size_t plistlen;
1375
1376     if (!using_ecc)
1377         return EXT_RETURN_NOT_SENT;
1378
1379     tls1_get_formatlist(s, &plist, &plistlen);
1380     if (!WPACKET_put_bytes_u16(pkt, TLSEXT_TYPE_ec_point_formats)
1381             || !WPACKET_start_sub_packet_u16(pkt)
1382             || !WPACKET_sub_memcpy_u8(pkt, plist, plistlen)
1383             || !WPACKET_close(pkt)) {
1384         SSLfatal(s, SSL_AD_INTERNAL_ERROR,
1385                  SSL_F_TLS_CONSTRUCT_STOC_EC_PT_FORMATS, ERR_R_INTERNAL_ERROR);
1386         return EXT_RETURN_FAIL;
1387     }
1388
1389     return EXT_RETURN_SENT;
1390 }
1391 #endif
1392
1393 #ifndef OPENSSL_NO_EC
1394 EXT_RETURN tls_construct_stoc_supported_groups(SSL *s, WPACKET *pkt,
1395                                                unsigned int context, X509 *x,
1396                                                size_t chainidx)
1397 {
1398     const uint16_t *groups;
1399     size_t numgroups, i, first = 1;
1400
1401     /* s->s3->group_id is non zero if we accepted a key_share */
1402     if (s->s3->group_id == 0)
1403         return EXT_RETURN_NOT_SENT;
1404
1405     /* Get our list of supported groups */
1406     tls1_get_supported_groups(s, &groups, &numgroups);
1407     if (numgroups == 0) {
1408         SSLfatal(s, SSL_AD_INTERNAL_ERROR,
1409                  SSL_F_TLS_CONSTRUCT_STOC_SUPPORTED_GROUPS, ERR_R_INTERNAL_ERROR);
1410         return EXT_RETURN_FAIL;
1411     }
1412
1413     /* Copy group ID if supported */
1414     for (i = 0; i < numgroups; i++) {
1415         uint16_t group = groups[i];
1416
1417         if (tls_curve_allowed(s, group, SSL_SECOP_CURVE_SUPPORTED)) {
1418             if (first) {
1419                 /*
1420                  * Check if the client is already using our preferred group. If
1421                  * so we don't need to add this extension
1422                  */
1423                 if (s->s3->group_id == group)
1424                     return EXT_RETURN_NOT_SENT;
1425
1426                 /* Add extension header */
1427                 if (!WPACKET_put_bytes_u16(pkt, TLSEXT_TYPE_supported_groups)
1428                            /* Sub-packet for supported_groups extension */
1429                         || !WPACKET_start_sub_packet_u16(pkt)
1430                         || !WPACKET_start_sub_packet_u16(pkt)) {
1431                     SSLfatal(s, SSL_AD_INTERNAL_ERROR,
1432                              SSL_F_TLS_CONSTRUCT_STOC_SUPPORTED_GROUPS,
1433                              ERR_R_INTERNAL_ERROR);
1434                     return EXT_RETURN_FAIL;
1435                 }
1436
1437                 first = 0;
1438             }
1439             if (!WPACKET_put_bytes_u16(pkt, group)) {
1440                     SSLfatal(s, SSL_AD_INTERNAL_ERROR,
1441                              SSL_F_TLS_CONSTRUCT_STOC_SUPPORTED_GROUPS,
1442                              ERR_R_INTERNAL_ERROR);
1443                     return EXT_RETURN_FAIL;
1444                 }
1445         }
1446     }
1447
1448     if (!WPACKET_close(pkt) || !WPACKET_close(pkt)) {
1449         SSLfatal(s, SSL_AD_INTERNAL_ERROR,
1450                  SSL_F_TLS_CONSTRUCT_STOC_SUPPORTED_GROUPS,
1451                  ERR_R_INTERNAL_ERROR);
1452         return EXT_RETURN_FAIL;
1453     }
1454
1455     return EXT_RETURN_SENT;
1456 }
1457 #endif
1458
1459 EXT_RETURN tls_construct_stoc_session_ticket(SSL *s, WPACKET *pkt,
1460                                              unsigned int context, X509 *x,
1461                                              size_t chainidx)
1462 {
1463     if (!s->ext.ticket_expected || !tls_use_ticket(s)) {
1464         s->ext.ticket_expected = 0;
1465         return EXT_RETURN_NOT_SENT;
1466     }
1467
1468     if (!WPACKET_put_bytes_u16(pkt, TLSEXT_TYPE_session_ticket)
1469             || !WPACKET_put_bytes_u16(pkt, 0)) {
1470         SSLfatal(s, SSL_AD_INTERNAL_ERROR,
1471                  SSL_F_TLS_CONSTRUCT_STOC_SESSION_TICKET, ERR_R_INTERNAL_ERROR);
1472         return EXT_RETURN_FAIL;
1473     }
1474
1475     return EXT_RETURN_SENT;
1476 }
1477
1478 #ifndef OPENSSL_NO_OCSP
1479 EXT_RETURN tls_construct_stoc_status_request(SSL *s, WPACKET *pkt,
1480                                              unsigned int context, X509 *x,
1481                                              size_t chainidx)
1482 {
1483     if (!s->ext.status_expected)
1484         return EXT_RETURN_NOT_SENT;
1485
1486     if (SSL_IS_TLS13(s) && chainidx != 0)
1487         return EXT_RETURN_NOT_SENT;
1488
1489     if (!WPACKET_put_bytes_u16(pkt, TLSEXT_TYPE_status_request)
1490             || !WPACKET_start_sub_packet_u16(pkt)) {
1491         SSLfatal(s, SSL_AD_INTERNAL_ERROR,
1492                  SSL_F_TLS_CONSTRUCT_STOC_STATUS_REQUEST, ERR_R_INTERNAL_ERROR);
1493         return EXT_RETURN_FAIL;
1494     }
1495
1496     /*
1497      * In TLSv1.3 we include the certificate status itself. In <= TLSv1.2 we
1498      * send back an empty extension, with the certificate status appearing as a
1499      * separate message
1500      */
1501     if (SSL_IS_TLS13(s) && !tls_construct_cert_status_body(s, pkt)) {
1502        /* SSLfatal() already called */
1503        return EXT_RETURN_FAIL;
1504     }
1505     if (!WPACKET_close(pkt)) {
1506         SSLfatal(s, SSL_AD_INTERNAL_ERROR,
1507                  SSL_F_TLS_CONSTRUCT_STOC_STATUS_REQUEST, ERR_R_INTERNAL_ERROR);
1508         return EXT_RETURN_FAIL;
1509     }
1510
1511     return EXT_RETURN_SENT;
1512 }
1513 #endif
1514
1515 #ifndef OPENSSL_NO_NEXTPROTONEG
1516 EXT_RETURN tls_construct_stoc_next_proto_neg(SSL *s, WPACKET *pkt,
1517                                              unsigned int context, X509 *x,
1518                                              size_t chainidx)
1519 {
1520     const unsigned char *npa;
1521     unsigned int npalen;
1522     int ret;
1523     int npn_seen = s->s3->npn_seen;
1524
1525     s->s3->npn_seen = 0;
1526     if (!npn_seen || s->ctx->ext.npn_advertised_cb == NULL)
1527         return EXT_RETURN_NOT_SENT;
1528
1529     ret = s->ctx->ext.npn_advertised_cb(s, &npa, &npalen,
1530                                         s->ctx->ext.npn_advertised_cb_arg);
1531     if (ret == SSL_TLSEXT_ERR_OK) {
1532         if (!WPACKET_put_bytes_u16(pkt, TLSEXT_TYPE_next_proto_neg)
1533                 || !WPACKET_sub_memcpy_u16(pkt, npa, npalen)) {
1534             SSLfatal(s, SSL_AD_INTERNAL_ERROR,
1535                      SSL_F_TLS_CONSTRUCT_STOC_NEXT_PROTO_NEG,
1536                      ERR_R_INTERNAL_ERROR);
1537             return EXT_RETURN_FAIL;
1538         }
1539         s->s3->npn_seen = 1;
1540     }
1541
1542     return EXT_RETURN_SENT;
1543 }
1544 #endif
1545
1546 EXT_RETURN tls_construct_stoc_alpn(SSL *s, WPACKET *pkt, unsigned int context,
1547                                    X509 *x, size_t chainidx)
1548 {
1549     if (s->s3->alpn_selected == NULL)
1550         return EXT_RETURN_NOT_SENT;
1551
1552     if (!WPACKET_put_bytes_u16(pkt,
1553                 TLSEXT_TYPE_application_layer_protocol_negotiation)
1554             || !WPACKET_start_sub_packet_u16(pkt)
1555             || !WPACKET_start_sub_packet_u16(pkt)
1556             || !WPACKET_sub_memcpy_u8(pkt, s->s3->alpn_selected,
1557                                       s->s3->alpn_selected_len)
1558             || !WPACKET_close(pkt)
1559             || !WPACKET_close(pkt)) {
1560         SSLfatal(s, SSL_AD_INTERNAL_ERROR,
1561                  SSL_F_TLS_CONSTRUCT_STOC_ALPN, ERR_R_INTERNAL_ERROR);
1562         return EXT_RETURN_FAIL;
1563     }
1564
1565     return EXT_RETURN_SENT;
1566 }
1567
1568 #ifndef OPENSSL_NO_SRTP
1569 EXT_RETURN tls_construct_stoc_use_srtp(SSL *s, WPACKET *pkt,
1570                                        unsigned int context, X509 *x,
1571                                        size_t chainidx)
1572 {
1573     if (s->srtp_profile == NULL)
1574         return EXT_RETURN_NOT_SENT;
1575
1576     if (!WPACKET_put_bytes_u16(pkt, TLSEXT_TYPE_use_srtp)
1577             || !WPACKET_start_sub_packet_u16(pkt)
1578             || !WPACKET_put_bytes_u16(pkt, 2)
1579             || !WPACKET_put_bytes_u16(pkt, s->srtp_profile->id)
1580             || !WPACKET_put_bytes_u8(pkt, 0)
1581             || !WPACKET_close(pkt)) {
1582         SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_F_TLS_CONSTRUCT_STOC_USE_SRTP,
1583                  ERR_R_INTERNAL_ERROR);
1584         return EXT_RETURN_FAIL;
1585     }
1586
1587     return EXT_RETURN_SENT;
1588 }
1589 #endif
1590
1591 EXT_RETURN tls_construct_stoc_etm(SSL *s, WPACKET *pkt, unsigned int context,
1592                                   X509 *x, size_t chainidx)
1593 {
1594     if (!s->ext.use_etm)
1595         return EXT_RETURN_NOT_SENT;
1596
1597     /*
1598      * Don't use encrypt_then_mac if AEAD or RC4 might want to disable
1599      * for other cases too.
1600      */
1601     if (s->s3->tmp.new_cipher->algorithm_mac == SSL_AEAD
1602         || s->s3->tmp.new_cipher->algorithm_enc == SSL_RC4
1603         || s->s3->tmp.new_cipher->algorithm_enc == SSL_eGOST2814789CNT
1604         || s->s3->tmp.new_cipher->algorithm_enc == SSL_eGOST2814789CNT12) {
1605         s->ext.use_etm = 0;
1606         return EXT_RETURN_NOT_SENT;
1607     }
1608
1609     if (!WPACKET_put_bytes_u16(pkt, TLSEXT_TYPE_encrypt_then_mac)
1610             || !WPACKET_put_bytes_u16(pkt, 0)) {
1611         SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_F_TLS_CONSTRUCT_STOC_ETM,
1612                  ERR_R_INTERNAL_ERROR);
1613         return EXT_RETURN_FAIL;
1614     }
1615
1616     return EXT_RETURN_SENT;
1617 }
1618
1619 EXT_RETURN tls_construct_stoc_ems(SSL *s, WPACKET *pkt, unsigned int context,
1620                                   X509 *x, size_t chainidx)
1621 {
1622     if ((s->s3->flags & TLS1_FLAGS_RECEIVED_EXTMS) == 0)
1623         return EXT_RETURN_NOT_SENT;
1624
1625     if (!WPACKET_put_bytes_u16(pkt, TLSEXT_TYPE_extended_master_secret)
1626             || !WPACKET_put_bytes_u16(pkt, 0)) {
1627         SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_F_TLS_CONSTRUCT_STOC_EMS,
1628                  ERR_R_INTERNAL_ERROR);
1629         return EXT_RETURN_FAIL;
1630     }
1631
1632     return EXT_RETURN_SENT;
1633 }
1634
1635 EXT_RETURN tls_construct_stoc_supported_versions(SSL *s, WPACKET *pkt,
1636                                                  unsigned int context, X509 *x,
1637                                                  size_t chainidx)
1638 {
1639     if (!ossl_assert(SSL_IS_TLS13(s))) {
1640         SSLfatal(s, SSL_AD_INTERNAL_ERROR,
1641                  SSL_F_TLS_CONSTRUCT_STOC_SUPPORTED_VERSIONS,
1642                  ERR_R_INTERNAL_ERROR);
1643         return EXT_RETURN_FAIL;
1644     }
1645
1646     if (!WPACKET_put_bytes_u16(pkt, TLSEXT_TYPE_supported_versions)
1647             || !WPACKET_start_sub_packet_u16(pkt)
1648                 /* TODO(TLS1.3): Update to remove the TLSv1.3 draft indicator */
1649             || !WPACKET_put_bytes_u16(pkt, s->version_draft)
1650             || !WPACKET_close(pkt)) {
1651         SSLfatal(s, SSL_AD_INTERNAL_ERROR,
1652                  SSL_F_TLS_CONSTRUCT_STOC_SUPPORTED_VERSIONS,
1653                  ERR_R_INTERNAL_ERROR);
1654         return EXT_RETURN_FAIL;
1655     }
1656
1657     return EXT_RETURN_SENT;
1658 }
1659
1660 EXT_RETURN tls_construct_stoc_key_share(SSL *s, WPACKET *pkt,
1661                                         unsigned int context, X509 *x,
1662                                         size_t chainidx)
1663 {
1664 #ifndef OPENSSL_NO_TLS1_3
1665     unsigned char *encodedPoint;
1666     size_t encoded_pt_len = 0;
1667     EVP_PKEY *ckey = s->s3->peer_tmp, *skey = NULL;
1668
1669     if (s->hello_retry_request == SSL_HRR_PENDING) {
1670         if (ckey != NULL) {
1671             /* Original key_share was acceptable so don't ask for another one */
1672             return EXT_RETURN_NOT_SENT;
1673         }
1674         if (!WPACKET_put_bytes_u16(pkt, TLSEXT_TYPE_key_share)
1675                 || !WPACKET_start_sub_packet_u16(pkt)
1676                 || !WPACKET_put_bytes_u16(pkt, s->s3->group_id)
1677                 || !WPACKET_close(pkt)) {
1678             SSLfatal(s, SSL_AD_INTERNAL_ERROR,
1679                      SSL_F_TLS_CONSTRUCT_STOC_KEY_SHARE,
1680                      ERR_R_INTERNAL_ERROR);
1681             return EXT_RETURN_FAIL;
1682         }
1683
1684         return EXT_RETURN_SENT;
1685     }
1686
1687     if (ckey == NULL) {
1688         /* No key_share received from client - must be resuming */
1689         if (!s->hit || !tls13_generate_handshake_secret(s, NULL, 0)) {
1690             SSLfatal(s, SSL_AD_INTERNAL_ERROR,
1691                      SSL_F_TLS_CONSTRUCT_STOC_KEY_SHARE, ERR_R_INTERNAL_ERROR);
1692             return EXT_RETURN_FAIL;
1693         }
1694         return EXT_RETURN_NOT_SENT;
1695     }
1696
1697     if (!WPACKET_put_bytes_u16(pkt, TLSEXT_TYPE_key_share)
1698             || !WPACKET_start_sub_packet_u16(pkt)
1699             || !WPACKET_put_bytes_u16(pkt, s->s3->group_id)) {
1700         SSLfatal(s, SSL_AD_INTERNAL_ERROR,
1701                  SSL_F_TLS_CONSTRUCT_STOC_KEY_SHARE, ERR_R_INTERNAL_ERROR);
1702         return EXT_RETURN_FAIL;
1703     }
1704
1705     skey = ssl_generate_pkey(ckey);
1706     if (skey == NULL) {
1707         SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_F_TLS_CONSTRUCT_STOC_KEY_SHARE,
1708                  ERR_R_MALLOC_FAILURE);
1709         return EXT_RETURN_FAIL;
1710     }
1711
1712     /* Generate encoding of server key */
1713     encoded_pt_len = EVP_PKEY_get1_tls_encodedpoint(skey, &encodedPoint);
1714     if (encoded_pt_len == 0) {
1715         SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_F_TLS_CONSTRUCT_STOC_KEY_SHARE,
1716                  ERR_R_EC_LIB);
1717         EVP_PKEY_free(skey);
1718         return EXT_RETURN_FAIL;
1719     }
1720
1721     if (!WPACKET_sub_memcpy_u16(pkt, encodedPoint, encoded_pt_len)
1722             || !WPACKET_close(pkt)) {
1723         SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_F_TLS_CONSTRUCT_STOC_KEY_SHARE,
1724                  ERR_R_INTERNAL_ERROR);
1725         EVP_PKEY_free(skey);
1726         OPENSSL_free(encodedPoint);
1727         return EXT_RETURN_FAIL;
1728     }
1729     OPENSSL_free(encodedPoint);
1730
1731     /* This causes the crypto state to be updated based on the derived keys */
1732     s->s3->tmp.pkey = skey;
1733     if (ssl_derive(s, skey, ckey, 1) == 0) {
1734         /* SSLfatal() already called */
1735         return EXT_RETURN_FAIL;
1736     }
1737     return EXT_RETURN_SENT;
1738 #else
1739     return EXT_RETURN_FAIL;
1740 #endif
1741 }
1742
1743 EXT_RETURN tls_construct_stoc_cookie(SSL *s, WPACKET *pkt, unsigned int context,
1744                                      X509 *x, size_t chainidx)
1745 {
1746 #ifndef OPENSSL_NO_TLS1_3
1747     unsigned char *hashval1, *hashval2, *appcookie1, *appcookie2, *cookie;
1748     unsigned char *hmac, *hmac2;
1749     size_t startlen, ciphlen, totcookielen, hashlen, hmaclen, appcookielen;
1750     EVP_MD_CTX *hctx;
1751     EVP_PKEY *pkey;
1752     int ret = EXT_RETURN_FAIL;
1753
1754     if ((s->s3->flags & TLS1_FLAGS_STATELESS) == 0)
1755         return EXT_RETURN_NOT_SENT;
1756
1757     if (s->ctx->gen_stateless_cookie_cb == NULL) {
1758         SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_F_TLS_CONSTRUCT_STOC_COOKIE,
1759                  SSL_R_NO_COOKIE_CALLBACK_SET);
1760         return EXT_RETURN_FAIL;
1761     }
1762
1763     if (!WPACKET_put_bytes_u16(pkt, TLSEXT_TYPE_cookie)
1764             || !WPACKET_start_sub_packet_u16(pkt)
1765             || !WPACKET_start_sub_packet_u16(pkt)
1766             || !WPACKET_get_total_written(pkt, &startlen)
1767             || !WPACKET_reserve_bytes(pkt, MAX_COOKIE_SIZE, &cookie)
1768             || !WPACKET_put_bytes_u16(pkt, COOKIE_STATE_FORMAT_VERSION)
1769             || !WPACKET_put_bytes_u16(pkt, TLS1_3_VERSION)
1770             || !WPACKET_put_bytes_u16(pkt, s->s3->group_id)
1771             || !s->method->put_cipher_by_char(s->s3->tmp.new_cipher, pkt,
1772                                               &ciphlen)
1773                /* Is there a key_share extension present in this HRR? */
1774             || !WPACKET_put_bytes_u8(pkt, s->s3->peer_tmp == NULL)
1775             || !WPACKET_put_bytes_u32(pkt, (unsigned int)time(NULL))
1776             || !WPACKET_start_sub_packet_u16(pkt)
1777             || !WPACKET_reserve_bytes(pkt, EVP_MAX_MD_SIZE, &hashval1)) {
1778         SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_F_TLS_CONSTRUCT_STOC_COOKIE,
1779                  ERR_R_INTERNAL_ERROR);
1780         return EXT_RETURN_FAIL;
1781     }
1782
1783     /*
1784      * Get the hash of the initial ClientHello. ssl_handshake_hash() operates
1785      * on raw buffers, so we first reserve sufficient bytes (above) and then
1786      * subsequently allocate them (below)
1787      */
1788     if (!ssl3_digest_cached_records(s, 0)
1789             || !ssl_handshake_hash(s, hashval1, EVP_MAX_MD_SIZE, &hashlen)) {
1790         /* SSLfatal() already called */
1791         return EXT_RETURN_FAIL;
1792     }
1793
1794     if (!WPACKET_allocate_bytes(pkt, hashlen, &hashval2)
1795             || !ossl_assert(hashval1 == hashval2)
1796             || !WPACKET_close(pkt)
1797             || !WPACKET_start_sub_packet_u8(pkt)
1798             || !WPACKET_reserve_bytes(pkt, SSL_COOKIE_LENGTH, &appcookie1)) {
1799         SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_F_TLS_CONSTRUCT_STOC_COOKIE,
1800                  ERR_R_INTERNAL_ERROR);
1801         return EXT_RETURN_FAIL;
1802     }
1803
1804     /* Generate the application cookie */
1805     if (s->ctx->gen_stateless_cookie_cb(s, appcookie1, &appcookielen) == 0) {
1806         SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_F_TLS_CONSTRUCT_STOC_COOKIE,
1807                  SSL_R_COOKIE_GEN_CALLBACK_FAILURE);
1808         return EXT_RETURN_FAIL;
1809     }
1810
1811     if (!WPACKET_allocate_bytes(pkt, appcookielen, &appcookie2)
1812             || !ossl_assert(appcookie1 == appcookie2)
1813             || !WPACKET_close(pkt)
1814             || !WPACKET_get_total_written(pkt, &totcookielen)
1815             || !WPACKET_reserve_bytes(pkt, SHA256_DIGEST_LENGTH, &hmac)) {
1816         SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_F_TLS_CONSTRUCT_STOC_COOKIE,
1817                  ERR_R_INTERNAL_ERROR);
1818         return EXT_RETURN_FAIL;
1819     }
1820     hmaclen = SHA256_DIGEST_LENGTH;
1821
1822     totcookielen -= startlen;
1823     if (!ossl_assert(totcookielen <= MAX_COOKIE_SIZE - SHA256_DIGEST_LENGTH)) {
1824         SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_F_TLS_CONSTRUCT_STOC_COOKIE,
1825                  ERR_R_INTERNAL_ERROR);
1826         return EXT_RETURN_FAIL;
1827     }
1828
1829     /* HMAC the cookie */
1830     hctx = EVP_MD_CTX_create();
1831     pkey = EVP_PKEY_new_raw_private_key(EVP_PKEY_HMAC, NULL,
1832                                         s->session_ctx->ext.cookie_hmac_key,
1833                                         sizeof(s->session_ctx->ext
1834                                                .cookie_hmac_key));
1835     if (hctx == NULL || pkey == NULL) {
1836         SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_F_TLS_CONSTRUCT_STOC_COOKIE,
1837                  ERR_R_MALLOC_FAILURE);
1838         goto err;
1839     }
1840
1841     if (EVP_DigestSignInit(hctx, NULL, EVP_sha256(), NULL, pkey) <= 0
1842             || EVP_DigestSign(hctx, hmac, &hmaclen, cookie,
1843                               totcookielen) <= 0) {
1844         SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_F_TLS_CONSTRUCT_STOC_COOKIE,
1845                  ERR_R_INTERNAL_ERROR);
1846         goto err;
1847     }
1848
1849     if (!ossl_assert(totcookielen + hmaclen <= MAX_COOKIE_SIZE)) {
1850         SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_F_TLS_CONSTRUCT_STOC_COOKIE,
1851                  ERR_R_INTERNAL_ERROR);
1852         goto err;
1853     }
1854
1855     if (!WPACKET_allocate_bytes(pkt, hmaclen, &hmac2)
1856             || !ossl_assert(hmac == hmac2)
1857             || !ossl_assert(cookie == hmac - totcookielen)
1858             || !WPACKET_close(pkt)
1859             || !WPACKET_close(pkt)) {
1860         SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_F_TLS_CONSTRUCT_STOC_COOKIE,
1861                  ERR_R_INTERNAL_ERROR);
1862         goto err;
1863     }
1864
1865     ret = EXT_RETURN_SENT;
1866
1867  err:
1868     EVP_MD_CTX_free(hctx);
1869     EVP_PKEY_free(pkey);
1870     return ret;
1871 #else
1872     return EXT_RETURN_FAIL;
1873 #endif
1874 }
1875
1876 EXT_RETURN tls_construct_stoc_cryptopro_bug(SSL *s, WPACKET *pkt,
1877                                             unsigned int context, X509 *x,
1878                                             size_t chainidx)
1879 {
1880     const unsigned char cryptopro_ext[36] = {
1881         0xfd, 0xe8,         /* 65000 */
1882         0x00, 0x20,         /* 32 bytes length */
1883         0x30, 0x1e, 0x30, 0x08, 0x06, 0x06, 0x2a, 0x85,
1884         0x03, 0x02, 0x02, 0x09, 0x30, 0x08, 0x06, 0x06,
1885         0x2a, 0x85, 0x03, 0x02, 0x02, 0x16, 0x30, 0x08,
1886         0x06, 0x06, 0x2a, 0x85, 0x03, 0x02, 0x02, 0x17
1887     };
1888
1889     if (((s->s3->tmp.new_cipher->id & 0xFFFF) != 0x80
1890          && (s->s3->tmp.new_cipher->id & 0xFFFF) != 0x81)
1891             || (SSL_get_options(s) & SSL_OP_CRYPTOPRO_TLSEXT_BUG) == 0)
1892         return EXT_RETURN_NOT_SENT;
1893
1894     if (!WPACKET_memcpy(pkt, cryptopro_ext, sizeof(cryptopro_ext))) {
1895         SSLfatal(s, SSL_AD_INTERNAL_ERROR,
1896                  SSL_F_TLS_CONSTRUCT_STOC_CRYPTOPRO_BUG, ERR_R_INTERNAL_ERROR);
1897         return EXT_RETURN_FAIL;
1898     }
1899
1900     return EXT_RETURN_SENT;
1901 }
1902
1903 EXT_RETURN tls_construct_stoc_early_data(SSL *s, WPACKET *pkt,
1904                                          unsigned int context, X509 *x,
1905                                          size_t chainidx)
1906 {
1907     if (context == SSL_EXT_TLS1_3_NEW_SESSION_TICKET) {
1908         if (s->max_early_data == 0)
1909             return EXT_RETURN_NOT_SENT;
1910
1911         if (!WPACKET_put_bytes_u16(pkt, TLSEXT_TYPE_early_data)
1912                 || !WPACKET_start_sub_packet_u16(pkt)
1913                 || !WPACKET_put_bytes_u32(pkt, s->max_early_data)
1914                 || !WPACKET_close(pkt)) {
1915             SSLfatal(s, SSL_AD_INTERNAL_ERROR,
1916                      SSL_F_TLS_CONSTRUCT_STOC_EARLY_DATA, ERR_R_INTERNAL_ERROR);
1917             return EXT_RETURN_FAIL;
1918         }
1919
1920         return EXT_RETURN_SENT;
1921     }
1922
1923     if (s->ext.early_data != SSL_EARLY_DATA_ACCEPTED)
1924         return EXT_RETURN_NOT_SENT;
1925
1926     if (!WPACKET_put_bytes_u16(pkt, TLSEXT_TYPE_early_data)
1927             || !WPACKET_start_sub_packet_u16(pkt)
1928             || !WPACKET_close(pkt)) {
1929         SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_F_TLS_CONSTRUCT_STOC_EARLY_DATA,
1930                  ERR_R_INTERNAL_ERROR);
1931         return EXT_RETURN_FAIL;
1932     }
1933
1934     return EXT_RETURN_SENT;
1935 }
1936
1937 EXT_RETURN tls_construct_stoc_psk(SSL *s, WPACKET *pkt, unsigned int context,
1938                                   X509 *x, size_t chainidx)
1939 {
1940     if (!s->hit)
1941         return EXT_RETURN_NOT_SENT;
1942
1943     if (!WPACKET_put_bytes_u16(pkt, TLSEXT_TYPE_psk)
1944             || !WPACKET_start_sub_packet_u16(pkt)
1945             || !WPACKET_put_bytes_u16(pkt, s->session->ext.tick_identity)
1946             || !WPACKET_close(pkt)) {
1947         SSLfatal(s, SSL_AD_INTERNAL_ERROR,
1948                  SSL_F_TLS_CONSTRUCT_STOC_PSK, ERR_R_INTERNAL_ERROR);
1949         return EXT_RETURN_FAIL;
1950     }
1951
1952     return EXT_RETURN_SENT;
1953 }