1 /* ssl/statem/statem_srvr.c -*- mode:C; c-file-style: "eay" -*- */
2 /* Copyright (C) 1995-1998 Eric Young (eay@cryptsoft.com)
5 * This package is an SSL implementation written
6 * by Eric Young (eay@cryptsoft.com).
7 * The implementation was written so as to conform with Netscapes SSL.
9 * This library is free for commercial and non-commercial use as long as
10 * the following conditions are aheared to. The following conditions
11 * apply to all code found in this distribution, be it the RC4, RSA,
12 * lhash, DES, etc., code; not just the SSL code. The SSL documentation
13 * included with this distribution is covered by the same copyright terms
14 * except that the holder is Tim Hudson (tjh@cryptsoft.com).
16 * Copyright remains Eric Young's, and as such any Copyright notices in
17 * the code are not to be removed.
18 * If this package is used in a product, Eric Young should be given attribution
19 * as the author of the parts of the library used.
20 * This can be in the form of a textual message at program startup or
21 * in documentation (online or textual) provided with the package.
23 * Redistribution and use in source and binary forms, with or without
24 * modification, are permitted provided that the following conditions
26 * 1. Redistributions of source code must retain the copyright
27 * notice, this list of conditions and the following disclaimer.
28 * 2. Redistributions in binary form must reproduce the above copyright
29 * notice, this list of conditions and the following disclaimer in the
30 * documentation and/or other materials provided with the distribution.
31 * 3. All advertising materials mentioning features or use of this software
32 * must display the following acknowledgement:
33 * "This product includes cryptographic software written by
34 * Eric Young (eay@cryptsoft.com)"
35 * The word 'cryptographic' can be left out if the rouines from the library
36 * being used are not cryptographic related :-).
37 * 4. If you include any Windows specific code (or a derivative thereof) from
38 * the apps directory (application code) you must include an acknowledgement:
39 * "This product includes software written by Tim Hudson (tjh@cryptsoft.com)"
41 * THIS SOFTWARE IS PROVIDED BY ERIC YOUNG ``AS IS'' AND
42 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
43 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
44 * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
45 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
46 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
47 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
48 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
49 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
50 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
53 * The licence and distribution terms for any publically available version or
54 * derivative of this code cannot be changed. i.e. this code cannot simply be
55 * copied and put under another distribution licence
56 * [including the GNU Public Licence.]
58 /* ====================================================================
59 * Copyright (c) 1998-2007 The OpenSSL Project. All rights reserved.
61 * Redistribution and use in source and binary forms, with or without
62 * modification, are permitted provided that the following conditions
65 * 1. Redistributions of source code must retain the above copyright
66 * notice, this list of conditions and the following disclaimer.
68 * 2. Redistributions in binary form must reproduce the above copyright
69 * notice, this list of conditions and the following disclaimer in
70 * the documentation and/or other materials provided with the
73 * 3. All advertising materials mentioning features or use of this
74 * software must display the following acknowledgment:
75 * "This product includes software developed by the OpenSSL Project
76 * for use in the OpenSSL Toolkit. (http://www.openssl.org/)"
78 * 4. The names "OpenSSL Toolkit" and "OpenSSL Project" must not be used to
79 * endorse or promote products derived from this software without
80 * prior written permission. For written permission, please contact
81 * openssl-core@openssl.org.
83 * 5. Products derived from this software may not be called "OpenSSL"
84 * nor may "OpenSSL" appear in their names without prior written
85 * permission of the OpenSSL Project.
87 * 6. Redistributions of any form whatsoever must retain the following
89 * "This product includes software developed by the OpenSSL Project
90 * for use in the OpenSSL Toolkit (http://www.openssl.org/)"
92 * THIS SOFTWARE IS PROVIDED BY THE OpenSSL PROJECT ``AS IS'' AND ANY
93 * EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
94 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
95 * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE OpenSSL PROJECT OR
96 * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
97 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
98 * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
99 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
100 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
101 * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
102 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
103 * OF THE POSSIBILITY OF SUCH DAMAGE.
104 * ====================================================================
106 * This product includes cryptographic software written by Eric Young
107 * (eay@cryptsoft.com). This product includes software written by Tim
108 * Hudson (tjh@cryptsoft.com).
111 /* ====================================================================
112 * Copyright 2002 Sun Microsystems, Inc. ALL RIGHTS RESERVED.
114 * Portions of the attached software ("Contribution") are developed by
115 * SUN MICROSYSTEMS, INC., and are contributed to the OpenSSL project.
117 * The Contribution is licensed pursuant to the OpenSSL open source
118 * license provided above.
120 * ECC cipher suite support in OpenSSL originally written by
121 * Vipul Gupta and Sumit Gupta of Sun Microsystems Laboratories.
124 /* ====================================================================
125 * Copyright 2005 Nokia. All rights reserved.
127 * The portions of the attached software ("Contribution") is developed by
128 * Nokia Corporation and is licensed pursuant to the OpenSSL open source
131 * The Contribution, originally written by Mika Kousa and Pasi Eronen of
132 * Nokia Corporation, consists of the "PSK" (Pre-Shared Key) ciphersuites
133 * support (see RFC 4279) to OpenSSL.
135 * No patent licenses or other rights except those expressly stated in
136 * the OpenSSL open source license shall be deemed granted or received
137 * expressly, by implication, estoppel, or otherwise.
139 * No assurances are provided by Nokia that the Contribution does not
140 * infringe the patent or other intellectual property rights of any third
141 * party or that the license provides you with all the necessary rights
142 * to make use of the Contribution.
144 * THE SOFTWARE IS PROVIDED "AS IS" WITHOUT WARRANTY OF ANY KIND. IN
145 * ADDITION TO THE DISCLAIMERS INCLUDED IN THE LICENSE, NOKIA
146 * SPECIFICALLY DISCLAIMS ANY LIABILITY FOR CLAIMS BROUGHT BY YOU OR ANY
147 * OTHER ENTITY BASED ON INFRINGEMENT OF INTELLECTUAL PROPERTY RIGHTS OR
153 #include "../ssl_locl.h"
154 #include "statem_locl.h"
155 #include "internal/constant_time_locl.h"
156 #include <openssl/buffer.h>
157 #include <openssl/rand.h>
158 #include <openssl/objects.h>
159 #include <openssl/evp.h>
160 #include <openssl/hmac.h>
161 #include <openssl/x509.h>
162 #ifndef OPENSSL_NO_DH
163 # include <openssl/dh.h>
165 #include <openssl/bn.h>
166 #include <openssl/md5.h>
168 static STACK_OF(SSL_CIPHER) *ssl_bytes_to_cipher_list(SSL *s,
169 PACKET *cipher_suites,
170 STACK_OF(SSL_CIPHER) **skp,
171 int sslv2format, int *al);
174 * server_read_transition() encapsulates the logic for the allowed handshake
175 * state transitions when the server is reading messages from the client. The
176 * message type that the client has sent is provided in |mt|. The current state
177 * is in |s->statem.hand_state|.
179 * Valid return values are:
180 * 1: Success (transition allowed)
181 * 0: Error (transition not allowed)
183 int server_read_transition(SSL *s, int mt)
185 STATEM *st = &s->statem;
187 switch(st->hand_state) {
189 case DTLS_ST_SW_HELLO_VERIFY_REQUEST:
190 if (mt == SSL3_MT_CLIENT_HELLO) {
191 st->hand_state = TLS_ST_SR_CLNT_HELLO;
196 case TLS_ST_SW_SRVR_DONE:
198 * If we get a CKE message after a ServerDone then either
199 * 1) We didn't request a Certificate
201 * 2) If we did request one then
202 * a) We allow no Certificate to be returned
204 * b) We are running SSL3 (in TLS1.0+ the client must return a 0
205 * list if we requested a certificate)
207 if (mt == SSL3_MT_CLIENT_KEY_EXCHANGE
208 && (!s->s3->tmp.cert_request
209 || (!((s->verify_mode & SSL_VERIFY_PEER) &&
210 (s->verify_mode & SSL_VERIFY_FAIL_IF_NO_PEER_CERT))
211 && (s->version == SSL3_VERSION)))) {
212 st->hand_state = TLS_ST_SR_KEY_EXCH;
214 } else if (s->s3->tmp.cert_request) {
215 if (mt == SSL3_MT_CERTIFICATE) {
216 st->hand_state = TLS_ST_SR_CERT;
223 if (mt == SSL3_MT_CLIENT_KEY_EXCHANGE) {
224 st->hand_state = TLS_ST_SR_KEY_EXCH;
229 case TLS_ST_SR_KEY_EXCH:
231 * We should only process a CertificateVerify message if we have
232 * received a Certificate from the client. If so then |s->session->peer|
233 * will be non NULL. In some instances a CertificateVerify message is
234 * not required even if the peer has sent a Certificate (e.g. such as in
235 * the case of static DH). In that case |s->no_cert_verify| should be
238 if (s->session->peer == NULL || s->no_cert_verify) {
239 if (mt == SSL3_MT_CHANGE_CIPHER_SPEC) {
241 * For the ECDH ciphersuites when the client sends its ECDH
242 * pub key in a certificate, the CertificateVerify message is
243 * not sent. Also for GOST ciphersuites when the client uses
244 * its key from the certificate for key exchange.
246 st->hand_state = TLS_ST_SR_CHANGE;
250 if (mt == SSL3_MT_CERTIFICATE_VERIFY) {
251 st->hand_state = TLS_ST_SR_CERT_VRFY;
257 case TLS_ST_SR_CERT_VRFY:
258 if (mt == SSL3_MT_CHANGE_CIPHER_SPEC) {
259 st->hand_state = TLS_ST_SR_CHANGE;
264 case TLS_ST_SR_CHANGE:
265 #ifndef OPENSSL_NO_NEXTPROTONEG
266 if (s->s3->next_proto_neg_seen) {
267 if (mt == SSL3_MT_NEXT_PROTO) {
268 st->hand_state = TLS_ST_SR_NEXT_PROTO;
273 if (mt == SSL3_MT_FINISHED) {
274 st->hand_state = TLS_ST_SR_FINISHED;
277 #ifndef OPENSSL_NO_NEXTPROTONEG
282 #ifndef OPENSSL_NO_NEXTPROTONEG
283 case TLS_ST_SR_NEXT_PROTO:
284 if (mt == SSL3_MT_FINISHED) {
285 st->hand_state = TLS_ST_SR_FINISHED;
291 case TLS_ST_SW_FINISHED:
292 if (mt == SSL3_MT_CHANGE_CIPHER_SPEC) {
293 st->hand_state = TLS_ST_SR_CHANGE;
302 /* No valid transition found */
307 * Should we send a ServerKeyExchange message?
309 * Valid return values are:
313 static inline int send_server_key_exchange(SSL *s)
315 unsigned long alg_k = s->s3->tmp.new_cipher->algorithm_mkey;
318 * only send a ServerKeyExchange if DH, fortezza or RSA but we have a
319 * sign only certificate PSK: may send PSK identity hints For
320 * ECC ciphersuites, we send a serverKeyExchange message only if
321 * the cipher suite is either ECDH-anon or ECDHE. In other cases,
322 * the server certificate contains the server's public key for
325 if ( (alg_k & SSL_kDHE)
326 || (alg_k & SSL_kECDHE)
327 || ((alg_k & SSL_kRSA)
328 && (s->cert->pkeys[SSL_PKEY_RSA_ENC].privatekey == NULL
329 || (SSL_C_IS_EXPORT(s->s3->tmp.new_cipher)
330 && EVP_PKEY_size(s->cert->pkeys
331 [SSL_PKEY_RSA_ENC].privatekey) *
332 8 > SSL_C_EXPORT_PKEYLENGTH(s->s3->tmp.new_cipher)
337 * PSK: send ServerKeyExchange if PSK identity hint if
340 #ifndef OPENSSL_NO_PSK
341 /* Only send SKE if we have identity hint for plain PSK */
342 || ((alg_k & (SSL_kPSK | SSL_kRSAPSK))
343 && s->cert->psk_identity_hint)
344 /* For other PSK always send SKE */
345 || (alg_k & (SSL_PSK & (SSL_kDHEPSK | SSL_kECDHEPSK)))
347 #ifndef OPENSSL_NO_SRP
348 /* SRP: send ServerKeyExchange */
349 || (alg_k & SSL_kSRP)
359 * Should we send a CertificateRequest message?
361 * Valid return values are:
365 static inline int send_certificate_request(SSL *s)
368 /* don't request cert unless asked for it: */
369 s->verify_mode & SSL_VERIFY_PEER
371 * if SSL_VERIFY_CLIENT_ONCE is set, don't request cert
372 * during re-negotiation:
374 && ((s->session->peer == NULL) ||
375 !(s->verify_mode & SSL_VERIFY_CLIENT_ONCE))
377 * never request cert in anonymous ciphersuites (see
378 * section "Certificate request" in SSL 3 drafts and in
381 && (!(s->s3->tmp.new_cipher->algorithm_auth & SSL_aNULL)
383 * ... except when the application insists on
384 * verification (against the specs, but s3_clnt.c accepts
387 || (s->verify_mode & SSL_VERIFY_FAIL_IF_NO_PEER_CERT))
388 /* don't request certificate for SRP auth */
389 && !(s->s3->tmp.new_cipher->algorithm_auth & SSL_aSRP)
391 * With normal PSK Certificates and Certificate Requests
394 && !(s->s3->tmp.new_cipher->algorithm_mkey & SSL_PSK)) {
402 * server_write_transition() works out what handshake state to move to next
403 * when the server is writing messages to be sent to the client.
405 enum WRITE_TRAN server_write_transition(SSL *s)
407 STATEM *st = &s->statem;
409 switch(st->hand_state) {
411 /* Just go straight to trying to read from the client */;
412 return WRITE_TRAN_FINISHED;
415 /* We must be trying to renegotiate */
416 st->hand_state = TLS_ST_SW_HELLO_REQ;
417 return WRITE_TRAN_CONTINUE;
419 case TLS_ST_SW_HELLO_REQ:
420 st->hand_state = TLS_ST_OK;
421 statem_set_in_init(s, 0);
422 return WRITE_TRAN_CONTINUE;
424 case TLS_ST_SR_CLNT_HELLO:
425 if (SSL_IS_DTLS(s) && !s->d1->cookie_verified
426 && (SSL_get_options(s) & SSL_OP_COOKIE_EXCHANGE))
427 st->hand_state = DTLS_ST_SW_HELLO_VERIFY_REQUEST;
429 st->hand_state = TLS_ST_SW_SRVR_HELLO;
430 return WRITE_TRAN_CONTINUE;
432 case DTLS_ST_SW_HELLO_VERIFY_REQUEST:
433 return WRITE_TRAN_FINISHED;
435 case TLS_ST_SW_SRVR_HELLO:
437 if (s->tlsext_ticket_expected)
438 st->hand_state = TLS_ST_SW_SESSION_TICKET;
440 st->hand_state = TLS_ST_SW_CHANGE;
442 /* Check if it is anon DH or anon ECDH, */
443 /* normal PSK or SRP */
444 if (!(s->s3->tmp.new_cipher->algorithm_auth &
445 (SSL_aNULL | SSL_aSRP | SSL_aPSK))) {
446 st->hand_state = TLS_ST_SW_CERT;
447 } else if (send_server_key_exchange(s)) {
448 st->hand_state = TLS_ST_SW_KEY_EXCH;
449 } else if (send_certificate_request(s)) {
450 st->hand_state = TLS_ST_SW_CERT_REQ;
452 st->hand_state = TLS_ST_SW_SRVR_DONE;
455 return WRITE_TRAN_CONTINUE;
458 if (s->tlsext_status_expected) {
459 st->hand_state = TLS_ST_SW_CERT_STATUS;
460 return WRITE_TRAN_CONTINUE;
464 case TLS_ST_SW_CERT_STATUS:
465 if (send_server_key_exchange(s)) {
466 st->hand_state = TLS_ST_SW_KEY_EXCH;
467 return WRITE_TRAN_CONTINUE;
471 case TLS_ST_SW_KEY_EXCH:
472 if (send_certificate_request(s)) {
473 st->hand_state = TLS_ST_SW_CERT_REQ;
474 return WRITE_TRAN_CONTINUE;
478 case TLS_ST_SW_CERT_REQ:
479 st->hand_state = TLS_ST_SW_SRVR_DONE;
480 return WRITE_TRAN_CONTINUE;
482 case TLS_ST_SW_SRVR_DONE:
483 return WRITE_TRAN_FINISHED;
485 case TLS_ST_SR_FINISHED:
487 st->hand_state = TLS_ST_OK;
488 statem_set_in_init(s, 0);
489 return WRITE_TRAN_CONTINUE;
490 } else if (s->tlsext_ticket_expected) {
491 st->hand_state = TLS_ST_SW_SESSION_TICKET;
493 st->hand_state = TLS_ST_SW_CHANGE;
495 return WRITE_TRAN_CONTINUE;
497 case TLS_ST_SW_SESSION_TICKET:
498 st->hand_state = TLS_ST_SW_CHANGE;
499 return WRITE_TRAN_CONTINUE;
501 case TLS_ST_SW_CHANGE:
502 st->hand_state = TLS_ST_SW_FINISHED;
503 return WRITE_TRAN_CONTINUE;
505 case TLS_ST_SW_FINISHED:
507 return WRITE_TRAN_FINISHED;
509 st->hand_state = TLS_ST_OK;
510 statem_set_in_init(s, 0);
511 return WRITE_TRAN_CONTINUE;
514 /* Shouldn't happen */
515 return WRITE_TRAN_ERROR;
520 * Perform any pre work that needs to be done prior to sending a message from
521 * the server to the client.
523 enum WORK_STATE server_pre_work(SSL *s, enum WORK_STATE wst)
525 STATEM *st = &s->statem;
527 switch(st->hand_state) {
528 case TLS_ST_SW_HELLO_REQ:
531 dtls1_clear_record_buffer(s);
534 case DTLS_ST_SW_HELLO_VERIFY_REQUEST:
536 if (SSL_IS_DTLS(s)) {
537 dtls1_clear_record_buffer(s);
538 /* We don't buffer this message so don't use the timer */
543 case TLS_ST_SW_SRVR_HELLO:
544 if (SSL_IS_DTLS(s)) {
546 * Messages we write from now on should be bufferred and
547 * retransmitted if necessary, so we need to use the timer now
553 case TLS_ST_SW_SRVR_DONE:
554 #ifndef OPENSSL_NO_SCTP
555 if (SSL_IS_DTLS(s) && BIO_dgram_is_sctp(SSL_get_wbio(s)))
556 return dtls_wait_for_dry(s);
558 return WORK_FINISHED_CONTINUE;
560 case TLS_ST_SW_SESSION_TICKET:
561 if (SSL_IS_DTLS(s)) {
563 * We're into the last flight. We don't retransmit the last flight
564 * unless we need to, so we don't use the timer
570 case TLS_ST_SW_CHANGE:
571 s->session->cipher = s->s3->tmp.new_cipher;
572 if (!s->method->ssl3_enc->setup_key_block(s)) {
576 if (SSL_IS_DTLS(s)) {
578 * We're into the last flight. We don't retransmit the last flight
579 * unless we need to, so we don't use the timer. This might have
580 * already been set to 0 if we sent a NewSessionTicket message,
581 * but we'll set it again here in case we didn't.
585 return WORK_FINISHED_CONTINUE;
588 return tls_finish_handshake(s, wst);
591 /* No pre work to be done */
595 return WORK_FINISHED_CONTINUE;
599 * Perform any work that needs to be done after sending a message from the
600 * server to the client.
602 enum WORK_STATE server_post_work(SSL *s, enum WORK_STATE wst)
604 STATEM *st = &s->statem;
608 switch(st->hand_state) {
609 case TLS_ST_SW_HELLO_REQ:
610 if (statem_flush(s) != 1)
612 ssl3_init_finished_mac(s);
615 case DTLS_ST_SW_HELLO_VERIFY_REQUEST:
616 if (statem_flush(s) != 1)
618 /* HelloVerifyRequest resets Finished MAC */
619 if (s->version != DTLS1_BAD_VER)
620 ssl3_init_finished_mac(s);
622 * The next message should be another ClientHello which we need to
623 * treat like it was the first packet
628 case TLS_ST_SW_SRVR_HELLO:
629 #ifndef OPENSSL_NO_SCTP
630 if (SSL_IS_DTLS(s) && s->hit) {
631 unsigned char sctpauthkey[64];
632 char labelbuffer[sizeof(DTLS1_SCTP_AUTH_LABEL)];
635 * Add new shared key for SCTP-Auth, will be ignored if no
638 snprintf((char *)labelbuffer, sizeof(DTLS1_SCTP_AUTH_LABEL),
639 DTLS1_SCTP_AUTH_LABEL);
641 if (SSL_export_keying_material(s, sctpauthkey,
642 sizeof(sctpauthkey), labelbuffer,
643 sizeof(labelbuffer), NULL, 0, 0) <= 0) {
648 BIO_ctrl(SSL_get_wbio(s), BIO_CTRL_DGRAM_SCTP_ADD_AUTH_KEY,
649 sizeof(sctpauthkey), sctpauthkey);
654 case TLS_ST_SW_CHANGE:
655 #ifndef OPENSSL_NO_SCTP
656 if (SSL_IS_DTLS(s) && !s->hit) {
658 * Change to new shared key of SCTP-Auth, will be ignored if
661 BIO_ctrl(SSL_get_wbio(s), BIO_CTRL_DGRAM_SCTP_NEXT_AUTH_KEY,
665 if (!s->method->ssl3_enc->change_cipher_state(s,
666 SSL3_CHANGE_CIPHER_SERVER_WRITE)) {
672 dtls1_reset_seq_numbers(s, SSL3_CC_WRITE);
675 case TLS_ST_SW_SRVR_DONE:
676 if (statem_flush(s) != 1)
680 case TLS_ST_SW_FINISHED:
681 if (statem_flush(s) != 1)
683 #ifndef OPENSSL_NO_SCTP
684 if (SSL_IS_DTLS(s) && s->hit) {
686 * Change to new shared key of SCTP-Auth, will be ignored if
689 BIO_ctrl(SSL_get_wbio(s), BIO_CTRL_DGRAM_SCTP_NEXT_AUTH_KEY,
696 /* No post work to be done */
700 return WORK_FINISHED_CONTINUE;
704 * Construct a message to be sent from the server to the client.
706 * Valid return values are:
710 int server_construct_message(SSL *s)
712 STATEM *st = &s->statem;
714 switch(st->hand_state) {
715 case DTLS_ST_SW_HELLO_VERIFY_REQUEST:
716 return dtls_construct_hello_verify_request(s);
718 case TLS_ST_SW_HELLO_REQ:
719 return tls_construct_hello_request(s);
721 case TLS_ST_SW_SRVR_HELLO:
722 return tls_construct_server_hello(s);
725 return tls_construct_server_certificate(s);
727 case TLS_ST_SW_KEY_EXCH:
728 return tls_construct_server_key_exchange(s);
730 case TLS_ST_SW_CERT_REQ:
731 return tls_construct_certificate_request(s);
733 case TLS_ST_SW_SRVR_DONE:
734 return tls_construct_server_done(s);
736 case TLS_ST_SW_SESSION_TICKET:
737 return tls_construct_new_session_ticket(s);
739 case TLS_ST_SW_CERT_STATUS:
740 return tls_construct_cert_status(s);
742 case TLS_ST_SW_CHANGE:
744 return dtls_construct_change_cipher_spec(s);
746 return tls_construct_change_cipher_spec(s);
748 case TLS_ST_SW_FINISHED:
749 return tls_construct_finished(s,
751 ssl3_enc->server_finished_label,
753 ssl3_enc->server_finished_label_len);
756 /* Shouldn't happen */
763 #define CLIENT_KEY_EXCH_MAX_LENGTH 2048
764 #define NEXT_PROTO_MAX_LENGTH 514
767 * Returns the maximum allowed length for the current message that we are
768 * reading. Excludes the message header.
770 unsigned long server_max_message_size(SSL *s)
772 STATEM *st = &s->statem;
774 switch(st->hand_state) {
775 case TLS_ST_SR_CLNT_HELLO:
776 return SSL3_RT_MAX_PLAIN_LENGTH;
779 return s->max_cert_list;
781 case TLS_ST_SR_KEY_EXCH:
782 return CLIENT_KEY_EXCH_MAX_LENGTH;
784 case TLS_ST_SR_CERT_VRFY:
785 return SSL3_RT_MAX_PLAIN_LENGTH;
787 #ifndef OPENSSL_NO_NEXTPROTONEG
788 case TLS_ST_SR_NEXT_PROTO:
789 return NEXT_PROTO_MAX_LENGTH;
792 case TLS_ST_SR_CHANGE:
793 return CCS_MAX_LENGTH;
795 case TLS_ST_SR_FINISHED:
796 return FINISHED_MAX_LENGTH;
799 /* Shouldn't happen */
807 * Process a message that the server has received from the client.
809 enum MSG_PROCESS_RETURN server_process_message(SSL *s, PACKET *pkt)
811 STATEM *st = &s->statem;
813 switch(st->hand_state) {
814 case TLS_ST_SR_CLNT_HELLO:
815 return tls_process_client_hello(s, pkt);
818 return tls_process_client_certificate(s, pkt);
820 case TLS_ST_SR_KEY_EXCH:
821 return tls_process_client_key_exchange(s, pkt);
823 case TLS_ST_SR_CERT_VRFY:
824 return tls_process_cert_verify(s, pkt);
826 #ifndef OPENSSL_NO_NEXTPROTONEG
827 case TLS_ST_SR_NEXT_PROTO:
828 return tls_process_next_proto(s, pkt);
831 case TLS_ST_SR_CHANGE:
832 return tls_process_change_cipher_spec(s, pkt);
834 case TLS_ST_SR_FINISHED:
835 return tls_process_finished(s, pkt);
838 /* Shouldn't happen */
842 return MSG_PROCESS_ERROR;
846 * Perform any further processing required following the receipt of a message
849 enum WORK_STATE server_post_process_message(SSL *s, enum WORK_STATE wst)
851 STATEM *st = &s->statem;
853 switch(st->hand_state) {
854 case TLS_ST_SR_CLNT_HELLO:
855 return tls_post_process_client_hello(s, wst);
857 case TLS_ST_SR_KEY_EXCH:
858 return tls_post_process_client_key_exchange(s, wst);
860 case TLS_ST_SR_CERT_VRFY:
861 #ifndef OPENSSL_NO_SCTP
862 if ( /* Is this SCTP? */
863 BIO_dgram_is_sctp(SSL_get_wbio(s))
864 /* Are we renegotiating? */
866 && BIO_dgram_sctp_msg_waiting(SSL_get_rbio(s))) {
867 s->s3->in_read_app_data = 2;
868 s->rwstate = SSL_READING;
869 BIO_clear_retry_flags(SSL_get_rbio(s));
870 BIO_set_retry_read(SSL_get_rbio(s));
871 statem_set_sctp_read_sock(s, 1);
874 statem_set_sctp_read_sock(s, 0);
877 return WORK_FINISHED_CONTINUE;
880 case TLS_ST_SR_FINISHED:
882 return tls_finish_handshake(s, wst);
884 return WORK_FINISHED_STOP;
889 /* Shouldn't happen */
893 #ifndef OPENSSL_NO_SRP
894 static int ssl_check_srp_ext_ClientHello(SSL *s, int *al)
896 int ret = SSL_ERROR_NONE;
898 *al = SSL_AD_UNRECOGNIZED_NAME;
900 if ((s->s3->tmp.new_cipher->algorithm_mkey & SSL_kSRP) &&
901 (s->srp_ctx.TLS_ext_srp_username_callback != NULL)) {
902 if (s->srp_ctx.login == NULL) {
904 * RFC 5054 says SHOULD reject, we do so if There is no srp
908 *al = SSL_AD_UNKNOWN_PSK_IDENTITY;
910 ret = SSL_srp_server_param_with_username(s, al);
917 int tls_construct_hello_request(SSL *s)
919 if (!ssl_set_handshake_header(s, SSL3_MT_HELLO_REQUEST, 0)) {
920 SSLerr(SSL_F_TLS_CONSTRUCT_HELLO_REQUEST, ERR_R_INTERNAL_ERROR);
928 unsigned int dtls_raw_hello_verify_request(unsigned char *buf,
929 unsigned char *cookie,
930 unsigned char cookie_len)
932 unsigned int msg_len;
936 /* Always use DTLS 1.0 version: see RFC 6347 */
937 *(p++) = DTLS1_VERSION >> 8;
938 *(p++) = DTLS1_VERSION & 0xFF;
940 *(p++) = (unsigned char)cookie_len;
941 memcpy(p, cookie, cookie_len);
948 int dtls_construct_hello_verify_request(SSL *s)
953 buf = (unsigned char *)s->init_buf->data;
955 if (s->ctx->app_gen_cookie_cb == NULL ||
956 s->ctx->app_gen_cookie_cb(s, s->d1->cookie,
957 &(s->d1->cookie_len)) == 0 ||
958 s->d1->cookie_len > 255) {
959 SSLerr(SSL_F_DTLS1_SEND_HELLO_VERIFY_REQUEST,
960 SSL_R_COOKIE_GEN_CALLBACK_FAILURE);
965 len = dtls_raw_hello_verify_request(&buf[DTLS1_HM_HEADER_LENGTH],
966 s->d1->cookie, s->d1->cookie_len);
968 dtls1_set_message_header(s, buf, DTLS1_MT_HELLO_VERIFY_REQUEST, len, 0,
970 len += DTLS1_HM_HEADER_LENGTH;
972 /* number of bytes to write */
979 enum MSG_PROCESS_RETURN tls_process_client_hello(SSL *s, PACKET *pkt)
981 int i, al = SSL_AD_INTERNAL_ERROR;
982 unsigned int j, complen = 0;
985 #ifndef OPENSSL_NO_COMP
986 SSL_COMP *comp = NULL;
988 STACK_OF(SSL_CIPHER) *ciphers = NULL;
990 /* |cookie| will only be initialized for DTLS. */
991 PACKET session_id, cipher_suites, compression, extensions, cookie;
994 is_v2_record = RECORD_LAYER_is_sslv2_record(&s->rlayer);
996 PACKET_null_init(&cookie);
997 /* First lets get s->client_version set correctly */
999 unsigned int version;
1002 * An SSLv3/TLSv1 backwards-compatible CLIENT-HELLO in an SSLv2
1003 * header is sent directly on the wire, not wrapped as a TLS
1004 * record. Our record layer just processes the message length and passes
1005 * the rest right through. Its format is:
1007 * 0-1 msg_length - decoded by the record layer
1008 * 2 msg_type - s->init_msg points here
1010 * 5-6 cipher_spec_length
1011 * 7-8 session_id_length
1012 * 9-10 challenge_length
1016 if (!PACKET_get_1(pkt, &mt)
1017 || mt != SSL2_MT_CLIENT_HELLO) {
1019 * Should never happen. We should have tested this in the record
1020 * layer in order to have determined that this is a SSLv2 record
1021 * in the first place
1023 SSLerr(SSL_F_TLS_PROCESS_CLIENT_HELLO, ERR_R_INTERNAL_ERROR);
1027 if (!PACKET_get_net_2(pkt, &version)) {
1028 /* No protocol version supplied! */
1029 SSLerr(SSL_F_TLS_PROCESS_CLIENT_HELLO, SSL_R_UNKNOWN_PROTOCOL);
1032 if (version == 0x0002) {
1033 /* This is real SSLv2. We don't support it. */
1034 SSLerr(SSL_F_TLS_PROCESS_CLIENT_HELLO, SSL_R_UNKNOWN_PROTOCOL);
1036 } else if ((version & 0xff00) == (SSL3_VERSION_MAJOR << 8)) {
1038 s->client_version = version;
1040 /* No idea what protocol this is */
1041 SSLerr(SSL_F_TLS_PROCESS_CLIENT_HELLO, SSL_R_UNKNOWN_PROTOCOL);
1046 * use version from inside client hello, not from record header (may
1047 * differ: see RFC 2246, Appendix E, second paragraph)
1049 if(!PACKET_get_net_2(pkt, (unsigned int *)&s->client_version)) {
1050 al = SSL_AD_DECODE_ERROR;
1051 SSLerr(SSL_F_TLS_PROCESS_CLIENT_HELLO, SSL_R_LENGTH_TOO_SHORT);
1056 /* Do SSL/TLS version negotiation if applicable */
1057 if (!SSL_IS_DTLS(s)) {
1058 if (s->version != TLS_ANY_VERSION) {
1059 if (s->client_version >= s->version) {
1062 } else if (s->client_version >= SSL3_VERSION) {
1063 switch(s->client_version) {
1065 case TLS1_2_VERSION:
1066 if(!(s->options & SSL_OP_NO_TLSv1_2)) {
1067 s->version = TLS1_2_VERSION;
1068 s->method = TLSv1_2_server_method();
1072 /* Deliberately fall through */
1073 case TLS1_1_VERSION:
1074 if(!(s->options & SSL_OP_NO_TLSv1_1)) {
1075 s->version = TLS1_1_VERSION;
1076 s->method = TLSv1_1_server_method();
1080 /* Deliberately fall through */
1082 if(!(s->options & SSL_OP_NO_TLSv1)) {
1083 s->version = TLS1_VERSION;
1084 s->method = TLSv1_server_method();
1088 /* Deliberately fall through */
1090 #ifndef OPENSSL_NO_SSL3
1091 if(!(s->options & SSL_OP_NO_SSLv3)) {
1092 s->version = SSL3_VERSION;
1093 s->method = SSLv3_server_method();
1102 } else if (s->client_version <= s->version
1103 || s->method->version == DTLS_ANY_VERSION) {
1105 * For DTLS we just check versions are potentially compatible. Version
1106 * negotiation comes later.
1112 SSLerr(SSL_F_TLS_PROCESS_CLIENT_HELLO, SSL_R_UNKNOWN_PROTOCOL);
1113 if ((!s->enc_write_ctx && !s->write_hash)) {
1115 * similar to ssl3_get_record, send alert using remote version
1118 s->version = s->client_version;
1120 al = SSL_AD_PROTOCOL_VERSION;
1124 /* Parse the message and load client random. */
1127 * Handle an SSLv2 backwards compatible ClientHello
1128 * Note, this is only for SSLv3+ using the backward compatible format.
1129 * Real SSLv2 is not supported, and is rejected above.
1131 unsigned int cipher_len, session_id_len, challenge_len;
1134 if (!PACKET_get_net_2(pkt, &cipher_len)
1135 || !PACKET_get_net_2(pkt, &session_id_len)
1136 || !PACKET_get_net_2(pkt, &challenge_len)) {
1137 SSLerr(SSL_F_TLS_PROCESS_CLIENT_HELLO,
1138 SSL_R_RECORD_LENGTH_MISMATCH);
1139 al = SSL_AD_DECODE_ERROR;
1143 if (!PACKET_get_sub_packet(pkt, &cipher_suites, cipher_len)
1144 || !PACKET_get_sub_packet(pkt, &session_id, session_id_len)
1145 || !PACKET_get_sub_packet(pkt, &challenge, challenge_len)
1146 /* No extensions. */
1147 || PACKET_remaining(pkt) != 0) {
1148 SSLerr(SSL_F_SSL3_GET_CLIENT_HELLO, SSL_R_RECORD_LENGTH_MISMATCH);
1149 al = SSL_AD_DECODE_ERROR;
1153 /* Load the client random */
1154 challenge_len = challenge_len > SSL3_RANDOM_SIZE ? SSL3_RANDOM_SIZE :
1156 memset(s->s3->client_random, 0, SSL3_RANDOM_SIZE);
1157 if (!PACKET_copy_bytes(&challenge,
1158 s->s3->client_random + SSL3_RANDOM_SIZE -
1159 challenge_len, challenge_len)) {
1160 SSLerr(SSL_F_SSL3_GET_CLIENT_HELLO, ERR_R_INTERNAL_ERROR);
1161 al = SSL_AD_INTERNAL_ERROR;
1165 PACKET_null_init(&compression);
1166 PACKET_null_init(&extensions);
1168 /* Regular ClientHello. */
1169 if (!PACKET_copy_bytes(pkt, s->s3->client_random, SSL3_RANDOM_SIZE)
1170 || !PACKET_get_length_prefixed_1(pkt, &session_id)) {
1171 al = SSL_AD_DECODE_ERROR;
1172 SSLerr(SSL_F_SSL3_GET_CLIENT_HELLO, SSL_R_LENGTH_MISMATCH);
1176 if (SSL_IS_DTLS(s)) {
1177 if (!PACKET_get_length_prefixed_1(pkt, &cookie)) {
1178 al = SSL_AD_DECODE_ERROR;
1179 SSLerr(SSL_F_SSL3_GET_CLIENT_HELLO, SSL_R_LENGTH_MISMATCH);
1183 * If we require cookies and this ClientHello doesn't contain one,
1184 * just return since we do not want to allocate any memory yet.
1185 * So check cookie length...
1187 if (SSL_get_options(s) & SSL_OP_COOKIE_EXCHANGE) {
1188 if (PACKET_remaining(&cookie) == 0)
1193 if (!PACKET_get_length_prefixed_2(pkt, &cipher_suites)
1194 || !PACKET_get_length_prefixed_1(pkt, &compression)) {
1195 al = SSL_AD_DECODE_ERROR;
1196 SSLerr(SSL_F_SSL3_GET_CLIENT_HELLO, SSL_R_LENGTH_MISMATCH);
1199 /* Could be empty. */
1206 * We don't allow resumption in a backwards compatible ClientHello.
1207 * TODO(openssl-team): in TLS1.1+, session_id MUST be empty.
1209 * Versions before 0.9.7 always allow clients to resume sessions in
1210 * renegotiation. 0.9.7 and later allow this by default, but optionally
1211 * ignore resumption requests with flag
1212 * SSL_OP_NO_SESSION_RESUMPTION_ON_RENEGOTIATION (it's a new flag rather
1213 * than a change to default behavior so that applications relying on
1214 * this for security won't even compile against older library versions).
1215 * 1.0.1 and later also have a function SSL_renegotiate_abbreviated() to
1216 * request renegotiation but not a new session (s->new_session remains
1217 * unset): for servers, this essentially just means that the
1218 * SSL_OP_NO_SESSION_RESUMPTION_ON_RENEGOTIATION setting will be
1223 (s->options & SSL_OP_NO_SESSION_RESUMPTION_ON_RENEGOTIATION))) {
1224 if (!ssl_get_new_session(s, 1))
1227 i = ssl_get_prev_session(s, &extensions, &session_id);
1229 * Only resume if the session's version matches the negotiated
1231 * RFC 5246 does not provide much useful advice on resumption
1232 * with a different protocol version. It doesn't forbid it but
1233 * the sanity of such behaviour would be questionable.
1234 * In practice, clients do not accept a version mismatch and
1235 * will abort the handshake with an error.
1237 if (i == 1 && s->version == s->session->ssl_version) {
1238 /* previous session */
1240 } else if (i == -1) {
1244 if (!ssl_get_new_session(s, 1))
1249 if (SSL_IS_DTLS(s)) {
1250 /* Empty cookie was already handled above by returning early. */
1251 if (SSL_get_options(s) & SSL_OP_COOKIE_EXCHANGE) {
1252 if (s->ctx->app_verify_cookie_cb != NULL) {
1253 if (s->ctx->app_verify_cookie_cb(s, PACKET_data(&cookie),
1254 PACKET_remaining(&cookie)) == 0) {
1255 al = SSL_AD_HANDSHAKE_FAILURE;
1256 SSLerr(SSL_F_SSL3_GET_CLIENT_HELLO,
1257 SSL_R_COOKIE_MISMATCH);
1259 /* else cookie verification succeeded */
1261 /* default verification */
1262 } else if (!PACKET_equal(&cookie, s->d1->cookie,
1263 s->d1->cookie_len)) {
1264 al = SSL_AD_HANDSHAKE_FAILURE;
1265 SSLerr(SSL_F_SSL3_GET_CLIENT_HELLO, SSL_R_COOKIE_MISMATCH);
1268 s->d1->cookie_verified = 1;
1270 if (s->method->version == DTLS_ANY_VERSION) {
1271 /* Select version to use */
1272 if (s->client_version <= DTLS1_2_VERSION &&
1273 !(s->options & SSL_OP_NO_DTLSv1_2)) {
1274 s->version = DTLS1_2_VERSION;
1275 s->method = DTLSv1_2_server_method();
1276 } else if (tls1_suiteb(s)) {
1277 SSLerr(SSL_F_SSL3_GET_CLIENT_HELLO,
1278 SSL_R_ONLY_DTLS_1_2_ALLOWED_IN_SUITEB_MODE);
1279 s->version = s->client_version;
1280 al = SSL_AD_PROTOCOL_VERSION;
1282 } else if (s->client_version <= DTLS1_VERSION &&
1283 !(s->options & SSL_OP_NO_DTLSv1)) {
1284 s->version = DTLS1_VERSION;
1285 s->method = DTLSv1_server_method();
1287 SSLerr(SSL_F_SSL3_GET_CLIENT_HELLO,
1288 SSL_R_WRONG_VERSION_NUMBER);
1289 s->version = s->client_version;
1290 al = SSL_AD_PROTOCOL_VERSION;
1293 s->session->ssl_version = s->version;
1297 if (ssl_bytes_to_cipher_list(s, &cipher_suites, &(ciphers),
1298 is_v2_record, &al) == NULL) {
1302 /* If it is a hit, check that the cipher is in the list */
1305 id = s->session->cipher->id;
1308 fprintf(stderr, "client sent %d ciphers\n",
1309 sk_SSL_CIPHER_num(ciphers));
1311 for (i = 0; i < sk_SSL_CIPHER_num(ciphers); i++) {
1312 c = sk_SSL_CIPHER_value(ciphers, i);
1314 fprintf(stderr, "client [%2d of %2d]:%s\n",
1315 i, sk_SSL_CIPHER_num(ciphers), SSL_CIPHER_get_name(c));
1324 * we need to have the cipher in the cipher list if we are asked
1327 al = SSL_AD_ILLEGAL_PARAMETER;
1328 SSLerr(SSL_F_SSL3_GET_CLIENT_HELLO,
1329 SSL_R_REQUIRED_CIPHER_MISSING);
1334 complen = PACKET_remaining(&compression);
1335 for (j = 0; j < complen; j++) {
1336 if (PACKET_data(&compression)[j] == 0)
1342 al = SSL_AD_DECODE_ERROR;
1343 SSLerr(SSL_F_SSL3_GET_CLIENT_HELLO, SSL_R_NO_COMPRESSION_SPECIFIED);
1347 /* TLS extensions */
1348 if (s->version >= SSL3_VERSION) {
1349 if (!ssl_parse_clienthello_tlsext(s, &extensions)) {
1350 SSLerr(SSL_F_SSL3_GET_CLIENT_HELLO, SSL_R_PARSE_TLSEXT);
1356 * Check if we want to use external pre-shared secret for this handshake
1357 * for not reused session only. We need to generate server_random before
1358 * calling tls_session_secret_cb in order to allow SessionTicket
1359 * processing to use it in key derivation.
1363 pos = s->s3->server_random;
1364 if (ssl_fill_hello_random(s, 1, pos, SSL3_RANDOM_SIZE) <= 0) {
1369 if (!s->hit && s->version >= TLS1_VERSION && s->tls_session_secret_cb) {
1370 SSL_CIPHER *pref_cipher = NULL;
1372 s->session->master_key_length = sizeof(s->session->master_key);
1373 if (s->tls_session_secret_cb(s, s->session->master_key,
1374 &s->session->master_key_length, ciphers,
1376 s->tls_session_secret_cb_arg)) {
1378 s->session->ciphers = ciphers;
1379 s->session->verify_result = X509_V_OK;
1383 /* check if some cipher was preferred by call back */
1385 pref_cipher ? pref_cipher : ssl3_choose_cipher(s,
1390 if (pref_cipher == NULL) {
1391 al = SSL_AD_HANDSHAKE_FAILURE;
1392 SSLerr(SSL_F_TLS_PROCESS_CLIENT_HELLO, SSL_R_NO_SHARED_CIPHER);
1396 s->session->cipher = pref_cipher;
1397 sk_SSL_CIPHER_free(s->cipher_list);
1398 s->cipher_list = sk_SSL_CIPHER_dup(s->session->ciphers);
1399 sk_SSL_CIPHER_free(s->cipher_list_by_id);
1400 s->cipher_list_by_id = sk_SSL_CIPHER_dup(s->session->ciphers);
1405 * Worst case, we will use the NULL compression, but if we have other
1406 * options, we will now look for them. We have complen-1 compression
1407 * algorithms from the client, starting at q.
1409 s->s3->tmp.new_compression = NULL;
1410 #ifndef OPENSSL_NO_COMP
1411 /* This only happens if we have a cache hit */
1412 if (s->session->compress_meth != 0) {
1413 int m, comp_id = s->session->compress_meth;
1415 /* Perform sanity checks on resumed compression algorithm */
1416 /* Can't disable compression */
1417 if (!ssl_allow_compression(s)) {
1418 SSLerr(SSL_F_TLS_PROCESS_CLIENT_HELLO,
1419 SSL_R_INCONSISTENT_COMPRESSION);
1422 /* Look for resumed compression method */
1423 for (m = 0; m < sk_SSL_COMP_num(s->ctx->comp_methods); m++) {
1424 comp = sk_SSL_COMP_value(s->ctx->comp_methods, m);
1425 if (comp_id == comp->id) {
1426 s->s3->tmp.new_compression = comp;
1430 if (s->s3->tmp.new_compression == NULL) {
1431 SSLerr(SSL_F_TLS_PROCESS_CLIENT_HELLO,
1432 SSL_R_INVALID_COMPRESSION_ALGORITHM);
1435 /* Look for resumed method in compression list */
1436 for (k = 0; k < complen; k++) {
1437 if (PACKET_data(&compression)[k] == comp_id)
1441 al = SSL_AD_ILLEGAL_PARAMETER;
1442 SSLerr(SSL_F_TLS_PROCESS_CLIENT_HELLO,
1443 SSL_R_REQUIRED_COMPRESSSION_ALGORITHM_MISSING);
1448 else if (ssl_allow_compression(s) && s->ctx->comp_methods) {
1449 /* See if we have a match */
1450 int m, nn, v, done = 0;
1453 nn = sk_SSL_COMP_num(s->ctx->comp_methods);
1454 for (m = 0; m < nn; m++) {
1455 comp = sk_SSL_COMP_value(s->ctx->comp_methods, m);
1457 for (o = 0; o < complen; o++) {
1458 if (v == PACKET_data(&compression)[o]) {
1467 s->s3->tmp.new_compression = comp;
1473 * If compression is disabled we'd better not try to resume a session
1474 * using compression.
1476 if (s->session->compress_meth != 0) {
1477 SSLerr(SSL_F_TLS_PROCESS_CLIENT_HELLO, SSL_R_INCONSISTENT_COMPRESSION);
1483 * Given s->session->ciphers and SSL_get_ciphers, we must pick a cipher
1487 #ifdef OPENSSL_NO_COMP
1488 s->session->compress_meth = 0;
1490 s->session->compress_meth = (comp == NULL) ? 0 : comp->id;
1492 sk_SSL_CIPHER_free(s->session->ciphers);
1493 s->session->ciphers = ciphers;
1494 if (ciphers == NULL) {
1495 al = SSL_AD_INTERNAL_ERROR;
1496 SSLerr(SSL_F_TLS_PROCESS_CLIENT_HELLO, ERR_R_INTERNAL_ERROR);
1500 if (!tls1_set_server_sigalgs(s)) {
1501 SSLerr(SSL_F_TLS_PROCESS_CLIENT_HELLO, SSL_R_CLIENTHELLO_TLSEXT);
1506 sk_SSL_CIPHER_free(ciphers);
1507 return MSG_PROCESS_CONTINUE_PROCESSING;
1509 ssl3_send_alert(s, SSL3_AL_FATAL, al);
1511 statem_set_error(s);
1513 sk_SSL_CIPHER_free(ciphers);
1514 return MSG_PROCESS_ERROR;
1518 enum WORK_STATE tls_post_process_client_hello(SSL *s, enum WORK_STATE wst)
1523 if (wst == WORK_MORE_A) {
1525 /* Let cert callback update server certificates if required */
1526 if (s->cert->cert_cb) {
1527 int rv = s->cert->cert_cb(s, s->cert->cert_cb_arg);
1529 al = SSL_AD_INTERNAL_ERROR;
1530 SSLerr(SSL_F_TLS_POST_PROCESS_CLIENT_HELLO, SSL_R_CERT_CB_ERROR);
1534 s->rwstate = SSL_X509_LOOKUP;
1537 s->rwstate = SSL_NOTHING;
1539 cipher = ssl3_choose_cipher(s, s->session->ciphers, SSL_get_ciphers(s));
1541 if (cipher == NULL) {
1542 al = SSL_AD_HANDSHAKE_FAILURE;
1543 SSLerr(SSL_F_TLS_POST_PROCESS_CLIENT_HELLO, SSL_R_NO_SHARED_CIPHER);
1546 s->s3->tmp.new_cipher = cipher;
1547 /* check whether we should disable session resumption */
1548 if (s->not_resumable_session_cb != NULL)
1549 s->session->not_resumable = s->not_resumable_session_cb(s,
1550 ((cipher->algorithm_mkey & (SSL_kDHE | SSL_kECDHE)) != 0));
1551 if (s->session->not_resumable)
1552 /* do not send a session ticket */
1553 s->tlsext_ticket_expected = 0;
1555 /* Session-id reuse */
1556 s->s3->tmp.new_cipher = s->session->cipher;
1559 if (!SSL_USE_SIGALGS(s) || !(s->verify_mode & SSL_VERIFY_PEER)) {
1560 if (!ssl3_digest_cached_records(s, 0))
1565 * we now have the following setup.
1567 * cipher_list - our prefered list of ciphers
1568 * ciphers - the clients prefered list of ciphers
1569 * compression - basically ignored right now
1570 * ssl version is set - sslv3
1571 * s->session - The ssl session has been setup.
1572 * s->hit - session reuse flag
1573 * s->s3->tmp.new_cipher- the new cipher to use.
1576 /* Handles TLS extensions that we couldn't check earlier */
1577 if (s->version >= SSL3_VERSION) {
1578 if (ssl_check_clienthello_tlsext_late(s) <= 0) {
1579 SSLerr(SSL_F_TLS_POST_PROCESS_CLIENT_HELLO, SSL_R_CLIENTHELLO_TLSEXT);
1586 #ifndef OPENSSL_NO_SRP
1587 if (wst == WORK_MORE_B) {
1589 if ((ret = ssl_check_srp_ext_ClientHello(s, &al)) < 0) {
1591 * callback indicates further work to be done
1593 s->rwstate = SSL_X509_LOOKUP;
1596 if (ret != SSL_ERROR_NONE) {
1598 * This is not really an error but the only means to for
1599 * a client to detect whether srp is supported.
1601 if (al != TLS1_AD_UNKNOWN_PSK_IDENTITY)
1602 SSLerr(SSL_F_TLS_POST_PROCESS_CLIENT_HELLO,
1603 SSL_R_CLIENTHELLO_TLSEXT);
1610 return WORK_FINISHED_STOP;
1612 ssl3_send_alert(s, SSL3_AL_FATAL, al);
1613 statem_set_error(s);
1617 int tls_construct_server_hello(SSL *s)
1620 unsigned char *p, *d;
1625 buf = (unsigned char *)s->init_buf->data;
1627 /* Do the message type and length last */
1628 d = p = ssl_handshake_start(s);
1630 *(p++) = s->version >> 8;
1631 *(p++) = s->version & 0xff;
1634 * Random stuff. Filling of the server_random takes place in
1635 * tls_process_client_hello()
1637 memcpy(p, s->s3->server_random, SSL3_RANDOM_SIZE);
1638 p += SSL3_RANDOM_SIZE;
1641 * There are several cases for the session ID to send
1642 * back in the server hello:
1643 * - For session reuse from the session cache,
1644 * we send back the old session ID.
1645 * - If stateless session reuse (using a session ticket)
1646 * is successful, we send back the client's "session ID"
1647 * (which doesn't actually identify the session).
1648 * - If it is a new session, we send back the new
1650 * - However, if we want the new session to be single-use,
1651 * we send back a 0-length session ID.
1652 * s->hit is non-zero in either case of session reuse,
1653 * so the following won't overwrite an ID that we're supposed
1656 if (s->session->not_resumable ||
1657 (!(s->ctx->session_cache_mode & SSL_SESS_CACHE_SERVER)
1659 s->session->session_id_length = 0;
1661 sl = s->session->session_id_length;
1662 if (sl > (int)sizeof(s->session->session_id)) {
1663 SSLerr(SSL_F_TLS_CONSTRUCT_SERVER_HELLO, ERR_R_INTERNAL_ERROR);
1664 statem_set_error(s);
1668 memcpy(p, s->session->session_id, sl);
1671 /* put the cipher */
1672 i = ssl3_put_cipher_by_char(s->s3->tmp.new_cipher, p);
1675 /* put the compression method */
1676 #ifdef OPENSSL_NO_COMP
1679 if (s->s3->tmp.new_compression == NULL)
1682 *(p++) = s->s3->tmp.new_compression->id;
1685 if (ssl_prepare_serverhello_tlsext(s) <= 0) {
1686 SSLerr(SSL_F_TLS_CONSTRUCT_SERVER_HELLO, SSL_R_SERVERHELLO_TLSEXT);
1687 statem_set_error(s);
1691 ssl_add_serverhello_tlsext(s, p, buf + SSL3_RT_MAX_PLAIN_LENGTH,
1693 ssl3_send_alert(s, SSL3_AL_FATAL, al);
1694 SSLerr(SSL_F_TLS_CONSTRUCT_SERVER_HELLO, ERR_R_INTERNAL_ERROR);
1695 statem_set_error(s);
1701 if (!ssl_set_handshake_header(s, SSL3_MT_SERVER_HELLO, l)) {
1702 SSLerr(SSL_F_TLS_CONSTRUCT_SERVER_HELLO, ERR_R_INTERNAL_ERROR);
1703 statem_set_error(s);
1710 int tls_construct_server_done(SSL *s)
1712 if (!ssl_set_handshake_header(s, SSL3_MT_SERVER_DONE, 0)) {
1713 SSLerr(SSL_F_TLS_CONSTRUCT_SERVER_DONE, ERR_R_INTERNAL_ERROR);
1714 statem_set_error(s);
1718 if (!s->s3->tmp.cert_request) {
1719 if (!ssl3_digest_cached_records(s, 0)) {
1720 statem_set_error(s);
1727 int tls_construct_server_key_exchange(SSL *s)
1729 #ifndef OPENSSL_NO_RSA
1733 unsigned char md_buf[MD5_DIGEST_LENGTH + SHA_DIGEST_LENGTH];
1736 #ifndef OPENSSL_NO_DH
1737 DH *dh = NULL, *dhp;
1739 #ifndef OPENSSL_NO_EC
1740 EC_KEY *ecdh = NULL, *ecdhp;
1741 unsigned char *encodedPoint = NULL;
1744 BN_CTX *bn_ctx = NULL;
1747 const EVP_MD *md = NULL;
1748 unsigned char *p, *d;
1758 EVP_MD_CTX_init(&md_ctx);
1760 type = s->s3->tmp.new_cipher->algorithm_mkey;
1765 r[0] = r[1] = r[2] = r[3] = NULL;
1767 #ifndef OPENSSL_NO_PSK
1768 if (type & SSL_PSK) {
1770 * reserve size for record length and PSK identity hint
1773 if (s->cert->psk_identity_hint)
1774 n += strlen(s->cert->psk_identity_hint);
1776 /* Plain PSK or RSAPSK nothing to do */
1777 if (type & (SSL_kPSK | SSL_kRSAPSK)) {
1779 #endif /* !OPENSSL_NO_PSK */
1780 #ifndef OPENSSL_NO_RSA
1781 if (type & SSL_kRSA) {
1782 rsa = cert->rsa_tmp;
1783 if ((rsa == NULL) && (s->cert->rsa_tmp_cb != NULL)) {
1784 rsa = s->cert->rsa_tmp_cb(s,
1785 SSL_C_IS_EXPORT(s->s3->
1787 SSL_C_EXPORT_PKEYLENGTH(s->s3->
1790 al = SSL_AD_HANDSHAKE_FAILURE;
1791 SSLerr(SSL_F_TLS_CONSTRUCT_SERVER_KEY_EXCHANGE,
1792 SSL_R_ERROR_GENERATING_TMP_RSA_KEY);
1796 cert->rsa_tmp = rsa;
1799 al = SSL_AD_HANDSHAKE_FAILURE;
1800 SSLerr(SSL_F_TLS_CONSTRUCT_SERVER_KEY_EXCHANGE,
1801 SSL_R_MISSING_TMP_RSA_KEY);
1806 s->s3->tmp.use_rsa_tmp = 1;
1809 #ifndef OPENSSL_NO_DH
1810 if (type & (SSL_kDHE | SSL_kDHEPSK)) {
1811 if (s->cert->dh_tmp_auto) {
1812 dhp = ssl_get_auto_dh(s);
1814 al = SSL_AD_INTERNAL_ERROR;
1815 SSLerr(SSL_F_TLS_CONSTRUCT_SERVER_KEY_EXCHANGE,
1816 ERR_R_INTERNAL_ERROR);
1821 if ((dhp == NULL) && (s->cert->dh_tmp_cb != NULL))
1822 dhp = s->cert->dh_tmp_cb(s,
1823 SSL_C_IS_EXPORT(s->s3->
1825 SSL_C_EXPORT_PKEYLENGTH(s->s3->
1828 al = SSL_AD_HANDSHAKE_FAILURE;
1829 SSLerr(SSL_F_TLS_CONSTRUCT_SERVER_KEY_EXCHANGE,
1830 SSL_R_MISSING_TMP_DH_KEY);
1833 if (!ssl_security(s, SSL_SECOP_TMP_DH,
1834 DH_security_bits(dhp), 0, dhp)) {
1835 al = SSL_AD_HANDSHAKE_FAILURE;
1836 SSLerr(SSL_F_TLS_CONSTRUCT_SERVER_KEY_EXCHANGE,
1837 SSL_R_DH_KEY_TOO_SMALL);
1840 if (s->s3->tmp.dh != NULL) {
1841 SSLerr(SSL_F_TLS_CONSTRUCT_SERVER_KEY_EXCHANGE,
1842 ERR_R_INTERNAL_ERROR);
1846 if (s->cert->dh_tmp_auto)
1848 else if ((dh = DHparams_dup(dhp)) == NULL) {
1849 SSLerr(SSL_F_TLS_CONSTRUCT_SERVER_KEY_EXCHANGE, ERR_R_DH_LIB);
1854 if ((dhp->pub_key == NULL ||
1855 dhp->priv_key == NULL ||
1856 (s->options & SSL_OP_SINGLE_DH_USE))) {
1857 if (!DH_generate_key(dh)) {
1858 SSLerr(SSL_F_TLS_CONSTRUCT_SERVER_KEY_EXCHANGE, ERR_R_DH_LIB);
1862 dh->pub_key = BN_dup(dhp->pub_key);
1863 dh->priv_key = BN_dup(dhp->priv_key);
1864 if ((dh->pub_key == NULL) || (dh->priv_key == NULL)) {
1865 SSLerr(SSL_F_TLS_CONSTRUCT_SERVER_KEY_EXCHANGE, ERR_R_DH_LIB);
1874 #ifndef OPENSSL_NO_EC
1875 if (type & (SSL_kECDHE | SSL_kECDHEPSK)) {
1876 const EC_GROUP *group;
1878 ecdhp = cert->ecdh_tmp;
1879 if (s->cert->ecdh_tmp_auto) {
1880 /* Get NID of appropriate shared curve */
1881 int nid = tls1_shared_curve(s, -2);
1882 if (nid != NID_undef)
1883 ecdhp = EC_KEY_new_by_curve_name(nid);
1884 } else if ((ecdhp == NULL) && s->cert->ecdh_tmp_cb) {
1885 ecdhp = s->cert->ecdh_tmp_cb(s,
1886 SSL_C_IS_EXPORT(s->s3->
1888 SSL_C_EXPORT_PKEYLENGTH(s->
1889 s3->tmp.new_cipher));
1891 if (ecdhp == NULL) {
1892 al = SSL_AD_HANDSHAKE_FAILURE;
1893 SSLerr(SSL_F_TLS_CONSTRUCT_SERVER_KEY_EXCHANGE,
1894 SSL_R_MISSING_TMP_ECDH_KEY);
1898 if (s->s3->tmp.ecdh != NULL) {
1899 SSLerr(SSL_F_TLS_CONSTRUCT_SERVER_KEY_EXCHANGE,
1900 ERR_R_INTERNAL_ERROR);
1904 /* Duplicate the ECDH structure. */
1905 if (ecdhp == NULL) {
1906 SSLerr(SSL_F_TLS_CONSTRUCT_SERVER_KEY_EXCHANGE, ERR_R_ECDH_LIB);
1909 if (s->cert->ecdh_tmp_auto)
1911 else if ((ecdh = EC_KEY_dup(ecdhp)) == NULL) {
1912 SSLerr(SSL_F_TLS_CONSTRUCT_SERVER_KEY_EXCHANGE, ERR_R_ECDH_LIB);
1916 s->s3->tmp.ecdh = ecdh;
1917 if ((EC_KEY_get0_public_key(ecdh) == NULL) ||
1918 (EC_KEY_get0_private_key(ecdh) == NULL) ||
1919 (s->options & SSL_OP_SINGLE_ECDH_USE)) {
1920 if (!EC_KEY_generate_key(ecdh)) {
1921 SSLerr(SSL_F_TLS_CONSTRUCT_SERVER_KEY_EXCHANGE,
1927 if (((group = EC_KEY_get0_group(ecdh)) == NULL) ||
1928 (EC_KEY_get0_public_key(ecdh) == NULL) ||
1929 (EC_KEY_get0_private_key(ecdh) == NULL)) {
1930 SSLerr(SSL_F_TLS_CONSTRUCT_SERVER_KEY_EXCHANGE, ERR_R_ECDH_LIB);
1934 if (SSL_C_IS_EXPORT(s->s3->tmp.new_cipher) &&
1935 (EC_GROUP_get_degree(group) > 163)) {
1936 SSLerr(SSL_F_TLS_CONSTRUCT_SERVER_KEY_EXCHANGE,
1937 SSL_R_ECGROUP_TOO_LARGE_FOR_CIPHER);
1942 * XXX: For now, we only support ephemeral ECDH keys over named
1943 * (not generic) curves. For supported named curves, curve_id is
1947 tls1_ec_nid2curve_id(EC_GROUP_get_curve_name(group)))
1949 SSLerr(SSL_F_TLS_CONSTRUCT_SERVER_KEY_EXCHANGE,
1950 SSL_R_UNSUPPORTED_ELLIPTIC_CURVE);
1955 * Encode the public key. First check the size of encoding and
1956 * allocate memory accordingly.
1958 encodedlen = EC_POINT_point2oct(group,
1959 EC_KEY_get0_public_key(ecdh),
1960 POINT_CONVERSION_UNCOMPRESSED,
1963 encodedPoint = (unsigned char *)
1964 OPENSSL_malloc(encodedlen * sizeof(unsigned char));
1965 bn_ctx = BN_CTX_new();
1966 if ((encodedPoint == NULL) || (bn_ctx == NULL)) {
1967 SSLerr(SSL_F_TLS_CONSTRUCT_SERVER_KEY_EXCHANGE,
1968 ERR_R_MALLOC_FAILURE);
1972 encodedlen = EC_POINT_point2oct(group,
1973 EC_KEY_get0_public_key(ecdh),
1974 POINT_CONVERSION_UNCOMPRESSED,
1975 encodedPoint, encodedlen, bn_ctx);
1977 if (encodedlen == 0) {
1978 SSLerr(SSL_F_TLS_CONSTRUCT_SERVER_KEY_EXCHANGE, ERR_R_ECDH_LIB);
1982 BN_CTX_free(bn_ctx);
1986 * XXX: For now, we only support named (not generic) curves in
1987 * ECDH ephemeral key exchanges. In this situation, we need four
1988 * additional bytes to encode the entire ServerECDHParams
1991 n += 4 + encodedlen;
1994 * We'll generate the serverKeyExchange message explicitly so we
1995 * can set these to NULLs
2002 #endif /* !OPENSSL_NO_EC */
2003 #ifndef OPENSSL_NO_SRP
2004 if (type & SSL_kSRP) {
2005 if ((s->srp_ctx.N == NULL) ||
2006 (s->srp_ctx.g == NULL) ||
2007 (s->srp_ctx.s == NULL) || (s->srp_ctx.B == NULL)) {
2008 SSLerr(SSL_F_TLS_CONSTRUCT_SERVER_KEY_EXCHANGE,
2009 SSL_R_MISSING_SRP_PARAM);
2012 r[0] = s->srp_ctx.N;
2013 r[1] = s->srp_ctx.g;
2014 r[2] = s->srp_ctx.s;
2015 r[3] = s->srp_ctx.B;
2019 al = SSL_AD_HANDSHAKE_FAILURE;
2020 SSLerr(SSL_F_TLS_CONSTRUCT_SERVER_KEY_EXCHANGE,
2021 SSL_R_UNKNOWN_KEY_EXCHANGE_TYPE);
2024 for (i = 0; i < 4 && r[i] != NULL; i++) {
2025 nr[i] = BN_num_bytes(r[i]);
2026 #ifndef OPENSSL_NO_SRP
2027 if ((i == 2) && (type & SSL_kSRP))
2034 if (!(s->s3->tmp.new_cipher->algorithm_auth & (SSL_aNULL|SSL_aSRP))
2035 && !(s->s3->tmp.new_cipher->algorithm_mkey & SSL_PSK)) {
2036 if ((pkey = ssl_get_sign_pkey(s, s->s3->tmp.new_cipher, &md))
2038 al = SSL_AD_DECODE_ERROR;
2041 kn = EVP_PKEY_size(pkey);
2047 if (!BUF_MEM_grow_clean(buf, n + SSL_HM_HEADER_LENGTH(s) + kn)) {
2048 SSLerr(SSL_F_TLS_CONSTRUCT_SERVER_KEY_EXCHANGE, ERR_LIB_BUF);
2051 d = p = ssl_handshake_start(s);
2053 #ifndef OPENSSL_NO_PSK
2054 if (type & SSL_PSK) {
2055 /* copy PSK identity hint */
2056 if (s->cert->psk_identity_hint) {
2057 s2n(strlen(s->cert->psk_identity_hint), p);
2058 strncpy((char *)p, s->cert->psk_identity_hint,
2059 strlen(s->cert->psk_identity_hint));
2060 p += strlen(s->cert->psk_identity_hint);
2067 for (i = 0; i < 4 && r[i] != NULL; i++) {
2068 #ifndef OPENSSL_NO_SRP
2069 if ((i == 2) && (type & SSL_kSRP)) {
2079 #ifndef OPENSSL_NO_EC
2080 if (type & (SSL_kECDHE | SSL_kECDHEPSK)) {
2082 * XXX: For now, we only support named (not generic) curves. In
2083 * this situation, the serverKeyExchange message has: [1 byte
2084 * CurveType], [2 byte CurveName] [1 byte length of encoded
2085 * point], followed by the actual encoded point itself
2087 *p = NAMED_CURVE_TYPE;
2095 memcpy(p, encodedPoint, encodedlen);
2096 OPENSSL_free(encodedPoint);
2097 encodedPoint = NULL;
2105 * n is the length of the params, they start at &(d[4]) and p
2106 * points to the space at the end.
2108 #ifndef OPENSSL_NO_RSA
2109 if (pkey->type == EVP_PKEY_RSA && !SSL_USE_SIGALGS(s)) {
2112 for (num = 2; num > 0; num--) {
2113 EVP_MD_CTX_set_flags(&md_ctx,
2114 EVP_MD_CTX_FLAG_NON_FIPS_ALLOW);
2115 EVP_DigestInit_ex(&md_ctx, (num == 2)
2116 ? s->ctx->md5 : s->ctx->sha1, NULL);
2117 EVP_DigestUpdate(&md_ctx, &(s->s3->client_random[0]),
2119 EVP_DigestUpdate(&md_ctx, &(s->s3->server_random[0]),
2121 EVP_DigestUpdate(&md_ctx, d, n);
2122 EVP_DigestFinal_ex(&md_ctx, q, (unsigned int *)&i);
2126 if (RSA_sign(NID_md5_sha1, md_buf, j,
2127 &(p[2]), &u, pkey->pkey.rsa) <= 0) {
2128 SSLerr(SSL_F_TLS_CONSTRUCT_SERVER_KEY_EXCHANGE, ERR_LIB_RSA);
2136 /* send signature algorithm */
2137 if (SSL_USE_SIGALGS(s)) {
2138 if (!tls12_get_sigandhash(p, pkey, md)) {
2139 /* Should never happen */
2140 al = SSL_AD_INTERNAL_ERROR;
2141 SSLerr(SSL_F_TLS_CONSTRUCT_SERVER_KEY_EXCHANGE,
2142 ERR_R_INTERNAL_ERROR);
2148 fprintf(stderr, "Using hash %s\n", EVP_MD_name(md));
2150 EVP_SignInit_ex(&md_ctx, md, NULL);
2151 EVP_SignUpdate(&md_ctx, &(s->s3->client_random[0]),
2153 EVP_SignUpdate(&md_ctx, &(s->s3->server_random[0]),
2155 EVP_SignUpdate(&md_ctx, d, n);
2156 if (!EVP_SignFinal(&md_ctx, &(p[2]),
2157 (unsigned int *)&i, pkey)) {
2158 SSLerr(SSL_F_TLS_CONSTRUCT_SERVER_KEY_EXCHANGE, ERR_LIB_EVP);
2163 if (SSL_USE_SIGALGS(s))
2166 /* Is this error check actually needed? */
2167 al = SSL_AD_HANDSHAKE_FAILURE;
2168 SSLerr(SSL_F_TLS_CONSTRUCT_SERVER_KEY_EXCHANGE,
2169 SSL_R_UNKNOWN_PKEY_TYPE);
2174 if (!ssl_set_handshake_header(s, SSL3_MT_SERVER_KEY_EXCHANGE, n)) {
2175 al = SSL_AD_HANDSHAKE_FAILURE;
2176 SSLerr(SSL_F_TLS_CONSTRUCT_SERVER_KEY_EXCHANGE, ERR_R_INTERNAL_ERROR);
2180 EVP_MD_CTX_cleanup(&md_ctx);
2183 ssl3_send_alert(s, SSL3_AL_FATAL, al);
2185 #ifndef OPENSSL_NO_EC
2186 OPENSSL_free(encodedPoint);
2187 BN_CTX_free(bn_ctx);
2189 EVP_MD_CTX_cleanup(&md_ctx);
2190 statem_set_error(s);
2194 int tls_construct_certificate_request(SSL *s)
2196 unsigned char *p, *d;
2197 int i, j, nl, off, n;
2198 STACK_OF(X509_NAME) *sk = NULL;
2204 d = p = ssl_handshake_start(s);
2206 /* get the list of acceptable cert types */
2208 n = ssl3_get_req_cert_type(s, p);
2213 if (SSL_USE_SIGALGS(s)) {
2214 const unsigned char *psigs;
2215 unsigned char *etmp = p;
2216 nl = tls12_get_psigalgs(s, &psigs);
2217 /* Skip over length for now */
2219 nl = tls12_copy_sigalgs(s, p, psigs, nl);
2220 /* Now fill in length */
2230 sk = SSL_get_client_CA_list(s);
2233 for (i = 0; i < sk_X509_NAME_num(sk); i++) {
2234 name = sk_X509_NAME_value(sk, i);
2235 j = i2d_X509_NAME(name, NULL);
2236 if (!BUF_MEM_grow_clean
2237 (buf, SSL_HM_HEADER_LENGTH(s) + n + j + 2)) {
2238 SSLerr(SSL_F_TLS_CONSTRUCT_CERTIFICATE_REQUEST,
2242 p = ssl_handshake_start(s) + n;
2244 i2d_X509_NAME(name, &p);
2249 /* else no CA names */
2250 p = ssl_handshake_start(s) + off;
2253 if (!ssl_set_handshake_header(s, SSL3_MT_CERTIFICATE_REQUEST, n)) {
2254 SSLerr(SSL_F_TLS_CONSTRUCT_CERTIFICATE_REQUEST, ERR_R_INTERNAL_ERROR);
2258 s->s3->tmp.cert_request = 1;
2262 statem_set_error(s);
2266 enum MSG_PROCESS_RETURN tls_process_client_key_exchange(SSL *s, PACKET *pkt)
2270 unsigned long alg_k;
2271 #ifndef OPENSSL_NO_RSA
2273 EVP_PKEY *pkey = NULL;
2275 #ifndef OPENSSL_NO_DH
2277 DH *dh_srvr, *dh_clnt = NULL;
2279 #ifndef OPENSSL_NO_EC
2280 EC_KEY *srvr_ecdh = NULL;
2281 EVP_PKEY *clnt_pub_pkey = NULL;
2282 EC_POINT *clnt_ecpoint = NULL;
2283 BN_CTX *bn_ctx = NULL;
2285 PACKET enc_premaster;
2286 unsigned char *data, *rsa_decrypt = NULL;
2288 alg_k = s->s3->tmp.new_cipher->algorithm_mkey;
2290 #ifndef OPENSSL_NO_PSK
2291 /* For PSK parse and retrieve identity, obtain PSK key */
2292 if (alg_k & SSL_PSK) {
2293 unsigned char psk[PSK_MAX_PSK_LEN];
2295 PACKET psk_identity;
2297 if (!PACKET_get_length_prefixed_2(pkt, &psk_identity)) {
2298 al = SSL_AD_DECODE_ERROR;
2299 SSLerr(SSL_F_TLS_PROCESS_CLIENT_KEY_EXCHANGE, SSL_R_LENGTH_MISMATCH);
2302 if (PACKET_remaining(&psk_identity) > PSK_MAX_IDENTITY_LEN) {
2303 al = SSL_AD_DECODE_ERROR;
2304 SSLerr(SSL_F_TLS_PROCESS_CLIENT_KEY_EXCHANGE,
2305 SSL_R_DATA_LENGTH_TOO_LONG);
2308 if (s->psk_server_callback == NULL) {
2309 al = SSL_AD_INTERNAL_ERROR;
2310 SSLerr(SSL_F_TLS_PROCESS_CLIENT_KEY_EXCHANGE,
2311 SSL_R_PSK_NO_SERVER_CB);
2315 if (!PACKET_strndup(&psk_identity, &s->session->psk_identity)) {
2316 SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE, ERR_R_INTERNAL_ERROR);
2317 al = SSL_AD_INTERNAL_ERROR;
2321 psklen = s->psk_server_callback(s, s->session->psk_identity,
2324 if (psklen > PSK_MAX_PSK_LEN) {
2325 al = SSL_AD_INTERNAL_ERROR;
2326 SSLerr(SSL_F_TLS_PROCESS_CLIENT_KEY_EXCHANGE, ERR_R_INTERNAL_ERROR);
2328 } else if (psklen == 0) {
2330 * PSK related to the given identity not found
2332 SSLerr(SSL_F_TLS_PROCESS_CLIENT_KEY_EXCHANGE,
2333 SSL_R_PSK_IDENTITY_NOT_FOUND);
2334 al = SSL_AD_UNKNOWN_PSK_IDENTITY;
2338 OPENSSL_free(s->s3->tmp.psk);
2339 s->s3->tmp.psk = BUF_memdup(psk, psklen);
2340 OPENSSL_cleanse(psk, psklen);
2342 if (s->s3->tmp.psk == NULL) {
2343 al = SSL_AD_INTERNAL_ERROR;
2344 SSLerr(SSL_F_TLS_PROCESS_CLIENT_KEY_EXCHANGE, ERR_R_MALLOC_FAILURE);
2348 s->s3->tmp.psklen = psklen;
2350 if (alg_k & SSL_kPSK) {
2351 /* Identity extracted earlier: should be nothing left */
2352 if (PACKET_remaining(pkt) != 0) {
2353 al = SSL_AD_HANDSHAKE_FAILURE;
2354 SSLerr(SSL_F_TLS_PROCESS_CLIENT_KEY_EXCHANGE, SSL_R_LENGTH_MISMATCH);
2357 /* PSK handled by ssl_generate_master_secret */
2358 if (!ssl_generate_master_secret(s, NULL, 0, 0)) {
2359 al = SSL_AD_INTERNAL_ERROR;
2360 SSLerr(SSL_F_TLS_PROCESS_CLIENT_KEY_EXCHANGE, ERR_R_INTERNAL_ERROR);
2365 #ifndef OPENSSL_NO_RSA
2366 if (alg_k & (SSL_kRSA | SSL_kRSAPSK)) {
2367 unsigned char rand_premaster_secret[SSL_MAX_MASTER_KEY_LENGTH];
2369 unsigned char decrypt_good, version_good;
2372 /* FIX THIS UP EAY EAY EAY EAY */
2373 if (s->s3->tmp.use_rsa_tmp) {
2374 if ((s->cert != NULL) && (s->cert->rsa_tmp != NULL))
2375 rsa = s->cert->rsa_tmp;
2377 * Don't do a callback because rsa_tmp should be sent already
2380 al = SSL_AD_HANDSHAKE_FAILURE;
2381 SSLerr(SSL_F_TLS_PROCESS_CLIENT_KEY_EXCHANGE,
2382 SSL_R_MISSING_TMP_RSA_PKEY);
2387 pkey = s->cert->pkeys[SSL_PKEY_RSA_ENC].privatekey;
2388 if ((pkey == NULL) ||
2389 (pkey->type != EVP_PKEY_RSA) || (pkey->pkey.rsa == NULL)) {
2390 al = SSL_AD_HANDSHAKE_FAILURE;
2391 SSLerr(SSL_F_TLS_PROCESS_CLIENT_KEY_EXCHANGE,
2392 SSL_R_MISSING_RSA_CERTIFICATE);
2395 rsa = pkey->pkey.rsa;
2398 /* SSLv3 and pre-standard DTLS omit the length bytes. */
2399 if (s->version == SSL3_VERSION || s->version == DTLS1_BAD_VER) {
2400 enc_premaster = *pkt;
2403 if (!PACKET_get_length_prefixed_2(pkt, &enc_premaster)
2404 || PACKET_remaining(pkt) != 0) {
2405 /* Try SSLv3 behaviour for TLS. */
2406 if (s->options & SSL_OP_TLS_D5_BUG) {
2407 enc_premaster = orig;
2409 al = SSL_AD_DECODE_ERROR;
2410 SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE, SSL_R_LENGTH_MISMATCH);
2417 * We want to be sure that the plaintext buffer size makes it safe to
2418 * iterate over the entire size of a premaster secret
2419 * (SSL_MAX_MASTER_KEY_LENGTH). Reject overly short RSA keys because
2420 * their ciphertext cannot accommodate a premaster secret anyway.
2422 if (RSA_size(rsa) < SSL_MAX_MASTER_KEY_LENGTH) {
2423 al = SSL_AD_INTERNAL_ERROR;
2424 SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,
2425 RSA_R_KEY_SIZE_TOO_SMALL);
2429 rsa_decrypt = OPENSSL_malloc(RSA_size(rsa));
2430 if (rsa_decrypt == NULL) {
2431 al = SSL_AD_INTERNAL_ERROR;
2432 SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE, ERR_R_MALLOC_FAILURE);
2437 * We must not leak whether a decryption failure occurs because of
2438 * Bleichenbacher's attack on PKCS #1 v1.5 RSA padding (see RFC 2246,
2439 * section 7.4.7.1). The code follows that advice of the TLS RFC and
2440 * generates a random premaster secret for the case that the decrypt
2441 * fails. See https://tools.ietf.org/html/rfc5246#section-7.4.7.1
2444 if (RAND_bytes(rand_premaster_secret,
2445 sizeof(rand_premaster_secret)) <= 0) {
2449 decrypt_len = RSA_private_decrypt(PACKET_remaining(&enc_premaster),
2450 PACKET_data(&enc_premaster),
2451 rsa_decrypt, rsa, RSA_PKCS1_PADDING);
2455 * decrypt_len should be SSL_MAX_MASTER_KEY_LENGTH. decrypt_good will
2456 * be 0xff if so and zero otherwise.
2459 constant_time_eq_int_8(decrypt_len, SSL_MAX_MASTER_KEY_LENGTH);
2462 * If the version in the decrypted pre-master secret is correct then
2463 * version_good will be 0xff, otherwise it'll be zero. The
2464 * Klima-Pokorny-Rosa extension of Bleichenbacher's attack
2465 * (http://eprint.iacr.org/2003/052/) exploits the version number
2466 * check as a "bad version oracle". Thus version checks are done in
2467 * constant time and are treated like any other decryption error.
2470 constant_time_eq_8(rsa_decrypt[0],
2471 (unsigned)(s->client_version >> 8));
2473 constant_time_eq_8(rsa_decrypt[1],
2474 (unsigned)(s->client_version & 0xff));
2477 * The premaster secret must contain the same version number as the
2478 * ClientHello to detect version rollback attacks (strangely, the
2479 * protocol does not offer such protection for DH ciphersuites).
2480 * However, buggy clients exist that send the negotiated protocol
2481 * version instead if the server does not support the requested
2482 * protocol version. If SSL_OP_TLS_ROLLBACK_BUG is set, tolerate such
2485 if (s->options & SSL_OP_TLS_ROLLBACK_BUG) {
2486 unsigned char workaround_good;
2488 constant_time_eq_8(rsa_decrypt[0], (unsigned)(s->version >> 8));
2490 constant_time_eq_8(rsa_decrypt[1],
2491 (unsigned)(s->version & 0xff));
2492 version_good |= workaround_good;
2496 * Both decryption and version must be good for decrypt_good to
2497 * remain non-zero (0xff).
2499 decrypt_good &= version_good;
2502 * Now copy rand_premaster_secret over from p using
2503 * decrypt_good_mask. If decryption failed, then p does not
2504 * contain valid plaintext, however, a check above guarantees
2505 * it is still sufficiently large to read from.
2507 for (j = 0; j < sizeof(rand_premaster_secret); j++) {
2509 constant_time_select_8(decrypt_good, rsa_decrypt[j],
2510 rand_premaster_secret[j]);
2513 if (!ssl_generate_master_secret(s, rsa_decrypt,
2514 sizeof(rand_premaster_secret), 0)) {
2515 al = SSL_AD_INTERNAL_ERROR;
2516 SSLerr(SSL_F_TLS_PROCESS_CLIENT_KEY_EXCHANGE, ERR_R_INTERNAL_ERROR);
2519 OPENSSL_free(rsa_decrypt);
2523 #ifndef OPENSSL_NO_DH
2524 if (alg_k & (SSL_kDHE | SSL_kDHr | SSL_kDHd | SSL_kDHEPSK)) {
2526 EVP_PKEY *skey = NULL;
2527 PACKET bookmark = *pkt;
2528 unsigned char shared[(OPENSSL_DH_MAX_MODULUS_BITS + 7) / 8];
2530 if (!PACKET_get_net_2(pkt, &i)) {
2531 if (alg_k & (SSL_kDHE | SSL_kDHEPSK)) {
2532 al = SSL_AD_HANDSHAKE_FAILURE;
2533 SSLerr(SSL_F_TLS_PROCESS_CLIENT_KEY_EXCHANGE,
2534 SSL_R_DH_PUBLIC_VALUE_LENGTH_IS_WRONG);
2539 if (PACKET_remaining(pkt) != i) {
2540 if (!(s->options & SSL_OP_SSLEAY_080_CLIENT_DH_BUG)) {
2541 SSLerr(SSL_F_TLS_PROCESS_CLIENT_KEY_EXCHANGE,
2542 SSL_R_DH_PUBLIC_VALUE_LENGTH_IS_WRONG);
2546 i = PACKET_remaining(pkt);
2549 if (alg_k & SSL_kDHr)
2550 idx = SSL_PKEY_DH_RSA;
2551 else if (alg_k & SSL_kDHd)
2552 idx = SSL_PKEY_DH_DSA;
2554 skey = s->cert->pkeys[idx].privatekey;
2555 if ((skey == NULL) ||
2556 (skey->type != EVP_PKEY_DH) || (skey->pkey.dh == NULL)) {
2557 al = SSL_AD_HANDSHAKE_FAILURE;
2558 SSLerr(SSL_F_TLS_PROCESS_CLIENT_KEY_EXCHANGE,
2559 SSL_R_MISSING_RSA_CERTIFICATE);
2562 dh_srvr = skey->pkey.dh;
2563 } else if (s->s3->tmp.dh == NULL) {
2564 al = SSL_AD_HANDSHAKE_FAILURE;
2565 SSLerr(SSL_F_TLS_PROCESS_CLIENT_KEY_EXCHANGE,
2566 SSL_R_MISSING_TMP_DH_KEY);
2569 dh_srvr = s->s3->tmp.dh;
2571 if (PACKET_remaining(pkt) == 0L) {
2572 /* Get pubkey from cert */
2573 EVP_PKEY *clkey = X509_get_pubkey(s->session->peer);
2575 if (EVP_PKEY_cmp_parameters(clkey, skey) == 1)
2576 dh_clnt = EVP_PKEY_get1_DH(clkey);
2578 if (dh_clnt == NULL) {
2579 al = SSL_AD_HANDSHAKE_FAILURE;
2580 SSLerr(SSL_F_TLS_PROCESS_CLIENT_KEY_EXCHANGE,
2581 SSL_R_MISSING_TMP_DH_KEY);
2584 EVP_PKEY_free(clkey);
2585 pub = dh_clnt->pub_key;
2587 if (!PACKET_get_bytes(pkt, &data, i)) {
2588 /* We already checked we have enough data */
2589 al = SSL_AD_INTERNAL_ERROR;
2590 SSLerr(SSL_F_TLS_PROCESS_CLIENT_KEY_EXCHANGE,
2591 ERR_R_INTERNAL_ERROR);
2594 pub = BN_bin2bn(data, i, NULL);
2597 SSLerr(SSL_F_TLS_PROCESS_CLIENT_KEY_EXCHANGE, SSL_R_BN_LIB);
2601 i = DH_compute_key(shared, pub, dh_srvr);
2604 SSLerr(SSL_F_TLS_PROCESS_CLIENT_KEY_EXCHANGE, ERR_R_DH_LIB);
2609 DH_free(s->s3->tmp.dh);
2610 s->s3->tmp.dh = NULL;
2616 if (!ssl_generate_master_secret(s, shared, i, 0)) {
2617 al = SSL_AD_INTERNAL_ERROR;
2618 SSLerr(SSL_F_TLS_PROCESS_CLIENT_KEY_EXCHANGE, ERR_R_INTERNAL_ERROR);
2622 s->no_cert_verify = 1;
2623 return MSG_PROCESS_CONTINUE_PROCESSING;
2628 #ifndef OPENSSL_NO_EC
2629 if (alg_k & (SSL_kECDHE | SSL_kECDHr | SSL_kECDHe | SSL_kECDHEPSK)) {
2632 const EC_GROUP *group;
2633 const BIGNUM *priv_key;
2634 unsigned char *shared;
2636 /* initialize structures for server's ECDH key pair */
2637 if ((srvr_ecdh = EC_KEY_new()) == NULL) {
2638 SSLerr(SSL_F_TLS_PROCESS_CLIENT_KEY_EXCHANGE, ERR_R_MALLOC_FAILURE);
2642 /* Let's get server private key and group information */
2643 if (alg_k & (SSL_kECDHr | SSL_kECDHe)) {
2644 /* use the certificate */
2645 tkey = s->cert->pkeys[SSL_PKEY_ECC].privatekey->pkey.ec;
2648 * use the ephermeral values we saved when generating the
2649 * ServerKeyExchange msg.
2651 tkey = s->s3->tmp.ecdh;
2654 group = EC_KEY_get0_group(tkey);
2655 priv_key = EC_KEY_get0_private_key(tkey);
2657 if (!EC_KEY_set_group(srvr_ecdh, group) ||
2658 !EC_KEY_set_private_key(srvr_ecdh, priv_key)) {
2659 SSLerr(SSL_F_TLS_PROCESS_CLIENT_KEY_EXCHANGE, ERR_R_EC_LIB);
2663 /* Let's get client's public key */
2664 if ((clnt_ecpoint = EC_POINT_new(group)) == NULL) {
2665 SSLerr(SSL_F_TLS_PROCESS_CLIENT_KEY_EXCHANGE, ERR_R_MALLOC_FAILURE);
2669 if (PACKET_remaining(pkt) == 0L) {
2670 /* Client Publickey was in Client Certificate */
2672 if (alg_k & (SSL_kECDHE | SSL_kECDHEPSK)) {
2673 al = SSL_AD_HANDSHAKE_FAILURE;
2674 SSLerr(SSL_F_TLS_PROCESS_CLIENT_KEY_EXCHANGE,
2675 SSL_R_MISSING_TMP_ECDH_KEY);
2678 if (((clnt_pub_pkey = X509_get_pubkey(s->session->peer))
2679 == NULL) || (clnt_pub_pkey->type != EVP_PKEY_EC)) {
2681 * XXX: For now, we do not support client authentication
2682 * using ECDH certificates so this branch (n == 0L) of the
2683 * code is never executed. When that support is added, we
2684 * ought to ensure the key received in the certificate is
2685 * authorized for key agreement. ECDH_compute_key implicitly
2686 * checks that the two ECDH shares are for the same group.
2688 al = SSL_AD_HANDSHAKE_FAILURE;
2689 SSLerr(SSL_F_TLS_PROCESS_CLIENT_KEY_EXCHANGE,
2690 SSL_R_UNABLE_TO_DECODE_ECDH_CERTS);
2694 if (EC_POINT_copy(clnt_ecpoint,
2695 EC_KEY_get0_public_key(clnt_pub_pkey->
2697 SSLerr(SSL_F_TLS_PROCESS_CLIENT_KEY_EXCHANGE, ERR_R_EC_LIB);
2700 s->no_cert_verify = 1;
2703 * Get client's public key from encoded point in the
2704 * ClientKeyExchange message.
2706 if ((bn_ctx = BN_CTX_new()) == NULL) {
2707 SSLerr(SSL_F_TLS_PROCESS_CLIENT_KEY_EXCHANGE,
2708 ERR_R_MALLOC_FAILURE);
2712 /* Get encoded point length */
2713 if (!PACKET_get_1(pkt, &i)) {
2714 al = SSL_AD_DECODE_ERROR;
2715 SSLerr(SSL_F_TLS_PROCESS_CLIENT_KEY_EXCHANGE,
2716 SSL_R_LENGTH_MISMATCH);
2719 if (!PACKET_get_bytes(pkt, &data, i)
2720 || PACKET_remaining(pkt) != 0) {
2721 SSLerr(SSL_F_TLS_PROCESS_CLIENT_KEY_EXCHANGE, ERR_R_EC_LIB);
2724 if (EC_POINT_oct2point(group, clnt_ecpoint, data, i, bn_ctx) == 0) {
2725 SSLerr(SSL_F_TLS_PROCESS_CLIENT_KEY_EXCHANGE, ERR_R_EC_LIB);
2730 /* Compute the shared pre-master secret */
2731 field_size = EC_GROUP_get_degree(group);
2732 if (field_size <= 0) {
2733 SSLerr(SSL_F_TLS_PROCESS_CLIENT_KEY_EXCHANGE, ERR_R_ECDH_LIB);
2736 shared = OPENSSL_malloc((field_size + 7) / 8);
2737 if (shared == NULL) {
2738 SSLerr(SSL_F_TLS_PROCESS_CLIENT_KEY_EXCHANGE, ERR_R_MALLOC_FAILURE);
2741 i = ECDH_compute_key(shared, (field_size + 7) / 8, clnt_ecpoint,
2744 SSLerr(SSL_F_TLS_PROCESS_CLIENT_KEY_EXCHANGE, ERR_R_ECDH_LIB);
2745 OPENSSL_free(shared);
2749 EVP_PKEY_free(clnt_pub_pkey);
2750 EC_POINT_free(clnt_ecpoint);
2751 EC_KEY_free(srvr_ecdh);
2752 BN_CTX_free(bn_ctx);
2753 EC_KEY_free(s->s3->tmp.ecdh);
2754 s->s3->tmp.ecdh = NULL;
2756 if (!ssl_generate_master_secret(s, shared, i, 1)) {
2757 al = SSL_AD_INTERNAL_ERROR;
2758 SSLerr(SSL_F_TLS_PROCESS_CLIENT_KEY_EXCHANGE, ERR_R_INTERNAL_ERROR);
2761 return MSG_PROCESS_CONTINUE_PROCESSING;
2764 #ifndef OPENSSL_NO_SRP
2765 if (alg_k & SSL_kSRP) {
2766 if (!PACKET_get_net_2(pkt, &i)
2767 || !PACKET_get_bytes(pkt, &data, i)) {
2768 al = SSL_AD_DECODE_ERROR;
2769 SSLerr(SSL_F_TLS_PROCESS_CLIENT_KEY_EXCHANGE, SSL_R_BAD_SRP_A_LENGTH);
2772 if ((s->srp_ctx.A = BN_bin2bn(data, i, NULL)) == NULL) {
2773 SSLerr(SSL_F_TLS_PROCESS_CLIENT_KEY_EXCHANGE, ERR_R_BN_LIB);
2776 if (BN_ucmp(s->srp_ctx.A, s->srp_ctx.N) >= 0
2777 || BN_is_zero(s->srp_ctx.A)) {
2778 al = SSL_AD_ILLEGAL_PARAMETER;
2779 SSLerr(SSL_F_TLS_PROCESS_CLIENT_KEY_EXCHANGE,
2780 SSL_R_BAD_SRP_PARAMETERS);
2783 OPENSSL_free(s->session->srp_username);
2784 s->session->srp_username = BUF_strdup(s->srp_ctx.login);
2785 if (s->session->srp_username == NULL) {
2786 SSLerr(SSL_F_TLS_PROCESS_CLIENT_KEY_EXCHANGE, ERR_R_MALLOC_FAILURE);
2790 if (!srp_generate_server_master_secret(s)) {
2791 SSLerr(SSL_F_TLS_PROCESS_CLIENT_KEY_EXCHANGE, ERR_R_INTERNAL_ERROR);
2795 #endif /* OPENSSL_NO_SRP */
2796 if (alg_k & SSL_kGOST) {
2797 EVP_PKEY_CTX *pkey_ctx;
2798 EVP_PKEY *client_pub_pkey = NULL, *pk = NULL;
2799 unsigned char premaster_secret[32], *start;
2800 size_t outlen = 32, inlen;
2801 unsigned long alg_a;
2806 /* Get our certificate private key */
2807 alg_a = s->s3->tmp.new_cipher->algorithm_auth;
2808 if (alg_a & SSL_aGOST01)
2809 pk = s->cert->pkeys[SSL_PKEY_GOST01].privatekey;
2811 pkey_ctx = EVP_PKEY_CTX_new(pk, NULL);
2812 EVP_PKEY_decrypt_init(pkey_ctx);
2814 * If client certificate is present and is of the same type, maybe
2815 * use it for key exchange. Don't mind errors from
2816 * EVP_PKEY_derive_set_peer, because it is completely valid to use a
2817 * client certificate for authorization only.
2819 client_pub_pkey = X509_get_pubkey(s->session->peer);
2820 if (client_pub_pkey) {
2821 if (EVP_PKEY_derive_set_peer(pkey_ctx, client_pub_pkey) <= 0)
2824 /* Decrypt session key */
2825 sess_key_len = PACKET_remaining(pkt);
2826 if (!PACKET_get_bytes(pkt, &data, sess_key_len)) {
2827 al = SSL_AD_INTERNAL_ERROR;
2828 SSLerr(SSL_F_TLS_PROCESS_CLIENT_KEY_EXCHANGE, ERR_R_INTERNAL_ERROR);
2831 if (ASN1_get_object ((const unsigned char **)&data, &Tlen, &Ttag,
2832 &Tclass, sess_key_len) != V_ASN1_CONSTRUCTED
2833 || Ttag != V_ASN1_SEQUENCE
2834 || Tclass != V_ASN1_UNIVERSAL) {
2835 SSLerr(SSL_F_TLS_PROCESS_CLIENT_KEY_EXCHANGE,
2836 SSL_R_DECRYPTION_FAILED);
2841 if (EVP_PKEY_decrypt
2842 (pkey_ctx, premaster_secret, &outlen, start, inlen) <= 0) {
2843 SSLerr(SSL_F_TLS_PROCESS_CLIENT_KEY_EXCHANGE,
2844 SSL_R_DECRYPTION_FAILED);
2847 /* Generate master secret */
2848 if (!ssl_generate_master_secret(s, premaster_secret,
2849 sizeof(premaster_secret), 0)) {
2850 al = SSL_AD_INTERNAL_ERROR;
2851 SSLerr(SSL_F_TLS_PROCESS_CLIENT_KEY_EXCHANGE, ERR_R_INTERNAL_ERROR);
2854 /* Check if pubkey from client certificate was used */
2855 if (EVP_PKEY_CTX_ctrl
2856 (pkey_ctx, -1, -1, EVP_PKEY_CTRL_PEER_KEY, 2, NULL) > 0)
2857 s->no_cert_verify = 1;
2859 EVP_PKEY_free(client_pub_pkey);
2860 EVP_PKEY_CTX_free(pkey_ctx);
2861 return MSG_PROCESS_CONTINUE_PROCESSING;
2863 EVP_PKEY_free(client_pub_pkey);
2864 EVP_PKEY_CTX_free(pkey_ctx);
2867 al = SSL_AD_HANDSHAKE_FAILURE;
2868 SSLerr(SSL_F_TLS_PROCESS_CLIENT_KEY_EXCHANGE, SSL_R_UNKNOWN_CIPHER_TYPE);
2872 return MSG_PROCESS_CONTINUE_PROCESSING;
2874 ssl3_send_alert(s, SSL3_AL_FATAL, al);
2875 #if !defined(OPENSSL_NO_DH) || !defined(OPENSSL_NO_RSA) || !defined(OPENSSL_NO_EC) || defined(OPENSSL_NO_SRP)
2878 #ifndef OPENSSL_NO_EC
2879 EVP_PKEY_free(clnt_pub_pkey);
2880 EC_POINT_free(clnt_ecpoint);
2881 EC_KEY_free(srvr_ecdh);
2882 BN_CTX_free(bn_ctx);
2883 OPENSSL_free(rsa_decrypt);
2885 #ifndef OPENSSL_NO_PSK
2886 OPENSSL_clear_free(s->s3->tmp.psk, s->s3->tmp.psklen);
2887 s->s3->tmp.psk = NULL;
2889 statem_set_error(s);
2890 return MSG_PROCESS_ERROR;
2893 enum WORK_STATE tls_post_process_client_key_exchange(SSL *s,
2894 enum WORK_STATE wst)
2896 #ifndef OPENSSL_NO_SCTP
2897 if (wst == WORK_MORE_A) {
2898 if (SSL_IS_DTLS(s)) {
2899 unsigned char sctpauthkey[64];
2900 char labelbuffer[sizeof(DTLS1_SCTP_AUTH_LABEL)];
2902 * Add new shared key for SCTP-Auth, will be ignored if no SCTP
2905 snprintf((char *)labelbuffer, sizeof(DTLS1_SCTP_AUTH_LABEL),
2906 DTLS1_SCTP_AUTH_LABEL);
2908 if (SSL_export_keying_material(s, sctpauthkey,
2909 sizeof(sctpauthkey), labelbuffer,
2910 sizeof(labelbuffer), NULL, 0, 0) <= 0) {
2911 statem_set_error(s);
2915 BIO_ctrl(SSL_get_wbio(s), BIO_CTRL_DGRAM_SCTP_ADD_AUTH_KEY,
2916 sizeof(sctpauthkey), sctpauthkey);
2921 if ((wst == WORK_MORE_B)
2923 && BIO_dgram_is_sctp(SSL_get_wbio(s))
2924 /* Are we renegotiating? */
2926 /* Are we going to skip the CertificateVerify? */
2927 && (s->session->peer == NULL || s->no_cert_verify)
2928 && BIO_dgram_sctp_msg_waiting(SSL_get_rbio(s))) {
2929 s->s3->in_read_app_data = 2;
2930 s->rwstate = SSL_READING;
2931 BIO_clear_retry_flags(SSL_get_rbio(s));
2932 BIO_set_retry_read(SSL_get_rbio(s));
2933 statem_set_sctp_read_sock(s, 1);
2936 statem_set_sctp_read_sock(s, 0);
2940 if (s->no_cert_verify) {
2941 /* No certificate verify so we no longer need the handshake_buffer */
2942 BIO_free(s->s3->handshake_buffer);
2943 return WORK_FINISHED_CONTINUE;
2944 } else if (SSL_USE_SIGALGS(s)) {
2945 if (!s->session->peer) {
2946 /* No peer certificate so we no longer need the handshake_buffer */
2947 BIO_free(s->s3->handshake_buffer);
2948 return WORK_FINISHED_CONTINUE;
2950 if (!s->s3->handshake_buffer) {
2951 SSLerr(SSL_F_TLS_POST_PROCESS_CLIENT_KEY_EXCHANGE,
2952 ERR_R_INTERNAL_ERROR);
2953 statem_set_error(s);
2957 * For sigalgs freeze the handshake buffer. If we support
2958 * extms we've done this already so this is a no-op
2960 if (!ssl3_digest_cached_records(s, 1)) {
2961 statem_set_error(s);
2969 * We need to get hashes here so if there is a client cert,
2970 * it can be verified FIXME - digest processing for
2971 * CertificateVerify should be generalized. But it is next
2974 if (!ssl3_digest_cached_records(s, 0)) {
2975 statem_set_error(s);
2978 for (dgst_num = 0; dgst_num < SSL_MAX_DIGEST; dgst_num++) {
2979 if (s->s3->handshake_dgst[dgst_num]) {
2982 s->method->ssl3_enc->cert_verify_mac(s,
2991 EVP_MD_CTX_size(s->s3->handshake_dgst[dgst_num]);
2992 if (dgst_size < 0) {
2993 statem_set_error(s);
2996 offset += dgst_size;
3001 return WORK_FINISHED_CONTINUE;
3004 enum MSG_PROCESS_RETURN tls_process_cert_verify(SSL *s, PACKET *pkt)
3006 EVP_PKEY *pkey = NULL;
3007 unsigned char *sig, *data;
3008 int al, ret = MSG_PROCESS_ERROR;
3012 const EVP_MD *md = NULL;
3014 EVP_MD_CTX_init(&mctx);
3016 peer = s->session->peer;
3017 pkey = X509_get_pubkey(peer);
3018 type = X509_certificate_type(peer, pkey);
3020 if (!(type & EVP_PKT_SIGN)) {
3021 SSLerr(SSL_F_TLS_PROCESS_CERT_VERIFY,
3022 SSL_R_SIGNATURE_FOR_NON_SIGNING_CERTIFICATE);
3023 al = SSL_AD_ILLEGAL_PARAMETER;
3027 /* Check for broken implementations of GOST ciphersuites */
3029 * If key is GOST and n is exactly 64, it is bare signature without
3032 if (PACKET_remaining(pkt) == 64 && pkey->type == NID_id_GostR3410_2001) {
3035 if (SSL_USE_SIGALGS(s)) {
3038 if (!PACKET_get_bytes(pkt, &sig, 2)) {
3039 al = SSL_AD_DECODE_ERROR;
3042 rv = tls12_check_peer_sigalg(&md, s, sig, pkey);
3044 al = SSL_AD_INTERNAL_ERROR;
3046 } else if (rv == 0) {
3047 al = SSL_AD_DECODE_ERROR;
3051 fprintf(stderr, "USING TLSv1.2 HASH %s\n", EVP_MD_name(md));
3054 if (!PACKET_get_net_2(pkt, &len)) {
3055 SSLerr(SSL_F_TLS_PROCESS_CERT_VERIFY, SSL_R_LENGTH_MISMATCH);
3056 al = SSL_AD_DECODE_ERROR;
3060 j = EVP_PKEY_size(pkey);
3061 if (((int)len > j) || ((int)PACKET_remaining(pkt) > j)
3062 || (PACKET_remaining(pkt) == 0)) {
3063 SSLerr(SSL_F_TLS_PROCESS_CERT_VERIFY, SSL_R_WRONG_SIGNATURE_SIZE);
3064 al = SSL_AD_DECODE_ERROR;
3067 if (!PACKET_get_bytes(pkt, &data, len)) {
3068 SSLerr(SSL_F_TLS_PROCESS_CERT_VERIFY, SSL_R_LENGTH_MISMATCH);
3069 al = SSL_AD_DECODE_ERROR;
3073 if (SSL_USE_SIGALGS(s)) {
3076 hdatalen = BIO_get_mem_data(s->s3->handshake_buffer, &hdata);
3077 if (hdatalen <= 0) {
3078 SSLerr(SSL_F_TLS_PROCESS_CERT_VERIFY, ERR_R_INTERNAL_ERROR);
3079 al = SSL_AD_INTERNAL_ERROR;
3083 fprintf(stderr, "Using TLS 1.2 with client verify alg %s\n",
3086 if (!EVP_VerifyInit_ex(&mctx, md, NULL)
3087 || !EVP_VerifyUpdate(&mctx, hdata, hdatalen)) {
3088 SSLerr(SSL_F_TLS_PROCESS_CERT_VERIFY, ERR_R_EVP_LIB);
3089 al = SSL_AD_INTERNAL_ERROR;
3093 if (EVP_VerifyFinal(&mctx, data, len, pkey) <= 0) {
3094 al = SSL_AD_DECRYPT_ERROR;
3095 SSLerr(SSL_F_TLS_PROCESS_CERT_VERIFY, SSL_R_BAD_SIGNATURE);
3099 #ifndef OPENSSL_NO_RSA
3100 if (pkey->type == EVP_PKEY_RSA) {
3101 i = RSA_verify(NID_md5_sha1, s->s3->tmp.cert_verify_md,
3102 MD5_DIGEST_LENGTH + SHA_DIGEST_LENGTH, data, len,
3105 al = SSL_AD_DECRYPT_ERROR;
3106 SSLerr(SSL_F_TLS_PROCESS_CERT_VERIFY, SSL_R_BAD_RSA_DECRYPT);
3110 al = SSL_AD_DECRYPT_ERROR;
3111 SSLerr(SSL_F_TLS_PROCESS_CERT_VERIFY, SSL_R_BAD_RSA_SIGNATURE);
3116 #ifndef OPENSSL_NO_DSA
3117 if (pkey->type == EVP_PKEY_DSA) {
3118 j = DSA_verify(pkey->save_type,
3119 &(s->s3->tmp.cert_verify_md[MD5_DIGEST_LENGTH]),
3120 SHA_DIGEST_LENGTH, data, len, pkey->pkey.dsa);
3123 al = SSL_AD_DECRYPT_ERROR;
3124 SSLerr(SSL_F_TLS_PROCESS_CERT_VERIFY, SSL_R_BAD_DSA_SIGNATURE);
3129 #ifndef OPENSSL_NO_EC
3130 if (pkey->type == EVP_PKEY_EC) {
3131 j = ECDSA_verify(pkey->save_type,
3132 &(s->s3->tmp.cert_verify_md[MD5_DIGEST_LENGTH]),
3133 SHA_DIGEST_LENGTH, data, len, pkey->pkey.ec);
3136 al = SSL_AD_DECRYPT_ERROR;
3137 SSLerr(SSL_F_TLS_PROCESS_CERT_VERIFY, SSL_R_BAD_ECDSA_SIGNATURE);
3142 if (pkey->type == NID_id_GostR3410_2001) {
3143 unsigned char signature[64];
3145 EVP_PKEY_CTX *pctx = EVP_PKEY_CTX_new(pkey, NULL);
3146 EVP_PKEY_verify_init(pctx);
3148 fprintf(stderr, "GOST signature length is %d", len);
3150 for (idx = 0; idx < 64; idx++) {
3151 signature[63 - idx] = data[idx];
3153 j = EVP_PKEY_verify(pctx, signature, 64, s->s3->tmp.cert_verify_md,
3155 EVP_PKEY_CTX_free(pctx);
3157 al = SSL_AD_DECRYPT_ERROR;
3158 SSLerr(SSL_F_TLS_PROCESS_CERT_VERIFY, SSL_R_BAD_ECDSA_SIGNATURE);
3162 SSLerr(SSL_F_TLS_PROCESS_CERT_VERIFY, ERR_R_INTERNAL_ERROR);
3163 al = SSL_AD_UNSUPPORTED_CERTIFICATE;
3167 ret = MSG_PROCESS_CONTINUE_PROCESSING;
3170 ssl3_send_alert(s, SSL3_AL_FATAL, al);
3171 statem_set_error(s);
3173 BIO_free(s->s3->handshake_buffer);
3174 s->s3->handshake_buffer = NULL;
3175 EVP_MD_CTX_cleanup(&mctx);
3176 EVP_PKEY_free(pkey);
3180 enum MSG_PROCESS_RETURN tls_process_client_certificate(SSL *s, PACKET *pkt)
3182 int i, al, ret = MSG_PROCESS_ERROR;
3184 unsigned long l, llen;
3185 const unsigned char *certstart;
3186 unsigned char *certbytes;
3187 STACK_OF(X509) *sk = NULL;
3190 if ((sk = sk_X509_new_null()) == NULL) {
3191 SSLerr(SSL_F_TLS_PROCESS_CLIENT_CERTIFICATE, ERR_R_MALLOC_FAILURE);
3195 if (!PACKET_get_net_3(pkt, &llen)
3196 || !PACKET_get_sub_packet(pkt, &spkt, llen)
3197 || PACKET_remaining(pkt) != 0) {
3198 al = SSL_AD_DECODE_ERROR;
3199 SSLerr(SSL_F_TLS_PROCESS_CLIENT_CERTIFICATE, SSL_R_LENGTH_MISMATCH);
3203 while (PACKET_remaining(&spkt) > 0) {
3204 if (!PACKET_get_net_3(&spkt, &l)
3205 || !PACKET_get_bytes(&spkt, &certbytes, l)) {
3206 al = SSL_AD_DECODE_ERROR;
3207 SSLerr(SSL_F_TLS_PROCESS_CLIENT_CERTIFICATE,
3208 SSL_R_CERT_LENGTH_MISMATCH);
3212 certstart = certbytes;
3213 x = d2i_X509(NULL, (const unsigned char **)&certbytes, l);
3215 SSLerr(SSL_F_TLS_PROCESS_CLIENT_CERTIFICATE, ERR_R_ASN1_LIB);
3218 if (certbytes != (certstart + l)) {
3219 al = SSL_AD_DECODE_ERROR;
3220 SSLerr(SSL_F_TLS_PROCESS_CLIENT_CERTIFICATE,
3221 SSL_R_CERT_LENGTH_MISMATCH);
3224 if (!sk_X509_push(sk, x)) {
3225 SSLerr(SSL_F_TLS_PROCESS_CLIENT_CERTIFICATE, ERR_R_MALLOC_FAILURE);
3231 if (sk_X509_num(sk) <= 0) {
3232 /* TLS does not mind 0 certs returned */
3233 if (s->version == SSL3_VERSION) {
3234 al = SSL_AD_HANDSHAKE_FAILURE;
3235 SSLerr(SSL_F_TLS_PROCESS_CLIENT_CERTIFICATE,
3236 SSL_R_NO_CERTIFICATES_RETURNED);
3239 /* Fail for TLS only if we required a certificate */
3240 else if ((s->verify_mode & SSL_VERIFY_PEER) &&
3241 (s->verify_mode & SSL_VERIFY_FAIL_IF_NO_PEER_CERT)) {
3242 SSLerr(SSL_F_TLS_PROCESS_CLIENT_CERTIFICATE,
3243 SSL_R_PEER_DID_NOT_RETURN_A_CERTIFICATE);
3244 al = SSL_AD_HANDSHAKE_FAILURE;
3247 /* No client certificate so digest cached records */
3248 if (s->s3->handshake_buffer && !ssl3_digest_cached_records(s, 0)) {
3249 al = SSL_AD_INTERNAL_ERROR;
3254 i = ssl_verify_cert_chain(s, sk);
3256 al = ssl_verify_alarm_type(s->verify_result);
3257 SSLerr(SSL_F_TLS_PROCESS_CLIENT_CERTIFICATE,
3258 SSL_R_CERTIFICATE_VERIFY_FAILED);
3262 SSLerr(SSL_F_TLS_PROCESS_CLIENT_CERTIFICATE, i);
3263 al = SSL_AD_HANDSHAKE_FAILURE;
3266 pkey = X509_get_pubkey(sk_X509_value(sk, 0));
3268 al = SSL3_AD_HANDSHAKE_FAILURE;
3269 SSLerr(SSL_F_TLS_PROCESS_CLIENT_CERTIFICATE,
3270 SSL_R_UNKNOWN_CERTIFICATE_TYPE);
3273 EVP_PKEY_free(pkey);
3276 X509_free(s->session->peer);
3277 s->session->peer = sk_X509_shift(sk);
3278 s->session->verify_result = s->verify_result;
3280 sk_X509_pop_free(s->session->peer_chain, X509_free);
3281 s->session->peer_chain = sk;
3283 * Inconsistency alert: cert_chain does *not* include the peer's own
3284 * certificate, while we do include it in s3_clnt.c
3287 ret = MSG_PROCESS_CONTINUE_READING;
3291 ssl3_send_alert(s, SSL3_AL_FATAL, al);
3292 statem_set_error(s);
3295 sk_X509_pop_free(sk, X509_free);
3299 int tls_construct_server_certificate(SSL *s)
3303 cpk = ssl_get_server_send_pkey(s);
3305 SSLerr(SSL_F_TLS_CONSTRUCT_SERVER_CERTIFICATE, ERR_R_INTERNAL_ERROR);
3306 statem_set_error(s);
3310 if (!ssl3_output_cert_chain(s, cpk)) {
3311 SSLerr(SSL_F_TLS_CONSTRUCT_SERVER_CERTIFICATE, ERR_R_INTERNAL_ERROR);
3312 statem_set_error(s);
3319 int tls_construct_new_session_ticket(SSL *s)
3321 unsigned char *senc = NULL;
3324 unsigned char *p, *macstart;
3325 const unsigned char *const_p;
3326 int len, slen_full, slen;
3329 SSL_CTX *tctx = s->initial_ctx;
3330 unsigned char iv[EVP_MAX_IV_LENGTH];
3331 unsigned char key_name[16];
3333 /* get session encoding length */
3334 slen_full = i2d_SSL_SESSION(s->session, NULL);
3336 * Some length values are 16 bits, so forget it if session is too
3339 if (slen_full == 0 || slen_full > 0xFF00) {
3340 statem_set_error(s);
3343 senc = OPENSSL_malloc(slen_full);
3345 statem_set_error(s);
3349 EVP_CIPHER_CTX_init(&ctx);
3350 HMAC_CTX_init(&hctx);
3353 if (!i2d_SSL_SESSION(s->session, &p))
3357 * create a fresh copy (not shared with other threads) to clean up
3360 sess = d2i_SSL_SESSION(NULL, &const_p, slen_full);
3363 sess->session_id_length = 0; /* ID is irrelevant for the ticket */
3365 slen = i2d_SSL_SESSION(sess, NULL);
3366 if (slen == 0 || slen > slen_full) { /* shouldn't ever happen */
3367 SSL_SESSION_free(sess);
3371 if (!i2d_SSL_SESSION(sess, &p)) {
3372 SSL_SESSION_free(sess);
3375 SSL_SESSION_free(sess);
3378 * Grow buffer if need be: the length calculation is as
3379 * follows handshake_header_length +
3380 * 4 (ticket lifetime hint) + 2 (ticket length) +
3381 * 16 (key name) + max_iv_len (iv length) +
3382 * session_length + max_enc_block_size (max encrypted session
3383 * length) + max_md_size (HMAC).
3385 if (!BUF_MEM_grow(s->init_buf,
3386 SSL_HM_HEADER_LENGTH(s) + 22 + EVP_MAX_IV_LENGTH +
3387 EVP_MAX_BLOCK_LENGTH + EVP_MAX_MD_SIZE + slen))
3390 p = ssl_handshake_start(s);
3392 * Initialize HMAC and cipher contexts. If callback present it does
3393 * all the work otherwise use generated values from parent ctx.
3395 if (tctx->tlsext_ticket_key_cb) {
3396 if (tctx->tlsext_ticket_key_cb(s, key_name, iv, &ctx,
3400 if (RAND_bytes(iv, 16) <= 0)
3402 if (!EVP_EncryptInit_ex(&ctx, EVP_aes_128_cbc(), NULL,
3403 tctx->tlsext_tick_aes_key, iv))
3405 if (!HMAC_Init_ex(&hctx, tctx->tlsext_tick_hmac_key, 16,
3406 EVP_sha256(), NULL))
3408 memcpy(key_name, tctx->tlsext_tick_key_name, 16);
3412 * Ticket lifetime hint (advisory only): We leave this unspecified
3413 * for resumed session (for simplicity), and guess that tickets for
3414 * new sessions will live as long as their sessions.
3416 l2n(s->hit ? 0 : s->session->timeout, p);
3418 /* Skip ticket length for now */
3420 /* Output key name */
3422 memcpy(p, key_name, 16);
3425 memcpy(p, iv, EVP_CIPHER_CTX_iv_length(&ctx));
3426 p += EVP_CIPHER_CTX_iv_length(&ctx);
3427 /* Encrypt session data */
3428 if (!EVP_EncryptUpdate(&ctx, p, &len, senc, slen))
3431 if (!EVP_EncryptFinal(&ctx, p, &len))
3435 if (!HMAC_Update(&hctx, macstart, p - macstart))
3437 if (!HMAC_Final(&hctx, p, &hlen))
3440 EVP_CIPHER_CTX_cleanup(&ctx);
3441 HMAC_CTX_cleanup(&hctx);
3444 /* Now write out lengths: p points to end of data written */
3446 len = p - ssl_handshake_start(s);
3447 /* Skip ticket lifetime hint */
3448 p = ssl_handshake_start(s) + 4;
3450 if (!ssl_set_handshake_header(s, SSL3_MT_NEWSESSION_TICKET, len))
3457 EVP_CIPHER_CTX_cleanup(&ctx);
3458 HMAC_CTX_cleanup(&hctx);
3459 statem_set_error(s);
3463 int tls_construct_cert_status(SSL *s)
3467 * Grow buffer if need be: the length calculation is as
3468 * follows 1 (message type) + 3 (message length) +
3469 * 1 (ocsp response type) + 3 (ocsp response length)
3472 if (!BUF_MEM_grow(s->init_buf, 8 + s->tlsext_ocsp_resplen)) {
3473 statem_set_error(s);
3477 p = (unsigned char *)s->init_buf->data;
3480 *(p++) = SSL3_MT_CERTIFICATE_STATUS;
3481 /* message length */
3482 l2n3(s->tlsext_ocsp_resplen + 4, p);
3484 *(p++) = s->tlsext_status_type;
3485 /* length of OCSP response */
3486 l2n3(s->tlsext_ocsp_resplen, p);
3487 /* actual response */
3488 memcpy(p, s->tlsext_ocsp_resp, s->tlsext_ocsp_resplen);
3489 /* number of bytes to write */
3490 s->init_num = 8 + s->tlsext_ocsp_resplen;
3496 #ifndef OPENSSL_NO_NEXTPROTONEG
3498 * tls_process_next_proto reads a Next Protocol Negotiation handshake message.
3499 * It sets the next_proto member in s if found
3501 enum MSG_PROCESS_RETURN tls_process_next_proto(SSL *s, PACKET *pkt)