blob: 77b30392ded9c0628a11b27b5efc9766414c5ee9 [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();
Chad Brubaker410ba592015-09-09 20:34:09 -0700945 return copyMasterKeyFile(src);
946 }
947
948 ResponseCode copyMasterKeyFile(UserState* src) {
949 /* Copy the master key file to the new user.
950 * Unfortunately we don't have the src user's password so we cannot
951 * generate a new file with a new salt.
952 */
953 int in = TEMP_FAILURE_RETRY(open(src->getMasterKeyFileName(), O_RDONLY));
954 if (in < 0) {
955 return ::SYSTEM_ERROR;
956 }
957 blob rawBlob;
958 size_t length = readFully(in, (uint8_t*) &rawBlob, sizeof(rawBlob));
959 if (close(in) != 0) {
960 return ::SYSTEM_ERROR;
961 }
962 int out = TEMP_FAILURE_RETRY(open(mMasterKeyFile,
963 O_WRONLY | O_TRUNC | O_CREAT, S_IRUSR | S_IWUSR));
964 if (out < 0) {
965 return ::SYSTEM_ERROR;
966 }
967 size_t outLength = writeFully(out, (uint8_t*) &rawBlob, length);
968 if (close(out) != 0) {
969 return ::SYSTEM_ERROR;
970 }
971 if (outLength != length) {
972 ALOGW("blob not fully written %zu != %zu", outLength, length);
973 unlink(mMasterKeyFile);
974 return ::SYSTEM_ERROR;
975 }
976
Robin Lee4e865752014-08-19 17:37:55 +0100977 return ::NO_ERROR;
978 }
979
Kenny Root655b9582013-04-04 08:37:42 -0700980 ResponseCode writeMasterKey(const android::String8& pw, Entropy* entropy) {
Kenny Roota91203b2012-02-15 15:00:46 -0800981 uint8_t passwordKey[MASTER_KEY_SIZE_BYTES];
982 generateKeyFromPassword(passwordKey, MASTER_KEY_SIZE_BYTES, pw, mSalt);
983 AES_KEY passwordAesKey;
984 AES_set_encrypt_key(passwordKey, MASTER_KEY_SIZE_BITS, &passwordAesKey);
Kenny Root822c3a92012-03-23 16:34:39 -0700985 Blob masterKeyBlob(mMasterKey, sizeof(mMasterKey), mSalt, sizeof(mSalt), TYPE_MASTER_KEY);
Kenny Rootf9119d62013-04-03 09:22:15 -0700986 return masterKeyBlob.writeBlob(mMasterKeyFile, &passwordAesKey, STATE_NO_ERROR, entropy);
Kenny Roota91203b2012-02-15 15:00:46 -0800987 }
988
Kenny Root655b9582013-04-04 08:37:42 -0700989 ResponseCode readMasterKey(const android::String8& pw, Entropy* entropy) {
990 int in = TEMP_FAILURE_RETRY(open(mMasterKeyFile, O_RDONLY));
Kenny Root150ca932012-11-14 14:29:02 -0800991 if (in < 0) {
Kenny Roota91203b2012-02-15 15:00:46 -0800992 return SYSTEM_ERROR;
993 }
994
995 // we read the raw blob to just to get the salt to generate
996 // the AES key, then we create the Blob to use with decryptBlob
997 blob rawBlob;
998 size_t length = readFully(in, (uint8_t*) &rawBlob, sizeof(rawBlob));
999 if (close(in) != 0) {
1000 return SYSTEM_ERROR;
1001 }
1002 // find salt at EOF if present, otherwise we have an old file
1003 uint8_t* salt;
1004 if (length > SALT_SIZE && rawBlob.info == SALT_SIZE) {
1005 salt = (uint8_t*) &rawBlob + length - SALT_SIZE;
1006 } else {
1007 salt = NULL;
1008 }
1009 uint8_t passwordKey[MASTER_KEY_SIZE_BYTES];
1010 generateKeyFromPassword(passwordKey, MASTER_KEY_SIZE_BYTES, pw, salt);
1011 AES_KEY passwordAesKey;
1012 AES_set_decrypt_key(passwordKey, MASTER_KEY_SIZE_BITS, &passwordAesKey);
1013 Blob masterKeyBlob(rawBlob);
Kenny Rootf9119d62013-04-03 09:22:15 -07001014 ResponseCode response = masterKeyBlob.readBlob(mMasterKeyFile, &passwordAesKey,
1015 STATE_NO_ERROR);
Kenny Roota91203b2012-02-15 15:00:46 -08001016 if (response == SYSTEM_ERROR) {
Kenny Rootf9119d62013-04-03 09:22:15 -07001017 return response;
Kenny Roota91203b2012-02-15 15:00:46 -08001018 }
1019 if (response == NO_ERROR && masterKeyBlob.getLength() == MASTER_KEY_SIZE_BYTES) {
1020 // if salt was missing, generate one and write a new master key file with the salt.
1021 if (salt == NULL) {
Kenny Root655b9582013-04-04 08:37:42 -07001022 if (!generateSalt(entropy)) {
Kenny Roota91203b2012-02-15 15:00:46 -08001023 return SYSTEM_ERROR;
1024 }
Kenny Root655b9582013-04-04 08:37:42 -07001025 response = writeMasterKey(pw, entropy);
Kenny Roota91203b2012-02-15 15:00:46 -08001026 }
1027 if (response == NO_ERROR) {
1028 memcpy(mMasterKey, masterKeyBlob.getValue(), MASTER_KEY_SIZE_BYTES);
1029 setupMasterKeys();
1030 }
1031 return response;
1032 }
1033 if (mRetry <= 0) {
1034 reset();
1035 return UNINITIALIZED;
1036 }
1037 --mRetry;
1038 switch (mRetry) {
1039 case 0: return WRONG_PASSWORD_0;
1040 case 1: return WRONG_PASSWORD_1;
1041 case 2: return WRONG_PASSWORD_2;
1042 case 3: return WRONG_PASSWORD_3;
1043 default: return WRONG_PASSWORD_3;
1044 }
1045 }
1046
Kenny Root655b9582013-04-04 08:37:42 -07001047 AES_KEY* getEncryptionKey() {
1048 return &mMasterKeyEncryption;
1049 }
1050
1051 AES_KEY* getDecryptionKey() {
1052 return &mMasterKeyDecryption;
1053 }
1054
Kenny Roota91203b2012-02-15 15:00:46 -08001055 bool reset() {
Kenny Root655b9582013-04-04 08:37:42 -07001056 DIR* dir = opendir(getUserDirName());
Kenny Roota91203b2012-02-15 15:00:46 -08001057 if (!dir) {
Chad Brubaker96d6d782015-05-07 10:19:40 -07001058 // If the directory doesn't exist then nothing to do.
1059 if (errno == ENOENT) {
1060 return true;
1061 }
Kenny Root655b9582013-04-04 08:37:42 -07001062 ALOGW("couldn't open user directory: %s", strerror(errno));
Kenny Roota91203b2012-02-15 15:00:46 -08001063 return false;
1064 }
Kenny Root655b9582013-04-04 08:37:42 -07001065
1066 struct dirent* file;
Kenny Roota91203b2012-02-15 15:00:46 -08001067 while ((file = readdir(dir)) != NULL) {
Chad Brubaker96d6d782015-05-07 10:19:40 -07001068 // skip . and ..
1069 if (!strcmp(".", file->d_name) || !strcmp("..", file->d_name)) {
Kenny Root655b9582013-04-04 08:37:42 -07001070 continue;
1071 }
1072
1073 unlinkat(dirfd(dir), file->d_name, 0);
Kenny Roota91203b2012-02-15 15:00:46 -08001074 }
1075 closedir(dir);
1076 return true;
1077 }
1078
Kenny Root655b9582013-04-04 08:37:42 -07001079private:
1080 static const int MASTER_KEY_SIZE_BYTES = 16;
1081 static const int MASTER_KEY_SIZE_BITS = MASTER_KEY_SIZE_BYTES * 8;
1082
1083 static const int MAX_RETRY = 4;
1084 static const size_t SALT_SIZE = 16;
1085
1086 void generateKeyFromPassword(uint8_t* key, ssize_t keySize, const android::String8& pw,
1087 uint8_t* salt) {
1088 size_t saltSize;
1089 if (salt != NULL) {
1090 saltSize = SALT_SIZE;
1091 } else {
1092 // pre-gingerbread used this hardwired salt, readMasterKey will rewrite these when found
1093 salt = (uint8_t*) "keystore";
1094 // sizeof = 9, not strlen = 8
1095 saltSize = sizeof("keystore");
1096 }
1097
1098 PKCS5_PBKDF2_HMAC_SHA1(reinterpret_cast<const char*>(pw.string()), pw.length(), salt,
1099 saltSize, 8192, keySize, key);
1100 }
1101
1102 bool generateSalt(Entropy* entropy) {
1103 return entropy->generate_random_data(mSalt, sizeof(mSalt));
1104 }
1105
1106 bool generateMasterKey(Entropy* entropy) {
1107 if (!entropy->generate_random_data(mMasterKey, sizeof(mMasterKey))) {
1108 return false;
1109 }
1110 if (!generateSalt(entropy)) {
1111 return false;
1112 }
1113 return true;
1114 }
1115
1116 void setupMasterKeys() {
1117 AES_set_encrypt_key(mMasterKey, MASTER_KEY_SIZE_BITS, &mMasterKeyEncryption);
1118 AES_set_decrypt_key(mMasterKey, MASTER_KEY_SIZE_BITS, &mMasterKeyDecryption);
1119 setState(STATE_NO_ERROR);
1120 }
1121
1122 uid_t mUserId;
1123
1124 char* mUserDir;
1125 char* mMasterKeyFile;
1126
1127 State mState;
1128 int8_t mRetry;
1129
1130 uint8_t mMasterKey[MASTER_KEY_SIZE_BYTES];
1131 uint8_t mSalt[SALT_SIZE];
1132
1133 AES_KEY mMasterKeyEncryption;
1134 AES_KEY mMasterKeyDecryption;
1135};
1136
1137typedef struct {
1138 uint32_t uid;
1139 const uint8_t* filename;
1140} grant_t;
1141
1142class KeyStore {
1143public:
Chad Brubaker67d2a502015-03-11 17:21:18 +00001144 KeyStore(Entropy* entropy, keymaster1_device_t* device, keymaster1_device_t* fallback)
Kenny Root655b9582013-04-04 08:37:42 -07001145 : mEntropy(entropy)
1146 , mDevice(device)
Chad Brubakerfc18edc2015-01-12 15:17:18 -08001147 , mFallbackDevice(fallback)
Kenny Root655b9582013-04-04 08:37:42 -07001148 {
1149 memset(&mMetaData, '\0', sizeof(mMetaData));
1150 }
1151
1152 ~KeyStore() {
1153 for (android::Vector<grant_t*>::iterator it(mGrants.begin());
1154 it != mGrants.end(); it++) {
1155 delete *it;
Kenny Root655b9582013-04-04 08:37:42 -07001156 }
haitao fangc35d4eb2013-12-06 11:34:49 +08001157 mGrants.clear();
Kenny Root655b9582013-04-04 08:37:42 -07001158
1159 for (android::Vector<UserState*>::iterator it(mMasterKeys.begin());
1160 it != mMasterKeys.end(); it++) {
1161 delete *it;
Kenny Root655b9582013-04-04 08:37:42 -07001162 }
haitao fangc35d4eb2013-12-06 11:34:49 +08001163 mMasterKeys.clear();
Kenny Root655b9582013-04-04 08:37:42 -07001164 }
1165
Chad Brubaker67d2a502015-03-11 17:21:18 +00001166 /**
1167 * Depending on the hardware keymaster version is this may return a
1168 * keymaster0_device_t* cast to a keymaster1_device_t*. All methods from
1169 * keymaster0 are safe to call, calls to keymaster1_device_t methods should
1170 * be guarded by a check on the device's version.
1171 */
1172 keymaster1_device_t *getDevice() const {
Kenny Root655b9582013-04-04 08:37:42 -07001173 return mDevice;
1174 }
1175
Chad Brubaker67d2a502015-03-11 17:21:18 +00001176 keymaster1_device_t *getFallbackDevice() const {
Chad Brubakerfc18edc2015-01-12 15:17:18 -08001177 return mFallbackDevice;
1178 }
1179
Chad Brubaker67d2a502015-03-11 17:21:18 +00001180 keymaster1_device_t *getDeviceForBlob(const Blob& blob) const {
Chad Brubakerfc18edc2015-01-12 15:17:18 -08001181 return blob.isFallback() ? mFallbackDevice: mDevice;
1182 }
1183
Kenny Root655b9582013-04-04 08:37:42 -07001184 ResponseCode initialize() {
1185 readMetaData();
1186 if (upgradeKeystore()) {
1187 writeMetaData();
1188 }
1189
1190 return ::NO_ERROR;
1191 }
1192
Chad Brubaker72593ee2015-05-12 10:42:00 -07001193 State getState(uid_t userId) {
1194 return getUserState(userId)->getState();
Kenny Root655b9582013-04-04 08:37:42 -07001195 }
1196
Chad Brubaker72593ee2015-05-12 10:42:00 -07001197 ResponseCode initializeUser(const android::String8& pw, uid_t userId) {
1198 UserState* userState = getUserState(userId);
Kenny Root655b9582013-04-04 08:37:42 -07001199 return userState->initialize(pw, mEntropy);
1200 }
1201
Chad Brubaker72593ee2015-05-12 10:42:00 -07001202 ResponseCode copyMasterKey(uid_t srcUser, uid_t dstUser) {
1203 UserState *userState = getUserState(dstUser);
1204 UserState *initState = getUserState(srcUser);
Robin Lee4e865752014-08-19 17:37:55 +01001205 return userState->copyMasterKey(initState);
1206 }
1207
Chad Brubaker72593ee2015-05-12 10:42:00 -07001208 ResponseCode writeMasterKey(const android::String8& pw, uid_t userId) {
1209 UserState* userState = getUserState(userId);
Kenny Root655b9582013-04-04 08:37:42 -07001210 return userState->writeMasterKey(pw, mEntropy);
1211 }
1212
Chad Brubaker72593ee2015-05-12 10:42:00 -07001213 ResponseCode readMasterKey(const android::String8& pw, uid_t userId) {
1214 UserState* userState = getUserState(userId);
Kenny Root655b9582013-04-04 08:37:42 -07001215 return userState->readMasterKey(pw, mEntropy);
1216 }
1217
1218 android::String8 getKeyName(const android::String8& keyName) {
Douglas Leunga77e8092013-06-13 16:34:43 -07001219 char encoded[encode_key_length(keyName) + 1]; // add 1 for null char
Kenny Root655b9582013-04-04 08:37:42 -07001220 encode_key(encoded, keyName);
1221 return android::String8(encoded);
1222 }
1223
1224 android::String8 getKeyNameForUid(const android::String8& keyName, uid_t uid) {
Douglas Leunga77e8092013-06-13 16:34:43 -07001225 char encoded[encode_key_length(keyName) + 1]; // add 1 for null char
Kenny Root655b9582013-04-04 08:37:42 -07001226 encode_key(encoded, keyName);
1227 return android::String8::format("%u_%s", uid, encoded);
1228 }
1229
1230 android::String8 getKeyNameForUidWithDir(const android::String8& keyName, uid_t uid) {
Douglas Leunga77e8092013-06-13 16:34:43 -07001231 char encoded[encode_key_length(keyName) + 1]; // add 1 for null char
Kenny Root655b9582013-04-04 08:37:42 -07001232 encode_key(encoded, keyName);
Chad Brubaker72593ee2015-05-12 10:42:00 -07001233 return android::String8::format("%s/%u_%s", getUserStateByUid(uid)->getUserDirName(), uid,
Kenny Root655b9582013-04-04 08:37:42 -07001234 encoded);
1235 }
1236
Chad Brubaker96d6d782015-05-07 10:19:40 -07001237 /*
1238 * Delete entries owned by userId. If keepUnencryptedEntries is true
1239 * then only encrypted entries will be removed, otherwise all entries will
1240 * be removed.
1241 */
1242 void resetUser(uid_t userId, bool keepUnenryptedEntries) {
Robin Lee4b84fdc2014-09-24 11:56:57 +01001243 android::String8 prefix("");
1244 android::Vector<android::String16> aliases;
Chad Brubaker72593ee2015-05-12 10:42:00 -07001245 UserState* userState = getUserState(userId);
Chad Brubakere6c3bfa2015-05-12 15:18:26 -07001246 if (list(prefix, &aliases, userId) != ::NO_ERROR) {
Chad Brubaker96d6d782015-05-07 10:19:40 -07001247 return;
1248 }
Robin Lee4b84fdc2014-09-24 11:56:57 +01001249 for (uint32_t i = 0; i < aliases.size(); i++) {
1250 android::String8 filename(aliases[i]);
1251 filename = android::String8::format("%s/%s", userState->getUserDirName(),
Chad Brubaker96d6d782015-05-07 10:19:40 -07001252 getKeyName(filename).string());
1253 bool shouldDelete = true;
1254 if (keepUnenryptedEntries) {
1255 Blob blob;
Chad Brubaker72593ee2015-05-12 10:42:00 -07001256 ResponseCode rc = get(filename, &blob, ::TYPE_ANY, userId);
Robin Lee4b84fdc2014-09-24 11:56:57 +01001257
Chad Brubaker96d6d782015-05-07 10:19:40 -07001258 /* get can fail if the blob is encrypted and the state is
1259 * not unlocked, only skip deleting blobs that were loaded and
1260 * who are not encrypted. If there are blobs we fail to read for
1261 * other reasons err on the safe side and delete them since we
1262 * can't tell if they're encrypted.
1263 */
1264 shouldDelete = !(rc == ::NO_ERROR && !blob.isEncrypted());
1265 }
1266 if (shouldDelete) {
Chad Brubaker72593ee2015-05-12 10:42:00 -07001267 del(filename, ::TYPE_ANY, userId);
Chad Brubaker96d6d782015-05-07 10:19:40 -07001268 }
1269 }
1270 if (!userState->deleteMasterKey()) {
1271 ALOGE("Failed to delete user %d's master key", userId);
1272 }
1273 if (!keepUnenryptedEntries) {
1274 if(!userState->reset()) {
1275 ALOGE("Failed to remove user %d's directory", userId);
1276 }
1277 }
Kenny Root655b9582013-04-04 08:37:42 -07001278 }
1279
Chad Brubaker72593ee2015-05-12 10:42:00 -07001280 bool isEmpty(uid_t userId) const {
1281 const UserState* userState = getUserState(userId);
Chad Brubaker96d6d782015-05-07 10:19:40 -07001282 if (userState == NULL) {
Kenny Root655b9582013-04-04 08:37:42 -07001283 return true;
1284 }
1285
1286 DIR* dir = opendir(userState->getUserDirName());
Kenny Roota91203b2012-02-15 15:00:46 -08001287 if (!dir) {
1288 return true;
1289 }
Kenny Root31e27462014-09-10 11:28:03 -07001290
Kenny Roota91203b2012-02-15 15:00:46 -08001291 bool result = true;
Kenny Root31e27462014-09-10 11:28:03 -07001292 struct dirent* file;
Kenny Roota91203b2012-02-15 15:00:46 -08001293 while ((file = readdir(dir)) != NULL) {
Kenny Root655b9582013-04-04 08:37:42 -07001294 // We only care about files.
1295 if (file->d_type != DT_REG) {
1296 continue;
1297 }
1298
1299 // Skip anything that starts with a "."
1300 if (file->d_name[0] == '.') {
1301 continue;
1302 }
1303
Kenny Root31e27462014-09-10 11:28:03 -07001304 result = false;
1305 break;
Kenny Roota91203b2012-02-15 15:00:46 -08001306 }
1307 closedir(dir);
1308 return result;
1309 }
1310
Chad Brubaker72593ee2015-05-12 10:42:00 -07001311 void lock(uid_t userId) {
1312 UserState* userState = getUserState(userId);
Kenny Root655b9582013-04-04 08:37:42 -07001313 userState->zeroizeMasterKeysInMemory();
1314 userState->setState(STATE_LOCKED);
Kenny Roota91203b2012-02-15 15:00:46 -08001315 }
1316
Chad Brubaker72593ee2015-05-12 10:42:00 -07001317 ResponseCode get(const char* filename, Blob* keyBlob, const BlobType type, uid_t userId) {
1318 UserState* userState = getUserState(userId);
Kenny Rootf9119d62013-04-03 09:22:15 -07001319 ResponseCode rc = keyBlob->readBlob(filename, userState->getDecryptionKey(),
1320 userState->getState());
Kenny Root822c3a92012-03-23 16:34:39 -07001321 if (rc != NO_ERROR) {
1322 return rc;
1323 }
1324
1325 const uint8_t version = keyBlob->getVersion();
Kenny Root07438c82012-11-02 15:41:02 -07001326 if (version < CURRENT_BLOB_VERSION) {
Kenny Rootcfeae072013-04-04 08:39:57 -07001327 /* If we upgrade the key, we need to write it to disk again. Then
1328 * it must be read it again since the blob is encrypted each time
1329 * it's written.
1330 */
Chad Brubaker72593ee2015-05-12 10:42:00 -07001331 if (upgradeBlob(filename, keyBlob, version, type, userId)) {
1332 if ((rc = this->put(filename, keyBlob, userId)) != NO_ERROR
Kenny Rootf9119d62013-04-03 09:22:15 -07001333 || (rc = keyBlob->readBlob(filename, userState->getDecryptionKey(),
1334 userState->getState())) != NO_ERROR) {
Kenny Rootcfeae072013-04-04 08:39:57 -07001335 return rc;
1336 }
1337 }
Kenny Root822c3a92012-03-23 16:34:39 -07001338 }
1339
Kenny Root17208e02013-09-04 13:56:03 -07001340 /*
1341 * This will upgrade software-backed keys to hardware-backed keys when
1342 * the HAL for the device supports the newer key types.
1343 */
1344 if (rc == NO_ERROR && type == TYPE_KEY_PAIR
1345 && mDevice->common.module->module_api_version >= KEYMASTER_MODULE_API_VERSION_0_2
1346 && keyBlob->isFallback()) {
1347 ResponseCode imported = importKey(keyBlob->getValue(), keyBlob->getLength(), filename,
Chad Brubaker72593ee2015-05-12 10:42:00 -07001348 userId, keyBlob->isEncrypted() ? KEYSTORE_FLAG_ENCRYPTED : KEYSTORE_FLAG_NONE);
Kenny Root17208e02013-09-04 13:56:03 -07001349
1350 // The HAL allowed the import, reget the key to have the "fresh"
1351 // version.
1352 if (imported == NO_ERROR) {
Chad Brubaker72593ee2015-05-12 10:42:00 -07001353 rc = get(filename, keyBlob, TYPE_KEY_PAIR, userId);
Kenny Root17208e02013-09-04 13:56:03 -07001354 }
1355 }
1356
Chad Brubaker3a7d9e62015-06-04 15:01:46 -07001357 // Keymaster 0.3 keys are valid keymaster 1.0 keys, so silently upgrade.
1358 if (keyBlob->getType() == TYPE_KEY_PAIR) {
Chad Brubaker3cc40122015-06-04 13:49:44 -07001359 keyBlob->setType(TYPE_KEYMASTER_10);
Chad Brubaker3a7d9e62015-06-04 15:01:46 -07001360 rc = this->put(filename, keyBlob, userId);
Chad Brubaker3cc40122015-06-04 13:49:44 -07001361 }
1362
Kenny Rootd53bc922013-03-21 14:10:15 -07001363 if (type != TYPE_ANY && keyBlob->getType() != type) {
Kenny Root822c3a92012-03-23 16:34:39 -07001364 ALOGW("key found but type doesn't match: %d vs %d", keyBlob->getType(), type);
1365 return KEY_NOT_FOUND;
1366 }
1367
1368 return rc;
Kenny Roota91203b2012-02-15 15:00:46 -08001369 }
1370
Chad Brubaker72593ee2015-05-12 10:42:00 -07001371 ResponseCode put(const char* filename, Blob* keyBlob, uid_t userId) {
1372 UserState* userState = getUserState(userId);
Kenny Rootf9119d62013-04-03 09:22:15 -07001373 return keyBlob->writeBlob(filename, userState->getEncryptionKey(), userState->getState(),
1374 mEntropy);
Kenny Roota91203b2012-02-15 15:00:46 -08001375 }
1376
Chad Brubaker72593ee2015-05-12 10:42:00 -07001377 ResponseCode del(const char *filename, const BlobType type, uid_t userId) {
Robin Lee4b84fdc2014-09-24 11:56:57 +01001378 Blob keyBlob;
Chad Brubaker72593ee2015-05-12 10:42:00 -07001379 ResponseCode rc = get(filename, &keyBlob, type, userId);
Chad Brubakera9a17ee2015-07-17 13:43:24 -07001380 if (rc == ::VALUE_CORRUPTED) {
1381 // The file is corrupt, the best we can do is rm it.
1382 return (unlink(filename) && errno != ENOENT) ? ::SYSTEM_ERROR : ::NO_ERROR;
1383 }
Robin Lee4b84fdc2014-09-24 11:56:57 +01001384 if (rc != ::NO_ERROR) {
1385 return rc;
1386 }
1387
1388 if (keyBlob.getType() == ::TYPE_KEY_PAIR) {
Shawn Willden55268b52015-07-28 11:06:00 -06001389 // A device doesn't have to implement delete_key.
1390 if (mDevice->delete_key != NULL && !keyBlob.isFallback()) {
1391 keymaster_key_blob_t blob = {keyBlob.getValue(),
1392 static_cast<size_t>(keyBlob.getLength())};
1393 if (mDevice->delete_key(mDevice, &blob)) {
Robin Lee4b84fdc2014-09-24 11:56:57 +01001394 rc = ::SYSTEM_ERROR;
1395 }
1396 }
1397 }
Chad Brubaker17d68b92015-02-05 22:04:16 -08001398 if (keyBlob.getType() == ::TYPE_KEYMASTER_10) {
1399 keymaster1_device_t* dev = getDeviceForBlob(keyBlob);
1400 if (dev->delete_key) {
1401 keymaster_key_blob_t blob;
1402 blob.key_material = keyBlob.getValue();
1403 blob.key_material_size = keyBlob.getLength();
1404 dev->delete_key(dev, &blob);
1405 }
1406 }
Robin Lee4b84fdc2014-09-24 11:56:57 +01001407 if (rc != ::NO_ERROR) {
1408 return rc;
1409 }
1410
1411 return (unlink(filename) && errno != ENOENT) ? ::SYSTEM_ERROR : ::NO_ERROR;
1412 }
1413
Chad Brubakere6c3bfa2015-05-12 15:18:26 -07001414 ResponseCode list(const android::String8& prefix, android::Vector<android::String16> *matches,
Chad Brubaker72593ee2015-05-12 10:42:00 -07001415 uid_t userId) {
Robin Lee4b84fdc2014-09-24 11:56:57 +01001416
Chad Brubaker72593ee2015-05-12 10:42:00 -07001417 UserState* userState = getUserState(userId);
Robin Lee4b84fdc2014-09-24 11:56:57 +01001418 size_t n = prefix.length();
1419
1420 DIR* dir = opendir(userState->getUserDirName());
1421 if (!dir) {
1422 ALOGW("can't open directory for user: %s", strerror(errno));
1423 return ::SYSTEM_ERROR;
1424 }
1425
1426 struct dirent* file;
1427 while ((file = readdir(dir)) != NULL) {
1428 // We only care about files.
1429 if (file->d_type != DT_REG) {
1430 continue;
1431 }
1432
1433 // Skip anything that starts with a "."
1434 if (file->d_name[0] == '.') {
1435 continue;
1436 }
1437
1438 if (!strncmp(prefix.string(), file->d_name, n)) {
1439 const char* p = &file->d_name[n];
1440 size_t plen = strlen(p);
1441
1442 size_t extra = decode_key_length(p, plen);
1443 char *match = (char*) malloc(extra + 1);
1444 if (match != NULL) {
1445 decode_key(match, p, plen);
1446 matches->push(android::String16(match, extra));
1447 free(match);
1448 } else {
1449 ALOGW("could not allocate match of size %zd", extra);
1450 }
1451 }
1452 }
1453 closedir(dir);
1454 return ::NO_ERROR;
1455 }
1456
Kenny Root07438c82012-11-02 15:41:02 -07001457 void addGrant(const char* filename, uid_t granteeUid) {
Kenny Root655b9582013-04-04 08:37:42 -07001458 const grant_t* existing = getGrant(filename, granteeUid);
1459 if (existing == NULL) {
1460 grant_t* grant = new grant_t;
Kenny Root07438c82012-11-02 15:41:02 -07001461 grant->uid = granteeUid;
Brian Carlstroma8c703d2012-07-17 14:43:46 -07001462 grant->filename = reinterpret_cast<const uint8_t*>(strdup(filename));
Kenny Root655b9582013-04-04 08:37:42 -07001463 mGrants.add(grant);
Kenny Root70e3a862012-02-15 17:20:23 -08001464 }
1465 }
1466
Kenny Root07438c82012-11-02 15:41:02 -07001467 bool removeGrant(const char* filename, uid_t granteeUid) {
Kenny Root655b9582013-04-04 08:37:42 -07001468 for (android::Vector<grant_t*>::iterator it(mGrants.begin());
1469 it != mGrants.end(); it++) {
1470 grant_t* grant = *it;
1471 if (grant->uid == granteeUid
1472 && !strcmp(reinterpret_cast<const char*>(grant->filename), filename)) {
1473 mGrants.erase(it);
1474 return true;
1475 }
Kenny Root70e3a862012-02-15 17:20:23 -08001476 }
Kenny Root70e3a862012-02-15 17:20:23 -08001477 return false;
1478 }
1479
Brian Carlstroma8c703d2012-07-17 14:43:46 -07001480 bool hasGrant(const char* filename, const uid_t uid) const {
1481 return getGrant(filename, uid) != NULL;
Kenny Root70e3a862012-02-15 17:20:23 -08001482 }
1483
Chad Brubaker72593ee2015-05-12 10:42:00 -07001484 ResponseCode importKey(const uint8_t* key, size_t keyLen, const char* filename, uid_t userId,
Kenny Rootf9119d62013-04-03 09:22:15 -07001485 int32_t flags) {
Shawn Willden55268b52015-07-28 11:06:00 -06001486 Unique_PKCS8_PRIV_KEY_INFO pkcs8(d2i_PKCS8_PRIV_KEY_INFO(NULL, &key, keyLen));
1487 if (!pkcs8.get()) {
1488 return ::SYSTEM_ERROR;
1489 }
1490 Unique_EVP_PKEY pkey(EVP_PKCS82PKEY(pkcs8.get()));
1491 if (!pkey.get()) {
1492 return ::SYSTEM_ERROR;
1493 }
1494 int type = EVP_PKEY_type(pkey->type);
1495 android::KeymasterArguments params;
1496 add_legacy_key_authorizations(type, &params.params);
1497 switch (type) {
1498 case EVP_PKEY_RSA:
1499 params.params.push_back(keymaster_param_enum(KM_TAG_ALGORITHM, KM_ALGORITHM_RSA));
1500 break;
1501 case EVP_PKEY_EC:
1502 params.params.push_back(keymaster_param_enum(KM_TAG_ALGORITHM,
1503 KM_ALGORITHM_EC));
1504 break;
1505 default:
1506 ALOGW("Unsupported key type %d", type);
1507 return ::SYSTEM_ERROR;
Kenny Root822c3a92012-03-23 16:34:39 -07001508 }
1509
Shawn Willden55268b52015-07-28 11:06:00 -06001510 std::vector<keymaster_key_param_t> opParams(params.params);
1511 const keymaster_key_param_set_t inParams = {opParams.data(), opParams.size()};
1512 keymaster_blob_t input = {key, keyLen};
1513 keymaster_key_blob_t blob = {nullptr, 0};
Kenny Root17208e02013-09-04 13:56:03 -07001514 bool isFallback = false;
Shawn Willden55268b52015-07-28 11:06:00 -06001515 keymaster_error_t error = mDevice->import_key(mDevice, &inParams, KM_KEY_FORMAT_PKCS8,
1516 &input, &blob, NULL /* characteristics */);
1517 if (error != KM_ERROR_OK){
1518 ALOGE("Keymaster error %d importing key pair, falling back", error);
1519
Kenny Roota39da5a2014-09-25 13:07:24 -07001520 /*
Shawn Willden55268b52015-07-28 11:06:00 -06001521 * There should be no way to get here. Fallback shouldn't ever really happen
1522 * because the main device may be many (SW, KM0/SW hybrid, KM1/SW hybrid), but it must
1523 * provide full support of the API. In any case, we'll do the fallback just for
1524 * consistency... and I suppose to cover for broken HW implementations.
Kenny Roota39da5a2014-09-25 13:07:24 -07001525 */
Shawn Willden55268b52015-07-28 11:06:00 -06001526 error = mFallbackDevice->import_key(mFallbackDevice, &inParams, KM_KEY_FORMAT_PKCS8,
1527 &input, &blob, NULL /* characteristics */);
Kenny Roota39da5a2014-09-25 13:07:24 -07001528 isFallback = true;
Kenny Root17208e02013-09-04 13:56:03 -07001529
Shawn Willden55268b52015-07-28 11:06:00 -06001530 if (error) {
1531 ALOGE("Keymaster error while importing key pair with fallback: %d", error);
Kenny Root17208e02013-09-04 13:56:03 -07001532 return SYSTEM_ERROR;
1533 }
Kenny Root822c3a92012-03-23 16:34:39 -07001534 }
1535
Shawn Willden55268b52015-07-28 11:06:00 -06001536 Blob keyBlob(blob.key_material, blob.key_material_size, NULL, 0, TYPE_KEYMASTER_10);
1537 free(const_cast<uint8_t*>(blob.key_material));
Kenny Root822c3a92012-03-23 16:34:39 -07001538
Kenny Rootf9119d62013-04-03 09:22:15 -07001539 keyBlob.setEncrypted(flags & KEYSTORE_FLAG_ENCRYPTED);
Kenny Root17208e02013-09-04 13:56:03 -07001540 keyBlob.setFallback(isFallback);
Kenny Rootf9119d62013-04-03 09:22:15 -07001541
Chad Brubaker72593ee2015-05-12 10:42:00 -07001542 return put(filename, &keyBlob, userId);
Kenny Root822c3a92012-03-23 16:34:39 -07001543 }
1544
Kenny Root1b0e3932013-09-05 13:06:32 -07001545 bool isHardwareBacked(const android::String16& keyType) const {
1546 if (mDevice == NULL) {
1547 ALOGW("can't get keymaster device");
1548 return false;
1549 }
1550
1551 if (sRSAKeyType == keyType) {
1552 return (mDevice->flags & KEYMASTER_SOFTWARE_ONLY) == 0;
1553 } else {
1554 return (mDevice->flags & KEYMASTER_SOFTWARE_ONLY) == 0
1555 && (mDevice->common.module->module_api_version
1556 >= KEYMASTER_MODULE_API_VERSION_0_2);
1557 }
Kenny Root8ddf35a2013-03-29 11:15:50 -07001558 }
1559
Kenny Root655b9582013-04-04 08:37:42 -07001560 ResponseCode getKeyForName(Blob* keyBlob, const android::String8& keyName, const uid_t uid,
1561 const BlobType type) {
Kenny Root86b16e82013-09-09 11:15:54 -07001562 android::String8 filepath8(getKeyNameForUidWithDir(keyName, uid));
Chad Brubaker72593ee2015-05-12 10:42:00 -07001563 uid_t userId = get_user_id(uid);
Kenny Root655b9582013-04-04 08:37:42 -07001564
Chad Brubaker72593ee2015-05-12 10:42:00 -07001565 ResponseCode responseCode = get(filepath8.string(), keyBlob, type, userId);
Kenny Root655b9582013-04-04 08:37:42 -07001566 if (responseCode == NO_ERROR) {
1567 return responseCode;
1568 }
1569
1570 // If this is one of the legacy UID->UID mappings, use it.
1571 uid_t euid = get_keystore_euid(uid);
1572 if (euid != uid) {
Kenny Root86b16e82013-09-09 11:15:54 -07001573 filepath8 = getKeyNameForUidWithDir(keyName, euid);
Chad Brubaker72593ee2015-05-12 10:42:00 -07001574 responseCode = get(filepath8.string(), keyBlob, type, userId);
Kenny Root655b9582013-04-04 08:37:42 -07001575 if (responseCode == NO_ERROR) {
1576 return responseCode;
1577 }
1578 }
1579
1580 // They might be using a granted key.
Kenny Root86b16e82013-09-09 11:15:54 -07001581 android::String8 filename8 = getKeyName(keyName);
Kenny Root655b9582013-04-04 08:37:42 -07001582 char* end;
Kenny Root86b16e82013-09-09 11:15:54 -07001583 strtoul(filename8.string(), &end, 10);
Kenny Root655b9582013-04-04 08:37:42 -07001584 if (end[0] != '_' || end[1] == 0) {
1585 return KEY_NOT_FOUND;
1586 }
Chad Brubaker72593ee2015-05-12 10:42:00 -07001587 filepath8 = android::String8::format("%s/%s", getUserState(userId)->getUserDirName(),
Kenny Root86b16e82013-09-09 11:15:54 -07001588 filename8.string());
Kenny Root655b9582013-04-04 08:37:42 -07001589 if (!hasGrant(filepath8.string(), uid)) {
1590 return responseCode;
1591 }
1592
1593 // It is a granted key. Try to load it.
Chad Brubaker72593ee2015-05-12 10:42:00 -07001594 return get(filepath8.string(), keyBlob, type, userId);
Kenny Root655b9582013-04-04 08:37:42 -07001595 }
1596
1597 /**
1598 * Returns any existing UserState or creates it if it doesn't exist.
1599 */
Chad Brubaker72593ee2015-05-12 10:42:00 -07001600 UserState* getUserState(uid_t userId) {
Kenny Root655b9582013-04-04 08:37:42 -07001601 for (android::Vector<UserState*>::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 UserState* userState = new UserState(userId);
1610 if (!userState->initialize()) {
1611 /* There's not much we can do if initialization fails. Trying to
1612 * unlock the keystore for that user will fail as well, so any
1613 * subsequent request for this user will just return SYSTEM_ERROR.
1614 */
1615 ALOGE("User initialization failed for %u; subsuquent operations will fail", userId);
1616 }
1617 mMasterKeys.add(userState);
1618 return userState;
1619 }
1620
1621 /**
Chad Brubaker72593ee2015-05-12 10:42:00 -07001622 * Returns any existing UserState or creates it if it doesn't exist.
1623 */
1624 UserState* getUserStateByUid(uid_t uid) {
1625 uid_t userId = get_user_id(uid);
1626 return getUserState(userId);
1627 }
1628
1629 /**
Kenny Root655b9582013-04-04 08:37:42 -07001630 * Returns NULL if the UserState doesn't already exist.
1631 */
Chad Brubaker72593ee2015-05-12 10:42:00 -07001632 const UserState* getUserState(uid_t userId) const {
Kenny Root655b9582013-04-04 08:37:42 -07001633 for (android::Vector<UserState*>::const_iterator it(mMasterKeys.begin());
1634 it != mMasterKeys.end(); it++) {
1635 UserState* state = *it;
1636 if (state->getUserId() == userId) {
1637 return state;
1638 }
1639 }
1640
1641 return NULL;
1642 }
1643
Chad Brubaker72593ee2015-05-12 10:42:00 -07001644 /**
1645 * Returns NULL if the UserState doesn't already exist.
1646 */
1647 const UserState* getUserStateByUid(uid_t uid) const {
1648 uid_t userId = get_user_id(uid);
1649 return getUserState(userId);
1650 }
1651
Kenny Roota91203b2012-02-15 15:00:46 -08001652private:
Kenny Root655b9582013-04-04 08:37:42 -07001653 static const char* sOldMasterKey;
1654 static const char* sMetaDataFile;
Kenny Root1b0e3932013-09-05 13:06:32 -07001655 static const android::String16 sRSAKeyType;
Kenny Roota91203b2012-02-15 15:00:46 -08001656 Entropy* mEntropy;
1657
Chad Brubaker67d2a502015-03-11 17:21:18 +00001658 keymaster1_device_t* mDevice;
1659 keymaster1_device_t* mFallbackDevice;
Kenny Root70e3a862012-02-15 17:20:23 -08001660
Kenny Root655b9582013-04-04 08:37:42 -07001661 android::Vector<UserState*> mMasterKeys;
Kenny Roota91203b2012-02-15 15:00:46 -08001662
Kenny Root655b9582013-04-04 08:37:42 -07001663 android::Vector<grant_t*> mGrants;
Kenny Roota91203b2012-02-15 15:00:46 -08001664
Kenny Root655b9582013-04-04 08:37:42 -07001665 typedef struct {
1666 uint32_t version;
1667 } keystore_metadata_t;
Kenny Roota91203b2012-02-15 15:00:46 -08001668
Kenny Root655b9582013-04-04 08:37:42 -07001669 keystore_metadata_t mMetaData;
Kenny Root70e3a862012-02-15 17:20:23 -08001670
Kenny Root655b9582013-04-04 08:37:42 -07001671 const grant_t* getGrant(const char* filename, uid_t uid) const {
1672 for (android::Vector<grant_t*>::const_iterator it(mGrants.begin());
1673 it != mGrants.end(); it++) {
1674 grant_t* grant = *it;
Kenny Root70e3a862012-02-15 17:20:23 -08001675 if (grant->uid == uid
Kenny Root655b9582013-04-04 08:37:42 -07001676 && !strcmp(reinterpret_cast<const char*>(grant->filename), filename)) {
Kenny Root70e3a862012-02-15 17:20:23 -08001677 return grant;
1678 }
1679 }
Kenny Root70e3a862012-02-15 17:20:23 -08001680 return NULL;
1681 }
1682
Kenny Root822c3a92012-03-23 16:34:39 -07001683 /**
1684 * Upgrade code. This will upgrade the key from the current version
1685 * to whatever is newest.
1686 */
Kenny Root655b9582013-04-04 08:37:42 -07001687 bool upgradeBlob(const char* filename, Blob* blob, const uint8_t oldVersion,
1688 const BlobType type, uid_t uid) {
Kenny Root822c3a92012-03-23 16:34:39 -07001689 bool updated = false;
1690 uint8_t version = oldVersion;
1691
1692 /* From V0 -> V1: All old types were unknown */
1693 if (version == 0) {
1694 ALOGV("upgrading to version 1 and setting type %d", type);
1695
1696 blob->setType(type);
1697 if (type == TYPE_KEY_PAIR) {
Kenny Root655b9582013-04-04 08:37:42 -07001698 importBlobAsKey(blob, filename, uid);
Kenny Root822c3a92012-03-23 16:34:39 -07001699 }
1700 version = 1;
1701 updated = true;
1702 }
1703
Kenny Rootf9119d62013-04-03 09:22:15 -07001704 /* From V1 -> V2: All old keys were encrypted */
1705 if (version == 1) {
1706 ALOGV("upgrading to version 2");
1707
1708 blob->setEncrypted(true);
1709 version = 2;
1710 updated = true;
1711 }
1712
Kenny Root822c3a92012-03-23 16:34:39 -07001713 /*
1714 * If we've updated, set the key blob to the right version
1715 * and write it.
Kenny Rootcfeae072013-04-04 08:39:57 -07001716 */
Kenny Root822c3a92012-03-23 16:34:39 -07001717 if (updated) {
1718 ALOGV("updated and writing file %s", filename);
1719 blob->setVersion(version);
Kenny Root822c3a92012-03-23 16:34:39 -07001720 }
Kenny Rootcfeae072013-04-04 08:39:57 -07001721
1722 return updated;
Kenny Root822c3a92012-03-23 16:34:39 -07001723 }
1724
1725 /**
1726 * Takes a blob that is an PEM-encoded RSA key as a byte array and
1727 * converts it to a DER-encoded PKCS#8 for import into a keymaster.
1728 * Then it overwrites the original blob with the new blob
1729 * format that is returned from the keymaster.
1730 */
Kenny Root655b9582013-04-04 08:37:42 -07001731 ResponseCode importBlobAsKey(Blob* blob, const char* filename, uid_t uid) {
Kenny Root822c3a92012-03-23 16:34:39 -07001732 // We won't even write to the blob directly with this BIO, so const_cast is okay.
1733 Unique_BIO b(BIO_new_mem_buf(const_cast<uint8_t*>(blob->getValue()), blob->getLength()));
1734 if (b.get() == NULL) {
1735 ALOGE("Problem instantiating BIO");
1736 return SYSTEM_ERROR;
1737 }
1738
1739 Unique_EVP_PKEY pkey(PEM_read_bio_PrivateKey(b.get(), NULL, NULL, NULL));
1740 if (pkey.get() == NULL) {
1741 ALOGE("Couldn't read old PEM file");
1742 return SYSTEM_ERROR;
1743 }
1744
1745 Unique_PKCS8_PRIV_KEY_INFO pkcs8(EVP_PKEY2PKCS8(pkey.get()));
1746 int len = i2d_PKCS8_PRIV_KEY_INFO(pkcs8.get(), NULL);
1747 if (len < 0) {
1748 ALOGE("Couldn't measure PKCS#8 length");
1749 return SYSTEM_ERROR;
1750 }
1751
Kenny Root70c98892013-02-07 09:10:36 -08001752 UniquePtr<unsigned char[]> pkcs8key(new unsigned char[len]);
1753 uint8_t* tmp = pkcs8key.get();
Kenny Root822c3a92012-03-23 16:34:39 -07001754 if (i2d_PKCS8_PRIV_KEY_INFO(pkcs8.get(), &tmp) != len) {
1755 ALOGE("Couldn't convert to PKCS#8");
1756 return SYSTEM_ERROR;
1757 }
1758
Chad Brubaker72593ee2015-05-12 10:42:00 -07001759 ResponseCode rc = importKey(pkcs8key.get(), len, filename, get_user_id(uid),
Kenny Rootf9119d62013-04-03 09:22:15 -07001760 blob->isEncrypted() ? KEYSTORE_FLAG_ENCRYPTED : KEYSTORE_FLAG_NONE);
Kenny Root822c3a92012-03-23 16:34:39 -07001761 if (rc != NO_ERROR) {
1762 return rc;
1763 }
1764
Kenny Root655b9582013-04-04 08:37:42 -07001765 return get(filename, blob, TYPE_KEY_PAIR, uid);
1766 }
1767
1768 void readMetaData() {
1769 int in = TEMP_FAILURE_RETRY(open(sMetaDataFile, O_RDONLY));
1770 if (in < 0) {
1771 return;
1772 }
1773 size_t fileLength = readFully(in, (uint8_t*) &mMetaData, sizeof(mMetaData));
1774 if (fileLength != sizeof(mMetaData)) {
1775 ALOGI("Metadata file is %zd bytes (%zd experted); upgrade?", fileLength,
1776 sizeof(mMetaData));
1777 }
1778 close(in);
1779 }
1780
1781 void writeMetaData() {
1782 const char* tmpFileName = ".metadata.tmp";
1783 int out = TEMP_FAILURE_RETRY(open(tmpFileName,
1784 O_WRONLY | O_TRUNC | O_CREAT, S_IRUSR | S_IWUSR));
1785 if (out < 0) {
1786 ALOGE("couldn't write metadata file: %s", strerror(errno));
1787 return;
1788 }
1789 size_t fileLength = writeFully(out, (uint8_t*) &mMetaData, sizeof(mMetaData));
1790 if (fileLength != sizeof(mMetaData)) {
1791 ALOGI("Could only write %zd bytes to metadata file (%zd expected)", fileLength,
1792 sizeof(mMetaData));
1793 }
1794 close(out);
1795 rename(tmpFileName, sMetaDataFile);
1796 }
1797
1798 bool upgradeKeystore() {
1799 bool upgraded = false;
1800
1801 if (mMetaData.version == 0) {
Chad Brubaker72593ee2015-05-12 10:42:00 -07001802 UserState* userState = getUserStateByUid(0);
Kenny Root655b9582013-04-04 08:37:42 -07001803
1804 // Initialize first so the directory is made.
1805 userState->initialize();
1806
1807 // Migrate the old .masterkey file to user 0.
1808 if (access(sOldMasterKey, R_OK) == 0) {
1809 if (rename(sOldMasterKey, userState->getMasterKeyFileName()) < 0) {
1810 ALOGE("couldn't migrate old masterkey: %s", strerror(errno));
1811 return false;
1812 }
1813 }
1814
1815 // Initialize again in case we had a key.
1816 userState->initialize();
1817
1818 // Try to migrate existing keys.
1819 DIR* dir = opendir(".");
1820 if (!dir) {
1821 // Give up now; maybe we can upgrade later.
1822 ALOGE("couldn't open keystore's directory; something is wrong");
1823 return false;
1824 }
1825
1826 struct dirent* file;
1827 while ((file = readdir(dir)) != NULL) {
1828 // We only care about files.
1829 if (file->d_type != DT_REG) {
1830 continue;
1831 }
1832
1833 // Skip anything that starts with a "."
1834 if (file->d_name[0] == '.') {
1835 continue;
1836 }
1837
1838 // Find the current file's user.
1839 char* end;
1840 unsigned long thisUid = strtoul(file->d_name, &end, 10);
1841 if (end[0] != '_' || end[1] == 0) {
1842 continue;
1843 }
Chad Brubaker72593ee2015-05-12 10:42:00 -07001844 UserState* otherUser = getUserStateByUid(thisUid);
Kenny Root655b9582013-04-04 08:37:42 -07001845 if (otherUser->getUserId() != 0) {
1846 unlinkat(dirfd(dir), file->d_name, 0);
1847 }
1848
1849 // Rename the file into user directory.
1850 DIR* otherdir = opendir(otherUser->getUserDirName());
1851 if (otherdir == NULL) {
1852 ALOGW("couldn't open user directory for rename");
1853 continue;
1854 }
1855 if (renameat(dirfd(dir), file->d_name, dirfd(otherdir), file->d_name) < 0) {
1856 ALOGW("couldn't rename blob: %s: %s", file->d_name, strerror(errno));
1857 }
1858 closedir(otherdir);
1859 }
1860 closedir(dir);
1861
1862 mMetaData.version = 1;
1863 upgraded = true;
1864 }
1865
1866 return upgraded;
Kenny Root822c3a92012-03-23 16:34:39 -07001867 }
Kenny Roota91203b2012-02-15 15:00:46 -08001868};
1869
Kenny Root655b9582013-04-04 08:37:42 -07001870const char* KeyStore::sOldMasterKey = ".masterkey";
1871const char* KeyStore::sMetaDataFile = ".metadata";
Kenny Root70e3a862012-02-15 17:20:23 -08001872
Kenny Root1b0e3932013-09-05 13:06:32 -07001873const android::String16 KeyStore::sRSAKeyType("RSA");
1874
Kenny Root07438c82012-11-02 15:41:02 -07001875namespace android {
1876class KeyStoreProxy : public BnKeystoreService, public IBinder::DeathRecipient {
1877public:
1878 KeyStoreProxy(KeyStore* keyStore)
Chad Brubaker40a1a9b2015-02-20 14:08:13 -08001879 : mKeyStore(keyStore),
1880 mOperationMap(this)
Kenny Root07438c82012-11-02 15:41:02 -07001881 {
Kenny Roota91203b2012-02-15 15:00:46 -08001882 }
Kenny Roota91203b2012-02-15 15:00:46 -08001883
Chad Brubaker40a1a9b2015-02-20 14:08:13 -08001884 void binderDied(const wp<IBinder>& who) {
1885 auto operations = mOperationMap.getOperationsForToken(who.unsafe_get());
1886 for (auto token: operations) {
1887 abort(token);
1888 }
Kenny Root822c3a92012-03-23 16:34:39 -07001889 }
Kenny Roota91203b2012-02-15 15:00:46 -08001890
Chad Brubakere6c3bfa2015-05-12 15:18:26 -07001891 int32_t getState(int32_t userId) {
1892 if (!checkBinderPermission(P_GET_STATE)) {
Kenny Root07438c82012-11-02 15:41:02 -07001893 return ::PERMISSION_DENIED;
Kenny Roota91203b2012-02-15 15:00:46 -08001894 }
Kenny Roota91203b2012-02-15 15:00:46 -08001895
Chad Brubakere6c3bfa2015-05-12 15:18:26 -07001896 return mKeyStore->getState(userId);
Kenny Root298e7b12012-03-26 13:54:44 -07001897 }
1898
Kenny Root07438c82012-11-02 15:41:02 -07001899 int32_t get(const String16& name, uint8_t** item, size_t* itemLength) {
Chad Brubaker9489b792015-04-14 11:01:45 -07001900 if (!checkBinderPermission(P_GET)) {
Kenny Root07438c82012-11-02 15:41:02 -07001901 return ::PERMISSION_DENIED;
Kenny Roota91203b2012-02-15 15:00:46 -08001902 }
Kenny Root07438c82012-11-02 15:41:02 -07001903
Chad Brubaker9489b792015-04-14 11:01:45 -07001904 uid_t callingUid = IPCThreadState::self()->getCallingUid();
Kenny Root07438c82012-11-02 15:41:02 -07001905 String8 name8(name);
Kenny Root07438c82012-11-02 15:41:02 -07001906 Blob keyBlob;
Nick Kralevich66dbf672014-06-30 17:09:14 +00001907
Kenny Root655b9582013-04-04 08:37:42 -07001908 ResponseCode responseCode = mKeyStore->getKeyForName(&keyBlob, name8, callingUid,
Kenny Root49468902013-03-19 13:41:33 -07001909 TYPE_GENERIC);
Kenny Root07438c82012-11-02 15:41:02 -07001910 if (responseCode != ::NO_ERROR) {
1911 *item = NULL;
1912 *itemLength = 0;
1913 return responseCode;
Kenny Roota91203b2012-02-15 15:00:46 -08001914 }
Kenny Roota91203b2012-02-15 15:00:46 -08001915
Kenny Root07438c82012-11-02 15:41:02 -07001916 *item = (uint8_t*) malloc(keyBlob.getLength());
1917 memcpy(*item, keyBlob.getValue(), keyBlob.getLength());
1918 *itemLength = keyBlob.getLength();
Kenny Roota91203b2012-02-15 15:00:46 -08001919
Kenny Root07438c82012-11-02 15:41:02 -07001920 return ::NO_ERROR;
Kenny Root70e3a862012-02-15 17:20:23 -08001921 }
1922
Kenny Rootf9119d62013-04-03 09:22:15 -07001923 int32_t insert(const String16& name, const uint8_t* item, size_t itemLength, int targetUid,
1924 int32_t flags) {
Chad Brubaker9489b792015-04-14 11:01:45 -07001925 targetUid = getEffectiveUid(targetUid);
1926 int32_t result = checkBinderPermissionAndKeystoreState(P_INSERT, targetUid,
1927 flags & KEYSTORE_FLAG_ENCRYPTED);
1928 if (result != ::NO_ERROR) {
1929 return result;
Kenny Rootb88c3eb2013-02-13 14:43:43 -08001930 }
1931
Kenny Root07438c82012-11-02 15:41:02 -07001932 String8 name8(name);
Kenny Root655b9582013-04-04 08:37:42 -07001933 String8 filename(mKeyStore->getKeyNameForUidWithDir(name8, targetUid));
Kenny Root07438c82012-11-02 15:41:02 -07001934
1935 Blob keyBlob(item, itemLength, NULL, 0, ::TYPE_GENERIC);
Kenny Rootee8068b2013-10-07 09:49:15 -07001936 keyBlob.setEncrypted(flags & KEYSTORE_FLAG_ENCRYPTED);
1937
Chad Brubaker72593ee2015-05-12 10:42:00 -07001938 return mKeyStore->put(filename.string(), &keyBlob, get_user_id(targetUid));
Kenny Root70e3a862012-02-15 17:20:23 -08001939 }
1940
Kenny Root49468902013-03-19 13:41:33 -07001941 int32_t del(const String16& name, int targetUid) {
Chad Brubaker9489b792015-04-14 11:01:45 -07001942 targetUid = getEffectiveUid(targetUid);
1943 if (!checkBinderPermission(P_DELETE, targetUid)) {
Kenny Root07438c82012-11-02 15:41:02 -07001944 return ::PERMISSION_DENIED;
1945 }
Kenny Root07438c82012-11-02 15:41:02 -07001946 String8 name8(name);
Kenny Root655b9582013-04-04 08:37:42 -07001947 String8 filename(mKeyStore->getKeyNameForUidWithDir(name8, targetUid));
Chad Brubaker72593ee2015-05-12 10:42:00 -07001948 return mKeyStore->del(filename.string(), ::TYPE_ANY, get_user_id(targetUid));
Kenny Root70e3a862012-02-15 17:20:23 -08001949 }
1950
Kenny Root49468902013-03-19 13:41:33 -07001951 int32_t exist(const String16& name, int targetUid) {
Chad Brubaker9489b792015-04-14 11:01:45 -07001952 targetUid = getEffectiveUid(targetUid);
1953 if (!checkBinderPermission(P_EXIST, targetUid)) {
Kenny Rootb88c3eb2013-02-13 14:43:43 -08001954 return ::PERMISSION_DENIED;
1955 }
1956
Kenny Root07438c82012-11-02 15:41:02 -07001957 String8 name8(name);
Kenny Root655b9582013-04-04 08:37:42 -07001958 String8 filename(mKeyStore->getKeyNameForUidWithDir(name8, targetUid));
Kenny Root70e3a862012-02-15 17:20:23 -08001959
Kenny Root655b9582013-04-04 08:37:42 -07001960 if (access(filename.string(), R_OK) == -1) {
Kenny Root07438c82012-11-02 15:41:02 -07001961 return (errno != ENOENT) ? ::SYSTEM_ERROR : ::KEY_NOT_FOUND;
1962 }
1963 return ::NO_ERROR;
Kenny Root70e3a862012-02-15 17:20:23 -08001964 }
1965
Chad Brubakere6c3bfa2015-05-12 15:18:26 -07001966 int32_t list(const String16& prefix, int targetUid, Vector<String16>* matches) {
Chad Brubaker9489b792015-04-14 11:01:45 -07001967 targetUid = getEffectiveUid(targetUid);
Chad Brubakere6c3bfa2015-05-12 15:18:26 -07001968 if (!checkBinderPermission(P_LIST, targetUid)) {
Kenny Root07438c82012-11-02 15:41:02 -07001969 return ::PERMISSION_DENIED;
1970 }
Kenny Root07438c82012-11-02 15:41:02 -07001971 const String8 prefix8(prefix);
Kenny Root655b9582013-04-04 08:37:42 -07001972 String8 filename(mKeyStore->getKeyNameForUid(prefix8, targetUid));
Kenny Root70e3a862012-02-15 17:20:23 -08001973
Chad Brubakere6c3bfa2015-05-12 15:18:26 -07001974 if (mKeyStore->list(filename, matches, get_user_id(targetUid)) != ::NO_ERROR) {
Robin Lee4b84fdc2014-09-24 11:56:57 +01001975 return ::SYSTEM_ERROR;
Kenny Root9a53d3e2012-08-14 10:47:54 -07001976 }
Kenny Root07438c82012-11-02 15:41:02 -07001977 return ::NO_ERROR;
Kenny Root70e3a862012-02-15 17:20:23 -08001978 }
1979
Kenny Root07438c82012-11-02 15:41:02 -07001980 int32_t reset() {
Chad Brubaker9489b792015-04-14 11:01:45 -07001981 if (!checkBinderPermission(P_RESET)) {
Kenny Root07438c82012-11-02 15:41:02 -07001982 return ::PERMISSION_DENIED;
1983 }
1984
Chad Brubaker9489b792015-04-14 11:01:45 -07001985 uid_t callingUid = IPCThreadState::self()->getCallingUid();
Chad Brubaker96d6d782015-05-07 10:19:40 -07001986 mKeyStore->resetUser(get_user_id(callingUid), false);
1987 return ::NO_ERROR;
Kenny Root70e3a862012-02-15 17:20:23 -08001988 }
1989
Chad Brubaker96d6d782015-05-07 10:19:40 -07001990 int32_t onUserPasswordChanged(int32_t userId, const String16& password) {
Chad Brubaker9489b792015-04-14 11:01:45 -07001991 if (!checkBinderPermission(P_PASSWORD)) {
Kenny Root07438c82012-11-02 15:41:02 -07001992 return ::PERMISSION_DENIED;
1993 }
Kenny Root70e3a862012-02-15 17:20:23 -08001994
Kenny Root07438c82012-11-02 15:41:02 -07001995 const String8 password8(password);
Chad Brubaker96d6d782015-05-07 10:19:40 -07001996 // Flush the auth token table to prevent stale tokens from sticking
1997 // around.
1998 mAuthTokenTable.Clear();
1999
2000 if (password.size() == 0) {
2001 ALOGI("Secure lockscreen for user %d removed, deleting encrypted entries", userId);
Chad Brubaker72593ee2015-05-12 10:42:00 -07002002 mKeyStore->resetUser(userId, true);
Chad Brubaker96d6d782015-05-07 10:19:40 -07002003 return ::NO_ERROR;
2004 } else {
Chad Brubaker72593ee2015-05-12 10:42:00 -07002005 switch (mKeyStore->getState(userId)) {
Chad Brubaker96d6d782015-05-07 10:19:40 -07002006 case ::STATE_UNINITIALIZED: {
2007 // generate master key, encrypt with password, write to file,
2008 // initialize mMasterKey*.
Chad Brubaker72593ee2015-05-12 10:42:00 -07002009 return mKeyStore->initializeUser(password8, userId);
Chad Brubaker96d6d782015-05-07 10:19:40 -07002010 }
2011 case ::STATE_NO_ERROR: {
2012 // rewrite master key with new password.
Chad Brubaker72593ee2015-05-12 10:42:00 -07002013 return mKeyStore->writeMasterKey(password8, userId);
Chad Brubaker96d6d782015-05-07 10:19:40 -07002014 }
2015 case ::STATE_LOCKED: {
2016 ALOGE("Changing user %d's password while locked, clearing old encryption",
2017 userId);
Chad Brubaker72593ee2015-05-12 10:42:00 -07002018 mKeyStore->resetUser(userId, true);
2019 return mKeyStore->initializeUser(password8, userId);
Chad Brubaker96d6d782015-05-07 10:19:40 -07002020 }
Kenny Root07438c82012-11-02 15:41:02 -07002021 }
Chad Brubaker96d6d782015-05-07 10:19:40 -07002022 return ::SYSTEM_ERROR;
Kenny Root07438c82012-11-02 15:41:02 -07002023 }
Kenny Root70e3a862012-02-15 17:20:23 -08002024 }
2025
Chad Brubakerc0f031a2015-05-12 10:43:10 -07002026 int32_t onUserAdded(int32_t userId, int32_t parentId) {
2027 if (!checkBinderPermission(P_USER_CHANGED)) {
2028 return ::PERMISSION_DENIED;
2029 }
2030
2031 // Sanity check that the new user has an empty keystore.
2032 if (!mKeyStore->isEmpty(userId)) {
2033 ALOGW("New user %d's keystore not empty. Clearing old entries.", userId);
2034 }
2035 // Unconditionally clear the keystore, just to be safe.
2036 mKeyStore->resetUser(userId, false);
Chad Brubakerc0f031a2015-05-12 10:43:10 -07002037 if (parentId != -1) {
Chad Brubaker410ba592015-09-09 20:34:09 -07002038 // This profile must share the same master key password as the parent
2039 // profile. Because the password of the parent profile is not known
2040 // here, the best we can do is copy the parent's master key and master
2041 // key file. This makes this profile use the same master key as the
2042 // parent profile, forever.
Chad Brubakerc0f031a2015-05-12 10:43:10 -07002043 return mKeyStore->copyMasterKey(parentId, userId);
2044 } else {
2045 return ::NO_ERROR;
2046 }
2047 }
2048
2049 int32_t onUserRemoved(int32_t userId) {
2050 if (!checkBinderPermission(P_USER_CHANGED)) {
2051 return ::PERMISSION_DENIED;
2052 }
2053
2054 mKeyStore->resetUser(userId, false);
2055 return ::NO_ERROR;
2056 }
2057
Chad Brubakere6c3bfa2015-05-12 15:18:26 -07002058 int32_t lock(int32_t userId) {
Chad Brubaker9489b792015-04-14 11:01:45 -07002059 if (!checkBinderPermission(P_LOCK)) {
Kenny Root07438c82012-11-02 15:41:02 -07002060 return ::PERMISSION_DENIED;
2061 }
Kenny Root70e3a862012-02-15 17:20:23 -08002062
Chad Brubaker72593ee2015-05-12 10:42:00 -07002063 State state = mKeyStore->getState(userId);
Kenny Root9d45d1c2013-02-14 10:32:30 -08002064 if (state != ::STATE_NO_ERROR) {
Kenny Root07438c82012-11-02 15:41:02 -07002065 ALOGD("calling lock in state: %d", state);
2066 return state;
2067 }
2068
Chad Brubaker72593ee2015-05-12 10:42:00 -07002069 mKeyStore->lock(userId);
Kenny Root07438c82012-11-02 15:41:02 -07002070 return ::NO_ERROR;
Kenny Root70e3a862012-02-15 17:20:23 -08002071 }
2072
Chad Brubaker96d6d782015-05-07 10:19:40 -07002073 int32_t unlock(int32_t userId, const String16& pw) {
Chad Brubaker9489b792015-04-14 11:01:45 -07002074 if (!checkBinderPermission(P_UNLOCK)) {
Kenny Root07438c82012-11-02 15:41:02 -07002075 return ::PERMISSION_DENIED;
2076 }
2077
Chad Brubaker72593ee2015-05-12 10:42:00 -07002078 State state = mKeyStore->getState(userId);
Kenny Root9d45d1c2013-02-14 10:32:30 -08002079 if (state != ::STATE_LOCKED) {
Chad Brubaker410ba592015-09-09 20:34:09 -07002080 switch (state) {
2081 case ::STATE_NO_ERROR:
2082 ALOGI("calling unlock when already unlocked, ignoring.");
2083 break;
2084 case ::STATE_UNINITIALIZED:
2085 ALOGE("unlock called on uninitialized keystore.");
2086 break;
2087 default:
2088 ALOGE("unlock called on keystore in unknown state: %d", state);
2089 break;
2090 }
Kenny Root07438c82012-11-02 15:41:02 -07002091 return state;
2092 }
2093
2094 const String8 password8(pw);
Chad Brubaker96d6d782015-05-07 10:19:40 -07002095 // read master key, decrypt with password, initialize mMasterKey*.
Chad Brubaker72593ee2015-05-12 10:42:00 -07002096 return mKeyStore->readMasterKey(password8, userId);
Kenny Root70e3a862012-02-15 17:20:23 -08002097 }
2098
Chad Brubakere6c3bfa2015-05-12 15:18:26 -07002099 bool isEmpty(int32_t userId) {
2100 if (!checkBinderPermission(P_IS_EMPTY)) {
2101 return false;
Kenny Root07438c82012-11-02 15:41:02 -07002102 }
Kenny Root70e3a862012-02-15 17:20:23 -08002103
Chad Brubakere6c3bfa2015-05-12 15:18:26 -07002104 return mKeyStore->isEmpty(userId);
Kenny Root70e3a862012-02-15 17:20:23 -08002105 }
2106
Kenny Root96427ba2013-08-16 14:02:41 -07002107 int32_t generate(const String16& name, int32_t targetUid, int32_t keyType, int32_t keySize,
2108 int32_t flags, Vector<sp<KeystoreArg> >* args) {
Chad Brubaker9489b792015-04-14 11:01:45 -07002109 targetUid = getEffectiveUid(targetUid);
2110 int32_t result = checkBinderPermissionAndKeystoreState(P_INSERT, targetUid,
2111 flags & KEYSTORE_FLAG_ENCRYPTED);
2112 if (result != ::NO_ERROR) {
2113 return result;
Kenny Root07438c82012-11-02 15:41:02 -07002114 }
Kenny Root07438c82012-11-02 15:41:02 -07002115
Chad Brubaker3a7d9e62015-06-04 15:01:46 -07002116 KeymasterArguments params;
Shawn Willden55268b52015-07-28 11:06:00 -06002117 add_legacy_key_authorizations(keyType, &params.params);
Kenny Root07438c82012-11-02 15:41:02 -07002118
Chad Brubaker3a7d9e62015-06-04 15:01:46 -07002119 switch (keyType) {
2120 case EVP_PKEY_EC: {
2121 params.params.push_back(keymaster_param_enum(KM_TAG_ALGORITHM, KM_ALGORITHM_EC));
2122 if (keySize == -1) {
2123 keySize = EC_DEFAULT_KEY_SIZE;
2124 } else if (keySize < EC_MIN_KEY_SIZE || keySize > EC_MAX_KEY_SIZE) {
2125 ALOGI("invalid key size %d", keySize);
Kenny Root96427ba2013-08-16 14:02:41 -07002126 return ::SYSTEM_ERROR;
2127 }
Chad Brubaker3a7d9e62015-06-04 15:01:46 -07002128 params.params.push_back(keymaster_param_int(KM_TAG_KEY_SIZE, keySize));
2129 break;
Kenny Root96427ba2013-08-16 14:02:41 -07002130 }
Chad Brubaker3a7d9e62015-06-04 15:01:46 -07002131 case EVP_PKEY_RSA: {
2132 params.params.push_back(keymaster_param_enum(KM_TAG_ALGORITHM, KM_ALGORITHM_RSA));
2133 if (keySize == -1) {
2134 keySize = RSA_DEFAULT_KEY_SIZE;
2135 } else if (keySize < RSA_MIN_KEY_SIZE || keySize > RSA_MAX_KEY_SIZE) {
2136 ALOGI("invalid key size %d", keySize);
2137 return ::SYSTEM_ERROR;
Kenny Root96427ba2013-08-16 14:02:41 -07002138 }
Chad Brubaker3a7d9e62015-06-04 15:01:46 -07002139 params.params.push_back(keymaster_param_int(KM_TAG_KEY_SIZE, keySize));
2140 unsigned long exponent = RSA_DEFAULT_EXPONENT;
2141 if (args->size() > 1) {
2142 ALOGI("invalid number of arguments: %zu", args->size());
2143 return ::SYSTEM_ERROR;
2144 } else if (args->size() == 1) {
2145 sp<KeystoreArg> expArg = args->itemAt(0);
2146 if (expArg != NULL) {
2147 Unique_BIGNUM pubExpBn(
2148 BN_bin2bn(reinterpret_cast<const unsigned char*>(expArg->data()),
2149 expArg->size(), NULL));
2150 if (pubExpBn.get() == NULL) {
2151 ALOGI("Could not convert public exponent to BN");
2152 return ::SYSTEM_ERROR;
2153 }
2154 exponent = BN_get_word(pubExpBn.get());
2155 if (exponent == 0xFFFFFFFFL) {
2156 ALOGW("cannot represent public exponent as a long value");
2157 return ::SYSTEM_ERROR;
2158 }
2159 } else {
2160 ALOGW("public exponent not read");
2161 return ::SYSTEM_ERROR;
2162 }
2163 }
2164 params.params.push_back(keymaster_param_long(KM_TAG_RSA_PUBLIC_EXPONENT,
2165 exponent));
2166 break;
Kenny Root96427ba2013-08-16 14:02:41 -07002167 }
Chad Brubaker3a7d9e62015-06-04 15:01:46 -07002168 default: {
2169 ALOGW("Unsupported key type %d", keyType);
2170 return ::SYSTEM_ERROR;
2171 }
Kenny Root96427ba2013-08-16 14:02:41 -07002172 }
2173
Chad Brubaker3a7d9e62015-06-04 15:01:46 -07002174 int32_t rc = generateKey(name, params, NULL, 0, targetUid, flags,
2175 /*outCharacteristics*/ NULL);
2176 if (rc != ::NO_ERROR) {
2177 ALOGW("generate failed: %d", rc);
Kenny Root07438c82012-11-02 15:41:02 -07002178 }
Chad Brubaker3a7d9e62015-06-04 15:01:46 -07002179 return translateResultToLegacyResult(rc);
Kenny Root70e3a862012-02-15 17:20:23 -08002180 }
2181
Kenny Rootf9119d62013-04-03 09:22:15 -07002182 int32_t import(const String16& name, const uint8_t* data, size_t length, int targetUid,
2183 int32_t flags) {
Chad Brubaker3a7d9e62015-06-04 15:01:46 -07002184 const uint8_t* ptr = data;
Kenny Root07438c82012-11-02 15:41:02 -07002185
Chad Brubaker3a7d9e62015-06-04 15:01:46 -07002186 Unique_PKCS8_PRIV_KEY_INFO pkcs8(d2i_PKCS8_PRIV_KEY_INFO(NULL, &ptr, length));
2187 if (!pkcs8.get()) {
2188 return ::SYSTEM_ERROR;
2189 }
2190 Unique_EVP_PKEY pkey(EVP_PKCS82PKEY(pkcs8.get()));
2191 if (!pkey.get()) {
2192 return ::SYSTEM_ERROR;
2193 }
2194 int type = EVP_PKEY_type(pkey->type);
Shawn Willden2de8b752015-07-23 05:54:31 -06002195 KeymasterArguments params;
Shawn Willden55268b52015-07-28 11:06:00 -06002196 add_legacy_key_authorizations(type, &params.params);
Chad Brubaker3a7d9e62015-06-04 15:01:46 -07002197 switch (type) {
2198 case EVP_PKEY_RSA:
2199 params.params.push_back(keymaster_param_enum(KM_TAG_ALGORITHM, KM_ALGORITHM_RSA));
2200 break;
2201 case EVP_PKEY_EC:
2202 params.params.push_back(keymaster_param_enum(KM_TAG_ALGORITHM,
2203 KM_ALGORITHM_EC));
2204 break;
2205 default:
2206 ALOGW("Unsupported key type %d", type);
2207 return ::SYSTEM_ERROR;
2208 }
2209 int32_t rc = importKey(name, params, KM_KEY_FORMAT_PKCS8, data, length, targetUid, flags,
2210 /*outCharacteristics*/ NULL);
2211 if (rc != ::NO_ERROR) {
2212 ALOGW("importKey failed: %d", rc);
2213 }
2214 return translateResultToLegacyResult(rc);
Kenny Root70e3a862012-02-15 17:20:23 -08002215 }
2216
Kenny Root07438c82012-11-02 15:41:02 -07002217 int32_t sign(const String16& name, const uint8_t* data, size_t length, uint8_t** out,
Chad Brubaker3a7d9e62015-06-04 15:01:46 -07002218 size_t* outLength) {
Chad Brubaker9489b792015-04-14 11:01:45 -07002219 if (!checkBinderPermission(P_SIGN)) {
Kenny Root07438c82012-11-02 15:41:02 -07002220 return ::PERMISSION_DENIED;
2221 }
Chad Brubaker3a7d9e62015-06-04 15:01:46 -07002222 return doLegacySignVerify(name, data, length, out, outLength, NULL, 0, KM_PURPOSE_SIGN);
Kenny Root70e3a862012-02-15 17:20:23 -08002223 }
2224
Kenny Root07438c82012-11-02 15:41:02 -07002225 int32_t verify(const String16& name, const uint8_t* data, size_t dataLength,
2226 const uint8_t* signature, size_t signatureLength) {
Chad Brubaker9489b792015-04-14 11:01:45 -07002227 if (!checkBinderPermission(P_VERIFY)) {
Kenny Root07438c82012-11-02 15:41:02 -07002228 return ::PERMISSION_DENIED;
2229 }
Chad Brubaker3a7d9e62015-06-04 15:01:46 -07002230 return doLegacySignVerify(name, data, dataLength, NULL, NULL, signature, signatureLength,
2231 KM_PURPOSE_VERIFY);
Kenny Roota91203b2012-02-15 15:00:46 -08002232 }
Kenny Root07438c82012-11-02 15:41:02 -07002233
2234 /*
2235 * TODO: The abstraction between things stored in hardware and regular blobs
2236 * of data stored on the filesystem should be moved down to keystore itself.
2237 * Unfortunately the Java code that calls this has naming conventions that it
2238 * knows about. Ideally keystore shouldn't be used to store random blobs of
2239 * data.
2240 *
2241 * Until that happens, it's necessary to have a separate "get_pubkey" and
2242 * "del_key" since the Java code doesn't really communicate what it's
2243 * intentions are.
2244 */
2245 int32_t get_pubkey(const String16& name, uint8_t** pubkey, size_t* pubkeyLength) {
Chad Brubaker3a7d9e62015-06-04 15:01:46 -07002246 ExportResult result;
2247 exportKey(name, KM_KEY_FORMAT_X509, NULL, NULL, &result);
2248 if (result.resultCode != ::NO_ERROR) {
2249 ALOGW("export failed: %d", result.resultCode);
2250 return translateResultToLegacyResult(result.resultCode);
Kenny Root07438c82012-11-02 15:41:02 -07002251 }
Kenny Root07438c82012-11-02 15:41:02 -07002252
Chad Brubaker3a7d9e62015-06-04 15:01:46 -07002253 *pubkey = result.exportData.release();
2254 *pubkeyLength = result.dataLength;
Kenny Root07438c82012-11-02 15:41:02 -07002255 return ::NO_ERROR;
Kenny Roota91203b2012-02-15 15:00:46 -08002256 }
Kenny Root07438c82012-11-02 15:41:02 -07002257
Kenny Root07438c82012-11-02 15:41:02 -07002258 int32_t grant(const String16& name, int32_t granteeUid) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08002259 uid_t callingUid = IPCThreadState::self()->getCallingUid();
Chad Brubaker9489b792015-04-14 11:01:45 -07002260 int32_t result = checkBinderPermissionAndKeystoreState(P_GRANT);
2261 if (result != ::NO_ERROR) {
2262 return result;
Kenny Root07438c82012-11-02 15:41:02 -07002263 }
2264
2265 String8 name8(name);
Kenny Root655b9582013-04-04 08:37:42 -07002266 String8 filename(mKeyStore->getKeyNameForUidWithDir(name8, callingUid));
Kenny Root07438c82012-11-02 15:41:02 -07002267
Kenny Root655b9582013-04-04 08:37:42 -07002268 if (access(filename.string(), R_OK) == -1) {
Kenny Root07438c82012-11-02 15:41:02 -07002269 return (errno != ENOENT) ? ::SYSTEM_ERROR : ::KEY_NOT_FOUND;
2270 }
2271
Kenny Root655b9582013-04-04 08:37:42 -07002272 mKeyStore->addGrant(filename.string(), granteeUid);
Kenny Root07438c82012-11-02 15:41:02 -07002273 return ::NO_ERROR;
2274 }
2275
2276 int32_t ungrant(const String16& name, int32_t granteeUid) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08002277 uid_t callingUid = IPCThreadState::self()->getCallingUid();
Chad Brubaker9489b792015-04-14 11:01:45 -07002278 int32_t result = checkBinderPermissionAndKeystoreState(P_GRANT);
2279 if (result != ::NO_ERROR) {
2280 return result;
Kenny Root07438c82012-11-02 15:41:02 -07002281 }
2282
2283 String8 name8(name);
Kenny Root655b9582013-04-04 08:37:42 -07002284 String8 filename(mKeyStore->getKeyNameForUidWithDir(name8, callingUid));
Kenny Root07438c82012-11-02 15:41:02 -07002285
Kenny Root655b9582013-04-04 08:37:42 -07002286 if (access(filename.string(), R_OK) == -1) {
Kenny Root07438c82012-11-02 15:41:02 -07002287 return (errno != ENOENT) ? ::SYSTEM_ERROR : ::KEY_NOT_FOUND;
2288 }
2289
Kenny Root655b9582013-04-04 08:37:42 -07002290 return mKeyStore->removeGrant(filename.string(), granteeUid) ? ::NO_ERROR : ::KEY_NOT_FOUND;
Kenny Root07438c82012-11-02 15:41:02 -07002291 }
2292
2293 int64_t getmtime(const String16& name) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08002294 uid_t callingUid = IPCThreadState::self()->getCallingUid();
Chad Brubaker9489b792015-04-14 11:01:45 -07002295 if (!checkBinderPermission(P_GET)) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08002296 ALOGW("permission denied for %d: getmtime", callingUid);
Kenny Root36a9e232013-02-04 14:24:15 -08002297 return -1L;
Kenny Root07438c82012-11-02 15:41:02 -07002298 }
Kenny Root07438c82012-11-02 15:41:02 -07002299
2300 String8 name8(name);
Kenny Root655b9582013-04-04 08:37:42 -07002301 String8 filename(mKeyStore->getKeyNameForUidWithDir(name8, callingUid));
Kenny Root07438c82012-11-02 15:41:02 -07002302
Kenny Root655b9582013-04-04 08:37:42 -07002303 if (access(filename.string(), R_OK) == -1) {
2304 ALOGW("could not access %s for getmtime", filename.string());
Kenny Root36a9e232013-02-04 14:24:15 -08002305 return -1L;
Kenny Root07438c82012-11-02 15:41:02 -07002306 }
2307
Kenny Root655b9582013-04-04 08:37:42 -07002308 int fd = TEMP_FAILURE_RETRY(open(filename.string(), O_NOFOLLOW, O_RDONLY));
Kenny Root07438c82012-11-02 15:41:02 -07002309 if (fd < 0) {
Kenny Root655b9582013-04-04 08:37:42 -07002310 ALOGW("could not open %s for getmtime", filename.string());
Kenny Root36a9e232013-02-04 14:24:15 -08002311 return -1L;
Kenny Root07438c82012-11-02 15:41:02 -07002312 }
2313
2314 struct stat s;
2315 int ret = fstat(fd, &s);
2316 close(fd);
2317 if (ret == -1) {
Kenny Root655b9582013-04-04 08:37:42 -07002318 ALOGW("could not stat %s for getmtime", filename.string());
Kenny Root36a9e232013-02-04 14:24:15 -08002319 return -1L;
Kenny Root07438c82012-11-02 15:41:02 -07002320 }
2321
Kenny Root36a9e232013-02-04 14:24:15 -08002322 return static_cast<int64_t>(s.st_mtime);
Kenny Root07438c82012-11-02 15:41:02 -07002323 }
2324
Kenny Rootd53bc922013-03-21 14:10:15 -07002325 int32_t duplicate(const String16& srcKey, int32_t srcUid, const String16& destKey,
2326 int32_t destUid) {
Kenny Root02254072013-03-20 11:48:19 -07002327 uid_t callingUid = IPCThreadState::self()->getCallingUid();
Riley Spahneaabae92014-06-30 12:39:52 -07002328 pid_t spid = IPCThreadState::self()->getCallingPid();
2329 if (!has_permission(callingUid, P_DUPLICATE, spid)) {
Kenny Rootd53bc922013-03-21 14:10:15 -07002330 ALOGW("permission denied for %d: duplicate", callingUid);
Kenny Root02254072013-03-20 11:48:19 -07002331 return -1L;
2332 }
2333
Chad Brubaker72593ee2015-05-12 10:42:00 -07002334 State state = mKeyStore->getState(get_user_id(callingUid));
Kenny Root02254072013-03-20 11:48:19 -07002335 if (!isKeystoreUnlocked(state)) {
Kenny Rootd53bc922013-03-21 14:10:15 -07002336 ALOGD("calling duplicate in state: %d", state);
Kenny Root02254072013-03-20 11:48:19 -07002337 return state;
2338 }
2339
Kenny Rootd53bc922013-03-21 14:10:15 -07002340 if (srcUid == -1 || static_cast<uid_t>(srcUid) == callingUid) {
2341 srcUid = callingUid;
2342 } else if (!is_granted_to(callingUid, srcUid)) {
2343 ALOGD("migrate not granted from source: %d -> %d", callingUid, srcUid);
Kenny Root02254072013-03-20 11:48:19 -07002344 return ::PERMISSION_DENIED;
2345 }
2346
Kenny Rootd53bc922013-03-21 14:10:15 -07002347 if (destUid == -1) {
2348 destUid = callingUid;
2349 }
2350
2351 if (srcUid != destUid) {
2352 if (static_cast<uid_t>(srcUid) != callingUid) {
2353 ALOGD("can only duplicate from caller to other or to same uid: "
2354 "calling=%d, srcUid=%d, destUid=%d", callingUid, srcUid, destUid);
2355 return ::PERMISSION_DENIED;
2356 }
2357
2358 if (!is_granted_to(callingUid, destUid)) {
2359 ALOGD("duplicate not granted to dest: %d -> %d", callingUid, destUid);
2360 return ::PERMISSION_DENIED;
2361 }
2362 }
2363
2364 String8 source8(srcKey);
Kenny Root655b9582013-04-04 08:37:42 -07002365 String8 sourceFile(mKeyStore->getKeyNameForUidWithDir(source8, srcUid));
Kenny Root02254072013-03-20 11:48:19 -07002366
Kenny Rootd53bc922013-03-21 14:10:15 -07002367 String8 target8(destKey);
Kenny Rootfa27d5b2013-10-15 09:01:08 -07002368 String8 targetFile(mKeyStore->getKeyNameForUidWithDir(target8, destUid));
Kenny Root02254072013-03-20 11:48:19 -07002369
Kenny Root655b9582013-04-04 08:37:42 -07002370 if (access(targetFile.string(), W_OK) != -1 || errno != ENOENT) {
2371 ALOGD("destination already exists: %s", targetFile.string());
Kenny Root02254072013-03-20 11:48:19 -07002372 return ::SYSTEM_ERROR;
2373 }
2374
Kenny Rootd53bc922013-03-21 14:10:15 -07002375 Blob keyBlob;
Kenny Root655b9582013-04-04 08:37:42 -07002376 ResponseCode responseCode = mKeyStore->get(sourceFile.string(), &keyBlob, TYPE_ANY,
Chad Brubaker72593ee2015-05-12 10:42:00 -07002377 get_user_id(srcUid));
Kenny Rootd53bc922013-03-21 14:10:15 -07002378 if (responseCode != ::NO_ERROR) {
2379 return responseCode;
Kenny Root02254072013-03-20 11:48:19 -07002380 }
Kenny Rootd53bc922013-03-21 14:10:15 -07002381
Chad Brubaker72593ee2015-05-12 10:42:00 -07002382 return mKeyStore->put(targetFile.string(), &keyBlob, get_user_id(destUid));
Kenny Root02254072013-03-20 11:48:19 -07002383 }
2384
Kenny Root1b0e3932013-09-05 13:06:32 -07002385 int32_t is_hardware_backed(const String16& keyType) {
2386 return mKeyStore->isHardwareBacked(keyType) ? 1 : 0;
Kenny Root8ddf35a2013-03-29 11:15:50 -07002387 }
2388
Kenny Rootfa27d5b2013-10-15 09:01:08 -07002389 int32_t clear_uid(int64_t targetUid64) {
Chad Brubaker9489b792015-04-14 11:01:45 -07002390 uid_t targetUid = getEffectiveUid(targetUid64);
Chad Brubakerb37a5232015-05-01 10:21:27 -07002391 if (!checkBinderPermissionSelfOrSystem(P_CLEAR_UID, targetUid)) {
Kenny Roota9bb5492013-04-01 16:29:11 -07002392 return ::PERMISSION_DENIED;
2393 }
2394
Robin Lee4b84fdc2014-09-24 11:56:57 +01002395 String8 prefix = String8::format("%u_", targetUid);
2396 Vector<String16> aliases;
Chad Brubakere6c3bfa2015-05-12 15:18:26 -07002397 if (mKeyStore->list(prefix, &aliases, get_user_id(targetUid)) != ::NO_ERROR) {
Kenny Roota9bb5492013-04-01 16:29:11 -07002398 return ::SYSTEM_ERROR;
2399 }
2400
Robin Lee4b84fdc2014-09-24 11:56:57 +01002401 for (uint32_t i = 0; i < aliases.size(); i++) {
2402 String8 name8(aliases[i]);
2403 String8 filename(mKeyStore->getKeyNameForUidWithDir(name8, targetUid));
Chad Brubaker72593ee2015-05-12 10:42:00 -07002404 mKeyStore->del(filename.string(), ::TYPE_ANY, get_user_id(targetUid));
Kenny Roota9bb5492013-04-01 16:29:11 -07002405 }
Robin Lee4b84fdc2014-09-24 11:56:57 +01002406 return ::NO_ERROR;
Kenny Roota9bb5492013-04-01 16:29:11 -07002407 }
2408
Chad Brubaker9c8612c2015-02-09 11:32:54 -08002409 int32_t addRngEntropy(const uint8_t* data, size_t dataLength) {
2410 const keymaster1_device_t* device = mKeyStore->getDevice();
2411 const keymaster1_device_t* fallback = mKeyStore->getFallbackDevice();
2412 int32_t devResult = KM_ERROR_UNIMPLEMENTED;
2413 int32_t fallbackResult = KM_ERROR_UNIMPLEMENTED;
2414 if (device->common.module->module_api_version >= KEYMASTER_MODULE_API_VERSION_1_0 &&
2415 device->add_rng_entropy != NULL) {
2416 devResult = device->add_rng_entropy(device, data, dataLength);
2417 }
2418 if (fallback->add_rng_entropy) {
2419 fallbackResult = fallback->add_rng_entropy(fallback, data, dataLength);
2420 }
2421 if (devResult) {
2422 return devResult;
2423 }
2424 if (fallbackResult) {
2425 return fallbackResult;
2426 }
2427 return ::NO_ERROR;
Chad Brubaker9899d6b2015-02-03 13:03:00 -08002428 }
2429
Chad Brubaker17d68b92015-02-05 22:04:16 -08002430 int32_t generateKey(const String16& name, const KeymasterArguments& params,
Chad Brubaker154d7692015-03-27 13:59:31 -07002431 const uint8_t* entropy, size_t entropyLength, int uid, int flags,
2432 KeyCharacteristics* outCharacteristics) {
Chad Brubaker9489b792015-04-14 11:01:45 -07002433 uid = getEffectiveUid(uid);
2434 int rc = checkBinderPermissionAndKeystoreState(P_INSERT, uid,
2435 flags & KEYSTORE_FLAG_ENCRYPTED);
2436 if (rc != ::NO_ERROR) {
2437 return rc;
Chad Brubaker17d68b92015-02-05 22:04:16 -08002438 }
2439
Chad Brubaker9489b792015-04-14 11:01:45 -07002440 rc = KM_ERROR_UNIMPLEMENTED;
Chad Brubaker17d68b92015-02-05 22:04:16 -08002441 bool isFallback = false;
2442 keymaster_key_blob_t blob;
2443 keymaster_key_characteristics_t *out = NULL;
2444
2445 const keymaster1_device_t* device = mKeyStore->getDevice();
2446 const keymaster1_device_t* fallback = mKeyStore->getFallbackDevice();
Chad Brubaker57e106d2015-06-01 12:59:00 -07002447 std::vector<keymaster_key_param_t> opParams(params.params);
2448 const keymaster_key_param_set_t inParams = {opParams.data(), opParams.size()};
Chad Brubaker17d68b92015-02-05 22:04:16 -08002449 if (device == NULL) {
2450 return ::SYSTEM_ERROR;
2451 }
Chad Brubaker154d7692015-03-27 13:59:31 -07002452 // TODO: Seed from Linux RNG before this.
Chad Brubaker17d68b92015-02-05 22:04:16 -08002453 if (device->common.module->module_api_version >= KEYMASTER_MODULE_API_VERSION_1_0 &&
2454 device->generate_key != NULL) {
Chad Brubaker154d7692015-03-27 13:59:31 -07002455 if (!entropy) {
2456 rc = KM_ERROR_OK;
2457 } else if (device->add_rng_entropy) {
2458 rc = device->add_rng_entropy(device, entropy, entropyLength);
2459 } else {
2460 rc = KM_ERROR_UNIMPLEMENTED;
2461 }
2462 if (rc == KM_ERROR_OK) {
Chad Brubaker57e106d2015-06-01 12:59:00 -07002463 rc = device->generate_key(device, &inParams, &blob, &out);
Chad Brubaker154d7692015-03-27 13:59:31 -07002464 }
Chad Brubaker17d68b92015-02-05 22:04:16 -08002465 }
2466 // If the HW device didn't support generate_key or generate_key failed
2467 // fall back to the software implementation.
2468 if (rc && fallback->generate_key != NULL) {
Shawn Willden55268b52015-07-28 11:06:00 -06002469 ALOGW("Primary keymaster device failed to generate key, falling back to SW.");
Chad Brubaker17d68b92015-02-05 22:04:16 -08002470 isFallback = true;
Chad Brubaker154d7692015-03-27 13:59:31 -07002471 if (!entropy) {
2472 rc = KM_ERROR_OK;
2473 } else if (fallback->add_rng_entropy) {
2474 rc = fallback->add_rng_entropy(fallback, entropy, entropyLength);
2475 } else {
2476 rc = KM_ERROR_UNIMPLEMENTED;
2477 }
2478 if (rc == KM_ERROR_OK) {
Chad Brubaker57e106d2015-06-01 12:59:00 -07002479 rc = fallback->generate_key(fallback, &inParams, &blob, &out);
Chad Brubaker154d7692015-03-27 13:59:31 -07002480 }
Chad Brubaker17d68b92015-02-05 22:04:16 -08002481 }
2482
2483 if (out) {
2484 if (outCharacteristics) {
2485 outCharacteristics->characteristics = *out;
2486 } else {
2487 keymaster_free_characteristics(out);
2488 }
2489 free(out);
2490 }
2491
2492 if (rc) {
2493 return rc;
2494 }
2495
2496 String8 name8(name);
2497 String8 filename(mKeyStore->getKeyNameForUidWithDir(name8, uid));
2498
2499 Blob keyBlob(blob.key_material, blob.key_material_size, NULL, 0, ::TYPE_KEYMASTER_10);
2500 keyBlob.setFallback(isFallback);
2501 keyBlob.setEncrypted(flags & KEYSTORE_FLAG_ENCRYPTED);
2502
2503 free(const_cast<uint8_t*>(blob.key_material));
2504
Chad Brubaker72593ee2015-05-12 10:42:00 -07002505 return mKeyStore->put(filename.string(), &keyBlob, get_user_id(uid));
Chad Brubaker9899d6b2015-02-03 13:03:00 -08002506 }
2507
Chad Brubakerf3f071f2015-02-10 19:38:51 -08002508 int32_t getKeyCharacteristics(const String16& name,
Chad Brubakerd6634422015-03-21 22:36:07 -07002509 const keymaster_blob_t* clientId,
2510 const keymaster_blob_t* appData,
Chad Brubakerf3f071f2015-02-10 19:38:51 -08002511 KeyCharacteristics* outCharacteristics) {
Chad Brubakerf3f071f2015-02-10 19:38:51 -08002512 if (!outCharacteristics) {
2513 return KM_ERROR_UNEXPECTED_NULL_POINTER;
2514 }
2515
2516 uid_t callingUid = IPCThreadState::self()->getCallingUid();
2517
2518 Blob keyBlob;
2519 String8 name8(name);
2520 int rc;
2521
2522 ResponseCode responseCode = mKeyStore->getKeyForName(&keyBlob, name8, callingUid,
2523 TYPE_KEYMASTER_10);
2524 if (responseCode != ::NO_ERROR) {
2525 return responseCode;
2526 }
2527 keymaster_key_blob_t key;
2528 key.key_material_size = keyBlob.getLength();
2529 key.key_material = keyBlob.getValue();
2530 keymaster1_device_t* dev = mKeyStore->getDeviceForBlob(keyBlob);
2531 keymaster_key_characteristics_t *out = NULL;
2532 if (!dev->get_key_characteristics) {
2533 ALOGW("device does not implement get_key_characteristics");
2534 return KM_ERROR_UNIMPLEMENTED;
2535 }
Chad Brubakerd6634422015-03-21 22:36:07 -07002536 rc = dev->get_key_characteristics(dev, &key, clientId, appData, &out);
Chad Brubakerf3f071f2015-02-10 19:38:51 -08002537 if (out) {
2538 outCharacteristics->characteristics = *out;
2539 free(out);
2540 }
2541 return rc ? rc : ::NO_ERROR;
Chad Brubaker9899d6b2015-02-03 13:03:00 -08002542 }
2543
Chad Brubaker4c353cb2015-02-11 14:36:11 -08002544 int32_t importKey(const String16& name, const KeymasterArguments& params,
2545 keymaster_key_format_t format, const uint8_t *keyData,
2546 size_t keyLength, int uid, int flags,
2547 KeyCharacteristics* outCharacteristics) {
Chad Brubaker9489b792015-04-14 11:01:45 -07002548 uid = getEffectiveUid(uid);
2549 int rc = checkBinderPermissionAndKeystoreState(P_INSERT, uid,
2550 flags & KEYSTORE_FLAG_ENCRYPTED);
2551 if (rc != ::NO_ERROR) {
2552 return rc;
Chad Brubaker4c353cb2015-02-11 14:36:11 -08002553 }
2554
Chad Brubaker9489b792015-04-14 11:01:45 -07002555 rc = KM_ERROR_UNIMPLEMENTED;
Chad Brubaker4c353cb2015-02-11 14:36:11 -08002556 bool isFallback = false;
2557 keymaster_key_blob_t blob;
2558 keymaster_key_characteristics_t *out = NULL;
2559
2560 const keymaster1_device_t* device = mKeyStore->getDevice();
2561 const keymaster1_device_t* fallback = mKeyStore->getFallbackDevice();
Chad Brubaker57e106d2015-06-01 12:59:00 -07002562 std::vector<keymaster_key_param_t> opParams(params.params);
2563 const keymaster_key_param_set_t inParams = {opParams.data(), opParams.size()};
2564 const keymaster_blob_t input = {keyData, keyLength};
Chad Brubaker4c353cb2015-02-11 14:36:11 -08002565 if (device == NULL) {
2566 return ::SYSTEM_ERROR;
2567 }
2568 if (device->common.module->module_api_version >= KEYMASTER_MODULE_API_VERSION_1_0 &&
2569 device->import_key != NULL) {
Chad Brubaker57e106d2015-06-01 12:59:00 -07002570 rc = device->import_key(device, &inParams, format,&input, &blob, &out);
Chad Brubaker4c353cb2015-02-11 14:36:11 -08002571 }
2572 if (rc && fallback->import_key != NULL) {
Shawn Willden55268b52015-07-28 11:06:00 -06002573 ALOGW("Primary keymaster device failed to import key, falling back to SW.");
Chad Brubaker4c353cb2015-02-11 14:36:11 -08002574 isFallback = true;
Chad Brubaker57e106d2015-06-01 12:59:00 -07002575 rc = fallback->import_key(fallback, &inParams, format, &input, &blob, &out);
Chad Brubaker4c353cb2015-02-11 14:36:11 -08002576 }
2577 if (out) {
2578 if (outCharacteristics) {
2579 outCharacteristics->characteristics = *out;
2580 } else {
2581 keymaster_free_characteristics(out);
2582 }
2583 free(out);
2584 }
2585 if (rc) {
2586 return rc;
2587 }
2588
2589 String8 name8(name);
2590 String8 filename(mKeyStore->getKeyNameForUidWithDir(name8, uid));
2591
2592 Blob keyBlob(blob.key_material, blob.key_material_size, NULL, 0, ::TYPE_KEYMASTER_10);
2593 keyBlob.setFallback(isFallback);
2594 keyBlob.setEncrypted(flags & KEYSTORE_FLAG_ENCRYPTED);
2595
2596 free((void*) blob.key_material);
2597
Chad Brubaker72593ee2015-05-12 10:42:00 -07002598 return mKeyStore->put(filename.string(), &keyBlob, get_user_id(uid));
Chad Brubaker9899d6b2015-02-03 13:03:00 -08002599 }
2600
Chad Brubaker07b0cda2015-02-18 15:52:54 -08002601 void exportKey(const String16& name, keymaster_key_format_t format,
Chad Brubakerd6634422015-03-21 22:36:07 -07002602 const keymaster_blob_t* clientId,
2603 const keymaster_blob_t* appData, ExportResult* result) {
Chad Brubaker07b0cda2015-02-18 15:52:54 -08002604
2605 uid_t callingUid = IPCThreadState::self()->getCallingUid();
2606
2607 Blob keyBlob;
2608 String8 name8(name);
2609 int rc;
2610
2611 ResponseCode responseCode = mKeyStore->getKeyForName(&keyBlob, name8, callingUid,
2612 TYPE_KEYMASTER_10);
2613 if (responseCode != ::NO_ERROR) {
2614 result->resultCode = responseCode;
2615 return;
2616 }
2617 keymaster_key_blob_t key;
2618 key.key_material_size = keyBlob.getLength();
2619 key.key_material = keyBlob.getValue();
2620 keymaster1_device_t* dev = mKeyStore->getDeviceForBlob(keyBlob);
2621 if (!dev->export_key) {
2622 result->resultCode = KM_ERROR_UNIMPLEMENTED;
2623 return;
2624 }
Chad Brubaker57e106d2015-06-01 12:59:00 -07002625 keymaster_blob_t output = {NULL, 0};
2626 rc = dev->export_key(dev, format, &key, clientId, appData, &output);
2627 result->exportData.reset(const_cast<uint8_t*>(output.data));
2628 result->dataLength = output.data_length;
Chad Brubaker07b0cda2015-02-18 15:52:54 -08002629 result->resultCode = rc ? rc : ::NO_ERROR;
Chad Brubaker9899d6b2015-02-03 13:03:00 -08002630 }
2631
Chad Brubakerad6514a2015-04-09 14:00:26 -07002632
Chad Brubaker40a1a9b2015-02-20 14:08:13 -08002633 void begin(const sp<IBinder>& appToken, const String16& name, keymaster_purpose_t purpose,
Chad Brubaker154d7692015-03-27 13:59:31 -07002634 bool pruneable, const KeymasterArguments& params, const uint8_t* entropy,
Chad Brubaker57e106d2015-06-01 12:59:00 -07002635 size_t entropyLength, OperationResult* result) {
Chad Brubaker40a1a9b2015-02-20 14:08:13 -08002636 uid_t callingUid = IPCThreadState::self()->getCallingUid();
2637 if (!pruneable && get_app_id(callingUid) != AID_SYSTEM) {
2638 ALOGE("Non-system uid %d trying to start non-pruneable operation", callingUid);
2639 result->resultCode = ::PERMISSION_DENIED;
2640 return;
2641 }
Chad Brubaker0cf34a22015-04-23 11:06:16 -07002642 if (!checkAllowedOperationParams(params.params)) {
2643 result->resultCode = KM_ERROR_INVALID_ARGUMENT;
2644 return;
2645 }
Chad Brubaker40a1a9b2015-02-20 14:08:13 -08002646 Blob keyBlob;
2647 String8 name8(name);
2648 ResponseCode responseCode = mKeyStore->getKeyForName(&keyBlob, name8, callingUid,
2649 TYPE_KEYMASTER_10);
2650 if (responseCode != ::NO_ERROR) {
2651 result->resultCode = responseCode;
2652 return;
2653 }
2654 keymaster_key_blob_t key;
2655 key.key_material_size = keyBlob.getLength();
2656 key.key_material = keyBlob.getValue();
Chad Brubaker40a1a9b2015-02-20 14:08:13 -08002657 keymaster_operation_handle_t handle;
2658 keymaster1_device_t* dev = mKeyStore->getDeviceForBlob(keyBlob);
Chad Brubaker154d7692015-03-27 13:59:31 -07002659 keymaster_error_t err = KM_ERROR_UNIMPLEMENTED;
Chad Brubaker06801e02015-03-31 15:13:13 -07002660 std::vector<keymaster_key_param_t> opParams(params.params);
Chad Brubakerad6514a2015-04-09 14:00:26 -07002661 Unique_keymaster_key_characteristics characteristics;
2662 characteristics.reset(new keymaster_key_characteristics_t);
2663 err = getOperationCharacteristics(key, dev, opParams, characteristics.get());
2664 if (err) {
2665 result->resultCode = err;
2666 return;
2667 }
Chad Brubaker0cf34a22015-04-23 11:06:16 -07002668 const hw_auth_token_t* authToken = NULL;
Shawn Willdenb2ffa422015-06-17 12:18:55 -06002669 int32_t authResult = getAuthToken(characteristics.get(), 0, purpose, &authToken,
Chad Brubaker06801e02015-03-31 15:13:13 -07002670 /*failOnTokenMissing*/ false);
Chad Brubaker0cf34a22015-04-23 11:06:16 -07002671 // If per-operation auth is needed we need to begin the operation and
2672 // the client will need to authorize that operation before calling
2673 // update. Any other auth issues stop here.
2674 if (authResult != ::NO_ERROR && authResult != ::OP_AUTH_NEEDED) {
2675 result->resultCode = authResult;
Chad Brubaker06801e02015-03-31 15:13:13 -07002676 return;
2677 }
Chad Brubaker0cf34a22015-04-23 11:06:16 -07002678 addAuthToParams(&opParams, authToken);
Chad Brubaker154d7692015-03-27 13:59:31 -07002679 // Add entropy to the device first.
2680 if (entropy) {
2681 if (dev->add_rng_entropy) {
2682 err = dev->add_rng_entropy(dev, entropy, entropyLength);
2683 } else {
2684 err = KM_ERROR_UNIMPLEMENTED;
2685 }
2686 if (err) {
2687 result->resultCode = err;
2688 return;
2689 }
2690 }
Chad Brubaker57e106d2015-06-01 12:59:00 -07002691 keymaster_key_param_set_t inParams = {opParams.data(), opParams.size()};
Chad Brubaker40a1a9b2015-02-20 14:08:13 -08002692
Shawn Willden9221bff2015-06-18 18:23:54 -06002693 // Create a keyid for this key.
2694 keymaster::km_id_t keyid;
2695 if (!enforcement_policy.CreateKeyId(key, &keyid)) {
2696 ALOGE("Failed to create a key ID for authorization checking.");
2697 result->resultCode = KM_ERROR_UNKNOWN_ERROR;
2698 return;
2699 }
2700
2701 // Check that all key authorization policy requirements are met.
2702 keymaster::AuthorizationSet key_auths(characteristics->hw_enforced);
2703 key_auths.push_back(characteristics->sw_enforced);
2704 keymaster::AuthorizationSet operation_params(inParams);
2705 err = enforcement_policy.AuthorizeOperation(purpose, keyid, key_auths, operation_params,
2706 0 /* op_handle */,
2707 true /* is_begin_operation */);
2708 if (err) {
2709 result->resultCode = err;
2710 return;
2711 }
2712
Alex Klyubin4e88f9b2015-06-23 15:04:05 -07002713 keymaster_key_param_set_t outParams = {NULL, 0};
Shawn Willden447095f2015-10-30 10:05:43 -06002714
2715 // If there are more than MAX_OPERATIONS, abort the oldest operation that was started as
2716 // pruneable.
2717 while (mOperationMap.getOperationCount() >= MAX_OPERATIONS) {
2718 ALOGD("Reached or exceeded concurrent operations limit");
2719 if (!pruneOperation()) {
2720 break;
2721 }
2722 }
2723
Alex Klyubin4e88f9b2015-06-23 15:04:05 -07002724 err = dev->begin(dev, purpose, &key, &inParams, &outParams, &handle);
Shawn Willden447095f2015-10-30 10:05:43 -06002725 if (err != KM_ERROR_OK) {
2726 ALOGE("Got error %d from begin()", err);
2727 }
Alex Klyubin4e88f9b2015-06-23 15:04:05 -07002728
Chad Brubaker40a1a9b2015-02-20 14:08:13 -08002729 // If there are too many operations abort the oldest operation that was
2730 // started as pruneable and try again.
2731 while (err == KM_ERROR_TOO_MANY_OPERATIONS && mOperationMap.hasPruneableOperation()) {
Shawn Willden447095f2015-10-30 10:05:43 -06002732 ALOGE("Ran out of operation handles");
2733 if (!pruneOperation()) {
Chad Brubaker40a1a9b2015-02-20 14:08:13 -08002734 break;
2735 }
Chad Brubaker57e106d2015-06-01 12:59:00 -07002736 err = dev->begin(dev, purpose, &key, &inParams, &outParams, &handle);
Chad Brubaker40a1a9b2015-02-20 14:08:13 -08002737 }
2738 if (err) {
2739 result->resultCode = err;
2740 return;
2741 }
Chad Brubaker40a1a9b2015-02-20 14:08:13 -08002742
Shawn Willden9221bff2015-06-18 18:23:54 -06002743 sp<IBinder> operationToken = mOperationMap.addOperation(handle, keyid, purpose, dev,
2744 appToken, characteristics.release(),
Chad Brubaker06801e02015-03-31 15:13:13 -07002745 pruneable);
Chad Brubaker0cf34a22015-04-23 11:06:16 -07002746 if (authToken) {
2747 mOperationMap.setOperationAuthToken(operationToken, authToken);
2748 }
2749 // Return the authentication lookup result. If this is a per operation
2750 // auth'd key then the resultCode will be ::OP_AUTH_NEEDED and the
2751 // application should get an auth token using the handle before the
2752 // first call to update, which will fail if keystore hasn't received the
2753 // auth token.
2754 result->resultCode = authResult;
Chad Brubaker40a1a9b2015-02-20 14:08:13 -08002755 result->token = operationToken;
Chad Brubakerc3a18562015-03-17 18:21:35 -07002756 result->handle = handle;
Chad Brubaker57e106d2015-06-01 12:59:00 -07002757 if (outParams.params) {
2758 result->outParams.params.assign(outParams.params, outParams.params + outParams.length);
2759 free(outParams.params);
2760 }
Chad Brubaker9899d6b2015-02-03 13:03:00 -08002761 }
2762
Chad Brubaker40a1a9b2015-02-20 14:08:13 -08002763 void update(const sp<IBinder>& token, const KeymasterArguments& params, const uint8_t* data,
2764 size_t dataLength, OperationResult* result) {
Chad Brubaker0cf34a22015-04-23 11:06:16 -07002765 if (!checkAllowedOperationParams(params.params)) {
2766 result->resultCode = KM_ERROR_INVALID_ARGUMENT;
2767 return;
2768 }
Chad Brubaker40a1a9b2015-02-20 14:08:13 -08002769 const keymaster1_device_t* dev;
2770 keymaster_operation_handle_t handle;
Shawn Willdenb2ffa422015-06-17 12:18:55 -06002771 keymaster_purpose_t purpose;
Shawn Willden9221bff2015-06-18 18:23:54 -06002772 keymaster::km_id_t keyid;
2773 const keymaster_key_characteristics_t* characteristics;
2774 if (!mOperationMap.getOperation(token, &handle, &keyid, &purpose, &dev, &characteristics)) {
Chad Brubaker40a1a9b2015-02-20 14:08:13 -08002775 result->resultCode = KM_ERROR_INVALID_OPERATION_HANDLE;
2776 return;
2777 }
Chad Brubaker06801e02015-03-31 15:13:13 -07002778 std::vector<keymaster_key_param_t> opParams(params.params);
Chad Brubaker0cf34a22015-04-23 11:06:16 -07002779 int32_t authResult = addOperationAuthTokenIfNeeded(token, &opParams);
2780 if (authResult != ::NO_ERROR) {
Chad Brubaker06801e02015-03-31 15:13:13 -07002781 result->resultCode = authResult;
2782 return;
2783 }
Chad Brubaker57e106d2015-06-01 12:59:00 -07002784 keymaster_key_param_set_t inParams = {opParams.data(), opParams.size()};
2785 keymaster_blob_t input = {data, dataLength};
2786 size_t consumed = 0;
2787 keymaster_blob_t output = {NULL, 0};
2788 keymaster_key_param_set_t outParams = {NULL, 0};
2789
Shawn Willden9221bff2015-06-18 18:23:54 -06002790 // Check that all key authorization policy requirements are met.
2791 keymaster::AuthorizationSet key_auths(characteristics->hw_enforced);
2792 key_auths.push_back(characteristics->sw_enforced);
2793 keymaster::AuthorizationSet operation_params(inParams);
2794 result->resultCode =
2795 enforcement_policy.AuthorizeOperation(purpose, keyid, key_auths,
2796 operation_params, handle,
2797 false /* is_begin_operation */);
2798 if (result->resultCode) {
2799 return;
2800 }
2801
Chad Brubaker57e106d2015-06-01 12:59:00 -07002802 keymaster_error_t err = dev->update(dev, handle, &inParams, &input, &consumed, &outParams,
2803 &output);
2804 result->data.reset(const_cast<uint8_t*>(output.data));
2805 result->dataLength = output.data_length;
Chad Brubaker40a1a9b2015-02-20 14:08:13 -08002806 result->inputConsumed = consumed;
2807 result->resultCode = err ? (int32_t) err : ::NO_ERROR;
Chad Brubaker57e106d2015-06-01 12:59:00 -07002808 if (outParams.params) {
2809 result->outParams.params.assign(outParams.params, outParams.params + outParams.length);
2810 free(outParams.params);
2811 }
Chad Brubaker9899d6b2015-02-03 13:03:00 -08002812 }
2813
Chad Brubaker40a1a9b2015-02-20 14:08:13 -08002814 void finish(const sp<IBinder>& token, const KeymasterArguments& params,
Chad Brubaker0d33e0b2015-05-29 12:30:19 -07002815 const uint8_t* signature, size_t signatureLength,
2816 const uint8_t* entropy, size_t entropyLength, OperationResult* result) {
Chad Brubaker0cf34a22015-04-23 11:06:16 -07002817 if (!checkAllowedOperationParams(params.params)) {
2818 result->resultCode = KM_ERROR_INVALID_ARGUMENT;
2819 return;
2820 }
Chad Brubaker40a1a9b2015-02-20 14:08:13 -08002821 const keymaster1_device_t* dev;
2822 keymaster_operation_handle_t handle;
Shawn Willdenb2ffa422015-06-17 12:18:55 -06002823 keymaster_purpose_t purpose;
Shawn Willden9221bff2015-06-18 18:23:54 -06002824 keymaster::km_id_t keyid;
2825 const keymaster_key_characteristics_t* characteristics;
2826 if (!mOperationMap.getOperation(token, &handle, &keyid, &purpose, &dev, &characteristics)) {
Chad Brubaker40a1a9b2015-02-20 14:08:13 -08002827 result->resultCode = KM_ERROR_INVALID_OPERATION_HANDLE;
2828 return;
2829 }
Chad Brubaker06801e02015-03-31 15:13:13 -07002830 std::vector<keymaster_key_param_t> opParams(params.params);
Chad Brubaker0cf34a22015-04-23 11:06:16 -07002831 int32_t authResult = addOperationAuthTokenIfNeeded(token, &opParams);
2832 if (authResult != ::NO_ERROR) {
Chad Brubaker06801e02015-03-31 15:13:13 -07002833 result->resultCode = authResult;
2834 return;
2835 }
Chad Brubaker0d33e0b2015-05-29 12:30:19 -07002836 keymaster_error_t err;
2837 if (entropy) {
2838 if (dev->add_rng_entropy) {
2839 err = dev->add_rng_entropy(dev, entropy, entropyLength);
2840 } else {
2841 err = KM_ERROR_UNIMPLEMENTED;
2842 }
2843 if (err) {
2844 result->resultCode = err;
2845 return;
2846 }
2847 }
Chad Brubaker0cf34a22015-04-23 11:06:16 -07002848
Chad Brubaker57e106d2015-06-01 12:59:00 -07002849 keymaster_key_param_set_t inParams = {opParams.data(), opParams.size()};
2850 keymaster_blob_t input = {signature, signatureLength};
2851 keymaster_blob_t output = {NULL, 0};
2852 keymaster_key_param_set_t outParams = {NULL, 0};
Shawn Willden9221bff2015-06-18 18:23:54 -06002853
2854 // Check that all key authorization policy requirements are met.
2855 keymaster::AuthorizationSet key_auths(characteristics->hw_enforced);
2856 key_auths.push_back(characteristics->sw_enforced);
2857 keymaster::AuthorizationSet operation_params(inParams);
2858 err = enforcement_policy.AuthorizeOperation(purpose, keyid, key_auths, operation_params,
2859 handle, false /* is_begin_operation */);
2860 if (err) {
2861 result->resultCode = err;
2862 return;
2863 }
2864
Chad Brubaker0d33e0b2015-05-29 12:30:19 -07002865 err = dev->finish(dev, handle, &inParams, &input, &outParams, &output);
Chad Brubaker40a1a9b2015-02-20 14:08:13 -08002866 // Remove the operation regardless of the result
2867 mOperationMap.removeOperation(token);
Chad Brubaker06801e02015-03-31 15:13:13 -07002868 mAuthTokenTable.MarkCompleted(handle);
Chad Brubaker57e106d2015-06-01 12:59:00 -07002869
2870 result->data.reset(const_cast<uint8_t*>(output.data));
2871 result->dataLength = output.data_length;
Chad Brubaker40a1a9b2015-02-20 14:08:13 -08002872 result->resultCode = err ? (int32_t) err : ::NO_ERROR;
Chad Brubaker57e106d2015-06-01 12:59:00 -07002873 if (outParams.params) {
2874 result->outParams.params.assign(outParams.params, outParams.params + outParams.length);
2875 free(outParams.params);
2876 }
Chad Brubaker9899d6b2015-02-03 13:03:00 -08002877 }
2878
Chad Brubaker40a1a9b2015-02-20 14:08:13 -08002879 int32_t abort(const sp<IBinder>& token) {
2880 const keymaster1_device_t* dev;
2881 keymaster_operation_handle_t handle;
Shawn Willdenb2ffa422015-06-17 12:18:55 -06002882 keymaster_purpose_t purpose;
Shawn Willden9221bff2015-06-18 18:23:54 -06002883 keymaster::km_id_t keyid;
2884 if (!mOperationMap.getOperation(token, &handle, &keyid, &purpose, &dev, NULL)) {
Chad Brubaker40a1a9b2015-02-20 14:08:13 -08002885 return KM_ERROR_INVALID_OPERATION_HANDLE;
2886 }
2887 mOperationMap.removeOperation(token);
Chad Brubaker06801e02015-03-31 15:13:13 -07002888 int32_t rc;
Chad Brubaker40a1a9b2015-02-20 14:08:13 -08002889 if (!dev->abort) {
Chad Brubaker06801e02015-03-31 15:13:13 -07002890 rc = KM_ERROR_UNIMPLEMENTED;
2891 } else {
2892 rc = dev->abort(dev, handle);
Chad Brubaker40a1a9b2015-02-20 14:08:13 -08002893 }
Chad Brubaker06801e02015-03-31 15:13:13 -07002894 mAuthTokenTable.MarkCompleted(handle);
Chad Brubaker40a1a9b2015-02-20 14:08:13 -08002895 if (rc) {
2896 return rc;
2897 }
2898 return ::NO_ERROR;
Chad Brubaker9899d6b2015-02-03 13:03:00 -08002899 }
2900
Chad Brubaker2ed2baa2015-03-21 21:20:10 -07002901 bool isOperationAuthorized(const sp<IBinder>& token) {
2902 const keymaster1_device_t* dev;
2903 keymaster_operation_handle_t handle;
Chad Brubakerad6514a2015-04-09 14:00:26 -07002904 const keymaster_key_characteristics_t* characteristics;
Shawn Willdenb2ffa422015-06-17 12:18:55 -06002905 keymaster_purpose_t purpose;
Shawn Willden9221bff2015-06-18 18:23:54 -06002906 keymaster::km_id_t keyid;
2907 if (!mOperationMap.getOperation(token, &handle, &keyid, &purpose, &dev, &characteristics)) {
Chad Brubaker2ed2baa2015-03-21 21:20:10 -07002908 return false;
2909 }
Chad Brubaker0cf34a22015-04-23 11:06:16 -07002910 const hw_auth_token_t* authToken = NULL;
2911 mOperationMap.getOperationAuthToken(token, &authToken);
Chad Brubaker06801e02015-03-31 15:13:13 -07002912 std::vector<keymaster_key_param_t> ignored;
Chad Brubaker0cf34a22015-04-23 11:06:16 -07002913 int32_t authResult = addOperationAuthTokenIfNeeded(token, &ignored);
2914 return authResult == ::NO_ERROR;
Chad Brubaker2ed2baa2015-03-21 21:20:10 -07002915 }
2916
Chad Brubakerd80c7b42015-03-31 11:04:28 -07002917 int32_t addAuthToken(const uint8_t* token, size_t length) {
Chad Brubaker9489b792015-04-14 11:01:45 -07002918 if (!checkBinderPermission(P_ADD_AUTH)) {
2919 ALOGW("addAuthToken: permission denied for %d",
2920 IPCThreadState::self()->getCallingUid());
Chad Brubakerd80c7b42015-03-31 11:04:28 -07002921 return ::PERMISSION_DENIED;
2922 }
2923 if (length != sizeof(hw_auth_token_t)) {
2924 return KM_ERROR_INVALID_ARGUMENT;
2925 }
2926 hw_auth_token_t* authToken = new hw_auth_token_t;
2927 memcpy(reinterpret_cast<void*>(authToken), token, sizeof(hw_auth_token_t));
2928 // The table takes ownership of authToken.
2929 mAuthTokenTable.AddAuthenticationToken(authToken);
2930 return ::NO_ERROR;
Chad Brubaker2ed2baa2015-03-21 21:20:10 -07002931 }
2932
Kenny Root07438c82012-11-02 15:41:02 -07002933private:
Chad Brubaker9489b792015-04-14 11:01:45 -07002934 static const int32_t UID_SELF = -1;
2935
2936 /**
Shawn Willden447095f2015-10-30 10:05:43 -06002937 * Prune the oldest pruneable operation.
2938 */
2939 inline bool pruneOperation() {
2940 sp<IBinder> oldest = mOperationMap.getOldestPruneableOperation();
2941 ALOGD("Trying to prune operation %p", oldest.get());
2942 size_t op_count_before_abort = mOperationMap.getOperationCount();
2943 // We mostly ignore errors from abort() because all we care about is whether at least
2944 // one operation has been removed.
2945 int abort_error = abort(oldest);
2946 if (mOperationMap.getOperationCount() >= op_count_before_abort) {
2947 ALOGE("Failed to abort pruneable operation %p, error: %d", oldest.get(),
2948 abort_error);
2949 return false;
2950 }
2951 return true;
2952 }
2953
2954 /**
Chad Brubaker9489b792015-04-14 11:01:45 -07002955 * Get the effective target uid for a binder operation that takes an
2956 * optional uid as the target.
2957 */
2958 inline uid_t getEffectiveUid(int32_t targetUid) {
2959 if (targetUid == UID_SELF) {
2960 return IPCThreadState::self()->getCallingUid();
2961 }
2962 return static_cast<uid_t>(targetUid);
2963 }
2964
2965 /**
2966 * Check if the caller of the current binder method has the required
2967 * permission and if acting on other uids the grants to do so.
2968 */
2969 inline bool checkBinderPermission(perm_t permission, int32_t targetUid = UID_SELF) {
2970 uid_t callingUid = IPCThreadState::self()->getCallingUid();
2971 pid_t spid = IPCThreadState::self()->getCallingPid();
2972 if (!has_permission(callingUid, permission, spid)) {
2973 ALOGW("permission %s denied for %d", get_perm_label(permission), callingUid);
2974 return false;
2975 }
2976 if (!is_granted_to(callingUid, getEffectiveUid(targetUid))) {
2977 ALOGW("uid %d not granted to act for %d", callingUid, targetUid);
2978 return false;
2979 }
2980 return true;
2981 }
2982
2983 /**
2984 * Check if the caller of the current binder method has the required
Chad Brubakerb37a5232015-05-01 10:21:27 -07002985 * permission and the target uid is the caller or the caller is system.
2986 */
2987 inline bool checkBinderPermissionSelfOrSystem(perm_t permission, int32_t targetUid) {
2988 uid_t callingUid = IPCThreadState::self()->getCallingUid();
2989 pid_t spid = IPCThreadState::self()->getCallingPid();
2990 if (!has_permission(callingUid, permission, spid)) {
2991 ALOGW("permission %s denied for %d", get_perm_label(permission), callingUid);
2992 return false;
2993 }
2994 return getEffectiveUid(targetUid) == callingUid || callingUid == AID_SYSTEM;
2995 }
2996
2997 /**
2998 * Check if the caller of the current binder method has the required
Chad Brubaker9489b792015-04-14 11:01:45 -07002999 * permission or the target of the operation is the caller's uid. This is
3000 * for operation where the permission is only for cross-uid activity and all
3001 * uids are allowed to act on their own (ie: clearing all entries for a
3002 * given uid).
3003 */
3004 inline bool checkBinderPermissionOrSelfTarget(perm_t permission, int32_t targetUid) {
3005 uid_t callingUid = IPCThreadState::self()->getCallingUid();
3006 if (getEffectiveUid(targetUid) == callingUid) {
3007 return true;
3008 } else {
3009 return checkBinderPermission(permission, targetUid);
3010 }
3011 }
3012
3013 /**
3014 * Helper method to check that the caller has the required permission as
3015 * well as the keystore is in the unlocked state if checkUnlocked is true.
3016 *
3017 * Returns NO_ERROR on success, PERMISSION_DENIED on a permission error and
3018 * otherwise the state of keystore when not unlocked and checkUnlocked is
3019 * true.
3020 */
3021 inline int32_t checkBinderPermissionAndKeystoreState(perm_t permission, int32_t targetUid = -1,
3022 bool checkUnlocked = true) {
3023 if (!checkBinderPermission(permission, targetUid)) {
3024 return ::PERMISSION_DENIED;
3025 }
Chad Brubaker72593ee2015-05-12 10:42:00 -07003026 State state = mKeyStore->getState(get_user_id(getEffectiveUid(targetUid)));
Chad Brubaker9489b792015-04-14 11:01:45 -07003027 if (checkUnlocked && !isKeystoreUnlocked(state)) {
3028 return state;
3029 }
3030
3031 return ::NO_ERROR;
3032
3033 }
3034
Kenny Root9d45d1c2013-02-14 10:32:30 -08003035 inline bool isKeystoreUnlocked(State state) {
3036 switch (state) {
3037 case ::STATE_NO_ERROR:
3038 return true;
3039 case ::STATE_UNINITIALIZED:
3040 case ::STATE_LOCKED:
3041 return false;
3042 }
3043 return false;
Kenny Root07438c82012-11-02 15:41:02 -07003044 }
3045
Chad Brubaker67d2a502015-03-11 17:21:18 +00003046 bool isKeyTypeSupported(const keymaster1_device_t* device, keymaster_keypair_t keyType) {
Kenny Root1d448c02013-11-21 10:36:53 -08003047 const int32_t device_api = device->common.module->module_api_version;
3048 if (device_api == KEYMASTER_MODULE_API_VERSION_0_2) {
3049 switch (keyType) {
3050 case TYPE_RSA:
3051 case TYPE_DSA:
3052 case TYPE_EC:
3053 return true;
3054 default:
3055 return false;
3056 }
3057 } else if (device_api >= KEYMASTER_MODULE_API_VERSION_0_3) {
3058 switch (keyType) {
3059 case TYPE_RSA:
3060 return true;
3061 case TYPE_DSA:
3062 return device->flags & KEYMASTER_SUPPORTS_DSA;
3063 case TYPE_EC:
3064 return device->flags & KEYMASTER_SUPPORTS_EC;
3065 default:
3066 return false;
3067 }
3068 } else {
3069 return keyType == TYPE_RSA;
3070 }
3071 }
3072
Chad Brubaker0cf34a22015-04-23 11:06:16 -07003073 /**
3074 * Check that all keymaster_key_param_t's provided by the application are
3075 * allowed. Any parameter that keystore adds itself should be disallowed here.
3076 */
3077 bool checkAllowedOperationParams(const std::vector<keymaster_key_param_t>& params) {
3078 for (auto param: params) {
3079 switch (param.tag) {
3080 case KM_TAG_AUTH_TOKEN:
3081 return false;
3082 default:
3083 break;
3084 }
3085 }
3086 return true;
3087 }
3088
3089 keymaster_error_t getOperationCharacteristics(const keymaster_key_blob_t& key,
3090 const keymaster1_device_t* dev,
3091 const std::vector<keymaster_key_param_t>& params,
3092 keymaster_key_characteristics_t* out) {
3093 UniquePtr<keymaster_blob_t> appId;
3094 UniquePtr<keymaster_blob_t> appData;
3095 for (auto param : params) {
3096 if (param.tag == KM_TAG_APPLICATION_ID) {
3097 appId.reset(new keymaster_blob_t);
3098 appId->data = param.blob.data;
3099 appId->data_length = param.blob.data_length;
3100 } else if (param.tag == KM_TAG_APPLICATION_DATA) {
3101 appData.reset(new keymaster_blob_t);
3102 appData->data = param.blob.data;
3103 appData->data_length = param.blob.data_length;
3104 }
3105 }
3106 keymaster_key_characteristics_t* result = NULL;
3107 if (!dev->get_key_characteristics) {
3108 return KM_ERROR_UNIMPLEMENTED;
3109 }
3110 keymaster_error_t error = dev->get_key_characteristics(dev, &key, appId.get(),
3111 appData.get(), &result);
3112 if (result) {
3113 *out = *result;
3114 free(result);
3115 }
3116 return error;
3117 }
3118
3119 /**
3120 * Get the auth token for this operation from the auth token table.
3121 *
3122 * Returns ::NO_ERROR if the auth token was set or none was required.
3123 * ::OP_AUTH_NEEDED if it is a per op authorization, no
3124 * authorization token exists for that operation and
3125 * failOnTokenMissing is false.
3126 * KM_ERROR_KEY_USER_NOT_AUTHENTICATED if there is no valid auth
3127 * token for the operation
3128 */
3129 int32_t getAuthToken(const keymaster_key_characteristics_t* characteristics,
3130 keymaster_operation_handle_t handle,
Shawn Willdenb2ffa422015-06-17 12:18:55 -06003131 keymaster_purpose_t purpose,
Chad Brubaker0cf34a22015-04-23 11:06:16 -07003132 const hw_auth_token_t** authToken,
3133 bool failOnTokenMissing = true) {
3134
3135 std::vector<keymaster_key_param_t> allCharacteristics;
3136 for (size_t i = 0; i < characteristics->sw_enforced.length; i++) {
3137 allCharacteristics.push_back(characteristics->sw_enforced.params[i]);
3138 }
3139 for (size_t i = 0; i < characteristics->hw_enforced.length; i++) {
3140 allCharacteristics.push_back(characteristics->hw_enforced.params[i]);
3141 }
Shawn Willdenb2ffa422015-06-17 12:18:55 -06003142 keymaster::AuthTokenTable::Error err = mAuthTokenTable.FindAuthorization(
3143 allCharacteristics.data(), allCharacteristics.size(), purpose, handle, authToken);
Chad Brubaker0cf34a22015-04-23 11:06:16 -07003144 switch (err) {
3145 case keymaster::AuthTokenTable::OK:
3146 case keymaster::AuthTokenTable::AUTH_NOT_REQUIRED:
3147 return ::NO_ERROR;
3148 case keymaster::AuthTokenTable::AUTH_TOKEN_NOT_FOUND:
3149 case keymaster::AuthTokenTable::AUTH_TOKEN_EXPIRED:
3150 case keymaster::AuthTokenTable::AUTH_TOKEN_WRONG_SID:
3151 return KM_ERROR_KEY_USER_NOT_AUTHENTICATED;
3152 case keymaster::AuthTokenTable::OP_HANDLE_REQUIRED:
3153 return failOnTokenMissing ? (int32_t) KM_ERROR_KEY_USER_NOT_AUTHENTICATED :
3154 (int32_t) ::OP_AUTH_NEEDED;
3155 default:
3156 ALOGE("Unexpected FindAuthorization return value %d", err);
3157 return KM_ERROR_INVALID_ARGUMENT;
3158 }
3159 }
3160
3161 inline void addAuthToParams(std::vector<keymaster_key_param_t>* params,
3162 const hw_auth_token_t* token) {
3163 if (token) {
3164 params->push_back(keymaster_param_blob(KM_TAG_AUTH_TOKEN,
3165 reinterpret_cast<const uint8_t*>(token),
3166 sizeof(hw_auth_token_t)));
3167 }
3168 }
3169
3170 /**
3171 * Add the auth token for the operation to the param list if the operation
3172 * requires authorization. Uses the cached result in the OperationMap if available
3173 * otherwise gets the token from the AuthTokenTable and caches the result.
3174 *
3175 * Returns ::NO_ERROR if the auth token was added or not needed.
3176 * KM_ERROR_KEY_USER_NOT_AUTHENTICATED if the operation is not
3177 * authenticated.
3178 * KM_ERROR_INVALID_OPERATION_HANDLE if token is not a valid
3179 * operation token.
3180 */
3181 int32_t addOperationAuthTokenIfNeeded(sp<IBinder> token,
3182 std::vector<keymaster_key_param_t>* params) {
3183 const hw_auth_token_t* authToken = NULL;
Chad Brubaker7169a842015-04-29 19:58:34 -07003184 mOperationMap.getOperationAuthToken(token, &authToken);
3185 if (!authToken) {
Chad Brubaker0cf34a22015-04-23 11:06:16 -07003186 const keymaster1_device_t* dev;
3187 keymaster_operation_handle_t handle;
3188 const keymaster_key_characteristics_t* characteristics = NULL;
Shawn Willdenb2ffa422015-06-17 12:18:55 -06003189 keymaster_purpose_t purpose;
Shawn Willden9221bff2015-06-18 18:23:54 -06003190 keymaster::km_id_t keyid;
3191 if (!mOperationMap.getOperation(token, &handle, &keyid, &purpose, &dev,
3192 &characteristics)) {
Chad Brubaker0cf34a22015-04-23 11:06:16 -07003193 return KM_ERROR_INVALID_OPERATION_HANDLE;
3194 }
Shawn Willdenb2ffa422015-06-17 12:18:55 -06003195 int32_t result = getAuthToken(characteristics, handle, purpose, &authToken);
Chad Brubaker0cf34a22015-04-23 11:06:16 -07003196 if (result != ::NO_ERROR) {
3197 return result;
3198 }
3199 if (authToken) {
3200 mOperationMap.setOperationAuthToken(token, authToken);
3201 }
3202 }
3203 addAuthToParams(params, authToken);
3204 return ::NO_ERROR;
3205 }
3206
Chad Brubaker3a7d9e62015-06-04 15:01:46 -07003207 /**
3208 * Translate a result value to a legacy return value. All keystore errors are
3209 * preserved and keymaster errors become SYSTEM_ERRORs
3210 */
3211 inline int32_t translateResultToLegacyResult(int32_t result) {
3212 if (result > 0) {
3213 return result;
3214 }
3215 return ::SYSTEM_ERROR;
3216 }
3217
Chad Brubaker3a7d9e62015-06-04 15:01:46 -07003218 keymaster_key_param_t* getKeyAlgorithm(keymaster_key_characteristics_t* characteristics) {
3219 for (size_t i = 0; i < characteristics->hw_enforced.length; i++) {
3220 if (characteristics->hw_enforced.params[i].tag == KM_TAG_ALGORITHM) {
3221 return &characteristics->hw_enforced.params[i];
3222 }
3223 }
3224 for (size_t i = 0; i < characteristics->sw_enforced.length; i++) {
3225 if (characteristics->sw_enforced.params[i].tag == KM_TAG_ALGORITHM) {
3226 return &characteristics->sw_enforced.params[i];
3227 }
3228 }
3229 return NULL;
3230 }
3231
3232 void addLegacyBeginParams(const String16& name, std::vector<keymaster_key_param_t>& params) {
3233 // All legacy keys are DIGEST_NONE/PAD_NONE.
3234 params.push_back(keymaster_param_enum(KM_TAG_DIGEST, KM_DIGEST_NONE));
3235 params.push_back(keymaster_param_enum(KM_TAG_PADDING, KM_PAD_NONE));
3236
3237 // Look up the algorithm of the key.
3238 KeyCharacteristics characteristics;
3239 int32_t rc = getKeyCharacteristics(name, NULL, NULL, &characteristics);
3240 if (rc != ::NO_ERROR) {
3241 ALOGE("Failed to get key characteristics");
3242 return;
3243 }
3244 keymaster_key_param_t* algorithm = getKeyAlgorithm(&characteristics.characteristics);
3245 if (!algorithm) {
3246 ALOGE("getKeyCharacteristics did not include KM_TAG_ALGORITHM");
3247 return;
3248 }
3249 params.push_back(*algorithm);
3250 }
3251
3252 int32_t doLegacySignVerify(const String16& name, const uint8_t* data, size_t length,
3253 uint8_t** out, size_t* outLength, const uint8_t* signature,
3254 size_t signatureLength, keymaster_purpose_t purpose) {
3255
Chad Brubaker3a7d9e62015-06-04 15:01:46 -07003256 std::basic_stringstream<uint8_t> outBuffer;
3257 OperationResult result;
3258 KeymasterArguments inArgs;
3259 addLegacyBeginParams(name, inArgs.params);
3260 sp<IBinder> appToken(new BBinder);
3261 sp<IBinder> token;
3262
3263 begin(appToken, name, purpose, true, inArgs, NULL, 0, &result);
3264 if (result.resultCode != ResponseCode::NO_ERROR) {
Chad Brubakerdf705172015-06-17 20:17:51 -07003265 if (result.resultCode == ::KEY_NOT_FOUND) {
3266 ALOGW("Key not found");
3267 } else {
3268 ALOGW("Error in begin: %d", result.resultCode);
3269 }
Chad Brubaker3a7d9e62015-06-04 15:01:46 -07003270 return translateResultToLegacyResult(result.resultCode);
3271 }
3272 inArgs.params.clear();
3273 token = result.token;
3274 size_t consumed = 0;
3275 size_t lastConsumed = 0;
3276 do {
3277 update(token, inArgs, data + consumed, length - consumed, &result);
3278 if (result.resultCode != ResponseCode::NO_ERROR) {
3279 ALOGW("Error in update: %d", result.resultCode);
3280 return translateResultToLegacyResult(result.resultCode);
3281 }
3282 if (out) {
3283 outBuffer.write(result.data.get(), result.dataLength);
3284 }
3285 lastConsumed = result.inputConsumed;
3286 consumed += lastConsumed;
3287 } while (consumed < length && lastConsumed > 0);
3288
3289 if (consumed != length) {
3290 ALOGW("Not all data consumed. Consumed %zu of %zu", consumed, length);
3291 return ::SYSTEM_ERROR;
3292 }
3293
3294 finish(token, inArgs, signature, signatureLength, NULL, 0, &result);
3295 if (result.resultCode != ResponseCode::NO_ERROR) {
3296 ALOGW("Error in finish: %d", result.resultCode);
3297 return translateResultToLegacyResult(result.resultCode);
3298 }
3299 if (out) {
3300 outBuffer.write(result.data.get(), result.dataLength);
3301 }
3302
3303 if (out) {
3304 auto buf = outBuffer.str();
3305 *out = new uint8_t[buf.size()];
3306 memcpy(*out, buf.c_str(), buf.size());
3307 *outLength = buf.size();
3308 }
3309
3310 return ::NO_ERROR;
3311 }
3312
Kenny Root07438c82012-11-02 15:41:02 -07003313 ::KeyStore* mKeyStore;
Chad Brubaker40a1a9b2015-02-20 14:08:13 -08003314 OperationMap mOperationMap;
Chad Brubakerd80c7b42015-03-31 11:04:28 -07003315 keymaster::AuthTokenTable mAuthTokenTable;
Shawn Willden9221bff2015-06-18 18:23:54 -06003316 KeystoreKeymasterEnforcement enforcement_policy;
Kenny Root07438c82012-11-02 15:41:02 -07003317};
3318
3319}; // namespace android
Kenny Roota91203b2012-02-15 15:00:46 -08003320
3321int main(int argc, char* argv[]) {
Kenny Roota91203b2012-02-15 15:00:46 -08003322 if (argc < 2) {
3323 ALOGE("A directory must be specified!");
3324 return 1;
3325 }
3326 if (chdir(argv[1]) == -1) {
3327 ALOGE("chdir: %s: %s", argv[1], strerror(errno));
3328 return 1;
3329 }
3330
3331 Entropy entropy;
3332 if (!entropy.open()) {
3333 return 1;
3334 }
Kenny Root70e3a862012-02-15 17:20:23 -08003335
Chad Brubakerbd07a232015-06-01 10:44:27 -07003336 keymaster1_device_t* dev;
Kenny Root70e3a862012-02-15 17:20:23 -08003337 if (keymaster_device_initialize(&dev)) {
3338 ALOGE("keystore keymaster could not be initialized; exiting");
3339 return 1;
3340 }
3341
Chad Brubaker67d2a502015-03-11 17:21:18 +00003342 keymaster1_device_t* fallback;
Chad Brubakerfc18edc2015-01-12 15:17:18 -08003343 if (fallback_keymaster_device_initialize(&fallback)) {
3344 ALOGE("software keymaster could not be initialized; exiting");
3345 return 1;
3346 }
3347
Riley Spahneaabae92014-06-30 12:39:52 -07003348 ks_is_selinux_enabled = is_selinux_enabled();
3349 if (ks_is_selinux_enabled) {
3350 union selinux_callback cb;
William Robertse46b8552015-10-02 08:19:52 -07003351 cb.func_audit = audit_callback;
3352 selinux_set_callback(SELINUX_CB_AUDIT, cb);
Riley Spahneaabae92014-06-30 12:39:52 -07003353 cb.func_log = selinux_log_callback;
3354 selinux_set_callback(SELINUX_CB_LOG, cb);
3355 if (getcon(&tctx) != 0) {
3356 ALOGE("SELinux: Could not acquire target context. Aborting keystore.\n");
3357 return -1;
3358 }
3359 } else {
3360 ALOGI("SELinux: Keystore SELinux is disabled.\n");
3361 }
3362
Chad Brubakerbd07a232015-06-01 10:44:27 -07003363 KeyStore keyStore(&entropy, dev, fallback);
Kenny Root655b9582013-04-04 08:37:42 -07003364 keyStore.initialize();
Kenny Root07438c82012-11-02 15:41:02 -07003365 android::sp<android::IServiceManager> sm = android::defaultServiceManager();
3366 android::sp<android::KeyStoreProxy> proxy = new android::KeyStoreProxy(&keyStore);
3367 android::status_t ret = sm->addService(android::String16("android.security.keystore"), proxy);
3368 if (ret != android::OK) {
3369 ALOGE("Couldn't register binder service!");
3370 return -1;
Kenny Roota91203b2012-02-15 15:00:46 -08003371 }
Kenny Root07438c82012-11-02 15:41:02 -07003372
3373 /*
3374 * We're the only thread in existence, so we're just going to process
3375 * Binder transaction as a single-threaded program.
3376 */
3377 android::IPCThreadState::self()->joinThreadPool();
Kenny Root70e3a862012-02-15 17:20:23 -08003378
3379 keymaster_device_release(dev);
Kenny Roota91203b2012-02-15 15:00:46 -08003380 return 1;
3381}