Revert "Delay setting the sig algs until after the cert_cb has been called"
[oweals/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->peer_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->peer_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->peer_ciphers);
1946             sk_SSL_CIPHER_free(s->cipher_list_by_id);
1947             s->cipher_list_by_id = sk_SSL_CIPHER_dup(s->peer_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->peer_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->peer_ciphers);
2052         s->peer_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         if (!tls1_set_server_sigalgs(s)) {
2069             /* SSLfatal() already called */
2070             goto err;
2071         }
2072     }
2073
2074     sk_SSL_CIPHER_free(ciphers);
2075     sk_SSL_CIPHER_free(scsvs);
2076     OPENSSL_free(clienthello->pre_proc_exts);
2077     OPENSSL_free(s->clienthello);
2078     s->clienthello = NULL;
2079     return 1;
2080  err:
2081     sk_SSL_CIPHER_free(ciphers);
2082     sk_SSL_CIPHER_free(scsvs);
2083     OPENSSL_free(clienthello->pre_proc_exts);
2084     OPENSSL_free(s->clienthello);
2085     s->clienthello = NULL;
2086
2087     return 0;
2088 }
2089
2090 /*
2091  * Call the status request callback if needed. Upon success, returns 1.
2092  * Upon failure, returns 0.
2093  */
2094 static int tls_handle_status_request(SSL *s)
2095 {
2096     s->ext.status_expected = 0;
2097
2098     /*
2099      * If status request then ask callback what to do. Note: this must be
2100      * called after servername callbacks in case the certificate has changed,
2101      * and must be called after the cipher has been chosen because this may
2102      * influence which certificate is sent
2103      */
2104     if (s->ext.status_type != TLSEXT_STATUSTYPE_nothing && s->ctx != NULL
2105             && s->ctx->ext.status_cb != NULL) {
2106         int ret;
2107
2108         /* If no certificate can't return certificate status */
2109         if (s->s3.tmp.cert != NULL) {
2110             /*
2111              * Set current certificate to one we will use so SSL_get_certificate
2112              * et al can pick it up.
2113              */
2114             s->cert->key = s->s3.tmp.cert;
2115             ret = s->ctx->ext.status_cb(s, s->ctx->ext.status_arg);
2116             switch (ret) {
2117                 /* We don't want to send a status request response */
2118             case SSL_TLSEXT_ERR_NOACK:
2119                 s->ext.status_expected = 0;
2120                 break;
2121                 /* status request response should be sent */
2122             case SSL_TLSEXT_ERR_OK:
2123                 if (s->ext.ocsp.resp)
2124                     s->ext.status_expected = 1;
2125                 break;
2126                 /* something bad happened */
2127             case SSL_TLSEXT_ERR_ALERT_FATAL:
2128             default:
2129                 SSLfatal(s, SSL_AD_INTERNAL_ERROR,
2130                          SSL_F_TLS_HANDLE_STATUS_REQUEST,
2131                          SSL_R_CLIENTHELLO_TLSEXT);
2132                 return 0;
2133             }
2134         }
2135     }
2136
2137     return 1;
2138 }
2139
2140 /*
2141  * Call the alpn_select callback if needed. Upon success, returns 1.
2142  * Upon failure, returns 0.
2143  */
2144 int tls_handle_alpn(SSL *s)
2145 {
2146     const unsigned char *selected = NULL;
2147     unsigned char selected_len = 0;
2148
2149     if (s->ctx->ext.alpn_select_cb != NULL && s->s3.alpn_proposed != NULL) {
2150         int r = s->ctx->ext.alpn_select_cb(s, &selected, &selected_len,
2151                                            s->s3.alpn_proposed,
2152                                            (unsigned int)s->s3.alpn_proposed_len,
2153                                            s->ctx->ext.alpn_select_cb_arg);
2154
2155         if (r == SSL_TLSEXT_ERR_OK) {
2156             OPENSSL_free(s->s3.alpn_selected);
2157             s->s3.alpn_selected = OPENSSL_memdup(selected, selected_len);
2158             if (s->s3.alpn_selected == NULL) {
2159                 SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_F_TLS_HANDLE_ALPN,
2160                          ERR_R_INTERNAL_ERROR);
2161                 return 0;
2162             }
2163             s->s3.alpn_selected_len = selected_len;
2164 #ifndef OPENSSL_NO_NEXTPROTONEG
2165             /* ALPN takes precedence over NPN. */
2166             s->s3.npn_seen = 0;
2167 #endif
2168
2169             /* Check ALPN is consistent with session */
2170             if (s->session->ext.alpn_selected == NULL
2171                         || selected_len != s->session->ext.alpn_selected_len
2172                         || memcmp(selected, s->session->ext.alpn_selected,
2173                                   selected_len) != 0) {
2174                 /* Not consistent so can't be used for early_data */
2175                 s->ext.early_data_ok = 0;
2176
2177                 if (!s->hit) {
2178                     /*
2179                      * This is a new session and so alpn_selected should have
2180                      * been initialised to NULL. We should update it with the
2181                      * selected ALPN.
2182                      */
2183                     if (!ossl_assert(s->session->ext.alpn_selected == NULL)) {
2184                         SSLfatal(s, SSL_AD_INTERNAL_ERROR,
2185                                  SSL_F_TLS_HANDLE_ALPN,
2186                                  ERR_R_INTERNAL_ERROR);
2187                         return 0;
2188                     }
2189                     s->session->ext.alpn_selected = OPENSSL_memdup(selected,
2190                                                                    selected_len);
2191                     if (s->session->ext.alpn_selected == NULL) {
2192                         SSLfatal(s, SSL_AD_INTERNAL_ERROR,
2193                                  SSL_F_TLS_HANDLE_ALPN,
2194                                  ERR_R_INTERNAL_ERROR);
2195                         return 0;
2196                     }
2197                     s->session->ext.alpn_selected_len = selected_len;
2198                 }
2199             }
2200
2201             return 1;
2202         } else if (r != SSL_TLSEXT_ERR_NOACK) {
2203             SSLfatal(s, SSL_AD_NO_APPLICATION_PROTOCOL, SSL_F_TLS_HANDLE_ALPN,
2204                      SSL_R_NO_APPLICATION_PROTOCOL);
2205             return 0;
2206         }
2207         /*
2208          * If r == SSL_TLSEXT_ERR_NOACK then behave as if no callback was
2209          * present.
2210          */
2211     }
2212
2213     /* Check ALPN is consistent with session */
2214     if (s->session->ext.alpn_selected != NULL) {
2215         /* Not consistent so can't be used for early_data */
2216         s->ext.early_data_ok = 0;
2217     }
2218
2219     return 1;
2220 }
2221
2222 WORK_STATE tls_post_process_client_hello(SSL *s, WORK_STATE wst)
2223 {
2224     const SSL_CIPHER *cipher;
2225
2226     if (wst == WORK_MORE_A) {
2227         int rv = tls_early_post_process_client_hello(s);
2228         if (rv == 0) {
2229             /* SSLfatal() was already called */
2230             goto err;
2231         }
2232         if (rv < 0)
2233             return WORK_MORE_A;
2234         wst = WORK_MORE_B;
2235     }
2236     if (wst == WORK_MORE_B) {
2237         if (!s->hit || SSL_IS_TLS13(s)) {
2238             /* Let cert callback update server certificates if required */
2239             if (!s->hit && s->cert->cert_cb != NULL) {
2240                 int rv = s->cert->cert_cb(s, s->cert->cert_cb_arg);
2241                 if (rv == 0) {
2242                     SSLfatal(s, SSL_AD_INTERNAL_ERROR,
2243                              SSL_F_TLS_POST_PROCESS_CLIENT_HELLO,
2244                              SSL_R_CERT_CB_ERROR);
2245                     goto err;
2246                 }
2247                 if (rv < 0) {
2248                     s->rwstate = SSL_X509_LOOKUP;
2249                     return WORK_MORE_B;
2250                 }
2251                 s->rwstate = SSL_NOTHING;
2252             }
2253
2254             /* In TLSv1.3 we selected the ciphersuite before resumption */
2255             if (!SSL_IS_TLS13(s)) {
2256                 cipher =
2257                     ssl3_choose_cipher(s, s->peer_ciphers, SSL_get_ciphers(s));
2258
2259                 if (cipher == NULL) {
2260                     SSLfatal(s, SSL_AD_HANDSHAKE_FAILURE,
2261                              SSL_F_TLS_POST_PROCESS_CLIENT_HELLO,
2262                              SSL_R_NO_SHARED_CIPHER);
2263                     goto err;
2264                 }
2265                 s->s3.tmp.new_cipher = cipher;
2266             }
2267             if (!s->hit) {
2268                 if (!tls_choose_sigalg(s, 1)) {
2269                     /* SSLfatal already called */
2270                     goto err;
2271                 }
2272                 /* check whether we should disable session resumption */
2273                 if (s->not_resumable_session_cb != NULL)
2274                     s->session->not_resumable =
2275                         s->not_resumable_session_cb(s,
2276                             ((s->s3.tmp.new_cipher->algorithm_mkey
2277                               & (SSL_kDHE | SSL_kECDHE)) != 0));
2278                 if (s->session->not_resumable)
2279                     /* do not send a session ticket */
2280                     s->ext.ticket_expected = 0;
2281             }
2282         } else {
2283             /* Session-id reuse */
2284             s->s3.tmp.new_cipher = s->session->cipher;
2285         }
2286
2287         /*-
2288          * we now have the following setup.
2289          * client_random
2290          * cipher_list          - our preferred list of ciphers
2291          * ciphers              - the clients preferred list of ciphers
2292          * compression          - basically ignored right now
2293          * ssl version is set   - sslv3
2294          * s->session           - The ssl session has been setup.
2295          * s->hit               - session reuse flag
2296          * s->s3.tmp.new_cipher - the new cipher to use.
2297          */
2298
2299         /*
2300          * Call status_request callback if needed. Has to be done after the
2301          * certificate callbacks etc above.
2302          */
2303         if (!tls_handle_status_request(s)) {
2304             /* SSLfatal() already called */
2305             goto err;
2306         }
2307         /*
2308          * Call alpn_select callback if needed.  Has to be done after SNI and
2309          * cipher negotiation (HTTP/2 restricts permitted ciphers). In TLSv1.3
2310          * we already did this because cipher negotiation happens earlier, and
2311          * we must handle ALPN before we decide whether to accept early_data.
2312          */
2313         if (!SSL_IS_TLS13(s) && !tls_handle_alpn(s)) {
2314             /* SSLfatal() already called */
2315             goto err;
2316         }
2317
2318         wst = WORK_MORE_C;
2319     }
2320 #ifndef OPENSSL_NO_SRP
2321     if (wst == WORK_MORE_C) {
2322         int ret;
2323         if ((ret = ssl_check_srp_ext_ClientHello(s)) == 0) {
2324             /*
2325              * callback indicates further work to be done
2326              */
2327             s->rwstate = SSL_X509_LOOKUP;
2328             return WORK_MORE_C;
2329         }
2330         if (ret < 0) {
2331             /* SSLfatal() already called */
2332             goto err;
2333         }
2334     }
2335 #endif
2336
2337     return WORK_FINISHED_STOP;
2338  err:
2339     return WORK_ERROR;
2340 }
2341
2342 int tls_construct_server_hello(SSL *s, WPACKET *pkt)
2343 {
2344     int compm;
2345     size_t sl, len;
2346     int version;
2347     unsigned char *session_id;
2348     int usetls13 = SSL_IS_TLS13(s) || s->hello_retry_request == SSL_HRR_PENDING;
2349
2350     version = usetls13 ? TLS1_2_VERSION : s->version;
2351     if (!WPACKET_put_bytes_u16(pkt, version)
2352                /*
2353                 * Random stuff. Filling of the server_random takes place in
2354                 * tls_process_client_hello()
2355                 */
2356             || !WPACKET_memcpy(pkt,
2357                                s->hello_retry_request == SSL_HRR_PENDING
2358                                    ? hrrrandom : s->s3.server_random,
2359                                SSL3_RANDOM_SIZE)) {
2360         SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_F_TLS_CONSTRUCT_SERVER_HELLO,
2361                  ERR_R_INTERNAL_ERROR);
2362         return 0;
2363     }
2364
2365     /*-
2366      * There are several cases for the session ID to send
2367      * back in the server hello:
2368      * - For session reuse from the session cache,
2369      *   we send back the old session ID.
2370      * - If stateless session reuse (using a session ticket)
2371      *   is successful, we send back the client's "session ID"
2372      *   (which doesn't actually identify the session).
2373      * - If it is a new session, we send back the new
2374      *   session ID.
2375      * - However, if we want the new session to be single-use,
2376      *   we send back a 0-length session ID.
2377      * - In TLSv1.3 we echo back the session id sent to us by the client
2378      *   regardless
2379      * s->hit is non-zero in either case of session reuse,
2380      * so the following won't overwrite an ID that we're supposed
2381      * to send back.
2382      */
2383     if (s->session->not_resumable ||
2384         (!(s->ctx->session_cache_mode & SSL_SESS_CACHE_SERVER)
2385          && !s->hit))
2386         s->session->session_id_length = 0;
2387
2388     if (usetls13) {
2389         sl = s->tmp_session_id_len;
2390         session_id = s->tmp_session_id;
2391     } else {
2392         sl = s->session->session_id_length;
2393         session_id = s->session->session_id;
2394     }
2395
2396     if (sl > sizeof(s->session->session_id)) {
2397         SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_F_TLS_CONSTRUCT_SERVER_HELLO,
2398                  ERR_R_INTERNAL_ERROR);
2399         return 0;
2400     }
2401
2402     /* set up the compression method */
2403 #ifdef OPENSSL_NO_COMP
2404     compm = 0;
2405 #else
2406     if (usetls13 || s->s3.tmp.new_compression == NULL)
2407         compm = 0;
2408     else
2409         compm = s->s3.tmp.new_compression->id;
2410 #endif
2411
2412     if (!WPACKET_sub_memcpy_u8(pkt, session_id, sl)
2413             || !s->method->put_cipher_by_char(s->s3.tmp.new_cipher, pkt, &len)
2414             || !WPACKET_put_bytes_u8(pkt, compm)) {
2415         SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_F_TLS_CONSTRUCT_SERVER_HELLO,
2416                  ERR_R_INTERNAL_ERROR);
2417         return 0;
2418     }
2419
2420     if (!tls_construct_extensions(s, pkt,
2421                                   s->hello_retry_request == SSL_HRR_PENDING
2422                                       ? SSL_EXT_TLS1_3_HELLO_RETRY_REQUEST
2423                                       : (SSL_IS_TLS13(s)
2424                                           ? SSL_EXT_TLS1_3_SERVER_HELLO
2425                                           : SSL_EXT_TLS1_2_SERVER_HELLO),
2426                                   NULL, 0)) {
2427         /* SSLfatal() already called */
2428         return 0;
2429     }
2430
2431     if (s->hello_retry_request == SSL_HRR_PENDING) {
2432         /* Ditch the session. We'll create a new one next time around */
2433         SSL_SESSION_free(s->session);
2434         s->session = NULL;
2435         s->hit = 0;
2436
2437         /*
2438          * Re-initialise the Transcript Hash. We're going to prepopulate it with
2439          * a synthetic message_hash in place of ClientHello1.
2440          */
2441         if (!create_synthetic_message_hash(s, NULL, 0, NULL, 0)) {
2442             /* SSLfatal() already called */
2443             return 0;
2444         }
2445     } else if (!(s->verify_mode & SSL_VERIFY_PEER)
2446                 && !ssl3_digest_cached_records(s, 0)) {
2447         /* SSLfatal() already called */;
2448         return 0;
2449     }
2450
2451     return 1;
2452 }
2453
2454 int tls_construct_server_done(SSL *s, WPACKET *pkt)
2455 {
2456     if (!s->s3.tmp.cert_request) {
2457         if (!ssl3_digest_cached_records(s, 0)) {
2458             /* SSLfatal() already called */
2459             return 0;
2460         }
2461     }
2462     return 1;
2463 }
2464
2465 int tls_construct_server_key_exchange(SSL *s, WPACKET *pkt)
2466 {
2467 #ifndef OPENSSL_NO_DH
2468     EVP_PKEY *pkdh = NULL;
2469 #endif
2470 #ifndef OPENSSL_NO_EC
2471     unsigned char *encodedPoint = NULL;
2472     size_t encodedlen = 0;
2473     int curve_id = 0;
2474 #endif
2475     const SIGALG_LOOKUP *lu = s->s3.tmp.sigalg;
2476     int i;
2477     unsigned long type;
2478     const BIGNUM *r[4];
2479     EVP_MD_CTX *md_ctx = EVP_MD_CTX_new();
2480     EVP_PKEY_CTX *pctx = NULL;
2481     size_t paramlen, paramoffset;
2482
2483     if (!WPACKET_get_total_written(pkt, &paramoffset)) {
2484         SSLfatal(s, SSL_AD_INTERNAL_ERROR,
2485                  SSL_F_TLS_CONSTRUCT_SERVER_KEY_EXCHANGE, ERR_R_INTERNAL_ERROR);
2486         goto err;
2487     }
2488
2489     if (md_ctx == NULL) {
2490         SSLfatal(s, SSL_AD_INTERNAL_ERROR,
2491                  SSL_F_TLS_CONSTRUCT_SERVER_KEY_EXCHANGE, ERR_R_MALLOC_FAILURE);
2492         goto err;
2493     }
2494
2495     type = s->s3.tmp.new_cipher->algorithm_mkey;
2496
2497     r[0] = r[1] = r[2] = r[3] = NULL;
2498 #ifndef OPENSSL_NO_PSK
2499     /* Plain PSK or RSAPSK nothing to do */
2500     if (type & (SSL_kPSK | SSL_kRSAPSK)) {
2501     } else
2502 #endif                          /* !OPENSSL_NO_PSK */
2503 #ifndef OPENSSL_NO_DH
2504     if (type & (SSL_kDHE | SSL_kDHEPSK)) {
2505         CERT *cert = s->cert;
2506
2507         EVP_PKEY *pkdhp = NULL;
2508         DH *dh;
2509
2510         if (s->cert->dh_tmp_auto) {
2511             DH *dhp = ssl_get_auto_dh(s);
2512             pkdh = EVP_PKEY_new();
2513             if (pkdh == NULL || dhp == NULL) {
2514                 DH_free(dhp);
2515                 SSLfatal(s, SSL_AD_INTERNAL_ERROR,
2516                          SSL_F_TLS_CONSTRUCT_SERVER_KEY_EXCHANGE,
2517                          ERR_R_INTERNAL_ERROR);
2518                 goto err;
2519             }
2520             EVP_PKEY_assign_DH(pkdh, dhp);
2521             pkdhp = pkdh;
2522         } else {
2523             pkdhp = cert->dh_tmp;
2524         }
2525         if ((pkdhp == NULL) && (s->cert->dh_tmp_cb != NULL)) {
2526             DH *dhp = s->cert->dh_tmp_cb(s, 0, 1024);
2527             pkdh = ssl_dh_to_pkey(dhp);
2528             if (pkdh == NULL) {
2529                 SSLfatal(s, SSL_AD_INTERNAL_ERROR,
2530                          SSL_F_TLS_CONSTRUCT_SERVER_KEY_EXCHANGE,
2531                          ERR_R_INTERNAL_ERROR);
2532                 goto err;
2533             }
2534             pkdhp = pkdh;
2535         }
2536         if (pkdhp == NULL) {
2537             SSLfatal(s, SSL_AD_INTERNAL_ERROR,
2538                      SSL_F_TLS_CONSTRUCT_SERVER_KEY_EXCHANGE,
2539                      SSL_R_MISSING_TMP_DH_KEY);
2540             goto err;
2541         }
2542         if (!ssl_security(s, SSL_SECOP_TMP_DH,
2543                           EVP_PKEY_security_bits(pkdhp), 0, pkdhp)) {
2544             SSLfatal(s, SSL_AD_HANDSHAKE_FAILURE,
2545                      SSL_F_TLS_CONSTRUCT_SERVER_KEY_EXCHANGE,
2546                      SSL_R_DH_KEY_TOO_SMALL);
2547             goto err;
2548         }
2549         if (s->s3.tmp.pkey != NULL) {
2550             SSLfatal(s, SSL_AD_INTERNAL_ERROR,
2551                      SSL_F_TLS_CONSTRUCT_SERVER_KEY_EXCHANGE,
2552                      ERR_R_INTERNAL_ERROR);
2553             goto err;
2554         }
2555
2556         s->s3.tmp.pkey = ssl_generate_pkey(pkdhp);
2557         if (s->s3.tmp.pkey == NULL) {
2558             /* SSLfatal() already called */
2559             goto err;
2560         }
2561
2562         dh = EVP_PKEY_get0_DH(s->s3.tmp.pkey);
2563         if (dh == NULL) {
2564             SSLfatal(s, SSL_AD_INTERNAL_ERROR,
2565                      SSL_F_TLS_CONSTRUCT_SERVER_KEY_EXCHANGE,
2566                      ERR_R_INTERNAL_ERROR);
2567             goto err;
2568         }
2569
2570         EVP_PKEY_free(pkdh);
2571         pkdh = NULL;
2572
2573         DH_get0_pqg(dh, &r[0], NULL, &r[1]);
2574         DH_get0_key(dh, &r[2], NULL);
2575     } else
2576 #endif
2577 #ifndef OPENSSL_NO_EC
2578     if (type & (SSL_kECDHE | SSL_kECDHEPSK)) {
2579
2580         if (s->s3.tmp.pkey != NULL) {
2581             SSLfatal(s, SSL_AD_INTERNAL_ERROR,
2582                      SSL_F_TLS_CONSTRUCT_SERVER_KEY_EXCHANGE,
2583                      ERR_R_INTERNAL_ERROR);
2584             goto err;
2585         }
2586
2587         /* Get NID of appropriate shared curve */
2588         curve_id = tls1_shared_group(s, -2);
2589         if (curve_id == 0) {
2590             SSLfatal(s, SSL_AD_HANDSHAKE_FAILURE,
2591                      SSL_F_TLS_CONSTRUCT_SERVER_KEY_EXCHANGE,
2592                      SSL_R_UNSUPPORTED_ELLIPTIC_CURVE);
2593             goto err;
2594         }
2595         s->s3.tmp.pkey = ssl_generate_pkey_group(s, curve_id);
2596         /* Generate a new key for this curve */
2597         if (s->s3.tmp.pkey == NULL) {
2598             /* SSLfatal() already called */
2599             goto err;
2600         }
2601
2602         /* Encode the public key. */
2603         encodedlen = EVP_PKEY_get1_tls_encodedpoint(s->s3.tmp.pkey,
2604                                                     &encodedPoint);
2605         if (encodedlen == 0) {
2606             SSLfatal(s, SSL_AD_INTERNAL_ERROR,
2607                      SSL_F_TLS_CONSTRUCT_SERVER_KEY_EXCHANGE, ERR_R_EC_LIB);
2608             goto err;
2609         }
2610
2611         /*
2612          * We'll generate the serverKeyExchange message explicitly so we
2613          * can set these to NULLs
2614          */
2615         r[0] = NULL;
2616         r[1] = NULL;
2617         r[2] = NULL;
2618         r[3] = NULL;
2619     } else
2620 #endif                          /* !OPENSSL_NO_EC */
2621 #ifndef OPENSSL_NO_SRP
2622     if (type & SSL_kSRP) {
2623         if ((s->srp_ctx.N == NULL) ||
2624             (s->srp_ctx.g == NULL) ||
2625             (s->srp_ctx.s == NULL) || (s->srp_ctx.B == NULL)) {
2626             SSLfatal(s, SSL_AD_INTERNAL_ERROR,
2627                      SSL_F_TLS_CONSTRUCT_SERVER_KEY_EXCHANGE,
2628                      SSL_R_MISSING_SRP_PARAM);
2629             goto err;
2630         }
2631         r[0] = s->srp_ctx.N;
2632         r[1] = s->srp_ctx.g;
2633         r[2] = s->srp_ctx.s;
2634         r[3] = s->srp_ctx.B;
2635     } else
2636 #endif
2637     {
2638         SSLfatal(s, SSL_AD_INTERNAL_ERROR,
2639                  SSL_F_TLS_CONSTRUCT_SERVER_KEY_EXCHANGE,
2640                  SSL_R_UNKNOWN_KEY_EXCHANGE_TYPE);
2641         goto err;
2642     }
2643
2644     if (((s->s3.tmp.new_cipher->algorithm_auth & (SSL_aNULL | SSL_aSRP)) != 0)
2645         || ((s->s3.tmp.new_cipher->algorithm_mkey & SSL_PSK)) != 0) {
2646         lu = NULL;
2647     } else if (lu == NULL) {
2648         SSLfatal(s, SSL_AD_DECODE_ERROR,
2649                  SSL_F_TLS_CONSTRUCT_SERVER_KEY_EXCHANGE, ERR_R_INTERNAL_ERROR);
2650         goto err;
2651     }
2652
2653 #ifndef OPENSSL_NO_PSK
2654     if (type & SSL_PSK) {
2655         size_t len = (s->cert->psk_identity_hint == NULL)
2656                         ? 0 : strlen(s->cert->psk_identity_hint);
2657
2658         /*
2659          * It should not happen that len > PSK_MAX_IDENTITY_LEN - we already
2660          * checked this when we set the identity hint - but just in case
2661          */
2662         if (len > PSK_MAX_IDENTITY_LEN
2663                 || !WPACKET_sub_memcpy_u16(pkt, s->cert->psk_identity_hint,
2664                                            len)) {
2665             SSLfatal(s, SSL_AD_INTERNAL_ERROR,
2666                      SSL_F_TLS_CONSTRUCT_SERVER_KEY_EXCHANGE,
2667                      ERR_R_INTERNAL_ERROR);
2668             goto err;
2669         }
2670     }
2671 #endif
2672
2673     for (i = 0; i < 4 && r[i] != NULL; i++) {
2674         unsigned char *binval;
2675         int res;
2676
2677 #ifndef OPENSSL_NO_SRP
2678         if ((i == 2) && (type & SSL_kSRP)) {
2679             res = WPACKET_start_sub_packet_u8(pkt);
2680         } else
2681 #endif
2682             res = WPACKET_start_sub_packet_u16(pkt);
2683
2684         if (!res) {
2685             SSLfatal(s, SSL_AD_INTERNAL_ERROR,
2686                      SSL_F_TLS_CONSTRUCT_SERVER_KEY_EXCHANGE,
2687                      ERR_R_INTERNAL_ERROR);
2688             goto err;
2689         }
2690
2691 #ifndef OPENSSL_NO_DH
2692         /*-
2693          * for interoperability with some versions of the Microsoft TLS
2694          * stack, we need to zero pad the DHE pub key to the same length
2695          * as the prime
2696          */
2697         if ((i == 2) && (type & (SSL_kDHE | SSL_kDHEPSK))) {
2698             size_t len = BN_num_bytes(r[0]) - BN_num_bytes(r[2]);
2699
2700             if (len > 0) {
2701                 if (!WPACKET_allocate_bytes(pkt, len, &binval)) {
2702                     SSLfatal(s, SSL_AD_INTERNAL_ERROR,
2703                              SSL_F_TLS_CONSTRUCT_SERVER_KEY_EXCHANGE,
2704                              ERR_R_INTERNAL_ERROR);
2705                     goto err;
2706                 }
2707                 memset(binval, 0, len);
2708             }
2709         }
2710 #endif
2711         if (!WPACKET_allocate_bytes(pkt, BN_num_bytes(r[i]), &binval)
2712                 || !WPACKET_close(pkt)) {
2713             SSLfatal(s, SSL_AD_INTERNAL_ERROR,
2714                      SSL_F_TLS_CONSTRUCT_SERVER_KEY_EXCHANGE,
2715                      ERR_R_INTERNAL_ERROR);
2716             goto err;
2717         }
2718
2719         BN_bn2bin(r[i], binval);
2720     }
2721
2722 #ifndef OPENSSL_NO_EC
2723     if (type & (SSL_kECDHE | SSL_kECDHEPSK)) {
2724         /*
2725          * We only support named (not generic) curves. In this situation, the
2726          * ServerKeyExchange message has: [1 byte CurveType], [2 byte CurveName]
2727          * [1 byte length of encoded point], followed by the actual encoded
2728          * point itself
2729          */
2730         if (!WPACKET_put_bytes_u8(pkt, NAMED_CURVE_TYPE)
2731                 || !WPACKET_put_bytes_u8(pkt, 0)
2732                 || !WPACKET_put_bytes_u8(pkt, curve_id)
2733                 || !WPACKET_sub_memcpy_u8(pkt, encodedPoint, encodedlen)) {
2734             SSLfatal(s, SSL_AD_INTERNAL_ERROR,
2735                      SSL_F_TLS_CONSTRUCT_SERVER_KEY_EXCHANGE,
2736                      ERR_R_INTERNAL_ERROR);
2737             goto err;
2738         }
2739         OPENSSL_free(encodedPoint);
2740         encodedPoint = NULL;
2741     }
2742 #endif
2743
2744     /* not anonymous */
2745     if (lu != NULL) {
2746         EVP_PKEY *pkey = s->s3.tmp.cert->privatekey;
2747         const EVP_MD *md;
2748         unsigned char *sigbytes1, *sigbytes2, *tbs;
2749         size_t siglen, tbslen;
2750         int rv;
2751
2752         if (pkey == NULL || !tls1_lookup_md(lu, &md)) {
2753             /* Should never happen */
2754             SSLfatal(s, SSL_AD_INTERNAL_ERROR,
2755                      SSL_F_TLS_CONSTRUCT_SERVER_KEY_EXCHANGE,
2756                      ERR_R_INTERNAL_ERROR);
2757             goto err;
2758         }
2759         /* Get length of the parameters we have written above */
2760         if (!WPACKET_get_length(pkt, &paramlen)) {
2761             SSLfatal(s, SSL_AD_INTERNAL_ERROR,
2762                      SSL_F_TLS_CONSTRUCT_SERVER_KEY_EXCHANGE,
2763                      ERR_R_INTERNAL_ERROR);
2764             goto err;
2765         }
2766         /* send signature algorithm */
2767         if (SSL_USE_SIGALGS(s) && !WPACKET_put_bytes_u16(pkt, lu->sigalg)) {
2768             SSLfatal(s, SSL_AD_INTERNAL_ERROR,
2769                      SSL_F_TLS_CONSTRUCT_SERVER_KEY_EXCHANGE,
2770                      ERR_R_INTERNAL_ERROR);
2771             goto err;
2772         }
2773         /*
2774          * Create the signature. We don't know the actual length of the sig
2775          * until after we've created it, so we reserve enough bytes for it
2776          * up front, and then properly allocate them in the WPACKET
2777          * afterwards.
2778          */
2779         siglen = EVP_PKEY_size(pkey);
2780         if (!WPACKET_sub_reserve_bytes_u16(pkt, siglen, &sigbytes1)
2781             || EVP_DigestSignInit(md_ctx, &pctx, md, NULL, pkey) <= 0) {
2782             SSLfatal(s, SSL_AD_INTERNAL_ERROR,
2783                      SSL_F_TLS_CONSTRUCT_SERVER_KEY_EXCHANGE,
2784                      ERR_R_INTERNAL_ERROR);
2785             goto err;
2786         }
2787         if (lu->sig == EVP_PKEY_RSA_PSS) {
2788             if (EVP_PKEY_CTX_set_rsa_padding(pctx, RSA_PKCS1_PSS_PADDING) <= 0
2789                 || EVP_PKEY_CTX_set_rsa_pss_saltlen(pctx, RSA_PSS_SALTLEN_DIGEST) <= 0) {
2790                 SSLfatal(s, SSL_AD_INTERNAL_ERROR,
2791                          SSL_F_TLS_CONSTRUCT_SERVER_KEY_EXCHANGE,
2792                         ERR_R_EVP_LIB);
2793                 goto err;
2794             }
2795         }
2796         tbslen = construct_key_exchange_tbs(s, &tbs,
2797                                             s->init_buf->data + paramoffset,
2798                                             paramlen);
2799         if (tbslen == 0) {
2800             /* SSLfatal() already called */
2801             goto err;
2802         }
2803         rv = EVP_DigestSign(md_ctx, sigbytes1, &siglen, tbs, tbslen);
2804         OPENSSL_free(tbs);
2805         if (rv <= 0 || !WPACKET_sub_allocate_bytes_u16(pkt, siglen, &sigbytes2)
2806             || sigbytes1 != sigbytes2) {
2807             SSLfatal(s, SSL_AD_INTERNAL_ERROR,
2808                      SSL_F_TLS_CONSTRUCT_SERVER_KEY_EXCHANGE,
2809                      ERR_R_INTERNAL_ERROR);
2810             goto err;
2811         }
2812     }
2813
2814     EVP_MD_CTX_free(md_ctx);
2815     return 1;
2816  err:
2817 #ifndef OPENSSL_NO_DH
2818     EVP_PKEY_free(pkdh);
2819 #endif
2820 #ifndef OPENSSL_NO_EC
2821     OPENSSL_free(encodedPoint);
2822 #endif
2823     EVP_MD_CTX_free(md_ctx);
2824     return 0;
2825 }
2826
2827 int tls_construct_certificate_request(SSL *s, WPACKET *pkt)
2828 {
2829     if (SSL_IS_TLS13(s)) {
2830         /* Send random context when doing post-handshake auth */
2831         if (s->post_handshake_auth == SSL_PHA_REQUEST_PENDING) {
2832             OPENSSL_free(s->pha_context);
2833             s->pha_context_len = 32;
2834             if ((s->pha_context = OPENSSL_malloc(s->pha_context_len)) == NULL
2835                     || RAND_bytes(s->pha_context, s->pha_context_len) <= 0
2836                     || !WPACKET_sub_memcpy_u8(pkt, s->pha_context, s->pha_context_len)) {
2837                 SSLfatal(s, SSL_AD_INTERNAL_ERROR,
2838                          SSL_F_TLS_CONSTRUCT_CERTIFICATE_REQUEST,
2839                          ERR_R_INTERNAL_ERROR);
2840                 return 0;
2841             }
2842             /* reset the handshake hash back to just after the ClientFinished */
2843             if (!tls13_restore_handshake_digest_for_pha(s)) {
2844                 /* SSLfatal() already called */
2845                 return 0;
2846             }
2847         } else {
2848             if (!WPACKET_put_bytes_u8(pkt, 0)) {
2849                 SSLfatal(s, SSL_AD_INTERNAL_ERROR,
2850                          SSL_F_TLS_CONSTRUCT_CERTIFICATE_REQUEST,
2851                          ERR_R_INTERNAL_ERROR);
2852                 return 0;
2853             }
2854         }
2855
2856         if (!tls_construct_extensions(s, pkt,
2857                                       SSL_EXT_TLS1_3_CERTIFICATE_REQUEST, NULL,
2858                                       0)) {
2859             /* SSLfatal() already called */
2860             return 0;
2861         }
2862         goto done;
2863     }
2864
2865     /* get the list of acceptable cert types */
2866     if (!WPACKET_start_sub_packet_u8(pkt)
2867         || !ssl3_get_req_cert_type(s, pkt) || !WPACKET_close(pkt)) {
2868         SSLfatal(s, SSL_AD_INTERNAL_ERROR,
2869                  SSL_F_TLS_CONSTRUCT_CERTIFICATE_REQUEST, ERR_R_INTERNAL_ERROR);
2870         return 0;
2871     }
2872
2873     if (SSL_USE_SIGALGS(s)) {
2874         const uint16_t *psigs;
2875         size_t nl = tls12_get_psigalgs(s, 1, &psigs);
2876
2877         if (!WPACKET_start_sub_packet_u16(pkt)
2878                 || !WPACKET_set_flags(pkt, WPACKET_FLAGS_NON_ZERO_LENGTH)
2879                 || !tls12_copy_sigalgs(s, pkt, psigs, nl)
2880                 || !WPACKET_close(pkt)) {
2881             SSLfatal(s, SSL_AD_INTERNAL_ERROR,
2882                      SSL_F_TLS_CONSTRUCT_CERTIFICATE_REQUEST,
2883                      ERR_R_INTERNAL_ERROR);
2884             return 0;
2885         }
2886     }
2887
2888     if (!construct_ca_names(s, get_ca_names(s), pkt)) {
2889         /* SSLfatal() already called */
2890         return 0;
2891     }
2892
2893  done:
2894     s->certreqs_sent++;
2895     s->s3.tmp.cert_request = 1;
2896     return 1;
2897 }
2898
2899 static int tls_process_cke_psk_preamble(SSL *s, PACKET *pkt)
2900 {
2901 #ifndef OPENSSL_NO_PSK
2902     unsigned char psk[PSK_MAX_PSK_LEN];
2903     size_t psklen;
2904     PACKET psk_identity;
2905
2906     if (!PACKET_get_length_prefixed_2(pkt, &psk_identity)) {
2907         SSLfatal(s, SSL_AD_DECODE_ERROR, SSL_F_TLS_PROCESS_CKE_PSK_PREAMBLE,
2908                  SSL_R_LENGTH_MISMATCH);
2909         return 0;
2910     }
2911     if (PACKET_remaining(&psk_identity) > PSK_MAX_IDENTITY_LEN) {
2912         SSLfatal(s, SSL_AD_DECODE_ERROR, SSL_F_TLS_PROCESS_CKE_PSK_PREAMBLE,
2913                  SSL_R_DATA_LENGTH_TOO_LONG);
2914         return 0;
2915     }
2916     if (s->psk_server_callback == NULL) {
2917         SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_F_TLS_PROCESS_CKE_PSK_PREAMBLE,
2918                  SSL_R_PSK_NO_SERVER_CB);
2919         return 0;
2920     }
2921
2922     if (!PACKET_strndup(&psk_identity, &s->session->psk_identity)) {
2923         SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_F_TLS_PROCESS_CKE_PSK_PREAMBLE,
2924                  ERR_R_INTERNAL_ERROR);
2925         return 0;
2926     }
2927
2928     psklen = s->psk_server_callback(s, s->session->psk_identity,
2929                                     psk, sizeof(psk));
2930
2931     if (psklen > PSK_MAX_PSK_LEN) {
2932         SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_F_TLS_PROCESS_CKE_PSK_PREAMBLE,
2933                  ERR_R_INTERNAL_ERROR);
2934         return 0;
2935     } else if (psklen == 0) {
2936         /*
2937          * PSK related to the given identity not found
2938          */
2939         SSLfatal(s, SSL_AD_UNKNOWN_PSK_IDENTITY,
2940                  SSL_F_TLS_PROCESS_CKE_PSK_PREAMBLE,
2941                  SSL_R_PSK_IDENTITY_NOT_FOUND);
2942         return 0;
2943     }
2944
2945     OPENSSL_free(s->s3.tmp.psk);
2946     s->s3.tmp.psk = OPENSSL_memdup(psk, psklen);
2947     OPENSSL_cleanse(psk, psklen);
2948
2949     if (s->s3.tmp.psk == NULL) {
2950         SSLfatal(s, SSL_AD_INTERNAL_ERROR,
2951                  SSL_F_TLS_PROCESS_CKE_PSK_PREAMBLE, ERR_R_MALLOC_FAILURE);
2952         return 0;
2953     }
2954
2955     s->s3.tmp.psklen = psklen;
2956
2957     return 1;
2958 #else
2959     /* Should never happen */
2960     SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_F_TLS_PROCESS_CKE_PSK_PREAMBLE,
2961              ERR_R_INTERNAL_ERROR);
2962     return 0;
2963 #endif
2964 }
2965
2966 static int tls_process_cke_rsa(SSL *s, PACKET *pkt)
2967 {
2968 #ifndef OPENSSL_NO_RSA
2969     unsigned char rand_premaster_secret[SSL_MAX_MASTER_KEY_LENGTH];
2970     int decrypt_len;
2971     unsigned char decrypt_good, version_good;
2972     size_t j, padding_len;
2973     PACKET enc_premaster;
2974     RSA *rsa = NULL;
2975     unsigned char *rsa_decrypt = NULL;
2976     int ret = 0;
2977
2978     rsa = EVP_PKEY_get0_RSA(s->cert->pkeys[SSL_PKEY_RSA].privatekey);
2979     if (rsa == NULL) {
2980         SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_F_TLS_PROCESS_CKE_RSA,
2981                  SSL_R_MISSING_RSA_CERTIFICATE);
2982         return 0;
2983     }
2984
2985     /* SSLv3 and pre-standard DTLS omit the length bytes. */
2986     if (s->version == SSL3_VERSION || s->version == DTLS1_BAD_VER) {
2987         enc_premaster = *pkt;
2988     } else {
2989         if (!PACKET_get_length_prefixed_2(pkt, &enc_premaster)
2990             || PACKET_remaining(pkt) != 0) {
2991             SSLfatal(s, SSL_AD_DECODE_ERROR, SSL_F_TLS_PROCESS_CKE_RSA,
2992                      SSL_R_LENGTH_MISMATCH);
2993             return 0;
2994         }
2995     }
2996
2997     /*
2998      * We want to be sure that the plaintext buffer size makes it safe to
2999      * iterate over the entire size of a premaster secret
3000      * (SSL_MAX_MASTER_KEY_LENGTH). Reject overly short RSA keys because
3001      * their ciphertext cannot accommodate a premaster secret anyway.
3002      */
3003     if (RSA_size(rsa) < SSL_MAX_MASTER_KEY_LENGTH) {
3004         SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_F_TLS_PROCESS_CKE_RSA,
3005                  RSA_R_KEY_SIZE_TOO_SMALL);
3006         return 0;
3007     }
3008
3009     rsa_decrypt = OPENSSL_malloc(RSA_size(rsa));
3010     if (rsa_decrypt == NULL) {
3011         SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_F_TLS_PROCESS_CKE_RSA,
3012                  ERR_R_MALLOC_FAILURE);
3013         return 0;
3014     }
3015
3016     /*
3017      * We must not leak whether a decryption failure occurs because of
3018      * Bleichenbacher's attack on PKCS #1 v1.5 RSA padding (see RFC 2246,
3019      * section 7.4.7.1). The code follows that advice of the TLS RFC and
3020      * generates a random premaster secret for the case that the decrypt
3021      * fails. See https://tools.ietf.org/html/rfc5246#section-7.4.7.1
3022      */
3023
3024     if (RAND_priv_bytes(rand_premaster_secret,
3025                       sizeof(rand_premaster_secret)) <= 0) {
3026         SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_F_TLS_PROCESS_CKE_RSA,
3027                  ERR_R_INTERNAL_ERROR);
3028         goto err;
3029     }
3030
3031     /*
3032      * Decrypt with no padding. PKCS#1 padding will be removed as part of
3033      * the timing-sensitive code below.
3034      */
3035      /* TODO(size_t): Convert this function */
3036     decrypt_len = (int)RSA_private_decrypt((int)PACKET_remaining(&enc_premaster),
3037                                            PACKET_data(&enc_premaster),
3038                                            rsa_decrypt, rsa, RSA_NO_PADDING);
3039     if (decrypt_len < 0) {
3040         SSLfatal(s, SSL_AD_DECRYPT_ERROR, SSL_F_TLS_PROCESS_CKE_RSA,
3041                  ERR_R_INTERNAL_ERROR);
3042         goto err;
3043     }
3044
3045     /* Check the padding. See RFC 3447, section 7.2.2. */
3046
3047     /*
3048      * The smallest padded premaster is 11 bytes of overhead. Small keys
3049      * are publicly invalid, so this may return immediately. This ensures
3050      * PS is at least 8 bytes.
3051      */
3052     if (decrypt_len < 11 + SSL_MAX_MASTER_KEY_LENGTH) {
3053         SSLfatal(s, SSL_AD_DECRYPT_ERROR, SSL_F_TLS_PROCESS_CKE_RSA,
3054                  SSL_R_DECRYPTION_FAILED);
3055         goto err;
3056     }
3057
3058     padding_len = decrypt_len - SSL_MAX_MASTER_KEY_LENGTH;
3059     decrypt_good = constant_time_eq_int_8(rsa_decrypt[0], 0) &
3060         constant_time_eq_int_8(rsa_decrypt[1], 2);
3061     for (j = 2; j < padding_len - 1; j++) {
3062         decrypt_good &= ~constant_time_is_zero_8(rsa_decrypt[j]);
3063     }
3064     decrypt_good &= constant_time_is_zero_8(rsa_decrypt[padding_len - 1]);
3065
3066     /*
3067      * If the version in the decrypted pre-master secret is correct then
3068      * version_good will be 0xff, otherwise it'll be zero. The
3069      * Klima-Pokorny-Rosa extension of Bleichenbacher's attack
3070      * (http://eprint.iacr.org/2003/052/) exploits the version number
3071      * check as a "bad version oracle". Thus version checks are done in
3072      * constant time and are treated like any other decryption error.
3073      */
3074     version_good =
3075         constant_time_eq_8(rsa_decrypt[padding_len],
3076                            (unsigned)(s->client_version >> 8));
3077     version_good &=
3078         constant_time_eq_8(rsa_decrypt[padding_len + 1],
3079                            (unsigned)(s->client_version & 0xff));
3080
3081     /*
3082      * The premaster secret must contain the same version number as the
3083      * ClientHello to detect version rollback attacks (strangely, the
3084      * protocol does not offer such protection for DH ciphersuites).
3085      * However, buggy clients exist that send the negotiated protocol
3086      * version instead if the server does not support the requested
3087      * protocol version. If SSL_OP_TLS_ROLLBACK_BUG is set, tolerate such
3088      * clients.
3089      */
3090     if (s->options & SSL_OP_TLS_ROLLBACK_BUG) {
3091         unsigned char workaround_good;
3092         workaround_good = constant_time_eq_8(rsa_decrypt[padding_len],
3093                                              (unsigned)(s->version >> 8));
3094         workaround_good &=
3095             constant_time_eq_8(rsa_decrypt[padding_len + 1],
3096                                (unsigned)(s->version & 0xff));
3097         version_good |= workaround_good;
3098     }
3099
3100     /*
3101      * Both decryption and version must be good for decrypt_good to
3102      * remain non-zero (0xff).
3103      */
3104     decrypt_good &= version_good;
3105
3106     /*
3107      * Now copy rand_premaster_secret over from p using
3108      * decrypt_good_mask. If decryption failed, then p does not
3109      * contain valid plaintext, however, a check above guarantees
3110      * it is still sufficiently large to read from.
3111      */
3112     for (j = 0; j < sizeof(rand_premaster_secret); j++) {
3113         rsa_decrypt[padding_len + j] =
3114             constant_time_select_8(decrypt_good,
3115                                    rsa_decrypt[padding_len + j],
3116                                    rand_premaster_secret[j]);
3117     }
3118
3119     if (!ssl_generate_master_secret(s, rsa_decrypt + padding_len,
3120                                     sizeof(rand_premaster_secret), 0)) {
3121         /* SSLfatal() already called */
3122         goto err;
3123     }
3124
3125     ret = 1;
3126  err:
3127     OPENSSL_free(rsa_decrypt);
3128     return ret;
3129 #else
3130     /* Should never happen */
3131     SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_F_TLS_PROCESS_CKE_RSA,
3132              ERR_R_INTERNAL_ERROR);
3133     return 0;
3134 #endif
3135 }
3136
3137 static int tls_process_cke_dhe(SSL *s, PACKET *pkt)
3138 {
3139 #ifndef OPENSSL_NO_DH
3140     EVP_PKEY *skey = NULL;
3141     DH *cdh;
3142     unsigned int i;
3143     BIGNUM *pub_key;
3144     const unsigned char *data;
3145     EVP_PKEY *ckey = NULL;
3146     int ret = 0;
3147
3148     if (!PACKET_get_net_2(pkt, &i) || PACKET_remaining(pkt) != i) {
3149         SSLfatal(s, SSL_AD_DECODE_ERROR, SSL_F_TLS_PROCESS_CKE_DHE,
3150                SSL_R_DH_PUBLIC_VALUE_LENGTH_IS_WRONG);
3151         goto err;
3152     }
3153     skey = s->s3.tmp.pkey;
3154     if (skey == NULL) {
3155         SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_F_TLS_PROCESS_CKE_DHE,
3156                  SSL_R_MISSING_TMP_DH_KEY);
3157         goto err;
3158     }
3159
3160     if (PACKET_remaining(pkt) == 0L) {
3161         SSLfatal(s, SSL_AD_DECODE_ERROR, SSL_F_TLS_PROCESS_CKE_DHE,
3162                  SSL_R_MISSING_TMP_DH_KEY);
3163         goto err;
3164     }
3165     if (!PACKET_get_bytes(pkt, &data, i)) {
3166         /* We already checked we have enough data */
3167         SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_F_TLS_PROCESS_CKE_DHE,
3168                  ERR_R_INTERNAL_ERROR);
3169         goto err;
3170     }
3171     ckey = EVP_PKEY_new();
3172     if (ckey == NULL || EVP_PKEY_copy_parameters(ckey, skey) == 0) {
3173         SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_F_TLS_PROCESS_CKE_DHE,
3174                  SSL_R_BN_LIB);
3175         goto err;
3176     }
3177
3178     cdh = EVP_PKEY_get0_DH(ckey);
3179     pub_key = BN_bin2bn(data, i, NULL);
3180     if (pub_key == NULL || cdh == NULL || !DH_set0_key(cdh, pub_key, NULL)) {
3181         SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_F_TLS_PROCESS_CKE_DHE,
3182                  ERR_R_INTERNAL_ERROR);
3183         BN_free(pub_key);
3184         goto err;
3185     }
3186
3187     if (ssl_derive(s, skey, ckey, 1) == 0) {
3188         /* SSLfatal() already called */
3189         goto err;
3190     }
3191
3192     ret = 1;
3193     EVP_PKEY_free(s->s3.tmp.pkey);
3194     s->s3.tmp.pkey = NULL;
3195  err:
3196     EVP_PKEY_free(ckey);
3197     return ret;
3198 #else
3199     /* Should never happen */
3200     SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_F_TLS_PROCESS_CKE_DHE,
3201              ERR_R_INTERNAL_ERROR);
3202     return 0;
3203 #endif
3204 }
3205
3206 static int tls_process_cke_ecdhe(SSL *s, PACKET *pkt)
3207 {
3208 #ifndef OPENSSL_NO_EC
3209     EVP_PKEY *skey = s->s3.tmp.pkey;
3210     EVP_PKEY *ckey = NULL;
3211     int ret = 0;
3212
3213     if (PACKET_remaining(pkt) == 0L) {
3214         /* We don't support ECDH client auth */
3215         SSLfatal(s, SSL_AD_HANDSHAKE_FAILURE, SSL_F_TLS_PROCESS_CKE_ECDHE,
3216                  SSL_R_MISSING_TMP_ECDH_KEY);
3217         goto err;
3218     } else {
3219         unsigned int i;
3220         const unsigned char *data;
3221
3222         /*
3223          * Get client's public key from encoded point in the
3224          * ClientKeyExchange message.
3225          */
3226
3227         /* Get encoded point length */
3228         if (!PACKET_get_1(pkt, &i) || !PACKET_get_bytes(pkt, &data, i)
3229             || PACKET_remaining(pkt) != 0) {
3230             SSLfatal(s, SSL_AD_DECODE_ERROR, SSL_F_TLS_PROCESS_CKE_ECDHE,
3231                      SSL_R_LENGTH_MISMATCH);
3232             goto err;
3233         }
3234         if (skey == NULL) {
3235             SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_F_TLS_PROCESS_CKE_ECDHE,
3236                      SSL_R_MISSING_TMP_ECDH_KEY);
3237             goto err;
3238         }
3239
3240         ckey = EVP_PKEY_new();
3241         if (ckey == NULL || EVP_PKEY_copy_parameters(ckey, skey) <= 0) {
3242             SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_F_TLS_PROCESS_CKE_ECDHE,
3243                      ERR_R_EVP_LIB);
3244             goto err;
3245         }
3246         if (EVP_PKEY_set1_tls_encodedpoint(ckey, data, i) == 0) {
3247             SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_F_TLS_PROCESS_CKE_ECDHE,
3248                      ERR_R_EC_LIB);
3249             goto err;
3250         }
3251     }
3252
3253     if (ssl_derive(s, skey, ckey, 1) == 0) {
3254         /* SSLfatal() already called */
3255         goto err;
3256     }
3257
3258     ret = 1;
3259     EVP_PKEY_free(s->s3.tmp.pkey);
3260     s->s3.tmp.pkey = NULL;
3261  err:
3262     EVP_PKEY_free(ckey);
3263
3264     return ret;
3265 #else
3266     /* Should never happen */
3267     SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_F_TLS_PROCESS_CKE_ECDHE,
3268              ERR_R_INTERNAL_ERROR);
3269     return 0;
3270 #endif
3271 }
3272
3273 static int tls_process_cke_srp(SSL *s, PACKET *pkt)
3274 {
3275 #ifndef OPENSSL_NO_SRP
3276     unsigned int i;
3277     const unsigned char *data;
3278
3279     if (!PACKET_get_net_2(pkt, &i)
3280         || !PACKET_get_bytes(pkt, &data, i)) {
3281         SSLfatal(s, SSL_AD_DECODE_ERROR, SSL_F_TLS_PROCESS_CKE_SRP,
3282                  SSL_R_BAD_SRP_A_LENGTH);
3283         return 0;
3284     }
3285     if ((s->srp_ctx.A = BN_bin2bn(data, i, NULL)) == NULL) {
3286         SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_F_TLS_PROCESS_CKE_SRP,
3287                  ERR_R_BN_LIB);
3288         return 0;
3289     }
3290     if (BN_ucmp(s->srp_ctx.A, s->srp_ctx.N) >= 0 || BN_is_zero(s->srp_ctx.A)) {
3291         SSLfatal(s, SSL_AD_ILLEGAL_PARAMETER, SSL_F_TLS_PROCESS_CKE_SRP,
3292                  SSL_R_BAD_SRP_PARAMETERS);
3293         return 0;
3294     }
3295     OPENSSL_free(s->session->srp_username);
3296     s->session->srp_username = OPENSSL_strdup(s->srp_ctx.login);
3297     if (s->session->srp_username == NULL) {
3298         SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_F_TLS_PROCESS_CKE_SRP,
3299                  ERR_R_MALLOC_FAILURE);
3300         return 0;
3301     }
3302
3303     if (!srp_generate_server_master_secret(s)) {
3304         /* SSLfatal() already called */
3305         return 0;
3306     }
3307
3308     return 1;
3309 #else
3310     /* Should never happen */
3311     SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_F_TLS_PROCESS_CKE_SRP,
3312              ERR_R_INTERNAL_ERROR);
3313     return 0;
3314 #endif
3315 }
3316
3317 static int tls_process_cke_gost(SSL *s, PACKET *pkt)
3318 {
3319 #ifndef OPENSSL_NO_GOST
3320     EVP_PKEY_CTX *pkey_ctx;
3321     EVP_PKEY *client_pub_pkey = NULL, *pk = NULL;
3322     unsigned char premaster_secret[32];
3323     const unsigned char *start;
3324     size_t outlen = 32, inlen;
3325     unsigned long alg_a;
3326     unsigned int asn1id, asn1len;
3327     int ret = 0;
3328     PACKET encdata;
3329
3330     /* Get our certificate private key */
3331     alg_a = s->s3.tmp.new_cipher->algorithm_auth;
3332     if (alg_a & SSL_aGOST12) {
3333         /*
3334          * New GOST ciphersuites have SSL_aGOST01 bit too
3335          */
3336         pk = s->cert->pkeys[SSL_PKEY_GOST12_512].privatekey;
3337         if (pk == NULL) {
3338             pk = s->cert->pkeys[SSL_PKEY_GOST12_256].privatekey;
3339         }
3340         if (pk == NULL) {
3341             pk = s->cert->pkeys[SSL_PKEY_GOST01].privatekey;
3342         }
3343     } else if (alg_a & SSL_aGOST01) {
3344         pk = s->cert->pkeys[SSL_PKEY_GOST01].privatekey;
3345     }
3346
3347     pkey_ctx = EVP_PKEY_CTX_new(pk, NULL);
3348     if (pkey_ctx == NULL) {
3349         SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_F_TLS_PROCESS_CKE_GOST,
3350                  ERR_R_MALLOC_FAILURE);
3351         return 0;
3352     }
3353     if (EVP_PKEY_decrypt_init(pkey_ctx) <= 0) {
3354         SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_F_TLS_PROCESS_CKE_GOST,
3355                  ERR_R_INTERNAL_ERROR);
3356         return 0;
3357     }
3358     /*
3359      * If client certificate is present and is of the same type, maybe
3360      * use it for key exchange.  Don't mind errors from
3361      * EVP_PKEY_derive_set_peer, because it is completely valid to use a
3362      * client certificate for authorization only.
3363      */
3364     client_pub_pkey = X509_get0_pubkey(s->session->peer);
3365     if (client_pub_pkey) {
3366         if (EVP_PKEY_derive_set_peer(pkey_ctx, client_pub_pkey) <= 0)
3367             ERR_clear_error();
3368     }
3369     /* Decrypt session key */
3370     if (!PACKET_get_1(pkt, &asn1id)
3371             || asn1id != (V_ASN1_SEQUENCE | V_ASN1_CONSTRUCTED)
3372             || !PACKET_peek_1(pkt, &asn1len)) {
3373         SSLfatal(s, SSL_AD_DECODE_ERROR, SSL_F_TLS_PROCESS_CKE_GOST,
3374                  SSL_R_DECRYPTION_FAILED);
3375         goto err;
3376     }
3377     if (asn1len == 0x81) {
3378         /*
3379          * Long form length. Should only be one byte of length. Anything else
3380          * isn't supported.
3381          * We did a successful peek before so this shouldn't fail
3382          */
3383         if (!PACKET_forward(pkt, 1)) {
3384             SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_F_TLS_PROCESS_CKE_GOST,
3385                      SSL_R_DECRYPTION_FAILED);
3386             goto err;
3387         }
3388     } else  if (asn1len >= 0x80) {
3389         /*
3390          * Indefinite length, or more than one long form length bytes. We don't
3391          * support it
3392          */
3393         SSLfatal(s, SSL_AD_DECODE_ERROR, SSL_F_TLS_PROCESS_CKE_GOST,
3394                  SSL_R_DECRYPTION_FAILED);
3395         goto err;
3396     } /* else short form length */
3397
3398     if (!PACKET_as_length_prefixed_1(pkt, &encdata)) {
3399         SSLfatal(s, SSL_AD_DECODE_ERROR, SSL_F_TLS_PROCESS_CKE_GOST,
3400                  SSL_R_DECRYPTION_FAILED);
3401         goto err;
3402     }
3403     inlen = PACKET_remaining(&encdata);
3404     start = PACKET_data(&encdata);
3405
3406     if (EVP_PKEY_decrypt(pkey_ctx, premaster_secret, &outlen, start,
3407                          inlen) <= 0) {
3408         SSLfatal(s, SSL_AD_DECODE_ERROR, SSL_F_TLS_PROCESS_CKE_GOST,
3409                  SSL_R_DECRYPTION_FAILED);
3410         goto err;
3411     }
3412     /* Generate master secret */
3413     if (!ssl_generate_master_secret(s, premaster_secret,
3414                                     sizeof(premaster_secret), 0)) {
3415         /* SSLfatal() already called */
3416         goto err;
3417     }
3418     /* Check if pubkey from client certificate was used */
3419     if (EVP_PKEY_CTX_ctrl(pkey_ctx, -1, -1, EVP_PKEY_CTRL_PEER_KEY, 2,
3420                           NULL) > 0)
3421         s->statem.no_cert_verify = 1;
3422
3423     ret = 1;
3424  err:
3425     EVP_PKEY_CTX_free(pkey_ctx);
3426     return ret;
3427 #else
3428     /* Should never happen */
3429     SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_F_TLS_PROCESS_CKE_GOST,
3430              ERR_R_INTERNAL_ERROR);
3431     return 0;
3432 #endif
3433 }
3434
3435 MSG_PROCESS_RETURN tls_process_client_key_exchange(SSL *s, PACKET *pkt)
3436 {
3437     unsigned long alg_k;
3438
3439     alg_k = s->s3.tmp.new_cipher->algorithm_mkey;
3440
3441     /* For PSK parse and retrieve identity, obtain PSK key */
3442     if ((alg_k & SSL_PSK) && !tls_process_cke_psk_preamble(s, pkt)) {
3443         /* SSLfatal() already called */
3444         goto err;
3445     }
3446
3447     if (alg_k & SSL_kPSK) {
3448         /* Identity extracted earlier: should be nothing left */
3449         if (PACKET_remaining(pkt) != 0) {
3450             SSLfatal(s, SSL_AD_DECODE_ERROR,
3451                      SSL_F_TLS_PROCESS_CLIENT_KEY_EXCHANGE,
3452                      SSL_R_LENGTH_MISMATCH);
3453             goto err;
3454         }
3455         /* PSK handled by ssl_generate_master_secret */
3456         if (!ssl_generate_master_secret(s, NULL, 0, 0)) {
3457             /* SSLfatal() already called */
3458             goto err;
3459         }
3460     } else if (alg_k & (SSL_kRSA | SSL_kRSAPSK)) {
3461         if (!tls_process_cke_rsa(s, pkt)) {
3462             /* SSLfatal() already called */
3463             goto err;
3464         }
3465     } else if (alg_k & (SSL_kDHE | SSL_kDHEPSK)) {
3466         if (!tls_process_cke_dhe(s, pkt)) {
3467             /* SSLfatal() already called */
3468             goto err;
3469         }
3470     } else if (alg_k & (SSL_kECDHE | SSL_kECDHEPSK)) {
3471         if (!tls_process_cke_ecdhe(s, pkt)) {
3472             /* SSLfatal() already called */
3473             goto err;
3474         }
3475     } else if (alg_k & SSL_kSRP) {
3476         if (!tls_process_cke_srp(s, pkt)) {
3477             /* SSLfatal() already called */
3478             goto err;
3479         }
3480     } else if (alg_k & SSL_kGOST) {
3481         if (!tls_process_cke_gost(s, pkt)) {
3482             /* SSLfatal() already called */
3483             goto err;
3484         }
3485     } else {
3486         SSLfatal(s, SSL_AD_INTERNAL_ERROR,
3487                  SSL_F_TLS_PROCESS_CLIENT_KEY_EXCHANGE,
3488                  SSL_R_UNKNOWN_CIPHER_TYPE);
3489         goto err;
3490     }
3491
3492     return MSG_PROCESS_CONTINUE_PROCESSING;
3493  err:
3494 #ifndef OPENSSL_NO_PSK
3495     OPENSSL_clear_free(s->s3.tmp.psk, s->s3.tmp.psklen);
3496     s->s3.tmp.psk = NULL;
3497 #endif
3498     return MSG_PROCESS_ERROR;
3499 }
3500
3501 WORK_STATE tls_post_process_client_key_exchange(SSL *s, WORK_STATE wst)
3502 {
3503 #ifndef OPENSSL_NO_SCTP
3504     if (wst == WORK_MORE_A) {
3505         if (SSL_IS_DTLS(s)) {
3506             unsigned char sctpauthkey[64];
3507             char labelbuffer[sizeof(DTLS1_SCTP_AUTH_LABEL)];
3508             size_t labellen;
3509             /*
3510              * Add new shared key for SCTP-Auth, will be ignored if no SCTP
3511              * used.
3512              */
3513             memcpy(labelbuffer, DTLS1_SCTP_AUTH_LABEL,
3514                    sizeof(DTLS1_SCTP_AUTH_LABEL));
3515
3516             /* Don't include the terminating zero. */
3517             labellen = sizeof(labelbuffer) - 1;
3518             if (s->mode & SSL_MODE_DTLS_SCTP_LABEL_LENGTH_BUG)
3519                 labellen += 1;
3520
3521             if (SSL_export_keying_material(s, sctpauthkey,
3522                                            sizeof(sctpauthkey), labelbuffer,
3523                                            labellen, NULL, 0,
3524                                            0) <= 0) {
3525                 SSLfatal(s, SSL_AD_INTERNAL_ERROR,
3526                          SSL_F_TLS_POST_PROCESS_CLIENT_KEY_EXCHANGE,
3527                          ERR_R_INTERNAL_ERROR);
3528                 return WORK_ERROR;
3529             }
3530
3531             BIO_ctrl(SSL_get_wbio(s), BIO_CTRL_DGRAM_SCTP_ADD_AUTH_KEY,
3532                      sizeof(sctpauthkey), sctpauthkey);
3533         }
3534     }
3535 #endif
3536
3537     if (s->statem.no_cert_verify || !s->session->peer) {
3538         /*
3539          * No certificate verify or no peer certificate so we no longer need
3540          * the handshake_buffer
3541          */
3542         if (!ssl3_digest_cached_records(s, 0)) {
3543             /* SSLfatal() already called */
3544             return WORK_ERROR;
3545         }
3546         return WORK_FINISHED_CONTINUE;
3547     } else {
3548         if (!s->s3.handshake_buffer) {
3549             SSLfatal(s, SSL_AD_INTERNAL_ERROR,
3550                      SSL_F_TLS_POST_PROCESS_CLIENT_KEY_EXCHANGE,
3551                      ERR_R_INTERNAL_ERROR);
3552             return WORK_ERROR;
3553         }
3554         /*
3555          * For sigalgs freeze the handshake buffer. If we support
3556          * extms we've done this already so this is a no-op
3557          */
3558         if (!ssl3_digest_cached_records(s, 1)) {
3559             /* SSLfatal() already called */
3560             return WORK_ERROR;
3561         }
3562     }
3563
3564     return WORK_FINISHED_CONTINUE;
3565 }
3566
3567 MSG_PROCESS_RETURN tls_process_client_certificate(SSL *s, PACKET *pkt)
3568 {
3569     int i;
3570     MSG_PROCESS_RETURN ret = MSG_PROCESS_ERROR;
3571     X509 *x = NULL;
3572     unsigned long l;
3573     const unsigned char *certstart, *certbytes;
3574     STACK_OF(X509) *sk = NULL;
3575     PACKET spkt, context;
3576     size_t chainidx;
3577     SSL_SESSION *new_sess = NULL;
3578
3579     /*
3580      * To get this far we must have read encrypted data from the client. We no
3581      * longer tolerate unencrypted alerts. This value is ignored if less than
3582      * TLSv1.3
3583      */
3584     s->statem.enc_read_state = ENC_READ_STATE_VALID;
3585
3586     if ((sk = sk_X509_new_null()) == NULL) {
3587         SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_F_TLS_PROCESS_CLIENT_CERTIFICATE,
3588                  ERR_R_MALLOC_FAILURE);
3589         goto err;
3590     }
3591
3592     if (SSL_IS_TLS13(s) && (!PACKET_get_length_prefixed_1(pkt, &context)
3593                             || (s->pha_context == NULL && PACKET_remaining(&context) != 0)
3594                             || (s->pha_context != NULL &&
3595                                 !PACKET_equal(&context, s->pha_context, s->pha_context_len)))) {
3596         SSLfatal(s, SSL_AD_DECODE_ERROR, SSL_F_TLS_PROCESS_CLIENT_CERTIFICATE,
3597                  SSL_R_INVALID_CONTEXT);
3598         goto err;
3599     }
3600
3601     if (!PACKET_get_length_prefixed_3(pkt, &spkt)
3602             || PACKET_remaining(pkt) != 0) {
3603         SSLfatal(s, SSL_AD_DECODE_ERROR, SSL_F_TLS_PROCESS_CLIENT_CERTIFICATE,
3604                  SSL_R_LENGTH_MISMATCH);
3605         goto err;
3606     }
3607
3608     for (chainidx = 0; PACKET_remaining(&spkt) > 0; chainidx++) {
3609         if (!PACKET_get_net_3(&spkt, &l)
3610             || !PACKET_get_bytes(&spkt, &certbytes, l)) {
3611             SSLfatal(s, SSL_AD_DECODE_ERROR,
3612                      SSL_F_TLS_PROCESS_CLIENT_CERTIFICATE,
3613                      SSL_R_CERT_LENGTH_MISMATCH);
3614             goto err;
3615         }
3616
3617         certstart = certbytes;
3618         x = d2i_X509(NULL, (const unsigned char **)&certbytes, l);
3619         if (x == NULL) {
3620             SSLfatal(s, SSL_AD_DECODE_ERROR,
3621                      SSL_F_TLS_PROCESS_CLIENT_CERTIFICATE, ERR_R_ASN1_LIB);
3622             goto err;
3623         }
3624         if (certbytes != (certstart + l)) {
3625             SSLfatal(s, SSL_AD_DECODE_ERROR,
3626                      SSL_F_TLS_PROCESS_CLIENT_CERTIFICATE,
3627                      SSL_R_CERT_LENGTH_MISMATCH);
3628             goto err;
3629         }
3630
3631         if (SSL_IS_TLS13(s)) {
3632             RAW_EXTENSION *rawexts = NULL;
3633             PACKET extensions;
3634
3635             if (!PACKET_get_length_prefixed_2(&spkt, &extensions)) {
3636                 SSLfatal(s, SSL_AD_DECODE_ERROR,
3637                          SSL_F_TLS_PROCESS_CLIENT_CERTIFICATE,
3638                          SSL_R_BAD_LENGTH);
3639                 goto err;
3640             }
3641             if (!tls_collect_extensions(s, &extensions,
3642                                         SSL_EXT_TLS1_3_CERTIFICATE, &rawexts,
3643                                         NULL, chainidx == 0)
3644                 || !tls_parse_all_extensions(s, SSL_EXT_TLS1_3_CERTIFICATE,
3645                                              rawexts, x, chainidx,
3646                                              PACKET_remaining(&spkt) == 0)) {
3647                 OPENSSL_free(rawexts);
3648                 goto err;
3649             }
3650             OPENSSL_free(rawexts);
3651         }
3652
3653         if (!sk_X509_push(sk, x)) {
3654             SSLfatal(s, SSL_AD_INTERNAL_ERROR,
3655                      SSL_F_TLS_PROCESS_CLIENT_CERTIFICATE,
3656                      ERR_R_MALLOC_FAILURE);
3657             goto err;
3658         }
3659         x = NULL;
3660     }
3661
3662     if (sk_X509_num(sk) <= 0) {
3663         /* TLS does not mind 0 certs returned */
3664         if (s->version == SSL3_VERSION) {
3665             SSLfatal(s, SSL_AD_HANDSHAKE_FAILURE,
3666                      SSL_F_TLS_PROCESS_CLIENT_CERTIFICATE,
3667                      SSL_R_NO_CERTIFICATES_RETURNED);
3668             goto err;
3669         }
3670         /* Fail for TLS only if we required a certificate */
3671         else if ((s->verify_mode & SSL_VERIFY_PEER) &&
3672                  (s->verify_mode & SSL_VERIFY_FAIL_IF_NO_PEER_CERT)) {
3673             SSLfatal(s, SSL_AD_CERTIFICATE_REQUIRED,
3674                      SSL_F_TLS_PROCESS_CLIENT_CERTIFICATE,
3675                      SSL_R_PEER_DID_NOT_RETURN_A_CERTIFICATE);
3676             goto err;
3677         }
3678         /* No client certificate so digest cached records */
3679         if (s->s3.handshake_buffer && !ssl3_digest_cached_records(s, 0)) {
3680             /* SSLfatal() already called */
3681             goto err;
3682         }
3683     } else {
3684         EVP_PKEY *pkey;
3685         i = ssl_verify_cert_chain(s, sk);
3686         if (i <= 0) {
3687             SSLfatal(s, ssl_x509err2alert(s->verify_result),
3688                      SSL_F_TLS_PROCESS_CLIENT_CERTIFICATE,
3689                      SSL_R_CERTIFICATE_VERIFY_FAILED);
3690             goto err;
3691         }
3692         if (i > 1) {
3693             SSLfatal(s, SSL_AD_HANDSHAKE_FAILURE,
3694                      SSL_F_TLS_PROCESS_CLIENT_CERTIFICATE, i);
3695             goto err;
3696         }
3697         pkey = X509_get0_pubkey(sk_X509_value(sk, 0));
3698         if (pkey == NULL) {
3699             SSLfatal(s, SSL_AD_HANDSHAKE_FAILURE,
3700                      SSL_F_TLS_PROCESS_CLIENT_CERTIFICATE,
3701                      SSL_R_UNKNOWN_CERTIFICATE_TYPE);
3702             goto err;
3703         }
3704     }
3705
3706     /*
3707      * Sessions must be immutable once they go into the session cache. Otherwise
3708      * we can get multi-thread problems. Therefore we don't "update" sessions,
3709      * we replace them with a duplicate. Here, we need to do this every time
3710      * a new certificate is received via post-handshake authentication, as the
3711      * session may have already gone into the session cache.
3712      */
3713
3714     if (s->post_handshake_auth == SSL_PHA_REQUESTED) {
3715         if ((new_sess = ssl_session_dup(s->session, 0)) == 0) {
3716             SSLfatal(s, SSL_AD_INTERNAL_ERROR,
3717                      SSL_F_TLS_PROCESS_CLIENT_CERTIFICATE,
3718                      ERR_R_MALLOC_FAILURE);
3719             goto err;
3720         }
3721
3722         SSL_SESSION_free(s->session);
3723         s->session = new_sess;
3724     }
3725
3726     X509_free(s->session->peer);
3727     s->session->peer = sk_X509_shift(sk);
3728     s->session->verify_result = s->verify_result;
3729
3730     sk_X509_pop_free(s->session->peer_chain, X509_free);
3731     s->session->peer_chain = sk;
3732
3733     /*
3734      * Freeze the handshake buffer. For <TLS1.3 we do this after the CKE
3735      * message
3736      */
3737     if (SSL_IS_TLS13(s) && !ssl3_digest_cached_records(s, 1)) {
3738         /* SSLfatal() already called */
3739         goto err;
3740     }
3741
3742     /*
3743      * Inconsistency alert: cert_chain does *not* include the peer's own
3744      * certificate, while we do include it in statem_clnt.c
3745      */
3746     sk = NULL;
3747
3748     /* Save the current hash state for when we receive the CertificateVerify */
3749     if (SSL_IS_TLS13(s)) {
3750         if (!ssl_handshake_hash(s, s->cert_verify_hash,
3751                                 sizeof(s->cert_verify_hash),
3752                                 &s->cert_verify_hash_len)) {
3753             /* SSLfatal() already called */
3754             goto err;
3755         }
3756
3757         /* Resend session tickets */
3758         s->sent_tickets = 0;
3759     }
3760
3761     ret = MSG_PROCESS_CONTINUE_READING;
3762
3763  err:
3764     X509_free(x);
3765     sk_X509_pop_free(sk, X509_free);
3766     return ret;
3767 }
3768
3769 int tls_construct_server_certificate(SSL *s, WPACKET *pkt)
3770 {
3771     CERT_PKEY *cpk = s->s3.tmp.cert;
3772
3773     if (cpk == NULL) {
3774         SSLfatal(s, SSL_AD_INTERNAL_ERROR,
3775                  SSL_F_TLS_CONSTRUCT_SERVER_CERTIFICATE, ERR_R_INTERNAL_ERROR);
3776         return 0;
3777     }
3778
3779     /*
3780      * In TLSv1.3 the certificate chain is always preceded by a 0 length context
3781      * for the server Certificate message
3782      */
3783     if (SSL_IS_TLS13(s) && !WPACKET_put_bytes_u8(pkt, 0)) {
3784         SSLfatal(s, SSL_AD_INTERNAL_ERROR,
3785                  SSL_F_TLS_CONSTRUCT_SERVER_CERTIFICATE, ERR_R_INTERNAL_ERROR);
3786         return 0;
3787     }
3788     if (!ssl3_output_cert_chain(s, pkt, cpk)) {
3789         /* SSLfatal() already called */
3790         return 0;
3791     }
3792
3793     return 1;
3794 }
3795
3796 static int create_ticket_prequel(SSL *s, WPACKET *pkt, uint32_t age_add,
3797                                  unsigned char *tick_nonce)
3798 {
3799     /*
3800      * Ticket lifetime hint: For TLSv1.2 this is advisory only and we leave this
3801      * unspecified for resumed session (for simplicity).
3802      * In TLSv1.3 we reset the "time" field above, and always specify the
3803      * timeout.
3804      */
3805     if (!WPACKET_put_bytes_u32(pkt,
3806                                (s->hit && !SSL_IS_TLS13(s))
3807                                ? 0 : s->session->timeout)) {
3808         SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_F_CREATE_TICKET_PREQUEL,
3809                  ERR_R_INTERNAL_ERROR);
3810         return 0;
3811     }
3812
3813     if (SSL_IS_TLS13(s)) {
3814         if (!WPACKET_put_bytes_u32(pkt, age_add)
3815                 || !WPACKET_sub_memcpy_u8(pkt, tick_nonce, TICKET_NONCE_SIZE)) {
3816             SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_F_CREATE_TICKET_PREQUEL,
3817                      ERR_R_INTERNAL_ERROR);
3818             return 0;
3819         }
3820     }
3821
3822     /* Start the sub-packet for the actual ticket data */
3823     if (!WPACKET_start_sub_packet_u16(pkt)) {
3824         SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_F_CREATE_TICKET_PREQUEL,
3825                  ERR_R_INTERNAL_ERROR);
3826         return 0;
3827     }
3828
3829     return 1;
3830 }
3831
3832 static int construct_stateless_ticket(SSL *s, WPACKET *pkt, uint32_t age_add,
3833                                       unsigned char *tick_nonce)
3834 {
3835     unsigned char *senc = NULL;
3836     EVP_CIPHER_CTX *ctx = NULL;
3837     HMAC_CTX *hctx = NULL;
3838     unsigned char *p, *encdata1, *encdata2, *macdata1, *macdata2;
3839     const unsigned char *const_p;
3840     int len, slen_full, slen, lenfinal;
3841     SSL_SESSION *sess;
3842     unsigned int hlen;
3843     SSL_CTX *tctx = s->session_ctx;
3844     unsigned char iv[EVP_MAX_IV_LENGTH];
3845     unsigned char key_name[TLSEXT_KEYNAME_LENGTH];
3846     int iv_len, ok = 0;
3847     size_t macoffset, macendoffset;
3848
3849     /* get session encoding length */
3850     slen_full = i2d_SSL_SESSION(s->session, NULL);
3851     /*
3852      * Some length values are 16 bits, so forget it if session is too
3853      * long
3854      */
3855     if (slen_full == 0 || slen_full > 0xFF00) {
3856         SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_F_CONSTRUCT_STATELESS_TICKET,
3857                  ERR_R_INTERNAL_ERROR);
3858         goto err;
3859     }
3860     senc = OPENSSL_malloc(slen_full);
3861     if (senc == NULL) {
3862         SSLfatal(s, SSL_AD_INTERNAL_ERROR,
3863                  SSL_F_CONSTRUCT_STATELESS_TICKET, ERR_R_MALLOC_FAILURE);
3864         goto err;
3865     }
3866
3867     ctx = EVP_CIPHER_CTX_new();
3868     hctx = HMAC_CTX_new();
3869     if (ctx == NULL || hctx == NULL) {
3870         SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_F_CONSTRUCT_STATELESS_TICKET,
3871                  ERR_R_MALLOC_FAILURE);
3872         goto err;
3873     }
3874
3875     p = senc;
3876     if (!i2d_SSL_SESSION(s->session, &p)) {
3877         SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_F_CONSTRUCT_STATELESS_TICKET,
3878                  ERR_R_INTERNAL_ERROR);
3879         goto err;
3880     }
3881
3882     /*
3883      * create a fresh copy (not shared with other threads) to clean up
3884      */
3885     const_p = senc;
3886     sess = d2i_SSL_SESSION(NULL, &const_p, slen_full);
3887     if (sess == NULL) {
3888         SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_F_CONSTRUCT_STATELESS_TICKET,
3889                  ERR_R_INTERNAL_ERROR);
3890         goto err;
3891     }
3892
3893     slen = i2d_SSL_SESSION(sess, NULL);
3894     if (slen == 0 || slen > slen_full) {
3895         /* shouldn't ever happen */
3896         SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_F_CONSTRUCT_STATELESS_TICKET,
3897                  ERR_R_INTERNAL_ERROR);
3898         SSL_SESSION_free(sess);
3899         goto err;
3900     }
3901     p = senc;
3902     if (!i2d_SSL_SESSION(sess, &p)) {
3903         SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_F_CONSTRUCT_STATELESS_TICKET,
3904                  ERR_R_INTERNAL_ERROR);
3905         SSL_SESSION_free(sess);
3906         goto err;
3907     }
3908     SSL_SESSION_free(sess);
3909
3910     /*
3911      * Initialize HMAC and cipher contexts. If callback present it does
3912      * all the work otherwise use generated values from parent ctx.
3913      */
3914     if (tctx->ext.ticket_key_cb) {
3915         /* if 0 is returned, write an empty ticket */
3916         int ret = tctx->ext.ticket_key_cb(s, key_name, iv, ctx,
3917                                              hctx, 1);
3918
3919         if (ret == 0) {
3920
3921             /* Put timeout and length */
3922             if (!WPACKET_put_bytes_u32(pkt, 0)
3923                     || !WPACKET_put_bytes_u16(pkt, 0)) {
3924                 SSLfatal(s, SSL_AD_INTERNAL_ERROR,
3925                          SSL_F_CONSTRUCT_STATELESS_TICKET,
3926                          ERR_R_INTERNAL_ERROR);
3927                 goto err;
3928             }
3929             OPENSSL_free(senc);
3930             EVP_CIPHER_CTX_free(ctx);
3931             HMAC_CTX_free(hctx);
3932             return 1;
3933         }
3934         if (ret < 0) {
3935             SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_F_CONSTRUCT_STATELESS_TICKET,
3936                      SSL_R_CALLBACK_FAILED);
3937             goto err;
3938         }
3939         iv_len = EVP_CIPHER_CTX_iv_length(ctx);
3940     } else {
3941         const EVP_CIPHER *cipher = EVP_aes_256_cbc();
3942
3943         iv_len = EVP_CIPHER_iv_length(cipher);
3944         if (RAND_bytes(iv, iv_len) <= 0
3945                 || !EVP_EncryptInit_ex(ctx, cipher, NULL,
3946                                        tctx->ext.secure->tick_aes_key, iv)
3947                 || !HMAC_Init_ex(hctx, tctx->ext.secure->tick_hmac_key,
3948                                  sizeof(tctx->ext.secure->tick_hmac_key),
3949                                  EVP_sha256(), NULL)) {
3950             SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_F_CONSTRUCT_STATELESS_TICKET,
3951                      ERR_R_INTERNAL_ERROR);
3952             goto err;
3953         }
3954         memcpy(key_name, tctx->ext.tick_key_name,
3955                sizeof(tctx->ext.tick_key_name));
3956     }
3957
3958     if (!create_ticket_prequel(s, pkt, age_add, tick_nonce)) {
3959         /* SSLfatal() already called */
3960         goto err;
3961     }
3962
3963     if (!WPACKET_get_total_written(pkt, &macoffset)
3964                /* Output key name */
3965             || !WPACKET_memcpy(pkt, key_name, sizeof(key_name))
3966                /* output IV */
3967             || !WPACKET_memcpy(pkt, iv, iv_len)
3968             || !WPACKET_reserve_bytes(pkt, slen + EVP_MAX_BLOCK_LENGTH,
3969                                       &encdata1)
3970                /* Encrypt session data */
3971             || !EVP_EncryptUpdate(ctx, encdata1, &len, senc, slen)
3972             || !WPACKET_allocate_bytes(pkt, len, &encdata2)
3973             || encdata1 != encdata2
3974             || !EVP_EncryptFinal(ctx, encdata1 + len, &lenfinal)
3975             || !WPACKET_allocate_bytes(pkt, lenfinal, &encdata2)
3976             || encdata1 + len != encdata2
3977             || len + lenfinal > slen + EVP_MAX_BLOCK_LENGTH
3978             || !WPACKET_get_total_written(pkt, &macendoffset)
3979             || !HMAC_Update(hctx,
3980                             (unsigned char *)s->init_buf->data + macoffset,
3981                             macendoffset - macoffset)
3982             || !WPACKET_reserve_bytes(pkt, EVP_MAX_MD_SIZE, &macdata1)
3983             || !HMAC_Final(hctx, macdata1, &hlen)
3984             || hlen > EVP_MAX_MD_SIZE
3985             || !WPACKET_allocate_bytes(pkt, hlen, &macdata2)
3986             || macdata1 != macdata2) {
3987         SSLfatal(s, SSL_AD_INTERNAL_ERROR,
3988                  SSL_F_CONSTRUCT_STATELESS_TICKET, ERR_R_INTERNAL_ERROR);
3989         goto err;
3990     }
3991
3992     /* Close the sub-packet created by create_ticket_prequel() */
3993     if (!WPACKET_close(pkt)) {
3994         SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_F_CONSTRUCT_STATELESS_TICKET,
3995                  ERR_R_INTERNAL_ERROR);
3996         goto err;
3997     }
3998
3999     ok = 1;
4000  err:
4001     OPENSSL_free(senc);
4002     EVP_CIPHER_CTX_free(ctx);
4003     HMAC_CTX_free(hctx);
4004     return ok;
4005 }
4006
4007 static int construct_stateful_ticket(SSL *s, WPACKET *pkt, uint32_t age_add,
4008                                      unsigned char *tick_nonce)
4009 {
4010     if (!create_ticket_prequel(s, pkt, age_add, tick_nonce)) {
4011         /* SSLfatal() already called */
4012         return 0;
4013     }
4014
4015     if (!WPACKET_memcpy(pkt, s->session->session_id,
4016                         s->session->session_id_length)
4017             || !WPACKET_close(pkt)) {
4018         SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_F_CONSTRUCT_STATEFUL_TICKET,
4019                  ERR_R_INTERNAL_ERROR);
4020         return 0;
4021     }
4022
4023     return 1;
4024 }
4025
4026 int tls_construct_new_session_ticket(SSL *s, WPACKET *pkt)
4027 {
4028     SSL_CTX *tctx = s->session_ctx;
4029     unsigned char tick_nonce[TICKET_NONCE_SIZE];
4030     union {
4031         unsigned char age_add_c[sizeof(uint32_t)];
4032         uint32_t age_add;
4033     } age_add_u;
4034
4035     age_add_u.age_add = 0;
4036
4037     if (SSL_IS_TLS13(s)) {
4038         size_t i, hashlen;
4039         uint64_t nonce;
4040         static const unsigned char nonce_label[] = "resumption";
4041         const EVP_MD *md = ssl_handshake_md(s);
4042         int hashleni = EVP_MD_size(md);
4043
4044         /* Ensure cast to size_t is safe */
4045         if (!ossl_assert(hashleni >= 0)) {
4046             SSLfatal(s, SSL_AD_INTERNAL_ERROR,
4047                      SSL_F_TLS_CONSTRUCT_NEW_SESSION_TICKET,
4048                      ERR_R_INTERNAL_ERROR);
4049             goto err;
4050         }
4051         hashlen = (size_t)hashleni;
4052
4053         /*
4054          * If we already sent one NewSessionTicket, or we resumed then
4055          * s->session may already be in a cache and so we must not modify it.
4056          * Instead we need to take a copy of it and modify that.
4057          */
4058         if (s->sent_tickets != 0 || s->hit) {
4059             SSL_SESSION *new_sess = ssl_session_dup(s->session, 0);
4060
4061             if (new_sess == NULL) {
4062                 /* SSLfatal already called */
4063                 goto err;
4064             }
4065
4066             SSL_SESSION_free(s->session);
4067             s->session = new_sess;
4068         }
4069
4070         if (!ssl_generate_session_id(s, s->session)) {
4071             /* SSLfatal() already called */
4072             goto err;
4073         }
4074         if (RAND_bytes(age_add_u.age_add_c, sizeof(age_add_u)) <= 0) {
4075             SSLfatal(s, SSL_AD_INTERNAL_ERROR,
4076                      SSL_F_TLS_CONSTRUCT_NEW_SESSION_TICKET,
4077                      ERR_R_INTERNAL_ERROR);
4078             goto err;
4079         }
4080         s->session->ext.tick_age_add = age_add_u.age_add;
4081
4082         nonce = s->next_ticket_nonce;
4083         for (i = TICKET_NONCE_SIZE; i > 0; i--) {
4084             tick_nonce[i - 1] = (unsigned char)(nonce & 0xff);
4085             nonce >>= 8;
4086         }
4087
4088         if (!tls13_hkdf_expand(s, md, s->resumption_master_secret,
4089                                nonce_label,
4090                                sizeof(nonce_label) - 1,
4091                                tick_nonce,
4092                                TICKET_NONCE_SIZE,
4093                                s->session->master_key,
4094                                hashlen, 1)) {
4095             /* SSLfatal() already called */
4096             goto err;
4097         }
4098         s->session->master_key_length = hashlen;
4099
4100         s->session->time = (long)time(NULL);
4101         if (s->s3.alpn_selected != NULL) {
4102             OPENSSL_free(s->session->ext.alpn_selected);
4103             s->session->ext.alpn_selected =
4104                 OPENSSL_memdup(s->s3.alpn_selected, s->s3.alpn_selected_len);
4105             if (s->session->ext.alpn_selected == NULL) {
4106                 SSLfatal(s, SSL_AD_INTERNAL_ERROR,
4107                          SSL_F_TLS_CONSTRUCT_NEW_SESSION_TICKET,
4108                          ERR_R_MALLOC_FAILURE);
4109                 goto err;
4110             }
4111             s->session->ext.alpn_selected_len = s->s3.alpn_selected_len;
4112         }
4113         s->session->ext.max_early_data = s->max_early_data;
4114     }
4115
4116     if (tctx->generate_ticket_cb != NULL &&
4117         tctx->generate_ticket_cb(s, tctx->ticket_cb_data) == 0)
4118         goto err;
4119
4120     /*
4121      * If we are using anti-replay protection then we behave as if
4122      * SSL_OP_NO_TICKET is set - we are caching tickets anyway so there
4123      * is no point in using full stateless tickets.
4124      */
4125     if (SSL_IS_TLS13(s)
4126             && ((s->options & SSL_OP_NO_TICKET) != 0
4127                 || (s->max_early_data > 0
4128                     && (s->options & SSL_OP_NO_ANTI_REPLAY) == 0))) {
4129         if (!construct_stateful_ticket(s, pkt, age_add_u.age_add, tick_nonce)) {
4130             /* SSLfatal() already called */
4131             goto err;
4132         }
4133     } else if (!construct_stateless_ticket(s, pkt, age_add_u.age_add,
4134                                            tick_nonce)) {
4135         /* SSLfatal() already called */
4136         goto err;
4137     }
4138
4139     if (SSL_IS_TLS13(s)) {
4140         if (!tls_construct_extensions(s, pkt,
4141                                       SSL_EXT_TLS1_3_NEW_SESSION_TICKET,
4142                                       NULL, 0)) {
4143             /* SSLfatal() already called */
4144             goto err;
4145         }
4146         /*
4147          * Increment both |sent_tickets| and |next_ticket_nonce|. |sent_tickets|
4148          * gets reset to 0 if we send more tickets following a post-handshake
4149          * auth, but |next_ticket_nonce| does not.
4150          */
4151         s->sent_tickets++;
4152         s->next_ticket_nonce++;
4153         ssl_update_cache(s, SSL_SESS_CACHE_SERVER);
4154     }
4155
4156     return 1;
4157  err:
4158     return 0;
4159 }
4160
4161 /*
4162  * In TLSv1.3 this is called from the extensions code, otherwise it is used to
4163  * create a separate message. Returns 1 on success or 0 on failure.
4164  */
4165 int tls_construct_cert_status_body(SSL *s, WPACKET *pkt)
4166 {
4167     if (!WPACKET_put_bytes_u8(pkt, s->ext.status_type)
4168             || !WPACKET_sub_memcpy_u24(pkt, s->ext.ocsp.resp,
4169                                        s->ext.ocsp.resp_len)) {
4170         SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_F_TLS_CONSTRUCT_CERT_STATUS_BODY,
4171                  ERR_R_INTERNAL_ERROR);
4172         return 0;
4173     }
4174
4175     return 1;
4176 }
4177
4178 int tls_construct_cert_status(SSL *s, WPACKET *pkt)
4179 {
4180     if (!tls_construct_cert_status_body(s, pkt)) {
4181         /* SSLfatal() already called */
4182         return 0;
4183     }
4184
4185     return 1;
4186 }
4187
4188 #ifndef OPENSSL_NO_NEXTPROTONEG
4189 /*
4190  * tls_process_next_proto reads a Next Protocol Negotiation handshake message.
4191  * It sets the next_proto member in s if found
4192  */
4193 MSG_PROCESS_RETURN tls_process_next_proto(SSL *s, PACKET *pkt)
4194 {
4195     PACKET next_proto, padding;
4196     size_t next_proto_len;
4197
4198     /*-
4199      * The payload looks like:
4200      *   uint8 proto_len;
4201      *   uint8 proto[proto_len];
4202      *   uint8 padding_len;
4203      *   uint8 padding[padding_len];
4204      */
4205     if (!PACKET_get_length_prefixed_1(pkt, &next_proto)
4206         || !PACKET_get_length_prefixed_1(pkt, &padding)
4207         || PACKET_remaining(pkt) > 0) {
4208         SSLfatal(s, SSL_AD_DECODE_ERROR, SSL_F_TLS_PROCESS_NEXT_PROTO,
4209                  SSL_R_LENGTH_MISMATCH);
4210         return MSG_PROCESS_ERROR;
4211     }
4212
4213     if (!PACKET_memdup(&next_proto, &s->ext.npn, &next_proto_len)) {
4214         s->ext.npn_len = 0;
4215         SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_F_TLS_PROCESS_NEXT_PROTO,
4216                  ERR_R_INTERNAL_ERROR);
4217         return MSG_PROCESS_ERROR;
4218     }
4219
4220     s->ext.npn_len = (unsigned char)next_proto_len;
4221
4222     return MSG_PROCESS_CONTINUE_READING;
4223 }
4224 #endif
4225
4226 static int tls_construct_encrypted_extensions(SSL *s, WPACKET *pkt)
4227 {
4228     if (!tls_construct_extensions(s, pkt, SSL_EXT_TLS1_3_ENCRYPTED_EXTENSIONS,
4229                                   NULL, 0)) {
4230         /* SSLfatal() already called */
4231         return 0;
4232     }
4233
4234     return 1;
4235 }
4236
4237 MSG_PROCESS_RETURN tls_process_end_of_early_data(SSL *s, PACKET *pkt)
4238 {
4239     if (PACKET_remaining(pkt) != 0) {
4240         SSLfatal(s, SSL_AD_DECODE_ERROR, SSL_F_TLS_PROCESS_END_OF_EARLY_DATA,
4241                  SSL_R_LENGTH_MISMATCH);
4242         return MSG_PROCESS_ERROR;
4243     }
4244
4245     if (s->early_data_state != SSL_EARLY_DATA_READING
4246             && s->early_data_state != SSL_EARLY_DATA_READ_RETRY) {
4247         SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_F_TLS_PROCESS_END_OF_EARLY_DATA,
4248                  ERR_R_INTERNAL_ERROR);
4249         return MSG_PROCESS_ERROR;
4250     }
4251
4252     /*
4253      * EndOfEarlyData signals a key change so the end of the message must be on
4254      * a record boundary.
4255      */
4256     if (RECORD_LAYER_processed_read_pending(&s->rlayer)) {
4257         SSLfatal(s, SSL_AD_UNEXPECTED_MESSAGE,
4258                  SSL_F_TLS_PROCESS_END_OF_EARLY_DATA,
4259                  SSL_R_NOT_ON_RECORD_BOUNDARY);
4260         return MSG_PROCESS_ERROR;
4261     }
4262
4263     s->early_data_state = SSL_EARLY_DATA_FINISHED_READING;
4264     if (!s->method->ssl3_enc->change_cipher_state(s,
4265                 SSL3_CC_HANDSHAKE | SSL3_CHANGE_CIPHER_SERVER_READ)) {
4266         /* SSLfatal() already called */
4267         return MSG_PROCESS_ERROR;
4268     }
4269
4270     return MSG_PROCESS_CONTINUE_READING;
4271 }