1 /*
2 * Copyright (C) 2021 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
17 #include "keystore2_engine.h"
18
19 #include <aidl/android/system/keystore2/IKeystoreService.h>
20 #include <android-base/logging.h>
21 #include <android-base/strings.h>
22 #include <android/binder_manager.h>
23
24 #include <private/android_filesystem_config.h>
25
26 #include <openssl/bio.h>
27 #include <openssl/bn.h>
28 #include <openssl/ec.h>
29 #include <openssl/ec_key.h>
30 #include <openssl/ecdsa.h>
31 #include <openssl/engine.h>
32 #include <openssl/pem.h>
33 #include <openssl/rsa.h>
34 #include <openssl/x509.h>
35
36 #define AT __func__ << ":" << __LINE__ << " "
37
38 constexpr const char keystore2_service_name[] = "android.system.keystore2.IKeystoreService/default";
39 const std::string keystore2_grant_id_prefix("ks2_keystore-engine_grant_id:");
40
41 /**
42 * Keystore 2.0 namespace identifiers.
43 * Keep in sync with system/sepolicy/private/keystore2_key_contexts.
44 */
45 constexpr const int64_t KS2_NAMESPACE_WIFI = 102;
46
47 namespace ks2 = ::aidl::android::system::keystore2;
48 namespace KMV1 = ::aidl::android::hardware::security::keymint;
49
50 namespace {
51
getNamespaceforCurrentUid()52 int64_t getNamespaceforCurrentUid() {
53 auto uid = getuid();
54 switch (uid) {
55 case AID_WIFI:
56 return KS2_NAMESPACE_WIFI;
57 // 0 is the super user namespace, and nothing has access to this namespace on user builds.
58 // So this will always fail.
59 default:
60 return 0;
61 }
62 }
63
64 struct Keystore2KeyBackend {
65 ks2::KeyDescriptor descriptor_;
66 std::shared_ptr<ks2::IKeystoreSecurityLevel> i_keystore_security_level_;
67 };
68
69 /* key_backend_dup is called when one of the RSA or EC_KEY objects is duplicated. */
key_backend_dup(CRYPTO_EX_DATA *,const CRYPTO_EX_DATA *,void ** from_d,int,long,void *)70 extern "C" int key_backend_dup(CRYPTO_EX_DATA* /* to */, const CRYPTO_EX_DATA* /* from */,
71 void** from_d, int /* index */, long /* argl */, void* /* argp */) {
72 auto key_backend = reinterpret_cast<std::shared_ptr<Keystore2KeyBackend>*>(*from_d);
73 if (key_backend != nullptr) {
74 *from_d = new std::shared_ptr<Keystore2KeyBackend>(*key_backend);
75 }
76 return 1;
77 }
78
79 /* key_backend_free is called when one of the RSA, DSA or EC_KEY object is freed. */
key_backend_free(void *,void * ptr,CRYPTO_EX_DATA *,int,long,void *)80 extern "C" void key_backend_free(void* /* parent */, void* ptr, CRYPTO_EX_DATA* /* ad */,
81 int /* index */, long /* argl */, void* /* argp */) {
82 delete reinterpret_cast<std::shared_ptr<Keystore2KeyBackend>*>(ptr);
83 }
84
85 extern "C" int rsa_private_transform(RSA* rsa, uint8_t* out, const uint8_t* in, size_t len);
86 extern "C" int ecdsa_sign(const uint8_t* digest, size_t digest_len, uint8_t* sig,
87 unsigned int* sig_len, EC_KEY* ec_key);
88 /* KeystoreEngine is a BoringSSL ENGINE that implements RSA and ECDSA by
89 * forwarding the requested operations to Keystore. */
90 class Keystore2Engine {
91 public:
Keystore2Engine()92 Keystore2Engine()
93 : rsa_index_(RSA_get_ex_new_index(0 /* argl */, nullptr /* argp */, nullptr /* new_func */,
94 key_backend_dup, key_backend_free)),
95 ec_key_index_(EC_KEY_get_ex_new_index(0 /* argl */, nullptr /* argp */,
96 nullptr /* new_func */, key_backend_dup,
97 key_backend_free)),
98 engine_(ENGINE_new()) {
99 memset(&rsa_method_, 0, sizeof(rsa_method_));
100 rsa_method_.common.is_static = 1;
101 rsa_method_.private_transform = rsa_private_transform;
102 rsa_method_.flags = RSA_FLAG_OPAQUE;
103 ENGINE_set_RSA_method(engine_, &rsa_method_, sizeof(rsa_method_));
104
105 memset(&ecdsa_method_, 0, sizeof(ecdsa_method_));
106 ecdsa_method_.common.is_static = 1;
107 ecdsa_method_.sign = ecdsa_sign;
108 ecdsa_method_.flags = ECDSA_FLAG_OPAQUE;
109 ENGINE_set_ECDSA_method(engine_, &ecdsa_method_, sizeof(ecdsa_method_));
110 }
111
rsa_ex_index() const112 int rsa_ex_index() const { return rsa_index_; }
ec_key_ex_index() const113 int ec_key_ex_index() const { return ec_key_index_; }
114
engine() const115 const ENGINE* engine() const { return engine_; }
116
get()117 static const Keystore2Engine& get() {
118 static Keystore2Engine engine;
119 return engine;
120 }
121
122 private:
123 const int rsa_index_;
124 const int ec_key_index_;
125 RSA_METHOD rsa_method_;
126 ECDSA_METHOD ecdsa_method_;
127 ENGINE* const engine_;
128 };
129
130 #define OWNERSHIP_TRANSFERRED(x) x.release()
131
132 /* wrap_rsa returns an |EVP_PKEY| that contains an RSA key where the public
133 * part is taken from |public_rsa| and the private operations are forwarded to
134 * KeyStore and operate on the key named |key_id|. */
wrap_rsa(std::shared_ptr<Keystore2KeyBackend> key_backend,const RSA * public_rsa)135 bssl::UniquePtr<EVP_PKEY> wrap_rsa(std::shared_ptr<Keystore2KeyBackend> key_backend,
136 const RSA* public_rsa) {
137 bssl::UniquePtr<RSA> rsa(RSA_new_method(Keystore2Engine::get().engine()));
138 if (rsa.get() == nullptr) {
139 return nullptr;
140 }
141
142 auto key_backend_copy = new decltype(key_backend)(key_backend);
143
144 if (!RSA_set_ex_data(rsa.get(), Keystore2Engine::get().rsa_ex_index(), key_backend_copy)) {
145 delete key_backend_copy;
146 return nullptr;
147 }
148
149 rsa->n = BN_dup(public_rsa->n);
150 rsa->e = BN_dup(public_rsa->e);
151 if (rsa->n == nullptr || rsa->e == nullptr) {
152 return nullptr;
153 }
154
155 bssl::UniquePtr<EVP_PKEY> result(EVP_PKEY_new());
156 if (result.get() == nullptr || !EVP_PKEY_assign_RSA(result.get(), rsa.get())) {
157 return nullptr;
158 }
159 OWNERSHIP_TRANSFERRED(rsa);
160
161 return result;
162 }
163
164 /* wrap_ecdsa returns an |EVP_PKEY| that contains an ECDSA key where the public
165 * part is taken from |public_rsa| and the private operations are forwarded to
166 * KeyStore and operate on the key named |key_id|. */
wrap_ecdsa(std::shared_ptr<Keystore2KeyBackend> key_backend,const EC_KEY * public_ecdsa)167 bssl::UniquePtr<EVP_PKEY> wrap_ecdsa(std::shared_ptr<Keystore2KeyBackend> key_backend,
168 const EC_KEY* public_ecdsa) {
169 bssl::UniquePtr<EC_KEY> ec(EC_KEY_new_method(Keystore2Engine::get().engine()));
170 if (ec.get() == nullptr) {
171 return nullptr;
172 }
173
174 if (!EC_KEY_set_group(ec.get(), EC_KEY_get0_group(public_ecdsa)) ||
175 !EC_KEY_set_public_key(ec.get(), EC_KEY_get0_public_key(public_ecdsa))) {
176 return nullptr;
177 }
178
179 auto key_backend_copy = new decltype(key_backend)(key_backend);
180
181 if (!EC_KEY_set_ex_data(ec.get(), Keystore2Engine::get().ec_key_ex_index(), key_backend_copy)) {
182 delete key_backend_copy;
183 return nullptr;
184 }
185
186 bssl::UniquePtr<EVP_PKEY> result(EVP_PKEY_new());
187 if (result.get() == nullptr || !EVP_PKEY_assign_EC_KEY(result.get(), ec.get())) {
188 return nullptr;
189 }
190 OWNERSHIP_TRANSFERRED(ec);
191
192 return result;
193 }
194
keystore2_sign(const Keystore2KeyBackend & key_backend,std::vector<uint8_t> input,KMV1::Algorithm algorithm)195 std::optional<std::vector<uint8_t>> keystore2_sign(const Keystore2KeyBackend& key_backend,
196 std::vector<uint8_t> input,
197 KMV1::Algorithm algorithm) {
198 auto sec_level = key_backend.i_keystore_security_level_;
199 ks2::CreateOperationResponse response;
200
201 std::vector<KMV1::KeyParameter> op_params(4);
202 op_params[0] = KMV1::KeyParameter{
203 .tag = KMV1::Tag::PURPOSE,
204 .value = KMV1::KeyParameterValue::make<KMV1::KeyParameterValue::keyPurpose>(
205 KMV1::KeyPurpose::SIGN)};
206 op_params[1] = KMV1::KeyParameter{
207 .tag = KMV1::Tag::ALGORITHM,
208 .value = KMV1::KeyParameterValue::make<KMV1::KeyParameterValue::algorithm>(algorithm)};
209 op_params[2] = KMV1::KeyParameter{
210 .tag = KMV1::Tag::PADDING,
211 .value = KMV1::KeyParameterValue::make<KMV1::KeyParameterValue::paddingMode>(
212 KMV1::PaddingMode::NONE)};
213 op_params[3] =
214 KMV1::KeyParameter{.tag = KMV1::Tag::DIGEST,
215 .value = KMV1::KeyParameterValue::make<KMV1::KeyParameterValue::digest>(
216 KMV1::Digest::NONE)};
217
218 auto rc = sec_level->createOperation(key_backend.descriptor_, op_params, false /* forced */,
219 &response);
220 if (!rc.isOk()) {
221 auto exception_code = rc.getExceptionCode();
222 if (exception_code == EX_SERVICE_SPECIFIC) {
223 LOG(ERROR) << AT << "Keystore createOperation returned service specific error: "
224 << rc.getServiceSpecificError();
225 } else {
226 LOG(ERROR) << AT << "Communication with Keystore createOperation failed error: "
227 << exception_code;
228 }
229 return std::nullopt;
230 }
231
232 auto op = response.iOperation;
233
234 std::optional<std::vector<uint8_t>> output = std::nullopt;
235 rc = op->finish(std::move(input), {}, &output);
236 if (!rc.isOk()) {
237 auto exception_code = rc.getExceptionCode();
238 if (exception_code == EX_SERVICE_SPECIFIC) {
239 LOG(ERROR) << AT << "Keystore finish returned service specific error: "
240 << rc.getServiceSpecificError();
241 } else {
242 LOG(ERROR) << AT
243 << "Communication with Keystore finish failed error: " << exception_code;
244 }
245 return std::nullopt;
246 }
247
248 if (!output) {
249 LOG(ERROR) << AT << "We did not get a signature from Keystore.";
250 }
251
252 return output;
253 }
254
255 /* rsa_private_transform takes a big-endian integer from |in|, calculates the
256 * d'th power of it, modulo the RSA modulus, and writes the result as a
257 * big-endian integer to |out|. Both |in| and |out| are |len| bytes long. It
258 * returns one on success and zero otherwise. */
rsa_private_transform(RSA * rsa,uint8_t * out,const uint8_t * in,size_t len)259 extern "C" int rsa_private_transform(RSA* rsa, uint8_t* out, const uint8_t* in, size_t len) {
260 auto key_backend = reinterpret_cast<std::shared_ptr<Keystore2KeyBackend>*>(
261 RSA_get_ex_data(rsa, Keystore2Engine::get().rsa_ex_index()));
262
263 if (key_backend == nullptr) {
264 LOG(ERROR) << AT << "Invalid key.";
265 return 0;
266 }
267
268 auto output =
269 keystore2_sign(**key_backend, std::vector<uint8_t>(in, in + len), KMV1::Algorithm::RSA);
270 if (!output) {
271 return 0;
272 }
273
274 if (output->size() > len) {
275 /* The result of the RSA operation can never be larger than the size of
276 * the modulus so we assume that the result has extra zeros on the
277 * left. This provides attackers with an oracle, but there's nothing
278 * that we can do about it here. */
279 LOG(WARNING) << "Reply len " << output->size() << " greater than expected " << len;
280 memcpy(out, &output->data()[output->size() - len], len);
281 } else if (output->size() < len) {
282 /* If the Keystore implementation returns a short value we assume that
283 * it's because it removed leading zeros from the left side. This is
284 * bad because it provides attackers with an oracle but we cannot do
285 * anything about a broken Keystore implementation here. */
286 LOG(WARNING) << "Reply len " << output->size() << " less than expected " << len;
287 memset(out, 0, len);
288 memcpy(out + len - output->size(), output->data(), output->size());
289 } else {
290 memcpy(out, output->data(), len);
291 }
292
293 return 1;
294 }
295
296 /* ecdsa_sign signs |digest_len| bytes from |digest| with |ec_key| and writes
297 * the resulting signature (an ASN.1 encoded blob) to |sig|. It returns one on
298 * success and zero otherwise. */
ecdsa_sign(const uint8_t * digest,size_t digest_len,uint8_t * sig,unsigned int * sig_len,EC_KEY * ec_key)299 extern "C" int ecdsa_sign(const uint8_t* digest, size_t digest_len, uint8_t* sig,
300 unsigned int* sig_len, EC_KEY* ec_key) {
301 auto key_backend = reinterpret_cast<std::shared_ptr<Keystore2KeyBackend>*>(
302 EC_KEY_get_ex_data(ec_key, Keystore2Engine::get().ec_key_ex_index()));
303
304 if (key_backend == nullptr) {
305 LOG(ERROR) << AT << "Invalid key.";
306 return 0;
307 }
308
309 size_t ecdsa_size = ECDSA_size(ec_key);
310
311 auto output = keystore2_sign(**key_backend, std::vector<uint8_t>(digest, digest + digest_len),
312 KMV1::Algorithm::EC);
313 if (!output) {
314 LOG(ERROR) << "There was an error during ecdsa_sign.";
315 return 0;
316 }
317
318 if (output->size() == 0) {
319 LOG(ERROR) << "No valid signature returned";
320 return 0;
321 } else if (output->size() > ecdsa_size) {
322 LOG(ERROR) << "Signature is too large";
323 return 0;
324 }
325
326 memcpy(sig, output->data(), output->size());
327 *sig_len = output->size();
328
329 return 1;
330 }
331
extractPubKey(const std::vector<uint8_t> & cert_bytes)332 bssl::UniquePtr<EVP_PKEY> extractPubKey(const std::vector<uint8_t>& cert_bytes) {
333 const uint8_t* p = cert_bytes.data();
334 bssl::UniquePtr<X509> decoded_cert(d2i_X509(nullptr, &p, cert_bytes.size()));
335 if (!decoded_cert) {
336 LOG(INFO) << AT << "Could not decode the cert, trying decoding as PEM";
337 bssl::UniquePtr<BIO> cert_bio(BIO_new_mem_buf(cert_bytes.data(), cert_bytes.size()));
338 if (!cert_bio) {
339 LOG(ERROR) << AT << "Failed to create BIO";
340 return {};
341 }
342 decoded_cert =
343 bssl::UniquePtr<X509>(PEM_read_bio_X509(cert_bio.get(), nullptr, nullptr, nullptr));
344 }
345 if (!decoded_cert) {
346 LOG(ERROR) << AT << "Could not decode the cert.";
347 return {};
348 }
349 bssl::UniquePtr<EVP_PKEY> pub_key(X509_get_pubkey(decoded_cert.get()));
350 if (!pub_key) {
351 LOG(ERROR) << AT << "Could not extract public key.";
352 return {};
353 }
354 return pub_key;
355 }
356
357 } // namespace
358
359 /* EVP_PKEY_from_keystore returns an |EVP_PKEY| that contains either an RSA or
360 * ECDSA key where the public part of the key reflects the value of the key
361 * named |key_id| in Keystore and the private operations are forwarded onto
362 * KeyStore. */
EVP_PKEY_from_keystore2(const char * key_id)363 extern "C" EVP_PKEY* EVP_PKEY_from_keystore2(const char* key_id) {
364 ::ndk::SpAIBinder keystoreBinder(AServiceManager_checkService(keystore2_service_name));
365 auto keystore2 = ks2::IKeystoreService::fromBinder(keystoreBinder);
366
367 if (!keystore2) {
368 LOG(ERROR) << AT << "Unable to connect to Keystore 2.0.";
369 return nullptr;
370 }
371
372 std::string alias = key_id;
373 if (android::base::StartsWith(alias, "USRPKEY_")) {
374 LOG(WARNING) << AT << "Keystore backend used with legacy alias prefix - ignoring.";
375 alias = alias.substr(8);
376 }
377
378 ks2::KeyDescriptor descriptor = {
379 .domain = ks2::Domain::SELINUX,
380 .nspace = getNamespaceforCurrentUid(),
381 .alias = alias,
382 .blob = std::nullopt,
383 };
384
385 // If the key_id starts with the grant id prefix, we parse the following string as numeric
386 // grant id. We can then use the grant domain without alias to load the designated key.
387 if (alias.find(keystore2_grant_id_prefix) == 0) {
388 std::stringstream s(alias.substr(keystore2_grant_id_prefix.size()));
389 s >> std::hex >> reinterpret_cast<uint64_t&>(descriptor.nspace);
390 descriptor.domain = ks2::Domain::GRANT;
391 descriptor.alias = std::nullopt;
392 }
393
394 ks2::KeyEntryResponse response;
395 auto rc = keystore2->getKeyEntry(descriptor, &response);
396 if (!rc.isOk()) {
397 auto exception_code = rc.getExceptionCode();
398 if (exception_code == EX_SERVICE_SPECIFIC) {
399 LOG(ERROR) << AT << "Keystore getKeyEntry returned service specific error: "
400 << rc.getServiceSpecificError();
401 } else {
402 LOG(ERROR) << AT << "Communication with Keystore getKeyEntry failed error: "
403 << exception_code;
404 }
405 return nullptr;
406 }
407
408 if (!response.metadata.certificate) {
409 LOG(ERROR) << AT << "No public key found.";
410 return nullptr;
411 }
412
413 auto pkey = extractPubKey(*response.metadata.certificate);
414 if (!pkey) {
415 LOG(ERROR) << AT << "Failed to extract public key.";
416 return nullptr;
417 }
418
419 auto key_backend = std::make_shared<Keystore2KeyBackend>(
420 Keystore2KeyBackend{response.metadata.key, response.iSecurityLevel});
421
422 bssl::UniquePtr<EVP_PKEY> result;
423 switch (EVP_PKEY_type(pkey->type)) {
424 case EVP_PKEY_RSA: {
425 bssl::UniquePtr<RSA> public_rsa(EVP_PKEY_get1_RSA(pkey.get()));
426 result = wrap_rsa(key_backend, public_rsa.get());
427 break;
428 }
429 case EVP_PKEY_EC: {
430 bssl::UniquePtr<EC_KEY> public_ecdsa(EVP_PKEY_get1_EC_KEY(pkey.get()));
431 result = wrap_ecdsa(key_backend, public_ecdsa.get());
432 break;
433 }
434 default:
435 LOG(ERROR) << AT << "Unsupported key type " << EVP_PKEY_type(pkey->type);
436 return nullptr;
437 }
438
439 return result.release();
440 }
441