Coverage Report

Created: 2026-04-15 06:25

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