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