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