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