aes_ctr.cc 9.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253
  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.
  4. #include <stddef.h>
  5. #include <stdint.h>
  6. #include <string.h>
  7. #include <array>
  8. #include <memory>
  9. #include "base/check_op.h"
  10. #include "base/containers/span.h"
  11. #include "base/numerics/safe_conversions.h"
  12. #include "base/numerics/safe_math.h"
  13. #include "components/webcrypto/algorithms/aes.h"
  14. #include "components/webcrypto/algorithms/util.h"
  15. #include "components/webcrypto/blink_key_handle.h"
  16. #include "components/webcrypto/status.h"
  17. #include "crypto/openssl_util.h"
  18. #include "third_party/abseil-cpp/absl/numeric/int128.h"
  19. #include "third_party/blink/public/platform/web_crypto_algorithm_params.h"
  20. #include "third_party/boringssl/src/include/openssl/aes.h"
  21. #include "third_party/boringssl/src/include/openssl/cipher.h"
  22. namespace webcrypto {
  23. namespace {
  24. const EVP_CIPHER* GetAESCipherByKeyLength(size_t key_length_bytes) {
  25. // 192-bit AES is intentionally unsupported (http://crbug.com/533699).
  26. switch (key_length_bytes) {
  27. case 16:
  28. return EVP_aes_128_ctr();
  29. case 32:
  30. return EVP_aes_256_ctr();
  31. default:
  32. return nullptr;
  33. }
  34. }
  35. // Encrypts/decrypts given a 128-bit counter.
  36. //
  37. // |output| must have the same length as |input|.
  38. Status AesCtrEncrypt128BitCounter(const EVP_CIPHER* cipher,
  39. base::span<const uint8_t> raw_key,
  40. base::span<const uint8_t> input,
  41. base::span<const uint8_t, 16> counter,
  42. base::span<uint8_t> output) {
  43. DCHECK(cipher);
  44. DCHECK_EQ(input.size(), output.size());
  45. crypto::OpenSSLErrStackTracer err_tracer(FROM_HERE);
  46. bssl::ScopedEVP_CIPHER_CTX context;
  47. if (!EVP_CipherInit_ex(context.get(), cipher, nullptr, raw_key.data(),
  48. counter.data(), ENCRYPT)) {
  49. return Status::OperationError();
  50. }
  51. int output_len = 0;
  52. if (!EVP_CipherUpdate(context.get(), output.data(), &output_len, input.data(),
  53. base::checked_cast<int>(input.size()))) {
  54. return Status::OperationError();
  55. }
  56. int final_output_chunk_len = 0;
  57. if (!EVP_CipherFinal_ex(context.get(), output.data() + output_len,
  58. &final_output_chunk_len)) {
  59. return Status::OperationError();
  60. }
  61. output_len += final_output_chunk_len;
  62. if (static_cast<size_t>(output_len) != input.size())
  63. return Status::ErrorUnexpected();
  64. return Status::Success();
  65. }
  66. // Returns ceil(a/b), where a and b are integers.
  67. template <typename T>
  68. T CeilDiv(T a, T b) {
  69. return a == 0 ? 0 : 1 + (a - 1) / b;
  70. }
  71. // Extracts the counter as a `absl::uint128`. The counter is the rightmost
  72. // `counter_length_bits` of the block, interpreted as a big-endian number.
  73. absl::uint128 GetCounter(base::span<const uint8_t, 16> counter_block,
  74. unsigned int counter_length_bits) {
  75. unsigned int counter_length_remainder_bits = counter_length_bits % 8;
  76. unsigned int byte_length = CeilDiv(counter_length_bits, 8u);
  77. DCHECK_GT(byte_length, 0u);
  78. base::span<const uint8_t> suffix = counter_block.last(byte_length);
  79. absl::uint128 ret = suffix[0];
  80. // The first byte may be partial.
  81. if (counter_length_remainder_bits != 0) {
  82. ret &= ~(0xFF << counter_length_remainder_bits);
  83. }
  84. for (uint8_t b : suffix.subspan(1)) {
  85. ret = (ret << 8) | b;
  86. }
  87. return ret;
  88. }
  89. // Returns a counter block with the counter bits all set all zero.
  90. std::array<uint8_t, AES_BLOCK_SIZE> BlockWithZeroedCounter(
  91. base::span<const uint8_t, AES_BLOCK_SIZE> counter_block,
  92. unsigned int counter_length_bits) {
  93. unsigned int counter_length_bytes = counter_length_bits / 8;
  94. unsigned int counter_length_bits_remainder = counter_length_bits % 8;
  95. std::array<uint8_t, AES_BLOCK_SIZE> new_counter_block;
  96. memcpy(new_counter_block.data(), counter_block.data(), AES_BLOCK_SIZE);
  97. size_t index = new_counter_block.size() - counter_length_bytes;
  98. memset(&new_counter_block.front() + index, 0, counter_length_bytes);
  99. if (counter_length_bits_remainder) {
  100. new_counter_block[index - 1] &= 0xFF << counter_length_bits_remainder;
  101. }
  102. return new_counter_block;
  103. }
  104. // This function does encryption/decryption for AES-CTR (encryption and
  105. // decryption are the same).
  106. //
  107. // BoringSSL's interface for AES-CTR differs from that of WebCrypto. In
  108. // WebCrypto the caller specifies a 16-byte counter block and designates how
  109. // many of the right-most X bits to use as a big-endian counter. Whereas in
  110. // BoringSSL the entire counter block is interpreted as a 128-bit counter.
  111. //
  112. // In AES-CTR, the counter block MUST be unique across all messages that are
  113. // encrypted/decrypted. WebCrypto expects that the counter can start at any
  114. // value, and is therefore permitted to wrap around to zero on overflow.
  115. //
  116. // Some care is taken to fail if the counter wraps back to an earlier value.
  117. // However this protection is only enforced during a *single* call to
  118. // encrypt/decrypt.
  119. Status AesCtrEncryptDecrypt(const blink::WebCryptoAlgorithm& algorithm,
  120. const blink::WebCryptoKey& key,
  121. base::span<const uint8_t> data,
  122. std::vector<uint8_t>* buffer) {
  123. const blink::WebCryptoAesCtrParams* params = algorithm.AesCtrParams();
  124. const std::vector<uint8_t>& raw_key = GetSymmetricKeyData(key);
  125. if (params->Counter().size() != AES_BLOCK_SIZE)
  126. return Status::ErrorIncorrectSizeAesCtrCounter();
  127. base::span<const uint8_t, AES_BLOCK_SIZE> counter_block(
  128. params->Counter().data(), params->Counter().size());
  129. unsigned int counter_length_bits = params->LengthBits();
  130. if (counter_length_bits < 1 || counter_length_bits > 128)
  131. return Status::ErrorInvalidAesCtrCounterLength();
  132. // The output of AES-CTR is the same size as the input. However BoringSSL
  133. // expects buffer sizes as an "int".
  134. base::CheckedNumeric<int> output_max_len = data.size();
  135. if (!output_max_len.IsValid())
  136. return Status::ErrorDataTooLarge();
  137. const EVP_CIPHER* const cipher = GetAESCipherByKeyLength(raw_key.size());
  138. if (!cipher)
  139. return Status::ErrorUnexpected();
  140. buffer->resize(base::ValueOrDieForType<size_t>(output_max_len));
  141. absl::uint128 current_counter =
  142. GetCounter(counter_block, counter_length_bits);
  143. if (counter_length_bits == 128) {
  144. return AesCtrEncrypt128BitCounter(cipher, raw_key, data, counter_block,
  145. *buffer);
  146. }
  147. // The total number of possible counter values is pow(2, counter_length_bits)
  148. absl::uint128 num_counter_values = absl::uint128(1) << counter_length_bits;
  149. // The number of AES blocks needed for encryption/decryption. The counter is
  150. // incremented this many times.
  151. size_t num_output_blocks = CeilDiv(buffer->size(), size_t{AES_BLOCK_SIZE});
  152. // If the counter is going to be incremented more times than there are counter
  153. // values, fail. (Repeating values of the counter block is bad).
  154. if (num_output_blocks > num_counter_values)
  155. return Status::ErrorAesCtrInputTooLongCounterRepeated();
  156. // This is the number of blocks that can be successfully encrypted without
  157. // overflowing the counter. Encrypting the subsequent block will need to
  158. // reset the counter to zero.
  159. absl::uint128 num_blocks_until_reset = num_counter_values - current_counter;
  160. // If the counter can be incremented for the entire input without
  161. // wrapping-around, do it as a single call into BoringSSL.
  162. if (num_blocks_until_reset >= num_output_blocks) {
  163. return AesCtrEncrypt128BitCounter(cipher, raw_key, data, counter_block,
  164. *buffer);
  165. }
  166. // Otherwise the encryption needs to be done in 2 parts. The first part using
  167. // the current counter_block, and the next part resetting the counter portion
  168. // of the block to zero.
  169. // This is guaranteed to fit in an `size_t` because it is bounded by the input
  170. // size.
  171. size_t input_size_part1 =
  172. static_cast<size_t>(num_blocks_until_reset * AES_BLOCK_SIZE);
  173. DCHECK_LT(input_size_part1, data.size());
  174. base::span<uint8_t> output_part1 =
  175. base::make_span(*buffer).first(input_size_part1);
  176. base::span<uint8_t> output_part2 =
  177. base::make_span(*buffer).subspan(input_size_part1);
  178. // Encrypt the first part (before wrap-around).
  179. Status status =
  180. AesCtrEncrypt128BitCounter(cipher, raw_key, data.first(input_size_part1),
  181. counter_block, output_part1);
  182. if (status.IsError())
  183. return status;
  184. // Encrypt the second part (after wrap-around).
  185. std::array<uint8_t, AES_BLOCK_SIZE> counter_block_part2 =
  186. BlockWithZeroedCounter(counter_block, counter_length_bits);
  187. return AesCtrEncrypt128BitCounter(cipher, raw_key,
  188. data.subspan(input_size_part1),
  189. counter_block_part2, output_part2);
  190. }
  191. class AesCtrImplementation : public AesAlgorithm {
  192. public:
  193. AesCtrImplementation() : AesAlgorithm("CTR") {}
  194. Status Encrypt(const blink::WebCryptoAlgorithm& algorithm,
  195. const blink::WebCryptoKey& key,
  196. base::span<const uint8_t> data,
  197. std::vector<uint8_t>* buffer) const override {
  198. return AesCtrEncryptDecrypt(algorithm, key, data, buffer);
  199. }
  200. Status Decrypt(const blink::WebCryptoAlgorithm& algorithm,
  201. const blink::WebCryptoKey& key,
  202. base::span<const uint8_t> data,
  203. std::vector<uint8_t>* buffer) const override {
  204. return AesCtrEncryptDecrypt(algorithm, key, data, buffer);
  205. }
  206. };
  207. } // namespace
  208. std::unique_ptr<AlgorithmImplementation> CreateAesCtrImplementation() {
  209. return std::make_unique<AesCtrImplementation>();
  210. }
  211. } // namespace webcrypto