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