etc/services - sync with NetBSD-8
[minix.git] / crypto / external / bsd / openssl / dist / ssl / s3_srvr.c
blob4dcc77bb9117d263953986893fcfda7a50185d6f
1 /* ssl/s3_srvr.c -*- mode:C; c-file-style: "eay" -*- */
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 &= ~SSL3_FLAGS_SGC_RESTART_DONE;
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 if (s->rwstate != SSL_X509_LOOKUP) {
364 ret = ssl3_get_client_hello(s);
365 if (ret <= 0)
366 goto end;
368 #ifndef OPENSSL_NO_SRP
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 = SSL_TLSEXT_ERR_ALERT_FATAL;
387 ret = -1;
388 s->state = SSL_ST_ERR;
389 goto end;
392 #endif
394 s->renegotiate = 2;
395 s->state = SSL3_ST_SW_SRVR_HELLO_A;
396 s->init_num = 0;
397 break;
399 case SSL3_ST_SW_SRVR_HELLO_A:
400 case SSL3_ST_SW_SRVR_HELLO_B:
401 ret = ssl3_send_server_hello(s);
402 if (ret <= 0)
403 goto end;
404 #ifndef OPENSSL_NO_TLSEXT
405 if (s->hit) {
406 if (s->tlsext_ticket_expected)
407 s->state = SSL3_ST_SW_SESSION_TICKET_A;
408 else
409 s->state = SSL3_ST_SW_CHANGE_A;
411 #else
412 if (s->hit)
413 s->state = SSL3_ST_SW_CHANGE_A;
414 #endif
415 else
416 s->state = SSL3_ST_SW_CERT_A;
417 s->init_num = 0;
418 break;
420 case SSL3_ST_SW_CERT_A:
421 case SSL3_ST_SW_CERT_B:
422 /* Check if it is anon DH or anon ECDH, */
423 /* normal PSK or KRB5 or SRP */
424 if (!
425 (s->s3->tmp.
426 new_cipher->algorithm_auth & (SSL_aNULL | SSL_aKRB5 |
427 SSL_aSRP))
428 && !(s->s3->tmp.new_cipher->algorithm_mkey & SSL_kPSK)) {
429 ret = ssl3_send_server_certificate(s);
430 if (ret <= 0)
431 goto end;
432 #ifndef OPENSSL_NO_TLSEXT
433 if (s->tlsext_status_expected)
434 s->state = SSL3_ST_SW_CERT_STATUS_A;
435 else
436 s->state = SSL3_ST_SW_KEY_EXCH_A;
437 } else {
438 skip = 1;
439 s->state = SSL3_ST_SW_KEY_EXCH_A;
441 #else
442 } else
443 skip = 1;
445 s->state = SSL3_ST_SW_KEY_EXCH_A;
446 #endif
447 s->init_num = 0;
448 break;
450 case SSL3_ST_SW_KEY_EXCH_A:
451 case SSL3_ST_SW_KEY_EXCH_B:
452 alg_k = s->s3->tmp.new_cipher->algorithm_mkey;
455 * clear this, it may get reset by
456 * send_server_key_exchange
458 s->s3->tmp.use_rsa_tmp = 0;
461 * only send if a DH key exchange, fortezza or RSA but we have a
462 * sign only certificate PSK: may send PSK identity hints For
463 * ECC ciphersuites, we send a serverKeyExchange message only if
464 * the cipher suite is either ECDH-anon or ECDHE. In other cases,
465 * the server certificate contains the server's public key for
466 * key exchange.
468 if (0
470 * PSK: send ServerKeyExchange if PSK identity hint if
471 * provided
473 #ifndef OPENSSL_NO_PSK
474 || ((alg_k & SSL_kPSK) && s->ctx->psk_identity_hint)
475 #endif
476 #ifndef OPENSSL_NO_SRP
477 /* SRP: send ServerKeyExchange */
478 || (alg_k & SSL_kSRP)
479 #endif
480 || (alg_k & (SSL_kDHr | SSL_kDHd | SSL_kEDH))
481 || (alg_k & SSL_kEECDH)
482 || ((alg_k & SSL_kRSA)
483 && (s->cert->pkeys[SSL_PKEY_RSA_ENC].privatekey == NULL
484 || (SSL_C_IS_EXPORT(s->s3->tmp.new_cipher)
485 && EVP_PKEY_size(s->cert->pkeys
486 [SSL_PKEY_RSA_ENC].privatekey) *
487 8 > SSL_C_EXPORT_PKEYLENGTH(s->s3->tmp.new_cipher)
492 ret = ssl3_send_server_key_exchange(s);
493 if (ret <= 0)
494 goto end;
495 } else
496 skip = 1;
498 s->state = SSL3_ST_SW_CERT_REQ_A;
499 s->init_num = 0;
500 break;
502 case SSL3_ST_SW_CERT_REQ_A:
503 case SSL3_ST_SW_CERT_REQ_B:
504 if ( /* don't request cert unless asked for it: */
505 !(s->verify_mode & SSL_VERIFY_PEER) ||
507 * if SSL_VERIFY_CLIENT_ONCE is set, don't request cert
508 * during re-negotiation:
510 ((s->session->peer != NULL) &&
511 (s->verify_mode & SSL_VERIFY_CLIENT_ONCE)) ||
513 * never request cert in anonymous ciphersuites (see
514 * section "Certificate request" in SSL 3 drafts and in
515 * RFC 2246):
517 ((s->s3->tmp.new_cipher->algorithm_auth & SSL_aNULL) &&
519 * ... except when the application insists on
520 * verification (against the specs, but s3_clnt.c accepts
521 * this for SSL 3)
523 !(s->verify_mode & SSL_VERIFY_FAIL_IF_NO_PEER_CERT)) ||
525 * never request cert in Kerberos ciphersuites
527 (s->s3->tmp.new_cipher->algorithm_auth & SSL_aKRB5) ||
528 /* don't request certificate for SRP auth */
529 (s->s3->tmp.new_cipher->algorithm_auth & SSL_aSRP)
531 * With normal PSK Certificates and Certificate Requests
532 * are omitted
534 || (s->s3->tmp.new_cipher->algorithm_mkey & SSL_kPSK)) {
535 /* no cert request */
536 skip = 1;
537 s->s3->tmp.cert_request = 0;
538 s->state = SSL3_ST_SW_SRVR_DONE_A;
539 if (s->s3->handshake_buffer) {
540 if (!ssl3_digest_cached_records(s)) {
541 s->state = SSL_ST_ERR;
542 return -1;
545 } else {
546 s->s3->tmp.cert_request = 1;
547 ret = ssl3_send_certificate_request(s);
548 if (ret <= 0)
549 goto end;
550 #ifndef NETSCAPE_HANG_BUG
551 s->state = SSL3_ST_SW_SRVR_DONE_A;
552 #else
553 s->state = SSL3_ST_SW_FLUSH;
554 s->s3->tmp.next_state = SSL3_ST_SR_CERT_A;
555 #endif
556 s->init_num = 0;
558 break;
560 case SSL3_ST_SW_SRVR_DONE_A:
561 case SSL3_ST_SW_SRVR_DONE_B:
562 ret = ssl3_send_server_done(s);
563 if (ret <= 0)
564 goto end;
565 s->s3->tmp.next_state = SSL3_ST_SR_CERT_A;
566 s->state = SSL3_ST_SW_FLUSH;
567 s->init_num = 0;
568 break;
570 case SSL3_ST_SW_FLUSH:
573 * This code originally checked to see if any data was pending
574 * using BIO_CTRL_INFO and then flushed. This caused problems as
575 * documented in PR#1939. The proposed fix doesn't completely
576 * resolve this issue as buggy implementations of
577 * BIO_CTRL_PENDING still exist. So instead we just flush
578 * unconditionally.
581 s->rwstate = SSL_WRITING;
582 if (BIO_flush(s->wbio) <= 0) {
583 ret = -1;
584 goto end;
586 s->rwstate = SSL_NOTHING;
588 s->state = s->s3->tmp.next_state;
589 break;
591 case SSL3_ST_SR_CERT_A:
592 case SSL3_ST_SR_CERT_B:
593 /* Check for second client hello (MS SGC) */
594 ret = ssl3_check_client_hello(s);
595 if (ret <= 0)
596 goto end;
597 if (ret == 2)
598 s->state = SSL3_ST_SR_CLNT_HELLO_C;
599 else {
600 if (s->s3->tmp.cert_request) {
601 ret = ssl3_get_client_certificate(s);
602 if (ret <= 0)
603 goto end;
605 s->init_num = 0;
606 s->state = SSL3_ST_SR_KEY_EXCH_A;
608 break;
610 case SSL3_ST_SR_KEY_EXCH_A:
611 case SSL3_ST_SR_KEY_EXCH_B:
612 ret = ssl3_get_client_key_exchange(s);
613 if (ret <= 0)
614 goto end;
615 if (ret == 2) {
617 * For the ECDH ciphersuites when the client sends its ECDH
618 * pub key in a certificate, the CertificateVerify message is
619 * not sent. Also for GOST ciphersuites when the client uses
620 * its key from the certificate for key exchange.
622 #if defined(OPENSSL_NO_TLSEXT) || defined(OPENSSL_NO_NEXTPROTONEG)
623 s->state = SSL3_ST_SR_FINISHED_A;
624 #else
625 if (s->s3->next_proto_neg_seen)
626 s->state = SSL3_ST_SR_NEXT_PROTO_A;
627 else
628 s->state = SSL3_ST_SR_FINISHED_A;
629 #endif
630 s->init_num = 0;
631 } else if (TLS1_get_version(s) >= TLS1_2_VERSION) {
632 s->state = SSL3_ST_SR_CERT_VRFY_A;
633 s->init_num = 0;
634 if (!s->session->peer)
635 break;
637 * For TLS v1.2 freeze the handshake buffer at this point and
638 * digest cached records.
640 if (!s->s3->handshake_buffer) {
641 SSLerr(SSL_F_SSL3_ACCEPT, ERR_R_INTERNAL_ERROR);
642 s->state = SSL_ST_ERR;
643 return -1;
645 s->s3->flags |= TLS1_FLAGS_KEEP_HANDSHAKE;
646 if (!ssl3_digest_cached_records(s)) {
647 s->state = SSL_ST_ERR;
648 return -1;
650 } else {
651 int offset = 0;
652 int dgst_num;
654 s->state = SSL3_ST_SR_CERT_VRFY_A;
655 s->init_num = 0;
658 * We need to get hashes here so if there is a client cert,
659 * it can be verified FIXME - digest processing for
660 * CertificateVerify should be generalized. But it is next
661 * step
663 if (s->s3->handshake_buffer) {
664 if (!ssl3_digest_cached_records(s)) {
665 s->state = SSL_ST_ERR;
666 return -1;
669 for (dgst_num = 0; dgst_num < SSL_MAX_DIGEST; dgst_num++)
670 if (s->s3->handshake_dgst[dgst_num]) {
671 int dgst_size;
673 s->method->ssl3_enc->cert_verify_mac(s,
674 EVP_MD_CTX_type
675 (s->
676 s3->handshake_dgst
677 [dgst_num]),
678 &(s->s3->
679 tmp.cert_verify_md
680 [offset]));
681 dgst_size =
682 EVP_MD_CTX_size(s->s3->handshake_dgst[dgst_num]);
683 if (dgst_size < 0) {
684 s->state = SSL_ST_ERR;
685 ret = -1;
686 goto end;
688 offset += dgst_size;
691 break;
693 case SSL3_ST_SR_CERT_VRFY_A:
694 case SSL3_ST_SR_CERT_VRFY_B:
695 ret = ssl3_get_cert_verify(s);
696 if (ret <= 0)
697 goto end;
699 #if defined(OPENSSL_NO_TLSEXT) || defined(OPENSSL_NO_NEXTPROTONEG)
700 s->state = SSL3_ST_SR_FINISHED_A;
701 #else
702 if (s->s3->next_proto_neg_seen)
703 s->state = SSL3_ST_SR_NEXT_PROTO_A;
704 else
705 s->state = SSL3_ST_SR_FINISHED_A;
706 #endif
707 s->init_num = 0;
708 break;
710 #if !defined(OPENSSL_NO_TLSEXT) && !defined(OPENSSL_NO_NEXTPROTONEG)
711 case SSL3_ST_SR_NEXT_PROTO_A:
712 case SSL3_ST_SR_NEXT_PROTO_B:
714 * Enable CCS for NPN. Receiving a CCS clears the flag, so make
715 * sure not to re-enable it to ban duplicates. This *should* be the
716 * first time we have received one - but we check anyway to be
717 * cautious.
718 * s->s3->change_cipher_spec is set when a CCS is
719 * processed in s3_pkt.c, and remains set until
720 * the client's Finished message is read.
722 if (!s->s3->change_cipher_spec)
723 s->s3->flags |= SSL3_FLAGS_CCS_OK;
725 ret = ssl3_get_next_proto(s);
726 if (ret <= 0)
727 goto end;
728 s->init_num = 0;
729 s->state = SSL3_ST_SR_FINISHED_A;
730 break;
731 #endif
733 case SSL3_ST_SR_FINISHED_A:
734 case SSL3_ST_SR_FINISHED_B:
736 * Enable CCS for handshakes without NPN. In NPN the CCS flag has
737 * already been set. Receiving a CCS clears the flag, so make
738 * sure not to re-enable it to ban duplicates.
739 * s->s3->change_cipher_spec is set when a CCS is
740 * processed in s3_pkt.c, and remains set until
741 * the client's Finished message is read.
743 if (!s->s3->change_cipher_spec)
744 s->s3->flags |= SSL3_FLAGS_CCS_OK;
745 ret = ssl3_get_finished(s, SSL3_ST_SR_FINISHED_A,
746 SSL3_ST_SR_FINISHED_B);
747 if (ret <= 0)
748 goto end;
749 if (s->hit)
750 s->state = SSL_ST_OK;
751 #ifndef OPENSSL_NO_TLSEXT
752 else if (s->tlsext_ticket_expected)
753 s->state = SSL3_ST_SW_SESSION_TICKET_A;
754 #endif
755 else
756 s->state = SSL3_ST_SW_CHANGE_A;
757 s->init_num = 0;
758 break;
760 #ifndef OPENSSL_NO_TLSEXT
761 case SSL3_ST_SW_SESSION_TICKET_A:
762 case SSL3_ST_SW_SESSION_TICKET_B:
763 ret = ssl3_send_newsession_ticket(s);
764 if (ret <= 0)
765 goto end;
766 s->state = SSL3_ST_SW_CHANGE_A;
767 s->init_num = 0;
768 break;
770 case SSL3_ST_SW_CERT_STATUS_A:
771 case SSL3_ST_SW_CERT_STATUS_B:
772 ret = ssl3_send_cert_status(s);
773 if (ret <= 0)
774 goto end;
775 s->state = SSL3_ST_SW_KEY_EXCH_A;
776 s->init_num = 0;
777 break;
779 #endif
781 case SSL3_ST_SW_CHANGE_A:
782 case SSL3_ST_SW_CHANGE_B:
784 s->session->cipher = s->s3->tmp.new_cipher;
785 if (!s->method->ssl3_enc->setup_key_block(s)) {
786 ret = -1;
787 s->state = SSL_ST_ERR;
788 goto end;
791 ret = ssl3_send_change_cipher_spec(s,
792 SSL3_ST_SW_CHANGE_A,
793 SSL3_ST_SW_CHANGE_B);
795 if (ret <= 0)
796 goto end;
797 s->state = SSL3_ST_SW_FINISHED_A;
798 s->init_num = 0;
800 if (!s->method->ssl3_enc->change_cipher_state(s,
801 SSL3_CHANGE_CIPHER_SERVER_WRITE))
803 ret = -1;
804 s->state = SSL_ST_ERR;
805 goto end;
808 break;
810 case SSL3_ST_SW_FINISHED_A:
811 case SSL3_ST_SW_FINISHED_B:
812 ret = ssl3_send_finished(s,
813 SSL3_ST_SW_FINISHED_A,
814 SSL3_ST_SW_FINISHED_B,
815 s->method->
816 ssl3_enc->server_finished_label,
817 s->method->
818 ssl3_enc->server_finished_label_len);
819 if (ret <= 0)
820 goto end;
821 s->state = SSL3_ST_SW_FLUSH;
822 if (s->hit) {
823 #if defined(OPENSSL_NO_TLSEXT) || defined(OPENSSL_NO_NEXTPROTONEG)
824 s->s3->tmp.next_state = SSL3_ST_SR_FINISHED_A;
825 #else
826 if (s->s3->next_proto_neg_seen) {
827 s->s3->tmp.next_state = SSL3_ST_SR_NEXT_PROTO_A;
828 } else
829 s->s3->tmp.next_state = SSL3_ST_SR_FINISHED_A;
830 #endif
831 } else
832 s->s3->tmp.next_state = SSL_ST_OK;
833 s->init_num = 0;
834 break;
836 case SSL_ST_OK:
837 /* clean a few things up */
838 ssl3_cleanup_key_block(s);
840 BUF_MEM_free(s->init_buf);
841 s->init_buf = NULL;
843 /* remove buffering on output */
844 ssl_free_wbio_buffer(s);
846 s->init_num = 0;
848 if (s->renegotiate == 2) { /* skipped if we just sent a
849 * HelloRequest */
850 s->renegotiate = 0;
851 s->new_session = 0;
853 ssl_update_cache(s, SSL_SESS_CACHE_SERVER);
855 s->ctx->stats.sess_accept_good++;
856 /* s->server=1; */
857 s->handshake_func = ssl3_accept;
859 if (cb != NULL)
860 cb(s, SSL_CB_HANDSHAKE_DONE, 1);
863 ret = 1;
864 goto end;
865 /* break; */
867 case SSL_ST_ERR:
868 default:
869 SSLerr(SSL_F_SSL3_ACCEPT, SSL_R_UNKNOWN_STATE);
870 ret = -1;
871 goto end;
872 /* break; */
875 if (!s->s3->tmp.reuse_message && !skip) {
876 if (s->debug) {
877 if ((ret = BIO_flush(s->wbio)) <= 0)
878 goto end;
881 if ((cb != NULL) && (s->state != state)) {
882 new_state = s->state;
883 s->state = state;
884 cb(s, SSL_CB_ACCEPT_LOOP, 1);
885 s->state = new_state;
888 skip = 0;
890 end:
891 /* BIO_flush(s->wbio); */
893 s->in_handshake--;
894 if (cb != NULL)
895 cb(s, SSL_CB_ACCEPT_EXIT, ret);
896 return (ret);
899 int ssl3_send_hello_request(SSL *s)
901 unsigned char *p;
903 if (s->state == SSL3_ST_SW_HELLO_REQ_A) {
904 p = (unsigned char *)s->init_buf->data;
905 *(p++) = SSL3_MT_HELLO_REQUEST;
906 *(p++) = 0;
907 *(p++) = 0;
908 *(p++) = 0;
910 s->state = SSL3_ST_SW_HELLO_REQ_B;
911 /* number of bytes to write */
912 s->init_num = 4;
913 s->init_off = 0;
916 /* SSL3_ST_SW_HELLO_REQ_B */
917 return (ssl3_do_write(s, SSL3_RT_HANDSHAKE));
920 int ssl3_check_client_hello(SSL *s)
922 int ok;
923 long n;
925 /* We only allow the client to restart the handshake once per
926 * negotiation. */
927 if (s->s3->flags & SSL3_FLAGS_SGC_RESTART_DONE) {
928 SSLerr(SSL_F_SSL3_CHECK_CLIENT_HELLO, SSL_R_MULTIPLE_SGC_RESTARTS);
929 return -1;
933 * this function is called when we really expect a Certificate message,
934 * so permit appropriate message length
936 n = s->method->ssl_get_message(s,
937 SSL3_ST_SR_CERT_A,
938 SSL3_ST_SR_CERT_B,
939 -1, s->max_cert_list, &ok);
940 if (!ok)
941 return ((int)n);
942 s->s3->tmp.reuse_message = 1;
943 if (s->s3->tmp.message_type == SSL3_MT_CLIENT_HELLO) {
945 * We only allow the client to restart the handshake once per
946 * negotiation.
948 if (s->s3->flags & SSL3_FLAGS_SGC_RESTART_DONE) {
949 SSLerr(SSL_F_SSL3_CHECK_CLIENT_HELLO,
950 SSL_R_MULTIPLE_SGC_RESTARTS);
951 return -1;
954 * Throw away what we have done so far in the current handshake,
955 * which will now be aborted. (A full SSL_clear would be too much.)
957 #ifndef OPENSSL_NO_DH
958 if (s->s3->tmp.dh != NULL) {
959 DH_free(s->s3->tmp.dh);
960 s->s3->tmp.dh = NULL;
962 #endif
963 #ifndef OPENSSL_NO_ECDH
964 if (s->s3->tmp.ecdh != NULL) {
965 EC_KEY_free(s->s3->tmp.ecdh);
966 s->s3->tmp.ecdh = NULL;
968 #endif
969 s->s3->flags |= SSL3_FLAGS_SGC_RESTART_DONE;
970 return 2;
972 return 1;
975 int ssl3_get_client_hello(SSL *s)
977 int i, j, ok, al, ret = -1;
978 unsigned int cookie_len;
979 long n;
980 unsigned long id;
981 unsigned char *p, *d, *q;
982 SSL_CIPHER *c;
983 #ifndef OPENSSL_NO_COMP
984 SSL_COMP *comp = NULL;
985 #endif
986 STACK_OF(SSL_CIPHER) *ciphers = NULL;
989 * We do this so that we will respond with our native type. If we are
990 * TLSv1 and we get SSLv3, we will respond with TLSv1, This down
991 * switching should be handled by a different method. If we are SSLv3, we
992 * will respond with SSLv3, even if prompted with TLSv1.
994 if (s->state == SSL3_ST_SR_CLNT_HELLO_A) {
995 s->state = SSL3_ST_SR_CLNT_HELLO_B;
997 s->first_packet = 1;
998 n = s->method->ssl_get_message(s,
999 SSL3_ST_SR_CLNT_HELLO_B,
1000 SSL3_ST_SR_CLNT_HELLO_C,
1001 SSL3_MT_CLIENT_HELLO,
1002 SSL3_RT_MAX_PLAIN_LENGTH, &ok);
1004 if (!ok)
1005 return ((int)n);
1006 s->first_packet = 0;
1007 d = p = (unsigned char *)s->init_msg;
1010 * 2 bytes for client version, SSL3_RANDOM_SIZE bytes for random, 1 byte
1011 * for session id length
1013 if (n < 2 + SSL3_RANDOM_SIZE + 1) {
1014 al = SSL_AD_DECODE_ERROR;
1015 SSLerr(SSL_F_SSL3_GET_CLIENT_HELLO, SSL_R_LENGTH_TOO_SHORT);
1016 goto f_err;
1020 * use version from inside client hello, not from record header (may
1021 * differ: see RFC 2246, Appendix E, second paragraph)
1023 s->client_version = (((int)p[0]) << 8) | (int)p[1];
1024 p += 2;
1026 if ((s->version == DTLS1_VERSION && s->client_version > s->version) ||
1027 (s->version != DTLS1_VERSION && s->client_version < s->version)) {
1028 SSLerr(SSL_F_SSL3_GET_CLIENT_HELLO, SSL_R_WRONG_VERSION_NUMBER);
1029 if ((s->client_version >> 8) == SSL3_VERSION_MAJOR &&
1030 !s->enc_write_ctx && !s->write_hash) {
1032 * similar to ssl3_get_record, send alert using remote version
1033 * number
1035 s->version = s->client_version;
1037 al = SSL_AD_PROTOCOL_VERSION;
1038 goto f_err;
1042 * If we require cookies and this ClientHello doesn't contain one, just
1043 * return since we do not want to allocate any memory yet. So check
1044 * cookie length...
1046 if (SSL_get_options(s) & SSL_OP_COOKIE_EXCHANGE) {
1047 unsigned int session_length, cookie_length;
1049 session_length = *(p + SSL3_RANDOM_SIZE);
1051 if (p + SSL3_RANDOM_SIZE + session_length + 1 >= d + n) {
1052 al = SSL_AD_DECODE_ERROR;
1053 SSLerr(SSL_F_SSL3_GET_CLIENT_HELLO, SSL_R_LENGTH_TOO_SHORT);
1054 goto f_err;
1056 cookie_length = *(p + SSL3_RANDOM_SIZE + session_length + 1);
1058 if (cookie_length == 0)
1059 return 1;
1062 /* load the client random */
1063 memcpy(s->s3->client_random, p, SSL3_RANDOM_SIZE);
1064 p += SSL3_RANDOM_SIZE;
1066 /* get the session-id */
1067 j = *(p++);
1069 if (p + j > d + n) {
1070 al = SSL_AD_DECODE_ERROR;
1071 SSLerr(SSL_F_SSL3_GET_CLIENT_HELLO, SSL_R_LENGTH_TOO_SHORT);
1072 goto f_err;
1075 s->hit = 0;
1077 * Versions before 0.9.7 always allow clients to resume sessions in
1078 * renegotiation. 0.9.7 and later allow this by default, but optionally
1079 * ignore resumption requests with flag
1080 * SSL_OP_NO_SESSION_RESUMPTION_ON_RENEGOTIATION (it's a new flag rather
1081 * than a change to default behavior so that applications relying on this
1082 * for security won't even compile against older library versions).
1083 * 1.0.1 and later also have a function SSL_renegotiate_abbreviated() to
1084 * request renegotiation but not a new session (s->new_session remains
1085 * unset): for servers, this essentially just means that the
1086 * SSL_OP_NO_SESSION_RESUMPTION_ON_RENEGOTIATION setting will be ignored.
1088 if ((s->new_session
1089 && (s->options & SSL_OP_NO_SESSION_RESUMPTION_ON_RENEGOTIATION))) {
1090 if (!ssl_get_new_session(s, 1))
1091 goto err;
1092 } else {
1093 i = ssl_get_prev_session(s, p, j, d + n);
1095 * Only resume if the session's version matches the negotiated
1096 * version.
1097 * RFC 5246 does not provide much useful advice on resumption
1098 * with a different protocol version. It doesn't forbid it but
1099 * the sanity of such behaviour would be questionable.
1100 * In practice, clients do not accept a version mismatch and
1101 * will abort the handshake with an error.
1103 if (i == 1 && s->version == s->session->ssl_version) { /* previous
1104 * session */
1105 s->hit = 1;
1106 } else if (i == -1)
1107 goto err;
1108 else { /* i == 0 */
1110 if (!ssl_get_new_session(s, 1))
1111 goto err;
1115 p += j;
1117 if (s->version == DTLS1_VERSION || s->version == DTLS1_BAD_VER) {
1118 /* cookie stuff */
1119 if (p + 1 > d + n) {
1120 al = SSL_AD_DECODE_ERROR;
1121 SSLerr(SSL_F_SSL3_GET_CLIENT_HELLO, SSL_R_LENGTH_TOO_SHORT);
1122 goto f_err;
1124 cookie_len = *(p++);
1126 if (p + cookie_len > d + n) {
1127 al = SSL_AD_DECODE_ERROR;
1128 SSLerr(SSL_F_SSL3_GET_CLIENT_HELLO, SSL_R_LENGTH_TOO_SHORT);
1129 goto f_err;
1133 * The ClientHello may contain a cookie even if the
1134 * HelloVerify message has not been sent--make sure that it
1135 * does not cause an overflow.
1137 if (cookie_len > sizeof(s->d1->rcvd_cookie)) {
1138 /* too much data */
1139 al = SSL_AD_DECODE_ERROR;
1140 SSLerr(SSL_F_SSL3_GET_CLIENT_HELLO, SSL_R_COOKIE_MISMATCH);
1141 goto f_err;
1144 /* verify the cookie if appropriate option is set. */
1145 if ((SSL_get_options(s) & SSL_OP_COOKIE_EXCHANGE) && cookie_len > 0) {
1146 memcpy(s->d1->rcvd_cookie, p, cookie_len);
1148 if (s->ctx->app_verify_cookie_cb != NULL) {
1149 if (s->ctx->app_verify_cookie_cb(s, s->d1->rcvd_cookie,
1150 cookie_len) == 0) {
1151 al = SSL_AD_HANDSHAKE_FAILURE;
1152 SSLerr(SSL_F_SSL3_GET_CLIENT_HELLO,
1153 SSL_R_COOKIE_MISMATCH);
1154 goto f_err;
1156 /* else cookie verification succeeded */
1158 /* default verification */
1159 else if (memcmp(s->d1->rcvd_cookie, s->d1->cookie,
1160 s->d1->cookie_len) != 0) {
1161 al = SSL_AD_HANDSHAKE_FAILURE;
1162 SSLerr(SSL_F_SSL3_GET_CLIENT_HELLO, SSL_R_COOKIE_MISMATCH);
1163 goto f_err;
1166 ret = 2;
1169 p += cookie_len;
1172 if (p + 2 > d + n) {
1173 al = SSL_AD_DECODE_ERROR;
1174 SSLerr(SSL_F_SSL3_GET_CLIENT_HELLO, SSL_R_LENGTH_TOO_SHORT);
1175 goto f_err;
1177 n2s(p, i);
1179 if (i == 0) {
1180 al = SSL_AD_ILLEGAL_PARAMETER;
1181 SSLerr(SSL_F_SSL3_GET_CLIENT_HELLO, SSL_R_NO_CIPHERS_SPECIFIED);
1182 goto f_err;
1185 /* i bytes of cipher data + 1 byte for compression length later */
1186 if ((p + i + 1) > (d + n)) {
1187 /* not enough data */
1188 al = SSL_AD_DECODE_ERROR;
1189 SSLerr(SSL_F_SSL3_GET_CLIENT_HELLO, SSL_R_LENGTH_MISMATCH);
1190 goto f_err;
1192 if (ssl_bytes_to_cipher_list(s, p, i, &(ciphers)) == NULL) {
1193 goto err;
1195 p += i;
1197 /* If it is a hit, check that the cipher is in the list */
1198 if (s->hit) {
1199 j = 0;
1200 id = s->session->cipher->id;
1202 #ifdef CIPHER_DEBUG
1203 fprintf(stderr, "client sent %d ciphers\n",
1204 sk_SSL_CIPHER_num(ciphers));
1205 #endif
1206 for (i = 0; i < sk_SSL_CIPHER_num(ciphers); i++) {
1207 c = sk_SSL_CIPHER_value(ciphers, i);
1208 #ifdef CIPHER_DEBUG
1209 fprintf(stderr, "client [%2d of %2d]:%s\n",
1210 i, sk_SSL_CIPHER_num(ciphers), SSL_CIPHER_get_name(c));
1211 #endif
1212 if (c->id == id) {
1213 j = 1;
1214 break;
1218 * Disabled because it can be used in a ciphersuite downgrade attack:
1219 * CVE-2010-4180.
1221 #if 0
1222 if (j == 0 && (s->options & SSL_OP_NETSCAPE_REUSE_CIPHER_CHANGE_BUG)
1223 && (sk_SSL_CIPHER_num(ciphers) == 1)) {
1225 * Special case as client bug workaround: the previously used
1226 * cipher may not be in the current list, the client instead
1227 * might be trying to continue using a cipher that before wasn't
1228 * chosen due to server preferences. We'll have to reject the
1229 * connection if the cipher is not enabled, though.
1231 c = sk_SSL_CIPHER_value(ciphers, 0);
1232 if (sk_SSL_CIPHER_find(SSL_get_ciphers(s), c) >= 0) {
1233 s->session->cipher = c;
1234 j = 1;
1237 #endif
1238 if (j == 0) {
1240 * we need to have the cipher in the cipher list if we are asked
1241 * to reuse it
1243 al = SSL_AD_ILLEGAL_PARAMETER;
1244 SSLerr(SSL_F_SSL3_GET_CLIENT_HELLO,
1245 SSL_R_REQUIRED_CIPHER_MISSING);
1246 goto f_err;
1250 /* compression */
1251 i = *(p++);
1252 if ((p + i) > (d + n)) {
1253 /* not enough data */
1254 al = SSL_AD_DECODE_ERROR;
1255 SSLerr(SSL_F_SSL3_GET_CLIENT_HELLO, SSL_R_LENGTH_MISMATCH);
1256 goto f_err;
1258 q = p;
1259 for (j = 0; j < i; j++) {
1260 if (p[j] == 0)
1261 break;
1264 p += i;
1265 if (j >= i) {
1266 /* no compress */
1267 al = SSL_AD_DECODE_ERROR;
1268 SSLerr(SSL_F_SSL3_GET_CLIENT_HELLO, SSL_R_NO_COMPRESSION_SPECIFIED);
1269 goto f_err;
1271 #ifndef OPENSSL_NO_TLSEXT
1272 /* TLS extensions */
1273 if (s->version >= SSL3_VERSION) {
1274 if (!ssl_parse_clienthello_tlsext(s, &p, d, n, &al)) {
1275 /* 'al' set by ssl_parse_clienthello_tlsext */
1276 SSLerr(SSL_F_SSL3_GET_CLIENT_HELLO, SSL_R_PARSE_TLSEXT);
1277 goto f_err;
1280 if (ssl_check_clienthello_tlsext_early(s) <= 0) {
1281 SSLerr(SSL_F_SSL3_GET_CLIENT_HELLO, SSL_R_CLIENTHELLO_TLSEXT);
1282 goto err;
1286 * Check if we want to use external pre-shared secret for this handshake
1287 * for not reused session only. We need to generate server_random before
1288 * calling tls_session_secret_cb in order to allow SessionTicket
1289 * processing to use it in key derivation.
1292 unsigned char *pos;
1293 pos = s->s3->server_random;
1294 if (ssl_fill_hello_random(s, 1, pos, SSL3_RANDOM_SIZE) <= 0) {
1295 al = SSL_AD_INTERNAL_ERROR;
1296 goto f_err;
1300 if (!s->hit && s->version >= TLS1_VERSION && s->tls_session_secret_cb) {
1301 SSL_CIPHER *pref_cipher = NULL;
1303 s->session->master_key_length = sizeof(s->session->master_key);
1304 if (s->tls_session_secret_cb(s, s->session->master_key,
1305 &s->session->master_key_length, ciphers,
1306 &pref_cipher,
1307 s->tls_session_secret_cb_arg)) {
1308 s->hit = 1;
1309 s->session->ciphers = ciphers;
1310 s->session->verify_result = X509_V_OK;
1312 ciphers = NULL;
1314 /* check if some cipher was preferred by call back */
1315 pref_cipher =
1316 pref_cipher ? pref_cipher : ssl3_choose_cipher(s,
1318 session->ciphers,
1319 SSL_get_ciphers
1320 (s));
1321 if (pref_cipher == NULL) {
1322 al = SSL_AD_HANDSHAKE_FAILURE;
1323 SSLerr(SSL_F_SSL3_GET_CLIENT_HELLO, SSL_R_NO_SHARED_CIPHER);
1324 goto f_err;
1327 s->session->cipher = pref_cipher;
1329 if (s->cipher_list)
1330 sk_SSL_CIPHER_free(s->cipher_list);
1332 if (s->cipher_list_by_id)
1333 sk_SSL_CIPHER_free(s->cipher_list_by_id);
1335 s->cipher_list = sk_SSL_CIPHER_dup(s->session->ciphers);
1336 s->cipher_list_by_id = sk_SSL_CIPHER_dup(s->session->ciphers);
1339 #endif
1342 * Worst case, we will use the NULL compression, but if we have other
1343 * options, we will now look for them. We have i-1 compression
1344 * algorithms from the client, starting at q.
1346 s->s3->tmp.new_compression = NULL;
1347 #ifndef OPENSSL_NO_COMP
1348 /* This only happens if we have a cache hit */
1349 if (s->session->compress_meth != 0) {
1350 int m, comp_id = s->session->compress_meth;
1351 /* Perform sanity checks on resumed compression algorithm */
1352 /* Can't disable compression */
1353 if (s->options & SSL_OP_NO_COMPRESSION) {
1354 al = SSL_AD_INTERNAL_ERROR;
1355 SSLerr(SSL_F_SSL3_GET_CLIENT_HELLO,
1356 SSL_R_INCONSISTENT_COMPRESSION);
1357 goto f_err;
1359 /* Look for resumed compression method */
1360 for (m = 0; m < sk_SSL_COMP_num(s->ctx->comp_methods); m++) {
1361 comp = sk_SSL_COMP_value(s->ctx->comp_methods, m);
1362 if (comp_id == comp->id) {
1363 s->s3->tmp.new_compression = comp;
1364 break;
1367 if (s->s3->tmp.new_compression == NULL) {
1368 al = SSL_AD_INTERNAL_ERROR;
1369 SSLerr(SSL_F_SSL3_GET_CLIENT_HELLO,
1370 SSL_R_INVALID_COMPRESSION_ALGORITHM);
1371 goto f_err;
1373 /* Look for resumed method in compression list */
1374 for (m = 0; m < i; m++) {
1375 if (q[m] == comp_id)
1376 break;
1378 if (m >= i) {
1379 al = SSL_AD_ILLEGAL_PARAMETER;
1380 SSLerr(SSL_F_SSL3_GET_CLIENT_HELLO,
1381 SSL_R_REQUIRED_COMPRESSSION_ALGORITHM_MISSING);
1382 goto f_err;
1384 } else if (s->hit)
1385 comp = NULL;
1386 else if (!(s->options & SSL_OP_NO_COMPRESSION) && s->ctx->comp_methods) {
1387 /* See if we have a match */
1388 int m, nn, o, v, done = 0;
1390 nn = sk_SSL_COMP_num(s->ctx->comp_methods);
1391 for (m = 0; m < nn; m++) {
1392 comp = sk_SSL_COMP_value(s->ctx->comp_methods, m);
1393 v = comp->id;
1394 for (o = 0; o < i; o++) {
1395 if (v == q[o]) {
1396 done = 1;
1397 break;
1400 if (done)
1401 break;
1403 if (done)
1404 s->s3->tmp.new_compression = comp;
1405 else
1406 comp = NULL;
1408 #else
1410 * If compression is disabled we'd better not try to resume a session
1411 * using compression.
1413 if (s->session->compress_meth != 0) {
1414 al = SSL_AD_INTERNAL_ERROR;
1415 SSLerr(SSL_F_SSL3_GET_CLIENT_HELLO, SSL_R_INCONSISTENT_COMPRESSION);
1416 goto f_err;
1418 #endif
1421 * Given s->session->ciphers and SSL_get_ciphers, we must pick a cipher
1424 if (!s->hit) {
1425 #ifdef OPENSSL_NO_COMP
1426 s->session->compress_meth = 0;
1427 #else
1428 s->session->compress_meth = (comp == NULL) ? 0 : comp->id;
1429 #endif
1430 if (s->session->ciphers != NULL)
1431 sk_SSL_CIPHER_free(s->session->ciphers);
1432 s->session->ciphers = ciphers;
1433 if (ciphers == NULL) {
1434 al = SSL_AD_INTERNAL_ERROR;
1435 SSLerr(SSL_F_SSL3_GET_CLIENT_HELLO, ERR_R_INTERNAL_ERROR);
1436 goto f_err;
1438 ciphers = NULL;
1439 c = ssl3_choose_cipher(s, s->session->ciphers, SSL_get_ciphers(s));
1441 if (c == NULL) {
1442 al = SSL_AD_HANDSHAKE_FAILURE;
1443 SSLerr(SSL_F_SSL3_GET_CLIENT_HELLO, SSL_R_NO_SHARED_CIPHER);
1444 goto f_err;
1446 s->s3->tmp.new_cipher = c;
1447 } else {
1448 /* Session-id reuse */
1449 #ifdef REUSE_CIPHER_BUG
1450 STACK_OF(SSL_CIPHER) *sk;
1451 SSL_CIPHER *nc = NULL;
1452 SSL_CIPHER *ec = NULL;
1454 if (s->options & SSL_OP_NETSCAPE_DEMO_CIPHER_CHANGE_BUG) {
1455 sk = s->session->ciphers;
1456 for (i = 0; i < sk_SSL_CIPHER_num(sk); i++) {
1457 c = sk_SSL_CIPHER_value(sk, i);
1458 if (c->algorithm_enc & SSL_eNULL)
1459 nc = c;
1460 if (SSL_C_IS_EXPORT(c))
1461 ec = c;
1463 if (nc != NULL)
1464 s->s3->tmp.new_cipher = nc;
1465 else if (ec != NULL)
1466 s->s3->tmp.new_cipher = ec;
1467 else
1468 s->s3->tmp.new_cipher = s->session->cipher;
1469 } else
1470 #endif
1471 s->s3->tmp.new_cipher = s->session->cipher;
1474 if (TLS1_get_version(s) < TLS1_2_VERSION
1475 || !(s->verify_mode & SSL_VERIFY_PEER)) {
1476 if (!ssl3_digest_cached_records(s)) {
1477 al = SSL_AD_INTERNAL_ERROR;
1478 goto f_err;
1483 * we now have the following setup.
1484 * client_random
1485 * cipher_list - our prefered list of ciphers
1486 * ciphers - the clients prefered list of ciphers
1487 * compression - basically ignored right now
1488 * ssl version is set - sslv3
1489 * s->session - The ssl session has been setup.
1490 * s->hit - session reuse flag
1491 * s->tmp.new_cipher - the new cipher to use.
1494 /* Handles TLS extensions that we couldn't check earlier */
1495 if (s->version >= SSL3_VERSION) {
1496 if (ssl_check_clienthello_tlsext_late(s) <= 0) {
1497 SSLerr(SSL_F_SSL3_GET_CLIENT_HELLO, SSL_R_CLIENTHELLO_TLSEXT);
1498 goto err;
1502 if (ret < 0)
1503 ret = 1;
1504 if (0) {
1505 f_err:
1506 ssl3_send_alert(s, SSL3_AL_FATAL, al);
1507 err:
1508 s->state = SSL_ST_ERR;
1511 if (ciphers != NULL)
1512 sk_SSL_CIPHER_free(ciphers);
1513 return (ret);
1516 int ssl3_send_server_hello(SSL *s)
1518 unsigned char *buf;
1519 unsigned char *p, *d;
1520 int i, sl;
1521 unsigned long l;
1523 if (s->state == SSL3_ST_SW_SRVR_HELLO_A) {
1524 buf = (unsigned char *)s->init_buf->data;
1525 #ifdef OPENSSL_NO_TLSEXT
1526 p = s->s3->server_random;
1527 if (ssl_fill_hello_random(s, 1, p, SSL3_RANDOM_SIZE) <= 0) {
1528 s->state = SSL_ST_ERR;
1529 return -1;
1531 #endif
1532 /* Do the message type and length last */
1533 d = p = &(buf[4]);
1535 *(p++) = s->version >> 8;
1536 *(p++) = s->version & 0xff;
1538 /* Random stuff */
1539 memcpy(p, s->s3->server_random, SSL3_RANDOM_SIZE);
1540 p += SSL3_RANDOM_SIZE;
1543 * There are several cases for the session ID to send
1544 * back in the server hello:
1545 * - For session reuse from the session cache,
1546 * we send back the old session ID.
1547 * - If stateless session reuse (using a session ticket)
1548 * is successful, we send back the client's "session ID"
1549 * (which doesn't actually identify the session).
1550 * - If it is a new session, we send back the new
1551 * session ID.
1552 * - However, if we want the new session to be single-use,
1553 * we send back a 0-length session ID.
1554 * s->hit is non-zero in either case of session reuse,
1555 * so the following won't overwrite an ID that we're supposed
1556 * to send back.
1558 if (!(s->ctx->session_cache_mode & SSL_SESS_CACHE_SERVER)
1559 && !s->hit)
1560 s->session->session_id_length = 0;
1562 sl = s->session->session_id_length;
1563 if (sl > (int)sizeof(s->session->session_id)) {
1564 SSLerr(SSL_F_SSL3_SEND_SERVER_HELLO, ERR_R_INTERNAL_ERROR);
1565 s->state = SSL_ST_ERR;
1566 return -1;
1568 *(p++) = sl;
1569 memcpy(p, s->session->session_id, sl);
1570 p += sl;
1572 /* put the cipher */
1573 i = ssl3_put_cipher_by_char(s->s3->tmp.new_cipher, p);
1574 p += i;
1576 /* put the compression method */
1577 #ifdef OPENSSL_NO_COMP
1578 *(p++) = 0;
1579 #else
1580 if (s->s3->tmp.new_compression == NULL)
1581 *(p++) = 0;
1582 else
1583 *(p++) = s->s3->tmp.new_compression->id;
1584 #endif
1585 #ifndef OPENSSL_NO_TLSEXT
1586 if (ssl_prepare_serverhello_tlsext(s) <= 0) {
1587 SSLerr(SSL_F_SSL3_SEND_SERVER_HELLO, SSL_R_SERVERHELLO_TLSEXT);
1588 s->state = SSL_ST_ERR;
1589 return -1;
1591 if ((p =
1592 ssl_add_serverhello_tlsext(s, p,
1593 buf + SSL3_RT_MAX_PLAIN_LENGTH)) ==
1594 NULL) {
1595 SSLerr(SSL_F_SSL3_SEND_SERVER_HELLO, ERR_R_INTERNAL_ERROR);
1596 s->state = SSL_ST_ERR;
1597 return -1;
1599 #endif
1600 /* do the header */
1601 l = (p - d);
1602 d = buf;
1603 *(d++) = SSL3_MT_SERVER_HELLO;
1604 l2n3(l, d);
1606 s->state = SSL3_ST_SW_SRVR_HELLO_B;
1607 /* number of bytes to write */
1608 s->init_num = p - buf;
1609 s->init_off = 0;
1612 /* SSL3_ST_SW_SRVR_HELLO_B */
1613 return (ssl3_do_write(s, SSL3_RT_HANDSHAKE));
1616 int ssl3_send_server_done(SSL *s)
1618 unsigned char *p;
1620 if (s->state == SSL3_ST_SW_SRVR_DONE_A) {
1621 p = (unsigned char *)s->init_buf->data;
1623 /* do the header */
1624 *(p++) = SSL3_MT_SERVER_DONE;
1625 *(p++) = 0;
1626 *(p++) = 0;
1627 *(p++) = 0;
1629 s->state = SSL3_ST_SW_SRVR_DONE_B;
1630 /* number of bytes to write */
1631 s->init_num = 4;
1632 s->init_off = 0;
1635 /* SSL3_ST_SW_SRVR_DONE_B */
1636 return (ssl3_do_write(s, SSL3_RT_HANDSHAKE));
1639 int ssl3_send_server_key_exchange(SSL *s)
1641 #ifndef OPENSSL_NO_RSA
1642 unsigned char *q;
1643 int j, num;
1644 RSA *rsa;
1645 unsigned char md_buf[MD5_DIGEST_LENGTH + SHA_DIGEST_LENGTH];
1646 unsigned int u;
1647 #endif
1648 #ifndef OPENSSL_NO_DH
1649 DH *dh = NULL, *dhp;
1650 #endif
1651 #ifndef OPENSSL_NO_ECDH
1652 EC_KEY *ecdh = NULL, *ecdhp;
1653 unsigned char *encodedPoint = NULL;
1654 int encodedlen = 0;
1655 int curve_id = 0;
1656 BN_CTX *bn_ctx = NULL;
1657 #endif
1658 EVP_PKEY *pkey;
1659 const EVP_MD *md = NULL;
1660 unsigned char *p, *d;
1661 int al, i;
1662 unsigned long type;
1663 int n;
1664 CERT *cert;
1665 BIGNUM *r[4];
1666 int nr[4], kn;
1667 BUF_MEM *buf;
1668 EVP_MD_CTX md_ctx;
1670 EVP_MD_CTX_init(&md_ctx);
1671 if (s->state == SSL3_ST_SW_KEY_EXCH_A) {
1672 type = s->s3->tmp.new_cipher->algorithm_mkey;
1673 cert = s->cert;
1675 buf = s->init_buf;
1677 r[0] = r[1] = r[2] = r[3] = NULL;
1678 n = 0;
1679 #ifndef OPENSSL_NO_RSA
1680 if (type & SSL_kRSA) {
1681 rsa = cert->rsa_tmp;
1682 if ((rsa == NULL) && (s->cert->rsa_tmp_cb != NULL)) {
1683 rsa = s->cert->rsa_tmp_cb(s,
1684 SSL_C_IS_EXPORT(s->s3->
1685 tmp.new_cipher),
1686 SSL_C_EXPORT_PKEYLENGTH(s->s3->
1687 tmp.new_cipher));
1688 if (rsa == NULL) {
1689 al = SSL_AD_HANDSHAKE_FAILURE;
1690 SSLerr(SSL_F_SSL3_SEND_SERVER_KEY_EXCHANGE,
1691 SSL_R_ERROR_GENERATING_TMP_RSA_KEY);
1692 goto f_err;
1694 RSA_up_ref(rsa);
1695 cert->rsa_tmp = rsa;
1697 if (rsa == NULL) {
1698 al = SSL_AD_HANDSHAKE_FAILURE;
1699 SSLerr(SSL_F_SSL3_SEND_SERVER_KEY_EXCHANGE,
1700 SSL_R_MISSING_TMP_RSA_KEY);
1701 goto f_err;
1703 r[0] = rsa->n;
1704 r[1] = rsa->e;
1705 s->s3->tmp.use_rsa_tmp = 1;
1706 } else
1707 #endif
1708 #ifndef OPENSSL_NO_DH
1709 if (type & SSL_kEDH) {
1710 dhp = cert->dh_tmp;
1711 if ((dhp == NULL) && (s->cert->dh_tmp_cb != NULL))
1712 dhp = s->cert->dh_tmp_cb(s,
1713 SSL_C_IS_EXPORT(s->s3->
1714 tmp.new_cipher),
1715 SSL_C_EXPORT_PKEYLENGTH(s->s3->
1716 tmp.new_cipher));
1717 if (dhp == NULL) {
1718 al = SSL_AD_HANDSHAKE_FAILURE;
1719 SSLerr(SSL_F_SSL3_SEND_SERVER_KEY_EXCHANGE,
1720 SSL_R_MISSING_TMP_DH_KEY);
1721 goto f_err;
1724 if (s->s3->tmp.dh != NULL) {
1725 SSLerr(SSL_F_SSL3_SEND_SERVER_KEY_EXCHANGE,
1726 ERR_R_INTERNAL_ERROR);
1727 goto err;
1730 if ((dh = DHparams_dup(dhp)) == NULL) {
1731 SSLerr(SSL_F_SSL3_SEND_SERVER_KEY_EXCHANGE, ERR_R_DH_LIB);
1732 goto err;
1735 s->s3->tmp.dh = dh;
1736 if ((dhp->pub_key == NULL ||
1737 dhp->priv_key == NULL ||
1738 (s->options & SSL_OP_SINGLE_DH_USE))) {
1739 if (!DH_generate_key(dh)) {
1740 SSLerr(SSL_F_SSL3_SEND_SERVER_KEY_EXCHANGE, ERR_R_DH_LIB);
1741 goto err;
1743 } else {
1744 dh->pub_key = BN_dup(dhp->pub_key);
1745 dh->priv_key = BN_dup(dhp->priv_key);
1746 if ((dh->pub_key == NULL) || (dh->priv_key == NULL)) {
1747 SSLerr(SSL_F_SSL3_SEND_SERVER_KEY_EXCHANGE, ERR_R_DH_LIB);
1748 goto err;
1751 r[0] = dh->p;
1752 r[1] = dh->g;
1753 r[2] = dh->pub_key;
1754 } else
1755 #endif
1756 #ifndef OPENSSL_NO_ECDH
1757 if (type & SSL_kEECDH) {
1758 const EC_GROUP *group;
1760 ecdhp = cert->ecdh_tmp;
1761 if ((ecdhp == NULL) && (s->cert->ecdh_tmp_cb != NULL)) {
1762 ecdhp = s->cert->ecdh_tmp_cb(s,
1763 SSL_C_IS_EXPORT(s->s3->
1764 tmp.new_cipher),
1765 SSL_C_EXPORT_PKEYLENGTH(s->
1766 s3->tmp.new_cipher));
1768 if (ecdhp == NULL) {
1769 al = SSL_AD_HANDSHAKE_FAILURE;
1770 SSLerr(SSL_F_SSL3_SEND_SERVER_KEY_EXCHANGE,
1771 SSL_R_MISSING_TMP_ECDH_KEY);
1772 goto f_err;
1775 if (s->s3->tmp.ecdh != NULL) {
1776 SSLerr(SSL_F_SSL3_SEND_SERVER_KEY_EXCHANGE,
1777 ERR_R_INTERNAL_ERROR);
1778 goto err;
1781 /* Duplicate the ECDH structure. */
1782 if (ecdhp == NULL) {
1783 SSLerr(SSL_F_SSL3_SEND_SERVER_KEY_EXCHANGE, ERR_R_ECDH_LIB);
1784 goto err;
1786 if ((ecdh = EC_KEY_dup(ecdhp)) == NULL) {
1787 SSLerr(SSL_F_SSL3_SEND_SERVER_KEY_EXCHANGE, ERR_R_ECDH_LIB);
1788 goto err;
1791 s->s3->tmp.ecdh = ecdh;
1792 if ((EC_KEY_get0_public_key(ecdh) == NULL) ||
1793 (EC_KEY_get0_private_key(ecdh) == NULL) ||
1794 (s->options & SSL_OP_SINGLE_ECDH_USE)) {
1795 if (!EC_KEY_generate_key(ecdh)) {
1796 SSLerr(SSL_F_SSL3_SEND_SERVER_KEY_EXCHANGE,
1797 ERR_R_ECDH_LIB);
1798 goto err;
1802 if (((group = EC_KEY_get0_group(ecdh)) == NULL) ||
1803 (EC_KEY_get0_public_key(ecdh) == NULL) ||
1804 (EC_KEY_get0_private_key(ecdh) == NULL)) {
1805 SSLerr(SSL_F_SSL3_SEND_SERVER_KEY_EXCHANGE, ERR_R_ECDH_LIB);
1806 goto err;
1809 if (SSL_C_IS_EXPORT(s->s3->tmp.new_cipher) &&
1810 (EC_GROUP_get_degree(group) > 163)) {
1811 SSLerr(SSL_F_SSL3_SEND_SERVER_KEY_EXCHANGE,
1812 SSL_R_ECGROUP_TOO_LARGE_FOR_CIPHER);
1813 goto err;
1817 * XXX: For now, we only support ephemeral ECDH keys over named
1818 * (not generic) curves. For supported named curves, curve_id is
1819 * non-zero.
1821 if ((curve_id =
1822 tls1_ec_nid2curve_id(EC_GROUP_get_curve_name(group)))
1823 == 0) {
1824 SSLerr(SSL_F_SSL3_SEND_SERVER_KEY_EXCHANGE,
1825 SSL_R_UNSUPPORTED_ELLIPTIC_CURVE);
1826 goto err;
1830 * Encode the public key. First check the size of encoding and
1831 * allocate memory accordingly.
1833 encodedlen = EC_POINT_point2oct(group,
1834 EC_KEY_get0_public_key(ecdh),
1835 POINT_CONVERSION_UNCOMPRESSED,
1836 NULL, 0, NULL);
1838 encodedPoint = (unsigned char *)
1839 OPENSSL_malloc(encodedlen * sizeof(unsigned char));
1840 bn_ctx = BN_CTX_new();
1841 if ((encodedPoint == NULL) || (bn_ctx == NULL)) {
1842 SSLerr(SSL_F_SSL3_SEND_SERVER_KEY_EXCHANGE,
1843 ERR_R_MALLOC_FAILURE);
1844 goto err;
1847 encodedlen = EC_POINT_point2oct(group,
1848 EC_KEY_get0_public_key(ecdh),
1849 POINT_CONVERSION_UNCOMPRESSED,
1850 encodedPoint, encodedlen, bn_ctx);
1852 if (encodedlen == 0) {
1853 SSLerr(SSL_F_SSL3_SEND_SERVER_KEY_EXCHANGE, ERR_R_ECDH_LIB);
1854 goto err;
1857 BN_CTX_free(bn_ctx);
1858 bn_ctx = NULL;
1861 * XXX: For now, we only support named (not generic) curves in
1862 * ECDH ephemeral key exchanges. In this situation, we need four
1863 * additional bytes to encode the entire ServerECDHParams
1864 * structure.
1866 n = 4 + encodedlen;
1869 * We'll generate the serverKeyExchange message explicitly so we
1870 * can set these to NULLs
1872 r[0] = NULL;
1873 r[1] = NULL;
1874 r[2] = NULL;
1875 r[3] = NULL;
1876 } else
1877 #endif /* !OPENSSL_NO_ECDH */
1878 #ifndef OPENSSL_NO_PSK
1879 if (type & SSL_kPSK) {
1881 * reserve size for record length and PSK identity hint
1883 n += 2 + strlen(s->ctx->psk_identity_hint);
1884 } else
1885 #endif /* !OPENSSL_NO_PSK */
1886 #ifndef OPENSSL_NO_SRP
1887 if (type & SSL_kSRP) {
1888 if ((s->srp_ctx.N == NULL) ||
1889 (s->srp_ctx.g == NULL) ||
1890 (s->srp_ctx.s == NULL) || (s->srp_ctx.B == NULL)) {
1891 SSLerr(SSL_F_SSL3_SEND_SERVER_KEY_EXCHANGE,
1892 SSL_R_MISSING_SRP_PARAM);
1893 goto err;
1895 r[0] = s->srp_ctx.N;
1896 r[1] = s->srp_ctx.g;
1897 r[2] = s->srp_ctx.s;
1898 r[3] = s->srp_ctx.B;
1899 } else
1900 #endif
1902 al = SSL_AD_HANDSHAKE_FAILURE;
1903 SSLerr(SSL_F_SSL3_SEND_SERVER_KEY_EXCHANGE,
1904 SSL_R_UNKNOWN_KEY_EXCHANGE_TYPE);
1905 goto f_err;
1907 for (i = 0; i < 4 && r[i] != NULL; i++) {
1908 nr[i] = BN_num_bytes(r[i]);
1909 #ifndef OPENSSL_NO_SRP
1910 if ((i == 2) && (type & SSL_kSRP))
1911 n += 1 + nr[i];
1912 else
1913 #endif
1914 n += 2 + nr[i];
1917 if (!(s->s3->tmp.new_cipher->algorithm_auth & (SSL_aNULL | SSL_aSRP))
1918 && !(s->s3->tmp.new_cipher->algorithm_mkey & SSL_kPSK)) {
1919 if ((pkey = ssl_get_sign_pkey(s, s->s3->tmp.new_cipher, &md))
1920 == NULL) {
1921 al = SSL_AD_DECODE_ERROR;
1922 goto f_err;
1924 kn = EVP_PKEY_size(pkey);
1925 } else {
1926 pkey = NULL;
1927 kn = 0;
1930 if (!BUF_MEM_grow_clean(buf, n + 4 + kn)) {
1931 SSLerr(SSL_F_SSL3_SEND_SERVER_KEY_EXCHANGE, ERR_LIB_BUF);
1932 goto err;
1934 d = (unsigned char *)s->init_buf->data;
1935 p = &(d[4]);
1937 for (i = 0; i < 4 && r[i] != NULL; i++) {
1938 #ifndef OPENSSL_NO_SRP
1939 if ((i == 2) && (type & SSL_kSRP)) {
1940 *p = nr[i];
1941 p++;
1942 } else
1943 #endif
1944 s2n(nr[i], p);
1945 BN_bn2bin(r[i], p);
1946 p += nr[i];
1949 #ifndef OPENSSL_NO_ECDH
1950 if (type & SSL_kEECDH) {
1952 * XXX: For now, we only support named (not generic) curves. In
1953 * this situation, the serverKeyExchange message has: [1 byte
1954 * CurveType], [2 byte CurveName] [1 byte length of encoded
1955 * point], followed by the actual encoded point itself
1957 *p = NAMED_CURVE_TYPE;
1958 p += 1;
1959 *p = 0;
1960 p += 1;
1961 *p = curve_id;
1962 p += 1;
1963 *p = encodedlen;
1964 p += 1;
1965 memcpy((unsigned char *)p,
1966 (unsigned char *)encodedPoint, encodedlen);
1967 OPENSSL_free(encodedPoint);
1968 encodedPoint = NULL;
1969 p += encodedlen;
1971 #endif
1973 #ifndef OPENSSL_NO_PSK
1974 if (type & SSL_kPSK) {
1975 /* copy PSK identity hint */
1976 s2n(strlen(s->ctx->psk_identity_hint), p);
1977 strncpy((char *)p, s->ctx->psk_identity_hint,
1978 strlen(s->ctx->psk_identity_hint));
1979 p += strlen(s->ctx->psk_identity_hint);
1981 #endif
1983 /* not anonymous */
1984 if (pkey != NULL) {
1986 * n is the length of the params, they start at &(d[4]) and p
1987 * points to the space at the end.
1989 #ifndef OPENSSL_NO_RSA
1990 if (pkey->type == EVP_PKEY_RSA
1991 && TLS1_get_version(s) < TLS1_2_VERSION) {
1992 q = md_buf;
1993 j = 0;
1994 for (num = 2; num > 0; num--) {
1995 EVP_MD_CTX_set_flags(&md_ctx,
1996 EVP_MD_CTX_FLAG_NON_FIPS_ALLOW);
1997 EVP_DigestInit_ex(&md_ctx, (num == 2)
1998 ? s->ctx->md5 : s->ctx->sha1, NULL);
1999 EVP_DigestUpdate(&md_ctx, &(s->s3->client_random[0]),
2000 SSL3_RANDOM_SIZE);
2001 EVP_DigestUpdate(&md_ctx, &(s->s3->server_random[0]),
2002 SSL3_RANDOM_SIZE);
2003 EVP_DigestUpdate(&md_ctx, &(d[4]), n);
2004 EVP_DigestFinal_ex(&md_ctx, q, (unsigned int *)&i);
2005 q += i;
2006 j += i;
2008 if (RSA_sign(NID_md5_sha1, md_buf, j,
2009 &(p[2]), &u, pkey->pkey.rsa) <= 0) {
2010 SSLerr(SSL_F_SSL3_SEND_SERVER_KEY_EXCHANGE, ERR_LIB_RSA);
2011 goto err;
2013 s2n(u, p);
2014 n += u + 2;
2015 } else
2016 #endif
2017 if (md) {
2019 * For TLS1.2 and later send signature algorithm
2021 if (TLS1_get_version(s) >= TLS1_2_VERSION) {
2022 if (!tls12_get_sigandhash(p, pkey, md)) {
2023 /* Should never happen */
2024 al = SSL_AD_INTERNAL_ERROR;
2025 SSLerr(SSL_F_SSL3_SEND_SERVER_KEY_EXCHANGE,
2026 ERR_R_INTERNAL_ERROR);
2027 goto f_err;
2029 p += 2;
2031 #ifdef SSL_DEBUG
2032 fprintf(stderr, "Using hash %s\n", EVP_MD_name(md));
2033 #endif
2034 EVP_SignInit_ex(&md_ctx, md, NULL);
2035 EVP_SignUpdate(&md_ctx, &(s->s3->client_random[0]),
2036 SSL3_RANDOM_SIZE);
2037 EVP_SignUpdate(&md_ctx, &(s->s3->server_random[0]),
2038 SSL3_RANDOM_SIZE);
2039 EVP_SignUpdate(&md_ctx, &(d[4]), n);
2040 if (!EVP_SignFinal(&md_ctx, &(p[2]),
2041 (unsigned int *)&i, pkey)) {
2042 SSLerr(SSL_F_SSL3_SEND_SERVER_KEY_EXCHANGE, ERR_LIB_EVP);
2043 goto err;
2045 s2n(i, p);
2046 n += i + 2;
2047 if (TLS1_get_version(s) >= TLS1_2_VERSION)
2048 n += 2;
2049 } else {
2050 /* Is this error check actually needed? */
2051 al = SSL_AD_HANDSHAKE_FAILURE;
2052 SSLerr(SSL_F_SSL3_SEND_SERVER_KEY_EXCHANGE,
2053 SSL_R_UNKNOWN_PKEY_TYPE);
2054 goto f_err;
2058 *(d++) = SSL3_MT_SERVER_KEY_EXCHANGE;
2059 l2n3(n, d);
2062 * we should now have things packed up, so lets send it off
2064 s->init_num = n + 4;
2065 s->init_off = 0;
2068 s->state = SSL3_ST_SW_KEY_EXCH_B;
2069 EVP_MD_CTX_cleanup(&md_ctx);
2070 return (ssl3_do_write(s, SSL3_RT_HANDSHAKE));
2071 f_err:
2072 ssl3_send_alert(s, SSL3_AL_FATAL, al);
2073 err:
2074 #ifndef OPENSSL_NO_ECDH
2075 if (encodedPoint != NULL)
2076 OPENSSL_free(encodedPoint);
2077 BN_CTX_free(bn_ctx);
2078 #endif
2079 EVP_MD_CTX_cleanup(&md_ctx);
2080 s->state = SSL_ST_ERR;
2081 return (-1);
2084 int ssl3_send_certificate_request(SSL *s)
2086 unsigned char *p, *d;
2087 int i, j, nl, off, n;
2088 STACK_OF(X509_NAME) *sk = NULL;
2089 X509_NAME *name;
2090 BUF_MEM *buf;
2092 if (s->state == SSL3_ST_SW_CERT_REQ_A) {
2093 buf = s->init_buf;
2095 d = p = (unsigned char *)&(buf->data[4]);
2097 /* get the list of acceptable cert types */
2098 p++;
2099 n = ssl3_get_req_cert_type(s, p);
2100 d[0] = n;
2101 p += n;
2102 n++;
2104 if (TLS1_get_version(s) >= TLS1_2_VERSION) {
2105 nl = tls12_get_req_sig_algs(s, p + 2);
2106 s2n(nl, p);
2107 p += nl + 2;
2108 n += nl + 2;
2111 off = n;
2112 p += 2;
2113 n += 2;
2115 sk = SSL_get_client_CA_list(s);
2116 nl = 0;
2117 if (sk != NULL) {
2118 for (i = 0; i < sk_X509_NAME_num(sk); i++) {
2119 name = sk_X509_NAME_value(sk, i);
2120 j = i2d_X509_NAME(name, NULL);
2121 if (!BUF_MEM_grow_clean(buf, 4 + n + j + 2)) {
2122 SSLerr(SSL_F_SSL3_SEND_CERTIFICATE_REQUEST,
2123 ERR_R_BUF_LIB);
2124 goto err;
2126 p = (unsigned char *)&(buf->data[4 + n]);
2127 if (!(s->options & SSL_OP_NETSCAPE_CA_DN_BUG)) {
2128 s2n(j, p);
2129 i2d_X509_NAME(name, &p);
2130 n += 2 + j;
2131 nl += 2 + j;
2132 } else {
2133 d = p;
2134 i2d_X509_NAME(name, &p);
2135 j -= 2;
2136 s2n(j, d);
2137 j += 2;
2138 n += j;
2139 nl += j;
2143 /* else no CA names */
2144 p = (unsigned char *)&(buf->data[4 + off]);
2145 s2n(nl, p);
2147 d = (unsigned char *)buf->data;
2148 *(d++) = SSL3_MT_CERTIFICATE_REQUEST;
2149 l2n3(n, d);
2152 * we should now have things packed up, so lets send it off
2155 s->init_num = n + 4;
2156 s->init_off = 0;
2157 #ifdef NETSCAPE_HANG_BUG
2158 if (!BUF_MEM_grow_clean(buf, s->init_num + 4)) {
2159 SSLerr(SSL_F_SSL3_SEND_CERTIFICATE_REQUEST, ERR_R_BUF_LIB);
2160 goto err;
2162 p = (unsigned char *)s->init_buf->data + s->init_num;
2164 /* do the header */
2165 *(p++) = SSL3_MT_SERVER_DONE;
2166 *(p++) = 0;
2167 *(p++) = 0;
2168 *(p++) = 0;
2169 s->init_num += 4;
2170 #endif
2172 s->state = SSL3_ST_SW_CERT_REQ_B;
2175 /* SSL3_ST_SW_CERT_REQ_B */
2176 return (ssl3_do_write(s, SSL3_RT_HANDSHAKE));
2177 err:
2178 s->state = SSL_ST_ERR;
2179 return (-1);
2182 int ssl3_get_client_key_exchange(SSL *s)
2184 int i, al, ok;
2185 long n;
2186 unsigned long alg_k;
2187 unsigned char *p;
2188 #ifndef OPENSSL_NO_RSA
2189 RSA *rsa = NULL;
2190 EVP_PKEY *pkey = NULL;
2191 #endif
2192 #ifndef OPENSSL_NO_DH
2193 BIGNUM *pub = NULL;
2194 DH *dh_srvr;
2195 #endif
2196 #ifndef OPENSSL_NO_KRB5
2197 KSSL_ERR kssl_err;
2198 #endif /* OPENSSL_NO_KRB5 */
2200 #ifndef OPENSSL_NO_ECDH
2201 EC_KEY *srvr_ecdh = NULL;
2202 EVP_PKEY *clnt_pub_pkey = NULL;
2203 EC_POINT *clnt_ecpoint = NULL;
2204 BN_CTX *bn_ctx = NULL;
2205 #endif
2207 n = s->method->ssl_get_message(s,
2208 SSL3_ST_SR_KEY_EXCH_A,
2209 SSL3_ST_SR_KEY_EXCH_B,
2210 SSL3_MT_CLIENT_KEY_EXCHANGE, 2048, &ok);
2212 if (!ok)
2213 return ((int)n);
2214 p = (unsigned char *)s->init_msg;
2216 alg_k = s->s3->tmp.new_cipher->algorithm_mkey;
2218 #ifndef OPENSSL_NO_RSA
2219 if (alg_k & SSL_kRSA) {
2220 unsigned char rand_premaster_secret[SSL_MAX_MASTER_KEY_LENGTH];
2221 int decrypt_len;
2222 unsigned char decrypt_good, version_good;
2223 size_t j;
2225 /* FIX THIS UP EAY EAY EAY EAY */
2226 if (s->s3->tmp.use_rsa_tmp) {
2227 if ((s->cert != NULL) && (s->cert->rsa_tmp != NULL))
2228 rsa = s->cert->rsa_tmp;
2230 * Don't do a callback because rsa_tmp should be sent already
2232 if (rsa == NULL) {
2233 al = SSL_AD_HANDSHAKE_FAILURE;
2234 SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,
2235 SSL_R_MISSING_TMP_RSA_PKEY);
2236 goto f_err;
2239 } else {
2240 pkey = s->cert->pkeys[SSL_PKEY_RSA_ENC].privatekey;
2241 if ((pkey == NULL) ||
2242 (pkey->type != EVP_PKEY_RSA) || (pkey->pkey.rsa == NULL)) {
2243 al = SSL_AD_HANDSHAKE_FAILURE;
2244 SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,
2245 SSL_R_MISSING_RSA_CERTIFICATE);
2246 goto f_err;
2248 rsa = pkey->pkey.rsa;
2251 /* TLS and [incidentally] DTLS{0xFEFF} */
2252 if (s->version > SSL3_VERSION && s->version != DTLS1_BAD_VER) {
2253 n2s(p, i);
2254 if (n != i + 2) {
2255 if (!(s->options & SSL_OP_TLS_D5_BUG)) {
2256 al = SSL_AD_DECODE_ERROR;
2257 SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,
2258 SSL_R_TLS_RSA_ENCRYPTED_VALUE_LENGTH_IS_WRONG);
2259 goto f_err;
2260 } else
2261 p -= 2;
2262 } else
2263 n = i;
2267 * Reject overly short RSA ciphertext because we want to be sure
2268 * that the buffer size makes it safe to iterate over the entire
2269 * size of a premaster secret (SSL_MAX_MASTER_KEY_LENGTH). The
2270 * actual expected size is larger due to RSA padding, but the
2271 * bound is sufficient to be safe.
2273 if (n < SSL_MAX_MASTER_KEY_LENGTH) {
2274 al = SSL_AD_DECRYPT_ERROR;
2275 SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,
2276 SSL_R_TLS_RSA_ENCRYPTED_VALUE_LENGTH_IS_WRONG);
2277 goto f_err;
2281 * We must not leak whether a decryption failure occurs because of
2282 * Bleichenbacher's attack on PKCS #1 v1.5 RSA padding (see RFC 2246,
2283 * section 7.4.7.1). The code follows that advice of the TLS RFC and
2284 * generates a random premaster secret for the case that the decrypt
2285 * fails. See https://tools.ietf.org/html/rfc5246#section-7.4.7.1
2289 * should be RAND_bytes, but we cannot work around a failure.
2291 if (RAND_pseudo_bytes(rand_premaster_secret,
2292 sizeof(rand_premaster_secret)) <= 0)
2293 goto err;
2294 decrypt_len =
2295 RSA_private_decrypt((int)n, p, p, rsa, RSA_PKCS1_PADDING);
2296 ERR_clear_error();
2299 * decrypt_len should be SSL_MAX_MASTER_KEY_LENGTH. decrypt_good will
2300 * be 0xff if so and zero otherwise.
2302 decrypt_good =
2303 constant_time_eq_int_8(decrypt_len, SSL_MAX_MASTER_KEY_LENGTH);
2306 * If the version in the decrypted pre-master secret is correct then
2307 * version_good will be 0xff, otherwise it'll be zero. The
2308 * Klima-Pokorny-Rosa extension of Bleichenbacher's attack
2309 * (http://eprint.iacr.org/2003/052/) exploits the version number
2310 * check as a "bad version oracle". Thus version checks are done in
2311 * constant time and are treated like any other decryption error.
2313 version_good =
2314 constant_time_eq_8(p[0], (unsigned)(s->client_version >> 8));
2315 version_good &=
2316 constant_time_eq_8(p[1], (unsigned)(s->client_version & 0xff));
2319 * The premaster secret must contain the same version number as the
2320 * ClientHello to detect version rollback attacks (strangely, the
2321 * protocol does not offer such protection for DH ciphersuites).
2322 * However, buggy clients exist that send the negotiated protocol
2323 * version instead if the server does not support the requested
2324 * protocol version. If SSL_OP_TLS_ROLLBACK_BUG is set, tolerate such
2325 * clients.
2327 if (s->options & SSL_OP_TLS_ROLLBACK_BUG) {
2328 unsigned char workaround_good;
2329 workaround_good =
2330 constant_time_eq_8(p[0], (unsigned)(s->version >> 8));
2331 workaround_good &=
2332 constant_time_eq_8(p[1], (unsigned)(s->version & 0xff));
2333 version_good |= workaround_good;
2337 * Both decryption and version must be good for decrypt_good to
2338 * remain non-zero (0xff).
2340 decrypt_good &= version_good;
2343 * Now copy rand_premaster_secret over from p using
2344 * decrypt_good_mask. If decryption failed, then p does not
2345 * contain valid plaintext, however, a check above guarantees
2346 * it is still sufficiently large to read from.
2348 for (j = 0; j < sizeof(rand_premaster_secret); j++) {
2349 p[j] = constant_time_select_8(decrypt_good, p[j],
2350 rand_premaster_secret[j]);
2353 s->session->master_key_length =
2354 s->method->ssl3_enc->generate_master_secret(s,
2356 session->master_key,
2358 sizeof
2359 (rand_premaster_secret));
2360 OPENSSL_cleanse(p, sizeof(rand_premaster_secret));
2361 } else
2362 #endif
2363 #ifndef OPENSSL_NO_DH
2364 if (alg_k & (SSL_kEDH | SSL_kDHr | SSL_kDHd)) {
2365 n2s(p, i);
2366 if (n != i + 2) {
2367 if (!(s->options & SSL_OP_SSLEAY_080_CLIENT_DH_BUG)) {
2368 SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,
2369 SSL_R_DH_PUBLIC_VALUE_LENGTH_IS_WRONG);
2370 goto err;
2371 } else {
2372 p -= 2;
2373 i = (int)n;
2377 if (n == 0L) { /* the parameters are in the cert */
2378 al = SSL_AD_HANDSHAKE_FAILURE;
2379 SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,
2380 SSL_R_UNABLE_TO_DECODE_DH_CERTS);
2381 goto f_err;
2382 } else {
2383 if (s->s3->tmp.dh == NULL) {
2384 al = SSL_AD_HANDSHAKE_FAILURE;
2385 SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,
2386 SSL_R_MISSING_TMP_DH_KEY);
2387 goto f_err;
2388 } else
2389 dh_srvr = s->s3->tmp.dh;
2392 pub = BN_bin2bn(p, i, NULL);
2393 if (pub == NULL) {
2394 SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE, SSL_R_BN_LIB);
2395 goto err;
2398 i = DH_compute_key(p, pub, dh_srvr);
2400 if (i <= 0) {
2401 SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE, ERR_R_DH_LIB);
2402 BN_clear_free(pub);
2403 goto err;
2406 DH_free(s->s3->tmp.dh);
2407 s->s3->tmp.dh = NULL;
2409 BN_clear_free(pub);
2410 pub = NULL;
2411 s->session->master_key_length =
2412 s->method->ssl3_enc->generate_master_secret(s,
2414 session->master_key,
2415 p, i);
2416 OPENSSL_cleanse(p, i);
2417 } else
2418 #endif
2419 #ifndef OPENSSL_NO_KRB5
2420 if (alg_k & SSL_kKRB5) {
2421 krb5_error_code krb5rc;
2422 krb5_data enc_ticket;
2423 krb5_data authenticator;
2424 krb5_data enc_pms;
2425 KSSL_CTX *kssl_ctx = s->kssl_ctx;
2426 EVP_CIPHER_CTX ciph_ctx;
2427 const EVP_CIPHER *enc = NULL;
2428 unsigned char iv[EVP_MAX_IV_LENGTH];
2429 unsigned char pms[SSL_MAX_MASTER_KEY_LENGTH + EVP_MAX_BLOCK_LENGTH];
2430 int padl, outl;
2431 krb5_timestamp authtime = 0;
2432 krb5_ticket_times ttimes;
2433 int kerr = 0;
2435 EVP_CIPHER_CTX_init(&ciph_ctx);
2437 if (!kssl_ctx)
2438 kssl_ctx = kssl_ctx_new();
2440 n2s(p, i);
2441 enc_ticket.length = i;
2443 if (n < (long)(enc_ticket.length + 6)) {
2444 SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,
2445 SSL_R_DATA_LENGTH_TOO_LONG);
2446 goto err;
2449 enc_ticket.data = (char *)p;
2450 p += enc_ticket.length;
2452 n2s(p, i);
2453 authenticator.length = i;
2455 if (n < (long)(enc_ticket.length + authenticator.length + 6)) {
2456 SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,
2457 SSL_R_DATA_LENGTH_TOO_LONG);
2458 goto err;
2461 authenticator.data = (char *)p;
2462 p += authenticator.length;
2464 n2s(p, i);
2465 enc_pms.length = i;
2466 enc_pms.data = (char *)p;
2467 p += enc_pms.length;
2470 * Note that the length is checked again below, ** after decryption
2472 if (enc_pms.length > sizeof pms) {
2473 SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,
2474 SSL_R_DATA_LENGTH_TOO_LONG);
2475 goto err;
2478 if (n != (long)(enc_ticket.length + authenticator.length +
2479 enc_pms.length + 6)) {
2480 SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,
2481 SSL_R_DATA_LENGTH_TOO_LONG);
2482 goto err;
2485 if ((krb5rc = kssl_sget_tkt(kssl_ctx, &enc_ticket, &ttimes,
2486 &kssl_err)) != 0) {
2487 # ifdef KSSL_DEBUG
2488 fprintf(stderr, "kssl_sget_tkt rtn %d [%d]\n",
2489 krb5rc, kssl_err.reason);
2490 if (kssl_err.text)
2491 fprintf(stderr, "kssl_err text= %s\n", kssl_err.text);
2492 # endif /* KSSL_DEBUG */
2493 SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE, kssl_err.reason);
2494 goto err;
2498 * Note: no authenticator is not considered an error, ** but will
2499 * return authtime == 0.
2501 if ((krb5rc = kssl_check_authent(kssl_ctx, &authenticator,
2502 &authtime, &kssl_err)) != 0) {
2503 # ifdef KSSL_DEBUG
2504 fprintf(stderr, "kssl_check_authent rtn %d [%d]\n",
2505 krb5rc, kssl_err.reason);
2506 if (kssl_err.text)
2507 fprintf(stderr, "kssl_err text= %s\n", kssl_err.text);
2508 # endif /* KSSL_DEBUG */
2509 SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE, kssl_err.reason);
2510 goto err;
2513 if ((krb5rc = kssl_validate_times(authtime, &ttimes)) != 0) {
2514 SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE, krb5rc);
2515 goto err;
2517 # ifdef KSSL_DEBUG
2518 kssl_ctx_show(kssl_ctx);
2519 # endif /* KSSL_DEBUG */
2521 enc = kssl_map_enc(kssl_ctx->enctype);
2522 if (enc == NULL)
2523 goto err;
2525 memset(iv, 0, sizeof iv); /* per RFC 1510 */
2527 if (!EVP_DecryptInit_ex(&ciph_ctx, enc, NULL, kssl_ctx->key, iv)) {
2528 SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,
2529 SSL_R_DECRYPTION_FAILED);
2530 goto err;
2532 if (!EVP_DecryptUpdate(&ciph_ctx, pms, &outl,
2533 (unsigned char *)enc_pms.data, enc_pms.length))
2535 SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,
2536 SSL_R_DECRYPTION_FAILED);
2537 kerr = 1;
2538 goto kclean;
2540 if (outl > SSL_MAX_MASTER_KEY_LENGTH) {
2541 SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,
2542 SSL_R_DATA_LENGTH_TOO_LONG);
2543 kerr = 1;
2544 goto kclean;
2546 if (!EVP_DecryptFinal_ex(&ciph_ctx, &(pms[outl]), &padl)) {
2547 SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,
2548 SSL_R_DECRYPTION_FAILED);
2549 kerr = 1;
2550 goto kclean;
2552 outl += padl;
2553 if (outl > SSL_MAX_MASTER_KEY_LENGTH) {
2554 SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,
2555 SSL_R_DATA_LENGTH_TOO_LONG);
2556 kerr = 1;
2557 goto kclean;
2559 if (!((pms[0] == (s->client_version >> 8))
2560 && (pms[1] == (s->client_version & 0xff)))) {
2562 * The premaster secret must contain the same version number as
2563 * the ClientHello to detect version rollback attacks (strangely,
2564 * the protocol does not offer such protection for DH
2565 * ciphersuites). However, buggy clients exist that send random
2566 * bytes instead of the protocol version. If
2567 * SSL_OP_TLS_ROLLBACK_BUG is set, tolerate such clients.
2568 * (Perhaps we should have a separate BUG value for the Kerberos
2569 * cipher)
2571 if (!(s->options & SSL_OP_TLS_ROLLBACK_BUG)) {
2572 SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,
2573 SSL_AD_DECODE_ERROR);
2574 kerr = 1;
2575 goto kclean;
2579 EVP_CIPHER_CTX_cleanup(&ciph_ctx);
2581 s->session->master_key_length =
2582 s->method->ssl3_enc->generate_master_secret(s,
2584 session->master_key,
2585 pms, outl);
2587 if (kssl_ctx->client_princ) {
2588 size_t len = strlen(kssl_ctx->client_princ);
2589 if (len < SSL_MAX_KRB5_PRINCIPAL_LENGTH) {
2590 s->session->krb5_client_princ_len = len;
2591 memcpy(s->session->krb5_client_princ, kssl_ctx->client_princ,
2592 len);
2596 /*- Was doing kssl_ctx_free() here,
2597 * but it caused problems for apache.
2598 * kssl_ctx = kssl_ctx_free(kssl_ctx);
2599 * if (s->kssl_ctx) s->kssl_ctx = NULL;
2602 kclean:
2603 OPENSSL_cleanse(pms, sizeof(pms));
2604 if (kerr)
2605 goto err;
2606 } else
2607 #endif /* OPENSSL_NO_KRB5 */
2609 #ifndef OPENSSL_NO_ECDH
2610 if (alg_k & (SSL_kEECDH | SSL_kECDHr | SSL_kECDHe)) {
2611 int ret = 1;
2612 int field_size = 0;
2613 const EC_KEY *tkey;
2614 const EC_GROUP *group;
2615 const BIGNUM *priv_key;
2617 /* initialize structures for server's ECDH key pair */
2618 if ((srvr_ecdh = EC_KEY_new()) == NULL) {
2619 SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE, ERR_R_MALLOC_FAILURE);
2620 goto err;
2623 /* Let's get server private key and group information */
2624 if (alg_k & (SSL_kECDHr | SSL_kECDHe)) {
2625 /* use the certificate */
2626 tkey = s->cert->pkeys[SSL_PKEY_ECC].privatekey->pkey.ec;
2627 } else {
2629 * use the ephermeral values we saved when generating the
2630 * ServerKeyExchange msg.
2632 tkey = s->s3->tmp.ecdh;
2635 group = EC_KEY_get0_group(tkey);
2636 priv_key = EC_KEY_get0_private_key(tkey);
2638 if (!EC_KEY_set_group(srvr_ecdh, group) ||
2639 !EC_KEY_set_private_key(srvr_ecdh, priv_key)) {
2640 SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE, ERR_R_EC_LIB);
2641 goto err;
2644 /* Let's get client's public key */
2645 if ((clnt_ecpoint = EC_POINT_new(group)) == NULL) {
2646 SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE, ERR_R_MALLOC_FAILURE);
2647 goto err;
2650 if (n == 0L) {
2651 /* Client Publickey was in Client Certificate */
2653 if (alg_k & SSL_kEECDH) {
2654 al = SSL_AD_HANDSHAKE_FAILURE;
2655 SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,
2656 SSL_R_MISSING_TMP_ECDH_KEY);
2657 goto f_err;
2659 if (((clnt_pub_pkey = X509_get_pubkey(s->session->peer))
2660 == NULL) || (clnt_pub_pkey->type != EVP_PKEY_EC)) {
2662 * XXX: For now, we do not support client authentication
2663 * using ECDH certificates so this branch (n == 0L) of the
2664 * code is never executed. When that support is added, we
2665 * ought to ensure the key received in the certificate is
2666 * authorized for key agreement. ECDH_compute_key implicitly
2667 * checks that the two ECDH shares are for the same group.
2669 al = SSL_AD_HANDSHAKE_FAILURE;
2670 SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,
2671 SSL_R_UNABLE_TO_DECODE_ECDH_CERTS);
2672 goto f_err;
2675 if (EC_POINT_copy(clnt_ecpoint,
2676 EC_KEY_get0_public_key(clnt_pub_pkey->
2677 pkey.ec)) == 0) {
2678 SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE, ERR_R_EC_LIB);
2679 goto err;
2681 ret = 2; /* Skip certificate verify processing */
2682 } else {
2684 * Get client's public key from encoded point in the
2685 * ClientKeyExchange message.
2687 if ((bn_ctx = BN_CTX_new()) == NULL) {
2688 SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,
2689 ERR_R_MALLOC_FAILURE);
2690 goto err;
2693 /* Get encoded point length */
2694 i = *p;
2695 p += 1;
2696 if (n != 1 + i) {
2697 SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE, ERR_R_EC_LIB);
2698 goto err;
2700 if (EC_POINT_oct2point(group, clnt_ecpoint, p, i, bn_ctx) == 0) {
2701 SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE, ERR_R_EC_LIB);
2702 goto err;
2705 * p is pointing to somewhere in the buffer currently, so set it
2706 * to the start
2708 p = (unsigned char *)s->init_buf->data;
2711 /* Compute the shared pre-master secret */
2712 field_size = EC_GROUP_get_degree(group);
2713 if (field_size <= 0) {
2714 SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE, ERR_R_ECDH_LIB);
2715 goto err;
2717 i = ECDH_compute_key(p, (field_size + 7) / 8, clnt_ecpoint, srvr_ecdh,
2718 NULL);
2719 if (i <= 0) {
2720 SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE, ERR_R_ECDH_LIB);
2721 goto err;
2724 EVP_PKEY_free(clnt_pub_pkey);
2725 EC_POINT_free(clnt_ecpoint);
2726 EC_KEY_free(srvr_ecdh);
2727 BN_CTX_free(bn_ctx);
2728 EC_KEY_free(s->s3->tmp.ecdh);
2729 s->s3->tmp.ecdh = NULL;
2731 /* Compute the master secret */
2732 s->session->master_key_length =
2733 s->method->ssl3_enc->generate_master_secret(s,
2735 session->master_key,
2736 p, i);
2738 OPENSSL_cleanse(p, i);
2739 return (ret);
2740 } else
2741 #endif
2742 #ifndef OPENSSL_NO_PSK
2743 if (alg_k & SSL_kPSK) {
2744 unsigned char *t = NULL;
2745 unsigned char psk_or_pre_ms[PSK_MAX_PSK_LEN * 2 + 4];
2746 unsigned int pre_ms_len = 0, psk_len = 0;
2747 int psk_err = 1;
2748 char tmp_id[PSK_MAX_IDENTITY_LEN + 1];
2750 al = SSL_AD_HANDSHAKE_FAILURE;
2752 n2s(p, i);
2753 if (n != i + 2) {
2754 SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE, SSL_R_LENGTH_MISMATCH);
2755 goto psk_err;
2757 if (i > PSK_MAX_IDENTITY_LEN) {
2758 SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,
2759 SSL_R_DATA_LENGTH_TOO_LONG);
2760 goto psk_err;
2762 if (s->psk_server_callback == NULL) {
2763 SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,
2764 SSL_R_PSK_NO_SERVER_CB);
2765 goto psk_err;
2769 * Create guaranteed NULL-terminated identity string for the callback
2771 memcpy(tmp_id, p, i);
2772 memset(tmp_id + i, 0, PSK_MAX_IDENTITY_LEN + 1 - i);
2773 psk_len = s->psk_server_callback(s, tmp_id,
2774 psk_or_pre_ms,
2775 sizeof(psk_or_pre_ms));
2776 OPENSSL_cleanse(tmp_id, PSK_MAX_IDENTITY_LEN + 1);
2778 if (psk_len > PSK_MAX_PSK_LEN) {
2779 SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE, ERR_R_INTERNAL_ERROR);
2780 goto psk_err;
2781 } else if (psk_len == 0) {
2783 * PSK related to the given identity not found
2785 SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,
2786 SSL_R_PSK_IDENTITY_NOT_FOUND);
2787 al = SSL_AD_UNKNOWN_PSK_IDENTITY;
2788 goto psk_err;
2791 /* create PSK pre_master_secret */
2792 pre_ms_len = 2 + psk_len + 2 + psk_len;
2793 t = psk_or_pre_ms;
2794 memmove(psk_or_pre_ms + psk_len + 4, psk_or_pre_ms, psk_len);
2795 s2n(psk_len, t);
2796 memset(t, 0, psk_len);
2797 t += psk_len;
2798 s2n(psk_len, t);
2800 if (s->session->psk_identity != NULL)
2801 OPENSSL_free(s->session->psk_identity);
2802 s->session->psk_identity = BUF_strndup((char *)p, i);
2803 if (s->session->psk_identity == NULL) {
2804 SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE, ERR_R_MALLOC_FAILURE);
2805 goto psk_err;
2808 if (s->session->psk_identity_hint != NULL)
2809 OPENSSL_free(s->session->psk_identity_hint);
2810 s->session->psk_identity_hint = BUF_strdup(s->ctx->psk_identity_hint);
2811 if (s->ctx->psk_identity_hint != NULL &&
2812 s->session->psk_identity_hint == NULL) {
2813 SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE, ERR_R_MALLOC_FAILURE);
2814 goto psk_err;
2817 s->session->master_key_length =
2818 s->method->ssl3_enc->generate_master_secret(s,
2820 session->master_key,
2821 psk_or_pre_ms,
2822 pre_ms_len);
2823 psk_err = 0;
2824 psk_err:
2825 OPENSSL_cleanse(psk_or_pre_ms, sizeof(psk_or_pre_ms));
2826 if (psk_err != 0)
2827 goto f_err;
2828 } else
2829 #endif
2830 #ifndef OPENSSL_NO_SRP
2831 if (alg_k & SSL_kSRP) {
2832 int param_len;
2834 n2s(p, i);
2835 param_len = i + 2;
2836 if (param_len > n) {
2837 al = SSL_AD_DECODE_ERROR;
2838 SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,
2839 SSL_R_BAD_SRP_A_LENGTH);
2840 goto f_err;
2842 if (!(s->srp_ctx.A = BN_bin2bn(p, i, NULL))) {
2843 SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE, ERR_R_BN_LIB);
2844 goto err;
2846 if (BN_ucmp(s->srp_ctx.A, s->srp_ctx.N) >= 0
2847 || BN_is_zero(s->srp_ctx.A)) {
2848 al = SSL_AD_ILLEGAL_PARAMETER;
2849 SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,
2850 SSL_R_BAD_SRP_PARAMETERS);
2851 goto f_err;
2853 if (s->session->srp_username != NULL)
2854 OPENSSL_free(s->session->srp_username);
2855 s->session->srp_username = BUF_strdup(s->srp_ctx.login);
2856 if (s->session->srp_username == NULL) {
2857 SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE, ERR_R_MALLOC_FAILURE);
2858 goto err;
2861 if ((s->session->master_key_length =
2862 SRP_generate_server_master_secret(s,
2863 s->session->master_key)) < 0) {
2864 SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE, ERR_R_INTERNAL_ERROR);
2865 goto err;
2868 p += i;
2869 } else
2870 #endif /* OPENSSL_NO_SRP */
2871 if (alg_k & SSL_kGOST) {
2872 int ret = 0;
2873 EVP_PKEY_CTX *pkey_ctx;
2874 EVP_PKEY *client_pub_pkey = NULL, *pk = NULL;
2875 unsigned char premaster_secret[32], *start;
2876 size_t outlen = 32, inlen;
2877 unsigned long alg_a;
2878 int Ttag, Tclass;
2879 long Tlen;
2881 /* Get our certificate private key */
2882 alg_a = s->s3->tmp.new_cipher->algorithm_auth;
2883 if (alg_a & SSL_aGOST94)
2884 pk = s->cert->pkeys[SSL_PKEY_GOST94].privatekey;
2885 else if (alg_a & SSL_aGOST01)
2886 pk = s->cert->pkeys[SSL_PKEY_GOST01].privatekey;
2888 pkey_ctx = EVP_PKEY_CTX_new(pk, NULL);
2889 EVP_PKEY_decrypt_init(pkey_ctx);
2891 * If client certificate is present and is of the same type, maybe
2892 * use it for key exchange. Don't mind errors from
2893 * EVP_PKEY_derive_set_peer, because it is completely valid to use a
2894 * client certificate for authorization only.
2896 client_pub_pkey = X509_get_pubkey(s->session->peer);
2897 if (client_pub_pkey) {
2898 if (EVP_PKEY_derive_set_peer(pkey_ctx, client_pub_pkey) <= 0)
2899 ERR_clear_error();
2901 /* Decrypt session key */
2902 if (ASN1_get_object
2903 ((const unsigned char **)&p, &Tlen, &Ttag, &Tclass,
2904 n) != V_ASN1_CONSTRUCTED || Ttag != V_ASN1_SEQUENCE
2905 || Tclass != V_ASN1_UNIVERSAL) {
2906 SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,
2907 SSL_R_DECRYPTION_FAILED);
2908 goto gerr;
2910 start = p;
2911 inlen = Tlen;
2912 if (EVP_PKEY_decrypt
2913 (pkey_ctx, premaster_secret, &outlen, start, inlen) <= 0) {
2914 SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,
2915 SSL_R_DECRYPTION_FAILED);
2916 goto gerr;
2918 /* Generate master secret */
2919 s->session->master_key_length =
2920 s->method->ssl3_enc->generate_master_secret(s,
2922 session->master_key,
2923 premaster_secret, 32);
2924 OPENSSL_cleanse(premaster_secret, sizeof(premaster_secret));
2925 /* Check if pubkey from client certificate was used */
2926 if (EVP_PKEY_CTX_ctrl
2927 (pkey_ctx, -1, -1, EVP_PKEY_CTRL_PEER_KEY, 2, NULL) > 0)
2928 ret = 2;
2929 else
2930 ret = 1;
2931 gerr:
2932 EVP_PKEY_free(client_pub_pkey);
2933 EVP_PKEY_CTX_free(pkey_ctx);
2934 if (ret)
2935 return ret;
2936 else
2937 goto err;
2938 } else {
2939 al = SSL_AD_HANDSHAKE_FAILURE;
2940 SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE, SSL_R_UNKNOWN_CIPHER_TYPE);
2941 goto f_err;
2944 return (1);
2945 f_err:
2946 ssl3_send_alert(s, SSL3_AL_FATAL, al);
2947 #if !defined(OPENSSL_NO_DH) || !defined(OPENSSL_NO_RSA) || !defined(OPENSSL_NO_ECDH) || defined(OPENSSL_NO_SRP)
2948 err:
2949 #endif
2950 #ifndef OPENSSL_NO_ECDH
2951 EVP_PKEY_free(clnt_pub_pkey);
2952 EC_POINT_free(clnt_ecpoint);
2953 if (srvr_ecdh != NULL)
2954 EC_KEY_free(srvr_ecdh);
2955 BN_CTX_free(bn_ctx);
2956 #endif
2957 s->state = SSL_ST_ERR;
2958 return (-1);
2961 int ssl3_get_cert_verify(SSL *s)
2963 EVP_PKEY *pkey = NULL;
2964 unsigned char *p;
2965 int al, ok, ret = 0;
2966 long n;
2967 int type = 0, i, j;
2968 X509 *peer;
2969 const EVP_MD *md = NULL;
2970 EVP_MD_CTX mctx;
2971 EVP_MD_CTX_init(&mctx);
2974 * We should only process a CertificateVerify message if we have received
2975 * a Certificate from the client. If so then |s->session->peer| will be non
2976 * NULL. In some instances a CertificateVerify message is not required even
2977 * if the peer has sent a Certificate (e.g. such as in the case of static
2978 * DH). In that case the ClientKeyExchange processing will skip the
2979 * CertificateVerify state so we should not arrive here.
2981 if (s->session->peer == NULL) {
2982 ret = 1;
2983 goto end;
2986 n = s->method->ssl_get_message(s,
2987 SSL3_ST_SR_CERT_VRFY_A,
2988 SSL3_ST_SR_CERT_VRFY_B,
2989 SSL3_MT_CERTIFICATE_VERIFY,
2990 SSL3_RT_MAX_PLAIN_LENGTH, &ok);
2992 if (!ok)
2993 return ((int)n);
2995 peer = s->session->peer;
2996 pkey = X509_get_pubkey(peer);
2997 type = X509_certificate_type(peer, pkey);
2999 if (!(type & EVP_PKT_SIGN)) {
3000 SSLerr(SSL_F_SSL3_GET_CERT_VERIFY,
3001 SSL_R_SIGNATURE_FOR_NON_SIGNING_CERTIFICATE);
3002 al = SSL_AD_ILLEGAL_PARAMETER;
3003 goto f_err;
3006 /* we now have a signature that we need to verify */
3007 p = (unsigned char *)s->init_msg;
3008 /* Check for broken implementations of GOST ciphersuites */
3010 * If key is GOST and n is exactly 64, it is bare signature without
3011 * length field
3013 if (n == 64 && (pkey->type == NID_id_GostR3410_94 ||
3014 pkey->type == NID_id_GostR3410_2001)) {
3015 i = 64;
3016 } else {
3017 if (TLS1_get_version(s) >= TLS1_2_VERSION) {
3018 int sigalg = tls12_get_sigid(pkey);
3019 /* Should never happen */
3020 if (sigalg == -1) {
3021 SSLerr(SSL_F_SSL3_GET_CERT_VERIFY, ERR_R_INTERNAL_ERROR);
3022 al = SSL_AD_INTERNAL_ERROR;
3023 goto f_err;
3025 /* Check key type is consistent with signature */
3026 if (sigalg != (int)p[1]) {
3027 SSLerr(SSL_F_SSL3_GET_CERT_VERIFY,
3028 SSL_R_WRONG_SIGNATURE_TYPE);
3029 al = SSL_AD_DECODE_ERROR;
3030 goto f_err;
3032 md = tls12_get_hash(p[0]);
3033 if (md == NULL) {
3034 SSLerr(SSL_F_SSL3_GET_CERT_VERIFY, SSL_R_UNKNOWN_DIGEST);
3035 al = SSL_AD_DECODE_ERROR;
3036 goto f_err;
3038 #ifdef SSL_DEBUG
3039 fprintf(stderr, "USING TLSv1.2 HASH %s\n", EVP_MD_name(md));
3040 #endif
3041 p += 2;
3042 n -= 2;
3044 n2s(p, i);
3045 n -= 2;
3046 if (i > n) {
3047 SSLerr(SSL_F_SSL3_GET_CERT_VERIFY, SSL_R_LENGTH_MISMATCH);
3048 al = SSL_AD_DECODE_ERROR;
3049 goto f_err;
3052 j = EVP_PKEY_size(pkey);
3053 if ((i > j) || (n > j) || (n <= 0)) {
3054 SSLerr(SSL_F_SSL3_GET_CERT_VERIFY, SSL_R_WRONG_SIGNATURE_SIZE);
3055 al = SSL_AD_DECODE_ERROR;
3056 goto f_err;
3059 if (TLS1_get_version(s) >= TLS1_2_VERSION) {
3060 long hdatalen = 0;
3061 void *hdata;
3062 hdatalen = BIO_get_mem_data(s->s3->handshake_buffer, &hdata);
3063 if (hdatalen <= 0) {
3064 SSLerr(SSL_F_SSL3_GET_CERT_VERIFY, ERR_R_INTERNAL_ERROR);
3065 al = SSL_AD_INTERNAL_ERROR;
3066 goto f_err;
3068 #ifdef SSL_DEBUG
3069 fprintf(stderr, "Using TLS 1.2 with client verify alg %s\n",
3070 EVP_MD_name(md));
3071 #endif
3072 if (!EVP_VerifyInit_ex(&mctx, md, NULL)
3073 || !EVP_VerifyUpdate(&mctx, hdata, hdatalen)) {
3074 SSLerr(SSL_F_SSL3_GET_CERT_VERIFY, ERR_R_EVP_LIB);
3075 al = SSL_AD_INTERNAL_ERROR;
3076 goto f_err;
3079 if (EVP_VerifyFinal(&mctx, p, i, pkey) <= 0) {
3080 al = SSL_AD_DECRYPT_ERROR;
3081 SSLerr(SSL_F_SSL3_GET_CERT_VERIFY, SSL_R_BAD_SIGNATURE);
3082 goto f_err;
3084 } else
3085 #ifndef OPENSSL_NO_RSA
3086 if (pkey->type == EVP_PKEY_RSA) {
3087 i = RSA_verify(NID_md5_sha1, s->s3->tmp.cert_verify_md,
3088 MD5_DIGEST_LENGTH + SHA_DIGEST_LENGTH, p, i,
3089 pkey->pkey.rsa);
3090 if (i < 0) {
3091 al = SSL_AD_DECRYPT_ERROR;
3092 SSLerr(SSL_F_SSL3_GET_CERT_VERIFY, SSL_R_BAD_RSA_DECRYPT);
3093 goto f_err;
3095 if (i == 0) {
3096 al = SSL_AD_DECRYPT_ERROR;
3097 SSLerr(SSL_F_SSL3_GET_CERT_VERIFY, SSL_R_BAD_RSA_SIGNATURE);
3098 goto f_err;
3100 } else
3101 #endif
3102 #ifndef OPENSSL_NO_DSA
3103 if (pkey->type == EVP_PKEY_DSA) {
3104 j = DSA_verify(pkey->save_type,
3105 &(s->s3->tmp.cert_verify_md[MD5_DIGEST_LENGTH]),
3106 SHA_DIGEST_LENGTH, p, i, pkey->pkey.dsa);
3107 if (j <= 0) {
3108 /* bad signature */
3109 al = SSL_AD_DECRYPT_ERROR;
3110 SSLerr(SSL_F_SSL3_GET_CERT_VERIFY, SSL_R_BAD_DSA_SIGNATURE);
3111 goto f_err;
3113 } else
3114 #endif
3115 #ifndef OPENSSL_NO_ECDSA
3116 if (pkey->type == EVP_PKEY_EC) {
3117 j = ECDSA_verify(pkey->save_type,
3118 &(s->s3->tmp.cert_verify_md[MD5_DIGEST_LENGTH]),
3119 SHA_DIGEST_LENGTH, p, i, pkey->pkey.ec);
3120 if (j <= 0) {
3121 /* bad signature */
3122 al = SSL_AD_DECRYPT_ERROR;
3123 SSLerr(SSL_F_SSL3_GET_CERT_VERIFY, SSL_R_BAD_ECDSA_SIGNATURE);
3124 goto f_err;
3126 } else
3127 #endif
3128 if (pkey->type == NID_id_GostR3410_94
3129 || pkey->type == NID_id_GostR3410_2001) {
3130 unsigned char signature[64];
3131 int idx;
3132 EVP_PKEY_CTX *pctx = EVP_PKEY_CTX_new(pkey, NULL);
3133 EVP_PKEY_verify_init(pctx);
3134 if (i != 64) {
3135 fprintf(stderr, "GOST signature length is %d", i);
3137 for (idx = 0; idx < 64; idx++) {
3138 signature[63 - idx] = p[idx];
3140 j = EVP_PKEY_verify(pctx, signature, 64, s->s3->tmp.cert_verify_md,
3141 32);
3142 EVP_PKEY_CTX_free(pctx);
3143 if (j <= 0) {
3144 al = SSL_AD_DECRYPT_ERROR;
3145 SSLerr(SSL_F_SSL3_GET_CERT_VERIFY, SSL_R_BAD_ECDSA_SIGNATURE);
3146 goto f_err;
3148 } else {
3149 SSLerr(SSL_F_SSL3_GET_CERT_VERIFY, ERR_R_INTERNAL_ERROR);
3150 al = SSL_AD_UNSUPPORTED_CERTIFICATE;
3151 goto f_err;
3154 ret = 1;
3155 if (0) {
3156 f_err:
3157 ssl3_send_alert(s, SSL3_AL_FATAL, al);
3158 s->state = SSL_ST_ERR;
3160 end:
3161 if (s->s3->handshake_buffer) {
3162 BIO_free(s->s3->handshake_buffer);
3163 s->s3->handshake_buffer = NULL;
3164 s->s3->flags &= ~TLS1_FLAGS_KEEP_HANDSHAKE;
3166 EVP_MD_CTX_cleanup(&mctx);
3167 EVP_PKEY_free(pkey);
3168 return (ret);
3171 int ssl3_get_client_certificate(SSL *s)
3173 int i, ok, al, ret = -1;
3174 X509 *x = NULL;
3175 unsigned long l, nc, llen, n;
3176 const unsigned char *p, *q;
3177 unsigned char *d;
3178 STACK_OF(X509) *sk = NULL;
3180 n = s->method->ssl_get_message(s,
3181 SSL3_ST_SR_CERT_A,
3182 SSL3_ST_SR_CERT_B,
3183 -1, s->max_cert_list, &ok);
3185 if (!ok)
3186 return ((int)n);
3188 if (s->s3->tmp.message_type == SSL3_MT_CLIENT_KEY_EXCHANGE) {
3189 if ((s->verify_mode & SSL_VERIFY_PEER) &&
3190 (s->verify_mode & SSL_VERIFY_FAIL_IF_NO_PEER_CERT)) {
3191 SSLerr(SSL_F_SSL3_GET_CLIENT_CERTIFICATE,
3192 SSL_R_PEER_DID_NOT_RETURN_A_CERTIFICATE);
3193 al = SSL_AD_HANDSHAKE_FAILURE;
3194 goto f_err;
3197 * If tls asked for a client cert, the client must return a 0 list
3199 if ((s->version > SSL3_VERSION) && s->s3->tmp.cert_request) {
3200 SSLerr(SSL_F_SSL3_GET_CLIENT_CERTIFICATE,
3201 SSL_R_TLS_PEER_DID_NOT_RESPOND_WITH_CERTIFICATE_LIST);
3202 al = SSL_AD_UNEXPECTED_MESSAGE;
3203 goto f_err;
3205 s->s3->tmp.reuse_message = 1;
3206 return (1);
3209 if (s->s3->tmp.message_type != SSL3_MT_CERTIFICATE) {
3210 al = SSL_AD_UNEXPECTED_MESSAGE;
3211 SSLerr(SSL_F_SSL3_GET_CLIENT_CERTIFICATE, SSL_R_WRONG_MESSAGE_TYPE);
3212 goto f_err;
3214 p = d = (unsigned char *)s->init_msg;
3216 if ((sk = sk_X509_new_null()) == NULL) {
3217 SSLerr(SSL_F_SSL3_GET_CLIENT_CERTIFICATE, ERR_R_MALLOC_FAILURE);
3218 goto err;
3221 n2l3(p, llen);
3222 if (llen + 3 != n) {
3223 al = SSL_AD_DECODE_ERROR;
3224 SSLerr(SSL_F_SSL3_GET_CLIENT_CERTIFICATE, SSL_R_LENGTH_MISMATCH);
3225 goto f_err;
3227 for (nc = 0; nc < llen;) {
3228 n2l3(p, l);
3229 if ((l + nc + 3) > llen) {
3230 al = SSL_AD_DECODE_ERROR;
3231 SSLerr(SSL_F_SSL3_GET_CLIENT_CERTIFICATE,
3232 SSL_R_CERT_LENGTH_MISMATCH);
3233 goto f_err;
3236 q = p;
3237 x = d2i_X509(NULL, &p, l);
3238 if (x == NULL) {
3239 SSLerr(SSL_F_SSL3_GET_CLIENT_CERTIFICATE, ERR_R_ASN1_LIB);
3240 goto err;
3242 if (p != (q + l)) {
3243 al = SSL_AD_DECODE_ERROR;
3244 SSLerr(SSL_F_SSL3_GET_CLIENT_CERTIFICATE,
3245 SSL_R_CERT_LENGTH_MISMATCH);
3246 goto f_err;
3248 if (!sk_X509_push(sk, x)) {
3249 SSLerr(SSL_F_SSL3_GET_CLIENT_CERTIFICATE, ERR_R_MALLOC_FAILURE);
3250 goto err;
3252 x = NULL;
3253 nc += l + 3;
3256 if (sk_X509_num(sk) <= 0) {
3257 /* TLS does not mind 0 certs returned */
3258 if (s->version == SSL3_VERSION) {
3259 al = SSL_AD_HANDSHAKE_FAILURE;
3260 SSLerr(SSL_F_SSL3_GET_CLIENT_CERTIFICATE,
3261 SSL_R_NO_CERTIFICATES_RETURNED);
3262 goto f_err;
3264 /* Fail for TLS only if we required a certificate */
3265 else if ((s->verify_mode & SSL_VERIFY_PEER) &&
3266 (s->verify_mode & SSL_VERIFY_FAIL_IF_NO_PEER_CERT)) {
3267 SSLerr(SSL_F_SSL3_GET_CLIENT_CERTIFICATE,
3268 SSL_R_PEER_DID_NOT_RETURN_A_CERTIFICATE);
3269 al = SSL_AD_HANDSHAKE_FAILURE;
3270 goto f_err;
3272 /* No client certificate so digest cached records */
3273 if (s->s3->handshake_buffer && !ssl3_digest_cached_records(s)) {
3274 al = SSL_AD_INTERNAL_ERROR;
3275 goto f_err;
3277 } else {
3278 i = ssl_verify_cert_chain(s, sk);
3279 if (i <= 0) {
3280 al = ssl_verify_alarm_type(s->verify_result);
3281 SSLerr(SSL_F_SSL3_GET_CLIENT_CERTIFICATE,
3282 SSL_R_NO_CERTIFICATE_RETURNED);
3283 goto f_err;
3287 if (s->session->peer != NULL) /* This should not be needed */
3288 X509_free(s->session->peer);
3289 s->session->peer = sk_X509_shift(sk);
3290 s->session->verify_result = s->verify_result;
3293 * With the current implementation, sess_cert will always be NULL when we
3294 * arrive here.
3296 if (s->session->sess_cert == NULL) {
3297 s->session->sess_cert = ssl_sess_cert_new();
3298 if (s->session->sess_cert == NULL) {
3299 SSLerr(SSL_F_SSL3_GET_CLIENT_CERTIFICATE, ERR_R_MALLOC_FAILURE);
3300 goto err;
3303 if (s->session->sess_cert->cert_chain != NULL)
3304 sk_X509_pop_free(s->session->sess_cert->cert_chain, X509_free);
3305 s->session->sess_cert->cert_chain = sk;
3307 * Inconsistency alert: cert_chain does *not* include the peer's own
3308 * certificate, while we do include it in s3_clnt.c
3311 sk = NULL;
3313 ret = 1;
3314 if (0) {
3315 f_err:
3316 ssl3_send_alert(s, SSL3_AL_FATAL, al);
3317 err:
3318 s->state = SSL_ST_ERR;
3321 if (x != NULL)
3322 X509_free(x);
3323 if (sk != NULL)
3324 sk_X509_pop_free(sk, X509_free);
3325 return (ret);
3328 int ssl3_send_server_certificate(SSL *s)
3330 unsigned long l;
3331 X509 *x;
3333 if (s->state == SSL3_ST_SW_CERT_A) {
3334 x = ssl_get_server_send_cert(s);
3335 if (x == NULL) {
3336 /* VRS: allow null cert if auth == KRB5 */
3337 if ((s->s3->tmp.new_cipher->algorithm_auth != SSL_aKRB5) ||
3338 (s->s3->tmp.new_cipher->algorithm_mkey & SSL_kKRB5)) {
3339 SSLerr(SSL_F_SSL3_SEND_SERVER_CERTIFICATE,
3340 ERR_R_INTERNAL_ERROR);
3341 s->state = SSL_ST_ERR;
3342 return (0);
3346 l = ssl3_output_cert_chain(s, x);
3347 if (!l) {
3348 SSLerr(SSL_F_SSL3_SEND_SERVER_CERTIFICATE, ERR_R_INTERNAL_ERROR);
3349 s->state = SSL_ST_ERR;
3350 return (0);
3352 s->state = SSL3_ST_SW_CERT_B;
3353 s->init_num = (int)l;
3354 s->init_off = 0;
3357 /* SSL3_ST_SW_CERT_B */
3358 return (ssl3_do_write(s, SSL3_RT_HANDSHAKE));
3361 #ifndef OPENSSL_NO_TLSEXT
3362 /* send a new session ticket (not necessarily for a new session) */
3363 int ssl3_send_newsession_ticket(SSL *s)
3365 unsigned char *senc = NULL;
3366 EVP_CIPHER_CTX ctx;
3367 HMAC_CTX hctx;
3369 if (s->state == SSL3_ST_SW_SESSION_TICKET_A) {
3370 unsigned char *p, *macstart;
3371 const unsigned char *const_p;
3372 int len, slen_full, slen;
3373 SSL_SESSION *sess;
3374 unsigned int hlen;
3375 SSL_CTX *tctx = s->initial_ctx;
3376 unsigned char iv[EVP_MAX_IV_LENGTH];
3377 unsigned char key_name[16];
3379 /* get session encoding length */
3380 slen_full = i2d_SSL_SESSION(s->session, NULL);
3382 * Some length values are 16 bits, so forget it if session is too
3383 * long
3385 if (slen_full == 0 || slen_full > 0xFF00) {
3386 s->state = SSL_ST_ERR;
3387 return -1;
3389 senc = OPENSSL_malloc(slen_full);
3390 if (!senc) {
3391 s->state = SSL_ST_ERR;
3392 return -1;
3395 EVP_CIPHER_CTX_init(&ctx);
3396 HMAC_CTX_init(&hctx);
3398 p = senc;
3399 if (!i2d_SSL_SESSION(s->session, &p))
3400 goto err;
3403 * create a fresh copy (not shared with other threads) to clean up
3405 const_p = senc;
3406 sess = d2i_SSL_SESSION(NULL, &const_p, slen_full);
3407 if (sess == NULL)
3408 goto err;
3409 sess->session_id_length = 0; /* ID is irrelevant for the ticket */
3411 slen = i2d_SSL_SESSION(sess, NULL);
3412 if (slen == 0 || slen > slen_full) { /* shouldn't ever happen */
3413 SSL_SESSION_free(sess);
3414 goto err;
3416 p = senc;
3417 if (!i2d_SSL_SESSION(sess, &p)) {
3418 SSL_SESSION_free(sess);
3419 goto err;
3421 SSL_SESSION_free(sess);
3424 * Grow buffer if need be: the length calculation is as
3425 * follows 1 (size of message name) + 3 (message length
3426 * bytes) + 4 (ticket lifetime hint) + 2 (ticket length) +
3427 * 16 (key name) + max_iv_len (iv length) +
3428 * session_length + max_enc_block_size (max encrypted session
3429 * length) + max_md_size (HMAC).
3431 if (!BUF_MEM_grow(s->init_buf,
3432 26 + EVP_MAX_IV_LENGTH + EVP_MAX_BLOCK_LENGTH +
3433 EVP_MAX_MD_SIZE + slen))
3434 goto err;
3436 p = (unsigned char *)s->init_buf->data;
3437 /* do the header */
3438 *(p++) = SSL3_MT_NEWSESSION_TICKET;
3439 /* Skip message length for now */
3440 p += 3;
3442 * Initialize HMAC and cipher contexts. If callback present it does
3443 * all the work otherwise use generated values from parent ctx.
3445 if (tctx->tlsext_ticket_key_cb) {
3446 if (tctx->tlsext_ticket_key_cb(s, key_name, iv, &ctx,
3447 &hctx, 1) < 0)
3448 goto err;
3449 } else {
3450 if (RAND_bytes(iv, 16) <= 0)
3451 goto err;
3452 if (!EVP_EncryptInit_ex(&ctx, EVP_aes_128_cbc(), NULL,
3453 tctx->tlsext_tick_aes_key, iv))
3454 goto err;
3455 if (!HMAC_Init_ex(&hctx, tctx->tlsext_tick_hmac_key, 16,
3456 tlsext_tick_md(), NULL))
3457 goto err;
3458 memcpy(key_name, tctx->tlsext_tick_key_name, 16);
3462 * Ticket lifetime hint (advisory only): We leave this unspecified
3463 * for resumed session (for simplicity), and guess that tickets for
3464 * new sessions will live as long as their sessions.
3466 l2n(s->hit ? 0 : s->session->timeout, p);
3468 /* Skip ticket length for now */
3469 p += 2;
3470 /* Output key name */
3471 macstart = p;
3472 memcpy(p, key_name, 16);
3473 p += 16;
3474 /* output IV */
3475 memcpy(p, iv, EVP_CIPHER_CTX_iv_length(&ctx));
3476 p += EVP_CIPHER_CTX_iv_length(&ctx);
3477 /* Encrypt session data */
3478 if (!EVP_EncryptUpdate(&ctx, p, &len, senc, slen))
3479 goto err;
3480 p += len;
3481 if (!EVP_EncryptFinal(&ctx, p, &len))
3482 goto err;
3483 p += len;
3485 if (!HMAC_Update(&hctx, macstart, p - macstart))
3486 goto err;
3487 if (!HMAC_Final(&hctx, p, &hlen))
3488 goto err;
3490 EVP_CIPHER_CTX_cleanup(&ctx);
3491 HMAC_CTX_cleanup(&hctx);
3493 p += hlen;
3494 /* Now write out lengths: p points to end of data written */
3495 /* Total length */
3496 len = p - (unsigned char *)s->init_buf->data;
3497 p = (unsigned char *)s->init_buf->data + 1;
3498 l2n3(len - 4, p); /* Message length */
3499 p += 4;
3500 s2n(len - 10, p); /* Ticket length */
3502 /* number of bytes to write */
3503 s->init_num = len;
3504 s->state = SSL3_ST_SW_SESSION_TICKET_B;
3505 s->init_off = 0;
3506 OPENSSL_free(senc);
3509 /* SSL3_ST_SW_SESSION_TICKET_B */
3510 return (ssl3_do_write(s, SSL3_RT_HANDSHAKE));
3511 err:
3512 if (senc)
3513 OPENSSL_free(senc);
3514 EVP_CIPHER_CTX_cleanup(&ctx);
3515 HMAC_CTX_cleanup(&hctx);
3516 s->state = SSL_ST_ERR;
3517 return -1;
3520 int ssl3_send_cert_status(SSL *s)
3522 if (s->state == SSL3_ST_SW_CERT_STATUS_A) {
3523 unsigned char *p;
3525 * Grow buffer if need be: the length calculation is as
3526 * follows 1 (message type) + 3 (message length) +
3527 * 1 (ocsp response type) + 3 (ocsp response length)
3528 * + (ocsp response)
3530 if (!BUF_MEM_grow(s->init_buf, 8 + s->tlsext_ocsp_resplen)) {
3531 s->state = SSL_ST_ERR;
3532 return -1;
3535 p = (unsigned char *)s->init_buf->data;
3537 /* do the header */
3538 *(p++) = SSL3_MT_CERTIFICATE_STATUS;
3539 /* message length */
3540 l2n3(s->tlsext_ocsp_resplen + 4, p);
3541 /* status type */
3542 *(p++) = s->tlsext_status_type;
3543 /* length of OCSP response */
3544 l2n3(s->tlsext_ocsp_resplen, p);
3545 /* actual response */
3546 memcpy(p, s->tlsext_ocsp_resp, s->tlsext_ocsp_resplen);
3547 /* number of bytes to write */
3548 s->init_num = 8 + s->tlsext_ocsp_resplen;
3549 s->state = SSL3_ST_SW_CERT_STATUS_B;
3550 s->init_off = 0;
3553 /* SSL3_ST_SW_CERT_STATUS_B */
3554 return (ssl3_do_write(s, SSL3_RT_HANDSHAKE));
3557 # ifndef OPENSSL_NO_NEXTPROTONEG
3559 * ssl3_get_next_proto reads a Next Protocol Negotiation handshake message.
3560 * It sets the next_proto member in s if found
3562 int ssl3_get_next_proto(SSL *s)
3564 int ok;
3565 int proto_len, padding_len;
3566 long n;
3567 const unsigned char *p;
3570 * Clients cannot send a NextProtocol message if we didn't see the
3571 * extension in their ClientHello
3573 if (!s->s3->next_proto_neg_seen) {
3574 SSLerr(SSL_F_SSL3_GET_NEXT_PROTO,
3575 SSL_R_GOT_NEXT_PROTO_WITHOUT_EXTENSION);
3576 s->state = SSL_ST_ERR;
3577 return -1;
3580 /* See the payload format below */
3581 n = s->method->ssl_get_message(s,
3582 SSL3_ST_SR_NEXT_PROTO_A,
3583 SSL3_ST_SR_NEXT_PROTO_B,
3584 SSL3_MT_NEXT_PROTO, 514, &ok);
3586 if (!ok)
3587 return ((int)n);
3590 * s->state doesn't reflect whether ChangeCipherSpec has been received in
3591 * this handshake, but s->s3->change_cipher_spec does (will be reset by
3592 * ssl3_get_finished).
3594 if (!s->s3->change_cipher_spec) {
3595 SSLerr(SSL_F_SSL3_GET_NEXT_PROTO, SSL_R_GOT_NEXT_PROTO_BEFORE_A_CCS);
3596 s->state = SSL_ST_ERR;
3597 return -1;
3600 if (n < 2) {
3601 s->state = SSL_ST_ERR;
3602 return 0; /* The body must be > 1 bytes long */
3605 p = (unsigned char *)s->init_msg;
3608 * The payload looks like:
3609 * uint8 proto_len;
3610 * uint8 proto[proto_len];
3611 * uint8 padding_len;
3612 * uint8 padding[padding_len];
3614 proto_len = p[0];
3615 if (proto_len + 2 > s->init_num) {
3616 s->state = SSL_ST_ERR;
3617 return 0;
3619 padding_len = p[proto_len + 1];
3620 if (proto_len + padding_len + 2 != s->init_num) {
3621 s->state = SSL_ST_ERR;
3622 return 0;
3625 s->next_proto_negotiated = OPENSSL_malloc(proto_len);
3626 if (!s->next_proto_negotiated) {
3627 SSLerr(SSL_F_SSL3_GET_NEXT_PROTO, ERR_R_MALLOC_FAILURE);
3628 s->state = SSL_ST_ERR;
3629 return 0;
3631 memcpy(s->next_proto_negotiated, p + 1, proto_len);
3632 s->next_proto_negotiated_len = proto_len;
3634 return 1;
3636 # endif
3637 #endif