Tighten session ticket handling
[openssl.git] / ssl / s3_clnt.c
1 /* ssl/s3_clnt.c */
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 #include <stdio.h>
152 #include "ssl_locl.h"
153 #include "kssl_lcl.h"
154 #include <openssl/buffer.h>
155 #include <openssl/rand.h>
156 #include <openssl/objects.h>
157 #include <openssl/evp.h>
158 #include <openssl/md5.h>
159 #ifdef OPENSSL_FIPS
160 #include <openssl/fips.h>
161 #endif
162 #ifndef OPENSSL_NO_DH
163 #include <openssl/dh.h>
164 #endif
165 #include <openssl/bn.h>
166 #ifndef OPENSSL_NO_ENGINE
167 #include <openssl/engine.h>
168 #endif
169
170 static const SSL_METHOD *ssl3_get_client_method(int ver);
171 static int ca_dn_cmp(const X509_NAME * const *a,const X509_NAME * const *b);
172
173 static const SSL_METHOD *ssl3_get_client_method(int ver)
174         {
175         if (ver == SSL3_VERSION)
176                 return(SSLv3_client_method());
177         else
178                 return(NULL);
179         }
180
181 IMPLEMENT_ssl3_meth_func(SSLv3_client_method,
182                         ssl_undefined_function,
183                         ssl3_connect,
184                         ssl3_get_client_method)
185
186 int ssl3_connect(SSL *s)
187         {
188         BUF_MEM *buf=NULL;
189         unsigned long Time=(unsigned long)time(NULL);
190         void (*cb)(const SSL *ssl,int type,int val)=NULL;
191         int ret= -1;
192         int new_state,state,skip=0;
193
194         RAND_add(&Time,sizeof(Time),0);
195         ERR_clear_error();
196         clear_sys_error();
197
198         if (s->info_callback != NULL)
199                 cb=s->info_callback;
200         else if (s->ctx->info_callback != NULL)
201                 cb=s->ctx->info_callback;
202         
203         s->in_handshake++;
204         if (!SSL_in_init(s) || SSL_in_before(s)) SSL_clear(s); 
205
206 #ifndef OPENSSL_NO_HEARTBEATS
207         /* If we're awaiting a HeartbeatResponse, pretend we
208          * already got and don't await it anymore, because
209          * Heartbeats don't make sense during handshakes anyway.
210          */
211         if (s->tlsext_hb_pending)
212                 {
213                 s->tlsext_hb_pending = 0;
214                 s->tlsext_hb_seq++;
215                 }
216 #endif
217
218         for (;;)
219                 {
220                 state=s->state;
221
222                 switch(s->state)
223                         {
224                 case SSL_ST_RENEGOTIATE:
225                         s->renegotiate=1;
226                         s->state=SSL_ST_CONNECT;
227                         s->ctx->stats.sess_connect_renegotiate++;
228 #ifndef OPENSSL_NO_TLSEXT
229                         /*
230                          * If renegotiating, the server may choose to not issue
231                          * a new ticket, so reset the flag. It will be set to
232                          * the right value when parsing ServerHello extensions.
233                          */
234                         s->tlsext_ticket_expected = 0;
235 #endif
236                         /* break */
237                 case SSL_ST_BEFORE:
238                 case SSL_ST_CONNECT:
239                 case SSL_ST_BEFORE|SSL_ST_CONNECT:
240                 case SSL_ST_OK|SSL_ST_CONNECT:
241
242                         s->server=0;
243                         if (cb != NULL) cb(s,SSL_CB_HANDSHAKE_START,1);
244
245                         if ((s->version & 0xff00 ) != 0x0300)
246                                 {
247                                 SSLerr(SSL_F_SSL3_CONNECT, ERR_R_INTERNAL_ERROR);
248                                 ret = -1;
249                                 goto end;
250                                 }
251                                 
252                         /* s->version=SSL3_VERSION; */
253                         s->type=SSL_ST_CONNECT;
254
255                         if (s->init_buf == NULL)
256                                 {
257                                 if ((buf=BUF_MEM_new()) == NULL)
258                                         {
259                                         ret= -1;
260                                         goto end;
261                                         }
262                                 if (!BUF_MEM_grow(buf,SSL3_RT_MAX_PLAIN_LENGTH))
263                                         {
264                                         ret= -1;
265                                         goto end;
266                                         }
267                                 s->init_buf=buf;
268                                 buf=NULL;
269                                 }
270
271                         if (!ssl3_setup_buffers(s)) { ret= -1; goto end; }
272
273                         /* setup buffing BIO */
274                         if (!ssl_init_wbio_buffer(s,0)) { ret= -1; goto end; }
275
276                         /* don't push the buffering BIO quite yet */
277
278                         ssl3_init_finished_mac(s);
279
280                         s->state=SSL3_ST_CW_CLNT_HELLO_A;
281                         s->ctx->stats.sess_connect++;
282                         s->init_num=0;
283                         break;
284
285                 case SSL3_ST_CW_CLNT_HELLO_A:
286                 case SSL3_ST_CW_CLNT_HELLO_B:
287
288                         s->shutdown=0;
289                         ret=ssl3_client_hello(s);
290                         if (ret <= 0) goto end;
291                         s->state=SSL3_ST_CR_SRVR_HELLO_A;
292                         s->init_num=0;
293
294                         /* turn on buffering for the next lot of output */
295                         if (s->bbio != s->wbio)
296                                 s->wbio=BIO_push(s->bbio,s->wbio);
297
298                         break;
299
300                 case SSL3_ST_CR_SRVR_HELLO_A:
301                 case SSL3_ST_CR_SRVR_HELLO_B:
302                         ret=ssl3_get_server_hello(s);
303                         if (ret <= 0) goto end;
304
305                         if (s->hit)
306                                 {
307                                 s->state=SSL3_ST_CR_FINISHED_A;
308 #ifndef OPENSSL_NO_TLSEXT
309                                 if (s->tlsext_ticket_expected)
310                                         {
311                                         /* receive renewed session ticket */
312                                         s->state=SSL3_ST_CR_SESSION_TICKET_A;
313                                         }
314 #endif
315                                 }
316                         else
317                                 {
318                                         s->state=SSL3_ST_CR_CERT_A;
319                                 }
320                         s->init_num=0;
321                         break;
322                 case SSL3_ST_CR_CERT_A:
323                 case SSL3_ST_CR_CERT_B:
324 #ifndef OPENSSL_NO_TLSEXT
325                         ret=ssl3_check_finished(s);
326                         if (ret <= 0) goto end;
327                         if (ret == 2)
328                                 {
329                                 s->hit = 1;
330                                 if (s->tlsext_ticket_expected)
331                                         s->state=SSL3_ST_CR_SESSION_TICKET_A;
332                                 else
333                                         s->state=SSL3_ST_CR_FINISHED_A;
334                                 s->init_num=0;
335                                 break;
336                                 }
337 #endif
338                         /* Check if it is anon DH/ECDH, SRP auth */
339                         /* or PSK */
340                         if (!(s->s3->tmp.new_cipher->algorithm_auth & (SSL_aNULL|SSL_aSRP)) &&
341                             !(s->s3->tmp.new_cipher->algorithm_mkey & SSL_kPSK))
342                                 {
343                                 ret=ssl3_get_server_certificate(s);
344                                 if (ret <= 0) goto end;
345 #ifndef OPENSSL_NO_TLSEXT
346                                 if (s->tlsext_status_expected)
347                                         s->state=SSL3_ST_CR_CERT_STATUS_A;
348                                 else
349                                         s->state=SSL3_ST_CR_KEY_EXCH_A;
350                                 }
351                         else
352                                 {
353                                 skip = 1;
354                                 s->state=SSL3_ST_CR_KEY_EXCH_A;
355                                 }
356 #else
357                                 }
358                         else
359                                 skip=1;
360
361                         s->state=SSL3_ST_CR_KEY_EXCH_A;
362 #endif
363                         s->init_num=0;
364                         break;
365
366                 case SSL3_ST_CR_KEY_EXCH_A:
367                 case SSL3_ST_CR_KEY_EXCH_B:
368                         ret=ssl3_get_key_exchange(s);
369                         if (ret <= 0) goto end;
370                         s->state=SSL3_ST_CR_CERT_REQ_A;
371                         s->init_num=0;
372
373                         /* at this point we check that we have the
374                          * required stuff from the server */
375                         if (!ssl3_check_cert_and_algorithm(s))
376                                 {
377                                 ret= -1;
378                                 goto end;
379                                 }
380                         break;
381
382                 case SSL3_ST_CR_CERT_REQ_A:
383                 case SSL3_ST_CR_CERT_REQ_B:
384                         ret=ssl3_get_certificate_request(s);
385                         if (ret <= 0) goto end;
386                         s->state=SSL3_ST_CR_SRVR_DONE_A;
387                         s->init_num=0;
388                         break;
389
390                 case SSL3_ST_CR_SRVR_DONE_A:
391                 case SSL3_ST_CR_SRVR_DONE_B:
392                         ret=ssl3_get_server_done(s);
393                         if (ret <= 0) goto end;
394 #ifndef OPENSSL_NO_SRP
395                         if (s->s3->tmp.new_cipher->algorithm_mkey & SSL_kSRP)
396                                 {
397                                 if ((ret = SRP_Calc_A_param(s))<=0)
398                                         {
399                                         SSLerr(SSL_F_SSL3_CONNECT,SSL_R_SRP_A_CALC);
400                                         ssl3_send_alert(s,SSL3_AL_FATAL,SSL_AD_INTERNAL_ERROR);
401                                         goto end;
402                                         }
403                                 }
404 #endif
405                         if (s->s3->tmp.cert_req)
406                                 s->state=SSL3_ST_CW_CERT_A;
407                         else
408                                 s->state=SSL3_ST_CW_KEY_EXCH_A;
409                         s->init_num=0;
410
411                         break;
412
413                 case SSL3_ST_CW_CERT_A:
414                 case SSL3_ST_CW_CERT_B:
415                 case SSL3_ST_CW_CERT_C:
416                 case SSL3_ST_CW_CERT_D:
417                         ret=ssl3_send_client_certificate(s);
418                         if (ret <= 0) goto end;
419                         s->state=SSL3_ST_CW_KEY_EXCH_A;
420                         s->init_num=0;
421                         break;
422
423                 case SSL3_ST_CW_KEY_EXCH_A:
424                 case SSL3_ST_CW_KEY_EXCH_B:
425                         ret=ssl3_send_client_key_exchange(s);
426                         if (ret <= 0) goto end;
427                         /* EAY EAY EAY need to check for DH fix cert
428                          * sent back */
429                         /* For TLS, cert_req is set to 2, so a cert chain
430                          * of nothing is sent, but no verify packet is sent */
431                         /* XXX: For now, we do not support client 
432                          * authentication in ECDH cipher suites with
433                          * ECDH (rather than ECDSA) certificates.
434                          * We need to skip the certificate verify 
435                          * message when client's ECDH public key is sent 
436                          * inside the client certificate.
437                          */
438                         if (s->s3->tmp.cert_req == 1)
439                                 {
440                                 s->state=SSL3_ST_CW_CERT_VRFY_A;
441                                 }
442                         else
443                                 {
444                                 s->state=SSL3_ST_CW_CHANGE_A;
445                                 s->s3->change_cipher_spec=0;
446                                 }
447                         if (s->s3->flags & TLS1_FLAGS_SKIP_CERT_VERIFY)
448                                 {
449                                 s->state=SSL3_ST_CW_CHANGE_A;
450                                 s->s3->change_cipher_spec=0;
451                                 }
452
453                         s->init_num=0;
454                         break;
455
456                 case SSL3_ST_CW_CERT_VRFY_A:
457                 case SSL3_ST_CW_CERT_VRFY_B:
458                         ret=ssl3_send_client_verify(s);
459                         if (ret <= 0) goto end;
460                         s->state=SSL3_ST_CW_CHANGE_A;
461                         s->init_num=0;
462                         s->s3->change_cipher_spec=0;
463                         break;
464
465                 case SSL3_ST_CW_CHANGE_A:
466                 case SSL3_ST_CW_CHANGE_B:
467                         ret=ssl3_send_change_cipher_spec(s,
468                                 SSL3_ST_CW_CHANGE_A,SSL3_ST_CW_CHANGE_B);
469                         if (ret <= 0) goto end;
470
471 #if defined(OPENSSL_NO_TLSEXT) || defined(OPENSSL_NO_NEXTPROTONEG)
472                         s->state=SSL3_ST_CW_FINISHED_A;
473 #else
474                         if (s->s3->next_proto_neg_seen)
475                                 s->state=SSL3_ST_CW_NEXT_PROTO_A;
476                         else
477                                 s->state=SSL3_ST_CW_FINISHED_A;
478 #endif
479                         s->init_num=0;
480
481                         s->session->cipher=s->s3->tmp.new_cipher;
482 #ifdef OPENSSL_NO_COMP
483                         s->session->compress_meth=0;
484 #else
485                         if (s->s3->tmp.new_compression == NULL)
486                                 s->session->compress_meth=0;
487                         else
488                                 s->session->compress_meth=
489                                         s->s3->tmp.new_compression->id;
490 #endif
491                         if (!s->method->ssl3_enc->setup_key_block(s))
492                                 {
493                                 ret= -1;
494                                 goto end;
495                                 }
496
497                         if (!s->method->ssl3_enc->change_cipher_state(s,
498                                 SSL3_CHANGE_CIPHER_CLIENT_WRITE))
499                                 {
500                                 ret= -1;
501                                 goto end;
502                                 }
503
504                         break;
505
506 #if !defined(OPENSSL_NO_TLSEXT) && !defined(OPENSSL_NO_NEXTPROTONEG)
507                 case SSL3_ST_CW_NEXT_PROTO_A:
508                 case SSL3_ST_CW_NEXT_PROTO_B:
509                         ret=ssl3_send_next_proto(s);
510                         if (ret <= 0) goto end;
511                         s->state=SSL3_ST_CW_FINISHED_A;
512                         break;
513 #endif
514
515                 case SSL3_ST_CW_FINISHED_A:
516                 case SSL3_ST_CW_FINISHED_B:
517                         ret=ssl3_send_finished(s,
518                                 SSL3_ST_CW_FINISHED_A,SSL3_ST_CW_FINISHED_B,
519                                 s->method->ssl3_enc->client_finished_label,
520                                 s->method->ssl3_enc->client_finished_label_len);
521                         if (ret <= 0) goto end;
522                         s->s3->flags |= SSL3_FLAGS_CCS_OK;
523                         s->state=SSL3_ST_CW_FLUSH;
524
525                         /* clear flags */
526                         s->s3->flags&= ~SSL3_FLAGS_POP_BUFFER;
527                         if (s->hit)
528                                 {
529                                 s->s3->tmp.next_state=SSL_ST_OK;
530                                 if (s->s3->flags & SSL3_FLAGS_DELAY_CLIENT_FINISHED)
531                                         {
532                                         s->state=SSL_ST_OK;
533                                         s->s3->flags|=SSL3_FLAGS_POP_BUFFER;
534                                         s->s3->delay_buf_pop_ret=0;
535                                         }
536                                 }
537                         else
538                                 {
539 #ifndef OPENSSL_NO_TLSEXT
540                                 /* Allow NewSessionTicket if ticket expected */
541                                 if (s->tlsext_ticket_expected)
542                                         s->s3->tmp.next_state=SSL3_ST_CR_SESSION_TICKET_A;
543                                 else
544 #endif
545                                 
546                                 s->s3->tmp.next_state=SSL3_ST_CR_FINISHED_A;
547                                 }
548                         s->init_num=0;
549                         break;
550
551 #ifndef OPENSSL_NO_TLSEXT
552                 case SSL3_ST_CR_SESSION_TICKET_A:
553                 case SSL3_ST_CR_SESSION_TICKET_B:
554                         ret=ssl3_get_new_session_ticket(s);
555                         if (ret <= 0) goto end;
556                         s->state=SSL3_ST_CR_FINISHED_A;
557                         s->init_num=0;
558                 break;
559
560                 case SSL3_ST_CR_CERT_STATUS_A:
561                 case SSL3_ST_CR_CERT_STATUS_B:
562                         ret=ssl3_get_cert_status(s);
563                         if (ret <= 0) goto end;
564                         s->state=SSL3_ST_CR_KEY_EXCH_A;
565                         s->init_num=0;
566                 break;
567 #endif
568
569                 case SSL3_ST_CR_FINISHED_A:
570                 case SSL3_ST_CR_FINISHED_B:
571
572                         s->s3->flags |= SSL3_FLAGS_CCS_OK;
573                         ret=ssl3_get_finished(s,SSL3_ST_CR_FINISHED_A,
574                                 SSL3_ST_CR_FINISHED_B);
575                         if (ret <= 0) goto end;
576
577                         if (s->hit)
578                                 s->state=SSL3_ST_CW_CHANGE_A;
579                         else
580                                 s->state=SSL_ST_OK;
581                         s->init_num=0;
582                         break;
583
584                 case SSL3_ST_CW_FLUSH:
585                         s->rwstate=SSL_WRITING;
586                         if (BIO_flush(s->wbio) <= 0)
587                                 {
588                                 ret= -1;
589                                 goto end;
590                                 }
591                         s->rwstate=SSL_NOTHING;
592                         s->state=s->s3->tmp.next_state;
593                         break;
594
595                 case SSL_ST_OK:
596                         /* clean a few things up */
597                         ssl3_cleanup_key_block(s);
598
599                         if (s->init_buf != NULL)
600                                 {
601                                 BUF_MEM_free(s->init_buf);
602                                 s->init_buf=NULL;
603                                 }
604
605                         /* If we are not 'joining' the last two packets,
606                          * remove the buffering now */
607                         if (!(s->s3->flags & SSL3_FLAGS_POP_BUFFER))
608                                 ssl_free_wbio_buffer(s);
609                         /* else do it later in ssl3_write */
610
611                         s->init_num=0;
612                         s->renegotiate=0;
613                         s->new_session=0;
614
615                         ssl_update_cache(s,SSL_SESS_CACHE_CLIENT);
616                         if (s->hit) s->ctx->stats.sess_hit++;
617
618                         ret=1;
619                         /* s->server=0; */
620                         s->handshake_func=ssl3_connect;
621                         s->ctx->stats.sess_connect_good++;
622
623                         if (cb != NULL) cb(s,SSL_CB_HANDSHAKE_DONE,1);
624
625                         goto end;
626                         /* break; */
627                         
628                 default:
629                         SSLerr(SSL_F_SSL3_CONNECT,SSL_R_UNKNOWN_STATE);
630                         ret= -1;
631                         goto end;
632                         /* break; */
633                         }
634
635                 /* did we do anything */
636                 if (!s->s3->tmp.reuse_message && !skip)
637                         {
638                         if (s->debug)
639                                 {
640                                 if ((ret=BIO_flush(s->wbio)) <= 0)
641                                         goto end;
642                                 }
643
644                         if ((cb != NULL) && (s->state != state))
645                                 {
646                                 new_state=s->state;
647                                 s->state=state;
648                                 cb(s,SSL_CB_CONNECT_LOOP,1);
649                                 s->state=new_state;
650                                 }
651                         }
652                 skip=0;
653                 }
654 end:
655         s->in_handshake--;
656         if (buf != NULL)
657                 BUF_MEM_free(buf);
658         if (cb != NULL)
659                 cb(s,SSL_CB_CONNECT_EXIT,ret);
660         return(ret);
661         }
662
663
664 int ssl3_client_hello(SSL *s)
665         {
666         unsigned char *buf;
667         unsigned char *p,*d;
668         int i;
669         unsigned long l;
670         int al = 0;
671 #ifndef OPENSSL_NO_COMP
672         int j;
673         SSL_COMP *comp;
674 #endif
675
676         buf=(unsigned char *)s->init_buf->data;
677         if (s->state == SSL3_ST_CW_CLNT_HELLO_A)
678                 {
679                 SSL_SESSION *sess = s->session;
680                 if ((sess == NULL) ||
681                         (sess->ssl_version != s->version) ||
682 #ifdef OPENSSL_NO_TLSEXT
683                         !sess->session_id_length ||
684 #else
685                         (!sess->session_id_length && !sess->tlsext_tick) ||
686 #endif
687                         (sess->not_resumable))
688                         {
689                         if (!ssl_get_new_session(s,0))
690                                 goto err;
691                         }
692                 if (s->method->version == DTLS_ANY_VERSION)
693                         {
694                         /* Determine which DTLS version to use */
695                         int options = s->options;
696                         /* If DTLS 1.2 disabled correct the version number */
697                         if (options & SSL_OP_NO_DTLSv1_2)
698                                 {
699                                 if (tls1_suiteb(s))
700                                         {
701                                         SSLerr(SSL_F_SSL3_CLIENT_HELLO, SSL_R_ONLY_DTLS_1_2_ALLOWED_IN_SUITEB_MODE);
702                                         goto err;
703                                         }
704                                 /* Disabling all versions is silly: return an
705                                  * error.
706                                  */
707                                 if (options & SSL_OP_NO_DTLSv1)
708                                         {
709                                         SSLerr(SSL_F_SSL3_CLIENT_HELLO,SSL_R_WRONG_SSL_VERSION);
710                                         goto err;
711                                         }
712                                 /* Update method so we don't use any DTLS 1.2
713                                  * features.
714                                  */
715                                 s->method = DTLSv1_client_method();
716                                 s->version = DTLS1_VERSION;
717                                 }
718                         else
719                                 {
720                                 /* We only support one version: update method */
721                                 if (options & SSL_OP_NO_DTLSv1)
722                                         s->method = DTLSv1_2_client_method();
723                                 s->version = DTLS1_2_VERSION;
724                                 }
725                         s->client_version = s->version;
726                         }
727                 /* else use the pre-loaded session */
728
729                 p=s->s3->client_random;
730
731                 /* for DTLS if client_random is initialized, reuse it, we are
732                  * required to use same upon reply to HelloVerify */
733                 if (SSL_IS_DTLS(s))
734                         {
735                         size_t idx;
736                         i = 1;
737                         for (idx=0; idx < sizeof(s->s3->client_random); idx++)
738                                 {
739                                 if (p[idx])
740                                         {
741                                         i = 0;
742                                         break;
743                                         }
744                                 }
745                         }
746                 else 
747                         i = 1;
748
749                 if (i)
750                         ssl_fill_hello_random(s, 0, p,
751                                               sizeof(s->s3->client_random));
752
753                 /* Do the message type and length last */
754                 d=p= ssl_handshake_start(s);
755
756                 /* version indicates the negotiated version: for example from
757                  * an SSLv2/v3 compatible client hello). The client_version
758                  * field is the maximum version we permit and it is also
759                  * used in RSA encrypted premaster secrets. Some servers can
760                  * choke if we initially report a higher version then
761                  * renegotiate to a lower one in the premaster secret. This
762                  * didn't happen with TLS 1.0 as most servers supported it
763                  * but it can with TLS 1.1 or later if the server only supports
764                  * 1.0.
765                  *
766                  * Possible scenario with previous logic:
767                  *      1. Client hello indicates TLS 1.2
768                  *      2. Server hello says TLS 1.0
769                  *      3. RSA encrypted premaster secret uses 1.2.
770                  *      4. Handhaked proceeds using TLS 1.0.
771                  *      5. Server sends hello request to renegotiate.
772                  *      6. Client hello indicates TLS v1.0 as we now
773                  *         know that is maximum server supports.
774                  *      7. Server chokes on RSA encrypted premaster secret
775                  *         containing version 1.0.
776                  *
777                  * For interoperability it should be OK to always use the
778                  * maximum version we support in client hello and then rely
779                  * on the checking of version to ensure the servers isn't
780                  * being inconsistent: for example initially negotiating with
781                  * TLS 1.0 and renegotiating with TLS 1.2. We do this by using
782                  * client_version in client hello and not resetting it to
783                  * the negotiated version.
784                  */
785 #if 0
786                 *(p++)=s->version>>8;
787                 *(p++)=s->version&0xff;
788                 s->client_version=s->version;
789 #else
790                 *(p++)=s->client_version>>8;
791                 *(p++)=s->client_version&0xff;
792 #endif
793
794                 /* Random stuff */
795                 memcpy(p,s->s3->client_random,SSL3_RANDOM_SIZE);
796                 p+=SSL3_RANDOM_SIZE;
797
798                 /* Session ID */
799                 if (s->new_session)
800                         i=0;
801                 else
802                         i=s->session->session_id_length;
803                 *(p++)=i;
804                 if (i != 0)
805                         {
806                         if (i > (int)sizeof(s->session->session_id))
807                                 {
808                                 SSLerr(SSL_F_SSL3_CLIENT_HELLO, ERR_R_INTERNAL_ERROR);
809                                 goto err;
810                                 }
811                         memcpy(p,s->session->session_id,i);
812                         p+=i;
813                         }
814                 
815                 /* cookie stuff for DTLS */
816                 if (SSL_IS_DTLS(s))
817                         {
818                         if ( s->d1->cookie_len > sizeof(s->d1->cookie))
819                                 {
820                                 SSLerr(SSL_F_SSL3_CLIENT_HELLO, ERR_R_INTERNAL_ERROR);
821                                 goto err;
822                                 }
823                         *(p++) = s->d1->cookie_len;
824                         memcpy(p, s->d1->cookie, s->d1->cookie_len);
825                         p += s->d1->cookie_len;
826                         }
827                 
828                 /* Ciphers supported */
829                 i=ssl_cipher_list_to_bytes(s,SSL_get_ciphers(s),&(p[2]),0);
830                 if (i == 0)
831                         {
832                         SSLerr(SSL_F_SSL3_CLIENT_HELLO,SSL_R_NO_CIPHERS_AVAILABLE);
833                         goto err;
834                         }
835 #ifdef OPENSSL_MAX_TLS1_2_CIPHER_LENGTH
836                         /* Some servers hang if client hello > 256 bytes
837                          * as hack workaround chop number of supported ciphers
838                          * to keep it well below this if we use TLS v1.2
839                          */
840                         if (TLS1_get_version(s) >= TLS1_2_VERSION
841                                 && i > OPENSSL_MAX_TLS1_2_CIPHER_LENGTH)
842                                 i = OPENSSL_MAX_TLS1_2_CIPHER_LENGTH & ~1;
843 #endif
844                 s2n(i,p);
845                 p+=i;
846
847                 /* COMPRESSION */
848 #ifdef OPENSSL_NO_COMP
849                 *(p++)=1;
850 #else
851
852                 if ((s->options & SSL_OP_NO_COMPRESSION)
853                                         || !s->ctx->comp_methods)
854                         j=0;
855                 else
856                         j=sk_SSL_COMP_num(s->ctx->comp_methods);
857                 *(p++)=1+j;
858                 for (i=0; i<j; i++)
859                         {
860                         comp=sk_SSL_COMP_value(s->ctx->comp_methods,i);
861                         *(p++)=comp->id;
862                         }
863 #endif
864                 *(p++)=0; /* Add the NULL method */
865
866 #ifndef OPENSSL_NO_TLSEXT
867                 /* TLS extensions*/
868                 if (ssl_prepare_clienthello_tlsext(s) <= 0)
869                         {
870                         SSLerr(SSL_F_SSL3_CLIENT_HELLO,SSL_R_CLIENTHELLO_TLSEXT);
871                         goto err;
872                         }
873                 if ((p = ssl_add_clienthello_tlsext(s, p, buf+SSL3_RT_MAX_PLAIN_LENGTH, &al)) == NULL)
874                         {
875                         ssl3_send_alert(s,SSL3_AL_FATAL,al);
876                         SSLerr(SSL_F_SSL3_CLIENT_HELLO,ERR_R_INTERNAL_ERROR);
877                         goto err;
878                         }
879 #endif
880                 
881                 l= p-d;
882                 ssl_set_handshake_header(s, SSL3_MT_CLIENT_HELLO, l);
883                 s->state=SSL3_ST_CW_CLNT_HELLO_B;
884                 }
885
886         /* SSL3_ST_CW_CLNT_HELLO_B */
887         return ssl_do_write(s);
888 err:
889         return(-1);
890         }
891
892 int ssl3_get_server_hello(SSL *s)
893         {
894         STACK_OF(SSL_CIPHER) *sk;
895         const SSL_CIPHER *c;
896         CERT *ct = s->cert;
897         unsigned char *p,*d;
898         int i,al=SSL_AD_INTERNAL_ERROR,ok;
899         unsigned int j;
900         long n;
901 #ifndef OPENSSL_NO_COMP
902         SSL_COMP *comp;
903 #endif
904         /* Hello verify request and/or server hello version may not
905          * match so set first packet if we're negotiating version.
906          */
907         if (SSL_IS_DTLS(s))
908                 s->first_packet = 1;
909
910         n=s->method->ssl_get_message(s,
911                 SSL3_ST_CR_SRVR_HELLO_A,
912                 SSL3_ST_CR_SRVR_HELLO_B,
913                 -1,
914                 20000, /* ?? */
915                 &ok);
916
917         if (!ok) return((int)n);
918
919         if (SSL_IS_DTLS(s))
920                 {
921                 s->first_packet = 0;
922                 if ( s->s3->tmp.message_type == DTLS1_MT_HELLO_VERIFY_REQUEST)
923                         {
924                         if ( s->d1->send_cookie == 0)
925                                 {
926                                 s->s3->tmp.reuse_message = 1;
927                                 return 1;
928                                 }
929                         else /* already sent a cookie */
930                                 {
931                                 al=SSL_AD_UNEXPECTED_MESSAGE;
932                                 SSLerr(SSL_F_SSL3_GET_SERVER_HELLO,SSL_R_BAD_MESSAGE_TYPE);
933                                 goto f_err;
934                                 }
935                         }
936                 }
937         
938         if ( s->s3->tmp.message_type != SSL3_MT_SERVER_HELLO)
939                 {
940                 al=SSL_AD_UNEXPECTED_MESSAGE;
941                 SSLerr(SSL_F_SSL3_GET_SERVER_HELLO,SSL_R_BAD_MESSAGE_TYPE);
942                 goto f_err;
943                 }
944
945         d=p=(unsigned char *)s->init_msg;
946         if (s->method->version == DTLS_ANY_VERSION)
947                 {
948                 /* Work out correct protocol version to use */
949                 int hversion = (p[0] << 8)|p[1];
950                 int options = s->options;
951                 if (hversion == DTLS1_2_VERSION
952                         && !(options & SSL_OP_NO_DTLSv1_2))
953                         s->method = DTLSv1_2_client_method();
954                 else if (tls1_suiteb(s))
955                         {
956                         SSLerr(SSL_F_SSL3_GET_SERVER_HELLO, SSL_R_ONLY_DTLS_1_2_ALLOWED_IN_SUITEB_MODE);
957                         s->version = hversion;
958                         al = SSL_AD_PROTOCOL_VERSION;
959                         goto f_err;
960                         }
961                 else if (hversion == DTLS1_VERSION
962                         && !(options & SSL_OP_NO_DTLSv1))
963                         s->method = DTLSv1_client_method();
964                 else
965                         {
966                         SSLerr(SSL_F_SSL3_GET_SERVER_HELLO,SSL_R_WRONG_SSL_VERSION);
967                         s->version = hversion;
968                         al = SSL_AD_PROTOCOL_VERSION;
969                         goto f_err;
970                         }
971                 s->version = s->client_version = s->method->version;
972                 }
973
974         if ((p[0] != (s->version>>8)) || (p[1] != (s->version&0xff)))
975                 {
976                 SSLerr(SSL_F_SSL3_GET_SERVER_HELLO,SSL_R_WRONG_SSL_VERSION);
977                 s->version=(s->version&0xff00)|p[1];
978                 al=SSL_AD_PROTOCOL_VERSION;
979                 goto f_err;
980                 }
981         p+=2;
982
983         /* load the server hello data */
984         /* load the server random */
985         memcpy(s->s3->server_random,p,SSL3_RANDOM_SIZE);
986         p+=SSL3_RANDOM_SIZE;
987
988         /* get the session-id */
989         j= *(p++);
990
991         if ((j > sizeof s->session->session_id) || (j > SSL3_SESSION_ID_SIZE))
992                 {
993                 al=SSL_AD_ILLEGAL_PARAMETER;
994                 SSLerr(SSL_F_SSL3_GET_SERVER_HELLO,SSL_R_SSL3_SESSION_ID_TOO_LONG);
995                 goto f_err;
996                 }
997
998 #ifndef OPENSSL_NO_TLSEXT
999         /* check if we want to resume the session based on external pre-shared secret */
1000         if (s->version >= TLS1_VERSION && s->tls_session_secret_cb)
1001                 {
1002                 SSL_CIPHER *pref_cipher=NULL;
1003                 s->session->master_key_length=sizeof(s->session->master_key);
1004                 if (s->tls_session_secret_cb(s, s->session->master_key,
1005                                              &s->session->master_key_length,
1006                                              NULL, &pref_cipher,
1007                                              s->tls_session_secret_cb_arg))
1008                         {
1009                         s->session->cipher = pref_cipher ?
1010                                 pref_cipher : ssl_get_cipher_by_char(s, p+j);
1011                         s->s3->flags |= SSL3_FLAGS_CCS_OK;
1012                         }
1013                 }
1014 #endif /* OPENSSL_NO_TLSEXT */
1015
1016         if (j != 0 && j == s->session->session_id_length
1017             && memcmp(p,s->session->session_id,j) == 0)
1018             {
1019             if(s->sid_ctx_length != s->session->sid_ctx_length
1020                || memcmp(s->session->sid_ctx,s->sid_ctx,s->sid_ctx_length))
1021                 {
1022                 /* actually a client application bug */
1023                 al=SSL_AD_ILLEGAL_PARAMETER;
1024                 SSLerr(SSL_F_SSL3_GET_SERVER_HELLO,SSL_R_ATTEMPT_TO_REUSE_SESSION_IN_DIFFERENT_CONTEXT);
1025                 goto f_err;
1026                 }
1027             s->s3->flags |= SSL3_FLAGS_CCS_OK;
1028             s->hit=1;
1029             }
1030         else    /* a miss or crap from the other end */
1031                 {
1032                 /* If we were trying for session-id reuse, make a new
1033                  * SSL_SESSION so we don't stuff up other people */
1034                 s->hit=0;
1035                 if (s->session->session_id_length > 0)
1036                         {
1037                         if (!ssl_get_new_session(s,0))
1038                                 {
1039                                 goto f_err;
1040                                 }
1041                         }
1042                 s->session->session_id_length=j;
1043                 memcpy(s->session->session_id,p,j); /* j could be 0 */
1044                 }
1045         p+=j;
1046         c=ssl_get_cipher_by_char(s,p);
1047         if (c == NULL)
1048                 {
1049                 /* unknown cipher */
1050                 al=SSL_AD_ILLEGAL_PARAMETER;
1051                 SSLerr(SSL_F_SSL3_GET_SERVER_HELLO,SSL_R_UNKNOWN_CIPHER_RETURNED);
1052                 goto f_err;
1053                 }
1054         /* If it is a disabled cipher we didn't send it in client hello,
1055          * so return an error.
1056          */
1057         if (c->algorithm_ssl & ct->mask_ssl ||
1058                 c->algorithm_mkey & ct->mask_k ||
1059                 c->algorithm_auth & ct->mask_a)
1060                 {
1061                 al=SSL_AD_ILLEGAL_PARAMETER;
1062                 SSLerr(SSL_F_SSL3_GET_SERVER_HELLO,SSL_R_WRONG_CIPHER_RETURNED);
1063                 goto f_err;
1064                 }
1065         p+=ssl_put_cipher_by_char(s,NULL,NULL);
1066
1067         sk=ssl_get_ciphers_by_id(s);
1068         i=sk_SSL_CIPHER_find(sk,c);
1069         if (i < 0)
1070                 {
1071                 /* we did not say we would use this cipher */
1072                 al=SSL_AD_ILLEGAL_PARAMETER;
1073                 SSLerr(SSL_F_SSL3_GET_SERVER_HELLO,SSL_R_WRONG_CIPHER_RETURNED);
1074                 goto f_err;
1075                 }
1076
1077         /* Depending on the session caching (internal/external), the cipher
1078            and/or cipher_id values may not be set. Make sure that
1079            cipher_id is set and use it for comparison. */
1080         if (s->session->cipher)
1081                 s->session->cipher_id = s->session->cipher->id;
1082         if (s->hit && (s->session->cipher_id != c->id))
1083                 {
1084 /* Workaround is now obsolete */
1085 #if 0
1086                 if (!(s->options &
1087                         SSL_OP_NETSCAPE_REUSE_CIPHER_CHANGE_BUG))
1088 #endif
1089                         {
1090                         al=SSL_AD_ILLEGAL_PARAMETER;
1091                         SSLerr(SSL_F_SSL3_GET_SERVER_HELLO,SSL_R_OLD_SESSION_CIPHER_NOT_RETURNED);
1092                         goto f_err;
1093                         }
1094                 }
1095         s->s3->tmp.new_cipher=c;
1096         /* Don't digest cached records if no sigalgs: we may need them for
1097          * client authentication.
1098          */
1099         if (!SSL_USE_SIGALGS(s) && !ssl3_digest_cached_records(s))
1100                 goto f_err;
1101         /* lets get the compression algorithm */
1102         /* COMPRESSION */
1103 #ifdef OPENSSL_NO_COMP
1104         if (*(p++) != 0)
1105                 {
1106                 al=SSL_AD_ILLEGAL_PARAMETER;
1107                 SSLerr(SSL_F_SSL3_GET_SERVER_HELLO,SSL_R_UNSUPPORTED_COMPRESSION_ALGORITHM);
1108                 goto f_err;
1109                 }
1110         /* If compression is disabled we'd better not try to resume a session
1111          * using compression.
1112          */
1113         if (s->session->compress_meth != 0)
1114                 {
1115                 SSLerr(SSL_F_SSL3_GET_SERVER_HELLO,SSL_R_INCONSISTENT_COMPRESSION);
1116                 goto f_err;
1117                 }
1118 #else
1119         j= *(p++);
1120         if (s->hit && j != s->session->compress_meth)
1121                 {
1122                 al=SSL_AD_ILLEGAL_PARAMETER;
1123                 SSLerr(SSL_F_SSL3_GET_SERVER_HELLO,SSL_R_OLD_SESSION_COMPRESSION_ALGORITHM_NOT_RETURNED);
1124                 goto f_err;
1125                 }
1126         if (j == 0)
1127                 comp=NULL;
1128         else if (s->options & SSL_OP_NO_COMPRESSION)
1129                 {
1130                 al=SSL_AD_ILLEGAL_PARAMETER;
1131                 SSLerr(SSL_F_SSL3_GET_SERVER_HELLO,SSL_R_COMPRESSION_DISABLED);
1132                 goto f_err;
1133                 }
1134         else
1135                 comp=ssl3_comp_find(s->ctx->comp_methods,j);
1136         
1137         if ((j != 0) && (comp == NULL))
1138                 {
1139                 al=SSL_AD_ILLEGAL_PARAMETER;
1140                 SSLerr(SSL_F_SSL3_GET_SERVER_HELLO,SSL_R_UNSUPPORTED_COMPRESSION_ALGORITHM);
1141                 goto f_err;
1142                 }
1143         else
1144                 {
1145                 s->s3->tmp.new_compression=comp;
1146                 }
1147 #endif
1148
1149 #ifndef OPENSSL_NO_TLSEXT
1150         /* TLS extensions*/
1151         if (!ssl_parse_serverhello_tlsext(s,&p,d,n))
1152                 {
1153                 SSLerr(SSL_F_SSL3_GET_SERVER_HELLO,SSL_R_PARSE_TLSEXT);
1154                 goto err; 
1155                 }
1156 #endif
1157
1158         if (p != (d+n))
1159                 {
1160                 /* wrong packet length */
1161                 al=SSL_AD_DECODE_ERROR;
1162                 SSLerr(SSL_F_SSL3_GET_SERVER_HELLO,SSL_R_BAD_PACKET_LENGTH);
1163                 goto f_err;
1164                 }
1165
1166         return(1);
1167 f_err:
1168         ssl3_send_alert(s,SSL3_AL_FATAL,al);
1169 err:
1170         return(-1);
1171         }
1172
1173 int ssl3_get_server_certificate(SSL *s)
1174         {
1175         int al,i,ok,ret= -1;
1176         unsigned long n,nc,llen,l;
1177         X509 *x=NULL;
1178         const unsigned char *q,*p;
1179         unsigned char *d;
1180         STACK_OF(X509) *sk=NULL;
1181         SESS_CERT *sc;
1182         EVP_PKEY *pkey=NULL;
1183         int need_cert = 1; /* VRS: 0=> will allow null cert if auth == KRB5 */
1184
1185         n=s->method->ssl_get_message(s,
1186                 SSL3_ST_CR_CERT_A,
1187                 SSL3_ST_CR_CERT_B,
1188                 -1,
1189                 s->max_cert_list,
1190                 &ok);
1191
1192         if (!ok) return((int)n);
1193
1194         if ((s->s3->tmp.message_type == SSL3_MT_SERVER_KEY_EXCHANGE) ||
1195                 ((s->s3->tmp.new_cipher->algorithm_auth & SSL_aKRB5) && 
1196                 (s->s3->tmp.message_type == SSL3_MT_SERVER_DONE)))
1197                 {
1198                 s->s3->tmp.reuse_message=1;
1199                 return(1);
1200                 }
1201
1202         if (s->s3->tmp.message_type != SSL3_MT_CERTIFICATE)
1203                 {
1204                 al=SSL_AD_UNEXPECTED_MESSAGE;
1205                 SSLerr(SSL_F_SSL3_GET_SERVER_CERTIFICATE,SSL_R_BAD_MESSAGE_TYPE);
1206                 goto f_err;
1207                 }
1208         p=d=(unsigned char *)s->init_msg;
1209
1210         if ((sk=sk_X509_new_null()) == NULL)
1211                 {
1212                 SSLerr(SSL_F_SSL3_GET_SERVER_CERTIFICATE,ERR_R_MALLOC_FAILURE);
1213                 goto err;
1214                 }
1215
1216         n2l3(p,llen);
1217         if (llen+3 != n)
1218                 {
1219                 al=SSL_AD_DECODE_ERROR;
1220                 SSLerr(SSL_F_SSL3_GET_SERVER_CERTIFICATE,SSL_R_LENGTH_MISMATCH);
1221                 goto f_err;
1222                 }
1223         for (nc=0; nc<llen; )
1224                 {
1225                 n2l3(p,l);
1226                 if ((l+nc+3) > llen)
1227                         {
1228                         al=SSL_AD_DECODE_ERROR;
1229                         SSLerr(SSL_F_SSL3_GET_SERVER_CERTIFICATE,SSL_R_CERT_LENGTH_MISMATCH);
1230                         goto f_err;
1231                         }
1232
1233                 q=p;
1234                 x=d2i_X509(NULL,&q,l);
1235                 if (x == NULL)
1236                         {
1237                         al=SSL_AD_BAD_CERTIFICATE;
1238                         SSLerr(SSL_F_SSL3_GET_SERVER_CERTIFICATE,ERR_R_ASN1_LIB);
1239                         goto f_err;
1240                         }
1241                 if (q != (p+l))
1242                         {
1243                         al=SSL_AD_DECODE_ERROR;
1244                         SSLerr(SSL_F_SSL3_GET_SERVER_CERTIFICATE,SSL_R_CERT_LENGTH_MISMATCH);
1245                         goto f_err;
1246                         }
1247                 if (!sk_X509_push(sk,x))
1248                         {
1249                         SSLerr(SSL_F_SSL3_GET_SERVER_CERTIFICATE,ERR_R_MALLOC_FAILURE);
1250                         goto err;
1251                         }
1252                 x=NULL;
1253                 nc+=l+3;
1254                 p=q;
1255                 }
1256
1257         i=ssl_verify_cert_chain(s,sk);
1258         if ((s->verify_mode != SSL_VERIFY_NONE) && (i <= 0)
1259 #ifndef OPENSSL_NO_KRB5
1260             && !((s->s3->tmp.new_cipher->algorithm_mkey & SSL_kKRB5) &&
1261                  (s->s3->tmp.new_cipher->algorithm_auth & SSL_aKRB5))
1262 #endif /* OPENSSL_NO_KRB5 */
1263                 )
1264                 {
1265                 al=ssl_verify_alarm_type(s->verify_result);
1266                 SSLerr(SSL_F_SSL3_GET_SERVER_CERTIFICATE,SSL_R_CERTIFICATE_VERIFY_FAILED);
1267                 goto f_err; 
1268                 }
1269         ERR_clear_error(); /* but we keep s->verify_result */
1270
1271         sc=ssl_sess_cert_new();
1272         if (sc == NULL) goto err;
1273
1274         if (s->session->sess_cert) ssl_sess_cert_free(s->session->sess_cert);
1275         s->session->sess_cert=sc;
1276
1277         sc->cert_chain=sk;
1278         /* Inconsistency alert: cert_chain does include the peer's
1279          * certificate, which we don't include in s3_srvr.c */
1280         x=sk_X509_value(sk,0);
1281         sk=NULL;
1282         /* VRS 19990621: possible memory leak; sk=null ==> !sk_pop_free() @end*/
1283
1284         pkey=X509_get_pubkey(x);
1285
1286         /* VRS: allow null cert if auth == KRB5 */
1287         need_cert = ((s->s3->tmp.new_cipher->algorithm_mkey & SSL_kKRB5) &&
1288                     (s->s3->tmp.new_cipher->algorithm_auth & SSL_aKRB5))
1289                     ? 0 : 1;
1290
1291 #ifdef KSSL_DEBUG
1292         printf("pkey,x = %p, %p\n", pkey,x);
1293         printf("ssl_cert_type(x,pkey) = %d\n", ssl_cert_type(x,pkey));
1294         printf("cipher, alg, nc = %s, %lx, %lx, %d\n", s->s3->tmp.new_cipher->name,
1295                 s->s3->tmp.new_cipher->algorithm_mkey, s->s3->tmp.new_cipher->algorithm_auth, need_cert);
1296 #endif    /* KSSL_DEBUG */
1297
1298         if (need_cert && ((pkey == NULL) || EVP_PKEY_missing_parameters(pkey)))
1299                 {
1300                 x=NULL;
1301                 al=SSL3_AL_FATAL;
1302                 SSLerr(SSL_F_SSL3_GET_SERVER_CERTIFICATE,
1303                         SSL_R_UNABLE_TO_FIND_PUBLIC_KEY_PARAMETERS);
1304                 goto f_err;
1305                 }
1306
1307         i=ssl_cert_type(x,pkey);
1308         if (need_cert && i < 0)
1309                 {
1310                 x=NULL;
1311                 al=SSL3_AL_FATAL;
1312                 SSLerr(SSL_F_SSL3_GET_SERVER_CERTIFICATE,
1313                         SSL_R_UNKNOWN_CERTIFICATE_TYPE);
1314                 goto f_err;
1315                 }
1316
1317         if (need_cert)
1318                 {
1319                 int exp_idx = ssl_cipher_get_cert_index(s->s3->tmp.new_cipher);
1320                 if (exp_idx >= 0 && i != exp_idx)
1321                         {
1322                         x=NULL;
1323                         al=SSL_AD_ILLEGAL_PARAMETER;
1324                         SSLerr(SSL_F_SSL3_GET_SERVER_CERTIFICATE,
1325                                 SSL_R_WRONG_CERTIFICATE_TYPE);
1326                         goto f_err;
1327                         }
1328                 sc->peer_cert_type=i;
1329                 CRYPTO_add(&x->references,1,CRYPTO_LOCK_X509);
1330                 /* Why would the following ever happen?
1331                  * We just created sc a couple of lines ago. */
1332                 if (sc->peer_pkeys[i].x509 != NULL)
1333                         X509_free(sc->peer_pkeys[i].x509);
1334                 sc->peer_pkeys[i].x509=x;
1335                 sc->peer_key= &(sc->peer_pkeys[i]);
1336
1337                 if (s->session->peer != NULL)
1338                         X509_free(s->session->peer);
1339                 CRYPTO_add(&x->references,1,CRYPTO_LOCK_X509);
1340                 s->session->peer=x;
1341                 }
1342         else
1343                 {
1344                 sc->peer_cert_type=i;
1345                 sc->peer_key= NULL;
1346
1347                 if (s->session->peer != NULL)
1348                         X509_free(s->session->peer);
1349                 s->session->peer=NULL;
1350                 }
1351         s->session->verify_result = s->verify_result;
1352
1353         x=NULL;
1354         ret=1;
1355         if (0)
1356                 {
1357 f_err:
1358                 ssl3_send_alert(s,SSL3_AL_FATAL,al);
1359                 }
1360 err:
1361         EVP_PKEY_free(pkey);
1362         X509_free(x);
1363         sk_X509_pop_free(sk,X509_free);
1364         return(ret);
1365         }
1366
1367 int ssl3_get_key_exchange(SSL *s)
1368         {
1369 #ifndef OPENSSL_NO_RSA
1370         unsigned char *q,md_buf[EVP_MAX_MD_SIZE*2];
1371 #endif
1372         EVP_MD_CTX md_ctx;
1373         unsigned char *param,*p;
1374         int al,j,ok;
1375         long i,param_len,n,alg_k,alg_a;
1376         EVP_PKEY *pkey=NULL;
1377         const EVP_MD *md = NULL;
1378 #ifndef OPENSSL_NO_RSA
1379         RSA *rsa=NULL;
1380 #endif
1381 #ifndef OPENSSL_NO_DH
1382         DH *dh=NULL;
1383 #endif
1384 #ifndef OPENSSL_NO_ECDH
1385         EC_KEY *ecdh = NULL;
1386         BN_CTX *bn_ctx = NULL;
1387         EC_POINT *srvr_ecpoint = NULL;
1388         int curve_nid = 0;
1389         int encoded_pt_len = 0;
1390 #endif
1391
1392         /* use same message size as in ssl3_get_certificate_request()
1393          * as ServerKeyExchange message may be skipped */
1394         n=s->method->ssl_get_message(s,
1395                 SSL3_ST_CR_KEY_EXCH_A,
1396                 SSL3_ST_CR_KEY_EXCH_B,
1397                 -1,
1398                 s->max_cert_list,
1399                 &ok);
1400         if (!ok) return((int)n);
1401
1402         if (s->s3->tmp.message_type != SSL3_MT_SERVER_KEY_EXCHANGE)
1403                 {
1404 #ifndef OPENSSL_NO_PSK
1405                 /* In plain PSK ciphersuite, ServerKeyExchange can be
1406                    omitted if no identity hint is sent. Set
1407                    session->sess_cert anyway to avoid problems
1408                    later.*/
1409                 if (s->s3->tmp.new_cipher->algorithm_mkey & SSL_kPSK)
1410                         {
1411                         s->session->sess_cert=ssl_sess_cert_new();
1412                         if (s->ctx->psk_identity_hint)
1413                                 OPENSSL_free(s->ctx->psk_identity_hint);
1414                         s->ctx->psk_identity_hint = NULL;
1415                         }
1416 #endif
1417                 s->s3->tmp.reuse_message=1;
1418                 return(1);
1419                 }
1420
1421         param=p=(unsigned char *)s->init_msg;
1422         if (s->session->sess_cert != NULL)
1423                 {
1424 #ifndef OPENSSL_NO_RSA
1425                 if (s->session->sess_cert->peer_rsa_tmp != NULL)
1426                         {
1427                         RSA_free(s->session->sess_cert->peer_rsa_tmp);
1428                         s->session->sess_cert->peer_rsa_tmp=NULL;
1429                         }
1430 #endif
1431 #ifndef OPENSSL_NO_DH
1432                 if (s->session->sess_cert->peer_dh_tmp)
1433                         {
1434                         DH_free(s->session->sess_cert->peer_dh_tmp);
1435                         s->session->sess_cert->peer_dh_tmp=NULL;
1436                         }
1437 #endif
1438 #ifndef OPENSSL_NO_ECDH
1439                 if (s->session->sess_cert->peer_ecdh_tmp)
1440                         {
1441                         EC_KEY_free(s->session->sess_cert->peer_ecdh_tmp);
1442                         s->session->sess_cert->peer_ecdh_tmp=NULL;
1443                         }
1444 #endif
1445                 }
1446         else
1447                 {
1448                 s->session->sess_cert=ssl_sess_cert_new();
1449                 }
1450
1451         /* Total length of the parameters including the length prefix */
1452         param_len=0;
1453
1454         alg_k=s->s3->tmp.new_cipher->algorithm_mkey;
1455         alg_a=s->s3->tmp.new_cipher->algorithm_auth;
1456         EVP_MD_CTX_init(&md_ctx);
1457
1458         al=SSL_AD_DECODE_ERROR;
1459
1460 #ifndef OPENSSL_NO_PSK
1461         if (alg_k & SSL_kPSK)
1462                 {
1463                 char tmp_id_hint[PSK_MAX_IDENTITY_LEN+1];
1464
1465                 param_len = 2;
1466                 if (param_len > n)
1467                         {
1468                         SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,
1469                                 SSL_R_LENGTH_TOO_SHORT);
1470                         goto f_err;
1471                         }
1472                 n2s(p,i);
1473
1474                 /* Store PSK identity hint for later use, hint is used
1475                  * in ssl3_send_client_key_exchange.  Assume that the
1476                  * maximum length of a PSK identity hint can be as
1477                  * long as the maximum length of a PSK identity. */
1478                 if (i > PSK_MAX_IDENTITY_LEN)
1479                         {
1480                         al=SSL_AD_HANDSHAKE_FAILURE;
1481                         SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,
1482                                 SSL_R_DATA_LENGTH_TOO_LONG);
1483                         goto f_err;
1484                         }
1485                 if (i > n - param_len)
1486                         {
1487                         SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,
1488                                 SSL_R_BAD_PSK_IDENTITY_HINT_LENGTH);
1489                         goto f_err;
1490                         }
1491                 param_len += i;
1492
1493                 /* If received PSK identity hint contains NULL
1494                  * characters, the hint is truncated from the first
1495                  * NULL. p may not be ending with NULL, so create a
1496                  * NULL-terminated string. */
1497                 memcpy(tmp_id_hint, p, i);
1498                 memset(tmp_id_hint+i, 0, PSK_MAX_IDENTITY_LEN+1-i);
1499                 if (s->ctx->psk_identity_hint != NULL)
1500                         OPENSSL_free(s->ctx->psk_identity_hint);
1501                 s->ctx->psk_identity_hint = BUF_strdup(tmp_id_hint);
1502                 if (s->ctx->psk_identity_hint == NULL)
1503                         {
1504                         al=SSL_AD_HANDSHAKE_FAILURE;
1505                         SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE, ERR_R_MALLOC_FAILURE);
1506                         goto f_err;
1507                         }          
1508
1509                 p+=i;
1510                 n-=param_len;
1511                 }
1512         else
1513 #endif /* !OPENSSL_NO_PSK */
1514 #ifndef OPENSSL_NO_SRP
1515         if (alg_k & SSL_kSRP)
1516                 {
1517                 param_len = 2;
1518                 if (param_len > n)
1519                         {
1520                         SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,
1521                                 SSL_R_LENGTH_TOO_SHORT);
1522                         goto f_err;
1523                         }
1524                 n2s(p,i);
1525
1526                 if (i > n - param_len)
1527                         {
1528                         SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,SSL_R_BAD_SRP_N_LENGTH);
1529                         goto f_err;
1530                         }
1531                 param_len += i;
1532
1533                 if (!(s->srp_ctx.N=BN_bin2bn(p,i,NULL)))
1534                         {
1535                         SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,ERR_R_BN_LIB);
1536                         goto err;
1537                         }
1538                 p+=i;
1539
1540
1541                 if (2 > n - param_len)
1542                         {
1543                         SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,
1544                                 SSL_R_LENGTH_TOO_SHORT);
1545                         goto f_err;
1546                         }
1547                 param_len += 2;
1548
1549                 n2s(p,i);
1550
1551                 if (i > n - param_len)
1552                         {
1553                         SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,SSL_R_BAD_SRP_G_LENGTH);
1554                         goto f_err;
1555                         }
1556                 param_len += i;
1557
1558                 if (!(s->srp_ctx.g=BN_bin2bn(p,i,NULL)))
1559                         {
1560                         SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,ERR_R_BN_LIB);
1561                         goto err;
1562                         }
1563                 p+=i;
1564
1565
1566                 if (1 > n - param_len)
1567                         {
1568                         SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,
1569                                 SSL_R_LENGTH_TOO_SHORT);
1570                         goto f_err;
1571                         }
1572                 param_len += 1;
1573
1574                 i = (unsigned int)(p[0]);
1575                 p++;
1576
1577                 if (i > n - param_len)
1578                         {
1579                         SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,SSL_R_BAD_SRP_S_LENGTH);
1580                         goto f_err;
1581                         }
1582                 param_len += i;
1583
1584                 if (!(s->srp_ctx.s=BN_bin2bn(p,i,NULL)))
1585                         {
1586                         SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,ERR_R_BN_LIB);
1587                         goto err;
1588                         }
1589                 p+=i;
1590
1591                 if (2 > n - param_len)
1592                         {
1593                         SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,
1594                                 SSL_R_LENGTH_TOO_SHORT);
1595                         goto f_err;
1596                         }
1597                 param_len += 2;
1598
1599                 n2s(p,i);
1600
1601                 if (i > n - param_len)
1602                         {
1603                         SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,SSL_R_BAD_SRP_B_LENGTH);
1604                         goto f_err;
1605                         }
1606                 param_len += i;
1607
1608                 if (!(s->srp_ctx.B=BN_bin2bn(p,i,NULL)))
1609                         {
1610                         SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,ERR_R_BN_LIB);
1611                         goto err;
1612                         }
1613                 p+=i;
1614                 n-=param_len;
1615
1616                 if (!srp_verify_server_param(s, &al))
1617                         {
1618                         SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,SSL_R_BAD_SRP_PARAMETERS);
1619                         goto f_err;
1620                         }
1621
1622 /* We must check if there is a certificate */
1623 #ifndef OPENSSL_NO_RSA
1624                 if (alg_a & SSL_aRSA)
1625                         pkey=X509_get_pubkey(s->session->sess_cert->peer_pkeys[SSL_PKEY_RSA_ENC].x509);
1626 #else
1627                 if (0)
1628                         ;
1629 #endif
1630 #ifndef OPENSSL_NO_DSA
1631                 else if (alg_a & SSL_aDSS)
1632                         pkey=X509_get_pubkey(s->session->sess_cert->peer_pkeys[SSL_PKEY_DSA_SIGN].x509);
1633 #endif
1634                 }
1635         else
1636 #endif /* !OPENSSL_NO_SRP */
1637 #ifndef OPENSSL_NO_RSA
1638         if (alg_k & SSL_kRSA)
1639                 {
1640                 if ((rsa=RSA_new()) == NULL)
1641                         {
1642                         SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,ERR_R_MALLOC_FAILURE);
1643                         goto err;
1644                         }
1645
1646                 param_len = 2;
1647                 if (param_len > n)
1648                         {
1649                         SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,
1650                                 SSL_R_LENGTH_TOO_SHORT);
1651                         goto f_err;
1652                         }
1653                 n2s(p,i);
1654
1655                 if (i > n - param_len)
1656                         {
1657                         SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,SSL_R_BAD_RSA_MODULUS_LENGTH);
1658                         goto f_err;
1659                         }
1660                 param_len += i;
1661
1662                 if (!(rsa->n=BN_bin2bn(p,i,rsa->n)))
1663                         {
1664                         SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,ERR_R_BN_LIB);
1665                         goto err;
1666                         }
1667                 p+=i;
1668
1669                 if (2 > n - param_len)
1670                         {
1671                         SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,
1672                                 SSL_R_LENGTH_TOO_SHORT);
1673                         goto f_err;
1674                         }
1675                 param_len += 2;
1676
1677                 n2s(p,i);
1678
1679                 if (i > n - param_len)
1680                         {
1681                         SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,SSL_R_BAD_RSA_E_LENGTH);
1682                         goto f_err;
1683                         }
1684                 param_len += i;
1685
1686                 if (!(rsa->e=BN_bin2bn(p,i,rsa->e)))
1687                         {
1688                         SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,ERR_R_BN_LIB);
1689                         goto err;
1690                         }
1691                 p+=i;
1692                 n-=param_len;
1693
1694                 /* this should be because we are using an export cipher */
1695                 if (alg_a & SSL_aRSA)
1696                         pkey=X509_get_pubkey(s->session->sess_cert->peer_pkeys[SSL_PKEY_RSA_ENC].x509);
1697                 else
1698                         {
1699                         SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,ERR_R_INTERNAL_ERROR);
1700                         goto err;
1701                         }
1702                 s->session->sess_cert->peer_rsa_tmp=rsa;
1703                 rsa=NULL;
1704                 }
1705 #else /* OPENSSL_NO_RSA */
1706         if (0)
1707                 ;
1708 #endif
1709 #ifndef OPENSSL_NO_DH
1710         else if (alg_k & SSL_kEDH)
1711                 {
1712                 if ((dh=DH_new()) == NULL)
1713                         {
1714                         SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,ERR_R_DH_LIB);
1715                         goto err;
1716                         }
1717
1718                 param_len = 2;
1719                 if (param_len > n)
1720                         {
1721                         SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,
1722                                 SSL_R_LENGTH_TOO_SHORT);
1723                         goto f_err;
1724                         }
1725                 n2s(p,i);
1726
1727                 if (i > n - param_len)
1728                         {
1729                         SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,SSL_R_BAD_DH_P_LENGTH);
1730                         goto f_err;
1731                         }
1732                 param_len += i;
1733
1734                 if (!(dh->p=BN_bin2bn(p,i,NULL)))
1735                         {
1736                         SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,ERR_R_BN_LIB);
1737                         goto err;
1738                         }
1739                 p+=i;
1740
1741                 if (2 > n - param_len)
1742                         {
1743                         SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,
1744                                 SSL_R_LENGTH_TOO_SHORT);
1745                         goto f_err;
1746                         }
1747                 param_len += 2;
1748
1749                 n2s(p,i);
1750
1751                 if (i > n - param_len)
1752                         {
1753                         SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,SSL_R_BAD_DH_G_LENGTH);
1754                         goto f_err;
1755                         }
1756                 param_len += i;
1757
1758                 if (!(dh->g=BN_bin2bn(p,i,NULL)))
1759                         {
1760                         SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,ERR_R_BN_LIB);
1761                         goto err;
1762                         }
1763                 p+=i;
1764
1765                 if (2 > n - param_len)
1766                         {
1767                         SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,
1768                                 SSL_R_LENGTH_TOO_SHORT);
1769                         goto f_err;
1770                         }
1771                 param_len += 2;
1772
1773                 n2s(p,i);
1774
1775                 if (i > n - param_len)
1776                         {
1777                         SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,SSL_R_BAD_DH_PUB_KEY_LENGTH);
1778                         goto f_err;
1779                         }
1780                 param_len += i;
1781
1782                 if (!(dh->pub_key=BN_bin2bn(p,i,NULL)))
1783                         {
1784                         SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,ERR_R_BN_LIB);
1785                         goto err;
1786                         }
1787                 p+=i;
1788                 n-=param_len;
1789
1790 #ifndef OPENSSL_NO_RSA
1791                 if (alg_a & SSL_aRSA)
1792                         pkey=X509_get_pubkey(s->session->sess_cert->peer_pkeys[SSL_PKEY_RSA_ENC].x509);
1793 #else
1794                 if (0)
1795                         ;
1796 #endif
1797 #ifndef OPENSSL_NO_DSA
1798                 else if (alg_a & SSL_aDSS)
1799                         pkey=X509_get_pubkey(s->session->sess_cert->peer_pkeys[SSL_PKEY_DSA_SIGN].x509);
1800 #endif
1801                 /* else anonymous DH, so no certificate or pkey. */
1802
1803                 s->session->sess_cert->peer_dh_tmp=dh;
1804                 dh=NULL;
1805                 }
1806         else if ((alg_k & SSL_kDHr) || (alg_k & SSL_kDHd))
1807                 {
1808                 al=SSL_AD_ILLEGAL_PARAMETER;
1809                 SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,SSL_R_TRIED_TO_USE_UNSUPPORTED_CIPHER);
1810                 goto f_err;
1811                 }
1812 #endif /* !OPENSSL_NO_DH */
1813
1814 #ifndef OPENSSL_NO_ECDH
1815         else if (alg_k & SSL_kEECDH)
1816                 {
1817                 EC_GROUP *ngroup;
1818                 const EC_GROUP *group;
1819
1820                 if ((ecdh=EC_KEY_new()) == NULL)
1821                         {
1822                         SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,ERR_R_MALLOC_FAILURE);
1823                         goto err;
1824                         }
1825
1826                 /* Extract elliptic curve parameters and the
1827                  * server's ephemeral ECDH public key.
1828                  * Keep accumulating lengths of various components in
1829                  * param_len and make sure it never exceeds n.
1830                  */
1831
1832                 /* XXX: For now we only support named (not generic) curves
1833                  * and the ECParameters in this case is just three bytes. We
1834                  * also need one byte for the length of the encoded point
1835                  */
1836                 param_len=4;
1837                 if (param_len > n)
1838                         {
1839                         SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,
1840                                 SSL_R_LENGTH_TOO_SHORT);
1841                         goto f_err;
1842                         }
1843                 /* Check curve is one of our preferences, if not server has
1844                  * sent an invalid curve. ECParameters is 3 bytes.
1845                  */
1846                 if (!tls1_check_curve(s, p, 3))
1847                         {
1848                         SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,SSL_R_WRONG_CURVE);
1849                         goto f_err;
1850                         }
1851
1852                 if ((curve_nid = tls1_ec_curve_id2nid(*(p + 2))) == 0) 
1853                         {
1854                         al=SSL_AD_INTERNAL_ERROR;
1855                         SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,SSL_R_UNABLE_TO_FIND_ECDH_PARAMETERS);
1856                         goto f_err;
1857                         }
1858
1859                 ngroup = EC_GROUP_new_by_curve_name(curve_nid);
1860                 if (ngroup == NULL)
1861                         {
1862                         SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,ERR_R_EC_LIB);
1863                         goto err;
1864                         }
1865                 if (EC_KEY_set_group(ecdh, ngroup) == 0)
1866                         {
1867                         SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,ERR_R_EC_LIB);
1868                         goto err;
1869                         }
1870                 EC_GROUP_free(ngroup);
1871
1872                 group = EC_KEY_get0_group(ecdh);
1873
1874                 if (SSL_C_IS_EXPORT(s->s3->tmp.new_cipher) &&
1875                     (EC_GROUP_get_degree(group) > 163))
1876                         {
1877                         al=SSL_AD_EXPORT_RESTRICTION;
1878                         SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,SSL_R_ECGROUP_TOO_LARGE_FOR_CIPHER);
1879                         goto f_err;
1880                         }
1881
1882                 p+=3;
1883
1884                 /* Next, get the encoded ECPoint */
1885                 if (((srvr_ecpoint = EC_POINT_new(group)) == NULL) ||
1886                     ((bn_ctx = BN_CTX_new()) == NULL))
1887                         {
1888                         SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,ERR_R_MALLOC_FAILURE);
1889                         goto err;
1890                         }
1891
1892                 encoded_pt_len = *p;  /* length of encoded point */
1893                 p+=1;
1894
1895                 if ((encoded_pt_len > n - param_len) ||
1896                     (EC_POINT_oct2point(group, srvr_ecpoint, 
1897                         p, encoded_pt_len, bn_ctx) == 0))
1898                         {
1899                         SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,SSL_R_BAD_ECPOINT);
1900                         goto f_err;
1901                         }
1902                 param_len += encoded_pt_len;
1903
1904                 n-=param_len;
1905                 p+=encoded_pt_len;
1906
1907                 /* The ECC/TLS specification does not mention
1908                  * the use of DSA to sign ECParameters in the server
1909                  * key exchange message. We do support RSA and ECDSA.
1910                  */
1911                 if (0) ;
1912 #ifndef OPENSSL_NO_RSA
1913                 else if (alg_a & SSL_aRSA)
1914                         pkey=X509_get_pubkey(s->session->sess_cert->peer_pkeys[SSL_PKEY_RSA_ENC].x509);
1915 #endif
1916 #ifndef OPENSSL_NO_ECDSA
1917                 else if (alg_a & SSL_aECDSA)
1918                         pkey=X509_get_pubkey(s->session->sess_cert->peer_pkeys[SSL_PKEY_ECC].x509);
1919 #endif
1920                 /* else anonymous ECDH, so no certificate or pkey. */
1921                 EC_KEY_set_public_key(ecdh, srvr_ecpoint);
1922                 s->session->sess_cert->peer_ecdh_tmp=ecdh;
1923                 ecdh=NULL;
1924                 BN_CTX_free(bn_ctx);
1925                 bn_ctx = NULL;
1926                 EC_POINT_free(srvr_ecpoint);
1927                 srvr_ecpoint = NULL;
1928                 }
1929         else if (alg_k)
1930                 {
1931                 al=SSL_AD_UNEXPECTED_MESSAGE;
1932                 SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,SSL_R_UNEXPECTED_MESSAGE);
1933                 goto f_err;
1934                 }
1935 #endif /* !OPENSSL_NO_ECDH */
1936
1937
1938         /* p points to the next byte, there are 'n' bytes left */
1939
1940         /* if it was signed, check the signature */
1941         if (pkey != NULL)
1942                 {
1943                 if (SSL_USE_SIGALGS(s))
1944                         {
1945                         int rv;
1946                         if (2 > n)
1947                                 {
1948                                 SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,
1949                                         SSL_R_LENGTH_TOO_SHORT);
1950                                 goto f_err;
1951                                 }
1952                         rv = tls12_check_peer_sigalg(&md, s, p, pkey);
1953                         if (rv == -1)
1954                                 goto err;
1955                         else if (rv == 0)
1956                                 {
1957                                 goto f_err;
1958                                 }
1959 #ifdef SSL_DEBUG
1960 fprintf(stderr, "USING TLSv1.2 HASH %s\n", EVP_MD_name(md));
1961 #endif
1962                         p += 2;
1963                         n -= 2;
1964                         }
1965                 else
1966                         md = EVP_sha1();
1967
1968                 if (2 > n)
1969                         {
1970                         SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,
1971                                 SSL_R_LENGTH_TOO_SHORT);
1972                         goto f_err;
1973                         }
1974                 n2s(p,i);
1975                 n-=2;
1976                 j=EVP_PKEY_size(pkey);
1977
1978                 /* Check signature length. If n is 0 then signature is empty */
1979                 if ((i != n) || (n > j) || (n <= 0))
1980                         {
1981                         /* wrong packet length */
1982                         SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,SSL_R_WRONG_SIGNATURE_LENGTH);
1983                         goto f_err;
1984                         }
1985
1986 #ifndef OPENSSL_NO_RSA
1987                 if (pkey->type == EVP_PKEY_RSA && !SSL_USE_SIGALGS(s))
1988                         {
1989                         int num;
1990                         unsigned int size;
1991
1992                         j=0;
1993                         q=md_buf;
1994                         for (num=2; num > 0; num--)
1995                                 {
1996                                 EVP_MD_CTX_set_flags(&md_ctx,
1997                                         EVP_MD_CTX_FLAG_NON_FIPS_ALLOW);
1998                                 EVP_DigestInit_ex(&md_ctx,(num == 2)
1999                                         ?s->ctx->md5:s->ctx->sha1, NULL);
2000                                 EVP_DigestUpdate(&md_ctx,&(s->s3->client_random[0]),SSL3_RANDOM_SIZE);
2001                                 EVP_DigestUpdate(&md_ctx,&(s->s3->server_random[0]),SSL3_RANDOM_SIZE);
2002                                 EVP_DigestUpdate(&md_ctx,param,param_len);
2003                                 EVP_DigestFinal_ex(&md_ctx,q,&size);
2004                                 q+=size;
2005                                 j+=size;
2006                                 }
2007                         i=RSA_verify(NID_md5_sha1, md_buf, j, p, n,
2008                                                                 pkey->pkey.rsa);
2009                         if (i < 0)
2010                                 {
2011                                 al=SSL_AD_DECRYPT_ERROR;
2012                                 SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,SSL_R_BAD_RSA_DECRYPT);
2013                                 goto f_err;
2014                                 }
2015                         if (i == 0)
2016                                 {
2017                                 /* bad signature */
2018                                 al=SSL_AD_DECRYPT_ERROR;
2019                                 SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,SSL_R_BAD_SIGNATURE);
2020                                 goto f_err;
2021                                 }
2022                         }
2023                 else
2024 #endif
2025                         {
2026                         EVP_VerifyInit_ex(&md_ctx, md, NULL);
2027                         EVP_VerifyUpdate(&md_ctx,&(s->s3->client_random[0]),SSL3_RANDOM_SIZE);
2028                         EVP_VerifyUpdate(&md_ctx,&(s->s3->server_random[0]),SSL3_RANDOM_SIZE);
2029                         EVP_VerifyUpdate(&md_ctx,param,param_len);
2030                         if (EVP_VerifyFinal(&md_ctx,p,(int)n,pkey) <= 0)
2031                                 {
2032                                 /* bad signature */
2033                                 al=SSL_AD_DECRYPT_ERROR;
2034                                 SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,SSL_R_BAD_SIGNATURE);
2035                                 goto f_err;
2036                                 }
2037                         }
2038                 }
2039         else
2040                 {
2041                 /* aNULL, aSRP or kPSK do not need public keys */
2042                 if (!(alg_a & (SSL_aNULL|SSL_aSRP)) && !(alg_k & SSL_kPSK))
2043                         {
2044                         /* Might be wrong key type, check it */
2045                         if (ssl3_check_cert_and_algorithm(s))
2046                                 /* Otherwise this shouldn't happen */
2047                                 SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,ERR_R_INTERNAL_ERROR);
2048                         goto err;
2049                         }
2050                 /* still data left over */
2051                 if (n != 0)
2052                         {
2053                         SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,SSL_R_EXTRA_DATA_IN_MESSAGE);
2054                         goto f_err;
2055                         }
2056                 }
2057         EVP_PKEY_free(pkey);
2058         EVP_MD_CTX_cleanup(&md_ctx);
2059         return(1);
2060 f_err:
2061         ssl3_send_alert(s,SSL3_AL_FATAL,al);
2062 err:
2063         EVP_PKEY_free(pkey);
2064 #ifndef OPENSSL_NO_RSA
2065         if (rsa != NULL)
2066                 RSA_free(rsa);
2067 #endif
2068 #ifndef OPENSSL_NO_DH
2069         if (dh != NULL)
2070                 DH_free(dh);
2071 #endif
2072 #ifndef OPENSSL_NO_ECDH
2073         BN_CTX_free(bn_ctx);
2074         EC_POINT_free(srvr_ecpoint);
2075         if (ecdh != NULL)
2076                 EC_KEY_free(ecdh);
2077 #endif
2078         EVP_MD_CTX_cleanup(&md_ctx);
2079         return(-1);
2080         }
2081
2082 int ssl3_get_certificate_request(SSL *s)
2083         {
2084         int ok,ret=0;
2085         unsigned long n,nc,l;
2086         unsigned int llen, ctype_num,i;
2087         X509_NAME *xn=NULL;
2088         const unsigned char *p,*q;
2089         unsigned char *d;
2090         STACK_OF(X509_NAME) *ca_sk=NULL;
2091
2092         n=s->method->ssl_get_message(s,
2093                 SSL3_ST_CR_CERT_REQ_A,
2094                 SSL3_ST_CR_CERT_REQ_B,
2095                 -1,
2096                 s->max_cert_list,
2097                 &ok);
2098
2099         if (!ok) return((int)n);
2100
2101         s->s3->tmp.cert_req=0;
2102
2103         if (s->s3->tmp.message_type == SSL3_MT_SERVER_DONE)
2104                 {
2105                 s->s3->tmp.reuse_message=1;
2106                 /* If we get here we don't need any cached handshake records
2107                  * as we wont be doing client auth.
2108                  */
2109                 if (s->s3->handshake_buffer)
2110                         {
2111                         if (!ssl3_digest_cached_records(s))
2112                                 goto err;
2113                         }
2114                 return(1);
2115                 }
2116
2117         if (s->s3->tmp.message_type != SSL3_MT_CERTIFICATE_REQUEST)
2118                 {
2119                 ssl3_send_alert(s,SSL3_AL_FATAL,SSL_AD_UNEXPECTED_MESSAGE);
2120                 SSLerr(SSL_F_SSL3_GET_CERTIFICATE_REQUEST,SSL_R_WRONG_MESSAGE_TYPE);
2121                 goto err;
2122                 }
2123
2124         /* TLS does not like anon-DH with client cert */
2125         if (s->version > SSL3_VERSION)
2126                 {
2127                 if (s->s3->tmp.new_cipher->algorithm_auth & SSL_aNULL)
2128                         {
2129                         ssl3_send_alert(s,SSL3_AL_FATAL,SSL_AD_UNEXPECTED_MESSAGE);
2130                         SSLerr(SSL_F_SSL3_GET_CERTIFICATE_REQUEST,SSL_R_TLS_CLIENT_CERT_REQ_WITH_ANON_CIPHER);
2131                         goto err;
2132                         }
2133                 }
2134
2135         p=d=(unsigned char *)s->init_msg;
2136
2137         if ((ca_sk=sk_X509_NAME_new(ca_dn_cmp)) == NULL)
2138                 {
2139                 SSLerr(SSL_F_SSL3_GET_CERTIFICATE_REQUEST,ERR_R_MALLOC_FAILURE);
2140                 goto err;
2141                 }
2142
2143         /* get the certificate types */
2144         ctype_num= *(p++);
2145         if (s->cert->ctypes)
2146                 {
2147                 OPENSSL_free(s->cert->ctypes);
2148                 s->cert->ctypes = NULL;
2149                 }
2150         if (ctype_num > SSL3_CT_NUMBER)
2151                 {
2152                 /* If we exceed static buffer copy all to cert structure */
2153                 s->cert->ctypes = OPENSSL_malloc(ctype_num);
2154                 memcpy(s->cert->ctypes, p, ctype_num);
2155                 s->cert->ctype_num = (size_t)ctype_num;
2156                 ctype_num=SSL3_CT_NUMBER;
2157                 }
2158         for (i=0; i<ctype_num; i++)
2159                 s->s3->tmp.ctype[i]= p[i];
2160         p+=p[-1];
2161         if (SSL_USE_SIGALGS(s))
2162                 {
2163                 n2s(p, llen);
2164                 /* Check we have enough room for signature algorithms and
2165                  * following length value.
2166                  */
2167                 if ((unsigned long)(p - d + llen + 2) > n)
2168                         {
2169                         ssl3_send_alert(s,SSL3_AL_FATAL,SSL_AD_DECODE_ERROR);
2170                         SSLerr(SSL_F_SSL3_GET_CERTIFICATE_REQUEST,SSL_R_DATA_LENGTH_TOO_LONG);
2171                         goto err;
2172                         }
2173                 /* Clear certificate digests and validity flags */
2174                 for (i = 0; i < SSL_PKEY_NUM; i++)
2175                         {
2176                         s->cert->pkeys[i].digest = NULL;
2177                         s->cert->pkeys[i].valid_flags = 0;
2178                         }
2179                 if ((llen & 1) || !tls1_save_sigalgs(s, p, llen))
2180                         {
2181                         ssl3_send_alert(s,SSL3_AL_FATAL,SSL_AD_DECODE_ERROR);
2182                         SSLerr(SSL_F_SSL3_GET_CERTIFICATE_REQUEST,SSL_R_SIGNATURE_ALGORITHMS_ERROR);
2183                         goto err;
2184                         }
2185                 if (!tls1_process_sigalgs(s))
2186                         {
2187                         ssl3_send_alert(s,SSL3_AL_FATAL, SSL_AD_INTERNAL_ERROR);
2188                         SSLerr(SSL_F_SSL3_GET_CERTIFICATE_REQUEST, ERR_R_MALLOC_FAILURE);
2189                         goto err;
2190                         }
2191                 p += llen;
2192                 }
2193
2194         /* get the CA RDNs */
2195         n2s(p,llen);
2196 #if 0
2197 {
2198 FILE *out;
2199 out=fopen("/tmp/vsign.der","w");
2200 fwrite(p,1,llen,out);
2201 fclose(out);
2202 }
2203 #endif
2204
2205         if ((unsigned long)(p - d + llen) != n)
2206                 {
2207                 ssl3_send_alert(s,SSL3_AL_FATAL,SSL_AD_DECODE_ERROR);
2208                 SSLerr(SSL_F_SSL3_GET_CERTIFICATE_REQUEST,SSL_R_LENGTH_MISMATCH);
2209                 goto err;
2210                 }
2211
2212         for (nc=0; nc<llen; )
2213                 {
2214                 n2s(p,l);
2215                 if ((l+nc+2) > llen)
2216                         {
2217                         if ((s->options & SSL_OP_NETSCAPE_CA_DN_BUG))
2218                                 goto cont; /* netscape bugs */
2219                         ssl3_send_alert(s,SSL3_AL_FATAL,SSL_AD_DECODE_ERROR);
2220                         SSLerr(SSL_F_SSL3_GET_CERTIFICATE_REQUEST,SSL_R_CA_DN_TOO_LONG);
2221                         goto err;
2222                         }
2223
2224                 q=p;
2225
2226                 if ((xn=d2i_X509_NAME(NULL,&q,l)) == NULL)
2227                         {
2228                         /* If netscape tolerance is on, ignore errors */
2229                         if (s->options & SSL_OP_NETSCAPE_CA_DN_BUG)
2230                                 goto cont;
2231                         else
2232                                 {
2233                                 ssl3_send_alert(s,SSL3_AL_FATAL,SSL_AD_DECODE_ERROR);
2234                                 SSLerr(SSL_F_SSL3_GET_CERTIFICATE_REQUEST,ERR_R_ASN1_LIB);
2235                                 goto err;
2236                                 }
2237                         }
2238
2239                 if (q != (p+l))
2240                         {
2241                         ssl3_send_alert(s,SSL3_AL_FATAL,SSL_AD_DECODE_ERROR);
2242                         SSLerr(SSL_F_SSL3_GET_CERTIFICATE_REQUEST,SSL_R_CA_DN_LENGTH_MISMATCH);
2243                         goto err;
2244                         }
2245                 if (!sk_X509_NAME_push(ca_sk,xn))
2246                         {
2247                         SSLerr(SSL_F_SSL3_GET_CERTIFICATE_REQUEST,ERR_R_MALLOC_FAILURE);
2248                         goto err;
2249                         }
2250
2251                 p+=l;
2252                 nc+=l+2;
2253                 }
2254
2255         if (0)
2256                 {
2257 cont:
2258                 ERR_clear_error();
2259                 }
2260
2261         /* we should setup a certificate to return.... */
2262         s->s3->tmp.cert_req=1;
2263         s->s3->tmp.ctype_num=ctype_num;
2264         if (s->s3->tmp.ca_names != NULL)
2265                 sk_X509_NAME_pop_free(s->s3->tmp.ca_names,X509_NAME_free);
2266         s->s3->tmp.ca_names=ca_sk;
2267         ca_sk=NULL;
2268
2269         ret=1;
2270 err:
2271         if (ca_sk != NULL) sk_X509_NAME_pop_free(ca_sk,X509_NAME_free);
2272         return(ret);
2273         }
2274
2275 static int ca_dn_cmp(const X509_NAME * const *a, const X509_NAME * const *b)
2276         {
2277         return(X509_NAME_cmp(*a,*b));
2278         }
2279 #ifndef OPENSSL_NO_TLSEXT
2280 int ssl3_get_new_session_ticket(SSL *s)
2281         {
2282         int ok,al,ret=0, ticklen;
2283         long n;
2284         const unsigned char *p;
2285         unsigned char *d;
2286
2287         n=s->method->ssl_get_message(s,
2288                 SSL3_ST_CR_SESSION_TICKET_A,
2289                 SSL3_ST_CR_SESSION_TICKET_B,
2290                 -1,
2291                 16384,
2292                 &ok);
2293
2294         if (!ok)
2295                 return((int)n);
2296
2297         if (s->s3->tmp.message_type == SSL3_MT_FINISHED)
2298                 {
2299                 s->s3->tmp.reuse_message=1;
2300                 return(1);
2301                 }
2302         if (s->s3->tmp.message_type != SSL3_MT_NEWSESSION_TICKET)
2303                 {
2304                 al=SSL_AD_UNEXPECTED_MESSAGE;
2305                 SSLerr(SSL_F_SSL3_GET_NEW_SESSION_TICKET,SSL_R_BAD_MESSAGE_TYPE);
2306                 goto f_err;
2307                 }
2308         if (n < 6)
2309                 {
2310                 /* need at least ticket_lifetime_hint + ticket length */
2311                 al = SSL_AD_DECODE_ERROR;
2312                 SSLerr(SSL_F_SSL3_GET_NEW_SESSION_TICKET,SSL_R_LENGTH_MISMATCH);
2313                 goto f_err;
2314                 }
2315
2316         p=d=(unsigned char *)s->init_msg;
2317         n2l(p, s->session->tlsext_tick_lifetime_hint);
2318         n2s(p, ticklen);
2319         /* ticket_lifetime_hint + ticket_length + ticket */
2320         if (ticklen + 6 != n)
2321                 {
2322                 al = SSL_AD_DECODE_ERROR;
2323                 SSLerr(SSL_F_SSL3_GET_NEW_SESSION_TICKET,SSL_R_LENGTH_MISMATCH);
2324                 goto f_err;
2325                 }
2326         if (s->session->tlsext_tick)
2327                 {
2328                 OPENSSL_free(s->session->tlsext_tick);
2329                 s->session->tlsext_ticklen = 0;
2330                 }
2331         s->session->tlsext_tick = OPENSSL_malloc(ticklen);
2332         if (!s->session->tlsext_tick)
2333                 {
2334                 SSLerr(SSL_F_SSL3_GET_NEW_SESSION_TICKET,ERR_R_MALLOC_FAILURE);
2335                 goto err;
2336                 }
2337         memcpy(s->session->tlsext_tick, p, ticklen);
2338         s->session->tlsext_ticklen = ticklen;
2339         /* There are two ways to detect a resumed ticket session.
2340          * One is to set an appropriate session ID and then the server
2341          * must return a match in ServerHello. This allows the normal
2342          * client session ID matching to work and we know much 
2343          * earlier that the ticket has been accepted.
2344          * 
2345          * The other way is to set zero length session ID when the
2346          * ticket is presented and rely on the handshake to determine
2347          * session resumption.
2348          *
2349          * We choose the former approach because this fits in with
2350          * assumptions elsewhere in OpenSSL. The session ID is set
2351          * to the SHA256 (or SHA1 is SHA256 is disabled) hash of the
2352          * ticket.
2353          */ 
2354         EVP_Digest(p, ticklen,
2355                         s->session->session_id, &s->session->session_id_length,
2356 #ifndef OPENSSL_NO_SHA256
2357                                                         EVP_sha256(), NULL);
2358 #else
2359                                                         EVP_sha1(), NULL);
2360 #endif
2361         ret=1;
2362         return(ret);
2363 f_err:
2364         ssl3_send_alert(s,SSL3_AL_FATAL,al);
2365 err:
2366         return(-1);
2367         }
2368
2369 int ssl3_get_cert_status(SSL *s)
2370         {
2371         int ok, al;
2372         unsigned long resplen,n;
2373         const unsigned char *p;
2374
2375         n=s->method->ssl_get_message(s,
2376                 SSL3_ST_CR_CERT_STATUS_A,
2377                 SSL3_ST_CR_CERT_STATUS_B,
2378                 SSL3_MT_CERTIFICATE_STATUS,
2379                 16384,
2380                 &ok);
2381
2382         if (!ok) return((int)n);
2383         if (n < 4)
2384                 {
2385                 /* need at least status type + length */
2386                 al = SSL_AD_DECODE_ERROR;
2387                 SSLerr(SSL_F_SSL3_GET_CERT_STATUS,SSL_R_LENGTH_MISMATCH);
2388                 goto f_err;
2389                 }
2390         p = (unsigned char *)s->init_msg;
2391         if (*p++ != TLSEXT_STATUSTYPE_ocsp)
2392                 {
2393                 al = SSL_AD_DECODE_ERROR;
2394                 SSLerr(SSL_F_SSL3_GET_CERT_STATUS,SSL_R_UNSUPPORTED_STATUS_TYPE);
2395                 goto f_err;
2396                 }
2397         n2l3(p, resplen);
2398         if (resplen + 4 != n)
2399                 {
2400                 al = SSL_AD_DECODE_ERROR;
2401                 SSLerr(SSL_F_SSL3_GET_CERT_STATUS,SSL_R_LENGTH_MISMATCH);
2402                 goto f_err;
2403                 }
2404         if (s->tlsext_ocsp_resp)
2405                 OPENSSL_free(s->tlsext_ocsp_resp);
2406         s->tlsext_ocsp_resp = BUF_memdup(p, resplen);
2407         if (!s->tlsext_ocsp_resp)
2408                 {
2409                 al = SSL_AD_INTERNAL_ERROR;
2410                 SSLerr(SSL_F_SSL3_GET_CERT_STATUS,ERR_R_MALLOC_FAILURE);
2411                 goto f_err;
2412                 }
2413         s->tlsext_ocsp_resplen = resplen;
2414         if (s->ctx->tlsext_status_cb)
2415                 {
2416                 int ret;
2417                 ret = s->ctx->tlsext_status_cb(s, s->ctx->tlsext_status_arg);
2418                 if (ret == 0)
2419                         {
2420                         al = SSL_AD_BAD_CERTIFICATE_STATUS_RESPONSE;
2421                         SSLerr(SSL_F_SSL3_GET_CERT_STATUS,SSL_R_INVALID_STATUS_RESPONSE);
2422                         goto f_err;
2423                         }
2424                 if (ret < 0)
2425                         {
2426                         al = SSL_AD_INTERNAL_ERROR;
2427                         SSLerr(SSL_F_SSL3_GET_CERT_STATUS,ERR_R_MALLOC_FAILURE);
2428                         goto f_err;
2429                         }
2430                 }
2431         return 1;
2432 f_err:
2433         ssl3_send_alert(s,SSL3_AL_FATAL,al);
2434         return(-1);
2435         }
2436 #endif
2437
2438 int ssl3_get_server_done(SSL *s)
2439         {
2440         int ok,ret=0;
2441         long n;
2442
2443         n=s->method->ssl_get_message(s,
2444                 SSL3_ST_CR_SRVR_DONE_A,
2445                 SSL3_ST_CR_SRVR_DONE_B,
2446                 SSL3_MT_SERVER_DONE,
2447                 30, /* should be very small, like 0 :-) */
2448                 &ok);
2449
2450         if (!ok) return((int)n);
2451         if (n > 0)
2452                 {
2453                 /* should contain no data */
2454                 ssl3_send_alert(s,SSL3_AL_FATAL,SSL_AD_DECODE_ERROR);
2455                 SSLerr(SSL_F_SSL3_GET_SERVER_DONE,SSL_R_LENGTH_MISMATCH);
2456                 return -1;
2457                 }
2458         ret=1;
2459         return(ret);
2460         }
2461
2462
2463 int ssl3_send_client_key_exchange(SSL *s)
2464         {
2465         unsigned char *p;
2466         int n;
2467         unsigned long alg_k;
2468 #ifndef OPENSSL_NO_RSA
2469         unsigned char *q;
2470         EVP_PKEY *pkey=NULL;
2471 #endif
2472 #ifndef OPENSSL_NO_KRB5
2473         KSSL_ERR kssl_err;
2474 #endif /* OPENSSL_NO_KRB5 */
2475 #ifndef OPENSSL_NO_ECDH
2476         EC_KEY *clnt_ecdh = NULL;
2477         const EC_POINT *srvr_ecpoint = NULL;
2478         EVP_PKEY *srvr_pub_pkey = NULL;
2479         unsigned char *encodedPoint = NULL;
2480         int encoded_pt_len = 0;
2481         BN_CTX * bn_ctx = NULL;
2482 #endif
2483
2484         if (s->state == SSL3_ST_CW_KEY_EXCH_A)
2485                 {
2486                 p = ssl_handshake_start(s);
2487
2488                 alg_k=s->s3->tmp.new_cipher->algorithm_mkey;
2489
2490                 /* Fool emacs indentation */
2491                 if (0) {}
2492 #ifndef OPENSSL_NO_RSA
2493                 else if (alg_k & SSL_kRSA)
2494                         {
2495                         RSA *rsa;
2496                         unsigned char tmp_buf[SSL_MAX_MASTER_KEY_LENGTH];
2497
2498                         if (s->session->sess_cert == NULL)
2499                                 {
2500                                 /* We should always have a server certificate with SSL_kRSA. */
2501                                 SSLerr(SSL_F_SSL3_SEND_CLIENT_KEY_EXCHANGE,ERR_R_INTERNAL_ERROR);
2502                                 goto err;
2503                                 }
2504
2505                         if (s->session->sess_cert->peer_rsa_tmp != NULL)
2506                                 rsa=s->session->sess_cert->peer_rsa_tmp;
2507                         else
2508                                 {
2509                                 pkey=X509_get_pubkey(s->session->sess_cert->peer_pkeys[SSL_PKEY_RSA_ENC].x509);
2510                                 if ((pkey == NULL) ||
2511                                         (pkey->type != EVP_PKEY_RSA) ||
2512                                         (pkey->pkey.rsa == NULL))
2513                                         {
2514                                         SSLerr(SSL_F_SSL3_SEND_CLIENT_KEY_EXCHANGE,ERR_R_INTERNAL_ERROR);
2515                                         goto err;
2516                                         }
2517                                 rsa=pkey->pkey.rsa;
2518                                 EVP_PKEY_free(pkey);
2519                                 }
2520                                 
2521                         tmp_buf[0]=s->client_version>>8;
2522                         tmp_buf[1]=s->client_version&0xff;
2523                         if (RAND_bytes(&(tmp_buf[2]),sizeof tmp_buf-2) <= 0)
2524                                         goto err;
2525
2526                         s->session->master_key_length=sizeof tmp_buf;
2527
2528                         q=p;
2529                         /* Fix buf for TLS and beyond */
2530                         if (s->version > SSL3_VERSION)
2531                                 p+=2;
2532                         n=RSA_public_encrypt(sizeof tmp_buf,
2533                                 tmp_buf,p,rsa,RSA_PKCS1_PADDING);
2534 #ifdef PKCS1_CHECK
2535                         if (s->options & SSL_OP_PKCS1_CHECK_1) p[1]++;
2536                         if (s->options & SSL_OP_PKCS1_CHECK_2) tmp_buf[0]=0x70;
2537 #endif
2538                         if (n <= 0)
2539                                 {
2540                                 SSLerr(SSL_F_SSL3_SEND_CLIENT_KEY_EXCHANGE,SSL_R_BAD_RSA_ENCRYPT);
2541                                 goto err;
2542                                 }
2543
2544                         /* Fix buf for TLS and beyond */
2545                         if (s->version > SSL3_VERSION)
2546                                 {
2547                                 s2n(n,q);
2548                                 n+=2;
2549                                 }
2550
2551                         s->session->master_key_length=
2552                                 s->method->ssl3_enc->generate_master_secret(s,
2553                                         s->session->master_key,
2554                                         tmp_buf,sizeof tmp_buf);
2555                         OPENSSL_cleanse(tmp_buf,sizeof tmp_buf);
2556                         }
2557 #endif
2558 #ifndef OPENSSL_NO_KRB5
2559                 else if (alg_k & SSL_kKRB5)
2560                         {
2561                         krb5_error_code krb5rc;
2562                         KSSL_CTX        *kssl_ctx = s->kssl_ctx;
2563                         /*  krb5_data   krb5_ap_req;  */
2564                         krb5_data       *enc_ticket;
2565                         krb5_data       authenticator, *authp = NULL;
2566                         EVP_CIPHER_CTX  ciph_ctx;
2567                         const EVP_CIPHER *enc = NULL;
2568                         unsigned char   iv[EVP_MAX_IV_LENGTH];
2569                         unsigned char   tmp_buf[SSL_MAX_MASTER_KEY_LENGTH];
2570                         unsigned char   epms[SSL_MAX_MASTER_KEY_LENGTH 
2571                                                 + EVP_MAX_IV_LENGTH];
2572                         int             padl, outl = sizeof(epms);
2573
2574                         EVP_CIPHER_CTX_init(&ciph_ctx);
2575
2576 #ifdef KSSL_DEBUG
2577                         printf("ssl3_send_client_key_exchange(%lx & %lx)\n",
2578                                 alg_k, SSL_kKRB5);
2579 #endif  /* KSSL_DEBUG */
2580
2581                         authp = NULL;
2582 #ifdef KRB5SENDAUTH
2583                         if (KRB5SENDAUTH)  authp = &authenticator;
2584 #endif  /* KRB5SENDAUTH */
2585
2586                         krb5rc = kssl_cget_tkt(kssl_ctx, &enc_ticket, authp,
2587                                 &kssl_err);
2588                         enc = kssl_map_enc(kssl_ctx->enctype);
2589                         if (enc == NULL)
2590                             goto err;
2591 #ifdef KSSL_DEBUG
2592                         {
2593                         printf("kssl_cget_tkt rtn %d\n", krb5rc);
2594                         if (krb5rc && kssl_err.text)
2595                           printf("kssl_cget_tkt kssl_err=%s\n", kssl_err.text);
2596                         }
2597 #endif  /* KSSL_DEBUG */
2598
2599                         if (krb5rc)
2600                                 {
2601                                 ssl3_send_alert(s,SSL3_AL_FATAL,
2602                                                 SSL_AD_HANDSHAKE_FAILURE);
2603                                 SSLerr(SSL_F_SSL3_SEND_CLIENT_KEY_EXCHANGE,
2604                                                 kssl_err.reason);
2605                                 goto err;
2606                                 }
2607
2608                         /*  20010406 VRS - Earlier versions used KRB5 AP_REQ
2609                         **  in place of RFC 2712 KerberosWrapper, as in:
2610                         **
2611                         **  Send ticket (copy to *p, set n = length)
2612                         **  n = krb5_ap_req.length;
2613                         **  memcpy(p, krb5_ap_req.data, krb5_ap_req.length);
2614                         **  if (krb5_ap_req.data)  
2615                         **    kssl_krb5_free_data_contents(NULL,&krb5_ap_req);
2616                         **
2617                         **  Now using real RFC 2712 KerberosWrapper
2618                         **  (Thanks to Simon Wilkinson <sxw@sxw.org.uk>)
2619                         **  Note: 2712 "opaque" types are here replaced
2620                         **  with a 2-byte length followed by the value.
2621                         **  Example:
2622                         **  KerberosWrapper= xx xx asn1ticket 0 0 xx xx encpms
2623                         **  Where "xx xx" = length bytes.  Shown here with
2624                         **  optional authenticator omitted.
2625                         */
2626
2627                         /*  KerberosWrapper.Ticket              */
2628                         s2n(enc_ticket->length,p);
2629                         memcpy(p, enc_ticket->data, enc_ticket->length);
2630                         p+= enc_ticket->length;
2631                         n = enc_ticket->length + 2;
2632
2633                         /*  KerberosWrapper.Authenticator       */
2634                         if (authp  &&  authp->length)  
2635                                 {
2636                                 s2n(authp->length,p);
2637                                 memcpy(p, authp->data, authp->length);
2638                                 p+= authp->length;
2639                                 n+= authp->length + 2;
2640                                 
2641                                 free(authp->data);
2642                                 authp->data = NULL;
2643                                 authp->length = 0;
2644                                 }
2645                         else
2646                                 {
2647                                 s2n(0,p);/*  null authenticator length  */
2648                                 n+=2;
2649                                 }
2650  
2651                             tmp_buf[0]=s->client_version>>8;
2652                             tmp_buf[1]=s->client_version&0xff;
2653                             if (RAND_bytes(&(tmp_buf[2]),sizeof tmp_buf-2) <= 0)
2654                                 goto err;
2655
2656                         /*  20010420 VRS.  Tried it this way; failed.
2657                         **      EVP_EncryptInit_ex(&ciph_ctx,enc, NULL,NULL);
2658                         **      EVP_CIPHER_CTX_set_key_length(&ciph_ctx,
2659                         **                              kssl_ctx->length);
2660                         **      EVP_EncryptInit_ex(&ciph_ctx,NULL, key,iv);
2661                         */
2662
2663                         memset(iv, 0, sizeof iv);  /* per RFC 1510 */
2664                         EVP_EncryptInit_ex(&ciph_ctx,enc, NULL,
2665                                 kssl_ctx->key,iv);
2666                         EVP_EncryptUpdate(&ciph_ctx,epms,&outl,tmp_buf,
2667                                 sizeof tmp_buf);
2668                         EVP_EncryptFinal_ex(&ciph_ctx,&(epms[outl]),&padl);
2669                         outl += padl;
2670                         if (outl > (int)sizeof epms)
2671                                 {
2672                                 SSLerr(SSL_F_SSL3_SEND_CLIENT_KEY_EXCHANGE, ERR_R_INTERNAL_ERROR);
2673                                 goto err;
2674                                 }
2675                         EVP_CIPHER_CTX_cleanup(&ciph_ctx);
2676
2677                         /*  KerberosWrapper.EncryptedPreMasterSecret    */
2678                         s2n(outl,p);
2679                         memcpy(p, epms, outl);
2680                         p+=outl;
2681                         n+=outl + 2;
2682
2683                         s->session->master_key_length=
2684                                 s->method->ssl3_enc->generate_master_secret(s,
2685                                         s->session->master_key,
2686                                         tmp_buf, sizeof tmp_buf);
2687
2688                         OPENSSL_cleanse(tmp_buf, sizeof tmp_buf);
2689                         OPENSSL_cleanse(epms, outl);
2690                         }
2691 #endif
2692 #ifndef OPENSSL_NO_DH
2693                 else if (alg_k & (SSL_kEDH|SSL_kDHr|SSL_kDHd))
2694                         {
2695                         DH *dh_srvr,*dh_clnt;
2696                         SESS_CERT *scert = s->session->sess_cert;
2697
2698                         if (scert == NULL) 
2699                                 {
2700                                 ssl3_send_alert(s,SSL3_AL_FATAL,SSL_AD_UNEXPECTED_MESSAGE);
2701                                 SSLerr(SSL_F_SSL3_SEND_CLIENT_KEY_EXCHANGE,SSL_R_UNEXPECTED_MESSAGE);
2702                                 goto err;
2703                                 }
2704
2705                         if (scert->peer_dh_tmp != NULL)
2706                                 dh_srvr=scert->peer_dh_tmp;
2707                         else
2708                                 {
2709                                 /* we get them from the cert */
2710                                 int idx = scert->peer_cert_type;
2711                                 EVP_PKEY *spkey = NULL;
2712                                 dh_srvr = NULL;
2713                                 if (idx >= 0)
2714                                         spkey = X509_get_pubkey(
2715                                                 scert->peer_pkeys[idx].x509);
2716                                 if (spkey)
2717                                         {
2718                                         dh_srvr = EVP_PKEY_get1_DH(spkey);
2719                                         EVP_PKEY_free(spkey);
2720                                         }
2721                                 if (dh_srvr == NULL)
2722                                         {
2723                                         SSLerr(SSL_F_SSL3_SEND_CLIENT_KEY_EXCHANGE,
2724                                             ERR_R_INTERNAL_ERROR);
2725                                         goto err;
2726                                         }
2727                                 }
2728                         if (s->s3->flags & TLS1_FLAGS_SKIP_CERT_VERIFY)
2729                                 {
2730                                 /* Use client certificate key */
2731                                 EVP_PKEY *clkey = s->cert->key->privatekey;
2732                                 dh_clnt = NULL;
2733                                 if (clkey)
2734                                         dh_clnt = EVP_PKEY_get1_DH(clkey);
2735                                 if (dh_clnt == NULL)
2736                                         {
2737                                         SSLerr(SSL_F_SSL3_SEND_CLIENT_KEY_EXCHANGE,
2738                                             ERR_R_INTERNAL_ERROR);
2739                                         goto err;
2740                                         }
2741                                 }
2742                         else
2743                                 {
2744                                 /* generate a new random key */
2745                                 if ((dh_clnt=DHparams_dup(dh_srvr)) == NULL)
2746                                         {
2747                                         SSLerr(SSL_F_SSL3_SEND_CLIENT_KEY_EXCHANGE,ERR_R_DH_LIB);
2748                                         goto err;
2749                                         }
2750                                 if (!DH_generate_key(dh_clnt))
2751                                         {
2752                                         SSLerr(SSL_F_SSL3_SEND_CLIENT_KEY_EXCHANGE,ERR_R_DH_LIB);
2753                                         DH_free(dh_clnt);
2754                                         goto err;
2755                                         }
2756                                 }
2757
2758                         /* use the 'p' output buffer for the DH key, but
2759                          * make sure to clear it out afterwards */
2760
2761                         n=DH_compute_key(p,dh_srvr->pub_key,dh_clnt);
2762                         if (scert->peer_dh_tmp == NULL)
2763                                 DH_free(dh_srvr);
2764
2765                         if (n <= 0)
2766                                 {
2767                                 SSLerr(SSL_F_SSL3_SEND_CLIENT_KEY_EXCHANGE,ERR_R_DH_LIB);
2768                                 DH_free(dh_clnt);
2769                                 goto err;
2770                                 }
2771
2772                         /* generate master key from the result */
2773                         s->session->master_key_length=
2774                                 s->method->ssl3_enc->generate_master_secret(s,
2775                                         s->session->master_key,p,n);
2776                         /* clean up */
2777                         memset(p,0,n);
2778
2779                         if (s->s3->flags & TLS1_FLAGS_SKIP_CERT_VERIFY)
2780                                 n = 0;
2781                         else
2782                                 {
2783                                 /* send off the data */
2784                                 n=BN_num_bytes(dh_clnt->pub_key);
2785                                 s2n(n,p);
2786                                 BN_bn2bin(dh_clnt->pub_key,p);
2787                                 n+=2;
2788                                 }
2789
2790                         DH_free(dh_clnt);
2791
2792                         /* perhaps clean things up a bit EAY EAY EAY EAY*/
2793                         }
2794 #endif
2795
2796 #ifndef OPENSSL_NO_ECDH 
2797                 else if (alg_k & (SSL_kEECDH|SSL_kECDHr|SSL_kECDHe))
2798                         {
2799                         const EC_GROUP *srvr_group = NULL;
2800                         EC_KEY *tkey;
2801                         int ecdh_clnt_cert = 0;
2802                         int field_size = 0;
2803
2804                         if (s->session->sess_cert == NULL) 
2805                                 {
2806                                 ssl3_send_alert(s,SSL3_AL_FATAL,SSL_AD_UNEXPECTED_MESSAGE);
2807                                 SSLerr(SSL_F_SSL3_SEND_CLIENT_KEY_EXCHANGE,SSL_R_UNEXPECTED_MESSAGE);
2808                                 goto err;
2809                                 }
2810
2811                         /* Did we send out the client's
2812                          * ECDH share for use in premaster
2813                          * computation as part of client certificate?
2814                          * If so, set ecdh_clnt_cert to 1.
2815                          */
2816                         if ((alg_k & (SSL_kECDHr|SSL_kECDHe)) && (s->cert != NULL)) 
2817                                 {
2818                                 /* XXX: For now, we do not support client
2819                                  * authentication using ECDH certificates.
2820                                  * To add such support, one needs to add
2821                                  * code that checks for appropriate 
2822                                  * conditions and sets ecdh_clnt_cert to 1.
2823                                  * For example, the cert have an ECC
2824                                  * key on the same curve as the server's
2825                                  * and the key should be authorized for
2826                                  * key agreement.
2827                                  *
2828                                  * One also needs to add code in ssl3_connect
2829                                  * to skip sending the certificate verify
2830                                  * message.
2831                                  *
2832                                  * if ((s->cert->key->privatekey != NULL) &&
2833                                  *     (s->cert->key->privatekey->type ==
2834                                  *      EVP_PKEY_EC) && ...)
2835                                  * ecdh_clnt_cert = 1;
2836                                  */
2837                                 }
2838
2839                         if (s->session->sess_cert->peer_ecdh_tmp != NULL)
2840                                 {
2841                                 tkey = s->session->sess_cert->peer_ecdh_tmp;
2842                                 }
2843                         else
2844                                 {
2845                                 /* Get the Server Public Key from Cert */
2846                                 srvr_pub_pkey = X509_get_pubkey(s->session-> \
2847                                     sess_cert->peer_pkeys[SSL_PKEY_ECC].x509);
2848                                 if ((srvr_pub_pkey == NULL) ||
2849                                     (srvr_pub_pkey->type != EVP_PKEY_EC) ||
2850                                     (srvr_pub_pkey->pkey.ec == NULL))
2851                                         {
2852                                         SSLerr(SSL_F_SSL3_SEND_CLIENT_KEY_EXCHANGE,
2853                                             ERR_R_INTERNAL_ERROR);
2854                                         goto err;
2855                                         }
2856
2857                                 tkey = srvr_pub_pkey->pkey.ec;
2858                                 }
2859
2860                         srvr_group   = EC_KEY_get0_group(tkey);
2861                         srvr_ecpoint = EC_KEY_get0_public_key(tkey);
2862
2863                         if ((srvr_group == NULL) || (srvr_ecpoint == NULL))
2864                                 {
2865                                 SSLerr(SSL_F_SSL3_SEND_CLIENT_KEY_EXCHANGE,
2866                                     ERR_R_INTERNAL_ERROR);
2867                                 goto err;
2868                                 }
2869
2870                         if ((clnt_ecdh=EC_KEY_new()) == NULL) 
2871                                 {
2872                                 SSLerr(SSL_F_SSL3_SEND_CLIENT_KEY_EXCHANGE,ERR_R_MALLOC_FAILURE);
2873                                 goto err;
2874                                 }
2875
2876                         if (!EC_KEY_set_group(clnt_ecdh, srvr_group))
2877                                 {
2878                                 SSLerr(SSL_F_SSL3_SEND_CLIENT_KEY_EXCHANGE,ERR_R_EC_LIB);
2879                                 goto err;
2880                                 }
2881                         if (ecdh_clnt_cert) 
2882                                 { 
2883                                 /* Reuse key info from our certificate
2884                                  * We only need our private key to perform
2885                                  * the ECDH computation.
2886                                  */
2887                                 const BIGNUM *priv_key;
2888                                 tkey = s->cert->key->privatekey->pkey.ec;
2889                                 priv_key = EC_KEY_get0_private_key(tkey);
2890                                 if (priv_key == NULL)
2891                                         {
2892                                         SSLerr(SSL_F_SSL3_SEND_CLIENT_KEY_EXCHANGE,ERR_R_MALLOC_FAILURE);
2893                                         goto err;
2894                                         }
2895                                 if (!EC_KEY_set_private_key(clnt_ecdh, priv_key))
2896                                         {
2897                                         SSLerr(SSL_F_SSL3_SEND_CLIENT_KEY_EXCHANGE,ERR_R_EC_LIB);
2898                                         goto err;
2899                                         }
2900                                 }
2901                         else 
2902                                 {
2903                                 /* Generate a new ECDH key pair */
2904                                 if (!(EC_KEY_generate_key(clnt_ecdh)))
2905                                         {
2906                                         SSLerr(SSL_F_SSL3_SEND_CLIENT_KEY_EXCHANGE, ERR_R_ECDH_LIB);
2907                                         goto err;
2908                                         }
2909                                 }
2910
2911                         /* use the 'p' output buffer for the ECDH key, but
2912                          * make sure to clear it out afterwards
2913                          */
2914
2915                         field_size = EC_GROUP_get_degree(srvr_group);
2916                         if (field_size <= 0)
2917                                 {
2918                                 SSLerr(SSL_F_SSL3_SEND_CLIENT_KEY_EXCHANGE, 
2919                                        ERR_R_ECDH_LIB);
2920                                 goto err;
2921                                 }
2922                         n=ECDH_compute_key(p, (field_size+7)/8, srvr_ecpoint, clnt_ecdh, NULL);
2923                         if (n <= 0)
2924                                 {
2925                                 SSLerr(SSL_F_SSL3_SEND_CLIENT_KEY_EXCHANGE, 
2926                                        ERR_R_ECDH_LIB);
2927                                 goto err;
2928                                 }
2929
2930                         /* generate master key from the result */
2931                         s->session->master_key_length = s->method->ssl3_enc \
2932                             -> generate_master_secret(s, 
2933                                 s->session->master_key,
2934                                 p, n);
2935
2936                         memset(p, 0, n); /* clean up */
2937
2938                         if (ecdh_clnt_cert) 
2939                                 {
2940                                 /* Send empty client key exch message */
2941                                 n = 0;
2942                                 }
2943                         else 
2944                                 {
2945                                 /* First check the size of encoding and
2946                                  * allocate memory accordingly.
2947                                  */
2948                                 encoded_pt_len = 
2949                                     EC_POINT_point2oct(srvr_group, 
2950                                         EC_KEY_get0_public_key(clnt_ecdh), 
2951                                         POINT_CONVERSION_UNCOMPRESSED, 
2952                                         NULL, 0, NULL);
2953
2954                                 encodedPoint = (unsigned char *) 
2955                                     OPENSSL_malloc(encoded_pt_len * 
2956                                         sizeof(unsigned char)); 
2957                                 bn_ctx = BN_CTX_new();
2958                                 if ((encodedPoint == NULL) || 
2959                                     (bn_ctx == NULL)) 
2960                                         {
2961                                         SSLerr(SSL_F_SSL3_SEND_CLIENT_KEY_EXCHANGE,ERR_R_MALLOC_FAILURE);
2962                                         goto err;
2963                                         }
2964
2965                                 /* Encode the public key */
2966                                 n = EC_POINT_point2oct(srvr_group, 
2967                                     EC_KEY_get0_public_key(clnt_ecdh), 
2968                                     POINT_CONVERSION_UNCOMPRESSED, 
2969                                     encodedPoint, encoded_pt_len, bn_ctx);
2970
2971                                 *p = n; /* length of encoded point */
2972                                 /* Encoded point will be copied here */
2973                                 p += 1; 
2974                                 /* copy the point */
2975                                 memcpy((unsigned char *)p, encodedPoint, n);
2976                                 /* increment n to account for length field */
2977                                 n += 1; 
2978                                 }
2979
2980                         /* Free allocated memory */
2981                         BN_CTX_free(bn_ctx);
2982                         if (encodedPoint != NULL) OPENSSL_free(encodedPoint);
2983                         if (clnt_ecdh != NULL) 
2984                                  EC_KEY_free(clnt_ecdh);
2985                         EVP_PKEY_free(srvr_pub_pkey);
2986                         }
2987 #endif /* !OPENSSL_NO_ECDH */
2988                 else if (alg_k & SSL_kGOST) 
2989                         {
2990                         /* GOST key exchange message creation */
2991                         EVP_PKEY_CTX *pkey_ctx;
2992                         X509 *peer_cert; 
2993                         size_t msglen;
2994                         unsigned int md_len;
2995                         int keytype;
2996                         unsigned char premaster_secret[32],shared_ukm[32], tmp[256];
2997                         EVP_MD_CTX *ukm_hash;
2998                         EVP_PKEY *pub_key;
2999
3000                         /* Get server sertificate PKEY and create ctx from it */
3001                         peer_cert=s->session->sess_cert->peer_pkeys[(keytype=SSL_PKEY_GOST01)].x509;
3002                         if (!peer_cert) 
3003                                 peer_cert=s->session->sess_cert->peer_pkeys[(keytype=SSL_PKEY_GOST94)].x509;
3004                         if (!peer_cert)         {
3005                                         SSLerr(SSL_F_SSL3_SEND_CLIENT_KEY_EXCHANGE,SSL_R_NO_GOST_CERTIFICATE_SENT_BY_PEER);
3006                                         goto err;
3007                                 }       
3008                                 
3009                         pkey_ctx=EVP_PKEY_CTX_new(pub_key=X509_get_pubkey(peer_cert),NULL);
3010                         /* If we have send a certificate, and certificate key
3011
3012                          * parameters match those of server certificate, use
3013                          * certificate key for key exchange
3014                          */
3015
3016                          /* Otherwise, generate ephemeral key pair */
3017                                         
3018                         EVP_PKEY_encrypt_init(pkey_ctx);
3019                           /* Generate session key */    
3020                     RAND_bytes(premaster_secret,32);
3021                         /* If we have client certificate, use its secret as peer key */
3022                         if (s->s3->tmp.cert_req && s->cert->key->privatekey) {
3023                                 if (EVP_PKEY_derive_set_peer(pkey_ctx,s->cert->key->privatekey) <=0) {
3024                                         /* If there was an error - just ignore it. Ephemeral key
3025                                         * would be used
3026                                         */
3027                                         ERR_clear_error();
3028                                 }
3029                         }                       
3030                         /* Compute shared IV and store it in algorithm-specific
3031                          * context data */
3032                         ukm_hash = EVP_MD_CTX_create();
3033                         EVP_DigestInit(ukm_hash,EVP_get_digestbynid(NID_id_GostR3411_94));
3034                         EVP_DigestUpdate(ukm_hash,s->s3->client_random,SSL3_RANDOM_SIZE);
3035                         EVP_DigestUpdate(ukm_hash,s->s3->server_random,SSL3_RANDOM_SIZE);
3036                         EVP_DigestFinal_ex(ukm_hash, shared_ukm, &md_len);
3037                         EVP_MD_CTX_destroy(ukm_hash);
3038                         if (EVP_PKEY_CTX_ctrl(pkey_ctx,-1,EVP_PKEY_OP_ENCRYPT,EVP_PKEY_CTRL_SET_IV,
3039                                 8,shared_ukm)<0) {
3040                                         SSLerr(SSL_F_SSL3_SEND_CLIENT_KEY_EXCHANGE,
3041                                                 SSL_R_LIBRARY_BUG);
3042                                         goto err;
3043                                 }       
3044                         /* Make GOST keytransport blob message */
3045                         /*Encapsulate it into sequence */
3046                         *(p++)=V_ASN1_SEQUENCE | V_ASN1_CONSTRUCTED;
3047                         msglen=255;
3048                         if (EVP_PKEY_encrypt(pkey_ctx,tmp,&msglen,premaster_secret,32)<0) {
3049                         SSLerr(SSL_F_SSL3_SEND_CLIENT_KEY_EXCHANGE,
3050                                         SSL_R_LIBRARY_BUG);
3051                                 goto err;
3052                         }
3053                         if (msglen >= 0x80)
3054                                 {
3055                                 *(p++)=0x81;
3056                                 *(p++)= msglen & 0xff;
3057                                 n=msglen+3;
3058                                 }
3059                         else
3060                                 {
3061                                 *(p++)= msglen & 0xff;
3062                                 n=msglen+2;
3063                                 }
3064                         memcpy(p, tmp, msglen);
3065                         /* Check if pubkey from client certificate was used */
3066                         if (EVP_PKEY_CTX_ctrl(pkey_ctx, -1, -1, EVP_PKEY_CTRL_PEER_KEY, 2, NULL) > 0)
3067                                 {
3068                                 /* Set flag "skip certificate verify" */
3069                                 s->s3->flags |= TLS1_FLAGS_SKIP_CERT_VERIFY;
3070                                 }
3071                         EVP_PKEY_CTX_free(pkey_ctx);
3072                         s->session->master_key_length=
3073                                 s->method->ssl3_enc->generate_master_secret(s,
3074                                         s->session->master_key,premaster_secret,32);
3075                         EVP_PKEY_free(pub_key);
3076
3077                         }
3078 #ifndef OPENSSL_NO_SRP
3079                 else if (alg_k & SSL_kSRP)
3080                         {
3081                         if (s->srp_ctx.A != NULL)
3082                                 {
3083                                 /* send off the data */
3084                                 n=BN_num_bytes(s->srp_ctx.A);
3085                                 s2n(n,p);
3086                                 BN_bn2bin(s->srp_ctx.A,p);
3087                                 n+=2;
3088                                 }
3089                         else
3090                                 {
3091                                 SSLerr(SSL_F_SSL3_SEND_CLIENT_KEY_EXCHANGE,ERR_R_INTERNAL_ERROR);
3092                                 goto err;
3093                                 }
3094                         if (s->session->srp_username != NULL)
3095                                 OPENSSL_free(s->session->srp_username);
3096                         s->session->srp_username = BUF_strdup(s->srp_ctx.login);
3097                         if (s->session->srp_username == NULL)
3098                                 {
3099                                 SSLerr(SSL_F_SSL3_SEND_CLIENT_KEY_EXCHANGE,
3100                                         ERR_R_MALLOC_FAILURE);
3101                                 goto err;
3102                                 }
3103
3104                         if ((s->session->master_key_length = SRP_generate_client_master_secret(s,s->session->master_key))<0)
3105                                 {
3106                                 SSLerr(SSL_F_SSL3_SEND_CLIENT_KEY_EXCHANGE,ERR_R_INTERNAL_ERROR);
3107                                 goto err;
3108                                 }
3109                         }
3110 #endif
3111 #ifndef OPENSSL_NO_PSK
3112                 else if (alg_k & SSL_kPSK)
3113                         {
3114                         /* The callback needs PSK_MAX_IDENTITY_LEN + 1 bytes
3115                          * to return a \0-terminated identity. The last byte
3116                          * is for us for simulating strnlen. */
3117                         char identity[PSK_MAX_IDENTITY_LEN + 2];
3118                         size_t identity_len;
3119                         unsigned char *t = NULL;
3120                         unsigned char psk_or_pre_ms[PSK_MAX_PSK_LEN*2+4];
3121                         unsigned int pre_ms_len = 0, psk_len = 0;
3122                         int psk_err = 1;
3123
3124                         n = 0;
3125                         if (s->psk_client_callback == NULL)
3126                                 {
3127                                 SSLerr(SSL_F_SSL3_SEND_CLIENT_KEY_EXCHANGE,
3128                                         SSL_R_PSK_NO_CLIENT_CB);
3129                                 goto err;
3130                                 }
3131
3132                         memset(identity, 0, sizeof(identity));
3133                         psk_len = s->psk_client_callback(s, s->ctx->psk_identity_hint,
3134                                 identity, sizeof(identity) - 1,
3135                                 psk_or_pre_ms, sizeof(psk_or_pre_ms));
3136                         if (psk_len > PSK_MAX_PSK_LEN)
3137                                 {
3138                                 SSLerr(SSL_F_SSL3_SEND_CLIENT_KEY_EXCHANGE,
3139                                         ERR_R_INTERNAL_ERROR);
3140                                 goto psk_err;
3141                                 }
3142                         else if (psk_len == 0)
3143                                 {
3144                                 SSLerr(SSL_F_SSL3_SEND_CLIENT_KEY_EXCHANGE,
3145                                         SSL_R_PSK_IDENTITY_NOT_FOUND);
3146                                 goto psk_err;
3147                                 }
3148                         identity[PSK_MAX_IDENTITY_LEN + 1] = '\0';
3149                         identity_len = strlen(identity);
3150                         if (identity_len > PSK_MAX_IDENTITY_LEN)
3151                                 {
3152                                 SSLerr(SSL_F_SSL3_SEND_CLIENT_KEY_EXCHANGE,
3153                                         ERR_R_INTERNAL_ERROR);
3154                                 goto psk_err;
3155                                 }
3156                         /* create PSK pre_master_secret */
3157                         pre_ms_len = 2+psk_len+2+psk_len;
3158                         t = psk_or_pre_ms;
3159                         memmove(psk_or_pre_ms+psk_len+4, psk_or_pre_ms, psk_len);
3160                         s2n(psk_len, t);
3161                         memset(t, 0, psk_len);
3162                         t+=psk_len;
3163                         s2n(psk_len, t);
3164
3165                         if (s->session->psk_identity_hint != NULL)
3166                                 OPENSSL_free(s->session->psk_identity_hint);
3167                         s->session->psk_identity_hint = BUF_strdup(s->ctx->psk_identity_hint);
3168                         if (s->ctx->psk_identity_hint != NULL &&
3169                                 s->session->psk_identity_hint == NULL)
3170                                 {
3171                                 SSLerr(SSL_F_SSL3_SEND_CLIENT_KEY_EXCHANGE,
3172                                         ERR_R_MALLOC_FAILURE);
3173                                 goto psk_err;
3174                                 }
3175
3176                         if (s->session->psk_identity != NULL)
3177                                 OPENSSL_free(s->session->psk_identity);
3178                         s->session->psk_identity = BUF_strdup(identity);
3179                         if (s->session->psk_identity == NULL)
3180                                 {
3181                                 SSLerr(SSL_F_SSL3_SEND_CLIENT_KEY_EXCHANGE,
3182                                         ERR_R_MALLOC_FAILURE);
3183                                 goto psk_err;
3184                                 }
3185
3186                         s->session->master_key_length =
3187                                 s->method->ssl3_enc->generate_master_secret(s,
3188                                         s->session->master_key,
3189                                         psk_or_pre_ms, pre_ms_len);
3190                         s2n(identity_len, p);
3191                         memcpy(p, identity, identity_len);
3192                         n = 2 + identity_len;
3193                         psk_err = 0;
3194                 psk_err:
3195                         OPENSSL_cleanse(identity, sizeof(identity));
3196                         OPENSSL_cleanse(psk_or_pre_ms, sizeof(psk_or_pre_ms));
3197                         if (psk_err != 0)
3198                                 {
3199                                 ssl3_send_alert(s, SSL3_AL_FATAL, SSL_AD_HANDSHAKE_FAILURE);
3200                                 goto err;
3201                                 }
3202                         }
3203 #endif
3204                 else
3205                         {
3206                         ssl3_send_alert(s, SSL3_AL_FATAL,
3207                             SSL_AD_HANDSHAKE_FAILURE);
3208                         SSLerr(SSL_F_SSL3_SEND_CLIENT_KEY_EXCHANGE,
3209                             ERR_R_INTERNAL_ERROR);
3210                         goto err;
3211                         }
3212
3213                 ssl_set_handshake_header(s, SSL3_MT_CLIENT_KEY_EXCHANGE, n);
3214                 s->state=SSL3_ST_CW_KEY_EXCH_B;
3215                 }
3216
3217         /* SSL3_ST_CW_KEY_EXCH_B */
3218         return ssl_do_write(s);
3219 err:
3220 #ifndef OPENSSL_NO_ECDH
3221         BN_CTX_free(bn_ctx);
3222         if (encodedPoint != NULL) OPENSSL_free(encodedPoint);
3223         if (clnt_ecdh != NULL) 
3224                 EC_KEY_free(clnt_ecdh);
3225         EVP_PKEY_free(srvr_pub_pkey);
3226 #endif
3227         return(-1);
3228         }
3229
3230 int ssl3_send_client_verify(SSL *s)
3231         {
3232         unsigned char *p;
3233         unsigned char data[MD5_DIGEST_LENGTH+SHA_DIGEST_LENGTH];
3234         EVP_PKEY *pkey;
3235         EVP_PKEY_CTX *pctx=NULL;
3236         EVP_MD_CTX mctx;
3237         unsigned u=0;
3238         unsigned long n;
3239         int j;
3240
3241         EVP_MD_CTX_init(&mctx);
3242
3243         if (s->state == SSL3_ST_CW_CERT_VRFY_A)
3244                 {
3245                 p= ssl_handshake_start(s);
3246                 pkey=s->cert->key->privatekey;
3247 /* Create context from key and test if sha1 is allowed as digest */
3248                 pctx = EVP_PKEY_CTX_new(pkey,NULL);
3249                 EVP_PKEY_sign_init(pctx);
3250                 if (EVP_PKEY_CTX_set_signature_md(pctx, EVP_sha1())>0)
3251                         {
3252                         if (!SSL_USE_SIGALGS(s))
3253                                 s->method->ssl3_enc->cert_verify_mac(s,
3254                                                 NID_sha1,
3255                                                 &(data[MD5_DIGEST_LENGTH]));
3256                         }
3257                 else
3258                         {
3259                         ERR_clear_error();
3260                         }
3261                 /* For TLS v1.2 send signature algorithm and signature
3262                  * using agreed digest and cached handshake records.
3263                  */
3264                 if (SSL_USE_SIGALGS(s))
3265                         {
3266                         long hdatalen = 0;
3267                         void *hdata;
3268                         const EVP_MD *md = s->cert->key->digest;
3269                         hdatalen = BIO_get_mem_data(s->s3->handshake_buffer,
3270                                                                 &hdata);
3271                         if (hdatalen <= 0 || !tls12_get_sigandhash(p, pkey, md))
3272                                 {
3273                                 SSLerr(SSL_F_SSL3_SEND_CLIENT_VERIFY,
3274                                                 ERR_R_INTERNAL_ERROR);
3275                                 goto err;
3276                                 }
3277                         p += 2;
3278 #ifdef SSL_DEBUG
3279                         fprintf(stderr, "Using TLS 1.2 with client alg %s\n",
3280                                                         EVP_MD_name(md));
3281 #endif
3282                         if (!EVP_SignInit_ex(&mctx, md, NULL)
3283                                 || !EVP_SignUpdate(&mctx, hdata, hdatalen)
3284                                 || !EVP_SignFinal(&mctx, p + 2, &u, pkey))
3285                                 {
3286                                 SSLerr(SSL_F_SSL3_SEND_CLIENT_VERIFY,
3287                                                 ERR_R_EVP_LIB);
3288                                 goto err;
3289                                 }
3290                         s2n(u,p);
3291                         n = u + 4;
3292                         if (!ssl3_digest_cached_records(s))
3293                                 goto err;
3294                         }
3295                 else
3296 #ifndef OPENSSL_NO_RSA
3297                 if (pkey->type == EVP_PKEY_RSA)
3298                         {
3299                         s->method->ssl3_enc->cert_verify_mac(s,
3300                                 NID_md5,
3301                                 &(data[0]));
3302                         if (RSA_sign(NID_md5_sha1, data,
3303                                          MD5_DIGEST_LENGTH+SHA_DIGEST_LENGTH,
3304                                         &(p[2]), &u, pkey->pkey.rsa) <= 0 )
3305                                 {
3306                                 SSLerr(SSL_F_SSL3_SEND_CLIENT_VERIFY,ERR_R_RSA_LIB);
3307                                 goto err;
3308                                 }
3309                         s2n(u,p);
3310                         n=u+2;
3311                         }
3312                 else
3313 #endif
3314 #ifndef OPENSSL_NO_DSA
3315                         if (pkey->type == EVP_PKEY_DSA)
3316                         {
3317                         if (!DSA_sign(pkey->save_type,
3318                                 &(data[MD5_DIGEST_LENGTH]),
3319                                 SHA_DIGEST_LENGTH,&(p[2]),
3320                                 (unsigned int *)&j,pkey->pkey.dsa))
3321                                 {
3322                                 SSLerr(SSL_F_SSL3_SEND_CLIENT_VERIFY,ERR_R_DSA_LIB);
3323                                 goto err;
3324                                 }
3325                         s2n(j,p);
3326                         n=j+2;
3327                         }
3328                 else
3329 #endif
3330 #ifndef OPENSSL_NO_ECDSA
3331                         if (pkey->type == EVP_PKEY_EC)
3332                         {
3333                         if (!ECDSA_sign(pkey->save_type,
3334                                 &(data[MD5_DIGEST_LENGTH]),
3335                                 SHA_DIGEST_LENGTH,&(p[2]),
3336                                 (unsigned int *)&j,pkey->pkey.ec))
3337                                 {
3338                                 SSLerr(SSL_F_SSL3_SEND_CLIENT_VERIFY,
3339                                     ERR_R_ECDSA_LIB);
3340                                 goto err;
3341                                 }
3342                         s2n(j,p);
3343                         n=j+2;
3344                         }
3345                 else
3346 #endif
3347                 if (pkey->type == NID_id_GostR3410_94 || pkey->type == NID_id_GostR3410_2001) 
3348                 {
3349                 unsigned char signbuf[64];
3350                 int i;
3351                 size_t sigsize=64;
3352                 s->method->ssl3_enc->cert_verify_mac(s,
3353                         NID_id_GostR3411_94,
3354                         data);
3355                 if (EVP_PKEY_sign(pctx, signbuf, &sigsize, data, 32) <= 0) {
3356                         SSLerr(SSL_F_SSL3_SEND_CLIENT_VERIFY,
3357                         ERR_R_INTERNAL_ERROR);
3358                         goto err;
3359                 }
3360                 for (i=63,j=0; i>=0; j++, i--) {
3361                         p[2+j]=signbuf[i];
3362                 }       
3363                 s2n(j,p);
3364                 n=j+2;
3365                 }
3366                 else
3367                 {
3368                         SSLerr(SSL_F_SSL3_SEND_CLIENT_VERIFY,ERR_R_INTERNAL_ERROR);
3369                         goto err;
3370                 }
3371                 ssl_set_handshake_header(s, SSL3_MT_CERTIFICATE_VERIFY, n);
3372                 s->state=SSL3_ST_CW_CERT_VRFY_B;
3373                 }
3374         EVP_MD_CTX_cleanup(&mctx);
3375         EVP_PKEY_CTX_free(pctx);
3376         return ssl_do_write(s);
3377 err:
3378         EVP_MD_CTX_cleanup(&mctx);
3379         EVP_PKEY_CTX_free(pctx);
3380         return(-1);
3381         }
3382
3383 /* Check a certificate can be used for client authentication. Currently
3384  * check cert exists, if we have a suitable digest for TLS 1.2 if
3385  * static DH client certificates can be used and optionally checks
3386  * suitability for Suite B.
3387  */
3388 static int ssl3_check_client_certificate(SSL *s)
3389         {
3390         unsigned long alg_k;
3391         if (!s->cert || !s->cert->key->x509 || !s->cert->key->privatekey)
3392                 return 0;
3393         /* If no suitable signature algorithm can't use certificate */
3394         if (SSL_USE_SIGALGS(s) && !s->cert->key->digest)
3395                 return 0;
3396         /* If strict mode check suitability of chain before using it.
3397          * This also adjusts suite B digest if necessary.
3398          */
3399         if (s->cert->cert_flags & SSL_CERT_FLAGS_CHECK_TLS_STRICT &&
3400                 !tls1_check_chain(s, NULL, NULL, NULL, -2))
3401                 return 0;
3402         alg_k=s->s3->tmp.new_cipher->algorithm_mkey;
3403         /* See if we can use client certificate for fixed DH */
3404         if (alg_k & (SSL_kDHr|SSL_kDHd))
3405                 {
3406                 SESS_CERT *scert = s->session->sess_cert;
3407                 int i = scert->peer_cert_type;
3408                 EVP_PKEY *clkey = NULL, *spkey = NULL;
3409                 clkey = s->cert->key->privatekey;
3410                 /* If client key not DH assume it can be used */
3411                 if (EVP_PKEY_id(clkey) != EVP_PKEY_DH)
3412                         return 1;
3413                 if (i >= 0)
3414                         spkey = X509_get_pubkey(scert->peer_pkeys[i].x509);
3415                 if (spkey)
3416                         {
3417                         /* Compare server and client parameters */
3418                         i = EVP_PKEY_cmp_parameters(clkey, spkey);
3419                         EVP_PKEY_free(spkey);
3420                         if (i != 1)
3421                                 return 0;
3422                         }
3423                 s->s3->flags |= TLS1_FLAGS_SKIP_CERT_VERIFY;
3424                 }
3425         return 1;
3426         }
3427
3428 int ssl3_send_client_certificate(SSL *s)
3429         {
3430         X509 *x509=NULL;
3431         EVP_PKEY *pkey=NULL;
3432         int i;
3433
3434         if (s->state == SSL3_ST_CW_CERT_A)
3435                 {
3436                 /* Let cert callback update client certificates if required */
3437                 if (s->cert->cert_cb)
3438                         {
3439                         i = s->cert->cert_cb(s, s->cert->cert_cb_arg);
3440                         if (i < 0)
3441                                 {
3442                                 s->rwstate=SSL_X509_LOOKUP;
3443                                 return -1;
3444                                 }
3445                         if (i == 0)
3446                                 {
3447                                 ssl3_send_alert(s,SSL3_AL_FATAL,SSL_AD_INTERNAL_ERROR);
3448                                 return 0;
3449                                 }
3450                         s->rwstate=SSL_NOTHING;
3451                         }
3452                 if (ssl3_check_client_certificate(s))
3453                         s->state=SSL3_ST_CW_CERT_C;
3454                 else
3455                         s->state=SSL3_ST_CW_CERT_B;
3456                 }
3457
3458         /* We need to get a client cert */
3459         if (s->state == SSL3_ST_CW_CERT_B)
3460                 {
3461                 /* If we get an error, we need to
3462                  * ssl->rwstate=SSL_X509_LOOKUP; return(-1);
3463                  * We then get retied later */
3464                 i=0;
3465                 i = ssl_do_client_cert_cb(s, &x509, &pkey);
3466                 if (i < 0)
3467                         {
3468                         s->rwstate=SSL_X509_LOOKUP;
3469                         return(-1);
3470                         }
3471                 s->rwstate=SSL_NOTHING;
3472                 if ((i == 1) && (pkey != NULL) && (x509 != NULL))
3473                         {
3474                         s->state=SSL3_ST_CW_CERT_B;
3475                         if (    !SSL_use_certificate(s,x509) ||
3476                                 !SSL_use_PrivateKey(s,pkey))
3477                                 i=0;
3478                         }
3479                 else if (i == 1)
3480                         {
3481                         i=0;
3482                         SSLerr(SSL_F_SSL3_SEND_CLIENT_CERTIFICATE,SSL_R_BAD_DATA_RETURNED_BY_CALLBACK);
3483                         }
3484
3485                 if (x509 != NULL) X509_free(x509);
3486                 if (pkey != NULL) EVP_PKEY_free(pkey);
3487                 if (i && !ssl3_check_client_certificate(s))
3488                         i = 0;
3489                 if (i == 0)
3490                         {
3491                         if (s->version == SSL3_VERSION)
3492                                 {
3493                                 s->s3->tmp.cert_req=0;
3494                                 ssl3_send_alert(s,SSL3_AL_WARNING,SSL_AD_NO_CERTIFICATE);
3495                                 return(1);
3496                                 }
3497                         else
3498                                 {
3499                                 s->s3->tmp.cert_req=2;
3500                                 }
3501                         }
3502
3503                 /* Ok, we have a cert */
3504                 s->state=SSL3_ST_CW_CERT_C;
3505                 }
3506
3507         if (s->state == SSL3_ST_CW_CERT_C)
3508                 {
3509                 s->state=SSL3_ST_CW_CERT_D;
3510                 ssl3_output_cert_chain(s,
3511                         (s->s3->tmp.cert_req == 2)?NULL:s->cert->key);
3512                 }
3513         /* SSL3_ST_CW_CERT_D */
3514         return ssl_do_write(s);
3515         }
3516
3517 #define has_bits(i,m)   (((i)&(m)) == (m))
3518
3519 int ssl3_check_cert_and_algorithm(SSL *s)
3520         {
3521         int i,idx;
3522         long alg_k,alg_a;
3523         EVP_PKEY *pkey=NULL;
3524         SESS_CERT *sc;
3525 #ifndef OPENSSL_NO_RSA
3526         RSA *rsa;
3527 #endif
3528 #ifndef OPENSSL_NO_DH
3529         DH *dh;
3530 #endif
3531
3532         alg_k=s->s3->tmp.new_cipher->algorithm_mkey;
3533         alg_a=s->s3->tmp.new_cipher->algorithm_auth;
3534
3535         /* we don't have a certificate */
3536         if ((alg_a & (SSL_aNULL|SSL_aKRB5)) || (alg_k & SSL_kPSK))
3537                 return(1);
3538
3539         sc=s->session->sess_cert;
3540         if (sc == NULL)
3541                 {
3542                 SSLerr(SSL_F_SSL3_CHECK_CERT_AND_ALGORITHM,ERR_R_INTERNAL_ERROR);
3543                 goto err;
3544                 }
3545
3546 #ifndef OPENSSL_NO_RSA
3547         rsa=s->session->sess_cert->peer_rsa_tmp;
3548 #endif
3549 #ifndef OPENSSL_NO_DH
3550         dh=s->session->sess_cert->peer_dh_tmp;
3551 #endif
3552
3553         /* This is the passed certificate */
3554
3555         idx=sc->peer_cert_type;
3556 #ifndef OPENSSL_NO_ECDH
3557         if (idx == SSL_PKEY_ECC)
3558                 {
3559                 if (ssl_check_srvr_ecc_cert_and_alg(sc->peer_pkeys[idx].x509,
3560                                                                 s) == 0) 
3561                         { /* check failed */
3562                         SSLerr(SSL_F_SSL3_CHECK_CERT_AND_ALGORITHM,SSL_R_BAD_ECC_CERT);
3563                         goto f_err;
3564                         }
3565                 else 
3566                         {
3567                         return 1;
3568                         }
3569                 }
3570         else if (alg_a & SSL_aECDSA)
3571                 {
3572                 SSLerr(SSL_F_SSL3_CHECK_CERT_AND_ALGORITHM,SSL_R_MISSING_ECDSA_SIGNING_CERT);
3573                 goto f_err;
3574                 }
3575         else if (alg_k & (SSL_kECDHr|SSL_kECDHe))
3576                 {
3577                 SSLerr(SSL_F_SSL3_CHECK_CERT_AND_ALGORITHM,SSL_R_MISSING_ECDH_CERT);
3578                 goto f_err;
3579                 }
3580 #endif
3581         pkey=X509_get_pubkey(sc->peer_pkeys[idx].x509);
3582         i=X509_certificate_type(sc->peer_pkeys[idx].x509,pkey);
3583         EVP_PKEY_free(pkey);
3584
3585         
3586         /* Check that we have a certificate if we require one */
3587         if ((alg_a & SSL_aRSA) && !has_bits(i,EVP_PK_RSA|EVP_PKT_SIGN))
3588                 {
3589                 SSLerr(SSL_F_SSL3_CHECK_CERT_AND_ALGORITHM,SSL_R_MISSING_RSA_SIGNING_CERT);
3590                 goto f_err;
3591                 }
3592 #ifndef OPENSSL_NO_DSA
3593         else if ((alg_a & SSL_aDSS) && !has_bits(i,EVP_PK_DSA|EVP_PKT_SIGN))
3594                 {
3595                 SSLerr(SSL_F_SSL3_CHECK_CERT_AND_ALGORITHM,SSL_R_MISSING_DSA_SIGNING_CERT);
3596                 goto f_err;
3597                 }
3598 #endif
3599 #ifndef OPENSSL_NO_RSA
3600         if ((alg_k & SSL_kRSA) &&
3601                 !(has_bits(i,EVP_PK_RSA|EVP_PKT_ENC) || (rsa != NULL)))
3602                 {
3603                 SSLerr(SSL_F_SSL3_CHECK_CERT_AND_ALGORITHM,SSL_R_MISSING_RSA_ENCRYPTING_CERT);
3604                 goto f_err;
3605                 }
3606 #endif
3607 #ifndef OPENSSL_NO_DH
3608         if ((alg_k & SSL_kEDH) && 
3609                 !(has_bits(i,EVP_PK_DH|EVP_PKT_EXCH) || (dh != NULL)))
3610                 {
3611                 SSLerr(SSL_F_SSL3_CHECK_CERT_AND_ALGORITHM,SSL_R_MISSING_DH_KEY);
3612                 goto f_err;
3613                 }
3614         else if ((alg_k & SSL_kDHr) && !SSL_USE_SIGALGS(s) &&
3615                 !has_bits(i,EVP_PK_DH|EVP_PKS_RSA))
3616                 {
3617                 SSLerr(SSL_F_SSL3_CHECK_CERT_AND_ALGORITHM,SSL_R_MISSING_DH_RSA_CERT);
3618                 goto f_err;
3619                 }
3620 #ifndef OPENSSL_NO_DSA
3621         else if ((alg_k & SSL_kDHd) && !SSL_USE_SIGALGS(s) &&
3622                 !has_bits(i,EVP_PK_DH|EVP_PKS_DSA))
3623                 {
3624                 SSLerr(SSL_F_SSL3_CHECK_CERT_AND_ALGORITHM,SSL_R_MISSING_DH_DSA_CERT);
3625                 goto f_err;
3626                 }
3627 #endif
3628 #endif
3629
3630         if (SSL_C_IS_EXPORT(s->s3->tmp.new_cipher) && !has_bits(i,EVP_PKT_EXP))
3631                 {
3632 #ifndef OPENSSL_NO_RSA
3633                 if (alg_k & SSL_kRSA)
3634                         {
3635                         if (rsa == NULL
3636                             || RSA_size(rsa)*8 > SSL_C_EXPORT_PKEYLENGTH(s->s3->tmp.new_cipher))
3637                                 {
3638                                 SSLerr(SSL_F_SSL3_CHECK_CERT_AND_ALGORITHM,SSL_R_MISSING_EXPORT_TMP_RSA_KEY);
3639                                 goto f_err;
3640                                 }
3641                         }
3642                 else
3643 #endif
3644 #ifndef OPENSSL_NO_DH
3645                         if (alg_k & (SSL_kEDH|SSL_kDHr|SSL_kDHd))
3646                             {
3647                             if (dh == NULL
3648                                 || DH_size(dh)*8 > SSL_C_EXPORT_PKEYLENGTH(s->s3->tmp.new_cipher))
3649                                 {
3650                                 SSLerr(SSL_F_SSL3_CHECK_CERT_AND_ALGORITHM,SSL_R_MISSING_EXPORT_TMP_DH_KEY);
3651                                 goto f_err;
3652                                 }
3653                         }
3654                 else
3655 #endif
3656                         {
3657                         SSLerr(SSL_F_SSL3_CHECK_CERT_AND_ALGORITHM,SSL_R_UNKNOWN_KEY_EXCHANGE_TYPE);
3658                         goto f_err;
3659                         }
3660                 }
3661         return(1);
3662 f_err:
3663         ssl3_send_alert(s,SSL3_AL_FATAL,SSL_AD_HANDSHAKE_FAILURE);
3664 err:
3665         return(0);
3666         }
3667
3668 #if !defined(OPENSSL_NO_TLSEXT) && !defined(OPENSSL_NO_NEXTPROTONEG)
3669 int ssl3_send_next_proto(SSL *s)
3670         {
3671         unsigned int len, padding_len;
3672         unsigned char *d;
3673
3674         if (s->state == SSL3_ST_CW_NEXT_PROTO_A)
3675                 {
3676                 len = s->next_proto_negotiated_len;
3677                 padding_len = 32 - ((len + 2) % 32);
3678                 d = (unsigned char *)s->init_buf->data;
3679                 d[4] = len;
3680                 memcpy(d + 5, s->next_proto_negotiated, len);
3681                 d[5 + len] = padding_len;
3682                 memset(d + 6 + len, 0, padding_len);
3683                 *(d++)=SSL3_MT_NEXT_PROTO;
3684                 l2n3(2 + len + padding_len, d);
3685                 s->state = SSL3_ST_CW_NEXT_PROTO_B;
3686                 s->init_num = 4 + 2 + len + padding_len;
3687                 s->init_off = 0;
3688                 }
3689
3690         return ssl3_do_write(s, SSL3_RT_HANDSHAKE);
3691 }
3692 #endif  /* !OPENSSL_NO_TLSEXT && !OPENSSL_NO_NEXTPROTONEG */
3693
3694 /* Check to see if handshake is full or resumed. Usually this is just a
3695  * case of checking to see if a cache hit has occurred. In the case of
3696  * session tickets we have to check the next message to be sure.
3697  */
3698
3699 #ifndef OPENSSL_NO_TLSEXT
3700 int ssl3_check_finished(SSL *s)
3701         {
3702         int ok;
3703         long n;
3704
3705         /* If we have no ticket it cannot be a resumed session. */
3706         if (!s->session->tlsext_tick)
3707                 return 1;
3708         /* this function is called when we really expect a Certificate
3709          * message, so permit appropriate message length */
3710         n=s->method->ssl_get_message(s,
3711                 SSL3_ST_CR_CERT_A,
3712                 SSL3_ST_CR_CERT_B,
3713                 -1,
3714                 s->max_cert_list,
3715                 &ok);
3716         if (!ok) return((int)n);
3717         s->s3->tmp.reuse_message = 1;
3718
3719         if ((s->s3->tmp.message_type == SSL3_MT_FINISHED)
3720                 || (s->s3->tmp.message_type == SSL3_MT_NEWSESSION_TICKET))
3721                 return 2;
3722
3723         return 1;
3724         }
3725 #endif
3726
3727 int ssl_do_client_cert_cb(SSL *s, X509 **px509, EVP_PKEY **ppkey)
3728         {
3729         int i = 0;
3730 #ifndef OPENSSL_NO_ENGINE
3731         if (s->ctx->client_cert_engine)
3732                 {
3733                 i = ENGINE_load_ssl_client_cert(s->ctx->client_cert_engine, s,
3734                                                 SSL_get_client_CA_list(s),
3735                                                 px509, ppkey, NULL, NULL, NULL);
3736                 if (i != 0)
3737                         return i;
3738                 }
3739 #endif
3740         if (s->ctx->client_cert_cb)
3741                 i = s->ctx->client_cert_cb(s,px509,ppkey);
3742         return i;
3743         }
3744