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