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