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);
176 static const SSL_METHOD *ssl3_get_server_method(int ver)
178 if (ver == SSL3_VERSION)
179 return(SSLv3_server_method());
184 IMPLEMENT_ssl3_meth_func(SSLv3_server_method,
186 ssl_undefined_function,
187 ssl3_get_server_method)
189 int ssl3_accept(SSL *s)
193 void (*cb)(const SSL *ssl,int type,int val)=NULL;
195 int new_state,state,skip=0;
198 ERR_clear_system_error();
200 if (s->info_callback != NULL)
202 else if (s->ctx->info_callback != NULL)
203 cb=s->ctx->info_callback;
205 /* init things to blank */
207 if (!SSL_in_init(s) || SSL_in_before(s)) SSL_clear(s);
211 OPENSSL_PUT_ERROR(SSL, ssl3_accept, SSL_R_NO_CERTIFICATE_SET);
221 case SSL_ST_RENEGOTIATE:
223 /* s->state=SSL_ST_ACCEPT; */
227 case SSL_ST_BEFORE|SSL_ST_ACCEPT:
228 case SSL_ST_OK|SSL_ST_ACCEPT:
231 if (cb != NULL) cb(s,SSL_CB_HANDSHAKE_START,1);
233 if ((s->version>>8) != 3)
235 OPENSSL_PUT_ERROR(SSL, ssl3_accept, ERR_R_INTERNAL_ERROR);
238 s->type=SSL_ST_ACCEPT;
240 if (s->init_buf == NULL)
242 if ((buf=BUF_MEM_new()) == NULL)
247 if (!BUF_MEM_grow(buf,SSL3_RT_MAX_PLAIN_LENGTH))
255 if (!ssl3_setup_buffers(s))
263 if (s->state != SSL_ST_RENEGOTIATE)
265 /* Ok, we now need to push on a buffering BIO so that
266 * the output is sent in a way that TCP likes :-)
268 if (!ssl_init_wbio_buffer(s,1)) { ret= -1; goto end; }
270 ssl3_init_finished_mac(s);
271 s->state=SSL3_ST_SR_CLNT_HELLO_A;
272 s->ctx->stats.sess_accept++;
274 else if (!s->s3->send_connection_binding &&
275 !(s->options & SSL_OP_ALLOW_UNSAFE_LEGACY_RENEGOTIATION))
277 /* Server attempting to renegotiate with
278 * client that doesn't support secure
281 OPENSSL_PUT_ERROR(SSL, ssl3_accept, SSL_R_UNSAFE_LEGACY_RENEGOTIATION_DISABLED);
282 ssl3_send_alert(s,SSL3_AL_FATAL,SSL_AD_HANDSHAKE_FAILURE);
288 /* s->state == SSL_ST_RENEGOTIATE,
289 * we will just send a HelloRequest */
290 s->ctx->stats.sess_accept_renegotiate++;
291 s->state=SSL3_ST_SW_HELLO_REQ_A;
295 case SSL3_ST_SW_HELLO_REQ_A:
296 case SSL3_ST_SW_HELLO_REQ_B:
299 ret=ssl3_send_hello_request(s);
300 if (ret <= 0) goto end;
301 s->s3->tmp.next_state=SSL3_ST_SW_HELLO_REQ_C;
302 s->state=SSL3_ST_SW_FLUSH;
305 ssl3_init_finished_mac(s);
308 case SSL3_ST_SW_HELLO_REQ_C:
312 case SSL3_ST_SR_CLNT_HELLO_A:
313 case SSL3_ST_SR_CLNT_HELLO_B:
314 case SSL3_ST_SR_CLNT_HELLO_C:
315 case SSL3_ST_SR_CLNT_HELLO_D:
317 ret=ssl3_get_client_hello(s);
318 if (ret == PENDING_SESSION) {
319 s->rwstate = SSL_PENDING_SESSION;
322 if (ret == CERTIFICATE_SELECTION_PENDING)
324 s->rwstate = SSL_CERTIFICATE_SELECTION_PENDING;
327 if (ret <= 0) goto end;
329 s->state=SSL3_ST_SW_SRVR_HELLO_A;
333 case SSL3_ST_SW_SRVR_HELLO_A:
334 case SSL3_ST_SW_SRVR_HELLO_B:
335 ret=ssl3_send_server_hello(s);
336 if (ret <= 0) goto end;
339 if (s->tlsext_ticket_expected)
340 s->state=SSL3_ST_SW_SESSION_TICKET_A;
342 s->state=SSL3_ST_SW_CHANGE_A;
345 s->state = SSL3_ST_SW_CERT_A;
349 case SSL3_ST_SW_CERT_A:
350 case SSL3_ST_SW_CERT_B:
351 if (ssl_cipher_has_server_public_key(s->s3->tmp.new_cipher))
353 ret=ssl3_send_server_certificate(s);
354 if (ret <= 0) goto end;
355 if (s->s3->tmp.certificate_status_expected)
356 s->state=SSL3_ST_SW_CERT_STATUS_A;
358 s->state=SSL3_ST_SW_KEY_EXCH_A;
363 s->state=SSL3_ST_SW_KEY_EXCH_A;
368 case SSL3_ST_SW_KEY_EXCH_A:
369 case SSL3_ST_SW_KEY_EXCH_B:
370 alg_a = s->s3->tmp.new_cipher->algorithm_auth;
372 /* Send a ServerKeyExchange message if:
373 * - The key exchange is ephemeral or anonymous
375 * - There is a PSK identity hint.
377 * TODO(davidben): This logic is currently duplicated
378 * in d1_srvr.c. Fix this. In the meantime, keep them
381 if (ssl_cipher_requires_server_key_exchange(s->s3->tmp.new_cipher) ||
382 ((alg_a & SSL_aPSK) && s->session->psk_identity_hint))
384 ret=ssl3_send_server_key_exchange(s);
385 if (ret <= 0) goto end;
390 s->state=SSL3_ST_SW_CERT_REQ_A;
394 case SSL3_ST_SW_CERT_REQ_A:
395 case SSL3_ST_SW_CERT_REQ_B:
396 if (/* don't request cert unless asked for it: */
397 !(s->verify_mode & SSL_VERIFY_PEER) ||
398 /* Don't request a certificate if an obc was presented */
399 ((s->verify_mode & SSL_VERIFY_PEER_IF_NO_OBC) &&
400 s->s3->tlsext_channel_id_valid) ||
401 /* if SSL_VERIFY_CLIENT_ONCE is set,
402 * don't request cert during re-negotiation: */
403 ((s->session->peer != NULL) &&
404 (s->verify_mode & SSL_VERIFY_CLIENT_ONCE)) ||
405 /* never request cert in anonymous ciphersuites
406 * (see section "Certificate request" in SSL 3 drafts
407 * and in RFC 2246): */
408 ((s->s3->tmp.new_cipher->algorithm_auth & SSL_aNULL) &&
409 /* ... except when the application insists on verification
410 * (against the specs, but s3_clnt.c accepts this for SSL 3) */
411 !(s->verify_mode & SSL_VERIFY_FAIL_IF_NO_PEER_CERT)) ||
412 /* With normal PSK Certificates and
413 * Certificate Requests are omitted */
414 (s->s3->tmp.new_cipher->algorithm_mkey & SSL_kPSK))
416 /* no cert request */
418 s->s3->tmp.cert_request=0;
419 s->state=SSL3_ST_SW_SRVR_DONE_A;
420 if (s->s3->handshake_buffer)
421 if (!ssl3_digest_cached_records(s))
426 s->s3->tmp.cert_request=1;
427 ret=ssl3_send_certificate_request(s);
428 if (ret <= 0) goto end;
429 #ifndef NETSCAPE_HANG_BUG
430 s->state=SSL3_ST_SW_SRVR_DONE_A;
432 s->state=SSL3_ST_SW_FLUSH;
433 s->s3->tmp.next_state=SSL3_ST_SR_CERT_A;
439 case SSL3_ST_SW_SRVR_DONE_A:
440 case SSL3_ST_SW_SRVR_DONE_B:
441 ret=ssl3_send_server_done(s);
442 if (ret <= 0) goto end;
443 s->s3->tmp.next_state=SSL3_ST_SR_CERT_A;
444 s->state=SSL3_ST_SW_FLUSH;
448 case SSL3_ST_SW_FLUSH:
450 /* This code originally checked to see if
451 * any data was pending using BIO_CTRL_INFO
452 * and then flushed. This caused problems
453 * as documented in PR#1939. The proposed
454 * fix doesn't completely resolve this issue
455 * as buggy implementations of BIO_CTRL_PENDING
456 * still exist. So instead we just flush
460 s->rwstate=SSL_WRITING;
461 if (BIO_flush(s->wbio) <= 0)
466 s->rwstate=SSL_NOTHING;
468 s->state=s->s3->tmp.next_state;
471 case SSL3_ST_SR_CERT_A:
472 case SSL3_ST_SR_CERT_B:
473 if (s->s3->tmp.cert_request)
475 ret=ssl3_get_client_certificate(s);
476 if (ret <= 0) goto end;
479 s->state=SSL3_ST_SR_KEY_EXCH_A;
482 case SSL3_ST_SR_KEY_EXCH_A:
483 case SSL3_ST_SR_KEY_EXCH_B:
484 ret=ssl3_get_client_key_exchange(s);
487 s->state=SSL3_ST_SR_CERT_VRFY_A;
491 case SSL3_ST_SR_CERT_VRFY_A:
492 case SSL3_ST_SR_CERT_VRFY_B:
493 ret=ssl3_get_cert_verify(s);
494 if (ret <= 0) goto end;
496 s->state = SSL3_ST_SR_CHANGE;
500 case SSL3_ST_SR_CHANGE: {
501 char next_proto_neg = 0;
503 next_proto_neg = s->s3->next_proto_neg_seen;
504 channel_id = s->s3->tlsext_channel_id_valid;
506 /* At this point, the next message must be entirely
507 * behind a ChangeCipherSpec. */
508 if (!ssl3_expect_change_cipher_spec(s))
514 s->state = SSL3_ST_SR_NEXT_PROTO_A;
516 s->state = SSL3_ST_SR_CHANNEL_ID_A;
518 s->state = SSL3_ST_SR_FINISHED_A;
522 case SSL3_ST_SR_NEXT_PROTO_A:
523 case SSL3_ST_SR_NEXT_PROTO_B:
524 ret=ssl3_get_next_proto(s);
525 if (ret <= 0) goto end;
527 if (s->s3->tlsext_channel_id_valid)
528 s->state=SSL3_ST_SR_CHANNEL_ID_A;
530 s->state=SSL3_ST_SR_FINISHED_A;
533 case SSL3_ST_SR_CHANNEL_ID_A:
534 case SSL3_ST_SR_CHANNEL_ID_B:
535 ret=ssl3_get_channel_id(s);
536 if (ret <= 0) goto end;
538 s->state=SSL3_ST_SR_FINISHED_A;
541 case SSL3_ST_SR_FINISHED_A:
542 case SSL3_ST_SR_FINISHED_B:
543 ret=ssl3_get_finished(s,SSL3_ST_SR_FINISHED_A,
544 SSL3_ST_SR_FINISHED_B);
545 if (ret <= 0) goto end;
548 else if (s->tlsext_ticket_expected)
549 s->state=SSL3_ST_SW_SESSION_TICKET_A;
551 s->state=SSL3_ST_SW_CHANGE_A;
552 /* If this is a full handshake with ChannelID then
553 * record the hashshake hashes in |s->session| in case
554 * we need them to verify a ChannelID signature on a
555 * resumption of this session in the future. */
556 if (!s->hit && s->s3->tlsext_channel_id_new)
558 ret = tls1_record_handshake_hashes_for_channel_id(s);
559 if (ret <= 0) goto end;
564 case SSL3_ST_SW_SESSION_TICKET_A:
565 case SSL3_ST_SW_SESSION_TICKET_B:
566 ret=ssl3_send_new_session_ticket(s);
567 if (ret <= 0) goto end;
568 s->state=SSL3_ST_SW_CHANGE_A;
573 // TODO(davidben): Implement OCSP stapling on the server.
574 case SSL3_ST_SW_CERT_STATUS_A:
575 case SSL3_ST_SW_CERT_STATUS_B:
576 ret=ssl3_send_cert_status(s);
577 if (ret <= 0) goto end;
578 s->state=SSL3_ST_SW_KEY_EXCH_A;
583 case SSL3_ST_SW_CHANGE_A:
584 case SSL3_ST_SW_CHANGE_B:
586 s->session->cipher=s->s3->tmp.new_cipher;
587 if (!s->method->ssl3_enc->setup_key_block(s))
588 { ret= -1; goto end; }
590 ret=ssl3_send_change_cipher_spec(s,
591 SSL3_ST_SW_CHANGE_A,SSL3_ST_SW_CHANGE_B);
593 if (ret <= 0) goto end;
594 s->state=SSL3_ST_SW_FINISHED_A;
597 if (!s->method->ssl3_enc->change_cipher_state(s,
598 SSL3_CHANGE_CIPHER_SERVER_WRITE))
606 case SSL3_ST_SW_FINISHED_A:
607 case SSL3_ST_SW_FINISHED_B:
608 ret=ssl3_send_finished(s,
609 SSL3_ST_SW_FINISHED_A,SSL3_ST_SW_FINISHED_B,
610 s->method->ssl3_enc->server_finished_label,
611 s->method->ssl3_enc->server_finished_label_len);
612 if (ret <= 0) goto end;
613 s->state = SSL3_ST_SW_FLUSH;
615 s->s3->tmp.next_state = SSL3_ST_SR_CHANGE;
617 s->s3->tmp.next_state = SSL_ST_OK;
622 /* clean a few things up */
623 ssl3_cleanup_key_block(s);
625 BUF_MEM_free(s->init_buf);
628 /* remove buffering on output */
629 ssl_free_wbio_buffer(s);
633 /* If we aren't retaining peer certificates then we can
635 if (s->session->peer && s->ctx->retain_only_sha256_of_client_certs)
637 X509_free(s->session->peer);
638 s->session->peer = NULL;
641 if (s->renegotiate == 2) /* skipped if we just sent a HelloRequest */
646 ssl_update_cache(s,SSL_SESS_CACHE_SERVER);
648 s->ctx->stats.sess_accept_good++;
650 s->handshake_func=ssl3_accept;
652 if (cb != NULL) cb(s,SSL_CB_HANDSHAKE_DONE,1);
660 OPENSSL_PUT_ERROR(SSL, ssl3_accept, SSL_R_UNKNOWN_STATE);
666 if (!s->s3->tmp.reuse_message && !skip)
670 if ((ret=BIO_flush(s->wbio)) <= 0)
675 if ((cb != NULL) && (s->state != state))
679 cb(s,SSL_CB_ACCEPT_LOOP,1);
686 /* BIO_flush(s->wbio); */
690 cb(s,SSL_CB_ACCEPT_EXIT,ret);
694 int ssl3_send_hello_request(SSL *s)
697 if (s->state == SSL3_ST_SW_HELLO_REQ_A)
699 ssl_set_handshake_header(s, SSL3_MT_HELLO_REQUEST, 0);
700 s->state=SSL3_ST_SW_HELLO_REQ_B;
703 /* SSL3_ST_SW_HELLO_REQ_B */
704 return ssl_do_write(s);
707 int ssl3_get_client_hello(SSL *s)
709 int i,ok,al=SSL_AD_INTERNAL_ERROR,ret= -1;
712 STACK_OF(SSL_CIPHER) *ciphers=NULL;
713 struct ssl_early_callback_ctx early_ctx;
715 uint16_t client_version;
716 CBS client_random, session_id, cipher_suites, compression_methods;
718 /* We do this so that we will respond with our native type.
719 * If we are TLSv1 and we get SSLv3, we will respond with TLSv1,
720 * This down switching should be handled by a different method.
721 * If we are SSLv3, we will respond with SSLv3, even if prompted with
725 case SSL3_ST_SR_CLNT_HELLO_A:
726 case SSL3_ST_SR_CLNT_HELLO_B:
728 n=s->method->ssl_get_message(s,
729 SSL3_ST_SR_CLNT_HELLO_A,
730 SSL3_ST_SR_CLNT_HELLO_B,
731 SSL3_MT_CLIENT_HELLO,
732 SSL3_RT_MAX_PLAIN_LENGTH,
733 SSL_GET_MESSAGE_HASH_MESSAGE,
736 if (!ok) return((int)n);
739 /* If we require cookies and this ClientHello doesn't
740 * contain one, just return since we do not want to
741 * allocate any memory yet. So check cookie length...
743 if (SSL_IS_DTLS(s) && (SSL_get_options(s) & SSL_OP_COOKIE_EXCHANGE))
746 uint8_t cookie_length;
748 CBS_init(&client_hello, s->init_msg, n);
749 if (!CBS_skip(&client_hello, 2 + SSL3_RANDOM_SIZE) ||
750 !CBS_get_u8_length_prefixed(&client_hello, &session_id) ||
751 !CBS_get_u8(&client_hello, &cookie_length))
753 al = SSL_AD_DECODE_ERROR;
754 OPENSSL_PUT_ERROR(SSL, ssl3_get_client_hello, SSL_R_DECODE_ERROR);
758 if (cookie_length == 0)
761 s->state = SSL3_ST_SR_CLNT_HELLO_C;
763 case SSL3_ST_SR_CLNT_HELLO_C:
764 case SSL3_ST_SR_CLNT_HELLO_D:
765 /* We have previously parsed the ClientHello message,
766 * and can't call ssl_get_message again without hashing
767 * the message into the Finished digest again. */
770 memset(&early_ctx, 0, sizeof(early_ctx));
772 early_ctx.client_hello = s->init_msg;
773 early_ctx.client_hello_len = n;
774 if (!ssl_early_callback_init(&early_ctx))
776 al = SSL_AD_DECODE_ERROR;
777 OPENSSL_PUT_ERROR(SSL, ssl3_get_client_hello, SSL_R_CLIENTHELLO_PARSE_FAILED);
781 if (s->state == SSL3_ST_SR_CLNT_HELLO_C &&
782 s->ctx->select_certificate_cb != NULL)
786 s->state = SSL3_ST_SR_CLNT_HELLO_D;
787 ret = s->ctx->select_certificate_cb(&early_ctx);
789 return CERTIFICATE_SELECTION_PENDING;
792 /* Connection rejected. */
793 al = SSL_AD_ACCESS_DENIED;
794 OPENSSL_PUT_ERROR(SSL, ssl3_get_client_hello, SSL_R_CONNECTION_REJECTED);
798 s->state = SSL3_ST_SR_CLNT_HELLO_D;
801 OPENSSL_PUT_ERROR(SSL, ssl3_get_client_hello, SSL_R_UNKNOWN_STATE);
805 CBS_init(&client_hello, s->init_msg, n);
806 if (!CBS_get_u16(&client_hello, &client_version) ||
807 !CBS_get_bytes(&client_hello, &client_random, SSL3_RANDOM_SIZE) ||
808 !CBS_get_u8_length_prefixed(&client_hello, &session_id) ||
809 CBS_len(&session_id) > SSL_MAX_SSL_SESSION_ID_LENGTH)
811 al = SSL_AD_DECODE_ERROR;
812 OPENSSL_PUT_ERROR(SSL, ssl3_get_client_hello, SSL_R_DECODE_ERROR);
816 /* use version from inside client hello, not from record header
817 * (may differ: see RFC 2246, Appendix E, second paragraph) */
818 s->client_version = client_version;
820 if (SSL_IS_DTLS(s) ? (s->client_version > s->version &&
821 s->method->version != DTLS_ANY_VERSION)
822 : (s->client_version < s->version))
824 OPENSSL_PUT_ERROR(SSL, ssl3_get_client_hello, SSL_R_WRONG_VERSION_NUMBER);
825 if ((s->client_version>>8) == SSL3_VERSION_MAJOR &&
826 !s->enc_write_ctx && !s->write_hash)
828 /* similar to ssl3_get_record, send alert using remote version number */
829 s->version = s->client_version;
831 al = SSL_AD_PROTOCOL_VERSION;
835 /* Load the client random. */
836 memcpy(s->s3->client_random, CBS_data(&client_random), SSL3_RANDOM_SIZE);
839 /* Versions before 0.9.7 always allow clients to resume sessions in renegotiation.
840 * 0.9.7 and later allow this by default, but optionally ignore resumption requests
841 * with flag SSL_OP_NO_SESSION_RESUMPTION_ON_RENEGOTIATION (it's a new flag rather
842 * than a change to default behavior so that applications relying on this for security
843 * won't even compile against older library versions).
845 * 1.0.1 and later also have a function SSL_renegotiate_abbreviated() to request
846 * renegotiation but not a new session (s->new_session remains unset): for servers,
847 * this essentially just means that the SSL_OP_NO_SESSION_RESUMPTION_ON_RENEGOTIATION
848 * setting will be ignored.
850 if ((s->new_session && (s->options & SSL_OP_NO_SESSION_RESUMPTION_ON_RENEGOTIATION)))
852 if (!ssl_get_new_session(s,1))
857 i=ssl_get_prev_session(s, &early_ctx);
859 { /* previous session */
864 else if (i == PENDING_SESSION)
866 ret = PENDING_SESSION;
871 if (!ssl_get_new_session(s,1))
880 /* TODO(davidben): The length check here is off. Per
881 * spec, the maximum cookie length is 32. However, the
882 * DTLS1_COOKIE_LENGTH check is checking against 256,
883 * not 32 (so it's actually redundant).
884 * 07a9d1a2c2b735cbc327065000b545deb5e136cf from
885 * OpenSSL switched this from 32 to 256. */
886 if (!CBS_get_u8_length_prefixed(&client_hello, &cookie) ||
887 CBS_len(&cookie) > DTLS1_COOKIE_LENGTH)
889 al = SSL_AD_DECODE_ERROR;
890 OPENSSL_PUT_ERROR(SSL, ssl3_get_client_hello, SSL_R_DECODE_ERROR);
894 /* Verify the cookie if appropriate option is set. */
895 if ((SSL_get_options(s) & SSL_OP_COOKIE_EXCHANGE) &&
896 CBS_len(&cookie) > 0)
898 if (s->ctx->app_verify_cookie_cb != NULL)
900 if (s->ctx->app_verify_cookie_cb(s,
901 CBS_data(&cookie), CBS_len(&cookie)) == 0)
903 al=SSL_AD_HANDSHAKE_FAILURE;
904 OPENSSL_PUT_ERROR(SSL, ssl3_get_client_hello, SSL_R_COOKIE_MISMATCH);
907 /* else cookie verification succeeded */
909 else if (!CBS_mem_equal(&cookie, s->d1->cookie, s->d1->cookie_len))
911 /* default verification */
912 al=SSL_AD_HANDSHAKE_FAILURE;
913 OPENSSL_PUT_ERROR(SSL, ssl3_get_client_hello, SSL_R_COOKIE_MISMATCH);
916 /* Set to -2 so if successful we return 2 and
917 * don't send HelloVerifyRequest. */
921 if (s->method->version == DTLS_ANY_VERSION)
923 /* Select version to use */
924 if (s->client_version <= DTLS1_2_VERSION &&
925 !(s->options & SSL_OP_NO_DTLSv1_2))
927 s->version = DTLS1_2_VERSION;
928 s->method = DTLSv1_2_server_method();
930 else if (s->client_version <= DTLS1_VERSION &&
931 !(s->options & SSL_OP_NO_DTLSv1))
933 s->version = DTLS1_VERSION;
934 s->method = DTLSv1_server_method();
938 OPENSSL_PUT_ERROR(SSL, ssl3_get_client_hello, SSL_R_WRONG_VERSION_NUMBER);
939 s->version = s->client_version;
940 al = SSL_AD_PROTOCOL_VERSION;
943 s->session->ssl_version = s->version;
947 if (!CBS_get_u16_length_prefixed(&client_hello, &cipher_suites) ||
948 !CBS_get_u8_length_prefixed(&client_hello, &compression_methods) ||
949 CBS_len(&compression_methods) == 0)
951 al = SSL_AD_DECODE_ERROR;
952 OPENSSL_PUT_ERROR(SSL, ssl3_get_client_hello, SSL_R_DECODE_ERROR);
956 /* TODO(davidben): Per spec, cipher_suites can never be empty
957 * (specified at the ClientHello structure level). This logic
958 * allows it to be empty if resuming a session. Can we always
959 * require non-empty? If a client sends empty cipher_suites
960 * because it's resuming a session, it could always fail to
961 * resume a session, so it's unlikely to actually work. */
962 if (CBS_len(&cipher_suites) == 0 && CBS_len(&session_id) != 0)
964 /* We need a cipher if we are not resuming a session. */
965 al = SSL_AD_ILLEGAL_PARAMETER;
966 OPENSSL_PUT_ERROR(SSL, ssl3_get_client_hello, SSL_R_NO_CIPHERS_SPECIFIED);
970 if (ssl_bytes_to_cipher_list(s, &cipher_suites, &ciphers) == NULL)
975 /* If it is a hit, check that the cipher is in the list */
976 if (s->hit && CBS_len(&cipher_suites) > 0)
978 int found_cipher = 0;
979 unsigned long id = s->session->cipher->id;
981 for (i=0; i<sk_SSL_CIPHER_num(ciphers); i++)
983 c=sk_SSL_CIPHER_value(ciphers,i);
992 /* we need to have the cipher in the cipher
993 * list if we are asked to reuse it */
994 al=SSL_AD_ILLEGAL_PARAMETER;
995 OPENSSL_PUT_ERROR(SSL, ssl3_get_client_hello, SSL_R_REQUIRED_CIPHER_MISSING);
1000 /* Only null compression is supported. */
1001 if (memchr(CBS_data(&compression_methods), 0,
1002 CBS_len(&compression_methods)) == NULL)
1004 al = SSL_AD_ILLEGAL_PARAMETER;
1005 OPENSSL_PUT_ERROR(SSL, ssl3_get_client_hello, SSL_R_NO_COMPRESSION_SPECIFIED);
1010 if (s->version >= SSL3_VERSION)
1012 if (!ssl_parse_clienthello_tlsext(s, &client_hello))
1014 OPENSSL_PUT_ERROR(SSL, ssl3_get_client_hello, SSL_R_PARSE_TLSEXT);
1019 /* There should be nothing left over in the record. */
1020 if (CBS_len(&client_hello) != 0)
1022 /* wrong packet length */
1023 al=SSL_AD_DECODE_ERROR;
1024 OPENSSL_PUT_ERROR(SSL, ssl3_get_client_hello, SSL_R_BAD_PACKET_LENGTH);
1028 /* Check if we want to use external pre-shared secret for this
1029 * handshake for not reused session only. We need to generate
1030 * server_random before calling tls_session_secret_cb in order to allow
1031 * SessionTicket processing to use it in key derivation. */
1034 pos=s->s3->server_random;
1035 if (ssl_fill_hello_random(s, 1, pos, SSL3_RANDOM_SIZE) <= 0)
1041 if (!s->hit && s->version >= TLS1_VERSION && s->tls_session_secret_cb)
1043 const SSL_CIPHER *pref_cipher=NULL;
1045 s->session->master_key_length=sizeof(s->session->master_key);
1046 if(s->tls_session_secret_cb(s, s->session->master_key, &s->session->master_key_length,
1047 ciphers, &pref_cipher, s->tls_session_secret_cb_arg))
1050 s->session->ciphers=ciphers;
1051 s->session->verify_result=X509_V_OK;
1055 /* check if some cipher was preferred by call back */
1056 pref_cipher=pref_cipher ? pref_cipher : ssl3_choose_cipher(s, s->session->ciphers, ssl_get_cipher_preferences(s));
1057 if (pref_cipher == NULL)
1059 al=SSL_AD_HANDSHAKE_FAILURE;
1060 OPENSSL_PUT_ERROR(SSL, ssl3_get_client_hello, SSL_R_NO_SHARED_CIPHER);
1064 s->session->cipher=pref_cipher;
1067 ssl_cipher_preference_list_free(s->cipher_list);
1069 if (s->cipher_list_by_id)
1070 sk_SSL_CIPHER_free(s->cipher_list_by_id);
1072 s->cipher_list = ssl_cipher_preference_list_from_ciphers(s->session->ciphers);
1073 s->cipher_list_by_id = sk_SSL_CIPHER_dup(s->session->ciphers);
1077 /* Given s->session->ciphers and SSL_get_ciphers, we must
1082 if (s->session->ciphers != NULL)
1083 sk_SSL_CIPHER_free(s->session->ciphers);
1084 s->session->ciphers=ciphers;
1085 if (ciphers == NULL)
1087 al=SSL_AD_ILLEGAL_PARAMETER;
1088 OPENSSL_PUT_ERROR(SSL, ssl3_get_client_hello, SSL_R_NO_CIPHERS_PASSED);
1092 /* Let cert callback update server certificates if required */
1093 if (s->cert->cert_cb)
1095 int rv = s->cert->cert_cb(s, s->cert->cert_cb_arg);
1098 al=SSL_AD_INTERNAL_ERROR;
1099 OPENSSL_PUT_ERROR(SSL, ssl3_get_client_hello, SSL_R_CERT_CB_ERROR);
1104 s->rwstate=SSL_X509_LOOKUP;
1107 s->rwstate = SSL_NOTHING;
1109 c=ssl3_choose_cipher(s,s->session->ciphers,
1110 ssl_get_cipher_preferences(s));
1114 al=SSL_AD_HANDSHAKE_FAILURE;
1115 OPENSSL_PUT_ERROR(SSL, ssl3_get_client_hello, SSL_R_NO_SHARED_CIPHER);
1118 s->s3->tmp.new_cipher=c;
1122 /* Session-id reuse */
1123 s->s3->tmp.new_cipher=s->session->cipher;
1126 if (!SSL_USE_SIGALGS(s) || !(s->verify_mode & SSL_VERIFY_PEER))
1128 if (!ssl3_digest_cached_records(s))
1132 /* we now have the following setup.
1134 * cipher_list - our prefered list of ciphers
1135 * ciphers - the clients prefered list of ciphers
1136 * compression - basically ignored right now
1137 * ssl version is set - sslv3
1138 * s->session - The ssl session has been setup.
1139 * s->hit - session reuse flag
1140 * s->tmp.new_cipher - the new cipher to use.
1143 if (ret < 0) ret=-ret;
1147 ssl3_send_alert(s,SSL3_AL_FATAL,al);
1150 if (ciphers != NULL) sk_SSL_CIPHER_free(ciphers);
1154 int ssl3_send_server_hello(SSL *s)
1157 unsigned char *p,*d;
1161 if (s->state == SSL3_ST_SW_SRVR_HELLO_A)
1163 /* We only accept ChannelIDs on connections with ECDHE in order
1164 * to avoid a known attack while we fix ChannelID itself. */
1166 s->s3->tlsext_channel_id_valid &&
1167 (s->s3->tmp.new_cipher->algorithm_mkey & SSL_kEECDH) == 0)
1168 s->s3->tlsext_channel_id_valid = 0;
1170 /* If this is a resumption and the original handshake didn't
1171 * support ChannelID then we didn't record the original
1172 * handshake hashes in the session and so cannot resume with
1175 s->s3->tlsext_channel_id_new &&
1176 s->session->original_handshake_hash_len == 0)
1177 s->s3->tlsext_channel_id_valid = 0;
1179 if (s->mode & SSL_MODE_RELEASE_BUFFERS)
1181 /* Free s->session->ciphers in order to release memory. This
1182 * breaks SSL_get_shared_ciphers(), but many servers will
1183 * prefer the memory savings. */
1184 sk_SSL_CIPHER_free(s->session->ciphers);
1185 s->session->ciphers = NULL;
1188 buf=(unsigned char *)s->init_buf->data;
1189 /* Do the message type and length last */
1190 d=p= ssl_handshake_start(s);
1192 *(p++)=s->version>>8;
1193 *(p++)=s->version&0xff;
1196 memcpy(p,s->s3->server_random,SSL3_RANDOM_SIZE);
1197 p+=SSL3_RANDOM_SIZE;
1199 /* There are several cases for the session ID to send
1200 * back in the server hello:
1201 * - For session reuse from the session cache,
1202 * we send back the old session ID.
1203 * - If stateless session reuse (using a session ticket)
1204 * is successful, we send back the client's "session ID"
1205 * (which doesn't actually identify the session).
1206 * - If it is a new session, we send back the new
1208 * - However, if we want the new session to be single-use,
1209 * we send back a 0-length session ID.
1210 * s->hit is non-zero in either case of session reuse,
1211 * so the following won't overwrite an ID that we're supposed
1214 if (!(s->ctx->session_cache_mode & SSL_SESS_CACHE_SERVER)
1216 s->session->session_id_length=0;
1218 sl=s->session->session_id_length;
1219 if (sl > (int)sizeof(s->session->session_id))
1221 OPENSSL_PUT_ERROR(SSL, ssl3_send_server_hello, ERR_R_INTERNAL_ERROR);
1225 memcpy(p,s->session->session_id,sl);
1228 /* put the cipher */
1229 s2n(ssl3_get_cipher_value(s->s3->tmp.new_cipher), p);
1231 /* put the compression method */
1233 if (ssl_prepare_serverhello_tlsext(s) <= 0)
1235 OPENSSL_PUT_ERROR(SSL, ssl3_send_server_hello, SSL_R_SERVERHELLO_TLSEXT);
1238 if ((p = ssl_add_serverhello_tlsext(s, p, buf+SSL3_RT_MAX_PLAIN_LENGTH)) == NULL)
1240 OPENSSL_PUT_ERROR(SSL, ssl3_send_server_hello, ERR_R_INTERNAL_ERROR);
1245 ssl_set_handshake_header(s, SSL3_MT_SERVER_HELLO, l);
1246 s->state=SSL3_ST_SW_SRVR_HELLO_B;
1249 /* SSL3_ST_SW_SRVR_HELLO_B */
1250 return ssl_do_write(s);
1253 int ssl3_send_server_done(SSL *s)
1256 if (s->state == SSL3_ST_SW_SRVR_DONE_A)
1258 ssl_set_handshake_header(s, SSL3_MT_SERVER_DONE, 0);
1259 s->state = SSL3_ST_SW_SRVR_DONE_B;
1262 /* SSL3_ST_SW_SRVR_DONE_B */
1263 return ssl_do_write(s);
1266 int ssl3_send_server_key_exchange(SSL *s)
1270 unsigned char md_buf[MD5_DIGEST_LENGTH+SHA_DIGEST_LENGTH];
1273 EC_KEY *ecdh=NULL, *ecdhp;
1274 unsigned char *encodedPoint = NULL;
1277 BN_CTX *bn_ctx = NULL;
1278 const char* psk_identity_hint = NULL;
1279 size_t psk_identity_hint_len = 0;
1281 const EVP_MD *md = NULL;
1282 unsigned char *p,*d;
1284 unsigned long alg_k;
1285 unsigned long alg_a;
1293 EVP_MD_CTX_init(&md_ctx);
1294 if (s->state == SSL3_ST_SW_KEY_EXCH_A)
1296 alg_k=s->s3->tmp.new_cipher->algorithm_mkey;
1297 alg_a=s->s3->tmp.new_cipher->algorithm_auth;
1302 r[0]=r[1]=r[2]=r[3]=NULL;
1304 if (alg_a & SSL_aPSK)
1306 /* size for PSK identity hint */
1307 psk_identity_hint = s->session->psk_identity_hint;
1308 if (psk_identity_hint)
1309 psk_identity_hint_len = strlen(psk_identity_hint);
1311 psk_identity_hint_len = 0;
1312 n+=2+psk_identity_hint_len;
1314 if (alg_k & SSL_kEDH)
1317 if ((dhp == NULL) && (s->cert->dh_tmp_cb != NULL))
1318 dhp=s->cert->dh_tmp_cb(s, 0, 1024);
1321 al=SSL_AD_HANDSHAKE_FAILURE;
1322 OPENSSL_PUT_ERROR(SSL, ssl3_send_server_key_exchange, SSL_R_MISSING_TMP_DH_KEY);
1326 if (s->s3->tmp.dh != NULL)
1328 OPENSSL_PUT_ERROR(SSL, ssl3_send_server_key_exchange, ERR_R_INTERNAL_ERROR);
1332 if ((dh=DHparams_dup(dhp)) == NULL)
1334 OPENSSL_PUT_ERROR(SSL, ssl3_send_server_key_exchange, ERR_R_DH_LIB);
1339 if ((dhp->pub_key == NULL ||
1340 dhp->priv_key == NULL ||
1341 (s->options & SSL_OP_SINGLE_DH_USE)))
1343 if(!DH_generate_key(dh))
1345 OPENSSL_PUT_ERROR(SSL, ssl3_send_server_key_exchange, ERR_R_DH_LIB);
1351 dh->pub_key=BN_dup(dhp->pub_key);
1352 dh->priv_key=BN_dup(dhp->priv_key);
1353 if ((dh->pub_key == NULL) ||
1354 (dh->priv_key == NULL))
1356 OPENSSL_PUT_ERROR(SSL, ssl3_send_server_key_exchange, ERR_R_DH_LIB);
1365 if (alg_k & SSL_kEECDH)
1367 const EC_GROUP *group;
1369 ecdhp=cert->ecdh_tmp;
1370 if (s->cert->ecdh_tmp_auto)
1372 /* Get NID of appropriate shared curve */
1373 int nid = tls1_get_shared_curve(s);
1374 if (nid != NID_undef)
1375 ecdhp = EC_KEY_new_by_curve_name(nid);
1377 else if ((ecdhp == NULL) && s->cert->ecdh_tmp_cb)
1379 ecdhp = s->cert->ecdh_tmp_cb(s, 0, 1024);
1383 al=SSL_AD_HANDSHAKE_FAILURE;
1384 OPENSSL_PUT_ERROR(SSL, ssl3_send_server_key_exchange, SSL_R_MISSING_TMP_ECDH_KEY);
1388 if (s->s3->tmp.ecdh != NULL)
1390 OPENSSL_PUT_ERROR(SSL, ssl3_send_server_key_exchange, ERR_R_INTERNAL_ERROR);
1394 /* Duplicate the ECDH structure. */
1397 OPENSSL_PUT_ERROR(SSL, ssl3_send_server_key_exchange, ERR_R_ECDH_LIB);
1400 if (s->cert->ecdh_tmp_auto)
1402 else if ((ecdh = EC_KEY_dup(ecdhp)) == NULL)
1404 OPENSSL_PUT_ERROR(SSL, ssl3_send_server_key_exchange, ERR_R_ECDH_LIB);
1408 s->s3->tmp.ecdh=ecdh;
1409 if ((EC_KEY_get0_public_key(ecdh) == NULL) ||
1410 (EC_KEY_get0_private_key(ecdh) == NULL) ||
1411 (s->options & SSL_OP_SINGLE_ECDH_USE))
1413 if(!EC_KEY_generate_key(ecdh))
1415 OPENSSL_PUT_ERROR(SSL, ssl3_send_server_key_exchange, ERR_R_ECDH_LIB);
1420 if (((group = EC_KEY_get0_group(ecdh)) == NULL) ||
1421 (EC_KEY_get0_public_key(ecdh) == NULL) ||
1422 (EC_KEY_get0_private_key(ecdh) == NULL))
1424 OPENSSL_PUT_ERROR(SSL, ssl3_send_server_key_exchange, ERR_R_ECDH_LIB);
1428 /* XXX: For now, we only support ephemeral ECDH
1429 * keys over named (not generic) curves. For
1430 * supported named curves, curve_id is non-zero.
1433 tls1_ec_nid2curve_id(EC_GROUP_get_curve_name(group)))
1436 OPENSSL_PUT_ERROR(SSL, ssl3_send_server_key_exchange, SSL_R_UNSUPPORTED_ELLIPTIC_CURVE);
1440 /* Encode the public key.
1441 * First check the size of encoding and
1442 * allocate memory accordingly.
1444 encodedlen = EC_POINT_point2oct(group,
1445 EC_KEY_get0_public_key(ecdh),
1446 POINT_CONVERSION_UNCOMPRESSED,
1449 encodedPoint = (unsigned char *)
1450 OPENSSL_malloc(encodedlen*sizeof(unsigned char));
1451 bn_ctx = BN_CTX_new();
1452 if ((encodedPoint == NULL) || (bn_ctx == NULL))
1454 OPENSSL_PUT_ERROR(SSL, ssl3_send_server_key_exchange, ERR_R_MALLOC_FAILURE);
1459 encodedlen = EC_POINT_point2oct(group,
1460 EC_KEY_get0_public_key(ecdh),
1461 POINT_CONVERSION_UNCOMPRESSED,
1462 encodedPoint, encodedlen, bn_ctx);
1464 if (encodedlen == 0)
1466 OPENSSL_PUT_ERROR(SSL, ssl3_send_server_key_exchange, ERR_R_ECDH_LIB);
1470 BN_CTX_free(bn_ctx); bn_ctx=NULL;
1472 /* XXX: For now, we only support named (not
1473 * generic) curves in ECDH ephemeral key exchanges.
1474 * In this situation, we need four additional bytes
1475 * to encode the entire ServerECDHParams
1478 n += 4 + encodedlen;
1480 /* We'll generate the serverKeyExchange message
1481 * explicitly so we can set these to NULLs
1489 if (!(alg_k & SSL_kPSK))
1491 al=SSL_AD_HANDSHAKE_FAILURE;
1492 OPENSSL_PUT_ERROR(SSL, ssl3_send_server_key_exchange, SSL_R_UNKNOWN_KEY_EXCHANGE_TYPE);
1495 for (i=0; i < 4 && r[i] != NULL; i++)
1497 nr[i]=BN_num_bytes(r[i]);
1501 if (ssl_cipher_has_server_public_key(s->s3->tmp.new_cipher))
1503 if ((pkey=ssl_get_sign_pkey(s,s->s3->tmp.new_cipher,&md))
1506 al=SSL_AD_DECODE_ERROR;
1509 kn=EVP_PKEY_size(pkey);
1517 if (!BUF_MEM_grow_clean(buf,n+SSL_HM_HEADER_LENGTH(s)+kn))
1519 OPENSSL_PUT_ERROR(SSL, ssl3_send_server_key_exchange, ERR_LIB_BUF);
1522 d = p = ssl_handshake_start(s);
1524 for (i=0; i < 4 && r[i] != NULL; i++)
1531 /* Note: ECDHE PSK ciphersuites use SSL_kEECDH and SSL_aPSK.
1532 * When one of them is used, the server key exchange record needs to have both
1533 * the psk_identity_hint and the ServerECDHParams. */
1534 if (alg_a & SSL_aPSK)
1536 /* copy PSK identity hint (if provided) */
1537 s2n(psk_identity_hint_len, p);
1538 if (psk_identity_hint_len > 0)
1540 memcpy(p, psk_identity_hint, psk_identity_hint_len);
1541 p+=psk_identity_hint_len;
1545 if (alg_k & SSL_kEECDH)
1547 /* XXX: For now, we only support named (not generic) curves.
1548 * In this situation, the serverKeyExchange message has:
1549 * [1 byte CurveType], [2 byte CurveName]
1550 * [1 byte length of encoded point], followed by
1551 * the actual encoded point itself
1553 *p = NAMED_CURVE_TYPE;
1561 memcpy((unsigned char*)p,
1562 (unsigned char *)encodedPoint,
1564 OPENSSL_free(encodedPoint);
1565 encodedPoint = NULL;
1572 /* n is the length of the params, they start at &(d[4])
1573 * and p points to the space at the end. */
1574 if (pkey->type == EVP_PKEY_RSA && !SSL_USE_SIGALGS(s))
1578 for (num=2; num > 0; num--)
1580 EVP_DigestInit_ex(&md_ctx,
1581 (num == 2) ? EVP_md5() : EVP_sha1(), NULL);
1582 EVP_DigestUpdate(&md_ctx,&(s->s3->client_random[0]),SSL3_RANDOM_SIZE);
1583 EVP_DigestUpdate(&md_ctx,&(s->s3->server_random[0]),SSL3_RANDOM_SIZE);
1584 EVP_DigestUpdate(&md_ctx,d,n);
1585 EVP_DigestFinal_ex(&md_ctx,q,
1586 (unsigned int *)&i);
1590 if (RSA_sign(NID_md5_sha1, md_buf, j,
1591 &(p[2]), &u, pkey->pkey.rsa) <= 0)
1593 OPENSSL_PUT_ERROR(SSL, ssl3_send_server_key_exchange, ERR_LIB_RSA);
1602 /* send signature algorithm */
1603 if (SSL_USE_SIGALGS(s))
1605 if (!tls12_get_sigandhash(p, pkey, md))
1607 /* Should never happen */
1608 al=SSL_AD_INTERNAL_ERROR;
1609 OPENSSL_PUT_ERROR(SSL, ssl3_send_server_key_exchange, ERR_R_INTERNAL_ERROR);
1615 fprintf(stderr, "Using hash %s\n",
1618 EVP_SignInit_ex(&md_ctx, md, NULL);
1619 EVP_SignUpdate(&md_ctx,&(s->s3->client_random[0]),SSL3_RANDOM_SIZE);
1620 EVP_SignUpdate(&md_ctx,&(s->s3->server_random[0]),SSL3_RANDOM_SIZE);
1621 EVP_SignUpdate(&md_ctx,d,n);
1622 if (!EVP_SignFinal(&md_ctx,&(p[2]),
1623 (unsigned int *)&i,pkey))
1625 OPENSSL_PUT_ERROR(SSL, ssl3_send_server_key_exchange, ERR_LIB_EVP);
1630 if (SSL_USE_SIGALGS(s))
1635 /* Is this error check actually needed? */
1636 al=SSL_AD_HANDSHAKE_FAILURE;
1637 OPENSSL_PUT_ERROR(SSL, ssl3_send_server_key_exchange, SSL_R_UNKNOWN_PKEY_TYPE);
1642 ssl_set_handshake_header(s, SSL3_MT_SERVER_KEY_EXCHANGE, n);
1645 s->state = SSL3_ST_SW_KEY_EXCH_B;
1646 EVP_MD_CTX_cleanup(&md_ctx);
1647 return ssl_do_write(s);
1649 ssl3_send_alert(s,SSL3_AL_FATAL,al);
1651 if (encodedPoint != NULL) OPENSSL_free(encodedPoint);
1652 BN_CTX_free(bn_ctx);
1653 EVP_MD_CTX_cleanup(&md_ctx);
1657 int ssl3_send_certificate_request(SSL *s)
1659 unsigned char *p,*d;
1661 STACK_OF(X509_NAME) *sk=NULL;
1665 if (s->state == SSL3_ST_SW_CERT_REQ_A)
1669 d=p=ssl_handshake_start(s);
1671 /* get the list of acceptable cert types */
1673 n=ssl3_get_req_cert_type(s,p);
1678 if (SSL_USE_SIGALGS(s))
1680 const unsigned char *psigs;
1681 nl = tls12_get_psigalgs(s, &psigs);
1683 memcpy(p, psigs, nl);
1692 sk=SSL_get_client_CA_list(s);
1696 for (i=0; i<sk_X509_NAME_num(sk); i++)
1698 name=sk_X509_NAME_value(sk,i);
1699 j=i2d_X509_NAME(name,NULL);
1700 if (!BUF_MEM_grow_clean(buf,SSL_HM_HEADER_LENGTH(s)+n+j+2))
1702 OPENSSL_PUT_ERROR(SSL, ssl3_send_certificate_request, ERR_R_BUF_LIB);
1705 p = ssl_handshake_start(s) + n;
1707 i2d_X509_NAME(name,&p);
1712 /* else no CA names */
1713 p = ssl_handshake_start(s) + off;
1716 ssl_set_handshake_header(s, SSL3_MT_CERTIFICATE_REQUEST, n);
1718 #ifdef NETSCAPE_HANG_BUG
1719 if (!SSL_IS_DTLS(s))
1721 if (!BUF_MEM_grow_clean(buf, s->init_num + 4))
1723 OPENSSL_PUT_ERROR(SSL, ssl3_send_certificate_request, ERR_R_BUF_LIB);
1726 p=(unsigned char *)s->init_buf->data + s->init_num;
1728 *(p++)=SSL3_MT_SERVER_DONE;
1736 s->state = SSL3_ST_SW_CERT_REQ_B;
1739 /* SSL3_ST_SW_CERT_REQ_B */
1740 return ssl_do_write(s);
1745 int ssl3_get_client_key_exchange(SSL *s)
1749 CBS client_key_exchange;
1750 unsigned long alg_k;
1751 unsigned long alg_a;
1752 uint8_t *premaster_secret = NULL;
1753 size_t premaster_secret_len = 0;
1755 uint8_t *decrypt_buf = NULL;
1756 EVP_PKEY *pkey=NULL;
1760 EC_KEY *srvr_ecdh = NULL;
1761 EVP_PKEY *clnt_pub_pkey = NULL;
1762 EC_POINT *clnt_ecpoint = NULL;
1763 BN_CTX *bn_ctx = NULL;
1764 unsigned int psk_len = 0;
1765 unsigned char psk[PSK_MAX_PSK_LEN];
1767 n=s->method->ssl_get_message(s,
1768 SSL3_ST_SR_KEY_EXCH_A,
1769 SSL3_ST_SR_KEY_EXCH_B,
1770 SSL3_MT_CLIENT_KEY_EXCHANGE,
1772 SSL_GET_MESSAGE_HASH_MESSAGE,
1775 if (!ok) return((int)n);
1776 CBS_init(&client_key_exchange, s->init_msg, n);
1778 alg_k=s->s3->tmp.new_cipher->algorithm_mkey;
1779 alg_a=s->s3->tmp.new_cipher->algorithm_auth;
1781 /* If using a PSK key exchange, prepare the pre-shared key. */
1782 if (alg_a & SSL_aPSK)
1786 /* If using PSK, the ClientKeyExchange contains a
1787 * psk_identity. If PSK, then this is the only field
1788 * in the message. */
1789 if (!CBS_get_u16_length_prefixed(&client_key_exchange, &psk_identity) ||
1790 ((alg_k & SSL_kPSK) && CBS_len(&client_key_exchange) != 0))
1792 OPENSSL_PUT_ERROR(SSL, ssl3_get_client_key_exchange, SSL_R_DECODE_ERROR);
1793 al = SSL_AD_DECODE_ERROR;
1797 if (s->psk_server_callback == NULL)
1799 OPENSSL_PUT_ERROR(SSL, ssl3_get_client_key_exchange, SSL_R_PSK_NO_SERVER_CB);
1800 al = SSL_AD_INTERNAL_ERROR;
1804 if (CBS_len(&psk_identity) > PSK_MAX_IDENTITY_LEN ||
1805 CBS_contains_zero_byte(&psk_identity))
1807 OPENSSL_PUT_ERROR(SSL, ssl3_get_client_key_exchange, SSL_R_DATA_LENGTH_TOO_LONG);
1808 al = SSL_AD_ILLEGAL_PARAMETER;
1812 if (!CBS_strdup(&psk_identity, &s->session->psk_identity))
1814 al = SSL_AD_INTERNAL_ERROR;
1815 OPENSSL_PUT_ERROR(SSL, ssl3_get_client_key_exchange, ERR_R_MALLOC_FAILURE);
1819 /* Look up the key for the identity. */
1820 psk_len = s->psk_server_callback(s, s->session->psk_identity, psk, sizeof(psk));
1821 if (psk_len > PSK_MAX_PSK_LEN)
1823 OPENSSL_PUT_ERROR(SSL, ssl3_get_client_key_exchange, ERR_R_INTERNAL_ERROR);
1824 al = SSL_AD_INTERNAL_ERROR;
1827 else if (psk_len == 0)
1829 /* PSK related to the given identity not found */
1830 OPENSSL_PUT_ERROR(SSL, ssl3_get_client_key_exchange, SSL_R_PSK_IDENTITY_NOT_FOUND);
1831 al = SSL_AD_UNKNOWN_PSK_IDENTITY;
1836 /* Depending on the key exchange method, compute |premaster_secret| and
1837 * |premaster_secret_len|. */
1838 if (alg_k & SSL_kRSA)
1840 CBS encrypted_premaster_secret;
1841 uint8_t rand_premaster_secret[SSL_MAX_MASTER_KEY_LENGTH];
1842 int decrypt_good_mask;
1843 uint8_t version_good;
1844 size_t rsa_size, decrypt_len, premaster_index, j;
1846 pkey=s->cert->pkeys[SSL_PKEY_RSA_ENC].privatekey;
1847 if ( (pkey == NULL) ||
1848 (pkey->type != EVP_PKEY_RSA) ||
1849 (pkey->pkey.rsa == NULL))
1851 al=SSL_AD_HANDSHAKE_FAILURE;
1852 OPENSSL_PUT_ERROR(SSL, ssl3_get_client_key_exchange, SSL_R_MISSING_RSA_CERTIFICATE);
1857 /* TLS and [incidentally] DTLS{0xFEFF} */
1858 if (s->version > SSL3_VERSION)
1860 CBS copy = client_key_exchange;
1861 if (!CBS_get_u16_length_prefixed(&client_key_exchange,
1862 &encrypted_premaster_secret) ||
1863 CBS_len(&client_key_exchange) != 0)
1865 if (!(s->options & SSL_OP_TLS_D5_BUG))
1867 al = SSL_AD_DECODE_ERROR;
1868 OPENSSL_PUT_ERROR(SSL, ssl3_get_client_key_exchange, SSL_R_TLS_RSA_ENCRYPTED_VALUE_LENGTH_IS_WRONG);
1872 encrypted_premaster_secret = copy;
1876 encrypted_premaster_secret = client_key_exchange;
1878 /* Reject overly short RSA keys because we want to be sure that
1879 * the buffer size makes it safe to iterate over the entire size
1880 * of a premaster secret (SSL_MAX_MASTER_KEY_LENGTH). The actual
1881 * expected size is larger due to RSA padding, but the bound is
1882 * sufficient to be safe. */
1883 rsa_size = RSA_size(rsa);
1884 if (rsa_size < SSL_MAX_MASTER_KEY_LENGTH)
1886 al = SSL_AD_DECRYPT_ERROR;
1887 OPENSSL_PUT_ERROR(SSL, ssl3_get_client_key_exchange, SSL_R_DECRYPTION_FAILED);
1891 /* We must not leak whether a decryption failure occurs because
1892 * of Bleichenbacher's attack on PKCS #1 v1.5 RSA padding (see
1893 * RFC 2246, section 7.4.7.1). The code follows that advice of
1894 * the TLS RFC and generates a random premaster secret for the
1895 * case that the decrypt fails. See
1896 * https://tools.ietf.org/html/rfc5246#section-7.4.7.1 */
1897 if (RAND_pseudo_bytes(rand_premaster_secret,
1898 sizeof(rand_premaster_secret)) <= 0)
1901 /* Allocate a buffer large enough for an RSA decryption. */
1902 decrypt_buf = OPENSSL_malloc(rsa_size);
1903 if (decrypt_buf == NULL)
1905 OPENSSL_PUT_ERROR(SSL, ssl3_get_client_key_exchange, ERR_R_MALLOC_FAILURE);
1909 /* Decrypt with no padding. PKCS#1 padding will be removed as
1910 * part of the timing-sensitive code below. */
1911 if (!RSA_decrypt(rsa, &decrypt_len, decrypt_buf, rsa_size,
1912 CBS_data(&encrypted_premaster_secret),
1913 CBS_len(&encrypted_premaster_secret),
1918 if (decrypt_len != rsa_size)
1920 /* This should never happen, but do a check so we do not
1921 * read uninitialized memory. */
1922 OPENSSL_PUT_ERROR(SSL, ssl3_get_client_key_exchange, ERR_R_INTERNAL_ERROR);
1926 /* Remove the PKCS#1 padding and adjust decrypt_len as
1927 * appropriate. decrypt_good_mask will be zero if the premaster
1928 * if good and non-zero otherwise. */
1929 decrypt_good_mask = RSA_message_index_PKCS1_type_2(
1930 decrypt_buf, decrypt_len, &premaster_index);
1931 decrypt_good_mask--;
1932 decrypt_len = decrypt_len - premaster_index;
1934 /* decrypt_len should be SSL_MAX_MASTER_KEY_LENGTH. */
1935 decrypt_good_mask |= decrypt_len ^ SSL_MAX_MASTER_KEY_LENGTH;
1937 /* Copy over the unpadded premaster. Whatever the value of
1938 * |decrypt_good_mask|, copy as if the premaster were the right
1939 * length. It is important the memory access pattern be
1941 premaster_secret = BUF_memdup(
1942 decrypt_buf + (rsa_size - SSL_MAX_MASTER_KEY_LENGTH),
1943 SSL_MAX_MASTER_KEY_LENGTH);
1944 if (premaster_secret == NULL)
1946 OPENSSL_PUT_ERROR(SSL, ssl3_get_client_key_exchange, ERR_R_MALLOC_FAILURE);
1949 OPENSSL_free(decrypt_buf);
1952 /* If the version in the decrypted pre-master secret is correct
1953 * then version_good will be zero. The Klima-Pokorny-Rosa
1954 * extension of Bleichenbacher's attack
1955 * (http://eprint.iacr.org/2003/052/) exploits the version
1956 * number check as a "bad version oracle". Thus version checks
1957 * are done in constant time and are treated like any other
1958 * decryption error. */
1959 version_good = premaster_secret[0] ^ (s->client_version>>8);
1960 version_good |= premaster_secret[1] ^ (s->client_version&0xff);
1962 /* If any bits in version_good are set then they'll poision
1963 * decrypt_good_mask and cause rand_premaster_secret to be
1965 decrypt_good_mask |= version_good;
1967 /* decrypt_good_mask will be zero iff decrypt_len ==
1968 * SSL_MAX_MASTER_KEY_LENGTH and the version check passed. We
1969 * fold the bottom 32 bits of it with an OR so that the LSB
1970 * will be zero iff everything is good. This assumes that we'll
1971 * never decrypt a value > 2**31 bytes, which seems safe. */
1972 decrypt_good_mask |= decrypt_good_mask >> 16;
1973 decrypt_good_mask |= decrypt_good_mask >> 8;
1974 decrypt_good_mask |= decrypt_good_mask >> 4;
1975 decrypt_good_mask |= decrypt_good_mask >> 2;
1976 decrypt_good_mask |= decrypt_good_mask >> 1;
1977 /* Now select only the LSB and subtract one. If decrypt_len ==
1978 * SSL_MAX_MASTER_KEY_LENGTH and the version check passed then
1979 * decrypt_good_mask will be all ones. Otherwise it'll be all
1981 decrypt_good_mask &= 1;
1982 decrypt_good_mask--;
1984 /* Now copy rand_premaster_secret over premaster_secret using
1985 * decrypt_good_mask. */
1986 for (j = 0; j < sizeof(rand_premaster_secret); j++)
1988 premaster_secret[j] = (premaster_secret[j] & decrypt_good_mask) |
1989 (rand_premaster_secret[j] & ~decrypt_good_mask);
1992 premaster_secret_len = sizeof(rand_premaster_secret);
1994 else if (alg_k & SSL_kEDH)
1999 if (!CBS_get_u16_length_prefixed(&client_key_exchange, &dh_Yc) ||
2000 CBS_len(&dh_Yc) == 0 ||
2001 CBS_len(&client_key_exchange) != 0)
2003 OPENSSL_PUT_ERROR(SSL, ssl3_get_client_key_exchange, SSL_R_DH_PUBLIC_VALUE_LENGTH_IS_WRONG);
2004 al = SSL_R_DECODE_ERROR;
2008 if (s->s3->tmp.dh == NULL)
2010 al=SSL_AD_HANDSHAKE_FAILURE;
2011 OPENSSL_PUT_ERROR(SSL, ssl3_get_client_key_exchange, SSL_R_MISSING_TMP_DH_KEY);
2014 dh_srvr=s->s3->tmp.dh;
2016 pub = BN_bin2bn(CBS_data(&dh_Yc), CBS_len(&dh_Yc), NULL);
2019 OPENSSL_PUT_ERROR(SSL, ssl3_get_client_key_exchange, SSL_R_BN_LIB);
2023 /* Allocate a buffer for the premaster secret. */
2024 premaster_secret = OPENSSL_malloc(DH_size(dh_srvr));
2025 if (premaster_secret == NULL)
2027 OPENSSL_PUT_ERROR(SSL, ssl3_get_client_key_exchange, ERR_R_MALLOC_FAILURE);
2031 dh_len = DH_compute_key(premaster_secret, pub, dh_srvr);
2034 OPENSSL_PUT_ERROR(SSL, ssl3_get_client_key_exchange, ERR_R_DH_LIB);
2039 DH_free(s->s3->tmp.dh);
2044 premaster_secret_len = dh_len;
2047 else if (alg_k & SSL_kEECDH)
2049 int field_size = 0, ecdh_len;
2051 const EC_GROUP *group;
2052 const BIGNUM *priv_key;
2055 /* initialize structures for server's ECDH key pair */
2056 if ((srvr_ecdh = EC_KEY_new()) == NULL)
2058 OPENSSL_PUT_ERROR(SSL, ssl3_get_client_key_exchange, ERR_R_MALLOC_FAILURE);
2062 /* Use the ephermeral values we saved when generating the
2063 * ServerKeyExchange msg. */
2064 tkey = s->s3->tmp.ecdh;
2066 group = EC_KEY_get0_group(tkey);
2067 priv_key = EC_KEY_get0_private_key(tkey);
2069 if (!EC_KEY_set_group(srvr_ecdh, group) ||
2070 !EC_KEY_set_private_key(srvr_ecdh, priv_key))
2072 OPENSSL_PUT_ERROR(SSL, ssl3_get_client_key_exchange, ERR_R_EC_LIB);
2076 /* Let's get client's public key */
2077 if ((clnt_ecpoint = EC_POINT_new(group)) == NULL)
2079 OPENSSL_PUT_ERROR(SSL, ssl3_get_client_key_exchange, ERR_R_MALLOC_FAILURE);
2083 /* Get client's public key from encoded point
2084 * in the ClientKeyExchange message.
2086 if (!CBS_get_u8_length_prefixed(&client_key_exchange, &ecdh_Yc) ||
2087 CBS_len(&client_key_exchange) != 0)
2089 al = SSL_AD_DECODE_ERROR;
2090 OPENSSL_PUT_ERROR(SSL, ssl3_get_client_key_exchange, SSL_R_DECODE_ERROR);
2094 if ((bn_ctx = BN_CTX_new()) == NULL)
2096 OPENSSL_PUT_ERROR(SSL, ssl3_get_client_key_exchange, ERR_R_MALLOC_FAILURE);
2100 if (!EC_POINT_oct2point(group, clnt_ecpoint,
2101 CBS_data(&ecdh_Yc), CBS_len(&ecdh_Yc), bn_ctx))
2103 OPENSSL_PUT_ERROR(SSL, ssl3_get_client_key_exchange, ERR_R_EC_LIB);
2107 /* Allocate a buffer for both the secret and the PSK. */
2108 field_size = EC_GROUP_get_degree(group);
2109 if (field_size <= 0)
2111 OPENSSL_PUT_ERROR(SSL, ssl3_get_client_key_exchange, ERR_R_ECDH_LIB);
2115 ecdh_len = (field_size + 7) / 8;
2116 premaster_secret = OPENSSL_malloc(ecdh_len);
2117 if (premaster_secret == NULL)
2119 OPENSSL_PUT_ERROR(SSL, ssl3_get_client_key_exchange, ERR_R_MALLOC_FAILURE);
2123 /* Compute the shared pre-master secret */
2124 ecdh_len = ECDH_compute_key(premaster_secret,
2125 ecdh_len, clnt_ecpoint, srvr_ecdh, NULL);
2128 OPENSSL_PUT_ERROR(SSL, ssl3_get_client_key_exchange, ERR_R_ECDH_LIB);
2132 EVP_PKEY_free(clnt_pub_pkey);
2133 EC_POINT_free(clnt_ecpoint);
2134 EC_KEY_free(srvr_ecdh);
2135 BN_CTX_free(bn_ctx);
2136 EC_KEY_free(s->s3->tmp.ecdh);
2137 s->s3->tmp.ecdh = NULL;
2139 premaster_secret_len = ecdh_len;
2141 else if (alg_k & SSL_kPSK)
2143 /* For plain PSK, other_secret is a block of 0s with the same
2144 * length as the pre-shared key. */
2145 premaster_secret_len = psk_len;
2146 premaster_secret = OPENSSL_malloc(premaster_secret_len);
2147 if (premaster_secret == NULL)
2149 OPENSSL_PUT_ERROR(SSL, ssl3_get_client_key_exchange, ERR_R_MALLOC_FAILURE);
2152 memset(premaster_secret, 0, premaster_secret_len);
2156 al=SSL_AD_HANDSHAKE_FAILURE;
2157 OPENSSL_PUT_ERROR(SSL, ssl3_get_client_key_exchange, SSL_R_UNKNOWN_CIPHER_TYPE);
2161 /* For a PSK cipher suite, the actual pre-master secret is combined with
2162 * the pre-shared key. */
2163 if (alg_a & SSL_aPSK)
2165 CBB new_premaster, child;
2169 if (!CBB_init(&new_premaster, 2 + psk_len + 2 + premaster_secret_len))
2171 OPENSSL_PUT_ERROR(SSL, ssl3_get_client_key_exchange, ERR_R_MALLOC_FAILURE);
2174 if (!CBB_add_u16_length_prefixed(&new_premaster, &child) ||
2175 !CBB_add_bytes(&child, premaster_secret, premaster_secret_len) ||
2176 !CBB_add_u16_length_prefixed(&new_premaster, &child) ||
2177 !CBB_add_bytes(&child, psk, psk_len) ||
2178 !CBB_finish(&new_premaster, &new_data, &new_len))
2180 OPENSSL_PUT_ERROR(SSL, ssl3_get_client_key_exchange, ERR_R_INTERNAL_ERROR);
2181 CBB_cleanup(&new_premaster);
2185 OPENSSL_cleanse(premaster_secret, premaster_secret_len);
2186 OPENSSL_free(premaster_secret);
2187 premaster_secret = new_data;
2188 premaster_secret_len = new_len;
2191 /* Compute the master secret */
2192 s->session->master_key_length = s->method->ssl3_enc
2193 ->generate_master_secret(s,
2194 s->session->master_key, premaster_secret, premaster_secret_len);
2196 OPENSSL_cleanse(premaster_secret, premaster_secret_len);
2197 OPENSSL_free(premaster_secret);
2200 ssl3_send_alert(s,SSL3_AL_FATAL,al);
2202 if (premaster_secret)
2204 if (premaster_secret_len)
2205 OPENSSL_cleanse(premaster_secret, premaster_secret_len);
2206 OPENSSL_free(premaster_secret);
2209 OPENSSL_free(decrypt_buf);
2210 EVP_PKEY_free(clnt_pub_pkey);
2211 EC_POINT_free(clnt_ecpoint);
2212 if (srvr_ecdh != NULL)
2213 EC_KEY_free(srvr_ecdh);
2214 BN_CTX_free(bn_ctx);
2218 int ssl3_get_cert_verify(SSL *s)
2222 CBS certificate_verify, signature;
2223 X509 *peer = s->session->peer;
2224 EVP_PKEY *pkey = NULL;
2225 const EVP_MD *md = NULL;
2226 uint8_t digest[EVP_MAX_MD_SIZE];
2227 size_t digest_length;
2228 EVP_PKEY_CTX *pctx = NULL;
2230 /* Only RSA and ECDSA client certificates are supported, so a
2231 * CertificateVerify is required if and only if there's a
2232 * client certificate. */
2235 if (s->s3->handshake_buffer && !ssl3_digest_cached_records(s))
2240 n=s->method->ssl_get_message(s,
2241 SSL3_ST_SR_CERT_VRFY_A,
2242 SSL3_ST_SR_CERT_VRFY_B,
2243 SSL3_MT_CERTIFICATE_VERIFY,
2244 SSL3_RT_MAX_PLAIN_LENGTH,
2245 SSL_GET_MESSAGE_DONT_HASH_MESSAGE,
2251 /* Filter out unsupported certificate types. */
2252 pkey = X509_get_pubkey(peer);
2253 if (!(X509_certificate_type(peer, pkey) & EVP_PKT_SIGN) ||
2254 (pkey->type != EVP_PKEY_RSA && pkey->type != EVP_PKEY_EC))
2256 al = SSL_AD_UNSUPPORTED_CERTIFICATE;
2257 OPENSSL_PUT_ERROR(SSL, ssl3_get_cert_verify, SSL_R_PEER_ERROR_UNSUPPORTED_CERTIFICATE_TYPE);
2261 CBS_init(&certificate_verify, s->init_msg, n);
2263 /* Determine the digest type if needbe. */
2264 if (SSL_USE_SIGALGS(s))
2266 if (!tls12_check_peer_sigalg(&md, &al, s, &certificate_verify, pkey))
2270 /* Compute the digest. */
2271 if (!ssl3_cert_verify_hash(s, digest, &digest_length, &md, pkey))
2274 /* The handshake buffer is no longer necessary, and we may hash the
2275 * current message.*/
2276 if (s->s3->handshake_buffer && !ssl3_digest_cached_records(s))
2278 ssl3_hash_current_message(s);
2280 /* Parse and verify the signature. */
2281 if (!CBS_get_u16_length_prefixed(&certificate_verify, &signature) ||
2282 CBS_len(&certificate_verify) != 0)
2284 al = SSL_AD_DECODE_ERROR;
2285 OPENSSL_PUT_ERROR(SSL, ssl3_get_cert_verify, SSL_R_DECODE_ERROR);
2289 pctx = EVP_PKEY_CTX_new(pkey, NULL);
2292 if (!EVP_PKEY_verify_init(pctx) ||
2293 !EVP_PKEY_CTX_set_signature_md(pctx, md) ||
2294 !EVP_PKEY_verify(pctx, CBS_data(&signature), CBS_len(&signature),
2295 digest, digest_length))
2297 al = SSL_AD_DECRYPT_ERROR;
2298 OPENSSL_PUT_ERROR(SSL, ssl3_get_cert_verify, SSL_R_BAD_SIGNATURE);
2306 ssl3_send_alert(s,SSL3_AL_FATAL,al);
2309 EVP_PKEY_CTX_free(pctx);
2310 EVP_PKEY_free(pkey);
2314 int ssl3_get_client_certificate(SSL *s)
2316 int i,ok,al,ret= -1;
2319 STACK_OF(X509) *sk=NULL;
2321 CBS certificate_msg, certificate_list;
2322 int is_first_certificate = 1;
2324 n=s->method->ssl_get_message(s,
2329 SSL_GET_MESSAGE_HASH_MESSAGE,
2332 if (!ok) return((int)n);
2334 if (s->s3->tmp.message_type == SSL3_MT_CLIENT_KEY_EXCHANGE)
2336 if ( (s->verify_mode & SSL_VERIFY_PEER) &&
2337 (s->verify_mode & SSL_VERIFY_FAIL_IF_NO_PEER_CERT))
2339 OPENSSL_PUT_ERROR(SSL, ssl3_get_client_certificate, SSL_R_PEER_DID_NOT_RETURN_A_CERTIFICATE);
2340 al=SSL_AD_HANDSHAKE_FAILURE;
2343 /* If tls asked for a client cert, the client must return a 0 list */
2344 if ((s->version > SSL3_VERSION) && s->s3->tmp.cert_request)
2346 OPENSSL_PUT_ERROR(SSL, ssl3_get_client_certificate, SSL_R_TLS_PEER_DID_NOT_RESPOND_WITH_CERTIFICATE_LIST);
2347 al=SSL_AD_UNEXPECTED_MESSAGE;
2350 s->s3->tmp.reuse_message=1;
2354 if (s->s3->tmp.message_type != SSL3_MT_CERTIFICATE)
2356 al=SSL_AD_UNEXPECTED_MESSAGE;
2357 OPENSSL_PUT_ERROR(SSL, ssl3_get_client_certificate, SSL_R_WRONG_MESSAGE_TYPE);
2361 CBS_init(&certificate_msg, s->init_msg, n);
2363 if ((sk=sk_X509_new_null()) == NULL)
2365 OPENSSL_PUT_ERROR(SSL, ssl3_get_client_certificate, ERR_R_MALLOC_FAILURE);
2369 if (!CBS_get_u24_length_prefixed(&certificate_msg, &certificate_list) ||
2370 CBS_len(&certificate_msg) != 0)
2372 al = SSL_AD_DECODE_ERROR;
2373 OPENSSL_PUT_ERROR(SSL, ssl3_get_client_certificate, SSL_R_DECODE_ERROR);
2377 while (CBS_len(&certificate_list) > 0)
2380 const uint8_t *data;
2382 if (!CBS_get_u24_length_prefixed(&certificate_list, &certificate))
2384 al = SSL_AD_DECODE_ERROR;
2385 OPENSSL_PUT_ERROR(SSL, ssl3_get_client_certificate, SSL_R_DECODE_ERROR);
2388 if (is_first_certificate && s->ctx->retain_only_sha256_of_client_certs)
2390 /* If this is the first certificate, and we don't want
2391 * to keep peer certificates in memory, then we hash it
2393 SHA256_Init(&sha256);
2394 SHA256_Update(&sha256, CBS_data(&certificate), CBS_len(&certificate));
2395 SHA256_Final(s->session->peer_sha256, &sha256);
2396 s->session->peer_sha256_valid = 1;
2398 is_first_certificate = 0;
2399 data = CBS_data(&certificate);
2400 x = d2i_X509(NULL, &data, CBS_len(&certificate));
2403 al = SSL_AD_BAD_CERTIFICATE;
2404 OPENSSL_PUT_ERROR(SSL, ssl3_get_client_certificate, ERR_R_ASN1_LIB);
2407 if (!CBS_skip(&certificate, data - CBS_data(&certificate)))
2409 al = SSL_AD_INTERNAL_ERROR;
2410 OPENSSL_PUT_ERROR(SSL, ssl3_get_client_certificate, ERR_R_INTERNAL_ERROR);
2413 if (CBS_len(&certificate) != 0)
2415 al = SSL_AD_DECODE_ERROR;
2416 OPENSSL_PUT_ERROR(SSL, ssl3_get_client_certificate, SSL_R_CERT_LENGTH_MISMATCH);
2419 if (!sk_X509_push(sk,x))
2421 OPENSSL_PUT_ERROR(SSL, ssl3_get_client_certificate, ERR_R_MALLOC_FAILURE);
2427 if (sk_X509_num(sk) <= 0)
2429 /* TLS does not mind 0 certs returned */
2430 if (s->version == SSL3_VERSION)
2432 al=SSL_AD_HANDSHAKE_FAILURE;
2433 OPENSSL_PUT_ERROR(SSL, ssl3_get_client_certificate, SSL_R_NO_CERTIFICATES_RETURNED);
2436 /* Fail for TLS only if we required a certificate */
2437 else if ((s->verify_mode & SSL_VERIFY_PEER) &&
2438 (s->verify_mode & SSL_VERIFY_FAIL_IF_NO_PEER_CERT))
2440 OPENSSL_PUT_ERROR(SSL, ssl3_get_client_certificate, SSL_R_PEER_DID_NOT_RETURN_A_CERTIFICATE);
2441 al=SSL_AD_HANDSHAKE_FAILURE;
2444 /* No client certificate so digest cached records */
2445 if (s->s3->handshake_buffer && !ssl3_digest_cached_records(s))
2447 al=SSL_AD_INTERNAL_ERROR;
2453 i=ssl_verify_cert_chain(s,sk);
2456 al=ssl_verify_alarm_type(s->verify_result);
2457 OPENSSL_PUT_ERROR(SSL, ssl3_get_client_certificate, SSL_R_CERTIFICATE_VERIFY_FAILED);
2462 if (s->session->peer != NULL) /* This should not be needed */
2463 X509_free(s->session->peer);
2464 s->session->peer=sk_X509_shift(sk);
2465 s->session->verify_result = s->verify_result;
2467 /* With the current implementation, sess_cert will always be NULL
2468 * when we arrive here. */
2469 if (s->session->sess_cert == NULL)
2471 s->session->sess_cert = ssl_sess_cert_new();
2472 if (s->session->sess_cert == NULL)
2474 OPENSSL_PUT_ERROR(SSL, ssl3_get_client_certificate, ERR_R_MALLOC_FAILURE);
2478 if (s->session->sess_cert->cert_chain != NULL)
2479 sk_X509_pop_free(s->session->sess_cert->cert_chain, X509_free);
2480 s->session->sess_cert->cert_chain=sk;
2481 /* Inconsistency alert: cert_chain does *not* include the
2482 * peer's own certificate, while we do include it in s3_clnt.c */
2490 ssl3_send_alert(s,SSL3_AL_FATAL,al);
2493 if (x != NULL) X509_free(x);
2494 if (sk != NULL) sk_X509_pop_free(sk,X509_free);
2498 int ssl3_send_server_certificate(SSL *s)
2502 if (s->state == SSL3_ST_SW_CERT_A)
2504 cpk=ssl_get_server_send_pkey(s);
2507 OPENSSL_PUT_ERROR(SSL, ssl3_send_server_certificate, ERR_R_INTERNAL_ERROR);
2511 ssl3_output_cert_chain(s,cpk);
2512 s->state=SSL3_ST_SW_CERT_B;
2515 /* SSL3_ST_SW_CERT_B */
2516 return ssl_do_write(s);
2519 /* send a new session ticket (not necessarily for a new session) */
2520 int ssl3_send_new_session_ticket(SSL *s)
2522 if (s->state == SSL3_ST_SW_SESSION_TICKET_A)
2524 unsigned char *p, *senc, *macstart;
2525 const unsigned char *const_p;
2526 int len, slen_full, slen;
2531 SSL_CTX *tctx = s->initial_ctx;
2532 unsigned char iv[EVP_MAX_IV_LENGTH];
2533 unsigned char key_name[16];
2535 /* get session encoding length */
2536 slen_full = i2d_SSL_SESSION(s->session, NULL);
2537 /* Some length values are 16 bits, so forget it if session is
2540 if (slen_full > 0xFF00)
2542 senc = OPENSSL_malloc(slen_full);
2546 i2d_SSL_SESSION(s->session, &p);
2548 /* create a fresh copy (not shared with other threads) to clean up */
2550 sess = d2i_SSL_SESSION(NULL, &const_p, slen_full);
2556 sess->session_id_length = 0; /* ID is irrelevant for the ticket */
2558 slen = i2d_SSL_SESSION(sess, NULL);
2559 if (slen > slen_full) /* shouldn't ever happen */
2565 i2d_SSL_SESSION(sess, &p);
2566 SSL_SESSION_free(sess);
2568 /* Grow buffer if need be: the length calculation is as
2569 * follows handshake_header_length +
2570 * 4 (ticket lifetime hint) + 2 (ticket length) +
2571 * 16 (key name) + max_iv_len (iv length) +
2572 * session_length + max_enc_block_size (max encrypted session
2573 * length) + max_md_size (HMAC).
2575 if (!BUF_MEM_grow(s->init_buf,
2576 SSL_HM_HEADER_LENGTH(s) + 22 + EVP_MAX_IV_LENGTH +
2577 EVP_MAX_BLOCK_LENGTH + EVP_MAX_MD_SIZE + slen))
2579 p = ssl_handshake_start(s);
2580 EVP_CIPHER_CTX_init(&ctx);
2581 HMAC_CTX_init(&hctx);
2582 /* Initialize HMAC and cipher contexts. If callback present
2583 * it does all the work otherwise use generated values
2586 if (tctx->tlsext_ticket_key_cb)
2588 if (tctx->tlsext_ticket_key_cb(s, key_name, iv, &ctx,
2597 RAND_pseudo_bytes(iv, 16);
2598 EVP_EncryptInit_ex(&ctx, EVP_aes_128_cbc(), NULL,
2599 tctx->tlsext_tick_aes_key, iv);
2600 HMAC_Init_ex(&hctx, tctx->tlsext_tick_hmac_key, 16,
2601 tlsext_tick_md(), NULL);
2602 memcpy(key_name, tctx->tlsext_tick_key_name, 16);
2605 /* Ticket lifetime hint (advisory only):
2606 * We leave this unspecified for resumed session (for simplicity),
2607 * and guess that tickets for new sessions will live as long
2608 * as their sessions. */
2609 l2n(s->hit ? 0 : s->session->timeout, p);
2611 /* Skip ticket length for now */
2613 /* Output key name */
2615 memcpy(p, key_name, 16);
2618 memcpy(p, iv, EVP_CIPHER_CTX_iv_length(&ctx));
2619 p += EVP_CIPHER_CTX_iv_length(&ctx);
2620 /* Encrypt session data */
2621 EVP_EncryptUpdate(&ctx, p, &len, senc, slen);
2623 EVP_EncryptFinal_ex(&ctx, p, &len);
2625 EVP_CIPHER_CTX_cleanup(&ctx);
2627 HMAC_Update(&hctx, macstart, p - macstart);
2628 HMAC_Final(&hctx, p, &hlen);
2629 HMAC_CTX_cleanup(&hctx);
2632 /* Now write out lengths: p points to end of data written */
2634 len = p - ssl_handshake_start(s);
2635 ssl_set_handshake_header(s, SSL3_MT_NEWSESSION_TICKET, len);
2636 /* Skip ticket lifetime hint */
2637 p = ssl_handshake_start(s) + 4;
2639 s->state=SSL3_ST_SW_SESSION_TICKET_B;
2643 /* SSL3_ST_SW_SESSION_TICKET_B */
2644 return ssl_do_write(s);
2648 int ssl3_send_cert_status(SSL *s)
2650 if (s->state == SSL3_ST_SW_CERT_STATUS_A)
2653 /* Grow buffer if need be: the length calculation is as
2654 * follows 1 (message type) + 3 (message length) +
2655 * 1 (ocsp response type) + 3 (ocsp response length)
2658 if (!BUF_MEM_grow(s->init_buf, 8 + s->tlsext_ocsp_resplen))
2661 p=(unsigned char *)s->init_buf->data;
2664 *(p++)=SSL3_MT_CERTIFICATE_STATUS;
2665 /* message length */
2666 l2n3(s->tlsext_ocsp_resplen + 4, p);
2668 *(p++)= s->tlsext_status_type;
2669 /* length of OCSP response */
2670 l2n3(s->tlsext_ocsp_resplen, p);
2671 /* actual response */
2672 memcpy(p, s->tlsext_ocsp_resp, s->tlsext_ocsp_resplen);
2673 /* number of bytes to write */
2674 s->init_num = 8 + s->tlsext_ocsp_resplen;
2675 s->state=SSL3_ST_SW_CERT_STATUS_B;
2679 /* SSL3_ST_SW_CERT_STATUS_B */
2680 return(ssl3_do_write(s,SSL3_RT_HANDSHAKE));
2684 /* ssl3_get_next_proto reads a Next Protocol Negotiation handshake message. It
2685 * sets the next_proto member in s if found */
2686 int ssl3_get_next_proto(SSL *s)
2690 CBS next_protocol, selected_protocol, padding;
2692 /* Clients cannot send a NextProtocol message if we didn't see the
2693 * extension in their ClientHello */
2694 if (!s->s3->next_proto_neg_seen)
2696 OPENSSL_PUT_ERROR(SSL, ssl3_get_next_proto, SSL_R_GOT_NEXT_PROTO_WITHOUT_EXTENSION);
2700 n=s->method->ssl_get_message(s,
2701 SSL3_ST_SR_NEXT_PROTO_A,
2702 SSL3_ST_SR_NEXT_PROTO_B,
2704 514, /* See the payload format below */
2705 SSL_GET_MESSAGE_HASH_MESSAGE,
2711 /* s->state doesn't reflect whether ChangeCipherSpec has been received
2712 * in this handshake, but s->s3->change_cipher_spec does (will be reset
2713 * by ssl3_get_finished).
2714 * TODO(davidben): Is this check now redundant with
2715 * SSL3_FLAGS_EXPECT_CCS? */
2716 if (!s->s3->change_cipher_spec)
2718 OPENSSL_PUT_ERROR(SSL, ssl3_get_next_proto, SSL_R_GOT_NEXT_PROTO_BEFORE_A_CCS);
2722 CBS_init(&next_protocol, s->init_msg, n);
2724 /* The payload looks like:
2726 * uint8 proto[proto_len];
2727 * uint8 padding_len;
2728 * uint8 padding[padding_len];
2730 if (!CBS_get_u8_length_prefixed(&next_protocol, &selected_protocol) ||
2731 !CBS_get_u8_length_prefixed(&next_protocol, &padding) ||
2732 CBS_len(&next_protocol) != 0)
2735 if (!CBS_stow(&selected_protocol,
2736 &s->next_proto_negotiated,
2737 &s->next_proto_negotiated_len))
2743 /* ssl3_get_channel_id reads and verifies a ClientID handshake message. */
2744 int ssl3_get_channel_id(SSL *s)
2749 uint8_t channel_id_hash[SHA256_DIGEST_LENGTH];
2750 unsigned int channel_id_hash_len;
2752 uint16_t extension_type, expected_extension_type;
2753 EC_GROUP* p256 = NULL;
2755 EC_POINT* point = NULL;
2758 CBS encrypted_extensions, extension;
2760 n = s->method->ssl_get_message(s,
2761 SSL3_ST_SR_CHANNEL_ID_A,
2762 SSL3_ST_SR_CHANNEL_ID_B,
2763 SSL3_MT_ENCRYPTED_EXTENSIONS,
2764 2 + 2 + TLSEXT_CHANNEL_ID_SIZE,
2765 SSL_GET_MESSAGE_DONT_HASH_MESSAGE,
2771 /* Before incorporating the EncryptedExtensions message to the
2772 * handshake hash, compute the hash that should have been signed. */
2773 channel_id_hash_len = sizeof(channel_id_hash);
2774 EVP_MD_CTX_init(&md_ctx);
2775 if (!EVP_DigestInit_ex(&md_ctx, EVP_sha256(), NULL) ||
2776 !tls1_channel_id_hash(&md_ctx, s) ||
2777 !EVP_DigestFinal(&md_ctx, channel_id_hash, &channel_id_hash_len))
2779 EVP_MD_CTX_cleanup(&md_ctx);
2782 EVP_MD_CTX_cleanup(&md_ctx);
2783 assert(channel_id_hash_len == SHA256_DIGEST_LENGTH);
2785 ssl3_hash_current_message(s);
2787 /* s->state doesn't reflect whether ChangeCipherSpec has been received
2788 * in this handshake, but s->s3->change_cipher_spec does (will be reset
2789 * by ssl3_get_finished).
2790 * TODO(davidben): Is this check now redundant with
2791 * SSL3_FLAGS_EXPECT_CCS? */
2792 if (!s->s3->change_cipher_spec)
2794 OPENSSL_PUT_ERROR(SSL, ssl3_get_channel_id, SSL_R_GOT_CHANNEL_ID_BEFORE_A_CCS);
2798 CBS_init(&encrypted_extensions, s->init_msg, n);
2800 /* EncryptedExtensions could include multiple extensions, but
2801 * the only extension that could be negotiated is ChannelID,
2802 * so there can only be one entry.
2804 * The payload looks like:
2805 * uint16 extension_type
2806 * uint16 extension_len;
2812 expected_extension_type = TLSEXT_TYPE_channel_id;
2813 if (s->s3->tlsext_channel_id_new)
2814 expected_extension_type = TLSEXT_TYPE_channel_id_new;
2816 if (!CBS_get_u16(&encrypted_extensions, &extension_type) ||
2817 !CBS_get_u16_length_prefixed(&encrypted_extensions, &extension) ||
2818 CBS_len(&encrypted_extensions) != 0 ||
2819 extension_type != expected_extension_type ||
2820 CBS_len(&extension) != TLSEXT_CHANNEL_ID_SIZE)
2822 OPENSSL_PUT_ERROR(SSL, ssl3_get_channel_id, SSL_R_INVALID_MESSAGE);
2826 p256 = EC_GROUP_new_by_curve_name(NID_X9_62_prime256v1);
2829 OPENSSL_PUT_ERROR(SSL, ssl3_get_channel_id, SSL_R_NO_P256_SUPPORT);
2838 p = CBS_data(&extension);
2839 if (BN_bin2bn(p + 0, 32, &x) == NULL ||
2840 BN_bin2bn(p + 32, 32, &y) == NULL ||
2841 BN_bin2bn(p + 64, 32, sig.r) == NULL ||
2842 BN_bin2bn(p + 96, 32, sig.s) == NULL)
2845 point = EC_POINT_new(p256);
2847 !EC_POINT_set_affine_coordinates_GFp(p256, point, &x, &y, NULL))
2852 !EC_KEY_set_group(key, p256) ||
2853 !EC_KEY_set_public_key(key, point))
2856 /* We stored the handshake hash in |tlsext_channel_id| the first time
2857 * that we were called. */
2858 if (!ECDSA_do_verify(channel_id_hash, channel_id_hash_len, &sig, key))
2860 OPENSSL_PUT_ERROR(SSL, ssl3_get_channel_id, SSL_R_CHANNEL_ID_SIGNATURE_INVALID);
2861 s->s3->tlsext_channel_id_valid = 0;
2865 memcpy(s->s3->tlsext_channel_id, p, 64);
2876 EC_POINT_free(point);
2878 EC_GROUP_free(p256);