2 * Copyright 1995-2018 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 OpenSSL license (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_locl.h"
14 #include "statem_locl.h"
15 #include "internal/constant_time_locl.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/hmac.h>
22 #include <openssl/x509.h>
23 #include <openssl/dh.h>
24 #include <openssl/bn.h>
25 #include <openssl/md5.h>
27 static int tls_construct_encrypted_extensions(SSL *s, WPACKET *pkt);
30 * ossl_statem_server13_read_transition() encapsulates the logic for the allowed
31 * handshake state transitions when a TLSv1.3 server is reading messages from
32 * the client. The message type that the client has sent is provided in |mt|.
33 * The current state is in |s->statem.hand_state|.
35 * Return values are 1 for success (transition allowed) and 0 on error
36 * (transition not allowed)
38 static int ossl_statem_server13_read_transition(SSL *s, int mt)
40 OSSL_STATEM *st = &s->statem;
43 * Note: There is no case for TLS_ST_BEFORE because at that stage we have
44 * not negotiated TLSv1.3 yet, so that case is handled by
45 * ossl_statem_server_read_transition()
47 switch (st->hand_state) {
51 case TLS_ST_EARLY_DATA:
52 if (s->hello_retry_request == SSL_HRR_PENDING) {
53 if (mt == SSL3_MT_CLIENT_HELLO) {
54 st->hand_state = TLS_ST_SR_CLNT_HELLO;
58 } else if (s->ext.early_data == SSL_EARLY_DATA_ACCEPTED) {
59 if (mt == SSL3_MT_END_OF_EARLY_DATA) {
60 st->hand_state = TLS_ST_SR_END_OF_EARLY_DATA;
67 case TLS_ST_SR_END_OF_EARLY_DATA:
68 case TLS_ST_SW_FINISHED:
69 if (s->s3->tmp.cert_request) {
70 if (mt == SSL3_MT_CERTIFICATE) {
71 st->hand_state = TLS_ST_SR_CERT;
75 if (mt == SSL3_MT_FINISHED) {
76 st->hand_state = TLS_ST_SR_FINISHED;
83 if (s->session->peer == NULL) {
84 if (mt == SSL3_MT_FINISHED) {
85 st->hand_state = TLS_ST_SR_FINISHED;
89 if (mt == SSL3_MT_CERTIFICATE_VERIFY) {
90 st->hand_state = TLS_ST_SR_CERT_VRFY;
96 case TLS_ST_SR_CERT_VRFY:
97 if (mt == SSL3_MT_FINISHED) {
98 st->hand_state = TLS_ST_SR_FINISHED;
105 * Its never ok to start processing handshake messages in the middle of
106 * early data (i.e. before we've received the end of early data alert)
108 if (s->early_data_state == SSL_EARLY_DATA_READING)
111 if (mt == SSL3_MT_CERTIFICATE
112 && s->post_handshake_auth == SSL_PHA_REQUESTED) {
113 st->hand_state = TLS_ST_SR_CERT;
117 if (mt == SSL3_MT_KEY_UPDATE) {
118 st->hand_state = TLS_ST_SR_KEY_UPDATE;
124 /* No valid transition found */
129 * ossl_statem_server_read_transition() encapsulates the logic for the allowed
130 * handshake state transitions when the server is reading messages from the
131 * client. The message type that the client has sent is provided in |mt|. The
132 * current state is in |s->statem.hand_state|.
134 * Return values are 1 for success (transition allowed) and 0 on error
135 * (transition not allowed)
137 int ossl_statem_server_read_transition(SSL *s, int mt)
139 OSSL_STATEM *st = &s->statem;
141 if (SSL_IS_TLS13(s)) {
142 if (!ossl_statem_server13_read_transition(s, mt))
147 switch (st->hand_state) {
153 case DTLS_ST_SW_HELLO_VERIFY_REQUEST:
154 if (mt == SSL3_MT_CLIENT_HELLO) {
155 st->hand_state = TLS_ST_SR_CLNT_HELLO;
160 case TLS_ST_SW_SRVR_DONE:
162 * If we get a CKE message after a ServerDone then either
163 * 1) We didn't request a Certificate
165 * 2) If we did request one then
166 * a) We allow no Certificate to be returned
168 * b) We are running SSL3 (in TLS1.0+ the client must return a 0
169 * list if we requested a certificate)
171 if (mt == SSL3_MT_CLIENT_KEY_EXCHANGE) {
172 if (s->s3->tmp.cert_request) {
173 if (s->version == SSL3_VERSION) {
174 if ((s->verify_mode & SSL_VERIFY_PEER)
175 && (s->verify_mode & SSL_VERIFY_FAIL_IF_NO_PEER_CERT)) {
177 * This isn't an unexpected message as such - we're just
178 * not going to accept it because we require a client
181 SSLfatal(s, SSL_AD_HANDSHAKE_FAILURE,
182 SSL_F_OSSL_STATEM_SERVER_READ_TRANSITION,
183 SSL_R_PEER_DID_NOT_RETURN_A_CERTIFICATE);
186 st->hand_state = TLS_ST_SR_KEY_EXCH;
190 st->hand_state = TLS_ST_SR_KEY_EXCH;
193 } else if (s->s3->tmp.cert_request) {
194 if (mt == SSL3_MT_CERTIFICATE) {
195 st->hand_state = TLS_ST_SR_CERT;
202 if (mt == SSL3_MT_CLIENT_KEY_EXCHANGE) {
203 st->hand_state = TLS_ST_SR_KEY_EXCH;
208 case TLS_ST_SR_KEY_EXCH:
210 * We should only process a CertificateVerify message if we have
211 * received a Certificate from the client. If so then |s->session->peer|
212 * will be non NULL. In some instances a CertificateVerify message is
213 * not required even if the peer has sent a Certificate (e.g. such as in
214 * the case of static DH). In that case |st->no_cert_verify| should be
217 if (s->session->peer == NULL || st->no_cert_verify) {
218 if (mt == SSL3_MT_CHANGE_CIPHER_SPEC) {
220 * For the ECDH ciphersuites when the client sends its ECDH
221 * pub key in a certificate, the CertificateVerify message is
222 * not sent. Also for GOST ciphersuites when the client uses
223 * its key from the certificate for key exchange.
225 st->hand_state = TLS_ST_SR_CHANGE;
229 if (mt == SSL3_MT_CERTIFICATE_VERIFY) {
230 st->hand_state = TLS_ST_SR_CERT_VRFY;
236 case TLS_ST_SR_CERT_VRFY:
237 if (mt == SSL3_MT_CHANGE_CIPHER_SPEC) {
238 st->hand_state = TLS_ST_SR_CHANGE;
243 case TLS_ST_SR_CHANGE:
244 #ifndef OPENSSL_NO_NEXTPROTONEG
245 if (s->s3->npn_seen) {
246 if (mt == SSL3_MT_NEXT_PROTO) {
247 st->hand_state = TLS_ST_SR_NEXT_PROTO;
252 if (mt == SSL3_MT_FINISHED) {
253 st->hand_state = TLS_ST_SR_FINISHED;
256 #ifndef OPENSSL_NO_NEXTPROTONEG
261 #ifndef OPENSSL_NO_NEXTPROTONEG
262 case TLS_ST_SR_NEXT_PROTO:
263 if (mt == SSL3_MT_FINISHED) {
264 st->hand_state = TLS_ST_SR_FINISHED;
270 case TLS_ST_SW_FINISHED:
271 if (mt == SSL3_MT_CHANGE_CIPHER_SPEC) {
272 st->hand_state = TLS_ST_SR_CHANGE;
279 /* No valid transition found */
280 if (SSL_IS_DTLS(s) && mt == SSL3_MT_CHANGE_CIPHER_SPEC) {
284 * CCS messages don't have a message sequence number so this is probably
285 * because of an out-of-order CCS. We'll just drop it.
288 s->rwstate = SSL_READING;
289 rbio = SSL_get_rbio(s);
290 BIO_clear_retry_flags(rbio);
291 BIO_set_retry_read(rbio);
294 SSLfatal(s, SSL3_AD_UNEXPECTED_MESSAGE,
295 SSL_F_OSSL_STATEM_SERVER_READ_TRANSITION,
296 SSL_R_UNEXPECTED_MESSAGE);
301 * Should we send a ServerKeyExchange message?
303 * Valid return values are:
307 static int send_server_key_exchange(SSL *s)
309 unsigned long alg_k = s->s3->tmp.new_cipher->algorithm_mkey;
312 * only send a ServerKeyExchange if DH or fortezza but we have a
313 * sign only certificate PSK: may send PSK identity hints For
314 * ECC ciphersuites, we send a serverKeyExchange message only if
315 * the cipher suite is either ECDH-anon or ECDHE. In other cases,
316 * the server certificate contains the server's public key for
319 if (alg_k & (SSL_kDHE | SSL_kECDHE)
321 * PSK: send ServerKeyExchange if PSK identity hint if
324 #ifndef OPENSSL_NO_PSK
325 /* Only send SKE if we have identity hint for plain PSK */
326 || ((alg_k & (SSL_kPSK | SSL_kRSAPSK))
327 && s->cert->psk_identity_hint)
328 /* For other PSK always send SKE */
329 || (alg_k & (SSL_PSK & (SSL_kDHEPSK | SSL_kECDHEPSK)))
331 #ifndef OPENSSL_NO_SRP
332 /* SRP: send ServerKeyExchange */
333 || (alg_k & SSL_kSRP)
343 * Should we send a CertificateRequest message?
345 * Valid return values are:
349 int send_certificate_request(SSL *s)
352 /* don't request cert unless asked for it: */
353 s->verify_mode & SSL_VERIFY_PEER
355 * don't request if post-handshake-only unless doing
356 * post-handshake in TLSv1.3:
358 && (!SSL_IS_TLS13(s) || !(s->verify_mode & SSL_VERIFY_POST_HANDSHAKE)
359 || s->post_handshake_auth == SSL_PHA_REQUEST_PENDING)
361 * if SSL_VERIFY_CLIENT_ONCE is set, don't request cert
364 && (s->certreqs_sent < 1 ||
365 !(s->verify_mode & SSL_VERIFY_CLIENT_ONCE))
367 * never request cert in anonymous ciphersuites (see
368 * section "Certificate request" in SSL 3 drafts and in
371 && (!(s->s3->tmp.new_cipher->algorithm_auth & SSL_aNULL)
373 * ... except when the application insists on
374 * verification (against the specs, but statem_clnt.c accepts
377 || (s->verify_mode & SSL_VERIFY_FAIL_IF_NO_PEER_CERT))
378 /* don't request certificate for SRP auth */
379 && !(s->s3->tmp.new_cipher->algorithm_auth & SSL_aSRP)
381 * With normal PSK Certificates and Certificate Requests
384 && !(s->s3->tmp.new_cipher->algorithm_auth & SSL_aPSK)) {
392 * ossl_statem_server13_write_transition() works out what handshake state to
393 * move to next when a TLSv1.3 server is writing messages to be sent to the
396 static WRITE_TRAN ossl_statem_server13_write_transition(SSL *s)
398 OSSL_STATEM *st = &s->statem;
401 * No case for TLS_ST_BEFORE, because at that stage we have not negotiated
402 * TLSv1.3 yet, so that is handled by ossl_statem_server_write_transition()
405 switch (st->hand_state) {
407 /* Shouldn't happen */
408 SSLfatal(s, SSL_AD_INTERNAL_ERROR,
409 SSL_F_OSSL_STATEM_SERVER13_WRITE_TRANSITION,
410 ERR_R_INTERNAL_ERROR);
411 return WRITE_TRAN_ERROR;
414 if (s->key_update != SSL_KEY_UPDATE_NONE) {
415 st->hand_state = TLS_ST_SW_KEY_UPDATE;
416 return WRITE_TRAN_CONTINUE;
418 if (s->post_handshake_auth == SSL_PHA_REQUEST_PENDING) {
419 st->hand_state = TLS_ST_SW_CERT_REQ;
420 return WRITE_TRAN_CONTINUE;
422 /* Try to read from the client instead */
423 return WRITE_TRAN_FINISHED;
425 case TLS_ST_SR_CLNT_HELLO:
426 st->hand_state = TLS_ST_SW_SRVR_HELLO;
427 return WRITE_TRAN_CONTINUE;
429 case TLS_ST_SW_SRVR_HELLO:
430 if ((s->options & SSL_OP_ENABLE_MIDDLEBOX_COMPAT) != 0
431 && s->hello_retry_request != SSL_HRR_COMPLETE)
432 st->hand_state = TLS_ST_SW_CHANGE;
433 else if (s->hello_retry_request == SSL_HRR_PENDING)
434 st->hand_state = TLS_ST_EARLY_DATA;
436 st->hand_state = TLS_ST_SW_ENCRYPTED_EXTENSIONS;
437 return WRITE_TRAN_CONTINUE;
439 case TLS_ST_SW_CHANGE:
440 if (s->hello_retry_request == SSL_HRR_PENDING)
441 st->hand_state = TLS_ST_EARLY_DATA;
443 st->hand_state = TLS_ST_SW_ENCRYPTED_EXTENSIONS;
444 return WRITE_TRAN_CONTINUE;
446 case TLS_ST_SW_ENCRYPTED_EXTENSIONS:
448 st->hand_state = TLS_ST_SW_FINISHED;
449 else if (send_certificate_request(s))
450 st->hand_state = TLS_ST_SW_CERT_REQ;
452 st->hand_state = TLS_ST_SW_CERT;
454 return WRITE_TRAN_CONTINUE;
456 case TLS_ST_SW_CERT_REQ:
457 if (s->post_handshake_auth == SSL_PHA_REQUEST_PENDING) {
458 s->post_handshake_auth = SSL_PHA_REQUESTED;
459 st->hand_state = TLS_ST_OK;
461 st->hand_state = TLS_ST_SW_CERT;
463 return WRITE_TRAN_CONTINUE;
466 st->hand_state = TLS_ST_SW_CERT_VRFY;
467 return WRITE_TRAN_CONTINUE;
469 case TLS_ST_SW_CERT_VRFY:
470 st->hand_state = TLS_ST_SW_FINISHED;
471 return WRITE_TRAN_CONTINUE;
473 case TLS_ST_SW_FINISHED:
474 st->hand_state = TLS_ST_EARLY_DATA;
475 return WRITE_TRAN_CONTINUE;
477 case TLS_ST_EARLY_DATA:
478 return WRITE_TRAN_FINISHED;
480 case TLS_ST_SR_FINISHED:
482 * Technically we have finished the handshake at this point, but we're
483 * going to remain "in_init" for now and write out any session tickets
486 if (s->post_handshake_auth == SSL_PHA_REQUESTED) {
487 s->post_handshake_auth = SSL_PHA_EXT_RECEIVED;
488 } else if (!s->ext.ticket_expected) {
490 * If we're not going to renew the ticket then we just finish the
491 * handshake at this point.
493 st->hand_state = TLS_ST_OK;
494 return WRITE_TRAN_CONTINUE;
496 if (s->num_tickets > s->sent_tickets)
497 st->hand_state = TLS_ST_SW_SESSION_TICKET;
499 st->hand_state = TLS_ST_OK;
500 return WRITE_TRAN_CONTINUE;
502 case TLS_ST_SR_KEY_UPDATE:
503 if (s->key_update != SSL_KEY_UPDATE_NONE) {
504 st->hand_state = TLS_ST_SW_KEY_UPDATE;
505 return WRITE_TRAN_CONTINUE;
509 case TLS_ST_SW_KEY_UPDATE:
510 case TLS_ST_SW_SESSION_TICKET:
511 /* In a resumption we only ever send a maximum of one new ticket.
512 * Following an initial handshake we send the number of tickets we have
513 * been configured for.
515 if (s->hit || s->num_tickets <= s->sent_tickets) {
516 /* We've written enough tickets out. */
517 st->hand_state = TLS_ST_OK;
519 return WRITE_TRAN_CONTINUE;
524 * ossl_statem_server_write_transition() works out what handshake state to move
525 * to next when the server is writing messages to be sent to the client.
527 WRITE_TRAN ossl_statem_server_write_transition(SSL *s)
529 OSSL_STATEM *st = &s->statem;
532 * Note that before the ClientHello we don't know what version we are going
533 * to negotiate yet, so we don't take this branch until later
537 return ossl_statem_server13_write_transition(s);
539 switch (st->hand_state) {
541 /* Shouldn't happen */
542 SSLfatal(s, SSL_AD_INTERNAL_ERROR,
543 SSL_F_OSSL_STATEM_SERVER_WRITE_TRANSITION,
544 ERR_R_INTERNAL_ERROR);
545 return WRITE_TRAN_ERROR;
548 if (st->request_state == TLS_ST_SW_HELLO_REQ) {
549 /* We must be trying to renegotiate */
550 st->hand_state = TLS_ST_SW_HELLO_REQ;
551 st->request_state = TLS_ST_BEFORE;
552 return WRITE_TRAN_CONTINUE;
554 /* Must be an incoming ClientHello */
555 if (!tls_setup_handshake(s)) {
556 /* SSLfatal() already called */
557 return WRITE_TRAN_ERROR;
562 /* Just go straight to trying to read from the client */
563 return WRITE_TRAN_FINISHED;
565 case TLS_ST_SW_HELLO_REQ:
566 st->hand_state = TLS_ST_OK;
567 return WRITE_TRAN_CONTINUE;
569 case TLS_ST_SR_CLNT_HELLO:
570 if (SSL_IS_DTLS(s) && !s->d1->cookie_verified
571 && (SSL_get_options(s) & SSL_OP_COOKIE_EXCHANGE)) {
572 st->hand_state = DTLS_ST_SW_HELLO_VERIFY_REQUEST;
573 } else if (s->renegotiate == 0 && !SSL_IS_FIRST_HANDSHAKE(s)) {
574 /* We must have rejected the renegotiation */
575 st->hand_state = TLS_ST_OK;
576 return WRITE_TRAN_CONTINUE;
578 st->hand_state = TLS_ST_SW_SRVR_HELLO;
580 return WRITE_TRAN_CONTINUE;
582 case DTLS_ST_SW_HELLO_VERIFY_REQUEST:
583 return WRITE_TRAN_FINISHED;
585 case TLS_ST_SW_SRVR_HELLO:
587 if (s->ext.ticket_expected)
588 st->hand_state = TLS_ST_SW_SESSION_TICKET;
590 st->hand_state = TLS_ST_SW_CHANGE;
592 /* Check if it is anon DH or anon ECDH, */
593 /* normal PSK or SRP */
594 if (!(s->s3->tmp.new_cipher->algorithm_auth &
595 (SSL_aNULL | SSL_aSRP | SSL_aPSK))) {
596 st->hand_state = TLS_ST_SW_CERT;
597 } else if (send_server_key_exchange(s)) {
598 st->hand_state = TLS_ST_SW_KEY_EXCH;
599 } else if (send_certificate_request(s)) {
600 st->hand_state = TLS_ST_SW_CERT_REQ;
602 st->hand_state = TLS_ST_SW_SRVR_DONE;
605 return WRITE_TRAN_CONTINUE;
608 if (s->ext.status_expected) {
609 st->hand_state = TLS_ST_SW_CERT_STATUS;
610 return WRITE_TRAN_CONTINUE;
614 case TLS_ST_SW_CERT_STATUS:
615 if (send_server_key_exchange(s)) {
616 st->hand_state = TLS_ST_SW_KEY_EXCH;
617 return WRITE_TRAN_CONTINUE;
621 case TLS_ST_SW_KEY_EXCH:
622 if (send_certificate_request(s)) {
623 st->hand_state = TLS_ST_SW_CERT_REQ;
624 return WRITE_TRAN_CONTINUE;
628 case TLS_ST_SW_CERT_REQ:
629 st->hand_state = TLS_ST_SW_SRVR_DONE;
630 return WRITE_TRAN_CONTINUE;
632 case TLS_ST_SW_SRVR_DONE:
633 return WRITE_TRAN_FINISHED;
635 case TLS_ST_SR_FINISHED:
637 st->hand_state = TLS_ST_OK;
638 return WRITE_TRAN_CONTINUE;
639 } else if (s->ext.ticket_expected) {
640 st->hand_state = TLS_ST_SW_SESSION_TICKET;
642 st->hand_state = TLS_ST_SW_CHANGE;
644 return WRITE_TRAN_CONTINUE;
646 case TLS_ST_SW_SESSION_TICKET:
647 st->hand_state = TLS_ST_SW_CHANGE;
648 return WRITE_TRAN_CONTINUE;
650 case TLS_ST_SW_CHANGE:
651 st->hand_state = TLS_ST_SW_FINISHED;
652 return WRITE_TRAN_CONTINUE;
654 case TLS_ST_SW_FINISHED:
656 return WRITE_TRAN_FINISHED;
658 st->hand_state = TLS_ST_OK;
659 return WRITE_TRAN_CONTINUE;
664 * Perform any pre work that needs to be done prior to sending a message from
665 * the server to the client.
667 WORK_STATE ossl_statem_server_pre_work(SSL *s, WORK_STATE wst)
669 OSSL_STATEM *st = &s->statem;
671 switch (st->hand_state) {
673 /* No pre work to be done */
676 case TLS_ST_SW_HELLO_REQ:
679 dtls1_clear_sent_buffer(s);
682 case DTLS_ST_SW_HELLO_VERIFY_REQUEST:
684 if (SSL_IS_DTLS(s)) {
685 dtls1_clear_sent_buffer(s);
686 /* We don't buffer this message so don't use the timer */
691 case TLS_ST_SW_SRVR_HELLO:
692 if (SSL_IS_DTLS(s)) {
694 * Messages we write from now on should be buffered and
695 * retransmitted if necessary, so we need to use the timer now
701 case TLS_ST_SW_SRVR_DONE:
702 #ifndef OPENSSL_NO_SCTP
703 if (SSL_IS_DTLS(s) && BIO_dgram_is_sctp(SSL_get_wbio(s))) {
704 /* Calls SSLfatal() as required */
705 return dtls_wait_for_dry(s);
708 return WORK_FINISHED_CONTINUE;
710 case TLS_ST_SW_SESSION_TICKET:
711 if (SSL_IS_TLS13(s)) {
713 * Actually this is the end of the handshake, but we're going
714 * straight into writing the session ticket out. So we finish off
715 * the handshake, but keep the various buffers active.
717 * Calls SSLfatal as required.
719 return tls_finish_handshake(s, wst, 0, 0);
720 } if (SSL_IS_DTLS(s)) {
722 * We're into the last flight. We don't retransmit the last flight
723 * unless we need to, so we don't use the timer
729 case TLS_ST_SW_CHANGE:
732 s->session->cipher = s->s3->tmp.new_cipher;
733 if (!s->method->ssl3_enc->setup_key_block(s)) {
734 /* SSLfatal() already called */
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. This might have
741 * already been set to 0 if we sent a NewSessionTicket message,
742 * but we'll set it again here in case we didn't.
746 return WORK_FINISHED_CONTINUE;
748 case TLS_ST_EARLY_DATA:
749 if (s->early_data_state != SSL_EARLY_DATA_ACCEPTING
750 && (s->s3->flags & TLS1_FLAGS_STATELESS) == 0)
751 return WORK_FINISHED_CONTINUE;
755 /* Calls SSLfatal() as required */
756 return tls_finish_handshake(s, wst, 1, 1);
759 return WORK_FINISHED_CONTINUE;
763 * Perform any work that needs to be done after sending a message from the
764 * server to the client.
766 WORK_STATE ossl_statem_server_post_work(SSL *s, WORK_STATE wst)
768 OSSL_STATEM *st = &s->statem;
772 switch (st->hand_state) {
774 /* No post work to be done */
777 case TLS_ST_SW_HELLO_REQ:
778 if (statem_flush(s) != 1)
780 if (!ssl3_init_finished_mac(s)) {
781 /* SSLfatal() already called */
786 case DTLS_ST_SW_HELLO_VERIFY_REQUEST:
787 if (statem_flush(s) != 1)
789 /* HelloVerifyRequest resets Finished MAC */
790 if (s->version != DTLS1_BAD_VER && !ssl3_init_finished_mac(s)) {
791 /* SSLfatal() already called */
795 * The next message should be another ClientHello which we need to
796 * treat like it was the first packet
801 case TLS_ST_SW_SRVR_HELLO:
802 if (SSL_IS_TLS13(s) && s->hello_retry_request == SSL_HRR_PENDING) {
803 if ((s->options & SSL_OP_ENABLE_MIDDLEBOX_COMPAT) == 0
804 && statem_flush(s) != 1)
808 #ifndef OPENSSL_NO_SCTP
809 if (SSL_IS_DTLS(s) && s->hit) {
810 unsigned char sctpauthkey[64];
811 char labelbuffer[sizeof(DTLS1_SCTP_AUTH_LABEL)];
814 * Add new shared key for SCTP-Auth, will be ignored if no
817 memcpy(labelbuffer, DTLS1_SCTP_AUTH_LABEL,
818 sizeof(DTLS1_SCTP_AUTH_LABEL));
820 if (SSL_export_keying_material(s, sctpauthkey,
821 sizeof(sctpauthkey), labelbuffer,
822 sizeof(labelbuffer), NULL, 0,
824 SSLfatal(s, SSL_AD_INTERNAL_ERROR,
825 SSL_F_OSSL_STATEM_SERVER_POST_WORK,
826 ERR_R_INTERNAL_ERROR);
830 BIO_ctrl(SSL_get_wbio(s), BIO_CTRL_DGRAM_SCTP_ADD_AUTH_KEY,
831 sizeof(sctpauthkey), sctpauthkey);
835 || ((s->options & SSL_OP_ENABLE_MIDDLEBOX_COMPAT) != 0
836 && s->hello_retry_request != SSL_HRR_COMPLETE))
840 case TLS_ST_SW_CHANGE:
841 if (s->hello_retry_request == SSL_HRR_PENDING) {
842 if (!statem_flush(s))
847 * TODO(TLS1.3): This actually causes a problem. We don't yet know
848 * whether the next record we are going to receive is an unencrypted
849 * alert, or an encrypted handshake message. We're going to need
850 * something clever in the record layer for this.
852 if (SSL_IS_TLS13(s)) {
853 if (!s->method->ssl3_enc->setup_key_block(s)
854 || !s->method->ssl3_enc->change_cipher_state(s,
855 SSL3_CC_HANDSHAKE | SSL3_CHANGE_CIPHER_SERVER_WRITE)) {
856 /* SSLfatal() already called */
860 if (s->ext.early_data != SSL_EARLY_DATA_ACCEPTED
861 && !s->method->ssl3_enc->change_cipher_state(s,
862 SSL3_CC_HANDSHAKE |SSL3_CHANGE_CIPHER_SERVER_READ)) {
863 /* SSLfatal() already called */
869 #ifndef OPENSSL_NO_SCTP
870 if (SSL_IS_DTLS(s) && !s->hit) {
872 * Change to new shared key of SCTP-Auth, will be ignored if
875 BIO_ctrl(SSL_get_wbio(s), BIO_CTRL_DGRAM_SCTP_NEXT_AUTH_KEY,
879 if (!s->method->ssl3_enc->change_cipher_state(s,
880 SSL3_CHANGE_CIPHER_SERVER_WRITE))
882 /* SSLfatal() already called */
887 dtls1_reset_seq_numbers(s, SSL3_CC_WRITE);
890 case TLS_ST_SW_SRVR_DONE:
891 if (statem_flush(s) != 1)
895 case TLS_ST_SW_FINISHED:
896 if (statem_flush(s) != 1)
898 #ifndef OPENSSL_NO_SCTP
899 if (SSL_IS_DTLS(s) && s->hit) {
901 * Change to new shared key of SCTP-Auth, will be ignored if
904 BIO_ctrl(SSL_get_wbio(s), BIO_CTRL_DGRAM_SCTP_NEXT_AUTH_KEY,
908 if (SSL_IS_TLS13(s)) {
909 if (!s->method->ssl3_enc->generate_master_secret(s,
910 s->master_secret, s->handshake_secret, 0,
911 &s->session->master_key_length)
912 || !s->method->ssl3_enc->change_cipher_state(s,
913 SSL3_CC_APPLICATION | SSL3_CHANGE_CIPHER_SERVER_WRITE))
914 /* SSLfatal() already called */
919 case TLS_ST_SW_CERT_REQ:
920 if (s->post_handshake_auth == SSL_PHA_REQUEST_PENDING) {
921 if (statem_flush(s) != 1)
926 case TLS_ST_SW_KEY_UPDATE:
927 if (statem_flush(s) != 1)
929 if (!tls13_update_key(s, 1)) {
930 /* SSLfatal() already called */
935 case TLS_ST_SW_SESSION_TICKET:
936 if (SSL_IS_TLS13(s) && statem_flush(s) != 1)
941 return WORK_FINISHED_CONTINUE;
945 * Get the message construction function and message type for sending from the
948 * Valid return values are:
952 int ossl_statem_server_construct_message(SSL *s, WPACKET *pkt,
953 confunc_f *confunc, int *mt)
955 OSSL_STATEM *st = &s->statem;
957 switch (st->hand_state) {
959 /* Shouldn't happen */
960 SSLfatal(s, SSL_AD_INTERNAL_ERROR,
961 SSL_F_OSSL_STATEM_SERVER_CONSTRUCT_MESSAGE,
962 SSL_R_BAD_HANDSHAKE_STATE);
965 case TLS_ST_SW_CHANGE:
967 *confunc = dtls_construct_change_cipher_spec;
969 *confunc = tls_construct_change_cipher_spec;
970 *mt = SSL3_MT_CHANGE_CIPHER_SPEC;
973 case DTLS_ST_SW_HELLO_VERIFY_REQUEST:
974 *confunc = dtls_construct_hello_verify_request;
975 *mt = DTLS1_MT_HELLO_VERIFY_REQUEST;
978 case TLS_ST_SW_HELLO_REQ:
979 /* No construction function needed */
981 *mt = SSL3_MT_HELLO_REQUEST;
984 case TLS_ST_SW_SRVR_HELLO:
985 *confunc = tls_construct_server_hello;
986 *mt = SSL3_MT_SERVER_HELLO;
990 *confunc = tls_construct_server_certificate;
991 *mt = SSL3_MT_CERTIFICATE;
994 case TLS_ST_SW_CERT_VRFY:
995 *confunc = tls_construct_cert_verify;
996 *mt = SSL3_MT_CERTIFICATE_VERIFY;
1000 case TLS_ST_SW_KEY_EXCH:
1001 *confunc = tls_construct_server_key_exchange;
1002 *mt = SSL3_MT_SERVER_KEY_EXCHANGE;
1005 case TLS_ST_SW_CERT_REQ:
1006 *confunc = tls_construct_certificate_request;
1007 *mt = SSL3_MT_CERTIFICATE_REQUEST;
1010 case TLS_ST_SW_SRVR_DONE:
1011 *confunc = tls_construct_server_done;
1012 *mt = SSL3_MT_SERVER_DONE;
1015 case TLS_ST_SW_SESSION_TICKET:
1016 *confunc = tls_construct_new_session_ticket;
1017 *mt = SSL3_MT_NEWSESSION_TICKET;
1020 case TLS_ST_SW_CERT_STATUS:
1021 *confunc = tls_construct_cert_status;
1022 *mt = SSL3_MT_CERTIFICATE_STATUS;
1025 case TLS_ST_SW_FINISHED:
1026 *confunc = tls_construct_finished;
1027 *mt = SSL3_MT_FINISHED;
1030 case TLS_ST_EARLY_DATA:
1032 *mt = SSL3_MT_DUMMY;
1035 case TLS_ST_SW_ENCRYPTED_EXTENSIONS:
1036 *confunc = tls_construct_encrypted_extensions;
1037 *mt = SSL3_MT_ENCRYPTED_EXTENSIONS;
1040 case TLS_ST_SW_KEY_UPDATE:
1041 *confunc = tls_construct_key_update;
1042 *mt = SSL3_MT_KEY_UPDATE;
1050 * Maximum size (excluding the Handshake header) of a ClientHello message,
1051 * calculated as follows:
1053 * 2 + # client_version
1054 * 32 + # only valid length for random
1055 * 1 + # length of session_id
1056 * 32 + # maximum size for session_id
1057 * 2 + # length of cipher suites
1058 * 2^16-2 + # maximum length of cipher suites array
1059 * 1 + # length of compression_methods
1060 * 2^8-1 + # maximum length of compression methods
1061 * 2 + # length of extensions
1062 * 2^16-1 # maximum length of extensions
1064 #define CLIENT_HELLO_MAX_LENGTH 131396
1066 #define CLIENT_KEY_EXCH_MAX_LENGTH 2048
1067 #define NEXT_PROTO_MAX_LENGTH 514
1070 * Returns the maximum allowed length for the current message that we are
1071 * reading. Excludes the message header.
1073 size_t ossl_statem_server_max_message_size(SSL *s)
1075 OSSL_STATEM *st = &s->statem;
1077 switch (st->hand_state) {
1079 /* Shouldn't happen */
1082 case TLS_ST_SR_CLNT_HELLO:
1083 return CLIENT_HELLO_MAX_LENGTH;
1085 case TLS_ST_SR_END_OF_EARLY_DATA:
1086 return END_OF_EARLY_DATA_MAX_LENGTH;
1088 case TLS_ST_SR_CERT:
1089 return s->max_cert_list;
1091 case TLS_ST_SR_KEY_EXCH:
1092 return CLIENT_KEY_EXCH_MAX_LENGTH;
1094 case TLS_ST_SR_CERT_VRFY:
1095 return SSL3_RT_MAX_PLAIN_LENGTH;
1097 #ifndef OPENSSL_NO_NEXTPROTONEG
1098 case TLS_ST_SR_NEXT_PROTO:
1099 return NEXT_PROTO_MAX_LENGTH;
1102 case TLS_ST_SR_CHANGE:
1103 return CCS_MAX_LENGTH;
1105 case TLS_ST_SR_FINISHED:
1106 return FINISHED_MAX_LENGTH;
1108 case TLS_ST_SR_KEY_UPDATE:
1109 return KEY_UPDATE_MAX_LENGTH;
1114 * Process a message that the server has received from the client.
1116 MSG_PROCESS_RETURN ossl_statem_server_process_message(SSL *s, PACKET *pkt)
1118 OSSL_STATEM *st = &s->statem;
1120 switch (st->hand_state) {
1122 /* Shouldn't happen */
1123 SSLfatal(s, SSL_AD_INTERNAL_ERROR,
1124 SSL_F_OSSL_STATEM_SERVER_PROCESS_MESSAGE,
1125 ERR_R_INTERNAL_ERROR);
1126 return MSG_PROCESS_ERROR;
1128 case TLS_ST_SR_CLNT_HELLO:
1129 return tls_process_client_hello(s, pkt);
1131 case TLS_ST_SR_END_OF_EARLY_DATA:
1132 return tls_process_end_of_early_data(s, pkt);
1134 case TLS_ST_SR_CERT:
1135 return tls_process_client_certificate(s, pkt);
1137 case TLS_ST_SR_KEY_EXCH:
1138 return tls_process_client_key_exchange(s, pkt);
1140 case TLS_ST_SR_CERT_VRFY:
1141 return tls_process_cert_verify(s, pkt);
1143 #ifndef OPENSSL_NO_NEXTPROTONEG
1144 case TLS_ST_SR_NEXT_PROTO:
1145 return tls_process_next_proto(s, pkt);
1148 case TLS_ST_SR_CHANGE:
1149 return tls_process_change_cipher_spec(s, pkt);
1151 case TLS_ST_SR_FINISHED:
1152 return tls_process_finished(s, pkt);
1154 case TLS_ST_SR_KEY_UPDATE:
1155 return tls_process_key_update(s, pkt);
1161 * Perform any further processing required following the receipt of a message
1164 WORK_STATE ossl_statem_server_post_process_message(SSL *s, WORK_STATE wst)
1166 OSSL_STATEM *st = &s->statem;
1168 switch (st->hand_state) {
1170 /* Shouldn't happen */
1171 SSLfatal(s, SSL_AD_INTERNAL_ERROR,
1172 SSL_F_OSSL_STATEM_SERVER_POST_PROCESS_MESSAGE,
1173 ERR_R_INTERNAL_ERROR);
1176 case TLS_ST_SR_CLNT_HELLO:
1177 return tls_post_process_client_hello(s, wst);
1179 case TLS_ST_SR_KEY_EXCH:
1180 return tls_post_process_client_key_exchange(s, wst);
1184 #ifndef OPENSSL_NO_SRP
1185 /* Returns 1 on success, 0 for retryable error, -1 for fatal error */
1186 static int ssl_check_srp_ext_ClientHello(SSL *s)
1189 int al = SSL_AD_UNRECOGNIZED_NAME;
1191 if ((s->s3->tmp.new_cipher->algorithm_mkey & SSL_kSRP) &&
1192 (s->srp_ctx.TLS_ext_srp_username_callback != NULL)) {
1193 if (s->srp_ctx.login == NULL) {
1195 * RFC 5054 says SHOULD reject, we do so if There is no srp
1198 SSLfatal(s, SSL_AD_UNKNOWN_PSK_IDENTITY,
1199 SSL_F_SSL_CHECK_SRP_EXT_CLIENTHELLO,
1200 SSL_R_PSK_IDENTITY_NOT_FOUND);
1203 ret = SSL_srp_server_param_with_username(s, &al);
1206 if (ret == SSL3_AL_FATAL) {
1207 SSLfatal(s, al, SSL_F_SSL_CHECK_SRP_EXT_CLIENTHELLO,
1208 al == SSL_AD_UNKNOWN_PSK_IDENTITY
1209 ? SSL_R_PSK_IDENTITY_NOT_FOUND
1210 : SSL_R_CLIENTHELLO_TLSEXT);
1219 int dtls_raw_hello_verify_request(WPACKET *pkt, unsigned char *cookie,
1222 /* Always use DTLS 1.0 version: see RFC 6347 */
1223 if (!WPACKET_put_bytes_u16(pkt, DTLS1_VERSION)
1224 || !WPACKET_sub_memcpy_u8(pkt, cookie, cookie_len))
1230 int dtls_construct_hello_verify_request(SSL *s, WPACKET *pkt)
1232 unsigned int cookie_leni;
1233 if (s->ctx->app_gen_cookie_cb == NULL ||
1234 s->ctx->app_gen_cookie_cb(s, s->d1->cookie,
1235 &cookie_leni) == 0 ||
1236 cookie_leni > 255) {
1237 SSLfatal(s, SSL_AD_NO_ALERT, SSL_F_DTLS_CONSTRUCT_HELLO_VERIFY_REQUEST,
1238 SSL_R_COOKIE_GEN_CALLBACK_FAILURE);
1241 s->d1->cookie_len = cookie_leni;
1243 if (!dtls_raw_hello_verify_request(pkt, s->d1->cookie,
1244 s->d1->cookie_len)) {
1245 SSLfatal(s, SSL_AD_NO_ALERT, SSL_F_DTLS_CONSTRUCT_HELLO_VERIFY_REQUEST,
1246 ERR_R_INTERNAL_ERROR);
1253 #ifndef OPENSSL_NO_EC
1255 * ssl_check_for_safari attempts to fingerprint Safari using OS X
1256 * SecureTransport using the TLS extension block in |hello|.
1257 * Safari, since 10.6, sends exactly these extensions, in this order:
1261 * signature_algorithms (for TLSv1.2 only)
1263 * We wish to fingerprint Safari because they broke ECDHE-ECDSA support in 10.8,
1264 * but they advertise support. So enabling ECDHE-ECDSA ciphers breaks them.
1265 * Sadly we cannot differentiate 10.6, 10.7 and 10.8.4 (which work), from
1266 * 10.8..10.8.3 (which don't work).
1268 static void ssl_check_for_safari(SSL *s, const CLIENTHELLO_MSG *hello)
1270 static const unsigned char kSafariExtensionsBlock[] = {
1271 0x00, 0x0a, /* elliptic_curves extension */
1272 0x00, 0x08, /* 8 bytes */
1273 0x00, 0x06, /* 6 bytes of curve ids */
1274 0x00, 0x17, /* P-256 */
1275 0x00, 0x18, /* P-384 */
1276 0x00, 0x19, /* P-521 */
1278 0x00, 0x0b, /* ec_point_formats */
1279 0x00, 0x02, /* 2 bytes */
1280 0x01, /* 1 point format */
1281 0x00, /* uncompressed */
1282 /* The following is only present in TLS 1.2 */
1283 0x00, 0x0d, /* signature_algorithms */
1284 0x00, 0x0c, /* 12 bytes */
1285 0x00, 0x0a, /* 10 bytes */
1286 0x05, 0x01, /* SHA-384/RSA */
1287 0x04, 0x01, /* SHA-256/RSA */
1288 0x02, 0x01, /* SHA-1/RSA */
1289 0x04, 0x03, /* SHA-256/ECDSA */
1290 0x02, 0x03, /* SHA-1/ECDSA */
1292 /* Length of the common prefix (first two extensions). */
1293 static const size_t kSafariCommonExtensionsLength = 18;
1298 tmppkt = hello->extensions;
1300 if (!PACKET_forward(&tmppkt, 2)
1301 || !PACKET_get_net_2(&tmppkt, &type)
1302 || !PACKET_get_length_prefixed_2(&tmppkt, &sni)) {
1306 if (type != TLSEXT_TYPE_server_name)
1309 ext_len = TLS1_get_client_version(s) >= TLS1_2_VERSION ?
1310 sizeof(kSafariExtensionsBlock) : kSafariCommonExtensionsLength;
1312 s->s3->is_probably_safari = PACKET_equal(&tmppkt, kSafariExtensionsBlock,
1315 #endif /* !OPENSSL_NO_EC */
1317 MSG_PROCESS_RETURN tls_process_client_hello(SSL *s, PACKET *pkt)
1319 /* |cookie| will only be initialized for DTLS. */
1320 PACKET session_id, compression, extensions, cookie;
1321 static const unsigned char null_compression = 0;
1322 CLIENTHELLO_MSG *clienthello = NULL;
1324 /* Check if this is actually an unexpected renegotiation ClientHello */
1325 if (s->renegotiate == 0 && !SSL_IS_FIRST_HANDSHAKE(s)) {
1326 if (!ossl_assert(!SSL_IS_TLS13(s))) {
1327 SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_F_TLS_PROCESS_CLIENT_HELLO,
1328 ERR_R_INTERNAL_ERROR);
1331 if ((s->options & SSL_OP_NO_RENEGOTIATION) != 0
1332 || (!s->s3->send_connection_binding
1334 & SSL_OP_ALLOW_UNSAFE_LEGACY_RENEGOTIATION) == 0)) {
1335 ssl3_send_alert(s, SSL3_AL_WARNING, SSL_AD_NO_RENEGOTIATION);
1336 return MSG_PROCESS_FINISHED_READING;
1342 clienthello = OPENSSL_zalloc(sizeof(*clienthello));
1343 if (clienthello == NULL) {
1344 SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_F_TLS_PROCESS_CLIENT_HELLO,
1345 ERR_R_INTERNAL_ERROR);
1350 * First, parse the raw ClientHello data into the CLIENTHELLO_MSG structure.
1352 clienthello->isv2 = RECORD_LAYER_is_sslv2_record(&s->rlayer);
1353 PACKET_null_init(&cookie);
1355 if (clienthello->isv2) {
1358 if (!SSL_IS_FIRST_HANDSHAKE(s)
1359 || s->hello_retry_request != SSL_HRR_NONE) {
1360 SSLfatal(s, SSL_AD_UNEXPECTED_MESSAGE,
1361 SSL_F_TLS_PROCESS_CLIENT_HELLO, SSL_R_UNEXPECTED_MESSAGE);
1366 * An SSLv3/TLSv1 backwards-compatible CLIENT-HELLO in an SSLv2
1367 * header is sent directly on the wire, not wrapped as a TLS
1368 * record. Our record layer just processes the message length and passes
1369 * the rest right through. Its format is:
1371 * 0-1 msg_length - decoded by the record layer
1372 * 2 msg_type - s->init_msg points here
1374 * 5-6 cipher_spec_length
1375 * 7-8 session_id_length
1376 * 9-10 challenge_length
1380 if (!PACKET_get_1(pkt, &mt)
1381 || mt != SSL2_MT_CLIENT_HELLO) {
1383 * Should never happen. We should have tested this in the record
1384 * layer in order to have determined that this is a SSLv2 record
1385 * in the first place
1387 SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_F_TLS_PROCESS_CLIENT_HELLO,
1388 ERR_R_INTERNAL_ERROR);
1393 if (!PACKET_get_net_2(pkt, &clienthello->legacy_version)) {
1394 SSLfatal(s, SSL_AD_DECODE_ERROR, SSL_F_TLS_PROCESS_CLIENT_HELLO,
1395 SSL_R_LENGTH_TOO_SHORT);
1399 /* Parse the message and load client random. */
1400 if (clienthello->isv2) {
1402 * Handle an SSLv2 backwards compatible ClientHello
1403 * Note, this is only for SSLv3+ using the backward compatible format.
1404 * Real SSLv2 is not supported, and is rejected below.
1406 unsigned int ciphersuite_len, session_id_len, challenge_len;
1409 if (!PACKET_get_net_2(pkt, &ciphersuite_len)
1410 || !PACKET_get_net_2(pkt, &session_id_len)
1411 || !PACKET_get_net_2(pkt, &challenge_len)) {
1412 SSLfatal(s, SSL_AD_DECODE_ERROR, SSL_F_TLS_PROCESS_CLIENT_HELLO,
1413 SSL_R_RECORD_LENGTH_MISMATCH);
1417 if (session_id_len > SSL_MAX_SSL_SESSION_ID_LENGTH) {
1418 SSLfatal(s, SSL_AD_ILLEGAL_PARAMETER,
1419 SSL_F_TLS_PROCESS_CLIENT_HELLO, SSL_R_LENGTH_MISMATCH);
1423 if (!PACKET_get_sub_packet(pkt, &clienthello->ciphersuites,
1425 || !PACKET_copy_bytes(pkt, clienthello->session_id, session_id_len)
1426 || !PACKET_get_sub_packet(pkt, &challenge, challenge_len)
1427 /* No extensions. */
1428 || PACKET_remaining(pkt) != 0) {
1429 SSLfatal(s, SSL_AD_DECODE_ERROR, SSL_F_TLS_PROCESS_CLIENT_HELLO,
1430 SSL_R_RECORD_LENGTH_MISMATCH);
1433 clienthello->session_id_len = session_id_len;
1435 /* Load the client random and compression list. We use SSL3_RANDOM_SIZE
1436 * here rather than sizeof(clienthello->random) because that is the limit
1437 * for SSLv3 and it is fixed. It won't change even if
1438 * sizeof(clienthello->random) does.
1440 challenge_len = challenge_len > SSL3_RANDOM_SIZE
1441 ? SSL3_RANDOM_SIZE : challenge_len;
1442 memset(clienthello->random, 0, SSL3_RANDOM_SIZE);
1443 if (!PACKET_copy_bytes(&challenge,
1444 clienthello->random + SSL3_RANDOM_SIZE -
1445 challenge_len, challenge_len)
1446 /* Advertise only null compression. */
1447 || !PACKET_buf_init(&compression, &null_compression, 1)) {
1448 SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_F_TLS_PROCESS_CLIENT_HELLO,
1449 ERR_R_INTERNAL_ERROR);
1453 PACKET_null_init(&clienthello->extensions);
1455 /* Regular ClientHello. */
1456 if (!PACKET_copy_bytes(pkt, clienthello->random, SSL3_RANDOM_SIZE)
1457 || !PACKET_get_length_prefixed_1(pkt, &session_id)
1458 || !PACKET_copy_all(&session_id, clienthello->session_id,
1459 SSL_MAX_SSL_SESSION_ID_LENGTH,
1460 &clienthello->session_id_len)) {
1461 SSLfatal(s, SSL_AD_DECODE_ERROR, SSL_F_TLS_PROCESS_CLIENT_HELLO,
1462 SSL_R_LENGTH_MISMATCH);
1466 if (SSL_IS_DTLS(s)) {
1467 if (!PACKET_get_length_prefixed_1(pkt, &cookie)) {
1468 SSLfatal(s, SSL_AD_DECODE_ERROR, SSL_F_TLS_PROCESS_CLIENT_HELLO,
1469 SSL_R_LENGTH_MISMATCH);
1472 if (!PACKET_copy_all(&cookie, clienthello->dtls_cookie,
1473 DTLS1_COOKIE_LENGTH,
1474 &clienthello->dtls_cookie_len)) {
1475 SSLfatal(s, SSL_AD_INTERNAL_ERROR,
1476 SSL_F_TLS_PROCESS_CLIENT_HELLO, ERR_R_INTERNAL_ERROR);
1480 * If we require cookies and this ClientHello doesn't contain one,
1481 * just return since we do not want to allocate any memory yet.
1482 * So check cookie length...
1484 if (SSL_get_options(s) & SSL_OP_COOKIE_EXCHANGE) {
1485 if (clienthello->dtls_cookie_len == 0)
1486 return MSG_PROCESS_FINISHED_READING;
1490 if (!PACKET_get_length_prefixed_2(pkt, &clienthello->ciphersuites)) {
1491 SSLfatal(s, SSL_AD_DECODE_ERROR, SSL_F_TLS_PROCESS_CLIENT_HELLO,
1492 SSL_R_LENGTH_MISMATCH);
1496 if (!PACKET_get_length_prefixed_1(pkt, &compression)) {
1497 SSLfatal(s, SSL_AD_DECODE_ERROR, SSL_F_TLS_PROCESS_CLIENT_HELLO,
1498 SSL_R_LENGTH_MISMATCH);
1502 /* Could be empty. */
1503 if (PACKET_remaining(pkt) == 0) {
1504 PACKET_null_init(&clienthello->extensions);
1506 if (!PACKET_get_length_prefixed_2(pkt, &clienthello->extensions)
1507 || PACKET_remaining(pkt) != 0) {
1508 SSLfatal(s, SSL_AD_DECODE_ERROR, SSL_F_TLS_PROCESS_CLIENT_HELLO,
1509 SSL_R_LENGTH_MISMATCH);
1515 if (!PACKET_copy_all(&compression, clienthello->compressions,
1516 MAX_COMPRESSIONS_SIZE,
1517 &clienthello->compressions_len)) {
1518 SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_F_TLS_PROCESS_CLIENT_HELLO,
1519 ERR_R_INTERNAL_ERROR);
1523 /* Preserve the raw extensions PACKET for later use */
1524 extensions = clienthello->extensions;
1525 if (!tls_collect_extensions(s, &extensions, SSL_EXT_CLIENT_HELLO,
1526 &clienthello->pre_proc_exts,
1527 &clienthello->pre_proc_exts_len, 1)) {
1528 /* SSLfatal already been called */
1531 s->clienthello = clienthello;
1533 return MSG_PROCESS_CONTINUE_PROCESSING;
1536 if (clienthello != NULL)
1537 OPENSSL_free(clienthello->pre_proc_exts);
1538 OPENSSL_free(clienthello);
1540 return MSG_PROCESS_ERROR;
1543 static int tls_early_post_process_client_hello(SSL *s)
1546 int i, al = SSL_AD_INTERNAL_ERROR;
1550 #ifndef OPENSSL_NO_COMP
1551 SSL_COMP *comp = NULL;
1553 const SSL_CIPHER *c;
1554 STACK_OF(SSL_CIPHER) *ciphers = NULL;
1555 STACK_OF(SSL_CIPHER) *scsvs = NULL;
1556 CLIENTHELLO_MSG *clienthello = s->clienthello;
1557 DOWNGRADE dgrd = DOWNGRADE_NONE;
1559 /* Finished parsing the ClientHello, now we can start processing it */
1560 /* Give the ClientHello callback a crack at things */
1561 if (s->ctx->client_hello_cb != NULL) {
1562 /* A failure in the ClientHello callback terminates the connection. */
1563 switch (s->ctx->client_hello_cb(s, &al, s->ctx->client_hello_cb_arg)) {
1564 case SSL_CLIENT_HELLO_SUCCESS:
1566 case SSL_CLIENT_HELLO_RETRY:
1567 s->rwstate = SSL_CLIENT_HELLO_CB;
1569 case SSL_CLIENT_HELLO_ERROR:
1572 SSL_F_TLS_EARLY_POST_PROCESS_CLIENT_HELLO,
1573 SSL_R_CALLBACK_FAILED);
1578 /* Set up the client_random */
1579 memcpy(s->s3->client_random, clienthello->random, SSL3_RANDOM_SIZE);
1581 /* Choose the version */
1583 if (clienthello->isv2) {
1584 if (clienthello->legacy_version == SSL2_VERSION
1585 || (clienthello->legacy_version & 0xff00)
1586 != (SSL3_VERSION_MAJOR << 8)) {
1588 * This is real SSLv2 or something completely unknown. We don't
1591 SSLfatal(s, SSL_AD_PROTOCOL_VERSION,
1592 SSL_F_TLS_EARLY_POST_PROCESS_CLIENT_HELLO,
1593 SSL_R_UNKNOWN_PROTOCOL);
1597 s->client_version = clienthello->legacy_version;
1600 * Do SSL/TLS version negotiation if applicable. For DTLS we just check
1601 * versions are potentially compatible. Version negotiation comes later.
1603 if (!SSL_IS_DTLS(s)) {
1604 protverr = ssl_choose_server_version(s, clienthello, &dgrd);
1605 } else if (s->method->version != DTLS_ANY_VERSION &&
1606 DTLS_VERSION_LT((int)clienthello->legacy_version, s->version)) {
1607 protverr = SSL_R_VERSION_TOO_LOW;
1613 if (SSL_IS_FIRST_HANDSHAKE(s)) {
1614 /* like ssl3_get_record, send alert using remote version number */
1615 s->version = s->client_version = clienthello->legacy_version;
1617 SSLfatal(s, SSL_AD_PROTOCOL_VERSION,
1618 SSL_F_TLS_EARLY_POST_PROCESS_CLIENT_HELLO, protverr);
1622 /* TLSv1.3 specifies that a ClientHello must end on a record boundary */
1623 if (SSL_IS_TLS13(s) && RECORD_LAYER_processed_read_pending(&s->rlayer)) {
1624 SSLfatal(s, SSL_AD_UNEXPECTED_MESSAGE,
1625 SSL_F_TLS_EARLY_POST_PROCESS_CLIENT_HELLO,
1626 SSL_R_NOT_ON_RECORD_BOUNDARY);
1630 if (SSL_IS_DTLS(s)) {
1631 /* Empty cookie was already handled above by returning early. */
1632 if (SSL_get_options(s) & SSL_OP_COOKIE_EXCHANGE) {
1633 if (s->ctx->app_verify_cookie_cb != NULL) {
1634 if (s->ctx->app_verify_cookie_cb(s, clienthello->dtls_cookie,
1635 clienthello->dtls_cookie_len) == 0) {
1636 SSLfatal(s, SSL_AD_HANDSHAKE_FAILURE,
1637 SSL_F_TLS_EARLY_POST_PROCESS_CLIENT_HELLO,
1638 SSL_R_COOKIE_MISMATCH);
1640 /* else cookie verification succeeded */
1642 /* default verification */
1643 } else if (s->d1->cookie_len != clienthello->dtls_cookie_len
1644 || memcmp(clienthello->dtls_cookie, s->d1->cookie,
1645 s->d1->cookie_len) != 0) {
1646 SSLfatal(s, SSL_AD_HANDSHAKE_FAILURE,
1647 SSL_F_TLS_EARLY_POST_PROCESS_CLIENT_HELLO,
1648 SSL_R_COOKIE_MISMATCH);
1651 s->d1->cookie_verified = 1;
1653 if (s->method->version == DTLS_ANY_VERSION) {
1654 protverr = ssl_choose_server_version(s, clienthello, &dgrd);
1655 if (protverr != 0) {
1656 s->version = s->client_version;
1657 SSLfatal(s, SSL_AD_PROTOCOL_VERSION,
1658 SSL_F_TLS_EARLY_POST_PROCESS_CLIENT_HELLO, protverr);
1666 if (!ssl_cache_cipherlist(s, &clienthello->ciphersuites,
1667 clienthello->isv2) ||
1668 !bytes_to_cipher_list(s, &clienthello->ciphersuites, &ciphers, &scsvs,
1669 clienthello->isv2, 1)) {
1670 /* SSLfatal() already called */
1674 s->s3->send_connection_binding = 0;
1675 /* Check what signalling cipher-suite values were received. */
1676 if (scsvs != NULL) {
1677 for(i = 0; i < sk_SSL_CIPHER_num(scsvs); i++) {
1678 c = sk_SSL_CIPHER_value(scsvs, i);
1679 if (SSL_CIPHER_get_id(c) == SSL3_CK_SCSV) {
1680 if (s->renegotiate) {
1681 /* SCSV is fatal if renegotiating */
1682 SSLfatal(s, SSL_AD_HANDSHAKE_FAILURE,
1683 SSL_F_TLS_EARLY_POST_PROCESS_CLIENT_HELLO,
1684 SSL_R_SCSV_RECEIVED_WHEN_RENEGOTIATING);
1687 s->s3->send_connection_binding = 1;
1688 } else if (SSL_CIPHER_get_id(c) == SSL3_CK_FALLBACK_SCSV &&
1689 !ssl_check_version_downgrade(s)) {
1691 * This SCSV indicates that the client previously tried
1692 * a higher version. We should fail if the current version
1693 * is an unexpected downgrade, as that indicates that the first
1694 * connection may have been tampered with in order to trigger
1695 * an insecure downgrade.
1697 SSLfatal(s, SSL_AD_INAPPROPRIATE_FALLBACK,
1698 SSL_F_TLS_EARLY_POST_PROCESS_CLIENT_HELLO,
1699 SSL_R_INAPPROPRIATE_FALLBACK);
1705 /* For TLSv1.3 we must select the ciphersuite *before* session resumption */
1706 if (SSL_IS_TLS13(s)) {
1707 const SSL_CIPHER *cipher =
1708 ssl3_choose_cipher(s, ciphers, SSL_get_ciphers(s));
1710 if (cipher == NULL) {
1711 SSLfatal(s, SSL_AD_HANDSHAKE_FAILURE,
1712 SSL_F_TLS_EARLY_POST_PROCESS_CLIENT_HELLO,
1713 SSL_R_NO_SHARED_CIPHER);
1716 if (s->hello_retry_request == SSL_HRR_PENDING
1717 && (s->s3->tmp.new_cipher == NULL
1718 || s->s3->tmp.new_cipher->id != cipher->id)) {
1720 * A previous HRR picked a different ciphersuite to the one we
1721 * just selected. Something must have changed.
1723 SSLfatal(s, SSL_AD_ILLEGAL_PARAMETER,
1724 SSL_F_TLS_EARLY_POST_PROCESS_CLIENT_HELLO,
1728 s->s3->tmp.new_cipher = cipher;
1731 /* We need to do this before getting the session */
1732 if (!tls_parse_extension(s, TLSEXT_IDX_extended_master_secret,
1733 SSL_EXT_CLIENT_HELLO,
1734 clienthello->pre_proc_exts, NULL, 0)) {
1735 /* SSLfatal() already called */
1740 * We don't allow resumption in a backwards compatible ClientHello.
1741 * TODO(openssl-team): in TLS1.1+, session_id MUST be empty.
1743 * Versions before 0.9.7 always allow clients to resume sessions in
1744 * renegotiation. 0.9.7 and later allow this by default, but optionally
1745 * ignore resumption requests with flag
1746 * SSL_OP_NO_SESSION_RESUMPTION_ON_RENEGOTIATION (it's a new flag rather
1747 * than a change to default behavior so that applications relying on
1748 * this for security won't even compile against older library versions).
1749 * 1.0.1 and later also have a function SSL_renegotiate_abbreviated() to
1750 * request renegotiation but not a new session (s->new_session remains
1751 * unset): for servers, this essentially just means that the
1752 * SSL_OP_NO_SESSION_RESUMPTION_ON_RENEGOTIATION setting will be
1755 if (clienthello->isv2 ||
1757 (s->options & SSL_OP_NO_SESSION_RESUMPTION_ON_RENEGOTIATION))) {
1758 if (!ssl_get_new_session(s, 1)) {
1759 /* SSLfatal() already called */
1763 i = ssl_get_prev_session(s, clienthello);
1765 /* previous session */
1767 } else if (i == -1) {
1768 /* SSLfatal() already called */
1772 if (!ssl_get_new_session(s, 1)) {
1773 /* SSLfatal() already called */
1779 if (SSL_IS_TLS13(s)) {
1780 memcpy(s->tmp_session_id, s->clienthello->session_id,
1781 s->clienthello->session_id_len);
1782 s->tmp_session_id_len = s->clienthello->session_id_len;
1786 * If it is a hit, check that the cipher is in the list. In TLSv1.3 we check
1787 * ciphersuite compatibility with the session as part of resumption.
1789 if (!SSL_IS_TLS13(s) && s->hit) {
1791 id = s->session->cipher->id;
1794 fprintf(stderr, "client sent %d ciphers\n", sk_SSL_CIPHER_num(ciphers));
1796 for (i = 0; i < sk_SSL_CIPHER_num(ciphers); i++) {
1797 c = sk_SSL_CIPHER_value(ciphers, i);
1799 fprintf(stderr, "client [%2d of %2d]:%s\n",
1800 i, sk_SSL_CIPHER_num(ciphers), SSL_CIPHER_get_name(c));
1809 * we need to have the cipher in the cipher list if we are asked
1812 SSLfatal(s, SSL_AD_ILLEGAL_PARAMETER,
1813 SSL_F_TLS_EARLY_POST_PROCESS_CLIENT_HELLO,
1814 SSL_R_REQUIRED_CIPHER_MISSING);
1819 for (loop = 0; loop < clienthello->compressions_len; loop++) {
1820 if (clienthello->compressions[loop] == 0)
1824 if (loop >= clienthello->compressions_len) {
1826 SSLfatal(s, SSL_AD_DECODE_ERROR,
1827 SSL_F_TLS_EARLY_POST_PROCESS_CLIENT_HELLO,
1828 SSL_R_NO_COMPRESSION_SPECIFIED);
1832 #ifndef OPENSSL_NO_EC
1833 if (s->options & SSL_OP_SAFARI_ECDHE_ECDSA_BUG)
1834 ssl_check_for_safari(s, clienthello);
1835 #endif /* !OPENSSL_NO_EC */
1837 /* TLS extensions */
1838 if (!tls_parse_all_extensions(s, SSL_EXT_CLIENT_HELLO,
1839 clienthello->pre_proc_exts, NULL, 0, 1)) {
1840 /* SSLfatal() already called */
1845 * Check if we want to use external pre-shared secret for this handshake
1846 * for not reused session only. We need to generate server_random before
1847 * calling tls_session_secret_cb in order to allow SessionTicket
1848 * processing to use it in key derivation.
1852 pos = s->s3->server_random;
1853 if (ssl_fill_hello_random(s, 1, pos, SSL3_RANDOM_SIZE, dgrd) <= 0) {
1854 SSLfatal(s, SSL_AD_INTERNAL_ERROR,
1855 SSL_F_TLS_EARLY_POST_PROCESS_CLIENT_HELLO,
1856 ERR_R_INTERNAL_ERROR);
1862 && s->version >= TLS1_VERSION
1865 && s->ext.session_secret_cb) {
1866 const SSL_CIPHER *pref_cipher = NULL;
1868 * s->session->master_key_length is a size_t, but this is an int for
1869 * backwards compat reasons
1871 int master_key_length;
1873 master_key_length = sizeof(s->session->master_key);
1874 if (s->ext.session_secret_cb(s, s->session->master_key,
1875 &master_key_length, ciphers,
1877 s->ext.session_secret_cb_arg)
1878 && master_key_length > 0) {
1879 s->session->master_key_length = master_key_length;
1881 s->session->ciphers = ciphers;
1882 s->session->verify_result = X509_V_OK;
1886 /* check if some cipher was preferred by call back */
1887 if (pref_cipher == NULL)
1888 pref_cipher = ssl3_choose_cipher(s, s->session->ciphers,
1889 SSL_get_ciphers(s));
1890 if (pref_cipher == NULL) {
1891 SSLfatal(s, SSL_AD_HANDSHAKE_FAILURE,
1892 SSL_F_TLS_EARLY_POST_PROCESS_CLIENT_HELLO,
1893 SSL_R_NO_SHARED_CIPHER);
1897 s->session->cipher = pref_cipher;
1898 sk_SSL_CIPHER_free(s->cipher_list);
1899 s->cipher_list = sk_SSL_CIPHER_dup(s->session->ciphers);
1900 sk_SSL_CIPHER_free(s->cipher_list_by_id);
1901 s->cipher_list_by_id = sk_SSL_CIPHER_dup(s->session->ciphers);
1906 * Worst case, we will use the NULL compression, but if we have other
1907 * options, we will now look for them. We have complen-1 compression
1908 * algorithms from the client, starting at q.
1910 s->s3->tmp.new_compression = NULL;
1911 if (SSL_IS_TLS13(s)) {
1913 * We already checked above that the NULL compression method appears in
1914 * the list. Now we check there aren't any others (which is illegal in
1915 * a TLSv1.3 ClientHello.
1917 if (clienthello->compressions_len != 1) {
1918 SSLfatal(s, SSL_AD_ILLEGAL_PARAMETER,
1919 SSL_F_TLS_EARLY_POST_PROCESS_CLIENT_HELLO,
1920 SSL_R_INVALID_COMPRESSION_ALGORITHM);
1924 #ifndef OPENSSL_NO_COMP
1925 /* This only happens if we have a cache hit */
1926 else if (s->session->compress_meth != 0) {
1927 int m, comp_id = s->session->compress_meth;
1929 /* Perform sanity checks on resumed compression algorithm */
1930 /* Can't disable compression */
1931 if (!ssl_allow_compression(s)) {
1932 SSLfatal(s, SSL_AD_HANDSHAKE_FAILURE,
1933 SSL_F_TLS_EARLY_POST_PROCESS_CLIENT_HELLO,
1934 SSL_R_INCONSISTENT_COMPRESSION);
1937 /* Look for resumed compression method */
1938 for (m = 0; m < sk_SSL_COMP_num(s->ctx->comp_methods); m++) {
1939 comp = sk_SSL_COMP_value(s->ctx->comp_methods, m);
1940 if (comp_id == comp->id) {
1941 s->s3->tmp.new_compression = comp;
1945 if (s->s3->tmp.new_compression == NULL) {
1946 SSLfatal(s, SSL_AD_HANDSHAKE_FAILURE,
1947 SSL_F_TLS_EARLY_POST_PROCESS_CLIENT_HELLO,
1948 SSL_R_INVALID_COMPRESSION_ALGORITHM);
1951 /* Look for resumed method in compression list */
1952 for (k = 0; k < clienthello->compressions_len; k++) {
1953 if (clienthello->compressions[k] == comp_id)
1956 if (k >= clienthello->compressions_len) {
1957 SSLfatal(s, SSL_AD_ILLEGAL_PARAMETER,
1958 SSL_F_TLS_EARLY_POST_PROCESS_CLIENT_HELLO,
1959 SSL_R_REQUIRED_COMPRESSION_ALGORITHM_MISSING);
1962 } else if (s->hit) {
1964 } else if (ssl_allow_compression(s) && s->ctx->comp_methods) {
1965 /* See if we have a match */
1966 int m, nn, v, done = 0;
1969 nn = sk_SSL_COMP_num(s->ctx->comp_methods);
1970 for (m = 0; m < nn; m++) {
1971 comp = sk_SSL_COMP_value(s->ctx->comp_methods, m);
1973 for (o = 0; o < clienthello->compressions_len; o++) {
1974 if (v == clienthello->compressions[o]) {
1983 s->s3->tmp.new_compression = comp;
1989 * If compression is disabled we'd better not try to resume a session
1990 * using compression.
1992 if (s->session->compress_meth != 0) {
1993 SSLfatal(s, SSL_AD_HANDSHAKE_FAILURE,
1994 SSL_F_TLS_EARLY_POST_PROCESS_CLIENT_HELLO,
1995 SSL_R_INCONSISTENT_COMPRESSION);
2001 * Given s->session->ciphers and SSL_get_ciphers, we must pick a cipher
2004 if (!s->hit || SSL_IS_TLS13(s)) {
2005 sk_SSL_CIPHER_free(s->session->ciphers);
2006 s->session->ciphers = ciphers;
2007 if (ciphers == NULL) {
2008 SSLfatal(s, SSL_AD_INTERNAL_ERROR,
2009 SSL_F_TLS_EARLY_POST_PROCESS_CLIENT_HELLO,
2010 ERR_R_INTERNAL_ERROR);
2017 #ifdef OPENSSL_NO_COMP
2018 s->session->compress_meth = 0;
2020 s->session->compress_meth = (comp == NULL) ? 0 : comp->id;
2022 if (!tls1_set_server_sigalgs(s)) {
2023 /* SSLfatal() already called */
2028 sk_SSL_CIPHER_free(ciphers);
2029 sk_SSL_CIPHER_free(scsvs);
2030 OPENSSL_free(clienthello->pre_proc_exts);
2031 OPENSSL_free(s->clienthello);
2032 s->clienthello = NULL;
2035 sk_SSL_CIPHER_free(ciphers);
2036 sk_SSL_CIPHER_free(scsvs);
2037 OPENSSL_free(clienthello->pre_proc_exts);
2038 OPENSSL_free(s->clienthello);
2039 s->clienthello = NULL;
2045 * Call the status request callback if needed. Upon success, returns 1.
2046 * Upon failure, returns 0.
2048 static int tls_handle_status_request(SSL *s)
2050 s->ext.status_expected = 0;
2053 * If status request then ask callback what to do. Note: this must be
2054 * called after servername callbacks in case the certificate has changed,
2055 * and must be called after the cipher has been chosen because this may
2056 * influence which certificate is sent
2058 if (s->ext.status_type != TLSEXT_STATUSTYPE_nothing && s->ctx != NULL
2059 && s->ctx->ext.status_cb != NULL) {
2062 /* If no certificate can't return certificate status */
2063 if (s->s3->tmp.cert != NULL) {
2065 * Set current certificate to one we will use so SSL_get_certificate
2066 * et al can pick it up.
2068 s->cert->key = s->s3->tmp.cert;
2069 ret = s->ctx->ext.status_cb(s, s->ctx->ext.status_arg);
2071 /* We don't want to send a status request response */
2072 case SSL_TLSEXT_ERR_NOACK:
2073 s->ext.status_expected = 0;
2075 /* status request response should be sent */
2076 case SSL_TLSEXT_ERR_OK:
2077 if (s->ext.ocsp.resp)
2078 s->ext.status_expected = 1;
2080 /* something bad happened */
2081 case SSL_TLSEXT_ERR_ALERT_FATAL:
2083 SSLfatal(s, SSL_AD_INTERNAL_ERROR,
2084 SSL_F_TLS_HANDLE_STATUS_REQUEST,
2085 SSL_R_CLIENTHELLO_TLSEXT);
2095 * Call the alpn_select callback if needed. Upon success, returns 1.
2096 * Upon failure, returns 0.
2098 int tls_handle_alpn(SSL *s)
2100 const unsigned char *selected = NULL;
2101 unsigned char selected_len = 0;
2103 if (s->ctx->ext.alpn_select_cb != NULL && s->s3->alpn_proposed != NULL) {
2104 int r = s->ctx->ext.alpn_select_cb(s, &selected, &selected_len,
2105 s->s3->alpn_proposed,
2106 (unsigned int)s->s3->alpn_proposed_len,
2107 s->ctx->ext.alpn_select_cb_arg);
2109 if (r == SSL_TLSEXT_ERR_OK) {
2110 OPENSSL_free(s->s3->alpn_selected);
2111 s->s3->alpn_selected = OPENSSL_memdup(selected, selected_len);
2112 if (s->s3->alpn_selected == NULL) {
2113 SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_F_TLS_HANDLE_ALPN,
2114 ERR_R_INTERNAL_ERROR);
2117 s->s3->alpn_selected_len = selected_len;
2118 #ifndef OPENSSL_NO_NEXTPROTONEG
2119 /* ALPN takes precedence over NPN. */
2120 s->s3->npn_seen = 0;
2123 /* Check ALPN is consistent with session */
2124 if (s->session->ext.alpn_selected == NULL
2125 || selected_len != s->session->ext.alpn_selected_len
2126 || memcmp(selected, s->session->ext.alpn_selected,
2127 selected_len) != 0) {
2128 /* Not consistent so can't be used for early_data */
2129 s->ext.early_data_ok = 0;
2133 * This is a new session and so alpn_selected should have
2134 * been initialised to NULL. We should update it with the
2137 if (!ossl_assert(s->session->ext.alpn_selected == NULL)) {
2138 SSLfatal(s, SSL_AD_INTERNAL_ERROR,
2139 SSL_F_TLS_HANDLE_ALPN,
2140 ERR_R_INTERNAL_ERROR);
2143 s->session->ext.alpn_selected = OPENSSL_memdup(selected,
2145 if (s->session->ext.alpn_selected == NULL) {
2146 SSLfatal(s, SSL_AD_INTERNAL_ERROR,
2147 SSL_F_TLS_HANDLE_ALPN,
2148 ERR_R_INTERNAL_ERROR);
2151 s->session->ext.alpn_selected_len = selected_len;
2156 } else if (r != SSL_TLSEXT_ERR_NOACK) {
2157 SSLfatal(s, SSL_AD_NO_APPLICATION_PROTOCOL, SSL_F_TLS_HANDLE_ALPN,
2158 SSL_R_NO_APPLICATION_PROTOCOL);
2162 * If r == SSL_TLSEXT_ERR_NOACK then behave as if no callback was
2167 /* Check ALPN is consistent with session */
2168 if (s->session->ext.alpn_selected != NULL) {
2169 /* Not consistent so can't be used for early_data */
2170 s->ext.early_data_ok = 0;
2176 WORK_STATE tls_post_process_client_hello(SSL *s, WORK_STATE wst)
2178 const SSL_CIPHER *cipher;
2180 if (wst == WORK_MORE_A) {
2181 int rv = tls_early_post_process_client_hello(s);
2183 /* SSLfatal() was already called */
2190 if (wst == WORK_MORE_B) {
2191 if (!s->hit || SSL_IS_TLS13(s)) {
2192 /* Let cert callback update server certificates if required */
2193 if (!s->hit && s->cert->cert_cb != NULL) {
2194 int rv = s->cert->cert_cb(s, s->cert->cert_cb_arg);
2196 SSLfatal(s, SSL_AD_INTERNAL_ERROR,
2197 SSL_F_TLS_POST_PROCESS_CLIENT_HELLO,
2198 SSL_R_CERT_CB_ERROR);
2202 s->rwstate = SSL_X509_LOOKUP;
2205 s->rwstate = SSL_NOTHING;
2208 /* In TLSv1.3 we selected the ciphersuite before resumption */
2209 if (!SSL_IS_TLS13(s)) {
2211 ssl3_choose_cipher(s, s->session->ciphers, SSL_get_ciphers(s));
2213 if (cipher == NULL) {
2214 SSLfatal(s, SSL_AD_HANDSHAKE_FAILURE,
2215 SSL_F_TLS_POST_PROCESS_CLIENT_HELLO,
2216 SSL_R_NO_SHARED_CIPHER);
2219 s->s3->tmp.new_cipher = cipher;
2222 if (!tls_choose_sigalg(s, 1)) {
2223 /* SSLfatal already called */
2226 /* check whether we should disable session resumption */
2227 if (s->not_resumable_session_cb != NULL)
2228 s->session->not_resumable =
2229 s->not_resumable_session_cb(s,
2230 ((s->s3->tmp.new_cipher->algorithm_mkey
2231 & (SSL_kDHE | SSL_kECDHE)) != 0));
2232 if (s->session->not_resumable)
2233 /* do not send a session ticket */
2234 s->ext.ticket_expected = 0;
2237 /* Session-id reuse */
2238 s->s3->tmp.new_cipher = s->session->cipher;
2242 * we now have the following setup.
2244 * cipher_list - our preferred list of ciphers
2245 * ciphers - the clients preferred list of ciphers
2246 * compression - basically ignored right now
2247 * ssl version is set - sslv3
2248 * s->session - The ssl session has been setup.
2249 * s->hit - session reuse flag
2250 * s->s3->tmp.new_cipher- the new cipher to use.
2254 * Call status_request callback if needed. Has to be done after the
2255 * certificate callbacks etc above.
2257 if (!tls_handle_status_request(s)) {
2258 /* SSLfatal() already called */
2262 * Call alpn_select callback if needed. Has to be done after SNI and
2263 * cipher negotiation (HTTP/2 restricts permitted ciphers). In TLSv1.3
2264 * we already did this because cipher negotiation happens earlier, and
2265 * we must handle ALPN before we decide whether to accept early_data.
2267 if (!SSL_IS_TLS13(s) && !tls_handle_alpn(s)) {
2268 /* SSLfatal() already called */
2274 #ifndef OPENSSL_NO_SRP
2275 if (wst == WORK_MORE_C) {
2277 if ((ret = ssl_check_srp_ext_ClientHello(s)) == 0) {
2279 * callback indicates further work to be done
2281 s->rwstate = SSL_X509_LOOKUP;
2285 /* SSLfatal() already called */
2291 return WORK_FINISHED_STOP;
2296 int tls_construct_server_hello(SSL *s, WPACKET *pkt)
2301 unsigned char *session_id;
2302 int usetls13 = SSL_IS_TLS13(s) || s->hello_retry_request == SSL_HRR_PENDING;
2304 version = usetls13 ? TLS1_2_VERSION : s->version;
2305 if (!WPACKET_put_bytes_u16(pkt, version)
2307 * Random stuff. Filling of the server_random takes place in
2308 * tls_process_client_hello()
2310 || !WPACKET_memcpy(pkt,
2311 s->hello_retry_request == SSL_HRR_PENDING
2312 ? hrrrandom : s->s3->server_random,
2313 SSL3_RANDOM_SIZE)) {
2314 SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_F_TLS_CONSTRUCT_SERVER_HELLO,
2315 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, SSL_F_TLS_CONSTRUCT_SERVER_HELLO,
2352 ERR_R_INTERNAL_ERROR);
2356 /* set up the compression method */
2357 #ifdef OPENSSL_NO_COMP
2360 if (usetls13 || s->s3->tmp.new_compression == NULL)
2363 compm = s->s3->tmp.new_compression->id;
2366 if (!WPACKET_sub_memcpy_u8(pkt, session_id, sl)
2367 || !s->method->put_cipher_by_char(s->s3->tmp.new_cipher, pkt, &len)
2368 || !WPACKET_put_bytes_u8(pkt, compm)
2369 || !tls_construct_extensions(s, pkt,
2370 s->hello_retry_request
2372 ? SSL_EXT_TLS1_3_HELLO_RETRY_REQUEST
2374 ? SSL_EXT_TLS1_3_SERVER_HELLO
2375 : SSL_EXT_TLS1_2_SERVER_HELLO),
2377 /* SSLfatal() already called */
2381 if (s->hello_retry_request == SSL_HRR_PENDING) {
2382 /* Ditch the session. We'll create a new one next time around */
2383 SSL_SESSION_free(s->session);
2388 * Re-initialise the Transcript Hash. We're going to prepopulate it with
2389 * a synthetic message_hash in place of ClientHello1.
2391 if (!create_synthetic_message_hash(s, NULL, 0, NULL, 0)) {
2392 /* SSLfatal() already called */
2395 } else if (!(s->verify_mode & SSL_VERIFY_PEER)
2396 && !ssl3_digest_cached_records(s, 0)) {
2397 /* SSLfatal() already called */;
2404 int tls_construct_server_done(SSL *s, WPACKET *pkt)
2406 if (!s->s3->tmp.cert_request) {
2407 if (!ssl3_digest_cached_records(s, 0)) {
2408 /* SSLfatal() already called */
2415 int tls_construct_server_key_exchange(SSL *s, WPACKET *pkt)
2417 #ifndef OPENSSL_NO_DH
2418 EVP_PKEY *pkdh = NULL;
2420 #ifndef OPENSSL_NO_EC
2421 unsigned char *encodedPoint = NULL;
2422 size_t encodedlen = 0;
2425 const SIGALG_LOOKUP *lu = s->s3->tmp.sigalg;
2429 EVP_MD_CTX *md_ctx = EVP_MD_CTX_new();
2430 EVP_PKEY_CTX *pctx = NULL;
2431 size_t paramlen, paramoffset;
2433 if (!WPACKET_get_total_written(pkt, ¶moffset)) {
2434 SSLfatal(s, SSL_AD_INTERNAL_ERROR,
2435 SSL_F_TLS_CONSTRUCT_SERVER_KEY_EXCHANGE, ERR_R_INTERNAL_ERROR);
2439 if (md_ctx == NULL) {
2440 SSLfatal(s, SSL_AD_INTERNAL_ERROR,
2441 SSL_F_TLS_CONSTRUCT_SERVER_KEY_EXCHANGE, ERR_R_MALLOC_FAILURE);
2445 type = s->s3->tmp.new_cipher->algorithm_mkey;
2447 r[0] = r[1] = r[2] = r[3] = NULL;
2448 #ifndef OPENSSL_NO_PSK
2449 /* Plain PSK or RSAPSK nothing to do */
2450 if (type & (SSL_kPSK | SSL_kRSAPSK)) {
2452 #endif /* !OPENSSL_NO_PSK */
2453 #ifndef OPENSSL_NO_DH
2454 if (type & (SSL_kDHE | SSL_kDHEPSK)) {
2455 CERT *cert = s->cert;
2457 EVP_PKEY *pkdhp = NULL;
2460 if (s->cert->dh_tmp_auto) {
2461 DH *dhp = ssl_get_auto_dh(s);
2462 pkdh = EVP_PKEY_new();
2463 if (pkdh == NULL || dhp == NULL) {
2465 SSLfatal(s, SSL_AD_INTERNAL_ERROR,
2466 SSL_F_TLS_CONSTRUCT_SERVER_KEY_EXCHANGE,
2467 ERR_R_INTERNAL_ERROR);
2470 EVP_PKEY_assign_DH(pkdh, dhp);
2473 pkdhp = cert->dh_tmp;
2475 if ((pkdhp == NULL) && (s->cert->dh_tmp_cb != NULL)) {
2476 DH *dhp = s->cert->dh_tmp_cb(s, 0, 1024);
2477 pkdh = ssl_dh_to_pkey(dhp);
2479 SSLfatal(s, SSL_AD_INTERNAL_ERROR,
2480 SSL_F_TLS_CONSTRUCT_SERVER_KEY_EXCHANGE,
2481 ERR_R_INTERNAL_ERROR);
2486 if (pkdhp == NULL) {
2487 SSLfatal(s, SSL_AD_INTERNAL_ERROR,
2488 SSL_F_TLS_CONSTRUCT_SERVER_KEY_EXCHANGE,
2489 SSL_R_MISSING_TMP_DH_KEY);
2492 if (!ssl_security(s, SSL_SECOP_TMP_DH,
2493 EVP_PKEY_security_bits(pkdhp), 0, pkdhp)) {
2494 SSLfatal(s, SSL_AD_HANDSHAKE_FAILURE,
2495 SSL_F_TLS_CONSTRUCT_SERVER_KEY_EXCHANGE,
2496 SSL_R_DH_KEY_TOO_SMALL);
2499 if (s->s3->tmp.pkey != NULL) {
2500 SSLfatal(s, SSL_AD_INTERNAL_ERROR,
2501 SSL_F_TLS_CONSTRUCT_SERVER_KEY_EXCHANGE,
2502 ERR_R_INTERNAL_ERROR);
2506 s->s3->tmp.pkey = ssl_generate_pkey(pkdhp);
2507 if (s->s3->tmp.pkey == NULL) {
2508 /* SSLfatal() already called */
2512 dh = EVP_PKEY_get0_DH(s->s3->tmp.pkey);
2514 SSLfatal(s, SSL_AD_INTERNAL_ERROR,
2515 SSL_F_TLS_CONSTRUCT_SERVER_KEY_EXCHANGE,
2516 ERR_R_INTERNAL_ERROR);
2520 EVP_PKEY_free(pkdh);
2523 DH_get0_pqg(dh, &r[0], NULL, &r[1]);
2524 DH_get0_key(dh, &r[2], NULL);
2527 #ifndef OPENSSL_NO_EC
2528 if (type & (SSL_kECDHE | SSL_kECDHEPSK)) {
2530 if (s->s3->tmp.pkey != NULL) {
2531 SSLfatal(s, SSL_AD_INTERNAL_ERROR,
2532 SSL_F_TLS_CONSTRUCT_SERVER_KEY_EXCHANGE,
2533 ERR_R_INTERNAL_ERROR);
2537 /* Get NID of appropriate shared curve */
2538 curve_id = tls1_shared_group(s, -2);
2539 if (curve_id == 0) {
2540 SSLfatal(s, SSL_AD_HANDSHAKE_FAILURE,
2541 SSL_F_TLS_CONSTRUCT_SERVER_KEY_EXCHANGE,
2542 SSL_R_UNSUPPORTED_ELLIPTIC_CURVE);
2545 s->s3->tmp.pkey = ssl_generate_pkey_group(s, curve_id);
2546 /* Generate a new key for this curve */
2547 if (s->s3->tmp.pkey == NULL) {
2548 /* SSLfatal() already called */
2552 /* Encode the public key. */
2553 encodedlen = EVP_PKEY_get1_tls_encodedpoint(s->s3->tmp.pkey,
2555 if (encodedlen == 0) {
2556 SSLfatal(s, SSL_AD_INTERNAL_ERROR,
2557 SSL_F_TLS_CONSTRUCT_SERVER_KEY_EXCHANGE, ERR_R_EC_LIB);
2562 * We'll generate the serverKeyExchange message explicitly so we
2563 * can set these to NULLs
2570 #endif /* !OPENSSL_NO_EC */
2571 #ifndef OPENSSL_NO_SRP
2572 if (type & SSL_kSRP) {
2573 if ((s->srp_ctx.N == NULL) ||
2574 (s->srp_ctx.g == NULL) ||
2575 (s->srp_ctx.s == NULL) || (s->srp_ctx.B == NULL)) {
2576 SSLfatal(s, SSL_AD_INTERNAL_ERROR,
2577 SSL_F_TLS_CONSTRUCT_SERVER_KEY_EXCHANGE,
2578 SSL_R_MISSING_SRP_PARAM);
2581 r[0] = s->srp_ctx.N;
2582 r[1] = s->srp_ctx.g;
2583 r[2] = s->srp_ctx.s;
2584 r[3] = s->srp_ctx.B;
2588 SSLfatal(s, SSL_AD_INTERNAL_ERROR,
2589 SSL_F_TLS_CONSTRUCT_SERVER_KEY_EXCHANGE,
2590 SSL_R_UNKNOWN_KEY_EXCHANGE_TYPE);
2594 if (((s->s3->tmp.new_cipher->algorithm_auth & (SSL_aNULL | SSL_aSRP)) != 0)
2595 || ((s->s3->tmp.new_cipher->algorithm_mkey & SSL_PSK)) != 0) {
2597 } else if (lu == NULL) {
2598 SSLfatal(s, SSL_AD_DECODE_ERROR,
2599 SSL_F_TLS_CONSTRUCT_SERVER_KEY_EXCHANGE, ERR_R_INTERNAL_ERROR);
2603 #ifndef OPENSSL_NO_PSK
2604 if (type & SSL_PSK) {
2605 size_t len = (s->cert->psk_identity_hint == NULL)
2606 ? 0 : strlen(s->cert->psk_identity_hint);
2609 * It should not happen that len > PSK_MAX_IDENTITY_LEN - we already
2610 * checked this when we set the identity hint - but just in case
2612 if (len > PSK_MAX_IDENTITY_LEN
2613 || !WPACKET_sub_memcpy_u16(pkt, s->cert->psk_identity_hint,
2615 SSLfatal(s, SSL_AD_INTERNAL_ERROR,
2616 SSL_F_TLS_CONSTRUCT_SERVER_KEY_EXCHANGE,
2617 ERR_R_INTERNAL_ERROR);
2623 for (i = 0; i < 4 && r[i] != NULL; i++) {
2624 unsigned char *binval;
2627 #ifndef OPENSSL_NO_SRP
2628 if ((i == 2) && (type & SSL_kSRP)) {
2629 res = WPACKET_start_sub_packet_u8(pkt);
2632 res = WPACKET_start_sub_packet_u16(pkt);
2635 SSLfatal(s, SSL_AD_INTERNAL_ERROR,
2636 SSL_F_TLS_CONSTRUCT_SERVER_KEY_EXCHANGE,
2637 ERR_R_INTERNAL_ERROR);
2641 #ifndef OPENSSL_NO_DH
2643 * for interoperability with some versions of the Microsoft TLS
2644 * stack, we need to zero pad the DHE pub key to the same length
2647 if ((i == 2) && (type & (SSL_kDHE | SSL_kDHEPSK))) {
2648 size_t len = BN_num_bytes(r[0]) - BN_num_bytes(r[2]);
2651 if (!WPACKET_allocate_bytes(pkt, len, &binval)) {
2652 SSLfatal(s, SSL_AD_INTERNAL_ERROR,
2653 SSL_F_TLS_CONSTRUCT_SERVER_KEY_EXCHANGE,
2654 ERR_R_INTERNAL_ERROR);
2657 memset(binval, 0, len);
2661 if (!WPACKET_allocate_bytes(pkt, BN_num_bytes(r[i]), &binval)
2662 || !WPACKET_close(pkt)) {
2663 SSLfatal(s, SSL_AD_INTERNAL_ERROR,
2664 SSL_F_TLS_CONSTRUCT_SERVER_KEY_EXCHANGE,
2665 ERR_R_INTERNAL_ERROR);
2669 BN_bn2bin(r[i], binval);
2672 #ifndef OPENSSL_NO_EC
2673 if (type & (SSL_kECDHE | SSL_kECDHEPSK)) {
2675 * We only support named (not generic) curves. In this situation, the
2676 * ServerKeyExchange message has: [1 byte CurveType], [2 byte CurveName]
2677 * [1 byte length of encoded point], followed by the actual encoded
2680 if (!WPACKET_put_bytes_u8(pkt, NAMED_CURVE_TYPE)
2681 || !WPACKET_put_bytes_u8(pkt, 0)
2682 || !WPACKET_put_bytes_u8(pkt, curve_id)
2683 || !WPACKET_sub_memcpy_u8(pkt, encodedPoint, encodedlen)) {
2684 SSLfatal(s, SSL_AD_INTERNAL_ERROR,
2685 SSL_F_TLS_CONSTRUCT_SERVER_KEY_EXCHANGE,
2686 ERR_R_INTERNAL_ERROR);
2689 OPENSSL_free(encodedPoint);
2690 encodedPoint = NULL;
2696 EVP_PKEY *pkey = s->s3->tmp.cert->privatekey;
2698 unsigned char *sigbytes1, *sigbytes2, *tbs;
2699 size_t siglen, tbslen;
2702 if (pkey == NULL || !tls1_lookup_md(lu, &md)) {
2703 /* Should never happen */
2704 SSLfatal(s, SSL_AD_INTERNAL_ERROR,
2705 SSL_F_TLS_CONSTRUCT_SERVER_KEY_EXCHANGE,
2706 ERR_R_INTERNAL_ERROR);
2709 /* Get length of the parameters we have written above */
2710 if (!WPACKET_get_length(pkt, ¶mlen)) {
2711 SSLfatal(s, SSL_AD_INTERNAL_ERROR,
2712 SSL_F_TLS_CONSTRUCT_SERVER_KEY_EXCHANGE,
2713 ERR_R_INTERNAL_ERROR);
2716 /* send signature algorithm */
2717 if (SSL_USE_SIGALGS(s) && !WPACKET_put_bytes_u16(pkt, lu->sigalg)) {
2718 SSLfatal(s, SSL_AD_INTERNAL_ERROR,
2719 SSL_F_TLS_CONSTRUCT_SERVER_KEY_EXCHANGE,
2720 ERR_R_INTERNAL_ERROR);
2724 * Create the signature. We don't know the actual length of the sig
2725 * until after we've created it, so we reserve enough bytes for it
2726 * up front, and then properly allocate them in the WPACKET
2729 siglen = EVP_PKEY_size(pkey);
2730 if (!WPACKET_sub_reserve_bytes_u16(pkt, siglen, &sigbytes1)
2731 || EVP_DigestSignInit(md_ctx, &pctx, md, NULL, pkey) <= 0) {
2732 SSLfatal(s, SSL_AD_INTERNAL_ERROR,
2733 SSL_F_TLS_CONSTRUCT_SERVER_KEY_EXCHANGE,
2734 ERR_R_INTERNAL_ERROR);
2737 if (lu->sig == EVP_PKEY_RSA_PSS) {
2738 if (EVP_PKEY_CTX_set_rsa_padding(pctx, RSA_PKCS1_PSS_PADDING) <= 0
2739 || EVP_PKEY_CTX_set_rsa_pss_saltlen(pctx, RSA_PSS_SALTLEN_DIGEST) <= 0) {
2740 SSLfatal(s, SSL_AD_INTERNAL_ERROR,
2741 SSL_F_TLS_CONSTRUCT_SERVER_KEY_EXCHANGE,
2746 tbslen = construct_key_exchange_tbs(s, &tbs,
2747 s->init_buf->data + paramoffset,
2750 /* SSLfatal() already called */
2753 rv = EVP_DigestSign(md_ctx, sigbytes1, &siglen, tbs, tbslen);
2755 if (rv <= 0 || !WPACKET_sub_allocate_bytes_u16(pkt, siglen, &sigbytes2)
2756 || sigbytes1 != sigbytes2) {
2757 SSLfatal(s, SSL_AD_INTERNAL_ERROR,
2758 SSL_F_TLS_CONSTRUCT_SERVER_KEY_EXCHANGE,
2759 ERR_R_INTERNAL_ERROR);
2764 EVP_MD_CTX_free(md_ctx);
2767 #ifndef OPENSSL_NO_DH
2768 EVP_PKEY_free(pkdh);
2770 #ifndef OPENSSL_NO_EC
2771 OPENSSL_free(encodedPoint);
2773 EVP_MD_CTX_free(md_ctx);
2777 int tls_construct_certificate_request(SSL *s, WPACKET *pkt)
2779 if (SSL_IS_TLS13(s)) {
2780 /* Send random context when doing post-handshake auth */
2781 if (s->post_handshake_auth == SSL_PHA_REQUEST_PENDING) {
2782 OPENSSL_free(s->pha_context);
2783 s->pha_context_len = 32;
2784 if ((s->pha_context = OPENSSL_malloc(s->pha_context_len)) == NULL
2785 || RAND_bytes(s->pha_context, s->pha_context_len) <= 0
2786 || !WPACKET_sub_memcpy_u8(pkt, s->pha_context, s->pha_context_len)) {
2787 SSLfatal(s, SSL_AD_INTERNAL_ERROR,
2788 SSL_F_TLS_CONSTRUCT_CERTIFICATE_REQUEST,
2789 ERR_R_INTERNAL_ERROR);
2792 /* reset the handshake hash back to just after the ClientFinished */
2793 if (!tls13_restore_handshake_digest_for_pha(s)) {
2794 /* SSLfatal() already called */
2798 if (!WPACKET_put_bytes_u8(pkt, 0)) {
2799 SSLfatal(s, SSL_AD_INTERNAL_ERROR,
2800 SSL_F_TLS_CONSTRUCT_CERTIFICATE_REQUEST,
2801 ERR_R_INTERNAL_ERROR);
2806 if (!tls_construct_extensions(s, pkt,
2807 SSL_EXT_TLS1_3_CERTIFICATE_REQUEST, NULL,
2809 /* SSLfatal() already called */
2815 /* get the list of acceptable cert types */
2816 if (!WPACKET_start_sub_packet_u8(pkt)
2817 || !ssl3_get_req_cert_type(s, pkt) || !WPACKET_close(pkt)) {
2818 SSLfatal(s, SSL_AD_INTERNAL_ERROR,
2819 SSL_F_TLS_CONSTRUCT_CERTIFICATE_REQUEST, ERR_R_INTERNAL_ERROR);
2823 if (SSL_USE_SIGALGS(s)) {
2824 const uint16_t *psigs;
2825 size_t nl = tls12_get_psigalgs(s, 1, &psigs);
2827 if (!WPACKET_start_sub_packet_u16(pkt)
2828 || !WPACKET_set_flags(pkt, WPACKET_FLAGS_NON_ZERO_LENGTH)
2829 || !tls12_copy_sigalgs(s, pkt, psigs, nl)
2830 || !WPACKET_close(pkt)) {
2831 SSLfatal(s, SSL_AD_INTERNAL_ERROR,
2832 SSL_F_TLS_CONSTRUCT_CERTIFICATE_REQUEST,
2833 ERR_R_INTERNAL_ERROR);
2838 if (!construct_ca_names(s, pkt)) {
2839 /* SSLfatal() already called */
2845 s->s3->tmp.cert_request = 1;
2849 static int tls_process_cke_psk_preamble(SSL *s, PACKET *pkt)
2851 #ifndef OPENSSL_NO_PSK
2852 unsigned char psk[PSK_MAX_PSK_LEN];
2854 PACKET psk_identity;
2856 if (!PACKET_get_length_prefixed_2(pkt, &psk_identity)) {
2857 SSLfatal(s, SSL_AD_DECODE_ERROR, SSL_F_TLS_PROCESS_CKE_PSK_PREAMBLE,
2858 SSL_R_LENGTH_MISMATCH);
2861 if (PACKET_remaining(&psk_identity) > PSK_MAX_IDENTITY_LEN) {
2862 SSLfatal(s, SSL_AD_DECODE_ERROR, SSL_F_TLS_PROCESS_CKE_PSK_PREAMBLE,
2863 SSL_R_DATA_LENGTH_TOO_LONG);
2866 if (s->psk_server_callback == NULL) {
2867 SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_F_TLS_PROCESS_CKE_PSK_PREAMBLE,
2868 SSL_R_PSK_NO_SERVER_CB);
2872 if (!PACKET_strndup(&psk_identity, &s->session->psk_identity)) {
2873 SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_F_TLS_PROCESS_CKE_PSK_PREAMBLE,
2874 ERR_R_INTERNAL_ERROR);
2878 psklen = s->psk_server_callback(s, s->session->psk_identity,
2881 if (psklen > PSK_MAX_PSK_LEN) {
2882 SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_F_TLS_PROCESS_CKE_PSK_PREAMBLE,
2883 ERR_R_INTERNAL_ERROR);
2885 } else if (psklen == 0) {
2887 * PSK related to the given identity not found
2889 SSLfatal(s, SSL_AD_UNKNOWN_PSK_IDENTITY,
2890 SSL_F_TLS_PROCESS_CKE_PSK_PREAMBLE,
2891 SSL_R_PSK_IDENTITY_NOT_FOUND);
2895 OPENSSL_free(s->s3->tmp.psk);
2896 s->s3->tmp.psk = OPENSSL_memdup(psk, psklen);
2897 OPENSSL_cleanse(psk, psklen);
2899 if (s->s3->tmp.psk == NULL) {
2900 SSLfatal(s, SSL_AD_INTERNAL_ERROR,
2901 SSL_F_TLS_PROCESS_CKE_PSK_PREAMBLE, ERR_R_MALLOC_FAILURE);
2905 s->s3->tmp.psklen = psklen;
2909 /* Should never happen */
2910 SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_F_TLS_PROCESS_CKE_PSK_PREAMBLE,
2911 ERR_R_INTERNAL_ERROR);
2916 static int tls_process_cke_rsa(SSL *s, PACKET *pkt)
2918 #ifndef OPENSSL_NO_RSA
2919 unsigned char rand_premaster_secret[SSL_MAX_MASTER_KEY_LENGTH];
2921 unsigned char decrypt_good, version_good;
2922 size_t j, padding_len;
2923 PACKET enc_premaster;
2925 unsigned char *rsa_decrypt = NULL;
2928 rsa = EVP_PKEY_get0_RSA(s->cert->pkeys[SSL_PKEY_RSA].privatekey);
2930 SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_F_TLS_PROCESS_CKE_RSA,
2931 SSL_R_MISSING_RSA_CERTIFICATE);
2935 /* SSLv3 and pre-standard DTLS omit the length bytes. */
2936 if (s->version == SSL3_VERSION || s->version == DTLS1_BAD_VER) {
2937 enc_premaster = *pkt;
2939 if (!PACKET_get_length_prefixed_2(pkt, &enc_premaster)
2940 || PACKET_remaining(pkt) != 0) {
2941 SSLfatal(s, SSL_AD_DECODE_ERROR, SSL_F_TLS_PROCESS_CKE_RSA,
2942 SSL_R_LENGTH_MISMATCH);
2948 * We want to be sure that the plaintext buffer size makes it safe to
2949 * iterate over the entire size of a premaster secret
2950 * (SSL_MAX_MASTER_KEY_LENGTH). Reject overly short RSA keys because
2951 * their ciphertext cannot accommodate a premaster secret anyway.
2953 if (RSA_size(rsa) < SSL_MAX_MASTER_KEY_LENGTH) {
2954 SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_F_TLS_PROCESS_CKE_RSA,
2955 RSA_R_KEY_SIZE_TOO_SMALL);
2959 rsa_decrypt = OPENSSL_malloc(RSA_size(rsa));
2960 if (rsa_decrypt == NULL) {
2961 SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_F_TLS_PROCESS_CKE_RSA,
2962 ERR_R_MALLOC_FAILURE);
2967 * We must not leak whether a decryption failure occurs because of
2968 * Bleichenbacher's attack on PKCS #1 v1.5 RSA padding (see RFC 2246,
2969 * section 7.4.7.1). The code follows that advice of the TLS RFC and
2970 * generates a random premaster secret for the case that the decrypt
2971 * fails. See https://tools.ietf.org/html/rfc5246#section-7.4.7.1
2974 if (RAND_priv_bytes(rand_premaster_secret,
2975 sizeof(rand_premaster_secret)) <= 0) {
2976 SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_F_TLS_PROCESS_CKE_RSA,
2977 ERR_R_INTERNAL_ERROR);
2982 * Decrypt with no padding. PKCS#1 padding will be removed as part of
2983 * the timing-sensitive code below.
2985 /* TODO(size_t): Convert this function */
2986 decrypt_len = (int)RSA_private_decrypt((int)PACKET_remaining(&enc_premaster),
2987 PACKET_data(&enc_premaster),
2988 rsa_decrypt, rsa, RSA_NO_PADDING);
2989 if (decrypt_len < 0) {
2990 SSLfatal(s, SSL_AD_DECRYPT_ERROR, SSL_F_TLS_PROCESS_CKE_RSA,
2991 ERR_R_INTERNAL_ERROR);
2995 /* Check the padding. See RFC 3447, section 7.2.2. */
2998 * The smallest padded premaster is 11 bytes of overhead. Small keys
2999 * are publicly invalid, so this may return immediately. This ensures
3000 * PS is at least 8 bytes.
3002 if (decrypt_len < 11 + SSL_MAX_MASTER_KEY_LENGTH) {
3003 SSLfatal(s, SSL_AD_DECRYPT_ERROR, SSL_F_TLS_PROCESS_CKE_RSA,
3004 SSL_R_DECRYPTION_FAILED);
3008 padding_len = decrypt_len - SSL_MAX_MASTER_KEY_LENGTH;
3009 decrypt_good = constant_time_eq_int_8(rsa_decrypt[0], 0) &
3010 constant_time_eq_int_8(rsa_decrypt[1], 2);
3011 for (j = 2; j < padding_len - 1; j++) {
3012 decrypt_good &= ~constant_time_is_zero_8(rsa_decrypt[j]);
3014 decrypt_good &= constant_time_is_zero_8(rsa_decrypt[padding_len - 1]);
3017 * If the version in the decrypted pre-master secret is correct then
3018 * version_good will be 0xff, otherwise it'll be zero. The
3019 * Klima-Pokorny-Rosa extension of Bleichenbacher's attack
3020 * (http://eprint.iacr.org/2003/052/) exploits the version number
3021 * check as a "bad version oracle". Thus version checks are done in
3022 * constant time and are treated like any other decryption error.
3025 constant_time_eq_8(rsa_decrypt[padding_len],
3026 (unsigned)(s->client_version >> 8));
3028 constant_time_eq_8(rsa_decrypt[padding_len + 1],
3029 (unsigned)(s->client_version & 0xff));
3032 * The premaster secret must contain the same version number as the
3033 * ClientHello to detect version rollback attacks (strangely, the
3034 * protocol does not offer such protection for DH ciphersuites).
3035 * However, buggy clients exist that send the negotiated protocol
3036 * version instead if the server does not support the requested
3037 * protocol version. If SSL_OP_TLS_ROLLBACK_BUG is set, tolerate such
3040 if (s->options & SSL_OP_TLS_ROLLBACK_BUG) {
3041 unsigned char workaround_good;
3042 workaround_good = constant_time_eq_8(rsa_decrypt[padding_len],
3043 (unsigned)(s->version >> 8));
3045 constant_time_eq_8(rsa_decrypt[padding_len + 1],
3046 (unsigned)(s->version & 0xff));
3047 version_good |= workaround_good;
3051 * Both decryption and version must be good for decrypt_good to
3052 * remain non-zero (0xff).
3054 decrypt_good &= version_good;
3057 * Now copy rand_premaster_secret over from p using
3058 * decrypt_good_mask. If decryption failed, then p does not
3059 * contain valid plaintext, however, a check above guarantees
3060 * it is still sufficiently large to read from.
3062 for (j = 0; j < sizeof(rand_premaster_secret); j++) {
3063 rsa_decrypt[padding_len + j] =
3064 constant_time_select_8(decrypt_good,
3065 rsa_decrypt[padding_len + j],
3066 rand_premaster_secret[j]);
3069 if (!ssl_generate_master_secret(s, rsa_decrypt + padding_len,
3070 sizeof(rand_premaster_secret), 0)) {
3071 /* SSLfatal() already called */
3077 OPENSSL_free(rsa_decrypt);
3080 /* Should never happen */
3081 SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_F_TLS_PROCESS_CKE_RSA,
3082 ERR_R_INTERNAL_ERROR);
3087 static int tls_process_cke_dhe(SSL *s, PACKET *pkt)
3089 #ifndef OPENSSL_NO_DH
3090 EVP_PKEY *skey = NULL;
3094 const unsigned char *data;
3095 EVP_PKEY *ckey = NULL;
3098 if (!PACKET_get_net_2(pkt, &i) || PACKET_remaining(pkt) != i) {
3099 SSLfatal(s, SSL_AD_DECODE_ERROR, SSL_F_TLS_PROCESS_CKE_DHE,
3100 SSL_R_DH_PUBLIC_VALUE_LENGTH_IS_WRONG);
3103 skey = s->s3->tmp.pkey;
3105 SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_F_TLS_PROCESS_CKE_DHE,
3106 SSL_R_MISSING_TMP_DH_KEY);
3110 if (PACKET_remaining(pkt) == 0L) {
3111 SSLfatal(s, SSL_AD_DECODE_ERROR, SSL_F_TLS_PROCESS_CKE_DHE,
3112 SSL_R_MISSING_TMP_DH_KEY);
3115 if (!PACKET_get_bytes(pkt, &data, i)) {
3116 /* We already checked we have enough data */
3117 SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_F_TLS_PROCESS_CKE_DHE,
3118 ERR_R_INTERNAL_ERROR);
3121 ckey = EVP_PKEY_new();
3122 if (ckey == NULL || EVP_PKEY_copy_parameters(ckey, skey) == 0) {
3123 SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_F_TLS_PROCESS_CKE_DHE,
3127 cdh = EVP_PKEY_get0_DH(ckey);
3128 pub_key = BN_bin2bn(data, i, NULL);
3130 if (pub_key == NULL || !DH_set0_key(cdh, pub_key, NULL)) {
3131 SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_F_TLS_PROCESS_CKE_DHE,
3132 ERR_R_INTERNAL_ERROR);
3133 if (pub_key != NULL)
3138 if (ssl_derive(s, skey, ckey, 1) == 0) {
3139 /* SSLfatal() already called */
3144 EVP_PKEY_free(s->s3->tmp.pkey);
3145 s->s3->tmp.pkey = NULL;
3147 EVP_PKEY_free(ckey);
3150 /* Should never happen */
3151 SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_F_TLS_PROCESS_CKE_DHE,
3152 ERR_R_INTERNAL_ERROR);
3157 static int tls_process_cke_ecdhe(SSL *s, PACKET *pkt)
3159 #ifndef OPENSSL_NO_EC
3160 EVP_PKEY *skey = s->s3->tmp.pkey;
3161 EVP_PKEY *ckey = NULL;
3164 if (PACKET_remaining(pkt) == 0L) {
3165 /* We don't support ECDH client auth */
3166 SSLfatal(s, SSL_AD_HANDSHAKE_FAILURE, SSL_F_TLS_PROCESS_CKE_ECDHE,
3167 SSL_R_MISSING_TMP_ECDH_KEY);
3171 const unsigned char *data;
3174 * Get client's public key from encoded point in the
3175 * ClientKeyExchange message.
3178 /* Get encoded point length */
3179 if (!PACKET_get_1(pkt, &i) || !PACKET_get_bytes(pkt, &data, i)
3180 || PACKET_remaining(pkt) != 0) {
3181 SSLfatal(s, SSL_AD_DECODE_ERROR, SSL_F_TLS_PROCESS_CKE_ECDHE,
3182 SSL_R_LENGTH_MISMATCH);
3185 ckey = EVP_PKEY_new();
3186 if (ckey == NULL || EVP_PKEY_copy_parameters(ckey, skey) <= 0) {
3187 SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_F_TLS_PROCESS_CKE_ECDHE,
3191 if (EVP_PKEY_set1_tls_encodedpoint(ckey, data, i) == 0) {
3192 SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_F_TLS_PROCESS_CKE_ECDHE,
3198 if (ssl_derive(s, skey, ckey, 1) == 0) {
3199 /* SSLfatal() already called */
3204 EVP_PKEY_free(s->s3->tmp.pkey);
3205 s->s3->tmp.pkey = NULL;
3207 EVP_PKEY_free(ckey);
3211 /* Should never happen */
3212 SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_F_TLS_PROCESS_CKE_ECDHE,
3213 ERR_R_INTERNAL_ERROR);
3218 static int tls_process_cke_srp(SSL *s, PACKET *pkt)
3220 #ifndef OPENSSL_NO_SRP
3222 const unsigned char *data;
3224 if (!PACKET_get_net_2(pkt, &i)
3225 || !PACKET_get_bytes(pkt, &data, i)) {
3226 SSLfatal(s, SSL_AD_DECODE_ERROR, SSL_F_TLS_PROCESS_CKE_SRP,
3227 SSL_R_BAD_SRP_A_LENGTH);
3230 if ((s->srp_ctx.A = BN_bin2bn(data, i, NULL)) == NULL) {
3231 SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_F_TLS_PROCESS_CKE_SRP,
3235 if (BN_ucmp(s->srp_ctx.A, s->srp_ctx.N) >= 0 || BN_is_zero(s->srp_ctx.A)) {
3236 SSLfatal(s, SSL_AD_ILLEGAL_PARAMETER, SSL_F_TLS_PROCESS_CKE_SRP,
3237 SSL_R_BAD_SRP_PARAMETERS);
3240 OPENSSL_free(s->session->srp_username);
3241 s->session->srp_username = OPENSSL_strdup(s->srp_ctx.login);
3242 if (s->session->srp_username == NULL) {
3243 SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_F_TLS_PROCESS_CKE_SRP,
3244 ERR_R_MALLOC_FAILURE);
3248 if (!srp_generate_server_master_secret(s)) {
3249 /* SSLfatal() already called */
3255 /* Should never happen */
3256 SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_F_TLS_PROCESS_CKE_SRP,
3257 ERR_R_INTERNAL_ERROR);
3262 static int tls_process_cke_gost(SSL *s, PACKET *pkt)
3264 #ifndef OPENSSL_NO_GOST
3265 EVP_PKEY_CTX *pkey_ctx;
3266 EVP_PKEY *client_pub_pkey = NULL, *pk = NULL;
3267 unsigned char premaster_secret[32];
3268 const unsigned char *start;
3269 size_t outlen = 32, inlen;
3270 unsigned long alg_a;
3271 unsigned int asn1id, asn1len;
3275 /* Get our certificate private key */
3276 alg_a = s->s3->tmp.new_cipher->algorithm_auth;
3277 if (alg_a & SSL_aGOST12) {
3279 * New GOST ciphersuites have SSL_aGOST01 bit too
3281 pk = s->cert->pkeys[SSL_PKEY_GOST12_512].privatekey;
3283 pk = s->cert->pkeys[SSL_PKEY_GOST12_256].privatekey;
3286 pk = s->cert->pkeys[SSL_PKEY_GOST01].privatekey;
3288 } else if (alg_a & SSL_aGOST01) {
3289 pk = s->cert->pkeys[SSL_PKEY_GOST01].privatekey;
3292 pkey_ctx = EVP_PKEY_CTX_new(pk, NULL);
3293 if (pkey_ctx == NULL) {
3294 SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_F_TLS_PROCESS_CKE_GOST,
3295 ERR_R_MALLOC_FAILURE);
3298 if (EVP_PKEY_decrypt_init(pkey_ctx) <= 0) {
3299 SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_F_TLS_PROCESS_CKE_GOST,
3300 ERR_R_INTERNAL_ERROR);
3304 * If client certificate is present and is of the same type, maybe
3305 * use it for key exchange. Don't mind errors from
3306 * EVP_PKEY_derive_set_peer, because it is completely valid to use a
3307 * client certificate for authorization only.
3309 client_pub_pkey = X509_get0_pubkey(s->session->peer);
3310 if (client_pub_pkey) {
3311 if (EVP_PKEY_derive_set_peer(pkey_ctx, client_pub_pkey) <= 0)
3314 /* Decrypt session key */
3315 if (!PACKET_get_1(pkt, &asn1id)
3316 || asn1id != (V_ASN1_SEQUENCE | V_ASN1_CONSTRUCTED)
3317 || !PACKET_peek_1(pkt, &asn1len)) {
3318 SSLfatal(s, SSL_AD_DECODE_ERROR, SSL_F_TLS_PROCESS_CKE_GOST,
3319 SSL_R_DECRYPTION_FAILED);
3322 if (asn1len == 0x81) {
3324 * Long form length. Should only be one byte of length. Anything else
3326 * We did a successful peek before so this shouldn't fail
3328 if (!PACKET_forward(pkt, 1)) {
3329 SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_F_TLS_PROCESS_CKE_GOST,
3330 SSL_R_DECRYPTION_FAILED);
3333 } else if (asn1len >= 0x80) {
3335 * Indefinite length, or more than one long form length bytes. We don't
3338 SSLfatal(s, SSL_AD_DECODE_ERROR, SSL_F_TLS_PROCESS_CKE_GOST,
3339 SSL_R_DECRYPTION_FAILED);
3341 } /* else short form length */
3343 if (!PACKET_as_length_prefixed_1(pkt, &encdata)) {
3344 SSLfatal(s, SSL_AD_DECODE_ERROR, SSL_F_TLS_PROCESS_CKE_GOST,
3345 SSL_R_DECRYPTION_FAILED);
3348 inlen = PACKET_remaining(&encdata);
3349 start = PACKET_data(&encdata);
3351 if (EVP_PKEY_decrypt(pkey_ctx, premaster_secret, &outlen, start,
3353 SSLfatal(s, SSL_AD_DECODE_ERROR, SSL_F_TLS_PROCESS_CKE_GOST,
3354 SSL_R_DECRYPTION_FAILED);
3357 /* Generate master secret */
3358 if (!ssl_generate_master_secret(s, premaster_secret,
3359 sizeof(premaster_secret), 0)) {
3360 /* SSLfatal() already called */
3363 /* Check if pubkey from client certificate was used */
3364 if (EVP_PKEY_CTX_ctrl(pkey_ctx, -1, -1, EVP_PKEY_CTRL_PEER_KEY, 2,
3366 s->statem.no_cert_verify = 1;
3370 EVP_PKEY_CTX_free(pkey_ctx);
3373 /* Should never happen */
3374 SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_F_TLS_PROCESS_CKE_GOST,
3375 ERR_R_INTERNAL_ERROR);
3380 MSG_PROCESS_RETURN tls_process_client_key_exchange(SSL *s, PACKET *pkt)
3382 unsigned long alg_k;
3384 alg_k = s->s3->tmp.new_cipher->algorithm_mkey;
3386 /* For PSK parse and retrieve identity, obtain PSK key */
3387 if ((alg_k & SSL_PSK) && !tls_process_cke_psk_preamble(s, pkt)) {
3388 /* SSLfatal() already called */
3392 if (alg_k & SSL_kPSK) {
3393 /* Identity extracted earlier: should be nothing left */
3394 if (PACKET_remaining(pkt) != 0) {
3395 SSLfatal(s, SSL_AD_DECODE_ERROR,
3396 SSL_F_TLS_PROCESS_CLIENT_KEY_EXCHANGE,
3397 SSL_R_LENGTH_MISMATCH);
3400 /* PSK handled by ssl_generate_master_secret */
3401 if (!ssl_generate_master_secret(s, NULL, 0, 0)) {
3402 /* SSLfatal() already called */
3405 } else if (alg_k & (SSL_kRSA | SSL_kRSAPSK)) {
3406 if (!tls_process_cke_rsa(s, pkt)) {
3407 /* SSLfatal() already called */
3410 } else if (alg_k & (SSL_kDHE | SSL_kDHEPSK)) {
3411 if (!tls_process_cke_dhe(s, pkt)) {
3412 /* SSLfatal() already called */
3415 } else if (alg_k & (SSL_kECDHE | SSL_kECDHEPSK)) {
3416 if (!tls_process_cke_ecdhe(s, pkt)) {
3417 /* SSLfatal() already called */
3420 } else if (alg_k & SSL_kSRP) {
3421 if (!tls_process_cke_srp(s, pkt)) {