d1d86ea5e66850ff85d12815ebbb29c48b386ce1
[openssl.git] / ssl / statem / statem_srvr.c
1 /*
2  * Copyright 1995-2020 The OpenSSL Project Authors. All Rights Reserved.
3  * Copyright (c) 2002, Oracle and/or its affiliates. All rights reserved
4  * Copyright 2005 Nokia. All rights reserved.
5  *
6  * Licensed under the Apache License 2.0 (the "License").  You may not use
7  * this file except in compliance with the License.  You can obtain a copy
8  * in the file LICENSE in the source distribution or at
9  * https://www.openssl.org/source/license.html
10  */
11
12 #include <stdio.h>
13 #include "../ssl_local.h"
14 #include "statem_local.h"
15 #include "internal/constant_time.h"
16 #include "internal/cryptlib.h"
17 #include <openssl/buffer.h>
18 #include <openssl/rand.h>
19 #include <openssl/objects.h>
20 #include <openssl/evp.h>
21 #include <openssl/x509.h>
22 #include <openssl/dh.h>
23 #include <openssl/bn.h>
24 #include <openssl/md5.h>
25 #include <openssl/trace.h>
26 #include <openssl/core_names.h>
27 #include <openssl/asn1t.h>
28
29 DEFINE_STACK_OF(X509)
30 DEFINE_STACK_OF(SSL_COMP)
31 DEFINE_STACK_OF_CONST(SSL_CIPHER)
32
33 #define TICKET_NONCE_SIZE       8
34
35 typedef struct {
36   ASN1_TYPE *kxBlob;
37   ASN1_TYPE *opaqueBlob;
38 } GOST_KX_MESSAGE;
39
40 DECLARE_ASN1_FUNCTIONS(GOST_KX_MESSAGE)
41
42 ASN1_SEQUENCE(GOST_KX_MESSAGE) = {
43   ASN1_SIMPLE(GOST_KX_MESSAGE,  kxBlob, ASN1_ANY),
44   ASN1_OPT(GOST_KX_MESSAGE, opaqueBlob, ASN1_ANY),
45 } ASN1_SEQUENCE_END(GOST_KX_MESSAGE)
46
47 IMPLEMENT_ASN1_FUNCTIONS(GOST_KX_MESSAGE)
48
49 static int tls_construct_encrypted_extensions(SSL *s, WPACKET *pkt);
50
51 /*
52  * ossl_statem_server13_read_transition() encapsulates the logic for the allowed
53  * handshake state transitions when a TLSv1.3 server is reading messages from
54  * the client. The message type that the client has sent is provided in |mt|.
55  * The current state is in |s->statem.hand_state|.
56  *
57  * Return values are 1 for success (transition allowed) and  0 on error
58  * (transition not allowed)
59  */
60 static int ossl_statem_server13_read_transition(SSL *s, int mt)
61 {
62     OSSL_STATEM *st = &s->statem;
63
64     /*
65      * Note: There is no case for TLS_ST_BEFORE because at that stage we have
66      * not negotiated TLSv1.3 yet, so that case is handled by
67      * ossl_statem_server_read_transition()
68      */
69     switch (st->hand_state) {
70     default:
71         break;
72
73     case TLS_ST_EARLY_DATA:
74         if (s->hello_retry_request == SSL_HRR_PENDING) {
75             if (mt == SSL3_MT_CLIENT_HELLO) {
76                 st->hand_state = TLS_ST_SR_CLNT_HELLO;
77                 return 1;
78             }
79             break;
80         } else if (s->ext.early_data == SSL_EARLY_DATA_ACCEPTED) {
81             if (mt == SSL3_MT_END_OF_EARLY_DATA) {
82                 st->hand_state = TLS_ST_SR_END_OF_EARLY_DATA;
83                 return 1;
84             }
85             break;
86         }
87         /* Fall through */
88
89     case TLS_ST_SR_END_OF_EARLY_DATA:
90     case TLS_ST_SW_FINISHED:
91         if (s->s3.tmp.cert_request) {
92             if (mt == SSL3_MT_CERTIFICATE) {
93                 st->hand_state = TLS_ST_SR_CERT;
94                 return 1;
95             }
96         } else {
97             if (mt == SSL3_MT_FINISHED) {
98                 st->hand_state = TLS_ST_SR_FINISHED;
99                 return 1;
100             }
101         }
102         break;
103
104     case TLS_ST_SR_CERT:
105         if (s->session->peer == NULL) {
106             if (mt == SSL3_MT_FINISHED) {
107                 st->hand_state = TLS_ST_SR_FINISHED;
108                 return 1;
109             }
110         } else {
111             if (mt == SSL3_MT_CERTIFICATE_VERIFY) {
112                 st->hand_state = TLS_ST_SR_CERT_VRFY;
113                 return 1;
114             }
115         }
116         break;
117
118     case TLS_ST_SR_CERT_VRFY:
119         if (mt == SSL3_MT_FINISHED) {
120             st->hand_state = TLS_ST_SR_FINISHED;
121             return 1;
122         }
123         break;
124
125     case TLS_ST_OK:
126         /*
127          * Its never ok to start processing handshake messages in the middle of
128          * early data (i.e. before we've received the end of early data alert)
129          */
130         if (s->early_data_state == SSL_EARLY_DATA_READING)
131             break;
132
133         if (mt == SSL3_MT_CERTIFICATE
134                 && s->post_handshake_auth == SSL_PHA_REQUESTED) {
135             st->hand_state = TLS_ST_SR_CERT;
136             return 1;
137         }
138
139         if (mt == SSL3_MT_KEY_UPDATE) {
140             st->hand_state = TLS_ST_SR_KEY_UPDATE;
141             return 1;
142         }
143         break;
144     }
145
146     /* No valid transition found */
147     return 0;
148 }
149
150 /*
151  * ossl_statem_server_read_transition() encapsulates the logic for the allowed
152  * handshake state transitions when the server is reading messages from the
153  * client. The message type that the client has sent is provided in |mt|. The
154  * current state is in |s->statem.hand_state|.
155  *
156  * Return values are 1 for success (transition allowed) and  0 on error
157  * (transition not allowed)
158  */
159 int ossl_statem_server_read_transition(SSL *s, int mt)
160 {
161     OSSL_STATEM *st = &s->statem;
162
163     if (SSL_IS_TLS13(s)) {
164         if (!ossl_statem_server13_read_transition(s, mt))
165             goto err;
166         return 1;
167     }
168
169     switch (st->hand_state) {
170     default:
171         break;
172
173     case TLS_ST_BEFORE:
174     case TLS_ST_OK:
175     case DTLS_ST_SW_HELLO_VERIFY_REQUEST:
176         if (mt == SSL3_MT_CLIENT_HELLO) {
177             st->hand_state = TLS_ST_SR_CLNT_HELLO;
178             return 1;
179         }
180         break;
181
182     case TLS_ST_SW_SRVR_DONE:
183         /*
184          * If we get a CKE message after a ServerDone then either
185          * 1) We didn't request a Certificate
186          * OR
187          * 2) If we did request one then
188          *      a) We allow no Certificate to be returned
189          *      AND
190          *      b) We are running SSL3 (in TLS1.0+ the client must return a 0
191          *         list if we requested a certificate)
192          */
193         if (mt == SSL3_MT_CLIENT_KEY_EXCHANGE) {
194             if (s->s3.tmp.cert_request) {
195                 if (s->version == SSL3_VERSION) {
196                     if ((s->verify_mode & SSL_VERIFY_PEER)
197                         && (s->verify_mode & SSL_VERIFY_FAIL_IF_NO_PEER_CERT)) {
198                         /*
199                          * This isn't an unexpected message as such - we're just
200                          * not going to accept it because we require a client
201                          * cert.
202                          */
203                         SSLfatal(s, SSL_AD_HANDSHAKE_FAILURE,
204                                  SSL_F_OSSL_STATEM_SERVER_READ_TRANSITION,
205                                  SSL_R_PEER_DID_NOT_RETURN_A_CERTIFICATE);
206                         return 0;
207                     }
208                     st->hand_state = TLS_ST_SR_KEY_EXCH;
209                     return 1;
210                 }
211             } else {
212                 st->hand_state = TLS_ST_SR_KEY_EXCH;
213                 return 1;
214             }
215         } else if (s->s3.tmp.cert_request) {
216             if (mt == SSL3_MT_CERTIFICATE) {
217                 st->hand_state = TLS_ST_SR_CERT;
218                 return 1;
219             }
220         }
221         break;
222
223     case TLS_ST_SR_CERT:
224         if (mt == SSL3_MT_CLIENT_KEY_EXCHANGE) {
225             st->hand_state = TLS_ST_SR_KEY_EXCH;
226             return 1;
227         }
228         break;
229
230     case TLS_ST_SR_KEY_EXCH:
231         /*
232          * We should only process a CertificateVerify message if we have
233          * received a Certificate from the client. If so then |s->session->peer|
234          * will be non NULL. In some instances a CertificateVerify message is
235          * not required even if the peer has sent a Certificate (e.g. such as in
236          * the case of static DH). In that case |st->no_cert_verify| should be
237          * set.
238          */
239         if (s->session->peer == NULL || st->no_cert_verify) {
240             if (mt == SSL3_MT_CHANGE_CIPHER_SPEC) {
241                 /*
242                  * For the ECDH ciphersuites when the client sends its ECDH
243                  * pub key in a certificate, the CertificateVerify message is
244                  * not sent. Also for GOST ciphersuites when the client uses
245                  * its key from the certificate for key exchange.
246                  */
247                 st->hand_state = TLS_ST_SR_CHANGE;
248                 return 1;
249             }
250         } else {
251             if (mt == SSL3_MT_CERTIFICATE_VERIFY) {
252                 st->hand_state = TLS_ST_SR_CERT_VRFY;
253                 return 1;
254             }
255         }
256         break;
257
258     case TLS_ST_SR_CERT_VRFY:
259         if (mt == SSL3_MT_CHANGE_CIPHER_SPEC) {
260             st->hand_state = TLS_ST_SR_CHANGE;
261             return 1;
262         }
263         break;
264
265     case TLS_ST_SR_CHANGE:
266 #ifndef OPENSSL_NO_NEXTPROTONEG
267         if (s->s3.npn_seen) {
268             if (mt == SSL3_MT_NEXT_PROTO) {
269                 st->hand_state = TLS_ST_SR_NEXT_PROTO;
270                 return 1;
271             }
272         } else {
273 #endif
274             if (mt == SSL3_MT_FINISHED) {
275                 st->hand_state = TLS_ST_SR_FINISHED;
276                 return 1;
277             }
278 #ifndef OPENSSL_NO_NEXTPROTONEG
279         }
280 #endif
281         break;
282
283 #ifndef OPENSSL_NO_NEXTPROTONEG
284     case TLS_ST_SR_NEXT_PROTO:
285         if (mt == SSL3_MT_FINISHED) {
286             st->hand_state = TLS_ST_SR_FINISHED;
287             return 1;
288         }
289         break;
290 #endif
291
292     case TLS_ST_SW_FINISHED:
293         if (mt == SSL3_MT_CHANGE_CIPHER_SPEC) {
294             st->hand_state = TLS_ST_SR_CHANGE;
295             return 1;
296         }
297         break;
298     }
299
300  err:
301     /* No valid transition found */
302     if (SSL_IS_DTLS(s) && mt == SSL3_MT_CHANGE_CIPHER_SPEC) {
303         BIO *rbio;
304
305         /*
306          * CCS messages don't have a message sequence number so this is probably
307          * because of an out-of-order CCS. We'll just drop it.
308          */
309         s->init_num = 0;
310         s->rwstate = SSL_READING;
311         rbio = SSL_get_rbio(s);
312         BIO_clear_retry_flags(rbio);
313         BIO_set_retry_read(rbio);
314         return 0;
315     }
316     SSLfatal(s, SSL3_AD_UNEXPECTED_MESSAGE,
317              SSL_F_OSSL_STATEM_SERVER_READ_TRANSITION,
318              SSL_R_UNEXPECTED_MESSAGE);
319     return 0;
320 }
321
322 /*
323  * Should we send a ServerKeyExchange message?
324  *
325  * Valid return values are:
326  *   1: Yes
327  *   0: No
328  */
329 static int send_server_key_exchange(SSL *s)
330 {
331     unsigned long alg_k = s->s3.tmp.new_cipher->algorithm_mkey;
332
333     /*
334      * only send a ServerKeyExchange if DH or fortezza but we have a
335      * sign only certificate PSK: may send PSK identity hints For
336      * ECC ciphersuites, we send a serverKeyExchange message only if
337      * the cipher suite is either ECDH-anon or ECDHE. In other cases,
338      * the server certificate contains the server's public key for
339      * key exchange.
340      */
341     if (alg_k & (SSL_kDHE | SSL_kECDHE)
342         /*
343          * PSK: send ServerKeyExchange if PSK identity hint if
344          * provided
345          */
346 #ifndef OPENSSL_NO_PSK
347         /* Only send SKE if we have identity hint for plain PSK */
348         || ((alg_k & (SSL_kPSK | SSL_kRSAPSK))
349             && s->cert->psk_identity_hint)
350         /* For other PSK always send SKE */
351         || (alg_k & (SSL_PSK & (SSL_kDHEPSK | SSL_kECDHEPSK)))
352 #endif
353 #ifndef OPENSSL_NO_SRP
354         /* SRP: send ServerKeyExchange */
355         || (alg_k & SSL_kSRP)
356 #endif
357         ) {
358         return 1;
359     }
360
361     return 0;
362 }
363
364 /*
365  * Should we send a CertificateRequest message?
366  *
367  * Valid return values are:
368  *   1: Yes
369  *   0: No
370  */
371 int send_certificate_request(SSL *s)
372 {
373     if (
374            /* don't request cert unless asked for it: */
375            s->verify_mode & SSL_VERIFY_PEER
376            /*
377             * don't request if post-handshake-only unless doing
378             * post-handshake in TLSv1.3:
379             */
380            && (!SSL_IS_TLS13(s) || !(s->verify_mode & SSL_VERIFY_POST_HANDSHAKE)
381                || s->post_handshake_auth == SSL_PHA_REQUEST_PENDING)
382            /*
383             * if SSL_VERIFY_CLIENT_ONCE is set, don't request cert
384             * a second time:
385             */
386            && (s->certreqs_sent < 1 ||
387                !(s->verify_mode & SSL_VERIFY_CLIENT_ONCE))
388            /*
389             * never request cert in anonymous ciphersuites (see
390             * section "Certificate request" in SSL 3 drafts and in
391             * RFC 2246):
392             */
393            && (!(s->s3.tmp.new_cipher->algorithm_auth & SSL_aNULL)
394                /*
395                 * ... except when the application insists on
396                 * verification (against the specs, but statem_clnt.c accepts
397                 * this for SSL 3)
398                 */
399                || (s->verify_mode & SSL_VERIFY_FAIL_IF_NO_PEER_CERT))
400            /* don't request certificate for SRP auth */
401            && !(s->s3.tmp.new_cipher->algorithm_auth & SSL_aSRP)
402            /*
403             * With normal PSK Certificates and Certificate Requests
404             * are omitted
405             */
406            && !(s->s3.tmp.new_cipher->algorithm_auth & SSL_aPSK)) {
407         return 1;
408     }
409
410     return 0;
411 }
412
413 /*
414  * ossl_statem_server13_write_transition() works out what handshake state to
415  * move to next when a TLSv1.3 server is writing messages to be sent to the
416  * client.
417  */
418 static WRITE_TRAN ossl_statem_server13_write_transition(SSL *s)
419 {
420     OSSL_STATEM *st = &s->statem;
421
422     /*
423      * No case for TLS_ST_BEFORE, because at that stage we have not negotiated
424      * TLSv1.3 yet, so that is handled by ossl_statem_server_write_transition()
425      */
426
427     switch (st->hand_state) {
428     default:
429         /* Shouldn't happen */
430         SSLfatal(s, SSL_AD_INTERNAL_ERROR,
431                  SSL_F_OSSL_STATEM_SERVER13_WRITE_TRANSITION,
432                  ERR_R_INTERNAL_ERROR);
433         return WRITE_TRAN_ERROR;
434
435     case TLS_ST_OK:
436         if (s->key_update != SSL_KEY_UPDATE_NONE) {
437             st->hand_state = TLS_ST_SW_KEY_UPDATE;
438             return WRITE_TRAN_CONTINUE;
439         }
440         if (s->post_handshake_auth == SSL_PHA_REQUEST_PENDING) {
441             st->hand_state = TLS_ST_SW_CERT_REQ;
442             return WRITE_TRAN_CONTINUE;
443         }
444         if (s->ext.extra_tickets_expected > 0) {
445             st->hand_state = TLS_ST_SW_SESSION_TICKET;
446             return WRITE_TRAN_CONTINUE;
447         }
448         /* Try to read from the client instead */
449         return WRITE_TRAN_FINISHED;
450
451     case TLS_ST_SR_CLNT_HELLO:
452         st->hand_state = TLS_ST_SW_SRVR_HELLO;
453         return WRITE_TRAN_CONTINUE;
454
455     case TLS_ST_SW_SRVR_HELLO:
456         if ((s->options & SSL_OP_ENABLE_MIDDLEBOX_COMPAT) != 0
457                 && s->hello_retry_request != SSL_HRR_COMPLETE)
458             st->hand_state = TLS_ST_SW_CHANGE;
459         else if (s->hello_retry_request == SSL_HRR_PENDING)
460             st->hand_state = TLS_ST_EARLY_DATA;
461         else
462             st->hand_state = TLS_ST_SW_ENCRYPTED_EXTENSIONS;
463         return WRITE_TRAN_CONTINUE;
464
465     case TLS_ST_SW_CHANGE:
466         if (s->hello_retry_request == SSL_HRR_PENDING)
467             st->hand_state = TLS_ST_EARLY_DATA;
468         else
469             st->hand_state = TLS_ST_SW_ENCRYPTED_EXTENSIONS;
470         return WRITE_TRAN_CONTINUE;
471
472     case TLS_ST_SW_ENCRYPTED_EXTENSIONS:
473         if (s->hit)
474             st->hand_state = TLS_ST_SW_FINISHED;
475         else if (send_certificate_request(s))
476             st->hand_state = TLS_ST_SW_CERT_REQ;
477         else
478             st->hand_state = TLS_ST_SW_CERT;
479
480         return WRITE_TRAN_CONTINUE;
481
482     case TLS_ST_SW_CERT_REQ:
483         if (s->post_handshake_auth == SSL_PHA_REQUEST_PENDING) {
484             s->post_handshake_auth = SSL_PHA_REQUESTED;
485             st->hand_state = TLS_ST_OK;
486         } else {
487             st->hand_state = TLS_ST_SW_CERT;
488         }
489         return WRITE_TRAN_CONTINUE;
490
491     case TLS_ST_SW_CERT:
492         st->hand_state = TLS_ST_SW_CERT_VRFY;
493         return WRITE_TRAN_CONTINUE;
494
495     case TLS_ST_SW_CERT_VRFY:
496         st->hand_state = TLS_ST_SW_FINISHED;
497         return WRITE_TRAN_CONTINUE;
498
499     case TLS_ST_SW_FINISHED:
500         st->hand_state = TLS_ST_EARLY_DATA;
501         return WRITE_TRAN_CONTINUE;
502
503     case TLS_ST_EARLY_DATA:
504         return WRITE_TRAN_FINISHED;
505
506     case TLS_ST_SR_FINISHED:
507         /*
508          * Technically we have finished the handshake at this point, but we're
509          * going to remain "in_init" for now and write out any session tickets
510          * immediately.
511          */
512         if (s->post_handshake_auth == SSL_PHA_REQUESTED) {
513             s->post_handshake_auth = SSL_PHA_EXT_RECEIVED;
514         } else if (!s->ext.ticket_expected) {
515             /*
516              * If we're not going to renew the ticket then we just finish the
517              * handshake at this point.
518              */
519             st->hand_state = TLS_ST_OK;
520             return WRITE_TRAN_CONTINUE;
521         }
522         if (s->num_tickets > s->sent_tickets)
523             st->hand_state = TLS_ST_SW_SESSION_TICKET;
524         else
525             st->hand_state = TLS_ST_OK;
526         return WRITE_TRAN_CONTINUE;
527
528     case TLS_ST_SR_KEY_UPDATE:
529     case TLS_ST_SW_KEY_UPDATE:
530         st->hand_state = TLS_ST_OK;
531         return WRITE_TRAN_CONTINUE;
532
533     case TLS_ST_SW_SESSION_TICKET:
534         /* In a resumption we only ever send a maximum of one new ticket.
535          * Following an initial handshake we send the number of tickets we have
536          * been configured for.
537          */
538         if (!SSL_IS_FIRST_HANDSHAKE(s) && s->ext.extra_tickets_expected > 0) {
539             return WRITE_TRAN_CONTINUE;
540         } else if (s->hit || s->num_tickets <= s->sent_tickets) {
541             /* We've written enough tickets out. */
542             st->hand_state = TLS_ST_OK;
543         }
544         return WRITE_TRAN_CONTINUE;
545     }
546 }
547
548 /*
549  * ossl_statem_server_write_transition() works out what handshake state to move
550  * to next when the server is writing messages to be sent to the client.
551  */
552 WRITE_TRAN ossl_statem_server_write_transition(SSL *s)
553 {
554     OSSL_STATEM *st = &s->statem;
555
556     /*
557      * Note that before the ClientHello we don't know what version we are going
558      * to negotiate yet, so we don't take this branch until later
559      */
560
561     if (SSL_IS_TLS13(s))
562         return ossl_statem_server13_write_transition(s);
563
564     switch (st->hand_state) {
565     default:
566         /* Shouldn't happen */
567         SSLfatal(s, SSL_AD_INTERNAL_ERROR,
568                  SSL_F_OSSL_STATEM_SERVER_WRITE_TRANSITION,
569                  ERR_R_INTERNAL_ERROR);
570         return WRITE_TRAN_ERROR;
571
572     case TLS_ST_OK:
573         if (st->request_state == TLS_ST_SW_HELLO_REQ) {
574             /* We must be trying to renegotiate */
575             st->hand_state = TLS_ST_SW_HELLO_REQ;
576             st->request_state = TLS_ST_BEFORE;
577             return WRITE_TRAN_CONTINUE;
578         }
579         /* Must be an incoming ClientHello */
580         if (!tls_setup_handshake(s)) {
581             /* SSLfatal() already called */
582             return WRITE_TRAN_ERROR;
583         }
584         /* Fall through */
585
586     case TLS_ST_BEFORE:
587         /* Just go straight to trying to read from the client */
588         return WRITE_TRAN_FINISHED;
589
590     case TLS_ST_SW_HELLO_REQ:
591         st->hand_state = TLS_ST_OK;
592         return WRITE_TRAN_CONTINUE;
593
594     case TLS_ST_SR_CLNT_HELLO:
595         if (SSL_IS_DTLS(s) && !s->d1->cookie_verified
596             && (SSL_get_options(s) & SSL_OP_COOKIE_EXCHANGE)) {
597             st->hand_state = DTLS_ST_SW_HELLO_VERIFY_REQUEST;
598         } else if (s->renegotiate == 0 && !SSL_IS_FIRST_HANDSHAKE(s)) {
599             /* We must have rejected the renegotiation */
600             st->hand_state = TLS_ST_OK;
601             return WRITE_TRAN_CONTINUE;
602         } else {
603             st->hand_state = TLS_ST_SW_SRVR_HELLO;
604         }
605         return WRITE_TRAN_CONTINUE;
606
607     case DTLS_ST_SW_HELLO_VERIFY_REQUEST:
608         return WRITE_TRAN_FINISHED;
609
610     case TLS_ST_SW_SRVR_HELLO:
611         if (s->hit) {
612             if (s->ext.ticket_expected)
613                 st->hand_state = TLS_ST_SW_SESSION_TICKET;
614             else
615                 st->hand_state = TLS_ST_SW_CHANGE;
616         } else {
617             /* Check if it is anon DH or anon ECDH, */
618             /* normal PSK or SRP */
619             if (!(s->s3.tmp.new_cipher->algorithm_auth &
620                   (SSL_aNULL | SSL_aSRP | SSL_aPSK))) {
621                 st->hand_state = TLS_ST_SW_CERT;
622             } else if (send_server_key_exchange(s)) {
623                 st->hand_state = TLS_ST_SW_KEY_EXCH;
624             } else if (send_certificate_request(s)) {
625                 st->hand_state = TLS_ST_SW_CERT_REQ;
626             } else {
627                 st->hand_state = TLS_ST_SW_SRVR_DONE;
628             }
629         }
630         return WRITE_TRAN_CONTINUE;
631
632     case TLS_ST_SW_CERT:
633         if (s->ext.status_expected) {
634             st->hand_state = TLS_ST_SW_CERT_STATUS;
635             return WRITE_TRAN_CONTINUE;
636         }
637         /* Fall through */
638
639     case TLS_ST_SW_CERT_STATUS:
640         if (send_server_key_exchange(s)) {
641             st->hand_state = TLS_ST_SW_KEY_EXCH;
642             return WRITE_TRAN_CONTINUE;
643         }
644         /* Fall through */
645
646     case TLS_ST_SW_KEY_EXCH:
647         if (send_certificate_request(s)) {
648             st->hand_state = TLS_ST_SW_CERT_REQ;
649             return WRITE_TRAN_CONTINUE;
650         }
651         /* Fall through */
652
653     case TLS_ST_SW_CERT_REQ:
654         st->hand_state = TLS_ST_SW_SRVR_DONE;
655         return WRITE_TRAN_CONTINUE;
656
657     case TLS_ST_SW_SRVR_DONE:
658         return WRITE_TRAN_FINISHED;
659
660     case TLS_ST_SR_FINISHED:
661         if (s->hit) {
662             st->hand_state = TLS_ST_OK;
663             return WRITE_TRAN_CONTINUE;
664         } else if (s->ext.ticket_expected) {
665             st->hand_state = TLS_ST_SW_SESSION_TICKET;
666         } else {
667             st->hand_state = TLS_ST_SW_CHANGE;
668         }
669         return WRITE_TRAN_CONTINUE;
670
671     case TLS_ST_SW_SESSION_TICKET:
672         st->hand_state = TLS_ST_SW_CHANGE;
673         return WRITE_TRAN_CONTINUE;
674
675     case TLS_ST_SW_CHANGE:
676         st->hand_state = TLS_ST_SW_FINISHED;
677         return WRITE_TRAN_CONTINUE;
678
679     case TLS_ST_SW_FINISHED:
680         if (s->hit) {
681             return WRITE_TRAN_FINISHED;
682         }
683         st->hand_state = TLS_ST_OK;
684         return WRITE_TRAN_CONTINUE;
685     }
686 }
687
688 /*
689  * Perform any pre work that needs to be done prior to sending a message from
690  * the server to the client.
691  */
692 WORK_STATE ossl_statem_server_pre_work(SSL *s, WORK_STATE wst)
693 {
694     OSSL_STATEM *st = &s->statem;
695
696     switch (st->hand_state) {
697     default:
698         /* No pre work to be done */
699         break;
700
701     case TLS_ST_SW_HELLO_REQ:
702         s->shutdown = 0;
703         if (SSL_IS_DTLS(s))
704             dtls1_clear_sent_buffer(s);
705         break;
706
707     case DTLS_ST_SW_HELLO_VERIFY_REQUEST:
708         s->shutdown = 0;
709         if (SSL_IS_DTLS(s)) {
710             dtls1_clear_sent_buffer(s);
711             /* We don't buffer this message so don't use the timer */
712             st->use_timer = 0;
713         }
714         break;
715
716     case TLS_ST_SW_SRVR_HELLO:
717         if (SSL_IS_DTLS(s)) {
718             /*
719              * Messages we write from now on should be buffered and
720              * retransmitted if necessary, so we need to use the timer now
721              */
722             st->use_timer = 1;
723         }
724         break;
725
726     case TLS_ST_SW_SRVR_DONE:
727 #ifndef OPENSSL_NO_SCTP
728         if (SSL_IS_DTLS(s) && BIO_dgram_is_sctp(SSL_get_wbio(s))) {
729             /* Calls SSLfatal() as required */
730             return dtls_wait_for_dry(s);
731         }
732 #endif
733         return WORK_FINISHED_CONTINUE;
734
735     case TLS_ST_SW_SESSION_TICKET:
736         if (SSL_IS_TLS13(s) && s->sent_tickets == 0
737                 && s->ext.extra_tickets_expected == 0) {
738             /*
739              * Actually this is the end of the handshake, but we're going
740              * straight into writing the session ticket out. So we finish off
741              * the handshake, but keep the various buffers active.
742              *
743              * Calls SSLfatal as required.
744              */
745             return tls_finish_handshake(s, wst, 0, 0);
746         }
747         if (SSL_IS_DTLS(s)) {
748             /*
749              * We're into the last flight. We don't retransmit the last flight
750              * unless we need to, so we don't use the timer
751              */
752             st->use_timer = 0;
753         }
754         break;
755
756     case TLS_ST_SW_CHANGE:
757         if (SSL_IS_TLS13(s))
758             break;
759         /* Writes to s->session are only safe for initial handshakes */
760         if (s->session->cipher == NULL) {
761             s->session->cipher = s->s3.tmp.new_cipher;
762         } else if (s->session->cipher != s->s3.tmp.new_cipher) {
763             SSLfatal(s, SSL_AD_INTERNAL_ERROR,
764                      SSL_F_OSSL_STATEM_SERVER_PRE_WORK,
765                      ERR_R_INTERNAL_ERROR);
766             return WORK_ERROR;
767         }
768         if (!s->method->ssl3_enc->setup_key_block(s)) {
769             /* SSLfatal() already called */
770             return WORK_ERROR;
771         }
772         if (SSL_IS_DTLS(s)) {
773             /*
774              * We're into the last flight. We don't retransmit the last flight
775              * unless we need to, so we don't use the timer. This might have
776              * already been set to 0 if we sent a NewSessionTicket message,
777              * but we'll set it again here in case we didn't.
778              */
779             st->use_timer = 0;
780         }
781         return WORK_FINISHED_CONTINUE;
782
783     case TLS_ST_EARLY_DATA:
784         if (s->early_data_state != SSL_EARLY_DATA_ACCEPTING
785                 && (s->s3.flags & TLS1_FLAGS_STATELESS) == 0)
786             return WORK_FINISHED_CONTINUE;
787         /* Fall through */
788
789     case TLS_ST_OK:
790         /* Calls SSLfatal() as required */
791         return tls_finish_handshake(s, wst, 1, 1);
792     }
793
794     return WORK_FINISHED_CONTINUE;
795 }
796
797 static ossl_inline int conn_is_closed(void)
798 {
799     switch (get_last_sys_error()) {
800 #if defined(EPIPE)
801     case EPIPE:
802         return 1;
803 #endif
804 #if defined(ECONNRESET)
805     case ECONNRESET:
806         return 1;
807 #endif
808 #if defined(WSAECONNRESET)
809     case WSAECONNRESET:
810         return 1;
811 #endif
812     default:
813         return 0;
814     }
815 }
816
817 /*
818  * Perform any work that needs to be done after sending a message from the
819  * server to the client.
820  */
821 WORK_STATE ossl_statem_server_post_work(SSL *s, WORK_STATE wst)
822 {
823     OSSL_STATEM *st = &s->statem;
824
825     s->init_num = 0;
826
827     switch (st->hand_state) {
828     default:
829         /* No post work to be done */
830         break;
831
832     case TLS_ST_SW_HELLO_REQ:
833         if (statem_flush(s) != 1)
834             return WORK_MORE_A;
835         if (!ssl3_init_finished_mac(s)) {
836             /* SSLfatal() already called */
837             return WORK_ERROR;
838         }
839         break;
840
841     case DTLS_ST_SW_HELLO_VERIFY_REQUEST:
842         if (statem_flush(s) != 1)
843             return WORK_MORE_A;
844         /* HelloVerifyRequest resets Finished MAC */
845         if (s->version != DTLS1_BAD_VER && !ssl3_init_finished_mac(s)) {
846             /* SSLfatal() already called */
847             return WORK_ERROR;
848         }
849         /*
850          * The next message should be another ClientHello which we need to
851          * treat like it was the first packet
852          */
853         s->first_packet = 1;
854         break;
855
856     case TLS_ST_SW_SRVR_HELLO:
857         if (SSL_IS_TLS13(s) && s->hello_retry_request == SSL_HRR_PENDING) {
858             if ((s->options & SSL_OP_ENABLE_MIDDLEBOX_COMPAT) == 0
859                     && statem_flush(s) != 1)
860                 return WORK_MORE_A;
861             break;
862         }
863 #ifndef OPENSSL_NO_SCTP
864         if (SSL_IS_DTLS(s) && s->hit) {
865             unsigned char sctpauthkey[64];
866             char labelbuffer[sizeof(DTLS1_SCTP_AUTH_LABEL)];
867             size_t labellen;
868
869             /*
870              * Add new shared key for SCTP-Auth, will be ignored if no
871              * SCTP used.
872              */
873             memcpy(labelbuffer, DTLS1_SCTP_AUTH_LABEL,
874                    sizeof(DTLS1_SCTP_AUTH_LABEL));
875
876             /* Don't include the terminating zero. */
877             labellen = sizeof(labelbuffer) - 1;
878             if (s->mode & SSL_MODE_DTLS_SCTP_LABEL_LENGTH_BUG)
879                 labellen += 1;
880
881             if (SSL_export_keying_material(s, sctpauthkey,
882                                            sizeof(sctpauthkey), labelbuffer,
883                                            labellen, NULL, 0,
884                                            0) <= 0) {
885                 SSLfatal(s, SSL_AD_INTERNAL_ERROR,
886                          SSL_F_OSSL_STATEM_SERVER_POST_WORK,
887                          ERR_R_INTERNAL_ERROR);
888                 return WORK_ERROR;
889             }
890
891             BIO_ctrl(SSL_get_wbio(s), BIO_CTRL_DGRAM_SCTP_ADD_AUTH_KEY,
892                      sizeof(sctpauthkey), sctpauthkey);
893         }
894 #endif
895         if (!SSL_IS_TLS13(s)
896                 || ((s->options & SSL_OP_ENABLE_MIDDLEBOX_COMPAT) != 0
897                     && s->hello_retry_request != SSL_HRR_COMPLETE))
898             break;
899         /* Fall through */
900
901     case TLS_ST_SW_CHANGE:
902         if (s->hello_retry_request == SSL_HRR_PENDING) {
903             if (!statem_flush(s))
904                 return WORK_MORE_A;
905             break;
906         }
907
908         if (SSL_IS_TLS13(s)) {
909             if (!s->method->ssl3_enc->setup_key_block(s)
910                 || !s->method->ssl3_enc->change_cipher_state(s,
911                         SSL3_CC_HANDSHAKE | SSL3_CHANGE_CIPHER_SERVER_WRITE)) {
912                 /* SSLfatal() already called */
913                 return WORK_ERROR;
914             }
915
916             if (s->ext.early_data != SSL_EARLY_DATA_ACCEPTED
917                 && !s->method->ssl3_enc->change_cipher_state(s,
918                         SSL3_CC_HANDSHAKE |SSL3_CHANGE_CIPHER_SERVER_READ)) {
919                 /* SSLfatal() already called */
920                 return WORK_ERROR;
921             }
922             /*
923              * We don't yet know whether the next record we are going to receive
924              * is an unencrypted alert, an encrypted alert, or an encrypted
925              * handshake message. We temporarily tolerate unencrypted alerts.
926              */
927             s->statem.enc_read_state = ENC_READ_STATE_ALLOW_PLAIN_ALERTS;
928             break;
929         }
930
931 #ifndef OPENSSL_NO_SCTP
932         if (SSL_IS_DTLS(s) && !s->hit) {
933             /*
934              * Change to new shared key of SCTP-Auth, will be ignored if
935              * no SCTP used.
936              */
937             BIO_ctrl(SSL_get_wbio(s), BIO_CTRL_DGRAM_SCTP_NEXT_AUTH_KEY,
938                      0, NULL);
939         }
940 #endif
941         if (!s->method->ssl3_enc->change_cipher_state(s,
942                                                       SSL3_CHANGE_CIPHER_SERVER_WRITE))
943         {
944             /* SSLfatal() already called */
945             return WORK_ERROR;
946         }
947
948         if (SSL_IS_DTLS(s))
949             dtls1_reset_seq_numbers(s, SSL3_CC_WRITE);
950         break;
951
952     case TLS_ST_SW_SRVR_DONE:
953         if (statem_flush(s) != 1)
954             return WORK_MORE_A;
955         break;
956
957     case TLS_ST_SW_FINISHED:
958         if (statem_flush(s) != 1)
959             return WORK_MORE_A;
960 #ifndef OPENSSL_NO_SCTP
961         if (SSL_IS_DTLS(s) && s->hit) {
962             /*
963              * Change to new shared key of SCTP-Auth, will be ignored if
964              * no SCTP used.
965              */
966             BIO_ctrl(SSL_get_wbio(s), BIO_CTRL_DGRAM_SCTP_NEXT_AUTH_KEY,
967                      0, NULL);
968         }
969 #endif
970         if (SSL_IS_TLS13(s)) {
971             /* TLS 1.3 gets the secret size from the handshake md */
972             size_t dummy;
973             if (!s->method->ssl3_enc->generate_master_secret(s,
974                         s->master_secret, s->handshake_secret, 0,
975                         &dummy)
976                 || !s->method->ssl3_enc->change_cipher_state(s,
977                         SSL3_CC_APPLICATION | SSL3_CHANGE_CIPHER_SERVER_WRITE))
978             /* SSLfatal() already called */
979             return WORK_ERROR;
980         }
981         break;
982
983     case TLS_ST_SW_CERT_REQ:
984         if (s->post_handshake_auth == SSL_PHA_REQUEST_PENDING) {
985             if (statem_flush(s) != 1)
986                 return WORK_MORE_A;
987         }
988         break;
989
990     case TLS_ST_SW_KEY_UPDATE:
991         if (statem_flush(s) != 1)
992             return WORK_MORE_A;
993         if (!tls13_update_key(s, 1)) {
994             /* SSLfatal() already called */
995             return WORK_ERROR;
996         }
997         break;
998
999     case TLS_ST_SW_SESSION_TICKET:
1000         clear_sys_error();
1001         if (SSL_IS_TLS13(s) && statem_flush(s) != 1) {
1002             if (SSL_get_error(s, 0) == SSL_ERROR_SYSCALL
1003                     && conn_is_closed()) {
1004                 /*
1005                  * We ignore connection closed errors in TLSv1.3 when sending a
1006                  * NewSessionTicket and behave as if we were successful. This is
1007                  * so that we are still able to read data sent to us by a client
1008                  * that closes soon after the end of the handshake without
1009                  * waiting to read our post-handshake NewSessionTickets.
1010                  */
1011                 s->rwstate = SSL_NOTHING;
1012                 break;
1013             }
1014
1015             return WORK_MORE_A;
1016         }
1017         break;
1018     }
1019
1020     return WORK_FINISHED_CONTINUE;
1021 }
1022
1023 /*
1024  * Get the message construction function and message type for sending from the
1025  * server
1026  *
1027  * Valid return values are:
1028  *   1: Success
1029  *   0: Error
1030  */
1031 int ossl_statem_server_construct_message(SSL *s, WPACKET *pkt,
1032                                          confunc_f *confunc, int *mt)
1033 {
1034     OSSL_STATEM *st = &s->statem;
1035
1036     switch (st->hand_state) {
1037     default:
1038         /* Shouldn't happen */
1039         SSLfatal(s, SSL_AD_INTERNAL_ERROR,
1040                  SSL_F_OSSL_STATEM_SERVER_CONSTRUCT_MESSAGE,
1041                  SSL_R_BAD_HANDSHAKE_STATE);
1042         return 0;
1043
1044     case TLS_ST_SW_CHANGE:
1045         if (SSL_IS_DTLS(s))
1046             *confunc = dtls_construct_change_cipher_spec;
1047         else
1048             *confunc = tls_construct_change_cipher_spec;
1049         *mt = SSL3_MT_CHANGE_CIPHER_SPEC;
1050         break;
1051
1052     case DTLS_ST_SW_HELLO_VERIFY_REQUEST:
1053         *confunc = dtls_construct_hello_verify_request;
1054         *mt = DTLS1_MT_HELLO_VERIFY_REQUEST;
1055         break;
1056
1057     case TLS_ST_SW_HELLO_REQ:
1058         /* No construction function needed */
1059         *confunc = NULL;
1060         *mt = SSL3_MT_HELLO_REQUEST;
1061         break;
1062
1063     case TLS_ST_SW_SRVR_HELLO:
1064         *confunc = tls_construct_server_hello;
1065         *mt = SSL3_MT_SERVER_HELLO;
1066         break;
1067
1068     case TLS_ST_SW_CERT:
1069         *confunc = tls_construct_server_certificate;
1070         *mt = SSL3_MT_CERTIFICATE;
1071         break;
1072
1073     case TLS_ST_SW_CERT_VRFY:
1074         *confunc = tls_construct_cert_verify;
1075         *mt = SSL3_MT_CERTIFICATE_VERIFY;
1076         break;
1077
1078
1079     case TLS_ST_SW_KEY_EXCH:
1080         *confunc = tls_construct_server_key_exchange;
1081         *mt = SSL3_MT_SERVER_KEY_EXCHANGE;
1082         break;
1083
1084     case TLS_ST_SW_CERT_REQ:
1085         *confunc = tls_construct_certificate_request;
1086         *mt = SSL3_MT_CERTIFICATE_REQUEST;
1087         break;
1088
1089     case TLS_ST_SW_SRVR_DONE:
1090         *confunc = tls_construct_server_done;
1091         *mt = SSL3_MT_SERVER_DONE;
1092         break;
1093
1094     case TLS_ST_SW_SESSION_TICKET:
1095         *confunc = tls_construct_new_session_ticket;
1096         *mt = SSL3_MT_NEWSESSION_TICKET;
1097         break;
1098
1099     case TLS_ST_SW_CERT_STATUS:
1100         *confunc = tls_construct_cert_status;
1101         *mt = SSL3_MT_CERTIFICATE_STATUS;
1102         break;
1103
1104     case TLS_ST_SW_FINISHED:
1105         *confunc = tls_construct_finished;
1106         *mt = SSL3_MT_FINISHED;
1107         break;
1108
1109     case TLS_ST_EARLY_DATA:
1110         *confunc = NULL;
1111         *mt = SSL3_MT_DUMMY;
1112         break;
1113
1114     case TLS_ST_SW_ENCRYPTED_EXTENSIONS:
1115         *confunc = tls_construct_encrypted_extensions;
1116         *mt = SSL3_MT_ENCRYPTED_EXTENSIONS;
1117         break;
1118
1119     case TLS_ST_SW_KEY_UPDATE:
1120         *confunc = tls_construct_key_update;
1121         *mt = SSL3_MT_KEY_UPDATE;
1122         break;
1123     }
1124
1125     return 1;
1126 }
1127
1128 /*
1129  * Maximum size (excluding the Handshake header) of a ClientHello message,
1130  * calculated as follows:
1131  *
1132  *  2 + # client_version
1133  *  32 + # only valid length for random
1134  *  1 + # length of session_id
1135  *  32 + # maximum size for session_id
1136  *  2 + # length of cipher suites
1137  *  2^16-2 + # maximum length of cipher suites array
1138  *  1 + # length of compression_methods
1139  *  2^8-1 + # maximum length of compression methods
1140  *  2 + # length of extensions
1141  *  2^16-1 # maximum length of extensions
1142  */
1143 #define CLIENT_HELLO_MAX_LENGTH         131396
1144
1145 #define CLIENT_KEY_EXCH_MAX_LENGTH      2048
1146 #define NEXT_PROTO_MAX_LENGTH           514
1147
1148 /*
1149  * Returns the maximum allowed length for the current message that we are
1150  * reading. Excludes the message header.
1151  */
1152 size_t ossl_statem_server_max_message_size(SSL *s)
1153 {
1154     OSSL_STATEM *st = &s->statem;
1155
1156     switch (st->hand_state) {
1157     default:
1158         /* Shouldn't happen */
1159         return 0;
1160
1161     case TLS_ST_SR_CLNT_HELLO:
1162         return CLIENT_HELLO_MAX_LENGTH;
1163
1164     case TLS_ST_SR_END_OF_EARLY_DATA:
1165         return END_OF_EARLY_DATA_MAX_LENGTH;
1166
1167     case TLS_ST_SR_CERT:
1168         return s->max_cert_list;
1169
1170     case TLS_ST_SR_KEY_EXCH:
1171         return CLIENT_KEY_EXCH_MAX_LENGTH;
1172
1173     case TLS_ST_SR_CERT_VRFY:
1174         return SSL3_RT_MAX_PLAIN_LENGTH;
1175
1176 #ifndef OPENSSL_NO_NEXTPROTONEG
1177     case TLS_ST_SR_NEXT_PROTO:
1178         return NEXT_PROTO_MAX_LENGTH;
1179 #endif
1180
1181     case TLS_ST_SR_CHANGE:
1182         return CCS_MAX_LENGTH;
1183
1184     case TLS_ST_SR_FINISHED:
1185         return FINISHED_MAX_LENGTH;
1186
1187     case TLS_ST_SR_KEY_UPDATE:
1188         return KEY_UPDATE_MAX_LENGTH;
1189     }
1190 }
1191
1192 /*
1193  * Process a message that the server has received from the client.
1194  */
1195 MSG_PROCESS_RETURN ossl_statem_server_process_message(SSL *s, PACKET *pkt)
1196 {
1197     OSSL_STATEM *st = &s->statem;
1198
1199     switch (st->hand_state) {
1200     default:
1201         /* Shouldn't happen */
1202         SSLfatal(s, SSL_AD_INTERNAL_ERROR,
1203                  SSL_F_OSSL_STATEM_SERVER_PROCESS_MESSAGE,
1204                  ERR_R_INTERNAL_ERROR);
1205         return MSG_PROCESS_ERROR;
1206
1207     case TLS_ST_SR_CLNT_HELLO:
1208         return tls_process_client_hello(s, pkt);
1209
1210     case TLS_ST_SR_END_OF_EARLY_DATA:
1211         return tls_process_end_of_early_data(s, pkt);
1212
1213     case TLS_ST_SR_CERT:
1214         return tls_process_client_certificate(s, pkt);
1215
1216     case TLS_ST_SR_KEY_EXCH:
1217         return tls_process_client_key_exchange(s, pkt);
1218
1219     case TLS_ST_SR_CERT_VRFY:
1220         return tls_process_cert_verify(s, pkt);
1221
1222 #ifndef OPENSSL_NO_NEXTPROTONEG
1223     case TLS_ST_SR_NEXT_PROTO:
1224         return tls_process_next_proto(s, pkt);
1225 #endif
1226
1227     case TLS_ST_SR_CHANGE:
1228         return tls_process_change_cipher_spec(s, pkt);
1229
1230     case TLS_ST_SR_FINISHED:
1231         return tls_process_finished(s, pkt);
1232
1233     case TLS_ST_SR_KEY_UPDATE:
1234         return tls_process_key_update(s, pkt);
1235
1236     }
1237 }
1238
1239 /*
1240  * Perform any further processing required following the receipt of a message
1241  * from the client
1242  */
1243 WORK_STATE ossl_statem_server_post_process_message(SSL *s, WORK_STATE wst)
1244 {
1245     OSSL_STATEM *st = &s->statem;
1246
1247     switch (st->hand_state) {
1248     default:
1249         /* Shouldn't happen */
1250         SSLfatal(s, SSL_AD_INTERNAL_ERROR,
1251                  SSL_F_OSSL_STATEM_SERVER_POST_PROCESS_MESSAGE,
1252                  ERR_R_INTERNAL_ERROR);
1253         return WORK_ERROR;
1254
1255     case TLS_ST_SR_CLNT_HELLO:
1256         return tls_post_process_client_hello(s, wst);
1257
1258     case TLS_ST_SR_KEY_EXCH:
1259         return tls_post_process_client_key_exchange(s, wst);
1260     }
1261 }
1262
1263 #ifndef OPENSSL_NO_SRP
1264 /* Returns 1 on success, 0 for retryable error, -1 for fatal error */
1265 static int ssl_check_srp_ext_ClientHello(SSL *s)
1266 {
1267     int ret;
1268     int al = SSL_AD_UNRECOGNIZED_NAME;
1269
1270     if ((s->s3.tmp.new_cipher->algorithm_mkey & SSL_kSRP) &&
1271         (s->srp_ctx.TLS_ext_srp_username_callback != NULL)) {
1272         if (s->srp_ctx.login == NULL) {
1273             /*
1274              * RFC 5054 says SHOULD reject, we do so if There is no srp
1275              * login name
1276              */
1277             SSLfatal(s, SSL_AD_UNKNOWN_PSK_IDENTITY,
1278                      SSL_F_SSL_CHECK_SRP_EXT_CLIENTHELLO,
1279                      SSL_R_PSK_IDENTITY_NOT_FOUND);
1280             return -1;
1281         } else {
1282             ret = SSL_srp_server_param_with_username(s, &al);
1283             if (ret < 0)
1284                 return 0;
1285             if (ret == SSL3_AL_FATAL) {
1286                 SSLfatal(s, al, SSL_F_SSL_CHECK_SRP_EXT_CLIENTHELLO,
1287                          al == SSL_AD_UNKNOWN_PSK_IDENTITY
1288                          ? SSL_R_PSK_IDENTITY_NOT_FOUND
1289                          : SSL_R_CLIENTHELLO_TLSEXT);
1290                 return -1;
1291             }
1292         }
1293     }
1294     return 1;
1295 }
1296 #endif
1297
1298 int dtls_raw_hello_verify_request(WPACKET *pkt, unsigned char *cookie,
1299                                   size_t cookie_len)
1300 {
1301     /* Always use DTLS 1.0 version: see RFC 6347 */
1302     if (!WPACKET_put_bytes_u16(pkt, DTLS1_VERSION)
1303             || !WPACKET_sub_memcpy_u8(pkt, cookie, cookie_len))
1304         return 0;
1305
1306     return 1;
1307 }
1308
1309 int dtls_construct_hello_verify_request(SSL *s, WPACKET *pkt)
1310 {
1311     unsigned int cookie_leni;
1312     if (s->ctx->app_gen_cookie_cb == NULL ||
1313         s->ctx->app_gen_cookie_cb(s, s->d1->cookie,
1314                                   &cookie_leni) == 0 ||
1315         cookie_leni > 255) {
1316         SSLfatal(s, SSL_AD_NO_ALERT, SSL_F_DTLS_CONSTRUCT_HELLO_VERIFY_REQUEST,
1317                  SSL_R_COOKIE_GEN_CALLBACK_FAILURE);
1318         return 0;
1319     }
1320     s->d1->cookie_len = cookie_leni;
1321
1322     if (!dtls_raw_hello_verify_request(pkt, s->d1->cookie,
1323                                               s->d1->cookie_len)) {
1324         SSLfatal(s, SSL_AD_NO_ALERT, SSL_F_DTLS_CONSTRUCT_HELLO_VERIFY_REQUEST,
1325                  ERR_R_INTERNAL_ERROR);
1326         return 0;
1327     }
1328
1329     return 1;
1330 }
1331
1332 #ifndef OPENSSL_NO_EC
1333 /*-
1334  * ssl_check_for_safari attempts to fingerprint Safari using OS X
1335  * SecureTransport using the TLS extension block in |hello|.
1336  * Safari, since 10.6, sends exactly these extensions, in this order:
1337  *   SNI,
1338  *   elliptic_curves
1339  *   ec_point_formats
1340  *   signature_algorithms (for TLSv1.2 only)
1341  *
1342  * We wish to fingerprint Safari because they broke ECDHE-ECDSA support in 10.8,
1343  * but they advertise support. So enabling ECDHE-ECDSA ciphers breaks them.
1344  * Sadly we cannot differentiate 10.6, 10.7 and 10.8.4 (which work), from
1345  * 10.8..10.8.3 (which don't work).
1346  */
1347 static void ssl_check_for_safari(SSL *s, const CLIENTHELLO_MSG *hello)
1348 {
1349     static const unsigned char kSafariExtensionsBlock[] = {
1350         0x00, 0x0a,             /* elliptic_curves extension */
1351         0x00, 0x08,             /* 8 bytes */
1352         0x00, 0x06,             /* 6 bytes of curve ids */
1353         0x00, 0x17,             /* P-256 */
1354         0x00, 0x18,             /* P-384 */
1355         0x00, 0x19,             /* P-521 */
1356
1357         0x00, 0x0b,             /* ec_point_formats */
1358         0x00, 0x02,             /* 2 bytes */
1359         0x01,                   /* 1 point format */
1360         0x00,                   /* uncompressed */
1361         /* The following is only present in TLS 1.2 */
1362         0x00, 0x0d,             /* signature_algorithms */
1363         0x00, 0x0c,             /* 12 bytes */
1364         0x00, 0x0a,             /* 10 bytes */
1365         0x05, 0x01,             /* SHA-384/RSA */
1366         0x04, 0x01,             /* SHA-256/RSA */
1367         0x02, 0x01,             /* SHA-1/RSA */
1368         0x04, 0x03,             /* SHA-256/ECDSA */
1369         0x02, 0x03,             /* SHA-1/ECDSA */
1370     };
1371     /* Length of the common prefix (first two extensions). */
1372     static const size_t kSafariCommonExtensionsLength = 18;
1373     unsigned int type;
1374     PACKET sni, tmppkt;
1375     size_t ext_len;
1376
1377     tmppkt = hello->extensions;
1378
1379     if (!PACKET_forward(&tmppkt, 2)
1380         || !PACKET_get_net_2(&tmppkt, &type)
1381         || !PACKET_get_length_prefixed_2(&tmppkt, &sni)) {
1382         return;
1383     }
1384
1385     if (type != TLSEXT_TYPE_server_name)
1386         return;
1387
1388     ext_len = TLS1_get_client_version(s) >= TLS1_2_VERSION ?
1389         sizeof(kSafariExtensionsBlock) : kSafariCommonExtensionsLength;
1390
1391     s->s3.is_probably_safari = PACKET_equal(&tmppkt, kSafariExtensionsBlock,
1392                                              ext_len);
1393 }
1394 #endif                          /* !OPENSSL_NO_EC */
1395
1396 MSG_PROCESS_RETURN tls_process_client_hello(SSL *s, PACKET *pkt)
1397 {
1398     /* |cookie| will only be initialized for DTLS. */
1399     PACKET session_id, compression, extensions, cookie;
1400     static const unsigned char null_compression = 0;
1401     CLIENTHELLO_MSG *clienthello = NULL;
1402
1403     /* Check if this is actually an unexpected renegotiation ClientHello */
1404     if (s->renegotiate == 0 && !SSL_IS_FIRST_HANDSHAKE(s)) {
1405         if (!ossl_assert(!SSL_IS_TLS13(s))) {
1406             SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_F_TLS_PROCESS_CLIENT_HELLO,
1407                      ERR_R_INTERNAL_ERROR);
1408             goto err;
1409         }
1410         if ((s->options & SSL_OP_NO_RENEGOTIATION) != 0
1411                 || (!s->s3.send_connection_binding
1412                     && (s->options
1413                         & SSL_OP_ALLOW_UNSAFE_LEGACY_RENEGOTIATION) == 0)) {
1414             ssl3_send_alert(s, SSL3_AL_WARNING, SSL_AD_NO_RENEGOTIATION);
1415             return MSG_PROCESS_FINISHED_READING;
1416         }
1417         s->renegotiate = 1;
1418         s->new_session = 1;
1419     }
1420
1421     clienthello = OPENSSL_zalloc(sizeof(*clienthello));
1422     if (clienthello == NULL) {
1423         SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_F_TLS_PROCESS_CLIENT_HELLO,
1424                  ERR_R_INTERNAL_ERROR);
1425         goto err;
1426     }
1427
1428     /*
1429      * First, parse the raw ClientHello data into the CLIENTHELLO_MSG structure.
1430      */
1431     clienthello->isv2 = RECORD_LAYER_is_sslv2_record(&s->rlayer);
1432     PACKET_null_init(&cookie);
1433
1434     if (clienthello->isv2) {
1435         unsigned int mt;
1436
1437         if (!SSL_IS_FIRST_HANDSHAKE(s)
1438                 || s->hello_retry_request != SSL_HRR_NONE) {
1439             SSLfatal(s, SSL_AD_UNEXPECTED_MESSAGE,
1440                      SSL_F_TLS_PROCESS_CLIENT_HELLO, SSL_R_UNEXPECTED_MESSAGE);
1441             goto err;
1442         }
1443
1444         /*-
1445          * An SSLv3/TLSv1 backwards-compatible CLIENT-HELLO in an SSLv2
1446          * header is sent directly on the wire, not wrapped as a TLS
1447          * record. Our record layer just processes the message length and passes
1448          * the rest right through. Its format is:
1449          * Byte  Content
1450          * 0-1   msg_length - decoded by the record layer
1451          * 2     msg_type - s->init_msg points here
1452          * 3-4   version
1453          * 5-6   cipher_spec_length
1454          * 7-8   session_id_length
1455          * 9-10  challenge_length
1456          * ...   ...
1457          */
1458
1459         if (!PACKET_get_1(pkt, &mt)
1460             || mt != SSL2_MT_CLIENT_HELLO) {
1461             /*
1462              * Should never happen. We should have tested this in the record
1463              * layer in order to have determined that this is a SSLv2 record
1464              * in the first place
1465              */
1466             SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_F_TLS_PROCESS_CLIENT_HELLO,
1467                      ERR_R_INTERNAL_ERROR);
1468             goto err;
1469         }
1470     }
1471
1472     if (!PACKET_get_net_2(pkt, &clienthello->legacy_version)) {
1473         SSLfatal(s, SSL_AD_DECODE_ERROR, SSL_F_TLS_PROCESS_CLIENT_HELLO,
1474                  SSL_R_LENGTH_TOO_SHORT);
1475         goto err;
1476     }
1477
1478     /* Parse the message and load client random. */
1479     if (clienthello->isv2) {
1480         /*
1481          * Handle an SSLv2 backwards compatible ClientHello
1482          * Note, this is only for SSLv3+ using the backward compatible format.
1483          * Real SSLv2 is not supported, and is rejected below.
1484          */
1485         unsigned int ciphersuite_len, session_id_len, challenge_len;
1486         PACKET challenge;
1487
1488         if (!PACKET_get_net_2(pkt, &ciphersuite_len)
1489             || !PACKET_get_net_2(pkt, &session_id_len)
1490             || !PACKET_get_net_2(pkt, &challenge_len)) {
1491             SSLfatal(s, SSL_AD_DECODE_ERROR, SSL_F_TLS_PROCESS_CLIENT_HELLO,
1492                      SSL_R_RECORD_LENGTH_MISMATCH);
1493             goto err;
1494         }
1495
1496         if (session_id_len > SSL_MAX_SSL_SESSION_ID_LENGTH) {
1497             SSLfatal(s, SSL_AD_ILLEGAL_PARAMETER,
1498                      SSL_F_TLS_PROCESS_CLIENT_HELLO, SSL_R_LENGTH_MISMATCH);
1499             goto err;
1500         }
1501
1502         if (!PACKET_get_sub_packet(pkt, &clienthello->ciphersuites,
1503                                    ciphersuite_len)
1504             || !PACKET_copy_bytes(pkt, clienthello->session_id, session_id_len)
1505             || !PACKET_get_sub_packet(pkt, &challenge, challenge_len)
1506             /* No extensions. */
1507             || PACKET_remaining(pkt) != 0) {
1508             SSLfatal(s, SSL_AD_DECODE_ERROR, SSL_F_TLS_PROCESS_CLIENT_HELLO,
1509                      SSL_R_RECORD_LENGTH_MISMATCH);
1510             goto err;
1511         }
1512         clienthello->session_id_len = session_id_len;
1513
1514         /* Load the client random and compression list. We use SSL3_RANDOM_SIZE
1515          * here rather than sizeof(clienthello->random) because that is the limit
1516          * for SSLv3 and it is fixed. It won't change even if
1517          * sizeof(clienthello->random) does.
1518          */
1519         challenge_len = challenge_len > SSL3_RANDOM_SIZE
1520                         ? SSL3_RANDOM_SIZE : challenge_len;
1521         memset(clienthello->random, 0, SSL3_RANDOM_SIZE);
1522         if (!PACKET_copy_bytes(&challenge,
1523                                clienthello->random + SSL3_RANDOM_SIZE -
1524                                challenge_len, challenge_len)
1525             /* Advertise only null compression. */
1526             || !PACKET_buf_init(&compression, &null_compression, 1)) {
1527             SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_F_TLS_PROCESS_CLIENT_HELLO,
1528                      ERR_R_INTERNAL_ERROR);
1529             goto err;
1530         }
1531
1532         PACKET_null_init(&clienthello->extensions);
1533     } else {
1534         /* Regular ClientHello. */
1535         if (!PACKET_copy_bytes(pkt, clienthello->random, SSL3_RANDOM_SIZE)
1536             || !PACKET_get_length_prefixed_1(pkt, &session_id)
1537             || !PACKET_copy_all(&session_id, clienthello->session_id,
1538                     SSL_MAX_SSL_SESSION_ID_LENGTH,
1539                     &clienthello->session_id_len)) {
1540             SSLfatal(s, SSL_AD_DECODE_ERROR, SSL_F_TLS_PROCESS_CLIENT_HELLO,
1541                      SSL_R_LENGTH_MISMATCH);
1542             goto err;
1543         }
1544
1545         if (SSL_IS_DTLS(s)) {
1546             if (!PACKET_get_length_prefixed_1(pkt, &cookie)) {
1547                 SSLfatal(s, SSL_AD_DECODE_ERROR, SSL_F_TLS_PROCESS_CLIENT_HELLO,
1548                          SSL_R_LENGTH_MISMATCH);
1549                 goto err;
1550             }
1551             if (!PACKET_copy_all(&cookie, clienthello->dtls_cookie,
1552                                  DTLS1_COOKIE_LENGTH,
1553                                  &clienthello->dtls_cookie_len)) {
1554                 SSLfatal(s, SSL_AD_INTERNAL_ERROR,
1555                          SSL_F_TLS_PROCESS_CLIENT_HELLO, ERR_R_INTERNAL_ERROR);
1556                 goto err;
1557             }
1558             /*
1559              * If we require cookies and this ClientHello doesn't contain one,
1560              * just return since we do not want to allocate any memory yet.
1561              * So check cookie length...
1562              */
1563             if (SSL_get_options(s) & SSL_OP_COOKIE_EXCHANGE) {
1564                 if (clienthello->dtls_cookie_len == 0) {
1565                     OPENSSL_free(clienthello);
1566                     return MSG_PROCESS_FINISHED_READING;
1567                 }
1568             }
1569         }
1570
1571         if (!PACKET_get_length_prefixed_2(pkt, &clienthello->ciphersuites)) {
1572             SSLfatal(s, SSL_AD_DECODE_ERROR, SSL_F_TLS_PROCESS_CLIENT_HELLO,
1573                      SSL_R_LENGTH_MISMATCH);
1574             goto err;
1575         }
1576
1577         if (!PACKET_get_length_prefixed_1(pkt, &compression)) {
1578             SSLfatal(s, SSL_AD_DECODE_ERROR, SSL_F_TLS_PROCESS_CLIENT_HELLO,
1579                      SSL_R_LENGTH_MISMATCH);
1580             goto err;
1581         }
1582
1583         /* Could be empty. */
1584         if (PACKET_remaining(pkt) == 0) {
1585             PACKET_null_init(&clienthello->extensions);
1586         } else {
1587             if (!PACKET_get_length_prefixed_2(pkt, &clienthello->extensions)
1588                     || PACKET_remaining(pkt) != 0) {
1589                 SSLfatal(s, SSL_AD_DECODE_ERROR, SSL_F_TLS_PROCESS_CLIENT_HELLO,
1590                          SSL_R_LENGTH_MISMATCH);
1591                 goto err;
1592             }
1593         }
1594     }
1595
1596     if (!PACKET_copy_all(&compression, clienthello->compressions,
1597                          MAX_COMPRESSIONS_SIZE,
1598                          &clienthello->compressions_len)) {
1599         SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_F_TLS_PROCESS_CLIENT_HELLO,
1600                  ERR_R_INTERNAL_ERROR);
1601         goto err;
1602     }
1603
1604     /* Preserve the raw extensions PACKET for later use */
1605     extensions = clienthello->extensions;
1606     if (!tls_collect_extensions(s, &extensions, SSL_EXT_CLIENT_HELLO,
1607                                 &clienthello->pre_proc_exts,
1608                                 &clienthello->pre_proc_exts_len, 1)) {
1609         /* SSLfatal already been called */
1610         goto err;
1611     }
1612     s->clienthello = clienthello;
1613
1614     return MSG_PROCESS_CONTINUE_PROCESSING;
1615
1616  err:
1617     if (clienthello != NULL)
1618         OPENSSL_free(clienthello->pre_proc_exts);
1619     OPENSSL_free(clienthello);
1620
1621     return MSG_PROCESS_ERROR;
1622 }
1623
1624 static int tls_early_post_process_client_hello(SSL *s)
1625 {
1626     unsigned int j;
1627     int i, al = SSL_AD_INTERNAL_ERROR;
1628     int protverr;
1629     size_t loop;
1630     unsigned long id;
1631 #ifndef OPENSSL_NO_COMP
1632     SSL_COMP *comp = NULL;
1633 #endif
1634     const SSL_CIPHER *c;
1635     STACK_OF(SSL_CIPHER) *ciphers = NULL;
1636     STACK_OF(SSL_CIPHER) *scsvs = NULL;
1637     CLIENTHELLO_MSG *clienthello = s->clienthello;
1638     DOWNGRADE dgrd = DOWNGRADE_NONE;
1639
1640     /* Finished parsing the ClientHello, now we can start processing it */
1641     /* Give the ClientHello callback a crack at things */
1642     if (s->ctx->client_hello_cb != NULL) {
1643         /* A failure in the ClientHello callback terminates the connection. */
1644         switch (s->ctx->client_hello_cb(s, &al, s->ctx->client_hello_cb_arg)) {
1645         case SSL_CLIENT_HELLO_SUCCESS:
1646             break;
1647         case SSL_CLIENT_HELLO_RETRY:
1648             s->rwstate = SSL_CLIENT_HELLO_CB;
1649             return -1;
1650         case SSL_CLIENT_HELLO_ERROR:
1651         default:
1652             SSLfatal(s, al,
1653                      SSL_F_TLS_EARLY_POST_PROCESS_CLIENT_HELLO,
1654                      SSL_R_CALLBACK_FAILED);
1655             goto err;
1656         }
1657     }
1658
1659     /* Set up the client_random */
1660     memcpy(s->s3.client_random, clienthello->random, SSL3_RANDOM_SIZE);
1661
1662     /* Choose the version */
1663
1664     if (clienthello->isv2) {
1665         if (clienthello->legacy_version == SSL2_VERSION
1666                 || (clienthello->legacy_version & 0xff00)
1667                    != (SSL3_VERSION_MAJOR << 8)) {
1668             /*
1669              * This is real SSLv2 or something completely unknown. We don't
1670              * support it.
1671              */
1672             SSLfatal(s, SSL_AD_PROTOCOL_VERSION,
1673                      SSL_F_TLS_EARLY_POST_PROCESS_CLIENT_HELLO,
1674                      SSL_R_UNKNOWN_PROTOCOL);
1675             goto err;
1676         }
1677         /* SSLv3/TLS */
1678         s->client_version = clienthello->legacy_version;
1679     }
1680     /*
1681      * Do SSL/TLS version negotiation if applicable. For DTLS we just check
1682      * versions are potentially compatible. Version negotiation comes later.
1683      */
1684     if (!SSL_IS_DTLS(s)) {
1685         protverr = ssl_choose_server_version(s, clienthello, &dgrd);
1686     } else if (s->method->version != DTLS_ANY_VERSION &&
1687                DTLS_VERSION_LT((int)clienthello->legacy_version, s->version)) {
1688         protverr = SSL_R_VERSION_TOO_LOW;
1689     } else {
1690         protverr = 0;
1691     }
1692
1693     if (protverr) {
1694         if (SSL_IS_FIRST_HANDSHAKE(s)) {
1695             /* like ssl3_get_record, send alert using remote version number */
1696             s->version = s->client_version = clienthello->legacy_version;
1697         }
1698         SSLfatal(s, SSL_AD_PROTOCOL_VERSION,
1699                  SSL_F_TLS_EARLY_POST_PROCESS_CLIENT_HELLO, protverr);
1700         goto err;
1701     }
1702
1703     /* TLSv1.3 specifies that a ClientHello must end on a record boundary */
1704     if (SSL_IS_TLS13(s) && RECORD_LAYER_processed_read_pending(&s->rlayer)) {
1705         SSLfatal(s, SSL_AD_UNEXPECTED_MESSAGE,
1706                  SSL_F_TLS_EARLY_POST_PROCESS_CLIENT_HELLO,
1707                  SSL_R_NOT_ON_RECORD_BOUNDARY);
1708         goto err;
1709     }
1710
1711     if (SSL_IS_DTLS(s)) {
1712         /* Empty cookie was already handled above by returning early. */
1713         if (SSL_get_options(s) & SSL_OP_COOKIE_EXCHANGE) {
1714             if (s->ctx->app_verify_cookie_cb != NULL) {
1715                 if (s->ctx->app_verify_cookie_cb(s, clienthello->dtls_cookie,
1716                         clienthello->dtls_cookie_len) == 0) {
1717                     SSLfatal(s, SSL_AD_HANDSHAKE_FAILURE,
1718                              SSL_F_TLS_EARLY_POST_PROCESS_CLIENT_HELLO,
1719                              SSL_R_COOKIE_MISMATCH);
1720                     goto err;
1721                     /* else cookie verification succeeded */
1722                 }
1723                 /* default verification */
1724             } else if (s->d1->cookie_len != clienthello->dtls_cookie_len
1725                     || memcmp(clienthello->dtls_cookie, s->d1->cookie,
1726                               s->d1->cookie_len) != 0) {
1727                 SSLfatal(s, SSL_AD_HANDSHAKE_FAILURE,
1728                          SSL_F_TLS_EARLY_POST_PROCESS_CLIENT_HELLO,
1729                          SSL_R_COOKIE_MISMATCH);
1730                 goto err;
1731             }
1732             s->d1->cookie_verified = 1;
1733         }
1734         if (s->method->version == DTLS_ANY_VERSION) {
1735             protverr = ssl_choose_server_version(s, clienthello, &dgrd);
1736             if (protverr != 0) {
1737                 s->version = s->client_version;
1738                 SSLfatal(s, SSL_AD_PROTOCOL_VERSION,
1739                          SSL_F_TLS_EARLY_POST_PROCESS_CLIENT_HELLO, protverr);
1740                 goto err;
1741             }
1742         }
1743     }
1744
1745     s->hit = 0;
1746
1747     if (!ssl_cache_cipherlist(s, &clienthello->ciphersuites,
1748                               clienthello->isv2) ||
1749         !bytes_to_cipher_list(s, &clienthello->ciphersuites, &ciphers, &scsvs,
1750                               clienthello->isv2, 1)) {
1751         /* SSLfatal() already called */
1752         goto err;
1753     }
1754
1755     s->s3.send_connection_binding = 0;
1756     /* Check what signalling cipher-suite values were received. */
1757     if (scsvs != NULL) {
1758         for(i = 0; i < sk_SSL_CIPHER_num(scsvs); i++) {
1759             c = sk_SSL_CIPHER_value(scsvs, i);
1760             if (SSL_CIPHER_get_id(c) == SSL3_CK_SCSV) {
1761                 if (s->renegotiate) {
1762                     /* SCSV is fatal if renegotiating */
1763                     SSLfatal(s, SSL_AD_HANDSHAKE_FAILURE,
1764                              SSL_F_TLS_EARLY_POST_PROCESS_CLIENT_HELLO,
1765                              SSL_R_SCSV_RECEIVED_WHEN_RENEGOTIATING);
1766                     goto err;
1767                 }
1768                 s->s3.send_connection_binding = 1;
1769             } else if (SSL_CIPHER_get_id(c) == SSL3_CK_FALLBACK_SCSV &&
1770                        !ssl_check_version_downgrade(s)) {
1771                 /*
1772                  * This SCSV indicates that the client previously tried
1773                  * a higher version.  We should fail if the current version
1774                  * is an unexpected downgrade, as that indicates that the first
1775                  * connection may have been tampered with in order to trigger
1776                  * an insecure downgrade.
1777                  */
1778                 SSLfatal(s, SSL_AD_INAPPROPRIATE_FALLBACK,
1779                          SSL_F_TLS_EARLY_POST_PROCESS_CLIENT_HELLO,
1780                          SSL_R_INAPPROPRIATE_FALLBACK);
1781                 goto err;
1782             }
1783         }
1784     }
1785
1786     /* For TLSv1.3 we must select the ciphersuite *before* session resumption */
1787     if (SSL_IS_TLS13(s)) {
1788         const SSL_CIPHER *cipher =
1789             ssl3_choose_cipher(s, ciphers, SSL_get_ciphers(s));
1790
1791         if (cipher == NULL) {
1792             SSLfatal(s, SSL_AD_HANDSHAKE_FAILURE,
1793                      SSL_F_TLS_EARLY_POST_PROCESS_CLIENT_HELLO,
1794                      SSL_R_NO_SHARED_CIPHER);
1795             goto err;
1796         }
1797         if (s->hello_retry_request == SSL_HRR_PENDING
1798                 && (s->s3.tmp.new_cipher == NULL
1799                     || s->s3.tmp.new_cipher->id != cipher->id)) {
1800             /*
1801              * A previous HRR picked a different ciphersuite to the one we
1802              * just selected. Something must have changed.
1803              */
1804             SSLfatal(s, SSL_AD_ILLEGAL_PARAMETER,
1805                      SSL_F_TLS_EARLY_POST_PROCESS_CLIENT_HELLO,
1806                      SSL_R_BAD_CIPHER);
1807             goto err;
1808         }
1809         s->s3.tmp.new_cipher = cipher;
1810     }
1811
1812     /* We need to do this before getting the session */
1813     if (!tls_parse_extension(s, TLSEXT_IDX_extended_master_secret,
1814                              SSL_EXT_CLIENT_HELLO,
1815                              clienthello->pre_proc_exts, NULL, 0)) {
1816         /* SSLfatal() already called */
1817         goto err;
1818     }
1819
1820     /*
1821      * We don't allow resumption in a backwards compatible ClientHello.
1822      * TODO(openssl-team): in TLS1.1+, session_id MUST be empty.
1823      *
1824      * Versions before 0.9.7 always allow clients to resume sessions in
1825      * renegotiation. 0.9.7 and later allow this by default, but optionally
1826      * ignore resumption requests with flag
1827      * SSL_OP_NO_SESSION_RESUMPTION_ON_RENEGOTIATION (it's a new flag rather
1828      * than a change to default behavior so that applications relying on
1829      * this for security won't even compile against older library versions).
1830      * 1.0.1 and later also have a function SSL_renegotiate_abbreviated() to
1831      * request renegotiation but not a new session (s->new_session remains
1832      * unset): for servers, this essentially just means that the
1833      * SSL_OP_NO_SESSION_RESUMPTION_ON_RENEGOTIATION setting will be
1834      * ignored.
1835      */
1836     if (clienthello->isv2 ||
1837         (s->new_session &&
1838          (s->options & SSL_OP_NO_SESSION_RESUMPTION_ON_RENEGOTIATION))) {
1839         if (!ssl_get_new_session(s, 1)) {
1840             /* SSLfatal() already called */
1841             goto err;
1842         }
1843     } else {
1844         i = ssl_get_prev_session(s, clienthello);
1845         if (i == 1) {
1846             /* previous session */
1847             s->hit = 1;
1848         } else if (i == -1) {
1849             /* SSLfatal() already called */
1850             goto err;
1851         } else {
1852             /* i == 0 */
1853             if (!ssl_get_new_session(s, 1)) {
1854                 /* SSLfatal() already called */
1855                 goto err;
1856             }
1857         }
1858     }
1859
1860     if (SSL_IS_TLS13(s)) {
1861         memcpy(s->tmp_session_id, s->clienthello->session_id,
1862                s->clienthello->session_id_len);
1863         s->tmp_session_id_len = s->clienthello->session_id_len;
1864     }
1865
1866     /*
1867      * If it is a hit, check that the cipher is in the list. In TLSv1.3 we check
1868      * ciphersuite compatibility with the session as part of resumption.
1869      */
1870     if (!SSL_IS_TLS13(s) && s->hit) {
1871         j = 0;
1872         id = s->session->cipher->id;
1873
1874         OSSL_TRACE_BEGIN(TLS_CIPHER) {
1875             BIO_printf(trc_out, "client sent %d ciphers\n",
1876                        sk_SSL_CIPHER_num(ciphers));
1877         }
1878         for (i = 0; i < sk_SSL_CIPHER_num(ciphers); i++) {
1879             c = sk_SSL_CIPHER_value(ciphers, i);
1880             if (trc_out != NULL)
1881                 BIO_printf(trc_out, "client [%2d of %2d]:%s\n", i,
1882                            sk_SSL_CIPHER_num(ciphers), SSL_CIPHER_get_name(c));
1883             if (c->id == id) {
1884                 j = 1;
1885                 break;
1886             }
1887         }
1888         if (j == 0) {
1889             /*
1890              * we need to have the cipher in the cipher list if we are asked
1891              * to reuse it
1892              */
1893             SSLfatal(s, SSL_AD_ILLEGAL_PARAMETER,
1894                      SSL_F_TLS_EARLY_POST_PROCESS_CLIENT_HELLO,
1895                      SSL_R_REQUIRED_CIPHER_MISSING);
1896             OSSL_TRACE_CANCEL(TLS_CIPHER);
1897             goto err;
1898         }
1899         OSSL_TRACE_END(TLS_CIPHER);
1900     }
1901
1902     for (loop = 0; loop < clienthello->compressions_len; loop++) {
1903         if (clienthello->compressions[loop] == 0)
1904             break;
1905     }
1906
1907     if (loop >= clienthello->compressions_len) {
1908         /* no compress */
1909         SSLfatal(s, SSL_AD_DECODE_ERROR,
1910                  SSL_F_TLS_EARLY_POST_PROCESS_CLIENT_HELLO,
1911                  SSL_R_NO_COMPRESSION_SPECIFIED);
1912         goto err;
1913     }
1914
1915 #ifndef OPENSSL_NO_EC
1916     if (s->options & SSL_OP_SAFARI_ECDHE_ECDSA_BUG)
1917         ssl_check_for_safari(s, clienthello);
1918 #endif                          /* !OPENSSL_NO_EC */
1919
1920     /* TLS extensions */
1921     if (!tls_parse_all_extensions(s, SSL_EXT_CLIENT_HELLO,
1922                                   clienthello->pre_proc_exts, NULL, 0, 1)) {
1923         /* SSLfatal() already called */
1924         goto err;
1925     }
1926
1927     /*
1928      * Check if we want to use external pre-shared secret for this handshake
1929      * for not reused session only. We need to generate server_random before
1930      * calling tls_session_secret_cb in order to allow SessionTicket
1931      * processing to use it in key derivation.
1932      */
1933     {
1934         unsigned char *pos;
1935         pos = s->s3.server_random;
1936         if (ssl_fill_hello_random(s, 1, pos, SSL3_RANDOM_SIZE, dgrd) <= 0) {
1937             SSLfatal(s, SSL_AD_INTERNAL_ERROR,
1938                      SSL_F_TLS_EARLY_POST_PROCESS_CLIENT_HELLO,
1939                      ERR_R_INTERNAL_ERROR);
1940             goto err;
1941         }
1942     }
1943
1944     if (!s->hit
1945             && s->version >= TLS1_VERSION
1946             && !SSL_IS_TLS13(s)
1947             && !SSL_IS_DTLS(s)
1948             && s->ext.session_secret_cb) {
1949         const SSL_CIPHER *pref_cipher = NULL;
1950         /*
1951          * s->session->master_key_length is a size_t, but this is an int for
1952          * backwards compat reasons
1953          */
1954         int master_key_length;
1955
1956         master_key_length = sizeof(s->session->master_key);
1957         if (s->ext.session_secret_cb(s, s->session->master_key,
1958                                      &master_key_length, ciphers,
1959                                      &pref_cipher,
1960                                      s->ext.session_secret_cb_arg)
1961                 && master_key_length > 0) {
1962             s->session->master_key_length = master_key_length;
1963             s->hit = 1;
1964             s->peer_ciphers = ciphers;
1965             s->session->verify_result = X509_V_OK;
1966
1967             ciphers = NULL;
1968
1969             /* check if some cipher was preferred by call back */
1970             if (pref_cipher == NULL)
1971                 pref_cipher = ssl3_choose_cipher(s, s->peer_ciphers,
1972                                                  SSL_get_ciphers(s));
1973             if (pref_cipher == NULL) {
1974                 SSLfatal(s, SSL_AD_HANDSHAKE_FAILURE,
1975                          SSL_F_TLS_EARLY_POST_PROCESS_CLIENT_HELLO,
1976                          SSL_R_NO_SHARED_CIPHER);
1977                 goto err;
1978             }
1979
1980             s->session->cipher = pref_cipher;
1981             sk_SSL_CIPHER_free(s->cipher_list);
1982             s->cipher_list = sk_SSL_CIPHER_dup(s->peer_ciphers);
1983             sk_SSL_CIPHER_free(s->cipher_list_by_id);
1984             s->cipher_list_by_id = sk_SSL_CIPHER_dup(s->peer_ciphers);
1985         }
1986     }
1987
1988     /*
1989      * Worst case, we will use the NULL compression, but if we have other
1990      * options, we will now look for them.  We have complen-1 compression
1991      * algorithms from the client, starting at q.
1992      */
1993     s->s3.tmp.new_compression = NULL;
1994     if (SSL_IS_TLS13(s)) {
1995         /*
1996          * We already checked above that the NULL compression method appears in
1997          * the list. Now we check there aren't any others (which is illegal in
1998          * a TLSv1.3 ClientHello.
1999          */
2000         if (clienthello->compressions_len != 1) {
2001             SSLfatal(s, SSL_AD_ILLEGAL_PARAMETER,
2002                      SSL_F_TLS_EARLY_POST_PROCESS_CLIENT_HELLO,
2003                      SSL_R_INVALID_COMPRESSION_ALGORITHM);
2004             goto err;
2005         }
2006     }
2007 #ifndef OPENSSL_NO_COMP
2008     /* This only happens if we have a cache hit */
2009     else if (s->session->compress_meth != 0) {
2010         int m, comp_id = s->session->compress_meth;
2011         unsigned int k;
2012         /* Perform sanity checks on resumed compression algorithm */
2013         /* Can't disable compression */
2014         if (!ssl_allow_compression(s)) {
2015             SSLfatal(s, SSL_AD_HANDSHAKE_FAILURE,
2016                      SSL_F_TLS_EARLY_POST_PROCESS_CLIENT_HELLO,
2017                      SSL_R_INCONSISTENT_COMPRESSION);
2018             goto err;
2019         }
2020         /* Look for resumed compression method */
2021         for (m = 0; m < sk_SSL_COMP_num(s->ctx->comp_methods); m++) {
2022             comp = sk_SSL_COMP_value(s->ctx->comp_methods, m);
2023             if (comp_id == comp->id) {
2024                 s->s3.tmp.new_compression = comp;
2025                 break;
2026             }
2027         }
2028         if (s->s3.tmp.new_compression == NULL) {
2029             SSLfatal(s, SSL_AD_HANDSHAKE_FAILURE,
2030                      SSL_F_TLS_EARLY_POST_PROCESS_CLIENT_HELLO,
2031                      SSL_R_INVALID_COMPRESSION_ALGORITHM);
2032             goto err;
2033         }
2034         /* Look for resumed method in compression list */
2035         for (k = 0; k < clienthello->compressions_len; k++) {
2036             if (clienthello->compressions[k] == comp_id)
2037                 break;
2038         }
2039         if (k >= clienthello->compressions_len) {
2040             SSLfatal(s, SSL_AD_ILLEGAL_PARAMETER,
2041                      SSL_F_TLS_EARLY_POST_PROCESS_CLIENT_HELLO,
2042                      SSL_R_REQUIRED_COMPRESSION_ALGORITHM_MISSING);
2043             goto err;
2044         }
2045     } else if (s->hit) {
2046         comp = NULL;
2047     } else if (ssl_allow_compression(s) && s->ctx->comp_methods) {
2048         /* See if we have a match */
2049         int m, nn, v, done = 0;
2050         unsigned int o;
2051
2052         nn = sk_SSL_COMP_num(s->ctx->comp_methods);
2053         for (m = 0; m < nn; m++) {
2054             comp = sk_SSL_COMP_value(s->ctx->comp_methods, m);
2055             v = comp->id;
2056             for (o = 0; o < clienthello->compressions_len; o++) {
2057                 if (v == clienthello->compressions[o]) {
2058                     done = 1;
2059                     break;
2060                 }
2061             }
2062             if (done)
2063                 break;
2064         }
2065         if (done)
2066             s->s3.tmp.new_compression = comp;
2067         else
2068             comp = NULL;
2069     }
2070 #else
2071     /*
2072      * If compression is disabled we'd better not try to resume a session
2073      * using compression.
2074      */
2075     if (s->session->compress_meth != 0) {
2076         SSLfatal(s, SSL_AD_HANDSHAKE_FAILURE,
2077                  SSL_F_TLS_EARLY_POST_PROCESS_CLIENT_HELLO,
2078                  SSL_R_INCONSISTENT_COMPRESSION);
2079         goto err;
2080     }
2081 #endif
2082
2083     /*
2084      * Given s->peer_ciphers and SSL_get_ciphers, we must pick a cipher
2085      */
2086
2087     if (!s->hit || SSL_IS_TLS13(s)) {
2088         sk_SSL_CIPHER_free(s->peer_ciphers);
2089         s->peer_ciphers = ciphers;
2090         if (ciphers == NULL) {
2091             SSLfatal(s, SSL_AD_INTERNAL_ERROR,
2092                      SSL_F_TLS_EARLY_POST_PROCESS_CLIENT_HELLO,
2093                      ERR_R_INTERNAL_ERROR);
2094             goto err;
2095         }
2096         ciphers = NULL;
2097     }
2098
2099     if (!s->hit) {
2100 #ifdef OPENSSL_NO_COMP
2101         s->session->compress_meth = 0;
2102 #else
2103         s->session->compress_meth = (comp == NULL) ? 0 : comp->id;
2104 #endif
2105         if (!tls1_set_server_sigalgs(s)) {
2106             /* SSLfatal() already called */
2107             goto err;
2108         }
2109     }
2110
2111     sk_SSL_CIPHER_free(ciphers);
2112     sk_SSL_CIPHER_free(scsvs);
2113     OPENSSL_free(clienthello->pre_proc_exts);
2114     OPENSSL_free(s->clienthello);
2115     s->clienthello = NULL;
2116     return 1;
2117  err:
2118     sk_SSL_CIPHER_free(ciphers);
2119     sk_SSL_CIPHER_free(scsvs);
2120     OPENSSL_free(clienthello->pre_proc_exts);
2121     OPENSSL_free(s->clienthello);
2122     s->clienthello = NULL;
2123
2124     return 0;
2125 }
2126
2127 /*
2128  * Call the status request callback if needed. Upon success, returns 1.
2129  * Upon failure, returns 0.
2130  */
2131 static int tls_handle_status_request(SSL *s)
2132 {
2133     s->ext.status_expected = 0;
2134
2135     /*
2136      * If status request then ask callback what to do. Note: this must be
2137      * called after servername callbacks in case the certificate has changed,
2138      * and must be called after the cipher has been chosen because this may
2139      * influence which certificate is sent
2140      */
2141     if (s->ext.status_type != TLSEXT_STATUSTYPE_nothing && s->ctx != NULL
2142             && s->ctx->ext.status_cb != NULL) {
2143         int ret;
2144
2145         /* If no certificate can't return certificate status */
2146         if (s->s3.tmp.cert != NULL) {
2147             /*
2148              * Set current certificate to one we will use so SSL_get_certificate
2149              * et al can pick it up.
2150              */
2151             s->cert->key = s->s3.tmp.cert;
2152             ret = s->ctx->ext.status_cb(s, s->ctx->ext.status_arg);
2153             switch (ret) {
2154                 /* We don't want to send a status request response */
2155             case SSL_TLSEXT_ERR_NOACK:
2156                 s->ext.status_expected = 0;
2157                 break;
2158                 /* status request response should be sent */
2159             case SSL_TLSEXT_ERR_OK:
2160                 if (s->ext.ocsp.resp)
2161                     s->ext.status_expected = 1;
2162                 break;
2163                 /* something bad happened */
2164             case SSL_TLSEXT_ERR_ALERT_FATAL:
2165             default:
2166                 SSLfatal(s, SSL_AD_INTERNAL_ERROR,
2167                          SSL_F_TLS_HANDLE_STATUS_REQUEST,
2168                          SSL_R_CLIENTHELLO_TLSEXT);
2169                 return 0;
2170             }
2171         }
2172     }
2173
2174     return 1;
2175 }
2176
2177 /*
2178  * Call the alpn_select callback if needed. Upon success, returns 1.
2179  * Upon failure, returns 0.
2180  */
2181 int tls_handle_alpn(SSL *s)
2182 {
2183     const unsigned char *selected = NULL;
2184     unsigned char selected_len = 0;
2185
2186     if (s->ctx->ext.alpn_select_cb != NULL && s->s3.alpn_proposed != NULL) {
2187         int r = s->ctx->ext.alpn_select_cb(s, &selected, &selected_len,
2188                                            s->s3.alpn_proposed,
2189                                            (unsigned int)s->s3.alpn_proposed_len,
2190                                            s->ctx->ext.alpn_select_cb_arg);
2191
2192         if (r == SSL_TLSEXT_ERR_OK) {
2193             OPENSSL_free(s->s3.alpn_selected);
2194             s->s3.alpn_selected = OPENSSL_memdup(selected, selected_len);
2195             if (s->s3.alpn_selected == NULL) {
2196                 SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_F_TLS_HANDLE_ALPN,
2197                          ERR_R_INTERNAL_ERROR);
2198                 return 0;
2199             }
2200             s->s3.alpn_selected_len = selected_len;
2201 #ifndef OPENSSL_NO_NEXTPROTONEG
2202             /* ALPN takes precedence over NPN. */
2203             s->s3.npn_seen = 0;
2204 #endif
2205
2206             /* Check ALPN is consistent with session */
2207             if (s->session->ext.alpn_selected == NULL
2208                         || selected_len != s->session->ext.alpn_selected_len
2209                         || memcmp(selected, s->session->ext.alpn_selected,
2210                                   selected_len) != 0) {
2211                 /* Not consistent so can't be used for early_data */
2212                 s->ext.early_data_ok = 0;
2213
2214                 if (!s->hit) {
2215                     /*
2216                      * This is a new session and so alpn_selected should have
2217                      * been initialised to NULL. We should update it with the
2218                      * selected ALPN.
2219                      */
2220                     if (!ossl_assert(s->session->ext.alpn_selected == NULL)) {
2221                         SSLfatal(s, SSL_AD_INTERNAL_ERROR,
2222                                  SSL_F_TLS_HANDLE_ALPN,
2223                                  ERR_R_INTERNAL_ERROR);
2224                         return 0;
2225                     }
2226                     s->session->ext.alpn_selected = OPENSSL_memdup(selected,
2227                                                                    selected_len);
2228                     if (s->session->ext.alpn_selected == NULL) {
2229                         SSLfatal(s, SSL_AD_INTERNAL_ERROR,
2230                                  SSL_F_TLS_HANDLE_ALPN,
2231                                  ERR_R_INTERNAL_ERROR);
2232                         return 0;
2233                     }
2234                     s->session->ext.alpn_selected_len = selected_len;
2235                 }
2236             }
2237
2238             return 1;
2239         } else if (r != SSL_TLSEXT_ERR_NOACK) {
2240             SSLfatal(s, SSL_AD_NO_APPLICATION_PROTOCOL, SSL_F_TLS_HANDLE_ALPN,
2241                      SSL_R_NO_APPLICATION_PROTOCOL);
2242             return 0;
2243         }
2244         /*
2245          * If r == SSL_TLSEXT_ERR_NOACK then behave as if no callback was
2246          * present.
2247          */
2248     }
2249
2250     /* Check ALPN is consistent with session */
2251     if (s->session->ext.alpn_selected != NULL) {
2252         /* Not consistent so can't be used for early_data */
2253         s->ext.early_data_ok = 0;
2254     }
2255
2256     return 1;
2257 }
2258
2259 WORK_STATE tls_post_process_client_hello(SSL *s, WORK_STATE wst)
2260 {
2261     const SSL_CIPHER *cipher;
2262
2263     if (wst == WORK_MORE_A) {
2264         int rv = tls_early_post_process_client_hello(s);
2265         if (rv == 0) {
2266             /* SSLfatal() was already called */
2267             goto err;
2268         }
2269         if (rv < 0)
2270             return WORK_MORE_A;
2271         wst = WORK_MORE_B;
2272     }
2273     if (wst == WORK_MORE_B) {
2274         if (!s->hit || SSL_IS_TLS13(s)) {
2275             /* Let cert callback update server certificates if required */
2276             if (!s->hit && s->cert->cert_cb != NULL) {
2277                 int rv = s->cert->cert_cb(s, s->cert->cert_cb_arg);
2278                 if (rv == 0) {
2279                     SSLfatal(s, SSL_AD_INTERNAL_ERROR,
2280                              SSL_F_TLS_POST_PROCESS_CLIENT_HELLO,
2281                              SSL_R_CERT_CB_ERROR);
2282                     goto err;
2283                 }
2284                 if (rv < 0) {
2285                     s->rwstate = SSL_X509_LOOKUP;
2286                     return WORK_MORE_B;
2287                 }
2288                 s->rwstate = SSL_NOTHING;
2289             }
2290
2291             /* In TLSv1.3 we selected the ciphersuite before resumption */
2292             if (!SSL_IS_TLS13(s)) {
2293                 cipher =
2294                     ssl3_choose_cipher(s, s->peer_ciphers, SSL_get_ciphers(s));
2295
2296                 if (cipher == NULL) {
2297                     SSLfatal(s, SSL_AD_HANDSHAKE_FAILURE,
2298                              SSL_F_TLS_POST_PROCESS_CLIENT_HELLO,
2299                              SSL_R_NO_SHARED_CIPHER);
2300                     goto err;
2301                 }
2302                 s->s3.tmp.new_cipher = cipher;
2303             }
2304             if (!s->hit) {
2305                 if (!tls_choose_sigalg(s, 1)) {
2306                     /* SSLfatal already called */
2307                     goto err;
2308                 }
2309                 /* check whether we should disable session resumption */
2310                 if (s->not_resumable_session_cb != NULL)
2311                     s->session->not_resumable =
2312                         s->not_resumable_session_cb(s,
2313                             ((s->s3.tmp.new_cipher->algorithm_mkey
2314                               & (SSL_kDHE | SSL_kECDHE)) != 0));
2315                 if (s->session->not_resumable)
2316                     /* do not send a session ticket */
2317                     s->ext.ticket_expected = 0;
2318             }
2319         } else {
2320             /* Session-id reuse */
2321             s->s3.tmp.new_cipher = s->session->cipher;
2322         }
2323
2324         /*-
2325          * we now have the following setup.
2326          * client_random
2327          * cipher_list          - our preferred list of ciphers
2328          * ciphers              - the clients preferred list of ciphers
2329          * compression          - basically ignored right now
2330          * ssl version is set   - sslv3
2331          * s->session           - The ssl session has been setup.
2332          * s->hit               - session reuse flag
2333          * s->s3.tmp.new_cipher - the new cipher to use.
2334          */
2335
2336         /*
2337          * Call status_request callback if needed. Has to be done after the
2338          * certificate callbacks etc above.
2339          */
2340         if (!tls_handle_status_request(s)) {
2341             /* SSLfatal() already called */
2342             goto err;
2343         }
2344         /*
2345          * Call alpn_select callback if needed.  Has to be done after SNI and
2346          * cipher negotiation (HTTP/2 restricts permitted ciphers). In TLSv1.3
2347          * we already did this because cipher negotiation happens earlier, and
2348          * we must handle ALPN before we decide whether to accept early_data.
2349          */
2350         if (!SSL_IS_TLS13(s) && !tls_handle_alpn(s)) {
2351             /* SSLfatal() already called */
2352             goto err;
2353         }
2354
2355         wst = WORK_MORE_C;
2356     }
2357 #ifndef OPENSSL_NO_SRP
2358     if (wst == WORK_MORE_C) {
2359         int ret;
2360         if ((ret = ssl_check_srp_ext_ClientHello(s)) == 0) {
2361             /*
2362              * callback indicates further work to be done
2363              */
2364             s->rwstate = SSL_X509_LOOKUP;
2365             return WORK_MORE_C;
2366         }
2367         if (ret < 0) {
2368             /* SSLfatal() already called */
2369             goto err;
2370         }
2371     }
2372 #endif
2373
2374     return WORK_FINISHED_STOP;
2375  err:
2376     return WORK_ERROR;
2377 }
2378
2379 int tls_construct_server_hello(SSL *s, WPACKET *pkt)
2380 {
2381     int compm;
2382     size_t sl, len;
2383     int version;
2384     unsigned char *session_id;
2385     int usetls13 = SSL_IS_TLS13(s) || s->hello_retry_request == SSL_HRR_PENDING;
2386
2387     version = usetls13 ? TLS1_2_VERSION : s->version;
2388     if (!WPACKET_put_bytes_u16(pkt, version)
2389                /*
2390                 * Random stuff. Filling of the server_random takes place in
2391                 * tls_process_client_hello()
2392                 */
2393             || !WPACKET_memcpy(pkt,
2394                                s->hello_retry_request == SSL_HRR_PENDING
2395                                    ? hrrrandom : s->s3.server_random,
2396                                SSL3_RANDOM_SIZE)) {
2397         SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_F_TLS_CONSTRUCT_SERVER_HELLO,
2398                  ERR_R_INTERNAL_ERROR);
2399         return 0;
2400     }
2401
2402     /*-
2403      * There are several cases for the session ID to send
2404      * back in the server hello:
2405      * - For session reuse from the session cache,
2406      *   we send back the old session ID.
2407      * - If stateless session reuse (using a session ticket)
2408      *   is successful, we send back the client's "session ID"
2409      *   (which doesn't actually identify the session).
2410      * - If it is a new session, we send back the new
2411      *   session ID.
2412      * - However, if we want the new session to be single-use,
2413      *   we send back a 0-length session ID.
2414      * - In TLSv1.3 we echo back the session id sent to us by the client
2415      *   regardless
2416      * s->hit is non-zero in either case of session reuse,
2417      * so the following won't overwrite an ID that we're supposed
2418      * to send back.
2419      */
2420     if (s->session->not_resumable ||
2421         (!(s->ctx->session_cache_mode & SSL_SESS_CACHE_SERVER)
2422          && !s->hit))
2423         s->session->session_id_length = 0;
2424
2425     if (usetls13) {
2426         sl = s->tmp_session_id_len;
2427         session_id = s->tmp_session_id;
2428     } else {
2429         sl = s->session->session_id_length;
2430         session_id = s->session->session_id;
2431     }
2432
2433     if (sl > sizeof(s->session->session_id)) {
2434         SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_F_TLS_CONSTRUCT_SERVER_HELLO,
2435                  ERR_R_INTERNAL_ERROR);
2436         return 0;
2437     }
2438
2439     /* set up the compression method */
2440 #ifdef OPENSSL_NO_COMP
2441     compm = 0;
2442 #else
2443     if (usetls13 || s->s3.tmp.new_compression == NULL)
2444         compm = 0;
2445     else
2446         compm = s->s3.tmp.new_compression->id;
2447 #endif
2448
2449     if (!WPACKET_sub_memcpy_u8(pkt, session_id, sl)
2450             || !s->method->put_cipher_by_char(s->s3.tmp.new_cipher, pkt, &len)
2451             || !WPACKET_put_bytes_u8(pkt, compm)) {
2452         SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_F_TLS_CONSTRUCT_SERVER_HELLO,
2453                  ERR_R_INTERNAL_ERROR);
2454         return 0;
2455     }
2456
2457     if (!tls_construct_extensions(s, pkt,
2458                                   s->hello_retry_request == SSL_HRR_PENDING
2459                                       ? SSL_EXT_TLS1_3_HELLO_RETRY_REQUEST
2460                                       : (SSL_IS_TLS13(s)
2461                                           ? SSL_EXT_TLS1_3_SERVER_HELLO
2462                                           : SSL_EXT_TLS1_2_SERVER_HELLO),
2463                                   NULL, 0)) {
2464         /* SSLfatal() already called */
2465         return 0;
2466     }
2467
2468     if (s->hello_retry_request == SSL_HRR_PENDING) {
2469         /* Ditch the session. We'll create a new one next time around */
2470         SSL_SESSION_free(s->session);
2471         s->session = NULL;
2472         s->hit = 0;
2473
2474         /*
2475          * Re-initialise the Transcript Hash. We're going to prepopulate it with
2476          * a synthetic message_hash in place of ClientHello1.
2477          */
2478         if (!create_synthetic_message_hash(s, NULL, 0, NULL, 0)) {
2479             /* SSLfatal() already called */
2480             return 0;
2481         }
2482     } else if (!(s->verify_mode & SSL_VERIFY_PEER)
2483                 && !ssl3_digest_cached_records(s, 0)) {
2484         /* SSLfatal() already called */;
2485         return 0;
2486     }
2487
2488     return 1;
2489 }
2490
2491 int tls_construct_server_done(SSL *s, WPACKET *pkt)
2492 {
2493     if (!s->s3.tmp.cert_request) {
2494         if (!ssl3_digest_cached_records(s, 0)) {
2495             /* SSLfatal() already called */
2496             return 0;
2497         }
2498     }
2499     return 1;
2500 }
2501
2502 int tls_construct_server_key_exchange(SSL *s, WPACKET *pkt)
2503 {
2504 #ifndef OPENSSL_NO_DH
2505     EVP_PKEY *pkdh = NULL;
2506 #endif
2507 #ifndef OPENSSL_NO_EC
2508     unsigned char *encodedPoint = NULL;
2509     size_t encodedlen = 0;
2510     int curve_id = 0;
2511 #endif
2512     const SIGALG_LOOKUP *lu = s->s3.tmp.sigalg;
2513     int i;
2514     unsigned long type;
2515     const BIGNUM *r[4];
2516     EVP_MD_CTX *md_ctx = EVP_MD_CTX_new();
2517     EVP_PKEY_CTX *pctx = NULL;
2518     size_t paramlen, paramoffset;
2519
2520     if (!WPACKET_get_total_written(pkt, &paramoffset)) {
2521         SSLfatal(s, SSL_AD_INTERNAL_ERROR,
2522                  SSL_F_TLS_CONSTRUCT_SERVER_KEY_EXCHANGE, ERR_R_INTERNAL_ERROR);
2523         goto err;
2524     }
2525
2526     if (md_ctx == NULL) {
2527         SSLfatal(s, SSL_AD_INTERNAL_ERROR,
2528                  SSL_F_TLS_CONSTRUCT_SERVER_KEY_EXCHANGE, ERR_R_MALLOC_FAILURE);
2529         goto err;
2530     }
2531
2532     type = s->s3.tmp.new_cipher->algorithm_mkey;
2533
2534     r[0] = r[1] = r[2] = r[3] = NULL;
2535 #ifndef OPENSSL_NO_PSK
2536     /* Plain PSK or RSAPSK nothing to do */
2537     if (type & (SSL_kPSK | SSL_kRSAPSK)) {
2538     } else
2539 #endif                          /* !OPENSSL_NO_PSK */
2540 #ifndef OPENSSL_NO_DH
2541     if (type & (SSL_kDHE | SSL_kDHEPSK)) {
2542         CERT *cert = s->cert;
2543
2544         EVP_PKEY *pkdhp = NULL;
2545         DH *dh;
2546
2547         if (s->cert->dh_tmp_auto) {
2548             DH *dhp = ssl_get_auto_dh(s);
2549             pkdh = EVP_PKEY_new();
2550             if (pkdh == NULL || dhp == NULL) {
2551                 DH_free(dhp);
2552                 SSLfatal(s, SSL_AD_INTERNAL_ERROR,
2553                          SSL_F_TLS_CONSTRUCT_SERVER_KEY_EXCHANGE,
2554                          ERR_R_INTERNAL_ERROR);
2555                 goto err;
2556             }
2557             EVP_PKEY_assign_DH(pkdh, dhp);
2558             pkdhp = pkdh;
2559         } else {
2560             pkdhp = cert->dh_tmp;
2561         }
2562         if ((pkdhp == NULL) && (s->cert->dh_tmp_cb != NULL)) {
2563             DH *dhp = s->cert->dh_tmp_cb(s, 0, 1024);
2564             pkdh = ssl_dh_to_pkey(dhp);
2565             if (pkdh == NULL) {
2566                 SSLfatal(s, SSL_AD_INTERNAL_ERROR,
2567                          SSL_F_TLS_CONSTRUCT_SERVER_KEY_EXCHANGE,
2568                          ERR_R_INTERNAL_ERROR);
2569                 goto err;
2570             }
2571             pkdhp = pkdh;
2572         }
2573         if (pkdhp == NULL) {
2574             SSLfatal(s, SSL_AD_INTERNAL_ERROR,
2575                      SSL_F_TLS_CONSTRUCT_SERVER_KEY_EXCHANGE,
2576                      SSL_R_MISSING_TMP_DH_KEY);
2577             goto err;
2578         }
2579         if (!ssl_security(s, SSL_SECOP_TMP_DH,
2580                           EVP_PKEY_security_bits(pkdhp), 0, pkdhp)) {
2581             SSLfatal(s, SSL_AD_HANDSHAKE_FAILURE,
2582                      SSL_F_TLS_CONSTRUCT_SERVER_KEY_EXCHANGE,
2583                      SSL_R_DH_KEY_TOO_SMALL);
2584             goto err;
2585         }
2586         if (s->s3.tmp.pkey != NULL) {
2587             SSLfatal(s, SSL_AD_INTERNAL_ERROR,
2588                      SSL_F_TLS_CONSTRUCT_SERVER_KEY_EXCHANGE,
2589                      ERR_R_INTERNAL_ERROR);
2590             goto err;
2591         }
2592
2593         s->s3.tmp.pkey = ssl_generate_pkey(s, pkdhp);
2594         if (s->s3.tmp.pkey == NULL) {
2595             /* SSLfatal() already called */
2596             goto err;
2597         }
2598
2599         dh = EVP_PKEY_get0_DH(s->s3.tmp.pkey);
2600         if (dh == NULL) {
2601             SSLfatal(s, SSL_AD_INTERNAL_ERROR,
2602                      SSL_F_TLS_CONSTRUCT_SERVER_KEY_EXCHANGE,
2603                      ERR_R_INTERNAL_ERROR);
2604             goto err;
2605         }
2606
2607         EVP_PKEY_free(pkdh);
2608         pkdh = NULL;
2609
2610         DH_get0_pqg(dh, &r[0], NULL, &r[1]);
2611         DH_get0_key(dh, &r[2], NULL);
2612     } else
2613 #endif
2614 #ifndef OPENSSL_NO_EC
2615     if (type & (SSL_kECDHE | SSL_kECDHEPSK)) {
2616
2617         if (s->s3.tmp.pkey != NULL) {
2618             SSLfatal(s, SSL_AD_INTERNAL_ERROR,
2619                      SSL_F_TLS_CONSTRUCT_SERVER_KEY_EXCHANGE,
2620                      ERR_R_INTERNAL_ERROR);
2621             goto err;
2622         }
2623
2624         /* Get NID of appropriate shared curve */
2625         curve_id = tls1_shared_group(s, -2);
2626         if (curve_id == 0) {
2627             SSLfatal(s, SSL_AD_HANDSHAKE_FAILURE,
2628                      SSL_F_TLS_CONSTRUCT_SERVER_KEY_EXCHANGE,
2629                      SSL_R_UNSUPPORTED_ELLIPTIC_CURVE);
2630             goto err;
2631         }
2632         s->s3.tmp.pkey = ssl_generate_pkey_group(s, curve_id);
2633         /* Generate a new key for this curve */
2634         if (s->s3.tmp.pkey == NULL) {
2635             /* SSLfatal() already called */
2636             goto err;
2637         }
2638
2639         /*
2640          * TODO(3.0) Remove this when EVP_PKEY_get1_tls_encodedpoint()
2641          * knows how to get a key from an encoded point with the help of
2642          * a OSSL_SERIALIZER deserializer.  We know that EVP_PKEY_get0()
2643          * downgrades an EVP_PKEY to contain a legacy key.
2644          *
2645          * THIS IS TEMPORARY
2646          */
2647         EVP_PKEY_get0(s->s3.tmp.pkey);
2648         if (EVP_PKEY_id(s->s3.tmp.pkey) == EVP_PKEY_NONE) {
2649             SSLfatal(s, SSL_AD_INTERNAL_ERROR, 0, ERR_R_EC_LIB);
2650             goto err;
2651         }
2652
2653         /* Encode the public key. */
2654         encodedlen = EVP_PKEY_get1_tls_encodedpoint(s->s3.tmp.pkey,
2655                                                     &encodedPoint);
2656         if (encodedlen == 0) {
2657             SSLfatal(s, SSL_AD_INTERNAL_ERROR,
2658                      SSL_F_TLS_CONSTRUCT_SERVER_KEY_EXCHANGE, ERR_R_EC_LIB);
2659             goto err;
2660         }
2661
2662         /*
2663          * We'll generate the serverKeyExchange message explicitly so we
2664          * can set these to NULLs
2665          */
2666         r[0] = NULL;
2667         r[1] = NULL;
2668         r[2] = NULL;
2669         r[3] = NULL;
2670     } else
2671 #endif                          /* !OPENSSL_NO_EC */
2672 #ifndef OPENSSL_NO_SRP
2673     if (type & SSL_kSRP) {
2674         if ((s->srp_ctx.N == NULL) ||
2675             (s->srp_ctx.g == NULL) ||
2676             (s->srp_ctx.s == NULL) || (s->srp_ctx.B == NULL)) {
2677             SSLfatal(s, SSL_AD_INTERNAL_ERROR,
2678                      SSL_F_TLS_CONSTRUCT_SERVER_KEY_EXCHANGE,
2679                      SSL_R_MISSING_SRP_PARAM);
2680             goto err;
2681         }
2682         r[0] = s->srp_ctx.N;
2683         r[1] = s->srp_ctx.g;
2684         r[2] = s->srp_ctx.s;
2685         r[3] = s->srp_ctx.B;
2686     } else
2687 #endif
2688     {
2689         SSLfatal(s, SSL_AD_INTERNAL_ERROR,
2690                  SSL_F_TLS_CONSTRUCT_SERVER_KEY_EXCHANGE,
2691                  SSL_R_UNKNOWN_KEY_EXCHANGE_TYPE);
2692         goto err;
2693     }
2694
2695     if (((s->s3.tmp.new_cipher->algorithm_auth & (SSL_aNULL | SSL_aSRP)) != 0)
2696         || ((s->s3.tmp.new_cipher->algorithm_mkey & SSL_PSK)) != 0) {
2697         lu = NULL;
2698     } else if (lu == NULL) {
2699         SSLfatal(s, SSL_AD_DECODE_ERROR,
2700                  SSL_F_TLS_CONSTRUCT_SERVER_KEY_EXCHANGE, ERR_R_INTERNAL_ERROR);
2701         goto err;
2702     }
2703
2704 #ifndef OPENSSL_NO_PSK
2705     if (type & SSL_PSK) {
2706         size_t len = (s->cert->psk_identity_hint == NULL)
2707                         ? 0 : strlen(s->cert->psk_identity_hint);
2708
2709         /*
2710          * It should not happen that len > PSK_MAX_IDENTITY_LEN - we already
2711          * checked this when we set the identity hint - but just in case
2712          */
2713         if (len > PSK_MAX_IDENTITY_LEN
2714                 || !WPACKET_sub_memcpy_u16(pkt, s->cert->psk_identity_hint,
2715                                            len)) {
2716             SSLfatal(s, SSL_AD_INTERNAL_ERROR,
2717                      SSL_F_TLS_CONSTRUCT_SERVER_KEY_EXCHANGE,
2718                      ERR_R_INTERNAL_ERROR);
2719             goto err;
2720         }
2721     }
2722 #endif
2723
2724     for (i = 0; i < 4 && r[i] != NULL; i++) {
2725         unsigned char *binval;
2726         int res;
2727
2728 #ifndef OPENSSL_NO_SRP
2729         if ((i == 2) && (type & SSL_kSRP)) {
2730             res = WPACKET_start_sub_packet_u8(pkt);
2731         } else
2732 #endif
2733             res = WPACKET_start_sub_packet_u16(pkt);
2734
2735         if (!res) {
2736             SSLfatal(s, SSL_AD_INTERNAL_ERROR,
2737                      SSL_F_TLS_CONSTRUCT_SERVER_KEY_EXCHANGE,
2738                      ERR_R_INTERNAL_ERROR);
2739             goto err;
2740         }
2741
2742 #ifndef OPENSSL_NO_DH
2743         /*-
2744          * for interoperability with some versions of the Microsoft TLS
2745          * stack, we need to zero pad the DHE pub key to the same length
2746          * as the prime
2747          */
2748         if ((i == 2) && (type & (SSL_kDHE | SSL_kDHEPSK))) {
2749             size_t len = BN_num_bytes(r[0]) - BN_num_bytes(r[2]);
2750
2751             if (len > 0) {
2752                 if (!WPACKET_allocate_bytes(pkt, len, &binval)) {
2753                     SSLfatal(s, SSL_AD_INTERNAL_ERROR,
2754                              SSL_F_TLS_CONSTRUCT_SERVER_KEY_EXCHANGE,
2755                              ERR_R_INTERNAL_ERROR);
2756                     goto err;
2757                 }
2758                 memset(binval, 0, len);
2759             }
2760         }
2761 #endif
2762         if (!WPACKET_allocate_bytes(pkt, BN_num_bytes(r[i]), &binval)
2763                 || !WPACKET_close(pkt)) {
2764             SSLfatal(s, SSL_AD_INTERNAL_ERROR,
2765                      SSL_F_TLS_CONSTRUCT_SERVER_KEY_EXCHANGE,
2766                      ERR_R_INTERNAL_ERROR);
2767             goto err;
2768         }
2769
2770         BN_bn2bin(r[i], binval);
2771     }
2772
2773 #ifndef OPENSSL_NO_EC
2774     if (type & (SSL_kECDHE | SSL_kECDHEPSK)) {
2775         /*
2776          * We only support named (not generic) curves. In this situation, the
2777          * ServerKeyExchange message has: [1 byte CurveType], [2 byte CurveName]
2778          * [1 byte length of encoded point], followed by the actual encoded
2779          * point itself
2780          */
2781         if (!WPACKET_put_bytes_u8(pkt, NAMED_CURVE_TYPE)
2782                 || !WPACKET_put_bytes_u8(pkt, 0)
2783                 || !WPACKET_put_bytes_u8(pkt, curve_id)
2784                 || !WPACKET_sub_memcpy_u8(pkt, encodedPoint, encodedlen)) {
2785             SSLfatal(s, SSL_AD_INTERNAL_ERROR,
2786                      SSL_F_TLS_CONSTRUCT_SERVER_KEY_EXCHANGE,
2787                      ERR_R_INTERNAL_ERROR);
2788             goto err;
2789         }
2790         OPENSSL_free(encodedPoint);
2791         encodedPoint = NULL;
2792     }
2793 #endif
2794
2795     /* not anonymous */
2796     if (lu != NULL) {
2797         EVP_PKEY *pkey = s->s3.tmp.cert->privatekey;
2798         const EVP_MD *md;
2799         unsigned char *sigbytes1, *sigbytes2, *tbs;
2800         size_t siglen = 0, tbslen;
2801
2802         if (pkey == NULL || !tls1_lookup_md(s->ctx, lu, &md)) {
2803             /* Should never happen */
2804             SSLfatal(s, SSL_AD_INTERNAL_ERROR,
2805                      SSL_F_TLS_CONSTRUCT_SERVER_KEY_EXCHANGE,
2806                      ERR_R_INTERNAL_ERROR);
2807             goto err;
2808         }
2809         /* Get length of the parameters we have written above */
2810         if (!WPACKET_get_length(pkt, &paramlen)) {
2811             SSLfatal(s, SSL_AD_INTERNAL_ERROR,
2812                      SSL_F_TLS_CONSTRUCT_SERVER_KEY_EXCHANGE,
2813                      ERR_R_INTERNAL_ERROR);
2814             goto err;
2815         }
2816         /* send signature algorithm */
2817         if (SSL_USE_SIGALGS(s) && !WPACKET_put_bytes_u16(pkt, lu->sigalg)) {
2818             SSLfatal(s, SSL_AD_INTERNAL_ERROR,
2819                      SSL_F_TLS_CONSTRUCT_SERVER_KEY_EXCHANGE,
2820                      ERR_R_INTERNAL_ERROR);
2821             goto err;
2822         }
2823
2824         if (EVP_DigestSignInit_ex(md_ctx, &pctx,
2825                                   md == NULL ? NULL : EVP_MD_name(md),
2826                                   s->ctx->propq, pkey, s->ctx->libctx) <= 0) {
2827             SSLfatal(s, SSL_AD_INTERNAL_ERROR,
2828                      SSL_F_TLS_CONSTRUCT_SERVER_KEY_EXCHANGE,
2829                      ERR_R_INTERNAL_ERROR);
2830             goto err;
2831         }
2832         if (lu->sig == EVP_PKEY_RSA_PSS) {
2833             if (EVP_PKEY_CTX_set_rsa_padding(pctx, RSA_PKCS1_PSS_PADDING) <= 0
2834                 || EVP_PKEY_CTX_set_rsa_pss_saltlen(pctx, RSA_PSS_SALTLEN_DIGEST) <= 0) {
2835                 SSLfatal(s, SSL_AD_INTERNAL_ERROR,
2836                          SSL_F_TLS_CONSTRUCT_SERVER_KEY_EXCHANGE,
2837                         ERR_R_EVP_LIB);
2838                 goto err;
2839             }
2840         }
2841         tbslen = construct_key_exchange_tbs(s, &tbs,
2842                                             s->init_buf->data + paramoffset,
2843                                             paramlen);
2844         if (tbslen == 0) {
2845             /* SSLfatal() already called */
2846             goto err;
2847         }
2848
2849         if (EVP_DigestSign(md_ctx, NULL, &siglen, tbs, tbslen) <=0
2850                 || !WPACKET_sub_reserve_bytes_u16(pkt, siglen, &sigbytes1)
2851                 || EVP_DigestSign(md_ctx, sigbytes1, &siglen, tbs, tbslen) <= 0
2852                 || !WPACKET_sub_allocate_bytes_u16(pkt, siglen, &sigbytes2)
2853                 || sigbytes1 != sigbytes2) {
2854             OPENSSL_free(tbs);
2855             SSLfatal(s, SSL_AD_INTERNAL_ERROR,
2856                      SSL_F_TLS_CONSTRUCT_SERVER_KEY_EXCHANGE,
2857                      ERR_R_INTERNAL_ERROR);
2858             goto err;
2859         }
2860         OPENSSL_free(tbs);
2861     }
2862
2863     EVP_MD_CTX_free(md_ctx);
2864     return 1;
2865  err:
2866 #ifndef OPENSSL_NO_DH
2867     EVP_PKEY_free(pkdh);
2868 #endif
2869 #ifndef OPENSSL_NO_EC
2870     OPENSSL_free(encodedPoint);
2871 #endif
2872     EVP_MD_CTX_free(md_ctx);
2873     return 0;
2874 }
2875
2876 int tls_construct_certificate_request(SSL *s, WPACKET *pkt)
2877 {
2878     if (SSL_IS_TLS13(s)) {
2879         /* Send random context when doing post-handshake auth */
2880         if (s->post_handshake_auth == SSL_PHA_REQUEST_PENDING) {
2881             OPENSSL_free(s->pha_context);
2882             s->pha_context_len = 32;
2883             if ((s->pha_context = OPENSSL_malloc(s->pha_context_len)) == NULL
2884                     || RAND_bytes_ex(s->ctx->libctx, s->pha_context,
2885                                      s->pha_context_len) <= 0
2886                     || !WPACKET_sub_memcpy_u8(pkt, s->pha_context, s->pha_context_len)) {
2887                 SSLfatal(s, SSL_AD_INTERNAL_ERROR,
2888                          SSL_F_TLS_CONSTRUCT_CERTIFICATE_REQUEST,
2889                          ERR_R_INTERNAL_ERROR);
2890                 return 0;
2891             }
2892             /* reset the handshake hash back to just after the ClientFinished */
2893             if (!tls13_restore_handshake_digest_for_pha(s)) {
2894                 /* SSLfatal() already called */
2895                 return 0;
2896             }
2897         } else {
2898             if (!WPACKET_put_bytes_u8(pkt, 0)) {
2899                 SSLfatal(s, SSL_AD_INTERNAL_ERROR,
2900                          SSL_F_TLS_CONSTRUCT_CERTIFICATE_REQUEST,
2901                          ERR_R_INTERNAL_ERROR);
2902                 return 0;
2903             }
2904         }
2905
2906         if (!tls_construct_extensions(s, pkt,
2907                                       SSL_EXT_TLS1_3_CERTIFICATE_REQUEST, NULL,
2908                                       0)) {
2909             /* SSLfatal() already called */
2910             return 0;
2911         }
2912         goto done;
2913     }
2914
2915     /* get the list of acceptable cert types */
2916     if (!WPACKET_start_sub_packet_u8(pkt)
2917         || !ssl3_get_req_cert_type(s, pkt) || !WPACKET_close(pkt)) {
2918         SSLfatal(s, SSL_AD_INTERNAL_ERROR,
2919                  SSL_F_TLS_CONSTRUCT_CERTIFICATE_REQUEST, ERR_R_INTERNAL_ERROR);
2920         return 0;
2921     }
2922
2923     if (SSL_USE_SIGALGS(s)) {
2924         const uint16_t *psigs;
2925         size_t nl = tls12_get_psigalgs(s, 1, &psigs);
2926
2927         if (!WPACKET_start_sub_packet_u16(pkt)
2928                 || !WPACKET_set_flags(pkt, WPACKET_FLAGS_NON_ZERO_LENGTH)
2929                 || !tls12_copy_sigalgs(s, pkt, psigs, nl)
2930                 || !WPACKET_close(pkt)) {
2931             SSLfatal(s, SSL_AD_INTERNAL_ERROR,
2932                      SSL_F_TLS_CONSTRUCT_CERTIFICATE_REQUEST,
2933                      ERR_R_INTERNAL_ERROR);
2934             return 0;
2935         }
2936     }
2937
2938     if (!construct_ca_names(s, get_ca_names(s), pkt)) {
2939         /* SSLfatal() already called */
2940         return 0;
2941     }
2942
2943  done:
2944     s->certreqs_sent++;
2945     s->s3.tmp.cert_request = 1;
2946     return 1;
2947 }
2948
2949 static int tls_process_cke_psk_preamble(SSL *s, PACKET *pkt)
2950 {
2951 #ifndef OPENSSL_NO_PSK
2952     unsigned char psk[PSK_MAX_PSK_LEN];
2953     size_t psklen;
2954     PACKET psk_identity;
2955
2956     if (!PACKET_get_length_prefixed_2(pkt, &psk_identity)) {
2957         SSLfatal(s, SSL_AD_DECODE_ERROR, SSL_F_TLS_PROCESS_CKE_PSK_PREAMBLE,
2958                  SSL_R_LENGTH_MISMATCH);
2959         return 0;
2960     }
2961     if (PACKET_remaining(&psk_identity) > PSK_MAX_IDENTITY_LEN) {
2962         SSLfatal(s, SSL_AD_DECODE_ERROR, SSL_F_TLS_PROCESS_CKE_PSK_PREAMBLE,
2963                  SSL_R_DATA_LENGTH_TOO_LONG);
2964         return 0;
2965     }
2966     if (s->psk_server_callback == NULL) {
2967         SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_F_TLS_PROCESS_CKE_PSK_PREAMBLE,
2968                  SSL_R_PSK_NO_SERVER_CB);
2969         return 0;
2970     }
2971
2972     if (!PACKET_strndup(&psk_identity, &s->session->psk_identity)) {
2973         SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_F_TLS_PROCESS_CKE_PSK_PREAMBLE,
2974                  ERR_R_INTERNAL_ERROR);
2975         return 0;
2976     }
2977
2978     psklen = s->psk_server_callback(s, s->session->psk_identity,
2979                                     psk, sizeof(psk));
2980
2981     if (psklen > PSK_MAX_PSK_LEN) {
2982         SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_F_TLS_PROCESS_CKE_PSK_PREAMBLE,
2983                  ERR_R_INTERNAL_ERROR);
2984         return 0;
2985     } else if (psklen == 0) {
2986         /*
2987          * PSK related to the given identity not found
2988          */
2989         SSLfatal(s, SSL_AD_UNKNOWN_PSK_IDENTITY,
2990                  SSL_F_TLS_PROCESS_CKE_PSK_PREAMBLE,
2991                  SSL_R_PSK_IDENTITY_NOT_FOUND);
2992         return 0;
2993     }
2994
2995     OPENSSL_free(s->s3.tmp.psk);
2996     s->s3.tmp.psk = OPENSSL_memdup(psk, psklen);
2997     OPENSSL_cleanse(psk, psklen);
2998
2999     if (s->s3.tmp.psk == NULL) {
3000         SSLfatal(s, SSL_AD_INTERNAL_ERROR,
3001                  SSL_F_TLS_PROCESS_CKE_PSK_PREAMBLE, ERR_R_MALLOC_FAILURE);
3002         return 0;
3003     }
3004
3005     s->s3.tmp.psklen = psklen;
3006
3007     return 1;
3008 #else
3009     /* Should never happen */
3010     SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_F_TLS_PROCESS_CKE_PSK_PREAMBLE,
3011              ERR_R_INTERNAL_ERROR);
3012     return 0;
3013 #endif
3014 }
3015
3016 static int tls_process_cke_rsa(SSL *s, PACKET *pkt)
3017 {
3018 #ifndef OPENSSL_NO_RSA
3019     size_t outlen;
3020     PACKET enc_premaster;
3021     EVP_PKEY *rsa = NULL;
3022     unsigned char *rsa_decrypt = NULL;
3023     int ret = 0;
3024     EVP_PKEY_CTX *ctx = NULL;
3025     OSSL_PARAM params[3], *p = params;
3026
3027     rsa = s->cert->pkeys[SSL_PKEY_RSA].privatekey;
3028     if (rsa == NULL) {
3029         SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_F_TLS_PROCESS_CKE_RSA,
3030                  SSL_R_MISSING_RSA_CERTIFICATE);
3031         return 0;
3032     }
3033
3034     /* SSLv3 and pre-standard DTLS omit the length bytes. */
3035     if (s->version == SSL3_VERSION || s->version == DTLS1_BAD_VER) {
3036         enc_premaster = *pkt;
3037     } else {
3038         if (!PACKET_get_length_prefixed_2(pkt, &enc_premaster)
3039             || PACKET_remaining(pkt) != 0) {
3040             SSLfatal(s, SSL_AD_DECODE_ERROR, SSL_F_TLS_PROCESS_CKE_RSA,
3041                      SSL_R_LENGTH_MISMATCH);
3042             return 0;
3043         }
3044     }
3045
3046     outlen = SSL_MAX_MASTER_KEY_LENGTH;
3047     rsa_decrypt = OPENSSL_malloc(outlen);
3048     if (rsa_decrypt == NULL) {
3049         SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_F_TLS_PROCESS_CKE_RSA,
3050                  ERR_R_MALLOC_FAILURE);
3051         return 0;
3052     }
3053
3054     ctx = EVP_PKEY_CTX_new_from_pkey(s->ctx->libctx, rsa, s->ctx->propq);
3055     if (ctx == NULL) {
3056         SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_F_TLS_PROCESS_CKE_RSA,
3057                  ERR_R_MALLOC_FAILURE);
3058         goto err;
3059     }
3060
3061     /*
3062      * We must not leak whether a decryption failure occurs because of
3063      * Bleichenbacher's attack on PKCS #1 v1.5 RSA padding (see RFC 2246,
3064      * section 7.4.7.1). We use the special padding type
3065      * RSA_PKCS1_WITH_TLS_PADDING to do that. It will automaticaly decrypt the
3066      * RSA, check the padding and check that the client version is as expected
3067      * in the premaster secret. If any of that fails then the function appears
3068      * to return successfully but with a random result. The call below could
3069      * still fail if the input is publicly invalid.
3070      * See https://tools.ietf.org/html/rfc5246#section-7.4.7.1
3071      */
3072     if (EVP_PKEY_decrypt_init(ctx) <= 0
3073             || EVP_PKEY_CTX_set_rsa_padding(ctx, RSA_PKCS1_WITH_TLS_PADDING) <= 0) {
3074         SSLfatal(s, SSL_AD_DECRYPT_ERROR, SSL_F_TLS_PROCESS_CKE_RSA,
3075                  SSL_R_DECRYPTION_FAILED);
3076         goto err;
3077     }
3078
3079     *p++ = OSSL_PARAM_construct_uint(OSSL_ASYM_CIPHER_PARAM_TLS_CLIENT_VERSION,
3080                                      (unsigned int *)&s->client_version);
3081    if ((s->options & SSL_OP_TLS_ROLLBACK_BUG) != 0)
3082         *p++ = OSSL_PARAM_construct_uint(
3083             OSSL_ASYM_CIPHER_PARAM_TLS_NEGOTIATED_VERSION,
3084             (unsigned int *)&s->version);
3085     *p++ = OSSL_PARAM_construct_end();
3086
3087     if (!EVP_PKEY_CTX_set_params(ctx, params)
3088             || EVP_PKEY_decrypt(ctx, rsa_decrypt, &outlen,
3089                                 PACKET_data(&enc_premaster),
3090                                 PACKET_remaining(&enc_premaster)) <= 0) {
3091         SSLfatal(s, SSL_AD_DECRYPT_ERROR, SSL_F_TLS_PROCESS_CKE_RSA,
3092                  SSL_R_DECRYPTION_FAILED);
3093         goto err;
3094     }
3095
3096     /*
3097      * This test should never fail (otherwise we should have failed above) but
3098      * we double check anyway.
3099      */
3100     if (outlen != SSL_MAX_MASTER_KEY_LENGTH) {
3101         OPENSSL_cleanse(rsa_decrypt, SSL_MAX_MASTER_KEY_LENGTH);
3102         SSLfatal(s, SSL_AD_DECRYPT_ERROR, SSL_F_TLS_PROCESS_CKE_RSA,
3103                  SSL_R_DECRYPTION_FAILED);
3104         goto err;
3105     }
3106
3107     /* Also cleanses rsa_decrypt (on success or failure) */
3108     if (!ssl_generate_master_secret(s, rsa_decrypt,
3109                                     SSL_MAX_MASTER_KEY_LENGTH, 0)) {
3110         /* SSLfatal() already called */
3111         goto err;
3112     }
3113
3114     ret = 1;
3115  err:
3116     OPENSSL_free(rsa_decrypt);
3117     EVP_PKEY_CTX_free(ctx);
3118     return ret;
3119 #else
3120     /* Should never happen */
3121     SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_F_TLS_PROCESS_CKE_RSA,
3122              ERR_R_INTERNAL_ERROR);
3123     return 0;
3124 #endif
3125 }
3126
3127 static int tls_process_cke_dhe(SSL *s, PACKET *pkt)
3128 {
3129 #ifndef OPENSSL_NO_DH
3130     EVP_PKEY *skey = NULL;
3131     DH *cdh;
3132     unsigned int i;
3133     BIGNUM *pub_key;
3134     const unsigned char *data;
3135     EVP_PKEY *ckey = NULL;
3136     int ret = 0;
3137
3138     if (!PACKET_get_net_2(pkt, &i) || PACKET_remaining(pkt) != i) {
3139         SSLfatal(s, SSL_AD_DECODE_ERROR, SSL_F_TLS_PROCESS_CKE_DHE,
3140                SSL_R_DH_PUBLIC_VALUE_LENGTH_IS_WRONG);
3141         goto err;
3142     }
3143     skey = s->s3.tmp.pkey;
3144     if (skey == NULL) {
3145         SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_F_TLS_PROCESS_CKE_DHE,
3146                  SSL_R_MISSING_TMP_DH_KEY);
3147         goto err;
3148     }
3149
3150     if (PACKET_remaining(pkt) == 0L) {
3151         SSLfatal(s, SSL_AD_DECODE_ERROR, SSL_F_TLS_PROCESS_CKE_DHE,
3152                  SSL_R_MISSING_TMP_DH_KEY);
3153         goto err;
3154     }
3155     if (!PACKET_get_bytes(pkt, &data, i)) {
3156         /* We already checked we have enough data */
3157         SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_F_TLS_PROCESS_CKE_DHE,
3158                  ERR_R_INTERNAL_ERROR);
3159         goto err;
3160     }
3161     ckey = EVP_PKEY_new();
3162     if (ckey == NULL || EVP_PKEY_copy_parameters(ckey, skey) == 0) {
3163         SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_F_TLS_PROCESS_CKE_DHE,
3164                  SSL_R_BN_LIB);
3165         goto err;
3166     }
3167
3168     cdh = EVP_PKEY_get0_DH(ckey);
3169     pub_key = BN_bin2bn(data, i, NULL);
3170     if (pub_key == NULL || cdh == NULL || !DH_set0_key(cdh, pub_key, NULL)) {
3171         SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_F_TLS_PROCESS_CKE_DHE,
3172                  ERR_R_INTERNAL_ERROR);
3173         BN_free(pub_key);
3174         goto err;
3175     }
3176
3177     if (ssl_derive(s, skey, ckey, 1) == 0) {
3178         /* SSLfatal() already called */
3179         goto err;
3180     }
3181
3182     ret = 1;
3183     EVP_PKEY_free(s->s3.tmp.pkey);
3184     s->s3.tmp.pkey = NULL;
3185  err:
3186     EVP_PKEY_free(ckey);
3187     return ret;
3188 #else
3189     /* Should never happen */
3190     SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_F_TLS_PROCESS_CKE_DHE,
3191              ERR_R_INTERNAL_ERROR);
3192     return 0;
3193 #endif
3194 }
3195
3196 static int tls_process_cke_ecdhe(SSL *s, PACKET *pkt)
3197 {
3198 #ifndef OPENSSL_NO_EC
3199     EVP_PKEY *skey = s->s3.tmp.pkey;
3200     EVP_PKEY *ckey = NULL;
3201     int ret = 0;
3202
3203     if (PACKET_remaining(pkt) == 0L) {
3204         /* We don't support ECDH client auth */
3205         SSLfatal(s, SSL_AD_HANDSHAKE_FAILURE, SSL_F_TLS_PROCESS_CKE_ECDHE,
3206                  SSL_R_MISSING_TMP_ECDH_KEY);
3207         goto err;
3208     } else {
3209         unsigned int i;
3210         const unsigned char *data;
3211
3212         /*
3213          * Get client's public key from encoded point in the
3214          * ClientKeyExchange message.
3215          */
3216
3217         /* Get encoded point length */
3218         if (!PACKET_get_1(pkt, &i) || !PACKET_get_bytes(pkt, &data, i)
3219             || PACKET_remaining(pkt) != 0) {
3220             SSLfatal(s, SSL_AD_DECODE_ERROR, SSL_F_TLS_PROCESS_CKE_ECDHE,
3221                      SSL_R_LENGTH_MISMATCH);
3222             goto err;
3223         }
3224         if (skey == NULL) {
3225             SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_F_TLS_PROCESS_CKE_ECDHE,
3226                      SSL_R_MISSING_TMP_ECDH_KEY);
3227             goto err;
3228         }
3229
3230         ckey = EVP_PKEY_new();
3231         if (ckey == NULL || EVP_PKEY_copy_parameters(ckey, skey) <= 0) {
3232             SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_F_TLS_PROCESS_CKE_ECDHE,
3233                      ERR_R_EVP_LIB);
3234             goto err;
3235         }
3236
3237         /*
3238          * TODO(3.0) Remove this when EVP_PKEY_get1_tls_encodedpoint()
3239          * knows how to get a key from an encoded point with the help of
3240          * a OSSL_SERIALIZER deserializer.  We know that EVP_PKEY_get0()
3241          * downgrades an EVP_PKEY to contain a legacy key.
3242          *
3243          * THIS IS TEMPORARY
3244          */
3245         EVP_PKEY_get0(ckey);
3246         if (EVP_PKEY_id(ckey) == EVP_PKEY_NONE) {
3247             SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_F_TLS_PROCESS_CKE_ECDHE,
3248                      ERR_R_INTERNAL_ERROR);
3249             goto err;
3250         }
3251
3252         if (EVP_PKEY_set1_tls_encodedpoint(ckey, data, i) == 0) {
3253             SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_F_TLS_PROCESS_CKE_ECDHE,
3254                      ERR_R_EC_LIB);
3255             goto err;
3256         }
3257     }
3258
3259     if (ssl_derive(s, skey, ckey, 1) == 0) {
3260         /* SSLfatal() already called */
3261         goto err;
3262     }
3263
3264     ret = 1;
3265     EVP_PKEY_free(s->s3.tmp.pkey);
3266     s->s3.tmp.pkey = NULL;
3267  err:
3268     EVP_PKEY_free(ckey);
3269
3270     return ret;
3271 #else
3272     /* Should never happen */
3273     SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_F_TLS_PROCESS_CKE_ECDHE,
3274              ERR_R_INTERNAL_ERROR);
3275     return 0;
3276 #endif
3277 }
3278
3279 static int tls_process_cke_srp(SSL *s, PACKET *pkt)
3280 {
3281 #ifndef OPENSSL_NO_SRP
3282     unsigned int i;
3283     const unsigned char *data;
3284
3285     if (!PACKET_get_net_2(pkt, &i)
3286         || !PACKET_get_bytes(pkt, &data, i)) {
3287         SSLfatal(s, SSL_AD_DECODE_ERROR, SSL_F_TLS_PROCESS_CKE_SRP,
3288                  SSL_R_BAD_SRP_A_LENGTH);
3289         return 0;
3290     }
3291     if ((s->srp_ctx.A = BN_bin2bn(data, i, NULL)) == NULL) {
3292         SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_F_TLS_PROCESS_CKE_SRP,
3293                  ERR_R_BN_LIB);
3294         return 0;
3295     }
3296     if (BN_ucmp(s->srp_ctx.A, s->srp_ctx.N) >= 0 || BN_is_zero(s->srp_ctx.A)) {
3297         SSLfatal(s, SSL_AD_ILLEGAL_PARAMETER, SSL_F_TLS_PROCESS_CKE_SRP,
3298                  SSL_R_BAD_SRP_PARAMETERS);
3299         return 0;
3300     }
3301     OPENSSL_free(s->session->srp_username);
3302     s->session->srp_username = OPENSSL_strdup(s->srp_ctx.login);
3303     if (s->session->srp_username == NULL) {
3304         SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_F_TLS_PROCESS_CKE_SRP,
3305                  ERR_R_MALLOC_FAILURE);
3306         return 0;
3307     }
3308
3309     if (!srp_generate_server_master_secret(s)) {
3310         /* SSLfatal() already called */
3311         return 0;
3312     }
3313
3314     return 1;
3315 #else
3316     /* Should never happen */
3317     SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_F_TLS_PROCESS_CKE_SRP,
3318              ERR_R_INTERNAL_ERROR);
3319     return 0;
3320 #endif
3321 }
3322
3323 static int tls_process_cke_gost(SSL *s, PACKET *pkt)
3324 {
3325 #ifndef OPENSSL_NO_GOST
3326     EVP_PKEY_CTX *pkey_ctx;
3327     EVP_PKEY *client_pub_pkey = NULL, *pk = NULL;
3328     unsigned char premaster_secret[32];
3329     const unsigned char *start;
3330     size_t outlen = 32, inlen;
3331     unsigned long alg_a;
3332     GOST_KX_MESSAGE *pKX = NULL;
3333     const unsigned char *ptr;
3334     int ret = 0;
3335
3336     /* Get our certificate private key */
3337     alg_a = s->s3.tmp.new_cipher->algorithm_auth;
3338     if (alg_a & SSL_aGOST12) {
3339         /*
3340          * New GOST ciphersuites have SSL_aGOST01 bit too
3341          */
3342         pk = s->cert->pkeys[SSL_PKEY_GOST12_512].privatekey;
3343         if (pk == NULL) {
3344             pk = s->cert->pkeys[SSL_PKEY_GOST12_256].privatekey;
3345         }
3346         if (pk == NULL) {
3347             pk = s->cert->pkeys[SSL_PKEY_GOST01].privatekey;
3348         }
3349     } else if (alg_a & SSL_aGOST01) {
3350         pk = s->cert->pkeys[SSL_PKEY_GOST01].privatekey;
3351     }
3352
3353     pkey_ctx = EVP_PKEY_CTX_new_from_pkey(s->ctx->libctx, pk, s->ctx->propq);
3354     if (pkey_ctx == NULL) {
3355         SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_F_TLS_PROCESS_CKE_GOST,
3356                  ERR_R_MALLOC_FAILURE);
3357         return 0;
3358     }
3359     if (EVP_PKEY_decrypt_init(pkey_ctx) <= 0) {
3360         SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_F_TLS_PROCESS_CKE_GOST,
3361                  ERR_R_INTERNAL_ERROR);
3362         return 0;
3363     }
3364     /*
3365      * If client certificate is present and is of the same type, maybe
3366      * use it for key exchange.  Don't mind errors from
3367      * EVP_PKEY_derive_set_peer, because it is completely valid to use a
3368      * client certificate for authorization only.
3369      */
3370     client_pub_pkey = X509_get0_pubkey(s->session->peer);
3371     if (client_pub_pkey) {
3372         if (EVP_PKEY_derive_set_peer(pkey_ctx, client_pub_pkey) <= 0)
3373             ERR_clear_error();
3374     }
3375
3376     ptr = PACKET_data(pkt);
3377     /* Some implementations provide extra data in the opaqueBlob
3378      * We have nothing to do with this blob so we just skip it */
3379     pKX = d2i_GOST_KX_MESSAGE(NULL, &ptr, PACKET_remaining(pkt));
3380     if (pKX == NULL
3381        || pKX->kxBlob == NULL
3382        || ASN1_TYPE_get(pKX->kxBlob) != V_ASN1_SEQUENCE) {
3383          SSLfatal(s, SSL_AD_DECODE_ERROR, SSL_F_TLS_PROCESS_CKE_GOST,
3384                   SSL_R_DECRYPTION_FAILED);
3385          goto err;
3386     }
3387
3388     if (!PACKET_forward(pkt, ptr - PACKET_data(pkt))) {
3389         SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_F_TLS_PROCESS_CKE_GOST,
3390                  SSL_R_DECRYPTION_FAILED);
3391         goto err;
3392     }
3393
3394     if (PACKET_remaining(pkt) != 0) {
3395         SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_F_TLS_PROCESS_CKE_GOST,
3396                  SSL_R_DECRYPTION_FAILED);
3397         goto err;
3398     }
3399
3400     inlen = pKX->kxBlob->value.sequence->length;
3401     start = pKX->kxBlob->value.sequence->data;
3402
3403     if (EVP_PKEY_decrypt(pkey_ctx, premaster_secret, &outlen, start,
3404                          inlen) <= 0) {
3405         SSLfatal(s, SSL_AD_DECODE_ERROR, SSL_F_TLS_PROCESS_CKE_GOST,
3406                  SSL_R_DECRYPTION_FAILED);
3407         goto err;
3408     }
3409     /* Generate master secret */
3410     if (!ssl_generate_master_secret(s, premaster_secret,
3411                                     sizeof(premaster_secret), 0)) {
3412         /* SSLfatal() already called */
3413         goto err;
3414     }
3415     /* Check if pubkey from client certificate was used */
3416     if (EVP_PKEY_CTX_ctrl(pkey_ctx, -1, -1, EVP_PKEY_CTRL_PEER_KEY, 2,
3417                           NULL) > 0)
3418         s->statem.no_cert_verify = 1;
3419
3420     ret = 1;
3421  err:
3422     EVP_PKEY_CTX_free(pkey_ctx);
3423     GOST_KX_MESSAGE_free(pKX);
3424     return ret;
3425 #else
3426     /* Should never happen */
3427     SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_F_TLS_PROCESS_CKE_GOST,
3428              ERR_R_INTERNAL_ERROR);
3429     return 0;
3430 #endif
3431 }
3432
3433 MSG_PROCESS_RETURN tls_process_client_key_exchange(SSL *s, PACKET *pkt)
3434 {
3435     unsigned long alg_k;
3436
3437     alg_k = s->s3.tmp.new_cipher->algorithm_mkey;
3438
3439     /* For PSK parse and retrieve identity, obtain PSK key */
3440     if ((alg_k & SSL_PSK) && !tls_process_cke_psk_preamble(s, pkt)) {
3441         /* SSLfatal() already called */
3442         goto err;
3443     }
3444
3445     if (alg_k & SSL_kPSK) {
3446         /* Identity extracted earlier: should be nothing left */
3447         if (PACKET_remaining(pkt) != 0) {
3448             SSLfatal(s, SSL_AD_DECODE_ERROR,
3449                      SSL_F_TLS_PROCESS_CLIENT_KEY_EXCHANGE,
3450                      SSL_R_LENGTH_MISMATCH);
3451             goto err;
3452         }
3453         /* PSK handled by ssl_generate_master_secret */
3454         if (!ssl_generate_master_secret(s, NULL, 0, 0)) {
3455             /* SSLfatal() already called */
3456             goto err;
3457         }
3458     } else if (alg_k & (SSL_kRSA | SSL_kRSAPSK)) {
3459         if (!tls_process_cke_rsa(s, pkt)) {
3460             /* SSLfatal() already called */
3461             goto err;
3462         }
3463     } else if (alg_k & (SSL_kDHE | SSL_kDHEPSK)) {
3464         if (!tls_process_cke_dhe(s, pkt)) {
3465             /* SSLfatal() already called */
3466             goto err;
3467         }
3468     } else if (alg_k & (SSL_kECDHE | SSL_kECDHEPSK)) {
3469         if (!tls_process_cke_ecdhe(s, pkt)) {
3470             /* SSLfatal() already called */
3471             goto err;
3472         }
3473     } else if (alg_k & SSL_kSRP) {
3474         if (!tls_process_cke_srp(s, pkt)) {
3475             /* SSLfatal() already called */
3476             goto err;
3477         }
3478     } else if (alg_k & SSL_kGOST) {
3479         if (!tls_process_cke_gost(s, pkt)) {
3480             /* SSLfatal() already called */
3481             goto err;
3482         }
3483     } else {
3484         SSLfatal(s, SSL_AD_INTERNAL_ERROR,
3485                  SSL_F_TLS_PROCESS_CLIENT_KEY_EXCHANGE,
3486                  SSL_R_UNKNOWN_CIPHER_TYPE);
3487         goto err;
3488     }
3489
3490     return MSG_PROCESS_CONTINUE_PROCESSING;
3491  err:
3492 #ifndef OPENSSL_NO_PSK
3493     OPENSSL_clear_free(s->s3.tmp.psk, s->s3.tmp.psklen);
3494     s->s3.tmp.psk = NULL;
3495 #endif
3496     return MSG_PROCESS_ERROR;
3497 }
3498
3499 WORK_STATE tls_post_process_client_key_exchange(SSL *s, WORK_STATE wst)
3500 {
3501 #ifndef OPENSSL_NO_SCTP
3502     if (wst == WORK_MORE_A) {
3503         if (SSL_IS_DTLS(s)) {
3504             unsigned char sctpauthkey[64];
3505             char labelbuffer[sizeof(DTLS1_SCTP_AUTH_LABEL)];
3506             size_t labellen;
3507             /*
3508              * Add new shared key for SCTP-Auth, will be ignored if no SCTP
3509              * used.
3510              */
3511             memcpy(labelbuffer, DTLS1_SCTP_AUTH_LABEL,
3512                    sizeof(DTLS1_SCTP_AUTH_LABEL));
3513
3514             /* Don't include the terminating zero. */
3515             labellen = sizeof(labelbuffer) - 1;
3516             if (s->mode & SSL_MODE_DTLS_SCTP_LABEL_LENGTH_BUG)
3517                 labellen += 1;
3518
3519             if (SSL_export_keying_material(s, sctpauthkey,
3520                                            sizeof(sctpauthkey), labelbuffer,
3521                                            labellen, NULL, 0,
3522                                            0) <= 0) {
3523                 SSLfatal(s, SSL_AD_INTERNAL_ERROR,
3524                          SSL_F_TLS_POST_PROCESS_CLIENT_KEY_EXCHANGE,
3525                          ERR_R_INTERNAL_ERROR);
3526                 return WORK_ERROR;
3527             }
3528
3529             BIO_ctrl(SSL_get_wbio(s), BIO_CTRL_DGRAM_SCTP_ADD_AUTH_KEY,
3530                      sizeof(sctpauthkey), sctpauthkey);
3531         }
3532     }
3533 #endif
3534
3535     if (s->statem.no_cert_verify || !s->session->peer) {
3536         /*
3537          * No certificate verify or no peer certificate so we no longer need
3538          * the handshake_buffer
3539          */
3540         if (!ssl3_digest_cached_records(s, 0)) {
3541             /* SSLfatal() already called */
3542             return WORK_ERROR;
3543         }
3544         return WORK_FINISHED_CONTINUE;
3545     } else {
3546         if (!s->s3.handshake_buffer) {
3547             SSLfatal(s, SSL_AD_INTERNAL_ERROR,
3548                      SSL_F_TLS_POST_PROCESS_CLIENT_KEY_EXCHANGE,
3549                      ERR_R_INTERNAL_ERROR);
3550             return WORK_ERROR;
3551         }
3552         /*
3553          * For sigalgs freeze the handshake buffer. If we support
3554          * extms we've done this already so this is a no-op
3555          */
3556         if (!ssl3_digest_cached_records(s, 1)) {
3557             /* SSLfatal() already called */
3558             return WORK_ERROR;
3559         }
3560     }
3561
3562     return WORK_FINISHED_CONTINUE;
3563 }
3564
3565 MSG_PROCESS_RETURN tls_process_client_certificate(SSL *s, PACKET *pkt)
3566 {
3567     int i;
3568     MSG_PROCESS_RETURN ret = MSG_PROCESS_ERROR;
3569     X509 *x = NULL;
3570     unsigned long l;
3571     const unsigned char *certstart, *certbytes;
3572     STACK_OF(X509) *sk = NULL;
3573     PACKET spkt, context;
3574     size_t chainidx;
3575     SSL_SESSION *new_sess = NULL;
3576
3577     /*
3578      * To get this far we must have read encrypted data from the client. We no
3579      * longer tolerate unencrypted alerts. This value is ignored if less than
3580      * TLSv1.3
3581      */
3582     s->statem.enc_read_state = ENC_READ_STATE_VALID;
3583
3584     if ((sk = sk_X509_new_null()) == NULL) {
3585         SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_F_TLS_PROCESS_CLIENT_CERTIFICATE,
3586                  ERR_R_MALLOC_FAILURE);
3587         goto err;
3588     }
3589
3590     if (SSL_IS_TLS13(s) && (!PACKET_get_length_prefixed_1(pkt, &context)
3591                             || (s->pha_context == NULL && PACKET_remaining(&context) != 0)
3592                             || (s->pha_context != NULL &&
3593                                 !PACKET_equal(&context, s->pha_context, s->pha_context_len)))) {
3594         SSLfatal(s, SSL_AD_DECODE_ERROR, SSL_F_TLS_PROCESS_CLIENT_CERTIFICATE,
3595                  SSL_R_INVALID_CONTEXT);
3596         goto err;
3597     }
3598
3599     if (!PACKET_get_length_prefixed_3(pkt, &spkt)
3600             || PACKET_remaining(pkt) != 0) {
3601         SSLfatal(s, SSL_AD_DECODE_ERROR, SSL_F_TLS_PROCESS_CLIENT_CERTIFICATE,
3602                  SSL_R_LENGTH_MISMATCH);
3603         goto err;
3604     }
3605
3606     for (chainidx = 0; PACKET_remaining(&spkt) > 0; chainidx++) {
3607         if (!PACKET_get_net_3(&spkt, &l)
3608             || !PACKET_get_bytes(&spkt, &certbytes, l)) {
3609             SSLfatal(s, SSL_AD_DECODE_ERROR,
3610                      SSL_F_TLS_PROCESS_CLIENT_CERTIFICATE,
3611                      SSL_R_CERT_LENGTH_MISMATCH);
3612             goto err;
3613         }
3614
3615         certstart = certbytes;
3616         x = d2i_X509(NULL, (const unsigned char **)&certbytes, l);
3617         if (x == NULL) {
3618             SSLfatal(s, SSL_AD_DECODE_ERROR,
3619                      SSL_F_TLS_PROCESS_CLIENT_CERTIFICATE, ERR_R_ASN1_LIB);
3620             goto err;
3621         }
3622         if (certbytes != (certstart + l)) {
3623             SSLfatal(s, SSL_AD_DECODE_ERROR,
3624                      SSL_F_TLS_PROCESS_CLIENT_CERTIFICATE,
3625                      SSL_R_CERT_LENGTH_MISMATCH);
3626             goto err;
3627         }
3628
3629         if (SSL_IS_TLS13(s)) {
3630             RAW_EXTENSION *rawexts = NULL;
3631             PACKET extensions;
3632
3633             if (!PACKET_get_length_prefixed_2(&spkt, &extensions)) {
3634                 SSLfatal(s, SSL_AD_DECODE_ERROR,
3635                          SSL_F_TLS_PROCESS_CLIENT_CERTIFICATE,
3636                          SSL_R_BAD_LENGTH);
3637                 goto err;
3638             }
3639             if (!tls_collect_extensions(s, &extensions,
3640                                         SSL_EXT_TLS1_3_CERTIFICATE, &rawexts,
3641                                         NULL, chainidx == 0)
3642                 || !tls_parse_all_extensions(s, SSL_EXT_TLS1_3_CERTIFICATE,
3643                                              rawexts, x, chainidx,
3644                                              PACKET_remaining(&spkt) == 0)) {
3645                 OPENSSL_free(rawexts);
3646                 goto err;
3647             }
3648             OPENSSL_free(rawexts);
3649         }
3650
3651         if (!sk_X509_push(sk, x)) {
3652             SSLfatal(s, SSL_AD_INTERNAL_ERROR,
3653                      SSL_F_TLS_PROCESS_CLIENT_CERTIFICATE,
3654                      ERR_R_MALLOC_FAILURE);
3655             goto err;
3656         }
3657         x = NULL;
3658     }
3659
3660     if (sk_X509_num(sk) <= 0) {
3661         /* TLS does not mind 0 certs returned */
3662         if (s->version == SSL3_VERSION) {
3663             SSLfatal(s, SSL_AD_HANDSHAKE_FAILURE,
3664                      SSL_F_TLS_PROCESS_CLIENT_CERTIFICATE,
3665                      SSL_R_NO_CERTIFICATES_RETURNED);
3666             goto err;
3667         }
3668         /* Fail for TLS only if we required a certificate */
3669         else if ((s->verify_mode & SSL_VERIFY_PEER) &&
3670                  (s->verify_mode & SSL_VERIFY_FAIL_IF_NO_PEER_CERT)) {
3671             SSLfatal(s, SSL_AD_CERTIFICATE_REQUIRED,
3672                      SSL_F_TLS_PROCESS_CLIENT_CERTIFICATE,
3673                      SSL_R_PEER_DID_NOT_RETURN_A_CERTIFICATE);
3674             goto err;
3675         }
3676         /* No client certificate so digest cached records */
3677         if (s->s3.handshake_buffer && !ssl3_digest_cached_records(s, 0)) {
3678             /* SSLfatal() already called */
3679             goto err;
3680         }
3681     } else {
3682         EVP_PKEY *pkey;
3683         i = ssl_verify_cert_chain(s, sk);
3684         if (i <= 0) {
3685             SSLfatal(s, ssl_x509err2alert(s->verify_result),
3686                      SSL_F_TLS_PROCESS_CLIENT_CERTIFICATE,
3687                      SSL_R_CERTIFICATE_VERIFY_FAILED);
3688             goto err;
3689         }
3690         if (i > 1) {
3691             SSLfatal(s, SSL_AD_HANDSHAKE_FAILURE,
3692                      SSL_F_TLS_PROCESS_CLIENT_CERTIFICATE, i);
3693             goto err;
3694         }
3695         pkey = X509_get0_pubkey(sk_X509_value(sk, 0));
3696         if (pkey == NULL) {
3697             SSLfatal(s, SSL_AD_HANDSHAKE_FAILURE,
3698                      SSL_F_TLS_PROCESS_CLIENT_CERTIFICATE,
3699                      SSL_R_UNKNOWN_CERTIFICATE_TYPE);
3700             goto err;
3701         }
3702     }
3703
3704     /*
3705      * Sessions must be immutable once they go into the session cache. Otherwise
3706      * we can get multi-thread problems. Therefore we don't "update" sessions,
3707      * we replace them with a duplicate. Here, we need to do this every time
3708      * a new certificate is received via post-handshake authentication, as the
3709      * session may have already gone into the session cache.
3710      */
3711
3712     if (s->post_handshake_auth == SSL_PHA_REQUESTED) {
3713         if ((new_sess = ssl_session_dup(s->session, 0)) == 0) {
3714             SSLfatal(s, SSL_AD_INTERNAL_ERROR,
3715                      SSL_F_TLS_PROCESS_CLIENT_CERTIFICATE,
3716                      ERR_R_MALLOC_FAILURE);
3717             goto err;
3718         }
3719
3720         SSL_SESSION_free(s->session);
3721         s->session = new_sess;
3722     }
3723
3724     X509_free(s->session->peer);
3725     s->session->peer = sk_X509_shift(sk);
3726     s->session->verify_result = s->verify_result;
3727
3728     sk_X509_pop_free(s->session->peer_chain, X509_free);
3729     s->session->peer_chain = sk;
3730
3731     /*
3732      * Freeze the handshake buffer. For <TLS1.3 we do this after the CKE
3733      * message
3734      */
3735     if (SSL_IS_TLS13(s) && !ssl3_digest_cached_records(s, 1)) {
3736         /* SSLfatal() already called */
3737         goto err;
3738     }
3739
3740     /*
3741      * Inconsistency alert: cert_chain does *not* include the peer's own
3742      * certificate, while we do include it in statem_clnt.c
3743      */
3744     sk = NULL;
3745
3746     /* Save the current hash state for when we receive the CertificateVerify */
3747     if (SSL_IS_TLS13(s)) {
3748         if (!ssl_handshake_hash(s, s->cert_verify_hash,
3749                                 sizeof(s->cert_verify_hash),
3750                                 &s->cert_verify_hash_len)) {
3751             /* SSLfatal() already called */
3752             goto err;
3753         }
3754
3755         /* Resend session tickets */
3756         s->sent_tickets = 0;
3757     }
3758
3759     ret = MSG_PROCESS_CONTINUE_READING;
3760
3761  err:
3762     X509_free(x);
3763     sk_X509_pop_free(sk, X509_free);
3764     return ret;
3765 }
3766
3767 int tls_construct_server_certificate(SSL *s, WPACKET *pkt)
3768 {
3769     CERT_PKEY *cpk = s->s3.tmp.cert;
3770
3771     if (cpk == NULL) {
3772         SSLfatal(s, SSL_AD_INTERNAL_ERROR,
3773                  SSL_F_TLS_CONSTRUCT_SERVER_CERTIFICATE, ERR_R_INTERNAL_ERROR);
3774         return 0;
3775     }
3776
3777     /*
3778      * In TLSv1.3 the certificate chain is always preceded by a 0 length context
3779      * for the server Certificate message
3780      */
3781     if (SSL_IS_TLS13(s) && !WPACKET_put_bytes_u8(pkt, 0)) {
3782         SSLfatal(s, SSL_AD_INTERNAL_ERROR,
3783                  SSL_F_TLS_CONSTRUCT_SERVER_CERTIFICATE, ERR_R_INTERNAL_ERROR);
3784         return 0;
3785     }
3786     if (!ssl3_output_cert_chain(s, pkt, cpk)) {
3787         /* SSLfatal() already called */
3788         return 0;
3789     }
3790
3791     return 1;
3792 }
3793
3794 static int create_ticket_prequel(SSL *s, WPACKET *pkt, uint32_t age_add,
3795                                  unsigned char *tick_nonce)
3796 {
3797     /*
3798      * Ticket lifetime hint: For TLSv1.2 this is advisory only and we leave this
3799      * unspecified for resumed session (for simplicity).
3800      * In TLSv1.3 we reset the "time" field above, and always specify the
3801      * timeout.
3802      */
3803     if (!WPACKET_put_bytes_u32(pkt,
3804                                (s->hit && !SSL_IS_TLS13(s))
3805                                ? 0 : s->session->timeout)) {
3806         SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_F_CREATE_TICKET_PREQUEL,
3807                  ERR_R_INTERNAL_ERROR);
3808         return 0;
3809     }
3810
3811     if (SSL_IS_TLS13(s)) {
3812         if (!WPACKET_put_bytes_u32(pkt, age_add)
3813                 || !WPACKET_sub_memcpy_u8(pkt, tick_nonce, TICKET_NONCE_SIZE)) {
3814             SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_F_CREATE_TICKET_PREQUEL,
3815                      ERR_R_INTERNAL_ERROR);
3816             return 0;
3817         }
3818     }
3819
3820     /* Start the sub-packet for the actual ticket data */
3821     if (!WPACKET_start_sub_packet_u16(pkt)) {
3822         SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_F_CREATE_TICKET_PREQUEL,
3823                  ERR_R_INTERNAL_ERROR);
3824         return 0;
3825     }
3826
3827     return 1;
3828 }
3829
3830 static int construct_stateless_ticket(SSL *s, WPACKET *pkt, uint32_t age_add,
3831                                       unsigned char *tick_nonce)
3832 {
3833     unsigned char *senc = NULL;
3834     EVP_CIPHER_CTX *ctx = NULL;
3835     SSL_HMAC *hctx = NULL;
3836     unsigned char *p, *encdata1, *encdata2, *macdata1, *macdata2;
3837     const unsigned char *const_p;
3838     int len, slen_full, slen, lenfinal;
3839     SSL_SESSION *sess;
3840     size_t hlen;
3841     SSL_CTX *tctx = s->session_ctx;
3842     unsigned char iv[EVP_MAX_IV_LENGTH];
3843     unsigned char key_name[TLSEXT_KEYNAME_LENGTH];
3844     int iv_len, ok = 0;
3845     size_t macoffset, macendoffset;
3846
3847     /* get session encoding length */
3848     slen_full = i2d_SSL_SESSION(s->session, NULL);
3849     /*
3850      * Some length values are 16 bits, so forget it if session is too
3851      * long
3852      */
3853     if (slen_full == 0 || slen_full > 0xFF00) {
3854         SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_F_CONSTRUCT_STATELESS_TICKET,
3855                  ERR_R_INTERNAL_ERROR);
3856         goto err;
3857     }
3858     senc = OPENSSL_malloc(slen_full);
3859     if (senc == NULL) {
3860         SSLfatal(s, SSL_AD_INTERNAL_ERROR,
3861                  SSL_F_CONSTRUCT_STATELESS_TICKET, ERR_R_MALLOC_FAILURE);
3862         goto err;
3863     }
3864
3865     ctx = EVP_CIPHER_CTX_new();
3866     hctx = ssl_hmac_new(tctx);
3867     if (ctx == NULL || hctx == NULL) {
3868         SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_F_CONSTRUCT_STATELESS_TICKET,
3869                  ERR_R_MALLOC_FAILURE);
3870         goto err;
3871     }
3872
3873     p = senc;
3874     if (!i2d_SSL_SESSION(s->session, &p)) {
3875         SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_F_CONSTRUCT_STATELESS_TICKET,
3876                  ERR_R_INTERNAL_ERROR);
3877         goto err;
3878     }
3879
3880     /*
3881      * create a fresh copy (not shared with other threads) to clean up
3882      */
3883     const_p = senc;
3884     sess = d2i_SSL_SESSION(NULL, &const_p, slen_full);
3885     if (sess == NULL) {
3886         SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_F_CONSTRUCT_STATELESS_TICKET,
3887                  ERR_R_INTERNAL_ERROR);
3888         goto err;
3889     }
3890
3891     slen = i2d_SSL_SESSION(sess, NULL);
3892     if (slen == 0 || slen > slen_full) {
3893         /* shouldn't ever happen */
3894         SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_F_CONSTRUCT_STATELESS_TICKET,
3895                  ERR_R_INTERNAL_ERROR);
3896         SSL_SESSION_free(sess);
3897         goto err;
3898     }
3899     p = senc;
3900     if (!i2d_SSL_SESSION(sess, &p)) {
3901         SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_F_CONSTRUCT_STATELESS_TICKET,
3902                  ERR_R_INTERNAL_ERROR);
3903         SSL_SESSION_free(sess);
3904         goto err;
3905     }
3906     SSL_SESSION_free(sess);
3907
3908     /*
3909      * Initialize HMAC and cipher contexts. If callback present it does
3910      * all the work otherwise use generated values from parent ctx.
3911      */
3912 #ifndef OPENSSL_NO_DEPRECATED_3_0
3913     if (tctx->ext.ticket_key_evp_cb != NULL || tctx->ext.ticket_key_cb != NULL)
3914 #else
3915     if (tctx->ext.ticket_key_evp_cb != NULL)
3916 #endif
3917     {
3918         int ret = 0;
3919
3920         if (tctx->ext.ticket_key_evp_cb != NULL)
3921             ret = tctx->ext.ticket_key_evp_cb(s, key_name, iv, ctx,
3922                                               ssl_hmac_get0_EVP_MAC_CTX(hctx),
3923                                               1);
3924 #ifndef OPENSSL_NO_DEPRECATED_3_0
3925         else if (tctx->ext.ticket_key_cb != NULL)
3926             /* if 0 is returned, write an empty ticket */
3927             ret = tctx->ext.ticket_key_cb(s, key_name, iv, ctx,
3928                                           ssl_hmac_get0_HMAC_CTX(hctx), 1);
3929 #endif
3930
3931         if (ret == 0) {
3932
3933             /* Put timeout and length */
3934             if (!WPACKET_put_bytes_u32(pkt, 0)
3935                     || !WPACKET_put_bytes_u16(pkt, 0)) {
3936                 SSLfatal(s, SSL_AD_INTERNAL_ERROR,
3937                          SSL_F_CONSTRUCT_STATELESS_TICKET,
3938                          ERR_R_INTERNAL_ERROR);
3939                 goto err;
3940             }
3941             OPENSSL_free(senc);
3942             EVP_CIPHER_CTX_free(ctx);
3943             ssl_hmac_free(hctx);
3944             return 1;
3945         }
3946         if (ret < 0) {
3947             SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_F_CONSTRUCT_STATELESS_TICKET,
3948                      SSL_R_CALLBACK_FAILED);
3949             goto err;
3950         }
3951         iv_len = EVP_CIPHER_CTX_iv_length(ctx);
3952     } else {
3953         EVP_CIPHER *cipher = EVP_CIPHER_fetch(s->ctx->libctx, "AES-256-CBC",
3954                                               s->ctx->propq);
3955
3956         if (cipher == NULL) {
3957             SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_F_CONSTRUCT_STATELESS_TICKET,
3958                      SSL_R_ALGORITHM_FETCH_FAILED);
3959             goto err;
3960         }
3961
3962         iv_len = EVP_CIPHER_iv_length(cipher);
3963         if (RAND_bytes_ex(s->ctx->libctx, iv, iv_len) <= 0
3964                 || !EVP_EncryptInit_ex(ctx, cipher, NULL,
3965                                        tctx->ext.secure->tick_aes_key, iv)
3966                 || !ssl_hmac_init(hctx, tctx->ext.secure->tick_hmac_key,
3967                                   sizeof(tctx->ext.secure->tick_hmac_key),
3968                                   "SHA256")) {
3969             EVP_CIPHER_free(cipher);
3970             SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_F_CONSTRUCT_STATELESS_TICKET,
3971                      ERR_R_INTERNAL_ERROR);
3972             goto err;
3973         }
3974         EVP_CIPHER_free(cipher);
3975         memcpy(key_name, tctx->ext.tick_key_name,
3976                sizeof(tctx->ext.tick_key_name));
3977     }
3978
3979     if (!create_ticket_prequel(s, pkt, age_add, tick_nonce)) {
3980         /* SSLfatal() already called */
3981         goto err;
3982     }
3983
3984     if (!WPACKET_get_total_written(pkt, &macoffset)
3985                /* Output key name */
3986             || !WPACKET_memcpy(pkt, key_name, sizeof(key_name))
3987                /* output IV */
3988             || !WPACKET_memcpy(pkt, iv, iv_len)
3989             || !WPACKET_reserve_bytes(pkt, slen + EVP_MAX_BLOCK_LENGTH,
3990                                       &encdata1)
3991                /* Encrypt session data */
3992             || !EVP_EncryptUpdate(ctx, encdata1, &len, senc, slen)
3993             || !WPACKET_allocate_bytes(pkt, len, &encdata2)
3994             || encdata1 != encdata2
3995             || !EVP_EncryptFinal(ctx, encdata1 + len, &lenfinal)
3996             || !WPACKET_allocate_bytes(pkt, lenfinal, &encdata2)
3997             || encdata1 + len != encdata2
3998             || len + lenfinal > slen + EVP_MAX_BLOCK_LENGTH
3999             || !WPACKET_get_total_written(pkt, &macendoffset)
4000             || !ssl_hmac_update(hctx,
4001                                 (unsigned char *)s->init_buf->data + macoffset,
4002                                 macendoffset - macoffset)
4003             || !WPACKET_reserve_bytes(pkt, EVP_MAX_MD_SIZE, &macdata1)
4004             || !ssl_hmac_final(hctx, macdata1, &hlen, EVP_MAX_MD_SIZE)
4005             || hlen > EVP_MAX_MD_SIZE
4006             || !WPACKET_allocate_bytes(pkt, hlen, &macdata2)
4007             || macdata1 != macdata2) {
4008         SSLfatal(s, SSL_AD_INTERNAL_ERROR,
4009                  SSL_F_CONSTRUCT_STATELESS_TICKET, ERR_R_INTERNAL_ERROR);
4010         goto err;
4011     }
4012
4013     /* Close the sub-packet created by create_ticket_prequel() */
4014     if (!WPACKET_close(pkt)) {
4015         SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_F_CONSTRUCT_STATELESS_TICKET,
4016                  ERR_R_INTERNAL_ERROR);
4017         goto err;
4018     }
4019
4020     ok = 1;
4021  err:
4022     OPENSSL_free(senc);
4023     EVP_CIPHER_CTX_free(ctx);
4024     ssl_hmac_free(hctx);
4025     return ok;
4026 }
4027
4028 static int construct_stateful_ticket(SSL *s, WPACKET *pkt, uint32_t age_add,
4029                                      unsigned char *tick_nonce)
4030 {
4031     if (!create_ticket_prequel(s, pkt, age_add, tick_nonce)) {
4032         /* SSLfatal() already called */
4033         return 0;
4034     }
4035
4036     if (!WPACKET_memcpy(pkt, s->session->session_id,
4037                         s->session->session_id_length)
4038             || !WPACKET_close(pkt)) {
4039         SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_F_CONSTRUCT_STATEFUL_TICKET,
4040                  ERR_R_INTERNAL_ERROR);
4041         return 0;
4042     }
4043
4044     return 1;
4045 }
4046
4047 int tls_construct_new_session_ticket(SSL *s, WPACKET *pkt)
4048 {
4049     SSL_CTX *tctx = s->session_ctx;
4050     unsigned char tick_nonce[TICKET_NONCE_SIZE];
4051     union {
4052         unsigned char age_add_c[sizeof(uint32_t)];
4053         uint32_t age_add;
4054     } age_add_u;
4055
4056     age_add_u.age_add = 0;
4057
4058     if (SSL_IS_TLS13(s)) {
4059         size_t i, hashlen;
4060         uint64_t nonce;
4061         static const unsigned char nonce_label[] = "resumption";
4062         const EVP_MD *md = ssl_handshake_md(s);
4063         int hashleni = EVP_MD_size(md);
4064
4065         /* Ensure cast to size_t is safe */
4066         if (!ossl_assert(hashleni >= 0)) {
4067             SSLfatal(s, SSL_AD_INTERNAL_ERROR,
4068                      SSL_F_TLS_CONSTRUCT_NEW_SESSION_TICKET,
4069                      ERR_R_INTERNAL_ERROR);
4070             goto err;
4071         }
4072         hashlen = (size_t)hashleni;
4073
4074         /*
4075          * If we already sent one NewSessionTicket, or we resumed then
4076          * s->session may already be in a cache and so we must not modify it.
4077          * Instead we need to take a copy of it and modify that.
4078          */
4079         if (s->sent_tickets != 0 || s->hit) {
4080             SSL_SESSION *new_sess = ssl_session_dup(s->session, 0);
4081
4082             if (new_sess == NULL) {
4083                 /* SSLfatal already called */
4084                 goto err;
4085             }
4086
4087             SSL_SESSION_free(s->session);
4088             s->session = new_sess;
4089         }
4090
4091         if (!ssl_generate_session_id(s, s->session)) {
4092             /* SSLfatal() already called */
4093             goto err;
4094         }
4095         if (RAND_bytes_ex(s->ctx->libctx, age_add_u.age_add_c,
4096                           sizeof(age_add_u)) <= 0) {
4097             SSLfatal(s, SSL_AD_INTERNAL_ERROR,
4098                      SSL_F_TLS_CONSTRUCT_NEW_SESSION_TICKET,
4099                      ERR_R_INTERNAL_ERROR);
4100             goto err;
4101         }
4102         s->session->ext.tick_age_add = age_add_u.age_add;
4103
4104         nonce = s->next_ticket_nonce;
4105         for (i = TICKET_NONCE_SIZE; i > 0; i--) {
4106             tick_nonce[i - 1] = (unsigned char)(nonce & 0xff);
4107             nonce >>= 8;
4108         }
4109
4110         if (!tls13_hkdf_expand(s, md, s->resumption_master_secret,
4111                                nonce_label,
4112                                sizeof(nonce_label) - 1,
4113                                tick_nonce,
4114                                TICKET_NONCE_SIZE,
4115                                s->session->master_key,
4116                                hashlen, 1)) {
4117             /* SSLfatal() already called */
4118             goto err;
4119         }
4120         s->session->master_key_length = hashlen;
4121
4122         s->session->time = (long)time(NULL);
4123         if (s->s3.alpn_selected != NULL) {
4124             OPENSSL_free(s->session->ext.alpn_selected);
4125             s->session->ext.alpn_selected =
4126                 OPENSSL_memdup(s->s3.alpn_selected, s->s3.alpn_selected_len);
4127             if (s->session->ext.alpn_selected == NULL) {
4128                 SSLfatal(s, SSL_AD_INTERNAL_ERROR,
4129                          SSL_F_TLS_CONSTRUCT_NEW_SESSION_TICKET,
4130                          ERR_R_MALLOC_FAILURE);
4131                 goto err;
4132             }
4133             s->session->ext.alpn_selected_len = s->s3.alpn_selected_len;
4134         }
4135         s->session->ext.max_early_data = s->max_early_data;
4136     }
4137
4138     if (tctx->generate_ticket_cb != NULL &&
4139         tctx->generate_ticket_cb(s, tctx->ticket_cb_data) == 0)
4140         goto err;
4141
4142     /*
4143      * If we are using anti-replay protection then we behave as if
4144      * SSL_OP_NO_TICKET is set - we are caching tickets anyway so there
4145      * is no point in using full stateless tickets.
4146      */
4147     if (SSL_IS_TLS13(s)
4148             && ((s->options & SSL_OP_NO_TICKET) != 0
4149                 || (s->max_early_data > 0
4150                     && (s->options & SSL_OP_NO_ANTI_REPLAY) == 0))) {
4151         if (!construct_stateful_ticket(s, pkt, age_add_u.age_add, tick_nonce)) {
4152             /* SSLfatal() already called */
4153             goto err;
4154         }
4155     } else if (!construct_stateless_ticket(s, pkt, age_add_u.age_add,
4156                                            tick_nonce)) {
4157         /* SSLfatal() already called */
4158         goto err;
4159     }
4160
4161     if (SSL_IS_TLS13(s)) {
4162         if (!tls_construct_extensions(s, pkt,
4163                                       SSL_EXT_TLS1_3_NEW_SESSION_TICKET,
4164                                       NULL, 0)) {
4165             /* SSLfatal() already called */
4166             goto err;
4167         }
4168         /*
4169          * Increment both |sent_tickets| and |next_ticket_nonce|. |sent_tickets|
4170          * gets reset to 0 if we send more tickets following a post-handshake
4171          * auth, but |next_ticket_nonce| does not.  If we're sending extra
4172          * tickets, decrement the count of pending extra tickets.
4173          */
4174         s->sent_tickets++;
4175         s->next_ticket_nonce++;
4176         if (s->ext.extra_tickets_expected > 0)
4177             s->ext.extra_tickets_expected--;
4178         ssl_update_cache(s, SSL_SESS_CACHE_SERVER);
4179     }
4180
4181     return 1;
4182  err:
4183     return 0;
4184 }
4185
4186 /*
4187  * In TLSv1.3 this is called from the extensions code, otherwise it is used to
4188  * create a separate message. Returns 1 on success or 0 on failure.
4189  */
4190 int tls_construct_cert_status_body(SSL *s, WPACKET *pkt)
4191 {
4192     if (!WPACKET_put_bytes_u8(pkt, s->ext.status_type)
4193             || !WPACKET_sub_memcpy_u24(pkt, s->ext.ocsp.resp,
4194                                        s->ext.ocsp.resp_len)) {
4195         SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_F_TLS_CONSTRUCT_CERT_STATUS_BODY,
4196                  ERR_R_INTERNAL_ERROR);
4197         return 0;
4198     }
4199
4200     return 1;
4201 }
4202
4203 int tls_construct_cert_status(SSL *s, WPACKET *pkt)
4204 {
4205     if (!tls_construct_cert_status_body(s, pkt)) {
4206         /* SSLfatal() already called */
4207         return 0;
4208     }
4209
4210     return 1;
4211 }
4212
4213 #ifndef OPENSSL_NO_NEXTPROTONEG
4214 /*
4215  * tls_process_next_proto reads a Next Protocol Negotiation handshake message.
4216  * It sets the next_proto member in s if found
4217  */
4218 MSG_PROCESS_RETURN tls_process_next_proto(SSL *s, PACKET *pkt)
4219 {
4220     PACKET next_proto, padding;
4221     size_t next_proto_len;
4222
4223     /*-
4224      * The payload looks like:
4225      *   uint8 proto_len;
4226      *   uint8 proto[proto_len];
4227      *   uint8 padding_len;
4228      *   uint8 padding[padding_len];
4229      */
4230     if (!PACKET_get_length_prefixed_1(pkt, &next_proto)
4231         || !PACKET_get_length_prefixed_1(pkt, &padding)
4232         || PACKET_remaining(pkt) > 0) {
4233         SSLfatal(s, SSL_AD_DECODE_ERROR, SSL_F_TLS_PROCESS_NEXT_PROTO,
4234                  SSL_R_LENGTH_MISMATCH);
4235         return MSG_PROCESS_ERROR;
4236     }
4237
4238     if (!PACKET_memdup(&next_proto, &s->ext.npn, &next_proto_len)) {
4239         s->ext.npn_len = 0;
4240         SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_F_TLS_PROCESS_NEXT_PROTO,
4241                  ERR_R_INTERNAL_ERROR);
4242         return MSG_PROCESS_ERROR;
4243     }
4244
4245     s->ext.npn_len = (unsigned char)next_proto_len;
4246
4247     return MSG_PROCESS_CONTINUE_READING;
4248 }
4249 #endif
4250
4251 static int tls_construct_encrypted_extensions(SSL *s, WPACKET *pkt)
4252 {
4253     if (!tls_construct_extensions(s, pkt, SSL_EXT_TLS1_3_ENCRYPTED_EXTENSIONS,
4254                                   NULL, 0)) {
4255         /* SSLfatal() already called */
4256         return 0;
4257     }
4258
4259     return 1;
4260 }
4261
4262 MSG_PROCESS_RETURN tls_process_end_of_early_data(SSL *s, PACKET *pkt)
4263 {
4264     if (PACKET_remaining(pkt) != 0) {
4265         SSLfatal(s, SSL_AD_DECODE_ERROR, SSL_F_TLS_PROCESS_END_OF_EARLY_DATA,
4266                  SSL_R_LENGTH_MISMATCH);
4267         return MSG_PROCESS_ERROR;
4268     }
4269
4270     if (s->early_data_state != SSL_EARLY_DATA_READING
4271             && s->early_data_state != SSL_EARLY_DATA_READ_RETRY) {
4272         SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_F_TLS_PROCESS_END_OF_EARLY_DATA,
4273                  ERR_R_INTERNAL_ERROR);
4274         return MSG_PROCESS_ERROR;
4275     }
4276
4277     /*
4278      * EndOfEarlyData signals a key change so the end of the message must be on
4279      * a record boundary.
4280      */
4281     if (RECORD_LAYER_processed_read_pending(&s->rlayer)) {
4282         SSLfatal(s, SSL_AD_UNEXPECTED_MESSAGE,
4283                  SSL_F_TLS_PROCESS_END_OF_EARLY_DATA,
4284                  SSL_R_NOT_ON_RECORD_BOUNDARY);
4285         return MSG_PROCESS_ERROR;
4286     }
4287
4288     s->early_data_state = SSL_EARLY_DATA_FINISHED_READING;
4289     if (!s->method->ssl3_enc->change_cipher_state(s,
4290                 SSL3_CC_HANDSHAKE | SSL3_CHANGE_CIPHER_SERVER_READ)) {
4291         /* SSLfatal() already called */
4292         return MSG_PROCESS_ERROR;
4293     }
4294
4295     return MSG_PROCESS_CONTINUE_READING;
4296 }