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