blob: 9c1e92c6154c9320b57c08e89d20f9713cecf672 [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 Willden7e8eabb2015-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 Willden7e8eabb2015-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 Willden7e8eabb2015-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 Willden7e8eabb2015-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 Willden7e8eabb2015-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 Willden7e8eabb2015-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 Willden7e8eabb2015-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 Willden7e8eabb2015-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 Willden7e8eabb2015-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 Willden7e8eabb2015-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);
Zhen Kong52415c52015-09-30 18:42:58 -07001307 if (rc != NO_ERROR) {
1308 return rc;
1309 }
1310
1311 rc = keyBlob->readBlob(filename, userState->getDecryptionKey(),
1312 userState->getState());
1313 if (rc != NO_ERROR) {
1314 return rc;
1315 }
Chad Brubaker3cc40122015-06-04 13:49:44 -07001316 }
1317
Kenny Rootd53bc922013-03-21 14:10:15 -07001318 if (type != TYPE_ANY && keyBlob->getType() != type) {
Kenny Root822c3a92012-03-23 16:34:39 -07001319 ALOGW("key found but type doesn't match: %d vs %d", keyBlob->getType(), type);
1320 return KEY_NOT_FOUND;
1321 }
1322
1323 return rc;
Kenny Roota91203b2012-02-15 15:00:46 -08001324 }
1325
Chad Brubaker72593ee2015-05-12 10:42:00 -07001326 ResponseCode put(const char* filename, Blob* keyBlob, uid_t userId) {
1327 UserState* userState = getUserState(userId);
Kenny Rootf9119d62013-04-03 09:22:15 -07001328 return keyBlob->writeBlob(filename, userState->getEncryptionKey(), userState->getState(),
1329 mEntropy);
Kenny Roota91203b2012-02-15 15:00:46 -08001330 }
1331
Chad Brubaker72593ee2015-05-12 10:42:00 -07001332 ResponseCode del(const char *filename, const BlobType type, uid_t userId) {
Robin Lee4b84fdc2014-09-24 11:56:57 +01001333 Blob keyBlob;
Chad Brubaker72593ee2015-05-12 10:42:00 -07001334 ResponseCode rc = get(filename, &keyBlob, type, userId);
Chad Brubakera9a17ee2015-07-17 13:43:24 -07001335 if (rc == ::VALUE_CORRUPTED) {
1336 // The file is corrupt, the best we can do is rm it.
1337 return (unlink(filename) && errno != ENOENT) ? ::SYSTEM_ERROR : ::NO_ERROR;
1338 }
Robin Lee4b84fdc2014-09-24 11:56:57 +01001339 if (rc != ::NO_ERROR) {
1340 return rc;
1341 }
1342
1343 if (keyBlob.getType() == ::TYPE_KEY_PAIR) {
Shawn Willden7e8eabb2015-07-28 11:06:00 -06001344 // A device doesn't have to implement delete_key.
1345 if (mDevice->delete_key != NULL && !keyBlob.isFallback()) {
1346 keymaster_key_blob_t blob = {keyBlob.getValue(),
1347 static_cast<size_t>(keyBlob.getLength())};
1348 if (mDevice->delete_key(mDevice, &blob)) {
Robin Lee4b84fdc2014-09-24 11:56:57 +01001349 rc = ::SYSTEM_ERROR;
1350 }
1351 }
1352 }
Chad Brubaker17d68b92015-02-05 22:04:16 -08001353 if (keyBlob.getType() == ::TYPE_KEYMASTER_10) {
1354 keymaster1_device_t* dev = getDeviceForBlob(keyBlob);
1355 if (dev->delete_key) {
1356 keymaster_key_blob_t blob;
1357 blob.key_material = keyBlob.getValue();
1358 blob.key_material_size = keyBlob.getLength();
1359 dev->delete_key(dev, &blob);
1360 }
1361 }
Robin Lee4b84fdc2014-09-24 11:56:57 +01001362 if (rc != ::NO_ERROR) {
1363 return rc;
1364 }
1365
1366 return (unlink(filename) && errno != ENOENT) ? ::SYSTEM_ERROR : ::NO_ERROR;
1367 }
1368
Chad Brubakere6c3bfa2015-05-12 15:18:26 -07001369 ResponseCode list(const android::String8& prefix, android::Vector<android::String16> *matches,
Chad Brubaker72593ee2015-05-12 10:42:00 -07001370 uid_t userId) {
Robin Lee4b84fdc2014-09-24 11:56:57 +01001371
Chad Brubaker72593ee2015-05-12 10:42:00 -07001372 UserState* userState = getUserState(userId);
Robin Lee4b84fdc2014-09-24 11:56:57 +01001373 size_t n = prefix.length();
1374
1375 DIR* dir = opendir(userState->getUserDirName());
1376 if (!dir) {
1377 ALOGW("can't open directory for user: %s", strerror(errno));
1378 return ::SYSTEM_ERROR;
1379 }
1380
1381 struct dirent* file;
1382 while ((file = readdir(dir)) != NULL) {
1383 // We only care about files.
1384 if (file->d_type != DT_REG) {
1385 continue;
1386 }
1387
1388 // Skip anything that starts with a "."
1389 if (file->d_name[0] == '.') {
1390 continue;
1391 }
1392
1393 if (!strncmp(prefix.string(), file->d_name, n)) {
1394 const char* p = &file->d_name[n];
1395 size_t plen = strlen(p);
1396
1397 size_t extra = decode_key_length(p, plen);
1398 char *match = (char*) malloc(extra + 1);
1399 if (match != NULL) {
1400 decode_key(match, p, plen);
1401 matches->push(android::String16(match, extra));
1402 free(match);
1403 } else {
1404 ALOGW("could not allocate match of size %zd", extra);
1405 }
1406 }
1407 }
1408 closedir(dir);
1409 return ::NO_ERROR;
1410 }
1411
Kenny Root07438c82012-11-02 15:41:02 -07001412 void addGrant(const char* filename, uid_t granteeUid) {
Kenny Root655b9582013-04-04 08:37:42 -07001413 const grant_t* existing = getGrant(filename, granteeUid);
1414 if (existing == NULL) {
1415 grant_t* grant = new grant_t;
Kenny Root07438c82012-11-02 15:41:02 -07001416 grant->uid = granteeUid;
Brian Carlstroma8c703d2012-07-17 14:43:46 -07001417 grant->filename = reinterpret_cast<const uint8_t*>(strdup(filename));
Kenny Root655b9582013-04-04 08:37:42 -07001418 mGrants.add(grant);
Kenny Root70e3a862012-02-15 17:20:23 -08001419 }
1420 }
1421
Kenny Root07438c82012-11-02 15:41:02 -07001422 bool removeGrant(const char* filename, uid_t granteeUid) {
Kenny Root655b9582013-04-04 08:37:42 -07001423 for (android::Vector<grant_t*>::iterator it(mGrants.begin());
1424 it != mGrants.end(); it++) {
1425 grant_t* grant = *it;
1426 if (grant->uid == granteeUid
1427 && !strcmp(reinterpret_cast<const char*>(grant->filename), filename)) {
1428 mGrants.erase(it);
1429 return true;
1430 }
Kenny Root70e3a862012-02-15 17:20:23 -08001431 }
Kenny Root70e3a862012-02-15 17:20:23 -08001432 return false;
1433 }
1434
Brian Carlstroma8c703d2012-07-17 14:43:46 -07001435 bool hasGrant(const char* filename, const uid_t uid) const {
1436 return getGrant(filename, uid) != NULL;
Kenny Root70e3a862012-02-15 17:20:23 -08001437 }
1438
Chad Brubaker72593ee2015-05-12 10:42:00 -07001439 ResponseCode importKey(const uint8_t* key, size_t keyLen, const char* filename, uid_t userId,
Kenny Rootf9119d62013-04-03 09:22:15 -07001440 int32_t flags) {
Shawn Willden7e8eabb2015-07-28 11:06:00 -06001441 Unique_PKCS8_PRIV_KEY_INFO pkcs8(d2i_PKCS8_PRIV_KEY_INFO(NULL, &key, keyLen));
1442 if (!pkcs8.get()) {
1443 return ::SYSTEM_ERROR;
1444 }
1445 Unique_EVP_PKEY pkey(EVP_PKCS82PKEY(pkcs8.get()));
1446 if (!pkey.get()) {
1447 return ::SYSTEM_ERROR;
1448 }
1449 int type = EVP_PKEY_type(pkey->type);
1450 android::KeymasterArguments params;
1451 add_legacy_key_authorizations(type, &params.params);
1452 switch (type) {
1453 case EVP_PKEY_RSA:
1454 params.params.push_back(keymaster_param_enum(KM_TAG_ALGORITHM, KM_ALGORITHM_RSA));
1455 break;
1456 case EVP_PKEY_EC:
1457 params.params.push_back(keymaster_param_enum(KM_TAG_ALGORITHM,
1458 KM_ALGORITHM_EC));
1459 break;
1460 default:
1461 ALOGW("Unsupported key type %d", type);
1462 return ::SYSTEM_ERROR;
Kenny Root822c3a92012-03-23 16:34:39 -07001463 }
1464
Shawn Willden7e8eabb2015-07-28 11:06:00 -06001465 std::vector<keymaster_key_param_t> opParams(params.params);
1466 const keymaster_key_param_set_t inParams = {opParams.data(), opParams.size()};
1467 keymaster_blob_t input = {key, keyLen};
1468 keymaster_key_blob_t blob = {nullptr, 0};
Kenny Root17208e02013-09-04 13:56:03 -07001469 bool isFallback = false;
Shawn Willden7e8eabb2015-07-28 11:06:00 -06001470 keymaster_error_t error = mDevice->import_key(mDevice, &inParams, KM_KEY_FORMAT_PKCS8,
1471 &input, &blob, NULL /* characteristics */);
1472 if (error != KM_ERROR_OK){
1473 ALOGE("Keymaster error %d importing key pair, falling back", error);
1474
Kenny Roota39da5a2014-09-25 13:07:24 -07001475 /*
Shawn Willden7e8eabb2015-07-28 11:06:00 -06001476 * There should be no way to get here. Fallback shouldn't ever really happen
1477 * because the main device may be many (SW, KM0/SW hybrid, KM1/SW hybrid), but it must
1478 * provide full support of the API. In any case, we'll do the fallback just for
1479 * consistency... and I suppose to cover for broken HW implementations.
Kenny Roota39da5a2014-09-25 13:07:24 -07001480 */
Shawn Willden7e8eabb2015-07-28 11:06:00 -06001481 error = mFallbackDevice->import_key(mFallbackDevice, &inParams, KM_KEY_FORMAT_PKCS8,
1482 &input, &blob, NULL /* characteristics */);
Kenny Roota39da5a2014-09-25 13:07:24 -07001483 isFallback = true;
Kenny Root17208e02013-09-04 13:56:03 -07001484
Shawn Willden7e8eabb2015-07-28 11:06:00 -06001485 if (error) {
1486 ALOGE("Keymaster error while importing key pair with fallback: %d", error);
Kenny Root17208e02013-09-04 13:56:03 -07001487 return SYSTEM_ERROR;
1488 }
Kenny Root822c3a92012-03-23 16:34:39 -07001489 }
1490
Shawn Willden7e8eabb2015-07-28 11:06:00 -06001491 Blob keyBlob(blob.key_material, blob.key_material_size, NULL, 0, TYPE_KEYMASTER_10);
1492 free(const_cast<uint8_t*>(blob.key_material));
Kenny Root822c3a92012-03-23 16:34:39 -07001493
Kenny Rootf9119d62013-04-03 09:22:15 -07001494 keyBlob.setEncrypted(flags & KEYSTORE_FLAG_ENCRYPTED);
Kenny Root17208e02013-09-04 13:56:03 -07001495 keyBlob.setFallback(isFallback);
Kenny Rootf9119d62013-04-03 09:22:15 -07001496
Chad Brubaker72593ee2015-05-12 10:42:00 -07001497 return put(filename, &keyBlob, userId);
Kenny Root822c3a92012-03-23 16:34:39 -07001498 }
1499
Kenny Root1b0e3932013-09-05 13:06:32 -07001500 bool isHardwareBacked(const android::String16& keyType) const {
1501 if (mDevice == NULL) {
1502 ALOGW("can't get keymaster device");
1503 return false;
1504 }
1505
1506 if (sRSAKeyType == keyType) {
1507 return (mDevice->flags & KEYMASTER_SOFTWARE_ONLY) == 0;
1508 } else {
1509 return (mDevice->flags & KEYMASTER_SOFTWARE_ONLY) == 0
1510 && (mDevice->common.module->module_api_version
1511 >= KEYMASTER_MODULE_API_VERSION_0_2);
1512 }
Kenny Root8ddf35a2013-03-29 11:15:50 -07001513 }
1514
Kenny Root655b9582013-04-04 08:37:42 -07001515 ResponseCode getKeyForName(Blob* keyBlob, const android::String8& keyName, const uid_t uid,
1516 const BlobType type) {
Kenny Root86b16e82013-09-09 11:15:54 -07001517 android::String8 filepath8(getKeyNameForUidWithDir(keyName, uid));
Chad Brubaker72593ee2015-05-12 10:42:00 -07001518 uid_t userId = get_user_id(uid);
Kenny Root655b9582013-04-04 08:37:42 -07001519
Chad Brubaker72593ee2015-05-12 10:42:00 -07001520 ResponseCode 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 // If this is one of the legacy UID->UID mappings, use it.
1526 uid_t euid = get_keystore_euid(uid);
1527 if (euid != uid) {
Kenny Root86b16e82013-09-09 11:15:54 -07001528 filepath8 = getKeyNameForUidWithDir(keyName, euid);
Chad Brubaker72593ee2015-05-12 10:42:00 -07001529 responseCode = get(filepath8.string(), keyBlob, type, userId);
Kenny Root655b9582013-04-04 08:37:42 -07001530 if (responseCode == NO_ERROR) {
1531 return responseCode;
1532 }
1533 }
1534
1535 // They might be using a granted key.
Kenny Root86b16e82013-09-09 11:15:54 -07001536 android::String8 filename8 = getKeyName(keyName);
Kenny Root655b9582013-04-04 08:37:42 -07001537 char* end;
Kenny Root86b16e82013-09-09 11:15:54 -07001538 strtoul(filename8.string(), &end, 10);
Kenny Root655b9582013-04-04 08:37:42 -07001539 if (end[0] != '_' || end[1] == 0) {
1540 return KEY_NOT_FOUND;
1541 }
Chad Brubaker72593ee2015-05-12 10:42:00 -07001542 filepath8 = android::String8::format("%s/%s", getUserState(userId)->getUserDirName(),
Kenny Root86b16e82013-09-09 11:15:54 -07001543 filename8.string());
Kenny Root655b9582013-04-04 08:37:42 -07001544 if (!hasGrant(filepath8.string(), uid)) {
1545 return responseCode;
1546 }
1547
1548 // It is a granted key. Try to load it.
Chad Brubaker72593ee2015-05-12 10:42:00 -07001549 return get(filepath8.string(), keyBlob, type, userId);
Kenny Root655b9582013-04-04 08:37:42 -07001550 }
1551
1552 /**
1553 * Returns any existing UserState or creates it if it doesn't exist.
1554 */
Chad Brubaker72593ee2015-05-12 10:42:00 -07001555 UserState* getUserState(uid_t userId) {
Kenny Root655b9582013-04-04 08:37:42 -07001556 for (android::Vector<UserState*>::iterator it(mMasterKeys.begin());
1557 it != mMasterKeys.end(); it++) {
1558 UserState* state = *it;
1559 if (state->getUserId() == userId) {
1560 return state;
1561 }
1562 }
1563
1564 UserState* userState = new UserState(userId);
1565 if (!userState->initialize()) {
1566 /* There's not much we can do if initialization fails. Trying to
1567 * unlock the keystore for that user will fail as well, so any
1568 * subsequent request for this user will just return SYSTEM_ERROR.
1569 */
1570 ALOGE("User initialization failed for %u; subsuquent operations will fail", userId);
1571 }
1572 mMasterKeys.add(userState);
1573 return userState;
1574 }
1575
1576 /**
Chad Brubaker72593ee2015-05-12 10:42:00 -07001577 * Returns any existing UserState or creates it if it doesn't exist.
1578 */
1579 UserState* getUserStateByUid(uid_t uid) {
1580 uid_t userId = get_user_id(uid);
1581 return getUserState(userId);
1582 }
1583
1584 /**
Kenny Root655b9582013-04-04 08:37:42 -07001585 * Returns NULL if the UserState doesn't already exist.
1586 */
Chad Brubaker72593ee2015-05-12 10:42:00 -07001587 const UserState* getUserState(uid_t userId) const {
Kenny Root655b9582013-04-04 08:37:42 -07001588 for (android::Vector<UserState*>::const_iterator it(mMasterKeys.begin());
1589 it != mMasterKeys.end(); it++) {
1590 UserState* state = *it;
1591 if (state->getUserId() == userId) {
1592 return state;
1593 }
1594 }
1595
1596 return NULL;
1597 }
1598
Chad Brubaker72593ee2015-05-12 10:42:00 -07001599 /**
1600 * Returns NULL if the UserState doesn't already exist.
1601 */
1602 const UserState* getUserStateByUid(uid_t uid) const {
1603 uid_t userId = get_user_id(uid);
1604 return getUserState(userId);
1605 }
1606
Kenny Roota91203b2012-02-15 15:00:46 -08001607private:
Kenny Root655b9582013-04-04 08:37:42 -07001608 static const char* sOldMasterKey;
1609 static const char* sMetaDataFile;
Kenny Root1b0e3932013-09-05 13:06:32 -07001610 static const android::String16 sRSAKeyType;
Kenny Roota91203b2012-02-15 15:00:46 -08001611 Entropy* mEntropy;
1612
Chad Brubaker67d2a502015-03-11 17:21:18 +00001613 keymaster1_device_t* mDevice;
1614 keymaster1_device_t* mFallbackDevice;
Kenny Root70e3a862012-02-15 17:20:23 -08001615
Kenny Root655b9582013-04-04 08:37:42 -07001616 android::Vector<UserState*> mMasterKeys;
Kenny Roota91203b2012-02-15 15:00:46 -08001617
Kenny Root655b9582013-04-04 08:37:42 -07001618 android::Vector<grant_t*> mGrants;
Kenny Roota91203b2012-02-15 15:00:46 -08001619
Kenny Root655b9582013-04-04 08:37:42 -07001620 typedef struct {
1621 uint32_t version;
1622 } keystore_metadata_t;
Kenny Roota91203b2012-02-15 15:00:46 -08001623
Kenny Root655b9582013-04-04 08:37:42 -07001624 keystore_metadata_t mMetaData;
Kenny Root70e3a862012-02-15 17:20:23 -08001625
Kenny Root655b9582013-04-04 08:37:42 -07001626 const grant_t* getGrant(const char* filename, uid_t uid) const {
1627 for (android::Vector<grant_t*>::const_iterator it(mGrants.begin());
1628 it != mGrants.end(); it++) {
1629 grant_t* grant = *it;
Kenny Root70e3a862012-02-15 17:20:23 -08001630 if (grant->uid == uid
Kenny Root655b9582013-04-04 08:37:42 -07001631 && !strcmp(reinterpret_cast<const char*>(grant->filename), filename)) {
Kenny Root70e3a862012-02-15 17:20:23 -08001632 return grant;
1633 }
1634 }
Kenny Root70e3a862012-02-15 17:20:23 -08001635 return NULL;
1636 }
1637
Kenny Root822c3a92012-03-23 16:34:39 -07001638 /**
1639 * Upgrade code. This will upgrade the key from the current version
1640 * to whatever is newest.
1641 */
Kenny Root655b9582013-04-04 08:37:42 -07001642 bool upgradeBlob(const char* filename, Blob* blob, const uint8_t oldVersion,
1643 const BlobType type, uid_t uid) {
Kenny Root822c3a92012-03-23 16:34:39 -07001644 bool updated = false;
1645 uint8_t version = oldVersion;
1646
1647 /* From V0 -> V1: All old types were unknown */
1648 if (version == 0) {
1649 ALOGV("upgrading to version 1 and setting type %d", type);
1650
1651 blob->setType(type);
1652 if (type == TYPE_KEY_PAIR) {
Kenny Root655b9582013-04-04 08:37:42 -07001653 importBlobAsKey(blob, filename, uid);
Kenny Root822c3a92012-03-23 16:34:39 -07001654 }
1655 version = 1;
1656 updated = true;
1657 }
1658
Kenny Rootf9119d62013-04-03 09:22:15 -07001659 /* From V1 -> V2: All old keys were encrypted */
1660 if (version == 1) {
1661 ALOGV("upgrading to version 2");
1662
1663 blob->setEncrypted(true);
1664 version = 2;
1665 updated = true;
1666 }
1667
Kenny Root822c3a92012-03-23 16:34:39 -07001668 /*
1669 * If we've updated, set the key blob to the right version
1670 * and write it.
Kenny Rootcfeae072013-04-04 08:39:57 -07001671 */
Kenny Root822c3a92012-03-23 16:34:39 -07001672 if (updated) {
1673 ALOGV("updated and writing file %s", filename);
1674 blob->setVersion(version);
Kenny Root822c3a92012-03-23 16:34:39 -07001675 }
Kenny Rootcfeae072013-04-04 08:39:57 -07001676
1677 return updated;
Kenny Root822c3a92012-03-23 16:34:39 -07001678 }
1679
1680 /**
1681 * Takes a blob that is an PEM-encoded RSA key as a byte array and
1682 * converts it to a DER-encoded PKCS#8 for import into a keymaster.
1683 * Then it overwrites the original blob with the new blob
1684 * format that is returned from the keymaster.
1685 */
Kenny Root655b9582013-04-04 08:37:42 -07001686 ResponseCode importBlobAsKey(Blob* blob, const char* filename, uid_t uid) {
Kenny Root822c3a92012-03-23 16:34:39 -07001687 // We won't even write to the blob directly with this BIO, so const_cast is okay.
1688 Unique_BIO b(BIO_new_mem_buf(const_cast<uint8_t*>(blob->getValue()), blob->getLength()));
1689 if (b.get() == NULL) {
1690 ALOGE("Problem instantiating BIO");
1691 return SYSTEM_ERROR;
1692 }
1693
1694 Unique_EVP_PKEY pkey(PEM_read_bio_PrivateKey(b.get(), NULL, NULL, NULL));
1695 if (pkey.get() == NULL) {
1696 ALOGE("Couldn't read old PEM file");
1697 return SYSTEM_ERROR;
1698 }
1699
1700 Unique_PKCS8_PRIV_KEY_INFO pkcs8(EVP_PKEY2PKCS8(pkey.get()));
1701 int len = i2d_PKCS8_PRIV_KEY_INFO(pkcs8.get(), NULL);
1702 if (len < 0) {
1703 ALOGE("Couldn't measure PKCS#8 length");
1704 return SYSTEM_ERROR;
1705 }
1706
Kenny Root70c98892013-02-07 09:10:36 -08001707 UniquePtr<unsigned char[]> pkcs8key(new unsigned char[len]);
1708 uint8_t* tmp = pkcs8key.get();
Kenny Root822c3a92012-03-23 16:34:39 -07001709 if (i2d_PKCS8_PRIV_KEY_INFO(pkcs8.get(), &tmp) != len) {
1710 ALOGE("Couldn't convert to PKCS#8");
1711 return SYSTEM_ERROR;
1712 }
1713
Chad Brubaker72593ee2015-05-12 10:42:00 -07001714 ResponseCode rc = importKey(pkcs8key.get(), len, filename, get_user_id(uid),
Kenny Rootf9119d62013-04-03 09:22:15 -07001715 blob->isEncrypted() ? KEYSTORE_FLAG_ENCRYPTED : KEYSTORE_FLAG_NONE);
Kenny Root822c3a92012-03-23 16:34:39 -07001716 if (rc != NO_ERROR) {
1717 return rc;
1718 }
1719
Kenny Root655b9582013-04-04 08:37:42 -07001720 return get(filename, blob, TYPE_KEY_PAIR, uid);
1721 }
1722
1723 void readMetaData() {
1724 int in = TEMP_FAILURE_RETRY(open(sMetaDataFile, O_RDONLY));
1725 if (in < 0) {
1726 return;
1727 }
1728 size_t fileLength = readFully(in, (uint8_t*) &mMetaData, sizeof(mMetaData));
1729 if (fileLength != sizeof(mMetaData)) {
1730 ALOGI("Metadata file is %zd bytes (%zd experted); upgrade?", fileLength,
1731 sizeof(mMetaData));
1732 }
1733 close(in);
1734 }
1735
1736 void writeMetaData() {
1737 const char* tmpFileName = ".metadata.tmp";
1738 int out = TEMP_FAILURE_RETRY(open(tmpFileName,
1739 O_WRONLY | O_TRUNC | O_CREAT, S_IRUSR | S_IWUSR));
1740 if (out < 0) {
1741 ALOGE("couldn't write metadata file: %s", strerror(errno));
1742 return;
1743 }
1744 size_t fileLength = writeFully(out, (uint8_t*) &mMetaData, sizeof(mMetaData));
1745 if (fileLength != sizeof(mMetaData)) {
1746 ALOGI("Could only write %zd bytes to metadata file (%zd expected)", fileLength,
1747 sizeof(mMetaData));
1748 }
1749 close(out);
1750 rename(tmpFileName, sMetaDataFile);
1751 }
1752
1753 bool upgradeKeystore() {
1754 bool upgraded = false;
1755
1756 if (mMetaData.version == 0) {
Chad Brubaker72593ee2015-05-12 10:42:00 -07001757 UserState* userState = getUserStateByUid(0);
Kenny Root655b9582013-04-04 08:37:42 -07001758
1759 // Initialize first so the directory is made.
1760 userState->initialize();
1761
1762 // Migrate the old .masterkey file to user 0.
1763 if (access(sOldMasterKey, R_OK) == 0) {
1764 if (rename(sOldMasterKey, userState->getMasterKeyFileName()) < 0) {
1765 ALOGE("couldn't migrate old masterkey: %s", strerror(errno));
1766 return false;
1767 }
1768 }
1769
1770 // Initialize again in case we had a key.
1771 userState->initialize();
1772
1773 // Try to migrate existing keys.
1774 DIR* dir = opendir(".");
1775 if (!dir) {
1776 // Give up now; maybe we can upgrade later.
1777 ALOGE("couldn't open keystore's directory; something is wrong");
1778 return false;
1779 }
1780
1781 struct dirent* file;
1782 while ((file = readdir(dir)) != NULL) {
1783 // We only care about files.
1784 if (file->d_type != DT_REG) {
1785 continue;
1786 }
1787
1788 // Skip anything that starts with a "."
1789 if (file->d_name[0] == '.') {
1790 continue;
1791 }
1792
1793 // Find the current file's user.
1794 char* end;
1795 unsigned long thisUid = strtoul(file->d_name, &end, 10);
1796 if (end[0] != '_' || end[1] == 0) {
1797 continue;
1798 }
Chad Brubaker72593ee2015-05-12 10:42:00 -07001799 UserState* otherUser = getUserStateByUid(thisUid);
Kenny Root655b9582013-04-04 08:37:42 -07001800 if (otherUser->getUserId() != 0) {
1801 unlinkat(dirfd(dir), file->d_name, 0);
1802 }
1803
1804 // Rename the file into user directory.
1805 DIR* otherdir = opendir(otherUser->getUserDirName());
1806 if (otherdir == NULL) {
1807 ALOGW("couldn't open user directory for rename");
1808 continue;
1809 }
1810 if (renameat(dirfd(dir), file->d_name, dirfd(otherdir), file->d_name) < 0) {
1811 ALOGW("couldn't rename blob: %s: %s", file->d_name, strerror(errno));
1812 }
1813 closedir(otherdir);
1814 }
1815 closedir(dir);
1816
1817 mMetaData.version = 1;
1818 upgraded = true;
1819 }
1820
1821 return upgraded;
Kenny Root822c3a92012-03-23 16:34:39 -07001822 }
Kenny Roota91203b2012-02-15 15:00:46 -08001823};
1824
Kenny Root655b9582013-04-04 08:37:42 -07001825const char* KeyStore::sOldMasterKey = ".masterkey";
1826const char* KeyStore::sMetaDataFile = ".metadata";
Kenny Root70e3a862012-02-15 17:20:23 -08001827
Kenny Root1b0e3932013-09-05 13:06:32 -07001828const android::String16 KeyStore::sRSAKeyType("RSA");
1829
Kenny Root07438c82012-11-02 15:41:02 -07001830namespace android {
1831class KeyStoreProxy : public BnKeystoreService, public IBinder::DeathRecipient {
1832public:
1833 KeyStoreProxy(KeyStore* keyStore)
Chad Brubaker40a1a9b2015-02-20 14:08:13 -08001834 : mKeyStore(keyStore),
1835 mOperationMap(this)
Kenny Root07438c82012-11-02 15:41:02 -07001836 {
Kenny Roota91203b2012-02-15 15:00:46 -08001837 }
Kenny Roota91203b2012-02-15 15:00:46 -08001838
Chad Brubaker40a1a9b2015-02-20 14:08:13 -08001839 void binderDied(const wp<IBinder>& who) {
1840 auto operations = mOperationMap.getOperationsForToken(who.unsafe_get());
1841 for (auto token: operations) {
1842 abort(token);
1843 }
Kenny Root822c3a92012-03-23 16:34:39 -07001844 }
Kenny Roota91203b2012-02-15 15:00:46 -08001845
Chad Brubakere6c3bfa2015-05-12 15:18:26 -07001846 int32_t getState(int32_t userId) {
1847 if (!checkBinderPermission(P_GET_STATE)) {
Kenny Root07438c82012-11-02 15:41:02 -07001848 return ::PERMISSION_DENIED;
Kenny Roota91203b2012-02-15 15:00:46 -08001849 }
Kenny Roota91203b2012-02-15 15:00:46 -08001850
Chad Brubakere6c3bfa2015-05-12 15:18:26 -07001851 return mKeyStore->getState(userId);
Kenny Root298e7b12012-03-26 13:54:44 -07001852 }
1853
Kenny Root07438c82012-11-02 15:41:02 -07001854 int32_t get(const String16& name, uint8_t** item, size_t* itemLength) {
Chad Brubaker9489b792015-04-14 11:01:45 -07001855 if (!checkBinderPermission(P_GET)) {
Kenny Root07438c82012-11-02 15:41:02 -07001856 return ::PERMISSION_DENIED;
Kenny Roota91203b2012-02-15 15:00:46 -08001857 }
Kenny Root07438c82012-11-02 15:41:02 -07001858
Chad Brubaker9489b792015-04-14 11:01:45 -07001859 uid_t callingUid = IPCThreadState::self()->getCallingUid();
Kenny Root07438c82012-11-02 15:41:02 -07001860 String8 name8(name);
Kenny Root07438c82012-11-02 15:41:02 -07001861 Blob keyBlob;
Nick Kralevich66dbf672014-06-30 17:09:14 +00001862
Kenny Root655b9582013-04-04 08:37:42 -07001863 ResponseCode responseCode = mKeyStore->getKeyForName(&keyBlob, name8, callingUid,
Kenny Root49468902013-03-19 13:41:33 -07001864 TYPE_GENERIC);
Kenny Root07438c82012-11-02 15:41:02 -07001865 if (responseCode != ::NO_ERROR) {
1866 *item = NULL;
1867 *itemLength = 0;
1868 return responseCode;
Kenny Roota91203b2012-02-15 15:00:46 -08001869 }
Kenny Roota91203b2012-02-15 15:00:46 -08001870
Kenny Root07438c82012-11-02 15:41:02 -07001871 *item = (uint8_t*) malloc(keyBlob.getLength());
1872 memcpy(*item, keyBlob.getValue(), keyBlob.getLength());
1873 *itemLength = keyBlob.getLength();
Kenny Roota91203b2012-02-15 15:00:46 -08001874
Kenny Root07438c82012-11-02 15:41:02 -07001875 return ::NO_ERROR;
Kenny Root70e3a862012-02-15 17:20:23 -08001876 }
1877
Kenny Rootf9119d62013-04-03 09:22:15 -07001878 int32_t insert(const String16& name, const uint8_t* item, size_t itemLength, int targetUid,
1879 int32_t flags) {
Chad Brubaker9489b792015-04-14 11:01:45 -07001880 targetUid = getEffectiveUid(targetUid);
1881 int32_t result = checkBinderPermissionAndKeystoreState(P_INSERT, targetUid,
1882 flags & KEYSTORE_FLAG_ENCRYPTED);
1883 if (result != ::NO_ERROR) {
1884 return result;
Kenny Rootb88c3eb2013-02-13 14:43:43 -08001885 }
1886
Kenny Root07438c82012-11-02 15:41:02 -07001887 String8 name8(name);
Kenny Root655b9582013-04-04 08:37:42 -07001888 String8 filename(mKeyStore->getKeyNameForUidWithDir(name8, targetUid));
Kenny Root07438c82012-11-02 15:41:02 -07001889
1890 Blob keyBlob(item, itemLength, NULL, 0, ::TYPE_GENERIC);
Kenny Rootee8068b2013-10-07 09:49:15 -07001891 keyBlob.setEncrypted(flags & KEYSTORE_FLAG_ENCRYPTED);
1892
Chad Brubaker72593ee2015-05-12 10:42:00 -07001893 return mKeyStore->put(filename.string(), &keyBlob, get_user_id(targetUid));
Kenny Root70e3a862012-02-15 17:20:23 -08001894 }
1895
Kenny Root49468902013-03-19 13:41:33 -07001896 int32_t del(const String16& name, int targetUid) {
Chad Brubaker9489b792015-04-14 11:01:45 -07001897 targetUid = getEffectiveUid(targetUid);
1898 if (!checkBinderPermission(P_DELETE, targetUid)) {
Kenny Root07438c82012-11-02 15:41:02 -07001899 return ::PERMISSION_DENIED;
1900 }
Kenny Root07438c82012-11-02 15:41:02 -07001901 String8 name8(name);
Kenny Root655b9582013-04-04 08:37:42 -07001902 String8 filename(mKeyStore->getKeyNameForUidWithDir(name8, targetUid));
Chad Brubaker72593ee2015-05-12 10:42:00 -07001903 return mKeyStore->del(filename.string(), ::TYPE_ANY, get_user_id(targetUid));
Kenny Root70e3a862012-02-15 17:20:23 -08001904 }
1905
Kenny Root49468902013-03-19 13:41:33 -07001906 int32_t exist(const String16& name, int targetUid) {
Chad Brubaker9489b792015-04-14 11:01:45 -07001907 targetUid = getEffectiveUid(targetUid);
1908 if (!checkBinderPermission(P_EXIST, targetUid)) {
Kenny Rootb88c3eb2013-02-13 14:43:43 -08001909 return ::PERMISSION_DENIED;
1910 }
1911
Kenny Root07438c82012-11-02 15:41:02 -07001912 String8 name8(name);
Kenny Root655b9582013-04-04 08:37:42 -07001913 String8 filename(mKeyStore->getKeyNameForUidWithDir(name8, targetUid));
Kenny Root70e3a862012-02-15 17:20:23 -08001914
Kenny Root655b9582013-04-04 08:37:42 -07001915 if (access(filename.string(), R_OK) == -1) {
Kenny Root07438c82012-11-02 15:41:02 -07001916 return (errno != ENOENT) ? ::SYSTEM_ERROR : ::KEY_NOT_FOUND;
1917 }
1918 return ::NO_ERROR;
Kenny Root70e3a862012-02-15 17:20:23 -08001919 }
1920
Chad Brubakere6c3bfa2015-05-12 15:18:26 -07001921 int32_t list(const String16& prefix, int targetUid, Vector<String16>* matches) {
Chad Brubaker9489b792015-04-14 11:01:45 -07001922 targetUid = getEffectiveUid(targetUid);
Chad Brubakere6c3bfa2015-05-12 15:18:26 -07001923 if (!checkBinderPermission(P_LIST, targetUid)) {
Kenny Root07438c82012-11-02 15:41:02 -07001924 return ::PERMISSION_DENIED;
1925 }
Kenny Root07438c82012-11-02 15:41:02 -07001926 const String8 prefix8(prefix);
Kenny Root655b9582013-04-04 08:37:42 -07001927 String8 filename(mKeyStore->getKeyNameForUid(prefix8, targetUid));
Kenny Root70e3a862012-02-15 17:20:23 -08001928
Chad Brubakere6c3bfa2015-05-12 15:18:26 -07001929 if (mKeyStore->list(filename, matches, get_user_id(targetUid)) != ::NO_ERROR) {
Robin Lee4b84fdc2014-09-24 11:56:57 +01001930 return ::SYSTEM_ERROR;
Kenny Root9a53d3e2012-08-14 10:47:54 -07001931 }
Kenny Root07438c82012-11-02 15:41:02 -07001932 return ::NO_ERROR;
Kenny Root70e3a862012-02-15 17:20:23 -08001933 }
1934
Kenny Root07438c82012-11-02 15:41:02 -07001935 int32_t reset() {
Chad Brubaker9489b792015-04-14 11:01:45 -07001936 if (!checkBinderPermission(P_RESET)) {
Kenny Root07438c82012-11-02 15:41:02 -07001937 return ::PERMISSION_DENIED;
1938 }
1939
Chad Brubaker9489b792015-04-14 11:01:45 -07001940 uid_t callingUid = IPCThreadState::self()->getCallingUid();
Chad Brubaker96d6d782015-05-07 10:19:40 -07001941 mKeyStore->resetUser(get_user_id(callingUid), false);
1942 return ::NO_ERROR;
Kenny Root70e3a862012-02-15 17:20:23 -08001943 }
1944
Chad Brubaker96d6d782015-05-07 10:19:40 -07001945 int32_t onUserPasswordChanged(int32_t userId, const String16& password) {
Chad Brubaker9489b792015-04-14 11:01:45 -07001946 if (!checkBinderPermission(P_PASSWORD)) {
Kenny Root07438c82012-11-02 15:41:02 -07001947 return ::PERMISSION_DENIED;
1948 }
Kenny Root70e3a862012-02-15 17:20:23 -08001949
Kenny Root07438c82012-11-02 15:41:02 -07001950 const String8 password8(password);
Chad Brubaker96d6d782015-05-07 10:19:40 -07001951 // Flush the auth token table to prevent stale tokens from sticking
1952 // around.
1953 mAuthTokenTable.Clear();
1954
1955 if (password.size() == 0) {
1956 ALOGI("Secure lockscreen for user %d removed, deleting encrypted entries", userId);
Chad Brubaker72593ee2015-05-12 10:42:00 -07001957 mKeyStore->resetUser(userId, true);
Chad Brubaker96d6d782015-05-07 10:19:40 -07001958 return ::NO_ERROR;
1959 } else {
Chad Brubaker72593ee2015-05-12 10:42:00 -07001960 switch (mKeyStore->getState(userId)) {
Chad Brubaker96d6d782015-05-07 10:19:40 -07001961 case ::STATE_UNINITIALIZED: {
1962 // generate master key, encrypt with password, write to file,
1963 // initialize mMasterKey*.
Chad Brubaker72593ee2015-05-12 10:42:00 -07001964 return mKeyStore->initializeUser(password8, userId);
Chad Brubaker96d6d782015-05-07 10:19:40 -07001965 }
1966 case ::STATE_NO_ERROR: {
1967 // rewrite master key with new password.
Chad Brubaker72593ee2015-05-12 10:42:00 -07001968 return mKeyStore->writeMasterKey(password8, userId);
Chad Brubaker96d6d782015-05-07 10:19:40 -07001969 }
1970 case ::STATE_LOCKED: {
1971 ALOGE("Changing user %d's password while locked, clearing old encryption",
1972 userId);
Chad Brubaker72593ee2015-05-12 10:42:00 -07001973 mKeyStore->resetUser(userId, true);
1974 return mKeyStore->initializeUser(password8, userId);
Chad Brubaker96d6d782015-05-07 10:19:40 -07001975 }
Kenny Root07438c82012-11-02 15:41:02 -07001976 }
Chad Brubaker96d6d782015-05-07 10:19:40 -07001977 return ::SYSTEM_ERROR;
Kenny Root07438c82012-11-02 15:41:02 -07001978 }
Kenny Root70e3a862012-02-15 17:20:23 -08001979 }
1980
Chad Brubakerc0f031a2015-05-12 10:43:10 -07001981 int32_t onUserAdded(int32_t userId, int32_t parentId) {
1982 if (!checkBinderPermission(P_USER_CHANGED)) {
1983 return ::PERMISSION_DENIED;
1984 }
1985
1986 // Sanity check that the new user has an empty keystore.
1987 if (!mKeyStore->isEmpty(userId)) {
1988 ALOGW("New user %d's keystore not empty. Clearing old entries.", userId);
1989 }
1990 // Unconditionally clear the keystore, just to be safe.
1991 mKeyStore->resetUser(userId, false);
1992
1993 // If the user has a parent user then use the parent's
1994 // masterkey/password, otherwise there's nothing to do.
1995 if (parentId != -1) {
1996 return mKeyStore->copyMasterKey(parentId, userId);
1997 } else {
1998 return ::NO_ERROR;
1999 }
2000 }
2001
2002 int32_t onUserRemoved(int32_t userId) {
2003 if (!checkBinderPermission(P_USER_CHANGED)) {
2004 return ::PERMISSION_DENIED;
2005 }
2006
2007 mKeyStore->resetUser(userId, false);
2008 return ::NO_ERROR;
2009 }
2010
Chad Brubakere6c3bfa2015-05-12 15:18:26 -07002011 int32_t lock(int32_t userId) {
Chad Brubaker9489b792015-04-14 11:01:45 -07002012 if (!checkBinderPermission(P_LOCK)) {
Kenny Root07438c82012-11-02 15:41:02 -07002013 return ::PERMISSION_DENIED;
2014 }
Kenny Root70e3a862012-02-15 17:20:23 -08002015
Chad Brubaker72593ee2015-05-12 10:42:00 -07002016 State state = mKeyStore->getState(userId);
Kenny Root9d45d1c2013-02-14 10:32:30 -08002017 if (state != ::STATE_NO_ERROR) {
Kenny Root07438c82012-11-02 15:41:02 -07002018 ALOGD("calling lock in state: %d", state);
2019 return state;
2020 }
2021
Chad Brubaker72593ee2015-05-12 10:42:00 -07002022 mKeyStore->lock(userId);
Kenny Root07438c82012-11-02 15:41:02 -07002023 return ::NO_ERROR;
Kenny Root70e3a862012-02-15 17:20:23 -08002024 }
2025
Chad Brubaker96d6d782015-05-07 10:19:40 -07002026 int32_t unlock(int32_t userId, const String16& pw) {
Chad Brubaker9489b792015-04-14 11:01:45 -07002027 if (!checkBinderPermission(P_UNLOCK)) {
Kenny Root07438c82012-11-02 15:41:02 -07002028 return ::PERMISSION_DENIED;
2029 }
2030
Chad Brubaker72593ee2015-05-12 10:42:00 -07002031 State state = mKeyStore->getState(userId);
Kenny Root9d45d1c2013-02-14 10:32:30 -08002032 if (state != ::STATE_LOCKED) {
Chad Brubaker96d6d782015-05-07 10:19:40 -07002033 ALOGI("calling unlock when not locked, ignoring.");
Kenny Root07438c82012-11-02 15:41:02 -07002034 return state;
2035 }
2036
2037 const String8 password8(pw);
Chad Brubaker96d6d782015-05-07 10:19:40 -07002038 // read master key, decrypt with password, initialize mMasterKey*.
Chad Brubaker72593ee2015-05-12 10:42:00 -07002039 return mKeyStore->readMasterKey(password8, userId);
Kenny Root70e3a862012-02-15 17:20:23 -08002040 }
2041
Chad Brubakere6c3bfa2015-05-12 15:18:26 -07002042 bool isEmpty(int32_t userId) {
2043 if (!checkBinderPermission(P_IS_EMPTY)) {
2044 return false;
Kenny Root07438c82012-11-02 15:41:02 -07002045 }
Kenny Root70e3a862012-02-15 17:20:23 -08002046
Chad Brubakere6c3bfa2015-05-12 15:18:26 -07002047 return mKeyStore->isEmpty(userId);
Kenny Root70e3a862012-02-15 17:20:23 -08002048 }
2049
Kenny Root96427ba2013-08-16 14:02:41 -07002050 int32_t generate(const String16& name, int32_t targetUid, int32_t keyType, int32_t keySize,
2051 int32_t flags, Vector<sp<KeystoreArg> >* args) {
Chad Brubaker9489b792015-04-14 11:01:45 -07002052 targetUid = getEffectiveUid(targetUid);
2053 int32_t result = checkBinderPermissionAndKeystoreState(P_INSERT, targetUid,
2054 flags & KEYSTORE_FLAG_ENCRYPTED);
2055 if (result != ::NO_ERROR) {
2056 return result;
Kenny Root07438c82012-11-02 15:41:02 -07002057 }
Kenny Root07438c82012-11-02 15:41:02 -07002058
Chad Brubaker3a7d9e62015-06-04 15:01:46 -07002059 KeymasterArguments params;
Shawn Willden7e8eabb2015-07-28 11:06:00 -06002060 add_legacy_key_authorizations(keyType, &params.params);
Kenny Root07438c82012-11-02 15:41:02 -07002061
Chad Brubaker3a7d9e62015-06-04 15:01:46 -07002062 switch (keyType) {
2063 case EVP_PKEY_EC: {
2064 params.params.push_back(keymaster_param_enum(KM_TAG_ALGORITHM, KM_ALGORITHM_EC));
2065 if (keySize == -1) {
2066 keySize = EC_DEFAULT_KEY_SIZE;
2067 } else if (keySize < EC_MIN_KEY_SIZE || keySize > EC_MAX_KEY_SIZE) {
2068 ALOGI("invalid key size %d", keySize);
Kenny Root96427ba2013-08-16 14:02:41 -07002069 return ::SYSTEM_ERROR;
2070 }
Chad Brubaker3a7d9e62015-06-04 15:01:46 -07002071 params.params.push_back(keymaster_param_int(KM_TAG_KEY_SIZE, keySize));
2072 break;
Kenny Root96427ba2013-08-16 14:02:41 -07002073 }
Chad Brubaker3a7d9e62015-06-04 15:01:46 -07002074 case EVP_PKEY_RSA: {
2075 params.params.push_back(keymaster_param_enum(KM_TAG_ALGORITHM, KM_ALGORITHM_RSA));
2076 if (keySize == -1) {
2077 keySize = RSA_DEFAULT_KEY_SIZE;
2078 } else if (keySize < RSA_MIN_KEY_SIZE || keySize > RSA_MAX_KEY_SIZE) {
2079 ALOGI("invalid key size %d", keySize);
2080 return ::SYSTEM_ERROR;
Kenny Root96427ba2013-08-16 14:02:41 -07002081 }
Chad Brubaker3a7d9e62015-06-04 15:01:46 -07002082 params.params.push_back(keymaster_param_int(KM_TAG_KEY_SIZE, keySize));
2083 unsigned long exponent = RSA_DEFAULT_EXPONENT;
2084 if (args->size() > 1) {
2085 ALOGI("invalid number of arguments: %zu", args->size());
2086 return ::SYSTEM_ERROR;
2087 } else if (args->size() == 1) {
2088 sp<KeystoreArg> expArg = args->itemAt(0);
2089 if (expArg != NULL) {
2090 Unique_BIGNUM pubExpBn(
2091 BN_bin2bn(reinterpret_cast<const unsigned char*>(expArg->data()),
2092 expArg->size(), NULL));
2093 if (pubExpBn.get() == NULL) {
2094 ALOGI("Could not convert public exponent to BN");
2095 return ::SYSTEM_ERROR;
2096 }
2097 exponent = BN_get_word(pubExpBn.get());
2098 if (exponent == 0xFFFFFFFFL) {
2099 ALOGW("cannot represent public exponent as a long value");
2100 return ::SYSTEM_ERROR;
2101 }
2102 } else {
2103 ALOGW("public exponent not read");
2104 return ::SYSTEM_ERROR;
2105 }
2106 }
2107 params.params.push_back(keymaster_param_long(KM_TAG_RSA_PUBLIC_EXPONENT,
2108 exponent));
2109 break;
Kenny Root96427ba2013-08-16 14:02:41 -07002110 }
Chad Brubaker3a7d9e62015-06-04 15:01:46 -07002111 default: {
2112 ALOGW("Unsupported key type %d", keyType);
2113 return ::SYSTEM_ERROR;
2114 }
Kenny Root96427ba2013-08-16 14:02:41 -07002115 }
2116
Chad Brubaker3a7d9e62015-06-04 15:01:46 -07002117 int32_t rc = generateKey(name, params, NULL, 0, targetUid, flags,
2118 /*outCharacteristics*/ NULL);
2119 if (rc != ::NO_ERROR) {
2120 ALOGW("generate failed: %d", rc);
Kenny Root07438c82012-11-02 15:41:02 -07002121 }
Chad Brubaker3a7d9e62015-06-04 15:01:46 -07002122 return translateResultToLegacyResult(rc);
Kenny Root70e3a862012-02-15 17:20:23 -08002123 }
2124
Kenny Rootf9119d62013-04-03 09:22:15 -07002125 int32_t import(const String16& name, const uint8_t* data, size_t length, int targetUid,
2126 int32_t flags) {
Chad Brubaker3a7d9e62015-06-04 15:01:46 -07002127 const uint8_t* ptr = data;
Kenny Root07438c82012-11-02 15:41:02 -07002128
Chad Brubaker3a7d9e62015-06-04 15:01:46 -07002129 Unique_PKCS8_PRIV_KEY_INFO pkcs8(d2i_PKCS8_PRIV_KEY_INFO(NULL, &ptr, length));
2130 if (!pkcs8.get()) {
2131 return ::SYSTEM_ERROR;
2132 }
2133 Unique_EVP_PKEY pkey(EVP_PKCS82PKEY(pkcs8.get()));
2134 if (!pkey.get()) {
2135 return ::SYSTEM_ERROR;
2136 }
2137 int type = EVP_PKEY_type(pkey->type);
Shawn Willden2de8b752015-07-23 05:54:31 -06002138 KeymasterArguments params;
Shawn Willden7e8eabb2015-07-28 11:06:00 -06002139 add_legacy_key_authorizations(type, &params.params);
Chad Brubaker3a7d9e62015-06-04 15:01:46 -07002140 switch (type) {
2141 case EVP_PKEY_RSA:
2142 params.params.push_back(keymaster_param_enum(KM_TAG_ALGORITHM, KM_ALGORITHM_RSA));
2143 break;
2144 case EVP_PKEY_EC:
2145 params.params.push_back(keymaster_param_enum(KM_TAG_ALGORITHM,
2146 KM_ALGORITHM_EC));
2147 break;
2148 default:
2149 ALOGW("Unsupported key type %d", type);
2150 return ::SYSTEM_ERROR;
2151 }
2152 int32_t rc = importKey(name, params, KM_KEY_FORMAT_PKCS8, data, length, targetUid, flags,
2153 /*outCharacteristics*/ NULL);
2154 if (rc != ::NO_ERROR) {
2155 ALOGW("importKey failed: %d", rc);
2156 }
2157 return translateResultToLegacyResult(rc);
Kenny Root70e3a862012-02-15 17:20:23 -08002158 }
2159
Kenny Root07438c82012-11-02 15:41:02 -07002160 int32_t sign(const String16& name, const uint8_t* data, size_t length, uint8_t** out,
Chad Brubaker3a7d9e62015-06-04 15:01:46 -07002161 size_t* outLength) {
Chad Brubaker9489b792015-04-14 11:01:45 -07002162 if (!checkBinderPermission(P_SIGN)) {
Kenny Root07438c82012-11-02 15:41:02 -07002163 return ::PERMISSION_DENIED;
2164 }
Chad Brubaker3a7d9e62015-06-04 15:01:46 -07002165 return doLegacySignVerify(name, data, length, out, outLength, NULL, 0, KM_PURPOSE_SIGN);
Kenny Root70e3a862012-02-15 17:20:23 -08002166 }
2167
Kenny Root07438c82012-11-02 15:41:02 -07002168 int32_t verify(const String16& name, const uint8_t* data, size_t dataLength,
2169 const uint8_t* signature, size_t signatureLength) {
Chad Brubaker9489b792015-04-14 11:01:45 -07002170 if (!checkBinderPermission(P_VERIFY)) {
Kenny Root07438c82012-11-02 15:41:02 -07002171 return ::PERMISSION_DENIED;
2172 }
Chad Brubaker3a7d9e62015-06-04 15:01:46 -07002173 return doLegacySignVerify(name, data, dataLength, NULL, NULL, signature, signatureLength,
2174 KM_PURPOSE_VERIFY);
Kenny Roota91203b2012-02-15 15:00:46 -08002175 }
Kenny Root07438c82012-11-02 15:41:02 -07002176
2177 /*
2178 * TODO: The abstraction between things stored in hardware and regular blobs
2179 * of data stored on the filesystem should be moved down to keystore itself.
2180 * Unfortunately the Java code that calls this has naming conventions that it
2181 * knows about. Ideally keystore shouldn't be used to store random blobs of
2182 * data.
2183 *
2184 * Until that happens, it's necessary to have a separate "get_pubkey" and
2185 * "del_key" since the Java code doesn't really communicate what it's
2186 * intentions are.
2187 */
2188 int32_t get_pubkey(const String16& name, uint8_t** pubkey, size_t* pubkeyLength) {
Chad Brubaker3a7d9e62015-06-04 15:01:46 -07002189 ExportResult result;
2190 exportKey(name, KM_KEY_FORMAT_X509, NULL, NULL, &result);
2191 if (result.resultCode != ::NO_ERROR) {
2192 ALOGW("export failed: %d", result.resultCode);
2193 return translateResultToLegacyResult(result.resultCode);
Kenny Root07438c82012-11-02 15:41:02 -07002194 }
Kenny Root07438c82012-11-02 15:41:02 -07002195
Chad Brubaker3a7d9e62015-06-04 15:01:46 -07002196 *pubkey = result.exportData.release();
2197 *pubkeyLength = result.dataLength;
Kenny Root07438c82012-11-02 15:41:02 -07002198 return ::NO_ERROR;
Kenny Roota91203b2012-02-15 15:00:46 -08002199 }
Kenny Root07438c82012-11-02 15:41:02 -07002200
Kenny Root07438c82012-11-02 15:41:02 -07002201 int32_t grant(const String16& name, int32_t granteeUid) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08002202 uid_t callingUid = IPCThreadState::self()->getCallingUid();
Chad Brubaker9489b792015-04-14 11:01:45 -07002203 int32_t result = checkBinderPermissionAndKeystoreState(P_GRANT);
2204 if (result != ::NO_ERROR) {
2205 return result;
Kenny Root07438c82012-11-02 15:41:02 -07002206 }
2207
2208 String8 name8(name);
Kenny Root655b9582013-04-04 08:37:42 -07002209 String8 filename(mKeyStore->getKeyNameForUidWithDir(name8, callingUid));
Kenny Root07438c82012-11-02 15:41:02 -07002210
Kenny Root655b9582013-04-04 08:37:42 -07002211 if (access(filename.string(), R_OK) == -1) {
Kenny Root07438c82012-11-02 15:41:02 -07002212 return (errno != ENOENT) ? ::SYSTEM_ERROR : ::KEY_NOT_FOUND;
2213 }
2214
Kenny Root655b9582013-04-04 08:37:42 -07002215 mKeyStore->addGrant(filename.string(), granteeUid);
Kenny Root07438c82012-11-02 15:41:02 -07002216 return ::NO_ERROR;
2217 }
2218
2219 int32_t ungrant(const String16& name, int32_t granteeUid) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08002220 uid_t callingUid = IPCThreadState::self()->getCallingUid();
Chad Brubaker9489b792015-04-14 11:01:45 -07002221 int32_t result = checkBinderPermissionAndKeystoreState(P_GRANT);
2222 if (result != ::NO_ERROR) {
2223 return result;
Kenny Root07438c82012-11-02 15:41:02 -07002224 }
2225
2226 String8 name8(name);
Kenny Root655b9582013-04-04 08:37:42 -07002227 String8 filename(mKeyStore->getKeyNameForUidWithDir(name8, callingUid));
Kenny Root07438c82012-11-02 15:41:02 -07002228
Kenny Root655b9582013-04-04 08:37:42 -07002229 if (access(filename.string(), R_OK) == -1) {
Kenny Root07438c82012-11-02 15:41:02 -07002230 return (errno != ENOENT) ? ::SYSTEM_ERROR : ::KEY_NOT_FOUND;
2231 }
2232
Kenny Root655b9582013-04-04 08:37:42 -07002233 return mKeyStore->removeGrant(filename.string(), granteeUid) ? ::NO_ERROR : ::KEY_NOT_FOUND;
Kenny Root07438c82012-11-02 15:41:02 -07002234 }
2235
2236 int64_t getmtime(const String16& name) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08002237 uid_t callingUid = IPCThreadState::self()->getCallingUid();
Chad Brubaker9489b792015-04-14 11:01:45 -07002238 if (!checkBinderPermission(P_GET)) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08002239 ALOGW("permission denied for %d: getmtime", callingUid);
Kenny Root36a9e232013-02-04 14:24:15 -08002240 return -1L;
Kenny Root07438c82012-11-02 15:41:02 -07002241 }
Kenny Root07438c82012-11-02 15:41:02 -07002242
2243 String8 name8(name);
Kenny Root655b9582013-04-04 08:37:42 -07002244 String8 filename(mKeyStore->getKeyNameForUidWithDir(name8, callingUid));
Kenny Root07438c82012-11-02 15:41:02 -07002245
Kenny Root655b9582013-04-04 08:37:42 -07002246 if (access(filename.string(), R_OK) == -1) {
2247 ALOGW("could not access %s for getmtime", filename.string());
Kenny Root36a9e232013-02-04 14:24:15 -08002248 return -1L;
Kenny Root07438c82012-11-02 15:41:02 -07002249 }
2250
Kenny Root655b9582013-04-04 08:37:42 -07002251 int fd = TEMP_FAILURE_RETRY(open(filename.string(), O_NOFOLLOW, O_RDONLY));
Kenny Root07438c82012-11-02 15:41:02 -07002252 if (fd < 0) {
Kenny Root655b9582013-04-04 08:37:42 -07002253 ALOGW("could not open %s for getmtime", filename.string());
Kenny Root36a9e232013-02-04 14:24:15 -08002254 return -1L;
Kenny Root07438c82012-11-02 15:41:02 -07002255 }
2256
2257 struct stat s;
2258 int ret = fstat(fd, &s);
2259 close(fd);
2260 if (ret == -1) {
Kenny Root655b9582013-04-04 08:37:42 -07002261 ALOGW("could not stat %s for getmtime", filename.string());
Kenny Root36a9e232013-02-04 14:24:15 -08002262 return -1L;
Kenny Root07438c82012-11-02 15:41:02 -07002263 }
2264
Kenny Root36a9e232013-02-04 14:24:15 -08002265 return static_cast<int64_t>(s.st_mtime);
Kenny Root07438c82012-11-02 15:41:02 -07002266 }
2267
Kenny Rootd53bc922013-03-21 14:10:15 -07002268 int32_t duplicate(const String16& srcKey, int32_t srcUid, const String16& destKey,
2269 int32_t destUid) {
Kenny Root02254072013-03-20 11:48:19 -07002270 uid_t callingUid = IPCThreadState::self()->getCallingUid();
Riley Spahneaabae92014-06-30 12:39:52 -07002271 pid_t spid = IPCThreadState::self()->getCallingPid();
2272 if (!has_permission(callingUid, P_DUPLICATE, spid)) {
Kenny Rootd53bc922013-03-21 14:10:15 -07002273 ALOGW("permission denied for %d: duplicate", callingUid);
Kenny Root02254072013-03-20 11:48:19 -07002274 return -1L;
2275 }
2276
Chad Brubaker72593ee2015-05-12 10:42:00 -07002277 State state = mKeyStore->getState(get_user_id(callingUid));
Kenny Root02254072013-03-20 11:48:19 -07002278 if (!isKeystoreUnlocked(state)) {
Kenny Rootd53bc922013-03-21 14:10:15 -07002279 ALOGD("calling duplicate in state: %d", state);
Kenny Root02254072013-03-20 11:48:19 -07002280 return state;
2281 }
2282
Kenny Rootd53bc922013-03-21 14:10:15 -07002283 if (srcUid == -1 || static_cast<uid_t>(srcUid) == callingUid) {
2284 srcUid = callingUid;
2285 } else if (!is_granted_to(callingUid, srcUid)) {
2286 ALOGD("migrate not granted from source: %d -> %d", callingUid, srcUid);
Kenny Root02254072013-03-20 11:48:19 -07002287 return ::PERMISSION_DENIED;
2288 }
2289
Kenny Rootd53bc922013-03-21 14:10:15 -07002290 if (destUid == -1) {
2291 destUid = callingUid;
2292 }
2293
2294 if (srcUid != destUid) {
2295 if (static_cast<uid_t>(srcUid) != callingUid) {
2296 ALOGD("can only duplicate from caller to other or to same uid: "
2297 "calling=%d, srcUid=%d, destUid=%d", callingUid, srcUid, destUid);
2298 return ::PERMISSION_DENIED;
2299 }
2300
2301 if (!is_granted_to(callingUid, destUid)) {
2302 ALOGD("duplicate not granted to dest: %d -> %d", callingUid, destUid);
2303 return ::PERMISSION_DENIED;
2304 }
2305 }
2306
2307 String8 source8(srcKey);
Kenny Root655b9582013-04-04 08:37:42 -07002308 String8 sourceFile(mKeyStore->getKeyNameForUidWithDir(source8, srcUid));
Kenny Root02254072013-03-20 11:48:19 -07002309
Kenny Rootd53bc922013-03-21 14:10:15 -07002310 String8 target8(destKey);
Kenny Rootfa27d5b2013-10-15 09:01:08 -07002311 String8 targetFile(mKeyStore->getKeyNameForUidWithDir(target8, destUid));
Kenny Root02254072013-03-20 11:48:19 -07002312
Kenny Root655b9582013-04-04 08:37:42 -07002313 if (access(targetFile.string(), W_OK) != -1 || errno != ENOENT) {
2314 ALOGD("destination already exists: %s", targetFile.string());
Kenny Root02254072013-03-20 11:48:19 -07002315 return ::SYSTEM_ERROR;
2316 }
2317
Kenny Rootd53bc922013-03-21 14:10:15 -07002318 Blob keyBlob;
Kenny Root655b9582013-04-04 08:37:42 -07002319 ResponseCode responseCode = mKeyStore->get(sourceFile.string(), &keyBlob, TYPE_ANY,
Chad Brubaker72593ee2015-05-12 10:42:00 -07002320 get_user_id(srcUid));
Kenny Rootd53bc922013-03-21 14:10:15 -07002321 if (responseCode != ::NO_ERROR) {
2322 return responseCode;
Kenny Root02254072013-03-20 11:48:19 -07002323 }
Kenny Rootd53bc922013-03-21 14:10:15 -07002324
Chad Brubaker72593ee2015-05-12 10:42:00 -07002325 return mKeyStore->put(targetFile.string(), &keyBlob, get_user_id(destUid));
Kenny Root02254072013-03-20 11:48:19 -07002326 }
2327
Kenny Root1b0e3932013-09-05 13:06:32 -07002328 int32_t is_hardware_backed(const String16& keyType) {
2329 return mKeyStore->isHardwareBacked(keyType) ? 1 : 0;
Kenny Root8ddf35a2013-03-29 11:15:50 -07002330 }
2331
Kenny Rootfa27d5b2013-10-15 09:01:08 -07002332 int32_t clear_uid(int64_t targetUid64) {
Chad Brubaker9489b792015-04-14 11:01:45 -07002333 uid_t targetUid = getEffectiveUid(targetUid64);
Chad Brubakerb37a5232015-05-01 10:21:27 -07002334 if (!checkBinderPermissionSelfOrSystem(P_CLEAR_UID, targetUid)) {
Kenny Roota9bb5492013-04-01 16:29:11 -07002335 return ::PERMISSION_DENIED;
2336 }
2337
Robin Lee4b84fdc2014-09-24 11:56:57 +01002338 String8 prefix = String8::format("%u_", targetUid);
2339 Vector<String16> aliases;
Chad Brubakere6c3bfa2015-05-12 15:18:26 -07002340 if (mKeyStore->list(prefix, &aliases, get_user_id(targetUid)) != ::NO_ERROR) {
Kenny Roota9bb5492013-04-01 16:29:11 -07002341 return ::SYSTEM_ERROR;
2342 }
2343
Robin Lee4b84fdc2014-09-24 11:56:57 +01002344 for (uint32_t i = 0; i < aliases.size(); i++) {
2345 String8 name8(aliases[i]);
2346 String8 filename(mKeyStore->getKeyNameForUidWithDir(name8, targetUid));
Chad Brubaker72593ee2015-05-12 10:42:00 -07002347 mKeyStore->del(filename.string(), ::TYPE_ANY, get_user_id(targetUid));
Kenny Roota9bb5492013-04-01 16:29:11 -07002348 }
Robin Lee4b84fdc2014-09-24 11:56:57 +01002349 return ::NO_ERROR;
Kenny Roota9bb5492013-04-01 16:29:11 -07002350 }
2351
Chad Brubaker9c8612c2015-02-09 11:32:54 -08002352 int32_t addRngEntropy(const uint8_t* data, size_t dataLength) {
2353 const keymaster1_device_t* device = mKeyStore->getDevice();
2354 const keymaster1_device_t* fallback = mKeyStore->getFallbackDevice();
2355 int32_t devResult = KM_ERROR_UNIMPLEMENTED;
2356 int32_t fallbackResult = KM_ERROR_UNIMPLEMENTED;
2357 if (device->common.module->module_api_version >= KEYMASTER_MODULE_API_VERSION_1_0 &&
2358 device->add_rng_entropy != NULL) {
2359 devResult = device->add_rng_entropy(device, data, dataLength);
2360 }
2361 if (fallback->add_rng_entropy) {
2362 fallbackResult = fallback->add_rng_entropy(fallback, data, dataLength);
2363 }
2364 if (devResult) {
2365 return devResult;
2366 }
2367 if (fallbackResult) {
2368 return fallbackResult;
2369 }
2370 return ::NO_ERROR;
Chad Brubaker9899d6b2015-02-03 13:03:00 -08002371 }
2372
Chad Brubaker17d68b92015-02-05 22:04:16 -08002373 int32_t generateKey(const String16& name, const KeymasterArguments& params,
Chad Brubaker154d7692015-03-27 13:59:31 -07002374 const uint8_t* entropy, size_t entropyLength, int uid, int flags,
2375 KeyCharacteristics* outCharacteristics) {
Chad Brubaker9489b792015-04-14 11:01:45 -07002376 uid = getEffectiveUid(uid);
2377 int rc = checkBinderPermissionAndKeystoreState(P_INSERT, uid,
2378 flags & KEYSTORE_FLAG_ENCRYPTED);
2379 if (rc != ::NO_ERROR) {
2380 return rc;
Chad Brubaker17d68b92015-02-05 22:04:16 -08002381 }
2382
Chad Brubaker9489b792015-04-14 11:01:45 -07002383 rc = KM_ERROR_UNIMPLEMENTED;
Chad Brubaker17d68b92015-02-05 22:04:16 -08002384 bool isFallback = false;
2385 keymaster_key_blob_t blob;
2386 keymaster_key_characteristics_t *out = NULL;
2387
2388 const keymaster1_device_t* device = mKeyStore->getDevice();
2389 const keymaster1_device_t* fallback = mKeyStore->getFallbackDevice();
Chad Brubaker57e106d2015-06-01 12:59:00 -07002390 std::vector<keymaster_key_param_t> opParams(params.params);
2391 const keymaster_key_param_set_t inParams = {opParams.data(), opParams.size()};
Chad Brubaker17d68b92015-02-05 22:04:16 -08002392 if (device == NULL) {
2393 return ::SYSTEM_ERROR;
2394 }
Chad Brubaker154d7692015-03-27 13:59:31 -07002395 // TODO: Seed from Linux RNG before this.
Chad Brubaker17d68b92015-02-05 22:04:16 -08002396 if (device->common.module->module_api_version >= KEYMASTER_MODULE_API_VERSION_1_0 &&
2397 device->generate_key != NULL) {
Chad Brubaker154d7692015-03-27 13:59:31 -07002398 if (!entropy) {
2399 rc = KM_ERROR_OK;
2400 } else if (device->add_rng_entropy) {
2401 rc = device->add_rng_entropy(device, entropy, entropyLength);
2402 } else {
2403 rc = KM_ERROR_UNIMPLEMENTED;
2404 }
2405 if (rc == KM_ERROR_OK) {
Chad Brubaker57e106d2015-06-01 12:59:00 -07002406 rc = device->generate_key(device, &inParams, &blob, &out);
Chad Brubaker154d7692015-03-27 13:59:31 -07002407 }
Chad Brubaker17d68b92015-02-05 22:04:16 -08002408 }
2409 // If the HW device didn't support generate_key or generate_key failed
2410 // fall back to the software implementation.
2411 if (rc && fallback->generate_key != NULL) {
Shawn Willden7e8eabb2015-07-28 11:06:00 -06002412 ALOGW("Primary keymaster device failed to generate key, falling back to SW.");
Chad Brubaker17d68b92015-02-05 22:04:16 -08002413 isFallback = true;
Chad Brubaker154d7692015-03-27 13:59:31 -07002414 if (!entropy) {
2415 rc = KM_ERROR_OK;
2416 } else if (fallback->add_rng_entropy) {
2417 rc = fallback->add_rng_entropy(fallback, entropy, entropyLength);
2418 } else {
2419 rc = KM_ERROR_UNIMPLEMENTED;
2420 }
2421 if (rc == KM_ERROR_OK) {
Chad Brubaker57e106d2015-06-01 12:59:00 -07002422 rc = fallback->generate_key(fallback, &inParams, &blob, &out);
Chad Brubaker154d7692015-03-27 13:59:31 -07002423 }
Chad Brubaker17d68b92015-02-05 22:04:16 -08002424 }
2425
2426 if (out) {
2427 if (outCharacteristics) {
2428 outCharacteristics->characteristics = *out;
2429 } else {
2430 keymaster_free_characteristics(out);
2431 }
2432 free(out);
2433 }
2434
2435 if (rc) {
2436 return rc;
2437 }
2438
2439 String8 name8(name);
2440 String8 filename(mKeyStore->getKeyNameForUidWithDir(name8, uid));
2441
2442 Blob keyBlob(blob.key_material, blob.key_material_size, NULL, 0, ::TYPE_KEYMASTER_10);
2443 keyBlob.setFallback(isFallback);
2444 keyBlob.setEncrypted(flags & KEYSTORE_FLAG_ENCRYPTED);
2445
2446 free(const_cast<uint8_t*>(blob.key_material));
2447
Chad Brubaker72593ee2015-05-12 10:42:00 -07002448 return mKeyStore->put(filename.string(), &keyBlob, get_user_id(uid));
Chad Brubaker9899d6b2015-02-03 13:03:00 -08002449 }
2450
Chad Brubakerf3f071f2015-02-10 19:38:51 -08002451 int32_t getKeyCharacteristics(const String16& name,
Chad Brubakerd6634422015-03-21 22:36:07 -07002452 const keymaster_blob_t* clientId,
2453 const keymaster_blob_t* appData,
Chad Brubakerf3f071f2015-02-10 19:38:51 -08002454 KeyCharacteristics* outCharacteristics) {
Chad Brubakerf3f071f2015-02-10 19:38:51 -08002455 if (!outCharacteristics) {
2456 return KM_ERROR_UNEXPECTED_NULL_POINTER;
2457 }
2458
2459 uid_t callingUid = IPCThreadState::self()->getCallingUid();
2460
2461 Blob keyBlob;
2462 String8 name8(name);
2463 int rc;
2464
2465 ResponseCode responseCode = mKeyStore->getKeyForName(&keyBlob, name8, callingUid,
2466 TYPE_KEYMASTER_10);
2467 if (responseCode != ::NO_ERROR) {
2468 return responseCode;
2469 }
2470 keymaster_key_blob_t key;
2471 key.key_material_size = keyBlob.getLength();
2472 key.key_material = keyBlob.getValue();
2473 keymaster1_device_t* dev = mKeyStore->getDeviceForBlob(keyBlob);
2474 keymaster_key_characteristics_t *out = NULL;
2475 if (!dev->get_key_characteristics) {
2476 ALOGW("device does not implement get_key_characteristics");
2477 return KM_ERROR_UNIMPLEMENTED;
2478 }
Chad Brubakerd6634422015-03-21 22:36:07 -07002479 rc = dev->get_key_characteristics(dev, &key, clientId, appData, &out);
Chad Brubakerf3f071f2015-02-10 19:38:51 -08002480 if (out) {
2481 outCharacteristics->characteristics = *out;
2482 free(out);
2483 }
2484 return rc ? rc : ::NO_ERROR;
Chad Brubaker9899d6b2015-02-03 13:03:00 -08002485 }
2486
Chad Brubaker4c353cb2015-02-11 14:36:11 -08002487 int32_t importKey(const String16& name, const KeymasterArguments& params,
2488 keymaster_key_format_t format, const uint8_t *keyData,
2489 size_t keyLength, int uid, int flags,
2490 KeyCharacteristics* outCharacteristics) {
Chad Brubaker9489b792015-04-14 11:01:45 -07002491 uid = getEffectiveUid(uid);
2492 int rc = checkBinderPermissionAndKeystoreState(P_INSERT, uid,
2493 flags & KEYSTORE_FLAG_ENCRYPTED);
2494 if (rc != ::NO_ERROR) {
2495 return rc;
Chad Brubaker4c353cb2015-02-11 14:36:11 -08002496 }
2497
Chad Brubaker9489b792015-04-14 11:01:45 -07002498 rc = KM_ERROR_UNIMPLEMENTED;
Chad Brubaker4c353cb2015-02-11 14:36:11 -08002499 bool isFallback = false;
2500 keymaster_key_blob_t blob;
2501 keymaster_key_characteristics_t *out = NULL;
2502
2503 const keymaster1_device_t* device = mKeyStore->getDevice();
2504 const keymaster1_device_t* fallback = mKeyStore->getFallbackDevice();
Chad Brubaker57e106d2015-06-01 12:59:00 -07002505 std::vector<keymaster_key_param_t> opParams(params.params);
2506 const keymaster_key_param_set_t inParams = {opParams.data(), opParams.size()};
2507 const keymaster_blob_t input = {keyData, keyLength};
Chad Brubaker4c353cb2015-02-11 14:36:11 -08002508 if (device == NULL) {
2509 return ::SYSTEM_ERROR;
2510 }
2511 if (device->common.module->module_api_version >= KEYMASTER_MODULE_API_VERSION_1_0 &&
2512 device->import_key != NULL) {
Chad Brubaker57e106d2015-06-01 12:59:00 -07002513 rc = device->import_key(device, &inParams, format,&input, &blob, &out);
Chad Brubaker4c353cb2015-02-11 14:36:11 -08002514 }
2515 if (rc && fallback->import_key != NULL) {
Shawn Willden7e8eabb2015-07-28 11:06:00 -06002516 ALOGW("Primary keymaster device failed to import key, falling back to SW.");
Chad Brubaker4c353cb2015-02-11 14:36:11 -08002517 isFallback = true;
Chad Brubaker57e106d2015-06-01 12:59:00 -07002518 rc = fallback->import_key(fallback, &inParams, format, &input, &blob, &out);
Chad Brubaker4c353cb2015-02-11 14:36:11 -08002519 }
2520 if (out) {
2521 if (outCharacteristics) {
2522 outCharacteristics->characteristics = *out;
2523 } else {
2524 keymaster_free_characteristics(out);
2525 }
2526 free(out);
2527 }
2528 if (rc) {
2529 return rc;
2530 }
2531
2532 String8 name8(name);
2533 String8 filename(mKeyStore->getKeyNameForUidWithDir(name8, uid));
2534
2535 Blob keyBlob(blob.key_material, blob.key_material_size, NULL, 0, ::TYPE_KEYMASTER_10);
2536 keyBlob.setFallback(isFallback);
2537 keyBlob.setEncrypted(flags & KEYSTORE_FLAG_ENCRYPTED);
2538
2539 free((void*) blob.key_material);
2540
Chad Brubaker72593ee2015-05-12 10:42:00 -07002541 return mKeyStore->put(filename.string(), &keyBlob, get_user_id(uid));
Chad Brubaker9899d6b2015-02-03 13:03:00 -08002542 }
2543
Chad Brubaker07b0cda2015-02-18 15:52:54 -08002544 void exportKey(const String16& name, keymaster_key_format_t format,
Chad Brubakerd6634422015-03-21 22:36:07 -07002545 const keymaster_blob_t* clientId,
2546 const keymaster_blob_t* appData, ExportResult* result) {
Chad Brubaker07b0cda2015-02-18 15:52:54 -08002547
2548 uid_t callingUid = IPCThreadState::self()->getCallingUid();
2549
2550 Blob keyBlob;
2551 String8 name8(name);
2552 int rc;
2553
2554 ResponseCode responseCode = mKeyStore->getKeyForName(&keyBlob, name8, callingUid,
2555 TYPE_KEYMASTER_10);
2556 if (responseCode != ::NO_ERROR) {
2557 result->resultCode = responseCode;
2558 return;
2559 }
2560 keymaster_key_blob_t key;
2561 key.key_material_size = keyBlob.getLength();
2562 key.key_material = keyBlob.getValue();
2563 keymaster1_device_t* dev = mKeyStore->getDeviceForBlob(keyBlob);
2564 if (!dev->export_key) {
2565 result->resultCode = KM_ERROR_UNIMPLEMENTED;
2566 return;
2567 }
Chad Brubaker57e106d2015-06-01 12:59:00 -07002568 keymaster_blob_t output = {NULL, 0};
2569 rc = dev->export_key(dev, format, &key, clientId, appData, &output);
2570 result->exportData.reset(const_cast<uint8_t*>(output.data));
2571 result->dataLength = output.data_length;
Chad Brubaker07b0cda2015-02-18 15:52:54 -08002572 result->resultCode = rc ? rc : ::NO_ERROR;
Chad Brubaker9899d6b2015-02-03 13:03:00 -08002573 }
2574
Chad Brubakerad6514a2015-04-09 14:00:26 -07002575
Chad Brubaker40a1a9b2015-02-20 14:08:13 -08002576 void begin(const sp<IBinder>& appToken, const String16& name, keymaster_purpose_t purpose,
Chad Brubaker154d7692015-03-27 13:59:31 -07002577 bool pruneable, const KeymasterArguments& params, const uint8_t* entropy,
Chad Brubaker57e106d2015-06-01 12:59:00 -07002578 size_t entropyLength, OperationResult* result) {
Chad Brubaker40a1a9b2015-02-20 14:08:13 -08002579 uid_t callingUid = IPCThreadState::self()->getCallingUid();
2580 if (!pruneable && get_app_id(callingUid) != AID_SYSTEM) {
2581 ALOGE("Non-system uid %d trying to start non-pruneable operation", callingUid);
2582 result->resultCode = ::PERMISSION_DENIED;
2583 return;
2584 }
Chad Brubaker0cf34a22015-04-23 11:06:16 -07002585 if (!checkAllowedOperationParams(params.params)) {
2586 result->resultCode = KM_ERROR_INVALID_ARGUMENT;
2587 return;
2588 }
Chad Brubaker40a1a9b2015-02-20 14:08:13 -08002589 Blob keyBlob;
2590 String8 name8(name);
2591 ResponseCode responseCode = mKeyStore->getKeyForName(&keyBlob, name8, callingUid,
2592 TYPE_KEYMASTER_10);
2593 if (responseCode != ::NO_ERROR) {
2594 result->resultCode = responseCode;
2595 return;
2596 }
2597 keymaster_key_blob_t key;
2598 key.key_material_size = keyBlob.getLength();
2599 key.key_material = keyBlob.getValue();
Chad Brubaker40a1a9b2015-02-20 14:08:13 -08002600 keymaster_operation_handle_t handle;
2601 keymaster1_device_t* dev = mKeyStore->getDeviceForBlob(keyBlob);
Chad Brubaker154d7692015-03-27 13:59:31 -07002602 keymaster_error_t err = KM_ERROR_UNIMPLEMENTED;
Chad Brubaker06801e02015-03-31 15:13:13 -07002603 std::vector<keymaster_key_param_t> opParams(params.params);
Chad Brubakerad6514a2015-04-09 14:00:26 -07002604 Unique_keymaster_key_characteristics characteristics;
2605 characteristics.reset(new keymaster_key_characteristics_t);
2606 err = getOperationCharacteristics(key, dev, opParams, characteristics.get());
2607 if (err) {
2608 result->resultCode = err;
2609 return;
2610 }
Chad Brubaker0cf34a22015-04-23 11:06:16 -07002611 const hw_auth_token_t* authToken = NULL;
Shawn Willdenb2ffa422015-06-17 12:18:55 -06002612 int32_t authResult = getAuthToken(characteristics.get(), 0, purpose, &authToken,
Chad Brubaker06801e02015-03-31 15:13:13 -07002613 /*failOnTokenMissing*/ false);
Chad Brubaker0cf34a22015-04-23 11:06:16 -07002614 // If per-operation auth is needed we need to begin the operation and
2615 // the client will need to authorize that operation before calling
2616 // update. Any other auth issues stop here.
2617 if (authResult != ::NO_ERROR && authResult != ::OP_AUTH_NEEDED) {
2618 result->resultCode = authResult;
Chad Brubaker06801e02015-03-31 15:13:13 -07002619 return;
2620 }
Chad Brubaker0cf34a22015-04-23 11:06:16 -07002621 addAuthToParams(&opParams, authToken);
Chad Brubaker154d7692015-03-27 13:59:31 -07002622 // Add entropy to the device first.
2623 if (entropy) {
2624 if (dev->add_rng_entropy) {
2625 err = dev->add_rng_entropy(dev, entropy, entropyLength);
2626 } else {
2627 err = KM_ERROR_UNIMPLEMENTED;
2628 }
2629 if (err) {
2630 result->resultCode = err;
2631 return;
2632 }
2633 }
Chad Brubaker57e106d2015-06-01 12:59:00 -07002634 keymaster_key_param_set_t inParams = {opParams.data(), opParams.size()};
Chad Brubaker40a1a9b2015-02-20 14:08:13 -08002635
Shawn Willden9221bff2015-06-18 18:23:54 -06002636 // Create a keyid for this key.
2637 keymaster::km_id_t keyid;
2638 if (!enforcement_policy.CreateKeyId(key, &keyid)) {
2639 ALOGE("Failed to create a key ID for authorization checking.");
2640 result->resultCode = KM_ERROR_UNKNOWN_ERROR;
2641 return;
2642 }
2643
2644 // Check that all key authorization policy requirements are met.
2645 keymaster::AuthorizationSet key_auths(characteristics->hw_enforced);
2646 key_auths.push_back(characteristics->sw_enforced);
2647 keymaster::AuthorizationSet operation_params(inParams);
2648 err = enforcement_policy.AuthorizeOperation(purpose, keyid, key_auths, operation_params,
2649 0 /* op_handle */,
2650 true /* is_begin_operation */);
2651 if (err) {
2652 result->resultCode = err;
2653 return;
2654 }
2655
Alex Klyubin4e88f9b2015-06-23 15:04:05 -07002656 keymaster_key_param_set_t outParams = {NULL, 0};
2657 err = dev->begin(dev, purpose, &key, &inParams, &outParams, &handle);
2658
Chad Brubaker40a1a9b2015-02-20 14:08:13 -08002659 // If there are too many operations abort the oldest operation that was
2660 // started as pruneable and try again.
2661 while (err == KM_ERROR_TOO_MANY_OPERATIONS && mOperationMap.hasPruneableOperation()) {
2662 sp<IBinder> oldest = mOperationMap.getOldestPruneableOperation();
2663 ALOGD("Ran out of operation handles, trying to prune %p", oldest.get());
Alex Klyubin700c1a32015-06-23 15:21:51 -07002664
2665 // We mostly ignore errors from abort() below because all we care about is whether at
2666 // least one pruneable operation has been removed.
2667 size_t op_count_before = mOperationMap.getPruneableOperationCount();
2668 int abort_error = abort(oldest);
2669 size_t op_count_after = mOperationMap.getPruneableOperationCount();
2670 if (op_count_after >= op_count_before) {
2671 // Failed to create space for a new operation. Bail to avoid an infinite loop.
2672 ALOGE("Failed to remove pruneable operation %p, error: %d",
2673 oldest.get(), abort_error);
Chad Brubaker40a1a9b2015-02-20 14:08:13 -08002674 break;
2675 }
Chad Brubaker57e106d2015-06-01 12:59:00 -07002676 err = dev->begin(dev, purpose, &key, &inParams, &outParams, &handle);
Chad Brubaker40a1a9b2015-02-20 14:08:13 -08002677 }
2678 if (err) {
2679 result->resultCode = err;
2680 return;
2681 }
Chad Brubaker40a1a9b2015-02-20 14:08:13 -08002682
Shawn Willden9221bff2015-06-18 18:23:54 -06002683 sp<IBinder> operationToken = mOperationMap.addOperation(handle, keyid, purpose, dev,
2684 appToken, characteristics.release(),
Chad Brubaker06801e02015-03-31 15:13:13 -07002685 pruneable);
Chad Brubaker0cf34a22015-04-23 11:06:16 -07002686 if (authToken) {
2687 mOperationMap.setOperationAuthToken(operationToken, authToken);
2688 }
2689 // Return the authentication lookup result. If this is a per operation
2690 // auth'd key then the resultCode will be ::OP_AUTH_NEEDED and the
2691 // application should get an auth token using the handle before the
2692 // first call to update, which will fail if keystore hasn't received the
2693 // auth token.
2694 result->resultCode = authResult;
Chad Brubaker40a1a9b2015-02-20 14:08:13 -08002695 result->token = operationToken;
Chad Brubakerc3a18562015-03-17 18:21:35 -07002696 result->handle = handle;
Chad Brubaker57e106d2015-06-01 12:59:00 -07002697 if (outParams.params) {
2698 result->outParams.params.assign(outParams.params, outParams.params + outParams.length);
2699 free(outParams.params);
2700 }
Chad Brubaker9899d6b2015-02-03 13:03:00 -08002701 }
2702
Chad Brubaker40a1a9b2015-02-20 14:08:13 -08002703 void update(const sp<IBinder>& token, const KeymasterArguments& params, const uint8_t* data,
2704 size_t dataLength, OperationResult* result) {
Chad Brubaker0cf34a22015-04-23 11:06:16 -07002705 if (!checkAllowedOperationParams(params.params)) {
2706 result->resultCode = KM_ERROR_INVALID_ARGUMENT;
2707 return;
2708 }
Chad Brubaker40a1a9b2015-02-20 14:08:13 -08002709 const keymaster1_device_t* dev;
2710 keymaster_operation_handle_t handle;
Shawn Willdenb2ffa422015-06-17 12:18:55 -06002711 keymaster_purpose_t purpose;
Shawn Willden9221bff2015-06-18 18:23:54 -06002712 keymaster::km_id_t keyid;
2713 const keymaster_key_characteristics_t* characteristics;
2714 if (!mOperationMap.getOperation(token, &handle, &keyid, &purpose, &dev, &characteristics)) {
Chad Brubaker40a1a9b2015-02-20 14:08:13 -08002715 result->resultCode = KM_ERROR_INVALID_OPERATION_HANDLE;
2716 return;
2717 }
Chad Brubaker06801e02015-03-31 15:13:13 -07002718 std::vector<keymaster_key_param_t> opParams(params.params);
Chad Brubaker0cf34a22015-04-23 11:06:16 -07002719 int32_t authResult = addOperationAuthTokenIfNeeded(token, &opParams);
2720 if (authResult != ::NO_ERROR) {
Chad Brubaker06801e02015-03-31 15:13:13 -07002721 result->resultCode = authResult;
2722 return;
2723 }
Chad Brubaker57e106d2015-06-01 12:59:00 -07002724 keymaster_key_param_set_t inParams = {opParams.data(), opParams.size()};
2725 keymaster_blob_t input = {data, dataLength};
2726 size_t consumed = 0;
2727 keymaster_blob_t output = {NULL, 0};
2728 keymaster_key_param_set_t outParams = {NULL, 0};
2729
Shawn Willden9221bff2015-06-18 18:23:54 -06002730 // Check that all key authorization policy requirements are met.
2731 keymaster::AuthorizationSet key_auths(characteristics->hw_enforced);
2732 key_auths.push_back(characteristics->sw_enforced);
2733 keymaster::AuthorizationSet operation_params(inParams);
2734 result->resultCode =
2735 enforcement_policy.AuthorizeOperation(purpose, keyid, key_auths,
2736 operation_params, handle,
2737 false /* is_begin_operation */);
2738 if (result->resultCode) {
2739 return;
2740 }
2741
Chad Brubaker57e106d2015-06-01 12:59:00 -07002742 keymaster_error_t err = dev->update(dev, handle, &inParams, &input, &consumed, &outParams,
2743 &output);
2744 result->data.reset(const_cast<uint8_t*>(output.data));
2745 result->dataLength = output.data_length;
Chad Brubaker40a1a9b2015-02-20 14:08:13 -08002746 result->inputConsumed = consumed;
2747 result->resultCode = err ? (int32_t) err : ::NO_ERROR;
Chad Brubaker57e106d2015-06-01 12:59:00 -07002748 if (outParams.params) {
2749 result->outParams.params.assign(outParams.params, outParams.params + outParams.length);
2750 free(outParams.params);
2751 }
Chad Brubaker9899d6b2015-02-03 13:03:00 -08002752 }
2753
Chad Brubaker40a1a9b2015-02-20 14:08:13 -08002754 void finish(const sp<IBinder>& token, const KeymasterArguments& params,
Chad Brubaker0d33e0b2015-05-29 12:30:19 -07002755 const uint8_t* signature, size_t signatureLength,
2756 const uint8_t* entropy, size_t entropyLength, OperationResult* result) {
Chad Brubaker0cf34a22015-04-23 11:06:16 -07002757 if (!checkAllowedOperationParams(params.params)) {
2758 result->resultCode = KM_ERROR_INVALID_ARGUMENT;
2759 return;
2760 }
Chad Brubaker40a1a9b2015-02-20 14:08:13 -08002761 const keymaster1_device_t* dev;
2762 keymaster_operation_handle_t handle;
Shawn Willdenb2ffa422015-06-17 12:18:55 -06002763 keymaster_purpose_t purpose;
Shawn Willden9221bff2015-06-18 18:23:54 -06002764 keymaster::km_id_t keyid;
2765 const keymaster_key_characteristics_t* characteristics;
2766 if (!mOperationMap.getOperation(token, &handle, &keyid, &purpose, &dev, &characteristics)) {
Chad Brubaker40a1a9b2015-02-20 14:08:13 -08002767 result->resultCode = KM_ERROR_INVALID_OPERATION_HANDLE;
2768 return;
2769 }
Chad Brubaker06801e02015-03-31 15:13:13 -07002770 std::vector<keymaster_key_param_t> opParams(params.params);
Chad Brubaker0cf34a22015-04-23 11:06:16 -07002771 int32_t authResult = addOperationAuthTokenIfNeeded(token, &opParams);
2772 if (authResult != ::NO_ERROR) {
Chad Brubaker06801e02015-03-31 15:13:13 -07002773 result->resultCode = authResult;
2774 return;
2775 }
Chad Brubaker0d33e0b2015-05-29 12:30:19 -07002776 keymaster_error_t err;
2777 if (entropy) {
2778 if (dev->add_rng_entropy) {
2779 err = dev->add_rng_entropy(dev, entropy, entropyLength);
2780 } else {
2781 err = KM_ERROR_UNIMPLEMENTED;
2782 }
2783 if (err) {
2784 result->resultCode = err;
2785 return;
2786 }
2787 }
Chad Brubaker0cf34a22015-04-23 11:06:16 -07002788
Chad Brubaker57e106d2015-06-01 12:59:00 -07002789 keymaster_key_param_set_t inParams = {opParams.data(), opParams.size()};
2790 keymaster_blob_t input = {signature, signatureLength};
2791 keymaster_blob_t output = {NULL, 0};
2792 keymaster_key_param_set_t outParams = {NULL, 0};
Shawn Willden9221bff2015-06-18 18:23:54 -06002793
2794 // Check that all key authorization policy requirements are met.
2795 keymaster::AuthorizationSet key_auths(characteristics->hw_enforced);
2796 key_auths.push_back(characteristics->sw_enforced);
2797 keymaster::AuthorizationSet operation_params(inParams);
2798 err = enforcement_policy.AuthorizeOperation(purpose, keyid, key_auths, operation_params,
2799 handle, false /* is_begin_operation */);
2800 if (err) {
2801 result->resultCode = err;
2802 return;
2803 }
2804
Chad Brubaker0d33e0b2015-05-29 12:30:19 -07002805 err = dev->finish(dev, handle, &inParams, &input, &outParams, &output);
Chad Brubaker40a1a9b2015-02-20 14:08:13 -08002806 // Remove the operation regardless of the result
2807 mOperationMap.removeOperation(token);
Chad Brubaker06801e02015-03-31 15:13:13 -07002808 mAuthTokenTable.MarkCompleted(handle);
Chad Brubaker57e106d2015-06-01 12:59:00 -07002809
2810 result->data.reset(const_cast<uint8_t*>(output.data));
2811 result->dataLength = output.data_length;
Chad Brubaker40a1a9b2015-02-20 14:08:13 -08002812 result->resultCode = err ? (int32_t) err : ::NO_ERROR;
Chad Brubaker57e106d2015-06-01 12:59:00 -07002813 if (outParams.params) {
2814 result->outParams.params.assign(outParams.params, outParams.params + outParams.length);
2815 free(outParams.params);
2816 }
Chad Brubaker9899d6b2015-02-03 13:03:00 -08002817 }
2818
Chad Brubaker40a1a9b2015-02-20 14:08:13 -08002819 int32_t abort(const sp<IBinder>& token) {
2820 const keymaster1_device_t* dev;
2821 keymaster_operation_handle_t handle;
Shawn Willdenb2ffa422015-06-17 12:18:55 -06002822 keymaster_purpose_t purpose;
Shawn Willden9221bff2015-06-18 18:23:54 -06002823 keymaster::km_id_t keyid;
2824 if (!mOperationMap.getOperation(token, &handle, &keyid, &purpose, &dev, NULL)) {
Chad Brubaker40a1a9b2015-02-20 14:08:13 -08002825 return KM_ERROR_INVALID_OPERATION_HANDLE;
2826 }
2827 mOperationMap.removeOperation(token);
Chad Brubaker06801e02015-03-31 15:13:13 -07002828 int32_t rc;
Chad Brubaker40a1a9b2015-02-20 14:08:13 -08002829 if (!dev->abort) {
Chad Brubaker06801e02015-03-31 15:13:13 -07002830 rc = KM_ERROR_UNIMPLEMENTED;
2831 } else {
2832 rc = dev->abort(dev, handle);
Chad Brubaker40a1a9b2015-02-20 14:08:13 -08002833 }
Chad Brubaker06801e02015-03-31 15:13:13 -07002834 mAuthTokenTable.MarkCompleted(handle);
Chad Brubaker40a1a9b2015-02-20 14:08:13 -08002835 if (rc) {
2836 return rc;
2837 }
2838 return ::NO_ERROR;
Chad Brubaker9899d6b2015-02-03 13:03:00 -08002839 }
2840
Chad Brubaker2ed2baa2015-03-21 21:20:10 -07002841 bool isOperationAuthorized(const sp<IBinder>& token) {
2842 const keymaster1_device_t* dev;
2843 keymaster_operation_handle_t handle;
Chad Brubakerad6514a2015-04-09 14:00:26 -07002844 const keymaster_key_characteristics_t* characteristics;
Shawn Willdenb2ffa422015-06-17 12:18:55 -06002845 keymaster_purpose_t purpose;
Shawn Willden9221bff2015-06-18 18:23:54 -06002846 keymaster::km_id_t keyid;
2847 if (!mOperationMap.getOperation(token, &handle, &keyid, &purpose, &dev, &characteristics)) {
Chad Brubaker2ed2baa2015-03-21 21:20:10 -07002848 return false;
2849 }
Chad Brubaker0cf34a22015-04-23 11:06:16 -07002850 const hw_auth_token_t* authToken = NULL;
2851 mOperationMap.getOperationAuthToken(token, &authToken);
Chad Brubaker06801e02015-03-31 15:13:13 -07002852 std::vector<keymaster_key_param_t> ignored;
Chad Brubaker0cf34a22015-04-23 11:06:16 -07002853 int32_t authResult = addOperationAuthTokenIfNeeded(token, &ignored);
2854 return authResult == ::NO_ERROR;
Chad Brubaker2ed2baa2015-03-21 21:20:10 -07002855 }
2856
Chad Brubakerd80c7b42015-03-31 11:04:28 -07002857 int32_t addAuthToken(const uint8_t* token, size_t length) {
Chad Brubaker9489b792015-04-14 11:01:45 -07002858 if (!checkBinderPermission(P_ADD_AUTH)) {
2859 ALOGW("addAuthToken: permission denied for %d",
2860 IPCThreadState::self()->getCallingUid());
Chad Brubakerd80c7b42015-03-31 11:04:28 -07002861 return ::PERMISSION_DENIED;
2862 }
2863 if (length != sizeof(hw_auth_token_t)) {
2864 return KM_ERROR_INVALID_ARGUMENT;
2865 }
2866 hw_auth_token_t* authToken = new hw_auth_token_t;
2867 memcpy(reinterpret_cast<void*>(authToken), token, sizeof(hw_auth_token_t));
2868 // The table takes ownership of authToken.
2869 mAuthTokenTable.AddAuthenticationToken(authToken);
2870 return ::NO_ERROR;
Chad Brubaker2ed2baa2015-03-21 21:20:10 -07002871 }
2872
Kenny Root07438c82012-11-02 15:41:02 -07002873private:
Chad Brubaker9489b792015-04-14 11:01:45 -07002874 static const int32_t UID_SELF = -1;
2875
2876 /**
2877 * Get the effective target uid for a binder operation that takes an
2878 * optional uid as the target.
2879 */
2880 inline uid_t getEffectiveUid(int32_t targetUid) {
2881 if (targetUid == UID_SELF) {
2882 return IPCThreadState::self()->getCallingUid();
2883 }
2884 return static_cast<uid_t>(targetUid);
2885 }
2886
2887 /**
2888 * Check if the caller of the current binder method has the required
2889 * permission and if acting on other uids the grants to do so.
2890 */
2891 inline bool checkBinderPermission(perm_t permission, int32_t targetUid = UID_SELF) {
2892 uid_t callingUid = IPCThreadState::self()->getCallingUid();
2893 pid_t spid = IPCThreadState::self()->getCallingPid();
2894 if (!has_permission(callingUid, permission, spid)) {
2895 ALOGW("permission %s denied for %d", get_perm_label(permission), callingUid);
2896 return false;
2897 }
2898 if (!is_granted_to(callingUid, getEffectiveUid(targetUid))) {
2899 ALOGW("uid %d not granted to act for %d", callingUid, targetUid);
2900 return false;
2901 }
2902 return true;
2903 }
2904
2905 /**
2906 * Check if the caller of the current binder method has the required
Chad Brubakerb37a5232015-05-01 10:21:27 -07002907 * permission and the target uid is the caller or the caller is system.
2908 */
2909 inline bool checkBinderPermissionSelfOrSystem(perm_t permission, int32_t targetUid) {
2910 uid_t callingUid = IPCThreadState::self()->getCallingUid();
2911 pid_t spid = IPCThreadState::self()->getCallingPid();
2912 if (!has_permission(callingUid, permission, spid)) {
2913 ALOGW("permission %s denied for %d", get_perm_label(permission), callingUid);
2914 return false;
2915 }
2916 return getEffectiveUid(targetUid) == callingUid || callingUid == AID_SYSTEM;
2917 }
2918
2919 /**
2920 * Check if the caller of the current binder method has the required
Chad Brubaker9489b792015-04-14 11:01:45 -07002921 * permission or the target of the operation is the caller's uid. This is
2922 * for operation where the permission is only for cross-uid activity and all
2923 * uids are allowed to act on their own (ie: clearing all entries for a
2924 * given uid).
2925 */
2926 inline bool checkBinderPermissionOrSelfTarget(perm_t permission, int32_t targetUid) {
2927 uid_t callingUid = IPCThreadState::self()->getCallingUid();
2928 if (getEffectiveUid(targetUid) == callingUid) {
2929 return true;
2930 } else {
2931 return checkBinderPermission(permission, targetUid);
2932 }
2933 }
2934
2935 /**
2936 * Helper method to check that the caller has the required permission as
2937 * well as the keystore is in the unlocked state if checkUnlocked is true.
2938 *
2939 * Returns NO_ERROR on success, PERMISSION_DENIED on a permission error and
2940 * otherwise the state of keystore when not unlocked and checkUnlocked is
2941 * true.
2942 */
2943 inline int32_t checkBinderPermissionAndKeystoreState(perm_t permission, int32_t targetUid = -1,
2944 bool checkUnlocked = true) {
2945 if (!checkBinderPermission(permission, targetUid)) {
2946 return ::PERMISSION_DENIED;
2947 }
Chad Brubaker72593ee2015-05-12 10:42:00 -07002948 State state = mKeyStore->getState(get_user_id(getEffectiveUid(targetUid)));
Chad Brubaker9489b792015-04-14 11:01:45 -07002949 if (checkUnlocked && !isKeystoreUnlocked(state)) {
2950 return state;
2951 }
2952
2953 return ::NO_ERROR;
2954
2955 }
2956
Kenny Root9d45d1c2013-02-14 10:32:30 -08002957 inline bool isKeystoreUnlocked(State state) {
2958 switch (state) {
2959 case ::STATE_NO_ERROR:
2960 return true;
2961 case ::STATE_UNINITIALIZED:
2962 case ::STATE_LOCKED:
2963 return false;
2964 }
2965 return false;
Kenny Root07438c82012-11-02 15:41:02 -07002966 }
2967
Chad Brubaker67d2a502015-03-11 17:21:18 +00002968 bool isKeyTypeSupported(const keymaster1_device_t* device, keymaster_keypair_t keyType) {
Kenny Root1d448c02013-11-21 10:36:53 -08002969 const int32_t device_api = device->common.module->module_api_version;
2970 if (device_api == KEYMASTER_MODULE_API_VERSION_0_2) {
2971 switch (keyType) {
2972 case TYPE_RSA:
2973 case TYPE_DSA:
2974 case TYPE_EC:
2975 return true;
2976 default:
2977 return false;
2978 }
2979 } else if (device_api >= KEYMASTER_MODULE_API_VERSION_0_3) {
2980 switch (keyType) {
2981 case TYPE_RSA:
2982 return true;
2983 case TYPE_DSA:
2984 return device->flags & KEYMASTER_SUPPORTS_DSA;
2985 case TYPE_EC:
2986 return device->flags & KEYMASTER_SUPPORTS_EC;
2987 default:
2988 return false;
2989 }
2990 } else {
2991 return keyType == TYPE_RSA;
2992 }
2993 }
2994
Chad Brubaker0cf34a22015-04-23 11:06:16 -07002995 /**
2996 * Check that all keymaster_key_param_t's provided by the application are
2997 * allowed. Any parameter that keystore adds itself should be disallowed here.
2998 */
2999 bool checkAllowedOperationParams(const std::vector<keymaster_key_param_t>& params) {
3000 for (auto param: params) {
3001 switch (param.tag) {
3002 case KM_TAG_AUTH_TOKEN:
3003 return false;
3004 default:
3005 break;
3006 }
3007 }
3008 return true;
3009 }
3010
3011 keymaster_error_t getOperationCharacteristics(const keymaster_key_blob_t& key,
3012 const keymaster1_device_t* dev,
3013 const std::vector<keymaster_key_param_t>& params,
3014 keymaster_key_characteristics_t* out) {
3015 UniquePtr<keymaster_blob_t> appId;
3016 UniquePtr<keymaster_blob_t> appData;
3017 for (auto param : params) {
3018 if (param.tag == KM_TAG_APPLICATION_ID) {
3019 appId.reset(new keymaster_blob_t);
3020 appId->data = param.blob.data;
3021 appId->data_length = param.blob.data_length;
3022 } else if (param.tag == KM_TAG_APPLICATION_DATA) {
3023 appData.reset(new keymaster_blob_t);
3024 appData->data = param.blob.data;
3025 appData->data_length = param.blob.data_length;
3026 }
3027 }
3028 keymaster_key_characteristics_t* result = NULL;
3029 if (!dev->get_key_characteristics) {
3030 return KM_ERROR_UNIMPLEMENTED;
3031 }
3032 keymaster_error_t error = dev->get_key_characteristics(dev, &key, appId.get(),
3033 appData.get(), &result);
3034 if (result) {
3035 *out = *result;
3036 free(result);
3037 }
3038 return error;
3039 }
3040
3041 /**
3042 * Get the auth token for this operation from the auth token table.
3043 *
3044 * Returns ::NO_ERROR if the auth token was set or none was required.
3045 * ::OP_AUTH_NEEDED if it is a per op authorization, no
3046 * authorization token exists for that operation and
3047 * failOnTokenMissing is false.
3048 * KM_ERROR_KEY_USER_NOT_AUTHENTICATED if there is no valid auth
3049 * token for the operation
3050 */
3051 int32_t getAuthToken(const keymaster_key_characteristics_t* characteristics,
3052 keymaster_operation_handle_t handle,
Shawn Willdenb2ffa422015-06-17 12:18:55 -06003053 keymaster_purpose_t purpose,
Chad Brubaker0cf34a22015-04-23 11:06:16 -07003054 const hw_auth_token_t** authToken,
3055 bool failOnTokenMissing = true) {
3056
3057 std::vector<keymaster_key_param_t> allCharacteristics;
3058 for (size_t i = 0; i < characteristics->sw_enforced.length; i++) {
3059 allCharacteristics.push_back(characteristics->sw_enforced.params[i]);
3060 }
3061 for (size_t i = 0; i < characteristics->hw_enforced.length; i++) {
3062 allCharacteristics.push_back(characteristics->hw_enforced.params[i]);
3063 }
Shawn Willdenb2ffa422015-06-17 12:18:55 -06003064 keymaster::AuthTokenTable::Error err = mAuthTokenTable.FindAuthorization(
3065 allCharacteristics.data(), allCharacteristics.size(), purpose, handle, authToken);
Chad Brubaker0cf34a22015-04-23 11:06:16 -07003066 switch (err) {
3067 case keymaster::AuthTokenTable::OK:
3068 case keymaster::AuthTokenTable::AUTH_NOT_REQUIRED:
3069 return ::NO_ERROR;
3070 case keymaster::AuthTokenTable::AUTH_TOKEN_NOT_FOUND:
3071 case keymaster::AuthTokenTable::AUTH_TOKEN_EXPIRED:
3072 case keymaster::AuthTokenTable::AUTH_TOKEN_WRONG_SID:
3073 return KM_ERROR_KEY_USER_NOT_AUTHENTICATED;
3074 case keymaster::AuthTokenTable::OP_HANDLE_REQUIRED:
3075 return failOnTokenMissing ? (int32_t) KM_ERROR_KEY_USER_NOT_AUTHENTICATED :
3076 (int32_t) ::OP_AUTH_NEEDED;
3077 default:
3078 ALOGE("Unexpected FindAuthorization return value %d", err);
3079 return KM_ERROR_INVALID_ARGUMENT;
3080 }
3081 }
3082
3083 inline void addAuthToParams(std::vector<keymaster_key_param_t>* params,
3084 const hw_auth_token_t* token) {
3085 if (token) {
3086 params->push_back(keymaster_param_blob(KM_TAG_AUTH_TOKEN,
3087 reinterpret_cast<const uint8_t*>(token),
3088 sizeof(hw_auth_token_t)));
3089 }
3090 }
3091
3092 /**
3093 * Add the auth token for the operation to the param list if the operation
3094 * requires authorization. Uses the cached result in the OperationMap if available
3095 * otherwise gets the token from the AuthTokenTable and caches the result.
3096 *
3097 * Returns ::NO_ERROR if the auth token was added or not needed.
3098 * KM_ERROR_KEY_USER_NOT_AUTHENTICATED if the operation is not
3099 * authenticated.
3100 * KM_ERROR_INVALID_OPERATION_HANDLE if token is not a valid
3101 * operation token.
3102 */
3103 int32_t addOperationAuthTokenIfNeeded(sp<IBinder> token,
3104 std::vector<keymaster_key_param_t>* params) {
3105 const hw_auth_token_t* authToken = NULL;
Chad Brubaker7169a842015-04-29 19:58:34 -07003106 mOperationMap.getOperationAuthToken(token, &authToken);
3107 if (!authToken) {
Chad Brubaker0cf34a22015-04-23 11:06:16 -07003108 const keymaster1_device_t* dev;
3109 keymaster_operation_handle_t handle;
3110 const keymaster_key_characteristics_t* characteristics = NULL;
Shawn Willdenb2ffa422015-06-17 12:18:55 -06003111 keymaster_purpose_t purpose;
Shawn Willden9221bff2015-06-18 18:23:54 -06003112 keymaster::km_id_t keyid;
3113 if (!mOperationMap.getOperation(token, &handle, &keyid, &purpose, &dev,
3114 &characteristics)) {
Chad Brubaker0cf34a22015-04-23 11:06:16 -07003115 return KM_ERROR_INVALID_OPERATION_HANDLE;
3116 }
Shawn Willdenb2ffa422015-06-17 12:18:55 -06003117 int32_t result = getAuthToken(characteristics, handle, purpose, &authToken);
Chad Brubaker0cf34a22015-04-23 11:06:16 -07003118 if (result != ::NO_ERROR) {
3119 return result;
3120 }
3121 if (authToken) {
3122 mOperationMap.setOperationAuthToken(token, authToken);
3123 }
3124 }
3125 addAuthToParams(params, authToken);
3126 return ::NO_ERROR;
3127 }
3128
Chad Brubaker3a7d9e62015-06-04 15:01:46 -07003129 /**
3130 * Translate a result value to a legacy return value. All keystore errors are
3131 * preserved and keymaster errors become SYSTEM_ERRORs
3132 */
3133 inline int32_t translateResultToLegacyResult(int32_t result) {
3134 if (result > 0) {
3135 return result;
3136 }
3137 return ::SYSTEM_ERROR;
3138 }
3139
Chad Brubaker3a7d9e62015-06-04 15:01:46 -07003140 keymaster_key_param_t* getKeyAlgorithm(keymaster_key_characteristics_t* characteristics) {
3141 for (size_t i = 0; i < characteristics->hw_enforced.length; i++) {
3142 if (characteristics->hw_enforced.params[i].tag == KM_TAG_ALGORITHM) {
3143 return &characteristics->hw_enforced.params[i];
3144 }
3145 }
3146 for (size_t i = 0; i < characteristics->sw_enforced.length; i++) {
3147 if (characteristics->sw_enforced.params[i].tag == KM_TAG_ALGORITHM) {
3148 return &characteristics->sw_enforced.params[i];
3149 }
3150 }
3151 return NULL;
3152 }
3153
3154 void addLegacyBeginParams(const String16& name, std::vector<keymaster_key_param_t>& params) {
3155 // All legacy keys are DIGEST_NONE/PAD_NONE.
3156 params.push_back(keymaster_param_enum(KM_TAG_DIGEST, KM_DIGEST_NONE));
3157 params.push_back(keymaster_param_enum(KM_TAG_PADDING, KM_PAD_NONE));
3158
3159 // Look up the algorithm of the key.
3160 KeyCharacteristics characteristics;
3161 int32_t rc = getKeyCharacteristics(name, NULL, NULL, &characteristics);
3162 if (rc != ::NO_ERROR) {
3163 ALOGE("Failed to get key characteristics");
3164 return;
3165 }
3166 keymaster_key_param_t* algorithm = getKeyAlgorithm(&characteristics.characteristics);
3167 if (!algorithm) {
3168 ALOGE("getKeyCharacteristics did not include KM_TAG_ALGORITHM");
3169 return;
3170 }
3171 params.push_back(*algorithm);
3172 }
3173
3174 int32_t doLegacySignVerify(const String16& name, const uint8_t* data, size_t length,
3175 uint8_t** out, size_t* outLength, const uint8_t* signature,
3176 size_t signatureLength, keymaster_purpose_t purpose) {
3177
Chad Brubaker3a7d9e62015-06-04 15:01:46 -07003178 std::basic_stringstream<uint8_t> outBuffer;
3179 OperationResult result;
3180 KeymasterArguments inArgs;
3181 addLegacyBeginParams(name, inArgs.params);
3182 sp<IBinder> appToken(new BBinder);
3183 sp<IBinder> token;
3184
3185 begin(appToken, name, purpose, true, inArgs, NULL, 0, &result);
3186 if (result.resultCode != ResponseCode::NO_ERROR) {
Chad Brubakerdf705172015-06-17 20:17:51 -07003187 if (result.resultCode == ::KEY_NOT_FOUND) {
3188 ALOGW("Key not found");
3189 } else {
3190 ALOGW("Error in begin: %d", result.resultCode);
3191 }
Chad Brubaker3a7d9e62015-06-04 15:01:46 -07003192 return translateResultToLegacyResult(result.resultCode);
3193 }
3194 inArgs.params.clear();
3195 token = result.token;
3196 size_t consumed = 0;
3197 size_t lastConsumed = 0;
3198 do {
3199 update(token, inArgs, data + consumed, length - consumed, &result);
3200 if (result.resultCode != ResponseCode::NO_ERROR) {
3201 ALOGW("Error in update: %d", result.resultCode);
3202 return translateResultToLegacyResult(result.resultCode);
3203 }
3204 if (out) {
3205 outBuffer.write(result.data.get(), result.dataLength);
3206 }
3207 lastConsumed = result.inputConsumed;
3208 consumed += lastConsumed;
3209 } while (consumed < length && lastConsumed > 0);
3210
3211 if (consumed != length) {
3212 ALOGW("Not all data consumed. Consumed %zu of %zu", consumed, length);
3213 return ::SYSTEM_ERROR;
3214 }
3215
3216 finish(token, inArgs, signature, signatureLength, NULL, 0, &result);
3217 if (result.resultCode != ResponseCode::NO_ERROR) {
3218 ALOGW("Error in finish: %d", result.resultCode);
3219 return translateResultToLegacyResult(result.resultCode);
3220 }
3221 if (out) {
3222 outBuffer.write(result.data.get(), result.dataLength);
3223 }
3224
3225 if (out) {
3226 auto buf = outBuffer.str();
3227 *out = new uint8_t[buf.size()];
3228 memcpy(*out, buf.c_str(), buf.size());
3229 *outLength = buf.size();
3230 }
3231
3232 return ::NO_ERROR;
3233 }
3234
Kenny Root07438c82012-11-02 15:41:02 -07003235 ::KeyStore* mKeyStore;
Chad Brubaker40a1a9b2015-02-20 14:08:13 -08003236 OperationMap mOperationMap;
Chad Brubakerd80c7b42015-03-31 11:04:28 -07003237 keymaster::AuthTokenTable mAuthTokenTable;
Shawn Willden9221bff2015-06-18 18:23:54 -06003238 KeystoreKeymasterEnforcement enforcement_policy;
Kenny Root07438c82012-11-02 15:41:02 -07003239};
3240
3241}; // namespace android
Kenny Roota91203b2012-02-15 15:00:46 -08003242
3243int main(int argc, char* argv[]) {
Kenny Roota91203b2012-02-15 15:00:46 -08003244 if (argc < 2) {
3245 ALOGE("A directory must be specified!");
3246 return 1;
3247 }
3248 if (chdir(argv[1]) == -1) {
3249 ALOGE("chdir: %s: %s", argv[1], strerror(errno));
3250 return 1;
3251 }
3252
3253 Entropy entropy;
3254 if (!entropy.open()) {
3255 return 1;
3256 }
Kenny Root70e3a862012-02-15 17:20:23 -08003257
Chad Brubakerbd07a232015-06-01 10:44:27 -07003258 keymaster1_device_t* dev;
Kenny Root70e3a862012-02-15 17:20:23 -08003259 if (keymaster_device_initialize(&dev)) {
3260 ALOGE("keystore keymaster could not be initialized; exiting");
3261 return 1;
3262 }
3263
Chad Brubaker67d2a502015-03-11 17:21:18 +00003264 keymaster1_device_t* fallback;
Chad Brubakerfc18edc2015-01-12 15:17:18 -08003265 if (fallback_keymaster_device_initialize(&fallback)) {
3266 ALOGE("software keymaster could not be initialized; exiting");
3267 return 1;
3268 }
3269
Riley Spahneaabae92014-06-30 12:39:52 -07003270 ks_is_selinux_enabled = is_selinux_enabled();
3271 if (ks_is_selinux_enabled) {
3272 union selinux_callback cb;
3273 cb.func_log = selinux_log_callback;
3274 selinux_set_callback(SELINUX_CB_LOG, cb);
3275 if (getcon(&tctx) != 0) {
3276 ALOGE("SELinux: Could not acquire target context. Aborting keystore.\n");
3277 return -1;
3278 }
3279 } else {
3280 ALOGI("SELinux: Keystore SELinux is disabled.\n");
3281 }
3282
Chad Brubakerbd07a232015-06-01 10:44:27 -07003283 KeyStore keyStore(&entropy, dev, fallback);
Kenny Root655b9582013-04-04 08:37:42 -07003284 keyStore.initialize();
Kenny Root07438c82012-11-02 15:41:02 -07003285 android::sp<android::IServiceManager> sm = android::defaultServiceManager();
3286 android::sp<android::KeyStoreProxy> proxy = new android::KeyStoreProxy(&keyStore);
3287 android::status_t ret = sm->addService(android::String16("android.security.keystore"), proxy);
3288 if (ret != android::OK) {
3289 ALOGE("Couldn't register binder service!");
3290 return -1;
Kenny Roota91203b2012-02-15 15:00:46 -08003291 }
Kenny Root07438c82012-11-02 15:41:02 -07003292
3293 /*
3294 * We're the only thread in existence, so we're just going to process
3295 * Binder transaction as a single-threaded program.
3296 */
3297 android::IPCThreadState::self()->joinThreadPool();
Kenny Root70e3a862012-02-15 17:20:23 -08003298
3299 keymaster_device_release(dev);
Kenny Roota91203b2012-02-15 15:00:46 -08003300 return 1;
3301}