xref: /aosp_15_r20/external/cronet/third_party/boringssl/src/ssl/dtls_record.cc (revision 6777b5387eb2ff775bb5750e3f5d96f37fb7352b)
1 /* DTLS implementation written by Nagendra Modadugu
2  * ([email protected]) 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  *    [email protected].
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  * ([email protected]).  This product includes software written by Tim
53  * Hudson ([email protected]).
54  *
55  */
56 /* Copyright (C) 1995-1998 Eric Young ([email protected])
57  * All rights reserved.
58  *
59  * This package is an SSL implementation written
60  * by Eric Young ([email protected]).
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 ([email protected]).
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 ([email protected])"
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 ([email protected])"
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 <openssl/bytestring.h>
118 #include <openssl/err.h>
119 
120 #include "internal.h"
121 #include "../crypto/internal.h"
122 
123 
124 BSSL_NAMESPACE_BEGIN
125 
126 // dtls1_bitmap_should_discard returns one if |seq_num| has been seen in
127 // |bitmap| or is stale. Otherwise it returns zero.
dtls1_bitmap_should_discard(DTLS1_BITMAP * bitmap,uint64_t seq_num)128 static bool dtls1_bitmap_should_discard(DTLS1_BITMAP *bitmap,
129                                         uint64_t seq_num) {
130   const size_t kWindowSize = bitmap->map.size();
131 
132   if (seq_num > bitmap->max_seq_num) {
133     return false;
134   }
135   uint64_t idx = bitmap->max_seq_num - seq_num;
136   return idx >= kWindowSize || bitmap->map[idx];
137 }
138 
139 // dtls1_bitmap_record updates |bitmap| to record receipt of sequence number
140 // |seq_num|. It slides the window forward if needed. It is an error to call
141 // this function on a stale sequence number.
dtls1_bitmap_record(DTLS1_BITMAP * bitmap,uint64_t seq_num)142 static void dtls1_bitmap_record(DTLS1_BITMAP *bitmap, uint64_t seq_num) {
143   const size_t kWindowSize = bitmap->map.size();
144 
145   // Shift the window if necessary.
146   if (seq_num > bitmap->max_seq_num) {
147     uint64_t shift = seq_num - bitmap->max_seq_num;
148     if (shift >= kWindowSize) {
149       bitmap->map.reset();
150     } else {
151       bitmap->map <<= shift;
152     }
153     bitmap->max_seq_num = seq_num;
154   }
155 
156   uint64_t idx = bitmap->max_seq_num - seq_num;
157   if (idx < kWindowSize) {
158     bitmap->map[idx] = true;
159   }
160 }
161 
dtls_open_record(SSL * ssl,uint8_t * out_type,Span<uint8_t> * out,size_t * out_consumed,uint8_t * out_alert,Span<uint8_t> in)162 enum ssl_open_record_t dtls_open_record(SSL *ssl, uint8_t *out_type,
163                                         Span<uint8_t> *out,
164                                         size_t *out_consumed,
165                                         uint8_t *out_alert, Span<uint8_t> in) {
166   *out_consumed = 0;
167   if (ssl->s3->read_shutdown == ssl_shutdown_close_notify) {
168     return ssl_open_record_close_notify;
169   }
170 
171   if (in.empty()) {
172     return ssl_open_record_partial;
173   }
174 
175   CBS cbs = CBS(in);
176 
177   // Decode the record.
178   uint8_t type;
179   uint16_t version;
180   uint8_t sequence_bytes[8];
181   CBS body;
182   if (!CBS_get_u8(&cbs, &type) ||
183       !CBS_get_u16(&cbs, &version) ||
184       !CBS_copy_bytes(&cbs, sequence_bytes, sizeof(sequence_bytes)) ||
185       !CBS_get_u16_length_prefixed(&cbs, &body) ||
186       CBS_len(&body) > SSL3_RT_MAX_ENCRYPTED_LENGTH) {
187     // The record header was incomplete or malformed. Drop the entire packet.
188     *out_consumed = in.size();
189     return ssl_open_record_discard;
190   }
191 
192   bool version_ok;
193   if (ssl->s3->aead_read_ctx->is_null_cipher()) {
194     // Only check the first byte. Enforcing beyond that can prevent decoding
195     // version negotiation failure alerts.
196     version_ok = (version >> 8) == DTLS1_VERSION_MAJOR;
197   } else {
198     version_ok = version == ssl->s3->aead_read_ctx->RecordVersion();
199   }
200 
201   if (!version_ok) {
202     // The record header was incomplete or malformed. Drop the entire packet.
203     *out_consumed = in.size();
204     return ssl_open_record_discard;
205   }
206 
207   Span<const uint8_t> header = in.subspan(0, DTLS1_RT_HEADER_LENGTH);
208   ssl_do_msg_callback(ssl, 0 /* read */, SSL3_RT_HEADER, header);
209 
210   uint64_t sequence = CRYPTO_load_u64_be(sequence_bytes);
211   uint16_t epoch = static_cast<uint16_t>(sequence >> 48);
212   if (epoch != ssl->d1->r_epoch ||
213       dtls1_bitmap_should_discard(&ssl->d1->bitmap, sequence)) {
214     // Drop this record. It's from the wrong epoch or is a replay. Note that if
215     // |epoch| is the next epoch, the record could be buffered for later. For
216     // simplicity, drop it and expect retransmit to handle it later; DTLS must
217     // handle packet loss anyway.
218     *out_consumed = in.size() - CBS_len(&cbs);
219     return ssl_open_record_discard;
220   }
221 
222   // discard the body in-place.
223   if (!ssl->s3->aead_read_ctx->Open(
224           out, type, version, sequence, header,
225           MakeSpan(const_cast<uint8_t *>(CBS_data(&body)), CBS_len(&body)))) {
226     // Bad packets are silently dropped in DTLS. See section 4.2.1 of RFC 6347.
227     // Clear the error queue of any errors decryption may have added. Drop the
228     // entire packet as it must not have come from the peer.
229     //
230     // TODO(davidben): This doesn't distinguish malloc failures from encryption
231     // failures.
232     ERR_clear_error();
233     *out_consumed = in.size() - CBS_len(&cbs);
234     return ssl_open_record_discard;
235   }
236   *out_consumed = in.size() - CBS_len(&cbs);
237 
238   // Check the plaintext length.
239   if (out->size() > SSL3_RT_MAX_PLAIN_LENGTH) {
240     OPENSSL_PUT_ERROR(SSL, SSL_R_DATA_LENGTH_TOO_LONG);
241     *out_alert = SSL_AD_RECORD_OVERFLOW;
242     return ssl_open_record_error;
243   }
244 
245   dtls1_bitmap_record(&ssl->d1->bitmap, sequence);
246 
247   // TODO(davidben): Limit the number of empty records as in TLS? This is only
248   // useful if we also limit discarded packets.
249 
250   if (type == SSL3_RT_ALERT) {
251     return ssl_process_alert(ssl, out_alert, *out);
252   }
253 
254   ssl->s3->warning_alert_count = 0;
255 
256   *out_type = type;
257   return ssl_open_record_success;
258 }
259 
get_write_aead(const SSL * ssl,enum dtls1_use_epoch_t use_epoch)260 static const SSLAEADContext *get_write_aead(const SSL *ssl,
261                                             enum dtls1_use_epoch_t use_epoch) {
262   if (use_epoch == dtls1_use_previous_epoch) {
263     assert(ssl->d1->w_epoch >= 1);
264     return ssl->d1->last_aead_write_ctx.get();
265   }
266 
267   return ssl->s3->aead_write_ctx.get();
268 }
269 
dtls_max_seal_overhead(const SSL * ssl,enum dtls1_use_epoch_t use_epoch)270 size_t dtls_max_seal_overhead(const SSL *ssl,
271                               enum dtls1_use_epoch_t use_epoch) {
272   return DTLS1_RT_HEADER_LENGTH + get_write_aead(ssl, use_epoch)->MaxOverhead();
273 }
274 
dtls_seal_prefix_len(const SSL * ssl,enum dtls1_use_epoch_t use_epoch)275 size_t dtls_seal_prefix_len(const SSL *ssl, enum dtls1_use_epoch_t use_epoch) {
276   return DTLS1_RT_HEADER_LENGTH +
277          get_write_aead(ssl, use_epoch)->ExplicitNonceLen();
278 }
279 
dtls_seal_record(SSL * ssl,uint8_t * out,size_t * out_len,size_t max_out,uint8_t type,const uint8_t * in,size_t in_len,enum dtls1_use_epoch_t use_epoch)280 bool dtls_seal_record(SSL *ssl, uint8_t *out, size_t *out_len, size_t max_out,
281                       uint8_t type, const uint8_t *in, size_t in_len,
282                       enum dtls1_use_epoch_t use_epoch) {
283   const size_t prefix = dtls_seal_prefix_len(ssl, use_epoch);
284   if (buffers_alias(in, in_len, out, max_out) &&
285       (max_out < prefix || out + prefix != in)) {
286     OPENSSL_PUT_ERROR(SSL, SSL_R_OUTPUT_ALIASES_INPUT);
287     return false;
288   }
289 
290   // Determine the parameters for the current epoch.
291   uint16_t epoch = ssl->d1->w_epoch;
292   SSLAEADContext *aead = ssl->s3->aead_write_ctx.get();
293   uint64_t *seq = &ssl->s3->write_sequence;
294   if (use_epoch == dtls1_use_previous_epoch) {
295     assert(ssl->d1->w_epoch >= 1);
296     epoch = ssl->d1->w_epoch - 1;
297     aead = ssl->d1->last_aead_write_ctx.get();
298     seq = &ssl->d1->last_write_sequence;
299   }
300 
301   if (max_out < DTLS1_RT_HEADER_LENGTH) {
302     OPENSSL_PUT_ERROR(SSL, SSL_R_BUFFER_TOO_SMALL);
303     return false;
304   }
305 
306   out[0] = type;
307 
308   uint16_t record_version = ssl->s3->aead_write_ctx->RecordVersion();
309   out[1] = record_version >> 8;
310   out[2] = record_version & 0xff;
311 
312   // Ensure the sequence number update does not overflow.
313   const uint64_t kMaxSequenceNumber = (uint64_t{1} << 48) - 1;
314   if (*seq + 1 > kMaxSequenceNumber) {
315     OPENSSL_PUT_ERROR(SSL, ERR_R_OVERFLOW);
316     return false;
317   }
318 
319   uint64_t seq_with_epoch = (uint64_t{epoch} << 48) | *seq;
320   CRYPTO_store_u64_be(&out[3], seq_with_epoch);
321 
322   size_t ciphertext_len;
323   if (!aead->CiphertextLen(&ciphertext_len, in_len, 0)) {
324     OPENSSL_PUT_ERROR(SSL, SSL_R_RECORD_TOO_LARGE);
325     return false;
326   }
327   out[11] = ciphertext_len >> 8;
328   out[12] = ciphertext_len & 0xff;
329   Span<const uint8_t> header = MakeConstSpan(out, DTLS1_RT_HEADER_LENGTH);
330 
331   size_t len_copy;
332   if (!aead->Seal(out + DTLS1_RT_HEADER_LENGTH, &len_copy,
333                   max_out - DTLS1_RT_HEADER_LENGTH, type, record_version,
334                   seq_with_epoch, header, in, in_len)) {
335     return false;
336   }
337   assert(ciphertext_len == len_copy);
338 
339   (*seq)++;
340   *out_len = DTLS1_RT_HEADER_LENGTH + ciphertext_len;
341   ssl_do_msg_callback(ssl, 1 /* write */, SSL3_RT_HEADER, header);
342   return true;
343 }
344 
345 BSSL_NAMESPACE_END
346