ecdsa.cc 8.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210
  1. // Copyright 2016 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 "components/client_update_protocol/ecdsa.h"
  5. #include <stdint.h>
  6. #include "base/base64url.h"
  7. #include "base/logging.h"
  8. #include "base/memory/ptr_util.h"
  9. #include "base/strings/string_number_conversions.h"
  10. #include "base/strings/string_piece.h"
  11. #include "base/strings/string_util.h"
  12. #include "base/strings/stringprintf.h"
  13. #include "crypto/random.h"
  14. #include "crypto/sha2.h"
  15. #include "crypto/signature_verifier.h"
  16. namespace client_update_protocol {
  17. namespace {
  18. std::vector<uint8_t> SHA256HashStr(const base::StringPiece& str) {
  19. std::vector<uint8_t> result(crypto::kSHA256Length);
  20. crypto::SHA256HashString(str, &result.front(), result.size());
  21. return result;
  22. }
  23. std::vector<uint8_t> SHA256HashVec(const std::vector<uint8_t>& vec) {
  24. if (vec.empty())
  25. return SHA256HashStr(base::StringPiece());
  26. return SHA256HashStr(base::StringPiece(
  27. reinterpret_cast<const char*>(&vec.front()), vec.size()));
  28. }
  29. bool ParseETagHeader(const base::StringPiece& etag_header_value_in,
  30. std::vector<uint8_t>* ecdsa_signature_out,
  31. std::vector<uint8_t>* request_hash_out) {
  32. DCHECK(ecdsa_signature_out);
  33. DCHECK(request_hash_out);
  34. // The ETag value is a UTF-8 string, formatted as "S:H", where:
  35. // * S is the ECDSA signature in DER-encoded ASN.1 form, converted to hex.
  36. // * H is the SHA-256 hash of the observed request body, standard hex format.
  37. // A Weak ETag is formatted as W/"S:H". This function treats it the same as a
  38. // strong ETag.
  39. base::StringPiece etag_header_value(etag_header_value_in);
  40. // Remove the weak prefix, then remove the begin and the end quotes.
  41. const char kWeakETagPrefix[] = "W/";
  42. if (base::StartsWith(etag_header_value, kWeakETagPrefix))
  43. etag_header_value.remove_prefix(std::size(kWeakETagPrefix) - 1);
  44. if (etag_header_value.size() >= 2 &&
  45. base::StartsWith(etag_header_value, "\"") &&
  46. base::EndsWith(etag_header_value, "\"")) {
  47. etag_header_value.remove_prefix(1);
  48. etag_header_value.remove_suffix(1);
  49. }
  50. const base::StringPiece::size_type delim_pos = etag_header_value.find(':');
  51. if (delim_pos == base::StringPiece::npos || delim_pos == 0 ||
  52. delim_pos == etag_header_value.size() - 1)
  53. return false;
  54. const base::StringPiece sig_hex = etag_header_value.substr(0, delim_pos);
  55. const base::StringPiece hash_hex = etag_header_value.substr(delim_pos + 1);
  56. // Decode the ECDSA signature. Don't bother validating the contents of it;
  57. // the SignatureValidator class will handle the actual DER decoding and
  58. // ASN.1 parsing. Check for an expected size range only -- valid ECDSA
  59. // signatures are between 8 and 72 bytes.
  60. if (!base::HexStringToBytes(sig_hex, ecdsa_signature_out))
  61. return false;
  62. if (ecdsa_signature_out->size() < 8 || ecdsa_signature_out->size() > 72)
  63. return false;
  64. // Decode the SHA-256 hash; it should be exactly 32 bytes, no more or less.
  65. if (!base::HexStringToBytes(hash_hex, request_hash_out))
  66. return false;
  67. if (request_hash_out->size() != crypto::kSHA256Length)
  68. return false;
  69. return true;
  70. }
  71. } // namespace
  72. Ecdsa::Ecdsa(int key_version, const base::StringPiece& public_key)
  73. : pub_key_version_(key_version),
  74. public_key_(public_key.begin(), public_key.end()) {}
  75. Ecdsa::~Ecdsa() = default;
  76. std::unique_ptr<Ecdsa> Ecdsa::Create(int key_version,
  77. const base::StringPiece& public_key) {
  78. DCHECK_GT(key_version, 0);
  79. DCHECK(!public_key.empty());
  80. return base::WrapUnique(new Ecdsa(key_version, public_key));
  81. }
  82. void Ecdsa::OverrideNonceForTesting(int key_version, uint32_t nonce) {
  83. DCHECK(!request_query_cup2key_.empty());
  84. request_query_cup2key_ = base::StringPrintf("%d:%u", pub_key_version_, nonce);
  85. }
  86. void Ecdsa::SignRequest(const base::StringPiece& request_body,
  87. std::string* query_params) {
  88. DCHECK(query_params);
  89. Ecdsa::RequestParameters request_parameters = SignRequest(request_body);
  90. *query_params = base::StringPrintf("cup2key=%s&cup2hreq=%s",
  91. request_parameters.query_cup2key.c_str(),
  92. request_parameters.hash_hex.c_str());
  93. }
  94. Ecdsa::RequestParameters Ecdsa::SignRequest(
  95. const base::StringPiece& request_body) {
  96. // Generate a random nonce to use for freshness, build the cup2key query
  97. // string, and compute the SHA-256 hash of the request body. Set these
  98. // two pieces of data aside to use during ValidateResponse().
  99. uint8_t nonce[32] = {0};
  100. crypto::RandBytes(nonce);
  101. // The nonce is an opaque string to the server, so the exact encoding does not
  102. // matter. Use base64url as it is slightly more compact than hex.
  103. std::string nonce_b64;
  104. base::Base64UrlEncode(
  105. base::StringPiece(reinterpret_cast<const char*>(nonce), sizeof(nonce)),
  106. base::Base64UrlEncodePolicy::OMIT_PADDING, &nonce_b64);
  107. request_query_cup2key_ =
  108. base::StringPrintf("%d:%s", pub_key_version_, nonce_b64.c_str());
  109. request_hash_ = SHA256HashStr(request_body);
  110. // Return the query string for the user to send with the request.
  111. std::string request_hash_hex =
  112. base::HexEncode(&request_hash_.front(), request_hash_.size());
  113. request_hash_hex = base::ToLowerASCII(request_hash_hex);
  114. RequestParameters request_parameters;
  115. request_parameters.query_cup2key = request_query_cup2key_;
  116. request_parameters.hash_hex = request_hash_hex;
  117. return request_parameters;
  118. }
  119. bool Ecdsa::ValidateResponse(const base::StringPiece& response_body,
  120. const base::StringPiece& server_etag) {
  121. DCHECK(!request_hash_.empty());
  122. DCHECK(!request_query_cup2key_.empty());
  123. if (response_body.empty() || server_etag.empty())
  124. return false;
  125. // Break the ETag into its two components (the ECDSA signature, and the
  126. // hash of the request that the server observed) and decode to byte buffers.
  127. std::vector<uint8_t> signature;
  128. std::vector<uint8_t> observed_request_hash;
  129. if (!ParseETagHeader(server_etag, &signature, &observed_request_hash))
  130. return false;
  131. // Check that the server's observed request hash is equal to the original
  132. // request hash. (This is a quick rejection test; the signature test is
  133. // authoritative, but slower.)
  134. DCHECK_EQ(request_hash_.size(), crypto::kSHA256Length);
  135. if (observed_request_hash.size() != crypto::kSHA256Length)
  136. return false;
  137. if (!std::equal(observed_request_hash.begin(), observed_request_hash.end(),
  138. request_hash_.begin()))
  139. return false;
  140. // Next, build the buffer that the server will have signed on its end:
  141. // hash( hash(request) | hash(response) | cup2key_query_string )
  142. // When building the client's version of the buffer, it's important to use
  143. // the original request hash that it attempted to send, and not the observed
  144. // request hash that the server sent back to us.
  145. const std::vector<uint8_t> response_hash = SHA256HashStr(response_body);
  146. std::vector<uint8_t> signed_message;
  147. signed_message.insert(signed_message.end(), request_hash_.begin(),
  148. request_hash_.end());
  149. signed_message.insert(signed_message.end(), response_hash.begin(),
  150. response_hash.end());
  151. signed_message.insert(signed_message.end(), request_query_cup2key_.begin(),
  152. request_query_cup2key_.end());
  153. const std::vector<uint8_t> signed_message_hash =
  154. SHA256HashVec(signed_message);
  155. // Initialize the signature verifier.
  156. crypto::SignatureVerifier verifier;
  157. if (!verifier.VerifyInit(crypto::SignatureVerifier::ECDSA_SHA256, signature,
  158. public_key_)) {
  159. DVLOG(1) << "Couldn't init SignatureVerifier.";
  160. return false;
  161. }
  162. // If the verification fails, that implies one of two outcomes:
  163. // * The signature was modified
  164. // * The buffer that the server signed does not match the buffer that the
  165. // client assembled -- implying that either request body or response body
  166. // was modified, or a different nonce value was used.
  167. verifier.VerifyUpdate(signed_message_hash);
  168. return verifier.VerifyFinal();
  169. }
  170. } // namespace client_update_protocol