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