2 * Copyright 1995-2021 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.
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
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>
30 #define TICKET_NONCE_SIZE 8
34 ASN1_TYPE *opaqueBlob;
37 DECLARE_ASN1_FUNCTIONS(GOST_KX_MESSAGE)
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)
44 IMPLEMENT_ASN1_FUNCTIONS(GOST_KX_MESSAGE)
46 static int tls_construct_encrypted_extensions(SSL *s, WPACKET *pkt);
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|.
54 * Return values are 1 for success (transition allowed) and 0 on error
55 * (transition not allowed)
57 static int ossl_statem_server13_read_transition(SSL *s, int mt)
59 OSSL_STATEM *st = &s->statem;
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()
66 switch (st->hand_state) {
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;
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;
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;
94 if (mt == SSL3_MT_FINISHED) {
95 st->hand_state = TLS_ST_SR_FINISHED;
102 if (s->session->peer == NULL) {
103 if (mt == SSL3_MT_FINISHED) {
104 st->hand_state = TLS_ST_SR_FINISHED;
108 if (mt == SSL3_MT_CERTIFICATE_VERIFY) {
109 st->hand_state = TLS_ST_SR_CERT_VRFY;
115 case TLS_ST_SR_CERT_VRFY:
116 if (mt == SSL3_MT_FINISHED) {
117 st->hand_state = TLS_ST_SR_FINISHED;
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)
127 if (s->early_data_state == SSL_EARLY_DATA_READING)
130 if (mt == SSL3_MT_CERTIFICATE
131 && s->post_handshake_auth == SSL_PHA_REQUESTED) {
132 st->hand_state = TLS_ST_SR_CERT;
136 if (mt == SSL3_MT_KEY_UPDATE) {
137 st->hand_state = TLS_ST_SR_KEY_UPDATE;
143 /* No valid transition found */
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|.
153 * Return values are 1 for success (transition allowed) and 0 on error
154 * (transition not allowed)
156 int ossl_statem_server_read_transition(SSL *s, int mt)
158 OSSL_STATEM *st = &s->statem;
160 if (SSL_IS_TLS13(s)) {
161 if (!ossl_statem_server13_read_transition(s, mt))
166 switch (st->hand_state) {
172 case DTLS_ST_SW_HELLO_VERIFY_REQUEST:
173 if (mt == SSL3_MT_CLIENT_HELLO) {
174 st->hand_state = TLS_ST_SR_CLNT_HELLO;
179 case TLS_ST_SW_SRVR_DONE:
181 * If we get a CKE message after a ServerDone then either
182 * 1) We didn't request a Certificate
184 * 2) If we did request one then
185 * a) We allow no Certificate to be returned
187 * b) We are running SSL3 (in TLS1.0+ the client must return a 0
188 * list if we requested a certificate)
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)) {
196 * This isn't an unexpected message as such - we're just
197 * not going to accept it because we require a client
200 SSLfatal(s, SSL_AD_HANDSHAKE_FAILURE,
201 SSL_R_PEER_DID_NOT_RETURN_A_CERTIFICATE);
204 st->hand_state = TLS_ST_SR_KEY_EXCH;
208 st->hand_state = TLS_ST_SR_KEY_EXCH;
211 } else if (s->s3.tmp.cert_request) {
212 if (mt == SSL3_MT_CERTIFICATE) {
213 st->hand_state = TLS_ST_SR_CERT;
220 if (mt == SSL3_MT_CLIENT_KEY_EXCHANGE) {
221 st->hand_state = TLS_ST_SR_KEY_EXCH;
226 case TLS_ST_SR_KEY_EXCH:
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
235 if (s->session->peer == NULL || st->no_cert_verify) {
236 if (mt == SSL3_MT_CHANGE_CIPHER_SPEC) {
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.
243 st->hand_state = TLS_ST_SR_CHANGE;
247 if (mt == SSL3_MT_CERTIFICATE_VERIFY) {
248 st->hand_state = TLS_ST_SR_CERT_VRFY;
254 case TLS_ST_SR_CERT_VRFY:
255 if (mt == SSL3_MT_CHANGE_CIPHER_SPEC) {
256 st->hand_state = TLS_ST_SR_CHANGE;
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;
270 if (mt == SSL3_MT_FINISHED) {
271 st->hand_state = TLS_ST_SR_FINISHED;
274 #ifndef OPENSSL_NO_NEXTPROTONEG
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;
288 case TLS_ST_SW_FINISHED:
289 if (mt == SSL3_MT_CHANGE_CIPHER_SPEC) {
290 st->hand_state = TLS_ST_SR_CHANGE;
297 /* No valid transition found */
298 if (SSL_IS_DTLS(s) && mt == SSL3_MT_CHANGE_CIPHER_SPEC) {
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.
306 s->rwstate = SSL_READING;
307 rbio = SSL_get_rbio(s);
308 BIO_clear_retry_flags(rbio);
309 BIO_set_retry_read(rbio);
312 SSLfatal(s, SSL3_AD_UNEXPECTED_MESSAGE, SSL_R_UNEXPECTED_MESSAGE);
317 * Should we send a ServerKeyExchange message?
319 * Valid return values are:
323 static int send_server_key_exchange(SSL *s)
325 unsigned long alg_k = s->s3.tmp.new_cipher->algorithm_mkey;
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
335 if (alg_k & (SSL_kDHE | SSL_kECDHE)
337 * PSK: send ServerKeyExchange if PSK identity hint if
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)))
347 #ifndef OPENSSL_NO_SRP
348 /* SRP: send ServerKeyExchange */
349 || (alg_k & SSL_kSRP)
359 * Should we send a CertificateRequest message?
361 * Valid return values are:
365 int send_certificate_request(SSL *s)
368 /* don't request cert unless asked for it: */
369 s->verify_mode & SSL_VERIFY_PEER
371 * don't request if post-handshake-only unless doing
372 * post-handshake in TLSv1.3:
374 && (!SSL_IS_TLS13(s) || !(s->verify_mode & SSL_VERIFY_POST_HANDSHAKE)
375 || s->post_handshake_auth == SSL_PHA_REQUEST_PENDING)
377 * if SSL_VERIFY_CLIENT_ONCE is set, don't request cert
380 && (s->certreqs_sent < 1 ||
381 !(s->verify_mode & SSL_VERIFY_CLIENT_ONCE))
383 * never request cert in anonymous ciphersuites (see
384 * section "Certificate request" in SSL 3 drafts and in
387 && (!(s->s3.tmp.new_cipher->algorithm_auth & SSL_aNULL)
389 * ... except when the application insists on
390 * verification (against the specs, but statem_clnt.c accepts
393 || (s->verify_mode & SSL_VERIFY_FAIL_IF_NO_PEER_CERT))
394 /* don't request certificate for SRP auth */
395 && !(s->s3.tmp.new_cipher->algorithm_auth & SSL_aSRP)
397 * With normal PSK Certificates and Certificate Requests
400 && !(s->s3.tmp.new_cipher->algorithm_auth & SSL_aPSK)) {
408 * ossl_statem_server13_write_transition() works out what handshake state to
409 * move to next when a TLSv1.3 server is writing messages to be sent to the
412 static WRITE_TRAN ossl_statem_server13_write_transition(SSL *s)
414 OSSL_STATEM *st = &s->statem;
417 * No case for TLS_ST_BEFORE, because at that stage we have not negotiated
418 * TLSv1.3 yet, so that is handled by ossl_statem_server_write_transition()
421 switch (st->hand_state) {
423 /* Shouldn't happen */
424 SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
425 return WRITE_TRAN_ERROR;
428 if (s->key_update != SSL_KEY_UPDATE_NONE) {
429 st->hand_state = TLS_ST_SW_KEY_UPDATE;
430 return WRITE_TRAN_CONTINUE;
432 if (s->post_handshake_auth == SSL_PHA_REQUEST_PENDING) {
433 st->hand_state = TLS_ST_SW_CERT_REQ;
434 return WRITE_TRAN_CONTINUE;
436 if (s->ext.extra_tickets_expected > 0) {
437 st->hand_state = TLS_ST_SW_SESSION_TICKET;
438 return WRITE_TRAN_CONTINUE;
440 /* Try to read from the client instead */
441 return WRITE_TRAN_FINISHED;
443 case TLS_ST_SR_CLNT_HELLO:
444 st->hand_state = TLS_ST_SW_SRVR_HELLO;
445 return WRITE_TRAN_CONTINUE;
447 case TLS_ST_SW_SRVR_HELLO:
448 if ((s->options & SSL_OP_ENABLE_MIDDLEBOX_COMPAT) != 0
449 && s->hello_retry_request != SSL_HRR_COMPLETE)
450 st->hand_state = TLS_ST_SW_CHANGE;
451 else if (s->hello_retry_request == SSL_HRR_PENDING)
452 st->hand_state = TLS_ST_EARLY_DATA;
454 st->hand_state = TLS_ST_SW_ENCRYPTED_EXTENSIONS;
455 return WRITE_TRAN_CONTINUE;
457 case TLS_ST_SW_CHANGE:
458 if (s->hello_retry_request == SSL_HRR_PENDING)
459 st->hand_state = TLS_ST_EARLY_DATA;
461 st->hand_state = TLS_ST_SW_ENCRYPTED_EXTENSIONS;
462 return WRITE_TRAN_CONTINUE;
464 case TLS_ST_SW_ENCRYPTED_EXTENSIONS:
466 st->hand_state = TLS_ST_SW_FINISHED;
467 else if (send_certificate_request(s))
468 st->hand_state = TLS_ST_SW_CERT_REQ;
470 st->hand_state = TLS_ST_SW_CERT;
472 return WRITE_TRAN_CONTINUE;
474 case TLS_ST_SW_CERT_REQ:
475 if (s->post_handshake_auth == SSL_PHA_REQUEST_PENDING) {
476 s->post_handshake_auth = SSL_PHA_REQUESTED;
477 st->hand_state = TLS_ST_OK;
479 st->hand_state = TLS_ST_SW_CERT;
481 return WRITE_TRAN_CONTINUE;
484 st->hand_state = TLS_ST_SW_CERT_VRFY;
485 return WRITE_TRAN_CONTINUE;
487 case TLS_ST_SW_CERT_VRFY:
488 st->hand_state = TLS_ST_SW_FINISHED;
489 return WRITE_TRAN_CONTINUE;
491 case TLS_ST_SW_FINISHED:
492 st->hand_state = TLS_ST_EARLY_DATA;
493 return WRITE_TRAN_CONTINUE;
495 case TLS_ST_EARLY_DATA:
496 return WRITE_TRAN_FINISHED;
498 case TLS_ST_SR_FINISHED:
500 * Technically we have finished the handshake at this point, but we're
501 * going to remain "in_init" for now and write out any session tickets
504 if (s->post_handshake_auth == SSL_PHA_REQUESTED) {
505 s->post_handshake_auth = SSL_PHA_EXT_RECEIVED;
506 } else if (!s->ext.ticket_expected) {
508 * If we're not going to renew the ticket then we just finish the
509 * handshake at this point.
511 st->hand_state = TLS_ST_OK;
512 return WRITE_TRAN_CONTINUE;
514 if (s->num_tickets > s->sent_tickets)
515 st->hand_state = TLS_ST_SW_SESSION_TICKET;
517 st->hand_state = TLS_ST_OK;
518 return WRITE_TRAN_CONTINUE;
520 case TLS_ST_SR_KEY_UPDATE:
521 case TLS_ST_SW_KEY_UPDATE:
522 st->hand_state = TLS_ST_OK;
523 return WRITE_TRAN_CONTINUE;
525 case TLS_ST_SW_SESSION_TICKET:
526 /* In a resumption we only ever send a maximum of one new ticket.
527 * Following an initial handshake we send the number of tickets we have
528 * been configured for.
530 if (!SSL_IS_FIRST_HANDSHAKE(s) && s->ext.extra_tickets_expected > 0) {
531 return WRITE_TRAN_CONTINUE;
532 } else if (s->hit || s->num_tickets <= s->sent_tickets) {
533 /* We've written enough tickets out. */
534 st->hand_state = TLS_ST_OK;
536 return WRITE_TRAN_CONTINUE;
541 * ossl_statem_server_write_transition() works out what handshake state to move
542 * to next when the server is writing messages to be sent to the client.
544 WRITE_TRAN ossl_statem_server_write_transition(SSL *s)
546 OSSL_STATEM *st = &s->statem;
549 * Note that before the ClientHello we don't know what version we are going
550 * to negotiate yet, so we don't take this branch until later
554 return ossl_statem_server13_write_transition(s);
556 switch (st->hand_state) {
558 /* Shouldn't happen */
559 SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
560 return WRITE_TRAN_ERROR;
563 if (st->request_state == TLS_ST_SW_HELLO_REQ) {
564 /* We must be trying to renegotiate */
565 st->hand_state = TLS_ST_SW_HELLO_REQ;
566 st->request_state = TLS_ST_BEFORE;
567 return WRITE_TRAN_CONTINUE;
569 /* Must be an incoming ClientHello */
570 if (!tls_setup_handshake(s)) {
571 /* SSLfatal() already called */
572 return WRITE_TRAN_ERROR;
577 /* Just go straight to trying to read from the client */
578 return WRITE_TRAN_FINISHED;
580 case TLS_ST_SW_HELLO_REQ:
581 st->hand_state = TLS_ST_OK;
582 return WRITE_TRAN_CONTINUE;
584 case TLS_ST_SR_CLNT_HELLO:
585 if (SSL_IS_DTLS(s) && !s->d1->cookie_verified
586 && (SSL_get_options(s) & SSL_OP_COOKIE_EXCHANGE)) {
587 st->hand_state = DTLS_ST_SW_HELLO_VERIFY_REQUEST;
588 } else if (s->renegotiate == 0 && !SSL_IS_FIRST_HANDSHAKE(s)) {
589 /* We must have rejected the renegotiation */
590 st->hand_state = TLS_ST_OK;
591 return WRITE_TRAN_CONTINUE;
593 st->hand_state = TLS_ST_SW_SRVR_HELLO;
595 return WRITE_TRAN_CONTINUE;
597 case DTLS_ST_SW_HELLO_VERIFY_REQUEST:
598 return WRITE_TRAN_FINISHED;
600 case TLS_ST_SW_SRVR_HELLO:
602 if (s->ext.ticket_expected)
603 st->hand_state = TLS_ST_SW_SESSION_TICKET;
605 st->hand_state = TLS_ST_SW_CHANGE;
607 /* Check if it is anon DH or anon ECDH, */
608 /* normal PSK or SRP */
609 if (!(s->s3.tmp.new_cipher->algorithm_auth &
610 (SSL_aNULL | SSL_aSRP | SSL_aPSK))) {
611 st->hand_state = TLS_ST_SW_CERT;
612 } else if (send_server_key_exchange(s)) {
613 st->hand_state = TLS_ST_SW_KEY_EXCH;
614 } else if (send_certificate_request(s)) {
615 st->hand_state = TLS_ST_SW_CERT_REQ;
617 st->hand_state = TLS_ST_SW_SRVR_DONE;
620 return WRITE_TRAN_CONTINUE;
623 if (s->ext.status_expected) {
624 st->hand_state = TLS_ST_SW_CERT_STATUS;
625 return WRITE_TRAN_CONTINUE;
629 case TLS_ST_SW_CERT_STATUS:
630 if (send_server_key_exchange(s)) {
631 st->hand_state = TLS_ST_SW_KEY_EXCH;
632 return WRITE_TRAN_CONTINUE;
636 case TLS_ST_SW_KEY_EXCH:
637 if (send_certificate_request(s)) {
638 st->hand_state = TLS_ST_SW_CERT_REQ;
639 return WRITE_TRAN_CONTINUE;
643 case TLS_ST_SW_CERT_REQ:
644 st->hand_state = TLS_ST_SW_SRVR_DONE;
645 return WRITE_TRAN_CONTINUE;
647 case TLS_ST_SW_SRVR_DONE:
648 return WRITE_TRAN_FINISHED;
650 case TLS_ST_SR_FINISHED:
652 st->hand_state = TLS_ST_OK;
653 return WRITE_TRAN_CONTINUE;
654 } else if (s->ext.ticket_expected) {
655 st->hand_state = TLS_ST_SW_SESSION_TICKET;
657 st->hand_state = TLS_ST_SW_CHANGE;
659 return WRITE_TRAN_CONTINUE;
661 case TLS_ST_SW_SESSION_TICKET:
662 st->hand_state = TLS_ST_SW_CHANGE;
663 return WRITE_TRAN_CONTINUE;
665 case TLS_ST_SW_CHANGE:
666 st->hand_state = TLS_ST_SW_FINISHED;
667 return WRITE_TRAN_CONTINUE;
669 case TLS_ST_SW_FINISHED:
671 return WRITE_TRAN_FINISHED;
673 st->hand_state = TLS_ST_OK;
674 return WRITE_TRAN_CONTINUE;
679 * Perform any pre work that needs to be done prior to sending a message from
680 * the server to the client.
682 WORK_STATE ossl_statem_server_pre_work(SSL *s, WORK_STATE wst)
684 OSSL_STATEM *st = &s->statem;
686 switch (st->hand_state) {
688 /* No pre work to be done */
691 case TLS_ST_SW_HELLO_REQ:
694 dtls1_clear_sent_buffer(s);
697 case DTLS_ST_SW_HELLO_VERIFY_REQUEST:
699 if (SSL_IS_DTLS(s)) {
700 dtls1_clear_sent_buffer(s);
701 /* We don't buffer this message so don't use the timer */
706 case TLS_ST_SW_SRVR_HELLO:
707 if (SSL_IS_DTLS(s)) {
709 * Messages we write from now on should be buffered and
710 * retransmitted if necessary, so we need to use the timer now
716 case TLS_ST_SW_SRVR_DONE:
717 #ifndef OPENSSL_NO_SCTP
718 if (SSL_IS_DTLS(s) && BIO_dgram_is_sctp(SSL_get_wbio(s))) {
719 /* Calls SSLfatal() as required */
720 return dtls_wait_for_dry(s);
723 return WORK_FINISHED_CONTINUE;
725 case TLS_ST_SW_SESSION_TICKET:
726 if (SSL_IS_TLS13(s) && s->sent_tickets == 0
727 && s->ext.extra_tickets_expected == 0) {
729 * Actually this is the end of the handshake, but we're going
730 * straight into writing the session ticket out. So we finish off
731 * the handshake, but keep the various buffers active.
733 * Calls SSLfatal as required.
735 return tls_finish_handshake(s, wst, 0, 0);
737 if (SSL_IS_DTLS(s)) {
739 * We're into the last flight. We don't retransmit the last flight
740 * unless we need to, so we don't use the timer
746 case TLS_ST_SW_CHANGE:
749 /* Writes to s->session are only safe for initial handshakes */
750 if (s->session->cipher == NULL) {
751 s->session->cipher = s->s3.tmp.new_cipher;
752 } else if (s->session->cipher != s->s3.tmp.new_cipher) {
753 SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
756 if (!s->method->ssl3_enc->setup_key_block(s)) {
757 /* SSLfatal() already called */
760 if (SSL_IS_DTLS(s)) {
762 * We're into the last flight. We don't retransmit the last flight
763 * unless we need to, so we don't use the timer. This might have
764 * already been set to 0 if we sent a NewSessionTicket message,
765 * but we'll set it again here in case we didn't.
769 return WORK_FINISHED_CONTINUE;
771 case TLS_ST_EARLY_DATA:
772 if (s->early_data_state != SSL_EARLY_DATA_ACCEPTING
773 && (s->s3.flags & TLS1_FLAGS_STATELESS) == 0)
774 return WORK_FINISHED_CONTINUE;
778 /* Calls SSLfatal() as required */
779 return tls_finish_handshake(s, wst, 1, 1);
782 return WORK_FINISHED_CONTINUE;
785 static ossl_inline int conn_is_closed(void)
787 switch (get_last_sys_error()) {
792 #if defined(ECONNRESET)
796 #if defined(WSAECONNRESET)
806 * Perform any work that needs to be done after sending a message from the
807 * server to the client.
809 WORK_STATE ossl_statem_server_post_work(SSL *s, WORK_STATE wst)
811 OSSL_STATEM *st = &s->statem;
815 switch (st->hand_state) {
817 /* No post work to be done */
820 case TLS_ST_SW_HELLO_REQ:
821 if (statem_flush(s) != 1)
823 if (!ssl3_init_finished_mac(s)) {
824 /* SSLfatal() already called */
829 case DTLS_ST_SW_HELLO_VERIFY_REQUEST:
830 if (statem_flush(s) != 1)
832 /* HelloVerifyRequest resets Finished MAC */
833 if (s->version != DTLS1_BAD_VER && !ssl3_init_finished_mac(s)) {
834 /* SSLfatal() already called */
838 * The next message should be another ClientHello which we need to
839 * treat like it was the first packet
844 case TLS_ST_SW_SRVR_HELLO:
845 if (SSL_IS_TLS13(s) && s->hello_retry_request == SSL_HRR_PENDING) {
846 if ((s->options & SSL_OP_ENABLE_MIDDLEBOX_COMPAT) == 0
847 && statem_flush(s) != 1)
851 #ifndef OPENSSL_NO_SCTP
852 if (SSL_IS_DTLS(s) && s->hit) {
853 unsigned char sctpauthkey[64];
854 char labelbuffer[sizeof(DTLS1_SCTP_AUTH_LABEL)];
858 * Add new shared key for SCTP-Auth, will be ignored if no
861 memcpy(labelbuffer, DTLS1_SCTP_AUTH_LABEL,
862 sizeof(DTLS1_SCTP_AUTH_LABEL));
864 /* Don't include the terminating zero. */
865 labellen = sizeof(labelbuffer) - 1;
866 if (s->mode & SSL_MODE_DTLS_SCTP_LABEL_LENGTH_BUG)
869 if (SSL_export_keying_material(s, sctpauthkey,
870 sizeof(sctpauthkey), labelbuffer,
873 SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
877 BIO_ctrl(SSL_get_wbio(s), BIO_CTRL_DGRAM_SCTP_ADD_AUTH_KEY,
878 sizeof(sctpauthkey), sctpauthkey);
882 || ((s->options & SSL_OP_ENABLE_MIDDLEBOX_COMPAT) != 0
883 && s->hello_retry_request != SSL_HRR_COMPLETE))
887 case TLS_ST_SW_CHANGE:
888 if (s->hello_retry_request == SSL_HRR_PENDING) {
889 if (!statem_flush(s))
894 if (SSL_IS_TLS13(s)) {
895 if (!s->method->ssl3_enc->setup_key_block(s)
896 || !s->method->ssl3_enc->change_cipher_state(s,
897 SSL3_CC_HANDSHAKE | SSL3_CHANGE_CIPHER_SERVER_WRITE)) {
898 /* SSLfatal() already called */
902 if (s->ext.early_data != SSL_EARLY_DATA_ACCEPTED
903 && !s->method->ssl3_enc->change_cipher_state(s,
904 SSL3_CC_HANDSHAKE |SSL3_CHANGE_CIPHER_SERVER_READ)) {
905 /* SSLfatal() already called */
909 * We don't yet know whether the next record we are going to receive
910 * is an unencrypted alert, an encrypted alert, or an encrypted
911 * handshake message. We temporarily tolerate unencrypted alerts.
913 s->statem.enc_read_state = ENC_READ_STATE_ALLOW_PLAIN_ALERTS;
917 #ifndef OPENSSL_NO_SCTP
918 if (SSL_IS_DTLS(s) && !s->hit) {
920 * Change to new shared key of SCTP-Auth, will be ignored if
923 BIO_ctrl(SSL_get_wbio(s), BIO_CTRL_DGRAM_SCTP_NEXT_AUTH_KEY,
927 if (!s->method->ssl3_enc->change_cipher_state(s,
928 SSL3_CHANGE_CIPHER_SERVER_WRITE))
930 /* SSLfatal() already called */
935 dtls1_reset_seq_numbers(s, SSL3_CC_WRITE);
938 case TLS_ST_SW_SRVR_DONE:
939 if (statem_flush(s) != 1)
943 case TLS_ST_SW_FINISHED:
944 if (statem_flush(s) != 1)
946 #ifndef OPENSSL_NO_SCTP
947 if (SSL_IS_DTLS(s) && s->hit) {
949 * Change to new shared key of SCTP-Auth, will be ignored if
952 BIO_ctrl(SSL_get_wbio(s), BIO_CTRL_DGRAM_SCTP_NEXT_AUTH_KEY,
956 if (SSL_IS_TLS13(s)) {
957 /* TLS 1.3 gets the secret size from the handshake md */
959 if (!s->method->ssl3_enc->generate_master_secret(s,
960 s->master_secret, s->handshake_secret, 0,
962 || !s->method->ssl3_enc->change_cipher_state(s,
963 SSL3_CC_APPLICATION | SSL3_CHANGE_CIPHER_SERVER_WRITE))
964 /* SSLfatal() already called */
969 case TLS_ST_SW_CERT_REQ:
970 if (s->post_handshake_auth == SSL_PHA_REQUEST_PENDING) {
971 if (statem_flush(s) != 1)
976 case TLS_ST_SW_KEY_UPDATE:
977 if (statem_flush(s) != 1)
979 if (!tls13_update_key(s, 1)) {
980 /* SSLfatal() already called */
985 case TLS_ST_SW_SESSION_TICKET:
987 if (SSL_IS_TLS13(s) && statem_flush(s) != 1) {
988 if (SSL_get_error(s, 0) == SSL_ERROR_SYSCALL
989 && conn_is_closed()) {
991 * We ignore connection closed errors in TLSv1.3 when sending a
992 * NewSessionTicket and behave as if we were successful. This is
993 * so that we are still able to read data sent to us by a client
994 * that closes soon after the end of the handshake without
995 * waiting to read our post-handshake NewSessionTickets.
997 s->rwstate = SSL_NOTHING;
1006 return WORK_FINISHED_CONTINUE;
1010 * Get the message construction function and message type for sending from the
1013 * Valid return values are:
1017 int ossl_statem_server_construct_message(SSL *s, WPACKET *pkt,
1018 confunc_f *confunc, int *mt)
1020 OSSL_STATEM *st = &s->statem;
1022 switch (st->hand_state) {
1024 /* Shouldn't happen */
1025 SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_R_BAD_HANDSHAKE_STATE);
1028 case TLS_ST_SW_CHANGE:
1030 *confunc = dtls_construct_change_cipher_spec;
1032 *confunc = tls_construct_change_cipher_spec;
1033 *mt = SSL3_MT_CHANGE_CIPHER_SPEC;
1036 case DTLS_ST_SW_HELLO_VERIFY_REQUEST:
1037 *confunc = dtls_construct_hello_verify_request;
1038 *mt = DTLS1_MT_HELLO_VERIFY_REQUEST;
1041 case TLS_ST_SW_HELLO_REQ:
1042 /* No construction function needed */
1044 *mt = SSL3_MT_HELLO_REQUEST;
1047 case TLS_ST_SW_SRVR_HELLO:
1048 *confunc = tls_construct_server_hello;
1049 *mt = SSL3_MT_SERVER_HELLO;
1052 case TLS_ST_SW_CERT:
1053 *confunc = tls_construct_server_certificate;
1054 *mt = SSL3_MT_CERTIFICATE;
1057 case TLS_ST_SW_CERT_VRFY:
1058 *confunc = tls_construct_cert_verify;
1059 *mt = SSL3_MT_CERTIFICATE_VERIFY;
1063 case TLS_ST_SW_KEY_EXCH:
1064 *confunc = tls_construct_server_key_exchange;
1065 *mt = SSL3_MT_SERVER_KEY_EXCHANGE;
1068 case TLS_ST_SW_CERT_REQ:
1069 *confunc = tls_construct_certificate_request;
1070 *mt = SSL3_MT_CERTIFICATE_REQUEST;
1073 case TLS_ST_SW_SRVR_DONE:
1074 *confunc = tls_construct_server_done;
1075 *mt = SSL3_MT_SERVER_DONE;
1078 case TLS_ST_SW_SESSION_TICKET:
1079 *confunc = tls_construct_new_session_ticket;
1080 *mt = SSL3_MT_NEWSESSION_TICKET;
1083 case TLS_ST_SW_CERT_STATUS:
1084 *confunc = tls_construct_cert_status;
1085 *mt = SSL3_MT_CERTIFICATE_STATUS;
1088 case TLS_ST_SW_FINISHED:
1089 *confunc = tls_construct_finished;
1090 *mt = SSL3_MT_FINISHED;
1093 case TLS_ST_EARLY_DATA:
1095 *mt = SSL3_MT_DUMMY;
1098 case TLS_ST_SW_ENCRYPTED_EXTENSIONS:
1099 *confunc = tls_construct_encrypted_extensions;
1100 *mt = SSL3_MT_ENCRYPTED_EXTENSIONS;
1103 case TLS_ST_SW_KEY_UPDATE:
1104 *confunc = tls_construct_key_update;
1105 *mt = SSL3_MT_KEY_UPDATE;
1113 * Maximum size (excluding the Handshake header) of a ClientHello message,
1114 * calculated as follows:
1116 * 2 + # client_version
1117 * 32 + # only valid length for random
1118 * 1 + # length of session_id
1119 * 32 + # maximum size for session_id
1120 * 2 + # length of cipher suites
1121 * 2^16-2 + # maximum length of cipher suites array
1122 * 1 + # length of compression_methods
1123 * 2^8-1 + # maximum length of compression methods
1124 * 2 + # length of extensions
1125 * 2^16-1 # maximum length of extensions
1127 #define CLIENT_HELLO_MAX_LENGTH 131396
1129 #define CLIENT_KEY_EXCH_MAX_LENGTH 2048
1130 #define NEXT_PROTO_MAX_LENGTH 514
1133 * Returns the maximum allowed length for the current message that we are
1134 * reading. Excludes the message header.
1136 size_t ossl_statem_server_max_message_size(SSL *s)
1138 OSSL_STATEM *st = &s->statem;
1140 switch (st->hand_state) {
1142 /* Shouldn't happen */
1145 case TLS_ST_SR_CLNT_HELLO:
1146 return CLIENT_HELLO_MAX_LENGTH;
1148 case TLS_ST_SR_END_OF_EARLY_DATA:
1149 return END_OF_EARLY_DATA_MAX_LENGTH;
1151 case TLS_ST_SR_CERT:
1152 return s->max_cert_list;
1154 case TLS_ST_SR_KEY_EXCH:
1155 return CLIENT_KEY_EXCH_MAX_LENGTH;
1157 case TLS_ST_SR_CERT_VRFY:
1158 return SSL3_RT_MAX_PLAIN_LENGTH;
1160 #ifndef OPENSSL_NO_NEXTPROTONEG
1161 case TLS_ST_SR_NEXT_PROTO:
1162 return NEXT_PROTO_MAX_LENGTH;
1165 case TLS_ST_SR_CHANGE:
1166 return CCS_MAX_LENGTH;
1168 case TLS_ST_SR_FINISHED:
1169 return FINISHED_MAX_LENGTH;
1171 case TLS_ST_SR_KEY_UPDATE:
1172 return KEY_UPDATE_MAX_LENGTH;
1177 * Process a message that the server has received from the client.
1179 MSG_PROCESS_RETURN ossl_statem_server_process_message(SSL *s, PACKET *pkt)
1181 OSSL_STATEM *st = &s->statem;
1183 switch (st->hand_state) {
1185 /* Shouldn't happen */
1186 SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
1187 return MSG_PROCESS_ERROR;
1189 case TLS_ST_SR_CLNT_HELLO:
1190 return tls_process_client_hello(s, pkt);
1192 case TLS_ST_SR_END_OF_EARLY_DATA:
1193 return tls_process_end_of_early_data(s, pkt);
1195 case TLS_ST_SR_CERT:
1196 return tls_process_client_certificate(s, pkt);
1198 case TLS_ST_SR_KEY_EXCH:
1199 return tls_process_client_key_exchange(s, pkt);
1201 case TLS_ST_SR_CERT_VRFY:
1202 return tls_process_cert_verify(s, pkt);
1204 #ifndef OPENSSL_NO_NEXTPROTONEG
1205 case TLS_ST_SR_NEXT_PROTO:
1206 return tls_process_next_proto(s, pkt);
1209 case TLS_ST_SR_CHANGE:
1210 return tls_process_change_cipher_spec(s, pkt);
1212 case TLS_ST_SR_FINISHED:
1213 return tls_process_finished(s, pkt);
1215 case TLS_ST_SR_KEY_UPDATE:
1216 return tls_process_key_update(s, pkt);
1222 * Perform any further processing required following the receipt of a message
1225 WORK_STATE ossl_statem_server_post_process_message(SSL *s, WORK_STATE wst)
1227 OSSL_STATEM *st = &s->statem;
1229 switch (st->hand_state) {
1231 /* Shouldn't happen */
1232 SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
1235 case TLS_ST_SR_CLNT_HELLO:
1236 return tls_post_process_client_hello(s, wst);
1238 case TLS_ST_SR_KEY_EXCH:
1239 return tls_post_process_client_key_exchange(s, wst);
1243 #ifndef OPENSSL_NO_SRP
1244 /* Returns 1 on success, 0 for retryable error, -1 for fatal error */
1245 static int ssl_check_srp_ext_ClientHello(SSL *s)
1248 int al = SSL_AD_UNRECOGNIZED_NAME;
1250 if ((s->s3.tmp.new_cipher->algorithm_mkey & SSL_kSRP) &&
1251 (s->srp_ctx.TLS_ext_srp_username_callback != NULL)) {
1252 if (s->srp_ctx.login == NULL) {
1254 * RFC 5054 says SHOULD reject, we do so if There is no srp
1257 SSLfatal(s, SSL_AD_UNKNOWN_PSK_IDENTITY,
1258 SSL_R_PSK_IDENTITY_NOT_FOUND);
1261 ret = ssl_srp_server_param_with_username_intern(s, &al);
1264 if (ret == SSL3_AL_FATAL) {
1266 al == SSL_AD_UNKNOWN_PSK_IDENTITY
1267 ? SSL_R_PSK_IDENTITY_NOT_FOUND
1268 : SSL_R_CLIENTHELLO_TLSEXT);
1277 int dtls_raw_hello_verify_request(WPACKET *pkt, unsigned char *cookie,
1280 /* Always use DTLS 1.0 version: see RFC 6347 */
1281 if (!WPACKET_put_bytes_u16(pkt, DTLS1_VERSION)
1282 || !WPACKET_sub_memcpy_u8(pkt, cookie, cookie_len))
1288 int dtls_construct_hello_verify_request(SSL *s, WPACKET *pkt)
1290 unsigned int cookie_leni;
1291 if (s->ctx->app_gen_cookie_cb == NULL ||
1292 s->ctx->app_gen_cookie_cb(s, s->d1->cookie,
1293 &cookie_leni) == 0 ||
1294 cookie_leni > DTLS1_COOKIE_LENGTH) {
1295 SSLfatal(s, SSL_AD_NO_ALERT, SSL_R_COOKIE_GEN_CALLBACK_FAILURE);
1298 s->d1->cookie_len = cookie_leni;
1300 if (!dtls_raw_hello_verify_request(pkt, s->d1->cookie,
1301 s->d1->cookie_len)) {
1302 SSLfatal(s, SSL_AD_NO_ALERT, ERR_R_INTERNAL_ERROR);
1310 * ssl_check_for_safari attempts to fingerprint Safari using OS X
1311 * SecureTransport using the TLS extension block in |hello|.
1312 * Safari, since 10.6, sends exactly these extensions, in this order:
1316 * signature_algorithms (for TLSv1.2 only)
1318 * We wish to fingerprint Safari because they broke ECDHE-ECDSA support in 10.8,
1319 * but they advertise support. So enabling ECDHE-ECDSA ciphers breaks them.
1320 * Sadly we cannot differentiate 10.6, 10.7 and 10.8.4 (which work), from
1321 * 10.8..10.8.3 (which don't work).
1323 static void ssl_check_for_safari(SSL *s, const CLIENTHELLO_MSG *hello)
1325 static const unsigned char kSafariExtensionsBlock[] = {
1326 0x00, 0x0a, /* elliptic_curves extension */
1327 0x00, 0x08, /* 8 bytes */
1328 0x00, 0x06, /* 6 bytes of curve ids */
1329 0x00, 0x17, /* P-256 */
1330 0x00, 0x18, /* P-384 */
1331 0x00, 0x19, /* P-521 */
1333 0x00, 0x0b, /* ec_point_formats */
1334 0x00, 0x02, /* 2 bytes */
1335 0x01, /* 1 point format */
1336 0x00, /* uncompressed */
1337 /* The following is only present in TLS 1.2 */
1338 0x00, 0x0d, /* signature_algorithms */
1339 0x00, 0x0c, /* 12 bytes */
1340 0x00, 0x0a, /* 10 bytes */
1341 0x05, 0x01, /* SHA-384/RSA */
1342 0x04, 0x01, /* SHA-256/RSA */
1343 0x02, 0x01, /* SHA-1/RSA */
1344 0x04, 0x03, /* SHA-256/ECDSA */
1345 0x02, 0x03, /* SHA-1/ECDSA */
1347 /* Length of the common prefix (first two extensions). */
1348 static const size_t kSafariCommonExtensionsLength = 18;
1353 tmppkt = hello->extensions;
1355 if (!PACKET_forward(&tmppkt, 2)
1356 || !PACKET_get_net_2(&tmppkt, &type)
1357 || !PACKET_get_length_prefixed_2(&tmppkt, &sni)) {
1361 if (type != TLSEXT_TYPE_server_name)
1364 ext_len = TLS1_get_client_version(s) >= TLS1_2_VERSION ?
1365 sizeof(kSafariExtensionsBlock) : kSafariCommonExtensionsLength;
1367 s->s3.is_probably_safari = PACKET_equal(&tmppkt, kSafariExtensionsBlock,
1371 MSG_PROCESS_RETURN tls_process_client_hello(SSL *s, PACKET *pkt)
1373 /* |cookie| will only be initialized for DTLS. */
1374 PACKET session_id, compression, extensions, cookie;
1375 static const unsigned char null_compression = 0;
1376 CLIENTHELLO_MSG *clienthello = NULL;
1378 /* Check if this is actually an unexpected renegotiation ClientHello */
1379 if (s->renegotiate == 0 && !SSL_IS_FIRST_HANDSHAKE(s)) {
1380 if (!ossl_assert(!SSL_IS_TLS13(s))) {
1381 SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
1384 if ((s->options & SSL_OP_NO_RENEGOTIATION) != 0
1385 || (!s->s3.send_connection_binding
1387 & SSL_OP_ALLOW_UNSAFE_LEGACY_RENEGOTIATION) == 0)) {
1388 ssl3_send_alert(s, SSL3_AL_WARNING, SSL_AD_NO_RENEGOTIATION);
1389 return MSG_PROCESS_FINISHED_READING;
1395 clienthello = OPENSSL_zalloc(sizeof(*clienthello));
1396 if (clienthello == NULL) {
1397 SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
1402 * First, parse the raw ClientHello data into the CLIENTHELLO_MSG structure.
1404 clienthello->isv2 = RECORD_LAYER_is_sslv2_record(&s->rlayer);
1405 PACKET_null_init(&cookie);
1407 if (clienthello->isv2) {
1410 if (!SSL_IS_FIRST_HANDSHAKE(s)
1411 || s->hello_retry_request != SSL_HRR_NONE) {
1412 SSLfatal(s, SSL_AD_UNEXPECTED_MESSAGE, SSL_R_UNEXPECTED_MESSAGE);
1417 * An SSLv3/TLSv1 backwards-compatible CLIENT-HELLO in an SSLv2
1418 * header is sent directly on the wire, not wrapped as a TLS
1419 * record. Our record layer just processes the message length and passes
1420 * the rest right through. Its format is:
1422 * 0-1 msg_length - decoded by the record layer
1423 * 2 msg_type - s->init_msg points here
1425 * 5-6 cipher_spec_length
1426 * 7-8 session_id_length
1427 * 9-10 challenge_length
1431 if (!PACKET_get_1(pkt, &mt)
1432 || mt != SSL2_MT_CLIENT_HELLO) {
1434 * Should never happen. We should have tested this in the record
1435 * layer in order to have determined that this is a SSLv2 record
1436 * in the first place
1438 SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
1443 if (!PACKET_get_net_2(pkt, &clienthello->legacy_version)) {
1444 SSLfatal(s, SSL_AD_DECODE_ERROR, SSL_R_LENGTH_TOO_SHORT);
1448 /* Parse the message and load client random. */
1449 if (clienthello->isv2) {
1451 * Handle an SSLv2 backwards compatible ClientHello
1452 * Note, this is only for SSLv3+ using the backward compatible format.
1453 * Real SSLv2 is not supported, and is rejected below.
1455 unsigned int ciphersuite_len, session_id_len, challenge_len;
1458 if (!PACKET_get_net_2(pkt, &ciphersuite_len)
1459 || !PACKET_get_net_2(pkt, &session_id_len)
1460 || !PACKET_get_net_2(pkt, &challenge_len)) {
1461 SSLfatal(s, SSL_AD_DECODE_ERROR, SSL_R_RECORD_LENGTH_MISMATCH);
1465 if (session_id_len > SSL_MAX_SSL_SESSION_ID_LENGTH) {
1466 SSLfatal(s, SSL_AD_ILLEGAL_PARAMETER, SSL_R_LENGTH_MISMATCH);
1470 if (!PACKET_get_sub_packet(pkt, &clienthello->ciphersuites,
1472 || !PACKET_copy_bytes(pkt, clienthello->session_id, session_id_len)
1473 || !PACKET_get_sub_packet(pkt, &challenge, challenge_len)
1474 /* No extensions. */
1475 || PACKET_remaining(pkt) != 0) {
1476 SSLfatal(s, SSL_AD_DECODE_ERROR, SSL_R_RECORD_LENGTH_MISMATCH);
1479 clienthello->session_id_len = session_id_len;
1481 /* Load the client random and compression list. We use SSL3_RANDOM_SIZE
1482 * here rather than sizeof(clienthello->random) because that is the limit
1483 * for SSLv3 and it is fixed. It won't change even if
1484 * sizeof(clienthello->random) does.
1486 challenge_len = challenge_len > SSL3_RANDOM_SIZE
1487 ? SSL3_RANDOM_SIZE : challenge_len;
1488 memset(clienthello->random, 0, SSL3_RANDOM_SIZE);
1489 if (!PACKET_copy_bytes(&challenge,
1490 clienthello->random + SSL3_RANDOM_SIZE -
1491 challenge_len, challenge_len)
1492 /* Advertise only null compression. */
1493 || !PACKET_buf_init(&compression, &null_compression, 1)) {
1494 SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
1498 PACKET_null_init(&clienthello->extensions);
1500 /* Regular ClientHello. */
1501 if (!PACKET_copy_bytes(pkt, clienthello->random, SSL3_RANDOM_SIZE)
1502 || !PACKET_get_length_prefixed_1(pkt, &session_id)
1503 || !PACKET_copy_all(&session_id, clienthello->session_id,
1504 SSL_MAX_SSL_SESSION_ID_LENGTH,
1505 &clienthello->session_id_len)) {
1506 SSLfatal(s, SSL_AD_DECODE_ERROR, SSL_R_LENGTH_MISMATCH);
1510 if (SSL_IS_DTLS(s)) {
1511 if (!PACKET_get_length_prefixed_1(pkt, &cookie)) {
1512 SSLfatal(s, SSL_AD_DECODE_ERROR, SSL_R_LENGTH_MISMATCH);
1515 if (!PACKET_copy_all(&cookie, clienthello->dtls_cookie,
1516 DTLS1_COOKIE_LENGTH,
1517 &clienthello->dtls_cookie_len)) {
1518 SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
1522 * If we require cookies and this ClientHello doesn't contain one,
1523 * just return since we do not want to allocate any memory yet.
1524 * So check cookie length...
1526 if (SSL_get_options(s) & SSL_OP_COOKIE_EXCHANGE) {
1527 if (clienthello->dtls_cookie_len == 0) {
1528 OPENSSL_free(clienthello);
1529 return MSG_PROCESS_FINISHED_READING;
1534 if (!PACKET_get_length_prefixed_2(pkt, &clienthello->ciphersuites)) {
1535 SSLfatal(s, SSL_AD_DECODE_ERROR, SSL_R_LENGTH_MISMATCH);
1539 if (!PACKET_get_length_prefixed_1(pkt, &compression)) {
1540 SSLfatal(s, SSL_AD_DECODE_ERROR, SSL_R_LENGTH_MISMATCH);
1544 /* Could be empty. */
1545 if (PACKET_remaining(pkt) == 0) {
1546 PACKET_null_init(&clienthello->extensions);
1548 if (!PACKET_get_length_prefixed_2(pkt, &clienthello->extensions)
1549 || PACKET_remaining(pkt) != 0) {
1550 SSLfatal(s, SSL_AD_DECODE_ERROR, SSL_R_LENGTH_MISMATCH);
1556 if (!PACKET_copy_all(&compression, clienthello->compressions,
1557 MAX_COMPRESSIONS_SIZE,
1558 &clienthello->compressions_len)) {
1559 SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
1563 /* Preserve the raw extensions PACKET for later use */
1564 extensions = clienthello->extensions;
1565 if (!tls_collect_extensions(s, &extensions, SSL_EXT_CLIENT_HELLO,
1566 &clienthello->pre_proc_exts,
1567 &clienthello->pre_proc_exts_len, 1)) {
1568 /* SSLfatal already been called */
1571 s->clienthello = clienthello;
1573 return MSG_PROCESS_CONTINUE_PROCESSING;
1576 if (clienthello != NULL)
1577 OPENSSL_free(clienthello->pre_proc_exts);
1578 OPENSSL_free(clienthello);
1580 return MSG_PROCESS_ERROR;
1583 static int tls_early_post_process_client_hello(SSL *s)
1586 int i, al = SSL_AD_INTERNAL_ERROR;
1590 #ifndef OPENSSL_NO_COMP
1591 SSL_COMP *comp = NULL;
1593 const SSL_CIPHER *c;
1594 STACK_OF(SSL_CIPHER) *ciphers = NULL;
1595 STACK_OF(SSL_CIPHER) *scsvs = NULL;
1596 CLIENTHELLO_MSG *clienthello = s->clienthello;
1597 DOWNGRADE dgrd = DOWNGRADE_NONE;
1599 /* Finished parsing the ClientHello, now we can start processing it */
1600 /* Give the ClientHello callback a crack at things */
1601 if (s->ctx->client_hello_cb != NULL) {
1602 /* A failure in the ClientHello callback terminates the connection. */
1603 switch (s->ctx->client_hello_cb(s, &al, s->ctx->client_hello_cb_arg)) {
1604 case SSL_CLIENT_HELLO_SUCCESS:
1606 case SSL_CLIENT_HELLO_RETRY:
1607 s->rwstate = SSL_CLIENT_HELLO_CB;
1609 case SSL_CLIENT_HELLO_ERROR:
1611 SSLfatal(s, al, SSL_R_CALLBACK_FAILED);
1616 /* Set up the client_random */
1617 memcpy(s->s3.client_random, clienthello->random, SSL3_RANDOM_SIZE);
1619 /* Choose the version */
1621 if (clienthello->isv2) {
1622 if (clienthello->legacy_version == SSL2_VERSION
1623 || (clienthello->legacy_version & 0xff00)
1624 != (SSL3_VERSION_MAJOR << 8)) {
1626 * This is real SSLv2 or something completely unknown. We don't
1629 SSLfatal(s, SSL_AD_PROTOCOL_VERSION, SSL_R_UNKNOWN_PROTOCOL);
1633 s->client_version = clienthello->legacy_version;
1636 * Do SSL/TLS version negotiation if applicable. For DTLS we just check
1637 * versions are potentially compatible. Version negotiation comes later.
1639 if (!SSL_IS_DTLS(s)) {
1640 protverr = ssl_choose_server_version(s, clienthello, &dgrd);
1641 } else if (s->method->version != DTLS_ANY_VERSION &&
1642 DTLS_VERSION_LT((int)clienthello->legacy_version, s->version)) {
1643 protverr = SSL_R_VERSION_TOO_LOW;
1649 if (SSL_IS_FIRST_HANDSHAKE(s)) {
1650 /* like ssl3_get_record, send alert using remote version number */
1651 s->version = s->client_version = clienthello->legacy_version;
1653 SSLfatal(s, SSL_AD_PROTOCOL_VERSION, protverr);
1657 /* TLSv1.3 specifies that a ClientHello must end on a record boundary */
1658 if (SSL_IS_TLS13(s) && RECORD_LAYER_processed_read_pending(&s->rlayer)) {
1659 SSLfatal(s, SSL_AD_UNEXPECTED_MESSAGE, SSL_R_NOT_ON_RECORD_BOUNDARY);
1663 if (SSL_IS_DTLS(s)) {
1664 /* Empty cookie was already handled above by returning early. */
1665 if (SSL_get_options(s) & SSL_OP_COOKIE_EXCHANGE) {
1666 if (s->ctx->app_verify_cookie_cb != NULL) {
1667 if (s->ctx->app_verify_cookie_cb(s, clienthello->dtls_cookie,
1668 clienthello->dtls_cookie_len) == 0) {
1669 SSLfatal(s, SSL_AD_HANDSHAKE_FAILURE,
1670 SSL_R_COOKIE_MISMATCH);
1672 /* else cookie verification succeeded */
1674 /* default verification */
1675 } else if (s->d1->cookie_len != clienthello->dtls_cookie_len
1676 || memcmp(clienthello->dtls_cookie, s->d1->cookie,
1677 s->d1->cookie_len) != 0) {
1678 SSLfatal(s, SSL_AD_HANDSHAKE_FAILURE, SSL_R_COOKIE_MISMATCH);
1681 s->d1->cookie_verified = 1;
1683 if (s->method->version == DTLS_ANY_VERSION) {
1684 protverr = ssl_choose_server_version(s, clienthello, &dgrd);
1685 if (protverr != 0) {
1686 s->version = s->client_version;
1687 SSLfatal(s, SSL_AD_PROTOCOL_VERSION, protverr);
1695 if (!ssl_cache_cipherlist(s, &clienthello->ciphersuites,
1696 clienthello->isv2) ||
1697 !bytes_to_cipher_list(s, &clienthello->ciphersuites, &ciphers, &scsvs,
1698 clienthello->isv2, 1)) {
1699 /* SSLfatal() already called */
1703 s->s3.send_connection_binding = 0;
1704 /* Check what signalling cipher-suite values were received. */
1705 if (scsvs != NULL) {
1706 for(i = 0; i < sk_SSL_CIPHER_num(scsvs); i++) {
1707 c = sk_SSL_CIPHER_value(scsvs, i);
1708 if (SSL_CIPHER_get_id(c) == SSL3_CK_SCSV) {
1709 if (s->renegotiate) {
1710 /* SCSV is fatal if renegotiating */
1711 SSLfatal(s, SSL_AD_HANDSHAKE_FAILURE,
1712 SSL_R_SCSV_RECEIVED_WHEN_RENEGOTIATING);
1715 s->s3.send_connection_binding = 1;
1716 } else if (SSL_CIPHER_get_id(c) == SSL3_CK_FALLBACK_SCSV &&
1717 !ssl_check_version_downgrade(s)) {
1719 * This SCSV indicates that the client previously tried
1720 * a higher version. We should fail if the current version
1721 * is an unexpected downgrade, as that indicates that the first
1722 * connection may have been tampered with in order to trigger
1723 * an insecure downgrade.
1725 SSLfatal(s, SSL_AD_INAPPROPRIATE_FALLBACK,
1726 SSL_R_INAPPROPRIATE_FALLBACK);
1732 /* For TLSv1.3 we must select the ciphersuite *before* session resumption */
1733 if (SSL_IS_TLS13(s)) {
1734 const SSL_CIPHER *cipher =
1735 ssl3_choose_cipher(s, ciphers, SSL_get_ciphers(s));
1737 if (cipher == NULL) {
1738 SSLfatal(s, SSL_AD_HANDSHAKE_FAILURE, SSL_R_NO_SHARED_CIPHER);
1741 if (s->hello_retry_request == SSL_HRR_PENDING
1742 && (s->s3.tmp.new_cipher == NULL
1743 || s->s3.tmp.new_cipher->id != cipher->id)) {
1745 * A previous HRR picked a different ciphersuite to the one we
1746 * just selected. Something must have changed.
1748 SSLfatal(s, SSL_AD_ILLEGAL_PARAMETER, SSL_R_BAD_CIPHER);
1751 s->s3.tmp.new_cipher = cipher;
1754 /* We need to do this before getting the session */
1755 if (!tls_parse_extension(s, TLSEXT_IDX_extended_master_secret,
1756 SSL_EXT_CLIENT_HELLO,
1757 clienthello->pre_proc_exts, NULL, 0)) {
1758 /* SSLfatal() already called */
1763 * We don't allow resumption in a backwards compatible ClientHello.
1764 * TODO(openssl-team): in TLS1.1+, session_id MUST be empty.
1766 * Versions before 0.9.7 always allow clients to resume sessions in
1767 * renegotiation. 0.9.7 and later allow this by default, but optionally
1768 * ignore resumption requests with flag
1769 * SSL_OP_NO_SESSION_RESUMPTION_ON_RENEGOTIATION (it's a new flag rather
1770 * than a change to default behavior so that applications relying on
1771 * this for security won't even compile against older library versions).
1772 * 1.0.1 and later also have a function SSL_renegotiate_abbreviated() to
1773 * request renegotiation but not a new session (s->new_session remains
1774 * unset): for servers, this essentially just means that the
1775 * SSL_OP_NO_SESSION_RESUMPTION_ON_RENEGOTIATION setting will be
1778 if (clienthello->isv2 ||
1780 (s->options & SSL_OP_NO_SESSION_RESUMPTION_ON_RENEGOTIATION))) {
1781 if (!ssl_get_new_session(s, 1)) {
1782 /* SSLfatal() already called */
1786 i = ssl_get_prev_session(s, clienthello);
1788 /* previous session */
1790 } else if (i == -1) {
1791 /* SSLfatal() already called */
1795 if (!ssl_get_new_session(s, 1)) {
1796 /* SSLfatal() already called */
1802 if (SSL_IS_TLS13(s)) {
1803 memcpy(s->tmp_session_id, s->clienthello->session_id,
1804 s->clienthello->session_id_len);
1805 s->tmp_session_id_len = s->clienthello->session_id_len;
1809 * If it is a hit, check that the cipher is in the list. In TLSv1.3 we check
1810 * ciphersuite compatibility with the session as part of resumption.
1812 if (!SSL_IS_TLS13(s) && s->hit) {
1814 id = s->session->cipher->id;
1816 OSSL_TRACE_BEGIN(TLS_CIPHER) {
1817 BIO_printf(trc_out, "client sent %d ciphers\n",
1818 sk_SSL_CIPHER_num(ciphers));
1820 for (i = 0; i < sk_SSL_CIPHER_num(ciphers); i++) {
1821 c = sk_SSL_CIPHER_value(ciphers, i);
1822 if (trc_out != NULL)
1823 BIO_printf(trc_out, "client [%2d of %2d]:%s\n", i,
1824 sk_SSL_CIPHER_num(ciphers), SSL_CIPHER_get_name(c));
1832 * we need to have the cipher in the cipher list if we are asked
1835 SSLfatal(s, SSL_AD_ILLEGAL_PARAMETER,
1836 SSL_R_REQUIRED_CIPHER_MISSING);
1837 OSSL_TRACE_CANCEL(TLS_CIPHER);
1840 OSSL_TRACE_END(TLS_CIPHER);
1843 for (loop = 0; loop < clienthello->compressions_len; loop++) {
1844 if (clienthello->compressions[loop] == 0)
1848 if (loop >= clienthello->compressions_len) {
1850 SSLfatal(s, SSL_AD_DECODE_ERROR, SSL_R_NO_COMPRESSION_SPECIFIED);
1854 if (s->options & SSL_OP_SAFARI_ECDHE_ECDSA_BUG)
1855 ssl_check_for_safari(s, clienthello);
1857 /* TLS extensions */
1858 if (!tls_parse_all_extensions(s, SSL_EXT_CLIENT_HELLO,
1859 clienthello->pre_proc_exts, NULL, 0, 1)) {
1860 /* SSLfatal() already called */
1865 * Check if we want to use external pre-shared secret for this handshake
1866 * for not reused session only. We need to generate server_random before
1867 * calling tls_session_secret_cb in order to allow SessionTicket
1868 * processing to use it in key derivation.
1872 pos = s->s3.server_random;
1873 if (ssl_fill_hello_random(s, 1, pos, SSL3_RANDOM_SIZE, dgrd) <= 0) {
1874 SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
1880 && s->version >= TLS1_VERSION
1883 && s->ext.session_secret_cb) {
1884 const SSL_CIPHER *pref_cipher = NULL;
1886 * s->session->master_key_length is a size_t, but this is an int for
1887 * backwards compat reasons
1889 int master_key_length;
1891 master_key_length = sizeof(s->session->master_key);
1892 if (s->ext.session_secret_cb(s, s->session->master_key,
1893 &master_key_length, ciphers,
1895 s->ext.session_secret_cb_arg)
1896 && master_key_length > 0) {
1897 s->session->master_key_length = master_key_length;
1899 s->peer_ciphers = ciphers;
1900 s->session->verify_result = X509_V_OK;
1904 /* check if some cipher was preferred by call back */
1905 if (pref_cipher == NULL)
1906 pref_cipher = ssl3_choose_cipher(s, s->peer_ciphers,
1907 SSL_get_ciphers(s));
1908 if (pref_cipher == NULL) {
1909 SSLfatal(s, SSL_AD_HANDSHAKE_FAILURE, SSL_R_NO_SHARED_CIPHER);
1913 s->session->cipher = pref_cipher;
1914 sk_SSL_CIPHER_free(s->cipher_list);
1915 s->cipher_list = sk_SSL_CIPHER_dup(s->peer_ciphers);
1916 sk_SSL_CIPHER_free(s->cipher_list_by_id);
1917 s->cipher_list_by_id = sk_SSL_CIPHER_dup(s->peer_ciphers);
1922 * Worst case, we will use the NULL compression, but if we have other
1923 * options, we will now look for them. We have complen-1 compression
1924 * algorithms from the client, starting at q.
1926 s->s3.tmp.new_compression = NULL;
1927 if (SSL_IS_TLS13(s)) {
1929 * We already checked above that the NULL compression method appears in
1930 * the list. Now we check there aren't any others (which is illegal in
1931 * a TLSv1.3 ClientHello.
1933 if (clienthello->compressions_len != 1) {
1934 SSLfatal(s, SSL_AD_ILLEGAL_PARAMETER,
1935 SSL_R_INVALID_COMPRESSION_ALGORITHM);
1939 #ifndef OPENSSL_NO_COMP
1940 /* This only happens if we have a cache hit */
1941 else if (s->session->compress_meth != 0) {
1942 int m, comp_id = s->session->compress_meth;
1944 /* Perform sanity checks on resumed compression algorithm */
1945 /* Can't disable compression */
1946 if (!ssl_allow_compression(s)) {
1947 SSLfatal(s, SSL_AD_HANDSHAKE_FAILURE,
1948 SSL_R_INCONSISTENT_COMPRESSION);
1951 /* Look for resumed compression method */
1952 for (m = 0; m < sk_SSL_COMP_num(s->ctx->comp_methods); m++) {
1953 comp = sk_SSL_COMP_value(s->ctx->comp_methods, m);
1954 if (comp_id == comp->id) {
1955 s->s3.tmp.new_compression = comp;
1959 if (s->s3.tmp.new_compression == NULL) {
1960 SSLfatal(s, SSL_AD_HANDSHAKE_FAILURE,
1961 SSL_R_INVALID_COMPRESSION_ALGORITHM);
1964 /* Look for resumed method in compression list */
1965 for (k = 0; k < clienthello->compressions_len; k++) {
1966 if (clienthello->compressions[k] == comp_id)
1969 if (k >= clienthello->compressions_len) {
1970 SSLfatal(s, SSL_AD_ILLEGAL_PARAMETER,
1971 SSL_R_REQUIRED_COMPRESSION_ALGORITHM_MISSING);
1974 } else if (s->hit) {
1976 } else if (ssl_allow_compression(s) && s->ctx->comp_methods) {
1977 /* See if we have a match */
1978 int m, nn, v, done = 0;
1981 nn = sk_SSL_COMP_num(s->ctx->comp_methods);
1982 for (m = 0; m < nn; m++) {
1983 comp = sk_SSL_COMP_value(s->ctx->comp_methods, m);
1985 for (o = 0; o < clienthello->compressions_len; o++) {
1986 if (v == clienthello->compressions[o]) {
1995 s->s3.tmp.new_compression = comp;
2001 * If compression is disabled we'd better not try to resume a session
2002 * using compression.
2004 if (s->session->compress_meth != 0) {
2005 SSLfatal(s, SSL_AD_HANDSHAKE_FAILURE, SSL_R_INCONSISTENT_COMPRESSION);
2011 * Given s->peer_ciphers and SSL_get_ciphers, we must pick a cipher
2014 if (!s->hit || SSL_IS_TLS13(s)) {
2015 sk_SSL_CIPHER_free(s->peer_ciphers);
2016 s->peer_ciphers = ciphers;
2017 if (ciphers == NULL) {
2018 SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
2025 #ifdef OPENSSL_NO_COMP
2026 s->session->compress_meth = 0;
2028 s->session->compress_meth = (comp == NULL) ? 0 : comp->id;
2030 if (!tls1_set_server_sigalgs(s)) {
2031 /* SSLfatal() already called */
2036 sk_SSL_CIPHER_free(ciphers);
2037 sk_SSL_CIPHER_free(scsvs);
2038 OPENSSL_free(clienthello->pre_proc_exts);
2039 OPENSSL_free(s->clienthello);
2040 s->clienthello = NULL;
2043 sk_SSL_CIPHER_free(ciphers);
2044 sk_SSL_CIPHER_free(scsvs);
2045 OPENSSL_free(clienthello->pre_proc_exts);
2046 OPENSSL_free(s->clienthello);
2047 s->clienthello = NULL;
2053 * Call the status request callback if needed. Upon success, returns 1.
2054 * Upon failure, returns 0.
2056 static int tls_handle_status_request(SSL *s)
2058 s->ext.status_expected = 0;
2061 * If status request then ask callback what to do. Note: this must be
2062 * called after servername callbacks in case the certificate has changed,
2063 * and must be called after the cipher has been chosen because this may
2064 * influence which certificate is sent
2066 if (s->ext.status_type != TLSEXT_STATUSTYPE_nothing && s->ctx != NULL
2067 && s->ctx->ext.status_cb != NULL) {
2070 /* If no certificate can't return certificate status */
2071 if (s->s3.tmp.cert != NULL) {
2073 * Set current certificate to one we will use so SSL_get_certificate
2074 * et al can pick it up.
2076 s->cert->key = s->s3.tmp.cert;
2077 ret = s->ctx->ext.status_cb(s, s->ctx->ext.status_arg);
2079 /* We don't want to send a status request response */
2080 case SSL_TLSEXT_ERR_NOACK:
2081 s->ext.status_expected = 0;
2083 /* status request response should be sent */
2084 case SSL_TLSEXT_ERR_OK:
2085 if (s->ext.ocsp.resp)
2086 s->ext.status_expected = 1;
2088 /* something bad happened */
2089 case SSL_TLSEXT_ERR_ALERT_FATAL:
2091 SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_R_CLIENTHELLO_TLSEXT);
2101 * Call the alpn_select callback if needed. Upon success, returns 1.
2102 * Upon failure, returns 0.
2104 int tls_handle_alpn(SSL *s)
2106 const unsigned char *selected = NULL;
2107 unsigned char selected_len = 0;
2109 if (s->ctx->ext.alpn_select_cb != NULL && s->s3.alpn_proposed != NULL) {
2110 int r = s->ctx->ext.alpn_select_cb(s, &selected, &selected_len,
2111 s->s3.alpn_proposed,
2112 (unsigned int)s->s3.alpn_proposed_len,
2113 s->ctx->ext.alpn_select_cb_arg);
2115 if (r == SSL_TLSEXT_ERR_OK) {
2116 OPENSSL_free(s->s3.alpn_selected);
2117 s->s3.alpn_selected = OPENSSL_memdup(selected, selected_len);
2118 if (s->s3.alpn_selected == NULL) {
2119 s->s3.alpn_selected_len = 0;
2120 SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
2123 s->s3.alpn_selected_len = selected_len;
2124 #ifndef OPENSSL_NO_NEXTPROTONEG
2125 /* ALPN takes precedence over NPN. */
2129 /* Check ALPN is consistent with session */
2130 if (s->session->ext.alpn_selected == NULL
2131 || selected_len != s->session->ext.alpn_selected_len
2132 || memcmp(selected, s->session->ext.alpn_selected,
2133 selected_len) != 0) {
2134 /* Not consistent so can't be used for early_data */
2135 s->ext.early_data_ok = 0;
2139 * This is a new session and so alpn_selected should have
2140 * been initialised to NULL. We should update it with the
2143 if (!ossl_assert(s->session->ext.alpn_selected == NULL)) {
2144 SSLfatal(s, SSL_AD_INTERNAL_ERROR,
2145 ERR_R_INTERNAL_ERROR);
2148 s->session->ext.alpn_selected = OPENSSL_memdup(selected,
2150 if (s->session->ext.alpn_selected == NULL) {
2151 SSLfatal(s, SSL_AD_INTERNAL_ERROR,
2152 ERR_R_INTERNAL_ERROR);
2155 s->session->ext.alpn_selected_len = selected_len;
2160 } else if (r != SSL_TLSEXT_ERR_NOACK) {
2161 SSLfatal(s, SSL_AD_NO_APPLICATION_PROTOCOL,
2162 SSL_R_NO_APPLICATION_PROTOCOL);
2166 * If r == SSL_TLSEXT_ERR_NOACK then behave as if no callback was
2171 /* Check ALPN is consistent with session */
2172 if (s->session->ext.alpn_selected != NULL) {
2173 /* Not consistent so can't be used for early_data */
2174 s->ext.early_data_ok = 0;
2180 WORK_STATE tls_post_process_client_hello(SSL *s, WORK_STATE wst)
2182 const SSL_CIPHER *cipher;
2184 if (wst == WORK_MORE_A) {
2185 int rv = tls_early_post_process_client_hello(s);
2187 /* SSLfatal() was already called */
2194 if (wst == WORK_MORE_B) {
2195 if (!s->hit || SSL_IS_TLS13(s)) {
2196 /* Let cert callback update server certificates if required */
2197 if (!s->hit && s->cert->cert_cb != NULL) {
2198 int rv = s->cert->cert_cb(s, s->cert->cert_cb_arg);
2200 SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_R_CERT_CB_ERROR);
2204 s->rwstate = SSL_X509_LOOKUP;
2207 s->rwstate = SSL_NOTHING;
2210 /* In TLSv1.3 we selected the ciphersuite before resumption */
2211 if (!SSL_IS_TLS13(s)) {
2213 ssl3_choose_cipher(s, s->peer_ciphers, SSL_get_ciphers(s));
2215 if (cipher == NULL) {
2216 SSLfatal(s, SSL_AD_HANDSHAKE_FAILURE,
2217 SSL_R_NO_SHARED_CIPHER);
2220 s->s3.tmp.new_cipher = cipher;
2223 if (!tls_choose_sigalg(s, 1)) {
2224 /* SSLfatal already called */
2227 /* check whether we should disable session resumption */
2228 if (s->not_resumable_session_cb != NULL)
2229 s->session->not_resumable =
2230 s->not_resumable_session_cb(s,
2231 ((s->s3.tmp.new_cipher->algorithm_mkey
2232 & (SSL_kDHE | SSL_kECDHE)) != 0));
2233 if (s->session->not_resumable)
2234 /* do not send a session ticket */
2235 s->ext.ticket_expected = 0;
2238 /* Session-id reuse */
2239 s->s3.tmp.new_cipher = s->session->cipher;
2243 * we now have the following setup.
2245 * cipher_list - our preferred list of ciphers
2246 * ciphers - the clients preferred list of ciphers
2247 * compression - basically ignored right now
2248 * ssl version is set - sslv3
2249 * s->session - The ssl session has been setup.
2250 * s->hit - session reuse flag
2251 * s->s3.tmp.new_cipher - the new cipher to use.
2255 * Call status_request callback if needed. Has to be done after the
2256 * certificate callbacks etc above.
2258 if (!tls_handle_status_request(s)) {
2259 /* SSLfatal() already called */
2263 * Call alpn_select callback if needed. Has to be done after SNI and
2264 * cipher negotiation (HTTP/2 restricts permitted ciphers). In TLSv1.3
2265 * we already did this because cipher negotiation happens earlier, and
2266 * we must handle ALPN before we decide whether to accept early_data.
2268 if (!SSL_IS_TLS13(s) && !tls_handle_alpn(s)) {
2269 /* SSLfatal() already called */
2275 #ifndef OPENSSL_NO_SRP
2276 if (wst == WORK_MORE_C) {
2278 if ((ret = ssl_check_srp_ext_ClientHello(s)) == 0) {
2280 * callback indicates further work to be done
2282 s->rwstate = SSL_X509_LOOKUP;
2286 /* SSLfatal() already called */
2292 return WORK_FINISHED_STOP;
2297 int tls_construct_server_hello(SSL *s, WPACKET *pkt)
2302 unsigned char *session_id;
2303 int usetls13 = SSL_IS_TLS13(s) || s->hello_retry_request == SSL_HRR_PENDING;
2305 version = usetls13 ? TLS1_2_VERSION : s->version;
2306 if (!WPACKET_put_bytes_u16(pkt, version)
2308 * Random stuff. Filling of the server_random takes place in
2309 * tls_process_client_hello()
2311 || !WPACKET_memcpy(pkt,
2312 s->hello_retry_request == SSL_HRR_PENDING
2313 ? hrrrandom : s->s3.server_random,
2314 SSL3_RANDOM_SIZE)) {
2315 SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
2320 * There are several cases for the session ID to send
2321 * back in the server hello:
2322 * - For session reuse from the session cache,
2323 * we send back the old session ID.
2324 * - If stateless session reuse (using a session ticket)
2325 * is successful, we send back the client's "session ID"
2326 * (which doesn't actually identify the session).
2327 * - If it is a new session, we send back the new
2329 * - However, if we want the new session to be single-use,
2330 * we send back a 0-length session ID.
2331 * - In TLSv1.3 we echo back the session id sent to us by the client
2333 * s->hit is non-zero in either case of session reuse,
2334 * so the following won't overwrite an ID that we're supposed
2337 if (s->session->not_resumable ||
2338 (!(s->ctx->session_cache_mode & SSL_SESS_CACHE_SERVER)
2340 s->session->session_id_length = 0;
2343 sl = s->tmp_session_id_len;
2344 session_id = s->tmp_session_id;
2346 sl = s->session->session_id_length;
2347 session_id = s->session->session_id;
2350 if (sl > sizeof(s->session->session_id)) {
2351 SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
2355 /* set up the compression method */
2356 #ifdef OPENSSL_NO_COMP
2359 if (usetls13 || s->s3.tmp.new_compression == NULL)
2362 compm = s->s3.tmp.new_compression->id;
2365 if (!WPACKET_sub_memcpy_u8(pkt, session_id, sl)
2366 || !s->method->put_cipher_by_char(s->s3.tmp.new_cipher, pkt, &len)
2367 || !WPACKET_put_bytes_u8(pkt, compm)) {
2368 SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
2372 if (!tls_construct_extensions(s, pkt,
2373 s->hello_retry_request == SSL_HRR_PENDING
2374 ? SSL_EXT_TLS1_3_HELLO_RETRY_REQUEST
2376 ? SSL_EXT_TLS1_3_SERVER_HELLO
2377 : SSL_EXT_TLS1_2_SERVER_HELLO),
2379 /* SSLfatal() already called */
2383 if (s->hello_retry_request == SSL_HRR_PENDING) {
2384 /* Ditch the session. We'll create a new one next time around */
2385 SSL_SESSION_free(s->session);
2390 * Re-initialise the Transcript Hash. We're going to prepopulate it with
2391 * a synthetic message_hash in place of ClientHello1.
2393 if (!create_synthetic_message_hash(s, NULL, 0, NULL, 0)) {
2394 /* SSLfatal() already called */
2397 } else if (!(s->verify_mode & SSL_VERIFY_PEER)
2398 && !ssl3_digest_cached_records(s, 0)) {
2399 /* SSLfatal() already called */;
2406 int tls_construct_server_done(SSL *s, WPACKET *pkt)
2408 if (!s->s3.tmp.cert_request) {
2409 if (!ssl3_digest_cached_records(s, 0)) {
2410 /* SSLfatal() already called */
2417 int tls_construct_server_key_exchange(SSL *s, WPACKET *pkt)
2419 EVP_PKEY *pkdh = NULL;
2420 unsigned char *encodedPoint = NULL;
2421 size_t encodedlen = 0;
2423 const SIGALG_LOOKUP *lu = s->s3.tmp.sigalg;
2427 EVP_MD_CTX *md_ctx = EVP_MD_CTX_new();
2428 EVP_PKEY_CTX *pctx = NULL;
2429 size_t paramlen, paramoffset;
2430 int freer = 0, ret = 0;
2432 if (!WPACKET_get_total_written(pkt, ¶moffset)) {
2433 SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
2437 if (md_ctx == NULL) {
2438 SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_MALLOC_FAILURE);
2442 type = s->s3.tmp.new_cipher->algorithm_mkey;
2444 r[0] = r[1] = r[2] = r[3] = NULL;
2445 #ifndef OPENSSL_NO_PSK
2446 /* Plain PSK or RSAPSK nothing to do */
2447 if (type & (SSL_kPSK | SSL_kRSAPSK)) {
2449 #endif /* !OPENSSL_NO_PSK */
2450 if (type & (SSL_kDHE | SSL_kDHEPSK)) {
2451 CERT *cert = s->cert;
2452 EVP_PKEY *pkdhp = NULL;
2454 if (s->cert->dh_tmp_auto) {
2455 pkdh = ssl_get_auto_dh(s);
2457 SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
2462 pkdhp = cert->dh_tmp;
2464 #if !defined(OPENSSL_NO_DEPRECATED_3_0)
2465 if ((pkdhp == NULL) && (s->cert->dh_tmp_cb != NULL)) {
2466 pkdh = ssl_dh_to_pkey(s->cert->dh_tmp_cb(s, 0, 1024));
2468 SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
2474 if (pkdhp == NULL) {
2475 SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_R_MISSING_TMP_DH_KEY);
2478 if (!ssl_security(s, SSL_SECOP_TMP_DH,
2479 EVP_PKEY_security_bits(pkdhp), 0, pkdhp)) {
2480 SSLfatal(s, SSL_AD_HANDSHAKE_FAILURE, SSL_R_DH_KEY_TOO_SMALL);
2483 if (s->s3.tmp.pkey != NULL) {
2484 SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
2488 s->s3.tmp.pkey = ssl_generate_pkey(s, pkdhp);
2489 if (s->s3.tmp.pkey == NULL) {
2490 SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
2494 EVP_PKEY_free(pkdh);
2497 /* These BIGNUMs need to be freed when we're finished */
2499 if (!EVP_PKEY_get_bn_param(s->s3.tmp.pkey, OSSL_PKEY_PARAM_FFC_P,
2501 || !EVP_PKEY_get_bn_param(s->s3.tmp.pkey, OSSL_PKEY_PARAM_FFC_G,
2503 || !EVP_PKEY_get_bn_param(s->s3.tmp.pkey,
2504 OSSL_PKEY_PARAM_PUB_KEY, &r[2])) {
2505 SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
2508 } else if (type & (SSL_kECDHE | SSL_kECDHEPSK)) {
2510 if (s->s3.tmp.pkey != NULL) {
2511 SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
2515 /* Get NID of appropriate shared curve */
2516 curve_id = tls1_shared_group(s, -2);
2517 if (curve_id == 0) {
2518 SSLfatal(s, SSL_AD_HANDSHAKE_FAILURE,
2519 SSL_R_UNSUPPORTED_ELLIPTIC_CURVE);
2522 /* Cache the group used in the SSL_SESSION */
2523 s->session->kex_group = curve_id;
2524 /* Generate a new key for this curve */
2525 s->s3.tmp.pkey = ssl_generate_pkey_group(s, curve_id);
2526 if (s->s3.tmp.pkey == NULL) {
2527 /* SSLfatal() already called */
2531 /* Encode the public key. */
2532 encodedlen = EVP_PKEY_get1_encoded_public_key(s->s3.tmp.pkey,
2534 if (encodedlen == 0) {
2535 SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_EC_LIB);
2540 * We'll generate the serverKeyExchange message explicitly so we
2541 * can set these to NULLs
2548 #ifndef OPENSSL_NO_SRP
2549 if (type & SSL_kSRP) {
2550 if ((s->srp_ctx.N == NULL) ||
2551 (s->srp_ctx.g == NULL) ||
2552 (s->srp_ctx.s == NULL) || (s->srp_ctx.B == NULL)) {
2553 SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_R_MISSING_SRP_PARAM);
2556 r[0] = s->srp_ctx.N;
2557 r[1] = s->srp_ctx.g;
2558 r[2] = s->srp_ctx.s;
2559 r[3] = s->srp_ctx.B;
2563 SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_R_UNKNOWN_KEY_EXCHANGE_TYPE);
2567 if (((s->s3.tmp.new_cipher->algorithm_auth & (SSL_aNULL | SSL_aSRP)) != 0)
2568 || ((s->s3.tmp.new_cipher->algorithm_mkey & SSL_PSK)) != 0) {
2570 } else if (lu == NULL) {
2571 SSLfatal(s, SSL_AD_DECODE_ERROR, ERR_R_INTERNAL_ERROR);
2575 #ifndef OPENSSL_NO_PSK
2576 if (type & SSL_PSK) {
2577 size_t len = (s->cert->psk_identity_hint == NULL)
2578 ? 0 : strlen(s->cert->psk_identity_hint);
2581 * It should not happen that len > PSK_MAX_IDENTITY_LEN - we already
2582 * checked this when we set the identity hint - but just in case
2584 if (len > PSK_MAX_IDENTITY_LEN
2585 || !WPACKET_sub_memcpy_u16(pkt, s->cert->psk_identity_hint,
2587 SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
2593 for (i = 0; i < 4 && r[i] != NULL; i++) {
2594 unsigned char *binval;
2597 #ifndef OPENSSL_NO_SRP
2598 if ((i == 2) && (type & SSL_kSRP)) {
2599 res = WPACKET_start_sub_packet_u8(pkt);
2602 res = WPACKET_start_sub_packet_u16(pkt);
2605 SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
2610 * for interoperability with some versions of the Microsoft TLS
2611 * stack, we need to zero pad the DHE pub key to the same length
2614 if ((i == 2) && (type & (SSL_kDHE | SSL_kDHEPSK))) {
2615 size_t len = BN_num_bytes(r[0]) - BN_num_bytes(r[2]);
2618 if (!WPACKET_allocate_bytes(pkt, len, &binval)) {
2619 SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
2622 memset(binval, 0, len);
2626 if (!WPACKET_allocate_bytes(pkt, BN_num_bytes(r[i]), &binval)
2627 || !WPACKET_close(pkt)) {
2628 SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
2632 BN_bn2bin(r[i], binval);
2635 if (type & (SSL_kECDHE | SSL_kECDHEPSK)) {
2637 * We only support named (not generic) curves. In this situation, the
2638 * ServerKeyExchange message has: [1 byte CurveType], [2 byte CurveName]
2639 * [1 byte length of encoded point], followed by the actual encoded
2642 if (!WPACKET_put_bytes_u8(pkt, NAMED_CURVE_TYPE)
2643 || !WPACKET_put_bytes_u8(pkt, 0)
2644 || !WPACKET_put_bytes_u8(pkt, curve_id)
2645 || !WPACKET_sub_memcpy_u8(pkt, encodedPoint, encodedlen)) {
2646 SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
2649 OPENSSL_free(encodedPoint);
2650 encodedPoint = NULL;
2655 EVP_PKEY *pkey = s->s3.tmp.cert->privatekey;
2657 unsigned char *sigbytes1, *sigbytes2, *tbs;
2658 size_t siglen = 0, tbslen;
2660 if (pkey == NULL || !tls1_lookup_md(s->ctx, lu, &md)) {
2661 /* Should never happen */
2662 SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
2665 /* Get length of the parameters we have written above */
2666 if (!WPACKET_get_length(pkt, ¶mlen)) {
2667 SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
2670 /* send signature algorithm */
2671 if (SSL_USE_SIGALGS(s) && !WPACKET_put_bytes_u16(pkt, lu->sigalg)) {
2672 SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
2676 if (EVP_DigestSignInit_ex(md_ctx, &pctx,
2677 md == NULL ? NULL : EVP_MD_name(md),
2678 s->ctx->libctx, s->ctx->propq, pkey,
2680 SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
2683 if (lu->sig == EVP_PKEY_RSA_PSS) {
2684 if (EVP_PKEY_CTX_set_rsa_padding(pctx, RSA_PKCS1_PSS_PADDING) <= 0
2685 || EVP_PKEY_CTX_set_rsa_pss_saltlen(pctx, RSA_PSS_SALTLEN_DIGEST) <= 0) {
2686 SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_EVP_LIB);
2690 tbslen = construct_key_exchange_tbs(s, &tbs,
2691 s->init_buf->data + paramoffset,
2694 /* SSLfatal() already called */
2698 if (EVP_DigestSign(md_ctx, NULL, &siglen, tbs, tbslen) <=0
2699 || !WPACKET_sub_reserve_bytes_u16(pkt, siglen, &sigbytes1)
2700 || EVP_DigestSign(md_ctx, sigbytes1, &siglen, tbs, tbslen) <= 0
2701 || !WPACKET_sub_allocate_bytes_u16(pkt, siglen, &sigbytes2)
2702 || sigbytes1 != sigbytes2) {
2704 SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
2712 EVP_PKEY_free(pkdh);
2713 OPENSSL_free(encodedPoint);
2714 EVP_MD_CTX_free(md_ctx);
2724 int tls_construct_certificate_request(SSL *s, WPACKET *pkt)
2726 if (SSL_IS_TLS13(s)) {
2727 /* Send random context when doing post-handshake auth */
2728 if (s->post_handshake_auth == SSL_PHA_REQUEST_PENDING) {
2729 OPENSSL_free(s->pha_context);
2730 s->pha_context_len = 32;
2731 if ((s->pha_context = OPENSSL_malloc(s->pha_context_len)) == NULL) {
2732 s->pha_context_len = 0;
2733 SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
2736 if (RAND_bytes_ex(s->ctx->libctx, s->pha_context,
2737 s->pha_context_len) <= 0
2738 || !WPACKET_sub_memcpy_u8(pkt, s->pha_context,
2739 s->pha_context_len)) {
2740 SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
2743 /* reset the handshake hash back to just after the ClientFinished */
2744 if (!tls13_restore_handshake_digest_for_pha(s)) {
2745 /* SSLfatal() already called */
2749 if (!WPACKET_put_bytes_u8(pkt, 0)) {
2750 SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
2755 if (!tls_construct_extensions(s, pkt,
2756 SSL_EXT_TLS1_3_CERTIFICATE_REQUEST, NULL,
2758 /* SSLfatal() already called */
2764 /* get the list of acceptable cert types */
2765 if (!WPACKET_start_sub_packet_u8(pkt)
2766 || !ssl3_get_req_cert_type(s, pkt) || !WPACKET_close(pkt)) {
2767 SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
2771 if (SSL_USE_SIGALGS(s)) {
2772 const uint16_t *psigs;
2773 size_t nl = tls12_get_psigalgs(s, 1, &psigs);
2775 if (!WPACKET_start_sub_packet_u16(pkt)
2776 || !WPACKET_set_flags(pkt, WPACKET_FLAGS_NON_ZERO_LENGTH)
2777 || !tls12_copy_sigalgs(s, pkt, psigs, nl)
2778 || !WPACKET_close(pkt)) {
2779 SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
2784 if (!construct_ca_names(s, get_ca_names(s), pkt)) {
2785 /* SSLfatal() already called */
2791 s->s3.tmp.cert_request = 1;
2795 static int tls_process_cke_psk_preamble(SSL *s, PACKET *pkt)
2797 #ifndef OPENSSL_NO_PSK
2798 unsigned char psk[PSK_MAX_PSK_LEN];
2800 PACKET psk_identity;
2802 if (!PACKET_get_length_prefixed_2(pkt, &psk_identity)) {
2803 SSLfatal(s, SSL_AD_DECODE_ERROR, SSL_R_LENGTH_MISMATCH);
2806 if (PACKET_remaining(&psk_identity) > PSK_MAX_IDENTITY_LEN) {
2807 SSLfatal(s, SSL_AD_DECODE_ERROR, SSL_R_DATA_LENGTH_TOO_LONG);
2810 if (s->psk_server_callback == NULL) {
2811 SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_R_PSK_NO_SERVER_CB);
2815 if (!PACKET_strndup(&psk_identity, &s->session->psk_identity)) {
2816 SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
2820 psklen = s->psk_server_callback(s, s->session->psk_identity,
2823 if (psklen > PSK_MAX_PSK_LEN) {
2824 SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
2826 } else if (psklen == 0) {
2828 * PSK related to the given identity not found
2830 SSLfatal(s, SSL_AD_UNKNOWN_PSK_IDENTITY, SSL_R_PSK_IDENTITY_NOT_FOUND);
2834 OPENSSL_free(s->s3.tmp.psk);
2835 s->s3.tmp.psk = OPENSSL_memdup(psk, psklen);
2836 OPENSSL_cleanse(psk, psklen);
2838 if (s->s3.tmp.psk == NULL) {
2839 s->s3.tmp.psklen = 0;
2840 SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_MALLOC_FAILURE);
2844 s->s3.tmp.psklen = psklen;
2848 /* Should never happen */
2849 SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
2854 static int tls_process_cke_rsa(SSL *s, PACKET *pkt)
2857 PACKET enc_premaster;
2858 EVP_PKEY *rsa = NULL;
2859 unsigned char *rsa_decrypt = NULL;
2861 EVP_PKEY_CTX *ctx = NULL;
2862 OSSL_PARAM params[3], *p = params;
2864 rsa = s->cert->pkeys[SSL_PKEY_RSA].privatekey;
2866 SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_R_MISSING_RSA_CERTIFICATE);
2870 /* SSLv3 and pre-standard DTLS omit the length bytes. */
2871 if (s->version == SSL3_VERSION || s->version == DTLS1_BAD_VER) {
2872 enc_premaster = *pkt;
2874 if (!PACKET_get_length_prefixed_2(pkt, &enc_premaster)
2875 || PACKET_remaining(pkt) != 0) {
2876 SSLfatal(s, SSL_AD_DECODE_ERROR, SSL_R_LENGTH_MISMATCH);
2881 outlen = SSL_MAX_MASTER_KEY_LENGTH;
2882 rsa_decrypt = OPENSSL_malloc(outlen);
2883 if (rsa_decrypt == NULL) {
2884 SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_MALLOC_FAILURE);
2888 ctx = EVP_PKEY_CTX_new_from_pkey(s->ctx->libctx, rsa, s->ctx->propq);
2890 SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_MALLOC_FAILURE);
2895 * We must not leak whether a decryption failure occurs because of
2896 * Bleichenbacher's attack on PKCS #1 v1.5 RSA padding (see RFC 2246,
2897 * section 7.4.7.1). We use the special padding type
2898 * RSA_PKCS1_WITH_TLS_PADDING to do that. It will automaticaly decrypt the
2899 * RSA, check the padding and check that the client version is as expected
2900 * in the premaster secret. If any of that fails then the function appears
2901 * to return successfully but with a random result. The call below could
2902 * still fail if the input is publicly invalid.
2903 * See https://tools.ietf.org/html/rfc5246#section-7.4.7.1
2905 if (EVP_PKEY_decrypt_init(ctx) <= 0
2906 || EVP_PKEY_CTX_set_rsa_padding(ctx, RSA_PKCS1_WITH_TLS_PADDING) <= 0) {
2907 SSLfatal(s, SSL_AD_DECRYPT_ERROR, SSL_R_DECRYPTION_FAILED);
2911 *p++ = OSSL_PARAM_construct_uint(OSSL_ASYM_CIPHER_PARAM_TLS_CLIENT_VERSION,
2912 (unsigned int *)&s->client_version);
2913 if ((s->options & SSL_OP_TLS_ROLLBACK_BUG) != 0)
2914 *p++ = OSSL_PARAM_construct_uint(
2915 OSSL_ASYM_CIPHER_PARAM_TLS_NEGOTIATED_VERSION,
2916 (unsigned int *)&s->version);
2917 *p++ = OSSL_PARAM_construct_end();
2919 if (!EVP_PKEY_CTX_set_params(ctx, params)
2920 || EVP_PKEY_decrypt(ctx, rsa_decrypt, &outlen,
2921 PACKET_data(&enc_premaster),
2922 PACKET_remaining(&enc_premaster)) <= 0) {
2923 SSLfatal(s, SSL_AD_DECRYPT_ERROR, SSL_R_DECRYPTION_FAILED);
2928 * This test should never fail (otherwise we should have failed above) but
2929 * we double check anyway.
2931 if (outlen != SSL_MAX_MASTER_KEY_LENGTH) {
2932 OPENSSL_cleanse(rsa_decrypt, SSL_MAX_MASTER_KEY_LENGTH);
2933 SSLfatal(s, SSL_AD_DECRYPT_ERROR, SSL_R_DECRYPTION_FAILED);
2937 /* Also cleanses rsa_decrypt (on success or failure) */
2938 if (!ssl_generate_master_secret(s, rsa_decrypt,
2939 SSL_MAX_MASTER_KEY_LENGTH, 0)) {
2940 /* SSLfatal() already called */
2946 OPENSSL_free(rsa_decrypt);
2947 EVP_PKEY_CTX_free(ctx);
2951 static int tls_process_cke_dhe(SSL *s, PACKET *pkt)
2953 EVP_PKEY *skey = NULL;
2955 const unsigned char *data;
2956 EVP_PKEY *ckey = NULL;
2959 if (!PACKET_get_net_2(pkt, &i) || PACKET_remaining(pkt) != i) {
2960 SSLfatal(s, SSL_AD_DECODE_ERROR, SSL_R_DH_PUBLIC_VALUE_LENGTH_IS_WRONG);
2963 skey = s->s3.tmp.pkey;
2965 SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_R_MISSING_TMP_DH_KEY);
2969 if (PACKET_remaining(pkt) == 0L) {
2970 SSLfatal(s, SSL_AD_DECODE_ERROR, SSL_R_MISSING_TMP_DH_KEY);
2973 if (!PACKET_get_bytes(pkt, &data, i)) {
2974 /* We already checked we have enough data */
2975 SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
2978 ckey = EVP_PKEY_new();
2979 if (ckey == NULL || EVP_PKEY_copy_parameters(ckey, skey) == 0) {
2980 SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_R_COPY_PARAMETERS_FAILED);
2984 if (!EVP_PKEY_set1_encoded_public_key(ckey, data, i)) {
2985 SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
2989 if (ssl_derive(s, skey, ckey, 1) == 0) {
2990 /* SSLfatal() already called */
2995 EVP_PKEY_free(s->s3.tmp.pkey);
2996 s->s3.tmp.pkey = NULL;
2998 EVP_PKEY_free(ckey);
3002 static int tls_process_cke_ecdhe(SSL *s, PACKET *pkt)
3004 EVP_PKEY *skey = s->s3.tmp.pkey;
3005 EVP_PKEY *ckey = NULL;
3008 if (PACKET_remaining(pkt) == 0L) {
3009 /* We don't support ECDH client auth */
3010 SSLfatal(s, SSL_AD_HANDSHAKE_FAILURE, SSL_R_MISSING_TMP_ECDH_KEY);
3014 const unsigned char *data;
3017 * Get client's public key from encoded point in the
3018 * ClientKeyExchange message.
3021 /* Get encoded point length */
3022 if (!PACKET_get_1(pkt, &i) || !PACKET_get_bytes(pkt, &data, i)
3023 || PACKET_remaining(pkt) != 0) {
3024 SSLfatal(s, SSL_AD_DECODE_ERROR, SSL_R_LENGTH_MISMATCH);
3028 SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_R_MISSING_TMP_ECDH_KEY);
3032 ckey = EVP_PKEY_new();
3033 if (ckey == NULL || EVP_PKEY_copy_parameters(ckey, skey) <= 0) {
3034 SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_R_COPY_PARAMETERS_FAILED);
3038 if (EVP_PKEY_set1_encoded_public_key(ckey, data, i) <= 0) {
3039 SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_EC_LIB);
3044 if (ssl_derive(s, skey, ckey, 1) == 0) {
3045 /* SSLfatal() already called */
3050 EVP_PKEY_free(s->s3.tmp.pkey);
3051 s->s3.tmp.pkey = NULL;
3053 EVP_PKEY_free(ckey);
3058 static int tls_process_cke_srp(SSL *s, PACKET *pkt)
3060 #ifndef OPENSSL_NO_SRP
3062 const unsigned char *data;
3064 if (!PACKET_get_net_2(pkt, &i)
3065 || !PACKET_get_bytes(pkt, &data, i)) {
3066 SSLfatal(s, SSL_AD_DECODE_ERROR, SSL_R_BAD_SRP_A_LENGTH);
3069 if ((s->srp_ctx.A = BN_bin2bn(data, i, NULL)) == NULL) {
3070 SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_BN_LIB);
3073 if (BN_ucmp(s->srp_ctx.A, s->srp_ctx.N) >= 0 || BN_is_zero(s->srp_ctx.A)) {
3074 SSLfatal(s, SSL_AD_ILLEGAL_PARAMETER, SSL_R_BAD_SRP_PARAMETERS);
3077 OPENSSL_free(s->session->srp_username);
3078 s->session->srp_username = OPENSSL_strdup(s->srp_ctx.login);
3079 if (s->session->srp_username == NULL) {
3080 SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_MALLOC_FAILURE);
3084 if (!srp_generate_server_master_secret(s)) {
3085 /* SSLfatal() already called */
3091 /* Should never happen */
3092 SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
3097 static int tls_process_cke_gost(SSL *s, PACKET *pkt)
3099 #ifndef OPENSSL_NO_GOST
3100 EVP_PKEY_CTX *pkey_ctx;
3101 EVP_PKEY *client_pub_pkey = NULL, *pk = NULL;
3102 unsigned char premaster_secret[32];
3103 const unsigned char *start;
3104 size_t outlen = 32, inlen;
3105 unsigned long alg_a;
3106 GOST_KX_MESSAGE *pKX = NULL;
3107 const unsigned char *ptr;
3110 /* Get our certificate private key */
3111 alg_a = s->s3.tmp.new_cipher->algorithm_auth;
3112 if (alg_a & SSL_aGOST12) {
3114 * New GOST ciphersuites have SSL_aGOST01 bit too
3116 pk = s->cert->pkeys[SSL_PKEY_GOST12_512].privatekey;
3118 pk = s->cert->pkeys[SSL_PKEY_GOST12_256].privatekey;
3121 pk = s->cert->pkeys[SSL_PKEY_GOST01].privatekey;
3123 } else if (alg_a & SSL_aGOST01) {
3124 pk = s->cert->pkeys[SSL_PKEY_GOST01].privatekey;
3127 pkey_ctx = EVP_PKEY_CTX_new_from_pkey(s->ctx->libctx, pk, s->ctx->propq);
3128 if (pkey_ctx == NULL) {
3129 SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_MALLOC_FAILURE);
3132 if (EVP_PKEY_decrypt_init(pkey_ctx) <= 0) {
3133 SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
3137 * If client certificate is present and is of the same type, maybe
3138 * use it for key exchange. Don't mind errors from
3139 * EVP_PKEY_derive_set_peer, because it is completely valid to use a
3140 * client certificate for authorization only.
3142 client_pub_pkey = X509_get0_pubkey(s->session->peer);
3143 if (client_pub_pkey) {
3144 if (EVP_PKEY_derive_set_peer(pkey_ctx, client_pub_pkey) <= 0)
3148 ptr = PACKET_data(pkt);
3149 /* Some implementations provide extra data in the opaqueBlob
3150 * We have nothing to do with this blob so we just skip it */
3151 pKX = d2i_GOST_KX_MESSAGE(NULL, &ptr, PACKET_remaining(pkt));
3153 || pKX->kxBlob == NULL
3154 || ASN1_TYPE_get(pKX->kxBlob) != V_ASN1_SEQUENCE) {
3155 SSLfatal(s, SSL_AD_DECODE_ERROR, SSL_R_DECRYPTION_FAILED);
3159 if (!PACKET_forward(pkt, ptr - PACKET_data(pkt))) {
3160 SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_R_DECRYPTION_FAILED);
3164 if (PACKET_remaining(pkt) != 0) {
3165 SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_R_DECRYPTION_FAILED);
3169 inlen = pKX->kxBlob->value.sequence->length;
3170 start = pKX->kxBlob->value.sequence->data;
3172 if (EVP_PKEY_decrypt(pkey_ctx, premaster_secret, &outlen, start,
3174 SSLfatal(s, SSL_AD_DECODE_ERROR, SSL_R_DECRYPTION_FAILED);
3177 /* Generate master secret */
3178 if (!ssl_generate_master_secret(s, premaster_secret,
3179 sizeof(premaster_secret), 0)) {
3180 /* SSLfatal() already called */
3183 /* Check if pubkey from client certificate was used */
3184 if (EVP_PKEY_CTX_ctrl(pkey_ctx, -1, -1, EVP_PKEY_CTRL_PEER_KEY, 2,
3186 s->statem.no_cert_verify = 1;
3190 EVP_PKEY_CTX_free(pkey_ctx);
3191 GOST_KX_MESSAGE_free(pKX);
3194 /* Should never happen */
3195 SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
3200 static int tls_process_cke_gost18(SSL *s, PACKET *pkt)
3202 #ifndef OPENSSL_NO_GOST
3203 unsigned char rnd_dgst[32];
3204 EVP_PKEY_CTX *pkey_ctx = NULL;
3205 EVP_PKEY *pk = NULL;
3206 unsigned char premaster_secret[32];
3207 const unsigned char *start = NULL;
3208 size_t outlen = 32, inlen = 0;
3210 int cipher_nid = ossl_gost18_cke_cipher_nid(s);
3212 if (cipher_nid == NID_undef) {
3213 SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
3217 if (ossl_gost_ukm(s, rnd_dgst) <= 0) {
3218 SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
3222 /* Get our certificate private key */
3223 pk = s->cert->pkeys[SSL_PKEY_GOST12_512].privatekey != NULL ?
3224 s->cert->pkeys[SSL_PKEY_GOST12_512].privatekey :
3225 s->cert->pkeys[SSL_PKEY_GOST12_256].privatekey;
3227 SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_R_BAD_HANDSHAKE_STATE);
3231 pkey_ctx = EVP_PKEY_CTX_new_from_pkey(s->ctx->libctx, pk, s->ctx->propq);
3232 if (pkey_ctx == NULL) {
3233 SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_MALLOC_FAILURE);
3236 if (EVP_PKEY_decrypt_init(pkey_ctx) <= 0) {
3237 SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
3241 /* Reuse EVP_PKEY_CTRL_SET_IV, make choice in engine code depending on size */
3242 if (EVP_PKEY_CTX_ctrl(pkey_ctx, -1, EVP_PKEY_OP_DECRYPT,
3243 EVP_PKEY_CTRL_SET_IV, 32, rnd_dgst) < 0) {
3244 SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_R_LIBRARY_BUG);
3248 if (EVP_PKEY_CTX_ctrl(pkey_ctx, -1, EVP_PKEY_OP_DECRYPT,
3249 EVP_PKEY_CTRL_CIPHER, cipher_nid, NULL) < 0) {
3250 SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_R_LIBRARY_BUG);
3253 inlen = PACKET_remaining(pkt);
3254 start = PACKET_data(pkt);
3256 if (EVP_PKEY_decrypt(pkey_ctx, premaster_secret, &outlen, start, inlen) <= 0) {
3257 SSLfatal(s, SSL_AD_DECODE_ERROR, SSL_R_DECRYPTION_FAILED);
3260 /* Generate master secret */
3261 if (!ssl_generate_master_secret(s, premaster_secret,
3262 sizeof(premaster_secret), 0)) {
3263 /* SSLfatal() already called */
3269 EVP_PKEY_CTX_free(pkey_ctx);
3272 /* Should never happen */
3273 SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
3278 MSG_PROCESS_RETURN tls_process_client_key_exchange(SSL *s, PACKET *pkt)
3280 unsigned long alg_k;
3282 alg_k = s->s3.tmp.new_cipher->algorithm_mkey;
3284 /* For PSK parse and retrieve identity, obtain PSK key */
3285 if ((alg_k & SSL_PSK) && !tls_process_cke_psk_preamble(s, pkt)) {
3286 /* SSLfatal() already called */
3290 if (alg_k & SSL_kPSK) {
3291 /* Identity extracted earlier: should be nothing left */
3292 if (PACKET_remaining(pkt) != 0) {
3293 SSLfatal(s, SSL_AD_DECODE_ERROR, SSL_R_LENGTH_MISMATCH);
3296 /* PSK handled by ssl_generate_master_secret */
3297 if (!ssl_generate_master_secret(s, NULL, 0, 0)) {
3298 /* SSLfatal() already called */
3301 } else if (alg_k & (SSL_kRSA | SSL_kRSAPSK)) {
3302 if (!tls_process_cke_rsa(s, pkt)) {
3303 /* SSLfatal() already called */
3306 } else if (alg_k & (SSL_kDHE | SSL_kDHEPSK)) {
3307 if (!tls_process_cke_dhe(s, pkt)) {
3308 /* SSLfatal() already called */
3311 } else if (alg_k & (SSL_kECDHE | SSL_kECDHEPSK)) {
3312 if (!tls_process_cke_ecdhe(s, pkt)) {
3313 /* SSLfatal() already called */
3316 } else if (alg_k & SSL_kSRP) {
3317 if (!tls_process_cke_srp(s, pkt)) {
3318 /* SSLfatal() already called */
3321 } else if (alg_k & SSL_kGOST) {
3322 if (!tls_process_cke_gost(s, pkt)) {
3323 /* SSLfatal() already called */
3326 } else if (alg_k & SSL_kGOST18) {
3327 if (!tls_process_cke_gost18(s, pkt)) {
3328 /* SSLfatal() already called */
3332 SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_R_UNKNOWN_CIPHER_TYPE);
3336 return MSG_PROCESS_CONTINUE_PROCESSING;
3338 #ifndef OPENSSL_NO_PSK
3339 OPENSSL_clear_free(s->s3.tmp.psk, s->s3.tmp.psklen);
3340 s->s3.tmp.psk = NULL;
3341 s->s3.tmp.psklen = 0;
3343 return MSG_PROCESS_ERROR;
3346 WORK_STATE tls_post_process_client_key_exchange(SSL *s, WORK_STATE wst)
3348 #ifndef OPENSSL_NO_SCTP
3349 if (wst == WORK_MORE_A) {
3350 if (SSL_IS_DTLS(s)) {
3351 unsigned char sctpauthkey[64];
3352 char labelbuffer[sizeof(DTLS1_SCTP_AUTH_LABEL)];
3355 * Add new shared key for SCTP-Auth, will be ignored if no SCTP
3358 memcpy(labelbuffer, DTLS1_SCTP_AUTH_LABEL,
3359 sizeof(DTLS1_SCTP_AUTH_LABEL));
3361 /* Don't include the terminating zero. */
3362 labellen = sizeof(labelbuffer) - 1;
3363 if (s->mode & SSL_MODE_DTLS_SCTP_LABEL_LENGTH_BUG)
3366 if (SSL_export_keying_material(s, sctpauthkey,
3367 sizeof(sctpauthkey), labelbuffer,
3370 SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
3374 BIO_ctrl(SSL_get_wbio(s), BIO_CTRL_DGRAM_SCTP_ADD_AUTH_KEY,
3375 sizeof(sctpauthkey), sctpauthkey);
3380 if (s->statem.no_cert_verify || !s->session->peer) {
3382 * No certificate verify or no peer certificate so we no longer need
3383 * the handshake_buffer
3385 if (!ssl3_digest_cached_records(s, 0)) {
3386 /* SSLfatal() already called */
3389 return WORK_FINISHED_CONTINUE;
3391 if (!s->s3.handshake_buffer) {
3392 SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
3396 * For sigalgs freeze the handshake buffer. If we support
3397 * extms we've done this already so this is a no-op
3399 if (!ssl3_digest_cached_records(s, 1)) {
3400 /* SSLfatal() already called */
3405 return WORK_FINISHED_CONTINUE;
3408 MSG_PROCESS_RETURN tls_process_client_certificate(SSL *s, PACKET *pkt)
3411 MSG_PROCESS_RETURN ret = MSG_PROCESS_ERROR;
3414 const unsigned char *certstart, *certbytes;
3415 STACK_OF(X509) *sk = NULL;
3416 PACKET spkt, context;
3418 SSL_SESSION *new_sess = NULL;
3421 * To get this far we must have read encrypted data from the client. We no
3422 * longer tolerate unencrypted alerts. This value is ignored if less than
3425 s->statem.enc_read_state = ENC_READ_STATE_VALID;
3427 if ((sk = sk_X509_new_null()) == NULL) {
3428 SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_MALLOC_FAILURE);
3432 if (SSL_IS_TLS13(s) && (!PACKET_get_length_prefixed_1(pkt, &context)
3433 || (s->pha_context == NULL && PACKET_remaining(&context) != 0)
3434 || (s->pha_context != NULL &&
3435 !PACKET_equal(&context, s->pha_context, s->pha_context_len)))) {
3436 SSLfatal(s, SSL_AD_DECODE_ERROR, SSL_R_INVALID_CONTEXT);
3440 if (!PACKET_get_length_prefixed_3(pkt, &spkt)
3441 || PACKET_remaining(pkt) != 0) {
3442 SSLfatal(s, SSL_AD_DECODE_ERROR, SSL_R_LENGTH_MISMATCH);
3446 for (chainidx = 0; PACKET_remaining(&spkt) > 0; chainidx++) {
3447 if (!PACKET_get_net_3(&spkt, &l)
3448 || !PACKET_get_bytes(&spkt, &certbytes, l)) {
3449 SSLfatal(s, SSL_AD_DECODE_ERROR, SSL_R_CERT_LENGTH_MISMATCH);
3453 certstart = certbytes;
3454 x = X509_new_ex(s->ctx->libctx, s->ctx->propq);
3456 SSLfatal(s, SSL_AD_DECODE_ERROR, ERR_R_MALLOC_FAILURE);
3459 if (d2i_X509(&x, (const unsigned char **)&certbytes, l) == NULL) {
3460 SSLfatal(s, SSL_AD_DECODE_ERROR, ERR_R_ASN1_LIB);
3464 if (certbytes != (certstart + l)) {
3465 SSLfatal(s, SSL_AD_DECODE_ERROR, SSL_R_CERT_LENGTH_MISMATCH);
3469 if (SSL_IS_TLS13(s)) {
3470 RAW_EXTENSION *rawexts = NULL;
3473 if (!PACKET_get_length_prefixed_2(&spkt, &extensions)) {
3474 SSLfatal(s, SSL_AD_DECODE_ERROR, SSL_R_BAD_LENGTH);
3477 if (!tls_collect_extensions(s, &extensions,
3478 SSL_EXT_TLS1_3_CERTIFICATE, &rawexts,
3479 NULL, chainidx == 0)
3480 || !tls_parse_all_extensions(s, SSL_EXT_TLS1_3_CERTIFICATE,
3481 rawexts, x, chainidx,
3482 PACKET_remaining(&spkt) == 0)) {
3483 OPENSSL_free(rawexts);
3486 OPENSSL_free(rawexts);
3489 if (!sk_X509_push(sk, x)) {
3490 SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_MALLOC_FAILURE);
3496 if (sk_X509_num(sk) <= 0) {
3497 /* TLS does not mind 0 certs returned */
3498 if (s->version == SSL3_VERSION) {
3499 SSLfatal(s, SSL_AD_HANDSHAKE_FAILURE,
3500 SSL_R_NO_CERTIFICATES_RETURNED);
3503 /* Fail for TLS only if we required a certificate */
3504 else if ((s->verify_mode & SSL_VERIFY_PEER) &&
3505 (s->verify_mode & SSL_VERIFY_FAIL_IF_NO_PEER_CERT)) {
3506 SSLfatal(s, SSL_AD_CERTIFICATE_REQUIRED,
3507 SSL_R_PEER_DID_NOT_RETURN_A_CERTIFICATE);
3510 /* No client certificate so digest cached records */
3511 if (s->s3.handshake_buffer && !ssl3_digest_cached_records(s, 0)) {
3512 /* SSLfatal() already called */
3517 i = ssl_verify_cert_chain(s, sk);
3519 SSLfatal(s, ssl_x509err2alert(s->verify_result),
3520 SSL_R_CERTIFICATE_VERIFY_FAILED);
3524 SSLfatal(s, SSL_AD_HANDSHAKE_FAILURE, i);
3527 pkey = X509_get0_pubkey(sk_X509_value(sk, 0));
3529 SSLfatal(s, SSL_AD_HANDSHAKE_FAILURE,
3530 SSL_R_UNKNOWN_CERTIFICATE_TYPE);
3536 * Sessions must be immutable once they go into the session cache. Otherwise
3537 * we can get multi-thread problems. Therefore we don't "update" sessions,
3538 * we replace them with a duplicate. Here, we need to do this every time
3539 * a new certificate is received via post-handshake authentication, as the
3540 * session may have already gone into the session cache.
3543 if (s->post_handshake_auth == SSL_PHA_REQUESTED) {
3544 if ((new_sess = ssl_session_dup(s->session, 0)) == 0) {
3545 SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_MALLOC_FAILURE);
3549 SSL_SESSION_free(s->session);
3550 s->session = new_sess;
3553 X509_free(s->session->peer);
3554 s->session->peer = sk_X509_shift(sk);
3555 s->session->verify_result = s->verify_result;
3557 sk_X509_pop_free(s->session->peer_chain, X509_free);
3558 s->session->peer_chain = sk;
3561 * Freeze the handshake buffer. For <TLS1.3 we do this after the CKE
3564 if (SSL_IS_TLS13(s) && !ssl3_digest_cached_records(s, 1)) {
3565 /* SSLfatal() already called */
3570 * Inconsistency alert: cert_chain does *not* include the peer's own
3571 * certificate, while we do include it in statem_clnt.c
3575 /* Save the current hash state for when we receive the CertificateVerify */
3576 if (SSL_IS_TLS13(s)) {
3577 if (!ssl_handshake_hash(s, s->cert_verify_hash,
3578 sizeof(s->cert_verify_hash),
3579 &s->cert_verify_hash_len)) {
3580 /* SSLfatal() already called */
3584 /* Resend session tickets */
3585 s->sent_tickets = 0;
3588 ret = MSG_PROCESS_CONTINUE_READING;
3592 sk_X509_pop_free(sk, X509_free);
3596 int tls_construct_server_certificate(SSL *s, WPACKET *pkt)
3598 CERT_PKEY *cpk = s->s3.tmp.cert;
3601 SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
3606 * In TLSv1.3 the certificate chain is always preceded by a 0 length context
3607 * for the server Certificate message
3609 if (SSL_IS_TLS13(s) && !WPACKET_put_bytes_u8(pkt, 0)) {
3610 SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
3613 if (!ssl3_output_cert_chain(s, pkt, cpk)) {
3614 /* SSLfatal() already called */
3621 static int create_ticket_prequel(SSL *s, WPACKET *pkt, uint32_t age_add,
3622 unsigned char *tick_nonce)
3625 * Ticket lifetime hint: For TLSv1.2 this is advisory only and we leave this
3626 * unspecified for resumed session (for simplicity).
3627 * In TLSv1.3 we reset the "time" field above, and always specify the
3630 if (!WPACKET_put_bytes_u32(pkt,
3631 (s->hit && !SSL_IS_TLS13(s))
3632 ? 0 : s->session->timeout)) {
3633 SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
3637 if (SSL_IS_TLS13(s)) {
3638 if (!WPACKET_put_bytes_u32(pkt, age_add)
3639 || !WPACKET_sub_memcpy_u8(pkt, tick_nonce, TICKET_NONCE_SIZE)) {
3640 SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
3645 /* Start the sub-packet for the actual ticket data */
3646 if (!WPACKET_start_sub_packet_u16(pkt)) {
3647 SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
3654 static int construct_stateless_ticket(SSL *s, WPACKET *pkt, uint32_t age_add,
3655 unsigned char *tick_nonce)
3657 unsigned char *senc = NULL;
3658 EVP_CIPHER_CTX *ctx = NULL;
3659 SSL_HMAC *hctx = NULL;
3660 unsigned char *p, *encdata1, *encdata2, *macdata1, *macdata2;
3661 const unsigned char *const_p;
3662 int len, slen_full, slen, lenfinal;
3665 SSL_CTX *tctx = s->session_ctx;
3666 unsigned char iv[EVP_MAX_IV_LENGTH];
3667 unsigned char key_name[TLSEXT_KEYNAME_LENGTH];
3669 size_t macoffset, macendoffset;
3671 /* get session encoding length */
3672 slen_full = i2d_SSL_SESSION(s->session, NULL);
3674 * Some length values are 16 bits, so forget it if session is too
3677 if (slen_full == 0 || slen_full > 0xFF00) {
3678 SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
3681 senc = OPENSSL_malloc(slen_full);
3683 SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_MALLOC_FAILURE);
3687 ctx = EVP_CIPHER_CTX_new();
3688 hctx = ssl_hmac_new(tctx);
3689 if (ctx == NULL || hctx == NULL) {
3690 SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_MALLOC_FAILURE);
3695 if (!i2d_SSL_SESSION(s->session, &p)) {
3696 SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
3701 * create a fresh copy (not shared with other threads) to clean up
3704 sess = d2i_SSL_SESSION(NULL, &const_p, slen_full);
3706 SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
3710 slen = i2d_SSL_SESSION(sess, NULL);
3711 if (slen == 0 || slen > slen_full) {
3712 /* shouldn't ever happen */
3713 SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
3714 SSL_SESSION_free(sess);
3718 if (!i2d_SSL_SESSION(sess, &p)) {
3719 SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
3720 SSL_SESSION_free(sess);
3723 SSL_SESSION_free(sess);
3726 * Initialize HMAC and cipher contexts. If callback present it does
3727 * all the work otherwise use generated values from parent ctx.
3729 #ifndef OPENSSL_NO_DEPRECATED_3_0
3730 if (tctx->ext.ticket_key_evp_cb != NULL || tctx->ext.ticket_key_cb != NULL)
3732 if (tctx->ext.ticket_key_evp_cb != NULL)
3737 if (tctx->ext.ticket_key_evp_cb != NULL)
3738 ret = tctx->ext.ticket_key_evp_cb(s, key_name, iv, ctx,
3739 ssl_hmac_get0_EVP_MAC_CTX(hctx),
3741 #ifndef OPENSSL_NO_DEPRECATED_3_0
3742 else if (tctx->ext.ticket_key_cb != NULL)
3743 /* if 0 is returned, write an empty ticket */
3744 ret = tctx->ext.ticket_key_cb(s, key_name, iv, ctx,
3745 ssl_hmac_get0_HMAC_CTX(hctx), 1);
3750 /* Put timeout and length */
3751 if (!WPACKET_put_bytes_u32(pkt, 0)
3752 || !WPACKET_put_bytes_u16(pkt, 0)) {
3753 SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
3757 EVP_CIPHER_CTX_free(ctx);
3758 ssl_hmac_free(hctx);
3762 SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_R_CALLBACK_FAILED);
3765 iv_len = EVP_CIPHER_CTX_iv_length(ctx);
3767 EVP_CIPHER *cipher = EVP_CIPHER_fetch(s->ctx->libctx, "AES-256-CBC",
3770 if (cipher == NULL) {
3771 /* Error is already recorded */
3772 SSLfatal_alert(s, SSL_AD_INTERNAL_ERROR);
3776 iv_len = EVP_CIPHER_iv_length(cipher);
3777 if (RAND_bytes_ex(s->ctx->libctx, iv, iv_len) <= 0
3778 || !EVP_EncryptInit_ex(ctx, cipher, NULL,
3779 tctx->ext.secure->tick_aes_key, iv)
3780 || !ssl_hmac_init(hctx, tctx->ext.secure->tick_hmac_key,
3781 sizeof(tctx->ext.secure->tick_hmac_key),
3783 EVP_CIPHER_free(cipher);
3784 SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
3787 EVP_CIPHER_free(cipher);
3788 memcpy(key_name, tctx->ext.tick_key_name,
3789 sizeof(tctx->ext.tick_key_name));
3792 if (!create_ticket_prequel(s, pkt, age_add, tick_nonce)) {
3793 /* SSLfatal() already called */
3797 if (!WPACKET_get_total_written(pkt, &macoffset)
3798 /* Output key name */
3799 || !WPACKET_memcpy(pkt, key_name, sizeof(key_name))
3801 || !WPACKET_memcpy(pkt, iv, iv_len)
3802 || !WPACKET_reserve_bytes(pkt, slen + EVP_MAX_BLOCK_LENGTH,
3804 /* Encrypt session data */
3805 || !EVP_EncryptUpdate(ctx, encdata1, &len, senc, slen)
3806 || !WPACKET_allocate_bytes(pkt, len, &encdata2)
3807 || encdata1 != encdata2
3808 || !EVP_EncryptFinal(ctx, encdata1 + len, &lenfinal)
3809 || !WPACKET_allocate_bytes(pkt, lenfinal, &encdata2)
3810 || encdata1 + len != encdata2
3811 || len + lenfinal > slen + EVP_MAX_BLOCK_LENGTH
3812 || !WPACKET_get_total_written(pkt, &macendoffset)
3813 || !ssl_hmac_update(hctx,
3814 (unsigned char *)s->init_buf->data + macoffset,
3815 macendoffset - macoffset)
3816 || !WPACKET_reserve_bytes(pkt, EVP_MAX_MD_SIZE, &macdata1)
3817 || !ssl_hmac_final(hctx, macdata1, &hlen, EVP_MAX_MD_SIZE)
3818 || hlen > EVP_MAX_MD_SIZE
3819 || !WPACKET_allocate_bytes(pkt, hlen, &macdata2)
3820 || macdata1 != macdata2) {
3821 SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
3825 /* Close the sub-packet created by create_ticket_prequel() */
3826 if (!WPACKET_close(pkt)) {
3827 SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
3834 EVP_CIPHER_CTX_free(ctx);
3835 ssl_hmac_free(hctx);
3839 static int construct_stateful_ticket(SSL *s, WPACKET *pkt, uint32_t age_add,
3840 unsigned char *tick_nonce)
3842 if (!create_ticket_prequel(s, pkt, age_add, tick_nonce)) {
3843 /* SSLfatal() already called */
3847 if (!WPACKET_memcpy(pkt, s->session->session_id,
3848 s->session->session_id_length)
3849 || !WPACKET_close(pkt)) {
3850 SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
3857 int tls_construct_new_session_ticket(SSL *s, WPACKET *pkt)
3859 SSL_CTX *tctx = s->session_ctx;
3860 unsigned char tick_nonce[TICKET_NONCE_SIZE];
3862 unsigned char age_add_c[sizeof(uint32_t)];
3866 age_add_u.age_add = 0;
3868 if (SSL_IS_TLS13(s)) {
3871 static const unsigned char nonce_label[] = "resumption";
3872 const EVP_MD *md = ssl_handshake_md(s);
3873 int hashleni = EVP_MD_size(md);
3875 /* Ensure cast to size_t is safe */
3876 if (!ossl_assert(hashleni >= 0)) {
3877 SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
3880 hashlen = (size_t)hashleni;
3883 * If we already sent one NewSessionTicket, or we resumed then
3884 * s->session may already be in a cache and so we must not modify it.
3885 * Instead we need to take a copy of it and modify that.
3887 if (s->sent_tickets != 0 || s->hit) {
3888 SSL_SESSION *new_sess = ssl_session_dup(s->session, 0);
3890 if (new_sess == NULL) {
3891 /* SSLfatal already called */
3895 SSL_SESSION_free(s->session);
3896 s->session = new_sess;
3899 if (!ssl_generate_session_id(s, s->session)) {
3900 /* SSLfatal() already called */
3903 if (RAND_bytes_ex(s->ctx->libctx, age_add_u.age_add_c,
3904 sizeof(age_add_u)) <= 0) {
3905 SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
3908 s->session->ext.tick_age_add = age_add_u.age_add;
3910 nonce = s->next_ticket_nonce;
3911 for (i = TICKET_NONCE_SIZE; i > 0; i--) {
3912 tick_nonce[i - 1] = (unsigned char)(nonce & 0xff);
3916 if (!tls13_hkdf_expand(s, md, s->resumption_master_secret,
3918 sizeof(nonce_label) - 1,
3921 s->session->master_key,
3923 /* SSLfatal() already called */
3926 s->session->master_key_length = hashlen;
3928 s->session->time = (long)time(NULL);
3929 if (s->s3.alpn_selected != NULL) {
3930 OPENSSL_free(s->session->ext.alpn_selected);
3931 s->session->ext.alpn_selected =
3932 OPENSSL_memdup(s->s3.alpn_selected, s->s3.alpn_selected_len);
3933 if (s->session->ext.alpn_selected == NULL) {
3934 s->session->ext.alpn_selected_len = 0;
3935 SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_MALLOC_FAILURE);
3938 s->session->ext.alpn_selected_len = s->s3.alpn_selected_len;
3940 s->session->ext.max_early_data = s->max_early_data;
3943 if (tctx->generate_ticket_cb != NULL &&
3944 tctx->generate_ticket_cb(s, tctx->ticket_cb_data) == 0)
3948 * If we are using anti-replay protection then we behave as if
3949 * SSL_OP_NO_TICKET is set - we are caching tickets anyway so there
3950 * is no point in using full stateless tickets.
3953 && ((s->options & SSL_OP_NO_TICKET) != 0
3954 || (s->max_early_data > 0
3955 && (s->options & SSL_OP_NO_ANTI_REPLAY) == 0))) {
3956 if (!construct_stateful_ticket(s, pkt, age_add_u.age_add, tick_nonce)) {
3957 /* SSLfatal() already called */
3960 } else if (!construct_stateless_ticket(s, pkt, age_add_u.age_add,
3962 /* SSLfatal() already called */
3966 if (SSL_IS_TLS13(s)) {
3967 if (!tls_construct_extensions(s, pkt,
3968 SSL_EXT_TLS1_3_NEW_SESSION_TICKET,
3970 /* SSLfatal() already called */
3974 * Increment both |sent_tickets| and |next_ticket_nonce|. |sent_tickets|
3975 * gets reset to 0 if we send more tickets following a post-handshake
3976 * auth, but |next_ticket_nonce| does not. If we're sending extra
3977 * tickets, decrement the count of pending extra tickets.
3980 s->next_ticket_nonce++;
3981 if (s->ext.extra_tickets_expected > 0)
3982 s->ext.extra_tickets_expected--;
3983 ssl_update_cache(s, SSL_SESS_CACHE_SERVER);
3992 * In TLSv1.3 this is called from the extensions code, otherwise it is used to
3993 * create a separate message. Returns 1 on success or 0 on failure.
3995 int tls_construct_cert_status_body(SSL *s, WPACKET *pkt)
3997 if (!WPACKET_put_bytes_u8(pkt, s->ext.status_type)
3998 || !WPACKET_sub_memcpy_u24(pkt, s->ext.ocsp.resp,
3999 s->ext.ocsp.resp_len)) {
4000 SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
4007 int tls_construct_cert_status(SSL *s, WPACKET *pkt)
4009 if (!tls_construct_cert_status_body(s, pkt)) {
4010 /* SSLfatal() already called */
4017 #ifndef OPENSSL_NO_NEXTPROTONEG
4019 * tls_process_next_proto reads a Next Protocol Negotiation handshake message.
4020 * It sets the next_proto member in s if found
4022 MSG_PROCESS_RETURN tls_process_next_proto(SSL *s, PACKET *pkt)
4024 PACKET next_proto, padding;
4025 size_t next_proto_len;
4028 * The payload looks like:
4030 * uint8 proto[proto_len];
4031 * uint8 padding_len;
4032 * uint8 padding[padding_len];
4034 if (!PACKET_get_length_prefixed_1(pkt, &next_proto)
4035 || !PACKET_get_length_prefixed_1(pkt, &padding)
4036 || PACKET_remaining(pkt) > 0) {
4037 SSLfatal(s, SSL_AD_DECODE_ERROR, SSL_R_LENGTH_MISMATCH);
4038 return MSG_PROCESS_ERROR;
4041 if (!PACKET_memdup(&next_proto, &s->ext.npn, &next_proto_len)) {
4043 SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
4044 return MSG_PROCESS_ERROR;
4047 s->ext.npn_len = (unsigned char)next_proto_len;
4049 return MSG_PROCESS_CONTINUE_READING;
4053 static int tls_construct_encrypted_extensions(SSL *s, WPACKET *pkt)
4055 if (!tls_construct_extensions(s, pkt, SSL_EXT_TLS1_3_ENCRYPTED_EXTENSIONS,
4057 /* SSLfatal() already called */
4064 MSG_PROCESS_RETURN tls_process_end_of_early_data(SSL *s, PACKET *pkt)
4066 if (PACKET_remaining(pkt) != 0) {
4067 SSLfatal(s, SSL_AD_DECODE_ERROR, SSL_R_LENGTH_MISMATCH);
4068 return MSG_PROCESS_ERROR;
4071 if (s->early_data_state != SSL_EARLY_DATA_READING
4072 && s->early_data_state != SSL_EARLY_DATA_READ_RETRY) {
4073 SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
4074 return MSG_PROCESS_ERROR;
4078 * EndOfEarlyData signals a key change so the end of the message must be on
4079 * a record boundary.
4081 if (RECORD_LAYER_processed_read_pending(&s->rlayer)) {
4082 SSLfatal(s, SSL_AD_UNEXPECTED_MESSAGE, SSL_R_NOT_ON_RECORD_BOUNDARY);
4083 return MSG_PROCESS_ERROR;
4086 s->early_data_state = SSL_EARLY_DATA_FINISHED_READING;
4087 if (!s->method->ssl3_enc->change_cipher_state(s,
4088 SSL3_CC_HANDSHAKE | SSL3_CHANGE_CIPHER_SERVER_READ)) {
4089 /* SSLfatal() already called */
4090 return MSG_PROCESS_ERROR;
4093 return MSG_PROCESS_CONTINUE_READING;