OpenSSL 1.0.2f
[tomato.git] / release / src / router / openssl / ssl / s3_srvr.c
blobab28702ee972dac73060a4f5d0098d918b47c0b1
1 /* ssl/s3_srvr.c */
2 /* Copyright (C) 1995-1998 Eric Young (eay@cryptsoft.com)
3 * All rights reserved.
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
25 * are met:
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
51 * SUCH DAMAGE.
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
63 * are met:
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
71 * distribution.
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
88 * acknowledgment:
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
129 * license.
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
148 * OTHERWISE.
151 #define REUSE_CIPHER_BUG
152 #define NETSCAPE_HANG_BUG
154 #include <stdio.h>
155 #include "ssl_locl.h"
156 #include "kssl_lcl.h"
157 #include "../crypto/constant_time_locl.h"
158 #include <openssl/buffer.h>
159 #include <openssl/rand.h>
160 #include <openssl/objects.h>
161 #include <openssl/evp.h>
162 #include <openssl/hmac.h>
163 #include <openssl/x509.h>
164 #ifndef OPENSSL_NO_DH
165 # include <openssl/dh.h>
166 #endif
167 #include <openssl/bn.h>
168 #ifndef OPENSSL_NO_KRB5
169 # include <openssl/krb5_asn.h>
170 #endif
171 #include <openssl/md5.h>
173 #ifndef OPENSSL_NO_SSL3_METHOD
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());
180 else
181 return (NULL);
184 IMPLEMENT_ssl3_meth_func(SSLv3_server_method,
185 ssl3_accept,
186 ssl_undefined_function, ssl3_get_server_method)
187 #endif
188 #ifndef OPENSSL_NO_SRP
189 static int ssl_check_srp_ext_ClientHello(SSL *s, int *al)
191 int ret = SSL_ERROR_NONE;
193 *al = SSL_AD_UNRECOGNIZED_NAME;
195 if ((s->s3->tmp.new_cipher->algorithm_mkey & SSL_kSRP) &&
196 (s->srp_ctx.TLS_ext_srp_username_callback != NULL)) {
197 if (s->srp_ctx.login == NULL) {
199 * RFC 5054 says SHOULD reject, we do so if There is no srp
200 * login name
202 ret = SSL3_AL_FATAL;
203 *al = SSL_AD_UNKNOWN_PSK_IDENTITY;
204 } else {
205 ret = SSL_srp_server_param_with_username(s, al);
208 return ret;
210 #endif
212 int ssl3_accept(SSL *s)
214 BUF_MEM *buf;
215 unsigned long alg_k, Time = (unsigned long)time(NULL);
216 void (*cb) (const SSL *ssl, int type, int val) = NULL;
217 int ret = -1;
218 int new_state, state, skip = 0;
220 RAND_add(&Time, sizeof(Time), 0);
221 ERR_clear_error();
222 clear_sys_error();
224 if (s->info_callback != NULL)
225 cb = s->info_callback;
226 else if (s->ctx->info_callback != NULL)
227 cb = s->ctx->info_callback;
229 /* init things to blank */
230 s->in_handshake++;
231 if (!SSL_in_init(s) || SSL_in_before(s))
232 SSL_clear(s);
234 if (s->cert == NULL) {
235 SSLerr(SSL_F_SSL3_ACCEPT, SSL_R_NO_CERTIFICATE_SET);
236 return (-1);
238 #ifndef OPENSSL_NO_HEARTBEATS
240 * If we're awaiting a HeartbeatResponse, pretend we already got and
241 * don't await it anymore, because Heartbeats don't make sense during
242 * handshakes anyway.
244 if (s->tlsext_hb_pending) {
245 s->tlsext_hb_pending = 0;
246 s->tlsext_hb_seq++;
248 #endif
250 for (;;) {
251 state = s->state;
253 switch (s->state) {
254 case SSL_ST_RENEGOTIATE:
255 s->renegotiate = 1;
256 /* s->state=SSL_ST_ACCEPT; */
258 case SSL_ST_BEFORE:
259 case SSL_ST_ACCEPT:
260 case SSL_ST_BEFORE | SSL_ST_ACCEPT:
261 case SSL_ST_OK | SSL_ST_ACCEPT:
263 s->server = 1;
264 if (cb != NULL)
265 cb(s, SSL_CB_HANDSHAKE_START, 1);
267 if ((s->version >> 8) != 3) {
268 SSLerr(SSL_F_SSL3_ACCEPT, ERR_R_INTERNAL_ERROR);
269 s->state = SSL_ST_ERR;
270 return -1;
272 s->type = SSL_ST_ACCEPT;
274 if (s->init_buf == NULL) {
275 if ((buf = BUF_MEM_new()) == NULL) {
276 ret = -1;
277 s->state = SSL_ST_ERR;
278 goto end;
280 if (!BUF_MEM_grow(buf, SSL3_RT_MAX_PLAIN_LENGTH)) {
281 BUF_MEM_free(buf);
282 ret = -1;
283 s->state = SSL_ST_ERR;
284 goto end;
286 s->init_buf = buf;
289 if (!ssl3_setup_buffers(s)) {
290 ret = -1;
291 s->state = SSL_ST_ERR;
292 goto end;
295 s->init_num = 0;
296 s->s3->flags &= ~TLS1_FLAGS_SKIP_CERT_VERIFY;
297 s->s3->flags &= ~SSL3_FLAGS_CCS_OK;
299 * Should have been reset by ssl3_get_finished, too.
301 s->s3->change_cipher_spec = 0;
303 if (s->state != SSL_ST_RENEGOTIATE) {
305 * Ok, we now need to push on a buffering BIO so that the
306 * output is sent in a way that TCP likes :-)
308 if (!ssl_init_wbio_buffer(s, 1)) {
309 ret = -1;
310 s->state = SSL_ST_ERR;
311 goto end;
314 ssl3_init_finished_mac(s);
315 s->state = SSL3_ST_SR_CLNT_HELLO_A;
316 s->ctx->stats.sess_accept++;
317 } else if (!s->s3->send_connection_binding &&
318 !(s->options &
319 SSL_OP_ALLOW_UNSAFE_LEGACY_RENEGOTIATION)) {
321 * Server attempting to renegotiate with client that doesn't
322 * support secure renegotiation.
324 SSLerr(SSL_F_SSL3_ACCEPT,
325 SSL_R_UNSAFE_LEGACY_RENEGOTIATION_DISABLED);
326 ssl3_send_alert(s, SSL3_AL_FATAL, SSL_AD_HANDSHAKE_FAILURE);
327 ret = -1;
328 s->state = SSL_ST_ERR;
329 goto end;
330 } else {
332 * s->state == SSL_ST_RENEGOTIATE, we will just send a
333 * HelloRequest
335 s->ctx->stats.sess_accept_renegotiate++;
336 s->state = SSL3_ST_SW_HELLO_REQ_A;
338 break;
340 case SSL3_ST_SW_HELLO_REQ_A:
341 case SSL3_ST_SW_HELLO_REQ_B:
343 s->shutdown = 0;
344 ret = ssl3_send_hello_request(s);
345 if (ret <= 0)
346 goto end;
347 s->s3->tmp.next_state = SSL3_ST_SW_HELLO_REQ_C;
348 s->state = SSL3_ST_SW_FLUSH;
349 s->init_num = 0;
351 ssl3_init_finished_mac(s);
352 break;
354 case SSL3_ST_SW_HELLO_REQ_C:
355 s->state = SSL_ST_OK;
356 break;
358 case SSL3_ST_SR_CLNT_HELLO_A:
359 case SSL3_ST_SR_CLNT_HELLO_B:
360 case SSL3_ST_SR_CLNT_HELLO_C:
362 s->shutdown = 0;
363 ret = ssl3_get_client_hello(s);
364 if (ret <= 0)
365 goto end;
366 #ifndef OPENSSL_NO_SRP
367 s->state = SSL3_ST_SR_CLNT_HELLO_D;
368 case SSL3_ST_SR_CLNT_HELLO_D:
370 int al;
371 if ((ret = ssl_check_srp_ext_ClientHello(s, &al)) < 0) {
373 * callback indicates firther work to be done
375 s->rwstate = SSL_X509_LOOKUP;
376 goto end;
378 if (ret != SSL_ERROR_NONE) {
379 ssl3_send_alert(s, SSL3_AL_FATAL, al);
381 * This is not really an error but the only means to for
382 * a client to detect whether srp is supported.
384 if (al != TLS1_AD_UNKNOWN_PSK_IDENTITY)
385 SSLerr(SSL_F_SSL3_ACCEPT, SSL_R_CLIENTHELLO_TLSEXT);
386 ret = -1;
387 s->state = SSL_ST_ERR;
388 goto end;
391 #endif
393 s->renegotiate = 2;
394 s->state = SSL3_ST_SW_SRVR_HELLO_A;
395 s->init_num = 0;
396 break;
398 case SSL3_ST_SW_SRVR_HELLO_A:
399 case SSL3_ST_SW_SRVR_HELLO_B:
400 ret = ssl3_send_server_hello(s);
401 if (ret <= 0)
402 goto end;
403 #ifndef OPENSSL_NO_TLSEXT
404 if (s->hit) {
405 if (s->tlsext_ticket_expected)
406 s->state = SSL3_ST_SW_SESSION_TICKET_A;
407 else
408 s->state = SSL3_ST_SW_CHANGE_A;
410 #else
411 if (s->hit)
412 s->state = SSL3_ST_SW_CHANGE_A;
413 #endif
414 else
415 s->state = SSL3_ST_SW_CERT_A;
416 s->init_num = 0;
417 break;
419 case SSL3_ST_SW_CERT_A:
420 case SSL3_ST_SW_CERT_B:
421 /* Check if it is anon DH or anon ECDH, */
422 /* normal PSK or KRB5 or SRP */
423 if (!
424 (s->s3->tmp.
425 new_cipher->algorithm_auth & (SSL_aNULL | SSL_aKRB5 |
426 SSL_aSRP))
427 && !(s->s3->tmp.new_cipher->algorithm_mkey & SSL_kPSK)) {
428 ret = ssl3_send_server_certificate(s);
429 if (ret <= 0)
430 goto end;
431 #ifndef OPENSSL_NO_TLSEXT
432 if (s->tlsext_status_expected)
433 s->state = SSL3_ST_SW_CERT_STATUS_A;
434 else
435 s->state = SSL3_ST_SW_KEY_EXCH_A;
436 } else {
437 skip = 1;
438 s->state = SSL3_ST_SW_KEY_EXCH_A;
440 #else
441 } else
442 skip = 1;
444 s->state = SSL3_ST_SW_KEY_EXCH_A;
445 #endif
446 s->init_num = 0;
447 break;
449 case SSL3_ST_SW_KEY_EXCH_A:
450 case SSL3_ST_SW_KEY_EXCH_B:
451 alg_k = s->s3->tmp.new_cipher->algorithm_mkey;
454 * clear this, it may get reset by
455 * send_server_key_exchange
457 s->s3->tmp.use_rsa_tmp = 0;
460 * only send if a DH key exchange, fortezza or RSA but we have a
461 * sign only certificate PSK: may send PSK identity hints For
462 * ECC ciphersuites, we send a serverKeyExchange message only if
463 * the cipher suite is either ECDH-anon or ECDHE. In other cases,
464 * the server certificate contains the server's public key for
465 * key exchange.
467 if (0
469 * PSK: send ServerKeyExchange if PSK identity hint if
470 * provided
472 #ifndef OPENSSL_NO_PSK
473 || ((alg_k & SSL_kPSK) && s->ctx->psk_identity_hint)
474 #endif
475 #ifndef OPENSSL_NO_SRP
476 /* SRP: send ServerKeyExchange */
477 || (alg_k & SSL_kSRP)
478 #endif
479 || (alg_k & SSL_kEDH)
480 || (alg_k & SSL_kEECDH)
481 || ((alg_k & SSL_kRSA)
482 && (s->cert->pkeys[SSL_PKEY_RSA_ENC].privatekey == NULL
483 || (SSL_C_IS_EXPORT(s->s3->tmp.new_cipher)
484 && EVP_PKEY_size(s->cert->pkeys
485 [SSL_PKEY_RSA_ENC].privatekey) *
486 8 > SSL_C_EXPORT_PKEYLENGTH(s->s3->tmp.new_cipher)
491 ret = ssl3_send_server_key_exchange(s);
492 if (ret <= 0)
493 goto end;
494 } else
495 skip = 1;
497 s->state = SSL3_ST_SW_CERT_REQ_A;
498 s->init_num = 0;
499 break;
501 case SSL3_ST_SW_CERT_REQ_A:
502 case SSL3_ST_SW_CERT_REQ_B:
503 if ( /* don't request cert unless asked for it: */
504 !(s->verify_mode & SSL_VERIFY_PEER) ||
506 * if SSL_VERIFY_CLIENT_ONCE is set, don't request cert
507 * during re-negotiation:
509 ((s->session->peer != NULL) &&
510 (s->verify_mode & SSL_VERIFY_CLIENT_ONCE)) ||
512 * never request cert in anonymous ciphersuites (see
513 * section "Certificate request" in SSL 3 drafts and in
514 * RFC 2246):
516 ((s->s3->tmp.new_cipher->algorithm_auth & SSL_aNULL) &&
518 * ... except when the application insists on
519 * verification (against the specs, but s3_clnt.c accepts
520 * this for SSL 3)
522 !(s->verify_mode & SSL_VERIFY_FAIL_IF_NO_PEER_CERT)) ||
524 * never request cert in Kerberos ciphersuites
526 (s->s3->tmp.new_cipher->algorithm_auth & SSL_aKRB5) ||
527 /* don't request certificate for SRP auth */
528 (s->s3->tmp.new_cipher->algorithm_auth & SSL_aSRP)
530 * With normal PSK Certificates and Certificate Requests
531 * are omitted
533 || (s->s3->tmp.new_cipher->algorithm_mkey & SSL_kPSK)) {
534 /* no cert request */
535 skip = 1;
536 s->s3->tmp.cert_request = 0;
537 s->state = SSL3_ST_SW_SRVR_DONE_A;
538 if (s->s3->handshake_buffer) {
539 if (!ssl3_digest_cached_records(s)) {
540 s->state = SSL_ST_ERR;
541 return -1;
544 } else {
545 s->s3->tmp.cert_request = 1;
546 ret = ssl3_send_certificate_request(s);
547 if (ret <= 0)
548 goto end;
549 #ifndef NETSCAPE_HANG_BUG
550 s->state = SSL3_ST_SW_SRVR_DONE_A;
551 #else
552 s->state = SSL3_ST_SW_FLUSH;
553 s->s3->tmp.next_state = SSL3_ST_SR_CERT_A;
554 #endif
555 s->init_num = 0;
557 break;
559 case SSL3_ST_SW_SRVR_DONE_A:
560 case SSL3_ST_SW_SRVR_DONE_B:
561 ret = ssl3_send_server_done(s);
562 if (ret <= 0)
563 goto end;
564 s->s3->tmp.next_state = SSL3_ST_SR_CERT_A;
565 s->state = SSL3_ST_SW_FLUSH;
566 s->init_num = 0;
567 break;
569 case SSL3_ST_SW_FLUSH:
572 * This code originally checked to see if any data was pending
573 * using BIO_CTRL_INFO and then flushed. This caused problems as
574 * documented in PR#1939. The proposed fix doesn't completely
575 * resolve this issue as buggy implementations of
576 * BIO_CTRL_PENDING still exist. So instead we just flush
577 * unconditionally.
580 s->rwstate = SSL_WRITING;
581 if (BIO_flush(s->wbio) <= 0) {
582 ret = -1;
583 goto end;
585 s->rwstate = SSL_NOTHING;
587 s->state = s->s3->tmp.next_state;
588 break;
590 case SSL3_ST_SR_CERT_A:
591 case SSL3_ST_SR_CERT_B:
592 if (s->s3->tmp.cert_request) {
593 ret = ssl3_get_client_certificate(s);
594 if (ret <= 0)
595 goto end;
597 s->init_num = 0;
598 s->state = SSL3_ST_SR_KEY_EXCH_A;
599 break;
601 case SSL3_ST_SR_KEY_EXCH_A:
602 case SSL3_ST_SR_KEY_EXCH_B:
603 ret = ssl3_get_client_key_exchange(s);
604 if (ret <= 0)
605 goto end;
606 if (ret == 2) {
608 * For the ECDH ciphersuites when the client sends its ECDH
609 * pub key in a certificate, the CertificateVerify message is
610 * not sent. Also for GOST ciphersuites when the client uses
611 * its key from the certificate for key exchange.
613 #if defined(OPENSSL_NO_TLSEXT) || defined(OPENSSL_NO_NEXTPROTONEG)
614 s->state = SSL3_ST_SR_FINISHED_A;
615 #else
616 if (s->s3->next_proto_neg_seen)
617 s->state = SSL3_ST_SR_NEXT_PROTO_A;
618 else
619 s->state = SSL3_ST_SR_FINISHED_A;
620 #endif
621 s->init_num = 0;
622 } else if (SSL_USE_SIGALGS(s)) {
623 s->state = SSL3_ST_SR_CERT_VRFY_A;
624 s->init_num = 0;
625 if (!s->session->peer)
626 break;
628 * For sigalgs freeze the handshake buffer at this point and
629 * digest cached records.
631 if (!s->s3->handshake_buffer) {
632 SSLerr(SSL_F_SSL3_ACCEPT, ERR_R_INTERNAL_ERROR);
633 s->state = SSL_ST_ERR;
634 return -1;
636 s->s3->flags |= TLS1_FLAGS_KEEP_HANDSHAKE;
637 if (!ssl3_digest_cached_records(s)) {
638 s->state = SSL_ST_ERR;
639 return -1;
641 } else {
642 int offset = 0;
643 int dgst_num;
645 s->state = SSL3_ST_SR_CERT_VRFY_A;
646 s->init_num = 0;
649 * We need to get hashes here so if there is a client cert,
650 * it can be verified FIXME - digest processing for
651 * CertificateVerify should be generalized. But it is next
652 * step
654 if (s->s3->handshake_buffer) {
655 if (!ssl3_digest_cached_records(s)) {
656 s->state = SSL_ST_ERR;
657 return -1;
660 for (dgst_num = 0; dgst_num < SSL_MAX_DIGEST; dgst_num++)
661 if (s->s3->handshake_dgst[dgst_num]) {
662 int dgst_size;
664 s->method->ssl3_enc->cert_verify_mac(s,
665 EVP_MD_CTX_type
666 (s->
667 s3->handshake_dgst
668 [dgst_num]),
669 &(s->s3->
670 tmp.cert_verify_md
671 [offset]));
672 dgst_size =
673 EVP_MD_CTX_size(s->s3->handshake_dgst[dgst_num]);
674 if (dgst_size < 0) {
675 s->state = SSL_ST_ERR;
676 ret = -1;
677 goto end;
679 offset += dgst_size;
682 break;
684 case SSL3_ST_SR_CERT_VRFY_A:
685 case SSL3_ST_SR_CERT_VRFY_B:
686 ret = ssl3_get_cert_verify(s);
687 if (ret <= 0)
688 goto end;
690 #if defined(OPENSSL_NO_TLSEXT) || defined(OPENSSL_NO_NEXTPROTONEG)
691 s->state = SSL3_ST_SR_FINISHED_A;
692 #else
693 if (s->s3->next_proto_neg_seen)
694 s->state = SSL3_ST_SR_NEXT_PROTO_A;
695 else
696 s->state = SSL3_ST_SR_FINISHED_A;
697 #endif
698 s->init_num = 0;
699 break;
701 #if !defined(OPENSSL_NO_TLSEXT) && !defined(OPENSSL_NO_NEXTPROTONEG)
702 case SSL3_ST_SR_NEXT_PROTO_A:
703 case SSL3_ST_SR_NEXT_PROTO_B:
705 * Enable CCS for NPN. Receiving a CCS clears the flag, so make
706 * sure not to re-enable it to ban duplicates. This *should* be the
707 * first time we have received one - but we check anyway to be
708 * cautious.
709 * s->s3->change_cipher_spec is set when a CCS is
710 * processed in s3_pkt.c, and remains set until
711 * the client's Finished message is read.
713 if (!s->s3->change_cipher_spec)
714 s->s3->flags |= SSL3_FLAGS_CCS_OK;
716 ret = ssl3_get_next_proto(s);
717 if (ret <= 0)
718 goto end;
719 s->init_num = 0;
720 s->state = SSL3_ST_SR_FINISHED_A;
721 break;
722 #endif
724 case SSL3_ST_SR_FINISHED_A:
725 case SSL3_ST_SR_FINISHED_B:
727 * Enable CCS for handshakes without NPN. In NPN the CCS flag has
728 * already been set. Receiving a CCS clears the flag, so make
729 * sure not to re-enable it to ban duplicates.
730 * s->s3->change_cipher_spec is set when a CCS is
731 * processed in s3_pkt.c, and remains set until
732 * the client's Finished message is read.
734 if (!s->s3->change_cipher_spec)
735 s->s3->flags |= SSL3_FLAGS_CCS_OK;
736 ret = ssl3_get_finished(s, SSL3_ST_SR_FINISHED_A,
737 SSL3_ST_SR_FINISHED_B);
738 if (ret <= 0)
739 goto end;
740 if (s->hit)
741 s->state = SSL_ST_OK;
742 #ifndef OPENSSL_NO_TLSEXT
743 else if (s->tlsext_ticket_expected)
744 s->state = SSL3_ST_SW_SESSION_TICKET_A;
745 #endif
746 else
747 s->state = SSL3_ST_SW_CHANGE_A;
748 s->init_num = 0;
749 break;
751 #ifndef OPENSSL_NO_TLSEXT
752 case SSL3_ST_SW_SESSION_TICKET_A:
753 case SSL3_ST_SW_SESSION_TICKET_B:
754 ret = ssl3_send_newsession_ticket(s);
755 if (ret <= 0)
756 goto end;
757 s->state = SSL3_ST_SW_CHANGE_A;
758 s->init_num = 0;
759 break;
761 case SSL3_ST_SW_CERT_STATUS_A:
762 case SSL3_ST_SW_CERT_STATUS_B:
763 ret = ssl3_send_cert_status(s);
764 if (ret <= 0)
765 goto end;
766 s->state = SSL3_ST_SW_KEY_EXCH_A;
767 s->init_num = 0;
768 break;
770 #endif
772 case SSL3_ST_SW_CHANGE_A:
773 case SSL3_ST_SW_CHANGE_B:
775 s->session->cipher = s->s3->tmp.new_cipher;
776 if (!s->method->ssl3_enc->setup_key_block(s)) {
777 ret = -1;
778 s->state = SSL_ST_ERR;
779 goto end;
782 ret = ssl3_send_change_cipher_spec(s,
783 SSL3_ST_SW_CHANGE_A,
784 SSL3_ST_SW_CHANGE_B);
786 if (ret <= 0)
787 goto end;
788 s->state = SSL3_ST_SW_FINISHED_A;
789 s->init_num = 0;
791 if (!s->method->ssl3_enc->change_cipher_state(s,
792 SSL3_CHANGE_CIPHER_SERVER_WRITE))
794 ret = -1;
795 s->state = SSL_ST_ERR;
796 goto end;
799 break;
801 case SSL3_ST_SW_FINISHED_A:
802 case SSL3_ST_SW_FINISHED_B:
803 ret = ssl3_send_finished(s,
804 SSL3_ST_SW_FINISHED_A,
805 SSL3_ST_SW_FINISHED_B,
806 s->method->
807 ssl3_enc->server_finished_label,
808 s->method->
809 ssl3_enc->server_finished_label_len);
810 if (ret <= 0)
811 goto end;
812 s->state = SSL3_ST_SW_FLUSH;
813 if (s->hit) {
814 #if defined(OPENSSL_NO_TLSEXT) || defined(OPENSSL_NO_NEXTPROTONEG)
815 s->s3->tmp.next_state = SSL3_ST_SR_FINISHED_A;
816 #else
817 if (s->s3->next_proto_neg_seen) {
818 s->s3->tmp.next_state = SSL3_ST_SR_NEXT_PROTO_A;
819 } else
820 s->s3->tmp.next_state = SSL3_ST_SR_FINISHED_A;
821 #endif
822 } else
823 s->s3->tmp.next_state = SSL_ST_OK;
824 s->init_num = 0;
825 break;
827 case SSL_ST_OK:
828 /* clean a few things up */
829 ssl3_cleanup_key_block(s);
831 BUF_MEM_free(s->init_buf);
832 s->init_buf = NULL;
834 /* remove buffering on output */
835 ssl_free_wbio_buffer(s);
837 s->init_num = 0;
839 if (s->renegotiate == 2) { /* skipped if we just sent a
840 * HelloRequest */
841 s->renegotiate = 0;
842 s->new_session = 0;
844 ssl_update_cache(s, SSL_SESS_CACHE_SERVER);
846 s->ctx->stats.sess_accept_good++;
847 /* s->server=1; */
848 s->handshake_func = ssl3_accept;
850 if (cb != NULL)
851 cb(s, SSL_CB_HANDSHAKE_DONE, 1);
854 ret = 1;
855 goto end;
856 /* break; */
858 case SSL_ST_ERR:
859 default:
860 SSLerr(SSL_F_SSL3_ACCEPT, SSL_R_UNKNOWN_STATE);
861 ret = -1;
862 goto end;
863 /* break; */
866 if (!s->s3->tmp.reuse_message && !skip) {
867 if (s->debug) {
868 if ((ret = BIO_flush(s->wbio)) <= 0)
869 goto end;
872 if ((cb != NULL) && (s->state != state)) {
873 new_state = s->state;
874 s->state = state;
875 cb(s, SSL_CB_ACCEPT_LOOP, 1);
876 s->state = new_state;
879 skip = 0;
881 end:
882 /* BIO_flush(s->wbio); */
884 s->in_handshake--;
885 if (cb != NULL)
886 cb(s, SSL_CB_ACCEPT_EXIT, ret);
887 return (ret);
890 int ssl3_send_hello_request(SSL *s)
893 if (s->state == SSL3_ST_SW_HELLO_REQ_A) {
894 ssl_set_handshake_header(s, SSL3_MT_HELLO_REQUEST, 0);
895 s->state = SSL3_ST_SW_HELLO_REQ_B;
898 /* SSL3_ST_SW_HELLO_REQ_B */
899 return ssl_do_write(s);
902 int ssl3_get_client_hello(SSL *s)
904 int i, j, ok, al = SSL_AD_INTERNAL_ERROR, ret = -1, cookie_valid = 0;
905 unsigned int cookie_len;
906 long n;
907 unsigned long id;
908 unsigned char *p, *d;
909 SSL_CIPHER *c;
910 #ifndef OPENSSL_NO_COMP
911 unsigned char *q;
912 SSL_COMP *comp = NULL;
913 #endif
914 STACK_OF(SSL_CIPHER) *ciphers = NULL;
916 if (s->state == SSL3_ST_SR_CLNT_HELLO_C && !s->first_packet)
917 goto retry_cert;
920 * We do this so that we will respond with our native type. If we are
921 * TLSv1 and we get SSLv3, we will respond with TLSv1, This down
922 * switching should be handled by a different method. If we are SSLv3, we
923 * will respond with SSLv3, even if prompted with TLSv1.
925 if (s->state == SSL3_ST_SR_CLNT_HELLO_A) {
926 s->state = SSL3_ST_SR_CLNT_HELLO_B;
928 s->first_packet = 1;
929 n = s->method->ssl_get_message(s,
930 SSL3_ST_SR_CLNT_HELLO_B,
931 SSL3_ST_SR_CLNT_HELLO_C,
932 SSL3_MT_CLIENT_HELLO,
933 SSL3_RT_MAX_PLAIN_LENGTH, &ok);
935 if (!ok)
936 return ((int)n);
937 s->first_packet = 0;
938 d = p = (unsigned char *)s->init_msg;
941 * 2 bytes for client version, SSL3_RANDOM_SIZE bytes for random, 1 byte
942 * for session id length
944 if (n < 2 + SSL3_RANDOM_SIZE + 1) {
945 al = SSL_AD_DECODE_ERROR;
946 SSLerr(SSL_F_SSL3_GET_CLIENT_HELLO, SSL_R_LENGTH_TOO_SHORT);
947 goto f_err;
951 * use version from inside client hello, not from record header (may
952 * differ: see RFC 2246, Appendix E, second paragraph)
954 s->client_version = (((int)p[0]) << 8) | (int)p[1];
955 p += 2;
957 if (SSL_IS_DTLS(s) ? (s->client_version > s->version &&
958 s->method->version != DTLS_ANY_VERSION)
959 : (s->client_version < s->version)) {
960 SSLerr(SSL_F_SSL3_GET_CLIENT_HELLO, SSL_R_WRONG_VERSION_NUMBER);
961 if ((s->client_version >> 8) == SSL3_VERSION_MAJOR &&
962 !s->enc_write_ctx && !s->write_hash) {
964 * similar to ssl3_get_record, send alert using remote version
965 * number
967 s->version = s->client_version;
969 al = SSL_AD_PROTOCOL_VERSION;
970 goto f_err;
974 * If we require cookies and this ClientHello doesn't contain one, just
975 * return since we do not want to allocate any memory yet. So check
976 * cookie length...
978 if (SSL_get_options(s) & SSL_OP_COOKIE_EXCHANGE) {
979 unsigned int session_length, cookie_length;
981 session_length = *(p + SSL3_RANDOM_SIZE);
983 if (p + SSL3_RANDOM_SIZE + session_length + 1 >= d + n) {
984 al = SSL_AD_DECODE_ERROR;
985 SSLerr(SSL_F_SSL3_GET_CLIENT_HELLO, SSL_R_LENGTH_TOO_SHORT);
986 goto f_err;
988 cookie_length = *(p + SSL3_RANDOM_SIZE + session_length + 1);
990 if (cookie_length == 0)
991 return 1;
994 /* load the client random */
995 memcpy(s->s3->client_random, p, SSL3_RANDOM_SIZE);
996 p += SSL3_RANDOM_SIZE;
998 /* get the session-id */
999 j = *(p++);
1001 if (p + j > d + n) {
1002 al = SSL_AD_DECODE_ERROR;
1003 SSLerr(SSL_F_SSL3_GET_CLIENT_HELLO, SSL_R_LENGTH_TOO_SHORT);
1004 goto f_err;
1007 if ((j < 0) || (j > SSL_MAX_SSL_SESSION_ID_LENGTH)) {
1008 al = SSL_AD_DECODE_ERROR;
1009 SSLerr(SSL_F_SSL3_GET_CLIENT_HELLO, SSL_R_LENGTH_MISMATCH);
1010 goto f_err;
1013 s->hit = 0;
1015 * Versions before 0.9.7 always allow clients to resume sessions in
1016 * renegotiation. 0.9.7 and later allow this by default, but optionally
1017 * ignore resumption requests with flag
1018 * SSL_OP_NO_SESSION_RESUMPTION_ON_RENEGOTIATION (it's a new flag rather
1019 * than a change to default behavior so that applications relying on this
1020 * for security won't even compile against older library versions).
1021 * 1.0.1 and later also have a function SSL_renegotiate_abbreviated() to
1022 * request renegotiation but not a new session (s->new_session remains
1023 * unset): for servers, this essentially just means that the
1024 * SSL_OP_NO_SESSION_RESUMPTION_ON_RENEGOTIATION setting will be ignored.
1026 if ((s->new_session
1027 && (s->options & SSL_OP_NO_SESSION_RESUMPTION_ON_RENEGOTIATION))) {
1028 if (!ssl_get_new_session(s, 1))
1029 goto err;
1030 } else {
1031 i = ssl_get_prev_session(s, p, j, d + n);
1033 * Only resume if the session's version matches the negotiated
1034 * version.
1035 * RFC 5246 does not provide much useful advice on resumption
1036 * with a different protocol version. It doesn't forbid it but
1037 * the sanity of such behaviour would be questionable.
1038 * In practice, clients do not accept a version mismatch and
1039 * will abort the handshake with an error.
1041 if (i == 1 && s->version == s->session->ssl_version) { /* previous
1042 * session */
1043 s->hit = 1;
1044 } else if (i == -1)
1045 goto err;
1046 else { /* i == 0 */
1048 if (!ssl_get_new_session(s, 1))
1049 goto err;
1053 p += j;
1055 if (SSL_IS_DTLS(s)) {
1056 /* cookie stuff */
1057 if (p + 1 > d + n) {
1058 al = SSL_AD_DECODE_ERROR;
1059 SSLerr(SSL_F_SSL3_GET_CLIENT_HELLO, SSL_R_LENGTH_TOO_SHORT);
1060 goto f_err;
1062 cookie_len = *(p++);
1064 if (p + cookie_len > d + n) {
1065 al = SSL_AD_DECODE_ERROR;
1066 SSLerr(SSL_F_SSL3_GET_CLIENT_HELLO, SSL_R_LENGTH_TOO_SHORT);
1067 goto f_err;
1071 * The ClientHello may contain a cookie even if the
1072 * HelloVerify message has not been sent--make sure that it
1073 * does not cause an overflow.
1075 if (cookie_len > sizeof(s->d1->rcvd_cookie)) {
1076 /* too much data */
1077 al = SSL_AD_DECODE_ERROR;
1078 SSLerr(SSL_F_SSL3_GET_CLIENT_HELLO, SSL_R_COOKIE_MISMATCH);
1079 goto f_err;
1082 /* verify the cookie if appropriate option is set. */
1083 if ((SSL_get_options(s) & SSL_OP_COOKIE_EXCHANGE) && cookie_len > 0) {
1084 memcpy(s->d1->rcvd_cookie, p, cookie_len);
1086 if (s->ctx->app_verify_cookie_cb != NULL) {
1087 if (s->ctx->app_verify_cookie_cb(s, s->d1->rcvd_cookie,
1088 cookie_len) == 0) {
1089 al = SSL_AD_HANDSHAKE_FAILURE;
1090 SSLerr(SSL_F_SSL3_GET_CLIENT_HELLO,
1091 SSL_R_COOKIE_MISMATCH);
1092 goto f_err;
1094 /* else cookie verification succeeded */
1096 /* default verification */
1097 else if (memcmp(s->d1->rcvd_cookie, s->d1->cookie,
1098 s->d1->cookie_len) != 0) {
1099 al = SSL_AD_HANDSHAKE_FAILURE;
1100 SSLerr(SSL_F_SSL3_GET_CLIENT_HELLO, SSL_R_COOKIE_MISMATCH);
1101 goto f_err;
1103 cookie_valid = 1;
1106 p += cookie_len;
1107 if (s->method->version == DTLS_ANY_VERSION) {
1108 /* Select version to use */
1109 if (s->client_version <= DTLS1_2_VERSION &&
1110 !(s->options & SSL_OP_NO_DTLSv1_2)) {
1111 s->version = DTLS1_2_VERSION;
1112 s->method = DTLSv1_2_server_method();
1113 } else if (tls1_suiteb(s)) {
1114 SSLerr(SSL_F_SSL3_GET_CLIENT_HELLO,
1115 SSL_R_ONLY_DTLS_1_2_ALLOWED_IN_SUITEB_MODE);
1116 s->version = s->client_version;
1117 al = SSL_AD_PROTOCOL_VERSION;
1118 goto f_err;
1119 } else if (s->client_version <= DTLS1_VERSION &&
1120 !(s->options & SSL_OP_NO_DTLSv1)) {
1121 s->version = DTLS1_VERSION;
1122 s->method = DTLSv1_server_method();
1123 } else {
1124 SSLerr(SSL_F_SSL3_GET_CLIENT_HELLO,
1125 SSL_R_WRONG_VERSION_NUMBER);
1126 s->version = s->client_version;
1127 al = SSL_AD_PROTOCOL_VERSION;
1128 goto f_err;
1130 s->session->ssl_version = s->version;
1134 if (p + 2 > d + n) {
1135 al = SSL_AD_DECODE_ERROR;
1136 SSLerr(SSL_F_SSL3_GET_CLIENT_HELLO, SSL_R_LENGTH_TOO_SHORT);
1137 goto f_err;
1139 n2s(p, i);
1141 if (i == 0) {
1142 al = SSL_AD_ILLEGAL_PARAMETER;
1143 SSLerr(SSL_F_SSL3_GET_CLIENT_HELLO, SSL_R_NO_CIPHERS_SPECIFIED);
1144 goto f_err;
1147 /* i bytes of cipher data + 1 byte for compression length later */
1148 if ((p + i + 1) > (d + n)) {
1149 /* not enough data */
1150 al = SSL_AD_DECODE_ERROR;
1151 SSLerr(SSL_F_SSL3_GET_CLIENT_HELLO, SSL_R_LENGTH_MISMATCH);
1152 goto f_err;
1154 if (ssl_bytes_to_cipher_list(s, p, i, &(ciphers)) == NULL) {
1155 goto err;
1157 p += i;
1159 /* If it is a hit, check that the cipher is in the list */
1160 if (s->hit) {
1161 j = 0;
1162 id = s->session->cipher->id;
1164 #ifdef CIPHER_DEBUG
1165 fprintf(stderr, "client sent %d ciphers\n",
1166 sk_SSL_CIPHER_num(ciphers));
1167 #endif
1168 for (i = 0; i < sk_SSL_CIPHER_num(ciphers); i++) {
1169 c = sk_SSL_CIPHER_value(ciphers, i);
1170 #ifdef CIPHER_DEBUG
1171 fprintf(stderr, "client [%2d of %2d]:%s\n",
1172 i, sk_SSL_CIPHER_num(ciphers), SSL_CIPHER_get_name(c));
1173 #endif
1174 if (c->id == id) {
1175 j = 1;
1176 break;
1180 * Disabled because it can be used in a ciphersuite downgrade attack:
1181 * CVE-2010-4180.
1183 #if 0
1184 if (j == 0 && (s->options & SSL_OP_NETSCAPE_REUSE_CIPHER_CHANGE_BUG)
1185 && (sk_SSL_CIPHER_num(ciphers) == 1)) {
1187 * Special case as client bug workaround: the previously used
1188 * cipher may not be in the current list, the client instead
1189 * might be trying to continue using a cipher that before wasn't
1190 * chosen due to server preferences. We'll have to reject the
1191 * connection if the cipher is not enabled, though.
1193 c = sk_SSL_CIPHER_value(ciphers, 0);
1194 if (sk_SSL_CIPHER_find(SSL_get_ciphers(s), c) >= 0) {
1195 s->session->cipher = c;
1196 j = 1;
1199 #endif
1200 if (j == 0) {
1202 * we need to have the cipher in the cipher list if we are asked
1203 * to reuse it
1205 al = SSL_AD_ILLEGAL_PARAMETER;
1206 SSLerr(SSL_F_SSL3_GET_CLIENT_HELLO,
1207 SSL_R_REQUIRED_CIPHER_MISSING);
1208 goto f_err;
1212 /* compression */
1213 i = *(p++);
1214 if ((p + i) > (d + n)) {
1215 /* not enough data */
1216 al = SSL_AD_DECODE_ERROR;
1217 SSLerr(SSL_F_SSL3_GET_CLIENT_HELLO, SSL_R_LENGTH_MISMATCH);
1218 goto f_err;
1220 #ifndef OPENSSL_NO_COMP
1221 q = p;
1222 #endif
1223 for (j = 0; j < i; j++) {
1224 if (p[j] == 0)
1225 break;
1228 p += i;
1229 if (j >= i) {
1230 /* no compress */
1231 al = SSL_AD_DECODE_ERROR;
1232 SSLerr(SSL_F_SSL3_GET_CLIENT_HELLO, SSL_R_NO_COMPRESSION_SPECIFIED);
1233 goto f_err;
1235 #ifndef OPENSSL_NO_TLSEXT
1236 /* TLS extensions */
1237 if (s->version >= SSL3_VERSION) {
1238 if (!ssl_parse_clienthello_tlsext(s, &p, d + n)) {
1239 SSLerr(SSL_F_SSL3_GET_CLIENT_HELLO, SSL_R_PARSE_TLSEXT);
1240 goto err;
1245 * Check if we want to use external pre-shared secret for this handshake
1246 * for not reused session only. We need to generate server_random before
1247 * calling tls_session_secret_cb in order to allow SessionTicket
1248 * processing to use it in key derivation.
1251 unsigned char *pos;
1252 pos = s->s3->server_random;
1253 if (ssl_fill_hello_random(s, 1, pos, SSL3_RANDOM_SIZE) <= 0) {
1254 goto f_err;
1258 if (!s->hit && s->version >= TLS1_VERSION && s->tls_session_secret_cb) {
1259 SSL_CIPHER *pref_cipher = NULL;
1261 s->session->master_key_length = sizeof(s->session->master_key);
1262 if (s->tls_session_secret_cb(s, s->session->master_key,
1263 &s->session->master_key_length, ciphers,
1264 &pref_cipher,
1265 s->tls_session_secret_cb_arg)) {
1266 s->hit = 1;
1267 s->session->ciphers = ciphers;
1268 s->session->verify_result = X509_V_OK;
1270 ciphers = NULL;
1272 /* check if some cipher was preferred by call back */
1273 pref_cipher =
1274 pref_cipher ? pref_cipher : ssl3_choose_cipher(s,
1276 session->ciphers,
1277 SSL_get_ciphers
1278 (s));
1279 if (pref_cipher == NULL) {
1280 al = SSL_AD_HANDSHAKE_FAILURE;
1281 SSLerr(SSL_F_SSL3_GET_CLIENT_HELLO, SSL_R_NO_SHARED_CIPHER);
1282 goto f_err;
1285 s->session->cipher = pref_cipher;
1287 if (s->cipher_list)
1288 sk_SSL_CIPHER_free(s->cipher_list);
1290 if (s->cipher_list_by_id)
1291 sk_SSL_CIPHER_free(s->cipher_list_by_id);
1293 s->cipher_list = sk_SSL_CIPHER_dup(s->session->ciphers);
1294 s->cipher_list_by_id = sk_SSL_CIPHER_dup(s->session->ciphers);
1297 #endif
1300 * Worst case, we will use the NULL compression, but if we have other
1301 * options, we will now look for them. We have i-1 compression
1302 * algorithms from the client, starting at q.
1304 s->s3->tmp.new_compression = NULL;
1305 #ifndef OPENSSL_NO_COMP
1306 /* This only happens if we have a cache hit */
1307 if (s->session->compress_meth != 0) {
1308 int m, comp_id = s->session->compress_meth;
1309 /* Perform sanity checks on resumed compression algorithm */
1310 /* Can't disable compression */
1311 if (s->options & SSL_OP_NO_COMPRESSION) {
1312 SSLerr(SSL_F_SSL3_GET_CLIENT_HELLO,
1313 SSL_R_INCONSISTENT_COMPRESSION);
1314 goto f_err;
1316 /* Look for resumed compression method */
1317 for (m = 0; m < sk_SSL_COMP_num(s->ctx->comp_methods); m++) {
1318 comp = sk_SSL_COMP_value(s->ctx->comp_methods, m);
1319 if (comp_id == comp->id) {
1320 s->s3->tmp.new_compression = comp;
1321 break;
1324 if (s->s3->tmp.new_compression == NULL) {
1325 SSLerr(SSL_F_SSL3_GET_CLIENT_HELLO,
1326 SSL_R_INVALID_COMPRESSION_ALGORITHM);
1327 goto f_err;
1329 /* Look for resumed method in compression list */
1330 for (m = 0; m < i; m++) {
1331 if (q[m] == comp_id)
1332 break;
1334 if (m >= i) {
1335 al = SSL_AD_ILLEGAL_PARAMETER;
1336 SSLerr(SSL_F_SSL3_GET_CLIENT_HELLO,
1337 SSL_R_REQUIRED_COMPRESSSION_ALGORITHM_MISSING);
1338 goto f_err;
1340 } else if (s->hit)
1341 comp = NULL;
1342 else if (!(s->options & SSL_OP_NO_COMPRESSION) && s->ctx->comp_methods) {
1343 /* See if we have a match */
1344 int m, nn, o, v, done = 0;
1346 nn = sk_SSL_COMP_num(s->ctx->comp_methods);
1347 for (m = 0; m < nn; m++) {
1348 comp = sk_SSL_COMP_value(s->ctx->comp_methods, m);
1349 v = comp->id;
1350 for (o = 0; o < i; o++) {
1351 if (v == q[o]) {
1352 done = 1;
1353 break;
1356 if (done)
1357 break;
1359 if (done)
1360 s->s3->tmp.new_compression = comp;
1361 else
1362 comp = NULL;
1364 #else
1366 * If compression is disabled we'd better not try to resume a session
1367 * using compression.
1369 if (s->session->compress_meth != 0) {
1370 SSLerr(SSL_F_SSL3_GET_CLIENT_HELLO, SSL_R_INCONSISTENT_COMPRESSION);
1371 goto f_err;
1373 #endif
1376 * Given s->session->ciphers and SSL_get_ciphers, we must pick a cipher
1379 if (!s->hit) {
1380 #ifdef OPENSSL_NO_COMP
1381 s->session->compress_meth = 0;
1382 #else
1383 s->session->compress_meth = (comp == NULL) ? 0 : comp->id;
1384 #endif
1385 if (s->session->ciphers != NULL)
1386 sk_SSL_CIPHER_free(s->session->ciphers);
1387 s->session->ciphers = ciphers;
1388 if (ciphers == NULL) {
1389 al = SSL_AD_INTERNAL_ERROR;
1390 SSLerr(SSL_F_SSL3_GET_CLIENT_HELLO, ERR_R_INTERNAL_ERROR);
1391 goto f_err;
1393 ciphers = NULL;
1394 if (!tls1_set_server_sigalgs(s)) {
1395 SSLerr(SSL_F_SSL3_GET_CLIENT_HELLO, SSL_R_CLIENTHELLO_TLSEXT);
1396 goto err;
1398 /* Let cert callback update server certificates if required */
1399 retry_cert:
1400 if (s->cert->cert_cb) {
1401 int rv = s->cert->cert_cb(s, s->cert->cert_cb_arg);
1402 if (rv == 0) {
1403 al = SSL_AD_INTERNAL_ERROR;
1404 SSLerr(SSL_F_SSL3_GET_CLIENT_HELLO, SSL_R_CERT_CB_ERROR);
1405 goto f_err;
1407 if (rv < 0) {
1408 s->rwstate = SSL_X509_LOOKUP;
1409 return -1;
1411 s->rwstate = SSL_NOTHING;
1413 c = ssl3_choose_cipher(s, s->session->ciphers, SSL_get_ciphers(s));
1415 if (c == NULL) {
1416 al = SSL_AD_HANDSHAKE_FAILURE;
1417 SSLerr(SSL_F_SSL3_GET_CLIENT_HELLO, SSL_R_NO_SHARED_CIPHER);
1418 goto f_err;
1420 s->s3->tmp.new_cipher = c;
1421 } else {
1422 /* Session-id reuse */
1423 #ifdef REUSE_CIPHER_BUG
1424 STACK_OF(SSL_CIPHER) *sk;
1425 SSL_CIPHER *nc = NULL;
1426 SSL_CIPHER *ec = NULL;
1428 if (s->options & SSL_OP_NETSCAPE_DEMO_CIPHER_CHANGE_BUG) {
1429 sk = s->session->ciphers;
1430 for (i = 0; i < sk_SSL_CIPHER_num(sk); i++) {
1431 c = sk_SSL_CIPHER_value(sk, i);
1432 if (c->algorithm_enc & SSL_eNULL)
1433 nc = c;
1434 if (SSL_C_IS_EXPORT(c))
1435 ec = c;
1437 if (nc != NULL)
1438 s->s3->tmp.new_cipher = nc;
1439 else if (ec != NULL)
1440 s->s3->tmp.new_cipher = ec;
1441 else
1442 s->s3->tmp.new_cipher = s->session->cipher;
1443 } else
1444 #endif
1445 s->s3->tmp.new_cipher = s->session->cipher;
1448 if (!SSL_USE_SIGALGS(s) || !(s->verify_mode & SSL_VERIFY_PEER)) {
1449 if (!ssl3_digest_cached_records(s))
1450 goto f_err;
1454 * we now have the following setup.
1455 * client_random
1456 * cipher_list - our prefered list of ciphers
1457 * ciphers - the clients prefered list of ciphers
1458 * compression - basically ignored right now
1459 * ssl version is set - sslv3
1460 * s->session - The ssl session has been setup.
1461 * s->hit - session reuse flag
1462 * s->tmp.new_cipher - the new cipher to use.
1465 /* Handles TLS extensions that we couldn't check earlier */
1466 if (s->version >= SSL3_VERSION) {
1467 if (ssl_check_clienthello_tlsext_late(s) <= 0) {
1468 SSLerr(SSL_F_SSL3_GET_CLIENT_HELLO, SSL_R_CLIENTHELLO_TLSEXT);
1469 goto err;
1473 ret = cookie_valid ? 2 : 1;
1474 if (0) {
1475 f_err:
1476 ssl3_send_alert(s, SSL3_AL_FATAL, al);
1477 err:
1478 s->state = SSL_ST_ERR;
1481 if (ciphers != NULL)
1482 sk_SSL_CIPHER_free(ciphers);
1483 return ret;
1486 int ssl3_send_server_hello(SSL *s)
1488 unsigned char *buf;
1489 unsigned char *p, *d;
1490 int i, sl;
1491 int al = 0;
1492 unsigned long l;
1494 if (s->state == SSL3_ST_SW_SRVR_HELLO_A) {
1495 buf = (unsigned char *)s->init_buf->data;
1496 #ifdef OPENSSL_NO_TLSEXT
1497 p = s->s3->server_random;
1498 if (ssl_fill_hello_random(s, 1, p, SSL3_RANDOM_SIZE) <= 0) {
1499 s->state = SSL_ST_ERR;
1500 return -1;
1502 #endif
1503 /* Do the message type and length last */
1504 d = p = ssl_handshake_start(s);
1506 *(p++) = s->version >> 8;
1507 *(p++) = s->version & 0xff;
1509 /* Random stuff */
1510 memcpy(p, s->s3->server_random, SSL3_RANDOM_SIZE);
1511 p += SSL3_RANDOM_SIZE;
1514 * There are several cases for the session ID to send
1515 * back in the server hello:
1516 * - For session reuse from the session cache,
1517 * we send back the old session ID.
1518 * - If stateless session reuse (using a session ticket)
1519 * is successful, we send back the client's "session ID"
1520 * (which doesn't actually identify the session).
1521 * - If it is a new session, we send back the new
1522 * session ID.
1523 * - However, if we want the new session to be single-use,
1524 * we send back a 0-length session ID.
1525 * s->hit is non-zero in either case of session reuse,
1526 * so the following won't overwrite an ID that we're supposed
1527 * to send back.
1529 if (!(s->ctx->session_cache_mode & SSL_SESS_CACHE_SERVER)
1530 && !s->hit)
1531 s->session->session_id_length = 0;
1533 sl = s->session->session_id_length;
1534 if (sl > (int)sizeof(s->session->session_id)) {
1535 SSLerr(SSL_F_SSL3_SEND_SERVER_HELLO, ERR_R_INTERNAL_ERROR);
1536 s->state = SSL_ST_ERR;
1537 return -1;
1539 *(p++) = sl;
1540 memcpy(p, s->session->session_id, sl);
1541 p += sl;
1543 /* put the cipher */
1544 i = ssl3_put_cipher_by_char(s->s3->tmp.new_cipher, p);
1545 p += i;
1547 /* put the compression method */
1548 #ifdef OPENSSL_NO_COMP
1549 *(p++) = 0;
1550 #else
1551 if (s->s3->tmp.new_compression == NULL)
1552 *(p++) = 0;
1553 else
1554 *(p++) = s->s3->tmp.new_compression->id;
1555 #endif
1556 #ifndef OPENSSL_NO_TLSEXT
1557 if (ssl_prepare_serverhello_tlsext(s) <= 0) {
1558 SSLerr(SSL_F_SSL3_SEND_SERVER_HELLO, SSL_R_SERVERHELLO_TLSEXT);
1559 s->state = SSL_ST_ERR;
1560 return -1;
1562 if ((p =
1563 ssl_add_serverhello_tlsext(s, p, buf + SSL3_RT_MAX_PLAIN_LENGTH,
1564 &al)) == NULL) {
1565 ssl3_send_alert(s, SSL3_AL_FATAL, al);
1566 SSLerr(SSL_F_SSL3_SEND_SERVER_HELLO, ERR_R_INTERNAL_ERROR);
1567 s->state = SSL_ST_ERR;
1568 return -1;
1570 #endif
1571 /* do the header */
1572 l = (p - d);
1573 ssl_set_handshake_header(s, SSL3_MT_SERVER_HELLO, l);
1574 s->state = SSL3_ST_SW_SRVR_HELLO_B;
1577 /* SSL3_ST_SW_SRVR_HELLO_B */
1578 return ssl_do_write(s);
1581 int ssl3_send_server_done(SSL *s)
1584 if (s->state == SSL3_ST_SW_SRVR_DONE_A) {
1585 ssl_set_handshake_header(s, SSL3_MT_SERVER_DONE, 0);
1586 s->state = SSL3_ST_SW_SRVR_DONE_B;
1589 /* SSL3_ST_SW_SRVR_DONE_B */
1590 return ssl_do_write(s);
1593 int ssl3_send_server_key_exchange(SSL *s)
1595 #ifndef OPENSSL_NO_RSA
1596 unsigned char *q;
1597 int j, num;
1598 RSA *rsa;
1599 unsigned char md_buf[MD5_DIGEST_LENGTH + SHA_DIGEST_LENGTH];
1600 unsigned int u;
1601 #endif
1602 #ifndef OPENSSL_NO_DH
1603 DH *dh = NULL, *dhp;
1604 #endif
1605 #ifndef OPENSSL_NO_ECDH
1606 EC_KEY *ecdh = NULL, *ecdhp;
1607 unsigned char *encodedPoint = NULL;
1608 int encodedlen = 0;
1609 int curve_id = 0;
1610 BN_CTX *bn_ctx = NULL;
1611 #endif
1612 EVP_PKEY *pkey;
1613 const EVP_MD *md = NULL;
1614 unsigned char *p, *d;
1615 int al, i;
1616 unsigned long type;
1617 int n;
1618 CERT *cert;
1619 BIGNUM *r[4];
1620 int nr[4], kn;
1621 BUF_MEM *buf;
1622 EVP_MD_CTX md_ctx;
1624 EVP_MD_CTX_init(&md_ctx);
1625 if (s->state == SSL3_ST_SW_KEY_EXCH_A) {
1626 type = s->s3->tmp.new_cipher->algorithm_mkey;
1627 cert = s->cert;
1629 buf = s->init_buf;
1631 r[0] = r[1] = r[2] = r[3] = NULL;
1632 n = 0;
1633 #ifndef OPENSSL_NO_RSA
1634 if (type & SSL_kRSA) {
1635 rsa = cert->rsa_tmp;
1636 if ((rsa == NULL) && (s->cert->rsa_tmp_cb != NULL)) {
1637 rsa = s->cert->rsa_tmp_cb(s,
1638 SSL_C_IS_EXPORT(s->s3->
1639 tmp.new_cipher),
1640 SSL_C_EXPORT_PKEYLENGTH(s->s3->
1641 tmp.new_cipher));
1642 if (rsa == NULL) {
1643 al = SSL_AD_HANDSHAKE_FAILURE;
1644 SSLerr(SSL_F_SSL3_SEND_SERVER_KEY_EXCHANGE,
1645 SSL_R_ERROR_GENERATING_TMP_RSA_KEY);
1646 goto f_err;
1648 RSA_up_ref(rsa);
1649 cert->rsa_tmp = rsa;
1651 if (rsa == NULL) {
1652 al = SSL_AD_HANDSHAKE_FAILURE;
1653 SSLerr(SSL_F_SSL3_SEND_SERVER_KEY_EXCHANGE,
1654 SSL_R_MISSING_TMP_RSA_KEY);
1655 goto f_err;
1657 r[0] = rsa->n;
1658 r[1] = rsa->e;
1659 s->s3->tmp.use_rsa_tmp = 1;
1660 } else
1661 #endif
1662 #ifndef OPENSSL_NO_DH
1663 if (type & SSL_kEDH) {
1664 dhp = cert->dh_tmp;
1665 if ((dhp == NULL) && (s->cert->dh_tmp_cb != NULL))
1666 dhp = s->cert->dh_tmp_cb(s,
1667 SSL_C_IS_EXPORT(s->s3->
1668 tmp.new_cipher),
1669 SSL_C_EXPORT_PKEYLENGTH(s->s3->
1670 tmp.new_cipher));
1671 if (dhp == NULL) {
1672 al = SSL_AD_HANDSHAKE_FAILURE;
1673 SSLerr(SSL_F_SSL3_SEND_SERVER_KEY_EXCHANGE,
1674 SSL_R_MISSING_TMP_DH_KEY);
1675 goto f_err;
1678 if (s->s3->tmp.dh != NULL) {
1679 SSLerr(SSL_F_SSL3_SEND_SERVER_KEY_EXCHANGE,
1680 ERR_R_INTERNAL_ERROR);
1681 goto err;
1684 if ((dh = DHparams_dup(dhp)) == NULL) {
1685 SSLerr(SSL_F_SSL3_SEND_SERVER_KEY_EXCHANGE, ERR_R_DH_LIB);
1686 goto err;
1689 s->s3->tmp.dh = dh;
1690 if (!DH_generate_key(dh)) {
1691 SSLerr(SSL_F_SSL3_SEND_SERVER_KEY_EXCHANGE, ERR_R_DH_LIB);
1692 goto err;
1694 r[0] = dh->p;
1695 r[1] = dh->g;
1696 r[2] = dh->pub_key;
1697 } else
1698 #endif
1699 #ifndef OPENSSL_NO_ECDH
1700 if (type & SSL_kEECDH) {
1701 const EC_GROUP *group;
1703 ecdhp = cert->ecdh_tmp;
1704 if (s->cert->ecdh_tmp_auto) {
1705 /* Get NID of appropriate shared curve */
1706 int nid = tls1_shared_curve(s, -2);
1707 if (nid != NID_undef)
1708 ecdhp = EC_KEY_new_by_curve_name(nid);
1709 } else if ((ecdhp == NULL) && s->cert->ecdh_tmp_cb) {
1710 ecdhp = s->cert->ecdh_tmp_cb(s,
1711 SSL_C_IS_EXPORT(s->s3->
1712 tmp.new_cipher),
1713 SSL_C_EXPORT_PKEYLENGTH(s->
1714 s3->tmp.new_cipher));
1716 if (ecdhp == NULL) {
1717 al = SSL_AD_HANDSHAKE_FAILURE;
1718 SSLerr(SSL_F_SSL3_SEND_SERVER_KEY_EXCHANGE,
1719 SSL_R_MISSING_TMP_ECDH_KEY);
1720 goto f_err;
1723 if (s->s3->tmp.ecdh != NULL) {
1724 SSLerr(SSL_F_SSL3_SEND_SERVER_KEY_EXCHANGE,
1725 ERR_R_INTERNAL_ERROR);
1726 goto err;
1729 /* Duplicate the ECDH structure. */
1730 if (ecdhp == NULL) {
1731 SSLerr(SSL_F_SSL3_SEND_SERVER_KEY_EXCHANGE, ERR_R_ECDH_LIB);
1732 goto err;
1734 if (s->cert->ecdh_tmp_auto)
1735 ecdh = ecdhp;
1736 else if ((ecdh = EC_KEY_dup(ecdhp)) == NULL) {
1737 SSLerr(SSL_F_SSL3_SEND_SERVER_KEY_EXCHANGE, ERR_R_ECDH_LIB);
1738 goto err;
1741 s->s3->tmp.ecdh = ecdh;
1742 if ((EC_KEY_get0_public_key(ecdh) == NULL) ||
1743 (EC_KEY_get0_private_key(ecdh) == NULL) ||
1744 (s->options & SSL_OP_SINGLE_ECDH_USE)) {
1745 if (!EC_KEY_generate_key(ecdh)) {
1746 SSLerr(SSL_F_SSL3_SEND_SERVER_KEY_EXCHANGE,
1747 ERR_R_ECDH_LIB);
1748 goto err;
1752 if (((group = EC_KEY_get0_group(ecdh)) == NULL) ||
1753 (EC_KEY_get0_public_key(ecdh) == NULL) ||
1754 (EC_KEY_get0_private_key(ecdh) == NULL)) {
1755 SSLerr(SSL_F_SSL3_SEND_SERVER_KEY_EXCHANGE, ERR_R_ECDH_LIB);
1756 goto err;
1759 if (SSL_C_IS_EXPORT(s->s3->tmp.new_cipher) &&
1760 (EC_GROUP_get_degree(group) > 163)) {
1761 SSLerr(SSL_F_SSL3_SEND_SERVER_KEY_EXCHANGE,
1762 SSL_R_ECGROUP_TOO_LARGE_FOR_CIPHER);
1763 goto err;
1767 * XXX: For now, we only support ephemeral ECDH keys over named
1768 * (not generic) curves. For supported named curves, curve_id is
1769 * non-zero.
1771 if ((curve_id =
1772 tls1_ec_nid2curve_id(EC_GROUP_get_curve_name(group)))
1773 == 0) {
1774 SSLerr(SSL_F_SSL3_SEND_SERVER_KEY_EXCHANGE,
1775 SSL_R_UNSUPPORTED_ELLIPTIC_CURVE);
1776 goto err;
1780 * Encode the public key. First check the size of encoding and
1781 * allocate memory accordingly.
1783 encodedlen = EC_POINT_point2oct(group,
1784 EC_KEY_get0_public_key(ecdh),
1785 POINT_CONVERSION_UNCOMPRESSED,
1786 NULL, 0, NULL);
1788 encodedPoint = (unsigned char *)
1789 OPENSSL_malloc(encodedlen * sizeof(unsigned char));
1790 bn_ctx = BN_CTX_new();
1791 if ((encodedPoint == NULL) || (bn_ctx == NULL)) {
1792 SSLerr(SSL_F_SSL3_SEND_SERVER_KEY_EXCHANGE,
1793 ERR_R_MALLOC_FAILURE);
1794 goto err;
1797 encodedlen = EC_POINT_point2oct(group,
1798 EC_KEY_get0_public_key(ecdh),
1799 POINT_CONVERSION_UNCOMPRESSED,
1800 encodedPoint, encodedlen, bn_ctx);
1802 if (encodedlen == 0) {
1803 SSLerr(SSL_F_SSL3_SEND_SERVER_KEY_EXCHANGE, ERR_R_ECDH_LIB);
1804 goto err;
1807 BN_CTX_free(bn_ctx);
1808 bn_ctx = NULL;
1811 * XXX: For now, we only support named (not generic) curves in
1812 * ECDH ephemeral key exchanges. In this situation, we need four
1813 * additional bytes to encode the entire ServerECDHParams
1814 * structure.
1816 n = 4 + encodedlen;
1819 * We'll generate the serverKeyExchange message explicitly so we
1820 * can set these to NULLs
1822 r[0] = NULL;
1823 r[1] = NULL;
1824 r[2] = NULL;
1825 r[3] = NULL;
1826 } else
1827 #endif /* !OPENSSL_NO_ECDH */
1828 #ifndef OPENSSL_NO_PSK
1829 if (type & SSL_kPSK) {
1831 * reserve size for record length and PSK identity hint
1833 n += 2 + strlen(s->ctx->psk_identity_hint);
1834 } else
1835 #endif /* !OPENSSL_NO_PSK */
1836 #ifndef OPENSSL_NO_SRP
1837 if (type & SSL_kSRP) {
1838 if ((s->srp_ctx.N == NULL) ||
1839 (s->srp_ctx.g == NULL) ||
1840 (s->srp_ctx.s == NULL) || (s->srp_ctx.B == NULL)) {
1841 SSLerr(SSL_F_SSL3_SEND_SERVER_KEY_EXCHANGE,
1842 SSL_R_MISSING_SRP_PARAM);
1843 goto err;
1845 r[0] = s->srp_ctx.N;
1846 r[1] = s->srp_ctx.g;
1847 r[2] = s->srp_ctx.s;
1848 r[3] = s->srp_ctx.B;
1849 } else
1850 #endif
1852 al = SSL_AD_HANDSHAKE_FAILURE;
1853 SSLerr(SSL_F_SSL3_SEND_SERVER_KEY_EXCHANGE,
1854 SSL_R_UNKNOWN_KEY_EXCHANGE_TYPE);
1855 goto f_err;
1857 for (i = 0; i < 4 && r[i] != NULL; i++) {
1858 nr[i] = BN_num_bytes(r[i]);
1859 #ifndef OPENSSL_NO_SRP
1860 if ((i == 2) && (type & SSL_kSRP))
1861 n += 1 + nr[i];
1862 else
1863 #endif
1864 n += 2 + nr[i];
1867 if (!(s->s3->tmp.new_cipher->algorithm_auth & (SSL_aNULL | SSL_aSRP))
1868 && !(s->s3->tmp.new_cipher->algorithm_mkey & SSL_kPSK)) {
1869 if ((pkey = ssl_get_sign_pkey(s, s->s3->tmp.new_cipher, &md))
1870 == NULL) {
1871 al = SSL_AD_DECODE_ERROR;
1872 goto f_err;
1874 kn = EVP_PKEY_size(pkey);
1875 } else {
1876 pkey = NULL;
1877 kn = 0;
1880 if (!BUF_MEM_grow_clean(buf, n + SSL_HM_HEADER_LENGTH(s) + kn)) {
1881 SSLerr(SSL_F_SSL3_SEND_SERVER_KEY_EXCHANGE, ERR_LIB_BUF);
1882 goto err;
1884 d = p = ssl_handshake_start(s);
1886 for (i = 0; i < 4 && r[i] != NULL; i++) {
1887 #ifndef OPENSSL_NO_SRP
1888 if ((i == 2) && (type & SSL_kSRP)) {
1889 *p = nr[i];
1890 p++;
1891 } else
1892 #endif
1893 s2n(nr[i], p);
1894 BN_bn2bin(r[i], p);
1895 p += nr[i];
1898 #ifndef OPENSSL_NO_ECDH
1899 if (type & SSL_kEECDH) {
1901 * XXX: For now, we only support named (not generic) curves. In
1902 * this situation, the serverKeyExchange message has: [1 byte
1903 * CurveType], [2 byte CurveName] [1 byte length of encoded
1904 * point], followed by the actual encoded point itself
1906 *p = NAMED_CURVE_TYPE;
1907 p += 1;
1908 *p = 0;
1909 p += 1;
1910 *p = curve_id;
1911 p += 1;
1912 *p = encodedlen;
1913 p += 1;
1914 memcpy((unsigned char *)p,
1915 (unsigned char *)encodedPoint, encodedlen);
1916 OPENSSL_free(encodedPoint);
1917 encodedPoint = NULL;
1918 p += encodedlen;
1920 #endif
1922 #ifndef OPENSSL_NO_PSK
1923 if (type & SSL_kPSK) {
1924 /* copy PSK identity hint */
1925 s2n(strlen(s->ctx->psk_identity_hint), p);
1926 strncpy((char *)p, s->ctx->psk_identity_hint,
1927 strlen(s->ctx->psk_identity_hint));
1928 p += strlen(s->ctx->psk_identity_hint);
1930 #endif
1932 /* not anonymous */
1933 if (pkey != NULL) {
1935 * n is the length of the params, they start at &(d[4]) and p
1936 * points to the space at the end.
1938 #ifndef OPENSSL_NO_RSA
1939 if (pkey->type == EVP_PKEY_RSA && !SSL_USE_SIGALGS(s)) {
1940 q = md_buf;
1941 j = 0;
1942 for (num = 2; num > 0; num--) {
1943 EVP_MD_CTX_set_flags(&md_ctx,
1944 EVP_MD_CTX_FLAG_NON_FIPS_ALLOW);
1945 if (EVP_DigestInit_ex(&md_ctx,
1946 (num == 2) ? s->ctx->md5
1947 : s->ctx->sha1,
1948 NULL) <= 0
1949 || EVP_DigestUpdate(&md_ctx, &(s->s3->client_random[0]),
1950 SSL3_RANDOM_SIZE) <= 0
1951 || EVP_DigestUpdate(&md_ctx, &(s->s3->server_random[0]),
1952 SSL3_RANDOM_SIZE) <= 0
1953 || EVP_DigestUpdate(&md_ctx, d, n) <= 0
1954 || EVP_DigestFinal_ex(&md_ctx, q,
1955 (unsigned int *)&i) <= 0) {
1956 SSLerr(SSL_F_SSL3_SEND_SERVER_KEY_EXCHANGE,
1957 ERR_LIB_EVP);
1958 al = SSL_AD_INTERNAL_ERROR;
1959 goto f_err;
1961 q += i;
1962 j += i;
1964 if (RSA_sign(NID_md5_sha1, md_buf, j,
1965 &(p[2]), &u, pkey->pkey.rsa) <= 0) {
1966 SSLerr(SSL_F_SSL3_SEND_SERVER_KEY_EXCHANGE, ERR_LIB_RSA);
1967 goto err;
1969 s2n(u, p);
1970 n += u + 2;
1971 } else
1972 #endif
1973 if (md) {
1974 /* send signature algorithm */
1975 if (SSL_USE_SIGALGS(s)) {
1976 if (!tls12_get_sigandhash(p, pkey, md)) {
1977 /* Should never happen */
1978 al = SSL_AD_INTERNAL_ERROR;
1979 SSLerr(SSL_F_SSL3_SEND_SERVER_KEY_EXCHANGE,
1980 ERR_R_INTERNAL_ERROR);
1981 goto f_err;
1983 p += 2;
1985 #ifdef SSL_DEBUG
1986 fprintf(stderr, "Using hash %s\n", EVP_MD_name(md));
1987 #endif
1988 if (EVP_SignInit_ex(&md_ctx, md, NULL) <= 0
1989 || EVP_SignUpdate(&md_ctx, &(s->s3->client_random[0]),
1990 SSL3_RANDOM_SIZE) <= 0
1991 || EVP_SignUpdate(&md_ctx, &(s->s3->server_random[0]),
1992 SSL3_RANDOM_SIZE) <= 0
1993 || EVP_SignUpdate(&md_ctx, d, n) <= 0
1994 || EVP_SignFinal(&md_ctx, &(p[2]),
1995 (unsigned int *)&i, pkey) <= 0) {
1996 SSLerr(SSL_F_SSL3_SEND_SERVER_KEY_EXCHANGE, ERR_LIB_EVP);
1997 al = SSL_AD_INTERNAL_ERROR;
1998 goto f_err;
2000 s2n(i, p);
2001 n += i + 2;
2002 if (SSL_USE_SIGALGS(s))
2003 n += 2;
2004 } else {
2005 /* Is this error check actually needed? */
2006 al = SSL_AD_HANDSHAKE_FAILURE;
2007 SSLerr(SSL_F_SSL3_SEND_SERVER_KEY_EXCHANGE,
2008 SSL_R_UNKNOWN_PKEY_TYPE);
2009 goto f_err;
2013 ssl_set_handshake_header(s, SSL3_MT_SERVER_KEY_EXCHANGE, n);
2016 s->state = SSL3_ST_SW_KEY_EXCH_B;
2017 EVP_MD_CTX_cleanup(&md_ctx);
2018 return ssl_do_write(s);
2019 f_err:
2020 ssl3_send_alert(s, SSL3_AL_FATAL, al);
2021 err:
2022 #ifndef OPENSSL_NO_ECDH
2023 if (encodedPoint != NULL)
2024 OPENSSL_free(encodedPoint);
2025 BN_CTX_free(bn_ctx);
2026 #endif
2027 EVP_MD_CTX_cleanup(&md_ctx);
2028 s->state = SSL_ST_ERR;
2029 return (-1);
2032 int ssl3_send_certificate_request(SSL *s)
2034 unsigned char *p, *d;
2035 int i, j, nl, off, n;
2036 STACK_OF(X509_NAME) *sk = NULL;
2037 X509_NAME *name;
2038 BUF_MEM *buf;
2040 if (s->state == SSL3_ST_SW_CERT_REQ_A) {
2041 buf = s->init_buf;
2043 d = p = ssl_handshake_start(s);
2045 /* get the list of acceptable cert types */
2046 p++;
2047 n = ssl3_get_req_cert_type(s, p);
2048 d[0] = n;
2049 p += n;
2050 n++;
2052 if (SSL_USE_SIGALGS(s)) {
2053 const unsigned char *psigs;
2054 nl = tls12_get_psigalgs(s, &psigs);
2055 s2n(nl, p);
2056 memcpy(p, psigs, nl);
2057 p += nl;
2058 n += nl + 2;
2061 off = n;
2062 p += 2;
2063 n += 2;
2065 sk = SSL_get_client_CA_list(s);
2066 nl = 0;
2067 if (sk != NULL) {
2068 for (i = 0; i < sk_X509_NAME_num(sk); i++) {
2069 name = sk_X509_NAME_value(sk, i);
2070 j = i2d_X509_NAME(name, NULL);
2071 if (!BUF_MEM_grow_clean
2072 (buf, SSL_HM_HEADER_LENGTH(s) + n + j + 2)) {
2073 SSLerr(SSL_F_SSL3_SEND_CERTIFICATE_REQUEST,
2074 ERR_R_BUF_LIB);
2075 goto err;
2077 p = ssl_handshake_start(s) + n;
2078 if (!(s->options & SSL_OP_NETSCAPE_CA_DN_BUG)) {
2079 s2n(j, p);
2080 i2d_X509_NAME(name, &p);
2081 n += 2 + j;
2082 nl += 2 + j;
2083 } else {
2084 d = p;
2085 i2d_X509_NAME(name, &p);
2086 j -= 2;
2087 s2n(j, d);
2088 j += 2;
2089 n += j;
2090 nl += j;
2094 /* else no CA names */
2095 p = ssl_handshake_start(s) + off;
2096 s2n(nl, p);
2098 ssl_set_handshake_header(s, SSL3_MT_CERTIFICATE_REQUEST, n);
2100 #ifdef NETSCAPE_HANG_BUG
2101 if (!SSL_IS_DTLS(s)) {
2102 if (!BUF_MEM_grow_clean(buf, s->init_num + 4)) {
2103 SSLerr(SSL_F_SSL3_SEND_CERTIFICATE_REQUEST, ERR_R_BUF_LIB);
2104 goto err;
2106 p = (unsigned char *)s->init_buf->data + s->init_num;
2107 /* do the header */
2108 *(p++) = SSL3_MT_SERVER_DONE;
2109 *(p++) = 0;
2110 *(p++) = 0;
2111 *(p++) = 0;
2112 s->init_num += 4;
2114 #endif
2116 s->state = SSL3_ST_SW_CERT_REQ_B;
2119 /* SSL3_ST_SW_CERT_REQ_B */
2120 return ssl_do_write(s);
2121 err:
2122 s->state = SSL_ST_ERR;
2123 return (-1);
2126 int ssl3_get_client_key_exchange(SSL *s)
2128 int i, al, ok;
2129 long n;
2130 unsigned long alg_k;
2131 unsigned char *p;
2132 #ifndef OPENSSL_NO_RSA
2133 RSA *rsa = NULL;
2134 EVP_PKEY *pkey = NULL;
2135 #endif
2136 #ifndef OPENSSL_NO_DH
2137 BIGNUM *pub = NULL;
2138 DH *dh_srvr, *dh_clnt = NULL;
2139 #endif
2140 #ifndef OPENSSL_NO_KRB5
2141 KSSL_ERR kssl_err;
2142 #endif /* OPENSSL_NO_KRB5 */
2144 #ifndef OPENSSL_NO_ECDH
2145 EC_KEY *srvr_ecdh = NULL;
2146 EVP_PKEY *clnt_pub_pkey = NULL;
2147 EC_POINT *clnt_ecpoint = NULL;
2148 BN_CTX *bn_ctx = NULL;
2149 #endif
2151 n = s->method->ssl_get_message(s,
2152 SSL3_ST_SR_KEY_EXCH_A,
2153 SSL3_ST_SR_KEY_EXCH_B,
2154 SSL3_MT_CLIENT_KEY_EXCHANGE, 2048, &ok);
2156 if (!ok)
2157 return ((int)n);
2158 p = (unsigned char *)s->init_msg;
2160 alg_k = s->s3->tmp.new_cipher->algorithm_mkey;
2162 #ifndef OPENSSL_NO_RSA
2163 if (alg_k & SSL_kRSA) {
2164 unsigned char rand_premaster_secret[SSL_MAX_MASTER_KEY_LENGTH];
2165 int decrypt_len;
2166 unsigned char decrypt_good, version_good;
2167 size_t j;
2169 /* FIX THIS UP EAY EAY EAY EAY */
2170 if (s->s3->tmp.use_rsa_tmp) {
2171 if ((s->cert != NULL) && (s->cert->rsa_tmp != NULL))
2172 rsa = s->cert->rsa_tmp;
2174 * Don't do a callback because rsa_tmp should be sent already
2176 if (rsa == NULL) {
2177 al = SSL_AD_HANDSHAKE_FAILURE;
2178 SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,
2179 SSL_R_MISSING_TMP_RSA_PKEY);
2180 goto f_err;
2183 } else {
2184 pkey = s->cert->pkeys[SSL_PKEY_RSA_ENC].privatekey;
2185 if ((pkey == NULL) ||
2186 (pkey->type != EVP_PKEY_RSA) || (pkey->pkey.rsa == NULL)) {
2187 al = SSL_AD_HANDSHAKE_FAILURE;
2188 SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,
2189 SSL_R_MISSING_RSA_CERTIFICATE);
2190 goto f_err;
2192 rsa = pkey->pkey.rsa;
2195 /* TLS and [incidentally] DTLS{0xFEFF} */
2196 if (s->version > SSL3_VERSION && s->version != DTLS1_BAD_VER) {
2197 n2s(p, i);
2198 if (n != i + 2) {
2199 if (!(s->options & SSL_OP_TLS_D5_BUG)) {
2200 al = SSL_AD_DECODE_ERROR;
2201 SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,
2202 SSL_R_TLS_RSA_ENCRYPTED_VALUE_LENGTH_IS_WRONG);
2203 goto f_err;
2204 } else
2205 p -= 2;
2206 } else
2207 n = i;
2211 * Reject overly short RSA ciphertext because we want to be sure
2212 * that the buffer size makes it safe to iterate over the entire
2213 * size of a premaster secret (SSL_MAX_MASTER_KEY_LENGTH). The
2214 * actual expected size is larger due to RSA padding, but the
2215 * bound is sufficient to be safe.
2217 if (n < SSL_MAX_MASTER_KEY_LENGTH) {
2218 al = SSL_AD_DECRYPT_ERROR;
2219 SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,
2220 SSL_R_TLS_RSA_ENCRYPTED_VALUE_LENGTH_IS_WRONG);
2221 goto f_err;
2225 * We must not leak whether a decryption failure occurs because of
2226 * Bleichenbacher's attack on PKCS #1 v1.5 RSA padding (see RFC 2246,
2227 * section 7.4.7.1). The code follows that advice of the TLS RFC and
2228 * generates a random premaster secret for the case that the decrypt
2229 * fails. See https://tools.ietf.org/html/rfc5246#section-7.4.7.1
2233 * should be RAND_bytes, but we cannot work around a failure.
2235 if (RAND_pseudo_bytes(rand_premaster_secret,
2236 sizeof(rand_premaster_secret)) <= 0)
2237 goto err;
2238 decrypt_len =
2239 RSA_private_decrypt((int)n, p, p, rsa, RSA_PKCS1_PADDING);
2240 ERR_clear_error();
2243 * decrypt_len should be SSL_MAX_MASTER_KEY_LENGTH. decrypt_good will
2244 * be 0xff if so and zero otherwise.
2246 decrypt_good =
2247 constant_time_eq_int_8(decrypt_len, SSL_MAX_MASTER_KEY_LENGTH);
2250 * If the version in the decrypted pre-master secret is correct then
2251 * version_good will be 0xff, otherwise it'll be zero. The
2252 * Klima-Pokorny-Rosa extension of Bleichenbacher's attack
2253 * (http://eprint.iacr.org/2003/052/) exploits the version number
2254 * check as a "bad version oracle". Thus version checks are done in
2255 * constant time and are treated like any other decryption error.
2257 version_good =
2258 constant_time_eq_8(p[0], (unsigned)(s->client_version >> 8));
2259 version_good &=
2260 constant_time_eq_8(p[1], (unsigned)(s->client_version & 0xff));
2263 * The premaster secret must contain the same version number as the
2264 * ClientHello to detect version rollback attacks (strangely, the
2265 * protocol does not offer such protection for DH ciphersuites).
2266 * However, buggy clients exist that send the negotiated protocol
2267 * version instead if the server does not support the requested
2268 * protocol version. If SSL_OP_TLS_ROLLBACK_BUG is set, tolerate such
2269 * clients.
2271 if (s->options & SSL_OP_TLS_ROLLBACK_BUG) {
2272 unsigned char workaround_good;
2273 workaround_good =
2274 constant_time_eq_8(p[0], (unsigned)(s->version >> 8));
2275 workaround_good &=
2276 constant_time_eq_8(p[1], (unsigned)(s->version & 0xff));
2277 version_good |= workaround_good;
2281 * Both decryption and version must be good for decrypt_good to
2282 * remain non-zero (0xff).
2284 decrypt_good &= version_good;
2287 * Now copy rand_premaster_secret over from p using
2288 * decrypt_good_mask. If decryption failed, then p does not
2289 * contain valid plaintext, however, a check above guarantees
2290 * it is still sufficiently large to read from.
2292 for (j = 0; j < sizeof(rand_premaster_secret); j++) {
2293 p[j] = constant_time_select_8(decrypt_good, p[j],
2294 rand_premaster_secret[j]);
2297 s->session->master_key_length =
2298 s->method->ssl3_enc->generate_master_secret(s,
2300 session->master_key,
2302 sizeof
2303 (rand_premaster_secret));
2304 OPENSSL_cleanse(p, sizeof(rand_premaster_secret));
2305 } else
2306 #endif
2307 #ifndef OPENSSL_NO_DH
2308 if (alg_k & (SSL_kEDH | SSL_kDHr | SSL_kDHd)) {
2309 int idx = -1;
2310 EVP_PKEY *skey = NULL;
2311 if (n > 1) {
2312 n2s(p, i);
2313 } else {
2314 if (alg_k & SSL_kDHE) {
2315 al = SSL_AD_HANDSHAKE_FAILURE;
2316 SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,
2317 SSL_R_DH_PUBLIC_VALUE_LENGTH_IS_WRONG);
2318 goto f_err;
2320 i = 0;
2322 if (n && n != i + 2) {
2323 if (!(s->options & SSL_OP_SSLEAY_080_CLIENT_DH_BUG)) {
2324 SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,
2325 SSL_R_DH_PUBLIC_VALUE_LENGTH_IS_WRONG);
2326 goto err;
2327 } else {
2328 p -= 2;
2329 i = (int)n;
2332 if (alg_k & SSL_kDHr)
2333 idx = SSL_PKEY_DH_RSA;
2334 else if (alg_k & SSL_kDHd)
2335 idx = SSL_PKEY_DH_DSA;
2336 if (idx >= 0) {
2337 skey = s->cert->pkeys[idx].privatekey;
2338 if ((skey == NULL) ||
2339 (skey->type != EVP_PKEY_DH) || (skey->pkey.dh == NULL)) {
2340 al = SSL_AD_HANDSHAKE_FAILURE;
2341 SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,
2342 SSL_R_MISSING_RSA_CERTIFICATE);
2343 goto f_err;
2345 dh_srvr = skey->pkey.dh;
2346 } else if (s->s3->tmp.dh == NULL) {
2347 al = SSL_AD_HANDSHAKE_FAILURE;
2348 SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,
2349 SSL_R_MISSING_TMP_DH_KEY);
2350 goto f_err;
2351 } else
2352 dh_srvr = s->s3->tmp.dh;
2354 if (n == 0L) {
2355 /* Get pubkey from cert */
2356 EVP_PKEY *clkey = X509_get_pubkey(s->session->peer);
2357 if (clkey) {
2358 if (EVP_PKEY_cmp_parameters(clkey, skey) == 1)
2359 dh_clnt = EVP_PKEY_get1_DH(clkey);
2361 if (dh_clnt == NULL) {
2362 al = SSL_AD_HANDSHAKE_FAILURE;
2363 SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,
2364 SSL_R_MISSING_TMP_DH_KEY);
2365 goto f_err;
2367 EVP_PKEY_free(clkey);
2368 pub = dh_clnt->pub_key;
2369 } else
2370 pub = BN_bin2bn(p, i, NULL);
2371 if (pub == NULL) {
2372 SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE, SSL_R_BN_LIB);
2373 goto err;
2376 i = DH_compute_key(p, pub, dh_srvr);
2378 if (i <= 0) {
2379 SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE, ERR_R_DH_LIB);
2380 BN_clear_free(pub);
2381 goto err;
2384 DH_free(s->s3->tmp.dh);
2385 s->s3->tmp.dh = NULL;
2386 if (dh_clnt)
2387 DH_free(dh_clnt);
2388 else
2389 BN_clear_free(pub);
2390 pub = NULL;
2391 s->session->master_key_length =
2392 s->method->ssl3_enc->generate_master_secret(s,
2394 session->master_key,
2395 p, i);
2396 OPENSSL_cleanse(p, i);
2397 if (dh_clnt)
2398 return 2;
2399 } else
2400 #endif
2401 #ifndef OPENSSL_NO_KRB5
2402 if (alg_k & SSL_kKRB5) {
2403 krb5_error_code krb5rc;
2404 krb5_data enc_ticket;
2405 krb5_data authenticator;
2406 krb5_data enc_pms;
2407 KSSL_CTX *kssl_ctx = s->kssl_ctx;
2408 EVP_CIPHER_CTX ciph_ctx;
2409 const EVP_CIPHER *enc = NULL;
2410 unsigned char iv[EVP_MAX_IV_LENGTH];
2411 unsigned char pms[SSL_MAX_MASTER_KEY_LENGTH + EVP_MAX_BLOCK_LENGTH];
2412 int padl, outl;
2413 krb5_timestamp authtime = 0;
2414 krb5_ticket_times ttimes;
2415 int kerr = 0;
2417 EVP_CIPHER_CTX_init(&ciph_ctx);
2419 if (!kssl_ctx)
2420 kssl_ctx = kssl_ctx_new();
2422 n2s(p, i);
2423 enc_ticket.length = i;
2425 if (n < (long)(enc_ticket.length + 6)) {
2426 SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,
2427 SSL_R_DATA_LENGTH_TOO_LONG);
2428 goto err;
2431 enc_ticket.data = (char *)p;
2432 p += enc_ticket.length;
2434 n2s(p, i);
2435 authenticator.length = i;
2437 if (n < (long)(enc_ticket.length + authenticator.length + 6)) {
2438 SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,
2439 SSL_R_DATA_LENGTH_TOO_LONG);
2440 goto err;
2443 authenticator.data = (char *)p;
2444 p += authenticator.length;
2446 n2s(p, i);
2447 enc_pms.length = i;
2448 enc_pms.data = (char *)p;
2449 p += enc_pms.length;
2452 * Note that the length is checked again below, ** after decryption
2454 if (enc_pms.length > sizeof pms) {
2455 SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,
2456 SSL_R_DATA_LENGTH_TOO_LONG);
2457 goto err;
2460 if (n != (long)(enc_ticket.length + authenticator.length +
2461 enc_pms.length + 6)) {
2462 SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,
2463 SSL_R_DATA_LENGTH_TOO_LONG);
2464 goto err;
2467 if ((krb5rc = kssl_sget_tkt(kssl_ctx, &enc_ticket, &ttimes,
2468 &kssl_err)) != 0) {
2469 # ifdef KSSL_DEBUG
2470 fprintf(stderr, "kssl_sget_tkt rtn %d [%d]\n",
2471 krb5rc, kssl_err.reason);
2472 if (kssl_err.text)
2473 fprintf(stderr, "kssl_err text= %s\n", kssl_err.text);
2474 # endif /* KSSL_DEBUG */
2475 SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE, kssl_err.reason);
2476 goto err;
2480 * Note: no authenticator is not considered an error, ** but will
2481 * return authtime == 0.
2483 if ((krb5rc = kssl_check_authent(kssl_ctx, &authenticator,
2484 &authtime, &kssl_err)) != 0) {
2485 # ifdef KSSL_DEBUG
2486 fprintf(stderr, "kssl_check_authent rtn %d [%d]\n",
2487 krb5rc, kssl_err.reason);
2488 if (kssl_err.text)
2489 fprintf(stderr, "kssl_err text= %s\n", kssl_err.text);
2490 # endif /* KSSL_DEBUG */
2491 SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE, kssl_err.reason);
2492 goto err;
2495 if ((krb5rc = kssl_validate_times(authtime, &ttimes)) != 0) {
2496 SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE, krb5rc);
2497 goto err;
2499 # ifdef KSSL_DEBUG
2500 kssl_ctx_show(kssl_ctx);
2501 # endif /* KSSL_DEBUG */
2503 enc = kssl_map_enc(kssl_ctx->enctype);
2504 if (enc == NULL)
2505 goto err;
2507 memset(iv, 0, sizeof iv); /* per RFC 1510 */
2509 if (!EVP_DecryptInit_ex(&ciph_ctx, enc, NULL, kssl_ctx->key, iv)) {
2510 SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,
2511 SSL_R_DECRYPTION_FAILED);
2512 goto err;
2514 if (!EVP_DecryptUpdate(&ciph_ctx, pms, &outl,
2515 (unsigned char *)enc_pms.data, enc_pms.length))
2517 SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,
2518 SSL_R_DECRYPTION_FAILED);
2519 kerr = 1;
2520 goto kclean;
2522 if (outl > SSL_MAX_MASTER_KEY_LENGTH) {
2523 SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,
2524 SSL_R_DATA_LENGTH_TOO_LONG);
2525 kerr = 1;
2526 goto kclean;
2528 if (!EVP_DecryptFinal_ex(&ciph_ctx, &(pms[outl]), &padl)) {
2529 SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,
2530 SSL_R_DECRYPTION_FAILED);
2531 kerr = 1;
2532 goto kclean;
2534 outl += padl;
2535 if (outl > SSL_MAX_MASTER_KEY_LENGTH) {
2536 SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,
2537 SSL_R_DATA_LENGTH_TOO_LONG);
2538 kerr = 1;
2539 goto kclean;
2541 if (!((pms[0] == (s->client_version >> 8))
2542 && (pms[1] == (s->client_version & 0xff)))) {
2544 * The premaster secret must contain the same version number as
2545 * the ClientHello to detect version rollback attacks (strangely,
2546 * the protocol does not offer such protection for DH
2547 * ciphersuites). However, buggy clients exist that send random
2548 * bytes instead of the protocol version. If
2549 * SSL_OP_TLS_ROLLBACK_BUG is set, tolerate such clients.
2550 * (Perhaps we should have a separate BUG value for the Kerberos
2551 * cipher)
2553 if (!(s->options & SSL_OP_TLS_ROLLBACK_BUG)) {
2554 SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,
2555 SSL_AD_DECODE_ERROR);
2556 kerr = 1;
2557 goto kclean;
2561 EVP_CIPHER_CTX_cleanup(&ciph_ctx);
2563 s->session->master_key_length =
2564 s->method->ssl3_enc->generate_master_secret(s,
2566 session->master_key,
2567 pms, outl);
2569 if (kssl_ctx->client_princ) {
2570 size_t len = strlen(kssl_ctx->client_princ);
2571 if (len < SSL_MAX_KRB5_PRINCIPAL_LENGTH) {
2572 s->session->krb5_client_princ_len = len;
2573 memcpy(s->session->krb5_client_princ, kssl_ctx->client_princ,
2574 len);
2578 /*- Was doing kssl_ctx_free() here,
2579 * but it caused problems for apache.
2580 * kssl_ctx = kssl_ctx_free(kssl_ctx);
2581 * if (s->kssl_ctx) s->kssl_ctx = NULL;
2584 kclean:
2585 OPENSSL_cleanse(pms, sizeof(pms));
2586 if (kerr)
2587 goto err;
2588 } else
2589 #endif /* OPENSSL_NO_KRB5 */
2591 #ifndef OPENSSL_NO_ECDH
2592 if (alg_k & (SSL_kEECDH | SSL_kECDHr | SSL_kECDHe)) {
2593 int ret = 1;
2594 int field_size = 0;
2595 const EC_KEY *tkey;
2596 const EC_GROUP *group;
2597 const BIGNUM *priv_key;
2599 /* initialize structures for server's ECDH key pair */
2600 if ((srvr_ecdh = EC_KEY_new()) == NULL) {
2601 SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE, ERR_R_MALLOC_FAILURE);
2602 goto err;
2605 /* Let's get server private key and group information */
2606 if (alg_k & (SSL_kECDHr | SSL_kECDHe)) {
2607 /* use the certificate */
2608 tkey = s->cert->pkeys[SSL_PKEY_ECC].privatekey->pkey.ec;
2609 } else {
2611 * use the ephermeral values we saved when generating the
2612 * ServerKeyExchange msg.
2614 tkey = s->s3->tmp.ecdh;
2617 group = EC_KEY_get0_group(tkey);
2618 priv_key = EC_KEY_get0_private_key(tkey);
2620 if (!EC_KEY_set_group(srvr_ecdh, group) ||
2621 !EC_KEY_set_private_key(srvr_ecdh, priv_key)) {
2622 SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE, ERR_R_EC_LIB);
2623 goto err;
2626 /* Let's get client's public key */
2627 if ((clnt_ecpoint = EC_POINT_new(group)) == NULL) {
2628 SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE, ERR_R_MALLOC_FAILURE);
2629 goto err;
2632 if (n == 0L) {
2633 /* Client Publickey was in Client Certificate */
2635 if (alg_k & SSL_kEECDH) {
2636 al = SSL_AD_HANDSHAKE_FAILURE;
2637 SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,
2638 SSL_R_MISSING_TMP_ECDH_KEY);
2639 goto f_err;
2641 if (((clnt_pub_pkey = X509_get_pubkey(s->session->peer))
2642 == NULL) || (clnt_pub_pkey->type != EVP_PKEY_EC)) {
2644 * XXX: For now, we do not support client authentication
2645 * using ECDH certificates so this branch (n == 0L) of the
2646 * code is never executed. When that support is added, we
2647 * ought to ensure the key received in the certificate is
2648 * authorized for key agreement. ECDH_compute_key implicitly
2649 * checks that the two ECDH shares are for the same group.
2651 al = SSL_AD_HANDSHAKE_FAILURE;
2652 SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,
2653 SSL_R_UNABLE_TO_DECODE_ECDH_CERTS);
2654 goto f_err;
2657 if (EC_POINT_copy(clnt_ecpoint,
2658 EC_KEY_get0_public_key(clnt_pub_pkey->
2659 pkey.ec)) == 0) {
2660 SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE, ERR_R_EC_LIB);
2661 goto err;
2663 ret = 2; /* Skip certificate verify processing */
2664 } else {
2666 * Get client's public key from encoded point in the
2667 * ClientKeyExchange message.
2669 if ((bn_ctx = BN_CTX_new()) == NULL) {
2670 SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,
2671 ERR_R_MALLOC_FAILURE);
2672 goto err;
2675 /* Get encoded point length */
2676 i = *p;
2677 p += 1;
2678 if (n != 1 + i) {
2679 SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE, ERR_R_EC_LIB);
2680 goto err;
2682 if (EC_POINT_oct2point(group, clnt_ecpoint, p, i, bn_ctx) == 0) {
2683 SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE, ERR_R_EC_LIB);
2684 goto err;
2687 * p is pointing to somewhere in the buffer currently, so set it
2688 * to the start
2690 p = (unsigned char *)s->init_buf->data;
2693 /* Compute the shared pre-master secret */
2694 field_size = EC_GROUP_get_degree(group);
2695 if (field_size <= 0) {
2696 SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE, ERR_R_ECDH_LIB);
2697 goto err;
2699 i = ECDH_compute_key(p, (field_size + 7) / 8, clnt_ecpoint, srvr_ecdh,
2700 NULL);
2701 if (i <= 0) {
2702 SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE, ERR_R_ECDH_LIB);
2703 goto err;
2706 EVP_PKEY_free(clnt_pub_pkey);
2707 EC_POINT_free(clnt_ecpoint);
2708 EC_KEY_free(srvr_ecdh);
2709 BN_CTX_free(bn_ctx);
2710 EC_KEY_free(s->s3->tmp.ecdh);
2711 s->s3->tmp.ecdh = NULL;
2713 /* Compute the master secret */
2714 s->session->master_key_length =
2715 s->method->ssl3_enc->generate_master_secret(s,
2717 session->master_key,
2718 p, i);
2720 OPENSSL_cleanse(p, i);
2721 return (ret);
2722 } else
2723 #endif
2724 #ifndef OPENSSL_NO_PSK
2725 if (alg_k & SSL_kPSK) {
2726 unsigned char *t = NULL;
2727 unsigned char psk_or_pre_ms[PSK_MAX_PSK_LEN * 2 + 4];
2728 unsigned int pre_ms_len = 0, psk_len = 0;
2729 int psk_err = 1;
2730 char tmp_id[PSK_MAX_IDENTITY_LEN + 1];
2732 al = SSL_AD_HANDSHAKE_FAILURE;
2734 n2s(p, i);
2735 if (n != i + 2) {
2736 SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE, SSL_R_LENGTH_MISMATCH);
2737 goto psk_err;
2739 if (i > PSK_MAX_IDENTITY_LEN) {
2740 SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,
2741 SSL_R_DATA_LENGTH_TOO_LONG);
2742 goto psk_err;
2744 if (s->psk_server_callback == NULL) {
2745 SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,
2746 SSL_R_PSK_NO_SERVER_CB);
2747 goto psk_err;
2751 * Create guaranteed NULL-terminated identity string for the callback
2753 memcpy(tmp_id, p, i);
2754 memset(tmp_id + i, 0, PSK_MAX_IDENTITY_LEN + 1 - i);
2755 psk_len = s->psk_server_callback(s, tmp_id,
2756 psk_or_pre_ms,
2757 sizeof(psk_or_pre_ms));
2758 OPENSSL_cleanse(tmp_id, PSK_MAX_IDENTITY_LEN + 1);
2760 if (psk_len > PSK_MAX_PSK_LEN) {
2761 SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE, ERR_R_INTERNAL_ERROR);
2762 goto psk_err;
2763 } else if (psk_len == 0) {
2765 * PSK related to the given identity not found
2767 SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,
2768 SSL_R_PSK_IDENTITY_NOT_FOUND);
2769 al = SSL_AD_UNKNOWN_PSK_IDENTITY;
2770 goto psk_err;
2773 /* create PSK pre_master_secret */
2774 pre_ms_len = 2 + psk_len + 2 + psk_len;
2775 t = psk_or_pre_ms;
2776 memmove(psk_or_pre_ms + psk_len + 4, psk_or_pre_ms, psk_len);
2777 s2n(psk_len, t);
2778 memset(t, 0, psk_len);
2779 t += psk_len;
2780 s2n(psk_len, t);
2782 if (s->session->psk_identity != NULL)
2783 OPENSSL_free(s->session->psk_identity);
2784 s->session->psk_identity = BUF_strndup((char *)p, i);
2785 if (s->session->psk_identity == NULL) {
2786 SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE, ERR_R_MALLOC_FAILURE);
2787 goto psk_err;
2790 if (s->session->psk_identity_hint != NULL)
2791 OPENSSL_free(s->session->psk_identity_hint);
2792 s->session->psk_identity_hint = BUF_strdup(s->ctx->psk_identity_hint);
2793 if (s->ctx->psk_identity_hint != NULL &&
2794 s->session->psk_identity_hint == NULL) {
2795 SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE, ERR_R_MALLOC_FAILURE);
2796 goto psk_err;
2799 s->session->master_key_length =
2800 s->method->ssl3_enc->generate_master_secret(s,
2802 session->master_key,
2803 psk_or_pre_ms,
2804 pre_ms_len);
2805 psk_err = 0;
2806 psk_err:
2807 OPENSSL_cleanse(psk_or_pre_ms, sizeof(psk_or_pre_ms));
2808 if (psk_err != 0)
2809 goto f_err;
2810 } else
2811 #endif
2812 #ifndef OPENSSL_NO_SRP
2813 if (alg_k & SSL_kSRP) {
2814 int param_len;
2816 n2s(p, i);
2817 param_len = i + 2;
2818 if (param_len > n) {
2819 al = SSL_AD_DECODE_ERROR;
2820 SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,
2821 SSL_R_BAD_SRP_A_LENGTH);
2822 goto f_err;
2824 if (!(s->srp_ctx.A = BN_bin2bn(p, i, NULL))) {
2825 SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE, ERR_R_BN_LIB);
2826 goto err;
2828 if (BN_ucmp(s->srp_ctx.A, s->srp_ctx.N) >= 0
2829 || BN_is_zero(s->srp_ctx.A)) {
2830 al = SSL_AD_ILLEGAL_PARAMETER;
2831 SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,
2832 SSL_R_BAD_SRP_PARAMETERS);
2833 goto f_err;
2835 if (s->session->srp_username != NULL)
2836 OPENSSL_free(s->session->srp_username);
2837 s->session->srp_username = BUF_strdup(s->srp_ctx.login);
2838 if (s->session->srp_username == NULL) {
2839 SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE, ERR_R_MALLOC_FAILURE);
2840 goto err;
2843 if ((s->session->master_key_length =
2844 SRP_generate_server_master_secret(s,
2845 s->session->master_key)) < 0) {
2846 SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE, ERR_R_INTERNAL_ERROR);
2847 goto err;
2850 p += i;
2851 } else
2852 #endif /* OPENSSL_NO_SRP */
2853 if (alg_k & SSL_kGOST) {
2854 int ret = 0;
2855 EVP_PKEY_CTX *pkey_ctx;
2856 EVP_PKEY *client_pub_pkey = NULL, *pk = NULL;
2857 unsigned char premaster_secret[32], *start;
2858 size_t outlen = 32, inlen;
2859 unsigned long alg_a;
2860 int Ttag, Tclass;
2861 long Tlen;
2863 /* Get our certificate private key */
2864 alg_a = s->s3->tmp.new_cipher->algorithm_auth;
2865 if (alg_a & SSL_aGOST94)
2866 pk = s->cert->pkeys[SSL_PKEY_GOST94].privatekey;
2867 else if (alg_a & SSL_aGOST01)
2868 pk = s->cert->pkeys[SSL_PKEY_GOST01].privatekey;
2870 pkey_ctx = EVP_PKEY_CTX_new(pk, NULL);
2871 if (pkey_ctx == NULL) {
2872 al = SSL_AD_INTERNAL_ERROR;
2873 SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE, ERR_R_MALLOC_FAILURE);
2874 goto f_err;
2876 if (EVP_PKEY_decrypt_init(pkey_ctx) <= 0) {
2877 SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE, ERR_R_INTERNAL_ERROR);
2878 goto gerr;
2881 * If client certificate is present and is of the same type, maybe
2882 * use it for key exchange. Don't mind errors from
2883 * EVP_PKEY_derive_set_peer, because it is completely valid to use a
2884 * client certificate for authorization only.
2886 client_pub_pkey = X509_get_pubkey(s->session->peer);
2887 if (client_pub_pkey) {
2888 if (EVP_PKEY_derive_set_peer(pkey_ctx, client_pub_pkey) <= 0)
2889 ERR_clear_error();
2891 /* Decrypt session key */
2892 if (ASN1_get_object
2893 ((const unsigned char **)&p, &Tlen, &Ttag, &Tclass,
2894 n) != V_ASN1_CONSTRUCTED || Ttag != V_ASN1_SEQUENCE
2895 || Tclass != V_ASN1_UNIVERSAL) {
2896 SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,
2897 SSL_R_DECRYPTION_FAILED);
2898 goto gerr;
2900 start = p;
2901 inlen = Tlen;
2902 if (EVP_PKEY_decrypt
2903 (pkey_ctx, premaster_secret, &outlen, start, inlen) <= 0) {
2904 SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,
2905 SSL_R_DECRYPTION_FAILED);
2906 goto gerr;
2908 /* Generate master secret */
2909 s->session->master_key_length =
2910 s->method->ssl3_enc->generate_master_secret(s,
2912 session->master_key,
2913 premaster_secret, 32);
2914 OPENSSL_cleanse(premaster_secret, sizeof(premaster_secret));
2915 /* Check if pubkey from client certificate was used */
2916 if (EVP_PKEY_CTX_ctrl
2917 (pkey_ctx, -1, -1, EVP_PKEY_CTRL_PEER_KEY, 2, NULL) > 0)
2918 ret = 2;
2919 else
2920 ret = 1;
2921 gerr:
2922 EVP_PKEY_free(client_pub_pkey);
2923 EVP_PKEY_CTX_free(pkey_ctx);
2924 if (ret)
2925 return ret;
2926 else
2927 goto err;
2928 } else {
2929 al = SSL_AD_HANDSHAKE_FAILURE;
2930 SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE, SSL_R_UNKNOWN_CIPHER_TYPE);
2931 goto f_err;
2934 return (1);
2935 f_err:
2936 ssl3_send_alert(s, SSL3_AL_FATAL, al);
2937 #if !defined(OPENSSL_NO_DH) || !defined(OPENSSL_NO_RSA) || !defined(OPENSSL_NO_ECDH) || defined(OPENSSL_NO_SRP)
2938 err:
2939 #endif
2940 #ifndef OPENSSL_NO_ECDH
2941 EVP_PKEY_free(clnt_pub_pkey);
2942 EC_POINT_free(clnt_ecpoint);
2943 if (srvr_ecdh != NULL)
2944 EC_KEY_free(srvr_ecdh);
2945 BN_CTX_free(bn_ctx);
2946 #endif
2947 s->state = SSL_ST_ERR;
2948 return (-1);
2951 int ssl3_get_cert_verify(SSL *s)
2953 EVP_PKEY *pkey = NULL;
2954 unsigned char *p;
2955 int al, ok, ret = 0;
2956 long n;
2957 int type = 0, i, j;
2958 X509 *peer;
2959 const EVP_MD *md = NULL;
2960 EVP_MD_CTX mctx;
2961 EVP_MD_CTX_init(&mctx);
2964 * We should only process a CertificateVerify message if we have received
2965 * a Certificate from the client. If so then |s->session->peer| will be non
2966 * NULL. In some instances a CertificateVerify message is not required even
2967 * if the peer has sent a Certificate (e.g. such as in the case of static
2968 * DH). In that case the ClientKeyExchange processing will skip the
2969 * CertificateVerify state so we should not arrive here.
2971 if (s->session->peer == NULL) {
2972 ret = 1;
2973 goto end;
2976 n = s->method->ssl_get_message(s,
2977 SSL3_ST_SR_CERT_VRFY_A,
2978 SSL3_ST_SR_CERT_VRFY_B,
2979 SSL3_MT_CERTIFICATE_VERIFY,
2980 SSL3_RT_MAX_PLAIN_LENGTH, &ok);
2982 if (!ok)
2983 return ((int)n);
2985 peer = s->session->peer;
2986 pkey = X509_get_pubkey(peer);
2987 type = X509_certificate_type(peer, pkey);
2989 if (!(type & EVP_PKT_SIGN)) {
2990 SSLerr(SSL_F_SSL3_GET_CERT_VERIFY,
2991 SSL_R_SIGNATURE_FOR_NON_SIGNING_CERTIFICATE);
2992 al = SSL_AD_ILLEGAL_PARAMETER;
2993 goto f_err;
2996 /* we now have a signature that we need to verify */
2997 p = (unsigned char *)s->init_msg;
2998 /* Check for broken implementations of GOST ciphersuites */
3000 * If key is GOST and n is exactly 64, it is bare signature without
3001 * length field
3003 if (n == 64 && (pkey->type == NID_id_GostR3410_94 ||
3004 pkey->type == NID_id_GostR3410_2001)) {
3005 i = 64;
3006 } else {
3007 if (SSL_USE_SIGALGS(s)) {
3008 int rv = tls12_check_peer_sigalg(&md, s, p, pkey);
3009 if (rv == -1) {
3010 al = SSL_AD_INTERNAL_ERROR;
3011 goto f_err;
3012 } else if (rv == 0) {
3013 al = SSL_AD_DECODE_ERROR;
3014 goto f_err;
3016 #ifdef SSL_DEBUG
3017 fprintf(stderr, "USING TLSv1.2 HASH %s\n", EVP_MD_name(md));
3018 #endif
3019 p += 2;
3020 n -= 2;
3022 n2s(p, i);
3023 n -= 2;
3024 if (i > n) {
3025 SSLerr(SSL_F_SSL3_GET_CERT_VERIFY, SSL_R_LENGTH_MISMATCH);
3026 al = SSL_AD_DECODE_ERROR;
3027 goto f_err;
3030 j = EVP_PKEY_size(pkey);
3031 if ((i > j) || (n > j) || (n <= 0)) {
3032 SSLerr(SSL_F_SSL3_GET_CERT_VERIFY, SSL_R_WRONG_SIGNATURE_SIZE);
3033 al = SSL_AD_DECODE_ERROR;
3034 goto f_err;
3037 if (SSL_USE_SIGALGS(s)) {
3038 long hdatalen = 0;
3039 void *hdata;
3040 hdatalen = BIO_get_mem_data(s->s3->handshake_buffer, &hdata);
3041 if (hdatalen <= 0) {
3042 SSLerr(SSL_F_SSL3_GET_CERT_VERIFY, ERR_R_INTERNAL_ERROR);
3043 al = SSL_AD_INTERNAL_ERROR;
3044 goto f_err;
3046 #ifdef SSL_DEBUG
3047 fprintf(stderr, "Using TLS 1.2 with client verify alg %s\n",
3048 EVP_MD_name(md));
3049 #endif
3050 if (!EVP_VerifyInit_ex(&mctx, md, NULL)
3051 || !EVP_VerifyUpdate(&mctx, hdata, hdatalen)) {
3052 SSLerr(SSL_F_SSL3_GET_CERT_VERIFY, ERR_R_EVP_LIB);
3053 al = SSL_AD_INTERNAL_ERROR;
3054 goto f_err;
3057 if (EVP_VerifyFinal(&mctx, p, i, pkey) <= 0) {
3058 al = SSL_AD_DECRYPT_ERROR;
3059 SSLerr(SSL_F_SSL3_GET_CERT_VERIFY, SSL_R_BAD_SIGNATURE);
3060 goto f_err;
3062 } else
3063 #ifndef OPENSSL_NO_RSA
3064 if (pkey->type == EVP_PKEY_RSA) {
3065 i = RSA_verify(NID_md5_sha1, s->s3->tmp.cert_verify_md,
3066 MD5_DIGEST_LENGTH + SHA_DIGEST_LENGTH, p, i,
3067 pkey->pkey.rsa);
3068 if (i < 0) {
3069 al = SSL_AD_DECRYPT_ERROR;
3070 SSLerr(SSL_F_SSL3_GET_CERT_VERIFY, SSL_R_BAD_RSA_DECRYPT);
3071 goto f_err;
3073 if (i == 0) {
3074 al = SSL_AD_DECRYPT_ERROR;
3075 SSLerr(SSL_F_SSL3_GET_CERT_VERIFY, SSL_R_BAD_RSA_SIGNATURE);
3076 goto f_err;
3078 } else
3079 #endif
3080 #ifndef OPENSSL_NO_DSA
3081 if (pkey->type == EVP_PKEY_DSA) {
3082 j = DSA_verify(pkey->save_type,
3083 &(s->s3->tmp.cert_verify_md[MD5_DIGEST_LENGTH]),
3084 SHA_DIGEST_LENGTH, p, i, pkey->pkey.dsa);
3085 if (j <= 0) {
3086 /* bad signature */
3087 al = SSL_AD_DECRYPT_ERROR;
3088 SSLerr(SSL_F_SSL3_GET_CERT_VERIFY, SSL_R_BAD_DSA_SIGNATURE);
3089 goto f_err;
3091 } else
3092 #endif
3093 #ifndef OPENSSL_NO_ECDSA
3094 if (pkey->type == EVP_PKEY_EC) {
3095 j = ECDSA_verify(pkey->save_type,
3096 &(s->s3->tmp.cert_verify_md[MD5_DIGEST_LENGTH]),
3097 SHA_DIGEST_LENGTH, p, i, pkey->pkey.ec);
3098 if (j <= 0) {
3099 /* bad signature */
3100 al = SSL_AD_DECRYPT_ERROR;
3101 SSLerr(SSL_F_SSL3_GET_CERT_VERIFY, SSL_R_BAD_ECDSA_SIGNATURE);
3102 goto f_err;
3104 } else
3105 #endif
3106 if (pkey->type == NID_id_GostR3410_94
3107 || pkey->type == NID_id_GostR3410_2001) {
3108 unsigned char signature[64];
3109 int idx;
3110 EVP_PKEY_CTX *pctx = EVP_PKEY_CTX_new(pkey, NULL);
3111 if (pctx == NULL) {
3112 al = SSL_AD_INTERNAL_ERROR;
3113 SSLerr(SSL_F_SSL3_GET_CERT_VERIFY, ERR_R_MALLOC_FAILURE);
3114 goto f_err;
3116 if (EVP_PKEY_verify_init(pctx) <= 0) {
3117 EVP_PKEY_CTX_free(pctx);
3118 al = SSL_AD_INTERNAL_ERROR;
3119 SSLerr(SSL_F_SSL3_GET_CERT_VERIFY, ERR_R_INTERNAL_ERROR);
3120 goto f_err;
3122 if (i != 64) {
3123 fprintf(stderr, "GOST signature length is %d", i);
3125 for (idx = 0; idx < 64; idx++) {
3126 signature[63 - idx] = p[idx];
3128 j = EVP_PKEY_verify(pctx, signature, 64, s->s3->tmp.cert_verify_md,
3129 32);
3130 EVP_PKEY_CTX_free(pctx);
3131 if (j <= 0) {
3132 al = SSL_AD_DECRYPT_ERROR;
3133 SSLerr(SSL_F_SSL3_GET_CERT_VERIFY, SSL_R_BAD_ECDSA_SIGNATURE);
3134 goto f_err;
3136 } else {
3137 SSLerr(SSL_F_SSL3_GET_CERT_VERIFY, ERR_R_INTERNAL_ERROR);
3138 al = SSL_AD_UNSUPPORTED_CERTIFICATE;
3139 goto f_err;
3142 ret = 1;
3143 if (0) {
3144 f_err:
3145 ssl3_send_alert(s, SSL3_AL_FATAL, al);
3146 s->state = SSL_ST_ERR;
3148 end:
3149 if (s->s3->handshake_buffer) {
3150 BIO_free(s->s3->handshake_buffer);
3151 s->s3->handshake_buffer = NULL;
3152 s->s3->flags &= ~TLS1_FLAGS_KEEP_HANDSHAKE;
3154 EVP_MD_CTX_cleanup(&mctx);
3155 EVP_PKEY_free(pkey);
3156 return (ret);
3159 int ssl3_get_client_certificate(SSL *s)
3161 int i, ok, al, ret = -1;
3162 X509 *x = NULL;
3163 unsigned long l, nc, llen, n;
3164 const unsigned char *p, *q;
3165 unsigned char *d;
3166 STACK_OF(X509) *sk = NULL;
3168 n = s->method->ssl_get_message(s,
3169 SSL3_ST_SR_CERT_A,
3170 SSL3_ST_SR_CERT_B,
3171 -1, s->max_cert_list, &ok);
3173 if (!ok)
3174 return ((int)n);
3176 if (s->s3->tmp.message_type == SSL3_MT_CLIENT_KEY_EXCHANGE) {
3177 if ((s->verify_mode & SSL_VERIFY_PEER) &&
3178 (s->verify_mode & SSL_VERIFY_FAIL_IF_NO_PEER_CERT)) {
3179 SSLerr(SSL_F_SSL3_GET_CLIENT_CERTIFICATE,
3180 SSL_R_PEER_DID_NOT_RETURN_A_CERTIFICATE);
3181 al = SSL_AD_HANDSHAKE_FAILURE;
3182 goto f_err;
3185 * If tls asked for a client cert, the client must return a 0 list
3187 if ((s->version > SSL3_VERSION) && s->s3->tmp.cert_request) {
3188 SSLerr(SSL_F_SSL3_GET_CLIENT_CERTIFICATE,
3189 SSL_R_TLS_PEER_DID_NOT_RESPOND_WITH_CERTIFICATE_LIST);
3190 al = SSL_AD_UNEXPECTED_MESSAGE;
3191 goto f_err;
3193 s->s3->tmp.reuse_message = 1;
3194 return (1);
3197 if (s->s3->tmp.message_type != SSL3_MT_CERTIFICATE) {
3198 al = SSL_AD_UNEXPECTED_MESSAGE;
3199 SSLerr(SSL_F_SSL3_GET_CLIENT_CERTIFICATE, SSL_R_WRONG_MESSAGE_TYPE);
3200 goto f_err;
3202 p = d = (unsigned char *)s->init_msg;
3204 if ((sk = sk_X509_new_null()) == NULL) {
3205 SSLerr(SSL_F_SSL3_GET_CLIENT_CERTIFICATE, ERR_R_MALLOC_FAILURE);
3206 goto err;
3209 n2l3(p, llen);
3210 if (llen + 3 != n) {
3211 al = SSL_AD_DECODE_ERROR;
3212 SSLerr(SSL_F_SSL3_GET_CLIENT_CERTIFICATE, SSL_R_LENGTH_MISMATCH);
3213 goto f_err;
3215 for (nc = 0; nc < llen;) {
3216 n2l3(p, l);
3217 if ((l + nc + 3) > llen) {
3218 al = SSL_AD_DECODE_ERROR;
3219 SSLerr(SSL_F_SSL3_GET_CLIENT_CERTIFICATE,
3220 SSL_R_CERT_LENGTH_MISMATCH);
3221 goto f_err;
3224 q = p;
3225 x = d2i_X509(NULL, &p, l);
3226 if (x == NULL) {
3227 SSLerr(SSL_F_SSL3_GET_CLIENT_CERTIFICATE, ERR_R_ASN1_LIB);
3228 goto err;
3230 if (p != (q + l)) {
3231 al = SSL_AD_DECODE_ERROR;
3232 SSLerr(SSL_F_SSL3_GET_CLIENT_CERTIFICATE,
3233 SSL_R_CERT_LENGTH_MISMATCH);
3234 goto f_err;
3236 if (!sk_X509_push(sk, x)) {
3237 SSLerr(SSL_F_SSL3_GET_CLIENT_CERTIFICATE, ERR_R_MALLOC_FAILURE);
3238 goto err;
3240 x = NULL;
3241 nc += l + 3;
3244 if (sk_X509_num(sk) <= 0) {
3245 /* TLS does not mind 0 certs returned */
3246 if (s->version == SSL3_VERSION) {
3247 al = SSL_AD_HANDSHAKE_FAILURE;
3248 SSLerr(SSL_F_SSL3_GET_CLIENT_CERTIFICATE,
3249 SSL_R_NO_CERTIFICATES_RETURNED);
3250 goto f_err;
3252 /* Fail for TLS only if we required a certificate */
3253 else if ((s->verify_mode & SSL_VERIFY_PEER) &&
3254 (s->verify_mode & SSL_VERIFY_FAIL_IF_NO_PEER_CERT)) {
3255 SSLerr(SSL_F_SSL3_GET_CLIENT_CERTIFICATE,
3256 SSL_R_PEER_DID_NOT_RETURN_A_CERTIFICATE);
3257 al = SSL_AD_HANDSHAKE_FAILURE;
3258 goto f_err;
3260 /* No client certificate so digest cached records */
3261 if (s->s3->handshake_buffer && !ssl3_digest_cached_records(s)) {
3262 al = SSL_AD_INTERNAL_ERROR;
3263 goto f_err;
3265 } else {
3266 i = ssl_verify_cert_chain(s, sk);
3267 if (i <= 0) {
3268 al = ssl_verify_alarm_type(s->verify_result);
3269 SSLerr(SSL_F_SSL3_GET_CLIENT_CERTIFICATE,
3270 SSL_R_CERTIFICATE_VERIFY_FAILED);
3271 goto f_err;
3275 if (s->session->peer != NULL) /* This should not be needed */
3276 X509_free(s->session->peer);
3277 s->session->peer = sk_X509_shift(sk);
3278 s->session->verify_result = s->verify_result;
3281 * With the current implementation, sess_cert will always be NULL when we
3282 * arrive here.
3284 if (s->session->sess_cert == NULL) {
3285 s->session->sess_cert = ssl_sess_cert_new();
3286 if (s->session->sess_cert == NULL) {
3287 SSLerr(SSL_F_SSL3_GET_CLIENT_CERTIFICATE, ERR_R_MALLOC_FAILURE);
3288 goto err;
3291 if (s->session->sess_cert->cert_chain != NULL)
3292 sk_X509_pop_free(s->session->sess_cert->cert_chain, X509_free);
3293 s->session->sess_cert->cert_chain = sk;
3295 * Inconsistency alert: cert_chain does *not* include the peer's own
3296 * certificate, while we do include it in s3_clnt.c
3299 sk = NULL;
3301 ret = 1;
3302 if (0) {
3303 f_err:
3304 ssl3_send_alert(s, SSL3_AL_FATAL, al);
3305 err:
3306 s->state = SSL_ST_ERR;
3309 if (x != NULL)
3310 X509_free(x);
3311 if (sk != NULL)
3312 sk_X509_pop_free(sk, X509_free);
3313 return (ret);
3316 int ssl3_send_server_certificate(SSL *s)
3318 CERT_PKEY *cpk;
3320 if (s->state == SSL3_ST_SW_CERT_A) {
3321 cpk = ssl_get_server_send_pkey(s);
3322 if (cpk == NULL) {
3323 /* VRS: allow null cert if auth == KRB5 */
3324 if ((s->s3->tmp.new_cipher->algorithm_auth != SSL_aKRB5) ||
3325 (s->s3->tmp.new_cipher->algorithm_mkey & SSL_kKRB5)) {
3326 SSLerr(SSL_F_SSL3_SEND_SERVER_CERTIFICATE,
3327 ERR_R_INTERNAL_ERROR);
3328 s->state = SSL_ST_ERR;
3329 return (0);
3333 if (!ssl3_output_cert_chain(s, cpk)) {
3334 SSLerr(SSL_F_SSL3_SEND_SERVER_CERTIFICATE, ERR_R_INTERNAL_ERROR);
3335 s->state = SSL_ST_ERR;
3336 return (0);
3338 s->state = SSL3_ST_SW_CERT_B;
3341 /* SSL3_ST_SW_CERT_B */
3342 return ssl_do_write(s);
3345 #ifndef OPENSSL_NO_TLSEXT
3346 /* send a new session ticket (not necessarily for a new session) */
3347 int ssl3_send_newsession_ticket(SSL *s)
3349 unsigned char *senc = NULL;
3350 EVP_CIPHER_CTX ctx;
3351 HMAC_CTX hctx;
3353 if (s->state == SSL3_ST_SW_SESSION_TICKET_A) {
3354 unsigned char *p, *macstart;
3355 const unsigned char *const_p;
3356 int len, slen_full, slen;
3357 SSL_SESSION *sess;
3358 unsigned int hlen;
3359 SSL_CTX *tctx = s->initial_ctx;
3360 unsigned char iv[EVP_MAX_IV_LENGTH];
3361 unsigned char key_name[16];
3363 /* get session encoding length */
3364 slen_full = i2d_SSL_SESSION(s->session, NULL);
3366 * Some length values are 16 bits, so forget it if session is too
3367 * long
3369 if (slen_full == 0 || slen_full > 0xFF00) {
3370 s->state = SSL_ST_ERR;
3371 return -1;
3373 senc = OPENSSL_malloc(slen_full);
3374 if (!senc) {
3375 s->state = SSL_ST_ERR;
3376 return -1;
3379 EVP_CIPHER_CTX_init(&ctx);
3380 HMAC_CTX_init(&hctx);
3382 p = senc;
3383 if (!i2d_SSL_SESSION(s->session, &p))
3384 goto err;
3387 * create a fresh copy (not shared with other threads) to clean up
3389 const_p = senc;
3390 sess = d2i_SSL_SESSION(NULL, &const_p, slen_full);
3391 if (sess == NULL)
3392 goto err;
3393 sess->session_id_length = 0; /* ID is irrelevant for the ticket */
3395 slen = i2d_SSL_SESSION(sess, NULL);
3396 if (slen == 0 || slen > slen_full) { /* shouldn't ever happen */
3397 SSL_SESSION_free(sess);
3398 goto err;
3400 p = senc;
3401 if (!i2d_SSL_SESSION(sess, &p)) {
3402 SSL_SESSION_free(sess);
3403 goto err;
3405 SSL_SESSION_free(sess);
3408 * Grow buffer if need be: the length calculation is as
3409 * follows handshake_header_length +
3410 * 4 (ticket lifetime hint) + 2 (ticket length) +
3411 * 16 (key name) + max_iv_len (iv length) +
3412 * session_length + max_enc_block_size (max encrypted session
3413 * length) + max_md_size (HMAC).
3415 if (!BUF_MEM_grow(s->init_buf,
3416 SSL_HM_HEADER_LENGTH(s) + 22 + EVP_MAX_IV_LENGTH +
3417 EVP_MAX_BLOCK_LENGTH + EVP_MAX_MD_SIZE + slen))
3418 goto err;
3420 p = ssl_handshake_start(s);
3422 * Initialize HMAC and cipher contexts. If callback present it does
3423 * all the work otherwise use generated values from parent ctx.
3425 if (tctx->tlsext_ticket_key_cb) {
3426 if (tctx->tlsext_ticket_key_cb(s, key_name, iv, &ctx,
3427 &hctx, 1) < 0)
3428 goto err;
3429 } else {
3430 if (RAND_bytes(iv, 16) <= 0)
3431 goto err;
3432 if (!EVP_EncryptInit_ex(&ctx, EVP_aes_128_cbc(), NULL,
3433 tctx->tlsext_tick_aes_key, iv))
3434 goto err;
3435 if (!HMAC_Init_ex(&hctx, tctx->tlsext_tick_hmac_key, 16,
3436 tlsext_tick_md(), NULL))
3437 goto err;
3438 memcpy(key_name, tctx->tlsext_tick_key_name, 16);
3442 * Ticket lifetime hint (advisory only): We leave this unspecified
3443 * for resumed session (for simplicity), and guess that tickets for
3444 * new sessions will live as long as their sessions.
3446 l2n(s->hit ? 0 : s->session->timeout, p);
3448 /* Skip ticket length for now */
3449 p += 2;
3450 /* Output key name */
3451 macstart = p;
3452 memcpy(p, key_name, 16);
3453 p += 16;
3454 /* output IV */
3455 memcpy(p, iv, EVP_CIPHER_CTX_iv_length(&ctx));
3456 p += EVP_CIPHER_CTX_iv_length(&ctx);
3457 /* Encrypt session data */
3458 if (!EVP_EncryptUpdate(&ctx, p, &len, senc, slen))
3459 goto err;
3460 p += len;
3461 if (!EVP_EncryptFinal(&ctx, p, &len))
3462 goto err;
3463 p += len;
3465 if (!HMAC_Update(&hctx, macstart, p - macstart))
3466 goto err;
3467 if (!HMAC_Final(&hctx, p, &hlen))
3468 goto err;
3470 EVP_CIPHER_CTX_cleanup(&ctx);
3471 HMAC_CTX_cleanup(&hctx);
3473 p += hlen;
3474 /* Now write out lengths: p points to end of data written */
3475 /* Total length */
3476 len = p - ssl_handshake_start(s);
3477 /* Skip ticket lifetime hint */
3478 p = ssl_handshake_start(s) + 4;
3479 s2n(len - 6, p);
3480 ssl_set_handshake_header(s, SSL3_MT_NEWSESSION_TICKET, len);
3481 s->state = SSL3_ST_SW_SESSION_TICKET_B;
3482 OPENSSL_free(senc);
3485 /* SSL3_ST_SW_SESSION_TICKET_B */
3486 return ssl_do_write(s);
3487 err:
3488 if (senc)
3489 OPENSSL_free(senc);
3490 EVP_CIPHER_CTX_cleanup(&ctx);
3491 HMAC_CTX_cleanup(&hctx);
3492 s->state = SSL_ST_ERR;
3493 return -1;
3496 int ssl3_send_cert_status(SSL *s)
3498 if (s->state == SSL3_ST_SW_CERT_STATUS_A) {
3499 unsigned char *p;
3501 * Grow buffer if need be: the length calculation is as
3502 * follows 1 (message type) + 3 (message length) +
3503 * 1 (ocsp response type) + 3 (ocsp response length)
3504 * + (ocsp response)
3506 if (!BUF_MEM_grow(s->init_buf, 8 + s->tlsext_ocsp_resplen)) {
3507 s->state = SSL_ST_ERR;
3508 return -1;
3511 p = (unsigned char *)s->init_buf->data;
3513 /* do the header */
3514 *(p++) = SSL3_MT_CERTIFICATE_STATUS;
3515 /* message length */
3516 l2n3(s->tlsext_ocsp_resplen + 4, p);
3517 /* status type */
3518 *(p++) = s->tlsext_status_type;
3519 /* length of OCSP response */
3520 l2n3(s->tlsext_ocsp_resplen, p);
3521 /* actual response */
3522 memcpy(p, s->tlsext_ocsp_resp, s->tlsext_ocsp_resplen);
3523 /* number of bytes to write */
3524 s->init_num = 8 + s->tlsext_ocsp_resplen;
3525 s->state = SSL3_ST_SW_CERT_STATUS_B;
3526 s->init_off = 0;
3529 /* SSL3_ST_SW_CERT_STATUS_B */
3530 return (ssl3_do_write(s, SSL3_RT_HANDSHAKE));
3533 # ifndef OPENSSL_NO_NEXTPROTONEG
3535 * ssl3_get_next_proto reads a Next Protocol Negotiation handshake message.
3536 * It sets the next_proto member in s if found
3538 int ssl3_get_next_proto(SSL *s)
3540 int ok;
3541 int proto_len, padding_len;
3542 long n;
3543 const unsigned char *p;
3546 * Clients cannot send a NextProtocol message if we didn't see the
3547 * extension in their ClientHello
3549 if (!s->s3->next_proto_neg_seen) {
3550 SSLerr(SSL_F_SSL3_GET_NEXT_PROTO,
3551 SSL_R_GOT_NEXT_PROTO_WITHOUT_EXTENSION);
3552 s->state = SSL_ST_ERR;
3553 return -1;
3556 /* See the payload format below */
3557 n = s->method->ssl_get_message(s,
3558 SSL3_ST_SR_NEXT_PROTO_A,
3559 SSL3_ST_SR_NEXT_PROTO_B,
3560 SSL3_MT_NEXT_PROTO, 514, &ok);
3562 if (!ok)
3563 return ((int)n);
3566 * s->state doesn't reflect whether ChangeCipherSpec has been received in
3567 * this handshake, but s->s3->change_cipher_spec does (will be reset by
3568 * ssl3_get_finished).
3570 if (!s->s3->change_cipher_spec) {
3571 SSLerr(SSL_F_SSL3_GET_NEXT_PROTO, SSL_R_GOT_NEXT_PROTO_BEFORE_A_CCS);
3572 s->state = SSL_ST_ERR;
3573 return -1;
3576 if (n < 2) {
3577 s->state = SSL_ST_ERR;
3578 return 0; /* The body must be > 1 bytes long */
3581 p = (unsigned char *)s->init_msg;
3584 * The payload looks like:
3585 * uint8 proto_len;
3586 * uint8 proto[proto_len];
3587 * uint8 padding_len;
3588 * uint8 padding[padding_len];
3590 proto_len = p[0];
3591 if (proto_len + 2 > s->init_num) {
3592 s->state = SSL_ST_ERR;
3593 return 0;
3595 padding_len = p[proto_len + 1];
3596 if (proto_len + padding_len + 2 != s->init_num) {
3597 s->state = SSL_ST_ERR;
3598 return 0;
3601 s->next_proto_negotiated = OPENSSL_malloc(proto_len);
3602 if (!s->next_proto_negotiated) {
3603 SSLerr(SSL_F_SSL3_GET_NEXT_PROTO, ERR_R_MALLOC_FAILURE);
3604 s->state = SSL_ST_ERR;
3605 return 0;
3607 memcpy(s->next_proto_negotiated, p + 1, proto_len);
3608 s->next_proto_negotiated_len = proto_len;
3610 return 1;
3612 # endif
3614 #endif