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 bssl::UniquePtr<BIGNUM> n(BN_dup(RSA_get0_n(public_rsa)));
150 bssl::UniquePtr<BIGNUM> e(BN_dup(RSA_get0_e(public_rsa)));
151 if (n == nullptr || e == nullptr || !RSA_set0_key(rsa.get(), n.get(), e.get(), nullptr)) {
152 return nullptr;
153 }
154 OWNERSHIP_TRANSFERRED(n);
155 OWNERSHIP_TRANSFERRED(e);
156
157 bssl::UniquePtr<EVP_PKEY> result(EVP_PKEY_new());
158 if (result.get() == nullptr || !EVP_PKEY_assign_RSA(result.get(), rsa.get())) {
159 return nullptr;
160 }
161 OWNERSHIP_TRANSFERRED(rsa);
162
163 return result;
164 }
165
166 /* wrap_ecdsa returns an |EVP_PKEY| that contains an ECDSA key where the public
167 * part is taken from |public_rsa| and the private operations are forwarded to
168 * KeyStore and operate on the key named |key_id|. */
wrap_ecdsa(std::shared_ptr<Keystore2KeyBackend> key_backend,const EC_KEY * public_ecdsa)169 bssl::UniquePtr<EVP_PKEY> wrap_ecdsa(std::shared_ptr<Keystore2KeyBackend> key_backend,
170 const EC_KEY* public_ecdsa) {
171 bssl::UniquePtr<EC_KEY> ec(EC_KEY_new_method(Keystore2Engine::get().engine()));
172 if (ec.get() == nullptr) {
173 return nullptr;
174 }
175
176 if (!EC_KEY_set_group(ec.get(), EC_KEY_get0_group(public_ecdsa)) ||
177 !EC_KEY_set_public_key(ec.get(), EC_KEY_get0_public_key(public_ecdsa))) {
178 return nullptr;
179 }
180
181 auto key_backend_copy = new decltype(key_backend)(key_backend);
182
183 if (!EC_KEY_set_ex_data(ec.get(), Keystore2Engine::get().ec_key_ex_index(), key_backend_copy)) {
184 delete key_backend_copy;
185 return nullptr;
186 }
187
188 bssl::UniquePtr<EVP_PKEY> result(EVP_PKEY_new());
189 if (result.get() == nullptr || !EVP_PKEY_assign_EC_KEY(result.get(), ec.get())) {
190 return nullptr;
191 }
192 OWNERSHIP_TRANSFERRED(ec);
193
194 return result;
195 }
196
keystore2_sign(const Keystore2KeyBackend & key_backend,std::vector<uint8_t> input,KMV1::Algorithm algorithm)197 std::optional<std::vector<uint8_t>> keystore2_sign(const Keystore2KeyBackend& key_backend,
198 std::vector<uint8_t> input,
199 KMV1::Algorithm algorithm) {
200 auto sec_level = key_backend.i_keystore_security_level_;
201 ks2::CreateOperationResponse response;
202
203 std::vector<KMV1::KeyParameter> op_params(4);
204 op_params[0] = KMV1::KeyParameter{
205 .tag = KMV1::Tag::PURPOSE,
206 .value = KMV1::KeyParameterValue::make<KMV1::KeyParameterValue::keyPurpose>(
207 KMV1::KeyPurpose::SIGN)};
208 op_params[1] = KMV1::KeyParameter{
209 .tag = KMV1::Tag::ALGORITHM,
210 .value = KMV1::KeyParameterValue::make<KMV1::KeyParameterValue::algorithm>(algorithm)};
211 op_params[2] = KMV1::KeyParameter{
212 .tag = KMV1::Tag::PADDING,
213 .value = KMV1::KeyParameterValue::make<KMV1::KeyParameterValue::paddingMode>(
214 KMV1::PaddingMode::NONE)};
215 op_params[3] =
216 KMV1::KeyParameter{.tag = KMV1::Tag::DIGEST,
217 .value = KMV1::KeyParameterValue::make<KMV1::KeyParameterValue::digest>(
218 KMV1::Digest::NONE)};
219
220 auto rc = sec_level->createOperation(key_backend.descriptor_, op_params, false /* forced */,
221 &response);
222 if (!rc.isOk()) {
223 auto exception_code = rc.getExceptionCode();
224 if (exception_code == EX_SERVICE_SPECIFIC) {
225 LOG(ERROR) << AT << "Keystore createOperation returned service specific error: "
226 << rc.getServiceSpecificError();
227 } else {
228 LOG(ERROR) << AT << "Communication with Keystore createOperation failed error: "
229 << exception_code;
230 }
231 return std::nullopt;
232 }
233
234 auto op = response.iOperation;
235
236 std::optional<std::vector<uint8_t>> output = std::nullopt;
237 rc = op->finish(std::move(input), {}, &output);
238 if (!rc.isOk()) {
239 auto exception_code = rc.getExceptionCode();
240 if (exception_code == EX_SERVICE_SPECIFIC) {
241 LOG(ERROR) << AT << "Keystore finish returned service specific error: "
242 << rc.getServiceSpecificError();
243 } else {
244 LOG(ERROR) << AT
245 << "Communication with Keystore finish failed error: " << exception_code;
246 }
247 return std::nullopt;
248 }
249
250 if (!output) {
251 LOG(ERROR) << AT << "We did not get a signature from Keystore.";
252 }
253
254 return output;
255 }
256
257 /* rsa_private_transform takes a big-endian integer from |in|, calculates the
258 * d'th power of it, modulo the RSA modulus, and writes the result as a
259 * big-endian integer to |out|. Both |in| and |out| are |len| bytes long. It
260 * returns one on success and zero otherwise. */
rsa_private_transform(RSA * rsa,uint8_t * out,const uint8_t * in,size_t len)261 extern "C" int rsa_private_transform(RSA* rsa, uint8_t* out, const uint8_t* in, size_t len) {
262 auto key_backend = reinterpret_cast<std::shared_ptr<Keystore2KeyBackend>*>(
263 RSA_get_ex_data(rsa, Keystore2Engine::get().rsa_ex_index()));
264
265 if (key_backend == nullptr) {
266 LOG(ERROR) << AT << "Invalid key.";
267 return 0;
268 }
269
270 auto output =
271 keystore2_sign(**key_backend, std::vector<uint8_t>(in, in + len), KMV1::Algorithm::RSA);
272 if (!output) {
273 return 0;
274 }
275
276 if (output->size() > len) {
277 /* The result of the RSA operation can never be larger than the size of
278 * the modulus so we assume that the result has extra zeros on the
279 * left. This provides attackers with an oracle, but there's nothing
280 * that we can do about it here. */
281 LOG(WARNING) << "Reply len " << output->size() << " greater than expected " << len;
282 memcpy(out, &output->data()[output->size() - len], len);
283 } else if (output->size() < len) {
284 /* If the Keystore implementation returns a short value we assume that
285 * it's because it removed leading zeros from the left side. This is
286 * bad because it provides attackers with an oracle but we cannot do
287 * anything about a broken Keystore implementation here. */
288 LOG(WARNING) << "Reply len " << output->size() << " less than expected " << len;
289 memset(out, 0, len);
290 memcpy(out + len - output->size(), output->data(), output->size());
291 } else {
292 memcpy(out, output->data(), len);
293 }
294
295 return 1;
296 }
297
298 /* ecdsa_sign signs |digest_len| bytes from |digest| with |ec_key| and writes
299 * the resulting signature (an ASN.1 encoded blob) to |sig|. It returns one on
300 * 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)301 extern "C" int ecdsa_sign(const uint8_t* digest, size_t digest_len, uint8_t* sig,
302 unsigned int* sig_len, EC_KEY* ec_key) {
303 auto key_backend = reinterpret_cast<std::shared_ptr<Keystore2KeyBackend>*>(
304 EC_KEY_get_ex_data(ec_key, Keystore2Engine::get().ec_key_ex_index()));
305
306 if (key_backend == nullptr) {
307 LOG(ERROR) << AT << "Invalid key.";
308 return 0;
309 }
310
311 size_t ecdsa_size = ECDSA_size(ec_key);
312
313 auto output = keystore2_sign(**key_backend, std::vector<uint8_t>(digest, digest + digest_len),
314 KMV1::Algorithm::EC);
315 if (!output) {
316 LOG(ERROR) << "There was an error during ecdsa_sign.";
317 return 0;
318 }
319
320 if (output->size() == 0) {
321 LOG(ERROR) << "No valid signature returned";
322 return 0;
323 } else if (output->size() > ecdsa_size) {
324 LOG(ERROR) << "Signature is too large";
325 return 0;
326 }
327
328 memcpy(sig, output->data(), output->size());
329 *sig_len = output->size();
330
331 return 1;
332 }
333
extractPubKey(const std::vector<uint8_t> & cert_bytes)334 bssl::UniquePtr<EVP_PKEY> extractPubKey(const std::vector<uint8_t>& cert_bytes) {
335 const uint8_t* p = cert_bytes.data();
336 bssl::UniquePtr<X509> decoded_cert(d2i_X509(nullptr, &p, cert_bytes.size()));
337 if (!decoded_cert) {
338 LOG(INFO) << AT << "Could not decode the cert, trying decoding as PEM";
339 bssl::UniquePtr<BIO> cert_bio(BIO_new_mem_buf(cert_bytes.data(), cert_bytes.size()));
340 if (!cert_bio) {
341 LOG(ERROR) << AT << "Failed to create BIO";
342 return {};
343 }
344 decoded_cert =
345 bssl::UniquePtr<X509>(PEM_read_bio_X509(cert_bio.get(), nullptr, nullptr, nullptr));
346 }
347 if (!decoded_cert) {
348 LOG(ERROR) << AT << "Could not decode the cert.";
349 return {};
350 }
351 bssl::UniquePtr<EVP_PKEY> pub_key(X509_get_pubkey(decoded_cert.get()));
352 if (!pub_key) {
353 LOG(ERROR) << AT << "Could not extract public key.";
354 return {};
355 }
356 return pub_key;
357 }
358
359 } // namespace
360
361 /* EVP_PKEY_from_keystore returns an |EVP_PKEY| that contains either an RSA or
362 * ECDSA key where the public part of the key reflects the value of the key
363 * named |key_id| in Keystore and the private operations are forwarded onto
364 * KeyStore. */
EVP_PKEY_from_keystore2(const char * key_id)365 extern "C" EVP_PKEY* EVP_PKEY_from_keystore2(const char* key_id) {
366 ::ndk::SpAIBinder keystoreBinder(AServiceManager_checkService(keystore2_service_name));
367 auto keystore2 = ks2::IKeystoreService::fromBinder(keystoreBinder);
368
369 if (!keystore2) {
370 LOG(ERROR) << AT << "Unable to connect to Keystore 2.0.";
371 return nullptr;
372 }
373
374 std::string alias = key_id;
375 if (android::base::StartsWith(alias, "USRPKEY_")) {
376 LOG(WARNING) << AT << "Keystore backend used with legacy alias prefix - ignoring.";
377 alias = alias.substr(8);
378 }
379
380 ks2::KeyDescriptor descriptor = {
381 .domain = ks2::Domain::SELINUX,
382 .nspace = getNamespaceforCurrentUid(),
383 .alias = alias,
384 .blob = std::nullopt,
385 };
386
387 // If the key_id starts with the grant id prefix, we parse the following string as numeric
388 // grant id. We can then use the grant domain without alias to load the designated key.
389 if (android::base::StartsWith(alias, keystore2_grant_id_prefix)) {
390 std::stringstream s(alias.substr(keystore2_grant_id_prefix.size()));
391 s >> std::hex >> reinterpret_cast<uint64_t&>(descriptor.nspace);
392 descriptor.domain = ks2::Domain::GRANT;
393 descriptor.alias = std::nullopt;
394 }
395
396 ks2::KeyEntryResponse response;
397 auto rc = keystore2->getKeyEntry(descriptor, &response);
398 if (!rc.isOk()) {
399 auto exception_code = rc.getExceptionCode();
400 if (exception_code == EX_SERVICE_SPECIFIC) {
401 LOG(ERROR) << AT << "Keystore getKeyEntry returned service specific error: "
402 << rc.getServiceSpecificError();
403 } else {
404 LOG(ERROR) << AT << "Communication with Keystore getKeyEntry failed error: "
405 << exception_code;
406 }
407 return nullptr;
408 }
409
410 if (!response.metadata.certificate) {
411 LOG(ERROR) << AT << "No public key found.";
412 return nullptr;
413 }
414
415 auto pkey = extractPubKey(*response.metadata.certificate);
416 if (!pkey) {
417 LOG(ERROR) << AT << "Failed to extract public key.";
418 return nullptr;
419 }
420
421 auto key_backend = std::make_shared<Keystore2KeyBackend>(
422 Keystore2KeyBackend{response.metadata.key, response.iSecurityLevel});
423
424 bssl::UniquePtr<EVP_PKEY> result;
425 switch (EVP_PKEY_id(pkey.get())) {
426 case EVP_PKEY_RSA: {
427 RSA* public_rsa = EVP_PKEY_get0_RSA(pkey.get());
428 result = wrap_rsa(key_backend, public_rsa);
429 break;
430 }
431 case EVP_PKEY_EC: {
432 EC_KEY* public_ecdsa = EVP_PKEY_get0_EC_KEY(pkey.get());
433 result = wrap_ecdsa(key_backend, public_ecdsa);
434 break;
435 }
436 default:
437 LOG(ERROR) << AT << "Unsupported key type " << EVP_PKEY_id(pkey.get());
438 return nullptr;
439 }
440
441 return result.release();
442 }
443