2 * Copyright 1995-2016 The OpenSSL Project Authors. All Rights Reserved.
4 * Licensed under the OpenSSL license (the "License"). You may not use
5 * this file except in compliance with the License. You can obtain a copy
6 * in the file LICENSE in the source distribution or at
7 * https://www.openssl.org/source/license.html
10 /* ====================================================================
11 * Copyright 2002 Sun Microsystems, Inc. ALL RIGHTS RESERVED.
13 * Portions of the attached software ("Contribution") are developed by
14 * SUN MICROSYSTEMS, INC., and are contributed to the OpenSSL project.
16 * The Contribution is licensed pursuant to the OpenSSL open source
17 * license provided above.
19 * ECC cipher suite support in OpenSSL originally written by
20 * Vipul Gupta and Sumit Gupta of Sun Microsystems Laboratories.
23 /* ====================================================================
24 * Copyright 2005 Nokia. All rights reserved.
26 * The portions of the attached software ("Contribution") is developed by
27 * Nokia Corporation and is licensed pursuant to the OpenSSL open source
30 * The Contribution, originally written by Mika Kousa and Pasi Eronen of
31 * Nokia Corporation, consists of the "PSK" (Pre-Shared Key) ciphersuites
32 * support (see RFC 4279) to OpenSSL.
34 * No patent licenses or other rights except those expressly stated in
35 * the OpenSSL open source license shall be deemed granted or received
36 * expressly, by implication, estoppel, or otherwise.
38 * No assurances are provided by Nokia that the Contribution does not
39 * infringe the patent or other intellectual property rights of any third
40 * party or that the license provides you with all the necessary rights
41 * to make use of the Contribution.
43 * THE SOFTWARE IS PROVIDED "AS IS" WITHOUT WARRANTY OF ANY KIND. IN
44 * ADDITION TO THE DISCLAIMERS INCLUDED IN THE LICENSE, NOKIA
45 * SPECIFICALLY DISCLAIMS ANY LIABILITY FOR CLAIMS BROUGHT BY YOU OR ANY
46 * OTHER ENTITY BASED ON INFRINGEMENT OF INTELLECTUAL PROPERTY RIGHTS OR
51 #include "../ssl_locl.h"
52 #include "statem_locl.h"
53 #include "internal/constant_time_locl.h"
54 #include <openssl/buffer.h>
55 #include <openssl/rand.h>
56 #include <openssl/objects.h>
57 #include <openssl/evp.h>
58 #include <openssl/hmac.h>
59 #include <openssl/x509.h>
60 #include <openssl/dh.h>
61 #include <openssl/bn.h>
62 #include <openssl/md5.h>
64 static int tls_construct_encrypted_extensions(SSL *s, WPACKET *pkt);
65 static int tls_construct_hello_retry_request(SSL *s, WPACKET *pkt);
68 * ossl_statem_server13_read_transition() encapsulates the logic for the allowed
69 * handshake state transitions when a TLSv1.3 server is reading messages from
70 * the client. The message type that the client has sent is provided in |mt|.
71 * The current state is in |s->statem.hand_state|.
73 * Return values are 1 for success (transition allowed) and 0 on error
74 * (transition not allowed)
76 static int ossl_statem_server13_read_transition(SSL *s, int mt)
78 OSSL_STATEM *st = &s->statem;
81 * Note: There is no case for TLS_ST_BEFORE because at that stage we have
82 * not negotiated TLSv1.3 yet, so that case is handled by
83 * ossl_statem_server_read_transition()
85 switch (st->hand_state) {
89 case TLS_ST_SW_HELLO_RETRY_REQUEST:
90 if (mt == SSL3_MT_CLIENT_HELLO) {
91 st->hand_state = TLS_ST_SR_CLNT_HELLO;
96 case TLS_ST_SW_FINISHED:
97 if (s->s3->tmp.cert_request) {
98 if (mt == SSL3_MT_CERTIFICATE) {
99 st->hand_state = TLS_ST_SR_CERT;
103 if (mt == SSL3_MT_FINISHED) {
104 st->hand_state = TLS_ST_SR_FINISHED;
111 if (s->session->peer == NULL) {
112 if (mt == SSL3_MT_FINISHED) {
113 st->hand_state = TLS_ST_SR_FINISHED;
117 if (mt == SSL3_MT_CERTIFICATE_VERIFY) {
118 st->hand_state = TLS_ST_SR_CERT_VRFY;
124 case TLS_ST_SR_CERT_VRFY:
125 if (mt == SSL3_MT_FINISHED) {
126 st->hand_state = TLS_ST_SR_FINISHED;
133 * Its never ok to start processing handshake messages in the middle of
134 * early data (i.e. before we've received the end of early data alert)
136 if (s->early_data_state == SSL_EARLY_DATA_READING)
138 if (mt == SSL3_MT_KEY_UPDATE) {
139 st->hand_state = TLS_ST_SR_KEY_UPDATE;
145 /* No valid transition found */
146 ssl3_send_alert(s, SSL3_AL_FATAL, SSL3_AD_UNEXPECTED_MESSAGE);
147 SSLerr(SSL_F_OSSL_STATEM_SERVER13_READ_TRANSITION,
148 SSL_R_UNEXPECTED_MESSAGE);
153 * ossl_statem_server_read_transition() encapsulates the logic for the allowed
154 * handshake state transitions when the server is reading messages from the
155 * client. The message type that the client has sent is provided in |mt|. The
156 * current state is in |s->statem.hand_state|.
158 * Return values are 1 for success (transition allowed) and 0 on error
159 * (transition not allowed)
161 int ossl_statem_server_read_transition(SSL *s, int mt)
163 OSSL_STATEM *st = &s->statem;
165 if (SSL_IS_TLS13(s)) {
166 if (!ossl_statem_server13_read_transition(s, mt))
171 switch (st->hand_state) {
177 case DTLS_ST_SW_HELLO_VERIFY_REQUEST:
178 if (mt == SSL3_MT_CLIENT_HELLO) {
179 st->hand_state = TLS_ST_SR_CLNT_HELLO;
184 case TLS_ST_SW_SRVR_DONE:
186 * If we get a CKE message after a ServerDone then either
187 * 1) We didn't request a Certificate
189 * 2) If we did request one then
190 * a) We allow no Certificate to be returned
192 * b) We are running SSL3 (in TLS1.0+ the client must return a 0
193 * list if we requested a certificate)
195 if (mt == SSL3_MT_CLIENT_KEY_EXCHANGE) {
196 if (s->s3->tmp.cert_request) {
197 if (s->version == SSL3_VERSION) {
198 if ((s->verify_mode & SSL_VERIFY_PEER)
199 && (s->verify_mode & SSL_VERIFY_FAIL_IF_NO_PEER_CERT)) {
201 * This isn't an unexpected message as such - we're just
202 * not going to accept it because we require a client
205 ssl3_send_alert(s, SSL3_AL_FATAL,
206 SSL3_AD_HANDSHAKE_FAILURE);
207 SSLerr(SSL_F_OSSL_STATEM_SERVER_READ_TRANSITION,
208 SSL_R_PEER_DID_NOT_RETURN_A_CERTIFICATE);
211 st->hand_state = TLS_ST_SR_KEY_EXCH;
215 st->hand_state = TLS_ST_SR_KEY_EXCH;
218 } else if (s->s3->tmp.cert_request) {
219 if (mt == SSL3_MT_CERTIFICATE) {
220 st->hand_state = TLS_ST_SR_CERT;
227 if (mt == SSL3_MT_CLIENT_KEY_EXCHANGE) {
228 st->hand_state = TLS_ST_SR_KEY_EXCH;
233 case TLS_ST_SR_KEY_EXCH:
235 * We should only process a CertificateVerify message if we have
236 * received a Certificate from the client. If so then |s->session->peer|
237 * will be non NULL. In some instances a CertificateVerify message is
238 * not required even if the peer has sent a Certificate (e.g. such as in
239 * the case of static DH). In that case |st->no_cert_verify| should be
242 if (s->session->peer == NULL || st->no_cert_verify) {
243 if (mt == SSL3_MT_CHANGE_CIPHER_SPEC) {
245 * For the ECDH ciphersuites when the client sends its ECDH
246 * pub key in a certificate, the CertificateVerify message is
247 * not sent. Also for GOST ciphersuites when the client uses
248 * its key from the certificate for key exchange.
250 st->hand_state = TLS_ST_SR_CHANGE;
254 if (mt == SSL3_MT_CERTIFICATE_VERIFY) {
255 st->hand_state = TLS_ST_SR_CERT_VRFY;
261 case TLS_ST_SR_CERT_VRFY:
262 if (mt == SSL3_MT_CHANGE_CIPHER_SPEC) {
263 st->hand_state = TLS_ST_SR_CHANGE;
268 case TLS_ST_SR_CHANGE:
269 #ifndef OPENSSL_NO_NEXTPROTONEG
270 if (s->s3->npn_seen) {
271 if (mt == SSL3_MT_NEXT_PROTO) {
272 st->hand_state = TLS_ST_SR_NEXT_PROTO;
277 if (mt == SSL3_MT_FINISHED) {
278 st->hand_state = TLS_ST_SR_FINISHED;
281 #ifndef OPENSSL_NO_NEXTPROTONEG
286 #ifndef OPENSSL_NO_NEXTPROTONEG
287 case TLS_ST_SR_NEXT_PROTO:
288 if (mt == SSL3_MT_FINISHED) {
289 st->hand_state = TLS_ST_SR_FINISHED;
295 case TLS_ST_SW_FINISHED:
296 if (mt == SSL3_MT_CHANGE_CIPHER_SPEC) {
297 st->hand_state = TLS_ST_SR_CHANGE;
304 /* No valid transition found */
305 ssl3_send_alert(s, SSL3_AL_FATAL, SSL3_AD_UNEXPECTED_MESSAGE);
306 SSLerr(SSL_F_OSSL_STATEM_SERVER_READ_TRANSITION, SSL_R_UNEXPECTED_MESSAGE);
311 * Should we send a ServerKeyExchange message?
313 * Valid return values are:
317 static int send_server_key_exchange(SSL *s)
319 unsigned long alg_k = s->s3->tmp.new_cipher->algorithm_mkey;
322 * only send a ServerKeyExchange if DH or fortezza but we have a
323 * sign only certificate PSK: may send PSK identity hints For
324 * ECC ciphersuites, we send a serverKeyExchange message only if
325 * the cipher suite is either ECDH-anon or ECDHE. In other cases,
326 * the server certificate contains the server's public key for
329 if (alg_k & (SSL_kDHE | SSL_kECDHE)
331 * PSK: send ServerKeyExchange if PSK identity hint if
334 #ifndef OPENSSL_NO_PSK
335 /* Only send SKE if we have identity hint for plain PSK */
336 || ((alg_k & (SSL_kPSK | SSL_kRSAPSK))
337 && s->cert->psk_identity_hint)
338 /* For other PSK always send SKE */
339 || (alg_k & (SSL_PSK & (SSL_kDHEPSK | SSL_kECDHEPSK)))
341 #ifndef OPENSSL_NO_SRP
342 /* SRP: send ServerKeyExchange */
343 || (alg_k & SSL_kSRP)
353 * Should we send a CertificateRequest message?
355 * Valid return values are:
359 static int send_certificate_request(SSL *s)
362 /* don't request cert unless asked for it: */
363 s->verify_mode & SSL_VERIFY_PEER
365 * if SSL_VERIFY_CLIENT_ONCE is set, don't request cert
366 * during re-negotiation:
368 && (s->s3->tmp.finish_md_len == 0 ||
369 !(s->verify_mode & SSL_VERIFY_CLIENT_ONCE))
371 * never request cert in anonymous ciphersuites (see
372 * section "Certificate request" in SSL 3 drafts and in
375 && (!(s->s3->tmp.new_cipher->algorithm_auth & SSL_aNULL)
377 * ... except when the application insists on
378 * verification (against the specs, but statem_clnt.c accepts
381 || (s->verify_mode & SSL_VERIFY_FAIL_IF_NO_PEER_CERT))
382 /* don't request certificate for SRP auth */
383 && !(s->s3->tmp.new_cipher->algorithm_auth & SSL_aSRP)
385 * With normal PSK Certificates and Certificate Requests
388 && !(s->s3->tmp.new_cipher->algorithm_auth & SSL_aPSK)) {
396 * ossl_statem_server13_write_transition() works out what handshake state to
397 * move to next when a TLSv1.3 server is writing messages to be sent to the
400 static WRITE_TRAN ossl_statem_server13_write_transition(SSL *s)
402 OSSL_STATEM *st = &s->statem;
405 * No case for TLS_ST_BEFORE, because at that stage we have not negotiated
406 * TLSv1.3 yet, so that is handled by ossl_statem_server_write_transition()
409 switch (st->hand_state) {
411 /* Shouldn't happen */
412 return WRITE_TRAN_ERROR;
415 if (s->early_data_state == SSL_EARLY_DATA_FINISHED_READING) {
416 st->hand_state = TLS_ST_SW_FINISHED;
417 return WRITE_TRAN_FINISHED;
419 if (s->key_update != SSL_KEY_UPDATE_NONE) {
420 st->hand_state = TLS_ST_SW_KEY_UPDATE;
421 return WRITE_TRAN_CONTINUE;
423 /* Try to read from the client instead */
424 return WRITE_TRAN_FINISHED;
426 case TLS_ST_SR_CLNT_HELLO:
427 if (s->hello_retry_request)
428 st->hand_state = TLS_ST_SW_HELLO_RETRY_REQUEST;
430 st->hand_state = TLS_ST_SW_SRVR_HELLO;
431 return WRITE_TRAN_CONTINUE;
433 case TLS_ST_SW_HELLO_RETRY_REQUEST:
434 return WRITE_TRAN_FINISHED;
436 case TLS_ST_SW_SRVR_HELLO:
437 st->hand_state = TLS_ST_SW_ENCRYPTED_EXTENSIONS;
438 return WRITE_TRAN_CONTINUE;
440 case TLS_ST_SW_ENCRYPTED_EXTENSIONS:
442 st->hand_state = TLS_ST_SW_FINISHED;
443 else if (send_certificate_request(s))
444 st->hand_state = TLS_ST_SW_CERT_REQ;
446 st->hand_state = TLS_ST_SW_CERT;
448 return WRITE_TRAN_CONTINUE;
450 case TLS_ST_SW_CERT_REQ:
451 st->hand_state = TLS_ST_SW_CERT;
452 return WRITE_TRAN_CONTINUE;
455 st->hand_state = TLS_ST_SW_CERT_VRFY;
456 return WRITE_TRAN_CONTINUE;
458 case TLS_ST_SW_CERT_VRFY:
459 st->hand_state = TLS_ST_SW_FINISHED;
460 return WRITE_TRAN_CONTINUE;
462 case TLS_ST_SW_FINISHED:
463 if (s->early_data_state == SSL_EARLY_DATA_ACCEPTING) {
464 st->hand_state = TLS_ST_OK;
465 return WRITE_TRAN_CONTINUE;
467 return WRITE_TRAN_FINISHED;
469 case TLS_ST_SR_FINISHED:
471 * Technically we have finished the handshake at this point, but we're
472 * going to remain "in_init" for now and write out the session ticket
474 * TODO(TLS1.3): Perhaps we need to be able to control this behaviour
475 * and give the application the opportunity to delay sending the
478 st->hand_state = TLS_ST_SW_SESSION_TICKET;
479 return WRITE_TRAN_CONTINUE;
481 case TLS_ST_SR_KEY_UPDATE:
482 if (s->key_update != SSL_KEY_UPDATE_NONE) {
483 st->hand_state = TLS_ST_SW_KEY_UPDATE;
484 return WRITE_TRAN_CONTINUE;
488 case TLS_ST_SW_KEY_UPDATE:
489 case TLS_ST_SW_SESSION_TICKET:
490 st->hand_state = TLS_ST_OK;
491 return WRITE_TRAN_CONTINUE;
496 * ossl_statem_server_write_transition() works out what handshake state to move
497 * to next when the server is writing messages to be sent to the client.
499 WRITE_TRAN ossl_statem_server_write_transition(SSL *s)
501 OSSL_STATEM *st = &s->statem;
504 * Note that before the ClientHello we don't know what version we are going
505 * to negotiate yet, so we don't take this branch until later
509 return ossl_statem_server13_write_transition(s);
511 switch (st->hand_state) {
513 /* Shouldn't happen */
514 return WRITE_TRAN_ERROR;
517 if (st->request_state == TLS_ST_SW_HELLO_REQ) {
518 /* We must be trying to renegotiate */
519 st->hand_state = TLS_ST_SW_HELLO_REQ;
520 st->request_state = TLS_ST_BEFORE;
521 return WRITE_TRAN_CONTINUE;
523 /* Must be an incoming ClientHello */
524 if (!tls_setup_handshake(s)) {
525 ossl_statem_set_error(s);
526 return WRITE_TRAN_ERROR;
531 /* Just go straight to trying to read from the client */
532 return WRITE_TRAN_FINISHED;
534 case TLS_ST_SW_HELLO_REQ:
535 st->hand_state = TLS_ST_OK;
536 return WRITE_TRAN_CONTINUE;
538 case TLS_ST_SR_CLNT_HELLO:
539 if (SSL_IS_DTLS(s) && !s->d1->cookie_verified
540 && (SSL_get_options(s) & SSL_OP_COOKIE_EXCHANGE))
541 st->hand_state = DTLS_ST_SW_HELLO_VERIFY_REQUEST;
543 st->hand_state = TLS_ST_SW_SRVR_HELLO;
544 return WRITE_TRAN_CONTINUE;
546 case DTLS_ST_SW_HELLO_VERIFY_REQUEST:
547 return WRITE_TRAN_FINISHED;
549 case TLS_ST_SW_SRVR_HELLO:
551 if (s->ext.ticket_expected)
552 st->hand_state = TLS_ST_SW_SESSION_TICKET;
554 st->hand_state = TLS_ST_SW_CHANGE;
556 /* Check if it is anon DH or anon ECDH, */
557 /* normal PSK or SRP */
558 if (!(s->s3->tmp.new_cipher->algorithm_auth &
559 (SSL_aNULL | SSL_aSRP | SSL_aPSK))) {
560 st->hand_state = TLS_ST_SW_CERT;
561 } else if (send_server_key_exchange(s)) {
562 st->hand_state = TLS_ST_SW_KEY_EXCH;
563 } else if (send_certificate_request(s)) {
564 st->hand_state = TLS_ST_SW_CERT_REQ;
566 st->hand_state = TLS_ST_SW_SRVR_DONE;
569 return WRITE_TRAN_CONTINUE;
572 if (s->ext.status_expected) {
573 st->hand_state = TLS_ST_SW_CERT_STATUS;
574 return WRITE_TRAN_CONTINUE;
578 case TLS_ST_SW_CERT_STATUS:
579 if (send_server_key_exchange(s)) {
580 st->hand_state = TLS_ST_SW_KEY_EXCH;
581 return WRITE_TRAN_CONTINUE;
585 case TLS_ST_SW_KEY_EXCH:
586 if (send_certificate_request(s)) {
587 st->hand_state = TLS_ST_SW_CERT_REQ;
588 return WRITE_TRAN_CONTINUE;
592 case TLS_ST_SW_CERT_REQ:
593 st->hand_state = TLS_ST_SW_SRVR_DONE;
594 return WRITE_TRAN_CONTINUE;
596 case TLS_ST_SW_SRVR_DONE:
597 return WRITE_TRAN_FINISHED;
599 case TLS_ST_SR_FINISHED:
601 st->hand_state = TLS_ST_OK;
602 return WRITE_TRAN_CONTINUE;
603 } else if (s->ext.ticket_expected) {
604 st->hand_state = TLS_ST_SW_SESSION_TICKET;
606 st->hand_state = TLS_ST_SW_CHANGE;
608 return WRITE_TRAN_CONTINUE;
610 case TLS_ST_SW_SESSION_TICKET:
611 st->hand_state = TLS_ST_SW_CHANGE;
612 return WRITE_TRAN_CONTINUE;
614 case TLS_ST_SW_CHANGE:
615 st->hand_state = TLS_ST_SW_FINISHED;
616 return WRITE_TRAN_CONTINUE;
618 case TLS_ST_SW_FINISHED:
620 return WRITE_TRAN_FINISHED;
622 st->hand_state = TLS_ST_OK;
623 return WRITE_TRAN_CONTINUE;
628 * Perform any pre work that needs to be done prior to sending a message from
629 * the server to the client.
631 WORK_STATE ossl_statem_server_pre_work(SSL *s, WORK_STATE wst)
633 OSSL_STATEM *st = &s->statem;
635 switch (st->hand_state) {
637 /* No pre work to be done */
640 case TLS_ST_SW_HELLO_REQ:
643 dtls1_clear_sent_buffer(s);
646 case DTLS_ST_SW_HELLO_VERIFY_REQUEST:
648 if (SSL_IS_DTLS(s)) {
649 dtls1_clear_sent_buffer(s);
650 /* We don't buffer this message so don't use the timer */
655 case TLS_ST_SW_SRVR_HELLO:
656 if (SSL_IS_DTLS(s)) {
658 * Messages we write from now on should be bufferred and
659 * retransmitted if necessary, so we need to use the timer now
665 case TLS_ST_SW_SRVR_DONE:
666 #ifndef OPENSSL_NO_SCTP
667 if (SSL_IS_DTLS(s) && BIO_dgram_is_sctp(SSL_get_wbio(s)))
668 return dtls_wait_for_dry(s);
670 return WORK_FINISHED_CONTINUE;
672 case TLS_ST_SW_SESSION_TICKET:
673 if (SSL_IS_TLS13(s)) {
675 * Actually this is the end of the handshake, but we're going
676 * straight into writing the session ticket out. So we finish off
677 * the handshake, but keep the various buffers active.
679 return tls_finish_handshake(s, wst, 0);
680 } if (SSL_IS_DTLS(s)) {
682 * We're into the last flight. We don't retransmit the last flight
683 * unless we need to, so we don't use the timer
689 case TLS_ST_SW_CHANGE:
690 s->session->cipher = s->s3->tmp.new_cipher;
691 if (!s->method->ssl3_enc->setup_key_block(s)) {
692 ossl_statem_set_error(s);
695 if (SSL_IS_DTLS(s)) {
697 * We're into the last flight. We don't retransmit the last flight
698 * unless we need to, so we don't use the timer. This might have
699 * already been set to 0 if we sent a NewSessionTicket message,
700 * but we'll set it again here in case we didn't.
704 return WORK_FINISHED_CONTINUE;
707 return tls_finish_handshake(s, wst, 1);
710 return WORK_FINISHED_CONTINUE;
714 * Perform any work that needs to be done after sending a message from the
715 * server to the client.
717 WORK_STATE ossl_statem_server_post_work(SSL *s, WORK_STATE wst)
719 OSSL_STATEM *st = &s->statem;
723 switch (st->hand_state) {
725 /* No post work to be done */
728 case TLS_ST_SW_HELLO_RETRY_REQUEST:
729 if (statem_flush(s) != 1)
733 case TLS_ST_SW_HELLO_REQ:
734 if (statem_flush(s) != 1)
736 if (!ssl3_init_finished_mac(s)) {
737 ossl_statem_set_error(s);
742 case DTLS_ST_SW_HELLO_VERIFY_REQUEST:
743 if (statem_flush(s) != 1)
745 /* HelloVerifyRequest resets Finished MAC */
746 if (s->version != DTLS1_BAD_VER && !ssl3_init_finished_mac(s)) {
747 ossl_statem_set_error(s);
751 * The next message should be another ClientHello which we need to
752 * treat like it was the first packet
757 case TLS_ST_SW_SRVR_HELLO:
758 #ifndef OPENSSL_NO_SCTP
759 if (SSL_IS_DTLS(s) && s->hit) {
760 unsigned char sctpauthkey[64];
761 char labelbuffer[sizeof(DTLS1_SCTP_AUTH_LABEL)];
764 * Add new shared key for SCTP-Auth, will be ignored if no
767 memcpy(labelbuffer, DTLS1_SCTP_AUTH_LABEL,
768 sizeof(DTLS1_SCTP_AUTH_LABEL));
770 if (SSL_export_keying_material(s, sctpauthkey,
771 sizeof(sctpauthkey), labelbuffer,
772 sizeof(labelbuffer), NULL, 0,
774 ossl_statem_set_error(s);
778 BIO_ctrl(SSL_get_wbio(s), BIO_CTRL_DGRAM_SCTP_ADD_AUTH_KEY,
779 sizeof(sctpauthkey), sctpauthkey);
783 * TODO(TLS1.3): This actually causes a problem. We don't yet know
784 * whether the next record we are going to receive is an unencrypted
785 * alert, or an encrypted handshake message. We're going to need
786 * something clever in the record layer for this.
788 if (SSL_IS_TLS13(s)) {
789 if (!s->method->ssl3_enc->setup_key_block(s)
790 || !s->method->ssl3_enc->change_cipher_state(s,
791 SSL3_CC_HANDSHAKE | SSL3_CHANGE_CIPHER_SERVER_WRITE))
794 if (s->ext.early_data != SSL_EARLY_DATA_ACCEPTED
795 && !s->method->ssl3_enc->change_cipher_state(s,
796 SSL3_CC_HANDSHAKE |SSL3_CHANGE_CIPHER_SERVER_READ))
801 case TLS_ST_SW_CHANGE:
802 #ifndef OPENSSL_NO_SCTP
803 if (SSL_IS_DTLS(s) && !s->hit) {
805 * Change to new shared key of SCTP-Auth, will be ignored if
808 BIO_ctrl(SSL_get_wbio(s), BIO_CTRL_DGRAM_SCTP_NEXT_AUTH_KEY,
812 if (!s->method->ssl3_enc->change_cipher_state(s,
813 SSL3_CHANGE_CIPHER_SERVER_WRITE))
815 ossl_statem_set_error(s);
820 dtls1_reset_seq_numbers(s, SSL3_CC_WRITE);
823 case TLS_ST_SW_SRVR_DONE:
824 if (statem_flush(s) != 1)
828 case TLS_ST_SW_FINISHED:
829 if (statem_flush(s) != 1)
831 #ifndef OPENSSL_NO_SCTP
832 if (SSL_IS_DTLS(s) && s->hit) {
834 * Change to new shared key of SCTP-Auth, will be ignored if
837 BIO_ctrl(SSL_get_wbio(s), BIO_CTRL_DGRAM_SCTP_NEXT_AUTH_KEY,
841 if (SSL_IS_TLS13(s)) {
842 if (!s->method->ssl3_enc->generate_master_secret(s,
843 s->master_secret, s->handshake_secret, 0,
844 &s->session->master_key_length)
845 || !s->method->ssl3_enc->change_cipher_state(s,
846 SSL3_CC_APPLICATION | SSL3_CHANGE_CIPHER_SERVER_WRITE))
851 case TLS_ST_SW_KEY_UPDATE:
852 if (statem_flush(s) != 1)
854 if (!tls13_update_key(s, 1))
858 case TLS_ST_SW_SESSION_TICKET:
859 if (SSL_IS_TLS13(s) && statem_flush(s) != 1)
864 return WORK_FINISHED_CONTINUE;
868 * Get the message construction function and message type for sending from the
871 * Valid return values are:
875 int ossl_statem_server_construct_message(SSL *s, WPACKET *pkt,
876 confunc_f *confunc, int *mt)
878 OSSL_STATEM *st = &s->statem;
880 switch (st->hand_state) {
882 /* Shouldn't happen */
885 case TLS_ST_SW_CHANGE:
887 *confunc = dtls_construct_change_cipher_spec;
889 *confunc = tls_construct_change_cipher_spec;
890 *mt = SSL3_MT_CHANGE_CIPHER_SPEC;
893 case DTLS_ST_SW_HELLO_VERIFY_REQUEST:
894 *confunc = dtls_construct_hello_verify_request;
895 *mt = DTLS1_MT_HELLO_VERIFY_REQUEST;
898 case TLS_ST_SW_HELLO_REQ:
899 /* No construction function needed */
901 *mt = SSL3_MT_HELLO_REQUEST;
904 case TLS_ST_SW_SRVR_HELLO:
905 *confunc = tls_construct_server_hello;
906 *mt = SSL3_MT_SERVER_HELLO;
910 *confunc = tls_construct_server_certificate;
911 *mt = SSL3_MT_CERTIFICATE;
914 case TLS_ST_SW_CERT_VRFY:
915 *confunc = tls_construct_cert_verify;
916 *mt = SSL3_MT_CERTIFICATE_VERIFY;
920 case TLS_ST_SW_KEY_EXCH:
921 *confunc = tls_construct_server_key_exchange;
922 *mt = SSL3_MT_SERVER_KEY_EXCHANGE;
925 case TLS_ST_SW_CERT_REQ:
926 *confunc = tls_construct_certificate_request;
927 *mt = SSL3_MT_CERTIFICATE_REQUEST;
930 case TLS_ST_SW_SRVR_DONE:
931 *confunc = tls_construct_server_done;
932 *mt = SSL3_MT_SERVER_DONE;
935 case TLS_ST_SW_SESSION_TICKET:
936 *confunc = tls_construct_new_session_ticket;
937 *mt = SSL3_MT_NEWSESSION_TICKET;
940 case TLS_ST_SW_CERT_STATUS:
941 *confunc = tls_construct_cert_status;
942 *mt = SSL3_MT_CERTIFICATE_STATUS;
945 case TLS_ST_SW_FINISHED:
946 *confunc = tls_construct_finished;
947 *mt = SSL3_MT_FINISHED;
950 case TLS_ST_SW_ENCRYPTED_EXTENSIONS:
951 *confunc = tls_construct_encrypted_extensions;
952 *mt = SSL3_MT_ENCRYPTED_EXTENSIONS;
955 case TLS_ST_SW_HELLO_RETRY_REQUEST:
956 *confunc = tls_construct_hello_retry_request;
957 *mt = SSL3_MT_HELLO_RETRY_REQUEST;
960 case TLS_ST_SW_KEY_UPDATE:
961 *confunc = tls_construct_key_update;
962 *mt = SSL3_MT_KEY_UPDATE;
970 * Maximum size (excluding the Handshake header) of a ClientHello message,
971 * calculated as follows:
973 * 2 + # client_version
974 * 32 + # only valid length for random
975 * 1 + # length of session_id
976 * 32 + # maximum size for session_id
977 * 2 + # length of cipher suites
978 * 2^16-2 + # maximum length of cipher suites array
979 * 1 + # length of compression_methods
980 * 2^8-1 + # maximum length of compression methods
981 * 2 + # length of extensions
982 * 2^16-1 # maximum length of extensions
984 #define CLIENT_HELLO_MAX_LENGTH 131396
986 #define CLIENT_KEY_EXCH_MAX_LENGTH 2048
987 #define NEXT_PROTO_MAX_LENGTH 514
990 * Returns the maximum allowed length for the current message that we are
991 * reading. Excludes the message header.
993 size_t ossl_statem_server_max_message_size(SSL *s)
995 OSSL_STATEM *st = &s->statem;
997 switch (st->hand_state) {
999 /* Shouldn't happen */
1002 case TLS_ST_SR_CLNT_HELLO:
1003 return CLIENT_HELLO_MAX_LENGTH;
1005 case TLS_ST_SR_CERT:
1006 return s->max_cert_list;
1008 case TLS_ST_SR_KEY_EXCH:
1009 return CLIENT_KEY_EXCH_MAX_LENGTH;
1011 case TLS_ST_SR_CERT_VRFY:
1012 return SSL3_RT_MAX_PLAIN_LENGTH;
1014 #ifndef OPENSSL_NO_NEXTPROTONEG
1015 case TLS_ST_SR_NEXT_PROTO:
1016 return NEXT_PROTO_MAX_LENGTH;
1019 case TLS_ST_SR_CHANGE:
1020 return CCS_MAX_LENGTH;
1022 case TLS_ST_SR_FINISHED:
1023 return FINISHED_MAX_LENGTH;
1025 case TLS_ST_SR_KEY_UPDATE:
1026 return KEY_UPDATE_MAX_LENGTH;
1031 * Process a message that the server has received from the client.
1033 MSG_PROCESS_RETURN ossl_statem_server_process_message(SSL *s, PACKET *pkt)
1035 OSSL_STATEM *st = &s->statem;
1037 switch (st->hand_state) {
1039 /* Shouldn't happen */
1040 return MSG_PROCESS_ERROR;
1042 case TLS_ST_SR_CLNT_HELLO:
1043 return tls_process_client_hello(s, pkt);
1045 case TLS_ST_SR_CERT:
1046 return tls_process_client_certificate(s, pkt);
1048 case TLS_ST_SR_KEY_EXCH:
1049 return tls_process_client_key_exchange(s, pkt);
1051 case TLS_ST_SR_CERT_VRFY:
1052 return tls_process_cert_verify(s, pkt);
1054 #ifndef OPENSSL_NO_NEXTPROTONEG
1055 case TLS_ST_SR_NEXT_PROTO:
1056 return tls_process_next_proto(s, pkt);
1059 case TLS_ST_SR_CHANGE:
1060 return tls_process_change_cipher_spec(s, pkt);
1062 case TLS_ST_SR_FINISHED:
1063 return tls_process_finished(s, pkt);
1065 case TLS_ST_SR_KEY_UPDATE:
1066 return tls_process_key_update(s, pkt);
1072 * Perform any further processing required following the receipt of a message
1075 WORK_STATE ossl_statem_server_post_process_message(SSL *s, WORK_STATE wst)
1077 OSSL_STATEM *st = &s->statem;
1079 switch (st->hand_state) {
1081 /* Shouldn't happen */
1084 case TLS_ST_SR_CLNT_HELLO:
1085 return tls_post_process_client_hello(s, wst);
1087 case TLS_ST_SR_KEY_EXCH:
1088 return tls_post_process_client_key_exchange(s, wst);
1090 case TLS_ST_SR_CERT_VRFY:
1091 #ifndef OPENSSL_NO_SCTP
1092 if ( /* Is this SCTP? */
1093 BIO_dgram_is_sctp(SSL_get_wbio(s))
1094 /* Are we renegotiating? */
1095 && s->renegotiate && BIO_dgram_sctp_msg_waiting(SSL_get_rbio(s))) {
1096 s->s3->in_read_app_data = 2;
1097 s->rwstate = SSL_READING;
1098 BIO_clear_retry_flags(SSL_get_rbio(s));
1099 BIO_set_retry_read(SSL_get_rbio(s));
1100 ossl_statem_set_sctp_read_sock(s, 1);
1103 ossl_statem_set_sctp_read_sock(s, 0);
1106 return WORK_FINISHED_CONTINUE;
1108 return WORK_FINISHED_CONTINUE;
1111 int ossl_statem_finish_early_data(SSL *s)
1113 if (!s->method->ssl3_enc->change_cipher_state(s,
1114 SSL3_CC_HANDSHAKE | SSL3_CHANGE_CIPHER_SERVER_READ))
1120 #ifndef OPENSSL_NO_SRP
1121 static int ssl_check_srp_ext_ClientHello(SSL *s, int *al)
1123 int ret = SSL_ERROR_NONE;
1125 *al = SSL_AD_UNRECOGNIZED_NAME;
1127 if ((s->s3->tmp.new_cipher->algorithm_mkey & SSL_kSRP) &&
1128 (s->srp_ctx.TLS_ext_srp_username_callback != NULL)) {
1129 if (s->srp_ctx.login == NULL) {
1131 * RFC 5054 says SHOULD reject, we do so if There is no srp
1134 ret = SSL3_AL_FATAL;
1135 *al = SSL_AD_UNKNOWN_PSK_IDENTITY;
1137 ret = SSL_srp_server_param_with_username(s, al);
1144 int dtls_raw_hello_verify_request(WPACKET *pkt, unsigned char *cookie,
1147 /* Always use DTLS 1.0 version: see RFC 6347 */
1148 if (!WPACKET_put_bytes_u16(pkt, DTLS1_VERSION)
1149 || !WPACKET_sub_memcpy_u8(pkt, cookie, cookie_len))
1155 int dtls_construct_hello_verify_request(SSL *s, WPACKET *pkt)
1157 unsigned int cookie_leni;
1158 if (s->ctx->app_gen_cookie_cb == NULL ||
1159 s->ctx->app_gen_cookie_cb(s, s->d1->cookie,
1160 &cookie_leni) == 0 ||
1161 cookie_leni > 255) {
1162 SSLerr(SSL_F_DTLS_CONSTRUCT_HELLO_VERIFY_REQUEST,
1163 SSL_R_COOKIE_GEN_CALLBACK_FAILURE);
1166 s->d1->cookie_len = cookie_leni;
1168 if (!dtls_raw_hello_verify_request(pkt, s->d1->cookie,
1169 s->d1->cookie_len)) {
1170 SSLerr(SSL_F_DTLS_CONSTRUCT_HELLO_VERIFY_REQUEST, ERR_R_INTERNAL_ERROR);
1177 #ifndef OPENSSL_NO_EC
1179 * ssl_check_for_safari attempts to fingerprint Safari using OS X
1180 * SecureTransport using the TLS extension block in |hello|.
1181 * Safari, since 10.6, sends exactly these extensions, in this order:
1186 * We wish to fingerprint Safari because they broke ECDHE-ECDSA support in 10.8,
1187 * but they advertise support. So enabling ECDHE-ECDSA ciphers breaks them.
1188 * Sadly we cannot differentiate 10.6, 10.7 and 10.8.4 (which work), from
1189 * 10.8..10.8.3 (which don't work).
1191 static void ssl_check_for_safari(SSL *s, const CLIENTHELLO_MSG *hello)
1193 static const unsigned char kSafariExtensionsBlock[] = {
1194 0x00, 0x0a, /* elliptic_curves extension */
1195 0x00, 0x08, /* 8 bytes */
1196 0x00, 0x06, /* 6 bytes of curve ids */
1197 0x00, 0x17, /* P-256 */
1198 0x00, 0x18, /* P-384 */
1199 0x00, 0x19, /* P-521 */
1201 0x00, 0x0b, /* ec_point_formats */
1202 0x00, 0x02, /* 2 bytes */
1203 0x01, /* 1 point format */
1204 0x00, /* uncompressed */
1205 /* The following is only present in TLS 1.2 */
1206 0x00, 0x0d, /* signature_algorithms */
1207 0x00, 0x0c, /* 12 bytes */
1208 0x00, 0x0a, /* 10 bytes */
1209 0x05, 0x01, /* SHA-384/RSA */
1210 0x04, 0x01, /* SHA-256/RSA */
1211 0x02, 0x01, /* SHA-1/RSA */
1212 0x04, 0x03, /* SHA-256/ECDSA */
1213 0x02, 0x03, /* SHA-1/ECDSA */
1215 /* Length of the common prefix (first two extensions). */
1216 static const size_t kSafariCommonExtensionsLength = 18;
1221 tmppkt = hello->extensions;
1223 if (!PACKET_forward(&tmppkt, 2)
1224 || !PACKET_get_net_2(&tmppkt, &type)
1225 || !PACKET_get_length_prefixed_2(&tmppkt, &sni)) {
1229 if (type != TLSEXT_TYPE_server_name)
1232 ext_len = TLS1_get_client_version(s) >= TLS1_2_VERSION ?
1233 sizeof(kSafariExtensionsBlock) : kSafariCommonExtensionsLength;
1235 s->s3->is_probably_safari = PACKET_equal(&tmppkt, kSafariExtensionsBlock,
1238 #endif /* !OPENSSL_NO_EC */
1240 MSG_PROCESS_RETURN tls_process_client_hello(SSL *s, PACKET *pkt)
1242 int al = SSL_AD_INTERNAL_ERROR;
1243 /* |cookie| will only be initialized for DTLS. */
1244 PACKET session_id, compression, extensions, cookie;
1245 static const unsigned char null_compression = 0;
1246 CLIENTHELLO_MSG *clienthello;
1248 clienthello = OPENSSL_zalloc(sizeof(*clienthello));
1249 if (clienthello == NULL) {
1250 SSLerr(SSL_F_TLS_PROCESS_CLIENT_HELLO, ERR_R_INTERNAL_ERROR);
1253 /* Check if this is actually an unexpected renegotiation ClientHello */
1254 if (s->renegotiate == 0 && !SSL_IS_FIRST_HANDSHAKE(s)) {
1260 * First, parse the raw ClientHello data into the CLIENTHELLO_MSG structure.
1262 clienthello->isv2 = RECORD_LAYER_is_sslv2_record(&s->rlayer);
1263 PACKET_null_init(&cookie);
1265 if (clienthello->isv2) {
1268 if (!SSL_IS_FIRST_HANDSHAKE(s) || s->hello_retry_request) {
1269 al = SSL_AD_HANDSHAKE_FAILURE;
1270 SSLerr(SSL_F_TLS_PROCESS_CLIENT_HELLO, SSL_R_UNEXPECTED_MESSAGE);
1275 * An SSLv3/TLSv1 backwards-compatible CLIENT-HELLO in an SSLv2
1276 * header is sent directly on the wire, not wrapped as a TLS
1277 * record. Our record layer just processes the message length and passes
1278 * the rest right through. Its format is:
1280 * 0-1 msg_length - decoded by the record layer
1281 * 2 msg_type - s->init_msg points here
1283 * 5-6 cipher_spec_length
1284 * 7-8 session_id_length
1285 * 9-10 challenge_length
1289 if (!PACKET_get_1(pkt, &mt)
1290 || mt != SSL2_MT_CLIENT_HELLO) {
1292 * Should never happen. We should have tested this in the record
1293 * layer in order to have determined that this is a SSLv2 record
1294 * in the first place
1296 SSLerr(SSL_F_TLS_PROCESS_CLIENT_HELLO, ERR_R_INTERNAL_ERROR);
1301 if (!PACKET_get_net_2(pkt, &clienthello->legacy_version)) {
1302 al = SSL_AD_DECODE_ERROR;
1303 SSLerr(SSL_F_TLS_PROCESS_CLIENT_HELLO, SSL_R_LENGTH_TOO_SHORT);
1307 /* Parse the message and load client random. */
1308 if (clienthello->isv2) {
1310 * Handle an SSLv2 backwards compatible ClientHello
1311 * Note, this is only for SSLv3+ using the backward compatible format.
1312 * Real SSLv2 is not supported, and is rejected below.
1314 unsigned int ciphersuite_len, session_id_len, challenge_len;
1317 if (!PACKET_get_net_2(pkt, &ciphersuite_len)
1318 || !PACKET_get_net_2(pkt, &session_id_len)
1319 || !PACKET_get_net_2(pkt, &challenge_len)) {
1320 SSLerr(SSL_F_TLS_PROCESS_CLIENT_HELLO,
1321 SSL_R_RECORD_LENGTH_MISMATCH);
1322 al = SSL_AD_DECODE_ERROR;
1326 if (session_id_len > SSL_MAX_SSL_SESSION_ID_LENGTH) {
1327 al = SSL_AD_DECODE_ERROR;
1328 SSLerr(SSL_F_TLS_PROCESS_CLIENT_HELLO, SSL_R_LENGTH_MISMATCH);
1332 if (!PACKET_get_sub_packet(pkt, &clienthello->ciphersuites,
1334 || !PACKET_copy_bytes(pkt, clienthello->session_id, session_id_len)
1335 || !PACKET_get_sub_packet(pkt, &challenge, challenge_len)
1336 /* No extensions. */
1337 || PACKET_remaining(pkt) != 0) {
1338 SSLerr(SSL_F_TLS_PROCESS_CLIENT_HELLO,
1339 SSL_R_RECORD_LENGTH_MISMATCH);
1340 al = SSL_AD_DECODE_ERROR;
1343 clienthello->session_id_len = session_id_len;
1345 /* Load the client random and compression list. We use SSL3_RANDOM_SIZE
1346 * here rather than sizeof(clienthello->random) because that is the limit
1347 * for SSLv3 and it is fixed. It won't change even if
1348 * sizeof(clienthello->random) does.
1350 challenge_len = challenge_len > SSL3_RANDOM_SIZE
1351 ? SSL3_RANDOM_SIZE : challenge_len;
1352 memset(clienthello->random, 0, SSL3_RANDOM_SIZE);
1353 if (!PACKET_copy_bytes(&challenge,
1354 clienthello->random + SSL3_RANDOM_SIZE -
1355 challenge_len, challenge_len)
1356 /* Advertise only null compression. */
1357 || !PACKET_buf_init(&compression, &null_compression, 1)) {
1358 SSLerr(SSL_F_TLS_PROCESS_CLIENT_HELLO, ERR_R_INTERNAL_ERROR);
1359 al = SSL_AD_INTERNAL_ERROR;
1363 PACKET_null_init(&clienthello->extensions);
1365 /* Regular ClientHello. */
1366 if (!PACKET_copy_bytes(pkt, clienthello->random, SSL3_RANDOM_SIZE)
1367 || !PACKET_get_length_prefixed_1(pkt, &session_id)
1368 || !PACKET_copy_all(&session_id, clienthello->session_id,
1369 SSL_MAX_SSL_SESSION_ID_LENGTH,
1370 &clienthello->session_id_len)) {
1371 al = SSL_AD_DECODE_ERROR;
1372 SSLerr(SSL_F_TLS_PROCESS_CLIENT_HELLO, SSL_R_LENGTH_MISMATCH);
1376 if (SSL_IS_DTLS(s)) {
1377 if (!PACKET_get_length_prefixed_1(pkt, &cookie)) {
1378 al = SSL_AD_DECODE_ERROR;
1379 SSLerr(SSL_F_TLS_PROCESS_CLIENT_HELLO, SSL_R_LENGTH_MISMATCH);
1382 if (!PACKET_copy_all(&cookie, clienthello->dtls_cookie,
1383 DTLS1_COOKIE_LENGTH,
1384 &clienthello->dtls_cookie_len)) {
1385 al = SSL_AD_DECODE_ERROR;
1386 SSLerr(SSL_F_TLS_PROCESS_CLIENT_HELLO, SSL_R_LENGTH_MISMATCH);
1390 * If we require cookies and this ClientHello doesn't contain one,
1391 * just return since we do not want to allocate any memory yet.
1392 * So check cookie length...
1394 if (SSL_get_options(s) & SSL_OP_COOKIE_EXCHANGE) {
1395 if (clienthello->dtls_cookie_len == 0)
1400 if (!PACKET_get_length_prefixed_2(pkt, &clienthello->ciphersuites)) {
1401 al = SSL_AD_DECODE_ERROR;
1402 SSLerr(SSL_F_TLS_PROCESS_CLIENT_HELLO, SSL_R_LENGTH_MISMATCH);
1406 if (!PACKET_get_length_prefixed_1(pkt, &compression)) {
1407 al = SSL_AD_DECODE_ERROR;
1408 SSLerr(SSL_F_TLS_PROCESS_CLIENT_HELLO, SSL_R_LENGTH_MISMATCH);
1412 /* Could be empty. */
1413 if (PACKET_remaining(pkt) == 0) {
1414 PACKET_null_init(&clienthello->extensions);
1416 if (!PACKET_get_length_prefixed_2(pkt, &clienthello->extensions)) {
1417 al = SSL_AD_DECODE_ERROR;
1418 SSLerr(SSL_F_TLS_PROCESS_CLIENT_HELLO, SSL_R_LENGTH_MISMATCH);
1424 if (!PACKET_copy_all(&compression, clienthello->compressions,
1425 MAX_COMPRESSIONS_SIZE,
1426 &clienthello->compressions_len)) {
1427 al = SSL_AD_DECODE_ERROR;
1428 SSLerr(SSL_F_TLS_PROCESS_CLIENT_HELLO, SSL_R_LENGTH_MISMATCH);
1432 /* Preserve the raw extensions PACKET for later use */
1433 extensions = clienthello->extensions;
1434 if (!tls_collect_extensions(s, &extensions, EXT_CLIENT_HELLO,
1435 &clienthello->pre_proc_exts, &al,
1436 &clienthello->pre_proc_exts_len)) {
1437 /* SSLerr already been called */
1440 s->clienthello = clienthello;
1442 return MSG_PROCESS_CONTINUE_PROCESSING;
1444 ssl3_send_alert(s, SSL3_AL_FATAL, al);
1446 ossl_statem_set_error(s);
1448 OPENSSL_free(clienthello->pre_proc_exts);
1449 OPENSSL_free(clienthello);
1451 return MSG_PROCESS_ERROR;
1454 static int tls_early_post_process_client_hello(SSL *s, int *al)
1461 #ifndef OPENSSL_NO_COMP
1462 SSL_COMP *comp = NULL;
1464 const SSL_CIPHER *c;
1465 STACK_OF(SSL_CIPHER) *ciphers = NULL;
1466 STACK_OF(SSL_CIPHER) *scsvs = NULL;
1467 CLIENTHELLO_MSG *clienthello = s->clienthello;
1469 *al = SSL_AD_INTERNAL_ERROR;
1470 /* Finished parsing the ClientHello, now we can start processing it */
1471 /* Give the early callback a crack at things */
1472 if (s->ctx->early_cb != NULL) {
1474 /* A failure in the early callback terminates the connection. */
1475 code = s->ctx->early_cb(s, al, s->ctx->early_cb_arg);
1479 s->rwstate = SSL_EARLY_WORK;
1484 /* Set up the client_random */
1485 memcpy(s->s3->client_random, clienthello->random, SSL3_RANDOM_SIZE);
1487 /* Choose the version */
1489 if (clienthello->isv2) {
1490 if (clienthello->legacy_version == SSL2_VERSION
1491 || (clienthello->legacy_version & 0xff00)
1492 != (SSL3_VERSION_MAJOR << 8)) {
1494 * This is real SSLv2 or something complete unknown. We don't
1497 SSLerr(SSL_F_TLS_EARLY_POST_PROCESS_CLIENT_HELLO, SSL_R_UNKNOWN_PROTOCOL);
1501 s->client_version = clienthello->legacy_version;
1504 * Do SSL/TLS version negotiation if applicable. For DTLS we just check
1505 * versions are potentially compatible. Version negotiation comes later.
1507 if (!SSL_IS_DTLS(s)) {
1508 protverr = ssl_choose_server_version(s, clienthello);
1509 } else if (s->method->version != DTLS_ANY_VERSION &&
1510 DTLS_VERSION_LT((int)clienthello->legacy_version, s->version)) {
1511 protverr = SSL_R_VERSION_TOO_LOW;
1517 SSLerr(SSL_F_TLS_EARLY_POST_PROCESS_CLIENT_HELLO, protverr);
1518 if (SSL_IS_FIRST_HANDSHAKE(s)) {
1519 /* like ssl3_get_record, send alert using remote version number */
1520 s->version = s->client_version = clienthello->legacy_version;
1522 *al = SSL_AD_PROTOCOL_VERSION;
1526 if (SSL_IS_DTLS(s)) {
1527 /* Empty cookie was already handled above by returning early. */
1528 if (SSL_get_options(s) & SSL_OP_COOKIE_EXCHANGE) {
1529 if (s->ctx->app_verify_cookie_cb != NULL) {
1530 if (s->ctx->app_verify_cookie_cb(s, clienthello->dtls_cookie,
1531 clienthello->dtls_cookie_len) == 0) {
1532 *al = SSL_AD_HANDSHAKE_FAILURE;
1533 SSLerr(SSL_F_TLS_EARLY_POST_PROCESS_CLIENT_HELLO,
1534 SSL_R_COOKIE_MISMATCH);
1536 /* else cookie verification succeeded */
1538 /* default verification */
1539 } else if (s->d1->cookie_len != clienthello->dtls_cookie_len
1540 || memcmp(clienthello->dtls_cookie, s->d1->cookie,
1541 s->d1->cookie_len) != 0) {
1542 *al = SSL_AD_HANDSHAKE_FAILURE;
1543 SSLerr(SSL_F_TLS_EARLY_POST_PROCESS_CLIENT_HELLO, SSL_R_COOKIE_MISMATCH);
1546 s->d1->cookie_verified = 1;
1548 if (s->method->version == DTLS_ANY_VERSION) {
1549 protverr = ssl_choose_server_version(s, clienthello);
1550 if (protverr != 0) {
1551 SSLerr(SSL_F_TLS_EARLY_POST_PROCESS_CLIENT_HELLO, protverr);
1552 s->version = s->client_version;
1553 *al = SSL_AD_PROTOCOL_VERSION;
1561 /* We need to do this before getting the session */
1562 if (!tls_parse_extension(s, TLSEXT_IDX_extended_master_secret,
1564 clienthello->pre_proc_exts, NULL, 0, al)) {
1565 SSLerr(SSL_F_TLS_EARLY_POST_PROCESS_CLIENT_HELLO, SSL_R_CLIENTHELLO_TLSEXT);
1570 * We don't allow resumption in a backwards compatible ClientHello.
1571 * TODO(openssl-team): in TLS1.1+, session_id MUST be empty.
1573 * Versions before 0.9.7 always allow clients to resume sessions in
1574 * renegotiation. 0.9.7 and later allow this by default, but optionally
1575 * ignore resumption requests with flag
1576 * SSL_OP_NO_SESSION_RESUMPTION_ON_RENEGOTIATION (it's a new flag rather
1577 * than a change to default behavior so that applications relying on
1578 * this for security won't even compile against older library versions).
1579 * 1.0.1 and later also have a function SSL_renegotiate_abbreviated() to
1580 * request renegotiation but not a new session (s->new_session remains
1581 * unset): for servers, this essentially just means that the
1582 * SSL_OP_NO_SESSION_RESUMPTION_ON_RENEGOTIATION setting will be
1585 if (clienthello->isv2 ||
1587 (s->options & SSL_OP_NO_SESSION_RESUMPTION_ON_RENEGOTIATION))) {
1588 if (!ssl_get_new_session(s, 1))
1591 i = ssl_get_prev_session(s, clienthello, al);
1593 /* previous session */
1595 } else if (i == -1) {
1599 if (!ssl_get_new_session(s, 1))
1604 if (!ssl_cache_cipherlist(s, &clienthello->ciphersuites,
1605 clienthello->isv2, al) ||
1606 !bytes_to_cipher_list(s, &clienthello->ciphersuites, &ciphers, &scsvs,
1607 clienthello->isv2, al)) {
1611 s->s3->send_connection_binding = 0;
1612 /* Check what signalling cipher-suite values were received. */
1613 if (scsvs != NULL) {
1614 for(i = 0; i < sk_SSL_CIPHER_num(scsvs); i++) {
1615 c = sk_SSL_CIPHER_value(scsvs, i);
1616 if (SSL_CIPHER_get_id(c) == SSL3_CK_SCSV) {
1617 if (s->renegotiate) {
1618 /* SCSV is fatal if renegotiating */
1619 SSLerr(SSL_F_TLS_EARLY_POST_PROCESS_CLIENT_HELLO,
1620 SSL_R_SCSV_RECEIVED_WHEN_RENEGOTIATING);
1621 *al = SSL_AD_HANDSHAKE_FAILURE;
1624 s->s3->send_connection_binding = 1;
1625 } else if (SSL_CIPHER_get_id(c) == SSL3_CK_FALLBACK_SCSV &&
1626 !ssl_check_version_downgrade(s)) {
1628 * This SCSV indicates that the client previously tried
1629 * a higher version. We should fail if the current version
1630 * is an unexpected downgrade, as that indicates that the first
1631 * connection may have been tampered with in order to trigger
1632 * an insecure downgrade.
1634 SSLerr(SSL_F_TLS_EARLY_POST_PROCESS_CLIENT_HELLO,
1635 SSL_R_INAPPROPRIATE_FALLBACK);
1636 *al = SSL_AD_INAPPROPRIATE_FALLBACK;
1642 /* If it is a hit, check that the cipher is in the list */
1645 id = s->session->cipher->id;
1648 fprintf(stderr, "client sent %d ciphers\n", sk_SSL_CIPHER_num(ciphers));
1650 for (i = 0; i < sk_SSL_CIPHER_num(ciphers); i++) {
1651 c = sk_SSL_CIPHER_value(ciphers, i);
1653 fprintf(stderr, "client [%2d of %2d]:%s\n",
1654 i, sk_SSL_CIPHER_num(ciphers), SSL_CIPHER_get_name(c));
1663 * we need to have the cipher in the cipher list if we are asked
1666 *al = SSL_AD_ILLEGAL_PARAMETER;
1667 SSLerr(SSL_F_TLS_EARLY_POST_PROCESS_CLIENT_HELLO,
1668 SSL_R_REQUIRED_CIPHER_MISSING);
1673 for (loop = 0; loop < clienthello->compressions_len; loop++) {
1674 if (clienthello->compressions[loop] == 0)
1678 if (loop >= clienthello->compressions_len) {
1680 *al = SSL_AD_DECODE_ERROR;
1681 SSLerr(SSL_F_TLS_EARLY_POST_PROCESS_CLIENT_HELLO, SSL_R_NO_COMPRESSION_SPECIFIED);
1685 #ifndef OPENSSL_NO_EC
1686 if (s->options & SSL_OP_SAFARI_ECDHE_ECDSA_BUG)
1687 ssl_check_for_safari(s, clienthello);
1688 #endif /* !OPENSSL_NO_EC */
1690 /* TLS extensions */
1691 if (!tls_parse_all_extensions(s, EXT_CLIENT_HELLO,
1692 clienthello->pre_proc_exts, NULL, 0, al)) {
1693 SSLerr(SSL_F_TLS_EARLY_POST_PROCESS_CLIENT_HELLO, SSL_R_PARSE_TLSEXT);
1698 * Check if we want to use external pre-shared secret for this handshake
1699 * for not reused session only. We need to generate server_random before
1700 * calling tls_session_secret_cb in order to allow SessionTicket
1701 * processing to use it in key derivation.
1705 pos = s->s3->server_random;
1706 if (ssl_fill_hello_random(s, 1, pos, SSL3_RANDOM_SIZE) <= 0) {
1711 if (!s->hit && s->version >= TLS1_VERSION && s->ext.session_secret_cb) {
1712 const SSL_CIPHER *pref_cipher = NULL;
1714 * s->session->master_key_length is a size_t, but this is an int for
1715 * backwards compat reasons
1717 int master_key_length;
1719 master_key_length = sizeof(s->session->master_key);
1720 if (s->ext.session_secret_cb(s, s->session->master_key,
1721 &master_key_length, ciphers,
1723 s->ext.session_secret_cb_arg)
1724 && master_key_length > 0) {
1725 s->session->master_key_length = master_key_length;
1727 s->session->ciphers = ciphers;
1728 s->session->verify_result = X509_V_OK;
1732 /* check if some cipher was preferred by call back */
1733 if (pref_cipher == NULL)
1734 pref_cipher = ssl3_choose_cipher(s, s->session->ciphers,
1735 SSL_get_ciphers(s));
1736 if (pref_cipher == NULL) {
1737 *al = SSL_AD_HANDSHAKE_FAILURE;
1738 SSLerr(SSL_F_TLS_EARLY_POST_PROCESS_CLIENT_HELLO, SSL_R_NO_SHARED_CIPHER);
1742 s->session->cipher = pref_cipher;
1743 sk_SSL_CIPHER_free(s->cipher_list);
1744 s->cipher_list = sk_SSL_CIPHER_dup(s->session->ciphers);
1745 sk_SSL_CIPHER_free(s->cipher_list_by_id);
1746 s->cipher_list_by_id = sk_SSL_CIPHER_dup(s->session->ciphers);
1751 * Worst case, we will use the NULL compression, but if we have other
1752 * options, we will now look for them. We have complen-1 compression
1753 * algorithms from the client, starting at q.
1755 s->s3->tmp.new_compression = NULL;
1756 #ifndef OPENSSL_NO_COMP
1757 /* This only happens if we have a cache hit */
1758 if (s->session->compress_meth != 0 && !SSL_IS_TLS13(s)) {
1759 int m, comp_id = s->session->compress_meth;
1761 /* Perform sanity checks on resumed compression algorithm */
1762 /* Can't disable compression */
1763 if (!ssl_allow_compression(s)) {
1764 SSLerr(SSL_F_TLS_EARLY_POST_PROCESS_CLIENT_HELLO,
1765 SSL_R_INCONSISTENT_COMPRESSION);
1768 /* Look for resumed compression method */
1769 for (m = 0; m < sk_SSL_COMP_num(s->ctx->comp_methods); m++) {
1770 comp = sk_SSL_COMP_value(s->ctx->comp_methods, m);
1771 if (comp_id == comp->id) {
1772 s->s3->tmp.new_compression = comp;
1776 if (s->s3->tmp.new_compression == NULL) {
1777 SSLerr(SSL_F_TLS_EARLY_POST_PROCESS_CLIENT_HELLO,
1778 SSL_R_INVALID_COMPRESSION_ALGORITHM);
1781 /* Look for resumed method in compression list */
1782 for (k = 0; k < clienthello->compressions_len; k++) {
1783 if (clienthello->compressions[k] == comp_id)
1786 if (k >= clienthello->compressions_len) {
1787 *al = SSL_AD_ILLEGAL_PARAMETER;
1788 SSLerr(SSL_F_TLS_EARLY_POST_PROCESS_CLIENT_HELLO,
1789 SSL_R_REQUIRED_COMPRESSION_ALGORITHM_MISSING);
1792 } else if (s->hit) {
1794 } else if (ssl_allow_compression(s) && s->ctx->comp_methods
1795 && !SSL_IS_TLS13(s)) {
1796 /* See if we have a match */
1797 int m, nn, v, done = 0;
1800 nn = sk_SSL_COMP_num(s->ctx->comp_methods);
1801 for (m = 0; m < nn; m++) {
1802 comp = sk_SSL_COMP_value(s->ctx->comp_methods, m);
1804 for (o = 0; o < clienthello->compressions_len; o++) {
1805 if (v == clienthello->compressions[o]) {
1814 s->s3->tmp.new_compression = comp;
1820 * If compression is disabled we'd better not try to resume a session
1821 * using compression.
1823 if (s->session->compress_meth != 0) {
1824 SSLerr(SSL_F_TLS_EARLY_POST_PROCESS_CLIENT_HELLO, SSL_R_INCONSISTENT_COMPRESSION);
1830 * Given s->session->ciphers and SSL_get_ciphers, we must pick a cipher
1834 #ifdef OPENSSL_NO_COMP
1835 s->session->compress_meth = 0;
1837 s->session->compress_meth = (comp == NULL) ? 0 : comp->id;
1839 sk_SSL_CIPHER_free(s->session->ciphers);
1840 s->session->ciphers = ciphers;
1841 if (ciphers == NULL) {
1842 *al = SSL_AD_INTERNAL_ERROR;
1843 SSLerr(SSL_F_TLS_EARLY_POST_PROCESS_CLIENT_HELLO, ERR_R_INTERNAL_ERROR);
1847 if (!tls1_set_server_sigalgs(s)) {
1848 SSLerr(SSL_F_TLS_EARLY_POST_PROCESS_CLIENT_HELLO, SSL_R_CLIENTHELLO_TLSEXT);
1853 sk_SSL_CIPHER_free(ciphers);
1854 sk_SSL_CIPHER_free(scsvs);
1855 OPENSSL_free(clienthello->pre_proc_exts);
1856 OPENSSL_free(s->clienthello);
1857 s->clienthello = NULL;
1860 ossl_statem_set_error(s);
1862 sk_SSL_CIPHER_free(ciphers);
1863 sk_SSL_CIPHER_free(scsvs);
1864 OPENSSL_free(clienthello->pre_proc_exts);
1865 OPENSSL_free(s->clienthello);
1866 s->clienthello = NULL;
1872 * Call the status request callback if needed. Upon success, returns 1.
1873 * Upon failure, returns 0 and sets |*al| to the appropriate fatal alert.
1875 static int tls_handle_status_request(SSL *s, int *al)
1877 s->ext.status_expected = 0;
1880 * If status request then ask callback what to do. Note: this must be
1881 * called after servername callbacks in case the certificate has changed,
1882 * and must be called after the cipher has been chosen because this may
1883 * influence which certificate is sent
1885 if (s->ext.status_type != TLSEXT_STATUSTYPE_nothing && s->ctx != NULL
1886 && s->ctx->ext.status_cb != NULL) {
1889 /* If no certificate can't return certificate status */
1890 if (s->s3->tmp.cert != NULL) {
1892 * Set current certificate to one we will use so SSL_get_certificate
1893 * et al can pick it up.
1895 s->cert->key = s->s3->tmp.cert;
1896 ret = s->ctx->ext.status_cb(s, s->ctx->ext.status_arg);
1898 /* We don't want to send a status request response */
1899 case SSL_TLSEXT_ERR_NOACK:
1900 s->ext.status_expected = 0;
1902 /* status request response should be sent */
1903 case SSL_TLSEXT_ERR_OK:
1904 if (s->ext.ocsp.resp)
1905 s->ext.status_expected = 1;
1907 /* something bad happened */
1908 case SSL_TLSEXT_ERR_ALERT_FATAL:
1910 *al = SSL_AD_INTERNAL_ERROR;
1919 WORK_STATE tls_post_process_client_hello(SSL *s, WORK_STATE wst)
1921 int al = SSL_AD_HANDSHAKE_FAILURE;
1922 const SSL_CIPHER *cipher;
1924 if (wst == WORK_MORE_A) {
1925 int rv = tls_early_post_process_client_hello(s, &al);
1927 /* SSLErr() was already called */
1934 if (wst == WORK_MORE_B) {
1936 /* Let cert callback update server certificates if required */
1937 if (s->cert->cert_cb) {
1938 int rv = s->cert->cert_cb(s, s->cert->cert_cb_arg);
1940 al = SSL_AD_INTERNAL_ERROR;
1941 SSLerr(SSL_F_TLS_POST_PROCESS_CLIENT_HELLO,
1942 SSL_R_CERT_CB_ERROR);
1946 s->rwstate = SSL_X509_LOOKUP;
1949 s->rwstate = SSL_NOTHING;
1952 ssl3_choose_cipher(s, s->session->ciphers, SSL_get_ciphers(s));
1954 if (cipher == NULL) {
1955 SSLerr(SSL_F_TLS_POST_PROCESS_CLIENT_HELLO,
1956 SSL_R_NO_SHARED_CIPHER);
1959 s->s3->tmp.new_cipher = cipher;
1960 if (!tls_choose_sigalg(s, &al))
1962 /* check whether we should disable session resumption */
1963 if (s->not_resumable_session_cb != NULL)
1964 s->session->not_resumable =
1965 s->not_resumable_session_cb(s, ((cipher->algorithm_mkey
1966 & (SSL_kDHE | SSL_kECDHE))
1968 if (s->session->not_resumable)
1969 /* do not send a session ticket */
1970 s->ext.ticket_expected = 0;
1972 /* Session-id reuse */
1973 s->s3->tmp.new_cipher = s->session->cipher;
1977 * we now have the following setup.
1979 * cipher_list - our preferred list of ciphers
1980 * ciphers - the clients preferred list of ciphers
1981 * compression - basically ignored right now
1982 * ssl version is set - sslv3
1983 * s->session - The ssl session has been setup.
1984 * s->hit - session reuse flag
1985 * s->s3->tmp.new_cipher- the new cipher to use.
1989 * Call status_request callback if needed. Has to be done after the
1990 * certificate callbacks etc above.
1992 if (!tls_handle_status_request(s, &al)) {
1993 SSLerr(SSL_F_TLS_POST_PROCESS_CLIENT_HELLO,
1994 SSL_R_CLIENTHELLO_TLSEXT);
2000 #ifndef OPENSSL_NO_SRP
2001 if (wst == WORK_MORE_C) {
2003 if ((ret = ssl_check_srp_ext_ClientHello(s, &al)) < 0) {
2005 * callback indicates further work to be done
2007 s->rwstate = SSL_X509_LOOKUP;
2010 if (ret != SSL_ERROR_NONE) {
2012 * This is not really an error but the only means to for
2013 * a client to detect whether srp is supported.
2015 if (al != TLS1_AD_UNKNOWN_PSK_IDENTITY)
2016 SSLerr(SSL_F_TLS_POST_PROCESS_CLIENT_HELLO,
2017 SSL_R_CLIENTHELLO_TLSEXT);
2019 SSLerr(SSL_F_TLS_POST_PROCESS_CLIENT_HELLO,
2020 SSL_R_PSK_IDENTITY_NOT_FOUND);
2026 return WORK_FINISHED_STOP;
2028 ssl3_send_alert(s, SSL3_AL_FATAL, al);
2029 ossl_statem_set_error(s);
2033 int tls_construct_server_hello(SSL *s, WPACKET *pkt)
2035 int compm, al = SSL_AD_INTERNAL_ERROR;
2039 /* TODO(TLS1.3): Remove the DRAFT conditional before release */
2040 version = SSL_IS_TLS13(s) ? TLS1_3_VERSION_DRAFT : s->version;
2041 if (!WPACKET_put_bytes_u16(pkt, version)
2043 * Random stuff. Filling of the server_random takes place in
2044 * tls_process_client_hello()
2046 || !WPACKET_memcpy(pkt, s->s3->server_random, SSL3_RANDOM_SIZE)) {
2047 SSLerr(SSL_F_TLS_CONSTRUCT_SERVER_HELLO, ERR_R_INTERNAL_ERROR);
2052 * There are several cases for the session ID to send
2053 * back in the server hello:
2054 * - For session reuse from the session cache,
2055 * we send back the old session ID.
2056 * - If stateless session reuse (using a session ticket)
2057 * is successful, we send back the client's "session ID"
2058 * (which doesn't actually identify the session).
2059 * - If it is a new session, we send back the new
2061 * - However, if we want the new session to be single-use,
2062 * we send back a 0-length session ID.
2063 * s->hit is non-zero in either case of session reuse,
2064 * so the following won't overwrite an ID that we're supposed
2067 if (s->session->not_resumable ||
2068 (!(s->ctx->session_cache_mode & SSL_SESS_CACHE_SERVER)
2070 s->session->session_id_length = 0;
2072 sl = s->session->session_id_length;
2073 if (sl > sizeof(s->session->session_id)) {
2074 SSLerr(SSL_F_TLS_CONSTRUCT_SERVER_HELLO, ERR_R_INTERNAL_ERROR);
2078 /* set up the compression method */
2079 #ifdef OPENSSL_NO_COMP
2082 if (s->s3->tmp.new_compression == NULL)
2085 compm = s->s3->tmp.new_compression->id;
2088 if ((!SSL_IS_TLS13(s)
2089 && !WPACKET_sub_memcpy_u8(pkt, s->session->session_id, sl))
2090 || !s->method->put_cipher_by_char(s->s3->tmp.new_cipher, pkt, &len)
2091 || (!SSL_IS_TLS13(s)
2092 && !WPACKET_put_bytes_u8(pkt, compm))
2093 || !tls_construct_extensions(s, pkt,
2095 ? EXT_TLS1_3_SERVER_HELLO
2096 : EXT_TLS1_2_SERVER_HELLO,
2098 SSLerr(SSL_F_TLS_CONSTRUCT_SERVER_HELLO, ERR_R_INTERNAL_ERROR);
2102 if (!(s->verify_mode & SSL_VERIFY_PEER)
2103 && !ssl3_digest_cached_records(s, 0)) {
2104 al = SSL_AD_INTERNAL_ERROR;
2110 ssl3_send_alert(s, SSL3_AL_FATAL, al);
2114 int tls_construct_server_done(SSL *s, WPACKET *pkt)
2116 if (!s->s3->tmp.cert_request) {
2117 if (!ssl3_digest_cached_records(s, 0)) {
2118 ssl3_send_alert(s, SSL3_AL_FATAL, SSL_AD_INTERNAL_ERROR);
2125 int tls_construct_server_key_exchange(SSL *s, WPACKET *pkt)
2127 #ifndef OPENSSL_NO_DH
2128 EVP_PKEY *pkdh = NULL;
2130 #ifndef OPENSSL_NO_EC
2131 unsigned char *encodedPoint = NULL;
2132 size_t encodedlen = 0;
2135 const SIGALG_LOOKUP *lu = s->s3->tmp.sigalg;
2136 int al = SSL_AD_INTERNAL_ERROR, i;
2139 EVP_MD_CTX *md_ctx = EVP_MD_CTX_new();
2140 EVP_PKEY_CTX *pctx = NULL;
2141 size_t paramlen, paramoffset;
2143 if (!WPACKET_get_total_written(pkt, ¶moffset)) {
2144 SSLerr(SSL_F_TLS_CONSTRUCT_SERVER_KEY_EXCHANGE, ERR_R_INTERNAL_ERROR);
2148 if (md_ctx == NULL) {
2149 SSLerr(SSL_F_TLS_CONSTRUCT_SERVER_KEY_EXCHANGE, ERR_R_MALLOC_FAILURE);
2153 type = s->s3->tmp.new_cipher->algorithm_mkey;
2155 r[0] = r[1] = r[2] = r[3] = NULL;
2156 #ifndef OPENSSL_NO_PSK
2157 /* Plain PSK or RSAPSK nothing to do */
2158 if (type & (SSL_kPSK | SSL_kRSAPSK)) {
2160 #endif /* !OPENSSL_NO_PSK */
2161 #ifndef OPENSSL_NO_DH
2162 if (type & (SSL_kDHE | SSL_kDHEPSK)) {
2163 CERT *cert = s->cert;
2165 EVP_PKEY *pkdhp = NULL;
2168 if (s->cert->dh_tmp_auto) {
2169 DH *dhp = ssl_get_auto_dh(s);
2170 pkdh = EVP_PKEY_new();
2171 if (pkdh == NULL || dhp == NULL) {
2173 SSLerr(SSL_F_TLS_CONSTRUCT_SERVER_KEY_EXCHANGE,
2174 ERR_R_INTERNAL_ERROR);
2177 EVP_PKEY_assign_DH(pkdh, dhp);
2180 pkdhp = cert->dh_tmp;
2182 if ((pkdhp == NULL) && (s->cert->dh_tmp_cb != NULL)) {
2183 DH *dhp = s->cert->dh_tmp_cb(s, 0, 1024);
2184 pkdh = ssl_dh_to_pkey(dhp);
2186 SSLerr(SSL_F_TLS_CONSTRUCT_SERVER_KEY_EXCHANGE,
2187 ERR_R_INTERNAL_ERROR);
2192 if (pkdhp == NULL) {
2193 al = SSL_AD_HANDSHAKE_FAILURE;
2194 SSLerr(SSL_F_TLS_CONSTRUCT_SERVER_KEY_EXCHANGE,
2195 SSL_R_MISSING_TMP_DH_KEY);
2198 if (!ssl_security(s, SSL_SECOP_TMP_DH,
2199 EVP_PKEY_security_bits(pkdhp), 0, pkdhp)) {
2200 al = SSL_AD_HANDSHAKE_FAILURE;
2201 SSLerr(SSL_F_TLS_CONSTRUCT_SERVER_KEY_EXCHANGE,
2202 SSL_R_DH_KEY_TOO_SMALL);
2205 if (s->s3->tmp.pkey != NULL) {
2206 SSLerr(SSL_F_TLS_CONSTRUCT_SERVER_KEY_EXCHANGE,
2207 ERR_R_INTERNAL_ERROR);
2211 s->s3->tmp.pkey = ssl_generate_pkey(pkdhp);
2213 if (s->s3->tmp.pkey == NULL) {
2214 SSLerr(SSL_F_TLS_CONSTRUCT_SERVER_KEY_EXCHANGE, ERR_R_EVP_LIB);
2218 dh = EVP_PKEY_get0_DH(s->s3->tmp.pkey);
2220 EVP_PKEY_free(pkdh);
2223 DH_get0_pqg(dh, &r[0], NULL, &r[1]);
2224 DH_get0_key(dh, &r[2], NULL);
2227 #ifndef OPENSSL_NO_EC
2228 if (type & (SSL_kECDHE | SSL_kECDHEPSK)) {
2231 if (s->s3->tmp.pkey != NULL) {
2232 SSLerr(SSL_F_TLS_CONSTRUCT_SERVER_KEY_EXCHANGE,
2233 ERR_R_INTERNAL_ERROR);
2237 /* Get NID of appropriate shared curve */
2238 nid = tls1_shared_group(s, -2);
2239 curve_id = tls1_ec_nid2curve_id(nid);
2240 if (curve_id == 0) {
2241 SSLerr(SSL_F_TLS_CONSTRUCT_SERVER_KEY_EXCHANGE,
2242 SSL_R_UNSUPPORTED_ELLIPTIC_CURVE);
2245 s->s3->tmp.pkey = ssl_generate_pkey_curve(curve_id);
2246 /* Generate a new key for this curve */
2247 if (s->s3->tmp.pkey == NULL) {
2248 SSLerr(SSL_F_TLS_CONSTRUCT_SERVER_KEY_EXCHANGE, ERR_R_EVP_LIB);
2252 /* Encode the public key. */
2253 encodedlen = EVP_PKEY_get1_tls_encodedpoint(s->s3->tmp.pkey,
2255 if (encodedlen == 0) {
2256 SSLerr(SSL_F_TLS_CONSTRUCT_SERVER_KEY_EXCHANGE, ERR_R_EC_LIB);
2261 * We'll generate the serverKeyExchange message explicitly so we
2262 * can set these to NULLs
2269 #endif /* !OPENSSL_NO_EC */
2270 #ifndef OPENSSL_NO_SRP
2271 if (type & SSL_kSRP) {
2272 if ((s->srp_ctx.N == NULL) ||
2273 (s->srp_ctx.g == NULL) ||
2274 (s->srp_ctx.s == NULL) || (s->srp_ctx.B == NULL)) {
2275 SSLerr(SSL_F_TLS_CONSTRUCT_SERVER_KEY_EXCHANGE,
2276 SSL_R_MISSING_SRP_PARAM);
2279 r[0] = s->srp_ctx.N;
2280 r[1] = s->srp_ctx.g;
2281 r[2] = s->srp_ctx.s;
2282 r[3] = s->srp_ctx.B;
2286 al = SSL_AD_HANDSHAKE_FAILURE;
2287 SSLerr(SSL_F_TLS_CONSTRUCT_SERVER_KEY_EXCHANGE,
2288 SSL_R_UNKNOWN_KEY_EXCHANGE_TYPE);
2292 if (((s->s3->tmp.new_cipher->algorithm_auth & (SSL_aNULL | SSL_aSRP)) != 0)
2293 || ((s->s3->tmp.new_cipher->algorithm_mkey & SSL_PSK)) != 0) {
2295 } else if (lu == NULL) {
2296 al = SSL_AD_DECODE_ERROR;
2300 #ifndef OPENSSL_NO_PSK
2301 if (type & SSL_PSK) {
2302 size_t len = (s->cert->psk_identity_hint == NULL)
2303 ? 0 : strlen(s->cert->psk_identity_hint);
2306 * It should not happen that len > PSK_MAX_IDENTITY_LEN - we already
2307 * checked this when we set the identity hint - but just in case
2309 if (len > PSK_MAX_IDENTITY_LEN
2310 || !WPACKET_sub_memcpy_u16(pkt, s->cert->psk_identity_hint,
2312 SSLerr(SSL_F_TLS_CONSTRUCT_SERVER_KEY_EXCHANGE,
2313 ERR_R_INTERNAL_ERROR);
2319 for (i = 0; i < 4 && r[i] != NULL; i++) {
2320 unsigned char *binval;
2323 #ifndef OPENSSL_NO_SRP
2324 if ((i == 2) && (type & SSL_kSRP)) {
2325 res = WPACKET_start_sub_packet_u8(pkt);
2328 res = WPACKET_start_sub_packet_u16(pkt);
2331 SSLerr(SSL_F_TLS_CONSTRUCT_SERVER_KEY_EXCHANGE,
2332 ERR_R_INTERNAL_ERROR);
2336 #ifndef OPENSSL_NO_DH
2338 * for interoperability with some versions of the Microsoft TLS
2339 * stack, we need to zero pad the DHE pub key to the same length
2342 if ((i == 2) && (type & (SSL_kDHE | SSL_kDHEPSK))) {
2343 size_t len = BN_num_bytes(r[0]) - BN_num_bytes(r[2]);
2346 if (!WPACKET_allocate_bytes(pkt, len, &binval)) {
2347 SSLerr(SSL_F_TLS_CONSTRUCT_SERVER_KEY_EXCHANGE,
2348 ERR_R_INTERNAL_ERROR);
2351 memset(binval, 0, len);
2355 if (!WPACKET_allocate_bytes(pkt, BN_num_bytes(r[i]), &binval)
2356 || !WPACKET_close(pkt)) {
2357 SSLerr(SSL_F_TLS_CONSTRUCT_SERVER_KEY_EXCHANGE,
2358 ERR_R_INTERNAL_ERROR);
2362 BN_bn2bin(r[i], binval);
2365 #ifndef OPENSSL_NO_EC
2366 if (type & (SSL_kECDHE | SSL_kECDHEPSK)) {
2368 * We only support named (not generic) curves. In this situation, the
2369 * ServerKeyExchange message has: [1 byte CurveType], [2 byte CurveName]
2370 * [1 byte length of encoded point], followed by the actual encoded
2373 if (!WPACKET_put_bytes_u8(pkt, NAMED_CURVE_TYPE)
2374 || !WPACKET_put_bytes_u8(pkt, 0)
2375 || !WPACKET_put_bytes_u8(pkt, curve_id)
2376 || !WPACKET_sub_memcpy_u8(pkt, encodedPoint, encodedlen)) {
2377 SSLerr(SSL_F_TLS_CONSTRUCT_SERVER_KEY_EXCHANGE,
2378 ERR_R_INTERNAL_ERROR);
2381 OPENSSL_free(encodedPoint);
2382 encodedPoint = NULL;
2388 EVP_PKEY *pkey = s->s3->tmp.cert->privatekey;
2389 const EVP_MD *md = ssl_md(lu->hash_idx);
2390 unsigned char *sigbytes1, *sigbytes2;
2393 if (pkey == NULL || md == NULL) {
2394 /* Should never happen */
2395 al = SSL_AD_INTERNAL_ERROR;
2396 SSLerr(SSL_F_TLS_CONSTRUCT_SERVER_KEY_EXCHANGE,
2397 ERR_R_INTERNAL_ERROR);
2401 * n is the length of the params, they start at &(d[4]) and p
2402 * points to the space at the end.
2405 /* Get length of the parameters we have written above */
2406 if (!WPACKET_get_length(pkt, ¶mlen)) {
2407 SSLerr(SSL_F_TLS_CONSTRUCT_SERVER_KEY_EXCHANGE,
2408 ERR_R_INTERNAL_ERROR);
2411 /* send signature algorithm */
2412 if (SSL_USE_SIGALGS(s) && !WPACKET_put_bytes_u16(pkt, lu->sigalg))
2415 * Create the signature. We don't know the actual length of the sig
2416 * until after we've created it, so we reserve enough bytes for it
2417 * up front, and then properly allocate them in the WPACKET
2420 siglen = EVP_PKEY_size(pkey);
2421 if (!WPACKET_sub_reserve_bytes_u16(pkt, siglen, &sigbytes1)
2422 || EVP_DigestSignInit(md_ctx, &pctx, md, NULL, pkey) <= 0) {
2423 SSLerr(SSL_F_TLS_CONSTRUCT_SERVER_KEY_EXCHANGE,
2424 ERR_R_INTERNAL_ERROR);
2427 if (lu->sig == EVP_PKEY_RSA_PSS) {
2428 if (EVP_PKEY_CTX_set_rsa_padding(pctx, RSA_PKCS1_PSS_PADDING) <= 0
2429 || EVP_PKEY_CTX_set_rsa_pss_saltlen(pctx, RSA_PSS_SALTLEN_DIGEST) <= 0) {
2430 SSLerr(SSL_F_TLS_CONSTRUCT_SERVER_KEY_EXCHANGE,
2435 if (EVP_DigestSignUpdate(md_ctx, &(s->s3->client_random[0]),
2436 SSL3_RANDOM_SIZE) <= 0
2437 || EVP_DigestSignUpdate(md_ctx, &(s->s3->server_random[0]),
2438 SSL3_RANDOM_SIZE) <= 0
2439 || EVP_DigestSignUpdate(md_ctx,
2440 s->init_buf->data + paramoffset,
2442 || EVP_DigestSignFinal(md_ctx, sigbytes1, &siglen) <= 0
2443 || !WPACKET_sub_allocate_bytes_u16(pkt, siglen, &sigbytes2)
2444 || sigbytes1 != sigbytes2) {
2445 SSLerr(SSL_F_TLS_CONSTRUCT_SERVER_KEY_EXCHANGE,
2446 ERR_R_INTERNAL_ERROR);
2451 EVP_MD_CTX_free(md_ctx);
2454 ssl3_send_alert(s, SSL3_AL_FATAL, al);
2456 #ifndef OPENSSL_NO_DH
2457 EVP_PKEY_free(pkdh);
2459 #ifndef OPENSSL_NO_EC
2460 OPENSSL_free(encodedPoint);
2462 EVP_MD_CTX_free(md_ctx);
2466 int tls_construct_certificate_request(SSL *s, WPACKET *pkt)
2469 STACK_OF(X509_NAME) *sk = NULL;
2471 if (SSL_IS_TLS13(s)) {
2472 /* TODO(TLS1.3) for now send empty request context */
2473 if (!WPACKET_put_bytes_u8(pkt, 0)) {
2474 SSLerr(SSL_F_TLS_CONSTRUCT_CERTIFICATE_REQUEST,
2475 ERR_R_INTERNAL_ERROR);
2479 /* get the list of acceptable cert types */
2480 if (!WPACKET_start_sub_packet_u8(pkt)
2481 || !ssl3_get_req_cert_type(s, pkt) || !WPACKET_close(pkt)) {
2482 SSLerr(SSL_F_TLS_CONSTRUCT_CERTIFICATE_REQUEST,
2483 ERR_R_INTERNAL_ERROR);
2488 if (SSL_USE_SIGALGS(s)) {
2489 const uint16_t *psigs;
2490 size_t nl = tls12_get_psigalgs(s, 1, &psigs);
2492 if (!WPACKET_start_sub_packet_u16(pkt)
2493 || !tls12_copy_sigalgs(s, pkt, psigs, nl)
2494 || !WPACKET_close(pkt)) {
2495 SSLerr(SSL_F_TLS_CONSTRUCT_CERTIFICATE_REQUEST,
2496 ERR_R_INTERNAL_ERROR);
2501 /* Start sub-packet for client CA list */
2502 if (!WPACKET_start_sub_packet_u16(pkt)) {
2503 SSLerr(SSL_F_TLS_CONSTRUCT_CERTIFICATE_REQUEST, ERR_R_INTERNAL_ERROR);
2507 sk = SSL_get_client_CA_list(s);
2509 for (i = 0; i < sk_X509_NAME_num(sk); i++) {
2510 unsigned char *namebytes;
2511 X509_NAME *name = sk_X509_NAME_value(sk, i);
2515 || (namelen = i2d_X509_NAME(name, NULL)) < 0
2516 || !WPACKET_sub_allocate_bytes_u16(pkt, namelen,
2518 || i2d_X509_NAME(name, &namebytes) != namelen) {
2519 SSLerr(SSL_F_TLS_CONSTRUCT_CERTIFICATE_REQUEST,
2520 ERR_R_INTERNAL_ERROR);
2525 /* else no CA names */
2526 if (!WPACKET_close(pkt)) {
2527 SSLerr(SSL_F_TLS_CONSTRUCT_CERTIFICATE_REQUEST, ERR_R_INTERNAL_ERROR);
2531 * TODO(TLS1.3) implement configurable certificate_extensions
2532 * For now just send zero length extensions.
2534 if (SSL_IS_TLS13(s) && !WPACKET_put_bytes_u16(pkt, 0)) {
2535 SSLerr(SSL_F_TLS_CONSTRUCT_CERTIFICATE_REQUEST, ERR_R_INTERNAL_ERROR);
2539 s->s3->tmp.cert_request = 1;
2543 ssl3_send_alert(s, SSL3_AL_FATAL, SSL_AD_INTERNAL_ERROR);
2547 static int tls_process_cke_psk_preamble(SSL *s, PACKET *pkt, int *al)
2549 #ifndef OPENSSL_NO_PSK
2550 unsigned char psk[PSK_MAX_PSK_LEN];
2552 PACKET psk_identity;
2554 if (!PACKET_get_length_prefixed_2(pkt, &psk_identity)) {
2555 *al = SSL_AD_DECODE_ERROR;
2556 SSLerr(SSL_F_TLS_PROCESS_CKE_PSK_PREAMBLE, SSL_R_LENGTH_MISMATCH);
2559 if (PACKET_remaining(&psk_identity) > PSK_MAX_IDENTITY_LEN) {
2560 *al = SSL_AD_DECODE_ERROR;
2561 SSLerr(SSL_F_TLS_PROCESS_CKE_PSK_PREAMBLE, SSL_R_DATA_LENGTH_TOO_LONG);
2564 if (s->psk_server_callback == NULL) {
2565 *al = SSL_AD_INTERNAL_ERROR;
2566 SSLerr(SSL_F_TLS_PROCESS_CKE_PSK_PREAMBLE, SSL_R_PSK_NO_SERVER_CB);
2570 if (!PACKET_strndup(&psk_identity, &s->session->psk_identity)) {
2571 *al = SSL_AD_INTERNAL_ERROR;
2572 SSLerr(SSL_F_TLS_PROCESS_CKE_PSK_PREAMBLE, ERR_R_INTERNAL_ERROR);
2576 psklen = s->psk_server_callback(s, s->session->psk_identity,
2579 if (psklen > PSK_MAX_PSK_LEN) {
2580 *al = SSL_AD_INTERNAL_ERROR;
2581 SSLerr(SSL_F_TLS_PROCESS_CKE_PSK_PREAMBLE, ERR_R_INTERNAL_ERROR);
2583 } else if (psklen == 0) {
2585 * PSK related to the given identity not found
2587 *al = SSL_AD_UNKNOWN_PSK_IDENTITY;
2588 SSLerr(SSL_F_TLS_PROCESS_CKE_PSK_PREAMBLE,
2589 SSL_R_PSK_IDENTITY_NOT_FOUND);
2593 OPENSSL_free(s->s3->tmp.psk);
2594 s->s3->tmp.psk = OPENSSL_memdup(psk, psklen);
2595 OPENSSL_cleanse(psk, psklen);
2597 if (s->s3->tmp.psk == NULL) {
2598 *al = SSL_AD_INTERNAL_ERROR;
2599 SSLerr(SSL_F_TLS_PROCESS_CKE_PSK_PREAMBLE, ERR_R_MALLOC_FAILURE);
2603 s->s3->tmp.psklen = psklen;
2607 /* Should never happen */
2608 *al = SSL_AD_INTERNAL_ERROR;
2609 SSLerr(SSL_F_TLS_PROCESS_CKE_PSK_PREAMBLE, ERR_R_INTERNAL_ERROR);
2614 static int tls_process_cke_rsa(SSL *s, PACKET *pkt, int *al)
2616 #ifndef OPENSSL_NO_RSA
2617 unsigned char rand_premaster_secret[SSL_MAX_MASTER_KEY_LENGTH];
2619 unsigned char decrypt_good, version_good;
2620 size_t j, padding_len;
2621 PACKET enc_premaster;
2623 unsigned char *rsa_decrypt = NULL;
2626 rsa = EVP_PKEY_get0_RSA(s->cert->pkeys[SSL_PKEY_RSA].privatekey);
2628 *al = SSL_AD_HANDSHAKE_FAILURE;
2629 SSLerr(SSL_F_TLS_PROCESS_CKE_RSA, SSL_R_MISSING_RSA_CERTIFICATE);
2633 /* SSLv3 and pre-standard DTLS omit the length bytes. */
2634 if (s->version == SSL3_VERSION || s->version == DTLS1_BAD_VER) {
2635 enc_premaster = *pkt;
2637 if (!PACKET_get_length_prefixed_2(pkt, &enc_premaster)
2638 || PACKET_remaining(pkt) != 0) {
2639 *al = SSL_AD_DECODE_ERROR;
2640 SSLerr(SSL_F_TLS_PROCESS_CKE_RSA, SSL_R_LENGTH_MISMATCH);
2646 * We want to be sure that the plaintext buffer size makes it safe to
2647 * iterate over the entire size of a premaster secret
2648 * (SSL_MAX_MASTER_KEY_LENGTH). Reject overly short RSA keys because
2649 * their ciphertext cannot accommodate a premaster secret anyway.
2651 if (RSA_size(rsa) < SSL_MAX_MASTER_KEY_LENGTH) {
2652 *al = SSL_AD_INTERNAL_ERROR;
2653 SSLerr(SSL_F_TLS_PROCESS_CKE_RSA, RSA_R_KEY_SIZE_TOO_SMALL);
2657 rsa_decrypt = OPENSSL_malloc(RSA_size(rsa));
2658 if (rsa_decrypt == NULL) {
2659 *al = SSL_AD_INTERNAL_ERROR;
2660 SSLerr(SSL_F_TLS_PROCESS_CKE_RSA, ERR_R_MALLOC_FAILURE);
2665 * We must not leak whether a decryption failure occurs because of
2666 * Bleichenbacher's attack on PKCS #1 v1.5 RSA padding (see RFC 2246,
2667 * section 7.4.7.1). The code follows that advice of the TLS RFC and
2668 * generates a random premaster secret for the case that the decrypt
2669 * fails. See https://tools.ietf.org/html/rfc5246#section-7.4.7.1
2672 if (RAND_bytes(rand_premaster_secret, sizeof(rand_premaster_secret)) <= 0)
2676 * Decrypt with no padding. PKCS#1 padding will be removed as part of
2677 * the timing-sensitive code below.
2679 /* TODO(size_t): Convert this function */
2680 decrypt_len = (int)RSA_private_decrypt((int)PACKET_remaining(&enc_premaster),
2681 PACKET_data(&enc_premaster),
2682 rsa_decrypt, rsa, RSA_NO_PADDING);
2683 if (decrypt_len < 0)
2686 /* Check the padding. See RFC 3447, section 7.2.2. */
2689 * The smallest padded premaster is 11 bytes of overhead. Small keys
2690 * are publicly invalid, so this may return immediately. This ensures
2691 * PS is at least 8 bytes.
2693 if (decrypt_len < 11 + SSL_MAX_MASTER_KEY_LENGTH) {
2694 *al = SSL_AD_DECRYPT_ERROR;
2695 SSLerr(SSL_F_TLS_PROCESS_CKE_RSA, SSL_R_DECRYPTION_FAILED);
2699 padding_len = decrypt_len - SSL_MAX_MASTER_KEY_LENGTH;
2700 decrypt_good = constant_time_eq_int_8(rsa_decrypt[0], 0) &
2701 constant_time_eq_int_8(rsa_decrypt[1], 2);
2702 for (j = 2; j < padding_len - 1; j++) {
2703 decrypt_good &= ~constant_time_is_zero_8(rsa_decrypt[j]);
2705 decrypt_good &= constant_time_is_zero_8(rsa_decrypt[padding_len - 1]);
2708 * If the version in the decrypted pre-master secret is correct then
2709 * version_good will be 0xff, otherwise it'll be zero. The
2710 * Klima-Pokorny-Rosa extension of Bleichenbacher's attack
2711 * (http://eprint.iacr.org/2003/052/) exploits the version number
2712 * check as a "bad version oracle". Thus version checks are done in
2713 * constant time and are treated like any other decryption error.
2716 constant_time_eq_8(rsa_decrypt[padding_len],
2717 (unsigned)(s->client_version >> 8));
2719 constant_time_eq_8(rsa_decrypt[padding_len + 1],
2720 (unsigned)(s->client_version & 0xff));
2723 * The premaster secret must contain the same version number as the
2724 * ClientHello to detect version rollback attacks (strangely, the
2725 * protocol does not offer such protection for DH ciphersuites).
2726 * However, buggy clients exist that send the negotiated protocol
2727 * version instead if the server does not support the requested
2728 * protocol version. If SSL_OP_TLS_ROLLBACK_BUG is set, tolerate such
2731 if (s->options & SSL_OP_TLS_ROLLBACK_BUG) {
2732 unsigned char workaround_good;
2733 workaround_good = constant_time_eq_8(rsa_decrypt[padding_len],
2734 (unsigned)(s->version >> 8));
2736 constant_time_eq_8(rsa_decrypt[padding_len + 1],
2737 (unsigned)(s->version & 0xff));
2738 version_good |= workaround_good;
2742 * Both decryption and version must be good for decrypt_good to
2743 * remain non-zero (0xff).
2745 decrypt_good &= version_good;
2748 * Now copy rand_premaster_secret over from p using
2749 * decrypt_good_mask. If decryption failed, then p does not
2750 * contain valid plaintext, however, a check above guarantees
2751 * it is still sufficiently large to read from.
2753 for (j = 0; j < sizeof(rand_premaster_secret); j++) {
2754 rsa_decrypt[padding_len + j] =
2755 constant_time_select_8(decrypt_good,
2756 rsa_decrypt[padding_len + j],
2757 rand_premaster_secret[j]);
2760 if (!ssl_generate_master_secret(s, rsa_decrypt + padding_len,
2761 sizeof(rand_premaster_secret), 0)) {
2762 *al = SSL_AD_INTERNAL_ERROR;
2763 SSLerr(SSL_F_TLS_PROCESS_CKE_RSA, ERR_R_INTERNAL_ERROR);
2769 OPENSSL_free(rsa_decrypt);
2772 /* Should never happen */
2773 *al = SSL_AD_INTERNAL_ERROR;
2774 SSLerr(SSL_F_TLS_PROCESS_CKE_RSA, ERR_R_INTERNAL_ERROR);
2779 static int tls_process_cke_dhe(SSL *s, PACKET *pkt, int *al)
2781 #ifndef OPENSSL_NO_DH
2782 EVP_PKEY *skey = NULL;
2786 const unsigned char *data;
2787 EVP_PKEY *ckey = NULL;
2790 if (!PACKET_get_net_2(pkt, &i) || PACKET_remaining(pkt) != i) {
2791 *al = SSL_AD_HANDSHAKE_FAILURE;
2792 SSLerr(SSL_F_TLS_PROCESS_CKE_DHE,
2793 SSL_R_DH_PUBLIC_VALUE_LENGTH_IS_WRONG);
2796 skey = s->s3->tmp.pkey;
2798 *al = SSL_AD_HANDSHAKE_FAILURE;
2799 SSLerr(SSL_F_TLS_PROCESS_CKE_DHE, SSL_R_MISSING_TMP_DH_KEY);
2803 if (PACKET_remaining(pkt) == 0L) {
2804 *al = SSL_AD_HANDSHAKE_FAILURE;
2805 SSLerr(SSL_F_TLS_PROCESS_CKE_DHE, SSL_R_MISSING_TMP_DH_KEY);
2808 if (!PACKET_get_bytes(pkt, &data, i)) {
2809 /* We already checked we have enough data */
2810 *al = SSL_AD_INTERNAL_ERROR;
2811 SSLerr(SSL_F_TLS_PROCESS_CKE_DHE, ERR_R_INTERNAL_ERROR);
2814 ckey = EVP_PKEY_new();
2815 if (ckey == NULL || EVP_PKEY_copy_parameters(ckey, skey) == 0) {
2816 SSLerr(SSL_F_TLS_PROCESS_CKE_DHE, SSL_R_BN_LIB);
2819 cdh = EVP_PKEY_get0_DH(ckey);
2820 pub_key = BN_bin2bn(data, i, NULL);
2822 if (pub_key == NULL || !DH_set0_key(cdh, pub_key, NULL)) {
2823 SSLerr(SSL_F_TLS_PROCESS_CKE_DHE, ERR_R_INTERNAL_ERROR);
2824 if (pub_key != NULL)
2829 if (ssl_derive(s, skey, ckey, 1) == 0) {
2830 *al = SSL_AD_INTERNAL_ERROR;
2831 SSLerr(SSL_F_TLS_PROCESS_CKE_DHE, ERR_R_INTERNAL_ERROR);
2836 EVP_PKEY_free(s->s3->tmp.pkey);
2837 s->s3->tmp.pkey = NULL;
2839 EVP_PKEY_free(ckey);
2842 /* Should never happen */
2843 *al = SSL_AD_INTERNAL_ERROR;
2844 SSLerr(SSL_F_TLS_PROCESS_CKE_DHE, ERR_R_INTERNAL_ERROR);
2849 static int tls_process_cke_ecdhe(SSL *s, PACKET *pkt, int *al)
2851 #ifndef OPENSSL_NO_EC
2852 EVP_PKEY *skey = s->s3->tmp.pkey;
2853 EVP_PKEY *ckey = NULL;
2856 if (PACKET_remaining(pkt) == 0L) {
2857 /* We don't support ECDH client auth */
2858 *al = SSL_AD_HANDSHAKE_FAILURE;
2859 SSLerr(SSL_F_TLS_PROCESS_CKE_ECDHE, SSL_R_MISSING_TMP_ECDH_KEY);
2863 const unsigned char *data;
2866 * Get client's public key from encoded point in the
2867 * ClientKeyExchange message.
2870 /* Get encoded point length */
2871 if (!PACKET_get_1(pkt, &i) || !PACKET_get_bytes(pkt, &data, i)
2872 || PACKET_remaining(pkt) != 0) {
2873 *al = SSL_AD_DECODE_ERROR;
2874 SSLerr(SSL_F_TLS_PROCESS_CKE_ECDHE, SSL_R_LENGTH_MISMATCH);
2877 ckey = EVP_PKEY_new();
2878 if (ckey == NULL || EVP_PKEY_copy_parameters(ckey, skey) <= 0) {
2879 SSLerr(SSL_F_TLS_PROCESS_CKE_ECDHE, ERR_R_EVP_LIB);
2882 if (EVP_PKEY_set1_tls_encodedpoint(ckey, data, i) == 0) {
2883 *al = SSL_AD_HANDSHAKE_FAILURE;
2884 SSLerr(SSL_F_TLS_PROCESS_CKE_ECDHE, ERR_R_EC_LIB);
2889 if (ssl_derive(s, skey, ckey, 1) == 0) {
2890 *al = SSL_AD_INTERNAL_ERROR;
2891 SSLerr(SSL_F_TLS_PROCESS_CKE_ECDHE, ERR_R_INTERNAL_ERROR);
2896 EVP_PKEY_free(s->s3->tmp.pkey);
2897 s->s3->tmp.pkey = NULL;
2899 EVP_PKEY_free(ckey);
2903 /* Should never happen */
2904 *al = SSL_AD_INTERNAL_ERROR;
2905 SSLerr(SSL_F_TLS_PROCESS_CKE_ECDHE, ERR_R_INTERNAL_ERROR);
2910 static int tls_process_cke_srp(SSL *s, PACKET *pkt, int *al)
2912 #ifndef OPENSSL_NO_SRP
2914 const unsigned char *data;
2916 if (!PACKET_get_net_2(pkt, &i)
2917 || !PACKET_get_bytes(pkt, &data, i)) {
2918 *al = SSL_AD_DECODE_ERROR;
2919 SSLerr(SSL_F_TLS_PROCESS_CKE_SRP, SSL_R_BAD_SRP_A_LENGTH);
2922 if ((s->srp_ctx.A = BN_bin2bn(data, i, NULL)) == NULL) {
2923 SSLerr(SSL_F_TLS_PROCESS_CKE_SRP, ERR_R_BN_LIB);
2926 if (BN_ucmp(s->srp_ctx.A, s->srp_ctx.N) >= 0 || BN_is_zero(s->srp_ctx.A)) {
2927 *al = SSL_AD_ILLEGAL_PARAMETER;
2928 SSLerr(SSL_F_TLS_PROCESS_CKE_SRP, SSL_R_BAD_SRP_PARAMETERS);
2931 OPENSSL_free(s->session->srp_username);
2932 s->session->srp_username = OPENSSL_strdup(s->srp_ctx.login);
2933 if (s->session->srp_username == NULL) {
2934 SSLerr(SSL_F_TLS_PROCESS_CKE_SRP, ERR_R_MALLOC_FAILURE);
2938 if (!srp_generate_server_master_secret(s)) {
2939 SSLerr(SSL_F_TLS_PROCESS_CKE_SRP, ERR_R_INTERNAL_ERROR);
2945 /* Should never happen */
2946 *al = SSL_AD_INTERNAL_ERROR;
2947 SSLerr(SSL_F_TLS_PROCESS_CKE_SRP, ERR_R_INTERNAL_ERROR);
2952 static int tls_process_cke_gost(SSL *s, PACKET *pkt, int *al)
2954 #ifndef OPENSSL_NO_GOST
2955 EVP_PKEY_CTX *pkey_ctx;
2956 EVP_PKEY *client_pub_pkey = NULL, *pk = NULL;
2957 unsigned char premaster_secret[32];
2958 const unsigned char *start;
2959 size_t outlen = 32, inlen;
2960 unsigned long alg_a;
2963 size_t sess_key_len;
2964 const unsigned char *data;
2967 /* Get our certificate private key */
2968 alg_a = s->s3->tmp.new_cipher->algorithm_auth;
2969 if (alg_a & SSL_aGOST12) {
2971 * New GOST ciphersuites have SSL_aGOST01 bit too
2973 pk = s->cert->pkeys[SSL_PKEY_GOST12_512].privatekey;
2975 pk = s->cert->pkeys[SSL_PKEY_GOST12_256].privatekey;
2978 pk = s->cert->pkeys[SSL_PKEY_GOST01].privatekey;
2980 } else if (alg_a & SSL_aGOST01) {
2981 pk = s->cert->pkeys[SSL_PKEY_GOST01].privatekey;
2984 pkey_ctx = EVP_PKEY_CTX_new(pk, NULL);
2985 if (pkey_ctx == NULL) {
2986 *al = SSL_AD_INTERNAL_ERROR;
2987 SSLerr(SSL_F_TLS_PROCESS_CKE_GOST, ERR_R_MALLOC_FAILURE);
2990 if (EVP_PKEY_decrypt_init(pkey_ctx) <= 0) {
2991 *al = SSL_AD_INTERNAL_ERROR;
2992 SSLerr(SSL_F_TLS_PROCESS_CKE_GOST, ERR_R_INTERNAL_ERROR);
2996 * If client certificate is present and is of the same type, maybe
2997 * use it for key exchange. Don't mind errors from
2998 * EVP_PKEY_derive_set_peer, because it is completely valid to use a
2999 * client certificate for authorization only.
3001 client_pub_pkey = X509_get0_pubkey(s->session->peer);
3002 if (client_pub_pkey) {
3003 if (EVP_PKEY_derive_set_peer(pkey_ctx, client_pub_pkey) <= 0)
3006 /* Decrypt session key */
3007 sess_key_len = PACKET_remaining(pkt);
3008 if (!PACKET_get_bytes(pkt, &data, sess_key_len)) {
3009 *al = SSL_AD_INTERNAL_ERROR;
3010 SSLerr(SSL_F_TLS_PROCESS_CKE_GOST, ERR_R_INTERNAL_ERROR);
3013 /* TODO(size_t): Convert this function */
3014 if (ASN1_get_object((const unsigned char **)&data, &Tlen, &Ttag,
3015 &Tclass, (long)sess_key_len) != V_ASN1_CONSTRUCTED
3016 || Ttag != V_ASN1_SEQUENCE || Tclass != V_ASN1_UNIVERSAL) {
3017 *al = SSL_AD_DECODE_ERROR;
3018 SSLerr(SSL_F_TLS_PROCESS_CKE_GOST, SSL_R_DECRYPTION_FAILED);
3023 if (EVP_PKEY_decrypt
3024 (pkey_ctx, premaster_secret, &outlen, start, inlen) <= 0) {
3025 *al = SSL_AD_DECODE_ERROR;
3026 SSLerr(SSL_F_TLS_PROCESS_CKE_GOST, SSL_R_DECRYPTION_FAILED);
3029 /* Generate master secret */
3030 if (!ssl_generate_master_secret(s, premaster_secret,
3031 sizeof(premaster_secret), 0)) {
3032 *al = SSL_AD_INTERNAL_ERROR;
3033 SSLerr(SSL_F_TLS_PROCESS_CKE_GOST, ERR_R_INTERNAL_ERROR);
3036 /* Check if pubkey from client certificate was used */
3037 if (EVP_PKEY_CTX_ctrl
3038 (pkey_ctx, -1, -1, EVP_PKEY_CTRL_PEER_KEY, 2, NULL) > 0)
3039 s->statem.no_cert_verify = 1;
3043 EVP_PKEY_CTX_free(pkey_ctx);
3046 /* Should never happen */
3047 *al = SSL_AD_INTERNAL_ERROR;
3048 SSLerr(SSL_F_TLS_PROCESS_CKE_GOST, ERR_R_INTERNAL_ERROR);
3053 MSG_PROCESS_RETURN tls_process_client_key_exchange(SSL *s, PACKET *pkt)
3056 unsigned long alg_k;
3058 alg_k = s->s3->tmp.new_cipher->algorithm_mkey;
3060 /* For PSK parse and retrieve identity, obtain PSK key */
3061 if ((alg_k & SSL_PSK) && !tls_process_cke_psk_preamble(s, pkt, &al))
3064 if (alg_k & SSL_kPSK) {
3065 /* Identity extracted earlier: should be nothing left */
3066 if (PACKET_remaining(pkt) != 0) {
3067 al = SSL_AD_HANDSHAKE_FAILURE;
3068 SSLerr(SSL_F_TLS_PROCESS_CLIENT_KEY_EXCHANGE,
3069 SSL_R_LENGTH_MISMATCH);
3072 /* PSK handled by ssl_generate_master_secret */
3073 if (!ssl_generate_master_secret(s, NULL, 0, 0)) {
3074 al = SSL_AD_INTERNAL_ERROR;
3075 SSLerr(SSL_F_TLS_PROCESS_CLIENT_KEY_EXCHANGE, ERR_R_INTERNAL_ERROR);
3078 } else if (alg_k & (SSL_kRSA | SSL_kRSAPSK)) {
3079 if (!tls_process_cke_rsa(s, pkt, &al))
3081 } else if (alg_k & (SSL_kDHE | SSL_kDHEPSK)) {
3082 if (!tls_process_cke_dhe(s, pkt, &al))
3084 } else if (alg_k & (SSL_kECDHE | SSL_kECDHEPSK)) {
3085 if (!tls_process_cke_ecdhe(s, pkt, &al))
3087 } else if (alg_k & SSL_kSRP) {
3088 if (!tls_process_cke_srp(s, pkt, &al))
3090 } else if (alg_k & SSL_kGOST) {
3091 if (!tls_process_cke_gost(s, pkt, &al))
3094 al = SSL_AD_HANDSHAKE_FAILURE;
3095 SSLerr(SSL_F_TLS_PROCESS_CLIENT_KEY_EXCHANGE,
3096 SSL_R_UNKNOWN_CIPHER_TYPE);
3100 return MSG_PROCESS_CONTINUE_PROCESSING;
3103 ssl3_send_alert(s, SSL3_AL_FATAL, al);
3104 #ifndef OPENSSL_NO_PSK
3105 OPENSSL_clear_free(s->s3->tmp.psk, s->s3->tmp.psklen);
3106 s->s3->tmp.psk = NULL;
3108 ossl_statem_set_error(s);
3109 return MSG_PROCESS_ERROR;
3112 WORK_STATE tls_post_process_client_key_exchange(SSL *s, WORK_STATE wst)
3114 #ifndef OPENSSL_NO_SCTP
3115 if (wst == WORK_MORE_A) {
3116 if (SSL_IS_DTLS(s)) {
3117 unsigned char sctpauthkey[64];
3118 char labelbuffer[sizeof(DTLS1_SCTP_AUTH_LABEL)];
3120 * Add new shared key for SCTP-Auth, will be ignored if no SCTP
3123 memcpy(labelbuffer, DTLS1_SCTP_AUTH_LABEL,
3124 sizeof(DTLS1_SCTP_AUTH_LABEL));
3126 if (SSL_export_keying_material(s, sctpauthkey,
3127 sizeof(sctpauthkey), labelbuffer,
3128 sizeof(labelbuffer), NULL, 0,
3130 ossl_statem_set_error(s);
3134 BIO_ctrl(SSL_get_wbio(s), BIO_CTRL_DGRAM_SCTP_ADD_AUTH_KEY,
3135 sizeof(sctpauthkey), sctpauthkey);
3140 if ((wst == WORK_MORE_B)
3142 && BIO_dgram_is_sctp(SSL_get_wbio(s))
3143 /* Are we renegotiating? */
3145 /* Are we going to skip the CertificateVerify? */
3146 && (s->session->peer == NULL || s->statem.no_cert_verify)
3147 && BIO_dgram_sctp_msg_waiting(SSL_get_rbio(s))) {
3148 s->s3->in_read_app_data = 2;
3149 s->rwstate = SSL_READING;
3150 BIO_clear_retry_flags(SSL_get_rbio(s));
3151 BIO_set_retry_read(SSL_get_rbio(s));
3152 ossl_statem_set_sctp_read_sock(s, 1);
3155 ossl_statem_set_sctp_read_sock(s, 0);
3159 if (s->statem.no_cert_verify || !s->session->peer) {
3161 * No certificate verify or no peer certificate so we no longer need
3162 * the handshake_buffer
3164 if (!ssl3_digest_cached_records(s, 0)) {
3165 ossl_statem_set_error(s);
3168 return WORK_FINISHED_CONTINUE;
3170 if (!s->s3->handshake_buffer) {
3171 SSLerr(SSL_F_TLS_POST_PROCESS_CLIENT_KEY_EXCHANGE,
3172 ERR_R_INTERNAL_ERROR);
3173 ossl_statem_set_error(s);
3177 * For sigalgs freeze the handshake buffer. If we support
3178 * extms we've done this already so this is a no-op
3180 if (!ssl3_digest_cached_records(s, 1)) {
3181 ossl_statem_set_error(s);
3186 return WORK_FINISHED_CONTINUE;
3189 MSG_PROCESS_RETURN tls_process_client_certificate(SSL *s, PACKET *pkt)
3191 int i, al = SSL_AD_INTERNAL_ERROR, ret = MSG_PROCESS_ERROR;
3193 unsigned long l, llen;
3194 const unsigned char *certstart, *certbytes;
3195 STACK_OF(X509) *sk = NULL;
3196 PACKET spkt, context;
3199 if ((sk = sk_X509_new_null()) == NULL) {
3200 SSLerr(SSL_F_TLS_PROCESS_CLIENT_CERTIFICATE, ERR_R_MALLOC_FAILURE);
3204 /* TODO(TLS1.3): For now we ignore the context. We need to verify this */
3205 if ((SSL_IS_TLS13(s) && !PACKET_get_length_prefixed_1(pkt, &context))
3206 || !PACKET_get_net_3(pkt, &llen)
3207 || !PACKET_get_sub_packet(pkt, &spkt, llen)
3208 || PACKET_remaining(pkt) != 0) {
3209 al = SSL_AD_DECODE_ERROR;
3210 SSLerr(SSL_F_TLS_PROCESS_CLIENT_CERTIFICATE, SSL_R_LENGTH_MISMATCH);
3214 for (chainidx = 0; PACKET_remaining(&spkt) > 0; chainidx++) {
3215 if (!PACKET_get_net_3(&spkt, &l)
3216 || !PACKET_get_bytes(&spkt, &certbytes, l)) {
3217 al = SSL_AD_DECODE_ERROR;
3218 SSLerr(SSL_F_TLS_PROCESS_CLIENT_CERTIFICATE,
3219 SSL_R_CERT_LENGTH_MISMATCH);
3223 certstart = certbytes;
3224 x = d2i_X509(NULL, (const unsigned char **)&certbytes, l);
3226 SSLerr(SSL_F_TLS_PROCESS_CLIENT_CERTIFICATE, ERR_R_ASN1_LIB);
3229 if (certbytes != (certstart + l)) {
3230 al = SSL_AD_DECODE_ERROR;
3231 SSLerr(SSL_F_TLS_PROCESS_CLIENT_CERTIFICATE,
3232 SSL_R_CERT_LENGTH_MISMATCH);
3236 if (SSL_IS_TLS13(s)) {
3237 RAW_EXTENSION *rawexts = NULL;
3240 if (!PACKET_get_length_prefixed_2(&spkt, &extensions)) {
3241 al = SSL_AD_DECODE_ERROR;
3242 SSLerr(SSL_F_TLS_PROCESS_CLIENT_CERTIFICATE, SSL_R_BAD_LENGTH);
3245 if (!tls_collect_extensions(s, &extensions, EXT_TLS1_3_CERTIFICATE,
3246 &rawexts, &al, NULL)
3247 || !tls_parse_all_extensions(s, EXT_TLS1_3_CERTIFICATE,
3248 rawexts, x, chainidx, &al)) {
3249 OPENSSL_free(rawexts);
3252 OPENSSL_free(rawexts);
3255 if (!sk_X509_push(sk, x)) {
3256 SSLerr(SSL_F_TLS_PROCESS_CLIENT_CERTIFICATE, ERR_R_MALLOC_FAILURE);
3262 if (sk_X509_num(sk) <= 0) {
3263 /* TLS does not mind 0 certs returned */
3264 if (s->version == SSL3_VERSION) {
3265 al = SSL_AD_HANDSHAKE_FAILURE;
3266 SSLerr(SSL_F_TLS_PROCESS_CLIENT_CERTIFICATE,
3267 SSL_R_NO_CERTIFICATES_RETURNED);
3270 /* Fail for TLS only if we required a certificate */
3271 else if ((s->verify_mode & SSL_VERIFY_PEER) &&
3272 (s->verify_mode & SSL_VERIFY_FAIL_IF_NO_PEER_CERT)) {
3273 SSLerr(SSL_F_TLS_PROCESS_CLIENT_CERTIFICATE,
3274 SSL_R_PEER_DID_NOT_RETURN_A_CERTIFICATE);
3275 al = SSL_AD_HANDSHAKE_FAILURE;
3278 /* No client certificate so digest cached records */
3279 if (s->s3->handshake_buffer && !ssl3_digest_cached_records(s, 0)) {
3284 i = ssl_verify_cert_chain(s, sk);
3286 al = ssl_verify_alarm_type(s->verify_result);
3287 SSLerr(SSL_F_TLS_PROCESS_CLIENT_CERTIFICATE,
3288 SSL_R_CERTIFICATE_VERIFY_FAILED);
3292 SSLerr(SSL_F_TLS_PROCESS_CLIENT_CERTIFICATE, i);
3293 al = SSL_AD_HANDSHAKE_FAILURE;
3296 pkey = X509_get0_pubkey(sk_X509_value(sk, 0));
3298 al = SSL3_AD_HANDSHAKE_FAILURE;
3299 SSLerr(SSL_F_TLS_PROCESS_CLIENT_CERTIFICATE,
3300 SSL_R_UNKNOWN_CERTIFICATE_TYPE);
3305 X509_free(s->session->peer);
3306 s->session->peer = sk_X509_shift(sk);
3307 s->session->verify_result = s->verify_result;
3309 sk_X509_pop_free(s->session->peer_chain, X509_free);
3310 s->session->peer_chain = sk;
3313 * Freeze the handshake buffer. For <TLS1.3 we do this after the CKE
3316 if (SSL_IS_TLS13(s) && !ssl3_digest_cached_records(s, 1)) {
3317 al = SSL_AD_INTERNAL_ERROR;
3318 SSLerr(SSL_F_TLS_PROCESS_CLIENT_CERTIFICATE, ERR_R_INTERNAL_ERROR);
3323 * Inconsistency alert: cert_chain does *not* include the peer's own
3324 * certificate, while we do include it in statem_clnt.c
3328 /* Save the current hash state for when we receive the CertificateVerify */
3330 && !ssl_handshake_hash(s, s->cert_verify_hash,
3331 sizeof(s->cert_verify_hash),
3332 &s->cert_verify_hash_len)) {
3333 al = SSL_AD_INTERNAL_ERROR;
3334 SSLerr(SSL_F_TLS_PROCESS_CLIENT_CERTIFICATE, ERR_R_INTERNAL_ERROR);
3338 ret = MSG_PROCESS_CONTINUE_READING;
3342 ssl3_send_alert(s, SSL3_AL_FATAL, al);
3343 ossl_statem_set_error(s);
3346 sk_X509_pop_free(sk, X509_free);
3350 int tls_construct_server_certificate(SSL *s, WPACKET *pkt)
3352 CERT_PKEY *cpk = s->s3->tmp.cert;
3353 int al = SSL_AD_INTERNAL_ERROR;
3356 SSLerr(SSL_F_TLS_CONSTRUCT_SERVER_CERTIFICATE, ERR_R_INTERNAL_ERROR);
3361 * In TLSv1.3 the certificate chain is always preceded by a 0 length context
3362 * for the server Certificate message
3364 if ((SSL_IS_TLS13(s) && !WPACKET_put_bytes_u8(pkt, 0))
3365 || !ssl3_output_cert_chain(s, pkt, cpk, &al)) {
3366 SSLerr(SSL_F_TLS_CONSTRUCT_SERVER_CERTIFICATE, ERR_R_INTERNAL_ERROR);
3367 ssl3_send_alert(s, SSL3_AL_FATAL, al);
3374 int tls_construct_new_session_ticket(SSL *s, WPACKET *pkt)
3376 unsigned char *senc = NULL;
3377 EVP_CIPHER_CTX *ctx = NULL;
3378 HMAC_CTX *hctx = NULL;
3379 unsigned char *p, *encdata1, *encdata2, *macdata1, *macdata2;
3380 const unsigned char *const_p;
3381 int len, slen_full, slen, lenfinal;
3384 SSL_CTX *tctx = s->session_ctx;
3385 unsigned char iv[EVP_MAX_IV_LENGTH];
3386 unsigned char key_name[TLSEXT_KEYNAME_LENGTH];
3387 int iv_len, al = SSL_AD_INTERNAL_ERROR;
3388 size_t macoffset, macendoffset;
3390 unsigned char age_add_c[sizeof(uint32_t)];
3394 if (SSL_IS_TLS13(s)) {
3395 if (RAND_bytes(age_add_u.age_add_c, sizeof(age_add_u)) <= 0)
3397 s->session->ext.tick_age_add = age_add_u.age_add;
3398 s->session->time = (long)time(NULL);
3399 if (s->s3->alpn_selected != NULL) {
3400 OPENSSL_free(s->session->ext.alpn_selected);
3401 s->session->ext.alpn_selected =
3402 OPENSSL_memdup(s->s3->alpn_selected, s->s3->alpn_selected_len);
3403 if (s->session->ext.alpn_selected == NULL) {
3404 SSLerr(SSL_F_TLS_CONSTRUCT_NEW_SESSION_TICKET,
3405 ERR_R_MALLOC_FAILURE);
3408 s->session->ext.alpn_selected_len = s->s3->alpn_selected_len;
3410 s->session->ext.max_early_data = s->max_early_data;
3413 /* get session encoding length */
3414 slen_full = i2d_SSL_SESSION(s->session, NULL);
3416 * Some length values are 16 bits, so forget it if session is too
3419 if (slen_full == 0 || slen_full > 0xFF00) {
3420 SSLerr(SSL_F_TLS_CONSTRUCT_NEW_SESSION_TICKET, ERR_R_INTERNAL_ERROR);
3423 senc = OPENSSL_malloc(slen_full);
3425 SSLerr(SSL_F_TLS_CONSTRUCT_NEW_SESSION_TICKET, ERR_R_MALLOC_FAILURE);
3429 ctx = EVP_CIPHER_CTX_new();
3430 hctx = HMAC_CTX_new();
3431 if (ctx == NULL || hctx == NULL) {
3432 SSLerr(SSL_F_TLS_CONSTRUCT_NEW_SESSION_TICKET, ERR_R_MALLOC_FAILURE);
3437 if (!i2d_SSL_SESSION(s->session, &p))
3441 * create a fresh copy (not shared with other threads) to clean up
3444 sess = d2i_SSL_SESSION(NULL, &const_p, slen_full);
3447 sess->session_id_length = 0; /* ID is irrelevant for the ticket */
3449 slen = i2d_SSL_SESSION(sess, NULL);
3450 if (slen == 0 || slen > slen_full) { /* shouldn't ever happen */
3451 SSL_SESSION_free(sess);
3455 if (!i2d_SSL_SESSION(sess, &p)) {
3456 SSL_SESSION_free(sess);
3459 SSL_SESSION_free(sess);
3462 * Initialize HMAC and cipher contexts. If callback present it does
3463 * all the work otherwise use generated values from parent ctx.
3465 if (tctx->ext.ticket_key_cb) {
3466 /* if 0 is returned, write an empty ticket */
3467 int ret = tctx->ext.ticket_key_cb(s, key_name, iv, ctx,
3472 /* Put timeout and length */
3473 if (!WPACKET_put_bytes_u32(pkt, 0)
3474 || !WPACKET_put_bytes_u16(pkt, 0)) {
3475 SSLerr(SSL_F_TLS_CONSTRUCT_NEW_SESSION_TICKET,
3476 ERR_R_INTERNAL_ERROR);
3480 EVP_CIPHER_CTX_free(ctx);
3481 HMAC_CTX_free(hctx);
3486 iv_len = EVP_CIPHER_CTX_iv_length(ctx);
3488 const EVP_CIPHER *cipher = EVP_aes_256_cbc();
3490 iv_len = EVP_CIPHER_iv_length(cipher);
3491 if (RAND_bytes(iv, iv_len) <= 0)
3493 if (!EVP_EncryptInit_ex(ctx, cipher, NULL,
3494 tctx->ext.tick_aes_key, iv))
3496 if (!HMAC_Init_ex(hctx, tctx->ext.tick_hmac_key,
3497 sizeof(tctx->ext.tick_hmac_key),
3498 EVP_sha256(), NULL))
3500 memcpy(key_name, tctx->ext.tick_key_name,
3501 sizeof(tctx->ext.tick_key_name));
3505 * Ticket lifetime hint: For TLSv1.2 this is advisory only and we leave this
3506 * unspecified for resumed session (for simplicity).
3507 * In TLSv1.3 we reset the "time" field above, and always specify the
3510 if (!WPACKET_put_bytes_u32(pkt,
3511 (s->hit && !SSL_IS_TLS13(s))
3512 ? 0 : s->session->timeout)
3514 && !WPACKET_put_bytes_u32(pkt, age_add_u.age_add))
3515 /* Now the actual ticket data */
3516 || !WPACKET_start_sub_packet_u16(pkt)
3517 || !WPACKET_get_total_written(pkt, &macoffset)
3518 /* Output key name */
3519 || !WPACKET_memcpy(pkt, key_name, sizeof(key_name))
3521 || !WPACKET_memcpy(pkt, iv, iv_len)
3522 || !WPACKET_reserve_bytes(pkt, slen + EVP_MAX_BLOCK_LENGTH,
3524 /* Encrypt session data */
3525 || !EVP_EncryptUpdate(ctx, encdata1, &len, senc, slen)
3526 || !WPACKET_allocate_bytes(pkt, len, &encdata2)
3527 || encdata1 != encdata2
3528 || !EVP_EncryptFinal(ctx, encdata1 + len, &lenfinal)
3529 || !WPACKET_allocate_bytes(pkt, lenfinal, &encdata2)
3530 || encdata1 + len != encdata2
3531 || len + lenfinal > slen + EVP_MAX_BLOCK_LENGTH
3532 || !WPACKET_get_total_written(pkt, &macendoffset)
3533 || !HMAC_Update(hctx,
3534 (unsigned char *)s->init_buf->data + macoffset,
3535 macendoffset - macoffset)
3536 || !WPACKET_reserve_bytes(pkt, EVP_MAX_MD_SIZE, &macdata1)
3537 || !HMAC_Final(hctx, macdata1, &hlen)
3538 || hlen > EVP_MAX_MD_SIZE
3539 || !WPACKET_allocate_bytes(pkt, hlen, &macdata2)
3540 || macdata1 != macdata2
3541 || !WPACKET_close(pkt)
3543 && !tls_construct_extensions(s, pkt,
3544 EXT_TLS1_3_NEW_SESSION_TICKET,
3546 SSLerr(SSL_F_TLS_CONSTRUCT_NEW_SESSION_TICKET, ERR_R_INTERNAL_ERROR);
3549 EVP_CIPHER_CTX_free(ctx);
3550 HMAC_CTX_free(hctx);
3555 ossl_statem_set_error(s);
3557 EVP_CIPHER_CTX_free(ctx);
3558 HMAC_CTX_free(hctx);
3559 ssl3_send_alert(s, SSL3_AL_FATAL, SSL_AD_INTERNAL_ERROR);
3564 * In TLSv1.3 this is called from the extensions code, otherwise it is used to
3565 * create a separate message. Returns 1 on success or 0 on failure.
3567 int tls_construct_cert_status_body(SSL *s, WPACKET *pkt)
3569 if (!WPACKET_put_bytes_u8(pkt, s->ext.status_type)
3570 || !WPACKET_sub_memcpy_u24(pkt, s->ext.ocsp.resp,
3571 s->ext.ocsp.resp_len)) {
3572 SSLerr(SSL_F_TLS_CONSTRUCT_CERT_STATUS_BODY, ERR_R_INTERNAL_ERROR);
3579 int tls_construct_cert_status(SSL *s, WPACKET *pkt)
3581 if (!tls_construct_cert_status_body(s, pkt)) {
3582 ssl3_send_alert(s, SSL3_AL_FATAL, SSL_AD_INTERNAL_ERROR);
3589 #ifndef OPENSSL_NO_NEXTPROTONEG
3591 * tls_process_next_proto reads a Next Protocol Negotiation handshake message.
3592 * It sets the next_proto member in s if found
3594 MSG_PROCESS_RETURN tls_process_next_proto(SSL *s, PACKET *pkt)
3596 PACKET next_proto, padding;
3597 size_t next_proto_len;
3600 * The payload looks like:
3602 * uint8 proto[proto_len];
3603 * uint8 padding_len;
3604 * uint8 padding[padding_len];
3606 if (!PACKET_get_length_prefixed_1(pkt, &next_proto)
3607 || !PACKET_get_length_prefixed_1(pkt, &padding)
3608 || PACKET_remaining(pkt) > 0) {
3609 SSLerr(SSL_F_TLS_PROCESS_NEXT_PROTO, SSL_R_LENGTH_MISMATCH);
3613 if (!PACKET_memdup(&next_proto, &s->ext.npn, &next_proto_len)) {
3618 s->ext.npn_len = (unsigned char)next_proto_len;
3620 return MSG_PROCESS_CONTINUE_READING;
3622 ossl_statem_set_error(s);
3623 return MSG_PROCESS_ERROR;
3627 static int tls_construct_encrypted_extensions(SSL *s, WPACKET *pkt)
3631 if (!tls_construct_extensions(s, pkt, EXT_TLS1_3_ENCRYPTED_EXTENSIONS,
3633 ssl3_send_alert(s, SSL3_AL_FATAL, al);
3634 SSLerr(SSL_F_TLS_CONSTRUCT_ENCRYPTED_EXTENSIONS, ERR_R_INTERNAL_ERROR);
3635 ssl3_send_alert(s, SSL3_AL_FATAL, al);
3642 static int tls_construct_hello_retry_request(SSL *s, WPACKET *pkt)
3644 int al = SSL_AD_INTERNAL_ERROR;
3647 * TODO(TLS1.3): Remove the DRAFT version before release
3648 * (should be s->version)
3650 if (!WPACKET_put_bytes_u16(pkt, TLS1_3_VERSION_DRAFT)
3651 || !tls_construct_extensions(s, pkt, EXT_TLS1_3_HELLO_RETRY_REQUEST,
3653 SSLerr(SSL_F_TLS_CONSTRUCT_HELLO_RETRY_REQUEST, ERR_R_INTERNAL_ERROR);
3654 ssl3_send_alert(s, SSL3_AL_FATAL, al);
3658 /* Ditch the session. We'll create a new one next time around */
3659 SSL_SESSION_free(s->session);