• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
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/ssl.h>
58 
59 #include <assert.h>
60 #include <limits.h>
61 #include <string.h>
62 
63 #include <openssl/err.h>
64 #include <openssl/mem.h>
65 #include <openssl/nid.h>
66 
67 #include "../crypto/internal.h"
68 #include "internal.h"
69 
70 
71 BSSL_NAMESPACE_BEGIN
72 
73 // DTLS1_MTU_TIMEOUTS is the maximum number of timeouts to expire
74 // before starting to decrease the MTU.
75 #define DTLS1_MTU_TIMEOUTS 2
76 
77 // DTLS1_MAX_TIMEOUTS is the maximum number of timeouts to expire
78 // before failing the DTLS handshake.
79 #define DTLS1_MAX_TIMEOUTS 12
80 
DTLS1_STATE()81 DTLS1_STATE::DTLS1_STATE()
82     : has_change_cipher_spec(false),
83       outgoing_messages_complete(false),
84       flight_has_reply(false) {}
85 
~DTLS1_STATE()86 DTLS1_STATE::~DTLS1_STATE() {}
87 
Init()88 bool DTLS1_STATE::Init() {
89   // Set up the initial epochs.
90   read_epoch.aead = SSLAEADContext::CreateNullCipher();
91   write_epoch.aead = SSLAEADContext::CreateNullCipher();
92   if (read_epoch.aead == nullptr || write_epoch.aead == nullptr) {
93     return false;
94   }
95 
96   return true;
97 }
98 
dtls1_new(SSL * ssl)99 bool dtls1_new(SSL *ssl) {
100   if (!tls_new(ssl)) {
101     return false;
102   }
103   UniquePtr<DTLS1_STATE> d1 = MakeUnique<DTLS1_STATE>();
104   if (!d1 || !d1->Init()) {
105     tls_free(ssl);
106     return false;
107   }
108 
109   ssl->d1 = d1.release();
110   return true;
111 }
112 
dtls1_free(SSL * ssl)113 void dtls1_free(SSL *ssl) {
114   tls_free(ssl);
115 
116   if (ssl == NULL) {
117     return;
118   }
119 
120   Delete(ssl->d1);
121   ssl->d1 = NULL;
122 }
123 
StartMicroseconds(OPENSSL_timeval now,uint64_t microseconds)124 void DTLSTimer::StartMicroseconds(OPENSSL_timeval now, uint64_t microseconds) {
125   uint64_t seconds = microseconds / 1000000;
126   microseconds %= 1000000;
127 
128   now.tv_usec += microseconds;
129   if (now.tv_usec >= 1000000) {
130     now.tv_usec -= 1000000;
131     seconds++;
132   }
133 
134   if (now.tv_sec > UINT64_MAX - seconds) {
135     Stop();
136     return;
137   }
138   now.tv_sec += seconds;
139   expire_time_ = now;
140 }
141 
Stop()142 void DTLSTimer::Stop() { expire_time_ = {0, 0}; }
143 
IsExpired(OPENSSL_timeval now) const144 bool DTLSTimer::IsExpired(OPENSSL_timeval now) const {
145   return MicrosecondsRemaining(now) == 0;
146 }
147 
IsSet() const148 bool DTLSTimer::IsSet() const {
149   return expire_time_.tv_sec != 0 || expire_time_.tv_usec != 0;
150 }
151 
MicrosecondsRemaining(OPENSSL_timeval now) const152 uint64_t DTLSTimer::MicrosecondsRemaining(OPENSSL_timeval now) const {
153   if (!IsSet()) {
154     return kNever;
155   }
156 
157   if (now.tv_sec > expire_time_.tv_sec ||
158       (now.tv_sec == expire_time_.tv_sec &&
159        now.tv_usec >= expire_time_.tv_usec)) {
160     return 0;
161   }
162 
163   uint64_t sec = expire_time_.tv_sec - now.tv_sec;
164   uint32_t usec;
165   if (expire_time_.tv_usec >= now.tv_usec) {
166     usec = expire_time_.tv_usec - now.tv_usec;
167   } else {
168     sec--;
169     usec = expire_time_.tv_usec + 1000000 - now.tv_usec;
170   }
171 
172   // If remaining time is less than 15 ms, return 0 to prevent issues because of
173   // small divergences with socket timeouts.
174   if (sec == 0 && usec < 15000) {
175     return 0;
176   }
177 
178   if (sec > UINT64_MAX / 1000000) {
179     return kNever;
180   }
181   sec *= 1000000;
182   if (sec > UINT64_MAX - usec) {
183     return kNever;
184   }
185   return sec + usec;
186 }
187 
dtls1_start_timer(SSL * ssl)188 void dtls1_start_timer(SSL *ssl) {
189   // If timer is not set, initialize duration.
190   if (!ssl->d1->retransmit_timer.IsSet()) {
191     ssl->d1->timeout_duration_ms = ssl->initial_timeout_duration_ms;
192   }
193 
194   OPENSSL_timeval now = ssl_ctx_get_current_time(ssl->ctx.get());
195   ssl->d1->retransmit_timer.StartMicroseconds(
196       now, uint64_t{ssl->d1->timeout_duration_ms} * 1000);
197 }
198 
dtls1_double_timeout(SSL * ssl)199 static void dtls1_double_timeout(SSL *ssl) {
200   ssl->d1->timeout_duration_ms *= 2;
201   if (ssl->d1->timeout_duration_ms > 60000) {
202     ssl->d1->timeout_duration_ms = 60000;
203   }
204 }
205 
dtls1_stop_timer(SSL * ssl)206 void dtls1_stop_timer(SSL *ssl) {
207   ssl->d1->num_timeouts = 0;
208   ssl->d1->retransmit_timer.Stop();
209   ssl->d1->timeout_duration_ms = ssl->initial_timeout_duration_ms;
210 }
211 
dtls1_check_timeout_num(SSL * ssl)212 bool dtls1_check_timeout_num(SSL *ssl) {
213   ssl->d1->num_timeouts++;
214 
215   // Reduce MTU after 2 unsuccessful retransmissions
216   if (ssl->d1->num_timeouts > DTLS1_MTU_TIMEOUTS &&
217       !(SSL_get_options(ssl) & SSL_OP_NO_QUERY_MTU)) {
218     long mtu =
219         BIO_ctrl(ssl->wbio.get(), BIO_CTRL_DGRAM_GET_FALLBACK_MTU, 0, nullptr);
220     if (mtu >= 0 && mtu <= (1 << 30) && (unsigned)mtu >= dtls1_min_mtu()) {
221       ssl->d1->mtu = (unsigned)mtu;
222     }
223   }
224 
225   if (ssl->d1->num_timeouts > DTLS1_MAX_TIMEOUTS) {
226     // fail the connection, enough alerts have been sent
227     OPENSSL_PUT_ERROR(SSL, SSL_R_READ_TIMEOUT_EXPIRED);
228     return false;
229   }
230 
231   return true;
232 }
233 
234 BSSL_NAMESPACE_END
235 
236 using namespace bssl;
237 
DTLSv1_set_initial_timeout_duration(SSL * ssl,uint32_t duration_ms)238 void DTLSv1_set_initial_timeout_duration(SSL *ssl, uint32_t duration_ms) {
239   ssl->initial_timeout_duration_ms = duration_ms;
240 }
241 
DTLSv1_get_timeout(const SSL * ssl,struct timeval * out)242 int DTLSv1_get_timeout(const SSL *ssl, struct timeval *out) {
243   if (!SSL_is_dtls(ssl)) {
244     return 0;
245   }
246 
247   OPENSSL_timeval now = ssl_ctx_get_current_time(ssl->ctx.get());
248   uint64_t remaining_usec =
249       ssl->d1->retransmit_timer.MicrosecondsRemaining(now);
250   remaining_usec =
251       std::min(remaining_usec, ssl->d1->ack_timer.MicrosecondsRemaining(now));
252   if (remaining_usec == DTLSTimer::kNever) {
253     return 0;  // No timeout is set.
254   }
255 
256   uint64_t remaining_sec = remaining_usec / 1000000;
257   remaining_usec %= 1000000;
258 
259   // |timeval| uses |time_t|, which may be 32-bit.
260   const auto kTvSecMax = std::numeric_limits<decltype(out->tv_sec)>::max();
261   if (remaining_sec > static_cast<uint64_t>(kTvSecMax)) {
262     out->tv_sec = kTvSecMax;  // Saturate the output.
263     out->tv_usec = 999999;
264   } else {
265     out->tv_sec = static_cast<decltype(out->tv_sec)>(remaining_sec);
266   }
267   out->tv_usec = remaining_usec;
268   return 1;
269 }
270 
DTLSv1_handle_timeout(SSL * ssl)271 int DTLSv1_handle_timeout(SSL *ssl) {
272   ssl_reset_error_state(ssl);
273 
274   if (!SSL_is_dtls(ssl)) {
275     OPENSSL_PUT_ERROR(SSL, ERR_R_SHOULD_NOT_HAVE_BEEN_CALLED);
276     return -1;
277   }
278 
279   if (!ssl->d1->ack_timer.IsSet() && !ssl->d1->retransmit_timer.IsSet()) {
280     // No timers are running. Don't bother querying the clock.
281     return 0;
282   }
283 
284   OPENSSL_timeval now = ssl_ctx_get_current_time(ssl->ctx.get());
285   bool any_timer_expired = false;
286   if (ssl->d1->ack_timer.IsExpired(now)) {
287     any_timer_expired = true;
288     int ret = dtls1_send_ack(ssl);
289     if (ret <= 0) {
290       return ret;
291     }
292   }
293 
294   if (ssl->d1->retransmit_timer.IsExpired(now)) {
295     any_timer_expired = true;
296     if (!dtls1_check_timeout_num(ssl)) {
297       return -1;
298     }
299 
300     dtls1_double_timeout(ssl);
301     dtls1_start_timer(ssl);
302     int ret = dtls1_retransmit_outgoing_messages(ssl);
303     if (ret <= 0) {
304       return ret;
305     }
306   }
307 
308   return any_timer_expired ? 1 : 0;
309 }
310