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