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