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