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