2e7cb7a327e7613234d4276eafcaee5f8bf58eaf
[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
1129     if (i == 0) {
1130         al = SSL_AD_ILLEGAL_PARAMETER;
1131         SSLerr(SSL_F_SSL3_GET_CLIENT_HELLO, SSL_R_NO_CIPHERS_SPECIFIED);
1132         goto f_err;
1133     }
1134
1135     /* i bytes of cipher data + 1 byte for compression length later */
1136     if ((p + i + 1) > (d + n)) {
1137         /* not enough data */
1138         al = SSL_AD_DECODE_ERROR;
1139         SSLerr(SSL_F_SSL3_GET_CLIENT_HELLO, SSL_R_LENGTH_MISMATCH);
1140         goto f_err;
1141     }
1142     if (ssl_bytes_to_cipher_list(s, p, i, &(ciphers)) == NULL) {
1143         goto err;
1144     }
1145     p += i;
1146
1147     /* If it is a hit, check that the cipher is in the list */
1148     if (s->hit) {
1149         j = 0;
1150         id = s->session->cipher->id;
1151
1152 #ifdef CIPHER_DEBUG
1153         fprintf(stderr, "client sent %d ciphers\n",
1154                 sk_SSL_CIPHER_num(ciphers));
1155 #endif
1156         for (i = 0; i < sk_SSL_CIPHER_num(ciphers); i++) {
1157             c = sk_SSL_CIPHER_value(ciphers, i);
1158 #ifdef CIPHER_DEBUG
1159             fprintf(stderr, "client [%2d of %2d]:%s\n",
1160                     i, sk_SSL_CIPHER_num(ciphers), SSL_CIPHER_get_name(c));
1161 #endif
1162             if (c->id == id) {
1163                 j = 1;
1164                 break;
1165             }
1166         }
1167         /*
1168          * Disabled because it can be used in a ciphersuite downgrade attack:
1169          * CVE-2010-4180.
1170          */
1171 #if 0
1172         if (j == 0 && (s->options & SSL_OP_NETSCAPE_REUSE_CIPHER_CHANGE_BUG)
1173             && (sk_SSL_CIPHER_num(ciphers) == 1)) {
1174             /*
1175              * Special case as client bug workaround: the previously used
1176              * cipher may not be in the current list, the client instead
1177              * might be trying to continue using a cipher that before wasn't
1178              * chosen due to server preferences.  We'll have to reject the
1179              * connection if the cipher is not enabled, though.
1180              */
1181             c = sk_SSL_CIPHER_value(ciphers, 0);
1182             if (sk_SSL_CIPHER_find(SSL_get_ciphers(s), c) >= 0) {
1183                 s->session->cipher = c;
1184                 j = 1;
1185             }
1186         }
1187 #endif
1188         if (j == 0) {
1189             /*
1190              * we need to have the cipher in the cipher list if we are asked
1191              * to reuse it
1192              */
1193             al = SSL_AD_ILLEGAL_PARAMETER;
1194             SSLerr(SSL_F_SSL3_GET_CLIENT_HELLO,
1195                    SSL_R_REQUIRED_CIPHER_MISSING);
1196             goto f_err;
1197         }
1198     }
1199
1200     /* compression */
1201     i = *(p++);
1202     if ((p + i) > (d + n)) {
1203         /* not enough data */
1204         al = SSL_AD_DECODE_ERROR;
1205         SSLerr(SSL_F_SSL3_GET_CLIENT_HELLO, SSL_R_LENGTH_MISMATCH);
1206         goto f_err;
1207     }
1208 #ifndef OPENSSL_NO_COMP
1209     q = p;
1210 #endif
1211     for (j = 0; j < i; j++) {
1212         if (p[j] == 0)
1213             break;
1214     }
1215
1216     p += i;
1217     if (j >= i) {
1218         /* no compress */
1219         al = SSL_AD_DECODE_ERROR;
1220         SSLerr(SSL_F_SSL3_GET_CLIENT_HELLO, SSL_R_NO_COMPRESSION_SPECIFIED);
1221         goto f_err;
1222     }
1223 #ifndef OPENSSL_NO_TLSEXT
1224     /* TLS extensions */
1225     if (s->version >= SSL3_VERSION) {
1226         if (!ssl_parse_clienthello_tlsext(s, &p, d, n)) {
1227             SSLerr(SSL_F_SSL3_GET_CLIENT_HELLO, SSL_R_PARSE_TLSEXT);
1228             goto err;
1229         }
1230     }
1231
1232     /*
1233      * Check if we want to use external pre-shared secret for this handshake
1234      * for not reused session only. We need to generate server_random before
1235      * calling tls_session_secret_cb in order to allow SessionTicket
1236      * processing to use it in key derivation.
1237      */
1238     {
1239         unsigned char *pos;
1240         pos = s->s3->server_random;
1241         if (ssl_fill_hello_random(s, 1, pos, SSL3_RANDOM_SIZE) <= 0) {
1242             goto f_err;
1243         }
1244     }
1245
1246     if (!s->hit && s->version >= TLS1_VERSION && s->tls_session_secret_cb) {
1247         SSL_CIPHER *pref_cipher = NULL;
1248
1249         s->session->master_key_length = sizeof(s->session->master_key);
1250         if (s->tls_session_secret_cb(s, s->session->master_key,
1251                                      &s->session->master_key_length, ciphers,
1252                                      &pref_cipher,
1253                                      s->tls_session_secret_cb_arg)) {
1254             s->hit = 1;
1255             s->session->ciphers = ciphers;
1256             s->session->verify_result = X509_V_OK;
1257
1258             ciphers = NULL;
1259
1260             /* check if some cipher was preferred by call back */
1261             pref_cipher =
1262                 pref_cipher ? pref_cipher : ssl3_choose_cipher(s,
1263                                                                s->
1264                                                                session->ciphers,
1265                                                                SSL_get_ciphers
1266                                                                (s));
1267             if (pref_cipher == NULL) {
1268                 al = SSL_AD_HANDSHAKE_FAILURE;
1269                 SSLerr(SSL_F_SSL3_GET_CLIENT_HELLO, SSL_R_NO_SHARED_CIPHER);
1270                 goto f_err;
1271             }
1272
1273             s->session->cipher = pref_cipher;
1274
1275             if (s->cipher_list)
1276                 sk_SSL_CIPHER_free(s->cipher_list);
1277
1278             if (s->cipher_list_by_id)
1279                 sk_SSL_CIPHER_free(s->cipher_list_by_id);
1280
1281             s->cipher_list = sk_SSL_CIPHER_dup(s->session->ciphers);
1282             s->cipher_list_by_id = sk_SSL_CIPHER_dup(s->session->ciphers);
1283         }
1284     }
1285 #endif
1286
1287     /*
1288      * Worst case, we will use the NULL compression, but if we have other
1289      * options, we will now look for them.  We have i-1 compression
1290      * algorithms from the client, starting at q.
1291      */
1292     s->s3->tmp.new_compression = NULL;
1293 #ifndef OPENSSL_NO_COMP
1294     /* This only happens if we have a cache hit */
1295     if (s->session->compress_meth != 0) {
1296         int m, comp_id = s->session->compress_meth;
1297         /* Perform sanity checks on resumed compression algorithm */
1298         /* Can't disable compression */
1299         if (s->options & SSL_OP_NO_COMPRESSION) {
1300             SSLerr(SSL_F_SSL3_GET_CLIENT_HELLO,
1301                    SSL_R_INCONSISTENT_COMPRESSION);
1302             goto f_err;
1303         }
1304         /* Look for resumed compression method */
1305         for (m = 0; m < sk_SSL_COMP_num(s->ctx->comp_methods); m++) {
1306             comp = sk_SSL_COMP_value(s->ctx->comp_methods, m);
1307             if (comp_id == comp->id) {
1308                 s->s3->tmp.new_compression = comp;
1309                 break;
1310             }
1311         }
1312         if (s->s3->tmp.new_compression == NULL) {
1313             SSLerr(SSL_F_SSL3_GET_CLIENT_HELLO,
1314                    SSL_R_INVALID_COMPRESSION_ALGORITHM);
1315             goto f_err;
1316         }
1317         /* Look for resumed method in compression list */
1318         for (m = 0; m < i; m++) {
1319             if (q[m] == comp_id)
1320                 break;
1321         }
1322         if (m >= i) {
1323             al = SSL_AD_ILLEGAL_PARAMETER;
1324             SSLerr(SSL_F_SSL3_GET_CLIENT_HELLO,
1325                    SSL_R_REQUIRED_COMPRESSSION_ALGORITHM_MISSING);
1326             goto f_err;
1327         }
1328     } else if (s->hit)
1329         comp = NULL;
1330     else if (!(s->options & SSL_OP_NO_COMPRESSION) && s->ctx->comp_methods) {
1331         /* See if we have a match */
1332         int m, nn, o, v, done = 0;
1333
1334         nn = sk_SSL_COMP_num(s->ctx->comp_methods);
1335         for (m = 0; m < nn; m++) {
1336             comp = sk_SSL_COMP_value(s->ctx->comp_methods, m);
1337             v = comp->id;
1338             for (o = 0; o < i; o++) {
1339                 if (v == q[o]) {
1340                     done = 1;
1341                     break;
1342                 }
1343             }
1344             if (done)
1345                 break;
1346         }
1347         if (done)
1348             s->s3->tmp.new_compression = comp;
1349         else
1350             comp = NULL;
1351     }
1352 #else
1353     /*
1354      * If compression is disabled we'd better not try to resume a session
1355      * using compression.
1356      */
1357     if (s->session->compress_meth != 0) {
1358         SSLerr(SSL_F_SSL3_GET_CLIENT_HELLO, SSL_R_INCONSISTENT_COMPRESSION);
1359         goto f_err;
1360     }
1361 #endif
1362
1363     /*
1364      * Given s->session->ciphers and SSL_get_ciphers, we must pick a cipher
1365      */
1366
1367     if (!s->hit) {
1368 #ifdef OPENSSL_NO_COMP
1369         s->session->compress_meth = 0;
1370 #else
1371         s->session->compress_meth = (comp == NULL) ? 0 : comp->id;
1372 #endif
1373         if (s->session->ciphers != NULL)
1374             sk_SSL_CIPHER_free(s->session->ciphers);
1375         s->session->ciphers = ciphers;
1376         if (ciphers == NULL) {
1377             al = SSL_AD_INTERNAL_ERROR;
1378             SSLerr(SSL_F_SSL3_GET_CLIENT_HELLO, ERR_R_INTERNAL_ERROR);
1379             goto f_err;
1380         }
1381         ciphers = NULL;
1382         if (!tls1_set_server_sigalgs(s)) {
1383             SSLerr(SSL_F_SSL3_GET_CLIENT_HELLO, SSL_R_CLIENTHELLO_TLSEXT);
1384             goto err;
1385         }
1386         /* Let cert callback update server certificates if required */
1387  retry_cert:
1388         if (s->cert->cert_cb) {
1389             int rv = s->cert->cert_cb(s, s->cert->cert_cb_arg);
1390             if (rv == 0) {
1391                 al = SSL_AD_INTERNAL_ERROR;
1392                 SSLerr(SSL_F_SSL3_GET_CLIENT_HELLO, SSL_R_CERT_CB_ERROR);
1393                 goto f_err;
1394             }
1395             if (rv < 0) {
1396                 s->rwstate = SSL_X509_LOOKUP;
1397                 return -1;
1398             }
1399             s->rwstate = SSL_NOTHING;
1400         }
1401         c = ssl3_choose_cipher(s, s->session->ciphers, SSL_get_ciphers(s));
1402
1403         if (c == NULL) {
1404             al = SSL_AD_HANDSHAKE_FAILURE;
1405             SSLerr(SSL_F_SSL3_GET_CLIENT_HELLO, SSL_R_NO_SHARED_CIPHER);
1406             goto f_err;
1407         }
1408         s->s3->tmp.new_cipher = c;
1409     } else {
1410         /* Session-id reuse */
1411 #ifdef REUSE_CIPHER_BUG
1412         STACK_OF(SSL_CIPHER) *sk;
1413         SSL_CIPHER *nc = NULL;
1414         SSL_CIPHER *ec = NULL;
1415
1416         if (s->options & SSL_OP_NETSCAPE_DEMO_CIPHER_CHANGE_BUG) {
1417             sk = s->session->ciphers;
1418             for (i = 0; i < sk_SSL_CIPHER_num(sk); i++) {
1419                 c = sk_SSL_CIPHER_value(sk, i);
1420                 if (c->algorithm_enc & SSL_eNULL)
1421                     nc = c;
1422                 if (SSL_C_IS_EXPORT(c))
1423                     ec = c;
1424             }
1425             if (nc != NULL)
1426                 s->s3->tmp.new_cipher = nc;
1427             else if (ec != NULL)
1428                 s->s3->tmp.new_cipher = ec;
1429             else
1430                 s->s3->tmp.new_cipher = s->session->cipher;
1431         } else
1432 #endif
1433             s->s3->tmp.new_cipher = s->session->cipher;
1434     }
1435
1436     if (!SSL_USE_SIGALGS(s) || !(s->verify_mode & SSL_VERIFY_PEER)) {
1437         if (!ssl3_digest_cached_records(s))
1438             goto f_err;
1439     }
1440
1441     /*-
1442     * we now have the following setup.
1443      * client_random
1444      * cipher_list          - our prefered list of ciphers
1445      * ciphers              - the clients prefered list of ciphers
1446      * compression          - basically ignored right now
1447      * ssl version is set   - sslv3
1448      * s->session           - The ssl session has been setup.
1449      * s->hit               - session reuse flag
1450      * s->tmp.new_cipher    - the new cipher to use.
1451      */
1452
1453     /* Handles TLS extensions that we couldn't check earlier */
1454     if (s->version >= SSL3_VERSION) {
1455         if (ssl_check_clienthello_tlsext_late(s) <= 0) {
1456             SSLerr(SSL_F_SSL3_GET_CLIENT_HELLO, SSL_R_CLIENTHELLO_TLSEXT);
1457             goto err;
1458         }
1459     }
1460
1461     if (ret < 0)
1462         ret = -ret;
1463     if (0) {
1464  f_err:
1465         ssl3_send_alert(s, SSL3_AL_FATAL, al);
1466     }
1467  err:
1468     if (ciphers != NULL)
1469         sk_SSL_CIPHER_free(ciphers);
1470     return ret < 0 ? -1 : ret;
1471 }
1472
1473 int ssl3_send_server_hello(SSL *s)
1474 {
1475     unsigned char *buf;
1476     unsigned char *p, *d;
1477     int i, sl;
1478     int al = 0;
1479     unsigned long l;
1480
1481     if (s->state == SSL3_ST_SW_SRVR_HELLO_A) {
1482         buf = (unsigned char *)s->init_buf->data;
1483 #ifdef OPENSSL_NO_TLSEXT
1484         p = s->s3->server_random;
1485         if (ssl_fill_hello_random(s, 1, p, SSL3_RANDOM_SIZE) <= 0)
1486             return -1;
1487 #endif
1488         /* Do the message type and length last */
1489         d = p = ssl_handshake_start(s);
1490
1491         *(p++) = s->version >> 8;
1492         *(p++) = s->version & 0xff;
1493
1494         /* Random stuff */
1495         memcpy(p, s->s3->server_random, SSL3_RANDOM_SIZE);
1496         p += SSL3_RANDOM_SIZE;
1497
1498         /*-
1499          * There are several cases for the session ID to send
1500          * back in the server hello:
1501          * - For session reuse from the session cache,
1502          *   we send back the old session ID.
1503          * - If stateless session reuse (using a session ticket)
1504          *   is successful, we send back the client's "session ID"
1505          *   (which doesn't actually identify the session).
1506          * - If it is a new session, we send back the new
1507          *   session ID.
1508          * - However, if we want the new session to be single-use,
1509          *   we send back a 0-length session ID.
1510          * s->hit is non-zero in either case of session reuse,
1511          * so the following won't overwrite an ID that we're supposed
1512          * to send back.
1513          */
1514         if (!(s->ctx->session_cache_mode & SSL_SESS_CACHE_SERVER)
1515             && !s->hit)
1516             s->session->session_id_length = 0;
1517
1518         sl = s->session->session_id_length;
1519         if (sl > (int)sizeof(s->session->session_id)) {
1520             SSLerr(SSL_F_SSL3_SEND_SERVER_HELLO, ERR_R_INTERNAL_ERROR);
1521             return -1;
1522         }
1523         *(p++) = sl;
1524         memcpy(p, s->session->session_id, sl);
1525         p += sl;
1526
1527         /* put the cipher */
1528         i = ssl3_put_cipher_by_char(s->s3->tmp.new_cipher, p);
1529         p += i;
1530
1531         /* put the compression method */
1532 #ifdef OPENSSL_NO_COMP
1533         *(p++) = 0;
1534 #else
1535         if (s->s3->tmp.new_compression == NULL)
1536             *(p++) = 0;
1537         else
1538             *(p++) = s->s3->tmp.new_compression->id;
1539 #endif
1540 #ifndef OPENSSL_NO_TLSEXT
1541         if (ssl_prepare_serverhello_tlsext(s) <= 0) {
1542             SSLerr(SSL_F_SSL3_SEND_SERVER_HELLO, SSL_R_SERVERHELLO_TLSEXT);
1543             return -1;
1544         }
1545         if ((p =
1546              ssl_add_serverhello_tlsext(s, p, buf + SSL3_RT_MAX_PLAIN_LENGTH,
1547                                         &al)) == NULL) {
1548             ssl3_send_alert(s, SSL3_AL_FATAL, al);
1549             SSLerr(SSL_F_SSL3_SEND_SERVER_HELLO, ERR_R_INTERNAL_ERROR);
1550             return -1;
1551         }
1552 #endif
1553         /* do the header */
1554         l = (p - d);
1555         ssl_set_handshake_header(s, SSL3_MT_SERVER_HELLO, l);
1556         s->state = SSL3_ST_SW_SRVR_HELLO_B;
1557     }
1558
1559     /* SSL3_ST_SW_SRVR_HELLO_B */
1560     return ssl_do_write(s);
1561 }
1562
1563 int ssl3_send_server_done(SSL *s)
1564 {
1565
1566     if (s->state == SSL3_ST_SW_SRVR_DONE_A) {
1567         ssl_set_handshake_header(s, SSL3_MT_SERVER_DONE, 0);
1568         s->state = SSL3_ST_SW_SRVR_DONE_B;
1569     }
1570
1571     /* SSL3_ST_SW_SRVR_DONE_B */
1572     return ssl_do_write(s);
1573 }
1574
1575 int ssl3_send_server_key_exchange(SSL *s)
1576 {
1577 #ifndef OPENSSL_NO_RSA
1578     unsigned char *q;
1579     int j, num;
1580     RSA *rsa;
1581     unsigned char md_buf[MD5_DIGEST_LENGTH + SHA_DIGEST_LENGTH];
1582     unsigned int u;
1583 #endif
1584 #ifndef OPENSSL_NO_DH
1585     DH *dh = NULL, *dhp;
1586 #endif
1587 #ifndef OPENSSL_NO_ECDH
1588     EC_KEY *ecdh = NULL, *ecdhp;
1589     unsigned char *encodedPoint = NULL;
1590     int encodedlen = 0;
1591     int curve_id = 0;
1592     BN_CTX *bn_ctx = NULL;
1593 #endif
1594     EVP_PKEY *pkey;
1595     const EVP_MD *md = NULL;
1596     unsigned char *p, *d;
1597     int al, i;
1598     unsigned long type;
1599     int n;
1600     CERT *cert;
1601     BIGNUM *r[4];
1602     int nr[4], kn;
1603     BUF_MEM *buf;
1604     EVP_MD_CTX md_ctx;
1605
1606     EVP_MD_CTX_init(&md_ctx);
1607     if (s->state == SSL3_ST_SW_KEY_EXCH_A) {
1608         type = s->s3->tmp.new_cipher->algorithm_mkey;
1609         cert = s->cert;
1610
1611         buf = s->init_buf;
1612
1613         r[0] = r[1] = r[2] = r[3] = NULL;
1614         n = 0;
1615 #ifndef OPENSSL_NO_RSA
1616         if (type & SSL_kRSA) {
1617             rsa = cert->rsa_tmp;
1618             if ((rsa == NULL) && (s->cert->rsa_tmp_cb != NULL)) {
1619                 rsa = s->cert->rsa_tmp_cb(s,
1620                                           SSL_C_IS_EXPORT(s->s3->
1621                                                           tmp.new_cipher),
1622                                           SSL_C_EXPORT_PKEYLENGTH(s->s3->
1623                                                                   tmp.new_cipher));
1624                 if (rsa == NULL) {
1625                     al = SSL_AD_HANDSHAKE_FAILURE;
1626                     SSLerr(SSL_F_SSL3_SEND_SERVER_KEY_EXCHANGE,
1627                            SSL_R_ERROR_GENERATING_TMP_RSA_KEY);
1628                     goto f_err;
1629                 }
1630                 RSA_up_ref(rsa);
1631                 cert->rsa_tmp = rsa;
1632             }
1633             if (rsa == NULL) {
1634                 al = SSL_AD_HANDSHAKE_FAILURE;
1635                 SSLerr(SSL_F_SSL3_SEND_SERVER_KEY_EXCHANGE,
1636                        SSL_R_MISSING_TMP_RSA_KEY);
1637                 goto f_err;
1638             }
1639             r[0] = rsa->n;
1640             r[1] = rsa->e;
1641             s->s3->tmp.use_rsa_tmp = 1;
1642         } else
1643 #endif
1644 #ifndef OPENSSL_NO_DH
1645         if (type & SSL_kEDH) {
1646             dhp = cert->dh_tmp;
1647             if ((dhp == NULL) && (s->cert->dh_tmp_cb != NULL))
1648                 dhp = s->cert->dh_tmp_cb(s,
1649                                          SSL_C_IS_EXPORT(s->s3->
1650                                                          tmp.new_cipher),
1651                                          SSL_C_EXPORT_PKEYLENGTH(s->s3->
1652                                                                  tmp.new_cipher));
1653             if (dhp == NULL) {
1654                 al = SSL_AD_HANDSHAKE_FAILURE;
1655                 SSLerr(SSL_F_SSL3_SEND_SERVER_KEY_EXCHANGE,
1656                        SSL_R_MISSING_TMP_DH_KEY);
1657                 goto f_err;
1658             }
1659
1660             if (s->s3->tmp.dh != NULL) {
1661                 SSLerr(SSL_F_SSL3_SEND_SERVER_KEY_EXCHANGE,
1662                        ERR_R_INTERNAL_ERROR);
1663                 goto err;
1664             }
1665
1666             if ((dh = DHparams_dup(dhp)) == NULL) {
1667                 SSLerr(SSL_F_SSL3_SEND_SERVER_KEY_EXCHANGE, ERR_R_DH_LIB);
1668                 goto err;
1669             }
1670
1671             s->s3->tmp.dh = dh;
1672             if ((dhp->pub_key == NULL ||
1673                  dhp->priv_key == NULL ||
1674                  (s->options & SSL_OP_SINGLE_DH_USE))) {
1675                 if (!DH_generate_key(dh)) {
1676                     SSLerr(SSL_F_SSL3_SEND_SERVER_KEY_EXCHANGE, ERR_R_DH_LIB);
1677                     goto err;
1678                 }
1679             } else {
1680                 dh->pub_key = BN_dup(dhp->pub_key);
1681                 dh->priv_key = BN_dup(dhp->priv_key);
1682                 if ((dh->pub_key == NULL) || (dh->priv_key == NULL)) {
1683                     SSLerr(SSL_F_SSL3_SEND_SERVER_KEY_EXCHANGE, ERR_R_DH_LIB);
1684                     goto err;
1685                 }
1686             }
1687             r[0] = dh->p;
1688             r[1] = dh->g;
1689             r[2] = dh->pub_key;
1690         } else
1691 #endif
1692 #ifndef OPENSSL_NO_ECDH
1693         if (type & SSL_kEECDH) {
1694             const EC_GROUP *group;
1695
1696             ecdhp = cert->ecdh_tmp;
1697             if (s->cert->ecdh_tmp_auto) {
1698                 /* Get NID of appropriate shared curve */
1699                 int nid = tls1_shared_curve(s, -2);
1700                 if (nid != NID_undef)
1701                     ecdhp = EC_KEY_new_by_curve_name(nid);
1702             } else if ((ecdhp == NULL) && s->cert->ecdh_tmp_cb) {
1703                 ecdhp = s->cert->ecdh_tmp_cb(s,
1704                                              SSL_C_IS_EXPORT(s->s3->
1705                                                              tmp.new_cipher),
1706                                              SSL_C_EXPORT_PKEYLENGTH(s->
1707                                                                      s3->tmp.new_cipher));
1708             }
1709             if (ecdhp == NULL) {
1710                 al = SSL_AD_HANDSHAKE_FAILURE;
1711                 SSLerr(SSL_F_SSL3_SEND_SERVER_KEY_EXCHANGE,
1712                        SSL_R_MISSING_TMP_ECDH_KEY);
1713                 goto f_err;
1714             }
1715
1716             if (s->s3->tmp.ecdh != NULL) {
1717                 SSLerr(SSL_F_SSL3_SEND_SERVER_KEY_EXCHANGE,
1718                        ERR_R_INTERNAL_ERROR);
1719                 goto err;
1720             }
1721
1722             /* Duplicate the ECDH structure. */
1723             if (ecdhp == NULL) {
1724                 SSLerr(SSL_F_SSL3_SEND_SERVER_KEY_EXCHANGE, ERR_R_ECDH_LIB);
1725                 goto err;
1726             }
1727             if (s->cert->ecdh_tmp_auto)
1728                 ecdh = ecdhp;
1729             else if ((ecdh = EC_KEY_dup(ecdhp)) == NULL) {
1730                 SSLerr(SSL_F_SSL3_SEND_SERVER_KEY_EXCHANGE, ERR_R_ECDH_LIB);
1731                 goto err;
1732             }
1733
1734             s->s3->tmp.ecdh = ecdh;
1735             if ((EC_KEY_get0_public_key(ecdh) == NULL) ||
1736                 (EC_KEY_get0_private_key(ecdh) == NULL) ||
1737                 (s->options & SSL_OP_SINGLE_ECDH_USE)) {
1738                 if (!EC_KEY_generate_key(ecdh)) {
1739                     SSLerr(SSL_F_SSL3_SEND_SERVER_KEY_EXCHANGE,
1740                            ERR_R_ECDH_LIB);
1741                     goto err;
1742                 }
1743             }
1744
1745             if (((group = EC_KEY_get0_group(ecdh)) == NULL) ||
1746                 (EC_KEY_get0_public_key(ecdh) == NULL) ||
1747                 (EC_KEY_get0_private_key(ecdh) == NULL)) {
1748                 SSLerr(SSL_F_SSL3_SEND_SERVER_KEY_EXCHANGE, ERR_R_ECDH_LIB);
1749                 goto err;
1750             }
1751
1752             if (SSL_C_IS_EXPORT(s->s3->tmp.new_cipher) &&
1753                 (EC_GROUP_get_degree(group) > 163)) {
1754                 SSLerr(SSL_F_SSL3_SEND_SERVER_KEY_EXCHANGE,
1755                        SSL_R_ECGROUP_TOO_LARGE_FOR_CIPHER);
1756                 goto err;
1757             }
1758
1759             /*
1760              * XXX: For now, we only support ephemeral ECDH keys over named
1761              * (not generic) curves. For supported named curves, curve_id is
1762              * non-zero.
1763              */
1764             if ((curve_id =
1765                  tls1_ec_nid2curve_id(EC_GROUP_get_curve_name(group)))
1766                 == 0) {
1767                 SSLerr(SSL_F_SSL3_SEND_SERVER_KEY_EXCHANGE,
1768                        SSL_R_UNSUPPORTED_ELLIPTIC_CURVE);
1769                 goto err;
1770             }
1771
1772             /*
1773              * Encode the public key. First check the size of encoding and
1774              * allocate memory accordingly.
1775              */
1776             encodedlen = EC_POINT_point2oct(group,
1777                                             EC_KEY_get0_public_key(ecdh),
1778                                             POINT_CONVERSION_UNCOMPRESSED,
1779                                             NULL, 0, NULL);
1780
1781             encodedPoint = (unsigned char *)
1782                 OPENSSL_malloc(encodedlen * sizeof(unsigned char));
1783             bn_ctx = BN_CTX_new();
1784             if ((encodedPoint == NULL) || (bn_ctx == NULL)) {
1785                 SSLerr(SSL_F_SSL3_SEND_SERVER_KEY_EXCHANGE,
1786                        ERR_R_MALLOC_FAILURE);
1787                 goto err;
1788             }
1789
1790             encodedlen = EC_POINT_point2oct(group,
1791                                             EC_KEY_get0_public_key(ecdh),
1792                                             POINT_CONVERSION_UNCOMPRESSED,
1793                                             encodedPoint, encodedlen, bn_ctx);
1794
1795             if (encodedlen == 0) {
1796                 SSLerr(SSL_F_SSL3_SEND_SERVER_KEY_EXCHANGE, ERR_R_ECDH_LIB);
1797                 goto err;
1798             }
1799
1800             BN_CTX_free(bn_ctx);
1801             bn_ctx = NULL;
1802
1803             /*
1804              * XXX: For now, we only support named (not generic) curves in
1805              * ECDH ephemeral key exchanges. In this situation, we need four
1806              * additional bytes to encode the entire ServerECDHParams
1807              * structure.
1808              */
1809             n = 4 + encodedlen;
1810
1811             /*
1812              * We'll generate the serverKeyExchange message explicitly so we
1813              * can set these to NULLs
1814              */
1815             r[0] = NULL;
1816             r[1] = NULL;
1817             r[2] = NULL;
1818             r[3] = NULL;
1819         } else
1820 #endif                          /* !OPENSSL_NO_ECDH */
1821 #ifndef OPENSSL_NO_PSK
1822         if (type & SSL_kPSK) {
1823             /*
1824              * reserve size for record length and PSK identity hint
1825              */
1826             n += 2 + strlen(s->ctx->psk_identity_hint);
1827         } else
1828 #endif                          /* !OPENSSL_NO_PSK */
1829 #ifndef OPENSSL_NO_SRP
1830         if (type & SSL_kSRP) {
1831             if ((s->srp_ctx.N == NULL) ||
1832                 (s->srp_ctx.g == NULL) ||
1833                 (s->srp_ctx.s == NULL) || (s->srp_ctx.B == NULL)) {
1834                 SSLerr(SSL_F_SSL3_SEND_SERVER_KEY_EXCHANGE,
1835                        SSL_R_MISSING_SRP_PARAM);
1836                 goto err;
1837             }
1838             r[0] = s->srp_ctx.N;
1839             r[1] = s->srp_ctx.g;
1840             r[2] = s->srp_ctx.s;
1841             r[3] = s->srp_ctx.B;
1842         } else
1843 #endif
1844         {
1845             al = SSL_AD_HANDSHAKE_FAILURE;
1846             SSLerr(SSL_F_SSL3_SEND_SERVER_KEY_EXCHANGE,
1847                    SSL_R_UNKNOWN_KEY_EXCHANGE_TYPE);
1848             goto f_err;
1849         }
1850         for (i = 0; i < 4 && r[i] != NULL; i++) {
1851             nr[i] = BN_num_bytes(r[i]);
1852 #ifndef OPENSSL_NO_SRP
1853             if ((i == 2) && (type & SSL_kSRP))
1854                 n += 1 + nr[i];
1855             else
1856 #endif
1857                 n += 2 + nr[i];
1858         }
1859
1860         if (!(s->s3->tmp.new_cipher->algorithm_auth & (SSL_aNULL | SSL_aSRP))
1861             && !(s->s3->tmp.new_cipher->algorithm_mkey & SSL_kPSK)) {
1862             if ((pkey = ssl_get_sign_pkey(s, s->s3->tmp.new_cipher, &md))
1863                 == NULL) {
1864                 al = SSL_AD_DECODE_ERROR;
1865                 goto f_err;
1866             }
1867             kn = EVP_PKEY_size(pkey);
1868         } else {
1869             pkey = NULL;
1870             kn = 0;
1871         }
1872
1873         if (!BUF_MEM_grow_clean(buf, n + SSL_HM_HEADER_LENGTH(s) + kn)) {
1874             SSLerr(SSL_F_SSL3_SEND_SERVER_KEY_EXCHANGE, ERR_LIB_BUF);
1875             goto err;
1876         }
1877         d = p = ssl_handshake_start(s);
1878
1879         for (i = 0; i < 4 && r[i] != NULL; i++) {
1880 #ifndef OPENSSL_NO_SRP
1881             if ((i == 2) && (type & SSL_kSRP)) {
1882                 *p = nr[i];
1883                 p++;
1884             } else
1885 #endif
1886                 s2n(nr[i], p);
1887             BN_bn2bin(r[i], p);
1888             p += nr[i];
1889         }
1890
1891 #ifndef OPENSSL_NO_ECDH
1892         if (type & SSL_kEECDH) {
1893             /*
1894              * XXX: For now, we only support named (not generic) curves. In
1895              * this situation, the serverKeyExchange message has: [1 byte
1896              * CurveType], [2 byte CurveName] [1 byte length of encoded
1897              * point], followed by the actual encoded point itself
1898              */
1899             *p = NAMED_CURVE_TYPE;
1900             p += 1;
1901             *p = 0;
1902             p += 1;
1903             *p = curve_id;
1904             p += 1;
1905             *p = encodedlen;
1906             p += 1;
1907             memcpy((unsigned char *)p,
1908                    (unsigned char *)encodedPoint, encodedlen);
1909             OPENSSL_free(encodedPoint);
1910             encodedPoint = NULL;
1911             p += encodedlen;
1912         }
1913 #endif
1914
1915 #ifndef OPENSSL_NO_PSK
1916         if (type & SSL_kPSK) {
1917             /* copy PSK identity hint */
1918             s2n(strlen(s->ctx->psk_identity_hint), p);
1919             strncpy((char *)p, s->ctx->psk_identity_hint,
1920                     strlen(s->ctx->psk_identity_hint));
1921             p += strlen(s->ctx->psk_identity_hint);
1922         }
1923 #endif
1924
1925         /* not anonymous */
1926         if (pkey != NULL) {
1927             /*
1928              * n is the length of the params, they start at &(d[4]) and p
1929              * points to the space at the end.
1930              */
1931 #ifndef OPENSSL_NO_RSA
1932             if (pkey->type == EVP_PKEY_RSA && !SSL_USE_SIGALGS(s)) {
1933                 q = md_buf;
1934                 j = 0;
1935                 for (num = 2; num > 0; num--) {
1936                     EVP_MD_CTX_set_flags(&md_ctx,
1937                                          EVP_MD_CTX_FLAG_NON_FIPS_ALLOW);
1938                     EVP_DigestInit_ex(&md_ctx, (num == 2)
1939                                       ? s->ctx->md5 : s->ctx->sha1, NULL);
1940                     EVP_DigestUpdate(&md_ctx, &(s->s3->client_random[0]),
1941                                      SSL3_RANDOM_SIZE);
1942                     EVP_DigestUpdate(&md_ctx, &(s->s3->server_random[0]),
1943                                      SSL3_RANDOM_SIZE);
1944                     EVP_DigestUpdate(&md_ctx, d, n);
1945                     EVP_DigestFinal_ex(&md_ctx, q, (unsigned int *)&i);
1946                     q += i;
1947                     j += i;
1948                 }
1949                 if (RSA_sign(NID_md5_sha1, md_buf, j,
1950                              &(p[2]), &u, pkey->pkey.rsa) <= 0) {
1951                     SSLerr(SSL_F_SSL3_SEND_SERVER_KEY_EXCHANGE, ERR_LIB_RSA);
1952                     goto err;
1953                 }
1954                 s2n(u, p);
1955                 n += u + 2;
1956             } else
1957 #endif
1958             if (md) {
1959                 /* send signature algorithm */
1960                 if (SSL_USE_SIGALGS(s)) {
1961                     if (!tls12_get_sigandhash(p, pkey, md)) {
1962                         /* Should never happen */
1963                         al = SSL_AD_INTERNAL_ERROR;
1964                         SSLerr(SSL_F_SSL3_SEND_SERVER_KEY_EXCHANGE,
1965                                ERR_R_INTERNAL_ERROR);
1966                         goto f_err;
1967                     }
1968                     p += 2;
1969                 }
1970 #ifdef SSL_DEBUG
1971                 fprintf(stderr, "Using hash %s\n", EVP_MD_name(md));
1972 #endif
1973                 EVP_SignInit_ex(&md_ctx, md, NULL);
1974                 EVP_SignUpdate(&md_ctx, &(s->s3->client_random[0]),
1975                                SSL3_RANDOM_SIZE);
1976                 EVP_SignUpdate(&md_ctx, &(s->s3->server_random[0]),
1977                                SSL3_RANDOM_SIZE);
1978                 EVP_SignUpdate(&md_ctx, d, n);
1979                 if (!EVP_SignFinal(&md_ctx, &(p[2]),
1980                                    (unsigned int *)&i, pkey)) {
1981                     SSLerr(SSL_F_SSL3_SEND_SERVER_KEY_EXCHANGE, ERR_LIB_EVP);
1982                     goto err;
1983                 }
1984                 s2n(i, p);
1985                 n += i + 2;
1986                 if (SSL_USE_SIGALGS(s))
1987                     n += 2;
1988             } else {
1989                 /* Is this error check actually needed? */
1990                 al = SSL_AD_HANDSHAKE_FAILURE;
1991                 SSLerr(SSL_F_SSL3_SEND_SERVER_KEY_EXCHANGE,
1992                        SSL_R_UNKNOWN_PKEY_TYPE);
1993                 goto f_err;
1994             }
1995         }
1996
1997         ssl_set_handshake_header(s, SSL3_MT_SERVER_KEY_EXCHANGE, n);
1998     }
1999
2000     s->state = SSL3_ST_SW_KEY_EXCH_B;
2001     EVP_MD_CTX_cleanup(&md_ctx);
2002     return ssl_do_write(s);
2003  f_err:
2004     ssl3_send_alert(s, SSL3_AL_FATAL, al);
2005  err:
2006 #ifndef OPENSSL_NO_ECDH
2007     if (encodedPoint != NULL)
2008         OPENSSL_free(encodedPoint);
2009     BN_CTX_free(bn_ctx);
2010 #endif
2011     EVP_MD_CTX_cleanup(&md_ctx);
2012     return (-1);
2013 }
2014
2015 int ssl3_send_certificate_request(SSL *s)
2016 {
2017     unsigned char *p, *d;
2018     int i, j, nl, off, n;
2019     STACK_OF(X509_NAME) *sk = NULL;
2020     X509_NAME *name;
2021     BUF_MEM *buf;
2022
2023     if (s->state == SSL3_ST_SW_CERT_REQ_A) {
2024         buf = s->init_buf;
2025
2026         d = p = ssl_handshake_start(s);
2027
2028         /* get the list of acceptable cert types */
2029         p++;
2030         n = ssl3_get_req_cert_type(s, p);
2031         d[0] = n;
2032         p += n;
2033         n++;
2034
2035         if (SSL_USE_SIGALGS(s)) {
2036             const unsigned char *psigs;
2037             nl = tls12_get_psigalgs(s, &psigs);
2038             s2n(nl, p);
2039             memcpy(p, psigs, nl);
2040             p += nl;
2041             n += nl + 2;
2042         }
2043
2044         off = n;
2045         p += 2;
2046         n += 2;
2047
2048         sk = SSL_get_client_CA_list(s);
2049         nl = 0;
2050         if (sk != NULL) {
2051             for (i = 0; i < sk_X509_NAME_num(sk); i++) {
2052                 name = sk_X509_NAME_value(sk, i);
2053                 j = i2d_X509_NAME(name, NULL);
2054                 if (!BUF_MEM_grow_clean
2055                     (buf, SSL_HM_HEADER_LENGTH(s) + n + j + 2)) {
2056                     SSLerr(SSL_F_SSL3_SEND_CERTIFICATE_REQUEST,
2057                            ERR_R_BUF_LIB);
2058                     goto err;
2059                 }
2060                 p = ssl_handshake_start(s) + n;
2061                 if (!(s->options & SSL_OP_NETSCAPE_CA_DN_BUG)) {
2062                     s2n(j, p);
2063                     i2d_X509_NAME(name, &p);
2064                     n += 2 + j;
2065                     nl += 2 + j;
2066                 } else {
2067                     d = p;
2068                     i2d_X509_NAME(name, &p);
2069                     j -= 2;
2070                     s2n(j, d);
2071                     j += 2;
2072                     n += j;
2073                     nl += j;
2074                 }
2075             }
2076         }
2077         /* else no CA names */
2078         p = ssl_handshake_start(s) + off;
2079         s2n(nl, p);
2080
2081         ssl_set_handshake_header(s, SSL3_MT_CERTIFICATE_REQUEST, n);
2082
2083 #ifdef NETSCAPE_HANG_BUG
2084         if (!SSL_IS_DTLS(s)) {
2085             if (!BUF_MEM_grow_clean(buf, s->init_num + 4)) {
2086                 SSLerr(SSL_F_SSL3_SEND_CERTIFICATE_REQUEST, ERR_R_BUF_LIB);
2087                 goto err;
2088             }
2089             p = (unsigned char *)s->init_buf->data + s->init_num;
2090             /* do the header */
2091             *(p++) = SSL3_MT_SERVER_DONE;
2092             *(p++) = 0;
2093             *(p++) = 0;
2094             *(p++) = 0;
2095             s->init_num += 4;
2096         }
2097 #endif
2098
2099         s->state = SSL3_ST_SW_CERT_REQ_B;
2100     }
2101
2102     /* SSL3_ST_SW_CERT_REQ_B */
2103     return ssl_do_write(s);
2104  err:
2105     return (-1);
2106 }
2107
2108 int ssl3_get_client_key_exchange(SSL *s)
2109 {
2110     int i, al, ok;
2111     long n;
2112     unsigned long alg_k;
2113     unsigned char *p;
2114 #ifndef OPENSSL_NO_RSA
2115     RSA *rsa = NULL;
2116     EVP_PKEY *pkey = NULL;
2117 #endif
2118 #ifndef OPENSSL_NO_DH
2119     BIGNUM *pub = NULL;
2120     DH *dh_srvr, *dh_clnt = NULL;
2121 #endif
2122 #ifndef OPENSSL_NO_KRB5
2123     KSSL_ERR kssl_err;
2124 #endif                          /* OPENSSL_NO_KRB5 */
2125
2126 #ifndef OPENSSL_NO_ECDH
2127     EC_KEY *srvr_ecdh = NULL;
2128     EVP_PKEY *clnt_pub_pkey = NULL;
2129     EC_POINT *clnt_ecpoint = NULL;
2130     BN_CTX *bn_ctx = NULL;
2131 #endif
2132
2133     n = s->method->ssl_get_message(s,
2134                                    SSL3_ST_SR_KEY_EXCH_A,
2135                                    SSL3_ST_SR_KEY_EXCH_B,
2136                                    SSL3_MT_CLIENT_KEY_EXCHANGE, 2048, &ok);
2137
2138     if (!ok)
2139         return ((int)n);
2140     p = (unsigned char *)s->init_msg;
2141
2142     alg_k = s->s3->tmp.new_cipher->algorithm_mkey;
2143
2144 #ifndef OPENSSL_NO_RSA
2145     if (alg_k & SSL_kRSA) {
2146         unsigned char rand_premaster_secret[SSL_MAX_MASTER_KEY_LENGTH];
2147         int decrypt_len;
2148         unsigned char decrypt_good, version_good;
2149         size_t j;
2150
2151         /* FIX THIS UP EAY EAY EAY EAY */
2152         if (s->s3->tmp.use_rsa_tmp) {
2153             if ((s->cert != NULL) && (s->cert->rsa_tmp != NULL))
2154                 rsa = s->cert->rsa_tmp;
2155             /*
2156              * Don't do a callback because rsa_tmp should be sent already
2157              */
2158             if (rsa == NULL) {
2159                 al = SSL_AD_HANDSHAKE_FAILURE;
2160                 SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,
2161                        SSL_R_MISSING_TMP_RSA_PKEY);
2162                 goto f_err;
2163
2164             }
2165         } else {
2166             pkey = s->cert->pkeys[SSL_PKEY_RSA_ENC].privatekey;
2167             if ((pkey == NULL) ||
2168                 (pkey->type != EVP_PKEY_RSA) || (pkey->pkey.rsa == NULL)) {
2169                 al = SSL_AD_HANDSHAKE_FAILURE;
2170                 SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,
2171                        SSL_R_MISSING_RSA_CERTIFICATE);
2172                 goto f_err;
2173             }
2174             rsa = pkey->pkey.rsa;
2175         }
2176
2177         /* TLS and [incidentally] DTLS{0xFEFF} */
2178         if (s->version > SSL3_VERSION && s->version != DTLS1_BAD_VER) {
2179             n2s(p, i);
2180             if (n != i + 2) {
2181                 if (!(s->options & SSL_OP_TLS_D5_BUG)) {
2182                     al = SSL_AD_DECODE_ERROR;
2183                     SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,
2184                            SSL_R_TLS_RSA_ENCRYPTED_VALUE_LENGTH_IS_WRONG);
2185                     goto f_err;
2186                 } else
2187                     p -= 2;
2188             } else
2189                 n = i;
2190         }
2191
2192         /*
2193          * Reject overly short RSA ciphertext because we want to be sure
2194          * that the buffer size makes it safe to iterate over the entire
2195          * size of a premaster secret (SSL_MAX_MASTER_KEY_LENGTH). The
2196          * actual expected size is larger due to RSA padding, but the
2197          * bound is sufficient to be safe.
2198          */
2199         if (n < SSL_MAX_MASTER_KEY_LENGTH) {
2200             al = SSL_AD_DECRYPT_ERROR;
2201             SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,
2202                    SSL_R_TLS_RSA_ENCRYPTED_VALUE_LENGTH_IS_WRONG);
2203             goto f_err;
2204         }
2205
2206         /*
2207          * We must not leak whether a decryption failure occurs because of
2208          * Bleichenbacher's attack on PKCS #1 v1.5 RSA padding (see RFC 2246,
2209          * section 7.4.7.1). The code follows that advice of the TLS RFC and
2210          * generates a random premaster secret for the case that the decrypt
2211          * fails. See https://tools.ietf.org/html/rfc5246#section-7.4.7.1
2212          */
2213
2214         /*
2215          * should be RAND_bytes, but we cannot work around a failure.
2216          */
2217         if (RAND_pseudo_bytes(rand_premaster_secret,
2218                               sizeof(rand_premaster_secret)) <= 0)
2219             goto err;
2220         decrypt_len =
2221             RSA_private_decrypt((int)n, p, p, rsa, RSA_PKCS1_PADDING);
2222         ERR_clear_error();
2223
2224         /*
2225          * decrypt_len should be SSL_MAX_MASTER_KEY_LENGTH. decrypt_good will
2226          * be 0xff if so and zero otherwise.
2227          */
2228         decrypt_good =
2229             constant_time_eq_int_8(decrypt_len, SSL_MAX_MASTER_KEY_LENGTH);
2230
2231         /*
2232          * If the version in the decrypted pre-master secret is correct then
2233          * version_good will be 0xff, otherwise it'll be zero. The
2234          * Klima-Pokorny-Rosa extension of Bleichenbacher's attack
2235          * (http://eprint.iacr.org/2003/052/) exploits the version number
2236          * check as a "bad version oracle". Thus version checks are done in
2237          * constant time and are treated like any other decryption error.
2238          */
2239         version_good =
2240             constant_time_eq_8(p[0], (unsigned)(s->client_version >> 8));
2241         version_good &=
2242             constant_time_eq_8(p[1], (unsigned)(s->client_version & 0xff));
2243
2244         /*
2245          * The premaster secret must contain the same version number as the
2246          * ClientHello to detect version rollback attacks (strangely, the
2247          * protocol does not offer such protection for DH ciphersuites).
2248          * However, buggy clients exist that send the negotiated protocol
2249          * version instead if the server does not support the requested
2250          * protocol version. If SSL_OP_TLS_ROLLBACK_BUG is set, tolerate such
2251          * clients.
2252          */
2253         if (s->options & SSL_OP_TLS_ROLLBACK_BUG) {
2254             unsigned char workaround_good;
2255             workaround_good =
2256                 constant_time_eq_8(p[0], (unsigned)(s->version >> 8));
2257             workaround_good &=
2258                 constant_time_eq_8(p[1], (unsigned)(s->version & 0xff));
2259             version_good |= workaround_good;
2260         }
2261
2262         /*
2263          * Both decryption and version must be good for decrypt_good to
2264          * remain non-zero (0xff).
2265          */
2266         decrypt_good &= version_good;
2267
2268         /*
2269          * Now copy rand_premaster_secret over from p using
2270          * decrypt_good_mask. If decryption failed, then p does not
2271          * contain valid plaintext, however, a check above guarantees
2272          * it is still sufficiently large to read from.
2273          */
2274         for (j = 0; j < sizeof(rand_premaster_secret); j++) {
2275             p[j] = constant_time_select_8(decrypt_good, p[j],
2276                                           rand_premaster_secret[j]);
2277         }
2278
2279         s->session->master_key_length =
2280             s->method->ssl3_enc->generate_master_secret(s,
2281                                                         s->
2282                                                         session->master_key,
2283                                                         p,
2284                                                         sizeof
2285                                                         (rand_premaster_secret));
2286         OPENSSL_cleanse(p, sizeof(rand_premaster_secret));
2287     } else
2288 #endif
2289 #ifndef OPENSSL_NO_DH
2290     if (alg_k & (SSL_kEDH | SSL_kDHr | SSL_kDHd)) {
2291         int idx = -1;
2292         EVP_PKEY *skey = NULL;
2293         if (n > 1) {
2294             n2s(p, i);
2295         } else {
2296             if (alg_k & SSL_kDHE) {
2297                 al = SSL_AD_HANDSHAKE_FAILURE;
2298                 SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,
2299                        SSL_R_DH_PUBLIC_VALUE_LENGTH_IS_WRONG);
2300                 goto f_err;
2301             }
2302             i = 0;
2303         }
2304         if (n && n != i + 2) {
2305             if (!(s->options & SSL_OP_SSLEAY_080_CLIENT_DH_BUG)) {
2306                 SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,
2307                        SSL_R_DH_PUBLIC_VALUE_LENGTH_IS_WRONG);
2308                 goto err;
2309             } else {
2310                 p -= 2;
2311                 i = (int)n;
2312             }
2313         }
2314         if (alg_k & SSL_kDHr)
2315             idx = SSL_PKEY_DH_RSA;
2316         else if (alg_k & SSL_kDHd)
2317             idx = SSL_PKEY_DH_DSA;
2318         if (idx >= 0) {
2319             skey = s->cert->pkeys[idx].privatekey;
2320             if ((skey == NULL) ||
2321                 (skey->type != EVP_PKEY_DH) || (skey->pkey.dh == NULL)) {
2322                 al = SSL_AD_HANDSHAKE_FAILURE;
2323                 SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,
2324                        SSL_R_MISSING_RSA_CERTIFICATE);
2325                 goto f_err;
2326             }
2327             dh_srvr = skey->pkey.dh;
2328         } else if (s->s3->tmp.dh == NULL) {
2329             al = SSL_AD_HANDSHAKE_FAILURE;
2330             SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,
2331                    SSL_R_MISSING_TMP_DH_KEY);
2332             goto f_err;
2333         } else
2334             dh_srvr = s->s3->tmp.dh;
2335
2336         if (n == 0L) {
2337             /* Get pubkey from cert */
2338             EVP_PKEY *clkey = X509_get_pubkey(s->session->peer);
2339             if (clkey) {
2340                 if (EVP_PKEY_cmp_parameters(clkey, skey) == 1)
2341                     dh_clnt = EVP_PKEY_get1_DH(clkey);
2342             }
2343             if (dh_clnt == NULL) {
2344                 al = SSL_AD_HANDSHAKE_FAILURE;
2345                 SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,
2346                        SSL_R_MISSING_TMP_DH_KEY);
2347                 goto f_err;
2348             }
2349             EVP_PKEY_free(clkey);
2350             pub = dh_clnt->pub_key;
2351         } else
2352             pub = BN_bin2bn(p, i, NULL);
2353         if (pub == NULL) {
2354             SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE, SSL_R_BN_LIB);
2355             goto err;
2356         }
2357
2358         i = DH_compute_key(p, pub, dh_srvr);
2359
2360         if (i <= 0) {
2361             SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE, ERR_R_DH_LIB);
2362             BN_clear_free(pub);
2363             goto err;
2364         }
2365
2366         DH_free(s->s3->tmp.dh);
2367         s->s3->tmp.dh = NULL;
2368         if (dh_clnt)
2369             DH_free(dh_clnt);
2370         else
2371             BN_clear_free(pub);
2372         pub = NULL;
2373         s->session->master_key_length =
2374             s->method->ssl3_enc->generate_master_secret(s,
2375                                                         s->
2376                                                         session->master_key,
2377                                                         p, i);
2378         OPENSSL_cleanse(p, i);
2379         if (dh_clnt)
2380             return 2;
2381     } else
2382 #endif
2383 #ifndef OPENSSL_NO_KRB5
2384     if (alg_k & SSL_kKRB5) {
2385         krb5_error_code krb5rc;
2386         krb5_data enc_ticket;
2387         krb5_data authenticator;
2388         krb5_data enc_pms;
2389         KSSL_CTX *kssl_ctx = s->kssl_ctx;
2390         EVP_CIPHER_CTX ciph_ctx;
2391         const EVP_CIPHER *enc = NULL;
2392         unsigned char iv[EVP_MAX_IV_LENGTH];
2393         unsigned char pms[SSL_MAX_MASTER_KEY_LENGTH + EVP_MAX_BLOCK_LENGTH];
2394         int padl, outl;
2395         krb5_timestamp authtime = 0;
2396         krb5_ticket_times ttimes;
2397
2398         EVP_CIPHER_CTX_init(&ciph_ctx);
2399
2400         if (!kssl_ctx)
2401             kssl_ctx = kssl_ctx_new();
2402
2403         n2s(p, i);
2404         enc_ticket.length = i;
2405
2406         if (n < (long)(enc_ticket.length + 6)) {
2407             SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,
2408                    SSL_R_DATA_LENGTH_TOO_LONG);
2409             goto err;
2410         }
2411
2412         enc_ticket.data = (char *)p;
2413         p += enc_ticket.length;
2414
2415         n2s(p, i);
2416         authenticator.length = i;
2417
2418         if (n < (long)(enc_ticket.length + authenticator.length + 6)) {
2419             SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,
2420                    SSL_R_DATA_LENGTH_TOO_LONG);
2421             goto err;
2422         }
2423
2424         authenticator.data = (char *)p;
2425         p += authenticator.length;
2426
2427         n2s(p, i);
2428         enc_pms.length = i;
2429         enc_pms.data = (char *)p;
2430         p += enc_pms.length;
2431
2432         /*
2433          * Note that the length is checked again below, ** after decryption
2434          */
2435         if (enc_pms.length > sizeof pms) {
2436             SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,
2437                    SSL_R_DATA_LENGTH_TOO_LONG);
2438             goto err;
2439         }
2440
2441         if (n != (long)(enc_ticket.length + authenticator.length +
2442                         enc_pms.length + 6)) {
2443             SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,
2444                    SSL_R_DATA_LENGTH_TOO_LONG);
2445             goto err;
2446         }
2447
2448         if ((krb5rc = kssl_sget_tkt(kssl_ctx, &enc_ticket, &ttimes,
2449                                     &kssl_err)) != 0) {
2450 # ifdef KSSL_DEBUG
2451             fprintf(stderr, "kssl_sget_tkt rtn %d [%d]\n",
2452                     krb5rc, kssl_err.reason);
2453             if (kssl_err.text)
2454                 fprintf(stderr, "kssl_err text= %s\n", kssl_err.text);
2455 # endif                         /* KSSL_DEBUG */
2456             SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE, kssl_err.reason);
2457             goto err;
2458         }
2459
2460         /*
2461          * Note: no authenticator is not considered an error, ** but will
2462          * return authtime == 0.
2463          */
2464         if ((krb5rc = kssl_check_authent(kssl_ctx, &authenticator,
2465                                          &authtime, &kssl_err)) != 0) {
2466 # ifdef KSSL_DEBUG
2467             fprintf(stderr, "kssl_check_authent rtn %d [%d]\n",
2468                     krb5rc, kssl_err.reason);
2469             if (kssl_err.text)
2470                 fprintf(stderr, "kssl_err text= %s\n", kssl_err.text);
2471 # endif                         /* KSSL_DEBUG */
2472             SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE, kssl_err.reason);
2473             goto err;
2474         }
2475
2476         if ((krb5rc = kssl_validate_times(authtime, &ttimes)) != 0) {
2477             SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE, krb5rc);
2478             goto err;
2479         }
2480 # ifdef KSSL_DEBUG
2481         kssl_ctx_show(kssl_ctx);
2482 # endif                         /* KSSL_DEBUG */
2483
2484         enc = kssl_map_enc(kssl_ctx->enctype);
2485         if (enc == NULL)
2486             goto err;
2487
2488         memset(iv, 0, sizeof iv); /* per RFC 1510 */
2489
2490         if (!EVP_DecryptInit_ex(&ciph_ctx, enc, NULL, kssl_ctx->key, iv)) {
2491             SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,
2492                    SSL_R_DECRYPTION_FAILED);
2493             goto err;
2494         }
2495         if (!EVP_DecryptUpdate(&ciph_ctx, pms, &outl,
2496                                (unsigned char *)enc_pms.data, enc_pms.length))
2497         {
2498             SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,
2499                    SSL_R_DECRYPTION_FAILED);
2500             goto err;
2501         }
2502         if (outl > SSL_MAX_MASTER_KEY_LENGTH) {
2503             SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,
2504                    SSL_R_DATA_LENGTH_TOO_LONG);
2505             goto err;
2506         }
2507         if (!EVP_DecryptFinal_ex(&ciph_ctx, &(pms[outl]), &padl)) {
2508             SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,
2509                    SSL_R_DECRYPTION_FAILED);
2510             goto err;
2511         }
2512         outl += padl;
2513         if (outl > SSL_MAX_MASTER_KEY_LENGTH) {
2514             SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,
2515                    SSL_R_DATA_LENGTH_TOO_LONG);
2516             goto err;
2517         }
2518         if (!((pms[0] == (s->client_version >> 8))
2519               && (pms[1] == (s->client_version & 0xff)))) {
2520             /*
2521              * The premaster secret must contain the same version number as
2522              * the ClientHello to detect version rollback attacks (strangely,
2523              * the protocol does not offer such protection for DH
2524              * ciphersuites). However, buggy clients exist that send random
2525              * bytes instead of the protocol version. If
2526              * SSL_OP_TLS_ROLLBACK_BUG is set, tolerate such clients.
2527              * (Perhaps we should have a separate BUG value for the Kerberos
2528              * cipher)
2529              */
2530             if (!(s->options & SSL_OP_TLS_ROLLBACK_BUG)) {
2531                 SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,
2532                        SSL_AD_DECODE_ERROR);
2533                 goto err;
2534             }
2535         }
2536
2537         EVP_CIPHER_CTX_cleanup(&ciph_ctx);
2538
2539         s->session->master_key_length =
2540             s->method->ssl3_enc->generate_master_secret(s,
2541                                                         s->
2542                                                         session->master_key,
2543                                                         pms, outl);
2544
2545         if (kssl_ctx->client_princ) {
2546             size_t len = strlen(kssl_ctx->client_princ);
2547             if (len < SSL_MAX_KRB5_PRINCIPAL_LENGTH) {
2548                 s->session->krb5_client_princ_len = len;
2549                 memcpy(s->session->krb5_client_princ, kssl_ctx->client_princ,
2550                        len);
2551             }
2552         }
2553
2554         /*- Was doing kssl_ctx_free() here,
2555          *  but it caused problems for apache.
2556          *  kssl_ctx = kssl_ctx_free(kssl_ctx);
2557          *  if (s->kssl_ctx)  s->kssl_ctx = NULL;
2558          */
2559     } else
2560 #endif                          /* OPENSSL_NO_KRB5 */
2561
2562 #ifndef OPENSSL_NO_ECDH
2563     if (alg_k & (SSL_kEECDH | SSL_kECDHr | SSL_kECDHe)) {
2564         int ret = 1;
2565         int field_size = 0;
2566         const EC_KEY *tkey;
2567         const EC_GROUP *group;
2568         const BIGNUM *priv_key;
2569
2570         /* initialize structures for server's ECDH key pair */
2571         if ((srvr_ecdh = EC_KEY_new()) == NULL) {
2572             SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE, ERR_R_MALLOC_FAILURE);
2573             goto err;
2574         }
2575
2576         /* Let's get server private key and group information */
2577         if (alg_k & (SSL_kECDHr | SSL_kECDHe)) {
2578             /* use the certificate */
2579             tkey = s->cert->pkeys[SSL_PKEY_ECC].privatekey->pkey.ec;
2580         } else {
2581             /*
2582              * use the ephermeral values we saved when generating the
2583              * ServerKeyExchange msg.
2584              */
2585             tkey = s->s3->tmp.ecdh;
2586         }
2587
2588         group = EC_KEY_get0_group(tkey);
2589         priv_key = EC_KEY_get0_private_key(tkey);
2590
2591         if (!EC_KEY_set_group(srvr_ecdh, group) ||
2592             !EC_KEY_set_private_key(srvr_ecdh, priv_key)) {
2593             SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE, ERR_R_EC_LIB);
2594             goto err;
2595         }
2596
2597         /* Let's get client's public key */
2598         if ((clnt_ecpoint = EC_POINT_new(group)) == NULL) {
2599             SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE, ERR_R_MALLOC_FAILURE);
2600             goto err;
2601         }
2602
2603         if (n == 0L) {
2604             /* Client Publickey was in Client Certificate */
2605
2606             if (alg_k & SSL_kEECDH) {
2607                 al = SSL_AD_HANDSHAKE_FAILURE;
2608                 SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,
2609                        SSL_R_MISSING_TMP_ECDH_KEY);
2610                 goto f_err;
2611             }
2612             if (((clnt_pub_pkey = X509_get_pubkey(s->session->peer))
2613                  == NULL) || (clnt_pub_pkey->type != EVP_PKEY_EC)) {
2614                 /*
2615                  * XXX: For now, we do not support client authentication
2616                  * using ECDH certificates so this branch (n == 0L) of the
2617                  * code is never executed. When that support is added, we
2618                  * ought to ensure the key received in the certificate is
2619                  * authorized for key agreement. ECDH_compute_key implicitly
2620                  * checks that the two ECDH shares are for the same group.
2621                  */
2622                 al = SSL_AD_HANDSHAKE_FAILURE;
2623                 SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,
2624                        SSL_R_UNABLE_TO_DECODE_ECDH_CERTS);
2625                 goto f_err;
2626             }
2627
2628             if (EC_POINT_copy(clnt_ecpoint,
2629                               EC_KEY_get0_public_key(clnt_pub_pkey->
2630                                                      pkey.ec)) == 0) {
2631                 SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE, ERR_R_EC_LIB);
2632                 goto err;
2633             }
2634             ret = 2;            /* Skip certificate verify processing */
2635         } else {
2636             /*
2637              * Get client's public key from encoded point in the
2638              * ClientKeyExchange message.
2639              */
2640             if ((bn_ctx = BN_CTX_new()) == NULL) {
2641                 SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,
2642                        ERR_R_MALLOC_FAILURE);
2643                 goto err;
2644             }
2645
2646             /* Get encoded point length */
2647             i = *p;
2648             p += 1;
2649             if (n != 1 + i) {
2650                 SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE, ERR_R_EC_LIB);
2651                 goto err;
2652             }
2653             if (EC_POINT_oct2point(group, clnt_ecpoint, p, i, bn_ctx) == 0) {
2654                 SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE, ERR_R_EC_LIB);
2655                 goto err;
2656             }
2657             /*
2658              * p is pointing to somewhere in the buffer currently, so set it
2659              * to the start
2660              */
2661             p = (unsigned char *)s->init_buf->data;
2662         }
2663
2664         /* Compute the shared pre-master secret */
2665         field_size = EC_GROUP_get_degree(group);
2666         if (field_size <= 0) {
2667             SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE, ERR_R_ECDH_LIB);
2668             goto err;
2669         }
2670         i = ECDH_compute_key(p, (field_size + 7) / 8, clnt_ecpoint, srvr_ecdh,
2671                              NULL);
2672         if (i <= 0) {
2673             SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE, ERR_R_ECDH_LIB);
2674             goto err;
2675         }
2676
2677         EVP_PKEY_free(clnt_pub_pkey);
2678         EC_POINT_free(clnt_ecpoint);
2679         EC_KEY_free(srvr_ecdh);
2680         BN_CTX_free(bn_ctx);
2681         EC_KEY_free(s->s3->tmp.ecdh);
2682         s->s3->tmp.ecdh = NULL;
2683
2684         /* Compute the master secret */
2685         s->session->master_key_length =
2686             s->method->ssl3_enc->generate_master_secret(s,
2687                                                         s->
2688                                                         session->master_key,
2689                                                         p, i);
2690
2691         OPENSSL_cleanse(p, i);
2692         return (ret);
2693     } else
2694 #endif
2695 #ifndef OPENSSL_NO_PSK
2696     if (alg_k & SSL_kPSK) {
2697         unsigned char *t = NULL;
2698         unsigned char psk_or_pre_ms[PSK_MAX_PSK_LEN * 2 + 4];
2699         unsigned int pre_ms_len = 0, psk_len = 0;
2700         int psk_err = 1;
2701         char tmp_id[PSK_MAX_IDENTITY_LEN + 1];
2702
2703         al = SSL_AD_HANDSHAKE_FAILURE;
2704
2705         n2s(p, i);
2706         if (n != i + 2) {
2707             SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE, SSL_R_LENGTH_MISMATCH);
2708             goto psk_err;
2709         }
2710         if (i > PSK_MAX_IDENTITY_LEN) {
2711             SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,
2712                    SSL_R_DATA_LENGTH_TOO_LONG);
2713             goto psk_err;
2714         }
2715         if (s->psk_server_callback == NULL) {
2716             SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,
2717                    SSL_R_PSK_NO_SERVER_CB);
2718             goto psk_err;
2719         }
2720
2721         /*
2722          * Create guaranteed NULL-terminated identity string for the callback
2723          */
2724         memcpy(tmp_id, p, i);
2725         memset(tmp_id + i, 0, PSK_MAX_IDENTITY_LEN + 1 - i);
2726         psk_len = s->psk_server_callback(s, tmp_id,
2727                                          psk_or_pre_ms,
2728                                          sizeof(psk_or_pre_ms));
2729         OPENSSL_cleanse(tmp_id, PSK_MAX_IDENTITY_LEN + 1);
2730
2731         if (psk_len > PSK_MAX_PSK_LEN) {
2732             SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE, ERR_R_INTERNAL_ERROR);
2733             goto psk_err;
2734         } else if (psk_len == 0) {
2735             /*
2736              * PSK related to the given identity not found
2737              */
2738             SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,
2739                    SSL_R_PSK_IDENTITY_NOT_FOUND);
2740             al = SSL_AD_UNKNOWN_PSK_IDENTITY;
2741             goto psk_err;
2742         }
2743
2744         /* create PSK pre_master_secret */
2745         pre_ms_len = 2 + psk_len + 2 + psk_len;
2746         t = psk_or_pre_ms;
2747         memmove(psk_or_pre_ms + psk_len + 4, psk_or_pre_ms, psk_len);
2748         s2n(psk_len, t);
2749         memset(t, 0, psk_len);
2750         t += psk_len;
2751         s2n(psk_len, t);
2752
2753         if (s->session->psk_identity != NULL)
2754             OPENSSL_free(s->session->psk_identity);
2755         s->session->psk_identity = BUF_strdup((char *)p);
2756         if (s->session->psk_identity == NULL) {
2757             SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE, ERR_R_MALLOC_FAILURE);
2758             goto psk_err;
2759         }
2760
2761         if (s->session->psk_identity_hint != NULL)
2762             OPENSSL_free(s->session->psk_identity_hint);
2763         s->session->psk_identity_hint = BUF_strdup(s->ctx->psk_identity_hint);
2764         if (s->ctx->psk_identity_hint != NULL &&
2765             s->session->psk_identity_hint == NULL) {
2766             SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE, ERR_R_MALLOC_FAILURE);
2767             goto psk_err;
2768         }
2769
2770         s->session->master_key_length =
2771             s->method->ssl3_enc->generate_master_secret(s,
2772                                                         s->
2773                                                         session->master_key,
2774                                                         psk_or_pre_ms,
2775                                                         pre_ms_len);
2776         psk_err = 0;
2777  psk_err:
2778         OPENSSL_cleanse(psk_or_pre_ms, sizeof(psk_or_pre_ms));
2779         if (psk_err != 0)
2780             goto f_err;
2781     } else
2782 #endif
2783 #ifndef OPENSSL_NO_SRP
2784     if (alg_k & SSL_kSRP) {
2785         int param_len;
2786
2787         n2s(p, i);
2788         param_len = i + 2;
2789         if (param_len > n) {
2790             al = SSL_AD_DECODE_ERROR;
2791             SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,
2792                    SSL_R_BAD_SRP_A_LENGTH);
2793             goto f_err;
2794         }
2795         if (!(s->srp_ctx.A = BN_bin2bn(p, i, NULL))) {
2796             SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE, ERR_R_BN_LIB);
2797             goto err;
2798         }
2799         if (BN_ucmp(s->srp_ctx.A, s->srp_ctx.N) >= 0
2800             || BN_is_zero(s->srp_ctx.A)) {
2801             al = SSL_AD_ILLEGAL_PARAMETER;
2802             SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,
2803                    SSL_R_BAD_SRP_PARAMETERS);
2804             goto f_err;
2805         }
2806         if (s->session->srp_username != NULL)
2807             OPENSSL_free(s->session->srp_username);
2808         s->session->srp_username = BUF_strdup(s->srp_ctx.login);
2809         if (s->session->srp_username == NULL) {
2810             SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE, ERR_R_MALLOC_FAILURE);
2811             goto err;
2812         }
2813
2814         if ((s->session->master_key_length =
2815              SRP_generate_server_master_secret(s,
2816                                                s->session->master_key)) < 0) {
2817             SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE, ERR_R_INTERNAL_ERROR);
2818             goto err;
2819         }
2820
2821         p += i;
2822     } else
2823 #endif                          /* OPENSSL_NO_SRP */
2824     if (alg_k & SSL_kGOST) {
2825         int ret = 0;
2826         EVP_PKEY_CTX *pkey_ctx;
2827         EVP_PKEY *client_pub_pkey = NULL, *pk = NULL;
2828         unsigned char premaster_secret[32], *start;
2829         size_t outlen = 32, inlen;
2830         unsigned long alg_a;
2831         int Ttag, Tclass;
2832         long Tlen;
2833
2834         /* Get our certificate private key */
2835         alg_a = s->s3->tmp.new_cipher->algorithm_auth;
2836         if (alg_a & SSL_aGOST94)
2837             pk = s->cert->pkeys[SSL_PKEY_GOST94].privatekey;
2838         else if (alg_a & SSL_aGOST01)
2839             pk = s->cert->pkeys[SSL_PKEY_GOST01].privatekey;
2840
2841         pkey_ctx = EVP_PKEY_CTX_new(pk, NULL);
2842         EVP_PKEY_decrypt_init(pkey_ctx);
2843         /*
2844          * If client certificate is present and is of the same type, maybe
2845          * use it for key exchange.  Don't mind errors from
2846          * EVP_PKEY_derive_set_peer, because it is completely valid to use a
2847          * client certificate for authorization only.
2848          */
2849         client_pub_pkey = X509_get_pubkey(s->session->peer);
2850         if (client_pub_pkey) {
2851             if (EVP_PKEY_derive_set_peer(pkey_ctx, client_pub_pkey) <= 0)
2852                 ERR_clear_error();
2853         }
2854         /* Decrypt session key */
2855         if (ASN1_get_object
2856             ((const unsigned char **)&p, &Tlen, &Ttag, &Tclass,
2857              n) != V_ASN1_CONSTRUCTED || Ttag != V_ASN1_SEQUENCE
2858             || Tclass != V_ASN1_UNIVERSAL) {
2859             SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,
2860                    SSL_R_DECRYPTION_FAILED);
2861             goto gerr;
2862         }
2863         start = p;
2864         inlen = Tlen;
2865         if (EVP_PKEY_decrypt
2866             (pkey_ctx, premaster_secret, &outlen, start, inlen) <= 0) {
2867             SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,
2868                    SSL_R_DECRYPTION_FAILED);
2869             goto gerr;
2870         }
2871         /* Generate master secret */
2872         s->session->master_key_length =
2873             s->method->ssl3_enc->generate_master_secret(s,
2874                                                         s->
2875                                                         session->master_key,
2876                                                         premaster_secret, 32);
2877         /* Check if pubkey from client certificate was used */
2878         if (EVP_PKEY_CTX_ctrl
2879             (pkey_ctx, -1, -1, EVP_PKEY_CTRL_PEER_KEY, 2, NULL) > 0)
2880             ret = 2;
2881         else
2882             ret = 1;
2883  gerr:
2884         EVP_PKEY_free(client_pub_pkey);
2885         EVP_PKEY_CTX_free(pkey_ctx);
2886         if (ret)
2887             return ret;
2888         else
2889             goto err;
2890     } else {
2891         al = SSL_AD_HANDSHAKE_FAILURE;
2892         SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE, SSL_R_UNKNOWN_CIPHER_TYPE);
2893         goto f_err;
2894     }
2895
2896     return (1);
2897  f_err:
2898     ssl3_send_alert(s, SSL3_AL_FATAL, al);
2899 #if !defined(OPENSSL_NO_DH) || !defined(OPENSSL_NO_RSA) || !defined(OPENSSL_NO_ECDH) || defined(OPENSSL_NO_SRP)
2900  err:
2901 #endif
2902 #ifndef OPENSSL_NO_ECDH
2903     EVP_PKEY_free(clnt_pub_pkey);
2904     EC_POINT_free(clnt_ecpoint);
2905     if (srvr_ecdh != NULL)
2906         EC_KEY_free(srvr_ecdh);
2907     BN_CTX_free(bn_ctx);
2908 #endif
2909     return (-1);
2910 }
2911
2912 int ssl3_get_cert_verify(SSL *s)
2913 {
2914     EVP_PKEY *pkey = NULL;
2915     unsigned char *p;
2916     int al, ok, ret = 0;
2917     long n;
2918     int type = 0, i, j;
2919     X509 *peer;
2920     const EVP_MD *md = NULL;
2921     EVP_MD_CTX mctx;
2922     EVP_MD_CTX_init(&mctx);
2923
2924     n = s->method->ssl_get_message(s,
2925                                    SSL3_ST_SR_CERT_VRFY_A,
2926                                    SSL3_ST_SR_CERT_VRFY_B,
2927                                    -1, SSL3_RT_MAX_PLAIN_LENGTH, &ok);
2928
2929     if (!ok)
2930         return ((int)n);
2931
2932     if (s->session->peer != NULL) {
2933         peer = s->session->peer;
2934         pkey = X509_get_pubkey(peer);
2935         type = X509_certificate_type(peer, pkey);
2936     } else {
2937         peer = NULL;
2938         pkey = NULL;
2939     }
2940
2941     if (s->s3->tmp.message_type != SSL3_MT_CERTIFICATE_VERIFY) {
2942         s->s3->tmp.reuse_message = 1;
2943         if (peer != NULL) {
2944             al = SSL_AD_UNEXPECTED_MESSAGE;
2945             SSLerr(SSL_F_SSL3_GET_CERT_VERIFY, SSL_R_MISSING_VERIFY_MESSAGE);
2946             goto f_err;
2947         }
2948         ret = 1;
2949         goto end;
2950     }
2951
2952     if (peer == NULL) {
2953         SSLerr(SSL_F_SSL3_GET_CERT_VERIFY, SSL_R_NO_CLIENT_CERT_RECEIVED);
2954         al = SSL_AD_UNEXPECTED_MESSAGE;
2955         goto f_err;
2956     }
2957
2958     if (!(type & EVP_PKT_SIGN)) {
2959         SSLerr(SSL_F_SSL3_GET_CERT_VERIFY,
2960                SSL_R_SIGNATURE_FOR_NON_SIGNING_CERTIFICATE);
2961         al = SSL_AD_ILLEGAL_PARAMETER;
2962         goto f_err;
2963     }
2964
2965     if (s->s3->change_cipher_spec) {
2966         SSLerr(SSL_F_SSL3_GET_CERT_VERIFY, SSL_R_CCS_RECEIVED_EARLY);
2967         al = SSL_AD_UNEXPECTED_MESSAGE;
2968         goto f_err;
2969     }
2970
2971     /* we now have a signature that we need to verify */
2972     p = (unsigned char *)s->init_msg;
2973     /* Check for broken implementations of GOST ciphersuites */
2974     /*
2975      * If key is GOST and n is exactly 64, it is bare signature without
2976      * length field
2977      */
2978     if (n == 64 && (pkey->type == NID_id_GostR3410_94 ||
2979                     pkey->type == NID_id_GostR3410_2001)) {
2980         i = 64;
2981     } else {
2982         if (SSL_USE_SIGALGS(s)) {
2983             int rv = tls12_check_peer_sigalg(&md, s, p, pkey);
2984             if (rv == -1) {
2985                 al = SSL_AD_INTERNAL_ERROR;
2986                 goto f_err;
2987             } else if (rv == 0) {
2988                 al = SSL_AD_DECODE_ERROR;
2989                 goto f_err;
2990             }
2991 #ifdef SSL_DEBUG
2992             fprintf(stderr, "USING TLSv1.2 HASH %s\n", EVP_MD_name(md));
2993 #endif
2994             p += 2;
2995             n -= 2;
2996         }
2997         n2s(p, i);
2998         n -= 2;
2999         if (i > n) {
3000             SSLerr(SSL_F_SSL3_GET_CERT_VERIFY, SSL_R_LENGTH_MISMATCH);
3001             al = SSL_AD_DECODE_ERROR;
3002             goto f_err;
3003         }
3004     }
3005     j = EVP_PKEY_size(pkey);
3006     if ((i > j) || (n > j) || (n <= 0)) {
3007         SSLerr(SSL_F_SSL3_GET_CERT_VERIFY, SSL_R_WRONG_SIGNATURE_SIZE);
3008         al = SSL_AD_DECODE_ERROR;
3009         goto f_err;
3010     }
3011
3012     if (SSL_USE_SIGALGS(s)) {
3013         long hdatalen = 0;
3014         void *hdata;
3015         hdatalen = BIO_get_mem_data(s->s3->handshake_buffer, &hdata);
3016         if (hdatalen <= 0) {
3017             SSLerr(SSL_F_SSL3_GET_CERT_VERIFY, ERR_R_INTERNAL_ERROR);
3018             al = SSL_AD_INTERNAL_ERROR;
3019             goto f_err;
3020         }
3021 #ifdef SSL_DEBUG
3022         fprintf(stderr, "Using TLS 1.2 with client verify alg %s\n",
3023                 EVP_MD_name(md));
3024 #endif
3025         if (!EVP_VerifyInit_ex(&mctx, md, NULL)
3026             || !EVP_VerifyUpdate(&mctx, hdata, hdatalen)) {
3027             SSLerr(SSL_F_SSL3_GET_CERT_VERIFY, ERR_R_EVP_LIB);
3028             al = SSL_AD_INTERNAL_ERROR;
3029             goto f_err;
3030         }
3031
3032         if (EVP_VerifyFinal(&mctx, p, i, pkey) <= 0) {
3033             al = SSL_AD_DECRYPT_ERROR;
3034             SSLerr(SSL_F_SSL3_GET_CERT_VERIFY, SSL_R_BAD_SIGNATURE);
3035             goto f_err;
3036         }
3037     } else
3038 #ifndef OPENSSL_NO_RSA
3039     if (pkey->type == EVP_PKEY_RSA) {
3040         i = RSA_verify(NID_md5_sha1, s->s3->tmp.cert_verify_md,
3041                        MD5_DIGEST_LENGTH + SHA_DIGEST_LENGTH, p, i,
3042                        pkey->pkey.rsa);
3043         if (i < 0) {
3044             al = SSL_AD_DECRYPT_ERROR;
3045             SSLerr(SSL_F_SSL3_GET_CERT_VERIFY, SSL_R_BAD_RSA_DECRYPT);
3046             goto f_err;
3047         }
3048         if (i == 0) {
3049             al = SSL_AD_DECRYPT_ERROR;
3050             SSLerr(SSL_F_SSL3_GET_CERT_VERIFY, SSL_R_BAD_RSA_SIGNATURE);
3051             goto f_err;
3052         }
3053     } else
3054 #endif
3055 #ifndef OPENSSL_NO_DSA
3056     if (pkey->type == EVP_PKEY_DSA) {
3057         j = DSA_verify(pkey->save_type,
3058                        &(s->s3->tmp.cert_verify_md[MD5_DIGEST_LENGTH]),
3059                        SHA_DIGEST_LENGTH, p, i, pkey->pkey.dsa);
3060         if (j <= 0) {
3061             /* bad signature */
3062             al = SSL_AD_DECRYPT_ERROR;
3063             SSLerr(SSL_F_SSL3_GET_CERT_VERIFY, SSL_R_BAD_DSA_SIGNATURE);
3064             goto f_err;
3065         }
3066     } else
3067 #endif
3068 #ifndef OPENSSL_NO_ECDSA
3069     if (pkey->type == EVP_PKEY_EC) {
3070         j = ECDSA_verify(pkey->save_type,
3071                          &(s->s3->tmp.cert_verify_md[MD5_DIGEST_LENGTH]),
3072                          SHA_DIGEST_LENGTH, p, i, pkey->pkey.ec);
3073         if (j <= 0) {
3074             /* bad signature */
3075             al = SSL_AD_DECRYPT_ERROR;
3076             SSLerr(SSL_F_SSL3_GET_CERT_VERIFY, SSL_R_BAD_ECDSA_SIGNATURE);
3077             goto f_err;
3078         }
3079     } else
3080 #endif
3081     if (pkey->type == NID_id_GostR3410_94
3082             || pkey->type == NID_id_GostR3410_2001) {
3083         unsigned char signature[64];
3084         int idx;
3085         EVP_PKEY_CTX *pctx = EVP_PKEY_CTX_new(pkey, NULL);
3086         EVP_PKEY_verify_init(pctx);
3087         if (i != 64) {
3088             fprintf(stderr, "GOST signature length is %d", i);
3089         }
3090         for (idx = 0; idx < 64; idx++) {
3091             signature[63 - idx] = p[idx];
3092         }
3093         j = EVP_PKEY_verify(pctx, signature, 64, s->s3->tmp.cert_verify_md,
3094                             32);
3095         EVP_PKEY_CTX_free(pctx);
3096         if (j <= 0) {
3097             al = SSL_AD_DECRYPT_ERROR;
3098             SSLerr(SSL_F_SSL3_GET_CERT_VERIFY, SSL_R_BAD_ECDSA_SIGNATURE);
3099             goto f_err;
3100         }
3101     } else {
3102         SSLerr(SSL_F_SSL3_GET_CERT_VERIFY, ERR_R_INTERNAL_ERROR);
3103         al = SSL_AD_UNSUPPORTED_CERTIFICATE;
3104         goto f_err;
3105     }
3106
3107     ret = 1;
3108     if (0) {
3109  f_err:
3110         ssl3_send_alert(s, SSL3_AL_FATAL, al);
3111     }
3112  end:
3113     if (s->s3->handshake_buffer) {
3114         BIO_free(s->s3->handshake_buffer);
3115         s->s3->handshake_buffer = NULL;
3116         s->s3->flags &= ~TLS1_FLAGS_KEEP_HANDSHAKE;
3117     }
3118     EVP_MD_CTX_cleanup(&mctx);
3119     EVP_PKEY_free(pkey);
3120     return (ret);
3121 }
3122
3123 int ssl3_get_client_certificate(SSL *s)
3124 {
3125     int i, ok, al, ret = -1;
3126     X509 *x = NULL;
3127     unsigned long l, nc, llen, n;
3128     const unsigned char *p, *q;
3129     unsigned char *d;
3130     STACK_OF(X509) *sk = NULL;
3131
3132     n = s->method->ssl_get_message(s,
3133                                    SSL3_ST_SR_CERT_A,
3134                                    SSL3_ST_SR_CERT_B,
3135                                    -1, s->max_cert_list, &ok);
3136
3137     if (!ok)
3138         return ((int)n);
3139
3140     if (s->s3->tmp.message_type == SSL3_MT_CLIENT_KEY_EXCHANGE) {
3141         if ((s->verify_mode & SSL_VERIFY_PEER) &&
3142             (s->verify_mode & SSL_VERIFY_FAIL_IF_NO_PEER_CERT)) {
3143             SSLerr(SSL_F_SSL3_GET_CLIENT_CERTIFICATE,
3144                    SSL_R_PEER_DID_NOT_RETURN_A_CERTIFICATE);
3145             al = SSL_AD_HANDSHAKE_FAILURE;
3146             goto f_err;
3147         }
3148         /*
3149          * If tls asked for a client cert, the client must return a 0 list
3150          */
3151         if ((s->version > SSL3_VERSION) && s->s3->tmp.cert_request) {
3152             SSLerr(SSL_F_SSL3_GET_CLIENT_CERTIFICATE,
3153                    SSL_R_TLS_PEER_DID_NOT_RESPOND_WITH_CERTIFICATE_LIST);
3154             al = SSL_AD_UNEXPECTED_MESSAGE;
3155             goto f_err;
3156         }
3157         s->s3->tmp.reuse_message = 1;
3158         return (1);
3159     }
3160
3161     if (s->s3->tmp.message_type != SSL3_MT_CERTIFICATE) {
3162         al = SSL_AD_UNEXPECTED_MESSAGE;
3163         SSLerr(SSL_F_SSL3_GET_CLIENT_CERTIFICATE, SSL_R_WRONG_MESSAGE_TYPE);
3164         goto f_err;
3165     }
3166     p = d = (unsigned char *)s->init_msg;
3167
3168     if ((sk = sk_X509_new_null()) == NULL) {
3169         SSLerr(SSL_F_SSL3_GET_CLIENT_CERTIFICATE, ERR_R_MALLOC_FAILURE);
3170         goto err;
3171     }
3172
3173     n2l3(p, llen);
3174     if (llen + 3 != n) {
3175         al = SSL_AD_DECODE_ERROR;
3176         SSLerr(SSL_F_SSL3_GET_CLIENT_CERTIFICATE, SSL_R_LENGTH_MISMATCH);
3177         goto f_err;
3178     }
3179     for (nc = 0; nc < llen;) {
3180         n2l3(p, l);
3181         if ((l + nc + 3) > llen) {
3182             al = SSL_AD_DECODE_ERROR;
3183             SSLerr(SSL_F_SSL3_GET_CLIENT_CERTIFICATE,
3184                    SSL_R_CERT_LENGTH_MISMATCH);
3185             goto f_err;
3186         }
3187
3188         q = p;
3189         x = d2i_X509(NULL, &p, l);
3190         if (x == NULL) {
3191             SSLerr(SSL_F_SSL3_GET_CLIENT_CERTIFICATE, ERR_R_ASN1_LIB);
3192             goto err;
3193         }
3194         if (p != (q + l)) {
3195             al = SSL_AD_DECODE_ERROR;
3196             SSLerr(SSL_F_SSL3_GET_CLIENT_CERTIFICATE,
3197                    SSL_R_CERT_LENGTH_MISMATCH);
3198             goto f_err;
3199         }
3200         if (!sk_X509_push(sk, x)) {
3201             SSLerr(SSL_F_SSL3_GET_CLIENT_CERTIFICATE, ERR_R_MALLOC_FAILURE);
3202             goto err;
3203         }
3204         x = NULL;
3205         nc += l + 3;
3206     }
3207
3208     if (sk_X509_num(sk) <= 0) {
3209         /* TLS does not mind 0 certs returned */
3210         if (s->version == SSL3_VERSION) {
3211             al = SSL_AD_HANDSHAKE_FAILURE;
3212             SSLerr(SSL_F_SSL3_GET_CLIENT_CERTIFICATE,
3213                    SSL_R_NO_CERTIFICATES_RETURNED);
3214             goto f_err;
3215         }
3216         /* Fail for TLS only if we required a certificate */
3217         else if ((s->verify_mode & SSL_VERIFY_PEER) &&
3218                  (s->verify_mode & SSL_VERIFY_FAIL_IF_NO_PEER_CERT)) {
3219             SSLerr(SSL_F_SSL3_GET_CLIENT_CERTIFICATE,
3220                    SSL_R_PEER_DID_NOT_RETURN_A_CERTIFICATE);
3221             al = SSL_AD_HANDSHAKE_FAILURE;
3222             goto f_err;
3223         }
3224         /* No client certificate so digest cached records */
3225         if (s->s3->handshake_buffer && !ssl3_digest_cached_records(s)) {
3226             al = SSL_AD_INTERNAL_ERROR;
3227             goto f_err;
3228         }
3229     } else {
3230         i = ssl_verify_cert_chain(s, sk);
3231         if (i <= 0) {
3232             al = ssl_verify_alarm_type(s->verify_result);
3233             SSLerr(SSL_F_SSL3_GET_CLIENT_CERTIFICATE,
3234                    SSL_R_CERTIFICATE_VERIFY_FAILED);
3235             goto f_err;
3236         }
3237     }
3238
3239     if (s->session->peer != NULL) /* This should not be needed */
3240         X509_free(s->session->peer);
3241     s->session->peer = sk_X509_shift(sk);
3242     s->session->verify_result = s->verify_result;
3243
3244     /*
3245      * With the current implementation, sess_cert will always be NULL when we
3246      * arrive here.
3247      */
3248     if (s->session->sess_cert == NULL) {
3249         s->session->sess_cert = ssl_sess_cert_new();
3250         if (s->session->sess_cert == NULL) {
3251             SSLerr(SSL_F_SSL3_GET_CLIENT_CERTIFICATE, ERR_R_MALLOC_FAILURE);
3252             goto err;
3253         }
3254     }
3255     if (s->session->sess_cert->cert_chain != NULL)
3256         sk_X509_pop_free(s->session->sess_cert->cert_chain, X509_free);
3257     s->session->sess_cert->cert_chain = sk;
3258     /*
3259      * Inconsistency alert: cert_chain does *not* include the peer's own
3260      * certificate, while we do include it in s3_clnt.c
3261      */
3262
3263     sk = NULL;
3264
3265     ret = 1;
3266     if (0) {
3267  f_err:
3268         ssl3_send_alert(s, SSL3_AL_FATAL, al);
3269     }
3270  err:
3271     if (x != NULL)
3272         X509_free(x);
3273     if (sk != NULL)
3274         sk_X509_pop_free(sk, X509_free);
3275     return (ret);
3276 }
3277
3278 int ssl3_send_server_certificate(SSL *s)
3279 {
3280     CERT_PKEY *cpk;
3281
3282     if (s->state == SSL3_ST_SW_CERT_A) {
3283         cpk = ssl_get_server_send_pkey(s);
3284         if (cpk == NULL) {
3285             /* VRS: allow null cert if auth == KRB5 */
3286             if ((s->s3->tmp.new_cipher->algorithm_auth != SSL_aKRB5) ||
3287                 (s->s3->tmp.new_cipher->algorithm_mkey & SSL_kKRB5)) {
3288                 SSLerr(SSL_F_SSL3_SEND_SERVER_CERTIFICATE,
3289                        ERR_R_INTERNAL_ERROR);
3290                 return (0);
3291             }
3292         }
3293
3294         if (!ssl3_output_cert_chain(s, cpk)) {
3295             SSLerr(SSL_F_SSL3_SEND_SERVER_CERTIFICATE, ERR_R_INTERNAL_ERROR);
3296             return (0);
3297         }
3298         s->state = SSL3_ST_SW_CERT_B;
3299     }
3300
3301     /* SSL3_ST_SW_CERT_B */
3302     return ssl_do_write(s);
3303 }
3304
3305 #ifndef OPENSSL_NO_TLSEXT
3306 /* send a new session ticket (not necessarily for a new session) */
3307 int ssl3_send_newsession_ticket(SSL *s)
3308 {
3309     unsigned char *senc = NULL;
3310     EVP_CIPHER_CTX ctx;
3311     HMAC_CTX hctx;
3312
3313     if (s->state == SSL3_ST_SW_SESSION_TICKET_A) {
3314         unsigned char *p, *macstart;
3315         const unsigned char *const_p;
3316         int len, slen_full, slen;
3317         SSL_SESSION *sess;
3318         unsigned int hlen;
3319         SSL_CTX *tctx = s->initial_ctx;
3320         unsigned char iv[EVP_MAX_IV_LENGTH];
3321         unsigned char key_name[16];
3322
3323         /* get session encoding length */
3324         slen_full = i2d_SSL_SESSION(s->session, NULL);
3325         /*
3326          * Some length values are 16 bits, so forget it if session is too
3327          * long
3328          */
3329         if (slen_full == 0 || slen_full > 0xFF00)
3330             return -1;
3331         senc = OPENSSL_malloc(slen_full);
3332         if (!senc)
3333             return -1;
3334
3335         EVP_CIPHER_CTX_init(&ctx);
3336         HMAC_CTX_init(&hctx);
3337
3338         p = senc;
3339         if (!i2d_SSL_SESSION(s->session, &p))
3340             goto err;
3341
3342         /*
3343          * create a fresh copy (not shared with other threads) to clean up
3344          */
3345         const_p = senc;
3346         sess = d2i_SSL_SESSION(NULL, &const_p, slen_full);
3347         if (sess == NULL)
3348             goto err;
3349         sess->session_id_length = 0; /* ID is irrelevant for the ticket */
3350
3351         slen = i2d_SSL_SESSION(sess, NULL);
3352         if (slen == 0 || slen > slen_full) { /* shouldn't ever happen */
3353             SSL_SESSION_free(sess);
3354             goto err;
3355         }
3356         p = senc;
3357         if (!i2d_SSL_SESSION(sess, &p)) {
3358             SSL_SESSION_free(sess);
3359             goto err;
3360         }
3361         SSL_SESSION_free(sess);
3362
3363         /*-
3364          * Grow buffer if need be: the length calculation is as
3365          * follows handshake_header_length +
3366          * 4 (ticket lifetime hint) + 2 (ticket length) +
3367          * 16 (key name) + max_iv_len (iv length) +
3368          * session_length + max_enc_block_size (max encrypted session
3369          * length) + max_md_size (HMAC).
3370          */
3371         if (!BUF_MEM_grow(s->init_buf,
3372                           SSL_HM_HEADER_LENGTH(s) + 22 + EVP_MAX_IV_LENGTH +
3373                           EVP_MAX_BLOCK_LENGTH + EVP_MAX_MD_SIZE + slen))
3374             goto err;
3375
3376         p = ssl_handshake_start(s);
3377         /*
3378          * Initialize HMAC and cipher contexts. If callback present it does
3379          * all the work otherwise use generated values from parent ctx.
3380          */
3381         if (tctx->tlsext_ticket_key_cb) {
3382             if (tctx->tlsext_ticket_key_cb(s, key_name, iv, &ctx,
3383                                            &hctx, 1) < 0)
3384                 goto err;
3385         } else {
3386             if (RAND_bytes(iv, 16) <= 0)
3387                 goto err;
3388             if (!EVP_EncryptInit_ex(&ctx, EVP_aes_128_cbc(), NULL,
3389                                     tctx->tlsext_tick_aes_key, iv))
3390                 goto err;
3391             if (!HMAC_Init_ex(&hctx, tctx->tlsext_tick_hmac_key, 16,
3392                               tlsext_tick_md(), NULL))
3393                 goto err;
3394             memcpy(key_name, tctx->tlsext_tick_key_name, 16);
3395         }
3396
3397         /*
3398          * Ticket lifetime hint (advisory only): We leave this unspecified
3399          * for resumed session (for simplicity), and guess that tickets for
3400          * new sessions will live as long as their sessions.
3401          */
3402         l2n(s->hit ? 0 : s->session->timeout, p);
3403
3404         /* Skip ticket length for now */
3405         p += 2;
3406         /* Output key name */
3407         macstart = p;
3408         memcpy(p, key_name, 16);
3409         p += 16;
3410         /* output IV */
3411         memcpy(p, iv, EVP_CIPHER_CTX_iv_length(&ctx));
3412         p += EVP_CIPHER_CTX_iv_length(&ctx);
3413         /* Encrypt session data */
3414         if (!EVP_EncryptUpdate(&ctx, p, &len, senc, slen))
3415             goto err;
3416         p += len;
3417         if (!EVP_EncryptFinal(&ctx, p, &len))
3418             goto err;
3419         p += len;
3420
3421         if (!HMAC_Update(&hctx, macstart, p - macstart))
3422             goto err;
3423         if (!HMAC_Final(&hctx, p, &hlen))
3424             goto err;
3425
3426         EVP_CIPHER_CTX_cleanup(&ctx);
3427         HMAC_CTX_cleanup(&hctx);
3428
3429         p += hlen;
3430         /* Now write out lengths: p points to end of data written */
3431         /* Total length */
3432         len = p - ssl_handshake_start(s);
3433         /* Skip ticket lifetime hint */
3434         p = ssl_handshake_start(s) + 4;
3435         s2n(len - 6, p);
3436         ssl_set_handshake_header(s, SSL3_MT_NEWSESSION_TICKET, len);
3437         s->state = SSL3_ST_SW_SESSION_TICKET_B;
3438         OPENSSL_free(senc);
3439     }
3440
3441     /* SSL3_ST_SW_SESSION_TICKET_B */
3442     return ssl_do_write(s);
3443  err:
3444     if (senc)
3445         OPENSSL_free(senc);
3446     EVP_CIPHER_CTX_cleanup(&ctx);
3447     HMAC_CTX_cleanup(&hctx);
3448     return -1;
3449 }
3450
3451 int ssl3_send_cert_status(SSL *s)
3452 {
3453     if (s->state == SSL3_ST_SW_CERT_STATUS_A) {
3454         unsigned char *p;
3455         /*-
3456          * Grow buffer if need be: the length calculation is as
3457          * follows 1 (message type) + 3 (message length) +
3458          * 1 (ocsp response type) + 3 (ocsp response length)
3459          * + (ocsp response)
3460          */
3461         if (!BUF_MEM_grow(s->init_buf, 8 + s->tlsext_ocsp_resplen))
3462             return -1;
3463
3464         p = (unsigned char *)s->init_buf->data;
3465
3466         /* do the header */
3467         *(p++) = SSL3_MT_CERTIFICATE_STATUS;
3468         /* message length */
3469         l2n3(s->tlsext_ocsp_resplen + 4, p);
3470         /* status type */
3471         *(p++) = s->tlsext_status_type;
3472         /* length of OCSP response */
3473         l2n3(s->tlsext_ocsp_resplen, p);
3474         /* actual response */
3475         memcpy(p, s->tlsext_ocsp_resp, s->tlsext_ocsp_resplen);
3476         /* number of bytes to write */
3477         s->init_num = 8 + s->tlsext_ocsp_resplen;
3478         s->state = SSL3_ST_SW_CERT_STATUS_B;
3479         s->init_off = 0;
3480     }
3481
3482     /* SSL3_ST_SW_CERT_STATUS_B */
3483     return (ssl3_do_write(s, SSL3_RT_HANDSHAKE));
3484 }
3485
3486 # ifndef OPENSSL_NO_NEXTPROTONEG
3487 /*
3488  * ssl3_get_next_proto reads a Next Protocol Negotiation handshake message.
3489  * It sets the next_proto member in s if found
3490  */
3491 int ssl3_get_next_proto(SSL *s)
3492 {
3493     int ok;
3494     int proto_len, padding_len;
3495     long n;
3496     const unsigned char *p;
3497
3498     /*
3499      * Clients cannot send a NextProtocol message if we didn't see the
3500      * extension in their ClientHello
3501      */
3502     if (!s->s3->next_proto_neg_seen) {
3503         SSLerr(SSL_F_SSL3_GET_NEXT_PROTO,
3504                SSL_R_GOT_NEXT_PROTO_WITHOUT_EXTENSION);
3505         return -1;
3506     }
3507
3508     /* See the payload format below */
3509     n = s->method->ssl_get_message(s,
3510                                    SSL3_ST_SR_NEXT_PROTO_A,
3511                                    SSL3_ST_SR_NEXT_PROTO_B,
3512                                    SSL3_MT_NEXT_PROTO, 514, &ok);
3513
3514     if (!ok)
3515         return ((int)n);
3516
3517     /*
3518      * s->state doesn't reflect whether ChangeCipherSpec has been received in
3519      * this handshake, but s->s3->change_cipher_spec does (will be reset by
3520      * ssl3_get_finished).
3521      */
3522     if (!s->s3->change_cipher_spec) {
3523         SSLerr(SSL_F_SSL3_GET_NEXT_PROTO, SSL_R_GOT_NEXT_PROTO_BEFORE_A_CCS);
3524         return -1;
3525     }
3526
3527     if (n < 2)
3528         return 0;               /* The body must be > 1 bytes long */
3529
3530     p = (unsigned char *)s->init_msg;
3531
3532     /*-
3533      * The payload looks like:
3534      *   uint8 proto_len;
3535      *   uint8 proto[proto_len];
3536      *   uint8 padding_len;
3537      *   uint8 padding[padding_len];
3538      */
3539     proto_len = p[0];
3540     if (proto_len + 2 > s->init_num)
3541         return 0;
3542     padding_len = p[proto_len + 1];
3543     if (proto_len + padding_len + 2 != s->init_num)
3544         return 0;
3545
3546     s->next_proto_negotiated = OPENSSL_malloc(proto_len);
3547     if (!s->next_proto_negotiated) {
3548         SSLerr(SSL_F_SSL3_GET_NEXT_PROTO, ERR_R_MALLOC_FAILURE);
3549         return 0;
3550     }
3551     memcpy(s->next_proto_negotiated, p + 1, proto_len);
3552     s->next_proto_negotiated_len = proto_len;
3553
3554     return 1;
3555 }
3556 # endif
3557
3558 #endif