keymaster0_engine.cpp 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382
  1. /*
  2. * Copyright 2015 The Android Open Source Project
  3. *
  4. * Licensed under the Apache License, Version 2.0 (the "License");
  5. * you may not use this file except in compliance with the License.
  6. * You may obtain a copy of the License at
  7. *
  8. * http://www.apache.org/licenses/LICENSE-2.0
  9. *
  10. * Unless required by applicable law or agreed to in writing, software
  11. * distributed under the License is distributed on an "AS IS" BASIS,
  12. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13. * See the License for the specific language governing permissions and
  14. * limitations under the License.
  15. */
  16. #include <keymaster/legacy_support/keymaster0_engine.h>
  17. #include <assert.h>
  18. #include <string.h>
  19. #include <memory>
  20. #define LOG_TAG "Keymaster0Engine"
  21. #include <log/log.h>
  22. #include <keymaster/android_keymaster_utils.h>
  23. #include <keymaster/km_openssl/openssl_utils.h>
  24. #include <openssl/bn.h>
  25. #include <openssl/ec_key.h>
  26. #include <openssl/ecdsa.h>
  27. using std::shared_ptr;
  28. using std::unique_ptr;
  29. namespace keymaster {
  30. Keymaster0Engine* Keymaster0Engine::instance_ = nullptr;
  31. Keymaster0Engine::Keymaster0Engine(const keymaster0_device_t* keymaster0_device)
  32. : keymaster0_device_(keymaster0_device), engine_(ENGINE_new()), supports_ec_(false) {
  33. assert(!instance_);
  34. instance_ = this;
  35. rsa_index_ = RSA_get_ex_new_index(0 /* argl */, nullptr /* argp */, nullptr /* new_func */,
  36. keyblob_dup, keyblob_free);
  37. ec_key_index_ = EC_KEY_get_ex_new_index(0 /* argl */, nullptr /* argp */, nullptr /* new_func */,
  38. keyblob_dup, keyblob_free);
  39. memset(&rsa_method_, 0, sizeof(rsa_method_));
  40. rsa_method_.common.is_static = 1;
  41. rsa_method_.private_transform = Keymaster0Engine::rsa_private_transform;
  42. rsa_method_.flags = RSA_FLAG_OPAQUE;
  43. ENGINE_set_RSA_method(engine_, &rsa_method_, sizeof(rsa_method_));
  44. if ((keymaster0_device_->flags & KEYMASTER_SUPPORTS_EC) != 0) {
  45. supports_ec_ = true;
  46. memset(&ecdsa_method_, 0, sizeof(ecdsa_method_));
  47. ecdsa_method_.common.is_static = 1;
  48. ecdsa_method_.sign = Keymaster0Engine::ecdsa_sign;
  49. ecdsa_method_.flags = ECDSA_FLAG_OPAQUE;
  50. ENGINE_set_ECDSA_method(engine_, &ecdsa_method_, sizeof(ecdsa_method_));
  51. }
  52. }
  53. Keymaster0Engine::~Keymaster0Engine() {
  54. if (keymaster0_device_)
  55. keymaster0_device_->common.close(
  56. reinterpret_cast<hw_device_t*>(const_cast<keymaster0_device_t*>(keymaster0_device_)));
  57. ENGINE_free(engine_);
  58. instance_ = nullptr;
  59. }
  60. bool Keymaster0Engine::GenerateRsaKey(uint64_t public_exponent, uint32_t public_modulus,
  61. KeymasterKeyBlob* key_material) const {
  62. assert(key_material);
  63. keymaster_rsa_keygen_params_t params;
  64. params.public_exponent = public_exponent;
  65. params.modulus_size = public_modulus;
  66. uint8_t* key_blob = nullptr;
  67. if (keymaster0_device_->generate_keypair(keymaster0_device_, TYPE_RSA, &params, &key_blob,
  68. &key_material->key_material_size) < 0) {
  69. ALOGE("Error generating RSA key pair with keymaster0 device");
  70. return false;
  71. }
  72. unique_ptr<uint8_t, Malloc_Delete> key_blob_deleter(key_blob);
  73. key_material->key_material = dup_buffer(key_blob, key_material->key_material_size);
  74. return true;
  75. }
  76. bool Keymaster0Engine::GenerateEcKey(uint32_t key_size, KeymasterKeyBlob* key_material) const {
  77. assert(key_material);
  78. keymaster_ec_keygen_params_t params;
  79. params.field_size = key_size;
  80. uint8_t* key_blob = nullptr;
  81. if (keymaster0_device_->generate_keypair(keymaster0_device_, TYPE_EC, &params, &key_blob,
  82. &key_material->key_material_size) < 0) {
  83. ALOGE("Error generating EC key pair with keymaster0 device");
  84. return false;
  85. }
  86. unique_ptr<uint8_t, Malloc_Delete> key_blob_deleter(key_blob);
  87. key_material->key_material = dup_buffer(key_blob, key_material->key_material_size);
  88. return true;
  89. }
  90. bool Keymaster0Engine::ImportKey(keymaster_key_format_t key_format,
  91. const KeymasterKeyBlob& to_import,
  92. KeymasterKeyBlob* imported_key) const {
  93. assert(imported_key);
  94. if (key_format != KM_KEY_FORMAT_PKCS8)
  95. return false;
  96. uint8_t* key_blob = nullptr;
  97. if (keymaster0_device_->import_keypair(keymaster0_device_, to_import.key_material,
  98. to_import.key_material_size, &key_blob,
  99. &imported_key->key_material_size) < 0) {
  100. ALOGW("Error importing keypair with keymaster0 device");
  101. return false;
  102. }
  103. unique_ptr<uint8_t, Malloc_Delete> key_blob_deleter(key_blob);
  104. imported_key->key_material = dup_buffer(key_blob, imported_key->key_material_size);
  105. return true;
  106. }
  107. bool Keymaster0Engine::DeleteKey(const KeymasterKeyBlob& blob) const {
  108. if (!keymaster0_device_->delete_keypair)
  109. return true;
  110. return (keymaster0_device_->delete_keypair(keymaster0_device_, blob.key_material,
  111. blob.key_material_size) == 0);
  112. }
  113. bool Keymaster0Engine::DeleteAllKeys() const {
  114. if (!keymaster0_device_->delete_all)
  115. return true;
  116. return (keymaster0_device_->delete_all(keymaster0_device_) == 0);
  117. }
  118. static keymaster_key_blob_t* duplicate_blob(const uint8_t* key_data, size_t key_data_size) {
  119. unique_ptr<uint8_t[]> key_material_copy(dup_buffer(key_data, key_data_size));
  120. if (!key_material_copy)
  121. return nullptr;
  122. unique_ptr<keymaster_key_blob_t> blob_copy(new (std::nothrow) keymaster_key_blob_t);
  123. if (!blob_copy.get())
  124. return nullptr;
  125. blob_copy->key_material_size = key_data_size;
  126. blob_copy->key_material = key_material_copy.release();
  127. return blob_copy.release();
  128. }
  129. inline keymaster_key_blob_t* duplicate_blob(const keymaster_key_blob_t& blob) {
  130. return duplicate_blob(blob.key_material, blob.key_material_size);
  131. }
  132. RSA* Keymaster0Engine::BlobToRsaKey(const KeymasterKeyBlob& blob) const {
  133. // Create new RSA key (with engine methods) and insert blob
  134. unique_ptr<RSA, RSA_Delete> rsa(RSA_new_method(engine_));
  135. if (!rsa)
  136. return nullptr;
  137. keymaster_key_blob_t* blob_copy = duplicate_blob(blob);
  138. if (!blob_copy->key_material || !RSA_set_ex_data(rsa.get(), rsa_index_, blob_copy))
  139. return nullptr;
  140. // Copy public key into new RSA key
  141. unique_ptr<EVP_PKEY, EVP_PKEY_Delete> pkey(GetKeymaster0PublicKey(blob));
  142. if (!pkey)
  143. return nullptr;
  144. unique_ptr<RSA, RSA_Delete> public_rsa(EVP_PKEY_get1_RSA(pkey.get()));
  145. if (!public_rsa)
  146. return nullptr;
  147. rsa->n = BN_dup(public_rsa->n);
  148. rsa->e = BN_dup(public_rsa->e);
  149. if (!rsa->n || !rsa->e)
  150. return nullptr;
  151. return rsa.release();
  152. }
  153. EC_KEY* Keymaster0Engine::BlobToEcKey(const KeymasterKeyBlob& blob) const {
  154. // Create new EC key (with engine methods) and insert blob
  155. unique_ptr<EC_KEY, EC_KEY_Delete> ec_key(EC_KEY_new_method(engine_));
  156. if (!ec_key)
  157. return nullptr;
  158. keymaster_key_blob_t* blob_copy = duplicate_blob(blob);
  159. if (!blob_copy->key_material || !EC_KEY_set_ex_data(ec_key.get(), ec_key_index_, blob_copy))
  160. return nullptr;
  161. // Copy public key into new EC key
  162. unique_ptr<EVP_PKEY, EVP_PKEY_Delete> pkey(GetKeymaster0PublicKey(blob));
  163. if (!pkey)
  164. return nullptr;
  165. unique_ptr<EC_KEY, EC_KEY_Delete> public_ec_key(EVP_PKEY_get1_EC_KEY(pkey.get()));
  166. if (!public_ec_key)
  167. return nullptr;
  168. if (!EC_KEY_set_group(ec_key.get(), EC_KEY_get0_group(public_ec_key.get())) ||
  169. !EC_KEY_set_public_key(ec_key.get(), EC_KEY_get0_public_key(public_ec_key.get())))
  170. return nullptr;
  171. return ec_key.release();
  172. }
  173. const keymaster_key_blob_t* Keymaster0Engine::RsaKeyToBlob(const RSA* rsa) const {
  174. return reinterpret_cast<keymaster_key_blob_t*>(RSA_get_ex_data(rsa, rsa_index_));
  175. }
  176. const keymaster_key_blob_t* Keymaster0Engine::EcKeyToBlob(const EC_KEY* ec_key) const {
  177. return reinterpret_cast<keymaster_key_blob_t*>(EC_KEY_get_ex_data(ec_key, ec_key_index_));
  178. }
  179. /* static */
  180. int Keymaster0Engine::keyblob_dup(CRYPTO_EX_DATA* /* to */, const CRYPTO_EX_DATA* /* from */,
  181. void** from_d, int /* index */, long /* argl */,
  182. void* /* argp */) {
  183. keymaster_key_blob_t* blob = reinterpret_cast<keymaster_key_blob_t*>(*from_d);
  184. if (!blob)
  185. return 1;
  186. *from_d = duplicate_blob(*blob);
  187. if (*from_d)
  188. return 1;
  189. return 0;
  190. }
  191. /* static */
  192. void Keymaster0Engine::keyblob_free(void* /* parent */, void* ptr, CRYPTO_EX_DATA* /* data */,
  193. int /* index*/, long /* argl */, void* /* argp */) {
  194. keymaster_key_blob_t* blob = reinterpret_cast<keymaster_key_blob_t*>(ptr);
  195. if (blob) {
  196. delete[] blob->key_material;
  197. delete blob;
  198. }
  199. }
  200. /* static */
  201. int Keymaster0Engine::rsa_private_transform(RSA* rsa, uint8_t* out, const uint8_t* in, size_t len) {
  202. ALOGV("rsa_private_transform(%p, %p, %p, %u)", rsa, out, in, (unsigned)len);
  203. assert(instance_);
  204. return instance_->RsaPrivateTransform(rsa, out, in, len);
  205. }
  206. /* static */
  207. int Keymaster0Engine::ecdsa_sign(const uint8_t* digest, size_t digest_len, uint8_t* sig,
  208. unsigned int* sig_len, EC_KEY* ec_key) {
  209. ALOGV("ecdsa_sign(%p, %u, %p)", digest, (unsigned)digest_len, ec_key);
  210. assert(instance_);
  211. return instance_->EcdsaSign(digest, digest_len, sig, sig_len, ec_key);
  212. }
  213. bool Keymaster0Engine::Keymaster0Sign(const void* signing_params, const keymaster_key_blob_t& blob,
  214. const uint8_t* data, const size_t data_length,
  215. unique_ptr<uint8_t[], Malloc_Delete>* signature,
  216. size_t* signature_length) const {
  217. uint8_t* signed_data;
  218. int err = keymaster0_device_->sign_data(keymaster0_device_, signing_params, blob.key_material,
  219. blob.key_material_size, data, data_length, &signed_data,
  220. signature_length);
  221. if (err < 0) {
  222. ALOGE("Keymaster0 signing failed with error %d", err);
  223. return false;
  224. }
  225. signature->reset(signed_data);
  226. return true;
  227. }
  228. EVP_PKEY* Keymaster0Engine::GetKeymaster0PublicKey(const KeymasterKeyBlob& blob) const {
  229. uint8_t* pub_key_data;
  230. size_t pub_key_data_length;
  231. int err = keymaster0_device_->get_keypair_public(keymaster0_device_, blob.key_material,
  232. blob.key_material_size, &pub_key_data,
  233. &pub_key_data_length);
  234. if (err < 0) {
  235. ALOGE("Error %d extracting public key", err);
  236. return nullptr;
  237. }
  238. unique_ptr<uint8_t, Malloc_Delete> pub_key(pub_key_data);
  239. const uint8_t* p = pub_key_data;
  240. return d2i_PUBKEY(nullptr /* allocate new struct */, &p, pub_key_data_length);
  241. }
  242. static bool data_too_large_for_public_modulus(const uint8_t* data, size_t len, const RSA* rsa) {
  243. unique_ptr<BIGNUM, BIGNUM_Delete> input_as_bn(
  244. BN_bin2bn(data, len, nullptr /* allocate result */));
  245. return input_as_bn && BN_ucmp(input_as_bn.get(), rsa->n) >= 0;
  246. }
  247. int Keymaster0Engine::RsaPrivateTransform(RSA* rsa, uint8_t* out, const uint8_t* in,
  248. size_t len) const {
  249. const keymaster_key_blob_t* key_blob = RsaKeyToBlob(rsa);
  250. if (key_blob == nullptr) {
  251. ALOGE("key had no key_blob!");
  252. return 0;
  253. }
  254. keymaster_rsa_sign_params_t sign_params = {DIGEST_NONE, PADDING_NONE};
  255. unique_ptr<uint8_t[], Malloc_Delete> signature;
  256. size_t signature_length;
  257. if (!Keymaster0Sign(&sign_params, *key_blob, in, len, &signature, &signature_length)) {
  258. if (data_too_large_for_public_modulus(in, len, rsa)) {
  259. ALOGE("Keymaster0 signing failed because data is too large.");
  260. OPENSSL_PUT_ERROR(RSA, RSA_R_DATA_TOO_LARGE_FOR_MODULUS);
  261. } else {
  262. // We don't know what error code is correct; force an "unknown error" return
  263. OPENSSL_PUT_ERROR(USER, KM_ERROR_UNKNOWN_ERROR);
  264. }
  265. return 0;
  266. }
  267. Eraser eraser(signature.get(), signature_length);
  268. if (signature_length > len) {
  269. /* The result of the RSA operation can never be larger than the size of
  270. * the modulus so we assume that the result has extra zeros on the
  271. * left. This provides attackers with an oracle, but there's nothing
  272. * that we can do about it here. */
  273. memcpy(out, signature.get() + signature_length - len, len);
  274. } else if (signature_length < len) {
  275. /* If the keymaster0 implementation returns a short value we assume that
  276. * it's because it removed leading zeros from the left side. This is
  277. * bad because it provides attackers with an oracle but we cannot do
  278. * anything about a broken keymaster0 implementation here. */
  279. memset(out, 0, len);
  280. memcpy(out + len - signature_length, signature.get(), signature_length);
  281. } else {
  282. memcpy(out, signature.get(), len);
  283. }
  284. ALOGV("rsa=%p keystore_rsa_priv_dec successful", rsa);
  285. return 1;
  286. }
  287. int Keymaster0Engine::EcdsaSign(const uint8_t* digest, size_t digest_len, uint8_t* sig,
  288. unsigned int* sig_len, EC_KEY* ec_key) const {
  289. const keymaster_key_blob_t* key_blob = EcKeyToBlob(ec_key);
  290. if (key_blob == nullptr) {
  291. ALOGE("key had no key_blob!");
  292. return 0;
  293. }
  294. // Truncate digest if it's too long
  295. size_t max_input_len = (ec_group_size_bits(ec_key) + 7) / 8;
  296. if (digest_len > max_input_len)
  297. digest_len = max_input_len;
  298. keymaster_ec_sign_params_t sign_params = {DIGEST_NONE};
  299. unique_ptr<uint8_t[], Malloc_Delete> signature;
  300. size_t signature_length;
  301. if (!Keymaster0Sign(&sign_params, *key_blob, digest, digest_len, &signature,
  302. &signature_length)) {
  303. // We don't know what error code is correct; force an "unknown error" return
  304. OPENSSL_PUT_ERROR(USER, KM_ERROR_UNKNOWN_ERROR);
  305. return 0;
  306. }
  307. Eraser eraser(signature.get(), signature_length);
  308. if (signature_length == 0) {
  309. ALOGW("No valid signature returned");
  310. return 0;
  311. } else if (signature_length > ECDSA_size(ec_key)) {
  312. ALOGW("Signature is too large");
  313. return 0;
  314. } else {
  315. memcpy(sig, signature.get(), signature_length);
  316. *sig_len = signature_length;
  317. }
  318. ALOGV("ecdsa_sign(%p, %u, %p) => success", digest, (unsigned)digest_len, ec_key);
  319. return 1;
  320. }
  321. } // namespace keymaster