blob: bb5a411e64e95fb2edc6b639d43de1e8da9fa24a [file] [log] [blame]
Kenny Roota91203b2012-02-15 15:00:46 -08001/*
2 * Copyright (C) 2009 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
Kenny Root07438c82012-11-02 15:41:02 -070017//#define LOG_NDEBUG 0
18#define LOG_TAG "keystore"
19
Kenny Roota91203b2012-02-15 15:00:46 -080020#include <stdio.h>
21#include <stdint.h>
22#include <string.h>
Elliott Hughesaaf98022015-01-25 08:40:44 -080023#include <strings.h>
Kenny Roota91203b2012-02-15 15:00:46 -080024#include <unistd.h>
25#include <signal.h>
26#include <errno.h>
27#include <dirent.h>
Kenny Root655b9582013-04-04 08:37:42 -070028#include <errno.h>
Kenny Roota91203b2012-02-15 15:00:46 -080029#include <fcntl.h>
30#include <limits.h>
Kenny Root822c3a92012-03-23 16:34:39 -070031#include <assert.h>
Kenny Roota91203b2012-02-15 15:00:46 -080032#include <sys/types.h>
33#include <sys/socket.h>
34#include <sys/stat.h>
35#include <sys/time.h>
36#include <arpa/inet.h>
37
38#include <openssl/aes.h>
Kenny Root822c3a92012-03-23 16:34:39 -070039#include <openssl/bio.h>
Kenny Roota91203b2012-02-15 15:00:46 -080040#include <openssl/evp.h>
41#include <openssl/md5.h>
Kenny Root822c3a92012-03-23 16:34:39 -070042#include <openssl/pem.h>
Kenny Roota91203b2012-02-15 15:00:46 -080043
Shawn Willden80843db2015-02-24 09:31:25 -070044#include <hardware/keymaster0.h>
Kenny Root70e3a862012-02-15 17:20:23 -080045
Chad Brubaker67d2a502015-03-11 17:21:18 +000046#include <keymaster/soft_keymaster_device.h>
Shawn Willden04006752015-04-30 11:12:33 -060047#include <keymaster/soft_keymaster_logger.h>
48#include <keymaster/softkeymaster.h>
Kenny Root17208e02013-09-04 13:56:03 -070049
Kenny Root26cfc082013-09-11 14:38:56 -070050#include <UniquePtr.h>
Kenny Root655b9582013-04-04 08:37:42 -070051#include <utils/String8.h>
Kenny Root655b9582013-04-04 08:37:42 -070052#include <utils/Vector.h>
Kenny Root70e3a862012-02-15 17:20:23 -080053
Kenny Root07438c82012-11-02 15:41:02 -070054#include <keystore/IKeystoreService.h>
55#include <binder/IPCThreadState.h>
56#include <binder/IServiceManager.h>
57
Kenny Roota91203b2012-02-15 15:00:46 -080058#include <cutils/log.h>
59#include <cutils/sockets.h>
60#include <private/android_filesystem_config.h>
61
Kenny Root07438c82012-11-02 15:41:02 -070062#include <keystore/keystore.h>
Kenny Roota91203b2012-02-15 15:00:46 -080063
Riley Spahneaabae92014-06-30 12:39:52 -070064#include <selinux/android.h>
65
Chad Brubaker3a7d9e62015-06-04 15:01:46 -070066#include <sstream>
67
Chad Brubakerd80c7b42015-03-31 11:04:28 -070068#include "auth_token_table.h"
Kenny Root96427ba2013-08-16 14:02:41 -070069#include "defaults.h"
Shawn Willden9221bff2015-06-18 18:23:54 -060070#include "keystore_keymaster_enforcement.h"
Chad Brubaker40a1a9b2015-02-20 14:08:13 -080071#include "operation.h"
Kenny Root96427ba2013-08-16 14:02:41 -070072
Kenny Roota91203b2012-02-15 15:00:46 -080073/* KeyStore is a secured storage for key-value pairs. In this implementation,
74 * each file stores one key-value pair. Keys are encoded in file names, and
75 * values are encrypted with checksums. The encryption key is protected by a
76 * user-defined password. To keep things simple, buffers are always larger than
77 * the maximum space we needed, so boundary checks on buffers are omitted. */
78
79#define KEY_SIZE ((NAME_MAX - 15) / 2)
80#define VALUE_SIZE 32768
81#define PASSWORD_SIZE VALUE_SIZE
82
Shawn Willden55268b52015-07-28 11:06:00 -060083using keymaster::SoftKeymasterDevice;
Kenny Root822c3a92012-03-23 16:34:39 -070084
Kenny Root96427ba2013-08-16 14:02:41 -070085struct BIGNUM_Delete {
86 void operator()(BIGNUM* p) const {
87 BN_free(p);
88 }
89};
90typedef UniquePtr<BIGNUM, BIGNUM_Delete> Unique_BIGNUM;
91
Kenny Root822c3a92012-03-23 16:34:39 -070092struct BIO_Delete {
93 void operator()(BIO* p) const {
94 BIO_free(p);
95 }
96};
97typedef UniquePtr<BIO, BIO_Delete> Unique_BIO;
98
99struct EVP_PKEY_Delete {
100 void operator()(EVP_PKEY* p) const {
101 EVP_PKEY_free(p);
102 }
103};
104typedef UniquePtr<EVP_PKEY, EVP_PKEY_Delete> Unique_EVP_PKEY;
105
106struct PKCS8_PRIV_KEY_INFO_Delete {
107 void operator()(PKCS8_PRIV_KEY_INFO* p) const {
108 PKCS8_PRIV_KEY_INFO_free(p);
109 }
110};
111typedef UniquePtr<PKCS8_PRIV_KEY_INFO, PKCS8_PRIV_KEY_INFO_Delete> Unique_PKCS8_PRIV_KEY_INFO;
112
Shawn Willden55268b52015-07-28 11:06:00 -0600113static int keymaster0_device_initialize(const hw_module_t* mod, keymaster1_device_t** dev) {
114 assert(mod->module_api_version < KEYMASTER_MODULE_API_VERSION_1_0);
115 ALOGI("Found keymaster0 module %s, version %x", mod->name, mod->module_api_version);
Kenny Root70e3a862012-02-15 17:20:23 -0800116
Shawn Willden55268b52015-07-28 11:06:00 -0600117 UniquePtr<SoftKeymasterDevice> soft_keymaster(new SoftKeymasterDevice);
118 keymaster0_device_t* km0_device = NULL;
119 keymaster_error_t error = KM_ERROR_OK;
120
121 int rc = keymaster0_open(mod, &km0_device);
Kenny Root70e3a862012-02-15 17:20:23 -0800122 if (rc) {
Shawn Willden55268b52015-07-28 11:06:00 -0600123 ALOGE("Error opening keystore keymaster0 device.");
124 goto err;
Kenny Root70e3a862012-02-15 17:20:23 -0800125 }
126
Shawn Willden55268b52015-07-28 11:06:00 -0600127 if (km0_device->flags & KEYMASTER_SOFTWARE_ONLY) {
128 ALOGI("Keymaster0 module is software-only. Using SoftKeymasterDevice instead.");
129 km0_device->common.close(&km0_device->common);
130 km0_device = NULL;
131 // SoftKeymasterDevice will be deleted by keymaster_device_release()
132 *dev = soft_keymaster.release()->keymaster_device();
Chad Brubakerbd07a232015-06-01 10:44:27 -0700133 return 0;
134 }
Shawn Willden55268b52015-07-28 11:06:00 -0600135
136 ALOGE("Wrapping keymaster0 module %s with SoftKeymasterDevice", mod->name);
137 error = soft_keymaster->SetHardwareDevice(km0_device);
138 km0_device = NULL; // SoftKeymasterDevice has taken ownership.
139 if (error != KM_ERROR_OK) {
140 ALOGE("Got error %d from SetHardwareDevice", error);
141 rc = error;
142 goto err;
143 }
144
145 // SoftKeymasterDevice will be deleted by keymaster_device_release()
146 *dev = soft_keymaster.release()->keymaster_device();
Kenny Root70e3a862012-02-15 17:20:23 -0800147 return 0;
148
Shawn Willden55268b52015-07-28 11:06:00 -0600149err:
150 if (km0_device)
151 km0_device->common.close(&km0_device->common);
Kenny Root70e3a862012-02-15 17:20:23 -0800152 *dev = NULL;
153 return rc;
154}
155
Shawn Willden55268b52015-07-28 11:06:00 -0600156static int keymaster1_device_initialize(const hw_module_t* mod, keymaster1_device_t** dev) {
157 assert(mod->module_api_version >= KEYMASTER_MODULE_API_VERSION_1_0);
158 ALOGI("Found keymaster1 module %s, version %x", mod->name, mod->module_api_version);
159
160 UniquePtr<SoftKeymasterDevice> soft_keymaster(new SoftKeymasterDevice);
161 keymaster1_device_t* km1_device = NULL;
162 keymaster_error_t error = KM_ERROR_OK;
163
164 int rc = keymaster1_open(mod, &km1_device);
165 if (rc) {
166 ALOGE("Error %d opening keystore keymaster1 device", rc);
167 goto err;
168 }
169
170 error = soft_keymaster->SetHardwareDevice(km1_device);
171 km1_device = NULL; // SoftKeymasterDevice has taken ownership.
172 if (error != KM_ERROR_OK) {
173 ALOGE("Got error %d from SetHardwareDevice", error);
174 rc = error;
175 goto err;
176 }
177
178 if (!soft_keymaster->Keymaster1DeviceIsGood()) {
179 ALOGI("Keymaster1 module is incomplete, using SoftKeymasterDevice wrapper");
180 // SoftKeymasterDevice will be deleted by keymaster_device_release()
181 *dev = soft_keymaster.release()->keymaster_device();
182 return 0;
183 } else {
184 ALOGI("Keymaster1 module is good, destroying wrapper and re-opening");
185 soft_keymaster.reset(NULL);
186 rc = keymaster1_open(mod, &km1_device);
187 if (rc) {
188 ALOGE("Error %d re-opening keystore keymaster1 device.", rc);
189 goto err;
190 }
191 *dev = km1_device;
192 return 0;
193 }
194
195err:
196 if (km1_device)
197 km1_device->common.close(&km1_device->common);
198 *dev = NULL;
199 return rc;
200
201}
202
203static int keymaster_device_initialize(keymaster1_device_t** dev) {
204 const hw_module_t* mod;
205
206 int rc = hw_get_module_by_class(KEYSTORE_HARDWARE_MODULE_ID, NULL, &mod);
207 if (rc) {
208 ALOGI("Could not find any keystore module, using software-only implementation.");
209 // SoftKeymasterDevice will be deleted by keymaster_device_release()
210 *dev = (new SoftKeymasterDevice)->keymaster_device();
211 return 0;
212 }
213
214 if (mod->module_api_version < KEYMASTER_MODULE_API_VERSION_1_0) {
215 return keymaster0_device_initialize(mod, dev);
216 } else {
217 return keymaster1_device_initialize(mod, dev);
218 }
219}
220
Shawn Willden04006752015-04-30 11:12:33 -0600221// softkeymaster_logger appears not to be used in keystore, but it installs itself as the
222// logger used by SoftKeymasterDevice.
223static keymaster::SoftKeymasterLogger softkeymaster_logger;
224
Chad Brubaker67d2a502015-03-11 17:21:18 +0000225static int fallback_keymaster_device_initialize(keymaster1_device_t** dev) {
Shawn Willden55268b52015-07-28 11:06:00 -0600226 *dev = (new SoftKeymasterDevice)->keymaster_device();
227 // SoftKeymasterDevice will be deleted by keymaster_device_release()
Chad Brubakerfc18edc2015-01-12 15:17:18 -0800228 return 0;
Chad Brubakerfc18edc2015-01-12 15:17:18 -0800229}
230
Chad Brubakerbd07a232015-06-01 10:44:27 -0700231static void keymaster_device_release(keymaster1_device_t* dev) {
232 dev->common.close(&dev->common);
Kenny Root70e3a862012-02-15 17:20:23 -0800233}
234
Shawn Willden55268b52015-07-28 11:06:00 -0600235static void add_legacy_key_authorizations(int keyType, std::vector<keymaster_key_param_t>* params) {
236 params->push_back(keymaster_param_enum(KM_TAG_PURPOSE, KM_PURPOSE_SIGN));
237 params->push_back(keymaster_param_enum(KM_TAG_PURPOSE, KM_PURPOSE_VERIFY));
238 params->push_back(keymaster_param_enum(KM_TAG_PURPOSE, KM_PURPOSE_ENCRYPT));
239 params->push_back(keymaster_param_enum(KM_TAG_PURPOSE, KM_PURPOSE_DECRYPT));
240 params->push_back(keymaster_param_enum(KM_TAG_PADDING, KM_PAD_NONE));
241 if (keyType == EVP_PKEY_RSA) {
242 params->push_back(keymaster_param_enum(KM_TAG_PADDING, KM_PAD_RSA_PKCS1_1_5_SIGN));
243 params->push_back(keymaster_param_enum(KM_TAG_PADDING, KM_PAD_RSA_PKCS1_1_5_ENCRYPT));
244 params->push_back(keymaster_param_enum(KM_TAG_PADDING, KM_PAD_RSA_PSS));
245 params->push_back(keymaster_param_enum(KM_TAG_PADDING, KM_PAD_RSA_OAEP));
246 }
247 params->push_back(keymaster_param_enum(KM_TAG_DIGEST, KM_DIGEST_NONE));
248 params->push_back(keymaster_param_enum(KM_TAG_DIGEST, KM_DIGEST_MD5));
249 params->push_back(keymaster_param_enum(KM_TAG_DIGEST, KM_DIGEST_SHA1));
250 params->push_back(keymaster_param_enum(KM_TAG_DIGEST, KM_DIGEST_SHA_2_224));
251 params->push_back(keymaster_param_enum(KM_TAG_DIGEST, KM_DIGEST_SHA_2_256));
252 params->push_back(keymaster_param_enum(KM_TAG_DIGEST, KM_DIGEST_SHA_2_384));
253 params->push_back(keymaster_param_enum(KM_TAG_DIGEST, KM_DIGEST_SHA_2_512));
254 params->push_back(keymaster_param_bool(KM_TAG_ALL_USERS));
255 params->push_back(keymaster_param_bool(KM_TAG_NO_AUTH_REQUIRED));
256 params->push_back(keymaster_param_date(KM_TAG_ORIGINATION_EXPIRE_DATETIME, LLONG_MAX));
257 params->push_back(keymaster_param_date(KM_TAG_USAGE_EXPIRE_DATETIME, LLONG_MAX));
258 params->push_back(keymaster_param_date(KM_TAG_ACTIVE_DATETIME, 0));
259 uint64_t now = keymaster::java_time(time(NULL));
260 params->push_back(keymaster_param_date(KM_TAG_CREATION_DATETIME, now));
261}
262
Kenny Root07438c82012-11-02 15:41:02 -0700263/***************
264 * PERMISSIONS *
265 ***************/
266
267/* Here are the permissions, actions, users, and the main function. */
268typedef enum {
Chad Brubakere6c3bfa2015-05-12 15:18:26 -0700269 P_GET_STATE = 1 << 0,
Robin Lee4e865752014-08-19 17:37:55 +0100270 P_GET = 1 << 1,
271 P_INSERT = 1 << 2,
272 P_DELETE = 1 << 3,
273 P_EXIST = 1 << 4,
Chad Brubakere6c3bfa2015-05-12 15:18:26 -0700274 P_LIST = 1 << 5,
Robin Lee4e865752014-08-19 17:37:55 +0100275 P_RESET = 1 << 6,
276 P_PASSWORD = 1 << 7,
277 P_LOCK = 1 << 8,
278 P_UNLOCK = 1 << 9,
Chad Brubakere6c3bfa2015-05-12 15:18:26 -0700279 P_IS_EMPTY = 1 << 10,
Robin Lee4e865752014-08-19 17:37:55 +0100280 P_SIGN = 1 << 11,
281 P_VERIFY = 1 << 12,
282 P_GRANT = 1 << 13,
283 P_DUPLICATE = 1 << 14,
284 P_CLEAR_UID = 1 << 15,
Chad Brubakere6c3bfa2015-05-12 15:18:26 -0700285 P_ADD_AUTH = 1 << 16,
286 P_USER_CHANGED = 1 << 17,
Kenny Root07438c82012-11-02 15:41:02 -0700287} perm_t;
288
289static struct user_euid {
290 uid_t uid;
291 uid_t euid;
292} user_euids[] = {
293 {AID_VPN, AID_SYSTEM},
294 {AID_WIFI, AID_SYSTEM},
295 {AID_ROOT, AID_SYSTEM},
296};
297
Riley Spahneaabae92014-06-30 12:39:52 -0700298/* perm_labels associcated with keystore_key SELinux class verbs. */
299const char *perm_labels[] = {
Chad Brubakere6c3bfa2015-05-12 15:18:26 -0700300 "get_state",
Riley Spahneaabae92014-06-30 12:39:52 -0700301 "get",
302 "insert",
303 "delete",
304 "exist",
Chad Brubakere6c3bfa2015-05-12 15:18:26 -0700305 "list",
Riley Spahneaabae92014-06-30 12:39:52 -0700306 "reset",
307 "password",
308 "lock",
309 "unlock",
Chad Brubakere6c3bfa2015-05-12 15:18:26 -0700310 "is_empty",
Riley Spahneaabae92014-06-30 12:39:52 -0700311 "sign",
312 "verify",
313 "grant",
314 "duplicate",
Robin Lee4e865752014-08-19 17:37:55 +0100315 "clear_uid",
Chad Brubakerd80c7b42015-03-31 11:04:28 -0700316 "add_auth",
Chad Brubakerc0f031a2015-05-12 10:43:10 -0700317 "user_changed",
Riley Spahneaabae92014-06-30 12:39:52 -0700318};
319
Kenny Root07438c82012-11-02 15:41:02 -0700320static struct user_perm {
321 uid_t uid;
322 perm_t perms;
323} user_perms[] = {
324 {AID_SYSTEM, static_cast<perm_t>((uint32_t)(~0)) },
325 {AID_VPN, static_cast<perm_t>(P_GET | P_SIGN | P_VERIFY) },
326 {AID_WIFI, static_cast<perm_t>(P_GET | P_SIGN | P_VERIFY) },
327 {AID_ROOT, static_cast<perm_t>(P_GET) },
328};
329
Chad Brubakere6c3bfa2015-05-12 15:18:26 -0700330static const perm_t DEFAULT_PERMS = static_cast<perm_t>(P_GET_STATE | P_GET | P_INSERT | P_DELETE
331 | P_EXIST | P_LIST | P_SIGN | P_VERIFY);
Kenny Root07438c82012-11-02 15:41:02 -0700332
Riley Spahneaabae92014-06-30 12:39:52 -0700333static char *tctx;
334static int ks_is_selinux_enabled;
335
336static const char *get_perm_label(perm_t perm) {
337 unsigned int index = ffs(perm);
338 if (index > 0 && index <= (sizeof(perm_labels) / sizeof(perm_labels[0]))) {
339 return perm_labels[index - 1];
340 } else {
341 ALOGE("Keystore: Failed to retrieve permission label.\n");
342 abort();
343 }
344}
345
Kenny Root655b9582013-04-04 08:37:42 -0700346/**
347 * Returns the app ID (in the Android multi-user sense) for the current
348 * UNIX UID.
349 */
350static uid_t get_app_id(uid_t uid) {
351 return uid % AID_USER;
352}
353
354/**
355 * Returns the user ID (in the Android multi-user sense) for the current
356 * UNIX UID.
357 */
358static uid_t get_user_id(uid_t uid) {
359 return uid / AID_USER;
360}
361
Chih-Hung Hsieha25b2a32014-09-03 12:14:45 -0700362static bool keystore_selinux_check_access(uid_t /*uid*/, perm_t perm, pid_t spid) {
Riley Spahneaabae92014-06-30 12:39:52 -0700363 if (!ks_is_selinux_enabled) {
364 return true;
365 }
Nick Kralevich66dbf672014-06-30 17:09:14 +0000366
Riley Spahneaabae92014-06-30 12:39:52 -0700367 char *sctx = NULL;
368 const char *selinux_class = "keystore_key";
369 const char *str_perm = get_perm_label(perm);
370
371 if (!str_perm) {
372 return false;
373 }
374
375 if (getpidcon(spid, &sctx) != 0) {
376 ALOGE("SELinux: Failed to get source pid context.\n");
377 return false;
378 }
379
380 bool allowed = selinux_check_access(sctx, tctx, selinux_class, str_perm,
381 NULL) == 0;
382 freecon(sctx);
383 return allowed;
384}
385
386static bool has_permission(uid_t uid, perm_t perm, pid_t spid) {
Kenny Root655b9582013-04-04 08:37:42 -0700387 // All system users are equivalent for multi-user support.
388 if (get_app_id(uid) == AID_SYSTEM) {
389 uid = AID_SYSTEM;
390 }
391
Kenny Root07438c82012-11-02 15:41:02 -0700392 for (size_t i = 0; i < sizeof(user_perms)/sizeof(user_perms[0]); i++) {
393 struct user_perm user = user_perms[i];
394 if (user.uid == uid) {
Riley Spahneaabae92014-06-30 12:39:52 -0700395 return (user.perms & perm) &&
396 keystore_selinux_check_access(uid, perm, spid);
Kenny Root07438c82012-11-02 15:41:02 -0700397 }
398 }
399
Riley Spahneaabae92014-06-30 12:39:52 -0700400 return (DEFAULT_PERMS & perm) &&
401 keystore_selinux_check_access(uid, perm, spid);
Kenny Root07438c82012-11-02 15:41:02 -0700402}
403
Kenny Root49468902013-03-19 13:41:33 -0700404/**
405 * Returns the UID that the callingUid should act as. This is here for
406 * legacy support of the WiFi and VPN systems and should be removed
407 * when WiFi can operate in its own namespace.
408 */
Kenny Root07438c82012-11-02 15:41:02 -0700409static uid_t get_keystore_euid(uid_t uid) {
410 for (size_t i = 0; i < sizeof(user_euids)/sizeof(user_euids[0]); i++) {
411 struct user_euid user = user_euids[i];
412 if (user.uid == uid) {
413 return user.euid;
414 }
415 }
416
417 return uid;
418}
419
Kenny Root49468902013-03-19 13:41:33 -0700420/**
421 * Returns true if the callingUid is allowed to interact in the targetUid's
422 * namespace.
423 */
424static bool is_granted_to(uid_t callingUid, uid_t targetUid) {
Chad Brubaker9489b792015-04-14 11:01:45 -0700425 if (callingUid == targetUid) {
426 return true;
427 }
Kenny Root49468902013-03-19 13:41:33 -0700428 for (size_t i = 0; i < sizeof(user_euids)/sizeof(user_euids[0]); i++) {
429 struct user_euid user = user_euids[i];
430 if (user.euid == callingUid && user.uid == targetUid) {
431 return true;
432 }
433 }
434
435 return false;
436}
437
Kenny Roota91203b2012-02-15 15:00:46 -0800438/* Here is the encoding of keys. This is necessary in order to allow arbitrary
439 * characters in keys. Characters in [0-~] are not encoded. Others are encoded
440 * into two bytes. The first byte is one of [+-.] which represents the first
441 * two bits of the character. The second byte encodes the rest of the bits into
442 * [0-o]. Therefore in the worst case the length of a key gets doubled. Note
443 * that Base64 cannot be used here due to the need of prefix match on keys. */
444
Kenny Root655b9582013-04-04 08:37:42 -0700445static size_t encode_key_length(const android::String8& keyName) {
446 const uint8_t* in = reinterpret_cast<const uint8_t*>(keyName.string());
447 size_t length = keyName.length();
448 for (int i = length; i > 0; --i, ++in) {
449 if (*in < '0' || *in > '~') {
450 ++length;
451 }
452 }
453 return length;
454}
455
Kenny Root07438c82012-11-02 15:41:02 -0700456static int encode_key(char* out, const android::String8& keyName) {
457 const uint8_t* in = reinterpret_cast<const uint8_t*>(keyName.string());
458 size_t length = keyName.length();
Kenny Roota91203b2012-02-15 15:00:46 -0800459 for (int i = length; i > 0; --i, ++in, ++out) {
Kenny Root655b9582013-04-04 08:37:42 -0700460 if (*in < '0' || *in > '~') {
Kenny Roota91203b2012-02-15 15:00:46 -0800461 *out = '+' + (*in >> 6);
462 *++out = '0' + (*in & 0x3F);
463 ++length;
Kenny Root655b9582013-04-04 08:37:42 -0700464 } else {
465 *out = *in;
Kenny Roota91203b2012-02-15 15:00:46 -0800466 }
467 }
468 *out = '\0';
Kenny Root70e3a862012-02-15 17:20:23 -0800469 return length;
470}
471
Kenny Root07438c82012-11-02 15:41:02 -0700472/*
473 * Converts from the "escaped" format on disk to actual name.
474 * This will be smaller than the input string.
475 *
476 * Characters that should combine with the next at the end will be truncated.
477 */
478static size_t decode_key_length(const char* in, size_t length) {
479 size_t outLength = 0;
480
481 for (const char* end = in + length; in < end; in++) {
482 /* This combines with the next character. */
483 if (*in < '0' || *in > '~') {
484 continue;
485 }
486
487 outLength++;
488 }
489 return outLength;
490}
491
492static void decode_key(char* out, const char* in, size_t length) {
493 for (const char* end = in + length; in < end; in++) {
494 if (*in < '0' || *in > '~') {
495 /* Truncate combining characters at the end. */
496 if (in + 1 >= end) {
497 break;
498 }
499
500 *out = (*in++ - '+') << 6;
501 *out++ |= (*in - '0') & 0x3F;
Kenny Roota91203b2012-02-15 15:00:46 -0800502 } else {
Kenny Root07438c82012-11-02 15:41:02 -0700503 *out++ = *in;
Kenny Roota91203b2012-02-15 15:00:46 -0800504 }
505 }
506 *out = '\0';
Kenny Roota91203b2012-02-15 15:00:46 -0800507}
508
509static size_t readFully(int fd, uint8_t* data, size_t size) {
510 size_t remaining = size;
511 while (remaining > 0) {
Kenny Root150ca932012-11-14 14:29:02 -0800512 ssize_t n = TEMP_FAILURE_RETRY(read(fd, data, remaining));
Kenny Root5281edb2012-11-21 15:14:04 -0800513 if (n <= 0) {
Kenny Root150ca932012-11-14 14:29:02 -0800514 return size - remaining;
Kenny Roota91203b2012-02-15 15:00:46 -0800515 }
516 data += n;
517 remaining -= n;
518 }
519 return size;
520}
521
522static size_t writeFully(int fd, uint8_t* data, size_t size) {
523 size_t remaining = size;
524 while (remaining > 0) {
Kenny Root150ca932012-11-14 14:29:02 -0800525 ssize_t n = TEMP_FAILURE_RETRY(write(fd, data, remaining));
526 if (n < 0) {
527 ALOGW("write failed: %s", strerror(errno));
528 return size - remaining;
Kenny Roota91203b2012-02-15 15:00:46 -0800529 }
530 data += n;
531 remaining -= n;
532 }
533 return size;
534}
535
536class Entropy {
537public:
538 Entropy() : mRandom(-1) {}
539 ~Entropy() {
Kenny Root150ca932012-11-14 14:29:02 -0800540 if (mRandom >= 0) {
Kenny Roota91203b2012-02-15 15:00:46 -0800541 close(mRandom);
542 }
543 }
544
545 bool open() {
546 const char* randomDevice = "/dev/urandom";
Kenny Root150ca932012-11-14 14:29:02 -0800547 mRandom = TEMP_FAILURE_RETRY(::open(randomDevice, O_RDONLY));
548 if (mRandom < 0) {
Kenny Roota91203b2012-02-15 15:00:46 -0800549 ALOGE("open: %s: %s", randomDevice, strerror(errno));
550 return false;
551 }
552 return true;
553 }
554
Kenny Root51878182012-03-13 12:53:19 -0700555 bool generate_random_data(uint8_t* data, size_t size) const {
Kenny Roota91203b2012-02-15 15:00:46 -0800556 return (readFully(mRandom, data, size) == size);
557 }
558
559private:
560 int mRandom;
561};
562
563/* Here is the file format. There are two parts in blob.value, the secret and
564 * the description. The secret is stored in ciphertext, and its original size
565 * can be found in blob.length. The description is stored after the secret in
566 * plaintext, and its size is specified in blob.info. The total size of the two
Kenny Root822c3a92012-03-23 16:34:39 -0700567 * parts must be no more than VALUE_SIZE bytes. The first field is the version,
Kenny Rootf9119d62013-04-03 09:22:15 -0700568 * the second is the blob's type, and the third byte is flags. Fields other
Kenny Roota91203b2012-02-15 15:00:46 -0800569 * than blob.info, blob.length, and blob.value are modified by encryptBlob()
570 * and decryptBlob(). Thus they should not be accessed from outside. */
571
Kenny Root822c3a92012-03-23 16:34:39 -0700572/* ** Note to future implementors of encryption: **
573 * Currently this is the construction:
574 * metadata || Enc(MD5(data) || data)
575 *
576 * This should be the construction used for encrypting if re-implementing:
577 *
578 * Derive independent keys for encryption and MAC:
579 * Kenc = AES_encrypt(masterKey, "Encrypt")
580 * Kmac = AES_encrypt(masterKey, "MAC")
581 *
582 * Store this:
583 * metadata || AES_CTR_encrypt(Kenc, rand_IV, data) ||
584 * HMAC(Kmac, metadata || Enc(data))
585 */
Kenny Roota91203b2012-02-15 15:00:46 -0800586struct __attribute__((packed)) blob {
Kenny Root822c3a92012-03-23 16:34:39 -0700587 uint8_t version;
588 uint8_t type;
Kenny Rootf9119d62013-04-03 09:22:15 -0700589 uint8_t flags;
Kenny Roota91203b2012-02-15 15:00:46 -0800590 uint8_t info;
591 uint8_t vector[AES_BLOCK_SIZE];
Kenny Root822c3a92012-03-23 16:34:39 -0700592 uint8_t encrypted[0]; // Marks offset to encrypted data.
Kenny Roota91203b2012-02-15 15:00:46 -0800593 uint8_t digest[MD5_DIGEST_LENGTH];
Kenny Root822c3a92012-03-23 16:34:39 -0700594 uint8_t digested[0]; // Marks offset to digested data.
Kenny Roota91203b2012-02-15 15:00:46 -0800595 int32_t length; // in network byte order when encrypted
596 uint8_t value[VALUE_SIZE + AES_BLOCK_SIZE];
597};
598
Kenny Root822c3a92012-03-23 16:34:39 -0700599typedef enum {
Kenny Rootd53bc922013-03-21 14:10:15 -0700600 TYPE_ANY = 0, // meta type that matches anything
Kenny Root822c3a92012-03-23 16:34:39 -0700601 TYPE_GENERIC = 1,
602 TYPE_MASTER_KEY = 2,
603 TYPE_KEY_PAIR = 3,
Chad Brubaker17d68b92015-02-05 22:04:16 -0800604 TYPE_KEYMASTER_10 = 4,
Kenny Root822c3a92012-03-23 16:34:39 -0700605} BlobType;
606
Kenny Rootf9119d62013-04-03 09:22:15 -0700607static const uint8_t CURRENT_BLOB_VERSION = 2;
Kenny Root822c3a92012-03-23 16:34:39 -0700608
Kenny Roota91203b2012-02-15 15:00:46 -0800609class Blob {
610public:
Chad Brubaker803f37f2015-07-29 13:53:36 -0700611 Blob(const uint8_t* value, size_t valueLength, const uint8_t* info, uint8_t infoLength,
Kenny Root07438c82012-11-02 15:41:02 -0700612 BlobType type) {
Alex Klyubin1773b442015-02-20 12:33:33 -0800613 memset(&mBlob, 0, sizeof(mBlob));
Chad Brubaker54b1e9a2015-08-12 13:40:31 -0700614 if (valueLength > VALUE_SIZE) {
615 valueLength = VALUE_SIZE;
Chad Brubaker803f37f2015-07-29 13:53:36 -0700616 ALOGW("Provided blob length too large");
617 }
Chad Brubaker54b1e9a2015-08-12 13:40:31 -0700618 if (infoLength + valueLength > VALUE_SIZE) {
619 infoLength = VALUE_SIZE - valueLength;
Chad Brubaker803f37f2015-07-29 13:53:36 -0700620 ALOGW("Provided info length too large");
621 }
Kenny Roota91203b2012-02-15 15:00:46 -0800622 mBlob.length = valueLength;
623 memcpy(mBlob.value, value, valueLength);
624
625 mBlob.info = infoLength;
626 memcpy(mBlob.value + valueLength, info, infoLength);
Kenny Root822c3a92012-03-23 16:34:39 -0700627
Kenny Root07438c82012-11-02 15:41:02 -0700628 mBlob.version = CURRENT_BLOB_VERSION;
Kenny Root822c3a92012-03-23 16:34:39 -0700629 mBlob.type = uint8_t(type);
Kenny Rootf9119d62013-04-03 09:22:15 -0700630
Kenny Rootee8068b2013-10-07 09:49:15 -0700631 if (type == TYPE_MASTER_KEY) {
632 mBlob.flags = KEYSTORE_FLAG_ENCRYPTED;
633 } else {
634 mBlob.flags = KEYSTORE_FLAG_NONE;
635 }
Kenny Roota91203b2012-02-15 15:00:46 -0800636 }
637
638 Blob(blob b) {
639 mBlob = b;
640 }
641
Alex Klyubin1773b442015-02-20 12:33:33 -0800642 Blob() {
643 memset(&mBlob, 0, sizeof(mBlob));
644 }
Kenny Roota91203b2012-02-15 15:00:46 -0800645
Kenny Root51878182012-03-13 12:53:19 -0700646 const uint8_t* getValue() const {
Kenny Roota91203b2012-02-15 15:00:46 -0800647 return mBlob.value;
648 }
649
Kenny Root51878182012-03-13 12:53:19 -0700650 int32_t getLength() const {
Kenny Roota91203b2012-02-15 15:00:46 -0800651 return mBlob.length;
652 }
653
Kenny Root51878182012-03-13 12:53:19 -0700654 const uint8_t* getInfo() const {
655 return mBlob.value + mBlob.length;
656 }
657
658 uint8_t getInfoLength() const {
Kenny Roota91203b2012-02-15 15:00:46 -0800659 return mBlob.info;
660 }
661
Kenny Root822c3a92012-03-23 16:34:39 -0700662 uint8_t getVersion() const {
663 return mBlob.version;
664 }
665
Kenny Rootf9119d62013-04-03 09:22:15 -0700666 bool isEncrypted() const {
667 if (mBlob.version < 2) {
668 return true;
669 }
670
671 return mBlob.flags & KEYSTORE_FLAG_ENCRYPTED;
672 }
673
674 void setEncrypted(bool encrypted) {
675 if (encrypted) {
676 mBlob.flags |= KEYSTORE_FLAG_ENCRYPTED;
677 } else {
678 mBlob.flags &= ~KEYSTORE_FLAG_ENCRYPTED;
679 }
680 }
681
Kenny Root17208e02013-09-04 13:56:03 -0700682 bool isFallback() const {
683 return mBlob.flags & KEYSTORE_FLAG_FALLBACK;
684 }
685
686 void setFallback(bool fallback) {
687 if (fallback) {
688 mBlob.flags |= KEYSTORE_FLAG_FALLBACK;
689 } else {
690 mBlob.flags &= ~KEYSTORE_FLAG_FALLBACK;
691 }
692 }
693
Kenny Root822c3a92012-03-23 16:34:39 -0700694 void setVersion(uint8_t version) {
695 mBlob.version = version;
696 }
697
698 BlobType getType() const {
699 return BlobType(mBlob.type);
700 }
701
702 void setType(BlobType type) {
703 mBlob.type = uint8_t(type);
704 }
705
Kenny Rootf9119d62013-04-03 09:22:15 -0700706 ResponseCode writeBlob(const char* filename, AES_KEY *aes_key, State state, Entropy* entropy) {
707 ALOGV("writing blob %s", filename);
708 if (isEncrypted()) {
709 if (state != STATE_NO_ERROR) {
710 ALOGD("couldn't insert encrypted blob while not unlocked");
711 return LOCKED;
712 }
713
714 if (!entropy->generate_random_data(mBlob.vector, AES_BLOCK_SIZE)) {
715 ALOGW("Could not read random data for: %s", filename);
716 return SYSTEM_ERROR;
717 }
Kenny Roota91203b2012-02-15 15:00:46 -0800718 }
719
720 // data includes the value and the value's length
721 size_t dataLength = mBlob.length + sizeof(mBlob.length);
722 // pad data to the AES_BLOCK_SIZE
723 size_t digestedLength = ((dataLength + AES_BLOCK_SIZE - 1)
724 / AES_BLOCK_SIZE * AES_BLOCK_SIZE);
725 // encrypted data includes the digest value
726 size_t encryptedLength = digestedLength + MD5_DIGEST_LENGTH;
727 // move info after space for padding
728 memmove(&mBlob.encrypted[encryptedLength], &mBlob.value[mBlob.length], mBlob.info);
729 // zero padding area
730 memset(mBlob.value + mBlob.length, 0, digestedLength - dataLength);
731
732 mBlob.length = htonl(mBlob.length);
Kenny Roota91203b2012-02-15 15:00:46 -0800733
Kenny Rootf9119d62013-04-03 09:22:15 -0700734 if (isEncrypted()) {
735 MD5(mBlob.digested, digestedLength, mBlob.digest);
Kenny Roota91203b2012-02-15 15:00:46 -0800736
Kenny Rootf9119d62013-04-03 09:22:15 -0700737 uint8_t vector[AES_BLOCK_SIZE];
738 memcpy(vector, mBlob.vector, AES_BLOCK_SIZE);
739 AES_cbc_encrypt(mBlob.encrypted, mBlob.encrypted, encryptedLength,
740 aes_key, vector, AES_ENCRYPT);
741 }
742
Kenny Roota91203b2012-02-15 15:00:46 -0800743 size_t headerLength = (mBlob.encrypted - (uint8_t*) &mBlob);
744 size_t fileLength = encryptedLength + headerLength + mBlob.info;
745
746 const char* tmpFileName = ".tmp";
Kenny Root150ca932012-11-14 14:29:02 -0800747 int out = TEMP_FAILURE_RETRY(open(tmpFileName,
748 O_WRONLY | O_TRUNC | O_CREAT, S_IRUSR | S_IWUSR));
749 if (out < 0) {
750 ALOGW("could not open file: %s: %s", tmpFileName, strerror(errno));
Kenny Roota91203b2012-02-15 15:00:46 -0800751 return SYSTEM_ERROR;
752 }
753 size_t writtenBytes = writeFully(out, (uint8_t*) &mBlob, fileLength);
754 if (close(out) != 0) {
755 return SYSTEM_ERROR;
756 }
757 if (writtenBytes != fileLength) {
Kenny Root150ca932012-11-14 14:29:02 -0800758 ALOGW("blob not fully written %zu != %zu", writtenBytes, fileLength);
Kenny Roota91203b2012-02-15 15:00:46 -0800759 unlink(tmpFileName);
760 return SYSTEM_ERROR;
761 }
Kenny Root150ca932012-11-14 14:29:02 -0800762 if (rename(tmpFileName, filename) == -1) {
763 ALOGW("could not rename blob to %s: %s", filename, strerror(errno));
764 return SYSTEM_ERROR;
765 }
766 return NO_ERROR;
Kenny Roota91203b2012-02-15 15:00:46 -0800767 }
768
Kenny Rootf9119d62013-04-03 09:22:15 -0700769 ResponseCode readBlob(const char* filename, AES_KEY *aes_key, State state) {
770 ALOGV("reading blob %s", filename);
Kenny Root150ca932012-11-14 14:29:02 -0800771 int in = TEMP_FAILURE_RETRY(open(filename, O_RDONLY));
772 if (in < 0) {
Kenny Roota91203b2012-02-15 15:00:46 -0800773 return (errno == ENOENT) ? KEY_NOT_FOUND : SYSTEM_ERROR;
774 }
775 // fileLength may be less than sizeof(mBlob) since the in
776 // memory version has extra padding to tolerate rounding up to
777 // the AES_BLOCK_SIZE
778 size_t fileLength = readFully(in, (uint8_t*) &mBlob, sizeof(mBlob));
779 if (close(in) != 0) {
780 return SYSTEM_ERROR;
781 }
Kenny Rootf9119d62013-04-03 09:22:15 -0700782
Chad Brubakera9a17ee2015-07-17 13:43:24 -0700783 if (fileLength == 0) {
784 return VALUE_CORRUPTED;
785 }
786
Kenny Rootf9119d62013-04-03 09:22:15 -0700787 if (isEncrypted() && (state != STATE_NO_ERROR)) {
788 return LOCKED;
789 }
790
Kenny Roota91203b2012-02-15 15:00:46 -0800791 size_t headerLength = (mBlob.encrypted - (uint8_t*) &mBlob);
792 if (fileLength < headerLength) {
793 return VALUE_CORRUPTED;
794 }
795
796 ssize_t encryptedLength = fileLength - (headerLength + mBlob.info);
Kenny Rootf9119d62013-04-03 09:22:15 -0700797 if (encryptedLength < 0) {
Kenny Roota91203b2012-02-15 15:00:46 -0800798 return VALUE_CORRUPTED;
799 }
Kenny Rootf9119d62013-04-03 09:22:15 -0700800
801 ssize_t digestedLength;
802 if (isEncrypted()) {
803 if (encryptedLength % AES_BLOCK_SIZE != 0) {
804 return VALUE_CORRUPTED;
805 }
806
807 AES_cbc_encrypt(mBlob.encrypted, mBlob.encrypted, encryptedLength, aes_key,
808 mBlob.vector, AES_DECRYPT);
809 digestedLength = encryptedLength - MD5_DIGEST_LENGTH;
810 uint8_t computedDigest[MD5_DIGEST_LENGTH];
811 MD5(mBlob.digested, digestedLength, computedDigest);
812 if (memcmp(mBlob.digest, computedDigest, MD5_DIGEST_LENGTH) != 0) {
813 return VALUE_CORRUPTED;
814 }
815 } else {
816 digestedLength = encryptedLength;
Kenny Roota91203b2012-02-15 15:00:46 -0800817 }
818
819 ssize_t maxValueLength = digestedLength - sizeof(mBlob.length);
820 mBlob.length = ntohl(mBlob.length);
821 if (mBlob.length < 0 || mBlob.length > maxValueLength) {
822 return VALUE_CORRUPTED;
823 }
824 if (mBlob.info != 0) {
825 // move info from after padding to after data
826 memmove(&mBlob.value[mBlob.length], &mBlob.value[maxValueLength], mBlob.info);
827 }
Kenny Root07438c82012-11-02 15:41:02 -0700828 return ::NO_ERROR;
Kenny Roota91203b2012-02-15 15:00:46 -0800829 }
830
831private:
832 struct blob mBlob;
833};
834
Kenny Root655b9582013-04-04 08:37:42 -0700835class UserState {
Kenny Roota91203b2012-02-15 15:00:46 -0800836public:
Kenny Root655b9582013-04-04 08:37:42 -0700837 UserState(uid_t userId) : mUserId(userId), mRetry(MAX_RETRY) {
838 asprintf(&mUserDir, "user_%u", mUserId);
839 asprintf(&mMasterKeyFile, "%s/.masterkey", mUserDir);
840 }
841
842 ~UserState() {
843 free(mUserDir);
844 free(mMasterKeyFile);
845 }
846
847 bool initialize() {
848 if ((mkdir(mUserDir, S_IRUSR | S_IWUSR | S_IXUSR) < 0) && (errno != EEXIST)) {
849 ALOGE("Could not create directory '%s'", mUserDir);
850 return false;
851 }
852
853 if (access(mMasterKeyFile, R_OK) == 0) {
Kenny Roota91203b2012-02-15 15:00:46 -0800854 setState(STATE_LOCKED);
855 } else {
856 setState(STATE_UNINITIALIZED);
857 }
Kenny Root70e3a862012-02-15 17:20:23 -0800858
Kenny Root655b9582013-04-04 08:37:42 -0700859 return true;
860 }
861
862 uid_t getUserId() const {
863 return mUserId;
864 }
865
866 const char* getUserDirName() const {
867 return mUserDir;
868 }
869
870 const char* getMasterKeyFileName() const {
871 return mMasterKeyFile;
872 }
873
874 void setState(State state) {
875 mState = state;
876 if (mState == STATE_NO_ERROR || mState == STATE_UNINITIALIZED) {
877 mRetry = MAX_RETRY;
878 }
Kenny Roota91203b2012-02-15 15:00:46 -0800879 }
880
Kenny Root51878182012-03-13 12:53:19 -0700881 State getState() const {
Kenny Roota91203b2012-02-15 15:00:46 -0800882 return mState;
883 }
884
Kenny Root51878182012-03-13 12:53:19 -0700885 int8_t getRetry() const {
Kenny Roota91203b2012-02-15 15:00:46 -0800886 return mRetry;
887 }
888
Kenny Root655b9582013-04-04 08:37:42 -0700889 void zeroizeMasterKeysInMemory() {
890 memset(mMasterKey, 0, sizeof(mMasterKey));
891 memset(mSalt, 0, sizeof(mSalt));
892 memset(&mMasterKeyEncryption, 0, sizeof(mMasterKeyEncryption));
893 memset(&mMasterKeyDecryption, 0, sizeof(mMasterKeyDecryption));
Kenny Root70e3a862012-02-15 17:20:23 -0800894 }
895
Chad Brubaker96d6d782015-05-07 10:19:40 -0700896 bool deleteMasterKey() {
897 setState(STATE_UNINITIALIZED);
898 zeroizeMasterKeysInMemory();
899 return unlink(mMasterKeyFile) == 0 || errno == ENOENT;
900 }
901
Kenny Root655b9582013-04-04 08:37:42 -0700902 ResponseCode initialize(const android::String8& pw, Entropy* entropy) {
903 if (!generateMasterKey(entropy)) {
Kenny Roota91203b2012-02-15 15:00:46 -0800904 return SYSTEM_ERROR;
905 }
Kenny Root655b9582013-04-04 08:37:42 -0700906 ResponseCode response = writeMasterKey(pw, entropy);
Kenny Roota91203b2012-02-15 15:00:46 -0800907 if (response != NO_ERROR) {
908 return response;
909 }
910 setupMasterKeys();
Kenny Root07438c82012-11-02 15:41:02 -0700911 return ::NO_ERROR;
Kenny Roota91203b2012-02-15 15:00:46 -0800912 }
913
Robin Lee4e865752014-08-19 17:37:55 +0100914 ResponseCode copyMasterKey(UserState* src) {
915 if (mState != STATE_UNINITIALIZED) {
916 return ::SYSTEM_ERROR;
917 }
918 if (src->getState() != STATE_NO_ERROR) {
919 return ::SYSTEM_ERROR;
920 }
921 memcpy(mMasterKey, src->mMasterKey, MASTER_KEY_SIZE_BYTES);
922 setupMasterKeys();
Chad Brubaker410ba592015-09-09 20:34:09 -0700923 return copyMasterKeyFile(src);
924 }
925
926 ResponseCode copyMasterKeyFile(UserState* src) {
927 /* Copy the master key file to the new user.
928 * Unfortunately we don't have the src user's password so we cannot
929 * generate a new file with a new salt.
930 */
931 int in = TEMP_FAILURE_RETRY(open(src->getMasterKeyFileName(), O_RDONLY));
932 if (in < 0) {
933 return ::SYSTEM_ERROR;
934 }
935 blob rawBlob;
936 size_t length = readFully(in, (uint8_t*) &rawBlob, sizeof(rawBlob));
937 if (close(in) != 0) {
938 return ::SYSTEM_ERROR;
939 }
940 int out = TEMP_FAILURE_RETRY(open(mMasterKeyFile,
941 O_WRONLY | O_TRUNC | O_CREAT, S_IRUSR | S_IWUSR));
942 if (out < 0) {
943 return ::SYSTEM_ERROR;
944 }
945 size_t outLength = writeFully(out, (uint8_t*) &rawBlob, length);
946 if (close(out) != 0) {
947 return ::SYSTEM_ERROR;
948 }
949 if (outLength != length) {
950 ALOGW("blob not fully written %zu != %zu", outLength, length);
951 unlink(mMasterKeyFile);
952 return ::SYSTEM_ERROR;
953 }
954
Robin Lee4e865752014-08-19 17:37:55 +0100955 return ::NO_ERROR;
956 }
957
Kenny Root655b9582013-04-04 08:37:42 -0700958 ResponseCode writeMasterKey(const android::String8& pw, Entropy* entropy) {
Kenny Roota91203b2012-02-15 15:00:46 -0800959 uint8_t passwordKey[MASTER_KEY_SIZE_BYTES];
960 generateKeyFromPassword(passwordKey, MASTER_KEY_SIZE_BYTES, pw, mSalt);
961 AES_KEY passwordAesKey;
962 AES_set_encrypt_key(passwordKey, MASTER_KEY_SIZE_BITS, &passwordAesKey);
Kenny Root822c3a92012-03-23 16:34:39 -0700963 Blob masterKeyBlob(mMasterKey, sizeof(mMasterKey), mSalt, sizeof(mSalt), TYPE_MASTER_KEY);
Kenny Rootf9119d62013-04-03 09:22:15 -0700964 return masterKeyBlob.writeBlob(mMasterKeyFile, &passwordAesKey, STATE_NO_ERROR, entropy);
Kenny Roota91203b2012-02-15 15:00:46 -0800965 }
966
Kenny Root655b9582013-04-04 08:37:42 -0700967 ResponseCode readMasterKey(const android::String8& pw, Entropy* entropy) {
968 int in = TEMP_FAILURE_RETRY(open(mMasterKeyFile, O_RDONLY));
Kenny Root150ca932012-11-14 14:29:02 -0800969 if (in < 0) {
Kenny Roota91203b2012-02-15 15:00:46 -0800970 return SYSTEM_ERROR;
971 }
972
973 // we read the raw blob to just to get the salt to generate
974 // the AES key, then we create the Blob to use with decryptBlob
975 blob rawBlob;
976 size_t length = readFully(in, (uint8_t*) &rawBlob, sizeof(rawBlob));
977 if (close(in) != 0) {
978 return SYSTEM_ERROR;
979 }
980 // find salt at EOF if present, otherwise we have an old file
981 uint8_t* salt;
982 if (length > SALT_SIZE && rawBlob.info == SALT_SIZE) {
983 salt = (uint8_t*) &rawBlob + length - SALT_SIZE;
984 } else {
985 salt = NULL;
986 }
987 uint8_t passwordKey[MASTER_KEY_SIZE_BYTES];
988 generateKeyFromPassword(passwordKey, MASTER_KEY_SIZE_BYTES, pw, salt);
989 AES_KEY passwordAesKey;
990 AES_set_decrypt_key(passwordKey, MASTER_KEY_SIZE_BITS, &passwordAesKey);
991 Blob masterKeyBlob(rawBlob);
Kenny Rootf9119d62013-04-03 09:22:15 -0700992 ResponseCode response = masterKeyBlob.readBlob(mMasterKeyFile, &passwordAesKey,
993 STATE_NO_ERROR);
Kenny Roota91203b2012-02-15 15:00:46 -0800994 if (response == SYSTEM_ERROR) {
Kenny Rootf9119d62013-04-03 09:22:15 -0700995 return response;
Kenny Roota91203b2012-02-15 15:00:46 -0800996 }
997 if (response == NO_ERROR && masterKeyBlob.getLength() == MASTER_KEY_SIZE_BYTES) {
998 // if salt was missing, generate one and write a new master key file with the salt.
999 if (salt == NULL) {
Kenny Root655b9582013-04-04 08:37:42 -07001000 if (!generateSalt(entropy)) {
Kenny Roota91203b2012-02-15 15:00:46 -08001001 return SYSTEM_ERROR;
1002 }
Kenny Root655b9582013-04-04 08:37:42 -07001003 response = writeMasterKey(pw, entropy);
Kenny Roota91203b2012-02-15 15:00:46 -08001004 }
1005 if (response == NO_ERROR) {
1006 memcpy(mMasterKey, masterKeyBlob.getValue(), MASTER_KEY_SIZE_BYTES);
1007 setupMasterKeys();
1008 }
1009 return response;
1010 }
1011 if (mRetry <= 0) {
1012 reset();
1013 return UNINITIALIZED;
1014 }
1015 --mRetry;
1016 switch (mRetry) {
1017 case 0: return WRONG_PASSWORD_0;
1018 case 1: return WRONG_PASSWORD_1;
1019 case 2: return WRONG_PASSWORD_2;
1020 case 3: return WRONG_PASSWORD_3;
1021 default: return WRONG_PASSWORD_3;
1022 }
1023 }
1024
Kenny Root655b9582013-04-04 08:37:42 -07001025 AES_KEY* getEncryptionKey() {
1026 return &mMasterKeyEncryption;
1027 }
1028
1029 AES_KEY* getDecryptionKey() {
1030 return &mMasterKeyDecryption;
1031 }
1032
Kenny Roota91203b2012-02-15 15:00:46 -08001033 bool reset() {
Kenny Root655b9582013-04-04 08:37:42 -07001034 DIR* dir = opendir(getUserDirName());
Kenny Roota91203b2012-02-15 15:00:46 -08001035 if (!dir) {
Chad Brubaker96d6d782015-05-07 10:19:40 -07001036 // If the directory doesn't exist then nothing to do.
1037 if (errno == ENOENT) {
1038 return true;
1039 }
Kenny Root655b9582013-04-04 08:37:42 -07001040 ALOGW("couldn't open user directory: %s", strerror(errno));
Kenny Roota91203b2012-02-15 15:00:46 -08001041 return false;
1042 }
Kenny Root655b9582013-04-04 08:37:42 -07001043
1044 struct dirent* file;
Kenny Roota91203b2012-02-15 15:00:46 -08001045 while ((file = readdir(dir)) != NULL) {
Chad Brubaker96d6d782015-05-07 10:19:40 -07001046 // skip . and ..
1047 if (!strcmp(".", file->d_name) || !strcmp("..", file->d_name)) {
Kenny Root655b9582013-04-04 08:37:42 -07001048 continue;
1049 }
1050
1051 unlinkat(dirfd(dir), file->d_name, 0);
Kenny Roota91203b2012-02-15 15:00:46 -08001052 }
1053 closedir(dir);
1054 return true;
1055 }
1056
Kenny Root655b9582013-04-04 08:37:42 -07001057private:
1058 static const int MASTER_KEY_SIZE_BYTES = 16;
1059 static const int MASTER_KEY_SIZE_BITS = MASTER_KEY_SIZE_BYTES * 8;
1060
1061 static const int MAX_RETRY = 4;
1062 static const size_t SALT_SIZE = 16;
1063
1064 void generateKeyFromPassword(uint8_t* key, ssize_t keySize, const android::String8& pw,
1065 uint8_t* salt) {
1066 size_t saltSize;
1067 if (salt != NULL) {
1068 saltSize = SALT_SIZE;
1069 } else {
1070 // pre-gingerbread used this hardwired salt, readMasterKey will rewrite these when found
1071 salt = (uint8_t*) "keystore";
1072 // sizeof = 9, not strlen = 8
1073 saltSize = sizeof("keystore");
1074 }
1075
1076 PKCS5_PBKDF2_HMAC_SHA1(reinterpret_cast<const char*>(pw.string()), pw.length(), salt,
1077 saltSize, 8192, keySize, key);
1078 }
1079
1080 bool generateSalt(Entropy* entropy) {
1081 return entropy->generate_random_data(mSalt, sizeof(mSalt));
1082 }
1083
1084 bool generateMasterKey(Entropy* entropy) {
1085 if (!entropy->generate_random_data(mMasterKey, sizeof(mMasterKey))) {
1086 return false;
1087 }
1088 if (!generateSalt(entropy)) {
1089 return false;
1090 }
1091 return true;
1092 }
1093
1094 void setupMasterKeys() {
1095 AES_set_encrypt_key(mMasterKey, MASTER_KEY_SIZE_BITS, &mMasterKeyEncryption);
1096 AES_set_decrypt_key(mMasterKey, MASTER_KEY_SIZE_BITS, &mMasterKeyDecryption);
1097 setState(STATE_NO_ERROR);
1098 }
1099
1100 uid_t mUserId;
1101
1102 char* mUserDir;
1103 char* mMasterKeyFile;
1104
1105 State mState;
1106 int8_t mRetry;
1107
1108 uint8_t mMasterKey[MASTER_KEY_SIZE_BYTES];
1109 uint8_t mSalt[SALT_SIZE];
1110
1111 AES_KEY mMasterKeyEncryption;
1112 AES_KEY mMasterKeyDecryption;
1113};
1114
1115typedef struct {
1116 uint32_t uid;
1117 const uint8_t* filename;
1118} grant_t;
1119
1120class KeyStore {
1121public:
Chad Brubaker67d2a502015-03-11 17:21:18 +00001122 KeyStore(Entropy* entropy, keymaster1_device_t* device, keymaster1_device_t* fallback)
Kenny Root655b9582013-04-04 08:37:42 -07001123 : mEntropy(entropy)
1124 , mDevice(device)
Chad Brubakerfc18edc2015-01-12 15:17:18 -08001125 , mFallbackDevice(fallback)
Kenny Root655b9582013-04-04 08:37:42 -07001126 {
1127 memset(&mMetaData, '\0', sizeof(mMetaData));
1128 }
1129
1130 ~KeyStore() {
1131 for (android::Vector<grant_t*>::iterator it(mGrants.begin());
1132 it != mGrants.end(); it++) {
1133 delete *it;
Kenny Root655b9582013-04-04 08:37:42 -07001134 }
haitao fangc35d4eb2013-12-06 11:34:49 +08001135 mGrants.clear();
Kenny Root655b9582013-04-04 08:37:42 -07001136
1137 for (android::Vector<UserState*>::iterator it(mMasterKeys.begin());
1138 it != mMasterKeys.end(); it++) {
1139 delete *it;
Kenny Root655b9582013-04-04 08:37:42 -07001140 }
haitao fangc35d4eb2013-12-06 11:34:49 +08001141 mMasterKeys.clear();
Kenny Root655b9582013-04-04 08:37:42 -07001142 }
1143
Chad Brubaker67d2a502015-03-11 17:21:18 +00001144 /**
1145 * Depending on the hardware keymaster version is this may return a
1146 * keymaster0_device_t* cast to a keymaster1_device_t*. All methods from
1147 * keymaster0 are safe to call, calls to keymaster1_device_t methods should
1148 * be guarded by a check on the device's version.
1149 */
1150 keymaster1_device_t *getDevice() const {
Kenny Root655b9582013-04-04 08:37:42 -07001151 return mDevice;
1152 }
1153
Chad Brubaker67d2a502015-03-11 17:21:18 +00001154 keymaster1_device_t *getFallbackDevice() const {
Chad Brubakerfc18edc2015-01-12 15:17:18 -08001155 return mFallbackDevice;
1156 }
1157
Chad Brubaker67d2a502015-03-11 17:21:18 +00001158 keymaster1_device_t *getDeviceForBlob(const Blob& blob) const {
Chad Brubakerfc18edc2015-01-12 15:17:18 -08001159 return blob.isFallback() ? mFallbackDevice: mDevice;
1160 }
1161
Kenny Root655b9582013-04-04 08:37:42 -07001162 ResponseCode initialize() {
1163 readMetaData();
1164 if (upgradeKeystore()) {
1165 writeMetaData();
1166 }
1167
1168 return ::NO_ERROR;
1169 }
1170
Chad Brubaker72593ee2015-05-12 10:42:00 -07001171 State getState(uid_t userId) {
1172 return getUserState(userId)->getState();
Kenny Root655b9582013-04-04 08:37:42 -07001173 }
1174
Chad Brubaker72593ee2015-05-12 10:42:00 -07001175 ResponseCode initializeUser(const android::String8& pw, uid_t userId) {
1176 UserState* userState = getUserState(userId);
Kenny Root655b9582013-04-04 08:37:42 -07001177 return userState->initialize(pw, mEntropy);
1178 }
1179
Chad Brubaker72593ee2015-05-12 10:42:00 -07001180 ResponseCode copyMasterKey(uid_t srcUser, uid_t dstUser) {
1181 UserState *userState = getUserState(dstUser);
1182 UserState *initState = getUserState(srcUser);
Robin Lee4e865752014-08-19 17:37:55 +01001183 return userState->copyMasterKey(initState);
1184 }
1185
Chad Brubaker72593ee2015-05-12 10:42:00 -07001186 ResponseCode writeMasterKey(const android::String8& pw, uid_t userId) {
1187 UserState* userState = getUserState(userId);
Kenny Root655b9582013-04-04 08:37:42 -07001188 return userState->writeMasterKey(pw, mEntropy);
1189 }
1190
Chad Brubaker72593ee2015-05-12 10:42:00 -07001191 ResponseCode readMasterKey(const android::String8& pw, uid_t userId) {
1192 UserState* userState = getUserState(userId);
Kenny Root655b9582013-04-04 08:37:42 -07001193 return userState->readMasterKey(pw, mEntropy);
1194 }
1195
1196 android::String8 getKeyName(const android::String8& keyName) {
Douglas Leunga77e8092013-06-13 16:34:43 -07001197 char encoded[encode_key_length(keyName) + 1]; // add 1 for null char
Kenny Root655b9582013-04-04 08:37:42 -07001198 encode_key(encoded, keyName);
1199 return android::String8(encoded);
1200 }
1201
1202 android::String8 getKeyNameForUid(const android::String8& keyName, uid_t uid) {
Douglas Leunga77e8092013-06-13 16:34:43 -07001203 char encoded[encode_key_length(keyName) + 1]; // add 1 for null char
Kenny Root655b9582013-04-04 08:37:42 -07001204 encode_key(encoded, keyName);
1205 return android::String8::format("%u_%s", uid, encoded);
1206 }
1207
1208 android::String8 getKeyNameForUidWithDir(const android::String8& keyName, uid_t uid) {
Douglas Leunga77e8092013-06-13 16:34:43 -07001209 char encoded[encode_key_length(keyName) + 1]; // add 1 for null char
Kenny Root655b9582013-04-04 08:37:42 -07001210 encode_key(encoded, keyName);
Chad Brubaker72593ee2015-05-12 10:42:00 -07001211 return android::String8::format("%s/%u_%s", getUserStateByUid(uid)->getUserDirName(), uid,
Kenny Root655b9582013-04-04 08:37:42 -07001212 encoded);
1213 }
1214
Chad Brubaker96d6d782015-05-07 10:19:40 -07001215 /*
1216 * Delete entries owned by userId. If keepUnencryptedEntries is true
1217 * then only encrypted entries will be removed, otherwise all entries will
1218 * be removed.
1219 */
1220 void resetUser(uid_t userId, bool keepUnenryptedEntries) {
Robin Lee4b84fdc2014-09-24 11:56:57 +01001221 android::String8 prefix("");
1222 android::Vector<android::String16> aliases;
Chad Brubaker72593ee2015-05-12 10:42:00 -07001223 UserState* userState = getUserState(userId);
Chad Brubakere6c3bfa2015-05-12 15:18:26 -07001224 if (list(prefix, &aliases, userId) != ::NO_ERROR) {
Chad Brubaker96d6d782015-05-07 10:19:40 -07001225 return;
1226 }
Robin Lee4b84fdc2014-09-24 11:56:57 +01001227 for (uint32_t i = 0; i < aliases.size(); i++) {
1228 android::String8 filename(aliases[i]);
1229 filename = android::String8::format("%s/%s", userState->getUserDirName(),
Chad Brubaker96d6d782015-05-07 10:19:40 -07001230 getKeyName(filename).string());
1231 bool shouldDelete = true;
1232 if (keepUnenryptedEntries) {
1233 Blob blob;
Chad Brubaker72593ee2015-05-12 10:42:00 -07001234 ResponseCode rc = get(filename, &blob, ::TYPE_ANY, userId);
Robin Lee4b84fdc2014-09-24 11:56:57 +01001235
Chad Brubaker96d6d782015-05-07 10:19:40 -07001236 /* get can fail if the blob is encrypted and the state is
1237 * not unlocked, only skip deleting blobs that were loaded and
1238 * who are not encrypted. If there are blobs we fail to read for
1239 * other reasons err on the safe side and delete them since we
1240 * can't tell if they're encrypted.
1241 */
1242 shouldDelete = !(rc == ::NO_ERROR && !blob.isEncrypted());
1243 }
1244 if (shouldDelete) {
Chad Brubaker72593ee2015-05-12 10:42:00 -07001245 del(filename, ::TYPE_ANY, userId);
Chad Brubaker96d6d782015-05-07 10:19:40 -07001246 }
1247 }
1248 if (!userState->deleteMasterKey()) {
1249 ALOGE("Failed to delete user %d's master key", userId);
1250 }
1251 if (!keepUnenryptedEntries) {
1252 if(!userState->reset()) {
1253 ALOGE("Failed to remove user %d's directory", userId);
1254 }
1255 }
Kenny Root655b9582013-04-04 08:37:42 -07001256 }
1257
Chad Brubaker72593ee2015-05-12 10:42:00 -07001258 bool isEmpty(uid_t userId) const {
1259 const UserState* userState = getUserState(userId);
Chad Brubaker96d6d782015-05-07 10:19:40 -07001260 if (userState == NULL) {
Kenny Root655b9582013-04-04 08:37:42 -07001261 return true;
1262 }
1263
1264 DIR* dir = opendir(userState->getUserDirName());
Kenny Roota91203b2012-02-15 15:00:46 -08001265 if (!dir) {
1266 return true;
1267 }
Kenny Root31e27462014-09-10 11:28:03 -07001268
Kenny Roota91203b2012-02-15 15:00:46 -08001269 bool result = true;
Kenny Root31e27462014-09-10 11:28:03 -07001270 struct dirent* file;
Kenny Roota91203b2012-02-15 15:00:46 -08001271 while ((file = readdir(dir)) != NULL) {
Kenny Root655b9582013-04-04 08:37:42 -07001272 // We only care about files.
1273 if (file->d_type != DT_REG) {
1274 continue;
1275 }
1276
1277 // Skip anything that starts with a "."
1278 if (file->d_name[0] == '.') {
1279 continue;
1280 }
1281
Kenny Root31e27462014-09-10 11:28:03 -07001282 result = false;
1283 break;
Kenny Roota91203b2012-02-15 15:00:46 -08001284 }
1285 closedir(dir);
1286 return result;
1287 }
1288
Chad Brubaker72593ee2015-05-12 10:42:00 -07001289 void lock(uid_t userId) {
1290 UserState* userState = getUserState(userId);
Kenny Root655b9582013-04-04 08:37:42 -07001291 userState->zeroizeMasterKeysInMemory();
1292 userState->setState(STATE_LOCKED);
Kenny Roota91203b2012-02-15 15:00:46 -08001293 }
1294
Chad Brubaker72593ee2015-05-12 10:42:00 -07001295 ResponseCode get(const char* filename, Blob* keyBlob, const BlobType type, uid_t userId) {
1296 UserState* userState = getUserState(userId);
Kenny Rootf9119d62013-04-03 09:22:15 -07001297 ResponseCode rc = keyBlob->readBlob(filename, userState->getDecryptionKey(),
1298 userState->getState());
Kenny Root822c3a92012-03-23 16:34:39 -07001299 if (rc != NO_ERROR) {
1300 return rc;
1301 }
1302
1303 const uint8_t version = keyBlob->getVersion();
Kenny Root07438c82012-11-02 15:41:02 -07001304 if (version < CURRENT_BLOB_VERSION) {
Kenny Rootcfeae072013-04-04 08:39:57 -07001305 /* If we upgrade the key, we need to write it to disk again. Then
1306 * it must be read it again since the blob is encrypted each time
1307 * it's written.
1308 */
Chad Brubaker72593ee2015-05-12 10:42:00 -07001309 if (upgradeBlob(filename, keyBlob, version, type, userId)) {
1310 if ((rc = this->put(filename, keyBlob, userId)) != NO_ERROR
Kenny Rootf9119d62013-04-03 09:22:15 -07001311 || (rc = keyBlob->readBlob(filename, userState->getDecryptionKey(),
1312 userState->getState())) != NO_ERROR) {
Kenny Rootcfeae072013-04-04 08:39:57 -07001313 return rc;
1314 }
1315 }
Kenny Root822c3a92012-03-23 16:34:39 -07001316 }
1317
Kenny Root17208e02013-09-04 13:56:03 -07001318 /*
1319 * This will upgrade software-backed keys to hardware-backed keys when
1320 * the HAL for the device supports the newer key types.
1321 */
1322 if (rc == NO_ERROR && type == TYPE_KEY_PAIR
1323 && mDevice->common.module->module_api_version >= KEYMASTER_MODULE_API_VERSION_0_2
1324 && keyBlob->isFallback()) {
1325 ResponseCode imported = importKey(keyBlob->getValue(), keyBlob->getLength(), filename,
Chad Brubaker72593ee2015-05-12 10:42:00 -07001326 userId, keyBlob->isEncrypted() ? KEYSTORE_FLAG_ENCRYPTED : KEYSTORE_FLAG_NONE);
Kenny Root17208e02013-09-04 13:56:03 -07001327
1328 // The HAL allowed the import, reget the key to have the "fresh"
1329 // version.
1330 if (imported == NO_ERROR) {
Chad Brubaker72593ee2015-05-12 10:42:00 -07001331 rc = get(filename, keyBlob, TYPE_KEY_PAIR, userId);
Kenny Root17208e02013-09-04 13:56:03 -07001332 }
1333 }
1334
Chad Brubaker3a7d9e62015-06-04 15:01:46 -07001335 // Keymaster 0.3 keys are valid keymaster 1.0 keys, so silently upgrade.
1336 if (keyBlob->getType() == TYPE_KEY_PAIR) {
Chad Brubaker3cc40122015-06-04 13:49:44 -07001337 keyBlob->setType(TYPE_KEYMASTER_10);
Chad Brubaker3a7d9e62015-06-04 15:01:46 -07001338 rc = this->put(filename, keyBlob, userId);
Chad Brubaker3cc40122015-06-04 13:49:44 -07001339 }
1340
Kenny Rootd53bc922013-03-21 14:10:15 -07001341 if (type != TYPE_ANY && keyBlob->getType() != type) {
Kenny Root822c3a92012-03-23 16:34:39 -07001342 ALOGW("key found but type doesn't match: %d vs %d", keyBlob->getType(), type);
1343 return KEY_NOT_FOUND;
1344 }
1345
1346 return rc;
Kenny Roota91203b2012-02-15 15:00:46 -08001347 }
1348
Chad Brubaker72593ee2015-05-12 10:42:00 -07001349 ResponseCode put(const char* filename, Blob* keyBlob, uid_t userId) {
1350 UserState* userState = getUserState(userId);
Kenny Rootf9119d62013-04-03 09:22:15 -07001351 return keyBlob->writeBlob(filename, userState->getEncryptionKey(), userState->getState(),
1352 mEntropy);
Kenny Roota91203b2012-02-15 15:00:46 -08001353 }
1354
Chad Brubaker72593ee2015-05-12 10:42:00 -07001355 ResponseCode del(const char *filename, const BlobType type, uid_t userId) {
Robin Lee4b84fdc2014-09-24 11:56:57 +01001356 Blob keyBlob;
Chad Brubaker72593ee2015-05-12 10:42:00 -07001357 ResponseCode rc = get(filename, &keyBlob, type, userId);
Chad Brubakera9a17ee2015-07-17 13:43:24 -07001358 if (rc == ::VALUE_CORRUPTED) {
1359 // The file is corrupt, the best we can do is rm it.
1360 return (unlink(filename) && errno != ENOENT) ? ::SYSTEM_ERROR : ::NO_ERROR;
1361 }
Robin Lee4b84fdc2014-09-24 11:56:57 +01001362 if (rc != ::NO_ERROR) {
1363 return rc;
1364 }
1365
1366 if (keyBlob.getType() == ::TYPE_KEY_PAIR) {
Shawn Willden55268b52015-07-28 11:06:00 -06001367 // A device doesn't have to implement delete_key.
1368 if (mDevice->delete_key != NULL && !keyBlob.isFallback()) {
1369 keymaster_key_blob_t blob = {keyBlob.getValue(),
1370 static_cast<size_t>(keyBlob.getLength())};
1371 if (mDevice->delete_key(mDevice, &blob)) {
Robin Lee4b84fdc2014-09-24 11:56:57 +01001372 rc = ::SYSTEM_ERROR;
1373 }
1374 }
1375 }
Chad Brubaker17d68b92015-02-05 22:04:16 -08001376 if (keyBlob.getType() == ::TYPE_KEYMASTER_10) {
1377 keymaster1_device_t* dev = getDeviceForBlob(keyBlob);
1378 if (dev->delete_key) {
1379 keymaster_key_blob_t blob;
1380 blob.key_material = keyBlob.getValue();
1381 blob.key_material_size = keyBlob.getLength();
1382 dev->delete_key(dev, &blob);
1383 }
1384 }
Robin Lee4b84fdc2014-09-24 11:56:57 +01001385 if (rc != ::NO_ERROR) {
1386 return rc;
1387 }
1388
1389 return (unlink(filename) && errno != ENOENT) ? ::SYSTEM_ERROR : ::NO_ERROR;
1390 }
1391
Chad Brubakere6c3bfa2015-05-12 15:18:26 -07001392 ResponseCode list(const android::String8& prefix, android::Vector<android::String16> *matches,
Chad Brubaker72593ee2015-05-12 10:42:00 -07001393 uid_t userId) {
Robin Lee4b84fdc2014-09-24 11:56:57 +01001394
Chad Brubaker72593ee2015-05-12 10:42:00 -07001395 UserState* userState = getUserState(userId);
Robin Lee4b84fdc2014-09-24 11:56:57 +01001396 size_t n = prefix.length();
1397
1398 DIR* dir = opendir(userState->getUserDirName());
1399 if (!dir) {
1400 ALOGW("can't open directory for user: %s", strerror(errno));
1401 return ::SYSTEM_ERROR;
1402 }
1403
1404 struct dirent* file;
1405 while ((file = readdir(dir)) != NULL) {
1406 // We only care about files.
1407 if (file->d_type != DT_REG) {
1408 continue;
1409 }
1410
1411 // Skip anything that starts with a "."
1412 if (file->d_name[0] == '.') {
1413 continue;
1414 }
1415
1416 if (!strncmp(prefix.string(), file->d_name, n)) {
1417 const char* p = &file->d_name[n];
1418 size_t plen = strlen(p);
1419
1420 size_t extra = decode_key_length(p, plen);
1421 char *match = (char*) malloc(extra + 1);
1422 if (match != NULL) {
1423 decode_key(match, p, plen);
1424 matches->push(android::String16(match, extra));
1425 free(match);
1426 } else {
1427 ALOGW("could not allocate match of size %zd", extra);
1428 }
1429 }
1430 }
1431 closedir(dir);
1432 return ::NO_ERROR;
1433 }
1434
Kenny Root07438c82012-11-02 15:41:02 -07001435 void addGrant(const char* filename, uid_t granteeUid) {
Kenny Root655b9582013-04-04 08:37:42 -07001436 const grant_t* existing = getGrant(filename, granteeUid);
1437 if (existing == NULL) {
1438 grant_t* grant = new grant_t;
Kenny Root07438c82012-11-02 15:41:02 -07001439 grant->uid = granteeUid;
Brian Carlstroma8c703d2012-07-17 14:43:46 -07001440 grant->filename = reinterpret_cast<const uint8_t*>(strdup(filename));
Kenny Root655b9582013-04-04 08:37:42 -07001441 mGrants.add(grant);
Kenny Root70e3a862012-02-15 17:20:23 -08001442 }
1443 }
1444
Kenny Root07438c82012-11-02 15:41:02 -07001445 bool removeGrant(const char* filename, uid_t granteeUid) {
Kenny Root655b9582013-04-04 08:37:42 -07001446 for (android::Vector<grant_t*>::iterator it(mGrants.begin());
1447 it != mGrants.end(); it++) {
1448 grant_t* grant = *it;
1449 if (grant->uid == granteeUid
1450 && !strcmp(reinterpret_cast<const char*>(grant->filename), filename)) {
1451 mGrants.erase(it);
1452 return true;
1453 }
Kenny Root70e3a862012-02-15 17:20:23 -08001454 }
Kenny Root70e3a862012-02-15 17:20:23 -08001455 return false;
1456 }
1457
Brian Carlstroma8c703d2012-07-17 14:43:46 -07001458 bool hasGrant(const char* filename, const uid_t uid) const {
1459 return getGrant(filename, uid) != NULL;
Kenny Root70e3a862012-02-15 17:20:23 -08001460 }
1461
Chad Brubaker72593ee2015-05-12 10:42:00 -07001462 ResponseCode importKey(const uint8_t* key, size_t keyLen, const char* filename, uid_t userId,
Kenny Rootf9119d62013-04-03 09:22:15 -07001463 int32_t flags) {
Shawn Willden55268b52015-07-28 11:06:00 -06001464 Unique_PKCS8_PRIV_KEY_INFO pkcs8(d2i_PKCS8_PRIV_KEY_INFO(NULL, &key, keyLen));
1465 if (!pkcs8.get()) {
1466 return ::SYSTEM_ERROR;
1467 }
1468 Unique_EVP_PKEY pkey(EVP_PKCS82PKEY(pkcs8.get()));
1469 if (!pkey.get()) {
1470 return ::SYSTEM_ERROR;
1471 }
1472 int type = EVP_PKEY_type(pkey->type);
1473 android::KeymasterArguments params;
1474 add_legacy_key_authorizations(type, &params.params);
1475 switch (type) {
1476 case EVP_PKEY_RSA:
1477 params.params.push_back(keymaster_param_enum(KM_TAG_ALGORITHM, KM_ALGORITHM_RSA));
1478 break;
1479 case EVP_PKEY_EC:
1480 params.params.push_back(keymaster_param_enum(KM_TAG_ALGORITHM,
1481 KM_ALGORITHM_EC));
1482 break;
1483 default:
1484 ALOGW("Unsupported key type %d", type);
1485 return ::SYSTEM_ERROR;
Kenny Root822c3a92012-03-23 16:34:39 -07001486 }
1487
Shawn Willden55268b52015-07-28 11:06:00 -06001488 std::vector<keymaster_key_param_t> opParams(params.params);
1489 const keymaster_key_param_set_t inParams = {opParams.data(), opParams.size()};
1490 keymaster_blob_t input = {key, keyLen};
1491 keymaster_key_blob_t blob = {nullptr, 0};
Kenny Root17208e02013-09-04 13:56:03 -07001492 bool isFallback = false;
Shawn Willden55268b52015-07-28 11:06:00 -06001493 keymaster_error_t error = mDevice->import_key(mDevice, &inParams, KM_KEY_FORMAT_PKCS8,
1494 &input, &blob, NULL /* characteristics */);
1495 if (error != KM_ERROR_OK){
1496 ALOGE("Keymaster error %d importing key pair, falling back", error);
1497
Kenny Roota39da5a2014-09-25 13:07:24 -07001498 /*
Shawn Willden55268b52015-07-28 11:06:00 -06001499 * There should be no way to get here. Fallback shouldn't ever really happen
1500 * because the main device may be many (SW, KM0/SW hybrid, KM1/SW hybrid), but it must
1501 * provide full support of the API. In any case, we'll do the fallback just for
1502 * consistency... and I suppose to cover for broken HW implementations.
Kenny Roota39da5a2014-09-25 13:07:24 -07001503 */
Shawn Willden55268b52015-07-28 11:06:00 -06001504 error = mFallbackDevice->import_key(mFallbackDevice, &inParams, KM_KEY_FORMAT_PKCS8,
1505 &input, &blob, NULL /* characteristics */);
Kenny Roota39da5a2014-09-25 13:07:24 -07001506 isFallback = true;
Kenny Root17208e02013-09-04 13:56:03 -07001507
Shawn Willden55268b52015-07-28 11:06:00 -06001508 if (error) {
1509 ALOGE("Keymaster error while importing key pair with fallback: %d", error);
Kenny Root17208e02013-09-04 13:56:03 -07001510 return SYSTEM_ERROR;
1511 }
Kenny Root822c3a92012-03-23 16:34:39 -07001512 }
1513
Shawn Willden55268b52015-07-28 11:06:00 -06001514 Blob keyBlob(blob.key_material, blob.key_material_size, NULL, 0, TYPE_KEYMASTER_10);
1515 free(const_cast<uint8_t*>(blob.key_material));
Kenny Root822c3a92012-03-23 16:34:39 -07001516
Kenny Rootf9119d62013-04-03 09:22:15 -07001517 keyBlob.setEncrypted(flags & KEYSTORE_FLAG_ENCRYPTED);
Kenny Root17208e02013-09-04 13:56:03 -07001518 keyBlob.setFallback(isFallback);
Kenny Rootf9119d62013-04-03 09:22:15 -07001519
Chad Brubaker72593ee2015-05-12 10:42:00 -07001520 return put(filename, &keyBlob, userId);
Kenny Root822c3a92012-03-23 16:34:39 -07001521 }
1522
Kenny Root1b0e3932013-09-05 13:06:32 -07001523 bool isHardwareBacked(const android::String16& keyType) const {
1524 if (mDevice == NULL) {
1525 ALOGW("can't get keymaster device");
1526 return false;
1527 }
1528
1529 if (sRSAKeyType == keyType) {
1530 return (mDevice->flags & KEYMASTER_SOFTWARE_ONLY) == 0;
1531 } else {
1532 return (mDevice->flags & KEYMASTER_SOFTWARE_ONLY) == 0
1533 && (mDevice->common.module->module_api_version
1534 >= KEYMASTER_MODULE_API_VERSION_0_2);
1535 }
Kenny Root8ddf35a2013-03-29 11:15:50 -07001536 }
1537
Kenny Root655b9582013-04-04 08:37:42 -07001538 ResponseCode getKeyForName(Blob* keyBlob, const android::String8& keyName, const uid_t uid,
1539 const BlobType type) {
Kenny Root86b16e82013-09-09 11:15:54 -07001540 android::String8 filepath8(getKeyNameForUidWithDir(keyName, uid));
Chad Brubaker72593ee2015-05-12 10:42:00 -07001541 uid_t userId = get_user_id(uid);
Kenny Root655b9582013-04-04 08:37:42 -07001542
Chad Brubaker72593ee2015-05-12 10:42:00 -07001543 ResponseCode responseCode = get(filepath8.string(), keyBlob, type, userId);
Kenny Root655b9582013-04-04 08:37:42 -07001544 if (responseCode == NO_ERROR) {
1545 return responseCode;
1546 }
1547
1548 // If this is one of the legacy UID->UID mappings, use it.
1549 uid_t euid = get_keystore_euid(uid);
1550 if (euid != uid) {
Kenny Root86b16e82013-09-09 11:15:54 -07001551 filepath8 = getKeyNameForUidWithDir(keyName, euid);
Chad Brubaker72593ee2015-05-12 10:42:00 -07001552 responseCode = get(filepath8.string(), keyBlob, type, userId);
Kenny Root655b9582013-04-04 08:37:42 -07001553 if (responseCode == NO_ERROR) {
1554 return responseCode;
1555 }
1556 }
1557
1558 // They might be using a granted key.
Kenny Root86b16e82013-09-09 11:15:54 -07001559 android::String8 filename8 = getKeyName(keyName);
Kenny Root655b9582013-04-04 08:37:42 -07001560 char* end;
Kenny Root86b16e82013-09-09 11:15:54 -07001561 strtoul(filename8.string(), &end, 10);
Kenny Root655b9582013-04-04 08:37:42 -07001562 if (end[0] != '_' || end[1] == 0) {
1563 return KEY_NOT_FOUND;
1564 }
Chad Brubaker72593ee2015-05-12 10:42:00 -07001565 filepath8 = android::String8::format("%s/%s", getUserState(userId)->getUserDirName(),
Kenny Root86b16e82013-09-09 11:15:54 -07001566 filename8.string());
Kenny Root655b9582013-04-04 08:37:42 -07001567 if (!hasGrant(filepath8.string(), uid)) {
1568 return responseCode;
1569 }
1570
1571 // It is a granted key. Try to load it.
Chad Brubaker72593ee2015-05-12 10:42:00 -07001572 return get(filepath8.string(), keyBlob, type, userId);
Kenny Root655b9582013-04-04 08:37:42 -07001573 }
1574
1575 /**
1576 * Returns any existing UserState or creates it if it doesn't exist.
1577 */
Chad Brubaker72593ee2015-05-12 10:42:00 -07001578 UserState* getUserState(uid_t userId) {
Kenny Root655b9582013-04-04 08:37:42 -07001579 for (android::Vector<UserState*>::iterator it(mMasterKeys.begin());
1580 it != mMasterKeys.end(); it++) {
1581 UserState* state = *it;
1582 if (state->getUserId() == userId) {
1583 return state;
1584 }
1585 }
1586
1587 UserState* userState = new UserState(userId);
1588 if (!userState->initialize()) {
1589 /* There's not much we can do if initialization fails. Trying to
1590 * unlock the keystore for that user will fail as well, so any
1591 * subsequent request for this user will just return SYSTEM_ERROR.
1592 */
1593 ALOGE("User initialization failed for %u; subsuquent operations will fail", userId);
1594 }
1595 mMasterKeys.add(userState);
1596 return userState;
1597 }
1598
1599 /**
Chad Brubaker72593ee2015-05-12 10:42:00 -07001600 * Returns any existing UserState or creates it if it doesn't exist.
1601 */
1602 UserState* getUserStateByUid(uid_t uid) {
1603 uid_t userId = get_user_id(uid);
1604 return getUserState(userId);
1605 }
1606
1607 /**
Kenny Root655b9582013-04-04 08:37:42 -07001608 * Returns NULL if the UserState doesn't already exist.
1609 */
Chad Brubaker72593ee2015-05-12 10:42:00 -07001610 const UserState* getUserState(uid_t userId) const {
Kenny Root655b9582013-04-04 08:37:42 -07001611 for (android::Vector<UserState*>::const_iterator it(mMasterKeys.begin());
1612 it != mMasterKeys.end(); it++) {
1613 UserState* state = *it;
1614 if (state->getUserId() == userId) {
1615 return state;
1616 }
1617 }
1618
1619 return NULL;
1620 }
1621
Chad Brubaker72593ee2015-05-12 10:42:00 -07001622 /**
1623 * Returns NULL if the UserState doesn't already exist.
1624 */
1625 const UserState* getUserStateByUid(uid_t uid) const {
1626 uid_t userId = get_user_id(uid);
1627 return getUserState(userId);
1628 }
1629
Kenny Roota91203b2012-02-15 15:00:46 -08001630private:
Kenny Root655b9582013-04-04 08:37:42 -07001631 static const char* sOldMasterKey;
1632 static const char* sMetaDataFile;
Kenny Root1b0e3932013-09-05 13:06:32 -07001633 static const android::String16 sRSAKeyType;
Kenny Roota91203b2012-02-15 15:00:46 -08001634 Entropy* mEntropy;
1635
Chad Brubaker67d2a502015-03-11 17:21:18 +00001636 keymaster1_device_t* mDevice;
1637 keymaster1_device_t* mFallbackDevice;
Kenny Root70e3a862012-02-15 17:20:23 -08001638
Kenny Root655b9582013-04-04 08:37:42 -07001639 android::Vector<UserState*> mMasterKeys;
Kenny Roota91203b2012-02-15 15:00:46 -08001640
Kenny Root655b9582013-04-04 08:37:42 -07001641 android::Vector<grant_t*> mGrants;
Kenny Roota91203b2012-02-15 15:00:46 -08001642
Kenny Root655b9582013-04-04 08:37:42 -07001643 typedef struct {
1644 uint32_t version;
1645 } keystore_metadata_t;
Kenny Roota91203b2012-02-15 15:00:46 -08001646
Kenny Root655b9582013-04-04 08:37:42 -07001647 keystore_metadata_t mMetaData;
Kenny Root70e3a862012-02-15 17:20:23 -08001648
Kenny Root655b9582013-04-04 08:37:42 -07001649 const grant_t* getGrant(const char* filename, uid_t uid) const {
1650 for (android::Vector<grant_t*>::const_iterator it(mGrants.begin());
1651 it != mGrants.end(); it++) {
1652 grant_t* grant = *it;
Kenny Root70e3a862012-02-15 17:20:23 -08001653 if (grant->uid == uid
Kenny Root655b9582013-04-04 08:37:42 -07001654 && !strcmp(reinterpret_cast<const char*>(grant->filename), filename)) {
Kenny Root70e3a862012-02-15 17:20:23 -08001655 return grant;
1656 }
1657 }
Kenny Root70e3a862012-02-15 17:20:23 -08001658 return NULL;
1659 }
1660
Kenny Root822c3a92012-03-23 16:34:39 -07001661 /**
1662 * Upgrade code. This will upgrade the key from the current version
1663 * to whatever is newest.
1664 */
Kenny Root655b9582013-04-04 08:37:42 -07001665 bool upgradeBlob(const char* filename, Blob* blob, const uint8_t oldVersion,
1666 const BlobType type, uid_t uid) {
Kenny Root822c3a92012-03-23 16:34:39 -07001667 bool updated = false;
1668 uint8_t version = oldVersion;
1669
1670 /* From V0 -> V1: All old types were unknown */
1671 if (version == 0) {
1672 ALOGV("upgrading to version 1 and setting type %d", type);
1673
1674 blob->setType(type);
1675 if (type == TYPE_KEY_PAIR) {
Kenny Root655b9582013-04-04 08:37:42 -07001676 importBlobAsKey(blob, filename, uid);
Kenny Root822c3a92012-03-23 16:34:39 -07001677 }
1678 version = 1;
1679 updated = true;
1680 }
1681
Kenny Rootf9119d62013-04-03 09:22:15 -07001682 /* From V1 -> V2: All old keys were encrypted */
1683 if (version == 1) {
1684 ALOGV("upgrading to version 2");
1685
1686 blob->setEncrypted(true);
1687 version = 2;
1688 updated = true;
1689 }
1690
Kenny Root822c3a92012-03-23 16:34:39 -07001691 /*
1692 * If we've updated, set the key blob to the right version
1693 * and write it.
Kenny Rootcfeae072013-04-04 08:39:57 -07001694 */
Kenny Root822c3a92012-03-23 16:34:39 -07001695 if (updated) {
1696 ALOGV("updated and writing file %s", filename);
1697 blob->setVersion(version);
Kenny Root822c3a92012-03-23 16:34:39 -07001698 }
Kenny Rootcfeae072013-04-04 08:39:57 -07001699
1700 return updated;
Kenny Root822c3a92012-03-23 16:34:39 -07001701 }
1702
1703 /**
1704 * Takes a blob that is an PEM-encoded RSA key as a byte array and
1705 * converts it to a DER-encoded PKCS#8 for import into a keymaster.
1706 * Then it overwrites the original blob with the new blob
1707 * format that is returned from the keymaster.
1708 */
Kenny Root655b9582013-04-04 08:37:42 -07001709 ResponseCode importBlobAsKey(Blob* blob, const char* filename, uid_t uid) {
Kenny Root822c3a92012-03-23 16:34:39 -07001710 // We won't even write to the blob directly with this BIO, so const_cast is okay.
1711 Unique_BIO b(BIO_new_mem_buf(const_cast<uint8_t*>(blob->getValue()), blob->getLength()));
1712 if (b.get() == NULL) {
1713 ALOGE("Problem instantiating BIO");
1714 return SYSTEM_ERROR;
1715 }
1716
1717 Unique_EVP_PKEY pkey(PEM_read_bio_PrivateKey(b.get(), NULL, NULL, NULL));
1718 if (pkey.get() == NULL) {
1719 ALOGE("Couldn't read old PEM file");
1720 return SYSTEM_ERROR;
1721 }
1722
1723 Unique_PKCS8_PRIV_KEY_INFO pkcs8(EVP_PKEY2PKCS8(pkey.get()));
1724 int len = i2d_PKCS8_PRIV_KEY_INFO(pkcs8.get(), NULL);
1725 if (len < 0) {
1726 ALOGE("Couldn't measure PKCS#8 length");
1727 return SYSTEM_ERROR;
1728 }
1729
Kenny Root70c98892013-02-07 09:10:36 -08001730 UniquePtr<unsigned char[]> pkcs8key(new unsigned char[len]);
1731 uint8_t* tmp = pkcs8key.get();
Kenny Root822c3a92012-03-23 16:34:39 -07001732 if (i2d_PKCS8_PRIV_KEY_INFO(pkcs8.get(), &tmp) != len) {
1733 ALOGE("Couldn't convert to PKCS#8");
1734 return SYSTEM_ERROR;
1735 }
1736
Chad Brubaker72593ee2015-05-12 10:42:00 -07001737 ResponseCode rc = importKey(pkcs8key.get(), len, filename, get_user_id(uid),
Kenny Rootf9119d62013-04-03 09:22:15 -07001738 blob->isEncrypted() ? KEYSTORE_FLAG_ENCRYPTED : KEYSTORE_FLAG_NONE);
Kenny Root822c3a92012-03-23 16:34:39 -07001739 if (rc != NO_ERROR) {
1740 return rc;
1741 }
1742
Kenny Root655b9582013-04-04 08:37:42 -07001743 return get(filename, blob, TYPE_KEY_PAIR, uid);
1744 }
1745
1746 void readMetaData() {
1747 int in = TEMP_FAILURE_RETRY(open(sMetaDataFile, O_RDONLY));
1748 if (in < 0) {
1749 return;
1750 }
1751 size_t fileLength = readFully(in, (uint8_t*) &mMetaData, sizeof(mMetaData));
1752 if (fileLength != sizeof(mMetaData)) {
1753 ALOGI("Metadata file is %zd bytes (%zd experted); upgrade?", fileLength,
1754 sizeof(mMetaData));
1755 }
1756 close(in);
1757 }
1758
1759 void writeMetaData() {
1760 const char* tmpFileName = ".metadata.tmp";
1761 int out = TEMP_FAILURE_RETRY(open(tmpFileName,
1762 O_WRONLY | O_TRUNC | O_CREAT, S_IRUSR | S_IWUSR));
1763 if (out < 0) {
1764 ALOGE("couldn't write metadata file: %s", strerror(errno));
1765 return;
1766 }
1767 size_t fileLength = writeFully(out, (uint8_t*) &mMetaData, sizeof(mMetaData));
1768 if (fileLength != sizeof(mMetaData)) {
1769 ALOGI("Could only write %zd bytes to metadata file (%zd expected)", fileLength,
1770 sizeof(mMetaData));
1771 }
1772 close(out);
1773 rename(tmpFileName, sMetaDataFile);
1774 }
1775
1776 bool upgradeKeystore() {
1777 bool upgraded = false;
1778
1779 if (mMetaData.version == 0) {
Chad Brubaker72593ee2015-05-12 10:42:00 -07001780 UserState* userState = getUserStateByUid(0);
Kenny Root655b9582013-04-04 08:37:42 -07001781
1782 // Initialize first so the directory is made.
1783 userState->initialize();
1784
1785 // Migrate the old .masterkey file to user 0.
1786 if (access(sOldMasterKey, R_OK) == 0) {
1787 if (rename(sOldMasterKey, userState->getMasterKeyFileName()) < 0) {
1788 ALOGE("couldn't migrate old masterkey: %s", strerror(errno));
1789 return false;
1790 }
1791 }
1792
1793 // Initialize again in case we had a key.
1794 userState->initialize();
1795
1796 // Try to migrate existing keys.
1797 DIR* dir = opendir(".");
1798 if (!dir) {
1799 // Give up now; maybe we can upgrade later.
1800 ALOGE("couldn't open keystore's directory; something is wrong");
1801 return false;
1802 }
1803
1804 struct dirent* file;
1805 while ((file = readdir(dir)) != NULL) {
1806 // We only care about files.
1807 if (file->d_type != DT_REG) {
1808 continue;
1809 }
1810
1811 // Skip anything that starts with a "."
1812 if (file->d_name[0] == '.') {
1813 continue;
1814 }
1815
1816 // Find the current file's user.
1817 char* end;
1818 unsigned long thisUid = strtoul(file->d_name, &end, 10);
1819 if (end[0] != '_' || end[1] == 0) {
1820 continue;
1821 }
Chad Brubaker72593ee2015-05-12 10:42:00 -07001822 UserState* otherUser = getUserStateByUid(thisUid);
Kenny Root655b9582013-04-04 08:37:42 -07001823 if (otherUser->getUserId() != 0) {
1824 unlinkat(dirfd(dir), file->d_name, 0);
1825 }
1826
1827 // Rename the file into user directory.
1828 DIR* otherdir = opendir(otherUser->getUserDirName());
1829 if (otherdir == NULL) {
1830 ALOGW("couldn't open user directory for rename");
1831 continue;
1832 }
1833 if (renameat(dirfd(dir), file->d_name, dirfd(otherdir), file->d_name) < 0) {
1834 ALOGW("couldn't rename blob: %s: %s", file->d_name, strerror(errno));
1835 }
1836 closedir(otherdir);
1837 }
1838 closedir(dir);
1839
1840 mMetaData.version = 1;
1841 upgraded = true;
1842 }
1843
1844 return upgraded;
Kenny Root822c3a92012-03-23 16:34:39 -07001845 }
Kenny Roota91203b2012-02-15 15:00:46 -08001846};
1847
Kenny Root655b9582013-04-04 08:37:42 -07001848const char* KeyStore::sOldMasterKey = ".masterkey";
1849const char* KeyStore::sMetaDataFile = ".metadata";
Kenny Root70e3a862012-02-15 17:20:23 -08001850
Kenny Root1b0e3932013-09-05 13:06:32 -07001851const android::String16 KeyStore::sRSAKeyType("RSA");
1852
Kenny Root07438c82012-11-02 15:41:02 -07001853namespace android {
1854class KeyStoreProxy : public BnKeystoreService, public IBinder::DeathRecipient {
1855public:
1856 KeyStoreProxy(KeyStore* keyStore)
Chad Brubaker40a1a9b2015-02-20 14:08:13 -08001857 : mKeyStore(keyStore),
1858 mOperationMap(this)
Kenny Root07438c82012-11-02 15:41:02 -07001859 {
Kenny Roota91203b2012-02-15 15:00:46 -08001860 }
Kenny Roota91203b2012-02-15 15:00:46 -08001861
Chad Brubaker40a1a9b2015-02-20 14:08:13 -08001862 void binderDied(const wp<IBinder>& who) {
1863 auto operations = mOperationMap.getOperationsForToken(who.unsafe_get());
1864 for (auto token: operations) {
1865 abort(token);
1866 }
Kenny Root822c3a92012-03-23 16:34:39 -07001867 }
Kenny Roota91203b2012-02-15 15:00:46 -08001868
Chad Brubakere6c3bfa2015-05-12 15:18:26 -07001869 int32_t getState(int32_t userId) {
1870 if (!checkBinderPermission(P_GET_STATE)) {
Kenny Root07438c82012-11-02 15:41:02 -07001871 return ::PERMISSION_DENIED;
Kenny Roota91203b2012-02-15 15:00:46 -08001872 }
Kenny Roota91203b2012-02-15 15:00:46 -08001873
Chad Brubakere6c3bfa2015-05-12 15:18:26 -07001874 return mKeyStore->getState(userId);
Kenny Root298e7b12012-03-26 13:54:44 -07001875 }
1876
Kenny Root07438c82012-11-02 15:41:02 -07001877 int32_t get(const String16& name, uint8_t** item, size_t* itemLength) {
Chad Brubaker9489b792015-04-14 11:01:45 -07001878 if (!checkBinderPermission(P_GET)) {
Kenny Root07438c82012-11-02 15:41:02 -07001879 return ::PERMISSION_DENIED;
Kenny Roota91203b2012-02-15 15:00:46 -08001880 }
Kenny Root07438c82012-11-02 15:41:02 -07001881
Chad Brubaker9489b792015-04-14 11:01:45 -07001882 uid_t callingUid = IPCThreadState::self()->getCallingUid();
Kenny Root07438c82012-11-02 15:41:02 -07001883 String8 name8(name);
Kenny Root07438c82012-11-02 15:41:02 -07001884 Blob keyBlob;
Nick Kralevich66dbf672014-06-30 17:09:14 +00001885
Kenny Root655b9582013-04-04 08:37:42 -07001886 ResponseCode responseCode = mKeyStore->getKeyForName(&keyBlob, name8, callingUid,
Kenny Root49468902013-03-19 13:41:33 -07001887 TYPE_GENERIC);
Kenny Root07438c82012-11-02 15:41:02 -07001888 if (responseCode != ::NO_ERROR) {
1889 *item = NULL;
1890 *itemLength = 0;
1891 return responseCode;
Kenny Roota91203b2012-02-15 15:00:46 -08001892 }
Kenny Roota91203b2012-02-15 15:00:46 -08001893
Kenny Root07438c82012-11-02 15:41:02 -07001894 *item = (uint8_t*) malloc(keyBlob.getLength());
1895 memcpy(*item, keyBlob.getValue(), keyBlob.getLength());
1896 *itemLength = keyBlob.getLength();
Kenny Roota91203b2012-02-15 15:00:46 -08001897
Kenny Root07438c82012-11-02 15:41:02 -07001898 return ::NO_ERROR;
Kenny Root70e3a862012-02-15 17:20:23 -08001899 }
1900
Kenny Rootf9119d62013-04-03 09:22:15 -07001901 int32_t insert(const String16& name, const uint8_t* item, size_t itemLength, int targetUid,
1902 int32_t flags) {
Chad Brubaker9489b792015-04-14 11:01:45 -07001903 targetUid = getEffectiveUid(targetUid);
1904 int32_t result = checkBinderPermissionAndKeystoreState(P_INSERT, targetUid,
1905 flags & KEYSTORE_FLAG_ENCRYPTED);
1906 if (result != ::NO_ERROR) {
1907 return result;
Kenny Rootb88c3eb2013-02-13 14:43:43 -08001908 }
1909
Kenny Root07438c82012-11-02 15:41:02 -07001910 String8 name8(name);
Kenny Root655b9582013-04-04 08:37:42 -07001911 String8 filename(mKeyStore->getKeyNameForUidWithDir(name8, targetUid));
Kenny Root07438c82012-11-02 15:41:02 -07001912
1913 Blob keyBlob(item, itemLength, NULL, 0, ::TYPE_GENERIC);
Kenny Rootee8068b2013-10-07 09:49:15 -07001914 keyBlob.setEncrypted(flags & KEYSTORE_FLAG_ENCRYPTED);
1915
Chad Brubaker72593ee2015-05-12 10:42:00 -07001916 return mKeyStore->put(filename.string(), &keyBlob, get_user_id(targetUid));
Kenny Root70e3a862012-02-15 17:20:23 -08001917 }
1918
Kenny Root49468902013-03-19 13:41:33 -07001919 int32_t del(const String16& name, int targetUid) {
Chad Brubaker9489b792015-04-14 11:01:45 -07001920 targetUid = getEffectiveUid(targetUid);
1921 if (!checkBinderPermission(P_DELETE, targetUid)) {
Kenny Root07438c82012-11-02 15:41:02 -07001922 return ::PERMISSION_DENIED;
1923 }
Kenny Root07438c82012-11-02 15:41:02 -07001924 String8 name8(name);
Kenny Root655b9582013-04-04 08:37:42 -07001925 String8 filename(mKeyStore->getKeyNameForUidWithDir(name8, targetUid));
Chad Brubaker72593ee2015-05-12 10:42:00 -07001926 return mKeyStore->del(filename.string(), ::TYPE_ANY, get_user_id(targetUid));
Kenny Root70e3a862012-02-15 17:20:23 -08001927 }
1928
Kenny Root49468902013-03-19 13:41:33 -07001929 int32_t exist(const String16& name, int targetUid) {
Chad Brubaker9489b792015-04-14 11:01:45 -07001930 targetUid = getEffectiveUid(targetUid);
1931 if (!checkBinderPermission(P_EXIST, targetUid)) {
Kenny Rootb88c3eb2013-02-13 14:43:43 -08001932 return ::PERMISSION_DENIED;
1933 }
1934
Kenny Root07438c82012-11-02 15:41:02 -07001935 String8 name8(name);
Kenny Root655b9582013-04-04 08:37:42 -07001936 String8 filename(mKeyStore->getKeyNameForUidWithDir(name8, targetUid));
Kenny Root70e3a862012-02-15 17:20:23 -08001937
Kenny Root655b9582013-04-04 08:37:42 -07001938 if (access(filename.string(), R_OK) == -1) {
Kenny Root07438c82012-11-02 15:41:02 -07001939 return (errno != ENOENT) ? ::SYSTEM_ERROR : ::KEY_NOT_FOUND;
1940 }
1941 return ::NO_ERROR;
Kenny Root70e3a862012-02-15 17:20:23 -08001942 }
1943
Chad Brubakere6c3bfa2015-05-12 15:18:26 -07001944 int32_t list(const String16& prefix, int targetUid, Vector<String16>* matches) {
Chad Brubaker9489b792015-04-14 11:01:45 -07001945 targetUid = getEffectiveUid(targetUid);
Chad Brubakere6c3bfa2015-05-12 15:18:26 -07001946 if (!checkBinderPermission(P_LIST, targetUid)) {
Kenny Root07438c82012-11-02 15:41:02 -07001947 return ::PERMISSION_DENIED;
1948 }
Kenny Root07438c82012-11-02 15:41:02 -07001949 const String8 prefix8(prefix);
Kenny Root655b9582013-04-04 08:37:42 -07001950 String8 filename(mKeyStore->getKeyNameForUid(prefix8, targetUid));
Kenny Root70e3a862012-02-15 17:20:23 -08001951
Chad Brubakere6c3bfa2015-05-12 15:18:26 -07001952 if (mKeyStore->list(filename, matches, get_user_id(targetUid)) != ::NO_ERROR) {
Robin Lee4b84fdc2014-09-24 11:56:57 +01001953 return ::SYSTEM_ERROR;
Kenny Root9a53d3e2012-08-14 10:47:54 -07001954 }
Kenny Root07438c82012-11-02 15:41:02 -07001955 return ::NO_ERROR;
Kenny Root70e3a862012-02-15 17:20:23 -08001956 }
1957
Kenny Root07438c82012-11-02 15:41:02 -07001958 int32_t reset() {
Chad Brubaker9489b792015-04-14 11:01:45 -07001959 if (!checkBinderPermission(P_RESET)) {
Kenny Root07438c82012-11-02 15:41:02 -07001960 return ::PERMISSION_DENIED;
1961 }
1962
Chad Brubaker9489b792015-04-14 11:01:45 -07001963 uid_t callingUid = IPCThreadState::self()->getCallingUid();
Chad Brubaker96d6d782015-05-07 10:19:40 -07001964 mKeyStore->resetUser(get_user_id(callingUid), false);
1965 return ::NO_ERROR;
Kenny Root70e3a862012-02-15 17:20:23 -08001966 }
1967
Chad Brubaker96d6d782015-05-07 10:19:40 -07001968 int32_t onUserPasswordChanged(int32_t userId, const String16& password) {
Chad Brubaker9489b792015-04-14 11:01:45 -07001969 if (!checkBinderPermission(P_PASSWORD)) {
Kenny Root07438c82012-11-02 15:41:02 -07001970 return ::PERMISSION_DENIED;
1971 }
Kenny Root70e3a862012-02-15 17:20:23 -08001972
Kenny Root07438c82012-11-02 15:41:02 -07001973 const String8 password8(password);
Chad Brubaker96d6d782015-05-07 10:19:40 -07001974 // Flush the auth token table to prevent stale tokens from sticking
1975 // around.
1976 mAuthTokenTable.Clear();
1977
1978 if (password.size() == 0) {
1979 ALOGI("Secure lockscreen for user %d removed, deleting encrypted entries", userId);
Chad Brubaker72593ee2015-05-12 10:42:00 -07001980 mKeyStore->resetUser(userId, true);
Chad Brubaker96d6d782015-05-07 10:19:40 -07001981 return ::NO_ERROR;
1982 } else {
Chad Brubaker72593ee2015-05-12 10:42:00 -07001983 switch (mKeyStore->getState(userId)) {
Chad Brubaker96d6d782015-05-07 10:19:40 -07001984 case ::STATE_UNINITIALIZED: {
1985 // generate master key, encrypt with password, write to file,
1986 // initialize mMasterKey*.
Chad Brubaker72593ee2015-05-12 10:42:00 -07001987 return mKeyStore->initializeUser(password8, userId);
Chad Brubaker96d6d782015-05-07 10:19:40 -07001988 }
1989 case ::STATE_NO_ERROR: {
1990 // rewrite master key with new password.
Chad Brubaker72593ee2015-05-12 10:42:00 -07001991 return mKeyStore->writeMasterKey(password8, userId);
Chad Brubaker96d6d782015-05-07 10:19:40 -07001992 }
1993 case ::STATE_LOCKED: {
1994 ALOGE("Changing user %d's password while locked, clearing old encryption",
1995 userId);
Chad Brubaker72593ee2015-05-12 10:42:00 -07001996 mKeyStore->resetUser(userId, true);
1997 return mKeyStore->initializeUser(password8, userId);
Chad Brubaker96d6d782015-05-07 10:19:40 -07001998 }
Kenny Root07438c82012-11-02 15:41:02 -07001999 }
Chad Brubaker96d6d782015-05-07 10:19:40 -07002000 return ::SYSTEM_ERROR;
Kenny Root07438c82012-11-02 15:41:02 -07002001 }
Kenny Root70e3a862012-02-15 17:20:23 -08002002 }
2003
Chad Brubakerc0f031a2015-05-12 10:43:10 -07002004 int32_t onUserAdded(int32_t userId, int32_t parentId) {
2005 if (!checkBinderPermission(P_USER_CHANGED)) {
2006 return ::PERMISSION_DENIED;
2007 }
2008
2009 // Sanity check that the new user has an empty keystore.
2010 if (!mKeyStore->isEmpty(userId)) {
2011 ALOGW("New user %d's keystore not empty. Clearing old entries.", userId);
2012 }
2013 // Unconditionally clear the keystore, just to be safe.
2014 mKeyStore->resetUser(userId, false);
Chad Brubakerc0f031a2015-05-12 10:43:10 -07002015 if (parentId != -1) {
Chad Brubaker410ba592015-09-09 20:34:09 -07002016 // This profile must share the same master key password as the parent
2017 // profile. Because the password of the parent profile is not known
2018 // here, the best we can do is copy the parent's master key and master
2019 // key file. This makes this profile use the same master key as the
2020 // parent profile, forever.
Chad Brubakerc0f031a2015-05-12 10:43:10 -07002021 return mKeyStore->copyMasterKey(parentId, userId);
2022 } else {
2023 return ::NO_ERROR;
2024 }
2025 }
2026
2027 int32_t onUserRemoved(int32_t userId) {
2028 if (!checkBinderPermission(P_USER_CHANGED)) {
2029 return ::PERMISSION_DENIED;
2030 }
2031
2032 mKeyStore->resetUser(userId, false);
2033 return ::NO_ERROR;
2034 }
2035
Chad Brubakere6c3bfa2015-05-12 15:18:26 -07002036 int32_t lock(int32_t userId) {
Chad Brubaker9489b792015-04-14 11:01:45 -07002037 if (!checkBinderPermission(P_LOCK)) {
Kenny Root07438c82012-11-02 15:41:02 -07002038 return ::PERMISSION_DENIED;
2039 }
Kenny Root70e3a862012-02-15 17:20:23 -08002040
Chad Brubaker72593ee2015-05-12 10:42:00 -07002041 State state = mKeyStore->getState(userId);
Kenny Root9d45d1c2013-02-14 10:32:30 -08002042 if (state != ::STATE_NO_ERROR) {
Kenny Root07438c82012-11-02 15:41:02 -07002043 ALOGD("calling lock in state: %d", state);
2044 return state;
2045 }
2046
Chad Brubaker72593ee2015-05-12 10:42:00 -07002047 mKeyStore->lock(userId);
Kenny Root07438c82012-11-02 15:41:02 -07002048 return ::NO_ERROR;
Kenny Root70e3a862012-02-15 17:20:23 -08002049 }
2050
Chad Brubaker96d6d782015-05-07 10:19:40 -07002051 int32_t unlock(int32_t userId, const String16& pw) {
Chad Brubaker9489b792015-04-14 11:01:45 -07002052 if (!checkBinderPermission(P_UNLOCK)) {
Kenny Root07438c82012-11-02 15:41:02 -07002053 return ::PERMISSION_DENIED;
2054 }
2055
Chad Brubaker72593ee2015-05-12 10:42:00 -07002056 State state = mKeyStore->getState(userId);
Kenny Root9d45d1c2013-02-14 10:32:30 -08002057 if (state != ::STATE_LOCKED) {
Chad Brubaker410ba592015-09-09 20:34:09 -07002058 switch (state) {
2059 case ::STATE_NO_ERROR:
2060 ALOGI("calling unlock when already unlocked, ignoring.");
2061 break;
2062 case ::STATE_UNINITIALIZED:
2063 ALOGE("unlock called on uninitialized keystore.");
2064 break;
2065 default:
2066 ALOGE("unlock called on keystore in unknown state: %d", state);
2067 break;
2068 }
Kenny Root07438c82012-11-02 15:41:02 -07002069 return state;
2070 }
2071
2072 const String8 password8(pw);
Chad Brubaker96d6d782015-05-07 10:19:40 -07002073 // read master key, decrypt with password, initialize mMasterKey*.
Chad Brubaker72593ee2015-05-12 10:42:00 -07002074 return mKeyStore->readMasterKey(password8, userId);
Kenny Root70e3a862012-02-15 17:20:23 -08002075 }
2076
Chad Brubakere6c3bfa2015-05-12 15:18:26 -07002077 bool isEmpty(int32_t userId) {
2078 if (!checkBinderPermission(P_IS_EMPTY)) {
2079 return false;
Kenny Root07438c82012-11-02 15:41:02 -07002080 }
Kenny Root70e3a862012-02-15 17:20:23 -08002081
Chad Brubakere6c3bfa2015-05-12 15:18:26 -07002082 return mKeyStore->isEmpty(userId);
Kenny Root70e3a862012-02-15 17:20:23 -08002083 }
2084
Kenny Root96427ba2013-08-16 14:02:41 -07002085 int32_t generate(const String16& name, int32_t targetUid, int32_t keyType, int32_t keySize,
2086 int32_t flags, Vector<sp<KeystoreArg> >* args) {
Chad Brubaker9489b792015-04-14 11:01:45 -07002087 targetUid = getEffectiveUid(targetUid);
2088 int32_t result = checkBinderPermissionAndKeystoreState(P_INSERT, targetUid,
2089 flags & KEYSTORE_FLAG_ENCRYPTED);
2090 if (result != ::NO_ERROR) {
2091 return result;
Kenny Root07438c82012-11-02 15:41:02 -07002092 }
Kenny Root07438c82012-11-02 15:41:02 -07002093
Chad Brubaker3a7d9e62015-06-04 15:01:46 -07002094 KeymasterArguments params;
Shawn Willden55268b52015-07-28 11:06:00 -06002095 add_legacy_key_authorizations(keyType, &params.params);
Kenny Root07438c82012-11-02 15:41:02 -07002096
Chad Brubaker3a7d9e62015-06-04 15:01:46 -07002097 switch (keyType) {
2098 case EVP_PKEY_EC: {
2099 params.params.push_back(keymaster_param_enum(KM_TAG_ALGORITHM, KM_ALGORITHM_EC));
2100 if (keySize == -1) {
2101 keySize = EC_DEFAULT_KEY_SIZE;
2102 } else if (keySize < EC_MIN_KEY_SIZE || keySize > EC_MAX_KEY_SIZE) {
2103 ALOGI("invalid key size %d", keySize);
Kenny Root96427ba2013-08-16 14:02:41 -07002104 return ::SYSTEM_ERROR;
2105 }
Chad Brubaker3a7d9e62015-06-04 15:01:46 -07002106 params.params.push_back(keymaster_param_int(KM_TAG_KEY_SIZE, keySize));
2107 break;
Kenny Root96427ba2013-08-16 14:02:41 -07002108 }
Chad Brubaker3a7d9e62015-06-04 15:01:46 -07002109 case EVP_PKEY_RSA: {
2110 params.params.push_back(keymaster_param_enum(KM_TAG_ALGORITHM, KM_ALGORITHM_RSA));
2111 if (keySize == -1) {
2112 keySize = RSA_DEFAULT_KEY_SIZE;
2113 } else if (keySize < RSA_MIN_KEY_SIZE || keySize > RSA_MAX_KEY_SIZE) {
2114 ALOGI("invalid key size %d", keySize);
2115 return ::SYSTEM_ERROR;
Kenny Root96427ba2013-08-16 14:02:41 -07002116 }
Chad Brubaker3a7d9e62015-06-04 15:01:46 -07002117 params.params.push_back(keymaster_param_int(KM_TAG_KEY_SIZE, keySize));
2118 unsigned long exponent = RSA_DEFAULT_EXPONENT;
2119 if (args->size() > 1) {
2120 ALOGI("invalid number of arguments: %zu", args->size());
2121 return ::SYSTEM_ERROR;
2122 } else if (args->size() == 1) {
2123 sp<KeystoreArg> expArg = args->itemAt(0);
2124 if (expArg != NULL) {
2125 Unique_BIGNUM pubExpBn(
2126 BN_bin2bn(reinterpret_cast<const unsigned char*>(expArg->data()),
2127 expArg->size(), NULL));
2128 if (pubExpBn.get() == NULL) {
2129 ALOGI("Could not convert public exponent to BN");
2130 return ::SYSTEM_ERROR;
2131 }
2132 exponent = BN_get_word(pubExpBn.get());
2133 if (exponent == 0xFFFFFFFFL) {
2134 ALOGW("cannot represent public exponent as a long value");
2135 return ::SYSTEM_ERROR;
2136 }
2137 } else {
2138 ALOGW("public exponent not read");
2139 return ::SYSTEM_ERROR;
2140 }
2141 }
2142 params.params.push_back(keymaster_param_long(KM_TAG_RSA_PUBLIC_EXPONENT,
2143 exponent));
2144 break;
Kenny Root96427ba2013-08-16 14:02:41 -07002145 }
Chad Brubaker3a7d9e62015-06-04 15:01:46 -07002146 default: {
2147 ALOGW("Unsupported key type %d", keyType);
2148 return ::SYSTEM_ERROR;
2149 }
Kenny Root96427ba2013-08-16 14:02:41 -07002150 }
2151
Chad Brubaker3a7d9e62015-06-04 15:01:46 -07002152 int32_t rc = generateKey(name, params, NULL, 0, targetUid, flags,
2153 /*outCharacteristics*/ NULL);
2154 if (rc != ::NO_ERROR) {
2155 ALOGW("generate failed: %d", rc);
Kenny Root07438c82012-11-02 15:41:02 -07002156 }
Chad Brubaker3a7d9e62015-06-04 15:01:46 -07002157 return translateResultToLegacyResult(rc);
Kenny Root70e3a862012-02-15 17:20:23 -08002158 }
2159
Kenny Rootf9119d62013-04-03 09:22:15 -07002160 int32_t import(const String16& name, const uint8_t* data, size_t length, int targetUid,
2161 int32_t flags) {
Chad Brubaker3a7d9e62015-06-04 15:01:46 -07002162 const uint8_t* ptr = data;
Kenny Root07438c82012-11-02 15:41:02 -07002163
Chad Brubaker3a7d9e62015-06-04 15:01:46 -07002164 Unique_PKCS8_PRIV_KEY_INFO pkcs8(d2i_PKCS8_PRIV_KEY_INFO(NULL, &ptr, length));
2165 if (!pkcs8.get()) {
2166 return ::SYSTEM_ERROR;
2167 }
2168 Unique_EVP_PKEY pkey(EVP_PKCS82PKEY(pkcs8.get()));
2169 if (!pkey.get()) {
2170 return ::SYSTEM_ERROR;
2171 }
2172 int type = EVP_PKEY_type(pkey->type);
Shawn Willden2de8b752015-07-23 05:54:31 -06002173 KeymasterArguments params;
Shawn Willden55268b52015-07-28 11:06:00 -06002174 add_legacy_key_authorizations(type, &params.params);
Chad Brubaker3a7d9e62015-06-04 15:01:46 -07002175 switch (type) {
2176 case EVP_PKEY_RSA:
2177 params.params.push_back(keymaster_param_enum(KM_TAG_ALGORITHM, KM_ALGORITHM_RSA));
2178 break;
2179 case EVP_PKEY_EC:
2180 params.params.push_back(keymaster_param_enum(KM_TAG_ALGORITHM,
2181 KM_ALGORITHM_EC));
2182 break;
2183 default:
2184 ALOGW("Unsupported key type %d", type);
2185 return ::SYSTEM_ERROR;
2186 }
2187 int32_t rc = importKey(name, params, KM_KEY_FORMAT_PKCS8, data, length, targetUid, flags,
2188 /*outCharacteristics*/ NULL);
2189 if (rc != ::NO_ERROR) {
2190 ALOGW("importKey failed: %d", rc);
2191 }
2192 return translateResultToLegacyResult(rc);
Kenny Root70e3a862012-02-15 17:20:23 -08002193 }
2194
Kenny Root07438c82012-11-02 15:41:02 -07002195 int32_t sign(const String16& name, const uint8_t* data, size_t length, uint8_t** out,
Chad Brubaker3a7d9e62015-06-04 15:01:46 -07002196 size_t* outLength) {
Chad Brubaker9489b792015-04-14 11:01:45 -07002197 if (!checkBinderPermission(P_SIGN)) {
Kenny Root07438c82012-11-02 15:41:02 -07002198 return ::PERMISSION_DENIED;
2199 }
Chad Brubaker3a7d9e62015-06-04 15:01:46 -07002200 return doLegacySignVerify(name, data, length, out, outLength, NULL, 0, KM_PURPOSE_SIGN);
Kenny Root70e3a862012-02-15 17:20:23 -08002201 }
2202
Kenny Root07438c82012-11-02 15:41:02 -07002203 int32_t verify(const String16& name, const uint8_t* data, size_t dataLength,
2204 const uint8_t* signature, size_t signatureLength) {
Chad Brubaker9489b792015-04-14 11:01:45 -07002205 if (!checkBinderPermission(P_VERIFY)) {
Kenny Root07438c82012-11-02 15:41:02 -07002206 return ::PERMISSION_DENIED;
2207 }
Chad Brubaker3a7d9e62015-06-04 15:01:46 -07002208 return doLegacySignVerify(name, data, dataLength, NULL, NULL, signature, signatureLength,
2209 KM_PURPOSE_VERIFY);
Kenny Roota91203b2012-02-15 15:00:46 -08002210 }
Kenny Root07438c82012-11-02 15:41:02 -07002211
2212 /*
2213 * TODO: The abstraction between things stored in hardware and regular blobs
2214 * of data stored on the filesystem should be moved down to keystore itself.
2215 * Unfortunately the Java code that calls this has naming conventions that it
2216 * knows about. Ideally keystore shouldn't be used to store random blobs of
2217 * data.
2218 *
2219 * Until that happens, it's necessary to have a separate "get_pubkey" and
2220 * "del_key" since the Java code doesn't really communicate what it's
2221 * intentions are.
2222 */
2223 int32_t get_pubkey(const String16& name, uint8_t** pubkey, size_t* pubkeyLength) {
Chad Brubaker3a7d9e62015-06-04 15:01:46 -07002224 ExportResult result;
2225 exportKey(name, KM_KEY_FORMAT_X509, NULL, NULL, &result);
2226 if (result.resultCode != ::NO_ERROR) {
2227 ALOGW("export failed: %d", result.resultCode);
2228 return translateResultToLegacyResult(result.resultCode);
Kenny Root07438c82012-11-02 15:41:02 -07002229 }
Kenny Root07438c82012-11-02 15:41:02 -07002230
Chad Brubaker3a7d9e62015-06-04 15:01:46 -07002231 *pubkey = result.exportData.release();
2232 *pubkeyLength = result.dataLength;
Kenny Root07438c82012-11-02 15:41:02 -07002233 return ::NO_ERROR;
Kenny Roota91203b2012-02-15 15:00:46 -08002234 }
Kenny Root07438c82012-11-02 15:41:02 -07002235
Kenny Root07438c82012-11-02 15:41:02 -07002236 int32_t grant(const String16& name, int32_t granteeUid) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08002237 uid_t callingUid = IPCThreadState::self()->getCallingUid();
Chad Brubaker9489b792015-04-14 11:01:45 -07002238 int32_t result = checkBinderPermissionAndKeystoreState(P_GRANT);
2239 if (result != ::NO_ERROR) {
2240 return result;
Kenny Root07438c82012-11-02 15:41:02 -07002241 }
2242
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) {
Kenny Root07438c82012-11-02 15:41:02 -07002247 return (errno != ENOENT) ? ::SYSTEM_ERROR : ::KEY_NOT_FOUND;
2248 }
2249
Kenny Root655b9582013-04-04 08:37:42 -07002250 mKeyStore->addGrant(filename.string(), granteeUid);
Kenny Root07438c82012-11-02 15:41:02 -07002251 return ::NO_ERROR;
2252 }
2253
2254 int32_t ungrant(const String16& name, int32_t granteeUid) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08002255 uid_t callingUid = IPCThreadState::self()->getCallingUid();
Chad Brubaker9489b792015-04-14 11:01:45 -07002256 int32_t result = checkBinderPermissionAndKeystoreState(P_GRANT);
2257 if (result != ::NO_ERROR) {
2258 return result;
Kenny Root07438c82012-11-02 15:41:02 -07002259 }
2260
2261 String8 name8(name);
Kenny Root655b9582013-04-04 08:37:42 -07002262 String8 filename(mKeyStore->getKeyNameForUidWithDir(name8, callingUid));
Kenny Root07438c82012-11-02 15:41:02 -07002263
Kenny Root655b9582013-04-04 08:37:42 -07002264 if (access(filename.string(), R_OK) == -1) {
Kenny Root07438c82012-11-02 15:41:02 -07002265 return (errno != ENOENT) ? ::SYSTEM_ERROR : ::KEY_NOT_FOUND;
2266 }
2267
Kenny Root655b9582013-04-04 08:37:42 -07002268 return mKeyStore->removeGrant(filename.string(), granteeUid) ? ::NO_ERROR : ::KEY_NOT_FOUND;
Kenny Root07438c82012-11-02 15:41:02 -07002269 }
2270
2271 int64_t getmtime(const String16& name) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08002272 uid_t callingUid = IPCThreadState::self()->getCallingUid();
Chad Brubaker9489b792015-04-14 11:01:45 -07002273 if (!checkBinderPermission(P_GET)) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08002274 ALOGW("permission denied for %d: getmtime", callingUid);
Kenny Root36a9e232013-02-04 14:24:15 -08002275 return -1L;
Kenny Root07438c82012-11-02 15:41:02 -07002276 }
Kenny Root07438c82012-11-02 15:41:02 -07002277
2278 String8 name8(name);
Kenny Root655b9582013-04-04 08:37:42 -07002279 String8 filename(mKeyStore->getKeyNameForUidWithDir(name8, callingUid));
Kenny Root07438c82012-11-02 15:41:02 -07002280
Kenny Root655b9582013-04-04 08:37:42 -07002281 if (access(filename.string(), R_OK) == -1) {
2282 ALOGW("could not access %s for getmtime", filename.string());
Kenny Root36a9e232013-02-04 14:24:15 -08002283 return -1L;
Kenny Root07438c82012-11-02 15:41:02 -07002284 }
2285
Kenny Root655b9582013-04-04 08:37:42 -07002286 int fd = TEMP_FAILURE_RETRY(open(filename.string(), O_NOFOLLOW, O_RDONLY));
Kenny Root07438c82012-11-02 15:41:02 -07002287 if (fd < 0) {
Kenny Root655b9582013-04-04 08:37:42 -07002288 ALOGW("could not open %s for getmtime", filename.string());
Kenny Root36a9e232013-02-04 14:24:15 -08002289 return -1L;
Kenny Root07438c82012-11-02 15:41:02 -07002290 }
2291
2292 struct stat s;
2293 int ret = fstat(fd, &s);
2294 close(fd);
2295 if (ret == -1) {
Kenny Root655b9582013-04-04 08:37:42 -07002296 ALOGW("could not stat %s for getmtime", filename.string());
Kenny Root36a9e232013-02-04 14:24:15 -08002297 return -1L;
Kenny Root07438c82012-11-02 15:41:02 -07002298 }
2299
Kenny Root36a9e232013-02-04 14:24:15 -08002300 return static_cast<int64_t>(s.st_mtime);
Kenny Root07438c82012-11-02 15:41:02 -07002301 }
2302
Kenny Rootd53bc922013-03-21 14:10:15 -07002303 int32_t duplicate(const String16& srcKey, int32_t srcUid, const String16& destKey,
2304 int32_t destUid) {
Kenny Root02254072013-03-20 11:48:19 -07002305 uid_t callingUid = IPCThreadState::self()->getCallingUid();
Riley Spahneaabae92014-06-30 12:39:52 -07002306 pid_t spid = IPCThreadState::self()->getCallingPid();
2307 if (!has_permission(callingUid, P_DUPLICATE, spid)) {
Kenny Rootd53bc922013-03-21 14:10:15 -07002308 ALOGW("permission denied for %d: duplicate", callingUid);
Kenny Root02254072013-03-20 11:48:19 -07002309 return -1L;
2310 }
2311
Chad Brubaker72593ee2015-05-12 10:42:00 -07002312 State state = mKeyStore->getState(get_user_id(callingUid));
Kenny Root02254072013-03-20 11:48:19 -07002313 if (!isKeystoreUnlocked(state)) {
Kenny Rootd53bc922013-03-21 14:10:15 -07002314 ALOGD("calling duplicate in state: %d", state);
Kenny Root02254072013-03-20 11:48:19 -07002315 return state;
2316 }
2317
Kenny Rootd53bc922013-03-21 14:10:15 -07002318 if (srcUid == -1 || static_cast<uid_t>(srcUid) == callingUid) {
2319 srcUid = callingUid;
2320 } else if (!is_granted_to(callingUid, srcUid)) {
2321 ALOGD("migrate not granted from source: %d -> %d", callingUid, srcUid);
Kenny Root02254072013-03-20 11:48:19 -07002322 return ::PERMISSION_DENIED;
2323 }
2324
Kenny Rootd53bc922013-03-21 14:10:15 -07002325 if (destUid == -1) {
2326 destUid = callingUid;
2327 }
2328
2329 if (srcUid != destUid) {
2330 if (static_cast<uid_t>(srcUid) != callingUid) {
2331 ALOGD("can only duplicate from caller to other or to same uid: "
2332 "calling=%d, srcUid=%d, destUid=%d", callingUid, srcUid, destUid);
2333 return ::PERMISSION_DENIED;
2334 }
2335
2336 if (!is_granted_to(callingUid, destUid)) {
2337 ALOGD("duplicate not granted to dest: %d -> %d", callingUid, destUid);
2338 return ::PERMISSION_DENIED;
2339 }
2340 }
2341
2342 String8 source8(srcKey);
Kenny Root655b9582013-04-04 08:37:42 -07002343 String8 sourceFile(mKeyStore->getKeyNameForUidWithDir(source8, srcUid));
Kenny Root02254072013-03-20 11:48:19 -07002344
Kenny Rootd53bc922013-03-21 14:10:15 -07002345 String8 target8(destKey);
Kenny Rootfa27d5b2013-10-15 09:01:08 -07002346 String8 targetFile(mKeyStore->getKeyNameForUidWithDir(target8, destUid));
Kenny Root02254072013-03-20 11:48:19 -07002347
Kenny Root655b9582013-04-04 08:37:42 -07002348 if (access(targetFile.string(), W_OK) != -1 || errno != ENOENT) {
2349 ALOGD("destination already exists: %s", targetFile.string());
Kenny Root02254072013-03-20 11:48:19 -07002350 return ::SYSTEM_ERROR;
2351 }
2352
Kenny Rootd53bc922013-03-21 14:10:15 -07002353 Blob keyBlob;
Kenny Root655b9582013-04-04 08:37:42 -07002354 ResponseCode responseCode = mKeyStore->get(sourceFile.string(), &keyBlob, TYPE_ANY,
Chad Brubaker72593ee2015-05-12 10:42:00 -07002355 get_user_id(srcUid));
Kenny Rootd53bc922013-03-21 14:10:15 -07002356 if (responseCode != ::NO_ERROR) {
2357 return responseCode;
Kenny Root02254072013-03-20 11:48:19 -07002358 }
Kenny Rootd53bc922013-03-21 14:10:15 -07002359
Chad Brubaker72593ee2015-05-12 10:42:00 -07002360 return mKeyStore->put(targetFile.string(), &keyBlob, get_user_id(destUid));
Kenny Root02254072013-03-20 11:48:19 -07002361 }
2362
Kenny Root1b0e3932013-09-05 13:06:32 -07002363 int32_t is_hardware_backed(const String16& keyType) {
2364 return mKeyStore->isHardwareBacked(keyType) ? 1 : 0;
Kenny Root8ddf35a2013-03-29 11:15:50 -07002365 }
2366
Kenny Rootfa27d5b2013-10-15 09:01:08 -07002367 int32_t clear_uid(int64_t targetUid64) {
Chad Brubaker9489b792015-04-14 11:01:45 -07002368 uid_t targetUid = getEffectiveUid(targetUid64);
Chad Brubakerb37a5232015-05-01 10:21:27 -07002369 if (!checkBinderPermissionSelfOrSystem(P_CLEAR_UID, targetUid)) {
Kenny Roota9bb5492013-04-01 16:29:11 -07002370 return ::PERMISSION_DENIED;
2371 }
2372
Robin Lee4b84fdc2014-09-24 11:56:57 +01002373 String8 prefix = String8::format("%u_", targetUid);
2374 Vector<String16> aliases;
Chad Brubakere6c3bfa2015-05-12 15:18:26 -07002375 if (mKeyStore->list(prefix, &aliases, get_user_id(targetUid)) != ::NO_ERROR) {
Kenny Roota9bb5492013-04-01 16:29:11 -07002376 return ::SYSTEM_ERROR;
2377 }
2378
Robin Lee4b84fdc2014-09-24 11:56:57 +01002379 for (uint32_t i = 0; i < aliases.size(); i++) {
2380 String8 name8(aliases[i]);
2381 String8 filename(mKeyStore->getKeyNameForUidWithDir(name8, targetUid));
Chad Brubaker72593ee2015-05-12 10:42:00 -07002382 mKeyStore->del(filename.string(), ::TYPE_ANY, get_user_id(targetUid));
Kenny Roota9bb5492013-04-01 16:29:11 -07002383 }
Robin Lee4b84fdc2014-09-24 11:56:57 +01002384 return ::NO_ERROR;
Kenny Roota9bb5492013-04-01 16:29:11 -07002385 }
2386
Chad Brubaker9c8612c2015-02-09 11:32:54 -08002387 int32_t addRngEntropy(const uint8_t* data, size_t dataLength) {
2388 const keymaster1_device_t* device = mKeyStore->getDevice();
2389 const keymaster1_device_t* fallback = mKeyStore->getFallbackDevice();
2390 int32_t devResult = KM_ERROR_UNIMPLEMENTED;
2391 int32_t fallbackResult = KM_ERROR_UNIMPLEMENTED;
2392 if (device->common.module->module_api_version >= KEYMASTER_MODULE_API_VERSION_1_0 &&
2393 device->add_rng_entropy != NULL) {
2394 devResult = device->add_rng_entropy(device, data, dataLength);
2395 }
2396 if (fallback->add_rng_entropy) {
2397 fallbackResult = fallback->add_rng_entropy(fallback, data, dataLength);
2398 }
2399 if (devResult) {
2400 return devResult;
2401 }
2402 if (fallbackResult) {
2403 return fallbackResult;
2404 }
2405 return ::NO_ERROR;
Chad Brubaker9899d6b2015-02-03 13:03:00 -08002406 }
2407
Chad Brubaker17d68b92015-02-05 22:04:16 -08002408 int32_t generateKey(const String16& name, const KeymasterArguments& params,
Chad Brubaker154d7692015-03-27 13:59:31 -07002409 const uint8_t* entropy, size_t entropyLength, int uid, int flags,
2410 KeyCharacteristics* outCharacteristics) {
Chad Brubaker9489b792015-04-14 11:01:45 -07002411 uid = getEffectiveUid(uid);
2412 int rc = checkBinderPermissionAndKeystoreState(P_INSERT, uid,
2413 flags & KEYSTORE_FLAG_ENCRYPTED);
2414 if (rc != ::NO_ERROR) {
2415 return rc;
Chad Brubaker17d68b92015-02-05 22:04:16 -08002416 }
2417
Chad Brubaker9489b792015-04-14 11:01:45 -07002418 rc = KM_ERROR_UNIMPLEMENTED;
Chad Brubaker17d68b92015-02-05 22:04:16 -08002419 bool isFallback = false;
2420 keymaster_key_blob_t blob;
2421 keymaster_key_characteristics_t *out = NULL;
2422
2423 const keymaster1_device_t* device = mKeyStore->getDevice();
2424 const keymaster1_device_t* fallback = mKeyStore->getFallbackDevice();
Chad Brubaker57e106d2015-06-01 12:59:00 -07002425 std::vector<keymaster_key_param_t> opParams(params.params);
2426 const keymaster_key_param_set_t inParams = {opParams.data(), opParams.size()};
Chad Brubaker17d68b92015-02-05 22:04:16 -08002427 if (device == NULL) {
2428 return ::SYSTEM_ERROR;
2429 }
Chad Brubaker154d7692015-03-27 13:59:31 -07002430 // TODO: Seed from Linux RNG before this.
Chad Brubaker17d68b92015-02-05 22:04:16 -08002431 if (device->common.module->module_api_version >= KEYMASTER_MODULE_API_VERSION_1_0 &&
2432 device->generate_key != NULL) {
Chad Brubaker154d7692015-03-27 13:59:31 -07002433 if (!entropy) {
2434 rc = KM_ERROR_OK;
2435 } else if (device->add_rng_entropy) {
2436 rc = device->add_rng_entropy(device, entropy, entropyLength);
2437 } else {
2438 rc = KM_ERROR_UNIMPLEMENTED;
2439 }
2440 if (rc == KM_ERROR_OK) {
Chad Brubaker57e106d2015-06-01 12:59:00 -07002441 rc = device->generate_key(device, &inParams, &blob, &out);
Chad Brubaker154d7692015-03-27 13:59:31 -07002442 }
Chad Brubaker17d68b92015-02-05 22:04:16 -08002443 }
2444 // If the HW device didn't support generate_key or generate_key failed
2445 // fall back to the software implementation.
2446 if (rc && fallback->generate_key != NULL) {
Shawn Willden55268b52015-07-28 11:06:00 -06002447 ALOGW("Primary keymaster device failed to generate key, falling back to SW.");
Chad Brubaker17d68b92015-02-05 22:04:16 -08002448 isFallback = true;
Chad Brubaker154d7692015-03-27 13:59:31 -07002449 if (!entropy) {
2450 rc = KM_ERROR_OK;
2451 } else if (fallback->add_rng_entropy) {
2452 rc = fallback->add_rng_entropy(fallback, entropy, entropyLength);
2453 } else {
2454 rc = KM_ERROR_UNIMPLEMENTED;
2455 }
2456 if (rc == KM_ERROR_OK) {
Chad Brubaker57e106d2015-06-01 12:59:00 -07002457 rc = fallback->generate_key(fallback, &inParams, &blob, &out);
Chad Brubaker154d7692015-03-27 13:59:31 -07002458 }
Chad Brubaker17d68b92015-02-05 22:04:16 -08002459 }
2460
2461 if (out) {
2462 if (outCharacteristics) {
2463 outCharacteristics->characteristics = *out;
2464 } else {
2465 keymaster_free_characteristics(out);
2466 }
2467 free(out);
2468 }
2469
2470 if (rc) {
2471 return rc;
2472 }
2473
2474 String8 name8(name);
2475 String8 filename(mKeyStore->getKeyNameForUidWithDir(name8, uid));
2476
2477 Blob keyBlob(blob.key_material, blob.key_material_size, NULL, 0, ::TYPE_KEYMASTER_10);
2478 keyBlob.setFallback(isFallback);
2479 keyBlob.setEncrypted(flags & KEYSTORE_FLAG_ENCRYPTED);
2480
2481 free(const_cast<uint8_t*>(blob.key_material));
2482
Chad Brubaker72593ee2015-05-12 10:42:00 -07002483 return mKeyStore->put(filename.string(), &keyBlob, get_user_id(uid));
Chad Brubaker9899d6b2015-02-03 13:03:00 -08002484 }
2485
Chad Brubakerf3f071f2015-02-10 19:38:51 -08002486 int32_t getKeyCharacteristics(const String16& name,
Chad Brubakerd6634422015-03-21 22:36:07 -07002487 const keymaster_blob_t* clientId,
2488 const keymaster_blob_t* appData,
Chad Brubakerf3f071f2015-02-10 19:38:51 -08002489 KeyCharacteristics* outCharacteristics) {
Chad Brubakerf3f071f2015-02-10 19:38:51 -08002490 if (!outCharacteristics) {
2491 return KM_ERROR_UNEXPECTED_NULL_POINTER;
2492 }
2493
2494 uid_t callingUid = IPCThreadState::self()->getCallingUid();
2495
2496 Blob keyBlob;
2497 String8 name8(name);
2498 int rc;
2499
2500 ResponseCode responseCode = mKeyStore->getKeyForName(&keyBlob, name8, callingUid,
2501 TYPE_KEYMASTER_10);
2502 if (responseCode != ::NO_ERROR) {
2503 return responseCode;
2504 }
2505 keymaster_key_blob_t key;
2506 key.key_material_size = keyBlob.getLength();
2507 key.key_material = keyBlob.getValue();
2508 keymaster1_device_t* dev = mKeyStore->getDeviceForBlob(keyBlob);
2509 keymaster_key_characteristics_t *out = NULL;
2510 if (!dev->get_key_characteristics) {
2511 ALOGW("device does not implement get_key_characteristics");
2512 return KM_ERROR_UNIMPLEMENTED;
2513 }
Chad Brubakerd6634422015-03-21 22:36:07 -07002514 rc = dev->get_key_characteristics(dev, &key, clientId, appData, &out);
Chad Brubakerf3f071f2015-02-10 19:38:51 -08002515 if (out) {
2516 outCharacteristics->characteristics = *out;
2517 free(out);
2518 }
2519 return rc ? rc : ::NO_ERROR;
Chad Brubaker9899d6b2015-02-03 13:03:00 -08002520 }
2521
Chad Brubaker4c353cb2015-02-11 14:36:11 -08002522 int32_t importKey(const String16& name, const KeymasterArguments& params,
2523 keymaster_key_format_t format, const uint8_t *keyData,
2524 size_t keyLength, int uid, int flags,
2525 KeyCharacteristics* outCharacteristics) {
Chad Brubaker9489b792015-04-14 11:01:45 -07002526 uid = getEffectiveUid(uid);
2527 int rc = checkBinderPermissionAndKeystoreState(P_INSERT, uid,
2528 flags & KEYSTORE_FLAG_ENCRYPTED);
2529 if (rc != ::NO_ERROR) {
2530 return rc;
Chad Brubaker4c353cb2015-02-11 14:36:11 -08002531 }
2532
Chad Brubaker9489b792015-04-14 11:01:45 -07002533 rc = KM_ERROR_UNIMPLEMENTED;
Chad Brubaker4c353cb2015-02-11 14:36:11 -08002534 bool isFallback = false;
2535 keymaster_key_blob_t blob;
2536 keymaster_key_characteristics_t *out = NULL;
2537
2538 const keymaster1_device_t* device = mKeyStore->getDevice();
2539 const keymaster1_device_t* fallback = mKeyStore->getFallbackDevice();
Chad Brubaker57e106d2015-06-01 12:59:00 -07002540 std::vector<keymaster_key_param_t> opParams(params.params);
2541 const keymaster_key_param_set_t inParams = {opParams.data(), opParams.size()};
2542 const keymaster_blob_t input = {keyData, keyLength};
Chad Brubaker4c353cb2015-02-11 14:36:11 -08002543 if (device == NULL) {
2544 return ::SYSTEM_ERROR;
2545 }
2546 if (device->common.module->module_api_version >= KEYMASTER_MODULE_API_VERSION_1_0 &&
2547 device->import_key != NULL) {
Chad Brubaker57e106d2015-06-01 12:59:00 -07002548 rc = device->import_key(device, &inParams, format,&input, &blob, &out);
Chad Brubaker4c353cb2015-02-11 14:36:11 -08002549 }
2550 if (rc && fallback->import_key != NULL) {
Shawn Willden55268b52015-07-28 11:06:00 -06002551 ALOGW("Primary keymaster device failed to import key, falling back to SW.");
Chad Brubaker4c353cb2015-02-11 14:36:11 -08002552 isFallback = true;
Chad Brubaker57e106d2015-06-01 12:59:00 -07002553 rc = fallback->import_key(fallback, &inParams, format, &input, &blob, &out);
Chad Brubaker4c353cb2015-02-11 14:36:11 -08002554 }
2555 if (out) {
2556 if (outCharacteristics) {
2557 outCharacteristics->characteristics = *out;
2558 } else {
2559 keymaster_free_characteristics(out);
2560 }
2561 free(out);
2562 }
2563 if (rc) {
2564 return rc;
2565 }
2566
2567 String8 name8(name);
2568 String8 filename(mKeyStore->getKeyNameForUidWithDir(name8, uid));
2569
2570 Blob keyBlob(blob.key_material, blob.key_material_size, NULL, 0, ::TYPE_KEYMASTER_10);
2571 keyBlob.setFallback(isFallback);
2572 keyBlob.setEncrypted(flags & KEYSTORE_FLAG_ENCRYPTED);
2573
2574 free((void*) blob.key_material);
2575
Chad Brubaker72593ee2015-05-12 10:42:00 -07002576 return mKeyStore->put(filename.string(), &keyBlob, get_user_id(uid));
Chad Brubaker9899d6b2015-02-03 13:03:00 -08002577 }
2578
Chad Brubaker07b0cda2015-02-18 15:52:54 -08002579 void exportKey(const String16& name, keymaster_key_format_t format,
Chad Brubakerd6634422015-03-21 22:36:07 -07002580 const keymaster_blob_t* clientId,
2581 const keymaster_blob_t* appData, ExportResult* result) {
Chad Brubaker07b0cda2015-02-18 15:52:54 -08002582
2583 uid_t callingUid = IPCThreadState::self()->getCallingUid();
2584
2585 Blob keyBlob;
2586 String8 name8(name);
2587 int rc;
2588
2589 ResponseCode responseCode = mKeyStore->getKeyForName(&keyBlob, name8, callingUid,
2590 TYPE_KEYMASTER_10);
2591 if (responseCode != ::NO_ERROR) {
2592 result->resultCode = responseCode;
2593 return;
2594 }
2595 keymaster_key_blob_t key;
2596 key.key_material_size = keyBlob.getLength();
2597 key.key_material = keyBlob.getValue();
2598 keymaster1_device_t* dev = mKeyStore->getDeviceForBlob(keyBlob);
2599 if (!dev->export_key) {
2600 result->resultCode = KM_ERROR_UNIMPLEMENTED;
2601 return;
2602 }
Chad Brubaker57e106d2015-06-01 12:59:00 -07002603 keymaster_blob_t output = {NULL, 0};
2604 rc = dev->export_key(dev, format, &key, clientId, appData, &output);
2605 result->exportData.reset(const_cast<uint8_t*>(output.data));
2606 result->dataLength = output.data_length;
Chad Brubaker07b0cda2015-02-18 15:52:54 -08002607 result->resultCode = rc ? rc : ::NO_ERROR;
Chad Brubaker9899d6b2015-02-03 13:03:00 -08002608 }
2609
Chad Brubakerad6514a2015-04-09 14:00:26 -07002610
Chad Brubaker40a1a9b2015-02-20 14:08:13 -08002611 void begin(const sp<IBinder>& appToken, const String16& name, keymaster_purpose_t purpose,
Chad Brubaker154d7692015-03-27 13:59:31 -07002612 bool pruneable, const KeymasterArguments& params, const uint8_t* entropy,
Chad Brubaker57e106d2015-06-01 12:59:00 -07002613 size_t entropyLength, OperationResult* result) {
Chad Brubaker40a1a9b2015-02-20 14:08:13 -08002614 uid_t callingUid = IPCThreadState::self()->getCallingUid();
2615 if (!pruneable && get_app_id(callingUid) != AID_SYSTEM) {
2616 ALOGE("Non-system uid %d trying to start non-pruneable operation", callingUid);
2617 result->resultCode = ::PERMISSION_DENIED;
2618 return;
2619 }
Chad Brubaker0cf34a22015-04-23 11:06:16 -07002620 if (!checkAllowedOperationParams(params.params)) {
2621 result->resultCode = KM_ERROR_INVALID_ARGUMENT;
2622 return;
2623 }
Chad Brubaker40a1a9b2015-02-20 14:08:13 -08002624 Blob keyBlob;
2625 String8 name8(name);
2626 ResponseCode responseCode = mKeyStore->getKeyForName(&keyBlob, name8, callingUid,
2627 TYPE_KEYMASTER_10);
2628 if (responseCode != ::NO_ERROR) {
2629 result->resultCode = responseCode;
2630 return;
2631 }
2632 keymaster_key_blob_t key;
2633 key.key_material_size = keyBlob.getLength();
2634 key.key_material = keyBlob.getValue();
Chad Brubaker40a1a9b2015-02-20 14:08:13 -08002635 keymaster_operation_handle_t handle;
2636 keymaster1_device_t* dev = mKeyStore->getDeviceForBlob(keyBlob);
Chad Brubaker154d7692015-03-27 13:59:31 -07002637 keymaster_error_t err = KM_ERROR_UNIMPLEMENTED;
Chad Brubaker06801e02015-03-31 15:13:13 -07002638 std::vector<keymaster_key_param_t> opParams(params.params);
Chad Brubakerad6514a2015-04-09 14:00:26 -07002639 Unique_keymaster_key_characteristics characteristics;
2640 characteristics.reset(new keymaster_key_characteristics_t);
2641 err = getOperationCharacteristics(key, dev, opParams, characteristics.get());
2642 if (err) {
2643 result->resultCode = err;
2644 return;
2645 }
Chad Brubaker0cf34a22015-04-23 11:06:16 -07002646 const hw_auth_token_t* authToken = NULL;
Shawn Willdenb2ffa422015-06-17 12:18:55 -06002647 int32_t authResult = getAuthToken(characteristics.get(), 0, purpose, &authToken,
Chad Brubaker06801e02015-03-31 15:13:13 -07002648 /*failOnTokenMissing*/ false);
Chad Brubaker0cf34a22015-04-23 11:06:16 -07002649 // If per-operation auth is needed we need to begin the operation and
2650 // the client will need to authorize that operation before calling
2651 // update. Any other auth issues stop here.
2652 if (authResult != ::NO_ERROR && authResult != ::OP_AUTH_NEEDED) {
2653 result->resultCode = authResult;
Chad Brubaker06801e02015-03-31 15:13:13 -07002654 return;
2655 }
Chad Brubaker0cf34a22015-04-23 11:06:16 -07002656 addAuthToParams(&opParams, authToken);
Chad Brubaker154d7692015-03-27 13:59:31 -07002657 // Add entropy to the device first.
2658 if (entropy) {
2659 if (dev->add_rng_entropy) {
2660 err = dev->add_rng_entropy(dev, entropy, entropyLength);
2661 } else {
2662 err = KM_ERROR_UNIMPLEMENTED;
2663 }
2664 if (err) {
2665 result->resultCode = err;
2666 return;
2667 }
2668 }
Chad Brubaker57e106d2015-06-01 12:59:00 -07002669 keymaster_key_param_set_t inParams = {opParams.data(), opParams.size()};
Chad Brubaker40a1a9b2015-02-20 14:08:13 -08002670
Shawn Willden9221bff2015-06-18 18:23:54 -06002671 // Create a keyid for this key.
2672 keymaster::km_id_t keyid;
2673 if (!enforcement_policy.CreateKeyId(key, &keyid)) {
2674 ALOGE("Failed to create a key ID for authorization checking.");
2675 result->resultCode = KM_ERROR_UNKNOWN_ERROR;
2676 return;
2677 }
2678
2679 // Check that all key authorization policy requirements are met.
2680 keymaster::AuthorizationSet key_auths(characteristics->hw_enforced);
2681 key_auths.push_back(characteristics->sw_enforced);
2682 keymaster::AuthorizationSet operation_params(inParams);
2683 err = enforcement_policy.AuthorizeOperation(purpose, keyid, key_auths, operation_params,
2684 0 /* op_handle */,
2685 true /* is_begin_operation */);
2686 if (err) {
2687 result->resultCode = err;
2688 return;
2689 }
2690
Alex Klyubin4e88f9b2015-06-23 15:04:05 -07002691 keymaster_key_param_set_t outParams = {NULL, 0};
2692 err = dev->begin(dev, purpose, &key, &inParams, &outParams, &handle);
2693
Chad Brubaker40a1a9b2015-02-20 14:08:13 -08002694 // If there are too many operations abort the oldest operation that was
2695 // started as pruneable and try again.
2696 while (err == KM_ERROR_TOO_MANY_OPERATIONS && mOperationMap.hasPruneableOperation()) {
2697 sp<IBinder> oldest = mOperationMap.getOldestPruneableOperation();
2698 ALOGD("Ran out of operation handles, trying to prune %p", oldest.get());
Alex Klyubin700c1a32015-06-23 15:21:51 -07002699
2700 // We mostly ignore errors from abort() below because all we care about is whether at
2701 // least one pruneable operation has been removed.
2702 size_t op_count_before = mOperationMap.getPruneableOperationCount();
2703 int abort_error = abort(oldest);
2704 size_t op_count_after = mOperationMap.getPruneableOperationCount();
2705 if (op_count_after >= op_count_before) {
2706 // Failed to create space for a new operation. Bail to avoid an infinite loop.
2707 ALOGE("Failed to remove pruneable operation %p, error: %d",
2708 oldest.get(), abort_error);
Chad Brubaker40a1a9b2015-02-20 14:08:13 -08002709 break;
2710 }
Chad Brubaker57e106d2015-06-01 12:59:00 -07002711 err = dev->begin(dev, purpose, &key, &inParams, &outParams, &handle);
Chad Brubaker40a1a9b2015-02-20 14:08:13 -08002712 }
2713 if (err) {
2714 result->resultCode = err;
2715 return;
2716 }
Chad Brubaker40a1a9b2015-02-20 14:08:13 -08002717
Shawn Willden9221bff2015-06-18 18:23:54 -06002718 sp<IBinder> operationToken = mOperationMap.addOperation(handle, keyid, purpose, dev,
2719 appToken, characteristics.release(),
Chad Brubaker06801e02015-03-31 15:13:13 -07002720 pruneable);
Chad Brubaker0cf34a22015-04-23 11:06:16 -07002721 if (authToken) {
2722 mOperationMap.setOperationAuthToken(operationToken, authToken);
2723 }
2724 // Return the authentication lookup result. If this is a per operation
2725 // auth'd key then the resultCode will be ::OP_AUTH_NEEDED and the
2726 // application should get an auth token using the handle before the
2727 // first call to update, which will fail if keystore hasn't received the
2728 // auth token.
2729 result->resultCode = authResult;
Chad Brubaker40a1a9b2015-02-20 14:08:13 -08002730 result->token = operationToken;
Chad Brubakerc3a18562015-03-17 18:21:35 -07002731 result->handle = handle;
Chad Brubaker57e106d2015-06-01 12:59:00 -07002732 if (outParams.params) {
2733 result->outParams.params.assign(outParams.params, outParams.params + outParams.length);
2734 free(outParams.params);
2735 }
Chad Brubaker9899d6b2015-02-03 13:03:00 -08002736 }
2737
Chad Brubaker40a1a9b2015-02-20 14:08:13 -08002738 void update(const sp<IBinder>& token, const KeymasterArguments& params, const uint8_t* data,
2739 size_t dataLength, OperationResult* result) {
Chad Brubaker0cf34a22015-04-23 11:06:16 -07002740 if (!checkAllowedOperationParams(params.params)) {
2741 result->resultCode = KM_ERROR_INVALID_ARGUMENT;
2742 return;
2743 }
Chad Brubaker40a1a9b2015-02-20 14:08:13 -08002744 const keymaster1_device_t* dev;
2745 keymaster_operation_handle_t handle;
Shawn Willdenb2ffa422015-06-17 12:18:55 -06002746 keymaster_purpose_t purpose;
Shawn Willden9221bff2015-06-18 18:23:54 -06002747 keymaster::km_id_t keyid;
2748 const keymaster_key_characteristics_t* characteristics;
2749 if (!mOperationMap.getOperation(token, &handle, &keyid, &purpose, &dev, &characteristics)) {
Chad Brubaker40a1a9b2015-02-20 14:08:13 -08002750 result->resultCode = KM_ERROR_INVALID_OPERATION_HANDLE;
2751 return;
2752 }
Chad Brubaker06801e02015-03-31 15:13:13 -07002753 std::vector<keymaster_key_param_t> opParams(params.params);
Chad Brubaker0cf34a22015-04-23 11:06:16 -07002754 int32_t authResult = addOperationAuthTokenIfNeeded(token, &opParams);
2755 if (authResult != ::NO_ERROR) {
Chad Brubaker06801e02015-03-31 15:13:13 -07002756 result->resultCode = authResult;
2757 return;
2758 }
Chad Brubaker57e106d2015-06-01 12:59:00 -07002759 keymaster_key_param_set_t inParams = {opParams.data(), opParams.size()};
2760 keymaster_blob_t input = {data, dataLength};
2761 size_t consumed = 0;
2762 keymaster_blob_t output = {NULL, 0};
2763 keymaster_key_param_set_t outParams = {NULL, 0};
2764
Shawn Willden9221bff2015-06-18 18:23:54 -06002765 // Check that all key authorization policy requirements are met.
2766 keymaster::AuthorizationSet key_auths(characteristics->hw_enforced);
2767 key_auths.push_back(characteristics->sw_enforced);
2768 keymaster::AuthorizationSet operation_params(inParams);
2769 result->resultCode =
2770 enforcement_policy.AuthorizeOperation(purpose, keyid, key_auths,
2771 operation_params, handle,
2772 false /* is_begin_operation */);
2773 if (result->resultCode) {
2774 return;
2775 }
2776
Chad Brubaker57e106d2015-06-01 12:59:00 -07002777 keymaster_error_t err = dev->update(dev, handle, &inParams, &input, &consumed, &outParams,
2778 &output);
2779 result->data.reset(const_cast<uint8_t*>(output.data));
2780 result->dataLength = output.data_length;
Chad Brubaker40a1a9b2015-02-20 14:08:13 -08002781 result->inputConsumed = consumed;
2782 result->resultCode = err ? (int32_t) err : ::NO_ERROR;
Chad Brubaker57e106d2015-06-01 12:59:00 -07002783 if (outParams.params) {
2784 result->outParams.params.assign(outParams.params, outParams.params + outParams.length);
2785 free(outParams.params);
2786 }
Chad Brubaker9899d6b2015-02-03 13:03:00 -08002787 }
2788
Chad Brubaker40a1a9b2015-02-20 14:08:13 -08002789 void finish(const sp<IBinder>& token, const KeymasterArguments& params,
Chad Brubaker0d33e0b2015-05-29 12:30:19 -07002790 const uint8_t* signature, size_t signatureLength,
2791 const uint8_t* entropy, size_t entropyLength, OperationResult* result) {
Chad Brubaker0cf34a22015-04-23 11:06:16 -07002792 if (!checkAllowedOperationParams(params.params)) {
2793 result->resultCode = KM_ERROR_INVALID_ARGUMENT;
2794 return;
2795 }
Chad Brubaker40a1a9b2015-02-20 14:08:13 -08002796 const keymaster1_device_t* dev;
2797 keymaster_operation_handle_t handle;
Shawn Willdenb2ffa422015-06-17 12:18:55 -06002798 keymaster_purpose_t purpose;
Shawn Willden9221bff2015-06-18 18:23:54 -06002799 keymaster::km_id_t keyid;
2800 const keymaster_key_characteristics_t* characteristics;
2801 if (!mOperationMap.getOperation(token, &handle, &keyid, &purpose, &dev, &characteristics)) {
Chad Brubaker40a1a9b2015-02-20 14:08:13 -08002802 result->resultCode = KM_ERROR_INVALID_OPERATION_HANDLE;
2803 return;
2804 }
Chad Brubaker06801e02015-03-31 15:13:13 -07002805 std::vector<keymaster_key_param_t> opParams(params.params);
Chad Brubaker0cf34a22015-04-23 11:06:16 -07002806 int32_t authResult = addOperationAuthTokenIfNeeded(token, &opParams);
2807 if (authResult != ::NO_ERROR) {
Chad Brubaker06801e02015-03-31 15:13:13 -07002808 result->resultCode = authResult;
2809 return;
2810 }
Chad Brubaker0d33e0b2015-05-29 12:30:19 -07002811 keymaster_error_t err;
2812 if (entropy) {
2813 if (dev->add_rng_entropy) {
2814 err = dev->add_rng_entropy(dev, entropy, entropyLength);
2815 } else {
2816 err = KM_ERROR_UNIMPLEMENTED;
2817 }
2818 if (err) {
2819 result->resultCode = err;
2820 return;
2821 }
2822 }
Chad Brubaker0cf34a22015-04-23 11:06:16 -07002823
Chad Brubaker57e106d2015-06-01 12:59:00 -07002824 keymaster_key_param_set_t inParams = {opParams.data(), opParams.size()};
2825 keymaster_blob_t input = {signature, signatureLength};
2826 keymaster_blob_t output = {NULL, 0};
2827 keymaster_key_param_set_t outParams = {NULL, 0};
Shawn Willden9221bff2015-06-18 18:23:54 -06002828
2829 // Check that all key authorization policy requirements are met.
2830 keymaster::AuthorizationSet key_auths(characteristics->hw_enforced);
2831 key_auths.push_back(characteristics->sw_enforced);
2832 keymaster::AuthorizationSet operation_params(inParams);
2833 err = enforcement_policy.AuthorizeOperation(purpose, keyid, key_auths, operation_params,
2834 handle, false /* is_begin_operation */);
2835 if (err) {
2836 result->resultCode = err;
2837 return;
2838 }
2839
Chad Brubaker0d33e0b2015-05-29 12:30:19 -07002840 err = dev->finish(dev, handle, &inParams, &input, &outParams, &output);
Chad Brubaker40a1a9b2015-02-20 14:08:13 -08002841 // Remove the operation regardless of the result
2842 mOperationMap.removeOperation(token);
Chad Brubaker06801e02015-03-31 15:13:13 -07002843 mAuthTokenTable.MarkCompleted(handle);
Chad Brubaker57e106d2015-06-01 12:59:00 -07002844
2845 result->data.reset(const_cast<uint8_t*>(output.data));
2846 result->dataLength = output.data_length;
Chad Brubaker40a1a9b2015-02-20 14:08:13 -08002847 result->resultCode = err ? (int32_t) err : ::NO_ERROR;
Chad Brubaker57e106d2015-06-01 12:59:00 -07002848 if (outParams.params) {
2849 result->outParams.params.assign(outParams.params, outParams.params + outParams.length);
2850 free(outParams.params);
2851 }
Chad Brubaker9899d6b2015-02-03 13:03:00 -08002852 }
2853
Chad Brubaker40a1a9b2015-02-20 14:08:13 -08002854 int32_t abort(const sp<IBinder>& token) {
2855 const keymaster1_device_t* dev;
2856 keymaster_operation_handle_t handle;
Shawn Willdenb2ffa422015-06-17 12:18:55 -06002857 keymaster_purpose_t purpose;
Shawn Willden9221bff2015-06-18 18:23:54 -06002858 keymaster::km_id_t keyid;
2859 if (!mOperationMap.getOperation(token, &handle, &keyid, &purpose, &dev, NULL)) {
Chad Brubaker40a1a9b2015-02-20 14:08:13 -08002860 return KM_ERROR_INVALID_OPERATION_HANDLE;
2861 }
2862 mOperationMap.removeOperation(token);
Chad Brubaker06801e02015-03-31 15:13:13 -07002863 int32_t rc;
Chad Brubaker40a1a9b2015-02-20 14:08:13 -08002864 if (!dev->abort) {
Chad Brubaker06801e02015-03-31 15:13:13 -07002865 rc = KM_ERROR_UNIMPLEMENTED;
2866 } else {
2867 rc = dev->abort(dev, handle);
Chad Brubaker40a1a9b2015-02-20 14:08:13 -08002868 }
Chad Brubaker06801e02015-03-31 15:13:13 -07002869 mAuthTokenTable.MarkCompleted(handle);
Chad Brubaker40a1a9b2015-02-20 14:08:13 -08002870 if (rc) {
2871 return rc;
2872 }
2873 return ::NO_ERROR;
Chad Brubaker9899d6b2015-02-03 13:03:00 -08002874 }
2875
Chad Brubaker2ed2baa2015-03-21 21:20:10 -07002876 bool isOperationAuthorized(const sp<IBinder>& token) {
2877 const keymaster1_device_t* dev;
2878 keymaster_operation_handle_t handle;
Chad Brubakerad6514a2015-04-09 14:00:26 -07002879 const keymaster_key_characteristics_t* characteristics;
Shawn Willdenb2ffa422015-06-17 12:18:55 -06002880 keymaster_purpose_t purpose;
Shawn Willden9221bff2015-06-18 18:23:54 -06002881 keymaster::km_id_t keyid;
2882 if (!mOperationMap.getOperation(token, &handle, &keyid, &purpose, &dev, &characteristics)) {
Chad Brubaker2ed2baa2015-03-21 21:20:10 -07002883 return false;
2884 }
Chad Brubaker0cf34a22015-04-23 11:06:16 -07002885 const hw_auth_token_t* authToken = NULL;
2886 mOperationMap.getOperationAuthToken(token, &authToken);
Chad Brubaker06801e02015-03-31 15:13:13 -07002887 std::vector<keymaster_key_param_t> ignored;
Chad Brubaker0cf34a22015-04-23 11:06:16 -07002888 int32_t authResult = addOperationAuthTokenIfNeeded(token, &ignored);
2889 return authResult == ::NO_ERROR;
Chad Brubaker2ed2baa2015-03-21 21:20:10 -07002890 }
2891
Chad Brubakerd80c7b42015-03-31 11:04:28 -07002892 int32_t addAuthToken(const uint8_t* token, size_t length) {
Chad Brubaker9489b792015-04-14 11:01:45 -07002893 if (!checkBinderPermission(P_ADD_AUTH)) {
2894 ALOGW("addAuthToken: permission denied for %d",
2895 IPCThreadState::self()->getCallingUid());
Chad Brubakerd80c7b42015-03-31 11:04:28 -07002896 return ::PERMISSION_DENIED;
2897 }
2898 if (length != sizeof(hw_auth_token_t)) {
2899 return KM_ERROR_INVALID_ARGUMENT;
2900 }
2901 hw_auth_token_t* authToken = new hw_auth_token_t;
2902 memcpy(reinterpret_cast<void*>(authToken), token, sizeof(hw_auth_token_t));
2903 // The table takes ownership of authToken.
2904 mAuthTokenTable.AddAuthenticationToken(authToken);
2905 return ::NO_ERROR;
Chad Brubaker2ed2baa2015-03-21 21:20:10 -07002906 }
2907
Kenny Root07438c82012-11-02 15:41:02 -07002908private:
Chad Brubaker9489b792015-04-14 11:01:45 -07002909 static const int32_t UID_SELF = -1;
2910
2911 /**
2912 * Get the effective target uid for a binder operation that takes an
2913 * optional uid as the target.
2914 */
2915 inline uid_t getEffectiveUid(int32_t targetUid) {
2916 if (targetUid == UID_SELF) {
2917 return IPCThreadState::self()->getCallingUid();
2918 }
2919 return static_cast<uid_t>(targetUid);
2920 }
2921
2922 /**
2923 * Check if the caller of the current binder method has the required
2924 * permission and if acting on other uids the grants to do so.
2925 */
2926 inline bool checkBinderPermission(perm_t permission, int32_t targetUid = UID_SELF) {
2927 uid_t callingUid = IPCThreadState::self()->getCallingUid();
2928 pid_t spid = IPCThreadState::self()->getCallingPid();
2929 if (!has_permission(callingUid, permission, spid)) {
2930 ALOGW("permission %s denied for %d", get_perm_label(permission), callingUid);
2931 return false;
2932 }
2933 if (!is_granted_to(callingUid, getEffectiveUid(targetUid))) {
2934 ALOGW("uid %d not granted to act for %d", callingUid, targetUid);
2935 return false;
2936 }
2937 return true;
2938 }
2939
2940 /**
2941 * Check if the caller of the current binder method has the required
Chad Brubakerb37a5232015-05-01 10:21:27 -07002942 * permission and the target uid is the caller or the caller is system.
2943 */
2944 inline bool checkBinderPermissionSelfOrSystem(perm_t permission, int32_t targetUid) {
2945 uid_t callingUid = IPCThreadState::self()->getCallingUid();
2946 pid_t spid = IPCThreadState::self()->getCallingPid();
2947 if (!has_permission(callingUid, permission, spid)) {
2948 ALOGW("permission %s denied for %d", get_perm_label(permission), callingUid);
2949 return false;
2950 }
2951 return getEffectiveUid(targetUid) == callingUid || callingUid == AID_SYSTEM;
2952 }
2953
2954 /**
2955 * Check if the caller of the current binder method has the required
Chad Brubaker9489b792015-04-14 11:01:45 -07002956 * permission or the target of the operation is the caller's uid. This is
2957 * for operation where the permission is only for cross-uid activity and all
2958 * uids are allowed to act on their own (ie: clearing all entries for a
2959 * given uid).
2960 */
2961 inline bool checkBinderPermissionOrSelfTarget(perm_t permission, int32_t targetUid) {
2962 uid_t callingUid = IPCThreadState::self()->getCallingUid();
2963 if (getEffectiveUid(targetUid) == callingUid) {
2964 return true;
2965 } else {
2966 return checkBinderPermission(permission, targetUid);
2967 }
2968 }
2969
2970 /**
2971 * Helper method to check that the caller has the required permission as
2972 * well as the keystore is in the unlocked state if checkUnlocked is true.
2973 *
2974 * Returns NO_ERROR on success, PERMISSION_DENIED on a permission error and
2975 * otherwise the state of keystore when not unlocked and checkUnlocked is
2976 * true.
2977 */
2978 inline int32_t checkBinderPermissionAndKeystoreState(perm_t permission, int32_t targetUid = -1,
2979 bool checkUnlocked = true) {
2980 if (!checkBinderPermission(permission, targetUid)) {
2981 return ::PERMISSION_DENIED;
2982 }
Chad Brubaker72593ee2015-05-12 10:42:00 -07002983 State state = mKeyStore->getState(get_user_id(getEffectiveUid(targetUid)));
Chad Brubaker9489b792015-04-14 11:01:45 -07002984 if (checkUnlocked && !isKeystoreUnlocked(state)) {
2985 return state;
2986 }
2987
2988 return ::NO_ERROR;
2989
2990 }
2991
Kenny Root9d45d1c2013-02-14 10:32:30 -08002992 inline bool isKeystoreUnlocked(State state) {
2993 switch (state) {
2994 case ::STATE_NO_ERROR:
2995 return true;
2996 case ::STATE_UNINITIALIZED:
2997 case ::STATE_LOCKED:
2998 return false;
2999 }
3000 return false;
Kenny Root07438c82012-11-02 15:41:02 -07003001 }
3002
Chad Brubaker67d2a502015-03-11 17:21:18 +00003003 bool isKeyTypeSupported(const keymaster1_device_t* device, keymaster_keypair_t keyType) {
Kenny Root1d448c02013-11-21 10:36:53 -08003004 const int32_t device_api = device->common.module->module_api_version;
3005 if (device_api == KEYMASTER_MODULE_API_VERSION_0_2) {
3006 switch (keyType) {
3007 case TYPE_RSA:
3008 case TYPE_DSA:
3009 case TYPE_EC:
3010 return true;
3011 default:
3012 return false;
3013 }
3014 } else if (device_api >= KEYMASTER_MODULE_API_VERSION_0_3) {
3015 switch (keyType) {
3016 case TYPE_RSA:
3017 return true;
3018 case TYPE_DSA:
3019 return device->flags & KEYMASTER_SUPPORTS_DSA;
3020 case TYPE_EC:
3021 return device->flags & KEYMASTER_SUPPORTS_EC;
3022 default:
3023 return false;
3024 }
3025 } else {
3026 return keyType == TYPE_RSA;
3027 }
3028 }
3029
Chad Brubaker0cf34a22015-04-23 11:06:16 -07003030 /**
3031 * Check that all keymaster_key_param_t's provided by the application are
3032 * allowed. Any parameter that keystore adds itself should be disallowed here.
3033 */
3034 bool checkAllowedOperationParams(const std::vector<keymaster_key_param_t>& params) {
3035 for (auto param: params) {
3036 switch (param.tag) {
3037 case KM_TAG_AUTH_TOKEN:
3038 return false;
3039 default:
3040 break;
3041 }
3042 }
3043 return true;
3044 }
3045
3046 keymaster_error_t getOperationCharacteristics(const keymaster_key_blob_t& key,
3047 const keymaster1_device_t* dev,
3048 const std::vector<keymaster_key_param_t>& params,
3049 keymaster_key_characteristics_t* out) {
3050 UniquePtr<keymaster_blob_t> appId;
3051 UniquePtr<keymaster_blob_t> appData;
3052 for (auto param : params) {
3053 if (param.tag == KM_TAG_APPLICATION_ID) {
3054 appId.reset(new keymaster_blob_t);
3055 appId->data = param.blob.data;
3056 appId->data_length = param.blob.data_length;
3057 } else if (param.tag == KM_TAG_APPLICATION_DATA) {
3058 appData.reset(new keymaster_blob_t);
3059 appData->data = param.blob.data;
3060 appData->data_length = param.blob.data_length;
3061 }
3062 }
3063 keymaster_key_characteristics_t* result = NULL;
3064 if (!dev->get_key_characteristics) {
3065 return KM_ERROR_UNIMPLEMENTED;
3066 }
3067 keymaster_error_t error = dev->get_key_characteristics(dev, &key, appId.get(),
3068 appData.get(), &result);
3069 if (result) {
3070 *out = *result;
3071 free(result);
3072 }
3073 return error;
3074 }
3075
3076 /**
3077 * Get the auth token for this operation from the auth token table.
3078 *
3079 * Returns ::NO_ERROR if the auth token was set or none was required.
3080 * ::OP_AUTH_NEEDED if it is a per op authorization, no
3081 * authorization token exists for that operation and
3082 * failOnTokenMissing is false.
3083 * KM_ERROR_KEY_USER_NOT_AUTHENTICATED if there is no valid auth
3084 * token for the operation
3085 */
3086 int32_t getAuthToken(const keymaster_key_characteristics_t* characteristics,
3087 keymaster_operation_handle_t handle,
Shawn Willdenb2ffa422015-06-17 12:18:55 -06003088 keymaster_purpose_t purpose,
Chad Brubaker0cf34a22015-04-23 11:06:16 -07003089 const hw_auth_token_t** authToken,
3090 bool failOnTokenMissing = true) {
3091
3092 std::vector<keymaster_key_param_t> allCharacteristics;
3093 for (size_t i = 0; i < characteristics->sw_enforced.length; i++) {
3094 allCharacteristics.push_back(characteristics->sw_enforced.params[i]);
3095 }
3096 for (size_t i = 0; i < characteristics->hw_enforced.length; i++) {
3097 allCharacteristics.push_back(characteristics->hw_enforced.params[i]);
3098 }
Shawn Willdenb2ffa422015-06-17 12:18:55 -06003099 keymaster::AuthTokenTable::Error err = mAuthTokenTable.FindAuthorization(
3100 allCharacteristics.data(), allCharacteristics.size(), purpose, handle, authToken);
Chad Brubaker0cf34a22015-04-23 11:06:16 -07003101 switch (err) {
3102 case keymaster::AuthTokenTable::OK:
3103 case keymaster::AuthTokenTable::AUTH_NOT_REQUIRED:
3104 return ::NO_ERROR;
3105 case keymaster::AuthTokenTable::AUTH_TOKEN_NOT_FOUND:
3106 case keymaster::AuthTokenTable::AUTH_TOKEN_EXPIRED:
3107 case keymaster::AuthTokenTable::AUTH_TOKEN_WRONG_SID:
3108 return KM_ERROR_KEY_USER_NOT_AUTHENTICATED;
3109 case keymaster::AuthTokenTable::OP_HANDLE_REQUIRED:
3110 return failOnTokenMissing ? (int32_t) KM_ERROR_KEY_USER_NOT_AUTHENTICATED :
3111 (int32_t) ::OP_AUTH_NEEDED;
3112 default:
3113 ALOGE("Unexpected FindAuthorization return value %d", err);
3114 return KM_ERROR_INVALID_ARGUMENT;
3115 }
3116 }
3117
3118 inline void addAuthToParams(std::vector<keymaster_key_param_t>* params,
3119 const hw_auth_token_t* token) {
3120 if (token) {
3121 params->push_back(keymaster_param_blob(KM_TAG_AUTH_TOKEN,
3122 reinterpret_cast<const uint8_t*>(token),
3123 sizeof(hw_auth_token_t)));
3124 }
3125 }
3126
3127 /**
3128 * Add the auth token for the operation to the param list if the operation
3129 * requires authorization. Uses the cached result in the OperationMap if available
3130 * otherwise gets the token from the AuthTokenTable and caches the result.
3131 *
3132 * Returns ::NO_ERROR if the auth token was added or not needed.
3133 * KM_ERROR_KEY_USER_NOT_AUTHENTICATED if the operation is not
3134 * authenticated.
3135 * KM_ERROR_INVALID_OPERATION_HANDLE if token is not a valid
3136 * operation token.
3137 */
3138 int32_t addOperationAuthTokenIfNeeded(sp<IBinder> token,
3139 std::vector<keymaster_key_param_t>* params) {
3140 const hw_auth_token_t* authToken = NULL;
Chad Brubaker7169a842015-04-29 19:58:34 -07003141 mOperationMap.getOperationAuthToken(token, &authToken);
3142 if (!authToken) {
Chad Brubaker0cf34a22015-04-23 11:06:16 -07003143 const keymaster1_device_t* dev;
3144 keymaster_operation_handle_t handle;
3145 const keymaster_key_characteristics_t* characteristics = NULL;
Shawn Willdenb2ffa422015-06-17 12:18:55 -06003146 keymaster_purpose_t purpose;
Shawn Willden9221bff2015-06-18 18:23:54 -06003147 keymaster::km_id_t keyid;
3148 if (!mOperationMap.getOperation(token, &handle, &keyid, &purpose, &dev,
3149 &characteristics)) {
Chad Brubaker0cf34a22015-04-23 11:06:16 -07003150 return KM_ERROR_INVALID_OPERATION_HANDLE;
3151 }
Shawn Willdenb2ffa422015-06-17 12:18:55 -06003152 int32_t result = getAuthToken(characteristics, handle, purpose, &authToken);
Chad Brubaker0cf34a22015-04-23 11:06:16 -07003153 if (result != ::NO_ERROR) {
3154 return result;
3155 }
3156 if (authToken) {
3157 mOperationMap.setOperationAuthToken(token, authToken);
3158 }
3159 }
3160 addAuthToParams(params, authToken);
3161 return ::NO_ERROR;
3162 }
3163
Chad Brubaker3a7d9e62015-06-04 15:01:46 -07003164 /**
3165 * Translate a result value to a legacy return value. All keystore errors are
3166 * preserved and keymaster errors become SYSTEM_ERRORs
3167 */
3168 inline int32_t translateResultToLegacyResult(int32_t result) {
3169 if (result > 0) {
3170 return result;
3171 }
3172 return ::SYSTEM_ERROR;
3173 }
3174
Chad Brubaker3a7d9e62015-06-04 15:01:46 -07003175 keymaster_key_param_t* getKeyAlgorithm(keymaster_key_characteristics_t* characteristics) {
3176 for (size_t i = 0; i < characteristics->hw_enforced.length; i++) {
3177 if (characteristics->hw_enforced.params[i].tag == KM_TAG_ALGORITHM) {
3178 return &characteristics->hw_enforced.params[i];
3179 }
3180 }
3181 for (size_t i = 0; i < characteristics->sw_enforced.length; i++) {
3182 if (characteristics->sw_enforced.params[i].tag == KM_TAG_ALGORITHM) {
3183 return &characteristics->sw_enforced.params[i];
3184 }
3185 }
3186 return NULL;
3187 }
3188
3189 void addLegacyBeginParams(const String16& name, std::vector<keymaster_key_param_t>& params) {
3190 // All legacy keys are DIGEST_NONE/PAD_NONE.
3191 params.push_back(keymaster_param_enum(KM_TAG_DIGEST, KM_DIGEST_NONE));
3192 params.push_back(keymaster_param_enum(KM_TAG_PADDING, KM_PAD_NONE));
3193
3194 // Look up the algorithm of the key.
3195 KeyCharacteristics characteristics;
3196 int32_t rc = getKeyCharacteristics(name, NULL, NULL, &characteristics);
3197 if (rc != ::NO_ERROR) {
3198 ALOGE("Failed to get key characteristics");
3199 return;
3200 }
3201 keymaster_key_param_t* algorithm = getKeyAlgorithm(&characteristics.characteristics);
3202 if (!algorithm) {
3203 ALOGE("getKeyCharacteristics did not include KM_TAG_ALGORITHM");
3204 return;
3205 }
3206 params.push_back(*algorithm);
3207 }
3208
3209 int32_t doLegacySignVerify(const String16& name, const uint8_t* data, size_t length,
3210 uint8_t** out, size_t* outLength, const uint8_t* signature,
3211 size_t signatureLength, keymaster_purpose_t purpose) {
3212
Chad Brubaker3a7d9e62015-06-04 15:01:46 -07003213 std::basic_stringstream<uint8_t> outBuffer;
3214 OperationResult result;
3215 KeymasterArguments inArgs;
3216 addLegacyBeginParams(name, inArgs.params);
3217 sp<IBinder> appToken(new BBinder);
3218 sp<IBinder> token;
3219
3220 begin(appToken, name, purpose, true, inArgs, NULL, 0, &result);
3221 if (result.resultCode != ResponseCode::NO_ERROR) {
Chad Brubakerdf705172015-06-17 20:17:51 -07003222 if (result.resultCode == ::KEY_NOT_FOUND) {
3223 ALOGW("Key not found");
3224 } else {
3225 ALOGW("Error in begin: %d", result.resultCode);
3226 }
Chad Brubaker3a7d9e62015-06-04 15:01:46 -07003227 return translateResultToLegacyResult(result.resultCode);
3228 }
3229 inArgs.params.clear();
3230 token = result.token;
3231 size_t consumed = 0;
3232 size_t lastConsumed = 0;
3233 do {
3234 update(token, inArgs, data + consumed, length - consumed, &result);
3235 if (result.resultCode != ResponseCode::NO_ERROR) {
3236 ALOGW("Error in update: %d", result.resultCode);
3237 return translateResultToLegacyResult(result.resultCode);
3238 }
3239 if (out) {
3240 outBuffer.write(result.data.get(), result.dataLength);
3241 }
3242 lastConsumed = result.inputConsumed;
3243 consumed += lastConsumed;
3244 } while (consumed < length && lastConsumed > 0);
3245
3246 if (consumed != length) {
3247 ALOGW("Not all data consumed. Consumed %zu of %zu", consumed, length);
3248 return ::SYSTEM_ERROR;
3249 }
3250
3251 finish(token, inArgs, signature, signatureLength, NULL, 0, &result);
3252 if (result.resultCode != ResponseCode::NO_ERROR) {
3253 ALOGW("Error in finish: %d", result.resultCode);
3254 return translateResultToLegacyResult(result.resultCode);
3255 }
3256 if (out) {
3257 outBuffer.write(result.data.get(), result.dataLength);
3258 }
3259
3260 if (out) {
3261 auto buf = outBuffer.str();
3262 *out = new uint8_t[buf.size()];
3263 memcpy(*out, buf.c_str(), buf.size());
3264 *outLength = buf.size();
3265 }
3266
3267 return ::NO_ERROR;
3268 }
3269
Kenny Root07438c82012-11-02 15:41:02 -07003270 ::KeyStore* mKeyStore;
Chad Brubaker40a1a9b2015-02-20 14:08:13 -08003271 OperationMap mOperationMap;
Chad Brubakerd80c7b42015-03-31 11:04:28 -07003272 keymaster::AuthTokenTable mAuthTokenTable;
Shawn Willden9221bff2015-06-18 18:23:54 -06003273 KeystoreKeymasterEnforcement enforcement_policy;
Kenny Root07438c82012-11-02 15:41:02 -07003274};
3275
3276}; // namespace android
Kenny Roota91203b2012-02-15 15:00:46 -08003277
3278int main(int argc, char* argv[]) {
Kenny Roota91203b2012-02-15 15:00:46 -08003279 if (argc < 2) {
3280 ALOGE("A directory must be specified!");
3281 return 1;
3282 }
3283 if (chdir(argv[1]) == -1) {
3284 ALOGE("chdir: %s: %s", argv[1], strerror(errno));
3285 return 1;
3286 }
3287
3288 Entropy entropy;
3289 if (!entropy.open()) {
3290 return 1;
3291 }
Kenny Root70e3a862012-02-15 17:20:23 -08003292
Chad Brubakerbd07a232015-06-01 10:44:27 -07003293 keymaster1_device_t* dev;
Kenny Root70e3a862012-02-15 17:20:23 -08003294 if (keymaster_device_initialize(&dev)) {
3295 ALOGE("keystore keymaster could not be initialized; exiting");
3296 return 1;
3297 }
3298
Chad Brubaker67d2a502015-03-11 17:21:18 +00003299 keymaster1_device_t* fallback;
Chad Brubakerfc18edc2015-01-12 15:17:18 -08003300 if (fallback_keymaster_device_initialize(&fallback)) {
3301 ALOGE("software keymaster could not be initialized; exiting");
3302 return 1;
3303 }
3304
Riley Spahneaabae92014-06-30 12:39:52 -07003305 ks_is_selinux_enabled = is_selinux_enabled();
3306 if (ks_is_selinux_enabled) {
3307 union selinux_callback cb;
3308 cb.func_log = selinux_log_callback;
3309 selinux_set_callback(SELINUX_CB_LOG, cb);
3310 if (getcon(&tctx) != 0) {
3311 ALOGE("SELinux: Could not acquire target context. Aborting keystore.\n");
3312 return -1;
3313 }
3314 } else {
3315 ALOGI("SELinux: Keystore SELinux is disabled.\n");
3316 }
3317
Chad Brubakerbd07a232015-06-01 10:44:27 -07003318 KeyStore keyStore(&entropy, dev, fallback);
Kenny Root655b9582013-04-04 08:37:42 -07003319 keyStore.initialize();
Kenny Root07438c82012-11-02 15:41:02 -07003320 android::sp<android::IServiceManager> sm = android::defaultServiceManager();
3321 android::sp<android::KeyStoreProxy> proxy = new android::KeyStoreProxy(&keyStore);
3322 android::status_t ret = sm->addService(android::String16("android.security.keystore"), proxy);
3323 if (ret != android::OK) {
3324 ALOGE("Couldn't register binder service!");
3325 return -1;
Kenny Roota91203b2012-02-15 15:00:46 -08003326 }
Kenny Root07438c82012-11-02 15:41:02 -07003327
3328 /*
3329 * We're the only thread in existence, so we're just going to process
3330 * Binder transaction as a single-threaded program.
3331 */
3332 android::IPCThreadState::self()->joinThreadPool();
Kenny Root70e3a862012-02-15 17:20:23 -08003333
3334 keymaster_device_release(dev);
Kenny Roota91203b2012-02-15 15:00:46 -08003335 return 1;
3336}