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