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