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 <openssl/bytestring.h>
21 #include <openssl/err.h>
22 
23 #include "../crypto/internal.h"
24 #include "internal.h"
25 
26 
27 BSSL_NAMESPACE_BEGIN
28 
ShouldDiscard(uint64_t seq_num) const29 bool DTLSReplayBitmap::ShouldDiscard(uint64_t seq_num) const {
30   const size_t kWindowSize = map_.size();
31 
32   if (seq_num > max_seq_num_) {
33     return false;
34   }
35   uint64_t idx = max_seq_num_ - seq_num;
36   return idx >= kWindowSize || map_[idx];
37 }
38 
Record(uint64_t seq_num)39 void DTLSReplayBitmap::Record(uint64_t seq_num) {
40   const size_t kWindowSize = map_.size();
41 
42   // Shift the window if necessary.
43   if (seq_num > max_seq_num_) {
44     uint64_t shift = seq_num - max_seq_num_;
45     if (shift >= kWindowSize) {
46       map_.reset();
47     } else {
48       map_ <<= shift;
49     }
50     max_seq_num_ = seq_num;
51   }
52 
53   uint64_t idx = max_seq_num_ - seq_num;
54   if (idx < kWindowSize) {
55     map_[idx] = true;
56   }
57 }
58 
dtls_record_version(const SSL * ssl)59 static uint16_t dtls_record_version(const SSL *ssl) {
60   if (ssl->s3->version == 0) {
61     // Before the version is determined, outgoing records use dTLS 1.0 for
62     // historical compatibility requirements.
63     return DTLS1_VERSION;
64   }
65   // DTLS 1.3 freezes the record version at DTLS 1.2. Previous ones use the
66   // version itself.
67   return ssl_protocol_version(ssl) >= TLS1_3_VERSION ? DTLS1_2_VERSION
68                                                      : ssl->s3->version;
69 }
70 
dtls_aead_sequence(const SSL * ssl,DTLSRecordNumber num)71 static uint64_t dtls_aead_sequence(const SSL *ssl, DTLSRecordNumber num) {
72   // DTLS 1.3 uses the sequence number with the AEAD, while DTLS 1.2 uses the
73   // combined value. If the version is not known, the epoch is unencrypted and
74   // the value is ignored.
75   return (ssl->s3->version != 0 && ssl_protocol_version(ssl) >= TLS1_3_VERSION)
76              ? num.sequence()
77              : num.combined();
78 }
79 
80 // reconstruct_epoch finds the largest epoch that ends with the epoch bits from
81 // |wire_epoch| that is less than or equal to |current_epoch|, to match the
82 // epoch reconstruction algorithm described in RFC 9147 section 4.2.2.
reconstruct_epoch(uint8_t wire_epoch,uint16_t current_epoch)83 static uint16_t reconstruct_epoch(uint8_t wire_epoch, uint16_t current_epoch) {
84   uint16_t current_epoch_high = current_epoch & 0xfffc;
85   uint16_t epoch = (wire_epoch & 0x3) | current_epoch_high;
86   if (epoch > current_epoch && current_epoch_high > 0) {
87     epoch -= 0x4;
88   }
89   return epoch;
90 }
91 
reconstruct_seqnum(uint16_t wire_seq,uint64_t seq_mask,uint64_t max_valid_seqnum)92 uint64_t reconstruct_seqnum(uint16_t wire_seq, uint64_t seq_mask,
93                             uint64_t max_valid_seqnum) {
94   // Although DTLS 1.3 can support sequence numbers up to 2^64-1, we continue to
95   // enforce the DTLS 1.2 2^48-1 limit. With a minimal DTLS 1.3 record header (2
96   // bytes), no payload, and 16 byte AEAD overhead, sending 2^48 records would
97   // require 5 petabytes. This allows us to continue to pack a DTLS record
98   // number into an 8-byte structure.
99   assert(max_valid_seqnum <= DTLSRecordNumber::kMaxSequence);
100   assert(seq_mask == 0xff || seq_mask == 0xffff);
101 
102   uint64_t max_seqnum_plus_one = max_valid_seqnum + 1;
103   uint64_t diff = (wire_seq - max_seqnum_plus_one) & seq_mask;
104   uint64_t step = seq_mask + 1;
105   // This addition cannot overflow. It is at most 2^48 + seq_mask. It, however,
106   // may exceed 2^48-1.
107   uint64_t seqnum = max_seqnum_plus_one + diff;
108   bool too_large = seqnum > DTLSRecordNumber::kMaxSequence;
109   // If the diff is larger than half the step size, then the closest seqnum
110   // to max_seqnum_plus_one (in Z_{2^64}) is seqnum minus step instead of
111   // seqnum.
112   bool closer_is_less = diff > step / 2;
113   // Subtracting step from seqnum will cause underflow if seqnum is too small.
114   bool would_underflow = seqnum < step;
115   if (too_large || (closer_is_less && !would_underflow)) {
116     seqnum -= step;
117   }
118   assert(seqnum <= DTLSRecordNumber::kMaxSequence);
119   return seqnum;
120 }
121 
dtls_get_read_epoch(const SSL * ssl,uint16_t epoch)122 DTLSReadEpoch *dtls_get_read_epoch(const SSL *ssl, uint16_t epoch) {
123   if (epoch == ssl->d1->read_epoch.epoch) {
124     return &ssl->d1->read_epoch;
125   }
126   if (ssl->d1->next_read_epoch != nullptr &&
127       epoch == ssl->d1->next_read_epoch->epoch) {
128     return ssl->d1->next_read_epoch.get();
129   }
130   if (ssl->d1->prev_read_epoch != nullptr &&
131       epoch == ssl->d1->prev_read_epoch->epoch.epoch) {
132     return &ssl->d1->prev_read_epoch->epoch;
133   }
134   return nullptr;
135 }
136 
dtls_get_write_epoch(const SSL * ssl,uint16_t epoch)137 DTLSWriteEpoch *dtls_get_write_epoch(const SSL *ssl, uint16_t epoch) {
138   if (ssl->d1->write_epoch.epoch() == epoch) {
139     return &ssl->d1->write_epoch;
140   }
141   for (const auto &e : ssl->d1->extra_write_epochs) {
142     if (e->epoch() == epoch) {
143       return e.get();
144     }
145   }
146   return nullptr;
147 }
148 
cbs_to_writable_bytes(CBS cbs)149 static Span<uint8_t> cbs_to_writable_bytes(CBS cbs) {
150   return Span(const_cast<uint8_t *>(CBS_data(&cbs)), CBS_len(&cbs));
151 }
152 
153 struct ParsedDTLSRecord {
154   // read_epoch will be null if the record is for an unrecognized epoch. In that
155   // case, |number| may be unset.
156   DTLSReadEpoch *read_epoch = nullptr;
157   DTLSRecordNumber number;
158   CBS header, body;
159   uint8_t type = 0;
160   uint16_t version = 0;
161 };
162 
use_dtls13_record_header(const SSL * ssl,uint16_t epoch)163 static bool use_dtls13_record_header(const SSL *ssl, uint16_t epoch) {
164   // Plaintext records in DTLS 1.3 also use the DTLSPlaintext structure for
165   // backwards compatibility.
166   return ssl->s3->version != 0 && ssl_protocol_version(ssl) > TLS1_2_VERSION &&
167          epoch > 0;
168 }
169 
parse_dtls13_record(SSL * ssl,CBS * in,ParsedDTLSRecord * out)170 static bool parse_dtls13_record(SSL *ssl, CBS *in, ParsedDTLSRecord *out) {
171   if (out->type & 0x10) {
172     // Connection ID bit set, which we didn't negotiate.
173     return false;
174   }
175 
176   uint16_t max_epoch = ssl->d1->read_epoch.epoch;
177   if (ssl->d1->next_read_epoch != nullptr) {
178     max_epoch = std::max(max_epoch, ssl->d1->next_read_epoch->epoch);
179   }
180   uint16_t epoch = reconstruct_epoch(out->type, max_epoch);
181   size_t seq_len = (out->type & 0x08) ? 2 : 1;
182   CBS seq_bytes;
183   if (!CBS_get_bytes(in, &seq_bytes, seq_len)) {
184     return false;
185   }
186   if (out->type & 0x04) {
187     // 16-bit length present
188     if (!CBS_get_u16_length_prefixed(in, &out->body)) {
189       return false;
190     }
191   } else {
192     // No length present - the remaining contents are the whole packet.
193     // CBS_get_bytes is used here to advance |in| to the end so that future
194     // code that computes the number of consumed bytes functions correctly.
195     BSSL_CHECK(CBS_get_bytes(in, &out->body, CBS_len(in)));
196   }
197 
198   // Drop the previous read epoch if expired.
199   if (ssl->d1->prev_read_epoch != nullptr &&
200       ssl_ctx_get_current_time(ssl->ctx.get()).tv_sec >
201           ssl->d1->prev_read_epoch->expire) {
202     ssl->d1->prev_read_epoch = nullptr;
203   }
204 
205   // Look up the corresponding epoch. This header form only matches encrypted
206   // DTLS 1.3 epochs.
207   DTLSReadEpoch *read_epoch = dtls_get_read_epoch(ssl, epoch);
208   if (read_epoch != nullptr && use_dtls13_record_header(ssl, epoch)) {
209     out->read_epoch = read_epoch;
210 
211     // Decrypt and reconstruct the sequence number:
212     uint8_t mask[2];
213     if (!read_epoch->rn_encrypter->GenerateMask(mask, out->body)) {
214       // GenerateMask most likely failed because the record body was not long
215       // enough.
216       return false;
217     }
218     // Apply the mask to the sequence number in-place. The header (with the
219     // decrypted sequence number bytes) is used as the additional data for the
220     // AEAD function.
221     auto writable_seq = cbs_to_writable_bytes(seq_bytes);
222     uint64_t seq = 0;
223     for (size_t i = 0; i < writable_seq.size(); i++) {
224       writable_seq[i] ^= mask[i];
225       seq = (seq << 8) | writable_seq[i];
226     }
227     uint64_t full_seq = reconstruct_seqnum(seq, (1 << (seq_len * 8)) - 1,
228                                            read_epoch->bitmap.max_seq_num());
229     out->number = DTLSRecordNumber(epoch, full_seq);
230   }
231 
232   return true;
233 }
234 
parse_dtls12_record(SSL * ssl,CBS * in,ParsedDTLSRecord * out)235 static bool parse_dtls12_record(SSL *ssl, CBS *in, ParsedDTLSRecord *out) {
236   uint64_t epoch_and_seq;
237   if (!CBS_get_u16(in, &out->version) ||  //
238       !CBS_get_u64(in, &epoch_and_seq) ||
239       !CBS_get_u16_length_prefixed(in, &out->body)) {
240     return false;
241   }
242   out->number = DTLSRecordNumber::FromCombined(epoch_and_seq);
243 
244   uint16_t epoch = out->number.epoch();
245   bool version_ok;
246   if (epoch == 0) {
247     // Only check the first byte. Enforcing beyond that can prevent decoding
248     // version negotiation failure alerts.
249     version_ok = (out->version >> 8) == DTLS1_VERSION_MAJOR;
250   } else {
251     version_ok = out->version == dtls_record_version(ssl);
252   }
253   if (!version_ok) {
254     return false;
255   }
256 
257   // Look up the corresponding epoch. In DTLS 1.2, we only need to consider one
258   // epoch.
259   if (epoch == ssl->d1->read_epoch.epoch &&
260       !use_dtls13_record_header(ssl, epoch)) {
261     out->read_epoch = &ssl->d1->read_epoch;
262   }
263 
264   return true;
265 }
266 
parse_dtls_record(SSL * ssl,CBS * cbs,ParsedDTLSRecord * out)267 static bool parse_dtls_record(SSL *ssl, CBS *cbs, ParsedDTLSRecord *out) {
268   CBS copy = *cbs;
269   if (!CBS_get_u8(cbs, &out->type)) {
270     return false;
271   }
272 
273   bool ok;
274   if ((out->type & 0xe0) == 0x20) {
275     ok = parse_dtls13_record(ssl, cbs, out);
276   } else {
277     ok = parse_dtls12_record(ssl, cbs, out);
278   }
279   if (!ok) {
280     return false;
281   }
282 
283   if (CBS_len(&out->body) > SSL3_RT_MAX_ENCRYPTED_LENGTH) {
284     return false;
285   }
286 
287   size_t header_len = CBS_data(&out->body) - CBS_data(&copy);
288   BSSL_CHECK(CBS_get_bytes(&copy, &out->header, header_len));
289   return true;
290 }
291 
dtls_open_record(SSL * ssl,uint8_t * out_type,DTLSRecordNumber * out_number,Span<uint8_t> * out,size_t * out_consumed,uint8_t * out_alert,Span<uint8_t> in)292 enum ssl_open_record_t dtls_open_record(SSL *ssl, uint8_t *out_type,
293                                         DTLSRecordNumber *out_number,
294                                         Span<uint8_t> *out,
295                                         size_t *out_consumed,
296                                         uint8_t *out_alert, Span<uint8_t> in) {
297   *out_consumed = 0;
298   if (ssl->s3->read_shutdown == ssl_shutdown_close_notify) {
299     return ssl_open_record_close_notify;
300   }
301 
302   if (in.empty()) {
303     return ssl_open_record_partial;
304   }
305 
306   CBS cbs(in);
307   ParsedDTLSRecord record;
308   if (!parse_dtls_record(ssl, &cbs, &record)) {
309     // The record header was incomplete or malformed. Drop the entire packet.
310     *out_consumed = in.size();
311     return ssl_open_record_discard;
312   }
313 
314   ssl_do_msg_callback(ssl, 0 /* read */, SSL3_RT_HEADER, record.header);
315 
316   if (record.read_epoch == nullptr ||
317       record.read_epoch->bitmap.ShouldDiscard(record.number.sequence())) {
318     // Drop this record. It's from an unknown epoch or is a replay. Note that if
319     // the record is from next epoch, it could be buffered for later. For
320     // simplicity, drop it and expect retransmit to handle it later; DTLS must
321     // handle packet loss anyway.
322     *out_consumed = in.size() - CBS_len(&cbs);
323     return ssl_open_record_discard;
324   }
325 
326   // Decrypt the body in-place.
327   if (!record.read_epoch->aead->Open(out, record.type, record.version,
328                                      dtls_aead_sequence(ssl, record.number),
329                                      record.header,
330                                      cbs_to_writable_bytes(record.body))) {
331     // Bad packets are silently dropped in DTLS. See section 4.2.1 of RFC 6347.
332     // Clear the error queue of any errors decryption may have added. Drop the
333     // entire packet as it must not have come from the peer.
334     //
335     // TODO(davidben): This doesn't distinguish malloc failures from encryption
336     // failures.
337     ERR_clear_error();
338     *out_consumed = in.size() - CBS_len(&cbs);
339     return ssl_open_record_discard;
340   }
341   *out_consumed = in.size() - CBS_len(&cbs);
342 
343   // DTLS 1.3 hides the record type inside the encrypted data.
344   bool has_padding = !record.read_epoch->aead->is_null_cipher() &&
345                      ssl_protocol_version(ssl) >= TLS1_3_VERSION;
346   // Check the plaintext length.
347   size_t plaintext_limit = SSL3_RT_MAX_PLAIN_LENGTH + (has_padding ? 1 : 0);
348   if (out->size() > plaintext_limit) {
349     OPENSSL_PUT_ERROR(SSL, SSL_R_DATA_LENGTH_TOO_LONG);
350     *out_alert = SSL_AD_RECORD_OVERFLOW;
351     return ssl_open_record_error;
352   }
353 
354   if (has_padding) {
355     do {
356       if (out->empty()) {
357         OPENSSL_PUT_ERROR(SSL, SSL_R_DECRYPTION_FAILED_OR_BAD_RECORD_MAC);
358         *out_alert = SSL_AD_DECRYPT_ERROR;
359         return ssl_open_record_error;
360       }
361       record.type = out->back();
362       *out = out->subspan(0, out->size() - 1);
363     } while (record.type == 0);
364   }
365 
366   record.read_epoch->bitmap.Record(record.number.sequence());
367 
368   // Once we receive a record from the next epoch in DTLS 1.3, it becomes the
369   // current epoch. Also save the previous epoch. This allows us to handle
370   // packet reordering on KeyUpdate, as well as ACK retransmissions of the
371   // Finished flight.
372   if (record.read_epoch == ssl->d1->next_read_epoch.get()) {
373     assert(ssl_protocol_version(ssl) >= TLS1_3_VERSION);
374     auto prev = MakeUnique<DTLSPrevReadEpoch>();
375     if (prev == nullptr) {
376       *out_alert = SSL_AD_INTERNAL_ERROR;
377       return ssl_open_record_error;
378     }
379 
380     // Release the epoch after a timeout.
381     prev->expire = ssl_ctx_get_current_time(ssl->ctx.get()).tv_sec;
382     if (prev->expire >= UINT64_MAX - DTLS_PREV_READ_EPOCH_EXPIRE_SECONDS) {
383       prev->expire = UINT64_MAX;  // Saturate on overflow.
384     } else {
385       prev->expire += DTLS_PREV_READ_EPOCH_EXPIRE_SECONDS;
386     }
387 
388     prev->epoch = std::move(ssl->d1->read_epoch);
389     ssl->d1->prev_read_epoch = std::move(prev);
390     ssl->d1->read_epoch = std::move(*ssl->d1->next_read_epoch);
391     ssl->d1->next_read_epoch = nullptr;
392   }
393 
394   // TODO(davidben): Limit the number of empty records as in TLS? This is only
395   // useful if we also limit discarded packets.
396 
397   if (record.type == SSL3_RT_ALERT) {
398     return ssl_process_alert(ssl, out_alert, *out);
399   }
400 
401   // Reject application data in epochs that do not allow it.
402   if (record.type == SSL3_RT_APPLICATION_DATA) {
403     bool app_data_allowed;
404     if (ssl->s3->version != 0 && ssl_protocol_version(ssl) >= TLS1_3_VERSION) {
405       // Application data is allowed in 0-RTT (epoch 1) and after the handshake
406       // (3 and up).
407       app_data_allowed =
408           record.number.epoch() == 1 || record.number.epoch() >= 3;
409     } else {
410       // Application data is allowed starting epoch 1.
411       app_data_allowed = record.number.epoch() >= 1;
412     }
413     if (!app_data_allowed) {
414       OPENSSL_PUT_ERROR(SSL, SSL_R_UNEXPECTED_RECORD);
415       *out_alert = SSL_AD_UNEXPECTED_MESSAGE;
416       return ssl_open_record_error;
417     }
418   }
419 
420   ssl->s3->warning_alert_count = 0;
421 
422   *out_type = record.type;
423   *out_number = record.number;
424   return ssl_open_record_success;
425 }
426 
dtls_record_header_write_len(const SSL * ssl,uint16_t epoch)427 size_t dtls_record_header_write_len(const SSL *ssl, uint16_t epoch) {
428   if (!use_dtls13_record_header(ssl, epoch)) {
429     return DTLS_PLAINTEXT_RECORD_HEADER_LENGTH;
430   }
431   // The DTLS 1.3 has a variable length record header. We never send Connection
432   // ID, we always send 16-bit sequence numbers, and we send a length. (Length
433   // can be omitted, but only for the last record of a packet. Since we send
434   // multiple records in one packet, it's easier to implement always sending the
435   // length.)
436   return DTLS1_3_RECORD_HEADER_WRITE_LENGTH;
437 }
438 
dtls_max_seal_overhead(const SSL * ssl,uint16_t epoch)439 size_t dtls_max_seal_overhead(const SSL *ssl, uint16_t epoch) {
440   DTLSWriteEpoch *write_epoch = dtls_get_write_epoch(ssl, epoch);
441   if (write_epoch == nullptr) {
442     return 0;
443   }
444   size_t ret = dtls_record_header_write_len(ssl, epoch) +
445                write_epoch->aead->MaxOverhead();
446   if (use_dtls13_record_header(ssl, epoch)) {
447     // Add 1 byte for the encrypted record type.
448     ret++;
449   }
450   return ret;
451 }
452 
dtls_seal_prefix_len(const SSL * ssl,uint16_t epoch)453 size_t dtls_seal_prefix_len(const SSL *ssl, uint16_t epoch) {
454   DTLSWriteEpoch *write_epoch = dtls_get_write_epoch(ssl, epoch);
455   if (write_epoch == nullptr) {
456     return 0;
457   }
458   return dtls_record_header_write_len(ssl, epoch) +
459          write_epoch->aead->ExplicitNonceLen();
460 }
461 
dtls_seal_max_input_len(const SSL * ssl,uint16_t epoch,size_t max_out)462 size_t dtls_seal_max_input_len(const SSL *ssl, uint16_t epoch, size_t max_out) {
463   DTLSWriteEpoch *write_epoch = dtls_get_write_epoch(ssl, epoch);
464   if (write_epoch == nullptr) {
465     return 0;
466   }
467   size_t header_len = dtls_record_header_write_len(ssl, epoch);
468   if (max_out <= header_len) {
469     return 0;
470   }
471   max_out -= header_len;
472   max_out = write_epoch->aead->MaxSealInputLen(max_out);
473   if (max_out > 0 && use_dtls13_record_header(ssl, epoch)) {
474     // Remove 1 byte for the encrypted record type.
475     max_out--;
476   }
477   return max_out;
478 }
479 
dtls_seal_record(SSL * ssl,DTLSRecordNumber * out_number,uint8_t * out,size_t * out_len,size_t max_out,uint8_t type,const uint8_t * in,size_t in_len,uint16_t epoch)480 bool dtls_seal_record(SSL *ssl, DTLSRecordNumber *out_number, uint8_t *out,
481                       size_t *out_len, size_t max_out, uint8_t type,
482                       const uint8_t *in, size_t in_len, uint16_t epoch) {
483   const size_t prefix = dtls_seal_prefix_len(ssl, epoch);
484   if (buffers_alias(in, in_len, out, max_out) &&
485       (max_out < prefix || out + prefix != in)) {
486     OPENSSL_PUT_ERROR(SSL, SSL_R_OUTPUT_ALIASES_INPUT);
487     return false;
488   }
489 
490   // Determine the parameters for the current epoch.
491   DTLSWriteEpoch *write_epoch = dtls_get_write_epoch(ssl, epoch);
492   if (write_epoch == nullptr) {
493     OPENSSL_PUT_ERROR(SSL, ERR_R_INTERNAL_ERROR);
494     return false;
495   }
496 
497   const size_t record_header_len = dtls_record_header_write_len(ssl, epoch);
498 
499   // Ensure the sequence number update does not overflow.
500   DTLSRecordNumber record_number = write_epoch->next_record;
501   if (!record_number.HasNext()) {
502     OPENSSL_PUT_ERROR(SSL, ERR_R_OVERFLOW);
503     return false;
504   }
505 
506   bool dtls13_header = use_dtls13_record_header(ssl, epoch);
507   uint8_t *extra_in = NULL;
508   size_t extra_in_len = 0;
509   if (dtls13_header) {
510     extra_in = &type;
511     extra_in_len = 1;
512   }
513 
514   size_t ciphertext_len;
515   if (!write_epoch->aead->CiphertextLen(&ciphertext_len, in_len,
516                                         extra_in_len)) {
517     OPENSSL_PUT_ERROR(SSL, SSL_R_RECORD_TOO_LARGE);
518     return false;
519   }
520   if (max_out < record_header_len + ciphertext_len) {
521     OPENSSL_PUT_ERROR(SSL, SSL_R_BUFFER_TOO_SMALL);
522     return false;
523   }
524 
525   uint16_t record_version = dtls_record_version(ssl);
526   if (dtls13_header) {
527     // The first byte of the DTLS 1.3 record header has the following format:
528     // 0 1 2 3 4 5 6 7
529     // +-+-+-+-+-+-+-+-+
530     // |0|0|1|C|S|L|E E|
531     // +-+-+-+-+-+-+-+-+
532     //
533     // We set C=0 (no Connection ID), S=1 (16-bit sequence number), L=1 (length
534     // is present), which is a mask of 0x2c. The E E bits are the low-order two
535     // bits of the epoch.
536     //
537     // +-+-+-+-+-+-+-+-+
538     // |0|0|1|0|1|1|E E|
539     // +-+-+-+-+-+-+-+-+
540     out[0] = 0x2c | (epoch & 0x3);
541     // We always use a two-byte sequence number. A one-byte sequence number
542     // would require coordinating with the application on ACK feedback to know
543     // that the peer is not too far behind.
544     CRYPTO_store_u16_be(out + 1, write_epoch->next_record.sequence());
545     // TODO(crbug.com/42290594): When we know the record is last in the packet,
546     // omit the length.
547     CRYPTO_store_u16_be(out + 3, ciphertext_len);
548   } else {
549     out[0] = type;
550     CRYPTO_store_u16_be(out + 1, record_version);
551     CRYPTO_store_u64_be(out + 3, record_number.combined());
552     CRYPTO_store_u16_be(out + 11, ciphertext_len);
553   }
554   Span<const uint8_t> header(out, record_header_len);
555 
556   if (!write_epoch->aead->SealScatter(
557           out + record_header_len, out + prefix, out + prefix + in_len, type,
558           record_version, dtls_aead_sequence(ssl, record_number), header, in,
559           in_len, extra_in, extra_in_len)) {
560     return false;
561   }
562 
563   // Perform record number encryption (RFC 9147 section 4.2.3).
564   if (dtls13_header) {
565     // Record number encryption uses bytes from the ciphertext as a sample to
566     // generate the mask used for encryption. For simplicity, pass in the whole
567     // ciphertext as the sample - GenerateRecordNumberMask will read only what
568     // it needs (and error if |sample| is too short).
569     Span<const uint8_t> sample(out + record_header_len, ciphertext_len);
570     uint8_t mask[2];
571     if (!write_epoch->rn_encrypter->GenerateMask(mask, sample)) {
572       return false;
573     }
574     out[1] ^= mask[0];
575     out[2] ^= mask[1];
576   }
577 
578   *out_number = record_number;
579   write_epoch->next_record = record_number.Next();
580   *out_len = record_header_len + ciphertext_len;
581   ssl_do_msg_callback(ssl, 1 /* write */, SSL3_RT_HEADER, header);
582   return true;
583 }
584 
585 BSSL_NAMESPACE_END
586