android_engine.cpp 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399
  1. /* Copyright 2014 The Android Open Source Project
  2. *
  3. * Redistribution and use in source and binary forms, with or without
  4. * modification, are permitted provided that the following conditions
  5. * are met:
  6. * 1. Redistributions of source code must retain the above copyright
  7. * notice, this list of conditions and the following disclaimer.
  8. * 2. Redistributions in binary form must reproduce the above copyright
  9. * notice, this list of conditions and the following disclaimer in the
  10. * documentation and/or other materials provided with the distribution.
  11. *
  12. * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND ANY
  13. * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
  14. * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
  15. * DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE FOR ANY
  16. * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
  17. * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
  18. * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
  19. * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  20. * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
  21. * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */
  22. #define LOG_TAG "keystore-engine"
  23. #include <pthread.h>
  24. #include <sys/socket.h>
  25. #include <stdarg.h>
  26. #include <string.h>
  27. #include <unistd.h>
  28. #include <log/log.h>
  29. #include <openssl/bn.h>
  30. #include <openssl/ec.h>
  31. #include <openssl/ec_key.h>
  32. #include <openssl/ecdsa.h>
  33. #include <openssl/engine.h>
  34. #include <openssl/evp.h>
  35. #include <openssl/rsa.h>
  36. #include <openssl/x509.h>
  37. #include <memory>
  38. #ifndef BACKEND_WIFI_HIDL
  39. #include "keystore_backend_binder.h"
  40. #else
  41. #include "keystore_backend_hidl.h"
  42. #endif
  43. namespace {
  44. KeystoreBackend *g_keystore_backend;
  45. void ensure_keystore_engine();
  46. /* key_id_dup is called when one of the RSA or EC_KEY objects is duplicated. */
  47. int key_id_dup(CRYPTO_EX_DATA* /* to */,
  48. const CRYPTO_EX_DATA* /* from */,
  49. void** from_d,
  50. int /* index */,
  51. long /* argl */,
  52. void* /* argp */) {
  53. char *key_id = reinterpret_cast<char *>(*from_d);
  54. if (key_id != nullptr) {
  55. *from_d = strdup(key_id);
  56. }
  57. return 1;
  58. }
  59. /* key_id_free is called when one of the RSA, DSA or EC_KEY object is freed. */
  60. void key_id_free(void* /* parent */,
  61. void* ptr,
  62. CRYPTO_EX_DATA* /* ad */,
  63. int /* index */,
  64. long /* argl */,
  65. void* /* argp */) {
  66. char *key_id = reinterpret_cast<char *>(ptr);
  67. free(key_id);
  68. }
  69. /* Many OpenSSL APIs take ownership of an argument on success but don't free
  70. * the argument on failure. This means we need to tell our scoped pointers when
  71. * we've transferred ownership, without triggering a warning by not using the
  72. * result of release(). */
  73. #define OWNERSHIP_TRANSFERRED(obj) auto _dummy __attribute__((unused)) = (obj).release()
  74. const char* rsa_get_key_id(const RSA* rsa);
  75. /* rsa_private_transform takes a big-endian integer from |in|, calculates the
  76. * d'th power of it, modulo the RSA modulus, and writes the result as a
  77. * big-endian integer to |out|. Both |in| and |out| are |len| bytes long. It
  78. * returns one on success and zero otherwise. */
  79. int rsa_private_transform(RSA *rsa, uint8_t *out, const uint8_t *in, size_t len) {
  80. ALOGV("rsa_private_transform(%p, %p, %p, %u)", rsa, out, in, (unsigned) len);
  81. ensure_keystore_engine();
  82. const char *key_id = rsa_get_key_id(rsa);
  83. if (key_id == nullptr) {
  84. ALOGE("key had no key_id!");
  85. return 0;
  86. }
  87. uint8_t* reply = nullptr;
  88. size_t reply_len;
  89. int32_t ret = g_keystore_backend->sign(key_id, in, len, &reply, &reply_len);
  90. if (ret < 0) {
  91. ALOGW("There was an error during rsa_decrypt: could not connect");
  92. return 0;
  93. } else if (ret != 0) {
  94. ALOGW("Error during sign from keystore: %d", ret);
  95. return 0;
  96. } else if (reply_len == 0 || reply == nullptr) {
  97. ALOGW("No valid signature returned");
  98. return 0;
  99. }
  100. if (reply_len > len) {
  101. /* The result of the RSA operation can never be larger than the size of
  102. * the modulus so we assume that the result has extra zeros on the
  103. * left. This provides attackers with an oracle, but there's nothing
  104. * that we can do about it here. */
  105. ALOGW("Reply len %zu greater than expected %zu", reply_len, len);
  106. memcpy(out, &reply[reply_len - len], len);
  107. } else if (reply_len < len) {
  108. /* If the Keystore implementation returns a short value we assume that
  109. * it's because it removed leading zeros from the left side. This is
  110. * bad because it provides attackers with an oracle but we cannot do
  111. * anything about a broken Keystore implementation here. */
  112. ALOGW("Reply len %zu lesser than expected %zu", reply_len, len);
  113. memset(out, 0, len);
  114. memcpy(out + len - reply_len, &reply[0], reply_len);
  115. } else {
  116. memcpy(out, &reply[0], len);
  117. }
  118. ALOGV("rsa=%p keystore_rsa_priv_dec successful", rsa);
  119. return 1;
  120. }
  121. const char* ecdsa_get_key_id(const EC_KEY* ec_key);
  122. /* ecdsa_sign signs |digest_len| bytes from |digest| with |ec_key| and writes
  123. * the resulting signature (an ASN.1 encoded blob) to |sig|. It returns one on
  124. * success and zero otherwise. */
  125. static int ecdsa_sign(const uint8_t* digest, size_t digest_len, uint8_t* sig,
  126. unsigned int* sig_len, EC_KEY* ec_key) {
  127. ALOGV("ecdsa_sign(%p, %u, %p)", digest, (unsigned) digest_len, ec_key);
  128. ensure_keystore_engine();
  129. const char *key_id = ecdsa_get_key_id(ec_key);
  130. if (key_id == nullptr) {
  131. ALOGE("key had no key_id!");
  132. return 0;
  133. }
  134. size_t ecdsa_size = ECDSA_size(ec_key);
  135. uint8_t* reply = nullptr;
  136. size_t reply_len;
  137. int32_t ret = g_keystore_backend->sign(
  138. key_id, digest, digest_len, &reply, &reply_len);
  139. if (ret < 0) {
  140. ALOGW("There was an error during ecdsa_sign: could not connect");
  141. return 0;
  142. } else if (reply_len == 0 || reply == nullptr) {
  143. ALOGW("No valid signature returned");
  144. return 0;
  145. } else if (reply_len > ecdsa_size) {
  146. ALOGW("Signature is too large");
  147. return 0;
  148. }
  149. // Reviewer: should't sig_len be checked here? Or is it just assumed that it is at least ecdsa_size?
  150. memcpy(sig, &reply[0], reply_len);
  151. *sig_len = reply_len;
  152. ALOGV("ecdsa_sign(%p, %u, %p) => success", digest, (unsigned)digest_len,
  153. ec_key);
  154. return 1;
  155. }
  156. /* KeystoreEngine is a BoringSSL ENGINE that implements RSA and ECDSA by
  157. * forwarding the requested operations to Keystore. */
  158. class KeystoreEngine {
  159. public:
  160. KeystoreEngine()
  161. : rsa_index_(RSA_get_ex_new_index(0 /* argl */,
  162. nullptr /* argp */,
  163. nullptr /* new_func */,
  164. key_id_dup,
  165. key_id_free)),
  166. ec_key_index_(EC_KEY_get_ex_new_index(0 /* argl */,
  167. nullptr /* argp */,
  168. nullptr /* new_func */,
  169. key_id_dup,
  170. key_id_free)),
  171. engine_(ENGINE_new()) {
  172. memset(&rsa_method_, 0, sizeof(rsa_method_));
  173. rsa_method_.common.is_static = 1;
  174. rsa_method_.private_transform = rsa_private_transform;
  175. rsa_method_.flags = RSA_FLAG_OPAQUE;
  176. ENGINE_set_RSA_method(engine_, &rsa_method_, sizeof(rsa_method_));
  177. memset(&ecdsa_method_, 0, sizeof(ecdsa_method_));
  178. ecdsa_method_.common.is_static = 1;
  179. ecdsa_method_.sign = ecdsa_sign;
  180. ecdsa_method_.flags = ECDSA_FLAG_OPAQUE;
  181. ENGINE_set_ECDSA_method(engine_, &ecdsa_method_, sizeof(ecdsa_method_));
  182. }
  183. int rsa_ex_index() const { return rsa_index_; }
  184. int ec_key_ex_index() const { return ec_key_index_; }
  185. const ENGINE* engine() const { return engine_; }
  186. private:
  187. const int rsa_index_;
  188. const int ec_key_index_;
  189. RSA_METHOD rsa_method_;
  190. ECDSA_METHOD ecdsa_method_;
  191. ENGINE* const engine_;
  192. };
  193. pthread_once_t g_keystore_engine_once = PTHREAD_ONCE_INIT;
  194. KeystoreEngine *g_keystore_engine;
  195. /* init_keystore_engine is called to initialize |g_keystore_engine|. This
  196. * should only be called by |pthread_once|. */
  197. void init_keystore_engine() {
  198. g_keystore_engine = new KeystoreEngine;
  199. #ifndef BACKEND_WIFI_HIDL
  200. g_keystore_backend = new KeystoreBackendBinder;
  201. #else
  202. g_keystore_backend = new KeystoreBackendHidl;
  203. #endif
  204. }
  205. /* ensure_keystore_engine ensures that |g_keystore_engine| is pointing to a
  206. * valid |KeystoreEngine| object and creates one if not. */
  207. void ensure_keystore_engine() {
  208. pthread_once(&g_keystore_engine_once, init_keystore_engine);
  209. }
  210. const char* rsa_get_key_id(const RSA* rsa) {
  211. return reinterpret_cast<char*>(
  212. RSA_get_ex_data(rsa, g_keystore_engine->rsa_ex_index()));
  213. }
  214. const char* ecdsa_get_key_id(const EC_KEY* ec_key) {
  215. return reinterpret_cast<char*>(
  216. EC_KEY_get_ex_data(ec_key, g_keystore_engine->ec_key_ex_index()));
  217. }
  218. struct EVP_PKEY_Delete {
  219. void operator()(EVP_PKEY* p) const {
  220. EVP_PKEY_free(p);
  221. }
  222. };
  223. typedef std::unique_ptr<EVP_PKEY, EVP_PKEY_Delete> Unique_EVP_PKEY;
  224. struct RSA_Delete {
  225. void operator()(RSA* p) const {
  226. RSA_free(p);
  227. }
  228. };
  229. typedef std::unique_ptr<RSA, RSA_Delete> Unique_RSA;
  230. struct EC_KEY_Delete {
  231. void operator()(EC_KEY* ec) const {
  232. EC_KEY_free(ec);
  233. }
  234. };
  235. typedef std::unique_ptr<EC_KEY, EC_KEY_Delete> Unique_EC_KEY;
  236. /* wrap_rsa returns an |EVP_PKEY| that contains an RSA key where the public
  237. * part is taken from |public_rsa| and the private operations are forwarded to
  238. * KeyStore and operate on the key named |key_id|. */
  239. static EVP_PKEY *wrap_rsa(const char *key_id, const RSA *public_rsa) {
  240. Unique_RSA rsa(RSA_new_method(g_keystore_engine->engine()));
  241. if (rsa.get() == nullptr) {
  242. return nullptr;
  243. }
  244. char *key_id_copy = strdup(key_id);
  245. if (key_id_copy == nullptr) {
  246. return nullptr;
  247. }
  248. if (!RSA_set_ex_data(rsa.get(), g_keystore_engine->rsa_ex_index(),
  249. key_id_copy)) {
  250. free(key_id_copy);
  251. return nullptr;
  252. }
  253. rsa->n = BN_dup(public_rsa->n);
  254. rsa->e = BN_dup(public_rsa->e);
  255. if (rsa->n == nullptr || rsa->e == nullptr) {
  256. return nullptr;
  257. }
  258. Unique_EVP_PKEY result(EVP_PKEY_new());
  259. if (result.get() == nullptr ||
  260. !EVP_PKEY_assign_RSA(result.get(), rsa.get())) {
  261. return nullptr;
  262. }
  263. OWNERSHIP_TRANSFERRED(rsa);
  264. return result.release();
  265. }
  266. /* wrap_ecdsa returns an |EVP_PKEY| that contains an ECDSA key where the public
  267. * part is taken from |public_rsa| and the private operations are forwarded to
  268. * KeyStore and operate on the key named |key_id|. */
  269. static EVP_PKEY *wrap_ecdsa(const char *key_id, const EC_KEY *public_ecdsa) {
  270. Unique_EC_KEY ec(EC_KEY_new_method(g_keystore_engine->engine()));
  271. if (ec.get() == nullptr) {
  272. return nullptr;
  273. }
  274. if (!EC_KEY_set_group(ec.get(), EC_KEY_get0_group(public_ecdsa)) ||
  275. !EC_KEY_set_public_key(ec.get(), EC_KEY_get0_public_key(public_ecdsa))) {
  276. return nullptr;
  277. }
  278. char *key_id_copy = strdup(key_id);
  279. if (key_id_copy == nullptr) {
  280. return nullptr;
  281. }
  282. if (!EC_KEY_set_ex_data(ec.get(), g_keystore_engine->ec_key_ex_index(),
  283. key_id_copy)) {
  284. free(key_id_copy);
  285. return nullptr;
  286. }
  287. Unique_EVP_PKEY result(EVP_PKEY_new());
  288. if (result.get() == nullptr ||
  289. !EVP_PKEY_assign_EC_KEY(result.get(), ec.get())) {
  290. return nullptr;
  291. }
  292. OWNERSHIP_TRANSFERRED(ec);
  293. return result.release();
  294. }
  295. } /* anonymous namespace */
  296. extern "C" {
  297. EVP_PKEY* EVP_PKEY_from_keystore(const char* key_id) __attribute__((visibility("default")));
  298. /* EVP_PKEY_from_keystore returns an |EVP_PKEY| that contains either an RSA or
  299. * ECDSA key where the public part of the key reflects the value of the key
  300. * named |key_id| in Keystore and the private operations are forwarded onto
  301. * KeyStore. */
  302. EVP_PKEY* EVP_PKEY_from_keystore(const char* key_id) {
  303. ALOGV("EVP_PKEY_from_keystore(\"%s\")", key_id);
  304. ensure_keystore_engine();
  305. uint8_t *pubkey = nullptr;
  306. size_t pubkey_len;
  307. int32_t ret = g_keystore_backend->get_pubkey(key_id, &pubkey, &pubkey_len);
  308. if (ret < 0) {
  309. ALOGW("could not contact keystore");
  310. return nullptr;
  311. } else if (ret != 0 || pubkey == nullptr) {
  312. ALOGW("keystore reports error: %d", ret);
  313. return nullptr;
  314. }
  315. const uint8_t *inp = pubkey;
  316. Unique_EVP_PKEY pkey(d2i_PUBKEY(nullptr, &inp, pubkey_len));
  317. if (pkey.get() == nullptr) {
  318. ALOGW("Cannot convert pubkey");
  319. return nullptr;
  320. }
  321. EVP_PKEY *result;
  322. switch (EVP_PKEY_type(pkey->type)) {
  323. case EVP_PKEY_RSA: {
  324. Unique_RSA public_rsa(EVP_PKEY_get1_RSA(pkey.get()));
  325. result = wrap_rsa(key_id, public_rsa.get());
  326. break;
  327. }
  328. case EVP_PKEY_EC: {
  329. Unique_EC_KEY public_ecdsa(EVP_PKEY_get1_EC_KEY(pkey.get()));
  330. result = wrap_ecdsa(key_id, public_ecdsa.get());
  331. break;
  332. }
  333. default:
  334. ALOGE("Unsupported key type %d", EVP_PKEY_type(pkey->type));
  335. result = nullptr;
  336. }
  337. return result;
  338. }
  339. } // extern "C"