CTR.h 7.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195
  1. /*
  2. * Copyright (c) 2020, Peter Elliott <pelliott@serenityos.org>
  3. *
  4. * SPDX-License-Identifier: BSD-2-Clause
  5. */
  6. #pragma once
  7. #include <AK/StringBuilder.h>
  8. #include <AK/StringView.h>
  9. #include <LibCrypto/Cipher/Mode/Mode.h>
  10. #ifndef KERNEL
  11. # include <AK/ByteString.h>
  12. #endif
  13. namespace Crypto::Cipher {
  14. /*
  15. * Heads up: CTR is a *family* of modes, because the "counter" function is
  16. * implementation-defined. This makes interoperability a pain in the neurons.
  17. * Here are several contradicting(!) interpretations:
  18. *
  19. * "The counter can be *any function* which produces a sequence which is
  20. * guaranteed not to repeat for a long time, although an actual increment-by-one
  21. * counter is the simplest and most popular."
  22. * The illustrations show that first increment should happen *after* the first
  23. * round. I call this variant BIGINT_INCR_0.
  24. * The AESAVS goes a step further and requires only that "counters" do not
  25. * repeat, leaving the method of counting completely open.
  26. * See: https://en.wikipedia.org/wiki/Block_cipher_mode_of_operation#Counter_(CTR)
  27. * See: https://csrc.nist.gov/csrc/media/projects/cryptographic-algorithm-validation-program/documents/aes/aesavs.pdf
  28. *
  29. * BIGINT_INCR_0 is the behavior of the OpenSSL command "openssl enc -aes-128-ctr",
  30. * and the behavior of CRYPTO_ctr128_encrypt(). OpenSSL is not alone in the
  31. * assumption that BIGINT_INCR_0 is all there is; even some NIST
  32. * specification/survey(?) doesn't consider counting any other way.
  33. * See: https://github.com/openssl/openssl/blob/33388b44b67145af2181b1e9528c381c8ea0d1b6/crypto/modes/ctr128.c#L71
  34. * See: http://www.cryptogrium.com/aes-ctr.html
  35. * See: https://web.archive.org/web/20150226072817/http://csrc.nist.gov/groups/ST/toolkit/BCM/documents/proposedmodes/ctr/ctr-spec.pdf
  36. *
  37. * "[T]he successive counter blocks are derived by applying an incrementing
  38. * function."
  39. * It defines a *family* of functions called "Standard Incrementing Function"
  40. * which only increment the lower-m bits, for some number 0<m<=blocksize.
  41. * The included test vectors suggest that the first increment should happen
  42. * *after* the first round. I call this INT32_INCR_0, or in general INTm_INCR_0.
  43. * This in particular is the behavior of CRYPTO_ctr128_encrypt_ctr32() in OpenSSL.
  44. * See: https://nvlpubs.nist.gov/nistpubs/Legacy/SP/nistspecialpublication800-38a.pdf
  45. * See: https://github.com/openssl/openssl/blob/33388b44b67145af2181b1e9528c381c8ea0d1b6/crypto/modes/ctr128.c#L147
  46. *
  47. * The python package "cryptography" and RFC 3686 (which appears among the
  48. * first online search results when searching for "AES CTR 128 test vector")
  49. * share a peculiar interpretation of CTR mode: the counter is incremented *before*
  50. * the first round. RFC 3686 does not consider any other interpretation. I call
  51. * this variant BIGINT_INCR_1.
  52. * See: https://tools.ietf.org/html/rfc3686.html#section-6
  53. * See: https://cryptography.io/en/latest/development/test-vectors/#symmetric-ciphers
  54. *
  55. * And finally, because the method is left open, a different increment could be
  56. * used, for example little endian, or host endian, or mixed endian. Or any crazy
  57. * LSFR with sufficiently large period. That is the reason for the constant part
  58. * "INCR" in the previous counters.
  59. *
  60. * Due to this plethora of mutually-incompatible counters,
  61. * the method of counting should be a template parameter.
  62. * This currently implements BIGINT_INCR_0, which means perfect
  63. * interoperability with openssl. The test vectors from RFC 3686 just need to be
  64. * incremented by 1.
  65. * TODO: Implement other counters?
  66. */
  67. struct IncrementInplace {
  68. void operator()(Bytes& in) const
  69. {
  70. for (size_t i = in.size(); i > 0;) {
  71. --i;
  72. if (in[i] == (u8)-1) {
  73. in[i] = 0;
  74. } else {
  75. in[i]++;
  76. break;
  77. }
  78. }
  79. }
  80. };
  81. template<typename T, typename IncrementFunctionType = IncrementInplace>
  82. class CTR : public Mode<T> {
  83. public:
  84. constexpr static size_t IVSizeInBits = 128;
  85. virtual ~CTR() = default;
  86. // Must intercept `Intent`, because AES must always be set to
  87. // Encryption, even when decrypting AES-CTR.
  88. // TODO: How to deal with ciphers that take different arguments?
  89. // FIXME: Add back the default intent parameter once clang-11 is the default in GitHub Actions.
  90. // Once added back, remove the parameter where it's constructed in get_random_bytes in Kernel/Security/Random.h.
  91. template<typename KeyType, typename... Args>
  92. explicit constexpr CTR(KeyType const& user_key, size_t key_bits, Intent, Args... args)
  93. : Mode<T>(user_key, key_bits, Intent::Encryption, args...)
  94. {
  95. }
  96. #ifndef KERNEL
  97. virtual ByteString class_name() const override
  98. {
  99. StringBuilder builder;
  100. builder.append(this->cipher().class_name());
  101. builder.append("_CTR"sv);
  102. return builder.to_byte_string();
  103. }
  104. #endif
  105. virtual size_t IV_length() const override
  106. {
  107. return IVSizeInBits / 8;
  108. }
  109. virtual void encrypt(ReadonlyBytes in, Bytes& out, ReadonlyBytes ivec = {}, Bytes* ivec_out = nullptr) override
  110. {
  111. // Our interpretation of "ivec" is what AES-CTR
  112. // would define as nonce + IV + 4 zero bytes.
  113. this->encrypt_or_stream(&in, out, ivec, ivec_out);
  114. }
  115. void key_stream(Bytes& out, Bytes const& ivec = {}, Bytes* ivec_out = nullptr)
  116. {
  117. this->encrypt_or_stream(nullptr, out, ivec, ivec_out);
  118. }
  119. virtual void decrypt(ReadonlyBytes in, Bytes& out, ReadonlyBytes ivec = {}) override
  120. {
  121. // XOR (and thus CTR) is the most symmetric mode.
  122. this->encrypt(in, out, ivec);
  123. }
  124. private:
  125. u8 m_ivec_storage[IVSizeInBits / 8];
  126. typename T::BlockType m_cipher_block {};
  127. protected:
  128. constexpr static IncrementFunctionType increment {};
  129. void encrypt_or_stream(ReadonlyBytes const* in, Bytes& out, ReadonlyBytes ivec, Bytes* ivec_out = nullptr)
  130. {
  131. size_t length;
  132. if (in) {
  133. VERIFY(in->size() <= out.size());
  134. length = in->size();
  135. if (length == 0)
  136. return;
  137. } else {
  138. length = out.size();
  139. }
  140. auto& cipher = this->cipher();
  141. // FIXME: We should have two of these encrypt/decrypt functions that
  142. // we SFINAE out based on whether the Cipher mode needs an ivec
  143. VERIFY(!ivec.is_empty());
  144. VERIFY(ivec.size() >= IV_length());
  145. m_cipher_block.set_padding_mode(cipher.padding_mode());
  146. __builtin_memcpy(m_ivec_storage, ivec.data(), IV_length());
  147. Bytes iv { m_ivec_storage, IV_length() };
  148. size_t offset { 0 };
  149. auto block_size = cipher.block_size();
  150. while (length > 0) {
  151. m_cipher_block.overwrite(iv.slice(0, block_size));
  152. cipher.encrypt_block(m_cipher_block, m_cipher_block);
  153. if (in) {
  154. m_cipher_block.apply_initialization_vector(in->slice(offset));
  155. }
  156. auto write_size = min(block_size, length);
  157. VERIFY(offset + write_size <= out.size());
  158. __builtin_memcpy(out.offset(offset), m_cipher_block.bytes().data(), write_size);
  159. increment(iv);
  160. length -= write_size;
  161. offset += write_size;
  162. }
  163. if (ivec_out)
  164. __builtin_memcpy(ivec_out->data(), iv.data(), min(ivec_out->size(), IV_length()));
  165. }
  166. };
  167. }