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_EARLY_DATA:
97 case TLS_ST_SW_FINISHED:
98 if (s->s3->tmp.cert_request) {
99 if (mt == SSL3_MT_CERTIFICATE) {
100 st->hand_state = TLS_ST_SR_CERT;
104 if (mt == SSL3_MT_FINISHED) {
105 st->hand_state = TLS_ST_SR_FINISHED;
112 if (s->session->peer == NULL) {
113 if (mt == SSL3_MT_FINISHED) {
114 st->hand_state = TLS_ST_SR_FINISHED;
118 if (mt == SSL3_MT_CERTIFICATE_VERIFY) {
119 st->hand_state = TLS_ST_SR_CERT_VRFY;
125 case TLS_ST_SR_CERT_VRFY:
126 if (mt == SSL3_MT_FINISHED) {
127 st->hand_state = TLS_ST_SR_FINISHED;
134 * Its never ok to start processing handshake messages in the middle of
135 * early data (i.e. before we've received the end of early data alert)
137 if (s->early_data_state == SSL_EARLY_DATA_READING)
139 if (mt == SSL3_MT_KEY_UPDATE) {
140 st->hand_state = TLS_ST_SR_KEY_UPDATE;
146 /* No valid transition found */
147 ssl3_send_alert(s, SSL3_AL_FATAL, SSL3_AD_UNEXPECTED_MESSAGE);
148 SSLerr(SSL_F_OSSL_STATEM_SERVER13_READ_TRANSITION,
149 SSL_R_UNEXPECTED_MESSAGE);
154 * ossl_statem_server_read_transition() encapsulates the logic for the allowed
155 * handshake state transitions when the server is reading messages from the
156 * client. The message type that the client has sent is provided in |mt|. The
157 * current state is in |s->statem.hand_state|.
159 * Return values are 1 for success (transition allowed) and 0 on error
160 * (transition not allowed)
162 int ossl_statem_server_read_transition(SSL *s, int mt)
164 OSSL_STATEM *st = &s->statem;
166 if (SSL_IS_TLS13(s)) {
167 if (!ossl_statem_server13_read_transition(s, mt))
172 switch (st->hand_state) {
178 case DTLS_ST_SW_HELLO_VERIFY_REQUEST:
179 if (mt == SSL3_MT_CLIENT_HELLO) {
180 st->hand_state = TLS_ST_SR_CLNT_HELLO;
185 case TLS_ST_SW_SRVR_DONE:
187 * If we get a CKE message after a ServerDone then either
188 * 1) We didn't request a Certificate
190 * 2) If we did request one then
191 * a) We allow no Certificate to be returned
193 * b) We are running SSL3 (in TLS1.0+ the client must return a 0
194 * list if we requested a certificate)
196 if (mt == SSL3_MT_CLIENT_KEY_EXCHANGE) {
197 if (s->s3->tmp.cert_request) {
198 if (s->version == SSL3_VERSION) {
199 if ((s->verify_mode & SSL_VERIFY_PEER)
200 && (s->verify_mode & SSL_VERIFY_FAIL_IF_NO_PEER_CERT)) {
202 * This isn't an unexpected message as such - we're just
203 * not going to accept it because we require a client
206 ssl3_send_alert(s, SSL3_AL_FATAL,
207 SSL3_AD_HANDSHAKE_FAILURE);
208 SSLerr(SSL_F_OSSL_STATEM_SERVER_READ_TRANSITION,
209 SSL_R_PEER_DID_NOT_RETURN_A_CERTIFICATE);
212 st->hand_state = TLS_ST_SR_KEY_EXCH;
216 st->hand_state = TLS_ST_SR_KEY_EXCH;
219 } else if (s->s3->tmp.cert_request) {
220 if (mt == SSL3_MT_CERTIFICATE) {
221 st->hand_state = TLS_ST_SR_CERT;
228 if (mt == SSL3_MT_CLIENT_KEY_EXCHANGE) {
229 st->hand_state = TLS_ST_SR_KEY_EXCH;
234 case TLS_ST_SR_KEY_EXCH:
236 * We should only process a CertificateVerify message if we have
237 * received a Certificate from the client. If so then |s->session->peer|
238 * will be non NULL. In some instances a CertificateVerify message is
239 * not required even if the peer has sent a Certificate (e.g. such as in
240 * the case of static DH). In that case |st->no_cert_verify| should be
243 if (s->session->peer == NULL || st->no_cert_verify) {
244 if (mt == SSL3_MT_CHANGE_CIPHER_SPEC) {
246 * For the ECDH ciphersuites when the client sends its ECDH
247 * pub key in a certificate, the CertificateVerify message is
248 * not sent. Also for GOST ciphersuites when the client uses
249 * its key from the certificate for key exchange.
251 st->hand_state = TLS_ST_SR_CHANGE;
255 if (mt == SSL3_MT_CERTIFICATE_VERIFY) {
256 st->hand_state = TLS_ST_SR_CERT_VRFY;
262 case TLS_ST_SR_CERT_VRFY:
263 if (mt == SSL3_MT_CHANGE_CIPHER_SPEC) {
264 st->hand_state = TLS_ST_SR_CHANGE;
269 case TLS_ST_SR_CHANGE:
270 #ifndef OPENSSL_NO_NEXTPROTONEG
271 if (s->s3->npn_seen) {
272 if (mt == SSL3_MT_NEXT_PROTO) {
273 st->hand_state = TLS_ST_SR_NEXT_PROTO;
278 if (mt == SSL3_MT_FINISHED) {
279 st->hand_state = TLS_ST_SR_FINISHED;
282 #ifndef OPENSSL_NO_NEXTPROTONEG
287 #ifndef OPENSSL_NO_NEXTPROTONEG
288 case TLS_ST_SR_NEXT_PROTO:
289 if (mt == SSL3_MT_FINISHED) {
290 st->hand_state = TLS_ST_SR_FINISHED;
296 case TLS_ST_SW_FINISHED:
297 if (mt == SSL3_MT_CHANGE_CIPHER_SPEC) {
298 st->hand_state = TLS_ST_SR_CHANGE;
305 /* No valid transition found */
306 ssl3_send_alert(s, SSL3_AL_FATAL, SSL3_AD_UNEXPECTED_MESSAGE);
307 SSLerr(SSL_F_OSSL_STATEM_SERVER_READ_TRANSITION, SSL_R_UNEXPECTED_MESSAGE);
312 * Should we send a ServerKeyExchange message?
314 * Valid return values are:
318 static int send_server_key_exchange(SSL *s)
320 unsigned long alg_k = s->s3->tmp.new_cipher->algorithm_mkey;
323 * only send a ServerKeyExchange if DH or fortezza but we have a
324 * sign only certificate PSK: may send PSK identity hints For
325 * ECC ciphersuites, we send a serverKeyExchange message only if
326 * the cipher suite is either ECDH-anon or ECDHE. In other cases,
327 * the server certificate contains the server's public key for
330 if (alg_k & (SSL_kDHE | SSL_kECDHE)
332 * PSK: send ServerKeyExchange if PSK identity hint if
335 #ifndef OPENSSL_NO_PSK
336 /* Only send SKE if we have identity hint for plain PSK */
337 || ((alg_k & (SSL_kPSK | SSL_kRSAPSK))
338 && s->cert->psk_identity_hint)
339 /* For other PSK always send SKE */
340 || (alg_k & (SSL_PSK & (SSL_kDHEPSK | SSL_kECDHEPSK)))
342 #ifndef OPENSSL_NO_SRP
343 /* SRP: send ServerKeyExchange */
344 || (alg_k & SSL_kSRP)
354 * Should we send a CertificateRequest message?
356 * Valid return values are:
360 static int send_certificate_request(SSL *s)
363 /* don't request cert unless asked for it: */
364 s->verify_mode & SSL_VERIFY_PEER
366 * if SSL_VERIFY_CLIENT_ONCE is set, don't request cert
367 * during re-negotiation:
369 && (s->s3->tmp.finish_md_len == 0 ||
370 !(s->verify_mode & SSL_VERIFY_CLIENT_ONCE))
372 * never request cert in anonymous ciphersuites (see
373 * section "Certificate request" in SSL 3 drafts and in
376 && (!(s->s3->tmp.new_cipher->algorithm_auth & SSL_aNULL)
378 * ... except when the application insists on
379 * verification (against the specs, but statem_clnt.c accepts
382 || (s->verify_mode & SSL_VERIFY_FAIL_IF_NO_PEER_CERT))
383 /* don't request certificate for SRP auth */
384 && !(s->s3->tmp.new_cipher->algorithm_auth & SSL_aSRP)
386 * With normal PSK Certificates and Certificate Requests
389 && !(s->s3->tmp.new_cipher->algorithm_auth & SSL_aPSK)) {
397 * ossl_statem_server13_write_transition() works out what handshake state to
398 * move to next when a TLSv1.3 server is writing messages to be sent to the
401 static WRITE_TRAN ossl_statem_server13_write_transition(SSL *s)
403 OSSL_STATEM *st = &s->statem;
406 * No case for TLS_ST_BEFORE, because at that stage we have not negotiated
407 * TLSv1.3 yet, so that is handled by ossl_statem_server_write_transition()
410 switch (st->hand_state) {
412 /* Shouldn't happen */
413 return WRITE_TRAN_ERROR;
416 if (s->early_data_state == SSL_EARLY_DATA_FINISHED_READING) {
417 st->hand_state = TLS_ST_SW_FINISHED;
418 return WRITE_TRAN_FINISHED;
420 if (s->key_update != SSL_KEY_UPDATE_NONE) {
421 st->hand_state = TLS_ST_SW_KEY_UPDATE;
422 return WRITE_TRAN_CONTINUE;
424 /* Try to read from the client instead */
425 return WRITE_TRAN_FINISHED;
427 case TLS_ST_SR_CLNT_HELLO:
428 if (s->hello_retry_request)
429 st->hand_state = TLS_ST_SW_HELLO_RETRY_REQUEST;
431 st->hand_state = TLS_ST_SW_SRVR_HELLO;
432 return WRITE_TRAN_CONTINUE;
434 case TLS_ST_SW_HELLO_RETRY_REQUEST:
435 return WRITE_TRAN_FINISHED;
437 case TLS_ST_SW_SRVR_HELLO:
438 st->hand_state = TLS_ST_SW_ENCRYPTED_EXTENSIONS;
439 return WRITE_TRAN_CONTINUE;
441 case TLS_ST_SW_ENCRYPTED_EXTENSIONS:
443 st->hand_state = TLS_ST_SW_FINISHED;
444 else if (send_certificate_request(s))
445 st->hand_state = TLS_ST_SW_CERT_REQ;
447 st->hand_state = TLS_ST_SW_CERT;
449 return WRITE_TRAN_CONTINUE;
451 case TLS_ST_SW_CERT_REQ:
452 st->hand_state = TLS_ST_SW_CERT;
453 return WRITE_TRAN_CONTINUE;
456 st->hand_state = TLS_ST_SW_CERT_VRFY;
457 return WRITE_TRAN_CONTINUE;
459 case TLS_ST_SW_CERT_VRFY:
460 st->hand_state = TLS_ST_SW_FINISHED;
461 return WRITE_TRAN_CONTINUE;
463 case TLS_ST_SW_FINISHED:
464 if (s->early_data_state == SSL_EARLY_DATA_ACCEPTING) {
465 st->hand_state = TLS_ST_EARLY_DATA;
466 return WRITE_TRAN_CONTINUE;
468 return WRITE_TRAN_FINISHED;
470 case TLS_ST_EARLY_DATA:
471 return WRITE_TRAN_FINISHED;
473 case TLS_ST_SR_FINISHED:
475 * Technically we have finished the handshake at this point, but we're
476 * going to remain "in_init" for now and write out the session ticket
478 * TODO(TLS1.3): Perhaps we need to be able to control this behaviour
479 * and give the application the opportunity to delay sending the
482 st->hand_state = TLS_ST_SW_SESSION_TICKET;
483 return WRITE_TRAN_CONTINUE;
485 case TLS_ST_SR_KEY_UPDATE:
486 if (s->key_update != SSL_KEY_UPDATE_NONE) {
487 st->hand_state = TLS_ST_SW_KEY_UPDATE;
488 return WRITE_TRAN_CONTINUE;
492 case TLS_ST_SW_KEY_UPDATE:
493 case TLS_ST_SW_SESSION_TICKET:
494 st->hand_state = TLS_ST_OK;
495 return WRITE_TRAN_CONTINUE;
500 * ossl_statem_server_write_transition() works out what handshake state to move
501 * to next when the server is writing messages to be sent to the client.
503 WRITE_TRAN ossl_statem_server_write_transition(SSL *s)
505 OSSL_STATEM *st = &s->statem;
508 * Note that before the ClientHello we don't know what version we are going
509 * to negotiate yet, so we don't take this branch until later
513 return ossl_statem_server13_write_transition(s);
515 switch (st->hand_state) {
517 /* Shouldn't happen */
518 return WRITE_TRAN_ERROR;
521 if (st->request_state == TLS_ST_SW_HELLO_REQ) {
522 /* We must be trying to renegotiate */
523 st->hand_state = TLS_ST_SW_HELLO_REQ;
524 st->request_state = TLS_ST_BEFORE;
525 return WRITE_TRAN_CONTINUE;
527 /* Must be an incoming ClientHello */
528 if (!tls_setup_handshake(s)) {
529 ossl_statem_set_error(s);
530 return WRITE_TRAN_ERROR;
535 /* Just go straight to trying to read from the client */
536 return WRITE_TRAN_FINISHED;
538 case TLS_ST_SW_HELLO_REQ:
539 st->hand_state = TLS_ST_OK;
540 return WRITE_TRAN_CONTINUE;
542 case TLS_ST_SR_CLNT_HELLO:
543 if (SSL_IS_DTLS(s) && !s->d1->cookie_verified
544 && (SSL_get_options(s) & SSL_OP_COOKIE_EXCHANGE))
545 st->hand_state = DTLS_ST_SW_HELLO_VERIFY_REQUEST;
547 st->hand_state = TLS_ST_SW_SRVR_HELLO;
548 return WRITE_TRAN_CONTINUE;
550 case DTLS_ST_SW_HELLO_VERIFY_REQUEST:
551 return WRITE_TRAN_FINISHED;
553 case TLS_ST_SW_SRVR_HELLO:
555 if (s->ext.ticket_expected)
556 st->hand_state = TLS_ST_SW_SESSION_TICKET;
558 st->hand_state = TLS_ST_SW_CHANGE;
560 /* Check if it is anon DH or anon ECDH, */
561 /* normal PSK or SRP */
562 if (!(s->s3->tmp.new_cipher->algorithm_auth &
563 (SSL_aNULL | SSL_aSRP | SSL_aPSK))) {
564 st->hand_state = TLS_ST_SW_CERT;
565 } else if (send_server_key_exchange(s)) {
566 st->hand_state = TLS_ST_SW_KEY_EXCH;
567 } else if (send_certificate_request(s)) {
568 st->hand_state = TLS_ST_SW_CERT_REQ;
570 st->hand_state = TLS_ST_SW_SRVR_DONE;
573 return WRITE_TRAN_CONTINUE;
576 if (s->ext.status_expected) {
577 st->hand_state = TLS_ST_SW_CERT_STATUS;
578 return WRITE_TRAN_CONTINUE;
582 case TLS_ST_SW_CERT_STATUS:
583 if (send_server_key_exchange(s)) {
584 st->hand_state = TLS_ST_SW_KEY_EXCH;
585 return WRITE_TRAN_CONTINUE;
589 case TLS_ST_SW_KEY_EXCH:
590 if (send_certificate_request(s)) {
591 st->hand_state = TLS_ST_SW_CERT_REQ;
592 return WRITE_TRAN_CONTINUE;
596 case TLS_ST_SW_CERT_REQ:
597 st->hand_state = TLS_ST_SW_SRVR_DONE;
598 return WRITE_TRAN_CONTINUE;
600 case TLS_ST_SW_SRVR_DONE:
601 return WRITE_TRAN_FINISHED;
603 case TLS_ST_SR_FINISHED:
605 st->hand_state = TLS_ST_OK;
606 return WRITE_TRAN_CONTINUE;
607 } else if (s->ext.ticket_expected) {
608 st->hand_state = TLS_ST_SW_SESSION_TICKET;
610 st->hand_state = TLS_ST_SW_CHANGE;
612 return WRITE_TRAN_CONTINUE;
614 case TLS_ST_SW_SESSION_TICKET:
615 st->hand_state = TLS_ST_SW_CHANGE;
616 return WRITE_TRAN_CONTINUE;
618 case TLS_ST_SW_CHANGE:
619 st->hand_state = TLS_ST_SW_FINISHED;
620 return WRITE_TRAN_CONTINUE;
622 case TLS_ST_SW_FINISHED:
624 return WRITE_TRAN_FINISHED;
626 st->hand_state = TLS_ST_OK;
627 return WRITE_TRAN_CONTINUE;
632 * Perform any pre work that needs to be done prior to sending a message from
633 * the server to the client.
635 WORK_STATE ossl_statem_server_pre_work(SSL *s, WORK_STATE wst)
637 OSSL_STATEM *st = &s->statem;
639 switch (st->hand_state) {
641 /* No pre work to be done */
644 case TLS_ST_SW_HELLO_REQ:
647 dtls1_clear_sent_buffer(s);
650 case DTLS_ST_SW_HELLO_VERIFY_REQUEST:
652 if (SSL_IS_DTLS(s)) {
653 dtls1_clear_sent_buffer(s);
654 /* We don't buffer this message so don't use the timer */
659 case TLS_ST_SW_SRVR_HELLO:
660 if (SSL_IS_DTLS(s)) {
662 * Messages we write from now on should be bufferred and
663 * retransmitted if necessary, so we need to use the timer now
669 case TLS_ST_SW_SRVR_DONE:
670 #ifndef OPENSSL_NO_SCTP
671 if (SSL_IS_DTLS(s) && BIO_dgram_is_sctp(SSL_get_wbio(s)))
672 return dtls_wait_for_dry(s);
674 return WORK_FINISHED_CONTINUE;
676 case TLS_ST_SW_SESSION_TICKET:
677 if (SSL_IS_TLS13(s)) {
679 * Actually this is the end of the handshake, but we're going
680 * straight into writing the session ticket out. So we finish off
681 * the handshake, but keep the various buffers active.
683 return tls_finish_handshake(s, wst, 0);
684 } if (SSL_IS_DTLS(s)) {
686 * We're into the last flight. We don't retransmit the last flight
687 * unless we need to, so we don't use the timer
693 case TLS_ST_SW_CHANGE:
694 s->session->cipher = s->s3->tmp.new_cipher;
695 if (!s->method->ssl3_enc->setup_key_block(s)) {
696 ossl_statem_set_error(s);
699 if (SSL_IS_DTLS(s)) {
701 * We're into the last flight. We don't retransmit the last flight
702 * unless we need to, so we don't use the timer. This might have
703 * already been set to 0 if we sent a NewSessionTicket message,
704 * but we'll set it again here in case we didn't.
708 return WORK_FINISHED_CONTINUE;
710 case TLS_ST_EARLY_DATA:
712 return tls_finish_handshake(s, wst, 1);
715 return WORK_FINISHED_CONTINUE;
719 * Perform any work that needs to be done after sending a message from the
720 * server to the client.
722 WORK_STATE ossl_statem_server_post_work(SSL *s, WORK_STATE wst)
724 OSSL_STATEM *st = &s->statem;
728 switch (st->hand_state) {
730 /* No post work to be done */
733 case TLS_ST_SW_HELLO_RETRY_REQUEST:
734 if (statem_flush(s) != 1)
738 case TLS_ST_SW_HELLO_REQ:
739 if (statem_flush(s) != 1)
741 if (!ssl3_init_finished_mac(s)) {
742 ossl_statem_set_error(s);
747 case DTLS_ST_SW_HELLO_VERIFY_REQUEST:
748 if (statem_flush(s) != 1)
750 /* HelloVerifyRequest resets Finished MAC */
751 if (s->version != DTLS1_BAD_VER && !ssl3_init_finished_mac(s)) {
752 ossl_statem_set_error(s);
756 * The next message should be another ClientHello which we need to
757 * treat like it was the first packet
762 case TLS_ST_SW_SRVR_HELLO:
763 #ifndef OPENSSL_NO_SCTP
764 if (SSL_IS_DTLS(s) && s->hit) {
765 unsigned char sctpauthkey[64];
766 char labelbuffer[sizeof(DTLS1_SCTP_AUTH_LABEL)];
769 * Add new shared key for SCTP-Auth, will be ignored if no
772 memcpy(labelbuffer, DTLS1_SCTP_AUTH_LABEL,
773 sizeof(DTLS1_SCTP_AUTH_LABEL));
775 if (SSL_export_keying_material(s, sctpauthkey,
776 sizeof(sctpauthkey), labelbuffer,
777 sizeof(labelbuffer), NULL, 0,
779 ossl_statem_set_error(s);
783 BIO_ctrl(SSL_get_wbio(s), BIO_CTRL_DGRAM_SCTP_ADD_AUTH_KEY,
784 sizeof(sctpauthkey), sctpauthkey);
788 * TODO(TLS1.3): This actually causes a problem. We don't yet know
789 * whether the next record we are going to receive is an unencrypted
790 * alert, or an encrypted handshake message. We're going to need
791 * something clever in the record layer for this.
793 if (SSL_IS_TLS13(s)) {
794 if (!s->method->ssl3_enc->setup_key_block(s)
795 || !s->method->ssl3_enc->change_cipher_state(s,
796 SSL3_CC_HANDSHAKE | SSL3_CHANGE_CIPHER_SERVER_WRITE))
799 if (s->ext.early_data != SSL_EARLY_DATA_ACCEPTED
800 && !s->method->ssl3_enc->change_cipher_state(s,
801 SSL3_CC_HANDSHAKE |SSL3_CHANGE_CIPHER_SERVER_READ))
806 case TLS_ST_SW_CHANGE:
807 #ifndef OPENSSL_NO_SCTP
808 if (SSL_IS_DTLS(s) && !s->hit) {
810 * Change to new shared key of SCTP-Auth, will be ignored if
813 BIO_ctrl(SSL_get_wbio(s), BIO_CTRL_DGRAM_SCTP_NEXT_AUTH_KEY,
817 if (!s->method->ssl3_enc->change_cipher_state(s,
818 SSL3_CHANGE_CIPHER_SERVER_WRITE))
820 ossl_statem_set_error(s);
825 dtls1_reset_seq_numbers(s, SSL3_CC_WRITE);
828 case TLS_ST_SW_SRVR_DONE:
829 if (statem_flush(s) != 1)
833 case TLS_ST_SW_FINISHED:
834 if (statem_flush(s) != 1)
836 #ifndef OPENSSL_NO_SCTP
837 if (SSL_IS_DTLS(s) && s->hit) {
839 * Change to new shared key of SCTP-Auth, will be ignored if
842 BIO_ctrl(SSL_get_wbio(s), BIO_CTRL_DGRAM_SCTP_NEXT_AUTH_KEY,
846 if (SSL_IS_TLS13(s)) {
847 if (!s->method->ssl3_enc->generate_master_secret(s,
848 s->master_secret, s->handshake_secret, 0,
849 &s->session->master_key_length)
850 || !s->method->ssl3_enc->change_cipher_state(s,
851 SSL3_CC_APPLICATION | SSL3_CHANGE_CIPHER_SERVER_WRITE))
856 case TLS_ST_SW_KEY_UPDATE:
857 if (statem_flush(s) != 1)
859 if (!tls13_update_key(s, 1))
863 case TLS_ST_SW_SESSION_TICKET:
864 if (SSL_IS_TLS13(s) && statem_flush(s) != 1)
869 return WORK_FINISHED_CONTINUE;
873 * Get the message construction function and message type for sending from the
876 * Valid return values are:
880 int ossl_statem_server_construct_message(SSL *s, WPACKET *pkt,
881 confunc_f *confunc, int *mt)
883 OSSL_STATEM *st = &s->statem;
885 switch (st->hand_state) {
887 /* Shouldn't happen */
890 case TLS_ST_SW_CHANGE:
892 *confunc = dtls_construct_change_cipher_spec;
894 *confunc = tls_construct_change_cipher_spec;
895 *mt = SSL3_MT_CHANGE_CIPHER_SPEC;
898 case DTLS_ST_SW_HELLO_VERIFY_REQUEST:
899 *confunc = dtls_construct_hello_verify_request;
900 *mt = DTLS1_MT_HELLO_VERIFY_REQUEST;
903 case TLS_ST_SW_HELLO_REQ:
904 /* No construction function needed */
906 *mt = SSL3_MT_HELLO_REQUEST;
909 case TLS_ST_SW_SRVR_HELLO:
910 *confunc = tls_construct_server_hello;
911 *mt = SSL3_MT_SERVER_HELLO;
915 *confunc = tls_construct_server_certificate;
916 *mt = SSL3_MT_CERTIFICATE;
919 case TLS_ST_SW_CERT_VRFY:
920 *confunc = tls_construct_cert_verify;
921 *mt = SSL3_MT_CERTIFICATE_VERIFY;
925 case TLS_ST_SW_KEY_EXCH:
926 *confunc = tls_construct_server_key_exchange;
927 *mt = SSL3_MT_SERVER_KEY_EXCHANGE;
930 case TLS_ST_SW_CERT_REQ:
931 *confunc = tls_construct_certificate_request;
932 *mt = SSL3_MT_CERTIFICATE_REQUEST;
935 case TLS_ST_SW_SRVR_DONE:
936 *confunc = tls_construct_server_done;
937 *mt = SSL3_MT_SERVER_DONE;
940 case TLS_ST_SW_SESSION_TICKET:
941 *confunc = tls_construct_new_session_ticket;
942 *mt = SSL3_MT_NEWSESSION_TICKET;
945 case TLS_ST_SW_CERT_STATUS:
946 *confunc = tls_construct_cert_status;
947 *mt = SSL3_MT_CERTIFICATE_STATUS;
950 case TLS_ST_SW_FINISHED:
951 *confunc = tls_construct_finished;
952 *mt = SSL3_MT_FINISHED;
955 case TLS_ST_SW_ENCRYPTED_EXTENSIONS:
956 *confunc = tls_construct_encrypted_extensions;
957 *mt = SSL3_MT_ENCRYPTED_EXTENSIONS;
960 case TLS_ST_SW_HELLO_RETRY_REQUEST:
961 *confunc = tls_construct_hello_retry_request;
962 *mt = SSL3_MT_HELLO_RETRY_REQUEST;
965 case TLS_ST_SW_KEY_UPDATE:
966 *confunc = tls_construct_key_update;
967 *mt = SSL3_MT_KEY_UPDATE;
975 * Maximum size (excluding the Handshake header) of a ClientHello message,
976 * calculated as follows:
978 * 2 + # client_version
979 * 32 + # only valid length for random
980 * 1 + # length of session_id
981 * 32 + # maximum size for session_id
982 * 2 + # length of cipher suites
983 * 2^16-2 + # maximum length of cipher suites array
984 * 1 + # length of compression_methods
985 * 2^8-1 + # maximum length of compression methods
986 * 2 + # length of extensions
987 * 2^16-1 # maximum length of extensions
989 #define CLIENT_HELLO_MAX_LENGTH 131396
991 #define CLIENT_KEY_EXCH_MAX_LENGTH 2048
992 #define NEXT_PROTO_MAX_LENGTH 514
995 * Returns the maximum allowed length for the current message that we are
996 * reading. Excludes the message header.
998 size_t ossl_statem_server_max_message_size(SSL *s)
1000 OSSL_STATEM *st = &s->statem;
1002 switch (st->hand_state) {
1004 /* Shouldn't happen */
1007 case TLS_ST_SR_CLNT_HELLO:
1008 return CLIENT_HELLO_MAX_LENGTH;
1010 case TLS_ST_SR_CERT:
1011 return s->max_cert_list;
1013 case TLS_ST_SR_KEY_EXCH:
1014 return CLIENT_KEY_EXCH_MAX_LENGTH;
1016 case TLS_ST_SR_CERT_VRFY:
1017 return SSL3_RT_MAX_PLAIN_LENGTH;
1019 #ifndef OPENSSL_NO_NEXTPROTONEG
1020 case TLS_ST_SR_NEXT_PROTO:
1021 return NEXT_PROTO_MAX_LENGTH;
1024 case TLS_ST_SR_CHANGE:
1025 return CCS_MAX_LENGTH;
1027 case TLS_ST_SR_FINISHED:
1028 return FINISHED_MAX_LENGTH;
1030 case TLS_ST_SR_KEY_UPDATE:
1031 return KEY_UPDATE_MAX_LENGTH;
1036 * Process a message that the server has received from the client.
1038 MSG_PROCESS_RETURN ossl_statem_server_process_message(SSL *s, PACKET *pkt)
1040 OSSL_STATEM *st = &s->statem;
1042 switch (st->hand_state) {
1044 /* Shouldn't happen */
1045 return MSG_PROCESS_ERROR;
1047 case TLS_ST_SR_CLNT_HELLO:
1048 return tls_process_client_hello(s, pkt);
1050 case TLS_ST_SR_CERT:
1051 return tls_process_client_certificate(s, pkt);
1053 case TLS_ST_SR_KEY_EXCH:
1054 return tls_process_client_key_exchange(s, pkt);
1056 case TLS_ST_SR_CERT_VRFY:
1057 return tls_process_cert_verify(s, pkt);
1059 #ifndef OPENSSL_NO_NEXTPROTONEG
1060 case TLS_ST_SR_NEXT_PROTO:
1061 return tls_process_next_proto(s, pkt);
1064 case TLS_ST_SR_CHANGE:
1065 return tls_process_change_cipher_spec(s, pkt);
1067 case TLS_ST_SR_FINISHED:
1068 return tls_process_finished(s, pkt);
1070 case TLS_ST_SR_KEY_UPDATE:
1071 return tls_process_key_update(s, pkt);
1077 * Perform any further processing required following the receipt of a message
1080 WORK_STATE ossl_statem_server_post_process_message(SSL *s, WORK_STATE wst)
1082 OSSL_STATEM *st = &s->statem;
1084 switch (st->hand_state) {
1086 /* Shouldn't happen */
1089 case TLS_ST_SR_CLNT_HELLO:
1090 return tls_post_process_client_hello(s, wst);
1092 case TLS_ST_SR_KEY_EXCH:
1093 return tls_post_process_client_key_exchange(s, wst);
1095 case TLS_ST_SR_CERT_VRFY:
1096 #ifndef OPENSSL_NO_SCTP
1097 if ( /* Is this SCTP? */
1098 BIO_dgram_is_sctp(SSL_get_wbio(s))
1099 /* Are we renegotiating? */
1100 && s->renegotiate && BIO_dgram_sctp_msg_waiting(SSL_get_rbio(s))) {
1101 s->s3->in_read_app_data = 2;
1102 s->rwstate = SSL_READING;
1103 BIO_clear_retry_flags(SSL_get_rbio(s));
1104 BIO_set_retry_read(SSL_get_rbio(s));
1105 ossl_statem_set_sctp_read_sock(s, 1);
1108 ossl_statem_set_sctp_read_sock(s, 0);
1111 return WORK_FINISHED_CONTINUE;
1113 return WORK_FINISHED_CONTINUE;
1116 int ossl_statem_finish_early_data(SSL *s)
1118 if (!s->method->ssl3_enc->change_cipher_state(s,
1119 SSL3_CC_HANDSHAKE | SSL3_CHANGE_CIPHER_SERVER_READ))
1125 #ifndef OPENSSL_NO_SRP
1126 static int ssl_check_srp_ext_ClientHello(SSL *s, int *al)
1128 int ret = SSL_ERROR_NONE;
1130 *al = SSL_AD_UNRECOGNIZED_NAME;
1132 if ((s->s3->tmp.new_cipher->algorithm_mkey & SSL_kSRP) &&
1133 (s->srp_ctx.TLS_ext_srp_username_callback != NULL)) {
1134 if (s->srp_ctx.login == NULL) {
1136 * RFC 5054 says SHOULD reject, we do so if There is no srp
1139 ret = SSL3_AL_FATAL;
1140 *al = SSL_AD_UNKNOWN_PSK_IDENTITY;
1142 ret = SSL_srp_server_param_with_username(s, al);
1149 int dtls_raw_hello_verify_request(WPACKET *pkt, unsigned char *cookie,
1152 /* Always use DTLS 1.0 version: see RFC 6347 */
1153 if (!WPACKET_put_bytes_u16(pkt, DTLS1_VERSION)
1154 || !WPACKET_sub_memcpy_u8(pkt, cookie, cookie_len))
1160 int dtls_construct_hello_verify_request(SSL *s, WPACKET *pkt)
1162 unsigned int cookie_leni;
1163 if (s->ctx->app_gen_cookie_cb == NULL ||
1164 s->ctx->app_gen_cookie_cb(s, s->d1->cookie,
1165 &cookie_leni) == 0 ||
1166 cookie_leni > 255) {
1167 SSLerr(SSL_F_DTLS_CONSTRUCT_HELLO_VERIFY_REQUEST,
1168 SSL_R_COOKIE_GEN_CALLBACK_FAILURE);
1171 s->d1->cookie_len = cookie_leni;
1173 if (!dtls_raw_hello_verify_request(pkt, s->d1->cookie,
1174 s->d1->cookie_len)) {
1175 SSLerr(SSL_F_DTLS_CONSTRUCT_HELLO_VERIFY_REQUEST, ERR_R_INTERNAL_ERROR);
1182 #ifndef OPENSSL_NO_EC
1184 * ssl_check_for_safari attempts to fingerprint Safari using OS X
1185 * SecureTransport using the TLS extension block in |hello|.
1186 * Safari, since 10.6, sends exactly these extensions, in this order:
1191 * We wish to fingerprint Safari because they broke ECDHE-ECDSA support in 10.8,
1192 * but they advertise support. So enabling ECDHE-ECDSA ciphers breaks them.
1193 * Sadly we cannot differentiate 10.6, 10.7 and 10.8.4 (which work), from
1194 * 10.8..10.8.3 (which don't work).
1196 static void ssl_check_for_safari(SSL *s, const CLIENTHELLO_MSG *hello)
1198 static const unsigned char kSafariExtensionsBlock[] = {
1199 0x00, 0x0a, /* elliptic_curves extension */
1200 0x00, 0x08, /* 8 bytes */
1201 0x00, 0x06, /* 6 bytes of curve ids */
1202 0x00, 0x17, /* P-256 */
1203 0x00, 0x18, /* P-384 */
1204 0x00, 0x19, /* P-521 */
1206 0x00, 0x0b, /* ec_point_formats */
1207 0x00, 0x02, /* 2 bytes */
1208 0x01, /* 1 point format */
1209 0x00, /* uncompressed */
1210 /* The following is only present in TLS 1.2 */
1211 0x00, 0x0d, /* signature_algorithms */
1212 0x00, 0x0c, /* 12 bytes */
1213 0x00, 0x0a, /* 10 bytes */
1214 0x05, 0x01, /* SHA-384/RSA */
1215 0x04, 0x01, /* SHA-256/RSA */
1216 0x02, 0x01, /* SHA-1/RSA */
1217 0x04, 0x03, /* SHA-256/ECDSA */
1218 0x02, 0x03, /* SHA-1/ECDSA */
1220 /* Length of the common prefix (first two extensions). */
1221 static const size_t kSafariCommonExtensionsLength = 18;
1226 tmppkt = hello->extensions;
1228 if (!PACKET_forward(&tmppkt, 2)
1229 || !PACKET_get_net_2(&tmppkt, &type)
1230 || !PACKET_get_length_prefixed_2(&tmppkt, &sni)) {
1234 if (type != TLSEXT_TYPE_server_name)
1237 ext_len = TLS1_get_client_version(s) >= TLS1_2_VERSION ?
1238 sizeof(kSafariExtensionsBlock) : kSafariCommonExtensionsLength;
1240 s->s3->is_probably_safari = PACKET_equal(&tmppkt, kSafariExtensionsBlock,
1243 #endif /* !OPENSSL_NO_EC */
1245 MSG_PROCESS_RETURN tls_process_client_hello(SSL *s, PACKET *pkt)
1247 int al = SSL_AD_INTERNAL_ERROR;
1248 /* |cookie| will only be initialized for DTLS. */
1249 PACKET session_id, compression, extensions, cookie;
1250 static const unsigned char null_compression = 0;
1251 CLIENTHELLO_MSG *clienthello;
1253 clienthello = OPENSSL_zalloc(sizeof(*clienthello));
1254 if (clienthello == NULL) {
1255 SSLerr(SSL_F_TLS_PROCESS_CLIENT_HELLO, ERR_R_INTERNAL_ERROR);
1258 /* Check if this is actually an unexpected renegotiation ClientHello */
1259 if (s->renegotiate == 0 && !SSL_IS_FIRST_HANDSHAKE(s)) {
1265 * First, parse the raw ClientHello data into the CLIENTHELLO_MSG structure.
1267 clienthello->isv2 = RECORD_LAYER_is_sslv2_record(&s->rlayer);
1268 PACKET_null_init(&cookie);
1270 if (clienthello->isv2) {
1273 if (!SSL_IS_FIRST_HANDSHAKE(s) || s->hello_retry_request) {
1274 al = SSL_AD_HANDSHAKE_FAILURE;
1275 SSLerr(SSL_F_TLS_PROCESS_CLIENT_HELLO, SSL_R_UNEXPECTED_MESSAGE);
1280 * An SSLv3/TLSv1 backwards-compatible CLIENT-HELLO in an SSLv2
1281 * header is sent directly on the wire, not wrapped as a TLS
1282 * record. Our record layer just processes the message length and passes
1283 * the rest right through. Its format is:
1285 * 0-1 msg_length - decoded by the record layer
1286 * 2 msg_type - s->init_msg points here
1288 * 5-6 cipher_spec_length
1289 * 7-8 session_id_length
1290 * 9-10 challenge_length
1294 if (!PACKET_get_1(pkt, &mt)
1295 || mt != SSL2_MT_CLIENT_HELLO) {
1297 * Should never happen. We should have tested this in the record
1298 * layer in order to have determined that this is a SSLv2 record
1299 * in the first place
1301 SSLerr(SSL_F_TLS_PROCESS_CLIENT_HELLO, ERR_R_INTERNAL_ERROR);
1306 if (!PACKET_get_net_2(pkt, &clienthello->legacy_version)) {
1307 al = SSL_AD_DECODE_ERROR;
1308 SSLerr(SSL_F_TLS_PROCESS_CLIENT_HELLO, SSL_R_LENGTH_TOO_SHORT);
1312 /* Parse the message and load client random. */
1313 if (clienthello->isv2) {
1315 * Handle an SSLv2 backwards compatible ClientHello
1316 * Note, this is only for SSLv3+ using the backward compatible format.
1317 * Real SSLv2 is not supported, and is rejected below.
1319 unsigned int ciphersuite_len, session_id_len, challenge_len;
1322 if (!PACKET_get_net_2(pkt, &ciphersuite_len)
1323 || !PACKET_get_net_2(pkt, &session_id_len)
1324 || !PACKET_get_net_2(pkt, &challenge_len)) {
1325 SSLerr(SSL_F_TLS_PROCESS_CLIENT_HELLO,
1326 SSL_R_RECORD_LENGTH_MISMATCH);
1327 al = SSL_AD_DECODE_ERROR;
1331 if (session_id_len > SSL_MAX_SSL_SESSION_ID_LENGTH) {
1332 al = SSL_AD_DECODE_ERROR;
1333 SSLerr(SSL_F_TLS_PROCESS_CLIENT_HELLO, SSL_R_LENGTH_MISMATCH);
1337 if (!PACKET_get_sub_packet(pkt, &clienthello->ciphersuites,
1339 || !PACKET_copy_bytes(pkt, clienthello->session_id, session_id_len)
1340 || !PACKET_get_sub_packet(pkt, &challenge, challenge_len)
1341 /* No extensions. */
1342 || PACKET_remaining(pkt) != 0) {
1343 SSLerr(SSL_F_TLS_PROCESS_CLIENT_HELLO,
1344 SSL_R_RECORD_LENGTH_MISMATCH);
1345 al = SSL_AD_DECODE_ERROR;
1348 clienthello->session_id_len = session_id_len;
1350 /* Load the client random and compression list. We use SSL3_RANDOM_SIZE
1351 * here rather than sizeof(clienthello->random) because that is the limit
1352 * for SSLv3 and it is fixed. It won't change even if
1353 * sizeof(clienthello->random) does.
1355 challenge_len = challenge_len > SSL3_RANDOM_SIZE
1356 ? SSL3_RANDOM_SIZE : challenge_len;
1357 memset(clienthello->random, 0, SSL3_RANDOM_SIZE);
1358 if (!PACKET_copy_bytes(&challenge,
1359 clienthello->random + SSL3_RANDOM_SIZE -
1360 challenge_len, challenge_len)
1361 /* Advertise only null compression. */
1362 || !PACKET_buf_init(&compression, &null_compression, 1)) {
1363 SSLerr(SSL_F_TLS_PROCESS_CLIENT_HELLO, ERR_R_INTERNAL_ERROR);
1364 al = SSL_AD_INTERNAL_ERROR;
1368 PACKET_null_init(&clienthello->extensions);
1370 /* Regular ClientHello. */
1371 if (!PACKET_copy_bytes(pkt, clienthello->random, SSL3_RANDOM_SIZE)
1372 || !PACKET_get_length_prefixed_1(pkt, &session_id)
1373 || !PACKET_copy_all(&session_id, clienthello->session_id,
1374 SSL_MAX_SSL_SESSION_ID_LENGTH,
1375 &clienthello->session_id_len)) {
1376 al = SSL_AD_DECODE_ERROR;
1377 SSLerr(SSL_F_TLS_PROCESS_CLIENT_HELLO, SSL_R_LENGTH_MISMATCH);
1381 if (SSL_IS_DTLS(s)) {
1382 if (!PACKET_get_length_prefixed_1(pkt, &cookie)) {
1383 al = SSL_AD_DECODE_ERROR;
1384 SSLerr(SSL_F_TLS_PROCESS_CLIENT_HELLO, SSL_R_LENGTH_MISMATCH);
1387 if (!PACKET_copy_all(&cookie, clienthello->dtls_cookie,
1388 DTLS1_COOKIE_LENGTH,
1389 &clienthello->dtls_cookie_len)) {
1390 al = SSL_AD_DECODE_ERROR;
1391 SSLerr(SSL_F_TLS_PROCESS_CLIENT_HELLO, SSL_R_LENGTH_MISMATCH);
1395 * If we require cookies and this ClientHello doesn't contain one,
1396 * just return since we do not want to allocate any memory yet.
1397 * So check cookie length...
1399 if (SSL_get_options(s) & SSL_OP_COOKIE_EXCHANGE) {
1400 if (clienthello->dtls_cookie_len == 0)
1405 if (!PACKET_get_length_prefixed_2(pkt, &clienthello->ciphersuites)) {
1406 al = SSL_AD_DECODE_ERROR;
1407 SSLerr(SSL_F_TLS_PROCESS_CLIENT_HELLO, SSL_R_LENGTH_MISMATCH);
1411 if (!PACKET_get_length_prefixed_1(pkt, &compression)) {
1412 al = SSL_AD_DECODE_ERROR;
1413 SSLerr(SSL_F_TLS_PROCESS_CLIENT_HELLO, SSL_R_LENGTH_MISMATCH);
1417 /* Could be empty. */
1418 if (PACKET_remaining(pkt) == 0) {
1419 PACKET_null_init(&clienthello->extensions);
1421 if (!PACKET_get_length_prefixed_2(pkt, &clienthello->extensions)) {
1422 al = SSL_AD_DECODE_ERROR;
1423 SSLerr(SSL_F_TLS_PROCESS_CLIENT_HELLO, SSL_R_LENGTH_MISMATCH);
1429 if (!PACKET_copy_all(&compression, clienthello->compressions,
1430 MAX_COMPRESSIONS_SIZE,
1431 &clienthello->compressions_len)) {
1432 al = SSL_AD_DECODE_ERROR;
1433 SSLerr(SSL_F_TLS_PROCESS_CLIENT_HELLO, SSL_R_LENGTH_MISMATCH);
1437 /* Preserve the raw extensions PACKET for later use */
1438 extensions = clienthello->extensions;
1439 if (!tls_collect_extensions(s, &extensions, EXT_CLIENT_HELLO,
1440 &clienthello->pre_proc_exts, &al,
1441 &clienthello->pre_proc_exts_len)) {
1442 /* SSLerr already been called */
1445 s->clienthello = clienthello;
1447 return MSG_PROCESS_CONTINUE_PROCESSING;
1449 ssl3_send_alert(s, SSL3_AL_FATAL, al);
1451 ossl_statem_set_error(s);
1453 OPENSSL_free(clienthello->pre_proc_exts);
1454 OPENSSL_free(clienthello);
1456 return MSG_PROCESS_ERROR;
1459 static int tls_early_post_process_client_hello(SSL *s, int *al)
1466 #ifndef OPENSSL_NO_COMP
1467 SSL_COMP *comp = NULL;
1469 const SSL_CIPHER *c;
1470 STACK_OF(SSL_CIPHER) *ciphers = NULL;
1471 STACK_OF(SSL_CIPHER) *scsvs = NULL;
1472 CLIENTHELLO_MSG *clienthello = s->clienthello;
1474 *al = SSL_AD_INTERNAL_ERROR;
1475 /* Finished parsing the ClientHello, now we can start processing it */
1476 /* Give the early callback a crack at things */
1477 if (s->ctx->early_cb != NULL) {
1479 /* A failure in the early callback terminates the connection. */
1480 code = s->ctx->early_cb(s, al, s->ctx->early_cb_arg);
1484 s->rwstate = SSL_EARLY_WORK;
1489 /* Set up the client_random */
1490 memcpy(s->s3->client_random, clienthello->random, SSL3_RANDOM_SIZE);
1492 /* Choose the version */
1494 if (clienthello->isv2) {
1495 if (clienthello->legacy_version == SSL2_VERSION
1496 || (clienthello->legacy_version & 0xff00)
1497 != (SSL3_VERSION_MAJOR << 8)) {
1499 * This is real SSLv2 or something complete unknown. We don't
1502 SSLerr(SSL_F_TLS_EARLY_POST_PROCESS_CLIENT_HELLO, SSL_R_UNKNOWN_PROTOCOL);
1506 s->client_version = clienthello->legacy_version;
1509 * Do SSL/TLS version negotiation if applicable. For DTLS we just check
1510 * versions are potentially compatible. Version negotiation comes later.
1512 if (!SSL_IS_DTLS(s)) {
1513 protverr = ssl_choose_server_version(s, clienthello);
1514 } else if (s->method->version != DTLS_ANY_VERSION &&
1515 DTLS_VERSION_LT((int)clienthello->legacy_version, s->version)) {
1516 protverr = SSL_R_VERSION_TOO_LOW;
1522 SSLerr(SSL_F_TLS_EARLY_POST_PROCESS_CLIENT_HELLO, protverr);
1523 if (SSL_IS_FIRST_HANDSHAKE(s)) {
1524 /* like ssl3_get_record, send alert using remote version number */
1525 s->version = s->client_version = clienthello->legacy_version;
1527 *al = SSL_AD_PROTOCOL_VERSION;
1531 if (SSL_IS_DTLS(s)) {
1532 /* Empty cookie was already handled above by returning early. */
1533 if (SSL_get_options(s) & SSL_OP_COOKIE_EXCHANGE) {
1534 if (s->ctx->app_verify_cookie_cb != NULL) {
1535 if (s->ctx->app_verify_cookie_cb(s, clienthello->dtls_cookie,
1536 clienthello->dtls_cookie_len) == 0) {
1537 *al = SSL_AD_HANDSHAKE_FAILURE;
1538 SSLerr(SSL_F_TLS_EARLY_POST_PROCESS_CLIENT_HELLO,
1539 SSL_R_COOKIE_MISMATCH);
1541 /* else cookie verification succeeded */
1543 /* default verification */
1544 } else if (s->d1->cookie_len != clienthello->dtls_cookie_len
1545 || memcmp(clienthello->dtls_cookie, s->d1->cookie,
1546 s->d1->cookie_len) != 0) {
1547 *al = SSL_AD_HANDSHAKE_FAILURE;
1548 SSLerr(SSL_F_TLS_EARLY_POST_PROCESS_CLIENT_HELLO, SSL_R_COOKIE_MISMATCH);
1551 s->d1->cookie_verified = 1;
1553 if (s->method->version == DTLS_ANY_VERSION) {
1554 protverr = ssl_choose_server_version(s, clienthello);
1555 if (protverr != 0) {
1556 SSLerr(SSL_F_TLS_EARLY_POST_PROCESS_CLIENT_HELLO, protverr);
1557 s->version = s->client_version;
1558 *al = SSL_AD_PROTOCOL_VERSION;
1566 /* We need to do this before getting the session */
1567 if (!tls_parse_extension(s, TLSEXT_IDX_extended_master_secret,
1569 clienthello->pre_proc_exts, NULL, 0, al)) {
1570 SSLerr(SSL_F_TLS_EARLY_POST_PROCESS_CLIENT_HELLO, SSL_R_CLIENTHELLO_TLSEXT);
1575 * We don't allow resumption in a backwards compatible ClientHello.
1576 * TODO(openssl-team): in TLS1.1+, session_id MUST be empty.
1578 * Versions before 0.9.7 always allow clients to resume sessions in
1579 * renegotiation. 0.9.7 and later allow this by default, but optionally
1580 * ignore resumption requests with flag
1581 * SSL_OP_NO_SESSION_RESUMPTION_ON_RENEGOTIATION (it's a new flag rather
1582 * than a change to default behavior so that applications relying on
1583 * this for security won't even compile against older library versions).
1584 * 1.0.1 and later also have a function SSL_renegotiate_abbreviated() to
1585 * request renegotiation but not a new session (s->new_session remains
1586 * unset): for servers, this essentially just means that the
1587 * SSL_OP_NO_SESSION_RESUMPTION_ON_RENEGOTIATION setting will be
1590 if (clienthello->isv2 ||
1592 (s->options & SSL_OP_NO_SESSION_RESUMPTION_ON_RENEGOTIATION))) {
1593 if (!ssl_get_new_session(s, 1))
1596 i = ssl_get_prev_session(s, clienthello, al);
1598 /* previous session */
1600 } else if (i == -1) {
1604 if (!ssl_get_new_session(s, 1))
1609 if (!ssl_cache_cipherlist(s, &clienthello->ciphersuites,
1610 clienthello->isv2, al) ||
1611 !bytes_to_cipher_list(s, &clienthello->ciphersuites, &ciphers, &scsvs,
1612 clienthello->isv2, al)) {
1616 s->s3->send_connection_binding = 0;
1617 /* Check what signalling cipher-suite values were received. */
1618 if (scsvs != NULL) {
1619 for(i = 0; i < sk_SSL_CIPHER_num(scsvs); i++) {
1620 c = sk_SSL_CIPHER_value(scsvs, i);
1621 if (SSL_CIPHER_get_id(c) == SSL3_CK_SCSV) {
1622 if (s->renegotiate) {
1623 /* SCSV is fatal if renegotiating */
1624 SSLerr(SSL_F_TLS_EARLY_POST_PROCESS_CLIENT_HELLO,
1625 SSL_R_SCSV_RECEIVED_WHEN_RENEGOTIATING);
1626 *al = SSL_AD_HANDSHAKE_FAILURE;
1629 s->s3->send_connection_binding = 1;
1630 } else if (SSL_CIPHER_get_id(c) == SSL3_CK_FALLBACK_SCSV &&
1631 !ssl_check_version_downgrade(s)) {
1633 * This SCSV indicates that the client previously tried
1634 * a higher version. We should fail if the current version
1635 * is an unexpected downgrade, as that indicates that the first
1636 * connection may have been tampered with in order to trigger
1637 * an insecure downgrade.
1639 SSLerr(SSL_F_TLS_EARLY_POST_PROCESS_CLIENT_HELLO,
1640 SSL_R_INAPPROPRIATE_FALLBACK);
1641 *al = SSL_AD_INAPPROPRIATE_FALLBACK;
1647 /* If it is a hit, check that the cipher is in the list */
1650 id = s->session->cipher->id;
1653 fprintf(stderr, "client sent %d ciphers\n", sk_SSL_CIPHER_num(ciphers));
1655 for (i = 0; i < sk_SSL_CIPHER_num(ciphers); i++) {
1656 c = sk_SSL_CIPHER_value(ciphers, i);
1658 fprintf(stderr, "client [%2d of %2d]:%s\n",
1659 i, sk_SSL_CIPHER_num(ciphers), SSL_CIPHER_get_name(c));
1668 * we need to have the cipher in the cipher list if we are asked
1671 *al = SSL_AD_ILLEGAL_PARAMETER;
1672 SSLerr(SSL_F_TLS_EARLY_POST_PROCESS_CLIENT_HELLO,
1673 SSL_R_REQUIRED_CIPHER_MISSING);
1678 for (loop = 0; loop < clienthello->compressions_len; loop++) {
1679 if (clienthello->compressions[loop] == 0)
1683 if (loop >= clienthello->compressions_len) {
1685 *al = SSL_AD_DECODE_ERROR;
1686 SSLerr(SSL_F_TLS_EARLY_POST_PROCESS_CLIENT_HELLO, SSL_R_NO_COMPRESSION_SPECIFIED);
1690 #ifndef OPENSSL_NO_EC
1691 if (s->options & SSL_OP_SAFARI_ECDHE_ECDSA_BUG)
1692 ssl_check_for_safari(s, clienthello);
1693 #endif /* !OPENSSL_NO_EC */
1695 /* TLS extensions */
1696 if (!tls_parse_all_extensions(s, EXT_CLIENT_HELLO,
1697 clienthello->pre_proc_exts, NULL, 0, al)) {
1698 SSLerr(SSL_F_TLS_EARLY_POST_PROCESS_CLIENT_HELLO, SSL_R_PARSE_TLSEXT);
1703 * Check if we want to use external pre-shared secret for this handshake
1704 * for not reused session only. We need to generate server_random before
1705 * calling tls_session_secret_cb in order to allow SessionTicket
1706 * processing to use it in key derivation.
1710 pos = s->s3->server_random;
1711 if (ssl_fill_hello_random(s, 1, pos, SSL3_RANDOM_SIZE) <= 0) {
1716 if (!s->hit && s->version >= TLS1_VERSION && s->ext.session_secret_cb) {
1717 const SSL_CIPHER *pref_cipher = NULL;
1719 * s->session->master_key_length is a size_t, but this is an int for
1720 * backwards compat reasons
1722 int master_key_length;
1724 master_key_length = sizeof(s->session->master_key);
1725 if (s->ext.session_secret_cb(s, s->session->master_key,
1726 &master_key_length, ciphers,
1728 s->ext.session_secret_cb_arg)
1729 && master_key_length > 0) {
1730 s->session->master_key_length = master_key_length;
1732 s->session->ciphers = ciphers;
1733 s->session->verify_result = X509_V_OK;
1737 /* check if some cipher was preferred by call back */
1738 if (pref_cipher == NULL)
1739 pref_cipher = ssl3_choose_cipher(s, s->session->ciphers,
1740 SSL_get_ciphers(s));
1741 if (pref_cipher == NULL) {
1742 *al = SSL_AD_HANDSHAKE_FAILURE;
1743 SSLerr(SSL_F_TLS_EARLY_POST_PROCESS_CLIENT_HELLO, SSL_R_NO_SHARED_CIPHER);
1747 s->session->cipher = pref_cipher;
1748 sk_SSL_CIPHER_free(s->cipher_list);
1749 s->cipher_list = sk_SSL_CIPHER_dup(s->session->ciphers);
1750 sk_SSL_CIPHER_free(s->cipher_list_by_id);
1751 s->cipher_list_by_id = sk_SSL_CIPHER_dup(s->session->ciphers);
1756 * Worst case, we will use the NULL compression, but if we have other
1757 * options, we will now look for them. We have complen-1 compression
1758 * algorithms from the client, starting at q.
1760 s->s3->tmp.new_compression = NULL;
1761 #ifndef OPENSSL_NO_COMP
1762 /* This only happens if we have a cache hit */
1763 if (s->session->compress_meth != 0 && !SSL_IS_TLS13(s)) {
1764 int m, comp_id = s->session->compress_meth;
1766 /* Perform sanity checks on resumed compression algorithm */
1767 /* Can't disable compression */
1768 if (!ssl_allow_compression(s)) {
1769 SSLerr(SSL_F_TLS_EARLY_POST_PROCESS_CLIENT_HELLO,
1770 SSL_R_INCONSISTENT_COMPRESSION);
1773 /* Look for resumed compression method */
1774 for (m = 0; m < sk_SSL_COMP_num(s->ctx->comp_methods); m++) {
1775 comp = sk_SSL_COMP_value(s->ctx->comp_methods, m);
1776 if (comp_id == comp->id) {
1777 s->s3->tmp.new_compression = comp;
1781 if (s->s3->tmp.new_compression == NULL) {
1782 SSLerr(SSL_F_TLS_EARLY_POST_PROCESS_CLIENT_HELLO,
1783 SSL_R_INVALID_COMPRESSION_ALGORITHM);
1786 /* Look for resumed method in compression list */
1787 for (k = 0; k < clienthello->compressions_len; k++) {
1788 if (clienthello->compressions[k] == comp_id)
1791 if (k >= clienthello->compressions_len) {
1792 *al = SSL_AD_ILLEGAL_PARAMETER;
1793 SSLerr(SSL_F_TLS_EARLY_POST_PROCESS_CLIENT_HELLO,
1794 SSL_R_REQUIRED_COMPRESSION_ALGORITHM_MISSING);
1797 } else if (s->hit) {
1799 } else if (ssl_allow_compression(s) && s->ctx->comp_methods
1800 && !SSL_IS_TLS13(s)) {
1801 /* See if we have a match */
1802 int m, nn, v, done = 0;
1805 nn = sk_SSL_COMP_num(s->ctx->comp_methods);
1806 for (m = 0; m < nn; m++) {
1807 comp = sk_SSL_COMP_value(s->ctx->comp_methods, m);
1809 for (o = 0; o < clienthello->compressions_len; o++) {
1810 if (v == clienthello->compressions[o]) {
1819 s->s3->tmp.new_compression = comp;
1825 * If compression is disabled we'd better not try to resume a session
1826 * using compression.
1828 if (s->session->compress_meth != 0) {
1829 SSLerr(SSL_F_TLS_EARLY_POST_PROCESS_CLIENT_HELLO, SSL_R_INCONSISTENT_COMPRESSION);
1835 * Given s->session->ciphers and SSL_get_ciphers, we must pick a cipher
1839 #ifdef OPENSSL_NO_COMP
1840 s->session->compress_meth = 0;
1842 s->session->compress_meth = (comp == NULL) ? 0 : comp->id;
1844 sk_SSL_CIPHER_free(s->session->ciphers);
1845 s->session->ciphers = ciphers;
1846 if (ciphers == NULL) {
1847 *al = SSL_AD_INTERNAL_ERROR;
1848 SSLerr(SSL_F_TLS_EARLY_POST_PROCESS_CLIENT_HELLO, ERR_R_INTERNAL_ERROR);
1852 if (!tls1_set_server_sigalgs(s)) {
1853 SSLerr(SSL_F_TLS_EARLY_POST_PROCESS_CLIENT_HELLO, SSL_R_CLIENTHELLO_TLSEXT);
1858 sk_SSL_CIPHER_free(ciphers);
1859 sk_SSL_CIPHER_free(scsvs);
1860 OPENSSL_free(clienthello->pre_proc_exts);
1861 OPENSSL_free(s->clienthello);
1862 s->clienthello = NULL;
1865 ossl_statem_set_error(s);
1867 sk_SSL_CIPHER_free(ciphers);
1868 sk_SSL_CIPHER_free(scsvs);
1869 OPENSSL_free(clienthello->pre_proc_exts);
1870 OPENSSL_free(s->clienthello);
1871 s->clienthello = NULL;
1877 * Call the status request callback if needed. Upon success, returns 1.
1878 * Upon failure, returns 0 and sets |*al| to the appropriate fatal alert.
1880 static int tls_handle_status_request(SSL *s, int *al)
1882 s->ext.status_expected = 0;
1885 * If status request then ask callback what to do. Note: this must be
1886 * called after servername callbacks in case the certificate has changed,
1887 * and must be called after the cipher has been chosen because this may
1888 * influence which certificate is sent
1890 if (s->ext.status_type != TLSEXT_STATUSTYPE_nothing && s->ctx != NULL
1891 && s->ctx->ext.status_cb != NULL) {
1894 /* If no certificate can't return certificate status */
1895 if (s->s3->tmp.cert != NULL) {
1897 * Set current certificate to one we will use so SSL_get_certificate
1898 * et al can pick it up.
1900 s->cert->key = s->s3->tmp.cert;
1901 ret = s->ctx->ext.status_cb(s, s->ctx->ext.status_arg);
1903 /* We don't want to send a status request response */
1904 case SSL_TLSEXT_ERR_NOACK:
1905 s->ext.status_expected = 0;
1907 /* status request response should be sent */
1908 case SSL_TLSEXT_ERR_OK:
1909 if (s->ext.ocsp.resp)
1910 s->ext.status_expected = 1;
1912 /* something bad happened */
1913 case SSL_TLSEXT_ERR_ALERT_FATAL:
1915 *al = SSL_AD_INTERNAL_ERROR;
1924 WORK_STATE tls_post_process_client_hello(SSL *s, WORK_STATE wst)
1926 int al = SSL_AD_HANDSHAKE_FAILURE;
1927 const SSL_CIPHER *cipher;
1929 if (wst == WORK_MORE_A) {
1930 int rv = tls_early_post_process_client_hello(s, &al);
1932 /* SSLErr() was already called */
1939 if (wst == WORK_MORE_B) {
1941 /* Let cert callback update server certificates if required */
1942 if (s->cert->cert_cb) {
1943 int rv = s->cert->cert_cb(s, s->cert->cert_cb_arg);
1945 al = SSL_AD_INTERNAL_ERROR;
1946 SSLerr(SSL_F_TLS_POST_PROCESS_CLIENT_HELLO,
1947 SSL_R_CERT_CB_ERROR);
1951 s->rwstate = SSL_X509_LOOKUP;
1954 s->rwstate = SSL_NOTHING;
1957 ssl3_choose_cipher(s, s->session->ciphers, SSL_get_ciphers(s));
1959 if (cipher == NULL) {
1960 SSLerr(SSL_F_TLS_POST_PROCESS_CLIENT_HELLO,
1961 SSL_R_NO_SHARED_CIPHER);
1964 s->s3->tmp.new_cipher = cipher;
1965 if (!tls_choose_sigalg(s, &al))
1967 /* check whether we should disable session resumption */
1968 if (s->not_resumable_session_cb != NULL)
1969 s->session->not_resumable =
1970 s->not_resumable_session_cb(s, ((cipher->algorithm_mkey
1971 & (SSL_kDHE | SSL_kECDHE))
1973 if (s->session->not_resumable)
1974 /* do not send a session ticket */
1975 s->ext.ticket_expected = 0;
1977 /* Session-id reuse */
1978 s->s3->tmp.new_cipher = s->session->cipher;
1982 * we now have the following setup.
1984 * cipher_list - our preferred list of ciphers
1985 * ciphers - the clients preferred list of ciphers
1986 * compression - basically ignored right now
1987 * ssl version is set - sslv3
1988 * s->session - The ssl session has been setup.
1989 * s->hit - session reuse flag
1990 * s->s3->tmp.new_cipher- the new cipher to use.
1994 * Call status_request callback if needed. Has to be done after the
1995 * certificate callbacks etc above.
1997 if (!tls_handle_status_request(s, &al)) {
1998 SSLerr(SSL_F_TLS_POST_PROCESS_CLIENT_HELLO,
1999 SSL_R_CLIENTHELLO_TLSEXT);
2005 #ifndef OPENSSL_NO_SRP
2006 if (wst == WORK_MORE_C) {
2008 if ((ret = ssl_check_srp_ext_ClientHello(s, &al)) < 0) {
2010 * callback indicates further work to be done
2012 s->rwstate = SSL_X509_LOOKUP;
2015 if (ret != SSL_ERROR_NONE) {
2017 * This is not really an error but the only means to for
2018 * a client to detect whether srp is supported.
2020 if (al != TLS1_AD_UNKNOWN_PSK_IDENTITY)
2021 SSLerr(SSL_F_TLS_POST_PROCESS_CLIENT_HELLO,
2022 SSL_R_CLIENTHELLO_TLSEXT);
2024 SSLerr(SSL_F_TLS_POST_PROCESS_CLIENT_HELLO,
2025 SSL_R_PSK_IDENTITY_NOT_FOUND);
2031 return WORK_FINISHED_STOP;
2033 ssl3_send_alert(s, SSL3_AL_FATAL, al);
2034 ossl_statem_set_error(s);
2038 int tls_construct_server_hello(SSL *s, WPACKET *pkt)
2040 int compm, al = SSL_AD_INTERNAL_ERROR;
2044 /* TODO(TLS1.3): Remove the DRAFT conditional before release */
2045 version = SSL_IS_TLS13(s) ? TLS1_3_VERSION_DRAFT : s->version;
2046 if (!WPACKET_put_bytes_u16(pkt, version)
2048 * Random stuff. Filling of the server_random takes place in
2049 * tls_process_client_hello()
2051 || !WPACKET_memcpy(pkt, s->s3->server_random, SSL3_RANDOM_SIZE)) {
2052 SSLerr(SSL_F_TLS_CONSTRUCT_SERVER_HELLO, ERR_R_INTERNAL_ERROR);
2057 * There are several cases for the session ID to send
2058 * back in the server hello:
2059 * - For session reuse from the session cache,
2060 * we send back the old session ID.
2061 * - If stateless session reuse (using a session ticket)
2062 * is successful, we send back the client's "session ID"
2063 * (which doesn't actually identify the session).
2064 * - If it is a new session, we send back the new
2066 * - However, if we want the new session to be single-use,
2067 * we send back a 0-length session ID.
2068 * s->hit is non-zero in either case of session reuse,
2069 * so the following won't overwrite an ID that we're supposed
2072 if (s->session->not_resumable ||
2073 (!(s->ctx->session_cache_mode & SSL_SESS_CACHE_SERVER)
2075 s->session->session_id_length = 0;
2077 sl = s->session->session_id_length;
2078 if (sl > sizeof(s->session->session_id)) {
2079 SSLerr(SSL_F_TLS_CONSTRUCT_SERVER_HELLO, ERR_R_INTERNAL_ERROR);
2083 /* set up the compression method */
2084 #ifdef OPENSSL_NO_COMP
2087 if (s->s3->tmp.new_compression == NULL)
2090 compm = s->s3->tmp.new_compression->id;
2093 if ((!SSL_IS_TLS13(s)
2094 && !WPACKET_sub_memcpy_u8(pkt, s->session->session_id, sl))
2095 || !s->method->put_cipher_by_char(s->s3->tmp.new_cipher, pkt, &len)
2096 || (!SSL_IS_TLS13(s)
2097 && !WPACKET_put_bytes_u8(pkt, compm))
2098 || !tls_construct_extensions(s, pkt,
2100 ? EXT_TLS1_3_SERVER_HELLO
2101 : EXT_TLS1_2_SERVER_HELLO,
2103 SSLerr(SSL_F_TLS_CONSTRUCT_SERVER_HELLO, ERR_R_INTERNAL_ERROR);
2107 if (!(s->verify_mode & SSL_VERIFY_PEER)
2108 && !ssl3_digest_cached_records(s, 0)) {
2109 al = SSL_AD_INTERNAL_ERROR;
2115 ssl3_send_alert(s, SSL3_AL_FATAL, al);
2119 int tls_construct_server_done(SSL *s, WPACKET *pkt)
2121 if (!s->s3->tmp.cert_request) {
2122 if (!ssl3_digest_cached_records(s, 0)) {
2123 ssl3_send_alert(s, SSL3_AL_FATAL, SSL_AD_INTERNAL_ERROR);
2130 int tls_construct_server_key_exchange(SSL *s, WPACKET *pkt)
2132 #ifndef OPENSSL_NO_DH
2133 EVP_PKEY *pkdh = NULL;
2135 #ifndef OPENSSL_NO_EC
2136 unsigned char *encodedPoint = NULL;
2137 size_t encodedlen = 0;
2140 const SIGALG_LOOKUP *lu = s->s3->tmp.sigalg;
2141 int al = SSL_AD_INTERNAL_ERROR, i;
2144 EVP_MD_CTX *md_ctx = EVP_MD_CTX_new();
2145 EVP_PKEY_CTX *pctx = NULL;
2146 size_t paramlen, paramoffset;
2148 if (!WPACKET_get_total_written(pkt, ¶moffset)) {
2149 SSLerr(SSL_F_TLS_CONSTRUCT_SERVER_KEY_EXCHANGE, ERR_R_INTERNAL_ERROR);
2153 if (md_ctx == NULL) {
2154 SSLerr(SSL_F_TLS_CONSTRUCT_SERVER_KEY_EXCHANGE, ERR_R_MALLOC_FAILURE);
2158 type = s->s3->tmp.new_cipher->algorithm_mkey;
2160 r[0] = r[1] = r[2] = r[3] = NULL;
2161 #ifndef OPENSSL_NO_PSK
2162 /* Plain PSK or RSAPSK nothing to do */
2163 if (type & (SSL_kPSK | SSL_kRSAPSK)) {
2165 #endif /* !OPENSSL_NO_PSK */
2166 #ifndef OPENSSL_NO_DH
2167 if (type & (SSL_kDHE | SSL_kDHEPSK)) {
2168 CERT *cert = s->cert;
2170 EVP_PKEY *pkdhp = NULL;
2173 if (s->cert->dh_tmp_auto) {
2174 DH *dhp = ssl_get_auto_dh(s);
2175 pkdh = EVP_PKEY_new();
2176 if (pkdh == NULL || dhp == NULL) {
2178 SSLerr(SSL_F_TLS_CONSTRUCT_SERVER_KEY_EXCHANGE,
2179 ERR_R_INTERNAL_ERROR);
2182 EVP_PKEY_assign_DH(pkdh, dhp);
2185 pkdhp = cert->dh_tmp;
2187 if ((pkdhp == NULL) && (s->cert->dh_tmp_cb != NULL)) {
2188 DH *dhp = s->cert->dh_tmp_cb(s, 0, 1024);
2189 pkdh = ssl_dh_to_pkey(dhp);
2191 SSLerr(SSL_F_TLS_CONSTRUCT_SERVER_KEY_EXCHANGE,
2192 ERR_R_INTERNAL_ERROR);
2197 if (pkdhp == NULL) {
2198 al = SSL_AD_HANDSHAKE_FAILURE;
2199 SSLerr(SSL_F_TLS_CONSTRUCT_SERVER_KEY_EXCHANGE,
2200 SSL_R_MISSING_TMP_DH_KEY);
2203 if (!ssl_security(s, SSL_SECOP_TMP_DH,
2204 EVP_PKEY_security_bits(pkdhp), 0, pkdhp)) {
2205 al = SSL_AD_HANDSHAKE_FAILURE;
2206 SSLerr(SSL_F_TLS_CONSTRUCT_SERVER_KEY_EXCHANGE,
2207 SSL_R_DH_KEY_TOO_SMALL);
2210 if (s->s3->tmp.pkey != NULL) {
2211 SSLerr(SSL_F_TLS_CONSTRUCT_SERVER_KEY_EXCHANGE,
2212 ERR_R_INTERNAL_ERROR);
2216 s->s3->tmp.pkey = ssl_generate_pkey(pkdhp);
2218 if (s->s3->tmp.pkey == NULL) {
2219 SSLerr(SSL_F_TLS_CONSTRUCT_SERVER_KEY_EXCHANGE, ERR_R_EVP_LIB);
2223 dh = EVP_PKEY_get0_DH(s->s3->tmp.pkey);
2225 EVP_PKEY_free(pkdh);
2228 DH_get0_pqg(dh, &r[0], NULL, &r[1]);
2229 DH_get0_key(dh, &r[2], NULL);
2232 #ifndef OPENSSL_NO_EC
2233 if (type & (SSL_kECDHE | SSL_kECDHEPSK)) {
2236 if (s->s3->tmp.pkey != NULL) {
2237 SSLerr(SSL_F_TLS_CONSTRUCT_SERVER_KEY_EXCHANGE,
2238 ERR_R_INTERNAL_ERROR);
2242 /* Get NID of appropriate shared curve */
2243 nid = tls1_shared_group(s, -2);
2244 curve_id = tls1_ec_nid2curve_id(nid);
2245 if (curve_id == 0) {
2246 SSLerr(SSL_F_TLS_CONSTRUCT_SERVER_KEY_EXCHANGE,
2247 SSL_R_UNSUPPORTED_ELLIPTIC_CURVE);
2250 s->s3->tmp.pkey = ssl_generate_pkey_curve(curve_id);
2251 /* Generate a new key for this curve */
2252 if (s->s3->tmp.pkey == NULL) {
2253 SSLerr(SSL_F_TLS_CONSTRUCT_SERVER_KEY_EXCHANGE, ERR_R_EVP_LIB);
2257 /* Encode the public key. */
2258 encodedlen = EVP_PKEY_get1_tls_encodedpoint(s->s3->tmp.pkey,
2260 if (encodedlen == 0) {
2261 SSLerr(SSL_F_TLS_CONSTRUCT_SERVER_KEY_EXCHANGE, ERR_R_EC_LIB);
2266 * We'll generate the serverKeyExchange message explicitly so we
2267 * can set these to NULLs
2274 #endif /* !OPENSSL_NO_EC */
2275 #ifndef OPENSSL_NO_SRP
2276 if (type & SSL_kSRP) {
2277 if ((s->srp_ctx.N == NULL) ||
2278 (s->srp_ctx.g == NULL) ||
2279 (s->srp_ctx.s == NULL) || (s->srp_ctx.B == NULL)) {
2280 SSLerr(SSL_F_TLS_CONSTRUCT_SERVER_KEY_EXCHANGE,
2281 SSL_R_MISSING_SRP_PARAM);
2284 r[0] = s->srp_ctx.N;
2285 r[1] = s->srp_ctx.g;
2286 r[2] = s->srp_ctx.s;
2287 r[3] = s->srp_ctx.B;
2291 al = SSL_AD_HANDSHAKE_FAILURE;
2292 SSLerr(SSL_F_TLS_CONSTRUCT_SERVER_KEY_EXCHANGE,
2293 SSL_R_UNKNOWN_KEY_EXCHANGE_TYPE);
2297 if (((s->s3->tmp.new_cipher->algorithm_auth & (SSL_aNULL | SSL_aSRP)) != 0)
2298 || ((s->s3->tmp.new_cipher->algorithm_mkey & SSL_PSK)) != 0) {
2300 } else if (lu == NULL) {
2301 al = SSL_AD_DECODE_ERROR;
2305 #ifndef OPENSSL_NO_PSK
2306 if (type & SSL_PSK) {
2307 size_t len = (s->cert->psk_identity_hint == NULL)
2308 ? 0 : strlen(s->cert->psk_identity_hint);
2311 * It should not happen that len > PSK_MAX_IDENTITY_LEN - we already
2312 * checked this when we set the identity hint - but just in case
2314 if (len > PSK_MAX_IDENTITY_LEN
2315 || !WPACKET_sub_memcpy_u16(pkt, s->cert->psk_identity_hint,
2317 SSLerr(SSL_F_TLS_CONSTRUCT_SERVER_KEY_EXCHANGE,
2318 ERR_R_INTERNAL_ERROR);
2324 for (i = 0; i < 4 && r[i] != NULL; i++) {
2325 unsigned char *binval;
2328 #ifndef OPENSSL_NO_SRP
2329 if ((i == 2) && (type & SSL_kSRP)) {
2330 res = WPACKET_start_sub_packet_u8(pkt);
2333 res = WPACKET_start_sub_packet_u16(pkt);
2336 SSLerr(SSL_F_TLS_CONSTRUCT_SERVER_KEY_EXCHANGE,
2337 ERR_R_INTERNAL_ERROR);
2341 #ifndef OPENSSL_NO_DH
2343 * for interoperability with some versions of the Microsoft TLS
2344 * stack, we need to zero pad the DHE pub key to the same length
2347 if ((i == 2) && (type & (SSL_kDHE | SSL_kDHEPSK))) {
2348 size_t len = BN_num_bytes(r[0]) - BN_num_bytes(r[2]);
2351 if (!WPACKET_allocate_bytes(pkt, len, &binval)) {
2352 SSLerr(SSL_F_TLS_CONSTRUCT_SERVER_KEY_EXCHANGE,
2353 ERR_R_INTERNAL_ERROR);
2356 memset(binval, 0, len);
2360 if (!WPACKET_allocate_bytes(pkt, BN_num_bytes(r[i]), &binval)
2361 || !WPACKET_close(pkt)) {
2362 SSLerr(SSL_F_TLS_CONSTRUCT_SERVER_KEY_EXCHANGE,
2363 ERR_R_INTERNAL_ERROR);
2367 BN_bn2bin(r[i], binval);
2370 #ifndef OPENSSL_NO_EC
2371 if (type & (SSL_kECDHE | SSL_kECDHEPSK)) {
2373 * We only support named (not generic) curves. In this situation, the
2374 * ServerKeyExchange message has: [1 byte CurveType], [2 byte CurveName]
2375 * [1 byte length of encoded point], followed by the actual encoded
2378 if (!WPACKET_put_bytes_u8(pkt, NAMED_CURVE_TYPE)
2379 || !WPACKET_put_bytes_u8(pkt, 0)
2380 || !WPACKET_put_bytes_u8(pkt, curve_id)
2381 || !WPACKET_sub_memcpy_u8(pkt, encodedPoint, encodedlen)) {
2382 SSLerr(SSL_F_TLS_CONSTRUCT_SERVER_KEY_EXCHANGE,
2383 ERR_R_INTERNAL_ERROR);
2386 OPENSSL_free(encodedPoint);
2387 encodedPoint = NULL;
2393 EVP_PKEY *pkey = s->s3->tmp.cert->privatekey;
2394 const EVP_MD *md = ssl_md(lu->hash_idx);
2395 unsigned char *sigbytes1, *sigbytes2;
2398 if (pkey == NULL || md == NULL) {
2399 /* Should never happen */
2400 al = SSL_AD_INTERNAL_ERROR;
2401 SSLerr(SSL_F_TLS_CONSTRUCT_SERVER_KEY_EXCHANGE,
2402 ERR_R_INTERNAL_ERROR);
2406 * n is the length of the params, they start at &(d[4]) and p
2407 * points to the space at the end.
2410 /* Get length of the parameters we have written above */
2411 if (!WPACKET_get_length(pkt, ¶mlen)) {
2412 SSLerr(SSL_F_TLS_CONSTRUCT_SERVER_KEY_EXCHANGE,
2413 ERR_R_INTERNAL_ERROR);
2416 /* send signature algorithm */
2417 if (SSL_USE_SIGALGS(s) && !WPACKET_put_bytes_u16(pkt, lu->sigalg))
2420 * Create the signature. We don't know the actual length of the sig
2421 * until after we've created it, so we reserve enough bytes for it
2422 * up front, and then properly allocate them in the WPACKET
2425 siglen = EVP_PKEY_size(pkey);
2426 if (!WPACKET_sub_reserve_bytes_u16(pkt, siglen, &sigbytes1)
2427 || EVP_DigestSignInit(md_ctx, &pctx, md, NULL, pkey) <= 0) {
2428 SSLerr(SSL_F_TLS_CONSTRUCT_SERVER_KEY_EXCHANGE,
2429 ERR_R_INTERNAL_ERROR);
2432 if (lu->sig == EVP_PKEY_RSA_PSS) {
2433 if (EVP_PKEY_CTX_set_rsa_padding(pctx, RSA_PKCS1_PSS_PADDING) <= 0
2434 || EVP_PKEY_CTX_set_rsa_pss_saltlen(pctx, RSA_PSS_SALTLEN_DIGEST) <= 0) {
2435 SSLerr(SSL_F_TLS_CONSTRUCT_SERVER_KEY_EXCHANGE,
2440 if (EVP_DigestSignUpdate(md_ctx, &(s->s3->client_random[0]),
2441 SSL3_RANDOM_SIZE) <= 0
2442 || EVP_DigestSignUpdate(md_ctx, &(s->s3->server_random[0]),
2443 SSL3_RANDOM_SIZE) <= 0
2444 || EVP_DigestSignUpdate(md_ctx,
2445 s->init_buf->data + paramoffset,
2447 || EVP_DigestSignFinal(md_ctx, sigbytes1, &siglen) <= 0
2448 || !WPACKET_sub_allocate_bytes_u16(pkt, siglen, &sigbytes2)
2449 || sigbytes1 != sigbytes2) {
2450 SSLerr(SSL_F_TLS_CONSTRUCT_SERVER_KEY_EXCHANGE,
2451 ERR_R_INTERNAL_ERROR);
2456 EVP_MD_CTX_free(md_ctx);
2459 ssl3_send_alert(s, SSL3_AL_FATAL, al);
2461 #ifndef OPENSSL_NO_DH
2462 EVP_PKEY_free(pkdh);
2464 #ifndef OPENSSL_NO_EC
2465 OPENSSL_free(encodedPoint);
2467 EVP_MD_CTX_free(md_ctx);
2471 int tls_construct_certificate_request(SSL *s, WPACKET *pkt)
2474 STACK_OF(X509_NAME) *sk = NULL;
2476 if (SSL_IS_TLS13(s)) {
2477 /* TODO(TLS1.3) for now send empty request context */
2478 if (!WPACKET_put_bytes_u8(pkt, 0)) {
2479 SSLerr(SSL_F_TLS_CONSTRUCT_CERTIFICATE_REQUEST,
2480 ERR_R_INTERNAL_ERROR);
2484 /* get the list of acceptable cert types */
2485 if (!WPACKET_start_sub_packet_u8(pkt)
2486 || !ssl3_get_req_cert_type(s, pkt) || !WPACKET_close(pkt)) {
2487 SSLerr(SSL_F_TLS_CONSTRUCT_CERTIFICATE_REQUEST,
2488 ERR_R_INTERNAL_ERROR);
2493 if (SSL_USE_SIGALGS(s)) {
2494 const uint16_t *psigs;
2495 size_t nl = tls12_get_psigalgs(s, 1, &psigs);
2497 if (!WPACKET_start_sub_packet_u16(pkt)
2498 || !tls12_copy_sigalgs(s, pkt, psigs, nl)
2499 || !WPACKET_close(pkt)) {
2500 SSLerr(SSL_F_TLS_CONSTRUCT_CERTIFICATE_REQUEST,
2501 ERR_R_INTERNAL_ERROR);
2506 /* Start sub-packet for client CA list */
2507 if (!WPACKET_start_sub_packet_u16(pkt)) {
2508 SSLerr(SSL_F_TLS_CONSTRUCT_CERTIFICATE_REQUEST, ERR_R_INTERNAL_ERROR);
2512 sk = SSL_get_client_CA_list(s);
2514 for (i = 0; i < sk_X509_NAME_num(sk); i++) {
2515 unsigned char *namebytes;
2516 X509_NAME *name = sk_X509_NAME_value(sk, i);
2520 || (namelen = i2d_X509_NAME(name, NULL)) < 0
2521 || !WPACKET_sub_allocate_bytes_u16(pkt, namelen,
2523 || i2d_X509_NAME(name, &namebytes) != namelen) {
2524 SSLerr(SSL_F_TLS_CONSTRUCT_CERTIFICATE_REQUEST,
2525 ERR_R_INTERNAL_ERROR);
2530 /* else no CA names */
2531 if (!WPACKET_close(pkt)) {
2532 SSLerr(SSL_F_TLS_CONSTRUCT_CERTIFICATE_REQUEST, ERR_R_INTERNAL_ERROR);
2536 * TODO(TLS1.3) implement configurable certificate_extensions
2537 * For now just send zero length extensions.
2539 if (SSL_IS_TLS13(s) && !WPACKET_put_bytes_u16(pkt, 0)) {
2540 SSLerr(SSL_F_TLS_CONSTRUCT_CERTIFICATE_REQUEST, ERR_R_INTERNAL_ERROR);
2544 s->s3->tmp.cert_request = 1;
2548 ssl3_send_alert(s, SSL3_AL_FATAL, SSL_AD_INTERNAL_ERROR);
2552 static int tls_process_cke_psk_preamble(SSL *s, PACKET *pkt, int *al)
2554 #ifndef OPENSSL_NO_PSK
2555 unsigned char psk[PSK_MAX_PSK_LEN];
2557 PACKET psk_identity;
2559 if (!PACKET_get_length_prefixed_2(pkt, &psk_identity)) {
2560 *al = SSL_AD_DECODE_ERROR;
2561 SSLerr(SSL_F_TLS_PROCESS_CKE_PSK_PREAMBLE, SSL_R_LENGTH_MISMATCH);
2564 if (PACKET_remaining(&psk_identity) > PSK_MAX_IDENTITY_LEN) {
2565 *al = SSL_AD_DECODE_ERROR;
2566 SSLerr(SSL_F_TLS_PROCESS_CKE_PSK_PREAMBLE, SSL_R_DATA_LENGTH_TOO_LONG);
2569 if (s->psk_server_callback == NULL) {
2570 *al = SSL_AD_INTERNAL_ERROR;
2571 SSLerr(SSL_F_TLS_PROCESS_CKE_PSK_PREAMBLE, SSL_R_PSK_NO_SERVER_CB);
2575 if (!PACKET_strndup(&psk_identity, &s->session->psk_identity)) {
2576 *al = SSL_AD_INTERNAL_ERROR;
2577 SSLerr(SSL_F_TLS_PROCESS_CKE_PSK_PREAMBLE, ERR_R_INTERNAL_ERROR);
2581 psklen = s->psk_server_callback(s, s->session->psk_identity,
2584 if (psklen > PSK_MAX_PSK_LEN) {
2585 *al = SSL_AD_INTERNAL_ERROR;
2586 SSLerr(SSL_F_TLS_PROCESS_CKE_PSK_PREAMBLE, ERR_R_INTERNAL_ERROR);
2588 } else if (psklen == 0) {
2590 * PSK related to the given identity not found
2592 *al = SSL_AD_UNKNOWN_PSK_IDENTITY;
2593 SSLerr(SSL_F_TLS_PROCESS_CKE_PSK_PREAMBLE,
2594 SSL_R_PSK_IDENTITY_NOT_FOUND);
2598 OPENSSL_free(s->s3->tmp.psk);
2599 s->s3->tmp.psk = OPENSSL_memdup(psk, psklen);
2600 OPENSSL_cleanse(psk, psklen);
2602 if (s->s3->tmp.psk == NULL) {
2603 *al = SSL_AD_INTERNAL_ERROR;
2604 SSLerr(SSL_F_TLS_PROCESS_CKE_PSK_PREAMBLE, ERR_R_MALLOC_FAILURE);
2608 s->s3->tmp.psklen = psklen;
2612 /* Should never happen */
2613 *al = SSL_AD_INTERNAL_ERROR;
2614 SSLerr(SSL_F_TLS_PROCESS_CKE_PSK_PREAMBLE, ERR_R_INTERNAL_ERROR);
2619 static int tls_process_cke_rsa(SSL *s, PACKET *pkt, int *al)
2621 #ifndef OPENSSL_NO_RSA
2622 unsigned char rand_premaster_secret[SSL_MAX_MASTER_KEY_LENGTH];
2624 unsigned char decrypt_good, version_good;
2625 size_t j, padding_len;
2626 PACKET enc_premaster;
2628 unsigned char *rsa_decrypt = NULL;
2631 rsa = EVP_PKEY_get0_RSA(s->cert->pkeys[SSL_PKEY_RSA].privatekey);
2633 *al = SSL_AD_HANDSHAKE_FAILURE;
2634 SSLerr(SSL_F_TLS_PROCESS_CKE_RSA, SSL_R_MISSING_RSA_CERTIFICATE);
2638 /* SSLv3 and pre-standard DTLS omit the length bytes. */
2639 if (s->version == SSL3_VERSION || s->version == DTLS1_BAD_VER) {
2640 enc_premaster = *pkt;
2642 if (!PACKET_get_length_prefixed_2(pkt, &enc_premaster)
2643 || PACKET_remaining(pkt) != 0) {
2644 *al = SSL_AD_DECODE_ERROR;
2645 SSLerr(SSL_F_TLS_PROCESS_CKE_RSA, SSL_R_LENGTH_MISMATCH);
2651 * We want to be sure that the plaintext buffer size makes it safe to
2652 * iterate over the entire size of a premaster secret
2653 * (SSL_MAX_MASTER_KEY_LENGTH). Reject overly short RSA keys because
2654 * their ciphertext cannot accommodate a premaster secret anyway.
2656 if (RSA_size(rsa) < SSL_MAX_MASTER_KEY_LENGTH) {
2657 *al = SSL_AD_INTERNAL_ERROR;
2658 SSLerr(SSL_F_TLS_PROCESS_CKE_RSA, RSA_R_KEY_SIZE_TOO_SMALL);
2662 rsa_decrypt = OPENSSL_malloc(RSA_size(rsa));
2663 if (rsa_decrypt == NULL) {
2664 *al = SSL_AD_INTERNAL_ERROR;
2665 SSLerr(SSL_F_TLS_PROCESS_CKE_RSA, ERR_R_MALLOC_FAILURE);
2670 * We must not leak whether a decryption failure occurs because of
2671 * Bleichenbacher's attack on PKCS #1 v1.5 RSA padding (see RFC 2246,
2672 * section 7.4.7.1). The code follows that advice of the TLS RFC and
2673 * generates a random premaster secret for the case that the decrypt
2674 * fails. See https://tools.ietf.org/html/rfc5246#section-7.4.7.1
2677 if (RAND_bytes(rand_premaster_secret, sizeof(rand_premaster_secret)) <= 0)
2681 * Decrypt with no padding. PKCS#1 padding will be removed as part of
2682 * the timing-sensitive code below.
2684 /* TODO(size_t): Convert this function */
2685 decrypt_len = (int)RSA_private_decrypt((int)PACKET_remaining(&enc_premaster),
2686 PACKET_data(&enc_premaster),
2687 rsa_decrypt, rsa, RSA_NO_PADDING);
2688 if (decrypt_len < 0)
2691 /* Check the padding. See RFC 3447, section 7.2.2. */
2694 * The smallest padded premaster is 11 bytes of overhead. Small keys
2695 * are publicly invalid, so this may return immediately. This ensures
2696 * PS is at least 8 bytes.
2698 if (decrypt_len < 11 + SSL_MAX_MASTER_KEY_LENGTH) {
2699 *al = SSL_AD_DECRYPT_ERROR;
2700 SSLerr(SSL_F_TLS_PROCESS_CKE_RSA, SSL_R_DECRYPTION_FAILED);
2704 padding_len = decrypt_len - SSL_MAX_MASTER_KEY_LENGTH;
2705 decrypt_good = constant_time_eq_int_8(rsa_decrypt[0], 0) &
2706 constant_time_eq_int_8(rsa_decrypt[1], 2);
2707 for (j = 2; j < padding_len - 1; j++) {
2708 decrypt_good &= ~constant_time_is_zero_8(rsa_decrypt[j]);
2710 decrypt_good &= constant_time_is_zero_8(rsa_decrypt[padding_len - 1]);
2713 * If the version in the decrypted pre-master secret is correct then
2714 * version_good will be 0xff, otherwise it'll be zero. The
2715 * Klima-Pokorny-Rosa extension of Bleichenbacher's attack
2716 * (http://eprint.iacr.org/2003/052/) exploits the version number
2717 * check as a "bad version oracle". Thus version checks are done in
2718 * constant time and are treated like any other decryption error.
2721 constant_time_eq_8(rsa_decrypt[padding_len],
2722 (unsigned)(s->client_version >> 8));
2724 constant_time_eq_8(rsa_decrypt[padding_len + 1],
2725 (unsigned)(s->client_version & 0xff));
2728 * The premaster secret must contain the same version number as the
2729 * ClientHello to detect version rollback attacks (strangely, the
2730 * protocol does not offer such protection for DH ciphersuites).
2731 * However, buggy clients exist that send the negotiated protocol
2732 * version instead if the server does not support the requested
2733 * protocol version. If SSL_OP_TLS_ROLLBACK_BUG is set, tolerate such
2736 if (s->options & SSL_OP_TLS_ROLLBACK_BUG) {
2737 unsigned char workaround_good;
2738 workaround_good = constant_time_eq_8(rsa_decrypt[padding_len],
2739 (unsigned)(s->version >> 8));
2741 constant_time_eq_8(rsa_decrypt[padding_len + 1],
2742 (unsigned)(s->version & 0xff));
2743 version_good |= workaround_good;
2747 * Both decryption and version must be good for decrypt_good to
2748 * remain non-zero (0xff).
2750 decrypt_good &= version_good;
2753 * Now copy rand_premaster_secret over from p using
2754 * decrypt_good_mask. If decryption failed, then p does not
2755 * contain valid plaintext, however, a check above guarantees
2756 * it is still sufficiently large to read from.
2758 for (j = 0; j < sizeof(rand_premaster_secret); j++) {
2759 rsa_decrypt[padding_len + j] =
2760 constant_time_select_8(decrypt_good,
2761 rsa_decrypt[padding_len + j],
2762 rand_premaster_secret[j]);
2765 if (!ssl_generate_master_secret(s, rsa_decrypt + padding_len,
2766 sizeof(rand_premaster_secret), 0)) {
2767 *al = SSL_AD_INTERNAL_ERROR;
2768 SSLerr(SSL_F_TLS_PROCESS_CKE_RSA, ERR_R_INTERNAL_ERROR);
2774 OPENSSL_free(rsa_decrypt);
2777 /* Should never happen */
2778 *al = SSL_AD_INTERNAL_ERROR;
2779 SSLerr(SSL_F_TLS_PROCESS_CKE_RSA, ERR_R_INTERNAL_ERROR);
2784 static int tls_process_cke_dhe(SSL *s, PACKET *pkt, int *al)
2786 #ifndef OPENSSL_NO_DH
2787 EVP_PKEY *skey = NULL;
2791 const unsigned char *data;
2792 EVP_PKEY *ckey = NULL;
2795 if (!PACKET_get_net_2(pkt, &i) || PACKET_remaining(pkt) != i) {
2796 *al = SSL_AD_HANDSHAKE_FAILURE;
2797 SSLerr(SSL_F_TLS_PROCESS_CKE_DHE,
2798 SSL_R_DH_PUBLIC_VALUE_LENGTH_IS_WRONG);
2801 skey = s->s3->tmp.pkey;
2803 *al = SSL_AD_HANDSHAKE_FAILURE;
2804 SSLerr(SSL_F_TLS_PROCESS_CKE_DHE, SSL_R_MISSING_TMP_DH_KEY);
2808 if (PACKET_remaining(pkt) == 0L) {
2809 *al = SSL_AD_HANDSHAKE_FAILURE;
2810 SSLerr(SSL_F_TLS_PROCESS_CKE_DHE, SSL_R_MISSING_TMP_DH_KEY);
2813 if (!PACKET_get_bytes(pkt, &data, i)) {
2814 /* We already checked we have enough data */
2815 *al = SSL_AD_INTERNAL_ERROR;
2816 SSLerr(SSL_F_TLS_PROCESS_CKE_DHE, ERR_R_INTERNAL_ERROR);
2819 ckey = EVP_PKEY_new();
2820 if (ckey == NULL || EVP_PKEY_copy_parameters(ckey, skey) == 0) {
2821 SSLerr(SSL_F_TLS_PROCESS_CKE_DHE, SSL_R_BN_LIB);
2824 cdh = EVP_PKEY_get0_DH(ckey);
2825 pub_key = BN_bin2bn(data, i, NULL);
2827 if (pub_key == NULL || !DH_set0_key(cdh, pub_key, NULL)) {
2828 SSLerr(SSL_F_TLS_PROCESS_CKE_DHE, ERR_R_INTERNAL_ERROR);
2829 if (pub_key != NULL)
2834 if (ssl_derive(s, skey, ckey, 1) == 0) {
2835 *al = SSL_AD_INTERNAL_ERROR;
2836 SSLerr(SSL_F_TLS_PROCESS_CKE_DHE, ERR_R_INTERNAL_ERROR);
2841 EVP_PKEY_free(s->s3->tmp.pkey);
2842 s->s3->tmp.pkey = NULL;
2844 EVP_PKEY_free(ckey);
2847 /* Should never happen */
2848 *al = SSL_AD_INTERNAL_ERROR;
2849 SSLerr(SSL_F_TLS_PROCESS_CKE_DHE, ERR_R_INTERNAL_ERROR);
2854 static int tls_process_cke_ecdhe(SSL *s, PACKET *pkt, int *al)
2856 #ifndef OPENSSL_NO_EC
2857 EVP_PKEY *skey = s->s3->tmp.pkey;
2858 EVP_PKEY *ckey = NULL;
2861 if (PACKET_remaining(pkt) == 0L) {
2862 /* We don't support ECDH client auth */
2863 *al = SSL_AD_HANDSHAKE_FAILURE;
2864 SSLerr(SSL_F_TLS_PROCESS_CKE_ECDHE, SSL_R_MISSING_TMP_ECDH_KEY);
2868 const unsigned char *data;
2871 * Get client's public key from encoded point in the
2872 * ClientKeyExchange message.
2875 /* Get encoded point length */
2876 if (!PACKET_get_1(pkt, &i) || !PACKET_get_bytes(pkt, &data, i)
2877 || PACKET_remaining(pkt) != 0) {
2878 *al = SSL_AD_DECODE_ERROR;
2879 SSLerr(SSL_F_TLS_PROCESS_CKE_ECDHE, SSL_R_LENGTH_MISMATCH);
2882 ckey = EVP_PKEY_new();
2883 if (ckey == NULL || EVP_PKEY_copy_parameters(ckey, skey) <= 0) {
2884 SSLerr(SSL_F_TLS_PROCESS_CKE_ECDHE, ERR_R_EVP_LIB);
2887 if (EVP_PKEY_set1_tls_encodedpoint(ckey, data, i) == 0) {
2888 *al = SSL_AD_HANDSHAKE_FAILURE;
2889 SSLerr(SSL_F_TLS_PROCESS_CKE_ECDHE, ERR_R_EC_LIB);
2894 if (ssl_derive(s, skey, ckey, 1) == 0) {
2895 *al = SSL_AD_INTERNAL_ERROR;
2896 SSLerr(SSL_F_TLS_PROCESS_CKE_ECDHE, ERR_R_INTERNAL_ERROR);
2901 EVP_PKEY_free(s->s3->tmp.pkey);
2902 s->s3->tmp.pkey = NULL;
2904 EVP_PKEY_free(ckey);
2908 /* Should never happen */
2909 *al = SSL_AD_INTERNAL_ERROR;
2910 SSLerr(SSL_F_TLS_PROCESS_CKE_ECDHE, ERR_R_INTERNAL_ERROR);
2915 static int tls_process_cke_srp(SSL *s, PACKET *pkt, int *al)
2917 #ifndef OPENSSL_NO_SRP
2919 const unsigned char *data;
2921 if (!PACKET_get_net_2(pkt, &i)
2922 || !PACKET_get_bytes(pkt, &data, i)) {
2923 *al = SSL_AD_DECODE_ERROR;
2924 SSLerr(SSL_F_TLS_PROCESS_CKE_SRP, SSL_R_BAD_SRP_A_LENGTH);
2927 if ((s->srp_ctx.A = BN_bin2bn(data, i, NULL)) == NULL) {
2928 SSLerr(SSL_F_TLS_PROCESS_CKE_SRP, ERR_R_BN_LIB);
2931 if (BN_ucmp(s->srp_ctx.A, s->srp_ctx.N) >= 0 || BN_is_zero(s->srp_ctx.A)) {
2932 *al = SSL_AD_ILLEGAL_PARAMETER;
2933 SSLerr(SSL_F_TLS_PROCESS_CKE_SRP, SSL_R_BAD_SRP_PARAMETERS);
2936 OPENSSL_free(s->session->srp_username);
2937 s->session->srp_username = OPENSSL_strdup(s->srp_ctx.login);
2938 if (s->session->srp_username == NULL) {
2939 SSLerr(SSL_F_TLS_PROCESS_CKE_SRP, ERR_R_MALLOC_FAILURE);
2943 if (!srp_generate_server_master_secret(s)) {
2944 SSLerr(SSL_F_TLS_PROCESS_CKE_SRP, ERR_R_INTERNAL_ERROR);
2950 /* Should never happen */
2951 *al = SSL_AD_INTERNAL_ERROR;
2952 SSLerr(SSL_F_TLS_PROCESS_CKE_SRP, ERR_R_INTERNAL_ERROR);
2957 static int tls_process_cke_gost(SSL *s, PACKET *pkt, int *al)
2959 #ifndef OPENSSL_NO_GOST
2960 EVP_PKEY_CTX *pkey_ctx;
2961 EVP_PKEY *client_pub_pkey = NULL, *pk = NULL;
2962 unsigned char premaster_secret[32];
2963 const unsigned char *start;
2964 size_t outlen = 32, inlen;
2965 unsigned long alg_a;
2968 size_t sess_key_len;
2969 const unsigned char *data;
2972 /* Get our certificate private key */
2973 alg_a = s->s3->tmp.new_cipher->algorithm_auth;
2974 if (alg_a & SSL_aGOST12) {
2976 * New GOST ciphersuites have SSL_aGOST01 bit too
2978 pk = s->cert->pkeys[SSL_PKEY_GOST12_512].privatekey;
2980 pk = s->cert->pkeys[SSL_PKEY_GOST12_256].privatekey;
2983 pk = s->cert->pkeys[SSL_PKEY_GOST01].privatekey;
2985 } else if (alg_a & SSL_aGOST01) {
2986 pk = s->cert->pkeys[SSL_PKEY_GOST01].privatekey;
2989 pkey_ctx = EVP_PKEY_CTX_new(pk, NULL);
2990 if (pkey_ctx == NULL) {
2991 *al = SSL_AD_INTERNAL_ERROR;
2992 SSLerr(SSL_F_TLS_PROCESS_CKE_GOST, ERR_R_MALLOC_FAILURE);
2995 if (EVP_PKEY_decrypt_init(pkey_ctx) <= 0) {
2996 *al = SSL_AD_INTERNAL_ERROR;
2997 SSLerr(SSL_F_TLS_PROCESS_CKE_GOST, ERR_R_INTERNAL_ERROR);
3001 * If client certificate is present and is of the same type, maybe
3002 * use it for key exchange. Don't mind errors from
3003 * EVP_PKEY_derive_set_peer, because it is completely valid to use a
3004 * client certificate for authorization only.
3006 client_pub_pkey = X509_get0_pubkey(s->session->peer);
3007 if (client_pub_pkey) {
3008 if (EVP_PKEY_derive_set_peer(pkey_ctx, client_pub_pkey) <= 0)
3011 /* Decrypt session key */
3012 sess_key_len = PACKET_remaining(pkt);
3013 if (!PACKET_get_bytes(pkt, &data, sess_key_len)) {
3014 *al = SSL_AD_INTERNAL_ERROR;
3015 SSLerr(SSL_F_TLS_PROCESS_CKE_GOST, ERR_R_INTERNAL_ERROR);
3018 /* TODO(size_t): Convert this function */
3019 if (ASN1_get_object((const unsigned char **)&data, &Tlen, &Ttag,
3020 &Tclass, (long)sess_key_len) != V_ASN1_CONSTRUCTED
3021 || Ttag != V_ASN1_SEQUENCE || Tclass != V_ASN1_UNIVERSAL) {
3022 *al = SSL_AD_DECODE_ERROR;
3023 SSLerr(SSL_F_TLS_PROCESS_CKE_GOST, SSL_R_DECRYPTION_FAILED);
3028 if (EVP_PKEY_decrypt
3029 (pkey_ctx, premaster_secret, &outlen, start, inlen) <= 0) {
3030 *al = SSL_AD_DECODE_ERROR;
3031 SSLerr(SSL_F_TLS_PROCESS_CKE_GOST, SSL_R_DECRYPTION_FAILED);
3034 /* Generate master secret */
3035 if (!ssl_generate_master_secret(s, premaster_secret,
3036 sizeof(premaster_secret), 0)) {
3037 *al = SSL_AD_INTERNAL_ERROR;
3038 SSLerr(SSL_F_TLS_PROCESS_CKE_GOST, ERR_R_INTERNAL_ERROR);
3041 /* Check if pubkey from client certificate was used */
3042 if (EVP_PKEY_CTX_ctrl
3043 (pkey_ctx, -1, -1, EVP_PKEY_CTRL_PEER_KEY, 2, NULL) > 0)
3044 s->statem.no_cert_verify = 1;
3048 EVP_PKEY_CTX_free(pkey_ctx);
3051 /* Should never happen */
3052 *al = SSL_AD_INTERNAL_ERROR;
3053 SSLerr(SSL_F_TLS_PROCESS_CKE_GOST, ERR_R_INTERNAL_ERROR);
3058 MSG_PROCESS_RETURN tls_process_client_key_exchange(SSL *s, PACKET *pkt)
3061 unsigned long alg_k;
3063 alg_k = s->s3->tmp.new_cipher->algorithm_mkey;
3065 /* For PSK parse and retrieve identity, obtain PSK key */
3066 if ((alg_k & SSL_PSK) && !tls_process_cke_psk_preamble(s, pkt, &al))
3069 if (alg_k & SSL_kPSK) {
3070 /* Identity extracted earlier: should be nothing left */
3071 if (PACKET_remaining(pkt) != 0) {
3072 al = SSL_AD_HANDSHAKE_FAILURE;
3073 SSLerr(SSL_F_TLS_PROCESS_CLIENT_KEY_EXCHANGE,
3074 SSL_R_LENGTH_MISMATCH);
3077 /* PSK handled by ssl_generate_master_secret */
3078 if (!ssl_generate_master_secret(s, NULL, 0, 0)) {
3079 al = SSL_AD_INTERNAL_ERROR;
3080 SSLerr(SSL_F_TLS_PROCESS_CLIENT_KEY_EXCHANGE, ERR_R_INTERNAL_ERROR);
3083 } else if (alg_k & (SSL_kRSA | SSL_kRSAPSK)) {
3084 if (!tls_process_cke_rsa(s, pkt, &al))
3086 } else if (alg_k & (SSL_kDHE | SSL_kDHEPSK)) {
3087 if (!tls_process_cke_dhe(s, pkt, &al))
3089 } else if (alg_k & (SSL_kECDHE | SSL_kECDHEPSK)) {
3090 if (!tls_process_cke_ecdhe(s, pkt, &al))
3092 } else if (alg_k & SSL_kSRP) {
3093 if (!tls_process_cke_srp(s, pkt, &al))
3095 } else if (alg_k & SSL_kGOST) {
3096 if (!tls_process_cke_gost(s, pkt, &al))
3099 al = SSL_AD_HANDSHAKE_FAILURE;
3100 SSLerr(SSL_F_TLS_PROCESS_CLIENT_KEY_EXCHANGE,
3101 SSL_R_UNKNOWN_CIPHER_TYPE);
3105 return MSG_PROCESS_CONTINUE_PROCESSING;
3108 ssl3_send_alert(s, SSL3_AL_FATAL, al);
3109 #ifndef OPENSSL_NO_PSK
3110 OPENSSL_clear_free(s->s3->tmp.psk, s->s3->tmp.psklen);
3111 s->s3->tmp.psk = NULL;
3113 ossl_statem_set_error(s);
3114 return MSG_PROCESS_ERROR;
3117 WORK_STATE tls_post_process_client_key_exchange(SSL *s, WORK_STATE wst)
3119 #ifndef OPENSSL_NO_SCTP
3120 if (wst == WORK_MORE_A) {
3121 if (SSL_IS_DTLS(s)) {
3122 unsigned char sctpauthkey[64];
3123 char labelbuffer[sizeof(DTLS1_SCTP_AUTH_LABEL)];
3125 * Add new shared key for SCTP-Auth, will be ignored if no SCTP
3128 memcpy(labelbuffer, DTLS1_SCTP_AUTH_LABEL,
3129 sizeof(DTLS1_SCTP_AUTH_LABEL));
3131 if (SSL_export_keying_material(s, sctpauthkey,
3132 sizeof(sctpauthkey), labelbuffer,
3133 sizeof(labelbuffer), NULL, 0,
3135 ossl_statem_set_error(s);
3139 BIO_ctrl(SSL_get_wbio(s), BIO_CTRL_DGRAM_SCTP_ADD_AUTH_KEY,
3140 sizeof(sctpauthkey), sctpauthkey);
3145 if ((wst == WORK_MORE_B)
3147 && BIO_dgram_is_sctp(SSL_get_wbio(s))
3148 /* Are we renegotiating? */
3150 /* Are we going to skip the CertificateVerify? */
3151 && (s->session->peer == NULL || s->statem.no_cert_verify)
3152 && BIO_dgram_sctp_msg_waiting(SSL_get_rbio(s))) {
3153 s->s3->in_read_app_data = 2;
3154 s->rwstate = SSL_READING;
3155 BIO_clear_retry_flags(SSL_get_rbio(s));
3156 BIO_set_retry_read(SSL_get_rbio(s));
3157 ossl_statem_set_sctp_read_sock(s, 1);
3160 ossl_statem_set_sctp_read_sock(s, 0);
3164 if (s->statem.no_cert_verify || !s->session->peer) {
3166 * No certificate verify or no peer certificate so we no longer need
3167 * the handshake_buffer
3169 if (!ssl3_digest_cached_records(s, 0)) {
3170 ossl_statem_set_error(s);
3173 return WORK_FINISHED_CONTINUE;
3175 if (!s->s3->handshake_buffer) {
3176 SSLerr(SSL_F_TLS_POST_PROCESS_CLIENT_KEY_EXCHANGE,
3177 ERR_R_INTERNAL_ERROR);
3178 ossl_statem_set_error(s);
3182 * For sigalgs freeze the handshake buffer. If we support
3183 * extms we've done this already so this is a no-op
3185 if (!ssl3_digest_cached_records(s, 1)) {
3186 ossl_statem_set_error(s);
3191 return WORK_FINISHED_CONTINUE;
3194 MSG_PROCESS_RETURN tls_process_client_certificate(SSL *s, PACKET *pkt)
3196 int i, al = SSL_AD_INTERNAL_ERROR, ret = MSG_PROCESS_ERROR;
3198 unsigned long l, llen;
3199 const unsigned char *certstart, *certbytes;
3200 STACK_OF(X509) *sk = NULL;
3201 PACKET spkt, context;
3204 if ((sk = sk_X509_new_null()) == NULL) {
3205 SSLerr(SSL_F_TLS_PROCESS_CLIENT_CERTIFICATE, ERR_R_MALLOC_FAILURE);
3209 /* TODO(TLS1.3): For now we ignore the context. We need to verify this */
3210 if ((SSL_IS_TLS13(s) && !PACKET_get_length_prefixed_1(pkt, &context))
3211 || !PACKET_get_net_3(pkt, &llen)
3212 || !PACKET_get_sub_packet(pkt, &spkt, llen)
3213 || PACKET_remaining(pkt) != 0) {
3214 al = SSL_AD_DECODE_ERROR;
3215 SSLerr(SSL_F_TLS_PROCESS_CLIENT_CERTIFICATE, SSL_R_LENGTH_MISMATCH);
3219 for (chainidx = 0; PACKET_remaining(&spkt) > 0; chainidx++) {
3220 if (!PACKET_get_net_3(&spkt, &l)
3221 || !PACKET_get_bytes(&spkt, &certbytes, l)) {
3222 al = SSL_AD_DECODE_ERROR;
3223 SSLerr(SSL_F_TLS_PROCESS_CLIENT_CERTIFICATE,
3224 SSL_R_CERT_LENGTH_MISMATCH);
3228 certstart = certbytes;
3229 x = d2i_X509(NULL, (const unsigned char **)&certbytes, l);
3231 SSLerr(SSL_F_TLS_PROCESS_CLIENT_CERTIFICATE, ERR_R_ASN1_LIB);
3234 if (certbytes != (certstart + l)) {
3235 al = SSL_AD_DECODE_ERROR;
3236 SSLerr(SSL_F_TLS_PROCESS_CLIENT_CERTIFICATE,
3237 SSL_R_CERT_LENGTH_MISMATCH);
3241 if (SSL_IS_TLS13(s)) {
3242 RAW_EXTENSION *rawexts = NULL;
3245 if (!PACKET_get_length_prefixed_2(&spkt, &extensions)) {
3246 al = SSL_AD_DECODE_ERROR;
3247 SSLerr(SSL_F_TLS_PROCESS_CLIENT_CERTIFICATE, SSL_R_BAD_LENGTH);
3250 if (!tls_collect_extensions(s, &extensions, EXT_TLS1_3_CERTIFICATE,
3251 &rawexts, &al, NULL)
3252 || !tls_parse_all_extensions(s, EXT_TLS1_3_CERTIFICATE,
3253 rawexts, x, chainidx, &al)) {
3254 OPENSSL_free(rawexts);
3257 OPENSSL_free(rawexts);
3260 if (!sk_X509_push(sk, x)) {
3261 SSLerr(SSL_F_TLS_PROCESS_CLIENT_CERTIFICATE, ERR_R_MALLOC_FAILURE);
3267 if (sk_X509_num(sk) <= 0) {
3268 /* TLS does not mind 0 certs returned */
3269 if (s->version == SSL3_VERSION) {
3270 al = SSL_AD_HANDSHAKE_FAILURE;
3271 SSLerr(SSL_F_TLS_PROCESS_CLIENT_CERTIFICATE,
3272 SSL_R_NO_CERTIFICATES_RETURNED);
3275 /* Fail for TLS only if we required a certificate */
3276 else if ((s->verify_mode & SSL_VERIFY_PEER) &&
3277 (s->verify_mode & SSL_VERIFY_FAIL_IF_NO_PEER_CERT)) {
3278 SSLerr(SSL_F_TLS_PROCESS_CLIENT_CERTIFICATE,
3279 SSL_R_PEER_DID_NOT_RETURN_A_CERTIFICATE);
3280 al = SSL_AD_HANDSHAKE_FAILURE;
3283 /* No client certificate so digest cached records */
3284 if (s->s3->handshake_buffer && !ssl3_digest_cached_records(s, 0)) {
3289 i = ssl_verify_cert_chain(s, sk);
3291 al = ssl_verify_alarm_type(s->verify_result);
3292 SSLerr(SSL_F_TLS_PROCESS_CLIENT_CERTIFICATE,
3293 SSL_R_CERTIFICATE_VERIFY_FAILED);
3297 SSLerr(SSL_F_TLS_PROCESS_CLIENT_CERTIFICATE, i);
3298 al = SSL_AD_HANDSHAKE_FAILURE;
3301 pkey = X509_get0_pubkey(sk_X509_value(sk, 0));
3303 al = SSL3_AD_HANDSHAKE_FAILURE;
3304 SSLerr(SSL_F_TLS_PROCESS_CLIENT_CERTIFICATE,
3305 SSL_R_UNKNOWN_CERTIFICATE_TYPE);
3310 X509_free(s->session->peer);
3311 s->session->peer = sk_X509_shift(sk);
3312 s->session->verify_result = s->verify_result;
3314 sk_X509_pop_free(s->session->peer_chain, X509_free);
3315 s->session->peer_chain = sk;
3318 * Freeze the handshake buffer. For <TLS1.3 we do this after the CKE
3321 if (SSL_IS_TLS13(s) && !ssl3_digest_cached_records(s, 1)) {
3322 al = SSL_AD_INTERNAL_ERROR;
3323 SSLerr(SSL_F_TLS_PROCESS_CLIENT_CERTIFICATE, ERR_R_INTERNAL_ERROR);
3328 * Inconsistency alert: cert_chain does *not* include the peer's own
3329 * certificate, while we do include it in statem_clnt.c
3333 /* Save the current hash state for when we receive the CertificateVerify */
3335 && !ssl_handshake_hash(s, s->cert_verify_hash,
3336 sizeof(s->cert_verify_hash),
3337 &s->cert_verify_hash_len)) {
3338 al = SSL_AD_INTERNAL_ERROR;
3339 SSLerr(SSL_F_TLS_PROCESS_CLIENT_CERTIFICATE, ERR_R_INTERNAL_ERROR);
3343 ret = MSG_PROCESS_CONTINUE_READING;
3347 ssl3_send_alert(s, SSL3_AL_FATAL, al);
3348 ossl_statem_set_error(s);
3351 sk_X509_pop_free(sk, X509_free);
3355 int tls_construct_server_certificate(SSL *s, WPACKET *pkt)
3357 CERT_PKEY *cpk = s->s3->tmp.cert;
3358 int al = SSL_AD_INTERNAL_ERROR;
3361 SSLerr(SSL_F_TLS_CONSTRUCT_SERVER_CERTIFICATE, ERR_R_INTERNAL_ERROR);
3366 * In TLSv1.3 the certificate chain is always preceded by a 0 length context
3367 * for the server Certificate message
3369 if ((SSL_IS_TLS13(s) && !WPACKET_put_bytes_u8(pkt, 0))
3370 || !ssl3_output_cert_chain(s, pkt, cpk, &al)) {
3371 SSLerr(SSL_F_TLS_CONSTRUCT_SERVER_CERTIFICATE, ERR_R_INTERNAL_ERROR);
3372 ssl3_send_alert(s, SSL3_AL_FATAL, al);
3379 int tls_construct_new_session_ticket(SSL *s, WPACKET *pkt)
3381 unsigned char *senc = NULL;
3382 EVP_CIPHER_CTX *ctx = NULL;
3383 HMAC_CTX *hctx = NULL;
3384 unsigned char *p, *encdata1, *encdata2, *macdata1, *macdata2;
3385 const unsigned char *const_p;
3386 int len, slen_full, slen, lenfinal;
3389 SSL_CTX *tctx = s->session_ctx;
3390 unsigned char iv[EVP_MAX_IV_LENGTH];
3391 unsigned char key_name[TLSEXT_KEYNAME_LENGTH];
3392 int iv_len, al = SSL_AD_INTERNAL_ERROR;
3393 size_t macoffset, macendoffset;
3395 unsigned char age_add_c[sizeof(uint32_t)];
3399 if (SSL_IS_TLS13(s)) {
3400 if (RAND_bytes(age_add_u.age_add_c, sizeof(age_add_u)) <= 0)
3402 s->session->ext.tick_age_add = age_add_u.age_add;
3403 s->session->time = (long)time(NULL);
3404 if (s->s3->alpn_selected != NULL) {
3405 OPENSSL_free(s->session->ext.alpn_selected);
3406 s->session->ext.alpn_selected =
3407 OPENSSL_memdup(s->s3->alpn_selected, s->s3->alpn_selected_len);
3408 if (s->session->ext.alpn_selected == NULL) {
3409 SSLerr(SSL_F_TLS_CONSTRUCT_NEW_SESSION_TICKET,
3410 ERR_R_MALLOC_FAILURE);
3413 s->session->ext.alpn_selected_len = s->s3->alpn_selected_len;
3415 s->session->ext.max_early_data = s->max_early_data;
3418 /* get session encoding length */
3419 slen_full = i2d_SSL_SESSION(s->session, NULL);
3421 * Some length values are 16 bits, so forget it if session is too
3424 if (slen_full == 0 || slen_full > 0xFF00) {
3425 SSLerr(SSL_F_TLS_CONSTRUCT_NEW_SESSION_TICKET, ERR_R_INTERNAL_ERROR);
3428 senc = OPENSSL_malloc(slen_full);
3430 SSLerr(SSL_F_TLS_CONSTRUCT_NEW_SESSION_TICKET, ERR_R_MALLOC_FAILURE);
3434 ctx = EVP_CIPHER_CTX_new();
3435 hctx = HMAC_CTX_new();
3436 if (ctx == NULL || hctx == NULL) {
3437 SSLerr(SSL_F_TLS_CONSTRUCT_NEW_SESSION_TICKET, ERR_R_MALLOC_FAILURE);
3442 if (!i2d_SSL_SESSION(s->session, &p))
3446 * create a fresh copy (not shared with other threads) to clean up
3449 sess = d2i_SSL_SESSION(NULL, &const_p, slen_full);
3452 sess->session_id_length = 0; /* ID is irrelevant for the ticket */
3454 slen = i2d_SSL_SESSION(sess, NULL);
3455 if (slen == 0 || slen > slen_full) { /* shouldn't ever happen */
3456 SSL_SESSION_free(sess);
3460 if (!i2d_SSL_SESSION(sess, &p)) {
3461 SSL_SESSION_free(sess);
3464 SSL_SESSION_free(sess);
3467 * Initialize HMAC and cipher contexts. If callback present it does
3468 * all the work otherwise use generated values from parent ctx.
3470 if (tctx->ext.ticket_key_cb) {
3471 /* if 0 is returned, write an empty ticket */
3472 int ret = tctx->ext.ticket_key_cb(s, key_name, iv, ctx,
3477 /* Put timeout and length */
3478 if (!WPACKET_put_bytes_u32(pkt, 0)
3479 || !WPACKET_put_bytes_u16(pkt, 0)) {
3480 SSLerr(SSL_F_TLS_CONSTRUCT_NEW_SESSION_TICKET,
3481 ERR_R_INTERNAL_ERROR);
3485 EVP_CIPHER_CTX_free(ctx);
3486 HMAC_CTX_free(hctx);
3491 iv_len = EVP_CIPHER_CTX_iv_length(ctx);
3493 const EVP_CIPHER *cipher = EVP_aes_256_cbc();
3495 iv_len = EVP_CIPHER_iv_length(cipher);
3496 if (RAND_bytes(iv, iv_len) <= 0)
3498 if (!EVP_EncryptInit_ex(ctx, cipher, NULL,
3499 tctx->ext.tick_aes_key, iv))
3501 if (!HMAC_Init_ex(hctx, tctx->ext.tick_hmac_key,
3502 sizeof(tctx->ext.tick_hmac_key),
3503 EVP_sha256(), NULL))
3505 memcpy(key_name, tctx->ext.tick_key_name,
3506 sizeof(tctx->ext.tick_key_name));
3510 * Ticket lifetime hint: For TLSv1.2 this is advisory only and we leave this
3511 * unspecified for resumed session (for simplicity).
3512 * In TLSv1.3 we reset the "time" field above, and always specify the
3515 if (!WPACKET_put_bytes_u32(pkt,
3516 (s->hit && !SSL_IS_TLS13(s))
3517 ? 0 : s->session->timeout)
3519 && !WPACKET_put_bytes_u32(pkt, age_add_u.age_add))
3520 /* Now the actual ticket data */
3521 || !WPACKET_start_sub_packet_u16(pkt)
3522 || !WPACKET_get_total_written(pkt, &macoffset)
3523 /* Output key name */
3524 || !WPACKET_memcpy(pkt, key_name, sizeof(key_name))
3526 || !WPACKET_memcpy(pkt, iv, iv_len)
3527 || !WPACKET_reserve_bytes(pkt, slen + EVP_MAX_BLOCK_LENGTH,
3529 /* Encrypt session data */
3530 || !EVP_EncryptUpdate(ctx, encdata1, &len, senc, slen)
3531 || !WPACKET_allocate_bytes(pkt, len, &encdata2)
3532 || encdata1 != encdata2
3533 || !EVP_EncryptFinal(ctx, encdata1 + len, &lenfinal)
3534 || !WPACKET_allocate_bytes(pkt, lenfinal, &encdata2)
3535 || encdata1 + len != encdata2
3536 || len + lenfinal > slen + EVP_MAX_BLOCK_LENGTH
3537 || !WPACKET_get_total_written(pkt, &macendoffset)
3538 || !HMAC_Update(hctx,
3539 (unsigned char *)s->init_buf->data + macoffset,
3540 macendoffset - macoffset)
3541 || !WPACKET_reserve_bytes(pkt, EVP_MAX_MD_SIZE, &macdata1)
3542 || !HMAC_Final(hctx, macdata1, &hlen)
3543 || hlen > EVP_MAX_MD_SIZE
3544 || !WPACKET_allocate_bytes(pkt, hlen, &macdata2)
3545 || macdata1 != macdata2
3546 || !WPACKET_close(pkt)
3548 && !tls_construct_extensions(s, pkt,
3549 EXT_TLS1_3_NEW_SESSION_TICKET,
3551 SSLerr(SSL_F_TLS_CONSTRUCT_NEW_SESSION_TICKET, ERR_R_INTERNAL_ERROR);
3554 EVP_CIPHER_CTX_free(ctx);
3555 HMAC_CTX_free(hctx);
3560 ossl_statem_set_error(s);
3562 EVP_CIPHER_CTX_free(ctx);
3563 HMAC_CTX_free(hctx);
3564 ssl3_send_alert(s, SSL3_AL_FATAL, SSL_AD_INTERNAL_ERROR);
3569 * In TLSv1.3 this is called from the extensions code, otherwise it is used to
3570 * create a separate message. Returns 1 on success or 0 on failure.
3572 int tls_construct_cert_status_body(SSL *s, WPACKET *pkt)
3574 if (!WPACKET_put_bytes_u8(pkt, s->ext.status_type)
3575 || !WPACKET_sub_memcpy_u24(pkt, s->ext.ocsp.resp,
3576 s->ext.ocsp.resp_len)) {
3577 SSLerr(SSL_F_TLS_CONSTRUCT_CERT_STATUS_BODY, ERR_R_INTERNAL_ERROR);
3584 int tls_construct_cert_status(SSL *s, WPACKET *pkt)
3586 if (!tls_construct_cert_status_body(s, pkt)) {
3587 ssl3_send_alert(s, SSL3_AL_FATAL, SSL_AD_INTERNAL_ERROR);
3594 #ifndef OPENSSL_NO_NEXTPROTONEG
3596 * tls_process_next_proto reads a Next Protocol Negotiation handshake message.
3597 * It sets the next_proto member in s if found
3599 MSG_PROCESS_RETURN tls_process_next_proto(SSL *s, PACKET *pkt)
3601 PACKET next_proto, padding;
3602 size_t next_proto_len;
3605 * The payload looks like:
3607 * uint8 proto[proto_len];
3608 * uint8 padding_len;
3609 * uint8 padding[padding_len];
3611 if (!PACKET_get_length_prefixed_1(pkt, &next_proto)
3612 || !PACKET_get_length_prefixed_1(pkt, &padding)
3613 || PACKET_remaining(pkt) > 0) {
3614 SSLerr(SSL_F_TLS_PROCESS_NEXT_PROTO, SSL_R_LENGTH_MISMATCH);
3618 if (!PACKET_memdup(&next_proto, &s->ext.npn, &next_proto_len)) {
3623 s->ext.npn_len = (unsigned char)next_proto_len;
3625 return MSG_PROCESS_CONTINUE_READING;
3627 ossl_statem_set_error(s);
3628 return MSG_PROCESS_ERROR;
3632 static int tls_construct_encrypted_extensions(SSL *s, WPACKET *pkt)
3636 if (!tls_construct_extensions(s, pkt, EXT_TLS1_3_ENCRYPTED_EXTENSIONS,
3638 ssl3_send_alert(s, SSL3_AL_FATAL, al);
3639 SSLerr(SSL_F_TLS_CONSTRUCT_ENCRYPTED_EXTENSIONS, ERR_R_INTERNAL_ERROR);
3640 ssl3_send_alert(s, SSL3_AL_FATAL, al);
3647 static int tls_construct_hello_retry_request(SSL *s, WPACKET *pkt)
3649 int al = SSL_AD_INTERNAL_ERROR;
3652 * TODO(TLS1.3): Remove the DRAFT version before release
3653 * (should be s->version)
3655 if (!WPACKET_put_bytes_u16(pkt, TLS1_3_VERSION_DRAFT)
3656 || !tls_construct_extensions(s, pkt, EXT_TLS1_3_HELLO_RETRY_REQUEST,
3658 SSLerr(SSL_F_TLS_CONSTRUCT_HELLO_RETRY_REQUEST, ERR_R_INTERNAL_ERROR);
3659 ssl3_send_alert(s, SSL3_AL_FATAL, al);
3663 /* Ditch the session. We'll create a new one next time around */
3664 SSL_SESSION_free(s->session);