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