Disable SHA256 if not supported.
[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 <openssl/crypto.h>
118 #include "ssl_locl.h"
119 #ifndef OPENSSL_NO_KRB5
120 #include "kssl_lcl.h"
121 #endif
122 #include <openssl/buffer.h>
123 #include <openssl/rand.h>
124 #include <openssl/objects.h>
125 #include <openssl/evp.h>
126 #include <openssl/md5.h>
127 #include <openssl/bn.h>
128 #ifndef OPENSSL_NO_DH
129 #include <openssl/dh.h>
130 #endif
131
132 static const SSL_METHOD *dtls1_get_client_method(int ver);
133 static int dtls1_get_hello_verify(SSL *s);
134
135 static const SSL_METHOD *dtls1_get_client_method(int ver)
136         {
137         if (ver == DTLS1_VERSION || ver == DTLS1_BAD_VER)
138                 return(DTLSv1_client_method());
139         else
140                 return(NULL);
141         }
142
143 IMPLEMENT_dtls1_meth_func(DTLSv1_client_method,
144                         ssl_undefined_function,
145                         dtls1_connect,
146                         dtls1_get_client_method)
147
148 int dtls1_connect(SSL *s)
149         {
150         BUF_MEM *buf=NULL;
151         unsigned long Time=(unsigned long)time(NULL);
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->renegotiate=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                         s->rwstate=SSL_WRITING;
515                         if (BIO_flush(s->wbio) <= 0)
516                                 {
517                                 ret= -1;
518                                 goto end;
519                                 }
520                         s->rwstate=SSL_NOTHING;
521                         s->state=s->s3->tmp.next_state;
522                         break;
523
524                 case SSL_ST_OK:
525                         /* clean a few things up */
526                         ssl3_cleanup_key_block(s);
527
528 #if 0
529                         if (s->init_buf != NULL)
530                                 {
531                                 BUF_MEM_free(s->init_buf);
532                                 s->init_buf=NULL;
533                                 }
534 #endif
535
536                         /* If we are not 'joining' the last two packets,
537                          * remove the buffering now */
538                         if (!(s->s3->flags & SSL3_FLAGS_POP_BUFFER))
539                                 ssl_free_wbio_buffer(s);
540                         /* else do it later in ssl3_write */
541
542                         s->init_num=0;
543                         s->renegotiate=0;
544                         s->new_session=0;
545
546                         ssl_update_cache(s,SSL_SESS_CACHE_CLIENT);
547                         if (s->hit) s->ctx->stats.sess_hit++;
548
549                         ret=1;
550                         /* s->server=0; */
551                         s->handshake_func=dtls1_connect;
552                         s->ctx->stats.sess_connect_good++;
553
554                         if (cb != NULL) cb(s,SSL_CB_HANDSHAKE_DONE,1);
555
556                         /* done with handshaking */
557                         s->d1->handshake_read_seq  = 0;
558                         s->d1->next_handshake_write_seq = 0;
559                         goto end;
560                         /* break; */
561                         
562                 default:
563                         SSLerr(SSL_F_DTLS1_CONNECT,SSL_R_UNKNOWN_STATE);
564                         ret= -1;
565                         goto end;
566                         /* break; */
567                         }
568
569                 /* did we do anything */
570                 if (!s->s3->tmp.reuse_message && !skip)
571                         {
572                         if (s->debug)
573                                 {
574                                 if ((ret=BIO_flush(s->wbio)) <= 0)
575                                         goto end;
576                                 }
577
578                         if ((cb != NULL) && (s->state != state))
579                                 {
580                                 new_state=s->state;
581                                 s->state=state;
582                                 cb(s,SSL_CB_CONNECT_LOOP,1);
583                                 s->state=new_state;
584                                 }
585                         }
586                 skip=0;
587                 }
588 end:
589         s->in_handshake--;
590         if (buf != NULL)
591                 BUF_MEM_free(buf);
592         if (cb != NULL)
593                 cb(s,SSL_CB_CONNECT_EXIT,ret);
594         return(ret);
595         }
596
597 int dtls1_client_hello(SSL *s)
598         {
599         unsigned char *buf;
600         unsigned char *p,*d;
601         unsigned int i,j;
602         unsigned long Time,l;
603         SSL_COMP *comp;
604
605         buf=(unsigned char *)s->init_buf->data;
606         if (s->state == SSL3_ST_CW_CLNT_HELLO_A)
607                 {
608                 SSL_SESSION *sess = s->session;
609                 if ((s->session == NULL) ||
610                         (s->session->ssl_version != s->version) ||
611 #ifdef OPENSSL_NO_TLSEXT
612                         !sess->session_id_length ||
613 #else
614                         (!sess->session_id_length && !sess->tlsext_tick) ||
615 #endif
616                         (s->session->not_resumable))
617                         {
618                         if (!ssl_get_new_session(s,0))
619                                 goto err;
620                         }
621                 /* else use the pre-loaded session */
622
623                 p=s->s3->client_random;
624
625                 /* if client_random is initialized, reuse it, we are
626                  * required to use same upon reply to HelloVerify */
627                 for (i=0;p[i]=='\0' && i<sizeof(s->s3->client_random);i++) ;
628                 if (i==sizeof(s->s3->client_random))
629                         {
630                         Time=(unsigned long)time(NULL); /* Time */
631                         l2n(Time,p);
632                         RAND_pseudo_bytes(p,sizeof(s->s3->client_random)-4);
633                         }
634
635                 /* Do the message type and length last */
636                 d=p= &(buf[DTLS1_HM_HEADER_LENGTH]);
637
638                 *(p++)=s->version>>8;
639                 *(p++)=s->version&0xff;
640                 s->client_version=s->version;
641
642                 /* Random stuff */
643                 memcpy(p,s->s3->client_random,SSL3_RANDOM_SIZE);
644                 p+=SSL3_RANDOM_SIZE;
645
646                 /* Session ID */
647                 if (s->new_session)
648                         i=0;
649                 else
650                         i=s->session->session_id_length;
651                 *(p++)=i;
652                 if (i != 0)
653                         {
654                         if (i > sizeof s->session->session_id)
655                                 {
656                                 SSLerr(SSL_F_DTLS1_CLIENT_HELLO, ERR_R_INTERNAL_ERROR);
657                                 goto err;
658                                 }
659                         memcpy(p,s->session->session_id,i);
660                         p+=i;
661                         }
662                 
663                 /* cookie stuff */
664                 if ( s->d1->cookie_len > sizeof(s->d1->cookie))
665                         {
666                         SSLerr(SSL_F_DTLS1_CLIENT_HELLO, ERR_R_INTERNAL_ERROR);
667                         goto err;
668                         }
669                 *(p++) = s->d1->cookie_len;
670                 memcpy(p, s->d1->cookie, s->d1->cookie_len);
671                 p += s->d1->cookie_len;
672
673                 /* Ciphers supported */
674                 i=ssl_cipher_list_to_bytes(s,SSL_get_ciphers(s),&(p[2]),0);
675                 if (i == 0)
676                         {
677                         SSLerr(SSL_F_DTLS1_CLIENT_HELLO,SSL_R_NO_CIPHERS_AVAILABLE);
678                         goto err;
679                         }
680                 s2n(i,p);
681                 p+=i;
682
683                 /* COMPRESSION */
684                 if (s->ctx->comp_methods == NULL)
685                         j=0;
686                 else
687                         j=sk_SSL_COMP_num(s->ctx->comp_methods);
688                 *(p++)=1+j;
689                 for (i=0; i<j; i++)
690                         {
691                         comp=sk_SSL_COMP_value(s->ctx->comp_methods,i);
692                         *(p++)=comp->id;
693                         }
694                 *(p++)=0; /* Add the NULL method */
695
696 #ifndef OPENSSL_NO_TLSEXT
697                 if ((p = ssl_add_clienthello_tlsext(s, p, buf+SSL3_RT_MAX_PLAIN_LENGTH)) == NULL)
698                         {
699                         SSLerr(SSL_F_DTLS1_CLIENT_HELLO,ERR_R_INTERNAL_ERROR);
700                         goto err;
701                         }
702 #endif          
703
704                 l=(p-d);
705                 d=buf;
706
707                 d = dtls1_set_message_header(s, d, SSL3_MT_CLIENT_HELLO, l, 0, l);
708
709                 s->state=SSL3_ST_CW_CLNT_HELLO_B;
710                 /* number of bytes to write */
711                 s->init_num=p-buf;
712                 s->init_off=0;
713
714                 /* buffer the message to handle re-xmits */
715                 dtls1_buffer_message(s, 0);
716                 }
717
718         /* SSL3_ST_CW_CLNT_HELLO_B */
719         return(dtls1_do_write(s,SSL3_RT_HANDSHAKE));
720 err:
721         return(-1);
722         }
723
724 static int dtls1_get_hello_verify(SSL *s)
725         {
726         int n, al, ok = 0;
727         unsigned char *data;
728         unsigned int cookie_len;
729
730         n=s->method->ssl_get_message(s,
731                 DTLS1_ST_CR_HELLO_VERIFY_REQUEST_A,
732                 DTLS1_ST_CR_HELLO_VERIFY_REQUEST_B,
733                 -1,
734                 s->max_cert_list,
735                 &ok);
736
737         if (!ok) return((int)n);
738
739         if (s->s3->tmp.message_type != DTLS1_MT_HELLO_VERIFY_REQUEST)
740                 {
741                 s->d1->send_cookie = 0;
742                 s->s3->tmp.reuse_message=1;
743                 return(1);
744                 }
745
746         data = (unsigned char *)s->init_msg;
747
748         if ((data[0] != (s->version>>8)) || (data[1] != (s->version&0xff)))
749                 {
750                 SSLerr(SSL_F_DTLS1_GET_HELLO_VERIFY,SSL_R_WRONG_SSL_VERSION);
751                 s->version=(s->version&0xff00)|data[1];
752                 al = SSL_AD_PROTOCOL_VERSION;
753                 goto f_err;
754                 }
755         data+=2;
756
757         cookie_len = *(data++);
758         if ( cookie_len > sizeof(s->d1->cookie))
759                 {
760                 al=SSL_AD_ILLEGAL_PARAMETER;
761                 goto f_err;
762                 }
763
764         memcpy(s->d1->cookie, data, cookie_len);
765         s->d1->cookie_len = cookie_len;
766
767         s->d1->send_cookie = 1;
768         return 1;
769
770 f_err:
771         ssl3_send_alert(s, SSL3_AL_FATAL, al);
772         return -1;
773         }
774
775 int dtls1_send_client_key_exchange(SSL *s)
776         {
777         unsigned char *p,*d;
778         int n;
779         unsigned long alg_k;
780 #ifndef OPENSSL_NO_RSA
781         unsigned char *q;
782         EVP_PKEY *pkey=NULL;
783 #endif
784 #ifndef OPENSSL_NO_KRB5
785         KSSL_ERR kssl_err;
786 #endif /* OPENSSL_NO_KRB5 */
787 #ifndef OPENSSL_NO_ECDH
788         EC_KEY *clnt_ecdh = NULL;
789         const EC_POINT *srvr_ecpoint = NULL;
790         EVP_PKEY *srvr_pub_pkey = NULL;
791         unsigned char *encodedPoint = NULL;
792         int encoded_pt_len = 0;
793         BN_CTX * bn_ctx = NULL;
794 #endif
795
796         if (s->state == SSL3_ST_CW_KEY_EXCH_A)
797                 {
798                 d=(unsigned char *)s->init_buf->data;
799                 p= &(d[DTLS1_HM_HEADER_LENGTH]);
800                 
801                 alg_k=s->s3->tmp.new_cipher->algorithm_mkey;
802
803                 /* Fool emacs indentation */
804                 if (0) {}
805 #ifndef OPENSSL_NO_RSA
806                 else if (alg_k & SSL_kRSA)
807                         {
808                         RSA *rsa;
809                         unsigned char tmp_buf[SSL_MAX_MASTER_KEY_LENGTH];
810
811                         if (s->session->sess_cert->peer_rsa_tmp != NULL)
812                                 rsa=s->session->sess_cert->peer_rsa_tmp;
813                         else
814                                 {
815                                 pkey=X509_get_pubkey(s->session->sess_cert->peer_pkeys[SSL_PKEY_RSA_ENC].x509);
816                                 if ((pkey == NULL) ||
817                                         (pkey->type != EVP_PKEY_RSA) ||
818                                         (pkey->pkey.rsa == NULL))
819                                         {
820                                         SSLerr(SSL_F_DTLS1_SEND_CLIENT_KEY_EXCHANGE,ERR_R_INTERNAL_ERROR);
821                                         goto err;
822                                         }
823                                 rsa=pkey->pkey.rsa;
824                                 EVP_PKEY_free(pkey);
825                                 }
826                                 
827                         tmp_buf[0]=s->client_version>>8;
828                         tmp_buf[1]=s->client_version&0xff;
829                         if (RAND_bytes(&(tmp_buf[2]),sizeof tmp_buf-2) <= 0)
830                                         goto err;
831
832                         s->session->master_key_length=sizeof tmp_buf;
833
834                         q=p;
835                         /* Fix buf for TLS and [incidentally] DTLS */
836                         if (s->version > SSL3_VERSION)
837                                 p+=2;
838                         n=RSA_public_encrypt(sizeof tmp_buf,
839                                 tmp_buf,p,rsa,RSA_PKCS1_PADDING);
840 #ifdef PKCS1_CHECK
841                         if (s->options & SSL_OP_PKCS1_CHECK_1) p[1]++;
842                         if (s->options & SSL_OP_PKCS1_CHECK_2) tmp_buf[0]=0x70;
843 #endif
844                         if (n <= 0)
845                                 {
846                                 SSLerr(SSL_F_DTLS1_SEND_CLIENT_KEY_EXCHANGE,SSL_R_BAD_RSA_ENCRYPT);
847                                 goto err;
848                                 }
849
850                         /* Fix buf for TLS and [incidentally] DTLS */
851                         if (s->version > SSL3_VERSION)
852                                 {
853                                 s2n(n,q);
854                                 n+=2;
855                                 }
856
857                         s->session->master_key_length=
858                                 s->method->ssl3_enc->generate_master_secret(s,
859                                         s->session->master_key,
860                                         tmp_buf,sizeof tmp_buf);
861                         OPENSSL_cleanse(tmp_buf,sizeof tmp_buf);
862                         }
863 #endif
864 #ifndef OPENSSL_NO_KRB5
865                 else if (alg_k & SSL_kKRB5)
866                         {
867                         krb5_error_code krb5rc;
868                         KSSL_CTX        *kssl_ctx = s->kssl_ctx;
869                         /*  krb5_data   krb5_ap_req;  */
870                         krb5_data       *enc_ticket;
871                         krb5_data       authenticator, *authp = NULL;
872                         EVP_CIPHER_CTX  ciph_ctx;
873                         const EVP_CIPHER *enc = NULL;
874                         unsigned char   iv[EVP_MAX_IV_LENGTH];
875                         unsigned char   tmp_buf[SSL_MAX_MASTER_KEY_LENGTH];
876                         unsigned char   epms[SSL_MAX_MASTER_KEY_LENGTH 
877                                                 + EVP_MAX_IV_LENGTH];
878                         int             padl, outl = sizeof(epms);
879
880                         EVP_CIPHER_CTX_init(&ciph_ctx);
881
882 #ifdef KSSL_DEBUG
883                         printf("ssl3_send_client_key_exchange(%lx & %lx)\n",
884                                 alg_k, SSL_kKRB5);
885 #endif  /* KSSL_DEBUG */
886
887                         authp = NULL;
888 #ifdef KRB5SENDAUTH
889                         if (KRB5SENDAUTH)  authp = &authenticator;
890 #endif  /* KRB5SENDAUTH */
891
892                         krb5rc = kssl_cget_tkt(kssl_ctx, &enc_ticket, authp,
893                                 &kssl_err);
894                         enc = kssl_map_enc(kssl_ctx->enctype);
895                         if (enc == NULL)
896                             goto err;
897 #ifdef KSSL_DEBUG
898                         {
899                         printf("kssl_cget_tkt rtn %d\n", krb5rc);
900                         if (krb5rc && kssl_err.text)
901                           printf("kssl_cget_tkt kssl_err=%s\n", kssl_err.text);
902                         }
903 #endif  /* KSSL_DEBUG */
904
905                         if (krb5rc)
906                                 {
907                                 ssl3_send_alert(s,SSL3_AL_FATAL,
908                                                 SSL_AD_HANDSHAKE_FAILURE);
909                                 SSLerr(SSL_F_DTLS1_SEND_CLIENT_KEY_EXCHANGE,
910                                                 kssl_err.reason);
911                                 goto err;
912                                 }
913
914                         /*  20010406 VRS - Earlier versions used KRB5 AP_REQ
915                         **  in place of RFC 2712 KerberosWrapper, as in:
916                         **
917                         **  Send ticket (copy to *p, set n = length)
918                         **  n = krb5_ap_req.length;
919                         **  memcpy(p, krb5_ap_req.data, krb5_ap_req.length);
920                         **  if (krb5_ap_req.data)  
921                         **    kssl_krb5_free_data_contents(NULL,&krb5_ap_req);
922                         **
923                         **  Now using real RFC 2712 KerberosWrapper
924                         **  (Thanks to Simon Wilkinson <sxw@sxw.org.uk>)
925                         **  Note: 2712 "opaque" types are here replaced
926                         **  with a 2-byte length followed by the value.
927                         **  Example:
928                         **  KerberosWrapper= xx xx asn1ticket 0 0 xx xx encpms
929                         **  Where "xx xx" = length bytes.  Shown here with
930                         **  optional authenticator omitted.
931                         */
932
933                         /*  KerberosWrapper.Ticket              */
934                         s2n(enc_ticket->length,p);
935                         memcpy(p, enc_ticket->data, enc_ticket->length);
936                         p+= enc_ticket->length;
937                         n = enc_ticket->length + 2;
938
939                         /*  KerberosWrapper.Authenticator       */
940                         if (authp  &&  authp->length)  
941                                 {
942                                 s2n(authp->length,p);
943                                 memcpy(p, authp->data, authp->length);
944                                 p+= authp->length;
945                                 n+= authp->length + 2;
946                                 
947                                 free(authp->data);
948                                 authp->data = NULL;
949                                 authp->length = 0;
950                                 }
951                         else
952                                 {
953                                 s2n(0,p);/*  null authenticator length  */
954                                 n+=2;
955                                 }
956  
957                         if (RAND_bytes(tmp_buf,sizeof tmp_buf) <= 0)
958                             goto err;
959
960                         /*  20010420 VRS.  Tried it this way; failed.
961                         **      EVP_EncryptInit_ex(&ciph_ctx,enc, NULL,NULL);
962                         **      EVP_CIPHER_CTX_set_key_length(&ciph_ctx,
963                         **                              kssl_ctx->length);
964                         **      EVP_EncryptInit_ex(&ciph_ctx,NULL, key,iv);
965                         */
966
967                         memset(iv, 0, sizeof iv);  /* per RFC 1510 */
968                         EVP_EncryptInit_ex(&ciph_ctx,enc, NULL,
969                                 kssl_ctx->key,iv);
970                         EVP_EncryptUpdate(&ciph_ctx,epms,&outl,tmp_buf,
971                                 sizeof tmp_buf);
972                         EVP_EncryptFinal_ex(&ciph_ctx,&(epms[outl]),&padl);
973                         outl += padl;
974                         if (outl > (int)sizeof epms)
975                                 {
976                                 SSLerr(SSL_F_DTLS1_SEND_CLIENT_KEY_EXCHANGE, ERR_R_INTERNAL_ERROR);
977                                 goto err;
978                                 }
979                         EVP_CIPHER_CTX_cleanup(&ciph_ctx);
980
981                         /*  KerberosWrapper.EncryptedPreMasterSecret    */
982                         s2n(outl,p);
983                         memcpy(p, epms, outl);
984                         p+=outl;
985                         n+=outl + 2;
986
987                         s->session->master_key_length=
988                                 s->method->ssl3_enc->generate_master_secret(s,
989                                         s->session->master_key,
990                                         tmp_buf, sizeof tmp_buf);
991
992                         OPENSSL_cleanse(tmp_buf, sizeof tmp_buf);
993                         OPENSSL_cleanse(epms, outl);
994                         }
995 #endif
996 #ifndef OPENSSL_NO_DH
997                 else if (alg_k & (SSL_kEDH|SSL_kDHr|SSL_kDHd))
998                         {
999                         DH *dh_srvr,*dh_clnt;
1000
1001                         if (s->session->sess_cert->peer_dh_tmp != NULL)
1002                                 dh_srvr=s->session->sess_cert->peer_dh_tmp;
1003                         else
1004                                 {
1005                                 /* we get them from the cert */
1006                                 ssl3_send_alert(s,SSL3_AL_FATAL,SSL_AD_HANDSHAKE_FAILURE);
1007                                 SSLerr(SSL_F_DTLS1_SEND_CLIENT_KEY_EXCHANGE,SSL_R_UNABLE_TO_FIND_DH_PARAMETERS);
1008                                 goto err;
1009                                 }
1010                         
1011                         /* generate a new random key */
1012                         if ((dh_clnt=DHparams_dup(dh_srvr)) == NULL)
1013                                 {
1014                                 SSLerr(SSL_F_DTLS1_SEND_CLIENT_KEY_EXCHANGE,ERR_R_DH_LIB);
1015                                 goto err;
1016                                 }
1017                         if (!DH_generate_key(dh_clnt))
1018                                 {
1019                                 SSLerr(SSL_F_DTLS1_SEND_CLIENT_KEY_EXCHANGE,ERR_R_DH_LIB);
1020                                 goto err;
1021                                 }
1022
1023                         /* use the 'p' output buffer for the DH key, but
1024                          * make sure to clear it out afterwards */
1025
1026                         n=DH_compute_key(p,dh_srvr->pub_key,dh_clnt);
1027
1028                         if (n <= 0)
1029                                 {
1030                                 SSLerr(SSL_F_DTLS1_SEND_CLIENT_KEY_EXCHANGE,ERR_R_DH_LIB);
1031                                 goto err;
1032                                 }
1033
1034                         /* generate master key from the result */
1035                         s->session->master_key_length=
1036                                 s->method->ssl3_enc->generate_master_secret(s,
1037                                         s->session->master_key,p,n);
1038                         /* clean up */
1039                         memset(p,0,n);
1040
1041                         /* send off the data */
1042                         n=BN_num_bytes(dh_clnt->pub_key);
1043                         s2n(n,p);
1044                         BN_bn2bin(dh_clnt->pub_key,p);
1045                         n+=2;
1046
1047                         DH_free(dh_clnt);
1048
1049                         /* perhaps clean things up a bit EAY EAY EAY EAY*/
1050                         }
1051 #endif
1052 #ifndef OPENSSL_NO_ECDH 
1053                 else if (alg_k & (SSL_kEECDH|SSL_kECDHr|SSL_kECDHe))
1054                         {
1055                         const EC_GROUP *srvr_group = NULL;
1056                         EC_KEY *tkey;
1057                         int ecdh_clnt_cert = 0;
1058                         int field_size = 0;
1059
1060                         /* Did we send out the client's
1061                          * ECDH share for use in premaster
1062                          * computation as part of client certificate?
1063                          * If so, set ecdh_clnt_cert to 1.
1064                          */
1065                         if ((alg_k & (SSL_kECDHr|SSL_kECDHe)) && (s->cert != NULL)) 
1066                                 {
1067                                 /* XXX: For now, we do not support client
1068                                  * authentication using ECDH certificates.
1069                                  * To add such support, one needs to add
1070                                  * code that checks for appropriate 
1071                                  * conditions and sets ecdh_clnt_cert to 1.
1072                                  * For example, the cert have an ECC
1073                                  * key on the same curve as the server's
1074                                  * and the key should be authorized for
1075                                  * key agreement.
1076                                  *
1077                                  * One also needs to add code in ssl3_connect
1078                                  * to skip sending the certificate verify
1079                                  * message.
1080                                  *
1081                                  * if ((s->cert->key->privatekey != NULL) &&
1082                                  *     (s->cert->key->privatekey->type ==
1083                                  *      EVP_PKEY_EC) && ...)
1084                                  * ecdh_clnt_cert = 1;
1085                                  */
1086                                 }
1087
1088                         if (s->session->sess_cert->peer_ecdh_tmp != NULL)
1089                                 {
1090                                 tkey = s->session->sess_cert->peer_ecdh_tmp;
1091                                 }
1092                         else
1093                                 {
1094                                 /* Get the Server Public Key from Cert */
1095                                 srvr_pub_pkey = X509_get_pubkey(s->session-> \
1096                                     sess_cert->peer_pkeys[SSL_PKEY_ECC].x509);
1097                                 if ((srvr_pub_pkey == NULL) ||
1098                                     (srvr_pub_pkey->type != EVP_PKEY_EC) ||
1099                                     (srvr_pub_pkey->pkey.ec == NULL))
1100                                         {
1101                                         SSLerr(SSL_F_DTLS1_SEND_CLIENT_KEY_EXCHANGE,
1102                                             ERR_R_INTERNAL_ERROR);
1103                                         goto err;
1104                                         }
1105
1106                                 tkey = srvr_pub_pkey->pkey.ec;
1107                                 }
1108
1109                         srvr_group   = EC_KEY_get0_group(tkey);
1110                         srvr_ecpoint = EC_KEY_get0_public_key(tkey);
1111
1112                         if ((srvr_group == NULL) || (srvr_ecpoint == NULL))
1113                                 {
1114                                 SSLerr(SSL_F_DTLS1_SEND_CLIENT_KEY_EXCHANGE,
1115                                     ERR_R_INTERNAL_ERROR);
1116                                 goto err;
1117                                 }
1118
1119                         if ((clnt_ecdh=EC_KEY_new()) == NULL) 
1120                                 {
1121                                 SSLerr(SSL_F_DTLS1_SEND_CLIENT_KEY_EXCHANGE,ERR_R_MALLOC_FAILURE);
1122                                 goto err;
1123                                 }
1124
1125                         if (!EC_KEY_set_group(clnt_ecdh, srvr_group))
1126                                 {
1127                                 SSLerr(SSL_F_DTLS1_SEND_CLIENT_KEY_EXCHANGE,ERR_R_EC_LIB);
1128                                 goto err;
1129                                 }
1130                         if (ecdh_clnt_cert) 
1131                                 { 
1132                                 /* Reuse key info from our certificate
1133                                  * We only need our private key to perform
1134                                  * the ECDH computation.
1135                                  */
1136                                 const BIGNUM *priv_key;
1137                                 tkey = s->cert->key->privatekey->pkey.ec;
1138                                 priv_key = EC_KEY_get0_private_key(tkey);
1139                                 if (priv_key == NULL)
1140                                         {
1141                                         SSLerr(SSL_F_DTLS1_SEND_CLIENT_KEY_EXCHANGE,ERR_R_MALLOC_FAILURE);
1142                                         goto err;
1143                                         }
1144                                 if (!EC_KEY_set_private_key(clnt_ecdh, priv_key))
1145                                         {
1146                                         SSLerr(SSL_F_DTLS1_SEND_CLIENT_KEY_EXCHANGE,ERR_R_EC_LIB);
1147                                         goto err;
1148                                         }
1149                                 }
1150                         else 
1151                                 {
1152                                 /* Generate a new ECDH key pair */
1153                                 if (!(EC_KEY_generate_key(clnt_ecdh)))
1154                                         {
1155                                         SSLerr(SSL_F_DTLS1_SEND_CLIENT_KEY_EXCHANGE, ERR_R_ECDH_LIB);
1156                                         goto err;
1157                                         }
1158                                 }
1159
1160                         /* use the 'p' output buffer for the ECDH key, but
1161                          * make sure to clear it out afterwards
1162                          */
1163
1164                         field_size = EC_GROUP_get_degree(srvr_group);
1165                         if (field_size <= 0)
1166                                 {
1167                                 SSLerr(SSL_F_DTLS1_SEND_CLIENT_KEY_EXCHANGE, 
1168                                        ERR_R_ECDH_LIB);
1169                                 goto err;
1170                                 }
1171                         n=ECDH_compute_key(p, (field_size+7)/8, srvr_ecpoint, clnt_ecdh, NULL);
1172                         if (n <= 0)
1173                                 {
1174                                 SSLerr(SSL_F_DTLS1_SEND_CLIENT_KEY_EXCHANGE, 
1175                                        ERR_R_ECDH_LIB);
1176                                 goto err;
1177                                 }
1178
1179                         /* generate master key from the result */
1180                         s->session->master_key_length = s->method->ssl3_enc \
1181                             -> generate_master_secret(s, 
1182                                 s->session->master_key,
1183                                 p, n);
1184
1185                         memset(p, 0, n); /* clean up */
1186
1187                         if (ecdh_clnt_cert) 
1188                                 {
1189                                 /* Send empty client key exch message */
1190                                 n = 0;
1191                                 }
1192                         else 
1193                                 {
1194                                 /* First check the size of encoding and
1195                                  * allocate memory accordingly.
1196                                  */
1197                                 encoded_pt_len = 
1198                                     EC_POINT_point2oct(srvr_group, 
1199                                         EC_KEY_get0_public_key(clnt_ecdh), 
1200                                         POINT_CONVERSION_UNCOMPRESSED, 
1201                                         NULL, 0, NULL);
1202
1203                                 encodedPoint = (unsigned char *) 
1204                                     OPENSSL_malloc(encoded_pt_len * 
1205                                         sizeof(unsigned char)); 
1206                                 bn_ctx = BN_CTX_new();
1207                                 if ((encodedPoint == NULL) || 
1208                                     (bn_ctx == NULL)) 
1209                                         {
1210                                         SSLerr(SSL_F_DTLS1_SEND_CLIENT_KEY_EXCHANGE,ERR_R_MALLOC_FAILURE);
1211                                         goto err;
1212                                         }
1213
1214                                 /* Encode the public key */
1215                                 n = EC_POINT_point2oct(srvr_group, 
1216                                     EC_KEY_get0_public_key(clnt_ecdh), 
1217                                     POINT_CONVERSION_UNCOMPRESSED, 
1218                                     encodedPoint, encoded_pt_len, bn_ctx);
1219
1220                                 *p = n; /* length of encoded point */
1221                                 /* Encoded point will be copied here */
1222                                 p += 1; 
1223                                 /* copy the point */
1224                                 memcpy((unsigned char *)p, encodedPoint, n);
1225                                 /* increment n to account for length field */
1226                                 n += 1; 
1227                                 }
1228
1229                         /* Free allocated memory */
1230                         BN_CTX_free(bn_ctx);
1231                         if (encodedPoint != NULL) OPENSSL_free(encodedPoint);
1232                         if (clnt_ecdh != NULL) 
1233                                  EC_KEY_free(clnt_ecdh);
1234                         EVP_PKEY_free(srvr_pub_pkey);
1235                         }
1236 #endif /* !OPENSSL_NO_ECDH */
1237
1238 #ifndef OPENSSL_NO_PSK
1239                 else if (alg_k & SSL_kPSK)
1240                         {
1241                         char identity[PSK_MAX_IDENTITY_LEN];
1242                         unsigned char *t = NULL;
1243                         unsigned char psk_or_pre_ms[PSK_MAX_PSK_LEN*2+4];
1244                         unsigned int pre_ms_len = 0, psk_len = 0;
1245                         int psk_err = 1;
1246
1247                         n = 0;
1248                         if (s->psk_client_callback == NULL)
1249                                 {
1250                                 SSLerr(SSL_F_DTLS1_SEND_CLIENT_KEY_EXCHANGE,
1251                                         SSL_R_PSK_NO_CLIENT_CB);
1252                                 goto err;
1253                                 }
1254
1255                         psk_len = s->psk_client_callback(s, s->ctx->psk_identity_hint,
1256                                 identity, PSK_MAX_IDENTITY_LEN,
1257                                 psk_or_pre_ms, sizeof(psk_or_pre_ms));
1258                         if (psk_len > PSK_MAX_PSK_LEN)
1259                                 {
1260                                 SSLerr(SSL_F_DTLS1_SEND_CLIENT_KEY_EXCHANGE,
1261                                         ERR_R_INTERNAL_ERROR);
1262                                 goto psk_err;
1263                                 }
1264                         else if (psk_len == 0)
1265                                 {
1266                                 SSLerr(SSL_F_DTLS1_SEND_CLIENT_KEY_EXCHANGE,
1267                                         SSL_R_PSK_IDENTITY_NOT_FOUND);
1268                                 goto psk_err;
1269                                 }
1270
1271                         /* create PSK pre_master_secret */
1272                         pre_ms_len = 2+psk_len+2+psk_len;
1273                         t = psk_or_pre_ms;
1274                         memmove(psk_or_pre_ms+psk_len+4, psk_or_pre_ms, psk_len);
1275                         s2n(psk_len, t);
1276                         memset(t, 0, psk_len);
1277                         t+=psk_len;
1278                         s2n(psk_len, t);
1279
1280                         if (s->session->psk_identity_hint != NULL)
1281                                 OPENSSL_free(s->session->psk_identity_hint);
1282                         s->session->psk_identity_hint = BUF_strdup(s->ctx->psk_identity_hint);
1283                         if (s->ctx->psk_identity_hint != NULL &&
1284                                 s->session->psk_identity_hint == NULL)
1285                                 {
1286                                 SSLerr(SSL_F_DTLS1_SEND_CLIENT_KEY_EXCHANGE,
1287                                         ERR_R_MALLOC_FAILURE);
1288                                 goto psk_err;
1289                                 }
1290
1291                         if (s->session->psk_identity != NULL)
1292                                 OPENSSL_free(s->session->psk_identity);
1293                         s->session->psk_identity = BUF_strdup(identity);
1294                         if (s->session->psk_identity == NULL)
1295                                 {
1296                                 SSLerr(SSL_F_DTLS1_SEND_CLIENT_KEY_EXCHANGE,
1297                                         ERR_R_MALLOC_FAILURE);
1298                                 goto psk_err;
1299                                 }
1300
1301                         s->session->master_key_length =
1302                                 s->method->ssl3_enc->generate_master_secret(s,
1303                                         s->session->master_key,
1304                                         psk_or_pre_ms, pre_ms_len); 
1305                         n = strlen(identity);
1306                         s2n(n, p);
1307                         memcpy(p, identity, n);
1308                         n+=2;
1309                         psk_err = 0;
1310                 psk_err:
1311                         OPENSSL_cleanse(identity, PSK_MAX_IDENTITY_LEN);
1312                         OPENSSL_cleanse(psk_or_pre_ms, sizeof(psk_or_pre_ms));
1313                         if (psk_err != 0)
1314                                 {
1315                                 ssl3_send_alert(s, SSL3_AL_FATAL, SSL_AD_HANDSHAKE_FAILURE);
1316                                 goto err;
1317                                 }
1318                         }
1319 #endif
1320                 else
1321                         {
1322                         ssl3_send_alert(s,SSL3_AL_FATAL,SSL_AD_HANDSHAKE_FAILURE);
1323                         SSLerr(SSL_F_DTLS1_SEND_CLIENT_KEY_EXCHANGE,ERR_R_INTERNAL_ERROR);
1324                         goto err;
1325                         }
1326                 
1327                 d = dtls1_set_message_header(s, d,
1328                 SSL3_MT_CLIENT_KEY_EXCHANGE, n, 0, n);
1329                 /*
1330                  *(d++)=SSL3_MT_CLIENT_KEY_EXCHANGE;
1331                  l2n3(n,d);
1332                  l2n(s->d1->handshake_write_seq,d);
1333                  s->d1->handshake_write_seq++;
1334                 */
1335                 
1336                 s->state=SSL3_ST_CW_KEY_EXCH_B;
1337                 /* number of bytes to write */
1338                 s->init_num=n+DTLS1_HM_HEADER_LENGTH;
1339                 s->init_off=0;
1340
1341                 /* buffer the message to handle re-xmits */
1342                 dtls1_buffer_message(s, 0);
1343                 }
1344         
1345         /* SSL3_ST_CW_KEY_EXCH_B */
1346         return(dtls1_do_write(s,SSL3_RT_HANDSHAKE));
1347 err:
1348 #ifndef OPENSSL_NO_ECDH
1349         BN_CTX_free(bn_ctx);
1350         if (encodedPoint != NULL) OPENSSL_free(encodedPoint);
1351         if (clnt_ecdh != NULL) 
1352                 EC_KEY_free(clnt_ecdh);
1353         EVP_PKEY_free(srvr_pub_pkey);
1354 #endif
1355         return(-1);
1356         }
1357
1358 int dtls1_send_client_verify(SSL *s)
1359         {
1360         unsigned char *p,*d;
1361         unsigned char data[MD5_DIGEST_LENGTH+SHA_DIGEST_LENGTH];
1362         EVP_PKEY *pkey;
1363 #ifndef OPENSSL_NO_RSA
1364         unsigned u=0;
1365 #endif
1366         unsigned long n;
1367 #if !defined(OPENSSL_NO_DSA) || !defined(OPENSSL_NO_ECDSA)
1368         int j;
1369 #endif
1370
1371         if (s->state == SSL3_ST_CW_CERT_VRFY_A)
1372                 {
1373                 d=(unsigned char *)s->init_buf->data;
1374                 p= &(d[DTLS1_HM_HEADER_LENGTH]);
1375                 pkey=s->cert->key->privatekey;
1376
1377                 s->method->ssl3_enc->cert_verify_mac(s,
1378                 NID_sha1,
1379                         &(data[MD5_DIGEST_LENGTH]));
1380
1381 #ifndef OPENSSL_NO_RSA
1382                 if (pkey->type == EVP_PKEY_RSA)
1383                         {
1384                         s->method->ssl3_enc->cert_verify_mac(s,
1385                                 NID_md5,
1386                                 &(data[0]));
1387                         if (RSA_sign(NID_md5_sha1, data,
1388                                          MD5_DIGEST_LENGTH+SHA_DIGEST_LENGTH,
1389                                         &(p[2]), &u, pkey->pkey.rsa) <= 0 )
1390                                 {
1391                                 SSLerr(SSL_F_DTLS1_SEND_CLIENT_VERIFY,ERR_R_RSA_LIB);
1392                                 goto err;
1393                                 }
1394                         s2n(u,p);
1395                         n=u+2;
1396                         }
1397                 else
1398 #endif
1399 #ifndef OPENSSL_NO_DSA
1400                         if (pkey->type == EVP_PKEY_DSA)
1401                         {
1402                         if (!DSA_sign(pkey->save_type,
1403                                 &(data[MD5_DIGEST_LENGTH]),
1404                                 SHA_DIGEST_LENGTH,&(p[2]),
1405                                 (unsigned int *)&j,pkey->pkey.dsa))
1406                                 {
1407                                 SSLerr(SSL_F_DTLS1_SEND_CLIENT_VERIFY,ERR_R_DSA_LIB);
1408                                 goto err;
1409                                 }
1410                         s2n(j,p);
1411                         n=j+2;
1412                         }
1413                 else
1414 #endif
1415 #ifndef OPENSSL_NO_ECDSA
1416                         if (pkey->type == EVP_PKEY_EC)
1417                         {
1418                         if (!ECDSA_sign(pkey->save_type,
1419                                 &(data[MD5_DIGEST_LENGTH]),
1420                                 SHA_DIGEST_LENGTH,&(p[2]),
1421                                 (unsigned int *)&j,pkey->pkey.ec))
1422                                 {
1423                                 SSLerr(SSL_F_DTLS1_SEND_CLIENT_VERIFY,
1424                                     ERR_R_ECDSA_LIB);
1425                                 goto err;
1426                                 }
1427                         s2n(j,p);
1428                         n=j+2;
1429                         }
1430                 else
1431 #endif
1432                         {
1433                         SSLerr(SSL_F_DTLS1_SEND_CLIENT_VERIFY,ERR_R_INTERNAL_ERROR);
1434                         goto err;
1435                         }
1436
1437                 d = dtls1_set_message_header(s, d,
1438                         SSL3_MT_CERTIFICATE_VERIFY, n, 0, n) ;
1439
1440                 s->init_num=(int)n+DTLS1_HM_HEADER_LENGTH;
1441                 s->init_off=0;
1442
1443                 /* buffer the message to handle re-xmits */
1444                 dtls1_buffer_message(s, 0);
1445
1446                 s->state = SSL3_ST_CW_CERT_VRFY_B;
1447                 }
1448
1449         /* s->state = SSL3_ST_CW_CERT_VRFY_B */
1450         return(dtls1_do_write(s,SSL3_RT_HANDSHAKE));
1451 err:
1452         return(-1);
1453         }
1454
1455 int dtls1_send_client_certificate(SSL *s)
1456         {
1457         X509 *x509=NULL;
1458         EVP_PKEY *pkey=NULL;
1459         int i;
1460         unsigned long l;
1461
1462         if (s->state == SSL3_ST_CW_CERT_A)
1463                 {
1464                 if ((s->cert == NULL) ||
1465                         (s->cert->key->x509 == NULL) ||
1466                         (s->cert->key->privatekey == NULL))
1467                         s->state=SSL3_ST_CW_CERT_B;
1468                 else
1469                         s->state=SSL3_ST_CW_CERT_C;
1470                 }
1471
1472         /* We need to get a client cert */
1473         if (s->state == SSL3_ST_CW_CERT_B)
1474                 {
1475                 /* If we get an error, we need to
1476                  * ssl->rwstate=SSL_X509_LOOKUP; return(-1);
1477                  * We then get retied later */
1478                 i=0;
1479                 i = ssl_do_client_cert_cb(s, &x509, &pkey);
1480                 if (i < 0)
1481                         {
1482                         s->rwstate=SSL_X509_LOOKUP;
1483                         return(-1);
1484                         }
1485                 s->rwstate=SSL_NOTHING;
1486                 if ((i == 1) && (pkey != NULL) && (x509 != NULL))
1487                         {
1488                         s->state=SSL3_ST_CW_CERT_B;
1489                         if (    !SSL_use_certificate(s,x509) ||
1490                                 !SSL_use_PrivateKey(s,pkey))
1491                                 i=0;
1492                         }
1493                 else if (i == 1)
1494                         {
1495                         i=0;
1496                         SSLerr(SSL_F_DTLS1_SEND_CLIENT_CERTIFICATE,SSL_R_BAD_DATA_RETURNED_BY_CALLBACK);
1497                         }
1498
1499                 if (x509 != NULL) X509_free(x509);
1500                 if (pkey != NULL) EVP_PKEY_free(pkey);
1501                 if (i == 0)
1502                         {
1503                         if (s->version == SSL3_VERSION)
1504                                 {
1505                                 s->s3->tmp.cert_req=0;
1506                                 ssl3_send_alert(s,SSL3_AL_WARNING,SSL_AD_NO_CERTIFICATE);
1507                                 return(1);
1508                                 }
1509                         else
1510                                 {
1511                                 s->s3->tmp.cert_req=2;
1512                                 }
1513                         }
1514
1515                 /* Ok, we have a cert */
1516                 s->state=SSL3_ST_CW_CERT_C;
1517                 }
1518
1519         if (s->state == SSL3_ST_CW_CERT_C)
1520                 {
1521                 s->state=SSL3_ST_CW_CERT_D;
1522                 l=dtls1_output_cert_chain(s,
1523                         (s->s3->tmp.cert_req == 2)?NULL:s->cert->key->x509);
1524                 s->init_num=(int)l;
1525                 s->init_off=0;
1526
1527                 /* set header called by dtls1_output_cert_chain() */
1528
1529                 /* buffer the message to handle re-xmits */
1530                 dtls1_buffer_message(s, 0);
1531                 }
1532         /* SSL3_ST_CW_CERT_D */
1533         return(dtls1_do_write(s,SSL3_RT_HANDSHAKE));
1534         }
1535
1536