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