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