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
154 #include <openssl/bn.h>
155 #include <openssl/buf.h>
156 #include <openssl/bytestring.h>
157 #include <openssl/cipher.h>
158 #include <openssl/dh.h>
159 #include <openssl/ec.h>
160 #include <openssl/ecdsa.h>
161 #include <openssl/evp.h>
162 #include <openssl/hmac.h>
163 #include <openssl/md5.h>
164 #include <openssl/mem.h>
165 #include <openssl/obj.h>
166 #include <openssl/rand.h>
167 #include <openssl/sha.h>
168 #include <openssl/x509.h>
170 #include "ssl_locl.h"
171 #include "../crypto/dh/internal.h"
173 static const SSL_METHOD *ssl3_get_server_method(int ver);
175 static const SSL_METHOD *ssl3_get_server_method(int ver)
177 if (ver == SSL3_VERSION)
178 return(SSLv3_server_method());
183 IMPLEMENT_ssl3_meth_func(SSLv3_server_method,
185 ssl_undefined_function,
186 ssl3_get_server_method)
188 int ssl3_accept(SSL *s)
192 void (*cb)(const SSL *ssl,int type,int val)=NULL;
194 int new_state,state,skip=0;
197 ERR_clear_system_error();
199 if (s->info_callback != NULL)
201 else if (s->ctx->info_callback != NULL)
202 cb=s->ctx->info_callback;
204 /* init things to blank */
206 if (!SSL_in_init(s) || SSL_in_before(s)) SSL_clear(s);
210 OPENSSL_PUT_ERROR(SSL, ssl3_accept, SSL_R_NO_CERTIFICATE_SET);
220 case SSL_ST_RENEGOTIATE:
222 /* s->state=SSL_ST_ACCEPT; */
226 case SSL_ST_BEFORE|SSL_ST_ACCEPT:
227 case SSL_ST_OK|SSL_ST_ACCEPT:
230 if (cb != NULL) cb(s,SSL_CB_HANDSHAKE_START,1);
232 if ((s->version>>8) != 3)
234 OPENSSL_PUT_ERROR(SSL, ssl3_accept, ERR_R_INTERNAL_ERROR);
237 s->type=SSL_ST_ACCEPT;
239 if (s->init_buf == NULL)
241 if ((buf=BUF_MEM_new()) == NULL)
246 if (!BUF_MEM_grow(buf,SSL3_RT_MAX_PLAIN_LENGTH))
254 if (!ssl3_setup_buffers(s))
261 s->s3->flags &= ~SSL3_FLAGS_SGC_RESTART_DONE;
262 s->s3->flags &= ~TLS1_FLAGS_SKIP_CERT_VERIFY;
264 if (s->state != SSL_ST_RENEGOTIATE)
266 /* Ok, we now need to push on a buffering BIO so that
267 * the output is sent in a way that TCP likes :-)
269 if (!ssl_init_wbio_buffer(s,1)) { ret= -1; goto end; }
271 ssl3_init_finished_mac(s);
272 s->state=SSL3_ST_SR_CLNT_HELLO_A;
273 s->ctx->stats.sess_accept++;
275 else if (!s->s3->send_connection_binding &&
276 !(s->options & SSL_OP_ALLOW_UNSAFE_LEGACY_RENEGOTIATION))
278 /* Server attempting to renegotiate with
279 * client that doesn't support secure
282 OPENSSL_PUT_ERROR(SSL, ssl3_accept, SSL_R_UNSAFE_LEGACY_RENEGOTIATION_DISABLED);
283 ssl3_send_alert(s,SSL3_AL_FATAL,SSL_AD_HANDSHAKE_FAILURE);
289 /* s->state == SSL_ST_RENEGOTIATE,
290 * we will just send a HelloRequest */
291 s->ctx->stats.sess_accept_renegotiate++;
292 s->state=SSL3_ST_SW_HELLO_REQ_A;
296 case SSL3_ST_SW_HELLO_REQ_A:
297 case SSL3_ST_SW_HELLO_REQ_B:
300 ret=ssl3_send_hello_request(s);
301 if (ret <= 0) goto end;
302 s->s3->tmp.next_state=SSL3_ST_SW_HELLO_REQ_C;
303 s->state=SSL3_ST_SW_FLUSH;
306 ssl3_init_finished_mac(s);
309 case SSL3_ST_SW_HELLO_REQ_C:
313 case SSL3_ST_SR_CLNT_HELLO_A:
314 case SSL3_ST_SR_CLNT_HELLO_B:
315 case SSL3_ST_SR_CLNT_HELLO_C:
316 case SSL3_ST_SR_CLNT_HELLO_D:
318 ret=ssl3_get_client_hello(s);
319 if (ret == PENDING_SESSION) {
320 s->rwstate = SSL_PENDING_SESSION;
323 if (ret == CERTIFICATE_SELECTION_PENDING)
325 s->rwstate = SSL_CERTIFICATE_SELECTION_PENDING;
328 if (ret <= 0) goto end;
330 s->state=SSL3_ST_SW_SRVR_HELLO_A;
334 case SSL3_ST_SW_SRVR_HELLO_A:
335 case SSL3_ST_SW_SRVR_HELLO_B:
336 ret=ssl3_send_server_hello(s);
337 if (ret <= 0) goto end;
340 if (s->tlsext_ticket_expected)
341 s->state=SSL3_ST_SW_SESSION_TICKET_A;
343 s->state=SSL3_ST_SW_CHANGE_A;
346 s->state = SSL3_ST_SW_CERT_A;
350 case SSL3_ST_SW_CERT_A:
351 case SSL3_ST_SW_CERT_B:
352 if (ssl_cipher_has_server_public_key(s->s3->tmp.new_cipher))
354 ret=ssl3_send_server_certificate(s);
355 if (ret <= 0) goto end;
356 if (s->tlsext_status_expected)
357 s->state=SSL3_ST_SW_CERT_STATUS_A;
359 s->state=SSL3_ST_SW_KEY_EXCH_A;
364 s->state=SSL3_ST_SW_KEY_EXCH_A;
369 case SSL3_ST_SW_KEY_EXCH_A:
370 case SSL3_ST_SW_KEY_EXCH_B:
371 alg_a = s->s3->tmp.new_cipher->algorithm_auth;
373 /* Send a ServerKeyExchange message if:
374 * - The key exchange is ephemeral or anonymous
376 * - There is a PSK identity hint.
378 * TODO(davidben): This logic is currently duplicated
379 * in d1_srvr.c. Fix this. In the meantime, keep them
382 if (ssl_cipher_requires_server_key_exchange(s->s3->tmp.new_cipher) ||
383 ((alg_a & SSL_aPSK) && s->session->psk_identity_hint))
385 ret=ssl3_send_server_key_exchange(s);
386 if (ret <= 0) goto end;
391 s->state=SSL3_ST_SW_CERT_REQ_A;
395 case SSL3_ST_SW_CERT_REQ_A:
396 case SSL3_ST_SW_CERT_REQ_B:
397 if (/* don't request cert unless asked for it: */
398 !(s->verify_mode & SSL_VERIFY_PEER) ||
399 /* Don't request a certificate if an obc was presented */
400 ((s->verify_mode & SSL_VERIFY_PEER_IF_NO_OBC) &&
401 s->s3->tlsext_channel_id_valid) ||
402 /* if SSL_VERIFY_CLIENT_ONCE is set,
403 * don't request cert during re-negotiation: */
404 ((s->session->peer != NULL) &&
405 (s->verify_mode & SSL_VERIFY_CLIENT_ONCE)) ||
406 /* never request cert in anonymous ciphersuites
407 * (see section "Certificate request" in SSL 3 drafts
408 * and in RFC 2246): */
409 ((s->s3->tmp.new_cipher->algorithm_auth & SSL_aNULL) &&
410 /* ... except when the application insists on verification
411 * (against the specs, but s3_clnt.c accepts this for SSL 3) */
412 !(s->verify_mode & SSL_VERIFY_FAIL_IF_NO_PEER_CERT)) ||
413 /* With normal PSK Certificates and
414 * Certificate Requests are omitted */
415 (s->s3->tmp.new_cipher->algorithm_mkey & SSL_kPSK))
417 /* no cert request */
419 s->s3->tmp.cert_request=0;
420 s->state=SSL3_ST_SW_SRVR_DONE_A;
421 if (s->s3->handshake_buffer)
422 if (!ssl3_digest_cached_records(s))
427 s->s3->tmp.cert_request=1;
428 ret=ssl3_send_certificate_request(s);
429 if (ret <= 0) goto end;
430 #ifndef NETSCAPE_HANG_BUG
431 s->state=SSL3_ST_SW_SRVR_DONE_A;
433 s->state=SSL3_ST_SW_FLUSH;
434 s->s3->tmp.next_state=SSL3_ST_SR_CERT_A;
440 case SSL3_ST_SW_SRVR_DONE_A:
441 case SSL3_ST_SW_SRVR_DONE_B:
442 ret=ssl3_send_server_done(s);
443 if (ret <= 0) goto end;
444 s->s3->tmp.next_state=SSL3_ST_SR_CERT_A;
445 s->state=SSL3_ST_SW_FLUSH;
449 case SSL3_ST_SW_FLUSH:
451 /* This code originally checked to see if
452 * any data was pending using BIO_CTRL_INFO
453 * and then flushed. This caused problems
454 * as documented in PR#1939. The proposed
455 * fix doesn't completely resolve this issue
456 * as buggy implementations of BIO_CTRL_PENDING
457 * still exist. So instead we just flush
461 s->rwstate=SSL_WRITING;
462 if (BIO_flush(s->wbio) <= 0)
467 s->rwstate=SSL_NOTHING;
469 s->state=s->s3->tmp.next_state;
472 case SSL3_ST_SR_CERT_A:
473 case SSL3_ST_SR_CERT_B:
474 /* Check for second client hello (MS SGC) */
475 ret = ssl3_check_client_hello(s);
479 s->state = SSL3_ST_SR_CLNT_HELLO_C;
481 if (s->s3->tmp.cert_request)
483 ret=ssl3_get_client_certificate(s);
484 if (ret <= 0) goto end;
487 s->state=SSL3_ST_SR_KEY_EXCH_A;
491 case SSL3_ST_SR_KEY_EXCH_A:
492 case SSL3_ST_SR_KEY_EXCH_B:
493 ret=ssl3_get_client_key_exchange(s);
498 /* For the ECDH ciphersuites when
499 * the client sends its ECDH pub key in
500 * a certificate, the CertificateVerify
501 * message is not sent.
504 s->state = SSL3_ST_SR_CHANGE;
506 else if (SSL_USE_SIGALGS(s))
508 s->state=SSL3_ST_SR_CERT_VRFY_A;
510 if (!s->session->peer)
512 /* For sigalgs freeze the handshake buffer
513 * at this point and digest cached records.
515 if (!s->s3->handshake_buffer)
517 OPENSSL_PUT_ERROR(SSL, ssl3_accept, ERR_R_INTERNAL_ERROR);
520 s->s3->flags |= TLS1_FLAGS_KEEP_HANDSHAKE;
521 if (!ssl3_digest_cached_records(s))
529 s->state=SSL3_ST_SR_CERT_VRFY_A;
532 /* We need to get hashes here so if there is
533 * a client cert, it can be verified
534 * FIXME - digest processing for CertificateVerify
535 * should be generalized. But it is next step
537 if (s->s3->handshake_buffer)
538 if (!ssl3_digest_cached_records(s))
540 for (dgst_num=0; dgst_num<SSL_MAX_DIGEST;dgst_num++)
541 if (s->s3->handshake_dgst[dgst_num])
545 s->method->ssl3_enc->cert_verify_mac(s,EVP_MD_CTX_type(s->s3->handshake_dgst[dgst_num]),&(s->s3->tmp.cert_verify_md[offset]));
546 dgst_size=EVP_MD_CTX_size(s->s3->handshake_dgst[dgst_num]);
557 case SSL3_ST_SR_CERT_VRFY_A:
558 case SSL3_ST_SR_CERT_VRFY_B:
559 ret=ssl3_get_cert_verify(s);
560 if (ret <= 0) goto end;
562 s->state = SSL3_ST_SR_CHANGE;
566 case SSL3_ST_SR_CHANGE: {
567 char next_proto_neg = 0;
569 # if !defined(OPENSSL_NO_NEXTPROTONEG)
570 next_proto_neg = s->s3->next_proto_neg_seen;
572 channel_id = s->s3->tlsext_channel_id_valid;
574 /* At this point, the next message must be entirely
575 * behind a ChangeCipherSpec. */
576 if (!ssl3_expect_change_cipher_spec(s))
582 s->state = SSL3_ST_SR_NEXT_PROTO_A;
584 s->state = SSL3_ST_SR_CHANNEL_ID_A;
586 s->state = SSL3_ST_SR_FINISHED_A;
590 #if !defined(OPENSSL_NO_NEXTPROTONEG)
591 case SSL3_ST_SR_NEXT_PROTO_A:
592 case SSL3_ST_SR_NEXT_PROTO_B:
593 ret=ssl3_get_next_proto(s);
594 if (ret <= 0) goto end;
596 if (s->s3->tlsext_channel_id_valid)
597 s->state=SSL3_ST_SR_CHANNEL_ID_A;
599 s->state=SSL3_ST_SR_FINISHED_A;
603 case SSL3_ST_SR_CHANNEL_ID_A:
604 case SSL3_ST_SR_CHANNEL_ID_B:
605 ret=ssl3_get_channel_id(s);
606 if (ret <= 0) goto end;
608 s->state=SSL3_ST_SR_FINISHED_A;
611 case SSL3_ST_SR_FINISHED_A:
612 case SSL3_ST_SR_FINISHED_B:
613 ret=ssl3_get_finished(s,SSL3_ST_SR_FINISHED_A,
614 SSL3_ST_SR_FINISHED_B);
615 if (ret <= 0) goto end;
618 else if (s->tlsext_ticket_expected)
619 s->state=SSL3_ST_SW_SESSION_TICKET_A;
621 s->state=SSL3_ST_SW_CHANGE_A;
622 /* If this is a full handshake with ChannelID then
623 * record the hashshake hashes in |s->session| in case
624 * we need them to verify a ChannelID signature on a
625 * resumption of this session in the future. */
626 if (!s->hit && s->s3->tlsext_channel_id_new)
628 ret = tls1_record_handshake_hashes_for_channel_id(s);
629 if (ret <= 0) goto end;
634 case SSL3_ST_SW_SESSION_TICKET_A:
635 case SSL3_ST_SW_SESSION_TICKET_B:
636 ret=ssl3_send_newsession_ticket(s);
637 if (ret <= 0) goto end;
638 s->state=SSL3_ST_SW_CHANGE_A;
642 case SSL3_ST_SW_CERT_STATUS_A:
643 case SSL3_ST_SW_CERT_STATUS_B:
644 ret=ssl3_send_cert_status(s);
645 if (ret <= 0) goto end;
646 s->state=SSL3_ST_SW_KEY_EXCH_A;
650 case SSL3_ST_SW_CHANGE_A:
651 case SSL3_ST_SW_CHANGE_B:
653 s->session->cipher=s->s3->tmp.new_cipher;
654 if (!s->method->ssl3_enc->setup_key_block(s))
655 { ret= -1; goto end; }
657 ret=ssl3_send_change_cipher_spec(s,
658 SSL3_ST_SW_CHANGE_A,SSL3_ST_SW_CHANGE_B);
660 if (ret <= 0) goto end;
661 s->state=SSL3_ST_SW_FINISHED_A;
664 if (!s->method->ssl3_enc->change_cipher_state(s,
665 SSL3_CHANGE_CIPHER_SERVER_WRITE))
673 case SSL3_ST_SW_FINISHED_A:
674 case SSL3_ST_SW_FINISHED_B:
675 ret=ssl3_send_finished(s,
676 SSL3_ST_SW_FINISHED_A,SSL3_ST_SW_FINISHED_B,
677 s->method->ssl3_enc->server_finished_label,
678 s->method->ssl3_enc->server_finished_label_len);
679 if (ret <= 0) goto end;
680 s->state = SSL3_ST_SW_FLUSH;
682 s->s3->tmp.next_state = SSL3_ST_SR_CHANGE;
684 s->s3->tmp.next_state = SSL_ST_OK;
689 /* clean a few things up */
690 ssl3_cleanup_key_block(s);
692 BUF_MEM_free(s->init_buf);
695 /* remove buffering on output */
696 ssl_free_wbio_buffer(s);
700 /* If we aren't retaining peer certificates then we can
702 if (s->session->peer && s->ctx->retain_only_sha256_of_client_certs)
704 X509_free(s->session->peer);
705 s->session->peer = NULL;
708 if (s->renegotiate == 2) /* skipped if we just sent a HelloRequest */
713 ssl_update_cache(s,SSL_SESS_CACHE_SERVER);
715 s->ctx->stats.sess_accept_good++;
717 s->handshake_func=ssl3_accept;
719 if (cb != NULL) cb(s,SSL_CB_HANDSHAKE_DONE,1);
727 OPENSSL_PUT_ERROR(SSL, ssl3_accept, SSL_R_UNKNOWN_STATE);
733 if (!s->s3->tmp.reuse_message && !skip)
737 if ((ret=BIO_flush(s->wbio)) <= 0)
742 if ((cb != NULL) && (s->state != state))
746 cb(s,SSL_CB_ACCEPT_LOOP,1);
753 /* BIO_flush(s->wbio); */
757 cb(s,SSL_CB_ACCEPT_EXIT,ret);
761 int ssl3_send_hello_request(SSL *s)
764 if (s->state == SSL3_ST_SW_HELLO_REQ_A)
766 ssl_set_handshake_header(s, SSL3_MT_HELLO_REQUEST, 0);
767 s->state=SSL3_ST_SW_HELLO_REQ_B;
770 /* SSL3_ST_SW_HELLO_REQ_B */
771 return ssl_do_write(s);
774 int ssl3_check_client_hello(SSL *s)
779 /* this function is called when we really expect a Certificate message,
780 * so permit appropriate message length */
781 n=s->method->ssl_get_message(s,
787 if (!ok) return((int)n);
788 s->s3->tmp.reuse_message = 1;
789 if (s->s3->tmp.message_type == SSL3_MT_CLIENT_HELLO)
791 /* We only allow the client to restart the handshake once per
793 if (s->s3->flags & SSL3_FLAGS_SGC_RESTART_DONE)
795 OPENSSL_PUT_ERROR(SSL, ssl3_check_client_hello, SSL_R_MULTIPLE_SGC_RESTARTS);
798 /* Throw away what we have done so far in the current handshake,
799 * which will now be aborted. (A full SSL_clear would be too much.) */
800 #ifndef OPENSSL_NO_DH
801 if (s->s3->tmp.dh != NULL)
803 DH_free(s->s3->tmp.dh);
804 s->s3->tmp.dh = NULL;
807 #ifndef OPENSSL_NO_ECDH
808 if (s->s3->tmp.ecdh != NULL)
810 EC_KEY_free(s->s3->tmp.ecdh);
811 s->s3->tmp.ecdh = NULL;
814 s->s3->flags |= SSL3_FLAGS_SGC_RESTART_DONE;
820 int ssl3_get_client_hello(SSL *s)
822 int i,ok,al=SSL_AD_INTERNAL_ERROR,ret= -1;
825 STACK_OF(SSL_CIPHER) *ciphers=NULL;
826 struct ssl_early_callback_ctx early_ctx;
828 uint16_t client_version;
829 CBS client_random, session_id, cipher_suites, compression_methods;
831 /* We do this so that we will respond with our native type.
832 * If we are TLSv1 and we get SSLv3, we will respond with TLSv1,
833 * This down switching should be handled by a different method.
834 * If we are SSLv3, we will respond with SSLv3, even if prompted with
838 case SSL3_ST_SR_CLNT_HELLO_A:
839 case SSL3_ST_SR_CLNT_HELLO_B:
841 n=s->method->ssl_get_message(s,
842 SSL3_ST_SR_CLNT_HELLO_A,
843 SSL3_ST_SR_CLNT_HELLO_B,
844 SSL3_MT_CLIENT_HELLO,
845 SSL3_RT_MAX_PLAIN_LENGTH,
848 if (!ok) return((int)n);
851 /* If we require cookies and this ClientHello doesn't
852 * contain one, just return since we do not want to
853 * allocate any memory yet. So check cookie length...
855 if (SSL_IS_DTLS(s) && (SSL_get_options(s) & SSL_OP_COOKIE_EXCHANGE))
858 uint8_t cookie_length;
860 CBS_init(&client_hello, s->init_msg, n);
861 if (!CBS_skip(&client_hello, 2 + SSL3_RANDOM_SIZE) ||
862 !CBS_get_u8_length_prefixed(&client_hello, &session_id) ||
863 !CBS_get_u8(&client_hello, &cookie_length))
865 al = SSL_AD_DECODE_ERROR;
866 OPENSSL_PUT_ERROR(SSL, ssl3_get_client_hello, SSL_R_DECODE_ERROR);
870 if (cookie_length == 0)
873 s->state = SSL3_ST_SR_CLNT_HELLO_C;
875 case SSL3_ST_SR_CLNT_HELLO_C:
876 case SSL3_ST_SR_CLNT_HELLO_D:
877 /* We have previously parsed the ClientHello message,
878 * and can't call ssl_get_message again without hashing
879 * the message into the Finished digest again. */
882 memset(&early_ctx, 0, sizeof(early_ctx));
884 early_ctx.client_hello = s->init_msg;
885 early_ctx.client_hello_len = n;
886 if (!ssl_early_callback_init(&early_ctx))
888 al = SSL_AD_DECODE_ERROR;
889 OPENSSL_PUT_ERROR(SSL, ssl3_get_client_hello, SSL_R_CLIENTHELLO_PARSE_FAILED);
893 if (s->state == SSL3_ST_SR_CLNT_HELLO_C &&
894 s->ctx->select_certificate_cb != NULL)
898 s->state = SSL3_ST_SR_CLNT_HELLO_D;
899 ret = s->ctx->select_certificate_cb(&early_ctx);
901 return CERTIFICATE_SELECTION_PENDING;
904 /* Connection rejected. */
905 al = SSL_AD_ACCESS_DENIED;
906 OPENSSL_PUT_ERROR(SSL, ssl3_get_client_hello, SSL_R_CONNECTION_REJECTED);
910 s->state = SSL3_ST_SR_CLNT_HELLO_D;
913 OPENSSL_PUT_ERROR(SSL, ssl3_get_client_hello, SSL_R_UNKNOWN_STATE);
917 CBS_init(&client_hello, s->init_msg, n);
918 if (!CBS_get_u16(&client_hello, &client_version) ||
919 !CBS_get_bytes(&client_hello, &client_random, SSL3_RANDOM_SIZE) ||
920 !CBS_get_u8_length_prefixed(&client_hello, &session_id) ||
921 CBS_len(&session_id) > SSL_MAX_SSL_SESSION_ID_LENGTH)
923 al = SSL_AD_DECODE_ERROR;
924 OPENSSL_PUT_ERROR(SSL, ssl3_get_client_hello, SSL_R_DECODE_ERROR);
928 /* use version from inside client hello, not from record header
929 * (may differ: see RFC 2246, Appendix E, second paragraph) */
930 s->client_version = client_version;
932 if (SSL_IS_DTLS(s) ? (s->client_version > s->version &&
933 s->method->version != DTLS_ANY_VERSION)
934 : (s->client_version < s->version))
936 OPENSSL_PUT_ERROR(SSL, ssl3_get_client_hello, SSL_R_WRONG_VERSION_NUMBER);
937 if ((s->client_version>>8) == SSL3_VERSION_MAJOR &&
938 !s->enc_write_ctx && !s->write_hash)
940 /* similar to ssl3_get_record, send alert using remote version number */
941 s->version = s->client_version;
943 al = SSL_AD_PROTOCOL_VERSION;
947 /* Load the client random. */
948 memcpy(s->s3->client_random, CBS_data(&client_random), SSL3_RANDOM_SIZE);
951 /* Versions before 0.9.7 always allow clients to resume sessions in renegotiation.
952 * 0.9.7 and later allow this by default, but optionally ignore resumption requests
953 * with flag SSL_OP_NO_SESSION_RESUMPTION_ON_RENEGOTIATION (it's a new flag rather
954 * than a change to default behavior so that applications relying on this for security
955 * won't even compile against older library versions).
957 * 1.0.1 and later also have a function SSL_renegotiate_abbreviated() to request
958 * renegotiation but not a new session (s->new_session remains unset): for servers,
959 * this essentially just means that the SSL_OP_NO_SESSION_RESUMPTION_ON_RENEGOTIATION
960 * setting will be ignored.
962 if ((s->new_session && (s->options & SSL_OP_NO_SESSION_RESUMPTION_ON_RENEGOTIATION)))
964 if (!ssl_get_new_session(s,1))
969 i=ssl_get_prev_session(s, &early_ctx);
971 { /* previous session */
976 else if (i == PENDING_SESSION)
978 ret = PENDING_SESSION;
983 if (!ssl_get_new_session(s,1))
992 /* TODO(davidben): The length check here is off. Per
993 * spec, the maximum cookie length is 32. However, the
994 * DTLS1_COOKIE_LENGTH check is checking against 256,
995 * not 32 (so it's actually redundant).
996 * 07a9d1a2c2b735cbc327065000b545deb5e136cf from
997 * OpenSSL switched this from 32 to 256. */
998 if (!CBS_get_u8_length_prefixed(&client_hello, &cookie) ||
999 CBS_len(&cookie) > DTLS1_COOKIE_LENGTH)
1001 al = SSL_AD_DECODE_ERROR;
1002 OPENSSL_PUT_ERROR(SSL, ssl3_get_client_hello, SSL_R_DECODE_ERROR);
1006 /* Verify the cookie if appropriate option is set. */
1007 if ((SSL_get_options(s) & SSL_OP_COOKIE_EXCHANGE) &&
1008 CBS_len(&cookie) > 0)
1010 if (s->ctx->app_verify_cookie_cb != NULL)
1012 if (s->ctx->app_verify_cookie_cb(s,
1013 (unsigned char*)CBS_data(&cookie),
1014 CBS_len(&cookie)) == 0)
1016 al=SSL_AD_HANDSHAKE_FAILURE;
1017 OPENSSL_PUT_ERROR(SSL, ssl3_get_client_hello, SSL_R_COOKIE_MISMATCH);
1020 /* else cookie verification succeeded */
1022 else if (!CBS_mem_equal(&cookie, s->d1->cookie, s->d1->cookie_len))
1024 /* default verification */
1025 al=SSL_AD_HANDSHAKE_FAILURE;
1026 OPENSSL_PUT_ERROR(SSL, ssl3_get_client_hello, SSL_R_COOKIE_MISMATCH);
1029 /* Set to -2 so if successful we return 2 and
1030 * don't send HelloVerifyRequest. */
1034 if (s->method->version == DTLS_ANY_VERSION)
1036 /* Select version to use */
1037 if (s->client_version <= DTLS1_2_VERSION &&
1038 !(s->options & SSL_OP_NO_DTLSv1_2))
1040 s->version = DTLS1_2_VERSION;
1041 s->method = DTLSv1_2_server_method();
1043 else if (tls1_suiteb(s))
1045 OPENSSL_PUT_ERROR(SSL, ssl3_get_client_hello, SSL_R_ONLY_DTLS_1_2_ALLOWED_IN_SUITEB_MODE);
1046 s->version = s->client_version;
1047 al = SSL_AD_PROTOCOL_VERSION;
1050 else if (s->client_version <= DTLS1_VERSION &&
1051 !(s->options & SSL_OP_NO_DTLSv1))
1053 s->version = DTLS1_VERSION;
1054 s->method = DTLSv1_server_method();
1058 OPENSSL_PUT_ERROR(SSL, ssl3_get_client_hello, SSL_R_WRONG_VERSION_NUMBER);
1059 s->version = s->client_version;
1060 al = SSL_AD_PROTOCOL_VERSION;
1063 s->session->ssl_version = s->version;
1067 if (!CBS_get_u16_length_prefixed(&client_hello, &cipher_suites) ||
1068 !CBS_get_u8_length_prefixed(&client_hello, &compression_methods) ||
1069 CBS_len(&compression_methods) == 0)
1071 al = SSL_AD_DECODE_ERROR;
1072 OPENSSL_PUT_ERROR(SSL, ssl3_get_client_hello, SSL_R_DECODE_ERROR);
1076 /* TODO(davidben): Per spec, cipher_suites can never be empty
1077 * (specified at the ClientHello structure level). This logic
1078 * allows it to be empty if resuming a session. Can we always
1079 * require non-empty? If a client sends empty cipher_suites
1080 * because it's resuming a session, it could always fail to
1081 * resume a session, so it's unlikely to actually work. */
1082 if (CBS_len(&cipher_suites) == 0 && CBS_len(&session_id) != 0)
1084 /* We need a cipher if we are not resuming a session. */
1085 al = SSL_AD_ILLEGAL_PARAMETER;
1086 OPENSSL_PUT_ERROR(SSL, ssl3_get_client_hello, SSL_R_NO_CIPHERS_SPECIFIED);
1090 if (ssl_bytes_to_cipher_list(s, &cipher_suites, &ciphers) == NULL)
1095 /* If it is a hit, check that the cipher is in the list */
1096 if (s->hit && CBS_len(&cipher_suites) > 0)
1098 int found_cipher = 0;
1099 unsigned long id = s->session->cipher->id;
1101 for (i=0; i<sk_SSL_CIPHER_num(ciphers); i++)
1103 c=sk_SSL_CIPHER_value(ciphers,i);
1112 /* we need to have the cipher in the cipher
1113 * list if we are asked to reuse it */
1114 al=SSL_AD_ILLEGAL_PARAMETER;
1115 OPENSSL_PUT_ERROR(SSL, ssl3_get_client_hello, SSL_R_REQUIRED_CIPHER_MISSING);
1120 /* Only null compression is supported. */
1121 if (memchr(CBS_data(&compression_methods), 0,
1122 CBS_len(&compression_methods)) == NULL)
1124 al = SSL_AD_ILLEGAL_PARAMETER;
1125 OPENSSL_PUT_ERROR(SSL, ssl3_get_client_hello, SSL_R_NO_COMPRESSION_SPECIFIED);
1130 if (s->version >= SSL3_VERSION)
1132 if (!ssl_parse_clienthello_tlsext(s, &client_hello))
1134 OPENSSL_PUT_ERROR(SSL, ssl3_get_client_hello, SSL_R_PARSE_TLSEXT);
1139 /* There should be nothing left over in the record. */
1140 if (CBS_len(&client_hello) != 0)
1142 /* wrong packet length */
1143 al=SSL_AD_DECODE_ERROR;
1144 OPENSSL_PUT_ERROR(SSL, ssl3_get_client_hello, SSL_R_BAD_PACKET_LENGTH);
1148 /* Check if we want to use external pre-shared secret for this
1149 * handshake for not reused session only. We need to generate
1150 * server_random before calling tls_session_secret_cb in order to allow
1151 * SessionTicket processing to use it in key derivation. */
1154 pos=s->s3->server_random;
1155 if (ssl_fill_hello_random(s, 1, pos, SSL3_RANDOM_SIZE) <= 0)
1161 if (!s->hit && s->version >= TLS1_VERSION && s->tls_session_secret_cb)
1163 SSL_CIPHER *pref_cipher=NULL;
1165 s->session->master_key_length=sizeof(s->session->master_key);
1166 if(s->tls_session_secret_cb(s, s->session->master_key, &s->session->master_key_length,
1167 ciphers, &pref_cipher, s->tls_session_secret_cb_arg))
1170 s->session->ciphers=ciphers;
1171 s->session->verify_result=X509_V_OK;
1175 /* check if some cipher was preferred by call back */
1176 pref_cipher=pref_cipher ? pref_cipher : ssl3_choose_cipher(s, s->session->ciphers, ssl_get_cipher_preferences(s));
1177 if (pref_cipher == NULL)
1179 al=SSL_AD_HANDSHAKE_FAILURE;
1180 OPENSSL_PUT_ERROR(SSL, ssl3_get_client_hello, SSL_R_NO_SHARED_CIPHER);
1184 s->session->cipher=pref_cipher;
1187 ssl_cipher_preference_list_free(s->cipher_list);
1189 if (s->cipher_list_by_id)
1190 sk_SSL_CIPHER_free(s->cipher_list_by_id);
1192 s->cipher_list = ssl_cipher_preference_list_from_ciphers(s->session->ciphers);
1193 s->cipher_list_by_id = sk_SSL_CIPHER_dup(s->session->ciphers);
1197 /* Given s->session->ciphers and SSL_get_ciphers, we must
1202 if (s->session->ciphers != NULL)
1203 sk_SSL_CIPHER_free(s->session->ciphers);
1204 s->session->ciphers=ciphers;
1205 if (ciphers == NULL)
1207 al=SSL_AD_ILLEGAL_PARAMETER;
1208 OPENSSL_PUT_ERROR(SSL, ssl3_get_client_hello, SSL_R_NO_CIPHERS_PASSED);
1212 /* Let cert callback update server certificates if required */
1213 if (s->cert->cert_cb)
1215 int rv = s->cert->cert_cb(s, s->cert->cert_cb_arg);
1218 al=SSL_AD_INTERNAL_ERROR;
1219 OPENSSL_PUT_ERROR(SSL, ssl3_get_client_hello, SSL_R_CERT_CB_ERROR);
1224 s->rwstate=SSL_X509_LOOKUP;
1227 s->rwstate = SSL_NOTHING;
1229 c=ssl3_choose_cipher(s,s->session->ciphers,
1230 ssl_get_cipher_preferences(s));
1234 al=SSL_AD_HANDSHAKE_FAILURE;
1235 OPENSSL_PUT_ERROR(SSL, ssl3_get_client_hello, SSL_R_NO_SHARED_CIPHER);
1238 s->s3->tmp.new_cipher=c;
1242 /* Session-id reuse */
1243 s->s3->tmp.new_cipher=s->session->cipher;
1246 if (!SSL_USE_SIGALGS(s) || !(s->verify_mode & SSL_VERIFY_PEER))
1248 if (!ssl3_digest_cached_records(s))
1252 /* we now have the following setup.
1254 * cipher_list - our prefered list of ciphers
1255 * ciphers - the clients prefered list of ciphers
1256 * compression - basically ignored right now
1257 * ssl version is set - sslv3
1258 * s->session - The ssl session has been setup.
1259 * s->hit - session reuse flag
1260 * s->tmp.new_cipher - the new cipher to use.
1263 /* Handles TLS extensions that we couldn't check earlier */
1264 if (s->version >= SSL3_VERSION)
1266 if (ssl_check_clienthello_tlsext_late(s) <= 0)
1268 OPENSSL_PUT_ERROR(SSL, ssl3_get_client_hello, SSL_R_CLIENTHELLO_TLSEXT);
1273 if (ret < 0) ret=-ret;
1277 ssl3_send_alert(s,SSL3_AL_FATAL,al);
1280 if (ciphers != NULL) sk_SSL_CIPHER_free(ciphers);
1284 int ssl3_send_server_hello(SSL *s)
1287 unsigned char *p,*d;
1291 if (s->state == SSL3_ST_SW_SRVR_HELLO_A)
1293 /* We only accept ChannelIDs on connections with ECDHE in order
1294 * to avoid a known attack while we fix ChannelID itself. */
1296 s->s3->tlsext_channel_id_valid &&
1297 (s->s3->tmp.new_cipher->algorithm_mkey & SSL_kEECDH) == 0)
1298 s->s3->tlsext_channel_id_valid = 0;
1300 /* If this is a resumption and the original handshake didn't
1301 * support ChannelID then we didn't record the original
1302 * handshake hashes in the session and so cannot resume with
1305 s->s3->tlsext_channel_id_new &&
1306 s->session->original_handshake_hash_len == 0)
1307 s->s3->tlsext_channel_id_valid = 0;
1309 if (s->mode & SSL_MODE_RELEASE_BUFFERS)
1311 /* Free s->session->ciphers in order to release memory. This
1312 * breaks SSL_get_shared_ciphers(), but many servers will
1313 * prefer the memory savings. */
1314 sk_SSL_CIPHER_free(s->session->ciphers);
1315 s->session->ciphers = NULL;
1318 buf=(unsigned char *)s->init_buf->data;
1319 /* Do the message type and length last */
1320 d=p= ssl_handshake_start(s);
1322 *(p++)=s->version>>8;
1323 *(p++)=s->version&0xff;
1326 memcpy(p,s->s3->server_random,SSL3_RANDOM_SIZE);
1327 p+=SSL3_RANDOM_SIZE;
1329 /* There are several cases for the session ID to send
1330 * back in the server hello:
1331 * - For session reuse from the session cache,
1332 * we send back the old session ID.
1333 * - If stateless session reuse (using a session ticket)
1334 * is successful, we send back the client's "session ID"
1335 * (which doesn't actually identify the session).
1336 * - If it is a new session, we send back the new
1338 * - However, if we want the new session to be single-use,
1339 * we send back a 0-length session ID.
1340 * s->hit is non-zero in either case of session reuse,
1341 * so the following won't overwrite an ID that we're supposed
1344 if (!(s->ctx->session_cache_mode & SSL_SESS_CACHE_SERVER)
1346 s->session->session_id_length=0;
1348 sl=s->session->session_id_length;
1349 if (sl > (int)sizeof(s->session->session_id))
1351 OPENSSL_PUT_ERROR(SSL, ssl3_send_server_hello, ERR_R_INTERNAL_ERROR);
1355 memcpy(p,s->session->session_id,sl);
1358 /* put the cipher */
1359 s2n(ssl3_get_cipher_value(s->s3->tmp.new_cipher), p);
1361 /* put the compression method */
1363 if (ssl_prepare_serverhello_tlsext(s) <= 0)
1365 OPENSSL_PUT_ERROR(SSL, ssl3_send_server_hello, SSL_R_SERVERHELLO_TLSEXT);
1368 if ((p = ssl_add_serverhello_tlsext(s, p, buf+SSL3_RT_MAX_PLAIN_LENGTH)) == NULL)
1370 OPENSSL_PUT_ERROR(SSL, ssl3_send_server_hello, ERR_R_INTERNAL_ERROR);
1375 ssl_set_handshake_header(s, SSL3_MT_SERVER_HELLO, l);
1376 s->state=SSL3_ST_SW_SRVR_HELLO_B;
1379 /* SSL3_ST_SW_SRVR_HELLO_B */
1380 return ssl_do_write(s);
1383 int ssl3_send_server_done(SSL *s)
1386 if (s->state == SSL3_ST_SW_SRVR_DONE_A)
1388 ssl_set_handshake_header(s, SSL3_MT_SERVER_DONE, 0);
1389 s->state = SSL3_ST_SW_SRVR_DONE_B;
1392 /* SSL3_ST_SW_SRVR_DONE_B */
1393 return ssl_do_write(s);
1396 int ssl3_send_server_key_exchange(SSL *s)
1400 unsigned char md_buf[MD5_DIGEST_LENGTH+SHA_DIGEST_LENGTH];
1402 #ifndef OPENSSL_NO_DH
1405 #ifndef OPENSSL_NO_ECDH
1406 EC_KEY *ecdh=NULL, *ecdhp;
1407 unsigned char *encodedPoint = NULL;
1410 BN_CTX *bn_ctx = NULL;
1412 const char* psk_identity_hint = NULL;
1413 size_t psk_identity_hint_len = 0;
1415 const EVP_MD *md = NULL;
1416 unsigned char *p,*d;
1418 unsigned long alg_k;
1419 unsigned long alg_a;
1427 EVP_MD_CTX_init(&md_ctx);
1428 if (s->state == SSL3_ST_SW_KEY_EXCH_A)
1430 alg_k=s->s3->tmp.new_cipher->algorithm_mkey;
1431 alg_a=s->s3->tmp.new_cipher->algorithm_auth;
1436 r[0]=r[1]=r[2]=r[3]=NULL;
1438 if (alg_a & SSL_aPSK)
1440 /* size for PSK identity hint */
1441 psk_identity_hint = s->session->psk_identity_hint;
1442 if (psk_identity_hint)
1443 psk_identity_hint_len = strlen(psk_identity_hint);
1445 psk_identity_hint_len = 0;
1446 n+=2+psk_identity_hint_len;
1448 #ifndef OPENSSL_NO_DH
1449 if (alg_k & SSL_kEDH)
1452 if ((dhp == NULL) && (s->cert->dh_tmp_cb != NULL))
1453 dhp=s->cert->dh_tmp_cb(s, 0, 1024);
1456 al=SSL_AD_HANDSHAKE_FAILURE;
1457 OPENSSL_PUT_ERROR(SSL, ssl3_send_server_key_exchange, SSL_R_MISSING_TMP_DH_KEY);
1461 if (s->s3->tmp.dh != NULL)
1463 OPENSSL_PUT_ERROR(SSL, ssl3_send_server_key_exchange, ERR_R_INTERNAL_ERROR);
1467 if ((dh=DHparams_dup(dhp)) == NULL)
1469 OPENSSL_PUT_ERROR(SSL, ssl3_send_server_key_exchange, ERR_R_DH_LIB);
1474 if ((dhp->pub_key == NULL ||
1475 dhp->priv_key == NULL ||
1476 (s->options & SSL_OP_SINGLE_DH_USE)))
1478 if(!DH_generate_key(dh))
1480 OPENSSL_PUT_ERROR(SSL, ssl3_send_server_key_exchange, ERR_R_DH_LIB);
1486 dh->pub_key=BN_dup(dhp->pub_key);
1487 dh->priv_key=BN_dup(dhp->priv_key);
1488 if ((dh->pub_key == NULL) ||
1489 (dh->priv_key == NULL))
1491 OPENSSL_PUT_ERROR(SSL, ssl3_send_server_key_exchange, ERR_R_DH_LIB);
1501 #ifndef OPENSSL_NO_ECDH
1502 if (alg_k & SSL_kEECDH)
1504 const EC_GROUP *group;
1506 ecdhp=cert->ecdh_tmp;
1507 if (s->cert->ecdh_tmp_auto)
1509 /* Get NID of appropriate shared curve */
1510 int nid = tls1_get_shared_curve(s);
1511 if (nid != NID_undef)
1512 ecdhp = EC_KEY_new_by_curve_name(nid);
1514 else if ((ecdhp == NULL) && s->cert->ecdh_tmp_cb)
1516 ecdhp = s->cert->ecdh_tmp_cb(s, 0, 1024);
1520 al=SSL_AD_HANDSHAKE_FAILURE;
1521 OPENSSL_PUT_ERROR(SSL, ssl3_send_server_key_exchange, SSL_R_MISSING_TMP_ECDH_KEY);
1525 if (s->s3->tmp.ecdh != NULL)
1527 OPENSSL_PUT_ERROR(SSL, ssl3_send_server_key_exchange, ERR_R_INTERNAL_ERROR);
1531 /* Duplicate the ECDH structure. */
1534 OPENSSL_PUT_ERROR(SSL, ssl3_send_server_key_exchange, ERR_R_ECDH_LIB);
1537 if (s->cert->ecdh_tmp_auto)
1539 else if ((ecdh = EC_KEY_dup(ecdhp)) == NULL)
1541 OPENSSL_PUT_ERROR(SSL, ssl3_send_server_key_exchange, ERR_R_ECDH_LIB);
1545 s->s3->tmp.ecdh=ecdh;
1546 if ((EC_KEY_get0_public_key(ecdh) == NULL) ||
1547 (EC_KEY_get0_private_key(ecdh) == NULL) ||
1548 (s->options & SSL_OP_SINGLE_ECDH_USE))
1550 if(!EC_KEY_generate_key(ecdh))
1552 OPENSSL_PUT_ERROR(SSL, ssl3_send_server_key_exchange, ERR_R_ECDH_LIB);
1557 if (((group = EC_KEY_get0_group(ecdh)) == NULL) ||
1558 (EC_KEY_get0_public_key(ecdh) == NULL) ||
1559 (EC_KEY_get0_private_key(ecdh) == NULL))
1561 OPENSSL_PUT_ERROR(SSL, ssl3_send_server_key_exchange, ERR_R_ECDH_LIB);
1565 /* XXX: For now, we only support ephemeral ECDH
1566 * keys over named (not generic) curves. For
1567 * supported named curves, curve_id is non-zero.
1570 tls1_ec_nid2curve_id(EC_GROUP_get_curve_name(group)))
1573 OPENSSL_PUT_ERROR(SSL, ssl3_send_server_key_exchange, SSL_R_UNSUPPORTED_ELLIPTIC_CURVE);
1577 /* Encode the public key.
1578 * First check the size of encoding and
1579 * allocate memory accordingly.
1581 encodedlen = EC_POINT_point2oct(group,
1582 EC_KEY_get0_public_key(ecdh),
1583 POINT_CONVERSION_UNCOMPRESSED,
1586 encodedPoint = (unsigned char *)
1587 OPENSSL_malloc(encodedlen*sizeof(unsigned char));
1588 bn_ctx = BN_CTX_new();
1589 if ((encodedPoint == NULL) || (bn_ctx == NULL))
1591 OPENSSL_PUT_ERROR(SSL, ssl3_send_server_key_exchange, ERR_R_MALLOC_FAILURE);
1596 encodedlen = EC_POINT_point2oct(group,
1597 EC_KEY_get0_public_key(ecdh),
1598 POINT_CONVERSION_UNCOMPRESSED,
1599 encodedPoint, encodedlen, bn_ctx);
1601 if (encodedlen == 0)
1603 OPENSSL_PUT_ERROR(SSL, ssl3_send_server_key_exchange, ERR_R_ECDH_LIB);
1607 BN_CTX_free(bn_ctx); bn_ctx=NULL;
1609 /* XXX: For now, we only support named (not
1610 * generic) curves in ECDH ephemeral key exchanges.
1611 * In this situation, we need four additional bytes
1612 * to encode the entire ServerECDHParams
1615 n += 4 + encodedlen;
1617 /* We'll generate the serverKeyExchange message
1618 * explicitly so we can set these to NULLs
1626 #endif /* !OPENSSL_NO_ECDH */
1627 if (!(alg_k & SSL_kPSK))
1629 al=SSL_AD_HANDSHAKE_FAILURE;
1630 OPENSSL_PUT_ERROR(SSL, ssl3_send_server_key_exchange, SSL_R_UNKNOWN_KEY_EXCHANGE_TYPE);
1633 for (i=0; i < 4 && r[i] != NULL; i++)
1635 nr[i]=BN_num_bytes(r[i]);
1639 if (ssl_cipher_has_server_public_key(s->s3->tmp.new_cipher))
1641 if ((pkey=ssl_get_sign_pkey(s,s->s3->tmp.new_cipher,&md))
1644 al=SSL_AD_DECODE_ERROR;
1647 kn=EVP_PKEY_size(pkey);
1655 if (!BUF_MEM_grow_clean(buf,n+SSL_HM_HEADER_LENGTH(s)+kn))
1657 OPENSSL_PUT_ERROR(SSL, ssl3_send_server_key_exchange, ERR_LIB_BUF);
1660 d = p = ssl_handshake_start(s);
1662 for (i=0; i < 4 && r[i] != NULL; i++)
1669 /* Note: ECDHE PSK ciphersuites use SSL_kEECDH and SSL_aPSK.
1670 * When one of them is used, the server key exchange record needs to have both
1671 * the psk_identity_hint and the ServerECDHParams. */
1672 if (alg_a & SSL_aPSK)
1674 /* copy PSK identity hint (if provided) */
1675 s2n(psk_identity_hint_len, p);
1676 if (psk_identity_hint_len > 0)
1678 memcpy(p, psk_identity_hint, psk_identity_hint_len);
1679 p+=psk_identity_hint_len;
1683 #ifndef OPENSSL_NO_ECDH
1684 if (alg_k & SSL_kEECDH)
1686 /* XXX: For now, we only support named (not generic) curves.
1687 * In this situation, the serverKeyExchange message has:
1688 * [1 byte CurveType], [2 byte CurveName]
1689 * [1 byte length of encoded point], followed by
1690 * the actual encoded point itself
1692 *p = NAMED_CURVE_TYPE;
1700 memcpy((unsigned char*)p,
1701 (unsigned char *)encodedPoint,
1703 OPENSSL_free(encodedPoint);
1704 encodedPoint = NULL;
1707 #endif /* OPENSSL_NO_ECDH */
1712 /* n is the length of the params, they start at &(d[4])
1713 * and p points to the space at the end. */
1714 if (pkey->type == EVP_PKEY_RSA && !SSL_USE_SIGALGS(s))
1718 for (num=2; num > 0; num--)
1720 EVP_DigestInit_ex(&md_ctx,(num == 2)
1721 ?s->ctx->md5:s->ctx->sha1, NULL);
1722 EVP_DigestUpdate(&md_ctx,&(s->s3->client_random[0]),SSL3_RANDOM_SIZE);
1723 EVP_DigestUpdate(&md_ctx,&(s->s3->server_random[0]),SSL3_RANDOM_SIZE);
1724 EVP_DigestUpdate(&md_ctx,d,n);
1725 EVP_DigestFinal_ex(&md_ctx,q,
1726 (unsigned int *)&i);
1730 if (RSA_sign(NID_md5_sha1, md_buf, j,
1731 &(p[2]), &u, pkey->pkey.rsa) <= 0)
1733 OPENSSL_PUT_ERROR(SSL, ssl3_send_server_key_exchange, ERR_LIB_RSA);
1742 /* send signature algorithm */
1743 if (SSL_USE_SIGALGS(s))
1745 if (!tls12_get_sigandhash(p, pkey, md))
1747 /* Should never happen */
1748 al=SSL_AD_INTERNAL_ERROR;
1749 OPENSSL_PUT_ERROR(SSL, ssl3_send_server_key_exchange, ERR_R_INTERNAL_ERROR);
1755 fprintf(stderr, "Using hash %s\n",
1758 EVP_SignInit_ex(&md_ctx, md, NULL);
1759 EVP_SignUpdate(&md_ctx,&(s->s3->client_random[0]),SSL3_RANDOM_SIZE);
1760 EVP_SignUpdate(&md_ctx,&(s->s3->server_random[0]),SSL3_RANDOM_SIZE);
1761 EVP_SignUpdate(&md_ctx,d,n);
1762 if (!EVP_SignFinal(&md_ctx,&(p[2]),
1763 (unsigned int *)&i,pkey))
1765 OPENSSL_PUT_ERROR(SSL, ssl3_send_server_key_exchange, ERR_LIB_EVP);
1770 if (SSL_USE_SIGALGS(s))
1775 /* Is this error check actually needed? */
1776 al=SSL_AD_HANDSHAKE_FAILURE;
1777 OPENSSL_PUT_ERROR(SSL, ssl3_send_server_key_exchange, SSL_R_UNKNOWN_PKEY_TYPE);
1782 ssl_set_handshake_header(s, SSL3_MT_SERVER_KEY_EXCHANGE, n);
1785 s->state = SSL3_ST_SW_KEY_EXCH_B;
1786 EVP_MD_CTX_cleanup(&md_ctx);
1787 return ssl_do_write(s);
1789 ssl3_send_alert(s,SSL3_AL_FATAL,al);
1791 #ifndef OPENSSL_NO_ECDH
1792 if (encodedPoint != NULL) OPENSSL_free(encodedPoint);
1793 BN_CTX_free(bn_ctx);
1795 EVP_MD_CTX_cleanup(&md_ctx);
1799 int ssl3_send_certificate_request(SSL *s)
1801 unsigned char *p,*d;
1803 STACK_OF(X509_NAME) *sk=NULL;
1807 if (s->state == SSL3_ST_SW_CERT_REQ_A)
1811 d=p=ssl_handshake_start(s);
1813 /* get the list of acceptable cert types */
1815 n=ssl3_get_req_cert_type(s,p);
1820 if (SSL_USE_SIGALGS(s))
1822 const unsigned char *psigs;
1823 nl = tls12_get_psigalgs(s, &psigs);
1825 memcpy(p, psigs, nl);
1834 sk=SSL_get_client_CA_list(s);
1838 for (i=0; i<sk_X509_NAME_num(sk); i++)
1840 name=sk_X509_NAME_value(sk,i);
1841 j=i2d_X509_NAME(name,NULL);
1842 if (!BUF_MEM_grow_clean(buf,SSL_HM_HEADER_LENGTH(s)+n+j+2))
1844 OPENSSL_PUT_ERROR(SSL, ssl3_send_certificate_request, ERR_R_BUF_LIB);
1847 p = ssl_handshake_start(s) + n;
1849 i2d_X509_NAME(name,&p);
1854 /* else no CA names */
1855 p = ssl_handshake_start(s) + off;
1858 ssl_set_handshake_header(s, SSL3_MT_CERTIFICATE_REQUEST, n);
1860 #ifdef NETSCAPE_HANG_BUG
1861 if (!SSL_IS_DTLS(s))
1863 if (!BUF_MEM_grow_clean(buf, s->init_num + 4))
1865 OPENSSL_PUT_ERROR(SSL, ssl3_send_certificate_request, ERR_R_BUF_LIB);
1868 p=(unsigned char *)s->init_buf->data + s->init_num;
1870 *(p++)=SSL3_MT_SERVER_DONE;
1878 s->state = SSL3_ST_SW_CERT_REQ_B;
1881 /* SSL3_ST_SW_CERT_REQ_B */
1882 return ssl_do_write(s);
1887 int ssl3_get_client_key_exchange(SSL *s)
1891 CBS client_key_exchange;
1892 unsigned long alg_k;
1893 unsigned long alg_a;
1894 uint8_t *premaster_secret = NULL;
1895 size_t premaster_secret_len = 0;
1896 int skip_certificate_verify = 0;
1898 uint8_t *decrypt_buf = NULL;
1899 EVP_PKEY *pkey=NULL;
1900 #ifndef OPENSSL_NO_DH
1902 DH *dh_srvr, *dh_clnt = NULL;
1905 #ifndef OPENSSL_NO_ECDH
1906 EC_KEY *srvr_ecdh = NULL;
1907 EVP_PKEY *clnt_pub_pkey = NULL;
1908 EC_POINT *clnt_ecpoint = NULL;
1909 BN_CTX *bn_ctx = NULL;
1910 unsigned int psk_len = 0;
1911 unsigned char psk[PSK_MAX_PSK_LEN];
1914 n=s->method->ssl_get_message(s,
1915 SSL3_ST_SR_KEY_EXCH_A,
1916 SSL3_ST_SR_KEY_EXCH_B,
1917 SSL3_MT_CLIENT_KEY_EXCHANGE,
1921 if (!ok) return((int)n);
1922 CBS_init(&client_key_exchange, s->init_msg, n);
1924 alg_k=s->s3->tmp.new_cipher->algorithm_mkey;
1925 alg_a=s->s3->tmp.new_cipher->algorithm_auth;
1927 /* If using a PSK key exchange, prepare the pre-shared key. */
1928 if (alg_a & SSL_aPSK)
1932 /* If using PSK, the ClientKeyExchange contains a
1933 * psk_identity. If PSK, then this is the only field
1934 * in the message. */
1935 if (!CBS_get_u16_length_prefixed(&client_key_exchange, &psk_identity) ||
1936 ((alg_k & SSL_kPSK) && CBS_len(&client_key_exchange) != 0))
1938 OPENSSL_PUT_ERROR(SSL, ssl3_get_client_key_exchange, SSL_R_DECODE_ERROR);
1939 al = SSL_AD_DECODE_ERROR;
1943 if (s->psk_server_callback == NULL)
1945 OPENSSL_PUT_ERROR(SSL, ssl3_get_client_key_exchange, SSL_R_PSK_NO_SERVER_CB);
1946 al = SSL_AD_INTERNAL_ERROR;
1950 if (CBS_len(&psk_identity) > PSK_MAX_IDENTITY_LEN ||
1951 CBS_contains_zero_byte(&psk_identity))
1953 OPENSSL_PUT_ERROR(SSL, ssl3_get_client_key_exchange, SSL_R_DATA_LENGTH_TOO_LONG);
1954 al = SSL_AD_ILLEGAL_PARAMETER;
1958 if (!CBS_strdup(&psk_identity, &s->session->psk_identity))
1960 al = SSL_AD_INTERNAL_ERROR;
1961 OPENSSL_PUT_ERROR(SSL, ssl3_get_client_key_exchange, ERR_R_MALLOC_FAILURE);
1965 /* Look up the key for the identity. */
1966 psk_len = s->psk_server_callback(s, s->session->psk_identity, psk, sizeof(psk));
1967 if (psk_len > PSK_MAX_PSK_LEN)
1969 OPENSSL_PUT_ERROR(SSL, ssl3_get_client_key_exchange, ERR_R_INTERNAL_ERROR);
1970 al = SSL_AD_INTERNAL_ERROR;
1973 else if (psk_len == 0)
1975 /* PSK related to the given identity not found */
1976 OPENSSL_PUT_ERROR(SSL, ssl3_get_client_key_exchange, SSL_R_PSK_IDENTITY_NOT_FOUND);
1977 al = SSL_AD_UNKNOWN_PSK_IDENTITY;
1982 /* Depending on the key exchange method, compute |premaster_secret| and
1983 * |premaster_secret_len|. Also, for DH and ECDH, set
1984 * |skip_certificate_verify| as appropriate. */
1985 if (alg_k & SSL_kRSA)
1987 CBS encrypted_premaster_secret;
1988 uint8_t rand_premaster_secret[SSL_MAX_MASTER_KEY_LENGTH];
1989 int decrypt_good_mask;
1990 uint8_t version_good;
1991 size_t rsa_size, decrypt_len, premaster_index, j;
1993 pkey=s->cert->pkeys[SSL_PKEY_RSA_ENC].privatekey;
1994 if ( (pkey == NULL) ||
1995 (pkey->type != EVP_PKEY_RSA) ||
1996 (pkey->pkey.rsa == NULL))
1998 al=SSL_AD_HANDSHAKE_FAILURE;
1999 OPENSSL_PUT_ERROR(SSL, ssl3_get_client_key_exchange, SSL_R_MISSING_RSA_CERTIFICATE);
2004 /* TLS and [incidentally] DTLS{0xFEFF}
2006 * TODO(davidben): Should this (and
2007 * ssl3_send_client_key_exchange) include DTLS1_BAD_VER?
2008 * Alternatively, get rid of DTLS1_BAD_VER?
2010 if (s->version > SSL3_VERSION)
2012 CBS copy = client_key_exchange;
2013 if (!CBS_get_u16_length_prefixed(&client_key_exchange,
2014 &encrypted_premaster_secret) ||
2015 CBS_len(&client_key_exchange) != 0)
2017 if (!(s->options & SSL_OP_TLS_D5_BUG))
2019 al = SSL_AD_DECODE_ERROR;
2020 OPENSSL_PUT_ERROR(SSL, ssl3_get_client_key_exchange, SSL_R_TLS_RSA_ENCRYPTED_VALUE_LENGTH_IS_WRONG);
2024 encrypted_premaster_secret = copy;
2028 encrypted_premaster_secret = client_key_exchange;
2030 /* Reject overly short RSA keys because we want to be sure that
2031 * the buffer size makes it safe to iterate over the entire size
2032 * of a premaster secret (SSL_MAX_MASTER_KEY_LENGTH). The actual
2033 * expected size is larger due to RSA padding, but the bound is
2034 * sufficient to be safe. */
2035 rsa_size = RSA_size(rsa);
2036 if (rsa_size < SSL_MAX_MASTER_KEY_LENGTH)
2038 al = SSL_AD_DECRYPT_ERROR;
2039 OPENSSL_PUT_ERROR(SSL, ssl3_get_client_key_exchange, SSL_R_DECRYPTION_FAILED);
2043 /* We must not leak whether a decryption failure occurs because
2044 * of Bleichenbacher's attack on PKCS #1 v1.5 RSA padding (see
2045 * RFC 2246, section 7.4.7.1). The code follows that advice of
2046 * the TLS RFC and generates a random premaster secret for the
2047 * case that the decrypt fails. See
2048 * https://tools.ietf.org/html/rfc5246#section-7.4.7.1 */
2049 if (RAND_pseudo_bytes(rand_premaster_secret,
2050 sizeof(rand_premaster_secret)) <= 0)
2053 /* Allocate a buffer large enough for an RSA decryption. */
2054 decrypt_buf = OPENSSL_malloc(rsa_size);
2055 if (decrypt_buf == NULL)
2057 OPENSSL_PUT_ERROR(SSL, ssl3_get_client_key_exchange, ERR_R_MALLOC_FAILURE);
2061 /* Decrypt with no padding. PKCS#1 padding will be removed as
2062 * part of the timing-sensitive code below. */
2063 if (!RSA_decrypt(rsa, &decrypt_len, decrypt_buf, rsa_size,
2064 CBS_data(&encrypted_premaster_secret),
2065 CBS_len(&encrypted_premaster_secret),
2070 if (decrypt_len != rsa_size)
2072 /* This should never happen, but do a check so we do not
2073 * read uninitialized memory. */
2074 OPENSSL_PUT_ERROR(SSL, ssl3_get_client_key_exchange, ERR_R_INTERNAL_ERROR);
2078 /* Remove the PKCS#1 padding and adjust decrypt_len as
2079 * appropriate. decrypt_good_mask will be zero if the premaster
2080 * if good and non-zero otherwise. */
2081 decrypt_good_mask = RSA_message_index_PKCS1_type_2(
2082 decrypt_buf, decrypt_len, &premaster_index);
2083 decrypt_good_mask--;
2084 decrypt_len = decrypt_len - premaster_index;
2086 /* decrypt_len should be SSL_MAX_MASTER_KEY_LENGTH. */
2087 decrypt_good_mask |= decrypt_len ^ SSL_MAX_MASTER_KEY_LENGTH;
2089 /* Copy over the unpadded premaster. Whatever the value of
2090 * |decrypt_good_mask|, copy as if the premaster were the right
2091 * length. It is important the memory access pattern be
2093 premaster_secret = BUF_memdup(
2094 decrypt_buf + (rsa_size - SSL_MAX_MASTER_KEY_LENGTH),
2095 SSL_MAX_MASTER_KEY_LENGTH);
2096 if (premaster_secret == NULL)
2098 OPENSSL_PUT_ERROR(SSL, ssl3_get_client_key_exchange, ERR_R_MALLOC_FAILURE);
2101 OPENSSL_free(decrypt_buf);
2104 /* If the version in the decrypted pre-master secret is correct
2105 * then version_good will be zero. The Klima-Pokorny-Rosa
2106 * extension of Bleichenbacher's attack
2107 * (http://eprint.iacr.org/2003/052/) exploits the version
2108 * number check as a "bad version oracle". Thus version checks
2109 * are done in constant time and are treated like any other
2110 * decryption error. */
2111 version_good = premaster_secret[0] ^ (s->client_version>>8);
2112 version_good |= premaster_secret[1] ^ (s->client_version&0xff);
2114 /* The premaster secret must contain the same version number as
2115 * the ClientHello to detect version rollback attacks
2116 * (strangely, the protocol does not offer such protection for
2117 * DH ciphersuites). However, buggy clients exist that send the
2118 * negotiated protocol version instead if the server does not
2119 * support the requested protocol version. If
2120 * SSL_OP_TLS_ROLLBACK_BUG is set, tolerate such clients. */
2121 if (s->options & SSL_OP_TLS_ROLLBACK_BUG)
2123 unsigned char workaround_mask = version_good;
2124 unsigned char workaround;
2126 /* workaround_mask will be 0xff if version_good is
2127 * non-zero (i.e. the version match failed). Otherwise
2129 workaround_mask |= workaround_mask >> 4;
2130 workaround_mask |= workaround_mask >> 2;
2131 workaround_mask |= workaround_mask >> 1;
2132 workaround_mask = ~((workaround_mask & 1) - 1);
2134 workaround = premaster_secret[0] ^ (s->version>>8);
2135 workaround |= premaster_secret[1] ^ (s->version&0xff);
2137 /* If workaround_mask is 0xff (i.e. there was a version
2138 * mismatch) then we copy the value of workaround over
2140 version_good = (workaround & workaround_mask) |
2141 (version_good & ~workaround_mask);
2144 /* If any bits in version_good are set then they'll poision
2145 * decrypt_good_mask and cause rand_premaster_secret to be
2147 decrypt_good_mask |= version_good;
2149 /* decrypt_good_mask will be zero iff decrypt_len ==
2150 * SSL_MAX_MASTER_KEY_LENGTH and the version check passed. We
2151 * fold the bottom 32 bits of it with an OR so that the LSB
2152 * will be zero iff everything is good. This assumes that we'll
2153 * never decrypt a value > 2**31 bytes, which seems safe. */
2154 decrypt_good_mask |= decrypt_good_mask >> 16;
2155 decrypt_good_mask |= decrypt_good_mask >> 8;
2156 decrypt_good_mask |= decrypt_good_mask >> 4;
2157 decrypt_good_mask |= decrypt_good_mask >> 2;
2158 decrypt_good_mask |= decrypt_good_mask >> 1;
2159 /* Now select only the LSB and subtract one. If decrypt_len ==
2160 * SSL_MAX_MASTER_KEY_LENGTH and the version check passed then
2161 * decrypt_good_mask will be all ones. Otherwise it'll be all
2163 decrypt_good_mask &= 1;
2164 decrypt_good_mask--;
2166 /* Now copy rand_premaster_secret over premaster_secret using
2167 * decrypt_good_mask. */
2168 for (j = 0; j < sizeof(rand_premaster_secret); j++)
2170 premaster_secret[j] = (premaster_secret[j] & decrypt_good_mask) |
2171 (rand_premaster_secret[j] & ~decrypt_good_mask);
2174 premaster_secret_len = sizeof(rand_premaster_secret);
2176 #ifndef OPENSSL_NO_DH
2177 else if (alg_k & (SSL_kEDH|SSL_kDHr|SSL_kDHd))
2182 EVP_PKEY *skey = NULL;
2184 if (!CBS_get_u16_length_prefixed(&client_key_exchange, &dh_Yc) ||
2185 CBS_len(&client_key_exchange) != 0)
2187 OPENSSL_PUT_ERROR(SSL, ssl3_get_client_key_exchange, SSL_R_DH_PUBLIC_VALUE_LENGTH_IS_WRONG);
2188 al = SSL_R_DECODE_ERROR;
2192 if (alg_k & SSL_kDHr)
2193 idx = SSL_PKEY_DH_RSA;
2194 else if (alg_k & SSL_kDHd)
2195 idx = SSL_PKEY_DH_DSA;
2198 skey = s->cert->pkeys[idx].privatekey;
2199 if ((skey == NULL) ||
2200 (skey->type != EVP_PKEY_DH) ||
2201 (skey->pkey.dh == NULL))
2203 al=SSL_AD_HANDSHAKE_FAILURE;
2204 OPENSSL_PUT_ERROR(SSL, ssl3_get_client_key_exchange, SSL_R_MISSING_RSA_CERTIFICATE);
2207 dh_srvr = skey->pkey.dh;
2209 else if (s->s3->tmp.dh == NULL)
2211 al=SSL_AD_HANDSHAKE_FAILURE;
2212 OPENSSL_PUT_ERROR(SSL, ssl3_get_client_key_exchange, SSL_R_MISSING_TMP_DH_KEY);
2216 dh_srvr=s->s3->tmp.dh;
2218 if (CBS_len(&dh_Yc) == 0)
2220 /* Get pubkey from the client certificate. This is the
2221 * 'implicit' case of ClientDiffieHellman.
2223 * TODO(davidben): Either lose this code or fix a bug
2224 * (or get the spec changed): if there is a fixed_dh
2225 * client certificate, per spec, the 'implicit' mode
2226 * MUST be used. This logic will still accept 'explicit'
2228 EVP_PKEY *clkey=X509_get_pubkey(s->session->peer);
2231 if (EVP_PKEY_cmp_parameters(clkey, skey) == 1)
2232 dh_clnt = EVP_PKEY_get1_DH(clkey);
2234 if (dh_clnt == NULL)
2236 al=SSL_AD_HANDSHAKE_FAILURE;
2237 OPENSSL_PUT_ERROR(SSL, ssl3_get_client_key_exchange, SSL_R_MISSING_TMP_DH_KEY);
2240 EVP_PKEY_free(clkey);
2241 pub = dh_clnt->pub_key;
2244 pub = BN_bin2bn(CBS_data(&dh_Yc), CBS_len(&dh_Yc), NULL);
2247 OPENSSL_PUT_ERROR(SSL, ssl3_get_client_key_exchange, SSL_R_BN_LIB);
2251 /* Allocate a buffer for the premaster secret. */
2252 premaster_secret = OPENSSL_malloc(DH_size(dh_srvr));
2253 if (premaster_secret == NULL)
2255 OPENSSL_PUT_ERROR(SSL, ssl3_get_client_key_exchange, ERR_R_MALLOC_FAILURE);
2259 dh_len = DH_compute_key(premaster_secret, pub, dh_srvr);
2262 OPENSSL_PUT_ERROR(SSL, ssl3_get_client_key_exchange, ERR_R_DH_LIB);
2267 DH_free(s->s3->tmp.dh);
2275 premaster_secret_len = dh_len;
2277 skip_certificate_verify = 1;
2281 #ifndef OPENSSL_NO_ECDH
2282 else if (alg_k & (SSL_kEECDH|SSL_kECDHr|SSL_kECDHe))
2284 int field_size = 0, ecdh_len;
2286 const EC_GROUP *group;
2287 const BIGNUM *priv_key;
2289 /* initialize structures for server's ECDH key pair */
2290 if ((srvr_ecdh = EC_KEY_new()) == NULL)
2292 OPENSSL_PUT_ERROR(SSL, ssl3_get_client_key_exchange, ERR_R_MALLOC_FAILURE);
2296 /* Let's get server private key and group information */
2297 if (alg_k & (SSL_kECDHr|SSL_kECDHe))
2299 /* use the certificate */
2300 tkey = s->cert->pkeys[SSL_PKEY_ECC].privatekey->pkey.ec;
2304 /* use the ephermeral values we saved when
2305 * generating the ServerKeyExchange msg.
2307 tkey = s->s3->tmp.ecdh;
2310 group = EC_KEY_get0_group(tkey);
2311 priv_key = EC_KEY_get0_private_key(tkey);
2313 if (!EC_KEY_set_group(srvr_ecdh, group) ||
2314 !EC_KEY_set_private_key(srvr_ecdh, priv_key))
2316 OPENSSL_PUT_ERROR(SSL, ssl3_get_client_key_exchange, ERR_R_EC_LIB);
2320 /* Let's get client's public key */
2321 if ((clnt_ecpoint = EC_POINT_new(group)) == NULL)
2323 OPENSSL_PUT_ERROR(SSL, ssl3_get_client_key_exchange, ERR_R_MALLOC_FAILURE);
2327 if (CBS_len(&client_key_exchange) == 0)
2329 /* Client Publickey was in Client Certificate */
2331 if (alg_k & SSL_kEECDH)
2333 al=SSL_AD_HANDSHAKE_FAILURE;
2334 OPENSSL_PUT_ERROR(SSL, ssl3_get_client_key_exchange, SSL_R_MISSING_TMP_ECDH_KEY);
2337 if (((clnt_pub_pkey=X509_get_pubkey(s->session->peer))
2339 (clnt_pub_pkey->type != EVP_PKEY_EC))
2341 /* XXX: For now, we do not support client
2342 * authentication using ECDH certificates
2343 * so this branch (n == 0L) of the code is
2344 * never executed. When that support is
2345 * added, we ought to ensure the key
2346 * received in the certificate is
2347 * authorized for key agreement.
2348 * ECDH_compute_key implicitly checks that
2349 * the two ECDH shares are for the same
2352 al=SSL_AD_HANDSHAKE_FAILURE;
2353 OPENSSL_PUT_ERROR(SSL, ssl3_get_client_key_exchange, SSL_R_UNABLE_TO_DECODE_ECDH_CERTS);
2357 if (EC_POINT_copy(clnt_ecpoint,
2358 EC_KEY_get0_public_key(clnt_pub_pkey->pkey.ec)) == 0)
2360 OPENSSL_PUT_ERROR(SSL, ssl3_get_client_key_exchange, ERR_R_EC_LIB);
2363 /* Skip certificate verify processing */
2364 skip_certificate_verify = 1;
2370 /* Get client's public key from encoded point
2371 * in the ClientKeyExchange message.
2373 if (!CBS_get_u8_length_prefixed(&client_key_exchange, &ecdh_Yc) ||
2374 CBS_len(&client_key_exchange) != 0)
2376 al = SSL_AD_DECODE_ERROR;
2377 OPENSSL_PUT_ERROR(SSL, ssl3_get_client_key_exchange, SSL_R_DECODE_ERROR);
2381 if ((bn_ctx = BN_CTX_new()) == NULL)
2383 OPENSSL_PUT_ERROR(SSL, ssl3_get_client_key_exchange, ERR_R_MALLOC_FAILURE);
2387 if (!EC_POINT_oct2point(group, clnt_ecpoint,
2388 CBS_data(&ecdh_Yc), CBS_len(&ecdh_Yc), bn_ctx))
2390 OPENSSL_PUT_ERROR(SSL, ssl3_get_client_key_exchange, ERR_R_EC_LIB);
2395 /* Allocate a buffer for both the secret and the PSK. */
2396 field_size = EC_GROUP_get_degree(group);
2397 if (field_size <= 0)
2399 OPENSSL_PUT_ERROR(SSL, ssl3_get_client_key_exchange, ERR_R_ECDH_LIB);
2403 ecdh_len = (field_size + 7) / 8;
2404 premaster_secret = OPENSSL_malloc(ecdh_len);
2405 if (premaster_secret == NULL)
2407 OPENSSL_PUT_ERROR(SSL, ssl3_get_client_key_exchange, ERR_R_MALLOC_FAILURE);
2411 /* Compute the shared pre-master secret */
2412 ecdh_len = ECDH_compute_key(premaster_secret,
2413 ecdh_len, clnt_ecpoint, srvr_ecdh, NULL);
2416 OPENSSL_PUT_ERROR(SSL, ssl3_get_client_key_exchange, ERR_R_ECDH_LIB);
2420 EVP_PKEY_free(clnt_pub_pkey);
2421 EC_POINT_free(clnt_ecpoint);
2422 EC_KEY_free(srvr_ecdh);
2423 BN_CTX_free(bn_ctx);
2424 EC_KEY_free(s->s3->tmp.ecdh);
2425 s->s3->tmp.ecdh = NULL;
2427 premaster_secret_len = ecdh_len;
2430 else if (alg_k & SSL_kPSK)
2432 /* For plain PSK, other_secret is a block of 0s with the same
2433 * length as the pre-shared key. */
2434 premaster_secret_len = psk_len;
2435 premaster_secret = OPENSSL_malloc(premaster_secret_len);
2436 if (premaster_secret == NULL)
2438 OPENSSL_PUT_ERROR(SSL, ssl3_get_client_key_exchange, ERR_R_MALLOC_FAILURE);
2441 memset(premaster_secret, 0, premaster_secret_len);
2445 al=SSL_AD_HANDSHAKE_FAILURE;
2446 OPENSSL_PUT_ERROR(SSL, ssl3_get_client_key_exchange, SSL_R_UNKNOWN_CIPHER_TYPE);
2450 /* For a PSK cipher suite, the actual pre-master secret is combined with
2451 * the pre-shared key. */
2452 if (alg_a & SSL_aPSK)
2454 CBB new_premaster, child;
2458 if (!CBB_init(&new_premaster, 2 + psk_len + 2 + premaster_secret_len))
2460 OPENSSL_PUT_ERROR(SSL, ssl3_get_client_key_exchange, ERR_R_MALLOC_FAILURE);
2463 if (!CBB_add_u16_length_prefixed(&new_premaster, &child) ||
2464 !CBB_add_bytes(&child, premaster_secret, premaster_secret_len) ||
2465 !CBB_add_u16_length_prefixed(&new_premaster, &child) ||
2466 !CBB_add_bytes(&child, psk, psk_len) ||
2467 !CBB_finish(&new_premaster, &new_data, &new_len))
2469 OPENSSL_PUT_ERROR(SSL, ssl3_get_client_key_exchange, ERR_R_INTERNAL_ERROR);
2470 CBB_cleanup(&new_premaster);
2474 OPENSSL_cleanse(premaster_secret, premaster_secret_len);
2475 OPENSSL_free(premaster_secret);
2476 premaster_secret = new_data;
2477 premaster_secret_len = new_len;
2480 /* Compute the master secret */
2481 s->session->master_key_length = s->method->ssl3_enc
2482 ->generate_master_secret(s,
2483 s->session->master_key, premaster_secret, premaster_secret_len);
2485 OPENSSL_cleanse(premaster_secret, premaster_secret_len);
2486 OPENSSL_free(premaster_secret);
2487 return skip_certificate_verify ? 2 : 1;
2489 ssl3_send_alert(s,SSL3_AL_FATAL,al);
2491 if (premaster_secret)
2493 if (premaster_secret_len)
2494 OPENSSL_cleanse(premaster_secret, premaster_secret_len);
2495 OPENSSL_free(premaster_secret);
2498 OPENSSL_free(decrypt_buf);
2499 #ifndef OPENSSL_NO_ECDH
2500 EVP_PKEY_free(clnt_pub_pkey);
2501 EC_POINT_free(clnt_ecpoint);
2502 if (srvr_ecdh != NULL)
2503 EC_KEY_free(srvr_ecdh);
2504 BN_CTX_free(bn_ctx);
2509 int ssl3_get_cert_verify(SSL *s)
2511 EVP_PKEY *pkey=NULL;
2514 CBS certificate_verify, signature;
2516 X509 *peer = s->session->peer;
2517 const EVP_MD *md = NULL;
2520 EVP_MD_CTX_init(&mctx);
2522 /* Determine if a CertificateVerify message is expected at all. It is
2523 * important that this be determined before ssl_get_message is called,
2524 * so as not to process the ChangeCipherSpec message early. */
2527 pkey = X509_get_pubkey(peer);
2528 type = X509_certificate_type(peer,pkey);
2530 if (!(type & EVP_PKT_SIGN))
2533 goto done_with_buffer;
2536 n=s->method->ssl_get_message(s,
2537 SSL3_ST_SR_CERT_VRFY_A,
2538 SSL3_ST_SR_CERT_VRFY_B,
2539 SSL3_MT_CERTIFICATE_VERIFY,
2540 SSL3_RT_MAX_PLAIN_LENGTH,
2549 CBS_init(&certificate_verify, s->init_msg, n);
2551 /* We now have a signature that we need to verify. */
2552 /* TODO(davidben): This should share code with
2553 * ssl3_get_server_key_exchange. */
2555 if (SSL_USE_SIGALGS(s))
2557 if (!tls12_check_peer_sigalg(&md, &al, s, &certificate_verify, pkey))
2561 if (!CBS_get_u16_length_prefixed(&certificate_verify, &signature) ||
2562 CBS_len(&certificate_verify) != 0)
2564 al = SSL_AD_DECODE_ERROR;
2565 OPENSSL_PUT_ERROR(SSL, ssl3_get_cert_verify, SSL_R_DECODE_ERROR);
2569 if (SSL_USE_SIGALGS(s))
2572 const uint8_t *hdata;
2573 if (!BIO_mem_contents(s->s3->handshake_buffer, &hdata, &hdatalen))
2575 OPENSSL_PUT_ERROR(SSL, ssl3_get_cert_verify, ERR_R_INTERNAL_ERROR);
2576 al=SSL_AD_INTERNAL_ERROR;
2579 if (!EVP_VerifyInit_ex(&mctx, md, NULL)
2580 || !EVP_VerifyUpdate(&mctx, hdata, hdatalen))
2582 OPENSSL_PUT_ERROR(SSL, ssl3_get_cert_verify, ERR_R_EVP_LIB);
2583 al=SSL_AD_INTERNAL_ERROR;
2587 if (EVP_VerifyFinal(&mctx,
2588 CBS_data(&signature), CBS_len(&signature),
2591 al=SSL_AD_DECRYPT_ERROR;
2592 OPENSSL_PUT_ERROR(SSL, ssl3_get_cert_verify, SSL_R_BAD_SIGNATURE);
2597 if (pkey->type == EVP_PKEY_RSA)
2599 if (!RSA_verify(NID_md5_sha1, s->s3->tmp.cert_verify_md,
2600 MD5_DIGEST_LENGTH+SHA_DIGEST_LENGTH,
2601 CBS_data(&signature), CBS_len(&signature),
2604 al = SSL_AD_DECRYPT_ERROR;
2605 OPENSSL_PUT_ERROR(SSL, ssl3_get_cert_verify, SSL_R_BAD_RSA_SIGNATURE);
2610 #ifndef OPENSSL_NO_DSA
2611 if (pkey->type == EVP_PKEY_DSA)
2613 if (DSA_verify(pkey->save_type,
2614 &(s->s3->tmp.cert_verify_md[MD5_DIGEST_LENGTH]),
2616 CBS_data(&signature), CBS_len(&signature),
2617 pkey->pkey.dsa) <= 0)
2620 al = SSL_AD_DECRYPT_ERROR;
2621 OPENSSL_PUT_ERROR(SSL, ssl3_get_cert_verify, SSL_R_BAD_DSA_SIGNATURE);
2627 #ifndef OPENSSL_NO_ECDSA
2628 if (pkey->type == EVP_PKEY_EC)
2630 if (!ECDSA_verify(pkey->save_type,
2631 &(s->s3->tmp.cert_verify_md[MD5_DIGEST_LENGTH]),
2633 CBS_data(&signature), CBS_len(&signature),
2637 al = SSL_AD_DECRYPT_ERROR;
2638 OPENSSL_PUT_ERROR(SSL, ssl3_get_cert_verify, SSL_R_BAD_ECDSA_SIGNATURE);
2645 OPENSSL_PUT_ERROR(SSL, ssl3_get_cert_verify, ERR_R_INTERNAL_ERROR);
2646 al=SSL_AD_UNSUPPORTED_CERTIFICATE;
2655 ssl3_send_alert(s,SSL3_AL_FATAL,al);
2658 /* There is no more need for the handshake buffer. */
2659 if (s->s3->handshake_buffer)
2661 BIO_free(s->s3->handshake_buffer);
2662 s->s3->handshake_buffer = NULL;
2663 s->s3->flags &= ~TLS1_FLAGS_KEEP_HANDSHAKE;
2666 EVP_MD_CTX_cleanup(&mctx);
2667 EVP_PKEY_free(pkey);
2671 int ssl3_get_client_certificate(SSL *s)
2673 int i,ok,al,ret= -1;
2676 STACK_OF(X509) *sk=NULL;
2678 CBS certificate_msg, certificate_list;
2679 int is_first_certificate = 1;
2681 n=s->method->ssl_get_message(s,
2688 if (!ok) return((int)n);
2690 if (s->s3->tmp.message_type == SSL3_MT_CLIENT_KEY_EXCHANGE)
2692 if ( (s->verify_mode & SSL_VERIFY_PEER) &&
2693 (s->verify_mode & SSL_VERIFY_FAIL_IF_NO_PEER_CERT))
2695 OPENSSL_PUT_ERROR(SSL, ssl3_get_client_certificate, SSL_R_PEER_DID_NOT_RETURN_A_CERTIFICATE);
2696 al=SSL_AD_HANDSHAKE_FAILURE;
2699 /* If tls asked for a client cert, the client must return a 0 list */
2700 if ((s->version > SSL3_VERSION) && s->s3->tmp.cert_request)
2702 OPENSSL_PUT_ERROR(SSL, ssl3_get_client_certificate, SSL_R_TLS_PEER_DID_NOT_RESPOND_WITH_CERTIFICATE_LIST);
2703 al=SSL_AD_UNEXPECTED_MESSAGE;
2706 s->s3->tmp.reuse_message=1;
2710 if (s->s3->tmp.message_type != SSL3_MT_CERTIFICATE)
2712 al=SSL_AD_UNEXPECTED_MESSAGE;
2713 OPENSSL_PUT_ERROR(SSL, ssl3_get_client_certificate, SSL_R_WRONG_MESSAGE_TYPE);
2717 CBS_init(&certificate_msg, s->init_msg, n);
2719 if ((sk=sk_X509_new_null()) == NULL)
2721 OPENSSL_PUT_ERROR(SSL, ssl3_get_client_certificate, ERR_R_MALLOC_FAILURE);
2725 if (!CBS_get_u24_length_prefixed(&certificate_msg, &certificate_list) ||
2726 CBS_len(&certificate_msg) != 0)
2728 al = SSL_AD_DECODE_ERROR;
2729 OPENSSL_PUT_ERROR(SSL, ssl3_get_client_certificate, SSL_R_DECODE_ERROR);
2733 while (CBS_len(&certificate_list) > 0)
2736 const uint8_t *data;
2738 if (!CBS_get_u24_length_prefixed(&certificate_list, &certificate))
2740 al = SSL_AD_DECODE_ERROR;
2741 OPENSSL_PUT_ERROR(SSL, ssl3_get_client_certificate, SSL_R_DECODE_ERROR);
2744 if (is_first_certificate && s->ctx->retain_only_sha256_of_client_certs)
2746 /* If this is the first certificate, and we don't want
2747 * to keep peer certificates in memory, then we hash it
2749 SHA256_Init(&sha256);
2750 SHA256_Update(&sha256, CBS_data(&certificate), CBS_len(&certificate));
2751 SHA256_Final(s->session->peer_sha256, &sha256);
2752 s->session->peer_sha256_valid = 1;
2754 is_first_certificate = 0;
2755 data = CBS_data(&certificate);
2756 x = d2i_X509(NULL, &data, CBS_len(&certificate));
2759 al = SSL_AD_BAD_CERTIFICATE;
2760 OPENSSL_PUT_ERROR(SSL, ssl3_get_client_certificate, ERR_R_ASN1_LIB);
2763 if (!CBS_skip(&certificate, data - CBS_data(&certificate)))
2765 al = SSL_AD_INTERNAL_ERROR;
2766 OPENSSL_PUT_ERROR(SSL, ssl3_get_client_certificate, ERR_R_INTERNAL_ERROR);
2769 if (CBS_len(&certificate) != 0)
2771 al = SSL_AD_DECODE_ERROR;
2772 OPENSSL_PUT_ERROR(SSL, ssl3_get_client_certificate, SSL_R_CERT_LENGTH_MISMATCH);
2775 if (!sk_X509_push(sk,x))
2777 OPENSSL_PUT_ERROR(SSL, ssl3_get_client_certificate, ERR_R_MALLOC_FAILURE);
2783 if (sk_X509_num(sk) <= 0)
2785 /* TLS does not mind 0 certs returned */
2786 if (s->version == SSL3_VERSION)
2788 al=SSL_AD_HANDSHAKE_FAILURE;
2789 OPENSSL_PUT_ERROR(SSL, ssl3_get_client_certificate, SSL_R_NO_CERTIFICATES_RETURNED);
2792 /* Fail for TLS only if we required a certificate */
2793 else if ((s->verify_mode & SSL_VERIFY_PEER) &&
2794 (s->verify_mode & SSL_VERIFY_FAIL_IF_NO_PEER_CERT))
2796 OPENSSL_PUT_ERROR(SSL, ssl3_get_client_certificate, SSL_R_PEER_DID_NOT_RETURN_A_CERTIFICATE);
2797 al=SSL_AD_HANDSHAKE_FAILURE;
2800 /* No client certificate so digest cached records */
2801 if (s->s3->handshake_buffer && !ssl3_digest_cached_records(s))
2803 al=SSL_AD_INTERNAL_ERROR;
2809 i=ssl_verify_cert_chain(s,sk);
2812 al=ssl_verify_alarm_type(s->verify_result);
2813 OPENSSL_PUT_ERROR(SSL, ssl3_get_client_certificate, SSL_R_CERTIFICATE_VERIFY_FAILED);
2818 if (s->session->peer != NULL) /* This should not be needed */
2819 X509_free(s->session->peer);
2820 s->session->peer=sk_X509_shift(sk);
2821 s->session->verify_result = s->verify_result;
2823 /* With the current implementation, sess_cert will always be NULL
2824 * when we arrive here. */
2825 if (s->session->sess_cert == NULL)
2827 s->session->sess_cert = ssl_sess_cert_new();
2828 if (s->session->sess_cert == NULL)
2830 OPENSSL_PUT_ERROR(SSL, ssl3_get_client_certificate, ERR_R_MALLOC_FAILURE);
2834 if (s->session->sess_cert->cert_chain != NULL)
2835 sk_X509_pop_free(s->session->sess_cert->cert_chain, X509_free);
2836 s->session->sess_cert->cert_chain=sk;
2837 /* Inconsistency alert: cert_chain does *not* include the
2838 * peer's own certificate, while we do include it in s3_clnt.c */
2846 ssl3_send_alert(s,SSL3_AL_FATAL,al);
2849 if (x != NULL) X509_free(x);
2850 if (sk != NULL) sk_X509_pop_free(sk,X509_free);
2854 int ssl3_send_server_certificate(SSL *s)
2858 if (s->state == SSL3_ST_SW_CERT_A)
2860 cpk=ssl_get_server_send_pkey(s);
2863 OPENSSL_PUT_ERROR(SSL, ssl3_send_server_certificate, ERR_R_INTERNAL_ERROR);
2867 ssl3_output_cert_chain(s,cpk);
2868 s->state=SSL3_ST_SW_CERT_B;
2871 /* SSL3_ST_SW_CERT_B */
2872 return ssl_do_write(s);
2875 /* send a new session ticket (not necessarily for a new session) */
2876 int ssl3_send_newsession_ticket(SSL *s)
2878 if (s->state == SSL3_ST_SW_SESSION_TICKET_A)
2880 unsigned char *p, *senc, *macstart;
2881 const unsigned char *const_p;
2882 int len, slen_full, slen;
2887 SSL_CTX *tctx = s->initial_ctx;
2888 unsigned char iv[EVP_MAX_IV_LENGTH];
2889 unsigned char key_name[16];
2891 /* get session encoding length */
2892 slen_full = i2d_SSL_SESSION(s->session, NULL);
2893 /* Some length values are 16 bits, so forget it if session is
2896 if (slen_full > 0xFF00)
2898 senc = OPENSSL_malloc(slen_full);
2902 i2d_SSL_SESSION(s->session, &p);
2904 /* create a fresh copy (not shared with other threads) to clean up */
2906 sess = d2i_SSL_SESSION(NULL, &const_p, slen_full);
2912 sess->session_id_length = 0; /* ID is irrelevant for the ticket */
2914 slen = i2d_SSL_SESSION(sess, NULL);
2915 if (slen > slen_full) /* shouldn't ever happen */
2921 i2d_SSL_SESSION(sess, &p);
2922 SSL_SESSION_free(sess);
2924 /* Grow buffer if need be: the length calculation is as
2925 * follows handshake_header_length +
2926 * 4 (ticket lifetime hint) + 2 (ticket length) +
2927 * 16 (key name) + max_iv_len (iv length) +
2928 * session_length + max_enc_block_size (max encrypted session
2929 * length) + max_md_size (HMAC).
2931 if (!BUF_MEM_grow(s->init_buf,
2932 SSL_HM_HEADER_LENGTH(s) + 22 + EVP_MAX_IV_LENGTH +
2933 EVP_MAX_BLOCK_LENGTH + EVP_MAX_MD_SIZE + slen))
2935 p = ssl_handshake_start(s);
2936 EVP_CIPHER_CTX_init(&ctx);
2937 HMAC_CTX_init(&hctx);
2938 /* Initialize HMAC and cipher contexts. If callback present
2939 * it does all the work otherwise use generated values
2942 if (tctx->tlsext_ticket_key_cb)
2944 if (tctx->tlsext_ticket_key_cb(s, key_name, iv, &ctx,
2953 RAND_pseudo_bytes(iv, 16);
2954 EVP_EncryptInit_ex(&ctx, EVP_aes_128_cbc(), NULL,
2955 tctx->tlsext_tick_aes_key, iv);
2956 HMAC_Init_ex(&hctx, tctx->tlsext_tick_hmac_key, 16,
2957 tlsext_tick_md(), NULL);
2958 memcpy(key_name, tctx->tlsext_tick_key_name, 16);
2961 /* Ticket lifetime hint (advisory only):
2962 * We leave this unspecified for resumed session (for simplicity),
2963 * and guess that tickets for new sessions will live as long
2964 * as their sessions. */
2965 l2n(s->hit ? 0 : s->session->timeout, p);
2967 /* Skip ticket length for now */
2969 /* Output key name */
2971 memcpy(p, key_name, 16);
2974 memcpy(p, iv, EVP_CIPHER_CTX_iv_length(&ctx));
2975 p += EVP_CIPHER_CTX_iv_length(&ctx);
2976 /* Encrypt session data */
2977 EVP_EncryptUpdate(&ctx, p, &len, senc, slen);
2979 EVP_EncryptFinal_ex(&ctx, p, &len);
2981 EVP_CIPHER_CTX_cleanup(&ctx);
2983 HMAC_Update(&hctx, macstart, p - macstart);
2984 HMAC_Final(&hctx, p, &hlen);
2985 HMAC_CTX_cleanup(&hctx);
2988 /* Now write out lengths: p points to end of data written */
2990 len = p - ssl_handshake_start(s);
2991 ssl_set_handshake_header(s, SSL3_MT_NEWSESSION_TICKET, len);
2992 /* Skip ticket lifetime hint */
2993 p = ssl_handshake_start(s) + 4;
2995 s->state=SSL3_ST_SW_SESSION_TICKET_B;
2999 /* SSL3_ST_SW_SESSION_TICKET_B */
3000 return ssl_do_write(s);
3003 int ssl3_send_cert_status(SSL *s)
3005 if (s->state == SSL3_ST_SW_CERT_STATUS_A)
3008 /* Grow buffer if need be: the length calculation is as
3009 * follows 1 (message type) + 3 (message length) +
3010 * 1 (ocsp response type) + 3 (ocsp response length)
3013 if (!BUF_MEM_grow(s->init_buf, 8 + s->tlsext_ocsp_resplen))
3016 p=(unsigned char *)s->init_buf->data;
3019 *(p++)=SSL3_MT_CERTIFICATE_STATUS;
3020 /* message length */
3021 l2n3(s->tlsext_ocsp_resplen + 4, p);
3023 *(p++)= s->tlsext_status_type;
3024 /* length of OCSP response */
3025 l2n3(s->tlsext_ocsp_resplen, p);
3026 /* actual response */
3027 memcpy(p, s->tlsext_ocsp_resp, s->tlsext_ocsp_resplen);
3028 /* number of bytes to write */
3029 s->init_num = 8 + s->tlsext_ocsp_resplen;
3030 s->state=SSL3_ST_SW_CERT_STATUS_B;
3034 /* SSL3_ST_SW_CERT_STATUS_B */
3035 return(ssl3_do_write(s,SSL3_RT_HANDSHAKE));
3038 # ifndef OPENSSL_NO_NEXTPROTONEG
3039 /* ssl3_get_next_proto reads a Next Protocol Negotiation handshake message. It
3040 * sets the next_proto member in s if found */
3041 int ssl3_get_next_proto(SSL *s)
3045 CBS next_protocol, selected_protocol, padding;
3047 /* Clients cannot send a NextProtocol message if we didn't see the
3048 * extension in their ClientHello */
3049 if (!s->s3->next_proto_neg_seen)
3051 OPENSSL_PUT_ERROR(SSL, ssl3_get_next_proto, SSL_R_GOT_NEXT_PROTO_WITHOUT_EXTENSION);
3055 n=s->method->ssl_get_message(s,
3056 SSL3_ST_SR_NEXT_PROTO_A,
3057 SSL3_ST_SR_NEXT_PROTO_B,
3059 514, /* See the payload format below */
3065 /* s->state doesn't reflect whether ChangeCipherSpec has been received
3066 * in this handshake, but s->s3->change_cipher_spec does (will be reset
3067 * by ssl3_get_finished).
3068 * TODO(davidben): Is this check now redundant with
3069 * SSL3_FLAGS_EXPECT_CCS? */
3070 if (!s->s3->change_cipher_spec)
3072 OPENSSL_PUT_ERROR(SSL, ssl3_get_next_proto, SSL_R_GOT_NEXT_PROTO_BEFORE_A_CCS);
3076 CBS_init(&next_protocol, s->init_msg, n);
3078 /* The payload looks like:
3080 * uint8 proto[proto_len];
3081 * uint8 padding_len;
3082 * uint8 padding[padding_len];
3084 if (!CBS_get_u8_length_prefixed(&next_protocol, &selected_protocol) ||
3085 !CBS_get_u8_length_prefixed(&next_protocol, &padding) ||
3086 CBS_len(&next_protocol) != 0)
3089 if (!CBS_stow(&selected_protocol,
3090 &s->next_proto_negotiated,
3091 &s->next_proto_negotiated_len))
3098 /* ssl3_get_channel_id reads and verifies a ClientID handshake message. */
3099 int ssl3_get_channel_id(SSL *s)
3104 uint16_t extension_type, expected_extension_type;
3105 EC_GROUP* p256 = NULL;
3107 EC_POINT* point = NULL;
3110 CBS encrypted_extensions, extension;
3112 if (s->state == SSL3_ST_SR_CHANNEL_ID_A && s->init_num == 0)
3114 /* The first time that we're called we take the current
3115 * handshake hash and store it. */
3119 EVP_MD_CTX_init(&md_ctx);
3120 EVP_DigestInit_ex(&md_ctx, EVP_sha256(), NULL);
3121 if (!tls1_channel_id_hash(&md_ctx, s))
3123 len = sizeof(s->s3->tlsext_channel_id);
3124 EVP_DigestFinal(&md_ctx, s->s3->tlsext_channel_id, &len);
3125 EVP_MD_CTX_cleanup(&md_ctx);
3128 n = s->method->ssl_get_message(s,
3129 SSL3_ST_SR_CHANNEL_ID_A,
3130 SSL3_ST_SR_CHANNEL_ID_B,
3131 SSL3_MT_ENCRYPTED_EXTENSIONS,
3132 2 + 2 + TLSEXT_CHANNEL_ID_SIZE,
3138 ssl3_finish_mac(s, (unsigned char*)s->init_buf->data, s->init_num + 4);
3140 /* s->state doesn't reflect whether ChangeCipherSpec has been received
3141 * in this handshake, but s->s3->change_cipher_spec does (will be reset
3142 * by ssl3_get_finished).
3143 * TODO(davidben): Is this check now redundant with
3144 * SSL3_FLAGS_EXPECT_CCS? */
3145 if (!s->s3->change_cipher_spec)
3147 OPENSSL_PUT_ERROR(SSL, ssl3_get_channel_id, SSL_R_GOT_CHANNEL_ID_BEFORE_A_CCS);
3151 CBS_init(&encrypted_extensions, s->init_msg, n);
3153 /* EncryptedExtensions could include multiple extensions, but
3154 * the only extension that could be negotiated is ChannelID,
3155 * so there can only be one entry.
3157 * The payload looks like:
3158 * uint16 extension_type
3159 * uint16 extension_len;
3165 expected_extension_type = TLSEXT_TYPE_channel_id;
3166 if (s->s3->tlsext_channel_id_new)
3167 expected_extension_type = TLSEXT_TYPE_channel_id_new;
3169 if (!CBS_get_u16(&encrypted_extensions, &extension_type) ||
3170 !CBS_get_u16_length_prefixed(&encrypted_extensions, &extension) ||
3171 CBS_len(&encrypted_extensions) != 0 ||
3172 extension_type != expected_extension_type ||
3173 CBS_len(&extension) != TLSEXT_CHANNEL_ID_SIZE)
3175 OPENSSL_PUT_ERROR(SSL, ssl3_get_channel_id, SSL_R_INVALID_MESSAGE);
3179 p256 = EC_GROUP_new_by_curve_name(NID_X9_62_prime256v1);
3182 OPENSSL_PUT_ERROR(SSL, ssl3_get_channel_id, SSL_R_NO_P256_SUPPORT);
3191 p = CBS_data(&extension);
3192 if (BN_bin2bn(p + 0, 32, &x) == NULL ||
3193 BN_bin2bn(p + 32, 32, &y) == NULL ||
3194 BN_bin2bn(p + 64, 32, sig.r) == NULL ||
3195 BN_bin2bn(p + 96, 32, sig.s) == NULL)
3198 point = EC_POINT_new(p256);
3200 !EC_POINT_set_affine_coordinates_GFp(p256, point, &x, &y, NULL))
3205 !EC_KEY_set_group(key, p256) ||
3206 !EC_KEY_set_public_key(key, point))
3209 /* We stored the handshake hash in |tlsext_channel_id| the first time
3210 * that we were called. */
3211 switch (ECDSA_do_verify(s->s3->tlsext_channel_id, SHA256_DIGEST_LENGTH, &sig, key)) {
3215 OPENSSL_PUT_ERROR(SSL, ssl3_get_channel_id, SSL_R_CHANNEL_ID_SIGNATURE_INVALID);
3216 s->s3->tlsext_channel_id_valid = 0;
3219 s->s3->tlsext_channel_id_valid = 0;
3223 memcpy(s->s3->tlsext_channel_id, p, 64);
3234 EC_POINT_free(point);
3236 EC_GROUP_free(p256);