blob: e4664661a1ce8591da8d80d2e02d45279a8b197d [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 Willden1f769692015-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
Riley Spahneaabae92014-06-30 12:39:52 -0700334static char *tctx;
335static int ks_is_selinux_enabled;
336
337static const char *get_perm_label(perm_t perm) {
338 unsigned int index = ffs(perm);
339 if (index > 0 && index <= (sizeof(perm_labels) / sizeof(perm_labels[0]))) {
340 return perm_labels[index - 1];
341 } else {
342 ALOGE("Keystore: Failed to retrieve permission label.\n");
343 abort();
344 }
345}
346
Kenny Root655b9582013-04-04 08:37:42 -0700347/**
348 * Returns the app ID (in the Android multi-user sense) for the current
349 * UNIX UID.
350 */
351static uid_t get_app_id(uid_t uid) {
352 return uid % AID_USER;
353}
354
355/**
356 * Returns the user ID (in the Android multi-user sense) for the current
357 * UNIX UID.
358 */
359static uid_t get_user_id(uid_t uid) {
360 return uid / AID_USER;
361}
362
Chih-Hung Hsieha25b2a32014-09-03 12:14:45 -0700363static bool keystore_selinux_check_access(uid_t /*uid*/, perm_t perm, pid_t spid) {
Riley Spahneaabae92014-06-30 12:39:52 -0700364 if (!ks_is_selinux_enabled) {
365 return true;
366 }
Nick Kralevich66dbf672014-06-30 17:09:14 +0000367
Riley Spahneaabae92014-06-30 12:39:52 -0700368 char *sctx = NULL;
369 const char *selinux_class = "keystore_key";
370 const char *str_perm = get_perm_label(perm);
371
372 if (!str_perm) {
373 return false;
374 }
375
376 if (getpidcon(spid, &sctx) != 0) {
377 ALOGE("SELinux: Failed to get source pid context.\n");
378 return false;
379 }
380
381 bool allowed = selinux_check_access(sctx, tctx, selinux_class, str_perm,
382 NULL) == 0;
383 freecon(sctx);
384 return allowed;
385}
386
387static bool has_permission(uid_t uid, perm_t perm, pid_t spid) {
Kenny Root655b9582013-04-04 08:37:42 -0700388 // All system users are equivalent for multi-user support.
389 if (get_app_id(uid) == AID_SYSTEM) {
390 uid = AID_SYSTEM;
391 }
392
Kenny Root07438c82012-11-02 15:41:02 -0700393 for (size_t i = 0; i < sizeof(user_perms)/sizeof(user_perms[0]); i++) {
394 struct user_perm user = user_perms[i];
395 if (user.uid == uid) {
Riley Spahneaabae92014-06-30 12:39:52 -0700396 return (user.perms & perm) &&
397 keystore_selinux_check_access(uid, perm, spid);
Kenny Root07438c82012-11-02 15:41:02 -0700398 }
399 }
400
Riley Spahneaabae92014-06-30 12:39:52 -0700401 return (DEFAULT_PERMS & perm) &&
402 keystore_selinux_check_access(uid, perm, spid);
Kenny Root07438c82012-11-02 15:41:02 -0700403}
404
Kenny Root49468902013-03-19 13:41:33 -0700405/**
406 * Returns the UID that the callingUid should act as. This is here for
407 * legacy support of the WiFi and VPN systems and should be removed
408 * when WiFi can operate in its own namespace.
409 */
Kenny Root07438c82012-11-02 15:41:02 -0700410static uid_t get_keystore_euid(uid_t uid) {
411 for (size_t i = 0; i < sizeof(user_euids)/sizeof(user_euids[0]); i++) {
412 struct user_euid user = user_euids[i];
413 if (user.uid == uid) {
414 return user.euid;
415 }
416 }
417
418 return uid;
419}
420
Kenny Root49468902013-03-19 13:41:33 -0700421/**
422 * Returns true if the callingUid is allowed to interact in the targetUid's
423 * namespace.
424 */
425static bool is_granted_to(uid_t callingUid, uid_t targetUid) {
Chad Brubaker9489b792015-04-14 11:01:45 -0700426 if (callingUid == targetUid) {
427 return true;
428 }
Kenny Root49468902013-03-19 13:41:33 -0700429 for (size_t i = 0; i < sizeof(user_euids)/sizeof(user_euids[0]); i++) {
430 struct user_euid user = user_euids[i];
431 if (user.euid == callingUid && user.uid == targetUid) {
432 return true;
433 }
434 }
435
436 return false;
437}
438
Kenny Roota91203b2012-02-15 15:00:46 -0800439/* Here is the encoding of keys. This is necessary in order to allow arbitrary
440 * characters in keys. Characters in [0-~] are not encoded. Others are encoded
441 * into two bytes. The first byte is one of [+-.] which represents the first
442 * two bits of the character. The second byte encodes the rest of the bits into
443 * [0-o]. Therefore in the worst case the length of a key gets doubled. Note
444 * that Base64 cannot be used here due to the need of prefix match on keys. */
445
Kenny Root655b9582013-04-04 08:37:42 -0700446static size_t encode_key_length(const android::String8& keyName) {
447 const uint8_t* in = reinterpret_cast<const uint8_t*>(keyName.string());
448 size_t length = keyName.length();
449 for (int i = length; i > 0; --i, ++in) {
450 if (*in < '0' || *in > '~') {
451 ++length;
452 }
453 }
454 return length;
455}
456
Kenny Root07438c82012-11-02 15:41:02 -0700457static int encode_key(char* out, const android::String8& keyName) {
458 const uint8_t* in = reinterpret_cast<const uint8_t*>(keyName.string());
459 size_t length = keyName.length();
Kenny Roota91203b2012-02-15 15:00:46 -0800460 for (int i = length; i > 0; --i, ++in, ++out) {
Kenny Root655b9582013-04-04 08:37:42 -0700461 if (*in < '0' || *in > '~') {
Kenny Roota91203b2012-02-15 15:00:46 -0800462 *out = '+' + (*in >> 6);
463 *++out = '0' + (*in & 0x3F);
464 ++length;
Kenny Root655b9582013-04-04 08:37:42 -0700465 } else {
466 *out = *in;
Kenny Roota91203b2012-02-15 15:00:46 -0800467 }
468 }
469 *out = '\0';
Kenny Root70e3a862012-02-15 17:20:23 -0800470 return length;
471}
472
Kenny Root07438c82012-11-02 15:41:02 -0700473/*
474 * Converts from the "escaped" format on disk to actual name.
475 * This will be smaller than the input string.
476 *
477 * Characters that should combine with the next at the end will be truncated.
478 */
479static size_t decode_key_length(const char* in, size_t length) {
480 size_t outLength = 0;
481
482 for (const char* end = in + length; in < end; in++) {
483 /* This combines with the next character. */
484 if (*in < '0' || *in > '~') {
485 continue;
486 }
487
488 outLength++;
489 }
490 return outLength;
491}
492
493static void decode_key(char* out, const char* in, size_t length) {
494 for (const char* end = in + length; in < end; in++) {
495 if (*in < '0' || *in > '~') {
496 /* Truncate combining characters at the end. */
497 if (in + 1 >= end) {
498 break;
499 }
500
501 *out = (*in++ - '+') << 6;
502 *out++ |= (*in - '0') & 0x3F;
Kenny Roota91203b2012-02-15 15:00:46 -0800503 } else {
Kenny Root07438c82012-11-02 15:41:02 -0700504 *out++ = *in;
Kenny Roota91203b2012-02-15 15:00:46 -0800505 }
506 }
507 *out = '\0';
Kenny Roota91203b2012-02-15 15:00:46 -0800508}
509
510static size_t readFully(int fd, uint8_t* data, size_t size) {
511 size_t remaining = size;
512 while (remaining > 0) {
Kenny Root150ca932012-11-14 14:29:02 -0800513 ssize_t n = TEMP_FAILURE_RETRY(read(fd, data, remaining));
Kenny Root5281edb2012-11-21 15:14:04 -0800514 if (n <= 0) {
Kenny Root150ca932012-11-14 14:29:02 -0800515 return size - remaining;
Kenny Roota91203b2012-02-15 15:00:46 -0800516 }
517 data += n;
518 remaining -= n;
519 }
520 return size;
521}
522
523static size_t writeFully(int fd, uint8_t* data, size_t size) {
524 size_t remaining = size;
525 while (remaining > 0) {
Kenny Root150ca932012-11-14 14:29:02 -0800526 ssize_t n = TEMP_FAILURE_RETRY(write(fd, data, remaining));
527 if (n < 0) {
528 ALOGW("write failed: %s", strerror(errno));
529 return size - remaining;
Kenny Roota91203b2012-02-15 15:00:46 -0800530 }
531 data += n;
532 remaining -= n;
533 }
534 return size;
535}
536
537class Entropy {
538public:
539 Entropy() : mRandom(-1) {}
540 ~Entropy() {
Kenny Root150ca932012-11-14 14:29:02 -0800541 if (mRandom >= 0) {
Kenny Roota91203b2012-02-15 15:00:46 -0800542 close(mRandom);
543 }
544 }
545
546 bool open() {
547 const char* randomDevice = "/dev/urandom";
Kenny Root150ca932012-11-14 14:29:02 -0800548 mRandom = TEMP_FAILURE_RETRY(::open(randomDevice, O_RDONLY));
549 if (mRandom < 0) {
Kenny Roota91203b2012-02-15 15:00:46 -0800550 ALOGE("open: %s: %s", randomDevice, strerror(errno));
551 return false;
552 }
553 return true;
554 }
555
Kenny Root51878182012-03-13 12:53:19 -0700556 bool generate_random_data(uint8_t* data, size_t size) const {
Kenny Roota91203b2012-02-15 15:00:46 -0800557 return (readFully(mRandom, data, size) == size);
558 }
559
560private:
561 int mRandom;
562};
563
564/* Here is the file format. There are two parts in blob.value, the secret and
565 * the description. The secret is stored in ciphertext, and its original size
566 * can be found in blob.length. The description is stored after the secret in
567 * plaintext, and its size is specified in blob.info. The total size of the two
Kenny Root822c3a92012-03-23 16:34:39 -0700568 * parts must be no more than VALUE_SIZE bytes. The first field is the version,
Kenny Rootf9119d62013-04-03 09:22:15 -0700569 * the second is the blob's type, and the third byte is flags. Fields other
Kenny Roota91203b2012-02-15 15:00:46 -0800570 * than blob.info, blob.length, and blob.value are modified by encryptBlob()
571 * and decryptBlob(). Thus they should not be accessed from outside. */
572
Kenny Root822c3a92012-03-23 16:34:39 -0700573/* ** Note to future implementors of encryption: **
574 * Currently this is the construction:
575 * metadata || Enc(MD5(data) || data)
576 *
577 * This should be the construction used for encrypting if re-implementing:
578 *
579 * Derive independent keys for encryption and MAC:
580 * Kenc = AES_encrypt(masterKey, "Encrypt")
581 * Kmac = AES_encrypt(masterKey, "MAC")
582 *
583 * Store this:
584 * metadata || AES_CTR_encrypt(Kenc, rand_IV, data) ||
585 * HMAC(Kmac, metadata || Enc(data))
586 */
Kenny Roota91203b2012-02-15 15:00:46 -0800587struct __attribute__((packed)) blob {
Kenny Root822c3a92012-03-23 16:34:39 -0700588 uint8_t version;
589 uint8_t type;
Kenny Rootf9119d62013-04-03 09:22:15 -0700590 uint8_t flags;
Kenny Roota91203b2012-02-15 15:00:46 -0800591 uint8_t info;
592 uint8_t vector[AES_BLOCK_SIZE];
Kenny Root822c3a92012-03-23 16:34:39 -0700593 uint8_t encrypted[0]; // Marks offset to encrypted data.
Kenny Roota91203b2012-02-15 15:00:46 -0800594 uint8_t digest[MD5_DIGEST_LENGTH];
Kenny Root822c3a92012-03-23 16:34:39 -0700595 uint8_t digested[0]; // Marks offset to digested data.
Kenny Roota91203b2012-02-15 15:00:46 -0800596 int32_t length; // in network byte order when encrypted
597 uint8_t value[VALUE_SIZE + AES_BLOCK_SIZE];
598};
599
Kenny Root822c3a92012-03-23 16:34:39 -0700600typedef enum {
Kenny Rootd53bc922013-03-21 14:10:15 -0700601 TYPE_ANY = 0, // meta type that matches anything
Kenny Root822c3a92012-03-23 16:34:39 -0700602 TYPE_GENERIC = 1,
603 TYPE_MASTER_KEY = 2,
604 TYPE_KEY_PAIR = 3,
Chad Brubaker17d68b92015-02-05 22:04:16 -0800605 TYPE_KEYMASTER_10 = 4,
Kenny Root822c3a92012-03-23 16:34:39 -0700606} BlobType;
607
Kenny Rootf9119d62013-04-03 09:22:15 -0700608static const uint8_t CURRENT_BLOB_VERSION = 2;
Kenny Root822c3a92012-03-23 16:34:39 -0700609
Kenny Roota91203b2012-02-15 15:00:46 -0800610class Blob {
611public:
Chad Brubaker803f37f2015-07-29 13:53:36 -0700612 Blob(const uint8_t* value, size_t valueLength, const uint8_t* info, uint8_t infoLength,
Kenny Root07438c82012-11-02 15:41:02 -0700613 BlobType type) {
Alex Klyubin1773b442015-02-20 12:33:33 -0800614 memset(&mBlob, 0, sizeof(mBlob));
Chad Brubaker54b1e9a2015-08-12 13:40:31 -0700615 if (valueLength > VALUE_SIZE) {
616 valueLength = VALUE_SIZE;
Chad Brubaker803f37f2015-07-29 13:53:36 -0700617 ALOGW("Provided blob length too large");
618 }
Chad Brubaker54b1e9a2015-08-12 13:40:31 -0700619 if (infoLength + valueLength > VALUE_SIZE) {
620 infoLength = VALUE_SIZE - valueLength;
Chad Brubaker803f37f2015-07-29 13:53:36 -0700621 ALOGW("Provided info length too large");
622 }
Kenny Roota91203b2012-02-15 15:00:46 -0800623 mBlob.length = valueLength;
624 memcpy(mBlob.value, value, valueLength);
625
626 mBlob.info = infoLength;
627 memcpy(mBlob.value + valueLength, info, infoLength);
Kenny Root822c3a92012-03-23 16:34:39 -0700628
Kenny Root07438c82012-11-02 15:41:02 -0700629 mBlob.version = CURRENT_BLOB_VERSION;
Kenny Root822c3a92012-03-23 16:34:39 -0700630 mBlob.type = uint8_t(type);
Kenny Rootf9119d62013-04-03 09:22:15 -0700631
Kenny Rootee8068b2013-10-07 09:49:15 -0700632 if (type == TYPE_MASTER_KEY) {
633 mBlob.flags = KEYSTORE_FLAG_ENCRYPTED;
634 } else {
635 mBlob.flags = KEYSTORE_FLAG_NONE;
636 }
Kenny Roota91203b2012-02-15 15:00:46 -0800637 }
638
639 Blob(blob b) {
640 mBlob = b;
641 }
642
Alex Klyubin1773b442015-02-20 12:33:33 -0800643 Blob() {
644 memset(&mBlob, 0, sizeof(mBlob));
645 }
Kenny Roota91203b2012-02-15 15:00:46 -0800646
Kenny Root51878182012-03-13 12:53:19 -0700647 const uint8_t* getValue() const {
Kenny Roota91203b2012-02-15 15:00:46 -0800648 return mBlob.value;
649 }
650
Kenny Root51878182012-03-13 12:53:19 -0700651 int32_t getLength() const {
Kenny Roota91203b2012-02-15 15:00:46 -0800652 return mBlob.length;
653 }
654
Kenny Root51878182012-03-13 12:53:19 -0700655 const uint8_t* getInfo() const {
656 return mBlob.value + mBlob.length;
657 }
658
659 uint8_t getInfoLength() const {
Kenny Roota91203b2012-02-15 15:00:46 -0800660 return mBlob.info;
661 }
662
Kenny Root822c3a92012-03-23 16:34:39 -0700663 uint8_t getVersion() const {
664 return mBlob.version;
665 }
666
Kenny Rootf9119d62013-04-03 09:22:15 -0700667 bool isEncrypted() const {
668 if (mBlob.version < 2) {
669 return true;
670 }
671
672 return mBlob.flags & KEYSTORE_FLAG_ENCRYPTED;
673 }
674
675 void setEncrypted(bool encrypted) {
676 if (encrypted) {
677 mBlob.flags |= KEYSTORE_FLAG_ENCRYPTED;
678 } else {
679 mBlob.flags &= ~KEYSTORE_FLAG_ENCRYPTED;
680 }
681 }
682
Kenny Root17208e02013-09-04 13:56:03 -0700683 bool isFallback() const {
684 return mBlob.flags & KEYSTORE_FLAG_FALLBACK;
685 }
686
687 void setFallback(bool fallback) {
688 if (fallback) {
689 mBlob.flags |= KEYSTORE_FLAG_FALLBACK;
690 } else {
691 mBlob.flags &= ~KEYSTORE_FLAG_FALLBACK;
692 }
693 }
694
Kenny Root822c3a92012-03-23 16:34:39 -0700695 void setVersion(uint8_t version) {
696 mBlob.version = version;
697 }
698
699 BlobType getType() const {
700 return BlobType(mBlob.type);
701 }
702
703 void setType(BlobType type) {
704 mBlob.type = uint8_t(type);
705 }
706
Kenny Rootf9119d62013-04-03 09:22:15 -0700707 ResponseCode writeBlob(const char* filename, AES_KEY *aes_key, State state, Entropy* entropy) {
708 ALOGV("writing blob %s", filename);
709 if (isEncrypted()) {
710 if (state != STATE_NO_ERROR) {
711 ALOGD("couldn't insert encrypted blob while not unlocked");
712 return LOCKED;
713 }
714
715 if (!entropy->generate_random_data(mBlob.vector, AES_BLOCK_SIZE)) {
716 ALOGW("Could not read random data for: %s", filename);
717 return SYSTEM_ERROR;
718 }
Kenny Roota91203b2012-02-15 15:00:46 -0800719 }
720
721 // data includes the value and the value's length
722 size_t dataLength = mBlob.length + sizeof(mBlob.length);
723 // pad data to the AES_BLOCK_SIZE
724 size_t digestedLength = ((dataLength + AES_BLOCK_SIZE - 1)
725 / AES_BLOCK_SIZE * AES_BLOCK_SIZE);
726 // encrypted data includes the digest value
727 size_t encryptedLength = digestedLength + MD5_DIGEST_LENGTH;
728 // move info after space for padding
729 memmove(&mBlob.encrypted[encryptedLength], &mBlob.value[mBlob.length], mBlob.info);
730 // zero padding area
731 memset(mBlob.value + mBlob.length, 0, digestedLength - dataLength);
732
733 mBlob.length = htonl(mBlob.length);
Kenny Roota91203b2012-02-15 15:00:46 -0800734
Kenny Rootf9119d62013-04-03 09:22:15 -0700735 if (isEncrypted()) {
736 MD5(mBlob.digested, digestedLength, mBlob.digest);
Kenny Roota91203b2012-02-15 15:00:46 -0800737
Kenny Rootf9119d62013-04-03 09:22:15 -0700738 uint8_t vector[AES_BLOCK_SIZE];
739 memcpy(vector, mBlob.vector, AES_BLOCK_SIZE);
740 AES_cbc_encrypt(mBlob.encrypted, mBlob.encrypted, encryptedLength,
741 aes_key, vector, AES_ENCRYPT);
742 }
743
Kenny Roota91203b2012-02-15 15:00:46 -0800744 size_t headerLength = (mBlob.encrypted - (uint8_t*) &mBlob);
745 size_t fileLength = encryptedLength + headerLength + mBlob.info;
746
747 const char* tmpFileName = ".tmp";
Kenny Root150ca932012-11-14 14:29:02 -0800748 int out = TEMP_FAILURE_RETRY(open(tmpFileName,
749 O_WRONLY | O_TRUNC | O_CREAT, S_IRUSR | S_IWUSR));
750 if (out < 0) {
751 ALOGW("could not open file: %s: %s", tmpFileName, strerror(errno));
Kenny Roota91203b2012-02-15 15:00:46 -0800752 return SYSTEM_ERROR;
753 }
754 size_t writtenBytes = writeFully(out, (uint8_t*) &mBlob, fileLength);
755 if (close(out) != 0) {
756 return SYSTEM_ERROR;
757 }
758 if (writtenBytes != fileLength) {
Kenny Root150ca932012-11-14 14:29:02 -0800759 ALOGW("blob not fully written %zu != %zu", writtenBytes, fileLength);
Kenny Roota91203b2012-02-15 15:00:46 -0800760 unlink(tmpFileName);
761 return SYSTEM_ERROR;
762 }
Kenny Root150ca932012-11-14 14:29:02 -0800763 if (rename(tmpFileName, filename) == -1) {
764 ALOGW("could not rename blob to %s: %s", filename, strerror(errno));
765 return SYSTEM_ERROR;
766 }
767 return NO_ERROR;
Kenny Roota91203b2012-02-15 15:00:46 -0800768 }
769
Kenny Rootf9119d62013-04-03 09:22:15 -0700770 ResponseCode readBlob(const char* filename, AES_KEY *aes_key, State state) {
771 ALOGV("reading blob %s", filename);
Kenny Root150ca932012-11-14 14:29:02 -0800772 int in = TEMP_FAILURE_RETRY(open(filename, O_RDONLY));
773 if (in < 0) {
Kenny Roota91203b2012-02-15 15:00:46 -0800774 return (errno == ENOENT) ? KEY_NOT_FOUND : SYSTEM_ERROR;
775 }
776 // fileLength may be less than sizeof(mBlob) since the in
777 // memory version has extra padding to tolerate rounding up to
778 // the AES_BLOCK_SIZE
779 size_t fileLength = readFully(in, (uint8_t*) &mBlob, sizeof(mBlob));
780 if (close(in) != 0) {
781 return SYSTEM_ERROR;
782 }
Kenny Rootf9119d62013-04-03 09:22:15 -0700783
Chad Brubakera9a17ee2015-07-17 13:43:24 -0700784 if (fileLength == 0) {
785 return VALUE_CORRUPTED;
786 }
787
Kenny Rootf9119d62013-04-03 09:22:15 -0700788 if (isEncrypted() && (state != STATE_NO_ERROR)) {
789 return LOCKED;
790 }
791
Kenny Roota91203b2012-02-15 15:00:46 -0800792 size_t headerLength = (mBlob.encrypted - (uint8_t*) &mBlob);
793 if (fileLength < headerLength) {
794 return VALUE_CORRUPTED;
795 }
796
797 ssize_t encryptedLength = fileLength - (headerLength + mBlob.info);
Kenny Rootf9119d62013-04-03 09:22:15 -0700798 if (encryptedLength < 0) {
Kenny Roota91203b2012-02-15 15:00:46 -0800799 return VALUE_CORRUPTED;
800 }
Kenny Rootf9119d62013-04-03 09:22:15 -0700801
802 ssize_t digestedLength;
803 if (isEncrypted()) {
804 if (encryptedLength % AES_BLOCK_SIZE != 0) {
805 return VALUE_CORRUPTED;
806 }
807
808 AES_cbc_encrypt(mBlob.encrypted, mBlob.encrypted, encryptedLength, aes_key,
809 mBlob.vector, AES_DECRYPT);
810 digestedLength = encryptedLength - MD5_DIGEST_LENGTH;
811 uint8_t computedDigest[MD5_DIGEST_LENGTH];
812 MD5(mBlob.digested, digestedLength, computedDigest);
813 if (memcmp(mBlob.digest, computedDigest, MD5_DIGEST_LENGTH) != 0) {
814 return VALUE_CORRUPTED;
815 }
816 } else {
817 digestedLength = encryptedLength;
Kenny Roota91203b2012-02-15 15:00:46 -0800818 }
819
820 ssize_t maxValueLength = digestedLength - sizeof(mBlob.length);
821 mBlob.length = ntohl(mBlob.length);
822 if (mBlob.length < 0 || mBlob.length > maxValueLength) {
823 return VALUE_CORRUPTED;
824 }
825 if (mBlob.info != 0) {
826 // move info from after padding to after data
827 memmove(&mBlob.value[mBlob.length], &mBlob.value[maxValueLength], mBlob.info);
828 }
Kenny Root07438c82012-11-02 15:41:02 -0700829 return ::NO_ERROR;
Kenny Roota91203b2012-02-15 15:00:46 -0800830 }
831
832private:
833 struct blob mBlob;
834};
835
Kenny Root655b9582013-04-04 08:37:42 -0700836class UserState {
Kenny Roota91203b2012-02-15 15:00:46 -0800837public:
Kenny Root655b9582013-04-04 08:37:42 -0700838 UserState(uid_t userId) : mUserId(userId), mRetry(MAX_RETRY) {
839 asprintf(&mUserDir, "user_%u", mUserId);
840 asprintf(&mMasterKeyFile, "%s/.masterkey", mUserDir);
841 }
842
843 ~UserState() {
844 free(mUserDir);
845 free(mMasterKeyFile);
846 }
847
848 bool initialize() {
849 if ((mkdir(mUserDir, S_IRUSR | S_IWUSR | S_IXUSR) < 0) && (errno != EEXIST)) {
850 ALOGE("Could not create directory '%s'", mUserDir);
851 return false;
852 }
853
854 if (access(mMasterKeyFile, R_OK) == 0) {
Kenny Roota91203b2012-02-15 15:00:46 -0800855 setState(STATE_LOCKED);
856 } else {
857 setState(STATE_UNINITIALIZED);
858 }
Kenny Root70e3a862012-02-15 17:20:23 -0800859
Kenny Root655b9582013-04-04 08:37:42 -0700860 return true;
861 }
862
863 uid_t getUserId() const {
864 return mUserId;
865 }
866
867 const char* getUserDirName() const {
868 return mUserDir;
869 }
870
871 const char* getMasterKeyFileName() const {
872 return mMasterKeyFile;
873 }
874
875 void setState(State state) {
876 mState = state;
877 if (mState == STATE_NO_ERROR || mState == STATE_UNINITIALIZED) {
878 mRetry = MAX_RETRY;
879 }
Kenny Roota91203b2012-02-15 15:00:46 -0800880 }
881
Kenny Root51878182012-03-13 12:53:19 -0700882 State getState() const {
Kenny Roota91203b2012-02-15 15:00:46 -0800883 return mState;
884 }
885
Kenny Root51878182012-03-13 12:53:19 -0700886 int8_t getRetry() const {
Kenny Roota91203b2012-02-15 15:00:46 -0800887 return mRetry;
888 }
889
Kenny Root655b9582013-04-04 08:37:42 -0700890 void zeroizeMasterKeysInMemory() {
891 memset(mMasterKey, 0, sizeof(mMasterKey));
892 memset(mSalt, 0, sizeof(mSalt));
893 memset(&mMasterKeyEncryption, 0, sizeof(mMasterKeyEncryption));
894 memset(&mMasterKeyDecryption, 0, sizeof(mMasterKeyDecryption));
Kenny Root70e3a862012-02-15 17:20:23 -0800895 }
896
Chad Brubaker96d6d782015-05-07 10:19:40 -0700897 bool deleteMasterKey() {
898 setState(STATE_UNINITIALIZED);
899 zeroizeMasterKeysInMemory();
900 return unlink(mMasterKeyFile) == 0 || errno == ENOENT;
901 }
902
Kenny Root655b9582013-04-04 08:37:42 -0700903 ResponseCode initialize(const android::String8& pw, Entropy* entropy) {
904 if (!generateMasterKey(entropy)) {
Kenny Roota91203b2012-02-15 15:00:46 -0800905 return SYSTEM_ERROR;
906 }
Kenny Root655b9582013-04-04 08:37:42 -0700907 ResponseCode response = writeMasterKey(pw, entropy);
Kenny Roota91203b2012-02-15 15:00:46 -0800908 if (response != NO_ERROR) {
909 return response;
910 }
911 setupMasterKeys();
Kenny Root07438c82012-11-02 15:41:02 -0700912 return ::NO_ERROR;
Kenny Roota91203b2012-02-15 15:00:46 -0800913 }
914
Robin Lee4e865752014-08-19 17:37:55 +0100915 ResponseCode copyMasterKey(UserState* src) {
916 if (mState != STATE_UNINITIALIZED) {
917 return ::SYSTEM_ERROR;
918 }
919 if (src->getState() != STATE_NO_ERROR) {
920 return ::SYSTEM_ERROR;
921 }
922 memcpy(mMasterKey, src->mMasterKey, MASTER_KEY_SIZE_BYTES);
923 setupMasterKeys();
Chad Brubaker410ba592015-09-09 20:34:09 -0700924 return copyMasterKeyFile(src);
925 }
926
927 ResponseCode copyMasterKeyFile(UserState* src) {
928 /* Copy the master key file to the new user.
929 * Unfortunately we don't have the src user's password so we cannot
930 * generate a new file with a new salt.
931 */
932 int in = TEMP_FAILURE_RETRY(open(src->getMasterKeyFileName(), O_RDONLY));
933 if (in < 0) {
934 return ::SYSTEM_ERROR;
935 }
936 blob rawBlob;
937 size_t length = readFully(in, (uint8_t*) &rawBlob, sizeof(rawBlob));
938 if (close(in) != 0) {
939 return ::SYSTEM_ERROR;
940 }
941 int out = TEMP_FAILURE_RETRY(open(mMasterKeyFile,
942 O_WRONLY | O_TRUNC | O_CREAT, S_IRUSR | S_IWUSR));
943 if (out < 0) {
944 return ::SYSTEM_ERROR;
945 }
946 size_t outLength = writeFully(out, (uint8_t*) &rawBlob, length);
947 if (close(out) != 0) {
948 return ::SYSTEM_ERROR;
949 }
950 if (outLength != length) {
951 ALOGW("blob not fully written %zu != %zu", outLength, length);
952 unlink(mMasterKeyFile);
953 return ::SYSTEM_ERROR;
954 }
955
Robin Lee4e865752014-08-19 17:37:55 +0100956 return ::NO_ERROR;
957 }
958
Kenny Root655b9582013-04-04 08:37:42 -0700959 ResponseCode writeMasterKey(const android::String8& pw, Entropy* entropy) {
Kenny Roota91203b2012-02-15 15:00:46 -0800960 uint8_t passwordKey[MASTER_KEY_SIZE_BYTES];
961 generateKeyFromPassword(passwordKey, MASTER_KEY_SIZE_BYTES, pw, mSalt);
962 AES_KEY passwordAesKey;
963 AES_set_encrypt_key(passwordKey, MASTER_KEY_SIZE_BITS, &passwordAesKey);
Kenny Root822c3a92012-03-23 16:34:39 -0700964 Blob masterKeyBlob(mMasterKey, sizeof(mMasterKey), mSalt, sizeof(mSalt), TYPE_MASTER_KEY);
Kenny Rootf9119d62013-04-03 09:22:15 -0700965 return masterKeyBlob.writeBlob(mMasterKeyFile, &passwordAesKey, STATE_NO_ERROR, entropy);
Kenny Roota91203b2012-02-15 15:00:46 -0800966 }
967
Kenny Root655b9582013-04-04 08:37:42 -0700968 ResponseCode readMasterKey(const android::String8& pw, Entropy* entropy) {
969 int in = TEMP_FAILURE_RETRY(open(mMasterKeyFile, O_RDONLY));
Kenny Root150ca932012-11-14 14:29:02 -0800970 if (in < 0) {
Kenny Roota91203b2012-02-15 15:00:46 -0800971 return SYSTEM_ERROR;
972 }
973
974 // we read the raw blob to just to get the salt to generate
975 // the AES key, then we create the Blob to use with decryptBlob
976 blob rawBlob;
977 size_t length = readFully(in, (uint8_t*) &rawBlob, sizeof(rawBlob));
978 if (close(in) != 0) {
979 return SYSTEM_ERROR;
980 }
981 // find salt at EOF if present, otherwise we have an old file
982 uint8_t* salt;
983 if (length > SALT_SIZE && rawBlob.info == SALT_SIZE) {
984 salt = (uint8_t*) &rawBlob + length - SALT_SIZE;
985 } else {
986 salt = NULL;
987 }
988 uint8_t passwordKey[MASTER_KEY_SIZE_BYTES];
989 generateKeyFromPassword(passwordKey, MASTER_KEY_SIZE_BYTES, pw, salt);
990 AES_KEY passwordAesKey;
991 AES_set_decrypt_key(passwordKey, MASTER_KEY_SIZE_BITS, &passwordAesKey);
992 Blob masterKeyBlob(rawBlob);
Kenny Rootf9119d62013-04-03 09:22:15 -0700993 ResponseCode response = masterKeyBlob.readBlob(mMasterKeyFile, &passwordAesKey,
994 STATE_NO_ERROR);
Kenny Roota91203b2012-02-15 15:00:46 -0800995 if (response == SYSTEM_ERROR) {
Kenny Rootf9119d62013-04-03 09:22:15 -0700996 return response;
Kenny Roota91203b2012-02-15 15:00:46 -0800997 }
998 if (response == NO_ERROR && masterKeyBlob.getLength() == MASTER_KEY_SIZE_BYTES) {
999 // if salt was missing, generate one and write a new master key file with the salt.
1000 if (salt == NULL) {
Kenny Root655b9582013-04-04 08:37:42 -07001001 if (!generateSalt(entropy)) {
Kenny Roota91203b2012-02-15 15:00:46 -08001002 return SYSTEM_ERROR;
1003 }
Kenny Root655b9582013-04-04 08:37:42 -07001004 response = writeMasterKey(pw, entropy);
Kenny Roota91203b2012-02-15 15:00:46 -08001005 }
1006 if (response == NO_ERROR) {
1007 memcpy(mMasterKey, masterKeyBlob.getValue(), MASTER_KEY_SIZE_BYTES);
1008 setupMasterKeys();
1009 }
1010 return response;
1011 }
1012 if (mRetry <= 0) {
1013 reset();
1014 return UNINITIALIZED;
1015 }
1016 --mRetry;
1017 switch (mRetry) {
1018 case 0: return WRONG_PASSWORD_0;
1019 case 1: return WRONG_PASSWORD_1;
1020 case 2: return WRONG_PASSWORD_2;
1021 case 3: return WRONG_PASSWORD_3;
1022 default: return WRONG_PASSWORD_3;
1023 }
1024 }
1025
Kenny Root655b9582013-04-04 08:37:42 -07001026 AES_KEY* getEncryptionKey() {
1027 return &mMasterKeyEncryption;
1028 }
1029
1030 AES_KEY* getDecryptionKey() {
1031 return &mMasterKeyDecryption;
1032 }
1033
Kenny Roota91203b2012-02-15 15:00:46 -08001034 bool reset() {
Kenny Root655b9582013-04-04 08:37:42 -07001035 DIR* dir = opendir(getUserDirName());
Kenny Roota91203b2012-02-15 15:00:46 -08001036 if (!dir) {
Chad Brubaker96d6d782015-05-07 10:19:40 -07001037 // If the directory doesn't exist then nothing to do.
1038 if (errno == ENOENT) {
1039 return true;
1040 }
Kenny Root655b9582013-04-04 08:37:42 -07001041 ALOGW("couldn't open user directory: %s", strerror(errno));
Kenny Roota91203b2012-02-15 15:00:46 -08001042 return false;
1043 }
Kenny Root655b9582013-04-04 08:37:42 -07001044
1045 struct dirent* file;
Kenny Roota91203b2012-02-15 15:00:46 -08001046 while ((file = readdir(dir)) != NULL) {
Chad Brubaker96d6d782015-05-07 10:19:40 -07001047 // skip . and ..
1048 if (!strcmp(".", file->d_name) || !strcmp("..", file->d_name)) {
Kenny Root655b9582013-04-04 08:37:42 -07001049 continue;
1050 }
1051
1052 unlinkat(dirfd(dir), file->d_name, 0);
Kenny Roota91203b2012-02-15 15:00:46 -08001053 }
1054 closedir(dir);
1055 return true;
1056 }
1057
Kenny Root655b9582013-04-04 08:37:42 -07001058private:
1059 static const int MASTER_KEY_SIZE_BYTES = 16;
1060 static const int MASTER_KEY_SIZE_BITS = MASTER_KEY_SIZE_BYTES * 8;
1061
1062 static const int MAX_RETRY = 4;
1063 static const size_t SALT_SIZE = 16;
1064
1065 void generateKeyFromPassword(uint8_t* key, ssize_t keySize, const android::String8& pw,
1066 uint8_t* salt) {
1067 size_t saltSize;
1068 if (salt != NULL) {
1069 saltSize = SALT_SIZE;
1070 } else {
1071 // pre-gingerbread used this hardwired salt, readMasterKey will rewrite these when found
1072 salt = (uint8_t*) "keystore";
1073 // sizeof = 9, not strlen = 8
1074 saltSize = sizeof("keystore");
1075 }
1076
1077 PKCS5_PBKDF2_HMAC_SHA1(reinterpret_cast<const char*>(pw.string()), pw.length(), salt,
1078 saltSize, 8192, keySize, key);
1079 }
1080
1081 bool generateSalt(Entropy* entropy) {
1082 return entropy->generate_random_data(mSalt, sizeof(mSalt));
1083 }
1084
1085 bool generateMasterKey(Entropy* entropy) {
1086 if (!entropy->generate_random_data(mMasterKey, sizeof(mMasterKey))) {
1087 return false;
1088 }
1089 if (!generateSalt(entropy)) {
1090 return false;
1091 }
1092 return true;
1093 }
1094
1095 void setupMasterKeys() {
1096 AES_set_encrypt_key(mMasterKey, MASTER_KEY_SIZE_BITS, &mMasterKeyEncryption);
1097 AES_set_decrypt_key(mMasterKey, MASTER_KEY_SIZE_BITS, &mMasterKeyDecryption);
1098 setState(STATE_NO_ERROR);
1099 }
1100
1101 uid_t mUserId;
1102
1103 char* mUserDir;
1104 char* mMasterKeyFile;
1105
1106 State mState;
1107 int8_t mRetry;
1108
1109 uint8_t mMasterKey[MASTER_KEY_SIZE_BYTES];
1110 uint8_t mSalt[SALT_SIZE];
1111
1112 AES_KEY mMasterKeyEncryption;
1113 AES_KEY mMasterKeyDecryption;
1114};
1115
1116typedef struct {
1117 uint32_t uid;
1118 const uint8_t* filename;
1119} grant_t;
1120
1121class KeyStore {
1122public:
Chad Brubaker67d2a502015-03-11 17:21:18 +00001123 KeyStore(Entropy* entropy, keymaster1_device_t* device, keymaster1_device_t* fallback)
Kenny Root655b9582013-04-04 08:37:42 -07001124 : mEntropy(entropy)
1125 , mDevice(device)
Chad Brubakerfc18edc2015-01-12 15:17:18 -08001126 , mFallbackDevice(fallback)
Kenny Root655b9582013-04-04 08:37:42 -07001127 {
1128 memset(&mMetaData, '\0', sizeof(mMetaData));
1129 }
1130
1131 ~KeyStore() {
1132 for (android::Vector<grant_t*>::iterator it(mGrants.begin());
1133 it != mGrants.end(); it++) {
1134 delete *it;
Kenny Root655b9582013-04-04 08:37:42 -07001135 }
haitao fangc35d4eb2013-12-06 11:34:49 +08001136 mGrants.clear();
Kenny Root655b9582013-04-04 08:37:42 -07001137
1138 for (android::Vector<UserState*>::iterator it(mMasterKeys.begin());
1139 it != mMasterKeys.end(); it++) {
1140 delete *it;
Kenny Root655b9582013-04-04 08:37:42 -07001141 }
haitao fangc35d4eb2013-12-06 11:34:49 +08001142 mMasterKeys.clear();
Kenny Root655b9582013-04-04 08:37:42 -07001143 }
1144
Chad Brubaker67d2a502015-03-11 17:21:18 +00001145 /**
1146 * Depending on the hardware keymaster version is this may return a
1147 * keymaster0_device_t* cast to a keymaster1_device_t*. All methods from
1148 * keymaster0 are safe to call, calls to keymaster1_device_t methods should
1149 * be guarded by a check on the device's version.
1150 */
1151 keymaster1_device_t *getDevice() const {
Kenny Root655b9582013-04-04 08:37:42 -07001152 return mDevice;
1153 }
1154
Chad Brubaker67d2a502015-03-11 17:21:18 +00001155 keymaster1_device_t *getFallbackDevice() const {
Chad Brubakerfc18edc2015-01-12 15:17:18 -08001156 return mFallbackDevice;
1157 }
1158
Chad Brubaker67d2a502015-03-11 17:21:18 +00001159 keymaster1_device_t *getDeviceForBlob(const Blob& blob) const {
Chad Brubakerfc18edc2015-01-12 15:17:18 -08001160 return blob.isFallback() ? mFallbackDevice: mDevice;
1161 }
1162
Kenny Root655b9582013-04-04 08:37:42 -07001163 ResponseCode initialize() {
1164 readMetaData();
1165 if (upgradeKeystore()) {
1166 writeMetaData();
1167 }
1168
1169 return ::NO_ERROR;
1170 }
1171
Chad Brubaker72593ee2015-05-12 10:42:00 -07001172 State getState(uid_t userId) {
1173 return getUserState(userId)->getState();
Kenny Root655b9582013-04-04 08:37:42 -07001174 }
1175
Chad Brubaker72593ee2015-05-12 10:42:00 -07001176 ResponseCode initializeUser(const android::String8& pw, uid_t userId) {
1177 UserState* userState = getUserState(userId);
Kenny Root655b9582013-04-04 08:37:42 -07001178 return userState->initialize(pw, mEntropy);
1179 }
1180
Chad Brubaker72593ee2015-05-12 10:42:00 -07001181 ResponseCode copyMasterKey(uid_t srcUser, uid_t dstUser) {
1182 UserState *userState = getUserState(dstUser);
1183 UserState *initState = getUserState(srcUser);
Robin Lee4e865752014-08-19 17:37:55 +01001184 return userState->copyMasterKey(initState);
1185 }
1186
Chad Brubaker72593ee2015-05-12 10:42:00 -07001187 ResponseCode writeMasterKey(const android::String8& pw, uid_t userId) {
1188 UserState* userState = getUserState(userId);
Kenny Root655b9582013-04-04 08:37:42 -07001189 return userState->writeMasterKey(pw, mEntropy);
1190 }
1191
Chad Brubaker72593ee2015-05-12 10:42:00 -07001192 ResponseCode readMasterKey(const android::String8& pw, uid_t userId) {
1193 UserState* userState = getUserState(userId);
Kenny Root655b9582013-04-04 08:37:42 -07001194 return userState->readMasterKey(pw, mEntropy);
1195 }
1196
1197 android::String8 getKeyName(const android::String8& keyName) {
Douglas Leunga77e8092013-06-13 16:34:43 -07001198 char encoded[encode_key_length(keyName) + 1]; // add 1 for null char
Kenny Root655b9582013-04-04 08:37:42 -07001199 encode_key(encoded, keyName);
1200 return android::String8(encoded);
1201 }
1202
1203 android::String8 getKeyNameForUid(const android::String8& keyName, uid_t uid) {
Douglas Leunga77e8092013-06-13 16:34:43 -07001204 char encoded[encode_key_length(keyName) + 1]; // add 1 for null char
Kenny Root655b9582013-04-04 08:37:42 -07001205 encode_key(encoded, keyName);
1206 return android::String8::format("%u_%s", uid, encoded);
1207 }
1208
1209 android::String8 getKeyNameForUidWithDir(const android::String8& keyName, uid_t uid) {
Douglas Leunga77e8092013-06-13 16:34:43 -07001210 char encoded[encode_key_length(keyName) + 1]; // add 1 for null char
Kenny Root655b9582013-04-04 08:37:42 -07001211 encode_key(encoded, keyName);
Chad Brubaker72593ee2015-05-12 10:42:00 -07001212 return android::String8::format("%s/%u_%s", getUserStateByUid(uid)->getUserDirName(), uid,
Kenny Root655b9582013-04-04 08:37:42 -07001213 encoded);
1214 }
1215
Chad Brubaker96d6d782015-05-07 10:19:40 -07001216 /*
1217 * Delete entries owned by userId. If keepUnencryptedEntries is true
1218 * then only encrypted entries will be removed, otherwise all entries will
1219 * be removed.
1220 */
1221 void resetUser(uid_t userId, bool keepUnenryptedEntries) {
Robin Lee4b84fdc2014-09-24 11:56:57 +01001222 android::String8 prefix("");
1223 android::Vector<android::String16> aliases;
Chad Brubaker72593ee2015-05-12 10:42:00 -07001224 UserState* userState = getUserState(userId);
Chad Brubakere6c3bfa2015-05-12 15:18:26 -07001225 if (list(prefix, &aliases, userId) != ::NO_ERROR) {
Chad Brubaker96d6d782015-05-07 10:19:40 -07001226 return;
1227 }
Robin Lee4b84fdc2014-09-24 11:56:57 +01001228 for (uint32_t i = 0; i < aliases.size(); i++) {
1229 android::String8 filename(aliases[i]);
1230 filename = android::String8::format("%s/%s", userState->getUserDirName(),
Chad Brubaker96d6d782015-05-07 10:19:40 -07001231 getKeyName(filename).string());
1232 bool shouldDelete = true;
1233 if (keepUnenryptedEntries) {
1234 Blob blob;
Chad Brubaker72593ee2015-05-12 10:42:00 -07001235 ResponseCode rc = get(filename, &blob, ::TYPE_ANY, userId);
Robin Lee4b84fdc2014-09-24 11:56:57 +01001236
Chad Brubaker96d6d782015-05-07 10:19:40 -07001237 /* get can fail if the blob is encrypted and the state is
1238 * not unlocked, only skip deleting blobs that were loaded and
1239 * who are not encrypted. If there are blobs we fail to read for
1240 * other reasons err on the safe side and delete them since we
1241 * can't tell if they're encrypted.
1242 */
1243 shouldDelete = !(rc == ::NO_ERROR && !blob.isEncrypted());
1244 }
1245 if (shouldDelete) {
Chad Brubaker72593ee2015-05-12 10:42:00 -07001246 del(filename, ::TYPE_ANY, userId);
Chad Brubaker96d6d782015-05-07 10:19:40 -07001247 }
1248 }
1249 if (!userState->deleteMasterKey()) {
1250 ALOGE("Failed to delete user %d's master key", userId);
1251 }
1252 if (!keepUnenryptedEntries) {
1253 if(!userState->reset()) {
1254 ALOGE("Failed to remove user %d's directory", userId);
1255 }
1256 }
Kenny Root655b9582013-04-04 08:37:42 -07001257 }
1258
Chad Brubaker72593ee2015-05-12 10:42:00 -07001259 bool isEmpty(uid_t userId) const {
1260 const UserState* userState = getUserState(userId);
Chad Brubaker96d6d782015-05-07 10:19:40 -07001261 if (userState == NULL) {
Kenny Root655b9582013-04-04 08:37:42 -07001262 return true;
1263 }
1264
1265 DIR* dir = opendir(userState->getUserDirName());
Kenny Roota91203b2012-02-15 15:00:46 -08001266 if (!dir) {
1267 return true;
1268 }
Kenny Root31e27462014-09-10 11:28:03 -07001269
Kenny Roota91203b2012-02-15 15:00:46 -08001270 bool result = true;
Kenny Root31e27462014-09-10 11:28:03 -07001271 struct dirent* file;
Kenny Roota91203b2012-02-15 15:00:46 -08001272 while ((file = readdir(dir)) != NULL) {
Kenny Root655b9582013-04-04 08:37:42 -07001273 // We only care about files.
1274 if (file->d_type != DT_REG) {
1275 continue;
1276 }
1277
1278 // Skip anything that starts with a "."
1279 if (file->d_name[0] == '.') {
1280 continue;
1281 }
1282
Kenny Root31e27462014-09-10 11:28:03 -07001283 result = false;
1284 break;
Kenny Roota91203b2012-02-15 15:00:46 -08001285 }
1286 closedir(dir);
1287 return result;
1288 }
1289
Chad Brubaker72593ee2015-05-12 10:42:00 -07001290 void lock(uid_t userId) {
1291 UserState* userState = getUserState(userId);
Kenny Root655b9582013-04-04 08:37:42 -07001292 userState->zeroizeMasterKeysInMemory();
1293 userState->setState(STATE_LOCKED);
Kenny Roota91203b2012-02-15 15:00:46 -08001294 }
1295
Chad Brubaker72593ee2015-05-12 10:42:00 -07001296 ResponseCode get(const char* filename, Blob* keyBlob, const BlobType type, uid_t userId) {
1297 UserState* userState = getUserState(userId);
Kenny Rootf9119d62013-04-03 09:22:15 -07001298 ResponseCode rc = keyBlob->readBlob(filename, userState->getDecryptionKey(),
1299 userState->getState());
Kenny Root822c3a92012-03-23 16:34:39 -07001300 if (rc != NO_ERROR) {
1301 return rc;
1302 }
1303
1304 const uint8_t version = keyBlob->getVersion();
Kenny Root07438c82012-11-02 15:41:02 -07001305 if (version < CURRENT_BLOB_VERSION) {
Kenny Rootcfeae072013-04-04 08:39:57 -07001306 /* If we upgrade the key, we need to write it to disk again. Then
1307 * it must be read it again since the blob is encrypted each time
1308 * it's written.
1309 */
Chad Brubaker72593ee2015-05-12 10:42:00 -07001310 if (upgradeBlob(filename, keyBlob, version, type, userId)) {
1311 if ((rc = this->put(filename, keyBlob, userId)) != NO_ERROR
Kenny Rootf9119d62013-04-03 09:22:15 -07001312 || (rc = keyBlob->readBlob(filename, userState->getDecryptionKey(),
1313 userState->getState())) != NO_ERROR) {
Kenny Rootcfeae072013-04-04 08:39:57 -07001314 return rc;
1315 }
1316 }
Kenny Root822c3a92012-03-23 16:34:39 -07001317 }
1318
Kenny Root17208e02013-09-04 13:56:03 -07001319 /*
1320 * This will upgrade software-backed keys to hardware-backed keys when
1321 * the HAL for the device supports the newer key types.
1322 */
1323 if (rc == NO_ERROR && type == TYPE_KEY_PAIR
1324 && mDevice->common.module->module_api_version >= KEYMASTER_MODULE_API_VERSION_0_2
1325 && keyBlob->isFallback()) {
1326 ResponseCode imported = importKey(keyBlob->getValue(), keyBlob->getLength(), filename,
Chad Brubaker72593ee2015-05-12 10:42:00 -07001327 userId, keyBlob->isEncrypted() ? KEYSTORE_FLAG_ENCRYPTED : KEYSTORE_FLAG_NONE);
Kenny Root17208e02013-09-04 13:56:03 -07001328
1329 // The HAL allowed the import, reget the key to have the "fresh"
1330 // version.
1331 if (imported == NO_ERROR) {
Chad Brubaker72593ee2015-05-12 10:42:00 -07001332 rc = get(filename, keyBlob, TYPE_KEY_PAIR, userId);
Kenny Root17208e02013-09-04 13:56:03 -07001333 }
1334 }
1335
Chad Brubaker3a7d9e62015-06-04 15:01:46 -07001336 // Keymaster 0.3 keys are valid keymaster 1.0 keys, so silently upgrade.
1337 if (keyBlob->getType() == TYPE_KEY_PAIR) {
Chad Brubaker3cc40122015-06-04 13:49:44 -07001338 keyBlob->setType(TYPE_KEYMASTER_10);
Chad Brubaker3a7d9e62015-06-04 15:01:46 -07001339 rc = this->put(filename, keyBlob, userId);
Chad Brubaker3cc40122015-06-04 13:49:44 -07001340 }
1341
Kenny Rootd53bc922013-03-21 14:10:15 -07001342 if (type != TYPE_ANY && keyBlob->getType() != type) {
Kenny Root822c3a92012-03-23 16:34:39 -07001343 ALOGW("key found but type doesn't match: %d vs %d", keyBlob->getType(), type);
1344 return KEY_NOT_FOUND;
1345 }
1346
1347 return rc;
Kenny Roota91203b2012-02-15 15:00:46 -08001348 }
1349
Chad Brubaker72593ee2015-05-12 10:42:00 -07001350 ResponseCode put(const char* filename, Blob* keyBlob, uid_t userId) {
1351 UserState* userState = getUserState(userId);
Kenny Rootf9119d62013-04-03 09:22:15 -07001352 return keyBlob->writeBlob(filename, userState->getEncryptionKey(), userState->getState(),
1353 mEntropy);
Kenny Roota91203b2012-02-15 15:00:46 -08001354 }
1355
Chad Brubaker72593ee2015-05-12 10:42:00 -07001356 ResponseCode del(const char *filename, const BlobType type, uid_t userId) {
Robin Lee4b84fdc2014-09-24 11:56:57 +01001357 Blob keyBlob;
Chad Brubaker72593ee2015-05-12 10:42:00 -07001358 ResponseCode rc = get(filename, &keyBlob, type, userId);
Chad Brubakera9a17ee2015-07-17 13:43:24 -07001359 if (rc == ::VALUE_CORRUPTED) {
1360 // The file is corrupt, the best we can do is rm it.
1361 return (unlink(filename) && errno != ENOENT) ? ::SYSTEM_ERROR : ::NO_ERROR;
1362 }
Robin Lee4b84fdc2014-09-24 11:56:57 +01001363 if (rc != ::NO_ERROR) {
1364 return rc;
1365 }
1366
1367 if (keyBlob.getType() == ::TYPE_KEY_PAIR) {
Shawn Willden55268b52015-07-28 11:06:00 -06001368 // A device doesn't have to implement delete_key.
1369 if (mDevice->delete_key != NULL && !keyBlob.isFallback()) {
1370 keymaster_key_blob_t blob = {keyBlob.getValue(),
1371 static_cast<size_t>(keyBlob.getLength())};
1372 if (mDevice->delete_key(mDevice, &blob)) {
Robin Lee4b84fdc2014-09-24 11:56:57 +01001373 rc = ::SYSTEM_ERROR;
1374 }
1375 }
1376 }
Chad Brubaker17d68b92015-02-05 22:04:16 -08001377 if (keyBlob.getType() == ::TYPE_KEYMASTER_10) {
1378 keymaster1_device_t* dev = getDeviceForBlob(keyBlob);
1379 if (dev->delete_key) {
1380 keymaster_key_blob_t blob;
1381 blob.key_material = keyBlob.getValue();
1382 blob.key_material_size = keyBlob.getLength();
1383 dev->delete_key(dev, &blob);
1384 }
1385 }
Robin Lee4b84fdc2014-09-24 11:56:57 +01001386 if (rc != ::NO_ERROR) {
1387 return rc;
1388 }
1389
1390 return (unlink(filename) && errno != ENOENT) ? ::SYSTEM_ERROR : ::NO_ERROR;
1391 }
1392
Chad Brubakere6c3bfa2015-05-12 15:18:26 -07001393 ResponseCode list(const android::String8& prefix, android::Vector<android::String16> *matches,
Chad Brubaker72593ee2015-05-12 10:42:00 -07001394 uid_t userId) {
Robin Lee4b84fdc2014-09-24 11:56:57 +01001395
Chad Brubaker72593ee2015-05-12 10:42:00 -07001396 UserState* userState = getUserState(userId);
Robin Lee4b84fdc2014-09-24 11:56:57 +01001397 size_t n = prefix.length();
1398
1399 DIR* dir = opendir(userState->getUserDirName());
1400 if (!dir) {
1401 ALOGW("can't open directory for user: %s", strerror(errno));
1402 return ::SYSTEM_ERROR;
1403 }
1404
1405 struct dirent* file;
1406 while ((file = readdir(dir)) != NULL) {
1407 // We only care about files.
1408 if (file->d_type != DT_REG) {
1409 continue;
1410 }
1411
1412 // Skip anything that starts with a "."
1413 if (file->d_name[0] == '.') {
1414 continue;
1415 }
1416
1417 if (!strncmp(prefix.string(), file->d_name, n)) {
1418 const char* p = &file->d_name[n];
1419 size_t plen = strlen(p);
1420
1421 size_t extra = decode_key_length(p, plen);
1422 char *match = (char*) malloc(extra + 1);
1423 if (match != NULL) {
1424 decode_key(match, p, plen);
1425 matches->push(android::String16(match, extra));
1426 free(match);
1427 } else {
1428 ALOGW("could not allocate match of size %zd", extra);
1429 }
1430 }
1431 }
1432 closedir(dir);
1433 return ::NO_ERROR;
1434 }
1435
Kenny Root07438c82012-11-02 15:41:02 -07001436 void addGrant(const char* filename, uid_t granteeUid) {
Kenny Root655b9582013-04-04 08:37:42 -07001437 const grant_t* existing = getGrant(filename, granteeUid);
1438 if (existing == NULL) {
1439 grant_t* grant = new grant_t;
Kenny Root07438c82012-11-02 15:41:02 -07001440 grant->uid = granteeUid;
Brian Carlstroma8c703d2012-07-17 14:43:46 -07001441 grant->filename = reinterpret_cast<const uint8_t*>(strdup(filename));
Kenny Root655b9582013-04-04 08:37:42 -07001442 mGrants.add(grant);
Kenny Root70e3a862012-02-15 17:20:23 -08001443 }
1444 }
1445
Kenny Root07438c82012-11-02 15:41:02 -07001446 bool removeGrant(const char* filename, uid_t granteeUid) {
Kenny Root655b9582013-04-04 08:37:42 -07001447 for (android::Vector<grant_t*>::iterator it(mGrants.begin());
1448 it != mGrants.end(); it++) {
1449 grant_t* grant = *it;
1450 if (grant->uid == granteeUid
1451 && !strcmp(reinterpret_cast<const char*>(grant->filename), filename)) {
1452 mGrants.erase(it);
1453 return true;
1454 }
Kenny Root70e3a862012-02-15 17:20:23 -08001455 }
Kenny Root70e3a862012-02-15 17:20:23 -08001456 return false;
1457 }
1458
Brian Carlstroma8c703d2012-07-17 14:43:46 -07001459 bool hasGrant(const char* filename, const uid_t uid) const {
1460 return getGrant(filename, uid) != NULL;
Kenny Root70e3a862012-02-15 17:20:23 -08001461 }
1462
Chad Brubaker72593ee2015-05-12 10:42:00 -07001463 ResponseCode importKey(const uint8_t* key, size_t keyLen, const char* filename, uid_t userId,
Kenny Rootf9119d62013-04-03 09:22:15 -07001464 int32_t flags) {
Shawn Willden55268b52015-07-28 11:06:00 -06001465 Unique_PKCS8_PRIV_KEY_INFO pkcs8(d2i_PKCS8_PRIV_KEY_INFO(NULL, &key, keyLen));
1466 if (!pkcs8.get()) {
1467 return ::SYSTEM_ERROR;
1468 }
1469 Unique_EVP_PKEY pkey(EVP_PKCS82PKEY(pkcs8.get()));
1470 if (!pkey.get()) {
1471 return ::SYSTEM_ERROR;
1472 }
1473 int type = EVP_PKEY_type(pkey->type);
1474 android::KeymasterArguments params;
1475 add_legacy_key_authorizations(type, &params.params);
1476 switch (type) {
1477 case EVP_PKEY_RSA:
1478 params.params.push_back(keymaster_param_enum(KM_TAG_ALGORITHM, KM_ALGORITHM_RSA));
1479 break;
1480 case EVP_PKEY_EC:
1481 params.params.push_back(keymaster_param_enum(KM_TAG_ALGORITHM,
1482 KM_ALGORITHM_EC));
1483 break;
1484 default:
1485 ALOGW("Unsupported key type %d", type);
1486 return ::SYSTEM_ERROR;
Kenny Root822c3a92012-03-23 16:34:39 -07001487 }
1488
Shawn Willden55268b52015-07-28 11:06:00 -06001489 std::vector<keymaster_key_param_t> opParams(params.params);
1490 const keymaster_key_param_set_t inParams = {opParams.data(), opParams.size()};
1491 keymaster_blob_t input = {key, keyLen};
1492 keymaster_key_blob_t blob = {nullptr, 0};
Kenny Root17208e02013-09-04 13:56:03 -07001493 bool isFallback = false;
Shawn Willden55268b52015-07-28 11:06:00 -06001494 keymaster_error_t error = mDevice->import_key(mDevice, &inParams, KM_KEY_FORMAT_PKCS8,
1495 &input, &blob, NULL /* characteristics */);
1496 if (error != KM_ERROR_OK){
1497 ALOGE("Keymaster error %d importing key pair, falling back", error);
1498
Kenny Roota39da5a2014-09-25 13:07:24 -07001499 /*
Shawn Willden55268b52015-07-28 11:06:00 -06001500 * There should be no way to get here. Fallback shouldn't ever really happen
1501 * because the main device may be many (SW, KM0/SW hybrid, KM1/SW hybrid), but it must
1502 * provide full support of the API. In any case, we'll do the fallback just for
1503 * consistency... and I suppose to cover for broken HW implementations.
Kenny Roota39da5a2014-09-25 13:07:24 -07001504 */
Shawn Willden55268b52015-07-28 11:06:00 -06001505 error = mFallbackDevice->import_key(mFallbackDevice, &inParams, KM_KEY_FORMAT_PKCS8,
1506 &input, &blob, NULL /* characteristics */);
Kenny Roota39da5a2014-09-25 13:07:24 -07001507 isFallback = true;
Kenny Root17208e02013-09-04 13:56:03 -07001508
Shawn Willden55268b52015-07-28 11:06:00 -06001509 if (error) {
1510 ALOGE("Keymaster error while importing key pair with fallback: %d", error);
Kenny Root17208e02013-09-04 13:56:03 -07001511 return SYSTEM_ERROR;
1512 }
Kenny Root822c3a92012-03-23 16:34:39 -07001513 }
1514
Shawn Willden55268b52015-07-28 11:06:00 -06001515 Blob keyBlob(blob.key_material, blob.key_material_size, NULL, 0, TYPE_KEYMASTER_10);
1516 free(const_cast<uint8_t*>(blob.key_material));
Kenny Root822c3a92012-03-23 16:34:39 -07001517
Kenny Rootf9119d62013-04-03 09:22:15 -07001518 keyBlob.setEncrypted(flags & KEYSTORE_FLAG_ENCRYPTED);
Kenny Root17208e02013-09-04 13:56:03 -07001519 keyBlob.setFallback(isFallback);
Kenny Rootf9119d62013-04-03 09:22:15 -07001520
Chad Brubaker72593ee2015-05-12 10:42:00 -07001521 return put(filename, &keyBlob, userId);
Kenny Root822c3a92012-03-23 16:34:39 -07001522 }
1523
Kenny Root1b0e3932013-09-05 13:06:32 -07001524 bool isHardwareBacked(const android::String16& keyType) const {
1525 if (mDevice == NULL) {
1526 ALOGW("can't get keymaster device");
1527 return false;
1528 }
1529
1530 if (sRSAKeyType == keyType) {
1531 return (mDevice->flags & KEYMASTER_SOFTWARE_ONLY) == 0;
1532 } else {
1533 return (mDevice->flags & KEYMASTER_SOFTWARE_ONLY) == 0
1534 && (mDevice->common.module->module_api_version
1535 >= KEYMASTER_MODULE_API_VERSION_0_2);
1536 }
Kenny Root8ddf35a2013-03-29 11:15:50 -07001537 }
1538
Kenny Root655b9582013-04-04 08:37:42 -07001539 ResponseCode getKeyForName(Blob* keyBlob, const android::String8& keyName, const uid_t uid,
1540 const BlobType type) {
Kenny Root86b16e82013-09-09 11:15:54 -07001541 android::String8 filepath8(getKeyNameForUidWithDir(keyName, uid));
Chad Brubaker72593ee2015-05-12 10:42:00 -07001542 uid_t userId = get_user_id(uid);
Kenny Root655b9582013-04-04 08:37:42 -07001543
Chad Brubaker72593ee2015-05-12 10:42:00 -07001544 ResponseCode responseCode = get(filepath8.string(), keyBlob, type, userId);
Kenny Root655b9582013-04-04 08:37:42 -07001545 if (responseCode == NO_ERROR) {
1546 return responseCode;
1547 }
1548
1549 // If this is one of the legacy UID->UID mappings, use it.
1550 uid_t euid = get_keystore_euid(uid);
1551 if (euid != uid) {
Kenny Root86b16e82013-09-09 11:15:54 -07001552 filepath8 = getKeyNameForUidWithDir(keyName, euid);
Chad Brubaker72593ee2015-05-12 10:42:00 -07001553 responseCode = get(filepath8.string(), keyBlob, type, userId);
Kenny Root655b9582013-04-04 08:37:42 -07001554 if (responseCode == NO_ERROR) {
1555 return responseCode;
1556 }
1557 }
1558
1559 // They might be using a granted key.
Kenny Root86b16e82013-09-09 11:15:54 -07001560 android::String8 filename8 = getKeyName(keyName);
Kenny Root655b9582013-04-04 08:37:42 -07001561 char* end;
Kenny Root86b16e82013-09-09 11:15:54 -07001562 strtoul(filename8.string(), &end, 10);
Kenny Root655b9582013-04-04 08:37:42 -07001563 if (end[0] != '_' || end[1] == 0) {
1564 return KEY_NOT_FOUND;
1565 }
Chad Brubaker72593ee2015-05-12 10:42:00 -07001566 filepath8 = android::String8::format("%s/%s", getUserState(userId)->getUserDirName(),
Kenny Root86b16e82013-09-09 11:15:54 -07001567 filename8.string());
Kenny Root655b9582013-04-04 08:37:42 -07001568 if (!hasGrant(filepath8.string(), uid)) {
1569 return responseCode;
1570 }
1571
1572 // It is a granted key. Try to load it.
Chad Brubaker72593ee2015-05-12 10:42:00 -07001573 return get(filepath8.string(), keyBlob, type, userId);
Kenny Root655b9582013-04-04 08:37:42 -07001574 }
1575
1576 /**
1577 * Returns any existing UserState or creates it if it doesn't exist.
1578 */
Chad Brubaker72593ee2015-05-12 10:42:00 -07001579 UserState* getUserState(uid_t userId) {
Kenny Root655b9582013-04-04 08:37:42 -07001580 for (android::Vector<UserState*>::iterator it(mMasterKeys.begin());
1581 it != mMasterKeys.end(); it++) {
1582 UserState* state = *it;
1583 if (state->getUserId() == userId) {
1584 return state;
1585 }
1586 }
1587
1588 UserState* userState = new UserState(userId);
1589 if (!userState->initialize()) {
1590 /* There's not much we can do if initialization fails. Trying to
1591 * unlock the keystore for that user will fail as well, so any
1592 * subsequent request for this user will just return SYSTEM_ERROR.
1593 */
1594 ALOGE("User initialization failed for %u; subsuquent operations will fail", userId);
1595 }
1596 mMasterKeys.add(userState);
1597 return userState;
1598 }
1599
1600 /**
Chad Brubaker72593ee2015-05-12 10:42:00 -07001601 * Returns any existing UserState or creates it if it doesn't exist.
1602 */
1603 UserState* getUserStateByUid(uid_t uid) {
1604 uid_t userId = get_user_id(uid);
1605 return getUserState(userId);
1606 }
1607
1608 /**
Kenny Root655b9582013-04-04 08:37:42 -07001609 * Returns NULL if the UserState doesn't already exist.
1610 */
Chad Brubaker72593ee2015-05-12 10:42:00 -07001611 const UserState* getUserState(uid_t userId) const {
Kenny Root655b9582013-04-04 08:37:42 -07001612 for (android::Vector<UserState*>::const_iterator it(mMasterKeys.begin());
1613 it != mMasterKeys.end(); it++) {
1614 UserState* state = *it;
1615 if (state->getUserId() == userId) {
1616 return state;
1617 }
1618 }
1619
1620 return NULL;
1621 }
1622
Chad Brubaker72593ee2015-05-12 10:42:00 -07001623 /**
1624 * Returns NULL if the UserState doesn't already exist.
1625 */
1626 const UserState* getUserStateByUid(uid_t uid) const {
1627 uid_t userId = get_user_id(uid);
1628 return getUserState(userId);
1629 }
1630
Kenny Roota91203b2012-02-15 15:00:46 -08001631private:
Kenny Root655b9582013-04-04 08:37:42 -07001632 static const char* sOldMasterKey;
1633 static const char* sMetaDataFile;
Kenny Root1b0e3932013-09-05 13:06:32 -07001634 static const android::String16 sRSAKeyType;
Kenny Roota91203b2012-02-15 15:00:46 -08001635 Entropy* mEntropy;
1636
Chad Brubaker67d2a502015-03-11 17:21:18 +00001637 keymaster1_device_t* mDevice;
1638 keymaster1_device_t* mFallbackDevice;
Kenny Root70e3a862012-02-15 17:20:23 -08001639
Kenny Root655b9582013-04-04 08:37:42 -07001640 android::Vector<UserState*> mMasterKeys;
Kenny Roota91203b2012-02-15 15:00:46 -08001641
Kenny Root655b9582013-04-04 08:37:42 -07001642 android::Vector<grant_t*> mGrants;
Kenny Roota91203b2012-02-15 15:00:46 -08001643
Kenny Root655b9582013-04-04 08:37:42 -07001644 typedef struct {
1645 uint32_t version;
1646 } keystore_metadata_t;
Kenny Roota91203b2012-02-15 15:00:46 -08001647
Kenny Root655b9582013-04-04 08:37:42 -07001648 keystore_metadata_t mMetaData;
Kenny Root70e3a862012-02-15 17:20:23 -08001649
Kenny Root655b9582013-04-04 08:37:42 -07001650 const grant_t* getGrant(const char* filename, uid_t uid) const {
1651 for (android::Vector<grant_t*>::const_iterator it(mGrants.begin());
1652 it != mGrants.end(); it++) {
1653 grant_t* grant = *it;
Kenny Root70e3a862012-02-15 17:20:23 -08001654 if (grant->uid == uid
Kenny Root655b9582013-04-04 08:37:42 -07001655 && !strcmp(reinterpret_cast<const char*>(grant->filename), filename)) {
Kenny Root70e3a862012-02-15 17:20:23 -08001656 return grant;
1657 }
1658 }
Kenny Root70e3a862012-02-15 17:20:23 -08001659 return NULL;
1660 }
1661
Kenny Root822c3a92012-03-23 16:34:39 -07001662 /**
1663 * Upgrade code. This will upgrade the key from the current version
1664 * to whatever is newest.
1665 */
Kenny Root655b9582013-04-04 08:37:42 -07001666 bool upgradeBlob(const char* filename, Blob* blob, const uint8_t oldVersion,
1667 const BlobType type, uid_t uid) {
Kenny Root822c3a92012-03-23 16:34:39 -07001668 bool updated = false;
1669 uint8_t version = oldVersion;
1670
1671 /* From V0 -> V1: All old types were unknown */
1672 if (version == 0) {
1673 ALOGV("upgrading to version 1 and setting type %d", type);
1674
1675 blob->setType(type);
1676 if (type == TYPE_KEY_PAIR) {
Kenny Root655b9582013-04-04 08:37:42 -07001677 importBlobAsKey(blob, filename, uid);
Kenny Root822c3a92012-03-23 16:34:39 -07001678 }
1679 version = 1;
1680 updated = true;
1681 }
1682
Kenny Rootf9119d62013-04-03 09:22:15 -07001683 /* From V1 -> V2: All old keys were encrypted */
1684 if (version == 1) {
1685 ALOGV("upgrading to version 2");
1686
1687 blob->setEncrypted(true);
1688 version = 2;
1689 updated = true;
1690 }
1691
Kenny Root822c3a92012-03-23 16:34:39 -07001692 /*
1693 * If we've updated, set the key blob to the right version
1694 * and write it.
Kenny Rootcfeae072013-04-04 08:39:57 -07001695 */
Kenny Root822c3a92012-03-23 16:34:39 -07001696 if (updated) {
1697 ALOGV("updated and writing file %s", filename);
1698 blob->setVersion(version);
Kenny Root822c3a92012-03-23 16:34:39 -07001699 }
Kenny Rootcfeae072013-04-04 08:39:57 -07001700
1701 return updated;
Kenny Root822c3a92012-03-23 16:34:39 -07001702 }
1703
1704 /**
1705 * Takes a blob that is an PEM-encoded RSA key as a byte array and
1706 * converts it to a DER-encoded PKCS#8 for import into a keymaster.
1707 * Then it overwrites the original blob with the new blob
1708 * format that is returned from the keymaster.
1709 */
Kenny Root655b9582013-04-04 08:37:42 -07001710 ResponseCode importBlobAsKey(Blob* blob, const char* filename, uid_t uid) {
Kenny Root822c3a92012-03-23 16:34:39 -07001711 // We won't even write to the blob directly with this BIO, so const_cast is okay.
1712 Unique_BIO b(BIO_new_mem_buf(const_cast<uint8_t*>(blob->getValue()), blob->getLength()));
1713 if (b.get() == NULL) {
1714 ALOGE("Problem instantiating BIO");
1715 return SYSTEM_ERROR;
1716 }
1717
1718 Unique_EVP_PKEY pkey(PEM_read_bio_PrivateKey(b.get(), NULL, NULL, NULL));
1719 if (pkey.get() == NULL) {
1720 ALOGE("Couldn't read old PEM file");
1721 return SYSTEM_ERROR;
1722 }
1723
1724 Unique_PKCS8_PRIV_KEY_INFO pkcs8(EVP_PKEY2PKCS8(pkey.get()));
1725 int len = i2d_PKCS8_PRIV_KEY_INFO(pkcs8.get(), NULL);
1726 if (len < 0) {
1727 ALOGE("Couldn't measure PKCS#8 length");
1728 return SYSTEM_ERROR;
1729 }
1730
Kenny Root70c98892013-02-07 09:10:36 -08001731 UniquePtr<unsigned char[]> pkcs8key(new unsigned char[len]);
1732 uint8_t* tmp = pkcs8key.get();
Kenny Root822c3a92012-03-23 16:34:39 -07001733 if (i2d_PKCS8_PRIV_KEY_INFO(pkcs8.get(), &tmp) != len) {
1734 ALOGE("Couldn't convert to PKCS#8");
1735 return SYSTEM_ERROR;
1736 }
1737
Chad Brubaker72593ee2015-05-12 10:42:00 -07001738 ResponseCode rc = importKey(pkcs8key.get(), len, filename, get_user_id(uid),
Kenny Rootf9119d62013-04-03 09:22:15 -07001739 blob->isEncrypted() ? KEYSTORE_FLAG_ENCRYPTED : KEYSTORE_FLAG_NONE);
Kenny Root822c3a92012-03-23 16:34:39 -07001740 if (rc != NO_ERROR) {
1741 return rc;
1742 }
1743
Kenny Root655b9582013-04-04 08:37:42 -07001744 return get(filename, blob, TYPE_KEY_PAIR, uid);
1745 }
1746
1747 void readMetaData() {
1748 int in = TEMP_FAILURE_RETRY(open(sMetaDataFile, O_RDONLY));
1749 if (in < 0) {
1750 return;
1751 }
1752 size_t fileLength = readFully(in, (uint8_t*) &mMetaData, sizeof(mMetaData));
1753 if (fileLength != sizeof(mMetaData)) {
1754 ALOGI("Metadata file is %zd bytes (%zd experted); upgrade?", fileLength,
1755 sizeof(mMetaData));
1756 }
1757 close(in);
1758 }
1759
1760 void writeMetaData() {
1761 const char* tmpFileName = ".metadata.tmp";
1762 int out = TEMP_FAILURE_RETRY(open(tmpFileName,
1763 O_WRONLY | O_TRUNC | O_CREAT, S_IRUSR | S_IWUSR));
1764 if (out < 0) {
1765 ALOGE("couldn't write metadata file: %s", strerror(errno));
1766 return;
1767 }
1768 size_t fileLength = writeFully(out, (uint8_t*) &mMetaData, sizeof(mMetaData));
1769 if (fileLength != sizeof(mMetaData)) {
1770 ALOGI("Could only write %zd bytes to metadata file (%zd expected)", fileLength,
1771 sizeof(mMetaData));
1772 }
1773 close(out);
1774 rename(tmpFileName, sMetaDataFile);
1775 }
1776
1777 bool upgradeKeystore() {
1778 bool upgraded = false;
1779
1780 if (mMetaData.version == 0) {
Chad Brubaker72593ee2015-05-12 10:42:00 -07001781 UserState* userState = getUserStateByUid(0);
Kenny Root655b9582013-04-04 08:37:42 -07001782
1783 // Initialize first so the directory is made.
1784 userState->initialize();
1785
1786 // Migrate the old .masterkey file to user 0.
1787 if (access(sOldMasterKey, R_OK) == 0) {
1788 if (rename(sOldMasterKey, userState->getMasterKeyFileName()) < 0) {
1789 ALOGE("couldn't migrate old masterkey: %s", strerror(errno));
1790 return false;
1791 }
1792 }
1793
1794 // Initialize again in case we had a key.
1795 userState->initialize();
1796
1797 // Try to migrate existing keys.
1798 DIR* dir = opendir(".");
1799 if (!dir) {
1800 // Give up now; maybe we can upgrade later.
1801 ALOGE("couldn't open keystore's directory; something is wrong");
1802 return false;
1803 }
1804
1805 struct dirent* file;
1806 while ((file = readdir(dir)) != NULL) {
1807 // We only care about files.
1808 if (file->d_type != DT_REG) {
1809 continue;
1810 }
1811
1812 // Skip anything that starts with a "."
1813 if (file->d_name[0] == '.') {
1814 continue;
1815 }
1816
1817 // Find the current file's user.
1818 char* end;
1819 unsigned long thisUid = strtoul(file->d_name, &end, 10);
1820 if (end[0] != '_' || end[1] == 0) {
1821 continue;
1822 }
Chad Brubaker72593ee2015-05-12 10:42:00 -07001823 UserState* otherUser = getUserStateByUid(thisUid);
Kenny Root655b9582013-04-04 08:37:42 -07001824 if (otherUser->getUserId() != 0) {
1825 unlinkat(dirfd(dir), file->d_name, 0);
1826 }
1827
1828 // Rename the file into user directory.
1829 DIR* otherdir = opendir(otherUser->getUserDirName());
1830 if (otherdir == NULL) {
1831 ALOGW("couldn't open user directory for rename");
1832 continue;
1833 }
1834 if (renameat(dirfd(dir), file->d_name, dirfd(otherdir), file->d_name) < 0) {
1835 ALOGW("couldn't rename blob: %s: %s", file->d_name, strerror(errno));
1836 }
1837 closedir(otherdir);
1838 }
1839 closedir(dir);
1840
1841 mMetaData.version = 1;
1842 upgraded = true;
1843 }
1844
1845 return upgraded;
Kenny Root822c3a92012-03-23 16:34:39 -07001846 }
Kenny Roota91203b2012-02-15 15:00:46 -08001847};
1848
Kenny Root655b9582013-04-04 08:37:42 -07001849const char* KeyStore::sOldMasterKey = ".masterkey";
1850const char* KeyStore::sMetaDataFile = ".metadata";
Kenny Root70e3a862012-02-15 17:20:23 -08001851
Kenny Root1b0e3932013-09-05 13:06:32 -07001852const android::String16 KeyStore::sRSAKeyType("RSA");
1853
Kenny Root07438c82012-11-02 15:41:02 -07001854namespace android {
1855class KeyStoreProxy : public BnKeystoreService, public IBinder::DeathRecipient {
1856public:
1857 KeyStoreProxy(KeyStore* keyStore)
Chad Brubaker40a1a9b2015-02-20 14:08:13 -08001858 : mKeyStore(keyStore),
1859 mOperationMap(this)
Kenny Root07438c82012-11-02 15:41:02 -07001860 {
Kenny Roota91203b2012-02-15 15:00:46 -08001861 }
Kenny Roota91203b2012-02-15 15:00:46 -08001862
Chad Brubaker40a1a9b2015-02-20 14:08:13 -08001863 void binderDied(const wp<IBinder>& who) {
1864 auto operations = mOperationMap.getOperationsForToken(who.unsafe_get());
1865 for (auto token: operations) {
1866 abort(token);
1867 }
Kenny Root822c3a92012-03-23 16:34:39 -07001868 }
Kenny Roota91203b2012-02-15 15:00:46 -08001869
Chad Brubakere6c3bfa2015-05-12 15:18:26 -07001870 int32_t getState(int32_t userId) {
1871 if (!checkBinderPermission(P_GET_STATE)) {
Kenny Root07438c82012-11-02 15:41:02 -07001872 return ::PERMISSION_DENIED;
Kenny Roota91203b2012-02-15 15:00:46 -08001873 }
Kenny Roota91203b2012-02-15 15:00:46 -08001874
Chad Brubakere6c3bfa2015-05-12 15:18:26 -07001875 return mKeyStore->getState(userId);
Kenny Root298e7b12012-03-26 13:54:44 -07001876 }
1877
Kenny Root07438c82012-11-02 15:41:02 -07001878 int32_t get(const String16& name, uint8_t** item, size_t* itemLength) {
Chad Brubaker9489b792015-04-14 11:01:45 -07001879 if (!checkBinderPermission(P_GET)) {
Kenny Root07438c82012-11-02 15:41:02 -07001880 return ::PERMISSION_DENIED;
Kenny Roota91203b2012-02-15 15:00:46 -08001881 }
Kenny Root07438c82012-11-02 15:41:02 -07001882
Chad Brubaker9489b792015-04-14 11:01:45 -07001883 uid_t callingUid = IPCThreadState::self()->getCallingUid();
Kenny Root07438c82012-11-02 15:41:02 -07001884 String8 name8(name);
Kenny Root07438c82012-11-02 15:41:02 -07001885 Blob keyBlob;
Nick Kralevich66dbf672014-06-30 17:09:14 +00001886
Kenny Root655b9582013-04-04 08:37:42 -07001887 ResponseCode responseCode = mKeyStore->getKeyForName(&keyBlob, name8, callingUid,
Kenny Root49468902013-03-19 13:41:33 -07001888 TYPE_GENERIC);
Kenny Root07438c82012-11-02 15:41:02 -07001889 if (responseCode != ::NO_ERROR) {
1890 *item = NULL;
1891 *itemLength = 0;
1892 return responseCode;
Kenny Roota91203b2012-02-15 15:00:46 -08001893 }
Kenny Roota91203b2012-02-15 15:00:46 -08001894
Kenny Root07438c82012-11-02 15:41:02 -07001895 *item = (uint8_t*) malloc(keyBlob.getLength());
1896 memcpy(*item, keyBlob.getValue(), keyBlob.getLength());
1897 *itemLength = keyBlob.getLength();
Kenny Roota91203b2012-02-15 15:00:46 -08001898
Kenny Root07438c82012-11-02 15:41:02 -07001899 return ::NO_ERROR;
Kenny Root70e3a862012-02-15 17:20:23 -08001900 }
1901
Kenny Rootf9119d62013-04-03 09:22:15 -07001902 int32_t insert(const String16& name, const uint8_t* item, size_t itemLength, int targetUid,
1903 int32_t flags) {
Chad Brubaker9489b792015-04-14 11:01:45 -07001904 targetUid = getEffectiveUid(targetUid);
1905 int32_t result = checkBinderPermissionAndKeystoreState(P_INSERT, targetUid,
1906 flags & KEYSTORE_FLAG_ENCRYPTED);
1907 if (result != ::NO_ERROR) {
1908 return result;
Kenny Rootb88c3eb2013-02-13 14:43:43 -08001909 }
1910
Kenny Root07438c82012-11-02 15:41:02 -07001911 String8 name8(name);
Kenny Root655b9582013-04-04 08:37:42 -07001912 String8 filename(mKeyStore->getKeyNameForUidWithDir(name8, targetUid));
Kenny Root07438c82012-11-02 15:41:02 -07001913
1914 Blob keyBlob(item, itemLength, NULL, 0, ::TYPE_GENERIC);
Kenny Rootee8068b2013-10-07 09:49:15 -07001915 keyBlob.setEncrypted(flags & KEYSTORE_FLAG_ENCRYPTED);
1916
Chad Brubaker72593ee2015-05-12 10:42:00 -07001917 return mKeyStore->put(filename.string(), &keyBlob, get_user_id(targetUid));
Kenny Root70e3a862012-02-15 17:20:23 -08001918 }
1919
Kenny Root49468902013-03-19 13:41:33 -07001920 int32_t del(const String16& name, int targetUid) {
Chad Brubaker9489b792015-04-14 11:01:45 -07001921 targetUid = getEffectiveUid(targetUid);
1922 if (!checkBinderPermission(P_DELETE, targetUid)) {
Kenny Root07438c82012-11-02 15:41:02 -07001923 return ::PERMISSION_DENIED;
1924 }
Kenny Root07438c82012-11-02 15:41:02 -07001925 String8 name8(name);
Kenny Root655b9582013-04-04 08:37:42 -07001926 String8 filename(mKeyStore->getKeyNameForUidWithDir(name8, targetUid));
Chad Brubaker72593ee2015-05-12 10:42:00 -07001927 return mKeyStore->del(filename.string(), ::TYPE_ANY, get_user_id(targetUid));
Kenny Root70e3a862012-02-15 17:20:23 -08001928 }
1929
Kenny Root49468902013-03-19 13:41:33 -07001930 int32_t exist(const String16& name, int targetUid) {
Chad Brubaker9489b792015-04-14 11:01:45 -07001931 targetUid = getEffectiveUid(targetUid);
1932 if (!checkBinderPermission(P_EXIST, targetUid)) {
Kenny Rootb88c3eb2013-02-13 14:43:43 -08001933 return ::PERMISSION_DENIED;
1934 }
1935
Kenny Root07438c82012-11-02 15:41:02 -07001936 String8 name8(name);
Kenny Root655b9582013-04-04 08:37:42 -07001937 String8 filename(mKeyStore->getKeyNameForUidWithDir(name8, targetUid));
Kenny Root70e3a862012-02-15 17:20:23 -08001938
Kenny Root655b9582013-04-04 08:37:42 -07001939 if (access(filename.string(), R_OK) == -1) {
Kenny Root07438c82012-11-02 15:41:02 -07001940 return (errno != ENOENT) ? ::SYSTEM_ERROR : ::KEY_NOT_FOUND;
1941 }
1942 return ::NO_ERROR;
Kenny Root70e3a862012-02-15 17:20:23 -08001943 }
1944
Chad Brubakere6c3bfa2015-05-12 15:18:26 -07001945 int32_t list(const String16& prefix, int targetUid, Vector<String16>* matches) {
Chad Brubaker9489b792015-04-14 11:01:45 -07001946 targetUid = getEffectiveUid(targetUid);
Chad Brubakere6c3bfa2015-05-12 15:18:26 -07001947 if (!checkBinderPermission(P_LIST, targetUid)) {
Kenny Root07438c82012-11-02 15:41:02 -07001948 return ::PERMISSION_DENIED;
1949 }
Kenny Root07438c82012-11-02 15:41:02 -07001950 const String8 prefix8(prefix);
Kenny Root655b9582013-04-04 08:37:42 -07001951 String8 filename(mKeyStore->getKeyNameForUid(prefix8, targetUid));
Kenny Root70e3a862012-02-15 17:20:23 -08001952
Chad Brubakere6c3bfa2015-05-12 15:18:26 -07001953 if (mKeyStore->list(filename, matches, get_user_id(targetUid)) != ::NO_ERROR) {
Robin Lee4b84fdc2014-09-24 11:56:57 +01001954 return ::SYSTEM_ERROR;
Kenny Root9a53d3e2012-08-14 10:47:54 -07001955 }
Kenny Root07438c82012-11-02 15:41:02 -07001956 return ::NO_ERROR;
Kenny Root70e3a862012-02-15 17:20:23 -08001957 }
1958
Kenny Root07438c82012-11-02 15:41:02 -07001959 int32_t reset() {
Chad Brubaker9489b792015-04-14 11:01:45 -07001960 if (!checkBinderPermission(P_RESET)) {
Kenny Root07438c82012-11-02 15:41:02 -07001961 return ::PERMISSION_DENIED;
1962 }
1963
Chad Brubaker9489b792015-04-14 11:01:45 -07001964 uid_t callingUid = IPCThreadState::self()->getCallingUid();
Chad Brubaker96d6d782015-05-07 10:19:40 -07001965 mKeyStore->resetUser(get_user_id(callingUid), false);
1966 return ::NO_ERROR;
Kenny Root70e3a862012-02-15 17:20:23 -08001967 }
1968
Chad Brubaker96d6d782015-05-07 10:19:40 -07001969 int32_t onUserPasswordChanged(int32_t userId, const String16& password) {
Chad Brubaker9489b792015-04-14 11:01:45 -07001970 if (!checkBinderPermission(P_PASSWORD)) {
Kenny Root07438c82012-11-02 15:41:02 -07001971 return ::PERMISSION_DENIED;
1972 }
Kenny Root70e3a862012-02-15 17:20:23 -08001973
Kenny Root07438c82012-11-02 15:41:02 -07001974 const String8 password8(password);
Chad Brubaker96d6d782015-05-07 10:19:40 -07001975 // Flush the auth token table to prevent stale tokens from sticking
1976 // around.
1977 mAuthTokenTable.Clear();
1978
1979 if (password.size() == 0) {
1980 ALOGI("Secure lockscreen for user %d removed, deleting encrypted entries", userId);
Chad Brubaker72593ee2015-05-12 10:42:00 -07001981 mKeyStore->resetUser(userId, true);
Chad Brubaker96d6d782015-05-07 10:19:40 -07001982 return ::NO_ERROR;
1983 } else {
Chad Brubaker72593ee2015-05-12 10:42:00 -07001984 switch (mKeyStore->getState(userId)) {
Chad Brubaker96d6d782015-05-07 10:19:40 -07001985 case ::STATE_UNINITIALIZED: {
1986 // generate master key, encrypt with password, write to file,
1987 // initialize mMasterKey*.
Chad Brubaker72593ee2015-05-12 10:42:00 -07001988 return mKeyStore->initializeUser(password8, userId);
Chad Brubaker96d6d782015-05-07 10:19:40 -07001989 }
1990 case ::STATE_NO_ERROR: {
1991 // rewrite master key with new password.
Chad Brubaker72593ee2015-05-12 10:42:00 -07001992 return mKeyStore->writeMasterKey(password8, userId);
Chad Brubaker96d6d782015-05-07 10:19:40 -07001993 }
1994 case ::STATE_LOCKED: {
1995 ALOGE("Changing user %d's password while locked, clearing old encryption",
1996 userId);
Chad Brubaker72593ee2015-05-12 10:42:00 -07001997 mKeyStore->resetUser(userId, true);
1998 return mKeyStore->initializeUser(password8, userId);
Chad Brubaker96d6d782015-05-07 10:19:40 -07001999 }
Kenny Root07438c82012-11-02 15:41:02 -07002000 }
Chad Brubaker96d6d782015-05-07 10:19:40 -07002001 return ::SYSTEM_ERROR;
Kenny Root07438c82012-11-02 15:41:02 -07002002 }
Kenny Root70e3a862012-02-15 17:20:23 -08002003 }
2004
Chad Brubakerc0f031a2015-05-12 10:43:10 -07002005 int32_t onUserAdded(int32_t userId, int32_t parentId) {
2006 if (!checkBinderPermission(P_USER_CHANGED)) {
2007 return ::PERMISSION_DENIED;
2008 }
2009
2010 // Sanity check that the new user has an empty keystore.
2011 if (!mKeyStore->isEmpty(userId)) {
2012 ALOGW("New user %d's keystore not empty. Clearing old entries.", userId);
2013 }
2014 // Unconditionally clear the keystore, just to be safe.
2015 mKeyStore->resetUser(userId, false);
Chad Brubakerc0f031a2015-05-12 10:43:10 -07002016 if (parentId != -1) {
Chad Brubaker410ba592015-09-09 20:34:09 -07002017 // This profile must share the same master key password as the parent
2018 // profile. Because the password of the parent profile is not known
2019 // here, the best we can do is copy the parent's master key and master
2020 // key file. This makes this profile use the same master key as the
2021 // parent profile, forever.
Chad Brubakerc0f031a2015-05-12 10:43:10 -07002022 return mKeyStore->copyMasterKey(parentId, userId);
2023 } else {
2024 return ::NO_ERROR;
2025 }
2026 }
2027
2028 int32_t onUserRemoved(int32_t userId) {
2029 if (!checkBinderPermission(P_USER_CHANGED)) {
2030 return ::PERMISSION_DENIED;
2031 }
2032
2033 mKeyStore->resetUser(userId, false);
2034 return ::NO_ERROR;
2035 }
2036
Chad Brubakere6c3bfa2015-05-12 15:18:26 -07002037 int32_t lock(int32_t userId) {
Chad Brubaker9489b792015-04-14 11:01:45 -07002038 if (!checkBinderPermission(P_LOCK)) {
Kenny Root07438c82012-11-02 15:41:02 -07002039 return ::PERMISSION_DENIED;
2040 }
Kenny Root70e3a862012-02-15 17:20:23 -08002041
Chad Brubaker72593ee2015-05-12 10:42:00 -07002042 State state = mKeyStore->getState(userId);
Kenny Root9d45d1c2013-02-14 10:32:30 -08002043 if (state != ::STATE_NO_ERROR) {
Kenny Root07438c82012-11-02 15:41:02 -07002044 ALOGD("calling lock in state: %d", state);
2045 return state;
2046 }
2047
Chad Brubaker72593ee2015-05-12 10:42:00 -07002048 mKeyStore->lock(userId);
Kenny Root07438c82012-11-02 15:41:02 -07002049 return ::NO_ERROR;
Kenny Root70e3a862012-02-15 17:20:23 -08002050 }
2051
Chad Brubaker96d6d782015-05-07 10:19:40 -07002052 int32_t unlock(int32_t userId, const String16& pw) {
Chad Brubaker9489b792015-04-14 11:01:45 -07002053 if (!checkBinderPermission(P_UNLOCK)) {
Kenny Root07438c82012-11-02 15:41:02 -07002054 return ::PERMISSION_DENIED;
2055 }
2056
Chad Brubaker72593ee2015-05-12 10:42:00 -07002057 State state = mKeyStore->getState(userId);
Kenny Root9d45d1c2013-02-14 10:32:30 -08002058 if (state != ::STATE_LOCKED) {
Chad Brubaker410ba592015-09-09 20:34:09 -07002059 switch (state) {
2060 case ::STATE_NO_ERROR:
2061 ALOGI("calling unlock when already unlocked, ignoring.");
2062 break;
2063 case ::STATE_UNINITIALIZED:
2064 ALOGE("unlock called on uninitialized keystore.");
2065 break;
2066 default:
2067 ALOGE("unlock called on keystore in unknown state: %d", state);
2068 break;
2069 }
Kenny Root07438c82012-11-02 15:41:02 -07002070 return state;
2071 }
2072
2073 const String8 password8(pw);
Chad Brubaker96d6d782015-05-07 10:19:40 -07002074 // read master key, decrypt with password, initialize mMasterKey*.
Chad Brubaker72593ee2015-05-12 10:42:00 -07002075 return mKeyStore->readMasterKey(password8, userId);
Kenny Root70e3a862012-02-15 17:20:23 -08002076 }
2077
Chad Brubakere6c3bfa2015-05-12 15:18:26 -07002078 bool isEmpty(int32_t userId) {
2079 if (!checkBinderPermission(P_IS_EMPTY)) {
2080 return false;
Kenny Root07438c82012-11-02 15:41:02 -07002081 }
Kenny Root70e3a862012-02-15 17:20:23 -08002082
Chad Brubakere6c3bfa2015-05-12 15:18:26 -07002083 return mKeyStore->isEmpty(userId);
Kenny Root70e3a862012-02-15 17:20:23 -08002084 }
2085
Kenny Root96427ba2013-08-16 14:02:41 -07002086 int32_t generate(const String16& name, int32_t targetUid, int32_t keyType, int32_t keySize,
2087 int32_t flags, Vector<sp<KeystoreArg> >* args) {
Chad Brubaker9489b792015-04-14 11:01:45 -07002088 targetUid = getEffectiveUid(targetUid);
2089 int32_t result = checkBinderPermissionAndKeystoreState(P_INSERT, targetUid,
2090 flags & KEYSTORE_FLAG_ENCRYPTED);
2091 if (result != ::NO_ERROR) {
2092 return result;
Kenny Root07438c82012-11-02 15:41:02 -07002093 }
Kenny Root07438c82012-11-02 15:41:02 -07002094
Chad Brubaker3a7d9e62015-06-04 15:01:46 -07002095 KeymasterArguments params;
Shawn Willden55268b52015-07-28 11:06:00 -06002096 add_legacy_key_authorizations(keyType, &params.params);
Kenny Root07438c82012-11-02 15:41:02 -07002097
Chad Brubaker3a7d9e62015-06-04 15:01:46 -07002098 switch (keyType) {
2099 case EVP_PKEY_EC: {
2100 params.params.push_back(keymaster_param_enum(KM_TAG_ALGORITHM, KM_ALGORITHM_EC));
2101 if (keySize == -1) {
2102 keySize = EC_DEFAULT_KEY_SIZE;
2103 } else if (keySize < EC_MIN_KEY_SIZE || keySize > EC_MAX_KEY_SIZE) {
2104 ALOGI("invalid key size %d", keySize);
Kenny Root96427ba2013-08-16 14:02:41 -07002105 return ::SYSTEM_ERROR;
2106 }
Chad Brubaker3a7d9e62015-06-04 15:01:46 -07002107 params.params.push_back(keymaster_param_int(KM_TAG_KEY_SIZE, keySize));
2108 break;
Kenny Root96427ba2013-08-16 14:02:41 -07002109 }
Chad Brubaker3a7d9e62015-06-04 15:01:46 -07002110 case EVP_PKEY_RSA: {
2111 params.params.push_back(keymaster_param_enum(KM_TAG_ALGORITHM, KM_ALGORITHM_RSA));
2112 if (keySize == -1) {
2113 keySize = RSA_DEFAULT_KEY_SIZE;
2114 } else if (keySize < RSA_MIN_KEY_SIZE || keySize > RSA_MAX_KEY_SIZE) {
2115 ALOGI("invalid key size %d", keySize);
2116 return ::SYSTEM_ERROR;
Kenny Root96427ba2013-08-16 14:02:41 -07002117 }
Chad Brubaker3a7d9e62015-06-04 15:01:46 -07002118 params.params.push_back(keymaster_param_int(KM_TAG_KEY_SIZE, keySize));
2119 unsigned long exponent = RSA_DEFAULT_EXPONENT;
2120 if (args->size() > 1) {
2121 ALOGI("invalid number of arguments: %zu", args->size());
2122 return ::SYSTEM_ERROR;
2123 } else if (args->size() == 1) {
2124 sp<KeystoreArg> expArg = args->itemAt(0);
2125 if (expArg != NULL) {
2126 Unique_BIGNUM pubExpBn(
2127 BN_bin2bn(reinterpret_cast<const unsigned char*>(expArg->data()),
2128 expArg->size(), NULL));
2129 if (pubExpBn.get() == NULL) {
2130 ALOGI("Could not convert public exponent to BN");
2131 return ::SYSTEM_ERROR;
2132 }
2133 exponent = BN_get_word(pubExpBn.get());
2134 if (exponent == 0xFFFFFFFFL) {
2135 ALOGW("cannot represent public exponent as a long value");
2136 return ::SYSTEM_ERROR;
2137 }
2138 } else {
2139 ALOGW("public exponent not read");
2140 return ::SYSTEM_ERROR;
2141 }
2142 }
2143 params.params.push_back(keymaster_param_long(KM_TAG_RSA_PUBLIC_EXPONENT,
2144 exponent));
2145 break;
Kenny Root96427ba2013-08-16 14:02:41 -07002146 }
Chad Brubaker3a7d9e62015-06-04 15:01:46 -07002147 default: {
2148 ALOGW("Unsupported key type %d", keyType);
2149 return ::SYSTEM_ERROR;
2150 }
Kenny Root96427ba2013-08-16 14:02:41 -07002151 }
2152
Chad Brubaker3a7d9e62015-06-04 15:01:46 -07002153 int32_t rc = generateKey(name, params, NULL, 0, targetUid, flags,
2154 /*outCharacteristics*/ NULL);
2155 if (rc != ::NO_ERROR) {
2156 ALOGW("generate failed: %d", rc);
Kenny Root07438c82012-11-02 15:41:02 -07002157 }
Chad Brubaker3a7d9e62015-06-04 15:01:46 -07002158 return translateResultToLegacyResult(rc);
Kenny Root70e3a862012-02-15 17:20:23 -08002159 }
2160
Kenny Rootf9119d62013-04-03 09:22:15 -07002161 int32_t import(const String16& name, const uint8_t* data, size_t length, int targetUid,
2162 int32_t flags) {
Chad Brubaker3a7d9e62015-06-04 15:01:46 -07002163 const uint8_t* ptr = data;
Kenny Root07438c82012-11-02 15:41:02 -07002164
Chad Brubaker3a7d9e62015-06-04 15:01:46 -07002165 Unique_PKCS8_PRIV_KEY_INFO pkcs8(d2i_PKCS8_PRIV_KEY_INFO(NULL, &ptr, length));
2166 if (!pkcs8.get()) {
2167 return ::SYSTEM_ERROR;
2168 }
2169 Unique_EVP_PKEY pkey(EVP_PKCS82PKEY(pkcs8.get()));
2170 if (!pkey.get()) {
2171 return ::SYSTEM_ERROR;
2172 }
2173 int type = EVP_PKEY_type(pkey->type);
Shawn Willden2de8b752015-07-23 05:54:31 -06002174 KeymasterArguments params;
Shawn Willden55268b52015-07-28 11:06:00 -06002175 add_legacy_key_authorizations(type, &params.params);
Chad Brubaker3a7d9e62015-06-04 15:01:46 -07002176 switch (type) {
2177 case EVP_PKEY_RSA:
2178 params.params.push_back(keymaster_param_enum(KM_TAG_ALGORITHM, KM_ALGORITHM_RSA));
2179 break;
2180 case EVP_PKEY_EC:
2181 params.params.push_back(keymaster_param_enum(KM_TAG_ALGORITHM,
2182 KM_ALGORITHM_EC));
2183 break;
2184 default:
2185 ALOGW("Unsupported key type %d", type);
2186 return ::SYSTEM_ERROR;
2187 }
2188 int32_t rc = importKey(name, params, KM_KEY_FORMAT_PKCS8, data, length, targetUid, flags,
2189 /*outCharacteristics*/ NULL);
2190 if (rc != ::NO_ERROR) {
2191 ALOGW("importKey failed: %d", rc);
2192 }
2193 return translateResultToLegacyResult(rc);
Kenny Root70e3a862012-02-15 17:20:23 -08002194 }
2195
Kenny Root07438c82012-11-02 15:41:02 -07002196 int32_t sign(const String16& name, const uint8_t* data, size_t length, uint8_t** out,
Chad Brubaker3a7d9e62015-06-04 15:01:46 -07002197 size_t* outLength) {
Chad Brubaker9489b792015-04-14 11:01:45 -07002198 if (!checkBinderPermission(P_SIGN)) {
Kenny Root07438c82012-11-02 15:41:02 -07002199 return ::PERMISSION_DENIED;
2200 }
Chad Brubaker3a7d9e62015-06-04 15:01:46 -07002201 return doLegacySignVerify(name, data, length, out, outLength, NULL, 0, KM_PURPOSE_SIGN);
Kenny Root70e3a862012-02-15 17:20:23 -08002202 }
2203
Kenny Root07438c82012-11-02 15:41:02 -07002204 int32_t verify(const String16& name, const uint8_t* data, size_t dataLength,
2205 const uint8_t* signature, size_t signatureLength) {
Chad Brubaker9489b792015-04-14 11:01:45 -07002206 if (!checkBinderPermission(P_VERIFY)) {
Kenny Root07438c82012-11-02 15:41:02 -07002207 return ::PERMISSION_DENIED;
2208 }
Chad Brubaker3a7d9e62015-06-04 15:01:46 -07002209 return doLegacySignVerify(name, data, dataLength, NULL, NULL, signature, signatureLength,
2210 KM_PURPOSE_VERIFY);
Kenny Roota91203b2012-02-15 15:00:46 -08002211 }
Kenny Root07438c82012-11-02 15:41:02 -07002212
2213 /*
2214 * TODO: The abstraction between things stored in hardware and regular blobs
2215 * of data stored on the filesystem should be moved down to keystore itself.
2216 * Unfortunately the Java code that calls this has naming conventions that it
2217 * knows about. Ideally keystore shouldn't be used to store random blobs of
2218 * data.
2219 *
2220 * Until that happens, it's necessary to have a separate "get_pubkey" and
2221 * "del_key" since the Java code doesn't really communicate what it's
2222 * intentions are.
2223 */
2224 int32_t get_pubkey(const String16& name, uint8_t** pubkey, size_t* pubkeyLength) {
Chad Brubaker3a7d9e62015-06-04 15:01:46 -07002225 ExportResult result;
2226 exportKey(name, KM_KEY_FORMAT_X509, NULL, NULL, &result);
2227 if (result.resultCode != ::NO_ERROR) {
2228 ALOGW("export failed: %d", result.resultCode);
2229 return translateResultToLegacyResult(result.resultCode);
Kenny Root07438c82012-11-02 15:41:02 -07002230 }
Kenny Root07438c82012-11-02 15:41:02 -07002231
Chad Brubaker3a7d9e62015-06-04 15:01:46 -07002232 *pubkey = result.exportData.release();
2233 *pubkeyLength = result.dataLength;
Kenny Root07438c82012-11-02 15:41:02 -07002234 return ::NO_ERROR;
Kenny Roota91203b2012-02-15 15:00:46 -08002235 }
Kenny Root07438c82012-11-02 15:41:02 -07002236
Kenny Root07438c82012-11-02 15:41:02 -07002237 int32_t grant(const String16& name, int32_t granteeUid) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08002238 uid_t callingUid = IPCThreadState::self()->getCallingUid();
Chad Brubaker9489b792015-04-14 11:01:45 -07002239 int32_t result = checkBinderPermissionAndKeystoreState(P_GRANT);
2240 if (result != ::NO_ERROR) {
2241 return result;
Kenny Root07438c82012-11-02 15:41:02 -07002242 }
2243
2244 String8 name8(name);
Kenny Root655b9582013-04-04 08:37:42 -07002245 String8 filename(mKeyStore->getKeyNameForUidWithDir(name8, callingUid));
Kenny Root07438c82012-11-02 15:41:02 -07002246
Kenny Root655b9582013-04-04 08:37:42 -07002247 if (access(filename.string(), R_OK) == -1) {
Kenny Root07438c82012-11-02 15:41:02 -07002248 return (errno != ENOENT) ? ::SYSTEM_ERROR : ::KEY_NOT_FOUND;
2249 }
2250
Kenny Root655b9582013-04-04 08:37:42 -07002251 mKeyStore->addGrant(filename.string(), granteeUid);
Kenny Root07438c82012-11-02 15:41:02 -07002252 return ::NO_ERROR;
2253 }
2254
2255 int32_t ungrant(const String16& name, int32_t granteeUid) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08002256 uid_t callingUid = IPCThreadState::self()->getCallingUid();
Chad Brubaker9489b792015-04-14 11:01:45 -07002257 int32_t result = checkBinderPermissionAndKeystoreState(P_GRANT);
2258 if (result != ::NO_ERROR) {
2259 return result;
Kenny Root07438c82012-11-02 15:41:02 -07002260 }
2261
2262 String8 name8(name);
Kenny Root655b9582013-04-04 08:37:42 -07002263 String8 filename(mKeyStore->getKeyNameForUidWithDir(name8, callingUid));
Kenny Root07438c82012-11-02 15:41:02 -07002264
Kenny Root655b9582013-04-04 08:37:42 -07002265 if (access(filename.string(), R_OK) == -1) {
Kenny Root07438c82012-11-02 15:41:02 -07002266 return (errno != ENOENT) ? ::SYSTEM_ERROR : ::KEY_NOT_FOUND;
2267 }
2268
Kenny Root655b9582013-04-04 08:37:42 -07002269 return mKeyStore->removeGrant(filename.string(), granteeUid) ? ::NO_ERROR : ::KEY_NOT_FOUND;
Kenny Root07438c82012-11-02 15:41:02 -07002270 }
2271
2272 int64_t getmtime(const String16& name) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08002273 uid_t callingUid = IPCThreadState::self()->getCallingUid();
Chad Brubaker9489b792015-04-14 11:01:45 -07002274 if (!checkBinderPermission(P_GET)) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08002275 ALOGW("permission denied for %d: getmtime", callingUid);
Kenny Root36a9e232013-02-04 14:24:15 -08002276 return -1L;
Kenny Root07438c82012-11-02 15:41:02 -07002277 }
Kenny Root07438c82012-11-02 15:41:02 -07002278
2279 String8 name8(name);
Kenny Root655b9582013-04-04 08:37:42 -07002280 String8 filename(mKeyStore->getKeyNameForUidWithDir(name8, callingUid));
Kenny Root07438c82012-11-02 15:41:02 -07002281
Kenny Root655b9582013-04-04 08:37:42 -07002282 if (access(filename.string(), R_OK) == -1) {
2283 ALOGW("could not access %s for getmtime", filename.string());
Kenny Root36a9e232013-02-04 14:24:15 -08002284 return -1L;
Kenny Root07438c82012-11-02 15:41:02 -07002285 }
2286
Kenny Root655b9582013-04-04 08:37:42 -07002287 int fd = TEMP_FAILURE_RETRY(open(filename.string(), O_NOFOLLOW, O_RDONLY));
Kenny Root07438c82012-11-02 15:41:02 -07002288 if (fd < 0) {
Kenny Root655b9582013-04-04 08:37:42 -07002289 ALOGW("could not open %s for getmtime", filename.string());
Kenny Root36a9e232013-02-04 14:24:15 -08002290 return -1L;
Kenny Root07438c82012-11-02 15:41:02 -07002291 }
2292
2293 struct stat s;
2294 int ret = fstat(fd, &s);
2295 close(fd);
2296 if (ret == -1) {
Kenny Root655b9582013-04-04 08:37:42 -07002297 ALOGW("could not stat %s for getmtime", filename.string());
Kenny Root36a9e232013-02-04 14:24:15 -08002298 return -1L;
Kenny Root07438c82012-11-02 15:41:02 -07002299 }
2300
Kenny Root36a9e232013-02-04 14:24:15 -08002301 return static_cast<int64_t>(s.st_mtime);
Kenny Root07438c82012-11-02 15:41:02 -07002302 }
2303
Kenny Rootd53bc922013-03-21 14:10:15 -07002304 int32_t duplicate(const String16& srcKey, int32_t srcUid, const String16& destKey,
2305 int32_t destUid) {
Kenny Root02254072013-03-20 11:48:19 -07002306 uid_t callingUid = IPCThreadState::self()->getCallingUid();
Riley Spahneaabae92014-06-30 12:39:52 -07002307 pid_t spid = IPCThreadState::self()->getCallingPid();
2308 if (!has_permission(callingUid, P_DUPLICATE, spid)) {
Kenny Rootd53bc922013-03-21 14:10:15 -07002309 ALOGW("permission denied for %d: duplicate", callingUid);
Kenny Root02254072013-03-20 11:48:19 -07002310 return -1L;
2311 }
2312
Chad Brubaker72593ee2015-05-12 10:42:00 -07002313 State state = mKeyStore->getState(get_user_id(callingUid));
Kenny Root02254072013-03-20 11:48:19 -07002314 if (!isKeystoreUnlocked(state)) {
Kenny Rootd53bc922013-03-21 14:10:15 -07002315 ALOGD("calling duplicate in state: %d", state);
Kenny Root02254072013-03-20 11:48:19 -07002316 return state;
2317 }
2318
Kenny Rootd53bc922013-03-21 14:10:15 -07002319 if (srcUid == -1 || static_cast<uid_t>(srcUid) == callingUid) {
2320 srcUid = callingUid;
2321 } else if (!is_granted_to(callingUid, srcUid)) {
2322 ALOGD("migrate not granted from source: %d -> %d", callingUid, srcUid);
Kenny Root02254072013-03-20 11:48:19 -07002323 return ::PERMISSION_DENIED;
2324 }
2325
Kenny Rootd53bc922013-03-21 14:10:15 -07002326 if (destUid == -1) {
2327 destUid = callingUid;
2328 }
2329
2330 if (srcUid != destUid) {
2331 if (static_cast<uid_t>(srcUid) != callingUid) {
2332 ALOGD("can only duplicate from caller to other or to same uid: "
2333 "calling=%d, srcUid=%d, destUid=%d", callingUid, srcUid, destUid);
2334 return ::PERMISSION_DENIED;
2335 }
2336
2337 if (!is_granted_to(callingUid, destUid)) {
2338 ALOGD("duplicate not granted to dest: %d -> %d", callingUid, destUid);
2339 return ::PERMISSION_DENIED;
2340 }
2341 }
2342
2343 String8 source8(srcKey);
Kenny Root655b9582013-04-04 08:37:42 -07002344 String8 sourceFile(mKeyStore->getKeyNameForUidWithDir(source8, srcUid));
Kenny Root02254072013-03-20 11:48:19 -07002345
Kenny Rootd53bc922013-03-21 14:10:15 -07002346 String8 target8(destKey);
Kenny Rootfa27d5b2013-10-15 09:01:08 -07002347 String8 targetFile(mKeyStore->getKeyNameForUidWithDir(target8, destUid));
Kenny Root02254072013-03-20 11:48:19 -07002348
Kenny Root655b9582013-04-04 08:37:42 -07002349 if (access(targetFile.string(), W_OK) != -1 || errno != ENOENT) {
2350 ALOGD("destination already exists: %s", targetFile.string());
Kenny Root02254072013-03-20 11:48:19 -07002351 return ::SYSTEM_ERROR;
2352 }
2353
Kenny Rootd53bc922013-03-21 14:10:15 -07002354 Blob keyBlob;
Kenny Root655b9582013-04-04 08:37:42 -07002355 ResponseCode responseCode = mKeyStore->get(sourceFile.string(), &keyBlob, TYPE_ANY,
Chad Brubaker72593ee2015-05-12 10:42:00 -07002356 get_user_id(srcUid));
Kenny Rootd53bc922013-03-21 14:10:15 -07002357 if (responseCode != ::NO_ERROR) {
2358 return responseCode;
Kenny Root02254072013-03-20 11:48:19 -07002359 }
Kenny Rootd53bc922013-03-21 14:10:15 -07002360
Chad Brubaker72593ee2015-05-12 10:42:00 -07002361 return mKeyStore->put(targetFile.string(), &keyBlob, get_user_id(destUid));
Kenny Root02254072013-03-20 11:48:19 -07002362 }
2363
Kenny Root1b0e3932013-09-05 13:06:32 -07002364 int32_t is_hardware_backed(const String16& keyType) {
2365 return mKeyStore->isHardwareBacked(keyType) ? 1 : 0;
Kenny Root8ddf35a2013-03-29 11:15:50 -07002366 }
2367
Kenny Rootfa27d5b2013-10-15 09:01:08 -07002368 int32_t clear_uid(int64_t targetUid64) {
Chad Brubaker9489b792015-04-14 11:01:45 -07002369 uid_t targetUid = getEffectiveUid(targetUid64);
Chad Brubakerb37a5232015-05-01 10:21:27 -07002370 if (!checkBinderPermissionSelfOrSystem(P_CLEAR_UID, targetUid)) {
Kenny Roota9bb5492013-04-01 16:29:11 -07002371 return ::PERMISSION_DENIED;
2372 }
2373
Robin Lee4b84fdc2014-09-24 11:56:57 +01002374 String8 prefix = String8::format("%u_", targetUid);
2375 Vector<String16> aliases;
Chad Brubakere6c3bfa2015-05-12 15:18:26 -07002376 if (mKeyStore->list(prefix, &aliases, get_user_id(targetUid)) != ::NO_ERROR) {
Kenny Roota9bb5492013-04-01 16:29:11 -07002377 return ::SYSTEM_ERROR;
2378 }
2379
Robin Lee4b84fdc2014-09-24 11:56:57 +01002380 for (uint32_t i = 0; i < aliases.size(); i++) {
2381 String8 name8(aliases[i]);
2382 String8 filename(mKeyStore->getKeyNameForUidWithDir(name8, targetUid));
Chad Brubaker72593ee2015-05-12 10:42:00 -07002383 mKeyStore->del(filename.string(), ::TYPE_ANY, get_user_id(targetUid));
Kenny Roota9bb5492013-04-01 16:29:11 -07002384 }
Robin Lee4b84fdc2014-09-24 11:56:57 +01002385 return ::NO_ERROR;
Kenny Roota9bb5492013-04-01 16:29:11 -07002386 }
2387
Chad Brubaker9c8612c2015-02-09 11:32:54 -08002388 int32_t addRngEntropy(const uint8_t* data, size_t dataLength) {
2389 const keymaster1_device_t* device = mKeyStore->getDevice();
2390 const keymaster1_device_t* fallback = mKeyStore->getFallbackDevice();
2391 int32_t devResult = KM_ERROR_UNIMPLEMENTED;
2392 int32_t fallbackResult = KM_ERROR_UNIMPLEMENTED;
2393 if (device->common.module->module_api_version >= KEYMASTER_MODULE_API_VERSION_1_0 &&
2394 device->add_rng_entropy != NULL) {
2395 devResult = device->add_rng_entropy(device, data, dataLength);
2396 }
2397 if (fallback->add_rng_entropy) {
2398 fallbackResult = fallback->add_rng_entropy(fallback, data, dataLength);
2399 }
2400 if (devResult) {
2401 return devResult;
2402 }
2403 if (fallbackResult) {
2404 return fallbackResult;
2405 }
2406 return ::NO_ERROR;
Chad Brubaker9899d6b2015-02-03 13:03:00 -08002407 }
2408
Chad Brubaker17d68b92015-02-05 22:04:16 -08002409 int32_t generateKey(const String16& name, const KeymasterArguments& params,
Chad Brubaker154d7692015-03-27 13:59:31 -07002410 const uint8_t* entropy, size_t entropyLength, int uid, int flags,
2411 KeyCharacteristics* outCharacteristics) {
Chad Brubaker9489b792015-04-14 11:01:45 -07002412 uid = getEffectiveUid(uid);
2413 int rc = checkBinderPermissionAndKeystoreState(P_INSERT, uid,
2414 flags & KEYSTORE_FLAG_ENCRYPTED);
2415 if (rc != ::NO_ERROR) {
2416 return rc;
Chad Brubaker17d68b92015-02-05 22:04:16 -08002417 }
2418
Chad Brubaker9489b792015-04-14 11:01:45 -07002419 rc = KM_ERROR_UNIMPLEMENTED;
Chad Brubaker17d68b92015-02-05 22:04:16 -08002420 bool isFallback = false;
2421 keymaster_key_blob_t blob;
2422 keymaster_key_characteristics_t *out = NULL;
2423
2424 const keymaster1_device_t* device = mKeyStore->getDevice();
2425 const keymaster1_device_t* fallback = mKeyStore->getFallbackDevice();
Chad Brubaker57e106d2015-06-01 12:59:00 -07002426 std::vector<keymaster_key_param_t> opParams(params.params);
2427 const keymaster_key_param_set_t inParams = {opParams.data(), opParams.size()};
Chad Brubaker17d68b92015-02-05 22:04:16 -08002428 if (device == NULL) {
2429 return ::SYSTEM_ERROR;
2430 }
Chad Brubaker154d7692015-03-27 13:59:31 -07002431 // TODO: Seed from Linux RNG before this.
Chad Brubaker17d68b92015-02-05 22:04:16 -08002432 if (device->common.module->module_api_version >= KEYMASTER_MODULE_API_VERSION_1_0 &&
2433 device->generate_key != NULL) {
Chad Brubaker154d7692015-03-27 13:59:31 -07002434 if (!entropy) {
2435 rc = KM_ERROR_OK;
2436 } else if (device->add_rng_entropy) {
2437 rc = device->add_rng_entropy(device, entropy, entropyLength);
2438 } else {
2439 rc = KM_ERROR_UNIMPLEMENTED;
2440 }
2441 if (rc == KM_ERROR_OK) {
Chad Brubaker57e106d2015-06-01 12:59:00 -07002442 rc = device->generate_key(device, &inParams, &blob, &out);
Chad Brubaker154d7692015-03-27 13:59:31 -07002443 }
Chad Brubaker17d68b92015-02-05 22:04:16 -08002444 }
2445 // If the HW device didn't support generate_key or generate_key failed
2446 // fall back to the software implementation.
2447 if (rc && fallback->generate_key != NULL) {
Shawn Willden55268b52015-07-28 11:06:00 -06002448 ALOGW("Primary keymaster device failed to generate key, falling back to SW.");
Chad Brubaker17d68b92015-02-05 22:04:16 -08002449 isFallback = true;
Chad Brubaker154d7692015-03-27 13:59:31 -07002450 if (!entropy) {
2451 rc = KM_ERROR_OK;
2452 } else if (fallback->add_rng_entropy) {
2453 rc = fallback->add_rng_entropy(fallback, entropy, entropyLength);
2454 } else {
2455 rc = KM_ERROR_UNIMPLEMENTED;
2456 }
2457 if (rc == KM_ERROR_OK) {
Chad Brubaker57e106d2015-06-01 12:59:00 -07002458 rc = fallback->generate_key(fallback, &inParams, &blob, &out);
Chad Brubaker154d7692015-03-27 13:59:31 -07002459 }
Chad Brubaker17d68b92015-02-05 22:04:16 -08002460 }
2461
2462 if (out) {
2463 if (outCharacteristics) {
2464 outCharacteristics->characteristics = *out;
2465 } else {
2466 keymaster_free_characteristics(out);
2467 }
2468 free(out);
2469 }
2470
2471 if (rc) {
2472 return rc;
2473 }
2474
2475 String8 name8(name);
2476 String8 filename(mKeyStore->getKeyNameForUidWithDir(name8, uid));
2477
2478 Blob keyBlob(blob.key_material, blob.key_material_size, NULL, 0, ::TYPE_KEYMASTER_10);
2479 keyBlob.setFallback(isFallback);
2480 keyBlob.setEncrypted(flags & KEYSTORE_FLAG_ENCRYPTED);
2481
2482 free(const_cast<uint8_t*>(blob.key_material));
2483
Chad Brubaker72593ee2015-05-12 10:42:00 -07002484 return mKeyStore->put(filename.string(), &keyBlob, get_user_id(uid));
Chad Brubaker9899d6b2015-02-03 13:03:00 -08002485 }
2486
Chad Brubakerf3f071f2015-02-10 19:38:51 -08002487 int32_t getKeyCharacteristics(const String16& name,
Chad Brubakerd6634422015-03-21 22:36:07 -07002488 const keymaster_blob_t* clientId,
2489 const keymaster_blob_t* appData,
Chad Brubakerf3f071f2015-02-10 19:38:51 -08002490 KeyCharacteristics* outCharacteristics) {
Chad Brubakerf3f071f2015-02-10 19:38:51 -08002491 if (!outCharacteristics) {
2492 return KM_ERROR_UNEXPECTED_NULL_POINTER;
2493 }
2494
2495 uid_t callingUid = IPCThreadState::self()->getCallingUid();
2496
2497 Blob keyBlob;
2498 String8 name8(name);
2499 int rc;
2500
2501 ResponseCode responseCode = mKeyStore->getKeyForName(&keyBlob, name8, callingUid,
2502 TYPE_KEYMASTER_10);
2503 if (responseCode != ::NO_ERROR) {
2504 return responseCode;
2505 }
2506 keymaster_key_blob_t key;
2507 key.key_material_size = keyBlob.getLength();
2508 key.key_material = keyBlob.getValue();
2509 keymaster1_device_t* dev = mKeyStore->getDeviceForBlob(keyBlob);
2510 keymaster_key_characteristics_t *out = NULL;
2511 if (!dev->get_key_characteristics) {
2512 ALOGW("device does not implement get_key_characteristics");
2513 return KM_ERROR_UNIMPLEMENTED;
2514 }
Chad Brubakerd6634422015-03-21 22:36:07 -07002515 rc = dev->get_key_characteristics(dev, &key, clientId, appData, &out);
Chad Brubakerf3f071f2015-02-10 19:38:51 -08002516 if (out) {
2517 outCharacteristics->characteristics = *out;
2518 free(out);
2519 }
2520 return rc ? rc : ::NO_ERROR;
Chad Brubaker9899d6b2015-02-03 13:03:00 -08002521 }
2522
Chad Brubaker4c353cb2015-02-11 14:36:11 -08002523 int32_t importKey(const String16& name, const KeymasterArguments& params,
2524 keymaster_key_format_t format, const uint8_t *keyData,
2525 size_t keyLength, int uid, int flags,
2526 KeyCharacteristics* outCharacteristics) {
Chad Brubaker9489b792015-04-14 11:01:45 -07002527 uid = getEffectiveUid(uid);
2528 int rc = checkBinderPermissionAndKeystoreState(P_INSERT, uid,
2529 flags & KEYSTORE_FLAG_ENCRYPTED);
2530 if (rc != ::NO_ERROR) {
2531 return rc;
Chad Brubaker4c353cb2015-02-11 14:36:11 -08002532 }
2533
Chad Brubaker9489b792015-04-14 11:01:45 -07002534 rc = KM_ERROR_UNIMPLEMENTED;
Chad Brubaker4c353cb2015-02-11 14:36:11 -08002535 bool isFallback = false;
2536 keymaster_key_blob_t blob;
2537 keymaster_key_characteristics_t *out = NULL;
2538
2539 const keymaster1_device_t* device = mKeyStore->getDevice();
2540 const keymaster1_device_t* fallback = mKeyStore->getFallbackDevice();
Chad Brubaker57e106d2015-06-01 12:59:00 -07002541 std::vector<keymaster_key_param_t> opParams(params.params);
2542 const keymaster_key_param_set_t inParams = {opParams.data(), opParams.size()};
2543 const keymaster_blob_t input = {keyData, keyLength};
Chad Brubaker4c353cb2015-02-11 14:36:11 -08002544 if (device == NULL) {
2545 return ::SYSTEM_ERROR;
2546 }
2547 if (device->common.module->module_api_version >= KEYMASTER_MODULE_API_VERSION_1_0 &&
2548 device->import_key != NULL) {
Chad Brubaker57e106d2015-06-01 12:59:00 -07002549 rc = device->import_key(device, &inParams, format,&input, &blob, &out);
Chad Brubaker4c353cb2015-02-11 14:36:11 -08002550 }
2551 if (rc && fallback->import_key != NULL) {
Shawn Willden55268b52015-07-28 11:06:00 -06002552 ALOGW("Primary keymaster device failed to import key, falling back to SW.");
Chad Brubaker4c353cb2015-02-11 14:36:11 -08002553 isFallback = true;
Chad Brubaker57e106d2015-06-01 12:59:00 -07002554 rc = fallback->import_key(fallback, &inParams, format, &input, &blob, &out);
Chad Brubaker4c353cb2015-02-11 14:36:11 -08002555 }
2556 if (out) {
2557 if (outCharacteristics) {
2558 outCharacteristics->characteristics = *out;
2559 } else {
2560 keymaster_free_characteristics(out);
2561 }
2562 free(out);
2563 }
2564 if (rc) {
2565 return rc;
2566 }
2567
2568 String8 name8(name);
2569 String8 filename(mKeyStore->getKeyNameForUidWithDir(name8, uid));
2570
2571 Blob keyBlob(blob.key_material, blob.key_material_size, NULL, 0, ::TYPE_KEYMASTER_10);
2572 keyBlob.setFallback(isFallback);
2573 keyBlob.setEncrypted(flags & KEYSTORE_FLAG_ENCRYPTED);
2574
2575 free((void*) blob.key_material);
2576
Chad Brubaker72593ee2015-05-12 10:42:00 -07002577 return mKeyStore->put(filename.string(), &keyBlob, get_user_id(uid));
Chad Brubaker9899d6b2015-02-03 13:03:00 -08002578 }
2579
Chad Brubaker07b0cda2015-02-18 15:52:54 -08002580 void exportKey(const String16& name, keymaster_key_format_t format,
Chad Brubakerd6634422015-03-21 22:36:07 -07002581 const keymaster_blob_t* clientId,
2582 const keymaster_blob_t* appData, ExportResult* result) {
Chad Brubaker07b0cda2015-02-18 15:52:54 -08002583
2584 uid_t callingUid = IPCThreadState::self()->getCallingUid();
2585
2586 Blob keyBlob;
2587 String8 name8(name);
2588 int rc;
2589
2590 ResponseCode responseCode = mKeyStore->getKeyForName(&keyBlob, name8, callingUid,
2591 TYPE_KEYMASTER_10);
2592 if (responseCode != ::NO_ERROR) {
2593 result->resultCode = responseCode;
2594 return;
2595 }
2596 keymaster_key_blob_t key;
2597 key.key_material_size = keyBlob.getLength();
2598 key.key_material = keyBlob.getValue();
2599 keymaster1_device_t* dev = mKeyStore->getDeviceForBlob(keyBlob);
2600 if (!dev->export_key) {
2601 result->resultCode = KM_ERROR_UNIMPLEMENTED;
2602 return;
2603 }
Chad Brubaker57e106d2015-06-01 12:59:00 -07002604 keymaster_blob_t output = {NULL, 0};
2605 rc = dev->export_key(dev, format, &key, clientId, appData, &output);
2606 result->exportData.reset(const_cast<uint8_t*>(output.data));
2607 result->dataLength = output.data_length;
Chad Brubaker07b0cda2015-02-18 15:52:54 -08002608 result->resultCode = rc ? rc : ::NO_ERROR;
Chad Brubaker9899d6b2015-02-03 13:03:00 -08002609 }
2610
Chad Brubakerad6514a2015-04-09 14:00:26 -07002611
Chad Brubaker40a1a9b2015-02-20 14:08:13 -08002612 void begin(const sp<IBinder>& appToken, const String16& name, keymaster_purpose_t purpose,
Chad Brubaker154d7692015-03-27 13:59:31 -07002613 bool pruneable, const KeymasterArguments& params, const uint8_t* entropy,
Chad Brubaker57e106d2015-06-01 12:59:00 -07002614 size_t entropyLength, OperationResult* result) {
Chad Brubaker40a1a9b2015-02-20 14:08:13 -08002615 uid_t callingUid = IPCThreadState::self()->getCallingUid();
2616 if (!pruneable && get_app_id(callingUid) != AID_SYSTEM) {
2617 ALOGE("Non-system uid %d trying to start non-pruneable operation", callingUid);
2618 result->resultCode = ::PERMISSION_DENIED;
2619 return;
2620 }
Chad Brubaker0cf34a22015-04-23 11:06:16 -07002621 if (!checkAllowedOperationParams(params.params)) {
2622 result->resultCode = KM_ERROR_INVALID_ARGUMENT;
2623 return;
2624 }
Chad Brubaker40a1a9b2015-02-20 14:08:13 -08002625 Blob keyBlob;
2626 String8 name8(name);
2627 ResponseCode responseCode = mKeyStore->getKeyForName(&keyBlob, name8, callingUid,
2628 TYPE_KEYMASTER_10);
2629 if (responseCode != ::NO_ERROR) {
2630 result->resultCode = responseCode;
2631 return;
2632 }
2633 keymaster_key_blob_t key;
2634 key.key_material_size = keyBlob.getLength();
2635 key.key_material = keyBlob.getValue();
Chad Brubaker40a1a9b2015-02-20 14:08:13 -08002636 keymaster_operation_handle_t handle;
2637 keymaster1_device_t* dev = mKeyStore->getDeviceForBlob(keyBlob);
Chad Brubaker154d7692015-03-27 13:59:31 -07002638 keymaster_error_t err = KM_ERROR_UNIMPLEMENTED;
Chad Brubaker06801e02015-03-31 15:13:13 -07002639 std::vector<keymaster_key_param_t> opParams(params.params);
Chad Brubakerad6514a2015-04-09 14:00:26 -07002640 Unique_keymaster_key_characteristics characteristics;
2641 characteristics.reset(new keymaster_key_characteristics_t);
2642 err = getOperationCharacteristics(key, dev, opParams, characteristics.get());
2643 if (err) {
2644 result->resultCode = err;
2645 return;
2646 }
Chad Brubaker0cf34a22015-04-23 11:06:16 -07002647 const hw_auth_token_t* authToken = NULL;
Shawn Willdenb2ffa422015-06-17 12:18:55 -06002648 int32_t authResult = getAuthToken(characteristics.get(), 0, purpose, &authToken,
Chad Brubaker06801e02015-03-31 15:13:13 -07002649 /*failOnTokenMissing*/ false);
Chad Brubaker0cf34a22015-04-23 11:06:16 -07002650 // If per-operation auth is needed we need to begin the operation and
2651 // the client will need to authorize that operation before calling
2652 // update. Any other auth issues stop here.
2653 if (authResult != ::NO_ERROR && authResult != ::OP_AUTH_NEEDED) {
2654 result->resultCode = authResult;
Chad Brubaker06801e02015-03-31 15:13:13 -07002655 return;
2656 }
Chad Brubaker0cf34a22015-04-23 11:06:16 -07002657 addAuthToParams(&opParams, authToken);
Chad Brubaker154d7692015-03-27 13:59:31 -07002658 // Add entropy to the device first.
2659 if (entropy) {
2660 if (dev->add_rng_entropy) {
2661 err = dev->add_rng_entropy(dev, entropy, entropyLength);
2662 } else {
2663 err = KM_ERROR_UNIMPLEMENTED;
2664 }
2665 if (err) {
2666 result->resultCode = err;
2667 return;
2668 }
2669 }
Chad Brubaker57e106d2015-06-01 12:59:00 -07002670 keymaster_key_param_set_t inParams = {opParams.data(), opParams.size()};
Chad Brubaker40a1a9b2015-02-20 14:08:13 -08002671
Shawn Willden9221bff2015-06-18 18:23:54 -06002672 // Create a keyid for this key.
2673 keymaster::km_id_t keyid;
2674 if (!enforcement_policy.CreateKeyId(key, &keyid)) {
2675 ALOGE("Failed to create a key ID for authorization checking.");
2676 result->resultCode = KM_ERROR_UNKNOWN_ERROR;
2677 return;
2678 }
2679
2680 // Check that all key authorization policy requirements are met.
2681 keymaster::AuthorizationSet key_auths(characteristics->hw_enforced);
2682 key_auths.push_back(characteristics->sw_enforced);
2683 keymaster::AuthorizationSet operation_params(inParams);
2684 err = enforcement_policy.AuthorizeOperation(purpose, keyid, key_auths, operation_params,
2685 0 /* op_handle */,
2686 true /* is_begin_operation */);
2687 if (err) {
2688 result->resultCode = err;
2689 return;
2690 }
2691
Alex Klyubin4e88f9b2015-06-23 15:04:05 -07002692 keymaster_key_param_set_t outParams = {NULL, 0};
Shawn Willden1f769692015-10-30 10:05:43 -06002693
2694 // If there are more than MAX_OPERATIONS, abort the oldest operation that was started as
2695 // pruneable.
2696 while (mOperationMap.getOperationCount() >= MAX_OPERATIONS) {
2697 ALOGD("Reached or exceeded concurrent operations limit");
2698 if (!pruneOperation()) {
2699 break;
2700 }
2701 }
2702
Alex Klyubin4e88f9b2015-06-23 15:04:05 -07002703 err = dev->begin(dev, purpose, &key, &inParams, &outParams, &handle);
Shawn Willden1f769692015-10-30 10:05:43 -06002704 if (err != KM_ERROR_OK) {
2705 ALOGE("Got error %d from begin()", err);
2706 }
Alex Klyubin4e88f9b2015-06-23 15:04:05 -07002707
Chad Brubaker40a1a9b2015-02-20 14:08:13 -08002708 // If there are too many operations abort the oldest operation that was
2709 // started as pruneable and try again.
2710 while (err == KM_ERROR_TOO_MANY_OPERATIONS && mOperationMap.hasPruneableOperation()) {
Shawn Willden1f769692015-10-30 10:05:43 -06002711 ALOGE("Ran out of operation handles");
2712 if (!pruneOperation()) {
Chad Brubaker40a1a9b2015-02-20 14:08:13 -08002713 break;
2714 }
Chad Brubaker57e106d2015-06-01 12:59:00 -07002715 err = dev->begin(dev, purpose, &key, &inParams, &outParams, &handle);
Chad Brubaker40a1a9b2015-02-20 14:08:13 -08002716 }
2717 if (err) {
2718 result->resultCode = err;
2719 return;
2720 }
Chad Brubaker40a1a9b2015-02-20 14:08:13 -08002721
Shawn Willden9221bff2015-06-18 18:23:54 -06002722 sp<IBinder> operationToken = mOperationMap.addOperation(handle, keyid, purpose, dev,
2723 appToken, characteristics.release(),
Chad Brubaker06801e02015-03-31 15:13:13 -07002724 pruneable);
Chad Brubaker0cf34a22015-04-23 11:06:16 -07002725 if (authToken) {
2726 mOperationMap.setOperationAuthToken(operationToken, authToken);
2727 }
2728 // Return the authentication lookup result. If this is a per operation
2729 // auth'd key then the resultCode will be ::OP_AUTH_NEEDED and the
2730 // application should get an auth token using the handle before the
2731 // first call to update, which will fail if keystore hasn't received the
2732 // auth token.
2733 result->resultCode = authResult;
Chad Brubaker40a1a9b2015-02-20 14:08:13 -08002734 result->token = operationToken;
Chad Brubakerc3a18562015-03-17 18:21:35 -07002735 result->handle = handle;
Chad Brubaker57e106d2015-06-01 12:59:00 -07002736 if (outParams.params) {
2737 result->outParams.params.assign(outParams.params, outParams.params + outParams.length);
2738 free(outParams.params);
2739 }
Chad Brubaker9899d6b2015-02-03 13:03:00 -08002740 }
2741
Chad Brubaker40a1a9b2015-02-20 14:08:13 -08002742 void update(const sp<IBinder>& token, const KeymasterArguments& params, const uint8_t* data,
2743 size_t dataLength, OperationResult* result) {
Chad Brubaker0cf34a22015-04-23 11:06:16 -07002744 if (!checkAllowedOperationParams(params.params)) {
2745 result->resultCode = KM_ERROR_INVALID_ARGUMENT;
2746 return;
2747 }
Chad Brubaker40a1a9b2015-02-20 14:08:13 -08002748 const keymaster1_device_t* dev;
2749 keymaster_operation_handle_t handle;
Shawn Willdenb2ffa422015-06-17 12:18:55 -06002750 keymaster_purpose_t purpose;
Shawn Willden9221bff2015-06-18 18:23:54 -06002751 keymaster::km_id_t keyid;
2752 const keymaster_key_characteristics_t* characteristics;
2753 if (!mOperationMap.getOperation(token, &handle, &keyid, &purpose, &dev, &characteristics)) {
Chad Brubaker40a1a9b2015-02-20 14:08:13 -08002754 result->resultCode = KM_ERROR_INVALID_OPERATION_HANDLE;
2755 return;
2756 }
Chad Brubaker06801e02015-03-31 15:13:13 -07002757 std::vector<keymaster_key_param_t> opParams(params.params);
Chad Brubaker0cf34a22015-04-23 11:06:16 -07002758 int32_t authResult = addOperationAuthTokenIfNeeded(token, &opParams);
2759 if (authResult != ::NO_ERROR) {
Chad Brubaker06801e02015-03-31 15:13:13 -07002760 result->resultCode = authResult;
2761 return;
2762 }
Chad Brubaker57e106d2015-06-01 12:59:00 -07002763 keymaster_key_param_set_t inParams = {opParams.data(), opParams.size()};
2764 keymaster_blob_t input = {data, dataLength};
2765 size_t consumed = 0;
2766 keymaster_blob_t output = {NULL, 0};
2767 keymaster_key_param_set_t outParams = {NULL, 0};
2768
Shawn Willden9221bff2015-06-18 18:23:54 -06002769 // Check that all key authorization policy requirements are met.
2770 keymaster::AuthorizationSet key_auths(characteristics->hw_enforced);
2771 key_auths.push_back(characteristics->sw_enforced);
2772 keymaster::AuthorizationSet operation_params(inParams);
2773 result->resultCode =
2774 enforcement_policy.AuthorizeOperation(purpose, keyid, key_auths,
2775 operation_params, handle,
2776 false /* is_begin_operation */);
2777 if (result->resultCode) {
2778 return;
2779 }
2780
Chad Brubaker57e106d2015-06-01 12:59:00 -07002781 keymaster_error_t err = dev->update(dev, handle, &inParams, &input, &consumed, &outParams,
2782 &output);
2783 result->data.reset(const_cast<uint8_t*>(output.data));
2784 result->dataLength = output.data_length;
Chad Brubaker40a1a9b2015-02-20 14:08:13 -08002785 result->inputConsumed = consumed;
2786 result->resultCode = err ? (int32_t) err : ::NO_ERROR;
Chad Brubaker57e106d2015-06-01 12:59:00 -07002787 if (outParams.params) {
2788 result->outParams.params.assign(outParams.params, outParams.params + outParams.length);
2789 free(outParams.params);
2790 }
Chad Brubaker9899d6b2015-02-03 13:03:00 -08002791 }
2792
Chad Brubaker40a1a9b2015-02-20 14:08:13 -08002793 void finish(const sp<IBinder>& token, const KeymasterArguments& params,
Chad Brubaker0d33e0b2015-05-29 12:30:19 -07002794 const uint8_t* signature, size_t signatureLength,
2795 const uint8_t* entropy, size_t entropyLength, OperationResult* result) {
Chad Brubaker0cf34a22015-04-23 11:06:16 -07002796 if (!checkAllowedOperationParams(params.params)) {
2797 result->resultCode = KM_ERROR_INVALID_ARGUMENT;
2798 return;
2799 }
Chad Brubaker40a1a9b2015-02-20 14:08:13 -08002800 const keymaster1_device_t* dev;
2801 keymaster_operation_handle_t handle;
Shawn Willdenb2ffa422015-06-17 12:18:55 -06002802 keymaster_purpose_t purpose;
Shawn Willden9221bff2015-06-18 18:23:54 -06002803 keymaster::km_id_t keyid;
2804 const keymaster_key_characteristics_t* characteristics;
2805 if (!mOperationMap.getOperation(token, &handle, &keyid, &purpose, &dev, &characteristics)) {
Chad Brubaker40a1a9b2015-02-20 14:08:13 -08002806 result->resultCode = KM_ERROR_INVALID_OPERATION_HANDLE;
2807 return;
2808 }
Chad Brubaker06801e02015-03-31 15:13:13 -07002809 std::vector<keymaster_key_param_t> opParams(params.params);
Chad Brubaker0cf34a22015-04-23 11:06:16 -07002810 int32_t authResult = addOperationAuthTokenIfNeeded(token, &opParams);
2811 if (authResult != ::NO_ERROR) {
Chad Brubaker06801e02015-03-31 15:13:13 -07002812 result->resultCode = authResult;
2813 return;
2814 }
Chad Brubaker0d33e0b2015-05-29 12:30:19 -07002815 keymaster_error_t err;
2816 if (entropy) {
2817 if (dev->add_rng_entropy) {
2818 err = dev->add_rng_entropy(dev, entropy, entropyLength);
2819 } else {
2820 err = KM_ERROR_UNIMPLEMENTED;
2821 }
2822 if (err) {
2823 result->resultCode = err;
2824 return;
2825 }
2826 }
Chad Brubaker0cf34a22015-04-23 11:06:16 -07002827
Chad Brubaker57e106d2015-06-01 12:59:00 -07002828 keymaster_key_param_set_t inParams = {opParams.data(), opParams.size()};
2829 keymaster_blob_t input = {signature, signatureLength};
2830 keymaster_blob_t output = {NULL, 0};
2831 keymaster_key_param_set_t outParams = {NULL, 0};
Shawn Willden9221bff2015-06-18 18:23:54 -06002832
2833 // Check that all key authorization policy requirements are met.
2834 keymaster::AuthorizationSet key_auths(characteristics->hw_enforced);
2835 key_auths.push_back(characteristics->sw_enforced);
2836 keymaster::AuthorizationSet operation_params(inParams);
2837 err = enforcement_policy.AuthorizeOperation(purpose, keyid, key_auths, operation_params,
2838 handle, false /* is_begin_operation */);
2839 if (err) {
2840 result->resultCode = err;
2841 return;
2842 }
2843
Chad Brubaker0d33e0b2015-05-29 12:30:19 -07002844 err = dev->finish(dev, handle, &inParams, &input, &outParams, &output);
Chad Brubaker40a1a9b2015-02-20 14:08:13 -08002845 // Remove the operation regardless of the result
2846 mOperationMap.removeOperation(token);
Chad Brubaker06801e02015-03-31 15:13:13 -07002847 mAuthTokenTable.MarkCompleted(handle);
Chad Brubaker57e106d2015-06-01 12:59:00 -07002848
2849 result->data.reset(const_cast<uint8_t*>(output.data));
2850 result->dataLength = output.data_length;
Chad Brubaker40a1a9b2015-02-20 14:08:13 -08002851 result->resultCode = err ? (int32_t) err : ::NO_ERROR;
Chad Brubaker57e106d2015-06-01 12:59:00 -07002852 if (outParams.params) {
2853 result->outParams.params.assign(outParams.params, outParams.params + outParams.length);
2854 free(outParams.params);
2855 }
Chad Brubaker9899d6b2015-02-03 13:03:00 -08002856 }
2857
Chad Brubaker40a1a9b2015-02-20 14:08:13 -08002858 int32_t abort(const sp<IBinder>& token) {
2859 const keymaster1_device_t* dev;
2860 keymaster_operation_handle_t handle;
Shawn Willdenb2ffa422015-06-17 12:18:55 -06002861 keymaster_purpose_t purpose;
Shawn Willden9221bff2015-06-18 18:23:54 -06002862 keymaster::km_id_t keyid;
2863 if (!mOperationMap.getOperation(token, &handle, &keyid, &purpose, &dev, NULL)) {
Chad Brubaker40a1a9b2015-02-20 14:08:13 -08002864 return KM_ERROR_INVALID_OPERATION_HANDLE;
2865 }
2866 mOperationMap.removeOperation(token);
Chad Brubaker06801e02015-03-31 15:13:13 -07002867 int32_t rc;
Chad Brubaker40a1a9b2015-02-20 14:08:13 -08002868 if (!dev->abort) {
Chad Brubaker06801e02015-03-31 15:13:13 -07002869 rc = KM_ERROR_UNIMPLEMENTED;
2870 } else {
2871 rc = dev->abort(dev, handle);
Chad Brubaker40a1a9b2015-02-20 14:08:13 -08002872 }
Chad Brubaker06801e02015-03-31 15:13:13 -07002873 mAuthTokenTable.MarkCompleted(handle);
Chad Brubaker40a1a9b2015-02-20 14:08:13 -08002874 if (rc) {
2875 return rc;
2876 }
2877 return ::NO_ERROR;
Chad Brubaker9899d6b2015-02-03 13:03:00 -08002878 }
2879
Chad Brubaker2ed2baa2015-03-21 21:20:10 -07002880 bool isOperationAuthorized(const sp<IBinder>& token) {
2881 const keymaster1_device_t* dev;
2882 keymaster_operation_handle_t handle;
Chad Brubakerad6514a2015-04-09 14:00:26 -07002883 const keymaster_key_characteristics_t* characteristics;
Shawn Willdenb2ffa422015-06-17 12:18:55 -06002884 keymaster_purpose_t purpose;
Shawn Willden9221bff2015-06-18 18:23:54 -06002885 keymaster::km_id_t keyid;
2886 if (!mOperationMap.getOperation(token, &handle, &keyid, &purpose, &dev, &characteristics)) {
Chad Brubaker2ed2baa2015-03-21 21:20:10 -07002887 return false;
2888 }
Chad Brubaker0cf34a22015-04-23 11:06:16 -07002889 const hw_auth_token_t* authToken = NULL;
2890 mOperationMap.getOperationAuthToken(token, &authToken);
Chad Brubaker06801e02015-03-31 15:13:13 -07002891 std::vector<keymaster_key_param_t> ignored;
Chad Brubaker0cf34a22015-04-23 11:06:16 -07002892 int32_t authResult = addOperationAuthTokenIfNeeded(token, &ignored);
2893 return authResult == ::NO_ERROR;
Chad Brubaker2ed2baa2015-03-21 21:20:10 -07002894 }
2895
Chad Brubakerd80c7b42015-03-31 11:04:28 -07002896 int32_t addAuthToken(const uint8_t* token, size_t length) {
Chad Brubaker9489b792015-04-14 11:01:45 -07002897 if (!checkBinderPermission(P_ADD_AUTH)) {
2898 ALOGW("addAuthToken: permission denied for %d",
2899 IPCThreadState::self()->getCallingUid());
Chad Brubakerd80c7b42015-03-31 11:04:28 -07002900 return ::PERMISSION_DENIED;
2901 }
2902 if (length != sizeof(hw_auth_token_t)) {
2903 return KM_ERROR_INVALID_ARGUMENT;
2904 }
2905 hw_auth_token_t* authToken = new hw_auth_token_t;
2906 memcpy(reinterpret_cast<void*>(authToken), token, sizeof(hw_auth_token_t));
2907 // The table takes ownership of authToken.
2908 mAuthTokenTable.AddAuthenticationToken(authToken);
2909 return ::NO_ERROR;
Chad Brubaker2ed2baa2015-03-21 21:20:10 -07002910 }
2911
Kenny Root07438c82012-11-02 15:41:02 -07002912private:
Chad Brubaker9489b792015-04-14 11:01:45 -07002913 static const int32_t UID_SELF = -1;
2914
2915 /**
Shawn Willden1f769692015-10-30 10:05:43 -06002916 * Prune the oldest pruneable operation.
2917 */
2918 inline bool pruneOperation() {
2919 sp<IBinder> oldest = mOperationMap.getOldestPruneableOperation();
2920 ALOGD("Trying to prune operation %p", oldest.get());
2921 size_t op_count_before_abort = mOperationMap.getOperationCount();
2922 // We mostly ignore errors from abort() because all we care about is whether at least
2923 // one operation has been removed.
2924 int abort_error = abort(oldest);
2925 if (mOperationMap.getOperationCount() >= op_count_before_abort) {
2926 ALOGE("Failed to abort pruneable operation %p, error: %d", oldest.get(),
2927 abort_error);
2928 return false;
2929 }
2930 return true;
2931 }
2932
2933 /**
Chad Brubaker9489b792015-04-14 11:01:45 -07002934 * Get the effective target uid for a binder operation that takes an
2935 * optional uid as the target.
2936 */
2937 inline uid_t getEffectiveUid(int32_t targetUid) {
2938 if (targetUid == UID_SELF) {
2939 return IPCThreadState::self()->getCallingUid();
2940 }
2941 return static_cast<uid_t>(targetUid);
2942 }
2943
2944 /**
2945 * Check if the caller of the current binder method has the required
2946 * permission and if acting on other uids the grants to do so.
2947 */
2948 inline bool checkBinderPermission(perm_t permission, int32_t targetUid = UID_SELF) {
2949 uid_t callingUid = IPCThreadState::self()->getCallingUid();
2950 pid_t spid = IPCThreadState::self()->getCallingPid();
2951 if (!has_permission(callingUid, permission, spid)) {
2952 ALOGW("permission %s denied for %d", get_perm_label(permission), callingUid);
2953 return false;
2954 }
2955 if (!is_granted_to(callingUid, getEffectiveUid(targetUid))) {
2956 ALOGW("uid %d not granted to act for %d", callingUid, targetUid);
2957 return false;
2958 }
2959 return true;
2960 }
2961
2962 /**
2963 * Check if the caller of the current binder method has the required
Chad Brubakerb37a5232015-05-01 10:21:27 -07002964 * permission and the target uid is the caller or the caller is system.
2965 */
2966 inline bool checkBinderPermissionSelfOrSystem(perm_t permission, int32_t targetUid) {
2967 uid_t callingUid = IPCThreadState::self()->getCallingUid();
2968 pid_t spid = IPCThreadState::self()->getCallingPid();
2969 if (!has_permission(callingUid, permission, spid)) {
2970 ALOGW("permission %s denied for %d", get_perm_label(permission), callingUid);
2971 return false;
2972 }
2973 return getEffectiveUid(targetUid) == callingUid || callingUid == AID_SYSTEM;
2974 }
2975
2976 /**
2977 * Check if the caller of the current binder method has the required
Chad Brubaker9489b792015-04-14 11:01:45 -07002978 * permission or the target of the operation is the caller's uid. This is
2979 * for operation where the permission is only for cross-uid activity and all
2980 * uids are allowed to act on their own (ie: clearing all entries for a
2981 * given uid).
2982 */
2983 inline bool checkBinderPermissionOrSelfTarget(perm_t permission, int32_t targetUid) {
2984 uid_t callingUid = IPCThreadState::self()->getCallingUid();
2985 if (getEffectiveUid(targetUid) == callingUid) {
2986 return true;
2987 } else {
2988 return checkBinderPermission(permission, targetUid);
2989 }
2990 }
2991
2992 /**
2993 * Helper method to check that the caller has the required permission as
2994 * well as the keystore is in the unlocked state if checkUnlocked is true.
2995 *
2996 * Returns NO_ERROR on success, PERMISSION_DENIED on a permission error and
2997 * otherwise the state of keystore when not unlocked and checkUnlocked is
2998 * true.
2999 */
3000 inline int32_t checkBinderPermissionAndKeystoreState(perm_t permission, int32_t targetUid = -1,
3001 bool checkUnlocked = true) {
3002 if (!checkBinderPermission(permission, targetUid)) {
3003 return ::PERMISSION_DENIED;
3004 }
Chad Brubaker72593ee2015-05-12 10:42:00 -07003005 State state = mKeyStore->getState(get_user_id(getEffectiveUid(targetUid)));
Chad Brubaker9489b792015-04-14 11:01:45 -07003006 if (checkUnlocked && !isKeystoreUnlocked(state)) {
3007 return state;
3008 }
3009
3010 return ::NO_ERROR;
3011
3012 }
3013
Kenny Root9d45d1c2013-02-14 10:32:30 -08003014 inline bool isKeystoreUnlocked(State state) {
3015 switch (state) {
3016 case ::STATE_NO_ERROR:
3017 return true;
3018 case ::STATE_UNINITIALIZED:
3019 case ::STATE_LOCKED:
3020 return false;
3021 }
3022 return false;
Kenny Root07438c82012-11-02 15:41:02 -07003023 }
3024
Chad Brubaker67d2a502015-03-11 17:21:18 +00003025 bool isKeyTypeSupported(const keymaster1_device_t* device, keymaster_keypair_t keyType) {
Kenny Root1d448c02013-11-21 10:36:53 -08003026 const int32_t device_api = device->common.module->module_api_version;
3027 if (device_api == KEYMASTER_MODULE_API_VERSION_0_2) {
3028 switch (keyType) {
3029 case TYPE_RSA:
3030 case TYPE_DSA:
3031 case TYPE_EC:
3032 return true;
3033 default:
3034 return false;
3035 }
3036 } else if (device_api >= KEYMASTER_MODULE_API_VERSION_0_3) {
3037 switch (keyType) {
3038 case TYPE_RSA:
3039 return true;
3040 case TYPE_DSA:
3041 return device->flags & KEYMASTER_SUPPORTS_DSA;
3042 case TYPE_EC:
3043 return device->flags & KEYMASTER_SUPPORTS_EC;
3044 default:
3045 return false;
3046 }
3047 } else {
3048 return keyType == TYPE_RSA;
3049 }
3050 }
3051
Chad Brubaker0cf34a22015-04-23 11:06:16 -07003052 /**
3053 * Check that all keymaster_key_param_t's provided by the application are
3054 * allowed. Any parameter that keystore adds itself should be disallowed here.
3055 */
3056 bool checkAllowedOperationParams(const std::vector<keymaster_key_param_t>& params) {
3057 for (auto param: params) {
3058 switch (param.tag) {
3059 case KM_TAG_AUTH_TOKEN:
3060 return false;
3061 default:
3062 break;
3063 }
3064 }
3065 return true;
3066 }
3067
3068 keymaster_error_t getOperationCharacteristics(const keymaster_key_blob_t& key,
3069 const keymaster1_device_t* dev,
3070 const std::vector<keymaster_key_param_t>& params,
3071 keymaster_key_characteristics_t* out) {
3072 UniquePtr<keymaster_blob_t> appId;
3073 UniquePtr<keymaster_blob_t> appData;
3074 for (auto param : params) {
3075 if (param.tag == KM_TAG_APPLICATION_ID) {
3076 appId.reset(new keymaster_blob_t);
3077 appId->data = param.blob.data;
3078 appId->data_length = param.blob.data_length;
3079 } else if (param.tag == KM_TAG_APPLICATION_DATA) {
3080 appData.reset(new keymaster_blob_t);
3081 appData->data = param.blob.data;
3082 appData->data_length = param.blob.data_length;
3083 }
3084 }
3085 keymaster_key_characteristics_t* result = NULL;
3086 if (!dev->get_key_characteristics) {
3087 return KM_ERROR_UNIMPLEMENTED;
3088 }
3089 keymaster_error_t error = dev->get_key_characteristics(dev, &key, appId.get(),
3090 appData.get(), &result);
3091 if (result) {
3092 *out = *result;
3093 free(result);
3094 }
3095 return error;
3096 }
3097
3098 /**
3099 * Get the auth token for this operation from the auth token table.
3100 *
3101 * Returns ::NO_ERROR if the auth token was set or none was required.
3102 * ::OP_AUTH_NEEDED if it is a per op authorization, no
3103 * authorization token exists for that operation and
3104 * failOnTokenMissing is false.
3105 * KM_ERROR_KEY_USER_NOT_AUTHENTICATED if there is no valid auth
3106 * token for the operation
3107 */
3108 int32_t getAuthToken(const keymaster_key_characteristics_t* characteristics,
3109 keymaster_operation_handle_t handle,
Shawn Willdenb2ffa422015-06-17 12:18:55 -06003110 keymaster_purpose_t purpose,
Chad Brubaker0cf34a22015-04-23 11:06:16 -07003111 const hw_auth_token_t** authToken,
3112 bool failOnTokenMissing = true) {
3113
3114 std::vector<keymaster_key_param_t> allCharacteristics;
3115 for (size_t i = 0; i < characteristics->sw_enforced.length; i++) {
3116 allCharacteristics.push_back(characteristics->sw_enforced.params[i]);
3117 }
3118 for (size_t i = 0; i < characteristics->hw_enforced.length; i++) {
3119 allCharacteristics.push_back(characteristics->hw_enforced.params[i]);
3120 }
Shawn Willdenb2ffa422015-06-17 12:18:55 -06003121 keymaster::AuthTokenTable::Error err = mAuthTokenTable.FindAuthorization(
3122 allCharacteristics.data(), allCharacteristics.size(), purpose, handle, authToken);
Chad Brubaker0cf34a22015-04-23 11:06:16 -07003123 switch (err) {
3124 case keymaster::AuthTokenTable::OK:
3125 case keymaster::AuthTokenTable::AUTH_NOT_REQUIRED:
3126 return ::NO_ERROR;
3127 case keymaster::AuthTokenTable::AUTH_TOKEN_NOT_FOUND:
3128 case keymaster::AuthTokenTable::AUTH_TOKEN_EXPIRED:
3129 case keymaster::AuthTokenTable::AUTH_TOKEN_WRONG_SID:
3130 return KM_ERROR_KEY_USER_NOT_AUTHENTICATED;
3131 case keymaster::AuthTokenTable::OP_HANDLE_REQUIRED:
3132 return failOnTokenMissing ? (int32_t) KM_ERROR_KEY_USER_NOT_AUTHENTICATED :
3133 (int32_t) ::OP_AUTH_NEEDED;
3134 default:
3135 ALOGE("Unexpected FindAuthorization return value %d", err);
3136 return KM_ERROR_INVALID_ARGUMENT;
3137 }
3138 }
3139
3140 inline void addAuthToParams(std::vector<keymaster_key_param_t>* params,
3141 const hw_auth_token_t* token) {
3142 if (token) {
3143 params->push_back(keymaster_param_blob(KM_TAG_AUTH_TOKEN,
3144 reinterpret_cast<const uint8_t*>(token),
3145 sizeof(hw_auth_token_t)));
3146 }
3147 }
3148
3149 /**
3150 * Add the auth token for the operation to the param list if the operation
3151 * requires authorization. Uses the cached result in the OperationMap if available
3152 * otherwise gets the token from the AuthTokenTable and caches the result.
3153 *
3154 * Returns ::NO_ERROR if the auth token was added or not needed.
3155 * KM_ERROR_KEY_USER_NOT_AUTHENTICATED if the operation is not
3156 * authenticated.
3157 * KM_ERROR_INVALID_OPERATION_HANDLE if token is not a valid
3158 * operation token.
3159 */
3160 int32_t addOperationAuthTokenIfNeeded(sp<IBinder> token,
3161 std::vector<keymaster_key_param_t>* params) {
3162 const hw_auth_token_t* authToken = NULL;
Chad Brubaker7169a842015-04-29 19:58:34 -07003163 mOperationMap.getOperationAuthToken(token, &authToken);
3164 if (!authToken) {
Chad Brubaker0cf34a22015-04-23 11:06:16 -07003165 const keymaster1_device_t* dev;
3166 keymaster_operation_handle_t handle;
3167 const keymaster_key_characteristics_t* characteristics = NULL;
Shawn Willdenb2ffa422015-06-17 12:18:55 -06003168 keymaster_purpose_t purpose;
Shawn Willden9221bff2015-06-18 18:23:54 -06003169 keymaster::km_id_t keyid;
3170 if (!mOperationMap.getOperation(token, &handle, &keyid, &purpose, &dev,
3171 &characteristics)) {
Chad Brubaker0cf34a22015-04-23 11:06:16 -07003172 return KM_ERROR_INVALID_OPERATION_HANDLE;
3173 }
Shawn Willdenb2ffa422015-06-17 12:18:55 -06003174 int32_t result = getAuthToken(characteristics, handle, purpose, &authToken);
Chad Brubaker0cf34a22015-04-23 11:06:16 -07003175 if (result != ::NO_ERROR) {
3176 return result;
3177 }
3178 if (authToken) {
3179 mOperationMap.setOperationAuthToken(token, authToken);
3180 }
3181 }
3182 addAuthToParams(params, authToken);
3183 return ::NO_ERROR;
3184 }
3185
Chad Brubaker3a7d9e62015-06-04 15:01:46 -07003186 /**
3187 * Translate a result value to a legacy return value. All keystore errors are
3188 * preserved and keymaster errors become SYSTEM_ERRORs
3189 */
3190 inline int32_t translateResultToLegacyResult(int32_t result) {
3191 if (result > 0) {
3192 return result;
3193 }
3194 return ::SYSTEM_ERROR;
3195 }
3196
Chad Brubaker3a7d9e62015-06-04 15:01:46 -07003197 keymaster_key_param_t* getKeyAlgorithm(keymaster_key_characteristics_t* characteristics) {
3198 for (size_t i = 0; i < characteristics->hw_enforced.length; i++) {
3199 if (characteristics->hw_enforced.params[i].tag == KM_TAG_ALGORITHM) {
3200 return &characteristics->hw_enforced.params[i];
3201 }
3202 }
3203 for (size_t i = 0; i < characteristics->sw_enforced.length; i++) {
3204 if (characteristics->sw_enforced.params[i].tag == KM_TAG_ALGORITHM) {
3205 return &characteristics->sw_enforced.params[i];
3206 }
3207 }
3208 return NULL;
3209 }
3210
3211 void addLegacyBeginParams(const String16& name, std::vector<keymaster_key_param_t>& params) {
3212 // All legacy keys are DIGEST_NONE/PAD_NONE.
3213 params.push_back(keymaster_param_enum(KM_TAG_DIGEST, KM_DIGEST_NONE));
3214 params.push_back(keymaster_param_enum(KM_TAG_PADDING, KM_PAD_NONE));
3215
3216 // Look up the algorithm of the key.
3217 KeyCharacteristics characteristics;
3218 int32_t rc = getKeyCharacteristics(name, NULL, NULL, &characteristics);
3219 if (rc != ::NO_ERROR) {
3220 ALOGE("Failed to get key characteristics");
3221 return;
3222 }
3223 keymaster_key_param_t* algorithm = getKeyAlgorithm(&characteristics.characteristics);
3224 if (!algorithm) {
3225 ALOGE("getKeyCharacteristics did not include KM_TAG_ALGORITHM");
3226 return;
3227 }
3228 params.push_back(*algorithm);
3229 }
3230
3231 int32_t doLegacySignVerify(const String16& name, const uint8_t* data, size_t length,
3232 uint8_t** out, size_t* outLength, const uint8_t* signature,
3233 size_t signatureLength, keymaster_purpose_t purpose) {
3234
Chad Brubaker3a7d9e62015-06-04 15:01:46 -07003235 std::basic_stringstream<uint8_t> outBuffer;
3236 OperationResult result;
3237 KeymasterArguments inArgs;
3238 addLegacyBeginParams(name, inArgs.params);
3239 sp<IBinder> appToken(new BBinder);
3240 sp<IBinder> token;
3241
3242 begin(appToken, name, purpose, true, inArgs, NULL, 0, &result);
3243 if (result.resultCode != ResponseCode::NO_ERROR) {
Chad Brubakerdf705172015-06-17 20:17:51 -07003244 if (result.resultCode == ::KEY_NOT_FOUND) {
3245 ALOGW("Key not found");
3246 } else {
3247 ALOGW("Error in begin: %d", result.resultCode);
3248 }
Chad Brubaker3a7d9e62015-06-04 15:01:46 -07003249 return translateResultToLegacyResult(result.resultCode);
3250 }
3251 inArgs.params.clear();
3252 token = result.token;
3253 size_t consumed = 0;
3254 size_t lastConsumed = 0;
3255 do {
3256 update(token, inArgs, data + consumed, length - consumed, &result);
3257 if (result.resultCode != ResponseCode::NO_ERROR) {
3258 ALOGW("Error in update: %d", result.resultCode);
3259 return translateResultToLegacyResult(result.resultCode);
3260 }
3261 if (out) {
3262 outBuffer.write(result.data.get(), result.dataLength);
3263 }
3264 lastConsumed = result.inputConsumed;
3265 consumed += lastConsumed;
3266 } while (consumed < length && lastConsumed > 0);
3267
3268 if (consumed != length) {
3269 ALOGW("Not all data consumed. Consumed %zu of %zu", consumed, length);
3270 return ::SYSTEM_ERROR;
3271 }
3272
3273 finish(token, inArgs, signature, signatureLength, NULL, 0, &result);
3274 if (result.resultCode != ResponseCode::NO_ERROR) {
3275 ALOGW("Error in finish: %d", result.resultCode);
3276 return translateResultToLegacyResult(result.resultCode);
3277 }
3278 if (out) {
3279 outBuffer.write(result.data.get(), result.dataLength);
3280 }
3281
3282 if (out) {
3283 auto buf = outBuffer.str();
3284 *out = new uint8_t[buf.size()];
3285 memcpy(*out, buf.c_str(), buf.size());
3286 *outLength = buf.size();
3287 }
3288
3289 return ::NO_ERROR;
3290 }
3291
Kenny Root07438c82012-11-02 15:41:02 -07003292 ::KeyStore* mKeyStore;
Chad Brubaker40a1a9b2015-02-20 14:08:13 -08003293 OperationMap mOperationMap;
Chad Brubakerd80c7b42015-03-31 11:04:28 -07003294 keymaster::AuthTokenTable mAuthTokenTable;
Shawn Willden9221bff2015-06-18 18:23:54 -06003295 KeystoreKeymasterEnforcement enforcement_policy;
Kenny Root07438c82012-11-02 15:41:02 -07003296};
3297
3298}; // namespace android
Kenny Roota91203b2012-02-15 15:00:46 -08003299
3300int main(int argc, char* argv[]) {
Kenny Roota91203b2012-02-15 15:00:46 -08003301 if (argc < 2) {
3302 ALOGE("A directory must be specified!");
3303 return 1;
3304 }
3305 if (chdir(argv[1]) == -1) {
3306 ALOGE("chdir: %s: %s", argv[1], strerror(errno));
3307 return 1;
3308 }
3309
3310 Entropy entropy;
3311 if (!entropy.open()) {
3312 return 1;
3313 }
Kenny Root70e3a862012-02-15 17:20:23 -08003314
Chad Brubakerbd07a232015-06-01 10:44:27 -07003315 keymaster1_device_t* dev;
Kenny Root70e3a862012-02-15 17:20:23 -08003316 if (keymaster_device_initialize(&dev)) {
3317 ALOGE("keystore keymaster could not be initialized; exiting");
3318 return 1;
3319 }
3320
Chad Brubaker67d2a502015-03-11 17:21:18 +00003321 keymaster1_device_t* fallback;
Chad Brubakerfc18edc2015-01-12 15:17:18 -08003322 if (fallback_keymaster_device_initialize(&fallback)) {
3323 ALOGE("software keymaster could not be initialized; exiting");
3324 return 1;
3325 }
3326
Riley Spahneaabae92014-06-30 12:39:52 -07003327 ks_is_selinux_enabled = is_selinux_enabled();
3328 if (ks_is_selinux_enabled) {
3329 union selinux_callback cb;
3330 cb.func_log = selinux_log_callback;
3331 selinux_set_callback(SELINUX_CB_LOG, cb);
3332 if (getcon(&tctx) != 0) {
3333 ALOGE("SELinux: Could not acquire target context. Aborting keystore.\n");
3334 return -1;
3335 }
3336 } else {
3337 ALOGI("SELinux: Keystore SELinux is disabled.\n");
3338 }
3339
Chad Brubakerbd07a232015-06-01 10:44:27 -07003340 KeyStore keyStore(&entropy, dev, fallback);
Kenny Root655b9582013-04-04 08:37:42 -07003341 keyStore.initialize();
Kenny Root07438c82012-11-02 15:41:02 -07003342 android::sp<android::IServiceManager> sm = android::defaultServiceManager();
3343 android::sp<android::KeyStoreProxy> proxy = new android::KeyStoreProxy(&keyStore);
3344 android::status_t ret = sm->addService(android::String16("android.security.keystore"), proxy);
3345 if (ret != android::OK) {
3346 ALOGE("Couldn't register binder service!");
3347 return -1;
Kenny Roota91203b2012-02-15 15:00:46 -08003348 }
Kenny Root07438c82012-11-02 15:41:02 -07003349
3350 /*
3351 * We're the only thread in existence, so we're just going to process
3352 * Binder transaction as a single-threaded program.
3353 */
3354 android::IPCThreadState::self()->joinThreadPool();
Kenny Root70e3a862012-02-15 17:20:23 -08003355
3356 keymaster_device_release(dev);
Kenny Roota91203b2012-02-15 15:00:46 -08003357 return 1;
3358}