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