1 // Copyright 2005-2016 The OpenSSL Project Authors. All Rights Reserved.
2 //
3 // Licensed under the Apache License, Version 2.0 (the "License");
4 // you may not use this file except in compliance with the License.
5 // You may obtain a copy of the License at
6 //
7 //     https://www.apache.org/licenses/LICENSE-2.0
8 //
9 // Unless required by applicable law or agreed to in writing, software
10 // distributed under the License is distributed on an "AS IS" BASIS,
11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 // See the License for the specific language governing permissions and
13 // limitations under the License.
14 
15 #include <openssl/ssl.h>
16 
17 #include <assert.h>
18 #include <limits.h>
19 #include <string.h>
20 
21 #include <openssl/err.h>
22 #include <openssl/mem.h>
23 #include <openssl/nid.h>
24 
25 #include "../crypto/internal.h"
26 #include "internal.h"
27 
28 
29 BSSL_NAMESPACE_BEGIN
30 
DTLS1_STATE()31 DTLS1_STATE::DTLS1_STATE()
32     : has_change_cipher_spec(false),
33       outgoing_messages_complete(false),
34       flight_has_reply(false),
35       handshake_write_overflow(false),
36       handshake_read_overflow(false),
37       sending_flight(false),
38       sending_ack(false),
39       pending_flush(false),
40       queued_key_update(QueuedKeyUpdate::kNone) {}
41 
~DTLS1_STATE()42 DTLS1_STATE::~DTLS1_STATE() {}
43 
Init()44 bool DTLS1_STATE::Init() {
45   // Set up the initial epochs.
46   read_epoch.aead = SSLAEADContext::CreateNullCipher();
47   write_epoch.aead = SSLAEADContext::CreateNullCipher();
48   if (read_epoch.aead == nullptr || write_epoch.aead == nullptr) {
49     return false;
50   }
51 
52   return true;
53 }
54 
dtls1_new(SSL * ssl)55 bool dtls1_new(SSL *ssl) {
56   if (!tls_new(ssl)) {
57     return false;
58   }
59   UniquePtr<DTLS1_STATE> d1 = MakeUnique<DTLS1_STATE>();
60   if (!d1 || !d1->Init()) {
61     tls_free(ssl);
62     return false;
63   }
64 
65   ssl->d1 = d1.release();
66   return true;
67 }
68 
dtls1_free(SSL * ssl)69 void dtls1_free(SSL *ssl) {
70   tls_free(ssl);
71 
72   if (ssl == NULL) {
73     return;
74   }
75 
76   Delete(ssl->d1);
77   ssl->d1 = NULL;
78 }
79 
StartMicroseconds(OPENSSL_timeval now,uint64_t microseconds)80 void DTLSTimer::StartMicroseconds(OPENSSL_timeval now, uint64_t microseconds) {
81   uint64_t seconds = microseconds / 1000000;
82   microseconds %= 1000000;
83 
84   now.tv_usec += microseconds;
85   if (now.tv_usec >= 1000000) {
86     now.tv_usec -= 1000000;
87     seconds++;
88   }
89 
90   if (now.tv_sec > UINT64_MAX - seconds) {
91     Stop();
92     return;
93   }
94   now.tv_sec += seconds;
95   expire_time_ = now;
96 }
97 
Stop()98 void DTLSTimer::Stop() { expire_time_ = {0, 0}; }
99 
IsExpired(OPENSSL_timeval now) const100 bool DTLSTimer::IsExpired(OPENSSL_timeval now) const {
101   return MicrosecondsRemaining(now) == 0;
102 }
103 
IsSet() const104 bool DTLSTimer::IsSet() const {
105   return expire_time_.tv_sec != 0 || expire_time_.tv_usec != 0;
106 }
107 
MicrosecondsRemaining(OPENSSL_timeval now) const108 uint64_t DTLSTimer::MicrosecondsRemaining(OPENSSL_timeval now) const {
109   if (!IsSet()) {
110     return kNever;
111   }
112 
113   if (now.tv_sec > expire_time_.tv_sec ||
114       (now.tv_sec == expire_time_.tv_sec &&
115        now.tv_usec >= expire_time_.tv_usec)) {
116     return 0;
117   }
118 
119   uint64_t sec = expire_time_.tv_sec - now.tv_sec;
120   uint32_t usec;
121   if (expire_time_.tv_usec >= now.tv_usec) {
122     usec = expire_time_.tv_usec - now.tv_usec;
123   } else {
124     sec--;
125     usec = expire_time_.tv_usec + 1000000 - now.tv_usec;
126   }
127 
128   // If remaining time is less than 15 ms, return 0 to prevent issues because of
129   // small divergences with socket timeouts.
130   if (sec == 0 && usec < 15000) {
131     return 0;
132   }
133 
134   if (sec > UINT64_MAX / 1000000) {
135     return kNever;
136   }
137   sec *= 1000000;
138   if (sec > UINT64_MAX - usec) {
139     return kNever;
140   }
141   return sec + usec;
142 }
143 
dtls1_stop_timer(SSL * ssl)144 void dtls1_stop_timer(SSL *ssl) {
145   ssl->d1->num_timeouts = 0;
146   ssl->d1->retransmit_timer.Stop();
147   ssl->d1->timeout_duration_ms = ssl->initial_timeout_duration_ms;
148 }
149 
150 BSSL_NAMESPACE_END
151 
152 using namespace bssl;
153 
DTLSv1_set_initial_timeout_duration(SSL * ssl,uint32_t duration_ms)154 void DTLSv1_set_initial_timeout_duration(SSL *ssl, uint32_t duration_ms) {
155   ssl->initial_timeout_duration_ms = duration_ms;
156 }
157 
DTLSv1_get_timeout(const SSL * ssl,struct timeval * out)158 int DTLSv1_get_timeout(const SSL *ssl, struct timeval *out) {
159   if (!SSL_is_dtls(ssl)) {
160     return 0;
161   }
162 
163   OPENSSL_timeval now = ssl_ctx_get_current_time(ssl->ctx.get());
164   uint64_t remaining_usec =
165       ssl->d1->retransmit_timer.MicrosecondsRemaining(now);
166   remaining_usec =
167       std::min(remaining_usec, ssl->d1->ack_timer.MicrosecondsRemaining(now));
168   if (remaining_usec == DTLSTimer::kNever) {
169     return 0;  // No timeout is set.
170   }
171 
172   uint64_t remaining_sec = remaining_usec / 1000000;
173   remaining_usec %= 1000000;
174 
175   // |timeval| uses |time_t|, which may be 32-bit.
176   const auto kTvSecMax = std::numeric_limits<decltype(out->tv_sec)>::max();
177   if (remaining_sec > static_cast<uint64_t>(kTvSecMax)) {
178     out->tv_sec = kTvSecMax;  // Saturate the output.
179     out->tv_usec = 999999;
180   } else {
181     out->tv_sec = static_cast<decltype(out->tv_sec)>(remaining_sec);
182   }
183   out->tv_usec = remaining_usec;
184   return 1;
185 }
186 
DTLSv1_handle_timeout(SSL * ssl)187 int DTLSv1_handle_timeout(SSL *ssl) {
188   ssl_reset_error_state(ssl);
189 
190   if (!SSL_is_dtls(ssl)) {
191     OPENSSL_PUT_ERROR(SSL, ERR_R_SHOULD_NOT_HAVE_BEEN_CALLED);
192     return -1;
193   }
194 
195   if (!ssl->d1->ack_timer.IsSet() && !ssl->d1->retransmit_timer.IsSet()) {
196     // No timers are running. Don't bother querying the clock.
197     return 0;
198   }
199 
200   OPENSSL_timeval now = ssl_ctx_get_current_time(ssl->ctx.get());
201   bool any_timer_expired = false;
202   if (ssl->d1->ack_timer.IsExpired(now)) {
203     any_timer_expired = true;
204     ssl->d1->sending_ack = true;
205     ssl->d1->ack_timer.Stop();
206   }
207 
208   if (ssl->d1->retransmit_timer.IsExpired(now)) {
209     any_timer_expired = true;
210     ssl->d1->sending_flight = true;
211     ssl->d1->retransmit_timer.Stop();
212 
213     ssl->d1->num_timeouts++;
214     // Reduce MTU after 2 unsuccessful retransmissions.
215     if (ssl->d1->num_timeouts > DTLS1_MTU_TIMEOUTS &&
216         !(SSL_get_options(ssl) & SSL_OP_NO_QUERY_MTU)) {
217       long mtu = BIO_ctrl(ssl->wbio.get(), BIO_CTRL_DGRAM_GET_FALLBACK_MTU, 0,
218                           nullptr);
219       if (mtu >= 0 && mtu <= (1 << 30) && (unsigned)mtu >= dtls1_min_mtu()) {
220         ssl->d1->mtu = (unsigned)mtu;
221       }
222     }
223   }
224 
225   if (!any_timer_expired) {
226     return 0;
227   }
228 
229   return dtls1_flush(ssl);
230 }
231