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