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 <limits.h>
60 #include <stdio.h>
61 #include <string.h>
62 
63 #if defined(OPENSSL_WINDOWS)
64 #include <sys/timeb.h>
65 #else
66 #include <sys/socket.h>
67 #include <sys/time.h>
68 #endif
69 
70 #include <openssl/err.h>
71 #include <openssl/mem.h>
72 #include <openssl/obj.h>
73 
74 #include "internal.h"
75 
76 /* DTLS1_MTU_TIMEOUTS is the maximum number of timeouts to expire
77  * before starting to decrease the MTU. */
78 #define DTLS1_MTU_TIMEOUTS                     2
79 
80 /* DTLS1_MAX_TIMEOUTS is the maximum number of timeouts to expire
81  * before failing the DTLS handshake. */
82 #define DTLS1_MAX_TIMEOUTS                     12
83 
84 static void get_current_time(const SSL *ssl, struct timeval *out_clock);
85 
dtls1_new(SSL * s)86 int dtls1_new(SSL *s) {
87   DTLS1_STATE *d1;
88 
89   if (!ssl3_new(s)) {
90     return 0;
91   }
92   d1 = OPENSSL_malloc(sizeof *d1);
93   if (d1 == NULL) {
94     ssl3_free(s);
95     return 0;
96   }
97   memset(d1, 0, sizeof *d1);
98 
99   d1->buffered_messages = pqueue_new();
100   d1->sent_messages = pqueue_new();
101 
102   if (!d1->buffered_messages || !d1->sent_messages) {
103     pqueue_free(d1->buffered_messages);
104     pqueue_free(d1->sent_messages);
105     OPENSSL_free(d1);
106     ssl3_free(s);
107     return 0;
108   }
109 
110   s->d1 = d1;
111 
112   /* Set the version to the highest version for DTLS. This controls the initial
113    * state of |s->enc_method| and what the API reports as the version prior to
114    * negotiation.
115    *
116    * TODO(davidben): This is fragile and confusing. */
117   s->version = DTLS1_2_VERSION;
118   return 1;
119 }
120 
dtls1_clear_queues(SSL * s)121 static void dtls1_clear_queues(SSL *s) {
122   pitem *item = NULL;
123   hm_fragment *frag = NULL;
124 
125   while ((item = pqueue_pop(s->d1->buffered_messages)) != NULL) {
126     frag = (hm_fragment *)item->data;
127     dtls1_hm_fragment_free(frag);
128     pitem_free(item);
129   }
130 
131   while ((item = pqueue_pop(s->d1->sent_messages)) != NULL) {
132     frag = (hm_fragment *)item->data;
133     dtls1_hm_fragment_free(frag);
134     pitem_free(item);
135   }
136 }
137 
dtls1_free(SSL * s)138 void dtls1_free(SSL *s) {
139   ssl3_free(s);
140 
141   if (s == NULL || s->d1 == NULL) {
142     return;
143   }
144 
145   dtls1_clear_queues(s);
146 
147   pqueue_free(s->d1->buffered_messages);
148   pqueue_free(s->d1->sent_messages);
149 
150   OPENSSL_free(s->d1);
151   s->d1 = NULL;
152 }
153 
dtls1_supports_cipher(const SSL_CIPHER * cipher)154 int dtls1_supports_cipher(const SSL_CIPHER *cipher) {
155   /* DTLS does not support stream ciphers. */
156   return cipher->algorithm_enc != SSL_RC4;
157 }
158 
dtls1_start_timer(SSL * s)159 void dtls1_start_timer(SSL *s) {
160   /* If timer is not set, initialize duration with 1 second */
161   if (s->d1->next_timeout.tv_sec == 0 && s->d1->next_timeout.tv_usec == 0) {
162     s->d1->timeout_duration = 1;
163   }
164 
165   /* Set timeout to current time */
166   get_current_time(s, &s->d1->next_timeout);
167 
168   /* Add duration to current time */
169   s->d1->next_timeout.tv_sec += s->d1->timeout_duration;
170   BIO_ctrl(SSL_get_rbio(s), BIO_CTRL_DGRAM_SET_NEXT_TIMEOUT, 0,
171            &s->d1->next_timeout);
172 }
173 
DTLSv1_get_timeout(const SSL * ssl,struct timeval * out)174 int DTLSv1_get_timeout(const SSL *ssl, struct timeval *out) {
175   if (!SSL_IS_DTLS(ssl)) {
176     return 0;
177   }
178 
179   /* If no timeout is set, just return NULL */
180   if (ssl->d1->next_timeout.tv_sec == 0 && ssl->d1->next_timeout.tv_usec == 0) {
181     return 0;
182   }
183 
184   /* Get current time */
185   struct timeval timenow;
186   get_current_time(ssl, &timenow);
187 
188   /* If timer already expired, set remaining time to 0 */
189   if (ssl->d1->next_timeout.tv_sec < timenow.tv_sec ||
190       (ssl->d1->next_timeout.tv_sec == timenow.tv_sec &&
191        ssl->d1->next_timeout.tv_usec <= timenow.tv_usec)) {
192     memset(out, 0, sizeof(struct timeval));
193     return 1;
194   }
195 
196   /* Calculate time left until timer expires */
197   memcpy(out, &ssl->d1->next_timeout, sizeof(struct timeval));
198   out->tv_sec -= timenow.tv_sec;
199   out->tv_usec -= timenow.tv_usec;
200   if (out->tv_usec < 0) {
201     out->tv_sec--;
202     out->tv_usec += 1000000;
203   }
204 
205   /* If remaining time is less than 15 ms, set it to 0 to prevent issues
206    * because of small devergences with socket timeouts. */
207   if (out->tv_sec == 0 && out->tv_usec < 15000) {
208     memset(out, 0, sizeof(struct timeval));
209   }
210 
211   return 1;
212 }
213 
dtls1_is_timer_expired(SSL * s)214 int dtls1_is_timer_expired(SSL *s) {
215   struct timeval timeleft;
216 
217   /* Get time left until timeout, return false if no timer running */
218   if (!DTLSv1_get_timeout(s, &timeleft)) {
219     return 0;
220   }
221 
222   /* Return false if timer is not expired yet */
223   if (timeleft.tv_sec > 0 || timeleft.tv_usec > 0) {
224     return 0;
225   }
226 
227   /* Timer expired, so return true */
228   return 1;
229 }
230 
dtls1_double_timeout(SSL * s)231 void dtls1_double_timeout(SSL *s) {
232   s->d1->timeout_duration *= 2;
233   if (s->d1->timeout_duration > 60) {
234     s->d1->timeout_duration = 60;
235   }
236   dtls1_start_timer(s);
237 }
238 
dtls1_stop_timer(SSL * s)239 void dtls1_stop_timer(SSL *s) {
240   /* Reset everything */
241   s->d1->num_timeouts = 0;
242   memset(&s->d1->next_timeout, 0, sizeof(struct timeval));
243   s->d1->timeout_duration = 1;
244   BIO_ctrl(SSL_get_rbio(s), BIO_CTRL_DGRAM_SET_NEXT_TIMEOUT, 0,
245            &s->d1->next_timeout);
246   /* Clear retransmission buffer */
247   dtls1_clear_record_buffer(s);
248 }
249 
dtls1_check_timeout_num(SSL * s)250 int dtls1_check_timeout_num(SSL *s) {
251   s->d1->num_timeouts++;
252 
253   /* Reduce MTU after 2 unsuccessful retransmissions */
254   if (s->d1->num_timeouts > DTLS1_MTU_TIMEOUTS &&
255       !(SSL_get_options(s) & SSL_OP_NO_QUERY_MTU)) {
256     long mtu = BIO_ctrl(SSL_get_wbio(s), BIO_CTRL_DGRAM_GET_FALLBACK_MTU, 0,
257                         NULL);
258     if (mtu >= 0 && mtu <= (1 << 30) && (unsigned)mtu >= dtls1_min_mtu()) {
259       s->d1->mtu = (unsigned)mtu;
260     }
261   }
262 
263   if (s->d1->num_timeouts > DTLS1_MAX_TIMEOUTS) {
264     /* fail the connection, enough alerts have been sent */
265     OPENSSL_PUT_ERROR(SSL, dtls1_check_timeout_num, SSL_R_READ_TIMEOUT_EXPIRED);
266     return -1;
267   }
268 
269   return 0;
270 }
271 
DTLSv1_handle_timeout(SSL * ssl)272 int DTLSv1_handle_timeout(SSL *ssl) {
273   if (!SSL_IS_DTLS(ssl)) {
274     return -1;
275   }
276 
277   /* if no timer is expired, don't do anything */
278   if (!dtls1_is_timer_expired(ssl)) {
279     return 0;
280   }
281 
282   dtls1_double_timeout(ssl);
283 
284   if (dtls1_check_timeout_num(ssl) < 0) {
285     return -1;
286   }
287 
288   dtls1_start_timer(ssl);
289   return dtls1_retransmit_buffered_messages(ssl);
290 }
291 
get_current_time(const SSL * ssl,struct timeval * out_clock)292 static void get_current_time(const SSL *ssl, struct timeval *out_clock) {
293   if (ssl->ctx->current_time_cb != NULL) {
294     ssl->ctx->current_time_cb(ssl, out_clock);
295     return;
296   }
297 
298 #if defined(OPENSSL_WINDOWS)
299   struct _timeb time;
300   _ftime(&time);
301   out_clock->tv_sec = time.time;
302   out_clock->tv_usec = time.millitm * 1000;
303 #else
304   gettimeofday(out_clock, NULL);
305 #endif
306 }
307 
dtls1_set_handshake_header(SSL * s,int htype,unsigned long len)308 int dtls1_set_handshake_header(SSL *s, int htype, unsigned long len) {
309   uint8_t *message = (uint8_t *)s->init_buf->data;
310   const struct hm_header_st *msg_hdr = &s->d1->w_msg_hdr;
311   uint8_t serialised_header[DTLS1_HM_HEADER_LENGTH];
312   uint8_t *p = serialised_header;
313 
314   s->d1->handshake_write_seq = s->d1->next_handshake_write_seq;
315   s->d1->next_handshake_write_seq++;
316 
317   dtls1_set_message_header(s, htype, len, s->d1->handshake_write_seq, 0, len);
318   s->init_num = (int)len + DTLS1_HM_HEADER_LENGTH;
319   s->init_off = 0;
320 
321   /* Buffer the message to handle re-xmits */
322   dtls1_buffer_message(s, 0);
323 
324   /* Add the new message to the handshake hash. Serialize the message
325    * header as if it were a single fragment. */
326   *p++ = msg_hdr->type;
327   l2n3(msg_hdr->msg_len, p);
328   s2n(msg_hdr->seq, p);
329   l2n3(0, p);
330   l2n3(msg_hdr->msg_len, p);
331   return ssl3_finish_mac(s, serialised_header, sizeof(serialised_header)) &&
332          ssl3_finish_mac(s, message + DTLS1_HM_HEADER_LENGTH, len);
333 }
334 
dtls1_handshake_write(SSL * s)335 int dtls1_handshake_write(SSL *s) {
336   return dtls1_do_write(s, SSL3_RT_HANDSHAKE, dtls1_use_current_epoch);
337 }
338