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