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