1 /* Copyright (C) 1995-1998 Eric Young (eay@cryptsoft.com)
4 * This package is an SSL implementation written
5 * by Eric Young (eay@cryptsoft.com).
6 * The implementation was written so as to conform with Netscapes SSL.
8 * This library is free for commercial and non-commercial use as long as
9 * the following conditions are aheared to. The following conditions
10 * apply to all code found in this distribution, be it the RC4, RSA,
11 * lhash, DES, etc., code; not just the SSL code. The SSL documentation
12 * included with this distribution is covered by the same copyright terms
13 * except that the holder is Tim Hudson (tjh@cryptsoft.com).
15 * Copyright remains Eric Young's, and as such any Copyright notices in
16 * the code are not to be removed.
17 * If this package is used in a product, Eric Young should be given attribution
18 * as the author of the parts of the library used.
19 * This can be in the form of a textual message at program startup or
20 * in documentation (online or textual) provided with the package.
22 * Redistribution and use in source and binary forms, with or without
23 * modification, are permitted provided that the following conditions
25 * 1. Redistributions of source code must retain the copyright
26 * notice, this list of conditions and the following disclaimer.
27 * 2. Redistributions in binary form must reproduce the above copyright
28 * notice, this list of conditions and the following disclaimer in the
29 * documentation and/or other materials provided with the distribution.
30 * 3. All advertising materials mentioning features or use of this software
31 * must display the following acknowledgement:
32 * "This product includes cryptographic software written by
33 * Eric Young (eay@cryptsoft.com)"
34 * The word 'cryptographic' can be left out if the rouines from the library
35 * being used are not cryptographic related :-).
36 * 4. If you include any Windows specific code (or a derivative thereof) from
37 * the apps directory (application code) you must include an acknowledgement:
38 * "This product includes software written by Tim Hudson (tjh@cryptsoft.com)"
40 * THIS SOFTWARE IS PROVIDED BY ERIC YOUNG ``AS IS'' AND
41 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
42 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
43 * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
44 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
45 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
46 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
47 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
48 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
49 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
52 * The licence and distribution terms for any publically available version or
53 * derivative of this code cannot be changed. i.e. this code cannot simply be
54 * copied and put under another distribution licence
55 * [including the GNU Public Licence.]
57 /* ====================================================================
58 * Copyright (c) 1998-2007 The OpenSSL Project. All rights reserved.
60 * Redistribution and use in source and binary forms, with or without
61 * modification, are permitted provided that the following conditions
64 * 1. Redistributions of source code must retain the above copyright
65 * notice, this list of conditions and the following disclaimer.
67 * 2. Redistributions in binary form must reproduce the above copyright
68 * notice, this list of conditions and the following disclaimer in
69 * the documentation and/or other materials provided with the
72 * 3. All advertising materials mentioning features or use of this
73 * software must display the following acknowledgment:
74 * "This product includes software developed by the OpenSSL Project
75 * for use in the OpenSSL Toolkit. (http://www.openssl.org/)"
77 * 4. The names "OpenSSL Toolkit" and "OpenSSL Project" must not be used to
78 * endorse or promote products derived from this software without
79 * prior written permission. For written permission, please contact
80 * openssl-core@openssl.org.
82 * 5. Products derived from this software may not be called "OpenSSL"
83 * nor may "OpenSSL" appear in their names without prior written
84 * permission of the OpenSSL Project.
86 * 6. Redistributions of any form whatsoever must retain the following
88 * "This product includes software developed by the OpenSSL Project
89 * for use in the OpenSSL Toolkit (http://www.openssl.org/)"
91 * THIS SOFTWARE IS PROVIDED BY THE OpenSSL PROJECT ``AS IS'' AND ANY
92 * EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
93 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
94 * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE OpenSSL PROJECT OR
95 * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
96 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
97 * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
98 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
99 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
100 * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
101 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
102 * OF THE POSSIBILITY OF SUCH DAMAGE.
103 * ====================================================================
105 * This product includes cryptographic software written by Eric Young
106 * (eay@cryptsoft.com). This product includes software written by Tim
107 * Hudson (tjh@cryptsoft.com).
110 /* ====================================================================
111 * Copyright 2002 Sun Microsystems, Inc. ALL RIGHTS RESERVED.
113 * Portions of the attached software ("Contribution") are developed by
114 * SUN MICROSYSTEMS, INC., and are contributed to the OpenSSL project.
116 * The Contribution is licensed pursuant to the OpenSSL open source
117 * license provided above.
119 * ECC cipher suite support in OpenSSL originally written by
120 * Vipul Gupta and Sumit Gupta of Sun Microsystems Laboratories.
123 /* ====================================================================
124 * Copyright 2005 Nokia. All rights reserved.
126 * The portions of the attached software ("Contribution") is developed by
127 * Nokia Corporation and is licensed pursuant to the OpenSSL open source
130 * The Contribution, originally written by Mika Kousa and Pasi Eronen of
131 * Nokia Corporation, consists of the "PSK" (Pre-Shared Key) ciphersuites
132 * support (see RFC 4279) to OpenSSL.
134 * No patent licenses or other rights except those expressly stated in
135 * the OpenSSL open source license shall be deemed granted or received
136 * expressly, by implication, estoppel, or otherwise.
138 * No assurances are provided by Nokia that the Contribution does not
139 * infringe the patent or other intellectual property rights of any third
140 * party or that the license provides you with all the necessary rights
141 * to make use of the Contribution.
143 * THE SOFTWARE IS PROVIDED "AS IS" WITHOUT WARRANTY OF ANY KIND. IN
144 * ADDITION TO THE DISCLAIMERS INCLUDED IN THE LICENSE, NOKIA
145 * SPECIFICALLY DISCLAIMS ANY LIABILITY FOR CLAIMS BROUGHT BY YOU OR ANY
146 * OTHER ENTITY BASED ON INFRINGEMENT OF INTELLECTUAL PROPERTY RIGHTS OR
149 #define NETSCAPE_HANG_BUG
155 #include <openssl/bn.h>
156 #include <openssl/buf.h>
157 #include <openssl/bytestring.h>
158 #include <openssl/cipher.h>
159 #include <openssl/dh.h>
160 #include <openssl/ec.h>
161 #include <openssl/ecdsa.h>
162 #include <openssl/evp.h>
163 #include <openssl/hmac.h>
164 #include <openssl/md5.h>
165 #include <openssl/mem.h>
166 #include <openssl/obj.h>
167 #include <openssl/rand.h>
168 #include <openssl/sha.h>
169 #include <openssl/x509.h>
171 #include "ssl_locl.h"
172 #include "../crypto/dh/internal.h"
174 static const SSL_METHOD *ssl3_get_server_method(int ver)
179 return TLSv1_2_server_method();
181 return TLSv1_1_server_method();
183 return TLSv1_server_method();
185 return SSLv3_server_method();
191 IMPLEMENT_tls_meth_func(TLS1_2_VERSION, TLSv1_2_server_method,
193 ssl_undefined_function,
194 ssl3_get_server_method,
197 IMPLEMENT_tls_meth_func(TLS1_1_VERSION, TLSv1_1_server_method,
199 ssl_undefined_function,
200 ssl3_get_server_method,
203 IMPLEMENT_tls_meth_func(TLS1_VERSION, TLSv1_server_method,
205 ssl_undefined_function,
206 ssl3_get_server_method,
209 IMPLEMENT_tls_meth_func(SSL3_VERSION, SSLv3_server_method,
211 ssl_undefined_function,
212 ssl3_get_server_method,
215 int ssl3_accept(SSL *s)
219 void (*cb)(const SSL *ssl,int type,int val)=NULL;
221 int new_state,state,skip=0;
224 ERR_clear_system_error();
226 if (s->info_callback != NULL)
228 else if (s->ctx->info_callback != NULL)
229 cb=s->ctx->info_callback;
231 /* init things to blank */
233 if (!SSL_in_init(s) || SSL_in_before(s)) SSL_clear(s);
237 OPENSSL_PUT_ERROR(SSL, ssl3_accept, SSL_R_NO_CERTIFICATE_SET);
247 case SSL_ST_RENEGOTIATE:
249 /* s->state=SSL_ST_ACCEPT; */
253 case SSL_ST_BEFORE|SSL_ST_ACCEPT:
254 case SSL_ST_OK|SSL_ST_ACCEPT:
257 if (cb != NULL) cb(s,SSL_CB_HANDSHAKE_START,1);
259 if ((s->version>>8) != 3)
261 OPENSSL_PUT_ERROR(SSL, ssl3_accept, ERR_R_INTERNAL_ERROR);
264 s->type=SSL_ST_ACCEPT;
266 if (s->init_buf == NULL)
268 if ((buf=BUF_MEM_new()) == NULL)
273 if (!BUF_MEM_grow(buf,SSL3_RT_MAX_PLAIN_LENGTH))
281 if (!ssl3_setup_buffers(s))
289 if (s->state != SSL_ST_RENEGOTIATE)
291 /* Ok, we now need to push on a buffering BIO so that
292 * the output is sent in a way that TCP likes :-)
294 if (!ssl_init_wbio_buffer(s,1)) { ret= -1; goto end; }
296 ssl3_init_finished_mac(s);
297 s->state=SSL3_ST_SR_CLNT_HELLO_A;
298 s->ctx->stats.sess_accept++;
300 else if (!s->s3->send_connection_binding &&
301 !(s->options & SSL_OP_ALLOW_UNSAFE_LEGACY_RENEGOTIATION))
303 /* Server attempting to renegotiate with
304 * client that doesn't support secure
307 OPENSSL_PUT_ERROR(SSL, ssl3_accept, SSL_R_UNSAFE_LEGACY_RENEGOTIATION_DISABLED);
308 ssl3_send_alert(s,SSL3_AL_FATAL,SSL_AD_HANDSHAKE_FAILURE);
314 /* s->state == SSL_ST_RENEGOTIATE,
315 * we will just send a HelloRequest */
316 s->ctx->stats.sess_accept_renegotiate++;
317 s->state=SSL3_ST_SW_HELLO_REQ_A;
321 case SSL3_ST_SW_HELLO_REQ_A:
322 case SSL3_ST_SW_HELLO_REQ_B:
325 ret=ssl3_send_hello_request(s);
326 if (ret <= 0) goto end;
327 s->s3->tmp.next_state=SSL3_ST_SW_HELLO_REQ_C;
328 s->state=SSL3_ST_SW_FLUSH;
331 ssl3_init_finished_mac(s);
334 case SSL3_ST_SW_HELLO_REQ_C:
338 case SSL3_ST_SR_CLNT_HELLO_A:
339 case SSL3_ST_SR_CLNT_HELLO_B:
340 case SSL3_ST_SR_CLNT_HELLO_C:
341 case SSL3_ST_SR_CLNT_HELLO_D:
343 ret=ssl3_get_client_hello(s);
344 if (ret == PENDING_SESSION) {
345 s->rwstate = SSL_PENDING_SESSION;
348 if (ret == CERTIFICATE_SELECTION_PENDING)
350 s->rwstate = SSL_CERTIFICATE_SELECTION_PENDING;
353 if (ret <= 0) goto end;
355 s->state=SSL3_ST_SW_SRVR_HELLO_A;
359 case SSL3_ST_SW_SRVR_HELLO_A:
360 case SSL3_ST_SW_SRVR_HELLO_B:
361 ret=ssl3_send_server_hello(s);
362 if (ret <= 0) goto end;
365 if (s->tlsext_ticket_expected)
366 s->state=SSL3_ST_SW_SESSION_TICKET_A;
368 s->state=SSL3_ST_SW_CHANGE_A;
371 s->state = SSL3_ST_SW_CERT_A;
375 case SSL3_ST_SW_CERT_A:
376 case SSL3_ST_SW_CERT_B:
377 if (ssl_cipher_has_server_public_key(s->s3->tmp.new_cipher))
379 ret=ssl3_send_server_certificate(s);
380 if (ret <= 0) goto end;
381 if (s->s3->tmp.certificate_status_expected)
382 s->state=SSL3_ST_SW_CERT_STATUS_A;
384 s->state=SSL3_ST_SW_KEY_EXCH_A;
389 s->state=SSL3_ST_SW_KEY_EXCH_A;
394 case SSL3_ST_SW_KEY_EXCH_A:
395 case SSL3_ST_SW_KEY_EXCH_B:
396 alg_a = s->s3->tmp.new_cipher->algorithm_auth;
398 /* Send a ServerKeyExchange message if:
399 * - The key exchange is ephemeral or anonymous
401 * - There is a PSK identity hint.
403 * TODO(davidben): This logic is currently duplicated
404 * in d1_srvr.c. Fix this. In the meantime, keep them
407 if (ssl_cipher_requires_server_key_exchange(s->s3->tmp.new_cipher) ||
408 ((alg_a & SSL_aPSK) && s->session->psk_identity_hint))
410 ret=ssl3_send_server_key_exchange(s);
411 if (ret <= 0) goto end;
416 s->state=SSL3_ST_SW_CERT_REQ_A;
420 case SSL3_ST_SW_CERT_REQ_A:
421 case SSL3_ST_SW_CERT_REQ_B:
422 if (/* don't request cert unless asked for it: */
423 !(s->verify_mode & SSL_VERIFY_PEER) ||
424 /* Don't request a certificate if an obc was presented */
425 ((s->verify_mode & SSL_VERIFY_PEER_IF_NO_OBC) &&
426 s->s3->tlsext_channel_id_valid) ||
427 /* if SSL_VERIFY_CLIENT_ONCE is set,
428 * don't request cert during re-negotiation: */
429 ((s->session->peer != NULL) &&
430 (s->verify_mode & SSL_VERIFY_CLIENT_ONCE)) ||
431 /* never request cert in anonymous ciphersuites
432 * (see section "Certificate request" in SSL 3 drafts
433 * and in RFC 2246): */
434 ((s->s3->tmp.new_cipher->algorithm_auth & SSL_aNULL) &&
435 /* ... except when the application insists on verification
436 * (against the specs, but s3_clnt.c accepts this for SSL 3) */
437 !(s->verify_mode & SSL_VERIFY_FAIL_IF_NO_PEER_CERT)) ||
438 /* With normal PSK Certificates and
439 * Certificate Requests are omitted */
440 (s->s3->tmp.new_cipher->algorithm_mkey & SSL_kPSK))
442 /* no cert request */
444 s->s3->tmp.cert_request=0;
445 s->state=SSL3_ST_SW_SRVR_DONE_A;
446 if (s->s3->handshake_buffer)
447 if (!ssl3_digest_cached_records(s, free_handshake_buffer))
452 s->s3->tmp.cert_request=1;
453 ret=ssl3_send_certificate_request(s);
454 if (ret <= 0) goto end;
455 #ifndef NETSCAPE_HANG_BUG
456 s->state=SSL3_ST_SW_SRVR_DONE_A;
458 s->state=SSL3_ST_SW_FLUSH;
459 s->s3->tmp.next_state=SSL3_ST_SR_CERT_A;
465 case SSL3_ST_SW_SRVR_DONE_A:
466 case SSL3_ST_SW_SRVR_DONE_B:
467 ret=ssl3_send_server_done(s);
468 if (ret <= 0) goto end;
469 s->s3->tmp.next_state=SSL3_ST_SR_CERT_A;
470 s->state=SSL3_ST_SW_FLUSH;
474 case SSL3_ST_SW_FLUSH:
476 /* This code originally checked to see if
477 * any data was pending using BIO_CTRL_INFO
478 * and then flushed. This caused problems
479 * as documented in PR#1939. The proposed
480 * fix doesn't completely resolve this issue
481 * as buggy implementations of BIO_CTRL_PENDING
482 * still exist. So instead we just flush
486 s->rwstate=SSL_WRITING;
487 if (BIO_flush(s->wbio) <= 0)
492 s->rwstate=SSL_NOTHING;
494 s->state=s->s3->tmp.next_state;
497 case SSL3_ST_SR_CERT_A:
498 case SSL3_ST_SR_CERT_B:
499 if (s->s3->tmp.cert_request)
501 ret=ssl3_get_client_certificate(s);
502 if (ret <= 0) goto end;
505 s->state=SSL3_ST_SR_KEY_EXCH_A;
508 case SSL3_ST_SR_KEY_EXCH_A:
509 case SSL3_ST_SR_KEY_EXCH_B:
510 ret=ssl3_get_client_key_exchange(s);
513 s->state=SSL3_ST_SR_CERT_VRFY_A;
517 case SSL3_ST_SR_CERT_VRFY_A:
518 case SSL3_ST_SR_CERT_VRFY_B:
519 ret=ssl3_get_cert_verify(s);
520 if (ret <= 0) goto end;
522 s->state = SSL3_ST_SR_CHANGE;
526 case SSL3_ST_SR_CHANGE: {
527 char next_proto_neg = 0;
529 next_proto_neg = s->s3->next_proto_neg_seen;
530 channel_id = s->s3->tlsext_channel_id_valid;
532 /* At this point, the next message must be entirely
533 * behind a ChangeCipherSpec. */
534 if (!ssl3_expect_change_cipher_spec(s))
540 s->state = SSL3_ST_SR_NEXT_PROTO_A;
542 s->state = SSL3_ST_SR_CHANNEL_ID_A;
544 s->state = SSL3_ST_SR_FINISHED_A;
548 case SSL3_ST_SR_NEXT_PROTO_A:
549 case SSL3_ST_SR_NEXT_PROTO_B:
550 ret=ssl3_get_next_proto(s);
551 if (ret <= 0) goto end;
553 if (s->s3->tlsext_channel_id_valid)
554 s->state=SSL3_ST_SR_CHANNEL_ID_A;
556 s->state=SSL3_ST_SR_FINISHED_A;
559 case SSL3_ST_SR_CHANNEL_ID_A:
560 case SSL3_ST_SR_CHANNEL_ID_B:
561 ret=ssl3_get_channel_id(s);
562 if (ret <= 0) goto end;
564 s->state=SSL3_ST_SR_FINISHED_A;
567 case SSL3_ST_SR_FINISHED_A:
568 case SSL3_ST_SR_FINISHED_B:
569 ret=ssl3_get_finished(s,SSL3_ST_SR_FINISHED_A,
570 SSL3_ST_SR_FINISHED_B);
571 if (ret <= 0) goto end;
574 else if (s->tlsext_ticket_expected)
575 s->state=SSL3_ST_SW_SESSION_TICKET_A;
577 s->state=SSL3_ST_SW_CHANGE_A;
578 /* If this is a full handshake with ChannelID then
579 * record the hashshake hashes in |s->session| in case
580 * we need them to verify a ChannelID signature on a
581 * resumption of this session in the future. */
582 if (!s->hit && s->s3->tlsext_channel_id_new)
584 ret = tls1_record_handshake_hashes_for_channel_id(s);
585 if (ret <= 0) goto end;
590 case SSL3_ST_SW_SESSION_TICKET_A:
591 case SSL3_ST_SW_SESSION_TICKET_B:
592 ret=ssl3_send_new_session_ticket(s);
593 if (ret <= 0) goto end;
594 s->state=SSL3_ST_SW_CHANGE_A;
599 // TODO(davidben): Implement OCSP stapling on the server.
600 case SSL3_ST_SW_CERT_STATUS_A:
601 case SSL3_ST_SW_CERT_STATUS_B:
602 ret=ssl3_send_cert_status(s);
603 if (ret <= 0) goto end;
604 s->state=SSL3_ST_SW_KEY_EXCH_A;
609 case SSL3_ST_SW_CHANGE_A:
610 case SSL3_ST_SW_CHANGE_B:
612 s->session->cipher=s->s3->tmp.new_cipher;
613 if (!s->method->ssl3_enc->setup_key_block(s))
614 { ret= -1; goto end; }
616 ret=ssl3_send_change_cipher_spec(s,
617 SSL3_ST_SW_CHANGE_A,SSL3_ST_SW_CHANGE_B);
619 if (ret <= 0) goto end;
620 s->state=SSL3_ST_SW_FINISHED_A;
623 if (!s->method->ssl3_enc->change_cipher_state(s,
624 SSL3_CHANGE_CIPHER_SERVER_WRITE))
632 case SSL3_ST_SW_FINISHED_A:
633 case SSL3_ST_SW_FINISHED_B:
634 ret=ssl3_send_finished(s,
635 SSL3_ST_SW_FINISHED_A,SSL3_ST_SW_FINISHED_B,
636 s->method->ssl3_enc->server_finished_label,
637 s->method->ssl3_enc->server_finished_label_len);
638 if (ret <= 0) goto end;
639 s->state = SSL3_ST_SW_FLUSH;
641 s->s3->tmp.next_state = SSL3_ST_SR_CHANGE;
643 s->s3->tmp.next_state = SSL_ST_OK;
648 /* clean a few things up */
649 ssl3_cleanup_key_block(s);
651 BUF_MEM_free(s->init_buf);
654 /* remove buffering on output */
655 ssl_free_wbio_buffer(s);
659 /* If we aren't retaining peer certificates then we can
661 if (s->session->peer && s->ctx->retain_only_sha256_of_client_certs)
663 X509_free(s->session->peer);
664 s->session->peer = NULL;
667 if (s->renegotiate == 2) /* skipped if we just sent a HelloRequest */
672 ssl_update_cache(s,SSL_SESS_CACHE_SERVER);
674 s->ctx->stats.sess_accept_good++;
676 s->handshake_func=ssl3_accept;
678 if (cb != NULL) cb(s,SSL_CB_HANDSHAKE_DONE,1);
686 OPENSSL_PUT_ERROR(SSL, ssl3_accept, SSL_R_UNKNOWN_STATE);
692 if (!s->s3->tmp.reuse_message && !skip)
696 if ((ret=BIO_flush(s->wbio)) <= 0)
701 if ((cb != NULL) && (s->state != state))
705 cb(s,SSL_CB_ACCEPT_LOOP,1);
712 /* BIO_flush(s->wbio); */
716 cb(s,SSL_CB_ACCEPT_EXIT,ret);
720 int ssl3_send_hello_request(SSL *s)
723 if (s->state == SSL3_ST_SW_HELLO_REQ_A)
725 ssl_set_handshake_header(s, SSL3_MT_HELLO_REQUEST, 0);
726 s->state=SSL3_ST_SW_HELLO_REQ_B;
729 /* SSL3_ST_SW_HELLO_REQ_B */
730 return ssl_do_write(s);
733 int ssl3_get_client_hello(SSL *s)
735 int i,ok,al=SSL_AD_INTERNAL_ERROR,ret= -1;
738 STACK_OF(SSL_CIPHER) *ciphers=NULL;
739 struct ssl_early_callback_ctx early_ctx;
741 uint16_t client_version;
742 CBS client_random, session_id, cipher_suites, compression_methods;
744 /* We do this so that we will respond with our native type.
745 * If we are TLSv1 and we get SSLv3, we will respond with TLSv1,
746 * This down switching should be handled by a different method.
747 * If we are SSLv3, we will respond with SSLv3, even if prompted with
751 case SSL3_ST_SR_CLNT_HELLO_A:
752 case SSL3_ST_SR_CLNT_HELLO_B:
754 n=s->method->ssl_get_message(s,
755 SSL3_ST_SR_CLNT_HELLO_A,
756 SSL3_ST_SR_CLNT_HELLO_B,
757 SSL3_MT_CLIENT_HELLO,
758 SSL3_RT_MAX_PLAIN_LENGTH,
759 SSL_GET_MESSAGE_HASH_MESSAGE,
762 if (!ok) return((int)n);
765 /* If we require cookies and this ClientHello doesn't
766 * contain one, just return since we do not want to
767 * allocate any memory yet. So check cookie length...
769 if (SSL_IS_DTLS(s) && (SSL_get_options(s) & SSL_OP_COOKIE_EXCHANGE))
772 uint8_t cookie_length;
774 CBS_init(&client_hello, s->init_msg, n);
775 if (!CBS_skip(&client_hello, 2 + SSL3_RANDOM_SIZE) ||
776 !CBS_get_u8_length_prefixed(&client_hello, &session_id) ||
777 !CBS_get_u8(&client_hello, &cookie_length))
779 al = SSL_AD_DECODE_ERROR;
780 OPENSSL_PUT_ERROR(SSL, ssl3_get_client_hello, SSL_R_DECODE_ERROR);
784 if (cookie_length == 0)
787 s->state = SSL3_ST_SR_CLNT_HELLO_C;
789 case SSL3_ST_SR_CLNT_HELLO_C:
790 case SSL3_ST_SR_CLNT_HELLO_D:
791 /* We have previously parsed the ClientHello message,
792 * and can't call ssl_get_message again without hashing
793 * the message into the Finished digest again. */
796 memset(&early_ctx, 0, sizeof(early_ctx));
798 early_ctx.client_hello = s->init_msg;
799 early_ctx.client_hello_len = n;
800 if (!ssl_early_callback_init(&early_ctx))
802 al = SSL_AD_DECODE_ERROR;
803 OPENSSL_PUT_ERROR(SSL, ssl3_get_client_hello, SSL_R_CLIENTHELLO_PARSE_FAILED);
807 if (s->state == SSL3_ST_SR_CLNT_HELLO_C &&
808 s->ctx->select_certificate_cb != NULL)
812 s->state = SSL3_ST_SR_CLNT_HELLO_D;
813 ret = s->ctx->select_certificate_cb(&early_ctx);
815 return CERTIFICATE_SELECTION_PENDING;
818 /* Connection rejected. */
819 al = SSL_AD_ACCESS_DENIED;
820 OPENSSL_PUT_ERROR(SSL, ssl3_get_client_hello, SSL_R_CONNECTION_REJECTED);
824 s->state = SSL3_ST_SR_CLNT_HELLO_D;
827 OPENSSL_PUT_ERROR(SSL, ssl3_get_client_hello, SSL_R_UNKNOWN_STATE);
831 CBS_init(&client_hello, s->init_msg, n);
832 if (!CBS_get_u16(&client_hello, &client_version) ||
833 !CBS_get_bytes(&client_hello, &client_random, SSL3_RANDOM_SIZE) ||
834 !CBS_get_u8_length_prefixed(&client_hello, &session_id) ||
835 CBS_len(&session_id) > SSL_MAX_SSL_SESSION_ID_LENGTH)
837 al = SSL_AD_DECODE_ERROR;
838 OPENSSL_PUT_ERROR(SSL, ssl3_get_client_hello, SSL_R_DECODE_ERROR);
842 /* use version from inside client hello, not from record header
843 * (may differ: see RFC 2246, Appendix E, second paragraph) */
844 s->client_version = client_version;
846 if (SSL_IS_DTLS(s) ? (s->client_version > s->version &&
847 s->method->version != DTLS_ANY_VERSION)
848 : (s->client_version < s->version))
850 OPENSSL_PUT_ERROR(SSL, ssl3_get_client_hello, SSL_R_WRONG_VERSION_NUMBER);
851 if ((s->client_version>>8) == SSL3_VERSION_MAJOR &&
852 !s->enc_write_ctx && !s->write_hash)
854 /* similar to ssl3_get_record, send alert using remote version number */
855 s->version = s->client_version;
857 al = SSL_AD_PROTOCOL_VERSION;
861 /* Load the client random. */
862 memcpy(s->s3->client_random, CBS_data(&client_random), SSL3_RANDOM_SIZE);
865 /* Versions before 0.9.7 always allow clients to resume sessions in renegotiation.
866 * 0.9.7 and later allow this by default, but optionally ignore resumption requests
867 * with flag SSL_OP_NO_SESSION_RESUMPTION_ON_RENEGOTIATION (it's a new flag rather
868 * than a change to default behavior so that applications relying on this for security
869 * won't even compile against older library versions).
871 * 1.0.1 and later also have a function SSL_renegotiate_abbreviated() to request
872 * renegotiation but not a new session (s->new_session remains unset): for servers,
873 * this essentially just means that the SSL_OP_NO_SESSION_RESUMPTION_ON_RENEGOTIATION
874 * setting will be ignored.
876 if ((s->new_session && (s->options & SSL_OP_NO_SESSION_RESUMPTION_ON_RENEGOTIATION)))
878 if (!ssl_get_new_session(s,1))
883 i=ssl_get_prev_session(s, &early_ctx);
885 { /* previous session */
890 else if (i == PENDING_SESSION)
892 ret = PENDING_SESSION;
897 if (!ssl_get_new_session(s,1))
906 /* TODO(davidben): The length check here is off. Per
907 * spec, the maximum cookie length is 32. However, the
908 * DTLS1_COOKIE_LENGTH check is checking against 256,
909 * not 32 (so it's actually redundant).
910 * 07a9d1a2c2b735cbc327065000b545deb5e136cf from
911 * OpenSSL switched this from 32 to 256. */
912 if (!CBS_get_u8_length_prefixed(&client_hello, &cookie) ||
913 CBS_len(&cookie) > DTLS1_COOKIE_LENGTH)
915 al = SSL_AD_DECODE_ERROR;
916 OPENSSL_PUT_ERROR(SSL, ssl3_get_client_hello, SSL_R_DECODE_ERROR);
920 /* Verify the cookie if appropriate option is set. */
921 if ((SSL_get_options(s) & SSL_OP_COOKIE_EXCHANGE) &&
922 CBS_len(&cookie) > 0)
924 if (s->ctx->app_verify_cookie_cb != NULL)
926 if (s->ctx->app_verify_cookie_cb(s,
927 CBS_data(&cookie), CBS_len(&cookie)) == 0)
929 al=SSL_AD_HANDSHAKE_FAILURE;
930 OPENSSL_PUT_ERROR(SSL, ssl3_get_client_hello, SSL_R_COOKIE_MISMATCH);
933 /* else cookie verification succeeded */
935 else if (!CBS_mem_equal(&cookie, s->d1->cookie, s->d1->cookie_len))
937 /* default verification */
938 al=SSL_AD_HANDSHAKE_FAILURE;
939 OPENSSL_PUT_ERROR(SSL, ssl3_get_client_hello, SSL_R_COOKIE_MISMATCH);
942 /* Set to -2 so if successful we return 2 and
943 * don't send HelloVerifyRequest. */
947 if (s->method->version == DTLS_ANY_VERSION)
949 /* Select version to use */
950 if (s->client_version <= DTLS1_2_VERSION &&
951 !(s->options & SSL_OP_NO_DTLSv1_2))
953 s->version = DTLS1_2_VERSION;
954 s->method = DTLSv1_2_server_method();
956 else if (s->client_version <= DTLS1_VERSION &&
957 !(s->options & SSL_OP_NO_DTLSv1))
959 s->version = DTLS1_VERSION;
960 s->method = DTLSv1_server_method();
964 OPENSSL_PUT_ERROR(SSL, ssl3_get_client_hello, SSL_R_WRONG_VERSION_NUMBER);
965 s->version = s->client_version;
966 al = SSL_AD_PROTOCOL_VERSION;
969 s->session->ssl_version = s->version;
973 if (!CBS_get_u16_length_prefixed(&client_hello, &cipher_suites) ||
974 !CBS_get_u8_length_prefixed(&client_hello, &compression_methods) ||
975 CBS_len(&compression_methods) == 0)
977 al = SSL_AD_DECODE_ERROR;
978 OPENSSL_PUT_ERROR(SSL, ssl3_get_client_hello, SSL_R_DECODE_ERROR);
982 /* TODO(davidben): Per spec, cipher_suites can never be empty
983 * (specified at the ClientHello structure level). This logic
984 * allows it to be empty if resuming a session. Can we always
985 * require non-empty? If a client sends empty cipher_suites
986 * because it's resuming a session, it could always fail to
987 * resume a session, so it's unlikely to actually work. */
988 if (CBS_len(&cipher_suites) == 0 && CBS_len(&session_id) != 0)
990 /* We need a cipher if we are not resuming a session. */
991 al = SSL_AD_ILLEGAL_PARAMETER;
992 OPENSSL_PUT_ERROR(SSL, ssl3_get_client_hello, SSL_R_NO_CIPHERS_SPECIFIED);
996 ciphers = ssl_bytes_to_cipher_list(s, &cipher_suites);
1002 /* If it is a hit, check that the cipher is in the list */
1003 if (s->hit && CBS_len(&cipher_suites) > 0)
1006 int found_cipher = 0;
1007 unsigned long id = s->session->cipher->id;
1009 for (j = 0; j < sk_SSL_CIPHER_num(ciphers); j++)
1011 c = sk_SSL_CIPHER_value(ciphers, j);
1020 /* we need to have the cipher in the cipher
1021 * list if we are asked to reuse it */
1022 al=SSL_AD_ILLEGAL_PARAMETER;
1023 OPENSSL_PUT_ERROR(SSL, ssl3_get_client_hello, SSL_R_REQUIRED_CIPHER_MISSING);
1028 /* Only null compression is supported. */
1029 if (memchr(CBS_data(&compression_methods), 0,
1030 CBS_len(&compression_methods)) == NULL)
1032 al = SSL_AD_ILLEGAL_PARAMETER;
1033 OPENSSL_PUT_ERROR(SSL, ssl3_get_client_hello, SSL_R_NO_COMPRESSION_SPECIFIED);
1038 if (s->version >= SSL3_VERSION)
1040 if (!ssl_parse_clienthello_tlsext(s, &client_hello))
1042 OPENSSL_PUT_ERROR(SSL, ssl3_get_client_hello, SSL_R_PARSE_TLSEXT);
1047 /* There should be nothing left over in the record. */
1048 if (CBS_len(&client_hello) != 0)
1050 /* wrong packet length */
1051 al=SSL_AD_DECODE_ERROR;
1052 OPENSSL_PUT_ERROR(SSL, ssl3_get_client_hello, SSL_R_BAD_PACKET_LENGTH);
1056 /* Check if we want to use external pre-shared secret for this
1057 * handshake for not reused session only. We need to generate
1058 * server_random before calling tls_session_secret_cb in order to allow
1059 * SessionTicket processing to use it in key derivation. */
1062 pos=s->s3->server_random;
1063 if (ssl_fill_hello_random(s, 1, pos, SSL3_RANDOM_SIZE) <= 0)
1069 if (!s->hit && s->version >= TLS1_VERSION && s->tls_session_secret_cb)
1071 const SSL_CIPHER *pref_cipher=NULL;
1073 s->session->master_key_length=sizeof(s->session->master_key);
1074 if(s->tls_session_secret_cb(s, s->session->master_key, &s->session->master_key_length,
1075 ciphers, &pref_cipher, s->tls_session_secret_cb_arg))
1078 s->session->verify_result=X509_V_OK;
1080 /* check if some cipher was preferred by call back */
1081 pref_cipher=pref_cipher ? pref_cipher : ssl3_choose_cipher(s, ciphers, ssl_get_cipher_preferences(s));
1082 if (pref_cipher == NULL)
1084 al=SSL_AD_HANDSHAKE_FAILURE;
1085 OPENSSL_PUT_ERROR(SSL, ssl3_get_client_hello, SSL_R_NO_SHARED_CIPHER);
1089 s->session->cipher=pref_cipher;
1092 ssl_cipher_preference_list_free(s->cipher_list);
1094 if (s->cipher_list_by_id)
1095 sk_SSL_CIPHER_free(s->cipher_list_by_id);
1097 s->cipher_list = ssl_cipher_preference_list_from_ciphers(ciphers);
1098 s->cipher_list_by_id = sk_SSL_CIPHER_dup(ciphers);
1102 /* Given ciphers and SSL_get_ciphers, we must pick a cipher */
1106 if (ciphers == NULL)
1108 al=SSL_AD_ILLEGAL_PARAMETER;
1109 OPENSSL_PUT_ERROR(SSL, ssl3_get_client_hello, SSL_R_NO_CIPHERS_PASSED);
1112 /* Let cert callback update server certificates if required */
1113 if (s->cert->cert_cb)
1115 int rv = s->cert->cert_cb(s, s->cert->cert_cb_arg);
1118 al=SSL_AD_INTERNAL_ERROR;
1119 OPENSSL_PUT_ERROR(SSL, ssl3_get_client_hello, SSL_R_CERT_CB_ERROR);
1124 s->rwstate=SSL_X509_LOOKUP;
1127 s->rwstate = SSL_NOTHING;
1129 c=ssl3_choose_cipher(s, ciphers, ssl_get_cipher_preferences(s));
1133 al=SSL_AD_HANDSHAKE_FAILURE;
1134 OPENSSL_PUT_ERROR(SSL, ssl3_get_client_hello, SSL_R_NO_SHARED_CIPHER);
1137 s->s3->tmp.new_cipher=c;
1141 /* Session-id reuse */
1142 s->s3->tmp.new_cipher=s->session->cipher;
1145 if (!SSL_USE_SIGALGS(s) || !(s->verify_mode & SSL_VERIFY_PEER))
1147 if (!ssl3_digest_cached_records(s, free_handshake_buffer))
1151 /* we now have the following setup.
1153 * cipher_list - our prefered list of ciphers
1154 * ciphers - the clients prefered list of ciphers
1155 * compression - basically ignored right now
1156 * ssl version is set - sslv3
1157 * s->session - The ssl session has been setup.
1158 * s->hit - session reuse flag
1159 * s->tmp.new_cipher - the new cipher to use.
1162 if (ret < 0) ret=-ret;
1166 ssl3_send_alert(s,SSL3_AL_FATAL,al);
1169 if (ciphers != NULL) sk_SSL_CIPHER_free(ciphers);
1173 int ssl3_send_server_hello(SSL *s)
1176 unsigned char *p,*d;
1180 if (s->state == SSL3_ST_SW_SRVR_HELLO_A)
1182 /* We only accept ChannelIDs on connections with ECDHE in order
1183 * to avoid a known attack while we fix ChannelID itself. */
1185 s->s3->tlsext_channel_id_valid &&
1186 (s->s3->tmp.new_cipher->algorithm_mkey & SSL_kEECDH) == 0)
1187 s->s3->tlsext_channel_id_valid = 0;
1189 /* If this is a resumption and the original handshake didn't
1190 * support ChannelID then we didn't record the original
1191 * handshake hashes in the session and so cannot resume with
1194 s->s3->tlsext_channel_id_new &&
1195 s->session->original_handshake_hash_len == 0)
1196 s->s3->tlsext_channel_id_valid = 0;
1198 buf=(unsigned char *)s->init_buf->data;
1199 /* Do the message type and length last */
1200 d=p= ssl_handshake_start(s);
1202 *(p++)=s->version>>8;
1203 *(p++)=s->version&0xff;
1206 memcpy(p,s->s3->server_random,SSL3_RANDOM_SIZE);
1207 p+=SSL3_RANDOM_SIZE;
1209 /* There are several cases for the session ID to send
1210 * back in the server hello:
1211 * - For session reuse from the session cache,
1212 * we send back the old session ID.
1213 * - If stateless session reuse (using a session ticket)
1214 * is successful, we send back the client's "session ID"
1215 * (which doesn't actually identify the session).
1216 * - If it is a new session, we send back the new
1218 * - However, if we want the new session to be single-use,
1219 * we send back a 0-length session ID.
1220 * s->hit is non-zero in either case of session reuse,
1221 * so the following won't overwrite an ID that we're supposed
1224 if (!(s->ctx->session_cache_mode & SSL_SESS_CACHE_SERVER)
1226 s->session->session_id_length=0;
1228 sl=s->session->session_id_length;
1229 if (sl > (int)sizeof(s->session->session_id))
1231 OPENSSL_PUT_ERROR(SSL, ssl3_send_server_hello, ERR_R_INTERNAL_ERROR);
1235 memcpy(p,s->session->session_id,sl);
1238 /* put the cipher */
1239 s2n(ssl3_get_cipher_value(s->s3->tmp.new_cipher), p);
1241 /* put the compression method */
1243 if (ssl_prepare_serverhello_tlsext(s) <= 0)
1245 OPENSSL_PUT_ERROR(SSL, ssl3_send_server_hello, SSL_R_SERVERHELLO_TLSEXT);
1248 if ((p = ssl_add_serverhello_tlsext(s, p, buf+SSL3_RT_MAX_PLAIN_LENGTH)) == NULL)
1250 OPENSSL_PUT_ERROR(SSL, ssl3_send_server_hello, ERR_R_INTERNAL_ERROR);
1255 ssl_set_handshake_header(s, SSL3_MT_SERVER_HELLO, l);
1256 s->state=SSL3_ST_SW_SRVR_HELLO_B;
1259 /* SSL3_ST_SW_SRVR_HELLO_B */
1260 return ssl_do_write(s);
1263 int ssl3_send_server_done(SSL *s)
1266 if (s->state == SSL3_ST_SW_SRVR_DONE_A)
1268 ssl_set_handshake_header(s, SSL3_MT_SERVER_DONE, 0);
1269 s->state = SSL3_ST_SW_SRVR_DONE_B;
1272 /* SSL3_ST_SW_SRVR_DONE_B */
1273 return ssl_do_write(s);
1276 int ssl3_send_server_key_exchange(SSL *s)
1280 unsigned char md_buf[MD5_DIGEST_LENGTH+SHA_DIGEST_LENGTH];
1283 EC_KEY *ecdh=NULL, *ecdhp;
1284 unsigned char *encodedPoint = NULL;
1287 BN_CTX *bn_ctx = NULL;
1288 const char* psk_identity_hint = NULL;
1289 size_t psk_identity_hint_len = 0;
1291 const EVP_MD *md = NULL;
1292 unsigned char *p,*d;
1294 unsigned long alg_k;
1295 unsigned long alg_a;
1303 EVP_MD_CTX_init(&md_ctx);
1304 if (s->state == SSL3_ST_SW_KEY_EXCH_A)
1306 alg_k=s->s3->tmp.new_cipher->algorithm_mkey;
1307 alg_a=s->s3->tmp.new_cipher->algorithm_auth;
1312 r[0]=r[1]=r[2]=r[3]=NULL;
1314 if (alg_a & SSL_aPSK)
1316 /* size for PSK identity hint */
1317 psk_identity_hint = s->session->psk_identity_hint;
1318 if (psk_identity_hint)
1319 psk_identity_hint_len = strlen(psk_identity_hint);
1321 psk_identity_hint_len = 0;
1322 n+=2+psk_identity_hint_len;
1324 if (alg_k & SSL_kEDH)
1327 if ((dhp == NULL) && (s->cert->dh_tmp_cb != NULL))
1328 dhp=s->cert->dh_tmp_cb(s, 0, 1024);
1331 al=SSL_AD_HANDSHAKE_FAILURE;
1332 OPENSSL_PUT_ERROR(SSL, ssl3_send_server_key_exchange, SSL_R_MISSING_TMP_DH_KEY);
1336 if (s->s3->tmp.dh != NULL)
1338 OPENSSL_PUT_ERROR(SSL, ssl3_send_server_key_exchange, ERR_R_INTERNAL_ERROR);
1342 if ((dh=DHparams_dup(dhp)) == NULL)
1344 OPENSSL_PUT_ERROR(SSL, ssl3_send_server_key_exchange, ERR_R_DH_LIB);
1349 if ((dhp->pub_key == NULL ||
1350 dhp->priv_key == NULL ||
1351 (s->options & SSL_OP_SINGLE_DH_USE)))
1353 if(!DH_generate_key(dh))
1355 OPENSSL_PUT_ERROR(SSL, ssl3_send_server_key_exchange, ERR_R_DH_LIB);
1361 dh->pub_key=BN_dup(dhp->pub_key);
1362 dh->priv_key=BN_dup(dhp->priv_key);
1363 if ((dh->pub_key == NULL) ||
1364 (dh->priv_key == NULL))
1366 OPENSSL_PUT_ERROR(SSL, ssl3_send_server_key_exchange, ERR_R_DH_LIB);
1375 if (alg_k & SSL_kEECDH)
1377 const EC_GROUP *group;
1379 ecdhp=cert->ecdh_tmp;
1380 if (s->cert->ecdh_tmp_auto)
1382 /* Get NID of appropriate shared curve */
1383 int nid = tls1_get_shared_curve(s);
1384 if (nid != NID_undef)
1385 ecdhp = EC_KEY_new_by_curve_name(nid);
1387 else if ((ecdhp == NULL) && s->cert->ecdh_tmp_cb)
1389 ecdhp = s->cert->ecdh_tmp_cb(s, 0, 1024);
1393 al=SSL_AD_HANDSHAKE_FAILURE;
1394 OPENSSL_PUT_ERROR(SSL, ssl3_send_server_key_exchange, SSL_R_MISSING_TMP_ECDH_KEY);
1398 if (s->s3->tmp.ecdh != NULL)
1400 OPENSSL_PUT_ERROR(SSL, ssl3_send_server_key_exchange, ERR_R_INTERNAL_ERROR);
1404 /* Duplicate the ECDH structure. */
1407 OPENSSL_PUT_ERROR(SSL, ssl3_send_server_key_exchange, ERR_R_ECDH_LIB);
1410 if (s->cert->ecdh_tmp_auto)
1412 else if ((ecdh = EC_KEY_dup(ecdhp)) == NULL)
1414 OPENSSL_PUT_ERROR(SSL, ssl3_send_server_key_exchange, ERR_R_ECDH_LIB);
1418 s->s3->tmp.ecdh=ecdh;
1419 if ((EC_KEY_get0_public_key(ecdh) == NULL) ||
1420 (EC_KEY_get0_private_key(ecdh) == NULL) ||
1421 (s->options & SSL_OP_SINGLE_ECDH_USE))
1423 if(!EC_KEY_generate_key(ecdh))
1425 OPENSSL_PUT_ERROR(SSL, ssl3_send_server_key_exchange, ERR_R_ECDH_LIB);
1430 if (((group = EC_KEY_get0_group(ecdh)) == NULL) ||
1431 (EC_KEY_get0_public_key(ecdh) == NULL) ||
1432 (EC_KEY_get0_private_key(ecdh) == NULL))
1434 OPENSSL_PUT_ERROR(SSL, ssl3_send_server_key_exchange, ERR_R_ECDH_LIB);
1438 /* XXX: For now, we only support ephemeral ECDH
1439 * keys over named (not generic) curves. For
1440 * supported named curves, curve_id is non-zero.
1443 tls1_ec_nid2curve_id(EC_GROUP_get_curve_name(group)))
1446 OPENSSL_PUT_ERROR(SSL, ssl3_send_server_key_exchange, SSL_R_UNSUPPORTED_ELLIPTIC_CURVE);
1450 /* Encode the public key.
1451 * First check the size of encoding and
1452 * allocate memory accordingly.
1454 encodedlen = EC_POINT_point2oct(group,
1455 EC_KEY_get0_public_key(ecdh),
1456 POINT_CONVERSION_UNCOMPRESSED,
1459 encodedPoint = (unsigned char *)
1460 OPENSSL_malloc(encodedlen*sizeof(unsigned char));
1461 bn_ctx = BN_CTX_new();
1462 if ((encodedPoint == NULL) || (bn_ctx == NULL))
1464 OPENSSL_PUT_ERROR(SSL, ssl3_send_server_key_exchange, ERR_R_MALLOC_FAILURE);
1469 encodedlen = EC_POINT_point2oct(group,
1470 EC_KEY_get0_public_key(ecdh),
1471 POINT_CONVERSION_UNCOMPRESSED,
1472 encodedPoint, encodedlen, bn_ctx);
1474 if (encodedlen == 0)
1476 OPENSSL_PUT_ERROR(SSL, ssl3_send_server_key_exchange, ERR_R_ECDH_LIB);
1480 BN_CTX_free(bn_ctx); bn_ctx=NULL;
1482 /* XXX: For now, we only support named (not
1483 * generic) curves in ECDH ephemeral key exchanges.
1484 * In this situation, we need four additional bytes
1485 * to encode the entire ServerECDHParams
1488 n += 4 + encodedlen;
1490 /* We'll generate the serverKeyExchange message
1491 * explicitly so we can set these to NULLs
1499 if (!(alg_k & SSL_kPSK))
1501 al=SSL_AD_HANDSHAKE_FAILURE;
1502 OPENSSL_PUT_ERROR(SSL, ssl3_send_server_key_exchange, SSL_R_UNKNOWN_KEY_EXCHANGE_TYPE);
1505 for (i=0; i < 4 && r[i] != NULL; i++)
1507 nr[i]=BN_num_bytes(r[i]);
1511 if (ssl_cipher_has_server_public_key(s->s3->tmp.new_cipher))
1513 if ((pkey=ssl_get_sign_pkey(s,s->s3->tmp.new_cipher,&md))
1516 al=SSL_AD_DECODE_ERROR;
1519 kn=EVP_PKEY_size(pkey);
1527 if (!BUF_MEM_grow_clean(buf,n+SSL_HM_HEADER_LENGTH(s)+kn))
1529 OPENSSL_PUT_ERROR(SSL, ssl3_send_server_key_exchange, ERR_LIB_BUF);
1532 d = p = ssl_handshake_start(s);
1534 for (i=0; i < 4 && r[i] != NULL; i++)
1541 /* Note: ECDHE PSK ciphersuites use SSL_kEECDH and SSL_aPSK.
1542 * When one of them is used, the server key exchange record needs to have both
1543 * the psk_identity_hint and the ServerECDHParams. */
1544 if (alg_a & SSL_aPSK)
1546 /* copy PSK identity hint (if provided) */
1547 s2n(psk_identity_hint_len, p);
1548 if (psk_identity_hint_len > 0)
1550 memcpy(p, psk_identity_hint, psk_identity_hint_len);
1551 p+=psk_identity_hint_len;
1555 if (alg_k & SSL_kEECDH)
1557 /* XXX: For now, we only support named (not generic) curves.
1558 * In this situation, the serverKeyExchange message has:
1559 * [1 byte CurveType], [2 byte CurveName]
1560 * [1 byte length of encoded point], followed by
1561 * the actual encoded point itself
1563 *p = NAMED_CURVE_TYPE;
1571 memcpy((unsigned char*)p,
1572 (unsigned char *)encodedPoint,
1574 OPENSSL_free(encodedPoint);
1575 encodedPoint = NULL;
1582 /* n is the length of the params, they start at &(d[4])
1583 * and p points to the space at the end. */
1584 if (pkey->type == EVP_PKEY_RSA && !SSL_USE_SIGALGS(s))
1588 for (num=2; num > 0; num--)
1590 EVP_DigestInit_ex(&md_ctx,
1591 (num == 2) ? EVP_md5() : EVP_sha1(), NULL);
1592 EVP_DigestUpdate(&md_ctx,&(s->s3->client_random[0]),SSL3_RANDOM_SIZE);
1593 EVP_DigestUpdate(&md_ctx,&(s->s3->server_random[0]),SSL3_RANDOM_SIZE);
1594 EVP_DigestUpdate(&md_ctx,d,n);
1595 EVP_DigestFinal_ex(&md_ctx,q,
1596 (unsigned int *)&i);
1600 if (RSA_sign(NID_md5_sha1, md_buf, j,
1601 &(p[2]), &u, pkey->pkey.rsa) <= 0)
1603 OPENSSL_PUT_ERROR(SSL, ssl3_send_server_key_exchange, ERR_LIB_RSA);
1612 size_t sig_len = EVP_PKEY_size(pkey);
1614 /* send signature algorithm */
1615 if (SSL_USE_SIGALGS(s))
1617 if (!tls12_get_sigandhash(p, pkey, md))
1619 /* Should never happen */
1620 al=SSL_AD_INTERNAL_ERROR;
1621 OPENSSL_PUT_ERROR(SSL, ssl3_send_server_key_exchange, ERR_R_INTERNAL_ERROR);
1626 if (!EVP_DigestSignInit(&md_ctx, NULL, md, NULL, pkey) ||
1627 !EVP_DigestSignUpdate(&md_ctx, s->s3->client_random, SSL3_RANDOM_SIZE) ||
1628 !EVP_DigestSignUpdate(&md_ctx, s->s3->server_random, SSL3_RANDOM_SIZE) ||
1629 !EVP_DigestSignUpdate(&md_ctx, d, n) ||
1630 !EVP_DigestSignFinal(&md_ctx, &p[2], &sig_len))
1632 OPENSSL_PUT_ERROR(SSL, ssl3_send_server_key_exchange, ERR_LIB_EVP);
1637 if (SSL_USE_SIGALGS(s))
1642 /* Is this error check actually needed? */
1643 al=SSL_AD_HANDSHAKE_FAILURE;
1644 OPENSSL_PUT_ERROR(SSL, ssl3_send_server_key_exchange, SSL_R_UNKNOWN_PKEY_TYPE);
1649 ssl_set_handshake_header(s, SSL3_MT_SERVER_KEY_EXCHANGE, n);
1652 s->state = SSL3_ST_SW_KEY_EXCH_B;
1653 EVP_MD_CTX_cleanup(&md_ctx);
1654 return ssl_do_write(s);
1656 ssl3_send_alert(s,SSL3_AL_FATAL,al);
1658 if (encodedPoint != NULL) OPENSSL_free(encodedPoint);
1659 BN_CTX_free(bn_ctx);
1660 EVP_MD_CTX_cleanup(&md_ctx);
1664 int ssl3_send_certificate_request(SSL *s)
1666 unsigned char *p,*d;
1669 STACK_OF(X509_NAME) *sk=NULL;
1673 if (s->state == SSL3_ST_SW_CERT_REQ_A)
1677 d=p=ssl_handshake_start(s);
1679 /* get the list of acceptable cert types */
1681 n=ssl3_get_req_cert_type(s,p);
1686 if (SSL_USE_SIGALGS(s))
1688 const unsigned char *psigs;
1689 nl = tls12_get_psigalgs(s, &psigs);
1691 memcpy(p, psigs, nl);
1700 sk=SSL_get_client_CA_list(s);
1704 for (i=0; i<sk_X509_NAME_num(sk); i++)
1706 name=sk_X509_NAME_value(sk,i);
1707 j=i2d_X509_NAME(name,NULL);
1708 if (!BUF_MEM_grow_clean(buf,SSL_HM_HEADER_LENGTH(s)+n+j+2))
1710 OPENSSL_PUT_ERROR(SSL, ssl3_send_certificate_request, ERR_R_BUF_LIB);
1713 p = ssl_handshake_start(s) + n;
1715 i2d_X509_NAME(name,&p);
1720 /* else no CA names */
1721 p = ssl_handshake_start(s) + off;
1724 ssl_set_handshake_header(s, SSL3_MT_CERTIFICATE_REQUEST, n);
1726 #ifdef NETSCAPE_HANG_BUG
1727 if (!SSL_IS_DTLS(s))
1729 if (!BUF_MEM_grow_clean(buf, s->init_num + 4))
1731 OPENSSL_PUT_ERROR(SSL, ssl3_send_certificate_request, ERR_R_BUF_LIB);
1734 p=(unsigned char *)s->init_buf->data + s->init_num;
1736 *(p++)=SSL3_MT_SERVER_DONE;
1744 s->state = SSL3_ST_SW_CERT_REQ_B;
1747 /* SSL3_ST_SW_CERT_REQ_B */
1748 return ssl_do_write(s);
1753 int ssl3_get_client_key_exchange(SSL *s)
1757 CBS client_key_exchange;
1758 unsigned long alg_k;
1759 unsigned long alg_a;
1760 uint8_t *premaster_secret = NULL;
1761 size_t premaster_secret_len = 0;
1763 uint8_t *decrypt_buf = NULL;
1764 EVP_PKEY *pkey=NULL;
1768 EC_KEY *srvr_ecdh = NULL;
1769 EVP_PKEY *clnt_pub_pkey = NULL;
1770 EC_POINT *clnt_ecpoint = NULL;
1771 BN_CTX *bn_ctx = NULL;
1772 unsigned int psk_len = 0;
1773 unsigned char psk[PSK_MAX_PSK_LEN];
1775 n=s->method->ssl_get_message(s,
1776 SSL3_ST_SR_KEY_EXCH_A,
1777 SSL3_ST_SR_KEY_EXCH_B,
1778 SSL3_MT_CLIENT_KEY_EXCHANGE,
1780 SSL_GET_MESSAGE_HASH_MESSAGE,
1783 if (!ok) return((int)n);
1784 CBS_init(&client_key_exchange, s->init_msg, n);
1786 alg_k=s->s3->tmp.new_cipher->algorithm_mkey;
1787 alg_a=s->s3->tmp.new_cipher->algorithm_auth;
1789 /* If using a PSK key exchange, prepare the pre-shared key. */
1790 if (alg_a & SSL_aPSK)
1794 /* If using PSK, the ClientKeyExchange contains a
1795 * psk_identity. If PSK, then this is the only field
1796 * in the message. */
1797 if (!CBS_get_u16_length_prefixed(&client_key_exchange, &psk_identity) ||
1798 ((alg_k & SSL_kPSK) && CBS_len(&client_key_exchange) != 0))
1800 OPENSSL_PUT_ERROR(SSL, ssl3_get_client_key_exchange, SSL_R_DECODE_ERROR);
1801 al = SSL_AD_DECODE_ERROR;
1805 if (s->psk_server_callback == NULL)
1807 OPENSSL_PUT_ERROR(SSL, ssl3_get_client_key_exchange, SSL_R_PSK_NO_SERVER_CB);
1808 al = SSL_AD_INTERNAL_ERROR;
1812 if (CBS_len(&psk_identity) > PSK_MAX_IDENTITY_LEN ||
1813 CBS_contains_zero_byte(&psk_identity))
1815 OPENSSL_PUT_ERROR(SSL, ssl3_get_client_key_exchange, SSL_R_DATA_LENGTH_TOO_LONG);
1816 al = SSL_AD_ILLEGAL_PARAMETER;
1820 if (!CBS_strdup(&psk_identity, &s->session->psk_identity))
1822 al = SSL_AD_INTERNAL_ERROR;
1823 OPENSSL_PUT_ERROR(SSL, ssl3_get_client_key_exchange, ERR_R_MALLOC_FAILURE);
1827 /* Look up the key for the identity. */
1828 psk_len = s->psk_server_callback(s, s->session->psk_identity, psk, sizeof(psk));
1829 if (psk_len > PSK_MAX_PSK_LEN)
1831 OPENSSL_PUT_ERROR(SSL, ssl3_get_client_key_exchange, ERR_R_INTERNAL_ERROR);
1832 al = SSL_AD_INTERNAL_ERROR;
1835 else if (psk_len == 0)
1837 /* PSK related to the given identity not found */
1838 OPENSSL_PUT_ERROR(SSL, ssl3_get_client_key_exchange, SSL_R_PSK_IDENTITY_NOT_FOUND);
1839 al = SSL_AD_UNKNOWN_PSK_IDENTITY;
1844 /* Depending on the key exchange method, compute |premaster_secret| and
1845 * |premaster_secret_len|. */
1846 if (alg_k & SSL_kRSA)
1848 CBS encrypted_premaster_secret;
1849 uint8_t rand_premaster_secret[SSL_MAX_MASTER_KEY_LENGTH];
1850 int decrypt_good_mask;
1851 uint8_t version_good;
1852 size_t rsa_size, decrypt_len, premaster_index, j;
1854 pkey=s->cert->pkeys[SSL_PKEY_RSA_ENC].privatekey;
1855 if ( (pkey == NULL) ||
1856 (pkey->type != EVP_PKEY_RSA) ||
1857 (pkey->pkey.rsa == NULL))
1859 al=SSL_AD_HANDSHAKE_FAILURE;
1860 OPENSSL_PUT_ERROR(SSL, ssl3_get_client_key_exchange, SSL_R_MISSING_RSA_CERTIFICATE);
1865 /* TLS and [incidentally] DTLS{0xFEFF} */
1866 if (s->version > SSL3_VERSION)
1868 CBS copy = client_key_exchange;
1869 if (!CBS_get_u16_length_prefixed(&client_key_exchange,
1870 &encrypted_premaster_secret) ||
1871 CBS_len(&client_key_exchange) != 0)
1873 if (!(s->options & SSL_OP_TLS_D5_BUG))
1875 al = SSL_AD_DECODE_ERROR;
1876 OPENSSL_PUT_ERROR(SSL, ssl3_get_client_key_exchange, SSL_R_TLS_RSA_ENCRYPTED_VALUE_LENGTH_IS_WRONG);
1880 encrypted_premaster_secret = copy;
1884 encrypted_premaster_secret = client_key_exchange;
1886 /* Reject overly short RSA keys because we want to be sure that
1887 * the buffer size makes it safe to iterate over the entire size
1888 * of a premaster secret (SSL_MAX_MASTER_KEY_LENGTH). The actual
1889 * expected size is larger due to RSA padding, but the bound is
1890 * sufficient to be safe. */
1891 rsa_size = RSA_size(rsa);
1892 if (rsa_size < SSL_MAX_MASTER_KEY_LENGTH)
1894 al = SSL_AD_DECRYPT_ERROR;
1895 OPENSSL_PUT_ERROR(SSL, ssl3_get_client_key_exchange, SSL_R_DECRYPTION_FAILED);
1899 /* We must not leak whether a decryption failure occurs because
1900 * of Bleichenbacher's attack on PKCS #1 v1.5 RSA padding (see
1901 * RFC 2246, section 7.4.7.1). The code follows that advice of
1902 * the TLS RFC and generates a random premaster secret for the
1903 * case that the decrypt fails. See
1904 * https://tools.ietf.org/html/rfc5246#section-7.4.7.1 */
1905 if (RAND_pseudo_bytes(rand_premaster_secret,
1906 sizeof(rand_premaster_secret)) <= 0)
1909 /* Allocate a buffer large enough for an RSA decryption. */
1910 decrypt_buf = OPENSSL_malloc(rsa_size);
1911 if (decrypt_buf == NULL)
1913 OPENSSL_PUT_ERROR(SSL, ssl3_get_client_key_exchange, ERR_R_MALLOC_FAILURE);
1917 /* Decrypt with no padding. PKCS#1 padding will be removed as
1918 * part of the timing-sensitive code below. */
1919 if (!RSA_decrypt(rsa, &decrypt_len, decrypt_buf, rsa_size,
1920 CBS_data(&encrypted_premaster_secret),
1921 CBS_len(&encrypted_premaster_secret),
1926 if (decrypt_len != rsa_size)
1928 /* This should never happen, but do a check so we do not
1929 * read uninitialized memory. */
1930 OPENSSL_PUT_ERROR(SSL, ssl3_get_client_key_exchange, ERR_R_INTERNAL_ERROR);
1934 /* Remove the PKCS#1 padding and adjust decrypt_len as
1935 * appropriate. decrypt_good_mask will be zero if the premaster
1936 * if good and non-zero otherwise. */
1937 decrypt_good_mask = RSA_message_index_PKCS1_type_2(
1938 decrypt_buf, decrypt_len, &premaster_index);
1939 decrypt_good_mask--;
1940 decrypt_len = decrypt_len - premaster_index;
1942 /* decrypt_len should be SSL_MAX_MASTER_KEY_LENGTH. */
1943 decrypt_good_mask |= decrypt_len ^ SSL_MAX_MASTER_KEY_LENGTH;
1945 /* Copy over the unpadded premaster. Whatever the value of
1946 * |decrypt_good_mask|, copy as if the premaster were the right
1947 * length. It is important the memory access pattern be
1949 premaster_secret = BUF_memdup(
1950 decrypt_buf + (rsa_size - SSL_MAX_MASTER_KEY_LENGTH),
1951 SSL_MAX_MASTER_KEY_LENGTH);
1952 if (premaster_secret == NULL)
1954 OPENSSL_PUT_ERROR(SSL, ssl3_get_client_key_exchange, ERR_R_MALLOC_FAILURE);
1957 OPENSSL_free(decrypt_buf);
1960 /* If the version in the decrypted pre-master secret is correct
1961 * then version_good will be zero. The Klima-Pokorny-Rosa
1962 * extension of Bleichenbacher's attack
1963 * (http://eprint.iacr.org/2003/052/) exploits the version
1964 * number check as a "bad version oracle". Thus version checks
1965 * are done in constant time and are treated like any other
1966 * decryption error. */
1967 version_good = premaster_secret[0] ^ (s->client_version>>8);
1968 version_good |= premaster_secret[1] ^ (s->client_version&0xff);
1970 /* If any bits in version_good are set then they'll poision
1971 * decrypt_good_mask and cause rand_premaster_secret to be
1973 decrypt_good_mask |= version_good;
1975 /* decrypt_good_mask will be zero iff decrypt_len ==
1976 * SSL_MAX_MASTER_KEY_LENGTH and the version check passed. We
1977 * fold the bottom 32 bits of it with an OR so that the LSB
1978 * will be zero iff everything is good. This assumes that we'll
1979 * never decrypt a value > 2**31 bytes, which seems safe. */
1980 decrypt_good_mask |= decrypt_good_mask >> 16;
1981 decrypt_good_mask |= decrypt_good_mask >> 8;
1982 decrypt_good_mask |= decrypt_good_mask >> 4;
1983 decrypt_good_mask |= decrypt_good_mask >> 2;
1984 decrypt_good_mask |= decrypt_good_mask >> 1;
1985 /* Now select only the LSB and subtract one. If decrypt_len ==
1986 * SSL_MAX_MASTER_KEY_LENGTH and the version check passed then
1987 * decrypt_good_mask will be all ones. Otherwise it'll be all
1989 decrypt_good_mask &= 1;
1990 decrypt_good_mask--;
1992 /* Now copy rand_premaster_secret over premaster_secret using
1993 * decrypt_good_mask. */
1994 for (j = 0; j < sizeof(rand_premaster_secret); j++)
1996 premaster_secret[j] = (premaster_secret[j] & decrypt_good_mask) |
1997 (rand_premaster_secret[j] & ~decrypt_good_mask);
2000 premaster_secret_len = sizeof(rand_premaster_secret);
2002 else if (alg_k & SSL_kEDH)
2007 if (!CBS_get_u16_length_prefixed(&client_key_exchange, &dh_Yc) ||
2008 CBS_len(&dh_Yc) == 0 ||
2009 CBS_len(&client_key_exchange) != 0)
2011 OPENSSL_PUT_ERROR(SSL, ssl3_get_client_key_exchange, SSL_R_DH_PUBLIC_VALUE_LENGTH_IS_WRONG);
2012 al = SSL_R_DECODE_ERROR;
2016 if (s->s3->tmp.dh == NULL)
2018 al=SSL_AD_HANDSHAKE_FAILURE;
2019 OPENSSL_PUT_ERROR(SSL, ssl3_get_client_key_exchange, SSL_R_MISSING_TMP_DH_KEY);
2022 dh_srvr=s->s3->tmp.dh;
2024 pub = BN_bin2bn(CBS_data(&dh_Yc), CBS_len(&dh_Yc), NULL);
2027 OPENSSL_PUT_ERROR(SSL, ssl3_get_client_key_exchange, SSL_R_BN_LIB);
2031 /* Allocate a buffer for the premaster secret. */
2032 premaster_secret = OPENSSL_malloc(DH_size(dh_srvr));
2033 if (premaster_secret == NULL)
2035 OPENSSL_PUT_ERROR(SSL, ssl3_get_client_key_exchange, ERR_R_MALLOC_FAILURE);
2039 dh_len = DH_compute_key(premaster_secret, pub, dh_srvr);
2042 OPENSSL_PUT_ERROR(SSL, ssl3_get_client_key_exchange, ERR_R_DH_LIB);
2047 DH_free(s->s3->tmp.dh);
2052 premaster_secret_len = dh_len;
2055 else if (alg_k & SSL_kEECDH)
2057 int field_size = 0, ecdh_len;
2059 const EC_GROUP *group;
2060 const BIGNUM *priv_key;
2063 /* initialize structures for server's ECDH key pair */
2064 if ((srvr_ecdh = EC_KEY_new()) == NULL)
2066 OPENSSL_PUT_ERROR(SSL, ssl3_get_client_key_exchange, ERR_R_MALLOC_FAILURE);
2070 /* Use the ephermeral values we saved when generating the
2071 * ServerKeyExchange msg. */
2072 tkey = s->s3->tmp.ecdh;
2074 group = EC_KEY_get0_group(tkey);
2075 priv_key = EC_KEY_get0_private_key(tkey);
2077 if (!EC_KEY_set_group(srvr_ecdh, group) ||
2078 !EC_KEY_set_private_key(srvr_ecdh, priv_key))
2080 OPENSSL_PUT_ERROR(SSL, ssl3_get_client_key_exchange, ERR_R_EC_LIB);
2084 /* Let's get client's public key */
2085 if ((clnt_ecpoint = EC_POINT_new(group)) == NULL)
2087 OPENSSL_PUT_ERROR(SSL, ssl3_get_client_key_exchange, ERR_R_MALLOC_FAILURE);
2091 /* Get client's public key from encoded point
2092 * in the ClientKeyExchange message.
2094 if (!CBS_get_u8_length_prefixed(&client_key_exchange, &ecdh_Yc) ||
2095 CBS_len(&client_key_exchange) != 0)
2097 al = SSL_AD_DECODE_ERROR;
2098 OPENSSL_PUT_ERROR(SSL, ssl3_get_client_key_exchange, SSL_R_DECODE_ERROR);
2102 if ((bn_ctx = BN_CTX_new()) == NULL)
2104 OPENSSL_PUT_ERROR(SSL, ssl3_get_client_key_exchange, ERR_R_MALLOC_FAILURE);
2108 if (!EC_POINT_oct2point(group, clnt_ecpoint,
2109 CBS_data(&ecdh_Yc), CBS_len(&ecdh_Yc), bn_ctx))
2111 OPENSSL_PUT_ERROR(SSL, ssl3_get_client_key_exchange, ERR_R_EC_LIB);
2115 /* Allocate a buffer for both the secret and the PSK. */
2116 field_size = EC_GROUP_get_degree(group);
2117 if (field_size <= 0)
2119 OPENSSL_PUT_ERROR(SSL, ssl3_get_client_key_exchange, ERR_R_ECDH_LIB);
2123 ecdh_len = (field_size + 7) / 8;
2124 premaster_secret = OPENSSL_malloc(ecdh_len);
2125 if (premaster_secret == NULL)
2127 OPENSSL_PUT_ERROR(SSL, ssl3_get_client_key_exchange, ERR_R_MALLOC_FAILURE);
2131 /* Compute the shared pre-master secret */
2132 ecdh_len = ECDH_compute_key(premaster_secret,
2133 ecdh_len, clnt_ecpoint, srvr_ecdh, NULL);
2136 OPENSSL_PUT_ERROR(SSL, ssl3_get_client_key_exchange, ERR_R_ECDH_LIB);
2140 EVP_PKEY_free(clnt_pub_pkey);
2141 clnt_pub_pkey = NULL;
2142 EC_POINT_free(clnt_ecpoint);
2143 clnt_ecpoint = NULL;
2144 EC_KEY_free(srvr_ecdh);
2146 BN_CTX_free(bn_ctx);
2148 EC_KEY_free(s->s3->tmp.ecdh);
2149 s->s3->tmp.ecdh = NULL;
2151 premaster_secret_len = ecdh_len;
2153 else if (alg_k & SSL_kPSK)
2155 /* For plain PSK, other_secret is a block of 0s with the same
2156 * length as the pre-shared key. */
2157 premaster_secret_len = psk_len;
2158 premaster_secret = OPENSSL_malloc(premaster_secret_len);
2159 if (premaster_secret == NULL)
2161 OPENSSL_PUT_ERROR(SSL, ssl3_get_client_key_exchange, ERR_R_MALLOC_FAILURE);
2164 memset(premaster_secret, 0, premaster_secret_len);
2168 al=SSL_AD_HANDSHAKE_FAILURE;
2169 OPENSSL_PUT_ERROR(SSL, ssl3_get_client_key_exchange, SSL_R_UNKNOWN_CIPHER_TYPE);
2173 /* For a PSK cipher suite, the actual pre-master secret is combined with
2174 * the pre-shared key. */
2175 if (alg_a & SSL_aPSK)
2177 CBB new_premaster, child;
2181 if (!CBB_init(&new_premaster, 2 + psk_len + 2 + premaster_secret_len))
2183 OPENSSL_PUT_ERROR(SSL, ssl3_get_client_key_exchange, ERR_R_MALLOC_FAILURE);
2186 if (!CBB_add_u16_length_prefixed(&new_premaster, &child) ||
2187 !CBB_add_bytes(&child, premaster_secret, premaster_secret_len) ||
2188 !CBB_add_u16_length_prefixed(&new_premaster, &child) ||
2189 !CBB_add_bytes(&child, psk, psk_len) ||
2190 !CBB_finish(&new_premaster, &new_data, &new_len))
2192 OPENSSL_PUT_ERROR(SSL, ssl3_get_client_key_exchange, ERR_R_INTERNAL_ERROR);
2193 CBB_cleanup(&new_premaster);
2197 OPENSSL_cleanse(premaster_secret, premaster_secret_len);
2198 OPENSSL_free(premaster_secret);
2199 premaster_secret = new_data;
2200 premaster_secret_len = new_len;
2203 /* Compute the master secret */
2204 s->session->master_key_length = s->method->ssl3_enc
2205 ->generate_master_secret(s,
2206 s->session->master_key, premaster_secret, premaster_secret_len);
2207 if (s->session->master_key_length == 0)
2209 s->session->extended_master_secret = s->s3->tmp.extended_master_secret;
2211 OPENSSL_cleanse(premaster_secret, premaster_secret_len);
2212 OPENSSL_free(premaster_secret);
2215 ssl3_send_alert(s,SSL3_AL_FATAL,al);
2217 if (premaster_secret)
2219 if (premaster_secret_len)
2220 OPENSSL_cleanse(premaster_secret, premaster_secret_len);
2221 OPENSSL_free(premaster_secret);
2224 OPENSSL_free(decrypt_buf);
2225 EVP_PKEY_free(clnt_pub_pkey);
2226 EC_POINT_free(clnt_ecpoint);
2227 if (srvr_ecdh != NULL)
2228 EC_KEY_free(srvr_ecdh);
2229 BN_CTX_free(bn_ctx);
2233 int ssl3_get_cert_verify(SSL *s)
2237 CBS certificate_verify, signature;
2238 X509 *peer = s->session->peer;
2239 EVP_PKEY *pkey = NULL;
2240 const EVP_MD *md = NULL;
2241 uint8_t digest[EVP_MAX_MD_SIZE];
2242 size_t digest_length;
2243 EVP_PKEY_CTX *pctx = NULL;
2245 /* Only RSA and ECDSA client certificates are supported, so a
2246 * CertificateVerify is required if and only if there's a
2247 * client certificate. */
2250 if (s->s3->handshake_buffer && !ssl3_digest_cached_records(s, free_handshake_buffer))
2255 n=s->method->ssl_get_message(s,
2256 SSL3_ST_SR_CERT_VRFY_A,
2257 SSL3_ST_SR_CERT_VRFY_B,
2258 SSL3_MT_CERTIFICATE_VERIFY,
2259 SSL3_RT_MAX_PLAIN_LENGTH,
2260 SSL_GET_MESSAGE_DONT_HASH_MESSAGE,
2266 /* Filter out unsupported certificate types. */
2267 pkey = X509_get_pubkey(peer);
2268 if (!(X509_certificate_type(peer, pkey) & EVP_PKT_SIGN) ||
2269 (pkey->type != EVP_PKEY_RSA && pkey->type != EVP_PKEY_EC))
2271 al = SSL_AD_UNSUPPORTED_CERTIFICATE;
2272 OPENSSL_PUT_ERROR(SSL, ssl3_get_cert_verify, SSL_R_PEER_ERROR_UNSUPPORTED_CERTIFICATE_TYPE);
2276 CBS_init(&certificate_verify, s->init_msg, n);
2278 /* Determine the digest type if needbe. */
2279 if (SSL_USE_SIGALGS(s))
2281 if (!tls12_check_peer_sigalg(&md, &al, s, &certificate_verify, pkey))
2285 /* Compute the digest. */
2286 if (!ssl3_cert_verify_hash(s, digest, &digest_length, &md, pkey))
2289 /* The handshake buffer is no longer necessary, and we may hash the
2290 * current message.*/
2291 if (s->s3->handshake_buffer && !ssl3_digest_cached_records(s, free_handshake_buffer))
2293 ssl3_hash_current_message(s);
2295 /* Parse and verify the signature. */
2296 if (!CBS_get_u16_length_prefixed(&certificate_verify, &signature) ||
2297 CBS_len(&certificate_verify) != 0)
2299 al = SSL_AD_DECODE_ERROR;
2300 OPENSSL_PUT_ERROR(SSL, ssl3_get_cert_verify, SSL_R_DECODE_ERROR);
2304 pctx = EVP_PKEY_CTX_new(pkey, NULL);
2307 if (!EVP_PKEY_verify_init(pctx) ||
2308 !EVP_PKEY_CTX_set_signature_md(pctx, md) ||
2309 !EVP_PKEY_verify(pctx, CBS_data(&signature), CBS_len(&signature),
2310 digest, digest_length))
2312 al = SSL_AD_DECRYPT_ERROR;
2313 OPENSSL_PUT_ERROR(SSL, ssl3_get_cert_verify, SSL_R_BAD_SIGNATURE);
2321 ssl3_send_alert(s,SSL3_AL_FATAL,al);
2324 EVP_PKEY_CTX_free(pctx);
2325 EVP_PKEY_free(pkey);
2329 int ssl3_get_client_certificate(SSL *s)
2331 int i,ok,al,ret= -1;
2334 STACK_OF(X509) *sk=NULL;
2336 CBS certificate_msg, certificate_list;
2337 int is_first_certificate = 1;
2339 n=s->method->ssl_get_message(s,
2344 SSL_GET_MESSAGE_HASH_MESSAGE,
2347 if (!ok) return((int)n);
2349 if (s->s3->tmp.message_type == SSL3_MT_CLIENT_KEY_EXCHANGE)
2351 if ( (s->verify_mode & SSL_VERIFY_PEER) &&
2352 (s->verify_mode & SSL_VERIFY_FAIL_IF_NO_PEER_CERT))
2354 OPENSSL_PUT_ERROR(SSL, ssl3_get_client_certificate, SSL_R_PEER_DID_NOT_RETURN_A_CERTIFICATE);
2355 al=SSL_AD_HANDSHAKE_FAILURE;
2358 /* If tls asked for a client cert, the client must return a 0 list */
2359 if ((s->version > SSL3_VERSION) && s->s3->tmp.cert_request)
2361 OPENSSL_PUT_ERROR(SSL, ssl3_get_client_certificate, SSL_R_TLS_PEER_DID_NOT_RESPOND_WITH_CERTIFICATE_LIST);
2362 al=SSL_AD_UNEXPECTED_MESSAGE;
2365 s->s3->tmp.reuse_message=1;
2369 if (s->s3->tmp.message_type != SSL3_MT_CERTIFICATE)
2371 al=SSL_AD_UNEXPECTED_MESSAGE;
2372 OPENSSL_PUT_ERROR(SSL, ssl3_get_client_certificate, SSL_R_WRONG_MESSAGE_TYPE);
2376 CBS_init(&certificate_msg, s->init_msg, n);
2378 if ((sk=sk_X509_new_null()) == NULL)
2380 OPENSSL_PUT_ERROR(SSL, ssl3_get_client_certificate, ERR_R_MALLOC_FAILURE);
2384 if (!CBS_get_u24_length_prefixed(&certificate_msg, &certificate_list) ||
2385 CBS_len(&certificate_msg) != 0)
2387 al = SSL_AD_DECODE_ERROR;
2388 OPENSSL_PUT_ERROR(SSL, ssl3_get_client_certificate, SSL_R_DECODE_ERROR);
2392 while (CBS_len(&certificate_list) > 0)
2395 const uint8_t *data;
2397 if (!CBS_get_u24_length_prefixed(&certificate_list, &certificate))
2399 al = SSL_AD_DECODE_ERROR;
2400 OPENSSL_PUT_ERROR(SSL, ssl3_get_client_certificate, SSL_R_DECODE_ERROR);
2403 if (is_first_certificate && s->ctx->retain_only_sha256_of_client_certs)
2405 /* If this is the first certificate, and we don't want
2406 * to keep peer certificates in memory, then we hash it
2408 SHA256_Init(&sha256);
2409 SHA256_Update(&sha256, CBS_data(&certificate), CBS_len(&certificate));
2410 SHA256_Final(s->session->peer_sha256, &sha256);
2411 s->session->peer_sha256_valid = 1;
2413 is_first_certificate = 0;
2414 data = CBS_data(&certificate);
2415 x = d2i_X509(NULL, &data, CBS_len(&certificate));
2418 al = SSL_AD_BAD_CERTIFICATE;
2419 OPENSSL_PUT_ERROR(SSL, ssl3_get_client_certificate, ERR_R_ASN1_LIB);
2422 if (!CBS_skip(&certificate, data - CBS_data(&certificate)))
2424 al = SSL_AD_INTERNAL_ERROR;
2425 OPENSSL_PUT_ERROR(SSL, ssl3_get_client_certificate, ERR_R_INTERNAL_ERROR);
2428 if (CBS_len(&certificate) != 0)
2430 al = SSL_AD_DECODE_ERROR;
2431 OPENSSL_PUT_ERROR(SSL, ssl3_get_client_certificate, SSL_R_CERT_LENGTH_MISMATCH);
2434 if (!sk_X509_push(sk,x))
2436 OPENSSL_PUT_ERROR(SSL, ssl3_get_client_certificate, ERR_R_MALLOC_FAILURE);
2442 if (sk_X509_num(sk) <= 0)
2444 /* TLS does not mind 0 certs returned */
2445 if (s->version == SSL3_VERSION)
2447 al=SSL_AD_HANDSHAKE_FAILURE;
2448 OPENSSL_PUT_ERROR(SSL, ssl3_get_client_certificate, SSL_R_NO_CERTIFICATES_RETURNED);
2451 /* Fail for TLS only if we required a certificate */
2452 else if ((s->verify_mode & SSL_VERIFY_PEER) &&
2453 (s->verify_mode & SSL_VERIFY_FAIL_IF_NO_PEER_CERT))
2455 OPENSSL_PUT_ERROR(SSL, ssl3_get_client_certificate, SSL_R_PEER_DID_NOT_RETURN_A_CERTIFICATE);
2456 al=SSL_AD_HANDSHAKE_FAILURE;
2459 /* No client certificate so digest cached records */
2460 if (s->s3->handshake_buffer && !ssl3_digest_cached_records(s, free_handshake_buffer))
2462 al=SSL_AD_INTERNAL_ERROR;
2468 i=ssl_verify_cert_chain(s,sk);
2471 al=ssl_verify_alarm_type(s->verify_result);
2472 OPENSSL_PUT_ERROR(SSL, ssl3_get_client_certificate, SSL_R_CERTIFICATE_VERIFY_FAILED);
2477 if (s->session->peer != NULL) /* This should not be needed */
2478 X509_free(s->session->peer);
2479 s->session->peer=sk_X509_shift(sk);
2480 s->session->verify_result = s->verify_result;
2482 /* With the current implementation, sess_cert will always be NULL
2483 * when we arrive here. */
2484 if (s->session->sess_cert == NULL)
2486 s->session->sess_cert = ssl_sess_cert_new();
2487 if (s->session->sess_cert == NULL)
2489 OPENSSL_PUT_ERROR(SSL, ssl3_get_client_certificate, ERR_R_MALLOC_FAILURE);
2493 if (s->session->sess_cert->cert_chain != NULL)
2494 sk_X509_pop_free(s->session->sess_cert->cert_chain, X509_free);
2495 s->session->sess_cert->cert_chain=sk;
2496 /* Inconsistency alert: cert_chain does *not* include the
2497 * peer's own certificate, while we do include it in s3_clnt.c */
2505 ssl3_send_alert(s,SSL3_AL_FATAL,al);
2508 if (x != NULL) X509_free(x);
2509 if (sk != NULL) sk_X509_pop_free(sk,X509_free);
2513 int ssl3_send_server_certificate(SSL *s)
2517 if (s->state == SSL3_ST_SW_CERT_A)
2519 cpk=ssl_get_server_send_pkey(s);
2522 OPENSSL_PUT_ERROR(SSL, ssl3_send_server_certificate, ERR_R_INTERNAL_ERROR);
2526 ssl3_output_cert_chain(s,cpk);
2527 s->state=SSL3_ST_SW_CERT_B;
2530 /* SSL3_ST_SW_CERT_B */
2531 return ssl_do_write(s);
2534 /* send a new session ticket (not necessarily for a new session) */
2535 int ssl3_send_new_session_ticket(SSL *s)
2537 if (s->state == SSL3_ST_SW_SESSION_TICKET_A)
2541 uint8_t *p, *macstart;
2546 SSL_CTX *tctx = s->initial_ctx;
2547 unsigned char iv[EVP_MAX_IV_LENGTH];
2548 unsigned char key_name[16];
2549 /* The maximum overhead of encrypting the session is 16 (key
2550 * name) + IV + one block of encryption overhead + HMAC. */
2551 const size_t max_ticket_overhead = 16 + EVP_MAX_IV_LENGTH +
2552 EVP_MAX_BLOCK_LENGTH + EVP_MAX_MD_SIZE;
2554 /* Serialize the SSL_SESSION to be encoded into the ticket. */
2555 if (!SSL_SESSION_to_bytes_for_ticket(s->session, &session,
2561 /* If the session is too long, emit a dummy value rather than
2562 * abort the connection. */
2563 if (session_len > 0xFFFF - max_ticket_overhead)
2565 const char kTicketPlaceholder[] = "TICKET TOO LARGE";
2566 size_t placeholder_len = strlen(kTicketPlaceholder);
2568 OPENSSL_free(session);
2570 p = ssl_handshake_start(s);
2571 /* Emit ticket_lifetime_hint. */
2574 s2n(placeholder_len, p);
2575 memcpy(p, kTicketPlaceholder, placeholder_len);
2576 p += placeholder_len;
2578 len = p - ssl_handshake_start(s);
2579 ssl_set_handshake_header(s, SSL3_MT_NEWSESSION_TICKET, len);
2580 s->state = SSL3_ST_SW_SESSION_TICKET_B;
2581 return ssl_do_write(s);
2584 /* Grow buffer if need be: the length calculation is as
2585 * follows: handshake_header_length +
2586 * 4 (ticket lifetime hint) + 2 (ticket length) +
2587 * max_ticket_overhead + * session_length */
2588 if (!BUF_MEM_grow(s->init_buf,
2589 SSL_HM_HEADER_LENGTH(s) + 6 +
2590 max_ticket_overhead + session_len))
2592 OPENSSL_free(session);
2595 p = ssl_handshake_start(s);
2596 EVP_CIPHER_CTX_init(&ctx);
2597 HMAC_CTX_init(&hctx);
2598 /* Initialize HMAC and cipher contexts. If callback present
2599 * it does all the work otherwise use generated values
2602 if (tctx->tlsext_ticket_key_cb)
2604 if (tctx->tlsext_ticket_key_cb(s, key_name, iv, &ctx,
2607 OPENSSL_free(session);
2613 RAND_pseudo_bytes(iv, 16);
2614 EVP_EncryptInit_ex(&ctx, EVP_aes_128_cbc(), NULL,
2615 tctx->tlsext_tick_aes_key, iv);
2616 HMAC_Init_ex(&hctx, tctx->tlsext_tick_hmac_key, 16,
2617 tlsext_tick_md(), NULL);
2618 memcpy(key_name, tctx->tlsext_tick_key_name, 16);
2621 /* Ticket lifetime hint (advisory only):
2622 * We leave this unspecified for resumed session (for simplicity),
2623 * and guess that tickets for new sessions will live as long
2624 * as their sessions. */
2625 l2n(s->hit ? 0 : s->session->timeout, p);
2627 /* Skip ticket length for now */
2629 /* Output key name */
2631 memcpy(p, key_name, 16);
2634 memcpy(p, iv, EVP_CIPHER_CTX_iv_length(&ctx));
2635 p += EVP_CIPHER_CTX_iv_length(&ctx);
2636 /* Encrypt session data */
2637 EVP_EncryptUpdate(&ctx, p, &len, session, session_len);
2639 EVP_EncryptFinal_ex(&ctx, p, &len);
2641 EVP_CIPHER_CTX_cleanup(&ctx);
2643 HMAC_Update(&hctx, macstart, p - macstart);
2644 HMAC_Final(&hctx, p, &hlen);
2645 HMAC_CTX_cleanup(&hctx);
2648 /* Now write out lengths: p points to end of data written */
2650 len = p - ssl_handshake_start(s);
2651 ssl_set_handshake_header(s, SSL3_MT_NEWSESSION_TICKET, len);
2652 /* Skip ticket lifetime hint */
2653 p = ssl_handshake_start(s) + 4;
2655 s->state=SSL3_ST_SW_SESSION_TICKET_B;
2656 OPENSSL_free(session);
2659 /* SSL3_ST_SW_SESSION_TICKET_B */
2660 return ssl_do_write(s);
2664 int ssl3_send_cert_status(SSL *s)
2666 if (s->state == SSL3_ST_SW_CERT_STATUS_A)
2669 /* Grow buffer if need be: the length calculation is as
2670 * follows 1 (message type) + 3 (message length) +
2671 * 1 (ocsp response type) + 3 (ocsp response length)
2674 if (!BUF_MEM_grow(s->init_buf, 8 + s->tlsext_ocsp_resplen))
2677 p=(unsigned char *)s->init_buf->data;
2680 *(p++)=SSL3_MT_CERTIFICATE_STATUS;
2681 /* message length */
2682 l2n3(s->tlsext_ocsp_resplen + 4, p);
2684 *(p++)= s->tlsext_status_type;
2685 /* length of OCSP response */
2686 l2n3(s->tlsext_ocsp_resplen, p);
2687 /* actual response */
2688 memcpy(p, s->tlsext_ocsp_resp, s->tlsext_ocsp_resplen);
2689 /* number of bytes to write */
2690 s->init_num = 8 + s->tlsext_ocsp_resplen;
2691 s->state=SSL3_ST_SW_CERT_STATUS_B;
2695 /* SSL3_ST_SW_CERT_STATUS_B */
2696 return(ssl3_do_write(s,SSL3_RT_HANDSHAKE));
2700 /* ssl3_get_next_proto reads a Next Protocol Negotiation handshake message. It
2701 * sets the next_proto member in s if found */
2702 int ssl3_get_next_proto(SSL *s)
2706 CBS next_protocol, selected_protocol, padding;
2708 /* Clients cannot send a NextProtocol message if we didn't see the
2709 * extension in their ClientHello */
2710 if (!s->s3->next_proto_neg_seen)
2712 OPENSSL_PUT_ERROR(SSL, ssl3_get_next_proto, SSL_R_GOT_NEXT_PROTO_WITHOUT_EXTENSION);
2716 n=s->method->ssl_get_message(s,
2717 SSL3_ST_SR_NEXT_PROTO_A,
2718 SSL3_ST_SR_NEXT_PROTO_B,
2720 514, /* See the payload format below */
2721 SSL_GET_MESSAGE_HASH_MESSAGE,
2727 /* s->state doesn't reflect whether ChangeCipherSpec has been received
2728 * in this handshake, but s->s3->change_cipher_spec does (will be reset
2729 * by ssl3_get_finished).
2730 * TODO(davidben): Is this check now redundant with
2731 * SSL3_FLAGS_EXPECT_CCS? */
2732 if (!s->s3->change_cipher_spec)
2734 OPENSSL_PUT_ERROR(SSL, ssl3_get_next_proto, SSL_R_GOT_NEXT_PROTO_BEFORE_A_CCS);
2738 CBS_init(&next_protocol, s->init_msg, n);
2740 /* The payload looks like:
2742 * uint8 proto[proto_len];
2743 * uint8 padding_len;
2744 * uint8 padding[padding_len];
2746 if (!CBS_get_u8_length_prefixed(&next_protocol, &selected_protocol) ||
2747 !CBS_get_u8_length_prefixed(&next_protocol, &padding) ||
2748 CBS_len(&next_protocol) != 0)
2751 if (!CBS_stow(&selected_protocol,
2752 &s->next_proto_negotiated,
2753 &s->next_proto_negotiated_len))
2759 /* ssl3_get_channel_id reads and verifies a ClientID handshake message. */
2760 int ssl3_get_channel_id(SSL *s)
2765 uint8_t channel_id_hash[SHA256_DIGEST_LENGTH];
2766 unsigned int channel_id_hash_len;
2768 uint16_t extension_type, expected_extension_type;
2769 EC_GROUP* p256 = NULL;
2771 EC_POINT* point = NULL;
2774 CBS encrypted_extensions, extension;
2776 n = s->method->ssl_get_message(s,
2777 SSL3_ST_SR_CHANNEL_ID_A,
2778 SSL3_ST_SR_CHANNEL_ID_B,
2779 SSL3_MT_ENCRYPTED_EXTENSIONS,
2780 2 + 2 + TLSEXT_CHANNEL_ID_SIZE,
2781 SSL_GET_MESSAGE_DONT_HASH_MESSAGE,
2787 /* Before incorporating the EncryptedExtensions message to the
2788 * handshake hash, compute the hash that should have been signed. */
2789 channel_id_hash_len = sizeof(channel_id_hash);
2790 EVP_MD_CTX_init(&md_ctx);
2791 if (!EVP_DigestInit_ex(&md_ctx, EVP_sha256(), NULL) ||
2792 !tls1_channel_id_hash(&md_ctx, s) ||
2793 !EVP_DigestFinal(&md_ctx, channel_id_hash, &channel_id_hash_len))
2795 EVP_MD_CTX_cleanup(&md_ctx);
2798 EVP_MD_CTX_cleanup(&md_ctx);
2799 assert(channel_id_hash_len == SHA256_DIGEST_LENGTH);
2801 ssl3_hash_current_message(s);
2803 /* s->state doesn't reflect whether ChangeCipherSpec has been received
2804 * in this handshake, but s->s3->change_cipher_spec does (will be reset
2805 * by ssl3_get_finished).
2806 * TODO(davidben): Is this check now redundant with
2807 * SSL3_FLAGS_EXPECT_CCS? */
2808 if (!s->s3->change_cipher_spec)
2810 OPENSSL_PUT_ERROR(SSL, ssl3_get_channel_id, SSL_R_GOT_CHANNEL_ID_BEFORE_A_CCS);
2814 CBS_init(&encrypted_extensions, s->init_msg, n);
2816 /* EncryptedExtensions could include multiple extensions, but
2817 * the only extension that could be negotiated is ChannelID,
2818 * so there can only be one entry.
2820 * The payload looks like:
2821 * uint16 extension_type
2822 * uint16 extension_len;
2828 expected_extension_type = TLSEXT_TYPE_channel_id;
2829 if (s->s3->tlsext_channel_id_new)
2830 expected_extension_type = TLSEXT_TYPE_channel_id_new;
2832 if (!CBS_get_u16(&encrypted_extensions, &extension_type) ||
2833 !CBS_get_u16_length_prefixed(&encrypted_extensions, &extension) ||
2834 CBS_len(&encrypted_extensions) != 0 ||
2835 extension_type != expected_extension_type ||
2836 CBS_len(&extension) != TLSEXT_CHANNEL_ID_SIZE)
2838 OPENSSL_PUT_ERROR(SSL, ssl3_get_channel_id, SSL_R_INVALID_MESSAGE);
2842 p256 = EC_GROUP_new_by_curve_name(NID_X9_62_prime256v1);
2845 OPENSSL_PUT_ERROR(SSL, ssl3_get_channel_id, SSL_R_NO_P256_SUPPORT);
2854 p = CBS_data(&extension);
2855 if (BN_bin2bn(p + 0, 32, &x) == NULL ||
2856 BN_bin2bn(p + 32, 32, &y) == NULL ||
2857 BN_bin2bn(p + 64, 32, sig.r) == NULL ||
2858 BN_bin2bn(p + 96, 32, sig.s) == NULL)
2861 point = EC_POINT_new(p256);
2863 !EC_POINT_set_affine_coordinates_GFp(p256, point, &x, &y, NULL))
2868 !EC_KEY_set_group(key, p256) ||
2869 !EC_KEY_set_public_key(key, point))
2872 /* We stored the handshake hash in |tlsext_channel_id| the first time
2873 * that we were called. */
2874 if (!ECDSA_do_verify(channel_id_hash, channel_id_hash_len, &sig, key))
2876 OPENSSL_PUT_ERROR(SSL, ssl3_get_channel_id, SSL_R_CHANNEL_ID_SIGNATURE_INVALID);
2877 s->s3->tlsext_channel_id_valid = 0;
2881 memcpy(s->s3->tlsext_channel_id, p, 64);
2892 EC_POINT_free(point);
2894 EC_GROUP_free(p256);