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