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