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