2 /* Copyright (C) 1995-1998 Eric Young (eay@cryptsoft.com)
5 * This package is an SSL implementation written
6 * by Eric Young (eay@cryptsoft.com).
7 * The implementation was written so as to conform with Netscapes SSL.
9 * This library is free for commercial and non-commercial use as long as
10 * the following conditions are aheared to. The following conditions
11 * apply to all code found in this distribution, be it the RC4, RSA,
12 * lhash, DES, etc., code; not just the SSL code. The SSL documentation
13 * included with this distribution is covered by the same copyright terms
14 * except that the holder is Tim Hudson (tjh@cryptsoft.com).
16 * Copyright remains Eric Young's, and as such any Copyright notices in
17 * the code are not to be removed.
18 * If this package is used in a product, Eric Young should be given attribution
19 * as the author of the parts of the library used.
20 * This can be in the form of a textual message at program startup or
21 * in documentation (online or textual) provided with the package.
23 * Redistribution and use in source and binary forms, with or without
24 * modification, are permitted provided that the following conditions
26 * 1. Redistributions of source code must retain the copyright
27 * notice, this list of conditions and the following disclaimer.
28 * 2. Redistributions in binary form must reproduce the above copyright
29 * notice, this list of conditions and the following disclaimer in the
30 * documentation and/or other materials provided with the distribution.
31 * 3. All advertising materials mentioning features or use of this software
32 * must display the following acknowledgement:
33 * "This product includes cryptographic software written by
34 * Eric Young (eay@cryptsoft.com)"
35 * The word 'cryptographic' can be left out if the rouines from the library
36 * being used are not cryptographic related :-).
37 * 4. If you include any Windows specific code (or a derivative thereof) from
38 * the apps directory (application code) you must include an acknowledgement:
39 * "This product includes software written by Tim Hudson (tjh@cryptsoft.com)"
41 * THIS SOFTWARE IS PROVIDED BY ERIC YOUNG ``AS IS'' AND
42 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
43 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
44 * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
45 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
46 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
47 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
48 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
49 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
50 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
53 * The licence and distribution terms for any publically available version or
54 * derivative of this code cannot be changed. i.e. this code cannot simply be
55 * copied and put under another distribution licence
56 * [including the GNU Public Licence.]
58 /* ====================================================================
59 * Copyright (c) 1998-2007 The OpenSSL Project. All rights reserved.
61 * Redistribution and use in source and binary forms, with or without
62 * modification, are permitted provided that the following conditions
65 * 1. Redistributions of source code must retain the above copyright
66 * notice, this list of conditions and the following disclaimer.
68 * 2. Redistributions in binary form must reproduce the above copyright
69 * notice, this list of conditions and the following disclaimer in
70 * the documentation and/or other materials provided with the
73 * 3. All advertising materials mentioning features or use of this
74 * software must display the following acknowledgment:
75 * "This product includes software developed by the OpenSSL Project
76 * for use in the OpenSSL Toolkit. (http://www.openssl.org/)"
78 * 4. The names "OpenSSL Toolkit" and "OpenSSL Project" must not be used to
79 * endorse or promote products derived from this software without
80 * prior written permission. For written permission, please contact
81 * openssl-core@openssl.org.
83 * 5. Products derived from this software may not be called "OpenSSL"
84 * nor may "OpenSSL" appear in their names without prior written
85 * permission of the OpenSSL Project.
87 * 6. Redistributions of any form whatsoever must retain the following
89 * "This product includes software developed by the OpenSSL Project
90 * for use in the OpenSSL Toolkit (http://www.openssl.org/)"
92 * THIS SOFTWARE IS PROVIDED BY THE OpenSSL PROJECT ``AS IS'' AND ANY
93 * EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
94 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
95 * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE OpenSSL PROJECT OR
96 * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
97 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
98 * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
99 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
100 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
101 * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
102 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
103 * OF THE POSSIBILITY OF SUCH DAMAGE.
104 * ====================================================================
106 * This product includes cryptographic software written by Eric Young
107 * (eay@cryptsoft.com). This product includes software written by Tim
108 * Hudson (tjh@cryptsoft.com).
111 /* ====================================================================
112 * Copyright 2002 Sun Microsystems, Inc. ALL RIGHTS RESERVED.
114 * Portions of the attached software ("Contribution") are developed by
115 * SUN MICROSYSTEMS, INC., and are contributed to the OpenSSL project.
117 * The Contribution is licensed pursuant to the OpenSSL open source
118 * license provided above.
120 * ECC cipher suite support in OpenSSL originally written by
121 * Vipul Gupta and Sumit Gupta of Sun Microsystems Laboratories.
124 /* ====================================================================
125 * Copyright 2005 Nokia. All rights reserved.
127 * The portions of the attached software ("Contribution") is developed by
128 * Nokia Corporation and is licensed pursuant to the OpenSSL open source
131 * The Contribution, originally written by Mika Kousa and Pasi Eronen of
132 * Nokia Corporation, consists of the "PSK" (Pre-Shared Key) ciphersuites
133 * support (see RFC 4279) to OpenSSL.
135 * No patent licenses or other rights except those expressly stated in
136 * the OpenSSL open source license shall be deemed granted or received
137 * expressly, by implication, estoppel, or otherwise.
139 * No assurances are provided by Nokia that the Contribution does not
140 * infringe the patent or other intellectual property rights of any third
141 * party or that the license provides you with all the necessary rights
142 * to make use of the Contribution.
144 * THE SOFTWARE IS PROVIDED "AS IS" WITHOUT WARRANTY OF ANY KIND. IN
145 * ADDITION TO THE DISCLAIMERS INCLUDED IN THE LICENSE, NOKIA
146 * SPECIFICALLY DISCLAIMS ANY LIABILITY FOR CLAIMS BROUGHT BY YOU OR ANY
147 * OTHER ENTITY BASED ON INFRINGEMENT OF INTELLECTUAL PROPERTY RIGHTS OR
153 #include <openssl/buf.h>
154 #include <openssl/bytestring.h>
155 #include <openssl/rand.h>
156 #include <openssl/obj.h>
157 #include <openssl/evp.h>
158 #include <openssl/mem.h>
159 #include <openssl/md5.h>
160 #include <openssl/dh.h>
161 #include <openssl/bn.h>
162 #include <openssl/engine.h>
163 #include <openssl/x509.h>
165 #include "ssl_locl.h"
166 #include "../crypto/dh/internal.h"
168 static const SSL_METHOD *ssl3_get_client_method(int ver)
173 return TLSv1_2_client_method();
175 return TLSv1_1_client_method();
177 return TLSv1_client_method();
179 return SSLv3_client_method();
185 IMPLEMENT_tls_meth_func(TLS1_2_VERSION, TLSv1_2_client_method,
186 ssl_undefined_function,
188 ssl3_get_client_method,
191 IMPLEMENT_tls_meth_func(TLS1_1_VERSION, TLSv1_1_client_method,
192 ssl_undefined_function,
194 ssl3_get_client_method,
197 IMPLEMENT_tls_meth_func(TLS1_VERSION, TLSv1_client_method,
198 ssl_undefined_function,
200 ssl3_get_client_method,
203 IMPLEMENT_tls_meth_func(SSL3_VERSION, SSLv3_client_method,
204 ssl_undefined_function,
206 ssl3_get_client_method,
209 int ssl3_connect(SSL *s)
212 void (*cb)(const SSL *ssl,int type,int val)=NULL;
214 int new_state,state,skip=0;
217 ERR_clear_system_error();
219 if (s->info_callback != NULL)
221 else if (s->ctx->info_callback != NULL)
222 cb=s->ctx->info_callback;
225 if (!SSL_in_init(s) || SSL_in_before(s)) SSL_clear(s);
233 case SSL_ST_RENEGOTIATE:
235 s->state=SSL_ST_CONNECT;
236 s->ctx->stats.sess_connect_renegotiate++;
240 case SSL_ST_BEFORE|SSL_ST_CONNECT:
241 case SSL_ST_OK|SSL_ST_CONNECT:
244 if (cb != NULL) cb(s,SSL_CB_HANDSHAKE_START,1);
246 if ((s->version & 0xff00 ) != 0x0300)
248 OPENSSL_PUT_ERROR(SSL, ssl3_connect, ERR_R_INTERNAL_ERROR);
253 /* s->version=SSL3_VERSION; */
254 s->type=SSL_ST_CONNECT;
256 if (s->init_buf == NULL)
258 if ((buf=BUF_MEM_new()) == NULL)
263 if (!BUF_MEM_grow(buf,SSL3_RT_MAX_PLAIN_LENGTH))
272 if (!ssl3_setup_buffers(s)) { ret= -1; goto end; }
274 /* setup buffing BIO */
275 if (!ssl_init_wbio_buffer(s,0)) { ret= -1; goto end; }
277 /* don't push the buffering BIO quite yet */
279 ssl3_init_finished_mac(s);
281 s->state=SSL3_ST_CW_CLNT_HELLO_A;
282 s->ctx->stats.sess_connect++;
286 case SSL3_ST_CW_CLNT_HELLO_A:
287 case SSL3_ST_CW_CLNT_HELLO_B:
290 ret=ssl3_send_client_hello(s);
291 if (ret <= 0) goto end;
292 s->state=SSL3_ST_CR_SRVR_HELLO_A;
295 /* turn on buffering for the next lot of output */
296 if (s->bbio != s->wbio)
297 s->wbio=BIO_push(s->bbio,s->wbio);
301 case SSL3_ST_CR_SRVR_HELLO_A:
302 case SSL3_ST_CR_SRVR_HELLO_B:
303 ret=ssl3_get_server_hello(s);
304 if (ret <= 0) goto end;
308 s->state=SSL3_ST_CR_CHANGE;
309 if (s->tlsext_ticket_expected)
311 /* receive renewed session ticket */
312 s->state=SSL3_ST_CR_SESSION_TICKET_A;
317 s->state=SSL3_ST_CR_CERT_A;
322 case SSL3_ST_CR_CERT_A:
323 case SSL3_ST_CR_CERT_B:
324 if (ssl_cipher_has_server_public_key(s->s3->tmp.new_cipher))
326 ret=ssl3_get_server_certificate(s);
327 if (ret <= 0) goto end;
328 if (s->s3->tmp.certificate_status_expected)
329 s->state=SSL3_ST_CR_CERT_STATUS_A;
331 s->state=SSL3_ST_CR_KEY_EXCH_A;
336 s->state=SSL3_ST_CR_KEY_EXCH_A;
341 case SSL3_ST_CR_KEY_EXCH_A:
342 case SSL3_ST_CR_KEY_EXCH_B:
343 ret=ssl3_get_server_key_exchange(s);
344 if (ret <= 0) goto end;
345 s->state=SSL3_ST_CR_CERT_REQ_A;
348 /* at this point we check that we have the
349 * required stuff from the server */
350 if (!ssl3_check_cert_and_algorithm(s))
357 case SSL3_ST_CR_CERT_REQ_A:
358 case SSL3_ST_CR_CERT_REQ_B:
359 ret=ssl3_get_certificate_request(s);
360 if (ret <= 0) goto end;
361 s->state=SSL3_ST_CR_SRVR_DONE_A;
365 case SSL3_ST_CR_SRVR_DONE_A:
366 case SSL3_ST_CR_SRVR_DONE_B:
367 ret=ssl3_get_server_done(s);
368 if (ret <= 0) goto end;
369 if (s->s3->tmp.cert_req)
370 s->state=SSL3_ST_CW_CERT_A;
372 s->state=SSL3_ST_CW_KEY_EXCH_A;
377 case SSL3_ST_CW_CERT_A:
378 case SSL3_ST_CW_CERT_B:
379 case SSL3_ST_CW_CERT_C:
380 case SSL3_ST_CW_CERT_D:
381 ret=ssl3_send_client_certificate(s);
382 if (ret <= 0) goto end;
383 s->state=SSL3_ST_CW_KEY_EXCH_A;
387 case SSL3_ST_CW_KEY_EXCH_A:
388 case SSL3_ST_CW_KEY_EXCH_B:
389 ret=ssl3_send_client_key_exchange(s);
390 if (ret <= 0) goto end;
391 /* For TLS, cert_req is set to 2, so a cert chain
392 * of nothing is sent, but no verify packet is sent */
393 if (s->s3->tmp.cert_req == 1)
395 s->state=SSL3_ST_CW_CERT_VRFY_A;
399 s->state=SSL3_ST_CW_CHANGE_A;
400 s->s3->change_cipher_spec=0;
406 case SSL3_ST_CW_CERT_VRFY_A:
407 case SSL3_ST_CW_CERT_VRFY_B:
408 ret=ssl3_send_cert_verify(s);
409 if (ret <= 0) goto end;
410 s->state=SSL3_ST_CW_CHANGE_A;
412 s->s3->change_cipher_spec=0;
415 case SSL3_ST_CW_CHANGE_A:
416 case SSL3_ST_CW_CHANGE_B:
417 ret=ssl3_send_change_cipher_spec(s,
418 SSL3_ST_CW_CHANGE_A,SSL3_ST_CW_CHANGE_B);
419 if (ret <= 0) goto end;
421 s->state=SSL3_ST_CW_FINISHED_A;
422 if (s->s3->tlsext_channel_id_valid)
423 s->state=SSL3_ST_CW_CHANNEL_ID_A;
424 if (s->s3->next_proto_neg_seen)
425 s->state=SSL3_ST_CW_NEXT_PROTO_A;
428 s->session->cipher=s->s3->tmp.new_cipher;
429 if (!s->method->ssl3_enc->setup_key_block(s))
435 if (!s->method->ssl3_enc->change_cipher_state(s,
436 SSL3_CHANGE_CIPHER_CLIENT_WRITE))
444 case SSL3_ST_CW_NEXT_PROTO_A:
445 case SSL3_ST_CW_NEXT_PROTO_B:
446 ret=ssl3_send_next_proto(s);
447 if (ret <= 0) goto end;
448 if (s->s3->tlsext_channel_id_valid)
449 s->state=SSL3_ST_CW_CHANNEL_ID_A;
451 s->state=SSL3_ST_CW_FINISHED_A;
454 case SSL3_ST_CW_CHANNEL_ID_A:
455 case SSL3_ST_CW_CHANNEL_ID_B:
456 ret=ssl3_send_channel_id(s);
457 if (ret <= 0) goto end;
458 s->state=SSL3_ST_CW_FINISHED_A;
461 case SSL3_ST_CW_FINISHED_A:
462 case SSL3_ST_CW_FINISHED_B:
463 ret=ssl3_send_finished(s,
464 SSL3_ST_CW_FINISHED_A,SSL3_ST_CW_FINISHED_B,
465 s->method->ssl3_enc->client_finished_label,
466 s->method->ssl3_enc->client_finished_label_len);
467 if (ret <= 0) goto end;
468 s->state=SSL3_ST_CW_FLUSH;
471 s->s3->flags&= ~SSL3_FLAGS_POP_BUFFER;
474 s->s3->tmp.next_state=SSL_ST_OK;
478 /* This is a non-resumption handshake. If it
479 * involves ChannelID, then record the
480 * handshake hashes at this point in the
481 * session so that any resumption of this
482 * session with ChannelID can sign those
484 if (s->s3->tlsext_channel_id_new)
486 ret = tls1_record_handshake_hashes_for_channel_id(s);
490 if ((SSL_get_mode(s) & SSL_MODE_HANDSHAKE_CUTTHROUGH)
491 && ssl3_can_cutthrough(s)
492 && s->s3->previous_server_finished_len == 0 /* no cutthrough on renegotiation (would complicate the state machine) */
495 s->s3->tmp.next_state=SSL3_ST_CUTTHROUGH_COMPLETE;
499 /* Allow NewSessionTicket if ticket expected */
500 if (s->tlsext_ticket_expected)
501 s->s3->tmp.next_state=SSL3_ST_CR_SESSION_TICKET_A;
503 s->s3->tmp.next_state=SSL3_ST_CR_CHANGE;
509 case SSL3_ST_CR_SESSION_TICKET_A:
510 case SSL3_ST_CR_SESSION_TICKET_B:
511 ret=ssl3_get_new_session_ticket(s);
512 if (ret <= 0) goto end;
513 s->state=SSL3_ST_CR_CHANGE;
517 case SSL3_ST_CR_CERT_STATUS_A:
518 case SSL3_ST_CR_CERT_STATUS_B:
519 ret=ssl3_get_cert_status(s);
520 if (ret <= 0) goto end;
521 s->state=SSL3_ST_CR_KEY_EXCH_A;
525 case SSL3_ST_CR_CHANGE:
526 /* At this point, the next message must be entirely
527 * behind a ChangeCipherSpec. */
528 if (!ssl3_expect_change_cipher_spec(s))
533 s->state = SSL3_ST_CR_FINISHED_A;
536 case SSL3_ST_CR_FINISHED_A:
537 case SSL3_ST_CR_FINISHED_B:
538 ret=ssl3_get_finished(s,SSL3_ST_CR_FINISHED_A,
539 SSL3_ST_CR_FINISHED_B);
540 if (ret <= 0) goto end;
543 s->state=SSL3_ST_CW_CHANGE_A;
549 case SSL3_ST_CW_FLUSH:
550 s->rwstate=SSL_WRITING;
551 if (BIO_flush(s->wbio) <= 0)
556 s->rwstate=SSL_NOTHING;
557 s->state=s->s3->tmp.next_state;
560 case SSL3_ST_CUTTHROUGH_COMPLETE:
561 /* Allow NewSessionTicket if ticket expected */
562 if (s->tlsext_ticket_expected)
563 s->state=SSL3_ST_CR_SESSION_TICKET_A;
565 s->state=SSL3_ST_CR_CHANGE;
567 ssl_free_wbio_buffer(s);
573 /* clean a few things up */
574 ssl3_cleanup_key_block(s);
576 if (s->init_buf != NULL)
578 BUF_MEM_free(s->init_buf);
582 /* If we are not 'joining' the last two packets,
583 * remove the buffering now */
584 if (!(s->s3->flags & SSL3_FLAGS_POP_BUFFER))
585 ssl_free_wbio_buffer(s);
586 /* else do it later in ssl3_write */
592 ssl_update_cache(s,SSL_SESS_CACHE_CLIENT);
593 if (s->hit) s->ctx->stats.sess_hit++;
597 s->handshake_func=ssl3_connect;
598 s->ctx->stats.sess_connect_good++;
600 if (cb != NULL) cb(s,SSL_CB_HANDSHAKE_DONE,1);
606 OPENSSL_PUT_ERROR(SSL, ssl3_connect, SSL_R_UNKNOWN_STATE);
612 /* did we do anything */
613 if (!s->s3->tmp.reuse_message && !skip)
617 if ((ret=BIO_flush(s->wbio)) <= 0)
621 if ((cb != NULL) && (s->state != state))
625 cb(s,SSL_CB_CONNECT_LOOP,1);
636 cb(s,SSL_CB_CONNECT_EXIT,ret);
641 int ssl3_send_client_hello(SSL *s)
648 buf=(unsigned char *)s->init_buf->data;
649 if (s->state == SSL3_ST_CW_CLNT_HELLO_A)
651 SSL_SESSION *sess = s->session;
653 sess->ssl_version != s->version ||
654 !sess->session_id_length ||
657 if (!ssl_get_new_session(s,0))
660 if (s->method->version == DTLS_ANY_VERSION)
662 /* Determine which DTLS version to use */
663 int options = s->options;
664 /* If DTLS 1.2 disabled correct the version number */
665 if (options & SSL_OP_NO_DTLSv1_2)
667 /* Disabling all versions is silly: return an
670 if (options & SSL_OP_NO_DTLSv1)
672 OPENSSL_PUT_ERROR(SSL, ssl3_send_client_hello, SSL_R_WRONG_SSL_VERSION);
675 /* Update method so we don't use any DTLS 1.2
678 s->method = DTLSv1_client_method();
679 s->version = DTLS1_VERSION;
683 /* We only support one version: update method */
684 if (options & SSL_OP_NO_DTLSv1)
685 s->method = DTLSv1_2_client_method();
686 s->version = DTLS1_2_VERSION;
688 s->client_version = s->version;
690 /* else use the pre-loaded session */
692 p=s->s3->client_random;
694 /* If resending the ClientHello in DTLS after a
695 * HelloVerifyRequest, don't renegerate the client_random. The
696 * random must be reused. */
697 if (!SSL_IS_DTLS(s) || !s->d1->send_cookie)
699 ssl_fill_hello_random(s, 0, p,
700 sizeof(s->s3->client_random));
703 /* Do the message type and length last.
704 * Note: the final argument to ssl_add_clienthello_tlsext below
705 * depends on the size of this prefix. */
706 d=p= ssl_handshake_start(s);
708 /* version indicates the negotiated version: for example from
709 * an SSLv2/v3 compatible client hello). The client_version
710 * field is the maximum version we permit and it is also
711 * used in RSA encrypted premaster secrets. Some servers can
712 * choke if we initially report a higher version then
713 * renegotiate to a lower one in the premaster secret. This
714 * didn't happen with TLS 1.0 as most servers supported it
715 * but it can with TLS 1.1 or later if the server only supports
718 * Possible scenario with previous logic:
719 * 1. Client hello indicates TLS 1.2
720 * 2. Server hello says TLS 1.0
721 * 3. RSA encrypted premaster secret uses 1.2.
722 * 4. Handhaked proceeds using TLS 1.0.
723 * 5. Server sends hello request to renegotiate.
724 * 6. Client hello indicates TLS v1.0 as we now
725 * know that is maximum server supports.
726 * 7. Server chokes on RSA encrypted premaster secret
727 * containing version 1.0.
729 * For interoperability it should be OK to always use the
730 * maximum version we support in client hello and then rely
731 * on the checking of version to ensure the servers isn't
732 * being inconsistent: for example initially negotiating with
733 * TLS 1.0 and renegotiating with TLS 1.2. We do this by using
734 * client_version in client hello and not resetting it to
735 * the negotiated version.
738 *(p++)=s->version>>8;
739 *(p++)=s->version&0xff;
740 s->client_version=s->version;
742 *(p++)=s->client_version>>8;
743 *(p++)=s->client_version&0xff;
747 memcpy(p,s->s3->client_random,SSL3_RANDOM_SIZE);
754 i=s->session->session_id_length;
758 if (i > (int)sizeof(s->session->session_id))
760 OPENSSL_PUT_ERROR(SSL, ssl3_send_client_hello, ERR_R_INTERNAL_ERROR);
763 memcpy(p,s->session->session_id,i);
767 /* cookie stuff for DTLS */
770 if ( s->d1->cookie_len > sizeof(s->d1->cookie))
772 OPENSSL_PUT_ERROR(SSL, ssl3_send_client_hello, ERR_R_INTERNAL_ERROR);
775 *(p++) = s->d1->cookie_len;
776 memcpy(p, s->d1->cookie, s->d1->cookie_len);
777 p += s->d1->cookie_len;
780 /* Ciphers supported */
781 i = ssl_cipher_list_to_bytes(s, SSL_get_ciphers(s), &p[2]);
784 OPENSSL_PUT_ERROR(SSL, ssl3_send_client_hello, SSL_R_NO_CIPHERS_AVAILABLE);
792 *(p++)=0; /* Add the NULL method */
795 if (ssl_prepare_clienthello_tlsext(s) <= 0)
797 OPENSSL_PUT_ERROR(SSL, ssl3_send_client_hello, SSL_R_CLIENTHELLO_TLSEXT);
800 if ((p = ssl_add_clienthello_tlsext(s, p, buf+SSL3_RT_MAX_PLAIN_LENGTH, p-buf)) == NULL)
802 OPENSSL_PUT_ERROR(SSL, ssl3_send_client_hello, ERR_R_INTERNAL_ERROR);
807 ssl_set_handshake_header(s, SSL3_MT_CLIENT_HELLO, l);
808 s->state=SSL3_ST_CW_CLNT_HELLO_B;
811 /* SSL3_ST_CW_CLNT_HELLO_B */
812 return ssl_do_write(s);
817 int ssl3_get_server_hello(SSL *s)
819 STACK_OF(SSL_CIPHER) *sk;
822 int al=SSL_AD_INTERNAL_ERROR,ok;
824 CBS server_hello, server_random, session_id;
825 uint16_t server_version, cipher_suite;
826 uint8_t compression_method;
827 unsigned long mask_ssl;
829 n=s->method->ssl_get_message(s,
830 SSL3_ST_CR_SRVR_HELLO_A,
831 SSL3_ST_CR_SRVR_HELLO_B,
832 SSL3_MT_SERVER_HELLO,
834 SSL_GET_MESSAGE_HASH_MESSAGE,
837 if (!ok) return((int)n);
839 CBS_init(&server_hello, s->init_msg, n);
841 if (!CBS_get_u16(&server_hello, &server_version) ||
842 !CBS_get_bytes(&server_hello, &server_random, SSL3_RANDOM_SIZE) ||
843 !CBS_get_u8_length_prefixed(&server_hello, &session_id) ||
844 CBS_len(&session_id) > SSL3_SESSION_ID_SIZE ||
845 !CBS_get_u16(&server_hello, &cipher_suite) ||
846 !CBS_get_u8(&server_hello, &compression_method))
848 al = SSL_AD_DECODE_ERROR;
849 OPENSSL_PUT_ERROR(SSL, ssl3_get_server_hello, SSL_R_DECODE_ERROR);
853 if (s->method->version == DTLS_ANY_VERSION)
855 /* Work out correct protocol version to use */
856 int options = s->options;
857 if (server_version == DTLS1_2_VERSION
858 && !(options & SSL_OP_NO_DTLSv1_2))
859 s->method = DTLSv1_2_client_method();
860 else if (server_version == DTLS1_VERSION
861 && !(options & SSL_OP_NO_DTLSv1))
862 s->method = DTLSv1_client_method();
865 OPENSSL_PUT_ERROR(SSL, ssl3_get_server_hello, SSL_R_WRONG_SSL_VERSION);
866 s->version = server_version;
867 al = SSL_AD_PROTOCOL_VERSION;
870 s->version = s->client_version = s->method->version;
873 if (server_version != s->version)
875 OPENSSL_PUT_ERROR(SSL, ssl3_get_server_hello, SSL_R_WRONG_SSL_VERSION);
876 s->version = (s->version & 0xff00) | (server_version & 0xff);
877 al = SSL_AD_PROTOCOL_VERSION;
881 /* Copy over the server random. */
882 memcpy(s->s3->server_random, CBS_data(&server_random), SSL3_RANDOM_SIZE);
886 /* check if we want to resume the session based on external pre-shared secret */
887 if (s->version >= TLS1_VERSION && s->tls_session_secret_cb)
889 const SSL_CIPHER *pref_cipher=NULL;
890 s->session->master_key_length=sizeof(s->session->master_key);
891 if (s->tls_session_secret_cb(s, s->session->master_key,
892 &s->session->master_key_length,
894 s->tls_session_secret_cb_arg))
896 s->session->cipher = pref_cipher ?
898 ssl3_get_cipher_by_value(cipher_suite);
903 if (!s->hit && CBS_len(&session_id) != 0 &&
904 CBS_mem_equal(&session_id,
905 s->session->session_id, s->session->session_id_length))
907 if(s->sid_ctx_length != s->session->sid_ctx_length
908 || memcmp(s->session->sid_ctx, s->sid_ctx, s->sid_ctx_length))
910 /* actually a client application bug */
911 al = SSL_AD_ILLEGAL_PARAMETER;
912 OPENSSL_PUT_ERROR(SSL, ssl3_get_server_hello, SSL_R_ATTEMPT_TO_REUSE_SESSION_IN_DIFFERENT_CONTEXT);
918 /* a miss or crap from the other end */
921 /* If we were trying for session-id reuse, make a new
922 * SSL_SESSION so we don't stuff up other people */
923 if (s->session->session_id_length > 0)
925 if (!ssl_get_new_session(s,0))
930 /* Note: session_id could be empty. */
931 s->session->session_id_length = CBS_len(&session_id);
932 memcpy(s->session->session_id, CBS_data(&session_id), CBS_len(&session_id));
935 c = ssl3_get_cipher_by_value(cipher_suite);
939 al = SSL_AD_ILLEGAL_PARAMETER;
940 OPENSSL_PUT_ERROR(SSL, ssl3_get_server_hello, SSL_R_UNKNOWN_CIPHER_RETURNED);
943 /* ct->mask_ssl was computed from client capabilities. Now
944 * that the final version is known, compute a new mask_ssl. */
945 if (!SSL_USE_TLS1_2_CIPHERS(s))
946 mask_ssl = SSL_TLSV1_2;
949 /* If it is a disabled cipher we didn't send it in client hello,
950 * so return an error.
952 if (c->algorithm_ssl & mask_ssl ||
953 c->algorithm_mkey & ct->mask_k ||
954 c->algorithm_auth & ct->mask_a)
956 al=SSL_AD_ILLEGAL_PARAMETER;
957 OPENSSL_PUT_ERROR(SSL, ssl3_get_server_hello, SSL_R_WRONG_CIPHER_RETURNED);
961 sk=ssl_get_ciphers_by_id(s);
962 if (!sk_SSL_CIPHER_find(sk, NULL, c))
964 /* we did not say we would use this cipher */
965 al=SSL_AD_ILLEGAL_PARAMETER;
966 OPENSSL_PUT_ERROR(SSL, ssl3_get_server_hello, SSL_R_WRONG_CIPHER_RETURNED);
970 /* Depending on the session caching (internal/external), the cipher
971 and/or cipher_id values may not be set. Make sure that
972 cipher_id is set and use it for comparison. */
973 if (s->session->cipher)
974 s->session->cipher_id = s->session->cipher->id;
975 if (s->hit && (s->session->cipher_id != c->id))
977 al = SSL_AD_ILLEGAL_PARAMETER;
978 OPENSSL_PUT_ERROR(SSL, ssl3_get_server_hello, SSL_R_OLD_SESSION_CIPHER_NOT_RETURNED);
981 s->s3->tmp.new_cipher=c;
982 /* Don't digest cached records if no sigalgs: we may need them for
983 * client authentication.
985 if (!SSL_USE_SIGALGS(s) && !ssl3_digest_cached_records(s, free_handshake_buffer))
988 /* Only the NULL compression algorithm is supported. */
989 if (compression_method != 0)
991 al = SSL_AD_ILLEGAL_PARAMETER;
992 OPENSSL_PUT_ERROR(SSL, ssl3_get_server_hello, SSL_R_UNSUPPORTED_COMPRESSION_ALGORITHM);
997 if (!ssl_parse_serverhello_tlsext(s, &server_hello))
999 OPENSSL_PUT_ERROR(SSL, ssl3_get_server_hello, SSL_R_PARSE_TLSEXT);
1003 /* There should be nothing left over in the record. */
1004 if (CBS_len(&server_hello) != 0)
1006 /* wrong packet length */
1007 al=SSL_AD_DECODE_ERROR;
1008 OPENSSL_PUT_ERROR(SSL, ssl3_get_server_hello, SSL_R_BAD_PACKET_LENGTH);
1014 ssl3_send_alert(s,SSL3_AL_FATAL,al);
1019 int ssl3_get_server_certificate(SSL *s)
1021 int al,i,ok,ret= -1;
1024 STACK_OF(X509) *sk=NULL;
1026 EVP_PKEY *pkey=NULL;
1027 CBS cbs, certificate_list;
1028 const uint8_t* data;
1030 n=s->method->ssl_get_message(s,
1033 SSL3_MT_CERTIFICATE,
1035 SSL_GET_MESSAGE_HASH_MESSAGE,
1038 if (!ok) return((int)n);
1040 CBS_init(&cbs, s->init_msg, n);
1042 if ((sk=sk_X509_new_null()) == NULL)
1044 OPENSSL_PUT_ERROR(SSL, ssl3_get_server_certificate, ERR_R_MALLOC_FAILURE);
1048 if (!CBS_get_u24_length_prefixed(&cbs, &certificate_list) ||
1051 al = SSL_AD_DECODE_ERROR;
1052 OPENSSL_PUT_ERROR(SSL, ssl3_get_server_certificate, SSL_R_LENGTH_MISMATCH);
1056 while (CBS_len(&certificate_list) > 0)
1059 if (!CBS_get_u24_length_prefixed(&certificate_list, &certificate))
1061 al = SSL_AD_DECODE_ERROR;
1062 OPENSSL_PUT_ERROR(SSL, ssl3_get_server_certificate, SSL_R_CERT_LENGTH_MISMATCH);
1065 data = CBS_data(&certificate);
1066 x = d2i_X509(NULL, &data, CBS_len(&certificate));
1069 al=SSL_AD_BAD_CERTIFICATE;
1070 OPENSSL_PUT_ERROR(SSL, ssl3_get_server_certificate, ERR_R_ASN1_LIB);
1073 if (!CBS_skip(&certificate, data - CBS_data(&certificate)))
1075 al = SSL_AD_INTERNAL_ERROR;
1076 OPENSSL_PUT_ERROR(SSL, ssl3_get_server_certificate, ERR_R_INTERNAL_ERROR);
1079 if (CBS_len(&certificate) != 0)
1081 al = SSL_AD_DECODE_ERROR;
1082 OPENSSL_PUT_ERROR(SSL, ssl3_get_server_certificate, SSL_R_CERT_LENGTH_MISMATCH);
1085 if (!sk_X509_push(sk,x))
1087 OPENSSL_PUT_ERROR(SSL, ssl3_get_server_certificate, ERR_R_MALLOC_FAILURE);
1093 i=ssl_verify_cert_chain(s,sk);
1094 if ((s->verify_mode != SSL_VERIFY_NONE) && (i <= 0)
1097 al=ssl_verify_alarm_type(s->verify_result);
1098 OPENSSL_PUT_ERROR(SSL, ssl3_get_server_certificate, SSL_R_CERTIFICATE_VERIFY_FAILED);
1101 ERR_clear_error(); /* but we keep s->verify_result */
1103 sc=ssl_sess_cert_new();
1104 if (sc == NULL) goto err;
1106 if (s->session->sess_cert) ssl_sess_cert_free(s->session->sess_cert);
1107 s->session->sess_cert=sc;
1110 /* Inconsistency alert: cert_chain does include the peer's
1111 * certificate, which we don't include in s3_srvr.c */
1112 x=sk_X509_value(sk,0);
1114 /* VRS 19990621: possible memory leak; sk=null ==> !sk_pop_free() @end*/
1116 pkey=X509_get_pubkey(x);
1118 if ((pkey == NULL) || EVP_PKEY_missing_parameters(pkey))
1122 OPENSSL_PUT_ERROR(SSL, ssl3_get_server_certificate, SSL_R_UNABLE_TO_FIND_PUBLIC_KEY_PARAMETERS);
1126 i=ssl_cert_type(x,pkey);
1131 OPENSSL_PUT_ERROR(SSL, ssl3_get_server_certificate, SSL_R_UNKNOWN_CERTIFICATE_TYPE);
1135 int exp_idx = ssl_cipher_get_cert_index(s->s3->tmp.new_cipher);
1136 if (exp_idx >= 0 && i != exp_idx)
1139 al=SSL_AD_ILLEGAL_PARAMETER;
1140 OPENSSL_PUT_ERROR(SSL, ssl3_get_server_certificate, SSL_R_WRONG_CERTIFICATE_TYPE);
1143 sc->peer_cert_type=i;
1144 /* Why would the following ever happen?
1145 * We just created sc a couple of lines ago. */
1146 if (sc->peer_pkeys[i].x509 != NULL)
1147 X509_free(sc->peer_pkeys[i].x509);
1148 sc->peer_pkeys[i].x509 = X509_up_ref(x);
1149 sc->peer_key = &(sc->peer_pkeys[i]);
1151 if (s->session->peer != NULL)
1152 X509_free(s->session->peer);
1153 s->session->peer = X509_up_ref(x);
1155 s->session->verify_result = s->verify_result;
1162 ssl3_send_alert(s,SSL3_AL_FATAL,al);
1165 EVP_PKEY_free(pkey);
1167 sk_X509_pop_free(sk,X509_free);
1171 int ssl3_get_server_key_exchange(SSL *s)
1176 EVP_PKEY *pkey=NULL;
1177 const EVP_MD *md = NULL;
1180 EC_KEY *ecdh = NULL;
1181 BN_CTX *bn_ctx = NULL;
1182 EC_POINT *srvr_ecpoint = NULL;
1183 CBS server_key_exchange, server_key_exchange_orig, parameter;
1185 /* use same message size as in ssl3_get_certificate_request()
1186 * as ServerKeyExchange message may be skipped */
1187 n=s->method->ssl_get_message(s,
1188 SSL3_ST_CR_KEY_EXCH_A,
1189 SSL3_ST_CR_KEY_EXCH_B,
1192 SSL_GET_MESSAGE_HASH_MESSAGE,
1194 if (!ok) return((int)n);
1196 if (s->s3->tmp.message_type != SSL3_MT_SERVER_KEY_EXCHANGE)
1198 if (ssl_cipher_requires_server_key_exchange(s->s3->tmp.new_cipher))
1200 OPENSSL_PUT_ERROR(SSL, ssl3_get_server_key_exchange, SSL_R_UNEXPECTED_MESSAGE);
1201 ssl3_send_alert(s, SSL3_AL_FATAL, SSL_AD_UNEXPECTED_MESSAGE);
1205 /* In plain PSK ciphersuite, ServerKeyExchange can be
1206 omitted if no identity hint is sent. Set
1207 session->sess_cert anyway to avoid problems
1209 if (s->s3->tmp.new_cipher->algorithm_auth & SSL_aPSK)
1211 /* PSK ciphersuites that also send a
1212 * Certificate would have already initialized
1214 if (s->session->sess_cert == NULL)
1215 s->session->sess_cert = ssl_sess_cert_new();
1216 if (s->session->psk_identity_hint)
1218 OPENSSL_free(s->session->psk_identity_hint);
1219 s->session->psk_identity_hint = NULL;
1222 s->s3->tmp.reuse_message=1;
1226 /* Retain a copy of the original CBS to compute the signature
1228 CBS_init(&server_key_exchange, s->init_msg, n);
1229 server_key_exchange_orig = server_key_exchange;
1231 if (s->session->sess_cert != NULL)
1233 if (s->session->sess_cert->peer_rsa_tmp != NULL)
1235 RSA_free(s->session->sess_cert->peer_rsa_tmp);
1236 s->session->sess_cert->peer_rsa_tmp=NULL;
1238 if (s->session->sess_cert->peer_dh_tmp)
1240 DH_free(s->session->sess_cert->peer_dh_tmp);
1241 s->session->sess_cert->peer_dh_tmp=NULL;
1243 if (s->session->sess_cert->peer_ecdh_tmp)
1245 EC_KEY_free(s->session->sess_cert->peer_ecdh_tmp);
1246 s->session->sess_cert->peer_ecdh_tmp=NULL;
1251 s->session->sess_cert=ssl_sess_cert_new();
1254 alg_k=s->s3->tmp.new_cipher->algorithm_mkey;
1255 alg_a=s->s3->tmp.new_cipher->algorithm_auth;
1256 EVP_MD_CTX_init(&md_ctx);
1258 if (alg_a & SSL_aPSK)
1260 CBS psk_identity_hint;
1262 /* Each of the PSK key exchanges begins with a
1263 * psk_identity_hint. */
1264 if (!CBS_get_u16_length_prefixed(&server_key_exchange, &psk_identity_hint))
1266 al = SSL_AD_DECODE_ERROR;
1267 OPENSSL_PUT_ERROR(SSL, ssl3_get_server_key_exchange, SSL_R_DECODE_ERROR);
1271 /* Store PSK identity hint for later use, hint is used in
1272 * ssl3_send_client_key_exchange. Assume that the maximum
1273 * length of a PSK identity hint can be as long as the maximum
1274 * length of a PSK identity. Also do not allow NULL
1275 * characters; identities are saved as C strings.
1277 * TODO(davidben): Should invalid hints be ignored? It's a hint
1278 * rather than a specific identity. */
1279 if (CBS_len(&psk_identity_hint) > PSK_MAX_IDENTITY_LEN ||
1280 CBS_contains_zero_byte(&psk_identity_hint))
1282 al = SSL_AD_HANDSHAKE_FAILURE;
1283 OPENSSL_PUT_ERROR(SSL, ssl3_get_server_key_exchange, SSL_R_DATA_LENGTH_TOO_LONG);
1287 /* Save the identity hint as a C string. */
1288 if (!CBS_strdup(&psk_identity_hint, &s->session->psk_identity_hint))
1290 al = SSL_AD_HANDSHAKE_FAILURE;
1291 OPENSSL_PUT_ERROR(SSL, ssl3_get_server_key_exchange, ERR_R_MALLOC_FAILURE);
1296 if (alg_k & SSL_kRSA)
1298 CBS rsa_modulus, rsa_exponent;
1300 /* TODO(davidben): This was originally for export
1301 * reasons. Do we still need to support it? */
1303 if (!CBS_get_u16_length_prefixed(&server_key_exchange, &rsa_modulus) ||
1304 CBS_len(&rsa_modulus) == 0 ||
1305 !CBS_get_u16_length_prefixed(&server_key_exchange, &rsa_exponent) ||
1306 CBS_len(&rsa_exponent) == 0)
1308 al = SSL_AD_DECODE_ERROR;
1309 OPENSSL_PUT_ERROR(SSL, ssl3_get_server_key_exchange, SSL_R_DECODE_ERROR);
1313 if ((rsa=RSA_new()) == NULL)
1315 OPENSSL_PUT_ERROR(SSL, ssl3_get_server_key_exchange, ERR_R_MALLOC_FAILURE);
1319 if (!(rsa->n = BN_bin2bn(CBS_data(&rsa_modulus),
1320 CBS_len(&rsa_modulus), rsa->n)))
1322 OPENSSL_PUT_ERROR(SSL, ssl3_get_server_key_exchange, ERR_R_BN_LIB);
1326 if (!(rsa->e = BN_bin2bn(CBS_data(&rsa_exponent),
1327 CBS_len(&rsa_exponent), rsa->e)))
1329 OPENSSL_PUT_ERROR(SSL, ssl3_get_server_key_exchange, ERR_R_BN_LIB);
1333 /* this should be because we are using an export cipher */
1334 if (alg_a & SSL_aRSA)
1335 pkey=X509_get_pubkey(s->session->sess_cert->peer_pkeys[SSL_PKEY_RSA_ENC].x509);
1338 OPENSSL_PUT_ERROR(SSL, ssl3_get_server_key_exchange, ERR_R_INTERNAL_ERROR);
1341 s->session->sess_cert->peer_rsa_tmp=rsa;
1344 else if (alg_k & SSL_kEDH)
1346 CBS dh_p, dh_g, dh_Ys;
1348 if (!CBS_get_u16_length_prefixed(&server_key_exchange, &dh_p) ||
1349 CBS_len(&dh_p) == 0 ||
1350 !CBS_get_u16_length_prefixed(&server_key_exchange, &dh_g) ||
1351 CBS_len(&dh_g) == 0 ||
1352 !CBS_get_u16_length_prefixed(&server_key_exchange, &dh_Ys) ||
1353 CBS_len(&dh_Ys) == 0)
1355 al = SSL_AD_DECODE_ERROR;
1356 OPENSSL_PUT_ERROR(SSL, ssl3_get_server_key_exchange, SSL_R_DECODE_ERROR);
1360 if ((dh=DH_new()) == NULL)
1362 OPENSSL_PUT_ERROR(SSL, ssl3_get_server_key_exchange, ERR_R_DH_LIB);
1366 if (!(dh->p = BN_bin2bn(CBS_data(&dh_p), CBS_len(&dh_p), NULL)))
1368 OPENSSL_PUT_ERROR(SSL, ssl3_get_server_key_exchange, ERR_R_BN_LIB);
1371 if (!(dh->g=BN_bin2bn(CBS_data(&dh_g), CBS_len(&dh_g), NULL)))
1373 OPENSSL_PUT_ERROR(SSL, ssl3_get_server_key_exchange, ERR_R_BN_LIB);
1376 if (!(dh->pub_key = BN_bin2bn(CBS_data(&dh_Ys), CBS_len(&dh_Ys), NULL)))
1378 OPENSSL_PUT_ERROR(SSL, ssl3_get_server_key_exchange, ERR_R_BN_LIB);
1382 if (DH_size(dh) < 512/8)
1384 OPENSSL_PUT_ERROR(SSL, ssl3_get_server_key_exchange, SSL_R_BAD_DH_P_LENGTH);
1388 if (alg_a & SSL_aRSA)
1389 pkey=X509_get_pubkey(s->session->sess_cert->peer_pkeys[SSL_PKEY_RSA_ENC].x509);
1390 /* else anonymous DH, so no certificate or pkey. */
1392 s->session->sess_cert->peer_dh_tmp=dh;
1396 else if (alg_k & SSL_kEECDH)
1401 const EC_GROUP *group;
1404 /* Extract elliptic curve parameters and the server's
1405 * ephemeral ECDH public key. Check curve is one of
1406 * our preferences, if not server has sent an invalid
1409 if (!tls1_check_curve(s, &server_key_exchange, &curve_id))
1411 al = SSL_AD_DECODE_ERROR;
1412 OPENSSL_PUT_ERROR(SSL, ssl3_get_server_key_exchange, SSL_R_WRONG_CURVE);
1416 if ((curve_nid = tls1_ec_curve_id2nid(curve_id)) == 0)
1418 al=SSL_AD_INTERNAL_ERROR;
1419 OPENSSL_PUT_ERROR(SSL, ssl3_get_server_key_exchange, SSL_R_UNABLE_TO_FIND_ECDH_PARAMETERS);
1423 if ((ecdh=EC_KEY_new()) == NULL)
1425 OPENSSL_PUT_ERROR(SSL, ssl3_get_server_key_exchange, ERR_R_MALLOC_FAILURE);
1428 ngroup = EC_GROUP_new_by_curve_name(curve_nid);
1431 OPENSSL_PUT_ERROR(SSL, ssl3_get_server_key_exchange, ERR_R_EC_LIB);
1434 if (EC_KEY_set_group(ecdh, ngroup) == 0)
1436 OPENSSL_PUT_ERROR(SSL, ssl3_get_server_key_exchange, ERR_R_EC_LIB);
1439 EC_GROUP_free(ngroup);
1441 group = EC_KEY_get0_group(ecdh);
1443 /* Next, get the encoded ECPoint */
1444 if (!CBS_get_u8_length_prefixed(&server_key_exchange, &point))
1446 al = SSL_AD_DECODE_ERROR;
1447 OPENSSL_PUT_ERROR(SSL, ssl3_get_server_key_exchange, SSL_R_DECODE_ERROR);
1451 if (((srvr_ecpoint = EC_POINT_new(group)) == NULL) ||
1452 ((bn_ctx = BN_CTX_new()) == NULL))
1454 OPENSSL_PUT_ERROR(SSL, ssl3_get_server_key_exchange, ERR_R_MALLOC_FAILURE);
1458 if (!EC_POINT_oct2point(group, srvr_ecpoint,
1459 CBS_data(&point), CBS_len(&point), bn_ctx))
1461 al = SSL_AD_DECODE_ERROR;
1462 OPENSSL_PUT_ERROR(SSL, ssl3_get_server_key_exchange, SSL_R_BAD_ECPOINT);
1466 /* The ECC/TLS specification does not mention
1467 * the use of DSA to sign ECParameters in the server
1468 * key exchange message. We do support RSA and ECDSA.
1471 else if (alg_a & SSL_aRSA)
1472 pkey=X509_get_pubkey(s->session->sess_cert->peer_pkeys[SSL_PKEY_RSA_ENC].x509);
1473 else if (alg_a & SSL_aECDSA)
1474 pkey=X509_get_pubkey(s->session->sess_cert->peer_pkeys[SSL_PKEY_ECC].x509);
1475 /* else anonymous ECDH, so no certificate or pkey. */
1476 EC_KEY_set_public_key(ecdh, srvr_ecpoint);
1477 s->session->sess_cert->peer_ecdh_tmp=ecdh;
1479 BN_CTX_free(bn_ctx);
1481 EC_POINT_free(srvr_ecpoint);
1482 srvr_ecpoint = NULL;
1485 else if (!(alg_k & SSL_kPSK))
1487 al=SSL_AD_UNEXPECTED_MESSAGE;
1488 OPENSSL_PUT_ERROR(SSL, ssl3_get_server_key_exchange, SSL_R_UNEXPECTED_MESSAGE);
1492 /* At this point, |server_key_exchange| contains the
1493 * signature, if any, while |server_key_exchange_orig|
1494 * contains the entire message. From that, derive a CBS
1495 * containing just the parameter. */
1496 CBS_init(¶meter, CBS_data(&server_key_exchange_orig),
1497 CBS_len(&server_key_exchange_orig) -
1498 CBS_len(&server_key_exchange));
1500 /* if it was signed, check the signature */
1505 if (SSL_USE_SIGALGS(s))
1507 if (!tls12_check_peer_sigalg(&md, &al, s, &server_key_exchange, pkey))
1513 /* The last field in |server_key_exchange| is the
1515 if (!CBS_get_u16_length_prefixed(&server_key_exchange, &signature) ||
1516 CBS_len(&server_key_exchange) != 0)
1518 al = SSL_AD_DECODE_ERROR;
1519 OPENSSL_PUT_ERROR(SSL, ssl3_get_server_key_exchange, SSL_R_DECODE_ERROR);
1523 if (pkey->type == EVP_PKEY_RSA && !SSL_USE_SIGALGS(s))
1526 unsigned char *q, md_buf[EVP_MAX_MD_SIZE*2];
1530 for (num=2; num > 0; num--)
1532 unsigned int digest_len;
1533 EVP_DigestInit_ex(&md_ctx,
1534 (num == 2) ? EVP_md5() : EVP_sha1(), NULL);
1535 EVP_DigestUpdate(&md_ctx,&(s->s3->client_random[0]),SSL3_RANDOM_SIZE);
1536 EVP_DigestUpdate(&md_ctx,&(s->s3->server_random[0]),SSL3_RANDOM_SIZE);
1537 EVP_DigestUpdate(&md_ctx, CBS_data(¶meter), CBS_len(¶meter));
1538 EVP_DigestFinal_ex(&md_ctx, q, &digest_len);
1540 md_len += digest_len;
1542 if (!RSA_verify(NID_md5_sha1, md_buf, md_len,
1543 CBS_data(&signature), CBS_len(&signature),
1546 al = SSL_AD_DECRYPT_ERROR;
1547 OPENSSL_PUT_ERROR(SSL, ssl3_get_server_key_exchange, SSL_R_BAD_SIGNATURE);
1553 if (!EVP_DigestVerifyInit(&md_ctx, NULL, md, NULL, pkey) ||
1554 !EVP_DigestVerifyUpdate(&md_ctx, s->s3->client_random, SSL3_RANDOM_SIZE) ||
1555 !EVP_DigestVerifyUpdate(&md_ctx, s->s3->server_random, SSL3_RANDOM_SIZE) ||
1556 !EVP_DigestVerifyUpdate(&md_ctx, CBS_data(¶meter), CBS_len(¶meter)) ||
1557 !EVP_DigestVerifyFinal(&md_ctx, CBS_data(&signature), CBS_len(&signature)))
1560 al=SSL_AD_DECRYPT_ERROR;
1561 OPENSSL_PUT_ERROR(SSL, ssl3_get_server_key_exchange, SSL_R_BAD_SIGNATURE);
1568 if (ssl_cipher_has_server_public_key(s->s3->tmp.new_cipher))
1570 /* Might be wrong key type, check it */
1571 if (ssl3_check_cert_and_algorithm(s))
1572 /* Otherwise this shouldn't happen */
1573 OPENSSL_PUT_ERROR(SSL, ssl3_get_server_key_exchange, ERR_R_INTERNAL_ERROR);
1576 /* still data left over */
1577 if (CBS_len(&server_key_exchange) > 0)
1579 al=SSL_AD_DECODE_ERROR;
1580 OPENSSL_PUT_ERROR(SSL, ssl3_get_server_key_exchange, SSL_R_EXTRA_DATA_IN_MESSAGE);
1584 EVP_PKEY_free(pkey);
1585 EVP_MD_CTX_cleanup(&md_ctx);
1588 ssl3_send_alert(s,SSL3_AL_FATAL,al);
1590 EVP_PKEY_free(pkey);
1595 BN_CTX_free(bn_ctx);
1596 EC_POINT_free(srvr_ecpoint);
1599 EVP_MD_CTX_cleanup(&md_ctx);
1603 static int ca_dn_cmp(const X509_NAME **a, const X509_NAME **b)
1605 return(X509_NAME_cmp(*a,*b));
1608 int ssl3_get_certificate_request(SSL *s)
1614 STACK_OF(X509_NAME) *ca_sk=NULL;
1616 CBS certificate_types;
1617 CBS certificate_authorities;
1618 const uint8_t *data;
1620 n=s->method->ssl_get_message(s,
1621 SSL3_ST_CR_CERT_REQ_A,
1622 SSL3_ST_CR_CERT_REQ_B,
1625 SSL_GET_MESSAGE_HASH_MESSAGE,
1628 if (!ok) return((int)n);
1630 s->s3->tmp.cert_req=0;
1632 if (s->s3->tmp.message_type == SSL3_MT_SERVER_DONE)
1634 s->s3->tmp.reuse_message=1;
1635 /* If we get here we don't need any cached handshake records
1636 * as we wont be doing client auth.
1638 if (s->s3->handshake_buffer)
1640 if (!ssl3_digest_cached_records(s, free_handshake_buffer))
1646 if (s->s3->tmp.message_type != SSL3_MT_CERTIFICATE_REQUEST)
1648 ssl3_send_alert(s,SSL3_AL_FATAL,SSL_AD_UNEXPECTED_MESSAGE);
1649 OPENSSL_PUT_ERROR(SSL, ssl3_get_certificate_request, SSL_R_WRONG_MESSAGE_TYPE);
1653 /* TLS does not like anon-DH with client cert */
1654 if (s->version > SSL3_VERSION)
1656 if (s->s3->tmp.new_cipher->algorithm_auth & SSL_aNULL)
1658 ssl3_send_alert(s,SSL3_AL_FATAL,SSL_AD_UNEXPECTED_MESSAGE);
1659 OPENSSL_PUT_ERROR(SSL, ssl3_get_certificate_request, SSL_R_TLS_CLIENT_CERT_REQ_WITH_ANON_CIPHER);
1664 CBS_init(&cbs, s->init_msg, n);
1666 ca_sk = sk_X509_NAME_new(ca_dn_cmp);
1669 OPENSSL_PUT_ERROR(SSL, ssl3_get_certificate_request, ERR_R_MALLOC_FAILURE);
1673 /* get the certificate types */
1674 if (!CBS_get_u8_length_prefixed(&cbs, &certificate_types))
1676 ssl3_send_alert(s, SSL3_AL_FATAL, SSL_AD_DECODE_ERROR);
1677 OPENSSL_PUT_ERROR(SSL, ssl3_get_certificate_request, SSL_R_DECODE_ERROR);
1680 if (!CBS_stow(&certificate_types,
1681 &s->s3->tmp.certificate_types,
1682 &s->s3->tmp.num_certificate_types))
1684 ssl3_send_alert(s, SSL3_AL_FATAL, SSL_AD_INTERNAL_ERROR);
1687 if (SSL_USE_SIGALGS(s))
1689 CBS supported_signature_algorithms;
1690 if (!CBS_get_u16_length_prefixed(&cbs, &supported_signature_algorithms))
1692 ssl3_send_alert(s,SSL3_AL_FATAL,SSL_AD_DECODE_ERROR);
1693 OPENSSL_PUT_ERROR(SSL, ssl3_get_certificate_request, SSL_R_DECODE_ERROR);
1696 /* Clear certificate digests and validity flags */
1697 for (i = 0; i < SSL_PKEY_NUM; i++)
1699 s->cert->pkeys[i].digest = NULL;
1700 s->cert->pkeys[i].valid_flags = 0;
1702 if (!tls1_process_sigalgs(s, &supported_signature_algorithms))
1704 ssl3_send_alert(s,SSL3_AL_FATAL,SSL_AD_DECODE_ERROR);
1705 OPENSSL_PUT_ERROR(SSL, ssl3_get_certificate_request, SSL_R_SIGNATURE_ALGORITHMS_ERROR);
1710 /* get the CA RDNs */
1711 if (!CBS_get_u16_length_prefixed(&cbs, &certificate_authorities))
1713 ssl3_send_alert(s,SSL3_AL_FATAL,SSL_AD_DECODE_ERROR);
1714 OPENSSL_PUT_ERROR(SSL, ssl3_get_certificate_request, SSL_R_LENGTH_MISMATCH);
1718 while (CBS_len(&certificate_authorities) > 0)
1720 CBS distinguished_name;
1721 if (!CBS_get_u16_length_prefixed(&certificate_authorities, &distinguished_name))
1723 ssl3_send_alert(s,SSL3_AL_FATAL,SSL_AD_DECODE_ERROR);
1724 OPENSSL_PUT_ERROR(SSL, ssl3_get_certificate_request, SSL_R_CA_DN_TOO_LONG);
1728 data = CBS_data(&distinguished_name);
1729 if ((xn=d2i_X509_NAME(NULL, &data, CBS_len(&distinguished_name))) == NULL)
1731 ssl3_send_alert(s,SSL3_AL_FATAL,SSL_AD_DECODE_ERROR);
1732 OPENSSL_PUT_ERROR(SSL, ssl3_get_certificate_request, ERR_R_ASN1_LIB);
1736 if (!CBS_skip(&distinguished_name, data - CBS_data(&distinguished_name)))
1738 ssl3_send_alert(s,SSL3_AL_FATAL,SSL_AD_DECODE_ERROR);
1739 OPENSSL_PUT_ERROR(SSL, ssl3_get_server_certificate, ERR_R_INTERNAL_ERROR);
1742 if (CBS_len(&distinguished_name) != 0)
1744 ssl3_send_alert(s,SSL3_AL_FATAL,SSL_AD_DECODE_ERROR);
1745 OPENSSL_PUT_ERROR(SSL, ssl3_get_certificate_request, SSL_R_CA_DN_LENGTH_MISMATCH);
1748 if (!sk_X509_NAME_push(ca_sk,xn))
1750 OPENSSL_PUT_ERROR(SSL, ssl3_get_certificate_request, ERR_R_MALLOC_FAILURE);
1755 /* we should setup a certificate to return.... */
1756 s->s3->tmp.cert_req=1;
1757 if (s->s3->tmp.ca_names != NULL)
1758 sk_X509_NAME_pop_free(s->s3->tmp.ca_names,X509_NAME_free);
1759 s->s3->tmp.ca_names=ca_sk;
1764 if (ca_sk != NULL) sk_X509_NAME_pop_free(ca_sk,X509_NAME_free);
1768 int ssl3_get_new_session_ticket(SSL *s)
1772 CBS new_session_ticket, ticket;
1774 n=s->method->ssl_get_message(s,
1775 SSL3_ST_CR_SESSION_TICKET_A,
1776 SSL3_ST_CR_SESSION_TICKET_B,
1777 SSL3_MT_NEWSESSION_TICKET,
1779 SSL_GET_MESSAGE_HASH_MESSAGE,
1785 CBS_init(&new_session_ticket, s->init_msg, n);
1787 if (!CBS_get_u32(&new_session_ticket, &s->session->tlsext_tick_lifetime_hint) ||
1788 !CBS_get_u16_length_prefixed(&new_session_ticket, &ticket) ||
1789 CBS_len(&new_session_ticket) != 0)
1791 al = SSL_AD_DECODE_ERROR;
1792 OPENSSL_PUT_ERROR(SSL, ssl3_get_new_session_ticket, SSL_R_DECODE_ERROR);
1796 if (!CBS_stow(&ticket, &s->session->tlsext_tick, &s->session->tlsext_ticklen))
1798 OPENSSL_PUT_ERROR(SSL, ssl3_get_new_session_ticket, ERR_R_MALLOC_FAILURE);
1802 /* There are two ways to detect a resumed ticket sesion.
1803 * One is to set an appropriate session ID and then the server
1804 * must return a match in ServerHello. This allows the normal
1805 * client session ID matching to work and we know much
1806 * earlier that the ticket has been accepted.
1808 * The other way is to set zero length session ID when the
1809 * ticket is presented and rely on the handshake to determine
1810 * session resumption.
1812 * We choose the former approach because this fits in with
1813 * assumptions elsewhere in OpenSSL. The session ID is set
1814 * to the SHA256 (or SHA1 is SHA256 is disabled) hash of the
1817 EVP_Digest(CBS_data(&ticket), CBS_len(&ticket),
1818 s->session->session_id, &s->session->session_id_length,
1819 EVP_sha256(), NULL);
1823 ssl3_send_alert(s,SSL3_AL_FATAL,al);
1828 int ssl3_get_cert_status(SSL *s)
1832 CBS certificate_status, ocsp_response;
1833 uint8_t status_type;
1835 n=s->method->ssl_get_message(s,
1836 SSL3_ST_CR_CERT_STATUS_A,
1837 SSL3_ST_CR_CERT_STATUS_B,
1838 SSL3_MT_CERTIFICATE_STATUS,
1840 SSL_GET_MESSAGE_HASH_MESSAGE,
1843 if (!ok) return((int)n);
1845 CBS_init(&certificate_status, s->init_msg, n);
1846 if (!CBS_get_u8(&certificate_status, &status_type) ||
1847 status_type != TLSEXT_STATUSTYPE_ocsp ||
1848 !CBS_get_u24_length_prefixed(&certificate_status, &ocsp_response) ||
1849 CBS_len(&ocsp_response) == 0 ||
1850 CBS_len(&certificate_status) != 0)
1852 al = SSL_AD_DECODE_ERROR;
1853 OPENSSL_PUT_ERROR(SSL, ssl3_get_cert_status, SSL_R_DECODE_ERROR);
1857 if (!CBS_stow(&ocsp_response,
1858 &s->session->ocsp_response, &s->session->ocsp_response_length))
1860 al = SSL_AD_INTERNAL_ERROR;
1861 OPENSSL_PUT_ERROR(SSL, ssl3_get_cert_status, ERR_R_MALLOC_FAILURE);
1866 ssl3_send_alert(s,SSL3_AL_FATAL,al);
1870 int ssl3_get_server_done(SSL *s)
1875 n=s->method->ssl_get_message(s,
1876 SSL3_ST_CR_SRVR_DONE_A,
1877 SSL3_ST_CR_SRVR_DONE_B,
1878 SSL3_MT_SERVER_DONE,
1879 30, /* should be very small, like 0 :-) */
1880 SSL_GET_MESSAGE_HASH_MESSAGE,
1883 if (!ok) return((int)n);
1886 /* should contain no data */
1887 ssl3_send_alert(s,SSL3_AL_FATAL,SSL_AD_DECODE_ERROR);
1888 OPENSSL_PUT_ERROR(SSL, ssl3_get_server_done, SSL_R_LENGTH_MISMATCH);
1896 int ssl3_send_client_key_exchange(SSL *s)
1900 unsigned long alg_k;
1901 unsigned long alg_a;
1903 EVP_PKEY *pkey=NULL;
1904 EC_KEY *clnt_ecdh = NULL;
1905 const EC_POINT *srvr_ecpoint = NULL;
1906 EVP_PKEY *srvr_pub_pkey = NULL;
1907 unsigned char *encodedPoint = NULL;
1908 int encoded_pt_len = 0;
1909 BN_CTX * bn_ctx = NULL;
1910 unsigned int psk_len = 0;
1911 unsigned char psk[PSK_MAX_PSK_LEN];
1912 uint8_t *pms = NULL;
1915 if (s->state == SSL3_ST_CW_KEY_EXCH_A)
1917 p = ssl_handshake_start(s);
1919 alg_k=s->s3->tmp.new_cipher->algorithm_mkey;
1920 alg_a=s->s3->tmp.new_cipher->algorithm_auth;
1922 /* If using a PSK key exchange, prepare the pre-shared key. */
1923 if (alg_a & SSL_aPSK)
1925 char identity[PSK_MAX_IDENTITY_LEN + 1];
1926 size_t identity_len;
1928 if (s->psk_client_callback == NULL)
1930 OPENSSL_PUT_ERROR(SSL, ssl3_send_client_key_exchange, SSL_R_PSK_NO_CLIENT_CB);
1934 memset(identity, 0, sizeof(identity));
1935 psk_len = s->psk_client_callback(s, s->session->psk_identity_hint,
1936 identity, sizeof(identity), psk, sizeof(psk));
1937 if (psk_len > PSK_MAX_PSK_LEN)
1939 OPENSSL_PUT_ERROR(SSL, ssl3_send_client_key_exchange, ERR_R_INTERNAL_ERROR);
1942 else if (psk_len == 0)
1944 OPENSSL_PUT_ERROR(SSL, ssl3_send_client_key_exchange, SSL_R_PSK_IDENTITY_NOT_FOUND);
1945 ssl3_send_alert(s, SSL3_AL_FATAL, SSL_AD_HANDSHAKE_FAILURE);
1948 identity_len = OPENSSL_strnlen(identity, sizeof(identity));
1949 if (identity_len > PSK_MAX_IDENTITY_LEN)
1951 OPENSSL_PUT_ERROR(SSL, ssl3_send_client_key_exchange, ERR_R_INTERNAL_ERROR);
1955 if (s->session->psk_identity != NULL)
1956 OPENSSL_free(s->session->psk_identity);
1957 s->session->psk_identity = BUF_strdup(identity);
1958 if (s->session->psk_identity == NULL)
1960 OPENSSL_PUT_ERROR(SSL, ssl3_send_client_key_exchange, ERR_R_MALLOC_FAILURE);
1964 /* Write out psk_identity. */
1965 s2n(identity_len, p);
1966 memcpy(p, identity, identity_len);
1968 n = 2 + identity_len;
1971 /* Depending on the key exchange method, compute |pms|
1973 if (alg_k & SSL_kRSA)
1978 pms_len = SSL_MAX_MASTER_KEY_LENGTH;
1979 pms = OPENSSL_malloc(pms_len);
1982 OPENSSL_PUT_ERROR(SSL, ssl3_send_client_key_exchange, ERR_R_MALLOC_FAILURE);
1986 if (s->session->sess_cert == NULL)
1988 /* We should always have a server certificate with SSL_kRSA. */
1989 OPENSSL_PUT_ERROR(SSL, ssl3_send_client_key_exchange, ERR_R_INTERNAL_ERROR);
1993 if (s->session->sess_cert->peer_rsa_tmp != NULL)
1994 rsa=s->session->sess_cert->peer_rsa_tmp;
1997 pkey=X509_get_pubkey(s->session->sess_cert->peer_pkeys[SSL_PKEY_RSA_ENC].x509);
1998 if ((pkey == NULL) ||
1999 (pkey->type != EVP_PKEY_RSA) ||
2000 (pkey->pkey.rsa == NULL))
2002 OPENSSL_PUT_ERROR(SSL, ssl3_send_client_key_exchange, ERR_R_INTERNAL_ERROR);
2006 EVP_PKEY_free(pkey);
2009 pms[0]=s->client_version>>8;
2010 pms[1]=s->client_version&0xff;
2011 if (RAND_bytes(&pms[2],SSL_MAX_MASTER_KEY_LENGTH-2) <= 0)
2014 s->session->master_key_length=SSL_MAX_MASTER_KEY_LENGTH;
2017 /* In TLS and beyond, reserve space for the length prefix. */
2018 if (s->version > SSL3_VERSION)
2023 if (!RSA_encrypt(rsa, &enc_pms_len, p, RSA_size(rsa),
2024 pms, pms_len, RSA_PKCS1_PADDING))
2026 OPENSSL_PUT_ERROR(SSL, ssl3_send_client_key_exchange, SSL_R_BAD_RSA_ENCRYPT);
2031 /* Log the premaster secret, if logging is enabled. */
2032 if (!ssl_ctx_log_rsa_client_key_exchange(s->ctx,
2033 p, enc_pms_len, pms, pms_len))
2038 /* Fill in the length prefix. */
2039 if (s->version > SSL3_VERSION)
2041 s2n(enc_pms_len, q);
2044 else if (alg_k & SSL_kEDH)
2046 DH *dh_srvr, *dh_clnt;
2047 SESS_CERT *scert = s->session->sess_cert;
2053 ssl3_send_alert(s,SSL3_AL_FATAL,SSL_AD_UNEXPECTED_MESSAGE);
2054 OPENSSL_PUT_ERROR(SSL, ssl3_send_client_key_exchange, SSL_R_UNEXPECTED_MESSAGE);
2058 if (scert->peer_dh_tmp == NULL)
2060 OPENSSL_PUT_ERROR(SSL, ssl3_send_client_key_exchange, ERR_R_INTERNAL_ERROR);
2063 dh_srvr=scert->peer_dh_tmp;
2065 /* generate a new random key */
2066 if ((dh_clnt=DHparams_dup(dh_srvr)) == NULL)
2068 OPENSSL_PUT_ERROR(SSL, ssl3_send_client_key_exchange, ERR_R_DH_LIB);
2071 if (!DH_generate_key(dh_clnt))
2073 OPENSSL_PUT_ERROR(SSL, ssl3_send_client_key_exchange, ERR_R_DH_LIB);
2078 pms_len = DH_size(dh_clnt);
2079 pms = OPENSSL_malloc(pms_len);
2082 OPENSSL_PUT_ERROR(SSL, ssl3_send_client_key_exchange, ERR_R_MALLOC_FAILURE);
2087 dh_len = DH_compute_key(pms, dh_srvr->pub_key, dh_clnt);
2090 OPENSSL_PUT_ERROR(SSL, ssl3_send_client_key_exchange, ERR_R_DH_LIB);
2096 /* send off the data */
2097 pub_len = BN_num_bytes(dh_clnt->pub_key);
2099 BN_bn2bin(dh_clnt->pub_key, p);
2105 else if (alg_k & SSL_kEECDH)
2107 const EC_GROUP *srvr_group = NULL;
2109 int field_size = 0, ecdh_len;
2111 if (s->session->sess_cert == NULL)
2113 ssl3_send_alert(s,SSL3_AL_FATAL,SSL_AD_UNEXPECTED_MESSAGE);
2114 OPENSSL_PUT_ERROR(SSL, ssl3_send_client_key_exchange, SSL_R_UNEXPECTED_MESSAGE);
2118 if (s->session->sess_cert->peer_ecdh_tmp == NULL)
2120 OPENSSL_PUT_ERROR(SSL, ssl3_send_client_key_exchange, ERR_R_INTERNAL_ERROR);
2123 tkey = s->session->sess_cert->peer_ecdh_tmp;
2125 srvr_group = EC_KEY_get0_group(tkey);
2126 srvr_ecpoint = EC_KEY_get0_public_key(tkey);
2128 if ((srvr_group == NULL) || (srvr_ecpoint == NULL))
2130 OPENSSL_PUT_ERROR(SSL, ssl3_send_client_key_exchange, ERR_R_INTERNAL_ERROR);
2134 if ((clnt_ecdh=EC_KEY_new()) == NULL)
2136 OPENSSL_PUT_ERROR(SSL, ssl3_send_client_key_exchange, ERR_R_MALLOC_FAILURE);
2140 if (!EC_KEY_set_group(clnt_ecdh, srvr_group))
2142 OPENSSL_PUT_ERROR(SSL, ssl3_send_client_key_exchange, ERR_R_EC_LIB);
2145 /* Generate a new ECDH key pair */
2146 if (!(EC_KEY_generate_key(clnt_ecdh)))
2148 OPENSSL_PUT_ERROR(SSL, ssl3_send_client_key_exchange, ERR_R_ECDH_LIB);
2152 field_size = EC_GROUP_get_degree(srvr_group);
2153 if (field_size <= 0)
2155 OPENSSL_PUT_ERROR(SSL, ssl3_send_client_key_exchange, ERR_R_ECDH_LIB);
2159 pms_len = (field_size + 7) / 8;
2160 pms = OPENSSL_malloc(pms_len);
2163 OPENSSL_PUT_ERROR(SSL, ssl3_send_client_key_exchange, ERR_R_MALLOC_FAILURE);
2167 ecdh_len = ECDH_compute_key(pms, pms_len, srvr_ecpoint, clnt_ecdh, NULL);
2170 OPENSSL_PUT_ERROR(SSL, ssl3_send_client_key_exchange, ERR_R_ECDH_LIB);
2175 /* First check the size of encoding and
2176 * allocate memory accordingly.
2179 EC_POINT_point2oct(srvr_group,
2180 EC_KEY_get0_public_key(clnt_ecdh),
2181 POINT_CONVERSION_UNCOMPRESSED,
2184 encodedPoint = (unsigned char *)
2185 OPENSSL_malloc(encoded_pt_len *
2186 sizeof(unsigned char));
2187 bn_ctx = BN_CTX_new();
2188 if ((encodedPoint == NULL) ||
2191 OPENSSL_PUT_ERROR(SSL, ssl3_send_client_key_exchange, ERR_R_MALLOC_FAILURE);
2195 /* Encode the public key */
2196 encoded_pt_len = EC_POINT_point2oct(srvr_group,
2197 EC_KEY_get0_public_key(clnt_ecdh),
2198 POINT_CONVERSION_UNCOMPRESSED,
2199 encodedPoint, encoded_pt_len, bn_ctx);
2201 *p = encoded_pt_len; /* length of encoded point */
2202 /* Encoded point will be copied here */
2205 /* copy the point */
2206 memcpy(p, encodedPoint, encoded_pt_len);
2207 /* increment n to account for length field */
2208 n += encoded_pt_len;
2210 /* Free allocated memory */
2211 BN_CTX_free(bn_ctx);
2213 OPENSSL_free(encodedPoint);
2214 encodedPoint = NULL;
2215 EC_KEY_free(clnt_ecdh);
2217 EVP_PKEY_free(srvr_pub_pkey);
2218 srvr_pub_pkey = NULL;
2220 else if (alg_k & SSL_kPSK)
2222 /* For plain PSK, other_secret is a block of 0s with the same
2223 * length as the pre-shared key. */
2225 pms = OPENSSL_malloc(pms_len);
2228 OPENSSL_PUT_ERROR(SSL, ssl3_send_client_key_exchange, ERR_R_MALLOC_FAILURE);
2231 memset(pms, 0, pms_len);
2235 ssl3_send_alert(s, SSL3_AL_FATAL,
2236 SSL_AD_HANDSHAKE_FAILURE);
2237 OPENSSL_PUT_ERROR(SSL, ssl3_send_client_key_exchange, ERR_R_INTERNAL_ERROR);
2241 /* For a PSK cipher suite, other_secret is combined
2242 * with the pre-shared key. */
2243 if ((alg_a & SSL_aPSK) && psk_len != 0)
2249 if (!CBB_init(&cbb, 2 + psk_len + 2 + pms_len))
2251 OPENSSL_PUT_ERROR(SSL, ssl3_send_client_key_exchange, ERR_R_MALLOC_FAILURE);
2254 if (!CBB_add_u16_length_prefixed(&cbb, &child) ||
2255 !CBB_add_bytes(&child, pms, pms_len) ||
2256 !CBB_add_u16_length_prefixed(&cbb, &child) ||
2257 !CBB_add_bytes(&child, psk, psk_len) ||
2258 !CBB_finish(&cbb, &new_pms, &new_pms_len))
2261 OPENSSL_PUT_ERROR(SSL, ssl3_send_client_key_exchange, ERR_R_INTERNAL_ERROR);
2264 OPENSSL_cleanse(pms, pms_len);
2267 pms_len = new_pms_len;
2270 ssl_set_handshake_header(s, SSL3_MT_CLIENT_KEY_EXCHANGE, n);
2271 s->state=SSL3_ST_CW_KEY_EXCH_B;
2273 /* The message must be added to the finished hash before
2274 * calculating the master secret. */
2275 s->method->ssl3_enc->add_to_finished_hash(s);
2277 s->session->master_key_length =
2278 s->method->ssl3_enc->generate_master_secret(s,
2279 s->session->master_key,
2281 if (s->session->master_key_length == 0)
2285 s->session->extended_master_secret = s->s3->tmp.extended_master_secret;
2286 OPENSSL_cleanse(pms, pms_len);
2290 /* SSL3_ST_CW_KEY_EXCH_B */
2291 /* The message has already been added to the finished hash. */
2292 return s->method->ssl3_enc->do_write(s, dont_add_to_finished_hash);
2295 BN_CTX_free(bn_ctx);
2296 if (encodedPoint != NULL) OPENSSL_free(encodedPoint);
2297 if (clnt_ecdh != NULL)
2298 EC_KEY_free(clnt_ecdh);
2299 EVP_PKEY_free(srvr_pub_pkey);
2302 OPENSSL_cleanse(pms, pms_len);
2308 int ssl3_send_cert_verify(SSL *s)
2310 unsigned char *buf, *p;
2311 const EVP_MD *md = NULL;
2312 uint8_t digest[EVP_MAX_MD_SIZE];
2313 size_t digest_length;
2315 EVP_PKEY_CTX *pctx = NULL;
2316 size_t signature_length = 0;
2317 unsigned long n = 0;
2319 buf=(unsigned char *)s->init_buf->data;
2321 if (s->state == SSL3_ST_CW_CERT_VRFY_A)
2323 p= ssl_handshake_start(s);
2324 pkey = s->cert->key->privatekey;
2326 /* Write out the digest type if needbe. */
2327 if (SSL_USE_SIGALGS(s))
2329 md = s->cert->key->digest;
2330 if (!tls12_get_sigandhash(p, pkey, md))
2332 OPENSSL_PUT_ERROR(SSL, ssl3_send_cert_verify, ERR_R_INTERNAL_ERROR);
2339 /* Compute the digest. */
2340 if (!ssl3_cert_verify_hash(s, digest, &digest_length, &md, pkey))
2343 /* The handshake buffer is no longer necessary. */
2344 if (s->s3->handshake_buffer && !ssl3_digest_cached_records(s, free_handshake_buffer))
2347 /* Sign the digest. */
2348 pctx = EVP_PKEY_CTX_new(pkey, NULL);
2352 /* Initialize the EVP_PKEY_CTX and determine the size of the signature. */
2353 if (!EVP_PKEY_sign_init(pctx) ||
2354 !EVP_PKEY_CTX_set_signature_md(pctx, md) ||
2355 !EVP_PKEY_sign(pctx, NULL, &signature_length,
2356 digest, digest_length))
2358 OPENSSL_PUT_ERROR(SSL, ssl3_send_cert_verify, ERR_R_EVP_LIB);
2362 if (p + 2 + signature_length > buf + SSL3_RT_MAX_PLAIN_LENGTH)
2364 OPENSSL_PUT_ERROR(SSL, ssl3_send_cert_verify, SSL_R_DATA_LENGTH_TOO_LONG);
2368 if (!EVP_PKEY_sign(pctx, &p[2], &signature_length,
2369 digest, digest_length))
2371 OPENSSL_PUT_ERROR(SSL, ssl3_send_cert_verify, ERR_R_EVP_LIB);
2375 s2n(signature_length, p);
2376 n += signature_length + 2;
2378 ssl_set_handshake_header(s, SSL3_MT_CERTIFICATE_VERIFY, n);
2379 s->state=SSL3_ST_CW_CERT_VRFY_B;
2381 EVP_PKEY_CTX_free(pctx);
2382 return ssl_do_write(s);
2384 EVP_PKEY_CTX_free(pctx);
2388 /* Check a certificate can be used for client authentication. Currently
2389 * check the cert exists and if we have a suitable digest for TLS 1.2.
2391 static int ssl3_check_client_certificate(SSL *s)
2393 if (!s->cert || !s->cert->key->x509 || !s->cert->key->privatekey)
2395 /* If no suitable signature algorithm can't use certificate */
2396 if (SSL_USE_SIGALGS(s) && !s->cert->key->digest)
2398 /* If strict mode check suitability of chain before using it.
2400 if (s->cert->cert_flags & SSL_CERT_FLAGS_CHECK_TLS_STRICT &&
2401 !tls1_check_chain(s, NULL, NULL, NULL, -2))
2406 int ssl3_send_client_certificate(SSL *s)
2409 EVP_PKEY *pkey=NULL;
2412 if (s->state == SSL3_ST_CW_CERT_A)
2414 /* Let cert callback update client certificates if required */
2415 if (s->cert->cert_cb)
2417 i = s->cert->cert_cb(s, s->cert->cert_cb_arg);
2420 s->rwstate=SSL_X509_LOOKUP;
2425 ssl3_send_alert(s,SSL3_AL_FATAL,SSL_AD_INTERNAL_ERROR);
2428 s->rwstate=SSL_NOTHING;
2430 if (ssl3_check_client_certificate(s))
2431 s->state=SSL3_ST_CW_CERT_C;
2433 s->state=SSL3_ST_CW_CERT_B;
2436 /* We need to get a client cert */
2437 if (s->state == SSL3_ST_CW_CERT_B)
2439 /* If we get an error, we need to
2440 * ssl->rwstate=SSL_X509_LOOKUP; return(-1);
2441 * We then get retried later */
2442 i = ssl_do_client_cert_cb(s, &x509, &pkey);
2445 s->rwstate=SSL_X509_LOOKUP;
2448 s->rwstate=SSL_NOTHING;
2449 if ((i == 1) && (pkey != NULL) && (x509 != NULL))
2451 s->state=SSL3_ST_CW_CERT_B;
2452 if ( !SSL_use_certificate(s,x509) ||
2453 !SSL_use_PrivateKey(s,pkey))
2459 OPENSSL_PUT_ERROR(SSL, ssl3_send_client_certificate, SSL_R_BAD_DATA_RETURNED_BY_CALLBACK);
2462 if (x509 != NULL) X509_free(x509);
2463 if (pkey != NULL) EVP_PKEY_free(pkey);
2464 if (i && !ssl3_check_client_certificate(s))
2468 if (s->version == SSL3_VERSION)
2470 s->s3->tmp.cert_req=0;
2471 ssl3_send_alert(s,SSL3_AL_WARNING,SSL_AD_NO_CERTIFICATE);
2476 s->s3->tmp.cert_req=2;
2480 /* Ok, we have a cert */
2481 s->state=SSL3_ST_CW_CERT_C;
2484 if (s->state == SSL3_ST_CW_CERT_C)
2486 s->state=SSL3_ST_CW_CERT_D;
2487 ssl3_output_cert_chain(s,
2488 (s->s3->tmp.cert_req == 2)?NULL:s->cert->key);
2490 /* SSL3_ST_CW_CERT_D */
2491 return ssl_do_write(s);
2494 #define has_bits(i,m) (((i)&(m)) == (m))
2496 int ssl3_check_cert_and_algorithm(SSL *s)
2500 EVP_PKEY *pkey=NULL;
2505 /* we don't have a certificate */
2506 if (!ssl_cipher_has_server_public_key(s->s3->tmp.new_cipher))
2509 alg_k=s->s3->tmp.new_cipher->algorithm_mkey;
2510 alg_a=s->s3->tmp.new_cipher->algorithm_auth;
2512 sc=s->session->sess_cert;
2515 OPENSSL_PUT_ERROR(SSL, ssl3_check_cert_and_algorithm, ERR_R_INTERNAL_ERROR);
2519 rsa=s->session->sess_cert->peer_rsa_tmp;
2520 dh=s->session->sess_cert->peer_dh_tmp;
2522 /* This is the passed certificate */
2524 idx=sc->peer_cert_type;
2525 if (idx == SSL_PKEY_ECC)
2527 if (ssl_check_srvr_ecc_cert_and_alg(sc->peer_pkeys[idx].x509,
2529 { /* check failed */
2530 OPENSSL_PUT_ERROR(SSL, ssl3_check_cert_and_algorithm, SSL_R_BAD_ECC_CERT);
2538 else if (alg_a & SSL_aECDSA)
2540 OPENSSL_PUT_ERROR(SSL, ssl3_check_cert_and_algorithm, SSL_R_MISSING_ECDSA_SIGNING_CERT);
2543 pkey=X509_get_pubkey(sc->peer_pkeys[idx].x509);
2544 i=X509_certificate_type(sc->peer_pkeys[idx].x509,pkey);
2545 EVP_PKEY_free(pkey);
2548 /* Check that we have a certificate if we require one */
2549 if ((alg_a & SSL_aRSA) && !has_bits(i,EVP_PK_RSA|EVP_PKT_SIGN))
2551 OPENSSL_PUT_ERROR(SSL, ssl3_check_cert_and_algorithm, SSL_R_MISSING_RSA_SIGNING_CERT);
2554 if ((alg_k & SSL_kRSA) &&
2555 !(has_bits(i,EVP_PK_RSA|EVP_PKT_ENC) || (rsa != NULL)))
2557 OPENSSL_PUT_ERROR(SSL, ssl3_check_cert_and_algorithm, SSL_R_MISSING_RSA_ENCRYPTING_CERT);
2560 if ((alg_k & SSL_kEDH) &&
2561 !(has_bits(i,EVP_PK_DH|EVP_PKT_EXCH) || (dh != NULL)))
2563 OPENSSL_PUT_ERROR(SSL, ssl3_check_cert_and_algorithm, SSL_R_MISSING_DH_KEY);
2569 ssl3_send_alert(s,SSL3_AL_FATAL,SSL_AD_HANDSHAKE_FAILURE);
2574 int ssl3_send_next_proto(SSL *s)
2576 unsigned int len, padding_len;
2579 if (s->state == SSL3_ST_CW_NEXT_PROTO_A)
2581 len = s->next_proto_negotiated_len;
2582 padding_len = 32 - ((len + 2) % 32);
2583 d = (unsigned char *)s->init_buf->data;
2585 memcpy(d + 5, s->next_proto_negotiated, len);
2586 d[5 + len] = padding_len;
2587 memset(d + 6 + len, 0, padding_len);
2588 *(d++)=SSL3_MT_NEXT_PROTO;
2589 l2n3(2 + len + padding_len, d);
2590 s->state = SSL3_ST_CW_NEXT_PROTO_B;
2591 s->init_num = 4 + 2 + len + padding_len;
2595 return ssl3_do_write(s, SSL3_RT_HANDSHAKE, add_to_finished_hash);
2599 int ssl3_send_channel_id(SSL *s)
2602 int ret = -1, public_key_len;
2605 ECDSA_SIG *sig = NULL;
2606 unsigned char *public_key = NULL, *derp, *der_sig = NULL;
2608 if (s->state != SSL3_ST_CW_CHANNEL_ID_A)
2609 return ssl3_do_write(s, SSL3_RT_HANDSHAKE, add_to_finished_hash);
2611 if (!s->tlsext_channel_id_private && s->ctx->channel_id_cb)
2613 EVP_PKEY *key = NULL;
2614 s->ctx->channel_id_cb(s, &key);
2617 s->tlsext_channel_id_private = key;
2620 if (!s->tlsext_channel_id_private)
2622 s->rwstate=SSL_CHANNEL_ID_LOOKUP;
2625 s->rwstate=SSL_NOTHING;
2627 d = (unsigned char *)s->init_buf->data;
2628 *(d++)=SSL3_MT_ENCRYPTED_EXTENSIONS;
2629 l2n3(2 + 2 + TLSEXT_CHANNEL_ID_SIZE, d);
2630 if (s->s3->tlsext_channel_id_new)
2631 s2n(TLSEXT_TYPE_channel_id_new, d);
2633 s2n(TLSEXT_TYPE_channel_id, d);
2634 s2n(TLSEXT_CHANNEL_ID_SIZE, d);
2636 EVP_MD_CTX_init(&md_ctx);
2638 public_key_len = i2d_PublicKey(s->tlsext_channel_id_private, NULL);
2639 if (public_key_len <= 0)
2641 OPENSSL_PUT_ERROR(SSL, ssl3_send_channel_id, SSL_R_CANNOT_SERIALIZE_PUBLIC_KEY);
2644 /* i2d_PublicKey will produce an ANSI X9.62 public key which, for a
2645 * P-256 key, is 0x04 (meaning uncompressed) followed by the x and y
2646 * field elements as 32-byte, big-endian numbers. */
2647 if (public_key_len != 65)
2649 OPENSSL_PUT_ERROR(SSL, ssl3_send_channel_id, SSL_R_CHANNEL_ID_NOT_P256);
2652 public_key = OPENSSL_malloc(public_key_len);
2655 OPENSSL_PUT_ERROR(SSL, ssl3_send_channel_id, ERR_R_MALLOC_FAILURE);
2660 i2d_PublicKey(s->tlsext_channel_id_private, &derp);
2662 if (EVP_DigestSignInit(&md_ctx, NULL, EVP_sha256(), NULL,
2663 s->tlsext_channel_id_private) != 1)
2665 OPENSSL_PUT_ERROR(SSL, ssl3_send_channel_id, SSL_R_EVP_DIGESTSIGNINIT_FAILED);
2669 if (!tls1_channel_id_hash(&md_ctx, s))
2672 if (!EVP_DigestSignFinal(&md_ctx, NULL, &sig_len))
2674 OPENSSL_PUT_ERROR(SSL, ssl3_send_channel_id, SSL_R_EVP_DIGESTSIGNFINAL_FAILED);
2678 der_sig = OPENSSL_malloc(sig_len);
2681 OPENSSL_PUT_ERROR(SSL, ssl3_send_channel_id, ERR_R_MALLOC_FAILURE);
2685 if (!EVP_DigestSignFinal(&md_ctx, der_sig, &sig_len))
2687 OPENSSL_PUT_ERROR(SSL, ssl3_send_channel_id, SSL_R_EVP_DIGESTSIGNFINAL_FAILED);
2692 sig = d2i_ECDSA_SIG(NULL, (const unsigned char**) &derp, sig_len);
2695 OPENSSL_PUT_ERROR(SSL, ssl3_send_channel_id, SSL_R_D2I_ECDSA_SIG);
2699 /* The first byte of public_key will be 0x4, denoting an uncompressed key. */
2700 memcpy(d, public_key + 1, 64);
2702 memset(d, 0, 2 * 32);
2703 BN_bn2bin(sig->r, d + 32 - BN_num_bytes(sig->r));
2705 BN_bn2bin(sig->s, d + 32 - BN_num_bytes(sig->s));
2708 s->state = SSL3_ST_CW_CHANNEL_ID_B;
2709 s->init_num = 4 + 2 + 2 + TLSEXT_CHANNEL_ID_SIZE;
2712 ret = ssl3_do_write(s, SSL3_RT_HANDSHAKE, add_to_finished_hash);
2715 EVP_MD_CTX_cleanup(&md_ctx);
2717 OPENSSL_free(public_key);
2719 OPENSSL_free(der_sig);
2721 ECDSA_SIG_free(sig);
2726 int ssl_do_client_cert_cb(SSL *s, X509 **px509, EVP_PKEY **ppkey)
2729 if (s->ctx->client_cert_cb)
2730 i = s->ctx->client_cert_cb(s,px509,ppkey);