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     OPENSSL_PUT_ERROR(SSL, ERR_R_MALLOC_FAILURE);
95     return nullptr;
96   }
97 
98   assert(aead_ctx->ProtocolVersion() == protocol_version);
99 
100   if (!EVP_AEAD_CTX_init_with_direction(
101           aead_ctx->ctx_.get(), aead, enc_key.data(), enc_key.size(),
102           EVP_AEAD_DEFAULT_TAG_LENGTH, direction)) {
103     return nullptr;
104   }
105 
106   assert(EVP_AEAD_nonce_length(aead) <= EVP_AEAD_MAX_NONCE_LENGTH);
107   static_assert(EVP_AEAD_MAX_NONCE_LENGTH < 256,
108                 "variable_nonce_len doesn't fit in uint8_t");
109   aead_ctx->variable_nonce_len_ = (uint8_t)EVP_AEAD_nonce_length(aead);
110   if (mac_key.empty()) {
111     assert(fixed_iv.size() <= sizeof(aead_ctx->fixed_nonce_));
112     OPENSSL_memcpy(aead_ctx->fixed_nonce_, fixed_iv.data(), fixed_iv.size());
113     aead_ctx->fixed_nonce_len_ = fixed_iv.size();
114 
115     if (cipher->algorithm_enc & SSL_CHACHA20POLY1305) {
116       // The fixed nonce into the actual nonce (the sequence number).
117       aead_ctx->xor_fixed_nonce_ = true;
118       aead_ctx->variable_nonce_len_ = 8;
119     } else {
120       // The fixed IV is prepended to the nonce.
121       assert(fixed_iv.size() <= aead_ctx->variable_nonce_len_);
122       aead_ctx->variable_nonce_len_ -= fixed_iv.size();
123     }
124 
125     // AES-GCM uses an explicit nonce.
126     if (cipher->algorithm_enc & (SSL_AES128GCM | SSL_AES256GCM)) {
127       aead_ctx->variable_nonce_included_in_record_ = true;
128     }
129 
130     // The TLS 1.3 construction XORs the fixed nonce into the sequence number
131     // and omits the additional data.
132     if (protocol_version >= TLS1_3_VERSION) {
133       aead_ctx->xor_fixed_nonce_ = true;
134       aead_ctx->variable_nonce_len_ = 8;
135       aead_ctx->variable_nonce_included_in_record_ = false;
136       aead_ctx->ad_is_header_ = true;
137       assert(fixed_iv.size() >= aead_ctx->variable_nonce_len_);
138     }
139   } else {
140     assert(protocol_version < TLS1_3_VERSION);
141     aead_ctx->variable_nonce_included_in_record_ = true;
142     aead_ctx->random_variable_nonce_ = true;
143     aead_ctx->omit_length_in_ad_ = true;
144   }
145 
146   return aead_ctx;
147 }
148 
CreatePlaceholderForQUIC(uint16_t version,const SSL_CIPHER * cipher)149 UniquePtr<SSLAEADContext> SSLAEADContext::CreatePlaceholderForQUIC(
150     uint16_t version, const SSL_CIPHER *cipher) {
151   return MakeUnique<SSLAEADContext>(version, false, cipher);
152 }
153 
SetVersionIfNullCipher(uint16_t version)154 void SSLAEADContext::SetVersionIfNullCipher(uint16_t version) {
155   if (is_null_cipher()) {
156     version_ = version;
157   }
158 }
159 
ProtocolVersion() const160 uint16_t SSLAEADContext::ProtocolVersion() const {
161   uint16_t protocol_version;
162   if(!ssl_protocol_version_from_wire(&protocol_version, version_)) {
163     assert(false);
164     return 0;
165   }
166   return protocol_version;
167 }
168 
RecordVersion() const169 uint16_t SSLAEADContext::RecordVersion() const {
170   if (version_ == 0) {
171     assert(is_null_cipher());
172     return is_dtls_ ? DTLS1_VERSION : TLS1_VERSION;
173   }
174 
175   if (ProtocolVersion() <= TLS1_2_VERSION) {
176     return version_;
177   }
178 
179   return TLS1_2_VERSION;
180 }
181 
ExplicitNonceLen() const182 size_t SSLAEADContext::ExplicitNonceLen() const {
183   if (!FUZZER_MODE && variable_nonce_included_in_record_) {
184     return variable_nonce_len_;
185   }
186   return 0;
187 }
188 
SuffixLen(size_t * out_suffix_len,const size_t in_len,const size_t extra_in_len) const189 bool SSLAEADContext::SuffixLen(size_t *out_suffix_len, const size_t in_len,
190                                const size_t extra_in_len) const {
191   if (is_null_cipher() || FUZZER_MODE) {
192     *out_suffix_len = extra_in_len;
193     return true;
194   }
195   return !!EVP_AEAD_CTX_tag_len(ctx_.get(), out_suffix_len, in_len,
196                                 extra_in_len);
197 }
198 
CiphertextLen(size_t * out_len,const size_t in_len,const size_t extra_in_len) const199 bool SSLAEADContext::CiphertextLen(size_t *out_len, const size_t in_len,
200                                    const size_t extra_in_len) const {
201   size_t len;
202   if (!SuffixLen(&len, in_len, extra_in_len)) {
203     return false;
204   }
205   len += ExplicitNonceLen();
206   len += in_len;
207   if (len < in_len || len >= 0xffff) {
208     OPENSSL_PUT_ERROR(SSL, ERR_R_OVERFLOW);
209     return false;
210   }
211   *out_len = len;
212   return true;
213 }
214 
MaxOverhead() const215 size_t SSLAEADContext::MaxOverhead() const {
216   return ExplicitNonceLen() +
217          (is_null_cipher() || FUZZER_MODE
218               ? 0
219               : EVP_AEAD_max_overhead(EVP_AEAD_CTX_aead(ctx_.get())));
220 }
221 
GetAdditionalData(uint8_t storage[13],uint8_t type,uint16_t record_version,const uint8_t seqnum[8],size_t plaintext_len,Span<const uint8_t> header)222 Span<const uint8_t> SSLAEADContext::GetAdditionalData(
223     uint8_t storage[13], uint8_t type, uint16_t record_version,
224     const uint8_t seqnum[8], size_t plaintext_len, Span<const uint8_t> header) {
225   if (ad_is_header_) {
226     return header;
227   }
228 
229   OPENSSL_memcpy(storage, seqnum, 8);
230   size_t len = 8;
231   storage[len++] = type;
232   storage[len++] = static_cast<uint8_t>((record_version >> 8));
233   storage[len++] = static_cast<uint8_t>(record_version);
234   if (!omit_length_in_ad_) {
235     storage[len++] = static_cast<uint8_t>((plaintext_len >> 8));
236     storage[len++] = static_cast<uint8_t>(plaintext_len);
237   }
238   return MakeConstSpan(storage, len);
239 }
240 
Open(Span<uint8_t> * out,uint8_t type,uint16_t record_version,const uint8_t seqnum[8],Span<const uint8_t> header,Span<uint8_t> in)241 bool SSLAEADContext::Open(Span<uint8_t> *out, uint8_t type,
242                           uint16_t record_version, const uint8_t seqnum[8],
243                           Span<const uint8_t> header, Span<uint8_t> in) {
244   if (is_null_cipher() || FUZZER_MODE) {
245     // Handle the initial NULL cipher.
246     *out = in;
247     return true;
248   }
249 
250   // TLS 1.2 AEADs include the length in the AD and are assumed to have fixed
251   // overhead. Otherwise the parameter is unused.
252   size_t plaintext_len = 0;
253   if (!omit_length_in_ad_) {
254     size_t overhead = MaxOverhead();
255     if (in.size() < overhead) {
256       // Publicly invalid.
257       OPENSSL_PUT_ERROR(SSL, SSL_R_BAD_PACKET_LENGTH);
258       return false;
259     }
260     plaintext_len = in.size() - overhead;
261   }
262 
263   uint8_t ad_storage[13];
264   Span<const uint8_t> ad = GetAdditionalData(ad_storage, type, record_version,
265                                              seqnum, plaintext_len, header);
266 
267   // Assemble the nonce.
268   uint8_t nonce[EVP_AEAD_MAX_NONCE_LENGTH];
269   size_t nonce_len = 0;
270 
271   // Prepend the fixed nonce, or left-pad with zeros if XORing.
272   if (xor_fixed_nonce_) {
273     nonce_len = fixed_nonce_len_ - variable_nonce_len_;
274     OPENSSL_memset(nonce, 0, nonce_len);
275   } else {
276     OPENSSL_memcpy(nonce, fixed_nonce_, fixed_nonce_len_);
277     nonce_len += fixed_nonce_len_;
278   }
279 
280   // Add the variable nonce.
281   if (variable_nonce_included_in_record_) {
282     if (in.size() < variable_nonce_len_) {
283       // Publicly invalid.
284       OPENSSL_PUT_ERROR(SSL, SSL_R_BAD_PACKET_LENGTH);
285       return false;
286     }
287     OPENSSL_memcpy(nonce + nonce_len, in.data(), variable_nonce_len_);
288     in = in.subspan(variable_nonce_len_);
289   } else {
290     assert(variable_nonce_len_ == 8);
291     OPENSSL_memcpy(nonce + nonce_len, seqnum, variable_nonce_len_);
292   }
293   nonce_len += variable_nonce_len_;
294 
295   // XOR the fixed nonce, if necessary.
296   if (xor_fixed_nonce_) {
297     assert(nonce_len == fixed_nonce_len_);
298     for (size_t i = 0; i < fixed_nonce_len_; i++) {
299       nonce[i] ^= fixed_nonce_[i];
300     }
301   }
302 
303   // Decrypt in-place.
304   size_t len;
305   if (!EVP_AEAD_CTX_open(ctx_.get(), in.data(), &len, in.size(), nonce,
306                          nonce_len, in.data(), in.size(), ad.data(),
307                          ad.size())) {
308     return false;
309   }
310   *out = in.subspan(0, len);
311   return true;
312 }
313 
SealScatter(uint8_t * out_prefix,uint8_t * out,uint8_t * out_suffix,uint8_t type,uint16_t record_version,const uint8_t seqnum[8],Span<const uint8_t> header,const uint8_t * in,size_t in_len,const uint8_t * extra_in,size_t extra_in_len)314 bool SSLAEADContext::SealScatter(uint8_t *out_prefix, uint8_t *out,
315                                  uint8_t *out_suffix, uint8_t type,
316                                  uint16_t record_version,
317                                  const uint8_t seqnum[8],
318                                  Span<const uint8_t> header, const uint8_t *in,
319                                  size_t in_len, const uint8_t *extra_in,
320                                  size_t extra_in_len) {
321   const size_t prefix_len = ExplicitNonceLen();
322   size_t suffix_len;
323   if (!SuffixLen(&suffix_len, in_len, extra_in_len)) {
324     OPENSSL_PUT_ERROR(SSL, SSL_R_RECORD_TOO_LARGE);
325     return false;
326   }
327   if ((in != out && buffers_alias(in, in_len, out, in_len)) ||
328       buffers_alias(in, in_len, out_prefix, prefix_len) ||
329       buffers_alias(in, in_len, out_suffix, suffix_len)) {
330     OPENSSL_PUT_ERROR(SSL, SSL_R_OUTPUT_ALIASES_INPUT);
331     return false;
332   }
333 
334   if (is_null_cipher() || FUZZER_MODE) {
335     // Handle the initial NULL cipher.
336     OPENSSL_memmove(out, in, in_len);
337     OPENSSL_memmove(out_suffix, extra_in, extra_in_len);
338     return true;
339   }
340 
341   uint8_t ad_storage[13];
342   Span<const uint8_t> ad = GetAdditionalData(ad_storage, type, record_version,
343                                              seqnum, in_len, header);
344 
345   // Assemble the nonce.
346   uint8_t nonce[EVP_AEAD_MAX_NONCE_LENGTH];
347   size_t nonce_len = 0;
348 
349   // Prepend the fixed nonce, or left-pad with zeros if XORing.
350   if (xor_fixed_nonce_) {
351     nonce_len = fixed_nonce_len_ - variable_nonce_len_;
352     OPENSSL_memset(nonce, 0, nonce_len);
353   } else {
354     OPENSSL_memcpy(nonce, fixed_nonce_, fixed_nonce_len_);
355     nonce_len += fixed_nonce_len_;
356   }
357 
358   // Select the variable nonce.
359   if (random_variable_nonce_) {
360     assert(variable_nonce_included_in_record_);
361     if (!RAND_bytes(nonce + nonce_len, variable_nonce_len_)) {
362       return false;
363     }
364   } else {
365     // When sending we use the sequence number as the variable part of the
366     // nonce.
367     assert(variable_nonce_len_ == 8);
368     OPENSSL_memcpy(nonce + nonce_len, seqnum, variable_nonce_len_);
369   }
370   nonce_len += variable_nonce_len_;
371 
372   // Emit the variable nonce if included in the record.
373   if (variable_nonce_included_in_record_) {
374     assert(!xor_fixed_nonce_);
375     if (buffers_alias(in, in_len, out_prefix, variable_nonce_len_)) {
376       OPENSSL_PUT_ERROR(SSL, SSL_R_OUTPUT_ALIASES_INPUT);
377       return false;
378     }
379     OPENSSL_memcpy(out_prefix, nonce + fixed_nonce_len_,
380                    variable_nonce_len_);
381   }
382 
383   // XOR the fixed nonce, if necessary.
384   if (xor_fixed_nonce_) {
385     assert(nonce_len == fixed_nonce_len_);
386     for (size_t i = 0; i < fixed_nonce_len_; i++) {
387       nonce[i] ^= fixed_nonce_[i];
388     }
389   }
390 
391   size_t written_suffix_len;
392   bool result = !!EVP_AEAD_CTX_seal_scatter(
393       ctx_.get(), out, out_suffix, &written_suffix_len, suffix_len, nonce,
394       nonce_len, in, in_len, extra_in, extra_in_len, ad.data(), ad.size());
395   assert(!result || written_suffix_len == suffix_len);
396   return result;
397 }
398 
Seal(uint8_t * out,size_t * out_len,size_t max_out_len,uint8_t type,uint16_t record_version,const uint8_t seqnum[8],Span<const uint8_t> header,const uint8_t * in,size_t in_len)399 bool SSLAEADContext::Seal(uint8_t *out, size_t *out_len, size_t max_out_len,
400                           uint8_t type, uint16_t record_version,
401                           const uint8_t seqnum[8], Span<const uint8_t> header,
402                           const uint8_t *in, size_t in_len) {
403   const size_t prefix_len = ExplicitNonceLen();
404   size_t suffix_len;
405   if (!SuffixLen(&suffix_len, in_len, 0)) {
406     OPENSSL_PUT_ERROR(SSL, SSL_R_RECORD_TOO_LARGE);
407     return false;
408   }
409   if (in_len + prefix_len < in_len ||
410       in_len + prefix_len + suffix_len < in_len + prefix_len) {
411     OPENSSL_PUT_ERROR(CIPHER, SSL_R_RECORD_TOO_LARGE);
412     return false;
413   }
414   if (in_len + prefix_len + suffix_len > max_out_len) {
415     OPENSSL_PUT_ERROR(SSL, SSL_R_BUFFER_TOO_SMALL);
416     return false;
417   }
418 
419   if (!SealScatter(out, out + prefix_len, out + prefix_len + in_len, type,
420                    record_version, seqnum, header, in, in_len, 0, 0)) {
421     return false;
422   }
423   *out_len = prefix_len + in_len + suffix_len;
424   return true;
425 }
426 
GetIV(const uint8_t ** out_iv,size_t * out_iv_len) const427 bool SSLAEADContext::GetIV(const uint8_t **out_iv, size_t *out_iv_len) const {
428   return !is_null_cipher() &&
429          EVP_AEAD_CTX_get_iv(ctx_.get(), out_iv, out_iv_len);
430 }
431 
432 BSSL_NAMESPACE_END
433