blob: 21d75be249c3b3f2b25815c349307a0b2df301fd [file] [log] [blame]
Kenny Roota91203b2012-02-15 15:00:46 -08001/*
2 * Copyright (C) 2009 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
Kenny Root07438c82012-11-02 15:41:02 -070017//#define LOG_NDEBUG 0
18#define LOG_TAG "keystore"
19
Kenny Roota91203b2012-02-15 15:00:46 -080020#include <stdio.h>
21#include <stdint.h>
22#include <string.h>
Elliott Hughesaaf98022015-01-25 08:40:44 -080023#include <strings.h>
Kenny Roota91203b2012-02-15 15:00:46 -080024#include <unistd.h>
25#include <signal.h>
26#include <errno.h>
27#include <dirent.h>
Kenny Root655b9582013-04-04 08:37:42 -070028#include <errno.h>
Kenny Roota91203b2012-02-15 15:00:46 -080029#include <fcntl.h>
30#include <limits.h>
Kenny Root822c3a92012-03-23 16:34:39 -070031#include <assert.h>
Kenny Roota91203b2012-02-15 15:00:46 -080032#include <sys/types.h>
33#include <sys/socket.h>
34#include <sys/stat.h>
35#include <sys/time.h>
36#include <arpa/inet.h>
37
38#include <openssl/aes.h>
Kenny Root822c3a92012-03-23 16:34:39 -070039#include <openssl/bio.h>
Kenny Roota91203b2012-02-15 15:00:46 -080040#include <openssl/evp.h>
41#include <openssl/md5.h>
Kenny Root822c3a92012-03-23 16:34:39 -070042#include <openssl/pem.h>
Kenny Roota91203b2012-02-15 15:00:46 -080043
Shawn Willden80843db2015-02-24 09:31:25 -070044#include <hardware/keymaster0.h>
Kenny Root70e3a862012-02-15 17:20:23 -080045
Chad Brubaker67d2a502015-03-11 17:21:18 +000046#include <keymaster/soft_keymaster_device.h>
Shawn Willden04006752015-04-30 11:12:33 -060047#include <keymaster/soft_keymaster_logger.h>
48#include <keymaster/softkeymaster.h>
Kenny Root17208e02013-09-04 13:56:03 -070049
Kenny Root26cfc082013-09-11 14:38:56 -070050#include <UniquePtr.h>
Kenny Root655b9582013-04-04 08:37:42 -070051#include <utils/String8.h>
Kenny Root655b9582013-04-04 08:37:42 -070052#include <utils/Vector.h>
Kenny Root70e3a862012-02-15 17:20:23 -080053
Kenny Root07438c82012-11-02 15:41:02 -070054#include <keystore/IKeystoreService.h>
55#include <binder/IPCThreadState.h>
56#include <binder/IServiceManager.h>
57
Kenny Roota91203b2012-02-15 15:00:46 -080058#include <cutils/log.h>
59#include <cutils/sockets.h>
60#include <private/android_filesystem_config.h>
61
Kenny Root07438c82012-11-02 15:41:02 -070062#include <keystore/keystore.h>
Kenny Roota91203b2012-02-15 15:00:46 -080063
Riley Spahneaabae92014-06-30 12:39:52 -070064#include <selinux/android.h>
65
Chad Brubaker3a7d9e62015-06-04 15:01:46 -070066#include <sstream>
67
Chad Brubakerd80c7b42015-03-31 11:04:28 -070068#include "auth_token_table.h"
Kenny Root96427ba2013-08-16 14:02:41 -070069#include "defaults.h"
Shawn Willden9221bff2015-06-18 18:23:54 -060070#include "keystore_keymaster_enforcement.h"
Chad Brubaker40a1a9b2015-02-20 14:08:13 -080071#include "operation.h"
Kenny Root96427ba2013-08-16 14:02:41 -070072
Kenny Roota91203b2012-02-15 15:00:46 -080073/* KeyStore is a secured storage for key-value pairs. In this implementation,
74 * each file stores one key-value pair. Keys are encoded in file names, and
75 * values are encrypted with checksums. The encryption key is protected by a
76 * user-defined password. To keep things simple, buffers are always larger than
77 * the maximum space we needed, so boundary checks on buffers are omitted. */
78
79#define KEY_SIZE ((NAME_MAX - 15) / 2)
80#define VALUE_SIZE 32768
81#define PASSWORD_SIZE VALUE_SIZE
82
Shawn Willden55268b52015-07-28 11:06:00 -060083using keymaster::SoftKeymasterDevice;
Kenny Root822c3a92012-03-23 16:34:39 -070084
Kenny Root96427ba2013-08-16 14:02:41 -070085struct BIGNUM_Delete {
86 void operator()(BIGNUM* p) const {
87 BN_free(p);
88 }
89};
90typedef UniquePtr<BIGNUM, BIGNUM_Delete> Unique_BIGNUM;
91
Kenny Root822c3a92012-03-23 16:34:39 -070092struct BIO_Delete {
93 void operator()(BIO* p) const {
94 BIO_free(p);
95 }
96};
97typedef UniquePtr<BIO, BIO_Delete> Unique_BIO;
98
99struct EVP_PKEY_Delete {
100 void operator()(EVP_PKEY* p) const {
101 EVP_PKEY_free(p);
102 }
103};
104typedef UniquePtr<EVP_PKEY, EVP_PKEY_Delete> Unique_EVP_PKEY;
105
106struct PKCS8_PRIV_KEY_INFO_Delete {
107 void operator()(PKCS8_PRIV_KEY_INFO* p) const {
108 PKCS8_PRIV_KEY_INFO_free(p);
109 }
110};
111typedef UniquePtr<PKCS8_PRIV_KEY_INFO, PKCS8_PRIV_KEY_INFO_Delete> Unique_PKCS8_PRIV_KEY_INFO;
112
Shawn Willden55268b52015-07-28 11:06:00 -0600113static int keymaster0_device_initialize(const hw_module_t* mod, keymaster1_device_t** dev) {
114 assert(mod->module_api_version < KEYMASTER_MODULE_API_VERSION_1_0);
115 ALOGI("Found keymaster0 module %s, version %x", mod->name, mod->module_api_version);
Kenny Root70e3a862012-02-15 17:20:23 -0800116
Shawn Willden55268b52015-07-28 11:06:00 -0600117 UniquePtr<SoftKeymasterDevice> soft_keymaster(new SoftKeymasterDevice);
118 keymaster0_device_t* km0_device = NULL;
119 keymaster_error_t error = KM_ERROR_OK;
120
121 int rc = keymaster0_open(mod, &km0_device);
Kenny Root70e3a862012-02-15 17:20:23 -0800122 if (rc) {
Shawn Willden55268b52015-07-28 11:06:00 -0600123 ALOGE("Error opening keystore keymaster0 device.");
124 goto err;
Kenny Root70e3a862012-02-15 17:20:23 -0800125 }
126
Shawn Willden55268b52015-07-28 11:06:00 -0600127 if (km0_device->flags & KEYMASTER_SOFTWARE_ONLY) {
128 ALOGI("Keymaster0 module is software-only. Using SoftKeymasterDevice instead.");
129 km0_device->common.close(&km0_device->common);
130 km0_device = NULL;
131 // SoftKeymasterDevice will be deleted by keymaster_device_release()
132 *dev = soft_keymaster.release()->keymaster_device();
Chad Brubakerbd07a232015-06-01 10:44:27 -0700133 return 0;
134 }
Shawn Willden55268b52015-07-28 11:06:00 -0600135
136 ALOGE("Wrapping keymaster0 module %s with SoftKeymasterDevice", mod->name);
137 error = soft_keymaster->SetHardwareDevice(km0_device);
138 km0_device = NULL; // SoftKeymasterDevice has taken ownership.
139 if (error != KM_ERROR_OK) {
140 ALOGE("Got error %d from SetHardwareDevice", error);
141 rc = error;
142 goto err;
143 }
144
145 // SoftKeymasterDevice will be deleted by keymaster_device_release()
146 *dev = soft_keymaster.release()->keymaster_device();
Kenny Root70e3a862012-02-15 17:20:23 -0800147 return 0;
148
Shawn Willden55268b52015-07-28 11:06:00 -0600149err:
150 if (km0_device)
151 km0_device->common.close(&km0_device->common);
Kenny Root70e3a862012-02-15 17:20:23 -0800152 *dev = NULL;
153 return rc;
154}
155
Shawn Willden55268b52015-07-28 11:06:00 -0600156static int keymaster1_device_initialize(const hw_module_t* mod, keymaster1_device_t** dev) {
157 assert(mod->module_api_version >= KEYMASTER_MODULE_API_VERSION_1_0);
158 ALOGI("Found keymaster1 module %s, version %x", mod->name, mod->module_api_version);
159
160 UniquePtr<SoftKeymasterDevice> soft_keymaster(new SoftKeymasterDevice);
161 keymaster1_device_t* km1_device = NULL;
162 keymaster_error_t error = KM_ERROR_OK;
163
164 int rc = keymaster1_open(mod, &km1_device);
165 if (rc) {
166 ALOGE("Error %d opening keystore keymaster1 device", rc);
167 goto err;
168 }
169
170 error = soft_keymaster->SetHardwareDevice(km1_device);
171 km1_device = NULL; // SoftKeymasterDevice has taken ownership.
172 if (error != KM_ERROR_OK) {
173 ALOGE("Got error %d from SetHardwareDevice", error);
174 rc = error;
175 goto err;
176 }
177
178 if (!soft_keymaster->Keymaster1DeviceIsGood()) {
179 ALOGI("Keymaster1 module is incomplete, using SoftKeymasterDevice wrapper");
180 // SoftKeymasterDevice will be deleted by keymaster_device_release()
181 *dev = soft_keymaster.release()->keymaster_device();
182 return 0;
183 } else {
184 ALOGI("Keymaster1 module is good, destroying wrapper and re-opening");
185 soft_keymaster.reset(NULL);
186 rc = keymaster1_open(mod, &km1_device);
187 if (rc) {
188 ALOGE("Error %d re-opening keystore keymaster1 device.", rc);
189 goto err;
190 }
191 *dev = km1_device;
192 return 0;
193 }
194
195err:
196 if (km1_device)
197 km1_device->common.close(&km1_device->common);
198 *dev = NULL;
199 return rc;
200
201}
202
203static int keymaster_device_initialize(keymaster1_device_t** dev) {
204 const hw_module_t* mod;
205
206 int rc = hw_get_module_by_class(KEYSTORE_HARDWARE_MODULE_ID, NULL, &mod);
207 if (rc) {
208 ALOGI("Could not find any keystore module, using software-only implementation.");
209 // SoftKeymasterDevice will be deleted by keymaster_device_release()
210 *dev = (new SoftKeymasterDevice)->keymaster_device();
211 return 0;
212 }
213
214 if (mod->module_api_version < KEYMASTER_MODULE_API_VERSION_1_0) {
215 return keymaster0_device_initialize(mod, dev);
216 } else {
217 return keymaster1_device_initialize(mod, dev);
218 }
219}
220
Shawn Willden04006752015-04-30 11:12:33 -0600221// softkeymaster_logger appears not to be used in keystore, but it installs itself as the
222// logger used by SoftKeymasterDevice.
223static keymaster::SoftKeymasterLogger softkeymaster_logger;
224
Chad Brubaker67d2a502015-03-11 17:21:18 +0000225static int fallback_keymaster_device_initialize(keymaster1_device_t** dev) {
Shawn Willden55268b52015-07-28 11:06:00 -0600226 *dev = (new SoftKeymasterDevice)->keymaster_device();
227 // SoftKeymasterDevice will be deleted by keymaster_device_release()
Chad Brubakerfc18edc2015-01-12 15:17:18 -0800228 return 0;
Chad Brubakerfc18edc2015-01-12 15:17:18 -0800229}
230
Chad Brubakerbd07a232015-06-01 10:44:27 -0700231static void keymaster_device_release(keymaster1_device_t* dev) {
232 dev->common.close(&dev->common);
Kenny Root70e3a862012-02-15 17:20:23 -0800233}
234
Shawn Willden55268b52015-07-28 11:06:00 -0600235static void add_legacy_key_authorizations(int keyType, std::vector<keymaster_key_param_t>* params) {
236 params->push_back(keymaster_param_enum(KM_TAG_PURPOSE, KM_PURPOSE_SIGN));
237 params->push_back(keymaster_param_enum(KM_TAG_PURPOSE, KM_PURPOSE_VERIFY));
238 params->push_back(keymaster_param_enum(KM_TAG_PURPOSE, KM_PURPOSE_ENCRYPT));
239 params->push_back(keymaster_param_enum(KM_TAG_PURPOSE, KM_PURPOSE_DECRYPT));
240 params->push_back(keymaster_param_enum(KM_TAG_PADDING, KM_PAD_NONE));
241 if (keyType == EVP_PKEY_RSA) {
242 params->push_back(keymaster_param_enum(KM_TAG_PADDING, KM_PAD_RSA_PKCS1_1_5_SIGN));
243 params->push_back(keymaster_param_enum(KM_TAG_PADDING, KM_PAD_RSA_PKCS1_1_5_ENCRYPT));
244 params->push_back(keymaster_param_enum(KM_TAG_PADDING, KM_PAD_RSA_PSS));
245 params->push_back(keymaster_param_enum(KM_TAG_PADDING, KM_PAD_RSA_OAEP));
246 }
247 params->push_back(keymaster_param_enum(KM_TAG_DIGEST, KM_DIGEST_NONE));
248 params->push_back(keymaster_param_enum(KM_TAG_DIGEST, KM_DIGEST_MD5));
249 params->push_back(keymaster_param_enum(KM_TAG_DIGEST, KM_DIGEST_SHA1));
250 params->push_back(keymaster_param_enum(KM_TAG_DIGEST, KM_DIGEST_SHA_2_224));
251 params->push_back(keymaster_param_enum(KM_TAG_DIGEST, KM_DIGEST_SHA_2_256));
252 params->push_back(keymaster_param_enum(KM_TAG_DIGEST, KM_DIGEST_SHA_2_384));
253 params->push_back(keymaster_param_enum(KM_TAG_DIGEST, KM_DIGEST_SHA_2_512));
254 params->push_back(keymaster_param_bool(KM_TAG_ALL_USERS));
255 params->push_back(keymaster_param_bool(KM_TAG_NO_AUTH_REQUIRED));
256 params->push_back(keymaster_param_date(KM_TAG_ORIGINATION_EXPIRE_DATETIME, LLONG_MAX));
257 params->push_back(keymaster_param_date(KM_TAG_USAGE_EXPIRE_DATETIME, LLONG_MAX));
258 params->push_back(keymaster_param_date(KM_TAG_ACTIVE_DATETIME, 0));
Shawn Willden55268b52015-07-28 11:06:00 -0600259}
260
Kenny Root07438c82012-11-02 15:41:02 -0700261/***************
262 * PERMISSIONS *
263 ***************/
264
265/* Here are the permissions, actions, users, and the main function. */
266typedef enum {
Chad Brubakere6c3bfa2015-05-12 15:18:26 -0700267 P_GET_STATE = 1 << 0,
Robin Lee4e865752014-08-19 17:37:55 +0100268 P_GET = 1 << 1,
269 P_INSERT = 1 << 2,
270 P_DELETE = 1 << 3,
271 P_EXIST = 1 << 4,
Chad Brubakere6c3bfa2015-05-12 15:18:26 -0700272 P_LIST = 1 << 5,
Robin Lee4e865752014-08-19 17:37:55 +0100273 P_RESET = 1 << 6,
274 P_PASSWORD = 1 << 7,
275 P_LOCK = 1 << 8,
276 P_UNLOCK = 1 << 9,
Chad Brubakere6c3bfa2015-05-12 15:18:26 -0700277 P_IS_EMPTY = 1 << 10,
Robin Lee4e865752014-08-19 17:37:55 +0100278 P_SIGN = 1 << 11,
279 P_VERIFY = 1 << 12,
280 P_GRANT = 1 << 13,
281 P_DUPLICATE = 1 << 14,
282 P_CLEAR_UID = 1 << 15,
Chad Brubakere6c3bfa2015-05-12 15:18:26 -0700283 P_ADD_AUTH = 1 << 16,
284 P_USER_CHANGED = 1 << 17,
Kenny Root07438c82012-11-02 15:41:02 -0700285} perm_t;
286
287static struct user_euid {
288 uid_t uid;
289 uid_t euid;
290} user_euids[] = {
291 {AID_VPN, AID_SYSTEM},
292 {AID_WIFI, AID_SYSTEM},
293 {AID_ROOT, AID_SYSTEM},
294};
295
Riley Spahneaabae92014-06-30 12:39:52 -0700296/* perm_labels associcated with keystore_key SELinux class verbs. */
297const char *perm_labels[] = {
Chad Brubakere6c3bfa2015-05-12 15:18:26 -0700298 "get_state",
Riley Spahneaabae92014-06-30 12:39:52 -0700299 "get",
300 "insert",
301 "delete",
302 "exist",
Chad Brubakere6c3bfa2015-05-12 15:18:26 -0700303 "list",
Riley Spahneaabae92014-06-30 12:39:52 -0700304 "reset",
305 "password",
306 "lock",
307 "unlock",
Chad Brubakere6c3bfa2015-05-12 15:18:26 -0700308 "is_empty",
Riley Spahneaabae92014-06-30 12:39:52 -0700309 "sign",
310 "verify",
311 "grant",
312 "duplicate",
Robin Lee4e865752014-08-19 17:37:55 +0100313 "clear_uid",
Chad Brubakerd80c7b42015-03-31 11:04:28 -0700314 "add_auth",
Chad Brubakerc0f031a2015-05-12 10:43:10 -0700315 "user_changed",
Riley Spahneaabae92014-06-30 12:39:52 -0700316};
317
Kenny Root07438c82012-11-02 15:41:02 -0700318static struct user_perm {
319 uid_t uid;
320 perm_t perms;
321} user_perms[] = {
322 {AID_SYSTEM, static_cast<perm_t>((uint32_t)(~0)) },
323 {AID_VPN, static_cast<perm_t>(P_GET | P_SIGN | P_VERIFY) },
324 {AID_WIFI, static_cast<perm_t>(P_GET | P_SIGN | P_VERIFY) },
325 {AID_ROOT, static_cast<perm_t>(P_GET) },
326};
327
Chad Brubakere6c3bfa2015-05-12 15:18:26 -0700328static const perm_t DEFAULT_PERMS = static_cast<perm_t>(P_GET_STATE | P_GET | P_INSERT | P_DELETE
329 | P_EXIST | P_LIST | P_SIGN | P_VERIFY);
Kenny Root07438c82012-11-02 15:41:02 -0700330
Riley Spahneaabae92014-06-30 12:39:52 -0700331static char *tctx;
332static int ks_is_selinux_enabled;
333
334static const char *get_perm_label(perm_t perm) {
335 unsigned int index = ffs(perm);
336 if (index > 0 && index <= (sizeof(perm_labels) / sizeof(perm_labels[0]))) {
337 return perm_labels[index - 1];
338 } else {
339 ALOGE("Keystore: Failed to retrieve permission label.\n");
340 abort();
341 }
342}
343
Kenny Root655b9582013-04-04 08:37:42 -0700344/**
345 * Returns the app ID (in the Android multi-user sense) for the current
346 * UNIX UID.
347 */
348static uid_t get_app_id(uid_t uid) {
349 return uid % AID_USER;
350}
351
352/**
353 * Returns the user ID (in the Android multi-user sense) for the current
354 * UNIX UID.
355 */
356static uid_t get_user_id(uid_t uid) {
357 return uid / AID_USER;
358}
359
Chih-Hung Hsieha25b2a32014-09-03 12:14:45 -0700360static bool keystore_selinux_check_access(uid_t /*uid*/, perm_t perm, pid_t spid) {
Riley Spahneaabae92014-06-30 12:39:52 -0700361 if (!ks_is_selinux_enabled) {
362 return true;
363 }
Nick Kralevich66dbf672014-06-30 17:09:14 +0000364
Riley Spahneaabae92014-06-30 12:39:52 -0700365 char *sctx = NULL;
366 const char *selinux_class = "keystore_key";
367 const char *str_perm = get_perm_label(perm);
368
369 if (!str_perm) {
370 return false;
371 }
372
373 if (getpidcon(spid, &sctx) != 0) {
374 ALOGE("SELinux: Failed to get source pid context.\n");
375 return false;
376 }
377
378 bool allowed = selinux_check_access(sctx, tctx, selinux_class, str_perm,
379 NULL) == 0;
380 freecon(sctx);
381 return allowed;
382}
383
384static bool has_permission(uid_t uid, perm_t perm, pid_t spid) {
Kenny Root655b9582013-04-04 08:37:42 -0700385 // All system users are equivalent for multi-user support.
386 if (get_app_id(uid) == AID_SYSTEM) {
387 uid = AID_SYSTEM;
388 }
389
Kenny Root07438c82012-11-02 15:41:02 -0700390 for (size_t i = 0; i < sizeof(user_perms)/sizeof(user_perms[0]); i++) {
391 struct user_perm user = user_perms[i];
392 if (user.uid == uid) {
Riley Spahneaabae92014-06-30 12:39:52 -0700393 return (user.perms & perm) &&
394 keystore_selinux_check_access(uid, perm, spid);
Kenny Root07438c82012-11-02 15:41:02 -0700395 }
396 }
397
Riley Spahneaabae92014-06-30 12:39:52 -0700398 return (DEFAULT_PERMS & perm) &&
399 keystore_selinux_check_access(uid, perm, spid);
Kenny Root07438c82012-11-02 15:41:02 -0700400}
401
Kenny Root49468902013-03-19 13:41:33 -0700402/**
403 * Returns the UID that the callingUid should act as. This is here for
404 * legacy support of the WiFi and VPN systems and should be removed
405 * when WiFi can operate in its own namespace.
406 */
Kenny Root07438c82012-11-02 15:41:02 -0700407static uid_t get_keystore_euid(uid_t uid) {
408 for (size_t i = 0; i < sizeof(user_euids)/sizeof(user_euids[0]); i++) {
409 struct user_euid user = user_euids[i];
410 if (user.uid == uid) {
411 return user.euid;
412 }
413 }
414
415 return uid;
416}
417
Kenny Root49468902013-03-19 13:41:33 -0700418/**
419 * Returns true if the callingUid is allowed to interact in the targetUid's
420 * namespace.
421 */
422static bool is_granted_to(uid_t callingUid, uid_t targetUid) {
Chad Brubaker9489b792015-04-14 11:01:45 -0700423 if (callingUid == targetUid) {
424 return true;
425 }
Kenny Root49468902013-03-19 13:41:33 -0700426 for (size_t i = 0; i < sizeof(user_euids)/sizeof(user_euids[0]); i++) {
427 struct user_euid user = user_euids[i];
428 if (user.euid == callingUid && user.uid == targetUid) {
429 return true;
430 }
431 }
432
433 return false;
434}
435
Kenny Roota91203b2012-02-15 15:00:46 -0800436/* Here is the encoding of keys. This is necessary in order to allow arbitrary
437 * characters in keys. Characters in [0-~] are not encoded. Others are encoded
438 * into two bytes. The first byte is one of [+-.] which represents the first
439 * two bits of the character. The second byte encodes the rest of the bits into
440 * [0-o]. Therefore in the worst case the length of a key gets doubled. Note
441 * that Base64 cannot be used here due to the need of prefix match on keys. */
442
Kenny Root655b9582013-04-04 08:37:42 -0700443static size_t encode_key_length(const android::String8& keyName) {
444 const uint8_t* in = reinterpret_cast<const uint8_t*>(keyName.string());
445 size_t length = keyName.length();
446 for (int i = length; i > 0; --i, ++in) {
447 if (*in < '0' || *in > '~') {
448 ++length;
449 }
450 }
451 return length;
452}
453
Kenny Root07438c82012-11-02 15:41:02 -0700454static int encode_key(char* out, const android::String8& keyName) {
455 const uint8_t* in = reinterpret_cast<const uint8_t*>(keyName.string());
456 size_t length = keyName.length();
Kenny Roota91203b2012-02-15 15:00:46 -0800457 for (int i = length; i > 0; --i, ++in, ++out) {
Kenny Root655b9582013-04-04 08:37:42 -0700458 if (*in < '0' || *in > '~') {
Kenny Roota91203b2012-02-15 15:00:46 -0800459 *out = '+' + (*in >> 6);
460 *++out = '0' + (*in & 0x3F);
461 ++length;
Kenny Root655b9582013-04-04 08:37:42 -0700462 } else {
463 *out = *in;
Kenny Roota91203b2012-02-15 15:00:46 -0800464 }
465 }
466 *out = '\0';
Kenny Root70e3a862012-02-15 17:20:23 -0800467 return length;
468}
469
Kenny Root07438c82012-11-02 15:41:02 -0700470/*
471 * Converts from the "escaped" format on disk to actual name.
472 * This will be smaller than the input string.
473 *
474 * Characters that should combine with the next at the end will be truncated.
475 */
476static size_t decode_key_length(const char* in, size_t length) {
477 size_t outLength = 0;
478
479 for (const char* end = in + length; in < end; in++) {
480 /* This combines with the next character. */
481 if (*in < '0' || *in > '~') {
482 continue;
483 }
484
485 outLength++;
486 }
487 return outLength;
488}
489
490static void decode_key(char* out, const char* in, size_t length) {
491 for (const char* end = in + length; in < end; in++) {
492 if (*in < '0' || *in > '~') {
493 /* Truncate combining characters at the end. */
494 if (in + 1 >= end) {
495 break;
496 }
497
498 *out = (*in++ - '+') << 6;
499 *out++ |= (*in - '0') & 0x3F;
Kenny Roota91203b2012-02-15 15:00:46 -0800500 } else {
Kenny Root07438c82012-11-02 15:41:02 -0700501 *out++ = *in;
Kenny Roota91203b2012-02-15 15:00:46 -0800502 }
503 }
504 *out = '\0';
Kenny Roota91203b2012-02-15 15:00:46 -0800505}
506
507static size_t readFully(int fd, uint8_t* data, size_t size) {
508 size_t remaining = size;
509 while (remaining > 0) {
Kenny Root150ca932012-11-14 14:29:02 -0800510 ssize_t n = TEMP_FAILURE_RETRY(read(fd, data, remaining));
Kenny Root5281edb2012-11-21 15:14:04 -0800511 if (n <= 0) {
Kenny Root150ca932012-11-14 14:29:02 -0800512 return size - remaining;
Kenny Roota91203b2012-02-15 15:00:46 -0800513 }
514 data += n;
515 remaining -= n;
516 }
517 return size;
518}
519
520static size_t writeFully(int fd, uint8_t* data, size_t size) {
521 size_t remaining = size;
522 while (remaining > 0) {
Kenny Root150ca932012-11-14 14:29:02 -0800523 ssize_t n = TEMP_FAILURE_RETRY(write(fd, data, remaining));
524 if (n < 0) {
525 ALOGW("write failed: %s", strerror(errno));
526 return size - remaining;
Kenny Roota91203b2012-02-15 15:00:46 -0800527 }
528 data += n;
529 remaining -= n;
530 }
531 return size;
532}
533
534class Entropy {
535public:
536 Entropy() : mRandom(-1) {}
537 ~Entropy() {
Kenny Root150ca932012-11-14 14:29:02 -0800538 if (mRandom >= 0) {
Kenny Roota91203b2012-02-15 15:00:46 -0800539 close(mRandom);
540 }
541 }
542
543 bool open() {
544 const char* randomDevice = "/dev/urandom";
Kenny Root150ca932012-11-14 14:29:02 -0800545 mRandom = TEMP_FAILURE_RETRY(::open(randomDevice, O_RDONLY));
546 if (mRandom < 0) {
Kenny Roota91203b2012-02-15 15:00:46 -0800547 ALOGE("open: %s: %s", randomDevice, strerror(errno));
548 return false;
549 }
550 return true;
551 }
552
Kenny Root51878182012-03-13 12:53:19 -0700553 bool generate_random_data(uint8_t* data, size_t size) const {
Kenny Roota91203b2012-02-15 15:00:46 -0800554 return (readFully(mRandom, data, size) == size);
555 }
556
557private:
558 int mRandom;
559};
560
561/* Here is the file format. There are two parts in blob.value, the secret and
562 * the description. The secret is stored in ciphertext, and its original size
563 * can be found in blob.length. The description is stored after the secret in
564 * plaintext, and its size is specified in blob.info. The total size of the two
Kenny Root822c3a92012-03-23 16:34:39 -0700565 * parts must be no more than VALUE_SIZE bytes. The first field is the version,
Kenny Rootf9119d62013-04-03 09:22:15 -0700566 * the second is the blob's type, and the third byte is flags. Fields other
Kenny Roota91203b2012-02-15 15:00:46 -0800567 * than blob.info, blob.length, and blob.value are modified by encryptBlob()
568 * and decryptBlob(). Thus they should not be accessed from outside. */
569
Kenny Root822c3a92012-03-23 16:34:39 -0700570/* ** Note to future implementors of encryption: **
571 * Currently this is the construction:
572 * metadata || Enc(MD5(data) || data)
573 *
574 * This should be the construction used for encrypting if re-implementing:
575 *
576 * Derive independent keys for encryption and MAC:
577 * Kenc = AES_encrypt(masterKey, "Encrypt")
578 * Kmac = AES_encrypt(masterKey, "MAC")
579 *
580 * Store this:
581 * metadata || AES_CTR_encrypt(Kenc, rand_IV, data) ||
582 * HMAC(Kmac, metadata || Enc(data))
583 */
Kenny Roota91203b2012-02-15 15:00:46 -0800584struct __attribute__((packed)) blob {
Kenny Root822c3a92012-03-23 16:34:39 -0700585 uint8_t version;
586 uint8_t type;
Kenny Rootf9119d62013-04-03 09:22:15 -0700587 uint8_t flags;
Kenny Roota91203b2012-02-15 15:00:46 -0800588 uint8_t info;
589 uint8_t vector[AES_BLOCK_SIZE];
Kenny Root822c3a92012-03-23 16:34:39 -0700590 uint8_t encrypted[0]; // Marks offset to encrypted data.
Kenny Roota91203b2012-02-15 15:00:46 -0800591 uint8_t digest[MD5_DIGEST_LENGTH];
Kenny Root822c3a92012-03-23 16:34:39 -0700592 uint8_t digested[0]; // Marks offset to digested data.
Kenny Roota91203b2012-02-15 15:00:46 -0800593 int32_t length; // in network byte order when encrypted
594 uint8_t value[VALUE_SIZE + AES_BLOCK_SIZE];
595};
596
Kenny Root822c3a92012-03-23 16:34:39 -0700597typedef enum {
Kenny Rootd53bc922013-03-21 14:10:15 -0700598 TYPE_ANY = 0, // meta type that matches anything
Kenny Root822c3a92012-03-23 16:34:39 -0700599 TYPE_GENERIC = 1,
600 TYPE_MASTER_KEY = 2,
601 TYPE_KEY_PAIR = 3,
Chad Brubaker17d68b92015-02-05 22:04:16 -0800602 TYPE_KEYMASTER_10 = 4,
Kenny Root822c3a92012-03-23 16:34:39 -0700603} BlobType;
604
Kenny Rootf9119d62013-04-03 09:22:15 -0700605static const uint8_t CURRENT_BLOB_VERSION = 2;
Kenny Root822c3a92012-03-23 16:34:39 -0700606
Kenny Roota91203b2012-02-15 15:00:46 -0800607class Blob {
608public:
Chad Brubaker803f37f2015-07-29 13:53:36 -0700609 Blob(const uint8_t* value, size_t valueLength, const uint8_t* info, uint8_t infoLength,
Kenny Root07438c82012-11-02 15:41:02 -0700610 BlobType type) {
Alex Klyubin1773b442015-02-20 12:33:33 -0800611 memset(&mBlob, 0, sizeof(mBlob));
Chad Brubaker54b1e9a2015-08-12 13:40:31 -0700612 if (valueLength > VALUE_SIZE) {
613 valueLength = VALUE_SIZE;
Chad Brubaker803f37f2015-07-29 13:53:36 -0700614 ALOGW("Provided blob length too large");
615 }
Chad Brubaker54b1e9a2015-08-12 13:40:31 -0700616 if (infoLength + valueLength > VALUE_SIZE) {
617 infoLength = VALUE_SIZE - valueLength;
Chad Brubaker803f37f2015-07-29 13:53:36 -0700618 ALOGW("Provided info length too large");
619 }
Kenny Roota91203b2012-02-15 15:00:46 -0800620 mBlob.length = valueLength;
621 memcpy(mBlob.value, value, valueLength);
622
623 mBlob.info = infoLength;
624 memcpy(mBlob.value + valueLength, info, infoLength);
Kenny Root822c3a92012-03-23 16:34:39 -0700625
Kenny Root07438c82012-11-02 15:41:02 -0700626 mBlob.version = CURRENT_BLOB_VERSION;
Kenny Root822c3a92012-03-23 16:34:39 -0700627 mBlob.type = uint8_t(type);
Kenny Rootf9119d62013-04-03 09:22:15 -0700628
Kenny Rootee8068b2013-10-07 09:49:15 -0700629 if (type == TYPE_MASTER_KEY) {
630 mBlob.flags = KEYSTORE_FLAG_ENCRYPTED;
631 } else {
632 mBlob.flags = KEYSTORE_FLAG_NONE;
633 }
Kenny Roota91203b2012-02-15 15:00:46 -0800634 }
635
636 Blob(blob b) {
637 mBlob = b;
638 }
639
Alex Klyubin1773b442015-02-20 12:33:33 -0800640 Blob() {
641 memset(&mBlob, 0, sizeof(mBlob));
642 }
Kenny Roota91203b2012-02-15 15:00:46 -0800643
Kenny Root51878182012-03-13 12:53:19 -0700644 const uint8_t* getValue() const {
Kenny Roota91203b2012-02-15 15:00:46 -0800645 return mBlob.value;
646 }
647
Kenny Root51878182012-03-13 12:53:19 -0700648 int32_t getLength() const {
Kenny Roota91203b2012-02-15 15:00:46 -0800649 return mBlob.length;
650 }
651
Kenny Root51878182012-03-13 12:53:19 -0700652 const uint8_t* getInfo() const {
653 return mBlob.value + mBlob.length;
654 }
655
656 uint8_t getInfoLength() const {
Kenny Roota91203b2012-02-15 15:00:46 -0800657 return mBlob.info;
658 }
659
Kenny Root822c3a92012-03-23 16:34:39 -0700660 uint8_t getVersion() const {
661 return mBlob.version;
662 }
663
Kenny Rootf9119d62013-04-03 09:22:15 -0700664 bool isEncrypted() const {
665 if (mBlob.version < 2) {
666 return true;
667 }
668
669 return mBlob.flags & KEYSTORE_FLAG_ENCRYPTED;
670 }
671
672 void setEncrypted(bool encrypted) {
673 if (encrypted) {
674 mBlob.flags |= KEYSTORE_FLAG_ENCRYPTED;
675 } else {
676 mBlob.flags &= ~KEYSTORE_FLAG_ENCRYPTED;
677 }
678 }
679
Kenny Root17208e02013-09-04 13:56:03 -0700680 bool isFallback() const {
681 return mBlob.flags & KEYSTORE_FLAG_FALLBACK;
682 }
683
684 void setFallback(bool fallback) {
685 if (fallback) {
686 mBlob.flags |= KEYSTORE_FLAG_FALLBACK;
687 } else {
688 mBlob.flags &= ~KEYSTORE_FLAG_FALLBACK;
689 }
690 }
691
Kenny Root822c3a92012-03-23 16:34:39 -0700692 void setVersion(uint8_t version) {
693 mBlob.version = version;
694 }
695
696 BlobType getType() const {
697 return BlobType(mBlob.type);
698 }
699
700 void setType(BlobType type) {
701 mBlob.type = uint8_t(type);
702 }
703
Kenny Rootf9119d62013-04-03 09:22:15 -0700704 ResponseCode writeBlob(const char* filename, AES_KEY *aes_key, State state, Entropy* entropy) {
705 ALOGV("writing blob %s", filename);
706 if (isEncrypted()) {
707 if (state != STATE_NO_ERROR) {
708 ALOGD("couldn't insert encrypted blob while not unlocked");
709 return LOCKED;
710 }
711
712 if (!entropy->generate_random_data(mBlob.vector, AES_BLOCK_SIZE)) {
713 ALOGW("Could not read random data for: %s", filename);
714 return SYSTEM_ERROR;
715 }
Kenny Roota91203b2012-02-15 15:00:46 -0800716 }
717
718 // data includes the value and the value's length
719 size_t dataLength = mBlob.length + sizeof(mBlob.length);
720 // pad data to the AES_BLOCK_SIZE
721 size_t digestedLength = ((dataLength + AES_BLOCK_SIZE - 1)
722 / AES_BLOCK_SIZE * AES_BLOCK_SIZE);
723 // encrypted data includes the digest value
724 size_t encryptedLength = digestedLength + MD5_DIGEST_LENGTH;
725 // move info after space for padding
726 memmove(&mBlob.encrypted[encryptedLength], &mBlob.value[mBlob.length], mBlob.info);
727 // zero padding area
728 memset(mBlob.value + mBlob.length, 0, digestedLength - dataLength);
729
730 mBlob.length = htonl(mBlob.length);
Kenny Roota91203b2012-02-15 15:00:46 -0800731
Kenny Rootf9119d62013-04-03 09:22:15 -0700732 if (isEncrypted()) {
733 MD5(mBlob.digested, digestedLength, mBlob.digest);
Kenny Roota91203b2012-02-15 15:00:46 -0800734
Kenny Rootf9119d62013-04-03 09:22:15 -0700735 uint8_t vector[AES_BLOCK_SIZE];
736 memcpy(vector, mBlob.vector, AES_BLOCK_SIZE);
737 AES_cbc_encrypt(mBlob.encrypted, mBlob.encrypted, encryptedLength,
738 aes_key, vector, AES_ENCRYPT);
739 }
740
Kenny Roota91203b2012-02-15 15:00:46 -0800741 size_t headerLength = (mBlob.encrypted - (uint8_t*) &mBlob);
742 size_t fileLength = encryptedLength + headerLength + mBlob.info;
743
744 const char* tmpFileName = ".tmp";
Kenny Root150ca932012-11-14 14:29:02 -0800745 int out = TEMP_FAILURE_RETRY(open(tmpFileName,
746 O_WRONLY | O_TRUNC | O_CREAT, S_IRUSR | S_IWUSR));
747 if (out < 0) {
748 ALOGW("could not open file: %s: %s", tmpFileName, strerror(errno));
Kenny Roota91203b2012-02-15 15:00:46 -0800749 return SYSTEM_ERROR;
750 }
751 size_t writtenBytes = writeFully(out, (uint8_t*) &mBlob, fileLength);
752 if (close(out) != 0) {
753 return SYSTEM_ERROR;
754 }
755 if (writtenBytes != fileLength) {
Kenny Root150ca932012-11-14 14:29:02 -0800756 ALOGW("blob not fully written %zu != %zu", writtenBytes, fileLength);
Kenny Roota91203b2012-02-15 15:00:46 -0800757 unlink(tmpFileName);
758 return SYSTEM_ERROR;
759 }
Kenny Root150ca932012-11-14 14:29:02 -0800760 if (rename(tmpFileName, filename) == -1) {
761 ALOGW("could not rename blob to %s: %s", filename, strerror(errno));
762 return SYSTEM_ERROR;
763 }
764 return NO_ERROR;
Kenny Roota91203b2012-02-15 15:00:46 -0800765 }
766
Kenny Rootf9119d62013-04-03 09:22:15 -0700767 ResponseCode readBlob(const char* filename, AES_KEY *aes_key, State state) {
768 ALOGV("reading blob %s", filename);
Kenny Root150ca932012-11-14 14:29:02 -0800769 int in = TEMP_FAILURE_RETRY(open(filename, O_RDONLY));
770 if (in < 0) {
Kenny Roota91203b2012-02-15 15:00:46 -0800771 return (errno == ENOENT) ? KEY_NOT_FOUND : SYSTEM_ERROR;
772 }
773 // fileLength may be less than sizeof(mBlob) since the in
774 // memory version has extra padding to tolerate rounding up to
775 // the AES_BLOCK_SIZE
776 size_t fileLength = readFully(in, (uint8_t*) &mBlob, sizeof(mBlob));
777 if (close(in) != 0) {
778 return SYSTEM_ERROR;
779 }
Kenny Rootf9119d62013-04-03 09:22:15 -0700780
Chad Brubakera9a17ee2015-07-17 13:43:24 -0700781 if (fileLength == 0) {
782 return VALUE_CORRUPTED;
783 }
784
Kenny Rootf9119d62013-04-03 09:22:15 -0700785 if (isEncrypted() && (state != STATE_NO_ERROR)) {
786 return LOCKED;
787 }
788
Kenny Roota91203b2012-02-15 15:00:46 -0800789 size_t headerLength = (mBlob.encrypted - (uint8_t*) &mBlob);
790 if (fileLength < headerLength) {
791 return VALUE_CORRUPTED;
792 }
793
794 ssize_t encryptedLength = fileLength - (headerLength + mBlob.info);
Kenny Rootf9119d62013-04-03 09:22:15 -0700795 if (encryptedLength < 0) {
Kenny Roota91203b2012-02-15 15:00:46 -0800796 return VALUE_CORRUPTED;
797 }
Kenny Rootf9119d62013-04-03 09:22:15 -0700798
799 ssize_t digestedLength;
800 if (isEncrypted()) {
801 if (encryptedLength % AES_BLOCK_SIZE != 0) {
802 return VALUE_CORRUPTED;
803 }
804
805 AES_cbc_encrypt(mBlob.encrypted, mBlob.encrypted, encryptedLength, aes_key,
806 mBlob.vector, AES_DECRYPT);
807 digestedLength = encryptedLength - MD5_DIGEST_LENGTH;
808 uint8_t computedDigest[MD5_DIGEST_LENGTH];
809 MD5(mBlob.digested, digestedLength, computedDigest);
810 if (memcmp(mBlob.digest, computedDigest, MD5_DIGEST_LENGTH) != 0) {
811 return VALUE_CORRUPTED;
812 }
813 } else {
814 digestedLength = encryptedLength;
Kenny Roota91203b2012-02-15 15:00:46 -0800815 }
816
817 ssize_t maxValueLength = digestedLength - sizeof(mBlob.length);
818 mBlob.length = ntohl(mBlob.length);
819 if (mBlob.length < 0 || mBlob.length > maxValueLength) {
820 return VALUE_CORRUPTED;
821 }
822 if (mBlob.info != 0) {
823 // move info from after padding to after data
824 memmove(&mBlob.value[mBlob.length], &mBlob.value[maxValueLength], mBlob.info);
825 }
Kenny Root07438c82012-11-02 15:41:02 -0700826 return ::NO_ERROR;
Kenny Roota91203b2012-02-15 15:00:46 -0800827 }
828
829private:
830 struct blob mBlob;
831};
832
Kenny Root655b9582013-04-04 08:37:42 -0700833class UserState {
Kenny Roota91203b2012-02-15 15:00:46 -0800834public:
Kenny Root655b9582013-04-04 08:37:42 -0700835 UserState(uid_t userId) : mUserId(userId), mRetry(MAX_RETRY) {
836 asprintf(&mUserDir, "user_%u", mUserId);
837 asprintf(&mMasterKeyFile, "%s/.masterkey", mUserDir);
838 }
839
840 ~UserState() {
841 free(mUserDir);
842 free(mMasterKeyFile);
843 }
844
845 bool initialize() {
846 if ((mkdir(mUserDir, S_IRUSR | S_IWUSR | S_IXUSR) < 0) && (errno != EEXIST)) {
847 ALOGE("Could not create directory '%s'", mUserDir);
848 return false;
849 }
850
851 if (access(mMasterKeyFile, R_OK) == 0) {
Kenny Roota91203b2012-02-15 15:00:46 -0800852 setState(STATE_LOCKED);
853 } else {
854 setState(STATE_UNINITIALIZED);
855 }
Kenny Root70e3a862012-02-15 17:20:23 -0800856
Kenny Root655b9582013-04-04 08:37:42 -0700857 return true;
858 }
859
860 uid_t getUserId() const {
861 return mUserId;
862 }
863
864 const char* getUserDirName() const {
865 return mUserDir;
866 }
867
868 const char* getMasterKeyFileName() const {
869 return mMasterKeyFile;
870 }
871
872 void setState(State state) {
873 mState = state;
874 if (mState == STATE_NO_ERROR || mState == STATE_UNINITIALIZED) {
875 mRetry = MAX_RETRY;
876 }
Kenny Roota91203b2012-02-15 15:00:46 -0800877 }
878
Kenny Root51878182012-03-13 12:53:19 -0700879 State getState() const {
Kenny Roota91203b2012-02-15 15:00:46 -0800880 return mState;
881 }
882
Kenny Root51878182012-03-13 12:53:19 -0700883 int8_t getRetry() const {
Kenny Roota91203b2012-02-15 15:00:46 -0800884 return mRetry;
885 }
886
Kenny Root655b9582013-04-04 08:37:42 -0700887 void zeroizeMasterKeysInMemory() {
888 memset(mMasterKey, 0, sizeof(mMasterKey));
889 memset(mSalt, 0, sizeof(mSalt));
890 memset(&mMasterKeyEncryption, 0, sizeof(mMasterKeyEncryption));
891 memset(&mMasterKeyDecryption, 0, sizeof(mMasterKeyDecryption));
Kenny Root70e3a862012-02-15 17:20:23 -0800892 }
893
Chad Brubaker96d6d782015-05-07 10:19:40 -0700894 bool deleteMasterKey() {
895 setState(STATE_UNINITIALIZED);
896 zeroizeMasterKeysInMemory();
897 return unlink(mMasterKeyFile) == 0 || errno == ENOENT;
898 }
899
Kenny Root655b9582013-04-04 08:37:42 -0700900 ResponseCode initialize(const android::String8& pw, Entropy* entropy) {
901 if (!generateMasterKey(entropy)) {
Kenny Roota91203b2012-02-15 15:00:46 -0800902 return SYSTEM_ERROR;
903 }
Kenny Root655b9582013-04-04 08:37:42 -0700904 ResponseCode response = writeMasterKey(pw, entropy);
Kenny Roota91203b2012-02-15 15:00:46 -0800905 if (response != NO_ERROR) {
906 return response;
907 }
908 setupMasterKeys();
Kenny Root07438c82012-11-02 15:41:02 -0700909 return ::NO_ERROR;
Kenny Roota91203b2012-02-15 15:00:46 -0800910 }
911
Robin Lee4e865752014-08-19 17:37:55 +0100912 ResponseCode copyMasterKey(UserState* src) {
913 if (mState != STATE_UNINITIALIZED) {
914 return ::SYSTEM_ERROR;
915 }
916 if (src->getState() != STATE_NO_ERROR) {
917 return ::SYSTEM_ERROR;
918 }
919 memcpy(mMasterKey, src->mMasterKey, MASTER_KEY_SIZE_BYTES);
920 setupMasterKeys();
921 return ::NO_ERROR;
922 }
923
Kenny Root655b9582013-04-04 08:37:42 -0700924 ResponseCode writeMasterKey(const android::String8& pw, Entropy* entropy) {
Kenny Roota91203b2012-02-15 15:00:46 -0800925 uint8_t passwordKey[MASTER_KEY_SIZE_BYTES];
926 generateKeyFromPassword(passwordKey, MASTER_KEY_SIZE_BYTES, pw, mSalt);
927 AES_KEY passwordAesKey;
928 AES_set_encrypt_key(passwordKey, MASTER_KEY_SIZE_BITS, &passwordAesKey);
Kenny Root822c3a92012-03-23 16:34:39 -0700929 Blob masterKeyBlob(mMasterKey, sizeof(mMasterKey), mSalt, sizeof(mSalt), TYPE_MASTER_KEY);
Kenny Rootf9119d62013-04-03 09:22:15 -0700930 return masterKeyBlob.writeBlob(mMasterKeyFile, &passwordAesKey, STATE_NO_ERROR, entropy);
Kenny Roota91203b2012-02-15 15:00:46 -0800931 }
932
Kenny Root655b9582013-04-04 08:37:42 -0700933 ResponseCode readMasterKey(const android::String8& pw, Entropy* entropy) {
934 int in = TEMP_FAILURE_RETRY(open(mMasterKeyFile, O_RDONLY));
Kenny Root150ca932012-11-14 14:29:02 -0800935 if (in < 0) {
Kenny Roota91203b2012-02-15 15:00:46 -0800936 return SYSTEM_ERROR;
937 }
938
939 // we read the raw blob to just to get the salt to generate
940 // the AES key, then we create the Blob to use with decryptBlob
941 blob rawBlob;
942 size_t length = readFully(in, (uint8_t*) &rawBlob, sizeof(rawBlob));
943 if (close(in) != 0) {
944 return SYSTEM_ERROR;
945 }
946 // find salt at EOF if present, otherwise we have an old file
947 uint8_t* salt;
948 if (length > SALT_SIZE && rawBlob.info == SALT_SIZE) {
949 salt = (uint8_t*) &rawBlob + length - SALT_SIZE;
950 } else {
951 salt = NULL;
952 }
953 uint8_t passwordKey[MASTER_KEY_SIZE_BYTES];
954 generateKeyFromPassword(passwordKey, MASTER_KEY_SIZE_BYTES, pw, salt);
955 AES_KEY passwordAesKey;
956 AES_set_decrypt_key(passwordKey, MASTER_KEY_SIZE_BITS, &passwordAesKey);
957 Blob masterKeyBlob(rawBlob);
Kenny Rootf9119d62013-04-03 09:22:15 -0700958 ResponseCode response = masterKeyBlob.readBlob(mMasterKeyFile, &passwordAesKey,
959 STATE_NO_ERROR);
Kenny Roota91203b2012-02-15 15:00:46 -0800960 if (response == SYSTEM_ERROR) {
Kenny Rootf9119d62013-04-03 09:22:15 -0700961 return response;
Kenny Roota91203b2012-02-15 15:00:46 -0800962 }
963 if (response == NO_ERROR && masterKeyBlob.getLength() == MASTER_KEY_SIZE_BYTES) {
964 // if salt was missing, generate one and write a new master key file with the salt.
965 if (salt == NULL) {
Kenny Root655b9582013-04-04 08:37:42 -0700966 if (!generateSalt(entropy)) {
Kenny Roota91203b2012-02-15 15:00:46 -0800967 return SYSTEM_ERROR;
968 }
Kenny Root655b9582013-04-04 08:37:42 -0700969 response = writeMasterKey(pw, entropy);
Kenny Roota91203b2012-02-15 15:00:46 -0800970 }
971 if (response == NO_ERROR) {
972 memcpy(mMasterKey, masterKeyBlob.getValue(), MASTER_KEY_SIZE_BYTES);
973 setupMasterKeys();
974 }
975 return response;
976 }
977 if (mRetry <= 0) {
978 reset();
979 return UNINITIALIZED;
980 }
981 --mRetry;
982 switch (mRetry) {
983 case 0: return WRONG_PASSWORD_0;
984 case 1: return WRONG_PASSWORD_1;
985 case 2: return WRONG_PASSWORD_2;
986 case 3: return WRONG_PASSWORD_3;
987 default: return WRONG_PASSWORD_3;
988 }
989 }
990
Kenny Root655b9582013-04-04 08:37:42 -0700991 AES_KEY* getEncryptionKey() {
992 return &mMasterKeyEncryption;
993 }
994
995 AES_KEY* getDecryptionKey() {
996 return &mMasterKeyDecryption;
997 }
998
Kenny Roota91203b2012-02-15 15:00:46 -0800999 bool reset() {
Kenny Root655b9582013-04-04 08:37:42 -07001000 DIR* dir = opendir(getUserDirName());
Kenny Roota91203b2012-02-15 15:00:46 -08001001 if (!dir) {
Chad Brubaker96d6d782015-05-07 10:19:40 -07001002 // If the directory doesn't exist then nothing to do.
1003 if (errno == ENOENT) {
1004 return true;
1005 }
Kenny Root655b9582013-04-04 08:37:42 -07001006 ALOGW("couldn't open user directory: %s", strerror(errno));
Kenny Roota91203b2012-02-15 15:00:46 -08001007 return false;
1008 }
Kenny Root655b9582013-04-04 08:37:42 -07001009
1010 struct dirent* file;
Kenny Roota91203b2012-02-15 15:00:46 -08001011 while ((file = readdir(dir)) != NULL) {
Chad Brubaker96d6d782015-05-07 10:19:40 -07001012 // skip . and ..
1013 if (!strcmp(".", file->d_name) || !strcmp("..", file->d_name)) {
Kenny Root655b9582013-04-04 08:37:42 -07001014 continue;
1015 }
1016
1017 unlinkat(dirfd(dir), file->d_name, 0);
Kenny Roota91203b2012-02-15 15:00:46 -08001018 }
1019 closedir(dir);
1020 return true;
1021 }
1022
Kenny Root655b9582013-04-04 08:37:42 -07001023private:
1024 static const int MASTER_KEY_SIZE_BYTES = 16;
1025 static const int MASTER_KEY_SIZE_BITS = MASTER_KEY_SIZE_BYTES * 8;
1026
1027 static const int MAX_RETRY = 4;
1028 static const size_t SALT_SIZE = 16;
1029
1030 void generateKeyFromPassword(uint8_t* key, ssize_t keySize, const android::String8& pw,
1031 uint8_t* salt) {
1032 size_t saltSize;
1033 if (salt != NULL) {
1034 saltSize = SALT_SIZE;
1035 } else {
1036 // pre-gingerbread used this hardwired salt, readMasterKey will rewrite these when found
1037 salt = (uint8_t*) "keystore";
1038 // sizeof = 9, not strlen = 8
1039 saltSize = sizeof("keystore");
1040 }
1041
1042 PKCS5_PBKDF2_HMAC_SHA1(reinterpret_cast<const char*>(pw.string()), pw.length(), salt,
1043 saltSize, 8192, keySize, key);
1044 }
1045
1046 bool generateSalt(Entropy* entropy) {
1047 return entropy->generate_random_data(mSalt, sizeof(mSalt));
1048 }
1049
1050 bool generateMasterKey(Entropy* entropy) {
1051 if (!entropy->generate_random_data(mMasterKey, sizeof(mMasterKey))) {
1052 return false;
1053 }
1054 if (!generateSalt(entropy)) {
1055 return false;
1056 }
1057 return true;
1058 }
1059
1060 void setupMasterKeys() {
1061 AES_set_encrypt_key(mMasterKey, MASTER_KEY_SIZE_BITS, &mMasterKeyEncryption);
1062 AES_set_decrypt_key(mMasterKey, MASTER_KEY_SIZE_BITS, &mMasterKeyDecryption);
1063 setState(STATE_NO_ERROR);
1064 }
1065
1066 uid_t mUserId;
1067
1068 char* mUserDir;
1069 char* mMasterKeyFile;
1070
1071 State mState;
1072 int8_t mRetry;
1073
1074 uint8_t mMasterKey[MASTER_KEY_SIZE_BYTES];
1075 uint8_t mSalt[SALT_SIZE];
1076
1077 AES_KEY mMasterKeyEncryption;
1078 AES_KEY mMasterKeyDecryption;
1079};
1080
1081typedef struct {
1082 uint32_t uid;
1083 const uint8_t* filename;
1084} grant_t;
1085
1086class KeyStore {
1087public:
Chad Brubaker67d2a502015-03-11 17:21:18 +00001088 KeyStore(Entropy* entropy, keymaster1_device_t* device, keymaster1_device_t* fallback)
Kenny Root655b9582013-04-04 08:37:42 -07001089 : mEntropy(entropy)
1090 , mDevice(device)
Chad Brubakerfc18edc2015-01-12 15:17:18 -08001091 , mFallbackDevice(fallback)
Kenny Root655b9582013-04-04 08:37:42 -07001092 {
1093 memset(&mMetaData, '\0', sizeof(mMetaData));
1094 }
1095
1096 ~KeyStore() {
1097 for (android::Vector<grant_t*>::iterator it(mGrants.begin());
1098 it != mGrants.end(); it++) {
1099 delete *it;
Kenny Root655b9582013-04-04 08:37:42 -07001100 }
haitao fangc35d4eb2013-12-06 11:34:49 +08001101 mGrants.clear();
Kenny Root655b9582013-04-04 08:37:42 -07001102
1103 for (android::Vector<UserState*>::iterator it(mMasterKeys.begin());
1104 it != mMasterKeys.end(); it++) {
1105 delete *it;
Kenny Root655b9582013-04-04 08:37:42 -07001106 }
haitao fangc35d4eb2013-12-06 11:34:49 +08001107 mMasterKeys.clear();
Kenny Root655b9582013-04-04 08:37:42 -07001108 }
1109
Chad Brubaker67d2a502015-03-11 17:21:18 +00001110 /**
1111 * Depending on the hardware keymaster version is this may return a
1112 * keymaster0_device_t* cast to a keymaster1_device_t*. All methods from
1113 * keymaster0 are safe to call, calls to keymaster1_device_t methods should
1114 * be guarded by a check on the device's version.
1115 */
1116 keymaster1_device_t *getDevice() const {
Kenny Root655b9582013-04-04 08:37:42 -07001117 return mDevice;
1118 }
1119
Chad Brubaker67d2a502015-03-11 17:21:18 +00001120 keymaster1_device_t *getFallbackDevice() const {
Chad Brubakerfc18edc2015-01-12 15:17:18 -08001121 return mFallbackDevice;
1122 }
1123
Chad Brubaker67d2a502015-03-11 17:21:18 +00001124 keymaster1_device_t *getDeviceForBlob(const Blob& blob) const {
Chad Brubakerfc18edc2015-01-12 15:17:18 -08001125 return blob.isFallback() ? mFallbackDevice: mDevice;
1126 }
1127
Kenny Root655b9582013-04-04 08:37:42 -07001128 ResponseCode initialize() {
1129 readMetaData();
1130 if (upgradeKeystore()) {
1131 writeMetaData();
1132 }
1133
1134 return ::NO_ERROR;
1135 }
1136
Chad Brubaker72593ee2015-05-12 10:42:00 -07001137 State getState(uid_t userId) {
1138 return getUserState(userId)->getState();
Kenny Root655b9582013-04-04 08:37:42 -07001139 }
1140
Chad Brubaker72593ee2015-05-12 10:42:00 -07001141 ResponseCode initializeUser(const android::String8& pw, uid_t userId) {
1142 UserState* userState = getUserState(userId);
Kenny Root655b9582013-04-04 08:37:42 -07001143 return userState->initialize(pw, mEntropy);
1144 }
1145
Chad Brubaker72593ee2015-05-12 10:42:00 -07001146 ResponseCode copyMasterKey(uid_t srcUser, uid_t dstUser) {
1147 UserState *userState = getUserState(dstUser);
1148 UserState *initState = getUserState(srcUser);
Robin Lee4e865752014-08-19 17:37:55 +01001149 return userState->copyMasterKey(initState);
1150 }
1151
Chad Brubaker72593ee2015-05-12 10:42:00 -07001152 ResponseCode writeMasterKey(const android::String8& pw, uid_t userId) {
1153 UserState* userState = getUserState(userId);
Kenny Root655b9582013-04-04 08:37:42 -07001154 return userState->writeMasterKey(pw, mEntropy);
1155 }
1156
Chad Brubaker72593ee2015-05-12 10:42:00 -07001157 ResponseCode readMasterKey(const android::String8& pw, uid_t userId) {
1158 UserState* userState = getUserState(userId);
Kenny Root655b9582013-04-04 08:37:42 -07001159 return userState->readMasterKey(pw, mEntropy);
1160 }
1161
1162 android::String8 getKeyName(const android::String8& keyName) {
Douglas Leunga77e8092013-06-13 16:34:43 -07001163 char encoded[encode_key_length(keyName) + 1]; // add 1 for null char
Kenny Root655b9582013-04-04 08:37:42 -07001164 encode_key(encoded, keyName);
1165 return android::String8(encoded);
1166 }
1167
1168 android::String8 getKeyNameForUid(const android::String8& keyName, uid_t uid) {
Douglas Leunga77e8092013-06-13 16:34:43 -07001169 char encoded[encode_key_length(keyName) + 1]; // add 1 for null char
Kenny Root655b9582013-04-04 08:37:42 -07001170 encode_key(encoded, keyName);
1171 return android::String8::format("%u_%s", uid, encoded);
1172 }
1173
1174 android::String8 getKeyNameForUidWithDir(const android::String8& keyName, uid_t uid) {
Douglas Leunga77e8092013-06-13 16:34:43 -07001175 char encoded[encode_key_length(keyName) + 1]; // add 1 for null char
Kenny Root655b9582013-04-04 08:37:42 -07001176 encode_key(encoded, keyName);
Chad Brubaker72593ee2015-05-12 10:42:00 -07001177 return android::String8::format("%s/%u_%s", getUserStateByUid(uid)->getUserDirName(), uid,
Kenny Root655b9582013-04-04 08:37:42 -07001178 encoded);
1179 }
1180
Chad Brubaker96d6d782015-05-07 10:19:40 -07001181 /*
1182 * Delete entries owned by userId. If keepUnencryptedEntries is true
1183 * then only encrypted entries will be removed, otherwise all entries will
1184 * be removed.
1185 */
1186 void resetUser(uid_t userId, bool keepUnenryptedEntries) {
Robin Lee4b84fdc2014-09-24 11:56:57 +01001187 android::String8 prefix("");
1188 android::Vector<android::String16> aliases;
Chad Brubaker72593ee2015-05-12 10:42:00 -07001189 UserState* userState = getUserState(userId);
Chad Brubakere6c3bfa2015-05-12 15:18:26 -07001190 if (list(prefix, &aliases, userId) != ::NO_ERROR) {
Chad Brubaker96d6d782015-05-07 10:19:40 -07001191 return;
1192 }
Robin Lee4b84fdc2014-09-24 11:56:57 +01001193 for (uint32_t i = 0; i < aliases.size(); i++) {
1194 android::String8 filename(aliases[i]);
1195 filename = android::String8::format("%s/%s", userState->getUserDirName(),
Chad Brubaker96d6d782015-05-07 10:19:40 -07001196 getKeyName(filename).string());
1197 bool shouldDelete = true;
1198 if (keepUnenryptedEntries) {
1199 Blob blob;
Chad Brubaker72593ee2015-05-12 10:42:00 -07001200 ResponseCode rc = get(filename, &blob, ::TYPE_ANY, userId);
Robin Lee4b84fdc2014-09-24 11:56:57 +01001201
Chad Brubaker96d6d782015-05-07 10:19:40 -07001202 /* get can fail if the blob is encrypted and the state is
1203 * not unlocked, only skip deleting blobs that were loaded and
1204 * who are not encrypted. If there are blobs we fail to read for
1205 * other reasons err on the safe side and delete them since we
1206 * can't tell if they're encrypted.
1207 */
1208 shouldDelete = !(rc == ::NO_ERROR && !blob.isEncrypted());
1209 }
1210 if (shouldDelete) {
Chad Brubaker72593ee2015-05-12 10:42:00 -07001211 del(filename, ::TYPE_ANY, userId);
Chad Brubaker96d6d782015-05-07 10:19:40 -07001212 }
1213 }
1214 if (!userState->deleteMasterKey()) {
1215 ALOGE("Failed to delete user %d's master key", userId);
1216 }
1217 if (!keepUnenryptedEntries) {
1218 if(!userState->reset()) {
1219 ALOGE("Failed to remove user %d's directory", userId);
1220 }
1221 }
Kenny Root655b9582013-04-04 08:37:42 -07001222 }
1223
Chad Brubaker72593ee2015-05-12 10:42:00 -07001224 bool isEmpty(uid_t userId) const {
1225 const UserState* userState = getUserState(userId);
Chad Brubaker96d6d782015-05-07 10:19:40 -07001226 if (userState == NULL) {
Kenny Root655b9582013-04-04 08:37:42 -07001227 return true;
1228 }
1229
1230 DIR* dir = opendir(userState->getUserDirName());
Kenny Roota91203b2012-02-15 15:00:46 -08001231 if (!dir) {
1232 return true;
1233 }
Kenny Root31e27462014-09-10 11:28:03 -07001234
Kenny Roota91203b2012-02-15 15:00:46 -08001235 bool result = true;
Kenny Root31e27462014-09-10 11:28:03 -07001236 struct dirent* file;
Kenny Roota91203b2012-02-15 15:00:46 -08001237 while ((file = readdir(dir)) != NULL) {
Kenny Root655b9582013-04-04 08:37:42 -07001238 // We only care about files.
1239 if (file->d_type != DT_REG) {
1240 continue;
1241 }
1242
1243 // Skip anything that starts with a "."
1244 if (file->d_name[0] == '.') {
1245 continue;
1246 }
1247
Kenny Root31e27462014-09-10 11:28:03 -07001248 result = false;
1249 break;
Kenny Roota91203b2012-02-15 15:00:46 -08001250 }
1251 closedir(dir);
1252 return result;
1253 }
1254
Chad Brubaker72593ee2015-05-12 10:42:00 -07001255 void lock(uid_t userId) {
1256 UserState* userState = getUserState(userId);
Kenny Root655b9582013-04-04 08:37:42 -07001257 userState->zeroizeMasterKeysInMemory();
1258 userState->setState(STATE_LOCKED);
Kenny Roota91203b2012-02-15 15:00:46 -08001259 }
1260
Chad Brubaker72593ee2015-05-12 10:42:00 -07001261 ResponseCode get(const char* filename, Blob* keyBlob, const BlobType type, uid_t userId) {
1262 UserState* userState = getUserState(userId);
Kenny Rootf9119d62013-04-03 09:22:15 -07001263 ResponseCode rc = keyBlob->readBlob(filename, userState->getDecryptionKey(),
1264 userState->getState());
Kenny Root822c3a92012-03-23 16:34:39 -07001265 if (rc != NO_ERROR) {
1266 return rc;
1267 }
1268
1269 const uint8_t version = keyBlob->getVersion();
Kenny Root07438c82012-11-02 15:41:02 -07001270 if (version < CURRENT_BLOB_VERSION) {
Kenny Rootcfeae072013-04-04 08:39:57 -07001271 /* If we upgrade the key, we need to write it to disk again. Then
1272 * it must be read it again since the blob is encrypted each time
1273 * it's written.
1274 */
Chad Brubaker72593ee2015-05-12 10:42:00 -07001275 if (upgradeBlob(filename, keyBlob, version, type, userId)) {
1276 if ((rc = this->put(filename, keyBlob, userId)) != NO_ERROR
Kenny Rootf9119d62013-04-03 09:22:15 -07001277 || (rc = keyBlob->readBlob(filename, userState->getDecryptionKey(),
1278 userState->getState())) != NO_ERROR) {
Kenny Rootcfeae072013-04-04 08:39:57 -07001279 return rc;
1280 }
1281 }
Kenny Root822c3a92012-03-23 16:34:39 -07001282 }
1283
Kenny Root17208e02013-09-04 13:56:03 -07001284 /*
1285 * This will upgrade software-backed keys to hardware-backed keys when
1286 * the HAL for the device supports the newer key types.
1287 */
1288 if (rc == NO_ERROR && type == TYPE_KEY_PAIR
1289 && mDevice->common.module->module_api_version >= KEYMASTER_MODULE_API_VERSION_0_2
1290 && keyBlob->isFallback()) {
1291 ResponseCode imported = importKey(keyBlob->getValue(), keyBlob->getLength(), filename,
Chad Brubaker72593ee2015-05-12 10:42:00 -07001292 userId, keyBlob->isEncrypted() ? KEYSTORE_FLAG_ENCRYPTED : KEYSTORE_FLAG_NONE);
Kenny Root17208e02013-09-04 13:56:03 -07001293
1294 // The HAL allowed the import, reget the key to have the "fresh"
1295 // version.
1296 if (imported == NO_ERROR) {
Chad Brubaker72593ee2015-05-12 10:42:00 -07001297 rc = get(filename, keyBlob, TYPE_KEY_PAIR, userId);
Kenny Root17208e02013-09-04 13:56:03 -07001298 }
1299 }
1300
Chad Brubaker3a7d9e62015-06-04 15:01:46 -07001301 // Keymaster 0.3 keys are valid keymaster 1.0 keys, so silently upgrade.
1302 if (keyBlob->getType() == TYPE_KEY_PAIR) {
Chad Brubaker3cc40122015-06-04 13:49:44 -07001303 keyBlob->setType(TYPE_KEYMASTER_10);
Chad Brubaker3a7d9e62015-06-04 15:01:46 -07001304 rc = this->put(filename, keyBlob, userId);
Chad Brubaker3cc40122015-06-04 13:49:44 -07001305 }
1306
Kenny Rootd53bc922013-03-21 14:10:15 -07001307 if (type != TYPE_ANY && keyBlob->getType() != type) {
Kenny Root822c3a92012-03-23 16:34:39 -07001308 ALOGW("key found but type doesn't match: %d vs %d", keyBlob->getType(), type);
1309 return KEY_NOT_FOUND;
1310 }
1311
1312 return rc;
Kenny Roota91203b2012-02-15 15:00:46 -08001313 }
1314
Chad Brubaker72593ee2015-05-12 10:42:00 -07001315 ResponseCode put(const char* filename, Blob* keyBlob, uid_t userId) {
1316 UserState* userState = getUserState(userId);
Kenny Rootf9119d62013-04-03 09:22:15 -07001317 return keyBlob->writeBlob(filename, userState->getEncryptionKey(), userState->getState(),
1318 mEntropy);
Kenny Roota91203b2012-02-15 15:00:46 -08001319 }
1320
Chad Brubaker72593ee2015-05-12 10:42:00 -07001321 ResponseCode del(const char *filename, const BlobType type, uid_t userId) {
Robin Lee4b84fdc2014-09-24 11:56:57 +01001322 Blob keyBlob;
Chad Brubaker72593ee2015-05-12 10:42:00 -07001323 ResponseCode rc = get(filename, &keyBlob, type, userId);
Chad Brubakera9a17ee2015-07-17 13:43:24 -07001324 if (rc == ::VALUE_CORRUPTED) {
1325 // The file is corrupt, the best we can do is rm it.
1326 return (unlink(filename) && errno != ENOENT) ? ::SYSTEM_ERROR : ::NO_ERROR;
1327 }
Robin Lee4b84fdc2014-09-24 11:56:57 +01001328 if (rc != ::NO_ERROR) {
1329 return rc;
1330 }
1331
1332 if (keyBlob.getType() == ::TYPE_KEY_PAIR) {
Shawn Willden55268b52015-07-28 11:06:00 -06001333 // A device doesn't have to implement delete_key.
1334 if (mDevice->delete_key != NULL && !keyBlob.isFallback()) {
1335 keymaster_key_blob_t blob = {keyBlob.getValue(),
1336 static_cast<size_t>(keyBlob.getLength())};
1337 if (mDevice->delete_key(mDevice, &blob)) {
Robin Lee4b84fdc2014-09-24 11:56:57 +01001338 rc = ::SYSTEM_ERROR;
1339 }
1340 }
1341 }
Chad Brubaker17d68b92015-02-05 22:04:16 -08001342 if (keyBlob.getType() == ::TYPE_KEYMASTER_10) {
1343 keymaster1_device_t* dev = getDeviceForBlob(keyBlob);
1344 if (dev->delete_key) {
1345 keymaster_key_blob_t blob;
1346 blob.key_material = keyBlob.getValue();
1347 blob.key_material_size = keyBlob.getLength();
1348 dev->delete_key(dev, &blob);
1349 }
1350 }
Robin Lee4b84fdc2014-09-24 11:56:57 +01001351 if (rc != ::NO_ERROR) {
1352 return rc;
1353 }
1354
1355 return (unlink(filename) && errno != ENOENT) ? ::SYSTEM_ERROR : ::NO_ERROR;
1356 }
1357
Chad Brubakere6c3bfa2015-05-12 15:18:26 -07001358 ResponseCode list(const android::String8& prefix, android::Vector<android::String16> *matches,
Chad Brubaker72593ee2015-05-12 10:42:00 -07001359 uid_t userId) {
Robin Lee4b84fdc2014-09-24 11:56:57 +01001360
Chad Brubaker72593ee2015-05-12 10:42:00 -07001361 UserState* userState = getUserState(userId);
Robin Lee4b84fdc2014-09-24 11:56:57 +01001362 size_t n = prefix.length();
1363
1364 DIR* dir = opendir(userState->getUserDirName());
1365 if (!dir) {
1366 ALOGW("can't open directory for user: %s", strerror(errno));
1367 return ::SYSTEM_ERROR;
1368 }
1369
1370 struct dirent* file;
1371 while ((file = readdir(dir)) != NULL) {
1372 // We only care about files.
1373 if (file->d_type != DT_REG) {
1374 continue;
1375 }
1376
1377 // Skip anything that starts with a "."
1378 if (file->d_name[0] == '.') {
1379 continue;
1380 }
1381
1382 if (!strncmp(prefix.string(), file->d_name, n)) {
1383 const char* p = &file->d_name[n];
1384 size_t plen = strlen(p);
1385
1386 size_t extra = decode_key_length(p, plen);
1387 char *match = (char*) malloc(extra + 1);
1388 if (match != NULL) {
1389 decode_key(match, p, plen);
1390 matches->push(android::String16(match, extra));
1391 free(match);
1392 } else {
1393 ALOGW("could not allocate match of size %zd", extra);
1394 }
1395 }
1396 }
1397 closedir(dir);
1398 return ::NO_ERROR;
1399 }
1400
Kenny Root07438c82012-11-02 15:41:02 -07001401 void addGrant(const char* filename, uid_t granteeUid) {
Kenny Root655b9582013-04-04 08:37:42 -07001402 const grant_t* existing = getGrant(filename, granteeUid);
1403 if (existing == NULL) {
1404 grant_t* grant = new grant_t;
Kenny Root07438c82012-11-02 15:41:02 -07001405 grant->uid = granteeUid;
Brian Carlstroma8c703d2012-07-17 14:43:46 -07001406 grant->filename = reinterpret_cast<const uint8_t*>(strdup(filename));
Kenny Root655b9582013-04-04 08:37:42 -07001407 mGrants.add(grant);
Kenny Root70e3a862012-02-15 17:20:23 -08001408 }
1409 }
1410
Kenny Root07438c82012-11-02 15:41:02 -07001411 bool removeGrant(const char* filename, uid_t granteeUid) {
Kenny Root655b9582013-04-04 08:37:42 -07001412 for (android::Vector<grant_t*>::iterator it(mGrants.begin());
1413 it != mGrants.end(); it++) {
1414 grant_t* grant = *it;
1415 if (grant->uid == granteeUid
1416 && !strcmp(reinterpret_cast<const char*>(grant->filename), filename)) {
1417 mGrants.erase(it);
1418 return true;
1419 }
Kenny Root70e3a862012-02-15 17:20:23 -08001420 }
Kenny Root70e3a862012-02-15 17:20:23 -08001421 return false;
1422 }
1423
Brian Carlstroma8c703d2012-07-17 14:43:46 -07001424 bool hasGrant(const char* filename, const uid_t uid) const {
1425 return getGrant(filename, uid) != NULL;
Kenny Root70e3a862012-02-15 17:20:23 -08001426 }
1427
Chad Brubaker72593ee2015-05-12 10:42:00 -07001428 ResponseCode importKey(const uint8_t* key, size_t keyLen, const char* filename, uid_t userId,
Kenny Rootf9119d62013-04-03 09:22:15 -07001429 int32_t flags) {
Shawn Willden55268b52015-07-28 11:06:00 -06001430 Unique_PKCS8_PRIV_KEY_INFO pkcs8(d2i_PKCS8_PRIV_KEY_INFO(NULL, &key, keyLen));
1431 if (!pkcs8.get()) {
1432 return ::SYSTEM_ERROR;
1433 }
1434 Unique_EVP_PKEY pkey(EVP_PKCS82PKEY(pkcs8.get()));
1435 if (!pkey.get()) {
1436 return ::SYSTEM_ERROR;
1437 }
1438 int type = EVP_PKEY_type(pkey->type);
1439 android::KeymasterArguments params;
1440 add_legacy_key_authorizations(type, &params.params);
1441 switch (type) {
1442 case EVP_PKEY_RSA:
1443 params.params.push_back(keymaster_param_enum(KM_TAG_ALGORITHM, KM_ALGORITHM_RSA));
1444 break;
1445 case EVP_PKEY_EC:
1446 params.params.push_back(keymaster_param_enum(KM_TAG_ALGORITHM,
1447 KM_ALGORITHM_EC));
1448 break;
1449 default:
1450 ALOGW("Unsupported key type %d", type);
1451 return ::SYSTEM_ERROR;
Kenny Root822c3a92012-03-23 16:34:39 -07001452 }
1453
Shawn Willden55268b52015-07-28 11:06:00 -06001454 std::vector<keymaster_key_param_t> opParams(params.params);
1455 const keymaster_key_param_set_t inParams = {opParams.data(), opParams.size()};
1456 keymaster_blob_t input = {key, keyLen};
1457 keymaster_key_blob_t blob = {nullptr, 0};
Kenny Root17208e02013-09-04 13:56:03 -07001458 bool isFallback = false;
Shawn Willden55268b52015-07-28 11:06:00 -06001459 keymaster_error_t error = mDevice->import_key(mDevice, &inParams, KM_KEY_FORMAT_PKCS8,
1460 &input, &blob, NULL /* characteristics */);
1461 if (error != KM_ERROR_OK){
1462 ALOGE("Keymaster error %d importing key pair, falling back", error);
1463
Kenny Roota39da5a2014-09-25 13:07:24 -07001464 /*
Shawn Willden55268b52015-07-28 11:06:00 -06001465 * There should be no way to get here. Fallback shouldn't ever really happen
1466 * because the main device may be many (SW, KM0/SW hybrid, KM1/SW hybrid), but it must
1467 * provide full support of the API. In any case, we'll do the fallback just for
1468 * consistency... and I suppose to cover for broken HW implementations.
Kenny Roota39da5a2014-09-25 13:07:24 -07001469 */
Shawn Willden55268b52015-07-28 11:06:00 -06001470 error = mFallbackDevice->import_key(mFallbackDevice, &inParams, KM_KEY_FORMAT_PKCS8,
1471 &input, &blob, NULL /* characteristics */);
Kenny Roota39da5a2014-09-25 13:07:24 -07001472 isFallback = true;
Kenny Root17208e02013-09-04 13:56:03 -07001473
Shawn Willden55268b52015-07-28 11:06:00 -06001474 if (error) {
1475 ALOGE("Keymaster error while importing key pair with fallback: %d", error);
Kenny Root17208e02013-09-04 13:56:03 -07001476 return SYSTEM_ERROR;
1477 }
Kenny Root822c3a92012-03-23 16:34:39 -07001478 }
1479
Shawn Willden55268b52015-07-28 11:06:00 -06001480 Blob keyBlob(blob.key_material, blob.key_material_size, NULL, 0, TYPE_KEYMASTER_10);
1481 free(const_cast<uint8_t*>(blob.key_material));
Kenny Root822c3a92012-03-23 16:34:39 -07001482
Kenny Rootf9119d62013-04-03 09:22:15 -07001483 keyBlob.setEncrypted(flags & KEYSTORE_FLAG_ENCRYPTED);
Kenny Root17208e02013-09-04 13:56:03 -07001484 keyBlob.setFallback(isFallback);
Kenny Rootf9119d62013-04-03 09:22:15 -07001485
Chad Brubaker72593ee2015-05-12 10:42:00 -07001486 return put(filename, &keyBlob, userId);
Kenny Root822c3a92012-03-23 16:34:39 -07001487 }
1488
Kenny Root1b0e3932013-09-05 13:06:32 -07001489 bool isHardwareBacked(const android::String16& keyType) const {
1490 if (mDevice == NULL) {
1491 ALOGW("can't get keymaster device");
1492 return false;
1493 }
1494
1495 if (sRSAKeyType == keyType) {
1496 return (mDevice->flags & KEYMASTER_SOFTWARE_ONLY) == 0;
1497 } else {
1498 return (mDevice->flags & KEYMASTER_SOFTWARE_ONLY) == 0
1499 && (mDevice->common.module->module_api_version
1500 >= KEYMASTER_MODULE_API_VERSION_0_2);
1501 }
Kenny Root8ddf35a2013-03-29 11:15:50 -07001502 }
1503
Kenny Root655b9582013-04-04 08:37:42 -07001504 ResponseCode getKeyForName(Blob* keyBlob, const android::String8& keyName, const uid_t uid,
1505 const BlobType type) {
Kenny Root86b16e82013-09-09 11:15:54 -07001506 android::String8 filepath8(getKeyNameForUidWithDir(keyName, uid));
Chad Brubaker72593ee2015-05-12 10:42:00 -07001507 uid_t userId = get_user_id(uid);
Kenny Root655b9582013-04-04 08:37:42 -07001508
Chad Brubaker72593ee2015-05-12 10:42:00 -07001509 ResponseCode responseCode = get(filepath8.string(), keyBlob, type, userId);
Kenny Root655b9582013-04-04 08:37:42 -07001510 if (responseCode == NO_ERROR) {
1511 return responseCode;
1512 }
1513
1514 // If this is one of the legacy UID->UID mappings, use it.
1515 uid_t euid = get_keystore_euid(uid);
1516 if (euid != uid) {
Kenny Root86b16e82013-09-09 11:15:54 -07001517 filepath8 = getKeyNameForUidWithDir(keyName, euid);
Chad Brubaker72593ee2015-05-12 10:42:00 -07001518 responseCode = get(filepath8.string(), keyBlob, type, userId);
Kenny Root655b9582013-04-04 08:37:42 -07001519 if (responseCode == NO_ERROR) {
1520 return responseCode;
1521 }
1522 }
1523
1524 // They might be using a granted key.
Kenny Root86b16e82013-09-09 11:15:54 -07001525 android::String8 filename8 = getKeyName(keyName);
Kenny Root655b9582013-04-04 08:37:42 -07001526 char* end;
Kenny Root86b16e82013-09-09 11:15:54 -07001527 strtoul(filename8.string(), &end, 10);
Kenny Root655b9582013-04-04 08:37:42 -07001528 if (end[0] != '_' || end[1] == 0) {
1529 return KEY_NOT_FOUND;
1530 }
Chad Brubaker72593ee2015-05-12 10:42:00 -07001531 filepath8 = android::String8::format("%s/%s", getUserState(userId)->getUserDirName(),
Kenny Root86b16e82013-09-09 11:15:54 -07001532 filename8.string());
Kenny Root655b9582013-04-04 08:37:42 -07001533 if (!hasGrant(filepath8.string(), uid)) {
1534 return responseCode;
1535 }
1536
1537 // It is a granted key. Try to load it.
Chad Brubaker72593ee2015-05-12 10:42:00 -07001538 return get(filepath8.string(), keyBlob, type, userId);
Kenny Root655b9582013-04-04 08:37:42 -07001539 }
1540
1541 /**
1542 * Returns any existing UserState or creates it if it doesn't exist.
1543 */
Chad Brubaker72593ee2015-05-12 10:42:00 -07001544 UserState* getUserState(uid_t userId) {
Kenny Root655b9582013-04-04 08:37:42 -07001545 for (android::Vector<UserState*>::iterator it(mMasterKeys.begin());
1546 it != mMasterKeys.end(); it++) {
1547 UserState* state = *it;
1548 if (state->getUserId() == userId) {
1549 return state;
1550 }
1551 }
1552
1553 UserState* userState = new UserState(userId);
1554 if (!userState->initialize()) {
1555 /* There's not much we can do if initialization fails. Trying to
1556 * unlock the keystore for that user will fail as well, so any
1557 * subsequent request for this user will just return SYSTEM_ERROR.
1558 */
1559 ALOGE("User initialization failed for %u; subsuquent operations will fail", userId);
1560 }
1561 mMasterKeys.add(userState);
1562 return userState;
1563 }
1564
1565 /**
Chad Brubaker72593ee2015-05-12 10:42:00 -07001566 * Returns any existing UserState or creates it if it doesn't exist.
1567 */
1568 UserState* getUserStateByUid(uid_t uid) {
1569 uid_t userId = get_user_id(uid);
1570 return getUserState(userId);
1571 }
1572
1573 /**
Kenny Root655b9582013-04-04 08:37:42 -07001574 * Returns NULL if the UserState doesn't already exist.
1575 */
Chad Brubaker72593ee2015-05-12 10:42:00 -07001576 const UserState* getUserState(uid_t userId) const {
Kenny Root655b9582013-04-04 08:37:42 -07001577 for (android::Vector<UserState*>::const_iterator it(mMasterKeys.begin());
1578 it != mMasterKeys.end(); it++) {
1579 UserState* state = *it;
1580 if (state->getUserId() == userId) {
1581 return state;
1582 }
1583 }
1584
1585 return NULL;
1586 }
1587
Chad Brubaker72593ee2015-05-12 10:42:00 -07001588 /**
1589 * Returns NULL if the UserState doesn't already exist.
1590 */
1591 const UserState* getUserStateByUid(uid_t uid) const {
1592 uid_t userId = get_user_id(uid);
1593 return getUserState(userId);
1594 }
1595
Kenny Roota91203b2012-02-15 15:00:46 -08001596private:
Kenny Root655b9582013-04-04 08:37:42 -07001597 static const char* sOldMasterKey;
1598 static const char* sMetaDataFile;
Kenny Root1b0e3932013-09-05 13:06:32 -07001599 static const android::String16 sRSAKeyType;
Kenny Roota91203b2012-02-15 15:00:46 -08001600 Entropy* mEntropy;
1601
Chad Brubaker67d2a502015-03-11 17:21:18 +00001602 keymaster1_device_t* mDevice;
1603 keymaster1_device_t* mFallbackDevice;
Kenny Root70e3a862012-02-15 17:20:23 -08001604
Kenny Root655b9582013-04-04 08:37:42 -07001605 android::Vector<UserState*> mMasterKeys;
Kenny Roota91203b2012-02-15 15:00:46 -08001606
Kenny Root655b9582013-04-04 08:37:42 -07001607 android::Vector<grant_t*> mGrants;
Kenny Roota91203b2012-02-15 15:00:46 -08001608
Kenny Root655b9582013-04-04 08:37:42 -07001609 typedef struct {
1610 uint32_t version;
1611 } keystore_metadata_t;
Kenny Roota91203b2012-02-15 15:00:46 -08001612
Kenny Root655b9582013-04-04 08:37:42 -07001613 keystore_metadata_t mMetaData;
Kenny Root70e3a862012-02-15 17:20:23 -08001614
Kenny Root655b9582013-04-04 08:37:42 -07001615 const grant_t* getGrant(const char* filename, uid_t uid) const {
1616 for (android::Vector<grant_t*>::const_iterator it(mGrants.begin());
1617 it != mGrants.end(); it++) {
1618 grant_t* grant = *it;
Kenny Root70e3a862012-02-15 17:20:23 -08001619 if (grant->uid == uid
Kenny Root655b9582013-04-04 08:37:42 -07001620 && !strcmp(reinterpret_cast<const char*>(grant->filename), filename)) {
Kenny Root70e3a862012-02-15 17:20:23 -08001621 return grant;
1622 }
1623 }
Kenny Root70e3a862012-02-15 17:20:23 -08001624 return NULL;
1625 }
1626
Kenny Root822c3a92012-03-23 16:34:39 -07001627 /**
1628 * Upgrade code. This will upgrade the key from the current version
1629 * to whatever is newest.
1630 */
Kenny Root655b9582013-04-04 08:37:42 -07001631 bool upgradeBlob(const char* filename, Blob* blob, const uint8_t oldVersion,
1632 const BlobType type, uid_t uid) {
Kenny Root822c3a92012-03-23 16:34:39 -07001633 bool updated = false;
1634 uint8_t version = oldVersion;
1635
1636 /* From V0 -> V1: All old types were unknown */
1637 if (version == 0) {
1638 ALOGV("upgrading to version 1 and setting type %d", type);
1639
1640 blob->setType(type);
1641 if (type == TYPE_KEY_PAIR) {
Kenny Root655b9582013-04-04 08:37:42 -07001642 importBlobAsKey(blob, filename, uid);
Kenny Root822c3a92012-03-23 16:34:39 -07001643 }
1644 version = 1;
1645 updated = true;
1646 }
1647
Kenny Rootf9119d62013-04-03 09:22:15 -07001648 /* From V1 -> V2: All old keys were encrypted */
1649 if (version == 1) {
1650 ALOGV("upgrading to version 2");
1651
1652 blob->setEncrypted(true);
1653 version = 2;
1654 updated = true;
1655 }
1656
Kenny Root822c3a92012-03-23 16:34:39 -07001657 /*
1658 * If we've updated, set the key blob to the right version
1659 * and write it.
Kenny Rootcfeae072013-04-04 08:39:57 -07001660 */
Kenny Root822c3a92012-03-23 16:34:39 -07001661 if (updated) {
1662 ALOGV("updated and writing file %s", filename);
1663 blob->setVersion(version);
Kenny Root822c3a92012-03-23 16:34:39 -07001664 }
Kenny Rootcfeae072013-04-04 08:39:57 -07001665
1666 return updated;
Kenny Root822c3a92012-03-23 16:34:39 -07001667 }
1668
1669 /**
1670 * Takes a blob that is an PEM-encoded RSA key as a byte array and
1671 * converts it to a DER-encoded PKCS#8 for import into a keymaster.
1672 * Then it overwrites the original blob with the new blob
1673 * format that is returned from the keymaster.
1674 */
Kenny Root655b9582013-04-04 08:37:42 -07001675 ResponseCode importBlobAsKey(Blob* blob, const char* filename, uid_t uid) {
Kenny Root822c3a92012-03-23 16:34:39 -07001676 // We won't even write to the blob directly with this BIO, so const_cast is okay.
1677 Unique_BIO b(BIO_new_mem_buf(const_cast<uint8_t*>(blob->getValue()), blob->getLength()));
1678 if (b.get() == NULL) {
1679 ALOGE("Problem instantiating BIO");
1680 return SYSTEM_ERROR;
1681 }
1682
1683 Unique_EVP_PKEY pkey(PEM_read_bio_PrivateKey(b.get(), NULL, NULL, NULL));
1684 if (pkey.get() == NULL) {
1685 ALOGE("Couldn't read old PEM file");
1686 return SYSTEM_ERROR;
1687 }
1688
1689 Unique_PKCS8_PRIV_KEY_INFO pkcs8(EVP_PKEY2PKCS8(pkey.get()));
1690 int len = i2d_PKCS8_PRIV_KEY_INFO(pkcs8.get(), NULL);
1691 if (len < 0) {
1692 ALOGE("Couldn't measure PKCS#8 length");
1693 return SYSTEM_ERROR;
1694 }
1695
Kenny Root70c98892013-02-07 09:10:36 -08001696 UniquePtr<unsigned char[]> pkcs8key(new unsigned char[len]);
1697 uint8_t* tmp = pkcs8key.get();
Kenny Root822c3a92012-03-23 16:34:39 -07001698 if (i2d_PKCS8_PRIV_KEY_INFO(pkcs8.get(), &tmp) != len) {
1699 ALOGE("Couldn't convert to PKCS#8");
1700 return SYSTEM_ERROR;
1701 }
1702
Chad Brubaker72593ee2015-05-12 10:42:00 -07001703 ResponseCode rc = importKey(pkcs8key.get(), len, filename, get_user_id(uid),
Kenny Rootf9119d62013-04-03 09:22:15 -07001704 blob->isEncrypted() ? KEYSTORE_FLAG_ENCRYPTED : KEYSTORE_FLAG_NONE);
Kenny Root822c3a92012-03-23 16:34:39 -07001705 if (rc != NO_ERROR) {
1706 return rc;
1707 }
1708
Kenny Root655b9582013-04-04 08:37:42 -07001709 return get(filename, blob, TYPE_KEY_PAIR, uid);
1710 }
1711
1712 void readMetaData() {
1713 int in = TEMP_FAILURE_RETRY(open(sMetaDataFile, O_RDONLY));
1714 if (in < 0) {
1715 return;
1716 }
1717 size_t fileLength = readFully(in, (uint8_t*) &mMetaData, sizeof(mMetaData));
1718 if (fileLength != sizeof(mMetaData)) {
1719 ALOGI("Metadata file is %zd bytes (%zd experted); upgrade?", fileLength,
1720 sizeof(mMetaData));
1721 }
1722 close(in);
1723 }
1724
1725 void writeMetaData() {
1726 const char* tmpFileName = ".metadata.tmp";
1727 int out = TEMP_FAILURE_RETRY(open(tmpFileName,
1728 O_WRONLY | O_TRUNC | O_CREAT, S_IRUSR | S_IWUSR));
1729 if (out < 0) {
1730 ALOGE("couldn't write metadata file: %s", strerror(errno));
1731 return;
1732 }
1733 size_t fileLength = writeFully(out, (uint8_t*) &mMetaData, sizeof(mMetaData));
1734 if (fileLength != sizeof(mMetaData)) {
1735 ALOGI("Could only write %zd bytes to metadata file (%zd expected)", fileLength,
1736 sizeof(mMetaData));
1737 }
1738 close(out);
1739 rename(tmpFileName, sMetaDataFile);
1740 }
1741
1742 bool upgradeKeystore() {
1743 bool upgraded = false;
1744
1745 if (mMetaData.version == 0) {
Chad Brubaker72593ee2015-05-12 10:42:00 -07001746 UserState* userState = getUserStateByUid(0);
Kenny Root655b9582013-04-04 08:37:42 -07001747
1748 // Initialize first so the directory is made.
1749 userState->initialize();
1750
1751 // Migrate the old .masterkey file to user 0.
1752 if (access(sOldMasterKey, R_OK) == 0) {
1753 if (rename(sOldMasterKey, userState->getMasterKeyFileName()) < 0) {
1754 ALOGE("couldn't migrate old masterkey: %s", strerror(errno));
1755 return false;
1756 }
1757 }
1758
1759 // Initialize again in case we had a key.
1760 userState->initialize();
1761
1762 // Try to migrate existing keys.
1763 DIR* dir = opendir(".");
1764 if (!dir) {
1765 // Give up now; maybe we can upgrade later.
1766 ALOGE("couldn't open keystore's directory; something is wrong");
1767 return false;
1768 }
1769
1770 struct dirent* file;
1771 while ((file = readdir(dir)) != NULL) {
1772 // We only care about files.
1773 if (file->d_type != DT_REG) {
1774 continue;
1775 }
1776
1777 // Skip anything that starts with a "."
1778 if (file->d_name[0] == '.') {
1779 continue;
1780 }
1781
1782 // Find the current file's user.
1783 char* end;
1784 unsigned long thisUid = strtoul(file->d_name, &end, 10);
1785 if (end[0] != '_' || end[1] == 0) {
1786 continue;
1787 }
Chad Brubaker72593ee2015-05-12 10:42:00 -07001788 UserState* otherUser = getUserStateByUid(thisUid);
Kenny Root655b9582013-04-04 08:37:42 -07001789 if (otherUser->getUserId() != 0) {
1790 unlinkat(dirfd(dir), file->d_name, 0);
1791 }
1792
1793 // Rename the file into user directory.
1794 DIR* otherdir = opendir(otherUser->getUserDirName());
1795 if (otherdir == NULL) {
1796 ALOGW("couldn't open user directory for rename");
1797 continue;
1798 }
1799 if (renameat(dirfd(dir), file->d_name, dirfd(otherdir), file->d_name) < 0) {
1800 ALOGW("couldn't rename blob: %s: %s", file->d_name, strerror(errno));
1801 }
1802 closedir(otherdir);
1803 }
1804 closedir(dir);
1805
1806 mMetaData.version = 1;
1807 upgraded = true;
1808 }
1809
1810 return upgraded;
Kenny Root822c3a92012-03-23 16:34:39 -07001811 }
Kenny Roota91203b2012-02-15 15:00:46 -08001812};
1813
Kenny Root655b9582013-04-04 08:37:42 -07001814const char* KeyStore::sOldMasterKey = ".masterkey";
1815const char* KeyStore::sMetaDataFile = ".metadata";
Kenny Root70e3a862012-02-15 17:20:23 -08001816
Kenny Root1b0e3932013-09-05 13:06:32 -07001817const android::String16 KeyStore::sRSAKeyType("RSA");
1818
Kenny Root07438c82012-11-02 15:41:02 -07001819namespace android {
1820class KeyStoreProxy : public BnKeystoreService, public IBinder::DeathRecipient {
1821public:
1822 KeyStoreProxy(KeyStore* keyStore)
Chad Brubaker40a1a9b2015-02-20 14:08:13 -08001823 : mKeyStore(keyStore),
1824 mOperationMap(this)
Kenny Root07438c82012-11-02 15:41:02 -07001825 {
Kenny Roota91203b2012-02-15 15:00:46 -08001826 }
Kenny Roota91203b2012-02-15 15:00:46 -08001827
Chad Brubaker40a1a9b2015-02-20 14:08:13 -08001828 void binderDied(const wp<IBinder>& who) {
1829 auto operations = mOperationMap.getOperationsForToken(who.unsafe_get());
1830 for (auto token: operations) {
1831 abort(token);
1832 }
Kenny Root822c3a92012-03-23 16:34:39 -07001833 }
Kenny Roota91203b2012-02-15 15:00:46 -08001834
Chad Brubakere6c3bfa2015-05-12 15:18:26 -07001835 int32_t getState(int32_t userId) {
1836 if (!checkBinderPermission(P_GET_STATE)) {
Kenny Root07438c82012-11-02 15:41:02 -07001837 return ::PERMISSION_DENIED;
Kenny Roota91203b2012-02-15 15:00:46 -08001838 }
Kenny Roota91203b2012-02-15 15:00:46 -08001839
Chad Brubakere6c3bfa2015-05-12 15:18:26 -07001840 return mKeyStore->getState(userId);
Kenny Root298e7b12012-03-26 13:54:44 -07001841 }
1842
Kenny Root07438c82012-11-02 15:41:02 -07001843 int32_t get(const String16& name, uint8_t** item, size_t* itemLength) {
Chad Brubaker9489b792015-04-14 11:01:45 -07001844 if (!checkBinderPermission(P_GET)) {
Kenny Root07438c82012-11-02 15:41:02 -07001845 return ::PERMISSION_DENIED;
Kenny Roota91203b2012-02-15 15:00:46 -08001846 }
Kenny Root07438c82012-11-02 15:41:02 -07001847
Chad Brubaker9489b792015-04-14 11:01:45 -07001848 uid_t callingUid = IPCThreadState::self()->getCallingUid();
Kenny Root07438c82012-11-02 15:41:02 -07001849 String8 name8(name);
Kenny Root07438c82012-11-02 15:41:02 -07001850 Blob keyBlob;
Nick Kralevich66dbf672014-06-30 17:09:14 +00001851
Kenny Root655b9582013-04-04 08:37:42 -07001852 ResponseCode responseCode = mKeyStore->getKeyForName(&keyBlob, name8, callingUid,
Kenny Root49468902013-03-19 13:41:33 -07001853 TYPE_GENERIC);
Kenny Root07438c82012-11-02 15:41:02 -07001854 if (responseCode != ::NO_ERROR) {
1855 *item = NULL;
1856 *itemLength = 0;
1857 return responseCode;
Kenny Roota91203b2012-02-15 15:00:46 -08001858 }
Kenny Roota91203b2012-02-15 15:00:46 -08001859
Kenny Root07438c82012-11-02 15:41:02 -07001860 *item = (uint8_t*) malloc(keyBlob.getLength());
1861 memcpy(*item, keyBlob.getValue(), keyBlob.getLength());
1862 *itemLength = keyBlob.getLength();
Kenny Roota91203b2012-02-15 15:00:46 -08001863
Kenny Root07438c82012-11-02 15:41:02 -07001864 return ::NO_ERROR;
Kenny Root70e3a862012-02-15 17:20:23 -08001865 }
1866
Kenny Rootf9119d62013-04-03 09:22:15 -07001867 int32_t insert(const String16& name, const uint8_t* item, size_t itemLength, int targetUid,
1868 int32_t flags) {
Chad Brubaker9489b792015-04-14 11:01:45 -07001869 targetUid = getEffectiveUid(targetUid);
1870 int32_t result = checkBinderPermissionAndKeystoreState(P_INSERT, targetUid,
1871 flags & KEYSTORE_FLAG_ENCRYPTED);
1872 if (result != ::NO_ERROR) {
1873 return result;
Kenny Rootb88c3eb2013-02-13 14:43:43 -08001874 }
1875
Kenny Root07438c82012-11-02 15:41:02 -07001876 String8 name8(name);
Kenny Root655b9582013-04-04 08:37:42 -07001877 String8 filename(mKeyStore->getKeyNameForUidWithDir(name8, targetUid));
Kenny Root07438c82012-11-02 15:41:02 -07001878
1879 Blob keyBlob(item, itemLength, NULL, 0, ::TYPE_GENERIC);
Kenny Rootee8068b2013-10-07 09:49:15 -07001880 keyBlob.setEncrypted(flags & KEYSTORE_FLAG_ENCRYPTED);
1881
Chad Brubaker72593ee2015-05-12 10:42:00 -07001882 return mKeyStore->put(filename.string(), &keyBlob, get_user_id(targetUid));
Kenny Root70e3a862012-02-15 17:20:23 -08001883 }
1884
Kenny Root49468902013-03-19 13:41:33 -07001885 int32_t del(const String16& name, int targetUid) {
Chad Brubaker9489b792015-04-14 11:01:45 -07001886 targetUid = getEffectiveUid(targetUid);
1887 if (!checkBinderPermission(P_DELETE, targetUid)) {
Kenny Root07438c82012-11-02 15:41:02 -07001888 return ::PERMISSION_DENIED;
1889 }
Kenny Root07438c82012-11-02 15:41:02 -07001890 String8 name8(name);
Kenny Root655b9582013-04-04 08:37:42 -07001891 String8 filename(mKeyStore->getKeyNameForUidWithDir(name8, targetUid));
Chad Brubaker72593ee2015-05-12 10:42:00 -07001892 return mKeyStore->del(filename.string(), ::TYPE_ANY, get_user_id(targetUid));
Kenny Root70e3a862012-02-15 17:20:23 -08001893 }
1894
Kenny Root49468902013-03-19 13:41:33 -07001895 int32_t exist(const String16& name, int targetUid) {
Chad Brubaker9489b792015-04-14 11:01:45 -07001896 targetUid = getEffectiveUid(targetUid);
1897 if (!checkBinderPermission(P_EXIST, targetUid)) {
Kenny Rootb88c3eb2013-02-13 14:43:43 -08001898 return ::PERMISSION_DENIED;
1899 }
1900
Kenny Root07438c82012-11-02 15:41:02 -07001901 String8 name8(name);
Kenny Root655b9582013-04-04 08:37:42 -07001902 String8 filename(mKeyStore->getKeyNameForUidWithDir(name8, targetUid));
Kenny Root70e3a862012-02-15 17:20:23 -08001903
Kenny Root655b9582013-04-04 08:37:42 -07001904 if (access(filename.string(), R_OK) == -1) {
Kenny Root07438c82012-11-02 15:41:02 -07001905 return (errno != ENOENT) ? ::SYSTEM_ERROR : ::KEY_NOT_FOUND;
1906 }
1907 return ::NO_ERROR;
Kenny Root70e3a862012-02-15 17:20:23 -08001908 }
1909
Chad Brubakere6c3bfa2015-05-12 15:18:26 -07001910 int32_t list(const String16& prefix, int targetUid, Vector<String16>* matches) {
Chad Brubaker9489b792015-04-14 11:01:45 -07001911 targetUid = getEffectiveUid(targetUid);
Chad Brubakere6c3bfa2015-05-12 15:18:26 -07001912 if (!checkBinderPermission(P_LIST, targetUid)) {
Kenny Root07438c82012-11-02 15:41:02 -07001913 return ::PERMISSION_DENIED;
1914 }
Kenny Root07438c82012-11-02 15:41:02 -07001915 const String8 prefix8(prefix);
Kenny Root655b9582013-04-04 08:37:42 -07001916 String8 filename(mKeyStore->getKeyNameForUid(prefix8, targetUid));
Kenny Root70e3a862012-02-15 17:20:23 -08001917
Chad Brubakere6c3bfa2015-05-12 15:18:26 -07001918 if (mKeyStore->list(filename, matches, get_user_id(targetUid)) != ::NO_ERROR) {
Robin Lee4b84fdc2014-09-24 11:56:57 +01001919 return ::SYSTEM_ERROR;
Kenny Root9a53d3e2012-08-14 10:47:54 -07001920 }
Kenny Root07438c82012-11-02 15:41:02 -07001921 return ::NO_ERROR;
Kenny Root70e3a862012-02-15 17:20:23 -08001922 }
1923
Kenny Root07438c82012-11-02 15:41:02 -07001924 int32_t reset() {
Chad Brubaker9489b792015-04-14 11:01:45 -07001925 if (!checkBinderPermission(P_RESET)) {
Kenny Root07438c82012-11-02 15:41:02 -07001926 return ::PERMISSION_DENIED;
1927 }
1928
Chad Brubaker9489b792015-04-14 11:01:45 -07001929 uid_t callingUid = IPCThreadState::self()->getCallingUid();
Chad Brubaker96d6d782015-05-07 10:19:40 -07001930 mKeyStore->resetUser(get_user_id(callingUid), false);
1931 return ::NO_ERROR;
Kenny Root70e3a862012-02-15 17:20:23 -08001932 }
1933
Chad Brubaker96d6d782015-05-07 10:19:40 -07001934 int32_t onUserPasswordChanged(int32_t userId, const String16& password) {
Chad Brubaker9489b792015-04-14 11:01:45 -07001935 if (!checkBinderPermission(P_PASSWORD)) {
Kenny Root07438c82012-11-02 15:41:02 -07001936 return ::PERMISSION_DENIED;
1937 }
Kenny Root70e3a862012-02-15 17:20:23 -08001938
Kenny Root07438c82012-11-02 15:41:02 -07001939 const String8 password8(password);
Chad Brubaker96d6d782015-05-07 10:19:40 -07001940 // Flush the auth token table to prevent stale tokens from sticking
1941 // around.
1942 mAuthTokenTable.Clear();
1943
1944 if (password.size() == 0) {
1945 ALOGI("Secure lockscreen for user %d removed, deleting encrypted entries", userId);
Chad Brubaker72593ee2015-05-12 10:42:00 -07001946 mKeyStore->resetUser(userId, true);
Chad Brubaker96d6d782015-05-07 10:19:40 -07001947 return ::NO_ERROR;
1948 } else {
Chad Brubaker72593ee2015-05-12 10:42:00 -07001949 switch (mKeyStore->getState(userId)) {
Chad Brubaker96d6d782015-05-07 10:19:40 -07001950 case ::STATE_UNINITIALIZED: {
1951 // generate master key, encrypt with password, write to file,
1952 // initialize mMasterKey*.
Chad Brubaker72593ee2015-05-12 10:42:00 -07001953 return mKeyStore->initializeUser(password8, userId);
Chad Brubaker96d6d782015-05-07 10:19:40 -07001954 }
1955 case ::STATE_NO_ERROR: {
1956 // rewrite master key with new password.
Chad Brubaker72593ee2015-05-12 10:42:00 -07001957 return mKeyStore->writeMasterKey(password8, userId);
Chad Brubaker96d6d782015-05-07 10:19:40 -07001958 }
1959 case ::STATE_LOCKED: {
1960 ALOGE("Changing user %d's password while locked, clearing old encryption",
1961 userId);
Chad Brubaker72593ee2015-05-12 10:42:00 -07001962 mKeyStore->resetUser(userId, true);
1963 return mKeyStore->initializeUser(password8, userId);
Chad Brubaker96d6d782015-05-07 10:19:40 -07001964 }
Kenny Root07438c82012-11-02 15:41:02 -07001965 }
Chad Brubaker96d6d782015-05-07 10:19:40 -07001966 return ::SYSTEM_ERROR;
Kenny Root07438c82012-11-02 15:41:02 -07001967 }
Kenny Root70e3a862012-02-15 17:20:23 -08001968 }
1969
Chad Brubakerc0f031a2015-05-12 10:43:10 -07001970 int32_t onUserAdded(int32_t userId, int32_t parentId) {
1971 if (!checkBinderPermission(P_USER_CHANGED)) {
1972 return ::PERMISSION_DENIED;
1973 }
1974
1975 // Sanity check that the new user has an empty keystore.
1976 if (!mKeyStore->isEmpty(userId)) {
1977 ALOGW("New user %d's keystore not empty. Clearing old entries.", userId);
1978 }
1979 // Unconditionally clear the keystore, just to be safe.
1980 mKeyStore->resetUser(userId, false);
1981
1982 // If the user has a parent user then use the parent's
1983 // masterkey/password, otherwise there's nothing to do.
1984 if (parentId != -1) {
1985 return mKeyStore->copyMasterKey(parentId, userId);
1986 } else {
1987 return ::NO_ERROR;
1988 }
1989 }
1990
1991 int32_t onUserRemoved(int32_t userId) {
1992 if (!checkBinderPermission(P_USER_CHANGED)) {
1993 return ::PERMISSION_DENIED;
1994 }
1995
1996 mKeyStore->resetUser(userId, false);
1997 return ::NO_ERROR;
1998 }
1999
Chad Brubakere6c3bfa2015-05-12 15:18:26 -07002000 int32_t lock(int32_t userId) {
Chad Brubaker9489b792015-04-14 11:01:45 -07002001 if (!checkBinderPermission(P_LOCK)) {
Kenny Root07438c82012-11-02 15:41:02 -07002002 return ::PERMISSION_DENIED;
2003 }
Kenny Root70e3a862012-02-15 17:20:23 -08002004
Chad Brubaker72593ee2015-05-12 10:42:00 -07002005 State state = mKeyStore->getState(userId);
Kenny Root9d45d1c2013-02-14 10:32:30 -08002006 if (state != ::STATE_NO_ERROR) {
Kenny Root07438c82012-11-02 15:41:02 -07002007 ALOGD("calling lock in state: %d", state);
2008 return state;
2009 }
2010
Chad Brubaker72593ee2015-05-12 10:42:00 -07002011 mKeyStore->lock(userId);
Kenny Root07438c82012-11-02 15:41:02 -07002012 return ::NO_ERROR;
Kenny Root70e3a862012-02-15 17:20:23 -08002013 }
2014
Chad Brubaker96d6d782015-05-07 10:19:40 -07002015 int32_t unlock(int32_t userId, const String16& pw) {
Chad Brubaker9489b792015-04-14 11:01:45 -07002016 if (!checkBinderPermission(P_UNLOCK)) {
Kenny Root07438c82012-11-02 15:41:02 -07002017 return ::PERMISSION_DENIED;
2018 }
2019
Chad Brubaker72593ee2015-05-12 10:42:00 -07002020 State state = mKeyStore->getState(userId);
Kenny Root9d45d1c2013-02-14 10:32:30 -08002021 if (state != ::STATE_LOCKED) {
Chad Brubaker96d6d782015-05-07 10:19:40 -07002022 ALOGI("calling unlock when not locked, ignoring.");
Kenny Root07438c82012-11-02 15:41:02 -07002023 return state;
2024 }
2025
2026 const String8 password8(pw);
Chad Brubaker96d6d782015-05-07 10:19:40 -07002027 // read master key, decrypt with password, initialize mMasterKey*.
Chad Brubaker72593ee2015-05-12 10:42:00 -07002028 return mKeyStore->readMasterKey(password8, userId);
Kenny Root70e3a862012-02-15 17:20:23 -08002029 }
2030
Chad Brubakere6c3bfa2015-05-12 15:18:26 -07002031 bool isEmpty(int32_t userId) {
2032 if (!checkBinderPermission(P_IS_EMPTY)) {
2033 return false;
Kenny Root07438c82012-11-02 15:41:02 -07002034 }
Kenny Root70e3a862012-02-15 17:20:23 -08002035
Chad Brubakere6c3bfa2015-05-12 15:18:26 -07002036 return mKeyStore->isEmpty(userId);
Kenny Root70e3a862012-02-15 17:20:23 -08002037 }
2038
Kenny Root96427ba2013-08-16 14:02:41 -07002039 int32_t generate(const String16& name, int32_t targetUid, int32_t keyType, int32_t keySize,
2040 int32_t flags, Vector<sp<KeystoreArg> >* args) {
Chad Brubaker9489b792015-04-14 11:01:45 -07002041 targetUid = getEffectiveUid(targetUid);
2042 int32_t result = checkBinderPermissionAndKeystoreState(P_INSERT, targetUid,
2043 flags & KEYSTORE_FLAG_ENCRYPTED);
2044 if (result != ::NO_ERROR) {
2045 return result;
Kenny Root07438c82012-11-02 15:41:02 -07002046 }
Kenny Root07438c82012-11-02 15:41:02 -07002047
Chad Brubaker3a7d9e62015-06-04 15:01:46 -07002048 KeymasterArguments params;
Shawn Willden55268b52015-07-28 11:06:00 -06002049 add_legacy_key_authorizations(keyType, &params.params);
Kenny Root07438c82012-11-02 15:41:02 -07002050
Chad Brubaker3a7d9e62015-06-04 15:01:46 -07002051 switch (keyType) {
2052 case EVP_PKEY_EC: {
2053 params.params.push_back(keymaster_param_enum(KM_TAG_ALGORITHM, KM_ALGORITHM_EC));
2054 if (keySize == -1) {
2055 keySize = EC_DEFAULT_KEY_SIZE;
2056 } else if (keySize < EC_MIN_KEY_SIZE || keySize > EC_MAX_KEY_SIZE) {
2057 ALOGI("invalid key size %d", keySize);
Kenny Root96427ba2013-08-16 14:02:41 -07002058 return ::SYSTEM_ERROR;
2059 }
Chad Brubaker3a7d9e62015-06-04 15:01:46 -07002060 params.params.push_back(keymaster_param_int(KM_TAG_KEY_SIZE, keySize));
2061 break;
Kenny Root96427ba2013-08-16 14:02:41 -07002062 }
Chad Brubaker3a7d9e62015-06-04 15:01:46 -07002063 case EVP_PKEY_RSA: {
2064 params.params.push_back(keymaster_param_enum(KM_TAG_ALGORITHM, KM_ALGORITHM_RSA));
2065 if (keySize == -1) {
2066 keySize = RSA_DEFAULT_KEY_SIZE;
2067 } else if (keySize < RSA_MIN_KEY_SIZE || keySize > RSA_MAX_KEY_SIZE) {
2068 ALOGI("invalid key size %d", keySize);
2069 return ::SYSTEM_ERROR;
Kenny Root96427ba2013-08-16 14:02:41 -07002070 }
Chad Brubaker3a7d9e62015-06-04 15:01:46 -07002071 params.params.push_back(keymaster_param_int(KM_TAG_KEY_SIZE, keySize));
2072 unsigned long exponent = RSA_DEFAULT_EXPONENT;
2073 if (args->size() > 1) {
2074 ALOGI("invalid number of arguments: %zu", args->size());
2075 return ::SYSTEM_ERROR;
2076 } else if (args->size() == 1) {
2077 sp<KeystoreArg> expArg = args->itemAt(0);
2078 if (expArg != NULL) {
2079 Unique_BIGNUM pubExpBn(
2080 BN_bin2bn(reinterpret_cast<const unsigned char*>(expArg->data()),
2081 expArg->size(), NULL));
2082 if (pubExpBn.get() == NULL) {
2083 ALOGI("Could not convert public exponent to BN");
2084 return ::SYSTEM_ERROR;
2085 }
2086 exponent = BN_get_word(pubExpBn.get());
2087 if (exponent == 0xFFFFFFFFL) {
2088 ALOGW("cannot represent public exponent as a long value");
2089 return ::SYSTEM_ERROR;
2090 }
2091 } else {
2092 ALOGW("public exponent not read");
2093 return ::SYSTEM_ERROR;
2094 }
2095 }
2096 params.params.push_back(keymaster_param_long(KM_TAG_RSA_PUBLIC_EXPONENT,
2097 exponent));
2098 break;
Kenny Root96427ba2013-08-16 14:02:41 -07002099 }
Chad Brubaker3a7d9e62015-06-04 15:01:46 -07002100 default: {
2101 ALOGW("Unsupported key type %d", keyType);
2102 return ::SYSTEM_ERROR;
2103 }
Kenny Root96427ba2013-08-16 14:02:41 -07002104 }
2105
Chad Brubaker3a7d9e62015-06-04 15:01:46 -07002106 int32_t rc = generateKey(name, params, NULL, 0, targetUid, flags,
2107 /*outCharacteristics*/ NULL);
2108 if (rc != ::NO_ERROR) {
2109 ALOGW("generate failed: %d", rc);
Kenny Root07438c82012-11-02 15:41:02 -07002110 }
Chad Brubaker3a7d9e62015-06-04 15:01:46 -07002111 return translateResultToLegacyResult(rc);
Kenny Root70e3a862012-02-15 17:20:23 -08002112 }
2113
Kenny Rootf9119d62013-04-03 09:22:15 -07002114 int32_t import(const String16& name, const uint8_t* data, size_t length, int targetUid,
2115 int32_t flags) {
Chad Brubaker3a7d9e62015-06-04 15:01:46 -07002116 const uint8_t* ptr = data;
Kenny Root07438c82012-11-02 15:41:02 -07002117
Chad Brubaker3a7d9e62015-06-04 15:01:46 -07002118 Unique_PKCS8_PRIV_KEY_INFO pkcs8(d2i_PKCS8_PRIV_KEY_INFO(NULL, &ptr, length));
2119 if (!pkcs8.get()) {
2120 return ::SYSTEM_ERROR;
2121 }
2122 Unique_EVP_PKEY pkey(EVP_PKCS82PKEY(pkcs8.get()));
2123 if (!pkey.get()) {
2124 return ::SYSTEM_ERROR;
2125 }
2126 int type = EVP_PKEY_type(pkey->type);
Shawn Willden2de8b752015-07-23 05:54:31 -06002127 KeymasterArguments params;
Shawn Willden55268b52015-07-28 11:06:00 -06002128 add_legacy_key_authorizations(type, &params.params);
Chad Brubaker3a7d9e62015-06-04 15:01:46 -07002129 switch (type) {
2130 case EVP_PKEY_RSA:
2131 params.params.push_back(keymaster_param_enum(KM_TAG_ALGORITHM, KM_ALGORITHM_RSA));
2132 break;
2133 case EVP_PKEY_EC:
2134 params.params.push_back(keymaster_param_enum(KM_TAG_ALGORITHM,
2135 KM_ALGORITHM_EC));
2136 break;
2137 default:
2138 ALOGW("Unsupported key type %d", type);
2139 return ::SYSTEM_ERROR;
2140 }
2141 int32_t rc = importKey(name, params, KM_KEY_FORMAT_PKCS8, data, length, targetUid, flags,
2142 /*outCharacteristics*/ NULL);
2143 if (rc != ::NO_ERROR) {
2144 ALOGW("importKey failed: %d", rc);
2145 }
2146 return translateResultToLegacyResult(rc);
Kenny Root70e3a862012-02-15 17:20:23 -08002147 }
2148
Kenny Root07438c82012-11-02 15:41:02 -07002149 int32_t sign(const String16& name, const uint8_t* data, size_t length, uint8_t** out,
Chad Brubaker3a7d9e62015-06-04 15:01:46 -07002150 size_t* outLength) {
Chad Brubaker9489b792015-04-14 11:01:45 -07002151 if (!checkBinderPermission(P_SIGN)) {
Kenny Root07438c82012-11-02 15:41:02 -07002152 return ::PERMISSION_DENIED;
2153 }
Chad Brubaker3a7d9e62015-06-04 15:01:46 -07002154 return doLegacySignVerify(name, data, length, out, outLength, NULL, 0, KM_PURPOSE_SIGN);
Kenny Root70e3a862012-02-15 17:20:23 -08002155 }
2156
Kenny Root07438c82012-11-02 15:41:02 -07002157 int32_t verify(const String16& name, const uint8_t* data, size_t dataLength,
2158 const uint8_t* signature, size_t signatureLength) {
Chad Brubaker9489b792015-04-14 11:01:45 -07002159 if (!checkBinderPermission(P_VERIFY)) {
Kenny Root07438c82012-11-02 15:41:02 -07002160 return ::PERMISSION_DENIED;
2161 }
Chad Brubaker3a7d9e62015-06-04 15:01:46 -07002162 return doLegacySignVerify(name, data, dataLength, NULL, NULL, signature, signatureLength,
2163 KM_PURPOSE_VERIFY);
Kenny Roota91203b2012-02-15 15:00:46 -08002164 }
Kenny Root07438c82012-11-02 15:41:02 -07002165
2166 /*
2167 * TODO: The abstraction between things stored in hardware and regular blobs
2168 * of data stored on the filesystem should be moved down to keystore itself.
2169 * Unfortunately the Java code that calls this has naming conventions that it
2170 * knows about. Ideally keystore shouldn't be used to store random blobs of
2171 * data.
2172 *
2173 * Until that happens, it's necessary to have a separate "get_pubkey" and
2174 * "del_key" since the Java code doesn't really communicate what it's
2175 * intentions are.
2176 */
2177 int32_t get_pubkey(const String16& name, uint8_t** pubkey, size_t* pubkeyLength) {
Chad Brubaker3a7d9e62015-06-04 15:01:46 -07002178 ExportResult result;
2179 exportKey(name, KM_KEY_FORMAT_X509, NULL, NULL, &result);
2180 if (result.resultCode != ::NO_ERROR) {
2181 ALOGW("export failed: %d", result.resultCode);
2182 return translateResultToLegacyResult(result.resultCode);
Kenny Root07438c82012-11-02 15:41:02 -07002183 }
Kenny Root07438c82012-11-02 15:41:02 -07002184
Chad Brubaker3a7d9e62015-06-04 15:01:46 -07002185 *pubkey = result.exportData.release();
2186 *pubkeyLength = result.dataLength;
Kenny Root07438c82012-11-02 15:41:02 -07002187 return ::NO_ERROR;
Kenny Roota91203b2012-02-15 15:00:46 -08002188 }
Kenny Root07438c82012-11-02 15:41:02 -07002189
Kenny Root07438c82012-11-02 15:41:02 -07002190 int32_t grant(const String16& name, int32_t granteeUid) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08002191 uid_t callingUid = IPCThreadState::self()->getCallingUid();
Chad Brubaker9489b792015-04-14 11:01:45 -07002192 int32_t result = checkBinderPermissionAndKeystoreState(P_GRANT);
2193 if (result != ::NO_ERROR) {
2194 return result;
Kenny Root07438c82012-11-02 15:41:02 -07002195 }
2196
2197 String8 name8(name);
Kenny Root655b9582013-04-04 08:37:42 -07002198 String8 filename(mKeyStore->getKeyNameForUidWithDir(name8, callingUid));
Kenny Root07438c82012-11-02 15:41:02 -07002199
Kenny Root655b9582013-04-04 08:37:42 -07002200 if (access(filename.string(), R_OK) == -1) {
Kenny Root07438c82012-11-02 15:41:02 -07002201 return (errno != ENOENT) ? ::SYSTEM_ERROR : ::KEY_NOT_FOUND;
2202 }
2203
Kenny Root655b9582013-04-04 08:37:42 -07002204 mKeyStore->addGrant(filename.string(), granteeUid);
Kenny Root07438c82012-11-02 15:41:02 -07002205 return ::NO_ERROR;
2206 }
2207
2208 int32_t ungrant(const String16& name, int32_t granteeUid) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08002209 uid_t callingUid = IPCThreadState::self()->getCallingUid();
Chad Brubaker9489b792015-04-14 11:01:45 -07002210 int32_t result = checkBinderPermissionAndKeystoreState(P_GRANT);
2211 if (result != ::NO_ERROR) {
2212 return result;
Kenny Root07438c82012-11-02 15:41:02 -07002213 }
2214
2215 String8 name8(name);
Kenny Root655b9582013-04-04 08:37:42 -07002216 String8 filename(mKeyStore->getKeyNameForUidWithDir(name8, callingUid));
Kenny Root07438c82012-11-02 15:41:02 -07002217
Kenny Root655b9582013-04-04 08:37:42 -07002218 if (access(filename.string(), R_OK) == -1) {
Kenny Root07438c82012-11-02 15:41:02 -07002219 return (errno != ENOENT) ? ::SYSTEM_ERROR : ::KEY_NOT_FOUND;
2220 }
2221
Kenny Root655b9582013-04-04 08:37:42 -07002222 return mKeyStore->removeGrant(filename.string(), granteeUid) ? ::NO_ERROR : ::KEY_NOT_FOUND;
Kenny Root07438c82012-11-02 15:41:02 -07002223 }
2224
2225 int64_t getmtime(const String16& name) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08002226 uid_t callingUid = IPCThreadState::self()->getCallingUid();
Chad Brubaker9489b792015-04-14 11:01:45 -07002227 if (!checkBinderPermission(P_GET)) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08002228 ALOGW("permission denied for %d: getmtime", callingUid);
Kenny Root36a9e232013-02-04 14:24:15 -08002229 return -1L;
Kenny Root07438c82012-11-02 15:41:02 -07002230 }
Kenny Root07438c82012-11-02 15:41:02 -07002231
2232 String8 name8(name);
Kenny Root655b9582013-04-04 08:37:42 -07002233 String8 filename(mKeyStore->getKeyNameForUidWithDir(name8, callingUid));
Kenny Root07438c82012-11-02 15:41:02 -07002234
Kenny Root655b9582013-04-04 08:37:42 -07002235 if (access(filename.string(), R_OK) == -1) {
2236 ALOGW("could not access %s for getmtime", filename.string());
Kenny Root36a9e232013-02-04 14:24:15 -08002237 return -1L;
Kenny Root07438c82012-11-02 15:41:02 -07002238 }
2239
Kenny Root655b9582013-04-04 08:37:42 -07002240 int fd = TEMP_FAILURE_RETRY(open(filename.string(), O_NOFOLLOW, O_RDONLY));
Kenny Root07438c82012-11-02 15:41:02 -07002241 if (fd < 0) {
Kenny Root655b9582013-04-04 08:37:42 -07002242 ALOGW("could not open %s for getmtime", filename.string());
Kenny Root36a9e232013-02-04 14:24:15 -08002243 return -1L;
Kenny Root07438c82012-11-02 15:41:02 -07002244 }
2245
2246 struct stat s;
2247 int ret = fstat(fd, &s);
2248 close(fd);
2249 if (ret == -1) {
Kenny Root655b9582013-04-04 08:37:42 -07002250 ALOGW("could not stat %s for getmtime", filename.string());
Kenny Root36a9e232013-02-04 14:24:15 -08002251 return -1L;
Kenny Root07438c82012-11-02 15:41:02 -07002252 }
2253
Kenny Root36a9e232013-02-04 14:24:15 -08002254 return static_cast<int64_t>(s.st_mtime);
Kenny Root07438c82012-11-02 15:41:02 -07002255 }
2256
Kenny Rootd53bc922013-03-21 14:10:15 -07002257 int32_t duplicate(const String16& srcKey, int32_t srcUid, const String16& destKey,
2258 int32_t destUid) {
Kenny Root02254072013-03-20 11:48:19 -07002259 uid_t callingUid = IPCThreadState::self()->getCallingUid();
Riley Spahneaabae92014-06-30 12:39:52 -07002260 pid_t spid = IPCThreadState::self()->getCallingPid();
2261 if (!has_permission(callingUid, P_DUPLICATE, spid)) {
Kenny Rootd53bc922013-03-21 14:10:15 -07002262 ALOGW("permission denied for %d: duplicate", callingUid);
Kenny Root02254072013-03-20 11:48:19 -07002263 return -1L;
2264 }
2265
Chad Brubaker72593ee2015-05-12 10:42:00 -07002266 State state = mKeyStore->getState(get_user_id(callingUid));
Kenny Root02254072013-03-20 11:48:19 -07002267 if (!isKeystoreUnlocked(state)) {
Kenny Rootd53bc922013-03-21 14:10:15 -07002268 ALOGD("calling duplicate in state: %d", state);
Kenny Root02254072013-03-20 11:48:19 -07002269 return state;
2270 }
2271
Kenny Rootd53bc922013-03-21 14:10:15 -07002272 if (srcUid == -1 || static_cast<uid_t>(srcUid) == callingUid) {
2273 srcUid = callingUid;
2274 } else if (!is_granted_to(callingUid, srcUid)) {
2275 ALOGD("migrate not granted from source: %d -> %d", callingUid, srcUid);
Kenny Root02254072013-03-20 11:48:19 -07002276 return ::PERMISSION_DENIED;
2277 }
2278
Kenny Rootd53bc922013-03-21 14:10:15 -07002279 if (destUid == -1) {
2280 destUid = callingUid;
2281 }
2282
2283 if (srcUid != destUid) {
2284 if (static_cast<uid_t>(srcUid) != callingUid) {
2285 ALOGD("can only duplicate from caller to other or to same uid: "
2286 "calling=%d, srcUid=%d, destUid=%d", callingUid, srcUid, destUid);
2287 return ::PERMISSION_DENIED;
2288 }
2289
2290 if (!is_granted_to(callingUid, destUid)) {
2291 ALOGD("duplicate not granted to dest: %d -> %d", callingUid, destUid);
2292 return ::PERMISSION_DENIED;
2293 }
2294 }
2295
2296 String8 source8(srcKey);
Kenny Root655b9582013-04-04 08:37:42 -07002297 String8 sourceFile(mKeyStore->getKeyNameForUidWithDir(source8, srcUid));
Kenny Root02254072013-03-20 11:48:19 -07002298
Kenny Rootd53bc922013-03-21 14:10:15 -07002299 String8 target8(destKey);
Kenny Rootfa27d5b2013-10-15 09:01:08 -07002300 String8 targetFile(mKeyStore->getKeyNameForUidWithDir(target8, destUid));
Kenny Root02254072013-03-20 11:48:19 -07002301
Kenny Root655b9582013-04-04 08:37:42 -07002302 if (access(targetFile.string(), W_OK) != -1 || errno != ENOENT) {
2303 ALOGD("destination already exists: %s", targetFile.string());
Kenny Root02254072013-03-20 11:48:19 -07002304 return ::SYSTEM_ERROR;
2305 }
2306
Kenny Rootd53bc922013-03-21 14:10:15 -07002307 Blob keyBlob;
Kenny Root655b9582013-04-04 08:37:42 -07002308 ResponseCode responseCode = mKeyStore->get(sourceFile.string(), &keyBlob, TYPE_ANY,
Chad Brubaker72593ee2015-05-12 10:42:00 -07002309 get_user_id(srcUid));
Kenny Rootd53bc922013-03-21 14:10:15 -07002310 if (responseCode != ::NO_ERROR) {
2311 return responseCode;
Kenny Root02254072013-03-20 11:48:19 -07002312 }
Kenny Rootd53bc922013-03-21 14:10:15 -07002313
Chad Brubaker72593ee2015-05-12 10:42:00 -07002314 return mKeyStore->put(targetFile.string(), &keyBlob, get_user_id(destUid));
Kenny Root02254072013-03-20 11:48:19 -07002315 }
2316
Kenny Root1b0e3932013-09-05 13:06:32 -07002317 int32_t is_hardware_backed(const String16& keyType) {
2318 return mKeyStore->isHardwareBacked(keyType) ? 1 : 0;
Kenny Root8ddf35a2013-03-29 11:15:50 -07002319 }
2320
Kenny Rootfa27d5b2013-10-15 09:01:08 -07002321 int32_t clear_uid(int64_t targetUid64) {
Chad Brubaker9489b792015-04-14 11:01:45 -07002322 uid_t targetUid = getEffectiveUid(targetUid64);
Chad Brubakerb37a5232015-05-01 10:21:27 -07002323 if (!checkBinderPermissionSelfOrSystem(P_CLEAR_UID, targetUid)) {
Kenny Roota9bb5492013-04-01 16:29:11 -07002324 return ::PERMISSION_DENIED;
2325 }
2326
Robin Lee4b84fdc2014-09-24 11:56:57 +01002327 String8 prefix = String8::format("%u_", targetUid);
2328 Vector<String16> aliases;
Chad Brubakere6c3bfa2015-05-12 15:18:26 -07002329 if (mKeyStore->list(prefix, &aliases, get_user_id(targetUid)) != ::NO_ERROR) {
Kenny Roota9bb5492013-04-01 16:29:11 -07002330 return ::SYSTEM_ERROR;
2331 }
2332
Robin Lee4b84fdc2014-09-24 11:56:57 +01002333 for (uint32_t i = 0; i < aliases.size(); i++) {
2334 String8 name8(aliases[i]);
2335 String8 filename(mKeyStore->getKeyNameForUidWithDir(name8, targetUid));
Chad Brubaker72593ee2015-05-12 10:42:00 -07002336 mKeyStore->del(filename.string(), ::TYPE_ANY, get_user_id(targetUid));
Kenny Roota9bb5492013-04-01 16:29:11 -07002337 }
Robin Lee4b84fdc2014-09-24 11:56:57 +01002338 return ::NO_ERROR;
Kenny Roota9bb5492013-04-01 16:29:11 -07002339 }
2340
Chad Brubaker9c8612c2015-02-09 11:32:54 -08002341 int32_t addRngEntropy(const uint8_t* data, size_t dataLength) {
2342 const keymaster1_device_t* device = mKeyStore->getDevice();
2343 const keymaster1_device_t* fallback = mKeyStore->getFallbackDevice();
2344 int32_t devResult = KM_ERROR_UNIMPLEMENTED;
2345 int32_t fallbackResult = KM_ERROR_UNIMPLEMENTED;
2346 if (device->common.module->module_api_version >= KEYMASTER_MODULE_API_VERSION_1_0 &&
2347 device->add_rng_entropy != NULL) {
2348 devResult = device->add_rng_entropy(device, data, dataLength);
2349 }
2350 if (fallback->add_rng_entropy) {
2351 fallbackResult = fallback->add_rng_entropy(fallback, data, dataLength);
2352 }
2353 if (devResult) {
2354 return devResult;
2355 }
2356 if (fallbackResult) {
2357 return fallbackResult;
2358 }
2359 return ::NO_ERROR;
Chad Brubaker9899d6b2015-02-03 13:03:00 -08002360 }
2361
Chad Brubaker17d68b92015-02-05 22:04:16 -08002362 int32_t generateKey(const String16& name, const KeymasterArguments& params,
Chad Brubaker154d7692015-03-27 13:59:31 -07002363 const uint8_t* entropy, size_t entropyLength, int uid, int flags,
2364 KeyCharacteristics* outCharacteristics) {
Chad Brubaker9489b792015-04-14 11:01:45 -07002365 uid = getEffectiveUid(uid);
2366 int rc = checkBinderPermissionAndKeystoreState(P_INSERT, uid,
2367 flags & KEYSTORE_FLAG_ENCRYPTED);
2368 if (rc != ::NO_ERROR) {
2369 return rc;
Chad Brubaker17d68b92015-02-05 22:04:16 -08002370 }
2371
Chad Brubaker9489b792015-04-14 11:01:45 -07002372 rc = KM_ERROR_UNIMPLEMENTED;
Chad Brubaker17d68b92015-02-05 22:04:16 -08002373 bool isFallback = false;
2374 keymaster_key_blob_t blob;
2375 keymaster_key_characteristics_t *out = NULL;
2376
2377 const keymaster1_device_t* device = mKeyStore->getDevice();
2378 const keymaster1_device_t* fallback = mKeyStore->getFallbackDevice();
Chad Brubaker57e106d2015-06-01 12:59:00 -07002379 std::vector<keymaster_key_param_t> opParams(params.params);
2380 const keymaster_key_param_set_t inParams = {opParams.data(), opParams.size()};
Chad Brubaker17d68b92015-02-05 22:04:16 -08002381 if (device == NULL) {
2382 return ::SYSTEM_ERROR;
2383 }
Chad Brubaker154d7692015-03-27 13:59:31 -07002384 // TODO: Seed from Linux RNG before this.
Chad Brubaker17d68b92015-02-05 22:04:16 -08002385 if (device->common.module->module_api_version >= KEYMASTER_MODULE_API_VERSION_1_0 &&
2386 device->generate_key != NULL) {
Chad Brubaker154d7692015-03-27 13:59:31 -07002387 if (!entropy) {
2388 rc = KM_ERROR_OK;
2389 } else if (device->add_rng_entropy) {
2390 rc = device->add_rng_entropy(device, entropy, entropyLength);
2391 } else {
2392 rc = KM_ERROR_UNIMPLEMENTED;
2393 }
2394 if (rc == KM_ERROR_OK) {
Chad Brubaker57e106d2015-06-01 12:59:00 -07002395 rc = device->generate_key(device, &inParams, &blob, &out);
Chad Brubaker154d7692015-03-27 13:59:31 -07002396 }
Chad Brubaker17d68b92015-02-05 22:04:16 -08002397 }
2398 // If the HW device didn't support generate_key or generate_key failed
2399 // fall back to the software implementation.
2400 if (rc && fallback->generate_key != NULL) {
Shawn Willden55268b52015-07-28 11:06:00 -06002401 ALOGW("Primary keymaster device failed to generate key, falling back to SW.");
Chad Brubaker17d68b92015-02-05 22:04:16 -08002402 isFallback = true;
Chad Brubaker154d7692015-03-27 13:59:31 -07002403 if (!entropy) {
2404 rc = KM_ERROR_OK;
2405 } else if (fallback->add_rng_entropy) {
2406 rc = fallback->add_rng_entropy(fallback, entropy, entropyLength);
2407 } else {
2408 rc = KM_ERROR_UNIMPLEMENTED;
2409 }
2410 if (rc == KM_ERROR_OK) {
Chad Brubaker57e106d2015-06-01 12:59:00 -07002411 rc = fallback->generate_key(fallback, &inParams, &blob, &out);
Chad Brubaker154d7692015-03-27 13:59:31 -07002412 }
Chad Brubaker17d68b92015-02-05 22:04:16 -08002413 }
2414
2415 if (out) {
2416 if (outCharacteristics) {
2417 outCharacteristics->characteristics = *out;
2418 } else {
2419 keymaster_free_characteristics(out);
2420 }
2421 free(out);
2422 }
2423
2424 if (rc) {
2425 return rc;
2426 }
2427
2428 String8 name8(name);
2429 String8 filename(mKeyStore->getKeyNameForUidWithDir(name8, uid));
2430
2431 Blob keyBlob(blob.key_material, blob.key_material_size, NULL, 0, ::TYPE_KEYMASTER_10);
2432 keyBlob.setFallback(isFallback);
2433 keyBlob.setEncrypted(flags & KEYSTORE_FLAG_ENCRYPTED);
2434
2435 free(const_cast<uint8_t*>(blob.key_material));
2436
Chad Brubaker72593ee2015-05-12 10:42:00 -07002437 return mKeyStore->put(filename.string(), &keyBlob, get_user_id(uid));
Chad Brubaker9899d6b2015-02-03 13:03:00 -08002438 }
2439
Chad Brubakerf3f071f2015-02-10 19:38:51 -08002440 int32_t getKeyCharacteristics(const String16& name,
Chad Brubakerd6634422015-03-21 22:36:07 -07002441 const keymaster_blob_t* clientId,
2442 const keymaster_blob_t* appData,
Chad Brubakerf3f071f2015-02-10 19:38:51 -08002443 KeyCharacteristics* outCharacteristics) {
Chad Brubakerf3f071f2015-02-10 19:38:51 -08002444 if (!outCharacteristics) {
2445 return KM_ERROR_UNEXPECTED_NULL_POINTER;
2446 }
2447
2448 uid_t callingUid = IPCThreadState::self()->getCallingUid();
2449
2450 Blob keyBlob;
2451 String8 name8(name);
2452 int rc;
2453
2454 ResponseCode responseCode = mKeyStore->getKeyForName(&keyBlob, name8, callingUid,
2455 TYPE_KEYMASTER_10);
2456 if (responseCode != ::NO_ERROR) {
2457 return responseCode;
2458 }
2459 keymaster_key_blob_t key;
2460 key.key_material_size = keyBlob.getLength();
2461 key.key_material = keyBlob.getValue();
2462 keymaster1_device_t* dev = mKeyStore->getDeviceForBlob(keyBlob);
2463 keymaster_key_characteristics_t *out = NULL;
2464 if (!dev->get_key_characteristics) {
2465 ALOGW("device does not implement get_key_characteristics");
2466 return KM_ERROR_UNIMPLEMENTED;
2467 }
Chad Brubakerd6634422015-03-21 22:36:07 -07002468 rc = dev->get_key_characteristics(dev, &key, clientId, appData, &out);
Chad Brubakerf3f071f2015-02-10 19:38:51 -08002469 if (out) {
2470 outCharacteristics->characteristics = *out;
2471 free(out);
2472 }
2473 return rc ? rc : ::NO_ERROR;
Chad Brubaker9899d6b2015-02-03 13:03:00 -08002474 }
2475
Chad Brubaker4c353cb2015-02-11 14:36:11 -08002476 int32_t importKey(const String16& name, const KeymasterArguments& params,
2477 keymaster_key_format_t format, const uint8_t *keyData,
2478 size_t keyLength, int uid, int flags,
2479 KeyCharacteristics* outCharacteristics) {
Chad Brubaker9489b792015-04-14 11:01:45 -07002480 uid = getEffectiveUid(uid);
2481 int rc = checkBinderPermissionAndKeystoreState(P_INSERT, uid,
2482 flags & KEYSTORE_FLAG_ENCRYPTED);
2483 if (rc != ::NO_ERROR) {
2484 return rc;
Chad Brubaker4c353cb2015-02-11 14:36:11 -08002485 }
2486
Chad Brubaker9489b792015-04-14 11:01:45 -07002487 rc = KM_ERROR_UNIMPLEMENTED;
Chad Brubaker4c353cb2015-02-11 14:36:11 -08002488 bool isFallback = false;
2489 keymaster_key_blob_t blob;
2490 keymaster_key_characteristics_t *out = NULL;
2491
2492 const keymaster1_device_t* device = mKeyStore->getDevice();
2493 const keymaster1_device_t* fallback = mKeyStore->getFallbackDevice();
Chad Brubaker57e106d2015-06-01 12:59:00 -07002494 std::vector<keymaster_key_param_t> opParams(params.params);
2495 const keymaster_key_param_set_t inParams = {opParams.data(), opParams.size()};
2496 const keymaster_blob_t input = {keyData, keyLength};
Chad Brubaker4c353cb2015-02-11 14:36:11 -08002497 if (device == NULL) {
2498 return ::SYSTEM_ERROR;
2499 }
2500 if (device->common.module->module_api_version >= KEYMASTER_MODULE_API_VERSION_1_0 &&
2501 device->import_key != NULL) {
Chad Brubaker57e106d2015-06-01 12:59:00 -07002502 rc = device->import_key(device, &inParams, format,&input, &blob, &out);
Chad Brubaker4c353cb2015-02-11 14:36:11 -08002503 }
2504 if (rc && fallback->import_key != NULL) {
Shawn Willden55268b52015-07-28 11:06:00 -06002505 ALOGW("Primary keymaster device failed to import key, falling back to SW.");
Chad Brubaker4c353cb2015-02-11 14:36:11 -08002506 isFallback = true;
Chad Brubaker57e106d2015-06-01 12:59:00 -07002507 rc = fallback->import_key(fallback, &inParams, format, &input, &blob, &out);
Chad Brubaker4c353cb2015-02-11 14:36:11 -08002508 }
2509 if (out) {
2510 if (outCharacteristics) {
2511 outCharacteristics->characteristics = *out;
2512 } else {
2513 keymaster_free_characteristics(out);
2514 }
2515 free(out);
2516 }
2517 if (rc) {
2518 return rc;
2519 }
2520
2521 String8 name8(name);
2522 String8 filename(mKeyStore->getKeyNameForUidWithDir(name8, uid));
2523
2524 Blob keyBlob(blob.key_material, blob.key_material_size, NULL, 0, ::TYPE_KEYMASTER_10);
2525 keyBlob.setFallback(isFallback);
2526 keyBlob.setEncrypted(flags & KEYSTORE_FLAG_ENCRYPTED);
2527
2528 free((void*) blob.key_material);
2529
Chad Brubaker72593ee2015-05-12 10:42:00 -07002530 return mKeyStore->put(filename.string(), &keyBlob, get_user_id(uid));
Chad Brubaker9899d6b2015-02-03 13:03:00 -08002531 }
2532
Chad Brubaker07b0cda2015-02-18 15:52:54 -08002533 void exportKey(const String16& name, keymaster_key_format_t format,
Chad Brubakerd6634422015-03-21 22:36:07 -07002534 const keymaster_blob_t* clientId,
2535 const keymaster_blob_t* appData, ExportResult* result) {
Chad Brubaker07b0cda2015-02-18 15:52:54 -08002536
2537 uid_t callingUid = IPCThreadState::self()->getCallingUid();
2538
2539 Blob keyBlob;
2540 String8 name8(name);
2541 int rc;
2542
2543 ResponseCode responseCode = mKeyStore->getKeyForName(&keyBlob, name8, callingUid,
2544 TYPE_KEYMASTER_10);
2545 if (responseCode != ::NO_ERROR) {
2546 result->resultCode = responseCode;
2547 return;
2548 }
2549 keymaster_key_blob_t key;
2550 key.key_material_size = keyBlob.getLength();
2551 key.key_material = keyBlob.getValue();
2552 keymaster1_device_t* dev = mKeyStore->getDeviceForBlob(keyBlob);
2553 if (!dev->export_key) {
2554 result->resultCode = KM_ERROR_UNIMPLEMENTED;
2555 return;
2556 }
Chad Brubaker57e106d2015-06-01 12:59:00 -07002557 keymaster_blob_t output = {NULL, 0};
2558 rc = dev->export_key(dev, format, &key, clientId, appData, &output);
2559 result->exportData.reset(const_cast<uint8_t*>(output.data));
2560 result->dataLength = output.data_length;
Chad Brubaker07b0cda2015-02-18 15:52:54 -08002561 result->resultCode = rc ? rc : ::NO_ERROR;
Chad Brubaker9899d6b2015-02-03 13:03:00 -08002562 }
2563
Chad Brubakerad6514a2015-04-09 14:00:26 -07002564
Chad Brubaker40a1a9b2015-02-20 14:08:13 -08002565 void begin(const sp<IBinder>& appToken, const String16& name, keymaster_purpose_t purpose,
Chad Brubaker154d7692015-03-27 13:59:31 -07002566 bool pruneable, const KeymasterArguments& params, const uint8_t* entropy,
Chad Brubaker57e106d2015-06-01 12:59:00 -07002567 size_t entropyLength, OperationResult* result) {
Chad Brubaker40a1a9b2015-02-20 14:08:13 -08002568 uid_t callingUid = IPCThreadState::self()->getCallingUid();
2569 if (!pruneable && get_app_id(callingUid) != AID_SYSTEM) {
2570 ALOGE("Non-system uid %d trying to start non-pruneable operation", callingUid);
2571 result->resultCode = ::PERMISSION_DENIED;
2572 return;
2573 }
Chad Brubaker0cf34a22015-04-23 11:06:16 -07002574 if (!checkAllowedOperationParams(params.params)) {
2575 result->resultCode = KM_ERROR_INVALID_ARGUMENT;
2576 return;
2577 }
Chad Brubaker40a1a9b2015-02-20 14:08:13 -08002578 Blob keyBlob;
2579 String8 name8(name);
2580 ResponseCode responseCode = mKeyStore->getKeyForName(&keyBlob, name8, callingUid,
2581 TYPE_KEYMASTER_10);
2582 if (responseCode != ::NO_ERROR) {
2583 result->resultCode = responseCode;
2584 return;
2585 }
2586 keymaster_key_blob_t key;
2587 key.key_material_size = keyBlob.getLength();
2588 key.key_material = keyBlob.getValue();
Chad Brubaker40a1a9b2015-02-20 14:08:13 -08002589 keymaster_operation_handle_t handle;
2590 keymaster1_device_t* dev = mKeyStore->getDeviceForBlob(keyBlob);
Chad Brubaker154d7692015-03-27 13:59:31 -07002591 keymaster_error_t err = KM_ERROR_UNIMPLEMENTED;
Chad Brubaker06801e02015-03-31 15:13:13 -07002592 std::vector<keymaster_key_param_t> opParams(params.params);
Chad Brubakerad6514a2015-04-09 14:00:26 -07002593 Unique_keymaster_key_characteristics characteristics;
2594 characteristics.reset(new keymaster_key_characteristics_t);
2595 err = getOperationCharacteristics(key, dev, opParams, characteristics.get());
2596 if (err) {
2597 result->resultCode = err;
2598 return;
2599 }
Chad Brubaker0cf34a22015-04-23 11:06:16 -07002600 const hw_auth_token_t* authToken = NULL;
Shawn Willdenb2ffa422015-06-17 12:18:55 -06002601 int32_t authResult = getAuthToken(characteristics.get(), 0, purpose, &authToken,
Chad Brubaker06801e02015-03-31 15:13:13 -07002602 /*failOnTokenMissing*/ false);
Chad Brubaker0cf34a22015-04-23 11:06:16 -07002603 // If per-operation auth is needed we need to begin the operation and
2604 // the client will need to authorize that operation before calling
2605 // update. Any other auth issues stop here.
2606 if (authResult != ::NO_ERROR && authResult != ::OP_AUTH_NEEDED) {
2607 result->resultCode = authResult;
Chad Brubaker06801e02015-03-31 15:13:13 -07002608 return;
2609 }
Chad Brubaker0cf34a22015-04-23 11:06:16 -07002610 addAuthToParams(&opParams, authToken);
Chad Brubaker154d7692015-03-27 13:59:31 -07002611 // Add entropy to the device first.
2612 if (entropy) {
2613 if (dev->add_rng_entropy) {
2614 err = dev->add_rng_entropy(dev, entropy, entropyLength);
2615 } else {
2616 err = KM_ERROR_UNIMPLEMENTED;
2617 }
2618 if (err) {
2619 result->resultCode = err;
2620 return;
2621 }
2622 }
Chad Brubaker57e106d2015-06-01 12:59:00 -07002623 keymaster_key_param_set_t inParams = {opParams.data(), opParams.size()};
Chad Brubaker40a1a9b2015-02-20 14:08:13 -08002624
Shawn Willden9221bff2015-06-18 18:23:54 -06002625 // Create a keyid for this key.
2626 keymaster::km_id_t keyid;
2627 if (!enforcement_policy.CreateKeyId(key, &keyid)) {
2628 ALOGE("Failed to create a key ID for authorization checking.");
2629 result->resultCode = KM_ERROR_UNKNOWN_ERROR;
2630 return;
2631 }
2632
2633 // Check that all key authorization policy requirements are met.
2634 keymaster::AuthorizationSet key_auths(characteristics->hw_enforced);
2635 key_auths.push_back(characteristics->sw_enforced);
2636 keymaster::AuthorizationSet operation_params(inParams);
2637 err = enforcement_policy.AuthorizeOperation(purpose, keyid, key_auths, operation_params,
2638 0 /* op_handle */,
2639 true /* is_begin_operation */);
2640 if (err) {
2641 result->resultCode = err;
2642 return;
2643 }
2644
Alex Klyubin4e88f9b2015-06-23 15:04:05 -07002645 keymaster_key_param_set_t outParams = {NULL, 0};
2646 err = dev->begin(dev, purpose, &key, &inParams, &outParams, &handle);
2647
Chad Brubaker40a1a9b2015-02-20 14:08:13 -08002648 // If there are too many operations abort the oldest operation that was
2649 // started as pruneable and try again.
2650 while (err == KM_ERROR_TOO_MANY_OPERATIONS && mOperationMap.hasPruneableOperation()) {
2651 sp<IBinder> oldest = mOperationMap.getOldestPruneableOperation();
2652 ALOGD("Ran out of operation handles, trying to prune %p", oldest.get());
Alex Klyubin700c1a32015-06-23 15:21:51 -07002653
2654 // We mostly ignore errors from abort() below because all we care about is whether at
2655 // least one pruneable operation has been removed.
2656 size_t op_count_before = mOperationMap.getPruneableOperationCount();
2657 int abort_error = abort(oldest);
2658 size_t op_count_after = mOperationMap.getPruneableOperationCount();
2659 if (op_count_after >= op_count_before) {
2660 // Failed to create space for a new operation. Bail to avoid an infinite loop.
2661 ALOGE("Failed to remove pruneable operation %p, error: %d",
2662 oldest.get(), abort_error);
Chad Brubaker40a1a9b2015-02-20 14:08:13 -08002663 break;
2664 }
Chad Brubaker57e106d2015-06-01 12:59:00 -07002665 err = dev->begin(dev, purpose, &key, &inParams, &outParams, &handle);
Chad Brubaker40a1a9b2015-02-20 14:08:13 -08002666 }
2667 if (err) {
2668 result->resultCode = err;
2669 return;
2670 }
Chad Brubaker40a1a9b2015-02-20 14:08:13 -08002671
Shawn Willden9221bff2015-06-18 18:23:54 -06002672 sp<IBinder> operationToken = mOperationMap.addOperation(handle, keyid, purpose, dev,
2673 appToken, characteristics.release(),
Chad Brubaker06801e02015-03-31 15:13:13 -07002674 pruneable);
Chad Brubaker0cf34a22015-04-23 11:06:16 -07002675 if (authToken) {
2676 mOperationMap.setOperationAuthToken(operationToken, authToken);
2677 }
2678 // Return the authentication lookup result. If this is a per operation
2679 // auth'd key then the resultCode will be ::OP_AUTH_NEEDED and the
2680 // application should get an auth token using the handle before the
2681 // first call to update, which will fail if keystore hasn't received the
2682 // auth token.
2683 result->resultCode = authResult;
Chad Brubaker40a1a9b2015-02-20 14:08:13 -08002684 result->token = operationToken;
Chad Brubakerc3a18562015-03-17 18:21:35 -07002685 result->handle = handle;
Chad Brubaker57e106d2015-06-01 12:59:00 -07002686 if (outParams.params) {
2687 result->outParams.params.assign(outParams.params, outParams.params + outParams.length);
2688 free(outParams.params);
2689 }
Chad Brubaker9899d6b2015-02-03 13:03:00 -08002690 }
2691
Chad Brubaker40a1a9b2015-02-20 14:08:13 -08002692 void update(const sp<IBinder>& token, const KeymasterArguments& params, const uint8_t* data,
2693 size_t dataLength, OperationResult* result) {
Chad Brubaker0cf34a22015-04-23 11:06:16 -07002694 if (!checkAllowedOperationParams(params.params)) {
2695 result->resultCode = KM_ERROR_INVALID_ARGUMENT;
2696 return;
2697 }
Chad Brubaker40a1a9b2015-02-20 14:08:13 -08002698 const keymaster1_device_t* dev;
2699 keymaster_operation_handle_t handle;
Shawn Willdenb2ffa422015-06-17 12:18:55 -06002700 keymaster_purpose_t purpose;
Shawn Willden9221bff2015-06-18 18:23:54 -06002701 keymaster::km_id_t keyid;
2702 const keymaster_key_characteristics_t* characteristics;
2703 if (!mOperationMap.getOperation(token, &handle, &keyid, &purpose, &dev, &characteristics)) {
Chad Brubaker40a1a9b2015-02-20 14:08:13 -08002704 result->resultCode = KM_ERROR_INVALID_OPERATION_HANDLE;
2705 return;
2706 }
Chad Brubaker06801e02015-03-31 15:13:13 -07002707 std::vector<keymaster_key_param_t> opParams(params.params);
Chad Brubaker0cf34a22015-04-23 11:06:16 -07002708 int32_t authResult = addOperationAuthTokenIfNeeded(token, &opParams);
2709 if (authResult != ::NO_ERROR) {
Chad Brubaker06801e02015-03-31 15:13:13 -07002710 result->resultCode = authResult;
2711 return;
2712 }
Chad Brubaker57e106d2015-06-01 12:59:00 -07002713 keymaster_key_param_set_t inParams = {opParams.data(), opParams.size()};
2714 keymaster_blob_t input = {data, dataLength};
2715 size_t consumed = 0;
2716 keymaster_blob_t output = {NULL, 0};
2717 keymaster_key_param_set_t outParams = {NULL, 0};
2718
Shawn Willden9221bff2015-06-18 18:23:54 -06002719 // Check that all key authorization policy requirements are met.
2720 keymaster::AuthorizationSet key_auths(characteristics->hw_enforced);
2721 key_auths.push_back(characteristics->sw_enforced);
2722 keymaster::AuthorizationSet operation_params(inParams);
2723 result->resultCode =
2724 enforcement_policy.AuthorizeOperation(purpose, keyid, key_auths,
2725 operation_params, handle,
2726 false /* is_begin_operation */);
2727 if (result->resultCode) {
2728 return;
2729 }
2730
Chad Brubaker57e106d2015-06-01 12:59:00 -07002731 keymaster_error_t err = dev->update(dev, handle, &inParams, &input, &consumed, &outParams,
2732 &output);
2733 result->data.reset(const_cast<uint8_t*>(output.data));
2734 result->dataLength = output.data_length;
Chad Brubaker40a1a9b2015-02-20 14:08:13 -08002735 result->inputConsumed = consumed;
2736 result->resultCode = err ? (int32_t) err : ::NO_ERROR;
Chad Brubaker57e106d2015-06-01 12:59:00 -07002737 if (outParams.params) {
2738 result->outParams.params.assign(outParams.params, outParams.params + outParams.length);
2739 free(outParams.params);
2740 }
Chad Brubaker9899d6b2015-02-03 13:03:00 -08002741 }
2742
Chad Brubaker40a1a9b2015-02-20 14:08:13 -08002743 void finish(const sp<IBinder>& token, const KeymasterArguments& params,
Chad Brubaker0d33e0b2015-05-29 12:30:19 -07002744 const uint8_t* signature, size_t signatureLength,
2745 const uint8_t* entropy, size_t entropyLength, OperationResult* result) {
Chad Brubaker0cf34a22015-04-23 11:06:16 -07002746 if (!checkAllowedOperationParams(params.params)) {
2747 result->resultCode = KM_ERROR_INVALID_ARGUMENT;
2748 return;
2749 }
Chad Brubaker40a1a9b2015-02-20 14:08:13 -08002750 const keymaster1_device_t* dev;
2751 keymaster_operation_handle_t handle;
Shawn Willdenb2ffa422015-06-17 12:18:55 -06002752 keymaster_purpose_t purpose;
Shawn Willden9221bff2015-06-18 18:23:54 -06002753 keymaster::km_id_t keyid;
2754 const keymaster_key_characteristics_t* characteristics;
2755 if (!mOperationMap.getOperation(token, &handle, &keyid, &purpose, &dev, &characteristics)) {
Chad Brubaker40a1a9b2015-02-20 14:08:13 -08002756 result->resultCode = KM_ERROR_INVALID_OPERATION_HANDLE;
2757 return;
2758 }
Chad Brubaker06801e02015-03-31 15:13:13 -07002759 std::vector<keymaster_key_param_t> opParams(params.params);
Chad Brubaker0cf34a22015-04-23 11:06:16 -07002760 int32_t authResult = addOperationAuthTokenIfNeeded(token, &opParams);
2761 if (authResult != ::NO_ERROR) {
Chad Brubaker06801e02015-03-31 15:13:13 -07002762 result->resultCode = authResult;
2763 return;
2764 }
Chad Brubaker0d33e0b2015-05-29 12:30:19 -07002765 keymaster_error_t err;
2766 if (entropy) {
2767 if (dev->add_rng_entropy) {
2768 err = dev->add_rng_entropy(dev, entropy, entropyLength);
2769 } else {
2770 err = KM_ERROR_UNIMPLEMENTED;
2771 }
2772 if (err) {
2773 result->resultCode = err;
2774 return;
2775 }
2776 }
Chad Brubaker0cf34a22015-04-23 11:06:16 -07002777
Chad Brubaker57e106d2015-06-01 12:59:00 -07002778 keymaster_key_param_set_t inParams = {opParams.data(), opParams.size()};
2779 keymaster_blob_t input = {signature, signatureLength};
2780 keymaster_blob_t output = {NULL, 0};
2781 keymaster_key_param_set_t outParams = {NULL, 0};
Shawn Willden9221bff2015-06-18 18:23:54 -06002782
2783 // Check that all key authorization policy requirements are met.
2784 keymaster::AuthorizationSet key_auths(characteristics->hw_enforced);
2785 key_auths.push_back(characteristics->sw_enforced);
2786 keymaster::AuthorizationSet operation_params(inParams);
2787 err = enforcement_policy.AuthorizeOperation(purpose, keyid, key_auths, operation_params,
2788 handle, false /* is_begin_operation */);
2789 if (err) {
2790 result->resultCode = err;
2791 return;
2792 }
2793
Chad Brubaker0d33e0b2015-05-29 12:30:19 -07002794 err = dev->finish(dev, handle, &inParams, &input, &outParams, &output);
Chad Brubaker40a1a9b2015-02-20 14:08:13 -08002795 // Remove the operation regardless of the result
2796 mOperationMap.removeOperation(token);
Chad Brubaker06801e02015-03-31 15:13:13 -07002797 mAuthTokenTable.MarkCompleted(handle);
Chad Brubaker57e106d2015-06-01 12:59:00 -07002798
2799 result->data.reset(const_cast<uint8_t*>(output.data));
2800 result->dataLength = output.data_length;
Chad Brubaker40a1a9b2015-02-20 14:08:13 -08002801 result->resultCode = err ? (int32_t) err : ::NO_ERROR;
Chad Brubaker57e106d2015-06-01 12:59:00 -07002802 if (outParams.params) {
2803 result->outParams.params.assign(outParams.params, outParams.params + outParams.length);
2804 free(outParams.params);
2805 }
Chad Brubaker9899d6b2015-02-03 13:03:00 -08002806 }
2807
Chad Brubaker40a1a9b2015-02-20 14:08:13 -08002808 int32_t abort(const sp<IBinder>& token) {
2809 const keymaster1_device_t* dev;
2810 keymaster_operation_handle_t handle;
Shawn Willdenb2ffa422015-06-17 12:18:55 -06002811 keymaster_purpose_t purpose;
Shawn Willden9221bff2015-06-18 18:23:54 -06002812 keymaster::km_id_t keyid;
2813 if (!mOperationMap.getOperation(token, &handle, &keyid, &purpose, &dev, NULL)) {
Chad Brubaker40a1a9b2015-02-20 14:08:13 -08002814 return KM_ERROR_INVALID_OPERATION_HANDLE;
2815 }
2816 mOperationMap.removeOperation(token);
Chad Brubaker06801e02015-03-31 15:13:13 -07002817 int32_t rc;
Chad Brubaker40a1a9b2015-02-20 14:08:13 -08002818 if (!dev->abort) {
Chad Brubaker06801e02015-03-31 15:13:13 -07002819 rc = KM_ERROR_UNIMPLEMENTED;
2820 } else {
2821 rc = dev->abort(dev, handle);
Chad Brubaker40a1a9b2015-02-20 14:08:13 -08002822 }
Chad Brubaker06801e02015-03-31 15:13:13 -07002823 mAuthTokenTable.MarkCompleted(handle);
Chad Brubaker40a1a9b2015-02-20 14:08:13 -08002824 if (rc) {
2825 return rc;
2826 }
2827 return ::NO_ERROR;
Chad Brubaker9899d6b2015-02-03 13:03:00 -08002828 }
2829
Chad Brubaker2ed2baa2015-03-21 21:20:10 -07002830 bool isOperationAuthorized(const sp<IBinder>& token) {
2831 const keymaster1_device_t* dev;
2832 keymaster_operation_handle_t handle;
Chad Brubakerad6514a2015-04-09 14:00:26 -07002833 const keymaster_key_characteristics_t* characteristics;
Shawn Willdenb2ffa422015-06-17 12:18:55 -06002834 keymaster_purpose_t purpose;
Shawn Willden9221bff2015-06-18 18:23:54 -06002835 keymaster::km_id_t keyid;
2836 if (!mOperationMap.getOperation(token, &handle, &keyid, &purpose, &dev, &characteristics)) {
Chad Brubaker2ed2baa2015-03-21 21:20:10 -07002837 return false;
2838 }
Chad Brubaker0cf34a22015-04-23 11:06:16 -07002839 const hw_auth_token_t* authToken = NULL;
2840 mOperationMap.getOperationAuthToken(token, &authToken);
Chad Brubaker06801e02015-03-31 15:13:13 -07002841 std::vector<keymaster_key_param_t> ignored;
Chad Brubaker0cf34a22015-04-23 11:06:16 -07002842 int32_t authResult = addOperationAuthTokenIfNeeded(token, &ignored);
2843 return authResult == ::NO_ERROR;
Chad Brubaker2ed2baa2015-03-21 21:20:10 -07002844 }
2845
Chad Brubakerd80c7b42015-03-31 11:04:28 -07002846 int32_t addAuthToken(const uint8_t* token, size_t length) {
Chad Brubaker9489b792015-04-14 11:01:45 -07002847 if (!checkBinderPermission(P_ADD_AUTH)) {
2848 ALOGW("addAuthToken: permission denied for %d",
2849 IPCThreadState::self()->getCallingUid());
Chad Brubakerd80c7b42015-03-31 11:04:28 -07002850 return ::PERMISSION_DENIED;
2851 }
2852 if (length != sizeof(hw_auth_token_t)) {
2853 return KM_ERROR_INVALID_ARGUMENT;
2854 }
2855 hw_auth_token_t* authToken = new hw_auth_token_t;
2856 memcpy(reinterpret_cast<void*>(authToken), token, sizeof(hw_auth_token_t));
2857 // The table takes ownership of authToken.
2858 mAuthTokenTable.AddAuthenticationToken(authToken);
2859 return ::NO_ERROR;
Chad Brubaker2ed2baa2015-03-21 21:20:10 -07002860 }
2861
Kenny Root07438c82012-11-02 15:41:02 -07002862private:
Chad Brubaker9489b792015-04-14 11:01:45 -07002863 static const int32_t UID_SELF = -1;
2864
2865 /**
2866 * Get the effective target uid for a binder operation that takes an
2867 * optional uid as the target.
2868 */
2869 inline uid_t getEffectiveUid(int32_t targetUid) {
2870 if (targetUid == UID_SELF) {
2871 return IPCThreadState::self()->getCallingUid();
2872 }
2873 return static_cast<uid_t>(targetUid);
2874 }
2875
2876 /**
2877 * Check if the caller of the current binder method has the required
2878 * permission and if acting on other uids the grants to do so.
2879 */
2880 inline bool checkBinderPermission(perm_t permission, int32_t targetUid = UID_SELF) {
2881 uid_t callingUid = IPCThreadState::self()->getCallingUid();
2882 pid_t spid = IPCThreadState::self()->getCallingPid();
2883 if (!has_permission(callingUid, permission, spid)) {
2884 ALOGW("permission %s denied for %d", get_perm_label(permission), callingUid);
2885 return false;
2886 }
2887 if (!is_granted_to(callingUid, getEffectiveUid(targetUid))) {
2888 ALOGW("uid %d not granted to act for %d", callingUid, targetUid);
2889 return false;
2890 }
2891 return true;
2892 }
2893
2894 /**
2895 * Check if the caller of the current binder method has the required
Chad Brubakerb37a5232015-05-01 10:21:27 -07002896 * permission and the target uid is the caller or the caller is system.
2897 */
2898 inline bool checkBinderPermissionSelfOrSystem(perm_t permission, int32_t targetUid) {
2899 uid_t callingUid = IPCThreadState::self()->getCallingUid();
2900 pid_t spid = IPCThreadState::self()->getCallingPid();
2901 if (!has_permission(callingUid, permission, spid)) {
2902 ALOGW("permission %s denied for %d", get_perm_label(permission), callingUid);
2903 return false;
2904 }
2905 return getEffectiveUid(targetUid) == callingUid || callingUid == AID_SYSTEM;
2906 }
2907
2908 /**
2909 * Check if the caller of the current binder method has the required
Chad Brubaker9489b792015-04-14 11:01:45 -07002910 * permission or the target of the operation is the caller's uid. This is
2911 * for operation where the permission is only for cross-uid activity and all
2912 * uids are allowed to act on their own (ie: clearing all entries for a
2913 * given uid).
2914 */
2915 inline bool checkBinderPermissionOrSelfTarget(perm_t permission, int32_t targetUid) {
2916 uid_t callingUid = IPCThreadState::self()->getCallingUid();
2917 if (getEffectiveUid(targetUid) == callingUid) {
2918 return true;
2919 } else {
2920 return checkBinderPermission(permission, targetUid);
2921 }
2922 }
2923
2924 /**
2925 * Helper method to check that the caller has the required permission as
2926 * well as the keystore is in the unlocked state if checkUnlocked is true.
2927 *
2928 * Returns NO_ERROR on success, PERMISSION_DENIED on a permission error and
2929 * otherwise the state of keystore when not unlocked and checkUnlocked is
2930 * true.
2931 */
2932 inline int32_t checkBinderPermissionAndKeystoreState(perm_t permission, int32_t targetUid = -1,
2933 bool checkUnlocked = true) {
2934 if (!checkBinderPermission(permission, targetUid)) {
2935 return ::PERMISSION_DENIED;
2936 }
Chad Brubaker72593ee2015-05-12 10:42:00 -07002937 State state = mKeyStore->getState(get_user_id(getEffectiveUid(targetUid)));
Chad Brubaker9489b792015-04-14 11:01:45 -07002938 if (checkUnlocked && !isKeystoreUnlocked(state)) {
2939 return state;
2940 }
2941
2942 return ::NO_ERROR;
2943
2944 }
2945
Kenny Root9d45d1c2013-02-14 10:32:30 -08002946 inline bool isKeystoreUnlocked(State state) {
2947 switch (state) {
2948 case ::STATE_NO_ERROR:
2949 return true;
2950 case ::STATE_UNINITIALIZED:
2951 case ::STATE_LOCKED:
2952 return false;
2953 }
2954 return false;
Kenny Root07438c82012-11-02 15:41:02 -07002955 }
2956
Chad Brubaker67d2a502015-03-11 17:21:18 +00002957 bool isKeyTypeSupported(const keymaster1_device_t* device, keymaster_keypair_t keyType) {
Kenny Root1d448c02013-11-21 10:36:53 -08002958 const int32_t device_api = device->common.module->module_api_version;
2959 if (device_api == KEYMASTER_MODULE_API_VERSION_0_2) {
2960 switch (keyType) {
2961 case TYPE_RSA:
2962 case TYPE_DSA:
2963 case TYPE_EC:
2964 return true;
2965 default:
2966 return false;
2967 }
2968 } else if (device_api >= KEYMASTER_MODULE_API_VERSION_0_3) {
2969 switch (keyType) {
2970 case TYPE_RSA:
2971 return true;
2972 case TYPE_DSA:
2973 return device->flags & KEYMASTER_SUPPORTS_DSA;
2974 case TYPE_EC:
2975 return device->flags & KEYMASTER_SUPPORTS_EC;
2976 default:
2977 return false;
2978 }
2979 } else {
2980 return keyType == TYPE_RSA;
2981 }
2982 }
2983
Chad Brubaker0cf34a22015-04-23 11:06:16 -07002984 /**
2985 * Check that all keymaster_key_param_t's provided by the application are
2986 * allowed. Any parameter that keystore adds itself should be disallowed here.
2987 */
2988 bool checkAllowedOperationParams(const std::vector<keymaster_key_param_t>& params) {
2989 for (auto param: params) {
2990 switch (param.tag) {
2991 case KM_TAG_AUTH_TOKEN:
2992 return false;
2993 default:
2994 break;
2995 }
2996 }
2997 return true;
2998 }
2999
3000 keymaster_error_t getOperationCharacteristics(const keymaster_key_blob_t& key,
3001 const keymaster1_device_t* dev,
3002 const std::vector<keymaster_key_param_t>& params,
3003 keymaster_key_characteristics_t* out) {
3004 UniquePtr<keymaster_blob_t> appId;
3005 UniquePtr<keymaster_blob_t> appData;
3006 for (auto param : params) {
3007 if (param.tag == KM_TAG_APPLICATION_ID) {
3008 appId.reset(new keymaster_blob_t);
3009 appId->data = param.blob.data;
3010 appId->data_length = param.blob.data_length;
3011 } else if (param.tag == KM_TAG_APPLICATION_DATA) {
3012 appData.reset(new keymaster_blob_t);
3013 appData->data = param.blob.data;
3014 appData->data_length = param.blob.data_length;
3015 }
3016 }
3017 keymaster_key_characteristics_t* result = NULL;
3018 if (!dev->get_key_characteristics) {
3019 return KM_ERROR_UNIMPLEMENTED;
3020 }
3021 keymaster_error_t error = dev->get_key_characteristics(dev, &key, appId.get(),
3022 appData.get(), &result);
3023 if (result) {
3024 *out = *result;
3025 free(result);
3026 }
3027 return error;
3028 }
3029
3030 /**
3031 * Get the auth token for this operation from the auth token table.
3032 *
3033 * Returns ::NO_ERROR if the auth token was set or none was required.
3034 * ::OP_AUTH_NEEDED if it is a per op authorization, no
3035 * authorization token exists for that operation and
3036 * failOnTokenMissing is false.
3037 * KM_ERROR_KEY_USER_NOT_AUTHENTICATED if there is no valid auth
3038 * token for the operation
3039 */
3040 int32_t getAuthToken(const keymaster_key_characteristics_t* characteristics,
3041 keymaster_operation_handle_t handle,
Shawn Willdenb2ffa422015-06-17 12:18:55 -06003042 keymaster_purpose_t purpose,
Chad Brubaker0cf34a22015-04-23 11:06:16 -07003043 const hw_auth_token_t** authToken,
3044 bool failOnTokenMissing = true) {
3045
3046 std::vector<keymaster_key_param_t> allCharacteristics;
3047 for (size_t i = 0; i < characteristics->sw_enforced.length; i++) {
3048 allCharacteristics.push_back(characteristics->sw_enforced.params[i]);
3049 }
3050 for (size_t i = 0; i < characteristics->hw_enforced.length; i++) {
3051 allCharacteristics.push_back(characteristics->hw_enforced.params[i]);
3052 }
Shawn Willdenb2ffa422015-06-17 12:18:55 -06003053 keymaster::AuthTokenTable::Error err = mAuthTokenTable.FindAuthorization(
3054 allCharacteristics.data(), allCharacteristics.size(), purpose, handle, authToken);
Chad Brubaker0cf34a22015-04-23 11:06:16 -07003055 switch (err) {
3056 case keymaster::AuthTokenTable::OK:
3057 case keymaster::AuthTokenTable::AUTH_NOT_REQUIRED:
3058 return ::NO_ERROR;
3059 case keymaster::AuthTokenTable::AUTH_TOKEN_NOT_FOUND:
3060 case keymaster::AuthTokenTable::AUTH_TOKEN_EXPIRED:
3061 case keymaster::AuthTokenTable::AUTH_TOKEN_WRONG_SID:
3062 return KM_ERROR_KEY_USER_NOT_AUTHENTICATED;
3063 case keymaster::AuthTokenTable::OP_HANDLE_REQUIRED:
3064 return failOnTokenMissing ? (int32_t) KM_ERROR_KEY_USER_NOT_AUTHENTICATED :
3065 (int32_t) ::OP_AUTH_NEEDED;
3066 default:
3067 ALOGE("Unexpected FindAuthorization return value %d", err);
3068 return KM_ERROR_INVALID_ARGUMENT;
3069 }
3070 }
3071
3072 inline void addAuthToParams(std::vector<keymaster_key_param_t>* params,
3073 const hw_auth_token_t* token) {
3074 if (token) {
3075 params->push_back(keymaster_param_blob(KM_TAG_AUTH_TOKEN,
3076 reinterpret_cast<const uint8_t*>(token),
3077 sizeof(hw_auth_token_t)));
3078 }
3079 }
3080
3081 /**
3082 * Add the auth token for the operation to the param list if the operation
3083 * requires authorization. Uses the cached result in the OperationMap if available
3084 * otherwise gets the token from the AuthTokenTable and caches the result.
3085 *
3086 * Returns ::NO_ERROR if the auth token was added or not needed.
3087 * KM_ERROR_KEY_USER_NOT_AUTHENTICATED if the operation is not
3088 * authenticated.
3089 * KM_ERROR_INVALID_OPERATION_HANDLE if token is not a valid
3090 * operation token.
3091 */
3092 int32_t addOperationAuthTokenIfNeeded(sp<IBinder> token,
3093 std::vector<keymaster_key_param_t>* params) {
3094 const hw_auth_token_t* authToken = NULL;
Chad Brubaker7169a842015-04-29 19:58:34 -07003095 mOperationMap.getOperationAuthToken(token, &authToken);
3096 if (!authToken) {
Chad Brubaker0cf34a22015-04-23 11:06:16 -07003097 const keymaster1_device_t* dev;
3098 keymaster_operation_handle_t handle;
3099 const keymaster_key_characteristics_t* characteristics = NULL;
Shawn Willdenb2ffa422015-06-17 12:18:55 -06003100 keymaster_purpose_t purpose;
Shawn Willden9221bff2015-06-18 18:23:54 -06003101 keymaster::km_id_t keyid;
3102 if (!mOperationMap.getOperation(token, &handle, &keyid, &purpose, &dev,
3103 &characteristics)) {
Chad Brubaker0cf34a22015-04-23 11:06:16 -07003104 return KM_ERROR_INVALID_OPERATION_HANDLE;
3105 }
Shawn Willdenb2ffa422015-06-17 12:18:55 -06003106 int32_t result = getAuthToken(characteristics, handle, purpose, &authToken);
Chad Brubaker0cf34a22015-04-23 11:06:16 -07003107 if (result != ::NO_ERROR) {
3108 return result;
3109 }
3110 if (authToken) {
3111 mOperationMap.setOperationAuthToken(token, authToken);
3112 }
3113 }
3114 addAuthToParams(params, authToken);
3115 return ::NO_ERROR;
3116 }
3117
Chad Brubaker3a7d9e62015-06-04 15:01:46 -07003118 /**
3119 * Translate a result value to a legacy return value. All keystore errors are
3120 * preserved and keymaster errors become SYSTEM_ERRORs
3121 */
3122 inline int32_t translateResultToLegacyResult(int32_t result) {
3123 if (result > 0) {
3124 return result;
3125 }
3126 return ::SYSTEM_ERROR;
3127 }
3128
Chad Brubaker3a7d9e62015-06-04 15:01:46 -07003129 keymaster_key_param_t* getKeyAlgorithm(keymaster_key_characteristics_t* characteristics) {
3130 for (size_t i = 0; i < characteristics->hw_enforced.length; i++) {
3131 if (characteristics->hw_enforced.params[i].tag == KM_TAG_ALGORITHM) {
3132 return &characteristics->hw_enforced.params[i];
3133 }
3134 }
3135 for (size_t i = 0; i < characteristics->sw_enforced.length; i++) {
3136 if (characteristics->sw_enforced.params[i].tag == KM_TAG_ALGORITHM) {
3137 return &characteristics->sw_enforced.params[i];
3138 }
3139 }
3140 return NULL;
3141 }
3142
3143 void addLegacyBeginParams(const String16& name, std::vector<keymaster_key_param_t>& params) {
3144 // All legacy keys are DIGEST_NONE/PAD_NONE.
3145 params.push_back(keymaster_param_enum(KM_TAG_DIGEST, KM_DIGEST_NONE));
3146 params.push_back(keymaster_param_enum(KM_TAG_PADDING, KM_PAD_NONE));
3147
3148 // Look up the algorithm of the key.
3149 KeyCharacteristics characteristics;
3150 int32_t rc = getKeyCharacteristics(name, NULL, NULL, &characteristics);
3151 if (rc != ::NO_ERROR) {
3152 ALOGE("Failed to get key characteristics");
3153 return;
3154 }
3155 keymaster_key_param_t* algorithm = getKeyAlgorithm(&characteristics.characteristics);
3156 if (!algorithm) {
3157 ALOGE("getKeyCharacteristics did not include KM_TAG_ALGORITHM");
3158 return;
3159 }
3160 params.push_back(*algorithm);
3161 }
3162
3163 int32_t doLegacySignVerify(const String16& name, const uint8_t* data, size_t length,
3164 uint8_t** out, size_t* outLength, const uint8_t* signature,
3165 size_t signatureLength, keymaster_purpose_t purpose) {
3166
Chad Brubaker3a7d9e62015-06-04 15:01:46 -07003167 std::basic_stringstream<uint8_t> outBuffer;
3168 OperationResult result;
3169 KeymasterArguments inArgs;
3170 addLegacyBeginParams(name, inArgs.params);
3171 sp<IBinder> appToken(new BBinder);
3172 sp<IBinder> token;
3173
3174 begin(appToken, name, purpose, true, inArgs, NULL, 0, &result);
3175 if (result.resultCode != ResponseCode::NO_ERROR) {
Chad Brubakerdf705172015-06-17 20:17:51 -07003176 if (result.resultCode == ::KEY_NOT_FOUND) {
3177 ALOGW("Key not found");
3178 } else {
3179 ALOGW("Error in begin: %d", result.resultCode);
3180 }
Chad Brubaker3a7d9e62015-06-04 15:01:46 -07003181 return translateResultToLegacyResult(result.resultCode);
3182 }
3183 inArgs.params.clear();
3184 token = result.token;
3185 size_t consumed = 0;
3186 size_t lastConsumed = 0;
3187 do {
3188 update(token, inArgs, data + consumed, length - consumed, &result);
3189 if (result.resultCode != ResponseCode::NO_ERROR) {
3190 ALOGW("Error in update: %d", result.resultCode);
3191 return translateResultToLegacyResult(result.resultCode);
3192 }
3193 if (out) {
3194 outBuffer.write(result.data.get(), result.dataLength);
3195 }
3196 lastConsumed = result.inputConsumed;
3197 consumed += lastConsumed;
3198 } while (consumed < length && lastConsumed > 0);
3199
3200 if (consumed != length) {
3201 ALOGW("Not all data consumed. Consumed %zu of %zu", consumed, length);
3202 return ::SYSTEM_ERROR;
3203 }
3204
3205 finish(token, inArgs, signature, signatureLength, NULL, 0, &result);
3206 if (result.resultCode != ResponseCode::NO_ERROR) {
3207 ALOGW("Error in finish: %d", result.resultCode);
3208 return translateResultToLegacyResult(result.resultCode);
3209 }
3210 if (out) {
3211 outBuffer.write(result.data.get(), result.dataLength);
3212 }
3213
3214 if (out) {
3215 auto buf = outBuffer.str();
3216 *out = new uint8_t[buf.size()];
3217 memcpy(*out, buf.c_str(), buf.size());
3218 *outLength = buf.size();
3219 }
3220
3221 return ::NO_ERROR;
3222 }
3223
Kenny Root07438c82012-11-02 15:41:02 -07003224 ::KeyStore* mKeyStore;
Chad Brubaker40a1a9b2015-02-20 14:08:13 -08003225 OperationMap mOperationMap;
Chad Brubakerd80c7b42015-03-31 11:04:28 -07003226 keymaster::AuthTokenTable mAuthTokenTable;
Shawn Willden9221bff2015-06-18 18:23:54 -06003227 KeystoreKeymasterEnforcement enforcement_policy;
Kenny Root07438c82012-11-02 15:41:02 -07003228};
3229
3230}; // namespace android
Kenny Roota91203b2012-02-15 15:00:46 -08003231
3232int main(int argc, char* argv[]) {
Kenny Roota91203b2012-02-15 15:00:46 -08003233 if (argc < 2) {
3234 ALOGE("A directory must be specified!");
3235 return 1;
3236 }
3237 if (chdir(argv[1]) == -1) {
3238 ALOGE("chdir: %s: %s", argv[1], strerror(errno));
3239 return 1;
3240 }
3241
3242 Entropy entropy;
3243 if (!entropy.open()) {
3244 return 1;
3245 }
Kenny Root70e3a862012-02-15 17:20:23 -08003246
Chad Brubakerbd07a232015-06-01 10:44:27 -07003247 keymaster1_device_t* dev;
Kenny Root70e3a862012-02-15 17:20:23 -08003248 if (keymaster_device_initialize(&dev)) {
3249 ALOGE("keystore keymaster could not be initialized; exiting");
3250 return 1;
3251 }
3252
Chad Brubaker67d2a502015-03-11 17:21:18 +00003253 keymaster1_device_t* fallback;
Chad Brubakerfc18edc2015-01-12 15:17:18 -08003254 if (fallback_keymaster_device_initialize(&fallback)) {
3255 ALOGE("software keymaster could not be initialized; exiting");
3256 return 1;
3257 }
3258
Riley Spahneaabae92014-06-30 12:39:52 -07003259 ks_is_selinux_enabled = is_selinux_enabled();
3260 if (ks_is_selinux_enabled) {
3261 union selinux_callback cb;
3262 cb.func_log = selinux_log_callback;
3263 selinux_set_callback(SELINUX_CB_LOG, cb);
3264 if (getcon(&tctx) != 0) {
3265 ALOGE("SELinux: Could not acquire target context. Aborting keystore.\n");
3266 return -1;
3267 }
3268 } else {
3269 ALOGI("SELinux: Keystore SELinux is disabled.\n");
3270 }
3271
Chad Brubakerbd07a232015-06-01 10:44:27 -07003272 KeyStore keyStore(&entropy, dev, fallback);
Kenny Root655b9582013-04-04 08:37:42 -07003273 keyStore.initialize();
Kenny Root07438c82012-11-02 15:41:02 -07003274 android::sp<android::IServiceManager> sm = android::defaultServiceManager();
3275 android::sp<android::KeyStoreProxy> proxy = new android::KeyStoreProxy(&keyStore);
3276 android::status_t ret = sm->addService(android::String16("android.security.keystore"), proxy);
3277 if (ret != android::OK) {
3278 ALOGE("Couldn't register binder service!");
3279 return -1;
Kenny Roota91203b2012-02-15 15:00:46 -08003280 }
Kenny Root07438c82012-11-02 15:41:02 -07003281
3282 /*
3283 * We're the only thread in existence, so we're just going to process
3284 * Binder transaction as a single-threaded program.
3285 */
3286 android::IPCThreadState::self()->joinThreadPool();
Kenny Root70e3a862012-02-15 17:20:23 -08003287
3288 keymaster_device_release(dev);
Kenny Roota91203b2012-02-15 15:00:46 -08003289 return 1;
3290}