blob: 0906abf20d460594eedcb5e85f9b5dc1bc133482 [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));
259 uint64_t now = keymaster::java_time(time(NULL));
260 params->push_back(keymaster_param_date(KM_TAG_CREATION_DATETIME, now));
261}
262
Kenny Root07438c82012-11-02 15:41:02 -0700263/***************
264 * PERMISSIONS *
265 ***************/
266
267/* Here are the permissions, actions, users, and the main function. */
268typedef enum {
Chad Brubakere6c3bfa2015-05-12 15:18:26 -0700269 P_GET_STATE = 1 << 0,
Robin Lee4e865752014-08-19 17:37:55 +0100270 P_GET = 1 << 1,
271 P_INSERT = 1 << 2,
272 P_DELETE = 1 << 3,
273 P_EXIST = 1 << 4,
Chad Brubakere6c3bfa2015-05-12 15:18:26 -0700274 P_LIST = 1 << 5,
Robin Lee4e865752014-08-19 17:37:55 +0100275 P_RESET = 1 << 6,
276 P_PASSWORD = 1 << 7,
277 P_LOCK = 1 << 8,
278 P_UNLOCK = 1 << 9,
Chad Brubakere6c3bfa2015-05-12 15:18:26 -0700279 P_IS_EMPTY = 1 << 10,
Robin Lee4e865752014-08-19 17:37:55 +0100280 P_SIGN = 1 << 11,
281 P_VERIFY = 1 << 12,
282 P_GRANT = 1 << 13,
283 P_DUPLICATE = 1 << 14,
284 P_CLEAR_UID = 1 << 15,
Chad Brubakere6c3bfa2015-05-12 15:18:26 -0700285 P_ADD_AUTH = 1 << 16,
286 P_USER_CHANGED = 1 << 17,
Kenny Root07438c82012-11-02 15:41:02 -0700287} perm_t;
288
289static struct user_euid {
290 uid_t uid;
291 uid_t euid;
292} user_euids[] = {
293 {AID_VPN, AID_SYSTEM},
294 {AID_WIFI, AID_SYSTEM},
295 {AID_ROOT, AID_SYSTEM},
296};
297
Riley Spahneaabae92014-06-30 12:39:52 -0700298/* perm_labels associcated with keystore_key SELinux class verbs. */
299const char *perm_labels[] = {
Chad Brubakere6c3bfa2015-05-12 15:18:26 -0700300 "get_state",
Riley Spahneaabae92014-06-30 12:39:52 -0700301 "get",
302 "insert",
303 "delete",
304 "exist",
Chad Brubakere6c3bfa2015-05-12 15:18:26 -0700305 "list",
Riley Spahneaabae92014-06-30 12:39:52 -0700306 "reset",
307 "password",
308 "lock",
309 "unlock",
Chad Brubakere6c3bfa2015-05-12 15:18:26 -0700310 "is_empty",
Riley Spahneaabae92014-06-30 12:39:52 -0700311 "sign",
312 "verify",
313 "grant",
314 "duplicate",
Robin Lee4e865752014-08-19 17:37:55 +0100315 "clear_uid",
Chad Brubakerd80c7b42015-03-31 11:04:28 -0700316 "add_auth",
Chad Brubakerc0f031a2015-05-12 10:43:10 -0700317 "user_changed",
Riley Spahneaabae92014-06-30 12:39:52 -0700318};
319
Kenny Root07438c82012-11-02 15:41:02 -0700320static struct user_perm {
321 uid_t uid;
322 perm_t perms;
323} user_perms[] = {
324 {AID_SYSTEM, static_cast<perm_t>((uint32_t)(~0)) },
325 {AID_VPN, static_cast<perm_t>(P_GET | P_SIGN | P_VERIFY) },
326 {AID_WIFI, static_cast<perm_t>(P_GET | P_SIGN | P_VERIFY) },
327 {AID_ROOT, static_cast<perm_t>(P_GET) },
328};
329
Chad Brubakere6c3bfa2015-05-12 15:18:26 -0700330static const perm_t DEFAULT_PERMS = static_cast<perm_t>(P_GET_STATE | P_GET | P_INSERT | P_DELETE
331 | P_EXIST | P_LIST | P_SIGN | P_VERIFY);
Kenny Root07438c82012-11-02 15:41:02 -0700332
Riley Spahneaabae92014-06-30 12:39:52 -0700333static char *tctx;
334static int ks_is_selinux_enabled;
335
336static const char *get_perm_label(perm_t perm) {
337 unsigned int index = ffs(perm);
338 if (index > 0 && index <= (sizeof(perm_labels) / sizeof(perm_labels[0]))) {
339 return perm_labels[index - 1];
340 } else {
341 ALOGE("Keystore: Failed to retrieve permission label.\n");
342 abort();
343 }
344}
345
Kenny Root655b9582013-04-04 08:37:42 -0700346/**
347 * Returns the app ID (in the Android multi-user sense) for the current
348 * UNIX UID.
349 */
350static uid_t get_app_id(uid_t uid) {
351 return uid % AID_USER;
352}
353
354/**
355 * Returns the user ID (in the Android multi-user sense) for the current
356 * UNIX UID.
357 */
358static uid_t get_user_id(uid_t uid) {
359 return uid / AID_USER;
360}
361
Chih-Hung Hsieha25b2a32014-09-03 12:14:45 -0700362static bool keystore_selinux_check_access(uid_t /*uid*/, perm_t perm, pid_t spid) {
Riley Spahneaabae92014-06-30 12:39:52 -0700363 if (!ks_is_selinux_enabled) {
364 return true;
365 }
Nick Kralevich66dbf672014-06-30 17:09:14 +0000366
Riley Spahneaabae92014-06-30 12:39:52 -0700367 char *sctx = NULL;
368 const char *selinux_class = "keystore_key";
369 const char *str_perm = get_perm_label(perm);
370
371 if (!str_perm) {
372 return false;
373 }
374
375 if (getpidcon(spid, &sctx) != 0) {
376 ALOGE("SELinux: Failed to get source pid context.\n");
377 return false;
378 }
379
380 bool allowed = selinux_check_access(sctx, tctx, selinux_class, str_perm,
381 NULL) == 0;
382 freecon(sctx);
383 return allowed;
384}
385
386static bool has_permission(uid_t uid, perm_t perm, pid_t spid) {
Kenny Root655b9582013-04-04 08:37:42 -0700387 // All system users are equivalent for multi-user support.
388 if (get_app_id(uid) == AID_SYSTEM) {
389 uid = AID_SYSTEM;
390 }
391
Kenny Root07438c82012-11-02 15:41:02 -0700392 for (size_t i = 0; i < sizeof(user_perms)/sizeof(user_perms[0]); i++) {
393 struct user_perm user = user_perms[i];
394 if (user.uid == uid) {
Riley Spahneaabae92014-06-30 12:39:52 -0700395 return (user.perms & perm) &&
396 keystore_selinux_check_access(uid, perm, spid);
Kenny Root07438c82012-11-02 15:41:02 -0700397 }
398 }
399
Riley Spahneaabae92014-06-30 12:39:52 -0700400 return (DEFAULT_PERMS & perm) &&
401 keystore_selinux_check_access(uid, perm, spid);
Kenny Root07438c82012-11-02 15:41:02 -0700402}
403
Kenny Root49468902013-03-19 13:41:33 -0700404/**
405 * Returns the UID that the callingUid should act as. This is here for
406 * legacy support of the WiFi and VPN systems and should be removed
407 * when WiFi can operate in its own namespace.
408 */
Kenny Root07438c82012-11-02 15:41:02 -0700409static uid_t get_keystore_euid(uid_t uid) {
410 for (size_t i = 0; i < sizeof(user_euids)/sizeof(user_euids[0]); i++) {
411 struct user_euid user = user_euids[i];
412 if (user.uid == uid) {
413 return user.euid;
414 }
415 }
416
417 return uid;
418}
419
Kenny Root49468902013-03-19 13:41:33 -0700420/**
421 * Returns true if the callingUid is allowed to interact in the targetUid's
422 * namespace.
423 */
424static bool is_granted_to(uid_t callingUid, uid_t targetUid) {
Chad Brubaker9489b792015-04-14 11:01:45 -0700425 if (callingUid == targetUid) {
426 return true;
427 }
Kenny Root49468902013-03-19 13:41:33 -0700428 for (size_t i = 0; i < sizeof(user_euids)/sizeof(user_euids[0]); i++) {
429 struct user_euid user = user_euids[i];
430 if (user.euid == callingUid && user.uid == targetUid) {
431 return true;
432 }
433 }
434
435 return false;
436}
437
Kenny Roota91203b2012-02-15 15:00:46 -0800438/* Here is the encoding of keys. This is necessary in order to allow arbitrary
439 * characters in keys. Characters in [0-~] are not encoded. Others are encoded
440 * into two bytes. The first byte is one of [+-.] which represents the first
441 * two bits of the character. The second byte encodes the rest of the bits into
442 * [0-o]. Therefore in the worst case the length of a key gets doubled. Note
443 * that Base64 cannot be used here due to the need of prefix match on keys. */
444
Kenny Root655b9582013-04-04 08:37:42 -0700445static size_t encode_key_length(const android::String8& keyName) {
446 const uint8_t* in = reinterpret_cast<const uint8_t*>(keyName.string());
447 size_t length = keyName.length();
448 for (int i = length; i > 0; --i, ++in) {
449 if (*in < '0' || *in > '~') {
450 ++length;
451 }
452 }
453 return length;
454}
455
Kenny Root07438c82012-11-02 15:41:02 -0700456static int encode_key(char* out, const android::String8& keyName) {
457 const uint8_t* in = reinterpret_cast<const uint8_t*>(keyName.string());
458 size_t length = keyName.length();
Kenny Roota91203b2012-02-15 15:00:46 -0800459 for (int i = length; i > 0; --i, ++in, ++out) {
Kenny Root655b9582013-04-04 08:37:42 -0700460 if (*in < '0' || *in > '~') {
Kenny Roota91203b2012-02-15 15:00:46 -0800461 *out = '+' + (*in >> 6);
462 *++out = '0' + (*in & 0x3F);
463 ++length;
Kenny Root655b9582013-04-04 08:37:42 -0700464 } else {
465 *out = *in;
Kenny Roota91203b2012-02-15 15:00:46 -0800466 }
467 }
468 *out = '\0';
Kenny Root70e3a862012-02-15 17:20:23 -0800469 return length;
470}
471
Kenny Root07438c82012-11-02 15:41:02 -0700472/*
473 * Converts from the "escaped" format on disk to actual name.
474 * This will be smaller than the input string.
475 *
476 * Characters that should combine with the next at the end will be truncated.
477 */
478static size_t decode_key_length(const char* in, size_t length) {
479 size_t outLength = 0;
480
481 for (const char* end = in + length; in < end; in++) {
482 /* This combines with the next character. */
483 if (*in < '0' || *in > '~') {
484 continue;
485 }
486
487 outLength++;
488 }
489 return outLength;
490}
491
492static void decode_key(char* out, const char* in, size_t length) {
493 for (const char* end = in + length; in < end; in++) {
494 if (*in < '0' || *in > '~') {
495 /* Truncate combining characters at the end. */
496 if (in + 1 >= end) {
497 break;
498 }
499
500 *out = (*in++ - '+') << 6;
501 *out++ |= (*in - '0') & 0x3F;
Kenny Roota91203b2012-02-15 15:00:46 -0800502 } else {
Kenny Root07438c82012-11-02 15:41:02 -0700503 *out++ = *in;
Kenny Roota91203b2012-02-15 15:00:46 -0800504 }
505 }
506 *out = '\0';
Kenny Roota91203b2012-02-15 15:00:46 -0800507}
508
509static size_t readFully(int fd, uint8_t* data, size_t size) {
510 size_t remaining = size;
511 while (remaining > 0) {
Kenny Root150ca932012-11-14 14:29:02 -0800512 ssize_t n = TEMP_FAILURE_RETRY(read(fd, data, remaining));
Kenny Root5281edb2012-11-21 15:14:04 -0800513 if (n <= 0) {
Kenny Root150ca932012-11-14 14:29:02 -0800514 return size - remaining;
Kenny Roota91203b2012-02-15 15:00:46 -0800515 }
516 data += n;
517 remaining -= n;
518 }
519 return size;
520}
521
522static size_t writeFully(int fd, uint8_t* data, size_t size) {
523 size_t remaining = size;
524 while (remaining > 0) {
Kenny Root150ca932012-11-14 14:29:02 -0800525 ssize_t n = TEMP_FAILURE_RETRY(write(fd, data, remaining));
526 if (n < 0) {
527 ALOGW("write failed: %s", strerror(errno));
528 return size - remaining;
Kenny Roota91203b2012-02-15 15:00:46 -0800529 }
530 data += n;
531 remaining -= n;
532 }
533 return size;
534}
535
536class Entropy {
537public:
538 Entropy() : mRandom(-1) {}
539 ~Entropy() {
Kenny Root150ca932012-11-14 14:29:02 -0800540 if (mRandom >= 0) {
Kenny Roota91203b2012-02-15 15:00:46 -0800541 close(mRandom);
542 }
543 }
544
545 bool open() {
546 const char* randomDevice = "/dev/urandom";
Kenny Root150ca932012-11-14 14:29:02 -0800547 mRandom = TEMP_FAILURE_RETRY(::open(randomDevice, O_RDONLY));
548 if (mRandom < 0) {
Kenny Roota91203b2012-02-15 15:00:46 -0800549 ALOGE("open: %s: %s", randomDevice, strerror(errno));
550 return false;
551 }
552 return true;
553 }
554
Kenny Root51878182012-03-13 12:53:19 -0700555 bool generate_random_data(uint8_t* data, size_t size) const {
Kenny Roota91203b2012-02-15 15:00:46 -0800556 return (readFully(mRandom, data, size) == size);
557 }
558
559private:
560 int mRandom;
561};
562
563/* Here is the file format. There are two parts in blob.value, the secret and
564 * the description. The secret is stored in ciphertext, and its original size
565 * can be found in blob.length. The description is stored after the secret in
566 * plaintext, and its size is specified in blob.info. The total size of the two
Kenny Root822c3a92012-03-23 16:34:39 -0700567 * parts must be no more than VALUE_SIZE bytes. The first field is the version,
Kenny Rootf9119d62013-04-03 09:22:15 -0700568 * the second is the blob's type, and the third byte is flags. Fields other
Kenny Roota91203b2012-02-15 15:00:46 -0800569 * than blob.info, blob.length, and blob.value are modified by encryptBlob()
570 * and decryptBlob(). Thus they should not be accessed from outside. */
571
Kenny Root822c3a92012-03-23 16:34:39 -0700572/* ** Note to future implementors of encryption: **
573 * Currently this is the construction:
574 * metadata || Enc(MD5(data) || data)
575 *
576 * This should be the construction used for encrypting if re-implementing:
577 *
578 * Derive independent keys for encryption and MAC:
579 * Kenc = AES_encrypt(masterKey, "Encrypt")
580 * Kmac = AES_encrypt(masterKey, "MAC")
581 *
582 * Store this:
583 * metadata || AES_CTR_encrypt(Kenc, rand_IV, data) ||
584 * HMAC(Kmac, metadata || Enc(data))
585 */
Kenny Roota91203b2012-02-15 15:00:46 -0800586struct __attribute__((packed)) blob {
Kenny Root822c3a92012-03-23 16:34:39 -0700587 uint8_t version;
588 uint8_t type;
Kenny Rootf9119d62013-04-03 09:22:15 -0700589 uint8_t flags;
Kenny Roota91203b2012-02-15 15:00:46 -0800590 uint8_t info;
591 uint8_t vector[AES_BLOCK_SIZE];
Kenny Root822c3a92012-03-23 16:34:39 -0700592 uint8_t encrypted[0]; // Marks offset to encrypted data.
Kenny Roota91203b2012-02-15 15:00:46 -0800593 uint8_t digest[MD5_DIGEST_LENGTH];
Kenny Root822c3a92012-03-23 16:34:39 -0700594 uint8_t digested[0]; // Marks offset to digested data.
Kenny Roota91203b2012-02-15 15:00:46 -0800595 int32_t length; // in network byte order when encrypted
596 uint8_t value[VALUE_SIZE + AES_BLOCK_SIZE];
597};
598
Kenny Root822c3a92012-03-23 16:34:39 -0700599typedef enum {
Kenny Rootd53bc922013-03-21 14:10:15 -0700600 TYPE_ANY = 0, // meta type that matches anything
Kenny Root822c3a92012-03-23 16:34:39 -0700601 TYPE_GENERIC = 1,
602 TYPE_MASTER_KEY = 2,
603 TYPE_KEY_PAIR = 3,
Chad Brubaker17d68b92015-02-05 22:04:16 -0800604 TYPE_KEYMASTER_10 = 4,
Kenny Root822c3a92012-03-23 16:34:39 -0700605} BlobType;
606
Kenny Rootf9119d62013-04-03 09:22:15 -0700607static const uint8_t CURRENT_BLOB_VERSION = 2;
Kenny Root822c3a92012-03-23 16:34:39 -0700608
Kenny Roota91203b2012-02-15 15:00:46 -0800609class Blob {
610public:
Chad Brubaker803f37f2015-07-29 13:53:36 -0700611 Blob(const uint8_t* value, size_t valueLength, const uint8_t* info, uint8_t infoLength,
Kenny Root07438c82012-11-02 15:41:02 -0700612 BlobType type) {
Alex Klyubin1773b442015-02-20 12:33:33 -0800613 memset(&mBlob, 0, sizeof(mBlob));
Chad Brubaker54b1e9a2015-08-12 13:40:31 -0700614 if (valueLength > VALUE_SIZE) {
615 valueLength = VALUE_SIZE;
Chad Brubaker803f37f2015-07-29 13:53:36 -0700616 ALOGW("Provided blob length too large");
617 }
Chad Brubaker54b1e9a2015-08-12 13:40:31 -0700618 if (infoLength + valueLength > VALUE_SIZE) {
619 infoLength = VALUE_SIZE - valueLength;
Chad Brubaker803f37f2015-07-29 13:53:36 -0700620 ALOGW("Provided info length too large");
621 }
Kenny Roota91203b2012-02-15 15:00:46 -0800622 mBlob.length = valueLength;
623 memcpy(mBlob.value, value, valueLength);
624
625 mBlob.info = infoLength;
626 memcpy(mBlob.value + valueLength, info, infoLength);
Kenny Root822c3a92012-03-23 16:34:39 -0700627
Kenny Root07438c82012-11-02 15:41:02 -0700628 mBlob.version = CURRENT_BLOB_VERSION;
Kenny Root822c3a92012-03-23 16:34:39 -0700629 mBlob.type = uint8_t(type);
Kenny Rootf9119d62013-04-03 09:22:15 -0700630
Kenny Rootee8068b2013-10-07 09:49:15 -0700631 if (type == TYPE_MASTER_KEY) {
632 mBlob.flags = KEYSTORE_FLAG_ENCRYPTED;
633 } else {
634 mBlob.flags = KEYSTORE_FLAG_NONE;
635 }
Kenny Roota91203b2012-02-15 15:00:46 -0800636 }
637
638 Blob(blob b) {
639 mBlob = b;
640 }
641
Alex Klyubin1773b442015-02-20 12:33:33 -0800642 Blob() {
643 memset(&mBlob, 0, sizeof(mBlob));
644 }
Kenny Roota91203b2012-02-15 15:00:46 -0800645
Kenny Root51878182012-03-13 12:53:19 -0700646 const uint8_t* getValue() const {
Kenny Roota91203b2012-02-15 15:00:46 -0800647 return mBlob.value;
648 }
649
Kenny Root51878182012-03-13 12:53:19 -0700650 int32_t getLength() const {
Kenny Roota91203b2012-02-15 15:00:46 -0800651 return mBlob.length;
652 }
653
Kenny Root51878182012-03-13 12:53:19 -0700654 const uint8_t* getInfo() const {
655 return mBlob.value + mBlob.length;
656 }
657
658 uint8_t getInfoLength() const {
Kenny Roota91203b2012-02-15 15:00:46 -0800659 return mBlob.info;
660 }
661
Kenny Root822c3a92012-03-23 16:34:39 -0700662 uint8_t getVersion() const {
663 return mBlob.version;
664 }
665
Kenny Rootf9119d62013-04-03 09:22:15 -0700666 bool isEncrypted() const {
667 if (mBlob.version < 2) {
668 return true;
669 }
670
671 return mBlob.flags & KEYSTORE_FLAG_ENCRYPTED;
672 }
673
674 void setEncrypted(bool encrypted) {
675 if (encrypted) {
676 mBlob.flags |= KEYSTORE_FLAG_ENCRYPTED;
677 } else {
678 mBlob.flags &= ~KEYSTORE_FLAG_ENCRYPTED;
679 }
680 }
681
Kenny Root17208e02013-09-04 13:56:03 -0700682 bool isFallback() const {
683 return mBlob.flags & KEYSTORE_FLAG_FALLBACK;
684 }
685
686 void setFallback(bool fallback) {
687 if (fallback) {
688 mBlob.flags |= KEYSTORE_FLAG_FALLBACK;
689 } else {
690 mBlob.flags &= ~KEYSTORE_FLAG_FALLBACK;
691 }
692 }
693
Kenny Root822c3a92012-03-23 16:34:39 -0700694 void setVersion(uint8_t version) {
695 mBlob.version = version;
696 }
697
698 BlobType getType() const {
699 return BlobType(mBlob.type);
700 }
701
702 void setType(BlobType type) {
703 mBlob.type = uint8_t(type);
704 }
705
Kenny Rootf9119d62013-04-03 09:22:15 -0700706 ResponseCode writeBlob(const char* filename, AES_KEY *aes_key, State state, Entropy* entropy) {
707 ALOGV("writing blob %s", filename);
708 if (isEncrypted()) {
709 if (state != STATE_NO_ERROR) {
710 ALOGD("couldn't insert encrypted blob while not unlocked");
711 return LOCKED;
712 }
713
714 if (!entropy->generate_random_data(mBlob.vector, AES_BLOCK_SIZE)) {
715 ALOGW("Could not read random data for: %s", filename);
716 return SYSTEM_ERROR;
717 }
Kenny Roota91203b2012-02-15 15:00:46 -0800718 }
719
720 // data includes the value and the value's length
721 size_t dataLength = mBlob.length + sizeof(mBlob.length);
722 // pad data to the AES_BLOCK_SIZE
723 size_t digestedLength = ((dataLength + AES_BLOCK_SIZE - 1)
724 / AES_BLOCK_SIZE * AES_BLOCK_SIZE);
725 // encrypted data includes the digest value
726 size_t encryptedLength = digestedLength + MD5_DIGEST_LENGTH;
727 // move info after space for padding
728 memmove(&mBlob.encrypted[encryptedLength], &mBlob.value[mBlob.length], mBlob.info);
729 // zero padding area
730 memset(mBlob.value + mBlob.length, 0, digestedLength - dataLength);
731
732 mBlob.length = htonl(mBlob.length);
Kenny Roota91203b2012-02-15 15:00:46 -0800733
Kenny Rootf9119d62013-04-03 09:22:15 -0700734 if (isEncrypted()) {
735 MD5(mBlob.digested, digestedLength, mBlob.digest);
Kenny Roota91203b2012-02-15 15:00:46 -0800736
Kenny Rootf9119d62013-04-03 09:22:15 -0700737 uint8_t vector[AES_BLOCK_SIZE];
738 memcpy(vector, mBlob.vector, AES_BLOCK_SIZE);
739 AES_cbc_encrypt(mBlob.encrypted, mBlob.encrypted, encryptedLength,
740 aes_key, vector, AES_ENCRYPT);
741 }
742
Kenny Roota91203b2012-02-15 15:00:46 -0800743 size_t headerLength = (mBlob.encrypted - (uint8_t*) &mBlob);
744 size_t fileLength = encryptedLength + headerLength + mBlob.info;
745
746 const char* tmpFileName = ".tmp";
Kenny Root150ca932012-11-14 14:29:02 -0800747 int out = TEMP_FAILURE_RETRY(open(tmpFileName,
748 O_WRONLY | O_TRUNC | O_CREAT, S_IRUSR | S_IWUSR));
749 if (out < 0) {
750 ALOGW("could not open file: %s: %s", tmpFileName, strerror(errno));
Kenny Roota91203b2012-02-15 15:00:46 -0800751 return SYSTEM_ERROR;
752 }
753 size_t writtenBytes = writeFully(out, (uint8_t*) &mBlob, fileLength);
754 if (close(out) != 0) {
755 return SYSTEM_ERROR;
756 }
757 if (writtenBytes != fileLength) {
Kenny Root150ca932012-11-14 14:29:02 -0800758 ALOGW("blob not fully written %zu != %zu", writtenBytes, fileLength);
Kenny Roota91203b2012-02-15 15:00:46 -0800759 unlink(tmpFileName);
760 return SYSTEM_ERROR;
761 }
Kenny Root150ca932012-11-14 14:29:02 -0800762 if (rename(tmpFileName, filename) == -1) {
763 ALOGW("could not rename blob to %s: %s", filename, strerror(errno));
764 return SYSTEM_ERROR;
765 }
766 return NO_ERROR;
Kenny Roota91203b2012-02-15 15:00:46 -0800767 }
768
Kenny Rootf9119d62013-04-03 09:22:15 -0700769 ResponseCode readBlob(const char* filename, AES_KEY *aes_key, State state) {
770 ALOGV("reading blob %s", filename);
Kenny Root150ca932012-11-14 14:29:02 -0800771 int in = TEMP_FAILURE_RETRY(open(filename, O_RDONLY));
772 if (in < 0) {
Kenny Roota91203b2012-02-15 15:00:46 -0800773 return (errno == ENOENT) ? KEY_NOT_FOUND : SYSTEM_ERROR;
774 }
775 // fileLength may be less than sizeof(mBlob) since the in
776 // memory version has extra padding to tolerate rounding up to
777 // the AES_BLOCK_SIZE
778 size_t fileLength = readFully(in, (uint8_t*) &mBlob, sizeof(mBlob));
779 if (close(in) != 0) {
780 return SYSTEM_ERROR;
781 }
Kenny Rootf9119d62013-04-03 09:22:15 -0700782
Chad Brubakera9a17ee2015-07-17 13:43:24 -0700783 if (fileLength == 0) {
784 return VALUE_CORRUPTED;
785 }
786
Kenny Rootf9119d62013-04-03 09:22:15 -0700787 if (isEncrypted() && (state != STATE_NO_ERROR)) {
788 return LOCKED;
789 }
790
Kenny Roota91203b2012-02-15 15:00:46 -0800791 size_t headerLength = (mBlob.encrypted - (uint8_t*) &mBlob);
792 if (fileLength < headerLength) {
793 return VALUE_CORRUPTED;
794 }
795
796 ssize_t encryptedLength = fileLength - (headerLength + mBlob.info);
Kenny Rootf9119d62013-04-03 09:22:15 -0700797 if (encryptedLength < 0) {
Kenny Roota91203b2012-02-15 15:00:46 -0800798 return VALUE_CORRUPTED;
799 }
Kenny Rootf9119d62013-04-03 09:22:15 -0700800
801 ssize_t digestedLength;
802 if (isEncrypted()) {
803 if (encryptedLength % AES_BLOCK_SIZE != 0) {
804 return VALUE_CORRUPTED;
805 }
806
807 AES_cbc_encrypt(mBlob.encrypted, mBlob.encrypted, encryptedLength, aes_key,
808 mBlob.vector, AES_DECRYPT);
809 digestedLength = encryptedLength - MD5_DIGEST_LENGTH;
810 uint8_t computedDigest[MD5_DIGEST_LENGTH];
811 MD5(mBlob.digested, digestedLength, computedDigest);
812 if (memcmp(mBlob.digest, computedDigest, MD5_DIGEST_LENGTH) != 0) {
813 return VALUE_CORRUPTED;
814 }
815 } else {
816 digestedLength = encryptedLength;
Kenny Roota91203b2012-02-15 15:00:46 -0800817 }
818
819 ssize_t maxValueLength = digestedLength - sizeof(mBlob.length);
820 mBlob.length = ntohl(mBlob.length);
821 if (mBlob.length < 0 || mBlob.length > maxValueLength) {
822 return VALUE_CORRUPTED;
823 }
824 if (mBlob.info != 0) {
825 // move info from after padding to after data
826 memmove(&mBlob.value[mBlob.length], &mBlob.value[maxValueLength], mBlob.info);
827 }
Kenny Root07438c82012-11-02 15:41:02 -0700828 return ::NO_ERROR;
Kenny Roota91203b2012-02-15 15:00:46 -0800829 }
830
831private:
832 struct blob mBlob;
833};
834
Kenny Root655b9582013-04-04 08:37:42 -0700835class UserState {
Kenny Roota91203b2012-02-15 15:00:46 -0800836public:
Kenny Root655b9582013-04-04 08:37:42 -0700837 UserState(uid_t userId) : mUserId(userId), mRetry(MAX_RETRY) {
838 asprintf(&mUserDir, "user_%u", mUserId);
839 asprintf(&mMasterKeyFile, "%s/.masterkey", mUserDir);
840 }
841
842 ~UserState() {
843 free(mUserDir);
844 free(mMasterKeyFile);
845 }
846
847 bool initialize() {
848 if ((mkdir(mUserDir, S_IRUSR | S_IWUSR | S_IXUSR) < 0) && (errno != EEXIST)) {
849 ALOGE("Could not create directory '%s'", mUserDir);
850 return false;
851 }
852
853 if (access(mMasterKeyFile, R_OK) == 0) {
Kenny Roota91203b2012-02-15 15:00:46 -0800854 setState(STATE_LOCKED);
855 } else {
856 setState(STATE_UNINITIALIZED);
857 }
Kenny Root70e3a862012-02-15 17:20:23 -0800858
Kenny Root655b9582013-04-04 08:37:42 -0700859 return true;
860 }
861
862 uid_t getUserId() const {
863 return mUserId;
864 }
865
866 const char* getUserDirName() const {
867 return mUserDir;
868 }
869
870 const char* getMasterKeyFileName() const {
871 return mMasterKeyFile;
872 }
873
874 void setState(State state) {
875 mState = state;
876 if (mState == STATE_NO_ERROR || mState == STATE_UNINITIALIZED) {
877 mRetry = MAX_RETRY;
878 }
Kenny Roota91203b2012-02-15 15:00:46 -0800879 }
880
Kenny Root51878182012-03-13 12:53:19 -0700881 State getState() const {
Kenny Roota91203b2012-02-15 15:00:46 -0800882 return mState;
883 }
884
Kenny Root51878182012-03-13 12:53:19 -0700885 int8_t getRetry() const {
Kenny Roota91203b2012-02-15 15:00:46 -0800886 return mRetry;
887 }
888
Kenny Root655b9582013-04-04 08:37:42 -0700889 void zeroizeMasterKeysInMemory() {
890 memset(mMasterKey, 0, sizeof(mMasterKey));
891 memset(mSalt, 0, sizeof(mSalt));
892 memset(&mMasterKeyEncryption, 0, sizeof(mMasterKeyEncryption));
893 memset(&mMasterKeyDecryption, 0, sizeof(mMasterKeyDecryption));
Kenny Root70e3a862012-02-15 17:20:23 -0800894 }
895
Chad Brubaker96d6d782015-05-07 10:19:40 -0700896 bool deleteMasterKey() {
897 setState(STATE_UNINITIALIZED);
898 zeroizeMasterKeysInMemory();
899 return unlink(mMasterKeyFile) == 0 || errno == ENOENT;
900 }
901
Kenny Root655b9582013-04-04 08:37:42 -0700902 ResponseCode initialize(const android::String8& pw, Entropy* entropy) {
903 if (!generateMasterKey(entropy)) {
Kenny Roota91203b2012-02-15 15:00:46 -0800904 return SYSTEM_ERROR;
905 }
Kenny Root655b9582013-04-04 08:37:42 -0700906 ResponseCode response = writeMasterKey(pw, entropy);
Kenny Roota91203b2012-02-15 15:00:46 -0800907 if (response != NO_ERROR) {
908 return response;
909 }
910 setupMasterKeys();
Kenny Root07438c82012-11-02 15:41:02 -0700911 return ::NO_ERROR;
Kenny Roota91203b2012-02-15 15:00:46 -0800912 }
913
Robin Lee4e865752014-08-19 17:37:55 +0100914 ResponseCode copyMasterKey(UserState* src) {
915 if (mState != STATE_UNINITIALIZED) {
916 return ::SYSTEM_ERROR;
917 }
918 if (src->getState() != STATE_NO_ERROR) {
919 return ::SYSTEM_ERROR;
920 }
921 memcpy(mMasterKey, src->mMasterKey, MASTER_KEY_SIZE_BYTES);
922 setupMasterKeys();
923 return ::NO_ERROR;
924 }
925
Kenny Root655b9582013-04-04 08:37:42 -0700926 ResponseCode writeMasterKey(const android::String8& pw, Entropy* entropy) {
Kenny Roota91203b2012-02-15 15:00:46 -0800927 uint8_t passwordKey[MASTER_KEY_SIZE_BYTES];
928 generateKeyFromPassword(passwordKey, MASTER_KEY_SIZE_BYTES, pw, mSalt);
929 AES_KEY passwordAesKey;
930 AES_set_encrypt_key(passwordKey, MASTER_KEY_SIZE_BITS, &passwordAesKey);
Kenny Root822c3a92012-03-23 16:34:39 -0700931 Blob masterKeyBlob(mMasterKey, sizeof(mMasterKey), mSalt, sizeof(mSalt), TYPE_MASTER_KEY);
Kenny Rootf9119d62013-04-03 09:22:15 -0700932 return masterKeyBlob.writeBlob(mMasterKeyFile, &passwordAesKey, STATE_NO_ERROR, entropy);
Kenny Roota91203b2012-02-15 15:00:46 -0800933 }
934
Kenny Root655b9582013-04-04 08:37:42 -0700935 ResponseCode readMasterKey(const android::String8& pw, Entropy* entropy) {
936 int in = TEMP_FAILURE_RETRY(open(mMasterKeyFile, O_RDONLY));
Kenny Root150ca932012-11-14 14:29:02 -0800937 if (in < 0) {
Kenny Roota91203b2012-02-15 15:00:46 -0800938 return SYSTEM_ERROR;
939 }
940
941 // we read the raw blob to just to get the salt to generate
942 // the AES key, then we create the Blob to use with decryptBlob
943 blob rawBlob;
944 size_t length = readFully(in, (uint8_t*) &rawBlob, sizeof(rawBlob));
945 if (close(in) != 0) {
946 return SYSTEM_ERROR;
947 }
948 // find salt at EOF if present, otherwise we have an old file
949 uint8_t* salt;
950 if (length > SALT_SIZE && rawBlob.info == SALT_SIZE) {
951 salt = (uint8_t*) &rawBlob + length - SALT_SIZE;
952 } else {
953 salt = NULL;
954 }
955 uint8_t passwordKey[MASTER_KEY_SIZE_BYTES];
956 generateKeyFromPassword(passwordKey, MASTER_KEY_SIZE_BYTES, pw, salt);
957 AES_KEY passwordAesKey;
958 AES_set_decrypt_key(passwordKey, MASTER_KEY_SIZE_BITS, &passwordAesKey);
959 Blob masterKeyBlob(rawBlob);
Kenny Rootf9119d62013-04-03 09:22:15 -0700960 ResponseCode response = masterKeyBlob.readBlob(mMasterKeyFile, &passwordAesKey,
961 STATE_NO_ERROR);
Kenny Roota91203b2012-02-15 15:00:46 -0800962 if (response == SYSTEM_ERROR) {
Kenny Rootf9119d62013-04-03 09:22:15 -0700963 return response;
Kenny Roota91203b2012-02-15 15:00:46 -0800964 }
965 if (response == NO_ERROR && masterKeyBlob.getLength() == MASTER_KEY_SIZE_BYTES) {
966 // if salt was missing, generate one and write a new master key file with the salt.
967 if (salt == NULL) {
Kenny Root655b9582013-04-04 08:37:42 -0700968 if (!generateSalt(entropy)) {
Kenny Roota91203b2012-02-15 15:00:46 -0800969 return SYSTEM_ERROR;
970 }
Kenny Root655b9582013-04-04 08:37:42 -0700971 response = writeMasterKey(pw, entropy);
Kenny Roota91203b2012-02-15 15:00:46 -0800972 }
973 if (response == NO_ERROR) {
974 memcpy(mMasterKey, masterKeyBlob.getValue(), MASTER_KEY_SIZE_BYTES);
975 setupMasterKeys();
976 }
977 return response;
978 }
979 if (mRetry <= 0) {
980 reset();
981 return UNINITIALIZED;
982 }
983 --mRetry;
984 switch (mRetry) {
985 case 0: return WRONG_PASSWORD_0;
986 case 1: return WRONG_PASSWORD_1;
987 case 2: return WRONG_PASSWORD_2;
988 case 3: return WRONG_PASSWORD_3;
989 default: return WRONG_PASSWORD_3;
990 }
991 }
992
Kenny Root655b9582013-04-04 08:37:42 -0700993 AES_KEY* getEncryptionKey() {
994 return &mMasterKeyEncryption;
995 }
996
997 AES_KEY* getDecryptionKey() {
998 return &mMasterKeyDecryption;
999 }
1000
Kenny Roota91203b2012-02-15 15:00:46 -08001001 bool reset() {
Kenny Root655b9582013-04-04 08:37:42 -07001002 DIR* dir = opendir(getUserDirName());
Kenny Roota91203b2012-02-15 15:00:46 -08001003 if (!dir) {
Chad Brubaker96d6d782015-05-07 10:19:40 -07001004 // If the directory doesn't exist then nothing to do.
1005 if (errno == ENOENT) {
1006 return true;
1007 }
Kenny Root655b9582013-04-04 08:37:42 -07001008 ALOGW("couldn't open user directory: %s", strerror(errno));
Kenny Roota91203b2012-02-15 15:00:46 -08001009 return false;
1010 }
Kenny Root655b9582013-04-04 08:37:42 -07001011
1012 struct dirent* file;
Kenny Roota91203b2012-02-15 15:00:46 -08001013 while ((file = readdir(dir)) != NULL) {
Chad Brubaker96d6d782015-05-07 10:19:40 -07001014 // skip . and ..
1015 if (!strcmp(".", file->d_name) || !strcmp("..", file->d_name)) {
Kenny Root655b9582013-04-04 08:37:42 -07001016 continue;
1017 }
1018
1019 unlinkat(dirfd(dir), file->d_name, 0);
Kenny Roota91203b2012-02-15 15:00:46 -08001020 }
1021 closedir(dir);
1022 return true;
1023 }
1024
Kenny Root655b9582013-04-04 08:37:42 -07001025private:
1026 static const int MASTER_KEY_SIZE_BYTES = 16;
1027 static const int MASTER_KEY_SIZE_BITS = MASTER_KEY_SIZE_BYTES * 8;
1028
1029 static const int MAX_RETRY = 4;
1030 static const size_t SALT_SIZE = 16;
1031
1032 void generateKeyFromPassword(uint8_t* key, ssize_t keySize, const android::String8& pw,
1033 uint8_t* salt) {
1034 size_t saltSize;
1035 if (salt != NULL) {
1036 saltSize = SALT_SIZE;
1037 } else {
1038 // pre-gingerbread used this hardwired salt, readMasterKey will rewrite these when found
1039 salt = (uint8_t*) "keystore";
1040 // sizeof = 9, not strlen = 8
1041 saltSize = sizeof("keystore");
1042 }
1043
1044 PKCS5_PBKDF2_HMAC_SHA1(reinterpret_cast<const char*>(pw.string()), pw.length(), salt,
1045 saltSize, 8192, keySize, key);
1046 }
1047
1048 bool generateSalt(Entropy* entropy) {
1049 return entropy->generate_random_data(mSalt, sizeof(mSalt));
1050 }
1051
1052 bool generateMasterKey(Entropy* entropy) {
1053 if (!entropy->generate_random_data(mMasterKey, sizeof(mMasterKey))) {
1054 return false;
1055 }
1056 if (!generateSalt(entropy)) {
1057 return false;
1058 }
1059 return true;
1060 }
1061
1062 void setupMasterKeys() {
1063 AES_set_encrypt_key(mMasterKey, MASTER_KEY_SIZE_BITS, &mMasterKeyEncryption);
1064 AES_set_decrypt_key(mMasterKey, MASTER_KEY_SIZE_BITS, &mMasterKeyDecryption);
1065 setState(STATE_NO_ERROR);
1066 }
1067
1068 uid_t mUserId;
1069
1070 char* mUserDir;
1071 char* mMasterKeyFile;
1072
1073 State mState;
1074 int8_t mRetry;
1075
1076 uint8_t mMasterKey[MASTER_KEY_SIZE_BYTES];
1077 uint8_t mSalt[SALT_SIZE];
1078
1079 AES_KEY mMasterKeyEncryption;
1080 AES_KEY mMasterKeyDecryption;
1081};
1082
1083typedef struct {
1084 uint32_t uid;
1085 const uint8_t* filename;
1086} grant_t;
1087
1088class KeyStore {
1089public:
Chad Brubaker67d2a502015-03-11 17:21:18 +00001090 KeyStore(Entropy* entropy, keymaster1_device_t* device, keymaster1_device_t* fallback)
Kenny Root655b9582013-04-04 08:37:42 -07001091 : mEntropy(entropy)
1092 , mDevice(device)
Chad Brubakerfc18edc2015-01-12 15:17:18 -08001093 , mFallbackDevice(fallback)
Kenny Root655b9582013-04-04 08:37:42 -07001094 {
1095 memset(&mMetaData, '\0', sizeof(mMetaData));
1096 }
1097
1098 ~KeyStore() {
1099 for (android::Vector<grant_t*>::iterator it(mGrants.begin());
1100 it != mGrants.end(); it++) {
1101 delete *it;
Kenny Root655b9582013-04-04 08:37:42 -07001102 }
haitao fangc35d4eb2013-12-06 11:34:49 +08001103 mGrants.clear();
Kenny Root655b9582013-04-04 08:37:42 -07001104
1105 for (android::Vector<UserState*>::iterator it(mMasterKeys.begin());
1106 it != mMasterKeys.end(); it++) {
1107 delete *it;
Kenny Root655b9582013-04-04 08:37:42 -07001108 }
haitao fangc35d4eb2013-12-06 11:34:49 +08001109 mMasterKeys.clear();
Kenny Root655b9582013-04-04 08:37:42 -07001110 }
1111
Chad Brubaker67d2a502015-03-11 17:21:18 +00001112 /**
1113 * Depending on the hardware keymaster version is this may return a
1114 * keymaster0_device_t* cast to a keymaster1_device_t*. All methods from
1115 * keymaster0 are safe to call, calls to keymaster1_device_t methods should
1116 * be guarded by a check on the device's version.
1117 */
1118 keymaster1_device_t *getDevice() const {
Kenny Root655b9582013-04-04 08:37:42 -07001119 return mDevice;
1120 }
1121
Chad Brubaker67d2a502015-03-11 17:21:18 +00001122 keymaster1_device_t *getFallbackDevice() const {
Chad Brubakerfc18edc2015-01-12 15:17:18 -08001123 return mFallbackDevice;
1124 }
1125
Chad Brubaker67d2a502015-03-11 17:21:18 +00001126 keymaster1_device_t *getDeviceForBlob(const Blob& blob) const {
Chad Brubakerfc18edc2015-01-12 15:17:18 -08001127 return blob.isFallback() ? mFallbackDevice: mDevice;
1128 }
1129
Kenny Root655b9582013-04-04 08:37:42 -07001130 ResponseCode initialize() {
1131 readMetaData();
1132 if (upgradeKeystore()) {
1133 writeMetaData();
1134 }
1135
1136 return ::NO_ERROR;
1137 }
1138
Chad Brubaker72593ee2015-05-12 10:42:00 -07001139 State getState(uid_t userId) {
1140 return getUserState(userId)->getState();
Kenny Root655b9582013-04-04 08:37:42 -07001141 }
1142
Chad Brubaker72593ee2015-05-12 10:42:00 -07001143 ResponseCode initializeUser(const android::String8& pw, uid_t userId) {
1144 UserState* userState = getUserState(userId);
Kenny Root655b9582013-04-04 08:37:42 -07001145 return userState->initialize(pw, mEntropy);
1146 }
1147
Chad Brubaker72593ee2015-05-12 10:42:00 -07001148 ResponseCode copyMasterKey(uid_t srcUser, uid_t dstUser) {
1149 UserState *userState = getUserState(dstUser);
1150 UserState *initState = getUserState(srcUser);
Robin Lee4e865752014-08-19 17:37:55 +01001151 return userState->copyMasterKey(initState);
1152 }
1153
Chad Brubaker72593ee2015-05-12 10:42:00 -07001154 ResponseCode writeMasterKey(const android::String8& pw, uid_t userId) {
1155 UserState* userState = getUserState(userId);
Kenny Root655b9582013-04-04 08:37:42 -07001156 return userState->writeMasterKey(pw, mEntropy);
1157 }
1158
Chad Brubaker72593ee2015-05-12 10:42:00 -07001159 ResponseCode readMasterKey(const android::String8& pw, uid_t userId) {
1160 UserState* userState = getUserState(userId);
Kenny Root655b9582013-04-04 08:37:42 -07001161 return userState->readMasterKey(pw, mEntropy);
1162 }
1163
1164 android::String8 getKeyName(const android::String8& keyName) {
Douglas Leunga77e8092013-06-13 16:34:43 -07001165 char encoded[encode_key_length(keyName) + 1]; // add 1 for null char
Kenny Root655b9582013-04-04 08:37:42 -07001166 encode_key(encoded, keyName);
1167 return android::String8(encoded);
1168 }
1169
1170 android::String8 getKeyNameForUid(const android::String8& keyName, uid_t uid) {
Douglas Leunga77e8092013-06-13 16:34:43 -07001171 char encoded[encode_key_length(keyName) + 1]; // add 1 for null char
Kenny Root655b9582013-04-04 08:37:42 -07001172 encode_key(encoded, keyName);
1173 return android::String8::format("%u_%s", uid, encoded);
1174 }
1175
1176 android::String8 getKeyNameForUidWithDir(const android::String8& keyName, uid_t uid) {
Douglas Leunga77e8092013-06-13 16:34:43 -07001177 char encoded[encode_key_length(keyName) + 1]; // add 1 for null char
Kenny Root655b9582013-04-04 08:37:42 -07001178 encode_key(encoded, keyName);
Chad Brubaker72593ee2015-05-12 10:42:00 -07001179 return android::String8::format("%s/%u_%s", getUserStateByUid(uid)->getUserDirName(), uid,
Kenny Root655b9582013-04-04 08:37:42 -07001180 encoded);
1181 }
1182
Chad Brubaker96d6d782015-05-07 10:19:40 -07001183 /*
1184 * Delete entries owned by userId. If keepUnencryptedEntries is true
1185 * then only encrypted entries will be removed, otherwise all entries will
1186 * be removed.
1187 */
1188 void resetUser(uid_t userId, bool keepUnenryptedEntries) {
Robin Lee4b84fdc2014-09-24 11:56:57 +01001189 android::String8 prefix("");
1190 android::Vector<android::String16> aliases;
Chad Brubaker72593ee2015-05-12 10:42:00 -07001191 UserState* userState = getUserState(userId);
Chad Brubakere6c3bfa2015-05-12 15:18:26 -07001192 if (list(prefix, &aliases, userId) != ::NO_ERROR) {
Chad Brubaker96d6d782015-05-07 10:19:40 -07001193 return;
1194 }
Robin Lee4b84fdc2014-09-24 11:56:57 +01001195 for (uint32_t i = 0; i < aliases.size(); i++) {
1196 android::String8 filename(aliases[i]);
1197 filename = android::String8::format("%s/%s", userState->getUserDirName(),
Chad Brubaker96d6d782015-05-07 10:19:40 -07001198 getKeyName(filename).string());
1199 bool shouldDelete = true;
1200 if (keepUnenryptedEntries) {
1201 Blob blob;
Chad Brubaker72593ee2015-05-12 10:42:00 -07001202 ResponseCode rc = get(filename, &blob, ::TYPE_ANY, userId);
Robin Lee4b84fdc2014-09-24 11:56:57 +01001203
Chad Brubaker96d6d782015-05-07 10:19:40 -07001204 /* get can fail if the blob is encrypted and the state is
1205 * not unlocked, only skip deleting blobs that were loaded and
1206 * who are not encrypted. If there are blobs we fail to read for
1207 * other reasons err on the safe side and delete them since we
1208 * can't tell if they're encrypted.
1209 */
1210 shouldDelete = !(rc == ::NO_ERROR && !blob.isEncrypted());
1211 }
1212 if (shouldDelete) {
Chad Brubaker72593ee2015-05-12 10:42:00 -07001213 del(filename, ::TYPE_ANY, userId);
Chad Brubaker96d6d782015-05-07 10:19:40 -07001214 }
1215 }
1216 if (!userState->deleteMasterKey()) {
1217 ALOGE("Failed to delete user %d's master key", userId);
1218 }
1219 if (!keepUnenryptedEntries) {
1220 if(!userState->reset()) {
1221 ALOGE("Failed to remove user %d's directory", userId);
1222 }
1223 }
Kenny Root655b9582013-04-04 08:37:42 -07001224 }
1225
Chad Brubaker72593ee2015-05-12 10:42:00 -07001226 bool isEmpty(uid_t userId) const {
1227 const UserState* userState = getUserState(userId);
Chad Brubaker96d6d782015-05-07 10:19:40 -07001228 if (userState == NULL) {
Kenny Root655b9582013-04-04 08:37:42 -07001229 return true;
1230 }
1231
1232 DIR* dir = opendir(userState->getUserDirName());
Kenny Roota91203b2012-02-15 15:00:46 -08001233 if (!dir) {
1234 return true;
1235 }
Kenny Root31e27462014-09-10 11:28:03 -07001236
Kenny Roota91203b2012-02-15 15:00:46 -08001237 bool result = true;
Kenny Root31e27462014-09-10 11:28:03 -07001238 struct dirent* file;
Kenny Roota91203b2012-02-15 15:00:46 -08001239 while ((file = readdir(dir)) != NULL) {
Kenny Root655b9582013-04-04 08:37:42 -07001240 // We only care about files.
1241 if (file->d_type != DT_REG) {
1242 continue;
1243 }
1244
1245 // Skip anything that starts with a "."
1246 if (file->d_name[0] == '.') {
1247 continue;
1248 }
1249
Kenny Root31e27462014-09-10 11:28:03 -07001250 result = false;
1251 break;
Kenny Roota91203b2012-02-15 15:00:46 -08001252 }
1253 closedir(dir);
1254 return result;
1255 }
1256
Chad Brubaker72593ee2015-05-12 10:42:00 -07001257 void lock(uid_t userId) {
1258 UserState* userState = getUserState(userId);
Kenny Root655b9582013-04-04 08:37:42 -07001259 userState->zeroizeMasterKeysInMemory();
1260 userState->setState(STATE_LOCKED);
Kenny Roota91203b2012-02-15 15:00:46 -08001261 }
1262
Chad Brubaker72593ee2015-05-12 10:42:00 -07001263 ResponseCode get(const char* filename, Blob* keyBlob, const BlobType type, uid_t userId) {
1264 UserState* userState = getUserState(userId);
Kenny Rootf9119d62013-04-03 09:22:15 -07001265 ResponseCode rc = keyBlob->readBlob(filename, userState->getDecryptionKey(),
1266 userState->getState());
Kenny Root822c3a92012-03-23 16:34:39 -07001267 if (rc != NO_ERROR) {
1268 return rc;
1269 }
1270
1271 const uint8_t version = keyBlob->getVersion();
Kenny Root07438c82012-11-02 15:41:02 -07001272 if (version < CURRENT_BLOB_VERSION) {
Kenny Rootcfeae072013-04-04 08:39:57 -07001273 /* If we upgrade the key, we need to write it to disk again. Then
1274 * it must be read it again since the blob is encrypted each time
1275 * it's written.
1276 */
Chad Brubaker72593ee2015-05-12 10:42:00 -07001277 if (upgradeBlob(filename, keyBlob, version, type, userId)) {
1278 if ((rc = this->put(filename, keyBlob, userId)) != NO_ERROR
Kenny Rootf9119d62013-04-03 09:22:15 -07001279 || (rc = keyBlob->readBlob(filename, userState->getDecryptionKey(),
1280 userState->getState())) != NO_ERROR) {
Kenny Rootcfeae072013-04-04 08:39:57 -07001281 return rc;
1282 }
1283 }
Kenny Root822c3a92012-03-23 16:34:39 -07001284 }
1285
Kenny Root17208e02013-09-04 13:56:03 -07001286 /*
1287 * This will upgrade software-backed keys to hardware-backed keys when
1288 * the HAL for the device supports the newer key types.
1289 */
1290 if (rc == NO_ERROR && type == TYPE_KEY_PAIR
1291 && mDevice->common.module->module_api_version >= KEYMASTER_MODULE_API_VERSION_0_2
1292 && keyBlob->isFallback()) {
1293 ResponseCode imported = importKey(keyBlob->getValue(), keyBlob->getLength(), filename,
Chad Brubaker72593ee2015-05-12 10:42:00 -07001294 userId, keyBlob->isEncrypted() ? KEYSTORE_FLAG_ENCRYPTED : KEYSTORE_FLAG_NONE);
Kenny Root17208e02013-09-04 13:56:03 -07001295
1296 // The HAL allowed the import, reget the key to have the "fresh"
1297 // version.
1298 if (imported == NO_ERROR) {
Chad Brubaker72593ee2015-05-12 10:42:00 -07001299 rc = get(filename, keyBlob, TYPE_KEY_PAIR, userId);
Kenny Root17208e02013-09-04 13:56:03 -07001300 }
1301 }
1302
Chad Brubaker3a7d9e62015-06-04 15:01:46 -07001303 // Keymaster 0.3 keys are valid keymaster 1.0 keys, so silently upgrade.
1304 if (keyBlob->getType() == TYPE_KEY_PAIR) {
Chad Brubaker3cc40122015-06-04 13:49:44 -07001305 keyBlob->setType(TYPE_KEYMASTER_10);
Chad Brubaker3a7d9e62015-06-04 15:01:46 -07001306 rc = this->put(filename, keyBlob, userId);
Chad Brubaker3cc40122015-06-04 13:49:44 -07001307 }
1308
Kenny Rootd53bc922013-03-21 14:10:15 -07001309 if (type != TYPE_ANY && keyBlob->getType() != type) {
Kenny Root822c3a92012-03-23 16:34:39 -07001310 ALOGW("key found but type doesn't match: %d vs %d", keyBlob->getType(), type);
1311 return KEY_NOT_FOUND;
1312 }
1313
1314 return rc;
Kenny Roota91203b2012-02-15 15:00:46 -08001315 }
1316
Chad Brubaker72593ee2015-05-12 10:42:00 -07001317 ResponseCode put(const char* filename, Blob* keyBlob, uid_t userId) {
1318 UserState* userState = getUserState(userId);
Kenny Rootf9119d62013-04-03 09:22:15 -07001319 return keyBlob->writeBlob(filename, userState->getEncryptionKey(), userState->getState(),
1320 mEntropy);
Kenny Roota91203b2012-02-15 15:00:46 -08001321 }
1322
Chad Brubaker72593ee2015-05-12 10:42:00 -07001323 ResponseCode del(const char *filename, const BlobType type, uid_t userId) {
Robin Lee4b84fdc2014-09-24 11:56:57 +01001324 Blob keyBlob;
Chad Brubaker72593ee2015-05-12 10:42:00 -07001325 ResponseCode rc = get(filename, &keyBlob, type, userId);
Chad Brubakera9a17ee2015-07-17 13:43:24 -07001326 if (rc == ::VALUE_CORRUPTED) {
1327 // The file is corrupt, the best we can do is rm it.
1328 return (unlink(filename) && errno != ENOENT) ? ::SYSTEM_ERROR : ::NO_ERROR;
1329 }
Robin Lee4b84fdc2014-09-24 11:56:57 +01001330 if (rc != ::NO_ERROR) {
1331 return rc;
1332 }
1333
1334 if (keyBlob.getType() == ::TYPE_KEY_PAIR) {
Shawn Willden55268b52015-07-28 11:06:00 -06001335 // A device doesn't have to implement delete_key.
1336 if (mDevice->delete_key != NULL && !keyBlob.isFallback()) {
1337 keymaster_key_blob_t blob = {keyBlob.getValue(),
1338 static_cast<size_t>(keyBlob.getLength())};
1339 if (mDevice->delete_key(mDevice, &blob)) {
Robin Lee4b84fdc2014-09-24 11:56:57 +01001340 rc = ::SYSTEM_ERROR;
1341 }
1342 }
1343 }
Chad Brubaker17d68b92015-02-05 22:04:16 -08001344 if (keyBlob.getType() == ::TYPE_KEYMASTER_10) {
1345 keymaster1_device_t* dev = getDeviceForBlob(keyBlob);
1346 if (dev->delete_key) {
1347 keymaster_key_blob_t blob;
1348 blob.key_material = keyBlob.getValue();
1349 blob.key_material_size = keyBlob.getLength();
1350 dev->delete_key(dev, &blob);
1351 }
1352 }
Robin Lee4b84fdc2014-09-24 11:56:57 +01001353 if (rc != ::NO_ERROR) {
1354 return rc;
1355 }
1356
1357 return (unlink(filename) && errno != ENOENT) ? ::SYSTEM_ERROR : ::NO_ERROR;
1358 }
1359
Chad Brubakere6c3bfa2015-05-12 15:18:26 -07001360 ResponseCode list(const android::String8& prefix, android::Vector<android::String16> *matches,
Chad Brubaker72593ee2015-05-12 10:42:00 -07001361 uid_t userId) {
Robin Lee4b84fdc2014-09-24 11:56:57 +01001362
Chad Brubaker72593ee2015-05-12 10:42:00 -07001363 UserState* userState = getUserState(userId);
Robin Lee4b84fdc2014-09-24 11:56:57 +01001364 size_t n = prefix.length();
1365
1366 DIR* dir = opendir(userState->getUserDirName());
1367 if (!dir) {
1368 ALOGW("can't open directory for user: %s", strerror(errno));
1369 return ::SYSTEM_ERROR;
1370 }
1371
1372 struct dirent* file;
1373 while ((file = readdir(dir)) != NULL) {
1374 // We only care about files.
1375 if (file->d_type != DT_REG) {
1376 continue;
1377 }
1378
1379 // Skip anything that starts with a "."
1380 if (file->d_name[0] == '.') {
1381 continue;
1382 }
1383
1384 if (!strncmp(prefix.string(), file->d_name, n)) {
1385 const char* p = &file->d_name[n];
1386 size_t plen = strlen(p);
1387
1388 size_t extra = decode_key_length(p, plen);
1389 char *match = (char*) malloc(extra + 1);
1390 if (match != NULL) {
1391 decode_key(match, p, plen);
1392 matches->push(android::String16(match, extra));
1393 free(match);
1394 } else {
1395 ALOGW("could not allocate match of size %zd", extra);
1396 }
1397 }
1398 }
1399 closedir(dir);
1400 return ::NO_ERROR;
1401 }
1402
Kenny Root07438c82012-11-02 15:41:02 -07001403 void addGrant(const char* filename, uid_t granteeUid) {
Kenny Root655b9582013-04-04 08:37:42 -07001404 const grant_t* existing = getGrant(filename, granteeUid);
1405 if (existing == NULL) {
1406 grant_t* grant = new grant_t;
Kenny Root07438c82012-11-02 15:41:02 -07001407 grant->uid = granteeUid;
Brian Carlstroma8c703d2012-07-17 14:43:46 -07001408 grant->filename = reinterpret_cast<const uint8_t*>(strdup(filename));
Kenny Root655b9582013-04-04 08:37:42 -07001409 mGrants.add(grant);
Kenny Root70e3a862012-02-15 17:20:23 -08001410 }
1411 }
1412
Kenny Root07438c82012-11-02 15:41:02 -07001413 bool removeGrant(const char* filename, uid_t granteeUid) {
Kenny Root655b9582013-04-04 08:37:42 -07001414 for (android::Vector<grant_t*>::iterator it(mGrants.begin());
1415 it != mGrants.end(); it++) {
1416 grant_t* grant = *it;
1417 if (grant->uid == granteeUid
1418 && !strcmp(reinterpret_cast<const char*>(grant->filename), filename)) {
1419 mGrants.erase(it);
1420 return true;
1421 }
Kenny Root70e3a862012-02-15 17:20:23 -08001422 }
Kenny Root70e3a862012-02-15 17:20:23 -08001423 return false;
1424 }
1425
Brian Carlstroma8c703d2012-07-17 14:43:46 -07001426 bool hasGrant(const char* filename, const uid_t uid) const {
1427 return getGrant(filename, uid) != NULL;
Kenny Root70e3a862012-02-15 17:20:23 -08001428 }
1429
Chad Brubaker72593ee2015-05-12 10:42:00 -07001430 ResponseCode importKey(const uint8_t* key, size_t keyLen, const char* filename, uid_t userId,
Kenny Rootf9119d62013-04-03 09:22:15 -07001431 int32_t flags) {
Shawn Willden55268b52015-07-28 11:06:00 -06001432 Unique_PKCS8_PRIV_KEY_INFO pkcs8(d2i_PKCS8_PRIV_KEY_INFO(NULL, &key, keyLen));
1433 if (!pkcs8.get()) {
1434 return ::SYSTEM_ERROR;
1435 }
1436 Unique_EVP_PKEY pkey(EVP_PKCS82PKEY(pkcs8.get()));
1437 if (!pkey.get()) {
1438 return ::SYSTEM_ERROR;
1439 }
1440 int type = EVP_PKEY_type(pkey->type);
1441 android::KeymasterArguments params;
1442 add_legacy_key_authorizations(type, &params.params);
1443 switch (type) {
1444 case EVP_PKEY_RSA:
1445 params.params.push_back(keymaster_param_enum(KM_TAG_ALGORITHM, KM_ALGORITHM_RSA));
1446 break;
1447 case EVP_PKEY_EC:
1448 params.params.push_back(keymaster_param_enum(KM_TAG_ALGORITHM,
1449 KM_ALGORITHM_EC));
1450 break;
1451 default:
1452 ALOGW("Unsupported key type %d", type);
1453 return ::SYSTEM_ERROR;
Kenny Root822c3a92012-03-23 16:34:39 -07001454 }
1455
Shawn Willden55268b52015-07-28 11:06:00 -06001456 std::vector<keymaster_key_param_t> opParams(params.params);
1457 const keymaster_key_param_set_t inParams = {opParams.data(), opParams.size()};
1458 keymaster_blob_t input = {key, keyLen};
1459 keymaster_key_blob_t blob = {nullptr, 0};
Kenny Root17208e02013-09-04 13:56:03 -07001460 bool isFallback = false;
Shawn Willden55268b52015-07-28 11:06:00 -06001461 keymaster_error_t error = mDevice->import_key(mDevice, &inParams, KM_KEY_FORMAT_PKCS8,
1462 &input, &blob, NULL /* characteristics */);
1463 if (error != KM_ERROR_OK){
1464 ALOGE("Keymaster error %d importing key pair, falling back", error);
1465
Kenny Roota39da5a2014-09-25 13:07:24 -07001466 /*
Shawn Willden55268b52015-07-28 11:06:00 -06001467 * There should be no way to get here. Fallback shouldn't ever really happen
1468 * because the main device may be many (SW, KM0/SW hybrid, KM1/SW hybrid), but it must
1469 * provide full support of the API. In any case, we'll do the fallback just for
1470 * consistency... and I suppose to cover for broken HW implementations.
Kenny Roota39da5a2014-09-25 13:07:24 -07001471 */
Shawn Willden55268b52015-07-28 11:06:00 -06001472 error = mFallbackDevice->import_key(mFallbackDevice, &inParams, KM_KEY_FORMAT_PKCS8,
1473 &input, &blob, NULL /* characteristics */);
Kenny Roota39da5a2014-09-25 13:07:24 -07001474 isFallback = true;
Kenny Root17208e02013-09-04 13:56:03 -07001475
Shawn Willden55268b52015-07-28 11:06:00 -06001476 if (error) {
1477 ALOGE("Keymaster error while importing key pair with fallback: %d", error);
Kenny Root17208e02013-09-04 13:56:03 -07001478 return SYSTEM_ERROR;
1479 }
Kenny Root822c3a92012-03-23 16:34:39 -07001480 }
1481
Shawn Willden55268b52015-07-28 11:06:00 -06001482 Blob keyBlob(blob.key_material, blob.key_material_size, NULL, 0, TYPE_KEYMASTER_10);
1483 free(const_cast<uint8_t*>(blob.key_material));
Kenny Root822c3a92012-03-23 16:34:39 -07001484
Kenny Rootf9119d62013-04-03 09:22:15 -07001485 keyBlob.setEncrypted(flags & KEYSTORE_FLAG_ENCRYPTED);
Kenny Root17208e02013-09-04 13:56:03 -07001486 keyBlob.setFallback(isFallback);
Kenny Rootf9119d62013-04-03 09:22:15 -07001487
Chad Brubaker72593ee2015-05-12 10:42:00 -07001488 return put(filename, &keyBlob, userId);
Kenny Root822c3a92012-03-23 16:34:39 -07001489 }
1490
Kenny Root1b0e3932013-09-05 13:06:32 -07001491 bool isHardwareBacked(const android::String16& keyType) const {
1492 if (mDevice == NULL) {
1493 ALOGW("can't get keymaster device");
1494 return false;
1495 }
1496
1497 if (sRSAKeyType == keyType) {
1498 return (mDevice->flags & KEYMASTER_SOFTWARE_ONLY) == 0;
1499 } else {
1500 return (mDevice->flags & KEYMASTER_SOFTWARE_ONLY) == 0
1501 && (mDevice->common.module->module_api_version
1502 >= KEYMASTER_MODULE_API_VERSION_0_2);
1503 }
Kenny Root8ddf35a2013-03-29 11:15:50 -07001504 }
1505
Kenny Root655b9582013-04-04 08:37:42 -07001506 ResponseCode getKeyForName(Blob* keyBlob, const android::String8& keyName, const uid_t uid,
1507 const BlobType type) {
Kenny Root86b16e82013-09-09 11:15:54 -07001508 android::String8 filepath8(getKeyNameForUidWithDir(keyName, uid));
Chad Brubaker72593ee2015-05-12 10:42:00 -07001509 uid_t userId = get_user_id(uid);
Kenny Root655b9582013-04-04 08:37:42 -07001510
Chad Brubaker72593ee2015-05-12 10:42:00 -07001511 ResponseCode responseCode = get(filepath8.string(), keyBlob, type, userId);
Kenny Root655b9582013-04-04 08:37:42 -07001512 if (responseCode == NO_ERROR) {
1513 return responseCode;
1514 }
1515
1516 // If this is one of the legacy UID->UID mappings, use it.
1517 uid_t euid = get_keystore_euid(uid);
1518 if (euid != uid) {
Kenny Root86b16e82013-09-09 11:15:54 -07001519 filepath8 = getKeyNameForUidWithDir(keyName, euid);
Chad Brubaker72593ee2015-05-12 10:42:00 -07001520 responseCode = get(filepath8.string(), keyBlob, type, userId);
Kenny Root655b9582013-04-04 08:37:42 -07001521 if (responseCode == NO_ERROR) {
1522 return responseCode;
1523 }
1524 }
1525
1526 // They might be using a granted key.
Kenny Root86b16e82013-09-09 11:15:54 -07001527 android::String8 filename8 = getKeyName(keyName);
Kenny Root655b9582013-04-04 08:37:42 -07001528 char* end;
Kenny Root86b16e82013-09-09 11:15:54 -07001529 strtoul(filename8.string(), &end, 10);
Kenny Root655b9582013-04-04 08:37:42 -07001530 if (end[0] != '_' || end[1] == 0) {
1531 return KEY_NOT_FOUND;
1532 }
Chad Brubaker72593ee2015-05-12 10:42:00 -07001533 filepath8 = android::String8::format("%s/%s", getUserState(userId)->getUserDirName(),
Kenny Root86b16e82013-09-09 11:15:54 -07001534 filename8.string());
Kenny Root655b9582013-04-04 08:37:42 -07001535 if (!hasGrant(filepath8.string(), uid)) {
1536 return responseCode;
1537 }
1538
1539 // It is a granted key. Try to load it.
Chad Brubaker72593ee2015-05-12 10:42:00 -07001540 return get(filepath8.string(), keyBlob, type, userId);
Kenny Root655b9582013-04-04 08:37:42 -07001541 }
1542
1543 /**
1544 * Returns any existing UserState or creates it if it doesn't exist.
1545 */
Chad Brubaker72593ee2015-05-12 10:42:00 -07001546 UserState* getUserState(uid_t userId) {
Kenny Root655b9582013-04-04 08:37:42 -07001547 for (android::Vector<UserState*>::iterator it(mMasterKeys.begin());
1548 it != mMasterKeys.end(); it++) {
1549 UserState* state = *it;
1550 if (state->getUserId() == userId) {
1551 return state;
1552 }
1553 }
1554
1555 UserState* userState = new UserState(userId);
1556 if (!userState->initialize()) {
1557 /* There's not much we can do if initialization fails. Trying to
1558 * unlock the keystore for that user will fail as well, so any
1559 * subsequent request for this user will just return SYSTEM_ERROR.
1560 */
1561 ALOGE("User initialization failed for %u; subsuquent operations will fail", userId);
1562 }
1563 mMasterKeys.add(userState);
1564 return userState;
1565 }
1566
1567 /**
Chad Brubaker72593ee2015-05-12 10:42:00 -07001568 * Returns any existing UserState or creates it if it doesn't exist.
1569 */
1570 UserState* getUserStateByUid(uid_t uid) {
1571 uid_t userId = get_user_id(uid);
1572 return getUserState(userId);
1573 }
1574
1575 /**
Kenny Root655b9582013-04-04 08:37:42 -07001576 * Returns NULL if the UserState doesn't already exist.
1577 */
Chad Brubaker72593ee2015-05-12 10:42:00 -07001578 const UserState* getUserState(uid_t userId) const {
Kenny Root655b9582013-04-04 08:37:42 -07001579 for (android::Vector<UserState*>::const_iterator it(mMasterKeys.begin());
1580 it != mMasterKeys.end(); it++) {
1581 UserState* state = *it;
1582 if (state->getUserId() == userId) {
1583 return state;
1584 }
1585 }
1586
1587 return NULL;
1588 }
1589
Chad Brubaker72593ee2015-05-12 10:42:00 -07001590 /**
1591 * Returns NULL if the UserState doesn't already exist.
1592 */
1593 const UserState* getUserStateByUid(uid_t uid) const {
1594 uid_t userId = get_user_id(uid);
1595 return getUserState(userId);
1596 }
1597
Kenny Roota91203b2012-02-15 15:00:46 -08001598private:
Kenny Root655b9582013-04-04 08:37:42 -07001599 static const char* sOldMasterKey;
1600 static const char* sMetaDataFile;
Kenny Root1b0e3932013-09-05 13:06:32 -07001601 static const android::String16 sRSAKeyType;
Kenny Roota91203b2012-02-15 15:00:46 -08001602 Entropy* mEntropy;
1603
Chad Brubaker67d2a502015-03-11 17:21:18 +00001604 keymaster1_device_t* mDevice;
1605 keymaster1_device_t* mFallbackDevice;
Kenny Root70e3a862012-02-15 17:20:23 -08001606
Kenny Root655b9582013-04-04 08:37:42 -07001607 android::Vector<UserState*> mMasterKeys;
Kenny Roota91203b2012-02-15 15:00:46 -08001608
Kenny Root655b9582013-04-04 08:37:42 -07001609 android::Vector<grant_t*> mGrants;
Kenny Roota91203b2012-02-15 15:00:46 -08001610
Kenny Root655b9582013-04-04 08:37:42 -07001611 typedef struct {
1612 uint32_t version;
1613 } keystore_metadata_t;
Kenny Roota91203b2012-02-15 15:00:46 -08001614
Kenny Root655b9582013-04-04 08:37:42 -07001615 keystore_metadata_t mMetaData;
Kenny Root70e3a862012-02-15 17:20:23 -08001616
Kenny Root655b9582013-04-04 08:37:42 -07001617 const grant_t* getGrant(const char* filename, uid_t uid) const {
1618 for (android::Vector<grant_t*>::const_iterator it(mGrants.begin());
1619 it != mGrants.end(); it++) {
1620 grant_t* grant = *it;
Kenny Root70e3a862012-02-15 17:20:23 -08001621 if (grant->uid == uid
Kenny Root655b9582013-04-04 08:37:42 -07001622 && !strcmp(reinterpret_cast<const char*>(grant->filename), filename)) {
Kenny Root70e3a862012-02-15 17:20:23 -08001623 return grant;
1624 }
1625 }
Kenny Root70e3a862012-02-15 17:20:23 -08001626 return NULL;
1627 }
1628
Kenny Root822c3a92012-03-23 16:34:39 -07001629 /**
1630 * Upgrade code. This will upgrade the key from the current version
1631 * to whatever is newest.
1632 */
Kenny Root655b9582013-04-04 08:37:42 -07001633 bool upgradeBlob(const char* filename, Blob* blob, const uint8_t oldVersion,
1634 const BlobType type, uid_t uid) {
Kenny Root822c3a92012-03-23 16:34:39 -07001635 bool updated = false;
1636 uint8_t version = oldVersion;
1637
1638 /* From V0 -> V1: All old types were unknown */
1639 if (version == 0) {
1640 ALOGV("upgrading to version 1 and setting type %d", type);
1641
1642 blob->setType(type);
1643 if (type == TYPE_KEY_PAIR) {
Kenny Root655b9582013-04-04 08:37:42 -07001644 importBlobAsKey(blob, filename, uid);
Kenny Root822c3a92012-03-23 16:34:39 -07001645 }
1646 version = 1;
1647 updated = true;
1648 }
1649
Kenny Rootf9119d62013-04-03 09:22:15 -07001650 /* From V1 -> V2: All old keys were encrypted */
1651 if (version == 1) {
1652 ALOGV("upgrading to version 2");
1653
1654 blob->setEncrypted(true);
1655 version = 2;
1656 updated = true;
1657 }
1658
Kenny Root822c3a92012-03-23 16:34:39 -07001659 /*
1660 * If we've updated, set the key blob to the right version
1661 * and write it.
Kenny Rootcfeae072013-04-04 08:39:57 -07001662 */
Kenny Root822c3a92012-03-23 16:34:39 -07001663 if (updated) {
1664 ALOGV("updated and writing file %s", filename);
1665 blob->setVersion(version);
Kenny Root822c3a92012-03-23 16:34:39 -07001666 }
Kenny Rootcfeae072013-04-04 08:39:57 -07001667
1668 return updated;
Kenny Root822c3a92012-03-23 16:34:39 -07001669 }
1670
1671 /**
1672 * Takes a blob that is an PEM-encoded RSA key as a byte array and
1673 * converts it to a DER-encoded PKCS#8 for import into a keymaster.
1674 * Then it overwrites the original blob with the new blob
1675 * format that is returned from the keymaster.
1676 */
Kenny Root655b9582013-04-04 08:37:42 -07001677 ResponseCode importBlobAsKey(Blob* blob, const char* filename, uid_t uid) {
Kenny Root822c3a92012-03-23 16:34:39 -07001678 // We won't even write to the blob directly with this BIO, so const_cast is okay.
1679 Unique_BIO b(BIO_new_mem_buf(const_cast<uint8_t*>(blob->getValue()), blob->getLength()));
1680 if (b.get() == NULL) {
1681 ALOGE("Problem instantiating BIO");
1682 return SYSTEM_ERROR;
1683 }
1684
1685 Unique_EVP_PKEY pkey(PEM_read_bio_PrivateKey(b.get(), NULL, NULL, NULL));
1686 if (pkey.get() == NULL) {
1687 ALOGE("Couldn't read old PEM file");
1688 return SYSTEM_ERROR;
1689 }
1690
1691 Unique_PKCS8_PRIV_KEY_INFO pkcs8(EVP_PKEY2PKCS8(pkey.get()));
1692 int len = i2d_PKCS8_PRIV_KEY_INFO(pkcs8.get(), NULL);
1693 if (len < 0) {
1694 ALOGE("Couldn't measure PKCS#8 length");
1695 return SYSTEM_ERROR;
1696 }
1697
Kenny Root70c98892013-02-07 09:10:36 -08001698 UniquePtr<unsigned char[]> pkcs8key(new unsigned char[len]);
1699 uint8_t* tmp = pkcs8key.get();
Kenny Root822c3a92012-03-23 16:34:39 -07001700 if (i2d_PKCS8_PRIV_KEY_INFO(pkcs8.get(), &tmp) != len) {
1701 ALOGE("Couldn't convert to PKCS#8");
1702 return SYSTEM_ERROR;
1703 }
1704
Chad Brubaker72593ee2015-05-12 10:42:00 -07001705 ResponseCode rc = importKey(pkcs8key.get(), len, filename, get_user_id(uid),
Kenny Rootf9119d62013-04-03 09:22:15 -07001706 blob->isEncrypted() ? KEYSTORE_FLAG_ENCRYPTED : KEYSTORE_FLAG_NONE);
Kenny Root822c3a92012-03-23 16:34:39 -07001707 if (rc != NO_ERROR) {
1708 return rc;
1709 }
1710
Kenny Root655b9582013-04-04 08:37:42 -07001711 return get(filename, blob, TYPE_KEY_PAIR, uid);
1712 }
1713
1714 void readMetaData() {
1715 int in = TEMP_FAILURE_RETRY(open(sMetaDataFile, O_RDONLY));
1716 if (in < 0) {
1717 return;
1718 }
1719 size_t fileLength = readFully(in, (uint8_t*) &mMetaData, sizeof(mMetaData));
1720 if (fileLength != sizeof(mMetaData)) {
1721 ALOGI("Metadata file is %zd bytes (%zd experted); upgrade?", fileLength,
1722 sizeof(mMetaData));
1723 }
1724 close(in);
1725 }
1726
1727 void writeMetaData() {
1728 const char* tmpFileName = ".metadata.tmp";
1729 int out = TEMP_FAILURE_RETRY(open(tmpFileName,
1730 O_WRONLY | O_TRUNC | O_CREAT, S_IRUSR | S_IWUSR));
1731 if (out < 0) {
1732 ALOGE("couldn't write metadata file: %s", strerror(errno));
1733 return;
1734 }
1735 size_t fileLength = writeFully(out, (uint8_t*) &mMetaData, sizeof(mMetaData));
1736 if (fileLength != sizeof(mMetaData)) {
1737 ALOGI("Could only write %zd bytes to metadata file (%zd expected)", fileLength,
1738 sizeof(mMetaData));
1739 }
1740 close(out);
1741 rename(tmpFileName, sMetaDataFile);
1742 }
1743
1744 bool upgradeKeystore() {
1745 bool upgraded = false;
1746
1747 if (mMetaData.version == 0) {
Chad Brubaker72593ee2015-05-12 10:42:00 -07001748 UserState* userState = getUserStateByUid(0);
Kenny Root655b9582013-04-04 08:37:42 -07001749
1750 // Initialize first so the directory is made.
1751 userState->initialize();
1752
1753 // Migrate the old .masterkey file to user 0.
1754 if (access(sOldMasterKey, R_OK) == 0) {
1755 if (rename(sOldMasterKey, userState->getMasterKeyFileName()) < 0) {
1756 ALOGE("couldn't migrate old masterkey: %s", strerror(errno));
1757 return false;
1758 }
1759 }
1760
1761 // Initialize again in case we had a key.
1762 userState->initialize();
1763
1764 // Try to migrate existing keys.
1765 DIR* dir = opendir(".");
1766 if (!dir) {
1767 // Give up now; maybe we can upgrade later.
1768 ALOGE("couldn't open keystore's directory; something is wrong");
1769 return false;
1770 }
1771
1772 struct dirent* file;
1773 while ((file = readdir(dir)) != NULL) {
1774 // We only care about files.
1775 if (file->d_type != DT_REG) {
1776 continue;
1777 }
1778
1779 // Skip anything that starts with a "."
1780 if (file->d_name[0] == '.') {
1781 continue;
1782 }
1783
1784 // Find the current file's user.
1785 char* end;
1786 unsigned long thisUid = strtoul(file->d_name, &end, 10);
1787 if (end[0] != '_' || end[1] == 0) {
1788 continue;
1789 }
Chad Brubaker72593ee2015-05-12 10:42:00 -07001790 UserState* otherUser = getUserStateByUid(thisUid);
Kenny Root655b9582013-04-04 08:37:42 -07001791 if (otherUser->getUserId() != 0) {
1792 unlinkat(dirfd(dir), file->d_name, 0);
1793 }
1794
1795 // Rename the file into user directory.
1796 DIR* otherdir = opendir(otherUser->getUserDirName());
1797 if (otherdir == NULL) {
1798 ALOGW("couldn't open user directory for rename");
1799 continue;
1800 }
1801 if (renameat(dirfd(dir), file->d_name, dirfd(otherdir), file->d_name) < 0) {
1802 ALOGW("couldn't rename blob: %s: %s", file->d_name, strerror(errno));
1803 }
1804 closedir(otherdir);
1805 }
1806 closedir(dir);
1807
1808 mMetaData.version = 1;
1809 upgraded = true;
1810 }
1811
1812 return upgraded;
Kenny Root822c3a92012-03-23 16:34:39 -07001813 }
Kenny Roota91203b2012-02-15 15:00:46 -08001814};
1815
Kenny Root655b9582013-04-04 08:37:42 -07001816const char* KeyStore::sOldMasterKey = ".masterkey";
1817const char* KeyStore::sMetaDataFile = ".metadata";
Kenny Root70e3a862012-02-15 17:20:23 -08001818
Kenny Root1b0e3932013-09-05 13:06:32 -07001819const android::String16 KeyStore::sRSAKeyType("RSA");
1820
Kenny Root07438c82012-11-02 15:41:02 -07001821namespace android {
1822class KeyStoreProxy : public BnKeystoreService, public IBinder::DeathRecipient {
1823public:
1824 KeyStoreProxy(KeyStore* keyStore)
Chad Brubaker40a1a9b2015-02-20 14:08:13 -08001825 : mKeyStore(keyStore),
1826 mOperationMap(this)
Kenny Root07438c82012-11-02 15:41:02 -07001827 {
Kenny Roota91203b2012-02-15 15:00:46 -08001828 }
Kenny Roota91203b2012-02-15 15:00:46 -08001829
Chad Brubaker40a1a9b2015-02-20 14:08:13 -08001830 void binderDied(const wp<IBinder>& who) {
1831 auto operations = mOperationMap.getOperationsForToken(who.unsafe_get());
1832 for (auto token: operations) {
1833 abort(token);
1834 }
Kenny Root822c3a92012-03-23 16:34:39 -07001835 }
Kenny Roota91203b2012-02-15 15:00:46 -08001836
Chad Brubakere6c3bfa2015-05-12 15:18:26 -07001837 int32_t getState(int32_t userId) {
1838 if (!checkBinderPermission(P_GET_STATE)) {
Kenny Root07438c82012-11-02 15:41:02 -07001839 return ::PERMISSION_DENIED;
Kenny Roota91203b2012-02-15 15:00:46 -08001840 }
Kenny Roota91203b2012-02-15 15:00:46 -08001841
Chad Brubakere6c3bfa2015-05-12 15:18:26 -07001842 return mKeyStore->getState(userId);
Kenny Root298e7b12012-03-26 13:54:44 -07001843 }
1844
Kenny Root07438c82012-11-02 15:41:02 -07001845 int32_t get(const String16& name, uint8_t** item, size_t* itemLength) {
Chad Brubaker9489b792015-04-14 11:01:45 -07001846 if (!checkBinderPermission(P_GET)) {
Kenny Root07438c82012-11-02 15:41:02 -07001847 return ::PERMISSION_DENIED;
Kenny Roota91203b2012-02-15 15:00:46 -08001848 }
Kenny Root07438c82012-11-02 15:41:02 -07001849
Chad Brubaker9489b792015-04-14 11:01:45 -07001850 uid_t callingUid = IPCThreadState::self()->getCallingUid();
Kenny Root07438c82012-11-02 15:41:02 -07001851 String8 name8(name);
Kenny Root07438c82012-11-02 15:41:02 -07001852 Blob keyBlob;
Nick Kralevich66dbf672014-06-30 17:09:14 +00001853
Kenny Root655b9582013-04-04 08:37:42 -07001854 ResponseCode responseCode = mKeyStore->getKeyForName(&keyBlob, name8, callingUid,
Kenny Root49468902013-03-19 13:41:33 -07001855 TYPE_GENERIC);
Kenny Root07438c82012-11-02 15:41:02 -07001856 if (responseCode != ::NO_ERROR) {
1857 *item = NULL;
1858 *itemLength = 0;
1859 return responseCode;
Kenny Roota91203b2012-02-15 15:00:46 -08001860 }
Kenny Roota91203b2012-02-15 15:00:46 -08001861
Kenny Root07438c82012-11-02 15:41:02 -07001862 *item = (uint8_t*) malloc(keyBlob.getLength());
1863 memcpy(*item, keyBlob.getValue(), keyBlob.getLength());
1864 *itemLength = keyBlob.getLength();
Kenny Roota91203b2012-02-15 15:00:46 -08001865
Kenny Root07438c82012-11-02 15:41:02 -07001866 return ::NO_ERROR;
Kenny Root70e3a862012-02-15 17:20:23 -08001867 }
1868
Kenny Rootf9119d62013-04-03 09:22:15 -07001869 int32_t insert(const String16& name, const uint8_t* item, size_t itemLength, int targetUid,
1870 int32_t flags) {
Chad Brubaker9489b792015-04-14 11:01:45 -07001871 targetUid = getEffectiveUid(targetUid);
1872 int32_t result = checkBinderPermissionAndKeystoreState(P_INSERT, targetUid,
1873 flags & KEYSTORE_FLAG_ENCRYPTED);
1874 if (result != ::NO_ERROR) {
1875 return result;
Kenny Rootb88c3eb2013-02-13 14:43:43 -08001876 }
1877
Kenny Root07438c82012-11-02 15:41:02 -07001878 String8 name8(name);
Kenny Root655b9582013-04-04 08:37:42 -07001879 String8 filename(mKeyStore->getKeyNameForUidWithDir(name8, targetUid));
Kenny Root07438c82012-11-02 15:41:02 -07001880
1881 Blob keyBlob(item, itemLength, NULL, 0, ::TYPE_GENERIC);
Kenny Rootee8068b2013-10-07 09:49:15 -07001882 keyBlob.setEncrypted(flags & KEYSTORE_FLAG_ENCRYPTED);
1883
Chad Brubaker72593ee2015-05-12 10:42:00 -07001884 return mKeyStore->put(filename.string(), &keyBlob, get_user_id(targetUid));
Kenny Root70e3a862012-02-15 17:20:23 -08001885 }
1886
Kenny Root49468902013-03-19 13:41:33 -07001887 int32_t del(const String16& name, int targetUid) {
Chad Brubaker9489b792015-04-14 11:01:45 -07001888 targetUid = getEffectiveUid(targetUid);
1889 if (!checkBinderPermission(P_DELETE, targetUid)) {
Kenny Root07438c82012-11-02 15:41:02 -07001890 return ::PERMISSION_DENIED;
1891 }
Kenny Root07438c82012-11-02 15:41:02 -07001892 String8 name8(name);
Kenny Root655b9582013-04-04 08:37:42 -07001893 String8 filename(mKeyStore->getKeyNameForUidWithDir(name8, targetUid));
Chad Brubaker72593ee2015-05-12 10:42:00 -07001894 return mKeyStore->del(filename.string(), ::TYPE_ANY, get_user_id(targetUid));
Kenny Root70e3a862012-02-15 17:20:23 -08001895 }
1896
Kenny Root49468902013-03-19 13:41:33 -07001897 int32_t exist(const String16& name, int targetUid) {
Chad Brubaker9489b792015-04-14 11:01:45 -07001898 targetUid = getEffectiveUid(targetUid);
1899 if (!checkBinderPermission(P_EXIST, targetUid)) {
Kenny Rootb88c3eb2013-02-13 14:43:43 -08001900 return ::PERMISSION_DENIED;
1901 }
1902
Kenny Root07438c82012-11-02 15:41:02 -07001903 String8 name8(name);
Kenny Root655b9582013-04-04 08:37:42 -07001904 String8 filename(mKeyStore->getKeyNameForUidWithDir(name8, targetUid));
Kenny Root70e3a862012-02-15 17:20:23 -08001905
Kenny Root655b9582013-04-04 08:37:42 -07001906 if (access(filename.string(), R_OK) == -1) {
Kenny Root07438c82012-11-02 15:41:02 -07001907 return (errno != ENOENT) ? ::SYSTEM_ERROR : ::KEY_NOT_FOUND;
1908 }
1909 return ::NO_ERROR;
Kenny Root70e3a862012-02-15 17:20:23 -08001910 }
1911
Chad Brubakere6c3bfa2015-05-12 15:18:26 -07001912 int32_t list(const String16& prefix, int targetUid, Vector<String16>* matches) {
Chad Brubaker9489b792015-04-14 11:01:45 -07001913 targetUid = getEffectiveUid(targetUid);
Chad Brubakere6c3bfa2015-05-12 15:18:26 -07001914 if (!checkBinderPermission(P_LIST, targetUid)) {
Kenny Root07438c82012-11-02 15:41:02 -07001915 return ::PERMISSION_DENIED;
1916 }
Kenny Root07438c82012-11-02 15:41:02 -07001917 const String8 prefix8(prefix);
Kenny Root655b9582013-04-04 08:37:42 -07001918 String8 filename(mKeyStore->getKeyNameForUid(prefix8, targetUid));
Kenny Root70e3a862012-02-15 17:20:23 -08001919
Chad Brubakere6c3bfa2015-05-12 15:18:26 -07001920 if (mKeyStore->list(filename, matches, get_user_id(targetUid)) != ::NO_ERROR) {
Robin Lee4b84fdc2014-09-24 11:56:57 +01001921 return ::SYSTEM_ERROR;
Kenny Root9a53d3e2012-08-14 10:47:54 -07001922 }
Kenny Root07438c82012-11-02 15:41:02 -07001923 return ::NO_ERROR;
Kenny Root70e3a862012-02-15 17:20:23 -08001924 }
1925
Kenny Root07438c82012-11-02 15:41:02 -07001926 int32_t reset() {
Chad Brubaker9489b792015-04-14 11:01:45 -07001927 if (!checkBinderPermission(P_RESET)) {
Kenny Root07438c82012-11-02 15:41:02 -07001928 return ::PERMISSION_DENIED;
1929 }
1930
Chad Brubaker9489b792015-04-14 11:01:45 -07001931 uid_t callingUid = IPCThreadState::self()->getCallingUid();
Chad Brubaker96d6d782015-05-07 10:19:40 -07001932 mKeyStore->resetUser(get_user_id(callingUid), false);
1933 return ::NO_ERROR;
Kenny Root70e3a862012-02-15 17:20:23 -08001934 }
1935
Chad Brubaker96d6d782015-05-07 10:19:40 -07001936 int32_t onUserPasswordChanged(int32_t userId, const String16& password) {
Chad Brubaker9489b792015-04-14 11:01:45 -07001937 if (!checkBinderPermission(P_PASSWORD)) {
Kenny Root07438c82012-11-02 15:41:02 -07001938 return ::PERMISSION_DENIED;
1939 }
Kenny Root70e3a862012-02-15 17:20:23 -08001940
Kenny Root07438c82012-11-02 15:41:02 -07001941 const String8 password8(password);
Chad Brubaker96d6d782015-05-07 10:19:40 -07001942 // Flush the auth token table to prevent stale tokens from sticking
1943 // around.
1944 mAuthTokenTable.Clear();
1945
1946 if (password.size() == 0) {
1947 ALOGI("Secure lockscreen for user %d removed, deleting encrypted entries", userId);
Chad Brubaker72593ee2015-05-12 10:42:00 -07001948 mKeyStore->resetUser(userId, true);
Chad Brubaker96d6d782015-05-07 10:19:40 -07001949 return ::NO_ERROR;
1950 } else {
Chad Brubaker72593ee2015-05-12 10:42:00 -07001951 switch (mKeyStore->getState(userId)) {
Chad Brubaker96d6d782015-05-07 10:19:40 -07001952 case ::STATE_UNINITIALIZED: {
1953 // generate master key, encrypt with password, write to file,
1954 // initialize mMasterKey*.
Chad Brubaker72593ee2015-05-12 10:42:00 -07001955 return mKeyStore->initializeUser(password8, userId);
Chad Brubaker96d6d782015-05-07 10:19:40 -07001956 }
1957 case ::STATE_NO_ERROR: {
1958 // rewrite master key with new password.
Chad Brubaker72593ee2015-05-12 10:42:00 -07001959 return mKeyStore->writeMasterKey(password8, userId);
Chad Brubaker96d6d782015-05-07 10:19:40 -07001960 }
1961 case ::STATE_LOCKED: {
1962 ALOGE("Changing user %d's password while locked, clearing old encryption",
1963 userId);
Chad Brubaker72593ee2015-05-12 10:42:00 -07001964 mKeyStore->resetUser(userId, true);
1965 return mKeyStore->initializeUser(password8, userId);
Chad Brubaker96d6d782015-05-07 10:19:40 -07001966 }
Kenny Root07438c82012-11-02 15:41:02 -07001967 }
Chad Brubaker96d6d782015-05-07 10:19:40 -07001968 return ::SYSTEM_ERROR;
Kenny Root07438c82012-11-02 15:41:02 -07001969 }
Kenny Root70e3a862012-02-15 17:20:23 -08001970 }
1971
Chad Brubakerc0f031a2015-05-12 10:43:10 -07001972 int32_t onUserAdded(int32_t userId, int32_t parentId) {
1973 if (!checkBinderPermission(P_USER_CHANGED)) {
1974 return ::PERMISSION_DENIED;
1975 }
1976
1977 // Sanity check that the new user has an empty keystore.
1978 if (!mKeyStore->isEmpty(userId)) {
1979 ALOGW("New user %d's keystore not empty. Clearing old entries.", userId);
1980 }
1981 // Unconditionally clear the keystore, just to be safe.
1982 mKeyStore->resetUser(userId, false);
1983
1984 // If the user has a parent user then use the parent's
1985 // masterkey/password, otherwise there's nothing to do.
1986 if (parentId != -1) {
1987 return mKeyStore->copyMasterKey(parentId, userId);
1988 } else {
1989 return ::NO_ERROR;
1990 }
1991 }
1992
1993 int32_t onUserRemoved(int32_t userId) {
1994 if (!checkBinderPermission(P_USER_CHANGED)) {
1995 return ::PERMISSION_DENIED;
1996 }
1997
1998 mKeyStore->resetUser(userId, false);
1999 return ::NO_ERROR;
2000 }
2001
Chad Brubakere6c3bfa2015-05-12 15:18:26 -07002002 int32_t lock(int32_t userId) {
Chad Brubaker9489b792015-04-14 11:01:45 -07002003 if (!checkBinderPermission(P_LOCK)) {
Kenny Root07438c82012-11-02 15:41:02 -07002004 return ::PERMISSION_DENIED;
2005 }
Kenny Root70e3a862012-02-15 17:20:23 -08002006
Chad Brubaker72593ee2015-05-12 10:42:00 -07002007 State state = mKeyStore->getState(userId);
Kenny Root9d45d1c2013-02-14 10:32:30 -08002008 if (state != ::STATE_NO_ERROR) {
Kenny Root07438c82012-11-02 15:41:02 -07002009 ALOGD("calling lock in state: %d", state);
2010 return state;
2011 }
2012
Chad Brubaker72593ee2015-05-12 10:42:00 -07002013 mKeyStore->lock(userId);
Kenny Root07438c82012-11-02 15:41:02 -07002014 return ::NO_ERROR;
Kenny Root70e3a862012-02-15 17:20:23 -08002015 }
2016
Chad Brubaker96d6d782015-05-07 10:19:40 -07002017 int32_t unlock(int32_t userId, const String16& pw) {
Chad Brubaker9489b792015-04-14 11:01:45 -07002018 if (!checkBinderPermission(P_UNLOCK)) {
Kenny Root07438c82012-11-02 15:41:02 -07002019 return ::PERMISSION_DENIED;
2020 }
2021
Chad Brubaker72593ee2015-05-12 10:42:00 -07002022 State state = mKeyStore->getState(userId);
Kenny Root9d45d1c2013-02-14 10:32:30 -08002023 if (state != ::STATE_LOCKED) {
Chad Brubaker96d6d782015-05-07 10:19:40 -07002024 ALOGI("calling unlock when not locked, ignoring.");
Kenny Root07438c82012-11-02 15:41:02 -07002025 return state;
2026 }
2027
2028 const String8 password8(pw);
Chad Brubaker96d6d782015-05-07 10:19:40 -07002029 // read master key, decrypt with password, initialize mMasterKey*.
Chad Brubaker72593ee2015-05-12 10:42:00 -07002030 return mKeyStore->readMasterKey(password8, userId);
Kenny Root70e3a862012-02-15 17:20:23 -08002031 }
2032
Chad Brubakere6c3bfa2015-05-12 15:18:26 -07002033 bool isEmpty(int32_t userId) {
2034 if (!checkBinderPermission(P_IS_EMPTY)) {
2035 return false;
Kenny Root07438c82012-11-02 15:41:02 -07002036 }
Kenny Root70e3a862012-02-15 17:20:23 -08002037
Chad Brubakere6c3bfa2015-05-12 15:18:26 -07002038 return mKeyStore->isEmpty(userId);
Kenny Root70e3a862012-02-15 17:20:23 -08002039 }
2040
Kenny Root96427ba2013-08-16 14:02:41 -07002041 int32_t generate(const String16& name, int32_t targetUid, int32_t keyType, int32_t keySize,
2042 int32_t flags, Vector<sp<KeystoreArg> >* args) {
Chad Brubaker9489b792015-04-14 11:01:45 -07002043 targetUid = getEffectiveUid(targetUid);
2044 int32_t result = checkBinderPermissionAndKeystoreState(P_INSERT, targetUid,
2045 flags & KEYSTORE_FLAG_ENCRYPTED);
2046 if (result != ::NO_ERROR) {
2047 return result;
Kenny Root07438c82012-11-02 15:41:02 -07002048 }
Kenny Root07438c82012-11-02 15:41:02 -07002049
Chad Brubaker3a7d9e62015-06-04 15:01:46 -07002050 KeymasterArguments params;
Shawn Willden55268b52015-07-28 11:06:00 -06002051 add_legacy_key_authorizations(keyType, &params.params);
Kenny Root07438c82012-11-02 15:41:02 -07002052
Chad Brubaker3a7d9e62015-06-04 15:01:46 -07002053 switch (keyType) {
2054 case EVP_PKEY_EC: {
2055 params.params.push_back(keymaster_param_enum(KM_TAG_ALGORITHM, KM_ALGORITHM_EC));
2056 if (keySize == -1) {
2057 keySize = EC_DEFAULT_KEY_SIZE;
2058 } else if (keySize < EC_MIN_KEY_SIZE || keySize > EC_MAX_KEY_SIZE) {
2059 ALOGI("invalid key size %d", keySize);
Kenny Root96427ba2013-08-16 14:02:41 -07002060 return ::SYSTEM_ERROR;
2061 }
Chad Brubaker3a7d9e62015-06-04 15:01:46 -07002062 params.params.push_back(keymaster_param_int(KM_TAG_KEY_SIZE, keySize));
2063 break;
Kenny Root96427ba2013-08-16 14:02:41 -07002064 }
Chad Brubaker3a7d9e62015-06-04 15:01:46 -07002065 case EVP_PKEY_RSA: {
2066 params.params.push_back(keymaster_param_enum(KM_TAG_ALGORITHM, KM_ALGORITHM_RSA));
2067 if (keySize == -1) {
2068 keySize = RSA_DEFAULT_KEY_SIZE;
2069 } else if (keySize < RSA_MIN_KEY_SIZE || keySize > RSA_MAX_KEY_SIZE) {
2070 ALOGI("invalid key size %d", keySize);
2071 return ::SYSTEM_ERROR;
Kenny Root96427ba2013-08-16 14:02:41 -07002072 }
Chad Brubaker3a7d9e62015-06-04 15:01:46 -07002073 params.params.push_back(keymaster_param_int(KM_TAG_KEY_SIZE, keySize));
2074 unsigned long exponent = RSA_DEFAULT_EXPONENT;
2075 if (args->size() > 1) {
2076 ALOGI("invalid number of arguments: %zu", args->size());
2077 return ::SYSTEM_ERROR;
2078 } else if (args->size() == 1) {
2079 sp<KeystoreArg> expArg = args->itemAt(0);
2080 if (expArg != NULL) {
2081 Unique_BIGNUM pubExpBn(
2082 BN_bin2bn(reinterpret_cast<const unsigned char*>(expArg->data()),
2083 expArg->size(), NULL));
2084 if (pubExpBn.get() == NULL) {
2085 ALOGI("Could not convert public exponent to BN");
2086 return ::SYSTEM_ERROR;
2087 }
2088 exponent = BN_get_word(pubExpBn.get());
2089 if (exponent == 0xFFFFFFFFL) {
2090 ALOGW("cannot represent public exponent as a long value");
2091 return ::SYSTEM_ERROR;
2092 }
2093 } else {
2094 ALOGW("public exponent not read");
2095 return ::SYSTEM_ERROR;
2096 }
2097 }
2098 params.params.push_back(keymaster_param_long(KM_TAG_RSA_PUBLIC_EXPONENT,
2099 exponent));
2100 break;
Kenny Root96427ba2013-08-16 14:02:41 -07002101 }
Chad Brubaker3a7d9e62015-06-04 15:01:46 -07002102 default: {
2103 ALOGW("Unsupported key type %d", keyType);
2104 return ::SYSTEM_ERROR;
2105 }
Kenny Root96427ba2013-08-16 14:02:41 -07002106 }
2107
Chad Brubaker3a7d9e62015-06-04 15:01:46 -07002108 int32_t rc = generateKey(name, params, NULL, 0, targetUid, flags,
2109 /*outCharacteristics*/ NULL);
2110 if (rc != ::NO_ERROR) {
2111 ALOGW("generate failed: %d", rc);
Kenny Root07438c82012-11-02 15:41:02 -07002112 }
Chad Brubaker3a7d9e62015-06-04 15:01:46 -07002113 return translateResultToLegacyResult(rc);
Kenny Root70e3a862012-02-15 17:20:23 -08002114 }
2115
Kenny Rootf9119d62013-04-03 09:22:15 -07002116 int32_t import(const String16& name, const uint8_t* data, size_t length, int targetUid,
2117 int32_t flags) {
Chad Brubaker3a7d9e62015-06-04 15:01:46 -07002118 const uint8_t* ptr = data;
Kenny Root07438c82012-11-02 15:41:02 -07002119
Chad Brubaker3a7d9e62015-06-04 15:01:46 -07002120 Unique_PKCS8_PRIV_KEY_INFO pkcs8(d2i_PKCS8_PRIV_KEY_INFO(NULL, &ptr, length));
2121 if (!pkcs8.get()) {
2122 return ::SYSTEM_ERROR;
2123 }
2124 Unique_EVP_PKEY pkey(EVP_PKCS82PKEY(pkcs8.get()));
2125 if (!pkey.get()) {
2126 return ::SYSTEM_ERROR;
2127 }
2128 int type = EVP_PKEY_type(pkey->type);
Shawn Willden2de8b752015-07-23 05:54:31 -06002129 KeymasterArguments params;
Shawn Willden55268b52015-07-28 11:06:00 -06002130 add_legacy_key_authorizations(type, &params.params);
Chad Brubaker3a7d9e62015-06-04 15:01:46 -07002131 switch (type) {
2132 case EVP_PKEY_RSA:
2133 params.params.push_back(keymaster_param_enum(KM_TAG_ALGORITHM, KM_ALGORITHM_RSA));
2134 break;
2135 case EVP_PKEY_EC:
2136 params.params.push_back(keymaster_param_enum(KM_TAG_ALGORITHM,
2137 KM_ALGORITHM_EC));
2138 break;
2139 default:
2140 ALOGW("Unsupported key type %d", type);
2141 return ::SYSTEM_ERROR;
2142 }
2143 int32_t rc = importKey(name, params, KM_KEY_FORMAT_PKCS8, data, length, targetUid, flags,
2144 /*outCharacteristics*/ NULL);
2145 if (rc != ::NO_ERROR) {
2146 ALOGW("importKey failed: %d", rc);
2147 }
2148 return translateResultToLegacyResult(rc);
Kenny Root70e3a862012-02-15 17:20:23 -08002149 }
2150
Kenny Root07438c82012-11-02 15:41:02 -07002151 int32_t sign(const String16& name, const uint8_t* data, size_t length, uint8_t** out,
Chad Brubaker3a7d9e62015-06-04 15:01:46 -07002152 size_t* outLength) {
Chad Brubaker9489b792015-04-14 11:01:45 -07002153 if (!checkBinderPermission(P_SIGN)) {
Kenny Root07438c82012-11-02 15:41:02 -07002154 return ::PERMISSION_DENIED;
2155 }
Chad Brubaker3a7d9e62015-06-04 15:01:46 -07002156 return doLegacySignVerify(name, data, length, out, outLength, NULL, 0, KM_PURPOSE_SIGN);
Kenny Root70e3a862012-02-15 17:20:23 -08002157 }
2158
Kenny Root07438c82012-11-02 15:41:02 -07002159 int32_t verify(const String16& name, const uint8_t* data, size_t dataLength,
2160 const uint8_t* signature, size_t signatureLength) {
Chad Brubaker9489b792015-04-14 11:01:45 -07002161 if (!checkBinderPermission(P_VERIFY)) {
Kenny Root07438c82012-11-02 15:41:02 -07002162 return ::PERMISSION_DENIED;
2163 }
Chad Brubaker3a7d9e62015-06-04 15:01:46 -07002164 return doLegacySignVerify(name, data, dataLength, NULL, NULL, signature, signatureLength,
2165 KM_PURPOSE_VERIFY);
Kenny Roota91203b2012-02-15 15:00:46 -08002166 }
Kenny Root07438c82012-11-02 15:41:02 -07002167
2168 /*
2169 * TODO: The abstraction between things stored in hardware and regular blobs
2170 * of data stored on the filesystem should be moved down to keystore itself.
2171 * Unfortunately the Java code that calls this has naming conventions that it
2172 * knows about. Ideally keystore shouldn't be used to store random blobs of
2173 * data.
2174 *
2175 * Until that happens, it's necessary to have a separate "get_pubkey" and
2176 * "del_key" since the Java code doesn't really communicate what it's
2177 * intentions are.
2178 */
2179 int32_t get_pubkey(const String16& name, uint8_t** pubkey, size_t* pubkeyLength) {
Chad Brubaker3a7d9e62015-06-04 15:01:46 -07002180 ExportResult result;
2181 exportKey(name, KM_KEY_FORMAT_X509, NULL, NULL, &result);
2182 if (result.resultCode != ::NO_ERROR) {
2183 ALOGW("export failed: %d", result.resultCode);
2184 return translateResultToLegacyResult(result.resultCode);
Kenny Root07438c82012-11-02 15:41:02 -07002185 }
Kenny Root07438c82012-11-02 15:41:02 -07002186
Chad Brubaker3a7d9e62015-06-04 15:01:46 -07002187 *pubkey = result.exportData.release();
2188 *pubkeyLength = result.dataLength;
Kenny Root07438c82012-11-02 15:41:02 -07002189 return ::NO_ERROR;
Kenny Roota91203b2012-02-15 15:00:46 -08002190 }
Kenny Root07438c82012-11-02 15:41:02 -07002191
Kenny Root07438c82012-11-02 15:41:02 -07002192 int32_t grant(const String16& name, int32_t granteeUid) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08002193 uid_t callingUid = IPCThreadState::self()->getCallingUid();
Chad Brubaker9489b792015-04-14 11:01:45 -07002194 int32_t result = checkBinderPermissionAndKeystoreState(P_GRANT);
2195 if (result != ::NO_ERROR) {
2196 return result;
Kenny Root07438c82012-11-02 15:41:02 -07002197 }
2198
2199 String8 name8(name);
Kenny Root655b9582013-04-04 08:37:42 -07002200 String8 filename(mKeyStore->getKeyNameForUidWithDir(name8, callingUid));
Kenny Root07438c82012-11-02 15:41:02 -07002201
Kenny Root655b9582013-04-04 08:37:42 -07002202 if (access(filename.string(), R_OK) == -1) {
Kenny Root07438c82012-11-02 15:41:02 -07002203 return (errno != ENOENT) ? ::SYSTEM_ERROR : ::KEY_NOT_FOUND;
2204 }
2205
Kenny Root655b9582013-04-04 08:37:42 -07002206 mKeyStore->addGrant(filename.string(), granteeUid);
Kenny Root07438c82012-11-02 15:41:02 -07002207 return ::NO_ERROR;
2208 }
2209
2210 int32_t ungrant(const String16& name, int32_t granteeUid) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08002211 uid_t callingUid = IPCThreadState::self()->getCallingUid();
Chad Brubaker9489b792015-04-14 11:01:45 -07002212 int32_t result = checkBinderPermissionAndKeystoreState(P_GRANT);
2213 if (result != ::NO_ERROR) {
2214 return result;
Kenny Root07438c82012-11-02 15:41:02 -07002215 }
2216
2217 String8 name8(name);
Kenny Root655b9582013-04-04 08:37:42 -07002218 String8 filename(mKeyStore->getKeyNameForUidWithDir(name8, callingUid));
Kenny Root07438c82012-11-02 15:41:02 -07002219
Kenny Root655b9582013-04-04 08:37:42 -07002220 if (access(filename.string(), R_OK) == -1) {
Kenny Root07438c82012-11-02 15:41:02 -07002221 return (errno != ENOENT) ? ::SYSTEM_ERROR : ::KEY_NOT_FOUND;
2222 }
2223
Kenny Root655b9582013-04-04 08:37:42 -07002224 return mKeyStore->removeGrant(filename.string(), granteeUid) ? ::NO_ERROR : ::KEY_NOT_FOUND;
Kenny Root07438c82012-11-02 15:41:02 -07002225 }
2226
2227 int64_t getmtime(const String16& name) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08002228 uid_t callingUid = IPCThreadState::self()->getCallingUid();
Chad Brubaker9489b792015-04-14 11:01:45 -07002229 if (!checkBinderPermission(P_GET)) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08002230 ALOGW("permission denied for %d: getmtime", callingUid);
Kenny Root36a9e232013-02-04 14:24:15 -08002231 return -1L;
Kenny Root07438c82012-11-02 15:41:02 -07002232 }
Kenny Root07438c82012-11-02 15:41:02 -07002233
2234 String8 name8(name);
Kenny Root655b9582013-04-04 08:37:42 -07002235 String8 filename(mKeyStore->getKeyNameForUidWithDir(name8, callingUid));
Kenny Root07438c82012-11-02 15:41:02 -07002236
Kenny Root655b9582013-04-04 08:37:42 -07002237 if (access(filename.string(), R_OK) == -1) {
2238 ALOGW("could not access %s for getmtime", filename.string());
Kenny Root36a9e232013-02-04 14:24:15 -08002239 return -1L;
Kenny Root07438c82012-11-02 15:41:02 -07002240 }
2241
Kenny Root655b9582013-04-04 08:37:42 -07002242 int fd = TEMP_FAILURE_RETRY(open(filename.string(), O_NOFOLLOW, O_RDONLY));
Kenny Root07438c82012-11-02 15:41:02 -07002243 if (fd < 0) {
Kenny Root655b9582013-04-04 08:37:42 -07002244 ALOGW("could not open %s for getmtime", filename.string());
Kenny Root36a9e232013-02-04 14:24:15 -08002245 return -1L;
Kenny Root07438c82012-11-02 15:41:02 -07002246 }
2247
2248 struct stat s;
2249 int ret = fstat(fd, &s);
2250 close(fd);
2251 if (ret == -1) {
Kenny Root655b9582013-04-04 08:37:42 -07002252 ALOGW("could not stat %s for getmtime", filename.string());
Kenny Root36a9e232013-02-04 14:24:15 -08002253 return -1L;
Kenny Root07438c82012-11-02 15:41:02 -07002254 }
2255
Kenny Root36a9e232013-02-04 14:24:15 -08002256 return static_cast<int64_t>(s.st_mtime);
Kenny Root07438c82012-11-02 15:41:02 -07002257 }
2258
Kenny Rootd53bc922013-03-21 14:10:15 -07002259 int32_t duplicate(const String16& srcKey, int32_t srcUid, const String16& destKey,
2260 int32_t destUid) {
Kenny Root02254072013-03-20 11:48:19 -07002261 uid_t callingUid = IPCThreadState::self()->getCallingUid();
Riley Spahneaabae92014-06-30 12:39:52 -07002262 pid_t spid = IPCThreadState::self()->getCallingPid();
2263 if (!has_permission(callingUid, P_DUPLICATE, spid)) {
Kenny Rootd53bc922013-03-21 14:10:15 -07002264 ALOGW("permission denied for %d: duplicate", callingUid);
Kenny Root02254072013-03-20 11:48:19 -07002265 return -1L;
2266 }
2267
Chad Brubaker72593ee2015-05-12 10:42:00 -07002268 State state = mKeyStore->getState(get_user_id(callingUid));
Kenny Root02254072013-03-20 11:48:19 -07002269 if (!isKeystoreUnlocked(state)) {
Kenny Rootd53bc922013-03-21 14:10:15 -07002270 ALOGD("calling duplicate in state: %d", state);
Kenny Root02254072013-03-20 11:48:19 -07002271 return state;
2272 }
2273
Kenny Rootd53bc922013-03-21 14:10:15 -07002274 if (srcUid == -1 || static_cast<uid_t>(srcUid) == callingUid) {
2275 srcUid = callingUid;
2276 } else if (!is_granted_to(callingUid, srcUid)) {
2277 ALOGD("migrate not granted from source: %d -> %d", callingUid, srcUid);
Kenny Root02254072013-03-20 11:48:19 -07002278 return ::PERMISSION_DENIED;
2279 }
2280
Kenny Rootd53bc922013-03-21 14:10:15 -07002281 if (destUid == -1) {
2282 destUid = callingUid;
2283 }
2284
2285 if (srcUid != destUid) {
2286 if (static_cast<uid_t>(srcUid) != callingUid) {
2287 ALOGD("can only duplicate from caller to other or to same uid: "
2288 "calling=%d, srcUid=%d, destUid=%d", callingUid, srcUid, destUid);
2289 return ::PERMISSION_DENIED;
2290 }
2291
2292 if (!is_granted_to(callingUid, destUid)) {
2293 ALOGD("duplicate not granted to dest: %d -> %d", callingUid, destUid);
2294 return ::PERMISSION_DENIED;
2295 }
2296 }
2297
2298 String8 source8(srcKey);
Kenny Root655b9582013-04-04 08:37:42 -07002299 String8 sourceFile(mKeyStore->getKeyNameForUidWithDir(source8, srcUid));
Kenny Root02254072013-03-20 11:48:19 -07002300
Kenny Rootd53bc922013-03-21 14:10:15 -07002301 String8 target8(destKey);
Kenny Rootfa27d5b2013-10-15 09:01:08 -07002302 String8 targetFile(mKeyStore->getKeyNameForUidWithDir(target8, destUid));
Kenny Root02254072013-03-20 11:48:19 -07002303
Kenny Root655b9582013-04-04 08:37:42 -07002304 if (access(targetFile.string(), W_OK) != -1 || errno != ENOENT) {
2305 ALOGD("destination already exists: %s", targetFile.string());
Kenny Root02254072013-03-20 11:48:19 -07002306 return ::SYSTEM_ERROR;
2307 }
2308
Kenny Rootd53bc922013-03-21 14:10:15 -07002309 Blob keyBlob;
Kenny Root655b9582013-04-04 08:37:42 -07002310 ResponseCode responseCode = mKeyStore->get(sourceFile.string(), &keyBlob, TYPE_ANY,
Chad Brubaker72593ee2015-05-12 10:42:00 -07002311 get_user_id(srcUid));
Kenny Rootd53bc922013-03-21 14:10:15 -07002312 if (responseCode != ::NO_ERROR) {
2313 return responseCode;
Kenny Root02254072013-03-20 11:48:19 -07002314 }
Kenny Rootd53bc922013-03-21 14:10:15 -07002315
Chad Brubaker72593ee2015-05-12 10:42:00 -07002316 return mKeyStore->put(targetFile.string(), &keyBlob, get_user_id(destUid));
Kenny Root02254072013-03-20 11:48:19 -07002317 }
2318
Kenny Root1b0e3932013-09-05 13:06:32 -07002319 int32_t is_hardware_backed(const String16& keyType) {
2320 return mKeyStore->isHardwareBacked(keyType) ? 1 : 0;
Kenny Root8ddf35a2013-03-29 11:15:50 -07002321 }
2322
Kenny Rootfa27d5b2013-10-15 09:01:08 -07002323 int32_t clear_uid(int64_t targetUid64) {
Chad Brubaker9489b792015-04-14 11:01:45 -07002324 uid_t targetUid = getEffectiveUid(targetUid64);
Chad Brubakerb37a5232015-05-01 10:21:27 -07002325 if (!checkBinderPermissionSelfOrSystem(P_CLEAR_UID, targetUid)) {
Kenny Roota9bb5492013-04-01 16:29:11 -07002326 return ::PERMISSION_DENIED;
2327 }
2328
Robin Lee4b84fdc2014-09-24 11:56:57 +01002329 String8 prefix = String8::format("%u_", targetUid);
2330 Vector<String16> aliases;
Chad Brubakere6c3bfa2015-05-12 15:18:26 -07002331 if (mKeyStore->list(prefix, &aliases, get_user_id(targetUid)) != ::NO_ERROR) {
Kenny Roota9bb5492013-04-01 16:29:11 -07002332 return ::SYSTEM_ERROR;
2333 }
2334
Robin Lee4b84fdc2014-09-24 11:56:57 +01002335 for (uint32_t i = 0; i < aliases.size(); i++) {
2336 String8 name8(aliases[i]);
2337 String8 filename(mKeyStore->getKeyNameForUidWithDir(name8, targetUid));
Chad Brubaker72593ee2015-05-12 10:42:00 -07002338 mKeyStore->del(filename.string(), ::TYPE_ANY, get_user_id(targetUid));
Kenny Roota9bb5492013-04-01 16:29:11 -07002339 }
Robin Lee4b84fdc2014-09-24 11:56:57 +01002340 return ::NO_ERROR;
Kenny Roota9bb5492013-04-01 16:29:11 -07002341 }
2342
Chad Brubaker9c8612c2015-02-09 11:32:54 -08002343 int32_t addRngEntropy(const uint8_t* data, size_t dataLength) {
2344 const keymaster1_device_t* device = mKeyStore->getDevice();
2345 const keymaster1_device_t* fallback = mKeyStore->getFallbackDevice();
2346 int32_t devResult = KM_ERROR_UNIMPLEMENTED;
2347 int32_t fallbackResult = KM_ERROR_UNIMPLEMENTED;
2348 if (device->common.module->module_api_version >= KEYMASTER_MODULE_API_VERSION_1_0 &&
2349 device->add_rng_entropy != NULL) {
2350 devResult = device->add_rng_entropy(device, data, dataLength);
2351 }
2352 if (fallback->add_rng_entropy) {
2353 fallbackResult = fallback->add_rng_entropy(fallback, data, dataLength);
2354 }
2355 if (devResult) {
2356 return devResult;
2357 }
2358 if (fallbackResult) {
2359 return fallbackResult;
2360 }
2361 return ::NO_ERROR;
Chad Brubaker9899d6b2015-02-03 13:03:00 -08002362 }
2363
Chad Brubaker17d68b92015-02-05 22:04:16 -08002364 int32_t generateKey(const String16& name, const KeymasterArguments& params,
Chad Brubaker154d7692015-03-27 13:59:31 -07002365 const uint8_t* entropy, size_t entropyLength, int uid, int flags,
2366 KeyCharacteristics* outCharacteristics) {
Chad Brubaker9489b792015-04-14 11:01:45 -07002367 uid = getEffectiveUid(uid);
2368 int rc = checkBinderPermissionAndKeystoreState(P_INSERT, uid,
2369 flags & KEYSTORE_FLAG_ENCRYPTED);
2370 if (rc != ::NO_ERROR) {
2371 return rc;
Chad Brubaker17d68b92015-02-05 22:04:16 -08002372 }
2373
Chad Brubaker9489b792015-04-14 11:01:45 -07002374 rc = KM_ERROR_UNIMPLEMENTED;
Chad Brubaker17d68b92015-02-05 22:04:16 -08002375 bool isFallback = false;
2376 keymaster_key_blob_t blob;
2377 keymaster_key_characteristics_t *out = NULL;
2378
2379 const keymaster1_device_t* device = mKeyStore->getDevice();
2380 const keymaster1_device_t* fallback = mKeyStore->getFallbackDevice();
Chad Brubaker57e106d2015-06-01 12:59:00 -07002381 std::vector<keymaster_key_param_t> opParams(params.params);
2382 const keymaster_key_param_set_t inParams = {opParams.data(), opParams.size()};
Chad Brubaker17d68b92015-02-05 22:04:16 -08002383 if (device == NULL) {
2384 return ::SYSTEM_ERROR;
2385 }
Chad Brubaker154d7692015-03-27 13:59:31 -07002386 // TODO: Seed from Linux RNG before this.
Chad Brubaker17d68b92015-02-05 22:04:16 -08002387 if (device->common.module->module_api_version >= KEYMASTER_MODULE_API_VERSION_1_0 &&
2388 device->generate_key != NULL) {
Chad Brubaker154d7692015-03-27 13:59:31 -07002389 if (!entropy) {
2390 rc = KM_ERROR_OK;
2391 } else if (device->add_rng_entropy) {
2392 rc = device->add_rng_entropy(device, entropy, entropyLength);
2393 } else {
2394 rc = KM_ERROR_UNIMPLEMENTED;
2395 }
2396 if (rc == KM_ERROR_OK) {
Chad Brubaker57e106d2015-06-01 12:59:00 -07002397 rc = device->generate_key(device, &inParams, &blob, &out);
Chad Brubaker154d7692015-03-27 13:59:31 -07002398 }
Chad Brubaker17d68b92015-02-05 22:04:16 -08002399 }
2400 // If the HW device didn't support generate_key or generate_key failed
2401 // fall back to the software implementation.
2402 if (rc && fallback->generate_key != NULL) {
Shawn Willden55268b52015-07-28 11:06:00 -06002403 ALOGW("Primary keymaster device failed to generate key, falling back to SW.");
Chad Brubaker17d68b92015-02-05 22:04:16 -08002404 isFallback = true;
Chad Brubaker154d7692015-03-27 13:59:31 -07002405 if (!entropy) {
2406 rc = KM_ERROR_OK;
2407 } else if (fallback->add_rng_entropy) {
2408 rc = fallback->add_rng_entropy(fallback, entropy, entropyLength);
2409 } else {
2410 rc = KM_ERROR_UNIMPLEMENTED;
2411 }
2412 if (rc == KM_ERROR_OK) {
Chad Brubaker57e106d2015-06-01 12:59:00 -07002413 rc = fallback->generate_key(fallback, &inParams, &blob, &out);
Chad Brubaker154d7692015-03-27 13:59:31 -07002414 }
Chad Brubaker17d68b92015-02-05 22:04:16 -08002415 }
2416
2417 if (out) {
2418 if (outCharacteristics) {
2419 outCharacteristics->characteristics = *out;
2420 } else {
2421 keymaster_free_characteristics(out);
2422 }
2423 free(out);
2424 }
2425
2426 if (rc) {
2427 return rc;
2428 }
2429
2430 String8 name8(name);
2431 String8 filename(mKeyStore->getKeyNameForUidWithDir(name8, uid));
2432
2433 Blob keyBlob(blob.key_material, blob.key_material_size, NULL, 0, ::TYPE_KEYMASTER_10);
2434 keyBlob.setFallback(isFallback);
2435 keyBlob.setEncrypted(flags & KEYSTORE_FLAG_ENCRYPTED);
2436
2437 free(const_cast<uint8_t*>(blob.key_material));
2438
Chad Brubaker72593ee2015-05-12 10:42:00 -07002439 return mKeyStore->put(filename.string(), &keyBlob, get_user_id(uid));
Chad Brubaker9899d6b2015-02-03 13:03:00 -08002440 }
2441
Chad Brubakerf3f071f2015-02-10 19:38:51 -08002442 int32_t getKeyCharacteristics(const String16& name,
Chad Brubakerd6634422015-03-21 22:36:07 -07002443 const keymaster_blob_t* clientId,
2444 const keymaster_blob_t* appData,
Chad Brubakerf3f071f2015-02-10 19:38:51 -08002445 KeyCharacteristics* outCharacteristics) {
Chad Brubakerf3f071f2015-02-10 19:38:51 -08002446 if (!outCharacteristics) {
2447 return KM_ERROR_UNEXPECTED_NULL_POINTER;
2448 }
2449
2450 uid_t callingUid = IPCThreadState::self()->getCallingUid();
2451
2452 Blob keyBlob;
2453 String8 name8(name);
2454 int rc;
2455
2456 ResponseCode responseCode = mKeyStore->getKeyForName(&keyBlob, name8, callingUid,
2457 TYPE_KEYMASTER_10);
2458 if (responseCode != ::NO_ERROR) {
2459 return responseCode;
2460 }
2461 keymaster_key_blob_t key;
2462 key.key_material_size = keyBlob.getLength();
2463 key.key_material = keyBlob.getValue();
2464 keymaster1_device_t* dev = mKeyStore->getDeviceForBlob(keyBlob);
2465 keymaster_key_characteristics_t *out = NULL;
2466 if (!dev->get_key_characteristics) {
2467 ALOGW("device does not implement get_key_characteristics");
2468 return KM_ERROR_UNIMPLEMENTED;
2469 }
Chad Brubakerd6634422015-03-21 22:36:07 -07002470 rc = dev->get_key_characteristics(dev, &key, clientId, appData, &out);
Chad Brubakerf3f071f2015-02-10 19:38:51 -08002471 if (out) {
2472 outCharacteristics->characteristics = *out;
2473 free(out);
2474 }
2475 return rc ? rc : ::NO_ERROR;
Chad Brubaker9899d6b2015-02-03 13:03:00 -08002476 }
2477
Chad Brubaker4c353cb2015-02-11 14:36:11 -08002478 int32_t importKey(const String16& name, const KeymasterArguments& params,
2479 keymaster_key_format_t format, const uint8_t *keyData,
2480 size_t keyLength, int uid, int flags,
2481 KeyCharacteristics* outCharacteristics) {
Chad Brubaker9489b792015-04-14 11:01:45 -07002482 uid = getEffectiveUid(uid);
2483 int rc = checkBinderPermissionAndKeystoreState(P_INSERT, uid,
2484 flags & KEYSTORE_FLAG_ENCRYPTED);
2485 if (rc != ::NO_ERROR) {
2486 return rc;
Chad Brubaker4c353cb2015-02-11 14:36:11 -08002487 }
2488
Chad Brubaker9489b792015-04-14 11:01:45 -07002489 rc = KM_ERROR_UNIMPLEMENTED;
Chad Brubaker4c353cb2015-02-11 14:36:11 -08002490 bool isFallback = false;
2491 keymaster_key_blob_t blob;
2492 keymaster_key_characteristics_t *out = NULL;
2493
2494 const keymaster1_device_t* device = mKeyStore->getDevice();
2495 const keymaster1_device_t* fallback = mKeyStore->getFallbackDevice();
Chad Brubaker57e106d2015-06-01 12:59:00 -07002496 std::vector<keymaster_key_param_t> opParams(params.params);
2497 const keymaster_key_param_set_t inParams = {opParams.data(), opParams.size()};
2498 const keymaster_blob_t input = {keyData, keyLength};
Chad Brubaker4c353cb2015-02-11 14:36:11 -08002499 if (device == NULL) {
2500 return ::SYSTEM_ERROR;
2501 }
2502 if (device->common.module->module_api_version >= KEYMASTER_MODULE_API_VERSION_1_0 &&
2503 device->import_key != NULL) {
Chad Brubaker57e106d2015-06-01 12:59:00 -07002504 rc = device->import_key(device, &inParams, format,&input, &blob, &out);
Chad Brubaker4c353cb2015-02-11 14:36:11 -08002505 }
2506 if (rc && fallback->import_key != NULL) {
Shawn Willden55268b52015-07-28 11:06:00 -06002507 ALOGW("Primary keymaster device failed to import key, falling back to SW.");
Chad Brubaker4c353cb2015-02-11 14:36:11 -08002508 isFallback = true;
Chad Brubaker57e106d2015-06-01 12:59:00 -07002509 rc = fallback->import_key(fallback, &inParams, format, &input, &blob, &out);
Chad Brubaker4c353cb2015-02-11 14:36:11 -08002510 }
2511 if (out) {
2512 if (outCharacteristics) {
2513 outCharacteristics->characteristics = *out;
2514 } else {
2515 keymaster_free_characteristics(out);
2516 }
2517 free(out);
2518 }
2519 if (rc) {
2520 return rc;
2521 }
2522
2523 String8 name8(name);
2524 String8 filename(mKeyStore->getKeyNameForUidWithDir(name8, uid));
2525
2526 Blob keyBlob(blob.key_material, blob.key_material_size, NULL, 0, ::TYPE_KEYMASTER_10);
2527 keyBlob.setFallback(isFallback);
2528 keyBlob.setEncrypted(flags & KEYSTORE_FLAG_ENCRYPTED);
2529
2530 free((void*) blob.key_material);
2531
Chad Brubaker72593ee2015-05-12 10:42:00 -07002532 return mKeyStore->put(filename.string(), &keyBlob, get_user_id(uid));
Chad Brubaker9899d6b2015-02-03 13:03:00 -08002533 }
2534
Chad Brubaker07b0cda2015-02-18 15:52:54 -08002535 void exportKey(const String16& name, keymaster_key_format_t format,
Chad Brubakerd6634422015-03-21 22:36:07 -07002536 const keymaster_blob_t* clientId,
2537 const keymaster_blob_t* appData, ExportResult* result) {
Chad Brubaker07b0cda2015-02-18 15:52:54 -08002538
2539 uid_t callingUid = IPCThreadState::self()->getCallingUid();
2540
2541 Blob keyBlob;
2542 String8 name8(name);
2543 int rc;
2544
2545 ResponseCode responseCode = mKeyStore->getKeyForName(&keyBlob, name8, callingUid,
2546 TYPE_KEYMASTER_10);
2547 if (responseCode != ::NO_ERROR) {
2548 result->resultCode = responseCode;
2549 return;
2550 }
2551 keymaster_key_blob_t key;
2552 key.key_material_size = keyBlob.getLength();
2553 key.key_material = keyBlob.getValue();
2554 keymaster1_device_t* dev = mKeyStore->getDeviceForBlob(keyBlob);
2555 if (!dev->export_key) {
2556 result->resultCode = KM_ERROR_UNIMPLEMENTED;
2557 return;
2558 }
Chad Brubaker57e106d2015-06-01 12:59:00 -07002559 keymaster_blob_t output = {NULL, 0};
2560 rc = dev->export_key(dev, format, &key, clientId, appData, &output);
2561 result->exportData.reset(const_cast<uint8_t*>(output.data));
2562 result->dataLength = output.data_length;
Chad Brubaker07b0cda2015-02-18 15:52:54 -08002563 result->resultCode = rc ? rc : ::NO_ERROR;
Chad Brubaker9899d6b2015-02-03 13:03:00 -08002564 }
2565
Chad Brubakerad6514a2015-04-09 14:00:26 -07002566
Chad Brubaker40a1a9b2015-02-20 14:08:13 -08002567 void begin(const sp<IBinder>& appToken, const String16& name, keymaster_purpose_t purpose,
Chad Brubaker154d7692015-03-27 13:59:31 -07002568 bool pruneable, const KeymasterArguments& params, const uint8_t* entropy,
Chad Brubaker57e106d2015-06-01 12:59:00 -07002569 size_t entropyLength, OperationResult* result) {
Chad Brubaker40a1a9b2015-02-20 14:08:13 -08002570 uid_t callingUid = IPCThreadState::self()->getCallingUid();
2571 if (!pruneable && get_app_id(callingUid) != AID_SYSTEM) {
2572 ALOGE("Non-system uid %d trying to start non-pruneable operation", callingUid);
2573 result->resultCode = ::PERMISSION_DENIED;
2574 return;
2575 }
Chad Brubaker0cf34a22015-04-23 11:06:16 -07002576 if (!checkAllowedOperationParams(params.params)) {
2577 result->resultCode = KM_ERROR_INVALID_ARGUMENT;
2578 return;
2579 }
Chad Brubaker40a1a9b2015-02-20 14:08:13 -08002580 Blob keyBlob;
2581 String8 name8(name);
2582 ResponseCode responseCode = mKeyStore->getKeyForName(&keyBlob, name8, callingUid,
2583 TYPE_KEYMASTER_10);
2584 if (responseCode != ::NO_ERROR) {
2585 result->resultCode = responseCode;
2586 return;
2587 }
2588 keymaster_key_blob_t key;
2589 key.key_material_size = keyBlob.getLength();
2590 key.key_material = keyBlob.getValue();
Chad Brubaker40a1a9b2015-02-20 14:08:13 -08002591 keymaster_operation_handle_t handle;
2592 keymaster1_device_t* dev = mKeyStore->getDeviceForBlob(keyBlob);
Chad Brubaker154d7692015-03-27 13:59:31 -07002593 keymaster_error_t err = KM_ERROR_UNIMPLEMENTED;
Chad Brubaker06801e02015-03-31 15:13:13 -07002594 std::vector<keymaster_key_param_t> opParams(params.params);
Chad Brubakerad6514a2015-04-09 14:00:26 -07002595 Unique_keymaster_key_characteristics characteristics;
2596 characteristics.reset(new keymaster_key_characteristics_t);
2597 err = getOperationCharacteristics(key, dev, opParams, characteristics.get());
2598 if (err) {
2599 result->resultCode = err;
2600 return;
2601 }
Chad Brubaker0cf34a22015-04-23 11:06:16 -07002602 const hw_auth_token_t* authToken = NULL;
Shawn Willdenb2ffa422015-06-17 12:18:55 -06002603 int32_t authResult = getAuthToken(characteristics.get(), 0, purpose, &authToken,
Chad Brubaker06801e02015-03-31 15:13:13 -07002604 /*failOnTokenMissing*/ false);
Chad Brubaker0cf34a22015-04-23 11:06:16 -07002605 // If per-operation auth is needed we need to begin the operation and
2606 // the client will need to authorize that operation before calling
2607 // update. Any other auth issues stop here.
2608 if (authResult != ::NO_ERROR && authResult != ::OP_AUTH_NEEDED) {
2609 result->resultCode = authResult;
Chad Brubaker06801e02015-03-31 15:13:13 -07002610 return;
2611 }
Chad Brubaker0cf34a22015-04-23 11:06:16 -07002612 addAuthToParams(&opParams, authToken);
Chad Brubaker154d7692015-03-27 13:59:31 -07002613 // Add entropy to the device first.
2614 if (entropy) {
2615 if (dev->add_rng_entropy) {
2616 err = dev->add_rng_entropy(dev, entropy, entropyLength);
2617 } else {
2618 err = KM_ERROR_UNIMPLEMENTED;
2619 }
2620 if (err) {
2621 result->resultCode = err;
2622 return;
2623 }
2624 }
Chad Brubaker57e106d2015-06-01 12:59:00 -07002625 keymaster_key_param_set_t inParams = {opParams.data(), opParams.size()};
Chad Brubaker40a1a9b2015-02-20 14:08:13 -08002626
Shawn Willden9221bff2015-06-18 18:23:54 -06002627 // Create a keyid for this key.
2628 keymaster::km_id_t keyid;
2629 if (!enforcement_policy.CreateKeyId(key, &keyid)) {
2630 ALOGE("Failed to create a key ID for authorization checking.");
2631 result->resultCode = KM_ERROR_UNKNOWN_ERROR;
2632 return;
2633 }
2634
2635 // Check that all key authorization policy requirements are met.
2636 keymaster::AuthorizationSet key_auths(characteristics->hw_enforced);
2637 key_auths.push_back(characteristics->sw_enforced);
2638 keymaster::AuthorizationSet operation_params(inParams);
2639 err = enforcement_policy.AuthorizeOperation(purpose, keyid, key_auths, operation_params,
2640 0 /* op_handle */,
2641 true /* is_begin_operation */);
2642 if (err) {
2643 result->resultCode = err;
2644 return;
2645 }
2646
Alex Klyubin4e88f9b2015-06-23 15:04:05 -07002647 keymaster_key_param_set_t outParams = {NULL, 0};
2648 err = dev->begin(dev, purpose, &key, &inParams, &outParams, &handle);
2649
Chad Brubaker40a1a9b2015-02-20 14:08:13 -08002650 // If there are too many operations abort the oldest operation that was
2651 // started as pruneable and try again.
2652 while (err == KM_ERROR_TOO_MANY_OPERATIONS && mOperationMap.hasPruneableOperation()) {
2653 sp<IBinder> oldest = mOperationMap.getOldestPruneableOperation();
2654 ALOGD("Ran out of operation handles, trying to prune %p", oldest.get());
Alex Klyubin700c1a32015-06-23 15:21:51 -07002655
2656 // We mostly ignore errors from abort() below because all we care about is whether at
2657 // least one pruneable operation has been removed.
2658 size_t op_count_before = mOperationMap.getPruneableOperationCount();
2659 int abort_error = abort(oldest);
2660 size_t op_count_after = mOperationMap.getPruneableOperationCount();
2661 if (op_count_after >= op_count_before) {
2662 // Failed to create space for a new operation. Bail to avoid an infinite loop.
2663 ALOGE("Failed to remove pruneable operation %p, error: %d",
2664 oldest.get(), abort_error);
Chad Brubaker40a1a9b2015-02-20 14:08:13 -08002665 break;
2666 }
Chad Brubaker57e106d2015-06-01 12:59:00 -07002667 err = dev->begin(dev, purpose, &key, &inParams, &outParams, &handle);
Chad Brubaker40a1a9b2015-02-20 14:08:13 -08002668 }
2669 if (err) {
2670 result->resultCode = err;
2671 return;
2672 }
Chad Brubaker40a1a9b2015-02-20 14:08:13 -08002673
Shawn Willden9221bff2015-06-18 18:23:54 -06002674 sp<IBinder> operationToken = mOperationMap.addOperation(handle, keyid, purpose, dev,
2675 appToken, characteristics.release(),
Chad Brubaker06801e02015-03-31 15:13:13 -07002676 pruneable);
Chad Brubaker0cf34a22015-04-23 11:06:16 -07002677 if (authToken) {
2678 mOperationMap.setOperationAuthToken(operationToken, authToken);
2679 }
2680 // Return the authentication lookup result. If this is a per operation
2681 // auth'd key then the resultCode will be ::OP_AUTH_NEEDED and the
2682 // application should get an auth token using the handle before the
2683 // first call to update, which will fail if keystore hasn't received the
2684 // auth token.
2685 result->resultCode = authResult;
Chad Brubaker40a1a9b2015-02-20 14:08:13 -08002686 result->token = operationToken;
Chad Brubakerc3a18562015-03-17 18:21:35 -07002687 result->handle = handle;
Chad Brubaker57e106d2015-06-01 12:59:00 -07002688 if (outParams.params) {
2689 result->outParams.params.assign(outParams.params, outParams.params + outParams.length);
2690 free(outParams.params);
2691 }
Chad Brubaker9899d6b2015-02-03 13:03:00 -08002692 }
2693
Chad Brubaker40a1a9b2015-02-20 14:08:13 -08002694 void update(const sp<IBinder>& token, const KeymasterArguments& params, const uint8_t* data,
2695 size_t dataLength, OperationResult* result) {
Chad Brubaker0cf34a22015-04-23 11:06:16 -07002696 if (!checkAllowedOperationParams(params.params)) {
2697 result->resultCode = KM_ERROR_INVALID_ARGUMENT;
2698 return;
2699 }
Chad Brubaker40a1a9b2015-02-20 14:08:13 -08002700 const keymaster1_device_t* dev;
2701 keymaster_operation_handle_t handle;
Shawn Willdenb2ffa422015-06-17 12:18:55 -06002702 keymaster_purpose_t purpose;
Shawn Willden9221bff2015-06-18 18:23:54 -06002703 keymaster::km_id_t keyid;
2704 const keymaster_key_characteristics_t* characteristics;
2705 if (!mOperationMap.getOperation(token, &handle, &keyid, &purpose, &dev, &characteristics)) {
Chad Brubaker40a1a9b2015-02-20 14:08:13 -08002706 result->resultCode = KM_ERROR_INVALID_OPERATION_HANDLE;
2707 return;
2708 }
Chad Brubaker06801e02015-03-31 15:13:13 -07002709 std::vector<keymaster_key_param_t> opParams(params.params);
Chad Brubaker0cf34a22015-04-23 11:06:16 -07002710 int32_t authResult = addOperationAuthTokenIfNeeded(token, &opParams);
2711 if (authResult != ::NO_ERROR) {
Chad Brubaker06801e02015-03-31 15:13:13 -07002712 result->resultCode = authResult;
2713 return;
2714 }
Chad Brubaker57e106d2015-06-01 12:59:00 -07002715 keymaster_key_param_set_t inParams = {opParams.data(), opParams.size()};
2716 keymaster_blob_t input = {data, dataLength};
2717 size_t consumed = 0;
2718 keymaster_blob_t output = {NULL, 0};
2719 keymaster_key_param_set_t outParams = {NULL, 0};
2720
Shawn Willden9221bff2015-06-18 18:23:54 -06002721 // Check that all key authorization policy requirements are met.
2722 keymaster::AuthorizationSet key_auths(characteristics->hw_enforced);
2723 key_auths.push_back(characteristics->sw_enforced);
2724 keymaster::AuthorizationSet operation_params(inParams);
2725 result->resultCode =
2726 enforcement_policy.AuthorizeOperation(purpose, keyid, key_auths,
2727 operation_params, handle,
2728 false /* is_begin_operation */);
2729 if (result->resultCode) {
2730 return;
2731 }
2732
Chad Brubaker57e106d2015-06-01 12:59:00 -07002733 keymaster_error_t err = dev->update(dev, handle, &inParams, &input, &consumed, &outParams,
2734 &output);
2735 result->data.reset(const_cast<uint8_t*>(output.data));
2736 result->dataLength = output.data_length;
Chad Brubaker40a1a9b2015-02-20 14:08:13 -08002737 result->inputConsumed = consumed;
2738 result->resultCode = err ? (int32_t) err : ::NO_ERROR;
Chad Brubaker57e106d2015-06-01 12:59:00 -07002739 if (outParams.params) {
2740 result->outParams.params.assign(outParams.params, outParams.params + outParams.length);
2741 free(outParams.params);
2742 }
Chad Brubaker9899d6b2015-02-03 13:03:00 -08002743 }
2744
Chad Brubaker40a1a9b2015-02-20 14:08:13 -08002745 void finish(const sp<IBinder>& token, const KeymasterArguments& params,
Chad Brubaker0d33e0b2015-05-29 12:30:19 -07002746 const uint8_t* signature, size_t signatureLength,
2747 const uint8_t* entropy, size_t entropyLength, OperationResult* result) {
Chad Brubaker0cf34a22015-04-23 11:06:16 -07002748 if (!checkAllowedOperationParams(params.params)) {
2749 result->resultCode = KM_ERROR_INVALID_ARGUMENT;
2750 return;
2751 }
Chad Brubaker40a1a9b2015-02-20 14:08:13 -08002752 const keymaster1_device_t* dev;
2753 keymaster_operation_handle_t handle;
Shawn Willdenb2ffa422015-06-17 12:18:55 -06002754 keymaster_purpose_t purpose;
Shawn Willden9221bff2015-06-18 18:23:54 -06002755 keymaster::km_id_t keyid;
2756 const keymaster_key_characteristics_t* characteristics;
2757 if (!mOperationMap.getOperation(token, &handle, &keyid, &purpose, &dev, &characteristics)) {
Chad Brubaker40a1a9b2015-02-20 14:08:13 -08002758 result->resultCode = KM_ERROR_INVALID_OPERATION_HANDLE;
2759 return;
2760 }
Chad Brubaker06801e02015-03-31 15:13:13 -07002761 std::vector<keymaster_key_param_t> opParams(params.params);
Chad Brubaker0cf34a22015-04-23 11:06:16 -07002762 int32_t authResult = addOperationAuthTokenIfNeeded(token, &opParams);
2763 if (authResult != ::NO_ERROR) {
Chad Brubaker06801e02015-03-31 15:13:13 -07002764 result->resultCode = authResult;
2765 return;
2766 }
Chad Brubaker0d33e0b2015-05-29 12:30:19 -07002767 keymaster_error_t err;
2768 if (entropy) {
2769 if (dev->add_rng_entropy) {
2770 err = dev->add_rng_entropy(dev, entropy, entropyLength);
2771 } else {
2772 err = KM_ERROR_UNIMPLEMENTED;
2773 }
2774 if (err) {
2775 result->resultCode = err;
2776 return;
2777 }
2778 }
Chad Brubaker0cf34a22015-04-23 11:06:16 -07002779
Chad Brubaker57e106d2015-06-01 12:59:00 -07002780 keymaster_key_param_set_t inParams = {opParams.data(), opParams.size()};
2781 keymaster_blob_t input = {signature, signatureLength};
2782 keymaster_blob_t output = {NULL, 0};
2783 keymaster_key_param_set_t outParams = {NULL, 0};
Shawn Willden9221bff2015-06-18 18:23:54 -06002784
2785 // Check that all key authorization policy requirements are met.
2786 keymaster::AuthorizationSet key_auths(characteristics->hw_enforced);
2787 key_auths.push_back(characteristics->sw_enforced);
2788 keymaster::AuthorizationSet operation_params(inParams);
2789 err = enforcement_policy.AuthorizeOperation(purpose, keyid, key_auths, operation_params,
2790 handle, false /* is_begin_operation */);
2791 if (err) {
2792 result->resultCode = err;
2793 return;
2794 }
2795
Chad Brubaker0d33e0b2015-05-29 12:30:19 -07002796 err = dev->finish(dev, handle, &inParams, &input, &outParams, &output);
Chad Brubaker40a1a9b2015-02-20 14:08:13 -08002797 // Remove the operation regardless of the result
2798 mOperationMap.removeOperation(token);
Chad Brubaker06801e02015-03-31 15:13:13 -07002799 mAuthTokenTable.MarkCompleted(handle);
Chad Brubaker57e106d2015-06-01 12:59:00 -07002800
2801 result->data.reset(const_cast<uint8_t*>(output.data));
2802 result->dataLength = output.data_length;
Chad Brubaker40a1a9b2015-02-20 14:08:13 -08002803 result->resultCode = err ? (int32_t) err : ::NO_ERROR;
Chad Brubaker57e106d2015-06-01 12:59:00 -07002804 if (outParams.params) {
2805 result->outParams.params.assign(outParams.params, outParams.params + outParams.length);
2806 free(outParams.params);
2807 }
Chad Brubaker9899d6b2015-02-03 13:03:00 -08002808 }
2809
Chad Brubaker40a1a9b2015-02-20 14:08:13 -08002810 int32_t abort(const sp<IBinder>& token) {
2811 const keymaster1_device_t* dev;
2812 keymaster_operation_handle_t handle;
Shawn Willdenb2ffa422015-06-17 12:18:55 -06002813 keymaster_purpose_t purpose;
Shawn Willden9221bff2015-06-18 18:23:54 -06002814 keymaster::km_id_t keyid;
2815 if (!mOperationMap.getOperation(token, &handle, &keyid, &purpose, &dev, NULL)) {
Chad Brubaker40a1a9b2015-02-20 14:08:13 -08002816 return KM_ERROR_INVALID_OPERATION_HANDLE;
2817 }
2818 mOperationMap.removeOperation(token);
Chad Brubaker06801e02015-03-31 15:13:13 -07002819 int32_t rc;
Chad Brubaker40a1a9b2015-02-20 14:08:13 -08002820 if (!dev->abort) {
Chad Brubaker06801e02015-03-31 15:13:13 -07002821 rc = KM_ERROR_UNIMPLEMENTED;
2822 } else {
2823 rc = dev->abort(dev, handle);
Chad Brubaker40a1a9b2015-02-20 14:08:13 -08002824 }
Chad Brubaker06801e02015-03-31 15:13:13 -07002825 mAuthTokenTable.MarkCompleted(handle);
Chad Brubaker40a1a9b2015-02-20 14:08:13 -08002826 if (rc) {
2827 return rc;
2828 }
2829 return ::NO_ERROR;
Chad Brubaker9899d6b2015-02-03 13:03:00 -08002830 }
2831
Chad Brubaker2ed2baa2015-03-21 21:20:10 -07002832 bool isOperationAuthorized(const sp<IBinder>& token) {
2833 const keymaster1_device_t* dev;
2834 keymaster_operation_handle_t handle;
Chad Brubakerad6514a2015-04-09 14:00:26 -07002835 const keymaster_key_characteristics_t* characteristics;
Shawn Willdenb2ffa422015-06-17 12:18:55 -06002836 keymaster_purpose_t purpose;
Shawn Willden9221bff2015-06-18 18:23:54 -06002837 keymaster::km_id_t keyid;
2838 if (!mOperationMap.getOperation(token, &handle, &keyid, &purpose, &dev, &characteristics)) {
Chad Brubaker2ed2baa2015-03-21 21:20:10 -07002839 return false;
2840 }
Chad Brubaker0cf34a22015-04-23 11:06:16 -07002841 const hw_auth_token_t* authToken = NULL;
2842 mOperationMap.getOperationAuthToken(token, &authToken);
Chad Brubaker06801e02015-03-31 15:13:13 -07002843 std::vector<keymaster_key_param_t> ignored;
Chad Brubaker0cf34a22015-04-23 11:06:16 -07002844 int32_t authResult = addOperationAuthTokenIfNeeded(token, &ignored);
2845 return authResult == ::NO_ERROR;
Chad Brubaker2ed2baa2015-03-21 21:20:10 -07002846 }
2847
Chad Brubakerd80c7b42015-03-31 11:04:28 -07002848 int32_t addAuthToken(const uint8_t* token, size_t length) {
Chad Brubaker9489b792015-04-14 11:01:45 -07002849 if (!checkBinderPermission(P_ADD_AUTH)) {
2850 ALOGW("addAuthToken: permission denied for %d",
2851 IPCThreadState::self()->getCallingUid());
Chad Brubakerd80c7b42015-03-31 11:04:28 -07002852 return ::PERMISSION_DENIED;
2853 }
2854 if (length != sizeof(hw_auth_token_t)) {
2855 return KM_ERROR_INVALID_ARGUMENT;
2856 }
2857 hw_auth_token_t* authToken = new hw_auth_token_t;
2858 memcpy(reinterpret_cast<void*>(authToken), token, sizeof(hw_auth_token_t));
2859 // The table takes ownership of authToken.
2860 mAuthTokenTable.AddAuthenticationToken(authToken);
2861 return ::NO_ERROR;
Chad Brubaker2ed2baa2015-03-21 21:20:10 -07002862 }
2863
Kenny Root07438c82012-11-02 15:41:02 -07002864private:
Chad Brubaker9489b792015-04-14 11:01:45 -07002865 static const int32_t UID_SELF = -1;
2866
2867 /**
2868 * Get the effective target uid for a binder operation that takes an
2869 * optional uid as the target.
2870 */
2871 inline uid_t getEffectiveUid(int32_t targetUid) {
2872 if (targetUid == UID_SELF) {
2873 return IPCThreadState::self()->getCallingUid();
2874 }
2875 return static_cast<uid_t>(targetUid);
2876 }
2877
2878 /**
2879 * Check if the caller of the current binder method has the required
2880 * permission and if acting on other uids the grants to do so.
2881 */
2882 inline bool checkBinderPermission(perm_t permission, int32_t targetUid = UID_SELF) {
2883 uid_t callingUid = IPCThreadState::self()->getCallingUid();
2884 pid_t spid = IPCThreadState::self()->getCallingPid();
2885 if (!has_permission(callingUid, permission, spid)) {
2886 ALOGW("permission %s denied for %d", get_perm_label(permission), callingUid);
2887 return false;
2888 }
2889 if (!is_granted_to(callingUid, getEffectiveUid(targetUid))) {
2890 ALOGW("uid %d not granted to act for %d", callingUid, targetUid);
2891 return false;
2892 }
2893 return true;
2894 }
2895
2896 /**
2897 * Check if the caller of the current binder method has the required
Chad Brubakerb37a5232015-05-01 10:21:27 -07002898 * permission and the target uid is the caller or the caller is system.
2899 */
2900 inline bool checkBinderPermissionSelfOrSystem(perm_t permission, int32_t targetUid) {
2901 uid_t callingUid = IPCThreadState::self()->getCallingUid();
2902 pid_t spid = IPCThreadState::self()->getCallingPid();
2903 if (!has_permission(callingUid, permission, spid)) {
2904 ALOGW("permission %s denied for %d", get_perm_label(permission), callingUid);
2905 return false;
2906 }
2907 return getEffectiveUid(targetUid) == callingUid || callingUid == AID_SYSTEM;
2908 }
2909
2910 /**
2911 * Check if the caller of the current binder method has the required
Chad Brubaker9489b792015-04-14 11:01:45 -07002912 * permission or the target of the operation is the caller's uid. This is
2913 * for operation where the permission is only for cross-uid activity and all
2914 * uids are allowed to act on their own (ie: clearing all entries for a
2915 * given uid).
2916 */
2917 inline bool checkBinderPermissionOrSelfTarget(perm_t permission, int32_t targetUid) {
2918 uid_t callingUid = IPCThreadState::self()->getCallingUid();
2919 if (getEffectiveUid(targetUid) == callingUid) {
2920 return true;
2921 } else {
2922 return checkBinderPermission(permission, targetUid);
2923 }
2924 }
2925
2926 /**
2927 * Helper method to check that the caller has the required permission as
2928 * well as the keystore is in the unlocked state if checkUnlocked is true.
2929 *
2930 * Returns NO_ERROR on success, PERMISSION_DENIED on a permission error and
2931 * otherwise the state of keystore when not unlocked and checkUnlocked is
2932 * true.
2933 */
2934 inline int32_t checkBinderPermissionAndKeystoreState(perm_t permission, int32_t targetUid = -1,
2935 bool checkUnlocked = true) {
2936 if (!checkBinderPermission(permission, targetUid)) {
2937 return ::PERMISSION_DENIED;
2938 }
Chad Brubaker72593ee2015-05-12 10:42:00 -07002939 State state = mKeyStore->getState(get_user_id(getEffectiveUid(targetUid)));
Chad Brubaker9489b792015-04-14 11:01:45 -07002940 if (checkUnlocked && !isKeystoreUnlocked(state)) {
2941 return state;
2942 }
2943
2944 return ::NO_ERROR;
2945
2946 }
2947
Kenny Root9d45d1c2013-02-14 10:32:30 -08002948 inline bool isKeystoreUnlocked(State state) {
2949 switch (state) {
2950 case ::STATE_NO_ERROR:
2951 return true;
2952 case ::STATE_UNINITIALIZED:
2953 case ::STATE_LOCKED:
2954 return false;
2955 }
2956 return false;
Kenny Root07438c82012-11-02 15:41:02 -07002957 }
2958
Chad Brubaker67d2a502015-03-11 17:21:18 +00002959 bool isKeyTypeSupported(const keymaster1_device_t* device, keymaster_keypair_t keyType) {
Kenny Root1d448c02013-11-21 10:36:53 -08002960 const int32_t device_api = device->common.module->module_api_version;
2961 if (device_api == KEYMASTER_MODULE_API_VERSION_0_2) {
2962 switch (keyType) {
2963 case TYPE_RSA:
2964 case TYPE_DSA:
2965 case TYPE_EC:
2966 return true;
2967 default:
2968 return false;
2969 }
2970 } else if (device_api >= KEYMASTER_MODULE_API_VERSION_0_3) {
2971 switch (keyType) {
2972 case TYPE_RSA:
2973 return true;
2974 case TYPE_DSA:
2975 return device->flags & KEYMASTER_SUPPORTS_DSA;
2976 case TYPE_EC:
2977 return device->flags & KEYMASTER_SUPPORTS_EC;
2978 default:
2979 return false;
2980 }
2981 } else {
2982 return keyType == TYPE_RSA;
2983 }
2984 }
2985
Chad Brubaker0cf34a22015-04-23 11:06:16 -07002986 /**
2987 * Check that all keymaster_key_param_t's provided by the application are
2988 * allowed. Any parameter that keystore adds itself should be disallowed here.
2989 */
2990 bool checkAllowedOperationParams(const std::vector<keymaster_key_param_t>& params) {
2991 for (auto param: params) {
2992 switch (param.tag) {
2993 case KM_TAG_AUTH_TOKEN:
2994 return false;
2995 default:
2996 break;
2997 }
2998 }
2999 return true;
3000 }
3001
3002 keymaster_error_t getOperationCharacteristics(const keymaster_key_blob_t& key,
3003 const keymaster1_device_t* dev,
3004 const std::vector<keymaster_key_param_t>& params,
3005 keymaster_key_characteristics_t* out) {
3006 UniquePtr<keymaster_blob_t> appId;
3007 UniquePtr<keymaster_blob_t> appData;
3008 for (auto param : params) {
3009 if (param.tag == KM_TAG_APPLICATION_ID) {
3010 appId.reset(new keymaster_blob_t);
3011 appId->data = param.blob.data;
3012 appId->data_length = param.blob.data_length;
3013 } else if (param.tag == KM_TAG_APPLICATION_DATA) {
3014 appData.reset(new keymaster_blob_t);
3015 appData->data = param.blob.data;
3016 appData->data_length = param.blob.data_length;
3017 }
3018 }
3019 keymaster_key_characteristics_t* result = NULL;
3020 if (!dev->get_key_characteristics) {
3021 return KM_ERROR_UNIMPLEMENTED;
3022 }
3023 keymaster_error_t error = dev->get_key_characteristics(dev, &key, appId.get(),
3024 appData.get(), &result);
3025 if (result) {
3026 *out = *result;
3027 free(result);
3028 }
3029 return error;
3030 }
3031
3032 /**
3033 * Get the auth token for this operation from the auth token table.
3034 *
3035 * Returns ::NO_ERROR if the auth token was set or none was required.
3036 * ::OP_AUTH_NEEDED if it is a per op authorization, no
3037 * authorization token exists for that operation and
3038 * failOnTokenMissing is false.
3039 * KM_ERROR_KEY_USER_NOT_AUTHENTICATED if there is no valid auth
3040 * token for the operation
3041 */
3042 int32_t getAuthToken(const keymaster_key_characteristics_t* characteristics,
3043 keymaster_operation_handle_t handle,
Shawn Willdenb2ffa422015-06-17 12:18:55 -06003044 keymaster_purpose_t purpose,
Chad Brubaker0cf34a22015-04-23 11:06:16 -07003045 const hw_auth_token_t** authToken,
3046 bool failOnTokenMissing = true) {
3047
3048 std::vector<keymaster_key_param_t> allCharacteristics;
3049 for (size_t i = 0; i < characteristics->sw_enforced.length; i++) {
3050 allCharacteristics.push_back(characteristics->sw_enforced.params[i]);
3051 }
3052 for (size_t i = 0; i < characteristics->hw_enforced.length; i++) {
3053 allCharacteristics.push_back(characteristics->hw_enforced.params[i]);
3054 }
Shawn Willdenb2ffa422015-06-17 12:18:55 -06003055 keymaster::AuthTokenTable::Error err = mAuthTokenTable.FindAuthorization(
3056 allCharacteristics.data(), allCharacteristics.size(), purpose, handle, authToken);
Chad Brubaker0cf34a22015-04-23 11:06:16 -07003057 switch (err) {
3058 case keymaster::AuthTokenTable::OK:
3059 case keymaster::AuthTokenTable::AUTH_NOT_REQUIRED:
3060 return ::NO_ERROR;
3061 case keymaster::AuthTokenTable::AUTH_TOKEN_NOT_FOUND:
3062 case keymaster::AuthTokenTable::AUTH_TOKEN_EXPIRED:
3063 case keymaster::AuthTokenTable::AUTH_TOKEN_WRONG_SID:
3064 return KM_ERROR_KEY_USER_NOT_AUTHENTICATED;
3065 case keymaster::AuthTokenTable::OP_HANDLE_REQUIRED:
3066 return failOnTokenMissing ? (int32_t) KM_ERROR_KEY_USER_NOT_AUTHENTICATED :
3067 (int32_t) ::OP_AUTH_NEEDED;
3068 default:
3069 ALOGE("Unexpected FindAuthorization return value %d", err);
3070 return KM_ERROR_INVALID_ARGUMENT;
3071 }
3072 }
3073
3074 inline void addAuthToParams(std::vector<keymaster_key_param_t>* params,
3075 const hw_auth_token_t* token) {
3076 if (token) {
3077 params->push_back(keymaster_param_blob(KM_TAG_AUTH_TOKEN,
3078 reinterpret_cast<const uint8_t*>(token),
3079 sizeof(hw_auth_token_t)));
3080 }
3081 }
3082
3083 /**
3084 * Add the auth token for the operation to the param list if the operation
3085 * requires authorization. Uses the cached result in the OperationMap if available
3086 * otherwise gets the token from the AuthTokenTable and caches the result.
3087 *
3088 * Returns ::NO_ERROR if the auth token was added or not needed.
3089 * KM_ERROR_KEY_USER_NOT_AUTHENTICATED if the operation is not
3090 * authenticated.
3091 * KM_ERROR_INVALID_OPERATION_HANDLE if token is not a valid
3092 * operation token.
3093 */
3094 int32_t addOperationAuthTokenIfNeeded(sp<IBinder> token,
3095 std::vector<keymaster_key_param_t>* params) {
3096 const hw_auth_token_t* authToken = NULL;
Chad Brubaker7169a842015-04-29 19:58:34 -07003097 mOperationMap.getOperationAuthToken(token, &authToken);
3098 if (!authToken) {
Chad Brubaker0cf34a22015-04-23 11:06:16 -07003099 const keymaster1_device_t* dev;
3100 keymaster_operation_handle_t handle;
3101 const keymaster_key_characteristics_t* characteristics = NULL;
Shawn Willdenb2ffa422015-06-17 12:18:55 -06003102 keymaster_purpose_t purpose;
Shawn Willden9221bff2015-06-18 18:23:54 -06003103 keymaster::km_id_t keyid;
3104 if (!mOperationMap.getOperation(token, &handle, &keyid, &purpose, &dev,
3105 &characteristics)) {
Chad Brubaker0cf34a22015-04-23 11:06:16 -07003106 return KM_ERROR_INVALID_OPERATION_HANDLE;
3107 }
Shawn Willdenb2ffa422015-06-17 12:18:55 -06003108 int32_t result = getAuthToken(characteristics, handle, purpose, &authToken);
Chad Brubaker0cf34a22015-04-23 11:06:16 -07003109 if (result != ::NO_ERROR) {
3110 return result;
3111 }
3112 if (authToken) {
3113 mOperationMap.setOperationAuthToken(token, authToken);
3114 }
3115 }
3116 addAuthToParams(params, authToken);
3117 return ::NO_ERROR;
3118 }
3119
Chad Brubaker3a7d9e62015-06-04 15:01:46 -07003120 /**
3121 * Translate a result value to a legacy return value. All keystore errors are
3122 * preserved and keymaster errors become SYSTEM_ERRORs
3123 */
3124 inline int32_t translateResultToLegacyResult(int32_t result) {
3125 if (result > 0) {
3126 return result;
3127 }
3128 return ::SYSTEM_ERROR;
3129 }
3130
Chad Brubaker3a7d9e62015-06-04 15:01:46 -07003131 keymaster_key_param_t* getKeyAlgorithm(keymaster_key_characteristics_t* characteristics) {
3132 for (size_t i = 0; i < characteristics->hw_enforced.length; i++) {
3133 if (characteristics->hw_enforced.params[i].tag == KM_TAG_ALGORITHM) {
3134 return &characteristics->hw_enforced.params[i];
3135 }
3136 }
3137 for (size_t i = 0; i < characteristics->sw_enforced.length; i++) {
3138 if (characteristics->sw_enforced.params[i].tag == KM_TAG_ALGORITHM) {
3139 return &characteristics->sw_enforced.params[i];
3140 }
3141 }
3142 return NULL;
3143 }
3144
3145 void addLegacyBeginParams(const String16& name, std::vector<keymaster_key_param_t>& params) {
3146 // All legacy keys are DIGEST_NONE/PAD_NONE.
3147 params.push_back(keymaster_param_enum(KM_TAG_DIGEST, KM_DIGEST_NONE));
3148 params.push_back(keymaster_param_enum(KM_TAG_PADDING, KM_PAD_NONE));
3149
3150 // Look up the algorithm of the key.
3151 KeyCharacteristics characteristics;
3152 int32_t rc = getKeyCharacteristics(name, NULL, NULL, &characteristics);
3153 if (rc != ::NO_ERROR) {
3154 ALOGE("Failed to get key characteristics");
3155 return;
3156 }
3157 keymaster_key_param_t* algorithm = getKeyAlgorithm(&characteristics.characteristics);
3158 if (!algorithm) {
3159 ALOGE("getKeyCharacteristics did not include KM_TAG_ALGORITHM");
3160 return;
3161 }
3162 params.push_back(*algorithm);
3163 }
3164
3165 int32_t doLegacySignVerify(const String16& name, const uint8_t* data, size_t length,
3166 uint8_t** out, size_t* outLength, const uint8_t* signature,
3167 size_t signatureLength, keymaster_purpose_t purpose) {
3168
Chad Brubaker3a7d9e62015-06-04 15:01:46 -07003169 std::basic_stringstream<uint8_t> outBuffer;
3170 OperationResult result;
3171 KeymasterArguments inArgs;
3172 addLegacyBeginParams(name, inArgs.params);
3173 sp<IBinder> appToken(new BBinder);
3174 sp<IBinder> token;
3175
3176 begin(appToken, name, purpose, true, inArgs, NULL, 0, &result);
3177 if (result.resultCode != ResponseCode::NO_ERROR) {
Chad Brubakerdf705172015-06-17 20:17:51 -07003178 if (result.resultCode == ::KEY_NOT_FOUND) {
3179 ALOGW("Key not found");
3180 } else {
3181 ALOGW("Error in begin: %d", result.resultCode);
3182 }
Chad Brubaker3a7d9e62015-06-04 15:01:46 -07003183 return translateResultToLegacyResult(result.resultCode);
3184 }
3185 inArgs.params.clear();
3186 token = result.token;
3187 size_t consumed = 0;
3188 size_t lastConsumed = 0;
3189 do {
3190 update(token, inArgs, data + consumed, length - consumed, &result);
3191 if (result.resultCode != ResponseCode::NO_ERROR) {
3192 ALOGW("Error in update: %d", result.resultCode);
3193 return translateResultToLegacyResult(result.resultCode);
3194 }
3195 if (out) {
3196 outBuffer.write(result.data.get(), result.dataLength);
3197 }
3198 lastConsumed = result.inputConsumed;
3199 consumed += lastConsumed;
3200 } while (consumed < length && lastConsumed > 0);
3201
3202 if (consumed != length) {
3203 ALOGW("Not all data consumed. Consumed %zu of %zu", consumed, length);
3204 return ::SYSTEM_ERROR;
3205 }
3206
3207 finish(token, inArgs, signature, signatureLength, NULL, 0, &result);
3208 if (result.resultCode != ResponseCode::NO_ERROR) {
3209 ALOGW("Error in finish: %d", result.resultCode);
3210 return translateResultToLegacyResult(result.resultCode);
3211 }
3212 if (out) {
3213 outBuffer.write(result.data.get(), result.dataLength);
3214 }
3215
3216 if (out) {
3217 auto buf = outBuffer.str();
3218 *out = new uint8_t[buf.size()];
3219 memcpy(*out, buf.c_str(), buf.size());
3220 *outLength = buf.size();
3221 }
3222
3223 return ::NO_ERROR;
3224 }
3225
Kenny Root07438c82012-11-02 15:41:02 -07003226 ::KeyStore* mKeyStore;
Chad Brubaker40a1a9b2015-02-20 14:08:13 -08003227 OperationMap mOperationMap;
Chad Brubakerd80c7b42015-03-31 11:04:28 -07003228 keymaster::AuthTokenTable mAuthTokenTable;
Shawn Willden9221bff2015-06-18 18:23:54 -06003229 KeystoreKeymasterEnforcement enforcement_policy;
Kenny Root07438c82012-11-02 15:41:02 -07003230};
3231
3232}; // namespace android
Kenny Roota91203b2012-02-15 15:00:46 -08003233
3234int main(int argc, char* argv[]) {
Kenny Roota91203b2012-02-15 15:00:46 -08003235 if (argc < 2) {
3236 ALOGE("A directory must be specified!");
3237 return 1;
3238 }
3239 if (chdir(argv[1]) == -1) {
3240 ALOGE("chdir: %s: %s", argv[1], strerror(errno));
3241 return 1;
3242 }
3243
3244 Entropy entropy;
3245 if (!entropy.open()) {
3246 return 1;
3247 }
Kenny Root70e3a862012-02-15 17:20:23 -08003248
Chad Brubakerbd07a232015-06-01 10:44:27 -07003249 keymaster1_device_t* dev;
Kenny Root70e3a862012-02-15 17:20:23 -08003250 if (keymaster_device_initialize(&dev)) {
3251 ALOGE("keystore keymaster could not be initialized; exiting");
3252 return 1;
3253 }
3254
Chad Brubaker67d2a502015-03-11 17:21:18 +00003255 keymaster1_device_t* fallback;
Chad Brubakerfc18edc2015-01-12 15:17:18 -08003256 if (fallback_keymaster_device_initialize(&fallback)) {
3257 ALOGE("software keymaster could not be initialized; exiting");
3258 return 1;
3259 }
3260
Riley Spahneaabae92014-06-30 12:39:52 -07003261 ks_is_selinux_enabled = is_selinux_enabled();
3262 if (ks_is_selinux_enabled) {
3263 union selinux_callback cb;
3264 cb.func_log = selinux_log_callback;
3265 selinux_set_callback(SELINUX_CB_LOG, cb);
3266 if (getcon(&tctx) != 0) {
3267 ALOGE("SELinux: Could not acquire target context. Aborting keystore.\n");
3268 return -1;
3269 }
3270 } else {
3271 ALOGI("SELinux: Keystore SELinux is disabled.\n");
3272 }
3273
Chad Brubakerbd07a232015-06-01 10:44:27 -07003274 KeyStore keyStore(&entropy, dev, fallback);
Kenny Root655b9582013-04-04 08:37:42 -07003275 keyStore.initialize();
Kenny Root07438c82012-11-02 15:41:02 -07003276 android::sp<android::IServiceManager> sm = android::defaultServiceManager();
3277 android::sp<android::KeyStoreProxy> proxy = new android::KeyStoreProxy(&keyStore);
3278 android::status_t ret = sm->addService(android::String16("android.security.keystore"), proxy);
3279 if (ret != android::OK) {
3280 ALOGE("Couldn't register binder service!");
3281 return -1;
Kenny Roota91203b2012-02-15 15:00:46 -08003282 }
Kenny Root07438c82012-11-02 15:41:02 -07003283
3284 /*
3285 * We're the only thread in existence, so we're just going to process
3286 * Binder transaction as a single-threaded program.
3287 */
3288 android::IPCThreadState::self()->joinThreadPool();
Kenny Root70e3a862012-02-15 17:20:23 -08003289
3290 keymaster_device_release(dev);
Kenny Roota91203b2012-02-15 15:00:46 -08003291 return 1;
3292}