keymaster_worker.h 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298
  1. /*
  2. **
  3. ** Copyright 2018, The Android Open Source Project
  4. **
  5. ** Licensed under the Apache License, Version 2.0 (the "License");
  6. ** you may not use this file except in compliance with the License.
  7. ** You may obtain a copy of the License at
  8. **
  9. ** http://www.apache.org/licenses/LICENSE-2.0
  10. **
  11. ** Unless required by applicable law or agreed to in writing, software
  12. ** distributed under the License is distributed on an "AS IS" BASIS,
  13. ** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  14. ** See the License for the specific language governing permissions and
  15. ** limitations under the License.
  16. */
  17. #ifndef KEYSTORE_KEYMASTER_WORKER_H_
  18. #define KEYSTORE_KEYMASTER_WORKER_H_
  19. #include <condition_variable>
  20. #include <functional>
  21. #include <keymasterV4_0/Keymaster.h>
  22. #include <memory>
  23. #include <mutex>
  24. #include <optional>
  25. #include <queue>
  26. #include <thread>
  27. #include <tuple>
  28. #include <keystore/ExportResult.h>
  29. #include <keystore/KeyCharacteristics.h>
  30. #include <keystore/KeymasterBlob.h>
  31. #include <keystore/OperationResult.h>
  32. #include <keystore/keystore_return_types.h>
  33. #include "blob.h"
  34. #include "operation.h"
  35. namespace keystore {
  36. using android::sp;
  37. using ::android::hardware::hidl_vec;
  38. using ::android::hardware::Return;
  39. using ::android::hardware::Void;
  40. using android::hardware::keymaster::V4_0::ErrorCode;
  41. using android::hardware::keymaster::V4_0::HardwareAuthToken;
  42. using android::hardware::keymaster::V4_0::HmacSharingParameters;
  43. using android::hardware::keymaster::V4_0::KeyCharacteristics;
  44. using android::hardware::keymaster::V4_0::KeyFormat;
  45. using android::hardware::keymaster::V4_0::KeyParameter;
  46. using android::hardware::keymaster::V4_0::KeyPurpose;
  47. using android::hardware::keymaster::V4_0::VerificationToken;
  48. using android::hardware::keymaster::V4_0::support::Keymaster;
  49. // using KeystoreCharacteristics = ::android::security::keymaster::KeyCharacteristics;
  50. using ::android::security::keymaster::KeymasterBlob;
  51. class KeyStore;
  52. class Worker {
  53. /*
  54. * NonCopyableFunction works similar to std::function in that it wraps callable objects and
  55. * erases their type. The rationale for using a custom class instead of
  56. * std::function is that std::function requires the wrapped object to be copy contructible.
  57. * NonCopyableFunction is itself not copyable and never attempts to copy the wrapped object.
  58. * TODO use similar optimization as std::function to remove the extra make_unique allocation.
  59. */
  60. template <typename Fn> class NonCopyableFunction;
  61. template <typename Ret, typename... Args> class NonCopyableFunction<Ret(Args...)> {
  62. class NonCopyableFunctionBase {
  63. public:
  64. NonCopyableFunctionBase() = default;
  65. virtual ~NonCopyableFunctionBase() {}
  66. virtual Ret operator()(Args... args) = 0;
  67. NonCopyableFunctionBase(const NonCopyableFunctionBase&) = delete;
  68. NonCopyableFunctionBase& operator=(const NonCopyableFunctionBase&) = delete;
  69. };
  70. template <typename Fn>
  71. class NonCopyableFunctionTypeEraser : public NonCopyableFunctionBase {
  72. private:
  73. Fn f_;
  74. public:
  75. NonCopyableFunctionTypeEraser() = default;
  76. explicit NonCopyableFunctionTypeEraser(Fn f) : f_(std::move(f)) {}
  77. Ret operator()(Args... args) override { return f_(std::move(args)...); }
  78. };
  79. private:
  80. std::unique_ptr<NonCopyableFunctionBase> f_;
  81. public:
  82. NonCopyableFunction() = default;
  83. // NOLINTNEXTLINE(google-explicit-constructor)
  84. template <typename F> NonCopyableFunction(F f) {
  85. f_ = std::make_unique<NonCopyableFunctionTypeEraser<F>>(std::move(f));
  86. }
  87. NonCopyableFunction(NonCopyableFunction&& other) = default;
  88. NonCopyableFunction& operator=(NonCopyableFunction&& other) = default;
  89. NonCopyableFunction(const NonCopyableFunction& other) = delete;
  90. NonCopyableFunction& operator=(const NonCopyableFunction& other) = delete;
  91. Ret operator()(Args... args) {
  92. if (f_) return (*f_)(std::move(args)...);
  93. }
  94. };
  95. using WorkerTask = NonCopyableFunction<void()>;
  96. std::queue<WorkerTask> pending_requests_;
  97. std::mutex pending_requests_mutex_;
  98. std::condition_variable pending_requests_cond_var_;
  99. bool running_ = false;
  100. public:
  101. Worker();
  102. ~Worker();
  103. void addRequest(WorkerTask request);
  104. };
  105. template <typename... Args> struct MakeKeymasterWorkerCB;
  106. template <typename ErrorType, typename... Args>
  107. struct MakeKeymasterWorkerCB<ErrorType, std::function<void(Args...)>> {
  108. using type = std::function<void(ErrorType, std::tuple<std::decay_t<Args>...>&&)>;
  109. };
  110. template <typename ErrorType> struct MakeKeymasterWorkerCB<ErrorType> {
  111. using type = std::function<void(ErrorType)>;
  112. };
  113. template <typename... Args>
  114. using MakeKeymasterWorkerCB_t = typename MakeKeymasterWorkerCB<Args...>::type;
  115. class KeymasterWorker : protected Worker {
  116. private:
  117. sp<Keymaster> keymasterDevice_;
  118. OperationMap operationMap_;
  119. KeyStore* keyStore_;
  120. template <typename KMFn, typename ErrorType, typename... Args, size_t... I>
  121. void unwrap_tuple(KMFn kmfn, std::function<void(ErrorType)> cb,
  122. const std::tuple<Args...>& tuple, std::index_sequence<I...>) {
  123. cb(((*keymasterDevice_).*kmfn)(std::get<I>(tuple)...));
  124. }
  125. template <typename KMFn, typename ErrorType, typename... ReturnTypes, typename... Args,
  126. size_t... I>
  127. void unwrap_tuple(KMFn kmfn, std::function<void(ErrorType, std::tuple<ReturnTypes...>&&)> cb,
  128. const std::tuple<Args...>& tuple, std::index_sequence<I...>) {
  129. std::tuple<ReturnTypes...> returnValue;
  130. auto result = ((*keymasterDevice_).*kmfn)(
  131. std::get<I>(tuple)...,
  132. [&returnValue](const ReturnTypes&... args) { returnValue = std::make_tuple(args...); });
  133. cb(std::move(result), std::move(returnValue));
  134. }
  135. template <typename KMFn, typename ErrorType, typename... Args>
  136. void addRequest(KMFn kmfn, std::function<void(ErrorType)> cb, Args&&... args) {
  137. Worker::addRequest([this, kmfn, cb = std::move(cb),
  138. tuple = std::make_tuple(std::forward<Args>(args)...)]() {
  139. unwrap_tuple(kmfn, std::move(cb), tuple, std::index_sequence_for<Args...>{});
  140. });
  141. }
  142. template <typename KMFn, typename ErrorType, typename... ReturnTypes, typename... Args>
  143. void addRequest(KMFn kmfn, std::function<void(ErrorType, std::tuple<ReturnTypes...>&&)> cb,
  144. Args&&... args) {
  145. Worker::addRequest([this, kmfn, cb = std::move(cb),
  146. tuple = std::make_tuple(std::forward<Args>(args)...)]() {
  147. unwrap_tuple(kmfn, std::move(cb), tuple, std::index_sequence_for<Args...>{});
  148. });
  149. }
  150. std::tuple<KeyStoreServiceReturnCode, Blob>
  151. upgradeKeyBlob(const LockedKeyBlobEntry& lockedEntry, const AuthorizationSet& params);
  152. std::tuple<KeyStoreServiceReturnCode, KeyCharacteristics, Blob, Blob>
  153. createKeyCharacteristicsCache(const LockedKeyBlobEntry& lockedEntry,
  154. const hidl_vec<uint8_t>& clientId,
  155. const hidl_vec<uint8_t>& appData, Blob keyBlob, Blob charBlob);
  156. /**
  157. * Get the auth token for this operation from the auth token table.
  158. *
  159. * Returns NO_ERROR if the auth token was found or none was required. If not needed, the
  160. * token will be empty (which keymaster interprets as no auth token).
  161. * OP_AUTH_NEEDED if it is a per op authorization, no authorization token exists for
  162. * that operation and failOnTokenMissing is false.
  163. * KM_ERROR_KEY_USER_NOT_AUTHENTICATED if there is no valid auth token for the operation
  164. */
  165. std::pair<KeyStoreServiceReturnCode, HardwareAuthToken>
  166. getAuthToken(const KeyCharacteristics& characteristics, uint64_t handle, KeyPurpose purpose,
  167. bool failOnTokenMissing = true);
  168. KeyStoreServiceReturnCode abort(const sp<IBinder>& token);
  169. bool pruneOperation();
  170. KeyStoreServiceReturnCode getOperationAuthTokenIfNeeded(std::shared_ptr<Operation> op);
  171. void appendConfirmationTokenIfNeeded(const KeyCharacteristics& keyCharacteristics,
  172. hidl_vec<KeyParameter>* params);
  173. public:
  174. KeymasterWorker(sp<Keymaster> keymasterDevice, KeyStore* keyStore);
  175. void logIfKeymasterVendorError(ErrorCode ec) const;
  176. using worker_begin_cb = std::function<void(::android::security::keymaster::OperationResult)>;
  177. void begin(LockedKeyBlobEntry, sp<IBinder> appToken, Blob keyBlob, Blob charBlob,
  178. bool pruneable, KeyPurpose purpose, AuthorizationSet opParams,
  179. hidl_vec<uint8_t> entropy, worker_begin_cb worker_cb);
  180. using update_cb = std::function<void(::android::security::keymaster::OperationResult)>;
  181. void update(sp<IBinder> token, AuthorizationSet params, hidl_vec<uint8_t> data,
  182. update_cb _hidl_cb);
  183. using finish_cb = std::function<void(::android::security::keymaster::OperationResult)>;
  184. void finish(sp<IBinder> token, AuthorizationSet params, hidl_vec<uint8_t> input,
  185. hidl_vec<uint8_t> signature, hidl_vec<uint8_t> entorpy, finish_cb worker_cb);
  186. using abort_cb = std::function<void(KeyStoreServiceReturnCode)>;
  187. void abort(sp<IBinder> token, abort_cb _hidl_cb);
  188. using getHardwareInfo_cb = MakeKeymasterWorkerCB_t<Return<void>, Keymaster::getHardwareInfo_cb>;
  189. void getHardwareInfo(getHardwareInfo_cb _hidl_cb);
  190. using getHmacSharingParameters_cb =
  191. MakeKeymasterWorkerCB_t<Return<void>, Keymaster::getHmacSharingParameters_cb>;
  192. void getHmacSharingParameters(getHmacSharingParameters_cb _hidl_cb);
  193. using computeSharedHmac_cb =
  194. MakeKeymasterWorkerCB_t<Return<void>, Keymaster::computeSharedHmac_cb>;
  195. void computeSharedHmac(hidl_vec<HmacSharingParameters> params, computeSharedHmac_cb _hidl_cb);
  196. using verifyAuthorization_cb =
  197. std::function<void(KeyStoreServiceReturnCode ec, HardwareAuthToken, VerificationToken)>;
  198. void verifyAuthorization(uint64_t challenge, hidl_vec<KeyParameter> params,
  199. HardwareAuthToken token, verifyAuthorization_cb _hidl_cb);
  200. using addRngEntropy_cb = MakeKeymasterWorkerCB_t<Return<ErrorCode>>;
  201. void addRngEntropy(hidl_vec<uint8_t> data, addRngEntropy_cb _hidl_cb);
  202. using generateKey_cb = std::function<void(
  203. KeyStoreServiceReturnCode, ::android::hardware::keymaster::V4_0::KeyCharacteristics)>;
  204. void generateKey(LockedKeyBlobEntry, hidl_vec<KeyParameter> keyParams,
  205. hidl_vec<uint8_t> entropy, int flags, generateKey_cb _hidl_cb);
  206. using generateKey2_cb = MakeKeymasterWorkerCB_t<Return<void>, Keymaster::generateKey_cb>;
  207. void generateKey(hidl_vec<KeyParameter> keyParams, generateKey2_cb _hidl_cb);
  208. using getKeyCharacteristics_cb = std::function<void(
  209. KeyStoreServiceReturnCode, ::android::hardware::keymaster::V4_0::KeyCharacteristics)>;
  210. void getKeyCharacteristics(LockedKeyBlobEntry lockedEntry, hidl_vec<uint8_t> clientId,
  211. hidl_vec<uint8_t> appData, Blob keyBlob, Blob charBlob,
  212. getKeyCharacteristics_cb _hidl_cb);
  213. using importKey_cb = std::function<void(
  214. KeyStoreServiceReturnCode, ::android::hardware::keymaster::V4_0::KeyCharacteristics)>;
  215. void importKey(LockedKeyBlobEntry lockedEntry, hidl_vec<KeyParameter> params,
  216. KeyFormat keyFormat, hidl_vec<uint8_t> keyData, int flags,
  217. importKey_cb _hidl_cb);
  218. using importWrappedKey_cb = std::function<void(
  219. KeyStoreServiceReturnCode, ::android::hardware::keymaster::V4_0::KeyCharacteristics)>;
  220. void importWrappedKey(LockedKeyBlobEntry wrappingLockedEntry,
  221. LockedKeyBlobEntry wrapppedLockedEntry, hidl_vec<uint8_t> wrappedKeyData,
  222. hidl_vec<uint8_t> maskingKey, hidl_vec<KeyParameter> unwrappingParams,
  223. Blob wrappingBlob, Blob wrappingCharBlob, uint64_t passwordSid,
  224. uint64_t biometricSid, importWrappedKey_cb worker_cb);
  225. using exportKey_cb = std::function<void(::android::security::keymaster::ExportResult)>;
  226. void exportKey(LockedKeyBlobEntry lockedEntry, KeyFormat exportFormat,
  227. hidl_vec<uint8_t> clientId, hidl_vec<uint8_t> appData, Blob keyBlob,
  228. Blob charBlob, exportKey_cb _hidl_cb);
  229. using attestKey_cb = MakeKeymasterWorkerCB_t<Return<void>, Keymaster::attestKey_cb>;
  230. void attestKey(hidl_vec<uint8_t> keyToAttest, hidl_vec<KeyParameter> attestParams,
  231. attestKey_cb _hidl_cb);
  232. using deleteKey_cb = MakeKeymasterWorkerCB_t<Return<ErrorCode>>;
  233. void deleteKey(hidl_vec<uint8_t> keyBlob, deleteKey_cb _hidl_cb);
  234. using begin_cb = MakeKeymasterWorkerCB_t<Return<void>, Keymaster::begin_cb>;
  235. void begin(KeyPurpose purpose, hidl_vec<uint8_t> key, hidl_vec<KeyParameter> inParams,
  236. HardwareAuthToken authToken, begin_cb _hidl_cb);
  237. void binderDied(android::wp<IBinder> who);
  238. const Keymaster::VersionResult& halVersion() { return keymasterDevice_->halVersion(); }
  239. };
  240. } // namespace keystore
  241. #endif // KEYSTORE_KEYMASTER_WORKER_H_