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