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