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