Identify and move OpenSSL internal header files
[openssl.git] / ssl / s3_srvr.c
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.
4  *
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.
8  *
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).
15  *
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.
22  *
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)"
40  *
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.
52  *
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.]
57  */
58 /* ====================================================================
59  * Copyright (c) 1998-2007 The OpenSSL Project.  All rights reserved.
60  *
61  * Redistribution and use in source and binary forms, with or without
62  * modification, are permitted provided that the following conditions
63  * are met:
64  *
65  * 1. Redistributions of source code must retain the above copyright
66  *    notice, this list of conditions and the following disclaimer.
67  *
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.
72  *
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/)"
77  *
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.
82  *
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.
86  *
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/)"
91  *
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  * ====================================================================
105  *
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).
109  *
110  */
111 /* ====================================================================
112  * Copyright 2002 Sun Microsystems, Inc. ALL RIGHTS RESERVED.
113  *
114  * Portions of the attached software ("Contribution") are developed by
115  * SUN MICROSYSTEMS, INC., and are contributed to the OpenSSL project.
116  *
117  * The Contribution is licensed pursuant to the OpenSSL open source
118  * license provided above.
119  *
120  * ECC cipher suite support in OpenSSL originally written by
121  * Vipul Gupta and Sumit Gupta of Sun Microsystems Laboratories.
122  *
123  */
124 /* ====================================================================
125  * Copyright 2005 Nokia. All rights reserved.
126  *
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.
130  *
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.
134  *
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.
138  *
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.
143  *
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.
149  */
150
151
152 #include <stdio.h>
153 #include "ssl_locl.h"
154 #include "internal/constant_time_locl.h"
155 #include <openssl/buffer.h>
156 #include <openssl/rand.h>
157 #include <openssl/objects.h>
158 #include <openssl/evp.h>
159 #include <openssl/hmac.h>
160 #include <openssl/x509.h>
161 #ifndef OPENSSL_NO_DH
162 # include <openssl/dh.h>
163 #endif
164 #include <openssl/bn.h>
165 #include <openssl/md5.h>
166
167 #ifndef OPENSSL_NO_SSL3_METHOD
168 static const SSL_METHOD *ssl3_get_server_method(int ver);
169
170 static const SSL_METHOD *ssl3_get_server_method(int ver)
171 {
172     if (ver == SSL3_VERSION)
173         return (SSLv3_server_method());
174     else
175         return (NULL);
176 }
177
178 IMPLEMENT_ssl3_meth_func(SSLv3_server_method,
179                          ssl3_accept,
180                          ssl_undefined_function, ssl3_get_server_method)
181 #endif
182 #ifndef OPENSSL_NO_SRP
183 static int ssl_check_srp_ext_ClientHello(SSL *s, int *al)
184 {
185     int ret = SSL_ERROR_NONE;
186
187     *al = SSL_AD_UNRECOGNIZED_NAME;
188
189     if ((s->s3->tmp.new_cipher->algorithm_mkey & SSL_kSRP) &&
190         (s->srp_ctx.TLS_ext_srp_username_callback != NULL)) {
191         if (s->srp_ctx.login == NULL) {
192             /*
193              * RFC 5054 says SHOULD reject, we do so if There is no srp
194              * login name
195              */
196             ret = SSL3_AL_FATAL;
197             *al = SSL_AD_UNKNOWN_PSK_IDENTITY;
198         } else {
199             ret = SSL_srp_server_param_with_username(s, al);
200         }
201     }
202     return ret;
203 }
204 #endif
205
206 int ssl3_accept(SSL *s)
207 {
208     BUF_MEM *buf;
209     unsigned long alg_k, Time = (unsigned long)time(NULL);
210     void (*cb) (const SSL *ssl, int type, int val) = NULL;
211     int ret = -1;
212     int new_state, state, skip = 0;
213
214     RAND_add(&Time, sizeof(Time), 0);
215     ERR_clear_error();
216     clear_sys_error();
217
218     if (s->info_callback != NULL)
219         cb = s->info_callback;
220     else if (s->ctx->info_callback != NULL)
221         cb = s->ctx->info_callback;
222
223     /* init things to blank */
224     s->in_handshake++;
225     if (!SSL_in_init(s) || SSL_in_before(s)) {
226         if (!SSL_clear(s))
227             return -1;
228     }
229
230 #ifndef OPENSSL_NO_HEARTBEATS
231     /*
232      * If we're awaiting a HeartbeatResponse, pretend we already got and
233      * don't await it anymore, because Heartbeats don't make sense during
234      * handshakes anyway.
235      */
236     if (s->tlsext_hb_pending) {
237         s->tlsext_hb_pending = 0;
238         s->tlsext_hb_seq++;
239     }
240 #endif
241
242     for (;;) {
243         state = s->state;
244
245         switch (s->state) {
246         case SSL_ST_RENEGOTIATE:
247             s->renegotiate = 1;
248             /* s->state=SSL_ST_ACCEPT; */
249
250         case SSL_ST_BEFORE:
251         case SSL_ST_ACCEPT:
252         case SSL_ST_BEFORE | SSL_ST_ACCEPT:
253         case SSL_ST_OK | SSL_ST_ACCEPT:
254
255             s->server = 1;
256             if (cb != NULL)
257                 cb(s, SSL_CB_HANDSHAKE_START, 1);
258
259             if ((s->version >> 8) != 3) {
260                 SSLerr(SSL_F_SSL3_ACCEPT, ERR_R_INTERNAL_ERROR);
261                 s->state = SSL_ST_ERR;
262                 return -1;
263             }
264
265             if (!ssl_security(s, SSL_SECOP_VERSION, 0, s->version, NULL)) {
266                 SSLerr(SSL_F_SSL3_ACCEPT, SSL_R_VERSION_TOO_LOW);
267                 return -1;
268             }
269
270             s->type = SSL_ST_ACCEPT;
271
272             if (s->init_buf == NULL) {
273                 if ((buf = BUF_MEM_new()) == NULL) {
274                     ret = -1;
275                     s->state = SSL_ST_ERR;
276                     goto end;
277                 }
278                 if (!BUF_MEM_grow(buf, SSL3_RT_MAX_PLAIN_LENGTH)) {
279                     BUF_MEM_free(buf);
280                     ret = -1;
281                     s->state = SSL_ST_ERR;
282                     goto end;
283                 }
284                 s->init_buf = buf;
285             }
286
287             if (!ssl3_setup_buffers(s)) {
288                 ret = -1;
289                 s->state = SSL_ST_ERR;
290                 goto end;
291             }
292
293             s->init_num = 0;
294             s->s3->flags &= ~TLS1_FLAGS_SKIP_CERT_VERIFY;
295             s->s3->flags &= ~SSL3_FLAGS_CCS_OK;
296             /*
297              * Should have been reset by ssl3_get_finished, too.
298              */
299             s->s3->change_cipher_spec = 0;
300
301             if (s->state != SSL_ST_RENEGOTIATE) {
302                 /*
303                  * Ok, we now need to push on a buffering BIO so that the
304                  * output is sent in a way that TCP likes :-)
305                  */
306                 if (!ssl_init_wbio_buffer(s, 1)) {
307                     ret = -1;
308                     s->state = SSL_ST_ERR;
309                     goto end;
310                 }
311
312                 ssl3_init_finished_mac(s);
313                 s->state = SSL3_ST_SR_CLNT_HELLO_A;
314                 s->ctx->stats.sess_accept++;
315             } else if (!s->s3->send_connection_binding &&
316                        !(s->options &
317                          SSL_OP_ALLOW_UNSAFE_LEGACY_RENEGOTIATION)) {
318                 /*
319                  * Server attempting to renegotiate with client that doesn't
320                  * support secure renegotiation.
321                  */
322                 SSLerr(SSL_F_SSL3_ACCEPT,
323                        SSL_R_UNSAFE_LEGACY_RENEGOTIATION_DISABLED);
324                 ssl3_send_alert(s, SSL3_AL_FATAL, SSL_AD_HANDSHAKE_FAILURE);
325                 ret = -1;
326                 s->state = SSL_ST_ERR;
327                 goto end;
328             } else {
329                 /*
330                  * s->state == SSL_ST_RENEGOTIATE, we will just send a
331                  * HelloRequest
332                  */
333                 s->ctx->stats.sess_accept_renegotiate++;
334                 s->state = SSL3_ST_SW_HELLO_REQ_A;
335             }
336             break;
337
338         case SSL3_ST_SW_HELLO_REQ_A:
339         case SSL3_ST_SW_HELLO_REQ_B:
340
341             s->shutdown = 0;
342             ret = ssl3_send_hello_request(s);
343             if (ret <= 0)
344                 goto end;
345             s->s3->tmp.next_state = SSL3_ST_SW_HELLO_REQ_C;
346             s->state = SSL3_ST_SW_FLUSH;
347             s->init_num = 0;
348
349             ssl3_init_finished_mac(s);
350             break;
351
352         case SSL3_ST_SW_HELLO_REQ_C:
353             s->state = SSL_ST_OK;
354             break;
355
356         case SSL3_ST_SR_CLNT_HELLO_A:
357         case SSL3_ST_SR_CLNT_HELLO_B:
358         case SSL3_ST_SR_CLNT_HELLO_C:
359
360             ret = ssl3_get_client_hello(s);
361             if (ret <= 0)
362                 goto end;
363 #ifndef OPENSSL_NO_SRP
364             s->state = SSL3_ST_SR_CLNT_HELLO_D;
365         case SSL3_ST_SR_CLNT_HELLO_D:
366             {
367                 int al;
368                 if ((ret = ssl_check_srp_ext_ClientHello(s, &al)) < 0) {
369                     /*
370                      * callback indicates firther work to be done
371                      */
372                     s->rwstate = SSL_X509_LOOKUP;
373                     goto end;
374                 }
375                 if (ret != SSL_ERROR_NONE) {
376                     ssl3_send_alert(s, SSL3_AL_FATAL, al);
377                     /*
378                      * This is not really an error but the only means to for
379                      * a client to detect whether srp is supported.
380                      */
381                     if (al != TLS1_AD_UNKNOWN_PSK_IDENTITY)
382                         SSLerr(SSL_F_SSL3_ACCEPT, SSL_R_CLIENTHELLO_TLSEXT);
383                     ret = SSL_TLSEXT_ERR_ALERT_FATAL;
384                     ret = -1;
385                     s->state = SSL_ST_ERR;
386                     goto end;
387                 }
388             }
389 #endif
390
391             s->renegotiate = 2;
392             s->state = SSL3_ST_SW_SRVR_HELLO_A;
393             s->init_num = 0;
394             break;
395
396         case SSL3_ST_SW_SRVR_HELLO_A:
397         case SSL3_ST_SW_SRVR_HELLO_B:
398             ret = ssl3_send_server_hello(s);
399             if (ret <= 0)
400                 goto end;
401 #ifndef OPENSSL_NO_TLSEXT
402             if (s->hit) {
403                 if (s->tlsext_ticket_expected)
404                     s->state = SSL3_ST_SW_SESSION_TICKET_A;
405                 else
406                     s->state = SSL3_ST_SW_CHANGE_A;
407             }
408 #else
409             if (s->hit)
410                 s->state = SSL3_ST_SW_CHANGE_A;
411 #endif
412             else
413                 s->state = SSL3_ST_SW_CERT_A;
414             s->init_num = 0;
415             break;
416
417         case SSL3_ST_SW_CERT_A:
418         case SSL3_ST_SW_CERT_B:
419             /* Check if it is anon DH or anon ECDH, */
420             /* normal PSK or SRP */
421             if (!
422                 (s->s3->tmp.
423                  new_cipher->algorithm_auth & (SSL_aNULL | SSL_aSRP))
424 && !(s->s3->tmp.new_cipher->algorithm_mkey & SSL_kPSK)) {
425                 ret = ssl3_send_server_certificate(s);
426                 if (ret <= 0)
427                     goto end;
428 #ifndef OPENSSL_NO_TLSEXT
429                 if (s->tlsext_status_expected)
430                     s->state = SSL3_ST_SW_CERT_STATUS_A;
431                 else
432                     s->state = SSL3_ST_SW_KEY_EXCH_A;
433             } else {
434                 skip = 1;
435                 s->state = SSL3_ST_SW_KEY_EXCH_A;
436             }
437 #else
438             } else
439                 skip = 1;
440
441             s->state = SSL3_ST_SW_KEY_EXCH_A;
442 #endif
443             s->init_num = 0;
444             break;
445
446         case SSL3_ST_SW_KEY_EXCH_A:
447         case SSL3_ST_SW_KEY_EXCH_B:
448             alg_k = s->s3->tmp.new_cipher->algorithm_mkey;
449
450             /*
451              * clear this, it may get reset by
452              * send_server_key_exchange
453              */
454             s->s3->tmp.use_rsa_tmp = 0;
455
456             /*
457              * only send if a DH key exchange, fortezza or RSA but we have a
458              * sign only certificate PSK: may send PSK identity hints For
459              * ECC ciphersuites, we send a serverKeyExchange message only if
460              * the cipher suite is either ECDH-anon or ECDHE. In other cases,
461              * the server certificate contains the server's public key for
462              * key exchange.
463              */
464             if (0
465                 /*
466                  * PSK: send ServerKeyExchange if PSK identity hint if
467                  * provided
468                  */
469 #ifndef OPENSSL_NO_PSK
470                 || ((alg_k & SSL_kPSK) && s->ctx->psk_identity_hint)
471 #endif
472 #ifndef OPENSSL_NO_SRP
473                 /* SRP: send ServerKeyExchange */
474                 || (alg_k & SSL_kSRP)
475 #endif
476                 || (alg_k & SSL_kDHE)
477                 || (alg_k & SSL_kECDHE)
478                 || ((alg_k & SSL_kRSA)
479                     && (s->cert->pkeys[SSL_PKEY_RSA_ENC].privatekey == NULL
480                         || (SSL_C_IS_EXPORT(s->s3->tmp.new_cipher)
481                             && EVP_PKEY_size(s->cert->pkeys
482                                              [SSL_PKEY_RSA_ENC].privatekey) *
483                             8 > SSL_C_EXPORT_PKEYLENGTH(s->s3->tmp.new_cipher)
484                         )
485                     )
486                 )
487                 ) {
488                 ret = ssl3_send_server_key_exchange(s);
489                 if (ret <= 0)
490                     goto end;
491             } else
492                 skip = 1;
493
494             s->state = SSL3_ST_SW_CERT_REQ_A;
495             s->init_num = 0;
496             break;
497
498         case SSL3_ST_SW_CERT_REQ_A:
499         case SSL3_ST_SW_CERT_REQ_B:
500             if (                /* don't request cert unless asked for it: */
501                    !(s->verify_mode & SSL_VERIFY_PEER) ||
502                    /*
503                     * if SSL_VERIFY_CLIENT_ONCE is set, don't request cert
504                     * during re-negotiation:
505                     */
506                    ((s->session->peer != NULL) &&
507                     (s->verify_mode & SSL_VERIFY_CLIENT_ONCE)) ||
508                    /*
509                     * never request cert in anonymous ciphersuites (see
510                     * section "Certificate request" in SSL 3 drafts and in
511                     * RFC 2246):
512                     */
513                    ((s->s3->tmp.new_cipher->algorithm_auth & SSL_aNULL) &&
514                    /*
515                     * ... except when the application insists on
516                     * verification (against the specs, but s3_clnt.c accepts
517                     * this for SSL 3)
518                     */
519                    !(s->verify_mode & SSL_VERIFY_FAIL_IF_NO_PEER_CERT)) ||
520                    /* don't request certificate for SRP auth */
521                    (s->s3->tmp.new_cipher->algorithm_auth & SSL_aSRP)
522                    /*
523                     * With normal PSK Certificates and Certificate Requests
524                     * are omitted
525                     */
526                    || (s->s3->tmp.new_cipher->algorithm_mkey & SSL_kPSK)) {
527                 /* no cert request */
528                 skip = 1;
529                 s->s3->tmp.cert_request = 0;
530                 s->state = SSL3_ST_SW_SRVR_DONE_A;
531                 if (s->s3->handshake_buffer) {
532                     if (!ssl3_digest_cached_records(s)) {
533                         s->state = SSL_ST_ERR;
534                         return -1;
535                     }
536                 }
537             } else {
538                 s->s3->tmp.cert_request = 1;
539                 ret = ssl3_send_certificate_request(s);
540                 if (ret <= 0)
541                     goto end;
542                 s->state = SSL3_ST_SW_SRVR_DONE_A;
543                 s->init_num = 0;
544             }
545             break;
546
547         case SSL3_ST_SW_SRVR_DONE_A:
548         case SSL3_ST_SW_SRVR_DONE_B:
549             ret = ssl3_send_server_done(s);
550             if (ret <= 0)
551                 goto end;
552             s->s3->tmp.next_state = SSL3_ST_SR_CERT_A;
553             s->state = SSL3_ST_SW_FLUSH;
554             s->init_num = 0;
555             break;
556
557         case SSL3_ST_SW_FLUSH:
558
559             /*
560              * This code originally checked to see if any data was pending
561              * using BIO_CTRL_INFO and then flushed. This caused problems as
562              * documented in PR#1939. The proposed fix doesn't completely
563              * resolve this issue as buggy implementations of
564              * BIO_CTRL_PENDING still exist. So instead we just flush
565              * unconditionally.
566              */
567
568             s->rwstate = SSL_WRITING;
569             if (BIO_flush(s->wbio) <= 0) {
570                 ret = -1;
571                 goto end;
572             }
573             s->rwstate = SSL_NOTHING;
574
575             s->state = s->s3->tmp.next_state;
576             break;
577
578         case SSL3_ST_SR_CERT_A:
579         case SSL3_ST_SR_CERT_B:
580             if (s->s3->tmp.cert_request) {
581                 ret = ssl3_get_client_certificate(s);
582                 if (ret <= 0)
583                     goto end;
584             }
585             s->init_num = 0;
586             s->state = SSL3_ST_SR_KEY_EXCH_A;
587             break;
588
589         case SSL3_ST_SR_KEY_EXCH_A:
590         case SSL3_ST_SR_KEY_EXCH_B:
591             ret = ssl3_get_client_key_exchange(s);
592             if (ret <= 0)
593                 goto end;
594             if (ret == 2) {
595                 /*
596                  * For the ECDH ciphersuites when the client sends its ECDH
597                  * pub key in a certificate, the CertificateVerify message is
598                  * not sent. Also for GOST ciphersuites when the client uses
599                  * its key from the certificate for key exchange.
600                  */
601 #if defined(OPENSSL_NO_TLSEXT) || defined(OPENSSL_NO_NEXTPROTONEG)
602                 s->state = SSL3_ST_SR_FINISHED_A;
603 #else
604                 if (s->s3->next_proto_neg_seen)
605                     s->state = SSL3_ST_SR_NEXT_PROTO_A;
606                 else
607                     s->state = SSL3_ST_SR_FINISHED_A;
608 #endif
609                 s->init_num = 0;
610             } else if (SSL_USE_SIGALGS(s)) {
611                 s->state = SSL3_ST_SR_CERT_VRFY_A;
612                 s->init_num = 0;
613                 if (!s->session->peer)
614                     break;
615                 if (!s->s3->handshake_buffer) {
616                     SSLerr(SSL_F_SSL3_ACCEPT, ERR_R_INTERNAL_ERROR);
617                     s->state = SSL_ST_ERR;
618                     return -1;
619                 }
620                 /*
621                  * For sigalgs freeze the handshake buffer. If we support
622                  * extms we've done this already.
623                  */
624                 if (!(s->s3->flags & SSL_SESS_FLAG_EXTMS)) {
625                     s->s3->flags |= TLS1_FLAGS_KEEP_HANDSHAKE;
626                     if (!ssl3_digest_cached_records(s)) {
627                         s->state = SSL_ST_ERR;
628                         return -1;
629                     }
630                 }
631             } else {
632                 int offset = 0;
633                 int dgst_num;
634
635                 s->state = SSL3_ST_SR_CERT_VRFY_A;
636                 s->init_num = 0;
637
638                 /*
639                  * We need to get hashes here so if there is a client cert,
640                  * it can be verified FIXME - digest processing for
641                  * CertificateVerify should be generalized. But it is next
642                  * step
643                  */
644                 if (s->s3->handshake_buffer) {
645                     if (!ssl3_digest_cached_records(s)) {
646                         s->state = SSL_ST_ERR;
647                         return -1;
648                     }
649                 }
650                 for (dgst_num = 0; dgst_num < SSL_MAX_DIGEST; dgst_num++)
651                     if (s->s3->handshake_dgst[dgst_num]) {
652                         int dgst_size;
653
654                         s->method->ssl3_enc->cert_verify_mac(s,
655                                                              EVP_MD_CTX_type
656                                                              (s->
657                                                               s3->handshake_dgst
658                                                               [dgst_num]),
659                                                              &(s->s3->
660                                                                tmp.cert_verify_md
661                                                                [offset]));
662                         dgst_size =
663                             EVP_MD_CTX_size(s->s3->handshake_dgst[dgst_num]);
664                         if (dgst_size < 0) {
665                             s->state = SSL_ST_ERR;
666                             ret = -1;
667                             goto end;
668                         }
669                         offset += dgst_size;
670                     }
671             }
672             break;
673
674         case SSL3_ST_SR_CERT_VRFY_A:
675         case SSL3_ST_SR_CERT_VRFY_B:
676             ret = ssl3_get_cert_verify(s);
677             if (ret <= 0)
678                 goto end;
679
680 #if defined(OPENSSL_NO_TLSEXT) || defined(OPENSSL_NO_NEXTPROTONEG)
681             s->state = SSL3_ST_SR_FINISHED_A;
682 #else
683             if (s->s3->next_proto_neg_seen)
684                 s->state = SSL3_ST_SR_NEXT_PROTO_A;
685             else
686                 s->state = SSL3_ST_SR_FINISHED_A;
687 #endif
688             s->init_num = 0;
689             break;
690
691 #if !defined(OPENSSL_NO_TLSEXT) && !defined(OPENSSL_NO_NEXTPROTONEG)
692         case SSL3_ST_SR_NEXT_PROTO_A:
693         case SSL3_ST_SR_NEXT_PROTO_B:
694             /*
695              * Enable CCS for NPN. Receiving a CCS clears the flag, so make
696              * sure not to re-enable it to ban duplicates. This *should* be the
697              * first time we have received one - but we check anyway to be
698              * cautious.
699              * s->s3->change_cipher_spec is set when a CCS is
700              * processed in s3_pkt.c, and remains set until
701              * the client's Finished message is read.
702              */
703             if (!s->s3->change_cipher_spec)
704                 s->s3->flags |= SSL3_FLAGS_CCS_OK;
705
706             ret = ssl3_get_next_proto(s);
707             if (ret <= 0)
708                 goto end;
709             s->init_num = 0;
710             s->state = SSL3_ST_SR_FINISHED_A;
711             break;
712 #endif
713
714         case SSL3_ST_SR_FINISHED_A:
715         case SSL3_ST_SR_FINISHED_B:
716             /*
717              * Enable CCS for handshakes without NPN. In NPN the CCS flag has
718              * already been set. Receiving a CCS clears the flag, so make
719              * sure not to re-enable it to ban duplicates.
720              * s->s3->change_cipher_spec is set when a CCS is
721              * processed in s3_pkt.c, and remains set until
722              * the client's Finished message is read.
723              */
724             if (!s->s3->change_cipher_spec)
725                 s->s3->flags |= SSL3_FLAGS_CCS_OK;
726             ret = ssl3_get_finished(s, SSL3_ST_SR_FINISHED_A,
727                                     SSL3_ST_SR_FINISHED_B);
728             if (ret <= 0)
729                 goto end;
730             if (s->hit)
731                 s->state = SSL_ST_OK;
732 #ifndef OPENSSL_NO_TLSEXT
733             else if (s->tlsext_ticket_expected)
734                 s->state = SSL3_ST_SW_SESSION_TICKET_A;
735 #endif
736             else
737                 s->state = SSL3_ST_SW_CHANGE_A;
738             s->init_num = 0;
739             break;
740
741 #ifndef OPENSSL_NO_TLSEXT
742         case SSL3_ST_SW_SESSION_TICKET_A:
743         case SSL3_ST_SW_SESSION_TICKET_B:
744             ret = ssl3_send_newsession_ticket(s);
745             if (ret <= 0)
746                 goto end;
747             s->state = SSL3_ST_SW_CHANGE_A;
748             s->init_num = 0;
749             break;
750
751         case SSL3_ST_SW_CERT_STATUS_A:
752         case SSL3_ST_SW_CERT_STATUS_B:
753             ret = ssl3_send_cert_status(s);
754             if (ret <= 0)
755                 goto end;
756             s->state = SSL3_ST_SW_KEY_EXCH_A;
757             s->init_num = 0;
758             break;
759
760 #endif
761
762         case SSL3_ST_SW_CHANGE_A:
763         case SSL3_ST_SW_CHANGE_B:
764
765             s->session->cipher = s->s3->tmp.new_cipher;
766             if (!s->method->ssl3_enc->setup_key_block(s)) {
767                 ret = -1;
768                 s->state = SSL_ST_ERR;
769                 goto end;
770             }
771
772             ret = ssl3_send_change_cipher_spec(s,
773                                                SSL3_ST_SW_CHANGE_A,
774                                                SSL3_ST_SW_CHANGE_B);
775
776             if (ret <= 0)
777                 goto end;
778             s->state = SSL3_ST_SW_FINISHED_A;
779             s->init_num = 0;
780
781             if (!s->method->ssl3_enc->change_cipher_state(s,
782                                                           SSL3_CHANGE_CIPHER_SERVER_WRITE))
783             {
784                 ret = -1;
785                 s->state = SSL_ST_ERR;
786                 goto end;
787             }
788
789             break;
790
791         case SSL3_ST_SW_FINISHED_A:
792         case SSL3_ST_SW_FINISHED_B:
793             ret = ssl3_send_finished(s,
794                                      SSL3_ST_SW_FINISHED_A,
795                                      SSL3_ST_SW_FINISHED_B,
796                                      s->method->
797                                      ssl3_enc->server_finished_label,
798                                      s->method->
799                                      ssl3_enc->server_finished_label_len);
800             if (ret <= 0)
801                 goto end;
802             s->state = SSL3_ST_SW_FLUSH;
803             if (s->hit) {
804 #if defined(OPENSSL_NO_TLSEXT) || defined(OPENSSL_NO_NEXTPROTONEG)
805                 s->s3->tmp.next_state = SSL3_ST_SR_FINISHED_A;
806 #else
807                 if (s->s3->next_proto_neg_seen) {
808                     s->s3->tmp.next_state = SSL3_ST_SR_NEXT_PROTO_A;
809                 } else
810                     s->s3->tmp.next_state = SSL3_ST_SR_FINISHED_A;
811 #endif
812             } else
813                 s->s3->tmp.next_state = SSL_ST_OK;
814             s->init_num = 0;
815             break;
816
817         case SSL_ST_OK:
818             /* clean a few things up */
819             ssl3_cleanup_key_block(s);
820
821             BUF_MEM_free(s->init_buf);
822             s->init_buf = NULL;
823
824             /* remove buffering on output */
825             ssl_free_wbio_buffer(s);
826
827             s->init_num = 0;
828
829             if (s->renegotiate == 2) { /* skipped if we just sent a
830                                         * HelloRequest */
831                 s->renegotiate = 0;
832                 s->new_session = 0;
833
834                 ssl_update_cache(s, SSL_SESS_CACHE_SERVER);
835
836                 s->ctx->stats.sess_accept_good++;
837                 /* s->server=1; */
838                 s->handshake_func = ssl3_accept;
839
840                 if (cb != NULL)
841                     cb(s, SSL_CB_HANDSHAKE_DONE, 1);
842             }
843
844             ret = 1;
845             goto end;
846             /* break; */
847
848         case SSL_ST_ERR:
849         default:
850             SSLerr(SSL_F_SSL3_ACCEPT, SSL_R_UNKNOWN_STATE);
851             ret = -1;
852             goto end;
853             /* break; */
854         }
855
856         if (!s->s3->tmp.reuse_message && !skip) {
857             if (s->debug) {
858                 if ((ret = BIO_flush(s->wbio)) <= 0)
859                     goto end;
860             }
861
862             if ((cb != NULL) && (s->state != state)) {
863                 new_state = s->state;
864                 s->state = state;
865                 cb(s, SSL_CB_ACCEPT_LOOP, 1);
866                 s->state = new_state;
867             }
868         }
869         skip = 0;
870     }
871  end:
872     /* BIO_flush(s->wbio); */
873
874     s->in_handshake--;
875     if (cb != NULL)
876         cb(s, SSL_CB_ACCEPT_EXIT, ret);
877     return (ret);
878 }
879
880 int ssl3_send_hello_request(SSL *s)
881 {
882
883     if (s->state == SSL3_ST_SW_HELLO_REQ_A) {
884         if (!ssl_set_handshake_header(s, SSL3_MT_HELLO_REQUEST, 0)) {
885             SSLerr(SSL_F_SSL3_SEND_HELLO_REQUEST, ERR_R_INTERNAL_ERROR);
886             return -1;
887         }
888         s->state = SSL3_ST_SW_HELLO_REQ_B;
889     }
890
891     /* SSL3_ST_SW_HELLO_REQ_B */
892     return ssl_do_write(s);
893 }
894
895 int ssl3_get_client_hello(SSL *s)
896 {
897     int i, j, ok, al = SSL_AD_INTERNAL_ERROR, ret = -1;
898     unsigned int cookie_len;
899     long n;
900     unsigned long id;
901     unsigned char *p, *d;
902     SSL_CIPHER *c;
903 #ifndef OPENSSL_NO_COMP
904     unsigned char *q;
905     SSL_COMP *comp = NULL;
906 #endif
907     STACK_OF(SSL_CIPHER) *ciphers = NULL;
908
909     if (s->state == SSL3_ST_SR_CLNT_HELLO_C && !s->first_packet)
910         goto retry_cert;
911
912     /*
913      * We do this so that we will respond with our native type. If we are
914      * TLSv1 and we get SSLv3, we will respond with TLSv1, This down
915      * switching should be handled by a different method. If we are SSLv3, we
916      * will respond with SSLv3, even if prompted with TLSv1.
917      */
918     if (s->state == SSL3_ST_SR_CLNT_HELLO_A) {
919         s->state = SSL3_ST_SR_CLNT_HELLO_B;
920     }
921     s->first_packet = 1;
922     n = s->method->ssl_get_message(s,
923                                    SSL3_ST_SR_CLNT_HELLO_B,
924                                    SSL3_ST_SR_CLNT_HELLO_C,
925                                    SSL3_MT_CLIENT_HELLO,
926                                    SSL3_RT_MAX_PLAIN_LENGTH, &ok);
927
928     if (!ok)
929         return ((int)n);
930     s->first_packet = 0;
931     d = p = (unsigned char *)s->init_msg;
932
933     /*
934      * 2 bytes for client version, SSL3_RANDOM_SIZE bytes for random, 1 byte
935      * for session id length
936      */
937     if (n < 2 + SSL3_RANDOM_SIZE + 1) {
938         al = SSL_AD_DECODE_ERROR;
939         SSLerr(SSL_F_SSL3_GET_CLIENT_HELLO, SSL_R_LENGTH_TOO_SHORT);
940         goto f_err;
941     }
942
943     /*
944      * use version from inside client hello, not from record header (may
945      * differ: see RFC 2246, Appendix E, second paragraph)
946      */
947     s->client_version = (((int)p[0]) << 8) | (int)p[1];
948     p += 2;
949
950     if (SSL_IS_DTLS(s) ? (s->client_version > s->version &&
951                           s->method->version != DTLS_ANY_VERSION)
952         : (s->client_version < s->version)) {
953         SSLerr(SSL_F_SSL3_GET_CLIENT_HELLO, SSL_R_WRONG_VERSION_NUMBER);
954         if ((s->client_version >> 8) == SSL3_VERSION_MAJOR &&
955             !s->enc_write_ctx && !s->write_hash) {
956             /*
957              * similar to ssl3_get_record, send alert using remote version
958              * number
959              */
960             s->version = s->client_version;
961         }
962         al = SSL_AD_PROTOCOL_VERSION;
963         goto f_err;
964     }
965
966     /*
967      * If we require cookies and this ClientHello doesn't contain one, just
968      * return since we do not want to allocate any memory yet. So check
969      * cookie length...
970      */
971     if (SSL_get_options(s) & SSL_OP_COOKIE_EXCHANGE) {
972         unsigned int session_length, cookie_length;
973
974         session_length = *(p + SSL3_RANDOM_SIZE);
975
976         if (p + SSL3_RANDOM_SIZE + session_length + 1 >= d + n) {
977             al = SSL_AD_DECODE_ERROR;
978             SSLerr(SSL_F_SSL3_GET_CLIENT_HELLO, SSL_R_LENGTH_TOO_SHORT);
979             goto f_err;
980         }
981         cookie_length = *(p + SSL3_RANDOM_SIZE + session_length + 1);
982
983         if (cookie_length == 0)
984             return 1;
985     }
986
987     /* load the client random */
988     memcpy(s->s3->client_random, p, SSL3_RANDOM_SIZE);
989     p += SSL3_RANDOM_SIZE;
990
991     /* get the session-id */
992     j = *(p++);
993
994     if (p + j > d + n) {
995         al = SSL_AD_DECODE_ERROR;
996         SSLerr(SSL_F_SSL3_GET_CLIENT_HELLO, SSL_R_LENGTH_TOO_SHORT);
997         goto f_err;
998     }
999
1000     s->hit = 0;
1001     /*
1002      * Versions before 0.9.7 always allow clients to resume sessions in
1003      * renegotiation. 0.9.7 and later allow this by default, but optionally
1004      * ignore resumption requests with flag
1005      * SSL_OP_NO_SESSION_RESUMPTION_ON_RENEGOTIATION (it's a new flag rather
1006      * than a change to default behavior so that applications relying on this
1007      * for security won't even compile against older library versions).
1008      * 1.0.1 and later also have a function SSL_renegotiate_abbreviated() to
1009      * request renegotiation but not a new session (s->new_session remains
1010      * unset): for servers, this essentially just means that the
1011      * SSL_OP_NO_SESSION_RESUMPTION_ON_RENEGOTIATION setting will be ignored.
1012      */
1013     if ((s->new_session
1014          && (s->options & SSL_OP_NO_SESSION_RESUMPTION_ON_RENEGOTIATION))) {
1015         if (!ssl_get_new_session(s, 1))
1016             goto err;
1017     } else {
1018         i = ssl_get_prev_session(s, p, j, d + n);
1019         /*
1020          * Only resume if the session's version matches the negotiated
1021          * version.
1022          * RFC 5246 does not provide much useful advice on resumption
1023          * with a different protocol version. It doesn't forbid it but
1024          * the sanity of such behaviour would be questionable.
1025          * In practice, clients do not accept a version mismatch and
1026          * will abort the handshake with an error.
1027          */
1028         if (i == 1 && s->version == s->session->ssl_version) { /* previous
1029                                                                 * session */
1030             s->hit = 1;
1031         } else if (i == -1)
1032             goto err;
1033         else {                  /* i == 0 */
1034
1035             if (!ssl_get_new_session(s, 1))
1036                 goto err;
1037         }
1038     }
1039
1040     p += j;
1041
1042     if (SSL_IS_DTLS(s)) {
1043         /* cookie stuff */
1044         if (p + 1 > d + n) {
1045             al = SSL_AD_DECODE_ERROR;
1046             SSLerr(SSL_F_SSL3_GET_CLIENT_HELLO, SSL_R_LENGTH_TOO_SHORT);
1047             goto f_err;
1048         }
1049         cookie_len = *(p++);
1050
1051         if (p + cookie_len > 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;
1055         }
1056
1057         /*
1058          * The ClientHello may contain a cookie even if the
1059          * HelloVerify message has not been sent--make sure that it
1060          * does not cause an overflow.
1061          */
1062         if (cookie_len > sizeof(s->d1->rcvd_cookie)) {
1063             /* too much data */
1064             al = SSL_AD_DECODE_ERROR;
1065             SSLerr(SSL_F_SSL3_GET_CLIENT_HELLO, SSL_R_COOKIE_MISMATCH);
1066             goto f_err;
1067         }
1068
1069         /* verify the cookie if appropriate option is set. */
1070         if ((SSL_get_options(s) & SSL_OP_COOKIE_EXCHANGE) && cookie_len > 0) {
1071             memcpy(s->d1->rcvd_cookie, p, cookie_len);
1072
1073             if (s->ctx->app_verify_cookie_cb != NULL) {
1074                 if (s->ctx->app_verify_cookie_cb(s, s->d1->rcvd_cookie,
1075                                                  cookie_len) == 0) {
1076                     al = SSL_AD_HANDSHAKE_FAILURE;
1077                     SSLerr(SSL_F_SSL3_GET_CLIENT_HELLO,
1078                            SSL_R_COOKIE_MISMATCH);
1079                     goto f_err;
1080                 }
1081                 /* else cookie verification succeeded */
1082             }
1083             /* default verification */
1084             else if (memcmp(s->d1->rcvd_cookie, s->d1->cookie,
1085                             s->d1->cookie_len) != 0) {
1086                 al = SSL_AD_HANDSHAKE_FAILURE;
1087                 SSLerr(SSL_F_SSL3_GET_CLIENT_HELLO, SSL_R_COOKIE_MISMATCH);
1088                 goto f_err;
1089             }
1090             /* Set to -2 so if successful we return 2 */
1091             ret = -2;
1092         }
1093
1094         p += cookie_len;
1095         if (s->method->version == DTLS_ANY_VERSION) {
1096             /* Select version to use */
1097             if (s->client_version <= DTLS1_2_VERSION &&
1098                 !(s->options & SSL_OP_NO_DTLSv1_2)) {
1099                 s->version = DTLS1_2_VERSION;
1100                 s->method = DTLSv1_2_server_method();
1101             } else if (tls1_suiteb(s)) {
1102                 SSLerr(SSL_F_SSL3_GET_CLIENT_HELLO,
1103                        SSL_R_ONLY_DTLS_1_2_ALLOWED_IN_SUITEB_MODE);
1104                 s->version = s->client_version;
1105                 al = SSL_AD_PROTOCOL_VERSION;
1106                 goto f_err;
1107             } else if (s->client_version <= DTLS1_VERSION &&
1108                        !(s->options & SSL_OP_NO_DTLSv1)) {
1109                 s->version = DTLS1_VERSION;
1110                 s->method = DTLSv1_server_method();
1111             } else {
1112                 SSLerr(SSL_F_SSL3_GET_CLIENT_HELLO,
1113                        SSL_R_WRONG_VERSION_NUMBER);
1114                 s->version = s->client_version;
1115                 al = SSL_AD_PROTOCOL_VERSION;
1116                 goto f_err;
1117             }
1118             s->session->ssl_version = s->version;
1119         }
1120     }
1121
1122     if (p + 2 > d + n) {
1123         al = SSL_AD_DECODE_ERROR;
1124         SSLerr(SSL_F_SSL3_GET_CLIENT_HELLO, SSL_R_LENGTH_TOO_SHORT);
1125         goto f_err;
1126     }
1127     n2s(p, i);
1128
1129     if (i == 0) {
1130         al = SSL_AD_ILLEGAL_PARAMETER;
1131         SSLerr(SSL_F_SSL3_GET_CLIENT_HELLO, SSL_R_NO_CIPHERS_SPECIFIED);
1132         goto f_err;
1133     }
1134
1135     /* i bytes of cipher data + 1 byte for compression length later */
1136     if ((p + i + 1) > (d + n)) {
1137         /* not enough data */
1138         al = SSL_AD_DECODE_ERROR;
1139         SSLerr(SSL_F_SSL3_GET_CLIENT_HELLO, SSL_R_LENGTH_MISMATCH);
1140         goto f_err;
1141     }
1142     if (ssl_bytes_to_cipher_list(s, p, i, &(ciphers)) == NULL) {
1143         goto err;
1144     }
1145     p += i;
1146
1147     /* If it is a hit, check that the cipher is in the list */
1148     if (s->hit) {
1149         j = 0;
1150         id = s->session->cipher->id;
1151
1152 #ifdef CIPHER_DEBUG
1153         fprintf(stderr, "client sent %d ciphers\n",
1154                 sk_SSL_CIPHER_num(ciphers));
1155 #endif
1156         for (i = 0; i < sk_SSL_CIPHER_num(ciphers); i++) {
1157             c = sk_SSL_CIPHER_value(ciphers, i);
1158 #ifdef CIPHER_DEBUG
1159             fprintf(stderr, "client [%2d of %2d]:%s\n",
1160                     i, sk_SSL_CIPHER_num(ciphers), SSL_CIPHER_get_name(c));
1161 #endif
1162             if (c->id == id) {
1163                 j = 1;
1164                 break;
1165             }
1166         }
1167         /*
1168          * Disabled because it can be used in a ciphersuite downgrade attack:
1169          * CVE-2010-4180.
1170          */
1171 #if 0
1172         if (j == 0 && (s->options & SSL_OP_NETSCAPE_REUSE_CIPHER_CHANGE_BUG)
1173             && (sk_SSL_CIPHER_num(ciphers) == 1)) {
1174             /*
1175              * Special case as client bug workaround: the previously used
1176              * cipher may not be in the current list, the client instead
1177              * might be trying to continue using a cipher that before wasn't
1178              * chosen due to server preferences.  We'll have to reject the
1179              * connection if the cipher is not enabled, though.
1180              */
1181             c = sk_SSL_CIPHER_value(ciphers, 0);
1182             if (sk_SSL_CIPHER_find(SSL_get_ciphers(s), c) >= 0) {
1183                 s->session->cipher = c;
1184                 j = 1;
1185             }
1186         }
1187 #endif
1188         if (j == 0) {
1189             /*
1190              * we need to have the cipher in the cipher list if we are asked
1191              * to reuse it
1192              */
1193             al = SSL_AD_ILLEGAL_PARAMETER;
1194             SSLerr(SSL_F_SSL3_GET_CLIENT_HELLO,
1195                    SSL_R_REQUIRED_CIPHER_MISSING);
1196             goto f_err;
1197         }
1198     }
1199
1200     /* compression */
1201     i = *(p++);
1202     if ((p + i) > (d + n)) {
1203         /* not enough data */
1204         al = SSL_AD_DECODE_ERROR;
1205         SSLerr(SSL_F_SSL3_GET_CLIENT_HELLO, SSL_R_LENGTH_MISMATCH);
1206         goto f_err;
1207     }
1208 #ifndef OPENSSL_NO_COMP
1209     q = p;
1210 #endif
1211     for (j = 0; j < i; j++) {
1212         if (p[j] == 0)
1213             break;
1214     }
1215
1216     p += i;
1217     if (j >= i) {
1218         /* no compress */
1219         al = SSL_AD_DECODE_ERROR;
1220         SSLerr(SSL_F_SSL3_GET_CLIENT_HELLO, SSL_R_NO_COMPRESSION_SPECIFIED);
1221         goto f_err;
1222     }
1223 #ifndef OPENSSL_NO_TLSEXT
1224     /* TLS extensions */
1225     if (s->version >= SSL3_VERSION) {
1226         if (!ssl_parse_clienthello_tlsext(s, &p, d, n)) {
1227             SSLerr(SSL_F_SSL3_GET_CLIENT_HELLO, SSL_R_PARSE_TLSEXT);
1228             goto err;
1229         }
1230     }
1231
1232     /*
1233      * Check if we want to use external pre-shared secret for this handshake
1234      * for not reused session only. We need to generate server_random before
1235      * calling tls_session_secret_cb in order to allow SessionTicket
1236      * processing to use it in key derivation.
1237      */
1238     {
1239         unsigned char *pos;
1240         pos = s->s3->server_random;
1241         if (ssl_fill_hello_random(s, 1, pos, SSL3_RANDOM_SIZE) <= 0) {
1242             goto f_err;
1243         }
1244     }
1245
1246     if (!s->hit && s->version >= TLS1_VERSION && s->tls_session_secret_cb) {
1247         SSL_CIPHER *pref_cipher = NULL;
1248
1249         s->session->master_key_length = sizeof(s->session->master_key);
1250         if (s->tls_session_secret_cb(s, s->session->master_key,
1251                                      &s->session->master_key_length, ciphers,
1252                                      &pref_cipher,
1253                                      s->tls_session_secret_cb_arg)) {
1254             s->hit = 1;
1255             s->session->ciphers = ciphers;
1256             s->session->verify_result = X509_V_OK;
1257
1258             ciphers = NULL;
1259
1260             /* check if some cipher was preferred by call back */
1261             pref_cipher =
1262                 pref_cipher ? pref_cipher : ssl3_choose_cipher(s,
1263                                                                s->
1264                                                                session->ciphers,
1265                                                                SSL_get_ciphers
1266                                                                (s));
1267             if (pref_cipher == NULL) {
1268                 al = SSL_AD_HANDSHAKE_FAILURE;
1269                 SSLerr(SSL_F_SSL3_GET_CLIENT_HELLO, SSL_R_NO_SHARED_CIPHER);
1270                 goto f_err;
1271             }
1272
1273             s->session->cipher = pref_cipher;
1274             sk_SSL_CIPHER_free(s->cipher_list);
1275             s->cipher_list = sk_SSL_CIPHER_dup(s->session->ciphers);
1276             sk_SSL_CIPHER_free(s->cipher_list_by_id);
1277             s->cipher_list_by_id = sk_SSL_CIPHER_dup(s->session->ciphers);
1278         }
1279     }
1280 #endif
1281
1282     /*
1283      * Worst case, we will use the NULL compression, but if we have other
1284      * options, we will now look for them.  We have i-1 compression
1285      * algorithms from the client, starting at q.
1286      */
1287     s->s3->tmp.new_compression = NULL;
1288 #ifndef OPENSSL_NO_COMP
1289     /* This only happens if we have a cache hit */
1290     if (s->session->compress_meth != 0) {
1291         int m, comp_id = s->session->compress_meth;
1292         /* Perform sanity checks on resumed compression algorithm */
1293         /* Can't disable compression */
1294         if (!ssl_allow_compression(s)) {
1295             SSLerr(SSL_F_SSL3_GET_CLIENT_HELLO,
1296                    SSL_R_INCONSISTENT_COMPRESSION);
1297             goto f_err;
1298         }
1299         /* Look for resumed compression method */
1300         for (m = 0; m < sk_SSL_COMP_num(s->ctx->comp_methods); m++) {
1301             comp = sk_SSL_COMP_value(s->ctx->comp_methods, m);
1302             if (comp_id == comp->id) {
1303                 s->s3->tmp.new_compression = comp;
1304                 break;
1305             }
1306         }
1307         if (s->s3->tmp.new_compression == NULL) {
1308             SSLerr(SSL_F_SSL3_GET_CLIENT_HELLO,
1309                    SSL_R_INVALID_COMPRESSION_ALGORITHM);
1310             goto f_err;
1311         }
1312         /* Look for resumed method in compression list */
1313         for (m = 0; m < i; m++) {
1314             if (q[m] == comp_id)
1315                 break;
1316         }
1317         if (m >= i) {
1318             al = SSL_AD_ILLEGAL_PARAMETER;
1319             SSLerr(SSL_F_SSL3_GET_CLIENT_HELLO,
1320                    SSL_R_REQUIRED_COMPRESSSION_ALGORITHM_MISSING);
1321             goto f_err;
1322         }
1323     } else if (s->hit)
1324         comp = NULL;
1325     else if (ssl_allow_compression(s) && s->ctx->comp_methods) {
1326         /* See if we have a match */
1327         int m, nn, o, v, done = 0;
1328
1329         nn = sk_SSL_COMP_num(s->ctx->comp_methods);
1330         for (m = 0; m < nn; m++) {
1331             comp = sk_SSL_COMP_value(s->ctx->comp_methods, m);
1332             v = comp->id;
1333             for (o = 0; o < i; o++) {
1334                 if (v == q[o]) {
1335                     done = 1;
1336                     break;
1337                 }
1338             }
1339             if (done)
1340                 break;
1341         }
1342         if (done)
1343             s->s3->tmp.new_compression = comp;
1344         else
1345             comp = NULL;
1346     }
1347 #else
1348     /*
1349      * If compression is disabled we'd better not try to resume a session
1350      * using compression.
1351      */
1352     if (s->session->compress_meth != 0) {
1353         SSLerr(SSL_F_SSL3_GET_CLIENT_HELLO, SSL_R_INCONSISTENT_COMPRESSION);
1354         goto f_err;
1355     }
1356 #endif
1357
1358     /*
1359      * Given s->session->ciphers and SSL_get_ciphers, we must pick a cipher
1360      */
1361
1362     if (!s->hit) {
1363 #ifdef OPENSSL_NO_COMP
1364         s->session->compress_meth = 0;
1365 #else
1366         s->session->compress_meth = (comp == NULL) ? 0 : comp->id;
1367 #endif
1368         sk_SSL_CIPHER_free(s->session->ciphers);
1369         s->session->ciphers = ciphers;
1370         if (ciphers == NULL) {
1371             al = SSL_AD_INTERNAL_ERROR;
1372             SSLerr(SSL_F_SSL3_GET_CLIENT_HELLO, ERR_R_INTERNAL_ERROR);
1373             goto f_err;
1374         }
1375         ciphers = NULL;
1376         if (!tls1_set_server_sigalgs(s)) {
1377             SSLerr(SSL_F_SSL3_GET_CLIENT_HELLO, SSL_R_CLIENTHELLO_TLSEXT);
1378             goto err;
1379         }
1380         /* Let cert callback update server certificates if required */
1381  retry_cert:
1382         if (s->cert->cert_cb) {
1383             int rv = s->cert->cert_cb(s, s->cert->cert_cb_arg);
1384             if (rv == 0) {
1385                 al = SSL_AD_INTERNAL_ERROR;
1386                 SSLerr(SSL_F_SSL3_GET_CLIENT_HELLO, SSL_R_CERT_CB_ERROR);
1387                 goto f_err;
1388             }
1389             if (rv < 0) {
1390                 s->rwstate = SSL_X509_LOOKUP;
1391                 return -1;
1392             }
1393             s->rwstate = SSL_NOTHING;
1394         }
1395         c = ssl3_choose_cipher(s, s->session->ciphers, SSL_get_ciphers(s));
1396
1397         if (c == NULL) {
1398             al = SSL_AD_HANDSHAKE_FAILURE;
1399             SSLerr(SSL_F_SSL3_GET_CLIENT_HELLO, SSL_R_NO_SHARED_CIPHER);
1400             goto f_err;
1401         }
1402         s->s3->tmp.new_cipher = c;
1403         /* check whether we should disable session resumption */
1404         if (s->not_resumable_session_cb != NULL)
1405             s->session->not_resumable = s->not_resumable_session_cb(s,
1406                                                                     ((c->algorithm_mkey & (SSL_kDHE | SSL_kECDHE))
1407                                                                      != 0));
1408         if (s->session->not_resumable)
1409             /* do not send a session ticket */
1410             s->tlsext_ticket_expected = 0;
1411     } else {
1412         /* Session-id reuse */
1413         s->s3->tmp.new_cipher = s->session->cipher;
1414     }
1415
1416     if (!SSL_USE_SIGALGS(s) || !(s->verify_mode & SSL_VERIFY_PEER)) {
1417         if (!ssl3_digest_cached_records(s))
1418             goto f_err;
1419     }
1420
1421     /*-
1422      * we now have the following setup.
1423      * client_random
1424      * cipher_list          - our prefered list of ciphers
1425      * ciphers              - the clients prefered list of ciphers
1426      * compression          - basically ignored right now
1427      * ssl version is set   - sslv3
1428      * s->session           - The ssl session has been setup.
1429      * s->hit               - session reuse flag
1430      * s->s3->tmp.new_cipher- the new cipher to use.
1431      */
1432
1433     /* Handles TLS extensions that we couldn't check earlier */
1434     if (s->version >= SSL3_VERSION) {
1435         if (ssl_check_clienthello_tlsext_late(s) <= 0) {
1436             SSLerr(SSL_F_SSL3_GET_CLIENT_HELLO, SSL_R_CLIENTHELLO_TLSEXT);
1437             goto err;
1438         }
1439     }
1440
1441     if (ret < 0)
1442         ret = -ret;
1443     if (0) {
1444  f_err:
1445         ssl3_send_alert(s, SSL3_AL_FATAL, al);
1446  err:
1447         s->state = SSL_ST_ERR;
1448     }
1449
1450     sk_SSL_CIPHER_free(ciphers);
1451     return ret < 0 ? -1 : ret;
1452 }
1453
1454 int ssl3_send_server_hello(SSL *s)
1455 {
1456     unsigned char *buf;
1457     unsigned char *p, *d;
1458     int i, sl;
1459     int al = 0;
1460     unsigned long l;
1461
1462     if (s->state == SSL3_ST_SW_SRVR_HELLO_A) {
1463         buf = (unsigned char *)s->init_buf->data;
1464 #ifdef OPENSSL_NO_TLSEXT
1465         p = s->s3->server_random;
1466         if (ssl_fill_hello_random(s, 1, p, SSL3_RANDOM_SIZE) <= 0) {
1467             s->state = SSL_ST_ERR;
1468             return -1;
1469         }
1470 #endif
1471         /* Do the message type and length last */
1472         d = p = ssl_handshake_start(s);
1473
1474         *(p++) = s->version >> 8;
1475         *(p++) = s->version & 0xff;
1476
1477         /* Random stuff */
1478         memcpy(p, s->s3->server_random, SSL3_RANDOM_SIZE);
1479         p += SSL3_RANDOM_SIZE;
1480
1481         /*-
1482          * There are several cases for the session ID to send
1483          * back in the server hello:
1484          * - For session reuse from the session cache,
1485          *   we send back the old session ID.
1486          * - If stateless session reuse (using a session ticket)
1487          *   is successful, we send back the client's "session ID"
1488          *   (which doesn't actually identify the session).
1489          * - If it is a new session, we send back the new
1490          *   session ID.
1491          * - However, if we want the new session to be single-use,
1492          *   we send back a 0-length session ID.
1493          * s->hit is non-zero in either case of session reuse,
1494          * so the following won't overwrite an ID that we're supposed
1495          * to send back.
1496          */
1497         if (s->session->not_resumable ||
1498             (!(s->ctx->session_cache_mode & SSL_SESS_CACHE_SERVER)
1499              && !s->hit))
1500             s->session->session_id_length = 0;
1501
1502         sl = s->session->session_id_length;
1503         if (sl > (int)sizeof(s->session->session_id)) {
1504             SSLerr(SSL_F_SSL3_SEND_SERVER_HELLO, ERR_R_INTERNAL_ERROR);
1505             s->state = SSL_ST_ERR;
1506             return -1;
1507         }
1508         *(p++) = sl;
1509         memcpy(p, s->session->session_id, sl);
1510         p += sl;
1511
1512         /* put the cipher */
1513         i = ssl3_put_cipher_by_char(s->s3->tmp.new_cipher, p);
1514         p += i;
1515
1516         /* put the compression method */
1517 #ifdef OPENSSL_NO_COMP
1518         *(p++) = 0;
1519 #else
1520         if (s->s3->tmp.new_compression == NULL)
1521             *(p++) = 0;
1522         else
1523             *(p++) = s->s3->tmp.new_compression->id;
1524 #endif
1525 #ifndef OPENSSL_NO_TLSEXT
1526         if (ssl_prepare_serverhello_tlsext(s) <= 0) {
1527             SSLerr(SSL_F_SSL3_SEND_SERVER_HELLO, SSL_R_SERVERHELLO_TLSEXT);
1528             s->state = SSL_ST_ERR;
1529             return -1;
1530         }
1531         if ((p =
1532              ssl_add_serverhello_tlsext(s, p, buf + SSL3_RT_MAX_PLAIN_LENGTH,
1533                                         &al)) == NULL) {
1534             ssl3_send_alert(s, SSL3_AL_FATAL, al);
1535             SSLerr(SSL_F_SSL3_SEND_SERVER_HELLO, ERR_R_INTERNAL_ERROR);
1536             s->state = SSL_ST_ERR;
1537             return -1;
1538         }
1539 #endif
1540         /* do the header */
1541         l = (p - d);
1542         if (!ssl_set_handshake_header(s, SSL3_MT_SERVER_HELLO, l)) {
1543             SSLerr(SSL_F_SSL3_SEND_SERVER_HELLO, ERR_R_INTERNAL_ERROR);
1544             return -1;
1545         }
1546         s->state = SSL3_ST_SW_SRVR_HELLO_B;
1547     }
1548
1549     /* SSL3_ST_SW_SRVR_HELLO_B */
1550     return ssl_do_write(s);
1551 }
1552
1553 int ssl3_send_server_done(SSL *s)
1554 {
1555
1556     if (s->state == SSL3_ST_SW_SRVR_DONE_A) {
1557         if (!ssl_set_handshake_header(s, SSL3_MT_SERVER_DONE, 0)) {
1558             SSLerr(SSL_F_SSL3_SEND_SERVER_DONE, ERR_R_INTERNAL_ERROR);
1559             return -1;
1560         }
1561         s->state = SSL3_ST_SW_SRVR_DONE_B;
1562     }
1563
1564     /* SSL3_ST_SW_SRVR_DONE_B */
1565     return ssl_do_write(s);
1566 }
1567
1568 int ssl3_send_server_key_exchange(SSL *s)
1569 {
1570 #ifndef OPENSSL_NO_RSA
1571     unsigned char *q;
1572     int j, num;
1573     RSA *rsa;
1574     unsigned char md_buf[MD5_DIGEST_LENGTH + SHA_DIGEST_LENGTH];
1575     unsigned int u;
1576 #endif
1577 #ifndef OPENSSL_NO_DH
1578     DH *dh = NULL, *dhp;
1579 #endif
1580 #ifndef OPENSSL_NO_EC
1581     EC_KEY *ecdh = NULL, *ecdhp;
1582     unsigned char *encodedPoint = NULL;
1583     int encodedlen = 0;
1584     int curve_id = 0;
1585     BN_CTX *bn_ctx = NULL;
1586 #endif
1587     EVP_PKEY *pkey;
1588     const EVP_MD *md = NULL;
1589     unsigned char *p, *d;
1590     int al, i;
1591     unsigned long type;
1592     int n;
1593     CERT *cert;
1594     BIGNUM *r[4];
1595     int nr[4], kn;
1596     BUF_MEM *buf;
1597     EVP_MD_CTX md_ctx;
1598
1599     EVP_MD_CTX_init(&md_ctx);
1600     if (s->state == SSL3_ST_SW_KEY_EXCH_A) {
1601         type = s->s3->tmp.new_cipher->algorithm_mkey;
1602         cert = s->cert;
1603
1604         buf = s->init_buf;
1605
1606         r[0] = r[1] = r[2] = r[3] = NULL;
1607         n = 0;
1608 #ifndef OPENSSL_NO_RSA
1609         if (type & SSL_kRSA) {
1610             rsa = cert->rsa_tmp;
1611             if ((rsa == NULL) && (s->cert->rsa_tmp_cb != NULL)) {
1612                 rsa = s->cert->rsa_tmp_cb(s,
1613                                           SSL_C_IS_EXPORT(s->s3->
1614                                                           tmp.new_cipher),
1615                                           SSL_C_EXPORT_PKEYLENGTH(s->s3->
1616                                                                   tmp.new_cipher));
1617                 if (rsa == NULL) {
1618                     al = SSL_AD_HANDSHAKE_FAILURE;
1619                     SSLerr(SSL_F_SSL3_SEND_SERVER_KEY_EXCHANGE,
1620                            SSL_R_ERROR_GENERATING_TMP_RSA_KEY);
1621                     goto f_err;
1622                 }
1623                 RSA_up_ref(rsa);
1624                 cert->rsa_tmp = rsa;
1625             }
1626             if (rsa == NULL) {
1627                 al = SSL_AD_HANDSHAKE_FAILURE;
1628                 SSLerr(SSL_F_SSL3_SEND_SERVER_KEY_EXCHANGE,
1629                        SSL_R_MISSING_TMP_RSA_KEY);
1630                 goto f_err;
1631             }
1632             r[0] = rsa->n;
1633             r[1] = rsa->e;
1634             s->s3->tmp.use_rsa_tmp = 1;
1635         } else
1636 #endif
1637 #ifndef OPENSSL_NO_DH
1638         if (type & SSL_kDHE) {
1639             if (s->cert->dh_tmp_auto) {
1640                 dhp = ssl_get_auto_dh(s);
1641                 if (dhp == NULL) {
1642                     al = SSL_AD_INTERNAL_ERROR;
1643                     SSLerr(SSL_F_SSL3_SEND_SERVER_KEY_EXCHANGE,
1644                            ERR_R_INTERNAL_ERROR);
1645                     goto f_err;
1646                 }
1647             } else
1648                 dhp = cert->dh_tmp;
1649             if ((dhp == NULL) && (s->cert->dh_tmp_cb != NULL))
1650                 dhp = s->cert->dh_tmp_cb(s,
1651                                          SSL_C_IS_EXPORT(s->s3->
1652                                                          tmp.new_cipher),
1653                                          SSL_C_EXPORT_PKEYLENGTH(s->s3->
1654                                                                  tmp.new_cipher));
1655             if (dhp == NULL) {
1656                 al = SSL_AD_HANDSHAKE_FAILURE;
1657                 SSLerr(SSL_F_SSL3_SEND_SERVER_KEY_EXCHANGE,
1658                        SSL_R_MISSING_TMP_DH_KEY);
1659                 goto f_err;
1660             }
1661             if (!ssl_security(s, SSL_SECOP_TMP_DH,
1662                               DH_security_bits(dhp), 0, dhp)) {
1663                 al = SSL_AD_HANDSHAKE_FAILURE;
1664                 SSLerr(SSL_F_SSL3_SEND_SERVER_KEY_EXCHANGE,
1665                        SSL_R_DH_KEY_TOO_SMALL);
1666                 goto f_err;
1667             }
1668             if (s->s3->tmp.dh != NULL) {
1669                 SSLerr(SSL_F_SSL3_SEND_SERVER_KEY_EXCHANGE,
1670                        ERR_R_INTERNAL_ERROR);
1671                 goto err;
1672             }
1673
1674             if (s->cert->dh_tmp_auto)
1675                 dh = dhp;
1676             else if ((dh = DHparams_dup(dhp)) == NULL) {
1677                 SSLerr(SSL_F_SSL3_SEND_SERVER_KEY_EXCHANGE, ERR_R_DH_LIB);
1678                 goto err;
1679             }
1680
1681             s->s3->tmp.dh = dh;
1682             if ((dhp->pub_key == NULL ||
1683                  dhp->priv_key == NULL ||
1684                  (s->options & SSL_OP_SINGLE_DH_USE))) {
1685                 if (!DH_generate_key(dh)) {
1686                     SSLerr(SSL_F_SSL3_SEND_SERVER_KEY_EXCHANGE, ERR_R_DH_LIB);
1687                     goto err;
1688                 }
1689             } else {
1690                 dh->pub_key = BN_dup(dhp->pub_key);
1691                 dh->priv_key = BN_dup(dhp->priv_key);
1692                 if ((dh->pub_key == NULL) || (dh->priv_key == NULL)) {
1693                     SSLerr(SSL_F_SSL3_SEND_SERVER_KEY_EXCHANGE, ERR_R_DH_LIB);
1694                     goto err;
1695                 }
1696             }
1697             r[0] = dh->p;
1698             r[1] = dh->g;
1699             r[2] = dh->pub_key;
1700         } else
1701 #endif
1702 #ifndef OPENSSL_NO_EC
1703         if (type & SSL_kECDHE) {
1704             const EC_GROUP *group;
1705
1706             ecdhp = cert->ecdh_tmp;
1707             if (s->cert->ecdh_tmp_auto) {
1708                 /* Get NID of appropriate shared curve */
1709                 int nid = tls1_shared_curve(s, -2);
1710                 if (nid != NID_undef)
1711                     ecdhp = EC_KEY_new_by_curve_name(nid);
1712             } else if ((ecdhp == NULL) && s->cert->ecdh_tmp_cb) {
1713                 ecdhp = s->cert->ecdh_tmp_cb(s,
1714                                              SSL_C_IS_EXPORT(s->s3->
1715                                                              tmp.new_cipher),
1716                                              SSL_C_EXPORT_PKEYLENGTH(s->
1717                                                                      s3->tmp.new_cipher));
1718             }
1719             if (ecdhp == NULL) {
1720                 al = SSL_AD_HANDSHAKE_FAILURE;
1721                 SSLerr(SSL_F_SSL3_SEND_SERVER_KEY_EXCHANGE,
1722                        SSL_R_MISSING_TMP_ECDH_KEY);
1723                 goto f_err;
1724             }
1725
1726             if (s->s3->tmp.ecdh != NULL) {
1727                 SSLerr(SSL_F_SSL3_SEND_SERVER_KEY_EXCHANGE,
1728                        ERR_R_INTERNAL_ERROR);
1729                 goto err;
1730             }
1731
1732             /* Duplicate the ECDH structure. */
1733             if (ecdhp == NULL) {
1734                 SSLerr(SSL_F_SSL3_SEND_SERVER_KEY_EXCHANGE, ERR_R_ECDH_LIB);
1735                 goto err;
1736             }
1737             if (s->cert->ecdh_tmp_auto)
1738                 ecdh = ecdhp;
1739             else if ((ecdh = EC_KEY_dup(ecdhp)) == NULL) {
1740                 SSLerr(SSL_F_SSL3_SEND_SERVER_KEY_EXCHANGE, ERR_R_ECDH_LIB);
1741                 goto err;
1742             }
1743
1744             s->s3->tmp.ecdh = ecdh;
1745             if ((EC_KEY_get0_public_key(ecdh) == NULL) ||
1746                 (EC_KEY_get0_private_key(ecdh) == NULL) ||
1747                 (s->options & SSL_OP_SINGLE_ECDH_USE)) {
1748                 if (!EC_KEY_generate_key(ecdh)) {
1749                     SSLerr(SSL_F_SSL3_SEND_SERVER_KEY_EXCHANGE,
1750                            ERR_R_ECDH_LIB);
1751                     goto err;
1752                 }
1753             }
1754
1755             if (((group = EC_KEY_get0_group(ecdh)) == NULL) ||
1756                 (EC_KEY_get0_public_key(ecdh) == NULL) ||
1757                 (EC_KEY_get0_private_key(ecdh) == NULL)) {
1758                 SSLerr(SSL_F_SSL3_SEND_SERVER_KEY_EXCHANGE, ERR_R_ECDH_LIB);
1759                 goto err;
1760             }
1761
1762             if (SSL_C_IS_EXPORT(s->s3->tmp.new_cipher) &&
1763                 (EC_GROUP_get_degree(group) > 163)) {
1764                 SSLerr(SSL_F_SSL3_SEND_SERVER_KEY_EXCHANGE,
1765                        SSL_R_ECGROUP_TOO_LARGE_FOR_CIPHER);
1766                 goto err;
1767             }
1768
1769             /*
1770              * XXX: For now, we only support ephemeral ECDH keys over named
1771              * (not generic) curves. For supported named curves, curve_id is
1772              * non-zero.
1773              */
1774             if ((curve_id =
1775                  tls1_ec_nid2curve_id(EC_GROUP_get_curve_name(group)))
1776                 == 0) {
1777                 SSLerr(SSL_F_SSL3_SEND_SERVER_KEY_EXCHANGE,
1778                        SSL_R_UNSUPPORTED_ELLIPTIC_CURVE);
1779                 goto err;
1780             }
1781
1782             /*
1783              * Encode the public key. First check the size of encoding and
1784              * allocate memory accordingly.
1785              */
1786             encodedlen = EC_POINT_point2oct(group,
1787                                             EC_KEY_get0_public_key(ecdh),
1788                                             POINT_CONVERSION_UNCOMPRESSED,
1789                                             NULL, 0, NULL);
1790
1791             encodedPoint = (unsigned char *)
1792                 OPENSSL_malloc(encodedlen * sizeof(unsigned char));
1793             bn_ctx = BN_CTX_new();
1794             if ((encodedPoint == NULL) || (bn_ctx == NULL)) {
1795                 SSLerr(SSL_F_SSL3_SEND_SERVER_KEY_EXCHANGE,
1796                        ERR_R_MALLOC_FAILURE);
1797                 goto err;
1798             }
1799
1800             encodedlen = EC_POINT_point2oct(group,
1801                                             EC_KEY_get0_public_key(ecdh),
1802                                             POINT_CONVERSION_UNCOMPRESSED,
1803                                             encodedPoint, encodedlen, bn_ctx);
1804
1805             if (encodedlen == 0) {
1806                 SSLerr(SSL_F_SSL3_SEND_SERVER_KEY_EXCHANGE, ERR_R_ECDH_LIB);
1807                 goto err;
1808             }
1809
1810             BN_CTX_free(bn_ctx);
1811             bn_ctx = NULL;
1812
1813             /*
1814              * XXX: For now, we only support named (not generic) curves in
1815              * ECDH ephemeral key exchanges. In this situation, we need four
1816              * additional bytes to encode the entire ServerECDHParams
1817              * structure.
1818              */
1819             n = 4 + encodedlen;
1820
1821             /*
1822              * We'll generate the serverKeyExchange message explicitly so we
1823              * can set these to NULLs
1824              */
1825             r[0] = NULL;
1826             r[1] = NULL;
1827             r[2] = NULL;
1828             r[3] = NULL;
1829         } else
1830 #endif                          /* !OPENSSL_NO_EC */
1831 #ifndef OPENSSL_NO_PSK
1832         if (type & SSL_kPSK) {
1833             /*
1834              * reserve size for record length and PSK identity hint
1835              */
1836             n += 2 + strlen(s->ctx->psk_identity_hint);
1837         } else
1838 #endif                          /* !OPENSSL_NO_PSK */
1839 #ifndef OPENSSL_NO_SRP
1840         if (type & SSL_kSRP) {
1841             if ((s->srp_ctx.N == NULL) ||
1842                 (s->srp_ctx.g == NULL) ||
1843                 (s->srp_ctx.s == NULL) || (s->srp_ctx.B == NULL)) {
1844                 SSLerr(SSL_F_SSL3_SEND_SERVER_KEY_EXCHANGE,
1845                        SSL_R_MISSING_SRP_PARAM);
1846                 goto err;
1847             }
1848             r[0] = s->srp_ctx.N;
1849             r[1] = s->srp_ctx.g;
1850             r[2] = s->srp_ctx.s;
1851             r[3] = s->srp_ctx.B;
1852         } else
1853 #endif
1854         {
1855             al = SSL_AD_HANDSHAKE_FAILURE;
1856             SSLerr(SSL_F_SSL3_SEND_SERVER_KEY_EXCHANGE,
1857                    SSL_R_UNKNOWN_KEY_EXCHANGE_TYPE);
1858             goto f_err;
1859         }
1860         for (i = 0; i < 4 && r[i] != NULL; i++) {
1861             nr[i] = BN_num_bytes(r[i]);
1862 #ifndef OPENSSL_NO_SRP
1863             if ((i == 2) && (type & SSL_kSRP))
1864                 n += 1 + nr[i];
1865             else
1866 #endif
1867                 n += 2 + nr[i];
1868         }
1869
1870         if (!(s->s3->tmp.new_cipher->algorithm_auth & (SSL_aNULL | SSL_aSRP))
1871             && !(s->s3->tmp.new_cipher->algorithm_mkey & SSL_kPSK)) {
1872             if ((pkey = ssl_get_sign_pkey(s, s->s3->tmp.new_cipher, &md))
1873                 == NULL) {
1874                 al = SSL_AD_DECODE_ERROR;
1875                 goto f_err;
1876             }
1877             kn = EVP_PKEY_size(pkey);
1878         } else {
1879             pkey = NULL;
1880             kn = 0;
1881         }
1882
1883         if (!BUF_MEM_grow_clean(buf, n + SSL_HM_HEADER_LENGTH(s) + kn)) {
1884             SSLerr(SSL_F_SSL3_SEND_SERVER_KEY_EXCHANGE, ERR_LIB_BUF);
1885             goto err;
1886         }
1887         d = p = ssl_handshake_start(s);
1888
1889         for (i = 0; i < 4 && r[i] != NULL; i++) {
1890 #ifndef OPENSSL_NO_SRP
1891             if ((i == 2) && (type & SSL_kSRP)) {
1892                 *p = nr[i];
1893                 p++;
1894             } else
1895 #endif
1896                 s2n(nr[i], p);
1897             BN_bn2bin(r[i], p);
1898             p += nr[i];
1899         }
1900
1901 #ifndef OPENSSL_NO_EC
1902         if (type & SSL_kECDHE) {
1903             /*
1904              * XXX: For now, we only support named (not generic) curves. In
1905              * this situation, the serverKeyExchange message has: [1 byte
1906              * CurveType], [2 byte CurveName] [1 byte length of encoded
1907              * point], followed by the actual encoded point itself
1908              */
1909             *p = NAMED_CURVE_TYPE;
1910             p += 1;
1911             *p = 0;
1912             p += 1;
1913             *p = curve_id;
1914             p += 1;
1915             *p = encodedlen;
1916             p += 1;
1917             memcpy(p, encodedPoint, encodedlen);
1918             OPENSSL_free(encodedPoint);
1919             encodedPoint = NULL;
1920             p += encodedlen;
1921         }
1922 #endif
1923
1924 #ifndef OPENSSL_NO_PSK
1925         if (type & SSL_kPSK) {
1926             /* copy PSK identity hint */
1927             s2n(strlen(s->ctx->psk_identity_hint), p);
1928             strncpy((char *)p, s->ctx->psk_identity_hint,
1929                     strlen(s->ctx->psk_identity_hint));
1930             p += strlen(s->ctx->psk_identity_hint);
1931         }
1932 #endif
1933
1934         /* not anonymous */
1935         if (pkey != NULL) {
1936             /*
1937              * n is the length of the params, they start at &(d[4]) and p
1938              * points to the space at the end.
1939              */
1940 #ifndef OPENSSL_NO_RSA
1941             if (pkey->type == EVP_PKEY_RSA && !SSL_USE_SIGALGS(s)) {
1942                 q = md_buf;
1943                 j = 0;
1944                 for (num = 2; num > 0; num--) {
1945                     EVP_MD_CTX_set_flags(&md_ctx,
1946                                          EVP_MD_CTX_FLAG_NON_FIPS_ALLOW);
1947                     EVP_DigestInit_ex(&md_ctx, (num == 2)
1948                                       ? s->ctx->md5 : s->ctx->sha1, NULL);
1949                     EVP_DigestUpdate(&md_ctx, &(s->s3->client_random[0]),
1950                                      SSL3_RANDOM_SIZE);
1951                     EVP_DigestUpdate(&md_ctx, &(s->s3->server_random[0]),
1952                                      SSL3_RANDOM_SIZE);
1953                     EVP_DigestUpdate(&md_ctx, d, n);
1954                     EVP_DigestFinal_ex(&md_ctx, q, (unsigned int *)&i);
1955                     q += i;
1956                     j += i;
1957                 }
1958                 if (RSA_sign(NID_md5_sha1, md_buf, j,
1959                              &(p[2]), &u, pkey->pkey.rsa) <= 0) {
1960                     SSLerr(SSL_F_SSL3_SEND_SERVER_KEY_EXCHANGE, ERR_LIB_RSA);
1961                     goto err;
1962                 }
1963                 s2n(u, p);
1964                 n += u + 2;
1965             } else
1966 #endif
1967             if (md) {
1968                 /* send signature algorithm */
1969                 if (SSL_USE_SIGALGS(s)) {
1970                     if (!tls12_get_sigandhash(p, pkey, md)) {
1971                         /* Should never happen */
1972                         al = SSL_AD_INTERNAL_ERROR;
1973                         SSLerr(SSL_F_SSL3_SEND_SERVER_KEY_EXCHANGE,
1974                                ERR_R_INTERNAL_ERROR);
1975                         goto f_err;
1976                     }
1977                     p += 2;
1978                 }
1979 #ifdef SSL_DEBUG
1980                 fprintf(stderr, "Using hash %s\n", EVP_MD_name(md));
1981 #endif
1982                 EVP_SignInit_ex(&md_ctx, md, NULL);
1983                 EVP_SignUpdate(&md_ctx, &(s->s3->client_random[0]),
1984                                SSL3_RANDOM_SIZE);
1985                 EVP_SignUpdate(&md_ctx, &(s->s3->server_random[0]),
1986                                SSL3_RANDOM_SIZE);
1987                 EVP_SignUpdate(&md_ctx, d, n);
1988                 if (!EVP_SignFinal(&md_ctx, &(p[2]),
1989                                    (unsigned int *)&i, pkey)) {
1990                     SSLerr(SSL_F_SSL3_SEND_SERVER_KEY_EXCHANGE, ERR_LIB_EVP);
1991                     goto err;
1992                 }
1993                 s2n(i, p);
1994                 n += i + 2;
1995                 if (SSL_USE_SIGALGS(s))
1996                     n += 2;
1997             } else {
1998                 /* Is this error check actually needed? */
1999                 al = SSL_AD_HANDSHAKE_FAILURE;
2000                 SSLerr(SSL_F_SSL3_SEND_SERVER_KEY_EXCHANGE,
2001                        SSL_R_UNKNOWN_PKEY_TYPE);
2002                 goto f_err;
2003             }
2004         }
2005
2006         if (!ssl_set_handshake_header(s, SSL3_MT_SERVER_KEY_EXCHANGE, n)) {
2007             al = SSL_AD_HANDSHAKE_FAILURE;
2008             SSLerr(SSL_F_SSL3_SEND_SERVER_KEY_EXCHANGE, ERR_R_INTERNAL_ERROR);
2009             goto f_err;
2010         }
2011     }
2012
2013     s->state = SSL3_ST_SW_KEY_EXCH_B;
2014     EVP_MD_CTX_cleanup(&md_ctx);
2015     return ssl_do_write(s);
2016  f_err:
2017     ssl3_send_alert(s, SSL3_AL_FATAL, al);
2018  err:
2019 #ifndef OPENSSL_NO_EC
2020     OPENSSL_free(encodedPoint);
2021     BN_CTX_free(bn_ctx);
2022 #endif
2023     EVP_MD_CTX_cleanup(&md_ctx);
2024     s->state = SSL_ST_ERR;
2025     return (-1);
2026 }
2027
2028 int ssl3_send_certificate_request(SSL *s)
2029 {
2030     unsigned char *p, *d;
2031     int i, j, nl, off, n;
2032     STACK_OF(X509_NAME) *sk = NULL;
2033     X509_NAME *name;
2034     BUF_MEM *buf;
2035
2036     if (s->state == SSL3_ST_SW_CERT_REQ_A) {
2037         buf = s->init_buf;
2038
2039         d = p = ssl_handshake_start(s);
2040
2041         /* get the list of acceptable cert types */
2042         p++;
2043         n = ssl3_get_req_cert_type(s, p);
2044         d[0] = n;
2045         p += n;
2046         n++;
2047
2048         if (SSL_USE_SIGALGS(s)) {
2049             const unsigned char *psigs;
2050             unsigned char *etmp = p;
2051             nl = tls12_get_psigalgs(s, &psigs);
2052             /* Skip over length for now */
2053             p += 2;
2054             nl = tls12_copy_sigalgs(s, p, psigs, nl);
2055             /* Now fill in length */
2056             s2n(nl, etmp);
2057             p += nl;
2058             n += nl + 2;
2059         }
2060
2061         off = n;
2062         p += 2;
2063         n += 2;
2064
2065         sk = SSL_get_client_CA_list(s);
2066         nl = 0;
2067         if (sk != NULL) {
2068             for (i = 0; i < sk_X509_NAME_num(sk); i++) {
2069                 name = sk_X509_NAME_value(sk, i);
2070                 j = i2d_X509_NAME(name, NULL);
2071                 if (!BUF_MEM_grow_clean
2072                     (buf, SSL_HM_HEADER_LENGTH(s) + n + j + 2)) {
2073                     SSLerr(SSL_F_SSL3_SEND_CERTIFICATE_REQUEST,
2074                            ERR_R_BUF_LIB);
2075                     goto err;
2076                 }
2077                 p = ssl_handshake_start(s) + n;
2078                 s2n(j, p);
2079                 i2d_X509_NAME(name, &p);
2080                 n += 2 + j;
2081                 nl += 2 + j;
2082             }
2083         }
2084         /* else no CA names */
2085         p = ssl_handshake_start(s) + off;
2086         s2n(nl, p);
2087
2088         if (!ssl_set_handshake_header(s, SSL3_MT_CERTIFICATE_REQUEST, n)) {
2089             SSLerr(SSL_F_SSL3_SEND_CERTIFICATE_REQUEST, ERR_R_INTERNAL_ERROR);
2090             return -1;
2091         }
2092
2093         s->state = SSL3_ST_SW_CERT_REQ_B;
2094     }
2095
2096     /* SSL3_ST_SW_CERT_REQ_B */
2097     return ssl_do_write(s);
2098  err:
2099     s->state = SSL_ST_ERR;
2100     return (-1);
2101 }
2102
2103 int ssl3_get_client_key_exchange(SSL *s)
2104 {
2105     int i, al, ok;
2106     long n;
2107     unsigned long alg_k;
2108     unsigned char *p;
2109 #ifndef OPENSSL_NO_RSA
2110     RSA *rsa = NULL;
2111     EVP_PKEY *pkey = NULL;
2112 #endif
2113 #ifndef OPENSSL_NO_DH
2114     BIGNUM *pub = NULL;
2115     DH *dh_srvr, *dh_clnt = NULL;
2116 #endif
2117
2118 #ifndef OPENSSL_NO_EC
2119     EC_KEY *srvr_ecdh = NULL;
2120     EVP_PKEY *clnt_pub_pkey = NULL;
2121     EC_POINT *clnt_ecpoint = NULL;
2122     BN_CTX *bn_ctx = NULL;
2123 #endif
2124
2125     n = s->method->ssl_get_message(s,
2126                                    SSL3_ST_SR_KEY_EXCH_A,
2127                                    SSL3_ST_SR_KEY_EXCH_B,
2128                                    SSL3_MT_CLIENT_KEY_EXCHANGE, 2048, &ok);
2129
2130     if (!ok)
2131         return ((int)n);
2132     p = (unsigned char *)s->init_msg;
2133
2134     alg_k = s->s3->tmp.new_cipher->algorithm_mkey;
2135
2136 #ifndef OPENSSL_NO_RSA
2137     if (alg_k & SSL_kRSA) {
2138         unsigned char rand_premaster_secret[SSL_MAX_MASTER_KEY_LENGTH];
2139         int decrypt_len;
2140         unsigned char decrypt_good, version_good;
2141         size_t j;
2142
2143         /* FIX THIS UP EAY EAY EAY EAY */
2144         if (s->s3->tmp.use_rsa_tmp) {
2145             if ((s->cert != NULL) && (s->cert->rsa_tmp != NULL))
2146                 rsa = s->cert->rsa_tmp;
2147             /*
2148              * Don't do a callback because rsa_tmp should be sent already
2149              */
2150             if (rsa == NULL) {
2151                 al = SSL_AD_HANDSHAKE_FAILURE;
2152                 SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,
2153                        SSL_R_MISSING_TMP_RSA_PKEY);
2154                 goto f_err;
2155
2156             }
2157         } else {
2158             pkey = s->cert->pkeys[SSL_PKEY_RSA_ENC].privatekey;
2159             if ((pkey == NULL) ||
2160                 (pkey->type != EVP_PKEY_RSA) || (pkey->pkey.rsa == NULL)) {
2161                 al = SSL_AD_HANDSHAKE_FAILURE;
2162                 SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,
2163                        SSL_R_MISSING_RSA_CERTIFICATE);
2164                 goto f_err;
2165             }
2166             rsa = pkey->pkey.rsa;
2167         }
2168
2169         /* TLS and [incidentally] DTLS{0xFEFF} */
2170         if (s->version > SSL3_VERSION && s->version != DTLS1_BAD_VER) {
2171             n2s(p, i);
2172             if (n != i + 2) {
2173                 if (!(s->options & SSL_OP_TLS_D5_BUG)) {
2174                     al = SSL_AD_DECODE_ERROR;
2175                     SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,
2176                            SSL_R_TLS_RSA_ENCRYPTED_VALUE_LENGTH_IS_WRONG);
2177                     goto f_err;
2178                 } else
2179                     p -= 2;
2180             } else
2181                 n = i;
2182         }
2183
2184         /*
2185          * Reject overly short RSA ciphertext because we want to be sure
2186          * that the buffer size makes it safe to iterate over the entire
2187          * size of a premaster secret (SSL_MAX_MASTER_KEY_LENGTH). The
2188          * actual expected size is larger due to RSA padding, but the
2189          * bound is sufficient to be safe.
2190          */
2191         if (n < SSL_MAX_MASTER_KEY_LENGTH) {
2192             al = SSL_AD_DECRYPT_ERROR;
2193             SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,
2194                    SSL_R_TLS_RSA_ENCRYPTED_VALUE_LENGTH_IS_WRONG);
2195             goto f_err;
2196         }
2197
2198         /*
2199          * We must not leak whether a decryption failure occurs because of
2200          * Bleichenbacher's attack on PKCS #1 v1.5 RSA padding (see RFC 2246,
2201          * section 7.4.7.1). The code follows that advice of the TLS RFC and
2202          * generates a random premaster secret for the case that the decrypt
2203          * fails. See https://tools.ietf.org/html/rfc5246#section-7.4.7.1
2204          */
2205
2206         if (RAND_bytes(rand_premaster_secret,
2207                               sizeof(rand_premaster_secret)) <= 0)
2208             goto err;
2209         decrypt_len =
2210             RSA_private_decrypt((int)n, p, p, rsa, RSA_PKCS1_PADDING);
2211         ERR_clear_error();
2212
2213         /*
2214          * decrypt_len should be SSL_MAX_MASTER_KEY_LENGTH. decrypt_good will
2215          * be 0xff if so and zero otherwise.
2216          */
2217         decrypt_good =
2218             constant_time_eq_int_8(decrypt_len, SSL_MAX_MASTER_KEY_LENGTH);
2219
2220         /*
2221          * If the version in the decrypted pre-master secret is correct then
2222          * version_good will be 0xff, otherwise it'll be zero. The
2223          * Klima-Pokorny-Rosa extension of Bleichenbacher's attack
2224          * (http://eprint.iacr.org/2003/052/) exploits the version number
2225          * check as a "bad version oracle". Thus version checks are done in
2226          * constant time and are treated like any other decryption error.
2227          */
2228         version_good =
2229             constant_time_eq_8(p[0], (unsigned)(s->client_version >> 8));
2230         version_good &=
2231             constant_time_eq_8(p[1], (unsigned)(s->client_version & 0xff));
2232
2233         /*
2234          * The premaster secret must contain the same version number as the
2235          * ClientHello to detect version rollback attacks (strangely, the
2236          * protocol does not offer such protection for DH ciphersuites).
2237          * However, buggy clients exist that send the negotiated protocol
2238          * version instead if the server does not support the requested
2239          * protocol version. If SSL_OP_TLS_ROLLBACK_BUG is set, tolerate such
2240          * clients.
2241          */
2242         if (s->options & SSL_OP_TLS_ROLLBACK_BUG) {
2243             unsigned char workaround_good;
2244             workaround_good =
2245                 constant_time_eq_8(p[0], (unsigned)(s->version >> 8));
2246             workaround_good &=
2247                 constant_time_eq_8(p[1], (unsigned)(s->version & 0xff));
2248             version_good |= workaround_good;
2249         }
2250
2251         /*
2252          * Both decryption and version must be good for decrypt_good to
2253          * remain non-zero (0xff).
2254          */
2255         decrypt_good &= version_good;
2256
2257         /*
2258          * Now copy rand_premaster_secret over from p using
2259          * decrypt_good_mask. If decryption failed, then p does not
2260          * contain valid plaintext, however, a check above guarantees
2261          * it is still sufficiently large to read from.
2262          */
2263         for (j = 0; j < sizeof(rand_premaster_secret); j++) {
2264             p[j] = constant_time_select_8(decrypt_good, p[j],
2265                                           rand_premaster_secret[j]);
2266         }
2267
2268         s->session->master_key_length =
2269             s->method->ssl3_enc->generate_master_secret(s,
2270                                                         s->
2271                                                         session->master_key,
2272                                                         p,
2273                                                         sizeof
2274                                                         (rand_premaster_secret));
2275         OPENSSL_cleanse(p, sizeof(rand_premaster_secret));
2276         if (s->session->master_key_length < 0) {
2277             al = SSL_AD_INTERNAL_ERROR;
2278             SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE, ERR_R_INTERNAL_ERROR);
2279             goto f_err;
2280         }
2281     } else
2282 #endif
2283 #ifndef OPENSSL_NO_DH
2284     if (alg_k & (SSL_kDHE | SSL_kDHr | SSL_kDHd)) {
2285         int idx = -1;
2286         EVP_PKEY *skey = NULL;
2287         if (n > 1) {
2288             n2s(p, i);
2289         } else {
2290             if (alg_k & SSL_kDHE) {
2291                 al = SSL_AD_HANDSHAKE_FAILURE;
2292                 SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,
2293                        SSL_R_DH_PUBLIC_VALUE_LENGTH_IS_WRONG);
2294                 goto f_err;
2295             }
2296             i = 0;
2297         }
2298         if (n && n != i + 2) {
2299             if (!(s->options & SSL_OP_SSLEAY_080_CLIENT_DH_BUG)) {
2300                 SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,
2301                        SSL_R_DH_PUBLIC_VALUE_LENGTH_IS_WRONG);
2302                 goto err;
2303             } else {
2304                 p -= 2;
2305                 i = (int)n;
2306             }
2307         }
2308         if (alg_k & SSL_kDHr)
2309             idx = SSL_PKEY_DH_RSA;
2310         else if (alg_k & SSL_kDHd)
2311             idx = SSL_PKEY_DH_DSA;
2312         if (idx >= 0) {
2313             skey = s->cert->pkeys[idx].privatekey;
2314             if ((skey == NULL) ||
2315                 (skey->type != EVP_PKEY_DH) || (skey->pkey.dh == NULL)) {
2316                 al = SSL_AD_HANDSHAKE_FAILURE;
2317                 SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,
2318                        SSL_R_MISSING_RSA_CERTIFICATE);
2319                 goto f_err;
2320             }
2321             dh_srvr = skey->pkey.dh;
2322         } else if (s->s3->tmp.dh == NULL) {
2323             al = SSL_AD_HANDSHAKE_FAILURE;
2324             SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,
2325                    SSL_R_MISSING_TMP_DH_KEY);
2326             goto f_err;
2327         } else
2328             dh_srvr = s->s3->tmp.dh;
2329
2330         if (n == 0L) {
2331             /* Get pubkey from cert */
2332             EVP_PKEY *clkey = X509_get_pubkey(s->session->peer);
2333             if (clkey) {
2334                 if (EVP_PKEY_cmp_parameters(clkey, skey) == 1)
2335                     dh_clnt = EVP_PKEY_get1_DH(clkey);
2336             }
2337             if (dh_clnt == NULL) {
2338                 al = SSL_AD_HANDSHAKE_FAILURE;
2339                 SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,
2340                        SSL_R_MISSING_TMP_DH_KEY);
2341                 goto f_err;
2342             }
2343             EVP_PKEY_free(clkey);
2344             pub = dh_clnt->pub_key;
2345         } else
2346             pub = BN_bin2bn(p, i, NULL);
2347         if (pub == NULL) {
2348             SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE, SSL_R_BN_LIB);
2349             goto err;
2350         }
2351
2352         i = DH_compute_key(p, pub, dh_srvr);
2353
2354         if (i <= 0) {
2355             SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE, ERR_R_DH_LIB);
2356             BN_clear_free(pub);
2357             goto err;
2358         }
2359
2360         DH_free(s->s3->tmp.dh);
2361         s->s3->tmp.dh = NULL;
2362         if (dh_clnt)
2363             DH_free(dh_clnt);
2364         else
2365             BN_clear_free(pub);
2366         pub = NULL;
2367         s->session->master_key_length =
2368             s->method->ssl3_enc->generate_master_secret(s,
2369                                                         s->
2370                                                         session->master_key,
2371                                                         p, i);
2372         OPENSSL_cleanse(p, i);
2373         if (s->session->master_key_length < 0) {
2374             al = SSL_AD_INTERNAL_ERROR;
2375             SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE, ERR_R_INTERNAL_ERROR);
2376             goto f_err;
2377         }
2378         if (dh_clnt)
2379             return 2;
2380     } else
2381 #endif
2382
2383 #ifndef OPENSSL_NO_EC
2384     if (alg_k & (SSL_kECDHE | SSL_kECDHr | SSL_kECDHe)) {
2385         int ret = 1;
2386         int field_size = 0;
2387         const EC_KEY *tkey;
2388         const EC_GROUP *group;
2389         const BIGNUM *priv_key;
2390
2391         /* initialize structures for server's ECDH key pair */
2392         if ((srvr_ecdh = EC_KEY_new()) == NULL) {
2393             SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE, ERR_R_MALLOC_FAILURE);
2394             goto err;
2395         }
2396
2397         /* Let's get server private key and group information */
2398         if (alg_k & (SSL_kECDHr | SSL_kECDHe)) {
2399             /* use the certificate */
2400             tkey = s->cert->pkeys[SSL_PKEY_ECC].privatekey->pkey.ec;
2401         } else {
2402             /*
2403              * use the ephermeral values we saved when generating the
2404              * ServerKeyExchange msg.
2405              */
2406             tkey = s->s3->tmp.ecdh;
2407         }
2408
2409         group = EC_KEY_get0_group(tkey);
2410         priv_key = EC_KEY_get0_private_key(tkey);
2411
2412         if (!EC_KEY_set_group(srvr_ecdh, group) ||
2413             !EC_KEY_set_private_key(srvr_ecdh, priv_key)) {
2414             SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE, ERR_R_EC_LIB);
2415             goto err;
2416         }
2417
2418         /* Let's get client's public key */
2419         if ((clnt_ecpoint = EC_POINT_new(group)) == NULL) {
2420             SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE, ERR_R_MALLOC_FAILURE);
2421             goto err;
2422         }
2423
2424         if (n == 0L) {
2425             /* Client Publickey was in Client Certificate */
2426
2427             if (alg_k & SSL_kECDHE) {
2428                 al = SSL_AD_HANDSHAKE_FAILURE;
2429                 SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,
2430                        SSL_R_MISSING_TMP_ECDH_KEY);
2431                 goto f_err;
2432             }
2433             if (((clnt_pub_pkey = X509_get_pubkey(s->session->peer))
2434                  == NULL) || (clnt_pub_pkey->type != EVP_PKEY_EC)) {
2435                 /*
2436                  * XXX: For now, we do not support client authentication
2437                  * using ECDH certificates so this branch (n == 0L) of the
2438                  * code is never executed. When that support is added, we
2439                  * ought to ensure the key received in the certificate is
2440                  * authorized for key agreement. ECDH_compute_key implicitly
2441                  * checks that the two ECDH shares are for the same group.
2442                  */
2443                 al = SSL_AD_HANDSHAKE_FAILURE;
2444                 SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,
2445                        SSL_R_UNABLE_TO_DECODE_ECDH_CERTS);
2446                 goto f_err;
2447             }
2448
2449             if (EC_POINT_copy(clnt_ecpoint,
2450                               EC_KEY_get0_public_key(clnt_pub_pkey->
2451                                                      pkey.ec)) == 0) {
2452                 SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE, ERR_R_EC_LIB);
2453                 goto err;
2454             }
2455             ret = 2;            /* Skip certificate verify processing */
2456         } else {
2457             /*
2458              * Get client's public key from encoded point in the
2459              * ClientKeyExchange message.
2460              */
2461             if ((bn_ctx = BN_CTX_new()) == NULL) {
2462                 SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,
2463                        ERR_R_MALLOC_FAILURE);
2464                 goto err;
2465             }
2466
2467             /* Get encoded point length */
2468             i = *p;
2469             p += 1;
2470             if (n != 1 + i) {
2471                 SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE, ERR_R_EC_LIB);
2472                 goto err;
2473             }
2474             if (EC_POINT_oct2point(group, clnt_ecpoint, p, i, bn_ctx) == 0) {
2475                 SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE, ERR_R_EC_LIB);
2476                 goto err;
2477             }
2478             /*
2479              * p is pointing to somewhere in the buffer currently, so set it
2480              * to the start
2481              */
2482             p = (unsigned char *)s->init_buf->data;
2483         }
2484
2485         /* Compute the shared pre-master secret */
2486         field_size = EC_GROUP_get_degree(group);
2487         if (field_size <= 0) {
2488             SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE, ERR_R_ECDH_LIB);
2489             goto err;
2490         }
2491         i = ECDH_compute_key(p, (field_size + 7) / 8, clnt_ecpoint, srvr_ecdh,
2492                              NULL);
2493         if (i <= 0) {
2494             SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE, ERR_R_ECDH_LIB);
2495             goto err;
2496         }
2497
2498         EVP_PKEY_free(clnt_pub_pkey);
2499         EC_POINT_free(clnt_ecpoint);
2500         EC_KEY_free(srvr_ecdh);
2501         BN_CTX_free(bn_ctx);
2502         EC_KEY_free(s->s3->tmp.ecdh);
2503         s->s3->tmp.ecdh = NULL;
2504
2505         /* Compute the master secret */
2506         s->session->master_key_length =
2507             s->method->ssl3_enc->generate_master_secret(s,
2508                                                         s->
2509                                                         session->master_key,
2510                                                         p, i);
2511
2512         OPENSSL_cleanse(p, i);
2513         if (s->session->master_key_length < 0) {
2514             al = SSL_AD_INTERNAL_ERROR;
2515             SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE, ERR_R_INTERNAL_ERROR);
2516             goto f_err;
2517         }
2518         return (ret);
2519     } else
2520 #endif
2521 #ifndef OPENSSL_NO_PSK
2522     if (alg_k & SSL_kPSK) {
2523         unsigned char *t = NULL;
2524         unsigned char psk_or_pre_ms[PSK_MAX_PSK_LEN * 2 + 4];
2525         unsigned int pre_ms_len = 0, psk_len = 0;
2526         int psk_err = 1;
2527         char tmp_id[PSK_MAX_IDENTITY_LEN + 1];
2528
2529         al = SSL_AD_HANDSHAKE_FAILURE;
2530
2531         n2s(p, i);
2532         if (n != i + 2) {
2533             SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE, SSL_R_LENGTH_MISMATCH);
2534             goto psk_err;
2535         }
2536         if (i > PSK_MAX_IDENTITY_LEN) {
2537             SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,
2538                    SSL_R_DATA_LENGTH_TOO_LONG);
2539             goto psk_err;
2540         }
2541         if (s->psk_server_callback == NULL) {
2542             SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,
2543                    SSL_R_PSK_NO_SERVER_CB);
2544             goto psk_err;
2545         }
2546
2547         /*
2548          * Create guaranteed NULL-terminated identity string for the callback
2549          */
2550         memcpy(tmp_id, p, i);
2551         memset(tmp_id + i, 0, PSK_MAX_IDENTITY_LEN + 1 - i);
2552         psk_len = s->psk_server_callback(s, tmp_id,
2553                                          psk_or_pre_ms,
2554                                          sizeof(psk_or_pre_ms));
2555         OPENSSL_cleanse(tmp_id, PSK_MAX_IDENTITY_LEN + 1);
2556
2557         if (psk_len > PSK_MAX_PSK_LEN) {
2558             SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE, ERR_R_INTERNAL_ERROR);
2559             goto psk_err;
2560         } else if (psk_len == 0) {
2561             /*
2562              * PSK related to the given identity not found
2563              */
2564             SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,
2565                    SSL_R_PSK_IDENTITY_NOT_FOUND);
2566             al = SSL_AD_UNKNOWN_PSK_IDENTITY;
2567             goto psk_err;
2568         }
2569
2570         /* create PSK pre_master_secret */
2571         pre_ms_len = 2 + psk_len + 2 + psk_len;
2572         t = psk_or_pre_ms;
2573         memmove(psk_or_pre_ms + psk_len + 4, psk_or_pre_ms, psk_len);
2574         s2n(psk_len, t);
2575         memset(t, 0, psk_len);
2576         t += psk_len;
2577         s2n(psk_len, t);
2578
2579         OPENSSL_free(s->session->psk_identity);
2580         s->session->psk_identity = BUF_strdup((char *)p);
2581         if (s->session->psk_identity == NULL) {
2582             SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE, ERR_R_MALLOC_FAILURE);
2583             goto psk_err;
2584         }
2585
2586         OPENSSL_free(s->session->psk_identity_hint);
2587         s->session->psk_identity_hint = BUF_strdup(s->ctx->psk_identity_hint);
2588         if (s->ctx->psk_identity_hint != NULL &&
2589             s->session->psk_identity_hint == NULL) {
2590             SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE, ERR_R_MALLOC_FAILURE);
2591             goto psk_err;
2592         }
2593
2594         s->session->master_key_length =
2595             s->method->ssl3_enc->generate_master_secret(s,
2596                                                         s->
2597                                                         session->master_key,
2598                                                         psk_or_pre_ms,
2599                                                         pre_ms_len);
2600         if (s->session->master_key_length < 0) {
2601             al = SSL_AD_INTERNAL_ERROR;
2602             SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE, ERR_R_INTERNAL_ERROR);
2603             goto psk_err;
2604         }
2605         psk_err = 0;
2606  psk_err:
2607         OPENSSL_cleanse(psk_or_pre_ms, sizeof(psk_or_pre_ms));
2608         if (psk_err != 0)
2609             goto f_err;
2610     } else
2611 #endif
2612 #ifndef OPENSSL_NO_SRP
2613     if (alg_k & SSL_kSRP) {
2614         int param_len;
2615
2616         n2s(p, i);
2617         param_len = i + 2;
2618         if (param_len > n) {
2619             al = SSL_AD_DECODE_ERROR;
2620             SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,
2621                    SSL_R_BAD_SRP_A_LENGTH);
2622             goto f_err;
2623         }
2624         if ((s->srp_ctx.A = BN_bin2bn(p, i, NULL)) == NULL) {
2625             SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE, ERR_R_BN_LIB);
2626             goto err;
2627         }
2628         if (BN_ucmp(s->srp_ctx.A, s->srp_ctx.N) >= 0
2629             || BN_is_zero(s->srp_ctx.A)) {
2630             al = SSL_AD_ILLEGAL_PARAMETER;
2631             SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,
2632                    SSL_R_BAD_SRP_PARAMETERS);
2633             goto f_err;
2634         }
2635         OPENSSL_free(s->session->srp_username);
2636         s->session->srp_username = BUF_strdup(s->srp_ctx.login);
2637         if (s->session->srp_username == NULL) {
2638             SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE, ERR_R_MALLOC_FAILURE);
2639             goto err;
2640         }
2641
2642         if ((s->session->master_key_length =
2643              SRP_generate_server_master_secret(s,
2644                                                s->session->master_key)) < 0) {
2645             SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE, ERR_R_INTERNAL_ERROR);
2646             goto err;
2647         }
2648
2649         p += i;
2650     } else
2651 #endif                          /* OPENSSL_NO_SRP */
2652     if (alg_k & SSL_kGOST) {
2653         int ret = 0;
2654         EVP_PKEY_CTX *pkey_ctx;
2655         EVP_PKEY *client_pub_pkey = NULL, *pk = NULL;
2656         unsigned char premaster_secret[32], *start;
2657         size_t outlen = 32, inlen;
2658         unsigned long alg_a;
2659         int Ttag, Tclass;
2660         long Tlen;
2661
2662         /* Get our certificate private key */
2663         alg_a = s->s3->tmp.new_cipher->algorithm_auth;
2664         if (alg_a & SSL_aGOST94)
2665             pk = s->cert->pkeys[SSL_PKEY_GOST94].privatekey;
2666         else if (alg_a & SSL_aGOST01)
2667             pk = s->cert->pkeys[SSL_PKEY_GOST01].privatekey;
2668
2669         pkey_ctx = EVP_PKEY_CTX_new(pk, NULL);
2670         EVP_PKEY_decrypt_init(pkey_ctx);
2671         /*
2672          * If client certificate is present and is of the same type, maybe
2673          * use it for key exchange.  Don't mind errors from
2674          * EVP_PKEY_derive_set_peer, because it is completely valid to use a
2675          * client certificate for authorization only.
2676          */
2677         client_pub_pkey = X509_get_pubkey(s->session->peer);
2678         if (client_pub_pkey) {
2679             if (EVP_PKEY_derive_set_peer(pkey_ctx, client_pub_pkey) <= 0)
2680                 ERR_clear_error();
2681         }
2682         /* Decrypt session key */
2683         if (ASN1_get_object
2684             ((const unsigned char **)&p, &Tlen, &Ttag, &Tclass,
2685              n) != V_ASN1_CONSTRUCTED || Ttag != V_ASN1_SEQUENCE
2686             || Tclass != V_ASN1_UNIVERSAL) {
2687             SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,
2688                    SSL_R_DECRYPTION_FAILED);
2689             goto gerr;
2690         }
2691         start = p;
2692         inlen = Tlen;
2693         if (EVP_PKEY_decrypt
2694             (pkey_ctx, premaster_secret, &outlen, start, inlen) <= 0) {
2695             SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,
2696                    SSL_R_DECRYPTION_FAILED);
2697             goto gerr;
2698         }
2699         /* Generate master secret */
2700         s->session->master_key_length =
2701             s->method->ssl3_enc->generate_master_secret(s,
2702                                                         s->
2703                                                         session->master_key,
2704                                                         premaster_secret, 32);
2705         if (s->session->master_key_length < 0) {
2706             al = SSL_AD_INTERNAL_ERROR;
2707             SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE, ERR_R_INTERNAL_ERROR);
2708             goto f_err;
2709         }
2710         /* Check if pubkey from client certificate was used */
2711         if (EVP_PKEY_CTX_ctrl
2712             (pkey_ctx, -1, -1, EVP_PKEY_CTRL_PEER_KEY, 2, NULL) > 0)
2713             ret = 2;
2714         else
2715             ret = 1;
2716  gerr:
2717         EVP_PKEY_free(client_pub_pkey);
2718         EVP_PKEY_CTX_free(pkey_ctx);
2719         if (ret)
2720             return ret;
2721         goto err;
2722     } else {
2723         al = SSL_AD_HANDSHAKE_FAILURE;
2724         SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE, SSL_R_UNKNOWN_CIPHER_TYPE);
2725         goto f_err;
2726     }
2727
2728     return (1);
2729  f_err:
2730     ssl3_send_alert(s, SSL3_AL_FATAL, al);
2731 #if !defined(OPENSSL_NO_DH) || !defined(OPENSSL_NO_RSA) || !defined(OPENSSL_NO_EC) || defined(OPENSSL_NO_SRP)
2732  err:
2733 #endif
2734 #ifndef OPENSSL_NO_EC
2735     EVP_PKEY_free(clnt_pub_pkey);
2736     EC_POINT_free(clnt_ecpoint);
2737     EC_KEY_free(srvr_ecdh);
2738     BN_CTX_free(bn_ctx);
2739 #endif
2740     s->state = SSL_ST_ERR;
2741     return (-1);
2742 }
2743
2744 int ssl3_get_cert_verify(SSL *s)
2745 {
2746     EVP_PKEY *pkey = NULL;
2747     unsigned char *p;
2748     int al, ok, ret = 0;
2749     long n;
2750     int type = 0, i, j;
2751     X509 *peer;
2752     const EVP_MD *md = NULL;
2753     EVP_MD_CTX mctx;
2754     EVP_MD_CTX_init(&mctx);
2755
2756     /*
2757      * We should only process a CertificateVerify message if we have received
2758      * a Certificate from the client. If so then |s->session->peer| will be non
2759      * NULL. In some instances a CertificateVerify message is not required even
2760      * if the peer has sent a Certificate (e.g. such as in the case of static
2761      * DH). In that case the ClientKeyExchange processing will skip the
2762      * CertificateVerify state so we should not arrive here.
2763      */
2764     if (s->session->peer == NULL) {
2765         ret = 1;
2766         goto end;
2767     }
2768
2769     n = s->method->ssl_get_message(s,
2770                                    SSL3_ST_SR_CERT_VRFY_A,
2771                                    SSL3_ST_SR_CERT_VRFY_B,
2772                                    SSL3_MT_CERTIFICATE_VERIFY,
2773                                    SSL3_RT_MAX_PLAIN_LENGTH, &ok);
2774
2775     if (!ok)
2776         return ((int)n);
2777
2778     peer = s->session->peer;
2779     pkey = X509_get_pubkey(peer);
2780     type = X509_certificate_type(peer, pkey);
2781
2782     if (!(type & EVP_PKT_SIGN)) {
2783         SSLerr(SSL_F_SSL3_GET_CERT_VERIFY,
2784                SSL_R_SIGNATURE_FOR_NON_SIGNING_CERTIFICATE);
2785         al = SSL_AD_ILLEGAL_PARAMETER;
2786         goto f_err;
2787     }
2788
2789     /* we now have a signature that we need to verify */
2790     p = (unsigned char *)s->init_msg;
2791     /* Check for broken implementations of GOST ciphersuites */
2792     /*
2793      * If key is GOST and n is exactly 64, it is bare signature without
2794      * length field
2795      */
2796     if (n == 64 && (pkey->type == NID_id_GostR3410_94 ||
2797                     pkey->type == NID_id_GostR3410_2001)) {
2798         i = 64;
2799     } else {
2800         if (SSL_USE_SIGALGS(s)) {
2801             int rv = tls12_check_peer_sigalg(&md, s, p, pkey);
2802             if (rv == -1) {
2803                 al = SSL_AD_INTERNAL_ERROR;
2804                 goto f_err;
2805             } else if (rv == 0) {
2806                 al = SSL_AD_DECODE_ERROR;
2807                 goto f_err;
2808             }
2809 #ifdef SSL_DEBUG
2810             fprintf(stderr, "USING TLSv1.2 HASH %s\n", EVP_MD_name(md));
2811 #endif
2812             p += 2;
2813             n -= 2;
2814         }
2815         n2s(p, i);
2816         n -= 2;
2817         if (i > n) {
2818             SSLerr(SSL_F_SSL3_GET_CERT_VERIFY, SSL_R_LENGTH_MISMATCH);
2819             al = SSL_AD_DECODE_ERROR;
2820             goto f_err;
2821         }
2822     }
2823     j = EVP_PKEY_size(pkey);
2824     if ((i > j) || (n > j) || (n <= 0)) {
2825         SSLerr(SSL_F_SSL3_GET_CERT_VERIFY, SSL_R_WRONG_SIGNATURE_SIZE);
2826         al = SSL_AD_DECODE_ERROR;
2827         goto f_err;
2828     }
2829
2830     if (SSL_USE_SIGALGS(s)) {
2831         long hdatalen = 0;
2832         void *hdata;
2833         hdatalen = BIO_get_mem_data(s->s3->handshake_buffer, &hdata);
2834         if (hdatalen <= 0) {
2835             SSLerr(SSL_F_SSL3_GET_CERT_VERIFY, ERR_R_INTERNAL_ERROR);
2836             al = SSL_AD_INTERNAL_ERROR;
2837             goto f_err;
2838         }
2839 #ifdef SSL_DEBUG
2840         fprintf(stderr, "Using TLS 1.2 with client verify alg %s\n",
2841                 EVP_MD_name(md));
2842 #endif
2843         if (!EVP_VerifyInit_ex(&mctx, md, NULL)
2844             || !EVP_VerifyUpdate(&mctx, hdata, hdatalen)) {
2845             SSLerr(SSL_F_SSL3_GET_CERT_VERIFY, ERR_R_EVP_LIB);
2846             al = SSL_AD_INTERNAL_ERROR;
2847             goto f_err;
2848         }
2849
2850         if (EVP_VerifyFinal(&mctx, p, i, pkey) <= 0) {
2851             al = SSL_AD_DECRYPT_ERROR;
2852             SSLerr(SSL_F_SSL3_GET_CERT_VERIFY, SSL_R_BAD_SIGNATURE);
2853             goto f_err;
2854         }
2855     } else
2856 #ifndef OPENSSL_NO_RSA
2857     if (pkey->type == EVP_PKEY_RSA) {
2858         i = RSA_verify(NID_md5_sha1, s->s3->tmp.cert_verify_md,
2859                        MD5_DIGEST_LENGTH + SHA_DIGEST_LENGTH, p, i,
2860                        pkey->pkey.rsa);
2861         if (i < 0) {
2862             al = SSL_AD_DECRYPT_ERROR;
2863             SSLerr(SSL_F_SSL3_GET_CERT_VERIFY, SSL_R_BAD_RSA_DECRYPT);
2864             goto f_err;
2865         }
2866         if (i == 0) {
2867             al = SSL_AD_DECRYPT_ERROR;
2868             SSLerr(SSL_F_SSL3_GET_CERT_VERIFY, SSL_R_BAD_RSA_SIGNATURE);
2869             goto f_err;
2870         }
2871     } else
2872 #endif
2873 #ifndef OPENSSL_NO_DSA
2874     if (pkey->type == EVP_PKEY_DSA) {
2875         j = DSA_verify(pkey->save_type,
2876                        &(s->s3->tmp.cert_verify_md[MD5_DIGEST_LENGTH]),
2877                        SHA_DIGEST_LENGTH, p, i, pkey->pkey.dsa);
2878         if (j <= 0) {
2879             /* bad signature */
2880             al = SSL_AD_DECRYPT_ERROR;
2881             SSLerr(SSL_F_SSL3_GET_CERT_VERIFY, SSL_R_BAD_DSA_SIGNATURE);
2882             goto f_err;
2883         }
2884     } else
2885 #endif
2886 #ifndef OPENSSL_NO_EC
2887     if (pkey->type == EVP_PKEY_EC) {
2888         j = ECDSA_verify(pkey->save_type,
2889                          &(s->s3->tmp.cert_verify_md[MD5_DIGEST_LENGTH]),
2890                          SHA_DIGEST_LENGTH, p, i, pkey->pkey.ec);
2891         if (j <= 0) {
2892             /* bad signature */
2893             al = SSL_AD_DECRYPT_ERROR;
2894             SSLerr(SSL_F_SSL3_GET_CERT_VERIFY, SSL_R_BAD_ECDSA_SIGNATURE);
2895             goto f_err;
2896         }
2897     } else
2898 #endif
2899     if (pkey->type == NID_id_GostR3410_94
2900             || pkey->type == NID_id_GostR3410_2001) {
2901         unsigned char signature[64];
2902         int idx;
2903         EVP_PKEY_CTX *pctx = EVP_PKEY_CTX_new(pkey, NULL);
2904         EVP_PKEY_verify_init(pctx);
2905         if (i != 64) {
2906             fprintf(stderr, "GOST signature length is %d", i);
2907         }
2908         for (idx = 0; idx < 64; idx++) {
2909             signature[63 - idx] = p[idx];
2910         }
2911         j = EVP_PKEY_verify(pctx, signature, 64, s->s3->tmp.cert_verify_md,
2912                             32);
2913         EVP_PKEY_CTX_free(pctx);
2914         if (j <= 0) {
2915             al = SSL_AD_DECRYPT_ERROR;
2916             SSLerr(SSL_F_SSL3_GET_CERT_VERIFY, SSL_R_BAD_ECDSA_SIGNATURE);
2917             goto f_err;
2918         }
2919     } else {
2920         SSLerr(SSL_F_SSL3_GET_CERT_VERIFY, ERR_R_INTERNAL_ERROR);
2921         al = SSL_AD_UNSUPPORTED_CERTIFICATE;
2922         goto f_err;
2923     }
2924
2925     ret = 1;
2926     if (0) {
2927  f_err:
2928         ssl3_send_alert(s, SSL3_AL_FATAL, al);
2929         s->state = SSL_ST_ERR;
2930     }
2931  end:
2932     BIO_free(s->s3->handshake_buffer);
2933     s->s3->handshake_buffer = NULL;
2934     s->s3->flags &= ~TLS1_FLAGS_KEEP_HANDSHAKE;
2935     EVP_MD_CTX_cleanup(&mctx);
2936     EVP_PKEY_free(pkey);
2937     return (ret);
2938 }
2939
2940 int ssl3_get_client_certificate(SSL *s)
2941 {
2942     int i, ok, al, ret = -1;
2943     X509 *x = NULL;
2944     unsigned long l, nc, llen, n;
2945     const unsigned char *p, *q;
2946     unsigned char *d;
2947     STACK_OF(X509) *sk = NULL;
2948
2949     n = s->method->ssl_get_message(s,
2950                                    SSL3_ST_SR_CERT_A,
2951                                    SSL3_ST_SR_CERT_B,
2952                                    -1, s->max_cert_list, &ok);
2953
2954     if (!ok)
2955         return ((int)n);
2956
2957     if (s->s3->tmp.message_type == SSL3_MT_CLIENT_KEY_EXCHANGE) {
2958         if ((s->verify_mode & SSL_VERIFY_PEER) &&
2959             (s->verify_mode & SSL_VERIFY_FAIL_IF_NO_PEER_CERT)) {
2960             SSLerr(SSL_F_SSL3_GET_CLIENT_CERTIFICATE,
2961                    SSL_R_PEER_DID_NOT_RETURN_A_CERTIFICATE);
2962             al = SSL_AD_HANDSHAKE_FAILURE;
2963             goto f_err;
2964         }
2965         /*
2966          * If tls asked for a client cert, the client must return a 0 list
2967          */
2968         if ((s->version > SSL3_VERSION) && s->s3->tmp.cert_request) {
2969             SSLerr(SSL_F_SSL3_GET_CLIENT_CERTIFICATE,
2970                    SSL_R_TLS_PEER_DID_NOT_RESPOND_WITH_CERTIFICATE_LIST);
2971             al = SSL_AD_UNEXPECTED_MESSAGE;
2972             goto f_err;
2973         }
2974         s->s3->tmp.reuse_message = 1;
2975         return (1);
2976     }
2977
2978     if (s->s3->tmp.message_type != SSL3_MT_CERTIFICATE) {
2979         al = SSL_AD_UNEXPECTED_MESSAGE;
2980         SSLerr(SSL_F_SSL3_GET_CLIENT_CERTIFICATE, SSL_R_WRONG_MESSAGE_TYPE);
2981         goto f_err;
2982     }
2983     p = d = (unsigned char *)s->init_msg;
2984
2985     if ((sk = sk_X509_new_null()) == NULL) {
2986         SSLerr(SSL_F_SSL3_GET_CLIENT_CERTIFICATE, ERR_R_MALLOC_FAILURE);
2987         goto done;
2988     }
2989
2990     n2l3(p, llen);
2991     if (llen + 3 != n) {
2992         al = SSL_AD_DECODE_ERROR;
2993         SSLerr(SSL_F_SSL3_GET_CLIENT_CERTIFICATE, SSL_R_LENGTH_MISMATCH);
2994         goto f_err;
2995     }
2996     for (nc = 0; nc < llen;) {
2997         n2l3(p, l);
2998         if ((l + nc + 3) > llen) {
2999             al = SSL_AD_DECODE_ERROR;
3000             SSLerr(SSL_F_SSL3_GET_CLIENT_CERTIFICATE,
3001                    SSL_R_CERT_LENGTH_MISMATCH);
3002             goto f_err;
3003         }
3004
3005         q = p;
3006         x = d2i_X509(NULL, &p, l);
3007         if (x == NULL) {
3008             SSLerr(SSL_F_SSL3_GET_CLIENT_CERTIFICATE, ERR_R_ASN1_LIB);
3009             goto done;
3010         }
3011         if (p != (q + l)) {
3012             al = SSL_AD_DECODE_ERROR;
3013             SSLerr(SSL_F_SSL3_GET_CLIENT_CERTIFICATE,
3014                    SSL_R_CERT_LENGTH_MISMATCH);
3015             goto f_err;
3016         }
3017         if (!sk_X509_push(sk, x)) {
3018             SSLerr(SSL_F_SSL3_GET_CLIENT_CERTIFICATE, ERR_R_MALLOC_FAILURE);
3019             goto done;
3020         }
3021         x = NULL;
3022         nc += l + 3;
3023     }
3024
3025     if (sk_X509_num(sk) <= 0) {
3026         /* TLS does not mind 0 certs returned */
3027         if (s->version == SSL3_VERSION) {
3028             al = SSL_AD_HANDSHAKE_FAILURE;
3029             SSLerr(SSL_F_SSL3_GET_CLIENT_CERTIFICATE,
3030                    SSL_R_NO_CERTIFICATES_RETURNED);
3031             goto f_err;
3032         }
3033         /* Fail for TLS only if we required a certificate */
3034         else if ((s->verify_mode & SSL_VERIFY_PEER) &&
3035                  (s->verify_mode & SSL_VERIFY_FAIL_IF_NO_PEER_CERT)) {
3036             SSLerr(SSL_F_SSL3_GET_CLIENT_CERTIFICATE,
3037                    SSL_R_PEER_DID_NOT_RETURN_A_CERTIFICATE);
3038             al = SSL_AD_HANDSHAKE_FAILURE;
3039             goto f_err;
3040         }
3041         /* No client certificate so digest cached records */
3042         if (s->s3->handshake_buffer && !ssl3_digest_cached_records(s)) {
3043             al = SSL_AD_INTERNAL_ERROR;
3044             goto f_err;
3045         }
3046     } else {
3047         EVP_PKEY *pkey;
3048         i = ssl_verify_cert_chain(s, sk);
3049         if (i <= 0) {
3050             al = ssl_verify_alarm_type(s->verify_result);
3051             SSLerr(SSL_F_SSL3_GET_CLIENT_CERTIFICATE,
3052                    SSL_R_CERTIFICATE_VERIFY_FAILED);
3053             goto f_err;
3054         }
3055         if (i > 1) {
3056             SSLerr(SSL_F_SSL3_GET_CLIENT_CERTIFICATE, i);
3057             al = SSL_AD_HANDSHAKE_FAILURE;
3058             goto f_err;
3059         }
3060         pkey = X509_get_pubkey(sk_X509_value(sk, 0));
3061         if (pkey == NULL) {
3062             al = SSL3_AD_HANDSHAKE_FAILURE;
3063             SSLerr(SSL_F_SSL3_GET_CLIENT_CERTIFICATE,
3064                    SSL_R_UNKNOWN_CERTIFICATE_TYPE);
3065             goto f_err;
3066         }
3067         EVP_PKEY_free(pkey);
3068     }
3069
3070     X509_free(s->session->peer);
3071     s->session->peer = sk_X509_shift(sk);
3072     s->session->verify_result = s->verify_result;
3073
3074     /*
3075      * With the current implementation, sess_cert will always be NULL when we
3076      * arrive here.
3077      */
3078     if (s->session->sess_cert == NULL) {
3079         s->session->sess_cert = ssl_sess_cert_new();
3080         if (s->session->sess_cert == NULL) {
3081             SSLerr(SSL_F_SSL3_GET_CLIENT_CERTIFICATE, ERR_R_MALLOC_FAILURE);
3082             goto done;
3083         }
3084     }
3085     sk_X509_pop_free(s->session->sess_cert->cert_chain, X509_free);
3086     s->session->sess_cert->cert_chain = sk;
3087     /*
3088      * Inconsistency alert: cert_chain does *not* include the peer's own
3089      * certificate, while we do include it in s3_clnt.c
3090      */
3091     sk = NULL;
3092     ret = 1;
3093     goto done;
3094
3095  f_err:
3096     ssl3_send_alert(s, SSL3_AL_FATAL, al);
3097  done:
3098     s->state = SSL_ST_ERR;
3099     X509_free(x);
3100     sk_X509_pop_free(sk, X509_free);
3101     return (ret);
3102 }
3103
3104 int ssl3_send_server_certificate(SSL *s)
3105 {
3106     CERT_PKEY *cpk;
3107
3108     if (s->state == SSL3_ST_SW_CERT_A) {
3109         cpk = ssl_get_server_send_pkey(s);
3110         if (cpk == NULL) {
3111             SSLerr(SSL_F_SSL3_SEND_SERVER_CERTIFICATE, ERR_R_INTERNAL_ERROR);
3112             s->state = SSL_ST_ERR;
3113             return (0);
3114         }
3115
3116         if (!ssl3_output_cert_chain(s, cpk)) {
3117             SSLerr(SSL_F_SSL3_SEND_SERVER_CERTIFICATE, ERR_R_INTERNAL_ERROR);
3118             s->state = SSL_ST_ERR;
3119             return (0);
3120         }
3121         s->state = SSL3_ST_SW_CERT_B;
3122     }
3123
3124     /* SSL3_ST_SW_CERT_B */
3125     return ssl_do_write(s);
3126 }
3127
3128 #ifndef OPENSSL_NO_TLSEXT
3129 /* send a new session ticket (not necessarily for a new session) */
3130 int ssl3_send_newsession_ticket(SSL *s)
3131 {
3132     unsigned char *senc = NULL;
3133     EVP_CIPHER_CTX ctx;
3134     HMAC_CTX hctx;
3135
3136     if (s->state == SSL3_ST_SW_SESSION_TICKET_A) {
3137         unsigned char *p, *macstart;
3138         const unsigned char *const_p;
3139         int len, slen_full, slen;
3140         SSL_SESSION *sess;
3141         unsigned int hlen;
3142         SSL_CTX *tctx = s->initial_ctx;
3143         unsigned char iv[EVP_MAX_IV_LENGTH];
3144         unsigned char key_name[16];
3145
3146         /* get session encoding length */
3147         slen_full = i2d_SSL_SESSION(s->session, NULL);
3148         /*
3149          * Some length values are 16 bits, so forget it if session is too
3150          * long
3151          */
3152         if (slen_full == 0 || slen_full > 0xFF00) {
3153             s->state = SSL_ST_ERR;
3154             return -1;
3155         }
3156         senc = OPENSSL_malloc(slen_full);
3157         if (!senc) {
3158             s->state = SSL_ST_ERR;
3159             return -1;
3160         }
3161
3162         EVP_CIPHER_CTX_init(&ctx);
3163         HMAC_CTX_init(&hctx);
3164
3165         p = senc;
3166         if (!i2d_SSL_SESSION(s->session, &p))
3167             goto err;
3168
3169         /*
3170          * create a fresh copy (not shared with other threads) to clean up
3171          */
3172         const_p = senc;
3173         sess = d2i_SSL_SESSION(NULL, &const_p, slen_full);
3174         if (sess == NULL)
3175             goto err;
3176         sess->session_id_length = 0; /* ID is irrelevant for the ticket */
3177
3178         slen = i2d_SSL_SESSION(sess, NULL);
3179         if (slen == 0 || slen > slen_full) { /* shouldn't ever happen */
3180             SSL_SESSION_free(sess);
3181             goto err;
3182         }
3183         p = senc;
3184         if (!i2d_SSL_SESSION(sess, &p)) {
3185             SSL_SESSION_free(sess);
3186             goto err;
3187         }
3188         SSL_SESSION_free(sess);
3189
3190         /*-
3191          * Grow buffer if need be: the length calculation is as
3192          * follows handshake_header_length +
3193          * 4 (ticket lifetime hint) + 2 (ticket length) +
3194          * 16 (key name) + max_iv_len (iv length) +
3195          * session_length + max_enc_block_size (max encrypted session
3196          * length) + max_md_size (HMAC).
3197          */
3198         if (!BUF_MEM_grow(s->init_buf,
3199                           SSL_HM_HEADER_LENGTH(s) + 22 + EVP_MAX_IV_LENGTH +
3200                           EVP_MAX_BLOCK_LENGTH + EVP_MAX_MD_SIZE + slen))
3201             goto err;
3202
3203         p = ssl_handshake_start(s);
3204         /*
3205          * Initialize HMAC and cipher contexts. If callback present it does
3206          * all the work otherwise use generated values from parent ctx.
3207          */
3208         if (tctx->tlsext_ticket_key_cb) {
3209             if (tctx->tlsext_ticket_key_cb(s, key_name, iv, &ctx,
3210                                            &hctx, 1) < 0)
3211                 goto err;
3212         } else {
3213             if (RAND_bytes(iv, 16) <= 0)
3214                 goto err;
3215             if (!EVP_EncryptInit_ex(&ctx, EVP_aes_128_cbc(), NULL,
3216                                     tctx->tlsext_tick_aes_key, iv))
3217                 goto err;
3218             if (!HMAC_Init_ex(&hctx, tctx->tlsext_tick_hmac_key, 16,
3219                               EVP_sha256(), NULL))
3220                 goto err;
3221             memcpy(key_name, tctx->tlsext_tick_key_name, 16);
3222         }
3223
3224         /*
3225          * Ticket lifetime hint (advisory only): We leave this unspecified
3226          * for resumed session (for simplicity), and guess that tickets for
3227          * new sessions will live as long as their sessions.
3228          */
3229         l2n(s->hit ? 0 : s->session->timeout, p);
3230
3231         /* Skip ticket length for now */
3232         p += 2;
3233         /* Output key name */
3234         macstart = p;
3235         memcpy(p, key_name, 16);
3236         p += 16;
3237         /* output IV */
3238         memcpy(p, iv, EVP_CIPHER_CTX_iv_length(&ctx));
3239         p += EVP_CIPHER_CTX_iv_length(&ctx);
3240         /* Encrypt session data */
3241         if (!EVP_EncryptUpdate(&ctx, p, &len, senc, slen))
3242             goto err;
3243         p += len;
3244         if (!EVP_EncryptFinal(&ctx, p, &len))
3245             goto err;
3246         p += len;
3247
3248         if (!HMAC_Update(&hctx, macstart, p - macstart))
3249             goto err;
3250         if (!HMAC_Final(&hctx, p, &hlen))
3251             goto err;
3252
3253         EVP_CIPHER_CTX_cleanup(&ctx);
3254         HMAC_CTX_cleanup(&hctx);
3255
3256         p += hlen;
3257         /* Now write out lengths: p points to end of data written */
3258         /* Total length */
3259         len = p - ssl_handshake_start(s);
3260         /* Skip ticket lifetime hint */
3261         p = ssl_handshake_start(s) + 4;
3262         s2n(len - 6, p);
3263         if (!ssl_set_handshake_header(s, SSL3_MT_NEWSESSION_TICKET, len))
3264             goto err;
3265         s->state = SSL3_ST_SW_SESSION_TICKET_B;
3266         OPENSSL_free(senc);
3267     }
3268
3269     /* SSL3_ST_SW_SESSION_TICKET_B */
3270     return ssl_do_write(s);
3271  err:
3272     OPENSSL_free(senc);
3273     EVP_CIPHER_CTX_cleanup(&ctx);
3274     HMAC_CTX_cleanup(&hctx);
3275     s->state = SSL_ST_ERR;
3276     return -1;
3277 }
3278
3279 int ssl3_send_cert_status(SSL *s)
3280 {
3281     if (s->state == SSL3_ST_SW_CERT_STATUS_A) {
3282         unsigned char *p;
3283         /*-
3284          * Grow buffer if need be: the length calculation is as
3285          * follows 1 (message type) + 3 (message length) +
3286          * 1 (ocsp response type) + 3 (ocsp response length)
3287          * + (ocsp response)
3288          */
3289         if (!BUF_MEM_grow(s->init_buf, 8 + s->tlsext_ocsp_resplen)) {
3290             s->state = SSL_ST_ERR;
3291             return -1;
3292         }
3293
3294         p = (unsigned char *)s->init_buf->data;
3295
3296         /* do the header */
3297         *(p++) = SSL3_MT_CERTIFICATE_STATUS;
3298         /* message length */
3299         l2n3(s->tlsext_ocsp_resplen + 4, p);
3300         /* status type */
3301         *(p++) = s->tlsext_status_type;
3302         /* length of OCSP response */
3303         l2n3(s->tlsext_ocsp_resplen, p);
3304         /* actual response */
3305         memcpy(p, s->tlsext_ocsp_resp, s->tlsext_ocsp_resplen);
3306         /* number of bytes to write */
3307         s->init_num = 8 + s->tlsext_ocsp_resplen;
3308         s->state = SSL3_ST_SW_CERT_STATUS_B;
3309         s->init_off = 0;
3310     }
3311
3312     /* SSL3_ST_SW_CERT_STATUS_B */
3313     return (ssl3_do_write(s, SSL3_RT_HANDSHAKE));
3314 }
3315
3316 # ifndef OPENSSL_NO_NEXTPROTONEG
3317 /*
3318  * ssl3_get_next_proto reads a Next Protocol Negotiation handshake message.
3319  * It sets the next_proto member in s if found
3320  */
3321 int ssl3_get_next_proto(SSL *s)
3322 {
3323     int ok;
3324     int proto_len, padding_len;
3325     long n;
3326     const unsigned char *p;
3327
3328     /*
3329      * Clients cannot send a NextProtocol message if we didn't see the
3330      * extension in their ClientHello
3331      */
3332     if (!s->s3->next_proto_neg_seen) {
3333         SSLerr(SSL_F_SSL3_GET_NEXT_PROTO,
3334                SSL_R_GOT_NEXT_PROTO_WITHOUT_EXTENSION);
3335         s->state = SSL_ST_ERR;
3336         return -1;
3337     }
3338
3339     /* See the payload format below */
3340     n = s->method->ssl_get_message(s,
3341                                    SSL3_ST_SR_NEXT_PROTO_A,
3342                                    SSL3_ST_SR_NEXT_PROTO_B,
3343                                    SSL3_MT_NEXT_PROTO, 514, &ok);
3344
3345     if (!ok)
3346         return ((int)n);
3347
3348     /*
3349      * s->state doesn't reflect whether ChangeCipherSpec has been received in
3350      * this handshake, but s->s3->change_cipher_spec does (will be reset by
3351      * ssl3_get_finished).
3352      */
3353     if (!s->s3->change_cipher_spec) {
3354         SSLerr(SSL_F_SSL3_GET_NEXT_PROTO, SSL_R_GOT_NEXT_PROTO_BEFORE_A_CCS);
3355         s->state = SSL_ST_ERR;
3356         return -1;
3357     }
3358
3359     if (n < 2) {
3360         s->state = SSL_ST_ERR;
3361         return 0;               /* The body must be > 1 bytes long */
3362     }
3363
3364     p = (unsigned char *)s->init_msg;
3365
3366     /*-
3367      * The payload looks like:
3368      *   uint8 proto_len;
3369      *   uint8 proto[proto_len];
3370      *   uint8 padding_len;
3371      *   uint8 padding[padding_len];
3372      */
3373     proto_len = p[0];
3374     if (proto_len + 2 > s->init_num) {
3375         s->state = SSL_ST_ERR;
3376         return 0;
3377     }
3378     padding_len = p[proto_len + 1];
3379     if (proto_len + padding_len + 2 != s->init_num) {
3380         s->state = SSL_ST_ERR;
3381         return 0;
3382     }
3383
3384     s->next_proto_negotiated = OPENSSL_malloc(proto_len);
3385     if (!s->next_proto_negotiated) {
3386         SSLerr(SSL_F_SSL3_GET_NEXT_PROTO, ERR_R_MALLOC_FAILURE);
3387         s->state = SSL_ST_ERR;
3388         return 0;
3389     }
3390     memcpy(s->next_proto_negotiated, p + 1, proto_len);
3391     s->next_proto_negotiated_len = proto_len;
3392
3393     return 1;
3394 }
3395 # endif
3396
3397 #endif