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