1 // Copyright 2014 The Chromium Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
5 #include <openssl/aes.h>
6 #include <openssl/evp.h>
8 #include "base/logging.h"
9 #include "base/macros.h"
10 #include "base/numerics/safe_math.h"
11 #include "base/stl_util.h"
12 #include "content/child/webcrypto/crypto_data.h"
13 #include "content/child/webcrypto/openssl/aes_key_openssl.h"
14 #include "content/child/webcrypto/openssl/key_openssl.h"
15 #include "content/child/webcrypto/openssl/util_openssl.h"
16 #include "content/child/webcrypto/status.h"
17 #include "content/child/webcrypto/webcrypto_util.h"
18 #include "crypto/openssl_util.h"
19 #include "crypto/scoped_openssl_types.h"
20 #include "third_party/WebKit/public/platform/WebCryptoAlgorithmParams.h"
28 const EVP_CIPHER
* GetAESCipherByKeyLength(unsigned int key_length_bytes
) {
29 // BoringSSL does not support 192-bit AES keys.
30 switch (key_length_bytes
) {
32 return EVP_aes_128_ctr();
34 return EVP_aes_256_ctr();
40 // Encrypts/decrypts given a 128-bit counter.
42 // |output| must be a pointer to a buffer which has a length of at least
43 // |input.byte_length()|.
44 Status
AesCtrEncrypt128BitCounter(const EVP_CIPHER
* cipher
,
45 const CryptoData
& raw_key
,
46 const CryptoData
& input
,
47 const CryptoData
& counter
,
50 DCHECK_EQ(16u, counter
.byte_length());
52 crypto::OpenSSLErrStackTracer
err_tracer(FROM_HERE
);
53 crypto::ScopedOpenSSL
<EVP_CIPHER_CTX
, EVP_CIPHER_CTX_free
>::Type
context(
54 EVP_CIPHER_CTX_new());
57 return Status::OperationError();
59 if (!EVP_CipherInit_ex(context
.get(),
65 return Status::OperationError();
69 if (!EVP_CipherUpdate(context
.get(),
73 input
.byte_length())) {
74 return Status::OperationError();
76 int final_output_chunk_len
= 0;
77 if (!EVP_CipherFinal_ex(
78 context
.get(), output
+ output_len
, &final_output_chunk_len
)) {
79 return Status::OperationError();
82 output_len
+= final_output_chunk_len
;
83 if (static_cast<unsigned int>(output_len
) != input
.byte_length())
84 return Status::ErrorUnexpected();
86 return Status::Success();
89 // Returns ceil(a/b), where a and b are integers.
92 return a
== 0 ? 0 : 1 + (a
- 1) / b
;
95 // Extracts the counter as a BIGNUM. The counter is the rightmost
96 // "counter_length_bits" of the block, interpreted as a big-endian number.
97 crypto::ScopedBIGNUM
GetCounter(const CryptoData
& counter_block
,
98 unsigned int counter_length_bits
) {
99 unsigned int counter_length_remainder_bits
= (counter_length_bits
% 8);
101 // If the counter is a multiple of 8 bits then can call BN_bin2bn() directly.
102 if (counter_length_remainder_bits
== 0) {
103 unsigned int byte_length
= counter_length_bits
/ 8;
104 return crypto::ScopedBIGNUM(BN_bin2bn(
105 counter_block
.bytes() + counter_block
.byte_length() - byte_length
,
110 // Otherwise make a copy of the counter and zero out the topmost bits so
111 // BN_bin2bn() can be called with a byte stream.
112 unsigned int byte_length
= CeilDiv(counter_length_bits
, 8u);
113 std::vector
<uint8_t> counter(
114 counter_block
.bytes() + counter_block
.byte_length() - byte_length
,
115 counter_block
.bytes() + counter_block
.byte_length());
116 counter
[0] &= ~(0xFF << counter_length_remainder_bits
);
118 return crypto::ScopedBIGNUM(
119 BN_bin2bn(&counter
.front(), counter
.size(), NULL
));
122 // Returns a counter block with the counter bits all set all zero.
123 std::vector
<uint8_t> BlockWithZeroedCounter(const CryptoData
& counter_block
,
124 unsigned int counter_length_bits
) {
125 unsigned int counter_length_bytes
= counter_length_bits
/ 8;
126 unsigned int counter_length_bits_remainder
= counter_length_bits
% 8;
128 std::vector
<uint8_t> new_counter_block(
129 counter_block
.bytes(),
130 counter_block
.bytes() + counter_block
.byte_length());
132 unsigned int index
= new_counter_block
.size() - counter_length_bytes
;
133 memset(&new_counter_block
.front() + index
, 0, counter_length_bytes
);
135 if (counter_length_bits_remainder
) {
136 new_counter_block
[index
- 1] &= 0xFF << counter_length_bits_remainder
;
139 return new_counter_block
;
142 // This function does encryption/decryption for AES-CTR (encryption and
143 // decryption are the same).
145 // BoringSSL's interface for AES-CTR differs from that of WebCrypto. In
146 // WebCrypto the caller specifies a 16-byte counter block and designates how
147 // many of the right-most X bits to use as a big-endian counter. Whereas in
148 // BoringSSL the entire counter block is interpreted as a 128-bit counter.
150 // In AES-CTR, the counter block MUST be unique across all messages that are
151 // encrypted/decrypted. WebCrypto expects that the counter can start at any
152 // value, and is therefore permitted to wrap around to zero on overflow.
154 // Some care is taken to fail if the counter wraps back to an earlier value.
155 // However this protection is only enforced during a *single* call to
157 Status
AesCtrEncryptDecrypt(const blink::WebCryptoAlgorithm
& algorithm
,
158 const blink::WebCryptoKey
& key
,
159 const CryptoData
& data
,
160 std::vector
<uint8_t>* buffer
) {
161 const blink::WebCryptoAesCtrParams
* params
= algorithm
.aesCtrParams();
162 const std::vector
<uint8_t>& raw_key
=
163 SymKeyOpenSsl::Cast(key
)->raw_key_data();
165 if (params
->counter().size() != 16)
166 return Status::ErrorIncorrectSizeAesCtrCounter();
168 unsigned int counter_length_bits
= params
->lengthBits();
169 if (counter_length_bits
< 1 || counter_length_bits
> 128)
170 return Status::ErrorInvalidAesCtrCounterLength();
172 // The output of AES-CTR is the same size as the input. However BoringSSL
173 // expects buffer sizes as an "int".
174 base::CheckedNumeric
<int> output_max_len
= data
.byte_length();
175 if (!output_max_len
.IsValid())
176 return Status::ErrorDataTooLarge();
178 const EVP_CIPHER
* const cipher
= GetAESCipherByKeyLength(raw_key
.size());
180 return Status::ErrorUnexpected();
182 const CryptoData
counter_block(params
->counter());
183 buffer
->resize(output_max_len
.ValueOrDie());
185 // The total number of possible counter values is pow(2, counter_length_bits)
186 crypto::ScopedBIGNUM
num_counter_values(BN_new());
187 if (!BN_lshift(num_counter_values
.get(), BN_value_one(), counter_length_bits
))
188 return Status::ErrorUnexpected();
190 crypto::ScopedBIGNUM current_counter
=
191 GetCounter(counter_block
, counter_length_bits
);
193 // The number of AES blocks needed for encryption/decryption. The counter is
194 // incremented this many times.
195 crypto::ScopedBIGNUM
num_output_blocks(BN_new());
197 num_output_blocks
.get(),
198 CeilDiv(buffer
->size(), static_cast<size_t>(AES_BLOCK_SIZE
)))) {
199 return Status::ErrorUnexpected();
202 // If the counter is going to be incremented more times than there are counter
203 // values, fail. (Repeating values of the counter block is bad).
204 if (BN_cmp(num_output_blocks
.get(), num_counter_values
.get()) > 0)
205 return Status::ErrorAesCtrInputTooLongCounterRepeated();
207 // This is the number of blocks that can be successfully encrypted without
208 // overflowing the counter. Encrypting the subsequent block will need to
209 // reset the counter to zero.
210 crypto::ScopedBIGNUM
num_blocks_until_reset(BN_new());
212 if (!BN_sub(num_blocks_until_reset
.get(),
213 num_counter_values
.get(),
214 current_counter
.get())) {
215 return Status::ErrorUnexpected();
218 // If the counter can be incremented for the entire input without
219 // wrapping-around, do it as a single call into BoringSSL.
220 if (BN_cmp(num_blocks_until_reset
.get(), num_output_blocks
.get()) >= 0) {
221 return AesCtrEncrypt128BitCounter(cipher
,
225 vector_as_array(buffer
));
228 // Otherwise the encryption needs to be done in 2 parts. The first part using
229 // the current counter_block, and the next part resetting the counter portion
230 // of the block to zero.
232 // This is guaranteed to fit in an "unsigned int" because input size in bytes
233 // fits in an "unsigned int".
234 BN_ULONG num_blocks_part1
= BN_get_word(num_blocks_until_reset
.get());
235 BN_ULONG input_size_part1
= num_blocks_part1
* AES_BLOCK_SIZE
;
236 DCHECK_LT(input_size_part1
, data
.byte_length());
238 // Encrypt the first part (before wrap-around).
240 AesCtrEncrypt128BitCounter(cipher
,
242 CryptoData(data
.bytes(), input_size_part1
),
244 vector_as_array(buffer
));
245 if (status
.IsError())
248 // Encrypt the second part (after wrap-around).
249 std::vector
<uint8_t> counter_block_part2
=
250 BlockWithZeroedCounter(counter_block
, counter_length_bits
);
252 return AesCtrEncrypt128BitCounter(
255 CryptoData(data
.bytes() + input_size_part1
,
256 data
.byte_length() - input_size_part1
),
257 CryptoData(counter_block_part2
),
258 vector_as_array(buffer
) + input_size_part1
);
261 class AesCtrImplementation
: public AesAlgorithm
{
263 AesCtrImplementation() : AesAlgorithm("CTR") {}
265 virtual Status
Encrypt(const blink::WebCryptoAlgorithm
& algorithm
,
266 const blink::WebCryptoKey
& key
,
267 const CryptoData
& data
,
268 std::vector
<uint8_t>* buffer
) const OVERRIDE
{
269 return AesCtrEncryptDecrypt(algorithm
, key
, data
, buffer
);
272 virtual Status
Decrypt(const blink::WebCryptoAlgorithm
& algorithm
,
273 const blink::WebCryptoKey
& key
,
274 const CryptoData
& data
,
275 std::vector
<uint8_t>* buffer
) const OVERRIDE
{
276 return AesCtrEncryptDecrypt(algorithm
, key
, data
, buffer
);
282 AlgorithmImplementation
* CreatePlatformAesCtrImplementation() {
283 return new AesCtrImplementation
;
286 } // namespace webcrypto
288 } // namespace content