unexportable_key_win.cc 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500
  1. // Copyright (c) 2021 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 <windows.h>
  5. #include <ncrypt.h>
  6. #include <string>
  7. #include <tuple>
  8. #include <vector>
  9. #include "base/logging.h"
  10. #include "base/numerics/checked_math.h"
  11. #include "base/scoped_generic.h"
  12. #include "base/strings/string_number_conversions.h"
  13. #include "base/strings/string_piece.h"
  14. #include "base/strings/string_util.h"
  15. #include "base/strings/sys_string_conversions.h"
  16. #include "base/strings/utf_string_conversions.h"
  17. #include "base/threading/scoped_blocking_call.h"
  18. #include "crypto/random.h"
  19. #include "crypto/sha2.h"
  20. #include "crypto/unexportable_key.h"
  21. #include "third_party/boringssl/src/include/openssl/bn.h"
  22. #include "third_party/boringssl/src/include/openssl/bytestring.h"
  23. #include "third_party/boringssl/src/include/openssl/ec.h"
  24. #include "third_party/boringssl/src/include/openssl/ec_key.h"
  25. #include "third_party/boringssl/src/include/openssl/ecdsa.h"
  26. #include "third_party/boringssl/src/include/openssl/evp.h"
  27. #include "third_party/boringssl/src/include/openssl/nid.h"
  28. #include "third_party/boringssl/src/include/openssl/rsa.h"
  29. namespace crypto {
  30. namespace {
  31. // NCrypt has a style of returning handles by writing opaque pointers to
  32. // caller-provided locations. These pointers must be passed to
  33. // |NCryptFreeObject| when no longer needed.
  34. template <typename T>
  35. struct NCryptObjectTraits {
  36. // In practice a value of zero makes |NCryptFreeObject| a no-op, but this
  37. // isn't specified by the documentation so the code below avoids depending on
  38. // this by releasing() values that were never initialised.
  39. static T InvalidValue() { return 0; }
  40. static void Free(T handle) { NCryptFreeObject(handle); }
  41. };
  42. using ScopedProvider =
  43. base::ScopedGeneric<NCRYPT_PROV_HANDLE,
  44. NCryptObjectTraits<NCRYPT_PROV_HANDLE>>;
  45. using ScopedKey = base::ScopedGeneric<NCRYPT_KEY_HANDLE,
  46. NCryptObjectTraits<NCRYPT_KEY_HANDLE>>;
  47. std::vector<uint8_t> CBBToVector(const CBB* cbb) {
  48. return std::vector<uint8_t>(CBB_data(cbb), CBB_data(cbb) + CBB_len(cbb));
  49. }
  50. // BCryptAlgorithmFor returns the BCrypt algorithm ID for the given Chromium
  51. // signing algorithm.
  52. absl::optional<LPCWSTR> BCryptAlgorithmFor(
  53. SignatureVerifier::SignatureAlgorithm algo) {
  54. switch (algo) {
  55. case SignatureVerifier::SignatureAlgorithm::RSA_PKCS1_SHA256:
  56. return BCRYPT_RSA_ALGORITHM;
  57. case SignatureVerifier::SignatureAlgorithm::ECDSA_SHA256:
  58. return BCRYPT_ECDSA_P256_ALGORITHM;
  59. default:
  60. return absl::nullopt;
  61. }
  62. }
  63. // GetBestSupported returns the first element of |acceptable_algorithms| that
  64. // |provider| supports, or |nullopt| if there isn't any.
  65. absl::optional<SignatureVerifier::SignatureAlgorithm> GetBestSupported(
  66. NCRYPT_PROV_HANDLE provider,
  67. base::span<const SignatureVerifier::SignatureAlgorithm>
  68. acceptable_algorithms) {
  69. for (auto algo : acceptable_algorithms) {
  70. absl::optional<LPCWSTR> bcrypto_algo_name = BCryptAlgorithmFor(algo);
  71. if (!bcrypto_algo_name) {
  72. continue;
  73. }
  74. if (!FAILED(NCryptIsAlgSupported(provider, *bcrypto_algo_name,
  75. /*flags=*/0))) {
  76. return algo;
  77. }
  78. }
  79. return absl::nullopt;
  80. }
  81. // GetKeyProperty returns the given NCrypt key property of |key|.
  82. absl::optional<std::vector<uint8_t>> GetKeyProperty(NCRYPT_KEY_HANDLE key,
  83. LPCWSTR property) {
  84. DWORD size;
  85. if (FAILED(NCryptGetProperty(key, property, nullptr, 0, &size, 0))) {
  86. return absl::nullopt;
  87. }
  88. std::vector<uint8_t> ret(size);
  89. if (FAILED(
  90. NCryptGetProperty(key, property, ret.data(), ret.size(), &size, 0))) {
  91. return absl::nullopt;
  92. }
  93. CHECK_EQ(ret.size(), size);
  94. return ret;
  95. }
  96. // ExportKey returns |key| exported in the given format or nullopt on error.
  97. absl::optional<std::vector<uint8_t>> ExportKey(NCRYPT_KEY_HANDLE key,
  98. LPCWSTR format) {
  99. DWORD output_size;
  100. if (FAILED(NCryptExportKey(key, 0, format, nullptr, nullptr, 0, &output_size,
  101. 0))) {
  102. return absl::nullopt;
  103. }
  104. std::vector<uint8_t> output(output_size);
  105. if (FAILED(NCryptExportKey(key, 0, format, nullptr, output.data(),
  106. output.size(), &output_size, 0))) {
  107. return absl::nullopt;
  108. }
  109. CHECK_EQ(output.size(), output_size);
  110. return output;
  111. }
  112. absl::optional<std::vector<uint8_t>> GetP256ECDSASPKI(NCRYPT_KEY_HANDLE key) {
  113. const absl::optional<std::vector<uint8_t>> pub_key =
  114. ExportKey(key, BCRYPT_ECCPUBLIC_BLOB);
  115. if (!pub_key) {
  116. return absl::nullopt;
  117. }
  118. // The exported key is a |BCRYPT_ECCKEY_BLOB| followed by the bytes of the
  119. // public key itself.
  120. // https://docs.microsoft.com/en-us/windows/win32/api/bcrypt/ns-bcrypt-bcrypt_ecckey_blob
  121. BCRYPT_ECCKEY_BLOB header;
  122. if (pub_key->size() < sizeof(header)) {
  123. return absl::nullopt;
  124. }
  125. memcpy(&header, pub_key->data(), sizeof(header));
  126. // |cbKey| is documented[1] as "the length, in bytes, of the key". It is
  127. // not. For ECDSA public keys it is the length of a field element.
  128. if (header.dwMagic != BCRYPT_ECDSA_PUBLIC_P256_MAGIC ||
  129. header.cbKey != 256 / 8 ||
  130. pub_key->size() - sizeof(BCRYPT_ECCKEY_BLOB) != 64) {
  131. return absl::nullopt;
  132. }
  133. uint8_t x962[1 + 32 + 32];
  134. x962[0] = POINT_CONVERSION_UNCOMPRESSED;
  135. memcpy(&x962[1], pub_key->data() + sizeof(BCRYPT_ECCKEY_BLOB), 64);
  136. bssl::UniquePtr<EC_GROUP> p256(
  137. EC_GROUP_new_by_curve_name(NID_X9_62_prime256v1));
  138. bssl::UniquePtr<EC_POINT> point(EC_POINT_new(p256.get()));
  139. if (!EC_POINT_oct2point(p256.get(), point.get(), x962, sizeof(x962),
  140. /*ctx=*/nullptr)) {
  141. return absl::nullopt;
  142. }
  143. bssl::UniquePtr<EC_KEY> ec_key(
  144. EC_KEY_new_by_curve_name(NID_X9_62_prime256v1));
  145. CHECK(EC_KEY_set_public_key(ec_key.get(), point.get()));
  146. bssl::UniquePtr<EVP_PKEY> pkey(EVP_PKEY_new());
  147. CHECK(EVP_PKEY_set1_EC_KEY(pkey.get(), ec_key.get()));
  148. bssl::ScopedCBB cbb;
  149. CHECK(CBB_init(cbb.get(), /*initial_capacity=*/128) &&
  150. EVP_marshal_public_key(cbb.get(), pkey.get()));
  151. return CBBToVector(cbb.get());
  152. }
  153. absl::optional<std::vector<uint8_t>> GetRSASPKI(NCRYPT_KEY_HANDLE key) {
  154. const absl::optional<std::vector<uint8_t>> pub_key =
  155. ExportKey(key, BCRYPT_RSAPUBLIC_BLOB);
  156. if (!pub_key) {
  157. return absl::nullopt;
  158. }
  159. // The exported key is a |BCRYPT_RSAKEY_BLOB| followed by the bytes of the
  160. // key itself.
  161. // https://docs.microsoft.com/en-us/windows/win32/api/bcrypt/ns-bcrypt-bcrypt_rsakey_blob
  162. BCRYPT_RSAKEY_BLOB header;
  163. if (pub_key->size() < sizeof(header)) {
  164. return absl::nullopt;
  165. }
  166. memcpy(&header, pub_key->data(), sizeof(header));
  167. if (header.Magic != static_cast<ULONG>(BCRYPT_RSAPUBLIC_MAGIC)) {
  168. return absl::nullopt;
  169. }
  170. size_t bytes_needed;
  171. if (!base::CheckAdd(sizeof(BCRYPT_RSAKEY_BLOB),
  172. base::CheckAdd(header.cbPublicExp, header.cbModulus))
  173. .AssignIfValid(&bytes_needed) ||
  174. pub_key->size() < bytes_needed) {
  175. return absl::nullopt;
  176. }
  177. bssl::UniquePtr<BIGNUM> e(
  178. BN_bin2bn(&pub_key->data()[sizeof(BCRYPT_RSAKEY_BLOB)],
  179. header.cbPublicExp, nullptr));
  180. bssl::UniquePtr<BIGNUM> n(BN_bin2bn(
  181. &pub_key->data()[sizeof(BCRYPT_RSAKEY_BLOB) + header.cbPublicExp],
  182. header.cbModulus, nullptr));
  183. bssl::UniquePtr<RSA> rsa(RSA_new());
  184. CHECK(RSA_set0_key(rsa.get(), n.release(), e.release(), nullptr));
  185. bssl::UniquePtr<EVP_PKEY> pkey(EVP_PKEY_new());
  186. CHECK(EVP_PKEY_set1_RSA(pkey.get(), rsa.get()));
  187. bssl::ScopedCBB cbb;
  188. CHECK(CBB_init(cbb.get(), /*initial_capacity=*/384) &&
  189. EVP_marshal_public_key(cbb.get(), pkey.get()));
  190. return CBBToVector(cbb.get());
  191. }
  192. // ECDSAKey wraps a TPM-stored P-256 ECDSA key.
  193. class ECDSAKey : public UnexportableSigningKey {
  194. public:
  195. ECDSAKey(ScopedProvider provider,
  196. ScopedKey key,
  197. std::vector<uint8_t> wrapped,
  198. std::vector<uint8_t> spki)
  199. : provider_(std::move(provider)),
  200. key_(std::move(key)),
  201. wrapped_(std::move(wrapped)),
  202. spki_(std::move(spki)) {}
  203. SignatureVerifier::SignatureAlgorithm Algorithm() const override {
  204. return SignatureVerifier::SignatureAlgorithm::ECDSA_SHA256;
  205. }
  206. std::vector<uint8_t> GetSubjectPublicKeyInfo() const override {
  207. return spki_;
  208. }
  209. std::vector<uint8_t> GetWrappedKey() const override { return wrapped_; }
  210. absl::optional<std::vector<uint8_t>> SignSlowly(
  211. base::span<const uint8_t> data) override {
  212. base::ScopedBlockingCall scoped_blocking_call(
  213. FROM_HERE, base::BlockingType::WILL_BLOCK);
  214. std::array<uint8_t, kSHA256Length> digest = SHA256Hash(data);
  215. // The signature is written as a pair of big-endian field elements for P-256
  216. // ECDSA.
  217. std::vector<uint8_t> sig(64);
  218. DWORD sig_size;
  219. if (FAILED(NCryptSignHash(key_.get(), nullptr, digest.data(), digest.size(),
  220. sig.data(), sig.size(), &sig_size,
  221. NCRYPT_SILENT_FLAG))) {
  222. return absl::nullopt;
  223. }
  224. CHECK_EQ(sig.size(), sig_size);
  225. bssl::UniquePtr<BIGNUM> r(BN_bin2bn(sig.data(), 32, nullptr));
  226. bssl::UniquePtr<BIGNUM> s(BN_bin2bn(sig.data() + 32, 32, nullptr));
  227. ECDSA_SIG sig_st;
  228. sig_st.r = r.get();
  229. sig_st.s = s.get();
  230. bssl::ScopedCBB cbb;
  231. CHECK(CBB_init(cbb.get(), /*initial_capacity=*/72) &&
  232. ECDSA_SIG_marshal(cbb.get(), &sig_st));
  233. return CBBToVector(cbb.get());
  234. }
  235. private:
  236. ScopedProvider provider_;
  237. ScopedKey key_;
  238. const std::vector<uint8_t> wrapped_;
  239. const std::vector<uint8_t> spki_;
  240. };
  241. // RSAKey wraps a TPM-stored RSA key.
  242. class RSAKey : public UnexportableSigningKey {
  243. public:
  244. RSAKey(ScopedProvider provider,
  245. ScopedKey key,
  246. std::vector<uint8_t> wrapped,
  247. std::vector<uint8_t> spki)
  248. : provider_(std::move(provider)),
  249. key_(std::move(key)),
  250. wrapped_(std::move(wrapped)),
  251. spki_(std::move(spki)) {}
  252. SignatureVerifier::SignatureAlgorithm Algorithm() const override {
  253. return SignatureVerifier::SignatureAlgorithm::RSA_PKCS1_SHA256;
  254. }
  255. std::vector<uint8_t> GetSubjectPublicKeyInfo() const override {
  256. return spki_;
  257. }
  258. std::vector<uint8_t> GetWrappedKey() const override { return wrapped_; }
  259. absl::optional<std::vector<uint8_t>> SignSlowly(
  260. base::span<const uint8_t> data) override {
  261. base::ScopedBlockingCall scoped_blocking_call(
  262. FROM_HERE, base::BlockingType::WILL_BLOCK);
  263. std::array<uint8_t, kSHA256Length> digest = SHA256Hash(data);
  264. BCRYPT_PKCS1_PADDING_INFO padding_info = {0};
  265. padding_info.pszAlgId = NCRYPT_SHA256_ALGORITHM;
  266. DWORD sig_size;
  267. if (FAILED(NCryptSignHash(key_.get(), &padding_info, digest.data(),
  268. digest.size(), nullptr, 0, &sig_size,
  269. NCRYPT_SILENT_FLAG | BCRYPT_PAD_PKCS1))) {
  270. return absl::nullopt;
  271. }
  272. std::vector<uint8_t> sig(sig_size);
  273. if (FAILED(NCryptSignHash(key_.get(), &padding_info, digest.data(),
  274. digest.size(), sig.data(), sig.size(), &sig_size,
  275. NCRYPT_SILENT_FLAG | BCRYPT_PAD_PKCS1))) {
  276. return absl::nullopt;
  277. }
  278. CHECK_EQ(sig.size(), sig_size);
  279. return sig;
  280. }
  281. private:
  282. ScopedProvider provider_;
  283. ScopedKey key_;
  284. const std::vector<uint8_t> wrapped_;
  285. const std::vector<uint8_t> spki_;
  286. };
  287. // UnexportableKeyProviderWin uses NCrypt and the Platform Crypto
  288. // Provider to expose TPM-backed keys on Windows.
  289. class UnexportableKeyProviderWin : public UnexportableKeyProvider {
  290. public:
  291. ~UnexportableKeyProviderWin() override = default;
  292. absl::optional<SignatureVerifier::SignatureAlgorithm> SelectAlgorithm(
  293. base::span<const SignatureVerifier::SignatureAlgorithm>
  294. acceptable_algorithms) override {
  295. ScopedProvider provider;
  296. if (FAILED(NCryptOpenStorageProvider(
  297. ScopedProvider::Receiver(provider).get(),
  298. MS_PLATFORM_CRYPTO_PROVIDER, /*flags=*/0))) {
  299. // If the operation failed then |provider| doesn't have a valid handle in
  300. // it and we shouldn't try to free it.
  301. std::ignore = provider.release();
  302. return absl::nullopt;
  303. }
  304. return GetBestSupported(provider.get(), acceptable_algorithms);
  305. }
  306. std::unique_ptr<UnexportableSigningKey> GenerateSigningKeySlowly(
  307. base::span<const SignatureVerifier::SignatureAlgorithm>
  308. acceptable_algorithms) override {
  309. base::ScopedBlockingCall scoped_blocking_call(
  310. FROM_HERE, base::BlockingType::WILL_BLOCK);
  311. ScopedProvider provider;
  312. if (FAILED(NCryptOpenStorageProvider(
  313. ScopedProvider::Receiver(provider).get(),
  314. MS_PLATFORM_CRYPTO_PROVIDER, /*flags=*/0))) {
  315. // If the operation failed when |provider| doesn't have a valid handle in
  316. // it and we shouldn't try to free it.
  317. std::ignore = provider.release();
  318. return nullptr;
  319. }
  320. absl::optional<SignatureVerifier::SignatureAlgorithm> algo =
  321. GetBestSupported(provider.get(), acceptable_algorithms);
  322. if (!algo) {
  323. return nullptr;
  324. }
  325. ScopedKey key;
  326. // An empty key name stops the key being persisted to disk.
  327. if (FAILED(NCryptCreatePersistedKey(
  328. provider.get(), ScopedKey::Receiver(key).get(),
  329. BCryptAlgorithmFor(*algo).value(), /*pszKeyName=*/nullptr,
  330. /*dwLegacyKeySpec=*/0, /*dwFlags=*/0))) {
  331. // If the operation failed then |key| doesn't have a valid handle in it
  332. // and we shouldn't try and free it.
  333. std::ignore = key.release();
  334. return nullptr;
  335. }
  336. if (FAILED(NCryptFinalizeKey(key.get(), NCRYPT_SILENT_FLAG))) {
  337. return nullptr;
  338. }
  339. const absl::optional<std::vector<uint8_t>> wrapped_key =
  340. ExportKey(key.get(), BCRYPT_OPAQUE_KEY_BLOB);
  341. if (!wrapped_key) {
  342. return nullptr;
  343. }
  344. absl::optional<std::vector<uint8_t>> spki;
  345. switch (*algo) {
  346. case SignatureVerifier::SignatureAlgorithm::ECDSA_SHA256:
  347. spki = GetP256ECDSASPKI(key.get());
  348. if (!spki) {
  349. return nullptr;
  350. }
  351. return std::make_unique<ECDSAKey>(std::move(provider), std::move(key),
  352. std::move(*wrapped_key),
  353. std::move(spki.value()));
  354. case SignatureVerifier::SignatureAlgorithm::RSA_PKCS1_SHA256:
  355. spki = GetRSASPKI(key.get());
  356. if (!spki) {
  357. return nullptr;
  358. }
  359. return std::make_unique<RSAKey>(std::move(provider), std::move(key),
  360. std::move(*wrapped_key),
  361. std::move(spki.value()));
  362. default:
  363. return nullptr;
  364. }
  365. }
  366. std::unique_ptr<UnexportableSigningKey> FromWrappedSigningKeySlowly(
  367. base::span<const uint8_t> wrapped) override {
  368. base::ScopedBlockingCall scoped_blocking_call(
  369. FROM_HERE, base::BlockingType::WILL_BLOCK);
  370. ScopedProvider provider;
  371. if (FAILED(NCryptOpenStorageProvider(
  372. ScopedProvider::Receiver(provider).get(),
  373. MS_PLATFORM_CRYPTO_PROVIDER, /*flags=*/0))) {
  374. // If the operation failed when |provider| doesn't have a valid handle in
  375. // it and we shouldn't try to free it.
  376. std::ignore = provider.release();
  377. return nullptr;
  378. }
  379. ScopedKey key;
  380. if (FAILED(NCryptImportKey(
  381. provider.get(), /*hImportKey=*/NULL, BCRYPT_OPAQUE_KEY_BLOB,
  382. /*pParameterList=*/nullptr, ScopedKey::Receiver(key).get(),
  383. const_cast<PBYTE>(wrapped.data()), wrapped.size(),
  384. /*dwFlags=*/NCRYPT_SILENT_FLAG))) {
  385. // If the operation failed then |key| doesn't have a valid handle in it
  386. // and we shouldn't try and free it.
  387. std::ignore = key.release();
  388. return nullptr;
  389. }
  390. const absl::optional<std::vector<uint8_t>> algo_bytes =
  391. GetKeyProperty(key.get(), NCRYPT_ALGORITHM_PROPERTY);
  392. if (!algo_bytes) {
  393. return nullptr;
  394. }
  395. // The documentation suggests that |NCRYPT_ALGORITHM_PROPERTY| should return
  396. // the original algorithm, i.e. |BCRYPT_ECDSA_P256_ALGORITHM| for ECDSA. But
  397. // it actually returns just "ECDSA" for that case.
  398. static const wchar_t kECDSA[] = L"ECDSA";
  399. static const wchar_t kRSA[] = BCRYPT_RSA_ALGORITHM;
  400. absl::optional<std::vector<uint8_t>> spki;
  401. if (algo_bytes->size() == sizeof(kECDSA) &&
  402. memcmp(algo_bytes->data(), kECDSA, sizeof(kECDSA)) == 0) {
  403. spki = GetP256ECDSASPKI(key.get());
  404. if (!spki) {
  405. return nullptr;
  406. }
  407. return std::make_unique<ECDSAKey>(
  408. std::move(provider), std::move(key),
  409. std::vector<uint8_t>(wrapped.begin(), wrapped.end()),
  410. std::move(spki.value()));
  411. } else if (algo_bytes->size() == sizeof(kRSA) &&
  412. memcmp(algo_bytes->data(), kRSA, sizeof(kRSA)) == 0) {
  413. spki = GetRSASPKI(key.get());
  414. if (!spki) {
  415. return nullptr;
  416. }
  417. return std::make_unique<RSAKey>(
  418. std::move(provider), std::move(key),
  419. std::vector<uint8_t>(wrapped.begin(), wrapped.end()),
  420. std::move(spki.value()));
  421. }
  422. return nullptr;
  423. }
  424. };
  425. } // namespace
  426. std::unique_ptr<UnexportableKeyProvider> GetUnexportableKeyProviderWin() {
  427. return std::make_unique<UnexportableKeyProviderWin>();
  428. }
  429. } // namespace crypto