• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright 2005-2016 The OpenSSL Project Authors. All Rights Reserved.
3  *
4  * Licensed under the OpenSSL license (the "License").  You may not use
5  * this file except in compliance with the License.  You can obtain a copy
6  * in the file LICENSE in the source distribution or at
7  * https://www.openssl.org/source/license.html
8  */
9 
10 #include <openssl/ssl.h>
11 
12 #include <assert.h>
13 #include <string.h>
14 
15 #include <algorithm>
16 
17 #include <openssl/bio.h>
18 #include <openssl/bytestring.h>
19 #include <openssl/err.h>
20 #include <openssl/evp.h>
21 #include <openssl/mem.h>
22 #include <openssl/rand.h>
23 
24 #include "../crypto/internal.h"
25 #include "internal.h"
26 
27 
28 BSSL_NAMESPACE_BEGIN
29 
dtls1_process_ack(SSL * ssl,uint8_t * out_alert,DTLSRecordNumber ack_record_number,Span<const uint8_t> data)30 ssl_open_record_t dtls1_process_ack(SSL *ssl, uint8_t *out_alert,
31                                     DTLSRecordNumber ack_record_number,
32                                     Span<const uint8_t> data) {
33   // As a DTLS-1.3-capable client, it is possible to receive an ACK before we
34   // receive ServerHello and learned the server picked DTLS 1.3. Thus, tolerate
35   // but ignore ACKs before the version is set.
36   if (!ssl_has_final_version(ssl)) {
37     return ssl_open_record_discard;
38   }
39 
40   // ACKs are only allowed in DTLS 1.3. Reject them if we've negotiated a
41   // version and it's not 1.3.
42   if (ssl_protocol_version(ssl) < TLS1_3_VERSION) {
43     OPENSSL_PUT_ERROR(SSL, SSL_R_UNEXPECTED_RECORD);
44     *out_alert = SSL_AD_UNEXPECTED_MESSAGE;
45     return ssl_open_record_error;
46   }
47 
48   CBS cbs = data, record_numbers;
49   if (!CBS_get_u16_length_prefixed(&cbs, &record_numbers) ||
50       CBS_len(&cbs) != 0) {
51     OPENSSL_PUT_ERROR(SSL, SSL_R_DECODE_ERROR);
52     *out_alert = SSL_AD_DECODE_ERROR;
53     return ssl_open_record_error;
54   }
55 
56   while (CBS_len(&record_numbers) != 0) {
57     uint64_t epoch, seq;
58     if (!CBS_get_u64(&record_numbers, &epoch) ||
59         !CBS_get_u64(&record_numbers, &seq)) {
60       OPENSSL_PUT_ERROR(SSL, SSL_R_DECODE_ERROR);
61       *out_alert = SSL_AD_DECODE_ERROR;
62       return ssl_open_record_error;
63     }
64 
65     // During the handshake, records must be ACKed at the same or higher epoch.
66     // See https://www.rfc-editor.org/errata/eid8108. Additionally, if the
67     // record does not fit in DTLSRecordNumber, it is definitely not a record
68     // number that we sent.
69     if ((ack_record_number.epoch() < ssl_encryption_application &&
70          epoch > ack_record_number.epoch()) ||
71         epoch > UINT16_MAX || seq > DTLSRecordNumber::kMaxSequence) {
72       OPENSSL_PUT_ERROR(SSL, SSL_R_DECODE_ERROR);
73       *out_alert = SSL_AD_ILLEGAL_PARAMETER;
74       return ssl_open_record_error;
75     }
76 
77     // Find the sent record that matches this ACK.
78     DTLSRecordNumber number(static_cast<uint16_t>(epoch), seq);
79     DTLSSentRecord *sent_record = nullptr;
80     if (ssl->d1->sent_records != nullptr) {
81       for (size_t i = 0; i < ssl->d1->sent_records->size(); i++) {
82         if ((*ssl->d1->sent_records)[i].number == number) {
83           sent_record = &(*ssl->d1->sent_records)[i];
84           break;
85         }
86       }
87     }
88     if (sent_record == nullptr) {
89       // We may have sent this record and forgotten it, so this is not an error.
90       continue;
91     }
92 
93     // Mark each message as ACKed.
94     if (sent_record->first_msg == sent_record->last_msg) {
95       ssl->d1->outgoing_messages[sent_record->first_msg].acked.MarkRange(
96           sent_record->first_msg_start, sent_record->last_msg_end);
97     } else {
98       ssl->d1->outgoing_messages[sent_record->first_msg].acked.MarkRange(
99           sent_record->first_msg_start, SIZE_MAX);
100       for (size_t i = size_t{sent_record->first_msg} + 1;
101            i < sent_record->last_msg; i++) {
102         ssl->d1->outgoing_messages[i].acked.MarkRange(0, SIZE_MAX);
103       }
104       if (sent_record->last_msg_end != 0) {
105         ssl->d1->outgoing_messages[sent_record->last_msg].acked.MarkRange(
106             0, sent_record->last_msg_end);
107       }
108     }
109 
110     // Clear the state so we don't bother re-marking the messages next time.
111     sent_record->first_msg = 0;
112     sent_record->first_msg_start = 0;
113     sent_record->last_msg = 0;
114     sent_record->last_msg_end = 0;
115   }
116 
117   // If the outgoing flight is now fully ACKed, we are done retransmitting.
118   if (std::all_of(ssl->d1->outgoing_messages.begin(),
119                   ssl->d1->outgoing_messages.end(),
120                   [](const auto &msg) { return msg.IsFullyAcked(); })) {
121     dtls1_stop_timer(ssl);
122     dtls_clear_outgoing_messages(ssl);
123 
124     // DTLS 1.3 defers the key update to when the message is ACKed.
125     if (ssl->s3->key_update_pending) {
126       if (!tls13_rotate_traffic_key(ssl, evp_aead_seal)) {
127         return ssl_open_record_error;
128       }
129       ssl->s3->key_update_pending = false;
130     }
131 
132     // Check for deferred messages.
133     if (ssl->d1->queued_key_update != QueuedKeyUpdate::kNone) {
134       int request_type =
135           ssl->d1->queued_key_update == QueuedKeyUpdate::kUpdateRequested
136               ? SSL_KEY_UPDATE_REQUESTED
137               : SSL_KEY_UPDATE_NOT_REQUESTED;
138       ssl->d1->queued_key_update = QueuedKeyUpdate::kNone;
139       if (!tls13_add_key_update(ssl, request_type)) {
140         return ssl_open_record_error;
141       }
142     }
143   } else {
144     // We may still be able to drop unused write epochs.
145     dtls_clear_unused_write_epochs(ssl);
146 
147     // TODO(crbug.com/42290594): Schedule a retransmit. The peer will have
148     // waited before sending the ACK, so a partial ACK suggests packet loss.
149   }
150 
151   ssl_do_msg_callback(ssl, /*is_write=*/0, SSL3_RT_ACK, data);
152   return ssl_open_record_discard;
153 }
154 
dtls1_open_app_data(SSL * ssl,Span<uint8_t> * out,size_t * out_consumed,uint8_t * out_alert,Span<uint8_t> in)155 ssl_open_record_t dtls1_open_app_data(SSL *ssl, Span<uint8_t> *out,
156                                       size_t *out_consumed, uint8_t *out_alert,
157                                       Span<uint8_t> in) {
158   assert(!SSL_in_init(ssl));
159 
160   uint8_t type;
161   DTLSRecordNumber record_number;
162   Span<uint8_t> record;
163   auto ret = dtls_open_record(ssl, &type, &record_number, &record, out_consumed,
164                               out_alert, in);
165   if (ret != ssl_open_record_success) {
166     return ret;
167   }
168 
169   if (type == SSL3_RT_HANDSHAKE) {
170     // Process handshake fragments for DTLS 1.3 post-handshake messages.
171     if (ssl_protocol_version(ssl) >= TLS1_3_VERSION) {
172       if (!dtls1_process_handshake_fragments(ssl, out_alert, record_number,
173                                              record)) {
174         return ssl_open_record_error;
175       }
176       return ssl_open_record_discard;
177     }
178 
179     // Parse the first fragment header to determine if this is a pre-CCS or
180     // post-CCS handshake record. DTLS resets handshake message numbers on each
181     // handshake, so renegotiations and retransmissions are ambiguous.
182     //
183     // TODO(crbug.com/42290594): Move this logic into
184     // |dtls1_process_handshake_fragments| and integrate it into DTLS 1.3
185     // retransmit conditions.
186     CBS cbs, body;
187     struct hm_header_st msg_hdr;
188     CBS_init(&cbs, record.data(), record.size());
189     if (!dtls1_parse_fragment(&cbs, &msg_hdr, &body)) {
190       OPENSSL_PUT_ERROR(SSL, SSL_R_BAD_HANDSHAKE_RECORD);
191       *out_alert = SSL_AD_DECODE_ERROR;
192       return ssl_open_record_error;
193     }
194 
195     if (msg_hdr.type == SSL3_MT_FINISHED &&
196         msg_hdr.seq == ssl->d1->handshake_read_seq - 1) {
197       if (!ssl->d1->sending_flight && msg_hdr.frag_off == 0) {
198         // Retransmit our last flight of messages. If the peer sends the second
199         // Finished, they may not have received ours. Only do this for the
200         // first fragment, in case the Finished was fragmented.
201         //
202         // This is not really a timeout, but increment the timeout count so we
203         // eventually give up.
204         ssl->d1->num_timeouts++;
205         ssl->d1->sending_flight = true;
206       }
207       return ssl_open_record_discard;
208     }
209 
210     // Otherwise, this is a pre-CCS handshake message from an unsupported
211     // renegotiation attempt. Fall through to the error path.
212   }
213 
214   if (type == SSL3_RT_ACK) {
215     return dtls1_process_ack(ssl, out_alert, record_number, record);
216   }
217 
218   if (type != SSL3_RT_APPLICATION_DATA) {
219     OPENSSL_PUT_ERROR(SSL, SSL_R_UNEXPECTED_RECORD);
220     *out_alert = SSL_AD_UNEXPECTED_MESSAGE;
221     return ssl_open_record_error;
222   }
223 
224   if (record.empty()) {
225     return ssl_open_record_discard;
226   }
227 
228   *out = record;
229   return ssl_open_record_success;
230 }
231 
dtls1_write_app_data(SSL * ssl,bool * out_needs_handshake,size_t * out_bytes_written,Span<const uint8_t> in)232 int dtls1_write_app_data(SSL *ssl, bool *out_needs_handshake,
233                          size_t *out_bytes_written, Span<const uint8_t> in) {
234   assert(!SSL_in_init(ssl));
235   *out_needs_handshake = false;
236 
237   if (ssl->s3->write_shutdown != ssl_shutdown_none) {
238     OPENSSL_PUT_ERROR(SSL, SSL_R_PROTOCOL_IS_SHUTDOWN);
239     return -1;
240   }
241 
242   // DTLS does not split the input across records.
243   if (in.size() > SSL3_RT_MAX_PLAIN_LENGTH) {
244     OPENSSL_PUT_ERROR(SSL, SSL_R_DTLS_MESSAGE_TOO_BIG);
245     return -1;
246   }
247 
248   if (in.empty()) {
249     *out_bytes_written = 0;
250     return 1;
251   }
252 
253   // TODO(crbug.com/381113363): Use the 0-RTT epoch if writing 0-RTT.
254   int ret = dtls1_write_record(ssl, SSL3_RT_APPLICATION_DATA, in,
255                                ssl->d1->write_epoch.epoch());
256   if (ret <= 0) {
257     return ret;
258   }
259   *out_bytes_written = in.size();
260   return 1;
261 }
262 
dtls1_write_record(SSL * ssl,int type,Span<const uint8_t> in,uint16_t epoch)263 int dtls1_write_record(SSL *ssl, int type, Span<const uint8_t> in,
264                        uint16_t epoch) {
265   SSLBuffer *buf = &ssl->s3->write_buffer;
266   assert(in.size() <= SSL3_RT_MAX_PLAIN_LENGTH);
267   // There should never be a pending write buffer in DTLS. One can't write half
268   // a datagram, so the write buffer is always dropped in
269   // |ssl_write_buffer_flush|.
270   assert(buf->empty());
271 
272   if (in.size() > SSL3_RT_MAX_PLAIN_LENGTH) {
273     OPENSSL_PUT_ERROR(SSL, ERR_R_INTERNAL_ERROR);
274     return -1;
275   }
276 
277   DTLSRecordNumber record_number;
278   size_t ciphertext_len;
279   if (!buf->EnsureCap(dtls_seal_prefix_len(ssl, epoch),
280                       in.size() + SSL_max_seal_overhead(ssl)) ||
281       !dtls_seal_record(ssl, &record_number, buf->remaining().data(),
282                         &ciphertext_len, buf->remaining().size(), type,
283                         in.data(), in.size(), epoch)) {
284     buf->Clear();
285     return -1;
286   }
287   buf->DidWrite(ciphertext_len);
288 
289   int ret = ssl_write_buffer_flush(ssl);
290   if (ret <= 0) {
291     return ret;
292   }
293   return 1;
294 }
295 
dtls1_dispatch_alert(SSL * ssl)296 int dtls1_dispatch_alert(SSL *ssl) {
297   int ret = dtls1_write_record(ssl, SSL3_RT_ALERT, ssl->s3->send_alert,
298                                ssl->d1->write_epoch.epoch());
299   if (ret <= 0) {
300     return ret;
301   }
302   ssl->s3->alert_dispatch = false;
303 
304   // If the alert is fatal, flush the BIO now.
305   if (ssl->s3->send_alert[0] == SSL3_AL_FATAL) {
306     BIO_flush(ssl->wbio.get());
307   }
308 
309   ssl_do_msg_callback(ssl, 1 /* write */, SSL3_RT_ALERT, ssl->s3->send_alert);
310 
311   int alert = (ssl->s3->send_alert[0] << 8) | ssl->s3->send_alert[1];
312   ssl_do_info_callback(ssl, SSL_CB_WRITE_ALERT, alert);
313 
314   return 1;
315 }
316 
317 BSSL_NAMESPACE_END
318