2 * Copyright 1995-2016 The OpenSSL Project Authors. All Rights Reserved.
3 * Copyright (c) 2002, Oracle and/or its affiliates. All rights reserved
5 * Licensed under the OpenSSL license (the "License"). You may not use
6 * this file except in compliance with the License. You can obtain a copy
7 * in the file LICENSE in the source distribution or at
8 * https://www.openssl.org/source/license.html
11 /* ====================================================================
12 * Copyright 2005 Nokia. All rights reserved.
14 * The portions of the attached software ("Contribution") is developed by
15 * Nokia Corporation and is licensed pursuant to the OpenSSL open source
18 * The Contribution, originally written by Mika Kousa and Pasi Eronen of
19 * Nokia Corporation, consists of the "PSK" (Pre-Shared Key) ciphersuites
20 * support (see RFC 4279) to OpenSSL.
22 * No patent licenses or other rights except those expressly stated in
23 * the OpenSSL open source license shall be deemed granted or received
24 * expressly, by implication, estoppel, or otherwise.
26 * No assurances are provided by Nokia that the Contribution does not
27 * infringe the patent or other intellectual property rights of any third
28 * party or that the license provides you with all the necessary rights
29 * to make use of the Contribution.
31 * THE SOFTWARE IS PROVIDED "AS IS" WITHOUT WARRANTY OF ANY KIND. IN
32 * ADDITION TO THE DISCLAIMERS INCLUDED IN THE LICENSE, NOKIA
33 * SPECIFICALLY DISCLAIMS ANY LIABILITY FOR CLAIMS BROUGHT BY YOU OR ANY
34 * OTHER ENTITY BASED ON INFRINGEMENT OF INTELLECTUAL PROPERTY RIGHTS OR
39 #include "../ssl_locl.h"
40 #include "statem_locl.h"
41 #include "internal/constant_time_locl.h"
42 #include <openssl/buffer.h>
43 #include <openssl/rand.h>
44 #include <openssl/objects.h>
45 #include <openssl/evp.h>
46 #include <openssl/hmac.h>
47 #include <openssl/x509.h>
48 #include <openssl/dh.h>
49 #include <openssl/bn.h>
50 #include <openssl/md5.h>
52 static int tls_construct_encrypted_extensions(SSL *s, WPACKET *pkt);
53 static int tls_construct_hello_retry_request(SSL *s, WPACKET *pkt);
56 * ossl_statem_server13_read_transition() encapsulates the logic for the allowed
57 * handshake state transitions when a TLSv1.3 server is reading messages from
58 * the client. The message type that the client has sent is provided in |mt|.
59 * The current state is in |s->statem.hand_state|.
61 * Return values are 1 for success (transition allowed) and 0 on error
62 * (transition not allowed)
64 static int ossl_statem_server13_read_transition(SSL *s, int mt)
66 OSSL_STATEM *st = &s->statem;
69 * Note: There is no case for TLS_ST_BEFORE because at that stage we have
70 * not negotiated TLSv1.3 yet, so that case is handled by
71 * ossl_statem_server_read_transition()
73 switch (st->hand_state) {
77 case TLS_ST_SW_HELLO_RETRY_REQUEST:
78 if (mt == SSL3_MT_CLIENT_HELLO) {
79 st->hand_state = TLS_ST_SR_CLNT_HELLO;
84 case TLS_ST_EARLY_DATA:
85 if (s->ext.early_data == SSL_EARLY_DATA_ACCEPTED) {
86 if (mt == SSL3_MT_END_OF_EARLY_DATA) {
87 st->hand_state = TLS_ST_SR_END_OF_EARLY_DATA;
94 case TLS_ST_SR_END_OF_EARLY_DATA:
95 case TLS_ST_SW_FINISHED:
96 if (s->s3->tmp.cert_request) {
97 if (mt == SSL3_MT_CERTIFICATE) {
98 st->hand_state = TLS_ST_SR_CERT;
102 if (mt == SSL3_MT_FINISHED) {
103 st->hand_state = TLS_ST_SR_FINISHED;
110 if (s->session->peer == NULL) {
111 if (mt == SSL3_MT_FINISHED) {
112 st->hand_state = TLS_ST_SR_FINISHED;
116 if (mt == SSL3_MT_CERTIFICATE_VERIFY) {
117 st->hand_state = TLS_ST_SR_CERT_VRFY;
123 case TLS_ST_SR_CERT_VRFY:
124 if (mt == SSL3_MT_FINISHED) {
125 st->hand_state = TLS_ST_SR_FINISHED;
132 * Its never ok to start processing handshake messages in the middle of
133 * early data (i.e. before we've received the end of early data alert)
135 if (s->early_data_state == SSL_EARLY_DATA_READING)
137 if (mt == SSL3_MT_KEY_UPDATE) {
138 st->hand_state = TLS_ST_SR_KEY_UPDATE;
144 /* No valid transition found */
149 * ossl_statem_server_read_transition() encapsulates the logic for the allowed
150 * handshake state transitions when the server is reading messages from the
151 * client. The message type that the client has sent is provided in |mt|. The
152 * current state is in |s->statem.hand_state|.
154 * Return values are 1 for success (transition allowed) and 0 on error
155 * (transition not allowed)
157 int ossl_statem_server_read_transition(SSL *s, int mt)
159 OSSL_STATEM *st = &s->statem;
161 if (SSL_IS_TLS13(s)) {
162 if (!ossl_statem_server13_read_transition(s, mt))
167 switch (st->hand_state) {
173 case DTLS_ST_SW_HELLO_VERIFY_REQUEST:
174 if (mt == SSL3_MT_CLIENT_HELLO) {
175 st->hand_state = TLS_ST_SR_CLNT_HELLO;
180 case TLS_ST_SW_SRVR_DONE:
182 * If we get a CKE message after a ServerDone then either
183 * 1) We didn't request a Certificate
185 * 2) If we did request one then
186 * a) We allow no Certificate to be returned
188 * b) We are running SSL3 (in TLS1.0+ the client must return a 0
189 * list if we requested a certificate)
191 if (mt == SSL3_MT_CLIENT_KEY_EXCHANGE) {
192 if (s->s3->tmp.cert_request) {
193 if (s->version == SSL3_VERSION) {
194 if ((s->verify_mode & SSL_VERIFY_PEER)
195 && (s->verify_mode & SSL_VERIFY_FAIL_IF_NO_PEER_CERT)) {
197 * This isn't an unexpected message as such - we're just
198 * not going to accept it because we require a client
201 ssl3_send_alert(s, SSL3_AL_FATAL,
202 SSL3_AD_HANDSHAKE_FAILURE);
203 SSLerr(SSL_F_OSSL_STATEM_SERVER_READ_TRANSITION,
204 SSL_R_PEER_DID_NOT_RETURN_A_CERTIFICATE);
207 st->hand_state = TLS_ST_SR_KEY_EXCH;
211 st->hand_state = TLS_ST_SR_KEY_EXCH;
214 } else if (s->s3->tmp.cert_request) {
215 if (mt == SSL3_MT_CERTIFICATE) {
216 st->hand_state = TLS_ST_SR_CERT;
223 if (mt == SSL3_MT_CLIENT_KEY_EXCHANGE) {
224 st->hand_state = TLS_ST_SR_KEY_EXCH;
229 case TLS_ST_SR_KEY_EXCH:
231 * We should only process a CertificateVerify message if we have
232 * received a Certificate from the client. If so then |s->session->peer|
233 * will be non NULL. In some instances a CertificateVerify message is
234 * not required even if the peer has sent a Certificate (e.g. such as in
235 * the case of static DH). In that case |st->no_cert_verify| should be
238 if (s->session->peer == NULL || st->no_cert_verify) {
239 if (mt == SSL3_MT_CHANGE_CIPHER_SPEC) {
241 * For the ECDH ciphersuites when the client sends its ECDH
242 * pub key in a certificate, the CertificateVerify message is
243 * not sent. Also for GOST ciphersuites when the client uses
244 * its key from the certificate for key exchange.
246 st->hand_state = TLS_ST_SR_CHANGE;
250 if (mt == SSL3_MT_CERTIFICATE_VERIFY) {
251 st->hand_state = TLS_ST_SR_CERT_VRFY;
257 case TLS_ST_SR_CERT_VRFY:
258 if (mt == SSL3_MT_CHANGE_CIPHER_SPEC) {
259 st->hand_state = TLS_ST_SR_CHANGE;
264 case TLS_ST_SR_CHANGE:
265 #ifndef OPENSSL_NO_NEXTPROTONEG
266 if (s->s3->npn_seen) {
267 if (mt == SSL3_MT_NEXT_PROTO) {
268 st->hand_state = TLS_ST_SR_NEXT_PROTO;
273 if (mt == SSL3_MT_FINISHED) {
274 st->hand_state = TLS_ST_SR_FINISHED;
277 #ifndef OPENSSL_NO_NEXTPROTONEG
282 #ifndef OPENSSL_NO_NEXTPROTONEG
283 case TLS_ST_SR_NEXT_PROTO:
284 if (mt == SSL3_MT_FINISHED) {
285 st->hand_state = TLS_ST_SR_FINISHED;
291 case TLS_ST_SW_FINISHED:
292 if (mt == SSL3_MT_CHANGE_CIPHER_SPEC) {
293 st->hand_state = TLS_ST_SR_CHANGE;
300 /* No valid transition found */
301 ssl3_send_alert(s, SSL3_AL_FATAL, SSL3_AD_UNEXPECTED_MESSAGE);
302 SSLerr(SSL_F_OSSL_STATEM_SERVER_READ_TRANSITION, SSL_R_UNEXPECTED_MESSAGE);
307 * Should we send a ServerKeyExchange message?
309 * Valid return values are:
313 static int send_server_key_exchange(SSL *s)
315 unsigned long alg_k = s->s3->tmp.new_cipher->algorithm_mkey;
318 * only send a ServerKeyExchange if DH or fortezza but we have a
319 * sign only certificate PSK: may send PSK identity hints For
320 * ECC ciphersuites, we send a serverKeyExchange message only if
321 * the cipher suite is either ECDH-anon or ECDHE. In other cases,
322 * the server certificate contains the server's public key for
325 if (alg_k & (SSL_kDHE | SSL_kECDHE)
327 * PSK: send ServerKeyExchange if PSK identity hint if
330 #ifndef OPENSSL_NO_PSK
331 /* Only send SKE if we have identity hint for plain PSK */
332 || ((alg_k & (SSL_kPSK | SSL_kRSAPSK))
333 && s->cert->psk_identity_hint)
334 /* For other PSK always send SKE */
335 || (alg_k & (SSL_PSK & (SSL_kDHEPSK | SSL_kECDHEPSK)))
337 #ifndef OPENSSL_NO_SRP
338 /* SRP: send ServerKeyExchange */
339 || (alg_k & SSL_kSRP)
349 * Should we send a CertificateRequest message?
351 * Valid return values are:
355 static int send_certificate_request(SSL *s)
358 /* don't request cert unless asked for it: */
359 s->verify_mode & SSL_VERIFY_PEER
361 * if SSL_VERIFY_CLIENT_ONCE is set, don't request cert
362 * during re-negotiation:
364 && (s->s3->tmp.finish_md_len == 0 ||
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 return WRITE_TRAN_ERROR;
411 if (s->key_update != SSL_KEY_UPDATE_NONE) {
412 st->hand_state = TLS_ST_SW_KEY_UPDATE;
413 return WRITE_TRAN_CONTINUE;
415 /* Try to read from the client instead */
416 return WRITE_TRAN_FINISHED;
418 case TLS_ST_SR_CLNT_HELLO:
419 if (s->hello_retry_request)
420 st->hand_state = TLS_ST_SW_HELLO_RETRY_REQUEST;
422 st->hand_state = TLS_ST_SW_SRVR_HELLO;
423 return WRITE_TRAN_CONTINUE;
425 case TLS_ST_SW_HELLO_RETRY_REQUEST:
426 return WRITE_TRAN_FINISHED;
428 case TLS_ST_SW_SRVR_HELLO:
429 st->hand_state = TLS_ST_SW_ENCRYPTED_EXTENSIONS;
430 return WRITE_TRAN_CONTINUE;
432 case TLS_ST_SW_ENCRYPTED_EXTENSIONS:
434 st->hand_state = TLS_ST_SW_FINISHED;
435 else if (send_certificate_request(s))
436 st->hand_state = TLS_ST_SW_CERT_REQ;
438 st->hand_state = TLS_ST_SW_CERT;
440 return WRITE_TRAN_CONTINUE;
442 case TLS_ST_SW_CERT_REQ:
443 st->hand_state = TLS_ST_SW_CERT;
444 return WRITE_TRAN_CONTINUE;
447 st->hand_state = TLS_ST_SW_CERT_VRFY;
448 return WRITE_TRAN_CONTINUE;
450 case TLS_ST_SW_CERT_VRFY:
451 st->hand_state = TLS_ST_SW_FINISHED;
452 return WRITE_TRAN_CONTINUE;
454 case TLS_ST_SW_FINISHED:
455 st->hand_state = TLS_ST_EARLY_DATA;
456 return WRITE_TRAN_CONTINUE;
458 case TLS_ST_EARLY_DATA:
459 return WRITE_TRAN_FINISHED;
461 case TLS_ST_SR_FINISHED:
463 * Technically we have finished the handshake at this point, but we're
464 * going to remain "in_init" for now and write out the session ticket
466 * TODO(TLS1.3): Perhaps we need to be able to control this behaviour
467 * and give the application the opportunity to delay sending the
470 st->hand_state = TLS_ST_SW_SESSION_TICKET;
471 return WRITE_TRAN_CONTINUE;
473 case TLS_ST_SR_KEY_UPDATE:
474 if (s->key_update != SSL_KEY_UPDATE_NONE) {
475 st->hand_state = TLS_ST_SW_KEY_UPDATE;
476 return WRITE_TRAN_CONTINUE;
480 case TLS_ST_SW_KEY_UPDATE:
481 case TLS_ST_SW_SESSION_TICKET:
482 st->hand_state = TLS_ST_OK;
483 return WRITE_TRAN_CONTINUE;
488 * ossl_statem_server_write_transition() works out what handshake state to move
489 * to next when the server is writing messages to be sent to the client.
491 WRITE_TRAN ossl_statem_server_write_transition(SSL *s)
493 OSSL_STATEM *st = &s->statem;
496 * Note that before the ClientHello we don't know what version we are going
497 * to negotiate yet, so we don't take this branch until later
501 return ossl_statem_server13_write_transition(s);
503 switch (st->hand_state) {
505 /* Shouldn't happen */
506 return WRITE_TRAN_ERROR;
509 if (st->request_state == TLS_ST_SW_HELLO_REQ) {
510 /* We must be trying to renegotiate */
511 st->hand_state = TLS_ST_SW_HELLO_REQ;
512 st->request_state = TLS_ST_BEFORE;
513 return WRITE_TRAN_CONTINUE;
515 /* Must be an incoming ClientHello */
516 if (!tls_setup_handshake(s)) {
517 ossl_statem_set_error(s);
518 return WRITE_TRAN_ERROR;
523 /* Just go straight to trying to read from the client */
524 return WRITE_TRAN_FINISHED;
526 case TLS_ST_SW_HELLO_REQ:
527 st->hand_state = TLS_ST_OK;
528 return WRITE_TRAN_CONTINUE;
530 case TLS_ST_SR_CLNT_HELLO:
531 if (SSL_IS_DTLS(s) && !s->d1->cookie_verified
532 && (SSL_get_options(s) & SSL_OP_COOKIE_EXCHANGE))
533 st->hand_state = DTLS_ST_SW_HELLO_VERIFY_REQUEST;
535 st->hand_state = TLS_ST_SW_SRVR_HELLO;
536 return WRITE_TRAN_CONTINUE;
538 case DTLS_ST_SW_HELLO_VERIFY_REQUEST:
539 return WRITE_TRAN_FINISHED;
541 case TLS_ST_SW_SRVR_HELLO:
543 if (s->ext.ticket_expected)
544 st->hand_state = TLS_ST_SW_SESSION_TICKET;
546 st->hand_state = TLS_ST_SW_CHANGE;
548 /* Check if it is anon DH or anon ECDH, */
549 /* normal PSK or SRP */
550 if (!(s->s3->tmp.new_cipher->algorithm_auth &
551 (SSL_aNULL | SSL_aSRP | SSL_aPSK))) {
552 st->hand_state = TLS_ST_SW_CERT;
553 } else if (send_server_key_exchange(s)) {
554 st->hand_state = TLS_ST_SW_KEY_EXCH;
555 } else if (send_certificate_request(s)) {
556 st->hand_state = TLS_ST_SW_CERT_REQ;
558 st->hand_state = TLS_ST_SW_SRVR_DONE;
561 return WRITE_TRAN_CONTINUE;
564 if (s->ext.status_expected) {
565 st->hand_state = TLS_ST_SW_CERT_STATUS;
566 return WRITE_TRAN_CONTINUE;
570 case TLS_ST_SW_CERT_STATUS:
571 if (send_server_key_exchange(s)) {
572 st->hand_state = TLS_ST_SW_KEY_EXCH;
573 return WRITE_TRAN_CONTINUE;
577 case TLS_ST_SW_KEY_EXCH:
578 if (send_certificate_request(s)) {
579 st->hand_state = TLS_ST_SW_CERT_REQ;
580 return WRITE_TRAN_CONTINUE;
584 case TLS_ST_SW_CERT_REQ:
585 st->hand_state = TLS_ST_SW_SRVR_DONE;
586 return WRITE_TRAN_CONTINUE;
588 case TLS_ST_SW_SRVR_DONE:
589 return WRITE_TRAN_FINISHED;
591 case TLS_ST_SR_FINISHED:
593 st->hand_state = TLS_ST_OK;
594 return WRITE_TRAN_CONTINUE;
595 } else if (s->ext.ticket_expected) {
596 st->hand_state = TLS_ST_SW_SESSION_TICKET;
598 st->hand_state = TLS_ST_SW_CHANGE;
600 return WRITE_TRAN_CONTINUE;
602 case TLS_ST_SW_SESSION_TICKET:
603 st->hand_state = TLS_ST_SW_CHANGE;
604 return WRITE_TRAN_CONTINUE;
606 case TLS_ST_SW_CHANGE:
607 st->hand_state = TLS_ST_SW_FINISHED;
608 return WRITE_TRAN_CONTINUE;
610 case TLS_ST_SW_FINISHED:
612 return WRITE_TRAN_FINISHED;
614 st->hand_state = TLS_ST_OK;
615 return WRITE_TRAN_CONTINUE;
620 * Perform any pre work that needs to be done prior to sending a message from
621 * the server to the client.
623 WORK_STATE ossl_statem_server_pre_work(SSL *s, WORK_STATE wst)
625 OSSL_STATEM *st = &s->statem;
627 switch (st->hand_state) {
629 /* No pre work to be done */
632 case TLS_ST_SW_HELLO_REQ:
635 dtls1_clear_sent_buffer(s);
638 case DTLS_ST_SW_HELLO_VERIFY_REQUEST:
640 if (SSL_IS_DTLS(s)) {
641 dtls1_clear_sent_buffer(s);
642 /* We don't buffer this message so don't use the timer */
647 case TLS_ST_SW_SRVR_HELLO:
648 if (SSL_IS_DTLS(s)) {
650 * Messages we write from now on should be buffered and
651 * retransmitted if necessary, so we need to use the timer now
657 case TLS_ST_SW_SRVR_DONE:
658 #ifndef OPENSSL_NO_SCTP
659 if (SSL_IS_DTLS(s) && BIO_dgram_is_sctp(SSL_get_wbio(s)))
660 return dtls_wait_for_dry(s);
662 return WORK_FINISHED_CONTINUE;
664 case TLS_ST_SW_SESSION_TICKET:
665 if (SSL_IS_TLS13(s)) {
667 * Actually this is the end of the handshake, but we're going
668 * straight into writing the session ticket out. So we finish off
669 * the handshake, but keep the various buffers active.
671 return tls_finish_handshake(s, wst, 0);
672 } if (SSL_IS_DTLS(s)) {
674 * We're into the last flight. We don't retransmit the last flight
675 * unless we need to, so we don't use the timer
681 case TLS_ST_SW_CHANGE:
682 s->session->cipher = s->s3->tmp.new_cipher;
683 if (!s->method->ssl3_enc->setup_key_block(s)) {
684 ossl_statem_set_error(s);
687 if (SSL_IS_DTLS(s)) {
689 * We're into the last flight. We don't retransmit the last flight
690 * unless we need to, so we don't use the timer. This might have
691 * already been set to 0 if we sent a NewSessionTicket message,
692 * but we'll set it again here in case we didn't.
696 return WORK_FINISHED_CONTINUE;
698 case TLS_ST_EARLY_DATA:
699 if (s->early_data_state != SSL_EARLY_DATA_ACCEPTING)
700 return WORK_FINISHED_CONTINUE;
704 return tls_finish_handshake(s, wst, 1);
707 return WORK_FINISHED_CONTINUE;
711 * Perform any work that needs to be done after sending a message from the
712 * server to the client.
714 WORK_STATE ossl_statem_server_post_work(SSL *s, WORK_STATE wst)
716 OSSL_STATEM *st = &s->statem;
720 switch (st->hand_state) {
722 /* No post work to be done */
725 case TLS_ST_SW_HELLO_RETRY_REQUEST:
726 if (statem_flush(s) != 1)
730 case TLS_ST_SW_HELLO_REQ:
731 if (statem_flush(s) != 1)
733 if (!ssl3_init_finished_mac(s)) {
734 ossl_statem_set_error(s);
739 case DTLS_ST_SW_HELLO_VERIFY_REQUEST:
740 if (statem_flush(s) != 1)
742 /* HelloVerifyRequest resets Finished MAC */
743 if (s->version != DTLS1_BAD_VER && !ssl3_init_finished_mac(s)) {
744 ossl_statem_set_error(s);
748 * The next message should be another ClientHello which we need to
749 * treat like it was the first packet
754 case TLS_ST_SW_SRVR_HELLO:
755 #ifndef OPENSSL_NO_SCTP
756 if (SSL_IS_DTLS(s) && s->hit) {
757 unsigned char sctpauthkey[64];
758 char labelbuffer[sizeof(DTLS1_SCTP_AUTH_LABEL)];
761 * Add new shared key for SCTP-Auth, will be ignored if no
764 memcpy(labelbuffer, DTLS1_SCTP_AUTH_LABEL,
765 sizeof(DTLS1_SCTP_AUTH_LABEL));
767 if (SSL_export_keying_material(s, sctpauthkey,
768 sizeof(sctpauthkey), labelbuffer,
769 sizeof(labelbuffer), NULL, 0,
771 ossl_statem_set_error(s);
775 BIO_ctrl(SSL_get_wbio(s), BIO_CTRL_DGRAM_SCTP_ADD_AUTH_KEY,
776 sizeof(sctpauthkey), sctpauthkey);
780 * TODO(TLS1.3): This actually causes a problem. We don't yet know
781 * whether the next record we are going to receive is an unencrypted
782 * alert, or an encrypted handshake message. We're going to need
783 * something clever in the record layer for this.
785 if (SSL_IS_TLS13(s)) {
786 if (!s->method->ssl3_enc->setup_key_block(s)
787 || !s->method->ssl3_enc->change_cipher_state(s,
788 SSL3_CC_HANDSHAKE | SSL3_CHANGE_CIPHER_SERVER_WRITE))
791 if (s->ext.early_data != SSL_EARLY_DATA_ACCEPTED
792 && !s->method->ssl3_enc->change_cipher_state(s,
793 SSL3_CC_HANDSHAKE |SSL3_CHANGE_CIPHER_SERVER_READ))
798 case TLS_ST_SW_CHANGE:
799 #ifndef OPENSSL_NO_SCTP
800 if (SSL_IS_DTLS(s) && !s->hit) {
802 * Change to new shared key of SCTP-Auth, will be ignored if
805 BIO_ctrl(SSL_get_wbio(s), BIO_CTRL_DGRAM_SCTP_NEXT_AUTH_KEY,
809 if (!s->method->ssl3_enc->change_cipher_state(s,
810 SSL3_CHANGE_CIPHER_SERVER_WRITE))
812 ossl_statem_set_error(s);
817 dtls1_reset_seq_numbers(s, SSL3_CC_WRITE);
820 case TLS_ST_SW_SRVR_DONE:
821 if (statem_flush(s) != 1)
825 case TLS_ST_SW_FINISHED:
826 if (statem_flush(s) != 1)
828 #ifndef OPENSSL_NO_SCTP
829 if (SSL_IS_DTLS(s) && s->hit) {
831 * Change to new shared key of SCTP-Auth, will be ignored if
834 BIO_ctrl(SSL_get_wbio(s), BIO_CTRL_DGRAM_SCTP_NEXT_AUTH_KEY,
838 if (SSL_IS_TLS13(s)) {
839 if (!s->method->ssl3_enc->generate_master_secret(s,
840 s->master_secret, s->handshake_secret, 0,
841 &s->session->master_key_length)
842 || !s->method->ssl3_enc->change_cipher_state(s,
843 SSL3_CC_APPLICATION | SSL3_CHANGE_CIPHER_SERVER_WRITE))
848 case TLS_ST_SW_KEY_UPDATE:
849 if (statem_flush(s) != 1)
851 if (!tls13_update_key(s, 1))
855 case TLS_ST_SW_SESSION_TICKET:
856 if (SSL_IS_TLS13(s) && statem_flush(s) != 1)
861 return WORK_FINISHED_CONTINUE;
865 * Get the message construction function and message type for sending from the
868 * Valid return values are:
872 int ossl_statem_server_construct_message(SSL *s, WPACKET *pkt,
873 confunc_f *confunc, int *mt)
875 OSSL_STATEM *st = &s->statem;
877 switch (st->hand_state) {
879 /* Shouldn't happen */
882 case TLS_ST_SW_CHANGE:
884 *confunc = dtls_construct_change_cipher_spec;
886 *confunc = tls_construct_change_cipher_spec;
887 *mt = SSL3_MT_CHANGE_CIPHER_SPEC;
890 case DTLS_ST_SW_HELLO_VERIFY_REQUEST:
891 *confunc = dtls_construct_hello_verify_request;
892 *mt = DTLS1_MT_HELLO_VERIFY_REQUEST;
895 case TLS_ST_SW_HELLO_REQ:
896 /* No construction function needed */
898 *mt = SSL3_MT_HELLO_REQUEST;
901 case TLS_ST_SW_SRVR_HELLO:
902 *confunc = tls_construct_server_hello;
903 *mt = SSL3_MT_SERVER_HELLO;
907 *confunc = tls_construct_server_certificate;
908 *mt = SSL3_MT_CERTIFICATE;
911 case TLS_ST_SW_CERT_VRFY:
912 *confunc = tls_construct_cert_verify;
913 *mt = SSL3_MT_CERTIFICATE_VERIFY;
917 case TLS_ST_SW_KEY_EXCH:
918 *confunc = tls_construct_server_key_exchange;
919 *mt = SSL3_MT_SERVER_KEY_EXCHANGE;
922 case TLS_ST_SW_CERT_REQ:
923 *confunc = tls_construct_certificate_request;
924 *mt = SSL3_MT_CERTIFICATE_REQUEST;
927 case TLS_ST_SW_SRVR_DONE:
928 *confunc = tls_construct_server_done;
929 *mt = SSL3_MT_SERVER_DONE;
932 case TLS_ST_SW_SESSION_TICKET:
933 *confunc = tls_construct_new_session_ticket;
934 *mt = SSL3_MT_NEWSESSION_TICKET;
937 case TLS_ST_SW_CERT_STATUS:
938 *confunc = tls_construct_cert_status;
939 *mt = SSL3_MT_CERTIFICATE_STATUS;
942 case TLS_ST_SW_FINISHED:
943 *confunc = tls_construct_finished;
944 *mt = SSL3_MT_FINISHED;
947 case TLS_ST_EARLY_DATA:
952 case TLS_ST_SW_ENCRYPTED_EXTENSIONS:
953 *confunc = tls_construct_encrypted_extensions;
954 *mt = SSL3_MT_ENCRYPTED_EXTENSIONS;
957 case TLS_ST_SW_HELLO_RETRY_REQUEST:
958 *confunc = tls_construct_hello_retry_request;
959 *mt = SSL3_MT_HELLO_RETRY_REQUEST;
962 case TLS_ST_SW_KEY_UPDATE:
963 *confunc = tls_construct_key_update;
964 *mt = SSL3_MT_KEY_UPDATE;
972 * Maximum size (excluding the Handshake header) of a ClientHello message,
973 * calculated as follows:
975 * 2 + # client_version
976 * 32 + # only valid length for random
977 * 1 + # length of session_id
978 * 32 + # maximum size for session_id
979 * 2 + # length of cipher suites
980 * 2^16-2 + # maximum length of cipher suites array
981 * 1 + # length of compression_methods
982 * 2^8-1 + # maximum length of compression methods
983 * 2 + # length of extensions
984 * 2^16-1 # maximum length of extensions
986 #define CLIENT_HELLO_MAX_LENGTH 131396
988 #define CLIENT_KEY_EXCH_MAX_LENGTH 2048
989 #define NEXT_PROTO_MAX_LENGTH 514
992 * Returns the maximum allowed length for the current message that we are
993 * reading. Excludes the message header.
995 size_t ossl_statem_server_max_message_size(SSL *s)
997 OSSL_STATEM *st = &s->statem;
999 switch (st->hand_state) {
1001 /* Shouldn't happen */
1004 case TLS_ST_SR_CLNT_HELLO:
1005 return CLIENT_HELLO_MAX_LENGTH;
1007 case TLS_ST_SR_END_OF_EARLY_DATA:
1008 return END_OF_EARLY_DATA_MAX_LENGTH;
1010 case TLS_ST_SR_CERT:
1011 return s->max_cert_list;
1013 case TLS_ST_SR_KEY_EXCH:
1014 return CLIENT_KEY_EXCH_MAX_LENGTH;
1016 case TLS_ST_SR_CERT_VRFY:
1017 return SSL3_RT_MAX_PLAIN_LENGTH;
1019 #ifndef OPENSSL_NO_NEXTPROTONEG
1020 case TLS_ST_SR_NEXT_PROTO:
1021 return NEXT_PROTO_MAX_LENGTH;
1024 case TLS_ST_SR_CHANGE:
1025 return CCS_MAX_LENGTH;
1027 case TLS_ST_SR_FINISHED:
1028 return FINISHED_MAX_LENGTH;
1030 case TLS_ST_SR_KEY_UPDATE:
1031 return KEY_UPDATE_MAX_LENGTH;
1036 * Process a message that the server has received from the client.
1038 MSG_PROCESS_RETURN ossl_statem_server_process_message(SSL *s, PACKET *pkt)
1040 OSSL_STATEM *st = &s->statem;
1042 switch (st->hand_state) {
1044 /* Shouldn't happen */
1045 return MSG_PROCESS_ERROR;
1047 case TLS_ST_SR_CLNT_HELLO:
1048 return tls_process_client_hello(s, pkt);
1050 case TLS_ST_SR_END_OF_EARLY_DATA:
1051 return tls_process_end_of_early_data(s, pkt);
1053 case TLS_ST_SR_CERT:
1054 return tls_process_client_certificate(s, pkt);
1056 case TLS_ST_SR_KEY_EXCH:
1057 return tls_process_client_key_exchange(s, pkt);
1059 case TLS_ST_SR_CERT_VRFY:
1060 return tls_process_cert_verify(s, pkt);
1062 #ifndef OPENSSL_NO_NEXTPROTONEG
1063 case TLS_ST_SR_NEXT_PROTO:
1064 return tls_process_next_proto(s, pkt);
1067 case TLS_ST_SR_CHANGE:
1068 return tls_process_change_cipher_spec(s, pkt);
1070 case TLS_ST_SR_FINISHED:
1071 return tls_process_finished(s, pkt);
1073 case TLS_ST_SR_KEY_UPDATE:
1074 return tls_process_key_update(s, pkt);
1080 * Perform any further processing required following the receipt of a message
1083 WORK_STATE ossl_statem_server_post_process_message(SSL *s, WORK_STATE wst)
1085 OSSL_STATEM *st = &s->statem;
1087 switch (st->hand_state) {
1089 /* Shouldn't happen */
1092 case TLS_ST_SR_CLNT_HELLO:
1093 return tls_post_process_client_hello(s, wst);
1095 case TLS_ST_SR_KEY_EXCH:
1096 return tls_post_process_client_key_exchange(s, wst);
1098 return WORK_FINISHED_CONTINUE;
1101 #ifndef OPENSSL_NO_SRP
1102 static int ssl_check_srp_ext_ClientHello(SSL *s, int *al)
1104 int ret = SSL_ERROR_NONE;
1106 *al = SSL_AD_UNRECOGNIZED_NAME;
1108 if ((s->s3->tmp.new_cipher->algorithm_mkey & SSL_kSRP) &&
1109 (s->srp_ctx.TLS_ext_srp_username_callback != NULL)) {
1110 if (s->srp_ctx.login == NULL) {
1112 * RFC 5054 says SHOULD reject, we do so if There is no srp
1115 ret = SSL3_AL_FATAL;
1116 *al = SSL_AD_UNKNOWN_PSK_IDENTITY;
1118 ret = SSL_srp_server_param_with_username(s, al);
1125 int dtls_raw_hello_verify_request(WPACKET *pkt, unsigned char *cookie,
1128 /* Always use DTLS 1.0 version: see RFC 6347 */
1129 if (!WPACKET_put_bytes_u16(pkt, DTLS1_VERSION)
1130 || !WPACKET_sub_memcpy_u8(pkt, cookie, cookie_len))
1136 int dtls_construct_hello_verify_request(SSL *s, WPACKET *pkt)
1138 unsigned int cookie_leni;
1139 if (s->ctx->app_gen_cookie_cb == NULL ||
1140 s->ctx->app_gen_cookie_cb(s, s->d1->cookie,
1141 &cookie_leni) == 0 ||
1142 cookie_leni > 255) {
1143 SSLerr(SSL_F_DTLS_CONSTRUCT_HELLO_VERIFY_REQUEST,
1144 SSL_R_COOKIE_GEN_CALLBACK_FAILURE);
1147 s->d1->cookie_len = cookie_leni;
1149 if (!dtls_raw_hello_verify_request(pkt, s->d1->cookie,
1150 s->d1->cookie_len)) {
1151 SSLerr(SSL_F_DTLS_CONSTRUCT_HELLO_VERIFY_REQUEST, ERR_R_INTERNAL_ERROR);
1158 #ifndef OPENSSL_NO_EC
1160 * ssl_check_for_safari attempts to fingerprint Safari using OS X
1161 * SecureTransport using the TLS extension block in |hello|.
1162 * Safari, since 10.6, sends exactly these extensions, in this order:
1166 * signature_algorithms (for TLSv1.2 only)
1168 * We wish to fingerprint Safari because they broke ECDHE-ECDSA support in 10.8,
1169 * but they advertise support. So enabling ECDHE-ECDSA ciphers breaks them.
1170 * Sadly we cannot differentiate 10.6, 10.7 and 10.8.4 (which work), from
1171 * 10.8..10.8.3 (which don't work).
1173 static void ssl_check_for_safari(SSL *s, const CLIENTHELLO_MSG *hello)
1175 static const unsigned char kSafariExtensionsBlock[] = {
1176 0x00, 0x0a, /* elliptic_curves extension */
1177 0x00, 0x08, /* 8 bytes */
1178 0x00, 0x06, /* 6 bytes of curve ids */
1179 0x00, 0x17, /* P-256 */
1180 0x00, 0x18, /* P-384 */
1181 0x00, 0x19, /* P-521 */
1183 0x00, 0x0b, /* ec_point_formats */
1184 0x00, 0x02, /* 2 bytes */
1185 0x01, /* 1 point format */
1186 0x00, /* uncompressed */
1187 /* The following is only present in TLS 1.2 */
1188 0x00, 0x0d, /* signature_algorithms */
1189 0x00, 0x0c, /* 12 bytes */
1190 0x00, 0x0a, /* 10 bytes */
1191 0x05, 0x01, /* SHA-384/RSA */
1192 0x04, 0x01, /* SHA-256/RSA */
1193 0x02, 0x01, /* SHA-1/RSA */
1194 0x04, 0x03, /* SHA-256/ECDSA */
1195 0x02, 0x03, /* SHA-1/ECDSA */
1197 /* Length of the common prefix (first two extensions). */
1198 static const size_t kSafariCommonExtensionsLength = 18;
1203 tmppkt = hello->extensions;
1205 if (!PACKET_forward(&tmppkt, 2)
1206 || !PACKET_get_net_2(&tmppkt, &type)
1207 || !PACKET_get_length_prefixed_2(&tmppkt, &sni)) {
1211 if (type != TLSEXT_TYPE_server_name)
1214 ext_len = TLS1_get_client_version(s) >= TLS1_2_VERSION ?
1215 sizeof(kSafariExtensionsBlock) : kSafariCommonExtensionsLength;
1217 s->s3->is_probably_safari = PACKET_equal(&tmppkt, kSafariExtensionsBlock,
1220 #endif /* !OPENSSL_NO_EC */
1222 MSG_PROCESS_RETURN tls_process_client_hello(SSL *s, PACKET *pkt)
1224 int al = SSL_AD_INTERNAL_ERROR;
1225 /* |cookie| will only be initialized for DTLS. */
1226 PACKET session_id, compression, extensions, cookie;
1227 static const unsigned char null_compression = 0;
1228 CLIENTHELLO_MSG *clienthello;
1230 clienthello = OPENSSL_zalloc(sizeof(*clienthello));
1231 if (clienthello == NULL) {
1232 SSLerr(SSL_F_TLS_PROCESS_CLIENT_HELLO, ERR_R_INTERNAL_ERROR);
1235 /* Check if this is actually an unexpected renegotiation ClientHello */
1236 if (s->renegotiate == 0 && !SSL_IS_FIRST_HANDSHAKE(s)) {
1237 if ((s->options & SSL_OP_NO_RENEGOTIATION)) {
1238 ssl3_send_alert(s, SSL3_AL_WARNING, SSL_AD_NO_RENEGOTIATION);
1246 * First, parse the raw ClientHello data into the CLIENTHELLO_MSG structure.
1248 clienthello->isv2 = RECORD_LAYER_is_sslv2_record(&s->rlayer);
1249 PACKET_null_init(&cookie);
1251 if (clienthello->isv2) {
1254 if (!SSL_IS_FIRST_HANDSHAKE(s) || s->hello_retry_request) {
1255 al = SSL_AD_UNEXPECTED_MESSAGE;
1256 SSLerr(SSL_F_TLS_PROCESS_CLIENT_HELLO, SSL_R_UNEXPECTED_MESSAGE);
1261 * An SSLv3/TLSv1 backwards-compatible CLIENT-HELLO in an SSLv2
1262 * header is sent directly on the wire, not wrapped as a TLS
1263 * record. Our record layer just processes the message length and passes
1264 * the rest right through. Its format is:
1266 * 0-1 msg_length - decoded by the record layer
1267 * 2 msg_type - s->init_msg points here
1269 * 5-6 cipher_spec_length
1270 * 7-8 session_id_length
1271 * 9-10 challenge_length
1275 if (!PACKET_get_1(pkt, &mt)
1276 || mt != SSL2_MT_CLIENT_HELLO) {
1278 * Should never happen. We should have tested this in the record
1279 * layer in order to have determined that this is a SSLv2 record
1280 * in the first place
1282 SSLerr(SSL_F_TLS_PROCESS_CLIENT_HELLO, ERR_R_INTERNAL_ERROR);
1287 if (!PACKET_get_net_2(pkt, &clienthello->legacy_version)) {
1288 al = SSL_AD_DECODE_ERROR;
1289 SSLerr(SSL_F_TLS_PROCESS_CLIENT_HELLO, SSL_R_LENGTH_TOO_SHORT);
1293 /* Parse the message and load client random. */
1294 if (clienthello->isv2) {
1296 * Handle an SSLv2 backwards compatible ClientHello
1297 * Note, this is only for SSLv3+ using the backward compatible format.
1298 * Real SSLv2 is not supported, and is rejected below.
1300 unsigned int ciphersuite_len, session_id_len, challenge_len;
1303 if (!PACKET_get_net_2(pkt, &ciphersuite_len)
1304 || !PACKET_get_net_2(pkt, &session_id_len)
1305 || !PACKET_get_net_2(pkt, &challenge_len)) {
1306 SSLerr(SSL_F_TLS_PROCESS_CLIENT_HELLO,
1307 SSL_R_RECORD_LENGTH_MISMATCH);
1308 al = SSL_AD_DECODE_ERROR;
1312 if (session_id_len > SSL_MAX_SSL_SESSION_ID_LENGTH) {
1313 al = SSL_AD_ILLEGAL_PARAMETER;
1314 SSLerr(SSL_F_TLS_PROCESS_CLIENT_HELLO, SSL_R_LENGTH_MISMATCH);
1318 if (!PACKET_get_sub_packet(pkt, &clienthello->ciphersuites,
1320 || !PACKET_copy_bytes(pkt, clienthello->session_id, session_id_len)
1321 || !PACKET_get_sub_packet(pkt, &challenge, challenge_len)
1322 /* No extensions. */
1323 || PACKET_remaining(pkt) != 0) {
1324 SSLerr(SSL_F_TLS_PROCESS_CLIENT_HELLO,
1325 SSL_R_RECORD_LENGTH_MISMATCH);
1326 al = SSL_AD_DECODE_ERROR;
1329 clienthello->session_id_len = session_id_len;
1331 /* Load the client random and compression list. We use SSL3_RANDOM_SIZE
1332 * here rather than sizeof(clienthello->random) because that is the limit
1333 * for SSLv3 and it is fixed. It won't change even if
1334 * sizeof(clienthello->random) does.
1336 challenge_len = challenge_len > SSL3_RANDOM_SIZE
1337 ? SSL3_RANDOM_SIZE : challenge_len;
1338 memset(clienthello->random, 0, SSL3_RANDOM_SIZE);
1339 if (!PACKET_copy_bytes(&challenge,
1340 clienthello->random + SSL3_RANDOM_SIZE -
1341 challenge_len, challenge_len)
1342 /* Advertise only null compression. */
1343 || !PACKET_buf_init(&compression, &null_compression, 1)) {
1344 SSLerr(SSL_F_TLS_PROCESS_CLIENT_HELLO, ERR_R_INTERNAL_ERROR);
1345 al = SSL_AD_INTERNAL_ERROR;
1349 PACKET_null_init(&clienthello->extensions);
1351 /* Regular ClientHello. */
1352 if (!PACKET_copy_bytes(pkt, clienthello->random, SSL3_RANDOM_SIZE)
1353 || !PACKET_get_length_prefixed_1(pkt, &session_id)
1354 || !PACKET_copy_all(&session_id, clienthello->session_id,
1355 SSL_MAX_SSL_SESSION_ID_LENGTH,
1356 &clienthello->session_id_len)) {
1357 al = SSL_AD_DECODE_ERROR;
1358 SSLerr(SSL_F_TLS_PROCESS_CLIENT_HELLO, SSL_R_LENGTH_MISMATCH);
1362 if (SSL_IS_DTLS(s)) {
1363 if (!PACKET_get_length_prefixed_1(pkt, &cookie)) {
1364 al = SSL_AD_DECODE_ERROR;
1365 SSLerr(SSL_F_TLS_PROCESS_CLIENT_HELLO, SSL_R_LENGTH_MISMATCH);
1368 if (!PACKET_copy_all(&cookie, clienthello->dtls_cookie,
1369 DTLS1_COOKIE_LENGTH,
1370 &clienthello->dtls_cookie_len)) {
1371 al = SSL_AD_INTERNAL_ERROR;
1372 SSLerr(SSL_F_TLS_PROCESS_CLIENT_HELLO, ERR_R_INTERNAL_ERROR);
1376 * If we require cookies and this ClientHello doesn't contain one,
1377 * just return since we do not want to allocate any memory yet.
1378 * So check cookie length...
1380 if (SSL_get_options(s) & SSL_OP_COOKIE_EXCHANGE) {
1381 if (clienthello->dtls_cookie_len == 0)
1386 if (!PACKET_get_length_prefixed_2(pkt, &clienthello->ciphersuites)) {
1387 al = SSL_AD_DECODE_ERROR;
1388 SSLerr(SSL_F_TLS_PROCESS_CLIENT_HELLO, SSL_R_LENGTH_MISMATCH);
1392 if (!PACKET_get_length_prefixed_1(pkt, &compression)) {
1393 al = SSL_AD_DECODE_ERROR;
1394 SSLerr(SSL_F_TLS_PROCESS_CLIENT_HELLO, SSL_R_LENGTH_MISMATCH);
1398 /* Could be empty. */
1399 if (PACKET_remaining(pkt) == 0) {
1400 PACKET_null_init(&clienthello->extensions);
1402 if (!PACKET_get_length_prefixed_2(pkt, &clienthello->extensions)
1403 || PACKET_remaining(pkt) != 0) {
1404 al = SSL_AD_DECODE_ERROR;
1405 SSLerr(SSL_F_TLS_PROCESS_CLIENT_HELLO, SSL_R_LENGTH_MISMATCH);
1411 if (!PACKET_copy_all(&compression, clienthello->compressions,
1412 MAX_COMPRESSIONS_SIZE,
1413 &clienthello->compressions_len)) {
1414 al = SSL_AD_INTERNAL_ERROR;
1415 SSLerr(SSL_F_TLS_PROCESS_CLIENT_HELLO, ERR_R_INTERNAL_ERROR);
1419 /* Preserve the raw extensions PACKET for later use */
1420 extensions = clienthello->extensions;
1421 if (!tls_collect_extensions(s, &extensions, SSL_EXT_CLIENT_HELLO,
1422 &clienthello->pre_proc_exts, &al,
1423 &clienthello->pre_proc_exts_len, 1)) {
1424 /* SSLerr already been called */
1427 s->clienthello = clienthello;
1429 return MSG_PROCESS_CONTINUE_PROCESSING;
1431 ssl3_send_alert(s, SSL3_AL_FATAL, al);
1433 ossl_statem_set_error(s);
1435 if (clienthello != NULL)
1436 OPENSSL_free(clienthello->pre_proc_exts);
1437 OPENSSL_free(clienthello);
1439 return MSG_PROCESS_ERROR;
1442 static int tls_early_post_process_client_hello(SSL *s, int *pal)
1445 int i, al = SSL_AD_INTERNAL_ERROR;
1449 #ifndef OPENSSL_NO_COMP
1450 SSL_COMP *comp = NULL;
1452 const SSL_CIPHER *c;
1453 STACK_OF(SSL_CIPHER) *ciphers = NULL;
1454 STACK_OF(SSL_CIPHER) *scsvs = NULL;
1455 CLIENTHELLO_MSG *clienthello = s->clienthello;
1456 DOWNGRADE dgrd = DOWNGRADE_NONE;
1458 /* Finished parsing the ClientHello, now we can start processing it */
1459 /* Give the early callback a crack at things */
1460 if (s->ctx->early_cb != NULL) {
1462 /* A failure in the early callback terminates the connection. */
1463 code = s->ctx->early_cb(s, &al, s->ctx->early_cb_arg);
1467 s->rwstate = SSL_EARLY_WORK;
1472 /* Set up the client_random */
1473 memcpy(s->s3->client_random, clienthello->random, SSL3_RANDOM_SIZE);
1475 /* Choose the version */
1477 if (clienthello->isv2) {
1478 if (clienthello->legacy_version == SSL2_VERSION
1479 || (clienthello->legacy_version & 0xff00)
1480 != (SSL3_VERSION_MAJOR << 8)) {
1482 * This is real SSLv2 or something complete unknown. We don't
1485 SSLerr(SSL_F_TLS_EARLY_POST_PROCESS_CLIENT_HELLO, SSL_R_UNKNOWN_PROTOCOL);
1489 s->client_version = clienthello->legacy_version;
1492 * Do SSL/TLS version negotiation if applicable. For DTLS we just check
1493 * versions are potentially compatible. Version negotiation comes later.
1495 if (!SSL_IS_DTLS(s)) {
1496 protverr = ssl_choose_server_version(s, clienthello, &dgrd);
1497 } else if (s->method->version != DTLS_ANY_VERSION &&
1498 DTLS_VERSION_LT((int)clienthello->legacy_version, s->version)) {
1499 protverr = SSL_R_VERSION_TOO_LOW;
1505 SSLerr(SSL_F_TLS_EARLY_POST_PROCESS_CLIENT_HELLO, protverr);
1506 if (SSL_IS_FIRST_HANDSHAKE(s)) {
1507 /* like ssl3_get_record, send alert using remote version number */
1508 s->version = s->client_version = clienthello->legacy_version;
1510 al = SSL_AD_PROTOCOL_VERSION;
1514 /* TLSv1.3 specifies that a ClientHello must end on a record boundary */
1515 if (SSL_IS_TLS13(s) && RECORD_LAYER_processed_read_pending(&s->rlayer)) {
1516 al = SSL_AD_UNEXPECTED_MESSAGE;
1517 SSLerr(SSL_F_TLS_EARLY_POST_PROCESS_CLIENT_HELLO,
1518 SSL_R_NOT_ON_RECORD_BOUNDARY);
1522 if (SSL_IS_DTLS(s)) {
1523 /* Empty cookie was already handled above by returning early. */
1524 if (SSL_get_options(s) & SSL_OP_COOKIE_EXCHANGE) {
1525 if (s->ctx->app_verify_cookie_cb != NULL) {
1526 if (s->ctx->app_verify_cookie_cb(s, clienthello->dtls_cookie,
1527 clienthello->dtls_cookie_len) == 0) {
1528 al = SSL_AD_HANDSHAKE_FAILURE;
1529 SSLerr(SSL_F_TLS_EARLY_POST_PROCESS_CLIENT_HELLO,
1530 SSL_R_COOKIE_MISMATCH);
1532 /* else cookie verification succeeded */
1534 /* default verification */
1535 } else if (s->d1->cookie_len != clienthello->dtls_cookie_len
1536 || memcmp(clienthello->dtls_cookie, s->d1->cookie,
1537 s->d1->cookie_len) != 0) {
1538 al = SSL_AD_HANDSHAKE_FAILURE;
1539 SSLerr(SSL_F_TLS_EARLY_POST_PROCESS_CLIENT_HELLO, SSL_R_COOKIE_MISMATCH);
1542 s->d1->cookie_verified = 1;
1544 if (s->method->version == DTLS_ANY_VERSION) {
1545 protverr = ssl_choose_server_version(s, clienthello, &dgrd);
1546 if (protverr != 0) {
1547 SSLerr(SSL_F_TLS_EARLY_POST_PROCESS_CLIENT_HELLO, protverr);
1548 s->version = s->client_version;
1549 al = SSL_AD_PROTOCOL_VERSION;
1557 if (!ssl_cache_cipherlist(s, &clienthello->ciphersuites,
1558 clienthello->isv2, &al) ||
1559 !bytes_to_cipher_list(s, &clienthello->ciphersuites, &ciphers, &scsvs,
1560 clienthello->isv2, &al)) {
1564 s->s3->send_connection_binding = 0;
1565 /* Check what signalling cipher-suite values were received. */
1566 if (scsvs != NULL) {
1567 for(i = 0; i < sk_SSL_CIPHER_num(scsvs); i++) {
1568 c = sk_SSL_CIPHER_value(scsvs, i);
1569 if (SSL_CIPHER_get_id(c) == SSL3_CK_SCSV) {
1570 if (s->renegotiate) {
1571 /* SCSV is fatal if renegotiating */
1572 SSLerr(SSL_F_TLS_EARLY_POST_PROCESS_CLIENT_HELLO,
1573 SSL_R_SCSV_RECEIVED_WHEN_RENEGOTIATING);
1574 al = SSL_AD_HANDSHAKE_FAILURE;
1577 s->s3->send_connection_binding = 1;
1578 } else if (SSL_CIPHER_get_id(c) == SSL3_CK_FALLBACK_SCSV &&
1579 !ssl_check_version_downgrade(s)) {
1581 * This SCSV indicates that the client previously tried
1582 * a higher version. We should fail if the current version
1583 * is an unexpected downgrade, as that indicates that the first
1584 * connection may have been tampered with in order to trigger
1585 * an insecure downgrade.
1587 SSLerr(SSL_F_TLS_EARLY_POST_PROCESS_CLIENT_HELLO,
1588 SSL_R_INAPPROPRIATE_FALLBACK);
1589 al = SSL_AD_INAPPROPRIATE_FALLBACK;
1595 /* For TLSv1.3 we must select the ciphersuite *before* session resumption */
1596 if (SSL_IS_TLS13(s)) {
1597 const SSL_CIPHER *cipher =
1598 ssl3_choose_cipher(s, ciphers, SSL_get_ciphers(s));
1600 if (cipher == NULL) {
1601 SSLerr(SSL_F_TLS_EARLY_POST_PROCESS_CLIENT_HELLO,
1602 SSL_R_NO_SHARED_CIPHER);
1603 al = SSL_AD_HANDSHAKE_FAILURE;
1606 if (s->hello_retry_request
1607 && (s->s3->tmp.new_cipher == NULL
1608 || s->s3->tmp.new_cipher->id != cipher->id)) {
1610 * A previous HRR picked a different ciphersuite to the one we
1611 * just selected. Something must have changed.
1613 al = SSL_AD_ILLEGAL_PARAMETER;
1614 SSLerr(SSL_F_TLS_EARLY_POST_PROCESS_CLIENT_HELLO, SSL_R_BAD_CIPHER);
1617 s->s3->tmp.new_cipher = cipher;
1620 /* We need to do this before getting the session */
1621 if (!tls_parse_extension(s, TLSEXT_IDX_extended_master_secret,
1622 SSL_EXT_CLIENT_HELLO,
1623 clienthello->pre_proc_exts, NULL, 0, &al)) {
1624 SSLerr(SSL_F_TLS_EARLY_POST_PROCESS_CLIENT_HELLO, SSL_R_CLIENTHELLO_TLSEXT);
1629 * We don't allow resumption in a backwards compatible ClientHello.
1630 * TODO(openssl-team): in TLS1.1+, session_id MUST be empty.
1632 * Versions before 0.9.7 always allow clients to resume sessions in
1633 * renegotiation. 0.9.7 and later allow this by default, but optionally
1634 * ignore resumption requests with flag
1635 * SSL_OP_NO_SESSION_RESUMPTION_ON_RENEGOTIATION (it's a new flag rather
1636 * than a change to default behavior so that applications relying on
1637 * this for security won't even compile against older library versions).
1638 * 1.0.1 and later also have a function SSL_renegotiate_abbreviated() to
1639 * request renegotiation but not a new session (s->new_session remains
1640 * unset): for servers, this essentially just means that the
1641 * SSL_OP_NO_SESSION_RESUMPTION_ON_RENEGOTIATION setting will be
1644 if (clienthello->isv2 ||
1646 (s->options & SSL_OP_NO_SESSION_RESUMPTION_ON_RENEGOTIATION))) {
1647 if (!ssl_get_new_session(s, 1))
1650 i = ssl_get_prev_session(s, clienthello, &al);
1652 /* previous session */
1654 } else if (i == -1) {
1658 if (!ssl_get_new_session(s, 1))
1664 * If it is a hit, check that the cipher is in the list. In TLSv1.3 we check
1665 * ciphersuite compatibility with the session as part of resumption.
1667 if (!SSL_IS_TLS13(s) && s->hit) {
1669 id = s->session->cipher->id;
1672 fprintf(stderr, "client sent %d ciphers\n", sk_SSL_CIPHER_num(ciphers));
1674 for (i = 0; i < sk_SSL_CIPHER_num(ciphers); i++) {
1675 c = sk_SSL_CIPHER_value(ciphers, i);
1677 fprintf(stderr, "client [%2d of %2d]:%s\n",
1678 i, sk_SSL_CIPHER_num(ciphers), SSL_CIPHER_get_name(c));
1687 * we need to have the cipher in the cipher list if we are asked
1690 al = SSL_AD_ILLEGAL_PARAMETER;
1691 SSLerr(SSL_F_TLS_EARLY_POST_PROCESS_CLIENT_HELLO,
1692 SSL_R_REQUIRED_CIPHER_MISSING);
1697 for (loop = 0; loop < clienthello->compressions_len; loop++) {
1698 if (clienthello->compressions[loop] == 0)
1702 if (loop >= clienthello->compressions_len) {
1704 al = SSL_AD_DECODE_ERROR;
1705 SSLerr(SSL_F_TLS_EARLY_POST_PROCESS_CLIENT_HELLO, SSL_R_NO_COMPRESSION_SPECIFIED);
1709 #ifndef OPENSSL_NO_EC
1710 if (s->options & SSL_OP_SAFARI_ECDHE_ECDSA_BUG)
1711 ssl_check_for_safari(s, clienthello);
1712 #endif /* !OPENSSL_NO_EC */
1714 /* TLS extensions */
1715 if (!tls_parse_all_extensions(s, SSL_EXT_CLIENT_HELLO,
1716 clienthello->pre_proc_exts, NULL, 0, &al, 1)) {
1717 SSLerr(SSL_F_TLS_EARLY_POST_PROCESS_CLIENT_HELLO, SSL_R_PARSE_TLSEXT);
1722 * Check if we want to use external pre-shared secret for this handshake
1723 * for not reused session only. We need to generate server_random before
1724 * calling tls_session_secret_cb in order to allow SessionTicket
1725 * processing to use it in key derivation.
1729 pos = s->s3->server_random;
1730 if (ssl_fill_hello_random(s, 1, pos, SSL3_RANDOM_SIZE, dgrd) <= 0) {
1736 && s->version >= TLS1_VERSION
1739 && s->ext.session_secret_cb) {
1740 const SSL_CIPHER *pref_cipher = NULL;
1742 * s->session->master_key_length is a size_t, but this is an int for
1743 * backwards compat reasons
1745 int master_key_length;
1747 master_key_length = sizeof(s->session->master_key);
1748 if (s->ext.session_secret_cb(s, s->session->master_key,
1749 &master_key_length, ciphers,
1751 s->ext.session_secret_cb_arg)
1752 && master_key_length > 0) {
1753 s->session->master_key_length = master_key_length;
1755 s->session->ciphers = ciphers;
1756 s->session->verify_result = X509_V_OK;
1760 /* check if some cipher was preferred by call back */
1761 if (pref_cipher == NULL)
1762 pref_cipher = ssl3_choose_cipher(s, s->session->ciphers,
1763 SSL_get_ciphers(s));
1764 if (pref_cipher == NULL) {
1765 al = SSL_AD_HANDSHAKE_FAILURE;
1766 SSLerr(SSL_F_TLS_EARLY_POST_PROCESS_CLIENT_HELLO, SSL_R_NO_SHARED_CIPHER);
1770 s->session->cipher = pref_cipher;
1771 sk_SSL_CIPHER_free(s->cipher_list);
1772 s->cipher_list = sk_SSL_CIPHER_dup(s->session->ciphers);
1773 sk_SSL_CIPHER_free(s->cipher_list_by_id);
1774 s->cipher_list_by_id = sk_SSL_CIPHER_dup(s->session->ciphers);
1779 * Worst case, we will use the NULL compression, but if we have other
1780 * options, we will now look for them. We have complen-1 compression
1781 * algorithms from the client, starting at q.
1783 s->s3->tmp.new_compression = NULL;
1784 if (SSL_IS_TLS13(s)) {
1786 * We already checked above that the NULL compression method appears in
1787 * the list. Now we check there aren't any others (which is illegal in
1788 * a TLSv1.3 ClientHello.
1790 if (clienthello->compressions_len != 1) {
1791 al = SSL_AD_ILLEGAL_PARAMETER;
1792 SSLerr(SSL_F_TLS_EARLY_POST_PROCESS_CLIENT_HELLO,
1793 SSL_R_INVALID_COMPRESSION_ALGORITHM);
1797 #ifndef OPENSSL_NO_COMP
1798 /* This only happens if we have a cache hit */
1799 else if (s->session->compress_meth != 0) {
1800 int m, comp_id = s->session->compress_meth;
1802 /* Perform sanity checks on resumed compression algorithm */
1803 /* Can't disable compression */
1804 if (!ssl_allow_compression(s)) {
1805 SSLerr(SSL_F_TLS_EARLY_POST_PROCESS_CLIENT_HELLO,
1806 SSL_R_INCONSISTENT_COMPRESSION);
1809 /* Look for resumed compression method */
1810 for (m = 0; m < sk_SSL_COMP_num(s->ctx->comp_methods); m++) {
1811 comp = sk_SSL_COMP_value(s->ctx->comp_methods, m);
1812 if (comp_id == comp->id) {
1813 s->s3->tmp.new_compression = comp;
1817 if (s->s3->tmp.new_compression == NULL) {
1818 SSLerr(SSL_F_TLS_EARLY_POST_PROCESS_CLIENT_HELLO,
1819 SSL_R_INVALID_COMPRESSION_ALGORITHM);
1822 /* Look for resumed method in compression list */
1823 for (k = 0; k < clienthello->compressions_len; k++) {
1824 if (clienthello->compressions[k] == comp_id)
1827 if (k >= clienthello->compressions_len) {
1828 al = SSL_AD_ILLEGAL_PARAMETER;
1829 SSLerr(SSL_F_TLS_EARLY_POST_PROCESS_CLIENT_HELLO,
1830 SSL_R_REQUIRED_COMPRESSION_ALGORITHM_MISSING);
1833 } else if (s->hit) {
1835 } else if (ssl_allow_compression(s) && s->ctx->comp_methods) {
1836 /* See if we have a match */
1837 int m, nn, v, done = 0;
1840 nn = sk_SSL_COMP_num(s->ctx->comp_methods);
1841 for (m = 0; m < nn; m++) {
1842 comp = sk_SSL_COMP_value(s->ctx->comp_methods, m);
1844 for (o = 0; o < clienthello->compressions_len; o++) {
1845 if (v == clienthello->compressions[o]) {
1854 s->s3->tmp.new_compression = comp;
1860 * If compression is disabled we'd better not try to resume a session
1861 * using compression.
1863 if (s->session->compress_meth != 0) {
1864 SSLerr(SSL_F_TLS_EARLY_POST_PROCESS_CLIENT_HELLO, SSL_R_INCONSISTENT_COMPRESSION);
1870 * Given s->session->ciphers and SSL_get_ciphers, we must pick a cipher
1873 if (!s->hit || SSL_IS_TLS13(s)) {
1874 sk_SSL_CIPHER_free(s->session->ciphers);
1875 s->session->ciphers = ciphers;
1876 if (ciphers == NULL) {
1877 al = SSL_AD_INTERNAL_ERROR;
1878 SSLerr(SSL_F_TLS_EARLY_POST_PROCESS_CLIENT_HELLO, ERR_R_INTERNAL_ERROR);
1885 #ifdef OPENSSL_NO_COMP
1886 s->session->compress_meth = 0;
1888 s->session->compress_meth = (comp == NULL) ? 0 : comp->id;
1890 if (!tls1_set_server_sigalgs(s)) {
1891 SSLerr(SSL_F_TLS_EARLY_POST_PROCESS_CLIENT_HELLO, SSL_R_CLIENTHELLO_TLSEXT);
1896 sk_SSL_CIPHER_free(ciphers);
1897 sk_SSL_CIPHER_free(scsvs);
1898 OPENSSL_free(clienthello->pre_proc_exts);
1899 OPENSSL_free(s->clienthello);
1900 s->clienthello = NULL;
1903 ossl_statem_set_error(s);
1906 sk_SSL_CIPHER_free(ciphers);
1907 sk_SSL_CIPHER_free(scsvs);
1908 OPENSSL_free(clienthello->pre_proc_exts);
1909 OPENSSL_free(s->clienthello);
1910 s->clienthello = NULL;
1916 * Call the status request callback if needed. Upon success, returns 1.
1917 * Upon failure, returns 0 and sets |*al| to the appropriate fatal alert.
1919 static int tls_handle_status_request(SSL *s, int *al)
1921 s->ext.status_expected = 0;
1924 * If status request then ask callback what to do. Note: this must be
1925 * called after servername callbacks in case the certificate has changed,
1926 * and must be called after the cipher has been chosen because this may
1927 * influence which certificate is sent
1929 if (s->ext.status_type != TLSEXT_STATUSTYPE_nothing && s->ctx != NULL
1930 && s->ctx->ext.status_cb != NULL) {
1933 /* If no certificate can't return certificate status */
1934 if (s->s3->tmp.cert != NULL) {
1936 * Set current certificate to one we will use so SSL_get_certificate
1937 * et al can pick it up.
1939 s->cert->key = s->s3->tmp.cert;
1940 ret = s->ctx->ext.status_cb(s, s->ctx->ext.status_arg);
1942 /* We don't want to send a status request response */
1943 case SSL_TLSEXT_ERR_NOACK:
1944 s->ext.status_expected = 0;
1946 /* status request response should be sent */
1947 case SSL_TLSEXT_ERR_OK:
1948 if (s->ext.ocsp.resp)
1949 s->ext.status_expected = 1;
1951 /* something bad happened */
1952 case SSL_TLSEXT_ERR_ALERT_FATAL:
1954 *al = SSL_AD_INTERNAL_ERROR;
1963 WORK_STATE tls_post_process_client_hello(SSL *s, WORK_STATE wst)
1965 int al = SSL_AD_HANDSHAKE_FAILURE;
1966 const SSL_CIPHER *cipher;
1968 if (wst == WORK_MORE_A) {
1969 int rv = tls_early_post_process_client_hello(s, &al);
1971 /* SSLErr() was already called */
1978 if (wst == WORK_MORE_B) {
1979 if (!s->hit || SSL_IS_TLS13(s)) {
1980 /* Let cert callback update server certificates if required */
1981 if (!s->hit && s->cert->cert_cb != NULL) {
1982 int rv = s->cert->cert_cb(s, s->cert->cert_cb_arg);
1984 al = SSL_AD_INTERNAL_ERROR;
1985 SSLerr(SSL_F_TLS_POST_PROCESS_CLIENT_HELLO,
1986 SSL_R_CERT_CB_ERROR);
1990 s->rwstate = SSL_X509_LOOKUP;
1993 s->rwstate = SSL_NOTHING;
1996 /* In TLSv1.3 we selected the ciphersuite before resumption */
1997 if (!SSL_IS_TLS13(s)) {
1999 ssl3_choose_cipher(s, s->session->ciphers, SSL_get_ciphers(s));
2001 if (cipher == NULL) {
2002 SSLerr(SSL_F_TLS_POST_PROCESS_CLIENT_HELLO,
2003 SSL_R_NO_SHARED_CIPHER);
2006 s->s3->tmp.new_cipher = cipher;
2009 if (!tls_choose_sigalg(s, &al))
2011 /* check whether we should disable session resumption */
2012 if (s->not_resumable_session_cb != NULL)
2013 s->session->not_resumable =
2014 s->not_resumable_session_cb(s,
2015 ((s->s3->tmp.new_cipher->algorithm_mkey
2016 & (SSL_kDHE | SSL_kECDHE)) != 0));
2017 if (s->session->not_resumable)
2018 /* do not send a session ticket */
2019 s->ext.ticket_expected = 0;
2022 /* Session-id reuse */
2023 s->s3->tmp.new_cipher = s->session->cipher;
2027 * we now have the following setup.
2029 * cipher_list - our preferred list of ciphers
2030 * ciphers - the clients preferred list of ciphers
2031 * compression - basically ignored right now
2032 * ssl version is set - sslv3
2033 * s->session - The ssl session has been setup.
2034 * s->hit - session reuse flag
2035 * s->s3->tmp.new_cipher- the new cipher to use.
2039 * Call status_request callback if needed. Has to be done after the
2040 * certificate callbacks etc above.
2042 if (!tls_handle_status_request(s, &al)) {
2043 SSLerr(SSL_F_TLS_POST_PROCESS_CLIENT_HELLO,
2044 SSL_R_CLIENTHELLO_TLSEXT);
2050 #ifndef OPENSSL_NO_SRP
2051 if (wst == WORK_MORE_C) {
2053 if ((ret = ssl_check_srp_ext_ClientHello(s, &al)) < 0) {
2055 * callback indicates further work to be done
2057 s->rwstate = SSL_X509_LOOKUP;
2060 if (ret != SSL_ERROR_NONE) {
2062 * This is not really an error but the only means to for
2063 * a client to detect whether srp is supported.
2065 if (al != TLS1_AD_UNKNOWN_PSK_IDENTITY)
2066 SSLerr(SSL_F_TLS_POST_PROCESS_CLIENT_HELLO,
2067 SSL_R_CLIENTHELLO_TLSEXT);
2069 SSLerr(SSL_F_TLS_POST_PROCESS_CLIENT_HELLO,
2070 SSL_R_PSK_IDENTITY_NOT_FOUND);
2076 return WORK_FINISHED_STOP;
2078 ssl3_send_alert(s, SSL3_AL_FATAL, al);
2079 ossl_statem_set_error(s);
2083 int tls_construct_server_hello(SSL *s, WPACKET *pkt)
2085 int compm, al = SSL_AD_INTERNAL_ERROR;
2089 /* TODO(TLS1.3): Remove the DRAFT conditional before release */
2090 version = SSL_IS_TLS13(s) ? TLS1_3_VERSION_DRAFT : s->version;
2091 if (!WPACKET_put_bytes_u16(pkt, version)
2093 * Random stuff. Filling of the server_random takes place in
2094 * tls_process_client_hello()
2096 || !WPACKET_memcpy(pkt, s->s3->server_random, SSL3_RANDOM_SIZE)) {
2097 SSLerr(SSL_F_TLS_CONSTRUCT_SERVER_HELLO, ERR_R_INTERNAL_ERROR);
2102 * There are several cases for the session ID to send
2103 * back in the server hello:
2104 * - For session reuse from the session cache,
2105 * we send back the old session ID.
2106 * - If stateless session reuse (using a session ticket)
2107 * is successful, we send back the client's "session ID"
2108 * (which doesn't actually identify the session).
2109 * - If it is a new session, we send back the new
2111 * - However, if we want the new session to be single-use,
2112 * we send back a 0-length session ID.
2113 * s->hit is non-zero in either case of session reuse,
2114 * so the following won't overwrite an ID that we're supposed
2117 if (s->session->not_resumable ||
2118 (!(s->ctx->session_cache_mode & SSL_SESS_CACHE_SERVER)
2120 s->session->session_id_length = 0;
2122 sl = s->session->session_id_length;
2123 if (sl > sizeof(s->session->session_id)) {
2124 SSLerr(SSL_F_TLS_CONSTRUCT_SERVER_HELLO, ERR_R_INTERNAL_ERROR);
2128 /* set up the compression method */
2129 #ifdef OPENSSL_NO_COMP
2132 if (s->s3->tmp.new_compression == NULL)
2135 compm = s->s3->tmp.new_compression->id;
2138 if ((!SSL_IS_TLS13(s)
2139 && !WPACKET_sub_memcpy_u8(pkt, s->session->session_id, sl))
2140 || !s->method->put_cipher_by_char(s->s3->tmp.new_cipher, pkt, &len)
2141 || (!SSL_IS_TLS13(s)
2142 && !WPACKET_put_bytes_u8(pkt, compm))
2143 || !tls_construct_extensions(s, pkt,
2145 ? SSL_EXT_TLS1_3_SERVER_HELLO
2146 : SSL_EXT_TLS1_2_SERVER_HELLO,
2148 SSLerr(SSL_F_TLS_CONSTRUCT_SERVER_HELLO, ERR_R_INTERNAL_ERROR);
2152 if (!(s->verify_mode & SSL_VERIFY_PEER)
2153 && !ssl3_digest_cached_records(s, 0)) {
2154 al = SSL_AD_INTERNAL_ERROR;
2160 ssl3_send_alert(s, SSL3_AL_FATAL, al);
2164 int tls_construct_server_done(SSL *s, WPACKET *pkt)
2166 if (!s->s3->tmp.cert_request) {
2167 if (!ssl3_digest_cached_records(s, 0)) {
2168 ssl3_send_alert(s, SSL3_AL_FATAL, SSL_AD_INTERNAL_ERROR);
2175 int tls_construct_server_key_exchange(SSL *s, WPACKET *pkt)
2177 #ifndef OPENSSL_NO_DH
2178 EVP_PKEY *pkdh = NULL;
2180 #ifndef OPENSSL_NO_EC
2181 unsigned char *encodedPoint = NULL;
2182 size_t encodedlen = 0;
2185 const SIGALG_LOOKUP *lu = s->s3->tmp.sigalg;
2186 int al = SSL_AD_INTERNAL_ERROR, i;
2189 EVP_MD_CTX *md_ctx = EVP_MD_CTX_new();
2190 EVP_PKEY_CTX *pctx = NULL;
2191 size_t paramlen, paramoffset;
2193 if (!WPACKET_get_total_written(pkt, ¶moffset)) {
2194 SSLerr(SSL_F_TLS_CONSTRUCT_SERVER_KEY_EXCHANGE, ERR_R_INTERNAL_ERROR);
2198 if (md_ctx == NULL) {
2199 SSLerr(SSL_F_TLS_CONSTRUCT_SERVER_KEY_EXCHANGE, ERR_R_MALLOC_FAILURE);
2203 type = s->s3->tmp.new_cipher->algorithm_mkey;
2205 r[0] = r[1] = r[2] = r[3] = NULL;
2206 #ifndef OPENSSL_NO_PSK
2207 /* Plain PSK or RSAPSK nothing to do */
2208 if (type & (SSL_kPSK | SSL_kRSAPSK)) {
2210 #endif /* !OPENSSL_NO_PSK */
2211 #ifndef OPENSSL_NO_DH
2212 if (type & (SSL_kDHE | SSL_kDHEPSK)) {
2213 CERT *cert = s->cert;
2215 EVP_PKEY *pkdhp = NULL;
2218 if (s->cert->dh_tmp_auto) {
2219 DH *dhp = ssl_get_auto_dh(s);
2220 pkdh = EVP_PKEY_new();
2221 if (pkdh == NULL || dhp == NULL) {
2223 SSLerr(SSL_F_TLS_CONSTRUCT_SERVER_KEY_EXCHANGE,
2224 ERR_R_INTERNAL_ERROR);
2227 EVP_PKEY_assign_DH(pkdh, dhp);
2230 pkdhp = cert->dh_tmp;
2232 if ((pkdhp == NULL) && (s->cert->dh_tmp_cb != NULL)) {
2233 DH *dhp = s->cert->dh_tmp_cb(s, 0, 1024);
2234 pkdh = ssl_dh_to_pkey(dhp);
2236 SSLerr(SSL_F_TLS_CONSTRUCT_SERVER_KEY_EXCHANGE,
2237 ERR_R_INTERNAL_ERROR);
2242 if (pkdhp == NULL) {
2243 al = SSL_AD_INTERNAL_ERROR;
2244 SSLerr(SSL_F_TLS_CONSTRUCT_SERVER_KEY_EXCHANGE,
2245 SSL_R_MISSING_TMP_DH_KEY);
2248 if (!ssl_security(s, SSL_SECOP_TMP_DH,
2249 EVP_PKEY_security_bits(pkdhp), 0, pkdhp)) {
2250 al = SSL_AD_HANDSHAKE_FAILURE;
2251 SSLerr(SSL_F_TLS_CONSTRUCT_SERVER_KEY_EXCHANGE,
2252 SSL_R_DH_KEY_TOO_SMALL);
2255 if (s->s3->tmp.pkey != NULL) {
2256 SSLerr(SSL_F_TLS_CONSTRUCT_SERVER_KEY_EXCHANGE,
2257 ERR_R_INTERNAL_ERROR);
2261 s->s3->tmp.pkey = ssl_generate_pkey(pkdhp);
2263 if (s->s3->tmp.pkey == NULL) {
2264 SSLerr(SSL_F_TLS_CONSTRUCT_SERVER_KEY_EXCHANGE, ERR_R_EVP_LIB);
2268 dh = EVP_PKEY_get0_DH(s->s3->tmp.pkey);
2270 EVP_PKEY_free(pkdh);
2273 DH_get0_pqg(dh, &r[0], NULL, &r[1]);
2274 DH_get0_key(dh, &r[2], NULL);
2277 #ifndef OPENSSL_NO_EC
2278 if (type & (SSL_kECDHE | SSL_kECDHEPSK)) {
2281 if (s->s3->tmp.pkey != NULL) {
2282 SSLerr(SSL_F_TLS_CONSTRUCT_SERVER_KEY_EXCHANGE,
2283 ERR_R_INTERNAL_ERROR);
2287 /* Get NID of appropriate shared curve */
2288 nid = tls1_shared_group(s, -2);
2289 curve_id = tls1_ec_nid2curve_id(nid);
2290 if (curve_id == 0) {
2291 SSLerr(SSL_F_TLS_CONSTRUCT_SERVER_KEY_EXCHANGE,
2292 SSL_R_UNSUPPORTED_ELLIPTIC_CURVE);
2295 s->s3->tmp.pkey = ssl_generate_pkey_curve(curve_id);
2296 /* Generate a new key for this curve */
2297 if (s->s3->tmp.pkey == NULL) {
2298 SSLerr(SSL_F_TLS_CONSTRUCT_SERVER_KEY_EXCHANGE, ERR_R_EVP_LIB);
2302 /* Encode the public key. */
2303 encodedlen = EVP_PKEY_get1_tls_encodedpoint(s->s3->tmp.pkey,
2305 if (encodedlen == 0) {
2306 SSLerr(SSL_F_TLS_CONSTRUCT_SERVER_KEY_EXCHANGE, ERR_R_EC_LIB);
2311 * We'll generate the serverKeyExchange message explicitly so we
2312 * can set these to NULLs
2319 #endif /* !OPENSSL_NO_EC */
2320 #ifndef OPENSSL_NO_SRP
2321 if (type & SSL_kSRP) {
2322 if ((s->srp_ctx.N == NULL) ||
2323 (s->srp_ctx.g == NULL) ||
2324 (s->srp_ctx.s == NULL) || (s->srp_ctx.B == NULL)) {
2325 SSLerr(SSL_F_TLS_CONSTRUCT_SERVER_KEY_EXCHANGE,
2326 SSL_R_MISSING_SRP_PARAM);
2329 r[0] = s->srp_ctx.N;
2330 r[1] = s->srp_ctx.g;
2331 r[2] = s->srp_ctx.s;
2332 r[3] = s->srp_ctx.B;
2336 al = SSL_AD_INTERNAL_ERROR;
2337 SSLerr(SSL_F_TLS_CONSTRUCT_SERVER_KEY_EXCHANGE,
2338 SSL_R_UNKNOWN_KEY_EXCHANGE_TYPE);
2342 if (((s->s3->tmp.new_cipher->algorithm_auth & (SSL_aNULL | SSL_aSRP)) != 0)
2343 || ((s->s3->tmp.new_cipher->algorithm_mkey & SSL_PSK)) != 0) {
2345 } else if (lu == NULL) {
2346 al = SSL_AD_DECODE_ERROR;
2350 #ifndef OPENSSL_NO_PSK
2351 if (type & SSL_PSK) {
2352 size_t len = (s->cert->psk_identity_hint == NULL)
2353 ? 0 : strlen(s->cert->psk_identity_hint);
2356 * It should not happen that len > PSK_MAX_IDENTITY_LEN - we already
2357 * checked this when we set the identity hint - but just in case
2359 if (len > PSK_MAX_IDENTITY_LEN
2360 || !WPACKET_sub_memcpy_u16(pkt, s->cert->psk_identity_hint,
2362 SSLerr(SSL_F_TLS_CONSTRUCT_SERVER_KEY_EXCHANGE,
2363 ERR_R_INTERNAL_ERROR);
2369 for (i = 0; i < 4 && r[i] != NULL; i++) {
2370 unsigned char *binval;
2373 #ifndef OPENSSL_NO_SRP
2374 if ((i == 2) && (type & SSL_kSRP)) {
2375 res = WPACKET_start_sub_packet_u8(pkt);
2378 res = WPACKET_start_sub_packet_u16(pkt);
2381 SSLerr(SSL_F_TLS_CONSTRUCT_SERVER_KEY_EXCHANGE,
2382 ERR_R_INTERNAL_ERROR);
2386 #ifndef OPENSSL_NO_DH
2388 * for interoperability with some versions of the Microsoft TLS
2389 * stack, we need to zero pad the DHE pub key to the same length
2392 if ((i == 2) && (type & (SSL_kDHE | SSL_kDHEPSK))) {
2393 size_t len = BN_num_bytes(r[0]) - BN_num_bytes(r[2]);
2396 if (!WPACKET_allocate_bytes(pkt, len, &binval)) {
2397 SSLerr(SSL_F_TLS_CONSTRUCT_SERVER_KEY_EXCHANGE,
2398 ERR_R_INTERNAL_ERROR);
2401 memset(binval, 0, len);
2405 if (!WPACKET_allocate_bytes(pkt, BN_num_bytes(r[i]), &binval)
2406 || !WPACKET_close(pkt)) {
2407 SSLerr(SSL_F_TLS_CONSTRUCT_SERVER_KEY_EXCHANGE,
2408 ERR_R_INTERNAL_ERROR);
2412 BN_bn2bin(r[i], binval);
2415 #ifndef OPENSSL_NO_EC
2416 if (type & (SSL_kECDHE | SSL_kECDHEPSK)) {
2418 * We only support named (not generic) curves. In this situation, the
2419 * ServerKeyExchange message has: [1 byte CurveType], [2 byte CurveName]
2420 * [1 byte length of encoded point], followed by the actual encoded
2423 if (!WPACKET_put_bytes_u8(pkt, NAMED_CURVE_TYPE)
2424 || !WPACKET_put_bytes_u8(pkt, 0)
2425 || !WPACKET_put_bytes_u8(pkt, curve_id)
2426 || !WPACKET_sub_memcpy_u8(pkt, encodedPoint, encodedlen)) {
2427 SSLerr(SSL_F_TLS_CONSTRUCT_SERVER_KEY_EXCHANGE,
2428 ERR_R_INTERNAL_ERROR);
2431 OPENSSL_free(encodedPoint);
2432 encodedPoint = NULL;
2438 EVP_PKEY *pkey = s->s3->tmp.cert->privatekey;
2439 const EVP_MD *md = ssl_md(lu->hash_idx);
2440 unsigned char *sigbytes1, *sigbytes2;
2443 if (pkey == NULL || md == NULL) {
2444 /* Should never happen */
2445 al = SSL_AD_INTERNAL_ERROR;
2446 SSLerr(SSL_F_TLS_CONSTRUCT_SERVER_KEY_EXCHANGE,
2447 ERR_R_INTERNAL_ERROR);
2451 * n is the length of the params, they start at &(d[4]) and p
2452 * points to the space at the end.
2455 /* Get length of the parameters we have written above */
2456 if (!WPACKET_get_length(pkt, ¶mlen)) {
2457 SSLerr(SSL_F_TLS_CONSTRUCT_SERVER_KEY_EXCHANGE,
2458 ERR_R_INTERNAL_ERROR);
2461 /* send signature algorithm */
2462 if (SSL_USE_SIGALGS(s) && !WPACKET_put_bytes_u16(pkt, lu->sigalg))
2465 * Create the signature. We don't know the actual length of the sig
2466 * until after we've created it, so we reserve enough bytes for it
2467 * up front, and then properly allocate them in the WPACKET
2470 siglen = EVP_PKEY_size(pkey);
2471 if (!WPACKET_sub_reserve_bytes_u16(pkt, siglen, &sigbytes1)
2472 || EVP_DigestSignInit(md_ctx, &pctx, md, NULL, pkey) <= 0) {
2473 SSLerr(SSL_F_TLS_CONSTRUCT_SERVER_KEY_EXCHANGE,
2474 ERR_R_INTERNAL_ERROR);
2477 if (lu->sig == EVP_PKEY_RSA_PSS) {
2478 if (EVP_PKEY_CTX_set_rsa_padding(pctx, RSA_PKCS1_PSS_PADDING) <= 0
2479 || EVP_PKEY_CTX_set_rsa_pss_saltlen(pctx, RSA_PSS_SALTLEN_DIGEST) <= 0) {
2480 SSLerr(SSL_F_TLS_CONSTRUCT_SERVER_KEY_EXCHANGE,
2485 if (EVP_DigestSignUpdate(md_ctx, &(s->s3->client_random[0]),
2486 SSL3_RANDOM_SIZE) <= 0
2487 || EVP_DigestSignUpdate(md_ctx, &(s->s3->server_random[0]),
2488 SSL3_RANDOM_SIZE) <= 0
2489 || EVP_DigestSignUpdate(md_ctx,
2490 s->init_buf->data + paramoffset,
2492 || EVP_DigestSignFinal(md_ctx, sigbytes1, &siglen) <= 0
2493 || !WPACKET_sub_allocate_bytes_u16(pkt, siglen, &sigbytes2)
2494 || sigbytes1 != sigbytes2) {
2495 SSLerr(SSL_F_TLS_CONSTRUCT_SERVER_KEY_EXCHANGE,
2496 ERR_R_INTERNAL_ERROR);
2501 EVP_MD_CTX_free(md_ctx);
2504 ssl3_send_alert(s, SSL3_AL_FATAL, al);
2506 #ifndef OPENSSL_NO_DH
2507 EVP_PKEY_free(pkdh);
2509 #ifndef OPENSSL_NO_EC
2510 OPENSSL_free(encodedPoint);
2512 EVP_MD_CTX_free(md_ctx);
2516 int tls_construct_certificate_request(SSL *s, WPACKET *pkt)
2518 int al = SSL_AD_INTERNAL_ERROR;
2520 if (SSL_IS_TLS13(s)) {
2521 /* TODO(TLS1.3) for now send empty request context */
2522 if (!WPACKET_put_bytes_u8(pkt, 0)) {
2523 SSLerr(SSL_F_TLS_CONSTRUCT_CERTIFICATE_REQUEST,
2524 ERR_R_INTERNAL_ERROR);
2528 if (!tls_construct_extensions(s, pkt,
2529 SSL_EXT_TLS1_3_CERTIFICATE_REQUEST, NULL,
2531 SSLerr(SSL_F_TLS_CONSTRUCT_CERTIFICATE_REQUEST,
2532 ERR_R_INTERNAL_ERROR);
2538 /* get the list of acceptable cert types */
2539 if (!WPACKET_start_sub_packet_u8(pkt)
2540 || !ssl3_get_req_cert_type(s, pkt) || !WPACKET_close(pkt)) {
2541 SSLerr(SSL_F_TLS_CONSTRUCT_CERTIFICATE_REQUEST, ERR_R_INTERNAL_ERROR);
2545 if (SSL_USE_SIGALGS(s)) {
2546 const uint16_t *psigs;
2547 size_t nl = tls12_get_psigalgs(s, 1, &psigs);
2549 if (!WPACKET_start_sub_packet_u16(pkt)
2550 || !WPACKET_set_flags(pkt, WPACKET_FLAGS_NON_ZERO_LENGTH)
2551 || !tls12_copy_sigalgs(s, pkt, psigs, nl)
2552 || !WPACKET_close(pkt)) {
2553 SSLerr(SSL_F_TLS_CONSTRUCT_CERTIFICATE_REQUEST,
2554 ERR_R_INTERNAL_ERROR);
2559 if (!construct_ca_names(s, pkt)) {
2560 SSLerr(SSL_F_TLS_CONSTRUCT_CERTIFICATE_REQUEST, ERR_R_INTERNAL_ERROR);
2565 s->s3->tmp.cert_request = 1;
2568 ssl3_send_alert(s, SSL3_AL_FATAL, al);
2572 static int tls_process_cke_psk_preamble(SSL *s, PACKET *pkt, int *al)
2574 #ifndef OPENSSL_NO_PSK
2575 unsigned char psk[PSK_MAX_PSK_LEN];
2577 PACKET psk_identity;
2579 if (!PACKET_get_length_prefixed_2(pkt, &psk_identity)) {
2580 *al = SSL_AD_DECODE_ERROR;
2581 SSLerr(SSL_F_TLS_PROCESS_CKE_PSK_PREAMBLE, SSL_R_LENGTH_MISMATCH);
2584 if (PACKET_remaining(&psk_identity) > PSK_MAX_IDENTITY_LEN) {
2585 *al = SSL_AD_DECODE_ERROR;
2586 SSLerr(SSL_F_TLS_PROCESS_CKE_PSK_PREAMBLE, SSL_R_DATA_LENGTH_TOO_LONG);
2589 if (s->psk_server_callback == NULL) {
2590 *al = SSL_AD_INTERNAL_ERROR;
2591 SSLerr(SSL_F_TLS_PROCESS_CKE_PSK_PREAMBLE, SSL_R_PSK_NO_SERVER_CB);
2595 if (!PACKET_strndup(&psk_identity, &s->session->psk_identity)) {
2596 *al = SSL_AD_INTERNAL_ERROR;
2597 SSLerr(SSL_F_TLS_PROCESS_CKE_PSK_PREAMBLE, ERR_R_INTERNAL_ERROR);
2601 psklen = s->psk_server_callback(s, s->session->psk_identity,
2604 if (psklen > PSK_MAX_PSK_LEN) {
2605 *al = SSL_AD_INTERNAL_ERROR;
2606 SSLerr(SSL_F_TLS_PROCESS_CKE_PSK_PREAMBLE, ERR_R_INTERNAL_ERROR);
2608 } else if (psklen == 0) {
2610 * PSK related to the given identity not found
2612 *al = SSL_AD_UNKNOWN_PSK_IDENTITY;
2613 SSLerr(SSL_F_TLS_PROCESS_CKE_PSK_PREAMBLE,
2614 SSL_R_PSK_IDENTITY_NOT_FOUND);
2618 OPENSSL_free(s->s3->tmp.psk);
2619 s->s3->tmp.psk = OPENSSL_memdup(psk, psklen);
2620 OPENSSL_cleanse(psk, psklen);
2622 if (s->s3->tmp.psk == NULL) {
2623 *al = SSL_AD_INTERNAL_ERROR;
2624 SSLerr(SSL_F_TLS_PROCESS_CKE_PSK_PREAMBLE, ERR_R_MALLOC_FAILURE);
2628 s->s3->tmp.psklen = psklen;
2632 /* Should never happen */
2633 *al = SSL_AD_INTERNAL_ERROR;
2634 SSLerr(SSL_F_TLS_PROCESS_CKE_PSK_PREAMBLE, ERR_R_INTERNAL_ERROR);
2639 static int tls_process_cke_rsa(SSL *s, PACKET *pkt, int *al)
2641 #ifndef OPENSSL_NO_RSA
2642 unsigned char rand_premaster_secret[SSL_MAX_MASTER_KEY_LENGTH];
2644 unsigned char decrypt_good, version_good;
2645 size_t j, padding_len;
2646 PACKET enc_premaster;
2648 unsigned char *rsa_decrypt = NULL;
2651 rsa = EVP_PKEY_get0_RSA(s->cert->pkeys[SSL_PKEY_RSA].privatekey);
2653 *al = SSL_AD_INTERNAL_ERROR;
2654 SSLerr(SSL_F_TLS_PROCESS_CKE_RSA, SSL_R_MISSING_RSA_CERTIFICATE);
2658 /* SSLv3 and pre-standard DTLS omit the length bytes. */
2659 if (s->version == SSL3_VERSION || s->version == DTLS1_BAD_VER) {
2660 enc_premaster = *pkt;
2662 if (!PACKET_get_length_prefixed_2(pkt, &enc_premaster)
2663 || PACKET_remaining(pkt) != 0) {
2664 *al = SSL_AD_DECODE_ERROR;
2665 SSLerr(SSL_F_TLS_PROCESS_CKE_RSA, SSL_R_LENGTH_MISMATCH);
2671 * We want to be sure that the plaintext buffer size makes it safe to
2672 * iterate over the entire size of a premaster secret
2673 * (SSL_MAX_MASTER_KEY_LENGTH). Reject overly short RSA keys because
2674 * their ciphertext cannot accommodate a premaster secret anyway.
2676 if (RSA_size(rsa) < SSL_MAX_MASTER_KEY_LENGTH) {
2677 *al = SSL_AD_INTERNAL_ERROR;
2678 SSLerr(SSL_F_TLS_PROCESS_CKE_RSA, RSA_R_KEY_SIZE_TOO_SMALL);
2682 rsa_decrypt = OPENSSL_malloc(RSA_size(rsa));
2683 if (rsa_decrypt == NULL) {
2684 *al = SSL_AD_INTERNAL_ERROR;
2685 SSLerr(SSL_F_TLS_PROCESS_CKE_RSA, ERR_R_MALLOC_FAILURE);
2690 * We must not leak whether a decryption failure occurs because of
2691 * Bleichenbacher's attack on PKCS #1 v1.5 RSA padding (see RFC 2246,
2692 * section 7.4.7.1). The code follows that advice of the TLS RFC and
2693 * generates a random premaster secret for the case that the decrypt
2694 * fails. See https://tools.ietf.org/html/rfc5246#section-7.4.7.1
2697 if (RAND_bytes(rand_premaster_secret, sizeof(rand_premaster_secret)) <= 0)
2701 * Decrypt with no padding. PKCS#1 padding will be removed as part of
2702 * the timing-sensitive code below.
2704 /* TODO(size_t): Convert this function */
2705 decrypt_len = (int)RSA_private_decrypt((int)PACKET_remaining(&enc_premaster),
2706 PACKET_data(&enc_premaster),
2707 rsa_decrypt, rsa, RSA_NO_PADDING);
2708 if (decrypt_len < 0)
2711 /* Check the padding. See RFC 3447, section 7.2.2. */
2714 * The smallest padded premaster is 11 bytes of overhead. Small keys
2715 * are publicly invalid, so this may return immediately. This ensures
2716 * PS is at least 8 bytes.
2718 if (decrypt_len < 11 + SSL_MAX_MASTER_KEY_LENGTH) {
2719 *al = SSL_AD_DECRYPT_ERROR;
2720 SSLerr(SSL_F_TLS_PROCESS_CKE_RSA, SSL_R_DECRYPTION_FAILED);
2724 padding_len = decrypt_len - SSL_MAX_MASTER_KEY_LENGTH;
2725 decrypt_good = constant_time_eq_int_8(rsa_decrypt[0], 0) &
2726 constant_time_eq_int_8(rsa_decrypt[1], 2);
2727 for (j = 2; j < padding_len - 1; j++) {
2728 decrypt_good &= ~constant_time_is_zero_8(rsa_decrypt[j]);
2730 decrypt_good &= constant_time_is_zero_8(rsa_decrypt[padding_len - 1]);
2733 * If the version in the decrypted pre-master secret is correct then
2734 * version_good will be 0xff, otherwise it'll be zero. The
2735 * Klima-Pokorny-Rosa extension of Bleichenbacher's attack
2736 * (http://eprint.iacr.org/2003/052/) exploits the version number
2737 * check as a "bad version oracle". Thus version checks are done in
2738 * constant time and are treated like any other decryption error.
2741 constant_time_eq_8(rsa_decrypt[padding_len],
2742 (unsigned)(s->client_version >> 8));
2744 constant_time_eq_8(rsa_decrypt[padding_len + 1],
2745 (unsigned)(s->client_version & 0xff));
2748 * The premaster secret must contain the same version number as the
2749 * ClientHello to detect version rollback attacks (strangely, the
2750 * protocol does not offer such protection for DH ciphersuites).
2751 * However, buggy clients exist that send the negotiated protocol
2752 * version instead if the server does not support the requested
2753 * protocol version. If SSL_OP_TLS_ROLLBACK_BUG is set, tolerate such
2756 if (s->options & SSL_OP_TLS_ROLLBACK_BUG) {
2757 unsigned char workaround_good;
2758 workaround_good = constant_time_eq_8(rsa_decrypt[padding_len],
2759 (unsigned)(s->version >> 8));
2761 constant_time_eq_8(rsa_decrypt[padding_len + 1],
2762 (unsigned)(s->version & 0xff));
2763 version_good |= workaround_good;
2767 * Both decryption and version must be good for decrypt_good to
2768 * remain non-zero (0xff).
2770 decrypt_good &= version_good;
2773 * Now copy rand_premaster_secret over from p using
2774 * decrypt_good_mask. If decryption failed, then p does not
2775 * contain valid plaintext, however, a check above guarantees
2776 * it is still sufficiently large to read from.
2778 for (j = 0; j < sizeof(rand_premaster_secret); j++) {
2779 rsa_decrypt[padding_len + j] =
2780 constant_time_select_8(decrypt_good,
2781 rsa_decrypt[padding_len + j],
2782 rand_premaster_secret[j]);
2785 if (!ssl_generate_master_secret(s, rsa_decrypt + padding_len,
2786 sizeof(rand_premaster_secret), 0)) {
2787 *al = SSL_AD_INTERNAL_ERROR;
2788 SSLerr(SSL_F_TLS_PROCESS_CKE_RSA, ERR_R_INTERNAL_ERROR);
2794 OPENSSL_free(rsa_decrypt);
2797 /* Should never happen */
2798 *al = SSL_AD_INTERNAL_ERROR;
2799 SSLerr(SSL_F_TLS_PROCESS_CKE_RSA, ERR_R_INTERNAL_ERROR);
2804 static int tls_process_cke_dhe(SSL *s, PACKET *pkt, int *al)
2806 #ifndef OPENSSL_NO_DH
2807 EVP_PKEY *skey = NULL;
2811 const unsigned char *data;
2812 EVP_PKEY *ckey = NULL;
2815 if (!PACKET_get_net_2(pkt, &i) || PACKET_remaining(pkt) != i) {
2816 *al = SSL_AD_DECODE_ERROR;
2817 SSLerr(SSL_F_TLS_PROCESS_CKE_DHE,
2818 SSL_R_DH_PUBLIC_VALUE_LENGTH_IS_WRONG);
2821 skey = s->s3->tmp.pkey;
2823 *al = SSL_AD_INTERNAL_ERROR;
2824 SSLerr(SSL_F_TLS_PROCESS_CKE_DHE, SSL_R_MISSING_TMP_DH_KEY);
2828 if (PACKET_remaining(pkt) == 0L) {
2829 *al = SSL_AD_DECODE_ERROR;
2830 SSLerr(SSL_F_TLS_PROCESS_CKE_DHE, SSL_R_MISSING_TMP_DH_KEY);
2833 if (!PACKET_get_bytes(pkt, &data, i)) {
2834 /* We already checked we have enough data */
2835 *al = SSL_AD_INTERNAL_ERROR;
2836 SSLerr(SSL_F_TLS_PROCESS_CKE_DHE, ERR_R_INTERNAL_ERROR);
2839 ckey = EVP_PKEY_new();
2840 if (ckey == NULL || EVP_PKEY_copy_parameters(ckey, skey) == 0) {
2841 SSLerr(SSL_F_TLS_PROCESS_CKE_DHE, SSL_R_BN_LIB);
2844 cdh = EVP_PKEY_get0_DH(ckey);
2845 pub_key = BN_bin2bn(data, i, NULL);
2847 if (pub_key == NULL || !DH_set0_key(cdh, pub_key, NULL)) {
2848 SSLerr(SSL_F_TLS_PROCESS_CKE_DHE, ERR_R_INTERNAL_ERROR);
2849 if (pub_key != NULL)
2854 if (ssl_derive(s, skey, ckey, 1) == 0) {
2855 *al = SSL_AD_INTERNAL_ERROR;
2856 SSLerr(SSL_F_TLS_PROCESS_CKE_DHE, ERR_R_INTERNAL_ERROR);
2861 EVP_PKEY_free(s->s3->tmp.pkey);
2862 s->s3->tmp.pkey = NULL;
2864 EVP_PKEY_free(ckey);
2867 /* Should never happen */
2868 *al = SSL_AD_INTERNAL_ERROR;
2869 SSLerr(SSL_F_TLS_PROCESS_CKE_DHE, ERR_R_INTERNAL_ERROR);
2874 static int tls_process_cke_ecdhe(SSL *s, PACKET *pkt, int *al)
2876 #ifndef OPENSSL_NO_EC
2877 EVP_PKEY *skey = s->s3->tmp.pkey;
2878 EVP_PKEY *ckey = NULL;
2881 if (PACKET_remaining(pkt) == 0L) {
2882 /* We don't support ECDH client auth */
2883 *al = SSL_AD_HANDSHAKE_FAILURE;
2884 SSLerr(SSL_F_TLS_PROCESS_CKE_ECDHE, SSL_R_MISSING_TMP_ECDH_KEY);
2888 const unsigned char *data;
2891 * Get client's public key from encoded point in the
2892 * ClientKeyExchange message.
2895 /* Get encoded point length */
2896 if (!PACKET_get_1(pkt, &i) || !PACKET_get_bytes(pkt, &data, i)
2897 || PACKET_remaining(pkt) != 0) {
2898 *al = SSL_AD_DECODE_ERROR;
2899 SSLerr(SSL_F_TLS_PROCESS_CKE_ECDHE, SSL_R_LENGTH_MISMATCH);
2902 ckey = EVP_PKEY_new();
2903 if (ckey == NULL || EVP_PKEY_copy_parameters(ckey, skey) <= 0) {
2904 SSLerr(SSL_F_TLS_PROCESS_CKE_ECDHE, ERR_R_EVP_LIB);
2907 if (EVP_PKEY_set1_tls_encodedpoint(ckey, data, i) == 0) {
2908 *al = SSL_AD_ILLEGAL_PARAMETER;
2909 SSLerr(SSL_F_TLS_PROCESS_CKE_ECDHE, ERR_R_EC_LIB);
2914 if (ssl_derive(s, skey, ckey, 1) == 0) {
2915 *al = SSL_AD_INTERNAL_ERROR;
2916 SSLerr(SSL_F_TLS_PROCESS_CKE_ECDHE, ERR_R_INTERNAL_ERROR);
2921 EVP_PKEY_free(s->s3->tmp.pkey);
2922 s->s3->tmp.pkey = NULL;
2924 EVP_PKEY_free(ckey);
2928 /* Should never happen */
2929 *al = SSL_AD_INTERNAL_ERROR;
2930 SSLerr(SSL_F_TLS_PROCESS_CKE_ECDHE, ERR_R_INTERNAL_ERROR);
2935 static int tls_process_cke_srp(SSL *s, PACKET *pkt, int *al)
2937 #ifndef OPENSSL_NO_SRP
2939 const unsigned char *data;
2941 if (!PACKET_get_net_2(pkt, &i)
2942 || !PACKET_get_bytes(pkt, &data, i)) {
2943 *al = SSL_AD_DECODE_ERROR;
2944 SSLerr(SSL_F_TLS_PROCESS_CKE_SRP, SSL_R_BAD_SRP_A_LENGTH);
2947 if ((s->srp_ctx.A = BN_bin2bn(data, i, NULL)) == NULL) {
2948 *al = SSL_AD_INTERNAL_ERROR;
2949 SSLerr(SSL_F_TLS_PROCESS_CKE_SRP, ERR_R_BN_LIB);
2952 if (BN_ucmp(s->srp_ctx.A, s->srp_ctx.N) >= 0 || BN_is_zero(s->srp_ctx.A)) {
2953 *al = SSL_AD_ILLEGAL_PARAMETER;
2954 SSLerr(SSL_F_TLS_PROCESS_CKE_SRP, SSL_R_BAD_SRP_PARAMETERS);
2957 OPENSSL_free(s->session->srp_username);
2958 s->session->srp_username = OPENSSL_strdup(s->srp_ctx.login);
2959 if (s->session->srp_username == NULL) {
2960 SSLerr(SSL_F_TLS_PROCESS_CKE_SRP, ERR_R_MALLOC_FAILURE);
2964 if (!srp_generate_server_master_secret(s)) {
2965 SSLerr(SSL_F_TLS_PROCESS_CKE_SRP, ERR_R_INTERNAL_ERROR);
2971 /* Should never happen */
2972 *al = SSL_AD_INTERNAL_ERROR;
2973 SSLerr(SSL_F_TLS_PROCESS_CKE_SRP, ERR_R_INTERNAL_ERROR);
2978 static int tls_process_cke_gost(SSL *s, PACKET *pkt, int *al)
2980 #ifndef OPENSSL_NO_GOST
2981 EVP_PKEY_CTX *pkey_ctx;
2982 EVP_PKEY *client_pub_pkey = NULL, *pk = NULL;
2983 unsigned char premaster_secret[32];
2984 const unsigned char *start;
2985 size_t outlen = 32, inlen;
2986 unsigned long alg_a;
2989 size_t sess_key_len;
2990 const unsigned char *data;
2993 /* Get our certificate private key */
2994 alg_a = s->s3->tmp.new_cipher->algorithm_auth;
2995 if (alg_a & SSL_aGOST12) {
2997 * New GOST ciphersuites have SSL_aGOST01 bit too
2999 pk = s->cert->pkeys[SSL_PKEY_GOST12_512].privatekey;
3001 pk = s->cert->pkeys[SSL_PKEY_GOST12_256].privatekey;
3004 pk = s->cert->pkeys[SSL_PKEY_GOST01].privatekey;
3006 } else if (alg_a & SSL_aGOST01) {
3007 pk = s->cert->pkeys[SSL_PKEY_GOST01].privatekey;
3010 pkey_ctx = EVP_PKEY_CTX_new(pk, NULL);
3011 if (pkey_ctx == NULL) {
3012 *al = SSL_AD_INTERNAL_ERROR;
3013 SSLerr(SSL_F_TLS_PROCESS_CKE_GOST, ERR_R_MALLOC_FAILURE);
3016 if (EVP_PKEY_decrypt_init(pkey_ctx) <= 0) {
3017 *al = SSL_AD_INTERNAL_ERROR;
3018 SSLerr(SSL_F_TLS_PROCESS_CKE_GOST, ERR_R_INTERNAL_ERROR);
3022 * If client certificate is present and is of the same type, maybe
3023 * use it for key exchange. Don't mind errors from
3024 * EVP_PKEY_derive_set_peer, because it is completely valid to use a
3025 * client certificate for authorization only.
3027 client_pub_pkey = X509_get0_pubkey(s->session->peer);
3028 if (client_pub_pkey) {
3029 if (EVP_PKEY_derive_set_peer(pkey_ctx, client_pub_pkey) <= 0)
3032 /* Decrypt session key */
3033 sess_key_len = PACKET_remaining(pkt);
3034 if (!PACKET_get_bytes(pkt, &data, sess_key_len)) {
3035 *al = SSL_AD_INTERNAL_ERROR;
3036 SSLerr(SSL_F_TLS_PROCESS_CKE_GOST, ERR_R_INTERNAL_ERROR);
3039 /* TODO(size_t): Convert this function */
3040 if (ASN1_get_object((const unsigned char **)&data, &Tlen, &Ttag,
3041 &Tclass, (long)sess_key_len) != V_ASN1_CONSTRUCTED
3042 || Ttag != V_ASN1_SEQUENCE || Tclass != V_ASN1_UNIVERSAL) {
3043 *al = SSL_AD_DECODE_ERROR;
3044 SSLerr(SSL_F_TLS_PROCESS_CKE_GOST, SSL_R_DECRYPTION_FAILED);
3049 if (EVP_PKEY_decrypt
3050 (pkey_ctx, premaster_secret, &outlen, start, inlen) <= 0) {
3051 *al = SSL_AD_DECODE_ERROR;
3052 SSLerr(SSL_F_TLS_PROCESS_CKE_GOST, SSL_R_DECRYPTION_FAILED);
3055 /* Generate master secret */
3056 if (!ssl_generate_master_secret(s, premaster_secret,
3057 sizeof(premaster_secret), 0)) {
3058 *al = SSL_AD_INTERNAL_ERROR;
3059 SSLerr(SSL_F_TLS_PROCESS_CKE_GOST, ERR_R_INTERNAL_ERROR);
3062 /* Check if pubkey from client certificate was used */
3063 if (EVP_PKEY_CTX_ctrl
3064 (pkey_ctx, -1, -1, EVP_PKEY_CTRL_PEER_KEY, 2, NULL) > 0)
3065 s->statem.no_cert_verify = 1;
3069 EVP_PKEY_CTX_free(pkey_ctx);
3072 /* Should never happen */
3073 *al = SSL_AD_INTERNAL_ERROR;
3074 SSLerr(SSL_F_TLS_PROCESS_CKE_GOST, ERR_R_INTERNAL_ERROR);
3079 MSG_PROCESS_RETURN tls_process_client_key_exchange(SSL *s, PACKET *pkt)
3082 unsigned long alg_k;
3084 alg_k = s->s3->tmp.new_cipher->algorithm_mkey;
3086 /* For PSK parse and retrieve identity, obtain PSK key */
3087 if ((alg_k & SSL_PSK) && !tls_process_cke_psk_preamble(s, pkt, &al))
3090 if (alg_k & SSL_kPSK) {
3091 /* Identity extracted earlier: should be nothing left */
3092 if (PACKET_remaining(pkt) != 0) {
3093 al = SSL_AD_DECODE_ERROR;
3094 SSLerr(SSL_F_TLS_PROCESS_CLIENT_KEY_EXCHANGE,
3095 SSL_R_LENGTH_MISMATCH);
3098 /* PSK handled by ssl_generate_master_secret */
3099 if (!ssl_generate_master_secret(s, NULL, 0, 0)) {
3100 al = SSL_AD_INTERNAL_ERROR;
3101 SSLerr(SSL_F_TLS_PROCESS_CLIENT_KEY_EXCHANGE, ERR_R_INTERNAL_ERROR);
3104 } else if (alg_k & (SSL_kRSA | SSL_kRSAPSK)) {
3105 if (!tls_process_cke_rsa(s, pkt, &al))
3107 } else if (alg_k & (SSL_kDHE | SSL_kDHEPSK)) {
3108 if (!tls_process_cke_dhe(s, pkt, &al))
3110 } else if (alg_k & (SSL_kECDHE | SSL_kECDHEPSK)) {
3111 if (!tls_process_cke_ecdhe(s, pkt, &al))
3113 } else if (alg_k & SSL_kSRP) {
3114 if (!tls_process_cke_srp(s, pkt, &al))
3116 } else if (alg_k & SSL_kGOST) {
3117 if (!tls_process_cke_gost(s, pkt, &al))
3120 al = SSL_AD_INTERNAL_ERROR;
3121 SSLerr(SSL_F_TLS_PROCESS_CLIENT_KEY_EXCHANGE,
3122 SSL_R_UNKNOWN_CIPHER_TYPE);
3126 return MSG_PROCESS_CONTINUE_PROCESSING;
3129 ssl3_send_alert(s, SSL3_AL_FATAL, al);
3130 #ifndef OPENSSL_NO_PSK
3131 OPENSSL_clear_free(s->s3->tmp.psk, s->s3->tmp.psklen);
3132 s->s3->tmp.psk = NULL;
3134 ossl_statem_set_error(s);
3135 return MSG_PROCESS_ERROR;
3138 WORK_STATE tls_post_process_client_key_exchange(SSL *s, WORK_STATE wst)
3140 #ifndef OPENSSL_NO_SCTP
3141 if (wst == WORK_MORE_A) {
3142 if (SSL_IS_DTLS(s)) {
3143 unsigned char sctpauthkey[64];
3144 char labelbuffer[sizeof(DTLS1_SCTP_AUTH_LABEL)];
3146 * Add new shared key for SCTP-Auth, will be ignored if no SCTP
3149 memcpy(labelbuffer, DTLS1_SCTP_AUTH_LABEL,
3150 sizeof(DTLS1_SCTP_AUTH_LABEL));
3152 if (SSL_export_keying_material(s, sctpauthkey,
3153 sizeof(sctpauthkey), labelbuffer,
3154 sizeof(labelbuffer), NULL, 0,
3156 ossl_statem_set_error(s);
3160 BIO_ctrl(SSL_get_wbio(s), BIO_CTRL_DGRAM_SCTP_ADD_AUTH_KEY,
3161 sizeof(sctpauthkey), sctpauthkey);
3166 if (s->statem.no_cert_verify || !s->session->peer) {
3168 * No certificate verify or no peer certificate so we no longer need
3169 * the handshake_buffer
3171 if (!ssl3_digest_cached_records(s, 0)) {
3172 ossl_statem_set_error(s);
3175 return WORK_FINISHED_CONTINUE;
3177 if (!s->s3->handshake_buffer) {
3178 SSLerr(SSL_F_TLS_POST_PROCESS_CLIENT_KEY_EXCHANGE,
3179 ERR_R_INTERNAL_ERROR);
3180 ossl_statem_set_error(s);
3184 * For sigalgs freeze the handshake buffer. If we support
3185 * extms we've done this already so this is a no-op
3187 if (!ssl3_digest_cached_records(s, 1)) {
3188 ossl_statem_set_error(s);
3193 return WORK_FINISHED_CONTINUE;
3196 MSG_PROCESS_RETURN tls_process_client_certificate(SSL *s, PACKET *pkt)
3198 int i, al = SSL_AD_INTERNAL_ERROR, ret = MSG_PROCESS_ERROR;
3200 unsigned long l, llen;
3201 const unsigned char *certstart, *certbytes;
3202 STACK_OF(X509) *sk = NULL;
3203 PACKET spkt, context;
3206 if ((sk = sk_X509_new_null()) == NULL) {
3207 SSLerr(SSL_F_TLS_PROCESS_CLIENT_CERTIFICATE, ERR_R_MALLOC_FAILURE);
3211 /* TODO(TLS1.3): For now we ignore the context. We need to verify this */
3212 if ((SSL_IS_TLS13(s) && !PACKET_get_length_prefixed_1(pkt, &context))
3213 || !PACKET_get_net_3(pkt, &llen)
3214 || !PACKET_get_sub_packet(pkt, &spkt, llen)
3215 || PACKET_remaining(pkt) != 0) {
3216 al = SSL_AD_DECODE_ERROR;
3217 SSLerr(SSL_F_TLS_PROCESS_CLIENT_CERTIFICATE, SSL_R_LENGTH_MISMATCH);
3221 for (chainidx = 0; PACKET_remaining(&spkt) > 0; chainidx++) {
3222 if (!PACKET_get_net_3(&spkt, &l)
3223 || !PACKET_get_bytes(&spkt, &certbytes, l)) {
3224 al = SSL_AD_DECODE_ERROR;
3225 SSLerr(SSL_F_TLS_PROCESS_CLIENT_CERTIFICATE,
3226 SSL_R_CERT_LENGTH_MISMATCH);
3230 certstart = certbytes;
3231 x = d2i_X509(NULL, (const unsigned char **)&certbytes, l);
3233 SSLerr(SSL_F_TLS_PROCESS_CLIENT_CERTIFICATE, ERR_R_ASN1_LIB);
3236 if (certbytes != (certstart + l)) {
3237 al = SSL_AD_DECODE_ERROR;
3238 SSLerr(SSL_F_TLS_PROCESS_CLIENT_CERTIFICATE,
3239 SSL_R_CERT_LENGTH_MISMATCH);
3243 if (SSL_IS_TLS13(s)) {
3244 RAW_EXTENSION *rawexts = NULL;
3247 if (!PACKET_get_length_prefixed_2(&spkt, &extensions)) {
3248 al = SSL_AD_DECODE_ERROR;
3249 SSLerr(SSL_F_TLS_PROCESS_CLIENT_CERTIFICATE, SSL_R_BAD_LENGTH);
3252 if (!tls_collect_extensions(s, &extensions,
3253 SSL_EXT_TLS1_3_CERTIFICATE, &rawexts,
3254 &al, NULL, chainidx == 0)
3255 || !tls_parse_all_extensions(s, SSL_EXT_TLS1_3_CERTIFICATE,
3256 rawexts, x, chainidx, &al,
3257 PACKET_remaining(&spkt) == 0)) {
3258 OPENSSL_free(rawexts);
3261 OPENSSL_free(rawexts);
3264 if (!sk_X509_push(sk, x)) {
3265 SSLerr(SSL_F_TLS_PROCESS_CLIENT_CERTIFICATE, ERR_R_MALLOC_FAILURE);
3271 if (sk_X509_num(sk) <= 0) {
3272 /* TLS does not mind 0 certs returned */
3273 if (s->version == SSL3_VERSION) {
3274 al = SSL_AD_HANDSHAKE_FAILURE;
3275 SSLerr(SSL_F_TLS_PROCESS_CLIENT_CERTIFICATE,
3276 SSL_R_NO_CERTIFICATES_RETURNED);
3279 /* Fail for TLS only if we required a certificate */
3280 else if ((s->verify_mode & SSL_VERIFY_PEER) &&
3281 (s->verify_mode & SSL_VERIFY_FAIL_IF_NO_PEER_CERT)) {
3282 SSLerr(SSL_F_TLS_PROCESS_CLIENT_CERTIFICATE,
3283 SSL_R_PEER_DID_NOT_RETURN_A_CERTIFICATE);
3284 al = SSL_AD_CERTIFICATE_REQUIRED;
3287 /* No client certificate so digest cached records */
3288 if (s->s3->handshake_buffer && !ssl3_digest_cached_records(s, 0)) {
3293 i = ssl_verify_cert_chain(s, sk);
3295 al = ssl_verify_alarm_type(s->verify_result);
3296 SSLerr(SSL_F_TLS_PROCESS_CLIENT_CERTIFICATE,
3297 SSL_R_CERTIFICATE_VERIFY_FAILED);
3301 SSLerr(SSL_F_TLS_PROCESS_CLIENT_CERTIFICATE, i);
3302 al = SSL_AD_HANDSHAKE_FAILURE;
3305 pkey = X509_get0_pubkey(sk_X509_value(sk, 0));
3307 al = SSL3_AD_HANDSHAKE_FAILURE;
3308 SSLerr(SSL_F_TLS_PROCESS_CLIENT_CERTIFICATE,
3309 SSL_R_UNKNOWN_CERTIFICATE_TYPE);
3314 X509_free(s->session->peer);
3315 s->session->peer = sk_X509_shift(sk);
3316 s->session->verify_result = s->verify_result;
3318 sk_X509_pop_free(s->session->peer_chain, X509_free);
3319 s->session->peer_chain = sk;
3322 * Freeze the handshake buffer. For <TLS1.3 we do this after the CKE
3325 if (SSL_IS_TLS13(s) && !ssl3_digest_cached_records(s, 1)) {
3326 al = SSL_AD_INTERNAL_ERROR;
3327 SSLerr(SSL_F_TLS_PROCESS_CLIENT_CERTIFICATE, ERR_R_INTERNAL_ERROR);
3332 * Inconsistency alert: cert_chain does *not* include the peer's own
3333 * certificate, while we do include it in statem_clnt.c
3337 /* Save the current hash state for when we receive the CertificateVerify */
3339 && !ssl_handshake_hash(s, s->cert_verify_hash,
3340 sizeof(s->cert_verify_hash),
3341 &s->cert_verify_hash_len)) {
3342 al = SSL_AD_INTERNAL_ERROR;
3343 SSLerr(SSL_F_TLS_PROCESS_CLIENT_CERTIFICATE, ERR_R_INTERNAL_ERROR);
3347 ret = MSG_PROCESS_CONTINUE_READING;
3351 ssl3_send_alert(s, SSL3_AL_FATAL, al);
3352 ossl_statem_set_error(s);
3355 sk_X509_pop_free(sk, X509_free);
3359 int tls_construct_server_certificate(SSL *s, WPACKET *pkt)
3361 CERT_PKEY *cpk = s->s3->tmp.cert;
3362 int al = SSL_AD_INTERNAL_ERROR;
3365 SSLerr(SSL_F_TLS_CONSTRUCT_SERVER_CERTIFICATE, ERR_R_INTERNAL_ERROR);
3370 * In TLSv1.3 the certificate chain is always preceded by a 0 length context
3371 * for the server Certificate message
3373 if ((SSL_IS_TLS13(s) && !WPACKET_put_bytes_u8(pkt, 0))
3374 || !ssl3_output_cert_chain(s, pkt, cpk, &al)) {
3375 SSLerr(SSL_F_TLS_CONSTRUCT_SERVER_CERTIFICATE, ERR_R_INTERNAL_ERROR);
3376 ssl3_send_alert(s, SSL3_AL_FATAL, al);
3383 int tls_construct_new_session_ticket(SSL *s, WPACKET *pkt)
3385 unsigned char *senc = NULL;
3386 EVP_CIPHER_CTX *ctx = NULL;
3387 HMAC_CTX *hctx = NULL;
3388 unsigned char *p, *encdata1, *encdata2, *macdata1, *macdata2;
3389 const unsigned char *const_p;
3390 int len, slen_full, slen, lenfinal;
3393 SSL_CTX *tctx = s->session_ctx;
3394 unsigned char iv[EVP_MAX_IV_LENGTH];
3395 unsigned char key_name[TLSEXT_KEYNAME_LENGTH];
3396 int iv_len, al = SSL_AD_INTERNAL_ERROR;
3397 size_t macoffset, macendoffset;
3399 unsigned char age_add_c[sizeof(uint32_t)];
3403 if (SSL_IS_TLS13(s)) {
3404 if (RAND_bytes(age_add_u.age_add_c, sizeof(age_add_u)) <= 0)
3406 s->session->ext.tick_age_add = age_add_u.age_add;
3407 s->session->time = (long)time(NULL);
3408 if (s->s3->alpn_selected != NULL) {
3409 OPENSSL_free(s->session->ext.alpn_selected);
3410 s->session->ext.alpn_selected =
3411 OPENSSL_memdup(s->s3->alpn_selected, s->s3->alpn_selected_len);
3412 if (s->session->ext.alpn_selected == NULL) {
3413 SSLerr(SSL_F_TLS_CONSTRUCT_NEW_SESSION_TICKET,
3414 ERR_R_MALLOC_FAILURE);
3417 s->session->ext.alpn_selected_len = s->s3->alpn_selected_len;
3419 s->session->ext.max_early_data = s->max_early_data;
3422 /* get session encoding length */
3423 slen_full = i2d_SSL_SESSION(s->session, NULL);
3425 * Some length values are 16 bits, so forget it if session is too
3428 if (slen_full == 0 || slen_full > 0xFF00) {
3429 SSLerr(SSL_F_TLS_CONSTRUCT_NEW_SESSION_TICKET, ERR_R_INTERNAL_ERROR);
3432 senc = OPENSSL_malloc(slen_full);
3434 SSLerr(SSL_F_TLS_CONSTRUCT_NEW_SESSION_TICKET, ERR_R_MALLOC_FAILURE);
3438 ctx = EVP_CIPHER_CTX_new();
3439 hctx = HMAC_CTX_new();
3440 if (ctx == NULL || hctx == NULL) {
3441 SSLerr(SSL_F_TLS_CONSTRUCT_NEW_SESSION_TICKET, ERR_R_MALLOC_FAILURE);
3446 if (!i2d_SSL_SESSION(s->session, &p))
3450 * create a fresh copy (not shared with other threads) to clean up
3453 sess = d2i_SSL_SESSION(NULL, &const_p, slen_full);
3456 sess->session_id_length = 0; /* ID is irrelevant for the ticket */
3458 slen = i2d_SSL_SESSION(sess, NULL);
3459 if (slen == 0 || slen > slen_full) { /* shouldn't ever happen */
3460 SSL_SESSION_free(sess);
3464 if (!i2d_SSL_SESSION(sess, &p)) {
3465 SSL_SESSION_free(sess);
3468 SSL_SESSION_free(sess);
3471 * Initialize HMAC and cipher contexts. If callback present it does
3472 * all the work otherwise use generated values from parent ctx.
3474 if (tctx->ext.ticket_key_cb) {
3475 /* if 0 is returned, write an empty ticket */
3476 int ret = tctx->ext.ticket_key_cb(s, key_name, iv, ctx,
3481 /* Put timeout and length */
3482 if (!WPACKET_put_bytes_u32(pkt, 0)
3483 || !WPACKET_put_bytes_u16(pkt, 0)) {
3484 SSLerr(SSL_F_TLS_CONSTRUCT_NEW_SESSION_TICKET,
3485 ERR_R_INTERNAL_ERROR);
3489 EVP_CIPHER_CTX_free(ctx);
3490 HMAC_CTX_free(hctx);
3495 iv_len = EVP_CIPHER_CTX_iv_length(ctx);
3497 const EVP_CIPHER *cipher = EVP_aes_256_cbc();
3499 iv_len = EVP_CIPHER_iv_length(cipher);
3500 if (RAND_bytes(iv, iv_len) <= 0)
3502 if (!EVP_EncryptInit_ex(ctx, cipher, NULL,
3503 tctx->ext.tick_aes_key, iv))
3505 if (!HMAC_Init_ex(hctx, tctx->ext.tick_hmac_key,
3506 sizeof(tctx->ext.tick_hmac_key),
3507 EVP_sha256(), NULL))
3509 memcpy(key_name, tctx->ext.tick_key_name,
3510 sizeof(tctx->ext.tick_key_name));
3514 * Ticket lifetime hint: For TLSv1.2 this is advisory only and we leave this
3515 * unspecified for resumed session (for simplicity).
3516 * In TLSv1.3 we reset the "time" field above, and always specify the
3519 if (!WPACKET_put_bytes_u32(pkt,
3520 (s->hit && !SSL_IS_TLS13(s))
3521 ? 0 : s->session->timeout)
3523 && !WPACKET_put_bytes_u32(pkt, age_add_u.age_add))
3524 /* Now the actual ticket data */
3525 || !WPACKET_start_sub_packet_u16(pkt)
3526 || !WPACKET_get_total_written(pkt, &macoffset)
3527 /* Output key name */
3528 || !WPACKET_memcpy(pkt, key_name, sizeof(key_name))
3530 || !WPACKET_memcpy(pkt, iv, iv_len)
3531 || !WPACKET_reserve_bytes(pkt, slen + EVP_MAX_BLOCK_LENGTH,
3533 /* Encrypt session data */
3534 || !EVP_EncryptUpdate(ctx, encdata1, &len, senc, slen)
3535 || !WPACKET_allocate_bytes(pkt, len, &encdata2)
3536 || encdata1 != encdata2
3537 || !EVP_EncryptFinal(ctx, encdata1 + len, &lenfinal)
3538 || !WPACKET_allocate_bytes(pkt, lenfinal, &encdata2)
3539 || encdata1 + len != encdata2
3540 || len + lenfinal > slen + EVP_MAX_BLOCK_LENGTH
3541 || !WPACKET_get_total_written(pkt, &macendoffset)
3542 || !HMAC_Update(hctx,
3543 (unsigned char *)s->init_buf->data + macoffset,
3544 macendoffset - macoffset)
3545 || !WPACKET_reserve_bytes(pkt, EVP_MAX_MD_SIZE, &macdata1)
3546 || !HMAC_Final(hctx, macdata1, &hlen)
3547 || hlen > EVP_MAX_MD_SIZE
3548 || !WPACKET_allocate_bytes(pkt, hlen, &macdata2)
3549 || macdata1 != macdata2
3550 || !WPACKET_close(pkt)
3552 && !tls_construct_extensions(s, pkt,
3553 SSL_EXT_TLS1_3_NEW_SESSION_TICKET,
3555 SSLerr(SSL_F_TLS_CONSTRUCT_NEW_SESSION_TICKET, ERR_R_INTERNAL_ERROR);
3558 EVP_CIPHER_CTX_free(ctx);
3559 HMAC_CTX_free(hctx);
3564 ossl_statem_set_error(s);
3566 EVP_CIPHER_CTX_free(ctx);
3567 HMAC_CTX_free(hctx);
3568 ssl3_send_alert(s, SSL3_AL_FATAL, SSL_AD_INTERNAL_ERROR);
3573 * In TLSv1.3 this is called from the extensions code, otherwise it is used to
3574 * create a separate message. Returns 1 on success or 0 on failure.
3576 int tls_construct_cert_status_body(SSL *s, WPACKET *pkt)
3578 if (!WPACKET_put_bytes_u8(pkt, s->ext.status_type)
3579 || !WPACKET_sub_memcpy_u24(pkt, s->ext.ocsp.resp,
3580 s->ext.ocsp.resp_len)) {
3581 SSLerr(SSL_F_TLS_CONSTRUCT_CERT_STATUS_BODY, ERR_R_INTERNAL_ERROR);
3588 int tls_construct_cert_status(SSL *s, WPACKET *pkt)
3590 if (!tls_construct_cert_status_body(s, pkt)) {
3591 ssl3_send_alert(s, SSL3_AL_FATAL, SSL_AD_INTERNAL_ERROR);
3598 #ifndef OPENSSL_NO_NEXTPROTONEG
3600 * tls_process_next_proto reads a Next Protocol Negotiation handshake message.
3601 * It sets the next_proto member in s if found
3603 MSG_PROCESS_RETURN tls_process_next_proto(SSL *s, PACKET *pkt)
3605 PACKET next_proto, padding;
3606 size_t next_proto_len;
3607 int al = SSL_AD_INTERNAL_ERROR;
3610 * The payload looks like:
3612 * uint8 proto[proto_len];
3613 * uint8 padding_len;
3614 * uint8 padding[padding_len];
3616 if (!PACKET_get_length_prefixed_1(pkt, &next_proto)
3617 || !PACKET_get_length_prefixed_1(pkt, &padding)
3618 || PACKET_remaining(pkt) > 0) {
3619 al = SSL_AD_DECODE_ERROR;
3620 SSLerr(SSL_F_TLS_PROCESS_NEXT_PROTO, SSL_R_LENGTH_MISMATCH);
3624 if (!PACKET_memdup(&next_proto, &s->ext.npn, &next_proto_len)) {
3629 s->ext.npn_len = (unsigned char)next_proto_len;
3631 return MSG_PROCESS_CONTINUE_READING;
3633 ssl3_send_alert(s, SSL3_AL_FATAL, al);
3634 ossl_statem_set_error(s);
3635 return MSG_PROCESS_ERROR;
3639 static int tls_construct_encrypted_extensions(SSL *s, WPACKET *pkt)
3643 if (!tls_construct_extensions(s, pkt, SSL_EXT_TLS1_3_ENCRYPTED_EXTENSIONS,
3645 ssl3_send_alert(s, SSL3_AL_FATAL, al);
3646 SSLerr(SSL_F_TLS_CONSTRUCT_ENCRYPTED_EXTENSIONS, ERR_R_INTERNAL_ERROR);
3653 static int tls_construct_hello_retry_request(SSL *s, WPACKET *pkt)
3655 int al = SSL_AD_INTERNAL_ERROR;
3659 * TODO(TLS1.3): Remove the DRAFT version before release
3660 * (should be s->version)
3662 if (!WPACKET_put_bytes_u16(pkt, TLS1_3_VERSION_DRAFT)
3663 || !s->method->put_cipher_by_char(s->s3->tmp.new_cipher, pkt, &len)
3664 || !tls_construct_extensions(s, pkt,
3665 SSL_EXT_TLS1_3_HELLO_RETRY_REQUEST,
3667 SSLerr(SSL_F_TLS_CONSTRUCT_HELLO_RETRY_REQUEST, ERR_R_INTERNAL_ERROR);
3671 /* Ditch the session. We'll create a new one next time around */
3672 SSL_SESSION_free(s->session);
3677 * Re-initialise the Transcript Hash. We're going to prepopulate it with
3678 * a synthetic message_hash in place of ClientHello1.
3680 if (!create_synthetic_message_hash(s))
3685 ssl3_send_alert(s, SSL3_AL_FATAL, al);
3689 MSG_PROCESS_RETURN tls_process_end_of_early_data(SSL *s, PACKET *pkt)
3691 int al = SSL_AD_INTERNAL_ERROR;
3693 if (PACKET_remaining(pkt) != 0) {
3694 al = SSL_AD_DECODE_ERROR;
3695 SSLerr(SSL_F_TLS_PROCESS_END_OF_EARLY_DATA, SSL_R_LENGTH_MISMATCH);
3696 ossl_statem_set_error(s);
3697 return MSG_PROCESS_ERROR;
3700 if (s->early_data_state != SSL_EARLY_DATA_READING
3701 && s->early_data_state != SSL_EARLY_DATA_READ_RETRY) {
3702 SSLerr(SSL_F_TLS_PROCESS_END_OF_EARLY_DATA, ERR_R_INTERNAL_ERROR);
3707 * EndOfEarlyData signals a key change so the end of the message must be on
3708 * a record boundary.
3710 if (RECORD_LAYER_processed_read_pending(&s->rlayer)) {
3711 al = SSL_AD_UNEXPECTED_MESSAGE;
3712 SSLerr(SSL_F_TLS_PROCESS_END_OF_EARLY_DATA,
3713 SSL_R_NOT_ON_RECORD_BOUNDARY);
3717 s->early_data_state = SSL_EARLY_DATA_FINISHED_READING;
3718 if (!s->method->ssl3_enc->change_cipher_state(s,
3719 SSL3_CC_HANDSHAKE | SSL3_CHANGE_CIPHER_SERVER_READ)) {
3720 SSLerr(SSL_F_TLS_PROCESS_END_OF_EARLY_DATA, ERR_R_INTERNAL_ERROR);
3724 return MSG_PROCESS_CONTINUE_READING;
3726 ssl3_send_alert(s, SSL3_AL_FATAL, al);
3727 ossl_statem_set_error(s);
3728 return MSG_PROCESS_ERROR;