xref: /aosp_15_r20/external/boringssl/src/ssl/ssl_aead_ctx.cc (revision 8fb009dc861624b67b6cdb62ea21f0f22d0c584b)
1 /* Copyright (c) 2015, Google Inc.
2  *
3  * Permission to use, copy, modify, and/or distribute this software for any
4  * purpose with or without fee is hereby granted, provided that the above
5  * copyright notice and this permission notice appear in all copies.
6  *
7  * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
8  * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
9  * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY
10  * SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
11  * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION
12  * OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN
13  * CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. */
14 
15 #include <openssl/ssl.h>
16 
17 #include <assert.h>
18 #include <string.h>
19 
20 #include <openssl/aead.h>
21 #include <openssl/err.h>
22 #include <openssl/rand.h>
23 
24 #include "../crypto/internal.h"
25 #include "internal.h"
26 
27 
28 #if defined(BORINGSSL_UNSAFE_FUZZER_MODE)
29 #define FUZZER_MODE true
30 #else
31 #define FUZZER_MODE false
32 #endif
33 
34 BSSL_NAMESPACE_BEGIN
35 
SSLAEADContext(uint16_t version_arg,bool is_dtls_arg,const SSL_CIPHER * cipher_arg)36 SSLAEADContext::SSLAEADContext(uint16_t version_arg, bool is_dtls_arg,
37                                const SSL_CIPHER *cipher_arg)
38     : cipher_(cipher_arg),
39       version_(version_arg),
40       is_dtls_(is_dtls_arg),
41       variable_nonce_included_in_record_(false),
42       random_variable_nonce_(false),
43       xor_fixed_nonce_(false),
44       omit_length_in_ad_(false),
45       ad_is_header_(false) {
46   OPENSSL_memset(fixed_nonce_, 0, sizeof(fixed_nonce_));
47 }
48 
~SSLAEADContext()49 SSLAEADContext::~SSLAEADContext() {}
50 
CreateNullCipher(bool is_dtls)51 UniquePtr<SSLAEADContext> SSLAEADContext::CreateNullCipher(bool is_dtls) {
52   return MakeUnique<SSLAEADContext>(0 /* version */, is_dtls,
53                                     nullptr /* cipher */);
54 }
55 
Create(enum evp_aead_direction_t direction,uint16_t version,bool is_dtls,const SSL_CIPHER * cipher,Span<const uint8_t> enc_key,Span<const uint8_t> mac_key,Span<const uint8_t> fixed_iv)56 UniquePtr<SSLAEADContext> SSLAEADContext::Create(
57     enum evp_aead_direction_t direction, uint16_t version, bool is_dtls,
58     const SSL_CIPHER *cipher, Span<const uint8_t> enc_key,
59     Span<const uint8_t> mac_key, Span<const uint8_t> fixed_iv) {
60   const EVP_AEAD *aead;
61   uint16_t protocol_version;
62   size_t expected_mac_key_len, expected_fixed_iv_len;
63   if (!ssl_protocol_version_from_wire(&protocol_version, version) ||
64       !ssl_cipher_get_evp_aead(&aead, &expected_mac_key_len,
65                                &expected_fixed_iv_len, cipher, protocol_version,
66                                is_dtls) ||
67       // Ensure the caller returned correct key sizes.
68       expected_fixed_iv_len != fixed_iv.size() ||
69       expected_mac_key_len != mac_key.size()) {
70     OPENSSL_PUT_ERROR(SSL, ERR_R_INTERNAL_ERROR);
71     return nullptr;
72   }
73 
74   uint8_t merged_key[EVP_AEAD_MAX_KEY_LENGTH];
75   if (!mac_key.empty()) {
76     // This is a "stateful" AEAD (for compatibility with pre-AEAD cipher
77     // suites).
78     if (mac_key.size() + enc_key.size() + fixed_iv.size() >
79         sizeof(merged_key)) {
80       OPENSSL_PUT_ERROR(SSL, ERR_R_INTERNAL_ERROR);
81       return nullptr;
82     }
83     OPENSSL_memcpy(merged_key, mac_key.data(), mac_key.size());
84     OPENSSL_memcpy(merged_key + mac_key.size(), enc_key.data(), enc_key.size());
85     OPENSSL_memcpy(merged_key + mac_key.size() + enc_key.size(),
86                    fixed_iv.data(), fixed_iv.size());
87     enc_key = MakeConstSpan(merged_key,
88                             enc_key.size() + mac_key.size() + fixed_iv.size());
89   }
90 
91   UniquePtr<SSLAEADContext> aead_ctx =
92       MakeUnique<SSLAEADContext>(version, is_dtls, cipher);
93   if (!aead_ctx) {
94     return nullptr;
95   }
96 
97   assert(aead_ctx->ProtocolVersion() == protocol_version);
98 
99   if (!EVP_AEAD_CTX_init_with_direction(
100           aead_ctx->ctx_.get(), aead, enc_key.data(), enc_key.size(),
101           EVP_AEAD_DEFAULT_TAG_LENGTH, direction)) {
102     return nullptr;
103   }
104 
105   assert(EVP_AEAD_nonce_length(aead) <= EVP_AEAD_MAX_NONCE_LENGTH);
106   static_assert(EVP_AEAD_MAX_NONCE_LENGTH < 256,
107                 "variable_nonce_len doesn't fit in uint8_t");
108   aead_ctx->variable_nonce_len_ = (uint8_t)EVP_AEAD_nonce_length(aead);
109   if (mac_key.empty()) {
110     assert(fixed_iv.size() <= sizeof(aead_ctx->fixed_nonce_));
111     OPENSSL_memcpy(aead_ctx->fixed_nonce_, fixed_iv.data(), fixed_iv.size());
112     aead_ctx->fixed_nonce_len_ = fixed_iv.size();
113 
114     if (cipher->algorithm_enc & SSL_CHACHA20POLY1305) {
115       // The fixed nonce into the actual nonce (the sequence number).
116       aead_ctx->xor_fixed_nonce_ = true;
117       aead_ctx->variable_nonce_len_ = 8;
118     } else {
119       // The fixed IV is prepended to the nonce.
120       assert(fixed_iv.size() <= aead_ctx->variable_nonce_len_);
121       aead_ctx->variable_nonce_len_ -= fixed_iv.size();
122     }
123 
124     // AES-GCM uses an explicit nonce.
125     if (cipher->algorithm_enc & (SSL_AES128GCM | SSL_AES256GCM)) {
126       aead_ctx->variable_nonce_included_in_record_ = true;
127     }
128 
129     // The TLS 1.3 construction XORs the fixed nonce into the sequence number
130     // and omits the additional data.
131     if (protocol_version >= TLS1_3_VERSION) {
132       aead_ctx->xor_fixed_nonce_ = true;
133       aead_ctx->variable_nonce_len_ = 8;
134       aead_ctx->variable_nonce_included_in_record_ = false;
135       aead_ctx->ad_is_header_ = true;
136       assert(fixed_iv.size() >= aead_ctx->variable_nonce_len_);
137     }
138   } else {
139     assert(protocol_version < TLS1_3_VERSION);
140     aead_ctx->variable_nonce_included_in_record_ = true;
141     aead_ctx->random_variable_nonce_ = true;
142     aead_ctx->omit_length_in_ad_ = true;
143   }
144 
145   return aead_ctx;
146 }
147 
CreatePlaceholderForQUIC(uint16_t version,const SSL_CIPHER * cipher)148 UniquePtr<SSLAEADContext> SSLAEADContext::CreatePlaceholderForQUIC(
149     uint16_t version, const SSL_CIPHER *cipher) {
150   return MakeUnique<SSLAEADContext>(version, false, cipher);
151 }
152 
SetVersionIfNullCipher(uint16_t version)153 void SSLAEADContext::SetVersionIfNullCipher(uint16_t version) {
154   if (is_null_cipher()) {
155     version_ = version;
156   }
157 }
158 
ProtocolVersion() const159 uint16_t SSLAEADContext::ProtocolVersion() const {
160   uint16_t protocol_version;
161   if(!ssl_protocol_version_from_wire(&protocol_version, version_)) {
162     assert(false);
163     return 0;
164   }
165   return protocol_version;
166 }
167 
RecordVersion() const168 uint16_t SSLAEADContext::RecordVersion() const {
169   if (version_ == 0) {
170     assert(is_null_cipher());
171     return is_dtls_ ? DTLS1_VERSION : TLS1_VERSION;
172   }
173 
174   if (ProtocolVersion() <= TLS1_2_VERSION) {
175     return version_;
176   }
177 
178   return TLS1_2_VERSION;
179 }
180 
ExplicitNonceLen() const181 size_t SSLAEADContext::ExplicitNonceLen() const {
182   if (!FUZZER_MODE && variable_nonce_included_in_record_) {
183     return variable_nonce_len_;
184   }
185   return 0;
186 }
187 
SuffixLen(size_t * out_suffix_len,const size_t in_len,const size_t extra_in_len) const188 bool SSLAEADContext::SuffixLen(size_t *out_suffix_len, const size_t in_len,
189                                const size_t extra_in_len) const {
190   if (is_null_cipher() || FUZZER_MODE) {
191     *out_suffix_len = extra_in_len;
192     return true;
193   }
194   return !!EVP_AEAD_CTX_tag_len(ctx_.get(), out_suffix_len, in_len,
195                                 extra_in_len);
196 }
197 
CiphertextLen(size_t * out_len,const size_t in_len,const size_t extra_in_len) const198 bool SSLAEADContext::CiphertextLen(size_t *out_len, const size_t in_len,
199                                    const size_t extra_in_len) const {
200   size_t len;
201   if (!SuffixLen(&len, in_len, extra_in_len)) {
202     return false;
203   }
204   len += ExplicitNonceLen();
205   len += in_len;
206   if (len < in_len || len >= 0xffff) {
207     OPENSSL_PUT_ERROR(SSL, ERR_R_OVERFLOW);
208     return false;
209   }
210   *out_len = len;
211   return true;
212 }
213 
MaxOverhead() const214 size_t SSLAEADContext::MaxOverhead() const {
215   return ExplicitNonceLen() +
216          (is_null_cipher() || FUZZER_MODE
217               ? 0
218               : EVP_AEAD_max_overhead(EVP_AEAD_CTX_aead(ctx_.get())));
219 }
220 
GetAdditionalData(uint8_t storage[13],uint8_t type,uint16_t record_version,uint64_t seqnum,size_t plaintext_len,Span<const uint8_t> header)221 Span<const uint8_t> SSLAEADContext::GetAdditionalData(
222     uint8_t storage[13], uint8_t type, uint16_t record_version, uint64_t seqnum,
223     size_t plaintext_len, Span<const uint8_t> header) {
224   if (ad_is_header_) {
225     return header;
226   }
227 
228   CRYPTO_store_u64_be(storage, seqnum);
229   size_t len = 8;
230   storage[len++] = type;
231   storage[len++] = static_cast<uint8_t>((record_version >> 8));
232   storage[len++] = static_cast<uint8_t>(record_version);
233   if (!omit_length_in_ad_) {
234     storage[len++] = static_cast<uint8_t>((plaintext_len >> 8));
235     storage[len++] = static_cast<uint8_t>(plaintext_len);
236   }
237   return MakeConstSpan(storage, len);
238 }
239 
Open(Span<uint8_t> * out,uint8_t type,uint16_t record_version,uint64_t seqnum,Span<const uint8_t> header,Span<uint8_t> in)240 bool SSLAEADContext::Open(Span<uint8_t> *out, uint8_t type,
241                           uint16_t record_version, uint64_t seqnum,
242                           Span<const uint8_t> header, Span<uint8_t> in) {
243   if (is_null_cipher() || FUZZER_MODE) {
244     // Handle the initial NULL cipher.
245     *out = in;
246     return true;
247   }
248 
249   // TLS 1.2 AEADs include the length in the AD and are assumed to have fixed
250   // overhead. Otherwise the parameter is unused.
251   size_t plaintext_len = 0;
252   if (!omit_length_in_ad_) {
253     size_t overhead = MaxOverhead();
254     if (in.size() < overhead) {
255       // Publicly invalid.
256       OPENSSL_PUT_ERROR(SSL, SSL_R_BAD_PACKET_LENGTH);
257       return false;
258     }
259     plaintext_len = in.size() - overhead;
260   }
261 
262   uint8_t ad_storage[13];
263   Span<const uint8_t> ad = GetAdditionalData(ad_storage, type, record_version,
264                                              seqnum, plaintext_len, header);
265 
266   // Assemble the nonce.
267   uint8_t nonce[EVP_AEAD_MAX_NONCE_LENGTH];
268   size_t nonce_len = 0;
269 
270   // Prepend the fixed nonce, or left-pad with zeros if XORing.
271   if (xor_fixed_nonce_) {
272     nonce_len = fixed_nonce_len_ - variable_nonce_len_;
273     OPENSSL_memset(nonce, 0, nonce_len);
274   } else {
275     OPENSSL_memcpy(nonce, fixed_nonce_, fixed_nonce_len_);
276     nonce_len += fixed_nonce_len_;
277   }
278 
279   // Add the variable nonce.
280   if (variable_nonce_included_in_record_) {
281     if (in.size() < variable_nonce_len_) {
282       // Publicly invalid.
283       OPENSSL_PUT_ERROR(SSL, SSL_R_BAD_PACKET_LENGTH);
284       return false;
285     }
286     OPENSSL_memcpy(nonce + nonce_len, in.data(), variable_nonce_len_);
287     in = in.subspan(variable_nonce_len_);
288   } else {
289     assert(variable_nonce_len_ == 8);
290     CRYPTO_store_u64_be(nonce + nonce_len, seqnum);
291   }
292   nonce_len += variable_nonce_len_;
293 
294   // XOR the fixed nonce, if necessary.
295   if (xor_fixed_nonce_) {
296     assert(nonce_len == fixed_nonce_len_);
297     for (size_t i = 0; i < fixed_nonce_len_; i++) {
298       nonce[i] ^= fixed_nonce_[i];
299     }
300   }
301 
302   // Decrypt in-place.
303   size_t len;
304   if (!EVP_AEAD_CTX_open(ctx_.get(), in.data(), &len, in.size(), nonce,
305                          nonce_len, in.data(), in.size(), ad.data(),
306                          ad.size())) {
307     return false;
308   }
309   *out = in.subspan(0, len);
310   return true;
311 }
312 
SealScatter(uint8_t * out_prefix,uint8_t * out,uint8_t * out_suffix,uint8_t type,uint16_t record_version,uint64_t seqnum,Span<const uint8_t> header,const uint8_t * in,size_t in_len,const uint8_t * extra_in,size_t extra_in_len)313 bool SSLAEADContext::SealScatter(uint8_t *out_prefix, uint8_t *out,
314                                  uint8_t *out_suffix, uint8_t type,
315                                  uint16_t record_version, uint64_t seqnum,
316                                  Span<const uint8_t> header, const uint8_t *in,
317                                  size_t in_len, const uint8_t *extra_in,
318                                  size_t extra_in_len) {
319   const size_t prefix_len = ExplicitNonceLen();
320   size_t suffix_len;
321   if (!SuffixLen(&suffix_len, in_len, extra_in_len)) {
322     OPENSSL_PUT_ERROR(SSL, SSL_R_RECORD_TOO_LARGE);
323     return false;
324   }
325   if ((in != out && buffers_alias(in, in_len, out, in_len)) ||
326       buffers_alias(in, in_len, out_prefix, prefix_len) ||
327       buffers_alias(in, in_len, out_suffix, suffix_len)) {
328     OPENSSL_PUT_ERROR(SSL, SSL_R_OUTPUT_ALIASES_INPUT);
329     return false;
330   }
331 
332   if (is_null_cipher() || FUZZER_MODE) {
333     // Handle the initial NULL cipher.
334     OPENSSL_memmove(out, in, in_len);
335     OPENSSL_memmove(out_suffix, extra_in, extra_in_len);
336     return true;
337   }
338 
339   uint8_t ad_storage[13];
340   Span<const uint8_t> ad = GetAdditionalData(ad_storage, type, record_version,
341                                              seqnum, in_len, header);
342 
343   // Assemble the nonce.
344   uint8_t nonce[EVP_AEAD_MAX_NONCE_LENGTH];
345   size_t nonce_len = 0;
346 
347   // Prepend the fixed nonce, or left-pad with zeros if XORing.
348   if (xor_fixed_nonce_) {
349     nonce_len = fixed_nonce_len_ - variable_nonce_len_;
350     OPENSSL_memset(nonce, 0, nonce_len);
351   } else {
352     OPENSSL_memcpy(nonce, fixed_nonce_, fixed_nonce_len_);
353     nonce_len += fixed_nonce_len_;
354   }
355 
356   // Select the variable nonce.
357   if (random_variable_nonce_) {
358     assert(variable_nonce_included_in_record_);
359     if (!RAND_bytes(nonce + nonce_len, variable_nonce_len_)) {
360       return false;
361     }
362   } else {
363     // When sending we use the sequence number as the variable part of the
364     // nonce.
365     assert(variable_nonce_len_ == 8);
366     CRYPTO_store_u64_be(nonce + nonce_len, seqnum);
367   }
368   nonce_len += variable_nonce_len_;
369 
370   // Emit the variable nonce if included in the record.
371   if (variable_nonce_included_in_record_) {
372     assert(!xor_fixed_nonce_);
373     if (buffers_alias(in, in_len, out_prefix, variable_nonce_len_)) {
374       OPENSSL_PUT_ERROR(SSL, SSL_R_OUTPUT_ALIASES_INPUT);
375       return false;
376     }
377     OPENSSL_memcpy(out_prefix, nonce + fixed_nonce_len_,
378                    variable_nonce_len_);
379   }
380 
381   // XOR the fixed nonce, if necessary.
382   if (xor_fixed_nonce_) {
383     assert(nonce_len == fixed_nonce_len_);
384     for (size_t i = 0; i < fixed_nonce_len_; i++) {
385       nonce[i] ^= fixed_nonce_[i];
386     }
387   }
388 
389   size_t written_suffix_len;
390   bool result = !!EVP_AEAD_CTX_seal_scatter(
391       ctx_.get(), out, out_suffix, &written_suffix_len, suffix_len, nonce,
392       nonce_len, in, in_len, extra_in, extra_in_len, ad.data(), ad.size());
393   assert(!result || written_suffix_len == suffix_len);
394   return result;
395 }
396 
Seal(uint8_t * out,size_t * out_len,size_t max_out_len,uint8_t type,uint16_t record_version,uint64_t seqnum,Span<const uint8_t> header,const uint8_t * in,size_t in_len)397 bool SSLAEADContext::Seal(uint8_t *out, size_t *out_len, size_t max_out_len,
398                           uint8_t type, uint16_t record_version,
399                           uint64_t seqnum, Span<const uint8_t> header,
400                           const uint8_t *in, size_t in_len) {
401   const size_t prefix_len = ExplicitNonceLen();
402   size_t suffix_len;
403   if (!SuffixLen(&suffix_len, in_len, 0)) {
404     OPENSSL_PUT_ERROR(SSL, SSL_R_RECORD_TOO_LARGE);
405     return false;
406   }
407   if (in_len + prefix_len < in_len ||
408       in_len + prefix_len + suffix_len < in_len + prefix_len) {
409     OPENSSL_PUT_ERROR(CIPHER, SSL_R_RECORD_TOO_LARGE);
410     return false;
411   }
412   if (in_len + prefix_len + suffix_len > max_out_len) {
413     OPENSSL_PUT_ERROR(SSL, SSL_R_BUFFER_TOO_SMALL);
414     return false;
415   }
416 
417   if (!SealScatter(out, out + prefix_len, out + prefix_len + in_len, type,
418                    record_version, seqnum, header, in, in_len, 0, 0)) {
419     return false;
420   }
421   *out_len = prefix_len + in_len + suffix_len;
422   return true;
423 }
424 
GetIV(const uint8_t ** out_iv,size_t * out_iv_len) const425 bool SSLAEADContext::GetIV(const uint8_t **out_iv, size_t *out_iv_len) const {
426   return !is_null_cipher() &&
427          EVP_AEAD_CTX_get_iv(ctx_.get(), out_iv, out_iv_len);
428 }
429 
430 BSSL_NAMESPACE_END
431