1 #include <android-base/logging.h>
2 #include <android/security/keystore/BnKeystoreOperationResultCallback.h>
3 #include <android/security/keystore/BnKeystoreResponseCallback.h>
4 #include <android/security/keystore/IKeystoreService.h>
5 #include <binder/IServiceManager.h>
6 #include <private/android_filesystem_config.h>
7 
8 #include <keystore/KeyCharacteristics.h>
9 #include <keystore/KeymasterArguments.h>
10 #include <keystore/KeymasterBlob.h>
11 #include <keystore/KeystoreResponse.h>
12 #include <keystore/OperationResult.h>
13 #include <keystore/keymaster_types.h>
14 #include <keystore/keystore.h>
15 #include <keystore/keystore_hidl_support.h>
16 #include <keystore/keystore_promises.h>
17 #include <keystore/keystore_return_types.h>
18 
19 #include <future>
20 #include <vector>
21 #include "include/wifikeystorehal/keystore.h"
22 
23 using android::hardware::keymaster::V4_0::Algorithm;
24 using android::hardware::keymaster::V4_0::authorizationValue;
25 using android::hardware::keymaster::V4_0::Digest;
26 using android::hardware::keymaster::V4_0::KeyFormat;
27 using android::hardware::keymaster::V4_0::KeyParameter;
28 using android::hardware::keymaster::V4_0::KeyPurpose;
29 using android::hardware::keymaster::V4_0::NullOr;
30 using android::hardware::keymaster::V4_0::PaddingMode;
31 using android::hardware::keymaster::V4_0::TAG_ALGORITHM;
32 using android::hardware::keymaster::V4_0::TAG_DIGEST;
33 using android::hardware::keymaster::V4_0::TAG_PADDING;
34 using android::security::keymaster::ExportResult;
35 using android::security::keymaster::KeyCharacteristics;
36 using android::security::keymaster::KeymasterArguments;
37 using android::security::keymaster::KeymasterBlob;
38 using android::security::keymaster::OperationResult;
39 
40 using KSReturn = keystore::KeyStoreNativeReturnCode;
41 
42 namespace {
43 constexpr const char kKeystoreServiceName[] = "android.security.keystore";
44 constexpr int32_t UID_SELF = -1;
45 
46 using keystore::KeyCharacteristicsPromise;
47 using keystore::KeystoreExportPromise;
48 using keystore::KeystoreResponsePromise;
49 using keystore::OperationResultPromise;
50 
51 };  // namespace
52 
53 #define AT __func__ << ":" << __LINE__ << " "
54 
55 namespace android {
56 namespace system {
57 namespace wifi {
58 namespace keystore {
59 namespace V1_0 {
60 namespace implementation {
61 
62 using security::keystore::IKeystoreService;
63 // Methods from ::android::hardware::wifi::keystore::V1_0::IKeystore follow.
getBlob(const hidl_string & key,getBlob_cb _hidl_cb)64 Return<void> Keystore::getBlob(const hidl_string& key, getBlob_cb _hidl_cb) {
65     sp<IKeystoreService> service = interface_cast<IKeystoreService>(
66         defaultServiceManager()->getService(String16(kKeystoreServiceName)));
67     if (service == nullptr) {
68         _hidl_cb(KeystoreStatusCode::ERROR_UNKNOWN, {});
69         return Void();
70     }
71     ::std::vector<uint8_t> value;
72     // Retrieve the blob as wifi user.
73     auto ret = service->get(String16(key.c_str()), AID_WIFI, &value);
74     if (!ret.isOk()) {
75         _hidl_cb(KeystoreStatusCode::ERROR_UNKNOWN, {});
76         return Void();
77     }
78     _hidl_cb(KeystoreStatusCode::SUCCESS, (hidl_vec<uint8_t>)value);
79     return Void();
80 }
81 
getPublicKey(const hidl_string & keyId,getPublicKey_cb _hidl_cb)82 Return<void> Keystore::getPublicKey(const hidl_string& keyId, getPublicKey_cb _hidl_cb) {
83     sp<IServiceManager> sm = defaultServiceManager();
84     sp<IBinder> binder = sm->getService(String16(kKeystoreServiceName));
85     sp<IKeystoreService> service = interface_cast<IKeystoreService>(binder);
86 
87     if (service == nullptr) {
88         LOG(ERROR) << AT << "could not contact keystore";
89         _hidl_cb(KeystoreStatusCode::ERROR_UNKNOWN, {});
90         return Void();
91     }
92 
93     int32_t error_code;
94     android::sp<KeystoreExportPromise> promise(new KeystoreExportPromise);
95     auto future = promise->get_future();
96     auto binder_result = service->exportKey(
97         promise, String16(keyId.c_str()), static_cast<int32_t>(KeyFormat::X509),
98         KeymasterBlob() /* clientId */, KeymasterBlob() /* appData */, UID_SELF, &error_code);
99     if (!binder_result.isOk()) {
100         LOG(ERROR) << AT << "communication error while calling keystore";
101         _hidl_cb(KeystoreStatusCode::ERROR_UNKNOWN, {});
102         return Void();
103     }
104 
105     KSReturn rc(error_code);
106     if (!rc.isOk()) {
107         LOG(ERROR) << AT << "exportKey failed: " << error_code;
108         _hidl_cb(KeystoreStatusCode::ERROR_UNKNOWN, {});
109         return Void();
110     }
111 
112     auto export_result = future.get();
113     if (!export_result.resultCode.isOk()) {
114         LOG(ERROR) << AT << "exportKey failed: " << export_result.resultCode;
115         _hidl_cb(KeystoreStatusCode::ERROR_UNKNOWN, {});
116         return Void();
117     }
118 
119     _hidl_cb(KeystoreStatusCode::SUCCESS, export_result.exportData);
120     return Void();
121 }
122 
getKeyAlgoritmFromKeyCharacteristics(const::android::security::keymaster::KeyCharacteristics & characteristics)123 static NullOr<const Algorithm&> getKeyAlgoritmFromKeyCharacteristics(
124     const ::android::security::keymaster::KeyCharacteristics& characteristics) {
125     for (const auto& param : characteristics.hardwareEnforced.getParameters()) {
126         auto algo = authorizationValue(TAG_ALGORITHM, param);
127         if (algo.isOk()) return algo;
128     }
129     for (const auto& param : characteristics.softwareEnforced.getParameters()) {
130         auto algo = authorizationValue(TAG_ALGORITHM, param);
131         if (algo.isOk()) return algo;
132     }
133     return {};
134 }
135 
sign(const hidl_string & keyId,const hidl_vec<uint8_t> & dataToSign,sign_cb _hidl_cb)136 Return<void> Keystore::sign(const hidl_string& keyId, const hidl_vec<uint8_t>& dataToSign,
137                             sign_cb _hidl_cb) {
138     sp<IServiceManager> sm = defaultServiceManager();
139     sp<IBinder> binder = sm->getService(String16(kKeystoreServiceName));
140     sp<IKeystoreService> service = interface_cast<IKeystoreService>(binder);
141 
142     if (service == nullptr) {
143         LOG(ERROR) << AT << "could not contact keystore";
144         _hidl_cb(KeystoreStatusCode::ERROR_UNKNOWN, {});
145         return Void();
146     }
147 
148     String16 key_name16(keyId.c_str());
149     int32_t error_code;
150     android::sp<KeyCharacteristicsPromise> kc_promise(new KeyCharacteristicsPromise);
151     auto kc_future = kc_promise->get_future();
152     auto binder_result = service->getKeyCharacteristics(kc_promise, key_name16, KeymasterBlob(),
153                                                         KeymasterBlob(), UID_SELF, &error_code);
154     if (!binder_result.isOk()) {
155         LOG(ERROR) << AT << "communication error while calling keystore";
156         _hidl_cb(KeystoreStatusCode::ERROR_UNKNOWN, {});
157         return Void();
158     }
159     KSReturn rc(error_code);
160     if (!rc.isOk()) {
161         LOG(ERROR) << AT << "getKeyCharacteristics failed: " << error_code;
162         _hidl_cb(KeystoreStatusCode::ERROR_UNKNOWN, {});
163         return Void();
164     }
165 
166     auto [km_response, characteristics] = kc_future.get();
167 
168     if (!KSReturn(km_response.response_code()).isOk()) {
169         LOG(ERROR) << AT << "getKeyCharacteristics failed: " << km_response.response_code();
170         _hidl_cb(KeystoreStatusCode::ERROR_UNKNOWN, {});
171         return Void();
172     }
173 
174     auto algorithm = getKeyAlgoritmFromKeyCharacteristics(characteristics);
175     if (!algorithm.isOk()) {
176         LOG(ERROR) << AT << "could not get algorithm from key characteristics";
177         _hidl_cb(KeystoreStatusCode::ERROR_UNKNOWN, {});
178         return Void();
179     }
180 
181     hidl_vec<KeyParameter> params(3);
182     params[0] = Authorization(TAG_DIGEST, Digest::NONE);
183     params[1] = Authorization(TAG_PADDING, PaddingMode::NONE);
184     params[2] = Authorization(TAG_ALGORITHM, algorithm.value());
185 
186     android::sp<android::IBinder> token(new android::BBinder);
187     sp<OperationResultPromise> promise(new OperationResultPromise());
188     auto future = promise->get_future();
189     binder_result = service->begin(promise, token, key_name16, (int)KeyPurpose::SIGN,
190                                    true /*pruneable*/, KeymasterArguments(params),
191                                    std::vector<uint8_t>() /* entropy */, UID_SELF, &error_code);
192     if (!binder_result.isOk()) {
193         LOG(ERROR) << AT << "communication error while calling keystore";
194         _hidl_cb(KeystoreStatusCode::ERROR_UNKNOWN, {});
195         return Void();
196     }
197 
198     rc = KSReturn(error_code);
199     if (!rc.isOk()) {
200         LOG(ERROR) << AT << "Keystore begin returned: " << rc;
201         _hidl_cb(KeystoreStatusCode::ERROR_UNKNOWN, {});
202         return Void();
203     }
204 
205     OperationResult result = future.get();
206     if (!result.resultCode.isOk()) {
207         LOG(ERROR) << AT << "begin failed: " << result.resultCode;
208         _hidl_cb(KeystoreStatusCode::ERROR_UNKNOWN, {});
209         return Void();
210     }
211     auto handle = std::move(result.token);
212 
213     const uint8_t* in = dataToSign.data();
214     size_t len = dataToSign.size();
215     do {
216         promise = new OperationResultPromise();
217         future = promise->get_future();
218         binder_result = service->update(promise, handle, KeymasterArguments(params),
219                                         std::vector<uint8_t>(in, in + len), &error_code);
220         if (!binder_result.isOk()) {
221             LOG(ERROR) << AT << "communication error while calling keystore";
222             _hidl_cb(KeystoreStatusCode::ERROR_UNKNOWN, {});
223             return Void();
224         }
225 
226         rc = KSReturn(error_code);
227         if (!rc.isOk()) {
228             LOG(ERROR) << AT << "Keystore update returned: " << rc;
229             _hidl_cb(KeystoreStatusCode::ERROR_UNKNOWN, {});
230             return Void();
231         }
232 
233         result = future.get();
234 
235         if (!result.resultCode.isOk()) {
236             LOG(ERROR) << AT << "update failed: " << result.resultCode;
237             _hidl_cb(KeystoreStatusCode::ERROR_UNKNOWN, {});
238             return Void();
239         }
240         if ((size_t)result.inputConsumed > len) {
241             LOG(ERROR) << AT << "update consumed more data than provided";
242             sp<KeystoreResponsePromise> abortPromise(new KeystoreResponsePromise);
243             auto abortFuture = abortPromise->get_future();
244             binder_result = service->abort(abortPromise, handle, &error_code);
245             if (!binder_result.isOk()) {
246                 LOG(ERROR) << AT << "communication error while calling keystore";
247                 _hidl_cb(KeystoreStatusCode::ERROR_UNKNOWN, {});
248                 return Void();
249             }
250             // This is mainly for logging since we already failed.
251             // But if abort returned OK we have to wait untill abort calls the callback
252             // hence the call to abortFuture.get().
253             if (!KSReturn(error_code).isOk()) {
254                 LOG(ERROR) << AT << "abort failed: " << error_code;
255             } else if (!(rc = KSReturn(abortFuture.get().response_code())).isOk()) {
256                 LOG(ERROR) << AT << "abort failed: " << rc;
257             }
258             _hidl_cb(KeystoreStatusCode::ERROR_UNKNOWN, {});
259             return Void();
260         }
261         len -= result.inputConsumed;
262         in += result.inputConsumed;
263     } while (len > 0);
264 
265     future = {};
266     promise = new OperationResultPromise();
267     future = promise->get_future();
268 
269     binder_result = service->finish(
270         promise, handle, KeymasterArguments(params), std::vector<uint8_t>() /* input */,
271         std::vector<uint8_t>() /* signature */, std::vector<uint8_t>() /* entropy */, &error_code);
272     if (!binder_result.isOk()) {
273         LOG(ERROR) << AT << "communication error while calling keystore";
274         _hidl_cb(KeystoreStatusCode::ERROR_UNKNOWN, {});
275         return Void();
276     }
277 
278     rc = KSReturn(error_code);
279     if (!rc.isOk()) {
280         LOG(ERROR) << AT << "Keystore finish returned: " << rc;
281         _hidl_cb(KeystoreStatusCode::ERROR_UNKNOWN, {});
282         return Void();
283     }
284 
285     result = future.get();
286 
287     if (!result.resultCode.isOk()) {
288         LOG(ERROR) << AT << "finish failed: " << result.resultCode;
289         _hidl_cb(KeystoreStatusCode::ERROR_UNKNOWN, {});
290         return Void();
291     }
292 
293     _hidl_cb(KeystoreStatusCode::SUCCESS, result.data);
294     return Void();
295 }
296 
HIDL_FETCH_IKeystore(const char *)297 IKeystore* HIDL_FETCH_IKeystore(const char* /* name */) {
298     return new Keystore();
299 }
300 }  // namespace implementation
301 }  // namespace V1_0
302 }  // namespace keystore
303 }  // namespace wifi
304 }  // namespace system
305 }  // namespace android
306