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_algorithm_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
> context(
54 EVP_CIPHER_CTX_new());
57 return Status::OperationError();
59 if (!EVP_CipherInit_ex(context
.get(), cipher
, NULL
, raw_key
.bytes(),
60 counter
.bytes(), ENCRYPT
)) {
61 return Status::OperationError();
65 if (!EVP_CipherUpdate(context
.get(), output
, &output_len
, input
.bytes(),
66 input
.byte_length())) {
67 return Status::OperationError();
69 int final_output_chunk_len
= 0;
70 if (!EVP_CipherFinal_ex(context
.get(), output
+ output_len
,
71 &final_output_chunk_len
)) {
72 return Status::OperationError();
75 output_len
+= final_output_chunk_len
;
76 if (static_cast<unsigned int>(output_len
) != input
.byte_length())
77 return Status::ErrorUnexpected();
79 return Status::Success();
82 // Returns ceil(a/b), where a and b are integers.
85 return a
== 0 ? 0 : 1 + (a
- 1) / b
;
88 // Extracts the counter as a BIGNUM. The counter is the rightmost
89 // "counter_length_bits" of the block, interpreted as a big-endian number.
90 crypto::ScopedBIGNUM
GetCounter(const CryptoData
& counter_block
,
91 unsigned int counter_length_bits
) {
92 unsigned int counter_length_remainder_bits
= (counter_length_bits
% 8);
94 // If the counter is a multiple of 8 bits then can call BN_bin2bn() directly.
95 if (counter_length_remainder_bits
== 0) {
96 unsigned int byte_length
= counter_length_bits
/ 8;
97 return crypto::ScopedBIGNUM(BN_bin2bn(
98 counter_block
.bytes() + counter_block
.byte_length() - byte_length
,
102 // Otherwise make a copy of the counter and zero out the topmost bits so
103 // BN_bin2bn() can be called with a byte stream.
104 unsigned int byte_length
= CeilDiv(counter_length_bits
, 8u);
105 std::vector
<uint8_t> counter(
106 counter_block
.bytes() + counter_block
.byte_length() - byte_length
,
107 counter_block
.bytes() + counter_block
.byte_length());
108 counter
[0] &= ~(0xFF << counter_length_remainder_bits
);
110 return crypto::ScopedBIGNUM(
111 BN_bin2bn(vector_as_array(&counter
), counter
.size(), NULL
));
114 // Returns a counter block with the counter bits all set all zero.
115 std::vector
<uint8_t> BlockWithZeroedCounter(const CryptoData
& counter_block
,
116 unsigned int counter_length_bits
) {
117 unsigned int counter_length_bytes
= counter_length_bits
/ 8;
118 unsigned int counter_length_bits_remainder
= counter_length_bits
% 8;
120 std::vector
<uint8_t> new_counter_block(
121 counter_block
.bytes(),
122 counter_block
.bytes() + counter_block
.byte_length());
124 unsigned int index
= new_counter_block
.size() - counter_length_bytes
;
125 memset(&new_counter_block
.front() + index
, 0, counter_length_bytes
);
127 if (counter_length_bits_remainder
) {
128 new_counter_block
[index
- 1] &= 0xFF << counter_length_bits_remainder
;
131 return new_counter_block
;
134 // This function does encryption/decryption for AES-CTR (encryption and
135 // decryption are the same).
137 // BoringSSL's interface for AES-CTR differs from that of WebCrypto. In
138 // WebCrypto the caller specifies a 16-byte counter block and designates how
139 // many of the right-most X bits to use as a big-endian counter. Whereas in
140 // BoringSSL the entire counter block is interpreted as a 128-bit counter.
142 // In AES-CTR, the counter block MUST be unique across all messages that are
143 // encrypted/decrypted. WebCrypto expects that the counter can start at any
144 // value, and is therefore permitted to wrap around to zero on overflow.
146 // Some care is taken to fail if the counter wraps back to an earlier value.
147 // However this protection is only enforced during a *single* call to
149 Status
AesCtrEncryptDecrypt(const blink::WebCryptoAlgorithm
& algorithm
,
150 const blink::WebCryptoKey
& key
,
151 const CryptoData
& data
,
152 std::vector
<uint8_t>* buffer
) {
153 const blink::WebCryptoAesCtrParams
* params
= algorithm
.aesCtrParams();
154 const std::vector
<uint8_t>& raw_key
=
155 SymKeyOpenSsl::Cast(key
)->raw_key_data();
157 if (params
->counter().size() != 16)
158 return Status::ErrorIncorrectSizeAesCtrCounter();
160 unsigned int counter_length_bits
= params
->lengthBits();
161 if (counter_length_bits
< 1 || counter_length_bits
> 128)
162 return Status::ErrorInvalidAesCtrCounterLength();
164 // The output of AES-CTR is the same size as the input. However BoringSSL
165 // expects buffer sizes as an "int".
166 base::CheckedNumeric
<int> output_max_len
= data
.byte_length();
167 if (!output_max_len
.IsValid())
168 return Status::ErrorDataTooLarge();
170 const EVP_CIPHER
* const cipher
= GetAESCipherByKeyLength(raw_key
.size());
172 return Status::ErrorUnexpected();
174 const CryptoData
counter_block(params
->counter());
175 buffer
->resize(output_max_len
.ValueOrDie());
177 // The total number of possible counter values is pow(2, counter_length_bits)
178 crypto::ScopedBIGNUM
num_counter_values(BN_new());
179 if (!BN_lshift(num_counter_values
.get(), BN_value_one(), counter_length_bits
))
180 return Status::ErrorUnexpected();
182 crypto::ScopedBIGNUM current_counter
=
183 GetCounter(counter_block
, counter_length_bits
);
185 // The number of AES blocks needed for encryption/decryption. The counter is
186 // incremented this many times.
187 crypto::ScopedBIGNUM
num_output_blocks(BN_new());
189 num_output_blocks
.get(),
190 CeilDiv(buffer
->size(), static_cast<size_t>(AES_BLOCK_SIZE
)))) {
191 return Status::ErrorUnexpected();
194 // If the counter is going to be incremented more times than there are counter
195 // values, fail. (Repeating values of the counter block is bad).
196 if (BN_cmp(num_output_blocks
.get(), num_counter_values
.get()) > 0)
197 return Status::ErrorAesCtrInputTooLongCounterRepeated();
199 // This is the number of blocks that can be successfully encrypted without
200 // overflowing the counter. Encrypting the subsequent block will need to
201 // reset the counter to zero.
202 crypto::ScopedBIGNUM
num_blocks_until_reset(BN_new());
204 if (!BN_sub(num_blocks_until_reset
.get(), num_counter_values
.get(),
205 current_counter
.get())) {
206 return Status::ErrorUnexpected();
209 // If the counter can be incremented for the entire input without
210 // wrapping-around, do it as a single call into BoringSSL.
211 if (BN_cmp(num_blocks_until_reset
.get(), num_output_blocks
.get()) >= 0) {
212 return AesCtrEncrypt128BitCounter(cipher
, CryptoData(raw_key
), data
,
213 counter_block
, vector_as_array(buffer
));
216 // Otherwise the encryption needs to be done in 2 parts. The first part using
217 // the current counter_block, and the next part resetting the counter portion
218 // of the block to zero.
220 // This is guaranteed to fit in an "unsigned int" because input size in bytes
221 // fits in an "unsigned int".
222 BN_ULONG num_blocks_part1
= BN_get_word(num_blocks_until_reset
.get());
223 BN_ULONG input_size_part1
= num_blocks_part1
* AES_BLOCK_SIZE
;
224 DCHECK_LT(input_size_part1
, data
.byte_length());
226 // Encrypt the first part (before wrap-around).
227 Status status
= AesCtrEncrypt128BitCounter(
228 cipher
, CryptoData(raw_key
), CryptoData(data
.bytes(), input_size_part1
),
229 counter_block
, vector_as_array(buffer
));
230 if (status
.IsError())
233 // Encrypt the second part (after wrap-around).
234 std::vector
<uint8_t> counter_block_part2
=
235 BlockWithZeroedCounter(counter_block
, counter_length_bits
);
237 return AesCtrEncrypt128BitCounter(
238 cipher
, CryptoData(raw_key
),
239 CryptoData(data
.bytes() + input_size_part1
,
240 data
.byte_length() - input_size_part1
),
241 CryptoData(counter_block_part2
),
242 vector_as_array(buffer
) + input_size_part1
);
245 class AesCtrImplementation
: public AesAlgorithm
{
247 AesCtrImplementation() : AesAlgorithm("CTR") {}
249 Status
Encrypt(const blink::WebCryptoAlgorithm
& algorithm
,
250 const blink::WebCryptoKey
& key
,
251 const CryptoData
& data
,
252 std::vector
<uint8_t>* buffer
) const override
{
253 return AesCtrEncryptDecrypt(algorithm
, key
, data
, buffer
);
256 Status
Decrypt(const blink::WebCryptoAlgorithm
& algorithm
,
257 const blink::WebCryptoKey
& key
,
258 const CryptoData
& data
,
259 std::vector
<uint8_t>* buffer
) const override
{
260 return AesCtrEncryptDecrypt(algorithm
, key
, data
, buffer
);
266 AlgorithmImplementation
* CreatePlatformAesCtrImplementation() {
267 return new AesCtrImplementation
;
270 } // namespace webcrypto
272 } // namespace content