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