155714Skris/* ssl/s3_clnt.c */
255714Skris/* Copyright (C) 1995-1998 Eric Young (eay@cryptsoft.com)
355714Skris * All rights reserved.
455714Skris *
555714Skris * This package is an SSL implementation written
655714Skris * by Eric Young (eay@cryptsoft.com).
755714Skris * The implementation was written so as to conform with Netscapes SSL.
8280304Sjkim *
955714Skris * This library is free for commercial and non-commercial use as long as
1055714Skris * the following conditions are aheared to.  The following conditions
1155714Skris * apply to all code found in this distribution, be it the RC4, RSA,
1255714Skris * lhash, DES, etc., code; not just the SSL code.  The SSL documentation
1355714Skris * included with this distribution is covered by the same copyright terms
1455714Skris * except that the holder is Tim Hudson (tjh@cryptsoft.com).
15280304Sjkim *
1655714Skris * Copyright remains Eric Young's, and as such any Copyright notices in
1755714Skris * the code are not to be removed.
1855714Skris * If this package is used in a product, Eric Young should be given attribution
1955714Skris * as the author of the parts of the library used.
2055714Skris * This can be in the form of a textual message at program startup or
2155714Skris * in documentation (online or textual) provided with the package.
22280304Sjkim *
2355714Skris * Redistribution and use in source and binary forms, with or without
2455714Skris * modification, are permitted provided that the following conditions
2555714Skris * are met:
2655714Skris * 1. Redistributions of source code must retain the copyright
2755714Skris *    notice, this list of conditions and the following disclaimer.
2855714Skris * 2. Redistributions in binary form must reproduce the above copyright
2955714Skris *    notice, this list of conditions and the following disclaimer in the
3055714Skris *    documentation and/or other materials provided with the distribution.
3155714Skris * 3. All advertising materials mentioning features or use of this software
3255714Skris *    must display the following acknowledgement:
3355714Skris *    "This product includes cryptographic software written by
3455714Skris *     Eric Young (eay@cryptsoft.com)"
3555714Skris *    The word 'cryptographic' can be left out if the rouines from the library
3655714Skris *    being used are not cryptographic related :-).
37280304Sjkim * 4. If you include any Windows specific code (or a derivative thereof) from
3855714Skris *    the apps directory (application code) you must include an acknowledgement:
3955714Skris *    "This product includes software written by Tim Hudson (tjh@cryptsoft.com)"
40280304Sjkim *
4155714Skris * THIS SOFTWARE IS PROVIDED BY ERIC YOUNG ``AS IS'' AND
4255714Skris * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
4355714Skris * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
4455714Skris * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
4555714Skris * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
4655714Skris * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
4755714Skris * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
4855714Skris * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
4955714Skris * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
5055714Skris * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
5155714Skris * SUCH DAMAGE.
52280304Sjkim *
5355714Skris * The licence and distribution terms for any publically available version or
5455714Skris * derivative of this code cannot be changed.  i.e. this code cannot simply be
5555714Skris * copied and put under another distribution licence
5655714Skris * [including the GNU Public Licence.]
5755714Skris */
58100928Snectar/* ====================================================================
59238405Sjkim * Copyright (c) 1998-2007 The OpenSSL Project.  All rights reserved.
60100928Snectar *
61100928Snectar * Redistribution and use in source and binary forms, with or without
62100928Snectar * modification, are permitted provided that the following conditions
63100928Snectar * are met:
64100928Snectar *
65100928Snectar * 1. Redistributions of source code must retain the above copyright
66280304Sjkim *    notice, this list of conditions and the following disclaimer.
67100928Snectar *
68100928Snectar * 2. Redistributions in binary form must reproduce the above copyright
69100928Snectar *    notice, this list of conditions and the following disclaimer in
70100928Snectar *    the documentation and/or other materials provided with the
71100928Snectar *    distribution.
72100928Snectar *
73100928Snectar * 3. All advertising materials mentioning features or use of this
74100928Snectar *    software must display the following acknowledgment:
75100928Snectar *    "This product includes software developed by the OpenSSL Project
76100928Snectar *    for use in the OpenSSL Toolkit. (http://www.openssl.org/)"
77100928Snectar *
78100928Snectar * 4. The names "OpenSSL Toolkit" and "OpenSSL Project" must not be used to
79100928Snectar *    endorse or promote products derived from this software without
80100928Snectar *    prior written permission. For written permission, please contact
81100928Snectar *    openssl-core@openssl.org.
82100928Snectar *
83100928Snectar * 5. Products derived from this software may not be called "OpenSSL"
84100928Snectar *    nor may "OpenSSL" appear in their names without prior written
85100928Snectar *    permission of the OpenSSL Project.
86100928Snectar *
87100928Snectar * 6. Redistributions of any form whatsoever must retain the following
88100928Snectar *    acknowledgment:
89100928Snectar *    "This product includes software developed by the OpenSSL Project
90100928Snectar *    for use in the OpenSSL Toolkit (http://www.openssl.org/)"
91100928Snectar *
92100928Snectar * THIS SOFTWARE IS PROVIDED BY THE OpenSSL PROJECT ``AS IS'' AND ANY
93100928Snectar * EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
94100928Snectar * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
95100928Snectar * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE OpenSSL PROJECT OR
96100928Snectar * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
97100928Snectar * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
98100928Snectar * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
99100928Snectar * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
100100928Snectar * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
101100928Snectar * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
102100928Snectar * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
103100928Snectar * OF THE POSSIBILITY OF SUCH DAMAGE.
104100928Snectar * ====================================================================
105100928Snectar *
106100928Snectar * This product includes cryptographic software written by Eric Young
107100928Snectar * (eay@cryptsoft.com).  This product includes software written by Tim
108100928Snectar * Hudson (tjh@cryptsoft.com).
109100928Snectar *
110100928Snectar */
111160814Ssimon/* ====================================================================
112160814Ssimon * Copyright 2002 Sun Microsystems, Inc. ALL RIGHTS RESERVED.
113160814Ssimon *
114280304Sjkim * Portions of the attached software ("Contribution") are developed by
115160814Ssimon * SUN MICROSYSTEMS, INC., and are contributed to the OpenSSL project.
116160814Ssimon *
117160814Ssimon * The Contribution is licensed pursuant to the OpenSSL open source
118160814Ssimon * license provided above.
119160814Ssimon *
120160814Ssimon * ECC cipher suite support in OpenSSL originally written by
121160814Ssimon * Vipul Gupta and Sumit Gupta of Sun Microsystems Laboratories.
122160814Ssimon *
123160814Ssimon */
124238405Sjkim/* ====================================================================
125238405Sjkim * Copyright 2005 Nokia. All rights reserved.
126238405Sjkim *
127238405Sjkim * The portions of the attached software ("Contribution") is developed by
128238405Sjkim * Nokia Corporation and is licensed pursuant to the OpenSSL open source
129238405Sjkim * license.
130238405Sjkim *
131238405Sjkim * The Contribution, originally written by Mika Kousa and Pasi Eronen of
132238405Sjkim * Nokia Corporation, consists of the "PSK" (Pre-Shared Key) ciphersuites
133238405Sjkim * support (see RFC 4279) to OpenSSL.
134238405Sjkim *
135238405Sjkim * No patent licenses or other rights except those expressly stated in
136238405Sjkim * the OpenSSL open source license shall be deemed granted or received
137238405Sjkim * expressly, by implication, estoppel, or otherwise.
138238405Sjkim *
139238405Sjkim * No assurances are provided by Nokia that the Contribution does not
140238405Sjkim * infringe the patent or other intellectual property rights of any third
141238405Sjkim * party or that the license provides you with all the necessary rights
142238405Sjkim * to make use of the Contribution.
143238405Sjkim *
144238405Sjkim * THE SOFTWARE IS PROVIDED "AS IS" WITHOUT WARRANTY OF ANY KIND. IN
145238405Sjkim * ADDITION TO THE DISCLAIMERS INCLUDED IN THE LICENSE, NOKIA
146238405Sjkim * SPECIFICALLY DISCLAIMS ANY LIABILITY FOR CLAIMS BROUGHT BY YOU OR ANY
147238405Sjkim * OTHER ENTITY BASED ON INFRINGEMENT OF INTELLECTUAL PROPERTY RIGHTS OR
148238405Sjkim * OTHERWISE.
149238405Sjkim */
15055714Skris
15155714Skris#include <stdio.h>
152109998Smarkm#include "ssl_locl.h"
153109998Smarkm#include "kssl_lcl.h"
15455714Skris#include <openssl/buffer.h>
15555714Skris#include <openssl/rand.h>
15655714Skris#include <openssl/objects.h>
157109998Smarkm#include <openssl/evp.h>
15855714Skris#include <openssl/md5.h>
159194206Ssimon#ifdef OPENSSL_FIPS
160280304Sjkim# include <openssl/fips.h>
161194206Ssimon#endif
162160814Ssimon#ifndef OPENSSL_NO_DH
163280304Sjkim# include <openssl/dh.h>
164160814Ssimon#endif
165160814Ssimon#include <openssl/bn.h>
166194206Ssimon#ifndef OPENSSL_NO_ENGINE
167280304Sjkim# include <openssl/engine.h>
168194206Ssimon#endif
16955714Skris
170280304Sjkimstatic int ca_dn_cmp(const X509_NAME *const *a, const X509_NAME *const *b);
171284285Sjkim#ifndef OPENSSL_NO_TLSEXT
172284285Sjkimstatic int ssl3_check_finished(SSL *s);
173284285Sjkim#endif
174160814Ssimon
175276864Sjkim#ifndef OPENSSL_NO_SSL3_METHOD
176238405Sjkimstatic const SSL_METHOD *ssl3_get_client_method(int ver)
177280304Sjkim{
178280304Sjkim    if (ver == SSL3_VERSION)
179280304Sjkim        return (SSLv3_client_method());
180280304Sjkim    else
181280304Sjkim        return (NULL);
182280304Sjkim}
18355714Skris
184160814SsimonIMPLEMENT_ssl3_meth_func(SSLv3_client_method,
185280304Sjkim                         ssl_undefined_function,
186280304Sjkim                         ssl3_connect, ssl3_get_client_method)
187276864Sjkim#endif
18855714Skrisint ssl3_connect(SSL *s)
189280304Sjkim{
190280304Sjkim    BUF_MEM *buf = NULL;
191280304Sjkim    unsigned long Time = (unsigned long)time(NULL);
192280304Sjkim    void (*cb) (const SSL *ssl, int type, int val) = NULL;
193280304Sjkim    int ret = -1;
194280304Sjkim    int new_state, state, skip = 0;
19555714Skris
196280304Sjkim    RAND_add(&Time, sizeof(Time), 0);
197280304Sjkim    ERR_clear_error();
198280304Sjkim    clear_sys_error();
19955714Skris
200280304Sjkim    if (s->info_callback != NULL)
201280304Sjkim        cb = s->info_callback;
202280304Sjkim    else if (s->ctx->info_callback != NULL)
203280304Sjkim        cb = s->ctx->info_callback;
20455714Skris
205280304Sjkim    s->in_handshake++;
206280304Sjkim    if (!SSL_in_init(s) || SSL_in_before(s))
207280304Sjkim        SSL_clear(s);
208280304Sjkim
209238405Sjkim#ifndef OPENSSL_NO_HEARTBEATS
210280304Sjkim    /*
211280304Sjkim     * If we're awaiting a HeartbeatResponse, pretend we already got and
212280304Sjkim     * don't await it anymore, because Heartbeats don't make sense during
213280304Sjkim     * handshakes anyway.
214280304Sjkim     */
215280304Sjkim    if (s->tlsext_hb_pending) {
216280304Sjkim        s->tlsext_hb_pending = 0;
217280304Sjkim        s->tlsext_hb_seq++;
218280304Sjkim    }
219238405Sjkim#endif
220238405Sjkim
221280304Sjkim    for (;;) {
222280304Sjkim        state = s->state;
22355714Skris
224280304Sjkim        switch (s->state) {
225280304Sjkim        case SSL_ST_RENEGOTIATE:
226280304Sjkim            s->renegotiate = 1;
227280304Sjkim            s->state = SSL_ST_CONNECT;
228280304Sjkim            s->ctx->stats.sess_connect_renegotiate++;
229280304Sjkim            /* break */
230280304Sjkim        case SSL_ST_BEFORE:
231280304Sjkim        case SSL_ST_CONNECT:
232280304Sjkim        case SSL_ST_BEFORE | SSL_ST_CONNECT:
233280304Sjkim        case SSL_ST_OK | SSL_ST_CONNECT:
23455714Skris
235280304Sjkim            s->server = 0;
236280304Sjkim            if (cb != NULL)
237280304Sjkim                cb(s, SSL_CB_HANDSHAKE_START, 1);
23855714Skris
239280304Sjkim            if ((s->version & 0xff00) != 0x0300) {
240280304Sjkim                SSLerr(SSL_F_SSL3_CONNECT, ERR_R_INTERNAL_ERROR);
241284285Sjkim                s->state = SSL_ST_ERR;
242280304Sjkim                ret = -1;
243280304Sjkim                goto end;
244280304Sjkim            }
24555714Skris
246280304Sjkim            /* s->version=SSL3_VERSION; */
247280304Sjkim            s->type = SSL_ST_CONNECT;
24855714Skris
249280304Sjkim            if (s->init_buf == NULL) {
250280304Sjkim                if ((buf = BUF_MEM_new()) == NULL) {
251280304Sjkim                    ret = -1;
252284285Sjkim                    s->state = SSL_ST_ERR;
253280304Sjkim                    goto end;
254280304Sjkim                }
255280304Sjkim                if (!BUF_MEM_grow(buf, SSL3_RT_MAX_PLAIN_LENGTH)) {
256280304Sjkim                    ret = -1;
257284285Sjkim                    s->state = SSL_ST_ERR;
258280304Sjkim                    goto end;
259280304Sjkim                }
260280304Sjkim                s->init_buf = buf;
261280304Sjkim                buf = NULL;
262280304Sjkim            }
26355714Skris
264280304Sjkim            if (!ssl3_setup_buffers(s)) {
265280304Sjkim                ret = -1;
266280304Sjkim                goto end;
267280304Sjkim            }
26855714Skris
269280304Sjkim            /* setup buffing BIO */
270280304Sjkim            if (!ssl_init_wbio_buffer(s, 0)) {
271280304Sjkim                ret = -1;
272284285Sjkim                s->state = SSL_ST_ERR;
273280304Sjkim                goto end;
274280304Sjkim            }
27555714Skris
276280304Sjkim            /* don't push the buffering BIO quite yet */
27755714Skris
278280304Sjkim            ssl3_init_finished_mac(s);
27955714Skris
280280304Sjkim            s->state = SSL3_ST_CW_CLNT_HELLO_A;
281280304Sjkim            s->ctx->stats.sess_connect++;
282280304Sjkim            s->init_num = 0;
283280304Sjkim            s->s3->flags &= ~SSL3_FLAGS_CCS_OK;
284280304Sjkim            /*
285280304Sjkim             * Should have been reset by ssl3_get_finished, too.
286280304Sjkim             */
287280304Sjkim            s->s3->change_cipher_spec = 0;
288280304Sjkim            break;
28955714Skris
290280304Sjkim        case SSL3_ST_CW_CLNT_HELLO_A:
291280304Sjkim        case SSL3_ST_CW_CLNT_HELLO_B:
29255714Skris
293280304Sjkim            s->shutdown = 0;
294280304Sjkim            ret = ssl3_client_hello(s);
295280304Sjkim            if (ret <= 0)
296280304Sjkim                goto end;
297280304Sjkim            s->state = SSL3_ST_CR_SRVR_HELLO_A;
298280304Sjkim            s->init_num = 0;
29955714Skris
300280304Sjkim            /* turn on buffering for the next lot of output */
301280304Sjkim            if (s->bbio != s->wbio)
302280304Sjkim                s->wbio = BIO_push(s->bbio, s->wbio);
30355714Skris
304280304Sjkim            break;
305238405Sjkim
306280304Sjkim        case SSL3_ST_CR_SRVR_HELLO_A:
307280304Sjkim        case SSL3_ST_CR_SRVR_HELLO_B:
308280304Sjkim            ret = ssl3_get_server_hello(s);
309280304Sjkim            if (ret <= 0)
310280304Sjkim                goto end;
311280304Sjkim
312280304Sjkim            if (s->hit) {
313280304Sjkim                s->state = SSL3_ST_CR_FINISHED_A;
314238405Sjkim#ifndef OPENSSL_NO_TLSEXT
315280304Sjkim                if (s->tlsext_ticket_expected) {
316280304Sjkim                    /* receive renewed session ticket */
317280304Sjkim                    s->state = SSL3_ST_CR_SESSION_TICKET_A;
318280304Sjkim                }
319238405Sjkim#endif
320280304Sjkim            } else
321280304Sjkim                s->state = SSL3_ST_CR_CERT_A;
322280304Sjkim            s->init_num = 0;
323280304Sjkim            break;
32455714Skris
325280304Sjkim        case SSL3_ST_CR_CERT_A:
326280304Sjkim        case SSL3_ST_CR_CERT_B:
327284285Sjkim#ifndef OPENSSL_NO_TLSEXT
328284285Sjkim            /* Noop (ret = 0) for everything but EAP-FAST. */
329284285Sjkim            ret = ssl3_check_finished(s);
330284285Sjkim            if (ret < 0)
331284285Sjkim                goto end;
332284285Sjkim            if (ret == 1) {
333284285Sjkim                s->hit = 1;
334284285Sjkim                s->state = SSL3_ST_CR_FINISHED_A;
335284285Sjkim                s->init_num = 0;
336284285Sjkim                break;
337284285Sjkim            }
338284285Sjkim#endif
339280304Sjkim            /* Check if it is anon DH/ECDH, SRP auth */
340280304Sjkim            /* or PSK */
341280304Sjkim            if (!
342280304Sjkim                (s->s3->tmp.
343280304Sjkim                 new_cipher->algorithm_auth & (SSL_aNULL | SSL_aSRP))
344284285Sjkim                    && !(s->s3->tmp.new_cipher->algorithm_mkey & SSL_kPSK)) {
345280304Sjkim                ret = ssl3_get_server_certificate(s);
346280304Sjkim                if (ret <= 0)
347280304Sjkim                    goto end;
348194206Ssimon#ifndef OPENSSL_NO_TLSEXT
349280304Sjkim                if (s->tlsext_status_expected)
350280304Sjkim                    s->state = SSL3_ST_CR_CERT_STATUS_A;
351280304Sjkim                else
352280304Sjkim                    s->state = SSL3_ST_CR_KEY_EXCH_A;
353280304Sjkim            } else {
354280304Sjkim                skip = 1;
355280304Sjkim                s->state = SSL3_ST_CR_KEY_EXCH_A;
356280304Sjkim            }
357194206Ssimon#else
358280304Sjkim            } else
359280304Sjkim                skip = 1;
360194206Ssimon
361280304Sjkim            s->state = SSL3_ST_CR_KEY_EXCH_A;
362194206Ssimon#endif
363280304Sjkim            s->init_num = 0;
364280304Sjkim            break;
36555714Skris
366280304Sjkim        case SSL3_ST_CR_KEY_EXCH_A:
367280304Sjkim        case SSL3_ST_CR_KEY_EXCH_B:
368280304Sjkim            ret = ssl3_get_key_exchange(s);
369280304Sjkim            if (ret <= 0)
370280304Sjkim                goto end;
371280304Sjkim            s->state = SSL3_ST_CR_CERT_REQ_A;
372280304Sjkim            s->init_num = 0;
37355714Skris
374280304Sjkim            /*
375280304Sjkim             * at this point we check that we have the required stuff from
376280304Sjkim             * the server
377280304Sjkim             */
378280304Sjkim            if (!ssl3_check_cert_and_algorithm(s)) {
379280304Sjkim                ret = -1;
380284285Sjkim                s->state = SSL_ST_ERR;
381280304Sjkim                goto end;
382280304Sjkim            }
383280304Sjkim            break;
38455714Skris
385280304Sjkim        case SSL3_ST_CR_CERT_REQ_A:
386280304Sjkim        case SSL3_ST_CR_CERT_REQ_B:
387280304Sjkim            ret = ssl3_get_certificate_request(s);
388280304Sjkim            if (ret <= 0)
389280304Sjkim                goto end;
390280304Sjkim            s->state = SSL3_ST_CR_SRVR_DONE_A;
391280304Sjkim            s->init_num = 0;
392280304Sjkim            break;
39355714Skris
394280304Sjkim        case SSL3_ST_CR_SRVR_DONE_A:
395280304Sjkim        case SSL3_ST_CR_SRVR_DONE_B:
396280304Sjkim            ret = ssl3_get_server_done(s);
397280304Sjkim            if (ret <= 0)
398280304Sjkim                goto end;
399238405Sjkim#ifndef OPENSSL_NO_SRP
400280304Sjkim            if (s->s3->tmp.new_cipher->algorithm_mkey & SSL_kSRP) {
401280304Sjkim                if ((ret = SRP_Calc_A_param(s)) <= 0) {
402280304Sjkim                    SSLerr(SSL_F_SSL3_CONNECT, SSL_R_SRP_A_CALC);
403280304Sjkim                    ssl3_send_alert(s, SSL3_AL_FATAL, SSL_AD_INTERNAL_ERROR);
404284285Sjkim                    s->state = SSL_ST_ERR;
405280304Sjkim                    goto end;
406280304Sjkim                }
407280304Sjkim            }
408238405Sjkim#endif
409280304Sjkim            if (s->s3->tmp.cert_req)
410280304Sjkim                s->state = SSL3_ST_CW_CERT_A;
411280304Sjkim            else
412280304Sjkim                s->state = SSL3_ST_CW_KEY_EXCH_A;
413280304Sjkim            s->init_num = 0;
41455714Skris
415280304Sjkim            break;
41655714Skris
417280304Sjkim        case SSL3_ST_CW_CERT_A:
418280304Sjkim        case SSL3_ST_CW_CERT_B:
419280304Sjkim        case SSL3_ST_CW_CERT_C:
420280304Sjkim        case SSL3_ST_CW_CERT_D:
421280304Sjkim            ret = ssl3_send_client_certificate(s);
422280304Sjkim            if (ret <= 0)
423280304Sjkim                goto end;
424280304Sjkim            s->state = SSL3_ST_CW_KEY_EXCH_A;
425280304Sjkim            s->init_num = 0;
426280304Sjkim            break;
42755714Skris
428280304Sjkim        case SSL3_ST_CW_KEY_EXCH_A:
429280304Sjkim        case SSL3_ST_CW_KEY_EXCH_B:
430280304Sjkim            ret = ssl3_send_client_key_exchange(s);
431280304Sjkim            if (ret <= 0)
432280304Sjkim                goto end;
433280304Sjkim            /*
434280304Sjkim             * EAY EAY EAY need to check for DH fix cert sent back
435280304Sjkim             */
436280304Sjkim            /*
437280304Sjkim             * For TLS, cert_req is set to 2, so a cert chain of nothing is
438280304Sjkim             * sent, but no verify packet is sent
439280304Sjkim             */
440280304Sjkim            /*
441280304Sjkim             * XXX: For now, we do not support client authentication in ECDH
442280304Sjkim             * cipher suites with ECDH (rather than ECDSA) certificates. We
443280304Sjkim             * need to skip the certificate verify message when client's
444280304Sjkim             * ECDH public key is sent inside the client certificate.
445280304Sjkim             */
446280304Sjkim            if (s->s3->tmp.cert_req == 1) {
447280304Sjkim                s->state = SSL3_ST_CW_CERT_VRFY_A;
448280304Sjkim            } else {
449280304Sjkim                s->state = SSL3_ST_CW_CHANGE_A;
450280304Sjkim            }
451280304Sjkim            if (s->s3->flags & TLS1_FLAGS_SKIP_CERT_VERIFY) {
452280304Sjkim                s->state = SSL3_ST_CW_CHANGE_A;
453280304Sjkim            }
45455714Skris
455280304Sjkim            s->init_num = 0;
456280304Sjkim            break;
45755714Skris
458280304Sjkim        case SSL3_ST_CW_CERT_VRFY_A:
459280304Sjkim        case SSL3_ST_CW_CERT_VRFY_B:
460280304Sjkim            ret = ssl3_send_client_verify(s);
461280304Sjkim            if (ret <= 0)
462280304Sjkim                goto end;
463280304Sjkim            s->state = SSL3_ST_CW_CHANGE_A;
464280304Sjkim            s->init_num = 0;
465280304Sjkim            break;
46655714Skris
467280304Sjkim        case SSL3_ST_CW_CHANGE_A:
468280304Sjkim        case SSL3_ST_CW_CHANGE_B:
469280304Sjkim            ret = ssl3_send_change_cipher_spec(s,
470280304Sjkim                                               SSL3_ST_CW_CHANGE_A,
471280304Sjkim                                               SSL3_ST_CW_CHANGE_B);
472280304Sjkim            if (ret <= 0)
473280304Sjkim                goto end;
474238405Sjkim
475238405Sjkim#if defined(OPENSSL_NO_TLSEXT) || defined(OPENSSL_NO_NEXTPROTONEG)
476280304Sjkim            s->state = SSL3_ST_CW_FINISHED_A;
477238405Sjkim#else
478280304Sjkim            if (s->s3->next_proto_neg_seen)
479280304Sjkim                s->state = SSL3_ST_CW_NEXT_PROTO_A;
480280304Sjkim            else
481280304Sjkim                s->state = SSL3_ST_CW_FINISHED_A;
482238405Sjkim#endif
483280304Sjkim            s->init_num = 0;
48455714Skris
485280304Sjkim            s->session->cipher = s->s3->tmp.new_cipher;
486160814Ssimon#ifdef OPENSSL_NO_COMP
487280304Sjkim            s->session->compress_meth = 0;
488160814Ssimon#else
489280304Sjkim            if (s->s3->tmp.new_compression == NULL)
490280304Sjkim                s->session->compress_meth = 0;
491280304Sjkim            else
492280304Sjkim                s->session->compress_meth = s->s3->tmp.new_compression->id;
493160814Ssimon#endif
494280304Sjkim            if (!s->method->ssl3_enc->setup_key_block(s)) {
495280304Sjkim                ret = -1;
496284285Sjkim                s->state = SSL_ST_ERR;
497280304Sjkim                goto end;
498280304Sjkim            }
49955714Skris
500280304Sjkim            if (!s->method->ssl3_enc->change_cipher_state(s,
501280304Sjkim                                                          SSL3_CHANGE_CIPHER_CLIENT_WRITE))
502280304Sjkim            {
503280304Sjkim                ret = -1;
504284285Sjkim                s->state = SSL_ST_ERR;
505280304Sjkim                goto end;
506280304Sjkim            }
50755714Skris
508280304Sjkim            break;
50955714Skris
510238405Sjkim#if !defined(OPENSSL_NO_TLSEXT) && !defined(OPENSSL_NO_NEXTPROTONEG)
511280304Sjkim        case SSL3_ST_CW_NEXT_PROTO_A:
512280304Sjkim        case SSL3_ST_CW_NEXT_PROTO_B:
513280304Sjkim            ret = ssl3_send_next_proto(s);
514280304Sjkim            if (ret <= 0)
515280304Sjkim                goto end;
516280304Sjkim            s->state = SSL3_ST_CW_FINISHED_A;
517280304Sjkim            break;
518238405Sjkim#endif
519238405Sjkim
520280304Sjkim        case SSL3_ST_CW_FINISHED_A:
521280304Sjkim        case SSL3_ST_CW_FINISHED_B:
522280304Sjkim            ret = ssl3_send_finished(s,
523280304Sjkim                                     SSL3_ST_CW_FINISHED_A,
524280304Sjkim                                     SSL3_ST_CW_FINISHED_B,
525280304Sjkim                                     s->method->
526280304Sjkim                                     ssl3_enc->client_finished_label,
527280304Sjkim                                     s->method->
528280304Sjkim                                     ssl3_enc->client_finished_label_len);
529280304Sjkim            if (ret <= 0)
530280304Sjkim                goto end;
531280304Sjkim            s->state = SSL3_ST_CW_FLUSH;
53255714Skris
533280304Sjkim            /* clear flags */
534280304Sjkim            s->s3->flags &= ~SSL3_FLAGS_POP_BUFFER;
535280304Sjkim            if (s->hit) {
536280304Sjkim                s->s3->tmp.next_state = SSL_ST_OK;
537280304Sjkim                if (s->s3->flags & SSL3_FLAGS_DELAY_CLIENT_FINISHED) {
538280304Sjkim                    s->state = SSL_ST_OK;
539280304Sjkim                    s->s3->flags |= SSL3_FLAGS_POP_BUFFER;
540280304Sjkim                    s->s3->delay_buf_pop_ret = 0;
541280304Sjkim                }
542280304Sjkim            } else {
543194206Ssimon#ifndef OPENSSL_NO_TLSEXT
544280304Sjkim                /*
545280304Sjkim                 * Allow NewSessionTicket if ticket expected
546280304Sjkim                 */
547280304Sjkim                if (s->tlsext_ticket_expected)
548280304Sjkim                    s->s3->tmp.next_state = SSL3_ST_CR_SESSION_TICKET_A;
549280304Sjkim                else
550194206Ssimon#endif
55155714Skris
552280304Sjkim                    s->s3->tmp.next_state = SSL3_ST_CR_FINISHED_A;
553280304Sjkim            }
554280304Sjkim            s->init_num = 0;
555280304Sjkim            break;
556280304Sjkim
557194206Ssimon#ifndef OPENSSL_NO_TLSEXT
558280304Sjkim        case SSL3_ST_CR_SESSION_TICKET_A:
559280304Sjkim        case SSL3_ST_CR_SESSION_TICKET_B:
560280304Sjkim            ret = ssl3_get_new_session_ticket(s);
561280304Sjkim            if (ret <= 0)
562280304Sjkim                goto end;
563280304Sjkim            s->state = SSL3_ST_CR_FINISHED_A;
564280304Sjkim            s->init_num = 0;
565280304Sjkim            break;
566194206Ssimon
567280304Sjkim        case SSL3_ST_CR_CERT_STATUS_A:
568280304Sjkim        case SSL3_ST_CR_CERT_STATUS_B:
569280304Sjkim            ret = ssl3_get_cert_status(s);
570280304Sjkim            if (ret <= 0)
571280304Sjkim                goto end;
572280304Sjkim            s->state = SSL3_ST_CR_KEY_EXCH_A;
573280304Sjkim            s->init_num = 0;
574280304Sjkim            break;
575194206Ssimon#endif
576194206Ssimon
577280304Sjkim        case SSL3_ST_CR_FINISHED_A:
578280304Sjkim        case SSL3_ST_CR_FINISHED_B:
579284285Sjkim            if (!s->s3->change_cipher_spec)
580284285Sjkim                s->s3->flags |= SSL3_FLAGS_CCS_OK;
581280304Sjkim            ret = ssl3_get_finished(s, SSL3_ST_CR_FINISHED_A,
582280304Sjkim                                    SSL3_ST_CR_FINISHED_B);
583280304Sjkim            if (ret <= 0)
584280304Sjkim                goto end;
58555714Skris
586280304Sjkim            if (s->hit)
587280304Sjkim                s->state = SSL3_ST_CW_CHANGE_A;
588280304Sjkim            else
589280304Sjkim                s->state = SSL_ST_OK;
590280304Sjkim            s->init_num = 0;
591280304Sjkim            break;
59255714Skris
593280304Sjkim        case SSL3_ST_CW_FLUSH:
594280304Sjkim            s->rwstate = SSL_WRITING;
595280304Sjkim            if (BIO_flush(s->wbio) <= 0) {
596280304Sjkim                ret = -1;
597280304Sjkim                goto end;
598280304Sjkim            }
599280304Sjkim            s->rwstate = SSL_NOTHING;
600280304Sjkim            s->state = s->s3->tmp.next_state;
601280304Sjkim            break;
60255714Skris
603280304Sjkim        case SSL_ST_OK:
604280304Sjkim            /* clean a few things up */
605280304Sjkim            ssl3_cleanup_key_block(s);
60655714Skris
607280304Sjkim            if (s->init_buf != NULL) {
608280304Sjkim                BUF_MEM_free(s->init_buf);
609280304Sjkim                s->init_buf = NULL;
610280304Sjkim            }
61155714Skris
612280304Sjkim            /*
613280304Sjkim             * If we are not 'joining' the last two packets, remove the
614280304Sjkim             * buffering now
615280304Sjkim             */
616280304Sjkim            if (!(s->s3->flags & SSL3_FLAGS_POP_BUFFER))
617280304Sjkim                ssl_free_wbio_buffer(s);
618280304Sjkim            /* else do it later in ssl3_write */
61955714Skris
620280304Sjkim            s->init_num = 0;
621280304Sjkim            s->renegotiate = 0;
622280304Sjkim            s->new_session = 0;
62355714Skris
624280304Sjkim            ssl_update_cache(s, SSL_SESS_CACHE_CLIENT);
625280304Sjkim            if (s->hit)
626280304Sjkim                s->ctx->stats.sess_hit++;
62755714Skris
628280304Sjkim            ret = 1;
629280304Sjkim            /* s->server=0; */
630280304Sjkim            s->handshake_func = ssl3_connect;
631280304Sjkim            s->ctx->stats.sess_connect_good++;
63255714Skris
633280304Sjkim            if (cb != NULL)
634280304Sjkim                cb(s, SSL_CB_HANDSHAKE_DONE, 1);
63555714Skris
636280304Sjkim            goto end;
637280304Sjkim            /* break; */
63855714Skris
639284285Sjkim        case SSL_ST_ERR:
640280304Sjkim        default:
641280304Sjkim            SSLerr(SSL_F_SSL3_CONNECT, SSL_R_UNKNOWN_STATE);
642280304Sjkim            ret = -1;
643280304Sjkim            goto end;
644280304Sjkim            /* break; */
645280304Sjkim        }
64655714Skris
647280304Sjkim        /* did we do anything */
648280304Sjkim        if (!s->s3->tmp.reuse_message && !skip) {
649280304Sjkim            if (s->debug) {
650280304Sjkim                if ((ret = BIO_flush(s->wbio)) <= 0)
651280304Sjkim                    goto end;
652280304Sjkim            }
65355714Skris
654280304Sjkim            if ((cb != NULL) && (s->state != state)) {
655280304Sjkim                new_state = s->state;
656280304Sjkim                s->state = state;
657280304Sjkim                cb(s, SSL_CB_CONNECT_LOOP, 1);
658280304Sjkim                s->state = new_state;
659280304Sjkim            }
660280304Sjkim        }
661280304Sjkim        skip = 0;
662280304Sjkim    }
663280304Sjkim end:
664280304Sjkim    s->in_handshake--;
665280304Sjkim    if (buf != NULL)
666280304Sjkim        BUF_MEM_free(buf);
667280304Sjkim    if (cb != NULL)
668280304Sjkim        cb(s, SSL_CB_CONNECT_EXIT, ret);
669280304Sjkim    return (ret);
670280304Sjkim}
67155714Skris
672160814Ssimonint ssl3_client_hello(SSL *s)
673280304Sjkim{
674280304Sjkim    unsigned char *buf;
675280304Sjkim    unsigned char *p, *d;
676280304Sjkim    int i;
677280304Sjkim    unsigned long l;
678160814Ssimon#ifndef OPENSSL_NO_COMP
679280304Sjkim    int j;
680280304Sjkim    SSL_COMP *comp;
681160814Ssimon#endif
68255714Skris
683280304Sjkim    buf = (unsigned char *)s->init_buf->data;
684280304Sjkim    if (s->state == SSL3_ST_CW_CLNT_HELLO_A) {
685280304Sjkim        SSL_SESSION *sess = s->session;
686284285Sjkim        if ((sess == NULL) || (sess->ssl_version != s->version) ||
687284285Sjkim#ifdef OPENSSL_NO_TLSEXT
688284285Sjkim            !sess->session_id_length ||
689284285Sjkim#else
690284285Sjkim            /*
691284285Sjkim             * In the case of EAP-FAST, we can have a pre-shared
692284285Sjkim             * "ticket" without a session ID.
693284285Sjkim             */
694284285Sjkim            (!sess->session_id_length && !sess->tlsext_tick) ||
695284285Sjkim#endif
696284285Sjkim            (sess->not_resumable)) {
697280304Sjkim            if (!ssl_get_new_session(s, 0))
698280304Sjkim                goto err;
699280304Sjkim        }
700280304Sjkim        /* else use the pre-loaded session */
70155714Skris
702280304Sjkim        p = s->s3->client_random;
703264331Sjkim
704280304Sjkim        if (ssl_fill_hello_random(s, 0, p, SSL3_RANDOM_SIZE) <= 0)
705280304Sjkim            goto err;
70655714Skris
707280304Sjkim        /* Do the message type and length last */
708280304Sjkim        d = p = &(buf[4]);
70955714Skris
710280304Sjkim        /*-
711280304Sjkim         * version indicates the negotiated version: for example from
712280304Sjkim         * an SSLv2/v3 compatible client hello). The client_version
713280304Sjkim         * field is the maximum version we permit and it is also
714280304Sjkim         * used in RSA encrypted premaster secrets. Some servers can
715280304Sjkim         * choke if we initially report a higher version then
716280304Sjkim         * renegotiate to a lower one in the premaster secret. This
717280304Sjkim         * didn't happen with TLS 1.0 as most servers supported it
718280304Sjkim         * but it can with TLS 1.1 or later if the server only supports
719280304Sjkim         * 1.0.
720280304Sjkim         *
721280304Sjkim         * Possible scenario with previous logic:
722280304Sjkim         *      1. Client hello indicates TLS 1.2
723280304Sjkim         *      2. Server hello says TLS 1.0
724280304Sjkim         *      3. RSA encrypted premaster secret uses 1.2.
725280304Sjkim         *      4. Handhaked proceeds using TLS 1.0.
726280304Sjkim         *      5. Server sends hello request to renegotiate.
727280304Sjkim         *      6. Client hello indicates TLS v1.0 as we now
728280304Sjkim         *         know that is maximum server supports.
729280304Sjkim         *      7. Server chokes on RSA encrypted premaster secret
730280304Sjkim         *         containing version 1.0.
731280304Sjkim         *
732280304Sjkim         * For interoperability it should be OK to always use the
733280304Sjkim         * maximum version we support in client hello and then rely
734280304Sjkim         * on the checking of version to ensure the servers isn't
735280304Sjkim         * being inconsistent: for example initially negotiating with
736280304Sjkim         * TLS 1.0 and renegotiating with TLS 1.2. We do this by using
737280304Sjkim         * client_version in client hello and not resetting it to
738280304Sjkim         * the negotiated version.
739280304Sjkim         */
740238405Sjkim#if 0
741280304Sjkim        *(p++) = s->version >> 8;
742280304Sjkim        *(p++) = s->version & 0xff;
743280304Sjkim        s->client_version = s->version;
744238405Sjkim#else
745280304Sjkim        *(p++) = s->client_version >> 8;
746280304Sjkim        *(p++) = s->client_version & 0xff;
747238405Sjkim#endif
74855714Skris
749280304Sjkim        /* Random stuff */
750280304Sjkim        memcpy(p, s->s3->client_random, SSL3_RANDOM_SIZE);
751280304Sjkim        p += SSL3_RANDOM_SIZE;
75255714Skris
753280304Sjkim        /* Session ID */
754280304Sjkim        if (s->new_session)
755280304Sjkim            i = 0;
756280304Sjkim        else
757280304Sjkim            i = s->session->session_id_length;
758280304Sjkim        *(p++) = i;
759280304Sjkim        if (i != 0) {
760280304Sjkim            if (i > (int)sizeof(s->session->session_id)) {
761280304Sjkim                SSLerr(SSL_F_SSL3_CLIENT_HELLO, ERR_R_INTERNAL_ERROR);
762280304Sjkim                goto err;
763280304Sjkim            }
764280304Sjkim            memcpy(p, s->session->session_id, i);
765280304Sjkim            p += i;
766280304Sjkim        }
767280304Sjkim
768280304Sjkim        /* Ciphers supported */
769280304Sjkim        i = ssl_cipher_list_to_bytes(s, SSL_get_ciphers(s), &(p[2]), 0);
770280304Sjkim        if (i == 0) {
771280304Sjkim            SSLerr(SSL_F_SSL3_CLIENT_HELLO, SSL_R_NO_CIPHERS_AVAILABLE);
772280304Sjkim            goto err;
773280304Sjkim        }
774238405Sjkim#ifdef OPENSSL_MAX_TLS1_2_CIPHER_LENGTH
775280304Sjkim        /*
776280304Sjkim         * Some servers hang if client hello > 256 bytes as hack workaround
777280304Sjkim         * chop number of supported ciphers to keep it well below this if we
778280304Sjkim         * use TLS v1.2
779280304Sjkim         */
780280304Sjkim        if (TLS1_get_version(s) >= TLS1_2_VERSION
781280304Sjkim            && i > OPENSSL_MAX_TLS1_2_CIPHER_LENGTH)
782280304Sjkim            i = OPENSSL_MAX_TLS1_2_CIPHER_LENGTH & ~1;
783238405Sjkim#endif
784280304Sjkim        s2n(i, p);
785280304Sjkim        p += i;
78655714Skris
787280304Sjkim        /* COMPRESSION */
788160814Ssimon#ifdef OPENSSL_NO_COMP
789280304Sjkim        *(p++) = 1;
790160814Ssimon#else
791238405Sjkim
792280304Sjkim        if ((s->options & SSL_OP_NO_COMPRESSION)
793280304Sjkim            || !s->ctx->comp_methods)
794280304Sjkim            j = 0;
795280304Sjkim        else
796280304Sjkim            j = sk_SSL_COMP_num(s->ctx->comp_methods);
797280304Sjkim        *(p++) = 1 + j;
798280304Sjkim        for (i = 0; i < j; i++) {
799280304Sjkim            comp = sk_SSL_COMP_value(s->ctx->comp_methods, i);
800280304Sjkim            *(p++) = comp->id;
801280304Sjkim        }
802160814Ssimon#endif
803280304Sjkim        *(p++) = 0;             /* Add the NULL method */
804238405Sjkim
805194206Ssimon#ifndef OPENSSL_NO_TLSEXT
806280304Sjkim        /* TLS extensions */
807280304Sjkim        if (ssl_prepare_clienthello_tlsext(s) <= 0) {
808280304Sjkim            SSLerr(SSL_F_SSL3_CLIENT_HELLO, SSL_R_CLIENTHELLO_TLSEXT);
809280304Sjkim            goto err;
810280304Sjkim        }
811280304Sjkim        if ((p =
812280304Sjkim             ssl_add_clienthello_tlsext(s, p,
813280304Sjkim                                        buf + SSL3_RT_MAX_PLAIN_LENGTH)) ==
814280304Sjkim            NULL) {
815280304Sjkim            SSLerr(SSL_F_SSL3_CLIENT_HELLO, ERR_R_INTERNAL_ERROR);
816280304Sjkim            goto err;
817280304Sjkim        }
818238405Sjkim#endif
81955714Skris
820280304Sjkim        l = (p - d);
821280304Sjkim        d = buf;
822280304Sjkim        *(d++) = SSL3_MT_CLIENT_HELLO;
823280304Sjkim        l2n3(l, d);
82455714Skris
825280304Sjkim        s->state = SSL3_ST_CW_CLNT_HELLO_B;
826280304Sjkim        /* number of bytes to write */
827280304Sjkim        s->init_num = p - buf;
828280304Sjkim        s->init_off = 0;
829280304Sjkim    }
83055714Skris
831280304Sjkim    /* SSL3_ST_CW_CLNT_HELLO_B */
832280304Sjkim    return (ssl3_do_write(s, SSL3_RT_HANDSHAKE));
833280304Sjkim err:
834284285Sjkim    s->state = SSL_ST_ERR;
835280304Sjkim    return (-1);
836280304Sjkim}
837280304Sjkim
838160814Ssimonint ssl3_get_server_hello(SSL *s)
839280304Sjkim{
840280304Sjkim    STACK_OF(SSL_CIPHER) *sk;
841280304Sjkim    const SSL_CIPHER *c;
842280304Sjkim    unsigned char *p, *d;
843280304Sjkim    int i, al, ok;
844280304Sjkim    unsigned int j;
845280304Sjkim    long n;
846160814Ssimon#ifndef OPENSSL_NO_COMP
847280304Sjkim    SSL_COMP *comp;
848160814Ssimon#endif
84955714Skris
850280304Sjkim    n = s->method->ssl_get_message(s,
851280304Sjkim                                   SSL3_ST_CR_SRVR_HELLO_A,
852280304Sjkim                                   SSL3_ST_CR_SRVR_HELLO_B, -1, 20000, &ok);
85355714Skris
854280304Sjkim    if (!ok)
855280304Sjkim        return ((int)n);
856160814Ssimon
857280304Sjkim    if (SSL_version(s) == DTLS1_VERSION || SSL_version(s) == DTLS1_BAD_VER) {
858280304Sjkim        if (s->s3->tmp.message_type == DTLS1_MT_HELLO_VERIFY_REQUEST) {
859280304Sjkim            if (s->d1->send_cookie == 0) {
860280304Sjkim                s->s3->tmp.reuse_message = 1;
861280304Sjkim                return 1;
862280304Sjkim            } else {            /* already sent a cookie */
863160814Ssimon
864280304Sjkim                al = SSL_AD_UNEXPECTED_MESSAGE;
865280304Sjkim                SSLerr(SSL_F_SSL3_GET_SERVER_HELLO, SSL_R_BAD_MESSAGE_TYPE);
866280304Sjkim                goto f_err;
867280304Sjkim            }
868280304Sjkim        }
869280304Sjkim    }
87055714Skris
871280304Sjkim    if (s->s3->tmp.message_type != SSL3_MT_SERVER_HELLO) {
872280304Sjkim        al = SSL_AD_UNEXPECTED_MESSAGE;
873280304Sjkim        SSLerr(SSL_F_SSL3_GET_SERVER_HELLO, SSL_R_BAD_MESSAGE_TYPE);
874280304Sjkim        goto f_err;
875280304Sjkim    }
87655714Skris
877280304Sjkim    d = p = (unsigned char *)s->init_msg;
87855714Skris
879280304Sjkim    if ((p[0] != (s->version >> 8)) || (p[1] != (s->version & 0xff))) {
880280304Sjkim        SSLerr(SSL_F_SSL3_GET_SERVER_HELLO, SSL_R_WRONG_SSL_VERSION);
881280304Sjkim        s->version = (s->version & 0xff00) | p[1];
882280304Sjkim        al = SSL_AD_PROTOCOL_VERSION;
883280304Sjkim        goto f_err;
884280304Sjkim    }
885280304Sjkim    p += 2;
886276864Sjkim
887280304Sjkim    /* load the server hello data */
888280304Sjkim    /* load the server random */
889280304Sjkim    memcpy(s->s3->server_random, p, SSL3_RANDOM_SIZE);
890280304Sjkim    p += SSL3_RANDOM_SIZE;
89155714Skris
892280304Sjkim    s->hit = 0;
893109998Smarkm
894280304Sjkim    /* get the session-id */
895280304Sjkim    j = *(p++);
896280304Sjkim
897280304Sjkim    if ((j > sizeof s->session->session_id) || (j > SSL3_SESSION_ID_SIZE)) {
898280304Sjkim        al = SSL_AD_ILLEGAL_PARAMETER;
899280304Sjkim        SSLerr(SSL_F_SSL3_GET_SERVER_HELLO, SSL_R_SSL3_SESSION_ID_TOO_LONG);
900280304Sjkim        goto f_err;
901280304Sjkim    }
902238405Sjkim#ifndef OPENSSL_NO_TLSEXT
903280304Sjkim    /*
904284285Sjkim     * Check if we can resume the session based on external pre-shared secret.
905284285Sjkim     * EAP-FAST (RFC 4851) supports two types of session resumption.
906284285Sjkim     * Resumption based on server-side state works with session IDs.
907284285Sjkim     * Resumption based on pre-shared Protected Access Credentials (PACs)
908284285Sjkim     * works by overriding the SessionTicket extension at the application
909284285Sjkim     * layer, and does not send a session ID. (We do not know whether EAP-FAST
910284285Sjkim     * servers would honour the session ID.) Therefore, the session ID alone
911284285Sjkim     * is not a reliable indicator of session resumption, so we first check if
912284285Sjkim     * we can resume, and later peek at the next handshake message to see if the
913284285Sjkim     * server wants to resume.
914280304Sjkim     */
915284285Sjkim    if (s->version >= TLS1_VERSION && s->tls_session_secret_cb &&
916284285Sjkim        s->session->tlsext_tick) {
917280304Sjkim        SSL_CIPHER *pref_cipher = NULL;
918280304Sjkim        s->session->master_key_length = sizeof(s->session->master_key);
919280304Sjkim        if (s->tls_session_secret_cb(s, s->session->master_key,
920280304Sjkim                                     &s->session->master_key_length,
921280304Sjkim                                     NULL, &pref_cipher,
922280304Sjkim                                     s->tls_session_secret_cb_arg)) {
923280304Sjkim            s->session->cipher = pref_cipher ?
924280304Sjkim                pref_cipher : ssl_get_cipher_by_char(s, p + j);
925284285Sjkim        } else {
926284285Sjkim            SSLerr(SSL_F_SSL3_GET_SERVER_HELLO, ERR_R_INTERNAL_ERROR);
927284285Sjkim            al = SSL_AD_INTERNAL_ERROR;
928284285Sjkim            goto f_err;
929280304Sjkim        }
930280304Sjkim    }
931280304Sjkim#endif                          /* OPENSSL_NO_TLSEXT */
932238405Sjkim
933284285Sjkim    if (j != 0 && j == s->session->session_id_length
934280304Sjkim        && memcmp(p, s->session->session_id, j) == 0) {
935280304Sjkim        if (s->sid_ctx_length != s->session->sid_ctx_length
936280304Sjkim            || memcmp(s->session->sid_ctx, s->sid_ctx, s->sid_ctx_length)) {
937280304Sjkim            /* actually a client application bug */
938280304Sjkim            al = SSL_AD_ILLEGAL_PARAMETER;
939280304Sjkim            SSLerr(SSL_F_SSL3_GET_SERVER_HELLO,
940280304Sjkim                   SSL_R_ATTEMPT_TO_REUSE_SESSION_IN_DIFFERENT_CONTEXT);
941280304Sjkim            goto f_err;
942280304Sjkim        }
943280304Sjkim        s->hit = 1;
944284285Sjkim    } else {
945280304Sjkim        /*
946284285Sjkim         * If we were trying for session-id reuse but the server
947284285Sjkim         * didn't echo the ID, make a new SSL_SESSION.
948284285Sjkim         * In the case of EAP-FAST and PAC, we do not send a session ID,
949284285Sjkim         * so the PAC-based session secret is always preserved. It'll be
950284285Sjkim         * overwritten if the server refuses resumption.
951280304Sjkim         */
952280304Sjkim        if (s->session->session_id_length > 0) {
953280304Sjkim            if (!ssl_get_new_session(s, 0)) {
954280304Sjkim                al = SSL_AD_INTERNAL_ERROR;
955280304Sjkim                goto f_err;
956280304Sjkim            }
957280304Sjkim        }
958280304Sjkim        s->session->session_id_length = j;
959280304Sjkim        memcpy(s->session->session_id, p, j); /* j could be 0 */
960280304Sjkim    }
961280304Sjkim    p += j;
962280304Sjkim    c = ssl_get_cipher_by_char(s, p);
963280304Sjkim    if (c == NULL) {
964280304Sjkim        /* unknown cipher */
965280304Sjkim        al = SSL_AD_ILLEGAL_PARAMETER;
966280304Sjkim        SSLerr(SSL_F_SSL3_GET_SERVER_HELLO, SSL_R_UNKNOWN_CIPHER_RETURNED);
967280304Sjkim        goto f_err;
968280304Sjkim    }
969280304Sjkim    /* TLS v1.2 only ciphersuites require v1.2 or later */
970280304Sjkim    if ((c->algorithm_ssl & SSL_TLSV1_2) &&
971280304Sjkim        (TLS1_get_version(s) < TLS1_2_VERSION)) {
972280304Sjkim        al = SSL_AD_ILLEGAL_PARAMETER;
973280304Sjkim        SSLerr(SSL_F_SSL3_GET_SERVER_HELLO, SSL_R_WRONG_CIPHER_RETURNED);
974280304Sjkim        goto f_err;
975280304Sjkim    }
976269686Sjkim#ifndef OPENSSL_NO_SRP
977280304Sjkim    if (((c->algorithm_mkey & SSL_kSRP) || (c->algorithm_auth & SSL_aSRP)) &&
978280304Sjkim        !(s->srp_ctx.srp_Mask & SSL_kSRP)) {
979280304Sjkim        al = SSL_AD_ILLEGAL_PARAMETER;
980280304Sjkim        SSLerr(SSL_F_SSL3_GET_SERVER_HELLO, SSL_R_WRONG_CIPHER_RETURNED);
981280304Sjkim        goto f_err;
982280304Sjkim    }
983280304Sjkim#endif                          /* OPENSSL_NO_SRP */
984280304Sjkim    p += ssl_put_cipher_by_char(s, NULL, NULL);
98555714Skris
986280304Sjkim    sk = ssl_get_ciphers_by_id(s);
987280304Sjkim    i = sk_SSL_CIPHER_find(sk, c);
988280304Sjkim    if (i < 0) {
989280304Sjkim        /* we did not say we would use this cipher */
990280304Sjkim        al = SSL_AD_ILLEGAL_PARAMETER;
991280304Sjkim        SSLerr(SSL_F_SSL3_GET_SERVER_HELLO, SSL_R_WRONG_CIPHER_RETURNED);
992280304Sjkim        goto f_err;
993280304Sjkim    }
99455714Skris
995280304Sjkim    /*
996280304Sjkim     * Depending on the session caching (internal/external), the cipher
997280304Sjkim     * and/or cipher_id values may not be set. Make sure that cipher_id is
998280304Sjkim     * set and use it for comparison.
999280304Sjkim     */
1000280304Sjkim    if (s->session->cipher)
1001280304Sjkim        s->session->cipher_id = s->session->cipher->id;
1002280304Sjkim    if (s->hit && (s->session->cipher_id != c->id)) {
1003216166Ssimon/* Workaround is now obsolete */
1004216166Ssimon#if 0
1005280304Sjkim        if (!(s->options & SSL_OP_NETSCAPE_REUSE_CIPHER_CHANGE_BUG))
1006216166Ssimon#endif
1007280304Sjkim        {
1008280304Sjkim            al = SSL_AD_ILLEGAL_PARAMETER;
1009280304Sjkim            SSLerr(SSL_F_SSL3_GET_SERVER_HELLO,
1010280304Sjkim                   SSL_R_OLD_SESSION_CIPHER_NOT_RETURNED);
1011280304Sjkim            goto f_err;
1012280304Sjkim        }
1013280304Sjkim    }
1014280304Sjkim    s->s3->tmp.new_cipher = c;
1015280304Sjkim    /*
1016280304Sjkim     * Don't digest cached records if TLS v1.2: we may need them for client
1017280304Sjkim     * authentication.
1018280304Sjkim     */
1019280304Sjkim    if (TLS1_get_version(s) < TLS1_2_VERSION
1020280304Sjkim        && !ssl3_digest_cached_records(s)) {
1021280304Sjkim        al = SSL_AD_INTERNAL_ERROR;
1022280304Sjkim        goto f_err;
1023280304Sjkim    }
1024280304Sjkim    /* lets get the compression algorithm */
1025280304Sjkim    /* COMPRESSION */
1026160814Ssimon#ifdef OPENSSL_NO_COMP
1027280304Sjkim    if (*(p++) != 0) {
1028280304Sjkim        al = SSL_AD_ILLEGAL_PARAMETER;
1029280304Sjkim        SSLerr(SSL_F_SSL3_GET_SERVER_HELLO,
1030280304Sjkim               SSL_R_UNSUPPORTED_COMPRESSION_ALGORITHM);
1031280304Sjkim        goto f_err;
1032280304Sjkim    }
1033280304Sjkim    /*
1034280304Sjkim     * If compression is disabled we'd better not try to resume a session
1035280304Sjkim     * using compression.
1036280304Sjkim     */
1037280304Sjkim    if (s->session->compress_meth != 0) {
1038280304Sjkim        al = SSL_AD_INTERNAL_ERROR;
1039280304Sjkim        SSLerr(SSL_F_SSL3_GET_SERVER_HELLO, SSL_R_INCONSISTENT_COMPRESSION);
1040280304Sjkim        goto f_err;
1041280304Sjkim    }
1042160814Ssimon#else
1043280304Sjkim    j = *(p++);
1044280304Sjkim    if (s->hit && j != s->session->compress_meth) {
1045280304Sjkim        al = SSL_AD_ILLEGAL_PARAMETER;
1046280304Sjkim        SSLerr(SSL_F_SSL3_GET_SERVER_HELLO,
1047280304Sjkim               SSL_R_OLD_SESSION_COMPRESSION_ALGORITHM_NOT_RETURNED);
1048280304Sjkim        goto f_err;
1049280304Sjkim    }
1050280304Sjkim    if (j == 0)
1051280304Sjkim        comp = NULL;
1052280304Sjkim    else if (s->options & SSL_OP_NO_COMPRESSION) {
1053280304Sjkim        al = SSL_AD_ILLEGAL_PARAMETER;
1054280304Sjkim        SSLerr(SSL_F_SSL3_GET_SERVER_HELLO, SSL_R_COMPRESSION_DISABLED);
1055280304Sjkim        goto f_err;
1056280304Sjkim    } else
1057280304Sjkim        comp = ssl3_comp_find(s->ctx->comp_methods, j);
1058280304Sjkim
1059280304Sjkim    if ((j != 0) && (comp == NULL)) {
1060280304Sjkim        al = SSL_AD_ILLEGAL_PARAMETER;
1061280304Sjkim        SSLerr(SSL_F_SSL3_GET_SERVER_HELLO,
1062280304Sjkim               SSL_R_UNSUPPORTED_COMPRESSION_ALGORITHM);
1063280304Sjkim        goto f_err;
1064280304Sjkim    } else {
1065280304Sjkim        s->s3->tmp.new_compression = comp;
1066280304Sjkim    }
1067160814Ssimon#endif
1068238405Sjkim
1069194206Ssimon#ifndef OPENSSL_NO_TLSEXT
1070280304Sjkim    /* TLS extensions */
1071280304Sjkim    if (s->version >= SSL3_VERSION) {
1072280304Sjkim        if (!ssl_parse_serverhello_tlsext(s, &p, d, n, &al)) {
1073280304Sjkim            /* 'al' set by ssl_parse_serverhello_tlsext */
1074280304Sjkim            SSLerr(SSL_F_SSL3_GET_SERVER_HELLO, SSL_R_PARSE_TLSEXT);
1075280304Sjkim            goto f_err;
1076280304Sjkim        }
1077280304Sjkim        if (ssl_check_serverhello_tlsext(s) <= 0) {
1078280304Sjkim            SSLerr(SSL_F_SSL3_GET_SERVER_HELLO, SSL_R_SERVERHELLO_TLSEXT);
1079280304Sjkim            goto err;
1080280304Sjkim        }
1081280304Sjkim    }
1082194206Ssimon#endif
108355714Skris
1084280304Sjkim    if (p != (d + n)) {
1085280304Sjkim        /* wrong packet length */
1086280304Sjkim        al = SSL_AD_DECODE_ERROR;
1087280304Sjkim        SSLerr(SSL_F_SSL3_GET_SERVER_HELLO, SSL_R_BAD_PACKET_LENGTH);
1088280304Sjkim        goto f_err;
1089280304Sjkim    }
109055714Skris
1091280304Sjkim    return (1);
1092280304Sjkim f_err:
1093280304Sjkim    ssl3_send_alert(s, SSL3_AL_FATAL, al);
1094280304Sjkim err:
1095284285Sjkim    s->state = SSL_ST_ERR;
1096280304Sjkim    return (-1);
1097280304Sjkim}
109855714Skris
1099160814Ssimonint ssl3_get_server_certificate(SSL *s)
1100280304Sjkim{
1101280304Sjkim    int al, i, ok, ret = -1;
1102280304Sjkim    unsigned long n, nc, llen, l;
1103280304Sjkim    X509 *x = NULL;
1104280304Sjkim    const unsigned char *q, *p;
1105280304Sjkim    unsigned char *d;
1106280304Sjkim    STACK_OF(X509) *sk = NULL;
1107280304Sjkim    SESS_CERT *sc;
1108280304Sjkim    EVP_PKEY *pkey = NULL;
1109280304Sjkim    int need_cert = 1;          /* VRS: 0=> will allow null cert if auth ==
1110280304Sjkim                                 * KRB5 */
111155714Skris
1112280304Sjkim    n = s->method->ssl_get_message(s,
1113280304Sjkim                                   SSL3_ST_CR_CERT_A,
1114280304Sjkim                                   SSL3_ST_CR_CERT_B,
1115280304Sjkim                                   -1, s->max_cert_list, &ok);
111655714Skris
1117280304Sjkim    if (!ok)
1118280304Sjkim        return ((int)n);
111955714Skris
1120280304Sjkim    if ((s->s3->tmp.message_type == SSL3_MT_SERVER_KEY_EXCHANGE) ||
1121280304Sjkim        ((s->s3->tmp.new_cipher->algorithm_auth & SSL_aKRB5) &&
1122280304Sjkim         (s->s3->tmp.message_type == SSL3_MT_SERVER_DONE))) {
1123280304Sjkim        s->s3->tmp.reuse_message = 1;
1124280304Sjkim        return (1);
1125280304Sjkim    }
112655714Skris
1127280304Sjkim    if (s->s3->tmp.message_type != SSL3_MT_CERTIFICATE) {
1128280304Sjkim        al = SSL_AD_UNEXPECTED_MESSAGE;
1129280304Sjkim        SSLerr(SSL_F_SSL3_GET_SERVER_CERTIFICATE, SSL_R_BAD_MESSAGE_TYPE);
1130280304Sjkim        goto f_err;
1131280304Sjkim    }
1132280304Sjkim    p = d = (unsigned char *)s->init_msg;
113355714Skris
1134280304Sjkim    if ((sk = sk_X509_new_null()) == NULL) {
1135280304Sjkim        SSLerr(SSL_F_SSL3_GET_SERVER_CERTIFICATE, ERR_R_MALLOC_FAILURE);
1136280304Sjkim        goto err;
1137280304Sjkim    }
113855714Skris
1139280304Sjkim    n2l3(p, llen);
1140280304Sjkim    if (llen + 3 != n) {
1141280304Sjkim        al = SSL_AD_DECODE_ERROR;
1142280304Sjkim        SSLerr(SSL_F_SSL3_GET_SERVER_CERTIFICATE, SSL_R_LENGTH_MISMATCH);
1143280304Sjkim        goto f_err;
1144280304Sjkim    }
1145280304Sjkim    for (nc = 0; nc < llen;) {
1146306230Sdelphij        if (nc + 3 > llen) {
1147306230Sdelphij            al = SSL_AD_DECODE_ERROR;
1148306230Sdelphij            SSLerr(SSL_F_SSL3_GET_SERVER_CERTIFICATE,
1149306230Sdelphij                   SSL_R_CERT_LENGTH_MISMATCH);
1150306230Sdelphij            goto f_err;
1151306230Sdelphij        }
1152280304Sjkim        n2l3(p, l);
1153280304Sjkim        if ((l + nc + 3) > llen) {
1154280304Sjkim            al = SSL_AD_DECODE_ERROR;
1155280304Sjkim            SSLerr(SSL_F_SSL3_GET_SERVER_CERTIFICATE,
1156280304Sjkim                   SSL_R_CERT_LENGTH_MISMATCH);
1157280304Sjkim            goto f_err;
1158280304Sjkim        }
115955714Skris
1160280304Sjkim        q = p;
1161280304Sjkim        x = d2i_X509(NULL, &q, l);
1162280304Sjkim        if (x == NULL) {
1163280304Sjkim            al = SSL_AD_BAD_CERTIFICATE;
1164280304Sjkim            SSLerr(SSL_F_SSL3_GET_SERVER_CERTIFICATE, ERR_R_ASN1_LIB);
1165280304Sjkim            goto f_err;
1166280304Sjkim        }
1167280304Sjkim        if (q != (p + l)) {
1168280304Sjkim            al = SSL_AD_DECODE_ERROR;
1169280304Sjkim            SSLerr(SSL_F_SSL3_GET_SERVER_CERTIFICATE,
1170280304Sjkim                   SSL_R_CERT_LENGTH_MISMATCH);
1171280304Sjkim            goto f_err;
1172280304Sjkim        }
1173280304Sjkim        if (!sk_X509_push(sk, x)) {
1174280304Sjkim            SSLerr(SSL_F_SSL3_GET_SERVER_CERTIFICATE, ERR_R_MALLOC_FAILURE);
1175280304Sjkim            goto err;
1176280304Sjkim        }
1177280304Sjkim        x = NULL;
1178280304Sjkim        nc += l + 3;
1179280304Sjkim        p = q;
1180280304Sjkim    }
118155714Skris
1182280304Sjkim    i = ssl_verify_cert_chain(s, sk);
1183280304Sjkim    if ((s->verify_mode != SSL_VERIFY_NONE) && (i <= 0)
1184109998Smarkm#ifndef OPENSSL_NO_KRB5
1185280304Sjkim        && !((s->s3->tmp.new_cipher->algorithm_mkey & SSL_kKRB5) &&
1186280304Sjkim             (s->s3->tmp.new_cipher->algorithm_auth & SSL_aKRB5))
1187280304Sjkim#endif                          /* OPENSSL_NO_KRB5 */
1188280304Sjkim        ) {
1189280304Sjkim        al = ssl_verify_alarm_type(s->verify_result);
1190280304Sjkim        SSLerr(SSL_F_SSL3_GET_SERVER_CERTIFICATE,
1191280304Sjkim               SSL_R_CERTIFICATE_VERIFY_FAILED);
1192280304Sjkim        goto f_err;
1193280304Sjkim    }
1194280304Sjkim    ERR_clear_error();          /* but we keep s->verify_result */
119555714Skris
1196280304Sjkim    sc = ssl_sess_cert_new();
1197280304Sjkim    if (sc == NULL)
1198280304Sjkim        goto err;
119955714Skris
1200280304Sjkim    if (s->session->sess_cert)
1201280304Sjkim        ssl_sess_cert_free(s->session->sess_cert);
1202280304Sjkim    s->session->sess_cert = sc;
120355714Skris
1204280304Sjkim    sc->cert_chain = sk;
1205280304Sjkim    /*
1206280304Sjkim     * Inconsistency alert: cert_chain does include the peer's certificate,
1207280304Sjkim     * which we don't include in s3_srvr.c
1208280304Sjkim     */
1209280304Sjkim    x = sk_X509_value(sk, 0);
1210280304Sjkim    sk = NULL;
1211280304Sjkim    /*
1212280304Sjkim     * VRS 19990621: possible memory leak; sk=null ==> !sk_pop_free() @end
1213280304Sjkim     */
121455714Skris
1215280304Sjkim    pkey = X509_get_pubkey(x);
121655714Skris
1217280304Sjkim    /* VRS: allow null cert if auth == KRB5 */
1218280304Sjkim    need_cert = ((s->s3->tmp.new_cipher->algorithm_mkey & SSL_kKRB5) &&
1219280304Sjkim                 (s->s3->tmp.new_cipher->algorithm_auth & SSL_aKRB5))
1220280304Sjkim        ? 0 : 1;
1221109998Smarkm
1222109998Smarkm#ifdef KSSL_DEBUG
1223280304Sjkim    fprintf(stderr, "pkey,x = %p, %p\n", pkey, x);
1224280304Sjkim    fprintf(stderr, "ssl_cert_type(x,pkey) = %d\n", ssl_cert_type(x, pkey));
1225280304Sjkim    fprintf(stderr, "cipher, alg, nc = %s, %lx, %lx, %d\n",
1226280304Sjkim            s->s3->tmp.new_cipher->name,
1227280304Sjkim            s->s3->tmp.new_cipher->algorithm_mkey,
1228280304Sjkim            s->s3->tmp.new_cipher->algorithm_auth, need_cert);
1229280304Sjkim#endif                          /* KSSL_DEBUG */
1230109998Smarkm
1231280304Sjkim    if (need_cert && ((pkey == NULL) || EVP_PKEY_missing_parameters(pkey))) {
1232280304Sjkim        x = NULL;
1233280304Sjkim        al = SSL3_AL_FATAL;
1234280304Sjkim        SSLerr(SSL_F_SSL3_GET_SERVER_CERTIFICATE,
1235280304Sjkim               SSL_R_UNABLE_TO_FIND_PUBLIC_KEY_PARAMETERS);
1236280304Sjkim        goto f_err;
1237280304Sjkim    }
123855714Skris
1239280304Sjkim    i = ssl_cert_type(x, pkey);
1240280304Sjkim    if (need_cert && i < 0) {
1241280304Sjkim        x = NULL;
1242280304Sjkim        al = SSL3_AL_FATAL;
1243280304Sjkim        SSLerr(SSL_F_SSL3_GET_SERVER_CERTIFICATE,
1244280304Sjkim               SSL_R_UNKNOWN_CERTIFICATE_TYPE);
1245280304Sjkim        goto f_err;
1246280304Sjkim    }
124755714Skris
1248280304Sjkim    if (need_cert) {
1249280304Sjkim        sc->peer_cert_type = i;
1250280304Sjkim        CRYPTO_add(&x->references, 1, CRYPTO_LOCK_X509);
1251280304Sjkim        /*
1252280304Sjkim         * Why would the following ever happen? We just created sc a couple
1253280304Sjkim         * of lines ago.
1254280304Sjkim         */
1255280304Sjkim        if (sc->peer_pkeys[i].x509 != NULL)
1256280304Sjkim            X509_free(sc->peer_pkeys[i].x509);
1257280304Sjkim        sc->peer_pkeys[i].x509 = x;
1258280304Sjkim        sc->peer_key = &(sc->peer_pkeys[i]);
125955714Skris
1260280304Sjkim        if (s->session->peer != NULL)
1261280304Sjkim            X509_free(s->session->peer);
1262280304Sjkim        CRYPTO_add(&x->references, 1, CRYPTO_LOCK_X509);
1263280304Sjkim        s->session->peer = x;
1264280304Sjkim    } else {
1265280304Sjkim        sc->peer_cert_type = i;
1266280304Sjkim        sc->peer_key = NULL;
1267109998Smarkm
1268280304Sjkim        if (s->session->peer != NULL)
1269280304Sjkim            X509_free(s->session->peer);
1270280304Sjkim        s->session->peer = NULL;
1271280304Sjkim    }
1272280304Sjkim    s->session->verify_result = s->verify_result;
127355714Skris
1274280304Sjkim    x = NULL;
1275280304Sjkim    ret = 1;
127655714Skris
1277280304Sjkim    if (0) {
1278280304Sjkim f_err:
1279280304Sjkim        ssl3_send_alert(s, SSL3_AL_FATAL, al);
1280284285Sjkim err:
1281284285Sjkim        s->state = SSL_ST_ERR;
1282280304Sjkim    }
1283284285Sjkim
1284280304Sjkim    EVP_PKEY_free(pkey);
1285280304Sjkim    X509_free(x);
1286280304Sjkim    sk_X509_pop_free(sk, X509_free);
1287280304Sjkim    return (ret);
1288280304Sjkim}
128955714Skris
1290160814Ssimonint ssl3_get_key_exchange(SSL *s)
1291280304Sjkim{
1292109998Smarkm#ifndef OPENSSL_NO_RSA
1293280304Sjkim    unsigned char *q, md_buf[EVP_MAX_MD_SIZE * 2];
129455714Skris#endif
1295280304Sjkim    EVP_MD_CTX md_ctx;
1296280304Sjkim    unsigned char *param, *p;
1297280304Sjkim    int al, j, ok;
1298280304Sjkim    long i, param_len, n, alg_k, alg_a;
1299280304Sjkim    EVP_PKEY *pkey = NULL;
1300280304Sjkim    const EVP_MD *md = NULL;
1301109998Smarkm#ifndef OPENSSL_NO_RSA
1302280304Sjkim    RSA *rsa = NULL;
130355714Skris#endif
1304109998Smarkm#ifndef OPENSSL_NO_DH
1305280304Sjkim    DH *dh = NULL;
130655714Skris#endif
1307160814Ssimon#ifndef OPENSSL_NO_ECDH
1308280304Sjkim    EC_KEY *ecdh = NULL;
1309280304Sjkim    BN_CTX *bn_ctx = NULL;
1310280304Sjkim    EC_POINT *srvr_ecpoint = NULL;
1311280304Sjkim    int curve_nid = 0;
1312280304Sjkim    int encoded_pt_len = 0;
1313160814Ssimon#endif
131455714Skris
1315280304Sjkim    EVP_MD_CTX_init(&md_ctx);
1316276864Sjkim
1317280304Sjkim    /*
1318280304Sjkim     * use same message size as in ssl3_get_certificate_request() as
1319280304Sjkim     * ServerKeyExchange message may be skipped
1320280304Sjkim     */
1321280304Sjkim    n = s->method->ssl_get_message(s,
1322280304Sjkim                                   SSL3_ST_CR_KEY_EXCH_A,
1323280304Sjkim                                   SSL3_ST_CR_KEY_EXCH_B,
1324280304Sjkim                                   -1, s->max_cert_list, &ok);
1325280304Sjkim    if (!ok)
1326280304Sjkim        return ((int)n);
132755714Skris
1328280304Sjkim    alg_k = s->s3->tmp.new_cipher->algorithm_mkey;
1329276864Sjkim
1330280304Sjkim    if (s->s3->tmp.message_type != SSL3_MT_SERVER_KEY_EXCHANGE) {
1331280304Sjkim        /*
1332280304Sjkim         * Can't skip server key exchange if this is an ephemeral
1333280304Sjkim         * ciphersuite.
1334280304Sjkim         */
1335280304Sjkim        if (alg_k & (SSL_kEDH | SSL_kEECDH)) {
1336280304Sjkim            SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE, SSL_R_UNEXPECTED_MESSAGE);
1337280304Sjkim            al = SSL_AD_UNEXPECTED_MESSAGE;
1338280304Sjkim            goto f_err;
1339280304Sjkim        }
1340238405Sjkim#ifndef OPENSSL_NO_PSK
1341280304Sjkim        /*
1342280304Sjkim         * In plain PSK ciphersuite, ServerKeyExchange can be omitted if no
1343280304Sjkim         * identity hint is sent. Set session->sess_cert anyway to avoid
1344280304Sjkim         * problems later.
1345280304Sjkim         */
1346280304Sjkim        if (alg_k & SSL_kPSK) {
1347280304Sjkim            s->session->sess_cert = ssl_sess_cert_new();
1348280304Sjkim            if (s->ctx->psk_identity_hint)
1349280304Sjkim                OPENSSL_free(s->ctx->psk_identity_hint);
1350280304Sjkim            s->ctx->psk_identity_hint = NULL;
1351280304Sjkim        }
1352238405Sjkim#endif
1353280304Sjkim        s->s3->tmp.reuse_message = 1;
1354280304Sjkim        return (1);
1355280304Sjkim    }
135655714Skris
1357280304Sjkim    param = p = (unsigned char *)s->init_msg;
1358280304Sjkim    if (s->session->sess_cert != NULL) {
1359109998Smarkm#ifndef OPENSSL_NO_RSA
1360280304Sjkim        if (s->session->sess_cert->peer_rsa_tmp != NULL) {
1361280304Sjkim            RSA_free(s->session->sess_cert->peer_rsa_tmp);
1362280304Sjkim            s->session->sess_cert->peer_rsa_tmp = NULL;
1363280304Sjkim        }
136455714Skris#endif
1365109998Smarkm#ifndef OPENSSL_NO_DH
1366280304Sjkim        if (s->session->sess_cert->peer_dh_tmp) {
1367280304Sjkim            DH_free(s->session->sess_cert->peer_dh_tmp);
1368280304Sjkim            s->session->sess_cert->peer_dh_tmp = NULL;
1369280304Sjkim        }
137055714Skris#endif
1371160814Ssimon#ifndef OPENSSL_NO_ECDH
1372280304Sjkim        if (s->session->sess_cert->peer_ecdh_tmp) {
1373280304Sjkim            EC_KEY_free(s->session->sess_cert->peer_ecdh_tmp);
1374280304Sjkim            s->session->sess_cert->peer_ecdh_tmp = NULL;
1375280304Sjkim        }
1376160814Ssimon#endif
1377280304Sjkim    } else {
1378280304Sjkim        s->session->sess_cert = ssl_sess_cert_new();
1379280304Sjkim    }
138055714Skris
1381280304Sjkim    /* Total length of the parameters including the length prefix */
1382280304Sjkim    param_len = 0;
1383273149Sjkim
1384280304Sjkim    alg_a = s->s3->tmp.new_cipher->algorithm_auth;
138555714Skris
1386280304Sjkim    al = SSL_AD_DECODE_ERROR;
1387273149Sjkim
1388238405Sjkim#ifndef OPENSSL_NO_PSK
1389280304Sjkim    if (alg_k & SSL_kPSK) {
1390280304Sjkim        param_len = 2;
1391280304Sjkim        if (param_len > n) {
1392280304Sjkim            SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE, SSL_R_LENGTH_TOO_SHORT);
1393280304Sjkim            goto f_err;
1394280304Sjkim        }
1395280304Sjkim        n2s(p, i);
1396273149Sjkim
1397280304Sjkim        /*
1398280304Sjkim         * Store PSK identity hint for later use, hint is used in
1399280304Sjkim         * ssl3_send_client_key_exchange.  Assume that the maximum length of
1400280304Sjkim         * a PSK identity hint can be as long as the maximum length of a PSK
1401280304Sjkim         * identity.
1402280304Sjkim         */
1403280304Sjkim        if (i > PSK_MAX_IDENTITY_LEN) {
1404280304Sjkim            al = SSL_AD_HANDSHAKE_FAILURE;
1405280304Sjkim            SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE, SSL_R_DATA_LENGTH_TOO_LONG);
1406280304Sjkim            goto f_err;
1407280304Sjkim        }
1408280304Sjkim        if (i > n - param_len) {
1409280304Sjkim            SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,
1410280304Sjkim                   SSL_R_BAD_PSK_IDENTITY_HINT_LENGTH);
1411280304Sjkim            goto f_err;
1412280304Sjkim        }
1413280304Sjkim        param_len += i;
1414273149Sjkim
1415285330Sjkim        s->session->psk_identity_hint = BUF_strndup((char *)p, i);
1416285330Sjkim        if (s->session->psk_identity_hint == NULL) {
1417280304Sjkim            al = SSL_AD_HANDSHAKE_FAILURE;
1418280304Sjkim            SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE, ERR_R_MALLOC_FAILURE);
1419280304Sjkim            goto f_err;
1420280304Sjkim        }
1421238405Sjkim
1422280304Sjkim        p += i;
1423280304Sjkim        n -= param_len;
1424280304Sjkim    } else
1425280304Sjkim#endif                          /* !OPENSSL_NO_PSK */
1426238405Sjkim#ifndef OPENSSL_NO_SRP
1427280304Sjkim    if (alg_k & SSL_kSRP) {
1428280304Sjkim        param_len = 2;
1429280304Sjkim        if (param_len > n) {
1430280304Sjkim            SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE, SSL_R_LENGTH_TOO_SHORT);
1431280304Sjkim            goto f_err;
1432280304Sjkim        }
1433280304Sjkim        n2s(p, i);
1434273149Sjkim
1435280304Sjkim        if (i > n - param_len) {
1436280304Sjkim            SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE, SSL_R_BAD_SRP_N_LENGTH);
1437280304Sjkim            goto f_err;
1438280304Sjkim        }
1439280304Sjkim        param_len += i;
1440273149Sjkim
1441280304Sjkim        if (!(s->srp_ctx.N = BN_bin2bn(p, i, NULL))) {
1442280304Sjkim            SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE, ERR_R_BN_LIB);
1443280304Sjkim            goto err;
1444280304Sjkim        }
1445280304Sjkim        p += i;
1446238405Sjkim
1447280304Sjkim        if (2 > n - param_len) {
1448280304Sjkim            SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE, SSL_R_LENGTH_TOO_SHORT);
1449280304Sjkim            goto f_err;
1450280304Sjkim        }
1451280304Sjkim        param_len += 2;
1452273149Sjkim
1453280304Sjkim        n2s(p, i);
1454273149Sjkim
1455280304Sjkim        if (i > n - param_len) {
1456280304Sjkim            SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE, SSL_R_BAD_SRP_G_LENGTH);
1457280304Sjkim            goto f_err;
1458280304Sjkim        }
1459280304Sjkim        param_len += i;
1460273149Sjkim
1461280304Sjkim        if (!(s->srp_ctx.g = BN_bin2bn(p, i, NULL))) {
1462280304Sjkim            SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE, ERR_R_BN_LIB);
1463280304Sjkim            goto err;
1464280304Sjkim        }
1465280304Sjkim        p += i;
1466273149Sjkim
1467280304Sjkim        if (1 > n - param_len) {
1468280304Sjkim            SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE, SSL_R_LENGTH_TOO_SHORT);
1469280304Sjkim            goto f_err;
1470280304Sjkim        }
1471280304Sjkim        param_len += 1;
1472238405Sjkim
1473280304Sjkim        i = (unsigned int)(p[0]);
1474280304Sjkim        p++;
1475273149Sjkim
1476280304Sjkim        if (i > n - param_len) {
1477280304Sjkim            SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE, SSL_R_BAD_SRP_S_LENGTH);
1478280304Sjkim            goto f_err;
1479280304Sjkim        }
1480280304Sjkim        param_len += i;
1481273149Sjkim
1482280304Sjkim        if (!(s->srp_ctx.s = BN_bin2bn(p, i, NULL))) {
1483280304Sjkim            SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE, ERR_R_BN_LIB);
1484280304Sjkim            goto err;
1485280304Sjkim        }
1486280304Sjkim        p += i;
1487273149Sjkim
1488280304Sjkim        if (2 > n - param_len) {
1489280304Sjkim            SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE, SSL_R_LENGTH_TOO_SHORT);
1490280304Sjkim            goto f_err;
1491280304Sjkim        }
1492280304Sjkim        param_len += 2;
1493273149Sjkim
1494280304Sjkim        n2s(p, i);
1495238405Sjkim
1496280304Sjkim        if (i > n - param_len) {
1497280304Sjkim            SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE, SSL_R_BAD_SRP_B_LENGTH);
1498280304Sjkim            goto f_err;
1499280304Sjkim        }
1500280304Sjkim        param_len += i;
1501273149Sjkim
1502280304Sjkim        if (!(s->srp_ctx.B = BN_bin2bn(p, i, NULL))) {
1503280304Sjkim            SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE, ERR_R_BN_LIB);
1504280304Sjkim            goto err;
1505280304Sjkim        }
1506280304Sjkim        p += i;
1507280304Sjkim        n -= param_len;
1508273149Sjkim
1509280304Sjkim        if (!srp_verify_server_param(s, &al)) {
1510280304Sjkim            SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE, SSL_R_BAD_SRP_PARAMETERS);
1511280304Sjkim            goto f_err;
1512280304Sjkim        }
1513273149Sjkim
1514238405Sjkim/* We must check if there is a certificate */
1515280304Sjkim# ifndef OPENSSL_NO_RSA
1516280304Sjkim        if (alg_a & SSL_aRSA)
1517280304Sjkim            pkey =
1518280304Sjkim                X509_get_pubkey(s->session->
1519280304Sjkim                                sess_cert->peer_pkeys[SSL_PKEY_RSA_ENC].x509);
1520280304Sjkim# else
1521280304Sjkim        if (0) ;
1522280304Sjkim# endif
1523280304Sjkim# ifndef OPENSSL_NO_DSA
1524280304Sjkim        else if (alg_a & SSL_aDSS)
1525280304Sjkim            pkey =
1526280304Sjkim                X509_get_pubkey(s->session->
1527280304Sjkim                                sess_cert->peer_pkeys[SSL_PKEY_DSA_SIGN].
1528280304Sjkim                                x509);
1529280304Sjkim# endif
1530280304Sjkim    } else
1531280304Sjkim#endif                          /* !OPENSSL_NO_SRP */
1532109998Smarkm#ifndef OPENSSL_NO_RSA
1533280304Sjkim    if (alg_k & SSL_kRSA) {
1534280304Sjkim        /* Temporary RSA keys only allowed in export ciphersuites */
1535280304Sjkim        if (!SSL_C_IS_EXPORT(s->s3->tmp.new_cipher)) {
1536280304Sjkim            al = SSL_AD_UNEXPECTED_MESSAGE;
1537280304Sjkim            SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE, SSL_R_UNEXPECTED_MESSAGE);
1538280304Sjkim            goto f_err;
1539280304Sjkim        }
1540280304Sjkim        if ((rsa = RSA_new()) == NULL) {
1541280304Sjkim            SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE, ERR_R_MALLOC_FAILURE);
1542280304Sjkim            goto err;
1543280304Sjkim        }
1544273149Sjkim
1545280304Sjkim        param_len = 2;
1546280304Sjkim        if (param_len > n) {
1547280304Sjkim            SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE, SSL_R_LENGTH_TOO_SHORT);
1548280304Sjkim            goto f_err;
1549280304Sjkim        }
1550280304Sjkim        n2s(p, i);
1551273149Sjkim
1552280304Sjkim        if (i > n - param_len) {
1553280304Sjkim            SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE, SSL_R_BAD_RSA_MODULUS_LENGTH);
1554280304Sjkim            goto f_err;
1555280304Sjkim        }
1556280304Sjkim        param_len += i;
1557273149Sjkim
1558280304Sjkim        if (!(rsa->n = BN_bin2bn(p, i, rsa->n))) {
1559280304Sjkim            SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE, ERR_R_BN_LIB);
1560280304Sjkim            goto err;
1561280304Sjkim        }
1562280304Sjkim        p += i;
156355714Skris
1564280304Sjkim        if (2 > n - param_len) {
1565280304Sjkim            SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE, SSL_R_LENGTH_TOO_SHORT);
1566280304Sjkim            goto f_err;
1567280304Sjkim        }
1568280304Sjkim        param_len += 2;
1569273149Sjkim
1570280304Sjkim        n2s(p, i);
1571273149Sjkim
1572280304Sjkim        if (i > n - param_len) {
1573280304Sjkim            SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE, SSL_R_BAD_RSA_E_LENGTH);
1574280304Sjkim            goto f_err;
1575280304Sjkim        }
1576280304Sjkim        param_len += i;
1577273149Sjkim
1578280304Sjkim        if (!(rsa->e = BN_bin2bn(p, i, rsa->e))) {
1579280304Sjkim            SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE, ERR_R_BN_LIB);
1580280304Sjkim            goto err;
1581280304Sjkim        }
1582280304Sjkim        p += i;
1583280304Sjkim        n -= param_len;
158455714Skris
1585280304Sjkim        /* this should be because we are using an export cipher */
1586280304Sjkim        if (alg_a & SSL_aRSA)
1587280304Sjkim            pkey =
1588280304Sjkim                X509_get_pubkey(s->session->
1589280304Sjkim                                sess_cert->peer_pkeys[SSL_PKEY_RSA_ENC].x509);
1590280304Sjkim        else {
1591280304Sjkim            SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE, ERR_R_INTERNAL_ERROR);
1592280304Sjkim            goto err;
1593280304Sjkim        }
1594284285Sjkim
1595284285Sjkim        if (EVP_PKEY_bits(pkey) <= SSL_C_EXPORT_PKEYLENGTH(s->s3->tmp.new_cipher)) {
1596284285Sjkim            al = SSL_AD_UNEXPECTED_MESSAGE;
1597284285Sjkim            SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE, SSL_R_UNEXPECTED_MESSAGE);
1598284285Sjkim            goto f_err;
1599284285Sjkim        }
1600284285Sjkim
1601280304Sjkim        s->session->sess_cert->peer_rsa_tmp = rsa;
1602280304Sjkim        rsa = NULL;
1603280304Sjkim    }
1604280304Sjkim#else                           /* OPENSSL_NO_RSA */
1605280304Sjkim    if (0) ;
160655714Skris#endif
1607109998Smarkm#ifndef OPENSSL_NO_DH
1608280304Sjkim    else if (alg_k & SSL_kEDH) {
1609280304Sjkim        if ((dh = DH_new()) == NULL) {
1610280304Sjkim            SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE, ERR_R_DH_LIB);
1611280304Sjkim            goto err;
1612280304Sjkim        }
1613273149Sjkim
1614280304Sjkim        param_len = 2;
1615280304Sjkim        if (param_len > n) {
1616280304Sjkim            SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE, SSL_R_LENGTH_TOO_SHORT);
1617280304Sjkim            goto f_err;
1618280304Sjkim        }
1619280304Sjkim        n2s(p, i);
1620273149Sjkim
1621280304Sjkim        if (i > n - param_len) {
1622280304Sjkim            SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE, SSL_R_BAD_DH_P_LENGTH);
1623280304Sjkim            goto f_err;
1624280304Sjkim        }
1625280304Sjkim        param_len += i;
1626273149Sjkim
1627280304Sjkim        if (!(dh->p = BN_bin2bn(p, i, NULL))) {
1628280304Sjkim            SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE, ERR_R_BN_LIB);
1629280304Sjkim            goto err;
1630280304Sjkim        }
1631280304Sjkim        p += i;
163255714Skris
1633280304Sjkim        if (2 > n - param_len) {
1634280304Sjkim            SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE, SSL_R_LENGTH_TOO_SHORT);
1635280304Sjkim            goto f_err;
1636280304Sjkim        }
1637280304Sjkim        param_len += 2;
1638273149Sjkim
1639280304Sjkim        n2s(p, i);
1640273149Sjkim
1641280304Sjkim        if (i > n - param_len) {
1642280304Sjkim            SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE, SSL_R_BAD_DH_G_LENGTH);
1643280304Sjkim            goto f_err;
1644280304Sjkim        }
1645280304Sjkim        param_len += i;
1646273149Sjkim
1647280304Sjkim        if (!(dh->g = BN_bin2bn(p, i, NULL))) {
1648280304Sjkim            SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE, ERR_R_BN_LIB);
1649280304Sjkim            goto err;
1650280304Sjkim        }
1651280304Sjkim        p += i;
165255714Skris
1653280304Sjkim        if (2 > n - param_len) {
1654280304Sjkim            SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE, SSL_R_LENGTH_TOO_SHORT);
1655280304Sjkim            goto f_err;
1656280304Sjkim        }
1657280304Sjkim        param_len += 2;
1658273149Sjkim
1659280304Sjkim        n2s(p, i);
1660273149Sjkim
1661280304Sjkim        if (i > n - param_len) {
1662280304Sjkim            SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE, SSL_R_BAD_DH_PUB_KEY_LENGTH);
1663280304Sjkim            goto f_err;
1664280304Sjkim        }
1665280304Sjkim        param_len += i;
1666273149Sjkim
1667280304Sjkim        if (!(dh->pub_key = BN_bin2bn(p, i, NULL))) {
1668280304Sjkim            SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE, ERR_R_BN_LIB);
1669280304Sjkim            goto err;
1670280304Sjkim        }
1671280304Sjkim        p += i;
1672280304Sjkim        n -= param_len;
167355714Skris
1674280304Sjkim# ifndef OPENSSL_NO_RSA
1675280304Sjkim        if (alg_a & SSL_aRSA)
1676280304Sjkim            pkey =
1677280304Sjkim                X509_get_pubkey(s->session->
1678280304Sjkim                                sess_cert->peer_pkeys[SSL_PKEY_RSA_ENC].x509);
1679280304Sjkim# else
1680280304Sjkim        if (0) ;
1681280304Sjkim# endif
1682280304Sjkim# ifndef OPENSSL_NO_DSA
1683280304Sjkim        else if (alg_a & SSL_aDSS)
1684280304Sjkim            pkey =
1685280304Sjkim                X509_get_pubkey(s->session->
1686280304Sjkim                                sess_cert->peer_pkeys[SSL_PKEY_DSA_SIGN].
1687280304Sjkim                                x509);
1688280304Sjkim# endif
1689280304Sjkim        /* else anonymous DH, so no certificate or pkey. */
169055714Skris
1691280304Sjkim        s->session->sess_cert->peer_dh_tmp = dh;
1692280304Sjkim        dh = NULL;
1693280304Sjkim    } else if ((alg_k & SSL_kDHr) || (alg_k & SSL_kDHd)) {
1694280304Sjkim        al = SSL_AD_ILLEGAL_PARAMETER;
1695280304Sjkim        SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,
1696280304Sjkim               SSL_R_TRIED_TO_USE_UNSUPPORTED_CIPHER);
1697280304Sjkim        goto f_err;
1698280304Sjkim    }
1699280304Sjkim#endif                          /* !OPENSSL_NO_DH */
1700160814Ssimon
1701160814Ssimon#ifndef OPENSSL_NO_ECDH
1702280304Sjkim    else if (alg_k & SSL_kEECDH) {
1703280304Sjkim        EC_GROUP *ngroup;
1704280304Sjkim        const EC_GROUP *group;
1705160814Ssimon
1706280304Sjkim        if ((ecdh = EC_KEY_new()) == NULL) {
1707280304Sjkim            SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE, ERR_R_MALLOC_FAILURE);
1708280304Sjkim            goto err;
1709280304Sjkim        }
1710160814Ssimon
1711280304Sjkim        /*
1712280304Sjkim         * Extract elliptic curve parameters and the server's ephemeral ECDH
1713280304Sjkim         * public key. Keep accumulating lengths of various components in
1714280304Sjkim         * param_len and make sure it never exceeds n.
1715280304Sjkim         */
1716160814Ssimon
1717280304Sjkim        /*
1718280304Sjkim         * XXX: For now we only support named (not generic) curves and the
1719280304Sjkim         * ECParameters in this case is just three bytes. We also need one
1720280304Sjkim         * byte for the length of the encoded point
1721280304Sjkim         */
1722280304Sjkim        param_len = 4;
1723280304Sjkim        if (param_len > n) {
1724280304Sjkim            SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE, SSL_R_LENGTH_TOO_SHORT);
1725280304Sjkim            goto f_err;
1726280304Sjkim        }
1727273149Sjkim
1728280304Sjkim        if ((*p != NAMED_CURVE_TYPE) ||
1729280304Sjkim            ((curve_nid = tls1_ec_curve_id2nid(*(p + 2))) == 0)) {
1730280304Sjkim            al = SSL_AD_INTERNAL_ERROR;
1731280304Sjkim            SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,
1732280304Sjkim                   SSL_R_UNABLE_TO_FIND_ECDH_PARAMETERS);
1733280304Sjkim            goto f_err;
1734280304Sjkim        }
1735160814Ssimon
1736280304Sjkim        ngroup = EC_GROUP_new_by_curve_name(curve_nid);
1737280304Sjkim        if (ngroup == NULL) {
1738280304Sjkim            SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE, ERR_R_EC_LIB);
1739280304Sjkim            goto err;
1740280304Sjkim        }
1741280304Sjkim        if (EC_KEY_set_group(ecdh, ngroup) == 0) {
1742280304Sjkim            SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE, ERR_R_EC_LIB);
1743280304Sjkim            goto err;
1744280304Sjkim        }
1745280304Sjkim        EC_GROUP_free(ngroup);
1746160814Ssimon
1747280304Sjkim        group = EC_KEY_get0_group(ecdh);
1748160814Ssimon
1749280304Sjkim        if (SSL_C_IS_EXPORT(s->s3->tmp.new_cipher) &&
1750280304Sjkim            (EC_GROUP_get_degree(group) > 163)) {
1751280304Sjkim            al = SSL_AD_EXPORT_RESTRICTION;
1752280304Sjkim            SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,
1753280304Sjkim                   SSL_R_ECGROUP_TOO_LARGE_FOR_CIPHER);
1754280304Sjkim            goto f_err;
1755280304Sjkim        }
1756160814Ssimon
1757280304Sjkim        p += 3;
1758160814Ssimon
1759280304Sjkim        /* Next, get the encoded ECPoint */
1760280304Sjkim        if (((srvr_ecpoint = EC_POINT_new(group)) == NULL) ||
1761280304Sjkim            ((bn_ctx = BN_CTX_new()) == NULL)) {
1762280304Sjkim            SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE, ERR_R_MALLOC_FAILURE);
1763280304Sjkim            goto err;
1764280304Sjkim        }
1765160814Ssimon
1766280304Sjkim        encoded_pt_len = *p;    /* length of encoded point */
1767280304Sjkim        p += 1;
1768273149Sjkim
1769280304Sjkim        if ((encoded_pt_len > n - param_len) ||
1770280304Sjkim            (EC_POINT_oct2point(group, srvr_ecpoint,
1771280304Sjkim                                p, encoded_pt_len, bn_ctx) == 0)) {
1772280304Sjkim            SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE, SSL_R_BAD_ECPOINT);
1773280304Sjkim            goto f_err;
1774280304Sjkim        }
1775280304Sjkim        param_len += encoded_pt_len;
1776160814Ssimon
1777280304Sjkim        n -= param_len;
1778280304Sjkim        p += encoded_pt_len;
1779160814Ssimon
1780280304Sjkim        /*
1781280304Sjkim         * The ECC/TLS specification does not mention the use of DSA to sign
1782280304Sjkim         * ECParameters in the server key exchange message. We do support RSA
1783280304Sjkim         * and ECDSA.
1784280304Sjkim         */
1785280304Sjkim        if (0) ;
1786280304Sjkim# ifndef OPENSSL_NO_RSA
1787280304Sjkim        else if (alg_a & SSL_aRSA)
1788280304Sjkim            pkey =
1789280304Sjkim                X509_get_pubkey(s->session->
1790280304Sjkim                                sess_cert->peer_pkeys[SSL_PKEY_RSA_ENC].x509);
1791280304Sjkim# endif
1792280304Sjkim# ifndef OPENSSL_NO_ECDSA
1793280304Sjkim        else if (alg_a & SSL_aECDSA)
1794280304Sjkim            pkey =
1795280304Sjkim                X509_get_pubkey(s->session->
1796280304Sjkim                                sess_cert->peer_pkeys[SSL_PKEY_ECC].x509);
1797280304Sjkim# endif
1798280304Sjkim        /* else anonymous ECDH, so no certificate or pkey. */
1799280304Sjkim        EC_KEY_set_public_key(ecdh, srvr_ecpoint);
1800280304Sjkim        s->session->sess_cert->peer_ecdh_tmp = ecdh;
1801280304Sjkim        ecdh = NULL;
1802280304Sjkim        BN_CTX_free(bn_ctx);
1803280304Sjkim        bn_ctx = NULL;
1804280304Sjkim        EC_POINT_free(srvr_ecpoint);
1805280304Sjkim        srvr_ecpoint = NULL;
1806280304Sjkim    } else if (alg_k) {
1807280304Sjkim        al = SSL_AD_UNEXPECTED_MESSAGE;
1808280304Sjkim        SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE, SSL_R_UNEXPECTED_MESSAGE);
1809280304Sjkim        goto f_err;
1810280304Sjkim    }
1811280304Sjkim#endif                          /* !OPENSSL_NO_ECDH */
181255714Skris
1813280304Sjkim    /* p points to the next byte, there are 'n' bytes left */
181455714Skris
1815280304Sjkim    /* if it was signed, check the signature */
1816280304Sjkim    if (pkey != NULL) {
1817280304Sjkim        if (TLS1_get_version(s) >= TLS1_2_VERSION) {
1818280304Sjkim            int sigalg;
1819280304Sjkim            if (2 > n) {
1820280304Sjkim                SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE, SSL_R_LENGTH_TOO_SHORT);
1821280304Sjkim                goto f_err;
1822280304Sjkim            }
182355714Skris
1824280304Sjkim            sigalg = tls12_get_sigid(pkey);
1825280304Sjkim            /* Should never happen */
1826280304Sjkim            if (sigalg == -1) {
1827280304Sjkim                SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE, ERR_R_INTERNAL_ERROR);
1828280304Sjkim                goto err;
1829280304Sjkim            }
1830280304Sjkim            /* Check key type is consistent with signature */
1831280304Sjkim            if (sigalg != (int)p[1]) {
1832280304Sjkim                SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,
1833280304Sjkim                       SSL_R_WRONG_SIGNATURE_TYPE);
1834280304Sjkim                al = SSL_AD_DECODE_ERROR;
1835280304Sjkim                goto f_err;
1836280304Sjkim            }
1837280304Sjkim            md = tls12_get_hash(p[0]);
1838280304Sjkim            if (md == NULL) {
1839280304Sjkim                SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE, SSL_R_UNKNOWN_DIGEST);
1840280304Sjkim                goto f_err;
1841280304Sjkim            }
1842238405Sjkim#ifdef SSL_DEBUG
1843280304Sjkim            fprintf(stderr, "USING TLSv1.2 HASH %s\n", EVP_MD_name(md));
1844238405Sjkim#endif
1845280304Sjkim            p += 2;
1846280304Sjkim            n -= 2;
1847280304Sjkim        } else
1848280304Sjkim            md = EVP_sha1();
1849273149Sjkim
1850280304Sjkim        if (2 > n) {
1851280304Sjkim            SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE, SSL_R_LENGTH_TOO_SHORT);
1852280304Sjkim            goto f_err;
1853280304Sjkim        }
1854280304Sjkim        n2s(p, i);
1855280304Sjkim        n -= 2;
1856280304Sjkim        j = EVP_PKEY_size(pkey);
185755714Skris
1858280304Sjkim        /*
1859280304Sjkim         * Check signature length. If n is 0 then signature is empty
1860280304Sjkim         */
1861280304Sjkim        if ((i != n) || (n > j) || (n <= 0)) {
1862280304Sjkim            /* wrong packet length */
1863280304Sjkim            SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE, SSL_R_WRONG_SIGNATURE_LENGTH);
1864280304Sjkim            goto f_err;
1865280304Sjkim        }
1866109998Smarkm#ifndef OPENSSL_NO_RSA
1867280304Sjkim        if (pkey->type == EVP_PKEY_RSA
1868280304Sjkim            && TLS1_get_version(s) < TLS1_2_VERSION) {
1869280304Sjkim            int num;
1870280304Sjkim            unsigned int size;
187155714Skris
1872280304Sjkim            j = 0;
1873280304Sjkim            q = md_buf;
1874280304Sjkim            for (num = 2; num > 0; num--) {
1875280304Sjkim                EVP_MD_CTX_set_flags(&md_ctx, EVP_MD_CTX_FLAG_NON_FIPS_ALLOW);
1876280304Sjkim                EVP_DigestInit_ex(&md_ctx, (num == 2)
1877280304Sjkim                                  ? s->ctx->md5 : s->ctx->sha1, NULL);
1878280304Sjkim                EVP_DigestUpdate(&md_ctx, &(s->s3->client_random[0]),
1879280304Sjkim                                 SSL3_RANDOM_SIZE);
1880280304Sjkim                EVP_DigestUpdate(&md_ctx, &(s->s3->server_random[0]),
1881280304Sjkim                                 SSL3_RANDOM_SIZE);
1882280304Sjkim                EVP_DigestUpdate(&md_ctx, param, param_len);
1883280304Sjkim                EVP_DigestFinal_ex(&md_ctx, q, &size);
1884280304Sjkim                q += size;
1885280304Sjkim                j += size;
1886280304Sjkim            }
1887280304Sjkim            i = RSA_verify(NID_md5_sha1, md_buf, j, p, n, pkey->pkey.rsa);
1888280304Sjkim            if (i < 0) {
1889280304Sjkim                al = SSL_AD_DECRYPT_ERROR;
1890280304Sjkim                SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE, SSL_R_BAD_RSA_DECRYPT);
1891280304Sjkim                goto f_err;
1892280304Sjkim            }
1893280304Sjkim            if (i == 0) {
1894280304Sjkim                /* bad signature */
1895280304Sjkim                al = SSL_AD_DECRYPT_ERROR;
1896280304Sjkim                SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE, SSL_R_BAD_SIGNATURE);
1897280304Sjkim                goto f_err;
1898280304Sjkim            }
1899280304Sjkim        } else
190055714Skris#endif
1901280304Sjkim        {
1902280304Sjkim            EVP_VerifyInit_ex(&md_ctx, md, NULL);
1903280304Sjkim            EVP_VerifyUpdate(&md_ctx, &(s->s3->client_random[0]),
1904280304Sjkim                             SSL3_RANDOM_SIZE);
1905280304Sjkim            EVP_VerifyUpdate(&md_ctx, &(s->s3->server_random[0]),
1906280304Sjkim                             SSL3_RANDOM_SIZE);
1907280304Sjkim            EVP_VerifyUpdate(&md_ctx, param, param_len);
1908280304Sjkim            if (EVP_VerifyFinal(&md_ctx, p, (int)n, pkey) <= 0) {
1909280304Sjkim                /* bad signature */
1910280304Sjkim                al = SSL_AD_DECRYPT_ERROR;
1911280304Sjkim                SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE, SSL_R_BAD_SIGNATURE);
1912280304Sjkim                goto f_err;
1913280304Sjkim            }
1914280304Sjkim        }
1915280304Sjkim    } else {
1916280304Sjkim        /* aNULL, aSRP or kPSK do not need public keys */
1917280304Sjkim        if (!(alg_a & (SSL_aNULL | SSL_aSRP)) && !(alg_k & SSL_kPSK)) {
1918280304Sjkim            SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE, ERR_R_INTERNAL_ERROR);
1919280304Sjkim            goto err;
1920280304Sjkim        }
1921280304Sjkim        /* still data left over */
1922280304Sjkim        if (n != 0) {
1923280304Sjkim            SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE, SSL_R_EXTRA_DATA_IN_MESSAGE);
1924280304Sjkim            goto f_err;
1925280304Sjkim        }
1926280304Sjkim    }
1927280304Sjkim    EVP_PKEY_free(pkey);
1928280304Sjkim    EVP_MD_CTX_cleanup(&md_ctx);
1929280304Sjkim    return (1);
1930280304Sjkim f_err:
1931280304Sjkim    ssl3_send_alert(s, SSL3_AL_FATAL, al);
1932280304Sjkim err:
1933280304Sjkim    EVP_PKEY_free(pkey);
1934109998Smarkm#ifndef OPENSSL_NO_RSA
1935280304Sjkim    if (rsa != NULL)
1936280304Sjkim        RSA_free(rsa);
193755714Skris#endif
1938109998Smarkm#ifndef OPENSSL_NO_DH
1939280304Sjkim    if (dh != NULL)
1940280304Sjkim        DH_free(dh);
194155714Skris#endif
1942160814Ssimon#ifndef OPENSSL_NO_ECDH
1943280304Sjkim    BN_CTX_free(bn_ctx);
1944280304Sjkim    EC_POINT_free(srvr_ecpoint);
1945280304Sjkim    if (ecdh != NULL)
1946280304Sjkim        EC_KEY_free(ecdh);
1947160814Ssimon#endif
1948280304Sjkim    EVP_MD_CTX_cleanup(&md_ctx);
1949284285Sjkim    s->state = SSL_ST_ERR;
1950280304Sjkim    return (-1);
1951280304Sjkim}
195255714Skris
1953160814Ssimonint ssl3_get_certificate_request(SSL *s)
1954280304Sjkim{
1955280304Sjkim    int ok, ret = 0;
1956280304Sjkim    unsigned long n, nc, l;
1957280304Sjkim    unsigned int llen, ctype_num, i;
1958280304Sjkim    X509_NAME *xn = NULL;
1959280304Sjkim    const unsigned char *p, *q;
1960280304Sjkim    unsigned char *d;
1961280304Sjkim    STACK_OF(X509_NAME) *ca_sk = NULL;
196255714Skris
1963280304Sjkim    n = s->method->ssl_get_message(s,
1964280304Sjkim                                   SSL3_ST_CR_CERT_REQ_A,
1965280304Sjkim                                   SSL3_ST_CR_CERT_REQ_B,
1966280304Sjkim                                   -1, s->max_cert_list, &ok);
196755714Skris
1968280304Sjkim    if (!ok)
1969280304Sjkim        return ((int)n);
197055714Skris
1971280304Sjkim    s->s3->tmp.cert_req = 0;
197255714Skris
1973280304Sjkim    if (s->s3->tmp.message_type == SSL3_MT_SERVER_DONE) {
1974280304Sjkim        s->s3->tmp.reuse_message = 1;
1975280304Sjkim        /*
1976280304Sjkim         * If we get here we don't need any cached handshake records as we
1977280304Sjkim         * wont be doing client auth.
1978280304Sjkim         */
1979280304Sjkim        if (s->s3->handshake_buffer) {
1980280304Sjkim            if (!ssl3_digest_cached_records(s))
1981280304Sjkim                goto err;
1982280304Sjkim        }
1983280304Sjkim        return (1);
1984280304Sjkim    }
198555714Skris
1986280304Sjkim    if (s->s3->tmp.message_type != SSL3_MT_CERTIFICATE_REQUEST) {
1987280304Sjkim        ssl3_send_alert(s, SSL3_AL_FATAL, SSL_AD_UNEXPECTED_MESSAGE);
1988280304Sjkim        SSLerr(SSL_F_SSL3_GET_CERTIFICATE_REQUEST, SSL_R_WRONG_MESSAGE_TYPE);
1989280304Sjkim        goto err;
1990280304Sjkim    }
199155714Skris
1992280304Sjkim    /* TLS does not like anon-DH with client cert */
1993280304Sjkim    if (s->version > SSL3_VERSION) {
1994280304Sjkim        if (s->s3->tmp.new_cipher->algorithm_auth & SSL_aNULL) {
1995280304Sjkim            ssl3_send_alert(s, SSL3_AL_FATAL, SSL_AD_UNEXPECTED_MESSAGE);
1996280304Sjkim            SSLerr(SSL_F_SSL3_GET_CERTIFICATE_REQUEST,
1997280304Sjkim                   SSL_R_TLS_CLIENT_CERT_REQ_WITH_ANON_CIPHER);
1998280304Sjkim            goto err;
1999280304Sjkim        }
2000280304Sjkim    }
200155714Skris
2002280304Sjkim    p = d = (unsigned char *)s->init_msg;
200355714Skris
2004280304Sjkim    if ((ca_sk = sk_X509_NAME_new(ca_dn_cmp)) == NULL) {
2005280304Sjkim        SSLerr(SSL_F_SSL3_GET_CERTIFICATE_REQUEST, ERR_R_MALLOC_FAILURE);
2006280304Sjkim        goto err;
2007280304Sjkim    }
200855714Skris
2009280304Sjkim    /* get the certificate types */
2010280304Sjkim    ctype_num = *(p++);
2011280304Sjkim    if (ctype_num > SSL3_CT_NUMBER)
2012280304Sjkim        ctype_num = SSL3_CT_NUMBER;
2013280304Sjkim    for (i = 0; i < ctype_num; i++)
2014280304Sjkim        s->s3->tmp.ctype[i] = p[i];
2015280304Sjkim    p += ctype_num;
2016280304Sjkim    if (TLS1_get_version(s) >= TLS1_2_VERSION) {
2017280304Sjkim        n2s(p, llen);
2018280304Sjkim        /*
2019280304Sjkim         * Check we have enough room for signature algorithms and following
2020280304Sjkim         * length value.
2021280304Sjkim         */
2022280304Sjkim        if ((unsigned long)(p - d + llen + 2) > n) {
2023280304Sjkim            ssl3_send_alert(s, SSL3_AL_FATAL, SSL_AD_DECODE_ERROR);
2024280304Sjkim            SSLerr(SSL_F_SSL3_GET_CERTIFICATE_REQUEST,
2025280304Sjkim                   SSL_R_DATA_LENGTH_TOO_LONG);
2026280304Sjkim            goto err;
2027280304Sjkim        }
2028280304Sjkim        if ((llen & 1) || !tls1_process_sigalgs(s, p, llen)) {
2029280304Sjkim            ssl3_send_alert(s, SSL3_AL_FATAL, SSL_AD_DECODE_ERROR);
2030280304Sjkim            SSLerr(SSL_F_SSL3_GET_CERTIFICATE_REQUEST,
2031280304Sjkim                   SSL_R_SIGNATURE_ALGORITHMS_ERROR);
2032280304Sjkim            goto err;
2033280304Sjkim        }
2034280304Sjkim        p += llen;
2035280304Sjkim    }
203655714Skris
2037280304Sjkim    /* get the CA RDNs */
2038280304Sjkim    n2s(p, llen);
203955714Skris#if 0
2040280304Sjkim    {
2041280304Sjkim        FILE *out;
2042280304Sjkim        out = fopen("/tmp/vsign.der", "w");
2043280304Sjkim        fwrite(p, 1, llen, out);
2044280304Sjkim        fclose(out);
2045280304Sjkim    }
204655714Skris#endif
204755714Skris
2048280304Sjkim    if ((unsigned long)(p - d + llen) != n) {
2049280304Sjkim        ssl3_send_alert(s, SSL3_AL_FATAL, SSL_AD_DECODE_ERROR);
2050280304Sjkim        SSLerr(SSL_F_SSL3_GET_CERTIFICATE_REQUEST, SSL_R_LENGTH_MISMATCH);
2051280304Sjkim        goto err;
2052280304Sjkim    }
205355714Skris
2054280304Sjkim    for (nc = 0; nc < llen;) {
2055306230Sdelphij        if (nc + 2 > llen) {
2056306230Sdelphij            ssl3_send_alert(s, SSL3_AL_FATAL, SSL_AD_DECODE_ERROR);
2057306230Sdelphij            SSLerr(SSL_F_SSL3_GET_CERTIFICATE_REQUEST, SSL_R_CA_DN_TOO_LONG);
2058306230Sdelphij            goto err;
2059306230Sdelphij        }
2060280304Sjkim        n2s(p, l);
2061280304Sjkim        if ((l + nc + 2) > llen) {
2062280304Sjkim            if ((s->options & SSL_OP_NETSCAPE_CA_DN_BUG))
2063280304Sjkim                goto cont;      /* netscape bugs */
2064280304Sjkim            ssl3_send_alert(s, SSL3_AL_FATAL, SSL_AD_DECODE_ERROR);
2065280304Sjkim            SSLerr(SSL_F_SSL3_GET_CERTIFICATE_REQUEST, SSL_R_CA_DN_TOO_LONG);
2066280304Sjkim            goto err;
2067280304Sjkim        }
206855714Skris
2069280304Sjkim        q = p;
207055714Skris
2071280304Sjkim        if ((xn = d2i_X509_NAME(NULL, &q, l)) == NULL) {
2072280304Sjkim            /* If netscape tolerance is on, ignore errors */
2073280304Sjkim            if (s->options & SSL_OP_NETSCAPE_CA_DN_BUG)
2074280304Sjkim                goto cont;
2075280304Sjkim            else {
2076280304Sjkim                ssl3_send_alert(s, SSL3_AL_FATAL, SSL_AD_DECODE_ERROR);
2077280304Sjkim                SSLerr(SSL_F_SSL3_GET_CERTIFICATE_REQUEST, ERR_R_ASN1_LIB);
2078280304Sjkim                goto err;
2079280304Sjkim            }
2080280304Sjkim        }
208155714Skris
2082280304Sjkim        if (q != (p + l)) {
2083280304Sjkim            ssl3_send_alert(s, SSL3_AL_FATAL, SSL_AD_DECODE_ERROR);
2084280304Sjkim            SSLerr(SSL_F_SSL3_GET_CERTIFICATE_REQUEST,
2085280304Sjkim                   SSL_R_CA_DN_LENGTH_MISMATCH);
2086280304Sjkim            goto err;
2087280304Sjkim        }
2088280304Sjkim        if (!sk_X509_NAME_push(ca_sk, xn)) {
2089280304Sjkim            SSLerr(SSL_F_SSL3_GET_CERTIFICATE_REQUEST, ERR_R_MALLOC_FAILURE);
2090280304Sjkim            goto err;
2091280304Sjkim        }
209255714Skris
2093280304Sjkim        p += l;
2094280304Sjkim        nc += l + 2;
2095280304Sjkim    }
209655714Skris
2097280304Sjkim    if (0) {
2098280304Sjkim cont:
2099280304Sjkim        ERR_clear_error();
2100280304Sjkim    }
210155714Skris
2102280304Sjkim    /* we should setup a certificate to return.... */
2103280304Sjkim    s->s3->tmp.cert_req = 1;
2104280304Sjkim    s->s3->tmp.ctype_num = ctype_num;
2105280304Sjkim    if (s->s3->tmp.ca_names != NULL)
2106280304Sjkim        sk_X509_NAME_pop_free(s->s3->tmp.ca_names, X509_NAME_free);
2107280304Sjkim    s->s3->tmp.ca_names = ca_sk;
2108280304Sjkim    ca_sk = NULL;
210955714Skris
2110280304Sjkim    ret = 1;
2111284285Sjkim    goto done;
2112280304Sjkim err:
2113284285Sjkim    s->state = SSL_ST_ERR;
2114284285Sjkim done:
2115280304Sjkim    if (ca_sk != NULL)
2116280304Sjkim        sk_X509_NAME_pop_free(ca_sk, X509_NAME_free);
2117280304Sjkim    return (ret);
2118280304Sjkim}
211955714Skris
2120280304Sjkimstatic int ca_dn_cmp(const X509_NAME *const *a, const X509_NAME *const *b)
2121280304Sjkim{
2122280304Sjkim    return (X509_NAME_cmp(*a, *b));
2123280304Sjkim}
2124280304Sjkim
2125194206Ssimon#ifndef OPENSSL_NO_TLSEXT
2126194206Ssimonint ssl3_get_new_session_ticket(SSL *s)
2127280304Sjkim{
2128280304Sjkim    int ok, al, ret = 0, ticklen;
2129280304Sjkim    long n;
2130280304Sjkim    const unsigned char *p;
2131280304Sjkim    unsigned char *d;
213255714Skris
2133280304Sjkim    n = s->method->ssl_get_message(s,
2134280304Sjkim                                   SSL3_ST_CR_SESSION_TICKET_A,
2135280304Sjkim                                   SSL3_ST_CR_SESSION_TICKET_B,
2136280304Sjkim                                   SSL3_MT_NEWSESSION_TICKET, 16384, &ok);
2137194206Ssimon
2138280304Sjkim    if (!ok)
2139280304Sjkim        return ((int)n);
2140194206Ssimon
2141280304Sjkim    if (n < 6) {
2142280304Sjkim        /* need at least ticket_lifetime_hint + ticket length */
2143280304Sjkim        al = SSL_AD_DECODE_ERROR;
2144280304Sjkim        SSLerr(SSL_F_SSL3_GET_NEW_SESSION_TICKET, SSL_R_LENGTH_MISMATCH);
2145280304Sjkim        goto f_err;
2146280304Sjkim    }
2147205128Ssimon
2148280304Sjkim    p = d = (unsigned char *)s->init_msg;
2149284285Sjkim
2150284285Sjkim    if (s->session->session_id_length > 0) {
2151284285Sjkim        int i = s->session_ctx->session_cache_mode;
2152284285Sjkim        SSL_SESSION *new_sess;
2153284285Sjkim        /*
2154284285Sjkim         * We reused an existing session, so we need to replace it with a new
2155284285Sjkim         * one
2156284285Sjkim         */
2157284285Sjkim        if (i & SSL_SESS_CACHE_CLIENT) {
2158284285Sjkim            /*
2159284285Sjkim             * Remove the old session from the cache
2160284285Sjkim             */
2161284285Sjkim            if (i & SSL_SESS_CACHE_NO_INTERNAL_STORE) {
2162284285Sjkim                if (s->session_ctx->remove_session_cb != NULL)
2163284285Sjkim                    s->session_ctx->remove_session_cb(s->session_ctx,
2164284285Sjkim                                                      s->session);
2165284285Sjkim            } else {
2166284285Sjkim                /* We carry on if this fails */
2167284285Sjkim                SSL_CTX_remove_session(s->session_ctx, s->session);
2168284285Sjkim            }
2169284285Sjkim        }
2170284285Sjkim
2171284285Sjkim        if ((new_sess = ssl_session_dup(s->session, 0)) == 0) {
2172284285Sjkim            al = SSL_AD_INTERNAL_ERROR;
2173284285Sjkim            SSLerr(SSL_F_SSL3_GET_NEW_SESSION_TICKET, ERR_R_MALLOC_FAILURE);
2174284285Sjkim            goto f_err;
2175284285Sjkim        }
2176284285Sjkim
2177284285Sjkim        SSL_SESSION_free(s->session);
2178284285Sjkim        s->session = new_sess;
2179284285Sjkim    }
2180284285Sjkim
2181280304Sjkim    n2l(p, s->session->tlsext_tick_lifetime_hint);
2182280304Sjkim    n2s(p, ticklen);
2183280304Sjkim    /* ticket_lifetime_hint + ticket_length + ticket */
2184280304Sjkim    if (ticklen + 6 != n) {
2185280304Sjkim        al = SSL_AD_DECODE_ERROR;
2186280304Sjkim        SSLerr(SSL_F_SSL3_GET_NEW_SESSION_TICKET, SSL_R_LENGTH_MISMATCH);
2187280304Sjkim        goto f_err;
2188280304Sjkim    }
2189280304Sjkim    if (s->session->tlsext_tick) {
2190280304Sjkim        OPENSSL_free(s->session->tlsext_tick);
2191280304Sjkim        s->session->tlsext_ticklen = 0;
2192280304Sjkim    }
2193280304Sjkim    s->session->tlsext_tick = OPENSSL_malloc(ticklen);
2194280304Sjkim    if (!s->session->tlsext_tick) {
2195280304Sjkim        SSLerr(SSL_F_SSL3_GET_NEW_SESSION_TICKET, ERR_R_MALLOC_FAILURE);
2196280304Sjkim        goto err;
2197280304Sjkim    }
2198280304Sjkim    memcpy(s->session->tlsext_tick, p, ticklen);
2199280304Sjkim    s->session->tlsext_ticklen = ticklen;
2200280304Sjkim    /*
2201280304Sjkim     * There are two ways to detect a resumed ticket session. One is to set
2202280304Sjkim     * an appropriate session ID and then the server must return a match in
2203280304Sjkim     * ServerHello. This allows the normal client session ID matching to work
2204280304Sjkim     * and we know much earlier that the ticket has been accepted. The
2205280304Sjkim     * other way is to set zero length session ID when the ticket is
2206280304Sjkim     * presented and rely on the handshake to determine session resumption.
2207280304Sjkim     * We choose the former approach because this fits in with assumptions
2208280304Sjkim     * elsewhere in OpenSSL. The session ID is set to the SHA256 (or SHA1 is
2209280304Sjkim     * SHA256 is disabled) hash of the ticket.
2210280304Sjkim     */
2211280304Sjkim    EVP_Digest(p, ticklen,
2212280304Sjkim               s->session->session_id, &s->session->session_id_length,
2213280304Sjkim# ifndef OPENSSL_NO_SHA256
2214280304Sjkim               EVP_sha256(), NULL);
2215280304Sjkim# else
2216280304Sjkim               EVP_sha1(), NULL);
2217280304Sjkim# endif
2218280304Sjkim    ret = 1;
2219280304Sjkim    return (ret);
2220280304Sjkim f_err:
2221280304Sjkim    ssl3_send_alert(s, SSL3_AL_FATAL, al);
2222280304Sjkim err:
2223284285Sjkim    s->state = SSL_ST_ERR;
2224280304Sjkim    return (-1);
2225280304Sjkim}
2226194206Ssimon
2227194206Ssimonint ssl3_get_cert_status(SSL *s)
2228280304Sjkim{
2229280304Sjkim    int ok, al;
2230280304Sjkim    unsigned long resplen, n;
2231280304Sjkim    const unsigned char *p;
2232194206Ssimon
2233280304Sjkim    n = s->method->ssl_get_message(s,
2234280304Sjkim                                   SSL3_ST_CR_CERT_STATUS_A,
2235280304Sjkim                                   SSL3_ST_CR_CERT_STATUS_B,
2236280304Sjkim                                   SSL3_MT_CERTIFICATE_STATUS, 16384, &ok);
2237194206Ssimon
2238280304Sjkim    if (!ok)
2239280304Sjkim        return ((int)n);
2240280304Sjkim    if (n < 4) {
2241280304Sjkim        /* need at least status type + length */
2242280304Sjkim        al = SSL_AD_DECODE_ERROR;
2243280304Sjkim        SSLerr(SSL_F_SSL3_GET_CERT_STATUS, SSL_R_LENGTH_MISMATCH);
2244280304Sjkim        goto f_err;
2245280304Sjkim    }
2246280304Sjkim    p = (unsigned char *)s->init_msg;
2247280304Sjkim    if (*p++ != TLSEXT_STATUSTYPE_ocsp) {
2248280304Sjkim        al = SSL_AD_DECODE_ERROR;
2249280304Sjkim        SSLerr(SSL_F_SSL3_GET_CERT_STATUS, SSL_R_UNSUPPORTED_STATUS_TYPE);
2250280304Sjkim        goto f_err;
2251280304Sjkim    }
2252280304Sjkim    n2l3(p, resplen);
2253280304Sjkim    if (resplen + 4 != n) {
2254280304Sjkim        al = SSL_AD_DECODE_ERROR;
2255280304Sjkim        SSLerr(SSL_F_SSL3_GET_CERT_STATUS, SSL_R_LENGTH_MISMATCH);
2256280304Sjkim        goto f_err;
2257280304Sjkim    }
2258280304Sjkim    if (s->tlsext_ocsp_resp)
2259280304Sjkim        OPENSSL_free(s->tlsext_ocsp_resp);
2260280304Sjkim    s->tlsext_ocsp_resp = BUF_memdup(p, resplen);
2261280304Sjkim    if (!s->tlsext_ocsp_resp) {
2262280304Sjkim        al = SSL_AD_INTERNAL_ERROR;
2263280304Sjkim        SSLerr(SSL_F_SSL3_GET_CERT_STATUS, ERR_R_MALLOC_FAILURE);
2264280304Sjkim        goto f_err;
2265280304Sjkim    }
2266280304Sjkim    s->tlsext_ocsp_resplen = resplen;
2267280304Sjkim    if (s->ctx->tlsext_status_cb) {
2268280304Sjkim        int ret;
2269280304Sjkim        ret = s->ctx->tlsext_status_cb(s, s->ctx->tlsext_status_arg);
2270280304Sjkim        if (ret == 0) {
2271280304Sjkim            al = SSL_AD_BAD_CERTIFICATE_STATUS_RESPONSE;
2272280304Sjkim            SSLerr(SSL_F_SSL3_GET_CERT_STATUS, SSL_R_INVALID_STATUS_RESPONSE);
2273280304Sjkim            goto f_err;
2274280304Sjkim        }
2275280304Sjkim        if (ret < 0) {
2276280304Sjkim            al = SSL_AD_INTERNAL_ERROR;
2277280304Sjkim            SSLerr(SSL_F_SSL3_GET_CERT_STATUS, ERR_R_MALLOC_FAILURE);
2278280304Sjkim            goto f_err;
2279280304Sjkim        }
2280280304Sjkim    }
2281280304Sjkim    return 1;
2282280304Sjkim f_err:
2283280304Sjkim    ssl3_send_alert(s, SSL3_AL_FATAL, al);
2284284285Sjkim    s->state = SSL_ST_ERR;
2285280304Sjkim    return (-1);
2286280304Sjkim}
2287194206Ssimon#endif
2288194206Ssimon
2289160814Ssimonint ssl3_get_server_done(SSL *s)
2290280304Sjkim{
2291280304Sjkim    int ok, ret = 0;
2292280304Sjkim    long n;
229355714Skris
2294280304Sjkim    /* Second to last param should be very small, like 0 :-) */
2295280304Sjkim    n = s->method->ssl_get_message(s,
2296280304Sjkim                                   SSL3_ST_CR_SRVR_DONE_A,
2297280304Sjkim                                   SSL3_ST_CR_SRVR_DONE_B,
2298280304Sjkim                                   SSL3_MT_SERVER_DONE, 30, &ok);
229955714Skris
2300280304Sjkim    if (!ok)
2301280304Sjkim        return ((int)n);
2302280304Sjkim    if (n > 0) {
2303280304Sjkim        /* should contain no data */
2304280304Sjkim        ssl3_send_alert(s, SSL3_AL_FATAL, SSL_AD_DECODE_ERROR);
2305280304Sjkim        SSLerr(SSL_F_SSL3_GET_SERVER_DONE, SSL_R_LENGTH_MISMATCH);
2306284285Sjkim        s->state = SSL_ST_ERR;
2307280304Sjkim        return -1;
2308280304Sjkim    }
2309280304Sjkim    ret = 1;
2310280304Sjkim    return (ret);
2311280304Sjkim}
231255714Skris
2313160814Ssimonint ssl3_send_client_key_exchange(SSL *s)
2314280304Sjkim{
2315280304Sjkim    unsigned char *p, *d;
2316280304Sjkim    int n;
2317280304Sjkim    unsigned long alg_k;
2318109998Smarkm#ifndef OPENSSL_NO_RSA
2319280304Sjkim    unsigned char *q;
2320280304Sjkim    EVP_PKEY *pkey = NULL;
232155714Skris#endif
2322109998Smarkm#ifndef OPENSSL_NO_KRB5
2323280304Sjkim    KSSL_ERR kssl_err;
2324280304Sjkim#endif                          /* OPENSSL_NO_KRB5 */
2325160814Ssimon#ifndef OPENSSL_NO_ECDH
2326280304Sjkim    EC_KEY *clnt_ecdh = NULL;
2327280304Sjkim    const EC_POINT *srvr_ecpoint = NULL;
2328280304Sjkim    EVP_PKEY *srvr_pub_pkey = NULL;
2329280304Sjkim    unsigned char *encodedPoint = NULL;
2330280304Sjkim    int encoded_pt_len = 0;
2331280304Sjkim    BN_CTX *bn_ctx = NULL;
2332160814Ssimon#endif
233355714Skris
2334280304Sjkim    if (s->state == SSL3_ST_CW_KEY_EXCH_A) {
2335280304Sjkim        d = (unsigned char *)s->init_buf->data;
2336280304Sjkim        p = &(d[4]);
233755714Skris
2338280304Sjkim        alg_k = s->s3->tmp.new_cipher->algorithm_mkey;
233955714Skris
2340280304Sjkim        /* Fool emacs indentation */
2341280304Sjkim        if (0) {
2342280304Sjkim        }
2343109998Smarkm#ifndef OPENSSL_NO_RSA
2344280304Sjkim        else if (alg_k & SSL_kRSA) {
2345280304Sjkim            RSA *rsa;
2346280304Sjkim            unsigned char tmp_buf[SSL_MAX_MASTER_KEY_LENGTH];
234755714Skris
2348280304Sjkim            if (s->session->sess_cert == NULL) {
2349280304Sjkim                /*
2350280304Sjkim                 * We should always have a server certificate with SSL_kRSA.
2351280304Sjkim                 */
2352280304Sjkim                SSLerr(SSL_F_SSL3_SEND_CLIENT_KEY_EXCHANGE,
2353280304Sjkim                       ERR_R_INTERNAL_ERROR);
2354280304Sjkim                goto err;
2355280304Sjkim            }
2356269686Sjkim
2357280304Sjkim            if (s->session->sess_cert->peer_rsa_tmp != NULL)
2358280304Sjkim                rsa = s->session->sess_cert->peer_rsa_tmp;
2359280304Sjkim            else {
2360280304Sjkim                pkey =
2361280304Sjkim                    X509_get_pubkey(s->session->
2362280304Sjkim                                    sess_cert->peer_pkeys[SSL_PKEY_RSA_ENC].
2363280304Sjkim                                    x509);
2364280304Sjkim                if ((pkey == NULL) || (pkey->type != EVP_PKEY_RSA)
2365280304Sjkim                    || (pkey->pkey.rsa == NULL)) {
2366280304Sjkim                    SSLerr(SSL_F_SSL3_SEND_CLIENT_KEY_EXCHANGE,
2367280304Sjkim                           ERR_R_INTERNAL_ERROR);
2368280304Sjkim                    goto err;
2369280304Sjkim                }
2370280304Sjkim                rsa = pkey->pkey.rsa;
2371280304Sjkim                EVP_PKEY_free(pkey);
2372280304Sjkim            }
237355714Skris
2374280304Sjkim            tmp_buf[0] = s->client_version >> 8;
2375280304Sjkim            tmp_buf[1] = s->client_version & 0xff;
2376280304Sjkim            if (RAND_bytes(&(tmp_buf[2]), sizeof tmp_buf - 2) <= 0)
2377280304Sjkim                goto err;
237855714Skris
2379280304Sjkim            s->session->master_key_length = sizeof tmp_buf;
238055714Skris
2381280304Sjkim            q = p;
2382280304Sjkim            /* Fix buf for TLS and beyond */
2383280304Sjkim            if (s->version > SSL3_VERSION)
2384280304Sjkim                p += 2;
2385280304Sjkim            n = RSA_public_encrypt(sizeof tmp_buf,
2386280304Sjkim                                   tmp_buf, p, rsa, RSA_PKCS1_PADDING);
2387280304Sjkim# ifdef PKCS1_CHECK
2388280304Sjkim            if (s->options & SSL_OP_PKCS1_CHECK_1)
2389280304Sjkim                p[1]++;
2390280304Sjkim            if (s->options & SSL_OP_PKCS1_CHECK_2)
2391280304Sjkim                tmp_buf[0] = 0x70;
2392280304Sjkim# endif
2393280304Sjkim            if (n <= 0) {
2394280304Sjkim                SSLerr(SSL_F_SSL3_SEND_CLIENT_KEY_EXCHANGE,
2395280304Sjkim                       SSL_R_BAD_RSA_ENCRYPT);
2396280304Sjkim                goto err;
2397280304Sjkim            }
239855714Skris
2399280304Sjkim            /* Fix buf for TLS and beyond */
2400280304Sjkim            if (s->version > SSL3_VERSION) {
2401280304Sjkim                s2n(n, q);
2402280304Sjkim                n += 2;
2403280304Sjkim            }
2404280304Sjkim
2405280304Sjkim            s->session->master_key_length =
2406280304Sjkim                s->method->ssl3_enc->generate_master_secret(s,
2407280304Sjkim                                                            s->
2408280304Sjkim                                                            session->master_key,
2409280304Sjkim                                                            tmp_buf,
2410280304Sjkim                                                            sizeof tmp_buf);
2411280304Sjkim            OPENSSL_cleanse(tmp_buf, sizeof tmp_buf);
2412280304Sjkim        }
241355714Skris#endif
2414109998Smarkm#ifndef OPENSSL_NO_KRB5
2415280304Sjkim        else if (alg_k & SSL_kKRB5) {
2416280304Sjkim            krb5_error_code krb5rc;
2417280304Sjkim            KSSL_CTX *kssl_ctx = s->kssl_ctx;
2418280304Sjkim            /*  krb5_data   krb5_ap_req;  */
2419280304Sjkim            krb5_data *enc_ticket;
2420280304Sjkim            krb5_data authenticator, *authp = NULL;
2421280304Sjkim            EVP_CIPHER_CTX ciph_ctx;
2422280304Sjkim            const EVP_CIPHER *enc = NULL;
2423280304Sjkim            unsigned char iv[EVP_MAX_IV_LENGTH];
2424280304Sjkim            unsigned char tmp_buf[SSL_MAX_MASTER_KEY_LENGTH];
2425280304Sjkim            unsigned char epms[SSL_MAX_MASTER_KEY_LENGTH + EVP_MAX_IV_LENGTH];
2426280304Sjkim            int padl, outl = sizeof(epms);
2427109998Smarkm
2428280304Sjkim            EVP_CIPHER_CTX_init(&ciph_ctx);
2429109998Smarkm
2430280304Sjkim# ifdef KSSL_DEBUG
2431280304Sjkim            fprintf(stderr, "ssl3_send_client_key_exchange(%lx & %lx)\n",
2432280304Sjkim                    alg_k, SSL_kKRB5);
2433280304Sjkim# endif                         /* KSSL_DEBUG */
2434109998Smarkm
2435280304Sjkim            authp = NULL;
2436280304Sjkim# ifdef KRB5SENDAUTH
2437280304Sjkim            if (KRB5SENDAUTH)
2438280304Sjkim                authp = &authenticator;
2439280304Sjkim# endif                         /* KRB5SENDAUTH */
2440109998Smarkm
2441280304Sjkim            krb5rc = kssl_cget_tkt(kssl_ctx, &enc_ticket, authp, &kssl_err);
2442280304Sjkim            enc = kssl_map_enc(kssl_ctx->enctype);
2443280304Sjkim            if (enc == NULL)
2444280304Sjkim                goto err;
2445280304Sjkim# ifdef KSSL_DEBUG
2446280304Sjkim            {
2447280304Sjkim                fprintf(stderr, "kssl_cget_tkt rtn %d\n", krb5rc);
2448280304Sjkim                if (krb5rc && kssl_err.text)
2449280304Sjkim                    fprintf(stderr, "kssl_cget_tkt kssl_err=%s\n",
2450280304Sjkim                            kssl_err.text);
2451280304Sjkim            }
2452280304Sjkim# endif                         /* KSSL_DEBUG */
2453109998Smarkm
2454280304Sjkim            if (krb5rc) {
2455280304Sjkim                ssl3_send_alert(s, SSL3_AL_FATAL, SSL_AD_HANDSHAKE_FAILURE);
2456280304Sjkim                SSLerr(SSL_F_SSL3_SEND_CLIENT_KEY_EXCHANGE, kssl_err.reason);
2457280304Sjkim                goto err;
2458280304Sjkim            }
2459109998Smarkm
2460280304Sjkim            /*-
2461280304Sjkim             * 20010406 VRS - Earlier versions used KRB5 AP_REQ
2462280304Sjkim             * in place of RFC 2712 KerberosWrapper, as in:
2463280304Sjkim             *
2464280304Sjkim             * Send ticket (copy to *p, set n = length)
2465280304Sjkim             * n = krb5_ap_req.length;
2466280304Sjkim             * memcpy(p, krb5_ap_req.data, krb5_ap_req.length);
2467280304Sjkim             * if (krb5_ap_req.data)
2468280304Sjkim             *   kssl_krb5_free_data_contents(NULL,&krb5_ap_req);
2469280304Sjkim             *
2470280304Sjkim             * Now using real RFC 2712 KerberosWrapper
2471280304Sjkim             * (Thanks to Simon Wilkinson <sxw@sxw.org.uk>)
2472280304Sjkim             * Note: 2712 "opaque" types are here replaced
2473280304Sjkim             * with a 2-byte length followed by the value.
2474280304Sjkim             * Example:
2475280304Sjkim             * KerberosWrapper= xx xx asn1ticket 0 0 xx xx encpms
2476280304Sjkim             * Where "xx xx" = length bytes.  Shown here with
2477280304Sjkim             * optional authenticator omitted.
2478280304Sjkim             */
2479109998Smarkm
2480280304Sjkim            /*  KerberosWrapper.Ticket              */
2481280304Sjkim            s2n(enc_ticket->length, p);
2482280304Sjkim            memcpy(p, enc_ticket->data, enc_ticket->length);
2483280304Sjkim            p += enc_ticket->length;
2484280304Sjkim            n = enc_ticket->length + 2;
2485109998Smarkm
2486280304Sjkim            /*  KerberosWrapper.Authenticator       */
2487280304Sjkim            if (authp && authp->length) {
2488280304Sjkim                s2n(authp->length, p);
2489280304Sjkim                memcpy(p, authp->data, authp->length);
2490280304Sjkim                p += authp->length;
2491280304Sjkim                n += authp->length + 2;
2492109998Smarkm
2493280304Sjkim                free(authp->data);
2494280304Sjkim                authp->data = NULL;
2495280304Sjkim                authp->length = 0;
2496280304Sjkim            } else {
2497280304Sjkim                s2n(0, p);      /* null authenticator length */
2498280304Sjkim                n += 2;
2499280304Sjkim            }
2500109998Smarkm
2501280304Sjkim            tmp_buf[0] = s->client_version >> 8;
2502280304Sjkim            tmp_buf[1] = s->client_version & 0xff;
2503280304Sjkim            if (RAND_bytes(&(tmp_buf[2]), sizeof tmp_buf - 2) <= 0)
2504280304Sjkim                goto err;
2505109998Smarkm
2506280304Sjkim            /*-
2507280304Sjkim             * 20010420 VRS.  Tried it this way; failed.
2508280304Sjkim             *      EVP_EncryptInit_ex(&ciph_ctx,enc, NULL,NULL);
2509280304Sjkim             *      EVP_CIPHER_CTX_set_key_length(&ciph_ctx,
2510280304Sjkim             *                              kssl_ctx->length);
2511280304Sjkim             *      EVP_EncryptInit_ex(&ciph_ctx,NULL, key,iv);
2512280304Sjkim             */
2513109998Smarkm
2514280304Sjkim            memset(iv, 0, sizeof iv); /* per RFC 1510 */
2515280304Sjkim            EVP_EncryptInit_ex(&ciph_ctx, enc, NULL, kssl_ctx->key, iv);
2516280304Sjkim            EVP_EncryptUpdate(&ciph_ctx, epms, &outl, tmp_buf,
2517280304Sjkim                              sizeof tmp_buf);
2518280304Sjkim            EVP_EncryptFinal_ex(&ciph_ctx, &(epms[outl]), &padl);
2519280304Sjkim            outl += padl;
2520280304Sjkim            if (outl > (int)sizeof epms) {
2521280304Sjkim                SSLerr(SSL_F_SSL3_SEND_CLIENT_KEY_EXCHANGE,
2522280304Sjkim                       ERR_R_INTERNAL_ERROR);
2523280304Sjkim                goto err;
2524280304Sjkim            }
2525280304Sjkim            EVP_CIPHER_CTX_cleanup(&ciph_ctx);
2526109998Smarkm
2527280304Sjkim            /*  KerberosWrapper.EncryptedPreMasterSecret    */
2528280304Sjkim            s2n(outl, p);
2529280304Sjkim            memcpy(p, epms, outl);
2530280304Sjkim            p += outl;
2531280304Sjkim            n += outl + 2;
2532280304Sjkim
2533280304Sjkim            s->session->master_key_length =
2534280304Sjkim                s->method->ssl3_enc->generate_master_secret(s,
2535280304Sjkim                                                            s->
2536280304Sjkim                                                            session->master_key,
2537280304Sjkim                                                            tmp_buf,
2538280304Sjkim                                                            sizeof tmp_buf);
2539280304Sjkim
2540280304Sjkim            OPENSSL_cleanse(tmp_buf, sizeof tmp_buf);
2541280304Sjkim            OPENSSL_cleanse(epms, outl);
2542280304Sjkim        }
2543109998Smarkm#endif
2544109998Smarkm#ifndef OPENSSL_NO_DH
2545280304Sjkim        else if (alg_k & (SSL_kEDH | SSL_kDHr | SSL_kDHd)) {
2546280304Sjkim            DH *dh_srvr, *dh_clnt;
254755714Skris
2548280304Sjkim            if (s->session->sess_cert == NULL) {
2549280304Sjkim                ssl3_send_alert(s, SSL3_AL_FATAL, SSL_AD_UNEXPECTED_MESSAGE);
2550280304Sjkim                SSLerr(SSL_F_SSL3_SEND_CLIENT_KEY_EXCHANGE,
2551280304Sjkim                       SSL_R_UNEXPECTED_MESSAGE);
2552280304Sjkim                goto err;
2553280304Sjkim            }
2554194206Ssimon
2555280304Sjkim            if (s->session->sess_cert->peer_dh_tmp != NULL)
2556280304Sjkim                dh_srvr = s->session->sess_cert->peer_dh_tmp;
2557280304Sjkim            else {
2558280304Sjkim                /* we get them from the cert */
2559280304Sjkim                ssl3_send_alert(s, SSL3_AL_FATAL, SSL_AD_HANDSHAKE_FAILURE);
2560280304Sjkim                SSLerr(SSL_F_SSL3_SEND_CLIENT_KEY_EXCHANGE,
2561280304Sjkim                       SSL_R_UNABLE_TO_FIND_DH_PARAMETERS);
2562280304Sjkim                goto err;
2563280304Sjkim            }
256455714Skris
2565280304Sjkim            /* generate a new random key */
2566280304Sjkim            if ((dh_clnt = DHparams_dup(dh_srvr)) == NULL) {
2567280304Sjkim                SSLerr(SSL_F_SSL3_SEND_CLIENT_KEY_EXCHANGE, ERR_R_DH_LIB);
2568280304Sjkim                goto err;
2569280304Sjkim            }
2570280304Sjkim            if (!DH_generate_key(dh_clnt)) {
2571280304Sjkim                SSLerr(SSL_F_SSL3_SEND_CLIENT_KEY_EXCHANGE, ERR_R_DH_LIB);
2572280304Sjkim                DH_free(dh_clnt);
2573280304Sjkim                goto err;
2574280304Sjkim            }
257555714Skris
2576280304Sjkim            /*
2577280304Sjkim             * use the 'p' output buffer for the DH key, but make sure to
2578280304Sjkim             * clear it out afterwards
2579280304Sjkim             */
258055714Skris
2581280304Sjkim            n = DH_compute_key(p, dh_srvr->pub_key, dh_clnt);
258255714Skris
2583280304Sjkim            if (n <= 0) {
2584280304Sjkim                SSLerr(SSL_F_SSL3_SEND_CLIENT_KEY_EXCHANGE, ERR_R_DH_LIB);
2585280304Sjkim                DH_free(dh_clnt);
2586280304Sjkim                goto err;
2587280304Sjkim            }
258855714Skris
2589280304Sjkim            /* generate master key from the result */
2590280304Sjkim            s->session->master_key_length =
2591280304Sjkim                s->method->ssl3_enc->generate_master_secret(s,
2592280304Sjkim                                                            s->
2593280304Sjkim                                                            session->master_key,
2594280304Sjkim                                                            p, n);
2595280304Sjkim            /* clean up */
2596280304Sjkim            memset(p, 0, n);
259755714Skris
2598280304Sjkim            /* send off the data */
2599280304Sjkim            n = BN_num_bytes(dh_clnt->pub_key);
2600280304Sjkim            s2n(n, p);
2601280304Sjkim            BN_bn2bin(dh_clnt->pub_key, p);
2602280304Sjkim            n += 2;
260355714Skris
2604280304Sjkim            DH_free(dh_clnt);
2605280304Sjkim        }
2606109998Smarkm#endif
2607160814Ssimon
2608280304Sjkim#ifndef OPENSSL_NO_ECDH
2609280304Sjkim        else if (alg_k & (SSL_kEECDH | SSL_kECDHr | SSL_kECDHe)) {
2610280304Sjkim            const EC_GROUP *srvr_group = NULL;
2611280304Sjkim            EC_KEY *tkey;
2612280304Sjkim            int ecdh_clnt_cert = 0;
2613280304Sjkim            int field_size = 0;
2614160814Ssimon
2615280304Sjkim            if (s->session->sess_cert == NULL) {
2616280304Sjkim                ssl3_send_alert(s, SSL3_AL_FATAL, SSL_AD_UNEXPECTED_MESSAGE);
2617280304Sjkim                SSLerr(SSL_F_SSL3_SEND_CLIENT_KEY_EXCHANGE,
2618280304Sjkim                       SSL_R_UNEXPECTED_MESSAGE);
2619280304Sjkim                goto err;
2620280304Sjkim            }
2621267103Sdelphij
2622280304Sjkim            /*
2623280304Sjkim             * Did we send out the client's ECDH share for use in premaster
2624280304Sjkim             * computation as part of client certificate? If so, set
2625280304Sjkim             * ecdh_clnt_cert to 1.
2626280304Sjkim             */
2627280304Sjkim            if ((alg_k & (SSL_kECDHr | SSL_kECDHe)) && (s->cert != NULL)) {
2628280304Sjkim                /*-
2629280304Sjkim                 * XXX: For now, we do not support client
2630280304Sjkim                 * authentication using ECDH certificates.
2631280304Sjkim                 * To add such support, one needs to add
2632280304Sjkim                 * code that checks for appropriate
2633280304Sjkim                 * conditions and sets ecdh_clnt_cert to 1.
2634280304Sjkim                 * For example, the cert have an ECC
2635280304Sjkim                 * key on the same curve as the server's
2636280304Sjkim                 * and the key should be authorized for
2637280304Sjkim                 * key agreement.
2638280304Sjkim                 *
2639280304Sjkim                 * One also needs to add code in ssl3_connect
2640280304Sjkim                 * to skip sending the certificate verify
2641280304Sjkim                 * message.
2642280304Sjkim                 *
2643280304Sjkim                 * if ((s->cert->key->privatekey != NULL) &&
2644280304Sjkim                 *     (s->cert->key->privatekey->type ==
2645280304Sjkim                 *      EVP_PKEY_EC) && ...)
2646280304Sjkim                 * ecdh_clnt_cert = 1;
2647280304Sjkim                 */
2648280304Sjkim            }
2649160814Ssimon
2650280304Sjkim            if (s->session->sess_cert->peer_ecdh_tmp != NULL) {
2651280304Sjkim                tkey = s->session->sess_cert->peer_ecdh_tmp;
2652280304Sjkim            } else {
2653280304Sjkim                /* Get the Server Public Key from Cert */
2654280304Sjkim                srvr_pub_pkey =
2655280304Sjkim                    X509_get_pubkey(s->session->
2656280304Sjkim                                    sess_cert->peer_pkeys[SSL_PKEY_ECC].x509);
2657280304Sjkim                if ((srvr_pub_pkey == NULL)
2658280304Sjkim                    || (srvr_pub_pkey->type != EVP_PKEY_EC)
2659280304Sjkim                    || (srvr_pub_pkey->pkey.ec == NULL)) {
2660280304Sjkim                    SSLerr(SSL_F_SSL3_SEND_CLIENT_KEY_EXCHANGE,
2661280304Sjkim                           ERR_R_INTERNAL_ERROR);
2662280304Sjkim                    goto err;
2663280304Sjkim                }
2664160814Ssimon
2665280304Sjkim                tkey = srvr_pub_pkey->pkey.ec;
2666280304Sjkim            }
2667160814Ssimon
2668280304Sjkim            srvr_group = EC_KEY_get0_group(tkey);
2669280304Sjkim            srvr_ecpoint = EC_KEY_get0_public_key(tkey);
2670160814Ssimon
2671280304Sjkim            if ((srvr_group == NULL) || (srvr_ecpoint == NULL)) {
2672280304Sjkim                SSLerr(SSL_F_SSL3_SEND_CLIENT_KEY_EXCHANGE,
2673280304Sjkim                       ERR_R_INTERNAL_ERROR);
2674280304Sjkim                goto err;
2675280304Sjkim            }
2676160814Ssimon
2677280304Sjkim            if ((clnt_ecdh = EC_KEY_new()) == NULL) {
2678280304Sjkim                SSLerr(SSL_F_SSL3_SEND_CLIENT_KEY_EXCHANGE,
2679280304Sjkim                       ERR_R_MALLOC_FAILURE);
2680280304Sjkim                goto err;
2681280304Sjkim            }
2682160814Ssimon
2683280304Sjkim            if (!EC_KEY_set_group(clnt_ecdh, srvr_group)) {
2684280304Sjkim                SSLerr(SSL_F_SSL3_SEND_CLIENT_KEY_EXCHANGE, ERR_R_EC_LIB);
2685280304Sjkim                goto err;
2686280304Sjkim            }
2687280304Sjkim            if (ecdh_clnt_cert) {
2688280304Sjkim                /*
2689280304Sjkim                 * Reuse key info from our certificate We only need our
2690280304Sjkim                 * private key to perform the ECDH computation.
2691280304Sjkim                 */
2692280304Sjkim                const BIGNUM *priv_key;
2693280304Sjkim                tkey = s->cert->key->privatekey->pkey.ec;
2694280304Sjkim                priv_key = EC_KEY_get0_private_key(tkey);
2695280304Sjkim                if (priv_key == NULL) {
2696280304Sjkim                    SSLerr(SSL_F_SSL3_SEND_CLIENT_KEY_EXCHANGE,
2697280304Sjkim                           ERR_R_MALLOC_FAILURE);
2698280304Sjkim                    goto err;
2699280304Sjkim                }
2700280304Sjkim                if (!EC_KEY_set_private_key(clnt_ecdh, priv_key)) {
2701280304Sjkim                    SSLerr(SSL_F_SSL3_SEND_CLIENT_KEY_EXCHANGE, ERR_R_EC_LIB);
2702280304Sjkim                    goto err;
2703280304Sjkim                }
2704280304Sjkim            } else {
2705280304Sjkim                /* Generate a new ECDH key pair */
2706280304Sjkim                if (!(EC_KEY_generate_key(clnt_ecdh))) {
2707280304Sjkim                    SSLerr(SSL_F_SSL3_SEND_CLIENT_KEY_EXCHANGE,
2708280304Sjkim                           ERR_R_ECDH_LIB);
2709280304Sjkim                    goto err;
2710280304Sjkim                }
2711280304Sjkim            }
2712160814Ssimon
2713280304Sjkim            /*
2714280304Sjkim             * use the 'p' output buffer for the ECDH key, but make sure to
2715280304Sjkim             * clear it out afterwards
2716280304Sjkim             */
2717160814Ssimon
2718280304Sjkim            field_size = EC_GROUP_get_degree(srvr_group);
2719280304Sjkim            if (field_size <= 0) {
2720280304Sjkim                SSLerr(SSL_F_SSL3_SEND_CLIENT_KEY_EXCHANGE, ERR_R_ECDH_LIB);
2721280304Sjkim                goto err;
2722280304Sjkim            }
2723280304Sjkim            n = ECDH_compute_key(p, (field_size + 7) / 8, srvr_ecpoint,
2724280304Sjkim                                 clnt_ecdh, NULL);
2725280304Sjkim            if (n <= 0) {
2726280304Sjkim                SSLerr(SSL_F_SSL3_SEND_CLIENT_KEY_EXCHANGE, ERR_R_ECDH_LIB);
2727280304Sjkim                goto err;
2728280304Sjkim            }
2729160814Ssimon
2730280304Sjkim            /* generate master key from the result */
2731280304Sjkim            s->session->master_key_length =
2732280304Sjkim                s->method->ssl3_enc->generate_master_secret(s,
2733280304Sjkim                                                            s->
2734280304Sjkim                                                            session->master_key,
2735280304Sjkim                                                            p, n);
2736160814Ssimon
2737280304Sjkim            memset(p, 0, n);    /* clean up */
2738160814Ssimon
2739280304Sjkim            if (ecdh_clnt_cert) {
2740280304Sjkim                /* Send empty client key exch message */
2741280304Sjkim                n = 0;
2742280304Sjkim            } else {
2743280304Sjkim                /*
2744280304Sjkim                 * First check the size of encoding and allocate memory
2745280304Sjkim                 * accordingly.
2746280304Sjkim                 */
2747280304Sjkim                encoded_pt_len =
2748280304Sjkim                    EC_POINT_point2oct(srvr_group,
2749280304Sjkim                                       EC_KEY_get0_public_key(clnt_ecdh),
2750280304Sjkim                                       POINT_CONVERSION_UNCOMPRESSED,
2751280304Sjkim                                       NULL, 0, NULL);
2752160814Ssimon
2753280304Sjkim                encodedPoint = (unsigned char *)
2754280304Sjkim                    OPENSSL_malloc(encoded_pt_len * sizeof(unsigned char));
2755280304Sjkim                bn_ctx = BN_CTX_new();
2756280304Sjkim                if ((encodedPoint == NULL) || (bn_ctx == NULL)) {
2757280304Sjkim                    SSLerr(SSL_F_SSL3_SEND_CLIENT_KEY_EXCHANGE,
2758280304Sjkim                           ERR_R_MALLOC_FAILURE);
2759280304Sjkim                    goto err;
2760280304Sjkim                }
2761160814Ssimon
2762280304Sjkim                /* Encode the public key */
2763280304Sjkim                n = EC_POINT_point2oct(srvr_group,
2764280304Sjkim                                       EC_KEY_get0_public_key(clnt_ecdh),
2765280304Sjkim                                       POINT_CONVERSION_UNCOMPRESSED,
2766280304Sjkim                                       encodedPoint, encoded_pt_len, bn_ctx);
2767160814Ssimon
2768280304Sjkim                *p = n;         /* length of encoded point */
2769280304Sjkim                /* Encoded point will be copied here */
2770280304Sjkim                p += 1;
2771280304Sjkim                /* copy the point */
2772280304Sjkim                memcpy((unsigned char *)p, encodedPoint, n);
2773280304Sjkim                /* increment n to account for length field */
2774280304Sjkim                n += 1;
2775280304Sjkim            }
2776160814Ssimon
2777280304Sjkim            /* Free allocated memory */
2778280304Sjkim            BN_CTX_free(bn_ctx);
2779280304Sjkim            if (encodedPoint != NULL)
2780280304Sjkim                OPENSSL_free(encodedPoint);
2781280304Sjkim            if (clnt_ecdh != NULL)
2782280304Sjkim                EC_KEY_free(clnt_ecdh);
2783280304Sjkim            EVP_PKEY_free(srvr_pub_pkey);
2784280304Sjkim        }
2785280304Sjkim#endif                          /* !OPENSSL_NO_ECDH */
2786280304Sjkim        else if (alg_k & SSL_kGOST) {
2787280304Sjkim            /* GOST key exchange message creation */
2788280304Sjkim            EVP_PKEY_CTX *pkey_ctx;
2789280304Sjkim            X509 *peer_cert;
2790280304Sjkim            size_t msglen;
2791280304Sjkim            unsigned int md_len;
2792280304Sjkim            int keytype;
2793280304Sjkim            unsigned char premaster_secret[32], shared_ukm[32], tmp[256];
2794280304Sjkim            EVP_MD_CTX *ukm_hash;
2795280304Sjkim            EVP_PKEY *pub_key;
2796238405Sjkim
2797280304Sjkim            /*
2798280304Sjkim             * Get server sertificate PKEY and create ctx from it
2799280304Sjkim             */
2800280304Sjkim            peer_cert =
2801280304Sjkim                s->session->
2802280304Sjkim                sess_cert->peer_pkeys[(keytype = SSL_PKEY_GOST01)].x509;
2803280304Sjkim            if (!peer_cert)
2804280304Sjkim                peer_cert =
2805280304Sjkim                    s->session->
2806280304Sjkim                    sess_cert->peer_pkeys[(keytype = SSL_PKEY_GOST94)].x509;
2807280304Sjkim            if (!peer_cert) {
2808280304Sjkim                SSLerr(SSL_F_SSL3_SEND_CLIENT_KEY_EXCHANGE,
2809280304Sjkim                       SSL_R_NO_GOST_CERTIFICATE_SENT_BY_PEER);
2810280304Sjkim                goto err;
2811280304Sjkim            }
2812238405Sjkim
2813280304Sjkim            pkey_ctx = EVP_PKEY_CTX_new(pub_key =
2814280304Sjkim                                        X509_get_pubkey(peer_cert), NULL);
2815280304Sjkim            /*
2816280304Sjkim             * If we have send a certificate, and certificate key
2817280304Sjkim             *
2818280304Sjkim             * * parameters match those of server certificate, use
2819280304Sjkim             * certificate key for key exchange
2820280304Sjkim             */
2821238405Sjkim
2822280304Sjkim            /* Otherwise, generate ephemeral key pair */
2823238405Sjkim
2824280304Sjkim            EVP_PKEY_encrypt_init(pkey_ctx);
2825280304Sjkim            /* Generate session key */
2826284285Sjkim            if (RAND_bytes(premaster_secret, 32) <= 0) {
2827284285Sjkim                EVP_PKEY_CTX_free(pkey_ctx);
2828284285Sjkim                goto err;
2829284285Sjkim            }
2830280304Sjkim            /*
2831280304Sjkim             * If we have client certificate, use its secret as peer key
2832280304Sjkim             */
2833280304Sjkim            if (s->s3->tmp.cert_req && s->cert->key->privatekey) {
2834280304Sjkim                if (EVP_PKEY_derive_set_peer
2835280304Sjkim                    (pkey_ctx, s->cert->key->privatekey) <= 0) {
2836280304Sjkim                    /*
2837280304Sjkim                     * If there was an error - just ignore it. Ephemeral key
2838280304Sjkim                     * * would be used
2839280304Sjkim                     */
2840280304Sjkim                    ERR_clear_error();
2841280304Sjkim                }
2842280304Sjkim            }
2843280304Sjkim            /*
2844280304Sjkim             * Compute shared IV and store it in algorithm-specific context
2845280304Sjkim             * data
2846280304Sjkim             */
2847280304Sjkim            ukm_hash = EVP_MD_CTX_create();
2848280304Sjkim            EVP_DigestInit(ukm_hash,
2849280304Sjkim                           EVP_get_digestbynid(NID_id_GostR3411_94));
2850280304Sjkim            EVP_DigestUpdate(ukm_hash, s->s3->client_random,
2851280304Sjkim                             SSL3_RANDOM_SIZE);
2852280304Sjkim            EVP_DigestUpdate(ukm_hash, s->s3->server_random,
2853280304Sjkim                             SSL3_RANDOM_SIZE);
2854280304Sjkim            EVP_DigestFinal_ex(ukm_hash, shared_ukm, &md_len);
2855280304Sjkim            EVP_MD_CTX_destroy(ukm_hash);
2856280304Sjkim            if (EVP_PKEY_CTX_ctrl
2857280304Sjkim                (pkey_ctx, -1, EVP_PKEY_OP_ENCRYPT, EVP_PKEY_CTRL_SET_IV, 8,
2858280304Sjkim                 shared_ukm) < 0) {
2859280304Sjkim                SSLerr(SSL_F_SSL3_SEND_CLIENT_KEY_EXCHANGE,
2860280304Sjkim                       SSL_R_LIBRARY_BUG);
2861280304Sjkim                goto err;
2862280304Sjkim            }
2863280304Sjkim            /* Make GOST keytransport blob message */
2864280304Sjkim            /*
2865280304Sjkim             * Encapsulate it into sequence
2866280304Sjkim             */
2867280304Sjkim            *(p++) = V_ASN1_SEQUENCE | V_ASN1_CONSTRUCTED;
2868280304Sjkim            msglen = 255;
2869280304Sjkim            if (EVP_PKEY_encrypt(pkey_ctx, tmp, &msglen, premaster_secret, 32)
2870280304Sjkim                < 0) {
2871280304Sjkim                SSLerr(SSL_F_SSL3_SEND_CLIENT_KEY_EXCHANGE,
2872280304Sjkim                       SSL_R_LIBRARY_BUG);
2873280304Sjkim                goto err;
2874280304Sjkim            }
2875280304Sjkim            if (msglen >= 0x80) {
2876280304Sjkim                *(p++) = 0x81;
2877280304Sjkim                *(p++) = msglen & 0xff;
2878280304Sjkim                n = msglen + 3;
2879280304Sjkim            } else {
2880280304Sjkim                *(p++) = msglen & 0xff;
2881280304Sjkim                n = msglen + 2;
2882280304Sjkim            }
2883280304Sjkim            memcpy(p, tmp, msglen);
2884280304Sjkim            /* Check if pubkey from client certificate was used */
2885280304Sjkim            if (EVP_PKEY_CTX_ctrl
2886280304Sjkim                (pkey_ctx, -1, -1, EVP_PKEY_CTRL_PEER_KEY, 2, NULL) > 0) {
2887280304Sjkim                /* Set flag "skip certificate verify" */
2888280304Sjkim                s->s3->flags |= TLS1_FLAGS_SKIP_CERT_VERIFY;
2889280304Sjkim            }
2890280304Sjkim            EVP_PKEY_CTX_free(pkey_ctx);
2891280304Sjkim            s->session->master_key_length =
2892280304Sjkim                s->method->ssl3_enc->generate_master_secret(s,
2893280304Sjkim                                                            s->
2894280304Sjkim                                                            session->master_key,
2895280304Sjkim                                                            premaster_secret,
2896280304Sjkim                                                            32);
2897280304Sjkim            EVP_PKEY_free(pub_key);
2898280304Sjkim
2899280304Sjkim        }
2900238405Sjkim#ifndef OPENSSL_NO_SRP
2901280304Sjkim        else if (alg_k & SSL_kSRP) {
2902280304Sjkim            if (s->srp_ctx.A != NULL) {
2903280304Sjkim                /* send off the data */
2904280304Sjkim                n = BN_num_bytes(s->srp_ctx.A);
2905280304Sjkim                s2n(n, p);
2906280304Sjkim                BN_bn2bin(s->srp_ctx.A, p);
2907280304Sjkim                n += 2;
2908280304Sjkim            } else {
2909280304Sjkim                SSLerr(SSL_F_SSL3_SEND_CLIENT_KEY_EXCHANGE,
2910280304Sjkim                       ERR_R_INTERNAL_ERROR);
2911280304Sjkim                goto err;
2912280304Sjkim            }
2913280304Sjkim            if (s->session->srp_username != NULL)
2914280304Sjkim                OPENSSL_free(s->session->srp_username);
2915280304Sjkim            s->session->srp_username = BUF_strdup(s->srp_ctx.login);
2916280304Sjkim            if (s->session->srp_username == NULL) {
2917280304Sjkim                SSLerr(SSL_F_SSL3_SEND_CLIENT_KEY_EXCHANGE,
2918280304Sjkim                       ERR_R_MALLOC_FAILURE);
2919280304Sjkim                goto err;
2920280304Sjkim            }
2921238405Sjkim
2922280304Sjkim            if ((s->session->master_key_length =
2923280304Sjkim                 SRP_generate_client_master_secret(s,
2924280304Sjkim                                                   s->session->master_key)) <
2925280304Sjkim                0) {
2926280304Sjkim                SSLerr(SSL_F_SSL3_SEND_CLIENT_KEY_EXCHANGE,
2927280304Sjkim                       ERR_R_INTERNAL_ERROR);
2928280304Sjkim                goto err;
2929280304Sjkim            }
2930280304Sjkim        }
2931238405Sjkim#endif
2932238405Sjkim#ifndef OPENSSL_NO_PSK
2933280304Sjkim        else if (alg_k & SSL_kPSK) {
2934280304Sjkim            /*
2935280304Sjkim             * The callback needs PSK_MAX_IDENTITY_LEN + 1 bytes to return a
2936280304Sjkim             * \0-terminated identity. The last byte is for us for simulating
2937280304Sjkim             * strnlen.
2938280304Sjkim             */
2939280304Sjkim            char identity[PSK_MAX_IDENTITY_LEN + 2];
2940280304Sjkim            size_t identity_len;
2941280304Sjkim            unsigned char *t = NULL;
2942280304Sjkim            unsigned char psk_or_pre_ms[PSK_MAX_PSK_LEN * 2 + 4];
2943280304Sjkim            unsigned int pre_ms_len = 0, psk_len = 0;
2944280304Sjkim            int psk_err = 1;
2945238405Sjkim
2946280304Sjkim            n = 0;
2947280304Sjkim            if (s->psk_client_callback == NULL) {
2948280304Sjkim                SSLerr(SSL_F_SSL3_SEND_CLIENT_KEY_EXCHANGE,
2949280304Sjkim                       SSL_R_PSK_NO_CLIENT_CB);
2950280304Sjkim                goto err;
2951280304Sjkim            }
2952238405Sjkim
2953280304Sjkim            memset(identity, 0, sizeof(identity));
2954285330Sjkim            psk_len = s->psk_client_callback(s, s->session->psk_identity_hint,
2955280304Sjkim                                             identity, sizeof(identity) - 1,
2956280304Sjkim                                             psk_or_pre_ms,
2957280304Sjkim                                             sizeof(psk_or_pre_ms));
2958280304Sjkim            if (psk_len > PSK_MAX_PSK_LEN) {
2959280304Sjkim                SSLerr(SSL_F_SSL3_SEND_CLIENT_KEY_EXCHANGE,
2960280304Sjkim                       ERR_R_INTERNAL_ERROR);
2961280304Sjkim                goto psk_err;
2962280304Sjkim            } else if (psk_len == 0) {
2963280304Sjkim                SSLerr(SSL_F_SSL3_SEND_CLIENT_KEY_EXCHANGE,
2964280304Sjkim                       SSL_R_PSK_IDENTITY_NOT_FOUND);
2965280304Sjkim                goto psk_err;
2966280304Sjkim            }
2967280304Sjkim            identity[PSK_MAX_IDENTITY_LEN + 1] = '\0';
2968280304Sjkim            identity_len = strlen(identity);
2969280304Sjkim            if (identity_len > PSK_MAX_IDENTITY_LEN) {
2970280304Sjkim                SSLerr(SSL_F_SSL3_SEND_CLIENT_KEY_EXCHANGE,
2971280304Sjkim                       ERR_R_INTERNAL_ERROR);
2972280304Sjkim                goto psk_err;
2973280304Sjkim            }
2974280304Sjkim            /* create PSK pre_master_secret */
2975280304Sjkim            pre_ms_len = 2 + psk_len + 2 + psk_len;
2976280304Sjkim            t = psk_or_pre_ms;
2977280304Sjkim            memmove(psk_or_pre_ms + psk_len + 4, psk_or_pre_ms, psk_len);
2978280304Sjkim            s2n(psk_len, t);
2979280304Sjkim            memset(t, 0, psk_len);
2980280304Sjkim            t += psk_len;
2981280304Sjkim            s2n(psk_len, t);
2982238405Sjkim
2983280304Sjkim            if (s->session->psk_identity_hint != NULL)
2984280304Sjkim                OPENSSL_free(s->session->psk_identity_hint);
2985280304Sjkim            s->session->psk_identity_hint =
2986280304Sjkim                BUF_strdup(s->ctx->psk_identity_hint);
2987280304Sjkim            if (s->ctx->psk_identity_hint != NULL
2988280304Sjkim                && s->session->psk_identity_hint == NULL) {
2989280304Sjkim                SSLerr(SSL_F_SSL3_SEND_CLIENT_KEY_EXCHANGE,
2990280304Sjkim                       ERR_R_MALLOC_FAILURE);
2991280304Sjkim                goto psk_err;
2992280304Sjkim            }
2993238405Sjkim
2994280304Sjkim            if (s->session->psk_identity != NULL)
2995280304Sjkim                OPENSSL_free(s->session->psk_identity);
2996280304Sjkim            s->session->psk_identity = BUF_strdup(identity);
2997280304Sjkim            if (s->session->psk_identity == NULL) {
2998280304Sjkim                SSLerr(SSL_F_SSL3_SEND_CLIENT_KEY_EXCHANGE,
2999280304Sjkim                       ERR_R_MALLOC_FAILURE);
3000280304Sjkim                goto psk_err;
3001280304Sjkim            }
3002238405Sjkim
3003280304Sjkim            s->session->master_key_length =
3004280304Sjkim                s->method->ssl3_enc->generate_master_secret(s,
3005280304Sjkim                                                            s->
3006280304Sjkim                                                            session->master_key,
3007280304Sjkim                                                            psk_or_pre_ms,
3008280304Sjkim                                                            pre_ms_len);
3009280304Sjkim            s2n(identity_len, p);
3010280304Sjkim            memcpy(p, identity, identity_len);
3011280304Sjkim            n = 2 + identity_len;
3012280304Sjkim            psk_err = 0;
3013280304Sjkim psk_err:
3014280304Sjkim            OPENSSL_cleanse(identity, sizeof(identity));
3015280304Sjkim            OPENSSL_cleanse(psk_or_pre_ms, sizeof(psk_or_pre_ms));
3016280304Sjkim            if (psk_err != 0) {
3017280304Sjkim                ssl3_send_alert(s, SSL3_AL_FATAL, SSL_AD_HANDSHAKE_FAILURE);
3018280304Sjkim                goto err;
3019280304Sjkim            }
3020280304Sjkim        }
3021238405Sjkim#endif
3022280304Sjkim        else {
3023280304Sjkim            ssl3_send_alert(s, SSL3_AL_FATAL, SSL_AD_HANDSHAKE_FAILURE);
3024280304Sjkim            SSLerr(SSL_F_SSL3_SEND_CLIENT_KEY_EXCHANGE, ERR_R_INTERNAL_ERROR);
3025280304Sjkim            goto err;
3026280304Sjkim        }
302755714Skris
3028280304Sjkim        *(d++) = SSL3_MT_CLIENT_KEY_EXCHANGE;
3029280304Sjkim        l2n3(n, d);
303055714Skris
3031280304Sjkim        s->state = SSL3_ST_CW_KEY_EXCH_B;
3032280304Sjkim        /* number of bytes to write */
3033280304Sjkim        s->init_num = n + 4;
3034280304Sjkim        s->init_off = 0;
3035280304Sjkim    }
3036280304Sjkim
3037280304Sjkim    /* SSL3_ST_CW_KEY_EXCH_B */
3038280304Sjkim    return (ssl3_do_write(s, SSL3_RT_HANDSHAKE));
3039280304Sjkim err:
3040160814Ssimon#ifndef OPENSSL_NO_ECDH
3041280304Sjkim    BN_CTX_free(bn_ctx);
3042280304Sjkim    if (encodedPoint != NULL)
3043280304Sjkim        OPENSSL_free(encodedPoint);
3044280304Sjkim    if (clnt_ecdh != NULL)
3045280304Sjkim        EC_KEY_free(clnt_ecdh);
3046280304Sjkim    EVP_PKEY_free(srvr_pub_pkey);
3047160814Ssimon#endif
3048284285Sjkim    s->state = SSL_ST_ERR;
3049280304Sjkim    return (-1);
3050280304Sjkim}
305155714Skris
3052160814Ssimonint ssl3_send_client_verify(SSL *s)
3053280304Sjkim{
3054280304Sjkim    unsigned char *p, *d;
3055280304Sjkim    unsigned char data[MD5_DIGEST_LENGTH + SHA_DIGEST_LENGTH];
3056280304Sjkim    EVP_PKEY *pkey;
3057280304Sjkim    EVP_PKEY_CTX *pctx = NULL;
3058280304Sjkim    EVP_MD_CTX mctx;
3059280304Sjkim    unsigned u = 0;
3060280304Sjkim    unsigned long n;
3061280304Sjkim    int j;
306255714Skris
3063280304Sjkim    EVP_MD_CTX_init(&mctx);
3064238405Sjkim
3065280304Sjkim    if (s->state == SSL3_ST_CW_CERT_VRFY_A) {
3066280304Sjkim        d = (unsigned char *)s->init_buf->data;
3067280304Sjkim        p = &(d[4]);
3068280304Sjkim        pkey = s->cert->key->privatekey;
3069238405Sjkim/* Create context from key and test if sha1 is allowed as digest */
3070280304Sjkim        pctx = EVP_PKEY_CTX_new(pkey, NULL);
3071280304Sjkim        EVP_PKEY_sign_init(pctx);
3072280304Sjkim        if (EVP_PKEY_CTX_set_signature_md(pctx, EVP_sha1()) > 0) {
3073280304Sjkim            if (TLS1_get_version(s) < TLS1_2_VERSION)
3074280304Sjkim                s->method->ssl3_enc->cert_verify_mac(s,
3075280304Sjkim                                                     NID_sha1,
3076280304Sjkim                                                     &(data
3077280304Sjkim                                                       [MD5_DIGEST_LENGTH]));
3078280304Sjkim        } else {
3079280304Sjkim            ERR_clear_error();
3080280304Sjkim        }
3081280304Sjkim        /*
3082280304Sjkim         * For TLS v1.2 send signature algorithm and signature using agreed
3083280304Sjkim         * digest and cached handshake records.
3084280304Sjkim         */
3085280304Sjkim        if (TLS1_get_version(s) >= TLS1_2_VERSION) {
3086280304Sjkim            long hdatalen = 0;
3087280304Sjkim            void *hdata;
3088280304Sjkim            const EVP_MD *md = s->cert->key->digest;
3089280304Sjkim            hdatalen = BIO_get_mem_data(s->s3->handshake_buffer, &hdata);
3090280304Sjkim            if (hdatalen <= 0 || !tls12_get_sigandhash(p, pkey, md)) {
3091280304Sjkim                SSLerr(SSL_F_SSL3_SEND_CLIENT_VERIFY, ERR_R_INTERNAL_ERROR);
3092280304Sjkim                goto err;
3093280304Sjkim            }
3094280304Sjkim            p += 2;
3095238405Sjkim#ifdef SSL_DEBUG
3096280304Sjkim            fprintf(stderr, "Using TLS 1.2 with client alg %s\n",
3097280304Sjkim                    EVP_MD_name(md));
3098238405Sjkim#endif
3099280304Sjkim            if (!EVP_SignInit_ex(&mctx, md, NULL)
3100280304Sjkim                || !EVP_SignUpdate(&mctx, hdata, hdatalen)
3101280304Sjkim                || !EVP_SignFinal(&mctx, p + 2, &u, pkey)) {
3102280304Sjkim                SSLerr(SSL_F_SSL3_SEND_CLIENT_VERIFY, ERR_R_EVP_LIB);
3103280304Sjkim                goto err;
3104280304Sjkim            }
3105280304Sjkim            s2n(u, p);
3106280304Sjkim            n = u + 4;
3107280304Sjkim            if (!ssl3_digest_cached_records(s))
3108280304Sjkim                goto err;
3109280304Sjkim        } else
3110109998Smarkm#ifndef OPENSSL_NO_RSA
3111280304Sjkim        if (pkey->type == EVP_PKEY_RSA) {
3112280304Sjkim            s->method->ssl3_enc->cert_verify_mac(s, NID_md5, &(data[0]));
3113280304Sjkim            if (RSA_sign(NID_md5_sha1, data,
3114280304Sjkim                         MD5_DIGEST_LENGTH + SHA_DIGEST_LENGTH,
3115280304Sjkim                         &(p[2]), &u, pkey->pkey.rsa) <= 0) {
3116280304Sjkim                SSLerr(SSL_F_SSL3_SEND_CLIENT_VERIFY, ERR_R_RSA_LIB);
3117280304Sjkim                goto err;
3118280304Sjkim            }
3119280304Sjkim            s2n(u, p);
3120280304Sjkim            n = u + 2;
3121280304Sjkim        } else
312255714Skris#endif
3123109998Smarkm#ifndef OPENSSL_NO_DSA
3124280304Sjkim        if (pkey->type == EVP_PKEY_DSA) {
3125280304Sjkim            if (!DSA_sign(pkey->save_type,
3126280304Sjkim                          &(data[MD5_DIGEST_LENGTH]),
3127280304Sjkim                          SHA_DIGEST_LENGTH, &(p[2]),
3128280304Sjkim                          (unsigned int *)&j, pkey->pkey.dsa)) {
3129280304Sjkim                SSLerr(SSL_F_SSL3_SEND_CLIENT_VERIFY, ERR_R_DSA_LIB);
3130280304Sjkim                goto err;
3131280304Sjkim            }
3132280304Sjkim            s2n(j, p);
3133280304Sjkim            n = j + 2;
3134280304Sjkim        } else
313555714Skris#endif
3136160814Ssimon#ifndef OPENSSL_NO_ECDSA
3137280304Sjkim        if (pkey->type == EVP_PKEY_EC) {
3138280304Sjkim            if (!ECDSA_sign(pkey->save_type,
3139280304Sjkim                            &(data[MD5_DIGEST_LENGTH]),
3140280304Sjkim                            SHA_DIGEST_LENGTH, &(p[2]),
3141280304Sjkim                            (unsigned int *)&j, pkey->pkey.ec)) {
3142280304Sjkim                SSLerr(SSL_F_SSL3_SEND_CLIENT_VERIFY, ERR_R_ECDSA_LIB);
3143280304Sjkim                goto err;
3144280304Sjkim            }
3145280304Sjkim            s2n(j, p);
3146280304Sjkim            n = j + 2;
3147280304Sjkim        } else
3148160814Ssimon#endif
3149280304Sjkim        if (pkey->type == NID_id_GostR3410_94
3150280304Sjkim                || pkey->type == NID_id_GostR3410_2001) {
3151280304Sjkim            unsigned char signbuf[64];
3152280304Sjkim            int i;
3153280304Sjkim            size_t sigsize = 64;
3154280304Sjkim            s->method->ssl3_enc->cert_verify_mac(s,
3155280304Sjkim                                                 NID_id_GostR3411_94, data);
3156280304Sjkim            if (EVP_PKEY_sign(pctx, signbuf, &sigsize, data, 32) <= 0) {
3157280304Sjkim                SSLerr(SSL_F_SSL3_SEND_CLIENT_VERIFY, ERR_R_INTERNAL_ERROR);
3158280304Sjkim                goto err;
3159280304Sjkim            }
3160280304Sjkim            for (i = 63, j = 0; i >= 0; j++, i--) {
3161280304Sjkim                p[2 + j] = signbuf[i];
3162280304Sjkim            }
3163280304Sjkim            s2n(j, p);
3164280304Sjkim            n = j + 2;
3165280304Sjkim        } else {
3166280304Sjkim            SSLerr(SSL_F_SSL3_SEND_CLIENT_VERIFY, ERR_R_INTERNAL_ERROR);
3167280304Sjkim            goto err;
3168280304Sjkim        }
3169280304Sjkim        *(d++) = SSL3_MT_CERTIFICATE_VERIFY;
3170280304Sjkim        l2n3(n, d);
317155714Skris
3172280304Sjkim        s->state = SSL3_ST_CW_CERT_VRFY_B;
3173280304Sjkim        s->init_num = (int)n + 4;
3174280304Sjkim        s->init_off = 0;
3175280304Sjkim    }
3176280304Sjkim    EVP_MD_CTX_cleanup(&mctx);
3177280304Sjkim    EVP_PKEY_CTX_free(pctx);
3178280304Sjkim    return (ssl3_do_write(s, SSL3_RT_HANDSHAKE));
3179280304Sjkim err:
3180280304Sjkim    EVP_MD_CTX_cleanup(&mctx);
3181280304Sjkim    EVP_PKEY_CTX_free(pctx);
3182284285Sjkim    s->state = SSL_ST_ERR;
3183280304Sjkim    return (-1);
3184280304Sjkim}
318555714Skris
3186160814Ssimonint ssl3_send_client_certificate(SSL *s)
3187280304Sjkim{
3188280304Sjkim    X509 *x509 = NULL;
3189280304Sjkim    EVP_PKEY *pkey = NULL;
3190280304Sjkim    int i;
3191280304Sjkim    unsigned long l;
319255714Skris
3193280304Sjkim    if (s->state == SSL3_ST_CW_CERT_A) {
3194280304Sjkim        if ((s->cert == NULL) ||
3195280304Sjkim            (s->cert->key->x509 == NULL) ||
3196280304Sjkim            (s->cert->key->privatekey == NULL))
3197280304Sjkim            s->state = SSL3_ST_CW_CERT_B;
3198280304Sjkim        else
3199280304Sjkim            s->state = SSL3_ST_CW_CERT_C;
3200280304Sjkim    }
320155714Skris
3202280304Sjkim    /* We need to get a client cert */
3203280304Sjkim    if (s->state == SSL3_ST_CW_CERT_B) {
3204280304Sjkim        /*
3205280304Sjkim         * If we get an error, we need to ssl->rwstate=SSL_X509_LOOKUP;
3206280304Sjkim         * return(-1); We then get retied later
3207280304Sjkim         */
3208280304Sjkim        i = 0;
3209280304Sjkim        i = ssl_do_client_cert_cb(s, &x509, &pkey);
3210280304Sjkim        if (i < 0) {
3211280304Sjkim            s->rwstate = SSL_X509_LOOKUP;
3212280304Sjkim            return (-1);
3213280304Sjkim        }
3214280304Sjkim        s->rwstate = SSL_NOTHING;
3215280304Sjkim        if ((i == 1) && (pkey != NULL) && (x509 != NULL)) {
3216280304Sjkim            s->state = SSL3_ST_CW_CERT_B;
3217280304Sjkim            if (!SSL_use_certificate(s, x509) || !SSL_use_PrivateKey(s, pkey))
3218280304Sjkim                i = 0;
3219280304Sjkim        } else if (i == 1) {
3220280304Sjkim            i = 0;
3221280304Sjkim            SSLerr(SSL_F_SSL3_SEND_CLIENT_CERTIFICATE,
3222280304Sjkim                   SSL_R_BAD_DATA_RETURNED_BY_CALLBACK);
3223280304Sjkim        }
322455714Skris
3225280304Sjkim        if (x509 != NULL)
3226280304Sjkim            X509_free(x509);
3227280304Sjkim        if (pkey != NULL)
3228280304Sjkim            EVP_PKEY_free(pkey);
3229280304Sjkim        if (i == 0) {
3230280304Sjkim            if (s->version == SSL3_VERSION) {
3231280304Sjkim                s->s3->tmp.cert_req = 0;
3232280304Sjkim                ssl3_send_alert(s, SSL3_AL_WARNING, SSL_AD_NO_CERTIFICATE);
3233280304Sjkim                return (1);
3234280304Sjkim            } else {
3235280304Sjkim                s->s3->tmp.cert_req = 2;
3236280304Sjkim            }
3237280304Sjkim        }
323855714Skris
3239280304Sjkim        /* Ok, we have a cert */
3240280304Sjkim        s->state = SSL3_ST_CW_CERT_C;
3241280304Sjkim    }
324255714Skris
3243280304Sjkim    if (s->state == SSL3_ST_CW_CERT_C) {
3244280304Sjkim        s->state = SSL3_ST_CW_CERT_D;
3245280304Sjkim        l = ssl3_output_cert_chain(s,
3246280304Sjkim                                   (s->s3->tmp.cert_req ==
3247280304Sjkim                                    2) ? NULL : s->cert->key->x509);
3248280304Sjkim        if (!l) {
3249280304Sjkim            SSLerr(SSL_F_SSL3_SEND_CLIENT_CERTIFICATE, ERR_R_INTERNAL_ERROR);
3250280304Sjkim            ssl3_send_alert(s, SSL3_AL_FATAL, SSL_AD_INTERNAL_ERROR);
3251284285Sjkim            s->state = SSL_ST_ERR;
3252280304Sjkim            return 0;
3253280304Sjkim        }
3254280304Sjkim        s->init_num = (int)l;
3255280304Sjkim        s->init_off = 0;
3256280304Sjkim    }
3257280304Sjkim    /* SSL3_ST_CW_CERT_D */
3258280304Sjkim    return (ssl3_do_write(s, SSL3_RT_HANDSHAKE));
3259280304Sjkim}
326055714Skris
3261280304Sjkim#define has_bits(i,m)   (((i)&(m)) == (m))
326255714Skris
3263160814Ssimonint ssl3_check_cert_and_algorithm(SSL *s)
3264280304Sjkim{
3265280304Sjkim    int i, idx;
3266280304Sjkim    long alg_k, alg_a;
3267280304Sjkim    EVP_PKEY *pkey = NULL;
3268284285Sjkim    int pkey_bits;
3269280304Sjkim    SESS_CERT *sc;
3270109998Smarkm#ifndef OPENSSL_NO_RSA
3271280304Sjkim    RSA *rsa;
327255714Skris#endif
3273109998Smarkm#ifndef OPENSSL_NO_DH
3274280304Sjkim    DH *dh;
327555714Skris#endif
3276284285Sjkim    int al = SSL_AD_HANDSHAKE_FAILURE;
327755714Skris
3278280304Sjkim    alg_k = s->s3->tmp.new_cipher->algorithm_mkey;
3279280304Sjkim    alg_a = s->s3->tmp.new_cipher->algorithm_auth;
328055714Skris
3281280304Sjkim    /* we don't have a certificate */
3282280304Sjkim    if ((alg_a & (SSL_aDH | SSL_aNULL | SSL_aKRB5)) || (alg_k & SSL_kPSK))
3283280304Sjkim        return (1);
3284194206Ssimon
3285280304Sjkim    sc = s->session->sess_cert;
3286280304Sjkim    if (sc == NULL) {
3287280304Sjkim        SSLerr(SSL_F_SSL3_CHECK_CERT_AND_ALGORITHM, ERR_R_INTERNAL_ERROR);
3288280304Sjkim        goto err;
3289280304Sjkim    }
3290109998Smarkm#ifndef OPENSSL_NO_RSA
3291280304Sjkim    rsa = s->session->sess_cert->peer_rsa_tmp;
329255714Skris#endif
3293109998Smarkm#ifndef OPENSSL_NO_DH
3294280304Sjkim    dh = s->session->sess_cert->peer_dh_tmp;
329555714Skris#endif
329655714Skris
3297280304Sjkim    /* This is the passed certificate */
329855714Skris
3299280304Sjkim    idx = sc->peer_cert_type;
3300160814Ssimon#ifndef OPENSSL_NO_ECDH
3301280304Sjkim    if (idx == SSL_PKEY_ECC) {
3302280304Sjkim        if (ssl_check_srvr_ecc_cert_and_alg(sc->peer_pkeys[idx].x509, s) == 0) {
3303280304Sjkim            /* check failed */
3304280304Sjkim            SSLerr(SSL_F_SSL3_CHECK_CERT_AND_ALGORITHM, SSL_R_BAD_ECC_CERT);
3305280304Sjkim            goto f_err;
3306280304Sjkim        } else {
3307280304Sjkim            return 1;
3308280304Sjkim        }
3309280304Sjkim    }
3310160814Ssimon#endif
3311280304Sjkim    pkey = X509_get_pubkey(sc->peer_pkeys[idx].x509);
3312284285Sjkim    pkey_bits = EVP_PKEY_bits(pkey);
3313280304Sjkim    i = X509_certificate_type(sc->peer_pkeys[idx].x509, pkey);
3314280304Sjkim    EVP_PKEY_free(pkey);
331555714Skris
3316280304Sjkim    /* Check that we have a certificate if we require one */
3317280304Sjkim    if ((alg_a & SSL_aRSA) && !has_bits(i, EVP_PK_RSA | EVP_PKT_SIGN)) {
3318280304Sjkim        SSLerr(SSL_F_SSL3_CHECK_CERT_AND_ALGORITHM,
3319280304Sjkim               SSL_R_MISSING_RSA_SIGNING_CERT);
3320280304Sjkim        goto f_err;
3321280304Sjkim    }
3322109998Smarkm#ifndef OPENSSL_NO_DSA
3323280304Sjkim    else if ((alg_a & SSL_aDSS) && !has_bits(i, EVP_PK_DSA | EVP_PKT_SIGN)) {
3324280304Sjkim        SSLerr(SSL_F_SSL3_CHECK_CERT_AND_ALGORITHM,
3325280304Sjkim               SSL_R_MISSING_DSA_SIGNING_CERT);
3326280304Sjkim        goto f_err;
3327280304Sjkim    }
332855714Skris#endif
3329109998Smarkm#ifndef OPENSSL_NO_RSA
3330284285Sjkim    if (alg_k & SSL_kRSA) {
3331284285Sjkim        if (!SSL_C_IS_EXPORT(s->s3->tmp.new_cipher) &&
3332284285Sjkim            !has_bits(i, EVP_PK_RSA | EVP_PKT_ENC)) {
3333284285Sjkim            SSLerr(SSL_F_SSL3_CHECK_CERT_AND_ALGORITHM,
3334284285Sjkim                   SSL_R_MISSING_RSA_ENCRYPTING_CERT);
3335284285Sjkim            goto f_err;
3336284285Sjkim        } else if (SSL_C_IS_EXPORT(s->s3->tmp.new_cipher)) {
3337284285Sjkim            if (pkey_bits <= SSL_C_EXPORT_PKEYLENGTH(s->s3->tmp.new_cipher)) {
3338284285Sjkim                if (!has_bits(i, EVP_PK_RSA | EVP_PKT_ENC)) {
3339284285Sjkim                    SSLerr(SSL_F_SSL3_CHECK_CERT_AND_ALGORITHM,
3340284285Sjkim                           SSL_R_MISSING_RSA_ENCRYPTING_CERT);
3341284285Sjkim                    goto f_err;
3342284285Sjkim                }
3343284285Sjkim                if (rsa != NULL) {
3344284285Sjkim                    /* server key exchange is not allowed. */
3345284285Sjkim                    al = SSL_AD_INTERNAL_ERROR;
3346284285Sjkim                    SSLerr(SSL_F_SSL3_CHECK_CERT_AND_ALGORITHM, ERR_R_INTERNAL_ERROR);
3347284285Sjkim                    goto f_err;
3348284285Sjkim                }
3349284285Sjkim            }
3350284285Sjkim        }
3351280304Sjkim    }
335255714Skris#endif
3353109998Smarkm#ifndef OPENSSL_NO_DH
3354284285Sjkim    if ((alg_k & SSL_kEDH) && dh == NULL) {
3355284285Sjkim        al = SSL_AD_INTERNAL_ERROR;
3356284285Sjkim        SSLerr(SSL_F_SSL3_CHECK_CERT_AND_ALGORITHM, ERR_R_INTERNAL_ERROR);
3357280304Sjkim        goto f_err;
3358284285Sjkim    }
3359284285Sjkim    if ((alg_k & SSL_kDHr) && !has_bits(i, EVP_PK_DH | EVP_PKS_RSA)) {
3360280304Sjkim        SSLerr(SSL_F_SSL3_CHECK_CERT_AND_ALGORITHM,
3361280304Sjkim               SSL_R_MISSING_DH_RSA_CERT);
3362280304Sjkim        goto f_err;
3363280304Sjkim    }
3364280304Sjkim# ifndef OPENSSL_NO_DSA
3365284285Sjkim    if ((alg_k & SSL_kDHd) && !has_bits(i, EVP_PK_DH | EVP_PKS_DSA)) {
3366280304Sjkim        SSLerr(SSL_F_SSL3_CHECK_CERT_AND_ALGORITHM,
3367280304Sjkim               SSL_R_MISSING_DH_DSA_CERT);
3368280304Sjkim        goto f_err;
3369280304Sjkim    }
3370280304Sjkim# endif
337155714Skris
3372284285Sjkim    /* Check DHE only: static DH not implemented. */
3373284285Sjkim    if (alg_k & SSL_kEDH) {
3374284285Sjkim        int dh_size = BN_num_bits(dh->p);
3375284285Sjkim        if ((!SSL_C_IS_EXPORT(s->s3->tmp.new_cipher) && dh_size < 768)
3376284285Sjkim            || (SSL_C_IS_EXPORT(s->s3->tmp.new_cipher) && dh_size < 512)) {
3377284285Sjkim            SSLerr(SSL_F_SSL3_CHECK_CERT_AND_ALGORITHM, SSL_R_DH_KEY_TOO_SMALL);
3378284285Sjkim            goto f_err;
3379284285Sjkim        }
3380284285Sjkim    }
3381284285Sjkim#endif  /* !OPENSSL_NO_DH */
3382284285Sjkim
3383284285Sjkim    if (SSL_C_IS_EXPORT(s->s3->tmp.new_cipher) &&
3384284285Sjkim        pkey_bits > SSL_C_EXPORT_PKEYLENGTH(s->s3->tmp.new_cipher)) {
3385109998Smarkm#ifndef OPENSSL_NO_RSA
3386280304Sjkim        if (alg_k & SSL_kRSA) {
3387284285Sjkim            if (rsa == NULL) {
3388284285Sjkim                SSLerr(SSL_F_SSL3_CHECK_CERT_AND_ALGORITHM,
3389284285Sjkim                       SSL_R_MISSING_EXPORT_TMP_RSA_KEY);
3390284285Sjkim                goto f_err;
3391284285Sjkim            } else if (BN_num_bits(rsa->n) >
3392280304Sjkim                SSL_C_EXPORT_PKEYLENGTH(s->s3->tmp.new_cipher)) {
3393284285Sjkim                /* We have a temporary RSA key but it's too large. */
3394284285Sjkim                al = SSL_AD_EXPORT_RESTRICTION;
3395280304Sjkim                SSLerr(SSL_F_SSL3_CHECK_CERT_AND_ALGORITHM,
3396280304Sjkim                       SSL_R_MISSING_EXPORT_TMP_RSA_KEY);
3397280304Sjkim                goto f_err;
3398280304Sjkim            }
3399280304Sjkim        } else
340055714Skris#endif
3401109998Smarkm#ifndef OPENSSL_NO_DH
3402284285Sjkim        if (alg_k & SSL_kEDH) {
3403284285Sjkim            if (BN_num_bits(dh->p) >
3404280304Sjkim                SSL_C_EXPORT_PKEYLENGTH(s->s3->tmp.new_cipher)) {
3405284285Sjkim                /* We have a temporary DH key but it's too large. */
3406284285Sjkim                al = SSL_AD_EXPORT_RESTRICTION;
3407280304Sjkim                SSLerr(SSL_F_SSL3_CHECK_CERT_AND_ALGORITHM,
3408280304Sjkim                       SSL_R_MISSING_EXPORT_TMP_DH_KEY);
3409280304Sjkim                goto f_err;
3410280304Sjkim            }
3411284285Sjkim        } else if (alg_k & (SSL_kDHr | SSL_kDHd)) {
3412284285Sjkim            /* The cert should have had an export DH key. */
3413284285Sjkim            al = SSL_AD_EXPORT_RESTRICTION;
3414284285Sjkim            SSLerr(SSL_F_SSL3_CHECK_CERT_AND_ALGORITHM,
3415284285Sjkim                   SSL_R_MISSING_EXPORT_TMP_DH_KEY);
3416284285Sjkim                goto f_err;
3417280304Sjkim        } else
341855714Skris#endif
3419280304Sjkim        {
3420280304Sjkim            SSLerr(SSL_F_SSL3_CHECK_CERT_AND_ALGORITHM,
3421280304Sjkim                   SSL_R_UNKNOWN_KEY_EXCHANGE_TYPE);
3422280304Sjkim            goto f_err;
3423280304Sjkim        }
3424280304Sjkim    }
3425280304Sjkim    return (1);
3426280304Sjkim f_err:
3427284285Sjkim    ssl3_send_alert(s, SSL3_AL_FATAL, al);
3428280304Sjkim err:
3429280304Sjkim    return (0);
3430280304Sjkim}
343155714Skris
3432284285Sjkim#ifndef OPENSSL_NO_TLSEXT
3433284285Sjkim/*
3434284285Sjkim * Normally, we can tell if the server is resuming the session from
3435284285Sjkim * the session ID. EAP-FAST (RFC 4851), however, relies on the next server
3436284285Sjkim * message after the ServerHello to determine if the server is resuming.
3437284285Sjkim * Therefore, we allow EAP-FAST to peek ahead.
3438284285Sjkim * ssl3_check_finished returns 1 if we are resuming from an external
3439284285Sjkim * pre-shared secret, we have a "ticket" and the next server handshake message
3440284285Sjkim * is Finished; and 0 otherwise. It returns -1 upon an error.
3441284285Sjkim */
3442284285Sjkimstatic int ssl3_check_finished(SSL *s)
3443284285Sjkim{
3444284285Sjkim    int ok = 0;
3445284285Sjkim
3446284285Sjkim    if (s->version < TLS1_VERSION || !s->tls_session_secret_cb ||
3447284285Sjkim        !s->session->tlsext_tick)
3448284285Sjkim        return 0;
3449284285Sjkim
3450284285Sjkim    /* Need to permit this temporarily, in case the next message is Finished. */
3451284285Sjkim    s->s3->flags |= SSL3_FLAGS_CCS_OK;
3452284285Sjkim    /*
3453284285Sjkim     * This function is called when we might get a Certificate message instead,
3454284285Sjkim     * so permit appropriate message length.
3455284285Sjkim     * We ignore the return value as we're only interested in the message type
3456284285Sjkim     * and not its length.
3457284285Sjkim     */
3458284285Sjkim    s->method->ssl_get_message(s,
3459284285Sjkim                               SSL3_ST_CR_CERT_A,
3460284285Sjkim                               SSL3_ST_CR_CERT_B,
3461284285Sjkim                               -1, s->max_cert_list, &ok);
3462284285Sjkim    s->s3->flags &= ~SSL3_FLAGS_CCS_OK;
3463284285Sjkim
3464284285Sjkim    if (!ok)
3465284285Sjkim        return -1;
3466284285Sjkim
3467284285Sjkim    s->s3->tmp.reuse_message = 1;
3468284285Sjkim
3469284285Sjkim    if (s->s3->tmp.message_type == SSL3_MT_FINISHED)
3470284285Sjkim        return 1;
3471284285Sjkim
3472284285Sjkim    /* If we're not done, then the CCS arrived early and we should bail. */
3473284285Sjkim    if (s->s3->change_cipher_spec) {
3474284285Sjkim        SSLerr(SSL_F_SSL3_CHECK_FINISHED, SSL_R_CCS_RECEIVED_EARLY);
3475284285Sjkim        ssl3_send_alert(s, SSL3_AL_FATAL, SSL_AD_UNEXPECTED_MESSAGE);
3476284285Sjkim        return -1;
3477284285Sjkim    }
3478284285Sjkim
3479284285Sjkim    return 0;
3480284285Sjkim}
3481284285Sjkim
3482284285Sjkim# ifndef OPENSSL_NO_NEXTPROTONEG
3483238405Sjkimint ssl3_send_next_proto(SSL *s)
3484280304Sjkim{
3485280304Sjkim    unsigned int len, padding_len;
3486280304Sjkim    unsigned char *d;
3487160814Ssimon
3488280304Sjkim    if (s->state == SSL3_ST_CW_NEXT_PROTO_A) {
3489280304Sjkim        len = s->next_proto_negotiated_len;
3490280304Sjkim        padding_len = 32 - ((len + 2) % 32);
3491280304Sjkim        d = (unsigned char *)s->init_buf->data;
3492280304Sjkim        d[4] = len;
3493280304Sjkim        memcpy(d + 5, s->next_proto_negotiated, len);
3494280304Sjkim        d[5 + len] = padding_len;
3495280304Sjkim        memset(d + 6 + len, 0, padding_len);
3496280304Sjkim        *(d++) = SSL3_MT_NEXT_PROTO;
3497280304Sjkim        l2n3(2 + len + padding_len, d);
3498280304Sjkim        s->state = SSL3_ST_CW_NEXT_PROTO_B;
3499280304Sjkim        s->init_num = 4 + 2 + len + padding_len;
3500280304Sjkim        s->init_off = 0;
3501280304Sjkim    }
3502238405Sjkim
3503280304Sjkim    return ssl3_do_write(s, SSL3_RT_HANDSHAKE);
3504280304Sjkim}
3505284285Sjkim#endif                          /* !OPENSSL_NO_NEXTPROTONEG */
3506284285Sjkim#endif                          /* !OPENSSL_NO_TLSEXT */
3507194206Ssimon
3508194206Ssimonint ssl_do_client_cert_cb(SSL *s, X509 **px509, EVP_PKEY **ppkey)
3509280304Sjkim{
3510280304Sjkim    int i = 0;
3511194206Ssimon#ifndef OPENSSL_NO_ENGINE
3512280304Sjkim    if (s->ctx->client_cert_engine) {
3513280304Sjkim        i = ENGINE_load_ssl_client_cert(s->ctx->client_cert_engine, s,
3514280304Sjkim                                        SSL_get_client_CA_list(s),
3515280304Sjkim                                        px509, ppkey, NULL, NULL, NULL);
3516280304Sjkim        if (i != 0)
3517280304Sjkim            return i;
3518280304Sjkim    }
3519194206Ssimon#endif
3520280304Sjkim    if (s->ctx->client_cert_cb)
3521280304Sjkim        i = s->ctx->client_cert_cb(s, px509, ppkey);
3522280304Sjkim    return i;
3523280304Sjkim}
3524