b7d8d4213b80828f8f739f490b317d826faa9225
[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 #ifndef OPENSSL_NO_DH
160 #include <openssl/dh.h>
161 #endif
162 #include <openssl/bn.h>
163
164 static const SSL_METHOD *ssl3_get_client_method(int ver);
165 static int ca_dn_cmp(const X509_NAME * const *a,const X509_NAME * const *b);
166 #ifndef OPENSSL_NO_TLSEXT
167 static int ssl3_check_finished(SSL *s);
168 #endif
169
170 static const SSL_METHOD *ssl3_get_client_method(int ver)
171         {
172         if (ver == SSL3_VERSION)
173                 return(SSLv3_client_method());
174         else
175                 return(NULL);
176         }
177
178 IMPLEMENT_ssl3_meth_func(SSLv3_client_method,
179                         ssl_undefined_function,
180                         ssl3_connect,
181                         ssl3_get_client_method)
182
183 int ssl3_connect(SSL *s)
184         {
185         BUF_MEM *buf=NULL;
186         unsigned long Time=(unsigned long)time(NULL);
187         long num1;
188         void (*cb)(const SSL *ssl,int type,int val)=NULL;
189         int ret= -1;
190         int new_state,state,skip=0;;
191
192         RAND_add(&Time,sizeof(Time),0);
193         ERR_clear_error();
194         clear_sys_error();
195
196         if (s->info_callback != NULL)
197                 cb=s->info_callback;
198         else if (s->ctx->info_callback != NULL)
199                 cb=s->ctx->info_callback;
200         
201         s->in_handshake++;
202         if (!SSL_in_init(s) || SSL_in_before(s)) SSL_clear(s); 
203
204         for (;;)
205                 {
206                 state=s->state;
207
208                 switch(s->state)
209                         {
210                 case SSL_ST_RENEGOTIATE:
211                         s->new_session=1;
212                         s->state=SSL_ST_CONNECT;
213                         s->ctx->stats.sess_connect_renegotiate++;
214                         /* break */
215                 case SSL_ST_BEFORE:
216                 case SSL_ST_CONNECT:
217                 case SSL_ST_BEFORE|SSL_ST_CONNECT:
218                 case SSL_ST_OK|SSL_ST_CONNECT:
219
220                         s->server=0;
221                         if (cb != NULL) cb(s,SSL_CB_HANDSHAKE_START,1);
222
223                         if ((s->version & 0xff00 ) != 0x0300)
224                                 {
225                                 SSLerr(SSL_F_SSL3_CONNECT, ERR_R_INTERNAL_ERROR);
226                                 ret = -1;
227                                 goto end;
228                                 }
229                                 
230                         /* s->version=SSL3_VERSION; */
231                         s->type=SSL_ST_CONNECT;
232
233                         if (s->init_buf == NULL)
234                                 {
235                                 if ((buf=BUF_MEM_new()) == NULL)
236                                         {
237                                         ret= -1;
238                                         goto end;
239                                         }
240                                 if (!BUF_MEM_grow(buf,SSL3_RT_MAX_PLAIN_LENGTH))
241                                         {
242                                         ret= -1;
243                                         goto end;
244                                         }
245                                 s->init_buf=buf;
246                                 buf=NULL;
247                                 }
248
249                         if (!ssl3_setup_buffers(s)) { ret= -1; goto end; }
250
251                         /* setup buffing BIO */
252                         if (!ssl_init_wbio_buffer(s,0)) { ret= -1; goto end; }
253
254                         /* don't push the buffering BIO quite yet */
255
256                         ssl3_init_finished_mac(s);
257
258                         s->state=SSL3_ST_CW_CLNT_HELLO_A;
259                         s->ctx->stats.sess_connect++;
260                         s->init_num=0;
261                         break;
262
263                 case SSL3_ST_CW_CLNT_HELLO_A:
264                 case SSL3_ST_CW_CLNT_HELLO_B:
265
266                         s->shutdown=0;
267                         ret=ssl3_client_hello(s);
268                         if (ret <= 0) goto end;
269                         s->state=SSL3_ST_CR_SRVR_HELLO_A;
270                         s->init_num=0;
271
272                         /* turn on buffering for the next lot of output */
273                         if (s->bbio != s->wbio)
274                                 s->wbio=BIO_push(s->bbio,s->wbio);
275
276                         break;
277
278                 case SSL3_ST_CR_SRVR_HELLO_A:
279                 case SSL3_ST_CR_SRVR_HELLO_B:
280                         ret=ssl3_get_server_hello(s);
281                         if (ret <= 0) goto end;
282
283                         if (s->hit)
284                                 s->state=SSL3_ST_CR_FINISHED_A;
285                         else
286                                 s->state=SSL3_ST_CR_CERT_A;
287                         s->init_num=0;
288                         break;
289
290                 case SSL3_ST_CR_CERT_A:
291                 case SSL3_ST_CR_CERT_B:
292 #ifndef OPENSSL_NO_TLSEXT
293                         ret=ssl3_check_finished(s);
294                         if (ret <= 0) goto end;
295                         if (ret == 2)
296                                 {
297                                 s->hit = 1;
298                                 s->state=SSL3_ST_CR_FINISHED_A;
299                                 s->init_num=0;
300                                 break;
301                                 }
302 #endif
303                         /* Check if it is anon DH/ECDH */
304                         /* or PSK */
305                         if (!(s->s3->tmp.new_cipher->algorithm_auth & SSL_aNULL) &&
306                             !(s->s3->tmp.new_cipher->algorithm_mkey & SSL_kPSK))
307                                 {
308                                 ret=ssl3_get_server_certificate(s);
309                                 if (ret <= 0) goto end;
310 #ifndef OPENSSL_NO_TLSEXT
311                                 if (s->tlsext_status_expected)
312                                         s->state=SSL3_ST_CR_CERT_STATUS_A;
313                                 else
314                                         s->state=SSL3_ST_CR_KEY_EXCH_A;
315                                 }
316                         else
317                                 {
318                                 skip = 1;
319                                 s->state=SSL3_ST_CR_KEY_EXCH_A;
320                                 }
321 #else
322                         else
323                                 skip=1;
324
325                         s->state=SSL3_ST_CR_KEY_EXCH_A;
326 #endif
327                         s->init_num=0;
328                         break;
329
330                 case SSL3_ST_CR_KEY_EXCH_A:
331                 case SSL3_ST_CR_KEY_EXCH_B:
332                         ret=ssl3_get_key_exchange(s);
333                         if (ret <= 0) goto end;
334                         s->state=SSL3_ST_CR_CERT_REQ_A;
335                         s->init_num=0;
336
337                         /* at this point we check that we have the
338                          * required stuff from the server */
339                         if (!ssl3_check_cert_and_algorithm(s))
340                                 {
341                                 ret= -1;
342                                 goto end;
343                                 }
344                         break;
345
346                 case SSL3_ST_CR_CERT_REQ_A:
347                 case SSL3_ST_CR_CERT_REQ_B:
348                         ret=ssl3_get_certificate_request(s);
349                         if (ret <= 0) goto end;
350                         s->state=SSL3_ST_CR_SRVR_DONE_A;
351                         s->init_num=0;
352                         break;
353
354                 case SSL3_ST_CR_SRVR_DONE_A:
355                 case SSL3_ST_CR_SRVR_DONE_B:
356                         ret=ssl3_get_server_done(s);
357                         if (ret <= 0) goto end;
358                         if (s->s3->tmp.cert_req)
359                                 s->state=SSL3_ST_CW_CERT_A;
360                         else
361                                 s->state=SSL3_ST_CW_KEY_EXCH_A;
362                         s->init_num=0;
363
364                         break;
365
366                 case SSL3_ST_CW_CERT_A:
367                 case SSL3_ST_CW_CERT_B:
368                 case SSL3_ST_CW_CERT_C:
369                 case SSL3_ST_CW_CERT_D:
370                         ret=ssl3_send_client_certificate(s);
371                         if (ret <= 0) goto end;
372                         s->state=SSL3_ST_CW_KEY_EXCH_A;
373                         s->init_num=0;
374                         break;
375
376                 case SSL3_ST_CW_KEY_EXCH_A:
377                 case SSL3_ST_CW_KEY_EXCH_B:
378                         ret=ssl3_send_client_key_exchange(s);
379                         if (ret <= 0) goto end;
380                         /* EAY EAY EAY need to check for DH fix cert
381                          * sent back */
382                         /* For TLS, cert_req is set to 2, so a cert chain
383                          * of nothing is sent, but no verify packet is sent */
384                         /* XXX: For now, we do not support client 
385                          * authentication in ECDH cipher suites with
386                          * ECDH (rather than ECDSA) certificates.
387                          * We need to skip the certificate verify 
388                          * message when client's ECDH public key is sent 
389                          * inside the client certificate.
390                          */
391                         if (s->s3->tmp.cert_req == 1)
392                                 {
393                                 s->state=SSL3_ST_CW_CERT_VRFY_A;
394                                 }
395                         else
396                                 {
397                                 s->state=SSL3_ST_CW_CHANGE_A;
398                                 s->s3->change_cipher_spec=0;
399                                 }
400
401                         s->init_num=0;
402                         break;
403
404                 case SSL3_ST_CW_CERT_VRFY_A:
405                 case SSL3_ST_CW_CERT_VRFY_B:
406                         ret=ssl3_send_client_verify(s);
407                         if (ret <= 0) goto end;
408                         s->state=SSL3_ST_CW_CHANGE_A;
409                         s->init_num=0;
410                         s->s3->change_cipher_spec=0;
411                         break;
412
413                 case SSL3_ST_CW_CHANGE_A:
414                 case SSL3_ST_CW_CHANGE_B:
415                         ret=ssl3_send_change_cipher_spec(s,
416                                 SSL3_ST_CW_CHANGE_A,SSL3_ST_CW_CHANGE_B);
417                         if (ret <= 0) goto end;
418                         s->state=SSL3_ST_CW_FINISHED_A;
419                         s->init_num=0;
420
421                         s->session->cipher=s->s3->tmp.new_cipher;
422 #ifdef OPENSSL_NO_COMP
423                         s->session->compress_meth=0;
424 #else
425                         if (s->s3->tmp.new_compression == NULL)
426                                 s->session->compress_meth=0;
427                         else
428                                 s->session->compress_meth=
429                                         s->s3->tmp.new_compression->id;
430 #endif
431                         if (!s->method->ssl3_enc->setup_key_block(s))
432                                 {
433                                 ret= -1;
434                                 goto end;
435                                 }
436
437                         if (!s->method->ssl3_enc->change_cipher_state(s,
438                                 SSL3_CHANGE_CIPHER_CLIENT_WRITE))
439                                 {
440                                 ret= -1;
441                                 goto end;
442                                 }
443
444                         break;
445
446                 case SSL3_ST_CW_FINISHED_A:
447                 case SSL3_ST_CW_FINISHED_B:
448                         ret=ssl3_send_finished(s,
449                                 SSL3_ST_CW_FINISHED_A,SSL3_ST_CW_FINISHED_B,
450                                 s->method->ssl3_enc->client_finished_label,
451                                 s->method->ssl3_enc->client_finished_label_len);
452                         if (ret <= 0) goto end;
453                         s->state=SSL3_ST_CW_FLUSH;
454
455                         /* clear flags */
456                         s->s3->flags&= ~SSL3_FLAGS_POP_BUFFER;
457                         if (s->hit)
458                                 {
459                                 s->s3->tmp.next_state=SSL_ST_OK;
460                                 if (s->s3->flags & SSL3_FLAGS_DELAY_CLIENT_FINISHED)
461                                         {
462                                         s->state=SSL_ST_OK;
463                                         s->s3->flags|=SSL3_FLAGS_POP_BUFFER;
464                                         s->s3->delay_buf_pop_ret=0;
465                                         }
466                                 }
467                         else
468                                 {
469 #ifndef OPENSSL_NO_TLSEXT
470                                 /* Allow NewSessionTicket if ticket expected */
471                                 if (s->tlsext_ticket_expected)
472                                         s->s3->tmp.next_state=SSL3_ST_CR_SESSION_TICKET_A;
473                                 else
474 #endif
475                                 
476                                 s->s3->tmp.next_state=SSL3_ST_CR_FINISHED_A;
477                                 }
478                         s->init_num=0;
479                         break;
480
481 #ifndef OPENSSL_NO_TLSEXT
482                 case SSL3_ST_CR_SESSION_TICKET_A:
483                 case SSL3_ST_CR_SESSION_TICKET_B:
484                         ret=ssl3_get_new_session_ticket(s);
485                         if (ret <= 0) goto end;
486                         s->state=SSL3_ST_CR_FINISHED_A;
487                         s->init_num=0;
488                 break;
489
490                 case SSL3_ST_CR_CERT_STATUS_A:
491                 case SSL3_ST_CR_CERT_STATUS_B:
492                         ret=ssl3_get_cert_status(s);
493                         if (ret <= 0) goto end;
494                         s->state=SSL3_ST_CR_KEY_EXCH_A;
495                         s->init_num=0;
496                 break;
497 #endif
498
499                 case SSL3_ST_CR_FINISHED_A:
500                 case SSL3_ST_CR_FINISHED_B:
501
502                         ret=ssl3_get_finished(s,SSL3_ST_CR_FINISHED_A,
503                                 SSL3_ST_CR_FINISHED_B);
504                         if (ret <= 0) goto end;
505
506                         if (s->hit)
507                                 s->state=SSL3_ST_CW_CHANGE_A;
508                         else
509                                 s->state=SSL_ST_OK;
510                         s->init_num=0;
511                         break;
512
513                 case SSL3_ST_CW_FLUSH:
514                         /* number of bytes to be flushed */
515                         num1=BIO_ctrl(s->wbio,BIO_CTRL_INFO,0,NULL);
516                         if (num1 > 0)
517                                 {
518                                 s->rwstate=SSL_WRITING;
519                                 num1=BIO_flush(s->wbio);
520                                 if (num1 <= 0) { ret= -1; goto end; }
521                                 s->rwstate=SSL_NOTHING;
522                                 }
523
524                         s->state=s->s3->tmp.next_state;
525                         break;
526
527                 case SSL_ST_OK:
528                         /* clean a few things up */
529                         ssl3_cleanup_key_block(s);
530
531                         if (s->init_buf != NULL)
532                                 {
533                                 BUF_MEM_free(s->init_buf);
534                                 s->init_buf=NULL;
535                                 }
536
537                         /* If we are not 'joining' the last two packets,
538                          * remove the buffering now */
539                         if (!(s->s3->flags & SSL3_FLAGS_POP_BUFFER))
540                                 ssl_free_wbio_buffer(s);
541                         /* else do it later in ssl3_write */
542
543                         s->init_num=0;
544                         s->new_session=0;
545
546                         ssl_update_cache(s,SSL_SESS_CACHE_CLIENT);
547                         if (s->hit) s->ctx->stats.sess_hit++;
548
549                         ret=1;
550                         /* s->server=0; */
551                         s->handshake_func=ssl3_connect;
552                         s->ctx->stats.sess_connect_good++;
553
554                         if (cb != NULL) cb(s,SSL_CB_HANDSHAKE_DONE,1);
555
556                         goto end;
557                         /* break; */
558                         
559                 default:
560                         SSLerr(SSL_F_SSL3_CONNECT,SSL_R_UNKNOWN_STATE);
561                         ret= -1;
562                         goto end;
563                         /* break; */
564                         }
565
566                 /* did we do anything */
567                 if (!s->s3->tmp.reuse_message && !skip)
568                         {
569                         if (s->debug)
570                                 {
571                                 if ((ret=BIO_flush(s->wbio)) <= 0)
572                                         goto end;
573                                 }
574
575                         if ((cb != NULL) && (s->state != state))
576                                 {
577                                 new_state=s->state;
578                                 s->state=state;
579                                 cb(s,SSL_CB_CONNECT_LOOP,1);
580                                 s->state=new_state;
581                                 }
582                         }
583                 skip=0;
584                 }
585 end:
586         s->in_handshake--;
587         if (buf != NULL)
588                 BUF_MEM_free(buf);
589         if (cb != NULL)
590                 cb(s,SSL_CB_CONNECT_EXIT,ret);
591         return(ret);
592         }
593
594
595 int ssl3_client_hello(SSL *s)
596         {
597         unsigned char *buf;
598         unsigned char *p,*d;
599         int i;
600         unsigned long Time,l;
601 #ifndef OPENSSL_NO_COMP
602         int j;
603         SSL_COMP *comp;
604 #endif
605
606         buf=(unsigned char *)s->init_buf->data;
607         if (s->state == SSL3_ST_CW_CLNT_HELLO_A)
608                 {
609                 if ((s->session == NULL) ||
610                         (s->session->ssl_version != s->version) ||
611                         (s->session->not_resumable))
612                         {
613                         if (!ssl_get_new_session(s,0))
614                                 goto err;
615                         }
616                 /* else use the pre-loaded session */
617
618                 p=s->s3->client_random;
619                 Time=(unsigned long)time(NULL);                 /* Time */
620                 l2n(Time,p);
621                 if (RAND_pseudo_bytes(p,SSL3_RANDOM_SIZE-4) <= 0)
622                         goto err;
623
624                 /* Do the message type and length last */
625                 d=p= &(buf[4]);
626
627                 *(p++)=s->version>>8;
628                 *(p++)=s->version&0xff;
629                 s->client_version=s->version;
630
631                 /* Random stuff */
632                 memcpy(p,s->s3->client_random,SSL3_RANDOM_SIZE);
633                 p+=SSL3_RANDOM_SIZE;
634
635                 /* Session ID */
636                 if (s->new_session)
637                         i=0;
638                 else
639                         i=s->session->session_id_length;
640                 *(p++)=i;
641                 if (i != 0)
642                         {
643                         if (i > (int)sizeof(s->session->session_id))
644                                 {
645                                 SSLerr(SSL_F_SSL3_CLIENT_HELLO, ERR_R_INTERNAL_ERROR);
646                                 goto err;
647                                 }
648                         memcpy(p,s->session->session_id,i);
649                         p+=i;
650                         }
651                 
652                 /* Ciphers supported */
653                 i=ssl_cipher_list_to_bytes(s,SSL_get_ciphers(s),&(p[2]),0);
654                 if (i == 0)
655                         {
656                         SSLerr(SSL_F_SSL3_CLIENT_HELLO,SSL_R_NO_CIPHERS_AVAILABLE);
657                         goto err;
658                         }
659                 s2n(i,p);
660                 p+=i;
661
662                 /* COMPRESSION */
663 #ifdef OPENSSL_NO_COMP
664                 *(p++)=1;
665 #else
666
667                 if ((s->options & SSL_OP_NO_COMPRESSION)
668                                         || !s->ctx->comp_methods)
669                         j=0;
670                 else
671                         j=sk_SSL_COMP_num(s->ctx->comp_methods);
672                 *(p++)=1+j;
673                 for (i=0; i<j; i++)
674                         {
675                         comp=sk_SSL_COMP_value(s->ctx->comp_methods,i);
676                         *(p++)=comp->id;
677                         }
678 #endif
679                 *(p++)=0; /* Add the NULL method */
680
681 #ifndef OPENSSL_NO_TLSEXT
682                 /* TLS extensions*/
683                 if (ssl_prepare_clienthello_tlsext(s) <= 0)
684                         {
685                         SSLerr(SSL_F_SSL3_CLIENT_HELLO,SSL_R_CLIENTHELLO_TLSEXT);
686                         goto err;
687                         }
688                 if ((p = ssl_add_clienthello_tlsext(s, p, buf+SSL3_RT_MAX_PLAIN_LENGTH)) == NULL)
689                         {
690                         SSLerr(SSL_F_SSL3_CLIENT_HELLO,ERR_R_INTERNAL_ERROR);
691                         goto err;
692                         }
693 #endif
694                 
695                 l=(p-d);
696                 d=buf;
697                 *(d++)=SSL3_MT_CLIENT_HELLO;
698                 l2n3(l,d);
699
700                 s->state=SSL3_ST_CW_CLNT_HELLO_B;
701                 /* number of bytes to write */
702                 s->init_num=p-buf;
703                 s->init_off=0;
704                 }
705
706         /* SSL3_ST_CW_CLNT_HELLO_B */
707         return(ssl3_do_write(s,SSL3_RT_HANDSHAKE));
708 err:
709         return(-1);
710         }
711
712 int ssl3_get_server_hello(SSL *s)
713         {
714         STACK_OF(SSL_CIPHER) *sk;
715         SSL_CIPHER *c;
716         unsigned char *p,*d;
717         int i,al,ok;
718         unsigned int j;
719         long n;
720 #ifndef OPENSSL_NO_COMP
721         SSL_COMP *comp;
722 #endif
723
724         n=s->method->ssl_get_message(s,
725                 SSL3_ST_CR_SRVR_HELLO_A,
726                 SSL3_ST_CR_SRVR_HELLO_B,
727                 -1,
728                 20000, /* ?? */
729                 &ok);
730
731         if (!ok) return((int)n);
732
733         if ( SSL_version(s) == DTLS1_VERSION)
734                 {
735                 if ( s->s3->tmp.message_type == DTLS1_MT_HELLO_VERIFY_REQUEST)
736                         {
737                         if ( s->d1->send_cookie == 0)
738                                 {
739                                 s->s3->tmp.reuse_message = 1;
740                                 return 1;
741                                 }
742                         else /* already sent a cookie */
743                                 {
744                                 al=SSL_AD_UNEXPECTED_MESSAGE;
745                                 SSLerr(SSL_F_SSL3_GET_SERVER_HELLO,SSL_R_BAD_MESSAGE_TYPE);
746                                 goto f_err;
747                                 }
748                         }
749                 }
750         
751         if ( s->s3->tmp.message_type != SSL3_MT_SERVER_HELLO)
752                 {
753                 al=SSL_AD_UNEXPECTED_MESSAGE;
754                 SSLerr(SSL_F_SSL3_GET_SERVER_HELLO,SSL_R_BAD_MESSAGE_TYPE);
755                 goto f_err;
756                 }
757
758         d=p=(unsigned char *)s->init_msg;
759
760         if ((p[0] != (s->version>>8)) || (p[1] != (s->version&0xff)))
761                 {
762                 SSLerr(SSL_F_SSL3_GET_SERVER_HELLO,SSL_R_WRONG_SSL_VERSION);
763                 s->version=(s->version&0xff00)|p[1];
764                 al=SSL_AD_PROTOCOL_VERSION;
765                 goto f_err;
766                 }
767         p+=2;
768
769         /* load the server hello data */
770         /* load the server random */
771         memcpy(s->s3->server_random,p,SSL3_RANDOM_SIZE);
772         p+=SSL3_RANDOM_SIZE;
773
774         /* get the session-id */
775         j= *(p++);
776
777         if ((j > sizeof s->session->session_id) || (j > SSL3_SESSION_ID_SIZE))
778                 {
779                 al=SSL_AD_ILLEGAL_PARAMETER;
780                 SSLerr(SSL_F_SSL3_GET_SERVER_HELLO,SSL_R_SSL3_SESSION_ID_TOO_LONG);
781                 goto f_err;
782                 }
783
784         if (j != 0 && j == s->session->session_id_length
785             && memcmp(p,s->session->session_id,j) == 0)
786             {
787             if(s->sid_ctx_length != s->session->sid_ctx_length
788                || memcmp(s->session->sid_ctx,s->sid_ctx,s->sid_ctx_length))
789                 {
790                 /* actually a client application bug */
791                 al=SSL_AD_ILLEGAL_PARAMETER;
792                 SSLerr(SSL_F_SSL3_GET_SERVER_HELLO,SSL_R_ATTEMPT_TO_REUSE_SESSION_IN_DIFFERENT_CONTEXT);
793                 goto f_err;
794                 }
795             s->hit=1;
796             }
797         else    /* a miss or crap from the other end */
798                 {
799                 /* If we were trying for session-id reuse, make a new
800                  * SSL_SESSION so we don't stuff up other people */
801                 s->hit=0;
802                 if (s->session->session_id_length > 0)
803                         {
804                         if (!ssl_get_new_session(s,0))
805                                 {
806                                 al=SSL_AD_INTERNAL_ERROR;
807                                 goto f_err;
808                                 }
809                         }
810                 s->session->session_id_length=j;
811                 memcpy(s->session->session_id,p,j); /* j could be 0 */
812                 }
813         p+=j;
814         c=ssl_get_cipher_by_char(s,p);
815         if (c == NULL)
816                 {
817                 /* unknown cipher */
818                 al=SSL_AD_ILLEGAL_PARAMETER;
819                 SSLerr(SSL_F_SSL3_GET_SERVER_HELLO,SSL_R_UNKNOWN_CIPHER_RETURNED);
820                 goto f_err;
821                 }
822         p+=ssl_put_cipher_by_char(s,NULL,NULL);
823
824         sk=ssl_get_ciphers_by_id(s);
825         i=sk_SSL_CIPHER_find(sk,c);
826         if (i < 0)
827                 {
828                 /* we did not say we would use this cipher */
829                 al=SSL_AD_ILLEGAL_PARAMETER;
830                 SSLerr(SSL_F_SSL3_GET_SERVER_HELLO,SSL_R_WRONG_CIPHER_RETURNED);
831                 goto f_err;
832                 }
833
834         /* Depending on the session caching (internal/external), the cipher
835            and/or cipher_id values may not be set. Make sure that
836            cipher_id is set and use it for comparison. */
837         if (s->session->cipher)
838                 s->session->cipher_id = s->session->cipher->id;
839         if (s->hit && (s->session->cipher_id != c->id))
840                 {
841                 if (!(s->options &
842                         SSL_OP_NETSCAPE_REUSE_CIPHER_CHANGE_BUG))
843                         {
844                         al=SSL_AD_ILLEGAL_PARAMETER;
845                         SSLerr(SSL_F_SSL3_GET_SERVER_HELLO,SSL_R_OLD_SESSION_CIPHER_NOT_RETURNED);
846                         goto f_err;
847                         }
848                 }
849         s->s3->tmp.new_cipher=c;
850         ssl3_digest_cached_records(s);
851
852         /* lets get the compression algorithm */
853         /* COMPRESSION */
854 #ifdef OPENSSL_NO_COMP
855         if (*(p++) != 0)
856                 {
857                 al=SSL_AD_ILLEGAL_PARAMETER;
858                 SSLerr(SSL_F_SSL3_GET_SERVER_HELLO,SSL_R_UNSUPPORTED_COMPRESSION_ALGORITHM);
859                 goto f_err;
860                 }
861 #else
862         j= *(p++);
863         if ((j == 0) || (s->options & SSL_OP_NO_COMPRESSION))
864                 comp=NULL;
865         else
866                 comp=ssl3_comp_find(s->ctx->comp_methods,j);
867         
868         if ((j != 0) && (comp == NULL))
869                 {
870                 al=SSL_AD_ILLEGAL_PARAMETER;
871                 SSLerr(SSL_F_SSL3_GET_SERVER_HELLO,SSL_R_UNSUPPORTED_COMPRESSION_ALGORITHM);
872                 goto f_err;
873                 }
874         else
875                 {
876                 s->s3->tmp.new_compression=comp;
877                 }
878 #endif
879
880 #ifndef OPENSSL_NO_TLSEXT
881         /* TLS extensions*/
882         if (s->version > SSL3_VERSION)
883                 {
884                 if (!ssl_parse_serverhello_tlsext(s,&p,d,n, &al))
885                         {
886                         /* 'al' set by ssl_parse_serverhello_tlsext */
887                         SSLerr(SSL_F_SSL3_GET_SERVER_HELLO,SSL_R_PARSE_TLSEXT);
888                         goto f_err; 
889                         }
890                 if (ssl_check_serverhello_tlsext(s) <= 0)
891                         {
892                         SSLerr(SSL_F_SSL3_GET_SERVER_HELLO,SSL_R_SERVERHELLO_TLSEXT);
893                                 goto err;
894                         }
895                 }
896 #endif
897
898         if (p != (d+n))
899                 {
900                 /* wrong packet length */
901                 al=SSL_AD_DECODE_ERROR;
902                 SSLerr(SSL_F_SSL3_GET_SERVER_HELLO,SSL_R_BAD_PACKET_LENGTH);
903                 goto err;
904                 }
905
906         return(1);
907 f_err:
908         ssl3_send_alert(s,SSL3_AL_FATAL,al);
909 err:
910         return(-1);
911         }
912
913 int ssl3_get_server_certificate(SSL *s)
914         {
915         int al,i,ok,ret= -1;
916         unsigned long n,nc,llen,l;
917         X509 *x=NULL;
918         const unsigned char *q,*p;
919         unsigned char *d;
920         STACK_OF(X509) *sk=NULL;
921         SESS_CERT *sc;
922         EVP_PKEY *pkey=NULL;
923         int need_cert = 1; /* VRS: 0=> will allow null cert if auth == KRB5 */
924
925         n=s->method->ssl_get_message(s,
926                 SSL3_ST_CR_CERT_A,
927                 SSL3_ST_CR_CERT_B,
928                 -1,
929                 s->max_cert_list,
930                 &ok);
931
932         if (!ok) return((int)n);
933
934         if (s->s3->tmp.message_type == SSL3_MT_SERVER_KEY_EXCHANGE)
935                 {
936                 s->s3->tmp.reuse_message=1;
937                 return(1);
938                 }
939
940         if (s->s3->tmp.message_type != SSL3_MT_CERTIFICATE)
941                 {
942                 al=SSL_AD_UNEXPECTED_MESSAGE;
943                 SSLerr(SSL_F_SSL3_GET_SERVER_CERTIFICATE,SSL_R_BAD_MESSAGE_TYPE);
944                 goto f_err;
945                 }
946         p=d=(unsigned char *)s->init_msg;
947
948         if ((sk=sk_X509_new_null()) == NULL)
949                 {
950                 SSLerr(SSL_F_SSL3_GET_SERVER_CERTIFICATE,ERR_R_MALLOC_FAILURE);
951                 goto err;
952                 }
953
954         n2l3(p,llen);
955         if (llen+3 != n)
956                 {
957                 al=SSL_AD_DECODE_ERROR;
958                 SSLerr(SSL_F_SSL3_GET_SERVER_CERTIFICATE,SSL_R_LENGTH_MISMATCH);
959                 goto f_err;
960                 }
961         for (nc=0; nc<llen; )
962                 {
963                 n2l3(p,l);
964                 if ((l+nc+3) > llen)
965                         {
966                         al=SSL_AD_DECODE_ERROR;
967                         SSLerr(SSL_F_SSL3_GET_SERVER_CERTIFICATE,SSL_R_CERT_LENGTH_MISMATCH);
968                         goto f_err;
969                         }
970
971                 q=p;
972                 x=d2i_X509(NULL,&q,l);
973                 if (x == NULL)
974                         {
975                         al=SSL_AD_BAD_CERTIFICATE;
976                         SSLerr(SSL_F_SSL3_GET_SERVER_CERTIFICATE,ERR_R_ASN1_LIB);
977                         goto f_err;
978                         }
979                 if (q != (p+l))
980                         {
981                         al=SSL_AD_DECODE_ERROR;
982                         SSLerr(SSL_F_SSL3_GET_SERVER_CERTIFICATE,SSL_R_CERT_LENGTH_MISMATCH);
983                         goto f_err;
984                         }
985                 if (!sk_X509_push(sk,x))
986                         {
987                         SSLerr(SSL_F_SSL3_GET_SERVER_CERTIFICATE,ERR_R_MALLOC_FAILURE);
988                         goto err;
989                         }
990                 x=NULL;
991                 nc+=l+3;
992                 p=q;
993                 }
994
995         i=ssl_verify_cert_chain(s,sk);
996         if ((s->verify_mode != SSL_VERIFY_NONE) && (!i)
997 #ifndef OPENSSL_NO_KRB5
998             && !((s->s3->tmp.new_cipher->algorithm_mkey & SSL_kKRB5) &&
999                  (s->s3->tmp.new_cipher->algorithm_auth & SSL_aKRB5))
1000 #endif /* OPENSSL_NO_KRB5 */
1001                 )
1002                 {
1003                 al=ssl_verify_alarm_type(s->verify_result);
1004                 SSLerr(SSL_F_SSL3_GET_SERVER_CERTIFICATE,SSL_R_CERTIFICATE_VERIFY_FAILED);
1005                 goto f_err; 
1006                 }
1007         ERR_clear_error(); /* but we keep s->verify_result */
1008
1009         sc=ssl_sess_cert_new();
1010         if (sc == NULL) goto err;
1011
1012         if (s->session->sess_cert) ssl_sess_cert_free(s->session->sess_cert);
1013         s->session->sess_cert=sc;
1014
1015         sc->cert_chain=sk;
1016         /* Inconsistency alert: cert_chain does include the peer's
1017          * certificate, which we don't include in s3_srvr.c */
1018         x=sk_X509_value(sk,0);
1019         sk=NULL;
1020         /* VRS 19990621: possible memory leak; sk=null ==> !sk_pop_free() @end*/
1021
1022         pkey=X509_get_pubkey(x);
1023
1024         /* VRS: allow null cert if auth == KRB5 */
1025         need_cert = ((s->s3->tmp.new_cipher->algorithm_mkey & SSL_kKRB5) &&
1026                     (s->s3->tmp.new_cipher->algorithm_auth & SSL_aKRB5))
1027                     ? 0 : 1;
1028
1029 #ifdef KSSL_DEBUG
1030         printf("pkey,x = %p, %p\n", pkey,x);
1031         printf("ssl_cert_type(x,pkey) = %d\n", ssl_cert_type(x,pkey));
1032         printf("cipher, alg, nc = %s, %lx, %lx, %d\n", s->s3->tmp.new_cipher->name,
1033                 s->s3->tmp.new_cipher->algorithm_mkey, s->s3->tmp.new_cipher->algorithm_auth, need_cert);
1034 #endif    /* KSSL_DEBUG */
1035
1036         if (need_cert && ((pkey == NULL) || EVP_PKEY_missing_parameters(pkey)))
1037                 {
1038                 x=NULL;
1039                 al=SSL3_AL_FATAL;
1040                 SSLerr(SSL_F_SSL3_GET_SERVER_CERTIFICATE,
1041                         SSL_R_UNABLE_TO_FIND_PUBLIC_KEY_PARAMETERS);
1042                 goto f_err;
1043                 }
1044
1045         i=ssl_cert_type(x,pkey);
1046         if (need_cert && i < 0)
1047                 {
1048                 x=NULL;
1049                 al=SSL3_AL_FATAL;
1050                 SSLerr(SSL_F_SSL3_GET_SERVER_CERTIFICATE,
1051                         SSL_R_UNKNOWN_CERTIFICATE_TYPE);
1052                 goto f_err;
1053                 }
1054
1055         if (need_cert)
1056                 {
1057                 sc->peer_cert_type=i;
1058                 CRYPTO_add(&x->references,1,CRYPTO_LOCK_X509);
1059                 /* Why would the following ever happen?
1060                  * We just created sc a couple of lines ago. */
1061                 if (sc->peer_pkeys[i].x509 != NULL)
1062                         X509_free(sc->peer_pkeys[i].x509);
1063                 sc->peer_pkeys[i].x509=x;
1064                 sc->peer_key= &(sc->peer_pkeys[i]);
1065
1066                 if (s->session->peer != NULL)
1067                         X509_free(s->session->peer);
1068                 CRYPTO_add(&x->references,1,CRYPTO_LOCK_X509);
1069                 s->session->peer=x;
1070                 }
1071         else
1072                 {
1073                 sc->peer_cert_type=i;
1074                 sc->peer_key= NULL;
1075
1076                 if (s->session->peer != NULL)
1077                         X509_free(s->session->peer);
1078                 s->session->peer=NULL;
1079                 }
1080         s->session->verify_result = s->verify_result;
1081
1082         x=NULL;
1083         ret=1;
1084
1085         if (0)
1086                 {
1087 f_err:
1088                 ssl3_send_alert(s,SSL3_AL_FATAL,al);
1089                 }
1090 err:
1091         EVP_PKEY_free(pkey);
1092         X509_free(x);
1093         sk_X509_pop_free(sk,X509_free);
1094         return(ret);
1095         }
1096
1097 int ssl3_get_key_exchange(SSL *s)
1098         {
1099 #ifndef OPENSSL_NO_RSA
1100         unsigned char *q,md_buf[EVP_MAX_MD_SIZE*2];
1101 #endif
1102         EVP_MD_CTX md_ctx;
1103         unsigned char *param,*p;
1104         int al,i,j,param_len,ok;
1105         long n,alg_k,alg_a;
1106         EVP_PKEY *pkey=NULL;
1107 #ifndef OPENSSL_NO_RSA
1108         RSA *rsa=NULL;
1109 #endif
1110 #ifndef OPENSSL_NO_DH
1111         DH *dh=NULL;
1112 #endif
1113 #ifndef OPENSSL_NO_ECDH
1114         EC_KEY *ecdh = NULL;
1115         BN_CTX *bn_ctx = NULL;
1116         EC_POINT *srvr_ecpoint = NULL;
1117         int curve_nid = 0;
1118         int encoded_pt_len = 0;
1119 #endif
1120
1121         /* use same message size as in ssl3_get_certificate_request()
1122          * as ServerKeyExchange message may be skipped */
1123         n=s->method->ssl_get_message(s,
1124                 SSL3_ST_CR_KEY_EXCH_A,
1125                 SSL3_ST_CR_KEY_EXCH_B,
1126                 -1,
1127                 s->max_cert_list,
1128                 &ok);
1129         if (!ok) return((int)n);
1130
1131         if (s->s3->tmp.message_type != SSL3_MT_SERVER_KEY_EXCHANGE)
1132                 {
1133 #ifndef OPENSSL_NO_PSK
1134                 /* In plain PSK ciphersuite, ServerKeyExchange can be
1135                    omitted if no identity hint is sent. Set
1136                    session->sess_cert anyway to avoid problems
1137                    later.*/
1138                 if (s->s3->tmp.new_cipher->algorithm_mkey & SSL_kPSK)
1139                         {
1140                         s->session->sess_cert=ssl_sess_cert_new();
1141                         if (s->ctx->psk_identity_hint)
1142                                 OPENSSL_free(s->ctx->psk_identity_hint);
1143                         s->ctx->psk_identity_hint = NULL;
1144                         }
1145 #endif
1146                 s->s3->tmp.reuse_message=1;
1147                 return(1);
1148                 }
1149
1150         param=p=(unsigned char *)s->init_msg;
1151         if (s->session->sess_cert != NULL)
1152                 {
1153 #ifndef OPENSSL_NO_RSA
1154                 if (s->session->sess_cert->peer_rsa_tmp != NULL)
1155                         {
1156                         RSA_free(s->session->sess_cert->peer_rsa_tmp);
1157                         s->session->sess_cert->peer_rsa_tmp=NULL;
1158                         }
1159 #endif
1160 #ifndef OPENSSL_NO_DH
1161                 if (s->session->sess_cert->peer_dh_tmp)
1162                         {
1163                         DH_free(s->session->sess_cert->peer_dh_tmp);
1164                         s->session->sess_cert->peer_dh_tmp=NULL;
1165                         }
1166 #endif
1167 #ifndef OPENSSL_NO_ECDH
1168                 if (s->session->sess_cert->peer_ecdh_tmp)
1169                         {
1170                         EC_KEY_free(s->session->sess_cert->peer_ecdh_tmp);
1171                         s->session->sess_cert->peer_ecdh_tmp=NULL;
1172                         }
1173 #endif
1174                 }
1175         else
1176                 {
1177                 s->session->sess_cert=ssl_sess_cert_new();
1178                 }
1179
1180         param_len=0;
1181         alg_k=s->s3->tmp.new_cipher->algorithm_mkey;
1182         alg_a=s->s3->tmp.new_cipher->algorithm_auth;
1183         EVP_MD_CTX_init(&md_ctx);
1184
1185 #ifndef OPENSSL_NO_PSK
1186         if (alg_k & SSL_kPSK)
1187                 {
1188                 char tmp_id_hint[PSK_MAX_IDENTITY_LEN+1];
1189
1190                 al=SSL_AD_HANDSHAKE_FAILURE;
1191                 n2s(p,i);
1192                 param_len=i+2;
1193                 /* Store PSK identity hint for later use, hint is used
1194                  * in ssl3_send_client_key_exchange.  Assume that the
1195                  * maximum length of a PSK identity hint can be as
1196                  * long as the maximum length of a PSK identity. */
1197                 if (i > PSK_MAX_IDENTITY_LEN)
1198                         {
1199                         SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,
1200                                 SSL_R_DATA_LENGTH_TOO_LONG);
1201                         goto f_err;
1202                         }
1203                 if (param_len > n)
1204                         {
1205                         al=SSL_AD_DECODE_ERROR;
1206                         SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,
1207                                 SSL_R_BAD_PSK_IDENTITY_HINT_LENGTH);
1208                         goto f_err;
1209                         }
1210                 /* If received PSK identity hint contains NULL
1211                  * characters, the hint is truncated from the first
1212                  * NULL. p may not be ending with NULL, so create a
1213                  * NULL-terminated string. */
1214                 memcpy(tmp_id_hint, p, i);
1215                 memset(tmp_id_hint+i, 0, PSK_MAX_IDENTITY_LEN+1-i);
1216                 if (s->ctx->psk_identity_hint != NULL)
1217                         OPENSSL_free(s->ctx->psk_identity_hint);
1218                 s->ctx->psk_identity_hint = BUF_strdup(tmp_id_hint);
1219                 if (s->ctx->psk_identity_hint == NULL)
1220                         {
1221                         SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE, ERR_R_MALLOC_FAILURE);
1222                         goto f_err;
1223                         }          
1224
1225                 p+=i;
1226                 n-=param_len;
1227                 }
1228         else
1229 #endif /* !OPENSSL_NO_PSK */
1230 #ifndef OPENSSL_NO_RSA
1231         if (alg_k & SSL_kRSA)
1232                 {
1233                 if ((rsa=RSA_new()) == NULL)
1234                         {
1235                         SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,ERR_R_MALLOC_FAILURE);
1236                         goto err;
1237                         }
1238                 n2s(p,i);
1239                 param_len=i+2;
1240                 if (param_len > n)
1241                         {
1242                         al=SSL_AD_DECODE_ERROR;
1243                         SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,SSL_R_BAD_RSA_MODULUS_LENGTH);
1244                         goto f_err;
1245                         }
1246                 if (!(rsa->n=BN_bin2bn(p,i,rsa->n)))
1247                         {
1248                         SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,ERR_R_BN_LIB);
1249                         goto err;
1250                         }
1251                 p+=i;
1252
1253                 n2s(p,i);
1254                 param_len+=i+2;
1255                 if (param_len > n)
1256                         {
1257                         al=SSL_AD_DECODE_ERROR;
1258                         SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,SSL_R_BAD_RSA_E_LENGTH);
1259                         goto f_err;
1260                         }
1261                 if (!(rsa->e=BN_bin2bn(p,i,rsa->e)))
1262                         {
1263                         SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,ERR_R_BN_LIB);
1264                         goto err;
1265                         }
1266                 p+=i;
1267                 n-=param_len;
1268
1269                 /* this should be because we are using an export cipher */
1270                 if (alg_a & SSL_aRSA)
1271                         pkey=X509_get_pubkey(s->session->sess_cert->peer_pkeys[SSL_PKEY_RSA_ENC].x509);
1272                 else
1273                         {
1274                         SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,ERR_R_INTERNAL_ERROR);
1275                         goto err;
1276                         }
1277                 s->session->sess_cert->peer_rsa_tmp=rsa;
1278                 rsa=NULL;
1279                 }
1280 #else /* OPENSSL_NO_RSA */
1281         if (0)
1282                 ;
1283 #endif
1284 #ifndef OPENSSL_NO_DH
1285         else if (alg_k & SSL_kEDH)
1286                 {
1287                 if ((dh=DH_new()) == NULL)
1288                         {
1289                         SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,ERR_R_DH_LIB);
1290                         goto err;
1291                         }
1292                 n2s(p,i);
1293                 param_len=i+2;
1294                 if (param_len > n)
1295                         {
1296                         al=SSL_AD_DECODE_ERROR;
1297                         SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,SSL_R_BAD_DH_P_LENGTH);
1298                         goto f_err;
1299                         }
1300                 if (!(dh->p=BN_bin2bn(p,i,NULL)))
1301                         {
1302                         SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,ERR_R_BN_LIB);
1303                         goto err;
1304                         }
1305                 p+=i;
1306
1307                 n2s(p,i);
1308                 param_len+=i+2;
1309                 if (param_len > n)
1310                         {
1311                         al=SSL_AD_DECODE_ERROR;
1312                         SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,SSL_R_BAD_DH_G_LENGTH);
1313                         goto f_err;
1314                         }
1315                 if (!(dh->g=BN_bin2bn(p,i,NULL)))
1316                         {
1317                         SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,ERR_R_BN_LIB);
1318                         goto err;
1319                         }
1320                 p+=i;
1321
1322                 n2s(p,i);
1323                 param_len+=i+2;
1324                 if (param_len > n)
1325                         {
1326                         al=SSL_AD_DECODE_ERROR;
1327                         SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,SSL_R_BAD_DH_PUB_KEY_LENGTH);
1328                         goto f_err;
1329                         }
1330                 if (!(dh->pub_key=BN_bin2bn(p,i,NULL)))
1331                         {
1332                         SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,ERR_R_BN_LIB);
1333                         goto err;
1334                         }
1335                 p+=i;
1336                 n-=param_len;
1337
1338 #ifndef OPENSSL_NO_RSA
1339                 if (alg_a & SSL_aRSA)
1340                         pkey=X509_get_pubkey(s->session->sess_cert->peer_pkeys[SSL_PKEY_RSA_ENC].x509);
1341 #else
1342                 if (0)
1343                         ;
1344 #endif
1345 #ifndef OPENSSL_NO_DSA
1346                 else if (alg_a & SSL_aDSS)
1347                         pkey=X509_get_pubkey(s->session->sess_cert->peer_pkeys[SSL_PKEY_DSA_SIGN].x509);
1348 #endif
1349                 /* else anonymous DH, so no certificate or pkey. */
1350
1351                 s->session->sess_cert->peer_dh_tmp=dh;
1352                 dh=NULL;
1353                 }
1354         else if ((alg_k & SSL_kDHr) || (alg_k & SSL_kDHd))
1355                 {
1356                 al=SSL_AD_ILLEGAL_PARAMETER;
1357                 SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,SSL_R_TRIED_TO_USE_UNSUPPORTED_CIPHER);
1358                 goto f_err;
1359                 }
1360 #endif /* !OPENSSL_NO_DH */
1361
1362 #ifndef OPENSSL_NO_ECDH
1363         else if (alg_k & SSL_kEECDH)
1364                 {
1365                 EC_GROUP *ngroup;
1366                 const EC_GROUP *group;
1367
1368                 if ((ecdh=EC_KEY_new()) == NULL)
1369                         {
1370                         SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,ERR_R_MALLOC_FAILURE);
1371                         goto err;
1372                         }
1373
1374                 /* Extract elliptic curve parameters and the
1375                  * server's ephemeral ECDH public key.
1376                  * Keep accumulating lengths of various components in
1377                  * param_len and make sure it never exceeds n.
1378                  */
1379
1380                 /* XXX: For now we only support named (not generic) curves
1381                  * and the ECParameters in this case is just three bytes.
1382                  */
1383                 param_len=3;
1384                 if ((param_len > n) ||
1385                     (*p != NAMED_CURVE_TYPE) || 
1386                     ((curve_nid = tls1_ec_curve_id2nid(*(p + 2))) == 0)) 
1387                         {
1388                         al=SSL_AD_INTERNAL_ERROR;
1389                         SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,SSL_R_UNABLE_TO_FIND_ECDH_PARAMETERS);
1390                         goto f_err;
1391                         }
1392
1393                 ngroup = EC_GROUP_new_by_curve_name(curve_nid);
1394                 if (ngroup == NULL)
1395                         {
1396                         SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,ERR_R_EC_LIB);
1397                         goto err;
1398                         }
1399                 if (EC_KEY_set_group(ecdh, ngroup) == 0)
1400                         {
1401                         SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,ERR_R_EC_LIB);
1402                         goto err;
1403                         }
1404                 EC_GROUP_free(ngroup);
1405
1406                 group = EC_KEY_get0_group(ecdh);
1407
1408                 if (SSL_C_IS_EXPORT(s->s3->tmp.new_cipher) &&
1409                     (EC_GROUP_get_degree(group) > 163))
1410                         {
1411                         al=SSL_AD_EXPORT_RESTRICTION;
1412                         SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,SSL_R_ECGROUP_TOO_LARGE_FOR_CIPHER);
1413                         goto f_err;
1414                         }
1415
1416                 p+=3;
1417
1418                 /* Next, get the encoded ECPoint */
1419                 if (((srvr_ecpoint = EC_POINT_new(group)) == NULL) ||
1420                     ((bn_ctx = BN_CTX_new()) == NULL))
1421                         {
1422                         SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,ERR_R_MALLOC_FAILURE);
1423                         goto err;
1424                         }
1425
1426                 encoded_pt_len = *p;  /* length of encoded point */
1427                 p+=1;
1428                 param_len += (1 + encoded_pt_len);
1429                 if ((param_len > n) ||
1430                     (EC_POINT_oct2point(group, srvr_ecpoint, 
1431                         p, encoded_pt_len, bn_ctx) == 0))
1432                         {
1433                         al=SSL_AD_DECODE_ERROR;
1434                         SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,SSL_R_BAD_ECPOINT);
1435                         goto f_err;
1436                         }
1437
1438                 n-=param_len;
1439                 p+=encoded_pt_len;
1440
1441                 /* The ECC/TLS specification does not mention
1442                  * the use of DSA to sign ECParameters in the server
1443                  * key exchange message. We do support RSA and ECDSA.
1444                  */
1445                 if (0) ;
1446 #ifndef OPENSSL_NO_RSA
1447                 else if (alg_a & SSL_aRSA)
1448                         pkey=X509_get_pubkey(s->session->sess_cert->peer_pkeys[SSL_PKEY_RSA_ENC].x509);
1449 #endif
1450 #ifndef OPENSSL_NO_ECDSA
1451                 else if (alg_a & SSL_aECDSA)
1452                         pkey=X509_get_pubkey(s->session->sess_cert->peer_pkeys[SSL_PKEY_ECC].x509);
1453 #endif
1454                 /* else anonymous ECDH, so no certificate or pkey. */
1455                 EC_KEY_set_public_key(ecdh, srvr_ecpoint);
1456                 s->session->sess_cert->peer_ecdh_tmp=ecdh;
1457                 ecdh=NULL;
1458                 BN_CTX_free(bn_ctx);
1459                 EC_POINT_free(srvr_ecpoint);
1460                 srvr_ecpoint = NULL;
1461                 }
1462         else if (alg_k)
1463                 {
1464                 al=SSL_AD_UNEXPECTED_MESSAGE;
1465                 SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,SSL_R_UNEXPECTED_MESSAGE);
1466                 goto f_err;
1467                 }
1468 #endif /* !OPENSSL_NO_ECDH */
1469
1470
1471         /* p points to the next byte, there are 'n' bytes left */
1472
1473         /* if it was signed, check the signature */
1474         if (pkey != NULL)
1475                 {
1476                 n2s(p,i);
1477                 n-=2;
1478                 j=EVP_PKEY_size(pkey);
1479
1480                 if ((i != n) || (n > j) || (n <= 0))
1481                         {
1482                         /* wrong packet length */
1483                         al=SSL_AD_DECODE_ERROR;
1484                         SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,SSL_R_WRONG_SIGNATURE_LENGTH);
1485                         goto f_err;
1486                         }
1487
1488 #ifndef OPENSSL_NO_RSA
1489                 if (pkey->type == EVP_PKEY_RSA)
1490                         {
1491                         int num;
1492
1493                         j=0;
1494                         q=md_buf;
1495                         for (num=2; num > 0; num--)
1496                                 {
1497                                 EVP_DigestInit_ex(&md_ctx,(num == 2)
1498                                         ?s->ctx->md5:s->ctx->sha1, NULL);
1499                                 EVP_DigestUpdate(&md_ctx,&(s->s3->client_random[0]),SSL3_RANDOM_SIZE);
1500                                 EVP_DigestUpdate(&md_ctx,&(s->s3->server_random[0]),SSL3_RANDOM_SIZE);
1501                                 EVP_DigestUpdate(&md_ctx,param,param_len);
1502                                 EVP_DigestFinal_ex(&md_ctx,q,(unsigned int *)&i);
1503                                 q+=i;
1504                                 j+=i;
1505                                 }
1506                         i=RSA_verify(NID_md5_sha1, md_buf, j, p, n,
1507                                                                 pkey->pkey.rsa);
1508                         if (i < 0)
1509                                 {
1510                                 al=SSL_AD_DECRYPT_ERROR;
1511                                 SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,SSL_R_BAD_RSA_DECRYPT);
1512                                 goto f_err;
1513                                 }
1514                         if (i == 0)
1515                                 {
1516                                 /* bad signature */
1517                                 al=SSL_AD_DECRYPT_ERROR;
1518                                 SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,SSL_R_BAD_SIGNATURE);
1519                                 goto f_err;
1520                                 }
1521                         }
1522                 else
1523 #endif
1524 #ifndef OPENSSL_NO_DSA
1525                         if (pkey->type == EVP_PKEY_DSA)
1526                         {
1527                         /* lets do DSS */
1528                         EVP_VerifyInit_ex(&md_ctx,EVP_dss1(), NULL);
1529                         EVP_VerifyUpdate(&md_ctx,&(s->s3->client_random[0]),SSL3_RANDOM_SIZE);
1530                         EVP_VerifyUpdate(&md_ctx,&(s->s3->server_random[0]),SSL3_RANDOM_SIZE);
1531                         EVP_VerifyUpdate(&md_ctx,param,param_len);
1532                         if (!EVP_VerifyFinal(&md_ctx,p,(int)n,pkey))
1533                                 {
1534                                 /* bad signature */
1535                                 al=SSL_AD_DECRYPT_ERROR;
1536                                 SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,SSL_R_BAD_SIGNATURE);
1537                                 goto f_err;
1538                                 }
1539                         }
1540                 else
1541 #endif
1542 #ifndef OPENSSL_NO_ECDSA
1543                         if (pkey->type == EVP_PKEY_EC)
1544                         {
1545                         /* let's do ECDSA */
1546                         EVP_VerifyInit_ex(&md_ctx,EVP_ecdsa(), NULL);
1547                         EVP_VerifyUpdate(&md_ctx,&(s->s3->client_random[0]),SSL3_RANDOM_SIZE);
1548                         EVP_VerifyUpdate(&md_ctx,&(s->s3->server_random[0]),SSL3_RANDOM_SIZE);
1549                         EVP_VerifyUpdate(&md_ctx,param,param_len);
1550                         if (!EVP_VerifyFinal(&md_ctx,p,(int)n,pkey))
1551                                 {
1552                                 /* bad signature */
1553                                 al=SSL_AD_DECRYPT_ERROR;
1554                                 SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,SSL_R_BAD_SIGNATURE);
1555                                 goto f_err;
1556                                 }
1557                         }
1558                 else
1559 #endif
1560                         {
1561                         SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,ERR_R_INTERNAL_ERROR);
1562                         goto err;
1563                         }
1564                 }
1565         else
1566                 {
1567                 if (!(alg_a & SSL_aNULL) && !(alg_k & SSL_kPSK))
1568                         /* aNULL or kPSK do not need public keys */
1569                         {
1570                         SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,ERR_R_INTERNAL_ERROR);
1571                         goto err;
1572                         }
1573                 /* still data left over */
1574                 if (n != 0)
1575                         {
1576                         al=SSL_AD_DECODE_ERROR;
1577                         SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,SSL_R_EXTRA_DATA_IN_MESSAGE);
1578                         goto f_err;
1579                         }
1580                 }
1581         EVP_PKEY_free(pkey);
1582         EVP_MD_CTX_cleanup(&md_ctx);
1583         return(1);
1584 f_err:
1585         ssl3_send_alert(s,SSL3_AL_FATAL,al);
1586 err:
1587         EVP_PKEY_free(pkey);
1588 #ifndef OPENSSL_NO_RSA
1589         if (rsa != NULL)
1590                 RSA_free(rsa);
1591 #endif
1592 #ifndef OPENSSL_NO_DH
1593         if (dh != NULL)
1594                 DH_free(dh);
1595 #endif
1596 #ifndef OPENSSL_NO_ECDH
1597         BN_CTX_free(bn_ctx);
1598         EC_POINT_free(srvr_ecpoint);
1599         if (ecdh != NULL)
1600                 EC_KEY_free(ecdh);
1601 #endif
1602         EVP_MD_CTX_cleanup(&md_ctx);
1603         return(-1);
1604         }
1605
1606 int ssl3_get_certificate_request(SSL *s)
1607         {
1608         int ok,ret=0;
1609         unsigned long n,nc,l;
1610         unsigned int llen,ctype_num,i;
1611         X509_NAME *xn=NULL;
1612         const unsigned char *p,*q;
1613         unsigned char *d;
1614         STACK_OF(X509_NAME) *ca_sk=NULL;
1615
1616         n=s->method->ssl_get_message(s,
1617                 SSL3_ST_CR_CERT_REQ_A,
1618                 SSL3_ST_CR_CERT_REQ_B,
1619                 -1,
1620                 s->max_cert_list,
1621                 &ok);
1622
1623         if (!ok) return((int)n);
1624
1625         s->s3->tmp.cert_req=0;
1626
1627         if (s->s3->tmp.message_type == SSL3_MT_SERVER_DONE)
1628                 {
1629                 s->s3->tmp.reuse_message=1;
1630                 return(1);
1631                 }
1632
1633         if (s->s3->tmp.message_type != SSL3_MT_CERTIFICATE_REQUEST)
1634                 {
1635                 ssl3_send_alert(s,SSL3_AL_FATAL,SSL_AD_UNEXPECTED_MESSAGE);
1636                 SSLerr(SSL_F_SSL3_GET_CERTIFICATE_REQUEST,SSL_R_WRONG_MESSAGE_TYPE);
1637                 goto err;
1638                 }
1639
1640         /* TLS does not like anon-DH with client cert */
1641         if (s->version > SSL3_VERSION)
1642                 {
1643                 if (s->s3->tmp.new_cipher->algorithm_auth & SSL_aNULL)
1644                         {
1645                         ssl3_send_alert(s,SSL3_AL_FATAL,SSL_AD_UNEXPECTED_MESSAGE);
1646                         SSLerr(SSL_F_SSL3_GET_CERTIFICATE_REQUEST,SSL_R_TLS_CLIENT_CERT_REQ_WITH_ANON_CIPHER);
1647                         goto err;
1648                         }
1649                 }
1650
1651         p=d=(unsigned char *)s->init_msg;
1652
1653         if ((ca_sk=sk_X509_NAME_new(ca_dn_cmp)) == NULL)
1654                 {
1655                 SSLerr(SSL_F_SSL3_GET_CERTIFICATE_REQUEST,ERR_R_MALLOC_FAILURE);
1656                 goto err;
1657                 }
1658
1659         /* get the certificate types */
1660         ctype_num= *(p++);
1661         if (ctype_num > SSL3_CT_NUMBER)
1662                 ctype_num=SSL3_CT_NUMBER;
1663         for (i=0; i<ctype_num; i++)
1664                 s->s3->tmp.ctype[i]= p[i];
1665         p+=ctype_num;
1666
1667         /* get the CA RDNs */
1668         n2s(p,llen);
1669 #if 0
1670 {
1671 FILE *out;
1672 out=fopen("/tmp/vsign.der","w");
1673 fwrite(p,1,llen,out);
1674 fclose(out);
1675 }
1676 #endif
1677
1678         if ((llen+ctype_num+2+1) != n)
1679                 {
1680                 ssl3_send_alert(s,SSL3_AL_FATAL,SSL_AD_DECODE_ERROR);
1681                 SSLerr(SSL_F_SSL3_GET_CERTIFICATE_REQUEST,SSL_R_LENGTH_MISMATCH);
1682                 goto err;
1683                 }
1684
1685         for (nc=0; nc<llen; )
1686                 {
1687                 n2s(p,l);
1688                 if ((l+nc+2) > llen)
1689                         {
1690                         if ((s->options & SSL_OP_NETSCAPE_CA_DN_BUG))
1691                                 goto cont; /* netscape bugs */
1692                         ssl3_send_alert(s,SSL3_AL_FATAL,SSL_AD_DECODE_ERROR);
1693                         SSLerr(SSL_F_SSL3_GET_CERTIFICATE_REQUEST,SSL_R_CA_DN_TOO_LONG);
1694                         goto err;
1695                         }
1696
1697                 q=p;
1698
1699                 if ((xn=d2i_X509_NAME(NULL,&q,l)) == NULL)
1700                         {
1701                         /* If netscape tolerance is on, ignore errors */
1702                         if (s->options & SSL_OP_NETSCAPE_CA_DN_BUG)
1703                                 goto cont;
1704                         else
1705                                 {
1706                                 ssl3_send_alert(s,SSL3_AL_FATAL,SSL_AD_DECODE_ERROR);
1707                                 SSLerr(SSL_F_SSL3_GET_CERTIFICATE_REQUEST,ERR_R_ASN1_LIB);
1708                                 goto err;
1709                                 }
1710                         }
1711
1712                 if (q != (p+l))
1713                         {
1714                         ssl3_send_alert(s,SSL3_AL_FATAL,SSL_AD_DECODE_ERROR);
1715                         SSLerr(SSL_F_SSL3_GET_CERTIFICATE_REQUEST,SSL_R_CA_DN_LENGTH_MISMATCH);
1716                         goto err;
1717                         }
1718                 if (!sk_X509_NAME_push(ca_sk,xn))
1719                         {
1720                         SSLerr(SSL_F_SSL3_GET_CERTIFICATE_REQUEST,ERR_R_MALLOC_FAILURE);
1721                         goto err;
1722                         }
1723
1724                 p+=l;
1725                 nc+=l+2;
1726                 }
1727
1728         if (0)
1729                 {
1730 cont:
1731                 ERR_clear_error();
1732                 }
1733
1734         /* we should setup a certificate to return.... */
1735         s->s3->tmp.cert_req=1;
1736         s->s3->tmp.ctype_num=ctype_num;
1737         if (s->s3->tmp.ca_names != NULL)
1738                 sk_X509_NAME_pop_free(s->s3->tmp.ca_names,X509_NAME_free);
1739         s->s3->tmp.ca_names=ca_sk;
1740         ca_sk=NULL;
1741
1742         ret=1;
1743 err:
1744         if (ca_sk != NULL) sk_X509_NAME_pop_free(ca_sk,X509_NAME_free);
1745         return(ret);
1746         }
1747
1748 static int ca_dn_cmp(const X509_NAME * const *a, const X509_NAME * const *b)
1749         {
1750         return(X509_NAME_cmp(*a,*b));
1751         }
1752 #ifndef OPENSSL_NO_TLSEXT
1753 int ssl3_get_new_session_ticket(SSL *s)
1754         {
1755         int ok,al,ret=0, ticklen;
1756         long n;
1757         const unsigned char *p;
1758         unsigned char *d;
1759
1760         n=s->method->ssl_get_message(s,
1761                 SSL3_ST_CR_SESSION_TICKET_A,
1762                 SSL3_ST_CR_SESSION_TICKET_B,
1763                 -1,
1764                 16384,
1765                 &ok);
1766
1767         if (!ok)
1768                 return((int)n);
1769
1770         if (s->s3->tmp.message_type == SSL3_MT_FINISHED)
1771                 {
1772                 s->s3->tmp.reuse_message=1;
1773                 return(1);
1774                 }
1775         if (s->s3->tmp.message_type != SSL3_MT_NEWSESSION_TICKET)
1776                 {
1777                 al=SSL_AD_UNEXPECTED_MESSAGE;
1778                 SSLerr(SSL_F_SSL3_GET_NEW_SESSION_TICKET,SSL_R_BAD_MESSAGE_TYPE);
1779                 goto f_err;
1780                 }
1781         if (n < 6)
1782                 {
1783                 /* need at least ticket_lifetime_hint + ticket length */
1784                 al = SSL3_AL_FATAL,SSL_AD_DECODE_ERROR;
1785                 SSLerr(SSL_F_SSL3_GET_NEW_SESSION_TICKET,SSL_R_LENGTH_MISMATCH);
1786                 goto f_err;
1787                 }
1788         p=d=(unsigned char *)s->init_msg;
1789         n2l(p, s->session->tlsext_tick_lifetime_hint);
1790         n2s(p, ticklen);
1791         /* ticket_lifetime_hint + ticket_length + ticket */
1792         if (ticklen + 6 != n)
1793                 {
1794                 al = SSL3_AL_FATAL,SSL_AD_DECODE_ERROR;
1795                 SSLerr(SSL_F_SSL3_GET_NEW_SESSION_TICKET,SSL_R_LENGTH_MISMATCH);
1796                 goto f_err;
1797                 }
1798         if (s->session->tlsext_tick)
1799                 {
1800                 OPENSSL_free(s->session->tlsext_tick);
1801                 s->session->tlsext_ticklen = 0;
1802                 }
1803         s->session->tlsext_tick = OPENSSL_malloc(ticklen);
1804         if (!s->session->tlsext_tick)
1805                 {
1806                 SSLerr(SSL_F_SSL3_GET_NEW_SESSION_TICKET,ERR_R_MALLOC_FAILURE);
1807                 goto err;
1808                 }
1809         memcpy(s->session->tlsext_tick, p, ticklen);
1810         s->session->tlsext_ticklen = ticklen;
1811         
1812         ret=1;
1813         return(ret);
1814 f_err:
1815         ssl3_send_alert(s,SSL3_AL_FATAL,al);
1816 err:
1817         return(-1);
1818         }
1819
1820 int ssl3_get_cert_status(SSL *s)
1821         {
1822         int ok, al;
1823         unsigned long resplen;
1824         long n;
1825         const unsigned char *p;
1826
1827         n=s->method->ssl_get_message(s,
1828                 SSL3_ST_CR_CERT_STATUS_A,
1829                 SSL3_ST_CR_CERT_STATUS_B,
1830                 SSL3_MT_CERTIFICATE_STATUS,
1831                 16384,
1832                 &ok);
1833
1834         if (!ok) return((int)n);
1835         if (n < 4)
1836                 {
1837                 /* need at least status type + length */
1838                 al = SSL_AD_DECODE_ERROR;
1839                 SSLerr(SSL_F_SSL3_GET_CERT_STATUS,SSL_R_LENGTH_MISMATCH);
1840                 goto f_err;
1841                 }
1842         p = (unsigned char *)s->init_msg;
1843         if (*p++ != TLSEXT_STATUSTYPE_ocsp)
1844                 {
1845                 al = SSL_AD_DECODE_ERROR;
1846                 SSLerr(SSL_F_SSL3_GET_CERT_STATUS,SSL_R_UNSUPPORTED_STATUS_TYPE);
1847                 goto f_err;
1848                 }
1849         n2l3(p, resplen);
1850         if (resplen + 4 != n)
1851                 {
1852                 al = SSL_AD_DECODE_ERROR;
1853                 SSLerr(SSL_F_SSL3_GET_CERT_STATUS,SSL_R_LENGTH_MISMATCH);
1854                 goto f_err;
1855                 }
1856         if (s->tlsext_ocsp_resp)
1857                 OPENSSL_free(s->tlsext_ocsp_resp);
1858         s->tlsext_ocsp_resp = BUF_memdup(p, resplen);
1859         if (!s->tlsext_ocsp_resp)
1860                 {
1861                 al = SSL_AD_INTERNAL_ERROR;
1862                 SSLerr(SSL_F_SSL3_GET_CERT_STATUS,ERR_R_MALLOC_FAILURE);
1863                 goto f_err;
1864                 }
1865         s->tlsext_ocsp_resplen = resplen;
1866         if (s->ctx->tlsext_status_cb)
1867                 {
1868                 int ret;
1869                 ret = s->ctx->tlsext_status_cb(s, s->ctx->tlsext_status_arg);
1870                 if (ret == 0)
1871                         {
1872                         al = SSL_AD_BAD_CERTIFICATE_STATUS_RESPONSE;
1873                         SSLerr(SSL_F_SSL3_GET_CERT_STATUS,SSL_R_INVALID_STATUS_RESPONSE);
1874                         goto f_err;
1875                         }
1876                 if (ret < 0)
1877                         {
1878                         al = SSL_AD_INTERNAL_ERROR;
1879                         SSLerr(SSL_F_SSL3_GET_CERT_STATUS,ERR_R_MALLOC_FAILURE);
1880                         goto f_err;
1881                         }
1882                 }
1883         return 1;
1884 f_err:
1885         ssl3_send_alert(s,SSL3_AL_FATAL,al);
1886         return(-1);
1887         }
1888 #endif
1889
1890 int ssl3_get_server_done(SSL *s)
1891         {
1892         int ok,ret=0;
1893         long n;
1894
1895         n=s->method->ssl_get_message(s,
1896                 SSL3_ST_CR_SRVR_DONE_A,
1897                 SSL3_ST_CR_SRVR_DONE_B,
1898                 SSL3_MT_SERVER_DONE,
1899                 30, /* should be very small, like 0 :-) */
1900                 &ok);
1901
1902         if (!ok) return((int)n);
1903         if (n > 0)
1904                 {
1905                 /* should contain no data */
1906                 ssl3_send_alert(s,SSL3_AL_FATAL,SSL_AD_DECODE_ERROR);
1907                 SSLerr(SSL_F_SSL3_GET_SERVER_DONE,SSL_R_LENGTH_MISMATCH);
1908                 return -1;
1909                 }
1910         ret=1;
1911         return(ret);
1912         }
1913
1914
1915 int ssl3_send_client_key_exchange(SSL *s)
1916         {
1917         unsigned char *p,*d;
1918         int n;
1919         unsigned long alg_k;
1920 #ifndef OPENSSL_NO_RSA
1921         unsigned char *q;
1922         EVP_PKEY *pkey=NULL;
1923 #endif
1924 #ifndef OPENSSL_NO_KRB5
1925         KSSL_ERR kssl_err;
1926 #endif /* OPENSSL_NO_KRB5 */
1927 #ifndef OPENSSL_NO_ECDH
1928         EC_KEY *clnt_ecdh = NULL;
1929         const EC_POINT *srvr_ecpoint = NULL;
1930         EVP_PKEY *srvr_pub_pkey = NULL;
1931         unsigned char *encodedPoint = NULL;
1932         int encoded_pt_len = 0;
1933         BN_CTX * bn_ctx = NULL;
1934 #endif
1935
1936         if (s->state == SSL3_ST_CW_KEY_EXCH_A)
1937                 {
1938                 d=(unsigned char *)s->init_buf->data;
1939                 p= &(d[4]);
1940
1941                 alg_k=s->s3->tmp.new_cipher->algorithm_mkey;
1942
1943                 /* Fool emacs indentation */
1944                 if (0) {}
1945 #ifndef OPENSSL_NO_RSA
1946                 else if (alg_k & SSL_kRSA)
1947                         {
1948                         RSA *rsa;
1949                         unsigned char tmp_buf[SSL_MAX_MASTER_KEY_LENGTH];
1950
1951                         if (s->session->sess_cert->peer_rsa_tmp != NULL)
1952                                 rsa=s->session->sess_cert->peer_rsa_tmp;
1953                         else
1954                                 {
1955                                 pkey=X509_get_pubkey(s->session->sess_cert->peer_pkeys[SSL_PKEY_RSA_ENC].x509);
1956                                 if ((pkey == NULL) ||
1957                                         (pkey->type != EVP_PKEY_RSA) ||
1958                                         (pkey->pkey.rsa == NULL))
1959                                         {
1960                                         SSLerr(SSL_F_SSL3_SEND_CLIENT_KEY_EXCHANGE,ERR_R_INTERNAL_ERROR);
1961                                         goto err;
1962                                         }
1963                                 rsa=pkey->pkey.rsa;
1964                                 EVP_PKEY_free(pkey);
1965                                 }
1966                                 
1967                         tmp_buf[0]=s->client_version>>8;
1968                         tmp_buf[1]=s->client_version&0xff;
1969                         if (RAND_bytes(&(tmp_buf[2]),sizeof tmp_buf-2) <= 0)
1970                                         goto err;
1971
1972                         s->session->master_key_length=sizeof tmp_buf;
1973
1974                         q=p;
1975                         /* Fix buf for TLS and beyond */
1976                         if (s->version > SSL3_VERSION)
1977                                 p+=2;
1978                         n=RSA_public_encrypt(sizeof tmp_buf,
1979                                 tmp_buf,p,rsa,RSA_PKCS1_PADDING);
1980 #ifdef PKCS1_CHECK
1981                         if (s->options & SSL_OP_PKCS1_CHECK_1) p[1]++;
1982                         if (s->options & SSL_OP_PKCS1_CHECK_2) tmp_buf[0]=0x70;
1983 #endif
1984                         if (n <= 0)
1985                                 {
1986                                 SSLerr(SSL_F_SSL3_SEND_CLIENT_KEY_EXCHANGE,SSL_R_BAD_RSA_ENCRYPT);
1987                                 goto err;
1988                                 }
1989
1990                         /* Fix buf for TLS and beyond */
1991                         if (s->version > SSL3_VERSION)
1992                                 {
1993                                 s2n(n,q);
1994                                 n+=2;
1995                                 }
1996
1997                         s->session->master_key_length=
1998                                 s->method->ssl3_enc->generate_master_secret(s,
1999                                         s->session->master_key,
2000                                         tmp_buf,sizeof tmp_buf);
2001                         OPENSSL_cleanse(tmp_buf,sizeof tmp_buf);
2002                         }
2003 #endif
2004 #ifndef OPENSSL_NO_KRB5
2005                 else if (alg_k & SSL_kKRB5)
2006                         {
2007                         krb5_error_code krb5rc;
2008                         KSSL_CTX        *kssl_ctx = s->kssl_ctx;
2009                         /*  krb5_data   krb5_ap_req;  */
2010                         krb5_data       *enc_ticket;
2011                         krb5_data       authenticator, *authp = NULL;
2012                         EVP_CIPHER_CTX  ciph_ctx;
2013                         EVP_CIPHER      *enc = NULL;
2014                         unsigned char   iv[EVP_MAX_IV_LENGTH];
2015                         unsigned char   tmp_buf[SSL_MAX_MASTER_KEY_LENGTH];
2016                         unsigned char   epms[SSL_MAX_MASTER_KEY_LENGTH 
2017                                                 + EVP_MAX_IV_LENGTH];
2018                         int             padl, outl = sizeof(epms);
2019
2020                         EVP_CIPHER_CTX_init(&ciph_ctx);
2021
2022 #ifdef KSSL_DEBUG
2023                         printf("ssl3_send_client_key_exchange(%lx & %lx)\n",
2024                                 alg_k, SSL_kKRB5);
2025 #endif  /* KSSL_DEBUG */
2026
2027                         authp = NULL;
2028 #ifdef KRB5SENDAUTH
2029                         if (KRB5SENDAUTH)  authp = &authenticator;
2030 #endif  /* KRB5SENDAUTH */
2031
2032                         krb5rc = kssl_cget_tkt(kssl_ctx, &enc_ticket, authp,
2033                                 &kssl_err);
2034                         enc = kssl_map_enc(kssl_ctx->enctype);
2035                         if (enc == NULL)
2036                             goto err;
2037 #ifdef KSSL_DEBUG
2038                         {
2039                         printf("kssl_cget_tkt rtn %d\n", krb5rc);
2040                         if (krb5rc && kssl_err.text)
2041                           printf("kssl_cget_tkt kssl_err=%s\n", kssl_err.text);
2042                         }
2043 #endif  /* KSSL_DEBUG */
2044
2045                         if (krb5rc)
2046                                 {
2047                                 ssl3_send_alert(s,SSL3_AL_FATAL,
2048                                                 SSL_AD_HANDSHAKE_FAILURE);
2049                                 SSLerr(SSL_F_SSL3_SEND_CLIENT_KEY_EXCHANGE,
2050                                                 kssl_err.reason);
2051                                 goto err;
2052                                 }
2053
2054                         /*  20010406 VRS - Earlier versions used KRB5 AP_REQ
2055                         **  in place of RFC 2712 KerberosWrapper, as in:
2056                         **
2057                         **  Send ticket (copy to *p, set n = length)
2058                         **  n = krb5_ap_req.length;
2059                         **  memcpy(p, krb5_ap_req.data, krb5_ap_req.length);
2060                         **  if (krb5_ap_req.data)  
2061                         **    kssl_krb5_free_data_contents(NULL,&krb5_ap_req);
2062                         **
2063                         **  Now using real RFC 2712 KerberosWrapper
2064                         **  (Thanks to Simon Wilkinson <sxw@sxw.org.uk>)
2065                         **  Note: 2712 "opaque" types are here replaced
2066                         **  with a 2-byte length followed by the value.
2067                         **  Example:
2068                         **  KerberosWrapper= xx xx asn1ticket 0 0 xx xx encpms
2069                         **  Where "xx xx" = length bytes.  Shown here with
2070                         **  optional authenticator omitted.
2071                         */
2072
2073                         /*  KerberosWrapper.Ticket              */
2074                         s2n(enc_ticket->length,p);
2075                         memcpy(p, enc_ticket->data, enc_ticket->length);
2076                         p+= enc_ticket->length;
2077                         n = enc_ticket->length + 2;
2078
2079                         /*  KerberosWrapper.Authenticator       */
2080                         if (authp  &&  authp->length)  
2081                                 {
2082                                 s2n(authp->length,p);
2083                                 memcpy(p, authp->data, authp->length);
2084                                 p+= authp->length;
2085                                 n+= authp->length + 2;
2086                                 
2087                                 free(authp->data);
2088                                 authp->data = NULL;
2089                                 authp->length = 0;
2090                                 }
2091                         else
2092                                 {
2093                                 s2n(0,p);/*  null authenticator length  */
2094                                 n+=2;
2095                                 }
2096  
2097                             tmp_buf[0]=s->client_version>>8;
2098                             tmp_buf[1]=s->client_version&0xff;
2099                             if (RAND_bytes(&(tmp_buf[2]),sizeof tmp_buf-2) <= 0)
2100                                 goto err;
2101
2102                         /*  20010420 VRS.  Tried it this way; failed.
2103                         **      EVP_EncryptInit_ex(&ciph_ctx,enc, NULL,NULL);
2104                         **      EVP_CIPHER_CTX_set_key_length(&ciph_ctx,
2105                         **                              kssl_ctx->length);
2106                         **      EVP_EncryptInit_ex(&ciph_ctx,NULL, key,iv);
2107                         */
2108
2109                         memset(iv, 0, sizeof iv);  /* per RFC 1510 */
2110                         EVP_EncryptInit_ex(&ciph_ctx,enc, NULL,
2111                                 kssl_ctx->key,iv);
2112                         EVP_EncryptUpdate(&ciph_ctx,epms,&outl,tmp_buf,
2113                                 sizeof tmp_buf);
2114                         EVP_EncryptFinal_ex(&ciph_ctx,&(epms[outl]),&padl);
2115                         outl += padl;
2116                         if (outl > sizeof epms)
2117                                 {
2118                                 SSLerr(SSL_F_SSL3_SEND_CLIENT_KEY_EXCHANGE, ERR_R_INTERNAL_ERROR);
2119                                 goto err;
2120                                 }
2121                         EVP_CIPHER_CTX_cleanup(&ciph_ctx);
2122
2123                         /*  KerberosWrapper.EncryptedPreMasterSecret    */
2124                         s2n(outl,p);
2125                         memcpy(p, epms, outl);
2126                         p+=outl;
2127                         n+=outl + 2;
2128
2129                         s->session->master_key_length=
2130                                 s->method->ssl3_enc->generate_master_secret(s,
2131                                         s->session->master_key,
2132                                         tmp_buf, sizeof tmp_buf);
2133
2134                         OPENSSL_cleanse(tmp_buf, sizeof tmp_buf);
2135                         OPENSSL_cleanse(epms, outl);
2136                         }
2137 #endif
2138 #ifndef OPENSSL_NO_DH
2139                 else if (alg_k & (SSL_kEDH|SSL_kDHr|SSL_kDHd))
2140                         {
2141                         DH *dh_srvr,*dh_clnt;
2142
2143                         if (s->session->sess_cert->peer_dh_tmp != NULL)
2144                                 dh_srvr=s->session->sess_cert->peer_dh_tmp;
2145                         else
2146                                 {
2147                                 /* we get them from the cert */
2148                                 ssl3_send_alert(s,SSL3_AL_FATAL,SSL_AD_HANDSHAKE_FAILURE);
2149                                 SSLerr(SSL_F_SSL3_SEND_CLIENT_KEY_EXCHANGE,SSL_R_UNABLE_TO_FIND_DH_PARAMETERS);
2150                                 goto err;
2151                                 }
2152                         
2153                         /* generate a new random key */
2154                         if ((dh_clnt=DHparams_dup(dh_srvr)) == NULL)
2155                                 {
2156                                 SSLerr(SSL_F_SSL3_SEND_CLIENT_KEY_EXCHANGE,ERR_R_DH_LIB);
2157                                 goto err;
2158                                 }
2159                         if (!DH_generate_key(dh_clnt))
2160                                 {
2161                                 SSLerr(SSL_F_SSL3_SEND_CLIENT_KEY_EXCHANGE,ERR_R_DH_LIB);
2162                                 goto err;
2163                                 }
2164
2165                         /* use the 'p' output buffer for the DH key, but
2166                          * make sure to clear it out afterwards */
2167
2168                         n=DH_compute_key(p,dh_srvr->pub_key,dh_clnt);
2169
2170                         if (n <= 0)
2171                                 {
2172                                 SSLerr(SSL_F_SSL3_SEND_CLIENT_KEY_EXCHANGE,ERR_R_DH_LIB);
2173                                 goto err;
2174                                 }
2175
2176                         /* generate master key from the result */
2177                         s->session->master_key_length=
2178                                 s->method->ssl3_enc->generate_master_secret(s,
2179                                         s->session->master_key,p,n);
2180                         /* clean up */
2181                         memset(p,0,n);
2182
2183                         /* send off the data */
2184                         n=BN_num_bytes(dh_clnt->pub_key);
2185                         s2n(n,p);
2186                         BN_bn2bin(dh_clnt->pub_key,p);
2187                         n+=2;
2188
2189                         DH_free(dh_clnt);
2190
2191                         /* perhaps clean things up a bit EAY EAY EAY EAY*/
2192                         }
2193 #endif
2194
2195 #ifndef OPENSSL_NO_ECDH 
2196                 else if (alg_k & (SSL_kEECDH|SSL_kECDHr|SSL_kECDHe))
2197                         {
2198                         const EC_GROUP *srvr_group = NULL;
2199                         EC_KEY *tkey;
2200                         int ecdh_clnt_cert = 0;
2201                         int field_size = 0;
2202
2203                         /* Did we send out the client's
2204                          * ECDH share for use in premaster
2205                          * computation as part of client certificate?
2206                          * If so, set ecdh_clnt_cert to 1.
2207                          */
2208                         if ((alg_k & (SSL_kECDHr|SSL_kECDHe)) && (s->cert != NULL)) 
2209                                 {
2210                                 /* XXX: For now, we do not support client
2211                                  * authentication using ECDH certificates.
2212                                  * To add such support, one needs to add
2213                                  * code that checks for appropriate 
2214                                  * conditions and sets ecdh_clnt_cert to 1.
2215                                  * For example, the cert have an ECC
2216                                  * key on the same curve as the server's
2217                                  * and the key should be authorized for
2218                                  * key agreement.
2219                                  *
2220                                  * One also needs to add code in ssl3_connect
2221                                  * to skip sending the certificate verify
2222                                  * message.
2223                                  *
2224                                  * if ((s->cert->key->privatekey != NULL) &&
2225                                  *     (s->cert->key->privatekey->type ==
2226                                  *      EVP_PKEY_EC) && ...)
2227                                  * ecdh_clnt_cert = 1;
2228                                  */
2229                                 }
2230
2231                         if (s->session->sess_cert->peer_ecdh_tmp != NULL)
2232                                 {
2233                                 tkey = s->session->sess_cert->peer_ecdh_tmp;
2234                                 }
2235                         else
2236                                 {
2237                                 /* Get the Server Public Key from Cert */
2238                                 srvr_pub_pkey = X509_get_pubkey(s->session-> \
2239                                     sess_cert->peer_pkeys[SSL_PKEY_ECC].x509);
2240                                 if ((srvr_pub_pkey == NULL) ||
2241                                     (srvr_pub_pkey->type != EVP_PKEY_EC) ||
2242                                     (srvr_pub_pkey->pkey.ec == NULL))
2243                                         {
2244                                         SSLerr(SSL_F_SSL3_SEND_CLIENT_KEY_EXCHANGE,
2245                                             ERR_R_INTERNAL_ERROR);
2246                                         goto err;
2247                                         }
2248
2249                                 tkey = srvr_pub_pkey->pkey.ec;
2250                                 }
2251
2252                         srvr_group   = EC_KEY_get0_group(tkey);
2253                         srvr_ecpoint = EC_KEY_get0_public_key(tkey);
2254
2255                         if ((srvr_group == NULL) || (srvr_ecpoint == NULL))
2256                                 {
2257                                 SSLerr(SSL_F_SSL3_SEND_CLIENT_KEY_EXCHANGE,
2258                                     ERR_R_INTERNAL_ERROR);
2259                                 goto err;
2260                                 }
2261
2262                         if ((clnt_ecdh=EC_KEY_new()) == NULL) 
2263                                 {
2264                                 SSLerr(SSL_F_SSL3_SEND_CLIENT_KEY_EXCHANGE,ERR_R_MALLOC_FAILURE);
2265                                 goto err;
2266                                 }
2267
2268                         if (!EC_KEY_set_group(clnt_ecdh, srvr_group))
2269                                 {
2270                                 SSLerr(SSL_F_SSL3_SEND_CLIENT_KEY_EXCHANGE,ERR_R_EC_LIB);
2271                                 goto err;
2272                                 }
2273                         if (ecdh_clnt_cert) 
2274                                 { 
2275                                 /* Reuse key info from our certificate
2276                                  * We only need our private key to perform
2277                                  * the ECDH computation.
2278                                  */
2279                                 const BIGNUM *priv_key;
2280                                 tkey = s->cert->key->privatekey->pkey.ec;
2281                                 priv_key = EC_KEY_get0_private_key(tkey);
2282                                 if (priv_key == NULL)
2283                                         {
2284                                         SSLerr(SSL_F_SSL3_SEND_CLIENT_KEY_EXCHANGE,ERR_R_MALLOC_FAILURE);
2285                                         goto err;
2286                                         }
2287                                 if (!EC_KEY_set_private_key(clnt_ecdh, priv_key))
2288                                         {
2289                                         SSLerr(SSL_F_SSL3_SEND_CLIENT_KEY_EXCHANGE,ERR_R_EC_LIB);
2290                                         goto err;
2291                                         }
2292                                 }
2293                         else 
2294                                 {
2295                                 /* Generate a new ECDH key pair */
2296                                 if (!(EC_KEY_generate_key(clnt_ecdh)))
2297                                         {
2298                                         SSLerr(SSL_F_SSL3_SEND_CLIENT_KEY_EXCHANGE, ERR_R_ECDH_LIB);
2299                                         goto err;
2300                                         }
2301                                 }
2302
2303                         /* use the 'p' output buffer for the ECDH key, but
2304                          * make sure to clear it out afterwards
2305                          */
2306
2307                         field_size = EC_GROUP_get_degree(srvr_group);
2308                         if (field_size <= 0)
2309                                 {
2310                                 SSLerr(SSL_F_SSL3_SEND_CLIENT_KEY_EXCHANGE, 
2311                                        ERR_R_ECDH_LIB);
2312                                 goto err;
2313                                 }
2314                         n=ECDH_compute_key(p, (field_size+7)/8, srvr_ecpoint, clnt_ecdh, NULL);
2315                         if (n <= 0)
2316                                 {
2317                                 SSLerr(SSL_F_SSL3_SEND_CLIENT_KEY_EXCHANGE, 
2318                                        ERR_R_ECDH_LIB);
2319                                 goto err;
2320                                 }
2321
2322                         /* generate master key from the result */
2323                         s->session->master_key_length = s->method->ssl3_enc \
2324                             -> generate_master_secret(s, 
2325                                 s->session->master_key,
2326                                 p, n);
2327
2328                         memset(p, 0, n); /* clean up */
2329
2330                         if (ecdh_clnt_cert) 
2331                                 {
2332                                 /* Send empty client key exch message */
2333                                 n = 0;
2334                                 }
2335                         else 
2336                                 {
2337                                 /* First check the size of encoding and
2338                                  * allocate memory accordingly.
2339                                  */
2340                                 encoded_pt_len = 
2341                                     EC_POINT_point2oct(srvr_group, 
2342                                         EC_KEY_get0_public_key(clnt_ecdh), 
2343                                         POINT_CONVERSION_UNCOMPRESSED, 
2344                                         NULL, 0, NULL);
2345
2346                                 encodedPoint = (unsigned char *) 
2347                                     OPENSSL_malloc(encoded_pt_len * 
2348                                         sizeof(unsigned char)); 
2349                                 bn_ctx = BN_CTX_new();
2350                                 if ((encodedPoint == NULL) || 
2351                                     (bn_ctx == NULL)) 
2352                                         {
2353                                         SSLerr(SSL_F_SSL3_SEND_CLIENT_KEY_EXCHANGE,ERR_R_MALLOC_FAILURE);
2354                                         goto err;
2355                                         }
2356
2357                                 /* Encode the public key */
2358                                 n = EC_POINT_point2oct(srvr_group, 
2359                                     EC_KEY_get0_public_key(clnt_ecdh), 
2360                                     POINT_CONVERSION_UNCOMPRESSED, 
2361                                     encodedPoint, encoded_pt_len, bn_ctx);
2362
2363                                 *p = n; /* length of encoded point */
2364                                 /* Encoded point will be copied here */
2365                                 p += 1; 
2366                                 /* copy the point */
2367                                 memcpy((unsigned char *)p, encodedPoint, n);
2368                                 /* increment n to account for length field */
2369                                 n += 1; 
2370                                 }
2371
2372                         /* Free allocated memory */
2373                         BN_CTX_free(bn_ctx);
2374                         if (encodedPoint != NULL) OPENSSL_free(encodedPoint);
2375                         if (clnt_ecdh != NULL) 
2376                                  EC_KEY_free(clnt_ecdh);
2377                         EVP_PKEY_free(srvr_pub_pkey);
2378                         }
2379 #endif /* !OPENSSL_NO_ECDH */
2380 #ifndef OPENSSL_NO_PSK
2381                 else if (alg_k & SSL_kPSK)
2382                         {
2383                         char identity[PSK_MAX_IDENTITY_LEN];
2384                         unsigned char *t = NULL;
2385                         unsigned char psk_or_pre_ms[PSK_MAX_PSK_LEN*2+4];
2386                         unsigned int pre_ms_len = 0, psk_len = 0;
2387                         int psk_err = 1;
2388
2389                         n = 0;
2390                         if (s->psk_client_callback == NULL)
2391                                 {
2392                                 SSLerr(SSL_F_SSL3_SEND_CLIENT_KEY_EXCHANGE,
2393                                         SSL_R_PSK_NO_CLIENT_CB);
2394                                 goto err;
2395                                 }
2396
2397                         psk_len = s->psk_client_callback(s, s->ctx->psk_identity_hint,
2398                                 identity, PSK_MAX_IDENTITY_LEN,
2399                                 psk_or_pre_ms, sizeof(psk_or_pre_ms));
2400                         if (psk_len > PSK_MAX_PSK_LEN)
2401                                 {
2402                                 SSLerr(SSL_F_SSL3_SEND_CLIENT_KEY_EXCHANGE,
2403                                         ERR_R_INTERNAL_ERROR);
2404                                 goto psk_err;
2405                                 }
2406                         else if (psk_len == 0)
2407                                 {
2408                                 SSLerr(SSL_F_SSL3_SEND_CLIENT_KEY_EXCHANGE,
2409                                         SSL_R_PSK_IDENTITY_NOT_FOUND);
2410                                 goto psk_err;
2411                                 }
2412
2413                         /* create PSK pre_master_secret */
2414                         pre_ms_len = 2+psk_len+2+psk_len;
2415                         t = psk_or_pre_ms;
2416                         memmove(psk_or_pre_ms+psk_len+4, psk_or_pre_ms, psk_len);
2417                         s2n(psk_len, t);
2418                         memset(t, 0, psk_len);
2419                         t+=psk_len;
2420                         s2n(psk_len, t);
2421
2422                         if (s->session->psk_identity_hint != NULL)
2423                                 OPENSSL_free(s->session->psk_identity_hint);
2424                         s->session->psk_identity_hint = BUF_strdup(s->ctx->psk_identity_hint);
2425                         if (s->ctx->psk_identity_hint != NULL &&
2426                                 s->session->psk_identity_hint == NULL)
2427                                 {
2428                                 SSLerr(SSL_F_SSL3_SEND_CLIENT_KEY_EXCHANGE,
2429                                         ERR_R_MALLOC_FAILURE);
2430                                 goto psk_err;
2431                                 }
2432
2433                         if (s->session->psk_identity != NULL)
2434                                 OPENSSL_free(s->session->psk_identity);
2435                         s->session->psk_identity = BUF_strdup(identity);
2436                         if (s->session->psk_identity == NULL)
2437                                 {
2438                                 SSLerr(SSL_F_SSL3_SEND_CLIENT_KEY_EXCHANGE,
2439                                         ERR_R_MALLOC_FAILURE);
2440                                 goto psk_err;
2441                                 }
2442
2443                         s->session->master_key_length =
2444                                 s->method->ssl3_enc->generate_master_secret(s,
2445                                         s->session->master_key,
2446                                         psk_or_pre_ms, pre_ms_len); 
2447                         n = strlen(identity);
2448                         s2n(n, p);
2449                         memcpy(p, identity, n);
2450                         n+=2;
2451                         psk_err = 0;
2452                 psk_err:
2453                         OPENSSL_cleanse(identity, PSK_MAX_IDENTITY_LEN);
2454                         OPENSSL_cleanse(psk_or_pre_ms, sizeof(psk_or_pre_ms));
2455                         if (psk_err != 0)
2456                                 {
2457                                 ssl3_send_alert(s, SSL3_AL_FATAL, SSL_AD_HANDSHAKE_FAILURE);
2458                                 goto err;
2459                                 }
2460                         }
2461 #endif
2462                 else
2463                         {
2464                         ssl3_send_alert(s, SSL3_AL_FATAL,
2465                             SSL_AD_HANDSHAKE_FAILURE);
2466                         SSLerr(SSL_F_SSL3_SEND_CLIENT_KEY_EXCHANGE,
2467                             ERR_R_INTERNAL_ERROR);
2468                         goto err;
2469                         }
2470                 
2471                 *(d++)=SSL3_MT_CLIENT_KEY_EXCHANGE;
2472                 l2n3(n,d);
2473
2474                 s->state=SSL3_ST_CW_KEY_EXCH_B;
2475                 /* number of bytes to write */
2476                 s->init_num=n+4;
2477                 s->init_off=0;
2478                 }
2479
2480         /* SSL3_ST_CW_KEY_EXCH_B */
2481         return(ssl3_do_write(s,SSL3_RT_HANDSHAKE));
2482 err:
2483 #ifndef OPENSSL_NO_ECDH
2484         BN_CTX_free(bn_ctx);
2485         if (encodedPoint != NULL) OPENSSL_free(encodedPoint);
2486         if (clnt_ecdh != NULL) 
2487                 EC_KEY_free(clnt_ecdh);
2488         EVP_PKEY_free(srvr_pub_pkey);
2489 #endif
2490         return(-1);
2491         }
2492
2493 int ssl3_send_client_verify(SSL *s)
2494         {
2495         unsigned char *p,*d;
2496         unsigned char data[MD5_DIGEST_LENGTH+SHA_DIGEST_LENGTH];
2497         EVP_PKEY *pkey;
2498 #ifndef OPENSSL_NO_RSA
2499         unsigned u=0;
2500 #endif
2501         unsigned long n;
2502 #if !defined(OPENSSL_NO_DSA) || !defined(OPENSSL_NO_ECDSA)
2503         int j;
2504 #endif
2505
2506         if (s->state == SSL3_ST_CW_CERT_VRFY_A)
2507                 {
2508                 d=(unsigned char *)s->init_buf->data;
2509                 p= &(d[4]);
2510                 pkey=s->cert->key->privatekey;
2511
2512                 s->method->ssl3_enc->cert_verify_mac(s,
2513                         NID_sha1,
2514                         &(data[MD5_DIGEST_LENGTH]));
2515
2516 #ifndef OPENSSL_NO_RSA
2517                 if (pkey->type == EVP_PKEY_RSA)
2518                         {
2519                         s->method->ssl3_enc->cert_verify_mac(s,
2520                                 NID_md5,
2521                                 &(data[0]));
2522                         if (RSA_sign(NID_md5_sha1, data,
2523                                          MD5_DIGEST_LENGTH+SHA_DIGEST_LENGTH,
2524                                         &(p[2]), &u, pkey->pkey.rsa) <= 0 )
2525                                 {
2526                                 SSLerr(SSL_F_SSL3_SEND_CLIENT_VERIFY,ERR_R_RSA_LIB);
2527                                 goto err;
2528                                 }
2529                         s2n(u,p);
2530                         n=u+2;
2531                         }
2532                 else
2533 #endif
2534 #ifndef OPENSSL_NO_DSA
2535                         if (pkey->type == EVP_PKEY_DSA)
2536                         {
2537                         if (!DSA_sign(pkey->save_type,
2538                                 &(data[MD5_DIGEST_LENGTH]),
2539                                 SHA_DIGEST_LENGTH,&(p[2]),
2540                                 (unsigned int *)&j,pkey->pkey.dsa))
2541                                 {
2542                                 SSLerr(SSL_F_SSL3_SEND_CLIENT_VERIFY,ERR_R_DSA_LIB);
2543                                 goto err;
2544                                 }
2545                         s2n(j,p);
2546                         n=j+2;
2547                         }
2548                 else
2549 #endif
2550 #ifndef OPENSSL_NO_ECDSA
2551                         if (pkey->type == EVP_PKEY_EC)
2552                         {
2553                         if (!ECDSA_sign(pkey->save_type,
2554                                 &(data[MD5_DIGEST_LENGTH]),
2555                                 SHA_DIGEST_LENGTH,&(p[2]),
2556                                 (unsigned int *)&j,pkey->pkey.ec))
2557                                 {
2558                                 SSLerr(SSL_F_SSL3_SEND_CLIENT_VERIFY,
2559                                     ERR_R_ECDSA_LIB);
2560                                 goto err;
2561                                 }
2562                         s2n(j,p);
2563                         n=j+2;
2564                         }
2565                 else
2566 #endif
2567                         {
2568                         SSLerr(SSL_F_SSL3_SEND_CLIENT_VERIFY,ERR_R_INTERNAL_ERROR);
2569                         goto err;
2570                         }
2571                 *(d++)=SSL3_MT_CERTIFICATE_VERIFY;
2572                 l2n3(n,d);
2573
2574                 s->state=SSL3_ST_CW_CERT_VRFY_B;
2575                 s->init_num=(int)n+4;
2576                 s->init_off=0;
2577                 }
2578         return(ssl3_do_write(s,SSL3_RT_HANDSHAKE));
2579 err:
2580         return(-1);
2581         }
2582
2583 int ssl3_send_client_certificate(SSL *s)
2584         {
2585         X509 *x509=NULL;
2586         EVP_PKEY *pkey=NULL;
2587         int i;
2588         unsigned long l;
2589
2590         if (s->state == SSL3_ST_CW_CERT_A)
2591                 {
2592                 if ((s->cert == NULL) ||
2593                         (s->cert->key->x509 == NULL) ||
2594                         (s->cert->key->privatekey == NULL))
2595                         s->state=SSL3_ST_CW_CERT_B;
2596                 else
2597                         s->state=SSL3_ST_CW_CERT_C;
2598                 }
2599
2600         /* We need to get a client cert */
2601         if (s->state == SSL3_ST_CW_CERT_B)
2602                 {
2603                 /* If we get an error, we need to
2604                  * ssl->rwstate=SSL_X509_LOOKUP; return(-1);
2605                  * We then get retied later */
2606                 i=0;
2607                 if (s->ctx->client_cert_cb != NULL)
2608                         i=s->ctx->client_cert_cb(s,&(x509),&(pkey));
2609                 if (i < 0)
2610                         {
2611                         s->rwstate=SSL_X509_LOOKUP;
2612                         return(-1);
2613                         }
2614                 s->rwstate=SSL_NOTHING;
2615                 if ((i == 1) && (pkey != NULL) && (x509 != NULL))
2616                         {
2617                         s->state=SSL3_ST_CW_CERT_B;
2618                         if (    !SSL_use_certificate(s,x509) ||
2619                                 !SSL_use_PrivateKey(s,pkey))
2620                                 i=0;
2621                         }
2622                 else if (i == 1)
2623                         {
2624                         i=0;
2625                         SSLerr(SSL_F_SSL3_SEND_CLIENT_CERTIFICATE,SSL_R_BAD_DATA_RETURNED_BY_CALLBACK);
2626                         }
2627
2628                 if (x509 != NULL) X509_free(x509);
2629                 if (pkey != NULL) EVP_PKEY_free(pkey);
2630                 if (i == 0)
2631                         {
2632                         if (s->version == SSL3_VERSION)
2633                                 {
2634                                 s->s3->tmp.cert_req=0;
2635                                 ssl3_send_alert(s,SSL3_AL_WARNING,SSL_AD_NO_CERTIFICATE);
2636                                 return(1);
2637                                 }
2638                         else
2639                                 {
2640                                 s->s3->tmp.cert_req=2;
2641                                 }
2642                         }
2643
2644                 /* Ok, we have a cert */
2645                 s->state=SSL3_ST_CW_CERT_C;
2646                 }
2647
2648         if (s->state == SSL3_ST_CW_CERT_C)
2649                 {
2650                 s->state=SSL3_ST_CW_CERT_D;
2651                 l=ssl3_output_cert_chain(s,
2652                         (s->s3->tmp.cert_req == 2)?NULL:s->cert->key->x509);
2653                 s->init_num=(int)l;
2654                 s->init_off=0;
2655                 }
2656         /* SSL3_ST_CW_CERT_D */
2657         return(ssl3_do_write(s,SSL3_RT_HANDSHAKE));
2658         }
2659
2660 #define has_bits(i,m)   (((i)&(m)) == (m))
2661
2662 int ssl3_check_cert_and_algorithm(SSL *s)
2663         {
2664         int i,idx;
2665         long alg_k,alg_a;
2666         EVP_PKEY *pkey=NULL;
2667         SESS_CERT *sc;
2668 #ifndef OPENSSL_NO_RSA
2669         RSA *rsa;
2670 #endif
2671 #ifndef OPENSSL_NO_DH
2672         DH *dh;
2673 #endif
2674
2675         sc=s->session->sess_cert;
2676         if (sc == NULL)
2677                 {
2678                 SSLerr(SSL_F_SSL3_CHECK_CERT_AND_ALGORITHM,ERR_R_INTERNAL_ERROR);
2679                 goto err;
2680                 }
2681
2682         alg_k=s->s3->tmp.new_cipher->algorithm_mkey;
2683         alg_a=s->s3->tmp.new_cipher->algorithm_auth;
2684
2685         /* we don't have a certificate */
2686         if ((alg_a & (SSL_aDH|SSL_aNULL|SSL_aKRB5)) || (alg_k & SSL_kPSK))
2687                 return(1);
2688
2689 #ifndef OPENSSL_NO_RSA
2690         rsa=s->session->sess_cert->peer_rsa_tmp;
2691 #endif
2692 #ifndef OPENSSL_NO_DH
2693         dh=s->session->sess_cert->peer_dh_tmp;
2694 #endif
2695
2696         /* This is the passed certificate */
2697
2698         idx=sc->peer_cert_type;
2699 #ifndef OPENSSL_NO_ECDH
2700         if (idx == SSL_PKEY_ECC)
2701                 {
2702                 if (ssl_check_srvr_ecc_cert_and_alg(sc->peer_pkeys[idx].x509,
2703                     s->s3->tmp.new_cipher) == 0) 
2704                         { /* check failed */
2705                         SSLerr(SSL_F_SSL3_CHECK_CERT_AND_ALGORITHM,SSL_R_BAD_ECC_CERT);
2706                         goto f_err;
2707                         }
2708                 else 
2709                         {
2710                         return 1;
2711                         }
2712                 }
2713 #endif
2714         pkey=X509_get_pubkey(sc->peer_pkeys[idx].x509);
2715         i=X509_certificate_type(sc->peer_pkeys[idx].x509,pkey);
2716         EVP_PKEY_free(pkey);
2717
2718         
2719         /* Check that we have a certificate if we require one */
2720         if ((alg_a & SSL_aRSA) && !has_bits(i,EVP_PK_RSA|EVP_PKT_SIGN))
2721                 {
2722                 SSLerr(SSL_F_SSL3_CHECK_CERT_AND_ALGORITHM,SSL_R_MISSING_RSA_SIGNING_CERT);
2723                 goto f_err;
2724                 }
2725 #ifndef OPENSSL_NO_DSA
2726         else if ((alg_a & SSL_aDSS) && !has_bits(i,EVP_PK_DSA|EVP_PKT_SIGN))
2727                 {
2728                 SSLerr(SSL_F_SSL3_CHECK_CERT_AND_ALGORITHM,SSL_R_MISSING_DSA_SIGNING_CERT);
2729                 goto f_err;
2730                 }
2731 #endif
2732 #ifndef OPENSSL_NO_RSA
2733         if ((alg_k & SSL_kRSA) &&
2734                 !(has_bits(i,EVP_PK_RSA|EVP_PKT_ENC) || (rsa != NULL)))
2735                 {
2736                 SSLerr(SSL_F_SSL3_CHECK_CERT_AND_ALGORITHM,SSL_R_MISSING_RSA_ENCRYPTING_CERT);
2737                 goto f_err;
2738                 }
2739 #endif
2740 #ifndef OPENSSL_NO_DH
2741         if ((alg_k & SSL_kEDH) &&
2742                 !(has_bits(i,EVP_PK_DH|EVP_PKT_EXCH) || (dh != NULL)))
2743                 {
2744                 SSLerr(SSL_F_SSL3_CHECK_CERT_AND_ALGORITHM,SSL_R_MISSING_DH_KEY);
2745                 goto f_err;
2746                 }
2747         else if ((alg_k & SSL_kDHr) && !has_bits(i,EVP_PK_DH|EVP_PKS_RSA))
2748                 {
2749                 SSLerr(SSL_F_SSL3_CHECK_CERT_AND_ALGORITHM,SSL_R_MISSING_DH_RSA_CERT);
2750                 goto f_err;
2751                 }
2752 #ifndef OPENSSL_NO_DSA
2753         else if ((alg_k & SSL_kDHd) && !has_bits(i,EVP_PK_DH|EVP_PKS_DSA))
2754                 {
2755                 SSLerr(SSL_F_SSL3_CHECK_CERT_AND_ALGORITHM,SSL_R_MISSING_DH_DSA_CERT);
2756                 goto f_err;
2757                 }
2758 #endif
2759 #endif
2760
2761         if (SSL_C_IS_EXPORT(s->s3->tmp.new_cipher) && !has_bits(i,EVP_PKT_EXP))
2762                 {
2763 #ifndef OPENSSL_NO_RSA
2764                 if (alg_k & SSL_kRSA)
2765                         {
2766                         if (rsa == NULL
2767                             || RSA_size(rsa)*8 > SSL_C_EXPORT_PKEYLENGTH(s->s3->tmp.new_cipher))
2768                                 {
2769                                 SSLerr(SSL_F_SSL3_CHECK_CERT_AND_ALGORITHM,SSL_R_MISSING_EXPORT_TMP_RSA_KEY);
2770                                 goto f_err;
2771                                 }
2772                         }
2773                 else
2774 #endif
2775 #ifndef OPENSSL_NO_DH
2776                         if (alg_k & (SSL_kEDH|SSL_kDHr|SSL_kDHd))
2777                             {
2778                             if (dh == NULL
2779                                 || DH_size(dh)*8 > SSL_C_EXPORT_PKEYLENGTH(s->s3->tmp.new_cipher))
2780                                 {
2781                                 SSLerr(SSL_F_SSL3_CHECK_CERT_AND_ALGORITHM,SSL_R_MISSING_EXPORT_TMP_DH_KEY);
2782                                 goto f_err;
2783                                 }
2784                         }
2785                 else
2786 #endif
2787                         {
2788                         SSLerr(SSL_F_SSL3_CHECK_CERT_AND_ALGORITHM,SSL_R_UNKNOWN_KEY_EXCHANGE_TYPE);
2789                         goto f_err;
2790                         }
2791                 }
2792         return(1);
2793 f_err:
2794         ssl3_send_alert(s,SSL3_AL_FATAL,SSL_AD_HANDSHAKE_FAILURE);
2795 err:
2796         return(0);
2797         }
2798
2799 /* Check to see if handshake is full or resumed. Usually this is just a
2800  * case of checking to see if a cache hit has occurred. In the case of
2801  * session tickets we have to check the next message to be sure.
2802  */
2803
2804 #ifndef OPENSSL_NO_TLSEXT
2805 static int ssl3_check_finished(SSL *s)
2806         {
2807         int ok;
2808         long n;
2809         if (!s->session->tlsext_tick)
2810                 return 1;
2811         /* this function is called when we really expect a Certificate
2812          * message, so permit appropriate message length */
2813         n=s->method->ssl_get_message(s,
2814                 SSL3_ST_CR_CERT_A,
2815                 SSL3_ST_CR_CERT_B,
2816                 -1,
2817                 s->max_cert_list,
2818                 &ok);
2819         if (!ok) return((int)n);
2820         s->s3->tmp.reuse_message = 1;
2821         if ((s->s3->tmp.message_type == SSL3_MT_FINISHED)
2822                 || (s->s3->tmp.message_type == SSL3_MT_NEWSESSION_TICKET))
2823                 return 2;
2824
2825         return 1;
2826         }
2827 #endif