1 /*
2  * Copyright 2016-2021 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     0
16 
17 /*
18  * 2 bytes for packet length, 2 bytes for format version, 2 bytes for
19  * protocol version, 2 bytes for group id, 2 bytes for cipher id, 1 byte for
20  * key_share present flag, 4 bytes for timestamp, 2 bytes for the hashlen,
21  * EVP_MAX_MD_SIZE for transcript hash, 1 byte for app cookie length, app cookie
22  * length bytes, SHA256_DIGEST_LENGTH bytes for the HMAC of the whole thing.
23  */
24 #define MAX_COOKIE_SIZE (2 + 2 + 2 + 2 + 2 + 1 + 4 + 2 + EVP_MAX_MD_SIZE + 1 \
25                          + SSL_COOKIE_LENGTH + SHA256_DIGEST_LENGTH)
26 
27 /*
28  * Message header + 2 bytes for protocol version + number of random bytes +
29  * + 1 byte for legacy session id length + number of bytes in legacy session id
30  * + 2 bytes for ciphersuite + 1 byte for legacy compression
31  * + 2 bytes for extension block length + 6 bytes for key_share extension
32  * + 4 bytes for cookie extension header + the number of bytes in the cookie
33  */
34 #define MAX_HRR_SIZE    (SSL3_HM_HEADER_LENGTH + 2 + SSL3_RANDOM_SIZE + 1 \
35                          + SSL_MAX_SSL_SESSION_ID_LENGTH + 2 + 1 + 2 + 6 + 4 \
36                          + MAX_COOKIE_SIZE)
37 
38 /*
39  * Parse the client's renegotiation binding and abort if it's not right
40  */
41 int tls_parse_ctos_renegotiate(SSL *s, PACKET *pkt, unsigned int context,
42                                X509 *x, size_t chainidx)
43 {
44     unsigned int ilen;
45     const unsigned char *data;
46 
47     /* Parse the length byte */
48     if (!PACKET_get_1(pkt, &ilen)
49         || !PACKET_get_bytes(pkt, &data, ilen)) {
50         SSLfatal(s, SSL_AD_DECODE_ERROR, SSL_F_TLS_PARSE_CTOS_RENEGOTIATE,
51                  SSL_R_RENEGOTIATION_ENCODING_ERR);
52         return 0;
53     }
54 
55     /* Check that the extension matches */
56     if (ilen != s->s3->previous_client_finished_len) {
57         SSLfatal(s, SSL_AD_HANDSHAKE_FAILURE, SSL_F_TLS_PARSE_CTOS_RENEGOTIATE,
58                  SSL_R_RENEGOTIATION_MISMATCH);
59         return 0;
60     }
61 
62     if (memcmp(data, s->s3->previous_client_finished,
63                s->s3->previous_client_finished_len)) {
64         SSLfatal(s, SSL_AD_HANDSHAKE_FAILURE, SSL_F_TLS_PARSE_CTOS_RENEGOTIATE,
65                  SSL_R_RENEGOTIATION_MISMATCH);
66         return 0;
67     }
68 
69     s->s3->send_connection_binding = 1;
70 
71     return 1;
72 }
73 
74 /*-
75  * The servername extension is treated as follows:
76  *
77  * - Only the hostname type is supported with a maximum length of 255.
78  * - The servername is rejected if too long or if it contains zeros,
79  *   in which case an fatal alert is generated.
80  * - The servername field is maintained together with the session cache.
81  * - When a session is resumed, the servername call back invoked in order
82  *   to allow the application to position itself to the right context.
83  * - The servername is acknowledged if it is new for a session or when
84  *   it is identical to a previously used for the same session.
85  *   Applications can control the behaviour.  They can at any time
86  *   set a 'desirable' servername for a new SSL object. This can be the
87  *   case for example with HTTPS when a Host: header field is received and
88  *   a renegotiation is requested. In this case, a possible servername
89  *   presented in the new client hello is only acknowledged if it matches
90  *   the value of the Host: field.
91  * - Applications must  use SSL_OP_NO_SESSION_RESUMPTION_ON_RENEGOTIATION
92  *   if they provide for changing an explicit servername context for the
93  *   session, i.e. when the session has been established with a servername
94  *   extension.
95  * - On session reconnect, the servername extension may be absent.
96  */
97 int tls_parse_ctos_server_name(SSL *s, PACKET *pkt, unsigned int context,
98                                X509 *x, size_t chainidx)
99 {
100     unsigned int servname_type;
101     PACKET sni, hostname;
102 
103     if (!PACKET_as_length_prefixed_2(pkt, &sni)
104         /* ServerNameList must be at least 1 byte long. */
105         || PACKET_remaining(&sni) == 0) {
106         SSLfatal(s, SSL_AD_DECODE_ERROR, SSL_F_TLS_PARSE_CTOS_SERVER_NAME,
107                  SSL_R_BAD_EXTENSION);
108         return 0;
109     }
110 
111     /*
112      * Although the intent was for server_name to be extensible, RFC 4366
113      * was not clear about it; and so OpenSSL among other implementations,
114      * always and only allows a 'host_name' name types.
115      * RFC 6066 corrected the mistake but adding new name types
116      * is nevertheless no longer feasible, so act as if no other
117      * SNI types can exist, to simplify parsing.
118      *
119      * Also note that the RFC permits only one SNI value per type,
120      * i.e., we can only have a single hostname.
121      */
122     if (!PACKET_get_1(&sni, &servname_type)
123         || servname_type != TLSEXT_NAMETYPE_host_name
124         || !PACKET_as_length_prefixed_2(&sni, &hostname)) {
125         SSLfatal(s, SSL_AD_DECODE_ERROR, SSL_F_TLS_PARSE_CTOS_SERVER_NAME,
126                  SSL_R_BAD_EXTENSION);
127         return 0;
128     }
129 
130     /*
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     unsigned long 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_4(&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 = (unsigned long)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, now, 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             now = (uint32_t)time(NULL);
1213             agesec = now - (uint32_t)sess->time;
1214             agems = agesec * (uint32_t)1000;
1215             ticket_age -= sess->ext.tick_age_add;
1216 
1217             /*
1218              * For simplicity we do our age calculations in seconds. If the
1219              * client does it in ms then it could appear that their ticket age
1220              * is longer than ours (our ticket age calculation should always be
1221              * slightly longer than the client's due to the network latency).
1222              * Therefore we add 1000ms to our age calculation to adjust for
1223              * rounding errors.
1224              */
1225             if (id == 0
1226                     && sess->timeout >= (long)agesec
1227                     && agems / (uint32_t)1000 == agesec
1228                     && ticket_age <= agems + 1000
1229                     && ticket_age + TICKET_AGE_ALLOWANCE >= agems + 1000) {
1230                 /*
1231                  * Ticket age is within tolerance and not expired. We allow it
1232                  * for early data
1233                  */
1234                 s->ext.early_data_ok = 1;
1235             }
1236         }
1237 
1238         md = ssl_md(sess->cipher->algorithm2);
1239         if (md != ssl_md(s->s3->tmp.new_cipher->algorithm2)) {
1240             /* The ciphersuite is not compatible with this session. */
1241             SSL_SESSION_free(sess);
1242             sess = NULL;
1243             s->ext.early_data_ok = 0;
1244             s->ext.ticket_expected = 0;
1245             continue;
1246         }
1247         break;
1248     }
1249 
1250     if (sess == NULL)
1251         return 1;
1252 
1253     binderoffset = PACKET_data(pkt) - (const unsigned char *)s->init_buf->data;
1254     hashsize = EVP_MD_size(md);
1255 
1256     if (!PACKET_get_length_prefixed_2(pkt, &binders)) {
1257         SSLfatal(s, SSL_AD_DECODE_ERROR, SSL_F_TLS_PARSE_CTOS_PSK,
1258                  SSL_R_BAD_EXTENSION);
1259         goto err;
1260     }
1261 
1262     for (i = 0; i <= id; i++) {
1263         if (!PACKET_get_length_prefixed_1(&binders, &binder)) {
1264             SSLfatal(s, SSL_AD_DECODE_ERROR, SSL_F_TLS_PARSE_CTOS_PSK,
1265                      SSL_R_BAD_EXTENSION);
1266             goto err;
1267         }
1268     }
1269 
1270     if (PACKET_remaining(&binder) != hashsize) {
1271         SSLfatal(s, SSL_AD_DECODE_ERROR, SSL_F_TLS_PARSE_CTOS_PSK,
1272                  SSL_R_BAD_EXTENSION);
1273         goto err;
1274     }
1275     if (tls_psk_do_binder(s, md, (const unsigned char *)s->init_buf->data,
1276                           binderoffset, PACKET_data(&binder), NULL, sess, 0,
1277                           ext) != 1) {
1278         /* SSLfatal() already called */
1279         goto err;
1280     }
1281 
1282     s->ext.tick_identity = id;
1283 
1284     SSL_SESSION_free(s->session);
1285     s->session = sess;
1286     return 1;
1287 err:
1288     SSL_SESSION_free(sess);
1289     return 0;
1290 }
1291 
1292 int tls_parse_ctos_post_handshake_auth(SSL *s, PACKET *pkt, unsigned int context,
1293                                        X509 *x, size_t chainidx)
1294 {
1295     if (PACKET_remaining(pkt) != 0) {
1296         SSLfatal(s, SSL_AD_DECODE_ERROR, SSL_F_TLS_PARSE_CTOS_POST_HANDSHAKE_AUTH,
1297                  SSL_R_POST_HANDSHAKE_AUTH_ENCODING_ERR);
1298         return 0;
1299     }
1300 
1301     s->post_handshake_auth = SSL_PHA_EXT_RECEIVED;
1302 
1303     return 1;
1304 }
1305 
1306 /*
1307  * Add the server's renegotiation binding
1308  */
1309 EXT_RETURN tls_construct_stoc_renegotiate(SSL *s, WPACKET *pkt,
1310                                           unsigned int context, X509 *x,
1311                                           size_t chainidx)
1312 {
1313     if (!s->s3->send_connection_binding)
1314         return EXT_RETURN_NOT_SENT;
1315 
1316     /* Still add this even if SSL_OP_NO_RENEGOTIATION is set */
1317     if (!WPACKET_put_bytes_u16(pkt, TLSEXT_TYPE_renegotiate)
1318             || !WPACKET_start_sub_packet_u16(pkt)
1319             || !WPACKET_start_sub_packet_u8(pkt)
1320             || !WPACKET_memcpy(pkt, s->s3->previous_client_finished,
1321                                s->s3->previous_client_finished_len)
1322             || !WPACKET_memcpy(pkt, s->s3->previous_server_finished,
1323                                s->s3->previous_server_finished_len)
1324             || !WPACKET_close(pkt)
1325             || !WPACKET_close(pkt)) {
1326         SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_F_TLS_CONSTRUCT_STOC_RENEGOTIATE,
1327                  ERR_R_INTERNAL_ERROR);
1328         return EXT_RETURN_FAIL;
1329     }
1330 
1331     return EXT_RETURN_SENT;
1332 }
1333 
1334 EXT_RETURN tls_construct_stoc_server_name(SSL *s, WPACKET *pkt,
1335                                           unsigned int context, X509 *x,
1336                                           size_t chainidx)
1337 {
1338     if (s->servername_done != 1)
1339         return EXT_RETURN_NOT_SENT;
1340 
1341     /*
1342      * Prior to TLSv1.3 we ignore any SNI in the current handshake if resuming.
1343      * We just use the servername from the initial handshake.
1344      */
1345     if (s->hit && !SSL_IS_TLS13(s))
1346         return EXT_RETURN_NOT_SENT;
1347 
1348     if (!WPACKET_put_bytes_u16(pkt, TLSEXT_TYPE_server_name)
1349             || !WPACKET_put_bytes_u16(pkt, 0)) {
1350         SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_F_TLS_CONSTRUCT_STOC_SERVER_NAME,
1351                  ERR_R_INTERNAL_ERROR);
1352         return EXT_RETURN_FAIL;
1353     }
1354 
1355     return EXT_RETURN_SENT;
1356 }
1357 
1358 /* Add/include the server's max fragment len extension into ServerHello */
1359 EXT_RETURN tls_construct_stoc_maxfragmentlen(SSL *s, WPACKET *pkt,
1360                                              unsigned int context, X509 *x,
1361                                              size_t chainidx)
1362 {
1363     if (!USE_MAX_FRAGMENT_LENGTH_EXT(s->session))
1364         return EXT_RETURN_NOT_SENT;
1365 
1366     /*-
1367      * 4 bytes for this extension type and extension length
1368      * 1 byte for the Max Fragment Length code value.
1369      */
1370     if (!WPACKET_put_bytes_u16(pkt, TLSEXT_TYPE_max_fragment_length)
1371         || !WPACKET_start_sub_packet_u16(pkt)
1372         || !WPACKET_put_bytes_u8(pkt, s->session->ext.max_fragment_len_mode)
1373         || !WPACKET_close(pkt)) {
1374         SSLfatal(s, SSL_AD_INTERNAL_ERROR,
1375                  SSL_F_TLS_CONSTRUCT_STOC_MAXFRAGMENTLEN, ERR_R_INTERNAL_ERROR);
1376         return EXT_RETURN_FAIL;
1377     }
1378 
1379     return EXT_RETURN_SENT;
1380 }
1381 
1382 #ifndef OPENSSL_NO_EC
1383 EXT_RETURN tls_construct_stoc_ec_pt_formats(SSL *s, WPACKET *pkt,
1384                                             unsigned int context, X509 *x,
1385                                             size_t chainidx)
1386 {
1387     unsigned long alg_k = s->s3->tmp.new_cipher->algorithm_mkey;
1388     unsigned long alg_a = s->s3->tmp.new_cipher->algorithm_auth;
1389     int using_ecc = ((alg_k & SSL_kECDHE) || (alg_a & SSL_aECDSA))
1390                     && (s->ext.peer_ecpointformats != NULL);
1391     const unsigned char *plist;
1392     size_t plistlen;
1393 
1394     if (!using_ecc)
1395         return EXT_RETURN_NOT_SENT;
1396 
1397     tls1_get_formatlist(s, &plist, &plistlen);
1398     if (!WPACKET_put_bytes_u16(pkt, TLSEXT_TYPE_ec_point_formats)
1399             || !WPACKET_start_sub_packet_u16(pkt)
1400             || !WPACKET_sub_memcpy_u8(pkt, plist, plistlen)
1401             || !WPACKET_close(pkt)) {
1402         SSLfatal(s, SSL_AD_INTERNAL_ERROR,
1403                  SSL_F_TLS_CONSTRUCT_STOC_EC_PT_FORMATS, ERR_R_INTERNAL_ERROR);
1404         return EXT_RETURN_FAIL;
1405     }
1406 
1407     return EXT_RETURN_SENT;
1408 }
1409 #endif
1410 
1411 #ifndef OPENSSL_NO_EC
1412 EXT_RETURN tls_construct_stoc_supported_groups(SSL *s, WPACKET *pkt,
1413                                                unsigned int context, X509 *x,
1414                                                size_t chainidx)
1415 {
1416     const uint16_t *groups;
1417     size_t numgroups, i, first = 1;
1418 
1419     /* s->s3->group_id is non zero if we accepted a key_share */
1420     if (s->s3->group_id == 0)
1421         return EXT_RETURN_NOT_SENT;
1422 
1423     /* Get our list of supported groups */
1424     tls1_get_supported_groups(s, &groups, &numgroups);
1425     if (numgroups == 0) {
1426         SSLfatal(s, SSL_AD_INTERNAL_ERROR,
1427                  SSL_F_TLS_CONSTRUCT_STOC_SUPPORTED_GROUPS, ERR_R_INTERNAL_ERROR);
1428         return EXT_RETURN_FAIL;
1429     }
1430 
1431     /* Copy group ID if supported */
1432     for (i = 0; i < numgroups; i++) {
1433         uint16_t group = groups[i];
1434 
1435         if (tls_curve_allowed(s, group, SSL_SECOP_CURVE_SUPPORTED)) {
1436             if (first) {
1437                 /*
1438                  * Check if the client is already using our preferred group. If
1439                  * so we don't need to add this extension
1440                  */
1441                 if (s->s3->group_id == group)
1442                     return EXT_RETURN_NOT_SENT;
1443 
1444                 /* Add extension header */
1445                 if (!WPACKET_put_bytes_u16(pkt, TLSEXT_TYPE_supported_groups)
1446                            /* Sub-packet for supported_groups extension */
1447                         || !WPACKET_start_sub_packet_u16(pkt)
1448                         || !WPACKET_start_sub_packet_u16(pkt)) {
1449                     SSLfatal(s, SSL_AD_INTERNAL_ERROR,
1450                              SSL_F_TLS_CONSTRUCT_STOC_SUPPORTED_GROUPS,
1451                              ERR_R_INTERNAL_ERROR);
1452                     return EXT_RETURN_FAIL;
1453                 }
1454 
1455                 first = 0;
1456             }
1457             if (!WPACKET_put_bytes_u16(pkt, group)) {
1458                     SSLfatal(s, SSL_AD_INTERNAL_ERROR,
1459                              SSL_F_TLS_CONSTRUCT_STOC_SUPPORTED_GROUPS,
1460                              ERR_R_INTERNAL_ERROR);
1461                     return EXT_RETURN_FAIL;
1462                 }
1463         }
1464     }
1465 
1466     if (!WPACKET_close(pkt) || !WPACKET_close(pkt)) {
1467         SSLfatal(s, SSL_AD_INTERNAL_ERROR,
1468                  SSL_F_TLS_CONSTRUCT_STOC_SUPPORTED_GROUPS,
1469                  ERR_R_INTERNAL_ERROR);
1470         return EXT_RETURN_FAIL;
1471     }
1472 
1473     return EXT_RETURN_SENT;
1474 }
1475 #endif
1476 
1477 EXT_RETURN tls_construct_stoc_session_ticket(SSL *s, WPACKET *pkt,
1478                                              unsigned int context, X509 *x,
1479                                              size_t chainidx)
1480 {
1481     if (!s->ext.ticket_expected || !tls_use_ticket(s)) {
1482         s->ext.ticket_expected = 0;
1483         return EXT_RETURN_NOT_SENT;
1484     }
1485 
1486     if (!WPACKET_put_bytes_u16(pkt, TLSEXT_TYPE_session_ticket)
1487             || !WPACKET_put_bytes_u16(pkt, 0)) {
1488         SSLfatal(s, SSL_AD_INTERNAL_ERROR,
1489                  SSL_F_TLS_CONSTRUCT_STOC_SESSION_TICKET, ERR_R_INTERNAL_ERROR);
1490         return EXT_RETURN_FAIL;
1491     }
1492 
1493     return EXT_RETURN_SENT;
1494 }
1495 
1496 #ifndef OPENSSL_NO_OCSP
1497 EXT_RETURN tls_construct_stoc_status_request(SSL *s, WPACKET *pkt,
1498                                              unsigned int context, X509 *x,
1499                                              size_t chainidx)
1500 {
1501     /* We don't currently support this extension inside a CertificateRequest */
1502     if (context == SSL_EXT_TLS1_3_CERTIFICATE_REQUEST)
1503         return EXT_RETURN_NOT_SENT;
1504 
1505     if (!s->ext.status_expected)
1506         return EXT_RETURN_NOT_SENT;
1507 
1508     if (SSL_IS_TLS13(s) && chainidx != 0)
1509         return EXT_RETURN_NOT_SENT;
1510 
1511     if (!WPACKET_put_bytes_u16(pkt, TLSEXT_TYPE_status_request)
1512             || !WPACKET_start_sub_packet_u16(pkt)) {
1513         SSLfatal(s, SSL_AD_INTERNAL_ERROR,
1514                  SSL_F_TLS_CONSTRUCT_STOC_STATUS_REQUEST, ERR_R_INTERNAL_ERROR);
1515         return EXT_RETURN_FAIL;
1516     }
1517 
1518     /*
1519      * In TLSv1.3 we include the certificate status itself. In <= TLSv1.2 we
1520      * send back an empty extension, with the certificate status appearing as a
1521      * separate message
1522      */
1523     if (SSL_IS_TLS13(s) && !tls_construct_cert_status_body(s, pkt)) {
1524        /* SSLfatal() already called */
1525        return EXT_RETURN_FAIL;
1526     }
1527     if (!WPACKET_close(pkt)) {
1528         SSLfatal(s, SSL_AD_INTERNAL_ERROR,
1529                  SSL_F_TLS_CONSTRUCT_STOC_STATUS_REQUEST, ERR_R_INTERNAL_ERROR);
1530         return EXT_RETURN_FAIL;
1531     }
1532 
1533     return EXT_RETURN_SENT;
1534 }
1535 #endif
1536 
1537 #ifndef OPENSSL_NO_NEXTPROTONEG
1538 EXT_RETURN tls_construct_stoc_next_proto_neg(SSL *s, WPACKET *pkt,
1539                                              unsigned int context, X509 *x,
1540                                              size_t chainidx)
1541 {
1542     const unsigned char *npa;
1543     unsigned int npalen;
1544     int ret;
1545     int npn_seen = s->s3->npn_seen;
1546 
1547     s->s3->npn_seen = 0;
1548     if (!npn_seen || s->ctx->ext.npn_advertised_cb == NULL)
1549         return EXT_RETURN_NOT_SENT;
1550 
1551     ret = s->ctx->ext.npn_advertised_cb(s, &npa, &npalen,
1552                                         s->ctx->ext.npn_advertised_cb_arg);
1553     if (ret == SSL_TLSEXT_ERR_OK) {
1554         if (!WPACKET_put_bytes_u16(pkt, TLSEXT_TYPE_next_proto_neg)
1555                 || !WPACKET_sub_memcpy_u16(pkt, npa, npalen)) {
1556             SSLfatal(s, SSL_AD_INTERNAL_ERROR,
1557                      SSL_F_TLS_CONSTRUCT_STOC_NEXT_PROTO_NEG,
1558                      ERR_R_INTERNAL_ERROR);
1559             return EXT_RETURN_FAIL;
1560         }
1561         s->s3->npn_seen = 1;
1562     }
1563 
1564     return EXT_RETURN_SENT;
1565 }
1566 #endif
1567 
1568 EXT_RETURN tls_construct_stoc_alpn(SSL *s, WPACKET *pkt, unsigned int context,
1569                                    X509 *x, size_t chainidx)
1570 {
1571     if (s->s3->alpn_selected == NULL)
1572         return EXT_RETURN_NOT_SENT;
1573 
1574     if (!WPACKET_put_bytes_u16(pkt,
1575                 TLSEXT_TYPE_application_layer_protocol_negotiation)
1576             || !WPACKET_start_sub_packet_u16(pkt)
1577             || !WPACKET_start_sub_packet_u16(pkt)
1578             || !WPACKET_sub_memcpy_u8(pkt, s->s3->alpn_selected,
1579                                       s->s3->alpn_selected_len)
1580             || !WPACKET_close(pkt)
1581             || !WPACKET_close(pkt)) {
1582         SSLfatal(s, SSL_AD_INTERNAL_ERROR,
1583                  SSL_F_TLS_CONSTRUCT_STOC_ALPN, ERR_R_INTERNAL_ERROR);
1584         return EXT_RETURN_FAIL;
1585     }
1586 
1587     return EXT_RETURN_SENT;
1588 }
1589 
1590 #ifndef OPENSSL_NO_SRTP
1591 EXT_RETURN tls_construct_stoc_use_srtp(SSL *s, WPACKET *pkt,
1592                                        unsigned int context, X509 *x,
1593                                        size_t chainidx)
1594 {
1595     if (s->srtp_profile == NULL)
1596         return EXT_RETURN_NOT_SENT;
1597 
1598     if (!WPACKET_put_bytes_u16(pkt, TLSEXT_TYPE_use_srtp)
1599             || !WPACKET_start_sub_packet_u16(pkt)
1600             || !WPACKET_put_bytes_u16(pkt, 2)
1601             || !WPACKET_put_bytes_u16(pkt, s->srtp_profile->id)
1602             || !WPACKET_put_bytes_u8(pkt, 0)
1603             || !WPACKET_close(pkt)) {
1604         SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_F_TLS_CONSTRUCT_STOC_USE_SRTP,
1605                  ERR_R_INTERNAL_ERROR);
1606         return EXT_RETURN_FAIL;
1607     }
1608 
1609     return EXT_RETURN_SENT;
1610 }
1611 #endif
1612 
1613 EXT_RETURN tls_construct_stoc_etm(SSL *s, WPACKET *pkt, unsigned int context,
1614                                   X509 *x, size_t chainidx)
1615 {
1616     if (!s->ext.use_etm)
1617         return EXT_RETURN_NOT_SENT;
1618 
1619     /*
1620      * Don't use encrypt_then_mac if AEAD or RC4 might want to disable
1621      * for other cases too.
1622      */
1623     if (s->s3->tmp.new_cipher->algorithm_mac == SSL_AEAD
1624         || s->s3->tmp.new_cipher->algorithm_enc == SSL_RC4
1625         || s->s3->tmp.new_cipher->algorithm_enc == SSL_eGOST2814789CNT
1626         || s->s3->tmp.new_cipher->algorithm_enc == SSL_eGOST2814789CNT12) {
1627         s->ext.use_etm = 0;
1628         return EXT_RETURN_NOT_SENT;
1629     }
1630 
1631     if (!WPACKET_put_bytes_u16(pkt, TLSEXT_TYPE_encrypt_then_mac)
1632             || !WPACKET_put_bytes_u16(pkt, 0)) {
1633         SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_F_TLS_CONSTRUCT_STOC_ETM,
1634                  ERR_R_INTERNAL_ERROR);
1635         return EXT_RETURN_FAIL;
1636     }
1637 
1638     return EXT_RETURN_SENT;
1639 }
1640 
1641 EXT_RETURN tls_construct_stoc_ems(SSL *s, WPACKET *pkt, unsigned int context,
1642                                   X509 *x, size_t chainidx)
1643 {
1644     if ((s->s3->flags & TLS1_FLAGS_RECEIVED_EXTMS) == 0)
1645         return EXT_RETURN_NOT_SENT;
1646 
1647     if (!WPACKET_put_bytes_u16(pkt, TLSEXT_TYPE_extended_master_secret)
1648             || !WPACKET_put_bytes_u16(pkt, 0)) {
1649         SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_F_TLS_CONSTRUCT_STOC_EMS,
1650                  ERR_R_INTERNAL_ERROR);
1651         return EXT_RETURN_FAIL;
1652     }
1653 
1654     return EXT_RETURN_SENT;
1655 }
1656 
1657 EXT_RETURN tls_construct_stoc_supported_versions(SSL *s, WPACKET *pkt,
1658                                                  unsigned int context, X509 *x,
1659                                                  size_t chainidx)
1660 {
1661     if (!ossl_assert(SSL_IS_TLS13(s))) {
1662         SSLfatal(s, SSL_AD_INTERNAL_ERROR,
1663                  SSL_F_TLS_CONSTRUCT_STOC_SUPPORTED_VERSIONS,
1664                  ERR_R_INTERNAL_ERROR);
1665         return EXT_RETURN_FAIL;
1666     }
1667 
1668     if (!WPACKET_put_bytes_u16(pkt, TLSEXT_TYPE_supported_versions)
1669             || !WPACKET_start_sub_packet_u16(pkt)
1670             || !WPACKET_put_bytes_u16(pkt, s->version)
1671             || !WPACKET_close(pkt)) {
1672         SSLfatal(s, SSL_AD_INTERNAL_ERROR,
1673                  SSL_F_TLS_CONSTRUCT_STOC_SUPPORTED_VERSIONS,
1674                  ERR_R_INTERNAL_ERROR);
1675         return EXT_RETURN_FAIL;
1676     }
1677 
1678     return EXT_RETURN_SENT;
1679 }
1680 
1681 EXT_RETURN tls_construct_stoc_key_share(SSL *s, WPACKET *pkt,
1682                                         unsigned int context, X509 *x,
1683                                         size_t chainidx)
1684 {
1685 #ifndef OPENSSL_NO_TLS1_3
1686     unsigned char *encodedPoint;
1687     size_t encoded_pt_len = 0;
1688     EVP_PKEY *ckey = s->s3->peer_tmp, *skey = NULL;
1689 
1690     if (s->hello_retry_request == SSL_HRR_PENDING) {
1691         if (ckey != NULL) {
1692             /* Original key_share was acceptable so don't ask for another one */
1693             return EXT_RETURN_NOT_SENT;
1694         }
1695         if (!WPACKET_put_bytes_u16(pkt, TLSEXT_TYPE_key_share)
1696                 || !WPACKET_start_sub_packet_u16(pkt)
1697                 || !WPACKET_put_bytes_u16(pkt, s->s3->group_id)
1698                 || !WPACKET_close(pkt)) {
1699             SSLfatal(s, SSL_AD_INTERNAL_ERROR,
1700                      SSL_F_TLS_CONSTRUCT_STOC_KEY_SHARE,
1701                      ERR_R_INTERNAL_ERROR);
1702             return EXT_RETURN_FAIL;
1703         }
1704 
1705         return EXT_RETURN_SENT;
1706     }
1707 
1708     if (ckey == NULL) {
1709         /* No key_share received from client - must be resuming */
1710         if (!s->hit || !tls13_generate_handshake_secret(s, NULL, 0)) {
1711             SSLfatal(s, SSL_AD_INTERNAL_ERROR,
1712                      SSL_F_TLS_CONSTRUCT_STOC_KEY_SHARE, ERR_R_INTERNAL_ERROR);
1713             return EXT_RETURN_FAIL;
1714         }
1715         return EXT_RETURN_NOT_SENT;
1716     }
1717     if (s->hit && (s->ext.psk_kex_mode & TLSEXT_KEX_MODE_FLAG_KE_DHE) == 0) {
1718         /*
1719          * PSK ('hit') and explicitly not doing DHE (if the client sent the
1720          * DHE option we always take it); don't send key share.
1721          */
1722         return EXT_RETURN_NOT_SENT;
1723     }
1724 
1725     if (!WPACKET_put_bytes_u16(pkt, TLSEXT_TYPE_key_share)
1726             || !WPACKET_start_sub_packet_u16(pkt)
1727             || !WPACKET_put_bytes_u16(pkt, s->s3->group_id)) {
1728         SSLfatal(s, SSL_AD_INTERNAL_ERROR,
1729                  SSL_F_TLS_CONSTRUCT_STOC_KEY_SHARE, ERR_R_INTERNAL_ERROR);
1730         return EXT_RETURN_FAIL;
1731     }
1732 
1733     skey = ssl_generate_pkey(ckey);
1734     if (skey == NULL) {
1735         SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_F_TLS_CONSTRUCT_STOC_KEY_SHARE,
1736                  ERR_R_MALLOC_FAILURE);
1737         return EXT_RETURN_FAIL;
1738     }
1739 
1740     /* Generate encoding of server key */
1741     encoded_pt_len = EVP_PKEY_get1_tls_encodedpoint(skey, &encodedPoint);
1742     if (encoded_pt_len == 0) {
1743         SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_F_TLS_CONSTRUCT_STOC_KEY_SHARE,
1744                  ERR_R_EC_LIB);
1745         EVP_PKEY_free(skey);
1746         return EXT_RETURN_FAIL;
1747     }
1748 
1749     if (!WPACKET_sub_memcpy_u16(pkt, encodedPoint, encoded_pt_len)
1750             || !WPACKET_close(pkt)) {
1751         SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_F_TLS_CONSTRUCT_STOC_KEY_SHARE,
1752                  ERR_R_INTERNAL_ERROR);
1753         EVP_PKEY_free(skey);
1754         OPENSSL_free(encodedPoint);
1755         return EXT_RETURN_FAIL;
1756     }
1757     OPENSSL_free(encodedPoint);
1758 
1759     /* This causes the crypto state to be updated based on the derived keys */
1760     s->s3->tmp.pkey = skey;
1761     if (ssl_derive(s, skey, ckey, 1) == 0) {
1762         /* SSLfatal() already called */
1763         return EXT_RETURN_FAIL;
1764     }
1765     return EXT_RETURN_SENT;
1766 #else
1767     return EXT_RETURN_FAIL;
1768 #endif
1769 }
1770 
1771 EXT_RETURN tls_construct_stoc_cookie(SSL *s, WPACKET *pkt, unsigned int context,
1772                                      X509 *x, size_t chainidx)
1773 {
1774 #ifndef OPENSSL_NO_TLS1_3
1775     unsigned char *hashval1, *hashval2, *appcookie1, *appcookie2, *cookie;
1776     unsigned char *hmac, *hmac2;
1777     size_t startlen, ciphlen, totcookielen, hashlen, hmaclen, appcookielen;
1778     EVP_MD_CTX *hctx;
1779     EVP_PKEY *pkey;
1780     int ret = EXT_RETURN_FAIL;
1781 
1782     if ((s->s3->flags & TLS1_FLAGS_STATELESS) == 0)
1783         return EXT_RETURN_NOT_SENT;
1784 
1785     if (s->ctx->gen_stateless_cookie_cb == NULL) {
1786         SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_F_TLS_CONSTRUCT_STOC_COOKIE,
1787                  SSL_R_NO_COOKIE_CALLBACK_SET);
1788         return EXT_RETURN_FAIL;
1789     }
1790 
1791     if (!WPACKET_put_bytes_u16(pkt, TLSEXT_TYPE_cookie)
1792             || !WPACKET_start_sub_packet_u16(pkt)
1793             || !WPACKET_start_sub_packet_u16(pkt)
1794             || !WPACKET_get_total_written(pkt, &startlen)
1795             || !WPACKET_reserve_bytes(pkt, MAX_COOKIE_SIZE, &cookie)
1796             || !WPACKET_put_bytes_u16(pkt, COOKIE_STATE_FORMAT_VERSION)
1797             || !WPACKET_put_bytes_u16(pkt, TLS1_3_VERSION)
1798             || !WPACKET_put_bytes_u16(pkt, s->s3->group_id)
1799             || !s->method->put_cipher_by_char(s->s3->tmp.new_cipher, pkt,
1800                                               &ciphlen)
1801                /* Is there a key_share extension present in this HRR? */
1802             || !WPACKET_put_bytes_u8(pkt, s->s3->peer_tmp == NULL)
1803             || !WPACKET_put_bytes_u32(pkt, (unsigned int)time(NULL))
1804             || !WPACKET_start_sub_packet_u16(pkt)
1805             || !WPACKET_reserve_bytes(pkt, EVP_MAX_MD_SIZE, &hashval1)) {
1806         SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_F_TLS_CONSTRUCT_STOC_COOKIE,
1807                  ERR_R_INTERNAL_ERROR);
1808         return EXT_RETURN_FAIL;
1809     }
1810 
1811     /*
1812      * Get the hash of the initial ClientHello. ssl_handshake_hash() operates
1813      * on raw buffers, so we first reserve sufficient bytes (above) and then
1814      * subsequently allocate them (below)
1815      */
1816     if (!ssl3_digest_cached_records(s, 0)
1817             || !ssl_handshake_hash(s, hashval1, EVP_MAX_MD_SIZE, &hashlen)) {
1818         /* SSLfatal() already called */
1819         return EXT_RETURN_FAIL;
1820     }
1821 
1822     if (!WPACKET_allocate_bytes(pkt, hashlen, &hashval2)
1823             || !ossl_assert(hashval1 == hashval2)
1824             || !WPACKET_close(pkt)
1825             || !WPACKET_start_sub_packet_u8(pkt)
1826             || !WPACKET_reserve_bytes(pkt, SSL_COOKIE_LENGTH, &appcookie1)) {
1827         SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_F_TLS_CONSTRUCT_STOC_COOKIE,
1828                  ERR_R_INTERNAL_ERROR);
1829         return EXT_RETURN_FAIL;
1830     }
1831 
1832     /* Generate the application cookie */
1833     if (s->ctx->gen_stateless_cookie_cb(s, appcookie1, &appcookielen) == 0) {
1834         SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_F_TLS_CONSTRUCT_STOC_COOKIE,
1835                  SSL_R_COOKIE_GEN_CALLBACK_FAILURE);
1836         return EXT_RETURN_FAIL;
1837     }
1838 
1839     if (!WPACKET_allocate_bytes(pkt, appcookielen, &appcookie2)
1840             || !ossl_assert(appcookie1 == appcookie2)
1841             || !WPACKET_close(pkt)
1842             || !WPACKET_get_total_written(pkt, &totcookielen)
1843             || !WPACKET_reserve_bytes(pkt, SHA256_DIGEST_LENGTH, &hmac)) {
1844         SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_F_TLS_CONSTRUCT_STOC_COOKIE,
1845                  ERR_R_INTERNAL_ERROR);
1846         return EXT_RETURN_FAIL;
1847     }
1848     hmaclen = SHA256_DIGEST_LENGTH;
1849 
1850     totcookielen -= startlen;
1851     if (!ossl_assert(totcookielen <= MAX_COOKIE_SIZE - SHA256_DIGEST_LENGTH)) {
1852         SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_F_TLS_CONSTRUCT_STOC_COOKIE,
1853                  ERR_R_INTERNAL_ERROR);
1854         return EXT_RETURN_FAIL;
1855     }
1856 
1857     /* HMAC the cookie */
1858     hctx = EVP_MD_CTX_create();
1859     pkey = EVP_PKEY_new_raw_private_key(EVP_PKEY_HMAC, NULL,
1860                                         s->session_ctx->ext.cookie_hmac_key,
1861                                         sizeof(s->session_ctx->ext
1862                                                .cookie_hmac_key));
1863     if (hctx == NULL || pkey == NULL) {
1864         SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_F_TLS_CONSTRUCT_STOC_COOKIE,
1865                  ERR_R_MALLOC_FAILURE);
1866         goto err;
1867     }
1868 
1869     if (EVP_DigestSignInit(hctx, NULL, EVP_sha256(), NULL, pkey) <= 0
1870             || EVP_DigestSign(hctx, hmac, &hmaclen, cookie,
1871                               totcookielen) <= 0) {
1872         SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_F_TLS_CONSTRUCT_STOC_COOKIE,
1873                  ERR_R_INTERNAL_ERROR);
1874         goto err;
1875     }
1876 
1877     if (!ossl_assert(totcookielen + hmaclen <= MAX_COOKIE_SIZE)) {
1878         SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_F_TLS_CONSTRUCT_STOC_COOKIE,
1879                  ERR_R_INTERNAL_ERROR);
1880         goto err;
1881     }
1882 
1883     if (!WPACKET_allocate_bytes(pkt, hmaclen, &hmac2)
1884             || !ossl_assert(hmac == hmac2)
1885             || !ossl_assert(cookie == hmac - totcookielen)
1886             || !WPACKET_close(pkt)
1887             || !WPACKET_close(pkt)) {
1888         SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_F_TLS_CONSTRUCT_STOC_COOKIE,
1889                  ERR_R_INTERNAL_ERROR);
1890         goto err;
1891     }
1892 
1893     ret = EXT_RETURN_SENT;
1894 
1895  err:
1896     EVP_MD_CTX_free(hctx);
1897     EVP_PKEY_free(pkey);
1898     return ret;
1899 #else
1900     return EXT_RETURN_FAIL;
1901 #endif
1902 }
1903 
1904 EXT_RETURN tls_construct_stoc_cryptopro_bug(SSL *s, WPACKET *pkt,
1905                                             unsigned int context, X509 *x,
1906                                             size_t chainidx)
1907 {
1908     const unsigned char cryptopro_ext[36] = {
1909         0xfd, 0xe8,         /* 65000 */
1910         0x00, 0x20,         /* 32 bytes length */
1911         0x30, 0x1e, 0x30, 0x08, 0x06, 0x06, 0x2a, 0x85,
1912         0x03, 0x02, 0x02, 0x09, 0x30, 0x08, 0x06, 0x06,
1913         0x2a, 0x85, 0x03, 0x02, 0x02, 0x16, 0x30, 0x08,
1914         0x06, 0x06, 0x2a, 0x85, 0x03, 0x02, 0x02, 0x17
1915     };
1916 
1917     if (((s->s3->tmp.new_cipher->id & 0xFFFF) != 0x80
1918          && (s->s3->tmp.new_cipher->id & 0xFFFF) != 0x81)
1919             || (SSL_get_options(s) & SSL_OP_CRYPTOPRO_TLSEXT_BUG) == 0)
1920         return EXT_RETURN_NOT_SENT;
1921 
1922     if (!WPACKET_memcpy(pkt, cryptopro_ext, sizeof(cryptopro_ext))) {
1923         SSLfatal(s, SSL_AD_INTERNAL_ERROR,
1924                  SSL_F_TLS_CONSTRUCT_STOC_CRYPTOPRO_BUG, ERR_R_INTERNAL_ERROR);
1925         return EXT_RETURN_FAIL;
1926     }
1927 
1928     return EXT_RETURN_SENT;
1929 }
1930 
1931 EXT_RETURN tls_construct_stoc_early_data(SSL *s, WPACKET *pkt,
1932                                          unsigned int context, X509 *x,
1933                                          size_t chainidx)
1934 {
1935     if (context == SSL_EXT_TLS1_3_NEW_SESSION_TICKET) {
1936         if (s->max_early_data == 0)
1937             return EXT_RETURN_NOT_SENT;
1938 
1939         if (!WPACKET_put_bytes_u16(pkt, TLSEXT_TYPE_early_data)
1940                 || !WPACKET_start_sub_packet_u16(pkt)
1941                 || !WPACKET_put_bytes_u32(pkt, s->max_early_data)
1942                 || !WPACKET_close(pkt)) {
1943             SSLfatal(s, SSL_AD_INTERNAL_ERROR,
1944                      SSL_F_TLS_CONSTRUCT_STOC_EARLY_DATA, ERR_R_INTERNAL_ERROR);
1945             return EXT_RETURN_FAIL;
1946         }
1947 
1948         return EXT_RETURN_SENT;
1949     }
1950 
1951     if (s->ext.early_data != SSL_EARLY_DATA_ACCEPTED)
1952         return EXT_RETURN_NOT_SENT;
1953 
1954     if (!WPACKET_put_bytes_u16(pkt, TLSEXT_TYPE_early_data)
1955             || !WPACKET_start_sub_packet_u16(pkt)
1956             || !WPACKET_close(pkt)) {
1957         SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_F_TLS_CONSTRUCT_STOC_EARLY_DATA,
1958                  ERR_R_INTERNAL_ERROR);
1959         return EXT_RETURN_FAIL;
1960     }
1961 
1962     return EXT_RETURN_SENT;
1963 }
1964 
1965 EXT_RETURN tls_construct_stoc_psk(SSL *s, WPACKET *pkt, unsigned int context,
1966                                   X509 *x, size_t chainidx)
1967 {
1968     if (!s->hit)
1969         return EXT_RETURN_NOT_SENT;
1970 
1971     if (!WPACKET_put_bytes_u16(pkt, TLSEXT_TYPE_psk)
1972             || !WPACKET_start_sub_packet_u16(pkt)
1973             || !WPACKET_put_bytes_u16(pkt, s->ext.tick_identity)
1974             || !WPACKET_close(pkt)) {
1975         SSLfatal(s, SSL_AD_INTERNAL_ERROR,
1976                  SSL_F_TLS_CONSTRUCT_STOC_PSK, ERR_R_INTERNAL_ERROR);
1977         return EXT_RETURN_FAIL;
1978     }
1979 
1980     return EXT_RETURN_SENT;
1981 }
1982