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