PR: 2505
[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         void (*cb)(const SSL *ssl,int type,int val)=NULL;
152         int ret= -1;
153         int new_state,state,skip=0;;
154
155         RAND_add(&Time,sizeof(Time),0);
156         ERR_clear_error();
157         clear_sys_error();
158
159         if (s->info_callback != NULL)
160                 cb=s->info_callback;
161         else if (s->ctx->info_callback != NULL)
162                 cb=s->ctx->info_callback;
163         
164         s->in_handshake++;
165         if (!SSL_in_init(s) || SSL_in_before(s)) SSL_clear(s); 
166
167         for (;;)
168                 {
169                 state=s->state;
170
171                 switch(s->state)
172                         {
173                 case SSL_ST_RENEGOTIATE:
174                         s->renegotiate=1;
175                         s->state=SSL_ST_CONNECT;
176                         s->ctx->stats.sess_connect_renegotiate++;
177                         /* break */
178                 case SSL_ST_BEFORE:
179                 case SSL_ST_CONNECT:
180                 case SSL_ST_BEFORE|SSL_ST_CONNECT:
181                 case SSL_ST_OK|SSL_ST_CONNECT:
182
183                         s->server=0;
184                         if (cb != NULL) cb(s,SSL_CB_HANDSHAKE_START,1);
185
186                         if ((s->version & 0xff00 ) != (DTLS1_VERSION & 0xff00) &&
187                             (s->version & 0xff00 ) != (DTLS1_BAD_VER & 0xff00))
188                                 {
189                                 SSLerr(SSL_F_DTLS1_CONNECT, ERR_R_INTERNAL_ERROR);
190                                 ret = -1;
191                                 goto end;
192                                 }
193                                 
194                         /* s->version=SSL3_VERSION; */
195                         s->type=SSL_ST_CONNECT;
196
197                         if (s->init_buf == NULL)
198                                 {
199                                 if ((buf=BUF_MEM_new()) == NULL)
200                                         {
201                                         ret= -1;
202                                         goto end;
203                                         }
204                                 if (!BUF_MEM_grow(buf,SSL3_RT_MAX_PLAIN_LENGTH))
205                                         {
206                                         ret= -1;
207                                         goto end;
208                                         }
209                                 s->init_buf=buf;
210                                 buf=NULL;
211                                 }
212
213                         if (!ssl3_setup_buffers(s)) { ret= -1; goto end; }
214
215                         /* setup buffing BIO */
216                         if (!ssl_init_wbio_buffer(s,0)) { ret= -1; goto end; }
217
218                         /* don't push the buffering BIO quite yet */
219
220                         s->state=SSL3_ST_CW_CLNT_HELLO_A;
221                         s->ctx->stats.sess_connect++;
222                         s->init_num=0;
223                         /* mark client_random uninitialized */
224                         memset(s->s3->client_random,0,sizeof(s->s3->client_random));
225                         s->d1->send_cookie = 0;
226                         s->hit = 0;
227                         break;
228
229                 case SSL3_ST_CW_CLNT_HELLO_A:
230                 case SSL3_ST_CW_CLNT_HELLO_B:
231
232                         s->shutdown=0;
233
234                         /* every DTLS ClientHello resets Finished MAC */
235                         ssl3_init_finished_mac(s);
236
237                         dtls1_start_timer(s);
238                         ret=dtls1_client_hello(s);
239                         if (ret <= 0) goto end;
240
241                         if ( s->d1->send_cookie)
242                                 {
243                                 s->state=SSL3_ST_CW_FLUSH;
244                                 s->s3->tmp.next_state=SSL3_ST_CR_SRVR_HELLO_A;
245                                 }
246                         else
247                                 s->state=SSL3_ST_CR_SRVR_HELLO_A;
248
249                         s->init_num=0;
250
251                         /* turn on buffering for the next lot of output */
252                         if (s->bbio != s->wbio)
253                                 s->wbio=BIO_push(s->bbio,s->wbio);
254
255                         break;
256
257                 case SSL3_ST_CR_SRVR_HELLO_A:
258                 case SSL3_ST_CR_SRVR_HELLO_B:
259                         ret=ssl3_get_server_hello(s);
260                         if (ret <= 0) goto end;
261                         else
262                                 {
263                                 dtls1_stop_timer(s);
264                                 if (s->hit)
265                                         s->state=SSL3_ST_CR_FINISHED_A;
266                                 else
267                                         s->state=DTLS1_ST_CR_HELLO_VERIFY_REQUEST_A;
268                                 }
269                         s->init_num=0;
270                         break;
271
272                 case DTLS1_ST_CR_HELLO_VERIFY_REQUEST_A:
273                 case DTLS1_ST_CR_HELLO_VERIFY_REQUEST_B:
274
275                         ret = dtls1_get_hello_verify(s);
276                         if ( ret <= 0)
277                                 goto end;
278                         dtls1_stop_timer(s);
279                         if ( s->d1->send_cookie) /* start again, with a cookie */
280                                 s->state=SSL3_ST_CW_CLNT_HELLO_A;
281                         else
282                                 s->state = SSL3_ST_CR_CERT_A;
283                         s->init_num = 0;
284                         break;
285
286                 case SSL3_ST_CR_CERT_A:
287                 case SSL3_ST_CR_CERT_B:
288 #ifndef OPENSSL_NO_TLSEXT
289                         ret=ssl3_check_finished(s);
290                         if (ret <= 0) goto end;
291                         if (ret == 2)
292                                 {
293                                 s->hit = 1;
294                                 if (s->tlsext_ticket_expected)
295                                         s->state=SSL3_ST_CR_SESSION_TICKET_A;
296                                 else
297                                         s->state=SSL3_ST_CR_FINISHED_A;
298                                 s->init_num=0;
299                                 break;
300                                 }
301 #endif
302                         /* Check if it is anon DH or PSK */
303                         if (!(s->s3->tmp.new_cipher->algorithm_auth & SSL_aNULL) &&
304                             !(s->s3->tmp.new_cipher->algorithm_mkey & SSL_kPSK))
305                                 {
306                                 ret=ssl3_get_server_certificate(s);
307                                 if (ret <= 0) goto end;
308 #ifndef OPENSSL_NO_TLSEXT
309                                 if (s->tlsext_status_expected)
310                                         s->state=SSL3_ST_CR_CERT_STATUS_A;
311                                 else
312                                         s->state=SSL3_ST_CR_KEY_EXCH_A;
313                                 }
314                         else
315                                 {
316                                 skip = 1;
317                                 s->state=SSL3_ST_CR_KEY_EXCH_A;
318                                 }
319 #else
320                                 }
321                         else
322                                 skip=1;
323
324                         s->state=SSL3_ST_CR_KEY_EXCH_A;
325 #endif
326                         s->init_num=0;
327                         break;
328
329                 case SSL3_ST_CR_KEY_EXCH_A:
330                 case SSL3_ST_CR_KEY_EXCH_B:
331                         ret=ssl3_get_key_exchange(s);
332                         if (ret <= 0) goto end;
333                         s->state=SSL3_ST_CR_CERT_REQ_A;
334                         s->init_num=0;
335
336                         /* at this point we check that we have the
337                          * required stuff from the server */
338                         if (!ssl3_check_cert_and_algorithm(s))
339                                 {
340                                 ret= -1;
341                                 goto end;
342                                 }
343                         break;
344
345                 case SSL3_ST_CR_CERT_REQ_A:
346                 case SSL3_ST_CR_CERT_REQ_B:
347                         ret=ssl3_get_certificate_request(s);
348                         if (ret <= 0) goto end;
349                         s->state=SSL3_ST_CR_SRVR_DONE_A;
350                         s->init_num=0;
351                         break;
352
353                 case SSL3_ST_CR_SRVR_DONE_A:
354                 case SSL3_ST_CR_SRVR_DONE_B:
355                         ret=ssl3_get_server_done(s);
356                         if (ret <= 0) goto end;
357                         if (s->s3->tmp.cert_req)
358                                 s->state=SSL3_ST_CW_CERT_A;
359                         else
360                                 s->state=SSL3_ST_CW_KEY_EXCH_A;
361                         s->init_num=0;
362
363                         break;
364
365                 case SSL3_ST_CW_CERT_A:
366                 case SSL3_ST_CW_CERT_B:
367                 case SSL3_ST_CW_CERT_C:
368                 case SSL3_ST_CW_CERT_D:
369                         dtls1_start_timer(s);
370                         ret=dtls1_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                         dtls1_start_timer(s);
379                         ret=dtls1_send_client_key_exchange(s);
380                         if (ret <= 0) goto end;
381                         /* EAY EAY EAY need to check for DH fix cert
382                          * sent back */
383                         /* For TLS, cert_req is set to 2, so a cert chain
384                          * of nothing is sent, but no verify packet is sent */
385                         if (s->s3->tmp.cert_req == 1)
386                                 {
387                                 s->state=SSL3_ST_CW_CERT_VRFY_A;
388                                 }
389                         else
390                                 {
391                                 s->state=SSL3_ST_CW_CHANGE_A;
392                                 s->s3->change_cipher_spec=0;
393                                 }
394
395                         s->init_num=0;
396                         break;
397
398                 case SSL3_ST_CW_CERT_VRFY_A:
399                 case SSL3_ST_CW_CERT_VRFY_B:
400                         dtls1_start_timer(s);
401                         ret=dtls1_send_client_verify(s);
402                         if (ret <= 0) goto end;
403                         s->state=SSL3_ST_CW_CHANGE_A;
404                         s->init_num=0;
405                         s->s3->change_cipher_spec=0;
406                         break;
407
408                 case SSL3_ST_CW_CHANGE_A:
409                 case SSL3_ST_CW_CHANGE_B:
410                         if (!s->hit)
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                         if (!s->hit)
447                                 dtls1_start_timer(s);
448                         ret=dtls1_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                         s->d1->change_cipher_spec_ok = 1;
502                         ret=ssl3_get_finished(s,SSL3_ST_CR_FINISHED_A,
503                                 SSL3_ST_CR_FINISHED_B);
504                         if (ret <= 0) goto end;
505                         dtls1_stop_timer(s);
506
507                         if (s->hit)
508                                 s->state=SSL3_ST_CW_CHANGE_A;
509                         else
510                                 s->state=SSL_ST_OK;
511                         s->init_num=0;
512                         break;
513
514                 case SSL3_ST_CW_FLUSH:
515                         s->rwstate=SSL_WRITING;
516                         if (BIO_flush(s->wbio) <= 0)
517                                 {
518                                 ret= -1;
519                                 goto end;
520                                 }
521                         s->rwstate=SSL_NOTHING;
522                         s->state=s->s3->tmp.next_state;
523                         break;
524
525                 case SSL_ST_OK:
526                         /* clean a few things up */
527                         ssl3_cleanup_key_block(s);
528
529 #if 0
530                         if (s->init_buf != NULL)
531                                 {
532                                 BUF_MEM_free(s->init_buf);
533                                 s->init_buf=NULL;
534                                 }
535 #endif
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->renegotiate=0;
545                         s->new_session=0;
546
547                         ssl_update_cache(s,SSL_SESS_CACHE_CLIENT);
548                         if (s->hit) s->ctx->stats.sess_hit++;
549
550                         ret=1;
551                         /* s->server=0; */
552                         s->handshake_func=dtls1_connect;
553                         s->ctx->stats.sess_connect_good++;
554
555                         if (cb != NULL) cb(s,SSL_CB_HANDSHAKE_DONE,1);
556
557                         /* done with handshaking */
558                         s->d1->handshake_read_seq  = 0;
559                         s->d1->next_handshake_write_seq = 0;
560                         goto end;
561                         /* break; */
562                         
563                 default:
564                         SSLerr(SSL_F_DTLS1_CONNECT,SSL_R_UNKNOWN_STATE);
565                         ret= -1;
566                         goto end;
567                         /* break; */
568                         }
569
570                 /* did we do anything */
571                 if (!s->s3->tmp.reuse_message && !skip)
572                         {
573                         if (s->debug)
574                                 {
575                                 if ((ret=BIO_flush(s->wbio)) <= 0)
576                                         goto end;
577                                 }
578
579                         if ((cb != NULL) && (s->state != state))
580                                 {
581                                 new_state=s->state;
582                                 s->state=state;
583                                 cb(s,SSL_CB_CONNECT_LOOP,1);
584                                 s->state=new_state;
585                                 }
586                         }
587                 skip=0;
588                 }
589 end:
590         s->in_handshake--;
591         if (buf != NULL)
592                 BUF_MEM_free(buf);
593         if (cb != NULL)
594                 cb(s,SSL_CB_CONNECT_EXIT,ret);
595         return(ret);
596         }
597
598 int dtls1_client_hello(SSL *s)
599         {
600         unsigned char *buf;
601         unsigned char *p,*d;
602         unsigned int i,j;
603         unsigned long Time,l;
604         SSL_COMP *comp;
605
606         buf=(unsigned char *)s->init_buf->data;
607         if (s->state == SSL3_ST_CW_CLNT_HELLO_A)
608                 {
609                 SSL_SESSION *sess = s->session;
610                 if ((s->session == NULL) ||
611                         (s->session->ssl_version != s->version) ||
612 #ifdef OPENSSL_NO_TLSEXT
613                         !sess->session_id_length ||
614 #else
615                         (!sess->session_id_length && !sess->tlsext_tick) ||
616 #endif
617                         (s->session->not_resumable))
618                         {
619                         if (!ssl_get_new_session(s,0))
620                                 goto err;
621                         }
622                 /* else use the pre-loaded session */
623
624                 p=s->s3->client_random;
625
626                 /* if client_random is initialized, reuse it, we are
627                  * required to use same upon reply to HelloVerify */
628                 for (i=0;p[i]=='\0' && i<sizeof(s->s3->client_random);i++) ;
629                 if (i==sizeof(s->s3->client_random))
630                         {
631                         Time=(unsigned long)time(NULL); /* Time */
632                         l2n(Time,p);
633                         RAND_pseudo_bytes(p,sizeof(s->s3->client_random)-4);
634                         }
635
636                 /* Do the message type and length last */
637                 d=p= &(buf[DTLS1_HM_HEADER_LENGTH]);
638
639                 *(p++)=s->version>>8;
640                 *(p++)=s->version&0xff;
641                 s->client_version=s->version;
642
643                 /* Random stuff */
644                 memcpy(p,s->s3->client_random,SSL3_RANDOM_SIZE);
645                 p+=SSL3_RANDOM_SIZE;
646
647                 /* Session ID */
648                 if (s->new_session)
649                         i=0;
650                 else
651                         i=s->session->session_id_length;
652                 *(p++)=i;
653                 if (i != 0)
654                         {
655                         if (i > sizeof s->session->session_id)
656                                 {
657                                 SSLerr(SSL_F_DTLS1_CLIENT_HELLO, ERR_R_INTERNAL_ERROR);
658                                 goto err;
659                                 }
660                         memcpy(p,s->session->session_id,i);
661                         p+=i;
662                         }
663                 
664                 /* cookie stuff */
665                 if ( s->d1->cookie_len > sizeof(s->d1->cookie))
666                         {
667                         SSLerr(SSL_F_DTLS1_CLIENT_HELLO, ERR_R_INTERNAL_ERROR);
668                         goto err;
669                         }
670                 *(p++) = s->d1->cookie_len;
671                 memcpy(p, s->d1->cookie, s->d1->cookie_len);
672                 p += s->d1->cookie_len;
673
674                 /* Ciphers supported */
675                 i=ssl_cipher_list_to_bytes(s,SSL_get_ciphers(s),&(p[2]),0);
676                 if (i == 0)
677                         {
678                         SSLerr(SSL_F_DTLS1_CLIENT_HELLO,SSL_R_NO_CIPHERS_AVAILABLE);
679                         goto err;
680                         }
681                 s2n(i,p);
682                 p+=i;
683
684                 /* COMPRESSION */
685                 if (s->ctx->comp_methods == NULL)
686                         j=0;
687                 else
688                         j=sk_SSL_COMP_num(s->ctx->comp_methods);
689                 *(p++)=1+j;
690                 for (i=0; i<j; i++)
691                         {
692                         comp=sk_SSL_COMP_value(s->ctx->comp_methods,i);
693                         *(p++)=comp->id;
694                         }
695                 *(p++)=0; /* Add the NULL method */
696
697 #ifndef OPENSSL_NO_TLSEXT
698                 if ((p = ssl_add_clienthello_tlsext(s, p, buf+SSL3_RT_MAX_PLAIN_LENGTH)) == NULL)
699                         {
700                         SSLerr(SSL_F_DTLS1_CLIENT_HELLO,ERR_R_INTERNAL_ERROR);
701                         goto err;
702                         }
703 #endif          
704
705                 l=(p-d);
706                 d=buf;
707
708                 d = dtls1_set_message_header(s, d, SSL3_MT_CLIENT_HELLO, l, 0, l);
709
710                 s->state=SSL3_ST_CW_CLNT_HELLO_B;
711                 /* number of bytes to write */
712                 s->init_num=p-buf;
713                 s->init_off=0;
714
715                 /* buffer the message to handle re-xmits */
716                 dtls1_buffer_message(s, 0);
717                 }
718
719         /* SSL3_ST_CW_CLNT_HELLO_B */
720         return(dtls1_do_write(s,SSL3_RT_HANDSHAKE));
721 err:
722         return(-1);
723         }
724
725 static int dtls1_get_hello_verify(SSL *s)
726         {
727         int n, al, ok = 0;
728         unsigned char *data;
729         unsigned int cookie_len;
730
731         n=s->method->ssl_get_message(s,
732                 DTLS1_ST_CR_HELLO_VERIFY_REQUEST_A,
733                 DTLS1_ST_CR_HELLO_VERIFY_REQUEST_B,
734                 -1,
735                 s->max_cert_list,
736                 &ok);
737
738         if (!ok) return((int)n);
739
740         if (s->s3->tmp.message_type != DTLS1_MT_HELLO_VERIFY_REQUEST)
741                 {
742                 s->d1->send_cookie = 0;
743                 s->s3->tmp.reuse_message=1;
744                 return(1);
745                 }
746
747         data = (unsigned char *)s->init_msg;
748
749         if ((data[0] != (s->version>>8)) || (data[1] != (s->version&0xff)))
750                 {
751                 SSLerr(SSL_F_DTLS1_GET_HELLO_VERIFY,SSL_R_WRONG_SSL_VERSION);
752                 s->version=(s->version&0xff00)|data[1];
753                 al = SSL_AD_PROTOCOL_VERSION;
754                 goto f_err;
755                 }
756         data+=2;
757
758         cookie_len = *(data++);
759         if ( cookie_len > sizeof(s->d1->cookie))
760                 {
761                 al=SSL_AD_ILLEGAL_PARAMETER;
762                 goto f_err;
763                 }
764
765         memcpy(s->d1->cookie, data, cookie_len);
766         s->d1->cookie_len = cookie_len;
767
768         s->d1->send_cookie = 1;
769         return 1;
770
771 f_err:
772         ssl3_send_alert(s, SSL3_AL_FATAL, al);
773         return -1;
774         }
775
776 int dtls1_send_client_key_exchange(SSL *s)
777         {
778         unsigned char *p,*d;
779         int n;
780         unsigned long alg_k;
781 #ifndef OPENSSL_NO_RSA
782         unsigned char *q;
783         EVP_PKEY *pkey=NULL;
784 #endif
785 #ifndef OPENSSL_NO_KRB5
786         KSSL_ERR kssl_err;
787 #endif /* OPENSSL_NO_KRB5 */
788 #ifndef OPENSSL_NO_ECDH
789         EC_KEY *clnt_ecdh = NULL;
790         const EC_POINT *srvr_ecpoint = NULL;
791         EVP_PKEY *srvr_pub_pkey = NULL;
792         unsigned char *encodedPoint = NULL;
793         int encoded_pt_len = 0;
794         BN_CTX * bn_ctx = NULL;
795 #endif
796
797         if (s->state == SSL3_ST_CW_KEY_EXCH_A)
798                 {
799                 d=(unsigned char *)s->init_buf->data;
800                 p= &(d[DTLS1_HM_HEADER_LENGTH]);
801                 
802                 alg_k=s->s3->tmp.new_cipher->algorithm_mkey;
803
804                 /* Fool emacs indentation */
805                 if (0) {}
806 #ifndef OPENSSL_NO_RSA
807                 else if (alg_k & SSL_kRSA)
808                         {
809                         RSA *rsa;
810                         unsigned char tmp_buf[SSL_MAX_MASTER_KEY_LENGTH];
811
812                         if (s->session->sess_cert->peer_rsa_tmp != NULL)
813                                 rsa=s->session->sess_cert->peer_rsa_tmp;
814                         else
815                                 {
816                                 pkey=X509_get_pubkey(s->session->sess_cert->peer_pkeys[SSL_PKEY_RSA_ENC].x509);
817                                 if ((pkey == NULL) ||
818                                         (pkey->type != EVP_PKEY_RSA) ||
819                                         (pkey->pkey.rsa == NULL))
820                                         {
821                                         SSLerr(SSL_F_DTLS1_SEND_CLIENT_KEY_EXCHANGE,ERR_R_INTERNAL_ERROR);
822                                         goto err;
823                                         }
824                                 rsa=pkey->pkey.rsa;
825                                 EVP_PKEY_free(pkey);
826                                 }
827                                 
828                         tmp_buf[0]=s->client_version>>8;
829                         tmp_buf[1]=s->client_version&0xff;
830                         if (RAND_bytes(&(tmp_buf[2]),sizeof tmp_buf-2) <= 0)
831                                         goto err;
832
833                         s->session->master_key_length=sizeof tmp_buf;
834
835                         q=p;
836                         /* Fix buf for TLS and [incidentally] DTLS */
837                         if (s->version > SSL3_VERSION)
838                                 p+=2;
839                         n=RSA_public_encrypt(sizeof tmp_buf,
840                                 tmp_buf,p,rsa,RSA_PKCS1_PADDING);
841 #ifdef PKCS1_CHECK
842                         if (s->options & SSL_OP_PKCS1_CHECK_1) p[1]++;
843                         if (s->options & SSL_OP_PKCS1_CHECK_2) tmp_buf[0]=0x70;
844 #endif
845                         if (n <= 0)
846                                 {
847                                 SSLerr(SSL_F_DTLS1_SEND_CLIENT_KEY_EXCHANGE,SSL_R_BAD_RSA_ENCRYPT);
848                                 goto err;
849                                 }
850
851                         /* Fix buf for TLS and [incidentally] DTLS */
852                         if (s->version > SSL3_VERSION)
853                                 {
854                                 s2n(n,q);
855                                 n+=2;
856                                 }
857
858                         s->session->master_key_length=
859                                 s->method->ssl3_enc->generate_master_secret(s,
860                                         s->session->master_key,
861                                         tmp_buf,sizeof tmp_buf);
862                         OPENSSL_cleanse(tmp_buf,sizeof tmp_buf);
863                         }
864 #endif
865 #ifndef OPENSSL_NO_KRB5
866                 else if (alg_k & SSL_kKRB5)
867                         {
868                         krb5_error_code krb5rc;
869                         KSSL_CTX        *kssl_ctx = s->kssl_ctx;
870                         /*  krb5_data   krb5_ap_req;  */
871                         krb5_data       *enc_ticket;
872                         krb5_data       authenticator, *authp = NULL;
873                         EVP_CIPHER_CTX  ciph_ctx;
874                         const EVP_CIPHER *enc = NULL;
875                         unsigned char   iv[EVP_MAX_IV_LENGTH];
876                         unsigned char   tmp_buf[SSL_MAX_MASTER_KEY_LENGTH];
877                         unsigned char   epms[SSL_MAX_MASTER_KEY_LENGTH 
878                                                 + EVP_MAX_IV_LENGTH];
879                         int             padl, outl = sizeof(epms);
880
881                         EVP_CIPHER_CTX_init(&ciph_ctx);
882
883 #ifdef KSSL_DEBUG
884                         printf("ssl3_send_client_key_exchange(%lx & %lx)\n",
885                                 alg_k, SSL_kKRB5);
886 #endif  /* KSSL_DEBUG */
887
888                         authp = NULL;
889 #ifdef KRB5SENDAUTH
890                         if (KRB5SENDAUTH)  authp = &authenticator;
891 #endif  /* KRB5SENDAUTH */
892
893                         krb5rc = kssl_cget_tkt(kssl_ctx, &enc_ticket, authp,
894                                 &kssl_err);
895                         enc = kssl_map_enc(kssl_ctx->enctype);
896                         if (enc == NULL)
897                             goto err;
898 #ifdef KSSL_DEBUG
899                         {
900                         printf("kssl_cget_tkt rtn %d\n", krb5rc);
901                         if (krb5rc && kssl_err.text)
902                           printf("kssl_cget_tkt kssl_err=%s\n", kssl_err.text);
903                         }
904 #endif  /* KSSL_DEBUG */
905
906                         if (krb5rc)
907                                 {
908                                 ssl3_send_alert(s,SSL3_AL_FATAL,
909                                                 SSL_AD_HANDSHAKE_FAILURE);
910                                 SSLerr(SSL_F_DTLS1_SEND_CLIENT_KEY_EXCHANGE,
911                                                 kssl_err.reason);
912                                 goto err;
913                                 }
914
915                         /*  20010406 VRS - Earlier versions used KRB5 AP_REQ
916                         **  in place of RFC 2712 KerberosWrapper, as in:
917                         **
918                         **  Send ticket (copy to *p, set n = length)
919                         **  n = krb5_ap_req.length;
920                         **  memcpy(p, krb5_ap_req.data, krb5_ap_req.length);
921                         **  if (krb5_ap_req.data)  
922                         **    kssl_krb5_free_data_contents(NULL,&krb5_ap_req);
923                         **
924                         **  Now using real RFC 2712 KerberosWrapper
925                         **  (Thanks to Simon Wilkinson <sxw@sxw.org.uk>)
926                         **  Note: 2712 "opaque" types are here replaced
927                         **  with a 2-byte length followed by the value.
928                         **  Example:
929                         **  KerberosWrapper= xx xx asn1ticket 0 0 xx xx encpms
930                         **  Where "xx xx" = length bytes.  Shown here with
931                         **  optional authenticator omitted.
932                         */
933
934                         /*  KerberosWrapper.Ticket              */
935                         s2n(enc_ticket->length,p);
936                         memcpy(p, enc_ticket->data, enc_ticket->length);
937                         p+= enc_ticket->length;
938                         n = enc_ticket->length + 2;
939
940                         /*  KerberosWrapper.Authenticator       */
941                         if (authp  &&  authp->length)  
942                                 {
943                                 s2n(authp->length,p);
944                                 memcpy(p, authp->data, authp->length);
945                                 p+= authp->length;
946                                 n+= authp->length + 2;
947                                 
948                                 free(authp->data);
949                                 authp->data = NULL;
950                                 authp->length = 0;
951                                 }
952                         else
953                                 {
954                                 s2n(0,p);/*  null authenticator length  */
955                                 n+=2;
956                                 }
957  
958                         if (RAND_bytes(tmp_buf,sizeof tmp_buf) <= 0)
959                             goto err;
960
961                         /*  20010420 VRS.  Tried it this way; failed.
962                         **      EVP_EncryptInit_ex(&ciph_ctx,enc, NULL,NULL);
963                         **      EVP_CIPHER_CTX_set_key_length(&ciph_ctx,
964                         **                              kssl_ctx->length);
965                         **      EVP_EncryptInit_ex(&ciph_ctx,NULL, key,iv);
966                         */
967
968                         memset(iv, 0, sizeof iv);  /* per RFC 1510 */
969                         EVP_EncryptInit_ex(&ciph_ctx,enc, NULL,
970                                 kssl_ctx->key,iv);
971                         EVP_EncryptUpdate(&ciph_ctx,epms,&outl,tmp_buf,
972                                 sizeof tmp_buf);
973                         EVP_EncryptFinal_ex(&ciph_ctx,&(epms[outl]),&padl);
974                         outl += padl;
975                         if (outl > (int)sizeof epms)
976                                 {
977                                 SSLerr(SSL_F_DTLS1_SEND_CLIENT_KEY_EXCHANGE, ERR_R_INTERNAL_ERROR);
978                                 goto err;
979                                 }
980                         EVP_CIPHER_CTX_cleanup(&ciph_ctx);
981
982                         /*  KerberosWrapper.EncryptedPreMasterSecret    */
983                         s2n(outl,p);
984                         memcpy(p, epms, outl);
985                         p+=outl;
986                         n+=outl + 2;
987
988                         s->session->master_key_length=
989                                 s->method->ssl3_enc->generate_master_secret(s,
990                                         s->session->master_key,
991                                         tmp_buf, sizeof tmp_buf);
992
993                         OPENSSL_cleanse(tmp_buf, sizeof tmp_buf);
994                         OPENSSL_cleanse(epms, outl);
995                         }
996 #endif
997 #ifndef OPENSSL_NO_DH
998                 else if (alg_k & (SSL_kEDH|SSL_kDHr|SSL_kDHd))
999                         {
1000                         DH *dh_srvr,*dh_clnt;
1001
1002                         if (s->session->sess_cert->peer_dh_tmp != NULL)
1003                                 dh_srvr=s->session->sess_cert->peer_dh_tmp;
1004                         else
1005                                 {
1006                                 /* we get them from the cert */
1007                                 ssl3_send_alert(s,SSL3_AL_FATAL,SSL_AD_HANDSHAKE_FAILURE);
1008                                 SSLerr(SSL_F_DTLS1_SEND_CLIENT_KEY_EXCHANGE,SSL_R_UNABLE_TO_FIND_DH_PARAMETERS);
1009                                 goto err;
1010                                 }
1011                         
1012                         /* generate a new random key */
1013                         if ((dh_clnt=DHparams_dup(dh_srvr)) == NULL)
1014                                 {
1015                                 SSLerr(SSL_F_DTLS1_SEND_CLIENT_KEY_EXCHANGE,ERR_R_DH_LIB);
1016                                 goto err;
1017                                 }
1018                         if (!DH_generate_key(dh_clnt))
1019                                 {
1020                                 SSLerr(SSL_F_DTLS1_SEND_CLIENT_KEY_EXCHANGE,ERR_R_DH_LIB);
1021                                 goto err;
1022                                 }
1023
1024                         /* use the 'p' output buffer for the DH key, but
1025                          * make sure to clear it out afterwards */
1026
1027                         n=DH_compute_key(p,dh_srvr->pub_key,dh_clnt);
1028
1029                         if (n <= 0)
1030                                 {
1031                                 SSLerr(SSL_F_DTLS1_SEND_CLIENT_KEY_EXCHANGE,ERR_R_DH_LIB);
1032                                 goto err;
1033                                 }
1034
1035                         /* generate master key from the result */
1036                         s->session->master_key_length=
1037                                 s->method->ssl3_enc->generate_master_secret(s,
1038                                         s->session->master_key,p,n);
1039                         /* clean up */
1040                         memset(p,0,n);
1041
1042                         /* send off the data */
1043                         n=BN_num_bytes(dh_clnt->pub_key);
1044                         s2n(n,p);
1045                         BN_bn2bin(dh_clnt->pub_key,p);
1046                         n+=2;
1047
1048                         DH_free(dh_clnt);
1049
1050                         /* perhaps clean things up a bit EAY EAY EAY EAY*/
1051                         }
1052 #endif
1053 #ifndef OPENSSL_NO_ECDH 
1054                 else if (alg_k & (SSL_kEECDH|SSL_kECDHr|SSL_kECDHe))
1055                         {
1056                         const EC_GROUP *srvr_group = NULL;
1057                         EC_KEY *tkey;
1058                         int ecdh_clnt_cert = 0;
1059                         int field_size = 0;
1060
1061                         /* Did we send out the client's
1062                          * ECDH share for use in premaster
1063                          * computation as part of client certificate?
1064                          * If so, set ecdh_clnt_cert to 1.
1065                          */
1066                         if ((alg_k & (SSL_kECDHr|SSL_kECDHe)) && (s->cert != NULL)) 
1067                                 {
1068                                 /* XXX: For now, we do not support client
1069                                  * authentication using ECDH certificates.
1070                                  * To add such support, one needs to add
1071                                  * code that checks for appropriate 
1072                                  * conditions and sets ecdh_clnt_cert to 1.
1073                                  * For example, the cert have an ECC
1074                                  * key on the same curve as the server's
1075                                  * and the key should be authorized for
1076                                  * key agreement.
1077                                  *
1078                                  * One also needs to add code in ssl3_connect
1079                                  * to skip sending the certificate verify
1080                                  * message.
1081                                  *
1082                                  * if ((s->cert->key->privatekey != NULL) &&
1083                                  *     (s->cert->key->privatekey->type ==
1084                                  *      EVP_PKEY_EC) && ...)
1085                                  * ecdh_clnt_cert = 1;
1086                                  */
1087                                 }
1088
1089                         if (s->session->sess_cert->peer_ecdh_tmp != NULL)
1090                                 {
1091                                 tkey = s->session->sess_cert->peer_ecdh_tmp;
1092                                 }
1093                         else
1094                                 {
1095                                 /* Get the Server Public Key from Cert */
1096                                 srvr_pub_pkey = X509_get_pubkey(s->session-> \
1097                                     sess_cert->peer_pkeys[SSL_PKEY_ECC].x509);
1098                                 if ((srvr_pub_pkey == NULL) ||
1099                                     (srvr_pub_pkey->type != EVP_PKEY_EC) ||
1100                                     (srvr_pub_pkey->pkey.ec == NULL))
1101                                         {
1102                                         SSLerr(SSL_F_DTLS1_SEND_CLIENT_KEY_EXCHANGE,
1103                                             ERR_R_INTERNAL_ERROR);
1104                                         goto err;
1105                                         }
1106
1107                                 tkey = srvr_pub_pkey->pkey.ec;
1108                                 }
1109
1110                         srvr_group   = EC_KEY_get0_group(tkey);
1111                         srvr_ecpoint = EC_KEY_get0_public_key(tkey);
1112
1113                         if ((srvr_group == NULL) || (srvr_ecpoint == NULL))
1114                                 {
1115                                 SSLerr(SSL_F_DTLS1_SEND_CLIENT_KEY_EXCHANGE,
1116                                     ERR_R_INTERNAL_ERROR);
1117                                 goto err;
1118                                 }
1119
1120                         if ((clnt_ecdh=EC_KEY_new()) == NULL) 
1121                                 {
1122                                 SSLerr(SSL_F_DTLS1_SEND_CLIENT_KEY_EXCHANGE,ERR_R_MALLOC_FAILURE);
1123                                 goto err;
1124                                 }
1125
1126                         if (!EC_KEY_set_group(clnt_ecdh, srvr_group))
1127                                 {
1128                                 SSLerr(SSL_F_DTLS1_SEND_CLIENT_KEY_EXCHANGE,ERR_R_EC_LIB);
1129                                 goto err;
1130                                 }
1131                         if (ecdh_clnt_cert) 
1132                                 { 
1133                                 /* Reuse key info from our certificate
1134                                  * We only need our private key to perform
1135                                  * the ECDH computation.
1136                                  */
1137                                 const BIGNUM *priv_key;
1138                                 tkey = s->cert->key->privatekey->pkey.ec;
1139                                 priv_key = EC_KEY_get0_private_key(tkey);
1140                                 if (priv_key == NULL)
1141                                         {
1142                                         SSLerr(SSL_F_DTLS1_SEND_CLIENT_KEY_EXCHANGE,ERR_R_MALLOC_FAILURE);
1143                                         goto err;
1144                                         }
1145                                 if (!EC_KEY_set_private_key(clnt_ecdh, priv_key))
1146                                         {
1147                                         SSLerr(SSL_F_DTLS1_SEND_CLIENT_KEY_EXCHANGE,ERR_R_EC_LIB);
1148                                         goto err;
1149                                         }
1150                                 }
1151                         else 
1152                                 {
1153                                 /* Generate a new ECDH key pair */
1154                                 if (!(EC_KEY_generate_key(clnt_ecdh)))
1155                                         {
1156                                         SSLerr(SSL_F_DTLS1_SEND_CLIENT_KEY_EXCHANGE, ERR_R_ECDH_LIB);
1157                                         goto err;
1158                                         }
1159                                 }
1160
1161                         /* use the 'p' output buffer for the ECDH key, but
1162                          * make sure to clear it out afterwards
1163                          */
1164
1165                         field_size = EC_GROUP_get_degree(srvr_group);
1166                         if (field_size <= 0)
1167                                 {
1168                                 SSLerr(SSL_F_DTLS1_SEND_CLIENT_KEY_EXCHANGE, 
1169                                        ERR_R_ECDH_LIB);
1170                                 goto err;
1171                                 }
1172                         n=ECDH_compute_key(p, (field_size+7)/8, srvr_ecpoint, clnt_ecdh, NULL);
1173                         if (n <= 0)
1174                                 {
1175                                 SSLerr(SSL_F_DTLS1_SEND_CLIENT_KEY_EXCHANGE, 
1176                                        ERR_R_ECDH_LIB);
1177                                 goto err;
1178                                 }
1179
1180                         /* generate master key from the result */
1181                         s->session->master_key_length = s->method->ssl3_enc \
1182                             -> generate_master_secret(s, 
1183                                 s->session->master_key,
1184                                 p, n);
1185
1186                         memset(p, 0, n); /* clean up */
1187
1188                         if (ecdh_clnt_cert) 
1189                                 {
1190                                 /* Send empty client key exch message */
1191                                 n = 0;
1192                                 }
1193                         else 
1194                                 {
1195                                 /* First check the size of encoding and
1196                                  * allocate memory accordingly.
1197                                  */
1198                                 encoded_pt_len = 
1199                                     EC_POINT_point2oct(srvr_group, 
1200                                         EC_KEY_get0_public_key(clnt_ecdh), 
1201                                         POINT_CONVERSION_UNCOMPRESSED, 
1202                                         NULL, 0, NULL);
1203
1204                                 encodedPoint = (unsigned char *) 
1205                                     OPENSSL_malloc(encoded_pt_len * 
1206                                         sizeof(unsigned char)); 
1207                                 bn_ctx = BN_CTX_new();
1208                                 if ((encodedPoint == NULL) || 
1209                                     (bn_ctx == NULL)) 
1210                                         {
1211                                         SSLerr(SSL_F_DTLS1_SEND_CLIENT_KEY_EXCHANGE,ERR_R_MALLOC_FAILURE);
1212                                         goto err;
1213                                         }
1214
1215                                 /* Encode the public key */
1216                                 n = EC_POINT_point2oct(srvr_group, 
1217                                     EC_KEY_get0_public_key(clnt_ecdh), 
1218                                     POINT_CONVERSION_UNCOMPRESSED, 
1219                                     encodedPoint, encoded_pt_len, bn_ctx);
1220
1221                                 *p = n; /* length of encoded point */
1222                                 /* Encoded point will be copied here */
1223                                 p += 1; 
1224                                 /* copy the point */
1225                                 memcpy((unsigned char *)p, encodedPoint, n);
1226                                 /* increment n to account for length field */
1227                                 n += 1; 
1228                                 }
1229
1230                         /* Free allocated memory */
1231                         BN_CTX_free(bn_ctx);
1232                         if (encodedPoint != NULL) OPENSSL_free(encodedPoint);
1233                         if (clnt_ecdh != NULL) 
1234                                  EC_KEY_free(clnt_ecdh);
1235                         EVP_PKEY_free(srvr_pub_pkey);
1236                         }
1237 #endif /* !OPENSSL_NO_ECDH */
1238
1239 #ifndef OPENSSL_NO_PSK
1240                 else if (alg_k & SSL_kPSK)
1241                         {
1242                         char identity[PSK_MAX_IDENTITY_LEN];
1243                         unsigned char *t = NULL;
1244                         unsigned char psk_or_pre_ms[PSK_MAX_PSK_LEN*2+4];
1245                         unsigned int pre_ms_len = 0, psk_len = 0;
1246                         int psk_err = 1;
1247
1248                         n = 0;
1249                         if (s->psk_client_callback == NULL)
1250                                 {
1251                                 SSLerr(SSL_F_DTLS1_SEND_CLIENT_KEY_EXCHANGE,
1252                                         SSL_R_PSK_NO_CLIENT_CB);
1253                                 goto err;
1254                                 }
1255
1256                         psk_len = s->psk_client_callback(s, s->ctx->psk_identity_hint,
1257                                 identity, PSK_MAX_IDENTITY_LEN,
1258                                 psk_or_pre_ms, sizeof(psk_or_pre_ms));
1259                         if (psk_len > PSK_MAX_PSK_LEN)
1260                                 {
1261                                 SSLerr(SSL_F_DTLS1_SEND_CLIENT_KEY_EXCHANGE,
1262                                         ERR_R_INTERNAL_ERROR);
1263                                 goto psk_err;
1264                                 }
1265                         else if (psk_len == 0)
1266                                 {
1267                                 SSLerr(SSL_F_DTLS1_SEND_CLIENT_KEY_EXCHANGE,
1268                                         SSL_R_PSK_IDENTITY_NOT_FOUND);
1269                                 goto psk_err;
1270                                 }
1271
1272                         /* create PSK pre_master_secret */
1273                         pre_ms_len = 2+psk_len+2+psk_len;
1274                         t = psk_or_pre_ms;
1275                         memmove(psk_or_pre_ms+psk_len+4, psk_or_pre_ms, psk_len);
1276                         s2n(psk_len, t);
1277                         memset(t, 0, psk_len);
1278                         t+=psk_len;
1279                         s2n(psk_len, t);
1280
1281                         if (s->session->psk_identity_hint != NULL)
1282                                 OPENSSL_free(s->session->psk_identity_hint);
1283                         s->session->psk_identity_hint = BUF_strdup(s->ctx->psk_identity_hint);
1284                         if (s->ctx->psk_identity_hint != NULL &&
1285                                 s->session->psk_identity_hint == NULL)
1286                                 {
1287                                 SSLerr(SSL_F_DTLS1_SEND_CLIENT_KEY_EXCHANGE,
1288                                         ERR_R_MALLOC_FAILURE);
1289                                 goto psk_err;
1290                                 }
1291
1292                         if (s->session->psk_identity != NULL)
1293                                 OPENSSL_free(s->session->psk_identity);
1294                         s->session->psk_identity = BUF_strdup(identity);
1295                         if (s->session->psk_identity == NULL)
1296                                 {
1297                                 SSLerr(SSL_F_DTLS1_SEND_CLIENT_KEY_EXCHANGE,
1298                                         ERR_R_MALLOC_FAILURE);
1299                                 goto psk_err;
1300                                 }
1301
1302                         s->session->master_key_length =
1303                                 s->method->ssl3_enc->generate_master_secret(s,
1304                                         s->session->master_key,
1305                                         psk_or_pre_ms, pre_ms_len); 
1306                         n = strlen(identity);
1307                         s2n(n, p);
1308                         memcpy(p, identity, n);
1309                         n+=2;
1310                         psk_err = 0;
1311                 psk_err:
1312                         OPENSSL_cleanse(identity, PSK_MAX_IDENTITY_LEN);
1313                         OPENSSL_cleanse(psk_or_pre_ms, sizeof(psk_or_pre_ms));
1314                         if (psk_err != 0)
1315                                 {
1316                                 ssl3_send_alert(s, SSL3_AL_FATAL, SSL_AD_HANDSHAKE_FAILURE);
1317                                 goto err;
1318                                 }
1319                         }
1320 #endif
1321                 else
1322                         {
1323                         ssl3_send_alert(s,SSL3_AL_FATAL,SSL_AD_HANDSHAKE_FAILURE);
1324                         SSLerr(SSL_F_DTLS1_SEND_CLIENT_KEY_EXCHANGE,ERR_R_INTERNAL_ERROR);
1325                         goto err;
1326                         }
1327                 
1328                 d = dtls1_set_message_header(s, d,
1329                 SSL3_MT_CLIENT_KEY_EXCHANGE, n, 0, n);
1330                 /*
1331                  *(d++)=SSL3_MT_CLIENT_KEY_EXCHANGE;
1332                  l2n3(n,d);
1333                  l2n(s->d1->handshake_write_seq,d);
1334                  s->d1->handshake_write_seq++;
1335                 */
1336                 
1337                 s->state=SSL3_ST_CW_KEY_EXCH_B;
1338                 /* number of bytes to write */
1339                 s->init_num=n+DTLS1_HM_HEADER_LENGTH;
1340                 s->init_off=0;
1341
1342                 /* buffer the message to handle re-xmits */
1343                 dtls1_buffer_message(s, 0);
1344                 }
1345         
1346         /* SSL3_ST_CW_KEY_EXCH_B */
1347         return(dtls1_do_write(s,SSL3_RT_HANDSHAKE));
1348 err:
1349 #ifndef OPENSSL_NO_ECDH
1350         BN_CTX_free(bn_ctx);
1351         if (encodedPoint != NULL) OPENSSL_free(encodedPoint);
1352         if (clnt_ecdh != NULL) 
1353                 EC_KEY_free(clnt_ecdh);
1354         EVP_PKEY_free(srvr_pub_pkey);
1355 #endif
1356         return(-1);
1357         }
1358
1359 int dtls1_send_client_verify(SSL *s)
1360         {
1361         unsigned char *p,*d;
1362         unsigned char data[MD5_DIGEST_LENGTH+SHA_DIGEST_LENGTH];
1363         EVP_PKEY *pkey;
1364 #ifndef OPENSSL_NO_RSA
1365         unsigned u=0;
1366 #endif
1367         unsigned long n;
1368 #if !defined(OPENSSL_NO_DSA) || !defined(OPENSSL_NO_ECDSA)
1369         int j;
1370 #endif
1371
1372         if (s->state == SSL3_ST_CW_CERT_VRFY_A)
1373                 {
1374                 d=(unsigned char *)s->init_buf->data;
1375                 p= &(d[DTLS1_HM_HEADER_LENGTH]);
1376                 pkey=s->cert->key->privatekey;
1377
1378                 s->method->ssl3_enc->cert_verify_mac(s,
1379                 NID_sha1,
1380                         &(data[MD5_DIGEST_LENGTH]));
1381
1382 #ifndef OPENSSL_NO_RSA
1383                 if (pkey->type == EVP_PKEY_RSA)
1384                         {
1385                         s->method->ssl3_enc->cert_verify_mac(s,
1386                                 NID_md5,
1387                                 &(data[0]));
1388                         if (RSA_sign(NID_md5_sha1, data,
1389                                          MD5_DIGEST_LENGTH+SHA_DIGEST_LENGTH,
1390                                         &(p[2]), &u, pkey->pkey.rsa) <= 0 )
1391                                 {
1392                                 SSLerr(SSL_F_DTLS1_SEND_CLIENT_VERIFY,ERR_R_RSA_LIB);
1393                                 goto err;
1394                                 }
1395                         s2n(u,p);
1396                         n=u+2;
1397                         }
1398                 else
1399 #endif
1400 #ifndef OPENSSL_NO_DSA
1401                         if (pkey->type == EVP_PKEY_DSA)
1402                         {
1403                         if (!DSA_sign(pkey->save_type,
1404                                 &(data[MD5_DIGEST_LENGTH]),
1405                                 SHA_DIGEST_LENGTH,&(p[2]),
1406                                 (unsigned int *)&j,pkey->pkey.dsa))
1407                                 {
1408                                 SSLerr(SSL_F_DTLS1_SEND_CLIENT_VERIFY,ERR_R_DSA_LIB);
1409                                 goto err;
1410                                 }
1411                         s2n(j,p);
1412                         n=j+2;
1413                         }
1414                 else
1415 #endif
1416 #ifndef OPENSSL_NO_ECDSA
1417                         if (pkey->type == EVP_PKEY_EC)
1418                         {
1419                         if (!ECDSA_sign(pkey->save_type,
1420                                 &(data[MD5_DIGEST_LENGTH]),
1421                                 SHA_DIGEST_LENGTH,&(p[2]),
1422                                 (unsigned int *)&j,pkey->pkey.ec))
1423                                 {
1424                                 SSLerr(SSL_F_DTLS1_SEND_CLIENT_VERIFY,
1425                                     ERR_R_ECDSA_LIB);
1426                                 goto err;
1427                                 }
1428                         s2n(j,p);
1429                         n=j+2;
1430                         }
1431                 else
1432 #endif
1433                         {
1434                         SSLerr(SSL_F_DTLS1_SEND_CLIENT_VERIFY,ERR_R_INTERNAL_ERROR);
1435                         goto err;
1436                         }
1437
1438                 d = dtls1_set_message_header(s, d,
1439                         SSL3_MT_CERTIFICATE_VERIFY, n, 0, n) ;
1440
1441                 s->init_num=(int)n+DTLS1_HM_HEADER_LENGTH;
1442                 s->init_off=0;
1443
1444                 /* buffer the message to handle re-xmits */
1445                 dtls1_buffer_message(s, 0);
1446
1447                 s->state = SSL3_ST_CW_CERT_VRFY_B;
1448                 }
1449
1450         /* s->state = SSL3_ST_CW_CERT_VRFY_B */
1451         return(dtls1_do_write(s,SSL3_RT_HANDSHAKE));
1452 err:
1453         return(-1);
1454         }
1455
1456 int dtls1_send_client_certificate(SSL *s)
1457         {
1458         X509 *x509=NULL;
1459         EVP_PKEY *pkey=NULL;
1460         int i;
1461         unsigned long l;
1462
1463         if (s->state == SSL3_ST_CW_CERT_A)
1464                 {
1465                 if ((s->cert == NULL) ||
1466                         (s->cert->key->x509 == NULL) ||
1467                         (s->cert->key->privatekey == NULL))
1468                         s->state=SSL3_ST_CW_CERT_B;
1469                 else
1470                         s->state=SSL3_ST_CW_CERT_C;
1471                 }
1472
1473         /* We need to get a client cert */
1474         if (s->state == SSL3_ST_CW_CERT_B)
1475                 {
1476                 /* If we get an error, we need to
1477                  * ssl->rwstate=SSL_X509_LOOKUP; return(-1);
1478                  * We then get retied later */
1479                 i=0;
1480                 i = ssl_do_client_cert_cb(s, &x509, &pkey);
1481                 if (i < 0)
1482                         {
1483                         s->rwstate=SSL_X509_LOOKUP;
1484                         return(-1);
1485                         }
1486                 s->rwstate=SSL_NOTHING;
1487                 if ((i == 1) && (pkey != NULL) && (x509 != NULL))
1488                         {
1489                         s->state=SSL3_ST_CW_CERT_B;
1490                         if (    !SSL_use_certificate(s,x509) ||
1491                                 !SSL_use_PrivateKey(s,pkey))
1492                                 i=0;
1493                         }
1494                 else if (i == 1)
1495                         {
1496                         i=0;
1497                         SSLerr(SSL_F_DTLS1_SEND_CLIENT_CERTIFICATE,SSL_R_BAD_DATA_RETURNED_BY_CALLBACK);
1498                         }
1499
1500                 if (x509 != NULL) X509_free(x509);
1501                 if (pkey != NULL) EVP_PKEY_free(pkey);
1502                 if (i == 0)
1503                         {
1504                         if (s->version == SSL3_VERSION)
1505                                 {
1506                                 s->s3->tmp.cert_req=0;
1507                                 ssl3_send_alert(s,SSL3_AL_WARNING,SSL_AD_NO_CERTIFICATE);
1508                                 return(1);
1509                                 }
1510                         else
1511                                 {
1512                                 s->s3->tmp.cert_req=2;
1513                                 }
1514                         }
1515
1516                 /* Ok, we have a cert */
1517                 s->state=SSL3_ST_CW_CERT_C;
1518                 }
1519
1520         if (s->state == SSL3_ST_CW_CERT_C)
1521                 {
1522                 s->state=SSL3_ST_CW_CERT_D;
1523                 l=dtls1_output_cert_chain(s,
1524                         (s->s3->tmp.cert_req == 2)?NULL:s->cert->key->x509);
1525                 s->init_num=(int)l;
1526                 s->init_off=0;
1527
1528                 /* set header called by dtls1_output_cert_chain() */
1529
1530                 /* buffer the message to handle re-xmits */
1531                 dtls1_buffer_message(s, 0);
1532                 }
1533         /* SSL3_ST_CW_CERT_D */
1534         return(dtls1_do_write(s,SSL3_RT_HANDSHAKE));
1535         }
1536
1537