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