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