ecdsa.cc 9.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263
  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 <memory>
  7. #include "base/containers/span.h"
  8. #include "components/webcrypto/algorithm_implementation.h"
  9. #include "components/webcrypto/algorithms/ec.h"
  10. #include "components/webcrypto/algorithms/util.h"
  11. #include "components/webcrypto/blink_key_handle.h"
  12. #include "components/webcrypto/generate_key_result.h"
  13. #include "components/webcrypto/status.h"
  14. #include "crypto/openssl_util.h"
  15. #include "crypto/secure_util.h"
  16. #include "third_party/blink/public/platform/web_crypto_algorithm_params.h"
  17. #include "third_party/blink/public/platform/web_crypto_key.h"
  18. #include "third_party/blink/public/platform/web_crypto_key_algorithm.h"
  19. #include "third_party/boringssl/src/include/openssl/bn.h"
  20. #include "third_party/boringssl/src/include/openssl/digest.h"
  21. #include "third_party/boringssl/src/include/openssl/ec.h"
  22. #include "third_party/boringssl/src/include/openssl/ec_key.h"
  23. #include "third_party/boringssl/src/include/openssl/ecdsa.h"
  24. #include "third_party/boringssl/src/include/openssl/evp.h"
  25. #include "third_party/boringssl/src/include/openssl/mem.h"
  26. namespace webcrypto {
  27. namespace {
  28. // Extracts the OpenSSL key and digest from a WebCrypto key + algorithm. The
  29. // returned pkey pointer will remain valid as long as |key| is alive.
  30. Status GetPKeyAndDigest(const blink::WebCryptoAlgorithm& algorithm,
  31. const blink::WebCryptoKey& key,
  32. EVP_PKEY** pkey,
  33. const EVP_MD** digest) {
  34. *pkey = GetEVP_PKEY(key);
  35. *digest = GetDigest(algorithm.EcdsaParams()->GetHash());
  36. if (!*digest)
  37. return Status::ErrorUnsupported();
  38. return Status::Success();
  39. }
  40. // Gets the EC key's order size in bytes.
  41. Status GetEcGroupOrderSize(EVP_PKEY* pkey, size_t* order_size_bytes) {
  42. crypto::OpenSSLErrStackTracer err_tracer(FROM_HERE);
  43. EC_KEY* ec = EVP_PKEY_get0_EC_KEY(pkey);
  44. if (!ec)
  45. return Status::ErrorUnexpected();
  46. const EC_GROUP* group = EC_KEY_get0_group(ec);
  47. bssl::UniquePtr<BIGNUM> order(BN_new());
  48. if (!EC_GROUP_get_order(group, order.get(), nullptr))
  49. return Status::OperationError();
  50. *order_size_bytes = BN_num_bytes(order.get());
  51. return Status::Success();
  52. }
  53. // Formats a DER-encoded signature (ECDSA-Sig-Value as specified in RFC 3279) to
  54. // the signature format expected by WebCrypto (raw concatenated "r" and "s").
  55. //
  56. // TODO(eroman): Where is the specification for WebCrypto's signature format?
  57. Status ConvertDerSignatureToWebCryptoSignature(
  58. EVP_PKEY* key,
  59. std::vector<uint8_t>* signature) {
  60. crypto::OpenSSLErrStackTracer err_tracer(FROM_HERE);
  61. bssl::UniquePtr<ECDSA_SIG> ecdsa_sig(
  62. ECDSA_SIG_from_bytes(signature->data(), signature->size()));
  63. if (!ecdsa_sig.get())
  64. return Status::ErrorUnexpected();
  65. // Determine the maximum length of r and s.
  66. size_t order_size_bytes;
  67. Status status = GetEcGroupOrderSize(key, &order_size_bytes);
  68. if (status.IsError())
  69. return status;
  70. signature->resize(order_size_bytes * 2);
  71. if (!BN_bn2bin_padded(signature->data(), order_size_bytes,
  72. ecdsa_sig.get()->r)) {
  73. return Status::ErrorUnexpected();
  74. }
  75. if (!BN_bn2bin_padded(&(*signature)[order_size_bytes], order_size_bytes,
  76. ecdsa_sig.get()->s)) {
  77. return Status::ErrorUnexpected();
  78. }
  79. return Status::Success();
  80. }
  81. // Formats a WebCrypto ECDSA signature to a DER-encoded signature
  82. // (ECDSA-Sig-Value as specified in RFC 3279).
  83. //
  84. // TODO(eroman): What is the specification for WebCrypto's signature format?
  85. //
  86. // If the signature length is incorrect (not 2 * order_size), then
  87. // Status::Success() is returned and |*incorrect_length| is set to true;
  88. //
  89. // Otherwise on success, der_signature is filled with a ASN.1 encoded
  90. // ECDSA-Sig-Value.
  91. Status ConvertWebCryptoSignatureToDerSignature(
  92. EVP_PKEY* key,
  93. base::span<const uint8_t> signature,
  94. std::vector<uint8_t>* der_signature,
  95. bool* incorrect_length) {
  96. crypto::OpenSSLErrStackTracer err_tracer(FROM_HERE);
  97. // Determine the length of r and s.
  98. size_t order_size_bytes;
  99. Status status = GetEcGroupOrderSize(key, &order_size_bytes);
  100. if (status.IsError())
  101. return status;
  102. // If the size of the signature is incorrect, verification must fail. Success
  103. // is returned here rather than an error, so that the caller can fail
  104. // verification with a boolean, rather than reject the promise with an
  105. // exception.
  106. if (signature.size() != 2 * order_size_bytes) {
  107. *incorrect_length = true;
  108. return Status::Success();
  109. }
  110. base::span<const uint8_t> r_bytes = signature.first(order_size_bytes);
  111. base::span<const uint8_t> s_bytes = signature.subspan(order_size_bytes);
  112. *incorrect_length = false;
  113. // Construct an ECDSA_SIG from |signature|.
  114. bssl::UniquePtr<ECDSA_SIG> ecdsa_sig(ECDSA_SIG_new());
  115. if (!ecdsa_sig)
  116. return Status::OperationError();
  117. if (!BN_bin2bn(r_bytes.data(), r_bytes.size(), ecdsa_sig->r) ||
  118. !BN_bin2bn(s_bytes.data(), s_bytes.size(), ecdsa_sig->s)) {
  119. return Status::ErrorUnexpected();
  120. }
  121. // Encode the signature.
  122. uint8_t* der;
  123. size_t der_len;
  124. if (!ECDSA_SIG_to_bytes(&der, &der_len, ecdsa_sig.get()))
  125. return Status::OperationError();
  126. der_signature->assign(der, der + der_len);
  127. OPENSSL_free(der);
  128. return Status::Success();
  129. }
  130. class EcdsaImplementation : public EcAlgorithm {
  131. public:
  132. EcdsaImplementation()
  133. : EcAlgorithm(blink::kWebCryptoKeyUsageVerify,
  134. blink::kWebCryptoKeyUsageSign) {}
  135. const char* GetJwkAlgorithm(
  136. const blink::WebCryptoNamedCurve curve) const override {
  137. switch (curve) {
  138. case blink::kWebCryptoNamedCurveP256:
  139. return "ES256";
  140. case blink::kWebCryptoNamedCurveP384:
  141. return "ES384";
  142. case blink::kWebCryptoNamedCurveP521:
  143. // This is not a typo! ES512 means P-521 with SHA-512.
  144. return "ES512";
  145. default:
  146. return nullptr;
  147. }
  148. }
  149. Status Sign(const blink::WebCryptoAlgorithm& algorithm,
  150. const blink::WebCryptoKey& key,
  151. base::span<const uint8_t> data,
  152. std::vector<uint8_t>* buffer) const override {
  153. if (key.GetType() != blink::kWebCryptoKeyTypePrivate)
  154. return Status::ErrorUnexpectedKeyType();
  155. crypto::OpenSSLErrStackTracer err_tracer(FROM_HERE);
  156. EVP_PKEY* private_key = nullptr;
  157. const EVP_MD* digest = nullptr;
  158. Status status = GetPKeyAndDigest(algorithm, key, &private_key, &digest);
  159. if (status.IsError())
  160. return status;
  161. // NOTE: A call to EVP_DigestSignFinal() with a NULL second parameter
  162. // returns a maximum allocation size, while the call without a NULL returns
  163. // the real one, which may be smaller.
  164. bssl::ScopedEVP_MD_CTX ctx;
  165. size_t sig_len = 0;
  166. if (!EVP_DigestSignInit(ctx.get(), nullptr, digest, nullptr, private_key) ||
  167. !EVP_DigestSignUpdate(ctx.get(), data.data(), data.size()) ||
  168. !EVP_DigestSignFinal(ctx.get(), nullptr, &sig_len)) {
  169. return Status::OperationError();
  170. }
  171. buffer->resize(sig_len);
  172. if (!EVP_DigestSignFinal(ctx.get(), buffer->data(), &sig_len))
  173. return Status::OperationError();
  174. buffer->resize(sig_len);
  175. // ECDSA signing in BoringSSL outputs a DER-encoded (r,s). WebCrypto however
  176. // expects a padded bitstring that is r concatenated to s. Convert to the
  177. // expected format.
  178. return ConvertDerSignatureToWebCryptoSignature(private_key, buffer);
  179. }
  180. Status Verify(const blink::WebCryptoAlgorithm& algorithm,
  181. const blink::WebCryptoKey& key,
  182. base::span<const uint8_t> signature,
  183. base::span<const uint8_t> data,
  184. bool* signature_match) const override {
  185. if (key.GetType() != blink::kWebCryptoKeyTypePublic)
  186. return Status::ErrorUnexpectedKeyType();
  187. crypto::OpenSSLErrStackTracer err_tracer(FROM_HERE);
  188. EVP_PKEY* public_key = nullptr;
  189. const EVP_MD* digest = nullptr;
  190. Status status = GetPKeyAndDigest(algorithm, key, &public_key, &digest);
  191. if (status.IsError())
  192. return status;
  193. std::vector<uint8_t> der_signature;
  194. bool incorrect_length_signature = false;
  195. status = ConvertWebCryptoSignatureToDerSignature(
  196. public_key, signature, &der_signature, &incorrect_length_signature);
  197. if (status.IsError())
  198. return status;
  199. if (incorrect_length_signature) {
  200. *signature_match = false;
  201. return Status::Success();
  202. }
  203. bssl::ScopedEVP_MD_CTX ctx;
  204. if (!EVP_DigestVerifyInit(ctx.get(), nullptr, digest, nullptr,
  205. public_key) ||
  206. !EVP_DigestVerifyUpdate(ctx.get(), data.data(), data.size())) {
  207. return Status::OperationError();
  208. }
  209. *signature_match =
  210. 1 == EVP_DigestVerifyFinal(ctx.get(), der_signature.data(),
  211. der_signature.size());
  212. return Status::Success();
  213. }
  214. };
  215. } // namespace
  216. std::unique_ptr<AlgorithmImplementation> CreateEcdsaImplementation() {
  217. return std::make_unique<EcdsaImplementation>();
  218. }
  219. } // namespace webcrypto