Upstream version 10.39.225.0
[platform/framework/web/crosswalk.git] / src / third_party / boringssl / src / ssl / d1_lib.c
1 /*
2  * DTLS implementation written by Nagendra Modadugu
3  * (nagendra@cs.stanford.edu) for the OpenSSL project 2005.
4  */
5 /* ====================================================================
6  * Copyright (c) 1999-2005 The OpenSSL Project.  All rights reserved.
7  *
8  * Redistribution and use in source and binary forms, with or without
9  * modification, are permitted provided that the following conditions
10  * are met:
11  *
12  * 1. Redistributions of source code must retain the above copyright
13  *    notice, this list of conditions and the following disclaimer.
14  *
15  * 2. Redistributions in binary form must reproduce the above copyright
16  *    notice, this list of conditions and the following disclaimer in
17  *    the documentation and/or other materials provided with the
18  *    distribution.
19  *
20  * 3. All advertising materials mentioning features or use of this
21  *    software must display the following acknowledgment:
22  *    "This product includes software developed by the OpenSSL Project
23  *    for use in the OpenSSL Toolkit. (http://www.OpenSSL.org/)"
24  *
25  * 4. The names "OpenSSL Toolkit" and "OpenSSL Project" must not be used to
26  *    endorse or promote products derived from this software without
27  *    prior written permission. For written permission, please contact
28  *    openssl-core@OpenSSL.org.
29  *
30  * 5. Products derived from this software may not be called "OpenSSL"
31  *    nor may "OpenSSL" appear in their names without prior written
32  *    permission of the OpenSSL Project.
33  *
34  * 6. Redistributions of any form whatsoever must retain the following
35  *    acknowledgment:
36  *    "This product includes software developed by the OpenSSL Project
37  *    for use in the OpenSSL Toolkit (http://www.OpenSSL.org/)"
38  *
39  * THIS SOFTWARE IS PROVIDED BY THE OpenSSL PROJECT ``AS IS'' AND ANY
40  * EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
41  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
42  * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE OpenSSL PROJECT OR
43  * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
44  * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
45  * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
46  * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
47  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
48  * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
49  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
50  * OF THE POSSIBILITY OF SUCH DAMAGE.
51  * ====================================================================
52  *
53  * This product includes cryptographic software written by Eric Young
54  * (eay@cryptsoft.com).  This product includes software written by Tim
55  * Hudson (tjh@cryptsoft.com). */
56
57 #include <openssl/base.h>
58
59 #include <stdio.h>
60
61 #if defined(OPENSSL_WINDOWS)
62 #include <sys/timeb.h>
63 #else
64 #include <sys/socket.h>
65 #include <sys/time.h>
66 #endif
67
68 #include <openssl/err.h>
69 #include <openssl/mem.h>
70 #include <openssl/obj.h>
71
72 #include "ssl_locl.h"
73
74 static void get_current_time(OPENSSL_timeval *t);
75 static OPENSSL_timeval* dtls1_get_timeout(SSL *s, OPENSSL_timeval* timeleft);
76 static void dtls1_set_handshake_header(SSL *s, int type, unsigned long len);
77 static int dtls1_handshake_write(SSL *s);
78 int dtls1_listen(SSL *s, struct sockaddr *client);
79
80 SSL3_ENC_METHOD DTLSv1_enc_data={
81         tls1_enc,
82         tls1_mac,
83         tls1_setup_key_block,
84         tls1_generate_master_secret,
85         tls1_change_cipher_state,
86         tls1_final_finish_mac,
87         TLS1_FINISH_MAC_LENGTH,
88         tls1_cert_verify_mac,
89         TLS_MD_CLIENT_FINISH_CONST,TLS_MD_CLIENT_FINISH_CONST_SIZE,
90         TLS_MD_SERVER_FINISH_CONST,TLS_MD_SERVER_FINISH_CONST_SIZE,
91         tls1_alert_code,
92         tls1_export_keying_material,
93         SSL_ENC_FLAG_DTLS|SSL_ENC_FLAG_EXPLICIT_IV,
94         DTLS1_HM_HEADER_LENGTH,
95         dtls1_set_handshake_header,
96         dtls1_handshake_write   
97         };
98
99 SSL3_ENC_METHOD DTLSv1_2_enc_data={
100         tls1_enc,
101         tls1_mac,
102         tls1_setup_key_block,
103         tls1_generate_master_secret,
104         tls1_change_cipher_state,
105         tls1_final_finish_mac,
106         TLS1_FINISH_MAC_LENGTH,
107         tls1_cert_verify_mac,
108         TLS_MD_CLIENT_FINISH_CONST,TLS_MD_CLIENT_FINISH_CONST_SIZE,
109         TLS_MD_SERVER_FINISH_CONST,TLS_MD_SERVER_FINISH_CONST_SIZE,
110         tls1_alert_code,
111         tls1_export_keying_material,
112         SSL_ENC_FLAG_DTLS|SSL_ENC_FLAG_EXPLICIT_IV|SSL_ENC_FLAG_SIGALGS
113                 |SSL_ENC_FLAG_SHA256_PRF|SSL_ENC_FLAG_TLS1_2_CIPHERS,
114         DTLS1_HM_HEADER_LENGTH,
115         dtls1_set_handshake_header,
116         dtls1_handshake_write   
117         };
118
119 int dtls1_new(SSL *s)
120         {
121         DTLS1_STATE *d1;
122
123         if (!ssl3_new(s)) return(0);
124         if ((d1=OPENSSL_malloc(sizeof *d1)) == NULL)
125                 {
126                 ssl3_free(s);
127                 return (0);
128                 }
129         memset(d1,0, sizeof *d1);
130
131         /* d1->handshake_epoch=0; */
132
133         d1->unprocessed_rcds.q=pqueue_new();
134         d1->processed_rcds.q=pqueue_new();
135         d1->buffered_messages = pqueue_new();
136         d1->sent_messages=pqueue_new();
137         d1->buffered_app_data.q=pqueue_new();
138
139         if ( s->server)
140                 {
141                 d1->cookie_len = sizeof(s->d1->cookie);
142                 }
143
144         if( ! d1->unprocessed_rcds.q || ! d1->processed_rcds.q 
145         || ! d1->buffered_messages || ! d1->sent_messages || ! d1->buffered_app_data.q)
146                 {
147         if ( d1->unprocessed_rcds.q) pqueue_free(d1->unprocessed_rcds.q);
148         if ( d1->processed_rcds.q) pqueue_free(d1->processed_rcds.q);
149         if ( d1->buffered_messages) pqueue_free(d1->buffered_messages);
150                 if ( d1->sent_messages) pqueue_free(d1->sent_messages);
151                 if ( d1->buffered_app_data.q) pqueue_free(d1->buffered_app_data.q);
152                 OPENSSL_free(d1);
153                 ssl3_free(s);
154                 return (0);
155                 }
156
157         s->d1=d1;
158         s->method->ssl_clear(s);
159         return(1);
160         }
161
162 static void dtls1_clear_queues(SSL *s)
163         {
164     pitem *item = NULL;
165     hm_fragment *frag = NULL;
166         DTLS1_RECORD_DATA *rdata;
167
168     while( (item = pqueue_pop(s->d1->unprocessed_rcds.q)) != NULL)
169         {
170                 rdata = (DTLS1_RECORD_DATA *) item->data;
171                 if (rdata->rbuf.buf)
172                         {
173                         OPENSSL_free(rdata->rbuf.buf);
174                         }
175         OPENSSL_free(item->data);
176         pitem_free(item);
177         }
178
179     while( (item = pqueue_pop(s->d1->processed_rcds.q)) != NULL)
180         {
181                 rdata = (DTLS1_RECORD_DATA *) item->data;
182                 if (rdata->rbuf.buf)
183                         {
184                         OPENSSL_free(rdata->rbuf.buf);
185                         }
186         OPENSSL_free(item->data);
187         pitem_free(item);
188         }
189
190     while( (item = pqueue_pop(s->d1->buffered_messages)) != NULL)
191         {
192         frag = (hm_fragment *)item->data;
193         OPENSSL_free(frag->fragment);
194         OPENSSL_free(frag);
195         pitem_free(item);
196         }
197
198     while ( (item = pqueue_pop(s->d1->sent_messages)) != NULL)
199         {
200         frag = (hm_fragment *)item->data;
201         OPENSSL_free(frag->fragment);
202         OPENSSL_free(frag);
203         pitem_free(item);
204         }
205
206         while ( (item = pqueue_pop(s->d1->buffered_app_data.q)) != NULL)
207                 {
208                 rdata = (DTLS1_RECORD_DATA *) item->data;
209                 if (rdata->rbuf.buf)
210                         {
211                         OPENSSL_free(rdata->rbuf.buf);
212                         }
213                 OPENSSL_free(item->data);
214                 pitem_free(item);
215                 }
216         }
217
218 void dtls1_free(SSL *s)
219         {
220         ssl3_free(s);
221
222         dtls1_clear_queues(s);
223
224     pqueue_free(s->d1->unprocessed_rcds.q);
225     pqueue_free(s->d1->processed_rcds.q);
226     pqueue_free(s->d1->buffered_messages);
227         pqueue_free(s->d1->sent_messages);
228         pqueue_free(s->d1->buffered_app_data.q);
229
230         OPENSSL_free(s->d1);
231         s->d1 = NULL;
232         }
233
234 void dtls1_clear(SSL *s)
235         {
236     pqueue unprocessed_rcds;
237     pqueue processed_rcds;
238     pqueue buffered_messages;
239         pqueue sent_messages;
240         pqueue buffered_app_data;
241         unsigned int mtu;
242
243         if (s->d1)
244                 {
245                 unprocessed_rcds = s->d1->unprocessed_rcds.q;
246                 processed_rcds = s->d1->processed_rcds.q;
247                 buffered_messages = s->d1->buffered_messages;
248                 sent_messages = s->d1->sent_messages;
249                 buffered_app_data = s->d1->buffered_app_data.q;
250                 mtu = s->d1->mtu;
251
252                 dtls1_clear_queues(s);
253
254                 memset(s->d1, 0, sizeof(*(s->d1)));
255
256                 if (s->server)
257                         {
258                         s->d1->cookie_len = sizeof(s->d1->cookie);
259                         }
260
261                 if (SSL_get_options(s) & SSL_OP_NO_QUERY_MTU)
262                         {
263                         s->d1->mtu = mtu;
264                         }
265
266                 s->d1->unprocessed_rcds.q = unprocessed_rcds;
267                 s->d1->processed_rcds.q = processed_rcds;
268                 s->d1->buffered_messages = buffered_messages;
269                 s->d1->sent_messages = sent_messages;
270                 s->d1->buffered_app_data.q = buffered_app_data;
271                 }
272
273         ssl3_clear(s);
274         if (s->method->version == DTLS_ANY_VERSION)
275                 s->version=DTLS1_2_VERSION;
276         else
277                 s->version=s->method->version;
278         }
279
280 long dtls1_ctrl(SSL *s, int cmd, long larg, void *parg)
281         {
282         int ret=0;
283
284         switch (cmd)
285                 {
286         case DTLS_CTRL_GET_TIMEOUT:
287                 if (dtls1_get_timeout(s, (OPENSSL_timeval*) parg) != NULL)
288                         {
289                         ret = 1;
290                         }
291                 break;
292         case DTLS_CTRL_HANDLE_TIMEOUT:
293                 ret = dtls1_handle_timeout(s);
294                 break;
295         case DTLS_CTRL_LISTEN:
296                 ret = dtls1_listen(s, parg);
297                 break;
298
299         default:
300                 ret = ssl3_ctrl(s, cmd, larg, parg);
301                 break;
302                 }
303         return(ret);
304         }
305
306 /*
307  * As it's impossible to use stream ciphers in "datagram" mode, this
308  * simple filter is designed to disengage them in DTLS. Unfortunately
309  * there is no universal way to identify stream SSL_CIPHER, so we have
310  * to explicitly list their SSL_* codes. Currently RC4 is the only one
311  * available, but if new ones emerge, they will have to be added...
312  */
313 const SSL_CIPHER *dtls1_get_cipher(unsigned int u)
314         {
315         const SSL_CIPHER *ciph = ssl3_get_cipher(u);
316
317         if (ciph != NULL)
318                 {
319                 if (ciph->algorithm_enc == SSL_RC4)
320                         return NULL;
321                 }
322
323         return ciph;
324         }
325
326 void dtls1_start_timer(SSL *s)
327         {
328         /* If timer is not set, initialize duration with 1 second */
329         if (s->d1->next_timeout.tv_sec == 0 && s->d1->next_timeout.tv_usec == 0)
330                 {
331                 s->d1->timeout_duration = 1;
332                 }
333         
334         /* Set timeout to current time */
335         get_current_time(&s->d1->next_timeout);
336
337         /* Add duration to current time */
338         s->d1->next_timeout.tv_sec += s->d1->timeout_duration;
339         BIO_ctrl(SSL_get_rbio(s), BIO_CTRL_DGRAM_SET_NEXT_TIMEOUT, 0, &s->d1->next_timeout);
340         }
341
342 static OPENSSL_timeval* dtls1_get_timeout(SSL *s, OPENSSL_timeval* timeleft)
343         {
344         OPENSSL_timeval timenow;
345
346         /* If no timeout is set, just return NULL */
347         if (s->d1->next_timeout.tv_sec == 0 && s->d1->next_timeout.tv_usec == 0)
348                 {
349                 return NULL;
350                 }
351
352         /* Get current time */
353         get_current_time(&timenow);
354
355         /* If timer already expired, set remaining time to 0 */
356         if (s->d1->next_timeout.tv_sec < timenow.tv_sec ||
357                 (s->d1->next_timeout.tv_sec == timenow.tv_sec &&
358                  s->d1->next_timeout.tv_usec <= timenow.tv_usec))
359                 {
360                 memset(timeleft, 0, sizeof(OPENSSL_timeval));
361                 return timeleft;
362                 }
363
364         /* Calculate time left until timer expires */
365         memcpy(timeleft, &s->d1->next_timeout, sizeof(OPENSSL_timeval));
366         timeleft->tv_sec -= timenow.tv_sec;
367         timeleft->tv_usec -= timenow.tv_usec;
368         if (timeleft->tv_usec < 0)
369                 {
370                 timeleft->tv_sec--;
371                 timeleft->tv_usec += 1000000;
372                 }
373
374         /* If remaining time is less than 15 ms, set it to 0
375          * to prevent issues because of small devergences with
376          * socket timeouts.
377          */
378         if (timeleft->tv_sec == 0 && timeleft->tv_usec < 15000)
379                 {
380                 memset(timeleft, 0, sizeof(OPENSSL_timeval));
381                 }
382         
383
384         return timeleft;
385         }
386
387 int dtls1_is_timer_expired(SSL *s)
388         {
389         OPENSSL_timeval timeleft;
390
391         /* Get time left until timeout, return false if no timer running */
392         if (dtls1_get_timeout(s, &timeleft) == NULL)
393                 {
394                 return 0;
395                 }
396
397         /* Return false if timer is not expired yet */
398         if (timeleft.tv_sec > 0 || timeleft.tv_usec > 0)
399                 {
400                 return 0;
401                 }
402
403         /* Timer expired, so return true */     
404         return 1;
405         }
406
407 void dtls1_double_timeout(SSL *s)
408         {
409         s->d1->timeout_duration *= 2;
410         if (s->d1->timeout_duration > 60)
411                 s->d1->timeout_duration = 60;
412         dtls1_start_timer(s);
413         }
414
415 void dtls1_stop_timer(SSL *s)
416         {
417         /* Reset everything */
418         memset(&(s->d1->timeout), 0, sizeof(struct dtls1_timeout_st));
419         memset(&s->d1->next_timeout, 0, sizeof(OPENSSL_timeval));
420         s->d1->timeout_duration = 1;
421         BIO_ctrl(SSL_get_rbio(s), BIO_CTRL_DGRAM_SET_NEXT_TIMEOUT, 0, &s->d1->next_timeout);
422         /* Clear retransmission buffer */
423         dtls1_clear_record_buffer(s);
424         }
425
426 int dtls1_check_timeout_num(SSL *s)
427         {
428         s->d1->timeout.num_alerts++;
429
430         /* Reduce MTU after 2 unsuccessful retransmissions */
431         if (s->d1->timeout.num_alerts > 2)
432                 {
433                 s->d1->mtu = BIO_ctrl(SSL_get_wbio(s), BIO_CTRL_DGRAM_GET_FALLBACK_MTU, 0, NULL);               
434                 }
435
436         if (s->d1->timeout.num_alerts > DTLS1_TMO_ALERT_COUNT)
437                 {
438                 /* fail the connection, enough alerts have been sent */
439                 OPENSSL_PUT_ERROR(SSL, dtls1_check_timeout_num, SSL_R_READ_TIMEOUT_EXPIRED);
440                 return -1;
441                 }
442
443         return 0;
444         }
445
446 int dtls1_handle_timeout(SSL *s)
447         {
448         /* if no timer is expired, don't do anything */
449         if (!dtls1_is_timer_expired(s))
450                 {
451                 return 0;
452                 }
453
454         dtls1_double_timeout(s);
455
456         if (dtls1_check_timeout_num(s) < 0)
457                 return -1;
458
459         s->d1->timeout.read_timeouts++;
460         if (s->d1->timeout.read_timeouts > DTLS1_TMO_READ_COUNT)
461                 {
462                 s->d1->timeout.read_timeouts = 1;
463                 }
464
465         dtls1_start_timer(s);
466         return dtls1_retransmit_buffered_messages(s);
467         }
468
469 static void get_current_time(OPENSSL_timeval *t)
470 {
471 #if defined(OPENSSL_WINDOWS)
472         struct _timeb time;
473         _ftime(&time);
474         t->tv_sec = time.time;
475         t->tv_usec = time.millitm * 1000;
476 #else
477         gettimeofday(t, NULL);
478 #endif
479 }
480
481 int dtls1_listen(SSL *s, struct sockaddr *client)
482         {
483         int ret;
484
485         SSL_set_options(s, SSL_OP_COOKIE_EXCHANGE);
486         s->d1->listen = 1;
487
488         ret = SSL_accept(s);
489         if (ret <= 0) return ret;
490         
491         BIO_ctrl(SSL_get_rbio(s), BIO_CTRL_DGRAM_GET_PEER, 0, &client);
492         return 1;
493         }
494
495 static void dtls1_set_handshake_header(SSL *s, int htype, unsigned long len)
496         {
497         unsigned char *p = (unsigned char *)s->init_buf->data;
498         dtls1_set_message_header(s, p, htype, len, 0, len);
499         s->init_num = (int)len + DTLS1_HM_HEADER_LENGTH;
500         s->init_off = 0;
501         /* Buffer the message to handle re-xmits */
502         dtls1_buffer_message(s, 0);
503         }
504
505 static int dtls1_handshake_write(SSL *s)
506         {
507         return dtls1_do_write(s, SSL3_RT_HANDSHAKE);
508         }