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
52 #include "../ssl_locl.h"
53 #include "statem_locl.h"
54 #include "internal/constant_time_locl.h"
55 #include <openssl/buffer.h>
56 #include <openssl/rand.h>
57 #include <openssl/objects.h>
58 #include <openssl/evp.h>
59 #include <openssl/hmac.h>
60 #include <openssl/x509.h>
61 #include <openssl/dh.h>
62 #include <openssl/bn.h>
63 #include <openssl/md5.h>
65 static STACK_OF(SSL_CIPHER) *ssl_bytes_to_cipher_list(SSL *s,
66 PACKET *cipher_suites,
67 STACK_OF(SSL_CIPHER) **skp,
68 int sslv2format, int *al);
71 * server_read_transition() encapsulates the logic for the allowed handshake
72 * state transitions when the server is reading messages from the client. The
73 * message type that the client has sent is provided in |mt|. The current state
74 * is in |s->statem.hand_state|.
76 * Valid return values are:
77 * 1: Success (transition allowed)
78 * 0: Error (transition not allowed)
80 int ossl_statem_server_read_transition(SSL *s, int mt)
82 OSSL_STATEM *st = &s->statem;
84 switch(st->hand_state) {
86 case DTLS_ST_SW_HELLO_VERIFY_REQUEST:
87 if (mt == SSL3_MT_CLIENT_HELLO) {
88 st->hand_state = TLS_ST_SR_CLNT_HELLO;
93 case TLS_ST_SW_SRVR_DONE:
95 * If we get a CKE message after a ServerDone then either
96 * 1) We didn't request a Certificate
98 * 2) If we did request one then
99 * a) We allow no Certificate to be returned
101 * b) We are running SSL3 (in TLS1.0+ the client must return a 0
102 * list if we requested a certificate)
104 if (mt == SSL3_MT_CLIENT_KEY_EXCHANGE) {
105 if (s->s3->tmp.cert_request) {
106 if (s->version == SSL3_VERSION) {
107 if ((s->verify_mode & SSL_VERIFY_PEER) &&
108 (s->verify_mode & SSL_VERIFY_FAIL_IF_NO_PEER_CERT)) {
110 * This isn't an unexpected message as such - we're just
111 * not going to accept it.
113 ssl3_send_alert(s, SSL3_AL_FATAL,
114 SSL3_AD_HANDSHAKE_FAILURE);
115 SSLerr(SSL_F_READ_STATE_MACHINE,
116 SSL_R_PEER_DID_NOT_RETURN_A_CERTIFICATE);
119 st->hand_state = TLS_ST_SR_KEY_EXCH;
123 st->hand_state = TLS_ST_SR_KEY_EXCH;
126 } else if (s->s3->tmp.cert_request) {
127 if (mt == SSL3_MT_CERTIFICATE) {
128 st->hand_state = TLS_ST_SR_CERT;
135 if (mt == SSL3_MT_CLIENT_KEY_EXCHANGE) {
136 st->hand_state = TLS_ST_SR_KEY_EXCH;
141 case TLS_ST_SR_KEY_EXCH:
143 * We should only process a CertificateVerify message if we have
144 * received a Certificate from the client. If so then |s->session->peer|
145 * will be non NULL. In some instances a CertificateVerify message is
146 * not required even if the peer has sent a Certificate (e.g. such as in
147 * the case of static DH). In that case |st->no_cert_verify| should be
150 if (s->session->peer == NULL || st->no_cert_verify) {
151 if (mt == SSL3_MT_CHANGE_CIPHER_SPEC) {
153 * For the ECDH ciphersuites when the client sends its ECDH
154 * pub key in a certificate, the CertificateVerify message is
155 * not sent. Also for GOST ciphersuites when the client uses
156 * its key from the certificate for key exchange.
158 st->hand_state = TLS_ST_SR_CHANGE;
162 if (mt == SSL3_MT_CERTIFICATE_VERIFY) {
163 st->hand_state = TLS_ST_SR_CERT_VRFY;
169 case TLS_ST_SR_CERT_VRFY:
170 if (mt == SSL3_MT_CHANGE_CIPHER_SPEC) {
171 st->hand_state = TLS_ST_SR_CHANGE;
176 case TLS_ST_SR_CHANGE:
177 #ifndef OPENSSL_NO_NEXTPROTONEG
178 if (s->s3->next_proto_neg_seen) {
179 if (mt == SSL3_MT_NEXT_PROTO) {
180 st->hand_state = TLS_ST_SR_NEXT_PROTO;
185 if (mt == SSL3_MT_FINISHED) {
186 st->hand_state = TLS_ST_SR_FINISHED;
189 #ifndef OPENSSL_NO_NEXTPROTONEG
194 #ifndef OPENSSL_NO_NEXTPROTONEG
195 case TLS_ST_SR_NEXT_PROTO:
196 if (mt == SSL3_MT_FINISHED) {
197 st->hand_state = TLS_ST_SR_FINISHED;
203 case TLS_ST_SW_FINISHED:
204 if (mt == SSL3_MT_CHANGE_CIPHER_SPEC) {
205 st->hand_state = TLS_ST_SR_CHANGE;
214 /* No valid transition found */
215 ssl3_send_alert(s, SSL3_AL_FATAL, SSL3_AD_UNEXPECTED_MESSAGE);
216 SSLerr(SSL_F_READ_STATE_MACHINE, SSL_R_UNEXPECTED_MESSAGE);
221 * Should we send a ServerKeyExchange message?
223 * Valid return values are:
227 static int send_server_key_exchange(SSL *s)
229 unsigned long alg_k = s->s3->tmp.new_cipher->algorithm_mkey;
232 * only send a ServerKeyExchange if DH or fortezza but we have a
233 * sign only certificate PSK: may send PSK identity hints For
234 * ECC ciphersuites, we send a serverKeyExchange message only if
235 * the cipher suite is either ECDH-anon or ECDHE. In other cases,
236 * the server certificate contains the server's public key for
239 if (alg_k & (SSL_kDHE|SSL_kECDHE)
241 * PSK: send ServerKeyExchange if PSK identity hint if
244 #ifndef OPENSSL_NO_PSK
245 /* Only send SKE if we have identity hint for plain PSK */
246 || ((alg_k & (SSL_kPSK | SSL_kRSAPSK))
247 && s->cert->psk_identity_hint)
248 /* For other PSK always send SKE */
249 || (alg_k & (SSL_PSK & (SSL_kDHEPSK | SSL_kECDHEPSK)))
251 #ifndef OPENSSL_NO_SRP
252 /* SRP: send ServerKeyExchange */
253 || (alg_k & SSL_kSRP)
263 * Should we send a CertificateRequest message?
265 * Valid return values are:
269 static int send_certificate_request(SSL *s)
272 /* don't request cert unless asked for it: */
273 s->verify_mode & SSL_VERIFY_PEER
275 * if SSL_VERIFY_CLIENT_ONCE is set, don't request cert
276 * during re-negotiation:
278 && ((s->session->peer == NULL) ||
279 !(s->verify_mode & SSL_VERIFY_CLIENT_ONCE))
281 * never request cert in anonymous ciphersuites (see
282 * section "Certificate request" in SSL 3 drafts and in
285 && (!(s->s3->tmp.new_cipher->algorithm_auth & SSL_aNULL)
287 * ... except when the application insists on
288 * verification (against the specs, but statem_clnt.c accepts
291 || (s->verify_mode & SSL_VERIFY_FAIL_IF_NO_PEER_CERT))
292 /* don't request certificate for SRP auth */
293 && !(s->s3->tmp.new_cipher->algorithm_auth & SSL_aSRP)
295 * With normal PSK Certificates and Certificate Requests
298 && !(s->s3->tmp.new_cipher->algorithm_auth & SSL_aPSK)) {
306 * server_write_transition() works out what handshake state to move to next
307 * when the server is writing messages to be sent to the client.
309 WRITE_TRAN ossl_statem_server_write_transition(SSL *s)
311 OSSL_STATEM *st = &s->statem;
313 switch(st->hand_state) {
315 /* Just go straight to trying to read from the client */;
316 return WRITE_TRAN_FINISHED;
319 /* We must be trying to renegotiate */
320 st->hand_state = TLS_ST_SW_HELLO_REQ;
321 return WRITE_TRAN_CONTINUE;
323 case TLS_ST_SW_HELLO_REQ:
324 st->hand_state = TLS_ST_OK;
325 ossl_statem_set_in_init(s, 0);
326 return WRITE_TRAN_CONTINUE;
328 case TLS_ST_SR_CLNT_HELLO:
329 if (SSL_IS_DTLS(s) && !s->d1->cookie_verified
330 && (SSL_get_options(s) & SSL_OP_COOKIE_EXCHANGE))
331 st->hand_state = DTLS_ST_SW_HELLO_VERIFY_REQUEST;
333 st->hand_state = TLS_ST_SW_SRVR_HELLO;
334 return WRITE_TRAN_CONTINUE;
336 case DTLS_ST_SW_HELLO_VERIFY_REQUEST:
337 return WRITE_TRAN_FINISHED;
339 case TLS_ST_SW_SRVR_HELLO:
341 if (s->tlsext_ticket_expected)
342 st->hand_state = TLS_ST_SW_SESSION_TICKET;
344 st->hand_state = TLS_ST_SW_CHANGE;
346 /* Check if it is anon DH or anon ECDH, */
347 /* normal PSK or SRP */
348 if (!(s->s3->tmp.new_cipher->algorithm_auth &
349 (SSL_aNULL | SSL_aSRP | SSL_aPSK))) {
350 st->hand_state = TLS_ST_SW_CERT;
351 } else if (send_server_key_exchange(s)) {
352 st->hand_state = TLS_ST_SW_KEY_EXCH;
353 } else if (send_certificate_request(s)) {
354 st->hand_state = TLS_ST_SW_CERT_REQ;
356 st->hand_state = TLS_ST_SW_SRVR_DONE;
359 return WRITE_TRAN_CONTINUE;
362 if (s->tlsext_status_expected) {
363 st->hand_state = TLS_ST_SW_CERT_STATUS;
364 return WRITE_TRAN_CONTINUE;
368 case TLS_ST_SW_CERT_STATUS:
369 if (send_server_key_exchange(s)) {
370 st->hand_state = TLS_ST_SW_KEY_EXCH;
371 return WRITE_TRAN_CONTINUE;
375 case TLS_ST_SW_KEY_EXCH:
376 if (send_certificate_request(s)) {
377 st->hand_state = TLS_ST_SW_CERT_REQ;
378 return WRITE_TRAN_CONTINUE;
382 case TLS_ST_SW_CERT_REQ:
383 st->hand_state = TLS_ST_SW_SRVR_DONE;
384 return WRITE_TRAN_CONTINUE;
386 case TLS_ST_SW_SRVR_DONE:
387 return WRITE_TRAN_FINISHED;
389 case TLS_ST_SR_FINISHED:
391 st->hand_state = TLS_ST_OK;
392 ossl_statem_set_in_init(s, 0);
393 return WRITE_TRAN_CONTINUE;
394 } else if (s->tlsext_ticket_expected) {
395 st->hand_state = TLS_ST_SW_SESSION_TICKET;
397 st->hand_state = TLS_ST_SW_CHANGE;
399 return WRITE_TRAN_CONTINUE;
401 case TLS_ST_SW_SESSION_TICKET:
402 st->hand_state = TLS_ST_SW_CHANGE;
403 return WRITE_TRAN_CONTINUE;
405 case TLS_ST_SW_CHANGE:
406 st->hand_state = TLS_ST_SW_FINISHED;
407 return WRITE_TRAN_CONTINUE;
409 case TLS_ST_SW_FINISHED:
411 return WRITE_TRAN_FINISHED;
413 st->hand_state = TLS_ST_OK;
414 ossl_statem_set_in_init(s, 0);
415 return WRITE_TRAN_CONTINUE;
418 /* Shouldn't happen */
419 return WRITE_TRAN_ERROR;
424 * Perform any pre work that needs to be done prior to sending a message from
425 * the server to the client.
427 WORK_STATE ossl_statem_server_pre_work(SSL *s, WORK_STATE wst)
429 OSSL_STATEM *st = &s->statem;
431 switch(st->hand_state) {
432 case TLS_ST_SW_HELLO_REQ:
435 dtls1_clear_record_buffer(s);
438 case DTLS_ST_SW_HELLO_VERIFY_REQUEST:
440 if (SSL_IS_DTLS(s)) {
441 dtls1_clear_record_buffer(s);
442 /* We don't buffer this message so don't use the timer */
447 case TLS_ST_SW_SRVR_HELLO:
448 if (SSL_IS_DTLS(s)) {
450 * Messages we write from now on should be bufferred and
451 * retransmitted if necessary, so we need to use the timer now
457 case TLS_ST_SW_SRVR_DONE:
458 #ifndef OPENSSL_NO_SCTP
459 if (SSL_IS_DTLS(s) && BIO_dgram_is_sctp(SSL_get_wbio(s)))
460 return dtls_wait_for_dry(s);
462 return WORK_FINISHED_CONTINUE;
464 case TLS_ST_SW_SESSION_TICKET:
465 if (SSL_IS_DTLS(s)) {
467 * We're into the last flight. We don't retransmit the last flight
468 * unless we need to, so we don't use the timer
474 case TLS_ST_SW_CHANGE:
475 s->session->cipher = s->s3->tmp.new_cipher;
476 if (!s->method->ssl3_enc->setup_key_block(s)) {
477 ossl_statem_set_error(s);
480 if (SSL_IS_DTLS(s)) {
482 * We're into the last flight. We don't retransmit the last flight
483 * unless we need to, so we don't use the timer. This might have
484 * already been set to 0 if we sent a NewSessionTicket message,
485 * but we'll set it again here in case we didn't.
489 return WORK_FINISHED_CONTINUE;
492 return tls_finish_handshake(s, wst);
495 /* No pre work to be done */
499 return WORK_FINISHED_CONTINUE;
503 * Perform any work that needs to be done after sending a message from the
504 * server to the client.
506 WORK_STATE ossl_statem_server_post_work(SSL *s, WORK_STATE wst)
508 OSSL_STATEM *st = &s->statem;
512 switch(st->hand_state) {
513 case TLS_ST_SW_HELLO_REQ:
514 if (statem_flush(s) != 1)
516 if (!ssl3_init_finished_mac(s)) {
517 ossl_statem_set_error(s);
522 case DTLS_ST_SW_HELLO_VERIFY_REQUEST:
523 if (statem_flush(s) != 1)
525 /* HelloVerifyRequest resets Finished MAC */
526 if (s->version != DTLS1_BAD_VER && !ssl3_init_finished_mac(s)) {
527 ossl_statem_set_error(s);
531 * The next message should be another ClientHello which we need to
532 * treat like it was the first packet
537 case TLS_ST_SW_SRVR_HELLO:
538 #ifndef OPENSSL_NO_SCTP
539 if (SSL_IS_DTLS(s) && s->hit) {
540 unsigned char sctpauthkey[64];
541 char labelbuffer[sizeof(DTLS1_SCTP_AUTH_LABEL)];
544 * Add new shared key for SCTP-Auth, will be ignored if no
547 memcpy(labelbuffer, DTLS1_SCTP_AUTH_LABEL,
548 sizeof(DTLS1_SCTP_AUTH_LABEL));
550 if (SSL_export_keying_material(s, sctpauthkey,
551 sizeof(sctpauthkey), labelbuffer,
552 sizeof(labelbuffer), NULL, 0, 0) <= 0) {
553 ossl_statem_set_error(s);
557 BIO_ctrl(SSL_get_wbio(s), BIO_CTRL_DGRAM_SCTP_ADD_AUTH_KEY,
558 sizeof(sctpauthkey), sctpauthkey);
563 case TLS_ST_SW_CHANGE:
564 #ifndef OPENSSL_NO_SCTP
565 if (SSL_IS_DTLS(s) && !s->hit) {
567 * Change to new shared key of SCTP-Auth, will be ignored if
570 BIO_ctrl(SSL_get_wbio(s), BIO_CTRL_DGRAM_SCTP_NEXT_AUTH_KEY,
574 if (!s->method->ssl3_enc->change_cipher_state(s,
575 SSL3_CHANGE_CIPHER_SERVER_WRITE)) {
576 ossl_statem_set_error(s);
581 dtls1_reset_seq_numbers(s, SSL3_CC_WRITE);
584 case TLS_ST_SW_SRVR_DONE:
585 if (statem_flush(s) != 1)
589 case TLS_ST_SW_FINISHED:
590 if (statem_flush(s) != 1)
592 #ifndef OPENSSL_NO_SCTP
593 if (SSL_IS_DTLS(s) && s->hit) {
595 * Change to new shared key of SCTP-Auth, will be ignored if
598 BIO_ctrl(SSL_get_wbio(s), BIO_CTRL_DGRAM_SCTP_NEXT_AUTH_KEY,
605 /* No post work to be done */
609 return WORK_FINISHED_CONTINUE;
613 * Construct a message to be sent from the server to the client.
615 * Valid return values are:
619 int ossl_statem_server_construct_message(SSL *s)
621 OSSL_STATEM *st = &s->statem;
623 switch(st->hand_state) {
624 case DTLS_ST_SW_HELLO_VERIFY_REQUEST:
625 return dtls_construct_hello_verify_request(s);
627 case TLS_ST_SW_HELLO_REQ:
628 return tls_construct_hello_request(s);
630 case TLS_ST_SW_SRVR_HELLO:
631 return tls_construct_server_hello(s);
634 return tls_construct_server_certificate(s);
636 case TLS_ST_SW_KEY_EXCH:
637 return tls_construct_server_key_exchange(s);
639 case TLS_ST_SW_CERT_REQ:
640 return tls_construct_certificate_request(s);
642 case TLS_ST_SW_SRVR_DONE:
643 return tls_construct_server_done(s);
645 case TLS_ST_SW_SESSION_TICKET:
646 return tls_construct_new_session_ticket(s);
648 case TLS_ST_SW_CERT_STATUS:
649 return tls_construct_cert_status(s);
651 case TLS_ST_SW_CHANGE:
653 return dtls_construct_change_cipher_spec(s);
655 return tls_construct_change_cipher_spec(s);
657 case TLS_ST_SW_FINISHED:
658 return tls_construct_finished(s,
660 ssl3_enc->server_finished_label,
662 ssl3_enc->server_finished_label_len);
665 /* Shouldn't happen */
673 * Maximum size (excluding the Handshake header) of a ClientHello message,
674 * calculated as follows:
676 * 2 + # client_version
677 * 32 + # only valid length for random
678 * 1 + # length of session_id
679 * 32 + # maximum size for session_id
680 * 2 + # length of cipher suites
681 * 2^16-2 + # maximum length of cipher suites array
682 * 1 + # length of compression_methods
683 * 2^8-1 + # maximum length of compression methods
684 * 2 + # length of extensions
685 * 2^16-1 # maximum length of extensions
687 #define CLIENT_HELLO_MAX_LENGTH 131396
689 #define CLIENT_KEY_EXCH_MAX_LENGTH 2048
690 #define NEXT_PROTO_MAX_LENGTH 514
693 * Returns the maximum allowed length for the current message that we are
694 * reading. Excludes the message header.
696 unsigned long ossl_statem_server_max_message_size(SSL *s)
698 OSSL_STATEM *st = &s->statem;
700 switch(st->hand_state) {
701 case TLS_ST_SR_CLNT_HELLO:
702 return CLIENT_HELLO_MAX_LENGTH;
705 return s->max_cert_list;
707 case TLS_ST_SR_KEY_EXCH:
708 return CLIENT_KEY_EXCH_MAX_LENGTH;
710 case TLS_ST_SR_CERT_VRFY:
711 return SSL3_RT_MAX_PLAIN_LENGTH;
713 #ifndef OPENSSL_NO_NEXTPROTONEG
714 case TLS_ST_SR_NEXT_PROTO:
715 return NEXT_PROTO_MAX_LENGTH;
718 case TLS_ST_SR_CHANGE:
719 return CCS_MAX_LENGTH;
721 case TLS_ST_SR_FINISHED:
722 return FINISHED_MAX_LENGTH;
725 /* Shouldn't happen */
733 * Process a message that the server has received from the client.
735 MSG_PROCESS_RETURN ossl_statem_server_process_message(SSL *s, PACKET *pkt)
737 OSSL_STATEM *st = &s->statem;
739 switch(st->hand_state) {
740 case TLS_ST_SR_CLNT_HELLO:
741 return tls_process_client_hello(s, pkt);
744 return tls_process_client_certificate(s, pkt);
746 case TLS_ST_SR_KEY_EXCH:
747 return tls_process_client_key_exchange(s, pkt);
749 case TLS_ST_SR_CERT_VRFY:
750 return tls_process_cert_verify(s, pkt);
752 #ifndef OPENSSL_NO_NEXTPROTONEG
753 case TLS_ST_SR_NEXT_PROTO:
754 return tls_process_next_proto(s, pkt);
757 case TLS_ST_SR_CHANGE:
758 return tls_process_change_cipher_spec(s, pkt);
760 case TLS_ST_SR_FINISHED:
761 return tls_process_finished(s, pkt);
764 /* Shouldn't happen */
768 return MSG_PROCESS_ERROR;
772 * Perform any further processing required following the receipt of a message
775 WORK_STATE ossl_statem_server_post_process_message(SSL *s, WORK_STATE wst)
777 OSSL_STATEM *st = &s->statem;
779 switch(st->hand_state) {
780 case TLS_ST_SR_CLNT_HELLO:
781 return tls_post_process_client_hello(s, wst);
783 case TLS_ST_SR_KEY_EXCH:
784 return tls_post_process_client_key_exchange(s, wst);
786 case TLS_ST_SR_CERT_VRFY:
787 #ifndef OPENSSL_NO_SCTP
788 if ( /* Is this SCTP? */
789 BIO_dgram_is_sctp(SSL_get_wbio(s))
790 /* Are we renegotiating? */
792 && BIO_dgram_sctp_msg_waiting(SSL_get_rbio(s))) {
793 s->s3->in_read_app_data = 2;
794 s->rwstate = SSL_READING;
795 BIO_clear_retry_flags(SSL_get_rbio(s));
796 BIO_set_retry_read(SSL_get_rbio(s));
797 ossl_statem_set_sctp_read_sock(s, 1);
800 ossl_statem_set_sctp_read_sock(s, 0);
803 return WORK_FINISHED_CONTINUE;
809 /* Shouldn't happen */
813 #ifndef OPENSSL_NO_SRP
814 static int ssl_check_srp_ext_ClientHello(SSL *s, int *al)
816 int ret = SSL_ERROR_NONE;
818 *al = SSL_AD_UNRECOGNIZED_NAME;
820 if ((s->s3->tmp.new_cipher->algorithm_mkey & SSL_kSRP) &&
821 (s->srp_ctx.TLS_ext_srp_username_callback != NULL)) {
822 if (s->srp_ctx.login == NULL) {
824 * RFC 5054 says SHOULD reject, we do so if There is no srp
828 *al = SSL_AD_UNKNOWN_PSK_IDENTITY;
830 ret = SSL_srp_server_param_with_username(s, al);
837 int tls_construct_hello_request(SSL *s)
839 if (!ssl_set_handshake_header(s, SSL3_MT_HELLO_REQUEST, 0)) {
840 SSLerr(SSL_F_TLS_CONSTRUCT_HELLO_REQUEST, ERR_R_INTERNAL_ERROR);
841 ossl_statem_set_error(s);
848 unsigned int dtls_raw_hello_verify_request(unsigned char *buf,
849 unsigned char *cookie,
850 unsigned char cookie_len)
852 unsigned int msg_len;
856 /* Always use DTLS 1.0 version: see RFC 6347 */
857 *(p++) = DTLS1_VERSION >> 8;
858 *(p++) = DTLS1_VERSION & 0xFF;
860 *(p++) = (unsigned char)cookie_len;
861 memcpy(p, cookie, cookie_len);
868 int dtls_construct_hello_verify_request(SSL *s)
873 buf = (unsigned char *)s->init_buf->data;
875 if (s->ctx->app_gen_cookie_cb == NULL ||
876 s->ctx->app_gen_cookie_cb(s, s->d1->cookie,
877 &(s->d1->cookie_len)) == 0 ||
878 s->d1->cookie_len > 255) {
879 SSLerr(SSL_F_DTLS_CONSTRUCT_HELLO_VERIFY_REQUEST,
880 SSL_R_COOKIE_GEN_CALLBACK_FAILURE);
881 ossl_statem_set_error(s);
885 len = dtls_raw_hello_verify_request(&buf[DTLS1_HM_HEADER_LENGTH],
886 s->d1->cookie, s->d1->cookie_len);
888 dtls1_set_message_header(s, DTLS1_MT_HELLO_VERIFY_REQUEST, len, 0,
890 len += DTLS1_HM_HEADER_LENGTH;
892 /* number of bytes to write */
899 MSG_PROCESS_RETURN tls_process_client_hello(SSL *s, PACKET *pkt)
901 int i, al = SSL_AD_INTERNAL_ERROR;
902 unsigned int j, complen = 0;
905 #ifndef OPENSSL_NO_COMP
906 SSL_COMP *comp = NULL;
908 STACK_OF(SSL_CIPHER) *ciphers = NULL;
910 /* |cookie| will only be initialized for DTLS. */
911 PACKET session_id, cipher_suites, compression, extensions, cookie;
913 static const unsigned char null_compression = 0;
915 is_v2_record = RECORD_LAYER_is_sslv2_record(&s->rlayer);
917 PACKET_null_init(&cookie);
918 /* First lets get s->client_version set correctly */
920 unsigned int version;
923 * An SSLv3/TLSv1 backwards-compatible CLIENT-HELLO in an SSLv2
924 * header is sent directly on the wire, not wrapped as a TLS
925 * record. Our record layer just processes the message length and passes
926 * the rest right through. Its format is:
928 * 0-1 msg_length - decoded by the record layer
929 * 2 msg_type - s->init_msg points here
931 * 5-6 cipher_spec_length
932 * 7-8 session_id_length
933 * 9-10 challenge_length
937 if (!PACKET_get_1(pkt, &mt)
938 || mt != SSL2_MT_CLIENT_HELLO) {
940 * Should never happen. We should have tested this in the record
941 * layer in order to have determined that this is a SSLv2 record
944 SSLerr(SSL_F_TLS_PROCESS_CLIENT_HELLO, ERR_R_INTERNAL_ERROR);
948 if (!PACKET_get_net_2(pkt, &version)) {
949 /* No protocol version supplied! */
950 SSLerr(SSL_F_TLS_PROCESS_CLIENT_HELLO, SSL_R_UNKNOWN_PROTOCOL);
953 if (version == 0x0002) {
954 /* This is real SSLv2. We don't support it. */
955 SSLerr(SSL_F_TLS_PROCESS_CLIENT_HELLO, SSL_R_UNKNOWN_PROTOCOL);
957 } else if ((version & 0xff00) == (SSL3_VERSION_MAJOR << 8)) {
959 s->client_version = version;
961 /* No idea what protocol this is */
962 SSLerr(SSL_F_TLS_PROCESS_CLIENT_HELLO, SSL_R_UNKNOWN_PROTOCOL);
967 * use version from inside client hello, not from record header (may
968 * differ: see RFC 2246, Appendix E, second paragraph)
970 if(!PACKET_get_net_2(pkt, (unsigned int *)&s->client_version)) {
971 al = SSL_AD_DECODE_ERROR;
972 SSLerr(SSL_F_TLS_PROCESS_CLIENT_HELLO, SSL_R_LENGTH_TOO_SHORT);
978 * Do SSL/TLS version negotiation if applicable. For DTLS we just check
979 * versions are potentially compatible. Version negotiation comes later.
981 if (!SSL_IS_DTLS(s)) {
982 protverr = ssl_choose_server_version(s);
983 } else if (s->method->version != DTLS_ANY_VERSION &&
984 DTLS_VERSION_LT(s->client_version, s->version)) {
985 protverr = SSL_R_VERSION_TOO_LOW;
991 SSLerr(SSL_F_TLS_PROCESS_CLIENT_HELLO, protverr);
992 if ((!s->enc_write_ctx && !s->write_hash)) {
994 * similar to ssl3_get_record, send alert using remote version
997 s->version = s->client_version;
999 al = SSL_AD_PROTOCOL_VERSION;
1003 /* Parse the message and load client random. */
1006 * Handle an SSLv2 backwards compatible ClientHello
1007 * Note, this is only for SSLv3+ using the backward compatible format.
1008 * Real SSLv2 is not supported, and is rejected above.
1010 unsigned int cipher_len, session_id_len, challenge_len;
1013 if (!PACKET_get_net_2(pkt, &cipher_len)
1014 || !PACKET_get_net_2(pkt, &session_id_len)
1015 || !PACKET_get_net_2(pkt, &challenge_len)) {
1016 SSLerr(SSL_F_TLS_PROCESS_CLIENT_HELLO,
1017 SSL_R_RECORD_LENGTH_MISMATCH);
1018 al = SSL_AD_DECODE_ERROR;
1022 if (session_id_len > SSL_MAX_SSL_SESSION_ID_LENGTH) {
1023 al = SSL_AD_DECODE_ERROR;
1024 SSLerr(SSL_F_TLS_PROCESS_CLIENT_HELLO, SSL_R_LENGTH_MISMATCH);
1028 if (!PACKET_get_sub_packet(pkt, &cipher_suites, cipher_len)
1029 || !PACKET_get_sub_packet(pkt, &session_id, session_id_len)
1030 || !PACKET_get_sub_packet(pkt, &challenge, challenge_len)
1031 /* No extensions. */
1032 || PACKET_remaining(pkt) != 0) {
1033 SSLerr(SSL_F_TLS_PROCESS_CLIENT_HELLO,
1034 SSL_R_RECORD_LENGTH_MISMATCH);
1035 al = SSL_AD_DECODE_ERROR;
1039 /* Load the client random and compression list. */
1040 challenge_len = challenge_len > SSL3_RANDOM_SIZE ? SSL3_RANDOM_SIZE :
1042 memset(s->s3->client_random, 0, SSL3_RANDOM_SIZE);
1043 if (!PACKET_copy_bytes(&challenge,
1044 s->s3->client_random + SSL3_RANDOM_SIZE -
1045 challenge_len, challenge_len)
1046 /* Advertise only null compression. */
1047 || !PACKET_buf_init(&compression, &null_compression, 1)) {
1048 SSLerr(SSL_F_TLS_PROCESS_CLIENT_HELLO, ERR_R_INTERNAL_ERROR);
1049 al = SSL_AD_INTERNAL_ERROR;
1053 PACKET_null_init(&extensions);
1055 /* Regular ClientHello. */
1056 if (!PACKET_copy_bytes(pkt, s->s3->client_random, SSL3_RANDOM_SIZE)
1057 || !PACKET_get_length_prefixed_1(pkt, &session_id)) {
1058 al = SSL_AD_DECODE_ERROR;
1059 SSLerr(SSL_F_TLS_PROCESS_CLIENT_HELLO, SSL_R_LENGTH_MISMATCH);
1063 if (PACKET_remaining(&session_id) > SSL_MAX_SSL_SESSION_ID_LENGTH) {
1064 al = SSL_AD_DECODE_ERROR;
1065 SSLerr(SSL_F_TLS_PROCESS_CLIENT_HELLO, SSL_R_LENGTH_MISMATCH);
1069 if (SSL_IS_DTLS(s)) {
1070 if (!PACKET_get_length_prefixed_1(pkt, &cookie)) {
1071 al = SSL_AD_DECODE_ERROR;
1072 SSLerr(SSL_F_TLS_PROCESS_CLIENT_HELLO, SSL_R_LENGTH_MISMATCH);
1076 * If we require cookies and this ClientHello doesn't contain one,
1077 * just return since we do not want to allocate any memory yet.
1078 * So check cookie length...
1080 if (SSL_get_options(s) & SSL_OP_COOKIE_EXCHANGE) {
1081 if (PACKET_remaining(&cookie) == 0)
1086 if (!PACKET_get_length_prefixed_2(pkt, &cipher_suites)
1087 || !PACKET_get_length_prefixed_1(pkt, &compression)) {
1088 al = SSL_AD_DECODE_ERROR;
1089 SSLerr(SSL_F_TLS_PROCESS_CLIENT_HELLO, SSL_R_LENGTH_MISMATCH);
1092 /* Could be empty. */
1096 if (SSL_IS_DTLS(s)) {
1097 /* Empty cookie was already handled above by returning early. */
1098 if (SSL_get_options(s) & SSL_OP_COOKIE_EXCHANGE) {
1099 if (s->ctx->app_verify_cookie_cb != NULL) {
1100 if (s->ctx->app_verify_cookie_cb(s, PACKET_data(&cookie),
1101 PACKET_remaining(&cookie)) == 0) {
1102 al = SSL_AD_HANDSHAKE_FAILURE;
1103 SSLerr(SSL_F_TLS_PROCESS_CLIENT_HELLO,
1104 SSL_R_COOKIE_MISMATCH);
1106 /* else cookie verification succeeded */
1108 /* default verification */
1109 } else if (!PACKET_equal(&cookie, s->d1->cookie,
1110 s->d1->cookie_len)) {
1111 al = SSL_AD_HANDSHAKE_FAILURE;
1112 SSLerr(SSL_F_TLS_PROCESS_CLIENT_HELLO, SSL_R_COOKIE_MISMATCH);
1115 s->d1->cookie_verified = 1;
1117 if (s->method->version == DTLS_ANY_VERSION) {
1118 protverr = ssl_choose_server_version(s);
1119 if (protverr != 0) {
1120 SSLerr(SSL_F_TLS_PROCESS_CLIENT_HELLO, protverr);
1121 s->version = s->client_version;
1122 al = SSL_AD_PROTOCOL_VERSION;
1131 * We don't allow resumption in a backwards compatible ClientHello.
1132 * TODO(openssl-team): in TLS1.1+, session_id MUST be empty.
1134 * Versions before 0.9.7 always allow clients to resume sessions in
1135 * renegotiation. 0.9.7 and later allow this by default, but optionally
1136 * ignore resumption requests with flag
1137 * SSL_OP_NO_SESSION_RESUMPTION_ON_RENEGOTIATION (it's a new flag rather
1138 * than a change to default behavior so that applications relying on
1139 * this for security won't even compile against older library versions).
1140 * 1.0.1 and later also have a function SSL_renegotiate_abbreviated() to
1141 * request renegotiation but not a new session (s->new_session remains
1142 * unset): for servers, this essentially just means that the
1143 * SSL_OP_NO_SESSION_RESUMPTION_ON_RENEGOTIATION setting will be
1148 (s->options & SSL_OP_NO_SESSION_RESUMPTION_ON_RENEGOTIATION))) {
1149 if (!ssl_get_new_session(s, 1))
1152 i = ssl_get_prev_session(s, &extensions, &session_id);
1154 * Only resume if the session's version matches the negotiated
1156 * RFC 5246 does not provide much useful advice on resumption
1157 * with a different protocol version. It doesn't forbid it but
1158 * the sanity of such behaviour would be questionable.
1159 * In practice, clients do not accept a version mismatch and
1160 * will abort the handshake with an error.
1162 if (i == 1 && s->version == s->session->ssl_version) {
1163 /* previous session */
1165 } else if (i == -1) {
1169 if (!ssl_get_new_session(s, 1))
1174 if (ssl_bytes_to_cipher_list(s, &cipher_suites, &(ciphers),
1175 is_v2_record, &al) == NULL) {
1179 /* If it is a hit, check that the cipher is in the list */
1182 id = s->session->cipher->id;
1185 fprintf(stderr, "client sent %d ciphers\n",
1186 sk_SSL_CIPHER_num(ciphers));
1188 for (i = 0; i < sk_SSL_CIPHER_num(ciphers); i++) {
1189 c = sk_SSL_CIPHER_value(ciphers, i);
1191 fprintf(stderr, "client [%2d of %2d]:%s\n",
1192 i, sk_SSL_CIPHER_num(ciphers), SSL_CIPHER_get_name(c));
1201 * we need to have the cipher in the cipher list if we are asked
1204 al = SSL_AD_ILLEGAL_PARAMETER;
1205 SSLerr(SSL_F_TLS_PROCESS_CLIENT_HELLO,
1206 SSL_R_REQUIRED_CIPHER_MISSING);
1211 complen = PACKET_remaining(&compression);
1212 for (j = 0; j < complen; j++) {
1213 if (PACKET_data(&compression)[j] == 0)
1219 al = SSL_AD_DECODE_ERROR;
1220 SSLerr(SSL_F_TLS_PROCESS_CLIENT_HELLO, SSL_R_NO_COMPRESSION_SPECIFIED);
1224 /* TLS extensions */
1225 if (s->version >= SSL3_VERSION) {
1226 if (!ssl_parse_clienthello_tlsext(s, &extensions)) {
1227 SSLerr(SSL_F_TLS_PROCESS_CLIENT_HELLO, SSL_R_PARSE_TLSEXT);
1233 * Check if we want to use external pre-shared secret for this handshake
1234 * for not reused session only. We need to generate server_random before
1235 * calling tls_session_secret_cb in order to allow SessionTicket
1236 * processing to use it in key derivation.
1240 pos = s->s3->server_random;
1241 if (ssl_fill_hello_random(s, 1, pos, SSL3_RANDOM_SIZE) <= 0) {
1246 if (!s->hit && s->version >= TLS1_VERSION && s->tls_session_secret_cb) {
1247 const SSL_CIPHER *pref_cipher = NULL;
1249 s->session->master_key_length = sizeof(s->session->master_key);
1250 if (s->tls_session_secret_cb(s, s->session->master_key,
1251 &s->session->master_key_length, ciphers,
1253 s->tls_session_secret_cb_arg)) {
1255 s->session->ciphers = ciphers;
1256 s->session->verify_result = X509_V_OK;
1260 /* check if some cipher was preferred by call back */
1262 pref_cipher ? pref_cipher : ssl3_choose_cipher(s,
1267 if (pref_cipher == NULL) {
1268 al = SSL_AD_HANDSHAKE_FAILURE;
1269 SSLerr(SSL_F_TLS_PROCESS_CLIENT_HELLO, SSL_R_NO_SHARED_CIPHER);
1273 s->session->cipher = pref_cipher;
1274 sk_SSL_CIPHER_free(s->cipher_list);
1275 s->cipher_list = sk_SSL_CIPHER_dup(s->session->ciphers);
1276 sk_SSL_CIPHER_free(s->cipher_list_by_id);
1277 s->cipher_list_by_id = sk_SSL_CIPHER_dup(s->session->ciphers);
1282 * Worst case, we will use the NULL compression, but if we have other
1283 * options, we will now look for them. We have complen-1 compression
1284 * algorithms from the client, starting at q.
1286 s->s3->tmp.new_compression = NULL;
1287 #ifndef OPENSSL_NO_COMP
1288 /* This only happens if we have a cache hit */
1289 if (s->session->compress_meth != 0) {
1290 int m, comp_id = s->session->compress_meth;
1292 /* Perform sanity checks on resumed compression algorithm */
1293 /* Can't disable compression */
1294 if (!ssl_allow_compression(s)) {
1295 SSLerr(SSL_F_TLS_PROCESS_CLIENT_HELLO,
1296 SSL_R_INCONSISTENT_COMPRESSION);
1299 /* Look for resumed compression method */
1300 for (m = 0; m < sk_SSL_COMP_num(s->ctx->comp_methods); m++) {
1301 comp = sk_SSL_COMP_value(s->ctx->comp_methods, m);
1302 if (comp_id == comp->id) {
1303 s->s3->tmp.new_compression = comp;
1307 if (s->s3->tmp.new_compression == NULL) {
1308 SSLerr(SSL_F_TLS_PROCESS_CLIENT_HELLO,
1309 SSL_R_INVALID_COMPRESSION_ALGORITHM);
1312 /* Look for resumed method in compression list */
1313 for (k = 0; k < complen; k++) {
1314 if (PACKET_data(&compression)[k] == comp_id)
1318 al = SSL_AD_ILLEGAL_PARAMETER;
1319 SSLerr(SSL_F_TLS_PROCESS_CLIENT_HELLO,
1320 SSL_R_REQUIRED_COMPRESSION_ALGORITHM_MISSING);
1325 else if (ssl_allow_compression(s) && s->ctx->comp_methods) {
1326 /* See if we have a match */
1327 int m, nn, v, done = 0;
1330 nn = sk_SSL_COMP_num(s->ctx->comp_methods);
1331 for (m = 0; m < nn; m++) {
1332 comp = sk_SSL_COMP_value(s->ctx->comp_methods, m);
1334 for (o = 0; o < complen; o++) {
1335 if (v == PACKET_data(&compression)[o]) {
1344 s->s3->tmp.new_compression = comp;
1350 * If compression is disabled we'd better not try to resume a session
1351 * using compression.
1353 if (s->session->compress_meth != 0) {
1354 SSLerr(SSL_F_TLS_PROCESS_CLIENT_HELLO, SSL_R_INCONSISTENT_COMPRESSION);
1360 * Given s->session->ciphers and SSL_get_ciphers, we must pick a cipher
1364 #ifdef OPENSSL_NO_COMP
1365 s->session->compress_meth = 0;
1367 s->session->compress_meth = (comp == NULL) ? 0 : comp->id;
1369 sk_SSL_CIPHER_free(s->session->ciphers);
1370 s->session->ciphers = ciphers;
1371 if (ciphers == NULL) {
1372 al = SSL_AD_INTERNAL_ERROR;
1373 SSLerr(SSL_F_TLS_PROCESS_CLIENT_HELLO, ERR_R_INTERNAL_ERROR);
1377 if (!tls1_set_server_sigalgs(s)) {
1378 SSLerr(SSL_F_TLS_PROCESS_CLIENT_HELLO, SSL_R_CLIENTHELLO_TLSEXT);
1383 sk_SSL_CIPHER_free(ciphers);
1384 return MSG_PROCESS_CONTINUE_PROCESSING;
1386 ssl3_send_alert(s, SSL3_AL_FATAL, al);
1388 ossl_statem_set_error(s);
1390 sk_SSL_CIPHER_free(ciphers);
1391 return MSG_PROCESS_ERROR;
1395 WORK_STATE tls_post_process_client_hello(SSL *s, WORK_STATE wst)
1397 int al = SSL_AD_HANDSHAKE_FAILURE;
1398 const SSL_CIPHER *cipher;
1400 if (wst == WORK_MORE_A) {
1402 /* Let cert callback update server certificates if required */
1403 if (s->cert->cert_cb) {
1404 int rv = s->cert->cert_cb(s, s->cert->cert_cb_arg);
1406 al = SSL_AD_INTERNAL_ERROR;
1407 SSLerr(SSL_F_TLS_POST_PROCESS_CLIENT_HELLO, SSL_R_CERT_CB_ERROR);
1411 s->rwstate = SSL_X509_LOOKUP;
1414 s->rwstate = SSL_NOTHING;
1416 cipher = ssl3_choose_cipher(s, s->session->ciphers, SSL_get_ciphers(s));
1418 if (cipher == NULL) {
1419 SSLerr(SSL_F_TLS_POST_PROCESS_CLIENT_HELLO, SSL_R_NO_SHARED_CIPHER);
1422 s->s3->tmp.new_cipher = cipher;
1423 /* check whether we should disable session resumption */
1424 if (s->not_resumable_session_cb != NULL)
1425 s->session->not_resumable = s->not_resumable_session_cb(s,
1426 ((cipher->algorithm_mkey & (SSL_kDHE | SSL_kECDHE)) != 0));
1427 if (s->session->not_resumable)
1428 /* do not send a session ticket */
1429 s->tlsext_ticket_expected = 0;
1431 /* Session-id reuse */
1432 s->s3->tmp.new_cipher = s->session->cipher;
1435 if (!(s->verify_mode & SSL_VERIFY_PEER)) {
1436 if (!ssl3_digest_cached_records(s, 0)) {
1437 al = SSL_AD_INTERNAL_ERROR;
1443 * we now have the following setup.
1445 * cipher_list - our prefered list of ciphers
1446 * ciphers - the clients prefered list of ciphers
1447 * compression - basically ignored right now
1448 * ssl version is set - sslv3
1449 * s->session - The ssl session has been setup.
1450 * s->hit - session reuse flag
1451 * s->s3->tmp.new_cipher- the new cipher to use.
1454 /* Handles TLS extensions that we couldn't check earlier */
1455 if (s->version >= SSL3_VERSION) {
1456 if (ssl_check_clienthello_tlsext_late(s) <= 0) {
1457 SSLerr(SSL_F_TLS_POST_PROCESS_CLIENT_HELLO,
1458 SSL_R_CLIENTHELLO_TLSEXT);
1465 #ifndef OPENSSL_NO_SRP
1466 if (wst == WORK_MORE_B) {
1468 if ((ret = ssl_check_srp_ext_ClientHello(s, &al)) < 0) {
1470 * callback indicates further work to be done
1472 s->rwstate = SSL_X509_LOOKUP;
1475 if (ret != SSL_ERROR_NONE) {
1477 * This is not really an error but the only means to for
1478 * a client to detect whether srp is supported.
1480 if (al != TLS1_AD_UNKNOWN_PSK_IDENTITY)
1481 SSLerr(SSL_F_TLS_POST_PROCESS_CLIENT_HELLO,
1482 SSL_R_CLIENTHELLO_TLSEXT);
1489 return WORK_FINISHED_STOP;
1491 ssl3_send_alert(s, SSL3_AL_FATAL, al);
1492 ossl_statem_set_error(s);
1496 int tls_construct_server_hello(SSL *s)
1499 unsigned char *p, *d;
1504 buf = (unsigned char *)s->init_buf->data;
1506 /* Do the message type and length last */
1507 d = p = ssl_handshake_start(s);
1509 *(p++) = s->version >> 8;
1510 *(p++) = s->version & 0xff;
1513 * Random stuff. Filling of the server_random takes place in
1514 * tls_process_client_hello()
1516 memcpy(p, s->s3->server_random, SSL3_RANDOM_SIZE);
1517 p += SSL3_RANDOM_SIZE;
1520 * There are several cases for the session ID to send
1521 * back in the server hello:
1522 * - For session reuse from the session cache,
1523 * we send back the old session ID.
1524 * - If stateless session reuse (using a session ticket)
1525 * is successful, we send back the client's "session ID"
1526 * (which doesn't actually identify the session).
1527 * - If it is a new session, we send back the new
1529 * - However, if we want the new session to be single-use,
1530 * we send back a 0-length session ID.
1531 * s->hit is non-zero in either case of session reuse,
1532 * so the following won't overwrite an ID that we're supposed
1535 if (s->session->not_resumable ||
1536 (!(s->ctx->session_cache_mode & SSL_SESS_CACHE_SERVER)
1538 s->session->session_id_length = 0;
1540 sl = s->session->session_id_length;
1541 if (sl > (int)sizeof(s->session->session_id)) {
1542 SSLerr(SSL_F_TLS_CONSTRUCT_SERVER_HELLO, ERR_R_INTERNAL_ERROR);
1543 ossl_statem_set_error(s);
1547 memcpy(p, s->session->session_id, sl);
1550 /* put the cipher */
1551 i = ssl3_put_cipher_by_char(s->s3->tmp.new_cipher, p);
1554 /* put the compression method */
1555 #ifdef OPENSSL_NO_COMP
1558 if (s->s3->tmp.new_compression == NULL)
1561 *(p++) = s->s3->tmp.new_compression->id;
1564 if (ssl_prepare_serverhello_tlsext(s) <= 0) {
1565 SSLerr(SSL_F_TLS_CONSTRUCT_SERVER_HELLO, SSL_R_SERVERHELLO_TLSEXT);
1566 ossl_statem_set_error(s);
1570 ssl_add_serverhello_tlsext(s, p, buf + SSL3_RT_MAX_PLAIN_LENGTH,
1572 ssl3_send_alert(s, SSL3_AL_FATAL, al);
1573 SSLerr(SSL_F_TLS_CONSTRUCT_SERVER_HELLO, ERR_R_INTERNAL_ERROR);
1574 ossl_statem_set_error(s);
1580 if (!ssl_set_handshake_header(s, SSL3_MT_SERVER_HELLO, l)) {
1581 SSLerr(SSL_F_TLS_CONSTRUCT_SERVER_HELLO, ERR_R_INTERNAL_ERROR);
1582 ossl_statem_set_error(s);
1589 int tls_construct_server_done(SSL *s)
1591 if (!ssl_set_handshake_header(s, SSL3_MT_SERVER_DONE, 0)) {
1592 SSLerr(SSL_F_TLS_CONSTRUCT_SERVER_DONE, ERR_R_INTERNAL_ERROR);
1593 ossl_statem_set_error(s);
1597 if (!s->s3->tmp.cert_request) {
1598 if (!ssl3_digest_cached_records(s, 0)) {
1599 ossl_statem_set_error(s);
1606 int tls_construct_server_key_exchange(SSL *s)
1608 #ifndef OPENSSL_NO_DH
1609 EVP_PKEY *pkdh = NULL;
1611 #ifndef OPENSSL_NO_EC
1612 unsigned char *encodedPoint = NULL;
1617 const EVP_MD *md = NULL;
1618 unsigned char *p, *d;
1625 EVP_MD_CTX *md_ctx = EVP_MD_CTX_new();
1627 if (md_ctx == NULL) {
1628 SSLerr(SSL_F_TLS_CONSTRUCT_SERVER_KEY_EXCHANGE, ERR_R_MALLOC_FAILURE);
1629 al = SSL_AD_INTERNAL_ERROR;
1633 type = s->s3->tmp.new_cipher->algorithm_mkey;
1637 r[0] = r[1] = r[2] = r[3] = NULL;
1639 #ifndef OPENSSL_NO_PSK
1640 if (type & SSL_PSK) {
1642 * reserve size for record length and PSK identity hint
1645 if (s->cert->psk_identity_hint)
1646 n += strlen(s->cert->psk_identity_hint);
1648 /* Plain PSK or RSAPSK nothing to do */
1649 if (type & (SSL_kPSK | SSL_kRSAPSK)) {
1651 #endif /* !OPENSSL_NO_PSK */
1652 #ifndef OPENSSL_NO_DH
1653 if (type & (SSL_kDHE | SSL_kDHEPSK)) {
1654 CERT *cert = s->cert;
1656 EVP_PKEY *pkdhp = NULL;
1659 if (s->cert->dh_tmp_auto) {
1660 DH *dhp = ssl_get_auto_dh(s);
1661 pkdh = EVP_PKEY_new();
1662 if (pkdh == NULL || dhp == NULL) {
1664 al = SSL_AD_INTERNAL_ERROR;
1665 SSLerr(SSL_F_TLS_CONSTRUCT_SERVER_KEY_EXCHANGE,
1666 ERR_R_INTERNAL_ERROR);
1669 EVP_PKEY_assign_DH(pkdh, dhp);
1672 pkdhp = cert->dh_tmp;
1674 if ((pkdhp == NULL) && (s->cert->dh_tmp_cb != NULL)) {
1675 DH *dhp = s->cert->dh_tmp_cb(s, 0, 1024);
1676 pkdh = ssl_dh_to_pkey(dhp);
1678 al = SSL_AD_INTERNAL_ERROR;
1679 SSLerr(SSL_F_TLS_CONSTRUCT_SERVER_KEY_EXCHANGE,
1680 ERR_R_INTERNAL_ERROR);
1685 if (pkdhp == NULL) {
1686 al = SSL_AD_HANDSHAKE_FAILURE;
1687 SSLerr(SSL_F_TLS_CONSTRUCT_SERVER_KEY_EXCHANGE,
1688 SSL_R_MISSING_TMP_DH_KEY);
1691 if (!ssl_security(s, SSL_SECOP_TMP_DH,
1692 EVP_PKEY_security_bits(pkdhp), 0, pkdhp)) {
1693 al = SSL_AD_HANDSHAKE_FAILURE;
1694 SSLerr(SSL_F_TLS_CONSTRUCT_SERVER_KEY_EXCHANGE,
1695 SSL_R_DH_KEY_TOO_SMALL);
1698 if (s->s3->tmp.pkey != NULL) {
1699 SSLerr(SSL_F_TLS_CONSTRUCT_SERVER_KEY_EXCHANGE,
1700 ERR_R_INTERNAL_ERROR);
1704 s->s3->tmp.pkey = ssl_generate_pkey(pkdhp, NID_undef);
1706 if (s->s3->tmp.pkey == NULL) {
1707 SSLerr(SSL_F_TLS_CONSTRUCT_SERVER_KEY_EXCHANGE, ERR_R_EVP_LIB);
1711 dh = EVP_PKEY_get0_DH(s->s3->tmp.pkey);
1713 EVP_PKEY_free(pkdh);
1716 DH_get0_pqg(dh, &r[0], NULL, &r[1]);
1717 DH_get0_key(dh, &r[2], NULL);
1720 #ifndef OPENSSL_NO_EC
1721 if (type & (SSL_kECDHE | SSL_kECDHEPSK)) {
1724 if (s->s3->tmp.pkey != NULL) {
1725 SSLerr(SSL_F_TLS_CONSTRUCT_SERVER_KEY_EXCHANGE,
1726 ERR_R_INTERNAL_ERROR);
1730 /* Get NID of appropriate shared curve */
1731 nid = tls1_shared_curve(s, -2);
1732 curve_id = tls1_ec_nid2curve_id(nid);
1733 if (curve_id == 0) {
1734 SSLerr(SSL_F_TLS_CONSTRUCT_SERVER_KEY_EXCHANGE,
1735 SSL_R_UNSUPPORTED_ELLIPTIC_CURVE);
1738 s->s3->tmp.pkey = ssl_generate_pkey(NULL, nid);
1739 /* Generate a new key for this curve */
1740 if (s->s3->tmp.pkey == NULL) {
1741 al = SSL_AD_INTERNAL_ERROR;
1742 SSLerr(SSL_F_TLS_CONSTRUCT_SERVER_KEY_EXCHANGE, ERR_R_EVP_LIB);
1746 /* Encode the public key. */
1747 encodedlen = EC_KEY_key2buf(EVP_PKEY_get0_EC_KEY(s->s3->tmp.pkey),
1748 POINT_CONVERSION_UNCOMPRESSED,
1749 &encodedPoint, NULL);
1751 if (encodedlen == 0) {
1752 SSLerr(SSL_F_TLS_CONSTRUCT_SERVER_KEY_EXCHANGE, ERR_R_EC_LIB);
1757 * We only support named (not generic) curves in ECDH ephemeral key
1758 * exchanges. In this situation, we need four additional bytes to
1759 * encode the entire ServerECDHParams structure.
1761 n += 4 + encodedlen;
1764 * We'll generate the serverKeyExchange message explicitly so we
1765 * can set these to NULLs
1772 #endif /* !OPENSSL_NO_EC */
1773 #ifndef OPENSSL_NO_SRP
1774 if (type & SSL_kSRP) {
1775 if ((s->srp_ctx.N == NULL) ||
1776 (s->srp_ctx.g == NULL) ||
1777 (s->srp_ctx.s == NULL) || (s->srp_ctx.B == NULL)) {
1778 SSLerr(SSL_F_TLS_CONSTRUCT_SERVER_KEY_EXCHANGE,
1779 SSL_R_MISSING_SRP_PARAM);
1782 r[0] = s->srp_ctx.N;
1783 r[1] = s->srp_ctx.g;
1784 r[2] = s->srp_ctx.s;
1785 r[3] = s->srp_ctx.B;
1789 al = SSL_AD_HANDSHAKE_FAILURE;
1790 SSLerr(SSL_F_TLS_CONSTRUCT_SERVER_KEY_EXCHANGE,
1791 SSL_R_UNKNOWN_KEY_EXCHANGE_TYPE);
1794 for (i = 0; i < 4 && r[i] != NULL; i++) {
1795 nr[i] = BN_num_bytes(r[i]);
1796 #ifndef OPENSSL_NO_SRP
1797 if ((i == 2) && (type & SSL_kSRP))
1804 if (!(s->s3->tmp.new_cipher->algorithm_auth & (SSL_aNULL|SSL_aSRP))
1805 && !(s->s3->tmp.new_cipher->algorithm_mkey & SSL_PSK)) {
1806 if ((pkey = ssl_get_sign_pkey(s, s->s3->tmp.new_cipher, &md))
1808 al = SSL_AD_DECODE_ERROR;
1811 kn = EVP_PKEY_size(pkey);
1812 /* Allow space for signature algorithm */
1813 if (SSL_USE_SIGALGS(s))
1815 /* Allow space for signature length */
1822 if (!BUF_MEM_grow_clean(buf, n + SSL_HM_HEADER_LENGTH(s) + kn)) {
1823 SSLerr(SSL_F_TLS_CONSTRUCT_SERVER_KEY_EXCHANGE, ERR_LIB_BUF);
1826 d = p = ssl_handshake_start(s);
1828 #ifndef OPENSSL_NO_PSK
1829 if (type & SSL_PSK) {
1830 /* copy PSK identity hint */
1831 if (s->cert->psk_identity_hint) {
1832 s2n(strlen(s->cert->psk_identity_hint), p);
1833 strncpy((char *)p, s->cert->psk_identity_hint,
1834 strlen(s->cert->psk_identity_hint));
1835 p += strlen(s->cert->psk_identity_hint);
1842 for (i = 0; i < 4 && r[i] != NULL; i++) {
1843 #ifndef OPENSSL_NO_SRP
1844 if ((i == 2) && (type & SSL_kSRP)) {
1854 #ifndef OPENSSL_NO_EC
1855 if (type & (SSL_kECDHE | SSL_kECDHEPSK)) {
1857 * XXX: For now, we only support named (not generic) curves. In
1858 * this situation, the serverKeyExchange message has: [1 byte
1859 * CurveType], [2 byte CurveName] [1 byte length of encoded
1860 * point], followed by the actual encoded point itself
1862 *p = NAMED_CURVE_TYPE;
1870 memcpy(p, encodedPoint, encodedlen);
1871 OPENSSL_free(encodedPoint);
1872 encodedPoint = NULL;
1880 * n is the length of the params, they start at &(d[4]) and p
1881 * points to the space at the end.
1884 /* send signature algorithm */
1885 if (SSL_USE_SIGALGS(s)) {
1886 if (!tls12_get_sigandhash(p, pkey, md)) {
1887 /* Should never happen */
1888 al = SSL_AD_INTERNAL_ERROR;
1889 SSLerr(SSL_F_TLS_CONSTRUCT_SERVER_KEY_EXCHANGE,
1890 ERR_R_INTERNAL_ERROR);
1896 fprintf(stderr, "Using hash %s\n", EVP_MD_name(md));
1898 if (EVP_SignInit_ex(md_ctx, md, NULL) <= 0
1899 || EVP_SignUpdate(md_ctx, &(s->s3->client_random[0]),
1900 SSL3_RANDOM_SIZE) <= 0
1901 || EVP_SignUpdate(md_ctx, &(s->s3->server_random[0]),
1902 SSL3_RANDOM_SIZE) <= 0
1903 || EVP_SignUpdate(md_ctx, d, n) <= 0
1904 || EVP_SignFinal(md_ctx, &(p[2]),
1905 (unsigned int *)&i, pkey) <= 0) {
1906 SSLerr(SSL_F_TLS_CONSTRUCT_SERVER_KEY_EXCHANGE, ERR_LIB_EVP);
1907 al = SSL_AD_INTERNAL_ERROR;
1912 if (SSL_USE_SIGALGS(s))
1915 /* Is this error check actually needed? */
1916 al = SSL_AD_HANDSHAKE_FAILURE;
1917 SSLerr(SSL_F_TLS_CONSTRUCT_SERVER_KEY_EXCHANGE,
1918 SSL_R_UNKNOWN_PKEY_TYPE);
1923 if (!ssl_set_handshake_header(s, SSL3_MT_SERVER_KEY_EXCHANGE, n)) {
1924 al = SSL_AD_HANDSHAKE_FAILURE;
1925 SSLerr(SSL_F_TLS_CONSTRUCT_SERVER_KEY_EXCHANGE, ERR_R_INTERNAL_ERROR);
1929 EVP_MD_CTX_free(md_ctx);
1932 ssl3_send_alert(s, SSL3_AL_FATAL, al);
1934 #ifndef OPENSSL_NO_DH
1935 EVP_PKEY_free(pkdh);
1937 #ifndef OPENSSL_NO_EC
1938 OPENSSL_free(encodedPoint);
1940 EVP_MD_CTX_free(md_ctx);
1941 ossl_statem_set_error(s);
1945 int tls_construct_certificate_request(SSL *s)
1947 unsigned char *p, *d;
1948 int i, j, nl, off, n;
1949 STACK_OF(X509_NAME) *sk = NULL;
1955 d = p = ssl_handshake_start(s);
1957 /* get the list of acceptable cert types */
1959 n = ssl3_get_req_cert_type(s, p);
1964 if (SSL_USE_SIGALGS(s)) {
1965 const unsigned char *psigs;
1966 unsigned char *etmp = p;
1967 nl = tls12_get_psigalgs(s, &psigs);
1968 /* Skip over length for now */
1970 nl = tls12_copy_sigalgs(s, p, psigs, nl);
1971 /* Now fill in length */
1981 sk = SSL_get_client_CA_list(s);
1984 for (i = 0; i < sk_X509_NAME_num(sk); i++) {
1985 name = sk_X509_NAME_value(sk, i);
1986 j = i2d_X509_NAME(name, NULL);
1987 if (!BUF_MEM_grow_clean
1988 (buf, SSL_HM_HEADER_LENGTH(s) + n + j + 2)) {
1989 SSLerr(SSL_F_TLS_CONSTRUCT_CERTIFICATE_REQUEST,
1993 p = ssl_handshake_start(s) + n;
1995 i2d_X509_NAME(name, &p);
2000 /* else no CA names */
2001 p = ssl_handshake_start(s) + off;
2004 if (!ssl_set_handshake_header(s, SSL3_MT_CERTIFICATE_REQUEST, n)) {
2005 SSLerr(SSL_F_TLS_CONSTRUCT_CERTIFICATE_REQUEST, ERR_R_INTERNAL_ERROR);
2009 s->s3->tmp.cert_request = 1;
2013 ossl_statem_set_error(s);
2017 MSG_PROCESS_RETURN tls_process_client_key_exchange(SSL *s, PACKET *pkt)
2020 unsigned long alg_k;
2021 #ifndef OPENSSL_NO_RSA
2024 #if !defined(OPENSSL_NO_EC) || !defined(OPENSSL_NO_DH)
2025 EVP_PKEY *ckey = NULL;
2027 PACKET enc_premaster;
2028 unsigned char *rsa_decrypt = NULL;
2030 alg_k = s->s3->tmp.new_cipher->algorithm_mkey;
2032 #ifndef OPENSSL_NO_PSK
2033 /* For PSK parse and retrieve identity, obtain PSK key */
2034 if (alg_k & SSL_PSK) {
2035 unsigned char psk[PSK_MAX_PSK_LEN];
2037 PACKET psk_identity;
2039 if (!PACKET_get_length_prefixed_2(pkt, &psk_identity)) {
2040 al = SSL_AD_DECODE_ERROR;
2041 SSLerr(SSL_F_TLS_PROCESS_CLIENT_KEY_EXCHANGE, SSL_R_LENGTH_MISMATCH);
2044 if (PACKET_remaining(&psk_identity) > PSK_MAX_IDENTITY_LEN) {
2045 al = SSL_AD_DECODE_ERROR;
2046 SSLerr(SSL_F_TLS_PROCESS_CLIENT_KEY_EXCHANGE,
2047 SSL_R_DATA_LENGTH_TOO_LONG);
2050 if (s->psk_server_callback == NULL) {
2051 al = SSL_AD_INTERNAL_ERROR;
2052 SSLerr(SSL_F_TLS_PROCESS_CLIENT_KEY_EXCHANGE,
2053 SSL_R_PSK_NO_SERVER_CB);
2057 if (!PACKET_strndup(&psk_identity, &s->session->psk_identity)) {
2058 SSLerr(SSL_F_TLS_PROCESS_CLIENT_KEY_EXCHANGE, ERR_R_INTERNAL_ERROR);
2059 al = SSL_AD_INTERNAL_ERROR;
2063 psklen = s->psk_server_callback(s, s->session->psk_identity,
2066 if (psklen > PSK_MAX_PSK_LEN) {
2067 al = SSL_AD_INTERNAL_ERROR;
2068 SSLerr(SSL_F_TLS_PROCESS_CLIENT_KEY_EXCHANGE, ERR_R_INTERNAL_ERROR);
2070 } else if (psklen == 0) {
2072 * PSK related to the given identity not found
2074 SSLerr(SSL_F_TLS_PROCESS_CLIENT_KEY_EXCHANGE,
2075 SSL_R_PSK_IDENTITY_NOT_FOUND);
2076 al = SSL_AD_UNKNOWN_PSK_IDENTITY;
2080 OPENSSL_free(s->s3->tmp.psk);
2081 s->s3->tmp.psk = OPENSSL_memdup(psk, psklen);
2082 OPENSSL_cleanse(psk, psklen);
2084 if (s->s3->tmp.psk == NULL) {
2085 al = SSL_AD_INTERNAL_ERROR;
2086 SSLerr(SSL_F_TLS_PROCESS_CLIENT_KEY_EXCHANGE, ERR_R_MALLOC_FAILURE);
2090 s->s3->tmp.psklen = psklen;
2092 if (alg_k & SSL_kPSK) {
2093 /* Identity extracted earlier: should be nothing left */
2094 if (PACKET_remaining(pkt) != 0) {
2095 al = SSL_AD_HANDSHAKE_FAILURE;
2096 SSLerr(SSL_F_TLS_PROCESS_CLIENT_KEY_EXCHANGE, SSL_R_LENGTH_MISMATCH);
2099 /* PSK handled by ssl_generate_master_secret */
2100 if (!ssl_generate_master_secret(s, NULL, 0, 0)) {
2101 al = SSL_AD_INTERNAL_ERROR;
2102 SSLerr(SSL_F_TLS_PROCESS_CLIENT_KEY_EXCHANGE, ERR_R_INTERNAL_ERROR);
2107 #ifndef OPENSSL_NO_RSA
2108 if (alg_k & (SSL_kRSA | SSL_kRSAPSK)) {
2109 unsigned char rand_premaster_secret[SSL_MAX_MASTER_KEY_LENGTH];
2111 unsigned char decrypt_good, version_good;
2112 size_t j, padding_len;
2114 /* FIX THIS UP EAY EAY EAY EAY */
2115 rsa = EVP_PKEY_get0_RSA(s->cert->pkeys[SSL_PKEY_RSA_ENC].privatekey);
2117 al = SSL_AD_HANDSHAKE_FAILURE;
2118 SSLerr(SSL_F_TLS_PROCESS_CLIENT_KEY_EXCHANGE,
2119 SSL_R_MISSING_RSA_CERTIFICATE);
2123 /* SSLv3 and pre-standard DTLS omit the length bytes. */
2124 if (s->version == SSL3_VERSION || s->version == DTLS1_BAD_VER) {
2125 enc_premaster = *pkt;
2127 if (!PACKET_get_length_prefixed_2(pkt, &enc_premaster)
2128 || PACKET_remaining(pkt) != 0) {
2129 al = SSL_AD_DECODE_ERROR;
2130 SSLerr(SSL_F_TLS_PROCESS_CLIENT_KEY_EXCHANGE,
2131 SSL_R_LENGTH_MISMATCH);
2137 * We want to be sure that the plaintext buffer size makes it safe to
2138 * iterate over the entire size of a premaster secret
2139 * (SSL_MAX_MASTER_KEY_LENGTH). Reject overly short RSA keys because
2140 * their ciphertext cannot accommodate a premaster secret anyway.
2142 if (RSA_size(rsa) < SSL_MAX_MASTER_KEY_LENGTH) {
2143 al = SSL_AD_INTERNAL_ERROR;
2144 SSLerr(SSL_F_TLS_PROCESS_CLIENT_KEY_EXCHANGE,
2145 RSA_R_KEY_SIZE_TOO_SMALL);
2149 rsa_decrypt = OPENSSL_malloc(RSA_size(rsa));
2150 if (rsa_decrypt == NULL) {
2151 al = SSL_AD_INTERNAL_ERROR;
2152 SSLerr(SSL_F_TLS_PROCESS_CLIENT_KEY_EXCHANGE, ERR_R_MALLOC_FAILURE);
2157 * We must not leak whether a decryption failure occurs because of
2158 * Bleichenbacher's attack on PKCS #1 v1.5 RSA padding (see RFC 2246,
2159 * section 7.4.7.1). The code follows that advice of the TLS RFC and
2160 * generates a random premaster secret for the case that the decrypt
2161 * fails. See https://tools.ietf.org/html/rfc5246#section-7.4.7.1
2164 if (RAND_bytes(rand_premaster_secret,
2165 sizeof(rand_premaster_secret)) <= 0) {
2170 * Decrypt with no padding. PKCS#1 padding will be removed as part of
2171 * the timing-sensitive code below.
2173 decrypt_len = RSA_private_decrypt(PACKET_remaining(&enc_premaster),
2174 PACKET_data(&enc_premaster),
2175 rsa_decrypt, rsa, RSA_NO_PADDING);
2176 if (decrypt_len < 0) {
2180 /* Check the padding. See RFC 3447, section 7.2.2. */
2183 * The smallest padded premaster is 11 bytes of overhead. Small keys
2184 * are publicly invalid, so this may return immediately. This ensures
2185 * PS is at least 8 bytes.
2187 if (decrypt_len < 11 + SSL_MAX_MASTER_KEY_LENGTH) {
2188 al = SSL_AD_DECRYPT_ERROR;
2189 SSLerr(SSL_F_TLS_PROCESS_CLIENT_KEY_EXCHANGE, SSL_R_DECRYPTION_FAILED);
2193 padding_len = decrypt_len - SSL_MAX_MASTER_KEY_LENGTH;
2194 decrypt_good = constant_time_eq_int_8(rsa_decrypt[0], 0) &
2195 constant_time_eq_int_8(rsa_decrypt[1], 2);
2196 for (j = 2; j < padding_len - 1; j++) {
2197 decrypt_good &= ~constant_time_is_zero_8(rsa_decrypt[j]);
2199 decrypt_good &= constant_time_is_zero_8(rsa_decrypt[padding_len - 1]);
2202 * If the version in the decrypted pre-master secret is correct then
2203 * version_good will be 0xff, otherwise it'll be zero. The
2204 * Klima-Pokorny-Rosa extension of Bleichenbacher's attack
2205 * (http://eprint.iacr.org/2003/052/) exploits the version number
2206 * check as a "bad version oracle". Thus version checks are done in
2207 * constant time and are treated like any other decryption error.
2210 constant_time_eq_8(rsa_decrypt[padding_len],
2211 (unsigned)(s->client_version >> 8));
2213 constant_time_eq_8(rsa_decrypt[padding_len + 1],
2214 (unsigned)(s->client_version & 0xff));
2217 * The premaster secret must contain the same version number as the
2218 * ClientHello to detect version rollback attacks (strangely, the
2219 * protocol does not offer such protection for DH ciphersuites).
2220 * However, buggy clients exist that send the negotiated protocol
2221 * version instead if the server does not support the requested
2222 * protocol version. If SSL_OP_TLS_ROLLBACK_BUG is set, tolerate such
2225 if (s->options & SSL_OP_TLS_ROLLBACK_BUG) {
2226 unsigned char workaround_good;
2227 workaround_good = constant_time_eq_8(rsa_decrypt[padding_len],
2228 (unsigned)(s->version >> 8));
2230 constant_time_eq_8(rsa_decrypt[padding_len + 1],
2231 (unsigned)(s->version & 0xff));
2232 version_good |= workaround_good;
2236 * Both decryption and version must be good for decrypt_good to
2237 * remain non-zero (0xff).
2239 decrypt_good &= version_good;
2242 * Now copy rand_premaster_secret over from p using
2243 * decrypt_good_mask. If decryption failed, then p does not
2244 * contain valid plaintext, however, a check above guarantees
2245 * it is still sufficiently large to read from.
2247 for (j = 0; j < sizeof(rand_premaster_secret); j++) {
2248 rsa_decrypt[padding_len + j] =
2249 constant_time_select_8(decrypt_good,
2250 rsa_decrypt[padding_len + j],
2251 rand_premaster_secret[j]);
2254 if (!ssl_generate_master_secret(s, rsa_decrypt + padding_len,
2255 sizeof(rand_premaster_secret), 0)) {
2256 al = SSL_AD_INTERNAL_ERROR;
2257 SSLerr(SSL_F_TLS_PROCESS_CLIENT_KEY_EXCHANGE, ERR_R_INTERNAL_ERROR);
2260 OPENSSL_free(rsa_decrypt);
2264 #ifndef OPENSSL_NO_DH
2265 if (alg_k & (SSL_kDHE | SSL_kDHEPSK)) {
2266 EVP_PKEY *skey = NULL;
2270 const unsigned char *data;
2272 if (!PACKET_get_net_2(pkt, &i)) {
2273 if (alg_k & (SSL_kDHE | SSL_kDHEPSK)) {
2274 al = SSL_AD_HANDSHAKE_FAILURE;
2275 SSLerr(SSL_F_TLS_PROCESS_CLIENT_KEY_EXCHANGE,
2276 SSL_R_DH_PUBLIC_VALUE_LENGTH_IS_WRONG);
2281 if (PACKET_remaining(pkt) != i) {
2282 SSLerr(SSL_F_TLS_PROCESS_CLIENT_KEY_EXCHANGE,
2283 SSL_R_DH_PUBLIC_VALUE_LENGTH_IS_WRONG);
2286 skey = s->s3->tmp.pkey;
2288 al = SSL_AD_HANDSHAKE_FAILURE;
2289 SSLerr(SSL_F_TLS_PROCESS_CLIENT_KEY_EXCHANGE,
2290 SSL_R_MISSING_TMP_DH_KEY);
2294 if (PACKET_remaining(pkt) == 0L) {
2295 al = SSL_AD_HANDSHAKE_FAILURE;
2296 SSLerr(SSL_F_TLS_PROCESS_CLIENT_KEY_EXCHANGE,
2297 SSL_R_MISSING_TMP_DH_KEY);
2300 if (!PACKET_get_bytes(pkt, &data, i)) {
2301 /* We already checked we have enough data */
2302 al = SSL_AD_INTERNAL_ERROR;
2303 SSLerr(SSL_F_TLS_PROCESS_CLIENT_KEY_EXCHANGE,
2304 ERR_R_INTERNAL_ERROR);
2307 ckey = EVP_PKEY_new();
2308 if (ckey == NULL || EVP_PKEY_copy_parameters(ckey, skey) == 0) {
2309 SSLerr(SSL_F_TLS_PROCESS_CLIENT_KEY_EXCHANGE, SSL_R_BN_LIB);
2312 cdh = EVP_PKEY_get0_DH(ckey);
2313 pub_key = BN_bin2bn(data, i, NULL);
2315 if (pub_key == NULL || !DH_set0_key(cdh, pub_key, NULL)) {
2316 SSLerr(SSL_F_TLS_PROCESS_CLIENT_KEY_EXCHANGE, ERR_R_INTERNAL_ERROR);
2317 if (pub_key != NULL)
2322 if (ssl_derive(s, skey, ckey) == 0) {
2323 al = SSL_AD_INTERNAL_ERROR;
2324 SSLerr(SSL_F_TLS_PROCESS_CLIENT_KEY_EXCHANGE, ERR_R_INTERNAL_ERROR);
2328 EVP_PKEY_free(ckey);
2330 EVP_PKEY_free(s->s3->tmp.pkey);
2331 s->s3->tmp.pkey = NULL;
2336 #ifndef OPENSSL_NO_EC
2337 if (alg_k & (SSL_kECDHE | SSL_kECDHEPSK)) {
2338 EVP_PKEY *skey = s->s3->tmp.pkey;
2340 if (PACKET_remaining(pkt) == 0L) {
2341 /* We don't support ECDH client auth */
2342 al = SSL_AD_HANDSHAKE_FAILURE;
2343 SSLerr(SSL_F_TLS_PROCESS_CLIENT_KEY_EXCHANGE,
2344 SSL_R_MISSING_TMP_ECDH_KEY);
2348 const unsigned char *data;
2351 * Get client's public key from encoded point in the
2352 * ClientKeyExchange message.
2355 /* Get encoded point length */
2356 if (!PACKET_get_1(pkt, &i)) {
2357 al = SSL_AD_DECODE_ERROR;
2358 SSLerr(SSL_F_TLS_PROCESS_CLIENT_KEY_EXCHANGE,
2359 SSL_R_LENGTH_MISMATCH);
2362 if (!PACKET_get_bytes(pkt, &data, i)
2363 || PACKET_remaining(pkt) != 0) {
2364 SSLerr(SSL_F_TLS_PROCESS_CLIENT_KEY_EXCHANGE, ERR_R_EC_LIB);
2367 ckey = EVP_PKEY_new();
2368 if (ckey == NULL || EVP_PKEY_copy_parameters(ckey, skey) <= 0) {
2369 SSLerr(SSL_F_TLS_PROCESS_CLIENT_KEY_EXCHANGE, ERR_R_EVP_LIB);
2372 if (EC_KEY_oct2key(EVP_PKEY_get0_EC_KEY(ckey), data, i,
2374 SSLerr(SSL_F_TLS_PROCESS_CLIENT_KEY_EXCHANGE, ERR_R_EC_LIB);
2379 if (ssl_derive(s, skey, ckey) == 0) {
2380 al = SSL_AD_INTERNAL_ERROR;
2381 SSLerr(SSL_F_TLS_PROCESS_CLIENT_KEY_EXCHANGE, ERR_R_INTERNAL_ERROR);
2385 EVP_PKEY_free(ckey);
2387 EVP_PKEY_free(s->s3->tmp.pkey);
2388 s->s3->tmp.pkey = NULL;
2390 return MSG_PROCESS_CONTINUE_PROCESSING;
2393 #ifndef OPENSSL_NO_SRP
2394 if (alg_k & SSL_kSRP) {
2396 const unsigned char *data;
2398 if (!PACKET_get_net_2(pkt, &i)
2399 || !PACKET_get_bytes(pkt, &data, i)) {
2400 al = SSL_AD_DECODE_ERROR;
2401 SSLerr(SSL_F_TLS_PROCESS_CLIENT_KEY_EXCHANGE, SSL_R_BAD_SRP_A_LENGTH);
2404 if ((s->srp_ctx.A = BN_bin2bn(data, i, NULL)) == NULL) {
2405 SSLerr(SSL_F_TLS_PROCESS_CLIENT_KEY_EXCHANGE, ERR_R_BN_LIB);
2408 if (BN_ucmp(s->srp_ctx.A, s->srp_ctx.N) >= 0
2409 || BN_is_zero(s->srp_ctx.A)) {
2410 al = SSL_AD_ILLEGAL_PARAMETER;
2411 SSLerr(SSL_F_TLS_PROCESS_CLIENT_KEY_EXCHANGE,
2412 SSL_R_BAD_SRP_PARAMETERS);
2415 OPENSSL_free(s->session->srp_username);
2416 s->session->srp_username = OPENSSL_strdup(s->srp_ctx.login);
2417 if (s->session->srp_username == NULL) {
2418 SSLerr(SSL_F_TLS_PROCESS_CLIENT_KEY_EXCHANGE, ERR_R_MALLOC_FAILURE);
2422 if (!srp_generate_server_master_secret(s)) {
2423 SSLerr(SSL_F_TLS_PROCESS_CLIENT_KEY_EXCHANGE, ERR_R_INTERNAL_ERROR);
2427 #endif /* OPENSSL_NO_SRP */
2428 #ifndef OPENSSL_NO_GOST
2429 if (alg_k & SSL_kGOST) {
2430 EVP_PKEY_CTX *pkey_ctx;
2431 EVP_PKEY *client_pub_pkey = NULL, *pk = NULL;
2432 unsigned char premaster_secret[32];
2433 const unsigned char *start;
2434 size_t outlen = 32, inlen;
2435 unsigned long alg_a;
2439 const unsigned char *data;
2441 /* Get our certificate private key */
2442 alg_a = s->s3->tmp.new_cipher->algorithm_auth;
2443 if (alg_a & SSL_aGOST12) {
2445 * New GOST ciphersuites have SSL_aGOST01 bit too
2447 pk = s->cert->pkeys[SSL_PKEY_GOST12_512].privatekey;
2449 pk = s->cert->pkeys[SSL_PKEY_GOST12_256].privatekey;
2452 pk = s->cert->pkeys[SSL_PKEY_GOST01].privatekey;
2454 } else if (alg_a & SSL_aGOST01) {
2455 pk = s->cert->pkeys[SSL_PKEY_GOST01].privatekey;
2458 pkey_ctx = EVP_PKEY_CTX_new(pk, NULL);
2459 if (pkey_ctx == NULL) {
2460 al = SSL_AD_INTERNAL_ERROR;
2461 SSLerr(SSL_F_TLS_PROCESS_CLIENT_KEY_EXCHANGE, ERR_R_MALLOC_FAILURE);
2464 if (EVP_PKEY_decrypt_init(pkey_ctx) <= 0) {
2465 al = SSL_AD_INTERNAL_ERROR;
2466 SSLerr(SSL_F_TLS_PROCESS_CLIENT_KEY_EXCHANGE, ERR_R_INTERNAL_ERROR);
2470 * If client certificate is present and is of the same type, maybe
2471 * use it for key exchange. Don't mind errors from
2472 * EVP_PKEY_derive_set_peer, because it is completely valid to use a
2473 * client certificate for authorization only.
2475 client_pub_pkey = X509_get0_pubkey(s->session->peer);
2476 if (client_pub_pkey) {
2477 if (EVP_PKEY_derive_set_peer(pkey_ctx, client_pub_pkey) <= 0)
2480 /* Decrypt session key */
2481 sess_key_len = PACKET_remaining(pkt);
2482 if (!PACKET_get_bytes(pkt, &data, sess_key_len)) {
2483 al = SSL_AD_INTERNAL_ERROR;
2484 SSLerr(SSL_F_TLS_PROCESS_CLIENT_KEY_EXCHANGE, ERR_R_INTERNAL_ERROR);
2487 if (ASN1_get_object ((const unsigned char **)&data, &Tlen, &Ttag,
2488 &Tclass, sess_key_len) != V_ASN1_CONSTRUCTED
2489 || Ttag != V_ASN1_SEQUENCE
2490 || Tclass != V_ASN1_UNIVERSAL) {
2491 al = SSL_AD_DECODE_ERROR;
2492 SSLerr(SSL_F_TLS_PROCESS_CLIENT_KEY_EXCHANGE,
2493 SSL_R_DECRYPTION_FAILED);
2498 if (EVP_PKEY_decrypt
2499 (pkey_ctx, premaster_secret, &outlen, start, inlen) <= 0) {
2500 al = SSL_AD_DECODE_ERROR;
2501 SSLerr(SSL_F_TLS_PROCESS_CLIENT_KEY_EXCHANGE,
2502 SSL_R_DECRYPTION_FAILED);
2505 /* Generate master secret */
2506 if (!ssl_generate_master_secret(s, premaster_secret,
2507 sizeof(premaster_secret), 0)) {
2508 al = SSL_AD_INTERNAL_ERROR;
2509 SSLerr(SSL_F_TLS_PROCESS_CLIENT_KEY_EXCHANGE, ERR_R_INTERNAL_ERROR);
2512 /* Check if pubkey from client certificate was used */
2513 if (EVP_PKEY_CTX_ctrl
2514 (pkey_ctx, -1, -1, EVP_PKEY_CTRL_PEER_KEY, 2, NULL) > 0)
2515 s->statem.no_cert_verify = 1;
2517 EVP_PKEY_CTX_free(pkey_ctx);
2518 return MSG_PROCESS_CONTINUE_PROCESSING;
2520 EVP_PKEY_CTX_free(pkey_ctx);
2525 al = SSL_AD_HANDSHAKE_FAILURE;
2526 SSLerr(SSL_F_TLS_PROCESS_CLIENT_KEY_EXCHANGE, SSL_R_UNKNOWN_CIPHER_TYPE);
2530 return MSG_PROCESS_CONTINUE_PROCESSING;
2532 ssl3_send_alert(s, SSL3_AL_FATAL, al);
2533 #if !defined(OPENSSL_NO_DH) || !defined(OPENSSL_NO_RSA) || !defined(OPENSSL_NO_EC) || defined(OPENSSL_NO_SRP)
2536 #if !defined(OPENSSL_NO_EC) || !defined(OPENSSL_NO_DH)
2537 EVP_PKEY_free(ckey);
2539 OPENSSL_free(rsa_decrypt);
2540 #ifndef OPENSSL_NO_PSK
2541 OPENSSL_clear_free(s->s3->tmp.psk, s->s3->tmp.psklen);
2542 s->s3->tmp.psk = NULL;
2544 ossl_statem_set_error(s);
2545 return MSG_PROCESS_ERROR;
2548 WORK_STATE tls_post_process_client_key_exchange(SSL *s, WORK_STATE wst)
2550 #ifndef OPENSSL_NO_SCTP
2551 if (wst == WORK_MORE_A) {
2552 if (SSL_IS_DTLS(s)) {
2553 unsigned char sctpauthkey[64];
2554 char labelbuffer[sizeof(DTLS1_SCTP_AUTH_LABEL)];
2556 * Add new shared key for SCTP-Auth, will be ignored if no SCTP
2559 memcpy(labelbuffer, DTLS1_SCTP_AUTH_LABEL,
2560 sizeof(DTLS1_SCTP_AUTH_LABEL));
2562 if (SSL_export_keying_material(s, sctpauthkey,
2563 sizeof(sctpauthkey), labelbuffer,
2564 sizeof(labelbuffer), NULL, 0, 0) <= 0) {
2565 ossl_statem_set_error(s);
2569 BIO_ctrl(SSL_get_wbio(s), BIO_CTRL_DGRAM_SCTP_ADD_AUTH_KEY,
2570 sizeof(sctpauthkey), sctpauthkey);
2575 if ((wst == WORK_MORE_B)
2577 && BIO_dgram_is_sctp(SSL_get_wbio(s))
2578 /* Are we renegotiating? */
2580 /* Are we going to skip the CertificateVerify? */
2581 && (s->session->peer == NULL || s->statem.no_cert_verify)
2582 && BIO_dgram_sctp_msg_waiting(SSL_get_rbio(s))) {
2583 s->s3->in_read_app_data = 2;
2584 s->rwstate = SSL_READING;
2585 BIO_clear_retry_flags(SSL_get_rbio(s));
2586 BIO_set_retry_read(SSL_get_rbio(s));
2587 ossl_statem_set_sctp_read_sock(s, 1);
2590 ossl_statem_set_sctp_read_sock(s, 0);
2594 if (s->statem.no_cert_verify || !s->session->peer) {
2595 /* No certificate verify or no peer certificate so we no longer need the
2598 if (!ssl3_digest_cached_records(s, 0)) {
2599 ossl_statem_set_error(s);
2602 return WORK_FINISHED_CONTINUE;
2604 if (!s->s3->handshake_buffer) {
2605 SSLerr(SSL_F_TLS_POST_PROCESS_CLIENT_KEY_EXCHANGE,
2606 ERR_R_INTERNAL_ERROR);
2607 ossl_statem_set_error(s);
2611 * For sigalgs freeze the handshake buffer. If we support
2612 * extms we've done this already so this is a no-op
2614 if (!ssl3_digest_cached_records(s, 1)) {
2615 ossl_statem_set_error(s);
2620 return WORK_FINISHED_CONTINUE;
2623 MSG_PROCESS_RETURN tls_process_cert_verify(SSL *s, PACKET *pkt)
2625 EVP_PKEY *pkey = NULL;
2626 const unsigned char *sig, *data;
2627 #ifndef OPENSSL_NO_GOST
2628 unsigned char *gost_data = NULL;
2630 int al, ret = MSG_PROCESS_ERROR;
2634 const EVP_MD *md = NULL;
2638 EVP_MD_CTX *mctx = EVP_MD_CTX_new();
2641 SSLerr(SSL_F_TLS_PROCESS_CERT_VERIFY, ERR_R_MALLOC_FAILURE);
2642 al = SSL_AD_INTERNAL_ERROR;
2646 peer = s->session->peer;
2647 pkey = X509_get0_pubkey(peer);
2648 type = X509_certificate_type(peer, pkey);
2650 if (!(type & EVP_PKT_SIGN)) {
2651 SSLerr(SSL_F_TLS_PROCESS_CERT_VERIFY,
2652 SSL_R_SIGNATURE_FOR_NON_SIGNING_CERTIFICATE);
2653 al = SSL_AD_ILLEGAL_PARAMETER;
2657 /* Check for broken implementations of GOST ciphersuites */
2659 * If key is GOST and n is exactly 64, it is bare signature without
2660 * length field (CryptoPro implementations at least till CSP 4.0)
2662 #ifndef OPENSSL_NO_GOST
2663 if (PACKET_remaining(pkt) == 64
2664 && EVP_PKEY_id(pkey) == NID_id_GostR3410_2001) {
2669 if (SSL_USE_SIGALGS(s)) {
2672 if (!PACKET_get_bytes(pkt, &sig, 2)) {
2673 al = SSL_AD_DECODE_ERROR;
2676 rv = tls12_check_peer_sigalg(&md, s, sig, pkey);
2678 al = SSL_AD_INTERNAL_ERROR;
2680 } else if (rv == 0) {
2681 al = SSL_AD_DECODE_ERROR;
2685 fprintf(stderr, "USING TLSv1.2 HASH %s\n", EVP_MD_name(md));
2688 /* Use default digest for this key type */
2689 int idx = ssl_cert_type(NULL, pkey);
2691 md = s->s3->tmp.md[idx];
2693 al = SSL_AD_INTERNAL_ERROR;
2698 if (!PACKET_get_net_2(pkt, &len)) {
2699 SSLerr(SSL_F_TLS_PROCESS_CERT_VERIFY, SSL_R_LENGTH_MISMATCH);
2700 al = SSL_AD_DECODE_ERROR;
2704 j = EVP_PKEY_size(pkey);
2705 if (((int)len > j) || ((int)PACKET_remaining(pkt) > j)
2706 || (PACKET_remaining(pkt) == 0)) {
2707 SSLerr(SSL_F_TLS_PROCESS_CERT_VERIFY, SSL_R_WRONG_SIGNATURE_SIZE);
2708 al = SSL_AD_DECODE_ERROR;
2711 if (!PACKET_get_bytes(pkt, &data, len)) {
2712 SSLerr(SSL_F_TLS_PROCESS_CERT_VERIFY, SSL_R_LENGTH_MISMATCH);
2713 al = SSL_AD_DECODE_ERROR;
2717 hdatalen = BIO_get_mem_data(s->s3->handshake_buffer, &hdata);
2718 if (hdatalen <= 0) {
2719 SSLerr(SSL_F_TLS_PROCESS_CERT_VERIFY, ERR_R_INTERNAL_ERROR);
2720 al = SSL_AD_INTERNAL_ERROR;
2724 fprintf(stderr, "Using client verify alg %s\n", EVP_MD_name(md));
2726 if (!EVP_VerifyInit_ex(mctx, md, NULL)
2727 || !EVP_VerifyUpdate(mctx, hdata, hdatalen)) {
2728 SSLerr(SSL_F_TLS_PROCESS_CERT_VERIFY, ERR_R_EVP_LIB);
2729 al = SSL_AD_INTERNAL_ERROR;
2733 #ifndef OPENSSL_NO_GOST
2735 int pktype = EVP_PKEY_id(pkey);
2736 if (pktype == NID_id_GostR3410_2001
2737 || pktype == NID_id_GostR3410_2012_256
2738 || pktype == NID_id_GostR3410_2012_512) {
2739 if ((gost_data = OPENSSL_malloc(len)) == NULL) {
2740 SSLerr(SSL_F_TLS_PROCESS_CERT_VERIFY, ERR_R_MALLOC_FAILURE);
2741 al = SSL_AD_INTERNAL_ERROR;
2744 BUF_reverse(gost_data, data, len);
2750 if (s->version == SSL3_VERSION
2751 && !EVP_MD_CTX_ctrl(mctx, EVP_CTRL_SSL3_MASTER_SECRET,
2752 s->session->master_key_length,
2753 s->session->master_key)) {
2754 SSLerr(SSL_F_TLS_PROCESS_CERT_VERIFY, ERR_R_EVP_LIB);
2755 al = SSL_AD_INTERNAL_ERROR;
2759 if (EVP_VerifyFinal(mctx, data, len, pkey) <= 0) {
2760 al = SSL_AD_DECRYPT_ERROR;
2761 SSLerr(SSL_F_TLS_PROCESS_CERT_VERIFY, SSL_R_BAD_SIGNATURE);
2765 ret = MSG_PROCESS_CONTINUE_PROCESSING;
2768 ssl3_send_alert(s, SSL3_AL_FATAL, al);
2769 ossl_statem_set_error(s);
2771 BIO_free(s->s3->handshake_buffer);
2772 s->s3->handshake_buffer = NULL;
2773 EVP_MD_CTX_free(mctx);
2774 #ifndef OPENSSL_NO_GOST
2775 OPENSSL_free(gost_data);
2780 MSG_PROCESS_RETURN tls_process_client_certificate(SSL *s, PACKET *pkt)
2782 int i, al = SSL_AD_INTERNAL_ERROR, ret = MSG_PROCESS_ERROR;
2784 unsigned long l, llen;
2785 const unsigned char *certstart, *certbytes;
2786 STACK_OF(X509) *sk = NULL;
2789 if ((sk = sk_X509_new_null()) == NULL) {
2790 SSLerr(SSL_F_TLS_PROCESS_CLIENT_CERTIFICATE, ERR_R_MALLOC_FAILURE);
2794 if (!PACKET_get_net_3(pkt, &llen)
2795 || !PACKET_get_sub_packet(pkt, &spkt, llen)
2796 || PACKET_remaining(pkt) != 0) {
2797 al = SSL_AD_DECODE_ERROR;
2798 SSLerr(SSL_F_TLS_PROCESS_CLIENT_CERTIFICATE, SSL_R_LENGTH_MISMATCH);
2802 while (PACKET_remaining(&spkt) > 0) {
2803 if (!PACKET_get_net_3(&spkt, &l)
2804 || !PACKET_get_bytes(&spkt, &certbytes, l)) {
2805 al = SSL_AD_DECODE_ERROR;
2806 SSLerr(SSL_F_TLS_PROCESS_CLIENT_CERTIFICATE,
2807 SSL_R_CERT_LENGTH_MISMATCH);
2811 certstart = certbytes;
2812 x = d2i_X509(NULL, (const unsigned char **)&certbytes, l);
2814 SSLerr(SSL_F_TLS_PROCESS_CLIENT_CERTIFICATE, ERR_R_ASN1_LIB);
2817 if (certbytes != (certstart + l)) {
2818 al = SSL_AD_DECODE_ERROR;
2819 SSLerr(SSL_F_TLS_PROCESS_CLIENT_CERTIFICATE,
2820 SSL_R_CERT_LENGTH_MISMATCH);
2823 if (!sk_X509_push(sk, x)) {
2824 SSLerr(SSL_F_TLS_PROCESS_CLIENT_CERTIFICATE, ERR_R_MALLOC_FAILURE);
2830 if (sk_X509_num(sk) <= 0) {
2831 /* TLS does not mind 0 certs returned */
2832 if (s->version == SSL3_VERSION) {
2833 al = SSL_AD_HANDSHAKE_FAILURE;
2834 SSLerr(SSL_F_TLS_PROCESS_CLIENT_CERTIFICATE,
2835 SSL_R_NO_CERTIFICATES_RETURNED);
2838 /* Fail for TLS only if we required a certificate */
2839 else if ((s->verify_mode & SSL_VERIFY_PEER) &&
2840 (s->verify_mode & SSL_VERIFY_FAIL_IF_NO_PEER_CERT)) {
2841 SSLerr(SSL_F_TLS_PROCESS_CLIENT_CERTIFICATE,
2842 SSL_R_PEER_DID_NOT_RETURN_A_CERTIFICATE);
2843 al = SSL_AD_HANDSHAKE_FAILURE;
2846 /* No client certificate so digest cached records */
2847 if (s->s3->handshake_buffer && !ssl3_digest_cached_records(s, 0)) {
2852 i = ssl_verify_cert_chain(s, sk);
2854 al = ssl_verify_alarm_type(s->verify_result);
2855 SSLerr(SSL_F_TLS_PROCESS_CLIENT_CERTIFICATE,
2856 SSL_R_CERTIFICATE_VERIFY_FAILED);
2860 SSLerr(SSL_F_TLS_PROCESS_CLIENT_CERTIFICATE, i);
2861 al = SSL_AD_HANDSHAKE_FAILURE;
2864 pkey = X509_get0_pubkey(sk_X509_value(sk, 0));
2866 al = SSL3_AD_HANDSHAKE_FAILURE;
2867 SSLerr(SSL_F_TLS_PROCESS_CLIENT_CERTIFICATE,
2868 SSL_R_UNKNOWN_CERTIFICATE_TYPE);
2873 X509_free(s->session->peer);
2874 s->session->peer = sk_X509_shift(sk);
2875 s->session->verify_result = s->verify_result;
2877 sk_X509_pop_free(s->session->peer_chain, X509_free);
2878 s->session->peer_chain = sk;
2880 * Inconsistency alert: cert_chain does *not* include the peer's own
2881 * certificate, while we do include it in statem_clnt.c
2884 ret = MSG_PROCESS_CONTINUE_READING;
2888 ssl3_send_alert(s, SSL3_AL_FATAL, al);
2889 ossl_statem_set_error(s);
2892 sk_X509_pop_free(sk, X509_free);
2896 int tls_construct_server_certificate(SSL *s)
2900 cpk = ssl_get_server_send_pkey(s);
2902 SSLerr(SSL_F_TLS_CONSTRUCT_SERVER_CERTIFICATE, ERR_R_INTERNAL_ERROR);
2903 ossl_statem_set_error(s);
2907 if (!ssl3_output_cert_chain(s, cpk)) {
2908 SSLerr(SSL_F_TLS_CONSTRUCT_SERVER_CERTIFICATE, ERR_R_INTERNAL_ERROR);
2909 ossl_statem_set_error(s);
2916 int tls_construct_new_session_ticket(SSL *s)
2918 unsigned char *senc = NULL;
2919 EVP_CIPHER_CTX *ctx;
2920 HMAC_CTX *hctx = NULL;
2921 unsigned char *p, *macstart;
2922 const unsigned char *const_p;
2923 int len, slen_full, slen;
2926 SSL_CTX *tctx = s->initial_ctx;
2927 unsigned char iv[EVP_MAX_IV_LENGTH];
2928 unsigned char key_name[TLSEXT_KEYNAME_LENGTH];
2931 /* get session encoding length */
2932 slen_full = i2d_SSL_SESSION(s->session, NULL);
2934 * Some length values are 16 bits, so forget it if session is too
2937 if (slen_full == 0 || slen_full > 0xFF00) {
2938 ossl_statem_set_error(s);
2941 senc = OPENSSL_malloc(slen_full);
2943 ossl_statem_set_error(s);
2947 ctx = EVP_CIPHER_CTX_new();
2948 hctx = HMAC_CTX_new();
2951 if (!i2d_SSL_SESSION(s->session, &p))
2955 * create a fresh copy (not shared with other threads) to clean up
2958 sess = d2i_SSL_SESSION(NULL, &const_p, slen_full);
2961 sess->session_id_length = 0; /* ID is irrelevant for the ticket */
2963 slen = i2d_SSL_SESSION(sess, NULL);
2964 if (slen == 0 || slen > slen_full) { /* shouldn't ever happen */
2965 SSL_SESSION_free(sess);
2969 if (!i2d_SSL_SESSION(sess, &p)) {
2970 SSL_SESSION_free(sess);
2973 SSL_SESSION_free(sess);
2976 * Grow buffer if need be: the length calculation is as
2977 * follows handshake_header_length +
2978 * 4 (ticket lifetime hint) + 2 (ticket length) +
2979 * sizeof(keyname) + max_iv_len (iv length) +
2980 * max_enc_block_size (max encrypted session * length) +
2981 * max_md_size (HMAC) + session_length.
2983 if (!BUF_MEM_grow(s->init_buf,
2984 SSL_HM_HEADER_LENGTH(s) + 6 + sizeof(key_name) +
2985 EVP_MAX_IV_LENGTH + EVP_MAX_BLOCK_LENGTH +
2986 EVP_MAX_MD_SIZE + slen))
2989 p = ssl_handshake_start(s);
2991 * Initialize HMAC and cipher contexts. If callback present it does
2992 * all the work otherwise use generated values from parent ctx.
2994 if (tctx->tlsext_ticket_key_cb) {
2995 /* if 0 is returned, write an empty ticket */
2996 int ret = tctx->tlsext_ticket_key_cb(s, key_name, iv, ctx,
3000 l2n(0, p); /* timeout */
3001 s2n(0, p); /* length */
3002 if (!ssl_set_handshake_header(s, SSL3_MT_NEWSESSION_TICKET, p - ssl_handshake_start(s)))
3005 EVP_CIPHER_CTX_free(ctx);
3006 HMAC_CTX_free(hctx);
3011 iv_len = EVP_CIPHER_CTX_iv_length(ctx);
3013 const EVP_CIPHER *cipher = EVP_aes_256_cbc();
3015 iv_len = EVP_CIPHER_iv_length(cipher);
3016 if (RAND_bytes(iv, iv_len) <= 0)
3018 if (!EVP_EncryptInit_ex(ctx, cipher, NULL,
3019 tctx->tlsext_tick_aes_key, iv))
3021 if (!HMAC_Init_ex(hctx, tctx->tlsext_tick_hmac_key,
3022 sizeof(tctx->tlsext_tick_hmac_key),
3023 EVP_sha256(), NULL))
3025 memcpy(key_name, tctx->tlsext_tick_key_name,
3026 sizeof(tctx->tlsext_tick_key_name));
3030 * Ticket lifetime hint (advisory only): We leave this unspecified
3031 * for resumed session (for simplicity), and guess that tickets for
3032 * new sessions will live as long as their sessions.
3034 l2n(s->hit ? 0 : s->session->timeout, p);
3036 /* Skip ticket length for now */
3038 /* Output key name */
3040 memcpy(p, key_name, sizeof(key_name));
3041 p += sizeof(key_name);
3043 memcpy(p, iv, iv_len);
3045 /* Encrypt session data */
3046 if (!EVP_EncryptUpdate(ctx, p, &len, senc, slen))
3049 if (!EVP_EncryptFinal(ctx, p, &len))
3053 if (!HMAC_Update(hctx, macstart, p - macstart))
3055 if (!HMAC_Final(hctx, p, &hlen))
3058 EVP_CIPHER_CTX_free(ctx);
3059 HMAC_CTX_free(hctx);
3064 /* Now write out lengths: p points to end of data written */
3066 len = p - ssl_handshake_start(s);
3067 /* Skip ticket lifetime hint */
3068 p = ssl_handshake_start(s) + 4;
3070 if (!ssl_set_handshake_header(s, SSL3_MT_NEWSESSION_TICKET, len))
3077 EVP_CIPHER_CTX_free(ctx);
3078 HMAC_CTX_free(hctx);
3079 ossl_statem_set_error(s);
3083 int tls_construct_cert_status(SSL *s)
3087 * Grow buffer if need be: the length calculation is as
3088 * follows 1 (message type) + 3 (message length) +
3089 * 1 (ocsp response type) + 3 (ocsp response length)
3092 if (!BUF_MEM_grow(s->init_buf, 8 + s->tlsext_ocsp_resplen)) {
3093 ossl_statem_set_error(s);
3097 p = (unsigned char *)s->init_buf->data;
3100 *(p++) = SSL3_MT_CERTIFICATE_STATUS;
3101 /* message length */
3102 l2n3(s->tlsext_ocsp_resplen + 4, p);
3104 *(p++) = s->tlsext_status_type;
3105 /* length of OCSP response */
3106 l2n3(s->tlsext_ocsp_resplen, p);
3107 /* actual response */
3108 memcpy(p, s->tlsext_ocsp_resp, s->tlsext_ocsp_resplen);
3109 /* number of bytes to write */
3110 s->init_num = 8 + s->tlsext_ocsp_resplen;
3116 #ifndef OPENSSL_NO_NEXTPROTONEG
3118 * tls_process_next_proto reads a Next Protocol Negotiation handshake message.
3119 * It sets the next_proto member in s if found
3121 MSG_PROCESS_RETURN tls_process_next_proto(SSL *s, PACKET *pkt)
3123 PACKET next_proto, padding;
3124 size_t next_proto_len;
3127 * The payload looks like:
3129 * uint8 proto[proto_len];
3130 * uint8 padding_len;
3131 * uint8 padding[padding_len];
3133 if (!PACKET_get_length_prefixed_1(pkt, &next_proto)
3134 || !PACKET_get_length_prefixed_1(pkt, &padding)
3135 || PACKET_remaining(pkt) > 0) {
3136 SSLerr(SSL_F_TLS_PROCESS_NEXT_PROTO, SSL_R_LENGTH_MISMATCH);
3140 if (!PACKET_memdup(&next_proto, &s->next_proto_negotiated,
3142 s->next_proto_negotiated_len = 0;
3146 s->next_proto_negotiated_len = (unsigned char)next_proto_len;
3148 return MSG_PROCESS_CONTINUE_READING;
3150 ossl_statem_set_error(s);
3151 return MSG_PROCESS_ERROR;
3155 #define SSLV2_CIPHER_LEN 3
3157 STACK_OF(SSL_CIPHER) *ssl_bytes_to_cipher_list(SSL *s,
3158 PACKET *cipher_suites,
3159 STACK_OF(SSL_CIPHER) **skp,
3160 int sslv2format, int *al
3163 const SSL_CIPHER *c;
3164 STACK_OF(SSL_CIPHER) *sk;
3166 /* 3 = SSLV2_CIPHER_LEN > TLS_CIPHER_LEN = 2. */
3167 unsigned char cipher[SSLV2_CIPHER_LEN];
3169 s->s3->send_connection_binding = 0;
3171 n = sslv2format ? SSLV2_CIPHER_LEN : TLS_CIPHER_LEN;
3173 if (PACKET_remaining(cipher_suites) == 0) {
3174 SSLerr(SSL_F_SSL_BYTES_TO_CIPHER_LIST, SSL_R_NO_CIPHERS_SPECIFIED);
3175 *al = SSL_AD_ILLEGAL_PARAMETER;
3179 if (PACKET_remaining(cipher_suites) % n != 0) {
3180 SSLerr(SSL_F_SSL_BYTES_TO_CIPHER_LIST,
3181 SSL_R_ERROR_IN_RECEIVED_CIPHER_LIST);
3182 *al = SSL_AD_DECODE_ERROR;
3186 if ((skp == NULL) || (*skp == NULL)) {
3187 sk = sk_SSL_CIPHER_new_null(); /* change perhaps later */
3189 SSLerr(SSL_F_SSL_BYTES_TO_CIPHER_LIST, ERR_R_MALLOC_FAILURE);
3190 *al = SSL_AD_INTERNAL_ERROR;
3195 sk_SSL_CIPHER_zero(sk);
3198 if (!PACKET_memdup(cipher_suites, &s->s3->tmp.ciphers_raw,
3199 &s->s3->tmp.ciphers_rawlen)) {
3200 *al = SSL_AD_INTERNAL_ERROR;
3204 while (PACKET_copy_bytes(cipher_suites, cipher, n)) {
3206 * SSLv3 ciphers wrapped in an SSLv2-compatible ClientHello have the
3207 * first byte set to zero, while true SSLv2 ciphers have a non-zero
3208 * first byte. We don't support any true SSLv2 ciphers, so skip them.
3210 if (sslv2format && cipher[0] != '\0')
3213 /* Check for TLS_EMPTY_RENEGOTIATION_INFO_SCSV */
3214 if ((cipher[n - 2] == ((SSL3_CK_SCSV >> 8) & 0xff)) &&
3215 (cipher[n - 1] == (SSL3_CK_SCSV & 0xff))) {
3216 /* SCSV fatal if renegotiating */
3217 if (s->renegotiate) {
3218 SSLerr(SSL_F_SSL_BYTES_TO_CIPHER_LIST,
3219 SSL_R_SCSV_RECEIVED_WHEN_RENEGOTIATING);
3220 *al = SSL_AD_HANDSHAKE_FAILURE;
3223 s->s3->send_connection_binding = 1;
3227 /* Check for TLS_FALLBACK_SCSV */
3228 if ((cipher[n - 2] == ((SSL3_CK_FALLBACK_SCSV >> 8) & 0xff)) &&
3229 (cipher[n - 1] == (SSL3_CK_FALLBACK_SCSV & 0xff))) {
3231 * The SCSV indicates that the client previously tried a higher
3232 * version. Fail if the current version is an unexpected
3235 if (!ssl_check_version_downgrade(s)) {
3236 SSLerr(SSL_F_SSL_BYTES_TO_CIPHER_LIST,
3237 SSL_R_INAPPROPRIATE_FALLBACK);
3238 *al = SSL_AD_INAPPROPRIATE_FALLBACK;
3244 /* For SSLv2-compat, ignore leading 0-byte. */
3245 c = ssl_get_cipher_by_char(s, sslv2format ? &cipher[1] : cipher);
3247 if (!sk_SSL_CIPHER_push(sk, c)) {
3248 SSLerr(SSL_F_SSL_BYTES_TO_CIPHER_LIST, ERR_R_MALLOC_FAILURE);
3249 *al = SSL_AD_INTERNAL_ERROR;
3254 if (PACKET_remaining(cipher_suites) > 0) {
3255 *al = SSL_AD_INTERNAL_ERROR;
3256 SSLerr(SSL_F_SSL_BYTES_TO_CIPHER_LIST, ERR_R_INTERNAL_ERROR);
3264 if ((skp == NULL) || (*skp == NULL))
3265 sk_SSL_CIPHER_free(sk);