blob: 1a929bdc19a2e83c8ec398fe4d04d4a3fd79c5f3 [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 Willden76193b02015-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 Willden76193b02015-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 Willden76193b02015-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 Willden76193b02015-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 Willden76193b02015-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 Willden76193b02015-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 Willden76193b02015-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 Willden76193b02015-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 Willden76193b02015-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 Willden76193b02015-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
William Robertse46b8552015-10-02 08:19:52 -0700333struct audit_data {
334 pid_t pid;
335 uid_t uid;
336};
337
Riley Spahneaabae92014-06-30 12:39:52 -0700338static char *tctx;
339static int ks_is_selinux_enabled;
340
341static const char *get_perm_label(perm_t perm) {
342 unsigned int index = ffs(perm);
343 if (index > 0 && index <= (sizeof(perm_labels) / sizeof(perm_labels[0]))) {
344 return perm_labels[index - 1];
345 } else {
346 ALOGE("Keystore: Failed to retrieve permission label.\n");
347 abort();
348 }
349}
350
Kenny Root655b9582013-04-04 08:37:42 -0700351/**
352 * Returns the app ID (in the Android multi-user sense) for the current
353 * UNIX UID.
354 */
355static uid_t get_app_id(uid_t uid) {
356 return uid % AID_USER;
357}
358
359/**
360 * Returns the user ID (in the Android multi-user sense) for the current
361 * UNIX UID.
362 */
363static uid_t get_user_id(uid_t uid) {
364 return uid / AID_USER;
365}
366
William Robertse46b8552015-10-02 08:19:52 -0700367static int audit_callback(void *data, security_class_t /* cls */, char *buf, size_t len)
368{
369 struct audit_data *ad = reinterpret_cast<struct audit_data *>(data);
370 if (!ad) {
371 ALOGE("No keystore audit data");
372 return 0;
373 }
374
375 snprintf(buf, len, "pid=%d uid=%d", ad->pid, ad->uid);
376 return 0;
377}
378
379static bool keystore_selinux_check_access(uid_t uid, perm_t perm, pid_t spid) {
Riley Spahneaabae92014-06-30 12:39:52 -0700380 if (!ks_is_selinux_enabled) {
381 return true;
382 }
Nick Kralevich66dbf672014-06-30 17:09:14 +0000383
William Robertse46b8552015-10-02 08:19:52 -0700384 audit_data ad;
Riley Spahneaabae92014-06-30 12:39:52 -0700385 char *sctx = NULL;
386 const char *selinux_class = "keystore_key";
387 const char *str_perm = get_perm_label(perm);
388
389 if (!str_perm) {
390 return false;
391 }
392
393 if (getpidcon(spid, &sctx) != 0) {
394 ALOGE("SELinux: Failed to get source pid context.\n");
395 return false;
396 }
397
William Robertse46b8552015-10-02 08:19:52 -0700398 ad.pid = spid;
399 ad.uid = uid;
400
Riley Spahneaabae92014-06-30 12:39:52 -0700401 bool allowed = selinux_check_access(sctx, tctx, selinux_class, str_perm,
William Robertse46b8552015-10-02 08:19:52 -0700402 reinterpret_cast<void *>(&ad)) == 0;
Riley Spahneaabae92014-06-30 12:39:52 -0700403 freecon(sctx);
404 return allowed;
405}
406
407static bool has_permission(uid_t uid, perm_t perm, pid_t spid) {
Kenny Root655b9582013-04-04 08:37:42 -0700408 // All system users are equivalent for multi-user support.
409 if (get_app_id(uid) == AID_SYSTEM) {
410 uid = AID_SYSTEM;
411 }
412
Kenny Root07438c82012-11-02 15:41:02 -0700413 for (size_t i = 0; i < sizeof(user_perms)/sizeof(user_perms[0]); i++) {
414 struct user_perm user = user_perms[i];
415 if (user.uid == uid) {
Riley Spahneaabae92014-06-30 12:39:52 -0700416 return (user.perms & perm) &&
417 keystore_selinux_check_access(uid, perm, spid);
Kenny Root07438c82012-11-02 15:41:02 -0700418 }
419 }
420
Riley Spahneaabae92014-06-30 12:39:52 -0700421 return (DEFAULT_PERMS & perm) &&
422 keystore_selinux_check_access(uid, perm, spid);
Kenny Root07438c82012-11-02 15:41:02 -0700423}
424
Kenny Root49468902013-03-19 13:41:33 -0700425/**
426 * Returns the UID that the callingUid should act as. This is here for
427 * legacy support of the WiFi and VPN systems and should be removed
428 * when WiFi can operate in its own namespace.
429 */
Kenny Root07438c82012-11-02 15:41:02 -0700430static uid_t get_keystore_euid(uid_t uid) {
431 for (size_t i = 0; i < sizeof(user_euids)/sizeof(user_euids[0]); i++) {
432 struct user_euid user = user_euids[i];
433 if (user.uid == uid) {
434 return user.euid;
435 }
436 }
437
438 return uid;
439}
440
Kenny Root49468902013-03-19 13:41:33 -0700441/**
442 * Returns true if the callingUid is allowed to interact in the targetUid's
443 * namespace.
444 */
445static bool is_granted_to(uid_t callingUid, uid_t targetUid) {
Chad Brubaker9489b792015-04-14 11:01:45 -0700446 if (callingUid == targetUid) {
447 return true;
448 }
Kenny Root49468902013-03-19 13:41:33 -0700449 for (size_t i = 0; i < sizeof(user_euids)/sizeof(user_euids[0]); i++) {
450 struct user_euid user = user_euids[i];
451 if (user.euid == callingUid && user.uid == targetUid) {
452 return true;
453 }
454 }
455
456 return false;
457}
458
Kenny Roota91203b2012-02-15 15:00:46 -0800459/* Here is the encoding of keys. This is necessary in order to allow arbitrary
460 * characters in keys. Characters in [0-~] are not encoded. Others are encoded
461 * into two bytes. The first byte is one of [+-.] which represents the first
462 * two bits of the character. The second byte encodes the rest of the bits into
463 * [0-o]. Therefore in the worst case the length of a key gets doubled. Note
464 * that Base64 cannot be used here due to the need of prefix match on keys. */
465
Kenny Root655b9582013-04-04 08:37:42 -0700466static size_t encode_key_length(const android::String8& keyName) {
467 const uint8_t* in = reinterpret_cast<const uint8_t*>(keyName.string());
468 size_t length = keyName.length();
469 for (int i = length; i > 0; --i, ++in) {
470 if (*in < '0' || *in > '~') {
471 ++length;
472 }
473 }
474 return length;
475}
476
Kenny Root07438c82012-11-02 15:41:02 -0700477static int encode_key(char* out, const android::String8& keyName) {
478 const uint8_t* in = reinterpret_cast<const uint8_t*>(keyName.string());
479 size_t length = keyName.length();
Kenny Roota91203b2012-02-15 15:00:46 -0800480 for (int i = length; i > 0; --i, ++in, ++out) {
Kenny Root655b9582013-04-04 08:37:42 -0700481 if (*in < '0' || *in > '~') {
Kenny Roota91203b2012-02-15 15:00:46 -0800482 *out = '+' + (*in >> 6);
483 *++out = '0' + (*in & 0x3F);
484 ++length;
Kenny Root655b9582013-04-04 08:37:42 -0700485 } else {
486 *out = *in;
Kenny Roota91203b2012-02-15 15:00:46 -0800487 }
488 }
489 *out = '\0';
Kenny Root70e3a862012-02-15 17:20:23 -0800490 return length;
491}
492
Kenny Root07438c82012-11-02 15:41:02 -0700493/*
494 * Converts from the "escaped" format on disk to actual name.
495 * This will be smaller than the input string.
496 *
497 * Characters that should combine with the next at the end will be truncated.
498 */
499static size_t decode_key_length(const char* in, size_t length) {
500 size_t outLength = 0;
501
502 for (const char* end = in + length; in < end; in++) {
503 /* This combines with the next character. */
504 if (*in < '0' || *in > '~') {
505 continue;
506 }
507
508 outLength++;
509 }
510 return outLength;
511}
512
513static void decode_key(char* out, const char* in, size_t length) {
514 for (const char* end = in + length; in < end; in++) {
515 if (*in < '0' || *in > '~') {
516 /* Truncate combining characters at the end. */
517 if (in + 1 >= end) {
518 break;
519 }
520
521 *out = (*in++ - '+') << 6;
522 *out++ |= (*in - '0') & 0x3F;
Kenny Roota91203b2012-02-15 15:00:46 -0800523 } else {
Kenny Root07438c82012-11-02 15:41:02 -0700524 *out++ = *in;
Kenny Roota91203b2012-02-15 15:00:46 -0800525 }
526 }
527 *out = '\0';
Kenny Roota91203b2012-02-15 15:00:46 -0800528}
529
530static size_t readFully(int fd, uint8_t* data, size_t size) {
531 size_t remaining = size;
532 while (remaining > 0) {
Kenny Root150ca932012-11-14 14:29:02 -0800533 ssize_t n = TEMP_FAILURE_RETRY(read(fd, data, remaining));
Kenny Root5281edb2012-11-21 15:14:04 -0800534 if (n <= 0) {
Kenny Root150ca932012-11-14 14:29:02 -0800535 return size - remaining;
Kenny Roota91203b2012-02-15 15:00:46 -0800536 }
537 data += n;
538 remaining -= n;
539 }
540 return size;
541}
542
543static size_t writeFully(int fd, uint8_t* data, size_t size) {
544 size_t remaining = size;
545 while (remaining > 0) {
Kenny Root150ca932012-11-14 14:29:02 -0800546 ssize_t n = TEMP_FAILURE_RETRY(write(fd, data, remaining));
547 if (n < 0) {
548 ALOGW("write failed: %s", strerror(errno));
549 return size - remaining;
Kenny Roota91203b2012-02-15 15:00:46 -0800550 }
551 data += n;
552 remaining -= n;
553 }
554 return size;
555}
556
557class Entropy {
558public:
559 Entropy() : mRandom(-1) {}
560 ~Entropy() {
Kenny Root150ca932012-11-14 14:29:02 -0800561 if (mRandom >= 0) {
Kenny Roota91203b2012-02-15 15:00:46 -0800562 close(mRandom);
563 }
564 }
565
566 bool open() {
567 const char* randomDevice = "/dev/urandom";
Kenny Root150ca932012-11-14 14:29:02 -0800568 mRandom = TEMP_FAILURE_RETRY(::open(randomDevice, O_RDONLY));
569 if (mRandom < 0) {
Kenny Roota91203b2012-02-15 15:00:46 -0800570 ALOGE("open: %s: %s", randomDevice, strerror(errno));
571 return false;
572 }
573 return true;
574 }
575
Kenny Root51878182012-03-13 12:53:19 -0700576 bool generate_random_data(uint8_t* data, size_t size) const {
Kenny Roota91203b2012-02-15 15:00:46 -0800577 return (readFully(mRandom, data, size) == size);
578 }
579
580private:
581 int mRandom;
582};
583
584/* Here is the file format. There are two parts in blob.value, the secret and
585 * the description. The secret is stored in ciphertext, and its original size
586 * can be found in blob.length. The description is stored after the secret in
587 * plaintext, and its size is specified in blob.info. The total size of the two
Kenny Root822c3a92012-03-23 16:34:39 -0700588 * parts must be no more than VALUE_SIZE bytes. The first field is the version,
Kenny Rootf9119d62013-04-03 09:22:15 -0700589 * the second is the blob's type, and the third byte is flags. Fields other
Kenny Roota91203b2012-02-15 15:00:46 -0800590 * than blob.info, blob.length, and blob.value are modified by encryptBlob()
591 * and decryptBlob(). Thus they should not be accessed from outside. */
592
Kenny Root822c3a92012-03-23 16:34:39 -0700593/* ** Note to future implementors of encryption: **
594 * Currently this is the construction:
595 * metadata || Enc(MD5(data) || data)
596 *
597 * This should be the construction used for encrypting if re-implementing:
598 *
599 * Derive independent keys for encryption and MAC:
600 * Kenc = AES_encrypt(masterKey, "Encrypt")
601 * Kmac = AES_encrypt(masterKey, "MAC")
602 *
603 * Store this:
604 * metadata || AES_CTR_encrypt(Kenc, rand_IV, data) ||
605 * HMAC(Kmac, metadata || Enc(data))
606 */
Kenny Roota91203b2012-02-15 15:00:46 -0800607struct __attribute__((packed)) blob {
Kenny Root822c3a92012-03-23 16:34:39 -0700608 uint8_t version;
609 uint8_t type;
Kenny Rootf9119d62013-04-03 09:22:15 -0700610 uint8_t flags;
Kenny Roota91203b2012-02-15 15:00:46 -0800611 uint8_t info;
612 uint8_t vector[AES_BLOCK_SIZE];
Kenny Root822c3a92012-03-23 16:34:39 -0700613 uint8_t encrypted[0]; // Marks offset to encrypted data.
Kenny Roota91203b2012-02-15 15:00:46 -0800614 uint8_t digest[MD5_DIGEST_LENGTH];
Kenny Root822c3a92012-03-23 16:34:39 -0700615 uint8_t digested[0]; // Marks offset to digested data.
Kenny Roota91203b2012-02-15 15:00:46 -0800616 int32_t length; // in network byte order when encrypted
617 uint8_t value[VALUE_SIZE + AES_BLOCK_SIZE];
618};
619
Kenny Root822c3a92012-03-23 16:34:39 -0700620typedef enum {
Kenny Rootd53bc922013-03-21 14:10:15 -0700621 TYPE_ANY = 0, // meta type that matches anything
Kenny Root822c3a92012-03-23 16:34:39 -0700622 TYPE_GENERIC = 1,
623 TYPE_MASTER_KEY = 2,
624 TYPE_KEY_PAIR = 3,
Chad Brubaker17d68b92015-02-05 22:04:16 -0800625 TYPE_KEYMASTER_10 = 4,
Kenny Root822c3a92012-03-23 16:34:39 -0700626} BlobType;
627
Kenny Rootf9119d62013-04-03 09:22:15 -0700628static const uint8_t CURRENT_BLOB_VERSION = 2;
Kenny Root822c3a92012-03-23 16:34:39 -0700629
Kenny Roota91203b2012-02-15 15:00:46 -0800630class Blob {
631public:
Chad Brubaker803f37f2015-07-29 13:53:36 -0700632 Blob(const uint8_t* value, size_t valueLength, const uint8_t* info, uint8_t infoLength,
Kenny Root07438c82012-11-02 15:41:02 -0700633 BlobType type) {
Alex Klyubin1773b442015-02-20 12:33:33 -0800634 memset(&mBlob, 0, sizeof(mBlob));
Chad Brubaker54b1e9a2015-08-12 13:40:31 -0700635 if (valueLength > VALUE_SIZE) {
636 valueLength = VALUE_SIZE;
Chad Brubaker803f37f2015-07-29 13:53:36 -0700637 ALOGW("Provided blob length too large");
638 }
Chad Brubaker54b1e9a2015-08-12 13:40:31 -0700639 if (infoLength + valueLength > VALUE_SIZE) {
640 infoLength = VALUE_SIZE - valueLength;
Chad Brubaker803f37f2015-07-29 13:53:36 -0700641 ALOGW("Provided info length too large");
642 }
Kenny Roota91203b2012-02-15 15:00:46 -0800643 mBlob.length = valueLength;
644 memcpy(mBlob.value, value, valueLength);
645
646 mBlob.info = infoLength;
647 memcpy(mBlob.value + valueLength, info, infoLength);
Kenny Root822c3a92012-03-23 16:34:39 -0700648
Kenny Root07438c82012-11-02 15:41:02 -0700649 mBlob.version = CURRENT_BLOB_VERSION;
Kenny Root822c3a92012-03-23 16:34:39 -0700650 mBlob.type = uint8_t(type);
Kenny Rootf9119d62013-04-03 09:22:15 -0700651
Kenny Rootee8068b2013-10-07 09:49:15 -0700652 if (type == TYPE_MASTER_KEY) {
653 mBlob.flags = KEYSTORE_FLAG_ENCRYPTED;
654 } else {
655 mBlob.flags = KEYSTORE_FLAG_NONE;
656 }
Kenny Roota91203b2012-02-15 15:00:46 -0800657 }
658
659 Blob(blob b) {
660 mBlob = b;
661 }
662
Alex Klyubin1773b442015-02-20 12:33:33 -0800663 Blob() {
664 memset(&mBlob, 0, sizeof(mBlob));
665 }
Kenny Roota91203b2012-02-15 15:00:46 -0800666
Kenny Root51878182012-03-13 12:53:19 -0700667 const uint8_t* getValue() const {
Kenny Roota91203b2012-02-15 15:00:46 -0800668 return mBlob.value;
669 }
670
Kenny Root51878182012-03-13 12:53:19 -0700671 int32_t getLength() const {
Kenny Roota91203b2012-02-15 15:00:46 -0800672 return mBlob.length;
673 }
674
Kenny Root51878182012-03-13 12:53:19 -0700675 const uint8_t* getInfo() const {
676 return mBlob.value + mBlob.length;
677 }
678
679 uint8_t getInfoLength() const {
Kenny Roota91203b2012-02-15 15:00:46 -0800680 return mBlob.info;
681 }
682
Kenny Root822c3a92012-03-23 16:34:39 -0700683 uint8_t getVersion() const {
684 return mBlob.version;
685 }
686
Kenny Rootf9119d62013-04-03 09:22:15 -0700687 bool isEncrypted() const {
688 if (mBlob.version < 2) {
689 return true;
690 }
691
692 return mBlob.flags & KEYSTORE_FLAG_ENCRYPTED;
693 }
694
695 void setEncrypted(bool encrypted) {
696 if (encrypted) {
697 mBlob.flags |= KEYSTORE_FLAG_ENCRYPTED;
698 } else {
699 mBlob.flags &= ~KEYSTORE_FLAG_ENCRYPTED;
700 }
701 }
702
Kenny Root17208e02013-09-04 13:56:03 -0700703 bool isFallback() const {
704 return mBlob.flags & KEYSTORE_FLAG_FALLBACK;
705 }
706
707 void setFallback(bool fallback) {
708 if (fallback) {
709 mBlob.flags |= KEYSTORE_FLAG_FALLBACK;
710 } else {
711 mBlob.flags &= ~KEYSTORE_FLAG_FALLBACK;
712 }
713 }
714
Kenny Root822c3a92012-03-23 16:34:39 -0700715 void setVersion(uint8_t version) {
716 mBlob.version = version;
717 }
718
719 BlobType getType() const {
720 return BlobType(mBlob.type);
721 }
722
723 void setType(BlobType type) {
724 mBlob.type = uint8_t(type);
725 }
726
Kenny Rootf9119d62013-04-03 09:22:15 -0700727 ResponseCode writeBlob(const char* filename, AES_KEY *aes_key, State state, Entropy* entropy) {
728 ALOGV("writing blob %s", filename);
729 if (isEncrypted()) {
730 if (state != STATE_NO_ERROR) {
731 ALOGD("couldn't insert encrypted blob while not unlocked");
732 return LOCKED;
733 }
734
735 if (!entropy->generate_random_data(mBlob.vector, AES_BLOCK_SIZE)) {
736 ALOGW("Could not read random data for: %s", filename);
737 return SYSTEM_ERROR;
738 }
Kenny Roota91203b2012-02-15 15:00:46 -0800739 }
740
741 // data includes the value and the value's length
742 size_t dataLength = mBlob.length + sizeof(mBlob.length);
743 // pad data to the AES_BLOCK_SIZE
744 size_t digestedLength = ((dataLength + AES_BLOCK_SIZE - 1)
745 / AES_BLOCK_SIZE * AES_BLOCK_SIZE);
746 // encrypted data includes the digest value
747 size_t encryptedLength = digestedLength + MD5_DIGEST_LENGTH;
748 // move info after space for padding
749 memmove(&mBlob.encrypted[encryptedLength], &mBlob.value[mBlob.length], mBlob.info);
750 // zero padding area
751 memset(mBlob.value + mBlob.length, 0, digestedLength - dataLength);
752
753 mBlob.length = htonl(mBlob.length);
Kenny Roota91203b2012-02-15 15:00:46 -0800754
Kenny Rootf9119d62013-04-03 09:22:15 -0700755 if (isEncrypted()) {
756 MD5(mBlob.digested, digestedLength, mBlob.digest);
Kenny Roota91203b2012-02-15 15:00:46 -0800757
Kenny Rootf9119d62013-04-03 09:22:15 -0700758 uint8_t vector[AES_BLOCK_SIZE];
759 memcpy(vector, mBlob.vector, AES_BLOCK_SIZE);
760 AES_cbc_encrypt(mBlob.encrypted, mBlob.encrypted, encryptedLength,
761 aes_key, vector, AES_ENCRYPT);
762 }
763
Kenny Roota91203b2012-02-15 15:00:46 -0800764 size_t headerLength = (mBlob.encrypted - (uint8_t*) &mBlob);
765 size_t fileLength = encryptedLength + headerLength + mBlob.info;
766
767 const char* tmpFileName = ".tmp";
Kenny Root150ca932012-11-14 14:29:02 -0800768 int out = TEMP_FAILURE_RETRY(open(tmpFileName,
769 O_WRONLY | O_TRUNC | O_CREAT, S_IRUSR | S_IWUSR));
770 if (out < 0) {
771 ALOGW("could not open file: %s: %s", tmpFileName, strerror(errno));
Kenny Roota91203b2012-02-15 15:00:46 -0800772 return SYSTEM_ERROR;
773 }
774 size_t writtenBytes = writeFully(out, (uint8_t*) &mBlob, fileLength);
775 if (close(out) != 0) {
776 return SYSTEM_ERROR;
777 }
778 if (writtenBytes != fileLength) {
Kenny Root150ca932012-11-14 14:29:02 -0800779 ALOGW("blob not fully written %zu != %zu", writtenBytes, fileLength);
Kenny Roota91203b2012-02-15 15:00:46 -0800780 unlink(tmpFileName);
781 return SYSTEM_ERROR;
782 }
Kenny Root150ca932012-11-14 14:29:02 -0800783 if (rename(tmpFileName, filename) == -1) {
784 ALOGW("could not rename blob to %s: %s", filename, strerror(errno));
785 return SYSTEM_ERROR;
786 }
787 return NO_ERROR;
Kenny Roota91203b2012-02-15 15:00:46 -0800788 }
789
Kenny Rootf9119d62013-04-03 09:22:15 -0700790 ResponseCode readBlob(const char* filename, AES_KEY *aes_key, State state) {
791 ALOGV("reading blob %s", filename);
Kenny Root150ca932012-11-14 14:29:02 -0800792 int in = TEMP_FAILURE_RETRY(open(filename, O_RDONLY));
793 if (in < 0) {
Kenny Roota91203b2012-02-15 15:00:46 -0800794 return (errno == ENOENT) ? KEY_NOT_FOUND : SYSTEM_ERROR;
795 }
796 // fileLength may be less than sizeof(mBlob) since the in
797 // memory version has extra padding to tolerate rounding up to
798 // the AES_BLOCK_SIZE
799 size_t fileLength = readFully(in, (uint8_t*) &mBlob, sizeof(mBlob));
800 if (close(in) != 0) {
801 return SYSTEM_ERROR;
802 }
Kenny Rootf9119d62013-04-03 09:22:15 -0700803
Chad Brubakera9a17ee2015-07-17 13:43:24 -0700804 if (fileLength == 0) {
805 return VALUE_CORRUPTED;
806 }
807
Kenny Rootf9119d62013-04-03 09:22:15 -0700808 if (isEncrypted() && (state != STATE_NO_ERROR)) {
809 return LOCKED;
810 }
811
Kenny Roota91203b2012-02-15 15:00:46 -0800812 size_t headerLength = (mBlob.encrypted - (uint8_t*) &mBlob);
813 if (fileLength < headerLength) {
814 return VALUE_CORRUPTED;
815 }
816
817 ssize_t encryptedLength = fileLength - (headerLength + mBlob.info);
Kenny Rootf9119d62013-04-03 09:22:15 -0700818 if (encryptedLength < 0) {
Kenny Roota91203b2012-02-15 15:00:46 -0800819 return VALUE_CORRUPTED;
820 }
Kenny Rootf9119d62013-04-03 09:22:15 -0700821
822 ssize_t digestedLength;
823 if (isEncrypted()) {
824 if (encryptedLength % AES_BLOCK_SIZE != 0) {
825 return VALUE_CORRUPTED;
826 }
827
828 AES_cbc_encrypt(mBlob.encrypted, mBlob.encrypted, encryptedLength, aes_key,
829 mBlob.vector, AES_DECRYPT);
830 digestedLength = encryptedLength - MD5_DIGEST_LENGTH;
831 uint8_t computedDigest[MD5_DIGEST_LENGTH];
832 MD5(mBlob.digested, digestedLength, computedDigest);
833 if (memcmp(mBlob.digest, computedDigest, MD5_DIGEST_LENGTH) != 0) {
834 return VALUE_CORRUPTED;
835 }
836 } else {
837 digestedLength = encryptedLength;
Kenny Roota91203b2012-02-15 15:00:46 -0800838 }
839
840 ssize_t maxValueLength = digestedLength - sizeof(mBlob.length);
841 mBlob.length = ntohl(mBlob.length);
842 if (mBlob.length < 0 || mBlob.length > maxValueLength) {
843 return VALUE_CORRUPTED;
844 }
845 if (mBlob.info != 0) {
846 // move info from after padding to after data
847 memmove(&mBlob.value[mBlob.length], &mBlob.value[maxValueLength], mBlob.info);
848 }
Kenny Root07438c82012-11-02 15:41:02 -0700849 return ::NO_ERROR;
Kenny Roota91203b2012-02-15 15:00:46 -0800850 }
851
852private:
853 struct blob mBlob;
854};
855
Kenny Root655b9582013-04-04 08:37:42 -0700856class UserState {
Kenny Roota91203b2012-02-15 15:00:46 -0800857public:
Kenny Root655b9582013-04-04 08:37:42 -0700858 UserState(uid_t userId) : mUserId(userId), mRetry(MAX_RETRY) {
859 asprintf(&mUserDir, "user_%u", mUserId);
860 asprintf(&mMasterKeyFile, "%s/.masterkey", mUserDir);
861 }
862
863 ~UserState() {
864 free(mUserDir);
865 free(mMasterKeyFile);
866 }
867
868 bool initialize() {
869 if ((mkdir(mUserDir, S_IRUSR | S_IWUSR | S_IXUSR) < 0) && (errno != EEXIST)) {
870 ALOGE("Could not create directory '%s'", mUserDir);
871 return false;
872 }
873
874 if (access(mMasterKeyFile, R_OK) == 0) {
Kenny Roota91203b2012-02-15 15:00:46 -0800875 setState(STATE_LOCKED);
876 } else {
877 setState(STATE_UNINITIALIZED);
878 }
Kenny Root70e3a862012-02-15 17:20:23 -0800879
Kenny Root655b9582013-04-04 08:37:42 -0700880 return true;
881 }
882
883 uid_t getUserId() const {
884 return mUserId;
885 }
886
887 const char* getUserDirName() const {
888 return mUserDir;
889 }
890
891 const char* getMasterKeyFileName() const {
892 return mMasterKeyFile;
893 }
894
895 void setState(State state) {
896 mState = state;
897 if (mState == STATE_NO_ERROR || mState == STATE_UNINITIALIZED) {
898 mRetry = MAX_RETRY;
899 }
Kenny Roota91203b2012-02-15 15:00:46 -0800900 }
901
Kenny Root51878182012-03-13 12:53:19 -0700902 State getState() const {
Kenny Roota91203b2012-02-15 15:00:46 -0800903 return mState;
904 }
905
Kenny Root51878182012-03-13 12:53:19 -0700906 int8_t getRetry() const {
Kenny Roota91203b2012-02-15 15:00:46 -0800907 return mRetry;
908 }
909
Kenny Root655b9582013-04-04 08:37:42 -0700910 void zeroizeMasterKeysInMemory() {
911 memset(mMasterKey, 0, sizeof(mMasterKey));
912 memset(mSalt, 0, sizeof(mSalt));
913 memset(&mMasterKeyEncryption, 0, sizeof(mMasterKeyEncryption));
914 memset(&mMasterKeyDecryption, 0, sizeof(mMasterKeyDecryption));
Kenny Root70e3a862012-02-15 17:20:23 -0800915 }
916
Chad Brubaker96d6d782015-05-07 10:19:40 -0700917 bool deleteMasterKey() {
918 setState(STATE_UNINITIALIZED);
919 zeroizeMasterKeysInMemory();
920 return unlink(mMasterKeyFile) == 0 || errno == ENOENT;
921 }
922
Kenny Root655b9582013-04-04 08:37:42 -0700923 ResponseCode initialize(const android::String8& pw, Entropy* entropy) {
924 if (!generateMasterKey(entropy)) {
Kenny Roota91203b2012-02-15 15:00:46 -0800925 return SYSTEM_ERROR;
926 }
Kenny Root655b9582013-04-04 08:37:42 -0700927 ResponseCode response = writeMasterKey(pw, entropy);
Kenny Roota91203b2012-02-15 15:00:46 -0800928 if (response != NO_ERROR) {
929 return response;
930 }
931 setupMasterKeys();
Kenny Root07438c82012-11-02 15:41:02 -0700932 return ::NO_ERROR;
Kenny Roota91203b2012-02-15 15:00:46 -0800933 }
934
Robin Lee4e865752014-08-19 17:37:55 +0100935 ResponseCode copyMasterKey(UserState* src) {
936 if (mState != STATE_UNINITIALIZED) {
937 return ::SYSTEM_ERROR;
938 }
939 if (src->getState() != STATE_NO_ERROR) {
940 return ::SYSTEM_ERROR;
941 }
942 memcpy(mMasterKey, src->mMasterKey, MASTER_KEY_SIZE_BYTES);
943 setupMasterKeys();
944 return ::NO_ERROR;
945 }
946
Kenny Root655b9582013-04-04 08:37:42 -0700947 ResponseCode writeMasterKey(const android::String8& pw, Entropy* entropy) {
Kenny Roota91203b2012-02-15 15:00:46 -0800948 uint8_t passwordKey[MASTER_KEY_SIZE_BYTES];
949 generateKeyFromPassword(passwordKey, MASTER_KEY_SIZE_BYTES, pw, mSalt);
950 AES_KEY passwordAesKey;
951 AES_set_encrypt_key(passwordKey, MASTER_KEY_SIZE_BITS, &passwordAesKey);
Kenny Root822c3a92012-03-23 16:34:39 -0700952 Blob masterKeyBlob(mMasterKey, sizeof(mMasterKey), mSalt, sizeof(mSalt), TYPE_MASTER_KEY);
Kenny Rootf9119d62013-04-03 09:22:15 -0700953 return masterKeyBlob.writeBlob(mMasterKeyFile, &passwordAesKey, STATE_NO_ERROR, entropy);
Kenny Roota91203b2012-02-15 15:00:46 -0800954 }
955
Kenny Root655b9582013-04-04 08:37:42 -0700956 ResponseCode readMasterKey(const android::String8& pw, Entropy* entropy) {
957 int in = TEMP_FAILURE_RETRY(open(mMasterKeyFile, O_RDONLY));
Kenny Root150ca932012-11-14 14:29:02 -0800958 if (in < 0) {
Kenny Roota91203b2012-02-15 15:00:46 -0800959 return SYSTEM_ERROR;
960 }
961
962 // we read the raw blob to just to get the salt to generate
963 // the AES key, then we create the Blob to use with decryptBlob
964 blob rawBlob;
965 size_t length = readFully(in, (uint8_t*) &rawBlob, sizeof(rawBlob));
966 if (close(in) != 0) {
967 return SYSTEM_ERROR;
968 }
969 // find salt at EOF if present, otherwise we have an old file
970 uint8_t* salt;
971 if (length > SALT_SIZE && rawBlob.info == SALT_SIZE) {
972 salt = (uint8_t*) &rawBlob + length - SALT_SIZE;
973 } else {
974 salt = NULL;
975 }
976 uint8_t passwordKey[MASTER_KEY_SIZE_BYTES];
977 generateKeyFromPassword(passwordKey, MASTER_KEY_SIZE_BYTES, pw, salt);
978 AES_KEY passwordAesKey;
979 AES_set_decrypt_key(passwordKey, MASTER_KEY_SIZE_BITS, &passwordAesKey);
980 Blob masterKeyBlob(rawBlob);
Kenny Rootf9119d62013-04-03 09:22:15 -0700981 ResponseCode response = masterKeyBlob.readBlob(mMasterKeyFile, &passwordAesKey,
982 STATE_NO_ERROR);
Kenny Roota91203b2012-02-15 15:00:46 -0800983 if (response == SYSTEM_ERROR) {
Kenny Rootf9119d62013-04-03 09:22:15 -0700984 return response;
Kenny Roota91203b2012-02-15 15:00:46 -0800985 }
986 if (response == NO_ERROR && masterKeyBlob.getLength() == MASTER_KEY_SIZE_BYTES) {
987 // if salt was missing, generate one and write a new master key file with the salt.
988 if (salt == NULL) {
Kenny Root655b9582013-04-04 08:37:42 -0700989 if (!generateSalt(entropy)) {
Kenny Roota91203b2012-02-15 15:00:46 -0800990 return SYSTEM_ERROR;
991 }
Kenny Root655b9582013-04-04 08:37:42 -0700992 response = writeMasterKey(pw, entropy);
Kenny Roota91203b2012-02-15 15:00:46 -0800993 }
994 if (response == NO_ERROR) {
995 memcpy(mMasterKey, masterKeyBlob.getValue(), MASTER_KEY_SIZE_BYTES);
996 setupMasterKeys();
997 }
998 return response;
999 }
1000 if (mRetry <= 0) {
1001 reset();
1002 return UNINITIALIZED;
1003 }
1004 --mRetry;
1005 switch (mRetry) {
1006 case 0: return WRONG_PASSWORD_0;
1007 case 1: return WRONG_PASSWORD_1;
1008 case 2: return WRONG_PASSWORD_2;
1009 case 3: return WRONG_PASSWORD_3;
1010 default: return WRONG_PASSWORD_3;
1011 }
1012 }
1013
Kenny Root655b9582013-04-04 08:37:42 -07001014 AES_KEY* getEncryptionKey() {
1015 return &mMasterKeyEncryption;
1016 }
1017
1018 AES_KEY* getDecryptionKey() {
1019 return &mMasterKeyDecryption;
1020 }
1021
Kenny Roota91203b2012-02-15 15:00:46 -08001022 bool reset() {
Kenny Root655b9582013-04-04 08:37:42 -07001023 DIR* dir = opendir(getUserDirName());
Kenny Roota91203b2012-02-15 15:00:46 -08001024 if (!dir) {
Chad Brubaker96d6d782015-05-07 10:19:40 -07001025 // If the directory doesn't exist then nothing to do.
1026 if (errno == ENOENT) {
1027 return true;
1028 }
Kenny Root655b9582013-04-04 08:37:42 -07001029 ALOGW("couldn't open user directory: %s", strerror(errno));
Kenny Roota91203b2012-02-15 15:00:46 -08001030 return false;
1031 }
Kenny Root655b9582013-04-04 08:37:42 -07001032
1033 struct dirent* file;
Kenny Roota91203b2012-02-15 15:00:46 -08001034 while ((file = readdir(dir)) != NULL) {
Chad Brubaker96d6d782015-05-07 10:19:40 -07001035 // skip . and ..
1036 if (!strcmp(".", file->d_name) || !strcmp("..", file->d_name)) {
Kenny Root655b9582013-04-04 08:37:42 -07001037 continue;
1038 }
1039
1040 unlinkat(dirfd(dir), file->d_name, 0);
Kenny Roota91203b2012-02-15 15:00:46 -08001041 }
1042 closedir(dir);
1043 return true;
1044 }
1045
Kenny Root655b9582013-04-04 08:37:42 -07001046private:
1047 static const int MASTER_KEY_SIZE_BYTES = 16;
1048 static const int MASTER_KEY_SIZE_BITS = MASTER_KEY_SIZE_BYTES * 8;
1049
1050 static const int MAX_RETRY = 4;
1051 static const size_t SALT_SIZE = 16;
1052
1053 void generateKeyFromPassword(uint8_t* key, ssize_t keySize, const android::String8& pw,
1054 uint8_t* salt) {
1055 size_t saltSize;
1056 if (salt != NULL) {
1057 saltSize = SALT_SIZE;
1058 } else {
1059 // pre-gingerbread used this hardwired salt, readMasterKey will rewrite these when found
1060 salt = (uint8_t*) "keystore";
1061 // sizeof = 9, not strlen = 8
1062 saltSize = sizeof("keystore");
1063 }
1064
1065 PKCS5_PBKDF2_HMAC_SHA1(reinterpret_cast<const char*>(pw.string()), pw.length(), salt,
1066 saltSize, 8192, keySize, key);
1067 }
1068
1069 bool generateSalt(Entropy* entropy) {
1070 return entropy->generate_random_data(mSalt, sizeof(mSalt));
1071 }
1072
1073 bool generateMasterKey(Entropy* entropy) {
1074 if (!entropy->generate_random_data(mMasterKey, sizeof(mMasterKey))) {
1075 return false;
1076 }
1077 if (!generateSalt(entropy)) {
1078 return false;
1079 }
1080 return true;
1081 }
1082
1083 void setupMasterKeys() {
1084 AES_set_encrypt_key(mMasterKey, MASTER_KEY_SIZE_BITS, &mMasterKeyEncryption);
1085 AES_set_decrypt_key(mMasterKey, MASTER_KEY_SIZE_BITS, &mMasterKeyDecryption);
1086 setState(STATE_NO_ERROR);
1087 }
1088
1089 uid_t mUserId;
1090
1091 char* mUserDir;
1092 char* mMasterKeyFile;
1093
1094 State mState;
1095 int8_t mRetry;
1096
1097 uint8_t mMasterKey[MASTER_KEY_SIZE_BYTES];
1098 uint8_t mSalt[SALT_SIZE];
1099
1100 AES_KEY mMasterKeyEncryption;
1101 AES_KEY mMasterKeyDecryption;
1102};
1103
1104typedef struct {
1105 uint32_t uid;
1106 const uint8_t* filename;
1107} grant_t;
1108
1109class KeyStore {
1110public:
Chad Brubaker67d2a502015-03-11 17:21:18 +00001111 KeyStore(Entropy* entropy, keymaster1_device_t* device, keymaster1_device_t* fallback)
Kenny Root655b9582013-04-04 08:37:42 -07001112 : mEntropy(entropy)
1113 , mDevice(device)
Chad Brubakerfc18edc2015-01-12 15:17:18 -08001114 , mFallbackDevice(fallback)
Kenny Root655b9582013-04-04 08:37:42 -07001115 {
1116 memset(&mMetaData, '\0', sizeof(mMetaData));
1117 }
1118
1119 ~KeyStore() {
1120 for (android::Vector<grant_t*>::iterator it(mGrants.begin());
1121 it != mGrants.end(); it++) {
1122 delete *it;
Kenny Root655b9582013-04-04 08:37:42 -07001123 }
haitao fangc35d4eb2013-12-06 11:34:49 +08001124 mGrants.clear();
Kenny Root655b9582013-04-04 08:37:42 -07001125
1126 for (android::Vector<UserState*>::iterator it(mMasterKeys.begin());
1127 it != mMasterKeys.end(); it++) {
1128 delete *it;
Kenny Root655b9582013-04-04 08:37:42 -07001129 }
haitao fangc35d4eb2013-12-06 11:34:49 +08001130 mMasterKeys.clear();
Kenny Root655b9582013-04-04 08:37:42 -07001131 }
1132
Chad Brubaker67d2a502015-03-11 17:21:18 +00001133 /**
1134 * Depending on the hardware keymaster version is this may return a
1135 * keymaster0_device_t* cast to a keymaster1_device_t*. All methods from
1136 * keymaster0 are safe to call, calls to keymaster1_device_t methods should
1137 * be guarded by a check on the device's version.
1138 */
1139 keymaster1_device_t *getDevice() const {
Kenny Root655b9582013-04-04 08:37:42 -07001140 return mDevice;
1141 }
1142
Chad Brubaker67d2a502015-03-11 17:21:18 +00001143 keymaster1_device_t *getFallbackDevice() const {
Chad Brubakerfc18edc2015-01-12 15:17:18 -08001144 return mFallbackDevice;
1145 }
1146
Chad Brubaker67d2a502015-03-11 17:21:18 +00001147 keymaster1_device_t *getDeviceForBlob(const Blob& blob) const {
Chad Brubakerfc18edc2015-01-12 15:17:18 -08001148 return blob.isFallback() ? mFallbackDevice: mDevice;
1149 }
1150
Kenny Root655b9582013-04-04 08:37:42 -07001151 ResponseCode initialize() {
1152 readMetaData();
1153 if (upgradeKeystore()) {
1154 writeMetaData();
1155 }
1156
1157 return ::NO_ERROR;
1158 }
1159
Chad Brubaker72593ee2015-05-12 10:42:00 -07001160 State getState(uid_t userId) {
1161 return getUserState(userId)->getState();
Kenny Root655b9582013-04-04 08:37:42 -07001162 }
1163
Chad Brubaker72593ee2015-05-12 10:42:00 -07001164 ResponseCode initializeUser(const android::String8& pw, uid_t userId) {
1165 UserState* userState = getUserState(userId);
Kenny Root655b9582013-04-04 08:37:42 -07001166 return userState->initialize(pw, mEntropy);
1167 }
1168
Chad Brubaker72593ee2015-05-12 10:42:00 -07001169 ResponseCode copyMasterKey(uid_t srcUser, uid_t dstUser) {
1170 UserState *userState = getUserState(dstUser);
1171 UserState *initState = getUserState(srcUser);
Robin Lee4e865752014-08-19 17:37:55 +01001172 return userState->copyMasterKey(initState);
1173 }
1174
Chad Brubaker72593ee2015-05-12 10:42:00 -07001175 ResponseCode writeMasterKey(const android::String8& pw, uid_t userId) {
1176 UserState* userState = getUserState(userId);
Kenny Root655b9582013-04-04 08:37:42 -07001177 return userState->writeMasterKey(pw, mEntropy);
1178 }
1179
Chad Brubaker72593ee2015-05-12 10:42:00 -07001180 ResponseCode readMasterKey(const android::String8& pw, uid_t userId) {
1181 UserState* userState = getUserState(userId);
Kenny Root655b9582013-04-04 08:37:42 -07001182 return userState->readMasterKey(pw, mEntropy);
1183 }
1184
1185 android::String8 getKeyName(const android::String8& keyName) {
Douglas Leunga77e8092013-06-13 16:34:43 -07001186 char encoded[encode_key_length(keyName) + 1]; // add 1 for null char
Kenny Root655b9582013-04-04 08:37:42 -07001187 encode_key(encoded, keyName);
1188 return android::String8(encoded);
1189 }
1190
1191 android::String8 getKeyNameForUid(const android::String8& keyName, uid_t uid) {
Douglas Leunga77e8092013-06-13 16:34:43 -07001192 char encoded[encode_key_length(keyName) + 1]; // add 1 for null char
Kenny Root655b9582013-04-04 08:37:42 -07001193 encode_key(encoded, keyName);
1194 return android::String8::format("%u_%s", uid, encoded);
1195 }
1196
1197 android::String8 getKeyNameForUidWithDir(const android::String8& keyName, uid_t uid) {
Douglas Leunga77e8092013-06-13 16:34:43 -07001198 char encoded[encode_key_length(keyName) + 1]; // add 1 for null char
Kenny Root655b9582013-04-04 08:37:42 -07001199 encode_key(encoded, keyName);
Chad Brubaker72593ee2015-05-12 10:42:00 -07001200 return android::String8::format("%s/%u_%s", getUserStateByUid(uid)->getUserDirName(), uid,
Kenny Root655b9582013-04-04 08:37:42 -07001201 encoded);
1202 }
1203
Chad Brubaker96d6d782015-05-07 10:19:40 -07001204 /*
1205 * Delete entries owned by userId. If keepUnencryptedEntries is true
1206 * then only encrypted entries will be removed, otherwise all entries will
1207 * be removed.
1208 */
1209 void resetUser(uid_t userId, bool keepUnenryptedEntries) {
Robin Lee4b84fdc2014-09-24 11:56:57 +01001210 android::String8 prefix("");
1211 android::Vector<android::String16> aliases;
Chad Brubaker72593ee2015-05-12 10:42:00 -07001212 UserState* userState = getUserState(userId);
Chad Brubakere6c3bfa2015-05-12 15:18:26 -07001213 if (list(prefix, &aliases, userId) != ::NO_ERROR) {
Chad Brubaker96d6d782015-05-07 10:19:40 -07001214 return;
1215 }
Robin Lee4b84fdc2014-09-24 11:56:57 +01001216 for (uint32_t i = 0; i < aliases.size(); i++) {
1217 android::String8 filename(aliases[i]);
1218 filename = android::String8::format("%s/%s", userState->getUserDirName(),
Chad Brubaker96d6d782015-05-07 10:19:40 -07001219 getKeyName(filename).string());
1220 bool shouldDelete = true;
1221 if (keepUnenryptedEntries) {
1222 Blob blob;
Chad Brubaker72593ee2015-05-12 10:42:00 -07001223 ResponseCode rc = get(filename, &blob, ::TYPE_ANY, userId);
Robin Lee4b84fdc2014-09-24 11:56:57 +01001224
Chad Brubaker96d6d782015-05-07 10:19:40 -07001225 /* get can fail if the blob is encrypted and the state is
1226 * not unlocked, only skip deleting blobs that were loaded and
1227 * who are not encrypted. If there are blobs we fail to read for
1228 * other reasons err on the safe side and delete them since we
1229 * can't tell if they're encrypted.
1230 */
1231 shouldDelete = !(rc == ::NO_ERROR && !blob.isEncrypted());
1232 }
1233 if (shouldDelete) {
Chad Brubaker72593ee2015-05-12 10:42:00 -07001234 del(filename, ::TYPE_ANY, userId);
Chad Brubaker96d6d782015-05-07 10:19:40 -07001235 }
1236 }
1237 if (!userState->deleteMasterKey()) {
1238 ALOGE("Failed to delete user %d's master key", userId);
1239 }
1240 if (!keepUnenryptedEntries) {
1241 if(!userState->reset()) {
1242 ALOGE("Failed to remove user %d's directory", userId);
1243 }
1244 }
Kenny Root655b9582013-04-04 08:37:42 -07001245 }
1246
Chad Brubaker72593ee2015-05-12 10:42:00 -07001247 bool isEmpty(uid_t userId) const {
1248 const UserState* userState = getUserState(userId);
Chad Brubaker96d6d782015-05-07 10:19:40 -07001249 if (userState == NULL) {
Kenny Root655b9582013-04-04 08:37:42 -07001250 return true;
1251 }
1252
1253 DIR* dir = opendir(userState->getUserDirName());
Kenny Roota91203b2012-02-15 15:00:46 -08001254 if (!dir) {
1255 return true;
1256 }
Kenny Root31e27462014-09-10 11:28:03 -07001257
Kenny Roota91203b2012-02-15 15:00:46 -08001258 bool result = true;
Kenny Root31e27462014-09-10 11:28:03 -07001259 struct dirent* file;
Kenny Roota91203b2012-02-15 15:00:46 -08001260 while ((file = readdir(dir)) != NULL) {
Kenny Root655b9582013-04-04 08:37:42 -07001261 // We only care about files.
1262 if (file->d_type != DT_REG) {
1263 continue;
1264 }
1265
1266 // Skip anything that starts with a "."
1267 if (file->d_name[0] == '.') {
1268 continue;
1269 }
1270
Kenny Root31e27462014-09-10 11:28:03 -07001271 result = false;
1272 break;
Kenny Roota91203b2012-02-15 15:00:46 -08001273 }
1274 closedir(dir);
1275 return result;
1276 }
1277
Chad Brubaker72593ee2015-05-12 10:42:00 -07001278 void lock(uid_t userId) {
1279 UserState* userState = getUserState(userId);
Kenny Root655b9582013-04-04 08:37:42 -07001280 userState->zeroizeMasterKeysInMemory();
1281 userState->setState(STATE_LOCKED);
Kenny Roota91203b2012-02-15 15:00:46 -08001282 }
1283
Chad Brubaker72593ee2015-05-12 10:42:00 -07001284 ResponseCode get(const char* filename, Blob* keyBlob, const BlobType type, uid_t userId) {
1285 UserState* userState = getUserState(userId);
Kenny Rootf9119d62013-04-03 09:22:15 -07001286 ResponseCode rc = keyBlob->readBlob(filename, userState->getDecryptionKey(),
1287 userState->getState());
Kenny Root822c3a92012-03-23 16:34:39 -07001288 if (rc != NO_ERROR) {
1289 return rc;
1290 }
1291
1292 const uint8_t version = keyBlob->getVersion();
Kenny Root07438c82012-11-02 15:41:02 -07001293 if (version < CURRENT_BLOB_VERSION) {
Kenny Rootcfeae072013-04-04 08:39:57 -07001294 /* If we upgrade the key, we need to write it to disk again. Then
1295 * it must be read it again since the blob is encrypted each time
1296 * it's written.
1297 */
Chad Brubaker72593ee2015-05-12 10:42:00 -07001298 if (upgradeBlob(filename, keyBlob, version, type, userId)) {
1299 if ((rc = this->put(filename, keyBlob, userId)) != NO_ERROR
Kenny Rootf9119d62013-04-03 09:22:15 -07001300 || (rc = keyBlob->readBlob(filename, userState->getDecryptionKey(),
1301 userState->getState())) != NO_ERROR) {
Kenny Rootcfeae072013-04-04 08:39:57 -07001302 return rc;
1303 }
1304 }
Kenny Root822c3a92012-03-23 16:34:39 -07001305 }
1306
Kenny Root17208e02013-09-04 13:56:03 -07001307 /*
1308 * This will upgrade software-backed keys to hardware-backed keys when
1309 * the HAL for the device supports the newer key types.
1310 */
1311 if (rc == NO_ERROR && type == TYPE_KEY_PAIR
1312 && mDevice->common.module->module_api_version >= KEYMASTER_MODULE_API_VERSION_0_2
1313 && keyBlob->isFallback()) {
1314 ResponseCode imported = importKey(keyBlob->getValue(), keyBlob->getLength(), filename,
Chad Brubaker72593ee2015-05-12 10:42:00 -07001315 userId, keyBlob->isEncrypted() ? KEYSTORE_FLAG_ENCRYPTED : KEYSTORE_FLAG_NONE);
Kenny Root17208e02013-09-04 13:56:03 -07001316
1317 // The HAL allowed the import, reget the key to have the "fresh"
1318 // version.
1319 if (imported == NO_ERROR) {
Chad Brubaker72593ee2015-05-12 10:42:00 -07001320 rc = get(filename, keyBlob, TYPE_KEY_PAIR, userId);
Kenny Root17208e02013-09-04 13:56:03 -07001321 }
1322 }
1323
Chad Brubaker3a7d9e62015-06-04 15:01:46 -07001324 // Keymaster 0.3 keys are valid keymaster 1.0 keys, so silently upgrade.
1325 if (keyBlob->getType() == TYPE_KEY_PAIR) {
Chad Brubaker3cc40122015-06-04 13:49:44 -07001326 keyBlob->setType(TYPE_KEYMASTER_10);
Chad Brubaker3a7d9e62015-06-04 15:01:46 -07001327 rc = this->put(filename, keyBlob, userId);
Chad Brubaker3cc40122015-06-04 13:49:44 -07001328 }
1329
Kenny Rootd53bc922013-03-21 14:10:15 -07001330 if (type != TYPE_ANY && keyBlob->getType() != type) {
Kenny Root822c3a92012-03-23 16:34:39 -07001331 ALOGW("key found but type doesn't match: %d vs %d", keyBlob->getType(), type);
1332 return KEY_NOT_FOUND;
1333 }
1334
1335 return rc;
Kenny Roota91203b2012-02-15 15:00:46 -08001336 }
1337
Chad Brubaker72593ee2015-05-12 10:42:00 -07001338 ResponseCode put(const char* filename, Blob* keyBlob, uid_t userId) {
1339 UserState* userState = getUserState(userId);
Kenny Rootf9119d62013-04-03 09:22:15 -07001340 return keyBlob->writeBlob(filename, userState->getEncryptionKey(), userState->getState(),
1341 mEntropy);
Kenny Roota91203b2012-02-15 15:00:46 -08001342 }
1343
Chad Brubaker72593ee2015-05-12 10:42:00 -07001344 ResponseCode del(const char *filename, const BlobType type, uid_t userId) {
Robin Lee4b84fdc2014-09-24 11:56:57 +01001345 Blob keyBlob;
Chad Brubaker72593ee2015-05-12 10:42:00 -07001346 ResponseCode rc = get(filename, &keyBlob, type, userId);
Chad Brubakera9a17ee2015-07-17 13:43:24 -07001347 if (rc == ::VALUE_CORRUPTED) {
1348 // The file is corrupt, the best we can do is rm it.
1349 return (unlink(filename) && errno != ENOENT) ? ::SYSTEM_ERROR : ::NO_ERROR;
1350 }
Robin Lee4b84fdc2014-09-24 11:56:57 +01001351 if (rc != ::NO_ERROR) {
1352 return rc;
1353 }
1354
1355 if (keyBlob.getType() == ::TYPE_KEY_PAIR) {
Shawn Willden76193b02015-07-28 11:06:00 -06001356 // A device doesn't have to implement delete_key.
1357 if (mDevice->delete_key != NULL && !keyBlob.isFallback()) {
1358 keymaster_key_blob_t blob = {keyBlob.getValue(),
1359 static_cast<size_t>(keyBlob.getLength())};
1360 if (mDevice->delete_key(mDevice, &blob)) {
Robin Lee4b84fdc2014-09-24 11:56:57 +01001361 rc = ::SYSTEM_ERROR;
1362 }
1363 }
1364 }
Chad Brubaker17d68b92015-02-05 22:04:16 -08001365 if (keyBlob.getType() == ::TYPE_KEYMASTER_10) {
1366 keymaster1_device_t* dev = getDeviceForBlob(keyBlob);
1367 if (dev->delete_key) {
1368 keymaster_key_blob_t blob;
1369 blob.key_material = keyBlob.getValue();
1370 blob.key_material_size = keyBlob.getLength();
1371 dev->delete_key(dev, &blob);
1372 }
1373 }
Robin Lee4b84fdc2014-09-24 11:56:57 +01001374 if (rc != ::NO_ERROR) {
1375 return rc;
1376 }
1377
1378 return (unlink(filename) && errno != ENOENT) ? ::SYSTEM_ERROR : ::NO_ERROR;
1379 }
1380
Chad Brubakere6c3bfa2015-05-12 15:18:26 -07001381 ResponseCode list(const android::String8& prefix, android::Vector<android::String16> *matches,
Chad Brubaker72593ee2015-05-12 10:42:00 -07001382 uid_t userId) {
Robin Lee4b84fdc2014-09-24 11:56:57 +01001383
Chad Brubaker72593ee2015-05-12 10:42:00 -07001384 UserState* userState = getUserState(userId);
Robin Lee4b84fdc2014-09-24 11:56:57 +01001385 size_t n = prefix.length();
1386
1387 DIR* dir = opendir(userState->getUserDirName());
1388 if (!dir) {
1389 ALOGW("can't open directory for user: %s", strerror(errno));
1390 return ::SYSTEM_ERROR;
1391 }
1392
1393 struct dirent* file;
1394 while ((file = readdir(dir)) != NULL) {
1395 // We only care about files.
1396 if (file->d_type != DT_REG) {
1397 continue;
1398 }
1399
1400 // Skip anything that starts with a "."
1401 if (file->d_name[0] == '.') {
1402 continue;
1403 }
1404
1405 if (!strncmp(prefix.string(), file->d_name, n)) {
1406 const char* p = &file->d_name[n];
1407 size_t plen = strlen(p);
1408
1409 size_t extra = decode_key_length(p, plen);
1410 char *match = (char*) malloc(extra + 1);
1411 if (match != NULL) {
1412 decode_key(match, p, plen);
1413 matches->push(android::String16(match, extra));
1414 free(match);
1415 } else {
1416 ALOGW("could not allocate match of size %zd", extra);
1417 }
1418 }
1419 }
1420 closedir(dir);
1421 return ::NO_ERROR;
1422 }
1423
Kenny Root07438c82012-11-02 15:41:02 -07001424 void addGrant(const char* filename, uid_t granteeUid) {
Kenny Root655b9582013-04-04 08:37:42 -07001425 const grant_t* existing = getGrant(filename, granteeUid);
1426 if (existing == NULL) {
1427 grant_t* grant = new grant_t;
Kenny Root07438c82012-11-02 15:41:02 -07001428 grant->uid = granteeUid;
Brian Carlstroma8c703d2012-07-17 14:43:46 -07001429 grant->filename = reinterpret_cast<const uint8_t*>(strdup(filename));
Kenny Root655b9582013-04-04 08:37:42 -07001430 mGrants.add(grant);
Kenny Root70e3a862012-02-15 17:20:23 -08001431 }
1432 }
1433
Kenny Root07438c82012-11-02 15:41:02 -07001434 bool removeGrant(const char* filename, uid_t granteeUid) {
Kenny Root655b9582013-04-04 08:37:42 -07001435 for (android::Vector<grant_t*>::iterator it(mGrants.begin());
1436 it != mGrants.end(); it++) {
1437 grant_t* grant = *it;
1438 if (grant->uid == granteeUid
1439 && !strcmp(reinterpret_cast<const char*>(grant->filename), filename)) {
1440 mGrants.erase(it);
1441 return true;
1442 }
Kenny Root70e3a862012-02-15 17:20:23 -08001443 }
Kenny Root70e3a862012-02-15 17:20:23 -08001444 return false;
1445 }
1446
Brian Carlstroma8c703d2012-07-17 14:43:46 -07001447 bool hasGrant(const char* filename, const uid_t uid) const {
1448 return getGrant(filename, uid) != NULL;
Kenny Root70e3a862012-02-15 17:20:23 -08001449 }
1450
Chad Brubaker72593ee2015-05-12 10:42:00 -07001451 ResponseCode importKey(const uint8_t* key, size_t keyLen, const char* filename, uid_t userId,
Kenny Rootf9119d62013-04-03 09:22:15 -07001452 int32_t flags) {
Shawn Willden76193b02015-07-28 11:06:00 -06001453 Unique_PKCS8_PRIV_KEY_INFO pkcs8(d2i_PKCS8_PRIV_KEY_INFO(NULL, &key, keyLen));
1454 if (!pkcs8.get()) {
1455 return ::SYSTEM_ERROR;
1456 }
1457 Unique_EVP_PKEY pkey(EVP_PKCS82PKEY(pkcs8.get()));
1458 if (!pkey.get()) {
1459 return ::SYSTEM_ERROR;
1460 }
1461 int type = EVP_PKEY_type(pkey->type);
1462 android::KeymasterArguments params;
1463 add_legacy_key_authorizations(type, &params.params);
1464 switch (type) {
1465 case EVP_PKEY_RSA:
1466 params.params.push_back(keymaster_param_enum(KM_TAG_ALGORITHM, KM_ALGORITHM_RSA));
1467 break;
1468 case EVP_PKEY_EC:
1469 params.params.push_back(keymaster_param_enum(KM_TAG_ALGORITHM,
1470 KM_ALGORITHM_EC));
1471 break;
1472 default:
1473 ALOGW("Unsupported key type %d", type);
1474 return ::SYSTEM_ERROR;
Kenny Root822c3a92012-03-23 16:34:39 -07001475 }
1476
Shawn Willden76193b02015-07-28 11:06:00 -06001477 std::vector<keymaster_key_param_t> opParams(params.params);
1478 const keymaster_key_param_set_t inParams = {opParams.data(), opParams.size()};
1479 keymaster_blob_t input = {key, keyLen};
1480 keymaster_key_blob_t blob = {nullptr, 0};
Kenny Root17208e02013-09-04 13:56:03 -07001481 bool isFallback = false;
Shawn Willden76193b02015-07-28 11:06:00 -06001482 keymaster_error_t error = mDevice->import_key(mDevice, &inParams, KM_KEY_FORMAT_PKCS8,
1483 &input, &blob, NULL /* characteristics */);
1484 if (error != KM_ERROR_OK){
1485 ALOGE("Keymaster error %d importing key pair, falling back", error);
1486
Kenny Roota39da5a2014-09-25 13:07:24 -07001487 /*
Shawn Willden76193b02015-07-28 11:06:00 -06001488 * There should be no way to get here. Fallback shouldn't ever really happen
1489 * because the main device may be many (SW, KM0/SW hybrid, KM1/SW hybrid), but it must
1490 * provide full support of the API. In any case, we'll do the fallback just for
1491 * consistency... and I suppose to cover for broken HW implementations.
Kenny Roota39da5a2014-09-25 13:07:24 -07001492 */
Shawn Willden76193b02015-07-28 11:06:00 -06001493 error = mFallbackDevice->import_key(mFallbackDevice, &inParams, KM_KEY_FORMAT_PKCS8,
1494 &input, &blob, NULL /* characteristics */);
Kenny Roota39da5a2014-09-25 13:07:24 -07001495 isFallback = true;
Kenny Root17208e02013-09-04 13:56:03 -07001496
Shawn Willden76193b02015-07-28 11:06:00 -06001497 if (error) {
1498 ALOGE("Keymaster error while importing key pair with fallback: %d", error);
Kenny Root17208e02013-09-04 13:56:03 -07001499 return SYSTEM_ERROR;
1500 }
Kenny Root822c3a92012-03-23 16:34:39 -07001501 }
1502
Shawn Willden76193b02015-07-28 11:06:00 -06001503 Blob keyBlob(blob.key_material, blob.key_material_size, NULL, 0, TYPE_KEYMASTER_10);
1504 free(const_cast<uint8_t*>(blob.key_material));
Kenny Root822c3a92012-03-23 16:34:39 -07001505
Kenny Rootf9119d62013-04-03 09:22:15 -07001506 keyBlob.setEncrypted(flags & KEYSTORE_FLAG_ENCRYPTED);
Kenny Root17208e02013-09-04 13:56:03 -07001507 keyBlob.setFallback(isFallback);
Kenny Rootf9119d62013-04-03 09:22:15 -07001508
Chad Brubaker72593ee2015-05-12 10:42:00 -07001509 return put(filename, &keyBlob, userId);
Kenny Root822c3a92012-03-23 16:34:39 -07001510 }
1511
Kenny Root1b0e3932013-09-05 13:06:32 -07001512 bool isHardwareBacked(const android::String16& keyType) const {
1513 if (mDevice == NULL) {
1514 ALOGW("can't get keymaster device");
1515 return false;
1516 }
1517
1518 if (sRSAKeyType == keyType) {
1519 return (mDevice->flags & KEYMASTER_SOFTWARE_ONLY) == 0;
1520 } else {
1521 return (mDevice->flags & KEYMASTER_SOFTWARE_ONLY) == 0
1522 && (mDevice->common.module->module_api_version
1523 >= KEYMASTER_MODULE_API_VERSION_0_2);
1524 }
Kenny Root8ddf35a2013-03-29 11:15:50 -07001525 }
1526
Kenny Root655b9582013-04-04 08:37:42 -07001527 ResponseCode getKeyForName(Blob* keyBlob, const android::String8& keyName, const uid_t uid,
1528 const BlobType type) {
Kenny Root86b16e82013-09-09 11:15:54 -07001529 android::String8 filepath8(getKeyNameForUidWithDir(keyName, uid));
Chad Brubaker72593ee2015-05-12 10:42:00 -07001530 uid_t userId = get_user_id(uid);
Kenny Root655b9582013-04-04 08:37:42 -07001531
Chad Brubaker72593ee2015-05-12 10:42:00 -07001532 ResponseCode responseCode = get(filepath8.string(), keyBlob, type, userId);
Kenny Root655b9582013-04-04 08:37:42 -07001533 if (responseCode == NO_ERROR) {
1534 return responseCode;
1535 }
1536
1537 // If this is one of the legacy UID->UID mappings, use it.
1538 uid_t euid = get_keystore_euid(uid);
1539 if (euid != uid) {
Kenny Root86b16e82013-09-09 11:15:54 -07001540 filepath8 = getKeyNameForUidWithDir(keyName, euid);
Chad Brubaker72593ee2015-05-12 10:42:00 -07001541 responseCode = get(filepath8.string(), keyBlob, type, userId);
Kenny Root655b9582013-04-04 08:37:42 -07001542 if (responseCode == NO_ERROR) {
1543 return responseCode;
1544 }
1545 }
1546
1547 // They might be using a granted key.
Kenny Root86b16e82013-09-09 11:15:54 -07001548 android::String8 filename8 = getKeyName(keyName);
Kenny Root655b9582013-04-04 08:37:42 -07001549 char* end;
Kenny Root86b16e82013-09-09 11:15:54 -07001550 strtoul(filename8.string(), &end, 10);
Kenny Root655b9582013-04-04 08:37:42 -07001551 if (end[0] != '_' || end[1] == 0) {
1552 return KEY_NOT_FOUND;
1553 }
Chad Brubaker72593ee2015-05-12 10:42:00 -07001554 filepath8 = android::String8::format("%s/%s", getUserState(userId)->getUserDirName(),
Kenny Root86b16e82013-09-09 11:15:54 -07001555 filename8.string());
Kenny Root655b9582013-04-04 08:37:42 -07001556 if (!hasGrant(filepath8.string(), uid)) {
1557 return responseCode;
1558 }
1559
1560 // It is a granted key. Try to load it.
Chad Brubaker72593ee2015-05-12 10:42:00 -07001561 return get(filepath8.string(), keyBlob, type, userId);
Kenny Root655b9582013-04-04 08:37:42 -07001562 }
1563
1564 /**
1565 * Returns any existing UserState or creates it if it doesn't exist.
1566 */
Chad Brubaker72593ee2015-05-12 10:42:00 -07001567 UserState* getUserState(uid_t userId) {
Kenny Root655b9582013-04-04 08:37:42 -07001568 for (android::Vector<UserState*>::iterator it(mMasterKeys.begin());
1569 it != mMasterKeys.end(); it++) {
1570 UserState* state = *it;
1571 if (state->getUserId() == userId) {
1572 return state;
1573 }
1574 }
1575
1576 UserState* userState = new UserState(userId);
1577 if (!userState->initialize()) {
1578 /* There's not much we can do if initialization fails. Trying to
1579 * unlock the keystore for that user will fail as well, so any
1580 * subsequent request for this user will just return SYSTEM_ERROR.
1581 */
1582 ALOGE("User initialization failed for %u; subsuquent operations will fail", userId);
1583 }
1584 mMasterKeys.add(userState);
1585 return userState;
1586 }
1587
1588 /**
Chad Brubaker72593ee2015-05-12 10:42:00 -07001589 * Returns any existing UserState or creates it if it doesn't exist.
1590 */
1591 UserState* getUserStateByUid(uid_t uid) {
1592 uid_t userId = get_user_id(uid);
1593 return getUserState(userId);
1594 }
1595
1596 /**
Kenny Root655b9582013-04-04 08:37:42 -07001597 * Returns NULL if the UserState doesn't already exist.
1598 */
Chad Brubaker72593ee2015-05-12 10:42:00 -07001599 const UserState* getUserState(uid_t userId) const {
Kenny Root655b9582013-04-04 08:37:42 -07001600 for (android::Vector<UserState*>::const_iterator it(mMasterKeys.begin());
1601 it != mMasterKeys.end(); it++) {
1602 UserState* state = *it;
1603 if (state->getUserId() == userId) {
1604 return state;
1605 }
1606 }
1607
1608 return NULL;
1609 }
1610
Chad Brubaker72593ee2015-05-12 10:42:00 -07001611 /**
1612 * Returns NULL if the UserState doesn't already exist.
1613 */
1614 const UserState* getUserStateByUid(uid_t uid) const {
1615 uid_t userId = get_user_id(uid);
1616 return getUserState(userId);
1617 }
1618
Kenny Roota91203b2012-02-15 15:00:46 -08001619private:
Kenny Root655b9582013-04-04 08:37:42 -07001620 static const char* sOldMasterKey;
1621 static const char* sMetaDataFile;
Kenny Root1b0e3932013-09-05 13:06:32 -07001622 static const android::String16 sRSAKeyType;
Kenny Roota91203b2012-02-15 15:00:46 -08001623 Entropy* mEntropy;
1624
Chad Brubaker67d2a502015-03-11 17:21:18 +00001625 keymaster1_device_t* mDevice;
1626 keymaster1_device_t* mFallbackDevice;
Kenny Root70e3a862012-02-15 17:20:23 -08001627
Kenny Root655b9582013-04-04 08:37:42 -07001628 android::Vector<UserState*> mMasterKeys;
Kenny Roota91203b2012-02-15 15:00:46 -08001629
Kenny Root655b9582013-04-04 08:37:42 -07001630 android::Vector<grant_t*> mGrants;
Kenny Roota91203b2012-02-15 15:00:46 -08001631
Kenny Root655b9582013-04-04 08:37:42 -07001632 typedef struct {
1633 uint32_t version;
1634 } keystore_metadata_t;
Kenny Roota91203b2012-02-15 15:00:46 -08001635
Kenny Root655b9582013-04-04 08:37:42 -07001636 keystore_metadata_t mMetaData;
Kenny Root70e3a862012-02-15 17:20:23 -08001637
Kenny Root655b9582013-04-04 08:37:42 -07001638 const grant_t* getGrant(const char* filename, uid_t uid) const {
1639 for (android::Vector<grant_t*>::const_iterator it(mGrants.begin());
1640 it != mGrants.end(); it++) {
1641 grant_t* grant = *it;
Kenny Root70e3a862012-02-15 17:20:23 -08001642 if (grant->uid == uid
Kenny Root655b9582013-04-04 08:37:42 -07001643 && !strcmp(reinterpret_cast<const char*>(grant->filename), filename)) {
Kenny Root70e3a862012-02-15 17:20:23 -08001644 return grant;
1645 }
1646 }
Kenny Root70e3a862012-02-15 17:20:23 -08001647 return NULL;
1648 }
1649
Kenny Root822c3a92012-03-23 16:34:39 -07001650 /**
1651 * Upgrade code. This will upgrade the key from the current version
1652 * to whatever is newest.
1653 */
Kenny Root655b9582013-04-04 08:37:42 -07001654 bool upgradeBlob(const char* filename, Blob* blob, const uint8_t oldVersion,
1655 const BlobType type, uid_t uid) {
Kenny Root822c3a92012-03-23 16:34:39 -07001656 bool updated = false;
1657 uint8_t version = oldVersion;
1658
1659 /* From V0 -> V1: All old types were unknown */
1660 if (version == 0) {
1661 ALOGV("upgrading to version 1 and setting type %d", type);
1662
1663 blob->setType(type);
1664 if (type == TYPE_KEY_PAIR) {
Kenny Root655b9582013-04-04 08:37:42 -07001665 importBlobAsKey(blob, filename, uid);
Kenny Root822c3a92012-03-23 16:34:39 -07001666 }
1667 version = 1;
1668 updated = true;
1669 }
1670
Kenny Rootf9119d62013-04-03 09:22:15 -07001671 /* From V1 -> V2: All old keys were encrypted */
1672 if (version == 1) {
1673 ALOGV("upgrading to version 2");
1674
1675 blob->setEncrypted(true);
1676 version = 2;
1677 updated = true;
1678 }
1679
Kenny Root822c3a92012-03-23 16:34:39 -07001680 /*
1681 * If we've updated, set the key blob to the right version
1682 * and write it.
Kenny Rootcfeae072013-04-04 08:39:57 -07001683 */
Kenny Root822c3a92012-03-23 16:34:39 -07001684 if (updated) {
1685 ALOGV("updated and writing file %s", filename);
1686 blob->setVersion(version);
Kenny Root822c3a92012-03-23 16:34:39 -07001687 }
Kenny Rootcfeae072013-04-04 08:39:57 -07001688
1689 return updated;
Kenny Root822c3a92012-03-23 16:34:39 -07001690 }
1691
1692 /**
1693 * Takes a blob that is an PEM-encoded RSA key as a byte array and
1694 * converts it to a DER-encoded PKCS#8 for import into a keymaster.
1695 * Then it overwrites the original blob with the new blob
1696 * format that is returned from the keymaster.
1697 */
Kenny Root655b9582013-04-04 08:37:42 -07001698 ResponseCode importBlobAsKey(Blob* blob, const char* filename, uid_t uid) {
Kenny Root822c3a92012-03-23 16:34:39 -07001699 // We won't even write to the blob directly with this BIO, so const_cast is okay.
1700 Unique_BIO b(BIO_new_mem_buf(const_cast<uint8_t*>(blob->getValue()), blob->getLength()));
1701 if (b.get() == NULL) {
1702 ALOGE("Problem instantiating BIO");
1703 return SYSTEM_ERROR;
1704 }
1705
1706 Unique_EVP_PKEY pkey(PEM_read_bio_PrivateKey(b.get(), NULL, NULL, NULL));
1707 if (pkey.get() == NULL) {
1708 ALOGE("Couldn't read old PEM file");
1709 return SYSTEM_ERROR;
1710 }
1711
1712 Unique_PKCS8_PRIV_KEY_INFO pkcs8(EVP_PKEY2PKCS8(pkey.get()));
1713 int len = i2d_PKCS8_PRIV_KEY_INFO(pkcs8.get(), NULL);
1714 if (len < 0) {
1715 ALOGE("Couldn't measure PKCS#8 length");
1716 return SYSTEM_ERROR;
1717 }
1718
Kenny Root70c98892013-02-07 09:10:36 -08001719 UniquePtr<unsigned char[]> pkcs8key(new unsigned char[len]);
1720 uint8_t* tmp = pkcs8key.get();
Kenny Root822c3a92012-03-23 16:34:39 -07001721 if (i2d_PKCS8_PRIV_KEY_INFO(pkcs8.get(), &tmp) != len) {
1722 ALOGE("Couldn't convert to PKCS#8");
1723 return SYSTEM_ERROR;
1724 }
1725
Chad Brubaker72593ee2015-05-12 10:42:00 -07001726 ResponseCode rc = importKey(pkcs8key.get(), len, filename, get_user_id(uid),
Kenny Rootf9119d62013-04-03 09:22:15 -07001727 blob->isEncrypted() ? KEYSTORE_FLAG_ENCRYPTED : KEYSTORE_FLAG_NONE);
Kenny Root822c3a92012-03-23 16:34:39 -07001728 if (rc != NO_ERROR) {
1729 return rc;
1730 }
1731
Kenny Root655b9582013-04-04 08:37:42 -07001732 return get(filename, blob, TYPE_KEY_PAIR, uid);
1733 }
1734
1735 void readMetaData() {
1736 int in = TEMP_FAILURE_RETRY(open(sMetaDataFile, O_RDONLY));
1737 if (in < 0) {
1738 return;
1739 }
1740 size_t fileLength = readFully(in, (uint8_t*) &mMetaData, sizeof(mMetaData));
1741 if (fileLength != sizeof(mMetaData)) {
1742 ALOGI("Metadata file is %zd bytes (%zd experted); upgrade?", fileLength,
1743 sizeof(mMetaData));
1744 }
1745 close(in);
1746 }
1747
1748 void writeMetaData() {
1749 const char* tmpFileName = ".metadata.tmp";
1750 int out = TEMP_FAILURE_RETRY(open(tmpFileName,
1751 O_WRONLY | O_TRUNC | O_CREAT, S_IRUSR | S_IWUSR));
1752 if (out < 0) {
1753 ALOGE("couldn't write metadata file: %s", strerror(errno));
1754 return;
1755 }
1756 size_t fileLength = writeFully(out, (uint8_t*) &mMetaData, sizeof(mMetaData));
1757 if (fileLength != sizeof(mMetaData)) {
1758 ALOGI("Could only write %zd bytes to metadata file (%zd expected)", fileLength,
1759 sizeof(mMetaData));
1760 }
1761 close(out);
1762 rename(tmpFileName, sMetaDataFile);
1763 }
1764
1765 bool upgradeKeystore() {
1766 bool upgraded = false;
1767
1768 if (mMetaData.version == 0) {
Chad Brubaker72593ee2015-05-12 10:42:00 -07001769 UserState* userState = getUserStateByUid(0);
Kenny Root655b9582013-04-04 08:37:42 -07001770
1771 // Initialize first so the directory is made.
1772 userState->initialize();
1773
1774 // Migrate the old .masterkey file to user 0.
1775 if (access(sOldMasterKey, R_OK) == 0) {
1776 if (rename(sOldMasterKey, userState->getMasterKeyFileName()) < 0) {
1777 ALOGE("couldn't migrate old masterkey: %s", strerror(errno));
1778 return false;
1779 }
1780 }
1781
1782 // Initialize again in case we had a key.
1783 userState->initialize();
1784
1785 // Try to migrate existing keys.
1786 DIR* dir = opendir(".");
1787 if (!dir) {
1788 // Give up now; maybe we can upgrade later.
1789 ALOGE("couldn't open keystore's directory; something is wrong");
1790 return false;
1791 }
1792
1793 struct dirent* file;
1794 while ((file = readdir(dir)) != NULL) {
1795 // We only care about files.
1796 if (file->d_type != DT_REG) {
1797 continue;
1798 }
1799
1800 // Skip anything that starts with a "."
1801 if (file->d_name[0] == '.') {
1802 continue;
1803 }
1804
1805 // Find the current file's user.
1806 char* end;
1807 unsigned long thisUid = strtoul(file->d_name, &end, 10);
1808 if (end[0] != '_' || end[1] == 0) {
1809 continue;
1810 }
Chad Brubaker72593ee2015-05-12 10:42:00 -07001811 UserState* otherUser = getUserStateByUid(thisUid);
Kenny Root655b9582013-04-04 08:37:42 -07001812 if (otherUser->getUserId() != 0) {
1813 unlinkat(dirfd(dir), file->d_name, 0);
1814 }
1815
1816 // Rename the file into user directory.
1817 DIR* otherdir = opendir(otherUser->getUserDirName());
1818 if (otherdir == NULL) {
1819 ALOGW("couldn't open user directory for rename");
1820 continue;
1821 }
1822 if (renameat(dirfd(dir), file->d_name, dirfd(otherdir), file->d_name) < 0) {
1823 ALOGW("couldn't rename blob: %s: %s", file->d_name, strerror(errno));
1824 }
1825 closedir(otherdir);
1826 }
1827 closedir(dir);
1828
1829 mMetaData.version = 1;
1830 upgraded = true;
1831 }
1832
1833 return upgraded;
Kenny Root822c3a92012-03-23 16:34:39 -07001834 }
Kenny Roota91203b2012-02-15 15:00:46 -08001835};
1836
Kenny Root655b9582013-04-04 08:37:42 -07001837const char* KeyStore::sOldMasterKey = ".masterkey";
1838const char* KeyStore::sMetaDataFile = ".metadata";
Kenny Root70e3a862012-02-15 17:20:23 -08001839
Kenny Root1b0e3932013-09-05 13:06:32 -07001840const android::String16 KeyStore::sRSAKeyType("RSA");
1841
Kenny Root07438c82012-11-02 15:41:02 -07001842namespace android {
1843class KeyStoreProxy : public BnKeystoreService, public IBinder::DeathRecipient {
1844public:
1845 KeyStoreProxy(KeyStore* keyStore)
Chad Brubaker40a1a9b2015-02-20 14:08:13 -08001846 : mKeyStore(keyStore),
1847 mOperationMap(this)
Kenny Root07438c82012-11-02 15:41:02 -07001848 {
Kenny Roota91203b2012-02-15 15:00:46 -08001849 }
Kenny Roota91203b2012-02-15 15:00:46 -08001850
Chad Brubaker40a1a9b2015-02-20 14:08:13 -08001851 void binderDied(const wp<IBinder>& who) {
1852 auto operations = mOperationMap.getOperationsForToken(who.unsafe_get());
1853 for (auto token: operations) {
1854 abort(token);
1855 }
Kenny Root822c3a92012-03-23 16:34:39 -07001856 }
Kenny Roota91203b2012-02-15 15:00:46 -08001857
Chad Brubakere6c3bfa2015-05-12 15:18:26 -07001858 int32_t getState(int32_t userId) {
1859 if (!checkBinderPermission(P_GET_STATE)) {
Kenny Root07438c82012-11-02 15:41:02 -07001860 return ::PERMISSION_DENIED;
Kenny Roota91203b2012-02-15 15:00:46 -08001861 }
Kenny Roota91203b2012-02-15 15:00:46 -08001862
Chad Brubakere6c3bfa2015-05-12 15:18:26 -07001863 return mKeyStore->getState(userId);
Kenny Root298e7b12012-03-26 13:54:44 -07001864 }
1865
Kenny Root07438c82012-11-02 15:41:02 -07001866 int32_t get(const String16& name, uint8_t** item, size_t* itemLength) {
Chad Brubaker9489b792015-04-14 11:01:45 -07001867 if (!checkBinderPermission(P_GET)) {
Kenny Root07438c82012-11-02 15:41:02 -07001868 return ::PERMISSION_DENIED;
Kenny Roota91203b2012-02-15 15:00:46 -08001869 }
Kenny Root07438c82012-11-02 15:41:02 -07001870
Chad Brubaker9489b792015-04-14 11:01:45 -07001871 uid_t callingUid = IPCThreadState::self()->getCallingUid();
Kenny Root07438c82012-11-02 15:41:02 -07001872 String8 name8(name);
Kenny Root07438c82012-11-02 15:41:02 -07001873 Blob keyBlob;
Nick Kralevich66dbf672014-06-30 17:09:14 +00001874
Kenny Root655b9582013-04-04 08:37:42 -07001875 ResponseCode responseCode = mKeyStore->getKeyForName(&keyBlob, name8, callingUid,
Kenny Root49468902013-03-19 13:41:33 -07001876 TYPE_GENERIC);
Kenny Root07438c82012-11-02 15:41:02 -07001877 if (responseCode != ::NO_ERROR) {
1878 *item = NULL;
1879 *itemLength = 0;
1880 return responseCode;
Kenny Roota91203b2012-02-15 15:00:46 -08001881 }
Kenny Roota91203b2012-02-15 15:00:46 -08001882
Kenny Root07438c82012-11-02 15:41:02 -07001883 *item = (uint8_t*) malloc(keyBlob.getLength());
1884 memcpy(*item, keyBlob.getValue(), keyBlob.getLength());
1885 *itemLength = keyBlob.getLength();
Kenny Roota91203b2012-02-15 15:00:46 -08001886
Kenny Root07438c82012-11-02 15:41:02 -07001887 return ::NO_ERROR;
Kenny Root70e3a862012-02-15 17:20:23 -08001888 }
1889
Kenny Rootf9119d62013-04-03 09:22:15 -07001890 int32_t insert(const String16& name, const uint8_t* item, size_t itemLength, int targetUid,
1891 int32_t flags) {
Chad Brubaker9489b792015-04-14 11:01:45 -07001892 targetUid = getEffectiveUid(targetUid);
1893 int32_t result = checkBinderPermissionAndKeystoreState(P_INSERT, targetUid,
1894 flags & KEYSTORE_FLAG_ENCRYPTED);
1895 if (result != ::NO_ERROR) {
1896 return result;
Kenny Rootb88c3eb2013-02-13 14:43:43 -08001897 }
1898
Kenny Root07438c82012-11-02 15:41:02 -07001899 String8 name8(name);
Kenny Root655b9582013-04-04 08:37:42 -07001900 String8 filename(mKeyStore->getKeyNameForUidWithDir(name8, targetUid));
Kenny Root07438c82012-11-02 15:41:02 -07001901
1902 Blob keyBlob(item, itemLength, NULL, 0, ::TYPE_GENERIC);
Kenny Rootee8068b2013-10-07 09:49:15 -07001903 keyBlob.setEncrypted(flags & KEYSTORE_FLAG_ENCRYPTED);
1904
Chad Brubaker72593ee2015-05-12 10:42:00 -07001905 return mKeyStore->put(filename.string(), &keyBlob, get_user_id(targetUid));
Kenny Root70e3a862012-02-15 17:20:23 -08001906 }
1907
Kenny Root49468902013-03-19 13:41:33 -07001908 int32_t del(const String16& name, int targetUid) {
Chad Brubaker9489b792015-04-14 11:01:45 -07001909 targetUid = getEffectiveUid(targetUid);
1910 if (!checkBinderPermission(P_DELETE, targetUid)) {
Kenny Root07438c82012-11-02 15:41:02 -07001911 return ::PERMISSION_DENIED;
1912 }
Kenny Root07438c82012-11-02 15:41:02 -07001913 String8 name8(name);
Kenny Root655b9582013-04-04 08:37:42 -07001914 String8 filename(mKeyStore->getKeyNameForUidWithDir(name8, targetUid));
Chad Brubaker72593ee2015-05-12 10:42:00 -07001915 return mKeyStore->del(filename.string(), ::TYPE_ANY, get_user_id(targetUid));
Kenny Root70e3a862012-02-15 17:20:23 -08001916 }
1917
Kenny Root49468902013-03-19 13:41:33 -07001918 int32_t exist(const String16& name, int targetUid) {
Chad Brubaker9489b792015-04-14 11:01:45 -07001919 targetUid = getEffectiveUid(targetUid);
1920 if (!checkBinderPermission(P_EXIST, targetUid)) {
Kenny Rootb88c3eb2013-02-13 14:43:43 -08001921 return ::PERMISSION_DENIED;
1922 }
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));
Kenny Root70e3a862012-02-15 17:20:23 -08001926
Kenny Root655b9582013-04-04 08:37:42 -07001927 if (access(filename.string(), R_OK) == -1) {
Kenny Root07438c82012-11-02 15:41:02 -07001928 return (errno != ENOENT) ? ::SYSTEM_ERROR : ::KEY_NOT_FOUND;
1929 }
1930 return ::NO_ERROR;
Kenny Root70e3a862012-02-15 17:20:23 -08001931 }
1932
Chad Brubakere6c3bfa2015-05-12 15:18:26 -07001933 int32_t list(const String16& prefix, int targetUid, Vector<String16>* matches) {
Chad Brubaker9489b792015-04-14 11:01:45 -07001934 targetUid = getEffectiveUid(targetUid);
Chad Brubakere6c3bfa2015-05-12 15:18:26 -07001935 if (!checkBinderPermission(P_LIST, targetUid)) {
Kenny Root07438c82012-11-02 15:41:02 -07001936 return ::PERMISSION_DENIED;
1937 }
Kenny Root07438c82012-11-02 15:41:02 -07001938 const String8 prefix8(prefix);
Kenny Root655b9582013-04-04 08:37:42 -07001939 String8 filename(mKeyStore->getKeyNameForUid(prefix8, targetUid));
Kenny Root70e3a862012-02-15 17:20:23 -08001940
Chad Brubakere6c3bfa2015-05-12 15:18:26 -07001941 if (mKeyStore->list(filename, matches, get_user_id(targetUid)) != ::NO_ERROR) {
Robin Lee4b84fdc2014-09-24 11:56:57 +01001942 return ::SYSTEM_ERROR;
Kenny Root9a53d3e2012-08-14 10:47:54 -07001943 }
Kenny Root07438c82012-11-02 15:41:02 -07001944 return ::NO_ERROR;
Kenny Root70e3a862012-02-15 17:20:23 -08001945 }
1946
Kenny Root07438c82012-11-02 15:41:02 -07001947 int32_t reset() {
Chad Brubaker9489b792015-04-14 11:01:45 -07001948 if (!checkBinderPermission(P_RESET)) {
Kenny Root07438c82012-11-02 15:41:02 -07001949 return ::PERMISSION_DENIED;
1950 }
1951
Chad Brubaker9489b792015-04-14 11:01:45 -07001952 uid_t callingUid = IPCThreadState::self()->getCallingUid();
Chad Brubaker96d6d782015-05-07 10:19:40 -07001953 mKeyStore->resetUser(get_user_id(callingUid), false);
1954 return ::NO_ERROR;
Kenny Root70e3a862012-02-15 17:20:23 -08001955 }
1956
Chad Brubaker96d6d782015-05-07 10:19:40 -07001957 int32_t onUserPasswordChanged(int32_t userId, const String16& password) {
Chad Brubaker9489b792015-04-14 11:01:45 -07001958 if (!checkBinderPermission(P_PASSWORD)) {
Kenny Root07438c82012-11-02 15:41:02 -07001959 return ::PERMISSION_DENIED;
1960 }
Kenny Root70e3a862012-02-15 17:20:23 -08001961
Kenny Root07438c82012-11-02 15:41:02 -07001962 const String8 password8(password);
Chad Brubaker96d6d782015-05-07 10:19:40 -07001963 // Flush the auth token table to prevent stale tokens from sticking
1964 // around.
1965 mAuthTokenTable.Clear();
1966
1967 if (password.size() == 0) {
1968 ALOGI("Secure lockscreen for user %d removed, deleting encrypted entries", userId);
Chad Brubaker72593ee2015-05-12 10:42:00 -07001969 mKeyStore->resetUser(userId, true);
Chad Brubaker96d6d782015-05-07 10:19:40 -07001970 return ::NO_ERROR;
1971 } else {
Chad Brubaker72593ee2015-05-12 10:42:00 -07001972 switch (mKeyStore->getState(userId)) {
Chad Brubaker96d6d782015-05-07 10:19:40 -07001973 case ::STATE_UNINITIALIZED: {
1974 // generate master key, encrypt with password, write to file,
1975 // initialize mMasterKey*.
Chad Brubaker72593ee2015-05-12 10:42:00 -07001976 return mKeyStore->initializeUser(password8, userId);
Chad Brubaker96d6d782015-05-07 10:19:40 -07001977 }
1978 case ::STATE_NO_ERROR: {
1979 // rewrite master key with new password.
Chad Brubaker72593ee2015-05-12 10:42:00 -07001980 return mKeyStore->writeMasterKey(password8, userId);
Chad Brubaker96d6d782015-05-07 10:19:40 -07001981 }
1982 case ::STATE_LOCKED: {
1983 ALOGE("Changing user %d's password while locked, clearing old encryption",
1984 userId);
Chad Brubaker72593ee2015-05-12 10:42:00 -07001985 mKeyStore->resetUser(userId, true);
1986 return mKeyStore->initializeUser(password8, userId);
Chad Brubaker96d6d782015-05-07 10:19:40 -07001987 }
Kenny Root07438c82012-11-02 15:41:02 -07001988 }
Chad Brubaker96d6d782015-05-07 10:19:40 -07001989 return ::SYSTEM_ERROR;
Kenny Root07438c82012-11-02 15:41:02 -07001990 }
Kenny Root70e3a862012-02-15 17:20:23 -08001991 }
1992
Chad Brubakerc0f031a2015-05-12 10:43:10 -07001993 int32_t onUserAdded(int32_t userId, int32_t parentId) {
1994 if (!checkBinderPermission(P_USER_CHANGED)) {
1995 return ::PERMISSION_DENIED;
1996 }
1997
1998 // Sanity check that the new user has an empty keystore.
1999 if (!mKeyStore->isEmpty(userId)) {
2000 ALOGW("New user %d's keystore not empty. Clearing old entries.", userId);
2001 }
2002 // Unconditionally clear the keystore, just to be safe.
2003 mKeyStore->resetUser(userId, false);
2004
2005 // If the user has a parent user then use the parent's
2006 // masterkey/password, otherwise there's nothing to do.
2007 if (parentId != -1) {
2008 return mKeyStore->copyMasterKey(parentId, userId);
2009 } else {
2010 return ::NO_ERROR;
2011 }
2012 }
2013
2014 int32_t onUserRemoved(int32_t userId) {
2015 if (!checkBinderPermission(P_USER_CHANGED)) {
2016 return ::PERMISSION_DENIED;
2017 }
2018
2019 mKeyStore->resetUser(userId, false);
2020 return ::NO_ERROR;
2021 }
2022
Chad Brubakere6c3bfa2015-05-12 15:18:26 -07002023 int32_t lock(int32_t userId) {
Chad Brubaker9489b792015-04-14 11:01:45 -07002024 if (!checkBinderPermission(P_LOCK)) {
Kenny Root07438c82012-11-02 15:41:02 -07002025 return ::PERMISSION_DENIED;
2026 }
Kenny Root70e3a862012-02-15 17:20:23 -08002027
Chad Brubaker72593ee2015-05-12 10:42:00 -07002028 State state = mKeyStore->getState(userId);
Kenny Root9d45d1c2013-02-14 10:32:30 -08002029 if (state != ::STATE_NO_ERROR) {
Kenny Root07438c82012-11-02 15:41:02 -07002030 ALOGD("calling lock in state: %d", state);
2031 return state;
2032 }
2033
Chad Brubaker72593ee2015-05-12 10:42:00 -07002034 mKeyStore->lock(userId);
Kenny Root07438c82012-11-02 15:41:02 -07002035 return ::NO_ERROR;
Kenny Root70e3a862012-02-15 17:20:23 -08002036 }
2037
Chad Brubaker96d6d782015-05-07 10:19:40 -07002038 int32_t unlock(int32_t userId, const String16& pw) {
Chad Brubaker9489b792015-04-14 11:01:45 -07002039 if (!checkBinderPermission(P_UNLOCK)) {
Kenny Root07438c82012-11-02 15:41:02 -07002040 return ::PERMISSION_DENIED;
2041 }
2042
Chad Brubaker72593ee2015-05-12 10:42:00 -07002043 State state = mKeyStore->getState(userId);
Kenny Root9d45d1c2013-02-14 10:32:30 -08002044 if (state != ::STATE_LOCKED) {
Chad Brubaker96d6d782015-05-07 10:19:40 -07002045 ALOGI("calling unlock when not locked, ignoring.");
Kenny Root07438c82012-11-02 15:41:02 -07002046 return state;
2047 }
2048
2049 const String8 password8(pw);
Chad Brubaker96d6d782015-05-07 10:19:40 -07002050 // read master key, decrypt with password, initialize mMasterKey*.
Chad Brubaker72593ee2015-05-12 10:42:00 -07002051 return mKeyStore->readMasterKey(password8, userId);
Kenny Root70e3a862012-02-15 17:20:23 -08002052 }
2053
Chad Brubakere6c3bfa2015-05-12 15:18:26 -07002054 bool isEmpty(int32_t userId) {
2055 if (!checkBinderPermission(P_IS_EMPTY)) {
2056 return false;
Kenny Root07438c82012-11-02 15:41:02 -07002057 }
Kenny Root70e3a862012-02-15 17:20:23 -08002058
Chad Brubakere6c3bfa2015-05-12 15:18:26 -07002059 return mKeyStore->isEmpty(userId);
Kenny Root70e3a862012-02-15 17:20:23 -08002060 }
2061
Kenny Root96427ba2013-08-16 14:02:41 -07002062 int32_t generate(const String16& name, int32_t targetUid, int32_t keyType, int32_t keySize,
2063 int32_t flags, Vector<sp<KeystoreArg> >* args) {
Chad Brubaker9489b792015-04-14 11:01:45 -07002064 targetUid = getEffectiveUid(targetUid);
2065 int32_t result = checkBinderPermissionAndKeystoreState(P_INSERT, targetUid,
2066 flags & KEYSTORE_FLAG_ENCRYPTED);
2067 if (result != ::NO_ERROR) {
2068 return result;
Kenny Root07438c82012-11-02 15:41:02 -07002069 }
Kenny Root07438c82012-11-02 15:41:02 -07002070
Chad Brubaker3a7d9e62015-06-04 15:01:46 -07002071 KeymasterArguments params;
Shawn Willden76193b02015-07-28 11:06:00 -06002072 add_legacy_key_authorizations(keyType, &params.params);
Kenny Root07438c82012-11-02 15:41:02 -07002073
Chad Brubaker3a7d9e62015-06-04 15:01:46 -07002074 switch (keyType) {
2075 case EVP_PKEY_EC: {
2076 params.params.push_back(keymaster_param_enum(KM_TAG_ALGORITHM, KM_ALGORITHM_EC));
2077 if (keySize == -1) {
2078 keySize = EC_DEFAULT_KEY_SIZE;
2079 } else if (keySize < EC_MIN_KEY_SIZE || keySize > EC_MAX_KEY_SIZE) {
2080 ALOGI("invalid key size %d", keySize);
Kenny Root96427ba2013-08-16 14:02:41 -07002081 return ::SYSTEM_ERROR;
2082 }
Chad Brubaker3a7d9e62015-06-04 15:01:46 -07002083 params.params.push_back(keymaster_param_int(KM_TAG_KEY_SIZE, keySize));
2084 break;
Kenny Root96427ba2013-08-16 14:02:41 -07002085 }
Chad Brubaker3a7d9e62015-06-04 15:01:46 -07002086 case EVP_PKEY_RSA: {
2087 params.params.push_back(keymaster_param_enum(KM_TAG_ALGORITHM, KM_ALGORITHM_RSA));
2088 if (keySize == -1) {
2089 keySize = RSA_DEFAULT_KEY_SIZE;
2090 } else if (keySize < RSA_MIN_KEY_SIZE || keySize > RSA_MAX_KEY_SIZE) {
2091 ALOGI("invalid key size %d", keySize);
2092 return ::SYSTEM_ERROR;
Kenny Root96427ba2013-08-16 14:02:41 -07002093 }
Chad Brubaker3a7d9e62015-06-04 15:01:46 -07002094 params.params.push_back(keymaster_param_int(KM_TAG_KEY_SIZE, keySize));
2095 unsigned long exponent = RSA_DEFAULT_EXPONENT;
2096 if (args->size() > 1) {
2097 ALOGI("invalid number of arguments: %zu", args->size());
2098 return ::SYSTEM_ERROR;
2099 } else if (args->size() == 1) {
2100 sp<KeystoreArg> expArg = args->itemAt(0);
2101 if (expArg != NULL) {
2102 Unique_BIGNUM pubExpBn(
2103 BN_bin2bn(reinterpret_cast<const unsigned char*>(expArg->data()),
2104 expArg->size(), NULL));
2105 if (pubExpBn.get() == NULL) {
2106 ALOGI("Could not convert public exponent to BN");
2107 return ::SYSTEM_ERROR;
2108 }
2109 exponent = BN_get_word(pubExpBn.get());
2110 if (exponent == 0xFFFFFFFFL) {
2111 ALOGW("cannot represent public exponent as a long value");
2112 return ::SYSTEM_ERROR;
2113 }
2114 } else {
2115 ALOGW("public exponent not read");
2116 return ::SYSTEM_ERROR;
2117 }
2118 }
2119 params.params.push_back(keymaster_param_long(KM_TAG_RSA_PUBLIC_EXPONENT,
2120 exponent));
2121 break;
Kenny Root96427ba2013-08-16 14:02:41 -07002122 }
Chad Brubaker3a7d9e62015-06-04 15:01:46 -07002123 default: {
2124 ALOGW("Unsupported key type %d", keyType);
2125 return ::SYSTEM_ERROR;
2126 }
Kenny Root96427ba2013-08-16 14:02:41 -07002127 }
2128
Chad Brubaker3a7d9e62015-06-04 15:01:46 -07002129 int32_t rc = generateKey(name, params, NULL, 0, targetUid, flags,
2130 /*outCharacteristics*/ NULL);
2131 if (rc != ::NO_ERROR) {
2132 ALOGW("generate failed: %d", rc);
Kenny Root07438c82012-11-02 15:41:02 -07002133 }
Chad Brubaker3a7d9e62015-06-04 15:01:46 -07002134 return translateResultToLegacyResult(rc);
Kenny Root70e3a862012-02-15 17:20:23 -08002135 }
2136
Kenny Rootf9119d62013-04-03 09:22:15 -07002137 int32_t import(const String16& name, const uint8_t* data, size_t length, int targetUid,
2138 int32_t flags) {
Chad Brubaker3a7d9e62015-06-04 15:01:46 -07002139 const uint8_t* ptr = data;
Kenny Root07438c82012-11-02 15:41:02 -07002140
Chad Brubaker3a7d9e62015-06-04 15:01:46 -07002141 Unique_PKCS8_PRIV_KEY_INFO pkcs8(d2i_PKCS8_PRIV_KEY_INFO(NULL, &ptr, length));
2142 if (!pkcs8.get()) {
2143 return ::SYSTEM_ERROR;
2144 }
2145 Unique_EVP_PKEY pkey(EVP_PKCS82PKEY(pkcs8.get()));
2146 if (!pkey.get()) {
2147 return ::SYSTEM_ERROR;
2148 }
2149 int type = EVP_PKEY_type(pkey->type);
Shawn Willden2de8b752015-07-23 05:54:31 -06002150 KeymasterArguments params;
Shawn Willden76193b02015-07-28 11:06:00 -06002151 add_legacy_key_authorizations(type, &params.params);
Chad Brubaker3a7d9e62015-06-04 15:01:46 -07002152 switch (type) {
2153 case EVP_PKEY_RSA:
2154 params.params.push_back(keymaster_param_enum(KM_TAG_ALGORITHM, KM_ALGORITHM_RSA));
2155 break;
2156 case EVP_PKEY_EC:
2157 params.params.push_back(keymaster_param_enum(KM_TAG_ALGORITHM,
2158 KM_ALGORITHM_EC));
2159 break;
2160 default:
2161 ALOGW("Unsupported key type %d", type);
2162 return ::SYSTEM_ERROR;
2163 }
2164 int32_t rc = importKey(name, params, KM_KEY_FORMAT_PKCS8, data, length, targetUid, flags,
2165 /*outCharacteristics*/ NULL);
2166 if (rc != ::NO_ERROR) {
2167 ALOGW("importKey failed: %d", rc);
2168 }
2169 return translateResultToLegacyResult(rc);
Kenny Root70e3a862012-02-15 17:20:23 -08002170 }
2171
Kenny Root07438c82012-11-02 15:41:02 -07002172 int32_t sign(const String16& name, const uint8_t* data, size_t length, uint8_t** out,
Chad Brubaker3a7d9e62015-06-04 15:01:46 -07002173 size_t* outLength) {
Chad Brubaker9489b792015-04-14 11:01:45 -07002174 if (!checkBinderPermission(P_SIGN)) {
Kenny Root07438c82012-11-02 15:41:02 -07002175 return ::PERMISSION_DENIED;
2176 }
Chad Brubaker3a7d9e62015-06-04 15:01:46 -07002177 return doLegacySignVerify(name, data, length, out, outLength, NULL, 0, KM_PURPOSE_SIGN);
Kenny Root70e3a862012-02-15 17:20:23 -08002178 }
2179
Kenny Root07438c82012-11-02 15:41:02 -07002180 int32_t verify(const String16& name, const uint8_t* data, size_t dataLength,
2181 const uint8_t* signature, size_t signatureLength) {
Chad Brubaker9489b792015-04-14 11:01:45 -07002182 if (!checkBinderPermission(P_VERIFY)) {
Kenny Root07438c82012-11-02 15:41:02 -07002183 return ::PERMISSION_DENIED;
2184 }
Chad Brubaker3a7d9e62015-06-04 15:01:46 -07002185 return doLegacySignVerify(name, data, dataLength, NULL, NULL, signature, signatureLength,
2186 KM_PURPOSE_VERIFY);
Kenny Roota91203b2012-02-15 15:00:46 -08002187 }
Kenny Root07438c82012-11-02 15:41:02 -07002188
2189 /*
2190 * TODO: The abstraction between things stored in hardware and regular blobs
2191 * of data stored on the filesystem should be moved down to keystore itself.
2192 * Unfortunately the Java code that calls this has naming conventions that it
2193 * knows about. Ideally keystore shouldn't be used to store random blobs of
2194 * data.
2195 *
2196 * Until that happens, it's necessary to have a separate "get_pubkey" and
2197 * "del_key" since the Java code doesn't really communicate what it's
2198 * intentions are.
2199 */
2200 int32_t get_pubkey(const String16& name, uint8_t** pubkey, size_t* pubkeyLength) {
Chad Brubaker3a7d9e62015-06-04 15:01:46 -07002201 ExportResult result;
2202 exportKey(name, KM_KEY_FORMAT_X509, NULL, NULL, &result);
2203 if (result.resultCode != ::NO_ERROR) {
2204 ALOGW("export failed: %d", result.resultCode);
2205 return translateResultToLegacyResult(result.resultCode);
Kenny Root07438c82012-11-02 15:41:02 -07002206 }
Kenny Root07438c82012-11-02 15:41:02 -07002207
Chad Brubaker3a7d9e62015-06-04 15:01:46 -07002208 *pubkey = result.exportData.release();
2209 *pubkeyLength = result.dataLength;
Kenny Root07438c82012-11-02 15:41:02 -07002210 return ::NO_ERROR;
Kenny Roota91203b2012-02-15 15:00:46 -08002211 }
Kenny Root07438c82012-11-02 15:41:02 -07002212
Kenny Root07438c82012-11-02 15:41:02 -07002213 int32_t grant(const String16& name, int32_t granteeUid) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08002214 uid_t callingUid = IPCThreadState::self()->getCallingUid();
Chad Brubaker9489b792015-04-14 11:01:45 -07002215 int32_t result = checkBinderPermissionAndKeystoreState(P_GRANT);
2216 if (result != ::NO_ERROR) {
2217 return result;
Kenny Root07438c82012-11-02 15:41:02 -07002218 }
2219
2220 String8 name8(name);
Kenny Root655b9582013-04-04 08:37:42 -07002221 String8 filename(mKeyStore->getKeyNameForUidWithDir(name8, callingUid));
Kenny Root07438c82012-11-02 15:41:02 -07002222
Kenny Root655b9582013-04-04 08:37:42 -07002223 if (access(filename.string(), R_OK) == -1) {
Kenny Root07438c82012-11-02 15:41:02 -07002224 return (errno != ENOENT) ? ::SYSTEM_ERROR : ::KEY_NOT_FOUND;
2225 }
2226
Kenny Root655b9582013-04-04 08:37:42 -07002227 mKeyStore->addGrant(filename.string(), granteeUid);
Kenny Root07438c82012-11-02 15:41:02 -07002228 return ::NO_ERROR;
2229 }
2230
2231 int32_t ungrant(const String16& name, int32_t granteeUid) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08002232 uid_t callingUid = IPCThreadState::self()->getCallingUid();
Chad Brubaker9489b792015-04-14 11:01:45 -07002233 int32_t result = checkBinderPermissionAndKeystoreState(P_GRANT);
2234 if (result != ::NO_ERROR) {
2235 return result;
Kenny Root07438c82012-11-02 15:41:02 -07002236 }
2237
2238 String8 name8(name);
Kenny Root655b9582013-04-04 08:37:42 -07002239 String8 filename(mKeyStore->getKeyNameForUidWithDir(name8, callingUid));
Kenny Root07438c82012-11-02 15:41:02 -07002240
Kenny Root655b9582013-04-04 08:37:42 -07002241 if (access(filename.string(), R_OK) == -1) {
Kenny Root07438c82012-11-02 15:41:02 -07002242 return (errno != ENOENT) ? ::SYSTEM_ERROR : ::KEY_NOT_FOUND;
2243 }
2244
Kenny Root655b9582013-04-04 08:37:42 -07002245 return mKeyStore->removeGrant(filename.string(), granteeUid) ? ::NO_ERROR : ::KEY_NOT_FOUND;
Kenny Root07438c82012-11-02 15:41:02 -07002246 }
2247
2248 int64_t getmtime(const String16& name) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08002249 uid_t callingUid = IPCThreadState::self()->getCallingUid();
Chad Brubaker9489b792015-04-14 11:01:45 -07002250 if (!checkBinderPermission(P_GET)) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08002251 ALOGW("permission denied for %d: getmtime", callingUid);
Kenny Root36a9e232013-02-04 14:24:15 -08002252 return -1L;
Kenny Root07438c82012-11-02 15:41:02 -07002253 }
Kenny Root07438c82012-11-02 15:41:02 -07002254
2255 String8 name8(name);
Kenny Root655b9582013-04-04 08:37:42 -07002256 String8 filename(mKeyStore->getKeyNameForUidWithDir(name8, callingUid));
Kenny Root07438c82012-11-02 15:41:02 -07002257
Kenny Root655b9582013-04-04 08:37:42 -07002258 if (access(filename.string(), R_OK) == -1) {
2259 ALOGW("could not access %s for getmtime", filename.string());
Kenny Root36a9e232013-02-04 14:24:15 -08002260 return -1L;
Kenny Root07438c82012-11-02 15:41:02 -07002261 }
2262
Kenny Root655b9582013-04-04 08:37:42 -07002263 int fd = TEMP_FAILURE_RETRY(open(filename.string(), O_NOFOLLOW, O_RDONLY));
Kenny Root07438c82012-11-02 15:41:02 -07002264 if (fd < 0) {
Kenny Root655b9582013-04-04 08:37:42 -07002265 ALOGW("could not open %s for getmtime", filename.string());
Kenny Root36a9e232013-02-04 14:24:15 -08002266 return -1L;
Kenny Root07438c82012-11-02 15:41:02 -07002267 }
2268
2269 struct stat s;
2270 int ret = fstat(fd, &s);
2271 close(fd);
2272 if (ret == -1) {
Kenny Root655b9582013-04-04 08:37:42 -07002273 ALOGW("could not stat %s for getmtime", filename.string());
Kenny Root36a9e232013-02-04 14:24:15 -08002274 return -1L;
Kenny Root07438c82012-11-02 15:41:02 -07002275 }
2276
Kenny Root36a9e232013-02-04 14:24:15 -08002277 return static_cast<int64_t>(s.st_mtime);
Kenny Root07438c82012-11-02 15:41:02 -07002278 }
2279
Kenny Rootd53bc922013-03-21 14:10:15 -07002280 int32_t duplicate(const String16& srcKey, int32_t srcUid, const String16& destKey,
2281 int32_t destUid) {
Kenny Root02254072013-03-20 11:48:19 -07002282 uid_t callingUid = IPCThreadState::self()->getCallingUid();
Riley Spahneaabae92014-06-30 12:39:52 -07002283 pid_t spid = IPCThreadState::self()->getCallingPid();
2284 if (!has_permission(callingUid, P_DUPLICATE, spid)) {
Kenny Rootd53bc922013-03-21 14:10:15 -07002285 ALOGW("permission denied for %d: duplicate", callingUid);
Kenny Root02254072013-03-20 11:48:19 -07002286 return -1L;
2287 }
2288
Chad Brubaker72593ee2015-05-12 10:42:00 -07002289 State state = mKeyStore->getState(get_user_id(callingUid));
Kenny Root02254072013-03-20 11:48:19 -07002290 if (!isKeystoreUnlocked(state)) {
Kenny Rootd53bc922013-03-21 14:10:15 -07002291 ALOGD("calling duplicate in state: %d", state);
Kenny Root02254072013-03-20 11:48:19 -07002292 return state;
2293 }
2294
Kenny Rootd53bc922013-03-21 14:10:15 -07002295 if (srcUid == -1 || static_cast<uid_t>(srcUid) == callingUid) {
2296 srcUid = callingUid;
2297 } else if (!is_granted_to(callingUid, srcUid)) {
2298 ALOGD("migrate not granted from source: %d -> %d", callingUid, srcUid);
Kenny Root02254072013-03-20 11:48:19 -07002299 return ::PERMISSION_DENIED;
2300 }
2301
Kenny Rootd53bc922013-03-21 14:10:15 -07002302 if (destUid == -1) {
2303 destUid = callingUid;
2304 }
2305
2306 if (srcUid != destUid) {
2307 if (static_cast<uid_t>(srcUid) != callingUid) {
2308 ALOGD("can only duplicate from caller to other or to same uid: "
2309 "calling=%d, srcUid=%d, destUid=%d", callingUid, srcUid, destUid);
2310 return ::PERMISSION_DENIED;
2311 }
2312
2313 if (!is_granted_to(callingUid, destUid)) {
2314 ALOGD("duplicate not granted to dest: %d -> %d", callingUid, destUid);
2315 return ::PERMISSION_DENIED;
2316 }
2317 }
2318
2319 String8 source8(srcKey);
Kenny Root655b9582013-04-04 08:37:42 -07002320 String8 sourceFile(mKeyStore->getKeyNameForUidWithDir(source8, srcUid));
Kenny Root02254072013-03-20 11:48:19 -07002321
Kenny Rootd53bc922013-03-21 14:10:15 -07002322 String8 target8(destKey);
Kenny Rootfa27d5b2013-10-15 09:01:08 -07002323 String8 targetFile(mKeyStore->getKeyNameForUidWithDir(target8, destUid));
Kenny Root02254072013-03-20 11:48:19 -07002324
Kenny Root655b9582013-04-04 08:37:42 -07002325 if (access(targetFile.string(), W_OK) != -1 || errno != ENOENT) {
2326 ALOGD("destination already exists: %s", targetFile.string());
Kenny Root02254072013-03-20 11:48:19 -07002327 return ::SYSTEM_ERROR;
2328 }
2329
Kenny Rootd53bc922013-03-21 14:10:15 -07002330 Blob keyBlob;
Kenny Root655b9582013-04-04 08:37:42 -07002331 ResponseCode responseCode = mKeyStore->get(sourceFile.string(), &keyBlob, TYPE_ANY,
Chad Brubaker72593ee2015-05-12 10:42:00 -07002332 get_user_id(srcUid));
Kenny Rootd53bc922013-03-21 14:10:15 -07002333 if (responseCode != ::NO_ERROR) {
2334 return responseCode;
Kenny Root02254072013-03-20 11:48:19 -07002335 }
Kenny Rootd53bc922013-03-21 14:10:15 -07002336
Chad Brubaker72593ee2015-05-12 10:42:00 -07002337 return mKeyStore->put(targetFile.string(), &keyBlob, get_user_id(destUid));
Kenny Root02254072013-03-20 11:48:19 -07002338 }
2339
Kenny Root1b0e3932013-09-05 13:06:32 -07002340 int32_t is_hardware_backed(const String16& keyType) {
2341 return mKeyStore->isHardwareBacked(keyType) ? 1 : 0;
Kenny Root8ddf35a2013-03-29 11:15:50 -07002342 }
2343
Kenny Rootfa27d5b2013-10-15 09:01:08 -07002344 int32_t clear_uid(int64_t targetUid64) {
Chad Brubaker9489b792015-04-14 11:01:45 -07002345 uid_t targetUid = getEffectiveUid(targetUid64);
Chad Brubakerb37a5232015-05-01 10:21:27 -07002346 if (!checkBinderPermissionSelfOrSystem(P_CLEAR_UID, targetUid)) {
Kenny Roota9bb5492013-04-01 16:29:11 -07002347 return ::PERMISSION_DENIED;
2348 }
2349
Robin Lee4b84fdc2014-09-24 11:56:57 +01002350 String8 prefix = String8::format("%u_", targetUid);
2351 Vector<String16> aliases;
Chad Brubakere6c3bfa2015-05-12 15:18:26 -07002352 if (mKeyStore->list(prefix, &aliases, get_user_id(targetUid)) != ::NO_ERROR) {
Kenny Roota9bb5492013-04-01 16:29:11 -07002353 return ::SYSTEM_ERROR;
2354 }
2355
Robin Lee4b84fdc2014-09-24 11:56:57 +01002356 for (uint32_t i = 0; i < aliases.size(); i++) {
2357 String8 name8(aliases[i]);
2358 String8 filename(mKeyStore->getKeyNameForUidWithDir(name8, targetUid));
Chad Brubaker72593ee2015-05-12 10:42:00 -07002359 mKeyStore->del(filename.string(), ::TYPE_ANY, get_user_id(targetUid));
Kenny Roota9bb5492013-04-01 16:29:11 -07002360 }
Robin Lee4b84fdc2014-09-24 11:56:57 +01002361 return ::NO_ERROR;
Kenny Roota9bb5492013-04-01 16:29:11 -07002362 }
2363
Chad Brubaker9c8612c2015-02-09 11:32:54 -08002364 int32_t addRngEntropy(const uint8_t* data, size_t dataLength) {
2365 const keymaster1_device_t* device = mKeyStore->getDevice();
2366 const keymaster1_device_t* fallback = mKeyStore->getFallbackDevice();
2367 int32_t devResult = KM_ERROR_UNIMPLEMENTED;
2368 int32_t fallbackResult = KM_ERROR_UNIMPLEMENTED;
2369 if (device->common.module->module_api_version >= KEYMASTER_MODULE_API_VERSION_1_0 &&
2370 device->add_rng_entropy != NULL) {
2371 devResult = device->add_rng_entropy(device, data, dataLength);
2372 }
2373 if (fallback->add_rng_entropy) {
2374 fallbackResult = fallback->add_rng_entropy(fallback, data, dataLength);
2375 }
2376 if (devResult) {
2377 return devResult;
2378 }
2379 if (fallbackResult) {
2380 return fallbackResult;
2381 }
2382 return ::NO_ERROR;
Chad Brubaker9899d6b2015-02-03 13:03:00 -08002383 }
2384
Chad Brubaker17d68b92015-02-05 22:04:16 -08002385 int32_t generateKey(const String16& name, const KeymasterArguments& params,
Chad Brubaker154d7692015-03-27 13:59:31 -07002386 const uint8_t* entropy, size_t entropyLength, int uid, int flags,
2387 KeyCharacteristics* outCharacteristics) {
Chad Brubaker9489b792015-04-14 11:01:45 -07002388 uid = getEffectiveUid(uid);
2389 int rc = checkBinderPermissionAndKeystoreState(P_INSERT, uid,
2390 flags & KEYSTORE_FLAG_ENCRYPTED);
2391 if (rc != ::NO_ERROR) {
2392 return rc;
Chad Brubaker17d68b92015-02-05 22:04:16 -08002393 }
2394
Chad Brubaker9489b792015-04-14 11:01:45 -07002395 rc = KM_ERROR_UNIMPLEMENTED;
Chad Brubaker17d68b92015-02-05 22:04:16 -08002396 bool isFallback = false;
2397 keymaster_key_blob_t blob;
2398 keymaster_key_characteristics_t *out = NULL;
2399
2400 const keymaster1_device_t* device = mKeyStore->getDevice();
2401 const keymaster1_device_t* fallback = mKeyStore->getFallbackDevice();
Chad Brubaker57e106d2015-06-01 12:59:00 -07002402 std::vector<keymaster_key_param_t> opParams(params.params);
2403 const keymaster_key_param_set_t inParams = {opParams.data(), opParams.size()};
Chad Brubaker17d68b92015-02-05 22:04:16 -08002404 if (device == NULL) {
2405 return ::SYSTEM_ERROR;
2406 }
Chad Brubaker154d7692015-03-27 13:59:31 -07002407 // TODO: Seed from Linux RNG before this.
Chad Brubaker17d68b92015-02-05 22:04:16 -08002408 if (device->common.module->module_api_version >= KEYMASTER_MODULE_API_VERSION_1_0 &&
2409 device->generate_key != NULL) {
Chad Brubaker154d7692015-03-27 13:59:31 -07002410 if (!entropy) {
2411 rc = KM_ERROR_OK;
2412 } else if (device->add_rng_entropy) {
2413 rc = device->add_rng_entropy(device, entropy, entropyLength);
2414 } else {
2415 rc = KM_ERROR_UNIMPLEMENTED;
2416 }
2417 if (rc == KM_ERROR_OK) {
Chad Brubaker57e106d2015-06-01 12:59:00 -07002418 rc = device->generate_key(device, &inParams, &blob, &out);
Chad Brubaker154d7692015-03-27 13:59:31 -07002419 }
Chad Brubaker17d68b92015-02-05 22:04:16 -08002420 }
2421 // If the HW device didn't support generate_key or generate_key failed
2422 // fall back to the software implementation.
2423 if (rc && fallback->generate_key != NULL) {
Shawn Willden76193b02015-07-28 11:06:00 -06002424 ALOGW("Primary keymaster device failed to generate key, falling back to SW.");
Chad Brubaker17d68b92015-02-05 22:04:16 -08002425 isFallback = true;
Chad Brubaker154d7692015-03-27 13:59:31 -07002426 if (!entropy) {
2427 rc = KM_ERROR_OK;
2428 } else if (fallback->add_rng_entropy) {
2429 rc = fallback->add_rng_entropy(fallback, entropy, entropyLength);
2430 } else {
2431 rc = KM_ERROR_UNIMPLEMENTED;
2432 }
2433 if (rc == KM_ERROR_OK) {
Chad Brubaker57e106d2015-06-01 12:59:00 -07002434 rc = fallback->generate_key(fallback, &inParams, &blob, &out);
Chad Brubaker154d7692015-03-27 13:59:31 -07002435 }
Chad Brubaker17d68b92015-02-05 22:04:16 -08002436 }
2437
2438 if (out) {
2439 if (outCharacteristics) {
2440 outCharacteristics->characteristics = *out;
2441 } else {
2442 keymaster_free_characteristics(out);
2443 }
2444 free(out);
2445 }
2446
2447 if (rc) {
2448 return rc;
2449 }
2450
2451 String8 name8(name);
2452 String8 filename(mKeyStore->getKeyNameForUidWithDir(name8, uid));
2453
2454 Blob keyBlob(blob.key_material, blob.key_material_size, NULL, 0, ::TYPE_KEYMASTER_10);
2455 keyBlob.setFallback(isFallback);
2456 keyBlob.setEncrypted(flags & KEYSTORE_FLAG_ENCRYPTED);
2457
2458 free(const_cast<uint8_t*>(blob.key_material));
2459
Chad Brubaker72593ee2015-05-12 10:42:00 -07002460 return mKeyStore->put(filename.string(), &keyBlob, get_user_id(uid));
Chad Brubaker9899d6b2015-02-03 13:03:00 -08002461 }
2462
Chad Brubakerf3f071f2015-02-10 19:38:51 -08002463 int32_t getKeyCharacteristics(const String16& name,
Chad Brubakerd6634422015-03-21 22:36:07 -07002464 const keymaster_blob_t* clientId,
2465 const keymaster_blob_t* appData,
Chad Brubakerf3f071f2015-02-10 19:38:51 -08002466 KeyCharacteristics* outCharacteristics) {
Chad Brubakerf3f071f2015-02-10 19:38:51 -08002467 if (!outCharacteristics) {
2468 return KM_ERROR_UNEXPECTED_NULL_POINTER;
2469 }
2470
2471 uid_t callingUid = IPCThreadState::self()->getCallingUid();
2472
2473 Blob keyBlob;
2474 String8 name8(name);
2475 int rc;
2476
2477 ResponseCode responseCode = mKeyStore->getKeyForName(&keyBlob, name8, callingUid,
2478 TYPE_KEYMASTER_10);
2479 if (responseCode != ::NO_ERROR) {
2480 return responseCode;
2481 }
2482 keymaster_key_blob_t key;
2483 key.key_material_size = keyBlob.getLength();
2484 key.key_material = keyBlob.getValue();
2485 keymaster1_device_t* dev = mKeyStore->getDeviceForBlob(keyBlob);
2486 keymaster_key_characteristics_t *out = NULL;
2487 if (!dev->get_key_characteristics) {
2488 ALOGW("device does not implement get_key_characteristics");
2489 return KM_ERROR_UNIMPLEMENTED;
2490 }
Chad Brubakerd6634422015-03-21 22:36:07 -07002491 rc = dev->get_key_characteristics(dev, &key, clientId, appData, &out);
Chad Brubakerf3f071f2015-02-10 19:38:51 -08002492 if (out) {
2493 outCharacteristics->characteristics = *out;
2494 free(out);
2495 }
2496 return rc ? rc : ::NO_ERROR;
Chad Brubaker9899d6b2015-02-03 13:03:00 -08002497 }
2498
Chad Brubaker4c353cb2015-02-11 14:36:11 -08002499 int32_t importKey(const String16& name, const KeymasterArguments& params,
2500 keymaster_key_format_t format, const uint8_t *keyData,
2501 size_t keyLength, int uid, int flags,
2502 KeyCharacteristics* outCharacteristics) {
Chad Brubaker9489b792015-04-14 11:01:45 -07002503 uid = getEffectiveUid(uid);
2504 int rc = checkBinderPermissionAndKeystoreState(P_INSERT, uid,
2505 flags & KEYSTORE_FLAG_ENCRYPTED);
2506 if (rc != ::NO_ERROR) {
2507 return rc;
Chad Brubaker4c353cb2015-02-11 14:36:11 -08002508 }
2509
Chad Brubaker9489b792015-04-14 11:01:45 -07002510 rc = KM_ERROR_UNIMPLEMENTED;
Chad Brubaker4c353cb2015-02-11 14:36:11 -08002511 bool isFallback = false;
2512 keymaster_key_blob_t blob;
2513 keymaster_key_characteristics_t *out = NULL;
2514
2515 const keymaster1_device_t* device = mKeyStore->getDevice();
2516 const keymaster1_device_t* fallback = mKeyStore->getFallbackDevice();
Chad Brubaker57e106d2015-06-01 12:59:00 -07002517 std::vector<keymaster_key_param_t> opParams(params.params);
2518 const keymaster_key_param_set_t inParams = {opParams.data(), opParams.size()};
2519 const keymaster_blob_t input = {keyData, keyLength};
Chad Brubaker4c353cb2015-02-11 14:36:11 -08002520 if (device == NULL) {
2521 return ::SYSTEM_ERROR;
2522 }
2523 if (device->common.module->module_api_version >= KEYMASTER_MODULE_API_VERSION_1_0 &&
2524 device->import_key != NULL) {
Chad Brubaker57e106d2015-06-01 12:59:00 -07002525 rc = device->import_key(device, &inParams, format,&input, &blob, &out);
Chad Brubaker4c353cb2015-02-11 14:36:11 -08002526 }
2527 if (rc && fallback->import_key != NULL) {
Shawn Willden76193b02015-07-28 11:06:00 -06002528 ALOGW("Primary keymaster device failed to import key, falling back to SW.");
Chad Brubaker4c353cb2015-02-11 14:36:11 -08002529 isFallback = true;
Chad Brubaker57e106d2015-06-01 12:59:00 -07002530 rc = fallback->import_key(fallback, &inParams, format, &input, &blob, &out);
Chad Brubaker4c353cb2015-02-11 14:36:11 -08002531 }
2532 if (out) {
2533 if (outCharacteristics) {
2534 outCharacteristics->characteristics = *out;
2535 } else {
2536 keymaster_free_characteristics(out);
2537 }
2538 free(out);
2539 }
2540 if (rc) {
2541 return rc;
2542 }
2543
2544 String8 name8(name);
2545 String8 filename(mKeyStore->getKeyNameForUidWithDir(name8, uid));
2546
2547 Blob keyBlob(blob.key_material, blob.key_material_size, NULL, 0, ::TYPE_KEYMASTER_10);
2548 keyBlob.setFallback(isFallback);
2549 keyBlob.setEncrypted(flags & KEYSTORE_FLAG_ENCRYPTED);
2550
2551 free((void*) blob.key_material);
2552
Chad Brubaker72593ee2015-05-12 10:42:00 -07002553 return mKeyStore->put(filename.string(), &keyBlob, get_user_id(uid));
Chad Brubaker9899d6b2015-02-03 13:03:00 -08002554 }
2555
Chad Brubaker07b0cda2015-02-18 15:52:54 -08002556 void exportKey(const String16& name, keymaster_key_format_t format,
Chad Brubakerd6634422015-03-21 22:36:07 -07002557 const keymaster_blob_t* clientId,
2558 const keymaster_blob_t* appData, ExportResult* result) {
Chad Brubaker07b0cda2015-02-18 15:52:54 -08002559
2560 uid_t callingUid = IPCThreadState::self()->getCallingUid();
2561
2562 Blob keyBlob;
2563 String8 name8(name);
2564 int rc;
2565
2566 ResponseCode responseCode = mKeyStore->getKeyForName(&keyBlob, name8, callingUid,
2567 TYPE_KEYMASTER_10);
2568 if (responseCode != ::NO_ERROR) {
2569 result->resultCode = responseCode;
2570 return;
2571 }
2572 keymaster_key_blob_t key;
2573 key.key_material_size = keyBlob.getLength();
2574 key.key_material = keyBlob.getValue();
2575 keymaster1_device_t* dev = mKeyStore->getDeviceForBlob(keyBlob);
2576 if (!dev->export_key) {
2577 result->resultCode = KM_ERROR_UNIMPLEMENTED;
2578 return;
2579 }
Chad Brubaker57e106d2015-06-01 12:59:00 -07002580 keymaster_blob_t output = {NULL, 0};
2581 rc = dev->export_key(dev, format, &key, clientId, appData, &output);
2582 result->exportData.reset(const_cast<uint8_t*>(output.data));
2583 result->dataLength = output.data_length;
Chad Brubaker07b0cda2015-02-18 15:52:54 -08002584 result->resultCode = rc ? rc : ::NO_ERROR;
Chad Brubaker9899d6b2015-02-03 13:03:00 -08002585 }
2586
Chad Brubakerad6514a2015-04-09 14:00:26 -07002587
Chad Brubaker40a1a9b2015-02-20 14:08:13 -08002588 void begin(const sp<IBinder>& appToken, const String16& name, keymaster_purpose_t purpose,
Chad Brubaker154d7692015-03-27 13:59:31 -07002589 bool pruneable, const KeymasterArguments& params, const uint8_t* entropy,
Chad Brubaker57e106d2015-06-01 12:59:00 -07002590 size_t entropyLength, OperationResult* result) {
Chad Brubaker40a1a9b2015-02-20 14:08:13 -08002591 uid_t callingUid = IPCThreadState::self()->getCallingUid();
2592 if (!pruneable && get_app_id(callingUid) != AID_SYSTEM) {
2593 ALOGE("Non-system uid %d trying to start non-pruneable operation", callingUid);
2594 result->resultCode = ::PERMISSION_DENIED;
2595 return;
2596 }
Chad Brubaker0cf34a22015-04-23 11:06:16 -07002597 if (!checkAllowedOperationParams(params.params)) {
2598 result->resultCode = KM_ERROR_INVALID_ARGUMENT;
2599 return;
2600 }
Chad Brubaker40a1a9b2015-02-20 14:08:13 -08002601 Blob keyBlob;
2602 String8 name8(name);
2603 ResponseCode responseCode = mKeyStore->getKeyForName(&keyBlob, name8, callingUid,
2604 TYPE_KEYMASTER_10);
2605 if (responseCode != ::NO_ERROR) {
2606 result->resultCode = responseCode;
2607 return;
2608 }
2609 keymaster_key_blob_t key;
2610 key.key_material_size = keyBlob.getLength();
2611 key.key_material = keyBlob.getValue();
Chad Brubaker40a1a9b2015-02-20 14:08:13 -08002612 keymaster_operation_handle_t handle;
2613 keymaster1_device_t* dev = mKeyStore->getDeviceForBlob(keyBlob);
Chad Brubaker154d7692015-03-27 13:59:31 -07002614 keymaster_error_t err = KM_ERROR_UNIMPLEMENTED;
Chad Brubaker06801e02015-03-31 15:13:13 -07002615 std::vector<keymaster_key_param_t> opParams(params.params);
Chad Brubakerad6514a2015-04-09 14:00:26 -07002616 Unique_keymaster_key_characteristics characteristics;
2617 characteristics.reset(new keymaster_key_characteristics_t);
2618 err = getOperationCharacteristics(key, dev, opParams, characteristics.get());
2619 if (err) {
2620 result->resultCode = err;
2621 return;
2622 }
Chad Brubaker0cf34a22015-04-23 11:06:16 -07002623 const hw_auth_token_t* authToken = NULL;
Shawn Willdenb2ffa422015-06-17 12:18:55 -06002624 int32_t authResult = getAuthToken(characteristics.get(), 0, purpose, &authToken,
Chad Brubaker06801e02015-03-31 15:13:13 -07002625 /*failOnTokenMissing*/ false);
Chad Brubaker0cf34a22015-04-23 11:06:16 -07002626 // If per-operation auth is needed we need to begin the operation and
2627 // the client will need to authorize that operation before calling
2628 // update. Any other auth issues stop here.
2629 if (authResult != ::NO_ERROR && authResult != ::OP_AUTH_NEEDED) {
2630 result->resultCode = authResult;
Chad Brubaker06801e02015-03-31 15:13:13 -07002631 return;
2632 }
Chad Brubaker0cf34a22015-04-23 11:06:16 -07002633 addAuthToParams(&opParams, authToken);
Chad Brubaker154d7692015-03-27 13:59:31 -07002634 // Add entropy to the device first.
2635 if (entropy) {
2636 if (dev->add_rng_entropy) {
2637 err = dev->add_rng_entropy(dev, entropy, entropyLength);
2638 } else {
2639 err = KM_ERROR_UNIMPLEMENTED;
2640 }
2641 if (err) {
2642 result->resultCode = err;
2643 return;
2644 }
2645 }
Chad Brubaker57e106d2015-06-01 12:59:00 -07002646 keymaster_key_param_set_t inParams = {opParams.data(), opParams.size()};
Chad Brubaker40a1a9b2015-02-20 14:08:13 -08002647
Shawn Willden9221bff2015-06-18 18:23:54 -06002648 // Create a keyid for this key.
2649 keymaster::km_id_t keyid;
2650 if (!enforcement_policy.CreateKeyId(key, &keyid)) {
2651 ALOGE("Failed to create a key ID for authorization checking.");
2652 result->resultCode = KM_ERROR_UNKNOWN_ERROR;
2653 return;
2654 }
2655
2656 // Check that all key authorization policy requirements are met.
2657 keymaster::AuthorizationSet key_auths(characteristics->hw_enforced);
2658 key_auths.push_back(characteristics->sw_enforced);
2659 keymaster::AuthorizationSet operation_params(inParams);
2660 err = enforcement_policy.AuthorizeOperation(purpose, keyid, key_auths, operation_params,
2661 0 /* op_handle */,
2662 true /* is_begin_operation */);
2663 if (err) {
2664 result->resultCode = err;
2665 return;
2666 }
2667
Alex Klyubin4e88f9b2015-06-23 15:04:05 -07002668 keymaster_key_param_set_t outParams = {NULL, 0};
2669 err = dev->begin(dev, purpose, &key, &inParams, &outParams, &handle);
2670
Chad Brubaker40a1a9b2015-02-20 14:08:13 -08002671 // If there are too many operations abort the oldest operation that was
2672 // started as pruneable and try again.
2673 while (err == KM_ERROR_TOO_MANY_OPERATIONS && mOperationMap.hasPruneableOperation()) {
2674 sp<IBinder> oldest = mOperationMap.getOldestPruneableOperation();
2675 ALOGD("Ran out of operation handles, trying to prune %p", oldest.get());
Alex Klyubin700c1a32015-06-23 15:21:51 -07002676
2677 // We mostly ignore errors from abort() below because all we care about is whether at
2678 // least one pruneable operation has been removed.
2679 size_t op_count_before = mOperationMap.getPruneableOperationCount();
2680 int abort_error = abort(oldest);
2681 size_t op_count_after = mOperationMap.getPruneableOperationCount();
2682 if (op_count_after >= op_count_before) {
2683 // Failed to create space for a new operation. Bail to avoid an infinite loop.
2684 ALOGE("Failed to remove pruneable operation %p, error: %d",
2685 oldest.get(), abort_error);
Chad Brubaker40a1a9b2015-02-20 14:08:13 -08002686 break;
2687 }
Chad Brubaker57e106d2015-06-01 12:59:00 -07002688 err = dev->begin(dev, purpose, &key, &inParams, &outParams, &handle);
Chad Brubaker40a1a9b2015-02-20 14:08:13 -08002689 }
2690 if (err) {
2691 result->resultCode = err;
2692 return;
2693 }
Chad Brubaker40a1a9b2015-02-20 14:08:13 -08002694
Shawn Willden9221bff2015-06-18 18:23:54 -06002695 sp<IBinder> operationToken = mOperationMap.addOperation(handle, keyid, purpose, dev,
2696 appToken, characteristics.release(),
Chad Brubaker06801e02015-03-31 15:13:13 -07002697 pruneable);
Chad Brubaker0cf34a22015-04-23 11:06:16 -07002698 if (authToken) {
2699 mOperationMap.setOperationAuthToken(operationToken, authToken);
2700 }
2701 // Return the authentication lookup result. If this is a per operation
2702 // auth'd key then the resultCode will be ::OP_AUTH_NEEDED and the
2703 // application should get an auth token using the handle before the
2704 // first call to update, which will fail if keystore hasn't received the
2705 // auth token.
2706 result->resultCode = authResult;
Chad Brubaker40a1a9b2015-02-20 14:08:13 -08002707 result->token = operationToken;
Chad Brubakerc3a18562015-03-17 18:21:35 -07002708 result->handle = handle;
Chad Brubaker57e106d2015-06-01 12:59:00 -07002709 if (outParams.params) {
2710 result->outParams.params.assign(outParams.params, outParams.params + outParams.length);
2711 free(outParams.params);
2712 }
Chad Brubaker9899d6b2015-02-03 13:03:00 -08002713 }
2714
Chad Brubaker40a1a9b2015-02-20 14:08:13 -08002715 void update(const sp<IBinder>& token, const KeymasterArguments& params, const uint8_t* data,
2716 size_t dataLength, OperationResult* result) {
Chad Brubaker0cf34a22015-04-23 11:06:16 -07002717 if (!checkAllowedOperationParams(params.params)) {
2718 result->resultCode = KM_ERROR_INVALID_ARGUMENT;
2719 return;
2720 }
Chad Brubaker40a1a9b2015-02-20 14:08:13 -08002721 const keymaster1_device_t* dev;
2722 keymaster_operation_handle_t handle;
Shawn Willdenb2ffa422015-06-17 12:18:55 -06002723 keymaster_purpose_t purpose;
Shawn Willden9221bff2015-06-18 18:23:54 -06002724 keymaster::km_id_t keyid;
2725 const keymaster_key_characteristics_t* characteristics;
2726 if (!mOperationMap.getOperation(token, &handle, &keyid, &purpose, &dev, &characteristics)) {
Chad Brubaker40a1a9b2015-02-20 14:08:13 -08002727 result->resultCode = KM_ERROR_INVALID_OPERATION_HANDLE;
2728 return;
2729 }
Chad Brubaker06801e02015-03-31 15:13:13 -07002730 std::vector<keymaster_key_param_t> opParams(params.params);
Chad Brubaker0cf34a22015-04-23 11:06:16 -07002731 int32_t authResult = addOperationAuthTokenIfNeeded(token, &opParams);
2732 if (authResult != ::NO_ERROR) {
Chad Brubaker06801e02015-03-31 15:13:13 -07002733 result->resultCode = authResult;
2734 return;
2735 }
Chad Brubaker57e106d2015-06-01 12:59:00 -07002736 keymaster_key_param_set_t inParams = {opParams.data(), opParams.size()};
2737 keymaster_blob_t input = {data, dataLength};
2738 size_t consumed = 0;
2739 keymaster_blob_t output = {NULL, 0};
2740 keymaster_key_param_set_t outParams = {NULL, 0};
2741
Shawn Willden9221bff2015-06-18 18:23:54 -06002742 // Check that all key authorization policy requirements are met.
2743 keymaster::AuthorizationSet key_auths(characteristics->hw_enforced);
2744 key_auths.push_back(characteristics->sw_enforced);
2745 keymaster::AuthorizationSet operation_params(inParams);
2746 result->resultCode =
2747 enforcement_policy.AuthorizeOperation(purpose, keyid, key_auths,
2748 operation_params, handle,
2749 false /* is_begin_operation */);
2750 if (result->resultCode) {
2751 return;
2752 }
2753
Chad Brubaker57e106d2015-06-01 12:59:00 -07002754 keymaster_error_t err = dev->update(dev, handle, &inParams, &input, &consumed, &outParams,
2755 &output);
2756 result->data.reset(const_cast<uint8_t*>(output.data));
2757 result->dataLength = output.data_length;
Chad Brubaker40a1a9b2015-02-20 14:08:13 -08002758 result->inputConsumed = consumed;
2759 result->resultCode = err ? (int32_t) err : ::NO_ERROR;
Chad Brubaker57e106d2015-06-01 12:59:00 -07002760 if (outParams.params) {
2761 result->outParams.params.assign(outParams.params, outParams.params + outParams.length);
2762 free(outParams.params);
2763 }
Chad Brubaker9899d6b2015-02-03 13:03:00 -08002764 }
2765
Chad Brubaker40a1a9b2015-02-20 14:08:13 -08002766 void finish(const sp<IBinder>& token, const KeymasterArguments& params,
Chad Brubaker0d33e0b2015-05-29 12:30:19 -07002767 const uint8_t* signature, size_t signatureLength,
2768 const uint8_t* entropy, size_t entropyLength, OperationResult* result) {
Chad Brubaker0cf34a22015-04-23 11:06:16 -07002769 if (!checkAllowedOperationParams(params.params)) {
2770 result->resultCode = KM_ERROR_INVALID_ARGUMENT;
2771 return;
2772 }
Chad Brubaker40a1a9b2015-02-20 14:08:13 -08002773 const keymaster1_device_t* dev;
2774 keymaster_operation_handle_t handle;
Shawn Willdenb2ffa422015-06-17 12:18:55 -06002775 keymaster_purpose_t purpose;
Shawn Willden9221bff2015-06-18 18:23:54 -06002776 keymaster::km_id_t keyid;
2777 const keymaster_key_characteristics_t* characteristics;
2778 if (!mOperationMap.getOperation(token, &handle, &keyid, &purpose, &dev, &characteristics)) {
Chad Brubaker40a1a9b2015-02-20 14:08:13 -08002779 result->resultCode = KM_ERROR_INVALID_OPERATION_HANDLE;
2780 return;
2781 }
Chad Brubaker06801e02015-03-31 15:13:13 -07002782 std::vector<keymaster_key_param_t> opParams(params.params);
Chad Brubaker0cf34a22015-04-23 11:06:16 -07002783 int32_t authResult = addOperationAuthTokenIfNeeded(token, &opParams);
2784 if (authResult != ::NO_ERROR) {
Chad Brubaker06801e02015-03-31 15:13:13 -07002785 result->resultCode = authResult;
2786 return;
2787 }
Chad Brubaker0d33e0b2015-05-29 12:30:19 -07002788 keymaster_error_t err;
2789 if (entropy) {
2790 if (dev->add_rng_entropy) {
2791 err = dev->add_rng_entropy(dev, entropy, entropyLength);
2792 } else {
2793 err = KM_ERROR_UNIMPLEMENTED;
2794 }
2795 if (err) {
2796 result->resultCode = err;
2797 return;
2798 }
2799 }
Chad Brubaker0cf34a22015-04-23 11:06:16 -07002800
Chad Brubaker57e106d2015-06-01 12:59:00 -07002801 keymaster_key_param_set_t inParams = {opParams.data(), opParams.size()};
2802 keymaster_blob_t input = {signature, signatureLength};
2803 keymaster_blob_t output = {NULL, 0};
2804 keymaster_key_param_set_t outParams = {NULL, 0};
Shawn Willden9221bff2015-06-18 18:23:54 -06002805
2806 // Check that all key authorization policy requirements are met.
2807 keymaster::AuthorizationSet key_auths(characteristics->hw_enforced);
2808 key_auths.push_back(characteristics->sw_enforced);
2809 keymaster::AuthorizationSet operation_params(inParams);
2810 err = enforcement_policy.AuthorizeOperation(purpose, keyid, key_auths, operation_params,
2811 handle, false /* is_begin_operation */);
2812 if (err) {
2813 result->resultCode = err;
2814 return;
2815 }
2816
Chad Brubaker0d33e0b2015-05-29 12:30:19 -07002817 err = dev->finish(dev, handle, &inParams, &input, &outParams, &output);
Chad Brubaker40a1a9b2015-02-20 14:08:13 -08002818 // Remove the operation regardless of the result
2819 mOperationMap.removeOperation(token);
Chad Brubaker06801e02015-03-31 15:13:13 -07002820 mAuthTokenTable.MarkCompleted(handle);
Chad Brubaker57e106d2015-06-01 12:59:00 -07002821
2822 result->data.reset(const_cast<uint8_t*>(output.data));
2823 result->dataLength = output.data_length;
Chad Brubaker40a1a9b2015-02-20 14:08:13 -08002824 result->resultCode = err ? (int32_t) err : ::NO_ERROR;
Chad Brubaker57e106d2015-06-01 12:59:00 -07002825 if (outParams.params) {
2826 result->outParams.params.assign(outParams.params, outParams.params + outParams.length);
2827 free(outParams.params);
2828 }
Chad Brubaker9899d6b2015-02-03 13:03:00 -08002829 }
2830
Chad Brubaker40a1a9b2015-02-20 14:08:13 -08002831 int32_t abort(const sp<IBinder>& token) {
2832 const keymaster1_device_t* dev;
2833 keymaster_operation_handle_t handle;
Shawn Willdenb2ffa422015-06-17 12:18:55 -06002834 keymaster_purpose_t purpose;
Shawn Willden9221bff2015-06-18 18:23:54 -06002835 keymaster::km_id_t keyid;
2836 if (!mOperationMap.getOperation(token, &handle, &keyid, &purpose, &dev, NULL)) {
Chad Brubaker40a1a9b2015-02-20 14:08:13 -08002837 return KM_ERROR_INVALID_OPERATION_HANDLE;
2838 }
2839 mOperationMap.removeOperation(token);
Chad Brubaker06801e02015-03-31 15:13:13 -07002840 int32_t rc;
Chad Brubaker40a1a9b2015-02-20 14:08:13 -08002841 if (!dev->abort) {
Chad Brubaker06801e02015-03-31 15:13:13 -07002842 rc = KM_ERROR_UNIMPLEMENTED;
2843 } else {
2844 rc = dev->abort(dev, handle);
Chad Brubaker40a1a9b2015-02-20 14:08:13 -08002845 }
Chad Brubaker06801e02015-03-31 15:13:13 -07002846 mAuthTokenTable.MarkCompleted(handle);
Chad Brubaker40a1a9b2015-02-20 14:08:13 -08002847 if (rc) {
2848 return rc;
2849 }
2850 return ::NO_ERROR;
Chad Brubaker9899d6b2015-02-03 13:03:00 -08002851 }
2852
Chad Brubaker2ed2baa2015-03-21 21:20:10 -07002853 bool isOperationAuthorized(const sp<IBinder>& token) {
2854 const keymaster1_device_t* dev;
2855 keymaster_operation_handle_t handle;
Chad Brubakerad6514a2015-04-09 14:00:26 -07002856 const keymaster_key_characteristics_t* characteristics;
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, &characteristics)) {
Chad Brubaker2ed2baa2015-03-21 21:20:10 -07002860 return false;
2861 }
Chad Brubaker0cf34a22015-04-23 11:06:16 -07002862 const hw_auth_token_t* authToken = NULL;
2863 mOperationMap.getOperationAuthToken(token, &authToken);
Chad Brubaker06801e02015-03-31 15:13:13 -07002864 std::vector<keymaster_key_param_t> ignored;
Chad Brubaker0cf34a22015-04-23 11:06:16 -07002865 int32_t authResult = addOperationAuthTokenIfNeeded(token, &ignored);
2866 return authResult == ::NO_ERROR;
Chad Brubaker2ed2baa2015-03-21 21:20:10 -07002867 }
2868
Chad Brubakerd80c7b42015-03-31 11:04:28 -07002869 int32_t addAuthToken(const uint8_t* token, size_t length) {
Chad Brubaker9489b792015-04-14 11:01:45 -07002870 if (!checkBinderPermission(P_ADD_AUTH)) {
2871 ALOGW("addAuthToken: permission denied for %d",
2872 IPCThreadState::self()->getCallingUid());
Chad Brubakerd80c7b42015-03-31 11:04:28 -07002873 return ::PERMISSION_DENIED;
2874 }
2875 if (length != sizeof(hw_auth_token_t)) {
2876 return KM_ERROR_INVALID_ARGUMENT;
2877 }
2878 hw_auth_token_t* authToken = new hw_auth_token_t;
2879 memcpy(reinterpret_cast<void*>(authToken), token, sizeof(hw_auth_token_t));
2880 // The table takes ownership of authToken.
2881 mAuthTokenTable.AddAuthenticationToken(authToken);
2882 return ::NO_ERROR;
Chad Brubaker2ed2baa2015-03-21 21:20:10 -07002883 }
2884
Kenny Root07438c82012-11-02 15:41:02 -07002885private:
Chad Brubaker9489b792015-04-14 11:01:45 -07002886 static const int32_t UID_SELF = -1;
2887
2888 /**
2889 * Get the effective target uid for a binder operation that takes an
2890 * optional uid as the target.
2891 */
2892 inline uid_t getEffectiveUid(int32_t targetUid) {
2893 if (targetUid == UID_SELF) {
2894 return IPCThreadState::self()->getCallingUid();
2895 }
2896 return static_cast<uid_t>(targetUid);
2897 }
2898
2899 /**
2900 * Check if the caller of the current binder method has the required
2901 * permission and if acting on other uids the grants to do so.
2902 */
2903 inline bool checkBinderPermission(perm_t permission, int32_t targetUid = UID_SELF) {
2904 uid_t callingUid = IPCThreadState::self()->getCallingUid();
2905 pid_t spid = IPCThreadState::self()->getCallingPid();
2906 if (!has_permission(callingUid, permission, spid)) {
2907 ALOGW("permission %s denied for %d", get_perm_label(permission), callingUid);
2908 return false;
2909 }
2910 if (!is_granted_to(callingUid, getEffectiveUid(targetUid))) {
2911 ALOGW("uid %d not granted to act for %d", callingUid, targetUid);
2912 return false;
2913 }
2914 return true;
2915 }
2916
2917 /**
2918 * Check if the caller of the current binder method has the required
Chad Brubakerb37a5232015-05-01 10:21:27 -07002919 * permission and the target uid is the caller or the caller is system.
2920 */
2921 inline bool checkBinderPermissionSelfOrSystem(perm_t permission, int32_t targetUid) {
2922 uid_t callingUid = IPCThreadState::self()->getCallingUid();
2923 pid_t spid = IPCThreadState::self()->getCallingPid();
2924 if (!has_permission(callingUid, permission, spid)) {
2925 ALOGW("permission %s denied for %d", get_perm_label(permission), callingUid);
2926 return false;
2927 }
2928 return getEffectiveUid(targetUid) == callingUid || callingUid == AID_SYSTEM;
2929 }
2930
2931 /**
2932 * Check if the caller of the current binder method has the required
Chad Brubaker9489b792015-04-14 11:01:45 -07002933 * permission or the target of the operation is the caller's uid. This is
2934 * for operation where the permission is only for cross-uid activity and all
2935 * uids are allowed to act on their own (ie: clearing all entries for a
2936 * given uid).
2937 */
2938 inline bool checkBinderPermissionOrSelfTarget(perm_t permission, int32_t targetUid) {
2939 uid_t callingUid = IPCThreadState::self()->getCallingUid();
2940 if (getEffectiveUid(targetUid) == callingUid) {
2941 return true;
2942 } else {
2943 return checkBinderPermission(permission, targetUid);
2944 }
2945 }
2946
2947 /**
2948 * Helper method to check that the caller has the required permission as
2949 * well as the keystore is in the unlocked state if checkUnlocked is true.
2950 *
2951 * Returns NO_ERROR on success, PERMISSION_DENIED on a permission error and
2952 * otherwise the state of keystore when not unlocked and checkUnlocked is
2953 * true.
2954 */
2955 inline int32_t checkBinderPermissionAndKeystoreState(perm_t permission, int32_t targetUid = -1,
2956 bool checkUnlocked = true) {
2957 if (!checkBinderPermission(permission, targetUid)) {
2958 return ::PERMISSION_DENIED;
2959 }
Chad Brubaker72593ee2015-05-12 10:42:00 -07002960 State state = mKeyStore->getState(get_user_id(getEffectiveUid(targetUid)));
Chad Brubaker9489b792015-04-14 11:01:45 -07002961 if (checkUnlocked && !isKeystoreUnlocked(state)) {
2962 return state;
2963 }
2964
2965 return ::NO_ERROR;
2966
2967 }
2968
Kenny Root9d45d1c2013-02-14 10:32:30 -08002969 inline bool isKeystoreUnlocked(State state) {
2970 switch (state) {
2971 case ::STATE_NO_ERROR:
2972 return true;
2973 case ::STATE_UNINITIALIZED:
2974 case ::STATE_LOCKED:
2975 return false;
2976 }
2977 return false;
Kenny Root07438c82012-11-02 15:41:02 -07002978 }
2979
Chad Brubaker67d2a502015-03-11 17:21:18 +00002980 bool isKeyTypeSupported(const keymaster1_device_t* device, keymaster_keypair_t keyType) {
Kenny Root1d448c02013-11-21 10:36:53 -08002981 const int32_t device_api = device->common.module->module_api_version;
2982 if (device_api == KEYMASTER_MODULE_API_VERSION_0_2) {
2983 switch (keyType) {
2984 case TYPE_RSA:
2985 case TYPE_DSA:
2986 case TYPE_EC:
2987 return true;
2988 default:
2989 return false;
2990 }
2991 } else if (device_api >= KEYMASTER_MODULE_API_VERSION_0_3) {
2992 switch (keyType) {
2993 case TYPE_RSA:
2994 return true;
2995 case TYPE_DSA:
2996 return device->flags & KEYMASTER_SUPPORTS_DSA;
2997 case TYPE_EC:
2998 return device->flags & KEYMASTER_SUPPORTS_EC;
2999 default:
3000 return false;
3001 }
3002 } else {
3003 return keyType == TYPE_RSA;
3004 }
3005 }
3006
Chad Brubaker0cf34a22015-04-23 11:06:16 -07003007 /**
3008 * Check that all keymaster_key_param_t's provided by the application are
3009 * allowed. Any parameter that keystore adds itself should be disallowed here.
3010 */
3011 bool checkAllowedOperationParams(const std::vector<keymaster_key_param_t>& params) {
3012 for (auto param: params) {
3013 switch (param.tag) {
3014 case KM_TAG_AUTH_TOKEN:
3015 return false;
3016 default:
3017 break;
3018 }
3019 }
3020 return true;
3021 }
3022
3023 keymaster_error_t getOperationCharacteristics(const keymaster_key_blob_t& key,
3024 const keymaster1_device_t* dev,
3025 const std::vector<keymaster_key_param_t>& params,
3026 keymaster_key_characteristics_t* out) {
3027 UniquePtr<keymaster_blob_t> appId;
3028 UniquePtr<keymaster_blob_t> appData;
3029 for (auto param : params) {
3030 if (param.tag == KM_TAG_APPLICATION_ID) {
3031 appId.reset(new keymaster_blob_t);
3032 appId->data = param.blob.data;
3033 appId->data_length = param.blob.data_length;
3034 } else if (param.tag == KM_TAG_APPLICATION_DATA) {
3035 appData.reset(new keymaster_blob_t);
3036 appData->data = param.blob.data;
3037 appData->data_length = param.blob.data_length;
3038 }
3039 }
3040 keymaster_key_characteristics_t* result = NULL;
3041 if (!dev->get_key_characteristics) {
3042 return KM_ERROR_UNIMPLEMENTED;
3043 }
3044 keymaster_error_t error = dev->get_key_characteristics(dev, &key, appId.get(),
3045 appData.get(), &result);
3046 if (result) {
3047 *out = *result;
3048 free(result);
3049 }
3050 return error;
3051 }
3052
3053 /**
3054 * Get the auth token for this operation from the auth token table.
3055 *
3056 * Returns ::NO_ERROR if the auth token was set or none was required.
3057 * ::OP_AUTH_NEEDED if it is a per op authorization, no
3058 * authorization token exists for that operation and
3059 * failOnTokenMissing is false.
3060 * KM_ERROR_KEY_USER_NOT_AUTHENTICATED if there is no valid auth
3061 * token for the operation
3062 */
3063 int32_t getAuthToken(const keymaster_key_characteristics_t* characteristics,
3064 keymaster_operation_handle_t handle,
Shawn Willdenb2ffa422015-06-17 12:18:55 -06003065 keymaster_purpose_t purpose,
Chad Brubaker0cf34a22015-04-23 11:06:16 -07003066 const hw_auth_token_t** authToken,
3067 bool failOnTokenMissing = true) {
3068
3069 std::vector<keymaster_key_param_t> allCharacteristics;
3070 for (size_t i = 0; i < characteristics->sw_enforced.length; i++) {
3071 allCharacteristics.push_back(characteristics->sw_enforced.params[i]);
3072 }
3073 for (size_t i = 0; i < characteristics->hw_enforced.length; i++) {
3074 allCharacteristics.push_back(characteristics->hw_enforced.params[i]);
3075 }
Shawn Willdenb2ffa422015-06-17 12:18:55 -06003076 keymaster::AuthTokenTable::Error err = mAuthTokenTable.FindAuthorization(
3077 allCharacteristics.data(), allCharacteristics.size(), purpose, handle, authToken);
Chad Brubaker0cf34a22015-04-23 11:06:16 -07003078 switch (err) {
3079 case keymaster::AuthTokenTable::OK:
3080 case keymaster::AuthTokenTable::AUTH_NOT_REQUIRED:
3081 return ::NO_ERROR;
3082 case keymaster::AuthTokenTable::AUTH_TOKEN_NOT_FOUND:
3083 case keymaster::AuthTokenTable::AUTH_TOKEN_EXPIRED:
3084 case keymaster::AuthTokenTable::AUTH_TOKEN_WRONG_SID:
3085 return KM_ERROR_KEY_USER_NOT_AUTHENTICATED;
3086 case keymaster::AuthTokenTable::OP_HANDLE_REQUIRED:
3087 return failOnTokenMissing ? (int32_t) KM_ERROR_KEY_USER_NOT_AUTHENTICATED :
3088 (int32_t) ::OP_AUTH_NEEDED;
3089 default:
3090 ALOGE("Unexpected FindAuthorization return value %d", err);
3091 return KM_ERROR_INVALID_ARGUMENT;
3092 }
3093 }
3094
3095 inline void addAuthToParams(std::vector<keymaster_key_param_t>* params,
3096 const hw_auth_token_t* token) {
3097 if (token) {
3098 params->push_back(keymaster_param_blob(KM_TAG_AUTH_TOKEN,
3099 reinterpret_cast<const uint8_t*>(token),
3100 sizeof(hw_auth_token_t)));
3101 }
3102 }
3103
3104 /**
3105 * Add the auth token for the operation to the param list if the operation
3106 * requires authorization. Uses the cached result in the OperationMap if available
3107 * otherwise gets the token from the AuthTokenTable and caches the result.
3108 *
3109 * Returns ::NO_ERROR if the auth token was added or not needed.
3110 * KM_ERROR_KEY_USER_NOT_AUTHENTICATED if the operation is not
3111 * authenticated.
3112 * KM_ERROR_INVALID_OPERATION_HANDLE if token is not a valid
3113 * operation token.
3114 */
3115 int32_t addOperationAuthTokenIfNeeded(sp<IBinder> token,
3116 std::vector<keymaster_key_param_t>* params) {
3117 const hw_auth_token_t* authToken = NULL;
Chad Brubaker7169a842015-04-29 19:58:34 -07003118 mOperationMap.getOperationAuthToken(token, &authToken);
3119 if (!authToken) {
Chad Brubaker0cf34a22015-04-23 11:06:16 -07003120 const keymaster1_device_t* dev;
3121 keymaster_operation_handle_t handle;
3122 const keymaster_key_characteristics_t* characteristics = NULL;
Shawn Willdenb2ffa422015-06-17 12:18:55 -06003123 keymaster_purpose_t purpose;
Shawn Willden9221bff2015-06-18 18:23:54 -06003124 keymaster::km_id_t keyid;
3125 if (!mOperationMap.getOperation(token, &handle, &keyid, &purpose, &dev,
3126 &characteristics)) {
Chad Brubaker0cf34a22015-04-23 11:06:16 -07003127 return KM_ERROR_INVALID_OPERATION_HANDLE;
3128 }
Shawn Willdenb2ffa422015-06-17 12:18:55 -06003129 int32_t result = getAuthToken(characteristics, handle, purpose, &authToken);
Chad Brubaker0cf34a22015-04-23 11:06:16 -07003130 if (result != ::NO_ERROR) {
3131 return result;
3132 }
3133 if (authToken) {
3134 mOperationMap.setOperationAuthToken(token, authToken);
3135 }
3136 }
3137 addAuthToParams(params, authToken);
3138 return ::NO_ERROR;
3139 }
3140
Chad Brubaker3a7d9e62015-06-04 15:01:46 -07003141 /**
3142 * Translate a result value to a legacy return value. All keystore errors are
3143 * preserved and keymaster errors become SYSTEM_ERRORs
3144 */
3145 inline int32_t translateResultToLegacyResult(int32_t result) {
3146 if (result > 0) {
3147 return result;
3148 }
3149 return ::SYSTEM_ERROR;
3150 }
3151
Chad Brubaker3a7d9e62015-06-04 15:01:46 -07003152 keymaster_key_param_t* getKeyAlgorithm(keymaster_key_characteristics_t* characteristics) {
3153 for (size_t i = 0; i < characteristics->hw_enforced.length; i++) {
3154 if (characteristics->hw_enforced.params[i].tag == KM_TAG_ALGORITHM) {
3155 return &characteristics->hw_enforced.params[i];
3156 }
3157 }
3158 for (size_t i = 0; i < characteristics->sw_enforced.length; i++) {
3159 if (characteristics->sw_enforced.params[i].tag == KM_TAG_ALGORITHM) {
3160 return &characteristics->sw_enforced.params[i];
3161 }
3162 }
3163 return NULL;
3164 }
3165
3166 void addLegacyBeginParams(const String16& name, std::vector<keymaster_key_param_t>& params) {
3167 // All legacy keys are DIGEST_NONE/PAD_NONE.
3168 params.push_back(keymaster_param_enum(KM_TAG_DIGEST, KM_DIGEST_NONE));
3169 params.push_back(keymaster_param_enum(KM_TAG_PADDING, KM_PAD_NONE));
3170
3171 // Look up the algorithm of the key.
3172 KeyCharacteristics characteristics;
3173 int32_t rc = getKeyCharacteristics(name, NULL, NULL, &characteristics);
3174 if (rc != ::NO_ERROR) {
3175 ALOGE("Failed to get key characteristics");
3176 return;
3177 }
3178 keymaster_key_param_t* algorithm = getKeyAlgorithm(&characteristics.characteristics);
3179 if (!algorithm) {
3180 ALOGE("getKeyCharacteristics did not include KM_TAG_ALGORITHM");
3181 return;
3182 }
3183 params.push_back(*algorithm);
3184 }
3185
3186 int32_t doLegacySignVerify(const String16& name, const uint8_t* data, size_t length,
3187 uint8_t** out, size_t* outLength, const uint8_t* signature,
3188 size_t signatureLength, keymaster_purpose_t purpose) {
3189
Chad Brubaker3a7d9e62015-06-04 15:01:46 -07003190 std::basic_stringstream<uint8_t> outBuffer;
3191 OperationResult result;
3192 KeymasterArguments inArgs;
3193 addLegacyBeginParams(name, inArgs.params);
3194 sp<IBinder> appToken(new BBinder);
3195 sp<IBinder> token;
3196
3197 begin(appToken, name, purpose, true, inArgs, NULL, 0, &result);
3198 if (result.resultCode != ResponseCode::NO_ERROR) {
Chad Brubakerdf705172015-06-17 20:17:51 -07003199 if (result.resultCode == ::KEY_NOT_FOUND) {
3200 ALOGW("Key not found");
3201 } else {
3202 ALOGW("Error in begin: %d", result.resultCode);
3203 }
Chad Brubaker3a7d9e62015-06-04 15:01:46 -07003204 return translateResultToLegacyResult(result.resultCode);
3205 }
3206 inArgs.params.clear();
3207 token = result.token;
3208 size_t consumed = 0;
3209 size_t lastConsumed = 0;
3210 do {
3211 update(token, inArgs, data + consumed, length - consumed, &result);
3212 if (result.resultCode != ResponseCode::NO_ERROR) {
3213 ALOGW("Error in update: %d", result.resultCode);
3214 return translateResultToLegacyResult(result.resultCode);
3215 }
3216 if (out) {
3217 outBuffer.write(result.data.get(), result.dataLength);
3218 }
3219 lastConsumed = result.inputConsumed;
3220 consumed += lastConsumed;
3221 } while (consumed < length && lastConsumed > 0);
3222
3223 if (consumed != length) {
3224 ALOGW("Not all data consumed. Consumed %zu of %zu", consumed, length);
3225 return ::SYSTEM_ERROR;
3226 }
3227
3228 finish(token, inArgs, signature, signatureLength, NULL, 0, &result);
3229 if (result.resultCode != ResponseCode::NO_ERROR) {
3230 ALOGW("Error in finish: %d", result.resultCode);
3231 return translateResultToLegacyResult(result.resultCode);
3232 }
3233 if (out) {
3234 outBuffer.write(result.data.get(), result.dataLength);
3235 }
3236
3237 if (out) {
3238 auto buf = outBuffer.str();
3239 *out = new uint8_t[buf.size()];
3240 memcpy(*out, buf.c_str(), buf.size());
3241 *outLength = buf.size();
3242 }
3243
3244 return ::NO_ERROR;
3245 }
3246
Kenny Root07438c82012-11-02 15:41:02 -07003247 ::KeyStore* mKeyStore;
Chad Brubaker40a1a9b2015-02-20 14:08:13 -08003248 OperationMap mOperationMap;
Chad Brubakerd80c7b42015-03-31 11:04:28 -07003249 keymaster::AuthTokenTable mAuthTokenTable;
Shawn Willden9221bff2015-06-18 18:23:54 -06003250 KeystoreKeymasterEnforcement enforcement_policy;
Kenny Root07438c82012-11-02 15:41:02 -07003251};
3252
3253}; // namespace android
Kenny Roota91203b2012-02-15 15:00:46 -08003254
3255int main(int argc, char* argv[]) {
Kenny Roota91203b2012-02-15 15:00:46 -08003256 if (argc < 2) {
3257 ALOGE("A directory must be specified!");
3258 return 1;
3259 }
3260 if (chdir(argv[1]) == -1) {
3261 ALOGE("chdir: %s: %s", argv[1], strerror(errno));
3262 return 1;
3263 }
3264
3265 Entropy entropy;
3266 if (!entropy.open()) {
3267 return 1;
3268 }
Kenny Root70e3a862012-02-15 17:20:23 -08003269
Chad Brubakerbd07a232015-06-01 10:44:27 -07003270 keymaster1_device_t* dev;
Kenny Root70e3a862012-02-15 17:20:23 -08003271 if (keymaster_device_initialize(&dev)) {
3272 ALOGE("keystore keymaster could not be initialized; exiting");
3273 return 1;
3274 }
3275
Chad Brubaker67d2a502015-03-11 17:21:18 +00003276 keymaster1_device_t* fallback;
Chad Brubakerfc18edc2015-01-12 15:17:18 -08003277 if (fallback_keymaster_device_initialize(&fallback)) {
3278 ALOGE("software keymaster could not be initialized; exiting");
3279 return 1;
3280 }
3281
Riley Spahneaabae92014-06-30 12:39:52 -07003282 ks_is_selinux_enabled = is_selinux_enabled();
3283 if (ks_is_selinux_enabled) {
3284 union selinux_callback cb;
William Robertse46b8552015-10-02 08:19:52 -07003285 cb.func_audit = audit_callback;
3286 selinux_set_callback(SELINUX_CB_AUDIT, cb);
Riley Spahneaabae92014-06-30 12:39:52 -07003287 cb.func_log = selinux_log_callback;
3288 selinux_set_callback(SELINUX_CB_LOG, cb);
3289 if (getcon(&tctx) != 0) {
3290 ALOGE("SELinux: Could not acquire target context. Aborting keystore.\n");
3291 return -1;
3292 }
3293 } else {
3294 ALOGI("SELinux: Keystore SELinux is disabled.\n");
3295 }
3296
Chad Brubakerbd07a232015-06-01 10:44:27 -07003297 KeyStore keyStore(&entropy, dev, fallback);
Kenny Root655b9582013-04-04 08:37:42 -07003298 keyStore.initialize();
Kenny Root07438c82012-11-02 15:41:02 -07003299 android::sp<android::IServiceManager> sm = android::defaultServiceManager();
3300 android::sp<android::KeyStoreProxy> proxy = new android::KeyStoreProxy(&keyStore);
3301 android::status_t ret = sm->addService(android::String16("android.security.keystore"), proxy);
3302 if (ret != android::OK) {
3303 ALOGE("Couldn't register binder service!");
3304 return -1;
Kenny Roota91203b2012-02-15 15:00:46 -08003305 }
Kenny Root07438c82012-11-02 15:41:02 -07003306
3307 /*
3308 * We're the only thread in existence, so we're just going to process
3309 * Binder transaction as a single-threaded program.
3310 */
3311 android::IPCThreadState::self()->joinThreadPool();
Kenny Root70e3a862012-02-15 17:20:23 -08003312
3313 keymaster_device_release(dev);
Kenny Roota91203b2012-02-15 15:00:46 -08003314 return 1;
3315}