2 * Copyright 1995-2016 The OpenSSL Project Authors. All Rights Reserved.
4 * Licensed under the OpenSSL license (the "License"). You may not use
5 * this file except in compliance with the License. You can obtain a copy
6 * in the file LICENSE in the source distribution or at
7 * https://www.openssl.org/source/license.html
10 /* ====================================================================
11 * Copyright 2002 Sun Microsystems, Inc. ALL RIGHTS RESERVED.
13 * Portions of the attached software ("Contribution") are developed by
14 * SUN MICROSYSTEMS, INC., and are contributed to the OpenSSL project.
16 * The Contribution is licensed pursuant to the OpenSSL open source
17 * license provided above.
19 * ECC cipher suite support in OpenSSL originally written by
20 * Vipul Gupta and Sumit Gupta of Sun Microsystems Laboratories.
23 /* ====================================================================
24 * Copyright 2005 Nokia. All rights reserved.
26 * The portions of the attached software ("Contribution") is developed by
27 * Nokia Corporation and is licensed pursuant to the OpenSSL open source
30 * The Contribution, originally written by Mika Kousa and Pasi Eronen of
31 * Nokia Corporation, consists of the "PSK" (Pre-Shared Key) ciphersuites
32 * support (see RFC 4279) to OpenSSL.
34 * No patent licenses or other rights except those expressly stated in
35 * the OpenSSL open source license shall be deemed granted or received
36 * expressly, by implication, estoppel, or otherwise.
38 * No assurances are provided by Nokia that the Contribution does not
39 * infringe the patent or other intellectual property rights of any third
40 * party or that the license provides you with all the necessary rights
41 * to make use of the Contribution.
43 * THE SOFTWARE IS PROVIDED "AS IS" WITHOUT WARRANTY OF ANY KIND. IN
44 * ADDITION TO THE DISCLAIMERS INCLUDED IN THE LICENSE, NOKIA
45 * SPECIFICALLY DISCLAIMS ANY LIABILITY FOR CLAIMS BROUGHT BY YOU OR ANY
46 * OTHER ENTITY BASED ON INFRINGEMENT OF INTELLECTUAL PROPERTY RIGHTS OR
51 #include "../ssl_locl.h"
52 #include "statem_locl.h"
53 #include "internal/constant_time_locl.h"
54 #include <openssl/buffer.h>
55 #include <openssl/rand.h>
56 #include <openssl/objects.h>
57 #include <openssl/evp.h>
58 #include <openssl/hmac.h>
59 #include <openssl/x509.h>
60 #include <openssl/dh.h>
61 #include <openssl/bn.h>
62 #include <openssl/md5.h>
64 static int tls_construct_encrypted_extensions(SSL *s, WPACKET *pkt);
65 static int tls_construct_hello_retry_request(SSL *s, WPACKET *pkt);
68 * ossl_statem_server13_read_transition() encapsulates the logic for the allowed
69 * handshake state transitions when a TLSv1.3 server is reading messages from
70 * the client. The message type that the client has sent is provided in |mt|.
71 * The current state is in |s->statem.hand_state|.
73 * Return values are 1 for success (transition allowed) and 0 on error
74 * (transition not allowed)
76 static int ossl_statem_server13_read_transition(SSL *s, int mt)
78 OSSL_STATEM *st = &s->statem;
81 * Note: There is no case for TLS_ST_BEFORE because at that stage we have
82 * not negotiated TLSv1.3 yet, so that case is handled by
83 * ossl_statem_server_read_transition()
85 switch (st->hand_state) {
89 case TLS_ST_SW_HELLO_RETRY_REQUEST:
90 if (mt == SSL3_MT_CLIENT_HELLO) {
91 st->hand_state = TLS_ST_SR_CLNT_HELLO;
96 case TLS_ST_SW_FINISHED:
97 if (s->s3->tmp.cert_request) {
98 if (mt == SSL3_MT_CERTIFICATE) {
99 st->hand_state = TLS_ST_SR_CERT;
103 if (mt == SSL3_MT_FINISHED) {
104 st->hand_state = TLS_ST_SR_FINISHED;
111 if (s->session->peer == NULL) {
112 if (mt == SSL3_MT_FINISHED) {
113 st->hand_state = TLS_ST_SR_FINISHED;
117 if (mt == SSL3_MT_CERTIFICATE_VERIFY) {
118 st->hand_state = TLS_ST_SR_CERT_VRFY;
124 case TLS_ST_SR_CERT_VRFY:
125 if (mt == SSL3_MT_FINISHED) {
126 st->hand_state = TLS_ST_SR_FINISHED;
132 if (mt == SSL3_MT_KEY_UPDATE) {
133 st->hand_state = TLS_ST_SR_KEY_UPDATE;
139 /* No valid transition found */
140 ssl3_send_alert(s, SSL3_AL_FATAL, SSL3_AD_UNEXPECTED_MESSAGE);
141 SSLerr(SSL_F_OSSL_STATEM_SERVER13_READ_TRANSITION,
142 SSL_R_UNEXPECTED_MESSAGE);
147 * ossl_statem_server_read_transition() encapsulates the logic for the allowed
148 * handshake state transitions when the server is reading messages from the
149 * client. The message type that the client has sent is provided in |mt|. The
150 * current state is in |s->statem.hand_state|.
152 * Return values are 1 for success (transition allowed) and 0 on error
153 * (transition not allowed)
155 int ossl_statem_server_read_transition(SSL *s, int mt)
157 OSSL_STATEM *st = &s->statem;
159 if (SSL_IS_TLS13(s)) {
160 if (!ossl_statem_server13_read_transition(s, mt))
165 switch (st->hand_state) {
171 case DTLS_ST_SW_HELLO_VERIFY_REQUEST:
172 if (mt == SSL3_MT_CLIENT_HELLO) {
173 st->hand_state = TLS_ST_SR_CLNT_HELLO;
178 case TLS_ST_SW_SRVR_DONE:
180 * If we get a CKE message after a ServerDone then either
181 * 1) We didn't request a Certificate
183 * 2) If we did request one then
184 * a) We allow no Certificate to be returned
186 * b) We are running SSL3 (in TLS1.0+ the client must return a 0
187 * list if we requested a certificate)
189 if (mt == SSL3_MT_CLIENT_KEY_EXCHANGE) {
190 if (s->s3->tmp.cert_request) {
191 if (s->version == SSL3_VERSION) {
192 if ((s->verify_mode & SSL_VERIFY_PEER)
193 && (s->verify_mode & SSL_VERIFY_FAIL_IF_NO_PEER_CERT)) {
195 * This isn't an unexpected message as such - we're just
196 * not going to accept it because we require a client
199 ssl3_send_alert(s, SSL3_AL_FATAL,
200 SSL3_AD_HANDSHAKE_FAILURE);
201 SSLerr(SSL_F_OSSL_STATEM_SERVER_READ_TRANSITION,
202 SSL_R_PEER_DID_NOT_RETURN_A_CERTIFICATE);
205 st->hand_state = TLS_ST_SR_KEY_EXCH;
209 st->hand_state = TLS_ST_SR_KEY_EXCH;
212 } else if (s->s3->tmp.cert_request) {
213 if (mt == SSL3_MT_CERTIFICATE) {
214 st->hand_state = TLS_ST_SR_CERT;
221 if (mt == SSL3_MT_CLIENT_KEY_EXCHANGE) {
222 st->hand_state = TLS_ST_SR_KEY_EXCH;
227 case TLS_ST_SR_KEY_EXCH:
229 * We should only process a CertificateVerify message if we have
230 * received a Certificate from the client. If so then |s->session->peer|
231 * will be non NULL. In some instances a CertificateVerify message is
232 * not required even if the peer has sent a Certificate (e.g. such as in
233 * the case of static DH). In that case |st->no_cert_verify| should be
236 if (s->session->peer == NULL || st->no_cert_verify) {
237 if (mt == SSL3_MT_CHANGE_CIPHER_SPEC) {
239 * For the ECDH ciphersuites when the client sends its ECDH
240 * pub key in a certificate, the CertificateVerify message is
241 * not sent. Also for GOST ciphersuites when the client uses
242 * its key from the certificate for key exchange.
244 st->hand_state = TLS_ST_SR_CHANGE;
248 if (mt == SSL3_MT_CERTIFICATE_VERIFY) {
249 st->hand_state = TLS_ST_SR_CERT_VRFY;
255 case TLS_ST_SR_CERT_VRFY:
256 if (mt == SSL3_MT_CHANGE_CIPHER_SPEC) {
257 st->hand_state = TLS_ST_SR_CHANGE;
262 case TLS_ST_SR_CHANGE:
263 #ifndef OPENSSL_NO_NEXTPROTONEG
264 if (s->s3->npn_seen) {
265 if (mt == SSL3_MT_NEXT_PROTO) {
266 st->hand_state = TLS_ST_SR_NEXT_PROTO;
271 if (mt == SSL3_MT_FINISHED) {
272 st->hand_state = TLS_ST_SR_FINISHED;
275 #ifndef OPENSSL_NO_NEXTPROTONEG
280 #ifndef OPENSSL_NO_NEXTPROTONEG
281 case TLS_ST_SR_NEXT_PROTO:
282 if (mt == SSL3_MT_FINISHED) {
283 st->hand_state = TLS_ST_SR_FINISHED;
289 case TLS_ST_SW_FINISHED:
290 if (mt == SSL3_MT_CHANGE_CIPHER_SPEC) {
291 st->hand_state = TLS_ST_SR_CHANGE;
298 /* No valid transition found */
299 ssl3_send_alert(s, SSL3_AL_FATAL, SSL3_AD_UNEXPECTED_MESSAGE);
300 SSLerr(SSL_F_OSSL_STATEM_SERVER_READ_TRANSITION, SSL_R_UNEXPECTED_MESSAGE);
305 * Should we send a ServerKeyExchange message?
307 * Valid return values are:
311 static int send_server_key_exchange(SSL *s)
313 unsigned long alg_k = s->s3->tmp.new_cipher->algorithm_mkey;
316 * only send a ServerKeyExchange if DH or fortezza but we have a
317 * sign only certificate PSK: may send PSK identity hints For
318 * ECC ciphersuites, we send a serverKeyExchange message only if
319 * the cipher suite is either ECDH-anon or ECDHE. In other cases,
320 * the server certificate contains the server's public key for
323 if (alg_k & (SSL_kDHE | SSL_kECDHE)
325 * PSK: send ServerKeyExchange if PSK identity hint if
328 #ifndef OPENSSL_NO_PSK
329 /* Only send SKE if we have identity hint for plain PSK */
330 || ((alg_k & (SSL_kPSK | SSL_kRSAPSK))
331 && s->cert->psk_identity_hint)
332 /* For other PSK always send SKE */
333 || (alg_k & (SSL_PSK & (SSL_kDHEPSK | SSL_kECDHEPSK)))
335 #ifndef OPENSSL_NO_SRP
336 /* SRP: send ServerKeyExchange */
337 || (alg_k & SSL_kSRP)
347 * Should we send a CertificateRequest message?
349 * Valid return values are:
353 static int send_certificate_request(SSL *s)
356 /* don't request cert unless asked for it: */
357 s->verify_mode & SSL_VERIFY_PEER
359 * if SSL_VERIFY_CLIENT_ONCE is set, don't request cert
360 * during re-negotiation:
362 && (s->s3->tmp.finish_md_len == 0 ||
363 !(s->verify_mode & SSL_VERIFY_CLIENT_ONCE))
365 * never request cert in anonymous ciphersuites (see
366 * section "Certificate request" in SSL 3 drafts and in
369 && (!(s->s3->tmp.new_cipher->algorithm_auth & SSL_aNULL)
371 * ... except when the application insists on
372 * verification (against the specs, but statem_clnt.c accepts
375 || (s->verify_mode & SSL_VERIFY_FAIL_IF_NO_PEER_CERT))
376 /* don't request certificate for SRP auth */
377 && !(s->s3->tmp.new_cipher->algorithm_auth & SSL_aSRP)
379 * With normal PSK Certificates and Certificate Requests
382 && !(s->s3->tmp.new_cipher->algorithm_auth & SSL_aPSK)) {
390 * ossl_statem_server13_write_transition() works out what handshake state to
391 * move to next when a TLSv1.3 server is writing messages to be sent to the
394 static WRITE_TRAN ossl_statem_server13_write_transition(SSL *s)
396 OSSL_STATEM *st = &s->statem;
399 * No case for TLS_ST_BEFORE, because at that stage we have not negotiated
400 * TLSv1.3 yet, so that is handled by ossl_statem_server_write_transition()
403 switch (st->hand_state) {
405 /* Shouldn't happen */
406 return WRITE_TRAN_ERROR;
409 if (s->early_data_state == SSL_EARLY_DATA_FINISHED_READING) {
410 st->hand_state = TLS_ST_SW_FINISHED;
411 return WRITE_TRAN_FINISHED;
413 if (s->key_update != SSL_KEY_UPDATE_NONE) {
414 st->hand_state = TLS_ST_SW_KEY_UPDATE;
415 return WRITE_TRAN_CONTINUE;
417 /* Try to read from the client instead */
418 return WRITE_TRAN_FINISHED;
420 case TLS_ST_SR_CLNT_HELLO:
421 if (s->hello_retry_request)
422 st->hand_state = TLS_ST_SW_HELLO_RETRY_REQUEST;
424 st->hand_state = TLS_ST_SW_SRVR_HELLO;
425 return WRITE_TRAN_CONTINUE;
427 case TLS_ST_SW_HELLO_RETRY_REQUEST:
428 return WRITE_TRAN_FINISHED;
430 case TLS_ST_SW_SRVR_HELLO:
431 st->hand_state = TLS_ST_SW_ENCRYPTED_EXTENSIONS;
432 return WRITE_TRAN_CONTINUE;
434 case TLS_ST_SW_ENCRYPTED_EXTENSIONS:
436 st->hand_state = TLS_ST_SW_FINISHED;
437 else if (send_certificate_request(s))
438 st->hand_state = TLS_ST_SW_CERT_REQ;
440 st->hand_state = TLS_ST_SW_CERT;
442 return WRITE_TRAN_CONTINUE;
444 case TLS_ST_SW_CERT_REQ:
445 st->hand_state = TLS_ST_SW_CERT;
446 return WRITE_TRAN_CONTINUE;
449 st->hand_state = TLS_ST_SW_CERT_VRFY;
450 return WRITE_TRAN_CONTINUE;
452 case TLS_ST_SW_CERT_VRFY:
453 st->hand_state = TLS_ST_SW_FINISHED;
454 return WRITE_TRAN_CONTINUE;
456 case TLS_ST_SW_FINISHED:
457 if (s->early_data_state == SSL_EARLY_DATA_ACCEPTING) {
458 st->hand_state = TLS_ST_OK;
459 ossl_statem_set_in_init(s, 0);
460 return WRITE_TRAN_CONTINUE;
462 return WRITE_TRAN_FINISHED;
464 case TLS_ST_SR_FINISHED:
466 * Technically we have finished the handshake at this point, but we're
467 * going to remain "in_init" for now and write out the session ticket
469 * TODO(TLS1.3): Perhaps we need to be able to control this behaviour
470 * and give the application the opportunity to delay sending the
473 st->hand_state = TLS_ST_SW_SESSION_TICKET;
474 return WRITE_TRAN_CONTINUE;
476 case TLS_ST_SR_KEY_UPDATE:
477 if (s->key_update != SSL_KEY_UPDATE_NONE) {
478 st->hand_state = TLS_ST_SW_KEY_UPDATE;
479 return WRITE_TRAN_CONTINUE;
483 case TLS_ST_SW_KEY_UPDATE:
484 case TLS_ST_SW_SESSION_TICKET:
485 st->hand_state = TLS_ST_OK;
486 ossl_statem_set_in_init(s, 0);
487 return WRITE_TRAN_CONTINUE;
492 * ossl_statem_server_write_transition() works out what handshake state to move
493 * to next when the server is writing messages to be sent to the client.
495 WRITE_TRAN ossl_statem_server_write_transition(SSL *s)
497 OSSL_STATEM *st = &s->statem;
500 * Note that before the ClientHello we don't know what version we are going
501 * to negotiate yet, so we don't take this branch until later
505 return ossl_statem_server13_write_transition(s);
507 switch (st->hand_state) {
509 /* Shouldn't happen */
510 return WRITE_TRAN_ERROR;
513 if (st->request_state == TLS_ST_SW_HELLO_REQ) {
514 /* We must be trying to renegotiate */
515 st->hand_state = TLS_ST_SW_HELLO_REQ;
516 st->request_state = TLS_ST_BEFORE;
517 return WRITE_TRAN_CONTINUE;
519 /* Must be an incoming ClientHello */
520 if (!tls_setup_handshake(s)) {
521 ossl_statem_set_error(s);
522 return WRITE_TRAN_ERROR;
527 /* Just go straight to trying to read from the client */
528 return WRITE_TRAN_FINISHED;
530 case TLS_ST_SW_HELLO_REQ:
531 st->hand_state = TLS_ST_OK;
532 ossl_statem_set_in_init(s, 0);
533 return WRITE_TRAN_CONTINUE;
535 case TLS_ST_SR_CLNT_HELLO:
536 if (SSL_IS_DTLS(s) && !s->d1->cookie_verified
537 && (SSL_get_options(s) & SSL_OP_COOKIE_EXCHANGE))
538 st->hand_state = DTLS_ST_SW_HELLO_VERIFY_REQUEST;
540 st->hand_state = TLS_ST_SW_SRVR_HELLO;
541 return WRITE_TRAN_CONTINUE;
543 case DTLS_ST_SW_HELLO_VERIFY_REQUEST:
544 return WRITE_TRAN_FINISHED;
546 case TLS_ST_SW_SRVR_HELLO:
548 if (s->ext.ticket_expected)
549 st->hand_state = TLS_ST_SW_SESSION_TICKET;
551 st->hand_state = TLS_ST_SW_CHANGE;
553 /* Check if it is anon DH or anon ECDH, */
554 /* normal PSK or SRP */
555 if (!(s->s3->tmp.new_cipher->algorithm_auth &
556 (SSL_aNULL | SSL_aSRP | SSL_aPSK))) {
557 st->hand_state = TLS_ST_SW_CERT;
558 } else if (send_server_key_exchange(s)) {
559 st->hand_state = TLS_ST_SW_KEY_EXCH;
560 } else if (send_certificate_request(s)) {
561 st->hand_state = TLS_ST_SW_CERT_REQ;
563 st->hand_state = TLS_ST_SW_SRVR_DONE;
566 return WRITE_TRAN_CONTINUE;
569 if (s->ext.status_expected) {
570 st->hand_state = TLS_ST_SW_CERT_STATUS;
571 return WRITE_TRAN_CONTINUE;
575 case TLS_ST_SW_CERT_STATUS:
576 if (send_server_key_exchange(s)) {
577 st->hand_state = TLS_ST_SW_KEY_EXCH;
578 return WRITE_TRAN_CONTINUE;
582 case TLS_ST_SW_KEY_EXCH:
583 if (send_certificate_request(s)) {
584 st->hand_state = TLS_ST_SW_CERT_REQ;
585 return WRITE_TRAN_CONTINUE;
589 case TLS_ST_SW_CERT_REQ:
590 st->hand_state = TLS_ST_SW_SRVR_DONE;
591 return WRITE_TRAN_CONTINUE;
593 case TLS_ST_SW_SRVR_DONE:
594 return WRITE_TRAN_FINISHED;
596 case TLS_ST_SR_FINISHED:
598 st->hand_state = TLS_ST_OK;
599 ossl_statem_set_in_init(s, 0);
600 return WRITE_TRAN_CONTINUE;
601 } else if (s->ext.ticket_expected) {
602 st->hand_state = TLS_ST_SW_SESSION_TICKET;
604 st->hand_state = TLS_ST_SW_CHANGE;
606 return WRITE_TRAN_CONTINUE;
608 case TLS_ST_SW_SESSION_TICKET:
609 st->hand_state = TLS_ST_SW_CHANGE;
610 return WRITE_TRAN_CONTINUE;
612 case TLS_ST_SW_CHANGE:
613 st->hand_state = TLS_ST_SW_FINISHED;
614 return WRITE_TRAN_CONTINUE;
616 case TLS_ST_SW_FINISHED:
618 return WRITE_TRAN_FINISHED;
620 st->hand_state = TLS_ST_OK;
621 ossl_statem_set_in_init(s, 0);
622 return WRITE_TRAN_CONTINUE;
627 * Perform any pre work that needs to be done prior to sending a message from
628 * the server to the client.
630 WORK_STATE ossl_statem_server_pre_work(SSL *s, WORK_STATE wst)
632 OSSL_STATEM *st = &s->statem;
634 switch (st->hand_state) {
636 /* No pre work to be done */
639 case TLS_ST_SW_HELLO_REQ:
642 dtls1_clear_sent_buffer(s);
645 case DTLS_ST_SW_HELLO_VERIFY_REQUEST:
647 if (SSL_IS_DTLS(s)) {
648 dtls1_clear_sent_buffer(s);
649 /* We don't buffer this message so don't use the timer */
654 case TLS_ST_SW_SRVR_HELLO:
655 if (SSL_IS_DTLS(s)) {
657 * Messages we write from now on should be bufferred and
658 * retransmitted if necessary, so we need to use the timer now
664 case TLS_ST_SW_SRVR_DONE:
665 #ifndef OPENSSL_NO_SCTP
666 if (SSL_IS_DTLS(s) && BIO_dgram_is_sctp(SSL_get_wbio(s)))
667 return dtls_wait_for_dry(s);
669 return WORK_FINISHED_CONTINUE;
671 case TLS_ST_SW_SESSION_TICKET:
672 if (SSL_IS_TLS13(s)) {
674 * Actually this is the end of the handshake, but we're going
675 * straight into writing the session ticket out. So we finish off
676 * the handshake, but keep the various buffers active.
678 return tls_finish_handshake(s, wst, 0);
679 } if (SSL_IS_DTLS(s)) {
681 * We're into the last flight. We don't retransmit the last flight
682 * unless we need to, so we don't use the timer
688 case TLS_ST_SW_CHANGE:
689 s->session->cipher = s->s3->tmp.new_cipher;
690 if (!s->method->ssl3_enc->setup_key_block(s)) {
691 ossl_statem_set_error(s);
694 if (SSL_IS_DTLS(s)) {
696 * We're into the last flight. We don't retransmit the last flight
697 * unless we need to, so we don't use the timer. This might have
698 * already been set to 0 if we sent a NewSessionTicket message,
699 * but we'll set it again here in case we didn't.
703 return WORK_FINISHED_CONTINUE;
706 return tls_finish_handshake(s, wst, 1);
709 return WORK_FINISHED_CONTINUE;
713 * Perform any work that needs to be done after sending a message from the
714 * server to the client.
716 WORK_STATE ossl_statem_server_post_work(SSL *s, WORK_STATE wst)
718 OSSL_STATEM *st = &s->statem;
722 switch (st->hand_state) {
724 /* No post work to be done */
727 case TLS_ST_SW_HELLO_RETRY_REQUEST:
728 if (statem_flush(s) != 1)
732 case TLS_ST_SW_HELLO_REQ:
733 if (statem_flush(s) != 1)
735 if (!ssl3_init_finished_mac(s)) {
736 ossl_statem_set_error(s);
741 case DTLS_ST_SW_HELLO_VERIFY_REQUEST:
742 if (statem_flush(s) != 1)
744 /* HelloVerifyRequest resets Finished MAC */
745 if (s->version != DTLS1_BAD_VER && !ssl3_init_finished_mac(s)) {
746 ossl_statem_set_error(s);
750 * The next message should be another ClientHello which we need to
751 * treat like it was the first packet
756 case TLS_ST_SW_SRVR_HELLO:
757 #ifndef OPENSSL_NO_SCTP
758 if (SSL_IS_DTLS(s) && s->hit) {
759 unsigned char sctpauthkey[64];
760 char labelbuffer[sizeof(DTLS1_SCTP_AUTH_LABEL)];
763 * Add new shared key for SCTP-Auth, will be ignored if no
766 memcpy(labelbuffer, DTLS1_SCTP_AUTH_LABEL,
767 sizeof(DTLS1_SCTP_AUTH_LABEL));
769 if (SSL_export_keying_material(s, sctpauthkey,
770 sizeof(sctpauthkey), labelbuffer,
771 sizeof(labelbuffer), NULL, 0,
773 ossl_statem_set_error(s);
777 BIO_ctrl(SSL_get_wbio(s), BIO_CTRL_DGRAM_SCTP_ADD_AUTH_KEY,
778 sizeof(sctpauthkey), sctpauthkey);
782 * TODO(TLS1.3): This actually causes a problem. We don't yet know
783 * whether the next record we are going to receive is an unencrypted
784 * alert, or an encrypted handshake message. We're going to need
785 * something clever in the record layer for this.
787 if (SSL_IS_TLS13(s)) {
788 if (!s->method->ssl3_enc->setup_key_block(s)
789 || !s->method->ssl3_enc->change_cipher_state(s,
790 SSL3_CC_HANDSHAKE | SSL3_CHANGE_CIPHER_SERVER_WRITE)
791 || !s->method->ssl3_enc->change_cipher_state(s,
792 SSL3_CC_HANDSHAKE |SSL3_CHANGE_CIPHER_SERVER_READ))
797 case TLS_ST_SW_CHANGE:
798 #ifndef OPENSSL_NO_SCTP
799 if (SSL_IS_DTLS(s) && !s->hit) {
801 * Change to new shared key of SCTP-Auth, will be ignored if
804 BIO_ctrl(SSL_get_wbio(s), BIO_CTRL_DGRAM_SCTP_NEXT_AUTH_KEY,
808 if (!s->method->ssl3_enc->change_cipher_state(s,
809 SSL3_CHANGE_CIPHER_SERVER_WRITE))
811 ossl_statem_set_error(s);
816 dtls1_reset_seq_numbers(s, SSL3_CC_WRITE);
819 case TLS_ST_SW_SRVR_DONE:
820 if (statem_flush(s) != 1)
824 case TLS_ST_SW_FINISHED:
825 if (statem_flush(s) != 1)
827 #ifndef OPENSSL_NO_SCTP
828 if (SSL_IS_DTLS(s) && s->hit) {
830 * Change to new shared key of SCTP-Auth, will be ignored if
833 BIO_ctrl(SSL_get_wbio(s), BIO_CTRL_DGRAM_SCTP_NEXT_AUTH_KEY,
837 if (SSL_IS_TLS13(s)) {
838 if (!s->method->ssl3_enc->generate_master_secret(s,
839 s->master_secret, s->handshake_secret, 0,
840 &s->session->master_key_length)
841 || !s->method->ssl3_enc->change_cipher_state(s,
842 SSL3_CC_APPLICATION | SSL3_CHANGE_CIPHER_SERVER_WRITE))
847 case TLS_ST_SW_KEY_UPDATE:
848 if (statem_flush(s) != 1)
850 if (!tls13_update_key(s, 1))
854 case TLS_ST_SW_SESSION_TICKET:
855 if (SSL_IS_TLS13(s) && statem_flush(s) != 1)
860 return WORK_FINISHED_CONTINUE;
864 * Get the message construction function and message type for sending from the
867 * Valid return values are:
871 int ossl_statem_server_construct_message(SSL *s, WPACKET *pkt,
872 confunc_f *confunc, int *mt)
874 OSSL_STATEM *st = &s->statem;
876 switch (st->hand_state) {
878 /* Shouldn't happen */
881 case TLS_ST_SW_CHANGE:
883 *confunc = dtls_construct_change_cipher_spec;
885 *confunc = tls_construct_change_cipher_spec;
886 *mt = SSL3_MT_CHANGE_CIPHER_SPEC;
889 case DTLS_ST_SW_HELLO_VERIFY_REQUEST:
890 *confunc = dtls_construct_hello_verify_request;
891 *mt = DTLS1_MT_HELLO_VERIFY_REQUEST;
894 case TLS_ST_SW_HELLO_REQ:
895 /* No construction function needed */
897 *mt = SSL3_MT_HELLO_REQUEST;
900 case TLS_ST_SW_SRVR_HELLO:
901 *confunc = tls_construct_server_hello;
902 *mt = SSL3_MT_SERVER_HELLO;
906 *confunc = tls_construct_server_certificate;
907 *mt = SSL3_MT_CERTIFICATE;
910 case TLS_ST_SW_CERT_VRFY:
911 *confunc = tls_construct_cert_verify;
912 *mt = SSL3_MT_CERTIFICATE_VERIFY;
916 case TLS_ST_SW_KEY_EXCH:
917 *confunc = tls_construct_server_key_exchange;
918 *mt = SSL3_MT_SERVER_KEY_EXCHANGE;
921 case TLS_ST_SW_CERT_REQ:
922 *confunc = tls_construct_certificate_request;
923 *mt = SSL3_MT_CERTIFICATE_REQUEST;
926 case TLS_ST_SW_SRVR_DONE:
927 *confunc = tls_construct_server_done;
928 *mt = SSL3_MT_SERVER_DONE;
931 case TLS_ST_SW_SESSION_TICKET:
932 *confunc = tls_construct_new_session_ticket;
933 *mt = SSL3_MT_NEWSESSION_TICKET;
936 case TLS_ST_SW_CERT_STATUS:
937 *confunc = tls_construct_cert_status;
938 *mt = SSL3_MT_CERTIFICATE_STATUS;
941 case TLS_ST_SW_FINISHED:
942 *confunc = tls_construct_finished;
943 *mt = SSL3_MT_FINISHED;
946 case TLS_ST_SW_ENCRYPTED_EXTENSIONS:
947 *confunc = tls_construct_encrypted_extensions;
948 *mt = SSL3_MT_ENCRYPTED_EXTENSIONS;
951 case TLS_ST_SW_HELLO_RETRY_REQUEST:
952 *confunc = tls_construct_hello_retry_request;
953 *mt = SSL3_MT_HELLO_RETRY_REQUEST;
956 case TLS_ST_SW_KEY_UPDATE:
957 *confunc = tls_construct_key_update;
958 *mt = SSL3_MT_KEY_UPDATE;
966 * Maximum size (excluding the Handshake header) of a ClientHello message,
967 * calculated as follows:
969 * 2 + # client_version
970 * 32 + # only valid length for random
971 * 1 + # length of session_id
972 * 32 + # maximum size for session_id
973 * 2 + # length of cipher suites
974 * 2^16-2 + # maximum length of cipher suites array
975 * 1 + # length of compression_methods
976 * 2^8-1 + # maximum length of compression methods
977 * 2 + # length of extensions
978 * 2^16-1 # maximum length of extensions
980 #define CLIENT_HELLO_MAX_LENGTH 131396
982 #define CLIENT_KEY_EXCH_MAX_LENGTH 2048
983 #define NEXT_PROTO_MAX_LENGTH 514
986 * Returns the maximum allowed length for the current message that we are
987 * reading. Excludes the message header.
989 size_t ossl_statem_server_max_message_size(SSL *s)
991 OSSL_STATEM *st = &s->statem;
993 switch (st->hand_state) {
995 /* Shouldn't happen */
998 case TLS_ST_SR_CLNT_HELLO:
999 return CLIENT_HELLO_MAX_LENGTH;
1001 case TLS_ST_SR_CERT:
1002 return s->max_cert_list;
1004 case TLS_ST_SR_KEY_EXCH:
1005 return CLIENT_KEY_EXCH_MAX_LENGTH;
1007 case TLS_ST_SR_CERT_VRFY:
1008 return SSL3_RT_MAX_PLAIN_LENGTH;
1010 #ifndef OPENSSL_NO_NEXTPROTONEG
1011 case TLS_ST_SR_NEXT_PROTO:
1012 return NEXT_PROTO_MAX_LENGTH;
1015 case TLS_ST_SR_CHANGE:
1016 return CCS_MAX_LENGTH;
1018 case TLS_ST_SR_FINISHED:
1019 return FINISHED_MAX_LENGTH;
1021 case TLS_ST_SR_KEY_UPDATE:
1022 return KEY_UPDATE_MAX_LENGTH;
1027 * Process a message that the server has received from the client.
1029 MSG_PROCESS_RETURN ossl_statem_server_process_message(SSL *s, PACKET *pkt)
1031 OSSL_STATEM *st = &s->statem;
1033 switch (st->hand_state) {
1035 /* Shouldn't happen */
1036 return MSG_PROCESS_ERROR;
1038 case TLS_ST_SR_CLNT_HELLO:
1039 return tls_process_client_hello(s, pkt);
1041 case TLS_ST_SR_CERT:
1042 return tls_process_client_certificate(s, pkt);
1044 case TLS_ST_SR_KEY_EXCH:
1045 return tls_process_client_key_exchange(s, pkt);
1047 case TLS_ST_SR_CERT_VRFY:
1048 return tls_process_cert_verify(s, pkt);
1050 #ifndef OPENSSL_NO_NEXTPROTONEG
1051 case TLS_ST_SR_NEXT_PROTO:
1052 return tls_process_next_proto(s, pkt);
1055 case TLS_ST_SR_CHANGE:
1056 return tls_process_change_cipher_spec(s, pkt);
1058 case TLS_ST_SR_FINISHED:
1059 return tls_process_finished(s, pkt);
1061 case TLS_ST_SR_KEY_UPDATE:
1062 return tls_process_key_update(s, pkt);
1068 * Perform any further processing required following the receipt of a message
1071 WORK_STATE ossl_statem_server_post_process_message(SSL *s, WORK_STATE wst)
1073 OSSL_STATEM *st = &s->statem;
1075 switch (st->hand_state) {
1077 /* Shouldn't happen */
1080 case TLS_ST_SR_CLNT_HELLO:
1081 return tls_post_process_client_hello(s, wst);
1083 case TLS_ST_SR_KEY_EXCH:
1084 return tls_post_process_client_key_exchange(s, wst);
1086 case TLS_ST_SR_CERT_VRFY:
1087 #ifndef OPENSSL_NO_SCTP
1088 if ( /* Is this SCTP? */
1089 BIO_dgram_is_sctp(SSL_get_wbio(s))
1090 /* Are we renegotiating? */
1091 && s->renegotiate && BIO_dgram_sctp_msg_waiting(SSL_get_rbio(s))) {
1092 s->s3->in_read_app_data = 2;
1093 s->rwstate = SSL_READING;
1094 BIO_clear_retry_flags(SSL_get_rbio(s));
1095 BIO_set_retry_read(SSL_get_rbio(s));
1096 ossl_statem_set_sctp_read_sock(s, 1);
1099 ossl_statem_set_sctp_read_sock(s, 0);
1102 return WORK_FINISHED_CONTINUE;
1104 return WORK_FINISHED_CONTINUE;
1107 #ifndef OPENSSL_NO_SRP
1108 static int ssl_check_srp_ext_ClientHello(SSL *s, int *al)
1110 int ret = SSL_ERROR_NONE;
1112 *al = SSL_AD_UNRECOGNIZED_NAME;
1114 if ((s->s3->tmp.new_cipher->algorithm_mkey & SSL_kSRP) &&
1115 (s->srp_ctx.TLS_ext_srp_username_callback != NULL)) {
1116 if (s->srp_ctx.login == NULL) {
1118 * RFC 5054 says SHOULD reject, we do so if There is no srp
1121 ret = SSL3_AL_FATAL;
1122 *al = SSL_AD_UNKNOWN_PSK_IDENTITY;
1124 ret = SSL_srp_server_param_with_username(s, al);
1131 int dtls_raw_hello_verify_request(WPACKET *pkt, unsigned char *cookie,
1134 /* Always use DTLS 1.0 version: see RFC 6347 */
1135 if (!WPACKET_put_bytes_u16(pkt, DTLS1_VERSION)
1136 || !WPACKET_sub_memcpy_u8(pkt, cookie, cookie_len))
1142 int dtls_construct_hello_verify_request(SSL *s, WPACKET *pkt)
1144 unsigned int cookie_leni;
1145 if (s->ctx->app_gen_cookie_cb == NULL ||
1146 s->ctx->app_gen_cookie_cb(s, s->d1->cookie,
1147 &cookie_leni) == 0 ||
1148 cookie_leni > 255) {
1149 SSLerr(SSL_F_DTLS_CONSTRUCT_HELLO_VERIFY_REQUEST,
1150 SSL_R_COOKIE_GEN_CALLBACK_FAILURE);
1153 s->d1->cookie_len = cookie_leni;
1155 if (!dtls_raw_hello_verify_request(pkt, s->d1->cookie,
1156 s->d1->cookie_len)) {
1157 SSLerr(SSL_F_DTLS_CONSTRUCT_HELLO_VERIFY_REQUEST, ERR_R_INTERNAL_ERROR);
1164 #ifndef OPENSSL_NO_EC
1166 * ssl_check_for_safari attempts to fingerprint Safari using OS X
1167 * SecureTransport using the TLS extension block in |hello|.
1168 * Safari, since 10.6, sends exactly these extensions, in this order:
1173 * We wish to fingerprint Safari because they broke ECDHE-ECDSA support in 10.8,
1174 * but they advertise support. So enabling ECDHE-ECDSA ciphers breaks them.
1175 * Sadly we cannot differentiate 10.6, 10.7 and 10.8.4 (which work), from
1176 * 10.8..10.8.3 (which don't work).
1178 static void ssl_check_for_safari(SSL *s, const CLIENTHELLO_MSG *hello)
1180 static const unsigned char kSafariExtensionsBlock[] = {
1181 0x00, 0x0a, /* elliptic_curves extension */
1182 0x00, 0x08, /* 8 bytes */
1183 0x00, 0x06, /* 6 bytes of curve ids */
1184 0x00, 0x17, /* P-256 */
1185 0x00, 0x18, /* P-384 */
1186 0x00, 0x19, /* P-521 */
1188 0x00, 0x0b, /* ec_point_formats */
1189 0x00, 0x02, /* 2 bytes */
1190 0x01, /* 1 point format */
1191 0x00, /* uncompressed */
1192 /* The following is only present in TLS 1.2 */
1193 0x00, 0x0d, /* signature_algorithms */
1194 0x00, 0x0c, /* 12 bytes */
1195 0x00, 0x0a, /* 10 bytes */
1196 0x05, 0x01, /* SHA-384/RSA */
1197 0x04, 0x01, /* SHA-256/RSA */
1198 0x02, 0x01, /* SHA-1/RSA */
1199 0x04, 0x03, /* SHA-256/ECDSA */
1200 0x02, 0x03, /* SHA-1/ECDSA */
1202 /* Length of the common prefix (first two extensions). */
1203 static const size_t kSafariCommonExtensionsLength = 18;
1208 tmppkt = hello->extensions;
1210 if (!PACKET_forward(&tmppkt, 2)
1211 || !PACKET_get_net_2(&tmppkt, &type)
1212 || !PACKET_get_length_prefixed_2(&tmppkt, &sni)) {
1216 if (type != TLSEXT_TYPE_server_name)
1219 ext_len = TLS1_get_client_version(s) >= TLS1_2_VERSION ?
1220 sizeof(kSafariExtensionsBlock) : kSafariCommonExtensionsLength;
1222 s->s3->is_probably_safari = PACKET_equal(&tmppkt, kSafariExtensionsBlock,
1225 #endif /* !OPENSSL_NO_EC */
1227 MSG_PROCESS_RETURN tls_process_client_hello(SSL *s, PACKET *pkt)
1229 int al = SSL_AD_INTERNAL_ERROR;
1230 /* |cookie| will only be initialized for DTLS. */
1231 PACKET session_id, compression, extensions, cookie;
1232 static const unsigned char null_compression = 0;
1233 CLIENTHELLO_MSG *clienthello;
1235 clienthello = OPENSSL_zalloc(sizeof(*clienthello));
1236 if (clienthello == NULL) {
1237 SSLerr(SSL_F_TLS_PROCESS_CLIENT_HELLO, ERR_R_INTERNAL_ERROR);
1240 /* Check if this is actually an unexpected renegotiation ClientHello */
1241 if (s->renegotiate == 0 && !SSL_IS_FIRST_HANDSHAKE(s)) {
1247 * First, parse the raw ClientHello data into the CLIENTHELLO_MSG structure.
1249 clienthello->isv2 = RECORD_LAYER_is_sslv2_record(&s->rlayer);
1250 PACKET_null_init(&cookie);
1252 if (clienthello->isv2) {
1255 if (!SSL_IS_FIRST_HANDSHAKE(s) || s->hello_retry_request) {
1256 al = SSL_AD_HANDSHAKE_FAILURE;
1257 SSLerr(SSL_F_TLS_PROCESS_CLIENT_HELLO, SSL_R_UNEXPECTED_MESSAGE);
1262 * An SSLv3/TLSv1 backwards-compatible CLIENT-HELLO in an SSLv2
1263 * header is sent directly on the wire, not wrapped as a TLS
1264 * record. Our record layer just processes the message length and passes
1265 * the rest right through. Its format is:
1267 * 0-1 msg_length - decoded by the record layer
1268 * 2 msg_type - s->init_msg points here
1270 * 5-6 cipher_spec_length
1271 * 7-8 session_id_length
1272 * 9-10 challenge_length
1276 if (!PACKET_get_1(pkt, &mt)
1277 || mt != SSL2_MT_CLIENT_HELLO) {
1279 * Should never happen. We should have tested this in the record
1280 * layer in order to have determined that this is a SSLv2 record
1281 * in the first place
1283 SSLerr(SSL_F_TLS_PROCESS_CLIENT_HELLO, ERR_R_INTERNAL_ERROR);
1288 if (!PACKET_get_net_2(pkt, &clienthello->legacy_version)) {
1289 al = SSL_AD_DECODE_ERROR;
1290 SSLerr(SSL_F_TLS_PROCESS_CLIENT_HELLO, SSL_R_LENGTH_TOO_SHORT);
1294 /* Parse the message and load client random. */
1295 if (clienthello->isv2) {
1297 * Handle an SSLv2 backwards compatible ClientHello
1298 * Note, this is only for SSLv3+ using the backward compatible format.
1299 * Real SSLv2 is not supported, and is rejected below.
1301 unsigned int ciphersuite_len, session_id_len, challenge_len;
1304 if (!PACKET_get_net_2(pkt, &ciphersuite_len)
1305 || !PACKET_get_net_2(pkt, &session_id_len)
1306 || !PACKET_get_net_2(pkt, &challenge_len)) {
1307 SSLerr(SSL_F_TLS_PROCESS_CLIENT_HELLO,
1308 SSL_R_RECORD_LENGTH_MISMATCH);
1309 al = SSL_AD_DECODE_ERROR;
1313 if (session_id_len > SSL_MAX_SSL_SESSION_ID_LENGTH) {
1314 al = SSL_AD_DECODE_ERROR;
1315 SSLerr(SSL_F_TLS_PROCESS_CLIENT_HELLO, SSL_R_LENGTH_MISMATCH);
1319 if (!PACKET_get_sub_packet(pkt, &clienthello->ciphersuites,
1321 || !PACKET_copy_bytes(pkt, clienthello->session_id, session_id_len)
1322 || !PACKET_get_sub_packet(pkt, &challenge, challenge_len)
1323 /* No extensions. */
1324 || PACKET_remaining(pkt) != 0) {
1325 SSLerr(SSL_F_TLS_PROCESS_CLIENT_HELLO,
1326 SSL_R_RECORD_LENGTH_MISMATCH);
1327 al = SSL_AD_DECODE_ERROR;
1330 clienthello->session_id_len = session_id_len;
1332 /* Load the client random and compression list. We use SSL3_RANDOM_SIZE
1333 * here rather than sizeof(clienthello->random) because that is the limit
1334 * for SSLv3 and it is fixed. It won't change even if
1335 * sizeof(clienthello->random) does.
1337 challenge_len = challenge_len > SSL3_RANDOM_SIZE
1338 ? SSL3_RANDOM_SIZE : challenge_len;
1339 memset(clienthello->random, 0, SSL3_RANDOM_SIZE);
1340 if (!PACKET_copy_bytes(&challenge,
1341 clienthello->random + SSL3_RANDOM_SIZE -
1342 challenge_len, challenge_len)
1343 /* Advertise only null compression. */
1344 || !PACKET_buf_init(&compression, &null_compression, 1)) {
1345 SSLerr(SSL_F_TLS_PROCESS_CLIENT_HELLO, ERR_R_INTERNAL_ERROR);
1346 al = SSL_AD_INTERNAL_ERROR;
1350 PACKET_null_init(&clienthello->extensions);
1352 /* Regular ClientHello. */
1353 if (!PACKET_copy_bytes(pkt, clienthello->random, SSL3_RANDOM_SIZE)
1354 || !PACKET_get_length_prefixed_1(pkt, &session_id)
1355 || !PACKET_copy_all(&session_id, clienthello->session_id,
1356 SSL_MAX_SSL_SESSION_ID_LENGTH,
1357 &clienthello->session_id_len)) {
1358 al = SSL_AD_DECODE_ERROR;
1359 SSLerr(SSL_F_TLS_PROCESS_CLIENT_HELLO, SSL_R_LENGTH_MISMATCH);
1363 if (SSL_IS_DTLS(s)) {
1364 if (!PACKET_get_length_prefixed_1(pkt, &cookie)) {
1365 al = SSL_AD_DECODE_ERROR;
1366 SSLerr(SSL_F_TLS_PROCESS_CLIENT_HELLO, SSL_R_LENGTH_MISMATCH);
1369 if (!PACKET_copy_all(&cookie, clienthello->dtls_cookie,
1370 DTLS1_COOKIE_LENGTH,
1371 &clienthello->dtls_cookie_len)) {
1372 al = SSL_AD_DECODE_ERROR;
1373 SSLerr(SSL_F_TLS_PROCESS_CLIENT_HELLO, SSL_R_LENGTH_MISMATCH);
1377 * If we require cookies and this ClientHello doesn't contain one,
1378 * just return since we do not want to allocate any memory yet.
1379 * So check cookie length...
1381 if (SSL_get_options(s) & SSL_OP_COOKIE_EXCHANGE) {
1382 if (clienthello->dtls_cookie_len == 0)
1387 if (!PACKET_get_length_prefixed_2(pkt, &clienthello->ciphersuites)) {
1388 al = SSL_AD_DECODE_ERROR;
1389 SSLerr(SSL_F_TLS_PROCESS_CLIENT_HELLO, SSL_R_LENGTH_MISMATCH);
1393 if (!PACKET_get_length_prefixed_1(pkt, &compression)) {
1394 al = SSL_AD_DECODE_ERROR;
1395 SSLerr(SSL_F_TLS_PROCESS_CLIENT_HELLO, SSL_R_LENGTH_MISMATCH);
1399 /* Could be empty. */
1400 if (PACKET_remaining(pkt) == 0) {
1401 PACKET_null_init(&clienthello->extensions);
1403 if (!PACKET_get_length_prefixed_2(pkt, &clienthello->extensions)) {
1404 al = SSL_AD_DECODE_ERROR;
1405 SSLerr(SSL_F_TLS_PROCESS_CLIENT_HELLO, SSL_R_LENGTH_MISMATCH);
1411 if (!PACKET_copy_all(&compression, clienthello->compressions,
1412 MAX_COMPRESSIONS_SIZE,
1413 &clienthello->compressions_len)) {
1414 al = SSL_AD_DECODE_ERROR;
1415 SSLerr(SSL_F_TLS_PROCESS_CLIENT_HELLO, SSL_R_LENGTH_MISMATCH);
1419 /* Preserve the raw extensions PACKET for later use */
1420 extensions = clienthello->extensions;
1421 if (!tls_collect_extensions(s, &extensions, EXT_CLIENT_HELLO,
1422 &clienthello->pre_proc_exts, &al,
1423 &clienthello->pre_proc_exts_len)) {
1424 /* SSLerr already been called */
1427 s->clienthello = clienthello;
1429 return MSG_PROCESS_CONTINUE_PROCESSING;
1431 ssl3_send_alert(s, SSL3_AL_FATAL, al);
1433 ossl_statem_set_error(s);
1435 OPENSSL_free(clienthello->pre_proc_exts);
1436 OPENSSL_free(clienthello);
1438 return MSG_PROCESS_ERROR;
1441 static int tls_early_post_process_client_hello(SSL *s, int *al)
1448 #ifndef OPENSSL_NO_COMP
1449 SSL_COMP *comp = NULL;
1451 const SSL_CIPHER *c;
1452 STACK_OF(SSL_CIPHER) *ciphers = NULL;
1453 STACK_OF(SSL_CIPHER) *scsvs = NULL;
1454 CLIENTHELLO_MSG *clienthello = s->clienthello;
1456 *al = SSL_AD_INTERNAL_ERROR;
1457 /* Finished parsing the ClientHello, now we can start processing it */
1458 /* Give the early callback a crack at things */
1459 if (s->ctx->early_cb != NULL) {
1461 /* A failure in the early callback terminates the connection. */
1462 code = s->ctx->early_cb(s, al, s->ctx->early_cb_arg);
1466 s->rwstate = SSL_EARLY_WORK;
1471 /* Set up the client_random */
1472 memcpy(s->s3->client_random, clienthello->random, SSL3_RANDOM_SIZE);
1474 /* Choose the version */
1476 if (clienthello->isv2) {
1477 if (clienthello->legacy_version == SSL2_VERSION
1478 || (clienthello->legacy_version & 0xff00)
1479 != (SSL3_VERSION_MAJOR << 8)) {
1481 * This is real SSLv2 or something complete unknown. We don't
1484 SSLerr(SSL_F_TLS_EARLY_POST_PROCESS_CLIENT_HELLO, SSL_R_UNKNOWN_PROTOCOL);
1488 s->client_version = clienthello->legacy_version;
1491 * Do SSL/TLS version negotiation if applicable. For DTLS we just check
1492 * versions are potentially compatible. Version negotiation comes later.
1494 if (!SSL_IS_DTLS(s)) {
1495 protverr = ssl_choose_server_version(s, clienthello);
1496 } else if (s->method->version != DTLS_ANY_VERSION &&
1497 DTLS_VERSION_LT((int)clienthello->legacy_version, s->version)) {
1498 protverr = SSL_R_VERSION_TOO_LOW;
1504 SSLerr(SSL_F_TLS_EARLY_POST_PROCESS_CLIENT_HELLO, protverr);
1505 if (SSL_IS_FIRST_HANDSHAKE(s)) {
1506 /* like ssl3_get_record, send alert using remote version number */
1507 s->version = s->client_version = clienthello->legacy_version;
1509 *al = SSL_AD_PROTOCOL_VERSION;
1513 if (SSL_IS_DTLS(s)) {
1514 /* Empty cookie was already handled above by returning early. */
1515 if (SSL_get_options(s) & SSL_OP_COOKIE_EXCHANGE) {
1516 if (s->ctx->app_verify_cookie_cb != NULL) {
1517 if (s->ctx->app_verify_cookie_cb(s, clienthello->dtls_cookie,
1518 clienthello->dtls_cookie_len) == 0) {
1519 *al = SSL_AD_HANDSHAKE_FAILURE;
1520 SSLerr(SSL_F_TLS_EARLY_POST_PROCESS_CLIENT_HELLO,
1521 SSL_R_COOKIE_MISMATCH);
1523 /* else cookie verification succeeded */
1525 /* default verification */
1526 } else if (s->d1->cookie_len != clienthello->dtls_cookie_len
1527 || memcmp(clienthello->dtls_cookie, s->d1->cookie,
1528 s->d1->cookie_len) != 0) {
1529 *al = SSL_AD_HANDSHAKE_FAILURE;
1530 SSLerr(SSL_F_TLS_EARLY_POST_PROCESS_CLIENT_HELLO, SSL_R_COOKIE_MISMATCH);
1533 s->d1->cookie_verified = 1;
1535 if (s->method->version == DTLS_ANY_VERSION) {
1536 protverr = ssl_choose_server_version(s, clienthello);
1537 if (protverr != 0) {
1538 SSLerr(SSL_F_TLS_EARLY_POST_PROCESS_CLIENT_HELLO, protverr);
1539 s->version = s->client_version;
1540 *al = SSL_AD_PROTOCOL_VERSION;
1548 /* We need to do this before getting the session */
1549 if (!tls_parse_extension(s, TLSEXT_IDX_extended_master_secret,
1551 clienthello->pre_proc_exts, NULL, 0, al)) {
1552 SSLerr(SSL_F_TLS_EARLY_POST_PROCESS_CLIENT_HELLO, SSL_R_CLIENTHELLO_TLSEXT);
1557 * We don't allow resumption in a backwards compatible ClientHello.
1558 * TODO(openssl-team): in TLS1.1+, session_id MUST be empty.
1560 * Versions before 0.9.7 always allow clients to resume sessions in
1561 * renegotiation. 0.9.7 and later allow this by default, but optionally
1562 * ignore resumption requests with flag
1563 * SSL_OP_NO_SESSION_RESUMPTION_ON_RENEGOTIATION (it's a new flag rather
1564 * than a change to default behavior so that applications relying on
1565 * this for security won't even compile against older library versions).
1566 * 1.0.1 and later also have a function SSL_renegotiate_abbreviated() to
1567 * request renegotiation but not a new session (s->new_session remains
1568 * unset): for servers, this essentially just means that the
1569 * SSL_OP_NO_SESSION_RESUMPTION_ON_RENEGOTIATION setting will be
1572 if (clienthello->isv2 ||
1574 (s->options & SSL_OP_NO_SESSION_RESUMPTION_ON_RENEGOTIATION))) {
1575 if (!ssl_get_new_session(s, 1))
1578 i = ssl_get_prev_session(s, clienthello, al);
1580 /* previous session */
1582 } else if (i == -1) {
1586 if (!ssl_get_new_session(s, 1))
1591 if (!ssl_cache_cipherlist(s, &clienthello->ciphersuites,
1592 clienthello->isv2, al) ||
1593 !bytes_to_cipher_list(s, &clienthello->ciphersuites, &ciphers, &scsvs,
1594 clienthello->isv2, al)) {
1598 s->s3->send_connection_binding = 0;
1599 /* Check what signalling cipher-suite values were received. */
1600 if (scsvs != NULL) {
1601 for(i = 0; i < sk_SSL_CIPHER_num(scsvs); i++) {
1602 c = sk_SSL_CIPHER_value(scsvs, i);
1603 if (SSL_CIPHER_get_id(c) == SSL3_CK_SCSV) {
1604 if (s->renegotiate) {
1605 /* SCSV is fatal if renegotiating */
1606 SSLerr(SSL_F_TLS_EARLY_POST_PROCESS_CLIENT_HELLO,
1607 SSL_R_SCSV_RECEIVED_WHEN_RENEGOTIATING);
1608 *al = SSL_AD_HANDSHAKE_FAILURE;
1611 s->s3->send_connection_binding = 1;
1612 } else if (SSL_CIPHER_get_id(c) == SSL3_CK_FALLBACK_SCSV &&
1613 !ssl_check_version_downgrade(s)) {
1615 * This SCSV indicates that the client previously tried
1616 * a higher version. We should fail if the current version
1617 * is an unexpected downgrade, as that indicates that the first
1618 * connection may have been tampered with in order to trigger
1619 * an insecure downgrade.
1621 SSLerr(SSL_F_TLS_EARLY_POST_PROCESS_CLIENT_HELLO,
1622 SSL_R_INAPPROPRIATE_FALLBACK);
1623 *al = SSL_AD_INAPPROPRIATE_FALLBACK;
1629 /* If it is a hit, check that the cipher is in the list */
1632 id = s->session->cipher->id;
1635 fprintf(stderr, "client sent %d ciphers\n", sk_SSL_CIPHER_num(ciphers));
1637 for (i = 0; i < sk_SSL_CIPHER_num(ciphers); i++) {
1638 c = sk_SSL_CIPHER_value(ciphers, i);
1640 fprintf(stderr, "client [%2d of %2d]:%s\n",
1641 i, sk_SSL_CIPHER_num(ciphers), SSL_CIPHER_get_name(c));
1650 * we need to have the cipher in the cipher list if we are asked
1653 *al = SSL_AD_ILLEGAL_PARAMETER;
1654 SSLerr(SSL_F_TLS_EARLY_POST_PROCESS_CLIENT_HELLO,
1655 SSL_R_REQUIRED_CIPHER_MISSING);
1660 for (loop = 0; loop < clienthello->compressions_len; loop++) {
1661 if (clienthello->compressions[loop] == 0)
1665 if (loop >= clienthello->compressions_len) {
1667 *al = SSL_AD_DECODE_ERROR;
1668 SSLerr(SSL_F_TLS_EARLY_POST_PROCESS_CLIENT_HELLO, SSL_R_NO_COMPRESSION_SPECIFIED);
1672 #ifndef OPENSSL_NO_EC
1673 if (s->options & SSL_OP_SAFARI_ECDHE_ECDSA_BUG)
1674 ssl_check_for_safari(s, clienthello);
1675 #endif /* !OPENSSL_NO_EC */
1677 /* TLS extensions */
1678 if (!tls_parse_all_extensions(s, EXT_CLIENT_HELLO,
1679 clienthello->pre_proc_exts, NULL, 0, al)) {
1680 SSLerr(SSL_F_TLS_EARLY_POST_PROCESS_CLIENT_HELLO, SSL_R_PARSE_TLSEXT);
1685 * Check if we want to use external pre-shared secret for this handshake
1686 * for not reused session only. We need to generate server_random before
1687 * calling tls_session_secret_cb in order to allow SessionTicket
1688 * processing to use it in key derivation.
1692 pos = s->s3->server_random;
1693 if (ssl_fill_hello_random(s, 1, pos, SSL3_RANDOM_SIZE) <= 0) {
1698 if (!s->hit && s->version >= TLS1_VERSION && s->ext.session_secret_cb) {
1699 const SSL_CIPHER *pref_cipher = NULL;
1701 * s->session->master_key_length is a size_t, but this is an int for
1702 * backwards compat reasons
1704 int master_key_length;
1706 master_key_length = sizeof(s->session->master_key);
1707 if (s->ext.session_secret_cb(s, s->session->master_key,
1708 &master_key_length, ciphers,
1710 s->ext.session_secret_cb_arg)
1711 && master_key_length > 0) {
1712 s->session->master_key_length = master_key_length;
1714 s->session->ciphers = ciphers;
1715 s->session->verify_result = X509_V_OK;
1719 /* check if some cipher was preferred by call back */
1720 if (pref_cipher == NULL)
1721 pref_cipher = ssl3_choose_cipher(s, s->session->ciphers,
1722 SSL_get_ciphers(s));
1723 if (pref_cipher == NULL) {
1724 *al = SSL_AD_HANDSHAKE_FAILURE;
1725 SSLerr(SSL_F_TLS_EARLY_POST_PROCESS_CLIENT_HELLO, SSL_R_NO_SHARED_CIPHER);
1729 s->session->cipher = pref_cipher;
1730 sk_SSL_CIPHER_free(s->cipher_list);
1731 s->cipher_list = sk_SSL_CIPHER_dup(s->session->ciphers);
1732 sk_SSL_CIPHER_free(s->cipher_list_by_id);
1733 s->cipher_list_by_id = sk_SSL_CIPHER_dup(s->session->ciphers);
1738 * Worst case, we will use the NULL compression, but if we have other
1739 * options, we will now look for them. We have complen-1 compression
1740 * algorithms from the client, starting at q.
1742 s->s3->tmp.new_compression = NULL;
1743 #ifndef OPENSSL_NO_COMP
1744 /* This only happens if we have a cache hit */
1745 if (s->session->compress_meth != 0 && !SSL_IS_TLS13(s)) {
1746 int m, comp_id = s->session->compress_meth;
1748 /* Perform sanity checks on resumed compression algorithm */
1749 /* Can't disable compression */
1750 if (!ssl_allow_compression(s)) {
1751 SSLerr(SSL_F_TLS_EARLY_POST_PROCESS_CLIENT_HELLO,
1752 SSL_R_INCONSISTENT_COMPRESSION);
1755 /* Look for resumed compression method */
1756 for (m = 0; m < sk_SSL_COMP_num(s->ctx->comp_methods); m++) {
1757 comp = sk_SSL_COMP_value(s->ctx->comp_methods, m);
1758 if (comp_id == comp->id) {
1759 s->s3->tmp.new_compression = comp;
1763 if (s->s3->tmp.new_compression == NULL) {
1764 SSLerr(SSL_F_TLS_EARLY_POST_PROCESS_CLIENT_HELLO,
1765 SSL_R_INVALID_COMPRESSION_ALGORITHM);
1768 /* Look for resumed method in compression list */
1769 for (k = 0; k < clienthello->compressions_len; k++) {
1770 if (clienthello->compressions[k] == comp_id)
1773 if (k >= clienthello->compressions_len) {
1774 *al = SSL_AD_ILLEGAL_PARAMETER;
1775 SSLerr(SSL_F_TLS_EARLY_POST_PROCESS_CLIENT_HELLO,
1776 SSL_R_REQUIRED_COMPRESSION_ALGORITHM_MISSING);
1779 } else if (s->hit) {
1781 } else if (ssl_allow_compression(s) && s->ctx->comp_methods
1782 && !SSL_IS_TLS13(s)) {
1783 /* See if we have a match */
1784 int m, nn, v, done = 0;
1787 nn = sk_SSL_COMP_num(s->ctx->comp_methods);
1788 for (m = 0; m < nn; m++) {
1789 comp = sk_SSL_COMP_value(s->ctx->comp_methods, m);
1791 for (o = 0; o < clienthello->compressions_len; o++) {
1792 if (v == clienthello->compressions[o]) {
1801 s->s3->tmp.new_compression = comp;
1807 * If compression is disabled we'd better not try to resume a session
1808 * using compression.
1810 if (s->session->compress_meth != 0) {
1811 SSLerr(SSL_F_TLS_EARLY_POST_PROCESS_CLIENT_HELLO, SSL_R_INCONSISTENT_COMPRESSION);
1817 * Given s->session->ciphers and SSL_get_ciphers, we must pick a cipher
1821 #ifdef OPENSSL_NO_COMP
1822 s->session->compress_meth = 0;
1824 s->session->compress_meth = (comp == NULL) ? 0 : comp->id;
1826 sk_SSL_CIPHER_free(s->session->ciphers);
1827 s->session->ciphers = ciphers;
1828 if (ciphers == NULL) {
1829 *al = SSL_AD_INTERNAL_ERROR;
1830 SSLerr(SSL_F_TLS_EARLY_POST_PROCESS_CLIENT_HELLO, ERR_R_INTERNAL_ERROR);
1834 if (!tls1_set_server_sigalgs(s)) {
1835 SSLerr(SSL_F_TLS_EARLY_POST_PROCESS_CLIENT_HELLO, SSL_R_CLIENTHELLO_TLSEXT);
1840 sk_SSL_CIPHER_free(ciphers);
1841 sk_SSL_CIPHER_free(scsvs);
1842 OPENSSL_free(clienthello->pre_proc_exts);
1843 OPENSSL_free(s->clienthello);
1844 s->clienthello = NULL;
1847 ossl_statem_set_error(s);
1849 sk_SSL_CIPHER_free(ciphers);
1850 sk_SSL_CIPHER_free(scsvs);
1851 OPENSSL_free(clienthello->pre_proc_exts);
1852 OPENSSL_free(s->clienthello);
1853 s->clienthello = NULL;
1859 * Call the status request callback if needed. Upon success, returns 1.
1860 * Upon failure, returns 0 and sets |*al| to the appropriate fatal alert.
1862 static int tls_handle_status_request(SSL *s, int *al)
1864 s->ext.status_expected = 0;
1867 * If status request then ask callback what to do. Note: this must be
1868 * called after servername callbacks in case the certificate has changed,
1869 * and must be called after the cipher has been chosen because this may
1870 * influence which certificate is sent
1872 if (s->ext.status_type != TLSEXT_STATUSTYPE_nothing && s->ctx != NULL
1873 && s->ctx->ext.status_cb != NULL) {
1876 /* If no certificate can't return certificate status */
1877 if (s->s3->tmp.cert != NULL) {
1879 * Set current certificate to one we will use so SSL_get_certificate
1880 * et al can pick it up.
1882 s->cert->key = s->s3->tmp.cert;
1883 ret = s->ctx->ext.status_cb(s, s->ctx->ext.status_arg);
1885 /* We don't want to send a status request response */
1886 case SSL_TLSEXT_ERR_NOACK:
1887 s->ext.status_expected = 0;
1889 /* status request response should be sent */
1890 case SSL_TLSEXT_ERR_OK:
1891 if (s->ext.ocsp.resp)
1892 s->ext.status_expected = 1;
1894 /* something bad happened */
1895 case SSL_TLSEXT_ERR_ALERT_FATAL:
1897 *al = SSL_AD_INTERNAL_ERROR;
1906 WORK_STATE tls_post_process_client_hello(SSL *s, WORK_STATE wst)
1908 int al = SSL_AD_HANDSHAKE_FAILURE;
1909 const SSL_CIPHER *cipher;
1911 if (wst == WORK_MORE_A) {
1912 int rv = tls_early_post_process_client_hello(s, &al);
1914 /* SSLErr() was already called */
1921 if (wst == WORK_MORE_B) {
1923 /* Let cert callback update server certificates if required */
1924 if (s->cert->cert_cb) {
1925 int rv = s->cert->cert_cb(s, s->cert->cert_cb_arg);
1927 al = SSL_AD_INTERNAL_ERROR;
1928 SSLerr(SSL_F_TLS_POST_PROCESS_CLIENT_HELLO,
1929 SSL_R_CERT_CB_ERROR);
1933 s->rwstate = SSL_X509_LOOKUP;
1936 s->rwstate = SSL_NOTHING;
1939 ssl3_choose_cipher(s, s->session->ciphers, SSL_get_ciphers(s));
1941 if (cipher == NULL) {
1942 SSLerr(SSL_F_TLS_POST_PROCESS_CLIENT_HELLO,
1943 SSL_R_NO_SHARED_CIPHER);
1946 s->s3->tmp.new_cipher = cipher;
1947 if (!tls_choose_sigalg(s, &al))
1949 /* check whether we should disable session resumption */
1950 if (s->not_resumable_session_cb != NULL)
1951 s->session->not_resumable =
1952 s->not_resumable_session_cb(s, ((cipher->algorithm_mkey
1953 & (SSL_kDHE | SSL_kECDHE))
1955 if (s->session->not_resumable)
1956 /* do not send a session ticket */
1957 s->ext.ticket_expected = 0;
1959 /* Session-id reuse */
1960 s->s3->tmp.new_cipher = s->session->cipher;
1964 * we now have the following setup.
1966 * cipher_list - our preferred list of ciphers
1967 * ciphers - the clients preferred list of ciphers
1968 * compression - basically ignored right now
1969 * ssl version is set - sslv3
1970 * s->session - The ssl session has been setup.
1971 * s->hit - session reuse flag
1972 * s->s3->tmp.new_cipher- the new cipher to use.
1976 * Call status_request callback if needed. Has to be done after the
1977 * certificate callbacks etc above.
1979 if (!tls_handle_status_request(s, &al)) {
1980 SSLerr(SSL_F_TLS_POST_PROCESS_CLIENT_HELLO,
1981 SSL_R_CLIENTHELLO_TLSEXT);
1987 #ifndef OPENSSL_NO_SRP
1988 if (wst == WORK_MORE_C) {
1990 if ((ret = ssl_check_srp_ext_ClientHello(s, &al)) < 0) {
1992 * callback indicates further work to be done
1994 s->rwstate = SSL_X509_LOOKUP;
1997 if (ret != SSL_ERROR_NONE) {
1999 * This is not really an error but the only means to for
2000 * a client to detect whether srp is supported.
2002 if (al != TLS1_AD_UNKNOWN_PSK_IDENTITY)
2003 SSLerr(SSL_F_TLS_POST_PROCESS_CLIENT_HELLO,
2004 SSL_R_CLIENTHELLO_TLSEXT);
2006 SSLerr(SSL_F_TLS_POST_PROCESS_CLIENT_HELLO,
2007 SSL_R_PSK_IDENTITY_NOT_FOUND);
2013 return WORK_FINISHED_STOP;
2015 ssl3_send_alert(s, SSL3_AL_FATAL, al);
2016 ossl_statem_set_error(s);
2020 int tls_construct_server_hello(SSL *s, WPACKET *pkt)
2022 int compm, al = SSL_AD_INTERNAL_ERROR;
2026 /* TODO(TLS1.3): Remove the DRAFT conditional before release */
2027 version = SSL_IS_TLS13(s) ? TLS1_3_VERSION_DRAFT : s->version;
2028 if (!WPACKET_put_bytes_u16(pkt, version)
2030 * Random stuff. Filling of the server_random takes place in
2031 * tls_process_client_hello()
2033 || !WPACKET_memcpy(pkt, s->s3->server_random, SSL3_RANDOM_SIZE)) {
2034 SSLerr(SSL_F_TLS_CONSTRUCT_SERVER_HELLO, ERR_R_INTERNAL_ERROR);
2039 * There are several cases for the session ID to send
2040 * back in the server hello:
2041 * - For session reuse from the session cache,
2042 * we send back the old session ID.
2043 * - If stateless session reuse (using a session ticket)
2044 * is successful, we send back the client's "session ID"
2045 * (which doesn't actually identify the session).
2046 * - If it is a new session, we send back the new
2048 * - However, if we want the new session to be single-use,
2049 * we send back a 0-length session ID.
2050 * s->hit is non-zero in either case of session reuse,
2051 * so the following won't overwrite an ID that we're supposed
2054 if (s->session->not_resumable ||
2055 (!(s->ctx->session_cache_mode & SSL_SESS_CACHE_SERVER)
2057 s->session->session_id_length = 0;
2059 sl = s->session->session_id_length;
2060 if (sl > sizeof(s->session->session_id)) {
2061 SSLerr(SSL_F_TLS_CONSTRUCT_SERVER_HELLO, ERR_R_INTERNAL_ERROR);
2065 /* set up the compression method */
2066 #ifdef OPENSSL_NO_COMP
2069 if (s->s3->tmp.new_compression == NULL)
2072 compm = s->s3->tmp.new_compression->id;
2075 if ((!SSL_IS_TLS13(s)
2076 && !WPACKET_sub_memcpy_u8(pkt, s->session->session_id, sl))
2077 || !s->method->put_cipher_by_char(s->s3->tmp.new_cipher, pkt, &len)
2078 || (!SSL_IS_TLS13(s)
2079 && !WPACKET_put_bytes_u8(pkt, compm))
2080 || !tls_construct_extensions(s, pkt,
2082 ? EXT_TLS1_3_SERVER_HELLO
2083 : EXT_TLS1_2_SERVER_HELLO,
2085 SSLerr(SSL_F_TLS_CONSTRUCT_SERVER_HELLO, ERR_R_INTERNAL_ERROR);
2089 if (!(s->verify_mode & SSL_VERIFY_PEER)
2090 && !ssl3_digest_cached_records(s, 0)) {
2091 al = SSL_AD_INTERNAL_ERROR;
2097 ssl3_send_alert(s, SSL3_AL_FATAL, al);
2101 int tls_construct_server_done(SSL *s, WPACKET *pkt)
2103 if (!s->s3->tmp.cert_request) {
2104 if (!ssl3_digest_cached_records(s, 0)) {
2105 ssl3_send_alert(s, SSL3_AL_FATAL, SSL_AD_INTERNAL_ERROR);
2112 int tls_construct_server_key_exchange(SSL *s, WPACKET *pkt)
2114 #ifndef OPENSSL_NO_DH
2115 EVP_PKEY *pkdh = NULL;
2117 #ifndef OPENSSL_NO_EC
2118 unsigned char *encodedPoint = NULL;
2119 size_t encodedlen = 0;
2122 const SIGALG_LOOKUP *lu = s->s3->tmp.sigalg;
2123 int al = SSL_AD_INTERNAL_ERROR, i;
2126 EVP_MD_CTX *md_ctx = EVP_MD_CTX_new();
2127 EVP_PKEY_CTX *pctx = NULL;
2128 size_t paramlen, paramoffset;
2130 if (!WPACKET_get_total_written(pkt, ¶moffset)) {
2131 SSLerr(SSL_F_TLS_CONSTRUCT_SERVER_KEY_EXCHANGE, ERR_R_INTERNAL_ERROR);
2135 if (md_ctx == NULL) {
2136 SSLerr(SSL_F_TLS_CONSTRUCT_SERVER_KEY_EXCHANGE, ERR_R_MALLOC_FAILURE);
2140 type = s->s3->tmp.new_cipher->algorithm_mkey;
2142 r[0] = r[1] = r[2] = r[3] = NULL;
2143 #ifndef OPENSSL_NO_PSK
2144 /* Plain PSK or RSAPSK nothing to do */
2145 if (type & (SSL_kPSK | SSL_kRSAPSK)) {
2147 #endif /* !OPENSSL_NO_PSK */
2148 #ifndef OPENSSL_NO_DH
2149 if (type & (SSL_kDHE | SSL_kDHEPSK)) {
2150 CERT *cert = s->cert;
2152 EVP_PKEY *pkdhp = NULL;
2155 if (s->cert->dh_tmp_auto) {
2156 DH *dhp = ssl_get_auto_dh(s);
2157 pkdh = EVP_PKEY_new();
2158 if (pkdh == NULL || dhp == NULL) {
2160 SSLerr(SSL_F_TLS_CONSTRUCT_SERVER_KEY_EXCHANGE,
2161 ERR_R_INTERNAL_ERROR);
2164 EVP_PKEY_assign_DH(pkdh, dhp);
2167 pkdhp = cert->dh_tmp;
2169 if ((pkdhp == NULL) && (s->cert->dh_tmp_cb != NULL)) {
2170 DH *dhp = s->cert->dh_tmp_cb(s, 0, 1024);
2171 pkdh = ssl_dh_to_pkey(dhp);
2173 SSLerr(SSL_F_TLS_CONSTRUCT_SERVER_KEY_EXCHANGE,
2174 ERR_R_INTERNAL_ERROR);
2179 if (pkdhp == NULL) {
2180 al = SSL_AD_HANDSHAKE_FAILURE;
2181 SSLerr(SSL_F_TLS_CONSTRUCT_SERVER_KEY_EXCHANGE,
2182 SSL_R_MISSING_TMP_DH_KEY);
2185 if (!ssl_security(s, SSL_SECOP_TMP_DH,
2186 EVP_PKEY_security_bits(pkdhp), 0, pkdhp)) {
2187 al = SSL_AD_HANDSHAKE_FAILURE;
2188 SSLerr(SSL_F_TLS_CONSTRUCT_SERVER_KEY_EXCHANGE,
2189 SSL_R_DH_KEY_TOO_SMALL);
2192 if (s->s3->tmp.pkey != NULL) {
2193 SSLerr(SSL_F_TLS_CONSTRUCT_SERVER_KEY_EXCHANGE,
2194 ERR_R_INTERNAL_ERROR);
2198 s->s3->tmp.pkey = ssl_generate_pkey(pkdhp);
2200 if (s->s3->tmp.pkey == NULL) {
2201 SSLerr(SSL_F_TLS_CONSTRUCT_SERVER_KEY_EXCHANGE, ERR_R_EVP_LIB);
2205 dh = EVP_PKEY_get0_DH(s->s3->tmp.pkey);
2207 EVP_PKEY_free(pkdh);
2210 DH_get0_pqg(dh, &r[0], NULL, &r[1]);
2211 DH_get0_key(dh, &r[2], NULL);
2214 #ifndef OPENSSL_NO_EC
2215 if (type & (SSL_kECDHE | SSL_kECDHEPSK)) {
2218 if (s->s3->tmp.pkey != NULL) {
2219 SSLerr(SSL_F_TLS_CONSTRUCT_SERVER_KEY_EXCHANGE,
2220 ERR_R_INTERNAL_ERROR);
2224 /* Get NID of appropriate shared curve */
2225 nid = tls1_shared_group(s, -2);
2226 curve_id = tls1_ec_nid2curve_id(nid);
2227 if (curve_id == 0) {
2228 SSLerr(SSL_F_TLS_CONSTRUCT_SERVER_KEY_EXCHANGE,
2229 SSL_R_UNSUPPORTED_ELLIPTIC_CURVE);
2232 s->s3->tmp.pkey = ssl_generate_pkey_curve(curve_id);
2233 /* Generate a new key for this curve */
2234 if (s->s3->tmp.pkey == NULL) {
2235 SSLerr(SSL_F_TLS_CONSTRUCT_SERVER_KEY_EXCHANGE, ERR_R_EVP_LIB);
2239 /* Encode the public key. */
2240 encodedlen = EVP_PKEY_get1_tls_encodedpoint(s->s3->tmp.pkey,
2242 if (encodedlen == 0) {
2243 SSLerr(SSL_F_TLS_CONSTRUCT_SERVER_KEY_EXCHANGE, ERR_R_EC_LIB);
2248 * We'll generate the serverKeyExchange message explicitly so we
2249 * can set these to NULLs
2256 #endif /* !OPENSSL_NO_EC */
2257 #ifndef OPENSSL_NO_SRP
2258 if (type & SSL_kSRP) {
2259 if ((s->srp_ctx.N == NULL) ||
2260 (s->srp_ctx.g == NULL) ||
2261 (s->srp_ctx.s == NULL) || (s->srp_ctx.B == NULL)) {
2262 SSLerr(SSL_F_TLS_CONSTRUCT_SERVER_KEY_EXCHANGE,
2263 SSL_R_MISSING_SRP_PARAM);
2266 r[0] = s->srp_ctx.N;
2267 r[1] = s->srp_ctx.g;
2268 r[2] = s->srp_ctx.s;
2269 r[3] = s->srp_ctx.B;
2273 al = SSL_AD_HANDSHAKE_FAILURE;
2274 SSLerr(SSL_F_TLS_CONSTRUCT_SERVER_KEY_EXCHANGE,
2275 SSL_R_UNKNOWN_KEY_EXCHANGE_TYPE);
2279 if (((s->s3->tmp.new_cipher->algorithm_auth & (SSL_aNULL | SSL_aSRP)) != 0)
2280 || ((s->s3->tmp.new_cipher->algorithm_mkey & SSL_PSK)) != 0) {
2282 } else if (lu == NULL) {
2283 al = SSL_AD_DECODE_ERROR;
2287 #ifndef OPENSSL_NO_PSK
2288 if (type & SSL_PSK) {
2289 size_t len = (s->cert->psk_identity_hint == NULL)
2290 ? 0 : strlen(s->cert->psk_identity_hint);
2293 * It should not happen that len > PSK_MAX_IDENTITY_LEN - we already
2294 * checked this when we set the identity hint - but just in case
2296 if (len > PSK_MAX_IDENTITY_LEN
2297 || !WPACKET_sub_memcpy_u16(pkt, s->cert->psk_identity_hint,
2299 SSLerr(SSL_F_TLS_CONSTRUCT_SERVER_KEY_EXCHANGE,
2300 ERR_R_INTERNAL_ERROR);
2306 for (i = 0; i < 4 && r[i] != NULL; i++) {
2307 unsigned char *binval;
2310 #ifndef OPENSSL_NO_SRP
2311 if ((i == 2) && (type & SSL_kSRP)) {
2312 res = WPACKET_start_sub_packet_u8(pkt);
2315 res = WPACKET_start_sub_packet_u16(pkt);
2318 SSLerr(SSL_F_TLS_CONSTRUCT_SERVER_KEY_EXCHANGE,
2319 ERR_R_INTERNAL_ERROR);
2323 #ifndef OPENSSL_NO_DH
2325 * for interoperability with some versions of the Microsoft TLS
2326 * stack, we need to zero pad the DHE pub key to the same length
2329 if ((i == 2) && (type & (SSL_kDHE | SSL_kDHEPSK))) {
2330 size_t len = BN_num_bytes(r[0]) - BN_num_bytes(r[2]);
2333 if (!WPACKET_allocate_bytes(pkt, len, &binval)) {
2334 SSLerr(SSL_F_TLS_CONSTRUCT_SERVER_KEY_EXCHANGE,
2335 ERR_R_INTERNAL_ERROR);
2338 memset(binval, 0, len);
2342 if (!WPACKET_allocate_bytes(pkt, BN_num_bytes(r[i]), &binval)
2343 || !WPACKET_close(pkt)) {
2344 SSLerr(SSL_F_TLS_CONSTRUCT_SERVER_KEY_EXCHANGE,
2345 ERR_R_INTERNAL_ERROR);
2349 BN_bn2bin(r[i], binval);
2352 #ifndef OPENSSL_NO_EC
2353 if (type & (SSL_kECDHE | SSL_kECDHEPSK)) {
2355 * We only support named (not generic) curves. In this situation, the
2356 * ServerKeyExchange message has: [1 byte CurveType], [2 byte CurveName]
2357 * [1 byte length of encoded point], followed by the actual encoded
2360 if (!WPACKET_put_bytes_u8(pkt, NAMED_CURVE_TYPE)
2361 || !WPACKET_put_bytes_u8(pkt, 0)
2362 || !WPACKET_put_bytes_u8(pkt, curve_id)
2363 || !WPACKET_sub_memcpy_u8(pkt, encodedPoint, encodedlen)) {
2364 SSLerr(SSL_F_TLS_CONSTRUCT_SERVER_KEY_EXCHANGE,
2365 ERR_R_INTERNAL_ERROR);
2368 OPENSSL_free(encodedPoint);
2369 encodedPoint = NULL;
2375 EVP_PKEY *pkey = s->s3->tmp.cert->privatekey;
2376 const EVP_MD *md = ssl_md(lu->hash_idx);
2377 unsigned char *sigbytes1, *sigbytes2;
2380 if (pkey == NULL || md == NULL) {
2381 /* Should never happen */
2382 al = SSL_AD_INTERNAL_ERROR;
2383 SSLerr(SSL_F_TLS_CONSTRUCT_SERVER_KEY_EXCHANGE,
2384 ERR_R_INTERNAL_ERROR);
2388 * n is the length of the params, they start at &(d[4]) and p
2389 * points to the space at the end.
2392 /* Get length of the parameters we have written above */
2393 if (!WPACKET_get_length(pkt, ¶mlen)) {
2394 SSLerr(SSL_F_TLS_CONSTRUCT_SERVER_KEY_EXCHANGE,
2395 ERR_R_INTERNAL_ERROR);
2398 /* send signature algorithm */
2399 if (SSL_USE_SIGALGS(s) && !WPACKET_put_bytes_u16(pkt, lu->sigalg))
2402 * Create the signature. We don't know the actual length of the sig
2403 * until after we've created it, so we reserve enough bytes for it
2404 * up front, and then properly allocate them in the WPACKET
2407 siglen = EVP_PKEY_size(pkey);
2408 if (!WPACKET_sub_reserve_bytes_u16(pkt, siglen, &sigbytes1)
2409 || EVP_DigestSignInit(md_ctx, &pctx, md, NULL, pkey) <= 0) {
2410 SSLerr(SSL_F_TLS_CONSTRUCT_SERVER_KEY_EXCHANGE,
2411 ERR_R_INTERNAL_ERROR);
2414 if (lu->sig == EVP_PKEY_RSA_PSS) {
2415 if (EVP_PKEY_CTX_set_rsa_padding(pctx, RSA_PKCS1_PSS_PADDING) <= 0
2416 || EVP_PKEY_CTX_set_rsa_pss_saltlen(pctx, RSA_PSS_SALTLEN_DIGEST) <= 0) {
2417 SSLerr(SSL_F_TLS_CONSTRUCT_SERVER_KEY_EXCHANGE,
2422 if (EVP_DigestSignUpdate(md_ctx, &(s->s3->client_random[0]),
2423 SSL3_RANDOM_SIZE) <= 0
2424 || EVP_DigestSignUpdate(md_ctx, &(s->s3->server_random[0]),
2425 SSL3_RANDOM_SIZE) <= 0
2426 || EVP_DigestSignUpdate(md_ctx,
2427 s->init_buf->data + paramoffset,
2429 || EVP_DigestSignFinal(md_ctx, sigbytes1, &siglen) <= 0
2430 || !WPACKET_sub_allocate_bytes_u16(pkt, siglen, &sigbytes2)
2431 || sigbytes1 != sigbytes2) {
2432 SSLerr(SSL_F_TLS_CONSTRUCT_SERVER_KEY_EXCHANGE,
2433 ERR_R_INTERNAL_ERROR);
2438 EVP_MD_CTX_free(md_ctx);
2441 ssl3_send_alert(s, SSL3_AL_FATAL, al);
2443 #ifndef OPENSSL_NO_DH
2444 EVP_PKEY_free(pkdh);
2446 #ifndef OPENSSL_NO_EC
2447 OPENSSL_free(encodedPoint);
2449 EVP_MD_CTX_free(md_ctx);
2453 int tls_construct_certificate_request(SSL *s, WPACKET *pkt)
2456 STACK_OF(X509_NAME) *sk = NULL;
2458 if (SSL_IS_TLS13(s)) {
2459 /* TODO(TLS1.3) for now send empty request context */
2460 if (!WPACKET_put_bytes_u8(pkt, 0)) {
2461 SSLerr(SSL_F_TLS_CONSTRUCT_CERTIFICATE_REQUEST,
2462 ERR_R_INTERNAL_ERROR);
2466 /* get the list of acceptable cert types */
2467 if (!WPACKET_start_sub_packet_u8(pkt)
2468 || !ssl3_get_req_cert_type(s, pkt) || !WPACKET_close(pkt)) {
2469 SSLerr(SSL_F_TLS_CONSTRUCT_CERTIFICATE_REQUEST,
2470 ERR_R_INTERNAL_ERROR);
2475 if (SSL_USE_SIGALGS(s)) {
2476 const uint16_t *psigs;
2477 size_t nl = tls12_get_psigalgs(s, 1, &psigs);
2479 if (!WPACKET_start_sub_packet_u16(pkt)
2480 || !tls12_copy_sigalgs(s, pkt, psigs, nl)
2481 || !WPACKET_close(pkt)) {
2482 SSLerr(SSL_F_TLS_CONSTRUCT_CERTIFICATE_REQUEST,
2483 ERR_R_INTERNAL_ERROR);
2488 /* Start sub-packet for client CA list */
2489 if (!WPACKET_start_sub_packet_u16(pkt)) {
2490 SSLerr(SSL_F_TLS_CONSTRUCT_CERTIFICATE_REQUEST, ERR_R_INTERNAL_ERROR);
2494 sk = SSL_get_client_CA_list(s);
2496 for (i = 0; i < sk_X509_NAME_num(sk); i++) {
2497 unsigned char *namebytes;
2498 X509_NAME *name = sk_X509_NAME_value(sk, i);
2502 || (namelen = i2d_X509_NAME(name, NULL)) < 0
2503 || !WPACKET_sub_allocate_bytes_u16(pkt, namelen,
2505 || i2d_X509_NAME(name, &namebytes) != namelen) {
2506 SSLerr(SSL_F_TLS_CONSTRUCT_CERTIFICATE_REQUEST,
2507 ERR_R_INTERNAL_ERROR);
2512 /* else no CA names */
2513 if (!WPACKET_close(pkt)) {
2514 SSLerr(SSL_F_TLS_CONSTRUCT_CERTIFICATE_REQUEST, ERR_R_INTERNAL_ERROR);
2518 * TODO(TLS1.3) implement configurable certificate_extensions
2519 * For now just send zero length extensions.
2521 if (SSL_IS_TLS13(s) && !WPACKET_put_bytes_u16(pkt, 0)) {
2522 SSLerr(SSL_F_TLS_CONSTRUCT_CERTIFICATE_REQUEST, ERR_R_INTERNAL_ERROR);
2526 s->s3->tmp.cert_request = 1;
2530 ssl3_send_alert(s, SSL3_AL_FATAL, SSL_AD_INTERNAL_ERROR);
2534 static int tls_process_cke_psk_preamble(SSL *s, PACKET *pkt, int *al)
2536 #ifndef OPENSSL_NO_PSK
2537 unsigned char psk[PSK_MAX_PSK_LEN];
2539 PACKET psk_identity;
2541 if (!PACKET_get_length_prefixed_2(pkt, &psk_identity)) {
2542 *al = SSL_AD_DECODE_ERROR;
2543 SSLerr(SSL_F_TLS_PROCESS_CKE_PSK_PREAMBLE, SSL_R_LENGTH_MISMATCH);
2546 if (PACKET_remaining(&psk_identity) > PSK_MAX_IDENTITY_LEN) {
2547 *al = SSL_AD_DECODE_ERROR;
2548 SSLerr(SSL_F_TLS_PROCESS_CKE_PSK_PREAMBLE, SSL_R_DATA_LENGTH_TOO_LONG);
2551 if (s->psk_server_callback == NULL) {
2552 *al = SSL_AD_INTERNAL_ERROR;
2553 SSLerr(SSL_F_TLS_PROCESS_CKE_PSK_PREAMBLE, SSL_R_PSK_NO_SERVER_CB);
2557 if (!PACKET_strndup(&psk_identity, &s->session->psk_identity)) {
2558 *al = SSL_AD_INTERNAL_ERROR;
2559 SSLerr(SSL_F_TLS_PROCESS_CKE_PSK_PREAMBLE, ERR_R_INTERNAL_ERROR);
2563 psklen = s->psk_server_callback(s, s->session->psk_identity,
2566 if (psklen > PSK_MAX_PSK_LEN) {
2567 *al = SSL_AD_INTERNAL_ERROR;
2568 SSLerr(SSL_F_TLS_PROCESS_CKE_PSK_PREAMBLE, ERR_R_INTERNAL_ERROR);
2570 } else if (psklen == 0) {
2572 * PSK related to the given identity not found
2574 *al = SSL_AD_UNKNOWN_PSK_IDENTITY;
2575 SSLerr(SSL_F_TLS_PROCESS_CKE_PSK_PREAMBLE,
2576 SSL_R_PSK_IDENTITY_NOT_FOUND);
2580 OPENSSL_free(s->s3->tmp.psk);
2581 s->s3->tmp.psk = OPENSSL_memdup(psk, psklen);
2582 OPENSSL_cleanse(psk, psklen);
2584 if (s->s3->tmp.psk == NULL) {
2585 *al = SSL_AD_INTERNAL_ERROR;
2586 SSLerr(SSL_F_TLS_PROCESS_CKE_PSK_PREAMBLE, ERR_R_MALLOC_FAILURE);
2590 s->s3->tmp.psklen = psklen;
2594 /* Should never happen */
2595 *al = SSL_AD_INTERNAL_ERROR;
2596 SSLerr(SSL_F_TLS_PROCESS_CKE_PSK_PREAMBLE, ERR_R_INTERNAL_ERROR);
2601 static int tls_process_cke_rsa(SSL *s, PACKET *pkt, int *al)
2603 #ifndef OPENSSL_NO_RSA
2604 unsigned char rand_premaster_secret[SSL_MAX_MASTER_KEY_LENGTH];
2606 unsigned char decrypt_good, version_good;
2607 size_t j, padding_len;
2608 PACKET enc_premaster;
2610 unsigned char *rsa_decrypt = NULL;
2613 rsa = EVP_PKEY_get0_RSA(s->cert->pkeys[SSL_PKEY_RSA].privatekey);
2615 *al = SSL_AD_HANDSHAKE_FAILURE;
2616 SSLerr(SSL_F_TLS_PROCESS_CKE_RSA, SSL_R_MISSING_RSA_CERTIFICATE);
2620 /* SSLv3 and pre-standard DTLS omit the length bytes. */
2621 if (s->version == SSL3_VERSION || s->version == DTLS1_BAD_VER) {
2622 enc_premaster = *pkt;
2624 if (!PACKET_get_length_prefixed_2(pkt, &enc_premaster)
2625 || PACKET_remaining(pkt) != 0) {
2626 *al = SSL_AD_DECODE_ERROR;
2627 SSLerr(SSL_F_TLS_PROCESS_CKE_RSA, SSL_R_LENGTH_MISMATCH);
2633 * We want to be sure that the plaintext buffer size makes it safe to
2634 * iterate over the entire size of a premaster secret
2635 * (SSL_MAX_MASTER_KEY_LENGTH). Reject overly short RSA keys because
2636 * their ciphertext cannot accommodate a premaster secret anyway.
2638 if (RSA_size(rsa) < SSL_MAX_MASTER_KEY_LENGTH) {
2639 *al = SSL_AD_INTERNAL_ERROR;
2640 SSLerr(SSL_F_TLS_PROCESS_CKE_RSA, RSA_R_KEY_SIZE_TOO_SMALL);
2644 rsa_decrypt = OPENSSL_malloc(RSA_size(rsa));
2645 if (rsa_decrypt == NULL) {
2646 *al = SSL_AD_INTERNAL_ERROR;
2647 SSLerr(SSL_F_TLS_PROCESS_CKE_RSA, ERR_R_MALLOC_FAILURE);
2652 * We must not leak whether a decryption failure occurs because of
2653 * Bleichenbacher's attack on PKCS #1 v1.5 RSA padding (see RFC 2246,
2654 * section 7.4.7.1). The code follows that advice of the TLS RFC and
2655 * generates a random premaster secret for the case that the decrypt
2656 * fails. See https://tools.ietf.org/html/rfc5246#section-7.4.7.1
2659 if (RAND_bytes(rand_premaster_secret, sizeof(rand_premaster_secret)) <= 0)
2663 * Decrypt with no padding. PKCS#1 padding will be removed as part of
2664 * the timing-sensitive code below.
2666 /* TODO(size_t): Convert this function */
2667 decrypt_len = (int)RSA_private_decrypt((int)PACKET_remaining(&enc_premaster),
2668 PACKET_data(&enc_premaster),
2669 rsa_decrypt, rsa, RSA_NO_PADDING);
2670 if (decrypt_len < 0)
2673 /* Check the padding. See RFC 3447, section 7.2.2. */
2676 * The smallest padded premaster is 11 bytes of overhead. Small keys
2677 * are publicly invalid, so this may return immediately. This ensures
2678 * PS is at least 8 bytes.
2680 if (decrypt_len < 11 + SSL_MAX_MASTER_KEY_LENGTH) {
2681 *al = SSL_AD_DECRYPT_ERROR;
2682 SSLerr(SSL_F_TLS_PROCESS_CKE_RSA, SSL_R_DECRYPTION_FAILED);
2686 padding_len = decrypt_len - SSL_MAX_MASTER_KEY_LENGTH;
2687 decrypt_good = constant_time_eq_int_8(rsa_decrypt[0], 0) &
2688 constant_time_eq_int_8(rsa_decrypt[1], 2);
2689 for (j = 2; j < padding_len - 1; j++) {
2690 decrypt_good &= ~constant_time_is_zero_8(rsa_decrypt[j]);
2692 decrypt_good &= constant_time_is_zero_8(rsa_decrypt[padding_len - 1]);
2695 * If the version in the decrypted pre-master secret is correct then
2696 * version_good will be 0xff, otherwise it'll be zero. The
2697 * Klima-Pokorny-Rosa extension of Bleichenbacher's attack
2698 * (http://eprint.iacr.org/2003/052/) exploits the version number
2699 * check as a "bad version oracle". Thus version checks are done in
2700 * constant time and are treated like any other decryption error.
2703 constant_time_eq_8(rsa_decrypt[padding_len],
2704 (unsigned)(s->client_version >> 8));
2706 constant_time_eq_8(rsa_decrypt[padding_len + 1],
2707 (unsigned)(s->client_version & 0xff));
2710 * The premaster secret must contain the same version number as the
2711 * ClientHello to detect version rollback attacks (strangely, the
2712 * protocol does not offer such protection for DH ciphersuites).
2713 * However, buggy clients exist that send the negotiated protocol
2714 * version instead if the server does not support the requested
2715 * protocol version. If SSL_OP_TLS_ROLLBACK_BUG is set, tolerate such
2718 if (s->options & SSL_OP_TLS_ROLLBACK_BUG) {
2719 unsigned char workaround_good;
2720 workaround_good = constant_time_eq_8(rsa_decrypt[padding_len],
2721 (unsigned)(s->version >> 8));
2723 constant_time_eq_8(rsa_decrypt[padding_len + 1],
2724 (unsigned)(s->version & 0xff));
2725 version_good |= workaround_good;
2729 * Both decryption and version must be good for decrypt_good to
2730 * remain non-zero (0xff).
2732 decrypt_good &= version_good;
2735 * Now copy rand_premaster_secret over from p using
2736 * decrypt_good_mask. If decryption failed, then p does not
2737 * contain valid plaintext, however, a check above guarantees
2738 * it is still sufficiently large to read from.
2740 for (j = 0; j < sizeof(rand_premaster_secret); j++) {
2741 rsa_decrypt[padding_len + j] =
2742 constant_time_select_8(decrypt_good,
2743 rsa_decrypt[padding_len + j],
2744 rand_premaster_secret[j]);
2747 if (!ssl_generate_master_secret(s, rsa_decrypt + padding_len,
2748 sizeof(rand_premaster_secret), 0)) {
2749 *al = SSL_AD_INTERNAL_ERROR;
2750 SSLerr(SSL_F_TLS_PROCESS_CKE_RSA, ERR_R_INTERNAL_ERROR);
2756 OPENSSL_free(rsa_decrypt);
2759 /* Should never happen */
2760 *al = SSL_AD_INTERNAL_ERROR;
2761 SSLerr(SSL_F_TLS_PROCESS_CKE_RSA, ERR_R_INTERNAL_ERROR);
2766 static int tls_process_cke_dhe(SSL *s, PACKET *pkt, int *al)
2768 #ifndef OPENSSL_NO_DH
2769 EVP_PKEY *skey = NULL;
2773 const unsigned char *data;
2774 EVP_PKEY *ckey = NULL;
2777 if (!PACKET_get_net_2(pkt, &i) || PACKET_remaining(pkt) != i) {
2778 *al = SSL_AD_HANDSHAKE_FAILURE;
2779 SSLerr(SSL_F_TLS_PROCESS_CKE_DHE,
2780 SSL_R_DH_PUBLIC_VALUE_LENGTH_IS_WRONG);
2783 skey = s->s3->tmp.pkey;
2785 *al = SSL_AD_HANDSHAKE_FAILURE;
2786 SSLerr(SSL_F_TLS_PROCESS_CKE_DHE, SSL_R_MISSING_TMP_DH_KEY);
2790 if (PACKET_remaining(pkt) == 0L) {
2791 *al = SSL_AD_HANDSHAKE_FAILURE;
2792 SSLerr(SSL_F_TLS_PROCESS_CKE_DHE, SSL_R_MISSING_TMP_DH_KEY);
2795 if (!PACKET_get_bytes(pkt, &data, i)) {
2796 /* We already checked we have enough data */
2797 *al = SSL_AD_INTERNAL_ERROR;
2798 SSLerr(SSL_F_TLS_PROCESS_CKE_DHE, ERR_R_INTERNAL_ERROR);
2801 ckey = EVP_PKEY_new();
2802 if (ckey == NULL || EVP_PKEY_copy_parameters(ckey, skey) == 0) {
2803 SSLerr(SSL_F_TLS_PROCESS_CKE_DHE, SSL_R_BN_LIB);
2806 cdh = EVP_PKEY_get0_DH(ckey);
2807 pub_key = BN_bin2bn(data, i, NULL);
2809 if (pub_key == NULL || !DH_set0_key(cdh, pub_key, NULL)) {
2810 SSLerr(SSL_F_TLS_PROCESS_CKE_DHE, ERR_R_INTERNAL_ERROR);
2811 if (pub_key != NULL)
2816 if (ssl_derive(s, skey, ckey, 1) == 0) {
2817 *al = SSL_AD_INTERNAL_ERROR;
2818 SSLerr(SSL_F_TLS_PROCESS_CKE_DHE, ERR_R_INTERNAL_ERROR);
2823 EVP_PKEY_free(s->s3->tmp.pkey);
2824 s->s3->tmp.pkey = NULL;
2826 EVP_PKEY_free(ckey);
2829 /* Should never happen */
2830 *al = SSL_AD_INTERNAL_ERROR;
2831 SSLerr(SSL_F_TLS_PROCESS_CKE_DHE, ERR_R_INTERNAL_ERROR);
2836 static int tls_process_cke_ecdhe(SSL *s, PACKET *pkt, int *al)
2838 #ifndef OPENSSL_NO_EC
2839 EVP_PKEY *skey = s->s3->tmp.pkey;
2840 EVP_PKEY *ckey = NULL;
2843 if (PACKET_remaining(pkt) == 0L) {
2844 /* We don't support ECDH client auth */
2845 *al = SSL_AD_HANDSHAKE_FAILURE;
2846 SSLerr(SSL_F_TLS_PROCESS_CKE_ECDHE, SSL_R_MISSING_TMP_ECDH_KEY);
2850 const unsigned char *data;
2853 * Get client's public key from encoded point in the
2854 * ClientKeyExchange message.
2857 /* Get encoded point length */
2858 if (!PACKET_get_1(pkt, &i) || !PACKET_get_bytes(pkt, &data, i)
2859 || PACKET_remaining(pkt) != 0) {
2860 *al = SSL_AD_DECODE_ERROR;
2861 SSLerr(SSL_F_TLS_PROCESS_CKE_ECDHE, SSL_R_LENGTH_MISMATCH);
2864 ckey = EVP_PKEY_new();
2865 if (ckey == NULL || EVP_PKEY_copy_parameters(ckey, skey) <= 0) {
2866 SSLerr(SSL_F_TLS_PROCESS_CKE_ECDHE, ERR_R_EVP_LIB);
2869 if (EVP_PKEY_set1_tls_encodedpoint(ckey, data, i) == 0) {
2870 *al = SSL_AD_HANDSHAKE_FAILURE;
2871 SSLerr(SSL_F_TLS_PROCESS_CKE_ECDHE, ERR_R_EC_LIB);
2876 if (ssl_derive(s, skey, ckey, 1) == 0) {
2877 *al = SSL_AD_INTERNAL_ERROR;
2878 SSLerr(SSL_F_TLS_PROCESS_CKE_ECDHE, ERR_R_INTERNAL_ERROR);
2883 EVP_PKEY_free(s->s3->tmp.pkey);
2884 s->s3->tmp.pkey = NULL;
2886 EVP_PKEY_free(ckey);
2890 /* Should never happen */
2891 *al = SSL_AD_INTERNAL_ERROR;
2892 SSLerr(SSL_F_TLS_PROCESS_CKE_ECDHE, ERR_R_INTERNAL_ERROR);
2897 static int tls_process_cke_srp(SSL *s, PACKET *pkt, int *al)
2899 #ifndef OPENSSL_NO_SRP
2901 const unsigned char *data;
2903 if (!PACKET_get_net_2(pkt, &i)
2904 || !PACKET_get_bytes(pkt, &data, i)) {
2905 *al = SSL_AD_DECODE_ERROR;
2906 SSLerr(SSL_F_TLS_PROCESS_CKE_SRP, SSL_R_BAD_SRP_A_LENGTH);
2909 if ((s->srp_ctx.A = BN_bin2bn(data, i, NULL)) == NULL) {
2910 SSLerr(SSL_F_TLS_PROCESS_CKE_SRP, ERR_R_BN_LIB);
2913 if (BN_ucmp(s->srp_ctx.A, s->srp_ctx.N) >= 0 || BN_is_zero(s->srp_ctx.A)) {
2914 *al = SSL_AD_ILLEGAL_PARAMETER;
2915 SSLerr(SSL_F_TLS_PROCESS_CKE_SRP, SSL_R_BAD_SRP_PARAMETERS);
2918 OPENSSL_free(s->session->srp_username);
2919 s->session->srp_username = OPENSSL_strdup(s->srp_ctx.login);
2920 if (s->session->srp_username == NULL) {
2921 SSLerr(SSL_F_TLS_PROCESS_CKE_SRP, ERR_R_MALLOC_FAILURE);
2925 if (!srp_generate_server_master_secret(s)) {
2926 SSLerr(SSL_F_TLS_PROCESS_CKE_SRP, ERR_R_INTERNAL_ERROR);
2932 /* Should never happen */
2933 *al = SSL_AD_INTERNAL_ERROR;
2934 SSLerr(SSL_F_TLS_PROCESS_CKE_SRP, ERR_R_INTERNAL_ERROR);
2939 static int tls_process_cke_gost(SSL *s, PACKET *pkt, int *al)
2941 #ifndef OPENSSL_NO_GOST
2942 EVP_PKEY_CTX *pkey_ctx;
2943 EVP_PKEY *client_pub_pkey = NULL, *pk = NULL;
2944 unsigned char premaster_secret[32];
2945 const unsigned char *start;
2946 size_t outlen = 32, inlen;
2947 unsigned long alg_a;
2950 size_t sess_key_len;
2951 const unsigned char *data;
2954 /* Get our certificate private key */
2955 alg_a = s->s3->tmp.new_cipher->algorithm_auth;
2956 if (alg_a & SSL_aGOST12) {
2958 * New GOST ciphersuites have SSL_aGOST01 bit too
2960 pk = s->cert->pkeys[SSL_PKEY_GOST12_512].privatekey;
2962 pk = s->cert->pkeys[SSL_PKEY_GOST12_256].privatekey;
2965 pk = s->cert->pkeys[SSL_PKEY_GOST01].privatekey;
2967 } else if (alg_a & SSL_aGOST01) {
2968 pk = s->cert->pkeys[SSL_PKEY_GOST01].privatekey;
2971 pkey_ctx = EVP_PKEY_CTX_new(pk, NULL);
2972 if (pkey_ctx == NULL) {
2973 *al = SSL_AD_INTERNAL_ERROR;
2974 SSLerr(SSL_F_TLS_PROCESS_CKE_GOST, ERR_R_MALLOC_FAILURE);
2977 if (EVP_PKEY_decrypt_init(pkey_ctx) <= 0) {
2978 *al = SSL_AD_INTERNAL_ERROR;
2979 SSLerr(SSL_F_TLS_PROCESS_CKE_GOST, ERR_R_INTERNAL_ERROR);
2983 * If client certificate is present and is of the same type, maybe
2984 * use it for key exchange. Don't mind errors from
2985 * EVP_PKEY_derive_set_peer, because it is completely valid to use a
2986 * client certificate for authorization only.
2988 client_pub_pkey = X509_get0_pubkey(s->session->peer);
2989 if (client_pub_pkey) {
2990 if (EVP_PKEY_derive_set_peer(pkey_ctx, client_pub_pkey) <= 0)
2993 /* Decrypt session key */
2994 sess_key_len = PACKET_remaining(pkt);
2995 if (!PACKET_get_bytes(pkt, &data, sess_key_len)) {
2996 *al = SSL_AD_INTERNAL_ERROR;
2997 SSLerr(SSL_F_TLS_PROCESS_CKE_GOST, ERR_R_INTERNAL_ERROR);
3000 /* TODO(size_t): Convert this function */
3001 if (ASN1_get_object((const unsigned char **)&data, &Tlen, &Ttag,
3002 &Tclass, (long)sess_key_len) != V_ASN1_CONSTRUCTED
3003 || Ttag != V_ASN1_SEQUENCE || Tclass != V_ASN1_UNIVERSAL) {
3004 *al = SSL_AD_DECODE_ERROR;
3005 SSLerr(SSL_F_TLS_PROCESS_CKE_GOST, SSL_R_DECRYPTION_FAILED);
3010 if (EVP_PKEY_decrypt
3011 (pkey_ctx, premaster_secret, &outlen, start, inlen) <= 0) {
3012 *al = SSL_AD_DECODE_ERROR;
3013 SSLerr(SSL_F_TLS_PROCESS_CKE_GOST, SSL_R_DECRYPTION_FAILED);
3016 /* Generate master secret */
3017 if (!ssl_generate_master_secret(s, premaster_secret,
3018 sizeof(premaster_secret), 0)) {
3019 *al = SSL_AD_INTERNAL_ERROR;
3020 SSLerr(SSL_F_TLS_PROCESS_CKE_GOST, ERR_R_INTERNAL_ERROR);
3023 /* Check if pubkey from client certificate was used */
3024 if (EVP_PKEY_CTX_ctrl
3025 (pkey_ctx, -1, -1, EVP_PKEY_CTRL_PEER_KEY, 2, NULL) > 0)
3026 s->statem.no_cert_verify = 1;
3030 EVP_PKEY_CTX_free(pkey_ctx);
3033 /* Should never happen */
3034 *al = SSL_AD_INTERNAL_ERROR;
3035 SSLerr(SSL_F_TLS_PROCESS_CKE_GOST, ERR_R_INTERNAL_ERROR);
3040 MSG_PROCESS_RETURN tls_process_client_key_exchange(SSL *s, PACKET *pkt)
3043 unsigned long alg_k;
3045 alg_k = s->s3->tmp.new_cipher->algorithm_mkey;
3047 /* For PSK parse and retrieve identity, obtain PSK key */
3048 if ((alg_k & SSL_PSK) && !tls_process_cke_psk_preamble(s, pkt, &al))
3051 if (alg_k & SSL_kPSK) {
3052 /* Identity extracted earlier: should be nothing left */
3053 if (PACKET_remaining(pkt) != 0) {
3054 al = SSL_AD_HANDSHAKE_FAILURE;
3055 SSLerr(SSL_F_TLS_PROCESS_CLIENT_KEY_EXCHANGE,
3056 SSL_R_LENGTH_MISMATCH);
3059 /* PSK handled by ssl_generate_master_secret */
3060 if (!ssl_generate_master_secret(s, NULL, 0, 0)) {
3061 al = SSL_AD_INTERNAL_ERROR;
3062 SSLerr(SSL_F_TLS_PROCESS_CLIENT_KEY_EXCHANGE, ERR_R_INTERNAL_ERROR);
3065 } else if (alg_k & (SSL_kRSA | SSL_kRSAPSK)) {
3066 if (!tls_process_cke_rsa(s, pkt, &al))
3068 } else if (alg_k & (SSL_kDHE | SSL_kDHEPSK)) {
3069 if (!tls_process_cke_dhe(s, pkt, &al))
3071 } else if (alg_k & (SSL_kECDHE | SSL_kECDHEPSK)) {
3072 if (!tls_process_cke_ecdhe(s, pkt, &al))
3074 } else if (alg_k & SSL_kSRP) {
3075 if (!tls_process_cke_srp(s, pkt, &al))
3077 } else if (alg_k & SSL_kGOST) {
3078 if (!tls_process_cke_gost(s, pkt, &al))
3081 al = SSL_AD_HANDSHAKE_FAILURE;
3082 SSLerr(SSL_F_TLS_PROCESS_CLIENT_KEY_EXCHANGE,
3083 SSL_R_UNKNOWN_CIPHER_TYPE);
3087 return MSG_PROCESS_CONTINUE_PROCESSING;
3090 ssl3_send_alert(s, SSL3_AL_FATAL, al);
3091 #ifndef OPENSSL_NO_PSK
3092 OPENSSL_clear_free(s->s3->tmp.psk, s->s3->tmp.psklen);
3093 s->s3->tmp.psk = NULL;
3095 ossl_statem_set_error(s);
3096 return MSG_PROCESS_ERROR;
3099 WORK_STATE tls_post_process_client_key_exchange(SSL *s, WORK_STATE wst)
3101 #ifndef OPENSSL_NO_SCTP
3102 if (wst == WORK_MORE_A) {
3103 if (SSL_IS_DTLS(s)) {
3104 unsigned char sctpauthkey[64];
3105 char labelbuffer[sizeof(DTLS1_SCTP_AUTH_LABEL)];
3107 * Add new shared key for SCTP-Auth, will be ignored if no SCTP
3110 memcpy(labelbuffer, DTLS1_SCTP_AUTH_LABEL,
3111 sizeof(DTLS1_SCTP_AUTH_LABEL));
3113 if (SSL_export_keying_material(s, sctpauthkey,
3114 sizeof(sctpauthkey), labelbuffer,
3115 sizeof(labelbuffer), NULL, 0,
3117 ossl_statem_set_error(s);
3121 BIO_ctrl(SSL_get_wbio(s), BIO_CTRL_DGRAM_SCTP_ADD_AUTH_KEY,
3122 sizeof(sctpauthkey), sctpauthkey);
3127 if ((wst == WORK_MORE_B)
3129 && BIO_dgram_is_sctp(SSL_get_wbio(s))
3130 /* Are we renegotiating? */
3132 /* Are we going to skip the CertificateVerify? */
3133 && (s->session->peer == NULL || s->statem.no_cert_verify)
3134 && BIO_dgram_sctp_msg_waiting(SSL_get_rbio(s))) {
3135 s->s3->in_read_app_data = 2;
3136 s->rwstate = SSL_READING;
3137 BIO_clear_retry_flags(SSL_get_rbio(s));
3138 BIO_set_retry_read(SSL_get_rbio(s));
3139 ossl_statem_set_sctp_read_sock(s, 1);
3142 ossl_statem_set_sctp_read_sock(s, 0);
3146 if (s->statem.no_cert_verify || !s->session->peer) {
3148 * No certificate verify or no peer certificate so we no longer need
3149 * the handshake_buffer
3151 if (!ssl3_digest_cached_records(s, 0)) {
3152 ossl_statem_set_error(s);
3155 return WORK_FINISHED_CONTINUE;
3157 if (!s->s3->handshake_buffer) {
3158 SSLerr(SSL_F_TLS_POST_PROCESS_CLIENT_KEY_EXCHANGE,
3159 ERR_R_INTERNAL_ERROR);
3160 ossl_statem_set_error(s);
3164 * For sigalgs freeze the handshake buffer. If we support
3165 * extms we've done this already so this is a no-op
3167 if (!ssl3_digest_cached_records(s, 1)) {
3168 ossl_statem_set_error(s);
3173 return WORK_FINISHED_CONTINUE;
3176 MSG_PROCESS_RETURN tls_process_client_certificate(SSL *s, PACKET *pkt)
3178 int i, al = SSL_AD_INTERNAL_ERROR, ret = MSG_PROCESS_ERROR;
3180 unsigned long l, llen;
3181 const unsigned char *certstart, *certbytes;
3182 STACK_OF(X509) *sk = NULL;
3183 PACKET spkt, context;
3186 if ((sk = sk_X509_new_null()) == NULL) {
3187 SSLerr(SSL_F_TLS_PROCESS_CLIENT_CERTIFICATE, ERR_R_MALLOC_FAILURE);
3191 /* TODO(TLS1.3): For now we ignore the context. We need to verify this */
3192 if ((SSL_IS_TLS13(s) && !PACKET_get_length_prefixed_1(pkt, &context))
3193 || !PACKET_get_net_3(pkt, &llen)
3194 || !PACKET_get_sub_packet(pkt, &spkt, llen)
3195 || PACKET_remaining(pkt) != 0) {
3196 al = SSL_AD_DECODE_ERROR;
3197 SSLerr(SSL_F_TLS_PROCESS_CLIENT_CERTIFICATE, SSL_R_LENGTH_MISMATCH);
3201 for (chainidx = 0; PACKET_remaining(&spkt) > 0; chainidx++) {
3202 if (!PACKET_get_net_3(&spkt, &l)
3203 || !PACKET_get_bytes(&spkt, &certbytes, l)) {
3204 al = SSL_AD_DECODE_ERROR;
3205 SSLerr(SSL_F_TLS_PROCESS_CLIENT_CERTIFICATE,
3206 SSL_R_CERT_LENGTH_MISMATCH);
3210 certstart = certbytes;
3211 x = d2i_X509(NULL, (const unsigned char **)&certbytes, l);
3213 SSLerr(SSL_F_TLS_PROCESS_CLIENT_CERTIFICATE, ERR_R_ASN1_LIB);
3216 if (certbytes != (certstart + l)) {
3217 al = SSL_AD_DECODE_ERROR;
3218 SSLerr(SSL_F_TLS_PROCESS_CLIENT_CERTIFICATE,
3219 SSL_R_CERT_LENGTH_MISMATCH);
3223 if (SSL_IS_TLS13(s)) {
3224 RAW_EXTENSION *rawexts = NULL;
3227 if (!PACKET_get_length_prefixed_2(&spkt, &extensions)) {
3228 al = SSL_AD_DECODE_ERROR;
3229 SSLerr(SSL_F_TLS_PROCESS_CLIENT_CERTIFICATE, SSL_R_BAD_LENGTH);
3232 if (!tls_collect_extensions(s, &extensions, EXT_TLS1_3_CERTIFICATE,
3233 &rawexts, &al, NULL)
3234 || !tls_parse_all_extensions(s, EXT_TLS1_3_CERTIFICATE,
3235 rawexts, x, chainidx, &al)) {
3236 OPENSSL_free(rawexts);
3239 OPENSSL_free(rawexts);
3242 if (!sk_X509_push(sk, x)) {
3243 SSLerr(SSL_F_TLS_PROCESS_CLIENT_CERTIFICATE, ERR_R_MALLOC_FAILURE);
3249 if (sk_X509_num(sk) <= 0) {
3250 /* TLS does not mind 0 certs returned */
3251 if (s->version == SSL3_VERSION) {
3252 al = SSL_AD_HANDSHAKE_FAILURE;
3253 SSLerr(SSL_F_TLS_PROCESS_CLIENT_CERTIFICATE,
3254 SSL_R_NO_CERTIFICATES_RETURNED);
3257 /* Fail for TLS only if we required a certificate */
3258 else if ((s->verify_mode & SSL_VERIFY_PEER) &&
3259 (s->verify_mode & SSL_VERIFY_FAIL_IF_NO_PEER_CERT)) {
3260 SSLerr(SSL_F_TLS_PROCESS_CLIENT_CERTIFICATE,
3261 SSL_R_PEER_DID_NOT_RETURN_A_CERTIFICATE);
3262 al = SSL_AD_HANDSHAKE_FAILURE;
3265 /* No client certificate so digest cached records */
3266 if (s->s3->handshake_buffer && !ssl3_digest_cached_records(s, 0)) {
3271 i = ssl_verify_cert_chain(s, sk);
3273 al = ssl_verify_alarm_type(s->verify_result);
3274 SSLerr(SSL_F_TLS_PROCESS_CLIENT_CERTIFICATE,
3275 SSL_R_CERTIFICATE_VERIFY_FAILED);
3279 SSLerr(SSL_F_TLS_PROCESS_CLIENT_CERTIFICATE, i);
3280 al = SSL_AD_HANDSHAKE_FAILURE;
3283 pkey = X509_get0_pubkey(sk_X509_value(sk, 0));
3285 al = SSL3_AD_HANDSHAKE_FAILURE;
3286 SSLerr(SSL_F_TLS_PROCESS_CLIENT_CERTIFICATE,
3287 SSL_R_UNKNOWN_CERTIFICATE_TYPE);
3292 X509_free(s->session->peer);
3293 s->session->peer = sk_X509_shift(sk);
3294 s->session->verify_result = s->verify_result;
3296 sk_X509_pop_free(s->session->peer_chain, X509_free);
3297 s->session->peer_chain = sk;
3300 * Freeze the handshake buffer. For <TLS1.3 we do this after the CKE
3303 if (SSL_IS_TLS13(s) && !ssl3_digest_cached_records(s, 1)) {
3304 al = SSL_AD_INTERNAL_ERROR;
3305 SSLerr(SSL_F_TLS_PROCESS_CLIENT_CERTIFICATE, ERR_R_INTERNAL_ERROR);
3310 * Inconsistency alert: cert_chain does *not* include the peer's own
3311 * certificate, while we do include it in statem_clnt.c
3315 /* Save the current hash state for when we receive the CertificateVerify */
3317 && !ssl_handshake_hash(s, s->cert_verify_hash,
3318 sizeof(s->cert_verify_hash),
3319 &s->cert_verify_hash_len)) {
3320 al = SSL_AD_INTERNAL_ERROR;
3321 SSLerr(SSL_F_TLS_PROCESS_CLIENT_CERTIFICATE, ERR_R_INTERNAL_ERROR);
3325 ret = MSG_PROCESS_CONTINUE_READING;
3329 ssl3_send_alert(s, SSL3_AL_FATAL, al);
3330 ossl_statem_set_error(s);
3333 sk_X509_pop_free(sk, X509_free);
3337 int tls_construct_server_certificate(SSL *s, WPACKET *pkt)
3339 CERT_PKEY *cpk = s->s3->tmp.cert;
3340 int al = SSL_AD_INTERNAL_ERROR;
3343 SSLerr(SSL_F_TLS_CONSTRUCT_SERVER_CERTIFICATE, ERR_R_INTERNAL_ERROR);
3348 * In TLSv1.3 the certificate chain is always preceded by a 0 length context
3349 * for the server Certificate message
3351 if ((SSL_IS_TLS13(s) && !WPACKET_put_bytes_u8(pkt, 0))
3352 || !ssl3_output_cert_chain(s, pkt, cpk, &al)) {
3353 SSLerr(SSL_F_TLS_CONSTRUCT_SERVER_CERTIFICATE, ERR_R_INTERNAL_ERROR);
3354 ssl3_send_alert(s, SSL3_AL_FATAL, al);
3361 int tls_construct_new_session_ticket(SSL *s, WPACKET *pkt)
3363 unsigned char *senc = NULL;
3364 EVP_CIPHER_CTX *ctx = NULL;
3365 HMAC_CTX *hctx = NULL;
3366 unsigned char *p, *encdata1, *encdata2, *macdata1, *macdata2;
3367 const unsigned char *const_p;
3368 int len, slen_full, slen, lenfinal;
3371 SSL_CTX *tctx = s->session_ctx;
3372 unsigned char iv[EVP_MAX_IV_LENGTH];
3373 unsigned char key_name[TLSEXT_KEYNAME_LENGTH];
3374 int iv_len, al = SSL_AD_INTERNAL_ERROR;
3375 size_t macoffset, macendoffset;
3377 unsigned char age_add_c[sizeof(uint32_t)];
3381 if (SSL_IS_TLS13(s)) {
3382 if (RAND_bytes(age_add_u.age_add_c, sizeof(age_add_u)) <= 0)
3384 s->session->ext.tick_age_add = age_add_u.age_add;
3387 /* get session encoding length */
3388 slen_full = i2d_SSL_SESSION(s->session, NULL);
3390 * Some length values are 16 bits, so forget it if session is too
3393 if (slen_full == 0 || slen_full > 0xFF00) {
3394 ossl_statem_set_error(s);
3397 senc = OPENSSL_malloc(slen_full);
3399 ossl_statem_set_error(s);
3403 ctx = EVP_CIPHER_CTX_new();
3404 hctx = HMAC_CTX_new();
3405 if (ctx == NULL || hctx == NULL) {
3406 SSLerr(SSL_F_TLS_CONSTRUCT_NEW_SESSION_TICKET, ERR_R_MALLOC_FAILURE);
3411 if (!i2d_SSL_SESSION(s->session, &p))
3415 * create a fresh copy (not shared with other threads) to clean up
3418 sess = d2i_SSL_SESSION(NULL, &const_p, slen_full);
3421 sess->session_id_length = 0; /* ID is irrelevant for the ticket */
3423 slen = i2d_SSL_SESSION(sess, NULL);
3424 if (slen == 0 || slen > slen_full) { /* shouldn't ever happen */
3425 SSL_SESSION_free(sess);
3429 if (!i2d_SSL_SESSION(sess, &p)) {
3430 SSL_SESSION_free(sess);
3433 SSL_SESSION_free(sess);
3436 * Initialize HMAC and cipher contexts. If callback present it does
3437 * all the work otherwise use generated values from parent ctx.
3439 if (tctx->ext.ticket_key_cb) {
3440 /* if 0 is returned, write an empty ticket */
3441 int ret = tctx->ext.ticket_key_cb(s, key_name, iv, ctx,
3446 /* Put timeout and length */
3447 if (!WPACKET_put_bytes_u32(pkt, 0)
3448 || !WPACKET_put_bytes_u16(pkt, 0)) {
3449 SSLerr(SSL_F_TLS_CONSTRUCT_NEW_SESSION_TICKET,
3450 ERR_R_INTERNAL_ERROR);
3454 EVP_CIPHER_CTX_free(ctx);
3455 HMAC_CTX_free(hctx);
3460 iv_len = EVP_CIPHER_CTX_iv_length(ctx);
3462 const EVP_CIPHER *cipher = EVP_aes_256_cbc();
3464 iv_len = EVP_CIPHER_iv_length(cipher);
3465 if (RAND_bytes(iv, iv_len) <= 0)
3467 if (!EVP_EncryptInit_ex(ctx, cipher, NULL,
3468 tctx->ext.tick_aes_key, iv))
3470 if (!HMAC_Init_ex(hctx, tctx->ext.tick_hmac_key,
3471 sizeof(tctx->ext.tick_hmac_key),
3472 EVP_sha256(), NULL))
3474 memcpy(key_name, tctx->ext.tick_key_name,
3475 sizeof(tctx->ext.tick_key_name));
3479 * Ticket lifetime hint (advisory only): We leave this unspecified
3480 * for resumed session (for simplicity), and guess that tickets for
3481 * new sessions will live as long as their sessions.
3483 if (!WPACKET_put_bytes_u32(pkt, s->hit ? 0 : s->session->timeout)
3485 && !WPACKET_put_bytes_u32(pkt, age_add_u.age_add))
3486 /* Now the actual ticket data */
3487 || !WPACKET_start_sub_packet_u16(pkt)
3488 || !WPACKET_get_total_written(pkt, &macoffset)
3489 /* Output key name */
3490 || !WPACKET_memcpy(pkt, key_name, sizeof(key_name))
3492 || !WPACKET_memcpy(pkt, iv, iv_len)
3493 || !WPACKET_reserve_bytes(pkt, slen + EVP_MAX_BLOCK_LENGTH,
3495 /* Encrypt session data */
3496 || !EVP_EncryptUpdate(ctx, encdata1, &len, senc, slen)
3497 || !WPACKET_allocate_bytes(pkt, len, &encdata2)
3498 || encdata1 != encdata2
3499 || !EVP_EncryptFinal(ctx, encdata1 + len, &lenfinal)
3500 || !WPACKET_allocate_bytes(pkt, lenfinal, &encdata2)
3501 || encdata1 + len != encdata2
3502 || len + lenfinal > slen + EVP_MAX_BLOCK_LENGTH
3503 || !WPACKET_get_total_written(pkt, &macendoffset)
3504 || !HMAC_Update(hctx,
3505 (unsigned char *)s->init_buf->data + macoffset,
3506 macendoffset - macoffset)
3507 || !WPACKET_reserve_bytes(pkt, EVP_MAX_MD_SIZE, &macdata1)
3508 || !HMAC_Final(hctx, macdata1, &hlen)
3509 || hlen > EVP_MAX_MD_SIZE
3510 || !WPACKET_allocate_bytes(pkt, hlen, &macdata2)
3511 || macdata1 != macdata2
3512 || !WPACKET_close(pkt)
3514 && !tls_construct_extensions(s, pkt,
3515 EXT_TLS1_3_NEW_SESSION_TICKET,
3517 SSLerr(SSL_F_TLS_CONSTRUCT_NEW_SESSION_TICKET, ERR_R_INTERNAL_ERROR);
3520 EVP_CIPHER_CTX_free(ctx);
3521 HMAC_CTX_free(hctx);
3527 EVP_CIPHER_CTX_free(ctx);
3528 HMAC_CTX_free(hctx);
3529 ssl3_send_alert(s, SSL3_AL_FATAL, SSL_AD_INTERNAL_ERROR);
3534 * In TLSv1.3 this is called from the extensions code, otherwise it is used to
3535 * create a separate message. Returns 1 on success or 0 on failure.
3537 int tls_construct_cert_status_body(SSL *s, WPACKET *pkt)
3539 if (!WPACKET_put_bytes_u8(pkt, s->ext.status_type)
3540 || !WPACKET_sub_memcpy_u24(pkt, s->ext.ocsp.resp,
3541 s->ext.ocsp.resp_len)) {
3542 SSLerr(SSL_F_TLS_CONSTRUCT_CERT_STATUS_BODY, ERR_R_INTERNAL_ERROR);
3549 int tls_construct_cert_status(SSL *s, WPACKET *pkt)
3551 if (!tls_construct_cert_status_body(s, pkt)) {
3552 ssl3_send_alert(s, SSL3_AL_FATAL, SSL_AD_INTERNAL_ERROR);
3559 #ifndef OPENSSL_NO_NEXTPROTONEG
3561 * tls_process_next_proto reads a Next Protocol Negotiation handshake message.
3562 * It sets the next_proto member in s if found
3564 MSG_PROCESS_RETURN tls_process_next_proto(SSL *s, PACKET *pkt)
3566 PACKET next_proto, padding;
3567 size_t next_proto_len;
3570 * The payload looks like:
3572 * uint8 proto[proto_len];
3573 * uint8 padding_len;
3574 * uint8 padding[padding_len];
3576 if (!PACKET_get_length_prefixed_1(pkt, &next_proto)
3577 || !PACKET_get_length_prefixed_1(pkt, &padding)
3578 || PACKET_remaining(pkt) > 0) {
3579 SSLerr(SSL_F_TLS_PROCESS_NEXT_PROTO, SSL_R_LENGTH_MISMATCH);
3583 if (!PACKET_memdup(&next_proto, &s->ext.npn, &next_proto_len)) {
3588 s->ext.npn_len = (unsigned char)next_proto_len;
3590 return MSG_PROCESS_CONTINUE_READING;
3592 ossl_statem_set_error(s);
3593 return MSG_PROCESS_ERROR;
3597 static int tls_construct_encrypted_extensions(SSL *s, WPACKET *pkt)
3601 if (!tls_construct_extensions(s, pkt, EXT_TLS1_3_ENCRYPTED_EXTENSIONS,
3603 ssl3_send_alert(s, SSL3_AL_FATAL, al);
3604 SSLerr(SSL_F_TLS_CONSTRUCT_ENCRYPTED_EXTENSIONS, ERR_R_INTERNAL_ERROR);
3605 ssl3_send_alert(s, SSL3_AL_FATAL, al);
3612 static int tls_construct_hello_retry_request(SSL *s, WPACKET *pkt)
3614 int al = SSL_AD_INTERNAL_ERROR;
3617 * TODO(TLS1.3): Remove the DRAFT version before release
3618 * (should be s->version)
3620 if (!WPACKET_put_bytes_u16(pkt, TLS1_3_VERSION_DRAFT)
3621 || !tls_construct_extensions(s, pkt, EXT_TLS1_3_HELLO_RETRY_REQUEST,
3623 SSLerr(SSL_F_TLS_CONSTRUCT_HELLO_RETRY_REQUEST, ERR_R_INTERNAL_ERROR);
3624 ssl3_send_alert(s, SSL3_AL_FATAL, al);
3628 /* Ditch the session. We'll create a new one next time around */
3629 SSL_SESSION_free(s->session);