blob: 07212e99f419caf6dfec3ec937bb1294a59da3d7 [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 Willden7e8eabb2015-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 Willden7e8eabb2015-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 Willden7e8eabb2015-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 Willden7e8eabb2015-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 Willden7e8eabb2015-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 Willden7e8eabb2015-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 Willden7e8eabb2015-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 Willden7e8eabb2015-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 Willden7e8eabb2015-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 Willden7e8eabb2015-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);
Zhen Kong52415c52015-09-30 18:42:58 -07001340 if (rc != NO_ERROR) {
1341 return rc;
1342 }
1343
1344 rc = keyBlob->readBlob(filename, userState->getDecryptionKey(),
1345 userState->getState());
1346 if (rc != NO_ERROR) {
1347 return rc;
1348 }
Chad Brubaker3cc40122015-06-04 13:49:44 -07001349 }
1350
Kenny Rootd53bc922013-03-21 14:10:15 -07001351 if (type != TYPE_ANY && keyBlob->getType() != type) {
Kenny Root822c3a92012-03-23 16:34:39 -07001352 ALOGW("key found but type doesn't match: %d vs %d", keyBlob->getType(), type);
1353 return KEY_NOT_FOUND;
1354 }
1355
1356 return rc;
Kenny Roota91203b2012-02-15 15:00:46 -08001357 }
1358
Chad Brubaker72593ee2015-05-12 10:42:00 -07001359 ResponseCode put(const char* filename, Blob* keyBlob, uid_t userId) {
1360 UserState* userState = getUserState(userId);
Kenny Rootf9119d62013-04-03 09:22:15 -07001361 return keyBlob->writeBlob(filename, userState->getEncryptionKey(), userState->getState(),
1362 mEntropy);
Kenny Roota91203b2012-02-15 15:00:46 -08001363 }
1364
Chad Brubaker72593ee2015-05-12 10:42:00 -07001365 ResponseCode del(const char *filename, const BlobType type, uid_t userId) {
Robin Lee4b84fdc2014-09-24 11:56:57 +01001366 Blob keyBlob;
Chad Brubaker72593ee2015-05-12 10:42:00 -07001367 ResponseCode rc = get(filename, &keyBlob, type, userId);
Chad Brubakera9a17ee2015-07-17 13:43:24 -07001368 if (rc == ::VALUE_CORRUPTED) {
1369 // The file is corrupt, the best we can do is rm it.
1370 return (unlink(filename) && errno != ENOENT) ? ::SYSTEM_ERROR : ::NO_ERROR;
1371 }
Robin Lee4b84fdc2014-09-24 11:56:57 +01001372 if (rc != ::NO_ERROR) {
1373 return rc;
1374 }
1375
1376 if (keyBlob.getType() == ::TYPE_KEY_PAIR) {
Shawn Willden7e8eabb2015-07-28 11:06:00 -06001377 // A device doesn't have to implement delete_key.
1378 if (mDevice->delete_key != NULL && !keyBlob.isFallback()) {
1379 keymaster_key_blob_t blob = {keyBlob.getValue(),
1380 static_cast<size_t>(keyBlob.getLength())};
1381 if (mDevice->delete_key(mDevice, &blob)) {
Robin Lee4b84fdc2014-09-24 11:56:57 +01001382 rc = ::SYSTEM_ERROR;
1383 }
1384 }
1385 }
Chad Brubaker17d68b92015-02-05 22:04:16 -08001386 if (keyBlob.getType() == ::TYPE_KEYMASTER_10) {
1387 keymaster1_device_t* dev = getDeviceForBlob(keyBlob);
1388 if (dev->delete_key) {
1389 keymaster_key_blob_t blob;
1390 blob.key_material = keyBlob.getValue();
1391 blob.key_material_size = keyBlob.getLength();
1392 dev->delete_key(dev, &blob);
1393 }
1394 }
Robin Lee4b84fdc2014-09-24 11:56:57 +01001395 if (rc != ::NO_ERROR) {
1396 return rc;
1397 }
1398
1399 return (unlink(filename) && errno != ENOENT) ? ::SYSTEM_ERROR : ::NO_ERROR;
1400 }
1401
Chad Brubakere6c3bfa2015-05-12 15:18:26 -07001402 ResponseCode list(const android::String8& prefix, android::Vector<android::String16> *matches,
Chad Brubaker72593ee2015-05-12 10:42:00 -07001403 uid_t userId) {
Robin Lee4b84fdc2014-09-24 11:56:57 +01001404
Chad Brubaker72593ee2015-05-12 10:42:00 -07001405 UserState* userState = getUserState(userId);
Robin Lee4b84fdc2014-09-24 11:56:57 +01001406 size_t n = prefix.length();
1407
1408 DIR* dir = opendir(userState->getUserDirName());
1409 if (!dir) {
1410 ALOGW("can't open directory for user: %s", strerror(errno));
1411 return ::SYSTEM_ERROR;
1412 }
1413
1414 struct dirent* file;
1415 while ((file = readdir(dir)) != NULL) {
1416 // We only care about files.
1417 if (file->d_type != DT_REG) {
1418 continue;
1419 }
1420
1421 // Skip anything that starts with a "."
1422 if (file->d_name[0] == '.') {
1423 continue;
1424 }
1425
1426 if (!strncmp(prefix.string(), file->d_name, n)) {
1427 const char* p = &file->d_name[n];
1428 size_t plen = strlen(p);
1429
1430 size_t extra = decode_key_length(p, plen);
1431 char *match = (char*) malloc(extra + 1);
1432 if (match != NULL) {
1433 decode_key(match, p, plen);
1434 matches->push(android::String16(match, extra));
1435 free(match);
1436 } else {
1437 ALOGW("could not allocate match of size %zd", extra);
1438 }
1439 }
1440 }
1441 closedir(dir);
1442 return ::NO_ERROR;
1443 }
1444
Kenny Root07438c82012-11-02 15:41:02 -07001445 void addGrant(const char* filename, uid_t granteeUid) {
Kenny Root655b9582013-04-04 08:37:42 -07001446 const grant_t* existing = getGrant(filename, granteeUid);
1447 if (existing == NULL) {
1448 grant_t* grant = new grant_t;
Kenny Root07438c82012-11-02 15:41:02 -07001449 grant->uid = granteeUid;
Brian Carlstroma8c703d2012-07-17 14:43:46 -07001450 grant->filename = reinterpret_cast<const uint8_t*>(strdup(filename));
Kenny Root655b9582013-04-04 08:37:42 -07001451 mGrants.add(grant);
Kenny Root70e3a862012-02-15 17:20:23 -08001452 }
1453 }
1454
Kenny Root07438c82012-11-02 15:41:02 -07001455 bool removeGrant(const char* filename, uid_t granteeUid) {
Kenny Root655b9582013-04-04 08:37:42 -07001456 for (android::Vector<grant_t*>::iterator it(mGrants.begin());
1457 it != mGrants.end(); it++) {
1458 grant_t* grant = *it;
1459 if (grant->uid == granteeUid
1460 && !strcmp(reinterpret_cast<const char*>(grant->filename), filename)) {
1461 mGrants.erase(it);
1462 return true;
1463 }
Kenny Root70e3a862012-02-15 17:20:23 -08001464 }
Kenny Root70e3a862012-02-15 17:20:23 -08001465 return false;
1466 }
1467
Brian Carlstroma8c703d2012-07-17 14:43:46 -07001468 bool hasGrant(const char* filename, const uid_t uid) const {
1469 return getGrant(filename, uid) != NULL;
Kenny Root70e3a862012-02-15 17:20:23 -08001470 }
1471
Chad Brubaker72593ee2015-05-12 10:42:00 -07001472 ResponseCode importKey(const uint8_t* key, size_t keyLen, const char* filename, uid_t userId,
Kenny Rootf9119d62013-04-03 09:22:15 -07001473 int32_t flags) {
Shawn Willden7e8eabb2015-07-28 11:06:00 -06001474 Unique_PKCS8_PRIV_KEY_INFO pkcs8(d2i_PKCS8_PRIV_KEY_INFO(NULL, &key, keyLen));
1475 if (!pkcs8.get()) {
1476 return ::SYSTEM_ERROR;
1477 }
1478 Unique_EVP_PKEY pkey(EVP_PKCS82PKEY(pkcs8.get()));
1479 if (!pkey.get()) {
1480 return ::SYSTEM_ERROR;
1481 }
1482 int type = EVP_PKEY_type(pkey->type);
1483 android::KeymasterArguments params;
1484 add_legacy_key_authorizations(type, &params.params);
1485 switch (type) {
1486 case EVP_PKEY_RSA:
1487 params.params.push_back(keymaster_param_enum(KM_TAG_ALGORITHM, KM_ALGORITHM_RSA));
1488 break;
1489 case EVP_PKEY_EC:
1490 params.params.push_back(keymaster_param_enum(KM_TAG_ALGORITHM,
1491 KM_ALGORITHM_EC));
1492 break;
1493 default:
1494 ALOGW("Unsupported key type %d", type);
1495 return ::SYSTEM_ERROR;
Kenny Root822c3a92012-03-23 16:34:39 -07001496 }
1497
Shawn Willden7e8eabb2015-07-28 11:06:00 -06001498 std::vector<keymaster_key_param_t> opParams(params.params);
1499 const keymaster_key_param_set_t inParams = {opParams.data(), opParams.size()};
1500 keymaster_blob_t input = {key, keyLen};
1501 keymaster_key_blob_t blob = {nullptr, 0};
Kenny Root17208e02013-09-04 13:56:03 -07001502 bool isFallback = false;
Shawn Willden7e8eabb2015-07-28 11:06:00 -06001503 keymaster_error_t error = mDevice->import_key(mDevice, &inParams, KM_KEY_FORMAT_PKCS8,
1504 &input, &blob, NULL /* characteristics */);
1505 if (error != KM_ERROR_OK){
1506 ALOGE("Keymaster error %d importing key pair, falling back", error);
1507
Kenny Roota39da5a2014-09-25 13:07:24 -07001508 /*
Shawn Willden7e8eabb2015-07-28 11:06:00 -06001509 * There should be no way to get here. Fallback shouldn't ever really happen
1510 * because the main device may be many (SW, KM0/SW hybrid, KM1/SW hybrid), but it must
1511 * provide full support of the API. In any case, we'll do the fallback just for
1512 * consistency... and I suppose to cover for broken HW implementations.
Kenny Roota39da5a2014-09-25 13:07:24 -07001513 */
Shawn Willden7e8eabb2015-07-28 11:06:00 -06001514 error = mFallbackDevice->import_key(mFallbackDevice, &inParams, KM_KEY_FORMAT_PKCS8,
1515 &input, &blob, NULL /* characteristics */);
Kenny Roota39da5a2014-09-25 13:07:24 -07001516 isFallback = true;
Kenny Root17208e02013-09-04 13:56:03 -07001517
Shawn Willden7e8eabb2015-07-28 11:06:00 -06001518 if (error) {
1519 ALOGE("Keymaster error while importing key pair with fallback: %d", error);
Kenny Root17208e02013-09-04 13:56:03 -07001520 return SYSTEM_ERROR;
1521 }
Kenny Root822c3a92012-03-23 16:34:39 -07001522 }
1523
Shawn Willden7e8eabb2015-07-28 11:06:00 -06001524 Blob keyBlob(blob.key_material, blob.key_material_size, NULL, 0, TYPE_KEYMASTER_10);
1525 free(const_cast<uint8_t*>(blob.key_material));
Kenny Root822c3a92012-03-23 16:34:39 -07001526
Kenny Rootf9119d62013-04-03 09:22:15 -07001527 keyBlob.setEncrypted(flags & KEYSTORE_FLAG_ENCRYPTED);
Kenny Root17208e02013-09-04 13:56:03 -07001528 keyBlob.setFallback(isFallback);
Kenny Rootf9119d62013-04-03 09:22:15 -07001529
Chad Brubaker72593ee2015-05-12 10:42:00 -07001530 return put(filename, &keyBlob, userId);
Kenny Root822c3a92012-03-23 16:34:39 -07001531 }
1532
Kenny Root1b0e3932013-09-05 13:06:32 -07001533 bool isHardwareBacked(const android::String16& keyType) const {
1534 if (mDevice == NULL) {
1535 ALOGW("can't get keymaster device");
1536 return false;
1537 }
1538
1539 if (sRSAKeyType == keyType) {
1540 return (mDevice->flags & KEYMASTER_SOFTWARE_ONLY) == 0;
1541 } else {
1542 return (mDevice->flags & KEYMASTER_SOFTWARE_ONLY) == 0
1543 && (mDevice->common.module->module_api_version
1544 >= KEYMASTER_MODULE_API_VERSION_0_2);
1545 }
Kenny Root8ddf35a2013-03-29 11:15:50 -07001546 }
1547
Kenny Root655b9582013-04-04 08:37:42 -07001548 ResponseCode getKeyForName(Blob* keyBlob, const android::String8& keyName, const uid_t uid,
1549 const BlobType type) {
Kenny Root86b16e82013-09-09 11:15:54 -07001550 android::String8 filepath8(getKeyNameForUidWithDir(keyName, uid));
Chad Brubaker72593ee2015-05-12 10:42:00 -07001551 uid_t userId = get_user_id(uid);
Kenny Root655b9582013-04-04 08:37:42 -07001552
Chad Brubaker72593ee2015-05-12 10:42:00 -07001553 ResponseCode 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 // If this is one of the legacy UID->UID mappings, use it.
1559 uid_t euid = get_keystore_euid(uid);
1560 if (euid != uid) {
Kenny Root86b16e82013-09-09 11:15:54 -07001561 filepath8 = getKeyNameForUidWithDir(keyName, euid);
Chad Brubaker72593ee2015-05-12 10:42:00 -07001562 responseCode = get(filepath8.string(), keyBlob, type, userId);
Kenny Root655b9582013-04-04 08:37:42 -07001563 if (responseCode == NO_ERROR) {
1564 return responseCode;
1565 }
1566 }
1567
1568 // They might be using a granted key.
Kenny Root86b16e82013-09-09 11:15:54 -07001569 android::String8 filename8 = getKeyName(keyName);
Kenny Root655b9582013-04-04 08:37:42 -07001570 char* end;
Kenny Root86b16e82013-09-09 11:15:54 -07001571 strtoul(filename8.string(), &end, 10);
Kenny Root655b9582013-04-04 08:37:42 -07001572 if (end[0] != '_' || end[1] == 0) {
1573 return KEY_NOT_FOUND;
1574 }
Chad Brubaker72593ee2015-05-12 10:42:00 -07001575 filepath8 = android::String8::format("%s/%s", getUserState(userId)->getUserDirName(),
Kenny Root86b16e82013-09-09 11:15:54 -07001576 filename8.string());
Kenny Root655b9582013-04-04 08:37:42 -07001577 if (!hasGrant(filepath8.string(), uid)) {
1578 return responseCode;
1579 }
1580
1581 // It is a granted key. Try to load it.
Chad Brubaker72593ee2015-05-12 10:42:00 -07001582 return get(filepath8.string(), keyBlob, type, userId);
Kenny Root655b9582013-04-04 08:37:42 -07001583 }
1584
1585 /**
1586 * Returns any existing UserState or creates it if it doesn't exist.
1587 */
Chad Brubaker72593ee2015-05-12 10:42:00 -07001588 UserState* getUserState(uid_t userId) {
Kenny Root655b9582013-04-04 08:37:42 -07001589 for (android::Vector<UserState*>::iterator it(mMasterKeys.begin());
1590 it != mMasterKeys.end(); it++) {
1591 UserState* state = *it;
1592 if (state->getUserId() == userId) {
1593 return state;
1594 }
1595 }
1596
1597 UserState* userState = new UserState(userId);
1598 if (!userState->initialize()) {
1599 /* There's not much we can do if initialization fails. Trying to
1600 * unlock the keystore for that user will fail as well, so any
1601 * subsequent request for this user will just return SYSTEM_ERROR.
1602 */
1603 ALOGE("User initialization failed for %u; subsuquent operations will fail", userId);
1604 }
1605 mMasterKeys.add(userState);
1606 return userState;
1607 }
1608
1609 /**
Chad Brubaker72593ee2015-05-12 10:42:00 -07001610 * Returns any existing UserState or creates it if it doesn't exist.
1611 */
1612 UserState* getUserStateByUid(uid_t uid) {
1613 uid_t userId = get_user_id(uid);
1614 return getUserState(userId);
1615 }
1616
1617 /**
Kenny Root655b9582013-04-04 08:37:42 -07001618 * Returns NULL if the UserState doesn't already exist.
1619 */
Chad Brubaker72593ee2015-05-12 10:42:00 -07001620 const UserState* getUserState(uid_t userId) const {
Kenny Root655b9582013-04-04 08:37:42 -07001621 for (android::Vector<UserState*>::const_iterator it(mMasterKeys.begin());
1622 it != mMasterKeys.end(); it++) {
1623 UserState* state = *it;
1624 if (state->getUserId() == userId) {
1625 return state;
1626 }
1627 }
1628
1629 return NULL;
1630 }
1631
Chad Brubaker72593ee2015-05-12 10:42:00 -07001632 /**
1633 * Returns NULL if the UserState doesn't already exist.
1634 */
1635 const UserState* getUserStateByUid(uid_t uid) const {
1636 uid_t userId = get_user_id(uid);
1637 return getUserState(userId);
1638 }
1639
Kenny Roota91203b2012-02-15 15:00:46 -08001640private:
Kenny Root655b9582013-04-04 08:37:42 -07001641 static const char* sOldMasterKey;
1642 static const char* sMetaDataFile;
Kenny Root1b0e3932013-09-05 13:06:32 -07001643 static const android::String16 sRSAKeyType;
Kenny Roota91203b2012-02-15 15:00:46 -08001644 Entropy* mEntropy;
1645
Chad Brubaker67d2a502015-03-11 17:21:18 +00001646 keymaster1_device_t* mDevice;
1647 keymaster1_device_t* mFallbackDevice;
Kenny Root70e3a862012-02-15 17:20:23 -08001648
Kenny Root655b9582013-04-04 08:37:42 -07001649 android::Vector<UserState*> mMasterKeys;
Kenny Roota91203b2012-02-15 15:00:46 -08001650
Kenny Root655b9582013-04-04 08:37:42 -07001651 android::Vector<grant_t*> mGrants;
Kenny Roota91203b2012-02-15 15:00:46 -08001652
Kenny Root655b9582013-04-04 08:37:42 -07001653 typedef struct {
1654 uint32_t version;
1655 } keystore_metadata_t;
Kenny Roota91203b2012-02-15 15:00:46 -08001656
Kenny Root655b9582013-04-04 08:37:42 -07001657 keystore_metadata_t mMetaData;
Kenny Root70e3a862012-02-15 17:20:23 -08001658
Kenny Root655b9582013-04-04 08:37:42 -07001659 const grant_t* getGrant(const char* filename, uid_t uid) const {
1660 for (android::Vector<grant_t*>::const_iterator it(mGrants.begin());
1661 it != mGrants.end(); it++) {
1662 grant_t* grant = *it;
Kenny Root70e3a862012-02-15 17:20:23 -08001663 if (grant->uid == uid
Kenny Root655b9582013-04-04 08:37:42 -07001664 && !strcmp(reinterpret_cast<const char*>(grant->filename), filename)) {
Kenny Root70e3a862012-02-15 17:20:23 -08001665 return grant;
1666 }
1667 }
Kenny Root70e3a862012-02-15 17:20:23 -08001668 return NULL;
1669 }
1670
Kenny Root822c3a92012-03-23 16:34:39 -07001671 /**
1672 * Upgrade code. This will upgrade the key from the current version
1673 * to whatever is newest.
1674 */
Kenny Root655b9582013-04-04 08:37:42 -07001675 bool upgradeBlob(const char* filename, Blob* blob, const uint8_t oldVersion,
1676 const BlobType type, uid_t uid) {
Kenny Root822c3a92012-03-23 16:34:39 -07001677 bool updated = false;
1678 uint8_t version = oldVersion;
1679
1680 /* From V0 -> V1: All old types were unknown */
1681 if (version == 0) {
1682 ALOGV("upgrading to version 1 and setting type %d", type);
1683
1684 blob->setType(type);
1685 if (type == TYPE_KEY_PAIR) {
Kenny Root655b9582013-04-04 08:37:42 -07001686 importBlobAsKey(blob, filename, uid);
Kenny Root822c3a92012-03-23 16:34:39 -07001687 }
1688 version = 1;
1689 updated = true;
1690 }
1691
Kenny Rootf9119d62013-04-03 09:22:15 -07001692 /* From V1 -> V2: All old keys were encrypted */
1693 if (version == 1) {
1694 ALOGV("upgrading to version 2");
1695
1696 blob->setEncrypted(true);
1697 version = 2;
1698 updated = true;
1699 }
1700
Kenny Root822c3a92012-03-23 16:34:39 -07001701 /*
1702 * If we've updated, set the key blob to the right version
1703 * and write it.
Kenny Rootcfeae072013-04-04 08:39:57 -07001704 */
Kenny Root822c3a92012-03-23 16:34:39 -07001705 if (updated) {
1706 ALOGV("updated and writing file %s", filename);
1707 blob->setVersion(version);
Kenny Root822c3a92012-03-23 16:34:39 -07001708 }
Kenny Rootcfeae072013-04-04 08:39:57 -07001709
1710 return updated;
Kenny Root822c3a92012-03-23 16:34:39 -07001711 }
1712
1713 /**
1714 * Takes a blob that is an PEM-encoded RSA key as a byte array and
1715 * converts it to a DER-encoded PKCS#8 for import into a keymaster.
1716 * Then it overwrites the original blob with the new blob
1717 * format that is returned from the keymaster.
1718 */
Kenny Root655b9582013-04-04 08:37:42 -07001719 ResponseCode importBlobAsKey(Blob* blob, const char* filename, uid_t uid) {
Kenny Root822c3a92012-03-23 16:34:39 -07001720 // We won't even write to the blob directly with this BIO, so const_cast is okay.
1721 Unique_BIO b(BIO_new_mem_buf(const_cast<uint8_t*>(blob->getValue()), blob->getLength()));
1722 if (b.get() == NULL) {
1723 ALOGE("Problem instantiating BIO");
1724 return SYSTEM_ERROR;
1725 }
1726
1727 Unique_EVP_PKEY pkey(PEM_read_bio_PrivateKey(b.get(), NULL, NULL, NULL));
1728 if (pkey.get() == NULL) {
1729 ALOGE("Couldn't read old PEM file");
1730 return SYSTEM_ERROR;
1731 }
1732
1733 Unique_PKCS8_PRIV_KEY_INFO pkcs8(EVP_PKEY2PKCS8(pkey.get()));
1734 int len = i2d_PKCS8_PRIV_KEY_INFO(pkcs8.get(), NULL);
1735 if (len < 0) {
1736 ALOGE("Couldn't measure PKCS#8 length");
1737 return SYSTEM_ERROR;
1738 }
1739
Kenny Root70c98892013-02-07 09:10:36 -08001740 UniquePtr<unsigned char[]> pkcs8key(new unsigned char[len]);
1741 uint8_t* tmp = pkcs8key.get();
Kenny Root822c3a92012-03-23 16:34:39 -07001742 if (i2d_PKCS8_PRIV_KEY_INFO(pkcs8.get(), &tmp) != len) {
1743 ALOGE("Couldn't convert to PKCS#8");
1744 return SYSTEM_ERROR;
1745 }
1746
Chad Brubaker72593ee2015-05-12 10:42:00 -07001747 ResponseCode rc = importKey(pkcs8key.get(), len, filename, get_user_id(uid),
Kenny Rootf9119d62013-04-03 09:22:15 -07001748 blob->isEncrypted() ? KEYSTORE_FLAG_ENCRYPTED : KEYSTORE_FLAG_NONE);
Kenny Root822c3a92012-03-23 16:34:39 -07001749 if (rc != NO_ERROR) {
1750 return rc;
1751 }
1752
Kenny Root655b9582013-04-04 08:37:42 -07001753 return get(filename, blob, TYPE_KEY_PAIR, uid);
1754 }
1755
1756 void readMetaData() {
1757 int in = TEMP_FAILURE_RETRY(open(sMetaDataFile, O_RDONLY));
1758 if (in < 0) {
1759 return;
1760 }
1761 size_t fileLength = readFully(in, (uint8_t*) &mMetaData, sizeof(mMetaData));
1762 if (fileLength != sizeof(mMetaData)) {
1763 ALOGI("Metadata file is %zd bytes (%zd experted); upgrade?", fileLength,
1764 sizeof(mMetaData));
1765 }
1766 close(in);
1767 }
1768
1769 void writeMetaData() {
1770 const char* tmpFileName = ".metadata.tmp";
1771 int out = TEMP_FAILURE_RETRY(open(tmpFileName,
1772 O_WRONLY | O_TRUNC | O_CREAT, S_IRUSR | S_IWUSR));
1773 if (out < 0) {
1774 ALOGE("couldn't write metadata file: %s", strerror(errno));
1775 return;
1776 }
1777 size_t fileLength = writeFully(out, (uint8_t*) &mMetaData, sizeof(mMetaData));
1778 if (fileLength != sizeof(mMetaData)) {
1779 ALOGI("Could only write %zd bytes to metadata file (%zd expected)", fileLength,
1780 sizeof(mMetaData));
1781 }
1782 close(out);
1783 rename(tmpFileName, sMetaDataFile);
1784 }
1785
1786 bool upgradeKeystore() {
1787 bool upgraded = false;
1788
1789 if (mMetaData.version == 0) {
Chad Brubaker72593ee2015-05-12 10:42:00 -07001790 UserState* userState = getUserStateByUid(0);
Kenny Root655b9582013-04-04 08:37:42 -07001791
1792 // Initialize first so the directory is made.
1793 userState->initialize();
1794
1795 // Migrate the old .masterkey file to user 0.
1796 if (access(sOldMasterKey, R_OK) == 0) {
1797 if (rename(sOldMasterKey, userState->getMasterKeyFileName()) < 0) {
1798 ALOGE("couldn't migrate old masterkey: %s", strerror(errno));
1799 return false;
1800 }
1801 }
1802
1803 // Initialize again in case we had a key.
1804 userState->initialize();
1805
1806 // Try to migrate existing keys.
1807 DIR* dir = opendir(".");
1808 if (!dir) {
1809 // Give up now; maybe we can upgrade later.
1810 ALOGE("couldn't open keystore's directory; something is wrong");
1811 return false;
1812 }
1813
1814 struct dirent* file;
1815 while ((file = readdir(dir)) != NULL) {
1816 // We only care about files.
1817 if (file->d_type != DT_REG) {
1818 continue;
1819 }
1820
1821 // Skip anything that starts with a "."
1822 if (file->d_name[0] == '.') {
1823 continue;
1824 }
1825
1826 // Find the current file's user.
1827 char* end;
1828 unsigned long thisUid = strtoul(file->d_name, &end, 10);
1829 if (end[0] != '_' || end[1] == 0) {
1830 continue;
1831 }
Chad Brubaker72593ee2015-05-12 10:42:00 -07001832 UserState* otherUser = getUserStateByUid(thisUid);
Kenny Root655b9582013-04-04 08:37:42 -07001833 if (otherUser->getUserId() != 0) {
1834 unlinkat(dirfd(dir), file->d_name, 0);
1835 }
1836
1837 // Rename the file into user directory.
1838 DIR* otherdir = opendir(otherUser->getUserDirName());
1839 if (otherdir == NULL) {
1840 ALOGW("couldn't open user directory for rename");
1841 continue;
1842 }
1843 if (renameat(dirfd(dir), file->d_name, dirfd(otherdir), file->d_name) < 0) {
1844 ALOGW("couldn't rename blob: %s: %s", file->d_name, strerror(errno));
1845 }
1846 closedir(otherdir);
1847 }
1848 closedir(dir);
1849
1850 mMetaData.version = 1;
1851 upgraded = true;
1852 }
1853
1854 return upgraded;
Kenny Root822c3a92012-03-23 16:34:39 -07001855 }
Kenny Roota91203b2012-02-15 15:00:46 -08001856};
1857
Kenny Root655b9582013-04-04 08:37:42 -07001858const char* KeyStore::sOldMasterKey = ".masterkey";
1859const char* KeyStore::sMetaDataFile = ".metadata";
Kenny Root70e3a862012-02-15 17:20:23 -08001860
Kenny Root1b0e3932013-09-05 13:06:32 -07001861const android::String16 KeyStore::sRSAKeyType("RSA");
1862
Kenny Root07438c82012-11-02 15:41:02 -07001863namespace android {
1864class KeyStoreProxy : public BnKeystoreService, public IBinder::DeathRecipient {
1865public:
1866 KeyStoreProxy(KeyStore* keyStore)
Chad Brubaker40a1a9b2015-02-20 14:08:13 -08001867 : mKeyStore(keyStore),
1868 mOperationMap(this)
Kenny Root07438c82012-11-02 15:41:02 -07001869 {
Kenny Roota91203b2012-02-15 15:00:46 -08001870 }
Kenny Roota91203b2012-02-15 15:00:46 -08001871
Chad Brubaker40a1a9b2015-02-20 14:08:13 -08001872 void binderDied(const wp<IBinder>& who) {
1873 auto operations = mOperationMap.getOperationsForToken(who.unsafe_get());
1874 for (auto token: operations) {
1875 abort(token);
1876 }
Kenny Root822c3a92012-03-23 16:34:39 -07001877 }
Kenny Roota91203b2012-02-15 15:00:46 -08001878
Chad Brubakere6c3bfa2015-05-12 15:18:26 -07001879 int32_t getState(int32_t userId) {
1880 if (!checkBinderPermission(P_GET_STATE)) {
Kenny Root07438c82012-11-02 15:41:02 -07001881 return ::PERMISSION_DENIED;
Kenny Roota91203b2012-02-15 15:00:46 -08001882 }
Kenny Roota91203b2012-02-15 15:00:46 -08001883
Chad Brubakere6c3bfa2015-05-12 15:18:26 -07001884 return mKeyStore->getState(userId);
Kenny Root298e7b12012-03-26 13:54:44 -07001885 }
1886
Kenny Root07438c82012-11-02 15:41:02 -07001887 int32_t get(const String16& name, uint8_t** item, size_t* itemLength) {
Chad Brubaker9489b792015-04-14 11:01:45 -07001888 if (!checkBinderPermission(P_GET)) {
Kenny Root07438c82012-11-02 15:41:02 -07001889 return ::PERMISSION_DENIED;
Kenny Roota91203b2012-02-15 15:00:46 -08001890 }
Kenny Root07438c82012-11-02 15:41:02 -07001891
Chad Brubaker9489b792015-04-14 11:01:45 -07001892 uid_t callingUid = IPCThreadState::self()->getCallingUid();
Kenny Root07438c82012-11-02 15:41:02 -07001893 String8 name8(name);
Kenny Root07438c82012-11-02 15:41:02 -07001894 Blob keyBlob;
Nick Kralevich66dbf672014-06-30 17:09:14 +00001895
Kenny Root655b9582013-04-04 08:37:42 -07001896 ResponseCode responseCode = mKeyStore->getKeyForName(&keyBlob, name8, callingUid,
Kenny Root49468902013-03-19 13:41:33 -07001897 TYPE_GENERIC);
Kenny Root07438c82012-11-02 15:41:02 -07001898 if (responseCode != ::NO_ERROR) {
1899 *item = NULL;
1900 *itemLength = 0;
1901 return responseCode;
Kenny Roota91203b2012-02-15 15:00:46 -08001902 }
Kenny Roota91203b2012-02-15 15:00:46 -08001903
Kenny Root07438c82012-11-02 15:41:02 -07001904 *item = (uint8_t*) malloc(keyBlob.getLength());
1905 memcpy(*item, keyBlob.getValue(), keyBlob.getLength());
1906 *itemLength = keyBlob.getLength();
Kenny Roota91203b2012-02-15 15:00:46 -08001907
Kenny Root07438c82012-11-02 15:41:02 -07001908 return ::NO_ERROR;
Kenny Root70e3a862012-02-15 17:20:23 -08001909 }
1910
Kenny Rootf9119d62013-04-03 09:22:15 -07001911 int32_t insert(const String16& name, const uint8_t* item, size_t itemLength, int targetUid,
1912 int32_t flags) {
Chad Brubaker9489b792015-04-14 11:01:45 -07001913 targetUid = getEffectiveUid(targetUid);
1914 int32_t result = checkBinderPermissionAndKeystoreState(P_INSERT, targetUid,
1915 flags & KEYSTORE_FLAG_ENCRYPTED);
1916 if (result != ::NO_ERROR) {
1917 return result;
Kenny Rootb88c3eb2013-02-13 14:43:43 -08001918 }
1919
Kenny Root07438c82012-11-02 15:41:02 -07001920 String8 name8(name);
Kenny Root655b9582013-04-04 08:37:42 -07001921 String8 filename(mKeyStore->getKeyNameForUidWithDir(name8, targetUid));
Kenny Root07438c82012-11-02 15:41:02 -07001922
1923 Blob keyBlob(item, itemLength, NULL, 0, ::TYPE_GENERIC);
Kenny Rootee8068b2013-10-07 09:49:15 -07001924 keyBlob.setEncrypted(flags & KEYSTORE_FLAG_ENCRYPTED);
1925
Chad Brubaker72593ee2015-05-12 10:42:00 -07001926 return mKeyStore->put(filename.string(), &keyBlob, get_user_id(targetUid));
Kenny Root70e3a862012-02-15 17:20:23 -08001927 }
1928
Kenny Root49468902013-03-19 13:41:33 -07001929 int32_t del(const String16& name, int targetUid) {
Chad Brubaker9489b792015-04-14 11:01:45 -07001930 targetUid = getEffectiveUid(targetUid);
1931 if (!checkBinderPermission(P_DELETE, targetUid)) {
Kenny Root07438c82012-11-02 15:41:02 -07001932 return ::PERMISSION_DENIED;
1933 }
Kenny Root07438c82012-11-02 15:41:02 -07001934 String8 name8(name);
Kenny Root655b9582013-04-04 08:37:42 -07001935 String8 filename(mKeyStore->getKeyNameForUidWithDir(name8, targetUid));
Chad Brubaker72593ee2015-05-12 10:42:00 -07001936 return mKeyStore->del(filename.string(), ::TYPE_ANY, get_user_id(targetUid));
Kenny Root70e3a862012-02-15 17:20:23 -08001937 }
1938
Kenny Root49468902013-03-19 13:41:33 -07001939 int32_t exist(const String16& name, int targetUid) {
Chad Brubaker9489b792015-04-14 11:01:45 -07001940 targetUid = getEffectiveUid(targetUid);
1941 if (!checkBinderPermission(P_EXIST, targetUid)) {
Kenny Rootb88c3eb2013-02-13 14:43:43 -08001942 return ::PERMISSION_DENIED;
1943 }
1944
Kenny Root07438c82012-11-02 15:41:02 -07001945 String8 name8(name);
Kenny Root655b9582013-04-04 08:37:42 -07001946 String8 filename(mKeyStore->getKeyNameForUidWithDir(name8, targetUid));
Kenny Root70e3a862012-02-15 17:20:23 -08001947
Kenny Root655b9582013-04-04 08:37:42 -07001948 if (access(filename.string(), R_OK) == -1) {
Kenny Root07438c82012-11-02 15:41:02 -07001949 return (errno != ENOENT) ? ::SYSTEM_ERROR : ::KEY_NOT_FOUND;
1950 }
1951 return ::NO_ERROR;
Kenny Root70e3a862012-02-15 17:20:23 -08001952 }
1953
Chad Brubakere6c3bfa2015-05-12 15:18:26 -07001954 int32_t list(const String16& prefix, int targetUid, Vector<String16>* matches) {
Chad Brubaker9489b792015-04-14 11:01:45 -07001955 targetUid = getEffectiveUid(targetUid);
Chad Brubakere6c3bfa2015-05-12 15:18:26 -07001956 if (!checkBinderPermission(P_LIST, targetUid)) {
Kenny Root07438c82012-11-02 15:41:02 -07001957 return ::PERMISSION_DENIED;
1958 }
Kenny Root07438c82012-11-02 15:41:02 -07001959 const String8 prefix8(prefix);
Kenny Root655b9582013-04-04 08:37:42 -07001960 String8 filename(mKeyStore->getKeyNameForUid(prefix8, targetUid));
Kenny Root70e3a862012-02-15 17:20:23 -08001961
Chad Brubakere6c3bfa2015-05-12 15:18:26 -07001962 if (mKeyStore->list(filename, matches, get_user_id(targetUid)) != ::NO_ERROR) {
Robin Lee4b84fdc2014-09-24 11:56:57 +01001963 return ::SYSTEM_ERROR;
Kenny Root9a53d3e2012-08-14 10:47:54 -07001964 }
Kenny Root07438c82012-11-02 15:41:02 -07001965 return ::NO_ERROR;
Kenny Root70e3a862012-02-15 17:20:23 -08001966 }
1967
Kenny Root07438c82012-11-02 15:41:02 -07001968 int32_t reset() {
Chad Brubaker9489b792015-04-14 11:01:45 -07001969 if (!checkBinderPermission(P_RESET)) {
Kenny Root07438c82012-11-02 15:41:02 -07001970 return ::PERMISSION_DENIED;
1971 }
1972
Chad Brubaker9489b792015-04-14 11:01:45 -07001973 uid_t callingUid = IPCThreadState::self()->getCallingUid();
Chad Brubaker96d6d782015-05-07 10:19:40 -07001974 mKeyStore->resetUser(get_user_id(callingUid), false);
1975 return ::NO_ERROR;
Kenny Root70e3a862012-02-15 17:20:23 -08001976 }
1977
Chad Brubaker96d6d782015-05-07 10:19:40 -07001978 int32_t onUserPasswordChanged(int32_t userId, const String16& password) {
Chad Brubaker9489b792015-04-14 11:01:45 -07001979 if (!checkBinderPermission(P_PASSWORD)) {
Kenny Root07438c82012-11-02 15:41:02 -07001980 return ::PERMISSION_DENIED;
1981 }
Kenny Root70e3a862012-02-15 17:20:23 -08001982
Kenny Root07438c82012-11-02 15:41:02 -07001983 const String8 password8(password);
Chad Brubaker96d6d782015-05-07 10:19:40 -07001984 // Flush the auth token table to prevent stale tokens from sticking
1985 // around.
1986 mAuthTokenTable.Clear();
1987
1988 if (password.size() == 0) {
1989 ALOGI("Secure lockscreen for user %d removed, deleting encrypted entries", userId);
Chad Brubaker72593ee2015-05-12 10:42:00 -07001990 mKeyStore->resetUser(userId, true);
Chad Brubaker96d6d782015-05-07 10:19:40 -07001991 return ::NO_ERROR;
1992 } else {
Chad Brubaker72593ee2015-05-12 10:42:00 -07001993 switch (mKeyStore->getState(userId)) {
Chad Brubaker96d6d782015-05-07 10:19:40 -07001994 case ::STATE_UNINITIALIZED: {
1995 // generate master key, encrypt with password, write to file,
1996 // initialize mMasterKey*.
Chad Brubaker72593ee2015-05-12 10:42:00 -07001997 return mKeyStore->initializeUser(password8, userId);
Chad Brubaker96d6d782015-05-07 10:19:40 -07001998 }
1999 case ::STATE_NO_ERROR: {
2000 // rewrite master key with new password.
Chad Brubaker72593ee2015-05-12 10:42:00 -07002001 return mKeyStore->writeMasterKey(password8, userId);
Chad Brubaker96d6d782015-05-07 10:19:40 -07002002 }
2003 case ::STATE_LOCKED: {
2004 ALOGE("Changing user %d's password while locked, clearing old encryption",
2005 userId);
Chad Brubaker72593ee2015-05-12 10:42:00 -07002006 mKeyStore->resetUser(userId, true);
2007 return mKeyStore->initializeUser(password8, userId);
Chad Brubaker96d6d782015-05-07 10:19:40 -07002008 }
Kenny Root07438c82012-11-02 15:41:02 -07002009 }
Chad Brubaker96d6d782015-05-07 10:19:40 -07002010 return ::SYSTEM_ERROR;
Kenny Root07438c82012-11-02 15:41:02 -07002011 }
Kenny Root70e3a862012-02-15 17:20:23 -08002012 }
2013
Chad Brubakerc0f031a2015-05-12 10:43:10 -07002014 int32_t onUserAdded(int32_t userId, int32_t parentId) {
2015 if (!checkBinderPermission(P_USER_CHANGED)) {
2016 return ::PERMISSION_DENIED;
2017 }
2018
2019 // Sanity check that the new user has an empty keystore.
2020 if (!mKeyStore->isEmpty(userId)) {
2021 ALOGW("New user %d's keystore not empty. Clearing old entries.", userId);
2022 }
2023 // Unconditionally clear the keystore, just to be safe.
2024 mKeyStore->resetUser(userId, false);
Chad Brubakerc0f031a2015-05-12 10:43:10 -07002025 if (parentId != -1) {
Chad Brubaker410ba592015-09-09 20:34:09 -07002026 // This profile must share the same master key password as the parent
2027 // profile. Because the password of the parent profile is not known
2028 // here, the best we can do is copy the parent's master key and master
2029 // key file. This makes this profile use the same master key as the
2030 // parent profile, forever.
Chad Brubakerc0f031a2015-05-12 10:43:10 -07002031 return mKeyStore->copyMasterKey(parentId, userId);
2032 } else {
2033 return ::NO_ERROR;
2034 }
2035 }
2036
2037 int32_t onUserRemoved(int32_t userId) {
2038 if (!checkBinderPermission(P_USER_CHANGED)) {
2039 return ::PERMISSION_DENIED;
2040 }
2041
2042 mKeyStore->resetUser(userId, false);
2043 return ::NO_ERROR;
2044 }
2045
Chad Brubakere6c3bfa2015-05-12 15:18:26 -07002046 int32_t lock(int32_t userId) {
Chad Brubaker9489b792015-04-14 11:01:45 -07002047 if (!checkBinderPermission(P_LOCK)) {
Kenny Root07438c82012-11-02 15:41:02 -07002048 return ::PERMISSION_DENIED;
2049 }
Kenny Root70e3a862012-02-15 17:20:23 -08002050
Chad Brubaker72593ee2015-05-12 10:42:00 -07002051 State state = mKeyStore->getState(userId);
Kenny Root9d45d1c2013-02-14 10:32:30 -08002052 if (state != ::STATE_NO_ERROR) {
Kenny Root07438c82012-11-02 15:41:02 -07002053 ALOGD("calling lock in state: %d", state);
2054 return state;
2055 }
2056
Chad Brubaker72593ee2015-05-12 10:42:00 -07002057 mKeyStore->lock(userId);
Kenny Root07438c82012-11-02 15:41:02 -07002058 return ::NO_ERROR;
Kenny Root70e3a862012-02-15 17:20:23 -08002059 }
2060
Chad Brubaker96d6d782015-05-07 10:19:40 -07002061 int32_t unlock(int32_t userId, const String16& pw) {
Chad Brubaker9489b792015-04-14 11:01:45 -07002062 if (!checkBinderPermission(P_UNLOCK)) {
Kenny Root07438c82012-11-02 15:41:02 -07002063 return ::PERMISSION_DENIED;
2064 }
2065
Chad Brubaker72593ee2015-05-12 10:42:00 -07002066 State state = mKeyStore->getState(userId);
Kenny Root9d45d1c2013-02-14 10:32:30 -08002067 if (state != ::STATE_LOCKED) {
Chad Brubaker410ba592015-09-09 20:34:09 -07002068 switch (state) {
2069 case ::STATE_NO_ERROR:
2070 ALOGI("calling unlock when already unlocked, ignoring.");
2071 break;
2072 case ::STATE_UNINITIALIZED:
2073 ALOGE("unlock called on uninitialized keystore.");
2074 break;
2075 default:
2076 ALOGE("unlock called on keystore in unknown state: %d", state);
2077 break;
2078 }
Kenny Root07438c82012-11-02 15:41:02 -07002079 return state;
2080 }
2081
2082 const String8 password8(pw);
Chad Brubaker96d6d782015-05-07 10:19:40 -07002083 // read master key, decrypt with password, initialize mMasterKey*.
Chad Brubaker72593ee2015-05-12 10:42:00 -07002084 return mKeyStore->readMasterKey(password8, userId);
Kenny Root70e3a862012-02-15 17:20:23 -08002085 }
2086
Chad Brubakere6c3bfa2015-05-12 15:18:26 -07002087 bool isEmpty(int32_t userId) {
2088 if (!checkBinderPermission(P_IS_EMPTY)) {
2089 return false;
Kenny Root07438c82012-11-02 15:41:02 -07002090 }
Kenny Root70e3a862012-02-15 17:20:23 -08002091
Chad Brubakere6c3bfa2015-05-12 15:18:26 -07002092 return mKeyStore->isEmpty(userId);
Kenny Root70e3a862012-02-15 17:20:23 -08002093 }
2094
Kenny Root96427ba2013-08-16 14:02:41 -07002095 int32_t generate(const String16& name, int32_t targetUid, int32_t keyType, int32_t keySize,
2096 int32_t flags, Vector<sp<KeystoreArg> >* args) {
Chad Brubaker9489b792015-04-14 11:01:45 -07002097 targetUid = getEffectiveUid(targetUid);
2098 int32_t result = checkBinderPermissionAndKeystoreState(P_INSERT, targetUid,
2099 flags & KEYSTORE_FLAG_ENCRYPTED);
2100 if (result != ::NO_ERROR) {
2101 return result;
Kenny Root07438c82012-11-02 15:41:02 -07002102 }
Kenny Root07438c82012-11-02 15:41:02 -07002103
Chad Brubaker3a7d9e62015-06-04 15:01:46 -07002104 KeymasterArguments params;
Shawn Willden7e8eabb2015-07-28 11:06:00 -06002105 add_legacy_key_authorizations(keyType, &params.params);
Kenny Root07438c82012-11-02 15:41:02 -07002106
Chad Brubaker3a7d9e62015-06-04 15:01:46 -07002107 switch (keyType) {
2108 case EVP_PKEY_EC: {
2109 params.params.push_back(keymaster_param_enum(KM_TAG_ALGORITHM, KM_ALGORITHM_EC));
2110 if (keySize == -1) {
2111 keySize = EC_DEFAULT_KEY_SIZE;
2112 } else if (keySize < EC_MIN_KEY_SIZE || keySize > EC_MAX_KEY_SIZE) {
2113 ALOGI("invalid key size %d", keySize);
Kenny Root96427ba2013-08-16 14:02:41 -07002114 return ::SYSTEM_ERROR;
2115 }
Chad Brubaker3a7d9e62015-06-04 15:01:46 -07002116 params.params.push_back(keymaster_param_int(KM_TAG_KEY_SIZE, keySize));
2117 break;
Kenny Root96427ba2013-08-16 14:02:41 -07002118 }
Chad Brubaker3a7d9e62015-06-04 15:01:46 -07002119 case EVP_PKEY_RSA: {
2120 params.params.push_back(keymaster_param_enum(KM_TAG_ALGORITHM, KM_ALGORITHM_RSA));
2121 if (keySize == -1) {
2122 keySize = RSA_DEFAULT_KEY_SIZE;
2123 } else if (keySize < RSA_MIN_KEY_SIZE || keySize > RSA_MAX_KEY_SIZE) {
2124 ALOGI("invalid key size %d", keySize);
2125 return ::SYSTEM_ERROR;
Kenny Root96427ba2013-08-16 14:02:41 -07002126 }
Chad Brubaker3a7d9e62015-06-04 15:01:46 -07002127 params.params.push_back(keymaster_param_int(KM_TAG_KEY_SIZE, keySize));
2128 unsigned long exponent = RSA_DEFAULT_EXPONENT;
2129 if (args->size() > 1) {
2130 ALOGI("invalid number of arguments: %zu", args->size());
2131 return ::SYSTEM_ERROR;
2132 } else if (args->size() == 1) {
2133 sp<KeystoreArg> expArg = args->itemAt(0);
2134 if (expArg != NULL) {
2135 Unique_BIGNUM pubExpBn(
2136 BN_bin2bn(reinterpret_cast<const unsigned char*>(expArg->data()),
2137 expArg->size(), NULL));
2138 if (pubExpBn.get() == NULL) {
2139 ALOGI("Could not convert public exponent to BN");
2140 return ::SYSTEM_ERROR;
2141 }
2142 exponent = BN_get_word(pubExpBn.get());
2143 if (exponent == 0xFFFFFFFFL) {
2144 ALOGW("cannot represent public exponent as a long value");
2145 return ::SYSTEM_ERROR;
2146 }
2147 } else {
2148 ALOGW("public exponent not read");
2149 return ::SYSTEM_ERROR;
2150 }
2151 }
2152 params.params.push_back(keymaster_param_long(KM_TAG_RSA_PUBLIC_EXPONENT,
2153 exponent));
2154 break;
Kenny Root96427ba2013-08-16 14:02:41 -07002155 }
Chad Brubaker3a7d9e62015-06-04 15:01:46 -07002156 default: {
2157 ALOGW("Unsupported key type %d", keyType);
2158 return ::SYSTEM_ERROR;
2159 }
Kenny Root96427ba2013-08-16 14:02:41 -07002160 }
2161
Chad Brubaker3a7d9e62015-06-04 15:01:46 -07002162 int32_t rc = generateKey(name, params, NULL, 0, targetUid, flags,
2163 /*outCharacteristics*/ NULL);
2164 if (rc != ::NO_ERROR) {
2165 ALOGW("generate failed: %d", rc);
Kenny Root07438c82012-11-02 15:41:02 -07002166 }
Chad Brubaker3a7d9e62015-06-04 15:01:46 -07002167 return translateResultToLegacyResult(rc);
Kenny Root70e3a862012-02-15 17:20:23 -08002168 }
2169
Kenny Rootf9119d62013-04-03 09:22:15 -07002170 int32_t import(const String16& name, const uint8_t* data, size_t length, int targetUid,
2171 int32_t flags) {
Chad Brubaker3a7d9e62015-06-04 15:01:46 -07002172 const uint8_t* ptr = data;
Kenny Root07438c82012-11-02 15:41:02 -07002173
Chad Brubaker3a7d9e62015-06-04 15:01:46 -07002174 Unique_PKCS8_PRIV_KEY_INFO pkcs8(d2i_PKCS8_PRIV_KEY_INFO(NULL, &ptr, length));
2175 if (!pkcs8.get()) {
2176 return ::SYSTEM_ERROR;
2177 }
2178 Unique_EVP_PKEY pkey(EVP_PKCS82PKEY(pkcs8.get()));
2179 if (!pkey.get()) {
2180 return ::SYSTEM_ERROR;
2181 }
2182 int type = EVP_PKEY_type(pkey->type);
Shawn Willden2de8b752015-07-23 05:54:31 -06002183 KeymasterArguments params;
Shawn Willden7e8eabb2015-07-28 11:06:00 -06002184 add_legacy_key_authorizations(type, &params.params);
Chad Brubaker3a7d9e62015-06-04 15:01:46 -07002185 switch (type) {
2186 case EVP_PKEY_RSA:
2187 params.params.push_back(keymaster_param_enum(KM_TAG_ALGORITHM, KM_ALGORITHM_RSA));
2188 break;
2189 case EVP_PKEY_EC:
2190 params.params.push_back(keymaster_param_enum(KM_TAG_ALGORITHM,
2191 KM_ALGORITHM_EC));
2192 break;
2193 default:
2194 ALOGW("Unsupported key type %d", type);
2195 return ::SYSTEM_ERROR;
2196 }
2197 int32_t rc = importKey(name, params, KM_KEY_FORMAT_PKCS8, data, length, targetUid, flags,
2198 /*outCharacteristics*/ NULL);
2199 if (rc != ::NO_ERROR) {
2200 ALOGW("importKey failed: %d", rc);
2201 }
2202 return translateResultToLegacyResult(rc);
Kenny Root70e3a862012-02-15 17:20:23 -08002203 }
2204
Kenny Root07438c82012-11-02 15:41:02 -07002205 int32_t sign(const String16& name, const uint8_t* data, size_t length, uint8_t** out,
Chad Brubaker3a7d9e62015-06-04 15:01:46 -07002206 size_t* outLength) {
Chad Brubaker9489b792015-04-14 11:01:45 -07002207 if (!checkBinderPermission(P_SIGN)) {
Kenny Root07438c82012-11-02 15:41:02 -07002208 return ::PERMISSION_DENIED;
2209 }
Chad Brubaker3a7d9e62015-06-04 15:01:46 -07002210 return doLegacySignVerify(name, data, length, out, outLength, NULL, 0, KM_PURPOSE_SIGN);
Kenny Root70e3a862012-02-15 17:20:23 -08002211 }
2212
Kenny Root07438c82012-11-02 15:41:02 -07002213 int32_t verify(const String16& name, const uint8_t* data, size_t dataLength,
2214 const uint8_t* signature, size_t signatureLength) {
Chad Brubaker9489b792015-04-14 11:01:45 -07002215 if (!checkBinderPermission(P_VERIFY)) {
Kenny Root07438c82012-11-02 15:41:02 -07002216 return ::PERMISSION_DENIED;
2217 }
Chad Brubaker3a7d9e62015-06-04 15:01:46 -07002218 return doLegacySignVerify(name, data, dataLength, NULL, NULL, signature, signatureLength,
2219 KM_PURPOSE_VERIFY);
Kenny Roota91203b2012-02-15 15:00:46 -08002220 }
Kenny Root07438c82012-11-02 15:41:02 -07002221
2222 /*
2223 * TODO: The abstraction between things stored in hardware and regular blobs
2224 * of data stored on the filesystem should be moved down to keystore itself.
2225 * Unfortunately the Java code that calls this has naming conventions that it
2226 * knows about. Ideally keystore shouldn't be used to store random blobs of
2227 * data.
2228 *
2229 * Until that happens, it's necessary to have a separate "get_pubkey" and
2230 * "del_key" since the Java code doesn't really communicate what it's
2231 * intentions are.
2232 */
2233 int32_t get_pubkey(const String16& name, uint8_t** pubkey, size_t* pubkeyLength) {
Chad Brubaker3a7d9e62015-06-04 15:01:46 -07002234 ExportResult result;
2235 exportKey(name, KM_KEY_FORMAT_X509, NULL, NULL, &result);
2236 if (result.resultCode != ::NO_ERROR) {
2237 ALOGW("export failed: %d", result.resultCode);
2238 return translateResultToLegacyResult(result.resultCode);
Kenny Root07438c82012-11-02 15:41:02 -07002239 }
Kenny Root07438c82012-11-02 15:41:02 -07002240
Chad Brubaker3a7d9e62015-06-04 15:01:46 -07002241 *pubkey = result.exportData.release();
2242 *pubkeyLength = result.dataLength;
Kenny Root07438c82012-11-02 15:41:02 -07002243 return ::NO_ERROR;
Kenny Roota91203b2012-02-15 15:00:46 -08002244 }
Kenny Root07438c82012-11-02 15:41:02 -07002245
Kenny Root07438c82012-11-02 15:41:02 -07002246 int32_t grant(const String16& name, int32_t granteeUid) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08002247 uid_t callingUid = IPCThreadState::self()->getCallingUid();
Chad Brubaker9489b792015-04-14 11:01:45 -07002248 int32_t result = checkBinderPermissionAndKeystoreState(P_GRANT);
2249 if (result != ::NO_ERROR) {
2250 return result;
Kenny Root07438c82012-11-02 15:41:02 -07002251 }
2252
2253 String8 name8(name);
Kenny Root655b9582013-04-04 08:37:42 -07002254 String8 filename(mKeyStore->getKeyNameForUidWithDir(name8, callingUid));
Kenny Root07438c82012-11-02 15:41:02 -07002255
Kenny Root655b9582013-04-04 08:37:42 -07002256 if (access(filename.string(), R_OK) == -1) {
Kenny Root07438c82012-11-02 15:41:02 -07002257 return (errno != ENOENT) ? ::SYSTEM_ERROR : ::KEY_NOT_FOUND;
2258 }
2259
Kenny Root655b9582013-04-04 08:37:42 -07002260 mKeyStore->addGrant(filename.string(), granteeUid);
Kenny Root07438c82012-11-02 15:41:02 -07002261 return ::NO_ERROR;
2262 }
2263
2264 int32_t ungrant(const String16& name, int32_t granteeUid) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08002265 uid_t callingUid = IPCThreadState::self()->getCallingUid();
Chad Brubaker9489b792015-04-14 11:01:45 -07002266 int32_t result = checkBinderPermissionAndKeystoreState(P_GRANT);
2267 if (result != ::NO_ERROR) {
2268 return result;
Kenny Root07438c82012-11-02 15:41:02 -07002269 }
2270
2271 String8 name8(name);
Kenny Root655b9582013-04-04 08:37:42 -07002272 String8 filename(mKeyStore->getKeyNameForUidWithDir(name8, callingUid));
Kenny Root07438c82012-11-02 15:41:02 -07002273
Kenny Root655b9582013-04-04 08:37:42 -07002274 if (access(filename.string(), R_OK) == -1) {
Kenny Root07438c82012-11-02 15:41:02 -07002275 return (errno != ENOENT) ? ::SYSTEM_ERROR : ::KEY_NOT_FOUND;
2276 }
2277
Kenny Root655b9582013-04-04 08:37:42 -07002278 return mKeyStore->removeGrant(filename.string(), granteeUid) ? ::NO_ERROR : ::KEY_NOT_FOUND;
Kenny Root07438c82012-11-02 15:41:02 -07002279 }
2280
2281 int64_t getmtime(const String16& name) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08002282 uid_t callingUid = IPCThreadState::self()->getCallingUid();
Chad Brubaker9489b792015-04-14 11:01:45 -07002283 if (!checkBinderPermission(P_GET)) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08002284 ALOGW("permission denied for %d: getmtime", callingUid);
Kenny Root36a9e232013-02-04 14:24:15 -08002285 return -1L;
Kenny Root07438c82012-11-02 15:41:02 -07002286 }
Kenny Root07438c82012-11-02 15:41:02 -07002287
2288 String8 name8(name);
Kenny Root655b9582013-04-04 08:37:42 -07002289 String8 filename(mKeyStore->getKeyNameForUidWithDir(name8, callingUid));
Kenny Root07438c82012-11-02 15:41:02 -07002290
Kenny Root655b9582013-04-04 08:37:42 -07002291 if (access(filename.string(), R_OK) == -1) {
2292 ALOGW("could not access %s for getmtime", filename.string());
Kenny Root36a9e232013-02-04 14:24:15 -08002293 return -1L;
Kenny Root07438c82012-11-02 15:41:02 -07002294 }
2295
Kenny Root655b9582013-04-04 08:37:42 -07002296 int fd = TEMP_FAILURE_RETRY(open(filename.string(), O_NOFOLLOW, O_RDONLY));
Kenny Root07438c82012-11-02 15:41:02 -07002297 if (fd < 0) {
Kenny Root655b9582013-04-04 08:37:42 -07002298 ALOGW("could not open %s for getmtime", filename.string());
Kenny Root36a9e232013-02-04 14:24:15 -08002299 return -1L;
Kenny Root07438c82012-11-02 15:41:02 -07002300 }
2301
2302 struct stat s;
2303 int ret = fstat(fd, &s);
2304 close(fd);
2305 if (ret == -1) {
Kenny Root655b9582013-04-04 08:37:42 -07002306 ALOGW("could not stat %s for getmtime", filename.string());
Kenny Root36a9e232013-02-04 14:24:15 -08002307 return -1L;
Kenny Root07438c82012-11-02 15:41:02 -07002308 }
2309
Kenny Root36a9e232013-02-04 14:24:15 -08002310 return static_cast<int64_t>(s.st_mtime);
Kenny Root07438c82012-11-02 15:41:02 -07002311 }
2312
Kenny Rootd53bc922013-03-21 14:10:15 -07002313 int32_t duplicate(const String16& srcKey, int32_t srcUid, const String16& destKey,
2314 int32_t destUid) {
Kenny Root02254072013-03-20 11:48:19 -07002315 uid_t callingUid = IPCThreadState::self()->getCallingUid();
Riley Spahneaabae92014-06-30 12:39:52 -07002316 pid_t spid = IPCThreadState::self()->getCallingPid();
2317 if (!has_permission(callingUid, P_DUPLICATE, spid)) {
Kenny Rootd53bc922013-03-21 14:10:15 -07002318 ALOGW("permission denied for %d: duplicate", callingUid);
Kenny Root02254072013-03-20 11:48:19 -07002319 return -1L;
2320 }
2321
Chad Brubaker72593ee2015-05-12 10:42:00 -07002322 State state = mKeyStore->getState(get_user_id(callingUid));
Kenny Root02254072013-03-20 11:48:19 -07002323 if (!isKeystoreUnlocked(state)) {
Kenny Rootd53bc922013-03-21 14:10:15 -07002324 ALOGD("calling duplicate in state: %d", state);
Kenny Root02254072013-03-20 11:48:19 -07002325 return state;
2326 }
2327
Kenny Rootd53bc922013-03-21 14:10:15 -07002328 if (srcUid == -1 || static_cast<uid_t>(srcUid) == callingUid) {
2329 srcUid = callingUid;
2330 } else if (!is_granted_to(callingUid, srcUid)) {
2331 ALOGD("migrate not granted from source: %d -> %d", callingUid, srcUid);
Kenny Root02254072013-03-20 11:48:19 -07002332 return ::PERMISSION_DENIED;
2333 }
2334
Kenny Rootd53bc922013-03-21 14:10:15 -07002335 if (destUid == -1) {
2336 destUid = callingUid;
2337 }
2338
2339 if (srcUid != destUid) {
2340 if (static_cast<uid_t>(srcUid) != callingUid) {
2341 ALOGD("can only duplicate from caller to other or to same uid: "
2342 "calling=%d, srcUid=%d, destUid=%d", callingUid, srcUid, destUid);
2343 return ::PERMISSION_DENIED;
2344 }
2345
2346 if (!is_granted_to(callingUid, destUid)) {
2347 ALOGD("duplicate not granted to dest: %d -> %d", callingUid, destUid);
2348 return ::PERMISSION_DENIED;
2349 }
2350 }
2351
2352 String8 source8(srcKey);
Kenny Root655b9582013-04-04 08:37:42 -07002353 String8 sourceFile(mKeyStore->getKeyNameForUidWithDir(source8, srcUid));
Kenny Root02254072013-03-20 11:48:19 -07002354
Kenny Rootd53bc922013-03-21 14:10:15 -07002355 String8 target8(destKey);
Kenny Rootfa27d5b2013-10-15 09:01:08 -07002356 String8 targetFile(mKeyStore->getKeyNameForUidWithDir(target8, destUid));
Kenny Root02254072013-03-20 11:48:19 -07002357
Kenny Root655b9582013-04-04 08:37:42 -07002358 if (access(targetFile.string(), W_OK) != -1 || errno != ENOENT) {
2359 ALOGD("destination already exists: %s", targetFile.string());
Kenny Root02254072013-03-20 11:48:19 -07002360 return ::SYSTEM_ERROR;
2361 }
2362
Kenny Rootd53bc922013-03-21 14:10:15 -07002363 Blob keyBlob;
Kenny Root655b9582013-04-04 08:37:42 -07002364 ResponseCode responseCode = mKeyStore->get(sourceFile.string(), &keyBlob, TYPE_ANY,
Chad Brubaker72593ee2015-05-12 10:42:00 -07002365 get_user_id(srcUid));
Kenny Rootd53bc922013-03-21 14:10:15 -07002366 if (responseCode != ::NO_ERROR) {
2367 return responseCode;
Kenny Root02254072013-03-20 11:48:19 -07002368 }
Kenny Rootd53bc922013-03-21 14:10:15 -07002369
Chad Brubaker72593ee2015-05-12 10:42:00 -07002370 return mKeyStore->put(targetFile.string(), &keyBlob, get_user_id(destUid));
Kenny Root02254072013-03-20 11:48:19 -07002371 }
2372
Kenny Root1b0e3932013-09-05 13:06:32 -07002373 int32_t is_hardware_backed(const String16& keyType) {
2374 return mKeyStore->isHardwareBacked(keyType) ? 1 : 0;
Kenny Root8ddf35a2013-03-29 11:15:50 -07002375 }
2376
Kenny Rootfa27d5b2013-10-15 09:01:08 -07002377 int32_t clear_uid(int64_t targetUid64) {
Chad Brubaker9489b792015-04-14 11:01:45 -07002378 uid_t targetUid = getEffectiveUid(targetUid64);
Chad Brubakerb37a5232015-05-01 10:21:27 -07002379 if (!checkBinderPermissionSelfOrSystem(P_CLEAR_UID, targetUid)) {
Kenny Roota9bb5492013-04-01 16:29:11 -07002380 return ::PERMISSION_DENIED;
2381 }
2382
Robin Lee4b84fdc2014-09-24 11:56:57 +01002383 String8 prefix = String8::format("%u_", targetUid);
2384 Vector<String16> aliases;
Chad Brubakere6c3bfa2015-05-12 15:18:26 -07002385 if (mKeyStore->list(prefix, &aliases, get_user_id(targetUid)) != ::NO_ERROR) {
Kenny Roota9bb5492013-04-01 16:29:11 -07002386 return ::SYSTEM_ERROR;
2387 }
2388
Robin Lee4b84fdc2014-09-24 11:56:57 +01002389 for (uint32_t i = 0; i < aliases.size(); i++) {
2390 String8 name8(aliases[i]);
2391 String8 filename(mKeyStore->getKeyNameForUidWithDir(name8, targetUid));
Chad Brubaker72593ee2015-05-12 10:42:00 -07002392 mKeyStore->del(filename.string(), ::TYPE_ANY, get_user_id(targetUid));
Kenny Roota9bb5492013-04-01 16:29:11 -07002393 }
Robin Lee4b84fdc2014-09-24 11:56:57 +01002394 return ::NO_ERROR;
Kenny Roota9bb5492013-04-01 16:29:11 -07002395 }
2396
Chad Brubaker9c8612c2015-02-09 11:32:54 -08002397 int32_t addRngEntropy(const uint8_t* data, size_t dataLength) {
2398 const keymaster1_device_t* device = mKeyStore->getDevice();
2399 const keymaster1_device_t* fallback = mKeyStore->getFallbackDevice();
2400 int32_t devResult = KM_ERROR_UNIMPLEMENTED;
2401 int32_t fallbackResult = KM_ERROR_UNIMPLEMENTED;
2402 if (device->common.module->module_api_version >= KEYMASTER_MODULE_API_VERSION_1_0 &&
2403 device->add_rng_entropy != NULL) {
2404 devResult = device->add_rng_entropy(device, data, dataLength);
2405 }
2406 if (fallback->add_rng_entropy) {
2407 fallbackResult = fallback->add_rng_entropy(fallback, data, dataLength);
2408 }
2409 if (devResult) {
2410 return devResult;
2411 }
2412 if (fallbackResult) {
2413 return fallbackResult;
2414 }
2415 return ::NO_ERROR;
Chad Brubaker9899d6b2015-02-03 13:03:00 -08002416 }
2417
Chad Brubaker17d68b92015-02-05 22:04:16 -08002418 int32_t generateKey(const String16& name, const KeymasterArguments& params,
Chad Brubaker154d7692015-03-27 13:59:31 -07002419 const uint8_t* entropy, size_t entropyLength, int uid, int flags,
2420 KeyCharacteristics* outCharacteristics) {
Chad Brubaker9489b792015-04-14 11:01:45 -07002421 uid = getEffectiveUid(uid);
2422 int rc = checkBinderPermissionAndKeystoreState(P_INSERT, uid,
2423 flags & KEYSTORE_FLAG_ENCRYPTED);
2424 if (rc != ::NO_ERROR) {
2425 return rc;
Chad Brubaker17d68b92015-02-05 22:04:16 -08002426 }
2427
Chad Brubaker9489b792015-04-14 11:01:45 -07002428 rc = KM_ERROR_UNIMPLEMENTED;
Chad Brubaker17d68b92015-02-05 22:04:16 -08002429 bool isFallback = false;
2430 keymaster_key_blob_t blob;
2431 keymaster_key_characteristics_t *out = NULL;
2432
2433 const keymaster1_device_t* device = mKeyStore->getDevice();
2434 const keymaster1_device_t* fallback = mKeyStore->getFallbackDevice();
Chad Brubaker57e106d2015-06-01 12:59:00 -07002435 std::vector<keymaster_key_param_t> opParams(params.params);
Mao Licf9eced2015-12-07 20:14:55 +08002436
2437 for (auto param: params.params)
2438 {
2439 switch (param.tag) {
2440 case KM_TAG_SOTER_AUTO_SIGNED_COMMON_KEY_WHEN_GET_PUBLIC_KEY:
2441 {
2442 uid_t callingUid = IPCThreadState::self()->getCallingUid();
2443 Blob keyBlob;
AnilKumar Chimata0739cd52016-02-17 14:57:35 +05302444 String8 name8(reinterpret_cast<const char*>(param.blob.data),
2445 param.blob.data_length);
Mao Licf9eced2015-12-07 20:14:55 +08002446 ResponseCode responseCode = mKeyStore->getKeyForName(&keyBlob,
2447 name8, callingUid, TYPE_KEYMASTER_10);
2448 if (responseCode != ::NO_ERROR) {
2449 return responseCode;
2450 }
2451 opParams.push_back(keymaster_param_blob(
2452 KM_TAG_SOTER_AUTO_SIGNED_COMMON_KEY_WHEN_GET_PUBLIC_KEY_BLOB,
2453 keyBlob.getValue(),
2454 keyBlob.getLength()));
2455 break;
2456 }
2457 default:
2458 break;
2459 }
2460 }
2461
Chad Brubaker57e106d2015-06-01 12:59:00 -07002462 const keymaster_key_param_set_t inParams = {opParams.data(), opParams.size()};
Chad Brubaker17d68b92015-02-05 22:04:16 -08002463 if (device == NULL) {
2464 return ::SYSTEM_ERROR;
2465 }
Chad Brubaker154d7692015-03-27 13:59:31 -07002466 // TODO: Seed from Linux RNG before this.
Chad Brubaker17d68b92015-02-05 22:04:16 -08002467 if (device->common.module->module_api_version >= KEYMASTER_MODULE_API_VERSION_1_0 &&
2468 device->generate_key != NULL) {
Chad Brubaker154d7692015-03-27 13:59:31 -07002469 if (!entropy) {
2470 rc = KM_ERROR_OK;
2471 } else if (device->add_rng_entropy) {
2472 rc = device->add_rng_entropy(device, entropy, entropyLength);
2473 } else {
2474 rc = KM_ERROR_UNIMPLEMENTED;
2475 }
2476 if (rc == KM_ERROR_OK) {
Chad Brubaker57e106d2015-06-01 12:59:00 -07002477 rc = device->generate_key(device, &inParams, &blob, &out);
Chad Brubaker154d7692015-03-27 13:59:31 -07002478 }
Chad Brubaker17d68b92015-02-05 22:04:16 -08002479 }
2480 // If the HW device didn't support generate_key or generate_key failed
2481 // fall back to the software implementation.
2482 if (rc && fallback->generate_key != NULL) {
Shawn Willden7e8eabb2015-07-28 11:06:00 -06002483 ALOGW("Primary keymaster device failed to generate key, falling back to SW.");
Chad Brubaker17d68b92015-02-05 22:04:16 -08002484 isFallback = true;
Chad Brubaker154d7692015-03-27 13:59:31 -07002485 if (!entropy) {
2486 rc = KM_ERROR_OK;
2487 } else if (fallback->add_rng_entropy) {
2488 rc = fallback->add_rng_entropy(fallback, entropy, entropyLength);
2489 } else {
2490 rc = KM_ERROR_UNIMPLEMENTED;
2491 }
2492 if (rc == KM_ERROR_OK) {
Chad Brubaker57e106d2015-06-01 12:59:00 -07002493 rc = fallback->generate_key(fallback, &inParams, &blob, &out);
Chad Brubaker154d7692015-03-27 13:59:31 -07002494 }
Chad Brubaker17d68b92015-02-05 22:04:16 -08002495 }
2496
2497 if (out) {
2498 if (outCharacteristics) {
2499 outCharacteristics->characteristics = *out;
2500 } else {
2501 keymaster_free_characteristics(out);
2502 }
2503 free(out);
2504 }
2505
2506 if (rc) {
2507 return rc;
2508 }
2509
2510 String8 name8(name);
2511 String8 filename(mKeyStore->getKeyNameForUidWithDir(name8, uid));
2512
2513 Blob keyBlob(blob.key_material, blob.key_material_size, NULL, 0, ::TYPE_KEYMASTER_10);
2514 keyBlob.setFallback(isFallback);
2515 keyBlob.setEncrypted(flags & KEYSTORE_FLAG_ENCRYPTED);
2516
2517 free(const_cast<uint8_t*>(blob.key_material));
2518
Chad Brubaker72593ee2015-05-12 10:42:00 -07002519 return mKeyStore->put(filename.string(), &keyBlob, get_user_id(uid));
Chad Brubaker9899d6b2015-02-03 13:03:00 -08002520 }
2521
Chad Brubakerf3f071f2015-02-10 19:38:51 -08002522 int32_t getKeyCharacteristics(const String16& name,
Chad Brubakerd6634422015-03-21 22:36:07 -07002523 const keymaster_blob_t* clientId,
2524 const keymaster_blob_t* appData,
Chad Brubakerf3f071f2015-02-10 19:38:51 -08002525 KeyCharacteristics* outCharacteristics) {
Chad Brubakerf3f071f2015-02-10 19:38:51 -08002526 if (!outCharacteristics) {
2527 return KM_ERROR_UNEXPECTED_NULL_POINTER;
2528 }
2529
2530 uid_t callingUid = IPCThreadState::self()->getCallingUid();
2531
2532 Blob keyBlob;
2533 String8 name8(name);
2534 int rc;
2535
2536 ResponseCode responseCode = mKeyStore->getKeyForName(&keyBlob, name8, callingUid,
2537 TYPE_KEYMASTER_10);
2538 if (responseCode != ::NO_ERROR) {
2539 return responseCode;
2540 }
2541 keymaster_key_blob_t key;
2542 key.key_material_size = keyBlob.getLength();
2543 key.key_material = keyBlob.getValue();
2544 keymaster1_device_t* dev = mKeyStore->getDeviceForBlob(keyBlob);
2545 keymaster_key_characteristics_t *out = NULL;
2546 if (!dev->get_key_characteristics) {
2547 ALOGW("device does not implement get_key_characteristics");
2548 return KM_ERROR_UNIMPLEMENTED;
2549 }
Chad Brubakerd6634422015-03-21 22:36:07 -07002550 rc = dev->get_key_characteristics(dev, &key, clientId, appData, &out);
Chad Brubakerf3f071f2015-02-10 19:38:51 -08002551 if (out) {
2552 outCharacteristics->characteristics = *out;
2553 free(out);
2554 }
2555 return rc ? rc : ::NO_ERROR;
Chad Brubaker9899d6b2015-02-03 13:03:00 -08002556 }
2557
Chad Brubaker4c353cb2015-02-11 14:36:11 -08002558 int32_t importKey(const String16& name, const KeymasterArguments& params,
2559 keymaster_key_format_t format, const uint8_t *keyData,
2560 size_t keyLength, int uid, int flags,
2561 KeyCharacteristics* outCharacteristics) {
Chad Brubaker9489b792015-04-14 11:01:45 -07002562 uid = getEffectiveUid(uid);
2563 int rc = checkBinderPermissionAndKeystoreState(P_INSERT, uid,
2564 flags & KEYSTORE_FLAG_ENCRYPTED);
2565 if (rc != ::NO_ERROR) {
2566 return rc;
Chad Brubaker4c353cb2015-02-11 14:36:11 -08002567 }
2568
Chad Brubaker9489b792015-04-14 11:01:45 -07002569 rc = KM_ERROR_UNIMPLEMENTED;
Chad Brubaker4c353cb2015-02-11 14:36:11 -08002570 bool isFallback = false;
2571 keymaster_key_blob_t blob;
2572 keymaster_key_characteristics_t *out = NULL;
2573
2574 const keymaster1_device_t* device = mKeyStore->getDevice();
2575 const keymaster1_device_t* fallback = mKeyStore->getFallbackDevice();
Chad Brubaker57e106d2015-06-01 12:59:00 -07002576 std::vector<keymaster_key_param_t> opParams(params.params);
2577 const keymaster_key_param_set_t inParams = {opParams.data(), opParams.size()};
2578 const keymaster_blob_t input = {keyData, keyLength};
Chad Brubaker4c353cb2015-02-11 14:36:11 -08002579 if (device == NULL) {
2580 return ::SYSTEM_ERROR;
2581 }
2582 if (device->common.module->module_api_version >= KEYMASTER_MODULE_API_VERSION_1_0 &&
2583 device->import_key != NULL) {
Chad Brubaker57e106d2015-06-01 12:59:00 -07002584 rc = device->import_key(device, &inParams, format,&input, &blob, &out);
Chad Brubaker4c353cb2015-02-11 14:36:11 -08002585 }
2586 if (rc && fallback->import_key != NULL) {
Shawn Willden7e8eabb2015-07-28 11:06:00 -06002587 ALOGW("Primary keymaster device failed to import key, falling back to SW.");
Chad Brubaker4c353cb2015-02-11 14:36:11 -08002588 isFallback = true;
Chad Brubaker57e106d2015-06-01 12:59:00 -07002589 rc = fallback->import_key(fallback, &inParams, format, &input, &blob, &out);
Chad Brubaker4c353cb2015-02-11 14:36:11 -08002590 }
2591 if (out) {
2592 if (outCharacteristics) {
2593 outCharacteristics->characteristics = *out;
2594 } else {
2595 keymaster_free_characteristics(out);
2596 }
2597 free(out);
2598 }
2599 if (rc) {
2600 return rc;
2601 }
2602
2603 String8 name8(name);
2604 String8 filename(mKeyStore->getKeyNameForUidWithDir(name8, uid));
2605
2606 Blob keyBlob(blob.key_material, blob.key_material_size, NULL, 0, ::TYPE_KEYMASTER_10);
2607 keyBlob.setFallback(isFallback);
2608 keyBlob.setEncrypted(flags & KEYSTORE_FLAG_ENCRYPTED);
2609
2610 free((void*) blob.key_material);
2611
Chad Brubaker72593ee2015-05-12 10:42:00 -07002612 return mKeyStore->put(filename.string(), &keyBlob, get_user_id(uid));
Chad Brubaker9899d6b2015-02-03 13:03:00 -08002613 }
2614
Chad Brubaker07b0cda2015-02-18 15:52:54 -08002615 void exportKey(const String16& name, keymaster_key_format_t format,
Chad Brubakerd6634422015-03-21 22:36:07 -07002616 const keymaster_blob_t* clientId,
2617 const keymaster_blob_t* appData, ExportResult* result) {
Chad Brubaker07b0cda2015-02-18 15:52:54 -08002618
2619 uid_t callingUid = IPCThreadState::self()->getCallingUid();
2620
2621 Blob keyBlob;
2622 String8 name8(name);
2623 int rc;
2624
2625 ResponseCode responseCode = mKeyStore->getKeyForName(&keyBlob, name8, callingUid,
2626 TYPE_KEYMASTER_10);
2627 if (responseCode != ::NO_ERROR) {
2628 result->resultCode = responseCode;
2629 return;
2630 }
2631 keymaster_key_blob_t key;
2632 key.key_material_size = keyBlob.getLength();
2633 key.key_material = keyBlob.getValue();
2634 keymaster1_device_t* dev = mKeyStore->getDeviceForBlob(keyBlob);
2635 if (!dev->export_key) {
2636 result->resultCode = KM_ERROR_UNIMPLEMENTED;
2637 return;
2638 }
Chad Brubaker57e106d2015-06-01 12:59:00 -07002639 keymaster_blob_t output = {NULL, 0};
2640 rc = dev->export_key(dev, format, &key, clientId, appData, &output);
2641 result->exportData.reset(const_cast<uint8_t*>(output.data));
2642 result->dataLength = output.data_length;
Chad Brubaker07b0cda2015-02-18 15:52:54 -08002643 result->resultCode = rc ? rc : ::NO_ERROR;
Chad Brubaker9899d6b2015-02-03 13:03:00 -08002644 }
2645
Chad Brubakerad6514a2015-04-09 14:00:26 -07002646
Chad Brubaker40a1a9b2015-02-20 14:08:13 -08002647 void begin(const sp<IBinder>& appToken, const String16& name, keymaster_purpose_t purpose,
Chad Brubaker154d7692015-03-27 13:59:31 -07002648 bool pruneable, const KeymasterArguments& params, const uint8_t* entropy,
Chad Brubaker57e106d2015-06-01 12:59:00 -07002649 size_t entropyLength, OperationResult* result) {
Chad Brubaker40a1a9b2015-02-20 14:08:13 -08002650 uid_t callingUid = IPCThreadState::self()->getCallingUid();
2651 if (!pruneable && get_app_id(callingUid) != AID_SYSTEM) {
2652 ALOGE("Non-system uid %d trying to start non-pruneable operation", callingUid);
2653 result->resultCode = ::PERMISSION_DENIED;
2654 return;
2655 }
Chad Brubaker0cf34a22015-04-23 11:06:16 -07002656 if (!checkAllowedOperationParams(params.params)) {
2657 result->resultCode = KM_ERROR_INVALID_ARGUMENT;
2658 return;
2659 }
Chad Brubaker40a1a9b2015-02-20 14:08:13 -08002660 Blob keyBlob;
2661 String8 name8(name);
2662 ResponseCode responseCode = mKeyStore->getKeyForName(&keyBlob, name8, callingUid,
2663 TYPE_KEYMASTER_10);
2664 if (responseCode != ::NO_ERROR) {
2665 result->resultCode = responseCode;
2666 return;
2667 }
2668 keymaster_key_blob_t key;
2669 key.key_material_size = keyBlob.getLength();
2670 key.key_material = keyBlob.getValue();
Chad Brubaker40a1a9b2015-02-20 14:08:13 -08002671 keymaster_operation_handle_t handle;
2672 keymaster1_device_t* dev = mKeyStore->getDeviceForBlob(keyBlob);
Chad Brubaker154d7692015-03-27 13:59:31 -07002673 keymaster_error_t err = KM_ERROR_UNIMPLEMENTED;
Chad Brubaker06801e02015-03-31 15:13:13 -07002674 std::vector<keymaster_key_param_t> opParams(params.params);
Chad Brubakerad6514a2015-04-09 14:00:26 -07002675 Unique_keymaster_key_characteristics characteristics;
2676 characteristics.reset(new keymaster_key_characteristics_t);
2677 err = getOperationCharacteristics(key, dev, opParams, characteristics.get());
2678 if (err) {
2679 result->resultCode = err;
2680 return;
2681 }
Chad Brubaker0cf34a22015-04-23 11:06:16 -07002682 const hw_auth_token_t* authToken = NULL;
Shawn Willdenb2ffa422015-06-17 12:18:55 -06002683 int32_t authResult = getAuthToken(characteristics.get(), 0, purpose, &authToken,
Chad Brubaker06801e02015-03-31 15:13:13 -07002684 /*failOnTokenMissing*/ false);
Chad Brubaker0cf34a22015-04-23 11:06:16 -07002685 // If per-operation auth is needed we need to begin the operation and
2686 // the client will need to authorize that operation before calling
2687 // update. Any other auth issues stop here.
2688 if (authResult != ::NO_ERROR && authResult != ::OP_AUTH_NEEDED) {
2689 result->resultCode = authResult;
Chad Brubaker06801e02015-03-31 15:13:13 -07002690 return;
2691 }
Chad Brubaker0cf34a22015-04-23 11:06:16 -07002692 addAuthToParams(&opParams, authToken);
Chad Brubaker154d7692015-03-27 13:59:31 -07002693 // Add entropy to the device first.
2694 if (entropy) {
2695 if (dev->add_rng_entropy) {
2696 err = dev->add_rng_entropy(dev, entropy, entropyLength);
2697 } else {
2698 err = KM_ERROR_UNIMPLEMENTED;
2699 }
2700 if (err) {
2701 result->resultCode = err;
2702 return;
2703 }
2704 }
Chad Brubaker57e106d2015-06-01 12:59:00 -07002705 keymaster_key_param_set_t inParams = {opParams.data(), opParams.size()};
Chad Brubaker40a1a9b2015-02-20 14:08:13 -08002706
Shawn Willden9221bff2015-06-18 18:23:54 -06002707 // Create a keyid for this key.
2708 keymaster::km_id_t keyid;
2709 if (!enforcement_policy.CreateKeyId(key, &keyid)) {
2710 ALOGE("Failed to create a key ID for authorization checking.");
2711 result->resultCode = KM_ERROR_UNKNOWN_ERROR;
2712 return;
2713 }
2714
2715 // Check that all key authorization policy requirements are met.
2716 keymaster::AuthorizationSet key_auths(characteristics->hw_enforced);
2717 key_auths.push_back(characteristics->sw_enforced);
2718 keymaster::AuthorizationSet operation_params(inParams);
2719 err = enforcement_policy.AuthorizeOperation(purpose, keyid, key_auths, operation_params,
2720 0 /* op_handle */,
2721 true /* is_begin_operation */);
2722 if (err) {
2723 result->resultCode = err;
2724 return;
2725 }
2726
Alex Klyubin4e88f9b2015-06-23 15:04:05 -07002727 keymaster_key_param_set_t outParams = {NULL, 0};
Shawn Willden1f769692015-10-30 10:05:43 -06002728
2729 // If there are more than MAX_OPERATIONS, abort the oldest operation that was started as
2730 // pruneable.
2731 while (mOperationMap.getOperationCount() >= MAX_OPERATIONS) {
2732 ALOGD("Reached or exceeded concurrent operations limit");
2733 if (!pruneOperation()) {
2734 break;
2735 }
2736 }
2737
Alex Klyubin4e88f9b2015-06-23 15:04:05 -07002738 err = dev->begin(dev, purpose, &key, &inParams, &outParams, &handle);
Shawn Willden1f769692015-10-30 10:05:43 -06002739 if (err != KM_ERROR_OK) {
2740 ALOGE("Got error %d from begin()", err);
2741 }
Alex Klyubin4e88f9b2015-06-23 15:04:05 -07002742
Chad Brubaker40a1a9b2015-02-20 14:08:13 -08002743 // If there are too many operations abort the oldest operation that was
2744 // started as pruneable and try again.
2745 while (err == KM_ERROR_TOO_MANY_OPERATIONS && mOperationMap.hasPruneableOperation()) {
Shawn Willden1f769692015-10-30 10:05:43 -06002746 ALOGE("Ran out of operation handles");
2747 if (!pruneOperation()) {
Chad Brubaker40a1a9b2015-02-20 14:08:13 -08002748 break;
2749 }
Chad Brubaker57e106d2015-06-01 12:59:00 -07002750 err = dev->begin(dev, purpose, &key, &inParams, &outParams, &handle);
Chad Brubaker40a1a9b2015-02-20 14:08:13 -08002751 }
2752 if (err) {
2753 result->resultCode = err;
2754 return;
2755 }
Chad Brubaker40a1a9b2015-02-20 14:08:13 -08002756
Shawn Willden9221bff2015-06-18 18:23:54 -06002757 sp<IBinder> operationToken = mOperationMap.addOperation(handle, keyid, purpose, dev,
2758 appToken, characteristics.release(),
Chad Brubaker06801e02015-03-31 15:13:13 -07002759 pruneable);
Chad Brubaker0cf34a22015-04-23 11:06:16 -07002760 if (authToken) {
2761 mOperationMap.setOperationAuthToken(operationToken, authToken);
2762 }
2763 // Return the authentication lookup result. If this is a per operation
2764 // auth'd key then the resultCode will be ::OP_AUTH_NEEDED and the
2765 // application should get an auth token using the handle before the
2766 // first call to update, which will fail if keystore hasn't received the
2767 // auth token.
2768 result->resultCode = authResult;
Chad Brubaker40a1a9b2015-02-20 14:08:13 -08002769 result->token = operationToken;
Chad Brubakerc3a18562015-03-17 18:21:35 -07002770 result->handle = handle;
Chad Brubaker57e106d2015-06-01 12:59:00 -07002771 if (outParams.params) {
2772 result->outParams.params.assign(outParams.params, outParams.params + outParams.length);
2773 free(outParams.params);
2774 }
Chad Brubaker9899d6b2015-02-03 13:03:00 -08002775 }
2776
Chad Brubaker40a1a9b2015-02-20 14:08:13 -08002777 void update(const sp<IBinder>& token, const KeymasterArguments& params, const uint8_t* data,
2778 size_t dataLength, OperationResult* result) {
Chad Brubaker0cf34a22015-04-23 11:06:16 -07002779 if (!checkAllowedOperationParams(params.params)) {
2780 result->resultCode = KM_ERROR_INVALID_ARGUMENT;
2781 return;
2782 }
Chad Brubaker40a1a9b2015-02-20 14:08:13 -08002783 const keymaster1_device_t* dev;
2784 keymaster_operation_handle_t handle;
Shawn Willdenb2ffa422015-06-17 12:18:55 -06002785 keymaster_purpose_t purpose;
Shawn Willden9221bff2015-06-18 18:23:54 -06002786 keymaster::km_id_t keyid;
2787 const keymaster_key_characteristics_t* characteristics;
2788 if (!mOperationMap.getOperation(token, &handle, &keyid, &purpose, &dev, &characteristics)) {
Chad Brubaker40a1a9b2015-02-20 14:08:13 -08002789 result->resultCode = KM_ERROR_INVALID_OPERATION_HANDLE;
2790 return;
2791 }
Chad Brubaker06801e02015-03-31 15:13:13 -07002792 std::vector<keymaster_key_param_t> opParams(params.params);
Chad Brubaker0cf34a22015-04-23 11:06:16 -07002793 int32_t authResult = addOperationAuthTokenIfNeeded(token, &opParams);
2794 if (authResult != ::NO_ERROR) {
Chad Brubaker06801e02015-03-31 15:13:13 -07002795 result->resultCode = authResult;
2796 return;
2797 }
Chad Brubaker57e106d2015-06-01 12:59:00 -07002798 keymaster_key_param_set_t inParams = {opParams.data(), opParams.size()};
2799 keymaster_blob_t input = {data, dataLength};
2800 size_t consumed = 0;
2801 keymaster_blob_t output = {NULL, 0};
2802 keymaster_key_param_set_t outParams = {NULL, 0};
2803
Shawn Willden9221bff2015-06-18 18:23:54 -06002804 // Check that all key authorization policy requirements are met.
2805 keymaster::AuthorizationSet key_auths(characteristics->hw_enforced);
2806 key_auths.push_back(characteristics->sw_enforced);
2807 keymaster::AuthorizationSet operation_params(inParams);
2808 result->resultCode =
2809 enforcement_policy.AuthorizeOperation(purpose, keyid, key_auths,
2810 operation_params, handle,
2811 false /* is_begin_operation */);
2812 if (result->resultCode) {
2813 return;
2814 }
2815
Chad Brubaker57e106d2015-06-01 12:59:00 -07002816 keymaster_error_t err = dev->update(dev, handle, &inParams, &input, &consumed, &outParams,
2817 &output);
2818 result->data.reset(const_cast<uint8_t*>(output.data));
2819 result->dataLength = output.data_length;
Chad Brubaker40a1a9b2015-02-20 14:08:13 -08002820 result->inputConsumed = consumed;
2821 result->resultCode = err ? (int32_t) err : ::NO_ERROR;
Chad Brubaker57e106d2015-06-01 12:59:00 -07002822 if (outParams.params) {
2823 result->outParams.params.assign(outParams.params, outParams.params + outParams.length);
2824 free(outParams.params);
2825 }
Chad Brubaker9899d6b2015-02-03 13:03:00 -08002826 }
2827
Chad Brubaker40a1a9b2015-02-20 14:08:13 -08002828 void finish(const sp<IBinder>& token, const KeymasterArguments& params,
Chad Brubaker0d33e0b2015-05-29 12:30:19 -07002829 const uint8_t* signature, size_t signatureLength,
2830 const uint8_t* entropy, size_t entropyLength, OperationResult* result) {
Chad Brubaker0cf34a22015-04-23 11:06:16 -07002831 if (!checkAllowedOperationParams(params.params)) {
2832 result->resultCode = KM_ERROR_INVALID_ARGUMENT;
2833 return;
2834 }
Chad Brubaker40a1a9b2015-02-20 14:08:13 -08002835 const keymaster1_device_t* dev;
2836 keymaster_operation_handle_t handle;
Shawn Willdenb2ffa422015-06-17 12:18:55 -06002837 keymaster_purpose_t purpose;
Shawn Willden9221bff2015-06-18 18:23:54 -06002838 keymaster::km_id_t keyid;
2839 const keymaster_key_characteristics_t* characteristics;
2840 if (!mOperationMap.getOperation(token, &handle, &keyid, &purpose, &dev, &characteristics)) {
Chad Brubaker40a1a9b2015-02-20 14:08:13 -08002841 result->resultCode = KM_ERROR_INVALID_OPERATION_HANDLE;
2842 return;
2843 }
Chad Brubaker06801e02015-03-31 15:13:13 -07002844 std::vector<keymaster_key_param_t> opParams(params.params);
Chad Brubaker0cf34a22015-04-23 11:06:16 -07002845 int32_t authResult = addOperationAuthTokenIfNeeded(token, &opParams);
2846 if (authResult != ::NO_ERROR) {
Chad Brubaker06801e02015-03-31 15:13:13 -07002847 result->resultCode = authResult;
2848 return;
2849 }
Chad Brubaker0d33e0b2015-05-29 12:30:19 -07002850 keymaster_error_t err;
2851 if (entropy) {
2852 if (dev->add_rng_entropy) {
2853 err = dev->add_rng_entropy(dev, entropy, entropyLength);
2854 } else {
2855 err = KM_ERROR_UNIMPLEMENTED;
2856 }
2857 if (err) {
2858 result->resultCode = err;
2859 return;
2860 }
2861 }
Chad Brubaker0cf34a22015-04-23 11:06:16 -07002862
Chad Brubaker57e106d2015-06-01 12:59:00 -07002863 keymaster_key_param_set_t inParams = {opParams.data(), opParams.size()};
2864 keymaster_blob_t input = {signature, signatureLength};
2865 keymaster_blob_t output = {NULL, 0};
2866 keymaster_key_param_set_t outParams = {NULL, 0};
Shawn Willden9221bff2015-06-18 18:23:54 -06002867
2868 // Check that all key authorization policy requirements are met.
2869 keymaster::AuthorizationSet key_auths(characteristics->hw_enforced);
2870 key_auths.push_back(characteristics->sw_enforced);
2871 keymaster::AuthorizationSet operation_params(inParams);
2872 err = enforcement_policy.AuthorizeOperation(purpose, keyid, key_auths, operation_params,
2873 handle, false /* is_begin_operation */);
2874 if (err) {
2875 result->resultCode = err;
2876 return;
2877 }
2878
Chad Brubaker0d33e0b2015-05-29 12:30:19 -07002879 err = dev->finish(dev, handle, &inParams, &input, &outParams, &output);
Chad Brubaker40a1a9b2015-02-20 14:08:13 -08002880 // Remove the operation regardless of the result
2881 mOperationMap.removeOperation(token);
Chad Brubaker06801e02015-03-31 15:13:13 -07002882 mAuthTokenTable.MarkCompleted(handle);
Chad Brubaker57e106d2015-06-01 12:59:00 -07002883
2884 result->data.reset(const_cast<uint8_t*>(output.data));
2885 result->dataLength = output.data_length;
Chad Brubaker40a1a9b2015-02-20 14:08:13 -08002886 result->resultCode = err ? (int32_t) err : ::NO_ERROR;
Chad Brubaker57e106d2015-06-01 12:59:00 -07002887 if (outParams.params) {
2888 result->outParams.params.assign(outParams.params, outParams.params + outParams.length);
2889 free(outParams.params);
2890 }
Chad Brubaker9899d6b2015-02-03 13:03:00 -08002891 }
2892
Chad Brubaker40a1a9b2015-02-20 14:08:13 -08002893 int32_t abort(const sp<IBinder>& token) {
2894 const keymaster1_device_t* dev;
2895 keymaster_operation_handle_t handle;
Shawn Willdenb2ffa422015-06-17 12:18:55 -06002896 keymaster_purpose_t purpose;
Shawn Willden9221bff2015-06-18 18:23:54 -06002897 keymaster::km_id_t keyid;
2898 if (!mOperationMap.getOperation(token, &handle, &keyid, &purpose, &dev, NULL)) {
Chad Brubaker40a1a9b2015-02-20 14:08:13 -08002899 return KM_ERROR_INVALID_OPERATION_HANDLE;
2900 }
2901 mOperationMap.removeOperation(token);
Chad Brubaker06801e02015-03-31 15:13:13 -07002902 int32_t rc;
Chad Brubaker40a1a9b2015-02-20 14:08:13 -08002903 if (!dev->abort) {
Chad Brubaker06801e02015-03-31 15:13:13 -07002904 rc = KM_ERROR_UNIMPLEMENTED;
2905 } else {
2906 rc = dev->abort(dev, handle);
Chad Brubaker40a1a9b2015-02-20 14:08:13 -08002907 }
Chad Brubaker06801e02015-03-31 15:13:13 -07002908 mAuthTokenTable.MarkCompleted(handle);
Chad Brubaker40a1a9b2015-02-20 14:08:13 -08002909 if (rc) {
2910 return rc;
2911 }
2912 return ::NO_ERROR;
Chad Brubaker9899d6b2015-02-03 13:03:00 -08002913 }
2914
Chad Brubaker2ed2baa2015-03-21 21:20:10 -07002915 bool isOperationAuthorized(const sp<IBinder>& token) {
2916 const keymaster1_device_t* dev;
2917 keymaster_operation_handle_t handle;
Chad Brubakerad6514a2015-04-09 14:00:26 -07002918 const keymaster_key_characteristics_t* characteristics;
Shawn Willdenb2ffa422015-06-17 12:18:55 -06002919 keymaster_purpose_t purpose;
Shawn Willden9221bff2015-06-18 18:23:54 -06002920 keymaster::km_id_t keyid;
2921 if (!mOperationMap.getOperation(token, &handle, &keyid, &purpose, &dev, &characteristics)) {
Chad Brubaker2ed2baa2015-03-21 21:20:10 -07002922 return false;
2923 }
Chad Brubaker0cf34a22015-04-23 11:06:16 -07002924 const hw_auth_token_t* authToken = NULL;
2925 mOperationMap.getOperationAuthToken(token, &authToken);
Chad Brubaker06801e02015-03-31 15:13:13 -07002926 std::vector<keymaster_key_param_t> ignored;
Chad Brubaker0cf34a22015-04-23 11:06:16 -07002927 int32_t authResult = addOperationAuthTokenIfNeeded(token, &ignored);
2928 return authResult == ::NO_ERROR;
Chad Brubaker2ed2baa2015-03-21 21:20:10 -07002929 }
2930
Chad Brubakerd80c7b42015-03-31 11:04:28 -07002931 int32_t addAuthToken(const uint8_t* token, size_t length) {
Chad Brubaker9489b792015-04-14 11:01:45 -07002932 if (!checkBinderPermission(P_ADD_AUTH)) {
2933 ALOGW("addAuthToken: permission denied for %d",
2934 IPCThreadState::self()->getCallingUid());
Chad Brubakerd80c7b42015-03-31 11:04:28 -07002935 return ::PERMISSION_DENIED;
2936 }
2937 if (length != sizeof(hw_auth_token_t)) {
2938 return KM_ERROR_INVALID_ARGUMENT;
2939 }
2940 hw_auth_token_t* authToken = new hw_auth_token_t;
2941 memcpy(reinterpret_cast<void*>(authToken), token, sizeof(hw_auth_token_t));
2942 // The table takes ownership of authToken.
2943 mAuthTokenTable.AddAuthenticationToken(authToken);
2944 return ::NO_ERROR;
Chad Brubaker2ed2baa2015-03-21 21:20:10 -07002945 }
2946
Kenny Root07438c82012-11-02 15:41:02 -07002947private:
Chad Brubaker9489b792015-04-14 11:01:45 -07002948 static const int32_t UID_SELF = -1;
2949
2950 /**
Shawn Willden1f769692015-10-30 10:05:43 -06002951 * Prune the oldest pruneable operation.
2952 */
2953 inline bool pruneOperation() {
2954 sp<IBinder> oldest = mOperationMap.getOldestPruneableOperation();
2955 ALOGD("Trying to prune operation %p", oldest.get());
2956 size_t op_count_before_abort = mOperationMap.getOperationCount();
2957 // We mostly ignore errors from abort() because all we care about is whether at least
2958 // one operation has been removed.
2959 int abort_error = abort(oldest);
2960 if (mOperationMap.getOperationCount() >= op_count_before_abort) {
2961 ALOGE("Failed to abort pruneable operation %p, error: %d", oldest.get(),
2962 abort_error);
2963 return false;
2964 }
2965 return true;
2966 }
2967
2968 /**
Chad Brubaker9489b792015-04-14 11:01:45 -07002969 * Get the effective target uid for a binder operation that takes an
2970 * optional uid as the target.
2971 */
2972 inline uid_t getEffectiveUid(int32_t targetUid) {
2973 if (targetUid == UID_SELF) {
2974 return IPCThreadState::self()->getCallingUid();
2975 }
2976 return static_cast<uid_t>(targetUid);
2977 }
2978
2979 /**
2980 * Check if the caller of the current binder method has the required
2981 * permission and if acting on other uids the grants to do so.
2982 */
2983 inline bool checkBinderPermission(perm_t permission, int32_t targetUid = UID_SELF) {
2984 uid_t callingUid = IPCThreadState::self()->getCallingUid();
2985 pid_t spid = IPCThreadState::self()->getCallingPid();
2986 if (!has_permission(callingUid, permission, spid)) {
2987 ALOGW("permission %s denied for %d", get_perm_label(permission), callingUid);
2988 return false;
2989 }
2990 if (!is_granted_to(callingUid, getEffectiveUid(targetUid))) {
2991 ALOGW("uid %d not granted to act for %d", callingUid, targetUid);
2992 return false;
2993 }
2994 return true;
2995 }
2996
2997 /**
2998 * Check if the caller of the current binder method has the required
Chad Brubakerb37a5232015-05-01 10:21:27 -07002999 * permission and the target uid is the caller or the caller is system.
3000 */
3001 inline bool checkBinderPermissionSelfOrSystem(perm_t permission, int32_t targetUid) {
3002 uid_t callingUid = IPCThreadState::self()->getCallingUid();
3003 pid_t spid = IPCThreadState::self()->getCallingPid();
3004 if (!has_permission(callingUid, permission, spid)) {
3005 ALOGW("permission %s denied for %d", get_perm_label(permission), callingUid);
3006 return false;
3007 }
3008 return getEffectiveUid(targetUid) == callingUid || callingUid == AID_SYSTEM;
3009 }
3010
3011 /**
3012 * Check if the caller of the current binder method has the required
Chad Brubaker9489b792015-04-14 11:01:45 -07003013 * permission or the target of the operation is the caller's uid. This is
3014 * for operation where the permission is only for cross-uid activity and all
3015 * uids are allowed to act on their own (ie: clearing all entries for a
3016 * given uid).
3017 */
3018 inline bool checkBinderPermissionOrSelfTarget(perm_t permission, int32_t targetUid) {
3019 uid_t callingUid = IPCThreadState::self()->getCallingUid();
3020 if (getEffectiveUid(targetUid) == callingUid) {
3021 return true;
3022 } else {
3023 return checkBinderPermission(permission, targetUid);
3024 }
3025 }
3026
3027 /**
3028 * Helper method to check that the caller has the required permission as
3029 * well as the keystore is in the unlocked state if checkUnlocked is true.
3030 *
3031 * Returns NO_ERROR on success, PERMISSION_DENIED on a permission error and
3032 * otherwise the state of keystore when not unlocked and checkUnlocked is
3033 * true.
3034 */
3035 inline int32_t checkBinderPermissionAndKeystoreState(perm_t permission, int32_t targetUid = -1,
3036 bool checkUnlocked = true) {
3037 if (!checkBinderPermission(permission, targetUid)) {
3038 return ::PERMISSION_DENIED;
3039 }
Chad Brubaker72593ee2015-05-12 10:42:00 -07003040 State state = mKeyStore->getState(get_user_id(getEffectiveUid(targetUid)));
Chad Brubaker9489b792015-04-14 11:01:45 -07003041 if (checkUnlocked && !isKeystoreUnlocked(state)) {
3042 return state;
3043 }
3044
3045 return ::NO_ERROR;
3046
3047 }
3048
Kenny Root9d45d1c2013-02-14 10:32:30 -08003049 inline bool isKeystoreUnlocked(State state) {
3050 switch (state) {
3051 case ::STATE_NO_ERROR:
3052 return true;
3053 case ::STATE_UNINITIALIZED:
3054 case ::STATE_LOCKED:
3055 return false;
3056 }
3057 return false;
Kenny Root07438c82012-11-02 15:41:02 -07003058 }
3059
Chad Brubaker67d2a502015-03-11 17:21:18 +00003060 bool isKeyTypeSupported(const keymaster1_device_t* device, keymaster_keypair_t keyType) {
Kenny Root1d448c02013-11-21 10:36:53 -08003061 const int32_t device_api = device->common.module->module_api_version;
3062 if (device_api == KEYMASTER_MODULE_API_VERSION_0_2) {
3063 switch (keyType) {
3064 case TYPE_RSA:
3065 case TYPE_DSA:
3066 case TYPE_EC:
3067 return true;
3068 default:
3069 return false;
3070 }
3071 } else if (device_api >= KEYMASTER_MODULE_API_VERSION_0_3) {
3072 switch (keyType) {
3073 case TYPE_RSA:
3074 return true;
3075 case TYPE_DSA:
3076 return device->flags & KEYMASTER_SUPPORTS_DSA;
3077 case TYPE_EC:
3078 return device->flags & KEYMASTER_SUPPORTS_EC;
3079 default:
3080 return false;
3081 }
3082 } else {
3083 return keyType == TYPE_RSA;
3084 }
3085 }
3086
Chad Brubaker0cf34a22015-04-23 11:06:16 -07003087 /**
3088 * Check that all keymaster_key_param_t's provided by the application are
3089 * allowed. Any parameter that keystore adds itself should be disallowed here.
3090 */
3091 bool checkAllowedOperationParams(const std::vector<keymaster_key_param_t>& params) {
3092 for (auto param: params) {
3093 switch (param.tag) {
3094 case KM_TAG_AUTH_TOKEN:
3095 return false;
3096 default:
3097 break;
3098 }
3099 }
3100 return true;
3101 }
3102
3103 keymaster_error_t getOperationCharacteristics(const keymaster_key_blob_t& key,
3104 const keymaster1_device_t* dev,
3105 const std::vector<keymaster_key_param_t>& params,
3106 keymaster_key_characteristics_t* out) {
3107 UniquePtr<keymaster_blob_t> appId;
3108 UniquePtr<keymaster_blob_t> appData;
3109 for (auto param : params) {
3110 if (param.tag == KM_TAG_APPLICATION_ID) {
3111 appId.reset(new keymaster_blob_t);
3112 appId->data = param.blob.data;
3113 appId->data_length = param.blob.data_length;
3114 } else if (param.tag == KM_TAG_APPLICATION_DATA) {
3115 appData.reset(new keymaster_blob_t);
3116 appData->data = param.blob.data;
3117 appData->data_length = param.blob.data_length;
3118 }
3119 }
3120 keymaster_key_characteristics_t* result = NULL;
3121 if (!dev->get_key_characteristics) {
3122 return KM_ERROR_UNIMPLEMENTED;
3123 }
3124 keymaster_error_t error = dev->get_key_characteristics(dev, &key, appId.get(),
3125 appData.get(), &result);
3126 if (result) {
3127 *out = *result;
3128 free(result);
3129 }
3130 return error;
3131 }
3132
3133 /**
3134 * Get the auth token for this operation from the auth token table.
3135 *
3136 * Returns ::NO_ERROR if the auth token was set or none was required.
3137 * ::OP_AUTH_NEEDED if it is a per op authorization, no
3138 * authorization token exists for that operation and
3139 * failOnTokenMissing is false.
3140 * KM_ERROR_KEY_USER_NOT_AUTHENTICATED if there is no valid auth
3141 * token for the operation
3142 */
3143 int32_t getAuthToken(const keymaster_key_characteristics_t* characteristics,
3144 keymaster_operation_handle_t handle,
Shawn Willdenb2ffa422015-06-17 12:18:55 -06003145 keymaster_purpose_t purpose,
Chad Brubaker0cf34a22015-04-23 11:06:16 -07003146 const hw_auth_token_t** authToken,
3147 bool failOnTokenMissing = true) {
3148
3149 std::vector<keymaster_key_param_t> allCharacteristics;
3150 for (size_t i = 0; i < characteristics->sw_enforced.length; i++) {
3151 allCharacteristics.push_back(characteristics->sw_enforced.params[i]);
3152 }
3153 for (size_t i = 0; i < characteristics->hw_enforced.length; i++) {
3154 allCharacteristics.push_back(characteristics->hw_enforced.params[i]);
3155 }
Shawn Willdenb2ffa422015-06-17 12:18:55 -06003156 keymaster::AuthTokenTable::Error err = mAuthTokenTable.FindAuthorization(
3157 allCharacteristics.data(), allCharacteristics.size(), purpose, handle, authToken);
Chad Brubaker0cf34a22015-04-23 11:06:16 -07003158 switch (err) {
3159 case keymaster::AuthTokenTable::OK:
3160 case keymaster::AuthTokenTable::AUTH_NOT_REQUIRED:
3161 return ::NO_ERROR;
3162 case keymaster::AuthTokenTable::AUTH_TOKEN_NOT_FOUND:
3163 case keymaster::AuthTokenTable::AUTH_TOKEN_EXPIRED:
3164 case keymaster::AuthTokenTable::AUTH_TOKEN_WRONG_SID:
3165 return KM_ERROR_KEY_USER_NOT_AUTHENTICATED;
3166 case keymaster::AuthTokenTable::OP_HANDLE_REQUIRED:
3167 return failOnTokenMissing ? (int32_t) KM_ERROR_KEY_USER_NOT_AUTHENTICATED :
3168 (int32_t) ::OP_AUTH_NEEDED;
3169 default:
3170 ALOGE("Unexpected FindAuthorization return value %d", err);
3171 return KM_ERROR_INVALID_ARGUMENT;
3172 }
3173 }
3174
3175 inline void addAuthToParams(std::vector<keymaster_key_param_t>* params,
3176 const hw_auth_token_t* token) {
3177 if (token) {
3178 params->push_back(keymaster_param_blob(KM_TAG_AUTH_TOKEN,
3179 reinterpret_cast<const uint8_t*>(token),
3180 sizeof(hw_auth_token_t)));
3181 }
3182 }
3183
3184 /**
3185 * Add the auth token for the operation to the param list if the operation
3186 * requires authorization. Uses the cached result in the OperationMap if available
3187 * otherwise gets the token from the AuthTokenTable and caches the result.
3188 *
3189 * Returns ::NO_ERROR if the auth token was added or not needed.
3190 * KM_ERROR_KEY_USER_NOT_AUTHENTICATED if the operation is not
3191 * authenticated.
3192 * KM_ERROR_INVALID_OPERATION_HANDLE if token is not a valid
3193 * operation token.
3194 */
3195 int32_t addOperationAuthTokenIfNeeded(sp<IBinder> token,
3196 std::vector<keymaster_key_param_t>* params) {
3197 const hw_auth_token_t* authToken = NULL;
Chad Brubaker7169a842015-04-29 19:58:34 -07003198 mOperationMap.getOperationAuthToken(token, &authToken);
3199 if (!authToken) {
Chad Brubaker0cf34a22015-04-23 11:06:16 -07003200 const keymaster1_device_t* dev;
3201 keymaster_operation_handle_t handle;
3202 const keymaster_key_characteristics_t* characteristics = NULL;
Shawn Willdenb2ffa422015-06-17 12:18:55 -06003203 keymaster_purpose_t purpose;
Shawn Willden9221bff2015-06-18 18:23:54 -06003204 keymaster::km_id_t keyid;
3205 if (!mOperationMap.getOperation(token, &handle, &keyid, &purpose, &dev,
3206 &characteristics)) {
Chad Brubaker0cf34a22015-04-23 11:06:16 -07003207 return KM_ERROR_INVALID_OPERATION_HANDLE;
3208 }
Shawn Willdenb2ffa422015-06-17 12:18:55 -06003209 int32_t result = getAuthToken(characteristics, handle, purpose, &authToken);
Chad Brubaker0cf34a22015-04-23 11:06:16 -07003210 if (result != ::NO_ERROR) {
3211 return result;
3212 }
3213 if (authToken) {
3214 mOperationMap.setOperationAuthToken(token, authToken);
3215 }
3216 }
3217 addAuthToParams(params, authToken);
3218 return ::NO_ERROR;
3219 }
3220
Chad Brubaker3a7d9e62015-06-04 15:01:46 -07003221 /**
3222 * Translate a result value to a legacy return value. All keystore errors are
3223 * preserved and keymaster errors become SYSTEM_ERRORs
3224 */
3225 inline int32_t translateResultToLegacyResult(int32_t result) {
3226 if (result > 0) {
3227 return result;
3228 }
3229 return ::SYSTEM_ERROR;
3230 }
3231
Chad Brubaker3a7d9e62015-06-04 15:01:46 -07003232 keymaster_key_param_t* getKeyAlgorithm(keymaster_key_characteristics_t* characteristics) {
3233 for (size_t i = 0; i < characteristics->hw_enforced.length; i++) {
3234 if (characteristics->hw_enforced.params[i].tag == KM_TAG_ALGORITHM) {
3235 return &characteristics->hw_enforced.params[i];
3236 }
3237 }
3238 for (size_t i = 0; i < characteristics->sw_enforced.length; i++) {
3239 if (characteristics->sw_enforced.params[i].tag == KM_TAG_ALGORITHM) {
3240 return &characteristics->sw_enforced.params[i];
3241 }
3242 }
3243 return NULL;
3244 }
3245
3246 void addLegacyBeginParams(const String16& name, std::vector<keymaster_key_param_t>& params) {
3247 // All legacy keys are DIGEST_NONE/PAD_NONE.
3248 params.push_back(keymaster_param_enum(KM_TAG_DIGEST, KM_DIGEST_NONE));
3249 params.push_back(keymaster_param_enum(KM_TAG_PADDING, KM_PAD_NONE));
3250
3251 // Look up the algorithm of the key.
3252 KeyCharacteristics characteristics;
3253 int32_t rc = getKeyCharacteristics(name, NULL, NULL, &characteristics);
3254 if (rc != ::NO_ERROR) {
3255 ALOGE("Failed to get key characteristics");
3256 return;
3257 }
3258 keymaster_key_param_t* algorithm = getKeyAlgorithm(&characteristics.characteristics);
3259 if (!algorithm) {
3260 ALOGE("getKeyCharacteristics did not include KM_TAG_ALGORITHM");
3261 return;
3262 }
3263 params.push_back(*algorithm);
3264 }
3265
3266 int32_t doLegacySignVerify(const String16& name, const uint8_t* data, size_t length,
3267 uint8_t** out, size_t* outLength, const uint8_t* signature,
3268 size_t signatureLength, keymaster_purpose_t purpose) {
3269
Chad Brubaker3a7d9e62015-06-04 15:01:46 -07003270 std::basic_stringstream<uint8_t> outBuffer;
3271 OperationResult result;
3272 KeymasterArguments inArgs;
3273 addLegacyBeginParams(name, inArgs.params);
3274 sp<IBinder> appToken(new BBinder);
3275 sp<IBinder> token;
3276
3277 begin(appToken, name, purpose, true, inArgs, NULL, 0, &result);
3278 if (result.resultCode != ResponseCode::NO_ERROR) {
Chad Brubakerdf705172015-06-17 20:17:51 -07003279 if (result.resultCode == ::KEY_NOT_FOUND) {
3280 ALOGW("Key not found");
3281 } else {
3282 ALOGW("Error in begin: %d", result.resultCode);
3283 }
Chad Brubaker3a7d9e62015-06-04 15:01:46 -07003284 return translateResultToLegacyResult(result.resultCode);
3285 }
3286 inArgs.params.clear();
3287 token = result.token;
3288 size_t consumed = 0;
3289 size_t lastConsumed = 0;
3290 do {
3291 update(token, inArgs, data + consumed, length - consumed, &result);
3292 if (result.resultCode != ResponseCode::NO_ERROR) {
3293 ALOGW("Error in update: %d", result.resultCode);
3294 return translateResultToLegacyResult(result.resultCode);
3295 }
3296 if (out) {
3297 outBuffer.write(result.data.get(), result.dataLength);
3298 }
3299 lastConsumed = result.inputConsumed;
3300 consumed += lastConsumed;
3301 } while (consumed < length && lastConsumed > 0);
3302
3303 if (consumed != length) {
3304 ALOGW("Not all data consumed. Consumed %zu of %zu", consumed, length);
3305 return ::SYSTEM_ERROR;
3306 }
3307
3308 finish(token, inArgs, signature, signatureLength, NULL, 0, &result);
3309 if (result.resultCode != ResponseCode::NO_ERROR) {
3310 ALOGW("Error in finish: %d", result.resultCode);
3311 return translateResultToLegacyResult(result.resultCode);
3312 }
3313 if (out) {
3314 outBuffer.write(result.data.get(), result.dataLength);
3315 }
3316
3317 if (out) {
3318 auto buf = outBuffer.str();
3319 *out = new uint8_t[buf.size()];
3320 memcpy(*out, buf.c_str(), buf.size());
3321 *outLength = buf.size();
3322 }
3323
3324 return ::NO_ERROR;
3325 }
3326
Kenny Root07438c82012-11-02 15:41:02 -07003327 ::KeyStore* mKeyStore;
Chad Brubaker40a1a9b2015-02-20 14:08:13 -08003328 OperationMap mOperationMap;
Chad Brubakerd80c7b42015-03-31 11:04:28 -07003329 keymaster::AuthTokenTable mAuthTokenTable;
Shawn Willden9221bff2015-06-18 18:23:54 -06003330 KeystoreKeymasterEnforcement enforcement_policy;
Kenny Root07438c82012-11-02 15:41:02 -07003331};
3332
3333}; // namespace android
Kenny Roota91203b2012-02-15 15:00:46 -08003334
3335int main(int argc, char* argv[]) {
Kenny Roota91203b2012-02-15 15:00:46 -08003336 if (argc < 2) {
3337 ALOGE("A directory must be specified!");
3338 return 1;
3339 }
3340 if (chdir(argv[1]) == -1) {
3341 ALOGE("chdir: %s: %s", argv[1], strerror(errno));
3342 return 1;
3343 }
3344
3345 Entropy entropy;
3346 if (!entropy.open()) {
3347 return 1;
3348 }
Kenny Root70e3a862012-02-15 17:20:23 -08003349
Chad Brubakerbd07a232015-06-01 10:44:27 -07003350 keymaster1_device_t* dev;
Kenny Root70e3a862012-02-15 17:20:23 -08003351 if (keymaster_device_initialize(&dev)) {
3352 ALOGE("keystore keymaster could not be initialized; exiting");
3353 return 1;
3354 }
3355
Chad Brubaker67d2a502015-03-11 17:21:18 +00003356 keymaster1_device_t* fallback;
Chad Brubakerfc18edc2015-01-12 15:17:18 -08003357 if (fallback_keymaster_device_initialize(&fallback)) {
3358 ALOGE("software keymaster could not be initialized; exiting");
3359 return 1;
3360 }
3361
Riley Spahneaabae92014-06-30 12:39:52 -07003362 ks_is_selinux_enabled = is_selinux_enabled();
3363 if (ks_is_selinux_enabled) {
3364 union selinux_callback cb;
3365 cb.func_log = selinux_log_callback;
3366 selinux_set_callback(SELINUX_CB_LOG, cb);
3367 if (getcon(&tctx) != 0) {
3368 ALOGE("SELinux: Could not acquire target context. Aborting keystore.\n");
3369 return -1;
3370 }
3371 } else {
3372 ALOGI("SELinux: Keystore SELinux is disabled.\n");
3373 }
3374
Chad Brubakerbd07a232015-06-01 10:44:27 -07003375 KeyStore keyStore(&entropy, dev, fallback);
Kenny Root655b9582013-04-04 08:37:42 -07003376 keyStore.initialize();
Kenny Root07438c82012-11-02 15:41:02 -07003377 android::sp<android::IServiceManager> sm = android::defaultServiceManager();
3378 android::sp<android::KeyStoreProxy> proxy = new android::KeyStoreProxy(&keyStore);
3379 android::status_t ret = sm->addService(android::String16("android.security.keystore"), proxy);
3380 if (ret != android::OK) {
3381 ALOGE("Couldn't register binder service!");
3382 return -1;
Kenny Roota91203b2012-02-15 15:00:46 -08003383 }
Kenny Root07438c82012-11-02 15:41:02 -07003384
3385 /*
3386 * We're the only thread in existence, so we're just going to process
3387 * Binder transaction as a single-threaded program.
3388 */
3389 android::IPCThreadState::self()->joinThreadPool();
Kenny Root70e3a862012-02-15 17:20:23 -08003390
3391 keymaster_device_release(dev);
Kenny Roota91203b2012-02-15 15:00:46 -08003392 return 1;
3393}