Use EVP_DigestSignInit_ex and EVP_DigestVerifyInit_ex in libssl
[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(s, 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_ex(hctx, NULL, "SHA2-256", s->ctx->propq, pkey,
784                               s->ctx->libctx) <= 0
785             || EVP_DigestSign(hctx, hmac, &hmaclen, data,
786                               rawlen - SHA256_DIGEST_LENGTH) <= 0
787             || hmaclen != SHA256_DIGEST_LENGTH) {
788         EVP_MD_CTX_free(hctx);
789         EVP_PKEY_free(pkey);
790         SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_F_TLS_PARSE_CTOS_COOKIE,
791                  ERR_R_INTERNAL_ERROR);
792         return 0;
793     }
794
795     EVP_MD_CTX_free(hctx);
796     EVP_PKEY_free(pkey);
797
798     if (CRYPTO_memcmp(hmac, mdin, SHA256_DIGEST_LENGTH) != 0) {
799         SSLfatal(s, SSL_AD_ILLEGAL_PARAMETER, SSL_F_TLS_PARSE_CTOS_COOKIE,
800                  SSL_R_COOKIE_MISMATCH);
801         return 0;
802     }
803
804     if (!PACKET_get_net_2(&cookie, &format)) {
805         SSLfatal(s, SSL_AD_DECODE_ERROR, SSL_F_TLS_PARSE_CTOS_COOKIE,
806                  SSL_R_LENGTH_MISMATCH);
807         return 0;
808     }
809     /* Check the cookie format is something we recognise. Ignore it if not */
810     if (format != COOKIE_STATE_FORMAT_VERSION)
811         return 1;
812
813     /*
814      * The rest of these checks really shouldn't fail since we have verified the
815      * HMAC above.
816      */
817
818     /* Check the version number is sane */
819     if (!PACKET_get_net_2(&cookie, &version)) {
820         SSLfatal(s, SSL_AD_DECODE_ERROR, SSL_F_TLS_PARSE_CTOS_COOKIE,
821                  SSL_R_LENGTH_MISMATCH);
822         return 0;
823     }
824     if (version != TLS1_3_VERSION) {
825         SSLfatal(s, SSL_AD_ILLEGAL_PARAMETER, SSL_F_TLS_PARSE_CTOS_COOKIE,
826                  SSL_R_BAD_PROTOCOL_VERSION_NUMBER);
827         return 0;
828     }
829
830     if (!PACKET_get_net_2(&cookie, &group_id)) {
831         SSLfatal(s, SSL_AD_DECODE_ERROR, SSL_F_TLS_PARSE_CTOS_COOKIE,
832                  SSL_R_LENGTH_MISMATCH);
833         return 0;
834     }
835
836     ciphdata = PACKET_data(&cookie);
837     if (!PACKET_forward(&cookie, 2)) {
838         SSLfatal(s, SSL_AD_DECODE_ERROR, SSL_F_TLS_PARSE_CTOS_COOKIE,
839                  SSL_R_LENGTH_MISMATCH);
840         return 0;
841     }
842     if (group_id != s->s3.group_id
843             || s->s3.tmp.new_cipher
844                != ssl_get_cipher_by_char(s, ciphdata, 0)) {
845         /*
846          * We chose a different cipher or group id this time around to what is
847          * in the cookie. Something must have changed.
848          */
849         SSLfatal(s, SSL_AD_ILLEGAL_PARAMETER, SSL_F_TLS_PARSE_CTOS_COOKIE,
850                  SSL_R_BAD_CIPHER);
851         return 0;
852     }
853
854     if (!PACKET_get_1(&cookie, &key_share)
855             || !PACKET_get_net_4(&cookie, &tm)
856             || !PACKET_get_length_prefixed_2(&cookie, &chhash)
857             || !PACKET_get_length_prefixed_1(&cookie, &appcookie)
858             || PACKET_remaining(&cookie) != SHA256_DIGEST_LENGTH) {
859         SSLfatal(s, SSL_AD_DECODE_ERROR, SSL_F_TLS_PARSE_CTOS_COOKIE,
860                  SSL_R_LENGTH_MISMATCH);
861         return 0;
862     }
863
864     /* We tolerate a cookie age of up to 10 minutes (= 60 * 10 seconds) */
865     now = (unsigned long)time(NULL);
866     if (tm > now || (now - tm) > 600) {
867         /* Cookie is stale. Ignore it */
868         return 1;
869     }
870
871     /* Verify the app cookie */
872     if (s->ctx->verify_stateless_cookie_cb(s, PACKET_data(&appcookie),
873                                      PACKET_remaining(&appcookie)) == 0) {
874         SSLfatal(s, SSL_AD_ILLEGAL_PARAMETER, SSL_F_TLS_PARSE_CTOS_COOKIE,
875                  SSL_R_COOKIE_MISMATCH);
876         return 0;
877     }
878
879     /*
880      * Reconstruct the HRR that we would have sent in response to the original
881      * ClientHello so we can add it to the transcript hash.
882      * Note: This won't work with custom HRR extensions
883      */
884     if (!WPACKET_init_static_len(&hrrpkt, hrr, sizeof(hrr), 0)) {
885         SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_F_TLS_PARSE_CTOS_COOKIE,
886                  ERR_R_INTERNAL_ERROR);
887         return 0;
888     }
889     if (!WPACKET_put_bytes_u8(&hrrpkt, SSL3_MT_SERVER_HELLO)
890             || !WPACKET_start_sub_packet_u24(&hrrpkt)
891             || !WPACKET_put_bytes_u16(&hrrpkt, TLS1_2_VERSION)
892             || !WPACKET_memcpy(&hrrpkt, hrrrandom, SSL3_RANDOM_SIZE)
893             || !WPACKET_sub_memcpy_u8(&hrrpkt, s->tmp_session_id,
894                                       s->tmp_session_id_len)
895             || !s->method->put_cipher_by_char(s->s3.tmp.new_cipher, &hrrpkt,
896                                               &ciphlen)
897             || !WPACKET_put_bytes_u8(&hrrpkt, 0)
898             || !WPACKET_start_sub_packet_u16(&hrrpkt)) {
899         WPACKET_cleanup(&hrrpkt);
900         SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_F_TLS_PARSE_CTOS_COOKIE,
901                  ERR_R_INTERNAL_ERROR);
902         return 0;
903     }
904     if (!WPACKET_put_bytes_u16(&hrrpkt, TLSEXT_TYPE_supported_versions)
905             || !WPACKET_start_sub_packet_u16(&hrrpkt)
906             || !WPACKET_put_bytes_u16(&hrrpkt, s->version)
907             || !WPACKET_close(&hrrpkt)) {
908         WPACKET_cleanup(&hrrpkt);
909         SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_F_TLS_PARSE_CTOS_COOKIE,
910                  ERR_R_INTERNAL_ERROR);
911         return 0;
912     }
913     if (key_share) {
914         if (!WPACKET_put_bytes_u16(&hrrpkt, TLSEXT_TYPE_key_share)
915                 || !WPACKET_start_sub_packet_u16(&hrrpkt)
916                 || !WPACKET_put_bytes_u16(&hrrpkt, s->s3.group_id)
917                 || !WPACKET_close(&hrrpkt)) {
918             WPACKET_cleanup(&hrrpkt);
919             SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_F_TLS_PARSE_CTOS_COOKIE,
920                      ERR_R_INTERNAL_ERROR);
921             return 0;
922         }
923     }
924     if (!WPACKET_put_bytes_u16(&hrrpkt, TLSEXT_TYPE_cookie)
925             || !WPACKET_start_sub_packet_u16(&hrrpkt)
926             || !WPACKET_sub_memcpy_u16(&hrrpkt, data, rawlen)
927             || !WPACKET_close(&hrrpkt) /* cookie extension */
928             || !WPACKET_close(&hrrpkt) /* extension block */
929             || !WPACKET_close(&hrrpkt) /* message */
930             || !WPACKET_get_total_written(&hrrpkt, &hrrlen)
931             || !WPACKET_finish(&hrrpkt)) {
932         WPACKET_cleanup(&hrrpkt);
933         SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_F_TLS_PARSE_CTOS_COOKIE,
934                  ERR_R_INTERNAL_ERROR);
935         return 0;
936     }
937
938     /* Reconstruct the transcript hash */
939     if (!create_synthetic_message_hash(s, PACKET_data(&chhash),
940                                        PACKET_remaining(&chhash), hrr,
941                                        hrrlen)) {
942         /* SSLfatal() already called */
943         return 0;
944     }
945
946     /* Act as if this ClientHello came after a HelloRetryRequest */
947     s->hello_retry_request = 1;
948
949     s->ext.cookieok = 1;
950 #endif
951
952     return 1;
953 }
954
955 #if !defined(OPENSSL_NO_EC) || !defined(OPENSSL_NO_DH)
956 int tls_parse_ctos_supported_groups(SSL *s, PACKET *pkt, unsigned int context,
957                                     X509 *x, size_t chainidx)
958 {
959     PACKET supported_groups_list;
960
961     /* Each group is 2 bytes and we must have at least 1. */
962     if (!PACKET_as_length_prefixed_2(pkt, &supported_groups_list)
963             || PACKET_remaining(&supported_groups_list) == 0
964             || (PACKET_remaining(&supported_groups_list) % 2) != 0) {
965         SSLfatal(s, SSL_AD_DECODE_ERROR,
966                  SSL_F_TLS_PARSE_CTOS_SUPPORTED_GROUPS, SSL_R_BAD_EXTENSION);
967         return 0;
968     }
969
970     if (!s->hit || SSL_IS_TLS13(s)) {
971         OPENSSL_free(s->ext.peer_supportedgroups);
972         s->ext.peer_supportedgroups = NULL;
973         s->ext.peer_supportedgroups_len = 0;
974         if (!tls1_save_u16(&supported_groups_list,
975                            &s->ext.peer_supportedgroups,
976                            &s->ext.peer_supportedgroups_len)) {
977             SSLfatal(s, SSL_AD_INTERNAL_ERROR,
978                      SSL_F_TLS_PARSE_CTOS_SUPPORTED_GROUPS,
979                      ERR_R_INTERNAL_ERROR);
980             return 0;
981         }
982     }
983
984     return 1;
985 }
986 #endif
987
988 int tls_parse_ctos_ems(SSL *s, PACKET *pkt, unsigned int context, X509 *x,
989                        size_t chainidx)
990 {
991     /* The extension must always be empty */
992     if (PACKET_remaining(pkt) != 0) {
993         SSLfatal(s, SSL_AD_DECODE_ERROR,
994                  SSL_F_TLS_PARSE_CTOS_EMS, SSL_R_BAD_EXTENSION);
995         return 0;
996     }
997
998     if (s->options & SSL_OP_NO_EXTENDED_MASTER_SECRET)
999         return 1;
1000
1001     s->s3.flags |= TLS1_FLAGS_RECEIVED_EXTMS;
1002
1003     return 1;
1004 }
1005
1006
1007 int tls_parse_ctos_early_data(SSL *s, PACKET *pkt, unsigned int context,
1008                               X509 *x, size_t chainidx)
1009 {
1010     if (PACKET_remaining(pkt) != 0) {
1011         SSLfatal(s, SSL_AD_DECODE_ERROR,
1012                  SSL_F_TLS_PARSE_CTOS_EARLY_DATA, SSL_R_BAD_EXTENSION);
1013         return 0;
1014     }
1015
1016     if (s->hello_retry_request != SSL_HRR_NONE) {
1017         SSLfatal(s, SSL_AD_ILLEGAL_PARAMETER,
1018                  SSL_F_TLS_PARSE_CTOS_EARLY_DATA, SSL_R_BAD_EXTENSION);
1019         return 0;
1020     }
1021
1022     return 1;
1023 }
1024
1025 static SSL_TICKET_STATUS tls_get_stateful_ticket(SSL *s, PACKET *tick,
1026                                                  SSL_SESSION **sess)
1027 {
1028     SSL_SESSION *tmpsess = NULL;
1029
1030     s->ext.ticket_expected = 1;
1031
1032     switch (PACKET_remaining(tick)) {
1033         case 0:
1034             return SSL_TICKET_EMPTY;
1035
1036         case SSL_MAX_SSL_SESSION_ID_LENGTH:
1037             break;
1038
1039         default:
1040             return SSL_TICKET_NO_DECRYPT;
1041     }
1042
1043     tmpsess = lookup_sess_in_cache(s, PACKET_data(tick),
1044                                    SSL_MAX_SSL_SESSION_ID_LENGTH);
1045
1046     if (tmpsess == NULL)
1047         return SSL_TICKET_NO_DECRYPT;
1048
1049     *sess = tmpsess;
1050     return SSL_TICKET_SUCCESS;
1051 }
1052
1053 int tls_parse_ctos_psk(SSL *s, PACKET *pkt, unsigned int context, X509 *x,
1054                        size_t chainidx)
1055 {
1056     PACKET identities, binders, binder;
1057     size_t binderoffset, hashsize;
1058     SSL_SESSION *sess = NULL;
1059     unsigned int id, i, ext = 0;
1060     const EVP_MD *md = NULL;
1061
1062     /*
1063      * If we have no PSK kex mode that we recognise then we can't resume so
1064      * ignore this extension
1065      */
1066     if ((s->ext.psk_kex_mode
1067             & (TLSEXT_KEX_MODE_FLAG_KE | TLSEXT_KEX_MODE_FLAG_KE_DHE)) == 0)
1068         return 1;
1069
1070     if (!PACKET_get_length_prefixed_2(pkt, &identities)) {
1071         SSLfatal(s, SSL_AD_DECODE_ERROR,
1072                  SSL_F_TLS_PARSE_CTOS_PSK, SSL_R_BAD_EXTENSION);
1073         return 0;
1074     }
1075
1076     s->ext.ticket_expected = 0;
1077     for (id = 0; PACKET_remaining(&identities) != 0; id++) {
1078         PACKET identity;
1079         unsigned long ticket_agel;
1080         size_t idlen;
1081
1082         if (!PACKET_get_length_prefixed_2(&identities, &identity)
1083                 || !PACKET_get_net_4(&identities, &ticket_agel)) {
1084             SSLfatal(s, SSL_AD_DECODE_ERROR,
1085                      SSL_F_TLS_PARSE_CTOS_PSK, SSL_R_BAD_EXTENSION);
1086             return 0;
1087         }
1088
1089         idlen = PACKET_remaining(&identity);
1090         if (s->psk_find_session_cb != NULL
1091                 && !s->psk_find_session_cb(s, PACKET_data(&identity), idlen,
1092                                            &sess)) {
1093             SSLfatal(s, SSL_AD_INTERNAL_ERROR,
1094                      SSL_F_TLS_PARSE_CTOS_PSK, SSL_R_BAD_EXTENSION);
1095             return 0;
1096         }
1097
1098 #ifndef OPENSSL_NO_PSK
1099         if(sess == NULL
1100                 && s->psk_server_callback != NULL
1101                 && idlen <= PSK_MAX_IDENTITY_LEN) {
1102             char *pskid = NULL;
1103             unsigned char pskdata[PSK_MAX_PSK_LEN];
1104             unsigned int pskdatalen;
1105
1106             if (!PACKET_strndup(&identity, &pskid)) {
1107                 SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_F_TLS_PARSE_CTOS_PSK,
1108                          ERR_R_INTERNAL_ERROR);
1109                 return 0;
1110             }
1111             pskdatalen = s->psk_server_callback(s, pskid, pskdata,
1112                                                 sizeof(pskdata));
1113             OPENSSL_free(pskid);
1114             if (pskdatalen > PSK_MAX_PSK_LEN) {
1115                 SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_F_TLS_PARSE_CTOS_PSK,
1116                          ERR_R_INTERNAL_ERROR);
1117                 return 0;
1118             } else if (pskdatalen > 0) {
1119                 const SSL_CIPHER *cipher;
1120                 const unsigned char tls13_aes128gcmsha256_id[] = { 0x13, 0x01 };
1121
1122                 /*
1123                  * We found a PSK using an old style callback. We don't know
1124                  * the digest so we default to SHA256 as per the TLSv1.3 spec
1125                  */
1126                 cipher = SSL_CIPHER_find(s, tls13_aes128gcmsha256_id);
1127                 if (cipher == NULL) {
1128                     OPENSSL_cleanse(pskdata, pskdatalen);
1129                     SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_F_TLS_PARSE_CTOS_PSK,
1130                              ERR_R_INTERNAL_ERROR);
1131                     return 0;
1132                 }
1133
1134                 sess = SSL_SESSION_new();
1135                 if (sess == NULL
1136                         || !SSL_SESSION_set1_master_key(sess, pskdata,
1137                                                         pskdatalen)
1138                         || !SSL_SESSION_set_cipher(sess, cipher)
1139                         || !SSL_SESSION_set_protocol_version(sess,
1140                                                              TLS1_3_VERSION)) {
1141                     OPENSSL_cleanse(pskdata, pskdatalen);
1142                     SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_F_TLS_PARSE_CTOS_PSK,
1143                              ERR_R_INTERNAL_ERROR);
1144                     goto err;
1145                 }
1146                 OPENSSL_cleanse(pskdata, pskdatalen);
1147             }
1148         }
1149 #endif /* OPENSSL_NO_PSK */
1150
1151         if (sess != NULL) {
1152             /* We found a PSK */
1153             SSL_SESSION *sesstmp = ssl_session_dup(sess, 0);
1154
1155             if (sesstmp == NULL) {
1156                 SSLfatal(s, SSL_AD_INTERNAL_ERROR,
1157                          SSL_F_TLS_PARSE_CTOS_PSK, ERR_R_INTERNAL_ERROR);
1158                 return 0;
1159             }
1160             SSL_SESSION_free(sess);
1161             sess = sesstmp;
1162
1163             /*
1164              * We've just been told to use this session for this context so
1165              * make sure the sid_ctx matches up.
1166              */
1167             memcpy(sess->sid_ctx, s->sid_ctx, s->sid_ctx_length);
1168             sess->sid_ctx_length = s->sid_ctx_length;
1169             ext = 1;
1170             if (id == 0)
1171                 s->ext.early_data_ok = 1;
1172             s->ext.ticket_expected = 1;
1173         } else {
1174             uint32_t ticket_age = 0, now, agesec, agems;
1175             int ret;
1176
1177             /*
1178              * If we are using anti-replay protection then we behave as if
1179              * SSL_OP_NO_TICKET is set - we are caching tickets anyway so there
1180              * is no point in using full stateless tickets.
1181              */
1182             if ((s->options & SSL_OP_NO_TICKET) != 0
1183                     || (s->max_early_data > 0
1184                         && (s->options & SSL_OP_NO_ANTI_REPLAY) == 0))
1185                 ret = tls_get_stateful_ticket(s, &identity, &sess);
1186             else
1187                 ret = tls_decrypt_ticket(s, PACKET_data(&identity),
1188                                          PACKET_remaining(&identity), NULL, 0,
1189                                          &sess);
1190
1191             if (ret == SSL_TICKET_EMPTY) {
1192                 SSLfatal(s, SSL_AD_DECODE_ERROR, SSL_F_TLS_PARSE_CTOS_PSK,
1193                          SSL_R_BAD_EXTENSION);
1194                 return 0;
1195             }
1196
1197             if (ret == SSL_TICKET_FATAL_ERR_MALLOC
1198                     || ret == SSL_TICKET_FATAL_ERR_OTHER) {
1199                 SSLfatal(s, SSL_AD_INTERNAL_ERROR,
1200                          SSL_F_TLS_PARSE_CTOS_PSK, ERR_R_INTERNAL_ERROR);
1201                 return 0;
1202             }
1203             if (ret == SSL_TICKET_NONE || ret == SSL_TICKET_NO_DECRYPT)
1204                 continue;
1205
1206             /* Check for replay */
1207             if (s->max_early_data > 0
1208                     && (s->options & SSL_OP_NO_ANTI_REPLAY) == 0
1209                     && !SSL_CTX_remove_session(s->session_ctx, sess)) {
1210                 SSL_SESSION_free(sess);
1211                 sess = NULL;
1212                 continue;
1213             }
1214
1215             ticket_age = (uint32_t)ticket_agel;
1216             now = (uint32_t)time(NULL);
1217             agesec = now - (uint32_t)sess->time;
1218             agems = agesec * (uint32_t)1000;
1219             ticket_age -= sess->ext.tick_age_add;
1220
1221             /*
1222              * For simplicity we do our age calculations in seconds. If the
1223              * client does it in ms then it could appear that their ticket age
1224              * is longer than ours (our ticket age calculation should always be
1225              * slightly longer than the client's due to the network latency).
1226              * Therefore we add 1000ms to our age calculation to adjust for
1227              * rounding errors.
1228              */
1229             if (id == 0
1230                     && sess->timeout >= (long)agesec
1231                     && agems / (uint32_t)1000 == agesec
1232                     && ticket_age <= agems + 1000
1233                     && ticket_age + TICKET_AGE_ALLOWANCE >= agems + 1000) {
1234                 /*
1235                  * Ticket age is within tolerance and not expired. We allow it
1236                  * for early data
1237                  */
1238                 s->ext.early_data_ok = 1;
1239             }
1240         }
1241
1242         md = ssl_md(s->ctx, sess->cipher->algorithm2);
1243         if (!EVP_MD_is_a(md,
1244                 EVP_MD_name(ssl_md(s->ctx, s->s3.tmp.new_cipher->algorithm2)))) {
1245             /* The ciphersuite is not compatible with this session. */
1246             SSL_SESSION_free(sess);
1247             sess = NULL;
1248             s->ext.early_data_ok = 0;
1249             s->ext.ticket_expected = 0;
1250             continue;
1251         }
1252         break;
1253     }
1254
1255     if (sess == NULL)
1256         return 1;
1257
1258     binderoffset = PACKET_data(pkt) - (const unsigned char *)s->init_buf->data;
1259     hashsize = EVP_MD_size(md);
1260
1261     if (!PACKET_get_length_prefixed_2(pkt, &binders)) {
1262         SSLfatal(s, SSL_AD_DECODE_ERROR, SSL_F_TLS_PARSE_CTOS_PSK,
1263                  SSL_R_BAD_EXTENSION);
1264         goto err;
1265     }
1266
1267     for (i = 0; i <= id; i++) {
1268         if (!PACKET_get_length_prefixed_1(&binders, &binder)) {
1269             SSLfatal(s, SSL_AD_DECODE_ERROR, SSL_F_TLS_PARSE_CTOS_PSK,
1270                      SSL_R_BAD_EXTENSION);
1271             goto err;
1272         }
1273     }
1274
1275     if (PACKET_remaining(&binder) != hashsize) {
1276         SSLfatal(s, SSL_AD_DECODE_ERROR, SSL_F_TLS_PARSE_CTOS_PSK,
1277                  SSL_R_BAD_EXTENSION);
1278         goto err;
1279     }
1280     if (tls_psk_do_binder(s, md, (const unsigned char *)s->init_buf->data,
1281                           binderoffset, PACKET_data(&binder), NULL, sess, 0,
1282                           ext) != 1) {
1283         /* SSLfatal() already called */
1284         goto err;
1285     }
1286
1287     s->ext.tick_identity = id;
1288
1289     SSL_SESSION_free(s->session);
1290     s->session = sess;
1291     return 1;
1292 err:
1293     SSL_SESSION_free(sess);
1294     return 0;
1295 }
1296
1297 int tls_parse_ctos_post_handshake_auth(SSL *s, PACKET *pkt, unsigned int context,
1298                                        X509 *x, size_t chainidx)
1299 {
1300     if (PACKET_remaining(pkt) != 0) {
1301         SSLfatal(s, SSL_AD_DECODE_ERROR, SSL_F_TLS_PARSE_CTOS_POST_HANDSHAKE_AUTH,
1302                  SSL_R_POST_HANDSHAKE_AUTH_ENCODING_ERR);
1303         return 0;
1304     }
1305
1306     s->post_handshake_auth = SSL_PHA_EXT_RECEIVED;
1307
1308     return 1;
1309 }
1310
1311 /*
1312  * Add the server's renegotiation binding
1313  */
1314 EXT_RETURN tls_construct_stoc_renegotiate(SSL *s, WPACKET *pkt,
1315                                           unsigned int context, X509 *x,
1316                                           size_t chainidx)
1317 {
1318     if (!s->s3.send_connection_binding)
1319         return EXT_RETURN_NOT_SENT;
1320
1321     /* Still add this even if SSL_OP_NO_RENEGOTIATION is set */
1322     if (!WPACKET_put_bytes_u16(pkt, TLSEXT_TYPE_renegotiate)
1323             || !WPACKET_start_sub_packet_u16(pkt)
1324             || !WPACKET_start_sub_packet_u8(pkt)
1325             || !WPACKET_memcpy(pkt, s->s3.previous_client_finished,
1326                                s->s3.previous_client_finished_len)
1327             || !WPACKET_memcpy(pkt, s->s3.previous_server_finished,
1328                                s->s3.previous_server_finished_len)
1329             || !WPACKET_close(pkt)
1330             || !WPACKET_close(pkt)) {
1331         SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_F_TLS_CONSTRUCT_STOC_RENEGOTIATE,
1332                  ERR_R_INTERNAL_ERROR);
1333         return EXT_RETURN_FAIL;
1334     }
1335
1336     return EXT_RETURN_SENT;
1337 }
1338
1339 EXT_RETURN tls_construct_stoc_server_name(SSL *s, WPACKET *pkt,
1340                                           unsigned int context, X509 *x,
1341                                           size_t chainidx)
1342 {
1343     if (s->servername_done != 1)
1344         return EXT_RETURN_NOT_SENT;
1345
1346     /*
1347      * Prior to TLSv1.3 we ignore any SNI in the current handshake if resuming.
1348      * We just use the servername from the initial handshake.
1349      */
1350     if (s->hit && !SSL_IS_TLS13(s))
1351         return EXT_RETURN_NOT_SENT;
1352
1353     if (!WPACKET_put_bytes_u16(pkt, TLSEXT_TYPE_server_name)
1354             || !WPACKET_put_bytes_u16(pkt, 0)) {
1355         SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_F_TLS_CONSTRUCT_STOC_SERVER_NAME,
1356                  ERR_R_INTERNAL_ERROR);
1357         return EXT_RETURN_FAIL;
1358     }
1359
1360     return EXT_RETURN_SENT;
1361 }
1362
1363 /* Add/include the server's max fragment len extension into ServerHello */
1364 EXT_RETURN tls_construct_stoc_maxfragmentlen(SSL *s, WPACKET *pkt,
1365                                              unsigned int context, X509 *x,
1366                                              size_t chainidx)
1367 {
1368     if (!USE_MAX_FRAGMENT_LENGTH_EXT(s->session))
1369         return EXT_RETURN_NOT_SENT;
1370
1371     /*-
1372      * 4 bytes for this extension type and extension length
1373      * 1 byte for the Max Fragment Length code value.
1374      */
1375     if (!WPACKET_put_bytes_u16(pkt, TLSEXT_TYPE_max_fragment_length)
1376         || !WPACKET_start_sub_packet_u16(pkt)
1377         || !WPACKET_put_bytes_u8(pkt, s->session->ext.max_fragment_len_mode)
1378         || !WPACKET_close(pkt)) {
1379         SSLfatal(s, SSL_AD_INTERNAL_ERROR,
1380                  SSL_F_TLS_CONSTRUCT_STOC_MAXFRAGMENTLEN, ERR_R_INTERNAL_ERROR);
1381         return EXT_RETURN_FAIL;
1382     }
1383
1384     return EXT_RETURN_SENT;
1385 }
1386
1387 #ifndef OPENSSL_NO_EC
1388 EXT_RETURN tls_construct_stoc_ec_pt_formats(SSL *s, WPACKET *pkt,
1389                                             unsigned int context, X509 *x,
1390                                             size_t chainidx)
1391 {
1392     unsigned long alg_k = s->s3.tmp.new_cipher->algorithm_mkey;
1393     unsigned long alg_a = s->s3.tmp.new_cipher->algorithm_auth;
1394     int using_ecc = ((alg_k & SSL_kECDHE) || (alg_a & SSL_aECDSA))
1395                     && (s->ext.peer_ecpointformats != NULL);
1396     const unsigned char *plist;
1397     size_t plistlen;
1398
1399     if (!using_ecc)
1400         return EXT_RETURN_NOT_SENT;
1401
1402     tls1_get_formatlist(s, &plist, &plistlen);
1403     if (!WPACKET_put_bytes_u16(pkt, TLSEXT_TYPE_ec_point_formats)
1404             || !WPACKET_start_sub_packet_u16(pkt)
1405             || !WPACKET_sub_memcpy_u8(pkt, plist, plistlen)
1406             || !WPACKET_close(pkt)) {
1407         SSLfatal(s, SSL_AD_INTERNAL_ERROR,
1408                  SSL_F_TLS_CONSTRUCT_STOC_EC_PT_FORMATS, ERR_R_INTERNAL_ERROR);
1409         return EXT_RETURN_FAIL;
1410     }
1411
1412     return EXT_RETURN_SENT;
1413 }
1414 #endif
1415
1416 #if !defined(OPENSSL_NO_EC) || !defined(OPENSSL_NO_DH)
1417 EXT_RETURN tls_construct_stoc_supported_groups(SSL *s, WPACKET *pkt,
1418                                                unsigned int context, X509 *x,
1419                                                size_t chainidx)
1420 {
1421     const uint16_t *groups;
1422     size_t numgroups, i, first = 1;
1423
1424     /* s->s3.group_id is non zero if we accepted a key_share */
1425     if (s->s3.group_id == 0)
1426         return EXT_RETURN_NOT_SENT;
1427
1428     /* Get our list of supported groups */
1429     tls1_get_supported_groups(s, &groups, &numgroups);
1430     if (numgroups == 0) {
1431         SSLfatal(s, SSL_AD_INTERNAL_ERROR,
1432                  SSL_F_TLS_CONSTRUCT_STOC_SUPPORTED_GROUPS, ERR_R_INTERNAL_ERROR);
1433         return EXT_RETURN_FAIL;
1434     }
1435
1436     /* Copy group ID if supported */
1437     for (i = 0; i < numgroups; i++) {
1438         uint16_t group = groups[i];
1439
1440         if (tls_valid_group(s, group, SSL_version(s))
1441                 && tls_group_allowed(s, group, SSL_SECOP_CURVE_SUPPORTED)) {
1442             if (first) {
1443                 /*
1444                  * Check if the client is already using our preferred group. If
1445                  * so we don't need to add this extension
1446                  */
1447                 if (s->s3.group_id == group)
1448                     return EXT_RETURN_NOT_SENT;
1449
1450                 /* Add extension header */
1451                 if (!WPACKET_put_bytes_u16(pkt, TLSEXT_TYPE_supported_groups)
1452                            /* Sub-packet for supported_groups extension */
1453                         || !WPACKET_start_sub_packet_u16(pkt)
1454                         || !WPACKET_start_sub_packet_u16(pkt)) {
1455                     SSLfatal(s, SSL_AD_INTERNAL_ERROR,
1456                              SSL_F_TLS_CONSTRUCT_STOC_SUPPORTED_GROUPS,
1457                              ERR_R_INTERNAL_ERROR);
1458                     return EXT_RETURN_FAIL;
1459                 }
1460
1461                 first = 0;
1462             }
1463             if (!WPACKET_put_bytes_u16(pkt, group)) {
1464                     SSLfatal(s, SSL_AD_INTERNAL_ERROR,
1465                              SSL_F_TLS_CONSTRUCT_STOC_SUPPORTED_GROUPS,
1466                              ERR_R_INTERNAL_ERROR);
1467                     return EXT_RETURN_FAIL;
1468                 }
1469         }
1470     }
1471
1472     if (!WPACKET_close(pkt) || !WPACKET_close(pkt)) {
1473         SSLfatal(s, SSL_AD_INTERNAL_ERROR,
1474                  SSL_F_TLS_CONSTRUCT_STOC_SUPPORTED_GROUPS,
1475                  ERR_R_INTERNAL_ERROR);
1476         return EXT_RETURN_FAIL;
1477     }
1478
1479     return EXT_RETURN_SENT;
1480 }
1481 #endif
1482
1483 EXT_RETURN tls_construct_stoc_session_ticket(SSL *s, WPACKET *pkt,
1484                                              unsigned int context, X509 *x,
1485                                              size_t chainidx)
1486 {
1487     if (!s->ext.ticket_expected || !tls_use_ticket(s)) {
1488         s->ext.ticket_expected = 0;
1489         return EXT_RETURN_NOT_SENT;
1490     }
1491
1492     if (!WPACKET_put_bytes_u16(pkt, TLSEXT_TYPE_session_ticket)
1493             || !WPACKET_put_bytes_u16(pkt, 0)) {
1494         SSLfatal(s, SSL_AD_INTERNAL_ERROR,
1495                  SSL_F_TLS_CONSTRUCT_STOC_SESSION_TICKET, ERR_R_INTERNAL_ERROR);
1496         return EXT_RETURN_FAIL;
1497     }
1498
1499     return EXT_RETURN_SENT;
1500 }
1501
1502 #ifndef OPENSSL_NO_OCSP
1503 EXT_RETURN tls_construct_stoc_status_request(SSL *s, WPACKET *pkt,
1504                                              unsigned int context, X509 *x,
1505                                              size_t chainidx)
1506 {
1507     /* We don't currently support this extension inside a CertificateRequest */
1508     if (context == SSL_EXT_TLS1_3_CERTIFICATE_REQUEST)
1509         return EXT_RETURN_NOT_SENT;
1510
1511     if (!s->ext.status_expected)
1512         return EXT_RETURN_NOT_SENT;
1513
1514     if (SSL_IS_TLS13(s) && chainidx != 0)
1515         return EXT_RETURN_NOT_SENT;
1516
1517     if (!WPACKET_put_bytes_u16(pkt, TLSEXT_TYPE_status_request)
1518             || !WPACKET_start_sub_packet_u16(pkt)) {
1519         SSLfatal(s, SSL_AD_INTERNAL_ERROR,
1520                  SSL_F_TLS_CONSTRUCT_STOC_STATUS_REQUEST, ERR_R_INTERNAL_ERROR);
1521         return EXT_RETURN_FAIL;
1522     }
1523
1524     /*
1525      * In TLSv1.3 we include the certificate status itself. In <= TLSv1.2 we
1526      * send back an empty extension, with the certificate status appearing as a
1527      * separate message
1528      */
1529     if (SSL_IS_TLS13(s) && !tls_construct_cert_status_body(s, pkt)) {
1530        /* SSLfatal() already called */
1531        return EXT_RETURN_FAIL;
1532     }
1533     if (!WPACKET_close(pkt)) {
1534         SSLfatal(s, SSL_AD_INTERNAL_ERROR,
1535                  SSL_F_TLS_CONSTRUCT_STOC_STATUS_REQUEST, ERR_R_INTERNAL_ERROR);
1536         return EXT_RETURN_FAIL;
1537     }
1538
1539     return EXT_RETURN_SENT;
1540 }
1541 #endif
1542
1543 #ifndef OPENSSL_NO_NEXTPROTONEG
1544 EXT_RETURN tls_construct_stoc_next_proto_neg(SSL *s, WPACKET *pkt,
1545                                              unsigned int context, X509 *x,
1546                                              size_t chainidx)
1547 {
1548     const unsigned char *npa;
1549     unsigned int npalen;
1550     int ret;
1551     int npn_seen = s->s3.npn_seen;
1552
1553     s->s3.npn_seen = 0;
1554     if (!npn_seen || s->ctx->ext.npn_advertised_cb == NULL)
1555         return EXT_RETURN_NOT_SENT;
1556
1557     ret = s->ctx->ext.npn_advertised_cb(s, &npa, &npalen,
1558                                         s->ctx->ext.npn_advertised_cb_arg);
1559     if (ret == SSL_TLSEXT_ERR_OK) {
1560         if (!WPACKET_put_bytes_u16(pkt, TLSEXT_TYPE_next_proto_neg)
1561                 || !WPACKET_sub_memcpy_u16(pkt, npa, npalen)) {
1562             SSLfatal(s, SSL_AD_INTERNAL_ERROR,
1563                      SSL_F_TLS_CONSTRUCT_STOC_NEXT_PROTO_NEG,
1564                      ERR_R_INTERNAL_ERROR);
1565             return EXT_RETURN_FAIL;
1566         }
1567         s->s3.npn_seen = 1;
1568     }
1569
1570     return EXT_RETURN_SENT;
1571 }
1572 #endif
1573
1574 EXT_RETURN tls_construct_stoc_alpn(SSL *s, WPACKET *pkt, unsigned int context,
1575                                    X509 *x, size_t chainidx)
1576 {
1577     if (s->s3.alpn_selected == NULL)
1578         return EXT_RETURN_NOT_SENT;
1579
1580     if (!WPACKET_put_bytes_u16(pkt,
1581                 TLSEXT_TYPE_application_layer_protocol_negotiation)
1582             || !WPACKET_start_sub_packet_u16(pkt)
1583             || !WPACKET_start_sub_packet_u16(pkt)
1584             || !WPACKET_sub_memcpy_u8(pkt, s->s3.alpn_selected,
1585                                       s->s3.alpn_selected_len)
1586             || !WPACKET_close(pkt)
1587             || !WPACKET_close(pkt)) {
1588         SSLfatal(s, SSL_AD_INTERNAL_ERROR,
1589                  SSL_F_TLS_CONSTRUCT_STOC_ALPN, ERR_R_INTERNAL_ERROR);
1590         return EXT_RETURN_FAIL;
1591     }
1592
1593     return EXT_RETURN_SENT;
1594 }
1595
1596 #ifndef OPENSSL_NO_SRTP
1597 EXT_RETURN tls_construct_stoc_use_srtp(SSL *s, WPACKET *pkt,
1598                                        unsigned int context, X509 *x,
1599                                        size_t chainidx)
1600 {
1601     if (s->srtp_profile == NULL)
1602         return EXT_RETURN_NOT_SENT;
1603
1604     if (!WPACKET_put_bytes_u16(pkt, TLSEXT_TYPE_use_srtp)
1605             || !WPACKET_start_sub_packet_u16(pkt)
1606             || !WPACKET_put_bytes_u16(pkt, 2)
1607             || !WPACKET_put_bytes_u16(pkt, s->srtp_profile->id)
1608             || !WPACKET_put_bytes_u8(pkt, 0)
1609             || !WPACKET_close(pkt)) {
1610         SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_F_TLS_CONSTRUCT_STOC_USE_SRTP,
1611                  ERR_R_INTERNAL_ERROR);
1612         return EXT_RETURN_FAIL;
1613     }
1614
1615     return EXT_RETURN_SENT;
1616 }
1617 #endif
1618
1619 EXT_RETURN tls_construct_stoc_etm(SSL *s, WPACKET *pkt, unsigned int context,
1620                                   X509 *x, size_t chainidx)
1621 {
1622     if (!s->ext.use_etm)
1623         return EXT_RETURN_NOT_SENT;
1624
1625     /*
1626      * Don't use encrypt_then_mac if AEAD or RC4 might want to disable
1627      * for other cases too.
1628      */
1629     if (s->s3.tmp.new_cipher->algorithm_mac == SSL_AEAD
1630         || s->s3.tmp.new_cipher->algorithm_enc == SSL_RC4
1631         || s->s3.tmp.new_cipher->algorithm_enc == SSL_eGOST2814789CNT
1632         || s->s3.tmp.new_cipher->algorithm_enc == SSL_eGOST2814789CNT12) {
1633         s->ext.use_etm = 0;
1634         return EXT_RETURN_NOT_SENT;
1635     }
1636
1637     if (!WPACKET_put_bytes_u16(pkt, TLSEXT_TYPE_encrypt_then_mac)
1638             || !WPACKET_put_bytes_u16(pkt, 0)) {
1639         SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_F_TLS_CONSTRUCT_STOC_ETM,
1640                  ERR_R_INTERNAL_ERROR);
1641         return EXT_RETURN_FAIL;
1642     }
1643
1644     return EXT_RETURN_SENT;
1645 }
1646
1647 EXT_RETURN tls_construct_stoc_ems(SSL *s, WPACKET *pkt, unsigned int context,
1648                                   X509 *x, size_t chainidx)
1649 {
1650     if ((s->s3.flags & TLS1_FLAGS_RECEIVED_EXTMS) == 0)
1651         return EXT_RETURN_NOT_SENT;
1652
1653     if (!WPACKET_put_bytes_u16(pkt, TLSEXT_TYPE_extended_master_secret)
1654             || !WPACKET_put_bytes_u16(pkt, 0)) {
1655         SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_F_TLS_CONSTRUCT_STOC_EMS,
1656                  ERR_R_INTERNAL_ERROR);
1657         return EXT_RETURN_FAIL;
1658     }
1659
1660     return EXT_RETURN_SENT;
1661 }
1662
1663 EXT_RETURN tls_construct_stoc_supported_versions(SSL *s, WPACKET *pkt,
1664                                                  unsigned int context, X509 *x,
1665                                                  size_t chainidx)
1666 {
1667     if (!ossl_assert(SSL_IS_TLS13(s))) {
1668         SSLfatal(s, SSL_AD_INTERNAL_ERROR,
1669                  SSL_F_TLS_CONSTRUCT_STOC_SUPPORTED_VERSIONS,
1670                  ERR_R_INTERNAL_ERROR);
1671         return EXT_RETURN_FAIL;
1672     }
1673
1674     if (!WPACKET_put_bytes_u16(pkt, TLSEXT_TYPE_supported_versions)
1675             || !WPACKET_start_sub_packet_u16(pkt)
1676             || !WPACKET_put_bytes_u16(pkt, s->version)
1677             || !WPACKET_close(pkt)) {
1678         SSLfatal(s, SSL_AD_INTERNAL_ERROR,
1679                  SSL_F_TLS_CONSTRUCT_STOC_SUPPORTED_VERSIONS,
1680                  ERR_R_INTERNAL_ERROR);
1681         return EXT_RETURN_FAIL;
1682     }
1683
1684     return EXT_RETURN_SENT;
1685 }
1686
1687 EXT_RETURN tls_construct_stoc_key_share(SSL *s, WPACKET *pkt,
1688                                         unsigned int context, X509 *x,
1689                                         size_t chainidx)
1690 {
1691 #ifndef OPENSSL_NO_TLS1_3
1692     unsigned char *encodedPoint;
1693     size_t encoded_pt_len = 0;
1694     EVP_PKEY *ckey = s->s3.peer_tmp, *skey = NULL;
1695
1696     if (s->hello_retry_request == SSL_HRR_PENDING) {
1697         if (ckey != NULL) {
1698             /* Original key_share was acceptable so don't ask for another one */
1699             return EXT_RETURN_NOT_SENT;
1700         }
1701         if (!WPACKET_put_bytes_u16(pkt, TLSEXT_TYPE_key_share)
1702                 || !WPACKET_start_sub_packet_u16(pkt)
1703                 || !WPACKET_put_bytes_u16(pkt, s->s3.group_id)
1704                 || !WPACKET_close(pkt)) {
1705             SSLfatal(s, SSL_AD_INTERNAL_ERROR,
1706                      SSL_F_TLS_CONSTRUCT_STOC_KEY_SHARE,
1707                      ERR_R_INTERNAL_ERROR);
1708             return EXT_RETURN_FAIL;
1709         }
1710
1711         return EXT_RETURN_SENT;
1712     }
1713
1714     if (ckey == NULL) {
1715         /* No key_share received from client - must be resuming */
1716         if (!s->hit || !tls13_generate_handshake_secret(s, NULL, 0)) {
1717             SSLfatal(s, SSL_AD_INTERNAL_ERROR,
1718                      SSL_F_TLS_CONSTRUCT_STOC_KEY_SHARE, ERR_R_INTERNAL_ERROR);
1719             return EXT_RETURN_FAIL;
1720         }
1721         return EXT_RETURN_NOT_SENT;
1722     }
1723
1724     if (!WPACKET_put_bytes_u16(pkt, TLSEXT_TYPE_key_share)
1725             || !WPACKET_start_sub_packet_u16(pkt)
1726             || !WPACKET_put_bytes_u16(pkt, s->s3.group_id)) {
1727         SSLfatal(s, SSL_AD_INTERNAL_ERROR,
1728                  SSL_F_TLS_CONSTRUCT_STOC_KEY_SHARE, ERR_R_INTERNAL_ERROR);
1729         return EXT_RETURN_FAIL;
1730     }
1731
1732     skey = ssl_generate_pkey(s, ckey);
1733     if (skey == NULL) {
1734         SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_F_TLS_CONSTRUCT_STOC_KEY_SHARE,
1735                  ERR_R_MALLOC_FAILURE);
1736         return EXT_RETURN_FAIL;
1737     }
1738
1739     /* Generate encoding of server key */
1740     encoded_pt_len = EVP_PKEY_get1_tls_encodedpoint(skey, &encodedPoint);
1741     if (encoded_pt_len == 0) {
1742         SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_F_TLS_CONSTRUCT_STOC_KEY_SHARE,
1743                  ERR_R_EC_LIB);
1744         EVP_PKEY_free(skey);
1745         return EXT_RETURN_FAIL;
1746     }
1747
1748     if (!WPACKET_sub_memcpy_u16(pkt, encodedPoint, encoded_pt_len)
1749             || !WPACKET_close(pkt)) {
1750         SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_F_TLS_CONSTRUCT_STOC_KEY_SHARE,
1751                  ERR_R_INTERNAL_ERROR);
1752         EVP_PKEY_free(skey);
1753         OPENSSL_free(encodedPoint);
1754         return EXT_RETURN_FAIL;
1755     }
1756     OPENSSL_free(encodedPoint);
1757
1758     /* This causes the crypto state to be updated based on the derived keys */
1759     s->s3.tmp.pkey = skey;
1760     if (ssl_derive(s, skey, ckey, 1) == 0) {
1761         /* SSLfatal() already called */
1762         return EXT_RETURN_FAIL;
1763     }
1764     return EXT_RETURN_SENT;
1765 #else
1766     return EXT_RETURN_FAIL;
1767 #endif
1768 }
1769
1770 EXT_RETURN tls_construct_stoc_cookie(SSL *s, WPACKET *pkt, unsigned int context,
1771                                      X509 *x, size_t chainidx)
1772 {
1773 #ifndef OPENSSL_NO_TLS1_3
1774     unsigned char *hashval1, *hashval2, *appcookie1, *appcookie2, *cookie;
1775     unsigned char *hmac, *hmac2;
1776     size_t startlen, ciphlen, totcookielen, hashlen, hmaclen, appcookielen;
1777     EVP_MD_CTX *hctx;
1778     EVP_PKEY *pkey;
1779     int ret = EXT_RETURN_FAIL;
1780
1781     if ((s->s3.flags & TLS1_FLAGS_STATELESS) == 0)
1782         return EXT_RETURN_NOT_SENT;
1783
1784     if (s->ctx->gen_stateless_cookie_cb == NULL) {
1785         SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_F_TLS_CONSTRUCT_STOC_COOKIE,
1786                  SSL_R_NO_COOKIE_CALLBACK_SET);
1787         return EXT_RETURN_FAIL;
1788     }
1789
1790     if (!WPACKET_put_bytes_u16(pkt, TLSEXT_TYPE_cookie)
1791             || !WPACKET_start_sub_packet_u16(pkt)
1792             || !WPACKET_start_sub_packet_u16(pkt)
1793             || !WPACKET_get_total_written(pkt, &startlen)
1794             || !WPACKET_reserve_bytes(pkt, MAX_COOKIE_SIZE, &cookie)
1795             || !WPACKET_put_bytes_u16(pkt, COOKIE_STATE_FORMAT_VERSION)
1796             || !WPACKET_put_bytes_u16(pkt, TLS1_3_VERSION)
1797             || !WPACKET_put_bytes_u16(pkt, s->s3.group_id)
1798             || !s->method->put_cipher_by_char(s->s3.tmp.new_cipher, pkt,
1799                                               &ciphlen)
1800                /* Is there a key_share extension present in this HRR? */
1801             || !WPACKET_put_bytes_u8(pkt, s->s3.peer_tmp == NULL)
1802             || !WPACKET_put_bytes_u32(pkt, (unsigned int)time(NULL))
1803             || !WPACKET_start_sub_packet_u16(pkt)
1804             || !WPACKET_reserve_bytes(pkt, EVP_MAX_MD_SIZE, &hashval1)) {
1805         SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_F_TLS_CONSTRUCT_STOC_COOKIE,
1806                  ERR_R_INTERNAL_ERROR);
1807         return EXT_RETURN_FAIL;
1808     }
1809
1810     /*
1811      * Get the hash of the initial ClientHello. ssl_handshake_hash() operates
1812      * on raw buffers, so we first reserve sufficient bytes (above) and then
1813      * subsequently allocate them (below)
1814      */
1815     if (!ssl3_digest_cached_records(s, 0)
1816             || !ssl_handshake_hash(s, hashval1, EVP_MAX_MD_SIZE, &hashlen)) {
1817         /* SSLfatal() already called */
1818         return EXT_RETURN_FAIL;
1819     }
1820
1821     if (!WPACKET_allocate_bytes(pkt, hashlen, &hashval2)
1822             || !ossl_assert(hashval1 == hashval2)
1823             || !WPACKET_close(pkt)
1824             || !WPACKET_start_sub_packet_u8(pkt)
1825             || !WPACKET_reserve_bytes(pkt, SSL_COOKIE_LENGTH, &appcookie1)) {
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
1831     /* Generate the application cookie */
1832     if (s->ctx->gen_stateless_cookie_cb(s, appcookie1, &appcookielen) == 0) {
1833         SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_F_TLS_CONSTRUCT_STOC_COOKIE,
1834                  SSL_R_COOKIE_GEN_CALLBACK_FAILURE);
1835         return EXT_RETURN_FAIL;
1836     }
1837
1838     if (!WPACKET_allocate_bytes(pkt, appcookielen, &appcookie2)
1839             || !ossl_assert(appcookie1 == appcookie2)
1840             || !WPACKET_close(pkt)
1841             || !WPACKET_get_total_written(pkt, &totcookielen)
1842             || !WPACKET_reserve_bytes(pkt, SHA256_DIGEST_LENGTH, &hmac)) {
1843         SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_F_TLS_CONSTRUCT_STOC_COOKIE,
1844                  ERR_R_INTERNAL_ERROR);
1845         return EXT_RETURN_FAIL;
1846     }
1847     hmaclen = SHA256_DIGEST_LENGTH;
1848
1849     totcookielen -= startlen;
1850     if (!ossl_assert(totcookielen <= MAX_COOKIE_SIZE - SHA256_DIGEST_LENGTH)) {
1851         SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_F_TLS_CONSTRUCT_STOC_COOKIE,
1852                  ERR_R_INTERNAL_ERROR);
1853         return EXT_RETURN_FAIL;
1854     }
1855
1856     /* HMAC the cookie */
1857     hctx = EVP_MD_CTX_create();
1858     pkey = EVP_PKEY_new_raw_private_key(EVP_PKEY_HMAC, NULL,
1859                                         s->session_ctx->ext.cookie_hmac_key,
1860                                         sizeof(s->session_ctx->ext
1861                                                .cookie_hmac_key));
1862     if (hctx == NULL || pkey == NULL) {
1863         SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_F_TLS_CONSTRUCT_STOC_COOKIE,
1864                  ERR_R_MALLOC_FAILURE);
1865         goto err;
1866     }
1867
1868     if (EVP_DigestSignInit_ex(hctx, NULL, "SHA2-256", s->ctx->propq, pkey,
1869                               s->ctx->libctx) <= 0
1870             || EVP_DigestSign(hctx, hmac, &hmaclen, cookie,
1871                               totcookielen) <= 0) {
1872         SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_F_TLS_CONSTRUCT_STOC_COOKIE,
1873                  ERR_R_INTERNAL_ERROR);
1874         goto err;
1875     }
1876
1877     if (!ossl_assert(totcookielen + hmaclen <= MAX_COOKIE_SIZE)) {
1878         SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_F_TLS_CONSTRUCT_STOC_COOKIE,
1879                  ERR_R_INTERNAL_ERROR);
1880         goto err;
1881     }
1882
1883     if (!WPACKET_allocate_bytes(pkt, hmaclen, &hmac2)
1884             || !ossl_assert(hmac == hmac2)
1885             || !ossl_assert(cookie == hmac - totcookielen)
1886             || !WPACKET_close(pkt)
1887             || !WPACKET_close(pkt)) {
1888         SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_F_TLS_CONSTRUCT_STOC_COOKIE,
1889                  ERR_R_INTERNAL_ERROR);
1890         goto err;
1891     }
1892
1893     ret = EXT_RETURN_SENT;
1894
1895  err:
1896     EVP_MD_CTX_free(hctx);
1897     EVP_PKEY_free(pkey);
1898     return ret;
1899 #else
1900     return EXT_RETURN_FAIL;
1901 #endif
1902 }
1903
1904 EXT_RETURN tls_construct_stoc_cryptopro_bug(SSL *s, WPACKET *pkt,
1905                                             unsigned int context, X509 *x,
1906                                             size_t chainidx)
1907 {
1908     const unsigned char cryptopro_ext[36] = {
1909         0xfd, 0xe8,         /* 65000 */
1910         0x00, 0x20,         /* 32 bytes length */
1911         0x30, 0x1e, 0x30, 0x08, 0x06, 0x06, 0x2a, 0x85,
1912         0x03, 0x02, 0x02, 0x09, 0x30, 0x08, 0x06, 0x06,
1913         0x2a, 0x85, 0x03, 0x02, 0x02, 0x16, 0x30, 0x08,
1914         0x06, 0x06, 0x2a, 0x85, 0x03, 0x02, 0x02, 0x17
1915     };
1916
1917     if (((s->s3.tmp.new_cipher->id & 0xFFFF) != 0x80
1918          && (s->s3.tmp.new_cipher->id & 0xFFFF) != 0x81)
1919             || (SSL_get_options(s) & SSL_OP_CRYPTOPRO_TLSEXT_BUG) == 0)
1920         return EXT_RETURN_NOT_SENT;
1921
1922     if (!WPACKET_memcpy(pkt, cryptopro_ext, sizeof(cryptopro_ext))) {
1923         SSLfatal(s, SSL_AD_INTERNAL_ERROR,
1924                  SSL_F_TLS_CONSTRUCT_STOC_CRYPTOPRO_BUG, ERR_R_INTERNAL_ERROR);
1925         return EXT_RETURN_FAIL;
1926     }
1927
1928     return EXT_RETURN_SENT;
1929 }
1930
1931 EXT_RETURN tls_construct_stoc_early_data(SSL *s, WPACKET *pkt,
1932                                          unsigned int context, X509 *x,
1933                                          size_t chainidx)
1934 {
1935     if (context == SSL_EXT_TLS1_3_NEW_SESSION_TICKET) {
1936         if (s->max_early_data == 0)
1937             return EXT_RETURN_NOT_SENT;
1938
1939         if (!WPACKET_put_bytes_u16(pkt, TLSEXT_TYPE_early_data)
1940                 || !WPACKET_start_sub_packet_u16(pkt)
1941                 || !WPACKET_put_bytes_u32(pkt, s->max_early_data)
1942                 || !WPACKET_close(pkt)) {
1943             SSLfatal(s, SSL_AD_INTERNAL_ERROR,
1944                      SSL_F_TLS_CONSTRUCT_STOC_EARLY_DATA, ERR_R_INTERNAL_ERROR);
1945             return EXT_RETURN_FAIL;
1946         }
1947
1948         return EXT_RETURN_SENT;
1949     }
1950
1951     if (s->ext.early_data != SSL_EARLY_DATA_ACCEPTED)
1952         return EXT_RETURN_NOT_SENT;
1953
1954     if (!WPACKET_put_bytes_u16(pkt, TLSEXT_TYPE_early_data)
1955             || !WPACKET_start_sub_packet_u16(pkt)
1956             || !WPACKET_close(pkt)) {
1957         SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_F_TLS_CONSTRUCT_STOC_EARLY_DATA,
1958                  ERR_R_INTERNAL_ERROR);
1959         return EXT_RETURN_FAIL;
1960     }
1961
1962     return EXT_RETURN_SENT;
1963 }
1964
1965 EXT_RETURN tls_construct_stoc_psk(SSL *s, WPACKET *pkt, unsigned int context,
1966                                   X509 *x, size_t chainidx)
1967 {
1968     if (!s->hit)
1969         return EXT_RETURN_NOT_SENT;
1970
1971     if (!WPACKET_put_bytes_u16(pkt, TLSEXT_TYPE_psk)
1972             || !WPACKET_start_sub_packet_u16(pkt)
1973             || !WPACKET_put_bytes_u16(pkt, s->ext.tick_identity)
1974             || !WPACKET_close(pkt)) {
1975         SSLfatal(s, SSL_AD_INTERNAL_ERROR,
1976                  SSL_F_TLS_CONSTRUCT_STOC_PSK, ERR_R_INTERNAL_ERROR);
1977         return EXT_RETURN_FAIL;
1978     }
1979
1980     return EXT_RETURN_SENT;
1981 }