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