blob: 88a30e86b89cbaae8517fd5d9105223f33c3d521 [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
Shawn Willden447095f2015-10-30 10:05:43 -060082const size_t MAX_OPERATIONS = 15;
Kenny Roota91203b2012-02-15 15:00:46 -080083
Shawn Willden55268b52015-07-28 11:06:00 -060084using keymaster::SoftKeymasterDevice;
Kenny Root822c3a92012-03-23 16:34:39 -070085
Kenny Root96427ba2013-08-16 14:02:41 -070086struct BIGNUM_Delete {
87 void operator()(BIGNUM* p) const {
88 BN_free(p);
89 }
90};
91typedef UniquePtr<BIGNUM, BIGNUM_Delete> Unique_BIGNUM;
92
Kenny Root822c3a92012-03-23 16:34:39 -070093struct BIO_Delete {
94 void operator()(BIO* p) const {
95 BIO_free(p);
96 }
97};
98typedef UniquePtr<BIO, BIO_Delete> Unique_BIO;
99
100struct EVP_PKEY_Delete {
101 void operator()(EVP_PKEY* p) const {
102 EVP_PKEY_free(p);
103 }
104};
105typedef UniquePtr<EVP_PKEY, EVP_PKEY_Delete> Unique_EVP_PKEY;
106
107struct PKCS8_PRIV_KEY_INFO_Delete {
108 void operator()(PKCS8_PRIV_KEY_INFO* p) const {
109 PKCS8_PRIV_KEY_INFO_free(p);
110 }
111};
112typedef UniquePtr<PKCS8_PRIV_KEY_INFO, PKCS8_PRIV_KEY_INFO_Delete> Unique_PKCS8_PRIV_KEY_INFO;
113
Shawn Willden55268b52015-07-28 11:06:00 -0600114static int keymaster0_device_initialize(const hw_module_t* mod, keymaster1_device_t** dev) {
115 assert(mod->module_api_version < KEYMASTER_MODULE_API_VERSION_1_0);
116 ALOGI("Found keymaster0 module %s, version %x", mod->name, mod->module_api_version);
Kenny Root70e3a862012-02-15 17:20:23 -0800117
Shawn Willden55268b52015-07-28 11:06:00 -0600118 UniquePtr<SoftKeymasterDevice> soft_keymaster(new SoftKeymasterDevice);
119 keymaster0_device_t* km0_device = NULL;
120 keymaster_error_t error = KM_ERROR_OK;
121
122 int rc = keymaster0_open(mod, &km0_device);
Kenny Root70e3a862012-02-15 17:20:23 -0800123 if (rc) {
Shawn Willden55268b52015-07-28 11:06:00 -0600124 ALOGE("Error opening keystore keymaster0 device.");
125 goto err;
Kenny Root70e3a862012-02-15 17:20:23 -0800126 }
127
Shawn Willden55268b52015-07-28 11:06:00 -0600128 if (km0_device->flags & KEYMASTER_SOFTWARE_ONLY) {
129 ALOGI("Keymaster0 module is software-only. Using SoftKeymasterDevice instead.");
130 km0_device->common.close(&km0_device->common);
131 km0_device = NULL;
132 // SoftKeymasterDevice will be deleted by keymaster_device_release()
133 *dev = soft_keymaster.release()->keymaster_device();
Chad Brubakerbd07a232015-06-01 10:44:27 -0700134 return 0;
135 }
Shawn Willden55268b52015-07-28 11:06:00 -0600136
137 ALOGE("Wrapping keymaster0 module %s with SoftKeymasterDevice", mod->name);
138 error = soft_keymaster->SetHardwareDevice(km0_device);
139 km0_device = NULL; // SoftKeymasterDevice has taken ownership.
140 if (error != KM_ERROR_OK) {
141 ALOGE("Got error %d from SetHardwareDevice", error);
142 rc = error;
143 goto err;
144 }
145
146 // SoftKeymasterDevice will be deleted by keymaster_device_release()
147 *dev = soft_keymaster.release()->keymaster_device();
Kenny Root70e3a862012-02-15 17:20:23 -0800148 return 0;
149
Shawn Willden55268b52015-07-28 11:06:00 -0600150err:
151 if (km0_device)
152 km0_device->common.close(&km0_device->common);
Kenny Root70e3a862012-02-15 17:20:23 -0800153 *dev = NULL;
154 return rc;
155}
156
Shawn Willden55268b52015-07-28 11:06:00 -0600157static int keymaster1_device_initialize(const hw_module_t* mod, keymaster1_device_t** dev) {
158 assert(mod->module_api_version >= KEYMASTER_MODULE_API_VERSION_1_0);
159 ALOGI("Found keymaster1 module %s, version %x", mod->name, mod->module_api_version);
160
161 UniquePtr<SoftKeymasterDevice> soft_keymaster(new SoftKeymasterDevice);
162 keymaster1_device_t* km1_device = NULL;
163 keymaster_error_t error = KM_ERROR_OK;
164
165 int rc = keymaster1_open(mod, &km1_device);
166 if (rc) {
167 ALOGE("Error %d opening keystore keymaster1 device", rc);
168 goto err;
169 }
170
171 error = soft_keymaster->SetHardwareDevice(km1_device);
172 km1_device = NULL; // SoftKeymasterDevice has taken ownership.
173 if (error != KM_ERROR_OK) {
174 ALOGE("Got error %d from SetHardwareDevice", error);
175 rc = error;
176 goto err;
177 }
178
179 if (!soft_keymaster->Keymaster1DeviceIsGood()) {
180 ALOGI("Keymaster1 module is incomplete, using SoftKeymasterDevice wrapper");
181 // SoftKeymasterDevice will be deleted by keymaster_device_release()
182 *dev = soft_keymaster.release()->keymaster_device();
183 return 0;
184 } else {
185 ALOGI("Keymaster1 module is good, destroying wrapper and re-opening");
186 soft_keymaster.reset(NULL);
187 rc = keymaster1_open(mod, &km1_device);
188 if (rc) {
189 ALOGE("Error %d re-opening keystore keymaster1 device.", rc);
190 goto err;
191 }
192 *dev = km1_device;
193 return 0;
194 }
195
196err:
197 if (km1_device)
198 km1_device->common.close(&km1_device->common);
199 *dev = NULL;
200 return rc;
201
202}
203
204static int keymaster_device_initialize(keymaster1_device_t** dev) {
205 const hw_module_t* mod;
206
207 int rc = hw_get_module_by_class(KEYSTORE_HARDWARE_MODULE_ID, NULL, &mod);
208 if (rc) {
209 ALOGI("Could not find any keystore module, using software-only implementation.");
210 // SoftKeymasterDevice will be deleted by keymaster_device_release()
211 *dev = (new SoftKeymasterDevice)->keymaster_device();
212 return 0;
213 }
214
215 if (mod->module_api_version < KEYMASTER_MODULE_API_VERSION_1_0) {
216 return keymaster0_device_initialize(mod, dev);
217 } else {
218 return keymaster1_device_initialize(mod, dev);
219 }
220}
221
Shawn Willden04006752015-04-30 11:12:33 -0600222// softkeymaster_logger appears not to be used in keystore, but it installs itself as the
223// logger used by SoftKeymasterDevice.
224static keymaster::SoftKeymasterLogger softkeymaster_logger;
225
Chad Brubaker67d2a502015-03-11 17:21:18 +0000226static int fallback_keymaster_device_initialize(keymaster1_device_t** dev) {
Shawn Willden55268b52015-07-28 11:06:00 -0600227 *dev = (new SoftKeymasterDevice)->keymaster_device();
228 // SoftKeymasterDevice will be deleted by keymaster_device_release()
Chad Brubakerfc18edc2015-01-12 15:17:18 -0800229 return 0;
Chad Brubakerfc18edc2015-01-12 15:17:18 -0800230}
231
Chad Brubakerbd07a232015-06-01 10:44:27 -0700232static void keymaster_device_release(keymaster1_device_t* dev) {
233 dev->common.close(&dev->common);
Kenny Root70e3a862012-02-15 17:20:23 -0800234}
235
Shawn Willden55268b52015-07-28 11:06:00 -0600236static void add_legacy_key_authorizations(int keyType, std::vector<keymaster_key_param_t>* params) {
237 params->push_back(keymaster_param_enum(KM_TAG_PURPOSE, KM_PURPOSE_SIGN));
238 params->push_back(keymaster_param_enum(KM_TAG_PURPOSE, KM_PURPOSE_VERIFY));
239 params->push_back(keymaster_param_enum(KM_TAG_PURPOSE, KM_PURPOSE_ENCRYPT));
240 params->push_back(keymaster_param_enum(KM_TAG_PURPOSE, KM_PURPOSE_DECRYPT));
241 params->push_back(keymaster_param_enum(KM_TAG_PADDING, KM_PAD_NONE));
242 if (keyType == EVP_PKEY_RSA) {
243 params->push_back(keymaster_param_enum(KM_TAG_PADDING, KM_PAD_RSA_PKCS1_1_5_SIGN));
244 params->push_back(keymaster_param_enum(KM_TAG_PADDING, KM_PAD_RSA_PKCS1_1_5_ENCRYPT));
245 params->push_back(keymaster_param_enum(KM_TAG_PADDING, KM_PAD_RSA_PSS));
246 params->push_back(keymaster_param_enum(KM_TAG_PADDING, KM_PAD_RSA_OAEP));
247 }
248 params->push_back(keymaster_param_enum(KM_TAG_DIGEST, KM_DIGEST_NONE));
249 params->push_back(keymaster_param_enum(KM_TAG_DIGEST, KM_DIGEST_MD5));
250 params->push_back(keymaster_param_enum(KM_TAG_DIGEST, KM_DIGEST_SHA1));
251 params->push_back(keymaster_param_enum(KM_TAG_DIGEST, KM_DIGEST_SHA_2_224));
252 params->push_back(keymaster_param_enum(KM_TAG_DIGEST, KM_DIGEST_SHA_2_256));
253 params->push_back(keymaster_param_enum(KM_TAG_DIGEST, KM_DIGEST_SHA_2_384));
254 params->push_back(keymaster_param_enum(KM_TAG_DIGEST, KM_DIGEST_SHA_2_512));
255 params->push_back(keymaster_param_bool(KM_TAG_ALL_USERS));
256 params->push_back(keymaster_param_bool(KM_TAG_NO_AUTH_REQUIRED));
257 params->push_back(keymaster_param_date(KM_TAG_ORIGINATION_EXPIRE_DATETIME, LLONG_MAX));
258 params->push_back(keymaster_param_date(KM_TAG_USAGE_EXPIRE_DATETIME, LLONG_MAX));
259 params->push_back(keymaster_param_date(KM_TAG_ACTIVE_DATETIME, 0));
260 uint64_t now = keymaster::java_time(time(NULL));
261 params->push_back(keymaster_param_date(KM_TAG_CREATION_DATETIME, now));
262}
263
Kenny Root07438c82012-11-02 15:41:02 -0700264/***************
265 * PERMISSIONS *
266 ***************/
267
268/* Here are the permissions, actions, users, and the main function. */
269typedef enum {
Chad Brubakere6c3bfa2015-05-12 15:18:26 -0700270 P_GET_STATE = 1 << 0,
Robin Lee4e865752014-08-19 17:37:55 +0100271 P_GET = 1 << 1,
272 P_INSERT = 1 << 2,
273 P_DELETE = 1 << 3,
274 P_EXIST = 1 << 4,
Chad Brubakere6c3bfa2015-05-12 15:18:26 -0700275 P_LIST = 1 << 5,
Robin Lee4e865752014-08-19 17:37:55 +0100276 P_RESET = 1 << 6,
277 P_PASSWORD = 1 << 7,
278 P_LOCK = 1 << 8,
279 P_UNLOCK = 1 << 9,
Chad Brubakere6c3bfa2015-05-12 15:18:26 -0700280 P_IS_EMPTY = 1 << 10,
Robin Lee4e865752014-08-19 17:37:55 +0100281 P_SIGN = 1 << 11,
282 P_VERIFY = 1 << 12,
283 P_GRANT = 1 << 13,
284 P_DUPLICATE = 1 << 14,
285 P_CLEAR_UID = 1 << 15,
Chad Brubakere6c3bfa2015-05-12 15:18:26 -0700286 P_ADD_AUTH = 1 << 16,
287 P_USER_CHANGED = 1 << 17,
Kenny Root07438c82012-11-02 15:41:02 -0700288} perm_t;
289
290static struct user_euid {
291 uid_t uid;
292 uid_t euid;
293} user_euids[] = {
294 {AID_VPN, AID_SYSTEM},
295 {AID_WIFI, AID_SYSTEM},
296 {AID_ROOT, AID_SYSTEM},
297};
298
Riley Spahneaabae92014-06-30 12:39:52 -0700299/* perm_labels associcated with keystore_key SELinux class verbs. */
300const char *perm_labels[] = {
Chad Brubakere6c3bfa2015-05-12 15:18:26 -0700301 "get_state",
Riley Spahneaabae92014-06-30 12:39:52 -0700302 "get",
303 "insert",
304 "delete",
305 "exist",
Chad Brubakere6c3bfa2015-05-12 15:18:26 -0700306 "list",
Riley Spahneaabae92014-06-30 12:39:52 -0700307 "reset",
308 "password",
309 "lock",
310 "unlock",
Chad Brubakere6c3bfa2015-05-12 15:18:26 -0700311 "is_empty",
Riley Spahneaabae92014-06-30 12:39:52 -0700312 "sign",
313 "verify",
314 "grant",
315 "duplicate",
Robin Lee4e865752014-08-19 17:37:55 +0100316 "clear_uid",
Chad Brubakerd80c7b42015-03-31 11:04:28 -0700317 "add_auth",
Chad Brubakerc0f031a2015-05-12 10:43:10 -0700318 "user_changed",
Riley Spahneaabae92014-06-30 12:39:52 -0700319};
320
Kenny Root07438c82012-11-02 15:41:02 -0700321static struct user_perm {
322 uid_t uid;
323 perm_t perms;
324} user_perms[] = {
325 {AID_SYSTEM, static_cast<perm_t>((uint32_t)(~0)) },
326 {AID_VPN, static_cast<perm_t>(P_GET | P_SIGN | P_VERIFY) },
327 {AID_WIFI, static_cast<perm_t>(P_GET | P_SIGN | P_VERIFY) },
328 {AID_ROOT, static_cast<perm_t>(P_GET) },
329};
330
Chad Brubakere6c3bfa2015-05-12 15:18:26 -0700331static const perm_t DEFAULT_PERMS = static_cast<perm_t>(P_GET_STATE | P_GET | P_INSERT | P_DELETE
332 | P_EXIST | P_LIST | P_SIGN | P_VERIFY);
Kenny Root07438c82012-11-02 15:41:02 -0700333
William Robertse46b8552015-10-02 08:19:52 -0700334struct audit_data {
335 pid_t pid;
336 uid_t uid;
337};
338
Riley Spahneaabae92014-06-30 12:39:52 -0700339static char *tctx;
340static int ks_is_selinux_enabled;
341
342static const char *get_perm_label(perm_t perm) {
343 unsigned int index = ffs(perm);
344 if (index > 0 && index <= (sizeof(perm_labels) / sizeof(perm_labels[0]))) {
345 return perm_labels[index - 1];
346 } else {
347 ALOGE("Keystore: Failed to retrieve permission label.\n");
348 abort();
349 }
350}
351
Kenny Root655b9582013-04-04 08:37:42 -0700352/**
353 * Returns the app ID (in the Android multi-user sense) for the current
354 * UNIX UID.
355 */
356static uid_t get_app_id(uid_t uid) {
357 return uid % AID_USER;
358}
359
360/**
361 * Returns the user ID (in the Android multi-user sense) for the current
362 * UNIX UID.
363 */
364static uid_t get_user_id(uid_t uid) {
365 return uid / AID_USER;
366}
367
William Robertse46b8552015-10-02 08:19:52 -0700368static int audit_callback(void *data, security_class_t /* cls */, char *buf, size_t len)
369{
370 struct audit_data *ad = reinterpret_cast<struct audit_data *>(data);
371 if (!ad) {
372 ALOGE("No keystore audit data");
373 return 0;
374 }
375
376 snprintf(buf, len, "pid=%d uid=%d", ad->pid, ad->uid);
377 return 0;
378}
379
380static bool keystore_selinux_check_access(uid_t uid, perm_t perm, pid_t spid) {
Riley Spahneaabae92014-06-30 12:39:52 -0700381 if (!ks_is_selinux_enabled) {
382 return true;
383 }
Nick Kralevich66dbf672014-06-30 17:09:14 +0000384
William Robertse46b8552015-10-02 08:19:52 -0700385 audit_data ad;
Riley Spahneaabae92014-06-30 12:39:52 -0700386 char *sctx = NULL;
387 const char *selinux_class = "keystore_key";
388 const char *str_perm = get_perm_label(perm);
389
390 if (!str_perm) {
391 return false;
392 }
393
394 if (getpidcon(spid, &sctx) != 0) {
395 ALOGE("SELinux: Failed to get source pid context.\n");
396 return false;
397 }
398
William Robertse46b8552015-10-02 08:19:52 -0700399 ad.pid = spid;
400 ad.uid = uid;
401
Riley Spahneaabae92014-06-30 12:39:52 -0700402 bool allowed = selinux_check_access(sctx, tctx, selinux_class, str_perm,
William Robertse46b8552015-10-02 08:19:52 -0700403 reinterpret_cast<void *>(&ad)) == 0;
Riley Spahneaabae92014-06-30 12:39:52 -0700404 freecon(sctx);
405 return allowed;
406}
407
408static bool has_permission(uid_t uid, perm_t perm, pid_t spid) {
Kenny Root655b9582013-04-04 08:37:42 -0700409 // All system users are equivalent for multi-user support.
410 if (get_app_id(uid) == AID_SYSTEM) {
411 uid = AID_SYSTEM;
412 }
413
Kenny Root07438c82012-11-02 15:41:02 -0700414 for (size_t i = 0; i < sizeof(user_perms)/sizeof(user_perms[0]); i++) {
415 struct user_perm user = user_perms[i];
416 if (user.uid == uid) {
Riley Spahneaabae92014-06-30 12:39:52 -0700417 return (user.perms & perm) &&
418 keystore_selinux_check_access(uid, perm, spid);
Kenny Root07438c82012-11-02 15:41:02 -0700419 }
420 }
421
Riley Spahneaabae92014-06-30 12:39:52 -0700422 return (DEFAULT_PERMS & perm) &&
423 keystore_selinux_check_access(uid, perm, spid);
Kenny Root07438c82012-11-02 15:41:02 -0700424}
425
Kenny Root49468902013-03-19 13:41:33 -0700426/**
427 * Returns the UID that the callingUid should act as. This is here for
428 * legacy support of the WiFi and VPN systems and should be removed
429 * when WiFi can operate in its own namespace.
430 */
Kenny Root07438c82012-11-02 15:41:02 -0700431static uid_t get_keystore_euid(uid_t uid) {
432 for (size_t i = 0; i < sizeof(user_euids)/sizeof(user_euids[0]); i++) {
433 struct user_euid user = user_euids[i];
434 if (user.uid == uid) {
435 return user.euid;
436 }
437 }
438
439 return uid;
440}
441
Kenny Root49468902013-03-19 13:41:33 -0700442/**
443 * Returns true if the callingUid is allowed to interact in the targetUid's
444 * namespace.
445 */
446static bool is_granted_to(uid_t callingUid, uid_t targetUid) {
Chad Brubaker9489b792015-04-14 11:01:45 -0700447 if (callingUid == targetUid) {
448 return true;
449 }
Kenny Root49468902013-03-19 13:41:33 -0700450 for (size_t i = 0; i < sizeof(user_euids)/sizeof(user_euids[0]); i++) {
451 struct user_euid user = user_euids[i];
452 if (user.euid == callingUid && user.uid == targetUid) {
453 return true;
454 }
455 }
456
457 return false;
458}
459
Kenny Roota91203b2012-02-15 15:00:46 -0800460/* Here is the encoding of keys. This is necessary in order to allow arbitrary
461 * characters in keys. Characters in [0-~] are not encoded. Others are encoded
462 * into two bytes. The first byte is one of [+-.] which represents the first
463 * two bits of the character. The second byte encodes the rest of the bits into
464 * [0-o]. Therefore in the worst case the length of a key gets doubled. Note
465 * that Base64 cannot be used here due to the need of prefix match on keys. */
466
Kenny Root655b9582013-04-04 08:37:42 -0700467static size_t encode_key_length(const android::String8& keyName) {
468 const uint8_t* in = reinterpret_cast<const uint8_t*>(keyName.string());
469 size_t length = keyName.length();
470 for (int i = length; i > 0; --i, ++in) {
471 if (*in < '0' || *in > '~') {
472 ++length;
473 }
474 }
475 return length;
476}
477
Kenny Root07438c82012-11-02 15:41:02 -0700478static int encode_key(char* out, const android::String8& keyName) {
479 const uint8_t* in = reinterpret_cast<const uint8_t*>(keyName.string());
480 size_t length = keyName.length();
Kenny Roota91203b2012-02-15 15:00:46 -0800481 for (int i = length; i > 0; --i, ++in, ++out) {
Kenny Root655b9582013-04-04 08:37:42 -0700482 if (*in < '0' || *in > '~') {
Kenny Roota91203b2012-02-15 15:00:46 -0800483 *out = '+' + (*in >> 6);
484 *++out = '0' + (*in & 0x3F);
485 ++length;
Kenny Root655b9582013-04-04 08:37:42 -0700486 } else {
487 *out = *in;
Kenny Roota91203b2012-02-15 15:00:46 -0800488 }
489 }
490 *out = '\0';
Kenny Root70e3a862012-02-15 17:20:23 -0800491 return length;
492}
493
Kenny Root07438c82012-11-02 15:41:02 -0700494/*
495 * Converts from the "escaped" format on disk to actual name.
496 * This will be smaller than the input string.
497 *
498 * Characters that should combine with the next at the end will be truncated.
499 */
500static size_t decode_key_length(const char* in, size_t length) {
501 size_t outLength = 0;
502
503 for (const char* end = in + length; in < end; in++) {
504 /* This combines with the next character. */
505 if (*in < '0' || *in > '~') {
506 continue;
507 }
508
509 outLength++;
510 }
511 return outLength;
512}
513
514static void decode_key(char* out, const char* in, size_t length) {
515 for (const char* end = in + length; in < end; in++) {
516 if (*in < '0' || *in > '~') {
517 /* Truncate combining characters at the end. */
518 if (in + 1 >= end) {
519 break;
520 }
521
522 *out = (*in++ - '+') << 6;
523 *out++ |= (*in - '0') & 0x3F;
Kenny Roota91203b2012-02-15 15:00:46 -0800524 } else {
Kenny Root07438c82012-11-02 15:41:02 -0700525 *out++ = *in;
Kenny Roota91203b2012-02-15 15:00:46 -0800526 }
527 }
528 *out = '\0';
Kenny Roota91203b2012-02-15 15:00:46 -0800529}
530
531static size_t readFully(int fd, uint8_t* data, size_t size) {
532 size_t remaining = size;
533 while (remaining > 0) {
Kenny Root150ca932012-11-14 14:29:02 -0800534 ssize_t n = TEMP_FAILURE_RETRY(read(fd, data, remaining));
Kenny Root5281edb2012-11-21 15:14:04 -0800535 if (n <= 0) {
Kenny Root150ca932012-11-14 14:29:02 -0800536 return size - remaining;
Kenny Roota91203b2012-02-15 15:00:46 -0800537 }
538 data += n;
539 remaining -= n;
540 }
541 return size;
542}
543
544static size_t writeFully(int fd, uint8_t* data, size_t size) {
545 size_t remaining = size;
546 while (remaining > 0) {
Kenny Root150ca932012-11-14 14:29:02 -0800547 ssize_t n = TEMP_FAILURE_RETRY(write(fd, data, remaining));
548 if (n < 0) {
549 ALOGW("write failed: %s", strerror(errno));
550 return size - remaining;
Kenny Roota91203b2012-02-15 15:00:46 -0800551 }
552 data += n;
553 remaining -= n;
554 }
555 return size;
556}
557
558class Entropy {
559public:
560 Entropy() : mRandom(-1) {}
561 ~Entropy() {
Kenny Root150ca932012-11-14 14:29:02 -0800562 if (mRandom >= 0) {
Kenny Roota91203b2012-02-15 15:00:46 -0800563 close(mRandom);
564 }
565 }
566
567 bool open() {
568 const char* randomDevice = "/dev/urandom";
Kenny Root150ca932012-11-14 14:29:02 -0800569 mRandom = TEMP_FAILURE_RETRY(::open(randomDevice, O_RDONLY));
570 if (mRandom < 0) {
Kenny Roota91203b2012-02-15 15:00:46 -0800571 ALOGE("open: %s: %s", randomDevice, strerror(errno));
572 return false;
573 }
574 return true;
575 }
576
Kenny Root51878182012-03-13 12:53:19 -0700577 bool generate_random_data(uint8_t* data, size_t size) const {
Kenny Roota91203b2012-02-15 15:00:46 -0800578 return (readFully(mRandom, data, size) == size);
579 }
580
581private:
582 int mRandom;
583};
584
585/* Here is the file format. There are two parts in blob.value, the secret and
586 * the description. The secret is stored in ciphertext, and its original size
587 * can be found in blob.length. The description is stored after the secret in
588 * plaintext, and its size is specified in blob.info. The total size of the two
Kenny Root822c3a92012-03-23 16:34:39 -0700589 * parts must be no more than VALUE_SIZE bytes. The first field is the version,
Kenny Rootf9119d62013-04-03 09:22:15 -0700590 * the second is the blob's type, and the third byte is flags. Fields other
Kenny Roota91203b2012-02-15 15:00:46 -0800591 * than blob.info, blob.length, and blob.value are modified by encryptBlob()
592 * and decryptBlob(). Thus they should not be accessed from outside. */
593
Kenny Root822c3a92012-03-23 16:34:39 -0700594/* ** Note to future implementors of encryption: **
595 * Currently this is the construction:
596 * metadata || Enc(MD5(data) || data)
597 *
598 * This should be the construction used for encrypting if re-implementing:
599 *
600 * Derive independent keys for encryption and MAC:
601 * Kenc = AES_encrypt(masterKey, "Encrypt")
602 * Kmac = AES_encrypt(masterKey, "MAC")
603 *
604 * Store this:
605 * metadata || AES_CTR_encrypt(Kenc, rand_IV, data) ||
606 * HMAC(Kmac, metadata || Enc(data))
607 */
Kenny Roota91203b2012-02-15 15:00:46 -0800608struct __attribute__((packed)) blob {
Kenny Root822c3a92012-03-23 16:34:39 -0700609 uint8_t version;
610 uint8_t type;
Kenny Rootf9119d62013-04-03 09:22:15 -0700611 uint8_t flags;
Kenny Roota91203b2012-02-15 15:00:46 -0800612 uint8_t info;
613 uint8_t vector[AES_BLOCK_SIZE];
Kenny Root822c3a92012-03-23 16:34:39 -0700614 uint8_t encrypted[0]; // Marks offset to encrypted data.
Kenny Roota91203b2012-02-15 15:00:46 -0800615 uint8_t digest[MD5_DIGEST_LENGTH];
Kenny Root822c3a92012-03-23 16:34:39 -0700616 uint8_t digested[0]; // Marks offset to digested data.
Kenny Roota91203b2012-02-15 15:00:46 -0800617 int32_t length; // in network byte order when encrypted
618 uint8_t value[VALUE_SIZE + AES_BLOCK_SIZE];
619};
620
Kenny Root822c3a92012-03-23 16:34:39 -0700621typedef enum {
Kenny Rootd53bc922013-03-21 14:10:15 -0700622 TYPE_ANY = 0, // meta type that matches anything
Kenny Root822c3a92012-03-23 16:34:39 -0700623 TYPE_GENERIC = 1,
624 TYPE_MASTER_KEY = 2,
625 TYPE_KEY_PAIR = 3,
Chad Brubaker17d68b92015-02-05 22:04:16 -0800626 TYPE_KEYMASTER_10 = 4,
Kenny Root822c3a92012-03-23 16:34:39 -0700627} BlobType;
628
Kenny Rootf9119d62013-04-03 09:22:15 -0700629static const uint8_t CURRENT_BLOB_VERSION = 2;
Kenny Root822c3a92012-03-23 16:34:39 -0700630
Kenny Roota91203b2012-02-15 15:00:46 -0800631class Blob {
632public:
Chad Brubaker803f37f2015-07-29 13:53:36 -0700633 Blob(const uint8_t* value, size_t valueLength, const uint8_t* info, uint8_t infoLength,
Kenny Root07438c82012-11-02 15:41:02 -0700634 BlobType type) {
Alex Klyubin1773b442015-02-20 12:33:33 -0800635 memset(&mBlob, 0, sizeof(mBlob));
Chad Brubaker54b1e9a2015-08-12 13:40:31 -0700636 if (valueLength > VALUE_SIZE) {
637 valueLength = VALUE_SIZE;
Chad Brubaker803f37f2015-07-29 13:53:36 -0700638 ALOGW("Provided blob length too large");
639 }
Chad Brubaker54b1e9a2015-08-12 13:40:31 -0700640 if (infoLength + valueLength > VALUE_SIZE) {
641 infoLength = VALUE_SIZE - valueLength;
Chad Brubaker803f37f2015-07-29 13:53:36 -0700642 ALOGW("Provided info length too large");
643 }
Kenny Roota91203b2012-02-15 15:00:46 -0800644 mBlob.length = valueLength;
645 memcpy(mBlob.value, value, valueLength);
646
647 mBlob.info = infoLength;
648 memcpy(mBlob.value + valueLength, info, infoLength);
Kenny Root822c3a92012-03-23 16:34:39 -0700649
Kenny Root07438c82012-11-02 15:41:02 -0700650 mBlob.version = CURRENT_BLOB_VERSION;
Kenny Root822c3a92012-03-23 16:34:39 -0700651 mBlob.type = uint8_t(type);
Kenny Rootf9119d62013-04-03 09:22:15 -0700652
Kenny Rootee8068b2013-10-07 09:49:15 -0700653 if (type == TYPE_MASTER_KEY) {
654 mBlob.flags = KEYSTORE_FLAG_ENCRYPTED;
655 } else {
656 mBlob.flags = KEYSTORE_FLAG_NONE;
657 }
Kenny Roota91203b2012-02-15 15:00:46 -0800658 }
659
660 Blob(blob b) {
661 mBlob = b;
662 }
663
Alex Klyubin1773b442015-02-20 12:33:33 -0800664 Blob() {
665 memset(&mBlob, 0, sizeof(mBlob));
666 }
Kenny Roota91203b2012-02-15 15:00:46 -0800667
Kenny Root51878182012-03-13 12:53:19 -0700668 const uint8_t* getValue() const {
Kenny Roota91203b2012-02-15 15:00:46 -0800669 return mBlob.value;
670 }
671
Kenny Root51878182012-03-13 12:53:19 -0700672 int32_t getLength() const {
Kenny Roota91203b2012-02-15 15:00:46 -0800673 return mBlob.length;
674 }
675
Kenny Root51878182012-03-13 12:53:19 -0700676 const uint8_t* getInfo() const {
677 return mBlob.value + mBlob.length;
678 }
679
680 uint8_t getInfoLength() const {
Kenny Roota91203b2012-02-15 15:00:46 -0800681 return mBlob.info;
682 }
683
Kenny Root822c3a92012-03-23 16:34:39 -0700684 uint8_t getVersion() const {
685 return mBlob.version;
686 }
687
Kenny Rootf9119d62013-04-03 09:22:15 -0700688 bool isEncrypted() const {
689 if (mBlob.version < 2) {
690 return true;
691 }
692
693 return mBlob.flags & KEYSTORE_FLAG_ENCRYPTED;
694 }
695
696 void setEncrypted(bool encrypted) {
697 if (encrypted) {
698 mBlob.flags |= KEYSTORE_FLAG_ENCRYPTED;
699 } else {
700 mBlob.flags &= ~KEYSTORE_FLAG_ENCRYPTED;
701 }
702 }
703
Kenny Root17208e02013-09-04 13:56:03 -0700704 bool isFallback() const {
705 return mBlob.flags & KEYSTORE_FLAG_FALLBACK;
706 }
707
708 void setFallback(bool fallback) {
709 if (fallback) {
710 mBlob.flags |= KEYSTORE_FLAG_FALLBACK;
711 } else {
712 mBlob.flags &= ~KEYSTORE_FLAG_FALLBACK;
713 }
714 }
715
Kenny Root822c3a92012-03-23 16:34:39 -0700716 void setVersion(uint8_t version) {
717 mBlob.version = version;
718 }
719
720 BlobType getType() const {
721 return BlobType(mBlob.type);
722 }
723
724 void setType(BlobType type) {
725 mBlob.type = uint8_t(type);
726 }
727
Kenny Rootf9119d62013-04-03 09:22:15 -0700728 ResponseCode writeBlob(const char* filename, AES_KEY *aes_key, State state, Entropy* entropy) {
729 ALOGV("writing blob %s", filename);
730 if (isEncrypted()) {
731 if (state != STATE_NO_ERROR) {
732 ALOGD("couldn't insert encrypted blob while not unlocked");
733 return LOCKED;
734 }
735
736 if (!entropy->generate_random_data(mBlob.vector, AES_BLOCK_SIZE)) {
737 ALOGW("Could not read random data for: %s", filename);
738 return SYSTEM_ERROR;
739 }
Kenny Roota91203b2012-02-15 15:00:46 -0800740 }
741
742 // data includes the value and the value's length
743 size_t dataLength = mBlob.length + sizeof(mBlob.length);
744 // pad data to the AES_BLOCK_SIZE
745 size_t digestedLength = ((dataLength + AES_BLOCK_SIZE - 1)
746 / AES_BLOCK_SIZE * AES_BLOCK_SIZE);
747 // encrypted data includes the digest value
748 size_t encryptedLength = digestedLength + MD5_DIGEST_LENGTH;
749 // move info after space for padding
750 memmove(&mBlob.encrypted[encryptedLength], &mBlob.value[mBlob.length], mBlob.info);
751 // zero padding area
752 memset(mBlob.value + mBlob.length, 0, digestedLength - dataLength);
753
754 mBlob.length = htonl(mBlob.length);
Kenny Roota91203b2012-02-15 15:00:46 -0800755
Kenny Rootf9119d62013-04-03 09:22:15 -0700756 if (isEncrypted()) {
757 MD5(mBlob.digested, digestedLength, mBlob.digest);
Kenny Roota91203b2012-02-15 15:00:46 -0800758
Kenny Rootf9119d62013-04-03 09:22:15 -0700759 uint8_t vector[AES_BLOCK_SIZE];
760 memcpy(vector, mBlob.vector, AES_BLOCK_SIZE);
761 AES_cbc_encrypt(mBlob.encrypted, mBlob.encrypted, encryptedLength,
762 aes_key, vector, AES_ENCRYPT);
763 }
764
Kenny Roota91203b2012-02-15 15:00:46 -0800765 size_t headerLength = (mBlob.encrypted - (uint8_t*) &mBlob);
766 size_t fileLength = encryptedLength + headerLength + mBlob.info;
767
768 const char* tmpFileName = ".tmp";
Kenny Root150ca932012-11-14 14:29:02 -0800769 int out = TEMP_FAILURE_RETRY(open(tmpFileName,
770 O_WRONLY | O_TRUNC | O_CREAT, S_IRUSR | S_IWUSR));
771 if (out < 0) {
772 ALOGW("could not open file: %s: %s", tmpFileName, strerror(errno));
Kenny Roota91203b2012-02-15 15:00:46 -0800773 return SYSTEM_ERROR;
774 }
775 size_t writtenBytes = writeFully(out, (uint8_t*) &mBlob, fileLength);
776 if (close(out) != 0) {
777 return SYSTEM_ERROR;
778 }
779 if (writtenBytes != fileLength) {
Kenny Root150ca932012-11-14 14:29:02 -0800780 ALOGW("blob not fully written %zu != %zu", writtenBytes, fileLength);
Kenny Roota91203b2012-02-15 15:00:46 -0800781 unlink(tmpFileName);
782 return SYSTEM_ERROR;
783 }
Kenny Root150ca932012-11-14 14:29:02 -0800784 if (rename(tmpFileName, filename) == -1) {
785 ALOGW("could not rename blob to %s: %s", filename, strerror(errno));
786 return SYSTEM_ERROR;
787 }
788 return NO_ERROR;
Kenny Roota91203b2012-02-15 15:00:46 -0800789 }
790
Kenny Rootf9119d62013-04-03 09:22:15 -0700791 ResponseCode readBlob(const char* filename, AES_KEY *aes_key, State state) {
792 ALOGV("reading blob %s", filename);
Kenny Root150ca932012-11-14 14:29:02 -0800793 int in = TEMP_FAILURE_RETRY(open(filename, O_RDONLY));
794 if (in < 0) {
Kenny Roota91203b2012-02-15 15:00:46 -0800795 return (errno == ENOENT) ? KEY_NOT_FOUND : SYSTEM_ERROR;
796 }
797 // fileLength may be less than sizeof(mBlob) since the in
798 // memory version has extra padding to tolerate rounding up to
799 // the AES_BLOCK_SIZE
800 size_t fileLength = readFully(in, (uint8_t*) &mBlob, sizeof(mBlob));
801 if (close(in) != 0) {
802 return SYSTEM_ERROR;
803 }
Kenny Rootf9119d62013-04-03 09:22:15 -0700804
Chad Brubakera9a17ee2015-07-17 13:43:24 -0700805 if (fileLength == 0) {
806 return VALUE_CORRUPTED;
807 }
808
Kenny Rootf9119d62013-04-03 09:22:15 -0700809 if (isEncrypted() && (state != STATE_NO_ERROR)) {
810 return LOCKED;
811 }
812
Kenny Roota91203b2012-02-15 15:00:46 -0800813 size_t headerLength = (mBlob.encrypted - (uint8_t*) &mBlob);
814 if (fileLength < headerLength) {
815 return VALUE_CORRUPTED;
816 }
817
818 ssize_t encryptedLength = fileLength - (headerLength + mBlob.info);
Kenny Rootf9119d62013-04-03 09:22:15 -0700819 if (encryptedLength < 0) {
Kenny Roota91203b2012-02-15 15:00:46 -0800820 return VALUE_CORRUPTED;
821 }
Kenny Rootf9119d62013-04-03 09:22:15 -0700822
823 ssize_t digestedLength;
824 if (isEncrypted()) {
825 if (encryptedLength % AES_BLOCK_SIZE != 0) {
826 return VALUE_CORRUPTED;
827 }
828
829 AES_cbc_encrypt(mBlob.encrypted, mBlob.encrypted, encryptedLength, aes_key,
830 mBlob.vector, AES_DECRYPT);
831 digestedLength = encryptedLength - MD5_DIGEST_LENGTH;
832 uint8_t computedDigest[MD5_DIGEST_LENGTH];
833 MD5(mBlob.digested, digestedLength, computedDigest);
834 if (memcmp(mBlob.digest, computedDigest, MD5_DIGEST_LENGTH) != 0) {
835 return VALUE_CORRUPTED;
836 }
837 } else {
838 digestedLength = encryptedLength;
Kenny Roota91203b2012-02-15 15:00:46 -0800839 }
840
841 ssize_t maxValueLength = digestedLength - sizeof(mBlob.length);
842 mBlob.length = ntohl(mBlob.length);
843 if (mBlob.length < 0 || mBlob.length > maxValueLength) {
844 return VALUE_CORRUPTED;
845 }
846 if (mBlob.info != 0) {
847 // move info from after padding to after data
848 memmove(&mBlob.value[mBlob.length], &mBlob.value[maxValueLength], mBlob.info);
849 }
Kenny Root07438c82012-11-02 15:41:02 -0700850 return ::NO_ERROR;
Kenny Roota91203b2012-02-15 15:00:46 -0800851 }
852
853private:
854 struct blob mBlob;
855};
856
Kenny Root655b9582013-04-04 08:37:42 -0700857class UserState {
Kenny Roota91203b2012-02-15 15:00:46 -0800858public:
Kenny Root655b9582013-04-04 08:37:42 -0700859 UserState(uid_t userId) : mUserId(userId), mRetry(MAX_RETRY) {
860 asprintf(&mUserDir, "user_%u", mUserId);
861 asprintf(&mMasterKeyFile, "%s/.masterkey", mUserDir);
862 }
863
864 ~UserState() {
865 free(mUserDir);
866 free(mMasterKeyFile);
867 }
868
869 bool initialize() {
870 if ((mkdir(mUserDir, S_IRUSR | S_IWUSR | S_IXUSR) < 0) && (errno != EEXIST)) {
871 ALOGE("Could not create directory '%s'", mUserDir);
872 return false;
873 }
874
875 if (access(mMasterKeyFile, R_OK) == 0) {
Kenny Roota91203b2012-02-15 15:00:46 -0800876 setState(STATE_LOCKED);
877 } else {
878 setState(STATE_UNINITIALIZED);
879 }
Kenny Root70e3a862012-02-15 17:20:23 -0800880
Kenny Root655b9582013-04-04 08:37:42 -0700881 return true;
882 }
883
884 uid_t getUserId() const {
885 return mUserId;
886 }
887
888 const char* getUserDirName() const {
889 return mUserDir;
890 }
891
892 const char* getMasterKeyFileName() const {
893 return mMasterKeyFile;
894 }
895
896 void setState(State state) {
897 mState = state;
898 if (mState == STATE_NO_ERROR || mState == STATE_UNINITIALIZED) {
899 mRetry = MAX_RETRY;
900 }
Kenny Roota91203b2012-02-15 15:00:46 -0800901 }
902
Kenny Root51878182012-03-13 12:53:19 -0700903 State getState() const {
Kenny Roota91203b2012-02-15 15:00:46 -0800904 return mState;
905 }
906
Kenny Root51878182012-03-13 12:53:19 -0700907 int8_t getRetry() const {
Kenny Roota91203b2012-02-15 15:00:46 -0800908 return mRetry;
909 }
910
Kenny Root655b9582013-04-04 08:37:42 -0700911 void zeroizeMasterKeysInMemory() {
912 memset(mMasterKey, 0, sizeof(mMasterKey));
913 memset(mSalt, 0, sizeof(mSalt));
914 memset(&mMasterKeyEncryption, 0, sizeof(mMasterKeyEncryption));
915 memset(&mMasterKeyDecryption, 0, sizeof(mMasterKeyDecryption));
Kenny Root70e3a862012-02-15 17:20:23 -0800916 }
917
Chad Brubaker96d6d782015-05-07 10:19:40 -0700918 bool deleteMasterKey() {
919 setState(STATE_UNINITIALIZED);
920 zeroizeMasterKeysInMemory();
921 return unlink(mMasterKeyFile) == 0 || errno == ENOENT;
922 }
923
Kenny Root655b9582013-04-04 08:37:42 -0700924 ResponseCode initialize(const android::String8& pw, Entropy* entropy) {
925 if (!generateMasterKey(entropy)) {
Kenny Roota91203b2012-02-15 15:00:46 -0800926 return SYSTEM_ERROR;
927 }
Kenny Root655b9582013-04-04 08:37:42 -0700928 ResponseCode response = writeMasterKey(pw, entropy);
Kenny Roota91203b2012-02-15 15:00:46 -0800929 if (response != NO_ERROR) {
930 return response;
931 }
932 setupMasterKeys();
Kenny Root07438c82012-11-02 15:41:02 -0700933 return ::NO_ERROR;
Kenny Roota91203b2012-02-15 15:00:46 -0800934 }
935
Robin Lee4e865752014-08-19 17:37:55 +0100936 ResponseCode copyMasterKey(UserState* src) {
937 if (mState != STATE_UNINITIALIZED) {
938 return ::SYSTEM_ERROR;
939 }
940 if (src->getState() != STATE_NO_ERROR) {
941 return ::SYSTEM_ERROR;
942 }
943 memcpy(mMasterKey, src->mMasterKey, MASTER_KEY_SIZE_BYTES);
944 setupMasterKeys();
945 return ::NO_ERROR;
946 }
947
Kenny Root655b9582013-04-04 08:37:42 -0700948 ResponseCode writeMasterKey(const android::String8& pw, Entropy* entropy) {
Kenny Roota91203b2012-02-15 15:00:46 -0800949 uint8_t passwordKey[MASTER_KEY_SIZE_BYTES];
950 generateKeyFromPassword(passwordKey, MASTER_KEY_SIZE_BYTES, pw, mSalt);
951 AES_KEY passwordAesKey;
952 AES_set_encrypt_key(passwordKey, MASTER_KEY_SIZE_BITS, &passwordAesKey);
Kenny Root822c3a92012-03-23 16:34:39 -0700953 Blob masterKeyBlob(mMasterKey, sizeof(mMasterKey), mSalt, sizeof(mSalt), TYPE_MASTER_KEY);
Kenny Rootf9119d62013-04-03 09:22:15 -0700954 return masterKeyBlob.writeBlob(mMasterKeyFile, &passwordAesKey, STATE_NO_ERROR, entropy);
Kenny Roota91203b2012-02-15 15:00:46 -0800955 }
956
Kenny Root655b9582013-04-04 08:37:42 -0700957 ResponseCode readMasterKey(const android::String8& pw, Entropy* entropy) {
958 int in = TEMP_FAILURE_RETRY(open(mMasterKeyFile, O_RDONLY));
Kenny Root150ca932012-11-14 14:29:02 -0800959 if (in < 0) {
Kenny Roota91203b2012-02-15 15:00:46 -0800960 return SYSTEM_ERROR;
961 }
962
963 // we read the raw blob to just to get the salt to generate
964 // the AES key, then we create the Blob to use with decryptBlob
965 blob rawBlob;
966 size_t length = readFully(in, (uint8_t*) &rawBlob, sizeof(rawBlob));
967 if (close(in) != 0) {
968 return SYSTEM_ERROR;
969 }
970 // find salt at EOF if present, otherwise we have an old file
971 uint8_t* salt;
972 if (length > SALT_SIZE && rawBlob.info == SALT_SIZE) {
973 salt = (uint8_t*) &rawBlob + length - SALT_SIZE;
974 } else {
975 salt = NULL;
976 }
977 uint8_t passwordKey[MASTER_KEY_SIZE_BYTES];
978 generateKeyFromPassword(passwordKey, MASTER_KEY_SIZE_BYTES, pw, salt);
979 AES_KEY passwordAesKey;
980 AES_set_decrypt_key(passwordKey, MASTER_KEY_SIZE_BITS, &passwordAesKey);
981 Blob masterKeyBlob(rawBlob);
Kenny Rootf9119d62013-04-03 09:22:15 -0700982 ResponseCode response = masterKeyBlob.readBlob(mMasterKeyFile, &passwordAesKey,
983 STATE_NO_ERROR);
Kenny Roota91203b2012-02-15 15:00:46 -0800984 if (response == SYSTEM_ERROR) {
Kenny Rootf9119d62013-04-03 09:22:15 -0700985 return response;
Kenny Roota91203b2012-02-15 15:00:46 -0800986 }
987 if (response == NO_ERROR && masterKeyBlob.getLength() == MASTER_KEY_SIZE_BYTES) {
988 // if salt was missing, generate one and write a new master key file with the salt.
989 if (salt == NULL) {
Kenny Root655b9582013-04-04 08:37:42 -0700990 if (!generateSalt(entropy)) {
Kenny Roota91203b2012-02-15 15:00:46 -0800991 return SYSTEM_ERROR;
992 }
Kenny Root655b9582013-04-04 08:37:42 -0700993 response = writeMasterKey(pw, entropy);
Kenny Roota91203b2012-02-15 15:00:46 -0800994 }
995 if (response == NO_ERROR) {
996 memcpy(mMasterKey, masterKeyBlob.getValue(), MASTER_KEY_SIZE_BYTES);
997 setupMasterKeys();
998 }
999 return response;
1000 }
1001 if (mRetry <= 0) {
1002 reset();
1003 return UNINITIALIZED;
1004 }
1005 --mRetry;
1006 switch (mRetry) {
1007 case 0: return WRONG_PASSWORD_0;
1008 case 1: return WRONG_PASSWORD_1;
1009 case 2: return WRONG_PASSWORD_2;
1010 case 3: return WRONG_PASSWORD_3;
1011 default: return WRONG_PASSWORD_3;
1012 }
1013 }
1014
Kenny Root655b9582013-04-04 08:37:42 -07001015 AES_KEY* getEncryptionKey() {
1016 return &mMasterKeyEncryption;
1017 }
1018
1019 AES_KEY* getDecryptionKey() {
1020 return &mMasterKeyDecryption;
1021 }
1022
Kenny Roota91203b2012-02-15 15:00:46 -08001023 bool reset() {
Kenny Root655b9582013-04-04 08:37:42 -07001024 DIR* dir = opendir(getUserDirName());
Kenny Roota91203b2012-02-15 15:00:46 -08001025 if (!dir) {
Chad Brubaker96d6d782015-05-07 10:19:40 -07001026 // If the directory doesn't exist then nothing to do.
1027 if (errno == ENOENT) {
1028 return true;
1029 }
Kenny Root655b9582013-04-04 08:37:42 -07001030 ALOGW("couldn't open user directory: %s", strerror(errno));
Kenny Roota91203b2012-02-15 15:00:46 -08001031 return false;
1032 }
Kenny Root655b9582013-04-04 08:37:42 -07001033
1034 struct dirent* file;
Kenny Roota91203b2012-02-15 15:00:46 -08001035 while ((file = readdir(dir)) != NULL) {
Chad Brubaker96d6d782015-05-07 10:19:40 -07001036 // skip . and ..
1037 if (!strcmp(".", file->d_name) || !strcmp("..", file->d_name)) {
Kenny Root655b9582013-04-04 08:37:42 -07001038 continue;
1039 }
1040
1041 unlinkat(dirfd(dir), file->d_name, 0);
Kenny Roota91203b2012-02-15 15:00:46 -08001042 }
1043 closedir(dir);
1044 return true;
1045 }
1046
Kenny Root655b9582013-04-04 08:37:42 -07001047private:
1048 static const int MASTER_KEY_SIZE_BYTES = 16;
1049 static const int MASTER_KEY_SIZE_BITS = MASTER_KEY_SIZE_BYTES * 8;
1050
1051 static const int MAX_RETRY = 4;
1052 static const size_t SALT_SIZE = 16;
1053
1054 void generateKeyFromPassword(uint8_t* key, ssize_t keySize, const android::String8& pw,
1055 uint8_t* salt) {
1056 size_t saltSize;
1057 if (salt != NULL) {
1058 saltSize = SALT_SIZE;
1059 } else {
1060 // pre-gingerbread used this hardwired salt, readMasterKey will rewrite these when found
1061 salt = (uint8_t*) "keystore";
1062 // sizeof = 9, not strlen = 8
1063 saltSize = sizeof("keystore");
1064 }
1065
1066 PKCS5_PBKDF2_HMAC_SHA1(reinterpret_cast<const char*>(pw.string()), pw.length(), salt,
1067 saltSize, 8192, keySize, key);
1068 }
1069
1070 bool generateSalt(Entropy* entropy) {
1071 return entropy->generate_random_data(mSalt, sizeof(mSalt));
1072 }
1073
1074 bool generateMasterKey(Entropy* entropy) {
1075 if (!entropy->generate_random_data(mMasterKey, sizeof(mMasterKey))) {
1076 return false;
1077 }
1078 if (!generateSalt(entropy)) {
1079 return false;
1080 }
1081 return true;
1082 }
1083
1084 void setupMasterKeys() {
1085 AES_set_encrypt_key(mMasterKey, MASTER_KEY_SIZE_BITS, &mMasterKeyEncryption);
1086 AES_set_decrypt_key(mMasterKey, MASTER_KEY_SIZE_BITS, &mMasterKeyDecryption);
1087 setState(STATE_NO_ERROR);
1088 }
1089
1090 uid_t mUserId;
1091
1092 char* mUserDir;
1093 char* mMasterKeyFile;
1094
1095 State mState;
1096 int8_t mRetry;
1097
1098 uint8_t mMasterKey[MASTER_KEY_SIZE_BYTES];
1099 uint8_t mSalt[SALT_SIZE];
1100
1101 AES_KEY mMasterKeyEncryption;
1102 AES_KEY mMasterKeyDecryption;
1103};
1104
1105typedef struct {
1106 uint32_t uid;
1107 const uint8_t* filename;
1108} grant_t;
1109
1110class KeyStore {
1111public:
Chad Brubaker67d2a502015-03-11 17:21:18 +00001112 KeyStore(Entropy* entropy, keymaster1_device_t* device, keymaster1_device_t* fallback)
Kenny Root655b9582013-04-04 08:37:42 -07001113 : mEntropy(entropy)
1114 , mDevice(device)
Chad Brubakerfc18edc2015-01-12 15:17:18 -08001115 , mFallbackDevice(fallback)
Kenny Root655b9582013-04-04 08:37:42 -07001116 {
1117 memset(&mMetaData, '\0', sizeof(mMetaData));
1118 }
1119
1120 ~KeyStore() {
1121 for (android::Vector<grant_t*>::iterator it(mGrants.begin());
1122 it != mGrants.end(); it++) {
1123 delete *it;
Kenny Root655b9582013-04-04 08:37:42 -07001124 }
haitao fangc35d4eb2013-12-06 11:34:49 +08001125 mGrants.clear();
Kenny Root655b9582013-04-04 08:37:42 -07001126
1127 for (android::Vector<UserState*>::iterator it(mMasterKeys.begin());
1128 it != mMasterKeys.end(); it++) {
1129 delete *it;
Kenny Root655b9582013-04-04 08:37:42 -07001130 }
haitao fangc35d4eb2013-12-06 11:34:49 +08001131 mMasterKeys.clear();
Kenny Root655b9582013-04-04 08:37:42 -07001132 }
1133
Chad Brubaker67d2a502015-03-11 17:21:18 +00001134 /**
1135 * Depending on the hardware keymaster version is this may return a
1136 * keymaster0_device_t* cast to a keymaster1_device_t*. All methods from
1137 * keymaster0 are safe to call, calls to keymaster1_device_t methods should
1138 * be guarded by a check on the device's version.
1139 */
1140 keymaster1_device_t *getDevice() const {
Kenny Root655b9582013-04-04 08:37:42 -07001141 return mDevice;
1142 }
1143
Chad Brubaker67d2a502015-03-11 17:21:18 +00001144 keymaster1_device_t *getFallbackDevice() const {
Chad Brubakerfc18edc2015-01-12 15:17:18 -08001145 return mFallbackDevice;
1146 }
1147
Chad Brubaker67d2a502015-03-11 17:21:18 +00001148 keymaster1_device_t *getDeviceForBlob(const Blob& blob) const {
Chad Brubakerfc18edc2015-01-12 15:17:18 -08001149 return blob.isFallback() ? mFallbackDevice: mDevice;
1150 }
1151
Kenny Root655b9582013-04-04 08:37:42 -07001152 ResponseCode initialize() {
1153 readMetaData();
1154 if (upgradeKeystore()) {
1155 writeMetaData();
1156 }
1157
1158 return ::NO_ERROR;
1159 }
1160
Chad Brubaker72593ee2015-05-12 10:42:00 -07001161 State getState(uid_t userId) {
1162 return getUserState(userId)->getState();
Kenny Root655b9582013-04-04 08:37:42 -07001163 }
1164
Chad Brubaker72593ee2015-05-12 10:42:00 -07001165 ResponseCode initializeUser(const android::String8& pw, uid_t userId) {
1166 UserState* userState = getUserState(userId);
Kenny Root655b9582013-04-04 08:37:42 -07001167 return userState->initialize(pw, mEntropy);
1168 }
1169
Chad Brubaker72593ee2015-05-12 10:42:00 -07001170 ResponseCode copyMasterKey(uid_t srcUser, uid_t dstUser) {
1171 UserState *userState = getUserState(dstUser);
1172 UserState *initState = getUserState(srcUser);
Robin Lee4e865752014-08-19 17:37:55 +01001173 return userState->copyMasterKey(initState);
1174 }
1175
Chad Brubaker72593ee2015-05-12 10:42:00 -07001176 ResponseCode writeMasterKey(const android::String8& pw, uid_t userId) {
1177 UserState* userState = getUserState(userId);
Kenny Root655b9582013-04-04 08:37:42 -07001178 return userState->writeMasterKey(pw, mEntropy);
1179 }
1180
Chad Brubaker72593ee2015-05-12 10:42:00 -07001181 ResponseCode readMasterKey(const android::String8& pw, uid_t userId) {
1182 UserState* userState = getUserState(userId);
Kenny Root655b9582013-04-04 08:37:42 -07001183 return userState->readMasterKey(pw, mEntropy);
1184 }
1185
1186 android::String8 getKeyName(const android::String8& keyName) {
Douglas Leunga77e8092013-06-13 16:34:43 -07001187 char encoded[encode_key_length(keyName) + 1]; // add 1 for null char
Kenny Root655b9582013-04-04 08:37:42 -07001188 encode_key(encoded, keyName);
1189 return android::String8(encoded);
1190 }
1191
1192 android::String8 getKeyNameForUid(const android::String8& keyName, uid_t uid) {
Douglas Leunga77e8092013-06-13 16:34:43 -07001193 char encoded[encode_key_length(keyName) + 1]; // add 1 for null char
Kenny Root655b9582013-04-04 08:37:42 -07001194 encode_key(encoded, keyName);
1195 return android::String8::format("%u_%s", uid, encoded);
1196 }
1197
1198 android::String8 getKeyNameForUidWithDir(const android::String8& keyName, uid_t uid) {
Douglas Leunga77e8092013-06-13 16:34:43 -07001199 char encoded[encode_key_length(keyName) + 1]; // add 1 for null char
Kenny Root655b9582013-04-04 08:37:42 -07001200 encode_key(encoded, keyName);
Chad Brubaker72593ee2015-05-12 10:42:00 -07001201 return android::String8::format("%s/%u_%s", getUserStateByUid(uid)->getUserDirName(), uid,
Kenny Root655b9582013-04-04 08:37:42 -07001202 encoded);
1203 }
1204
Chad Brubaker96d6d782015-05-07 10:19:40 -07001205 /*
1206 * Delete entries owned by userId. If keepUnencryptedEntries is true
1207 * then only encrypted entries will be removed, otherwise all entries will
1208 * be removed.
1209 */
1210 void resetUser(uid_t userId, bool keepUnenryptedEntries) {
Robin Lee4b84fdc2014-09-24 11:56:57 +01001211 android::String8 prefix("");
1212 android::Vector<android::String16> aliases;
Chad Brubaker72593ee2015-05-12 10:42:00 -07001213 UserState* userState = getUserState(userId);
Chad Brubakere6c3bfa2015-05-12 15:18:26 -07001214 if (list(prefix, &aliases, userId) != ::NO_ERROR) {
Chad Brubaker96d6d782015-05-07 10:19:40 -07001215 return;
1216 }
Robin Lee4b84fdc2014-09-24 11:56:57 +01001217 for (uint32_t i = 0; i < aliases.size(); i++) {
1218 android::String8 filename(aliases[i]);
1219 filename = android::String8::format("%s/%s", userState->getUserDirName(),
Chad Brubaker96d6d782015-05-07 10:19:40 -07001220 getKeyName(filename).string());
1221 bool shouldDelete = true;
1222 if (keepUnenryptedEntries) {
1223 Blob blob;
Chad Brubaker72593ee2015-05-12 10:42:00 -07001224 ResponseCode rc = get(filename, &blob, ::TYPE_ANY, userId);
Robin Lee4b84fdc2014-09-24 11:56:57 +01001225
Chad Brubaker96d6d782015-05-07 10:19:40 -07001226 /* get can fail if the blob is encrypted and the state is
1227 * not unlocked, only skip deleting blobs that were loaded and
1228 * who are not encrypted. If there are blobs we fail to read for
1229 * other reasons err on the safe side and delete them since we
1230 * can't tell if they're encrypted.
1231 */
1232 shouldDelete = !(rc == ::NO_ERROR && !blob.isEncrypted());
1233 }
1234 if (shouldDelete) {
Chad Brubaker72593ee2015-05-12 10:42:00 -07001235 del(filename, ::TYPE_ANY, userId);
Chad Brubaker96d6d782015-05-07 10:19:40 -07001236 }
1237 }
1238 if (!userState->deleteMasterKey()) {
1239 ALOGE("Failed to delete user %d's master key", userId);
1240 }
1241 if (!keepUnenryptedEntries) {
1242 if(!userState->reset()) {
1243 ALOGE("Failed to remove user %d's directory", userId);
1244 }
1245 }
Kenny Root655b9582013-04-04 08:37:42 -07001246 }
1247
Chad Brubaker72593ee2015-05-12 10:42:00 -07001248 bool isEmpty(uid_t userId) const {
1249 const UserState* userState = getUserState(userId);
Chad Brubaker96d6d782015-05-07 10:19:40 -07001250 if (userState == NULL) {
Kenny Root655b9582013-04-04 08:37:42 -07001251 return true;
1252 }
1253
1254 DIR* dir = opendir(userState->getUserDirName());
Kenny Roota91203b2012-02-15 15:00:46 -08001255 if (!dir) {
1256 return true;
1257 }
Kenny Root31e27462014-09-10 11:28:03 -07001258
Kenny Roota91203b2012-02-15 15:00:46 -08001259 bool result = true;
Kenny Root31e27462014-09-10 11:28:03 -07001260 struct dirent* file;
Kenny Roota91203b2012-02-15 15:00:46 -08001261 while ((file = readdir(dir)) != NULL) {
Kenny Root655b9582013-04-04 08:37:42 -07001262 // We only care about files.
1263 if (file->d_type != DT_REG) {
1264 continue;
1265 }
1266
1267 // Skip anything that starts with a "."
1268 if (file->d_name[0] == '.') {
1269 continue;
1270 }
1271
Kenny Root31e27462014-09-10 11:28:03 -07001272 result = false;
1273 break;
Kenny Roota91203b2012-02-15 15:00:46 -08001274 }
1275 closedir(dir);
1276 return result;
1277 }
1278
Chad Brubaker72593ee2015-05-12 10:42:00 -07001279 void lock(uid_t userId) {
1280 UserState* userState = getUserState(userId);
Kenny Root655b9582013-04-04 08:37:42 -07001281 userState->zeroizeMasterKeysInMemory();
1282 userState->setState(STATE_LOCKED);
Kenny Roota91203b2012-02-15 15:00:46 -08001283 }
1284
Chad Brubaker72593ee2015-05-12 10:42:00 -07001285 ResponseCode get(const char* filename, Blob* keyBlob, const BlobType type, uid_t userId) {
1286 UserState* userState = getUserState(userId);
Kenny Rootf9119d62013-04-03 09:22:15 -07001287 ResponseCode rc = keyBlob->readBlob(filename, userState->getDecryptionKey(),
1288 userState->getState());
Kenny Root822c3a92012-03-23 16:34:39 -07001289 if (rc != NO_ERROR) {
1290 return rc;
1291 }
1292
1293 const uint8_t version = keyBlob->getVersion();
Kenny Root07438c82012-11-02 15:41:02 -07001294 if (version < CURRENT_BLOB_VERSION) {
Kenny Rootcfeae072013-04-04 08:39:57 -07001295 /* If we upgrade the key, we need to write it to disk again. Then
1296 * it must be read it again since the blob is encrypted each time
1297 * it's written.
1298 */
Chad Brubaker72593ee2015-05-12 10:42:00 -07001299 if (upgradeBlob(filename, keyBlob, version, type, userId)) {
1300 if ((rc = this->put(filename, keyBlob, userId)) != NO_ERROR
Kenny Rootf9119d62013-04-03 09:22:15 -07001301 || (rc = keyBlob->readBlob(filename, userState->getDecryptionKey(),
1302 userState->getState())) != NO_ERROR) {
Kenny Rootcfeae072013-04-04 08:39:57 -07001303 return rc;
1304 }
1305 }
Kenny Root822c3a92012-03-23 16:34:39 -07001306 }
1307
Kenny Root17208e02013-09-04 13:56:03 -07001308 /*
1309 * This will upgrade software-backed keys to hardware-backed keys when
1310 * the HAL for the device supports the newer key types.
1311 */
1312 if (rc == NO_ERROR && type == TYPE_KEY_PAIR
1313 && mDevice->common.module->module_api_version >= KEYMASTER_MODULE_API_VERSION_0_2
1314 && keyBlob->isFallback()) {
1315 ResponseCode imported = importKey(keyBlob->getValue(), keyBlob->getLength(), filename,
Chad Brubaker72593ee2015-05-12 10:42:00 -07001316 userId, keyBlob->isEncrypted() ? KEYSTORE_FLAG_ENCRYPTED : KEYSTORE_FLAG_NONE);
Kenny Root17208e02013-09-04 13:56:03 -07001317
1318 // The HAL allowed the import, reget the key to have the "fresh"
1319 // version.
1320 if (imported == NO_ERROR) {
Chad Brubaker72593ee2015-05-12 10:42:00 -07001321 rc = get(filename, keyBlob, TYPE_KEY_PAIR, userId);
Kenny Root17208e02013-09-04 13:56:03 -07001322 }
1323 }
1324
Chad Brubaker3a7d9e62015-06-04 15:01:46 -07001325 // Keymaster 0.3 keys are valid keymaster 1.0 keys, so silently upgrade.
1326 if (keyBlob->getType() == TYPE_KEY_PAIR) {
Chad Brubaker3cc40122015-06-04 13:49:44 -07001327 keyBlob->setType(TYPE_KEYMASTER_10);
Chad Brubaker3a7d9e62015-06-04 15:01:46 -07001328 rc = this->put(filename, keyBlob, userId);
Chad Brubaker3cc40122015-06-04 13:49:44 -07001329 }
1330
Kenny Rootd53bc922013-03-21 14:10:15 -07001331 if (type != TYPE_ANY && keyBlob->getType() != type) {
Kenny Root822c3a92012-03-23 16:34:39 -07001332 ALOGW("key found but type doesn't match: %d vs %d", keyBlob->getType(), type);
1333 return KEY_NOT_FOUND;
1334 }
1335
1336 return rc;
Kenny Roota91203b2012-02-15 15:00:46 -08001337 }
1338
Chad Brubaker72593ee2015-05-12 10:42:00 -07001339 ResponseCode put(const char* filename, Blob* keyBlob, uid_t userId) {
1340 UserState* userState = getUserState(userId);
Kenny Rootf9119d62013-04-03 09:22:15 -07001341 return keyBlob->writeBlob(filename, userState->getEncryptionKey(), userState->getState(),
1342 mEntropy);
Kenny Roota91203b2012-02-15 15:00:46 -08001343 }
1344
Chad Brubaker72593ee2015-05-12 10:42:00 -07001345 ResponseCode del(const char *filename, const BlobType type, uid_t userId) {
Robin Lee4b84fdc2014-09-24 11:56:57 +01001346 Blob keyBlob;
Chad Brubaker72593ee2015-05-12 10:42:00 -07001347 ResponseCode rc = get(filename, &keyBlob, type, userId);
Chad Brubakera9a17ee2015-07-17 13:43:24 -07001348 if (rc == ::VALUE_CORRUPTED) {
1349 // The file is corrupt, the best we can do is rm it.
1350 return (unlink(filename) && errno != ENOENT) ? ::SYSTEM_ERROR : ::NO_ERROR;
1351 }
Robin Lee4b84fdc2014-09-24 11:56:57 +01001352 if (rc != ::NO_ERROR) {
1353 return rc;
1354 }
1355
1356 if (keyBlob.getType() == ::TYPE_KEY_PAIR) {
Shawn Willden55268b52015-07-28 11:06:00 -06001357 // A device doesn't have to implement delete_key.
1358 if (mDevice->delete_key != NULL && !keyBlob.isFallback()) {
1359 keymaster_key_blob_t blob = {keyBlob.getValue(),
1360 static_cast<size_t>(keyBlob.getLength())};
1361 if (mDevice->delete_key(mDevice, &blob)) {
Robin Lee4b84fdc2014-09-24 11:56:57 +01001362 rc = ::SYSTEM_ERROR;
1363 }
1364 }
1365 }
Chad Brubaker17d68b92015-02-05 22:04:16 -08001366 if (keyBlob.getType() == ::TYPE_KEYMASTER_10) {
1367 keymaster1_device_t* dev = getDeviceForBlob(keyBlob);
1368 if (dev->delete_key) {
1369 keymaster_key_blob_t blob;
1370 blob.key_material = keyBlob.getValue();
1371 blob.key_material_size = keyBlob.getLength();
1372 dev->delete_key(dev, &blob);
1373 }
1374 }
Robin Lee4b84fdc2014-09-24 11:56:57 +01001375 if (rc != ::NO_ERROR) {
1376 return rc;
1377 }
1378
1379 return (unlink(filename) && errno != ENOENT) ? ::SYSTEM_ERROR : ::NO_ERROR;
1380 }
1381
Chad Brubakere6c3bfa2015-05-12 15:18:26 -07001382 ResponseCode list(const android::String8& prefix, android::Vector<android::String16> *matches,
Chad Brubaker72593ee2015-05-12 10:42:00 -07001383 uid_t userId) {
Robin Lee4b84fdc2014-09-24 11:56:57 +01001384
Chad Brubaker72593ee2015-05-12 10:42:00 -07001385 UserState* userState = getUserState(userId);
Robin Lee4b84fdc2014-09-24 11:56:57 +01001386 size_t n = prefix.length();
1387
1388 DIR* dir = opendir(userState->getUserDirName());
1389 if (!dir) {
1390 ALOGW("can't open directory for user: %s", strerror(errno));
1391 return ::SYSTEM_ERROR;
1392 }
1393
1394 struct dirent* file;
1395 while ((file = readdir(dir)) != NULL) {
1396 // We only care about files.
1397 if (file->d_type != DT_REG) {
1398 continue;
1399 }
1400
1401 // Skip anything that starts with a "."
1402 if (file->d_name[0] == '.') {
1403 continue;
1404 }
1405
1406 if (!strncmp(prefix.string(), file->d_name, n)) {
1407 const char* p = &file->d_name[n];
1408 size_t plen = strlen(p);
1409
1410 size_t extra = decode_key_length(p, plen);
1411 char *match = (char*) malloc(extra + 1);
1412 if (match != NULL) {
1413 decode_key(match, p, plen);
1414 matches->push(android::String16(match, extra));
1415 free(match);
1416 } else {
1417 ALOGW("could not allocate match of size %zd", extra);
1418 }
1419 }
1420 }
1421 closedir(dir);
1422 return ::NO_ERROR;
1423 }
1424
Kenny Root07438c82012-11-02 15:41:02 -07001425 void addGrant(const char* filename, uid_t granteeUid) {
Kenny Root655b9582013-04-04 08:37:42 -07001426 const grant_t* existing = getGrant(filename, granteeUid);
1427 if (existing == NULL) {
1428 grant_t* grant = new grant_t;
Kenny Root07438c82012-11-02 15:41:02 -07001429 grant->uid = granteeUid;
Brian Carlstroma8c703d2012-07-17 14:43:46 -07001430 grant->filename = reinterpret_cast<const uint8_t*>(strdup(filename));
Kenny Root655b9582013-04-04 08:37:42 -07001431 mGrants.add(grant);
Kenny Root70e3a862012-02-15 17:20:23 -08001432 }
1433 }
1434
Kenny Root07438c82012-11-02 15:41:02 -07001435 bool removeGrant(const char* filename, uid_t granteeUid) {
Kenny Root655b9582013-04-04 08:37:42 -07001436 for (android::Vector<grant_t*>::iterator it(mGrants.begin());
1437 it != mGrants.end(); it++) {
1438 grant_t* grant = *it;
1439 if (grant->uid == granteeUid
1440 && !strcmp(reinterpret_cast<const char*>(grant->filename), filename)) {
1441 mGrants.erase(it);
1442 return true;
1443 }
Kenny Root70e3a862012-02-15 17:20:23 -08001444 }
Kenny Root70e3a862012-02-15 17:20:23 -08001445 return false;
1446 }
1447
Brian Carlstroma8c703d2012-07-17 14:43:46 -07001448 bool hasGrant(const char* filename, const uid_t uid) const {
1449 return getGrant(filename, uid) != NULL;
Kenny Root70e3a862012-02-15 17:20:23 -08001450 }
1451
Chad Brubaker72593ee2015-05-12 10:42:00 -07001452 ResponseCode importKey(const uint8_t* key, size_t keyLen, const char* filename, uid_t userId,
Kenny Rootf9119d62013-04-03 09:22:15 -07001453 int32_t flags) {
Shawn Willden55268b52015-07-28 11:06:00 -06001454 Unique_PKCS8_PRIV_KEY_INFO pkcs8(d2i_PKCS8_PRIV_KEY_INFO(NULL, &key, keyLen));
1455 if (!pkcs8.get()) {
1456 return ::SYSTEM_ERROR;
1457 }
1458 Unique_EVP_PKEY pkey(EVP_PKCS82PKEY(pkcs8.get()));
1459 if (!pkey.get()) {
1460 return ::SYSTEM_ERROR;
1461 }
1462 int type = EVP_PKEY_type(pkey->type);
1463 android::KeymasterArguments params;
1464 add_legacy_key_authorizations(type, &params.params);
1465 switch (type) {
1466 case EVP_PKEY_RSA:
1467 params.params.push_back(keymaster_param_enum(KM_TAG_ALGORITHM, KM_ALGORITHM_RSA));
1468 break;
1469 case EVP_PKEY_EC:
1470 params.params.push_back(keymaster_param_enum(KM_TAG_ALGORITHM,
1471 KM_ALGORITHM_EC));
1472 break;
1473 default:
1474 ALOGW("Unsupported key type %d", type);
1475 return ::SYSTEM_ERROR;
Kenny Root822c3a92012-03-23 16:34:39 -07001476 }
1477
Shawn Willden55268b52015-07-28 11:06:00 -06001478 std::vector<keymaster_key_param_t> opParams(params.params);
1479 const keymaster_key_param_set_t inParams = {opParams.data(), opParams.size()};
1480 keymaster_blob_t input = {key, keyLen};
1481 keymaster_key_blob_t blob = {nullptr, 0};
Kenny Root17208e02013-09-04 13:56:03 -07001482 bool isFallback = false;
Shawn Willden55268b52015-07-28 11:06:00 -06001483 keymaster_error_t error = mDevice->import_key(mDevice, &inParams, KM_KEY_FORMAT_PKCS8,
1484 &input, &blob, NULL /* characteristics */);
1485 if (error != KM_ERROR_OK){
1486 ALOGE("Keymaster error %d importing key pair, falling back", error);
1487
Kenny Roota39da5a2014-09-25 13:07:24 -07001488 /*
Shawn Willden55268b52015-07-28 11:06:00 -06001489 * There should be no way to get here. Fallback shouldn't ever really happen
1490 * because the main device may be many (SW, KM0/SW hybrid, KM1/SW hybrid), but it must
1491 * provide full support of the API. In any case, we'll do the fallback just for
1492 * consistency... and I suppose to cover for broken HW implementations.
Kenny Roota39da5a2014-09-25 13:07:24 -07001493 */
Shawn Willden55268b52015-07-28 11:06:00 -06001494 error = mFallbackDevice->import_key(mFallbackDevice, &inParams, KM_KEY_FORMAT_PKCS8,
1495 &input, &blob, NULL /* characteristics */);
Kenny Roota39da5a2014-09-25 13:07:24 -07001496 isFallback = true;
Kenny Root17208e02013-09-04 13:56:03 -07001497
Shawn Willden55268b52015-07-28 11:06:00 -06001498 if (error) {
1499 ALOGE("Keymaster error while importing key pair with fallback: %d", error);
Kenny Root17208e02013-09-04 13:56:03 -07001500 return SYSTEM_ERROR;
1501 }
Kenny Root822c3a92012-03-23 16:34:39 -07001502 }
1503
Shawn Willden55268b52015-07-28 11:06:00 -06001504 Blob keyBlob(blob.key_material, blob.key_material_size, NULL, 0, TYPE_KEYMASTER_10);
1505 free(const_cast<uint8_t*>(blob.key_material));
Kenny Root822c3a92012-03-23 16:34:39 -07001506
Kenny Rootf9119d62013-04-03 09:22:15 -07001507 keyBlob.setEncrypted(flags & KEYSTORE_FLAG_ENCRYPTED);
Kenny Root17208e02013-09-04 13:56:03 -07001508 keyBlob.setFallback(isFallback);
Kenny Rootf9119d62013-04-03 09:22:15 -07001509
Chad Brubaker72593ee2015-05-12 10:42:00 -07001510 return put(filename, &keyBlob, userId);
Kenny Root822c3a92012-03-23 16:34:39 -07001511 }
1512
Kenny Root1b0e3932013-09-05 13:06:32 -07001513 bool isHardwareBacked(const android::String16& keyType) const {
1514 if (mDevice == NULL) {
1515 ALOGW("can't get keymaster device");
1516 return false;
1517 }
1518
1519 if (sRSAKeyType == keyType) {
1520 return (mDevice->flags & KEYMASTER_SOFTWARE_ONLY) == 0;
1521 } else {
1522 return (mDevice->flags & KEYMASTER_SOFTWARE_ONLY) == 0
1523 && (mDevice->common.module->module_api_version
1524 >= KEYMASTER_MODULE_API_VERSION_0_2);
1525 }
Kenny Root8ddf35a2013-03-29 11:15:50 -07001526 }
1527
Kenny Root655b9582013-04-04 08:37:42 -07001528 ResponseCode getKeyForName(Blob* keyBlob, const android::String8& keyName, const uid_t uid,
1529 const BlobType type) {
Kenny Root86b16e82013-09-09 11:15:54 -07001530 android::String8 filepath8(getKeyNameForUidWithDir(keyName, uid));
Chad Brubaker72593ee2015-05-12 10:42:00 -07001531 uid_t userId = get_user_id(uid);
Kenny Root655b9582013-04-04 08:37:42 -07001532
Chad Brubaker72593ee2015-05-12 10:42:00 -07001533 ResponseCode responseCode = get(filepath8.string(), keyBlob, type, userId);
Kenny Root655b9582013-04-04 08:37:42 -07001534 if (responseCode == NO_ERROR) {
1535 return responseCode;
1536 }
1537
1538 // If this is one of the legacy UID->UID mappings, use it.
1539 uid_t euid = get_keystore_euid(uid);
1540 if (euid != uid) {
Kenny Root86b16e82013-09-09 11:15:54 -07001541 filepath8 = getKeyNameForUidWithDir(keyName, euid);
Chad Brubaker72593ee2015-05-12 10:42:00 -07001542 responseCode = get(filepath8.string(), keyBlob, type, userId);
Kenny Root655b9582013-04-04 08:37:42 -07001543 if (responseCode == NO_ERROR) {
1544 return responseCode;
1545 }
1546 }
1547
1548 // They might be using a granted key.
Kenny Root86b16e82013-09-09 11:15:54 -07001549 android::String8 filename8 = getKeyName(keyName);
Kenny Root655b9582013-04-04 08:37:42 -07001550 char* end;
Kenny Root86b16e82013-09-09 11:15:54 -07001551 strtoul(filename8.string(), &end, 10);
Kenny Root655b9582013-04-04 08:37:42 -07001552 if (end[0] != '_' || end[1] == 0) {
1553 return KEY_NOT_FOUND;
1554 }
Chad Brubaker72593ee2015-05-12 10:42:00 -07001555 filepath8 = android::String8::format("%s/%s", getUserState(userId)->getUserDirName(),
Kenny Root86b16e82013-09-09 11:15:54 -07001556 filename8.string());
Kenny Root655b9582013-04-04 08:37:42 -07001557 if (!hasGrant(filepath8.string(), uid)) {
1558 return responseCode;
1559 }
1560
1561 // It is a granted key. Try to load it.
Chad Brubaker72593ee2015-05-12 10:42:00 -07001562 return get(filepath8.string(), keyBlob, type, userId);
Kenny Root655b9582013-04-04 08:37:42 -07001563 }
1564
1565 /**
1566 * Returns any existing UserState or creates it if it doesn't exist.
1567 */
Chad Brubaker72593ee2015-05-12 10:42:00 -07001568 UserState* getUserState(uid_t userId) {
Kenny Root655b9582013-04-04 08:37:42 -07001569 for (android::Vector<UserState*>::iterator it(mMasterKeys.begin());
1570 it != mMasterKeys.end(); it++) {
1571 UserState* state = *it;
1572 if (state->getUserId() == userId) {
1573 return state;
1574 }
1575 }
1576
1577 UserState* userState = new UserState(userId);
1578 if (!userState->initialize()) {
1579 /* There's not much we can do if initialization fails. Trying to
1580 * unlock the keystore for that user will fail as well, so any
1581 * subsequent request for this user will just return SYSTEM_ERROR.
1582 */
1583 ALOGE("User initialization failed for %u; subsuquent operations will fail", userId);
1584 }
1585 mMasterKeys.add(userState);
1586 return userState;
1587 }
1588
1589 /**
Chad Brubaker72593ee2015-05-12 10:42:00 -07001590 * Returns any existing UserState or creates it if it doesn't exist.
1591 */
1592 UserState* getUserStateByUid(uid_t uid) {
1593 uid_t userId = get_user_id(uid);
1594 return getUserState(userId);
1595 }
1596
1597 /**
Kenny Root655b9582013-04-04 08:37:42 -07001598 * Returns NULL if the UserState doesn't already exist.
1599 */
Chad Brubaker72593ee2015-05-12 10:42:00 -07001600 const UserState* getUserState(uid_t userId) const {
Kenny Root655b9582013-04-04 08:37:42 -07001601 for (android::Vector<UserState*>::const_iterator it(mMasterKeys.begin());
1602 it != mMasterKeys.end(); it++) {
1603 UserState* state = *it;
1604 if (state->getUserId() == userId) {
1605 return state;
1606 }
1607 }
1608
1609 return NULL;
1610 }
1611
Chad Brubaker72593ee2015-05-12 10:42:00 -07001612 /**
1613 * Returns NULL if the UserState doesn't already exist.
1614 */
1615 const UserState* getUserStateByUid(uid_t uid) const {
1616 uid_t userId = get_user_id(uid);
1617 return getUserState(userId);
1618 }
1619
Kenny Roota91203b2012-02-15 15:00:46 -08001620private:
Kenny Root655b9582013-04-04 08:37:42 -07001621 static const char* sOldMasterKey;
1622 static const char* sMetaDataFile;
Kenny Root1b0e3932013-09-05 13:06:32 -07001623 static const android::String16 sRSAKeyType;
Kenny Roota91203b2012-02-15 15:00:46 -08001624 Entropy* mEntropy;
1625
Chad Brubaker67d2a502015-03-11 17:21:18 +00001626 keymaster1_device_t* mDevice;
1627 keymaster1_device_t* mFallbackDevice;
Kenny Root70e3a862012-02-15 17:20:23 -08001628
Kenny Root655b9582013-04-04 08:37:42 -07001629 android::Vector<UserState*> mMasterKeys;
Kenny Roota91203b2012-02-15 15:00:46 -08001630
Kenny Root655b9582013-04-04 08:37:42 -07001631 android::Vector<grant_t*> mGrants;
Kenny Roota91203b2012-02-15 15:00:46 -08001632
Kenny Root655b9582013-04-04 08:37:42 -07001633 typedef struct {
1634 uint32_t version;
1635 } keystore_metadata_t;
Kenny Roota91203b2012-02-15 15:00:46 -08001636
Kenny Root655b9582013-04-04 08:37:42 -07001637 keystore_metadata_t mMetaData;
Kenny Root70e3a862012-02-15 17:20:23 -08001638
Kenny Root655b9582013-04-04 08:37:42 -07001639 const grant_t* getGrant(const char* filename, uid_t uid) const {
1640 for (android::Vector<grant_t*>::const_iterator it(mGrants.begin());
1641 it != mGrants.end(); it++) {
1642 grant_t* grant = *it;
Kenny Root70e3a862012-02-15 17:20:23 -08001643 if (grant->uid == uid
Kenny Root655b9582013-04-04 08:37:42 -07001644 && !strcmp(reinterpret_cast<const char*>(grant->filename), filename)) {
Kenny Root70e3a862012-02-15 17:20:23 -08001645 return grant;
1646 }
1647 }
Kenny Root70e3a862012-02-15 17:20:23 -08001648 return NULL;
1649 }
1650
Kenny Root822c3a92012-03-23 16:34:39 -07001651 /**
1652 * Upgrade code. This will upgrade the key from the current version
1653 * to whatever is newest.
1654 */
Kenny Root655b9582013-04-04 08:37:42 -07001655 bool upgradeBlob(const char* filename, Blob* blob, const uint8_t oldVersion,
1656 const BlobType type, uid_t uid) {
Kenny Root822c3a92012-03-23 16:34:39 -07001657 bool updated = false;
1658 uint8_t version = oldVersion;
1659
1660 /* From V0 -> V1: All old types were unknown */
1661 if (version == 0) {
1662 ALOGV("upgrading to version 1 and setting type %d", type);
1663
1664 blob->setType(type);
1665 if (type == TYPE_KEY_PAIR) {
Kenny Root655b9582013-04-04 08:37:42 -07001666 importBlobAsKey(blob, filename, uid);
Kenny Root822c3a92012-03-23 16:34:39 -07001667 }
1668 version = 1;
1669 updated = true;
1670 }
1671
Kenny Rootf9119d62013-04-03 09:22:15 -07001672 /* From V1 -> V2: All old keys were encrypted */
1673 if (version == 1) {
1674 ALOGV("upgrading to version 2");
1675
1676 blob->setEncrypted(true);
1677 version = 2;
1678 updated = true;
1679 }
1680
Kenny Root822c3a92012-03-23 16:34:39 -07001681 /*
1682 * If we've updated, set the key blob to the right version
1683 * and write it.
Kenny Rootcfeae072013-04-04 08:39:57 -07001684 */
Kenny Root822c3a92012-03-23 16:34:39 -07001685 if (updated) {
1686 ALOGV("updated and writing file %s", filename);
1687 blob->setVersion(version);
Kenny Root822c3a92012-03-23 16:34:39 -07001688 }
Kenny Rootcfeae072013-04-04 08:39:57 -07001689
1690 return updated;
Kenny Root822c3a92012-03-23 16:34:39 -07001691 }
1692
1693 /**
1694 * Takes a blob that is an PEM-encoded RSA key as a byte array and
1695 * converts it to a DER-encoded PKCS#8 for import into a keymaster.
1696 * Then it overwrites the original blob with the new blob
1697 * format that is returned from the keymaster.
1698 */
Kenny Root655b9582013-04-04 08:37:42 -07001699 ResponseCode importBlobAsKey(Blob* blob, const char* filename, uid_t uid) {
Kenny Root822c3a92012-03-23 16:34:39 -07001700 // We won't even write to the blob directly with this BIO, so const_cast is okay.
1701 Unique_BIO b(BIO_new_mem_buf(const_cast<uint8_t*>(blob->getValue()), blob->getLength()));
1702 if (b.get() == NULL) {
1703 ALOGE("Problem instantiating BIO");
1704 return SYSTEM_ERROR;
1705 }
1706
1707 Unique_EVP_PKEY pkey(PEM_read_bio_PrivateKey(b.get(), NULL, NULL, NULL));
1708 if (pkey.get() == NULL) {
1709 ALOGE("Couldn't read old PEM file");
1710 return SYSTEM_ERROR;
1711 }
1712
1713 Unique_PKCS8_PRIV_KEY_INFO pkcs8(EVP_PKEY2PKCS8(pkey.get()));
1714 int len = i2d_PKCS8_PRIV_KEY_INFO(pkcs8.get(), NULL);
1715 if (len < 0) {
1716 ALOGE("Couldn't measure PKCS#8 length");
1717 return SYSTEM_ERROR;
1718 }
1719
Kenny Root70c98892013-02-07 09:10:36 -08001720 UniquePtr<unsigned char[]> pkcs8key(new unsigned char[len]);
1721 uint8_t* tmp = pkcs8key.get();
Kenny Root822c3a92012-03-23 16:34:39 -07001722 if (i2d_PKCS8_PRIV_KEY_INFO(pkcs8.get(), &tmp) != len) {
1723 ALOGE("Couldn't convert to PKCS#8");
1724 return SYSTEM_ERROR;
1725 }
1726
Chad Brubaker72593ee2015-05-12 10:42:00 -07001727 ResponseCode rc = importKey(pkcs8key.get(), len, filename, get_user_id(uid),
Kenny Rootf9119d62013-04-03 09:22:15 -07001728 blob->isEncrypted() ? KEYSTORE_FLAG_ENCRYPTED : KEYSTORE_FLAG_NONE);
Kenny Root822c3a92012-03-23 16:34:39 -07001729 if (rc != NO_ERROR) {
1730 return rc;
1731 }
1732
Kenny Root655b9582013-04-04 08:37:42 -07001733 return get(filename, blob, TYPE_KEY_PAIR, uid);
1734 }
1735
1736 void readMetaData() {
1737 int in = TEMP_FAILURE_RETRY(open(sMetaDataFile, O_RDONLY));
1738 if (in < 0) {
1739 return;
1740 }
1741 size_t fileLength = readFully(in, (uint8_t*) &mMetaData, sizeof(mMetaData));
1742 if (fileLength != sizeof(mMetaData)) {
1743 ALOGI("Metadata file is %zd bytes (%zd experted); upgrade?", fileLength,
1744 sizeof(mMetaData));
1745 }
1746 close(in);
1747 }
1748
1749 void writeMetaData() {
1750 const char* tmpFileName = ".metadata.tmp";
1751 int out = TEMP_FAILURE_RETRY(open(tmpFileName,
1752 O_WRONLY | O_TRUNC | O_CREAT, S_IRUSR | S_IWUSR));
1753 if (out < 0) {
1754 ALOGE("couldn't write metadata file: %s", strerror(errno));
1755 return;
1756 }
1757 size_t fileLength = writeFully(out, (uint8_t*) &mMetaData, sizeof(mMetaData));
1758 if (fileLength != sizeof(mMetaData)) {
1759 ALOGI("Could only write %zd bytes to metadata file (%zd expected)", fileLength,
1760 sizeof(mMetaData));
1761 }
1762 close(out);
1763 rename(tmpFileName, sMetaDataFile);
1764 }
1765
1766 bool upgradeKeystore() {
1767 bool upgraded = false;
1768
1769 if (mMetaData.version == 0) {
Chad Brubaker72593ee2015-05-12 10:42:00 -07001770 UserState* userState = getUserStateByUid(0);
Kenny Root655b9582013-04-04 08:37:42 -07001771
1772 // Initialize first so the directory is made.
1773 userState->initialize();
1774
1775 // Migrate the old .masterkey file to user 0.
1776 if (access(sOldMasterKey, R_OK) == 0) {
1777 if (rename(sOldMasterKey, userState->getMasterKeyFileName()) < 0) {
1778 ALOGE("couldn't migrate old masterkey: %s", strerror(errno));
1779 return false;
1780 }
1781 }
1782
1783 // Initialize again in case we had a key.
1784 userState->initialize();
1785
1786 // Try to migrate existing keys.
1787 DIR* dir = opendir(".");
1788 if (!dir) {
1789 // Give up now; maybe we can upgrade later.
1790 ALOGE("couldn't open keystore's directory; something is wrong");
1791 return false;
1792 }
1793
1794 struct dirent* file;
1795 while ((file = readdir(dir)) != NULL) {
1796 // We only care about files.
1797 if (file->d_type != DT_REG) {
1798 continue;
1799 }
1800
1801 // Skip anything that starts with a "."
1802 if (file->d_name[0] == '.') {
1803 continue;
1804 }
1805
1806 // Find the current file's user.
1807 char* end;
1808 unsigned long thisUid = strtoul(file->d_name, &end, 10);
1809 if (end[0] != '_' || end[1] == 0) {
1810 continue;
1811 }
Chad Brubaker72593ee2015-05-12 10:42:00 -07001812 UserState* otherUser = getUserStateByUid(thisUid);
Kenny Root655b9582013-04-04 08:37:42 -07001813 if (otherUser->getUserId() != 0) {
1814 unlinkat(dirfd(dir), file->d_name, 0);
1815 }
1816
1817 // Rename the file into user directory.
1818 DIR* otherdir = opendir(otherUser->getUserDirName());
1819 if (otherdir == NULL) {
1820 ALOGW("couldn't open user directory for rename");
1821 continue;
1822 }
1823 if (renameat(dirfd(dir), file->d_name, dirfd(otherdir), file->d_name) < 0) {
1824 ALOGW("couldn't rename blob: %s: %s", file->d_name, strerror(errno));
1825 }
1826 closedir(otherdir);
1827 }
1828 closedir(dir);
1829
1830 mMetaData.version = 1;
1831 upgraded = true;
1832 }
1833
1834 return upgraded;
Kenny Root822c3a92012-03-23 16:34:39 -07001835 }
Kenny Roota91203b2012-02-15 15:00:46 -08001836};
1837
Kenny Root655b9582013-04-04 08:37:42 -07001838const char* KeyStore::sOldMasterKey = ".masterkey";
1839const char* KeyStore::sMetaDataFile = ".metadata";
Kenny Root70e3a862012-02-15 17:20:23 -08001840
Kenny Root1b0e3932013-09-05 13:06:32 -07001841const android::String16 KeyStore::sRSAKeyType("RSA");
1842
Kenny Root07438c82012-11-02 15:41:02 -07001843namespace android {
1844class KeyStoreProxy : public BnKeystoreService, public IBinder::DeathRecipient {
1845public:
1846 KeyStoreProxy(KeyStore* keyStore)
Chad Brubaker40a1a9b2015-02-20 14:08:13 -08001847 : mKeyStore(keyStore),
1848 mOperationMap(this)
Kenny Root07438c82012-11-02 15:41:02 -07001849 {
Kenny Roota91203b2012-02-15 15:00:46 -08001850 }
Kenny Roota91203b2012-02-15 15:00:46 -08001851
Chad Brubaker40a1a9b2015-02-20 14:08:13 -08001852 void binderDied(const wp<IBinder>& who) {
1853 auto operations = mOperationMap.getOperationsForToken(who.unsafe_get());
1854 for (auto token: operations) {
1855 abort(token);
1856 }
Kenny Root822c3a92012-03-23 16:34:39 -07001857 }
Kenny Roota91203b2012-02-15 15:00:46 -08001858
Chad Brubakere6c3bfa2015-05-12 15:18:26 -07001859 int32_t getState(int32_t userId) {
1860 if (!checkBinderPermission(P_GET_STATE)) {
Kenny Root07438c82012-11-02 15:41:02 -07001861 return ::PERMISSION_DENIED;
Kenny Roota91203b2012-02-15 15:00:46 -08001862 }
Kenny Roota91203b2012-02-15 15:00:46 -08001863
Chad Brubakere6c3bfa2015-05-12 15:18:26 -07001864 return mKeyStore->getState(userId);
Kenny Root298e7b12012-03-26 13:54:44 -07001865 }
1866
Kenny Root07438c82012-11-02 15:41:02 -07001867 int32_t get(const String16& name, uint8_t** item, size_t* itemLength) {
Chad Brubaker9489b792015-04-14 11:01:45 -07001868 if (!checkBinderPermission(P_GET)) {
Kenny Root07438c82012-11-02 15:41:02 -07001869 return ::PERMISSION_DENIED;
Kenny Roota91203b2012-02-15 15:00:46 -08001870 }
Kenny Root07438c82012-11-02 15:41:02 -07001871
Chad Brubaker9489b792015-04-14 11:01:45 -07001872 uid_t callingUid = IPCThreadState::self()->getCallingUid();
Kenny Root07438c82012-11-02 15:41:02 -07001873 String8 name8(name);
Kenny Root07438c82012-11-02 15:41:02 -07001874 Blob keyBlob;
Nick Kralevich66dbf672014-06-30 17:09:14 +00001875
Kenny Root655b9582013-04-04 08:37:42 -07001876 ResponseCode responseCode = mKeyStore->getKeyForName(&keyBlob, name8, callingUid,
Kenny Root49468902013-03-19 13:41:33 -07001877 TYPE_GENERIC);
Kenny Root07438c82012-11-02 15:41:02 -07001878 if (responseCode != ::NO_ERROR) {
1879 *item = NULL;
1880 *itemLength = 0;
1881 return responseCode;
Kenny Roota91203b2012-02-15 15:00:46 -08001882 }
Kenny Roota91203b2012-02-15 15:00:46 -08001883
Kenny Root07438c82012-11-02 15:41:02 -07001884 *item = (uint8_t*) malloc(keyBlob.getLength());
1885 memcpy(*item, keyBlob.getValue(), keyBlob.getLength());
1886 *itemLength = keyBlob.getLength();
Kenny Roota91203b2012-02-15 15:00:46 -08001887
Kenny Root07438c82012-11-02 15:41:02 -07001888 return ::NO_ERROR;
Kenny Root70e3a862012-02-15 17:20:23 -08001889 }
1890
Kenny Rootf9119d62013-04-03 09:22:15 -07001891 int32_t insert(const String16& name, const uint8_t* item, size_t itemLength, int targetUid,
1892 int32_t flags) {
Chad Brubaker9489b792015-04-14 11:01:45 -07001893 targetUid = getEffectiveUid(targetUid);
1894 int32_t result = checkBinderPermissionAndKeystoreState(P_INSERT, targetUid,
1895 flags & KEYSTORE_FLAG_ENCRYPTED);
1896 if (result != ::NO_ERROR) {
1897 return result;
Kenny Rootb88c3eb2013-02-13 14:43:43 -08001898 }
1899
Kenny Root07438c82012-11-02 15:41:02 -07001900 String8 name8(name);
Kenny Root655b9582013-04-04 08:37:42 -07001901 String8 filename(mKeyStore->getKeyNameForUidWithDir(name8, targetUid));
Kenny Root07438c82012-11-02 15:41:02 -07001902
1903 Blob keyBlob(item, itemLength, NULL, 0, ::TYPE_GENERIC);
Kenny Rootee8068b2013-10-07 09:49:15 -07001904 keyBlob.setEncrypted(flags & KEYSTORE_FLAG_ENCRYPTED);
1905
Chad Brubaker72593ee2015-05-12 10:42:00 -07001906 return mKeyStore->put(filename.string(), &keyBlob, get_user_id(targetUid));
Kenny Root70e3a862012-02-15 17:20:23 -08001907 }
1908
Kenny Root49468902013-03-19 13:41:33 -07001909 int32_t del(const String16& name, int targetUid) {
Chad Brubaker9489b792015-04-14 11:01:45 -07001910 targetUid = getEffectiveUid(targetUid);
1911 if (!checkBinderPermission(P_DELETE, targetUid)) {
Kenny Root07438c82012-11-02 15:41:02 -07001912 return ::PERMISSION_DENIED;
1913 }
Kenny Root07438c82012-11-02 15:41:02 -07001914 String8 name8(name);
Kenny Root655b9582013-04-04 08:37:42 -07001915 String8 filename(mKeyStore->getKeyNameForUidWithDir(name8, targetUid));
Chad Brubaker72593ee2015-05-12 10:42:00 -07001916 return mKeyStore->del(filename.string(), ::TYPE_ANY, get_user_id(targetUid));
Kenny Root70e3a862012-02-15 17:20:23 -08001917 }
1918
Kenny Root49468902013-03-19 13:41:33 -07001919 int32_t exist(const String16& name, int targetUid) {
Chad Brubaker9489b792015-04-14 11:01:45 -07001920 targetUid = getEffectiveUid(targetUid);
1921 if (!checkBinderPermission(P_EXIST, targetUid)) {
Kenny Rootb88c3eb2013-02-13 14:43:43 -08001922 return ::PERMISSION_DENIED;
1923 }
1924
Kenny Root07438c82012-11-02 15:41:02 -07001925 String8 name8(name);
Kenny Root655b9582013-04-04 08:37:42 -07001926 String8 filename(mKeyStore->getKeyNameForUidWithDir(name8, targetUid));
Kenny Root70e3a862012-02-15 17:20:23 -08001927
Kenny Root655b9582013-04-04 08:37:42 -07001928 if (access(filename.string(), R_OK) == -1) {
Kenny Root07438c82012-11-02 15:41:02 -07001929 return (errno != ENOENT) ? ::SYSTEM_ERROR : ::KEY_NOT_FOUND;
1930 }
1931 return ::NO_ERROR;
Kenny Root70e3a862012-02-15 17:20:23 -08001932 }
1933
Chad Brubakere6c3bfa2015-05-12 15:18:26 -07001934 int32_t list(const String16& prefix, int targetUid, Vector<String16>* matches) {
Chad Brubaker9489b792015-04-14 11:01:45 -07001935 targetUid = getEffectiveUid(targetUid);
Chad Brubakere6c3bfa2015-05-12 15:18:26 -07001936 if (!checkBinderPermission(P_LIST, targetUid)) {
Kenny Root07438c82012-11-02 15:41:02 -07001937 return ::PERMISSION_DENIED;
1938 }
Kenny Root07438c82012-11-02 15:41:02 -07001939 const String8 prefix8(prefix);
Kenny Root655b9582013-04-04 08:37:42 -07001940 String8 filename(mKeyStore->getKeyNameForUid(prefix8, targetUid));
Kenny Root70e3a862012-02-15 17:20:23 -08001941
Chad Brubakere6c3bfa2015-05-12 15:18:26 -07001942 if (mKeyStore->list(filename, matches, get_user_id(targetUid)) != ::NO_ERROR) {
Robin Lee4b84fdc2014-09-24 11:56:57 +01001943 return ::SYSTEM_ERROR;
Kenny Root9a53d3e2012-08-14 10:47:54 -07001944 }
Kenny Root07438c82012-11-02 15:41:02 -07001945 return ::NO_ERROR;
Kenny Root70e3a862012-02-15 17:20:23 -08001946 }
1947
Kenny Root07438c82012-11-02 15:41:02 -07001948 int32_t reset() {
Chad Brubaker9489b792015-04-14 11:01:45 -07001949 if (!checkBinderPermission(P_RESET)) {
Kenny Root07438c82012-11-02 15:41:02 -07001950 return ::PERMISSION_DENIED;
1951 }
1952
Chad Brubaker9489b792015-04-14 11:01:45 -07001953 uid_t callingUid = IPCThreadState::self()->getCallingUid();
Chad Brubaker96d6d782015-05-07 10:19:40 -07001954 mKeyStore->resetUser(get_user_id(callingUid), false);
1955 return ::NO_ERROR;
Kenny Root70e3a862012-02-15 17:20:23 -08001956 }
1957
Chad Brubaker96d6d782015-05-07 10:19:40 -07001958 int32_t onUserPasswordChanged(int32_t userId, const String16& password) {
Chad Brubaker9489b792015-04-14 11:01:45 -07001959 if (!checkBinderPermission(P_PASSWORD)) {
Kenny Root07438c82012-11-02 15:41:02 -07001960 return ::PERMISSION_DENIED;
1961 }
Kenny Root70e3a862012-02-15 17:20:23 -08001962
Kenny Root07438c82012-11-02 15:41:02 -07001963 const String8 password8(password);
Chad Brubaker96d6d782015-05-07 10:19:40 -07001964 // Flush the auth token table to prevent stale tokens from sticking
1965 // around.
1966 mAuthTokenTable.Clear();
1967
1968 if (password.size() == 0) {
1969 ALOGI("Secure lockscreen for user %d removed, deleting encrypted entries", userId);
Chad Brubaker72593ee2015-05-12 10:42:00 -07001970 mKeyStore->resetUser(userId, true);
Chad Brubaker96d6d782015-05-07 10:19:40 -07001971 return ::NO_ERROR;
1972 } else {
Chad Brubaker72593ee2015-05-12 10:42:00 -07001973 switch (mKeyStore->getState(userId)) {
Chad Brubaker96d6d782015-05-07 10:19:40 -07001974 case ::STATE_UNINITIALIZED: {
1975 // generate master key, encrypt with password, write to file,
1976 // initialize mMasterKey*.
Chad Brubaker72593ee2015-05-12 10:42:00 -07001977 return mKeyStore->initializeUser(password8, userId);
Chad Brubaker96d6d782015-05-07 10:19:40 -07001978 }
1979 case ::STATE_NO_ERROR: {
1980 // rewrite master key with new password.
Chad Brubaker72593ee2015-05-12 10:42:00 -07001981 return mKeyStore->writeMasterKey(password8, userId);
Chad Brubaker96d6d782015-05-07 10:19:40 -07001982 }
1983 case ::STATE_LOCKED: {
1984 ALOGE("Changing user %d's password while locked, clearing old encryption",
1985 userId);
Chad Brubaker72593ee2015-05-12 10:42:00 -07001986 mKeyStore->resetUser(userId, true);
1987 return mKeyStore->initializeUser(password8, userId);
Chad Brubaker96d6d782015-05-07 10:19:40 -07001988 }
Kenny Root07438c82012-11-02 15:41:02 -07001989 }
Chad Brubaker96d6d782015-05-07 10:19:40 -07001990 return ::SYSTEM_ERROR;
Kenny Root07438c82012-11-02 15:41:02 -07001991 }
Kenny Root70e3a862012-02-15 17:20:23 -08001992 }
1993
Chad Brubakerc0f031a2015-05-12 10:43:10 -07001994 int32_t onUserAdded(int32_t userId, int32_t parentId) {
1995 if (!checkBinderPermission(P_USER_CHANGED)) {
1996 return ::PERMISSION_DENIED;
1997 }
1998
1999 // Sanity check that the new user has an empty keystore.
2000 if (!mKeyStore->isEmpty(userId)) {
2001 ALOGW("New user %d's keystore not empty. Clearing old entries.", userId);
2002 }
2003 // Unconditionally clear the keystore, just to be safe.
2004 mKeyStore->resetUser(userId, false);
2005
2006 // If the user has a parent user then use the parent's
2007 // masterkey/password, otherwise there's nothing to do.
2008 if (parentId != -1) {
2009 return mKeyStore->copyMasterKey(parentId, userId);
2010 } else {
2011 return ::NO_ERROR;
2012 }
2013 }
2014
2015 int32_t onUserRemoved(int32_t userId) {
2016 if (!checkBinderPermission(P_USER_CHANGED)) {
2017 return ::PERMISSION_DENIED;
2018 }
2019
2020 mKeyStore->resetUser(userId, false);
2021 return ::NO_ERROR;
2022 }
2023
Chad Brubakere6c3bfa2015-05-12 15:18:26 -07002024 int32_t lock(int32_t userId) {
Chad Brubaker9489b792015-04-14 11:01:45 -07002025 if (!checkBinderPermission(P_LOCK)) {
Kenny Root07438c82012-11-02 15:41:02 -07002026 return ::PERMISSION_DENIED;
2027 }
Kenny Root70e3a862012-02-15 17:20:23 -08002028
Chad Brubaker72593ee2015-05-12 10:42:00 -07002029 State state = mKeyStore->getState(userId);
Kenny Root9d45d1c2013-02-14 10:32:30 -08002030 if (state != ::STATE_NO_ERROR) {
Kenny Root07438c82012-11-02 15:41:02 -07002031 ALOGD("calling lock in state: %d", state);
2032 return state;
2033 }
2034
Chad Brubaker72593ee2015-05-12 10:42:00 -07002035 mKeyStore->lock(userId);
Kenny Root07438c82012-11-02 15:41:02 -07002036 return ::NO_ERROR;
Kenny Root70e3a862012-02-15 17:20:23 -08002037 }
2038
Chad Brubaker96d6d782015-05-07 10:19:40 -07002039 int32_t unlock(int32_t userId, const String16& pw) {
Chad Brubaker9489b792015-04-14 11:01:45 -07002040 if (!checkBinderPermission(P_UNLOCK)) {
Kenny Root07438c82012-11-02 15:41:02 -07002041 return ::PERMISSION_DENIED;
2042 }
2043
Chad Brubaker72593ee2015-05-12 10:42:00 -07002044 State state = mKeyStore->getState(userId);
Kenny Root9d45d1c2013-02-14 10:32:30 -08002045 if (state != ::STATE_LOCKED) {
Chad Brubaker96d6d782015-05-07 10:19:40 -07002046 ALOGI("calling unlock when not locked, ignoring.");
Kenny Root07438c82012-11-02 15:41:02 -07002047 return state;
2048 }
2049
2050 const String8 password8(pw);
Chad Brubaker96d6d782015-05-07 10:19:40 -07002051 // read master key, decrypt with password, initialize mMasterKey*.
Chad Brubaker72593ee2015-05-12 10:42:00 -07002052 return mKeyStore->readMasterKey(password8, userId);
Kenny Root70e3a862012-02-15 17:20:23 -08002053 }
2054
Chad Brubakere6c3bfa2015-05-12 15:18:26 -07002055 bool isEmpty(int32_t userId) {
2056 if (!checkBinderPermission(P_IS_EMPTY)) {
2057 return false;
Kenny Root07438c82012-11-02 15:41:02 -07002058 }
Kenny Root70e3a862012-02-15 17:20:23 -08002059
Chad Brubakere6c3bfa2015-05-12 15:18:26 -07002060 return mKeyStore->isEmpty(userId);
Kenny Root70e3a862012-02-15 17:20:23 -08002061 }
2062
Kenny Root96427ba2013-08-16 14:02:41 -07002063 int32_t generate(const String16& name, int32_t targetUid, int32_t keyType, int32_t keySize,
2064 int32_t flags, Vector<sp<KeystoreArg> >* args) {
Chad Brubaker9489b792015-04-14 11:01:45 -07002065 targetUid = getEffectiveUid(targetUid);
2066 int32_t result = checkBinderPermissionAndKeystoreState(P_INSERT, targetUid,
2067 flags & KEYSTORE_FLAG_ENCRYPTED);
2068 if (result != ::NO_ERROR) {
2069 return result;
Kenny Root07438c82012-11-02 15:41:02 -07002070 }
Kenny Root07438c82012-11-02 15:41:02 -07002071
Chad Brubaker3a7d9e62015-06-04 15:01:46 -07002072 KeymasterArguments params;
Shawn Willden55268b52015-07-28 11:06:00 -06002073 add_legacy_key_authorizations(keyType, &params.params);
Kenny Root07438c82012-11-02 15:41:02 -07002074
Chad Brubaker3a7d9e62015-06-04 15:01:46 -07002075 switch (keyType) {
2076 case EVP_PKEY_EC: {
2077 params.params.push_back(keymaster_param_enum(KM_TAG_ALGORITHM, KM_ALGORITHM_EC));
2078 if (keySize == -1) {
2079 keySize = EC_DEFAULT_KEY_SIZE;
2080 } else if (keySize < EC_MIN_KEY_SIZE || keySize > EC_MAX_KEY_SIZE) {
2081 ALOGI("invalid key size %d", keySize);
Kenny Root96427ba2013-08-16 14:02:41 -07002082 return ::SYSTEM_ERROR;
2083 }
Chad Brubaker3a7d9e62015-06-04 15:01:46 -07002084 params.params.push_back(keymaster_param_int(KM_TAG_KEY_SIZE, keySize));
2085 break;
Kenny Root96427ba2013-08-16 14:02:41 -07002086 }
Chad Brubaker3a7d9e62015-06-04 15:01:46 -07002087 case EVP_PKEY_RSA: {
2088 params.params.push_back(keymaster_param_enum(KM_TAG_ALGORITHM, KM_ALGORITHM_RSA));
2089 if (keySize == -1) {
2090 keySize = RSA_DEFAULT_KEY_SIZE;
2091 } else if (keySize < RSA_MIN_KEY_SIZE || keySize > RSA_MAX_KEY_SIZE) {
2092 ALOGI("invalid key size %d", keySize);
2093 return ::SYSTEM_ERROR;
Kenny Root96427ba2013-08-16 14:02:41 -07002094 }
Chad Brubaker3a7d9e62015-06-04 15:01:46 -07002095 params.params.push_back(keymaster_param_int(KM_TAG_KEY_SIZE, keySize));
2096 unsigned long exponent = RSA_DEFAULT_EXPONENT;
2097 if (args->size() > 1) {
2098 ALOGI("invalid number of arguments: %zu", args->size());
2099 return ::SYSTEM_ERROR;
2100 } else if (args->size() == 1) {
2101 sp<KeystoreArg> expArg = args->itemAt(0);
2102 if (expArg != NULL) {
2103 Unique_BIGNUM pubExpBn(
2104 BN_bin2bn(reinterpret_cast<const unsigned char*>(expArg->data()),
2105 expArg->size(), NULL));
2106 if (pubExpBn.get() == NULL) {
2107 ALOGI("Could not convert public exponent to BN");
2108 return ::SYSTEM_ERROR;
2109 }
2110 exponent = BN_get_word(pubExpBn.get());
2111 if (exponent == 0xFFFFFFFFL) {
2112 ALOGW("cannot represent public exponent as a long value");
2113 return ::SYSTEM_ERROR;
2114 }
2115 } else {
2116 ALOGW("public exponent not read");
2117 return ::SYSTEM_ERROR;
2118 }
2119 }
2120 params.params.push_back(keymaster_param_long(KM_TAG_RSA_PUBLIC_EXPONENT,
2121 exponent));
2122 break;
Kenny Root96427ba2013-08-16 14:02:41 -07002123 }
Chad Brubaker3a7d9e62015-06-04 15:01:46 -07002124 default: {
2125 ALOGW("Unsupported key type %d", keyType);
2126 return ::SYSTEM_ERROR;
2127 }
Kenny Root96427ba2013-08-16 14:02:41 -07002128 }
2129
Chad Brubaker3a7d9e62015-06-04 15:01:46 -07002130 int32_t rc = generateKey(name, params, NULL, 0, targetUid, flags,
2131 /*outCharacteristics*/ NULL);
2132 if (rc != ::NO_ERROR) {
2133 ALOGW("generate failed: %d", rc);
Kenny Root07438c82012-11-02 15:41:02 -07002134 }
Chad Brubaker3a7d9e62015-06-04 15:01:46 -07002135 return translateResultToLegacyResult(rc);
Kenny Root70e3a862012-02-15 17:20:23 -08002136 }
2137
Kenny Rootf9119d62013-04-03 09:22:15 -07002138 int32_t import(const String16& name, const uint8_t* data, size_t length, int targetUid,
2139 int32_t flags) {
Chad Brubaker3a7d9e62015-06-04 15:01:46 -07002140 const uint8_t* ptr = data;
Kenny Root07438c82012-11-02 15:41:02 -07002141
Chad Brubaker3a7d9e62015-06-04 15:01:46 -07002142 Unique_PKCS8_PRIV_KEY_INFO pkcs8(d2i_PKCS8_PRIV_KEY_INFO(NULL, &ptr, length));
2143 if (!pkcs8.get()) {
2144 return ::SYSTEM_ERROR;
2145 }
2146 Unique_EVP_PKEY pkey(EVP_PKCS82PKEY(pkcs8.get()));
2147 if (!pkey.get()) {
2148 return ::SYSTEM_ERROR;
2149 }
2150 int type = EVP_PKEY_type(pkey->type);
Shawn Willden2de8b752015-07-23 05:54:31 -06002151 KeymasterArguments params;
Shawn Willden55268b52015-07-28 11:06:00 -06002152 add_legacy_key_authorizations(type, &params.params);
Chad Brubaker3a7d9e62015-06-04 15:01:46 -07002153 switch (type) {
2154 case EVP_PKEY_RSA:
2155 params.params.push_back(keymaster_param_enum(KM_TAG_ALGORITHM, KM_ALGORITHM_RSA));
2156 break;
2157 case EVP_PKEY_EC:
2158 params.params.push_back(keymaster_param_enum(KM_TAG_ALGORITHM,
2159 KM_ALGORITHM_EC));
2160 break;
2161 default:
2162 ALOGW("Unsupported key type %d", type);
2163 return ::SYSTEM_ERROR;
2164 }
2165 int32_t rc = importKey(name, params, KM_KEY_FORMAT_PKCS8, data, length, targetUid, flags,
2166 /*outCharacteristics*/ NULL);
2167 if (rc != ::NO_ERROR) {
2168 ALOGW("importKey failed: %d", rc);
2169 }
2170 return translateResultToLegacyResult(rc);
Kenny Root70e3a862012-02-15 17:20:23 -08002171 }
2172
Kenny Root07438c82012-11-02 15:41:02 -07002173 int32_t sign(const String16& name, const uint8_t* data, size_t length, uint8_t** out,
Chad Brubaker3a7d9e62015-06-04 15:01:46 -07002174 size_t* outLength) {
Chad Brubaker9489b792015-04-14 11:01:45 -07002175 if (!checkBinderPermission(P_SIGN)) {
Kenny Root07438c82012-11-02 15:41:02 -07002176 return ::PERMISSION_DENIED;
2177 }
Chad Brubaker3a7d9e62015-06-04 15:01:46 -07002178 return doLegacySignVerify(name, data, length, out, outLength, NULL, 0, KM_PURPOSE_SIGN);
Kenny Root70e3a862012-02-15 17:20:23 -08002179 }
2180
Kenny Root07438c82012-11-02 15:41:02 -07002181 int32_t verify(const String16& name, const uint8_t* data, size_t dataLength,
2182 const uint8_t* signature, size_t signatureLength) {
Chad Brubaker9489b792015-04-14 11:01:45 -07002183 if (!checkBinderPermission(P_VERIFY)) {
Kenny Root07438c82012-11-02 15:41:02 -07002184 return ::PERMISSION_DENIED;
2185 }
Chad Brubaker3a7d9e62015-06-04 15:01:46 -07002186 return doLegacySignVerify(name, data, dataLength, NULL, NULL, signature, signatureLength,
2187 KM_PURPOSE_VERIFY);
Kenny Roota91203b2012-02-15 15:00:46 -08002188 }
Kenny Root07438c82012-11-02 15:41:02 -07002189
2190 /*
2191 * TODO: The abstraction between things stored in hardware and regular blobs
2192 * of data stored on the filesystem should be moved down to keystore itself.
2193 * Unfortunately the Java code that calls this has naming conventions that it
2194 * knows about. Ideally keystore shouldn't be used to store random blobs of
2195 * data.
2196 *
2197 * Until that happens, it's necessary to have a separate "get_pubkey" and
2198 * "del_key" since the Java code doesn't really communicate what it's
2199 * intentions are.
2200 */
2201 int32_t get_pubkey(const String16& name, uint8_t** pubkey, size_t* pubkeyLength) {
Chad Brubaker3a7d9e62015-06-04 15:01:46 -07002202 ExportResult result;
2203 exportKey(name, KM_KEY_FORMAT_X509, NULL, NULL, &result);
2204 if (result.resultCode != ::NO_ERROR) {
2205 ALOGW("export failed: %d", result.resultCode);
2206 return translateResultToLegacyResult(result.resultCode);
Kenny Root07438c82012-11-02 15:41:02 -07002207 }
Kenny Root07438c82012-11-02 15:41:02 -07002208
Chad Brubaker3a7d9e62015-06-04 15:01:46 -07002209 *pubkey = result.exportData.release();
2210 *pubkeyLength = result.dataLength;
Kenny Root07438c82012-11-02 15:41:02 -07002211 return ::NO_ERROR;
Kenny Roota91203b2012-02-15 15:00:46 -08002212 }
Kenny Root07438c82012-11-02 15:41:02 -07002213
Kenny Root07438c82012-11-02 15:41:02 -07002214 int32_t grant(const String16& name, int32_t granteeUid) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08002215 uid_t callingUid = IPCThreadState::self()->getCallingUid();
Chad Brubaker9489b792015-04-14 11:01:45 -07002216 int32_t result = checkBinderPermissionAndKeystoreState(P_GRANT);
2217 if (result != ::NO_ERROR) {
2218 return result;
Kenny Root07438c82012-11-02 15:41:02 -07002219 }
2220
2221 String8 name8(name);
Kenny Root655b9582013-04-04 08:37:42 -07002222 String8 filename(mKeyStore->getKeyNameForUidWithDir(name8, callingUid));
Kenny Root07438c82012-11-02 15:41:02 -07002223
Kenny Root655b9582013-04-04 08:37:42 -07002224 if (access(filename.string(), R_OK) == -1) {
Kenny Root07438c82012-11-02 15:41:02 -07002225 return (errno != ENOENT) ? ::SYSTEM_ERROR : ::KEY_NOT_FOUND;
2226 }
2227
Kenny Root655b9582013-04-04 08:37:42 -07002228 mKeyStore->addGrant(filename.string(), granteeUid);
Kenny Root07438c82012-11-02 15:41:02 -07002229 return ::NO_ERROR;
2230 }
2231
2232 int32_t ungrant(const String16& name, int32_t granteeUid) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08002233 uid_t callingUid = IPCThreadState::self()->getCallingUid();
Chad Brubaker9489b792015-04-14 11:01:45 -07002234 int32_t result = checkBinderPermissionAndKeystoreState(P_GRANT);
2235 if (result != ::NO_ERROR) {
2236 return result;
Kenny Root07438c82012-11-02 15:41:02 -07002237 }
2238
2239 String8 name8(name);
Kenny Root655b9582013-04-04 08:37:42 -07002240 String8 filename(mKeyStore->getKeyNameForUidWithDir(name8, callingUid));
Kenny Root07438c82012-11-02 15:41:02 -07002241
Kenny Root655b9582013-04-04 08:37:42 -07002242 if (access(filename.string(), R_OK) == -1) {
Kenny Root07438c82012-11-02 15:41:02 -07002243 return (errno != ENOENT) ? ::SYSTEM_ERROR : ::KEY_NOT_FOUND;
2244 }
2245
Kenny Root655b9582013-04-04 08:37:42 -07002246 return mKeyStore->removeGrant(filename.string(), granteeUid) ? ::NO_ERROR : ::KEY_NOT_FOUND;
Kenny Root07438c82012-11-02 15:41:02 -07002247 }
2248
2249 int64_t getmtime(const String16& name) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08002250 uid_t callingUid = IPCThreadState::self()->getCallingUid();
Chad Brubaker9489b792015-04-14 11:01:45 -07002251 if (!checkBinderPermission(P_GET)) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08002252 ALOGW("permission denied for %d: getmtime", callingUid);
Kenny Root36a9e232013-02-04 14:24:15 -08002253 return -1L;
Kenny Root07438c82012-11-02 15:41:02 -07002254 }
Kenny Root07438c82012-11-02 15:41:02 -07002255
2256 String8 name8(name);
Kenny Root655b9582013-04-04 08:37:42 -07002257 String8 filename(mKeyStore->getKeyNameForUidWithDir(name8, callingUid));
Kenny Root07438c82012-11-02 15:41:02 -07002258
Kenny Root655b9582013-04-04 08:37:42 -07002259 if (access(filename.string(), R_OK) == -1) {
2260 ALOGW("could not access %s for getmtime", filename.string());
Kenny Root36a9e232013-02-04 14:24:15 -08002261 return -1L;
Kenny Root07438c82012-11-02 15:41:02 -07002262 }
2263
Kenny Root655b9582013-04-04 08:37:42 -07002264 int fd = TEMP_FAILURE_RETRY(open(filename.string(), O_NOFOLLOW, O_RDONLY));
Kenny Root07438c82012-11-02 15:41:02 -07002265 if (fd < 0) {
Kenny Root655b9582013-04-04 08:37:42 -07002266 ALOGW("could not open %s for getmtime", filename.string());
Kenny Root36a9e232013-02-04 14:24:15 -08002267 return -1L;
Kenny Root07438c82012-11-02 15:41:02 -07002268 }
2269
2270 struct stat s;
2271 int ret = fstat(fd, &s);
2272 close(fd);
2273 if (ret == -1) {
Kenny Root655b9582013-04-04 08:37:42 -07002274 ALOGW("could not stat %s for getmtime", filename.string());
Kenny Root36a9e232013-02-04 14:24:15 -08002275 return -1L;
Kenny Root07438c82012-11-02 15:41:02 -07002276 }
2277
Kenny Root36a9e232013-02-04 14:24:15 -08002278 return static_cast<int64_t>(s.st_mtime);
Kenny Root07438c82012-11-02 15:41:02 -07002279 }
2280
Kenny Rootd53bc922013-03-21 14:10:15 -07002281 int32_t duplicate(const String16& srcKey, int32_t srcUid, const String16& destKey,
2282 int32_t destUid) {
Kenny Root02254072013-03-20 11:48:19 -07002283 uid_t callingUid = IPCThreadState::self()->getCallingUid();
Riley Spahneaabae92014-06-30 12:39:52 -07002284 pid_t spid = IPCThreadState::self()->getCallingPid();
2285 if (!has_permission(callingUid, P_DUPLICATE, spid)) {
Kenny Rootd53bc922013-03-21 14:10:15 -07002286 ALOGW("permission denied for %d: duplicate", callingUid);
Kenny Root02254072013-03-20 11:48:19 -07002287 return -1L;
2288 }
2289
Chad Brubaker72593ee2015-05-12 10:42:00 -07002290 State state = mKeyStore->getState(get_user_id(callingUid));
Kenny Root02254072013-03-20 11:48:19 -07002291 if (!isKeystoreUnlocked(state)) {
Kenny Rootd53bc922013-03-21 14:10:15 -07002292 ALOGD("calling duplicate in state: %d", state);
Kenny Root02254072013-03-20 11:48:19 -07002293 return state;
2294 }
2295
Kenny Rootd53bc922013-03-21 14:10:15 -07002296 if (srcUid == -1 || static_cast<uid_t>(srcUid) == callingUid) {
2297 srcUid = callingUid;
2298 } else if (!is_granted_to(callingUid, srcUid)) {
2299 ALOGD("migrate not granted from source: %d -> %d", callingUid, srcUid);
Kenny Root02254072013-03-20 11:48:19 -07002300 return ::PERMISSION_DENIED;
2301 }
2302
Kenny Rootd53bc922013-03-21 14:10:15 -07002303 if (destUid == -1) {
2304 destUid = callingUid;
2305 }
2306
2307 if (srcUid != destUid) {
2308 if (static_cast<uid_t>(srcUid) != callingUid) {
2309 ALOGD("can only duplicate from caller to other or to same uid: "
2310 "calling=%d, srcUid=%d, destUid=%d", callingUid, srcUid, destUid);
2311 return ::PERMISSION_DENIED;
2312 }
2313
2314 if (!is_granted_to(callingUid, destUid)) {
2315 ALOGD("duplicate not granted to dest: %d -> %d", callingUid, destUid);
2316 return ::PERMISSION_DENIED;
2317 }
2318 }
2319
2320 String8 source8(srcKey);
Kenny Root655b9582013-04-04 08:37:42 -07002321 String8 sourceFile(mKeyStore->getKeyNameForUidWithDir(source8, srcUid));
Kenny Root02254072013-03-20 11:48:19 -07002322
Kenny Rootd53bc922013-03-21 14:10:15 -07002323 String8 target8(destKey);
Kenny Rootfa27d5b2013-10-15 09:01:08 -07002324 String8 targetFile(mKeyStore->getKeyNameForUidWithDir(target8, destUid));
Kenny Root02254072013-03-20 11:48:19 -07002325
Kenny Root655b9582013-04-04 08:37:42 -07002326 if (access(targetFile.string(), W_OK) != -1 || errno != ENOENT) {
2327 ALOGD("destination already exists: %s", targetFile.string());
Kenny Root02254072013-03-20 11:48:19 -07002328 return ::SYSTEM_ERROR;
2329 }
2330
Kenny Rootd53bc922013-03-21 14:10:15 -07002331 Blob keyBlob;
Kenny Root655b9582013-04-04 08:37:42 -07002332 ResponseCode responseCode = mKeyStore->get(sourceFile.string(), &keyBlob, TYPE_ANY,
Chad Brubaker72593ee2015-05-12 10:42:00 -07002333 get_user_id(srcUid));
Kenny Rootd53bc922013-03-21 14:10:15 -07002334 if (responseCode != ::NO_ERROR) {
2335 return responseCode;
Kenny Root02254072013-03-20 11:48:19 -07002336 }
Kenny Rootd53bc922013-03-21 14:10:15 -07002337
Chad Brubaker72593ee2015-05-12 10:42:00 -07002338 return mKeyStore->put(targetFile.string(), &keyBlob, get_user_id(destUid));
Kenny Root02254072013-03-20 11:48:19 -07002339 }
2340
Kenny Root1b0e3932013-09-05 13:06:32 -07002341 int32_t is_hardware_backed(const String16& keyType) {
2342 return mKeyStore->isHardwareBacked(keyType) ? 1 : 0;
Kenny Root8ddf35a2013-03-29 11:15:50 -07002343 }
2344
Kenny Rootfa27d5b2013-10-15 09:01:08 -07002345 int32_t clear_uid(int64_t targetUid64) {
Chad Brubaker9489b792015-04-14 11:01:45 -07002346 uid_t targetUid = getEffectiveUid(targetUid64);
Chad Brubakerb37a5232015-05-01 10:21:27 -07002347 if (!checkBinderPermissionSelfOrSystem(P_CLEAR_UID, targetUid)) {
Kenny Roota9bb5492013-04-01 16:29:11 -07002348 return ::PERMISSION_DENIED;
2349 }
2350
Robin Lee4b84fdc2014-09-24 11:56:57 +01002351 String8 prefix = String8::format("%u_", targetUid);
2352 Vector<String16> aliases;
Chad Brubakere6c3bfa2015-05-12 15:18:26 -07002353 if (mKeyStore->list(prefix, &aliases, get_user_id(targetUid)) != ::NO_ERROR) {
Kenny Roota9bb5492013-04-01 16:29:11 -07002354 return ::SYSTEM_ERROR;
2355 }
2356
Robin Lee4b84fdc2014-09-24 11:56:57 +01002357 for (uint32_t i = 0; i < aliases.size(); i++) {
2358 String8 name8(aliases[i]);
2359 String8 filename(mKeyStore->getKeyNameForUidWithDir(name8, targetUid));
Chad Brubaker72593ee2015-05-12 10:42:00 -07002360 mKeyStore->del(filename.string(), ::TYPE_ANY, get_user_id(targetUid));
Kenny Roota9bb5492013-04-01 16:29:11 -07002361 }
Robin Lee4b84fdc2014-09-24 11:56:57 +01002362 return ::NO_ERROR;
Kenny Roota9bb5492013-04-01 16:29:11 -07002363 }
2364
Chad Brubaker9c8612c2015-02-09 11:32:54 -08002365 int32_t addRngEntropy(const uint8_t* data, size_t dataLength) {
2366 const keymaster1_device_t* device = mKeyStore->getDevice();
2367 const keymaster1_device_t* fallback = mKeyStore->getFallbackDevice();
2368 int32_t devResult = KM_ERROR_UNIMPLEMENTED;
2369 int32_t fallbackResult = KM_ERROR_UNIMPLEMENTED;
2370 if (device->common.module->module_api_version >= KEYMASTER_MODULE_API_VERSION_1_0 &&
2371 device->add_rng_entropy != NULL) {
2372 devResult = device->add_rng_entropy(device, data, dataLength);
2373 }
2374 if (fallback->add_rng_entropy) {
2375 fallbackResult = fallback->add_rng_entropy(fallback, data, dataLength);
2376 }
2377 if (devResult) {
2378 return devResult;
2379 }
2380 if (fallbackResult) {
2381 return fallbackResult;
2382 }
2383 return ::NO_ERROR;
Chad Brubaker9899d6b2015-02-03 13:03:00 -08002384 }
2385
Chad Brubaker17d68b92015-02-05 22:04:16 -08002386 int32_t generateKey(const String16& name, const KeymasterArguments& params,
Chad Brubaker154d7692015-03-27 13:59:31 -07002387 const uint8_t* entropy, size_t entropyLength, int uid, int flags,
2388 KeyCharacteristics* outCharacteristics) {
Chad Brubaker9489b792015-04-14 11:01:45 -07002389 uid = getEffectiveUid(uid);
2390 int rc = checkBinderPermissionAndKeystoreState(P_INSERT, uid,
2391 flags & KEYSTORE_FLAG_ENCRYPTED);
2392 if (rc != ::NO_ERROR) {
2393 return rc;
Chad Brubaker17d68b92015-02-05 22:04:16 -08002394 }
2395
Chad Brubaker9489b792015-04-14 11:01:45 -07002396 rc = KM_ERROR_UNIMPLEMENTED;
Chad Brubaker17d68b92015-02-05 22:04:16 -08002397 bool isFallback = false;
2398 keymaster_key_blob_t blob;
2399 keymaster_key_characteristics_t *out = NULL;
2400
2401 const keymaster1_device_t* device = mKeyStore->getDevice();
2402 const keymaster1_device_t* fallback = mKeyStore->getFallbackDevice();
Chad Brubaker57e106d2015-06-01 12:59:00 -07002403 std::vector<keymaster_key_param_t> opParams(params.params);
2404 const keymaster_key_param_set_t inParams = {opParams.data(), opParams.size()};
Chad Brubaker17d68b92015-02-05 22:04:16 -08002405 if (device == NULL) {
2406 return ::SYSTEM_ERROR;
2407 }
Chad Brubaker154d7692015-03-27 13:59:31 -07002408 // TODO: Seed from Linux RNG before this.
Chad Brubaker17d68b92015-02-05 22:04:16 -08002409 if (device->common.module->module_api_version >= KEYMASTER_MODULE_API_VERSION_1_0 &&
2410 device->generate_key != NULL) {
Chad Brubaker154d7692015-03-27 13:59:31 -07002411 if (!entropy) {
2412 rc = KM_ERROR_OK;
2413 } else if (device->add_rng_entropy) {
2414 rc = device->add_rng_entropy(device, entropy, entropyLength);
2415 } else {
2416 rc = KM_ERROR_UNIMPLEMENTED;
2417 }
2418 if (rc == KM_ERROR_OK) {
Chad Brubaker57e106d2015-06-01 12:59:00 -07002419 rc = device->generate_key(device, &inParams, &blob, &out);
Chad Brubaker154d7692015-03-27 13:59:31 -07002420 }
Chad Brubaker17d68b92015-02-05 22:04:16 -08002421 }
2422 // If the HW device didn't support generate_key or generate_key failed
2423 // fall back to the software implementation.
2424 if (rc && fallback->generate_key != NULL) {
Shawn Willden55268b52015-07-28 11:06:00 -06002425 ALOGW("Primary keymaster device failed to generate key, falling back to SW.");
Chad Brubaker17d68b92015-02-05 22:04:16 -08002426 isFallback = true;
Chad Brubaker154d7692015-03-27 13:59:31 -07002427 if (!entropy) {
2428 rc = KM_ERROR_OK;
2429 } else if (fallback->add_rng_entropy) {
2430 rc = fallback->add_rng_entropy(fallback, entropy, entropyLength);
2431 } else {
2432 rc = KM_ERROR_UNIMPLEMENTED;
2433 }
2434 if (rc == KM_ERROR_OK) {
Chad Brubaker57e106d2015-06-01 12:59:00 -07002435 rc = fallback->generate_key(fallback, &inParams, &blob, &out);
Chad Brubaker154d7692015-03-27 13:59:31 -07002436 }
Chad Brubaker17d68b92015-02-05 22:04:16 -08002437 }
2438
2439 if (out) {
2440 if (outCharacteristics) {
2441 outCharacteristics->characteristics = *out;
2442 } else {
2443 keymaster_free_characteristics(out);
2444 }
2445 free(out);
2446 }
2447
2448 if (rc) {
2449 return rc;
2450 }
2451
2452 String8 name8(name);
2453 String8 filename(mKeyStore->getKeyNameForUidWithDir(name8, uid));
2454
2455 Blob keyBlob(blob.key_material, blob.key_material_size, NULL, 0, ::TYPE_KEYMASTER_10);
2456 keyBlob.setFallback(isFallback);
2457 keyBlob.setEncrypted(flags & KEYSTORE_FLAG_ENCRYPTED);
2458
2459 free(const_cast<uint8_t*>(blob.key_material));
2460
Chad Brubaker72593ee2015-05-12 10:42:00 -07002461 return mKeyStore->put(filename.string(), &keyBlob, get_user_id(uid));
Chad Brubaker9899d6b2015-02-03 13:03:00 -08002462 }
2463
Chad Brubakerf3f071f2015-02-10 19:38:51 -08002464 int32_t getKeyCharacteristics(const String16& name,
Chad Brubakerd6634422015-03-21 22:36:07 -07002465 const keymaster_blob_t* clientId,
2466 const keymaster_blob_t* appData,
Chad Brubakerf3f071f2015-02-10 19:38:51 -08002467 KeyCharacteristics* outCharacteristics) {
Chad Brubakerf3f071f2015-02-10 19:38:51 -08002468 if (!outCharacteristics) {
2469 return KM_ERROR_UNEXPECTED_NULL_POINTER;
2470 }
2471
2472 uid_t callingUid = IPCThreadState::self()->getCallingUid();
2473
2474 Blob keyBlob;
2475 String8 name8(name);
2476 int rc;
2477
2478 ResponseCode responseCode = mKeyStore->getKeyForName(&keyBlob, name8, callingUid,
2479 TYPE_KEYMASTER_10);
2480 if (responseCode != ::NO_ERROR) {
2481 return responseCode;
2482 }
2483 keymaster_key_blob_t key;
2484 key.key_material_size = keyBlob.getLength();
2485 key.key_material = keyBlob.getValue();
2486 keymaster1_device_t* dev = mKeyStore->getDeviceForBlob(keyBlob);
2487 keymaster_key_characteristics_t *out = NULL;
2488 if (!dev->get_key_characteristics) {
2489 ALOGW("device does not implement get_key_characteristics");
2490 return KM_ERROR_UNIMPLEMENTED;
2491 }
Chad Brubakerd6634422015-03-21 22:36:07 -07002492 rc = dev->get_key_characteristics(dev, &key, clientId, appData, &out);
Chad Brubakerf3f071f2015-02-10 19:38:51 -08002493 if (out) {
2494 outCharacteristics->characteristics = *out;
2495 free(out);
2496 }
2497 return rc ? rc : ::NO_ERROR;
Chad Brubaker9899d6b2015-02-03 13:03:00 -08002498 }
2499
Chad Brubaker4c353cb2015-02-11 14:36:11 -08002500 int32_t importKey(const String16& name, const KeymasterArguments& params,
2501 keymaster_key_format_t format, const uint8_t *keyData,
2502 size_t keyLength, int uid, int flags,
2503 KeyCharacteristics* outCharacteristics) {
Chad Brubaker9489b792015-04-14 11:01:45 -07002504 uid = getEffectiveUid(uid);
2505 int rc = checkBinderPermissionAndKeystoreState(P_INSERT, uid,
2506 flags & KEYSTORE_FLAG_ENCRYPTED);
2507 if (rc != ::NO_ERROR) {
2508 return rc;
Chad Brubaker4c353cb2015-02-11 14:36:11 -08002509 }
2510
Chad Brubaker9489b792015-04-14 11:01:45 -07002511 rc = KM_ERROR_UNIMPLEMENTED;
Chad Brubaker4c353cb2015-02-11 14:36:11 -08002512 bool isFallback = false;
2513 keymaster_key_blob_t blob;
2514 keymaster_key_characteristics_t *out = NULL;
2515
2516 const keymaster1_device_t* device = mKeyStore->getDevice();
2517 const keymaster1_device_t* fallback = mKeyStore->getFallbackDevice();
Chad Brubaker57e106d2015-06-01 12:59:00 -07002518 std::vector<keymaster_key_param_t> opParams(params.params);
2519 const keymaster_key_param_set_t inParams = {opParams.data(), opParams.size()};
2520 const keymaster_blob_t input = {keyData, keyLength};
Chad Brubaker4c353cb2015-02-11 14:36:11 -08002521 if (device == NULL) {
2522 return ::SYSTEM_ERROR;
2523 }
2524 if (device->common.module->module_api_version >= KEYMASTER_MODULE_API_VERSION_1_0 &&
2525 device->import_key != NULL) {
Chad Brubaker57e106d2015-06-01 12:59:00 -07002526 rc = device->import_key(device, &inParams, format,&input, &blob, &out);
Chad Brubaker4c353cb2015-02-11 14:36:11 -08002527 }
2528 if (rc && fallback->import_key != NULL) {
Shawn Willden55268b52015-07-28 11:06:00 -06002529 ALOGW("Primary keymaster device failed to import key, falling back to SW.");
Chad Brubaker4c353cb2015-02-11 14:36:11 -08002530 isFallback = true;
Chad Brubaker57e106d2015-06-01 12:59:00 -07002531 rc = fallback->import_key(fallback, &inParams, format, &input, &blob, &out);
Chad Brubaker4c353cb2015-02-11 14:36:11 -08002532 }
2533 if (out) {
2534 if (outCharacteristics) {
2535 outCharacteristics->characteristics = *out;
2536 } else {
2537 keymaster_free_characteristics(out);
2538 }
2539 free(out);
2540 }
2541 if (rc) {
2542 return rc;
2543 }
2544
2545 String8 name8(name);
2546 String8 filename(mKeyStore->getKeyNameForUidWithDir(name8, uid));
2547
2548 Blob keyBlob(blob.key_material, blob.key_material_size, NULL, 0, ::TYPE_KEYMASTER_10);
2549 keyBlob.setFallback(isFallback);
2550 keyBlob.setEncrypted(flags & KEYSTORE_FLAG_ENCRYPTED);
2551
2552 free((void*) blob.key_material);
2553
Chad Brubaker72593ee2015-05-12 10:42:00 -07002554 return mKeyStore->put(filename.string(), &keyBlob, get_user_id(uid));
Chad Brubaker9899d6b2015-02-03 13:03:00 -08002555 }
2556
Chad Brubaker07b0cda2015-02-18 15:52:54 -08002557 void exportKey(const String16& name, keymaster_key_format_t format,
Chad Brubakerd6634422015-03-21 22:36:07 -07002558 const keymaster_blob_t* clientId,
2559 const keymaster_blob_t* appData, ExportResult* result) {
Chad Brubaker07b0cda2015-02-18 15:52:54 -08002560
2561 uid_t callingUid = IPCThreadState::self()->getCallingUid();
2562
2563 Blob keyBlob;
2564 String8 name8(name);
2565 int rc;
2566
2567 ResponseCode responseCode = mKeyStore->getKeyForName(&keyBlob, name8, callingUid,
2568 TYPE_KEYMASTER_10);
2569 if (responseCode != ::NO_ERROR) {
2570 result->resultCode = responseCode;
2571 return;
2572 }
2573 keymaster_key_blob_t key;
2574 key.key_material_size = keyBlob.getLength();
2575 key.key_material = keyBlob.getValue();
2576 keymaster1_device_t* dev = mKeyStore->getDeviceForBlob(keyBlob);
2577 if (!dev->export_key) {
2578 result->resultCode = KM_ERROR_UNIMPLEMENTED;
2579 return;
2580 }
Chad Brubaker57e106d2015-06-01 12:59:00 -07002581 keymaster_blob_t output = {NULL, 0};
2582 rc = dev->export_key(dev, format, &key, clientId, appData, &output);
2583 result->exportData.reset(const_cast<uint8_t*>(output.data));
2584 result->dataLength = output.data_length;
Chad Brubaker07b0cda2015-02-18 15:52:54 -08002585 result->resultCode = rc ? rc : ::NO_ERROR;
Chad Brubaker9899d6b2015-02-03 13:03:00 -08002586 }
2587
Chad Brubakerad6514a2015-04-09 14:00:26 -07002588
Chad Brubaker40a1a9b2015-02-20 14:08:13 -08002589 void begin(const sp<IBinder>& appToken, const String16& name, keymaster_purpose_t purpose,
Chad Brubaker154d7692015-03-27 13:59:31 -07002590 bool pruneable, const KeymasterArguments& params, const uint8_t* entropy,
Chad Brubaker57e106d2015-06-01 12:59:00 -07002591 size_t entropyLength, OperationResult* result) {
Chad Brubaker40a1a9b2015-02-20 14:08:13 -08002592 uid_t callingUid = IPCThreadState::self()->getCallingUid();
2593 if (!pruneable && get_app_id(callingUid) != AID_SYSTEM) {
2594 ALOGE("Non-system uid %d trying to start non-pruneable operation", callingUid);
2595 result->resultCode = ::PERMISSION_DENIED;
2596 return;
2597 }
Chad Brubaker0cf34a22015-04-23 11:06:16 -07002598 if (!checkAllowedOperationParams(params.params)) {
2599 result->resultCode = KM_ERROR_INVALID_ARGUMENT;
2600 return;
2601 }
Chad Brubaker40a1a9b2015-02-20 14:08:13 -08002602 Blob keyBlob;
2603 String8 name8(name);
2604 ResponseCode responseCode = mKeyStore->getKeyForName(&keyBlob, name8, callingUid,
2605 TYPE_KEYMASTER_10);
2606 if (responseCode != ::NO_ERROR) {
2607 result->resultCode = responseCode;
2608 return;
2609 }
2610 keymaster_key_blob_t key;
2611 key.key_material_size = keyBlob.getLength();
2612 key.key_material = keyBlob.getValue();
Chad Brubaker40a1a9b2015-02-20 14:08:13 -08002613 keymaster_operation_handle_t handle;
2614 keymaster1_device_t* dev = mKeyStore->getDeviceForBlob(keyBlob);
Chad Brubaker154d7692015-03-27 13:59:31 -07002615 keymaster_error_t err = KM_ERROR_UNIMPLEMENTED;
Chad Brubaker06801e02015-03-31 15:13:13 -07002616 std::vector<keymaster_key_param_t> opParams(params.params);
Chad Brubakerad6514a2015-04-09 14:00:26 -07002617 Unique_keymaster_key_characteristics characteristics;
2618 characteristics.reset(new keymaster_key_characteristics_t);
2619 err = getOperationCharacteristics(key, dev, opParams, characteristics.get());
2620 if (err) {
2621 result->resultCode = err;
2622 return;
2623 }
Chad Brubaker0cf34a22015-04-23 11:06:16 -07002624 const hw_auth_token_t* authToken = NULL;
Shawn Willdenb2ffa422015-06-17 12:18:55 -06002625 int32_t authResult = getAuthToken(characteristics.get(), 0, purpose, &authToken,
Chad Brubaker06801e02015-03-31 15:13:13 -07002626 /*failOnTokenMissing*/ false);
Chad Brubaker0cf34a22015-04-23 11:06:16 -07002627 // If per-operation auth is needed we need to begin the operation and
2628 // the client will need to authorize that operation before calling
2629 // update. Any other auth issues stop here.
2630 if (authResult != ::NO_ERROR && authResult != ::OP_AUTH_NEEDED) {
2631 result->resultCode = authResult;
Chad Brubaker06801e02015-03-31 15:13:13 -07002632 return;
2633 }
Chad Brubaker0cf34a22015-04-23 11:06:16 -07002634 addAuthToParams(&opParams, authToken);
Chad Brubaker154d7692015-03-27 13:59:31 -07002635 // Add entropy to the device first.
2636 if (entropy) {
2637 if (dev->add_rng_entropy) {
2638 err = dev->add_rng_entropy(dev, entropy, entropyLength);
2639 } else {
2640 err = KM_ERROR_UNIMPLEMENTED;
2641 }
2642 if (err) {
2643 result->resultCode = err;
2644 return;
2645 }
2646 }
Chad Brubaker57e106d2015-06-01 12:59:00 -07002647 keymaster_key_param_set_t inParams = {opParams.data(), opParams.size()};
Chad Brubaker40a1a9b2015-02-20 14:08:13 -08002648
Shawn Willden9221bff2015-06-18 18:23:54 -06002649 // Create a keyid for this key.
2650 keymaster::km_id_t keyid;
2651 if (!enforcement_policy.CreateKeyId(key, &keyid)) {
2652 ALOGE("Failed to create a key ID for authorization checking.");
2653 result->resultCode = KM_ERROR_UNKNOWN_ERROR;
2654 return;
2655 }
2656
2657 // Check that all key authorization policy requirements are met.
2658 keymaster::AuthorizationSet key_auths(characteristics->hw_enforced);
2659 key_auths.push_back(characteristics->sw_enforced);
2660 keymaster::AuthorizationSet operation_params(inParams);
2661 err = enforcement_policy.AuthorizeOperation(purpose, keyid, key_auths, operation_params,
2662 0 /* op_handle */,
2663 true /* is_begin_operation */);
2664 if (err) {
2665 result->resultCode = err;
2666 return;
2667 }
2668
Alex Klyubin4e88f9b2015-06-23 15:04:05 -07002669 keymaster_key_param_set_t outParams = {NULL, 0};
Shawn Willden447095f2015-10-30 10:05:43 -06002670
2671 // If there are more than MAX_OPERATIONS, abort the oldest operation that was started as
2672 // pruneable.
2673 while (mOperationMap.getOperationCount() >= MAX_OPERATIONS) {
2674 ALOGD("Reached or exceeded concurrent operations limit");
2675 if (!pruneOperation()) {
2676 break;
2677 }
2678 }
2679
Alex Klyubin4e88f9b2015-06-23 15:04:05 -07002680 err = dev->begin(dev, purpose, &key, &inParams, &outParams, &handle);
Shawn Willden447095f2015-10-30 10:05:43 -06002681 if (err != KM_ERROR_OK) {
2682 ALOGE("Got error %d from begin()", err);
2683 }
Alex Klyubin4e88f9b2015-06-23 15:04:05 -07002684
Chad Brubaker40a1a9b2015-02-20 14:08:13 -08002685 // If there are too many operations abort the oldest operation that was
2686 // started as pruneable and try again.
2687 while (err == KM_ERROR_TOO_MANY_OPERATIONS && mOperationMap.hasPruneableOperation()) {
Shawn Willden447095f2015-10-30 10:05:43 -06002688 ALOGE("Ran out of operation handles");
2689 if (!pruneOperation()) {
Chad Brubaker40a1a9b2015-02-20 14:08:13 -08002690 break;
2691 }
Chad Brubaker57e106d2015-06-01 12:59:00 -07002692 err = dev->begin(dev, purpose, &key, &inParams, &outParams, &handle);
Chad Brubaker40a1a9b2015-02-20 14:08:13 -08002693 }
2694 if (err) {
2695 result->resultCode = err;
2696 return;
2697 }
Chad Brubaker40a1a9b2015-02-20 14:08:13 -08002698
Shawn Willden9221bff2015-06-18 18:23:54 -06002699 sp<IBinder> operationToken = mOperationMap.addOperation(handle, keyid, purpose, dev,
2700 appToken, characteristics.release(),
Chad Brubaker06801e02015-03-31 15:13:13 -07002701 pruneable);
Chad Brubaker0cf34a22015-04-23 11:06:16 -07002702 if (authToken) {
2703 mOperationMap.setOperationAuthToken(operationToken, authToken);
2704 }
2705 // Return the authentication lookup result. If this is a per operation
2706 // auth'd key then the resultCode will be ::OP_AUTH_NEEDED and the
2707 // application should get an auth token using the handle before the
2708 // first call to update, which will fail if keystore hasn't received the
2709 // auth token.
2710 result->resultCode = authResult;
Chad Brubaker40a1a9b2015-02-20 14:08:13 -08002711 result->token = operationToken;
Chad Brubakerc3a18562015-03-17 18:21:35 -07002712 result->handle = handle;
Chad Brubaker57e106d2015-06-01 12:59:00 -07002713 if (outParams.params) {
2714 result->outParams.params.assign(outParams.params, outParams.params + outParams.length);
2715 free(outParams.params);
2716 }
Chad Brubaker9899d6b2015-02-03 13:03:00 -08002717 }
2718
Chad Brubaker40a1a9b2015-02-20 14:08:13 -08002719 void update(const sp<IBinder>& token, const KeymasterArguments& params, const uint8_t* data,
2720 size_t dataLength, OperationResult* result) {
Chad Brubaker0cf34a22015-04-23 11:06:16 -07002721 if (!checkAllowedOperationParams(params.params)) {
2722 result->resultCode = KM_ERROR_INVALID_ARGUMENT;
2723 return;
2724 }
Chad Brubaker40a1a9b2015-02-20 14:08:13 -08002725 const keymaster1_device_t* dev;
2726 keymaster_operation_handle_t handle;
Shawn Willdenb2ffa422015-06-17 12:18:55 -06002727 keymaster_purpose_t purpose;
Shawn Willden9221bff2015-06-18 18:23:54 -06002728 keymaster::km_id_t keyid;
2729 const keymaster_key_characteristics_t* characteristics;
2730 if (!mOperationMap.getOperation(token, &handle, &keyid, &purpose, &dev, &characteristics)) {
Chad Brubaker40a1a9b2015-02-20 14:08:13 -08002731 result->resultCode = KM_ERROR_INVALID_OPERATION_HANDLE;
2732 return;
2733 }
Chad Brubaker06801e02015-03-31 15:13:13 -07002734 std::vector<keymaster_key_param_t> opParams(params.params);
Chad Brubaker0cf34a22015-04-23 11:06:16 -07002735 int32_t authResult = addOperationAuthTokenIfNeeded(token, &opParams);
2736 if (authResult != ::NO_ERROR) {
Chad Brubaker06801e02015-03-31 15:13:13 -07002737 result->resultCode = authResult;
2738 return;
2739 }
Chad Brubaker57e106d2015-06-01 12:59:00 -07002740 keymaster_key_param_set_t inParams = {opParams.data(), opParams.size()};
2741 keymaster_blob_t input = {data, dataLength};
2742 size_t consumed = 0;
2743 keymaster_blob_t output = {NULL, 0};
2744 keymaster_key_param_set_t outParams = {NULL, 0};
2745
Shawn Willden9221bff2015-06-18 18:23:54 -06002746 // Check that all key authorization policy requirements are met.
2747 keymaster::AuthorizationSet key_auths(characteristics->hw_enforced);
2748 key_auths.push_back(characteristics->sw_enforced);
2749 keymaster::AuthorizationSet operation_params(inParams);
2750 result->resultCode =
2751 enforcement_policy.AuthorizeOperation(purpose, keyid, key_auths,
2752 operation_params, handle,
2753 false /* is_begin_operation */);
2754 if (result->resultCode) {
2755 return;
2756 }
2757
Chad Brubaker57e106d2015-06-01 12:59:00 -07002758 keymaster_error_t err = dev->update(dev, handle, &inParams, &input, &consumed, &outParams,
2759 &output);
2760 result->data.reset(const_cast<uint8_t*>(output.data));
2761 result->dataLength = output.data_length;
Chad Brubaker40a1a9b2015-02-20 14:08:13 -08002762 result->inputConsumed = consumed;
2763 result->resultCode = err ? (int32_t) err : ::NO_ERROR;
Chad Brubaker57e106d2015-06-01 12:59:00 -07002764 if (outParams.params) {
2765 result->outParams.params.assign(outParams.params, outParams.params + outParams.length);
2766 free(outParams.params);
2767 }
Chad Brubaker9899d6b2015-02-03 13:03:00 -08002768 }
2769
Chad Brubaker40a1a9b2015-02-20 14:08:13 -08002770 void finish(const sp<IBinder>& token, const KeymasterArguments& params,
Chad Brubaker0d33e0b2015-05-29 12:30:19 -07002771 const uint8_t* signature, size_t signatureLength,
2772 const uint8_t* entropy, size_t entropyLength, OperationResult* result) {
Chad Brubaker0cf34a22015-04-23 11:06:16 -07002773 if (!checkAllowedOperationParams(params.params)) {
2774 result->resultCode = KM_ERROR_INVALID_ARGUMENT;
2775 return;
2776 }
Chad Brubaker40a1a9b2015-02-20 14:08:13 -08002777 const keymaster1_device_t* dev;
2778 keymaster_operation_handle_t handle;
Shawn Willdenb2ffa422015-06-17 12:18:55 -06002779 keymaster_purpose_t purpose;
Shawn Willden9221bff2015-06-18 18:23:54 -06002780 keymaster::km_id_t keyid;
2781 const keymaster_key_characteristics_t* characteristics;
2782 if (!mOperationMap.getOperation(token, &handle, &keyid, &purpose, &dev, &characteristics)) {
Chad Brubaker40a1a9b2015-02-20 14:08:13 -08002783 result->resultCode = KM_ERROR_INVALID_OPERATION_HANDLE;
2784 return;
2785 }
Chad Brubaker06801e02015-03-31 15:13:13 -07002786 std::vector<keymaster_key_param_t> opParams(params.params);
Chad Brubaker0cf34a22015-04-23 11:06:16 -07002787 int32_t authResult = addOperationAuthTokenIfNeeded(token, &opParams);
2788 if (authResult != ::NO_ERROR) {
Chad Brubaker06801e02015-03-31 15:13:13 -07002789 result->resultCode = authResult;
2790 return;
2791 }
Chad Brubaker0d33e0b2015-05-29 12:30:19 -07002792 keymaster_error_t err;
2793 if (entropy) {
2794 if (dev->add_rng_entropy) {
2795 err = dev->add_rng_entropy(dev, entropy, entropyLength);
2796 } else {
2797 err = KM_ERROR_UNIMPLEMENTED;
2798 }
2799 if (err) {
2800 result->resultCode = err;
2801 return;
2802 }
2803 }
Chad Brubaker0cf34a22015-04-23 11:06:16 -07002804
Chad Brubaker57e106d2015-06-01 12:59:00 -07002805 keymaster_key_param_set_t inParams = {opParams.data(), opParams.size()};
2806 keymaster_blob_t input = {signature, signatureLength};
2807 keymaster_blob_t output = {NULL, 0};
2808 keymaster_key_param_set_t outParams = {NULL, 0};
Shawn Willden9221bff2015-06-18 18:23:54 -06002809
2810 // Check that all key authorization policy requirements are met.
2811 keymaster::AuthorizationSet key_auths(characteristics->hw_enforced);
2812 key_auths.push_back(characteristics->sw_enforced);
2813 keymaster::AuthorizationSet operation_params(inParams);
2814 err = enforcement_policy.AuthorizeOperation(purpose, keyid, key_auths, operation_params,
2815 handle, false /* is_begin_operation */);
2816 if (err) {
2817 result->resultCode = err;
2818 return;
2819 }
2820
Chad Brubaker0d33e0b2015-05-29 12:30:19 -07002821 err = dev->finish(dev, handle, &inParams, &input, &outParams, &output);
Chad Brubaker40a1a9b2015-02-20 14:08:13 -08002822 // Remove the operation regardless of the result
2823 mOperationMap.removeOperation(token);
Chad Brubaker06801e02015-03-31 15:13:13 -07002824 mAuthTokenTable.MarkCompleted(handle);
Chad Brubaker57e106d2015-06-01 12:59:00 -07002825
2826 result->data.reset(const_cast<uint8_t*>(output.data));
2827 result->dataLength = output.data_length;
Chad Brubaker40a1a9b2015-02-20 14:08:13 -08002828 result->resultCode = err ? (int32_t) err : ::NO_ERROR;
Chad Brubaker57e106d2015-06-01 12:59:00 -07002829 if (outParams.params) {
2830 result->outParams.params.assign(outParams.params, outParams.params + outParams.length);
2831 free(outParams.params);
2832 }
Chad Brubaker9899d6b2015-02-03 13:03:00 -08002833 }
2834
Chad Brubaker40a1a9b2015-02-20 14:08:13 -08002835 int32_t abort(const sp<IBinder>& token) {
2836 const keymaster1_device_t* dev;
2837 keymaster_operation_handle_t handle;
Shawn Willdenb2ffa422015-06-17 12:18:55 -06002838 keymaster_purpose_t purpose;
Shawn Willden9221bff2015-06-18 18:23:54 -06002839 keymaster::km_id_t keyid;
2840 if (!mOperationMap.getOperation(token, &handle, &keyid, &purpose, &dev, NULL)) {
Chad Brubaker40a1a9b2015-02-20 14:08:13 -08002841 return KM_ERROR_INVALID_OPERATION_HANDLE;
2842 }
2843 mOperationMap.removeOperation(token);
Chad Brubaker06801e02015-03-31 15:13:13 -07002844 int32_t rc;
Chad Brubaker40a1a9b2015-02-20 14:08:13 -08002845 if (!dev->abort) {
Chad Brubaker06801e02015-03-31 15:13:13 -07002846 rc = KM_ERROR_UNIMPLEMENTED;
2847 } else {
2848 rc = dev->abort(dev, handle);
Chad Brubaker40a1a9b2015-02-20 14:08:13 -08002849 }
Chad Brubaker06801e02015-03-31 15:13:13 -07002850 mAuthTokenTable.MarkCompleted(handle);
Chad Brubaker40a1a9b2015-02-20 14:08:13 -08002851 if (rc) {
2852 return rc;
2853 }
2854 return ::NO_ERROR;
Chad Brubaker9899d6b2015-02-03 13:03:00 -08002855 }
2856
Chad Brubaker2ed2baa2015-03-21 21:20:10 -07002857 bool isOperationAuthorized(const sp<IBinder>& token) {
2858 const keymaster1_device_t* dev;
2859 keymaster_operation_handle_t handle;
Chad Brubakerad6514a2015-04-09 14:00:26 -07002860 const keymaster_key_characteristics_t* characteristics;
Shawn Willdenb2ffa422015-06-17 12:18:55 -06002861 keymaster_purpose_t purpose;
Shawn Willden9221bff2015-06-18 18:23:54 -06002862 keymaster::km_id_t keyid;
2863 if (!mOperationMap.getOperation(token, &handle, &keyid, &purpose, &dev, &characteristics)) {
Chad Brubaker2ed2baa2015-03-21 21:20:10 -07002864 return false;
2865 }
Chad Brubaker0cf34a22015-04-23 11:06:16 -07002866 const hw_auth_token_t* authToken = NULL;
2867 mOperationMap.getOperationAuthToken(token, &authToken);
Chad Brubaker06801e02015-03-31 15:13:13 -07002868 std::vector<keymaster_key_param_t> ignored;
Chad Brubaker0cf34a22015-04-23 11:06:16 -07002869 int32_t authResult = addOperationAuthTokenIfNeeded(token, &ignored);
2870 return authResult == ::NO_ERROR;
Chad Brubaker2ed2baa2015-03-21 21:20:10 -07002871 }
2872
Chad Brubakerd80c7b42015-03-31 11:04:28 -07002873 int32_t addAuthToken(const uint8_t* token, size_t length) {
Chad Brubaker9489b792015-04-14 11:01:45 -07002874 if (!checkBinderPermission(P_ADD_AUTH)) {
2875 ALOGW("addAuthToken: permission denied for %d",
2876 IPCThreadState::self()->getCallingUid());
Chad Brubakerd80c7b42015-03-31 11:04:28 -07002877 return ::PERMISSION_DENIED;
2878 }
2879 if (length != sizeof(hw_auth_token_t)) {
2880 return KM_ERROR_INVALID_ARGUMENT;
2881 }
2882 hw_auth_token_t* authToken = new hw_auth_token_t;
2883 memcpy(reinterpret_cast<void*>(authToken), token, sizeof(hw_auth_token_t));
2884 // The table takes ownership of authToken.
2885 mAuthTokenTable.AddAuthenticationToken(authToken);
2886 return ::NO_ERROR;
Chad Brubaker2ed2baa2015-03-21 21:20:10 -07002887 }
2888
Kenny Root07438c82012-11-02 15:41:02 -07002889private:
Chad Brubaker9489b792015-04-14 11:01:45 -07002890 static const int32_t UID_SELF = -1;
2891
2892 /**
Shawn Willden447095f2015-10-30 10:05:43 -06002893 * Prune the oldest pruneable operation.
2894 */
2895 inline bool pruneOperation() {
2896 sp<IBinder> oldest = mOperationMap.getOldestPruneableOperation();
2897 ALOGD("Trying to prune operation %p", oldest.get());
2898 size_t op_count_before_abort = mOperationMap.getOperationCount();
2899 // We mostly ignore errors from abort() because all we care about is whether at least
2900 // one operation has been removed.
2901 int abort_error = abort(oldest);
2902 if (mOperationMap.getOperationCount() >= op_count_before_abort) {
2903 ALOGE("Failed to abort pruneable operation %p, error: %d", oldest.get(),
2904 abort_error);
2905 return false;
2906 }
2907 return true;
2908 }
2909
2910 /**
Chad Brubaker9489b792015-04-14 11:01:45 -07002911 * Get the effective target uid for a binder operation that takes an
2912 * optional uid as the target.
2913 */
2914 inline uid_t getEffectiveUid(int32_t targetUid) {
2915 if (targetUid == UID_SELF) {
2916 return IPCThreadState::self()->getCallingUid();
2917 }
2918 return static_cast<uid_t>(targetUid);
2919 }
2920
2921 /**
2922 * Check if the caller of the current binder method has the required
2923 * permission and if acting on other uids the grants to do so.
2924 */
2925 inline bool checkBinderPermission(perm_t permission, int32_t targetUid = UID_SELF) {
2926 uid_t callingUid = IPCThreadState::self()->getCallingUid();
2927 pid_t spid = IPCThreadState::self()->getCallingPid();
2928 if (!has_permission(callingUid, permission, spid)) {
2929 ALOGW("permission %s denied for %d", get_perm_label(permission), callingUid);
2930 return false;
2931 }
2932 if (!is_granted_to(callingUid, getEffectiveUid(targetUid))) {
2933 ALOGW("uid %d not granted to act for %d", callingUid, targetUid);
2934 return false;
2935 }
2936 return true;
2937 }
2938
2939 /**
2940 * Check if the caller of the current binder method has the required
Chad Brubakerb37a5232015-05-01 10:21:27 -07002941 * permission and the target uid is the caller or the caller is system.
2942 */
2943 inline bool checkBinderPermissionSelfOrSystem(perm_t permission, int32_t targetUid) {
2944 uid_t callingUid = IPCThreadState::self()->getCallingUid();
2945 pid_t spid = IPCThreadState::self()->getCallingPid();
2946 if (!has_permission(callingUid, permission, spid)) {
2947 ALOGW("permission %s denied for %d", get_perm_label(permission), callingUid);
2948 return false;
2949 }
2950 return getEffectiveUid(targetUid) == callingUid || callingUid == AID_SYSTEM;
2951 }
2952
2953 /**
2954 * Check if the caller of the current binder method has the required
Chad Brubaker9489b792015-04-14 11:01:45 -07002955 * permission or the target of the operation is the caller's uid. This is
2956 * for operation where the permission is only for cross-uid activity and all
2957 * uids are allowed to act on their own (ie: clearing all entries for a
2958 * given uid).
2959 */
2960 inline bool checkBinderPermissionOrSelfTarget(perm_t permission, int32_t targetUid) {
2961 uid_t callingUid = IPCThreadState::self()->getCallingUid();
2962 if (getEffectiveUid(targetUid) == callingUid) {
2963 return true;
2964 } else {
2965 return checkBinderPermission(permission, targetUid);
2966 }
2967 }
2968
2969 /**
2970 * Helper method to check that the caller has the required permission as
2971 * well as the keystore is in the unlocked state if checkUnlocked is true.
2972 *
2973 * Returns NO_ERROR on success, PERMISSION_DENIED on a permission error and
2974 * otherwise the state of keystore when not unlocked and checkUnlocked is
2975 * true.
2976 */
2977 inline int32_t checkBinderPermissionAndKeystoreState(perm_t permission, int32_t targetUid = -1,
2978 bool checkUnlocked = true) {
2979 if (!checkBinderPermission(permission, targetUid)) {
2980 return ::PERMISSION_DENIED;
2981 }
Chad Brubaker72593ee2015-05-12 10:42:00 -07002982 State state = mKeyStore->getState(get_user_id(getEffectiveUid(targetUid)));
Chad Brubaker9489b792015-04-14 11:01:45 -07002983 if (checkUnlocked && !isKeystoreUnlocked(state)) {
2984 return state;
2985 }
2986
2987 return ::NO_ERROR;
2988
2989 }
2990
Kenny Root9d45d1c2013-02-14 10:32:30 -08002991 inline bool isKeystoreUnlocked(State state) {
2992 switch (state) {
2993 case ::STATE_NO_ERROR:
2994 return true;
2995 case ::STATE_UNINITIALIZED:
2996 case ::STATE_LOCKED:
2997 return false;
2998 }
2999 return false;
Kenny Root07438c82012-11-02 15:41:02 -07003000 }
3001
Chad Brubaker67d2a502015-03-11 17:21:18 +00003002 bool isKeyTypeSupported(const keymaster1_device_t* device, keymaster_keypair_t keyType) {
Kenny Root1d448c02013-11-21 10:36:53 -08003003 const int32_t device_api = device->common.module->module_api_version;
3004 if (device_api == KEYMASTER_MODULE_API_VERSION_0_2) {
3005 switch (keyType) {
3006 case TYPE_RSA:
3007 case TYPE_DSA:
3008 case TYPE_EC:
3009 return true;
3010 default:
3011 return false;
3012 }
3013 } else if (device_api >= KEYMASTER_MODULE_API_VERSION_0_3) {
3014 switch (keyType) {
3015 case TYPE_RSA:
3016 return true;
3017 case TYPE_DSA:
3018 return device->flags & KEYMASTER_SUPPORTS_DSA;
3019 case TYPE_EC:
3020 return device->flags & KEYMASTER_SUPPORTS_EC;
3021 default:
3022 return false;
3023 }
3024 } else {
3025 return keyType == TYPE_RSA;
3026 }
3027 }
3028
Chad Brubaker0cf34a22015-04-23 11:06:16 -07003029 /**
3030 * Check that all keymaster_key_param_t's provided by the application are
3031 * allowed. Any parameter that keystore adds itself should be disallowed here.
3032 */
3033 bool checkAllowedOperationParams(const std::vector<keymaster_key_param_t>& params) {
3034 for (auto param: params) {
3035 switch (param.tag) {
3036 case KM_TAG_AUTH_TOKEN:
3037 return false;
3038 default:
3039 break;
3040 }
3041 }
3042 return true;
3043 }
3044
3045 keymaster_error_t getOperationCharacteristics(const keymaster_key_blob_t& key,
3046 const keymaster1_device_t* dev,
3047 const std::vector<keymaster_key_param_t>& params,
3048 keymaster_key_characteristics_t* out) {
3049 UniquePtr<keymaster_blob_t> appId;
3050 UniquePtr<keymaster_blob_t> appData;
3051 for (auto param : params) {
3052 if (param.tag == KM_TAG_APPLICATION_ID) {
3053 appId.reset(new keymaster_blob_t);
3054 appId->data = param.blob.data;
3055 appId->data_length = param.blob.data_length;
3056 } else if (param.tag == KM_TAG_APPLICATION_DATA) {
3057 appData.reset(new keymaster_blob_t);
3058 appData->data = param.blob.data;
3059 appData->data_length = param.blob.data_length;
3060 }
3061 }
3062 keymaster_key_characteristics_t* result = NULL;
3063 if (!dev->get_key_characteristics) {
3064 return KM_ERROR_UNIMPLEMENTED;
3065 }
3066 keymaster_error_t error = dev->get_key_characteristics(dev, &key, appId.get(),
3067 appData.get(), &result);
3068 if (result) {
3069 *out = *result;
3070 free(result);
3071 }
3072 return error;
3073 }
3074
3075 /**
3076 * Get the auth token for this operation from the auth token table.
3077 *
3078 * Returns ::NO_ERROR if the auth token was set or none was required.
3079 * ::OP_AUTH_NEEDED if it is a per op authorization, no
3080 * authorization token exists for that operation and
3081 * failOnTokenMissing is false.
3082 * KM_ERROR_KEY_USER_NOT_AUTHENTICATED if there is no valid auth
3083 * token for the operation
3084 */
3085 int32_t getAuthToken(const keymaster_key_characteristics_t* characteristics,
3086 keymaster_operation_handle_t handle,
Shawn Willdenb2ffa422015-06-17 12:18:55 -06003087 keymaster_purpose_t purpose,
Chad Brubaker0cf34a22015-04-23 11:06:16 -07003088 const hw_auth_token_t** authToken,
3089 bool failOnTokenMissing = true) {
3090
3091 std::vector<keymaster_key_param_t> allCharacteristics;
3092 for (size_t i = 0; i < characteristics->sw_enforced.length; i++) {
3093 allCharacteristics.push_back(characteristics->sw_enforced.params[i]);
3094 }
3095 for (size_t i = 0; i < characteristics->hw_enforced.length; i++) {
3096 allCharacteristics.push_back(characteristics->hw_enforced.params[i]);
3097 }
Shawn Willdenb2ffa422015-06-17 12:18:55 -06003098 keymaster::AuthTokenTable::Error err = mAuthTokenTable.FindAuthorization(
3099 allCharacteristics.data(), allCharacteristics.size(), purpose, handle, authToken);
Chad Brubaker0cf34a22015-04-23 11:06:16 -07003100 switch (err) {
3101 case keymaster::AuthTokenTable::OK:
3102 case keymaster::AuthTokenTable::AUTH_NOT_REQUIRED:
3103 return ::NO_ERROR;
3104 case keymaster::AuthTokenTable::AUTH_TOKEN_NOT_FOUND:
3105 case keymaster::AuthTokenTable::AUTH_TOKEN_EXPIRED:
3106 case keymaster::AuthTokenTable::AUTH_TOKEN_WRONG_SID:
3107 return KM_ERROR_KEY_USER_NOT_AUTHENTICATED;
3108 case keymaster::AuthTokenTable::OP_HANDLE_REQUIRED:
3109 return failOnTokenMissing ? (int32_t) KM_ERROR_KEY_USER_NOT_AUTHENTICATED :
3110 (int32_t) ::OP_AUTH_NEEDED;
3111 default:
3112 ALOGE("Unexpected FindAuthorization return value %d", err);
3113 return KM_ERROR_INVALID_ARGUMENT;
3114 }
3115 }
3116
3117 inline void addAuthToParams(std::vector<keymaster_key_param_t>* params,
3118 const hw_auth_token_t* token) {
3119 if (token) {
3120 params->push_back(keymaster_param_blob(KM_TAG_AUTH_TOKEN,
3121 reinterpret_cast<const uint8_t*>(token),
3122 sizeof(hw_auth_token_t)));
3123 }
3124 }
3125
3126 /**
3127 * Add the auth token for the operation to the param list if the operation
3128 * requires authorization. Uses the cached result in the OperationMap if available
3129 * otherwise gets the token from the AuthTokenTable and caches the result.
3130 *
3131 * Returns ::NO_ERROR if the auth token was added or not needed.
3132 * KM_ERROR_KEY_USER_NOT_AUTHENTICATED if the operation is not
3133 * authenticated.
3134 * KM_ERROR_INVALID_OPERATION_HANDLE if token is not a valid
3135 * operation token.
3136 */
3137 int32_t addOperationAuthTokenIfNeeded(sp<IBinder> token,
3138 std::vector<keymaster_key_param_t>* params) {
3139 const hw_auth_token_t* authToken = NULL;
Chad Brubaker7169a842015-04-29 19:58:34 -07003140 mOperationMap.getOperationAuthToken(token, &authToken);
3141 if (!authToken) {
Chad Brubaker0cf34a22015-04-23 11:06:16 -07003142 const keymaster1_device_t* dev;
3143 keymaster_operation_handle_t handle;
3144 const keymaster_key_characteristics_t* characteristics = NULL;
Shawn Willdenb2ffa422015-06-17 12:18:55 -06003145 keymaster_purpose_t purpose;
Shawn Willden9221bff2015-06-18 18:23:54 -06003146 keymaster::km_id_t keyid;
3147 if (!mOperationMap.getOperation(token, &handle, &keyid, &purpose, &dev,
3148 &characteristics)) {
Chad Brubaker0cf34a22015-04-23 11:06:16 -07003149 return KM_ERROR_INVALID_OPERATION_HANDLE;
3150 }
Shawn Willdenb2ffa422015-06-17 12:18:55 -06003151 int32_t result = getAuthToken(characteristics, handle, purpose, &authToken);
Chad Brubaker0cf34a22015-04-23 11:06:16 -07003152 if (result != ::NO_ERROR) {
3153 return result;
3154 }
3155 if (authToken) {
3156 mOperationMap.setOperationAuthToken(token, authToken);
3157 }
3158 }
3159 addAuthToParams(params, authToken);
3160 return ::NO_ERROR;
3161 }
3162
Chad Brubaker3a7d9e62015-06-04 15:01:46 -07003163 /**
3164 * Translate a result value to a legacy return value. All keystore errors are
3165 * preserved and keymaster errors become SYSTEM_ERRORs
3166 */
3167 inline int32_t translateResultToLegacyResult(int32_t result) {
3168 if (result > 0) {
3169 return result;
3170 }
3171 return ::SYSTEM_ERROR;
3172 }
3173
Chad Brubaker3a7d9e62015-06-04 15:01:46 -07003174 keymaster_key_param_t* getKeyAlgorithm(keymaster_key_characteristics_t* characteristics) {
3175 for (size_t i = 0; i < characteristics->hw_enforced.length; i++) {
3176 if (characteristics->hw_enforced.params[i].tag == KM_TAG_ALGORITHM) {
3177 return &characteristics->hw_enforced.params[i];
3178 }
3179 }
3180 for (size_t i = 0; i < characteristics->sw_enforced.length; i++) {
3181 if (characteristics->sw_enforced.params[i].tag == KM_TAG_ALGORITHM) {
3182 return &characteristics->sw_enforced.params[i];
3183 }
3184 }
3185 return NULL;
3186 }
3187
3188 void addLegacyBeginParams(const String16& name, std::vector<keymaster_key_param_t>& params) {
3189 // All legacy keys are DIGEST_NONE/PAD_NONE.
3190 params.push_back(keymaster_param_enum(KM_TAG_DIGEST, KM_DIGEST_NONE));
3191 params.push_back(keymaster_param_enum(KM_TAG_PADDING, KM_PAD_NONE));
3192
3193 // Look up the algorithm of the key.
3194 KeyCharacteristics characteristics;
3195 int32_t rc = getKeyCharacteristics(name, NULL, NULL, &characteristics);
3196 if (rc != ::NO_ERROR) {
3197 ALOGE("Failed to get key characteristics");
3198 return;
3199 }
3200 keymaster_key_param_t* algorithm = getKeyAlgorithm(&characteristics.characteristics);
3201 if (!algorithm) {
3202 ALOGE("getKeyCharacteristics did not include KM_TAG_ALGORITHM");
3203 return;
3204 }
3205 params.push_back(*algorithm);
3206 }
3207
3208 int32_t doLegacySignVerify(const String16& name, const uint8_t* data, size_t length,
3209 uint8_t** out, size_t* outLength, const uint8_t* signature,
3210 size_t signatureLength, keymaster_purpose_t purpose) {
3211
Chad Brubaker3a7d9e62015-06-04 15:01:46 -07003212 std::basic_stringstream<uint8_t> outBuffer;
3213 OperationResult result;
3214 KeymasterArguments inArgs;
3215 addLegacyBeginParams(name, inArgs.params);
3216 sp<IBinder> appToken(new BBinder);
3217 sp<IBinder> token;
3218
3219 begin(appToken, name, purpose, true, inArgs, NULL, 0, &result);
3220 if (result.resultCode != ResponseCode::NO_ERROR) {
Chad Brubakerdf705172015-06-17 20:17:51 -07003221 if (result.resultCode == ::KEY_NOT_FOUND) {
3222 ALOGW("Key not found");
3223 } else {
3224 ALOGW("Error in begin: %d", result.resultCode);
3225 }
Chad Brubaker3a7d9e62015-06-04 15:01:46 -07003226 return translateResultToLegacyResult(result.resultCode);
3227 }
3228 inArgs.params.clear();
3229 token = result.token;
3230 size_t consumed = 0;
3231 size_t lastConsumed = 0;
3232 do {
3233 update(token, inArgs, data + consumed, length - consumed, &result);
3234 if (result.resultCode != ResponseCode::NO_ERROR) {
3235 ALOGW("Error in update: %d", result.resultCode);
3236 return translateResultToLegacyResult(result.resultCode);
3237 }
3238 if (out) {
3239 outBuffer.write(result.data.get(), result.dataLength);
3240 }
3241 lastConsumed = result.inputConsumed;
3242 consumed += lastConsumed;
3243 } while (consumed < length && lastConsumed > 0);
3244
3245 if (consumed != length) {
3246 ALOGW("Not all data consumed. Consumed %zu of %zu", consumed, length);
3247 return ::SYSTEM_ERROR;
3248 }
3249
3250 finish(token, inArgs, signature, signatureLength, NULL, 0, &result);
3251 if (result.resultCode != ResponseCode::NO_ERROR) {
3252 ALOGW("Error in finish: %d", result.resultCode);
3253 return translateResultToLegacyResult(result.resultCode);
3254 }
3255 if (out) {
3256 outBuffer.write(result.data.get(), result.dataLength);
3257 }
3258
3259 if (out) {
3260 auto buf = outBuffer.str();
3261 *out = new uint8_t[buf.size()];
3262 memcpy(*out, buf.c_str(), buf.size());
3263 *outLength = buf.size();
3264 }
3265
3266 return ::NO_ERROR;
3267 }
3268
Kenny Root07438c82012-11-02 15:41:02 -07003269 ::KeyStore* mKeyStore;
Chad Brubaker40a1a9b2015-02-20 14:08:13 -08003270 OperationMap mOperationMap;
Chad Brubakerd80c7b42015-03-31 11:04:28 -07003271 keymaster::AuthTokenTable mAuthTokenTable;
Shawn Willden9221bff2015-06-18 18:23:54 -06003272 KeystoreKeymasterEnforcement enforcement_policy;
Kenny Root07438c82012-11-02 15:41:02 -07003273};
3274
3275}; // namespace android
Kenny Roota91203b2012-02-15 15:00:46 -08003276
3277int main(int argc, char* argv[]) {
Kenny Roota91203b2012-02-15 15:00:46 -08003278 if (argc < 2) {
3279 ALOGE("A directory must be specified!");
3280 return 1;
3281 }
3282 if (chdir(argv[1]) == -1) {
3283 ALOGE("chdir: %s: %s", argv[1], strerror(errno));
3284 return 1;
3285 }
3286
3287 Entropy entropy;
3288 if (!entropy.open()) {
3289 return 1;
3290 }
Kenny Root70e3a862012-02-15 17:20:23 -08003291
Chad Brubakerbd07a232015-06-01 10:44:27 -07003292 keymaster1_device_t* dev;
Kenny Root70e3a862012-02-15 17:20:23 -08003293 if (keymaster_device_initialize(&dev)) {
3294 ALOGE("keystore keymaster could not be initialized; exiting");
3295 return 1;
3296 }
3297
Chad Brubaker67d2a502015-03-11 17:21:18 +00003298 keymaster1_device_t* fallback;
Chad Brubakerfc18edc2015-01-12 15:17:18 -08003299 if (fallback_keymaster_device_initialize(&fallback)) {
3300 ALOGE("software keymaster could not be initialized; exiting");
3301 return 1;
3302 }
3303
Riley Spahneaabae92014-06-30 12:39:52 -07003304 ks_is_selinux_enabled = is_selinux_enabled();
3305 if (ks_is_selinux_enabled) {
3306 union selinux_callback cb;
William Robertse46b8552015-10-02 08:19:52 -07003307 cb.func_audit = audit_callback;
3308 selinux_set_callback(SELINUX_CB_AUDIT, cb);
Riley Spahneaabae92014-06-30 12:39:52 -07003309 cb.func_log = selinux_log_callback;
3310 selinux_set_callback(SELINUX_CB_LOG, cb);
3311 if (getcon(&tctx) != 0) {
3312 ALOGE("SELinux: Could not acquire target context. Aborting keystore.\n");
3313 return -1;
3314 }
3315 } else {
3316 ALOGI("SELinux: Keystore SELinux is disabled.\n");
3317 }
3318
Chad Brubakerbd07a232015-06-01 10:44:27 -07003319 KeyStore keyStore(&entropy, dev, fallback);
Kenny Root655b9582013-04-04 08:37:42 -07003320 keyStore.initialize();
Kenny Root07438c82012-11-02 15:41:02 -07003321 android::sp<android::IServiceManager> sm = android::defaultServiceManager();
3322 android::sp<android::KeyStoreProxy> proxy = new android::KeyStoreProxy(&keyStore);
3323 android::status_t ret = sm->addService(android::String16("android.security.keystore"), proxy);
3324 if (ret != android::OK) {
3325 ALOGE("Couldn't register binder service!");
3326 return -1;
Kenny Roota91203b2012-02-15 15:00:46 -08003327 }
Kenny Root07438c82012-11-02 15:41:02 -07003328
3329 /*
3330 * We're the only thread in existence, so we're just going to process
3331 * Binder transaction as a single-threaded program.
3332 */
3333 android::IPCThreadState::self()->joinThreadPool();
Kenny Root70e3a862012-02-15 17:20:23 -08003334
3335 keymaster_device_release(dev);
Kenny Roota91203b2012-02-15 15:00:46 -08003336 return 1;
3337}