blob: 2a35977a297917961ed23be368b5912e08cde092 [file] [log] [blame]
Janis Danisevskisff3d7f42018-10-08 07:15:09 -07001/*
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
18#ifndef KEYSTORE_KEYMASTER_WORKER_H_
19#define KEYSTORE_KEYMASTER_WORKER_H_
20
21#include <condition_variable>
22#include <functional>
23#include <keymasterV4_0/Keymaster.h>
24#include <memory>
25#include <mutex>
26#include <optional>
27#include <queue>
28#include <thread>
29#include <tuple>
30
31#include <keystore/ExportResult.h>
32#include <keystore/KeyCharacteristics.h>
33#include <keystore/KeymasterBlob.h>
34#include <keystore/OperationResult.h>
35#include <keystore/keystore_return_types.h>
36
37#include "blob.h"
38#include "operation.h"
39
40namespace keystore {
41
42using android::sp;
43using ::android::hardware::hidl_vec;
44using ::android::hardware::Return;
45using ::android::hardware::Void;
46using android::hardware::keymaster::V4_0::ErrorCode;
47using android::hardware::keymaster::V4_0::HardwareAuthToken;
48using android::hardware::keymaster::V4_0::HmacSharingParameters;
49using android::hardware::keymaster::V4_0::KeyCharacteristics;
50using android::hardware::keymaster::V4_0::KeyFormat;
51using android::hardware::keymaster::V4_0::KeyParameter;
52using android::hardware::keymaster::V4_0::KeyPurpose;
53using android::hardware::keymaster::V4_0::VerificationToken;
54using android::hardware::keymaster::V4_0::support::Keymaster;
55// using KeystoreCharacteristics = ::android::security::keymaster::KeyCharacteristics;
56using ::android::security::keymaster::KeymasterBlob;
57
58class KeyStore;
59
60class Worker {
61
62 /*
63 * NonCopyableFunction works similar to std::function in that it wraps callable objects and
64 * erases their type. The rationale for using a custom class instead of
65 * std::function is that std::function requires the wrapped object to be copy contructible.
66 * NonCopyableFunction is itself not copyable and never attempts to copy the wrapped object.
67 * TODO use similar optimization as std::function to remove the extra make_unique allocation.
68 */
69 template <typename Fn> class NonCopyableFunction;
70
71 template <typename Ret, typename... Args> class NonCopyableFunction<Ret(Args...)> {
72
73 class NonCopyableFunctionBase {
74 public:
75 NonCopyableFunctionBase() = default;
76 virtual ~NonCopyableFunctionBase() {}
77 virtual Ret operator()(Args... args) = 0;
78 NonCopyableFunctionBase(const NonCopyableFunctionBase&) = delete;
79 NonCopyableFunctionBase& operator=(const NonCopyableFunctionBase&) = delete;
80 };
81
82 template <typename Fn>
83 class NonCopyableFunctionTypeEraser : public NonCopyableFunctionBase {
84 private:
85 Fn f_;
86
87 public:
88 NonCopyableFunctionTypeEraser() = default;
89 explicit NonCopyableFunctionTypeEraser(Fn f) : f_(std::move(f)) {}
90 Ret operator()(Args... args) override { return f_(std::move(args)...); }
91 };
92
93 private:
94 std::unique_ptr<NonCopyableFunctionBase> f_;
95
96 public:
97 NonCopyableFunction() = default;
98 template <typename F> NonCopyableFunction(F f) {
99 f_ = std::make_unique<NonCopyableFunctionTypeEraser<F>>(std::move(f));
100 }
101 NonCopyableFunction(NonCopyableFunction&& other) = default;
102 NonCopyableFunction& operator=(NonCopyableFunction&& other) = default;
103 NonCopyableFunction(const NonCopyableFunction& other) = delete;
104 NonCopyableFunction& operator=(const NonCopyableFunction& other) = delete;
105
106 Ret operator()(Args... args) {
107 if (f_) return (*f_)(std::move(args)...);
108 }
109 };
110
111 using WorkerTask = NonCopyableFunction<void()>;
112
113 std::queue<WorkerTask> pending_requests_;
114 std::mutex pending_requests_mutex_;
115 std::condition_variable pending_requests_cond_var_;
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700116 bool running_ = false;
117
118 public:
119 Worker();
120 ~Worker();
121 void addRequest(WorkerTask request);
122};
123
124template <typename... Args> struct MakeKeymasterWorkerCB;
125
126template <typename ErrorType, typename... Args>
127struct MakeKeymasterWorkerCB<ErrorType, std::function<void(Args...)>> {
128 using type = std::function<void(ErrorType, std::tuple<std::decay_t<Args>...>&&)>;
129};
130
131template <typename ErrorType> struct MakeKeymasterWorkerCB<ErrorType> {
132 using type = std::function<void(ErrorType)>;
133};
134
135template <typename... Args>
136using MakeKeymasterWorkerCB_t = typename MakeKeymasterWorkerCB<Args...>::type;
137
138class KeymasterWorker : protected Worker {
139 private:
140 sp<Keymaster> keymasterDevice_;
141 OperationMap operationMap_;
142 KeyStore* keyStore_;
143
144 template <typename KMFn, typename ErrorType, typename... Args, size_t... I>
145 void unwrap_tuple(KMFn kmfn, std::function<void(ErrorType)> cb,
146 const std::tuple<Args...>& tuple, std::index_sequence<I...>) {
147 cb(((*keymasterDevice_).*kmfn)(std::get<I>(tuple)...));
148 }
149
150 template <typename KMFn, typename ErrorType, typename... ReturnTypes, typename... Args,
151 size_t... I>
152 void unwrap_tuple(KMFn kmfn, std::function<void(ErrorType, std::tuple<ReturnTypes...>&&)> cb,
153 const std::tuple<Args...>& tuple, std::index_sequence<I...>) {
154 std::tuple<ReturnTypes...> returnValue;
155 auto result = ((*keymasterDevice_).*kmfn)(
156 std::get<I>(tuple)...,
157 [&returnValue](const ReturnTypes&... args) { returnValue = std::make_tuple(args...); });
158 cb(std::move(result), std::move(returnValue));
159 }
160
161 template <typename KMFn, typename ErrorType, typename... Args>
162 void addRequest(KMFn kmfn, std::function<void(ErrorType)> cb, Args&&... args) {
163 Worker::addRequest([this, kmfn, cb = std::move(cb),
164 tuple = std::make_tuple(std::forward<Args>(args)...)]() {
165 unwrap_tuple(kmfn, std::move(cb), tuple, std::index_sequence_for<Args...>{});
166 });
167 }
168
169 template <typename KMFn, typename ErrorType, typename... ReturnTypes, typename... Args>
170 void addRequest(KMFn kmfn, std::function<void(ErrorType, std::tuple<ReturnTypes...>&&)> cb,
171 Args&&... args) {
172 Worker::addRequest([this, kmfn, cb = std::move(cb),
173 tuple = std::make_tuple(std::forward<Args>(args)...)]() {
174 unwrap_tuple(kmfn, std::move(cb), tuple, std::index_sequence_for<Args...>{});
175 });
176 }
177 std::tuple<KeyStoreServiceReturnCode, Blob>
178 upgradeKeyBlob(const LockedKeyBlobEntry& lockedEntry, const AuthorizationSet& params);
179 std::tuple<KeyStoreServiceReturnCode, KeyCharacteristics, Blob, Blob>
180 createKeyCharacteristicsCache(const LockedKeyBlobEntry& lockedEntry,
181 const hidl_vec<uint8_t>& clientId,
182 const hidl_vec<uint8_t>& appData, Blob keyBlob, Blob charBlob);
183
184 /**
185 * Get the auth token for this operation from the auth token table.
186 *
187 * Returns NO_ERROR if the auth token was found or none was required. If not needed, the
188 * token will be empty (which keymaster interprets as no auth token).
189 * OP_AUTH_NEEDED if it is a per op authorization, no authorization token exists for
190 * that operation and failOnTokenMissing is false.
191 * KM_ERROR_KEY_USER_NOT_AUTHENTICATED if there is no valid auth token for the operation
192 */
193 std::pair<KeyStoreServiceReturnCode, HardwareAuthToken>
194 getAuthToken(const KeyCharacteristics& characteristics, uint64_t handle, KeyPurpose purpose,
195 bool failOnTokenMissing = true);
196
197 KeyStoreServiceReturnCode abort(const sp<IBinder>& token);
198
199 bool pruneOperation();
200
201 KeyStoreServiceReturnCode getOperationAuthTokenIfNeeded(std::shared_ptr<Operation> op);
202
203 void appendConfirmationTokenIfNeeded(const KeyCharacteristics& keyCharacteristics,
204 hidl_vec<KeyParameter>* params);
205
206 public:
207 KeymasterWorker(sp<Keymaster> keymasterDevice, KeyStore* keyStore);
208
209 using worker_begin_cb = std::function<void(::android::security::keymaster::OperationResult)>;
210 void begin(LockedKeyBlobEntry, sp<IBinder> appToken, Blob keyBlob, Blob charBlob,
211 bool pruneable, KeyPurpose purpose, AuthorizationSet opParams,
212 hidl_vec<uint8_t> entropy, worker_begin_cb worker_cb);
213
214 using update_cb = std::function<void(::android::security::keymaster::OperationResult)>;
215 void update(sp<IBinder> token, AuthorizationSet params, hidl_vec<uint8_t> data,
216 update_cb _hidl_cb);
217
218 using finish_cb = std::function<void(::android::security::keymaster::OperationResult)>;
219 void finish(sp<IBinder> token, AuthorizationSet params, hidl_vec<uint8_t> input,
220 hidl_vec<uint8_t> signature, hidl_vec<uint8_t> entorpy, finish_cb worker_cb);
221
222 using abort_cb = std::function<void(KeyStoreServiceReturnCode)>;
223 void abort(sp<IBinder> token, abort_cb _hidl_cb);
224
225 using getHardwareInfo_cb = MakeKeymasterWorkerCB_t<Return<void>, Keymaster::getHardwareInfo_cb>;
226 void getHardwareInfo(getHardwareInfo_cb _hidl_cb);
227
228 using getHmacSharingParameters_cb =
229 MakeKeymasterWorkerCB_t<Return<void>, Keymaster::getHmacSharingParameters_cb>;
230 void getHmacSharingParameters(getHmacSharingParameters_cb _hidl_cb);
231
232 using computeSharedHmac_cb =
233 MakeKeymasterWorkerCB_t<Return<void>, Keymaster::computeSharedHmac_cb>;
234 void computeSharedHmac(hidl_vec<HmacSharingParameters> params, computeSharedHmac_cb _hidl_cb);
235
236 using verifyAuthorization_cb =
237 std::function<void(KeyStoreServiceReturnCode ec, HardwareAuthToken, VerificationToken)>;
238 void verifyAuthorization(uint64_t challenge, hidl_vec<KeyParameter> params,
239 HardwareAuthToken token, verifyAuthorization_cb _hidl_cb);
240
241 using addRngEntropy_cb = MakeKeymasterWorkerCB_t<Return<ErrorCode>>;
242 void addRngEntropy(hidl_vec<uint8_t> data, addRngEntropy_cb _hidl_cb);
243
244 using generateKey_cb = std::function<void(
245 KeyStoreServiceReturnCode, ::android::hardware::keymaster::V4_0::KeyCharacteristics)>;
246 void generateKey(LockedKeyBlobEntry, hidl_vec<KeyParameter> keyParams,
247 hidl_vec<uint8_t> entropy, int flags, generateKey_cb _hidl_cb);
248
249 using generateKey2_cb = MakeKeymasterWorkerCB_t<Return<void>, Keymaster::generateKey_cb>;
250 void generateKey(hidl_vec<KeyParameter> keyParams, generateKey2_cb _hidl_cb);
251
252 using getKeyCharacteristics_cb = std::function<void(
253 KeyStoreServiceReturnCode, ::android::hardware::keymaster::V4_0::KeyCharacteristics)>;
254 void getKeyCharacteristics(LockedKeyBlobEntry lockedEntry, hidl_vec<uint8_t> clientId,
255 hidl_vec<uint8_t> appData, Blob keyBlob, Blob charBlob,
256 getKeyCharacteristics_cb _hidl_cb);
257
258 using importKey_cb = std::function<void(
259 KeyStoreServiceReturnCode, ::android::hardware::keymaster::V4_0::KeyCharacteristics)>;
260 void importKey(LockedKeyBlobEntry lockedEntry, hidl_vec<KeyParameter> params,
261 KeyFormat keyFormat, hidl_vec<uint8_t> keyData, int flags,
262 importKey_cb _hidl_cb);
263
264 using importWrappedKey_cb = std::function<void(
265 KeyStoreServiceReturnCode, ::android::hardware::keymaster::V4_0::KeyCharacteristics)>;
266 void importWrappedKey(LockedKeyBlobEntry wrappingLockedEntry,
267 LockedKeyBlobEntry wrapppedLockedEntry, hidl_vec<uint8_t> wrappedKeyData,
268 hidl_vec<uint8_t> maskingKey, hidl_vec<KeyParameter> unwrappingParams,
269 Blob wrappingBlob, Blob wrappingCharBlob, uint64_t passwordSid,
270 uint64_t biometricSid, importWrappedKey_cb worker_cb);
271
272 using exportKey_cb = std::function<void(::android::security::keymaster::ExportResult)>;
273 void exportKey(LockedKeyBlobEntry lockedEntry, KeyFormat exportFormat,
274 hidl_vec<uint8_t> clientId, hidl_vec<uint8_t> appData, Blob keyBlob,
275 Blob charBlob, exportKey_cb _hidl_cb);
276
277 using attestKey_cb = MakeKeymasterWorkerCB_t<Return<void>, Keymaster::attestKey_cb>;
278 void attestKey(hidl_vec<uint8_t> keyToAttest, hidl_vec<KeyParameter> attestParams,
279 attestKey_cb _hidl_cb);
280
281 using upgradeKey_cb = MakeKeymasterWorkerCB_t<Return<void>, Keymaster::upgradeKey_cb>;
282 void upgradeKey(hidl_vec<uint8_t> keyBlobToUpgrade, hidl_vec<KeyParameter> upgradeParams,
283 upgradeKey_cb _hidl_cb);
284
285 using deleteKey_cb = MakeKeymasterWorkerCB_t<Return<ErrorCode>>;
286 void deleteKey(hidl_vec<uint8_t> keyBlob, deleteKey_cb _hidl_cb);
287
288 using deleteAllKeys_cb = MakeKeymasterWorkerCB_t<Return<ErrorCode>>;
289 void deleteAllKeys(deleteAllKeys_cb _hidl_cb);
290
291 using destroyAttestationIds_cb = MakeKeymasterWorkerCB_t<Return<ErrorCode>>;
292 void destroyAttestationIds(destroyAttestationIds_cb _hidl_cb);
293
294 using begin_cb = MakeKeymasterWorkerCB_t<Return<void>, Keymaster::begin_cb>;
295 void begin(KeyPurpose purpose, hidl_vec<uint8_t> key, hidl_vec<KeyParameter> inParams,
296 HardwareAuthToken authToken, begin_cb _hidl_cb);
297
298 void binderDied(android::wp<IBinder> who);
299
300 const Keymaster::VersionResult& halVersion() { return keymasterDevice_->halVersion(); }
301};
302
303} // namespace keystore
304
305#endif // KEYSTORE_KEYMASTER_WORKER_H_