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