New option to enable/disable connection to unpatched servers
[openssl.git] / ssl / d1_clnt.c
1 /* ssl/d1_clnt.c */
2 /* 
3  * DTLS implementation written by Nagendra Modadugu
4  * (nagendra@cs.stanford.edu) for the OpenSSL project 2005.  
5  */
6 /* ====================================================================
7  * Copyright (c) 1999-2007 The OpenSSL Project.  All rights reserved.
8  *
9  * Redistribution and use in source and binary forms, with or without
10  * modification, are permitted provided that the following conditions
11  * are met:
12  *
13  * 1. Redistributions of source code must retain the above copyright
14  *    notice, this list of conditions and the following disclaimer. 
15  *
16  * 2. Redistributions in binary form must reproduce the above copyright
17  *    notice, this list of conditions and the following disclaimer in
18  *    the documentation and/or other materials provided with the
19  *    distribution.
20  *
21  * 3. All advertising materials mentioning features or use of this
22  *    software must display the following acknowledgment:
23  *    "This product includes software developed by the OpenSSL Project
24  *    for use in the OpenSSL Toolkit. (http://www.OpenSSL.org/)"
25  *
26  * 4. The names "OpenSSL Toolkit" and "OpenSSL Project" must not be used to
27  *    endorse or promote products derived from this software without
28  *    prior written permission. For written permission, please contact
29  *    openssl-core@OpenSSL.org.
30  *
31  * 5. Products derived from this software may not be called "OpenSSL"
32  *    nor may "OpenSSL" appear in their names without prior written
33  *    permission of the OpenSSL Project.
34  *
35  * 6. Redistributions of any form whatsoever must retain the following
36  *    acknowledgment:
37  *    "This product includes software developed by the OpenSSL Project
38  *    for use in the OpenSSL Toolkit (http://www.OpenSSL.org/)"
39  *
40  * THIS SOFTWARE IS PROVIDED BY THE OpenSSL PROJECT ``AS IS'' AND ANY
41  * EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
42  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
43  * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE OpenSSL PROJECT OR
44  * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
45  * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
46  * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
47  * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
48  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
49  * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
50  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
51  * OF THE POSSIBILITY OF SUCH DAMAGE.
52  * ====================================================================
53  *
54  * This product includes cryptographic software written by Eric Young
55  * (eay@cryptsoft.com).  This product includes software written by Tim
56  * Hudson (tjh@cryptsoft.com).
57  *
58  */
59 /* Copyright (C) 1995-1998 Eric Young (eay@cryptsoft.com)
60  * All rights reserved.
61  *
62  * This package is an SSL implementation written
63  * by Eric Young (eay@cryptsoft.com).
64  * The implementation was written so as to conform with Netscapes SSL.
65  * 
66  * This library is free for commercial and non-commercial use as long as
67  * the following conditions are aheared to.  The following conditions
68  * apply to all code found in this distribution, be it the RC4, RSA,
69  * lhash, DES, etc., code; not just the SSL code.  The SSL documentation
70  * included with this distribution is covered by the same copyright terms
71  * except that the holder is Tim Hudson (tjh@cryptsoft.com).
72  * 
73  * Copyright remains Eric Young's, and as such any Copyright notices in
74  * the code are not to be removed.
75  * If this package is used in a product, Eric Young should be given attribution
76  * as the author of the parts of the library used.
77  * This can be in the form of a textual message at program startup or
78  * in documentation (online or textual) provided with the package.
79  * 
80  * Redistribution and use in source and binary forms, with or without
81  * modification, are permitted provided that the following conditions
82  * are met:
83  * 1. Redistributions of source code must retain the copyright
84  *    notice, this list of conditions and the following disclaimer.
85  * 2. Redistributions in binary form must reproduce the above copyright
86  *    notice, this list of conditions and the following disclaimer in the
87  *    documentation and/or other materials provided with the distribution.
88  * 3. All advertising materials mentioning features or use of this software
89  *    must display the following acknowledgement:
90  *    "This product includes cryptographic software written by
91  *     Eric Young (eay@cryptsoft.com)"
92  *    The word 'cryptographic' can be left out if the rouines from the library
93  *    being used are not cryptographic related :-).
94  * 4. If you include any Windows specific code (or a derivative thereof) from 
95  *    the apps directory (application code) you must include an acknowledgement:
96  *    "This product includes software written by Tim Hudson (tjh@cryptsoft.com)"
97  * 
98  * THIS SOFTWARE IS PROVIDED BY ERIC YOUNG ``AS IS'' AND
99  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
100  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
101  * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
102  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
103  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
104  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
105  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
106  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
107  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
108  * SUCH DAMAGE.
109  * 
110  * The licence and distribution terms for any publically available version or
111  * derivative of this code cannot be changed.  i.e. this code cannot simply be
112  * copied and put under another distribution licence
113  * [including the GNU Public Licence.]
114  */
115
116 #include <stdio.h>
117 #include "ssl_locl.h"
118 #ifndef OPENSSL_NO_KRB5
119 #include "kssl_lcl.h"
120 #endif
121 #include <openssl/buffer.h>
122 #include <openssl/rand.h>
123 #include <openssl/objects.h>
124 #include <openssl/evp.h>
125 #include <openssl/md5.h>
126 #include <openssl/bn.h>
127 #ifndef OPENSSL_NO_DH
128 #include <openssl/dh.h>
129 #endif
130
131 static const SSL_METHOD *dtls1_get_client_method(int ver);
132 static int dtls1_get_hello_verify(SSL *s);
133
134 static const SSL_METHOD *dtls1_get_client_method(int ver)
135         {
136         if (ver == DTLS1_VERSION || ver == DTLS1_BAD_VER)
137                 return(DTLSv1_client_method());
138         else
139                 return(NULL);
140         }
141
142 IMPLEMENT_dtls1_meth_func(DTLSv1_client_method,
143                         ssl_undefined_function,
144                         dtls1_connect,
145                         dtls1_get_client_method)
146
147 int dtls1_connect(SSL *s)
148         {
149         BUF_MEM *buf=NULL;
150         unsigned long Time=(unsigned long)time(NULL);
151         long num1;
152         void (*cb)(const SSL *ssl,int type,int val)=NULL;
153         int ret= -1;
154         int new_state,state,skip=0;;
155
156         RAND_add(&Time,sizeof(Time),0);
157         ERR_clear_error();
158         clear_sys_error();
159
160         if (s->info_callback != NULL)
161                 cb=s->info_callback;
162         else if (s->ctx->info_callback != NULL)
163                 cb=s->ctx->info_callback;
164         
165         s->in_handshake++;
166         if (!SSL_in_init(s) || SSL_in_before(s)) SSL_clear(s); 
167
168         for (;;)
169                 {
170                 state=s->state;
171
172                 switch(s->state)
173                         {
174                 case SSL_ST_RENEGOTIATE:
175                         s->new_session=1;
176                         s->state=SSL_ST_CONNECT;
177                         s->ctx->stats.sess_connect_renegotiate++;
178                         /* break */
179                 case SSL_ST_BEFORE:
180                 case SSL_ST_CONNECT:
181                 case SSL_ST_BEFORE|SSL_ST_CONNECT:
182                 case SSL_ST_OK|SSL_ST_CONNECT:
183
184                         s->server=0;
185                         if (cb != NULL) cb(s,SSL_CB_HANDSHAKE_START,1);
186
187                         if ((s->version & 0xff00 ) != (DTLS1_VERSION & 0xff00) &&
188                             (s->version & 0xff00 ) != (DTLS1_BAD_VER & 0xff00))
189                                 {
190                                 SSLerr(SSL_F_DTLS1_CONNECT, ERR_R_INTERNAL_ERROR);
191                                 ret = -1;
192                                 goto end;
193                                 }
194                                 
195                         /* s->version=SSL3_VERSION; */
196                         s->type=SSL_ST_CONNECT;
197
198                         if (s->init_buf == NULL)
199                                 {
200                                 if ((buf=BUF_MEM_new()) == NULL)
201                                         {
202                                         ret= -1;
203                                         goto end;
204                                         }
205                                 if (!BUF_MEM_grow(buf,SSL3_RT_MAX_PLAIN_LENGTH))
206                                         {
207                                         ret= -1;
208                                         goto end;
209                                         }
210                                 s->init_buf=buf;
211                                 buf=NULL;
212                                 }
213
214                         if (!ssl3_setup_buffers(s)) { ret= -1; goto end; }
215
216                         /* setup buffing BIO */
217                         if (!ssl_init_wbio_buffer(s,0)) { ret= -1; goto end; }
218
219                         /* don't push the buffering BIO quite yet */
220
221                         s->state=SSL3_ST_CW_CLNT_HELLO_A;
222                         s->ctx->stats.sess_connect++;
223                         s->init_num=0;
224                         /* mark client_random uninitialized */
225                         memset(s->s3->client_random,0,sizeof(s->s3->client_random));
226                         s->d1->send_cookie = 0;
227                         s->hit = 0;
228                         break;
229
230                 case SSL3_ST_CW_CLNT_HELLO_A:
231                 case SSL3_ST_CW_CLNT_HELLO_B:
232
233                         s->shutdown=0;
234
235                         /* every DTLS ClientHello resets Finished MAC */
236                         ssl3_init_finished_mac(s);
237
238                         dtls1_start_timer(s);
239                         ret=dtls1_client_hello(s);
240                         if (ret <= 0) goto end;
241
242                         if ( s->d1->send_cookie)
243                                 {
244                                 s->state=SSL3_ST_CW_FLUSH;
245                                 s->s3->tmp.next_state=SSL3_ST_CR_SRVR_HELLO_A;
246                                 }
247                         else
248                                 s->state=SSL3_ST_CR_SRVR_HELLO_A;
249
250                         s->init_num=0;
251
252                         /* turn on buffering for the next lot of output */
253                         if (s->bbio != s->wbio)
254                                 s->wbio=BIO_push(s->bbio,s->wbio);
255
256                         break;
257
258                 case SSL3_ST_CR_SRVR_HELLO_A:
259                 case SSL3_ST_CR_SRVR_HELLO_B:
260                         ret=ssl3_get_server_hello(s);
261                         if (ret <= 0) goto end;
262                         else
263                                 {
264                                 dtls1_stop_timer(s);
265                                 if (s->hit)
266                                         s->state=SSL3_ST_CR_FINISHED_A;
267                                 else
268                                         s->state=DTLS1_ST_CR_HELLO_VERIFY_REQUEST_A;
269                                 }
270                         s->init_num=0;
271                         break;
272
273                 case DTLS1_ST_CR_HELLO_VERIFY_REQUEST_A:
274                 case DTLS1_ST_CR_HELLO_VERIFY_REQUEST_B:
275
276                         ret = dtls1_get_hello_verify(s);
277                         if ( ret <= 0)
278                                 goto end;
279                         dtls1_stop_timer(s);
280                         if ( s->d1->send_cookie) /* start again, with a cookie */
281                                 s->state=SSL3_ST_CW_CLNT_HELLO_A;
282                         else
283                                 s->state = SSL3_ST_CR_CERT_A;
284                         s->init_num = 0;
285                         break;
286
287                 case SSL3_ST_CR_CERT_A:
288                 case SSL3_ST_CR_CERT_B:
289 #ifndef OPENSSL_NO_TLSEXT
290                         ret=ssl3_check_finished(s);
291                         if (ret <= 0) goto end;
292                         if (ret == 2)
293                                 {
294                                 s->hit = 1;
295                                 if (s->tlsext_ticket_expected)
296                                         s->state=SSL3_ST_CR_SESSION_TICKET_A;
297                                 else
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 or PSK */
304                         if (!(s->s3->tmp.new_cipher->algorithm_auth & SSL_aNULL) &&
305                             !(s->s3->tmp.new_cipher->algorithm_mkey & SSL_kPSK))
306                                 {
307                                 ret=ssl3_get_server_certificate(s);
308                                 if (ret <= 0) goto end;
309 #ifndef OPENSSL_NO_TLSEXT
310                                 if (s->tlsext_status_expected)
311                                         s->state=SSL3_ST_CR_CERT_STATUS_A;
312                                 else
313                                         s->state=SSL3_ST_CR_KEY_EXCH_A;
314                                 }
315                         else
316                                 {
317                                 skip = 1;
318                                 s->state=SSL3_ST_CR_KEY_EXCH_A;
319                                 }
320 #else
321                                 }
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                         dtls1_start_timer(s);
371                         ret=dtls1_send_client_certificate(s);
372                         if (ret <= 0) goto end;
373                         s->state=SSL3_ST_CW_KEY_EXCH_A;
374                         s->init_num=0;
375                         break;
376
377                 case SSL3_ST_CW_KEY_EXCH_A:
378                 case SSL3_ST_CW_KEY_EXCH_B:
379                         dtls1_start_timer(s);
380                         ret=dtls1_send_client_key_exchange(s);
381                         if (ret <= 0) goto end;
382                         /* EAY EAY EAY need to check for DH fix cert
383                          * sent back */
384                         /* For TLS, cert_req is set to 2, so a cert chain
385                          * of nothing is sent, but no verify packet is sent */
386                         if (s->s3->tmp.cert_req == 1)
387                                 {
388                                 s->state=SSL3_ST_CW_CERT_VRFY_A;
389                                 }
390                         else
391                                 {
392                                 s->state=SSL3_ST_CW_CHANGE_A;
393                                 s->s3->change_cipher_spec=0;
394                                 }
395
396                         s->init_num=0;
397                         break;
398
399                 case SSL3_ST_CW_CERT_VRFY_A:
400                 case SSL3_ST_CW_CERT_VRFY_B:
401                         dtls1_start_timer(s);
402                         ret=dtls1_send_client_verify(s);
403                         if (ret <= 0) goto end;
404                         s->state=SSL3_ST_CW_CHANGE_A;
405                         s->init_num=0;
406                         s->s3->change_cipher_spec=0;
407                         break;
408
409                 case SSL3_ST_CW_CHANGE_A:
410                 case SSL3_ST_CW_CHANGE_B:
411                         dtls1_start_timer(s);
412                         ret=dtls1_send_change_cipher_spec(s,
413                                 SSL3_ST_CW_CHANGE_A,SSL3_ST_CW_CHANGE_B);
414                         if (ret <= 0) goto end;
415                         s->state=SSL3_ST_CW_FINISHED_A;
416                         s->init_num=0;
417
418                         s->session->cipher=s->s3->tmp.new_cipher;
419 #ifdef OPENSSL_NO_COMP
420                         s->session->compress_meth=0;
421 #else
422                         if (s->s3->tmp.new_compression == NULL)
423                                 s->session->compress_meth=0;
424                         else
425                                 s->session->compress_meth=
426                                         s->s3->tmp.new_compression->id;
427 #endif
428                         if (!s->method->ssl3_enc->setup_key_block(s))
429                                 {
430                                 ret= -1;
431                                 goto end;
432                                 }
433
434                         if (!s->method->ssl3_enc->change_cipher_state(s,
435                                 SSL3_CHANGE_CIPHER_CLIENT_WRITE))
436                                 {
437                                 ret= -1;
438                                 goto end;
439                                 }
440                         
441                         dtls1_reset_seq_numbers(s, SSL3_CC_WRITE);
442                         break;
443
444                 case SSL3_ST_CW_FINISHED_A:
445                 case SSL3_ST_CW_FINISHED_B:
446                         dtls1_start_timer(s);
447                         ret=dtls1_send_finished(s,
448                                 SSL3_ST_CW_FINISHED_A,SSL3_ST_CW_FINISHED_B,
449                                 s->method->ssl3_enc->client_finished_label,
450                                 s->method->ssl3_enc->client_finished_label_len);
451                         if (ret <= 0) goto end;
452                         s->state=SSL3_ST_CW_FLUSH;
453
454                         /* clear flags */
455                         s->s3->flags&= ~SSL3_FLAGS_POP_BUFFER;
456                         if (s->hit)
457                                 {
458                                 s->s3->tmp.next_state=SSL_ST_OK;
459                                 if (s->s3->flags & SSL3_FLAGS_DELAY_CLIENT_FINISHED)
460                                         {
461                                         s->state=SSL_ST_OK;
462                                         s->s3->flags|=SSL3_FLAGS_POP_BUFFER;
463                                         s->s3->delay_buf_pop_ret=0;
464                                         }
465                                 }
466                         else
467                                 {
468 #ifndef OPENSSL_NO_TLSEXT
469                                 /* Allow NewSessionTicket if ticket expected */
470                                 if (s->tlsext_ticket_expected)
471                                         s->s3->tmp.next_state=SSL3_ST_CR_SESSION_TICKET_A;
472                                 else
473 #endif
474                                 
475                                 s->s3->tmp.next_state=SSL3_ST_CR_FINISHED_A;
476                                 }
477                         s->init_num=0;
478                         break;
479
480 #ifndef OPENSSL_NO_TLSEXT
481                 case SSL3_ST_CR_SESSION_TICKET_A:
482                 case SSL3_ST_CR_SESSION_TICKET_B:
483                         ret=ssl3_get_new_session_ticket(s);
484                         if (ret <= 0) goto end;
485                         s->state=SSL3_ST_CR_FINISHED_A;
486                         s->init_num=0;
487                 break;
488
489                 case SSL3_ST_CR_CERT_STATUS_A:
490                 case SSL3_ST_CR_CERT_STATUS_B:
491                         ret=ssl3_get_cert_status(s);
492                         if (ret <= 0) goto end;
493                         s->state=SSL3_ST_CR_KEY_EXCH_A;
494                         s->init_num=0;
495                 break;
496 #endif
497
498                 case SSL3_ST_CR_FINISHED_A:
499                 case SSL3_ST_CR_FINISHED_B:
500                         s->d1->change_cipher_spec_ok = 1;
501                         ret=ssl3_get_finished(s,SSL3_ST_CR_FINISHED_A,
502                                 SSL3_ST_CR_FINISHED_B);
503                         if (ret <= 0) goto end;
504                         dtls1_stop_timer(s);
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 0
532                         if (s->init_buf != NULL)
533                                 {
534                                 BUF_MEM_free(s->init_buf);
535                                 s->init_buf=NULL;
536                                 }
537 #endif
538
539                         /* If we are not 'joining' the last two packets,
540                          * remove the buffering now */
541                         if (!(s->s3->flags & SSL3_FLAGS_POP_BUFFER))
542                                 ssl_free_wbio_buffer(s);
543                         /* else do it later in ssl3_write */
544
545                         s->init_num=0;
546                         s->new_session=0;
547
548                         ssl_update_cache(s,SSL_SESS_CACHE_CLIENT);
549                         if (s->hit) s->ctx->stats.sess_hit++;
550
551                         ret=1;
552                         /* s->server=0; */
553                         s->handshake_func=dtls1_connect;
554                         s->ctx->stats.sess_connect_good++;
555
556                         if (cb != NULL) cb(s,SSL_CB_HANDSHAKE_DONE,1);
557
558                         /* done with handshaking */
559                         s->d1->handshake_read_seq  = 0;
560                         s->d1->next_handshake_write_seq = 0;
561                         goto end;
562                         /* break; */
563                         
564                 default:
565                         SSLerr(SSL_F_DTLS1_CONNECT,SSL_R_UNKNOWN_STATE);
566                         ret= -1;
567                         goto end;
568                         /* break; */
569                         }
570
571                 /* did we do anything */
572                 if (!s->s3->tmp.reuse_message && !skip)
573                         {
574                         if (s->debug)
575                                 {
576                                 if ((ret=BIO_flush(s->wbio)) <= 0)
577                                         goto end;
578                                 }
579
580                         if ((cb != NULL) && (s->state != state))
581                                 {
582                                 new_state=s->state;
583                                 s->state=state;
584                                 cb(s,SSL_CB_CONNECT_LOOP,1);
585                                 s->state=new_state;
586                                 }
587                         }
588                 skip=0;
589                 }
590 end:
591         s->in_handshake--;
592         if (buf != NULL)
593                 BUF_MEM_free(buf);
594         if (cb != NULL)
595                 cb(s,SSL_CB_CONNECT_EXIT,ret);
596         return(ret);
597         }
598
599 int dtls1_client_hello(SSL *s)
600         {
601         unsigned char *buf;
602         unsigned char *p,*d;
603         unsigned int i,j;
604         unsigned long Time,l;
605         SSL_COMP *comp;
606
607         buf=(unsigned char *)s->init_buf->data;
608         if (s->state == SSL3_ST_CW_CLNT_HELLO_A)
609                 {
610                 SSL_SESSION *sess = s->session;
611                 if ((s->session == NULL) ||
612                         (s->session->ssl_version != s->version) ||
613 #ifdef OPENSSL_NO_TLSEXT
614                         !sess->session_id_length ||
615 #else
616                         (!sess->session_id_length && !sess->tlsext_tick) ||
617 #endif
618                         (s->session->not_resumable))
619                         {
620                         if (!ssl_get_new_session(s,0))
621                                 goto err;
622                         }
623                 /* else use the pre-loaded session */
624
625                 p=s->s3->client_random;
626
627                 /* if client_random is initialized, reuse it, we are
628                  * required to use same upon reply to HelloVerify */
629                 for (i=0;p[i]=='\0' && i<sizeof(s->s3->client_random);i++) ;
630                 if (i==sizeof(s->s3->client_random))
631                         {
632                         Time=(unsigned long)time(NULL); /* Time */
633                         l2n(Time,p);
634                         RAND_pseudo_bytes(p,sizeof(s->s3->client_random)-4);
635                         }
636
637                 /* Do the message type and length last */
638                 d=p= &(buf[DTLS1_HM_HEADER_LENGTH]);
639
640                 *(p++)=s->version>>8;
641                 *(p++)=s->version&0xff;
642                 s->client_version=s->version;
643
644                 /* Random stuff */
645                 memcpy(p,s->s3->client_random,SSL3_RANDOM_SIZE);
646                 p+=SSL3_RANDOM_SIZE;
647
648                 /* Session ID */
649                 if (s->new_session)
650                         i=0;
651                 else
652                         i=s->session->session_id_length;
653                 *(p++)=i;
654                 if (i != 0)
655                         {
656                         if (i > sizeof s->session->session_id)
657                                 {
658                                 SSLerr(SSL_F_DTLS1_CLIENT_HELLO, ERR_R_INTERNAL_ERROR);
659                                 goto err;
660                                 }
661                         memcpy(p,s->session->session_id,i);
662                         p+=i;
663                         }
664                 
665                 /* cookie stuff */
666                 if ( s->d1->cookie_len > sizeof(s->d1->cookie))
667                         {
668                         SSLerr(SSL_F_DTLS1_CLIENT_HELLO, ERR_R_INTERNAL_ERROR);
669                         goto err;
670                         }
671                 *(p++) = s->d1->cookie_len;
672                 memcpy(p, s->d1->cookie, s->d1->cookie_len);
673                 p += s->d1->cookie_len;
674
675                 /* Ciphers supported */
676                 i=ssl_cipher_list_to_bytes(s,SSL_get_ciphers(s),&(p[2]),0);
677                 if (i == 0)
678                         {
679                         SSLerr(SSL_F_DTLS1_CLIENT_HELLO,SSL_R_NO_CIPHERS_AVAILABLE);
680                         goto err;
681                         }
682                 s2n(i,p);
683                 p+=i;
684
685                 /* COMPRESSION */
686                 if (s->ctx->comp_methods == NULL)
687                         j=0;
688                 else
689                         j=sk_SSL_COMP_num(s->ctx->comp_methods);
690                 *(p++)=1+j;
691                 for (i=0; i<j; i++)
692                         {
693                         comp=sk_SSL_COMP_value(s->ctx->comp_methods,i);
694                         *(p++)=comp->id;
695                         }
696                 *(p++)=0; /* Add the NULL method */
697
698 #ifndef OPENSSL_NO_TLSEXT
699                 if ((p = ssl_add_clienthello_tlsext(s, p, buf+SSL3_RT_MAX_PLAIN_LENGTH)) == NULL)
700                         {
701                         SSLerr(SSL_F_DTLS1_CLIENT_HELLO,ERR_R_INTERNAL_ERROR);
702                         goto err;
703                         }
704 #endif          
705
706                 l=(p-d);
707                 d=buf;
708
709                 d = dtls1_set_message_header(s, d, SSL3_MT_CLIENT_HELLO, l, 0, l);
710
711                 s->state=SSL3_ST_CW_CLNT_HELLO_B;
712                 /* number of bytes to write */
713                 s->init_num=p-buf;
714                 s->init_off=0;
715
716                 /* buffer the message to handle re-xmits */
717                 dtls1_buffer_message(s, 0);
718                 }
719
720         /* SSL3_ST_CW_CLNT_HELLO_B */
721         return(dtls1_do_write(s,SSL3_RT_HANDSHAKE));
722 err:
723         return(-1);
724         }
725
726 static int dtls1_get_hello_verify(SSL *s)
727         {
728         int n, al, ok = 0;
729         unsigned char *data;
730         unsigned int cookie_len;
731
732         n=s->method->ssl_get_message(s,
733                 DTLS1_ST_CR_HELLO_VERIFY_REQUEST_A,
734                 DTLS1_ST_CR_HELLO_VERIFY_REQUEST_B,
735                 -1,
736                 s->max_cert_list,
737                 &ok);
738
739         if (!ok) return((int)n);
740
741         if (s->s3->tmp.message_type != DTLS1_MT_HELLO_VERIFY_REQUEST)
742                 {
743                 s->d1->send_cookie = 0;
744                 s->s3->tmp.reuse_message=1;
745                 return(1);
746                 }
747
748         data = (unsigned char *)s->init_msg;
749
750         if ((data[0] != (s->version>>8)) || (data[1] != (s->version&0xff)))
751                 {
752                 SSLerr(SSL_F_DTLS1_GET_HELLO_VERIFY,SSL_R_WRONG_SSL_VERSION);
753                 s->version=(s->version&0xff00)|data[1];
754                 al = SSL_AD_PROTOCOL_VERSION;
755                 goto f_err;
756                 }
757         data+=2;
758
759         cookie_len = *(data++);
760         if ( cookie_len > sizeof(s->d1->cookie))
761                 {
762                 al=SSL_AD_ILLEGAL_PARAMETER;
763                 goto f_err;
764                 }
765
766         memcpy(s->d1->cookie, data, cookie_len);
767         s->d1->cookie_len = cookie_len;
768
769         s->d1->send_cookie = 1;
770         return 1;
771
772 f_err:
773         ssl3_send_alert(s, SSL3_AL_FATAL, al);
774         return -1;
775         }
776
777 int dtls1_send_client_key_exchange(SSL *s)
778         {
779         unsigned char *p,*d;
780         int n;
781         unsigned long alg_k;
782 #ifndef OPENSSL_NO_RSA
783         unsigned char *q;
784         EVP_PKEY *pkey=NULL;
785 #endif
786 #ifndef OPENSSL_NO_KRB5
787         KSSL_ERR kssl_err;
788 #endif /* OPENSSL_NO_KRB5 */
789 #ifndef OPENSSL_NO_ECDH
790         EC_KEY *clnt_ecdh = NULL;
791         const EC_POINT *srvr_ecpoint = NULL;
792         EVP_PKEY *srvr_pub_pkey = NULL;
793         unsigned char *encodedPoint = NULL;
794         int encoded_pt_len = 0;
795         BN_CTX * bn_ctx = NULL;
796 #endif
797
798         if (s->state == SSL3_ST_CW_KEY_EXCH_A)
799                 {
800                 d=(unsigned char *)s->init_buf->data;
801                 p= &(d[DTLS1_HM_HEADER_LENGTH]);
802                 
803                 alg_k=s->s3->tmp.new_cipher->algorithm_mkey;
804
805                 /* Fool emacs indentation */
806                 if (0) {}
807 #ifndef OPENSSL_NO_RSA
808                 else if (alg_k & SSL_kRSA)
809                         {
810                         RSA *rsa;
811                         unsigned char tmp_buf[SSL_MAX_MASTER_KEY_LENGTH];
812
813                         if (s->session->sess_cert->peer_rsa_tmp != NULL)
814                                 rsa=s->session->sess_cert->peer_rsa_tmp;
815                         else
816                                 {
817                                 pkey=X509_get_pubkey(s->session->sess_cert->peer_pkeys[SSL_PKEY_RSA_ENC].x509);
818                                 if ((pkey == NULL) ||
819                                         (pkey->type != EVP_PKEY_RSA) ||
820                                         (pkey->pkey.rsa == NULL))
821                                         {
822                                         SSLerr(SSL_F_DTLS1_SEND_CLIENT_KEY_EXCHANGE,ERR_R_INTERNAL_ERROR);
823                                         goto err;
824                                         }
825                                 rsa=pkey->pkey.rsa;
826                                 EVP_PKEY_free(pkey);
827                                 }
828                                 
829                         tmp_buf[0]=s->client_version>>8;
830                         tmp_buf[1]=s->client_version&0xff;
831                         if (RAND_bytes(&(tmp_buf[2]),sizeof tmp_buf-2) <= 0)
832                                         goto err;
833
834                         s->session->master_key_length=sizeof tmp_buf;
835
836                         q=p;
837                         /* Fix buf for TLS and [incidentally] DTLS */
838                         if (s->version > SSL3_VERSION)
839                                 p+=2;
840                         n=RSA_public_encrypt(sizeof tmp_buf,
841                                 tmp_buf,p,rsa,RSA_PKCS1_PADDING);
842 #ifdef PKCS1_CHECK
843                         if (s->options & SSL_OP_PKCS1_CHECK_1) p[1]++;
844                         if (s->options & SSL_OP_PKCS1_CHECK_2) tmp_buf[0]=0x70;
845 #endif
846                         if (n <= 0)
847                                 {
848                                 SSLerr(SSL_F_DTLS1_SEND_CLIENT_KEY_EXCHANGE,SSL_R_BAD_RSA_ENCRYPT);
849                                 goto err;
850                                 }
851
852                         /* Fix buf for TLS and [incidentally] DTLS */
853                         if (s->version > SSL3_VERSION)
854                                 {
855                                 s2n(n,q);
856                                 n+=2;
857                                 }
858
859                         s->session->master_key_length=
860                                 s->method->ssl3_enc->generate_master_secret(s,
861                                         s->session->master_key,
862                                         tmp_buf,sizeof tmp_buf);
863                         OPENSSL_cleanse(tmp_buf,sizeof tmp_buf);
864                         }
865 #endif
866 #ifndef OPENSSL_NO_KRB5
867                 else if (alg_k & SSL_kKRB5)
868                         {
869                         krb5_error_code krb5rc;
870                         KSSL_CTX        *kssl_ctx = s->kssl_ctx;
871                         /*  krb5_data   krb5_ap_req;  */
872                         krb5_data       *enc_ticket;
873                         krb5_data       authenticator, *authp = NULL;
874                         EVP_CIPHER_CTX  ciph_ctx;
875                         const EVP_CIPHER *enc = NULL;
876                         unsigned char   iv[EVP_MAX_IV_LENGTH];
877                         unsigned char   tmp_buf[SSL_MAX_MASTER_KEY_LENGTH];
878                         unsigned char   epms[SSL_MAX_MASTER_KEY_LENGTH 
879                                                 + EVP_MAX_IV_LENGTH];
880                         int             padl, outl = sizeof(epms);
881
882                         EVP_CIPHER_CTX_init(&ciph_ctx);
883
884 #ifdef KSSL_DEBUG
885                         printf("ssl3_send_client_key_exchange(%lx & %lx)\n",
886                                 alg_k, SSL_kKRB5);
887 #endif  /* KSSL_DEBUG */
888
889                         authp = NULL;
890 #ifdef KRB5SENDAUTH
891                         if (KRB5SENDAUTH)  authp = &authenticator;
892 #endif  /* KRB5SENDAUTH */
893
894                         krb5rc = kssl_cget_tkt(kssl_ctx, &enc_ticket, authp,
895                                 &kssl_err);
896                         enc = kssl_map_enc(kssl_ctx->enctype);
897                         if (enc == NULL)
898                             goto err;
899 #ifdef KSSL_DEBUG
900                         {
901                         printf("kssl_cget_tkt rtn %d\n", krb5rc);
902                         if (krb5rc && kssl_err.text)
903                           printf("kssl_cget_tkt kssl_err=%s\n", kssl_err.text);
904                         }
905 #endif  /* KSSL_DEBUG */
906
907                         if (krb5rc)
908                                 {
909                                 ssl3_send_alert(s,SSL3_AL_FATAL,
910                                                 SSL_AD_HANDSHAKE_FAILURE);
911                                 SSLerr(SSL_F_DTLS1_SEND_CLIENT_KEY_EXCHANGE,
912                                                 kssl_err.reason);
913                                 goto err;
914                                 }
915
916                         /*  20010406 VRS - Earlier versions used KRB5 AP_REQ
917                         **  in place of RFC 2712 KerberosWrapper, as in:
918                         **
919                         **  Send ticket (copy to *p, set n = length)
920                         **  n = krb5_ap_req.length;
921                         **  memcpy(p, krb5_ap_req.data, krb5_ap_req.length);
922                         **  if (krb5_ap_req.data)  
923                         **    kssl_krb5_free_data_contents(NULL,&krb5_ap_req);
924                         **
925                         **  Now using real RFC 2712 KerberosWrapper
926                         **  (Thanks to Simon Wilkinson <sxw@sxw.org.uk>)
927                         **  Note: 2712 "opaque" types are here replaced
928                         **  with a 2-byte length followed by the value.
929                         **  Example:
930                         **  KerberosWrapper= xx xx asn1ticket 0 0 xx xx encpms
931                         **  Where "xx xx" = length bytes.  Shown here with
932                         **  optional authenticator omitted.
933                         */
934
935                         /*  KerberosWrapper.Ticket              */
936                         s2n(enc_ticket->length,p);
937                         memcpy(p, enc_ticket->data, enc_ticket->length);
938                         p+= enc_ticket->length;
939                         n = enc_ticket->length + 2;
940
941                         /*  KerberosWrapper.Authenticator       */
942                         if (authp  &&  authp->length)  
943                                 {
944                                 s2n(authp->length,p);
945                                 memcpy(p, authp->data, authp->length);
946                                 p+= authp->length;
947                                 n+= authp->length + 2;
948                                 
949                                 free(authp->data);
950                                 authp->data = NULL;
951                                 authp->length = 0;
952                                 }
953                         else
954                                 {
955                                 s2n(0,p);/*  null authenticator length  */
956                                 n+=2;
957                                 }
958  
959                         if (RAND_bytes(tmp_buf,sizeof tmp_buf) <= 0)
960                             goto err;
961
962                         /*  20010420 VRS.  Tried it this way; failed.
963                         **      EVP_EncryptInit_ex(&ciph_ctx,enc, NULL,NULL);
964                         **      EVP_CIPHER_CTX_set_key_length(&ciph_ctx,
965                         **                              kssl_ctx->length);
966                         **      EVP_EncryptInit_ex(&ciph_ctx,NULL, key,iv);
967                         */
968
969                         memset(iv, 0, sizeof iv);  /* per RFC 1510 */
970                         EVP_EncryptInit_ex(&ciph_ctx,enc, NULL,
971                                 kssl_ctx->key,iv);
972                         EVP_EncryptUpdate(&ciph_ctx,epms,&outl,tmp_buf,
973                                 sizeof tmp_buf);
974                         EVP_EncryptFinal_ex(&ciph_ctx,&(epms[outl]),&padl);
975                         outl += padl;
976                         if (outl > (int)sizeof epms)
977                                 {
978                                 SSLerr(SSL_F_DTLS1_SEND_CLIENT_KEY_EXCHANGE, ERR_R_INTERNAL_ERROR);
979                                 goto err;
980                                 }
981                         EVP_CIPHER_CTX_cleanup(&ciph_ctx);
982
983                         /*  KerberosWrapper.EncryptedPreMasterSecret    */
984                         s2n(outl,p);
985                         memcpy(p, epms, outl);
986                         p+=outl;
987                         n+=outl + 2;
988
989                         s->session->master_key_length=
990                                 s->method->ssl3_enc->generate_master_secret(s,
991                                         s->session->master_key,
992                                         tmp_buf, sizeof tmp_buf);
993
994                         OPENSSL_cleanse(tmp_buf, sizeof tmp_buf);
995                         OPENSSL_cleanse(epms, outl);
996                         }
997 #endif
998 #ifndef OPENSSL_NO_DH
999                 else if (alg_k & (SSL_kEDH|SSL_kDHr|SSL_kDHd))
1000                         {
1001                         DH *dh_srvr,*dh_clnt;
1002
1003                         if (s->session->sess_cert->peer_dh_tmp != NULL)
1004                                 dh_srvr=s->session->sess_cert->peer_dh_tmp;
1005                         else
1006                                 {
1007                                 /* we get them from the cert */
1008                                 ssl3_send_alert(s,SSL3_AL_FATAL,SSL_AD_HANDSHAKE_FAILURE);
1009                                 SSLerr(SSL_F_DTLS1_SEND_CLIENT_KEY_EXCHANGE,SSL_R_UNABLE_TO_FIND_DH_PARAMETERS);
1010                                 goto err;
1011                                 }
1012                         
1013                         /* generate a new random key */
1014                         if ((dh_clnt=DHparams_dup(dh_srvr)) == NULL)
1015                                 {
1016                                 SSLerr(SSL_F_DTLS1_SEND_CLIENT_KEY_EXCHANGE,ERR_R_DH_LIB);
1017                                 goto err;
1018                                 }
1019                         if (!DH_generate_key(dh_clnt))
1020                                 {
1021                                 SSLerr(SSL_F_DTLS1_SEND_CLIENT_KEY_EXCHANGE,ERR_R_DH_LIB);
1022                                 goto err;
1023                                 }
1024
1025                         /* use the 'p' output buffer for the DH key, but
1026                          * make sure to clear it out afterwards */
1027
1028                         n=DH_compute_key(p,dh_srvr->pub_key,dh_clnt);
1029
1030                         if (n <= 0)
1031                                 {
1032                                 SSLerr(SSL_F_DTLS1_SEND_CLIENT_KEY_EXCHANGE,ERR_R_DH_LIB);
1033                                 goto err;
1034                                 }
1035
1036                         /* generate master key from the result */
1037                         s->session->master_key_length=
1038                                 s->method->ssl3_enc->generate_master_secret(s,
1039                                         s->session->master_key,p,n);
1040                         /* clean up */
1041                         memset(p,0,n);
1042
1043                         /* send off the data */
1044                         n=BN_num_bytes(dh_clnt->pub_key);
1045                         s2n(n,p);
1046                         BN_bn2bin(dh_clnt->pub_key,p);
1047                         n+=2;
1048
1049                         DH_free(dh_clnt);
1050
1051                         /* perhaps clean things up a bit EAY EAY EAY EAY*/
1052                         }
1053 #endif
1054 #ifndef OPENSSL_NO_ECDH 
1055                 else if (alg_k & (SSL_kEECDH|SSL_kECDHr|SSL_kECDHe))
1056                         {
1057                         const EC_GROUP *srvr_group = NULL;
1058                         EC_KEY *tkey;
1059                         int ecdh_clnt_cert = 0;
1060                         int field_size = 0;
1061
1062                         /* Did we send out the client's
1063                          * ECDH share for use in premaster
1064                          * computation as part of client certificate?
1065                          * If so, set ecdh_clnt_cert to 1.
1066                          */
1067                         if ((alg_k & (SSL_kECDHr|SSL_kECDHe)) && (s->cert != NULL)) 
1068                                 {
1069                                 /* XXX: For now, we do not support client
1070                                  * authentication using ECDH certificates.
1071                                  * To add such support, one needs to add
1072                                  * code that checks for appropriate 
1073                                  * conditions and sets ecdh_clnt_cert to 1.
1074                                  * For example, the cert have an ECC
1075                                  * key on the same curve as the server's
1076                                  * and the key should be authorized for
1077                                  * key agreement.
1078                                  *
1079                                  * One also needs to add code in ssl3_connect
1080                                  * to skip sending the certificate verify
1081                                  * message.
1082                                  *
1083                                  * if ((s->cert->key->privatekey != NULL) &&
1084                                  *     (s->cert->key->privatekey->type ==
1085                                  *      EVP_PKEY_EC) && ...)
1086                                  * ecdh_clnt_cert = 1;
1087                                  */
1088                                 }
1089
1090                         if (s->session->sess_cert->peer_ecdh_tmp != NULL)
1091                                 {
1092                                 tkey = s->session->sess_cert->peer_ecdh_tmp;
1093                                 }
1094                         else
1095                                 {
1096                                 /* Get the Server Public Key from Cert */
1097                                 srvr_pub_pkey = X509_get_pubkey(s->session-> \
1098                                     sess_cert->peer_pkeys[SSL_PKEY_ECC].x509);
1099                                 if ((srvr_pub_pkey == NULL) ||
1100                                     (srvr_pub_pkey->type != EVP_PKEY_EC) ||
1101                                     (srvr_pub_pkey->pkey.ec == NULL))
1102                                         {
1103                                         SSLerr(SSL_F_DTLS1_SEND_CLIENT_KEY_EXCHANGE,
1104                                             ERR_R_INTERNAL_ERROR);
1105                                         goto err;
1106                                         }
1107
1108                                 tkey = srvr_pub_pkey->pkey.ec;
1109                                 }
1110
1111                         srvr_group   = EC_KEY_get0_group(tkey);
1112                         srvr_ecpoint = EC_KEY_get0_public_key(tkey);
1113
1114                         if ((srvr_group == NULL) || (srvr_ecpoint == NULL))
1115                                 {
1116                                 SSLerr(SSL_F_DTLS1_SEND_CLIENT_KEY_EXCHANGE,
1117                                     ERR_R_INTERNAL_ERROR);
1118                                 goto err;
1119                                 }
1120
1121                         if ((clnt_ecdh=EC_KEY_new()) == NULL) 
1122                                 {
1123                                 SSLerr(SSL_F_DTLS1_SEND_CLIENT_KEY_EXCHANGE,ERR_R_MALLOC_FAILURE);
1124                                 goto err;
1125                                 }
1126
1127                         if (!EC_KEY_set_group(clnt_ecdh, srvr_group))
1128                                 {
1129                                 SSLerr(SSL_F_DTLS1_SEND_CLIENT_KEY_EXCHANGE,ERR_R_EC_LIB);
1130                                 goto err;
1131                                 }
1132                         if (ecdh_clnt_cert) 
1133                                 { 
1134                                 /* Reuse key info from our certificate
1135                                  * We only need our private key to perform
1136                                  * the ECDH computation.
1137                                  */
1138                                 const BIGNUM *priv_key;
1139                                 tkey = s->cert->key->privatekey->pkey.ec;
1140                                 priv_key = EC_KEY_get0_private_key(tkey);
1141                                 if (priv_key == NULL)
1142                                         {
1143                                         SSLerr(SSL_F_DTLS1_SEND_CLIENT_KEY_EXCHANGE,ERR_R_MALLOC_FAILURE);
1144                                         goto err;
1145                                         }
1146                                 if (!EC_KEY_set_private_key(clnt_ecdh, priv_key))
1147                                         {
1148                                         SSLerr(SSL_F_DTLS1_SEND_CLIENT_KEY_EXCHANGE,ERR_R_EC_LIB);
1149                                         goto err;
1150                                         }
1151                                 }
1152                         else 
1153                                 {
1154                                 /* Generate a new ECDH key pair */
1155                                 if (!(EC_KEY_generate_key(clnt_ecdh)))
1156                                         {
1157                                         SSLerr(SSL_F_DTLS1_SEND_CLIENT_KEY_EXCHANGE, ERR_R_ECDH_LIB);
1158                                         goto err;
1159                                         }
1160                                 }
1161
1162                         /* use the 'p' output buffer for the ECDH key, but
1163                          * make sure to clear it out afterwards
1164                          */
1165
1166                         field_size = EC_GROUP_get_degree(srvr_group);
1167                         if (field_size <= 0)
1168                                 {
1169                                 SSLerr(SSL_F_DTLS1_SEND_CLIENT_KEY_EXCHANGE, 
1170                                        ERR_R_ECDH_LIB);
1171                                 goto err;
1172                                 }
1173                         n=ECDH_compute_key(p, (field_size+7)/8, srvr_ecpoint, clnt_ecdh, NULL);
1174                         if (n <= 0)
1175                                 {
1176                                 SSLerr(SSL_F_DTLS1_SEND_CLIENT_KEY_EXCHANGE, 
1177                                        ERR_R_ECDH_LIB);
1178                                 goto err;
1179                                 }
1180
1181                         /* generate master key from the result */
1182                         s->session->master_key_length = s->method->ssl3_enc \
1183                             -> generate_master_secret(s, 
1184                                 s->session->master_key,
1185                                 p, n);
1186
1187                         memset(p, 0, n); /* clean up */
1188
1189                         if (ecdh_clnt_cert) 
1190                                 {
1191                                 /* Send empty client key exch message */
1192                                 n = 0;
1193                                 }
1194                         else 
1195                                 {
1196                                 /* First check the size of encoding and
1197                                  * allocate memory accordingly.
1198                                  */
1199                                 encoded_pt_len = 
1200                                     EC_POINT_point2oct(srvr_group, 
1201                                         EC_KEY_get0_public_key(clnt_ecdh), 
1202                                         POINT_CONVERSION_UNCOMPRESSED, 
1203                                         NULL, 0, NULL);
1204
1205                                 encodedPoint = (unsigned char *) 
1206                                     OPENSSL_malloc(encoded_pt_len * 
1207                                         sizeof(unsigned char)); 
1208                                 bn_ctx = BN_CTX_new();
1209                                 if ((encodedPoint == NULL) || 
1210                                     (bn_ctx == NULL)) 
1211                                         {
1212                                         SSLerr(SSL_F_DTLS1_SEND_CLIENT_KEY_EXCHANGE,ERR_R_MALLOC_FAILURE);
1213                                         goto err;
1214                                         }
1215
1216                                 /* Encode the public key */
1217                                 n = EC_POINT_point2oct(srvr_group, 
1218                                     EC_KEY_get0_public_key(clnt_ecdh), 
1219                                     POINT_CONVERSION_UNCOMPRESSED, 
1220                                     encodedPoint, encoded_pt_len, bn_ctx);
1221
1222                                 *p = n; /* length of encoded point */
1223                                 /* Encoded point will be copied here */
1224                                 p += 1; 
1225                                 /* copy the point */
1226                                 memcpy((unsigned char *)p, encodedPoint, n);
1227                                 /* increment n to account for length field */
1228                                 n += 1; 
1229                                 }
1230
1231                         /* Free allocated memory */
1232                         BN_CTX_free(bn_ctx);
1233                         if (encodedPoint != NULL) OPENSSL_free(encodedPoint);
1234                         if (clnt_ecdh != NULL) 
1235                                  EC_KEY_free(clnt_ecdh);
1236                         EVP_PKEY_free(srvr_pub_pkey);
1237                         }
1238 #endif /* !OPENSSL_NO_ECDH */
1239
1240 #ifndef OPENSSL_NO_PSK
1241                 else if (alg_k & SSL_kPSK)
1242                         {
1243                         char identity[PSK_MAX_IDENTITY_LEN];
1244                         unsigned char *t = NULL;
1245                         unsigned char psk_or_pre_ms[PSK_MAX_PSK_LEN*2+4];
1246                         unsigned int pre_ms_len = 0, psk_len = 0;
1247                         int psk_err = 1;
1248
1249                         n = 0;
1250                         if (s->psk_client_callback == NULL)
1251                                 {
1252                                 SSLerr(SSL_F_DTLS1_SEND_CLIENT_KEY_EXCHANGE,
1253                                         SSL_R_PSK_NO_CLIENT_CB);
1254                                 goto err;
1255                                 }
1256
1257                         psk_len = s->psk_client_callback(s, s->ctx->psk_identity_hint,
1258                                 identity, PSK_MAX_IDENTITY_LEN,
1259                                 psk_or_pre_ms, sizeof(psk_or_pre_ms));
1260                         if (psk_len > PSK_MAX_PSK_LEN)
1261                                 {
1262                                 SSLerr(SSL_F_DTLS1_SEND_CLIENT_KEY_EXCHANGE,
1263                                         ERR_R_INTERNAL_ERROR);
1264                                 goto psk_err;
1265                                 }
1266                         else if (psk_len == 0)
1267                                 {
1268                                 SSLerr(SSL_F_DTLS1_SEND_CLIENT_KEY_EXCHANGE,
1269                                         SSL_R_PSK_IDENTITY_NOT_FOUND);
1270                                 goto psk_err;
1271                                 }
1272
1273                         /* create PSK pre_master_secret */
1274                         pre_ms_len = 2+psk_len+2+psk_len;
1275                         t = psk_or_pre_ms;
1276                         memmove(psk_or_pre_ms+psk_len+4, psk_or_pre_ms, psk_len);
1277                         s2n(psk_len, t);
1278                         memset(t, 0, psk_len);
1279                         t+=psk_len;
1280                         s2n(psk_len, t);
1281
1282                         if (s->session->psk_identity_hint != NULL)
1283                                 OPENSSL_free(s->session->psk_identity_hint);
1284                         s->session->psk_identity_hint = BUF_strdup(s->ctx->psk_identity_hint);
1285                         if (s->ctx->psk_identity_hint != NULL &&
1286                                 s->session->psk_identity_hint == NULL)
1287                                 {
1288                                 SSLerr(SSL_F_DTLS1_SEND_CLIENT_KEY_EXCHANGE,
1289                                         ERR_R_MALLOC_FAILURE);
1290                                 goto psk_err;
1291                                 }
1292
1293                         if (s->session->psk_identity != NULL)
1294                                 OPENSSL_free(s->session->psk_identity);
1295                         s->session->psk_identity = BUF_strdup(identity);
1296                         if (s->session->psk_identity == NULL)
1297                                 {
1298                                 SSLerr(SSL_F_DTLS1_SEND_CLIENT_KEY_EXCHANGE,
1299                                         ERR_R_MALLOC_FAILURE);
1300                                 goto psk_err;
1301                                 }
1302
1303                         s->session->master_key_length =
1304                                 s->method->ssl3_enc->generate_master_secret(s,
1305                                         s->session->master_key,
1306                                         psk_or_pre_ms, pre_ms_len); 
1307                         n = strlen(identity);
1308                         s2n(n, p);
1309                         memcpy(p, identity, n);
1310                         n+=2;
1311                         psk_err = 0;
1312                 psk_err:
1313                         OPENSSL_cleanse(identity, PSK_MAX_IDENTITY_LEN);
1314                         OPENSSL_cleanse(psk_or_pre_ms, sizeof(psk_or_pre_ms));
1315                         if (psk_err != 0)
1316                                 {
1317                                 ssl3_send_alert(s, SSL3_AL_FATAL, SSL_AD_HANDSHAKE_FAILURE);
1318                                 goto err;
1319                                 }
1320                         }
1321 #endif
1322                 else
1323                         {
1324                         ssl3_send_alert(s,SSL3_AL_FATAL,SSL_AD_HANDSHAKE_FAILURE);
1325                         SSLerr(SSL_F_DTLS1_SEND_CLIENT_KEY_EXCHANGE,ERR_R_INTERNAL_ERROR);
1326                         goto err;
1327                         }
1328                 
1329                 d = dtls1_set_message_header(s, d,
1330                 SSL3_MT_CLIENT_KEY_EXCHANGE, n, 0, n);
1331                 /*
1332                  *(d++)=SSL3_MT_CLIENT_KEY_EXCHANGE;
1333                  l2n3(n,d);
1334                  l2n(s->d1->handshake_write_seq,d);
1335                  s->d1->handshake_write_seq++;
1336                 */
1337                 
1338                 s->state=SSL3_ST_CW_KEY_EXCH_B;
1339                 /* number of bytes to write */
1340                 s->init_num=n+DTLS1_HM_HEADER_LENGTH;
1341                 s->init_off=0;
1342
1343                 /* buffer the message to handle re-xmits */
1344                 dtls1_buffer_message(s, 0);
1345                 }
1346         
1347         /* SSL3_ST_CW_KEY_EXCH_B */
1348         return(dtls1_do_write(s,SSL3_RT_HANDSHAKE));
1349 err:
1350 #ifndef OPENSSL_NO_ECDH
1351         BN_CTX_free(bn_ctx);
1352         if (encodedPoint != NULL) OPENSSL_free(encodedPoint);
1353         if (clnt_ecdh != NULL) 
1354                 EC_KEY_free(clnt_ecdh);
1355         EVP_PKEY_free(srvr_pub_pkey);
1356 #endif
1357         return(-1);
1358         }
1359
1360 int dtls1_send_client_verify(SSL *s)
1361         {
1362         unsigned char *p,*d;
1363         unsigned char data[MD5_DIGEST_LENGTH+SHA_DIGEST_LENGTH];
1364         EVP_PKEY *pkey;
1365 #ifndef OPENSSL_NO_RSA
1366         unsigned u=0;
1367 #endif
1368         unsigned long n;
1369 #if !defined(OPENSSL_NO_DSA) || !defined(OPENSSL_NO_ECDSA)
1370         int j;
1371 #endif
1372
1373         if (s->state == SSL3_ST_CW_CERT_VRFY_A)
1374                 {
1375                 d=(unsigned char *)s->init_buf->data;
1376                 p= &(d[DTLS1_HM_HEADER_LENGTH]);
1377                 pkey=s->cert->key->privatekey;
1378
1379                 s->method->ssl3_enc->cert_verify_mac(s,
1380                 NID_sha1,
1381                         &(data[MD5_DIGEST_LENGTH]));
1382
1383 #ifndef OPENSSL_NO_RSA
1384                 if (pkey->type == EVP_PKEY_RSA)
1385                         {
1386                         s->method->ssl3_enc->cert_verify_mac(s,
1387                                 NID_md5,
1388                                 &(data[0]));
1389                         if (RSA_sign(NID_md5_sha1, data,
1390                                          MD5_DIGEST_LENGTH+SHA_DIGEST_LENGTH,
1391                                         &(p[2]), &u, pkey->pkey.rsa) <= 0 )
1392                                 {
1393                                 SSLerr(SSL_F_DTLS1_SEND_CLIENT_VERIFY,ERR_R_RSA_LIB);
1394                                 goto err;
1395                                 }
1396                         s2n(u,p);
1397                         n=u+2;
1398                         }
1399                 else
1400 #endif
1401 #ifndef OPENSSL_NO_DSA
1402                         if (pkey->type == EVP_PKEY_DSA)
1403                         {
1404                         if (!DSA_sign(pkey->save_type,
1405                                 &(data[MD5_DIGEST_LENGTH]),
1406                                 SHA_DIGEST_LENGTH,&(p[2]),
1407                                 (unsigned int *)&j,pkey->pkey.dsa))
1408                                 {
1409                                 SSLerr(SSL_F_DTLS1_SEND_CLIENT_VERIFY,ERR_R_DSA_LIB);
1410                                 goto err;
1411                                 }
1412                         s2n(j,p);
1413                         n=j+2;
1414                         }
1415                 else
1416 #endif
1417 #ifndef OPENSSL_NO_ECDSA
1418                         if (pkey->type == EVP_PKEY_EC)
1419                         {
1420                         if (!ECDSA_sign(pkey->save_type,
1421                                 &(data[MD5_DIGEST_LENGTH]),
1422                                 SHA_DIGEST_LENGTH,&(p[2]),
1423                                 (unsigned int *)&j,pkey->pkey.ec))
1424                                 {
1425                                 SSLerr(SSL_F_DTLS1_SEND_CLIENT_VERIFY,
1426                                     ERR_R_ECDSA_LIB);
1427                                 goto err;
1428                                 }
1429                         s2n(j,p);
1430                         n=j+2;
1431                         }
1432                 else
1433 #endif
1434                         {
1435                         SSLerr(SSL_F_DTLS1_SEND_CLIENT_VERIFY,ERR_R_INTERNAL_ERROR);
1436                         goto err;
1437                         }
1438
1439                 d = dtls1_set_message_header(s, d,
1440                         SSL3_MT_CERTIFICATE_VERIFY, n, 0, n) ;
1441
1442                 s->init_num=(int)n+DTLS1_HM_HEADER_LENGTH;
1443                 s->init_off=0;
1444
1445                 /* buffer the message to handle re-xmits */
1446                 dtls1_buffer_message(s, 0);
1447
1448                 s->state = SSL3_ST_CW_CERT_VRFY_B;
1449                 }
1450
1451         /* s->state = SSL3_ST_CW_CERT_VRFY_B */
1452         return(dtls1_do_write(s,SSL3_RT_HANDSHAKE));
1453 err:
1454         return(-1);
1455         }
1456
1457 int dtls1_send_client_certificate(SSL *s)
1458         {
1459         X509 *x509=NULL;
1460         EVP_PKEY *pkey=NULL;
1461         int i;
1462         unsigned long l;
1463
1464         if (s->state == SSL3_ST_CW_CERT_A)
1465                 {
1466                 if ((s->cert == NULL) ||
1467                         (s->cert->key->x509 == NULL) ||
1468                         (s->cert->key->privatekey == NULL))
1469                         s->state=SSL3_ST_CW_CERT_B;
1470                 else
1471                         s->state=SSL3_ST_CW_CERT_C;
1472                 }
1473
1474         /* We need to get a client cert */
1475         if (s->state == SSL3_ST_CW_CERT_B)
1476                 {
1477                 /* If we get an error, we need to
1478                  * ssl->rwstate=SSL_X509_LOOKUP; return(-1);
1479                  * We then get retied later */
1480                 i=0;
1481                 i = ssl_do_client_cert_cb(s, &x509, &pkey);
1482                 if (i < 0)
1483                         {
1484                         s->rwstate=SSL_X509_LOOKUP;
1485                         return(-1);
1486                         }
1487                 s->rwstate=SSL_NOTHING;
1488                 if ((i == 1) && (pkey != NULL) && (x509 != NULL))
1489                         {
1490                         s->state=SSL3_ST_CW_CERT_B;
1491                         if (    !SSL_use_certificate(s,x509) ||
1492                                 !SSL_use_PrivateKey(s,pkey))
1493                                 i=0;
1494                         }
1495                 else if (i == 1)
1496                         {
1497                         i=0;
1498                         SSLerr(SSL_F_DTLS1_SEND_CLIENT_CERTIFICATE,SSL_R_BAD_DATA_RETURNED_BY_CALLBACK);
1499                         }
1500
1501                 if (x509 != NULL) X509_free(x509);
1502                 if (pkey != NULL) EVP_PKEY_free(pkey);
1503                 if (i == 0)
1504                         {
1505                         if (s->version == SSL3_VERSION)
1506                                 {
1507                                 s->s3->tmp.cert_req=0;
1508                                 ssl3_send_alert(s,SSL3_AL_WARNING,SSL_AD_NO_CERTIFICATE);
1509                                 return(1);
1510                                 }
1511                         else
1512                                 {
1513                                 s->s3->tmp.cert_req=2;
1514                                 }
1515                         }
1516
1517                 /* Ok, we have a cert */
1518                 s->state=SSL3_ST_CW_CERT_C;
1519                 }
1520
1521         if (s->state == SSL3_ST_CW_CERT_C)
1522                 {
1523                 s->state=SSL3_ST_CW_CERT_D;
1524                 l=dtls1_output_cert_chain(s,
1525                         (s->s3->tmp.cert_req == 2)?NULL:s->cert->key->x509);
1526                 s->init_num=(int)l;
1527                 s->init_off=0;
1528
1529                 /* set header called by dtls1_output_cert_chain() */
1530
1531                 /* buffer the message to handle re-xmits */
1532                 dtls1_buffer_message(s, 0);
1533                 }
1534         /* SSL3_ST_CW_CERT_D */
1535         return(dtls1_do_write(s,SSL3_RT_HANDSHAKE));
1536         }
1537
1538