1 /* DTLS implementation written by Nagendra Modadugu
2 * (nagendra@cs.stanford.edu) for the OpenSSL project 2005. */
3 /* ====================================================================
4 * Copyright (c) 1998-2005 The OpenSSL Project. All rights reserved.
5 *
6 * Redistribution and use in source and binary forms, with or without
7 * modification, are permitted provided that the following conditions
8 * are met:
9 *
10 * 1. Redistributions of source code must retain the above copyright
11 * notice, this list of conditions and the following disclaimer.
12 *
13 * 2. Redistributions in binary form must reproduce the above copyright
14 * notice, this list of conditions and the following disclaimer in
15 * the documentation and/or other materials provided with the
16 * distribution.
17 *
18 * 3. All advertising materials mentioning features or use of this
19 * software must display the following acknowledgment:
20 * "This product includes software developed by the OpenSSL Project
21 * for use in the OpenSSL Toolkit. (http://www.openssl.org/)"
22 *
23 * 4. The names "OpenSSL Toolkit" and "OpenSSL Project" must not be used to
24 * endorse or promote products derived from this software without
25 * prior written permission. For written permission, please contact
26 * openssl-core@openssl.org.
27 *
28 * 5. Products derived from this software may not be called "OpenSSL"
29 * nor may "OpenSSL" appear in their names without prior written
30 * permission of the OpenSSL Project.
31 *
32 * 6. Redistributions of any form whatsoever must retain the following
33 * acknowledgment:
34 * "This product includes software developed by the OpenSSL Project
35 * for use in the OpenSSL Toolkit (http://www.openssl.org/)"
36 *
37 * THIS SOFTWARE IS PROVIDED BY THE OpenSSL PROJECT ``AS IS'' AND ANY
38 * EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
39 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
40 * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE OpenSSL PROJECT OR
41 * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
42 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
43 * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
44 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
45 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
46 * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
47 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
48 * OF THE POSSIBILITY OF SUCH DAMAGE.
49 * ====================================================================
50 *
51 * This product includes cryptographic software written by Eric Young
52 * (eay@cryptsoft.com). This product includes software written by Tim
53 * Hudson (tjh@cryptsoft.com).
54 *
55 */
56 /* Copyright (C) 1995-1998 Eric Young (eay@cryptsoft.com)
57 * All rights reserved.
58 *
59 * This package is an SSL implementation written
60 * by Eric Young (eay@cryptsoft.com).
61 * The implementation was written so as to conform with Netscapes SSL.
62 *
63 * This library is free for commercial and non-commercial use as long as
64 * the following conditions are aheared to. The following conditions
65 * apply to all code found in this distribution, be it the RC4, RSA,
66 * lhash, DES, etc., code; not just the SSL code. The SSL documentation
67 * included with this distribution is covered by the same copyright terms
68 * except that the holder is Tim Hudson (tjh@cryptsoft.com).
69 *
70 * Copyright remains Eric Young's, and as such any Copyright notices in
71 * the code are not to be removed.
72 * If this package is used in a product, Eric Young should be given attribution
73 * as the author of the parts of the library used.
74 * This can be in the form of a textual message at program startup or
75 * in documentation (online or textual) provided with the package.
76 *
77 * Redistribution and use in source and binary forms, with or without
78 * modification, are permitted provided that the following conditions
79 * are met:
80 * 1. Redistributions of source code must retain the copyright
81 * notice, this list of conditions and the following disclaimer.
82 * 2. Redistributions in binary form must reproduce the above copyright
83 * notice, this list of conditions and the following disclaimer in the
84 * documentation and/or other materials provided with the distribution.
85 * 3. All advertising materials mentioning features or use of this software
86 * must display the following acknowledgement:
87 * "This product includes cryptographic software written by
88 * Eric Young (eay@cryptsoft.com)"
89 * The word 'cryptographic' can be left out if the rouines from the library
90 * being used are not cryptographic related :-).
91 * 4. If you include any Windows specific code (or a derivative thereof) from
92 * the apps directory (application code) you must include an acknowledgement:
93 * "This product includes software written by Tim Hudson (tjh@cryptsoft.com)"
94 *
95 * THIS SOFTWARE IS PROVIDED BY ERIC YOUNG ``AS IS'' AND
96 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
97 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
98 * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
99 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
100 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
101 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
102 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
103 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
104 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
105 * SUCH DAMAGE.
106 *
107 * The licence and distribution terms for any publically available version or
108 * derivative of this code cannot be changed. i.e. this code cannot simply be
109 * copied and put under another distribution licence
110 * [including the GNU Public Licence.] */
111
112 #include <openssl/ssl.h>
113
114 #include <assert.h>
115 #include <string.h>
116
117 #include <algorithm>
118
119 #include <openssl/bio.h>
120 #include <openssl/bytestring.h>
121 #include <openssl/err.h>
122 #include <openssl/evp.h>
123 #include <openssl/mem.h>
124 #include <openssl/rand.h>
125
126 #include "../crypto/internal.h"
127 #include "internal.h"
128
129
130 BSSL_NAMESPACE_BEGIN
131
dtls1_process_ack(SSL * ssl,uint8_t * out_alert,DTLSRecordNumber ack_record_number,Span<const uint8_t> data)132 ssl_open_record_t dtls1_process_ack(SSL *ssl, uint8_t *out_alert,
133 DTLSRecordNumber ack_record_number,
134 Span<const uint8_t> data) {
135 // As a DTLS-1.3-capable client, it is possible to receive an ACK before we
136 // receive ServerHello and learned the server picked DTLS 1.3. Thus, tolerate
137 // but ignore ACKs before the version is set.
138 if (!ssl_has_final_version(ssl)) {
139 return ssl_open_record_discard;
140 }
141
142 // ACKs are only allowed in DTLS 1.3. Reject them if we've negotiated a
143 // version and it's not 1.3.
144 if (ssl_protocol_version(ssl) < TLS1_3_VERSION) {
145 OPENSSL_PUT_ERROR(SSL, SSL_R_UNEXPECTED_RECORD);
146 *out_alert = SSL_AD_UNEXPECTED_MESSAGE;
147 return ssl_open_record_error;
148 }
149
150 CBS cbs = data, record_numbers;
151 if (!CBS_get_u16_length_prefixed(&cbs, &record_numbers) ||
152 CBS_len(&cbs) != 0) {
153 OPENSSL_PUT_ERROR(SSL, SSL_R_DECODE_ERROR);
154 *out_alert = SSL_AD_DECODE_ERROR;
155 return ssl_open_record_error;
156 }
157
158 while (CBS_len(&record_numbers) != 0) {
159 uint64_t epoch, seq;
160 if (!CBS_get_u64(&record_numbers, &epoch) ||
161 !CBS_get_u64(&record_numbers, &seq)) {
162 OPENSSL_PUT_ERROR(SSL, SSL_R_DECODE_ERROR);
163 *out_alert = SSL_AD_DECODE_ERROR;
164 return ssl_open_record_error;
165 }
166
167 // During the handshake, records must be ACKed at the same or higher epoch.
168 // See https://www.rfc-editor.org/errata/eid8108. Additionally, if the
169 // record does not fit in DTLSRecordNumber, it is definitely not a record
170 // number that we sent.
171 if ((ack_record_number.epoch() < ssl_encryption_application &&
172 epoch > ack_record_number.epoch()) ||
173 epoch > UINT16_MAX || seq > DTLSRecordNumber::kMaxSequence) {
174 OPENSSL_PUT_ERROR(SSL, SSL_R_DECODE_ERROR);
175 *out_alert = SSL_AD_ILLEGAL_PARAMETER;
176 return ssl_open_record_error;
177 }
178
179 // Find the sent record that matches this ACK.
180 DTLSRecordNumber number(static_cast<uint16_t>(epoch), seq);
181 DTLSSentRecord *sent_record = nullptr;
182 if (ssl->d1->sent_records != nullptr) {
183 for (size_t i = 0; i < ssl->d1->sent_records->size(); i++) {
184 if ((*ssl->d1->sent_records)[i].number == number) {
185 sent_record = &(*ssl->d1->sent_records)[i];
186 break;
187 }
188 }
189 }
190 if (sent_record == nullptr) {
191 // We may have sent this record and forgotten it, so this is not an error.
192 continue;
193 }
194
195 // Mark each message as ACKed.
196 if (sent_record->first_msg == sent_record->last_msg) {
197 ssl->d1->outgoing_messages[sent_record->first_msg].acked.MarkRange(
198 sent_record->first_msg_start, sent_record->last_msg_end);
199 } else {
200 ssl->d1->outgoing_messages[sent_record->first_msg].acked.MarkRange(
201 sent_record->first_msg_start, SIZE_MAX);
202 for (size_t i = size_t{sent_record->first_msg} + 1;
203 i < sent_record->last_msg; i++) {
204 ssl->d1->outgoing_messages[i].acked.MarkRange(0, SIZE_MAX);
205 }
206 if (sent_record->last_msg_end != 0) {
207 ssl->d1->outgoing_messages[sent_record->last_msg].acked.MarkRange(
208 0, sent_record->last_msg_end);
209 }
210 }
211
212 // Clear the state so we don't bother re-marking the messages next time.
213 sent_record->first_msg = 0;
214 sent_record->first_msg_start = 0;
215 sent_record->last_msg = 0;
216 sent_record->last_msg_end = 0;
217 }
218
219 // If the outgoing flight is now fully ACKed, we are done retransmitting.
220 if (std::all_of(ssl->d1->outgoing_messages.begin(),
221 ssl->d1->outgoing_messages.end(),
222 [](const auto &msg) { return msg.IsFullyAcked(); })) {
223 dtls1_stop_timer(ssl);
224 dtls_clear_outgoing_messages(ssl);
225 } else {
226 // We may still be able to drop unused write epochs.
227 dtls_clear_unused_write_epochs(ssl);
228
229 // TODO(crbug.com/42290594): Schedule a retransmit. The peer will have
230 // waited before sending the ACK, so a partial ACK suggests packet loss.
231 }
232
233 ssl_do_msg_callback(ssl, /*is_write=*/0, SSL3_RT_ACK, data);
234 return ssl_open_record_discard;
235 }
236
dtls1_open_app_data(SSL * ssl,Span<uint8_t> * out,size_t * out_consumed,uint8_t * out_alert,Span<uint8_t> in)237 ssl_open_record_t dtls1_open_app_data(SSL *ssl, Span<uint8_t> *out,
238 size_t *out_consumed, uint8_t *out_alert,
239 Span<uint8_t> in) {
240 assert(!SSL_in_init(ssl));
241
242 uint8_t type;
243 DTLSRecordNumber record_number;
244 Span<uint8_t> record;
245 auto ret = dtls_open_record(ssl, &type, &record_number, &record, out_consumed,
246 out_alert, in);
247 if (ret != ssl_open_record_success) {
248 return ret;
249 }
250
251 if (type == SSL3_RT_HANDSHAKE) {
252 // Process handshake fragments for DTLS 1.3 post-handshake messages.
253 if (ssl_protocol_version(ssl) >= TLS1_3_VERSION) {
254 if (!dtls1_process_handshake_fragments(ssl, out_alert, record_number,
255 record)) {
256 return ssl_open_record_error;
257 }
258 return ssl_open_record_discard;
259 }
260
261 // Parse the first fragment header to determine if this is a pre-CCS or
262 // post-CCS handshake record. DTLS resets handshake message numbers on each
263 // handshake, so renegotiations and retransmissions are ambiguous.
264 CBS cbs, body;
265 struct hm_header_st msg_hdr;
266 CBS_init(&cbs, record.data(), record.size());
267 if (!dtls1_parse_fragment(&cbs, &msg_hdr, &body)) {
268 OPENSSL_PUT_ERROR(SSL, SSL_R_BAD_HANDSHAKE_RECORD);
269 *out_alert = SSL_AD_DECODE_ERROR;
270 return ssl_open_record_error;
271 }
272
273 if (msg_hdr.type == SSL3_MT_FINISHED &&
274 msg_hdr.seq == ssl->d1->handshake_read_seq - 1) {
275 if (msg_hdr.frag_off == 0) {
276 // Retransmit our last flight of messages. If the peer sends the second
277 // Finished, they may not have received ours. Only do this for the
278 // first fragment, in case the Finished was fragmented.
279 if (!dtls1_check_timeout_num(ssl)) {
280 *out_alert = 0; // TODO(davidben): Send an alert?
281 return ssl_open_record_error;
282 }
283
284 dtls1_retransmit_outgoing_messages(ssl);
285 }
286 return ssl_open_record_discard;
287 }
288
289 // Otherwise, this is a pre-CCS handshake message from an unsupported
290 // renegotiation attempt. Fall through to the error path.
291 }
292
293 if (type == SSL3_RT_ACK) {
294 return dtls1_process_ack(ssl, out_alert, record_number, record);
295 }
296
297 if (type != SSL3_RT_APPLICATION_DATA) {
298 OPENSSL_PUT_ERROR(SSL, SSL_R_UNEXPECTED_RECORD);
299 *out_alert = SSL_AD_UNEXPECTED_MESSAGE;
300 return ssl_open_record_error;
301 }
302
303 if (record.empty()) {
304 return ssl_open_record_discard;
305 }
306
307 *out = record;
308 return ssl_open_record_success;
309 }
310
dtls1_write_app_data(SSL * ssl,bool * out_needs_handshake,size_t * out_bytes_written,Span<const uint8_t> in)311 int dtls1_write_app_data(SSL *ssl, bool *out_needs_handshake,
312 size_t *out_bytes_written, Span<const uint8_t> in) {
313 assert(!SSL_in_init(ssl));
314 *out_needs_handshake = false;
315
316 if (ssl->s3->write_shutdown != ssl_shutdown_none) {
317 OPENSSL_PUT_ERROR(SSL, SSL_R_PROTOCOL_IS_SHUTDOWN);
318 return -1;
319 }
320
321 // DTLS does not split the input across records.
322 if (in.size() > SSL3_RT_MAX_PLAIN_LENGTH) {
323 OPENSSL_PUT_ERROR(SSL, SSL_R_DTLS_MESSAGE_TOO_BIG);
324 return -1;
325 }
326
327 if (in.empty()) {
328 *out_bytes_written = 0;
329 return 1;
330 }
331
332 // TODO(crbug.com/42290594): Use the 0-RTT epoch if writing 0-RTT.
333 int ret = dtls1_write_record(ssl, SSL3_RT_APPLICATION_DATA, in,
334 ssl->d1->write_epoch.epoch());
335 if (ret <= 0) {
336 return ret;
337 }
338 *out_bytes_written = in.size();
339 return 1;
340 }
341
dtls1_write_record(SSL * ssl,int type,Span<const uint8_t> in,uint16_t epoch)342 int dtls1_write_record(SSL *ssl, int type, Span<const uint8_t> in,
343 uint16_t epoch) {
344 SSLBuffer *buf = &ssl->s3->write_buffer;
345 assert(in.size() <= SSL3_RT_MAX_PLAIN_LENGTH);
346 // There should never be a pending write buffer in DTLS. One can't write half
347 // a datagram, so the write buffer is always dropped in
348 // |ssl_write_buffer_flush|.
349 assert(buf->empty());
350
351 if (in.size() > SSL3_RT_MAX_PLAIN_LENGTH) {
352 OPENSSL_PUT_ERROR(SSL, ERR_R_INTERNAL_ERROR);
353 return -1;
354 }
355
356 DTLSRecordNumber record_number;
357 size_t ciphertext_len;
358 if (!buf->EnsureCap(dtls_seal_prefix_len(ssl, epoch),
359 in.size() + SSL_max_seal_overhead(ssl)) ||
360 !dtls_seal_record(ssl, &record_number, buf->remaining().data(),
361 &ciphertext_len, buf->remaining().size(), type,
362 in.data(), in.size(), epoch)) {
363 buf->Clear();
364 return -1;
365 }
366 buf->DidWrite(ciphertext_len);
367
368 int ret = ssl_write_buffer_flush(ssl);
369 if (ret <= 0) {
370 return ret;
371 }
372 return 1;
373 }
374
dtls1_dispatch_alert(SSL * ssl)375 int dtls1_dispatch_alert(SSL *ssl) {
376 int ret = dtls1_write_record(ssl, SSL3_RT_ALERT, ssl->s3->send_alert,
377 ssl->d1->write_epoch.epoch());
378 if (ret <= 0) {
379 return ret;
380 }
381 ssl->s3->alert_dispatch = false;
382
383 // If the alert is fatal, flush the BIO now.
384 if (ssl->s3->send_alert[0] == SSL3_AL_FATAL) {
385 BIO_flush(ssl->wbio.get());
386 }
387
388 ssl_do_msg_callback(ssl, 1 /* write */, SSL3_RT_ALERT, ssl->s3->send_alert);
389
390 int alert = (ssl->s3->send_alert[0] << 8) | ssl->s3->send_alert[1];
391 ssl_do_info_callback(ssl, SSL_CB_WRITE_ALERT, alert);
392
393 return 1;
394 }
395
396 BSSL_NAMESPACE_END
397