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