blob: 91487ed9c1751f702b88efd42d42a81250052abe [file] [log] [blame]
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001/*
2 * Copyright (C) 2010 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
17/* TO DO:
18 * 1. Perhaps keep several copies of the encrypted key, in case something
19 * goes horribly wrong?
20 *
21 */
22
23#include <sys/types.h>
Ken Sumralle550f782013-08-20 13:48:23 -070024#include <sys/wait.h>
Ken Sumrall8f869aa2010-12-03 03:47:09 -080025#include <sys/stat.h>
Paul Lawrencef4faa572014-01-29 13:31:03 -080026#include <ctype.h>
Ken Sumrall8f869aa2010-12-03 03:47:09 -080027#include <fcntl.h>
Elliott Hughes73737162014-06-25 17:27:42 -070028#include <inttypes.h>
Ken Sumrall8f869aa2010-12-03 03:47:09 -080029#include <unistd.h>
30#include <stdio.h>
31#include <sys/ioctl.h>
32#include <linux/dm-ioctl.h>
33#include <libgen.h>
34#include <stdlib.h>
35#include <sys/param.h>
36#include <string.h>
37#include <sys/mount.h>
38#include <openssl/evp.h>
Adam Langley41405bb2015-01-22 16:45:28 -080039#include <openssl/sha.h>
Ken Sumrall8f869aa2010-12-03 03:47:09 -080040#include <errno.h>
Ken Sumrall3ed82362011-01-28 23:31:16 -080041#include <ext4.h>
Ken Sumrall29d8da82011-05-18 17:20:07 -070042#include <linux/kdev_t.h>
Ken Sumralle5032c42012-04-01 23:58:44 -070043#include <fs_mgr.h>
Paul Lawrence9c58a872014-09-30 09:12:51 -070044#include <time.h>
Rubin Xu85c01f92014-10-13 12:49:54 +010045#include <math.h>
Ken Sumrall8f869aa2010-12-03 03:47:09 -080046#include "cryptfs.h"
47#define LOG_TAG "Cryptfs"
48#include "cutils/log.h"
49#include "cutils/properties.h"
Ken Sumralladfba362013-06-04 16:37:52 -070050#include "cutils/android_reboot.h"
Ken Sumrall5d4c68e2011-01-30 19:06:03 -080051#include "hardware_legacy/power.h"
Ken Sumralle550f782013-08-20 13:48:23 -070052#include <logwrap/logwrap.h>
Ken Sumrall29d8da82011-05-18 17:20:07 -070053#include "VolumeManager.h"
Ken Sumrall9caab762013-06-11 19:10:20 -070054#include "VoldUtil.h"
Kenny Rootc4c70f12013-06-14 12:11:38 -070055#include "crypto_scrypt.h"
Paul Lawrence8175a0b2015-03-05 09:46:23 -080056#include "ext4_crypt.h"
Paul Lawrenceae59fe62014-01-21 08:23:27 -080057#include "ext4_utils.h"
Daniel Rosenberge82df162014-08-15 22:19:23 +000058#include "f2fs_sparseblock.h"
Paul Lawrence87999172014-02-20 12:21:31 -080059#include "CheckBattery.h"
jessica_yu3f14fe42014-09-22 15:57:40 +080060#include "Process.h"
Ken Sumrall8f869aa2010-12-03 03:47:09 -080061
Shawn Willdend1fd8462015-02-24 09:51:34 -070062#include <hardware/keymaster0.h>
Paul Lawrence69f4ebd2014-04-14 12:17:14 -070063
Mark Salyzyn3e971272014-01-21 13:27:04 -080064#define UNUSED __attribute__((unused))
65
Mark Salyzyn5eecc442014-02-12 14:16:14 -080066#define UNUSED __attribute__((unused))
67
Ajay Dudani87701e22014-09-17 21:02:52 -070068#ifdef CONFIG_HW_DISK_ENCRYPTION
69#include "cryptfs_hw.h"
70#endif
71
Ken Sumrall8f869aa2010-12-03 03:47:09 -080072#define DM_CRYPT_BUF_SIZE 4096
73
Jason parks70a4b3f2011-01-28 10:10:47 -060074#define HASH_COUNT 2000
75#define KEY_LEN_BYTES 16
76#define IV_LEN_BYTES 16
77
Ken Sumrall29d8da82011-05-18 17:20:07 -070078#define KEY_IN_FOOTER "footer"
79
Paul Lawrencef4faa572014-01-29 13:31:03 -080080// "default_password" encoded into hex (d=0x64 etc)
81#define DEFAULT_PASSWORD "64656661756c745f70617373776f7264"
82
Ken Sumrall29d8da82011-05-18 17:20:07 -070083#define EXT4_FS 1
JP Abgrall62c7af32014-06-16 13:01:23 -070084#define F2FS_FS 2
Ken Sumrall29d8da82011-05-18 17:20:07 -070085
Ken Sumralle919efe2012-09-29 17:07:41 -070086#define TABLE_LOAD_RETRIES 10
87
Shawn Willden47ba10d2014-09-03 17:07:06 -060088#define RSA_KEY_SIZE 2048
89#define RSA_KEY_SIZE_BYTES (RSA_KEY_SIZE / 8)
90#define RSA_EXPONENT 0x10001
Paul Lawrence69f4ebd2014-04-14 12:17:14 -070091
Paul Lawrence8e3f4512014-09-08 10:11:17 -070092#define RETRY_MOUNT_ATTEMPTS 10
93#define RETRY_MOUNT_DELAY_SECONDS 1
94
Ken Sumrall8f869aa2010-12-03 03:47:09 -080095char *me = "cryptfs";
96
Jason parks70a4b3f2011-01-28 10:10:47 -060097static unsigned char saved_master_key[KEY_LEN_BYTES];
Ken Sumrall3ad90722011-10-04 20:38:29 -070098static char *saved_mount_point;
Jason parks70a4b3f2011-01-28 10:10:47 -060099static int master_key_saved = 0;
Ken Sumrall160b4d62013-04-22 12:15:39 -0700100static struct crypt_persist_data *persist_data = NULL;
Ken Sumrall56ad03c2013-02-13 13:00:19 -0800101
Shawn Willdend1fd8462015-02-24 09:51:34 -0700102static int keymaster_init(keymaster0_device_t **keymaster_dev)
Paul Lawrence69f4ebd2014-04-14 12:17:14 -0700103{
104 int rc;
105
106 const hw_module_t* mod;
107 rc = hw_get_module_by_class(KEYSTORE_HARDWARE_MODULE_ID, NULL, &mod);
108 if (rc) {
109 ALOGE("could not find any keystore module");
110 goto out;
111 }
112
Shawn Willdend1fd8462015-02-24 09:51:34 -0700113 rc = keymaster0_open(mod, keymaster_dev);
Paul Lawrence69f4ebd2014-04-14 12:17:14 -0700114 if (rc) {
115 ALOGE("could not open keymaster device in %s (%s)",
116 KEYSTORE_HARDWARE_MODULE_ID, strerror(-rc));
117 goto out;
118 }
119
120 return 0;
121
122out:
123 *keymaster_dev = NULL;
124 return rc;
125}
126
127/* Should we use keymaster? */
128static int keymaster_check_compatibility()
129{
Shawn Willdend1fd8462015-02-24 09:51:34 -0700130 keymaster0_device_t *keymaster_dev = 0;
Paul Lawrence69f4ebd2014-04-14 12:17:14 -0700131 int rc = 0;
132
133 if (keymaster_init(&keymaster_dev)) {
134 SLOGE("Failed to init keymaster");
135 rc = -1;
136 goto out;
137 }
138
Paul Lawrence8c008392014-05-06 14:02:48 -0700139 SLOGI("keymaster version is %d", keymaster_dev->common.module->module_api_version);
140
141 if (keymaster_dev->common.module->module_api_version
142 < KEYMASTER_MODULE_API_VERSION_0_3) {
143 rc = 0;
144 goto out;
145 }
146
Shawn Willden7c49ab02014-10-30 08:12:32 -0600147 if (!(keymaster_dev->flags & KEYMASTER_SOFTWARE_ONLY) &&
148 (keymaster_dev->flags & KEYMASTER_BLOBS_ARE_STANDALONE)) {
Paul Lawrence69f4ebd2014-04-14 12:17:14 -0700149 rc = 1;
150 }
151
152out:
Shawn Willdend1fd8462015-02-24 09:51:34 -0700153 keymaster0_close(keymaster_dev);
Paul Lawrence69f4ebd2014-04-14 12:17:14 -0700154 return rc;
155}
156
157/* Create a new keymaster key and store it in this footer */
158static int keymaster_create_key(struct crypt_mnt_ftr *ftr)
159{
160 uint8_t* key = 0;
Shawn Willdend1fd8462015-02-24 09:51:34 -0700161 keymaster0_device_t *keymaster_dev = 0;
Paul Lawrence69f4ebd2014-04-14 12:17:14 -0700162
163 if (keymaster_init(&keymaster_dev)) {
164 SLOGE("Failed to init keymaster");
165 return -1;
166 }
167
168 int rc = 0;
169
170 keymaster_rsa_keygen_params_t params;
171 memset(&params, '\0', sizeof(params));
Shawn Willden47ba10d2014-09-03 17:07:06 -0600172 params.public_exponent = RSA_EXPONENT;
173 params.modulus_size = RSA_KEY_SIZE;
Paul Lawrence69f4ebd2014-04-14 12:17:14 -0700174
175 size_t key_size;
176 if (keymaster_dev->generate_keypair(keymaster_dev, TYPE_RSA, &params,
177 &key, &key_size)) {
178 SLOGE("Failed to generate keypair");
179 rc = -1;
180 goto out;
181 }
182
183 if (key_size > KEYMASTER_BLOB_SIZE) {
184 SLOGE("Keymaster key too large for crypto footer");
185 rc = -1;
186 goto out;
187 }
188
189 memcpy(ftr->keymaster_blob, key, key_size);
190 ftr->keymaster_blob_size = key_size;
191
192out:
Shawn Willdend1fd8462015-02-24 09:51:34 -0700193 keymaster0_close(keymaster_dev);
Paul Lawrence69f4ebd2014-04-14 12:17:14 -0700194 free(key);
195 return rc;
196}
197
Shawn Willdene17a9c42014-09-08 13:04:08 -0600198/* This signs the given object using the keymaster key. */
199static int keymaster_sign_object(struct crypt_mnt_ftr *ftr,
Shawn Willden47ba10d2014-09-03 17:07:06 -0600200 const unsigned char *object,
201 const size_t object_size,
202 unsigned char **signature,
203 size_t *signature_size)
204{
205 int rc = 0;
Shawn Willdend1fd8462015-02-24 09:51:34 -0700206 keymaster0_device_t *keymaster_dev = 0;
Shawn Willden47ba10d2014-09-03 17:07:06 -0600207 if (keymaster_init(&keymaster_dev)) {
208 SLOGE("Failed to init keymaster");
209 return -1;
210 }
211
212 /* We currently set the digest type to DIGEST_NONE because it's the
213 * only supported value for keymaster. A similar issue exists with
214 * PADDING_NONE. Long term both of these should likely change.
215 */
216 keymaster_rsa_sign_params_t params;
217 params.digest_type = DIGEST_NONE;
218 params.padding_type = PADDING_NONE;
219
220 unsigned char to_sign[RSA_KEY_SIZE_BYTES];
Shawn Willdene17a9c42014-09-08 13:04:08 -0600221 size_t to_sign_size = sizeof(to_sign);
Shawn Willden47ba10d2014-09-03 17:07:06 -0600222 memset(to_sign, 0, RSA_KEY_SIZE_BYTES);
Shawn Willden47ba10d2014-09-03 17:07:06 -0600223
Shawn Willdene17a9c42014-09-08 13:04:08 -0600224 // To sign a message with RSA, the message must satisfy two
225 // constraints:
226 //
227 // 1. The message, when interpreted as a big-endian numeric value, must
228 // be strictly less than the public modulus of the RSA key. Note
229 // that because the most significant bit of the public modulus is
230 // guaranteed to be 1 (else it's an (n-1)-bit key, not an n-bit
231 // key), an n-bit message with most significant bit 0 always
232 // satisfies this requirement.
233 //
234 // 2. The message must have the same length in bits as the public
235 // modulus of the RSA key. This requirement isn't mathematically
236 // necessary, but is necessary to ensure consistency in
237 // implementations.
238 switch (ftr->kdf_type) {
239 case KDF_SCRYPT_KEYMASTER_UNPADDED:
240 // This is broken: It produces a message which is shorter than
241 // the public modulus, failing criterion 2.
242 memcpy(to_sign, object, object_size);
243 to_sign_size = object_size;
244 SLOGI("Signing unpadded object");
245 break;
246 case KDF_SCRYPT_KEYMASTER_BADLY_PADDED:
247 // This is broken: Since the value of object is uniformly
248 // distributed, it produces a message that is larger than the
249 // public modulus with probability 0.25.
250 memcpy(to_sign, object, min(RSA_KEY_SIZE_BYTES, object_size));
251 SLOGI("Signing end-padded object");
252 break;
253 case KDF_SCRYPT_KEYMASTER:
254 // This ensures the most significant byte of the signed message
255 // is zero. We could have zero-padded to the left instead, but
256 // this approach is slightly more robust against changes in
257 // object size. However, it's still broken (but not unusably
258 // so) because we really should be using a proper RSA padding
259 // function, such as OAEP.
260 //
261 // TODO(paullawrence): When keymaster 0.4 is available, change
262 // this to use the padding options it provides.
263 memcpy(to_sign + 1, object, min(RSA_KEY_SIZE_BYTES - 1, object_size));
264 SLOGI("Signing safely-padded object");
265 break;
266 default:
267 SLOGE("Unknown KDF type %d", ftr->kdf_type);
268 return -1;
269 }
270
Shawn Willden47ba10d2014-09-03 17:07:06 -0600271 rc = keymaster_dev->sign_data(keymaster_dev,
272 &params,
273 ftr->keymaster_blob,
274 ftr->keymaster_blob_size,
275 to_sign,
Shawn Willdene17a9c42014-09-08 13:04:08 -0600276 to_sign_size,
Shawn Willden47ba10d2014-09-03 17:07:06 -0600277 signature,
278 signature_size);
279
Shawn Willdend1fd8462015-02-24 09:51:34 -0700280 keymaster0_close(keymaster_dev);
Shawn Willden47ba10d2014-09-03 17:07:06 -0600281 return rc;
282}
283
Paul Lawrence399317e2014-03-10 13:20:50 -0700284/* Store password when userdata is successfully decrypted and mounted.
285 * Cleared by cryptfs_clear_password
286 *
287 * To avoid a double prompt at boot, we need to store the CryptKeeper
288 * password and pass it to KeyGuard, which uses it to unlock KeyStore.
289 * Since the entire framework is torn down and rebuilt after encryption,
290 * we have to use a daemon or similar to store the password. Since vold
291 * is secured against IPC except from system processes, it seems a reasonable
292 * place to store this.
293 *
294 * password should be cleared once it has been used.
295 *
296 * password is aged out after password_max_age_seconds seconds.
Paul Lawrence684dbdf2014-02-07 12:07:22 -0800297 */
Paul Lawrence399317e2014-03-10 13:20:50 -0700298static char* password = 0;
299static int password_expiry_time = 0;
300static const int password_max_age_seconds = 60;
Paul Lawrence684dbdf2014-02-07 12:07:22 -0800301
Ken Sumrall56ad03c2013-02-13 13:00:19 -0800302extern struct fstab *fstab;
Ken Sumrall8ddbe402011-01-17 15:26:29 -0800303
Paul Lawrence87999172014-02-20 12:21:31 -0800304enum RebootType {reboot, recovery, shutdown};
305static void cryptfs_reboot(enum RebootType rt)
Ken Sumralladfba362013-06-04 16:37:52 -0700306{
Paul Lawrence87999172014-02-20 12:21:31 -0800307 switch(rt) {
308 case reboot:
309 property_set(ANDROID_RB_PROPERTY, "reboot");
310 break;
311
312 case recovery:
313 property_set(ANDROID_RB_PROPERTY, "reboot,recovery");
314 break;
315
316 case shutdown:
317 property_set(ANDROID_RB_PROPERTY, "shutdown");
318 break;
Ken Sumralladfba362013-06-04 16:37:52 -0700319 }
Paul Lawrence87999172014-02-20 12:21:31 -0800320
Ken Sumralladfba362013-06-04 16:37:52 -0700321 sleep(20);
322
323 /* Shouldn't get here, reboot should happen before sleep times out */
324 return;
325}
326
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800327static void ioctl_init(struct dm_ioctl *io, size_t dataSize, const char *name, unsigned flags)
328{
329 memset(io, 0, dataSize);
330 io->data_size = dataSize;
331 io->data_start = sizeof(struct dm_ioctl);
332 io->version[0] = 4;
333 io->version[1] = 0;
334 io->version[2] = 0;
335 io->flags = flags;
336 if (name) {
Marek Pola5e6b9142015-02-05 14:22:34 +0100337 strlcpy(io->name, name, sizeof(io->name));
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800338 }
339}
340
Kenny Rootc4c70f12013-06-14 12:11:38 -0700341/**
342 * Gets the default device scrypt parameters for key derivation time tuning.
343 * The parameters should lead to about one second derivation time for the
344 * given device.
345 */
346static void get_device_scrypt_params(struct crypt_mnt_ftr *ftr) {
347 const int default_params[] = SCRYPT_DEFAULTS;
348 int params[] = SCRYPT_DEFAULTS;
349 char paramstr[PROPERTY_VALUE_MAX];
350 char *token;
351 char *saveptr;
352 int i;
353
354 property_get(SCRYPT_PROP, paramstr, "");
355 if (paramstr[0] != '\0') {
356 /*
357 * The token we're looking for should be three integers separated by
358 * colons (e.g., "12:8:1"). Scan the property to make sure it matches.
359 */
Kenny Root2947e342013-08-14 15:54:49 -0700360 for (i = 0, token = strtok_r(paramstr, ":", &saveptr);
361 token != NULL && i < 3;
Kenny Rootc4c70f12013-06-14 12:11:38 -0700362 i++, token = strtok_r(NULL, ":", &saveptr)) {
363 char *endptr;
364 params[i] = strtol(token, &endptr, 10);
365
366 /*
367 * Check that there was a valid number and it's 8-bit. If not,
368 * break out and the end check will take the default values.
369 */
370 if ((*token == '\0') || (*endptr != '\0') || params[i] < 0 || params[i] > 255) {
371 break;
372 }
373 }
374
375 /*
376 * If there were not enough tokens or a token was malformed (not an
377 * integer), it will end up here and the default parameters can be
378 * taken.
379 */
380 if ((i != 3) || (token != NULL)) {
381 SLOGW("bad scrypt parameters '%s' should be like '12:8:1'; using defaults", paramstr);
382 memcpy(params, default_params, sizeof(params));
383 }
384 }
385
386 ftr->N_factor = params[0];
387 ftr->r_factor = params[1];
388 ftr->p_factor = params[2];
389}
390
Ken Sumrall3ed82362011-01-28 23:31:16 -0800391static unsigned int get_fs_size(char *dev)
392{
393 int fd, block_size;
394 struct ext4_super_block sb;
395 off64_t len;
396
397 if ((fd = open(dev, O_RDONLY)) < 0) {
398 SLOGE("Cannot open device to get filesystem size ");
399 return 0;
400 }
401
402 if (lseek64(fd, 1024, SEEK_SET) < 0) {
403 SLOGE("Cannot seek to superblock");
404 return 0;
405 }
406
407 if (read(fd, &sb, sizeof(sb)) != sizeof(sb)) {
408 SLOGE("Cannot read superblock");
409 return 0;
410 }
411
412 close(fd);
413
Daniel Rosenberge82df162014-08-15 22:19:23 +0000414 if (le32_to_cpu(sb.s_magic) != EXT4_SUPER_MAGIC) {
415 SLOGE("Not a valid ext4 superblock");
416 return 0;
417 }
Ken Sumrall3ed82362011-01-28 23:31:16 -0800418 block_size = 1024 << sb.s_log_block_size;
419 /* compute length in bytes */
420 len = ( ((off64_t)sb.s_blocks_count_hi << 32) + sb.s_blocks_count_lo) * block_size;
421
422 /* return length in sectors */
423 return (unsigned int) (len / 512);
424}
425
Ken Sumrall160b4d62013-04-22 12:15:39 -0700426static int get_crypt_ftr_info(char **metadata_fname, off64_t *off)
427{
428 static int cached_data = 0;
429 static off64_t cached_off = 0;
430 static char cached_metadata_fname[PROPERTY_VALUE_MAX] = "";
431 int fd;
432 char key_loc[PROPERTY_VALUE_MAX];
433 char real_blkdev[PROPERTY_VALUE_MAX];
Ken Sumrall160b4d62013-04-22 12:15:39 -0700434 int rc = -1;
435
436 if (!cached_data) {
437 fs_mgr_get_crypt_info(fstab, key_loc, real_blkdev, sizeof(key_loc));
438
439 if (!strcmp(key_loc, KEY_IN_FOOTER)) {
440 if ( (fd = open(real_blkdev, O_RDWR)) < 0) {
441 SLOGE("Cannot open real block device %s\n", real_blkdev);
442 return -1;
443 }
444
Hiroaki Miyazawa14eab552015-02-04 13:29:15 +0900445 unsigned long nr_sec = 0;
446 get_blkdev_size(fd, &nr_sec);
447 if (nr_sec != 0) {
Ken Sumrall160b4d62013-04-22 12:15:39 -0700448 /* If it's an encrypted Android partition, the last 16 Kbytes contain the
449 * encryption info footer and key, and plenty of bytes to spare for future
450 * growth.
451 */
452 strlcpy(cached_metadata_fname, real_blkdev, sizeof(cached_metadata_fname));
453 cached_off = ((off64_t)nr_sec * 512) - CRYPT_FOOTER_OFFSET;
454 cached_data = 1;
455 } else {
456 SLOGE("Cannot get size of block device %s\n", real_blkdev);
457 }
458 close(fd);
459 } else {
460 strlcpy(cached_metadata_fname, key_loc, sizeof(cached_metadata_fname));
461 cached_off = 0;
462 cached_data = 1;
463 }
464 }
465
466 if (cached_data) {
467 if (metadata_fname) {
468 *metadata_fname = cached_metadata_fname;
469 }
470 if (off) {
471 *off = cached_off;
472 }
473 rc = 0;
474 }
475
476 return rc;
477}
478
Ken Sumralle8744072011-01-18 22:01:55 -0800479/* key or salt can be NULL, in which case just skip writing that value. Useful to
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800480 * update the failed mount count but not change the key.
481 */
Ken Sumrall160b4d62013-04-22 12:15:39 -0700482static int put_crypt_ftr_and_key(struct crypt_mnt_ftr *crypt_ftr)
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800483{
484 int fd;
Tim Murray8439dc92014-12-15 11:56:11 -0800485 unsigned int cnt;
Ken Sumrall160b4d62013-04-22 12:15:39 -0700486 /* starting_off is set to the SEEK_SET offset
487 * where the crypto structure starts
488 */
489 off64_t starting_off;
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800490 int rc = -1;
Ken Sumrall160b4d62013-04-22 12:15:39 -0700491 char *fname = NULL;
Ken Sumrall3be890f2011-09-14 16:53:46 -0700492 struct stat statbuf;
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800493
Ken Sumrall160b4d62013-04-22 12:15:39 -0700494 if (get_crypt_ftr_info(&fname, &starting_off)) {
495 SLOGE("Unable to get crypt_ftr_info\n");
496 return -1;
497 }
498 if (fname[0] != '/') {
Ken Sumralle5032c42012-04-01 23:58:44 -0700499 SLOGE("Unexpected value for crypto key location\n");
Ken Sumrall160b4d62013-04-22 12:15:39 -0700500 return -1;
501 }
Ken Sumralle550f782013-08-20 13:48:23 -0700502 if ( (fd = open(fname, O_RDWR | O_CREAT, 0600)) < 0) {
503 SLOGE("Cannot open footer file %s for put\n", fname);
Ken Sumrall160b4d62013-04-22 12:15:39 -0700504 return -1;
505 }
506
507 /* Seek to the start of the crypt footer */
508 if (lseek64(fd, starting_off, SEEK_SET) == -1) {
509 SLOGE("Cannot seek to real block device footer\n");
510 goto errout;
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800511 }
512
513 if ((cnt = write(fd, crypt_ftr, sizeof(struct crypt_mnt_ftr))) != sizeof(struct crypt_mnt_ftr)) {
514 SLOGE("Cannot write real block device footer\n");
515 goto errout;
516 }
517
Ken Sumrall3be890f2011-09-14 16:53:46 -0700518 fstat(fd, &statbuf);
519 /* If the keys are kept on a raw block device, do not try to truncate it. */
Ken Sumralle550f782013-08-20 13:48:23 -0700520 if (S_ISREG(statbuf.st_mode)) {
Ken Sumrall29d8da82011-05-18 17:20:07 -0700521 if (ftruncate(fd, 0x4000)) {
Colin Cross59846b62014-02-06 20:34:29 -0800522 SLOGE("Cannot set footer file size\n");
Ken Sumralle8744072011-01-18 22:01:55 -0800523 goto errout;
524 }
525 }
526
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800527 /* Success! */
528 rc = 0;
529
530errout:
531 close(fd);
532 return rc;
533
534}
535
Ken Sumrall160b4d62013-04-22 12:15:39 -0700536static inline int unix_read(int fd, void* buff, int len)
537{
538 return TEMP_FAILURE_RETRY(read(fd, buff, len));
539}
540
541static inline int unix_write(int fd, const void* buff, int len)
542{
543 return TEMP_FAILURE_RETRY(write(fd, buff, len));
544}
545
546static void init_empty_persist_data(struct crypt_persist_data *pdata, int len)
547{
548 memset(pdata, 0, len);
549 pdata->persist_magic = PERSIST_DATA_MAGIC;
550 pdata->persist_valid_entries = 0;
551}
552
553/* A routine to update the passed in crypt_ftr to the lastest version.
554 * fd is open read/write on the device that holds the crypto footer and persistent
555 * data, crypt_ftr is a pointer to the struct to be updated, and offset is the
556 * absolute offset to the start of the crypt_mnt_ftr on the passed in fd.
557 */
558static void upgrade_crypt_ftr(int fd, struct crypt_mnt_ftr *crypt_ftr, off64_t offset)
559{
Kenny Root7434b312013-06-14 11:29:53 -0700560 int orig_major = crypt_ftr->major_version;
561 int orig_minor = crypt_ftr->minor_version;
Ken Sumrall160b4d62013-04-22 12:15:39 -0700562
Kenny Root7434b312013-06-14 11:29:53 -0700563 if ((crypt_ftr->major_version == 1) && (crypt_ftr->minor_version == 0)) {
564 struct crypt_persist_data *pdata;
565 off64_t pdata_offset = offset + CRYPT_FOOTER_TO_PERSIST_OFFSET;
Ken Sumrall160b4d62013-04-22 12:15:39 -0700566
Kenny Rootc4c70f12013-06-14 12:11:38 -0700567 SLOGW("upgrading crypto footer to 1.1");
568
Kenny Root7434b312013-06-14 11:29:53 -0700569 pdata = malloc(CRYPT_PERSIST_DATA_SIZE);
570 if (pdata == NULL) {
571 SLOGE("Cannot allocate persisent data\n");
572 return;
573 }
574 memset(pdata, 0, CRYPT_PERSIST_DATA_SIZE);
575
576 /* Need to initialize the persistent data area */
577 if (lseek64(fd, pdata_offset, SEEK_SET) == -1) {
578 SLOGE("Cannot seek to persisent data offset\n");
Henrik Baard91064632015-02-05 15:09:17 +0100579 free(pdata);
Kenny Root7434b312013-06-14 11:29:53 -0700580 return;
581 }
582 /* Write all zeros to the first copy, making it invalid */
583 unix_write(fd, pdata, CRYPT_PERSIST_DATA_SIZE);
584
585 /* Write a valid but empty structure to the second copy */
586 init_empty_persist_data(pdata, CRYPT_PERSIST_DATA_SIZE);
587 unix_write(fd, pdata, CRYPT_PERSIST_DATA_SIZE);
588
589 /* Update the footer */
590 crypt_ftr->persist_data_size = CRYPT_PERSIST_DATA_SIZE;
591 crypt_ftr->persist_data_offset[0] = pdata_offset;
592 crypt_ftr->persist_data_offset[1] = pdata_offset + CRYPT_PERSIST_DATA_SIZE;
593 crypt_ftr->minor_version = 1;
Henrik Baard91064632015-02-05 15:09:17 +0100594 free(pdata);
Ken Sumrall160b4d62013-04-22 12:15:39 -0700595 }
596
Paul Lawrencef4faa572014-01-29 13:31:03 -0800597 if ((crypt_ftr->major_version == 1) && (crypt_ftr->minor_version == 1)) {
Kenny Rootc4c70f12013-06-14 12:11:38 -0700598 SLOGW("upgrading crypto footer to 1.2");
JP Abgrall7bdfa522013-11-15 13:42:56 -0800599 /* But keep the old kdf_type.
600 * It will get updated later to KDF_SCRYPT after the password has been verified.
601 */
Kenny Rootc4c70f12013-06-14 12:11:38 -0700602 crypt_ftr->kdf_type = KDF_PBKDF2;
603 get_device_scrypt_params(crypt_ftr);
604 crypt_ftr->minor_version = 2;
605 }
606
Paul Lawrencef4faa572014-01-29 13:31:03 -0800607 if ((crypt_ftr->major_version == 1) && (crypt_ftr->minor_version == 2)) {
608 SLOGW("upgrading crypto footer to 1.3");
609 crypt_ftr->crypt_type = CRYPT_TYPE_PASSWORD;
610 crypt_ftr->minor_version = 3;
611 }
612
Kenny Root7434b312013-06-14 11:29:53 -0700613 if ((orig_major != crypt_ftr->major_version) || (orig_minor != crypt_ftr->minor_version)) {
614 if (lseek64(fd, offset, SEEK_SET) == -1) {
615 SLOGE("Cannot seek to crypt footer\n");
616 return;
617 }
618 unix_write(fd, crypt_ftr, sizeof(struct crypt_mnt_ftr));
Ken Sumrall160b4d62013-04-22 12:15:39 -0700619 }
Ken Sumrall160b4d62013-04-22 12:15:39 -0700620}
621
622
623static int get_crypt_ftr_and_key(struct crypt_mnt_ftr *crypt_ftr)
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800624{
625 int fd;
Tim Murray8439dc92014-12-15 11:56:11 -0800626 unsigned int cnt;
Ken Sumrall160b4d62013-04-22 12:15:39 -0700627 off64_t starting_off;
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800628 int rc = -1;
Ken Sumrall160b4d62013-04-22 12:15:39 -0700629 char *fname = NULL;
Ken Sumrall29d8da82011-05-18 17:20:07 -0700630 struct stat statbuf;
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800631
Ken Sumrall160b4d62013-04-22 12:15:39 -0700632 if (get_crypt_ftr_info(&fname, &starting_off)) {
633 SLOGE("Unable to get crypt_ftr_info\n");
634 return -1;
635 }
636 if (fname[0] != '/') {
Ken Sumralle5032c42012-04-01 23:58:44 -0700637 SLOGE("Unexpected value for crypto key location\n");
Ken Sumrall160b4d62013-04-22 12:15:39 -0700638 return -1;
639 }
640 if ( (fd = open(fname, O_RDWR)) < 0) {
Ken Sumralle550f782013-08-20 13:48:23 -0700641 SLOGE("Cannot open footer file %s for get\n", fname);
Ken Sumrall160b4d62013-04-22 12:15:39 -0700642 return -1;
643 }
644
645 /* Make sure it's 16 Kbytes in length */
646 fstat(fd, &statbuf);
647 if (S_ISREG(statbuf.st_mode) && (statbuf.st_size != 0x4000)) {
648 SLOGE("footer file %s is not the expected size!\n", fname);
649 goto errout;
650 }
651
652 /* Seek to the start of the crypt footer */
653 if (lseek64(fd, starting_off, SEEK_SET) == -1) {
654 SLOGE("Cannot seek to real block device footer\n");
655 goto errout;
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800656 }
657
658 if ( (cnt = read(fd, crypt_ftr, sizeof(struct crypt_mnt_ftr))) != sizeof(struct crypt_mnt_ftr)) {
659 SLOGE("Cannot read real block device footer\n");
660 goto errout;
661 }
662
663 if (crypt_ftr->magic != CRYPT_MNT_MAGIC) {
Ken Sumrall29d8da82011-05-18 17:20:07 -0700664 SLOGE("Bad magic for real block device %s\n", fname);
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800665 goto errout;
666 }
667
Kenny Rootc96a5f82013-06-14 12:08:28 -0700668 if (crypt_ftr->major_version != CURRENT_MAJOR_VERSION) {
669 SLOGE("Cannot understand major version %d real block device footer; expected %d\n",
670 crypt_ftr->major_version, CURRENT_MAJOR_VERSION);
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800671 goto errout;
672 }
673
Kenny Rootc96a5f82013-06-14 12:08:28 -0700674 if (crypt_ftr->minor_version > CURRENT_MINOR_VERSION) {
675 SLOGW("Warning: crypto footer minor version %d, expected <= %d, continuing...\n",
676 crypt_ftr->minor_version, CURRENT_MINOR_VERSION);
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800677 }
678
Ken Sumrall160b4d62013-04-22 12:15:39 -0700679 /* If this is a verion 1.0 crypt_ftr, make it a 1.1 crypt footer, and update the
680 * copy on disk before returning.
681 */
Kenny Rootc96a5f82013-06-14 12:08:28 -0700682 if (crypt_ftr->minor_version < CURRENT_MINOR_VERSION) {
Ken Sumrall160b4d62013-04-22 12:15:39 -0700683 upgrade_crypt_ftr(fd, crypt_ftr, starting_off);
Ken Sumralle8744072011-01-18 22:01:55 -0800684 }
685
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800686 /* Success! */
687 rc = 0;
688
689errout:
690 close(fd);
691 return rc;
692}
693
Ken Sumrall160b4d62013-04-22 12:15:39 -0700694static int validate_persistent_data_storage(struct crypt_mnt_ftr *crypt_ftr)
695{
696 if (crypt_ftr->persist_data_offset[0] + crypt_ftr->persist_data_size >
697 crypt_ftr->persist_data_offset[1]) {
698 SLOGE("Crypt_ftr persist data regions overlap");
699 return -1;
700 }
701
702 if (crypt_ftr->persist_data_offset[0] >= crypt_ftr->persist_data_offset[1]) {
703 SLOGE("Crypt_ftr persist data region 0 starts after region 1");
704 return -1;
705 }
706
707 if (((crypt_ftr->persist_data_offset[1] + crypt_ftr->persist_data_size) -
708 (crypt_ftr->persist_data_offset[0] - CRYPT_FOOTER_TO_PERSIST_OFFSET)) >
709 CRYPT_FOOTER_OFFSET) {
710 SLOGE("Persistent data extends past crypto footer");
711 return -1;
712 }
713
714 return 0;
715}
716
717static int load_persistent_data(void)
718{
719 struct crypt_mnt_ftr crypt_ftr;
720 struct crypt_persist_data *pdata = NULL;
721 char encrypted_state[PROPERTY_VALUE_MAX];
722 char *fname;
723 int found = 0;
724 int fd;
725 int ret;
726 int i;
727
728 if (persist_data) {
729 /* Nothing to do, we've already loaded or initialized it */
730 return 0;
731 }
732
733
734 /* If not encrypted, just allocate an empty table and initialize it */
735 property_get("ro.crypto.state", encrypted_state, "");
736 if (strcmp(encrypted_state, "encrypted") ) {
737 pdata = malloc(CRYPT_PERSIST_DATA_SIZE);
738 if (pdata) {
739 init_empty_persist_data(pdata, CRYPT_PERSIST_DATA_SIZE);
740 persist_data = pdata;
741 return 0;
742 }
743 return -1;
744 }
745
746 if(get_crypt_ftr_and_key(&crypt_ftr)) {
747 return -1;
748 }
749
Paul Lawrence8561b5c2014-03-17 14:10:51 -0700750 if ((crypt_ftr.major_version < 1)
751 || (crypt_ftr.major_version == 1 && crypt_ftr.minor_version < 1)) {
Ken Sumrall160b4d62013-04-22 12:15:39 -0700752 SLOGE("Crypt_ftr version doesn't support persistent data");
753 return -1;
754 }
755
756 if (get_crypt_ftr_info(&fname, NULL)) {
757 return -1;
758 }
759
760 ret = validate_persistent_data_storage(&crypt_ftr);
761 if (ret) {
762 return -1;
763 }
764
765 fd = open(fname, O_RDONLY);
766 if (fd < 0) {
767 SLOGE("Cannot open %s metadata file", fname);
768 return -1;
769 }
770
771 if (persist_data == NULL) {
772 pdata = malloc(crypt_ftr.persist_data_size);
773 if (pdata == NULL) {
774 SLOGE("Cannot allocate memory for persistent data");
775 goto err;
776 }
777 }
778
779 for (i = 0; i < 2; i++) {
780 if (lseek64(fd, crypt_ftr.persist_data_offset[i], SEEK_SET) < 0) {
781 SLOGE("Cannot seek to read persistent data on %s", fname);
782 goto err2;
783 }
784 if (unix_read(fd, pdata, crypt_ftr.persist_data_size) < 0){
785 SLOGE("Error reading persistent data on iteration %d", i);
786 goto err2;
787 }
788 if (pdata->persist_magic == PERSIST_DATA_MAGIC) {
789 found = 1;
790 break;
791 }
792 }
793
794 if (!found) {
795 SLOGI("Could not find valid persistent data, creating");
796 init_empty_persist_data(pdata, crypt_ftr.persist_data_size);
797 }
798
799 /* Success */
800 persist_data = pdata;
801 close(fd);
802 return 0;
803
804err2:
805 free(pdata);
806
807err:
808 close(fd);
809 return -1;
810}
811
812static int save_persistent_data(void)
813{
814 struct crypt_mnt_ftr crypt_ftr;
815 struct crypt_persist_data *pdata;
816 char *fname;
817 off64_t write_offset;
818 off64_t erase_offset;
Ken Sumrall160b4d62013-04-22 12:15:39 -0700819 int fd;
820 int ret;
821
822 if (persist_data == NULL) {
823 SLOGE("No persistent data to save");
824 return -1;
825 }
826
827 if(get_crypt_ftr_and_key(&crypt_ftr)) {
828 return -1;
829 }
830
Paul Lawrence8561b5c2014-03-17 14:10:51 -0700831 if ((crypt_ftr.major_version < 1)
832 || (crypt_ftr.major_version == 1 && crypt_ftr.minor_version < 1)) {
Ken Sumrall160b4d62013-04-22 12:15:39 -0700833 SLOGE("Crypt_ftr version doesn't support persistent data");
834 return -1;
835 }
836
837 ret = validate_persistent_data_storage(&crypt_ftr);
838 if (ret) {
839 return -1;
840 }
841
842 if (get_crypt_ftr_info(&fname, NULL)) {
843 return -1;
844 }
845
846 fd = open(fname, O_RDWR);
847 if (fd < 0) {
848 SLOGE("Cannot open %s metadata file", fname);
849 return -1;
850 }
851
852 pdata = malloc(crypt_ftr.persist_data_size);
853 if (pdata == NULL) {
854 SLOGE("Cannot allocate persistant data");
855 goto err;
856 }
857
858 if (lseek64(fd, crypt_ftr.persist_data_offset[0], SEEK_SET) < 0) {
859 SLOGE("Cannot seek to read persistent data on %s", fname);
860 goto err2;
861 }
862
863 if (unix_read(fd, pdata, crypt_ftr.persist_data_size) < 0) {
864 SLOGE("Error reading persistent data before save");
865 goto err2;
866 }
867
868 if (pdata->persist_magic == PERSIST_DATA_MAGIC) {
869 /* The first copy is the curent valid copy, so write to
870 * the second copy and erase this one */
871 write_offset = crypt_ftr.persist_data_offset[1];
872 erase_offset = crypt_ftr.persist_data_offset[0];
873 } else {
874 /* The second copy must be the valid copy, so write to
875 * the first copy, and erase the second */
876 write_offset = crypt_ftr.persist_data_offset[0];
877 erase_offset = crypt_ftr.persist_data_offset[1];
878 }
879
880 /* Write the new copy first, if successful, then erase the old copy */
Björn Landström96dbee72015-01-20 12:43:56 +0100881 if (lseek64(fd, write_offset, SEEK_SET) < 0) {
Ken Sumrall160b4d62013-04-22 12:15:39 -0700882 SLOGE("Cannot seek to write persistent data");
883 goto err2;
884 }
885 if (unix_write(fd, persist_data, crypt_ftr.persist_data_size) ==
886 (int) crypt_ftr.persist_data_size) {
Björn Landström96dbee72015-01-20 12:43:56 +0100887 if (lseek64(fd, erase_offset, SEEK_SET) < 0) {
Ken Sumrall160b4d62013-04-22 12:15:39 -0700888 SLOGE("Cannot seek to erase previous persistent data");
889 goto err2;
890 }
891 fsync(fd);
892 memset(pdata, 0, crypt_ftr.persist_data_size);
893 if (unix_write(fd, pdata, crypt_ftr.persist_data_size) !=
894 (int) crypt_ftr.persist_data_size) {
895 SLOGE("Cannot write to erase previous persistent data");
896 goto err2;
897 }
898 fsync(fd);
899 } else {
900 SLOGE("Cannot write to save persistent data");
901 goto err2;
902 }
903
904 /* Success */
905 free(pdata);
906 close(fd);
907 return 0;
908
909err2:
910 free(pdata);
911err:
912 close(fd);
913 return -1;
914}
915
Paul Lawrencef4faa572014-01-29 13:31:03 -0800916static int hexdigit (char c)
917{
918 if (c >= '0' && c <= '9') return c - '0';
919 c = tolower(c);
920 if (c >= 'a' && c <= 'f') return c - 'a' + 10;
921 return -1;
922}
923
924static unsigned char* convert_hex_ascii_to_key(const char* master_key_ascii,
925 unsigned int* out_keysize)
926{
927 unsigned int i;
928 *out_keysize = 0;
929
930 size_t size = strlen (master_key_ascii);
931 if (size % 2) {
932 SLOGE("Trying to convert ascii string of odd length");
933 return NULL;
934 }
935
936 unsigned char* master_key = (unsigned char*) malloc(size / 2);
937 if (master_key == 0) {
938 SLOGE("Cannot allocate");
939 return NULL;
940 }
941
942 for (i = 0; i < size; i += 2) {
943 int high_nibble = hexdigit (master_key_ascii[i]);
944 int low_nibble = hexdigit (master_key_ascii[i + 1]);
945
946 if(high_nibble < 0 || low_nibble < 0) {
947 SLOGE("Invalid hex string");
948 free (master_key);
949 return NULL;
950 }
951
952 master_key[*out_keysize] = high_nibble * 16 + low_nibble;
953 (*out_keysize)++;
954 }
955
956 return master_key;
957}
958
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800959/* Convert a binary key of specified length into an ascii hex string equivalent,
960 * without the leading 0x and with null termination
961 */
Paul Lawrencef4faa572014-01-29 13:31:03 -0800962static void convert_key_to_hex_ascii(unsigned char *master_key, unsigned int keysize,
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800963 char *master_key_ascii)
964{
965 unsigned int i, a;
966 unsigned char nibble;
967
968 for (i=0, a=0; i<keysize; i++, a+=2) {
969 /* For each byte, write out two ascii hex digits */
970 nibble = (master_key[i] >> 4) & 0xf;
971 master_key_ascii[a] = nibble + (nibble > 9 ? 0x37 : 0x30);
972
973 nibble = master_key[i] & 0xf;
974 master_key_ascii[a+1] = nibble + (nibble > 9 ? 0x37 : 0x30);
975 }
976
977 /* Add the null termination */
978 master_key_ascii[a] = '\0';
979
980}
981
Ken Sumralldb5e0262013-02-05 17:39:48 -0800982static int load_crypto_mapping_table(struct crypt_mnt_ftr *crypt_ftr, unsigned char *master_key,
983 char *real_blk_name, const char *name, int fd,
984 char *extra_params)
985{
Dan Albertc07fa3f2014-12-18 10:00:55 -0800986 _Alignas(struct dm_ioctl) char buffer[DM_CRYPT_BUF_SIZE];
Ken Sumralldb5e0262013-02-05 17:39:48 -0800987 struct dm_ioctl *io;
988 struct dm_target_spec *tgt;
989 char *crypt_params;
990 char master_key_ascii[129]; /* Large enough to hold 512 bit key and null */
991 int i;
992
993 io = (struct dm_ioctl *) buffer;
994
995 /* Load the mapping table for this device */
996 tgt = (struct dm_target_spec *) &buffer[sizeof(struct dm_ioctl)];
997
998 ioctl_init(io, DM_CRYPT_BUF_SIZE, name, 0);
999 io->target_count = 1;
1000 tgt->status = 0;
1001 tgt->sector_start = 0;
1002 tgt->length = crypt_ftr->fs_size;
Ajay Dudani87701e22014-09-17 21:02:52 -07001003#ifdef CONFIG_HW_DISK_ENCRYPTION
Iliyan Malchevbb7d9af2014-11-20 18:42:23 -08001004 if (!strcmp((char *)crypt_ftr->crypto_type_name, "aes-xts")) {
1005 strlcpy(tgt->target_type, "req-crypt", DM_MAX_TYPE_NAME);
1006 }
1007 else {
1008 strlcpy(tgt->target_type, "crypt", DM_MAX_TYPE_NAME);
1009 }
Ajay Dudani87701e22014-09-17 21:02:52 -07001010#else
1011 strlcpy(tgt->target_type, "crypt", DM_MAX_TYPE_NAME);
1012#endif
Ken Sumralldb5e0262013-02-05 17:39:48 -08001013
1014 crypt_params = buffer + sizeof(struct dm_ioctl) + sizeof(struct dm_target_spec);
1015 convert_key_to_hex_ascii(master_key, crypt_ftr->keysize, master_key_ascii);
1016 sprintf(crypt_params, "%s %s 0 %s 0 %s", crypt_ftr->crypto_type_name,
1017 master_key_ascii, real_blk_name, extra_params);
1018 crypt_params += strlen(crypt_params) + 1;
1019 crypt_params = (char *) (((unsigned long)crypt_params + 7) & ~8); /* Align to an 8 byte boundary */
1020 tgt->next = crypt_params - buffer;
1021
1022 for (i = 0; i < TABLE_LOAD_RETRIES; i++) {
1023 if (! ioctl(fd, DM_TABLE_LOAD, io)) {
1024 break;
1025 }
1026 usleep(500000);
1027 }
1028
1029 if (i == TABLE_LOAD_RETRIES) {
1030 /* We failed to load the table, return an error */
1031 return -1;
1032 } else {
1033 return i + 1;
1034 }
1035}
1036
1037
1038static int get_dm_crypt_version(int fd, const char *name, int *version)
1039{
1040 char buffer[DM_CRYPT_BUF_SIZE];
1041 struct dm_ioctl *io;
1042 struct dm_target_versions *v;
Ken Sumralldb5e0262013-02-05 17:39:48 -08001043
1044 io = (struct dm_ioctl *) buffer;
1045
1046 ioctl_init(io, DM_CRYPT_BUF_SIZE, name, 0);
1047
1048 if (ioctl(fd, DM_LIST_VERSIONS, io)) {
1049 return -1;
1050 }
1051
1052 /* Iterate over the returned versions, looking for name of "crypt".
1053 * When found, get and return the version.
1054 */
1055 v = (struct dm_target_versions *) &buffer[sizeof(struct dm_ioctl)];
1056 while (v->next) {
Ajay Dudani87701e22014-09-17 21:02:52 -07001057#ifdef CONFIG_HW_DISK_ENCRYPTION
Iliyan Malchevbb7d9af2014-11-20 18:42:23 -08001058 if (! strcmp(v->name, "crypt") || ! strcmp(v->name, "req-crypt")) {
Ajay Dudani87701e22014-09-17 21:02:52 -07001059#else
Ken Sumralldb5e0262013-02-05 17:39:48 -08001060 if (! strcmp(v->name, "crypt")) {
Ajay Dudani87701e22014-09-17 21:02:52 -07001061#endif
Ken Sumralldb5e0262013-02-05 17:39:48 -08001062 /* We found the crypt driver, return the version, and get out */
1063 version[0] = v->version[0];
1064 version[1] = v->version[1];
1065 version[2] = v->version[2];
1066 return 0;
1067 }
1068 v = (struct dm_target_versions *)(((char *)v) + v->next);
1069 }
1070
1071 return -1;
1072}
1073
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001074static int create_crypto_blk_dev(struct crypt_mnt_ftr *crypt_ftr, unsigned char *master_key,
Ken Sumrall29d8da82011-05-18 17:20:07 -07001075 char *real_blk_name, char *crypto_blk_name, const char *name)
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001076{
1077 char buffer[DM_CRYPT_BUF_SIZE];
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001078 struct dm_ioctl *io;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001079 unsigned int minor;
Ajay Dudani87701e22014-09-17 21:02:52 -07001080 int fd=0;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001081 int retval = -1;
Ken Sumralldb5e0262013-02-05 17:39:48 -08001082 int version[3];
1083 char *extra_params;
1084 int load_count;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001085
1086 if ((fd = open("/dev/device-mapper", O_RDWR)) < 0 ) {
1087 SLOGE("Cannot open device-mapper\n");
1088 goto errout;
1089 }
1090
1091 io = (struct dm_ioctl *) buffer;
1092
1093 ioctl_init(io, DM_CRYPT_BUF_SIZE, name, 0);
1094 if (ioctl(fd, DM_DEV_CREATE, io)) {
1095 SLOGE("Cannot create dm-crypt device\n");
1096 goto errout;
1097 }
1098
1099 /* Get the device status, in particular, the name of it's device file */
1100 ioctl_init(io, DM_CRYPT_BUF_SIZE, name, 0);
1101 if (ioctl(fd, DM_DEV_STATUS, io)) {
1102 SLOGE("Cannot retrieve dm-crypt device status\n");
1103 goto errout;
1104 }
1105 minor = (io->dev & 0xff) | ((io->dev >> 12) & 0xfff00);
1106 snprintf(crypto_blk_name, MAXPATHLEN, "/dev/block/dm-%u", minor);
1107
Ken Sumralldb5e0262013-02-05 17:39:48 -08001108 extra_params = "";
1109 if (! get_dm_crypt_version(fd, name, version)) {
1110 /* Support for allow_discards was added in version 1.11.0 */
1111 if ((version[0] >= 2) ||
1112 ((version[0] == 1) && (version[1] >= 11))) {
1113 extra_params = "1 allow_discards";
1114 SLOGI("Enabling support for allow_discards in dmcrypt.\n");
1115 }
Ken Sumralle919efe2012-09-29 17:07:41 -07001116 }
1117
Ken Sumralldb5e0262013-02-05 17:39:48 -08001118 load_count = load_crypto_mapping_table(crypt_ftr, master_key, real_blk_name, name,
1119 fd, extra_params);
1120 if (load_count < 0) {
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001121 SLOGE("Cannot load dm-crypt mapping table.\n");
1122 goto errout;
Ken Sumralldb5e0262013-02-05 17:39:48 -08001123 } else if (load_count > 1) {
1124 SLOGI("Took %d tries to load dmcrypt table.\n", load_count);
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001125 }
1126
1127 /* Resume this device to activate it */
Ken Sumralldb5e0262013-02-05 17:39:48 -08001128 ioctl_init(io, DM_CRYPT_BUF_SIZE, name, 0);
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001129
1130 if (ioctl(fd, DM_DEV_SUSPEND, io)) {
1131 SLOGE("Cannot resume the dm-crypt device\n");
1132 goto errout;
1133 }
1134
1135 /* We made it here with no errors. Woot! */
1136 retval = 0;
1137
1138errout:
1139 close(fd); /* If fd is <0 from a failed open call, it's safe to just ignore the close error */
1140
1141 return retval;
1142}
1143
Ken Sumrall29d8da82011-05-18 17:20:07 -07001144static int delete_crypto_blk_dev(char *name)
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001145{
1146 int fd;
1147 char buffer[DM_CRYPT_BUF_SIZE];
1148 struct dm_ioctl *io;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001149 int retval = -1;
1150
1151 if ((fd = open("/dev/device-mapper", O_RDWR)) < 0 ) {
1152 SLOGE("Cannot open device-mapper\n");
1153 goto errout;
1154 }
1155
1156 io = (struct dm_ioctl *) buffer;
1157
1158 ioctl_init(io, DM_CRYPT_BUF_SIZE, name, 0);
1159 if (ioctl(fd, DM_DEV_REMOVE, io)) {
1160 SLOGE("Cannot remove dm-crypt device\n");
1161 goto errout;
1162 }
1163
1164 /* We made it here with no errors. Woot! */
1165 retval = 0;
1166
1167errout:
1168 close(fd); /* If fd is <0 from a failed open call, it's safe to just ignore the close error */
1169
1170 return retval;
1171
1172}
1173
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001174static int pbkdf2(const char *passwd, const unsigned char *salt,
Paul Lawrencef4faa572014-01-29 13:31:03 -08001175 unsigned char *ikey, void *params UNUSED)
1176{
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001177 SLOGI("Using pbkdf2 for cryptfs KDF");
1178
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001179 /* Turn the password into a key and IV that can decrypt the master key */
Paul Lawrencef4faa572014-01-29 13:31:03 -08001180 unsigned int keysize;
1181 char* master_key = (char*)convert_hex_ascii_to_key(passwd, &keysize);
1182 if (!master_key) return -1;
1183 PKCS5_PBKDF2_HMAC_SHA1(master_key, keysize, salt, SALT_LEN,
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001184 HASH_COUNT, KEY_LEN_BYTES+IV_LEN_BYTES, ikey);
Paul Lawrencef4faa572014-01-29 13:31:03 -08001185
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001186 memset(master_key, 0, keysize);
Paul Lawrencef4faa572014-01-29 13:31:03 -08001187 free (master_key);
1188 return 0;
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001189}
1190
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001191static int scrypt(const char *passwd, const unsigned char *salt,
Paul Lawrencef4faa572014-01-29 13:31:03 -08001192 unsigned char *ikey, void *params)
1193{
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001194 SLOGI("Using scrypt for cryptfs KDF");
1195
Kenny Rootc4c70f12013-06-14 12:11:38 -07001196 struct crypt_mnt_ftr *ftr = (struct crypt_mnt_ftr *) params;
1197
1198 int N = 1 << ftr->N_factor;
1199 int r = 1 << ftr->r_factor;
1200 int p = 1 << ftr->p_factor;
1201
1202 /* Turn the password into a key and IV that can decrypt the master key */
Paul Lawrencef4faa572014-01-29 13:31:03 -08001203 unsigned int keysize;
1204 unsigned char* master_key = convert_hex_ascii_to_key(passwd, &keysize);
1205 if (!master_key) return -1;
1206 crypto_scrypt(master_key, keysize, salt, SALT_LEN, N, r, p, ikey,
Kenny Rootc4c70f12013-06-14 12:11:38 -07001207 KEY_LEN_BYTES + IV_LEN_BYTES);
Paul Lawrencef4faa572014-01-29 13:31:03 -08001208
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001209 memset(master_key, 0, keysize);
Paul Lawrencef4faa572014-01-29 13:31:03 -08001210 free (master_key);
1211 return 0;
Kenny Rootc4c70f12013-06-14 12:11:38 -07001212}
1213
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001214static int scrypt_keymaster(const char *passwd, const unsigned char *salt,
1215 unsigned char *ikey, void *params)
1216{
1217 SLOGI("Using scrypt with keymaster for cryptfs KDF");
1218
1219 int rc;
1220 unsigned int key_size;
1221 size_t signature_size;
1222 unsigned char* signature;
1223 struct crypt_mnt_ftr *ftr = (struct crypt_mnt_ftr *) params;
1224
1225 int N = 1 << ftr->N_factor;
1226 int r = 1 << ftr->r_factor;
1227 int p = 1 << ftr->p_factor;
1228
1229 unsigned char* master_key = convert_hex_ascii_to_key(passwd, &key_size);
1230 if (!master_key) {
1231 SLOGE("Failed to convert passwd from hex");
1232 return -1;
1233 }
1234
1235 rc = crypto_scrypt(master_key, key_size, salt, SALT_LEN,
1236 N, r, p, ikey, KEY_LEN_BYTES + IV_LEN_BYTES);
1237 memset(master_key, 0, key_size);
1238 free(master_key);
1239
1240 if (rc) {
1241 SLOGE("scrypt failed");
1242 return -1;
1243 }
1244
Shawn Willdene17a9c42014-09-08 13:04:08 -06001245 if (keymaster_sign_object(ftr, ikey, KEY_LEN_BYTES + IV_LEN_BYTES,
1246 &signature, &signature_size)) {
1247 SLOGE("Signing failed");
1248 return -1;
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001249 }
1250
1251 rc = crypto_scrypt(signature, signature_size, salt, SALT_LEN,
1252 N, r, p, ikey, KEY_LEN_BYTES + IV_LEN_BYTES);
1253 free(signature);
1254
1255 if (rc) {
1256 SLOGE("scrypt failed");
1257 return -1;
1258 }
1259
1260 return 0;
1261}
1262
1263static int encrypt_master_key(const char *passwd, const unsigned char *salt,
1264 const unsigned char *decrypted_master_key,
Kenny Rootc4c70f12013-06-14 12:11:38 -07001265 unsigned char *encrypted_master_key,
1266 struct crypt_mnt_ftr *crypt_ftr)
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001267{
1268 unsigned char ikey[32+32] = { 0 }; /* Big enough to hold a 256 bit key and 256 bit IV */
1269 EVP_CIPHER_CTX e_ctx;
1270 int encrypted_len, final_len;
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001271 int rc = 0;
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001272
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001273 /* Turn the password into an intermediate key and IV that can decrypt the master key */
Kenny Rootc4c70f12013-06-14 12:11:38 -07001274 get_device_scrypt_params(crypt_ftr);
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001275
1276 switch (crypt_ftr->kdf_type) {
Shawn Willdene17a9c42014-09-08 13:04:08 -06001277 case KDF_SCRYPT_KEYMASTER_UNPADDED:
1278 case KDF_SCRYPT_KEYMASTER_BADLY_PADDED:
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001279 case KDF_SCRYPT_KEYMASTER:
1280 if (keymaster_create_key(crypt_ftr)) {
1281 SLOGE("keymaster_create_key failed");
1282 return -1;
1283 }
1284
1285 if (scrypt_keymaster(passwd, salt, ikey, crypt_ftr)) {
1286 SLOGE("scrypt failed");
1287 return -1;
1288 }
1289 break;
1290
1291 case KDF_SCRYPT:
1292 if (scrypt(passwd, salt, ikey, crypt_ftr)) {
1293 SLOGE("scrypt failed");
1294 return -1;
1295 }
1296 break;
1297
1298 default:
1299 SLOGE("Invalid kdf_type");
Paul Lawrencef4faa572014-01-29 13:31:03 -08001300 return -1;
1301 }
Kenny Rootc4c70f12013-06-14 12:11:38 -07001302
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001303 /* Initialize the decryption engine */
Adam Langley889c4f12014-09-03 14:23:13 -07001304 EVP_CIPHER_CTX_init(&e_ctx);
1305 if (! EVP_EncryptInit_ex(&e_ctx, EVP_aes_128_cbc(), NULL, ikey, ikey+KEY_LEN_BYTES)) {
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001306 SLOGE("EVP_EncryptInit failed\n");
1307 return -1;
1308 }
1309 EVP_CIPHER_CTX_set_padding(&e_ctx, 0); /* Turn off padding as our data is block aligned */
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001310
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001311 /* Encrypt the master key */
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001312 if (! EVP_EncryptUpdate(&e_ctx, encrypted_master_key, &encrypted_len,
1313 decrypted_master_key, KEY_LEN_BYTES)) {
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001314 SLOGE("EVP_EncryptUpdate failed\n");
1315 return -1;
1316 }
Adam Langley889c4f12014-09-03 14:23:13 -07001317 if (! EVP_EncryptFinal_ex(&e_ctx, encrypted_master_key + encrypted_len, &final_len)) {
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001318 SLOGE("EVP_EncryptFinal failed\n");
1319 return -1;
1320 }
1321
1322 if (encrypted_len + final_len != KEY_LEN_BYTES) {
1323 SLOGE("EVP_Encryption length check failed with %d, %d bytes\n", encrypted_len, final_len);
1324 return -1;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001325 }
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001326
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001327 /* Store the scrypt of the intermediate key, so we can validate if it's a
1328 password error or mount error when things go wrong.
1329 Note there's no need to check for errors, since if this is incorrect, we
1330 simply won't wipe userdata, which is the correct default behavior
1331 */
1332 int N = 1 << crypt_ftr->N_factor;
1333 int r = 1 << crypt_ftr->r_factor;
1334 int p = 1 << crypt_ftr->p_factor;
1335
1336 rc = crypto_scrypt(ikey, KEY_LEN_BYTES,
1337 crypt_ftr->salt, sizeof(crypt_ftr->salt), N, r, p,
1338 crypt_ftr->scrypted_intermediate_key,
1339 sizeof(crypt_ftr->scrypted_intermediate_key));
1340
1341 if (rc) {
1342 SLOGE("encrypt_master_key: crypto_scrypt failed");
1343 }
1344
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001345 return 0;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001346}
1347
JP Abgrall7bdfa522013-11-15 13:42:56 -08001348static int decrypt_master_key_aux(char *passwd, unsigned char *salt,
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001349 unsigned char *encrypted_master_key,
1350 unsigned char *decrypted_master_key,
1351 kdf_func kdf, void *kdf_params,
1352 unsigned char** intermediate_key,
1353 size_t* intermediate_key_size)
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001354{
1355 unsigned char ikey[32+32] = { 0 }; /* Big enough to hold a 256 bit key and 256 bit IV */
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001356 EVP_CIPHER_CTX d_ctx;
1357 int decrypted_len, final_len;
1358
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001359 /* Turn the password into an intermediate key and IV that can decrypt the
1360 master key */
Paul Lawrencef4faa572014-01-29 13:31:03 -08001361 if (kdf(passwd, salt, ikey, kdf_params)) {
1362 SLOGE("kdf failed");
1363 return -1;
1364 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001365
1366 /* Initialize the decryption engine */
Adam Langley889c4f12014-09-03 14:23:13 -07001367 EVP_CIPHER_CTX_init(&d_ctx);
1368 if (! EVP_DecryptInit_ex(&d_ctx, EVP_aes_128_cbc(), NULL, ikey, ikey+KEY_LEN_BYTES)) {
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001369 return -1;
1370 }
1371 EVP_CIPHER_CTX_set_padding(&d_ctx, 0); /* Turn off padding as our data is block aligned */
1372 /* Decrypt the master key */
1373 if (! EVP_DecryptUpdate(&d_ctx, decrypted_master_key, &decrypted_len,
1374 encrypted_master_key, KEY_LEN_BYTES)) {
1375 return -1;
1376 }
Adam Langley889c4f12014-09-03 14:23:13 -07001377 if (! EVP_DecryptFinal_ex(&d_ctx, decrypted_master_key + decrypted_len, &final_len)) {
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001378 return -1;
1379 }
1380
1381 if (decrypted_len + final_len != KEY_LEN_BYTES) {
1382 return -1;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001383 }
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001384
1385 /* Copy intermediate key if needed by params */
1386 if (intermediate_key && intermediate_key_size) {
1387 *intermediate_key = (unsigned char*) malloc(KEY_LEN_BYTES);
1388 if (intermediate_key) {
1389 memcpy(*intermediate_key, ikey, KEY_LEN_BYTES);
1390 *intermediate_key_size = KEY_LEN_BYTES;
1391 }
1392 }
1393
1394 return 0;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001395}
1396
Kenny Rootc4c70f12013-06-14 12:11:38 -07001397static void get_kdf_func(struct crypt_mnt_ftr *ftr, kdf_func *kdf, void** kdf_params)
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001398{
Shawn Willdene17a9c42014-09-08 13:04:08 -06001399 if (ftr->kdf_type == KDF_SCRYPT_KEYMASTER_UNPADDED ||
1400 ftr->kdf_type == KDF_SCRYPT_KEYMASTER_BADLY_PADDED ||
1401 ftr->kdf_type == KDF_SCRYPT_KEYMASTER) {
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001402 *kdf = scrypt_keymaster;
1403 *kdf_params = ftr;
1404 } else if (ftr->kdf_type == KDF_SCRYPT) {
Kenny Rootc4c70f12013-06-14 12:11:38 -07001405 *kdf = scrypt;
1406 *kdf_params = ftr;
1407 } else {
1408 *kdf = pbkdf2;
1409 *kdf_params = NULL;
1410 }
1411}
1412
JP Abgrall7bdfa522013-11-15 13:42:56 -08001413static int decrypt_master_key(char *passwd, unsigned char *decrypted_master_key,
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001414 struct crypt_mnt_ftr *crypt_ftr,
1415 unsigned char** intermediate_key,
1416 size_t* intermediate_key_size)
Kenny Rootc4c70f12013-06-14 12:11:38 -07001417{
1418 kdf_func kdf;
1419 void *kdf_params;
1420 int ret;
1421
1422 get_kdf_func(crypt_ftr, &kdf, &kdf_params);
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001423 ret = decrypt_master_key_aux(passwd, crypt_ftr->salt, crypt_ftr->master_key,
1424 decrypted_master_key, kdf, kdf_params,
1425 intermediate_key, intermediate_key_size);
Kenny Rootc4c70f12013-06-14 12:11:38 -07001426 if (ret != 0) {
1427 SLOGW("failure decrypting master key");
Kenny Rootc4c70f12013-06-14 12:11:38 -07001428 }
1429
1430 return ret;
1431}
1432
1433static int create_encrypted_random_key(char *passwd, unsigned char *master_key, unsigned char *salt,
1434 struct crypt_mnt_ftr *crypt_ftr) {
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001435 int fd;
Ken Sumralle8744072011-01-18 22:01:55 -08001436 unsigned char key_buf[KEY_LEN_BYTES];
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001437
1438 /* Get some random bits for a key */
1439 fd = open("/dev/urandom", O_RDONLY);
Ken Sumralle8744072011-01-18 22:01:55 -08001440 read(fd, key_buf, sizeof(key_buf));
1441 read(fd, salt, SALT_LEN);
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001442 close(fd);
1443
1444 /* Now encrypt it with the password */
Kenny Rootc4c70f12013-06-14 12:11:38 -07001445 return encrypt_master_key(passwd, salt, key_buf, master_key, crypt_ftr);
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001446}
1447
Greg Hackmann6e8440f2014-10-02 17:18:20 -07001448static int wait_and_unmount(char *mountpoint, bool kill)
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001449{
Greg Hackmann955653e2014-09-24 14:55:20 -07001450 int i, err, rc;
Ken Sumrall2eaf7132011-01-14 12:45:48 -08001451#define WAIT_UNMOUNT_COUNT 20
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001452
1453 /* Now umount the tmpfs filesystem */
1454 for (i=0; i<WAIT_UNMOUNT_COUNT; i++) {
Greg Hackmann6e8440f2014-10-02 17:18:20 -07001455 if (umount(mountpoint) == 0) {
1456 break;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001457 }
Greg Hackmann6e8440f2014-10-02 17:18:20 -07001458
1459 if (errno == EINVAL) {
1460 /* EINVAL is returned if the directory is not a mountpoint,
1461 * i.e. there is no filesystem mounted there. So just get out.
1462 */
1463 break;
1464 }
1465
1466 err = errno;
1467
1468 /* If allowed, be increasingly aggressive before the last two retries */
1469 if (kill) {
1470 if (i == (WAIT_UNMOUNT_COUNT - 3)) {
1471 SLOGW("sending SIGHUP to processes with open files\n");
1472 vold_killProcessesWithOpenFiles(mountpoint, 1);
1473 } else if (i == (WAIT_UNMOUNT_COUNT - 2)) {
1474 SLOGW("sending SIGKILL to processes with open files\n");
1475 vold_killProcessesWithOpenFiles(mountpoint, 2);
1476 }
1477 }
1478
1479 sleep(1);
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001480 }
1481
1482 if (i < WAIT_UNMOUNT_COUNT) {
1483 SLOGD("unmounting %s succeeded\n", mountpoint);
1484 rc = 0;
1485 } else {
jessica_yu3f14fe42014-09-22 15:57:40 +08001486 vold_killProcessesWithOpenFiles(mountpoint, 0);
Greg Hackmann955653e2014-09-24 14:55:20 -07001487 SLOGE("unmounting %s failed: %s\n", mountpoint, strerror(err));
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001488 rc = -1;
1489 }
1490
1491 return rc;
1492}
1493
Ken Sumrallc5872692013-05-14 15:26:31 -07001494#define DATA_PREP_TIMEOUT 200
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001495static int prep_data_fs(void)
1496{
1497 int i;
1498
1499 /* Do the prep of the /data filesystem */
1500 property_set("vold.post_fs_data_done", "0");
1501 property_set("vold.decrypt", "trigger_post_fs_data");
1502 SLOGD("Just triggered post_fs_data\n");
1503
Ken Sumrallc5872692013-05-14 15:26:31 -07001504 /* Wait a max of 50 seconds, hopefully it takes much less */
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001505 for (i=0; i<DATA_PREP_TIMEOUT; i++) {
Ken Sumrall29d8da82011-05-18 17:20:07 -07001506 char p[PROPERTY_VALUE_MAX];
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001507
1508 property_get("vold.post_fs_data_done", p, "0");
1509 if (*p == '1') {
1510 break;
1511 } else {
1512 usleep(250000);
1513 }
1514 }
1515 if (i == DATA_PREP_TIMEOUT) {
1516 /* Ugh, we failed to prep /data in time. Bail. */
Ken Sumrallc5872692013-05-14 15:26:31 -07001517 SLOGE("post_fs_data timed out!\n");
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001518 return -1;
1519 } else {
1520 SLOGD("post_fs_data done\n");
1521 return 0;
1522 }
1523}
1524
Paul Lawrence74f29f12014-08-28 15:54:10 -07001525static void cryptfs_set_corrupt()
1526{
1527 // Mark the footer as bad
1528 struct crypt_mnt_ftr crypt_ftr;
1529 if (get_crypt_ftr_and_key(&crypt_ftr)) {
1530 SLOGE("Failed to get crypto footer - panic");
1531 return;
1532 }
1533
1534 crypt_ftr.flags |= CRYPT_DATA_CORRUPT;
1535 if (put_crypt_ftr_and_key(&crypt_ftr)) {
1536 SLOGE("Failed to set crypto footer - panic");
1537 return;
1538 }
1539}
1540
1541static void cryptfs_trigger_restart_min_framework()
1542{
1543 if (fs_mgr_do_tmpfs_mount(DATA_MNT_POINT)) {
1544 SLOGE("Failed to mount tmpfs on data - panic");
1545 return;
1546 }
1547
1548 if (property_set("vold.decrypt", "trigger_post_fs_data")) {
1549 SLOGE("Failed to trigger post fs data - panic");
1550 return;
1551 }
1552
1553 if (property_set("vold.decrypt", "trigger_restart_min_framework")) {
1554 SLOGE("Failed to trigger restart min framework - panic");
1555 return;
1556 }
1557}
1558
Paul Lawrence8e3f4512014-09-08 10:11:17 -07001559/* returns < 0 on failure */
Paul Lawrencef4faa572014-01-29 13:31:03 -08001560static int cryptfs_restart_internal(int restart_main)
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001561{
Ken Sumrall6864b7e2011-01-14 15:20:02 -08001562 char crypto_blkdev[MAXPATHLEN];
Tim Murray8439dc92014-12-15 11:56:11 -08001563 int rc = -1;
Ken Sumrall0cc16632011-01-18 20:32:26 -08001564 static int restart_successful = 0;
1565
1566 /* Validate that it's OK to call this routine */
Jason parks70a4b3f2011-01-28 10:10:47 -06001567 if (! master_key_saved) {
Ken Sumrall0cc16632011-01-18 20:32:26 -08001568 SLOGE("Encrypted filesystem not validated, aborting");
1569 return -1;
1570 }
1571
1572 if (restart_successful) {
1573 SLOGE("System already restarted with encrypted disk, aborting");
1574 return -1;
1575 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001576
Paul Lawrencef4faa572014-01-29 13:31:03 -08001577 if (restart_main) {
1578 /* Here is where we shut down the framework. The init scripts
1579 * start all services in one of three classes: core, main or late_start.
1580 * On boot, we start core and main. Now, we stop main, but not core,
1581 * as core includes vold and a few other really important things that
1582 * we need to keep running. Once main has stopped, we should be able
1583 * to umount the tmpfs /data, then mount the encrypted /data.
1584 * We then restart the class main, and also the class late_start.
1585 * At the moment, I've only put a few things in late_start that I know
1586 * are not needed to bring up the framework, and that also cause problems
1587 * with unmounting the tmpfs /data, but I hope to add add more services
1588 * to the late_start class as we optimize this to decrease the delay
1589 * till the user is asked for the password to the filesystem.
1590 */
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001591
Paul Lawrencef4faa572014-01-29 13:31:03 -08001592 /* The init files are setup to stop the class main when vold.decrypt is
1593 * set to trigger_reset_main.
1594 */
1595 property_set("vold.decrypt", "trigger_reset_main");
1596 SLOGD("Just asked init to shut down class main\n");
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001597
Paul Lawrencef4faa572014-01-29 13:31:03 -08001598 /* Ugh, shutting down the framework is not synchronous, so until it
1599 * can be fixed, this horrible hack will wait a moment for it all to
1600 * shut down before proceeding. Without it, some devices cannot
1601 * restart the graphics services.
1602 */
1603 sleep(2);
1604 }
Ken Sumrall9dedfd42012-10-09 14:16:59 -07001605
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001606 /* Now that the framework is shutdown, we should be able to umount()
1607 * the tmpfs filesystem, and mount the real one.
1608 */
1609
Ken Sumrall6864b7e2011-01-14 15:20:02 -08001610 property_get("ro.crypto.fs_crypto_blkdev", crypto_blkdev, "");
1611 if (strlen(crypto_blkdev) == 0) {
1612 SLOGE("fs_crypto_blkdev not set\n");
1613 return -1;
1614 }
1615
Greg Hackmann6e8440f2014-10-02 17:18:20 -07001616 if (! (rc = wait_and_unmount(DATA_MNT_POINT, true)) ) {
Doug Zongker6fd57712013-12-17 09:43:23 -08001617 /* If ro.crypto.readonly is set to 1, mount the decrypted
1618 * filesystem readonly. This is used when /data is mounted by
1619 * recovery mode.
1620 */
1621 char ro_prop[PROPERTY_VALUE_MAX];
1622 property_get("ro.crypto.readonly", ro_prop, "");
1623 if (strlen(ro_prop) > 0 && atoi(ro_prop)) {
1624 struct fstab_rec* rec = fs_mgr_get_entry_for_mount_point(fstab, DATA_MNT_POINT);
1625 rec->flags |= MS_RDONLY;
1626 }
JP Abgrall62c7af32014-06-16 13:01:23 -07001627
Ken Sumralle5032c42012-04-01 23:58:44 -07001628 /* If that succeeded, then mount the decrypted filesystem */
Paul Lawrence8e3f4512014-09-08 10:11:17 -07001629 int retries = RETRY_MOUNT_ATTEMPTS;
1630 int mount_rc;
1631 while ((mount_rc = fs_mgr_do_mount(fstab, DATA_MNT_POINT,
1632 crypto_blkdev, 0))
1633 != 0) {
1634 if (mount_rc == FS_MGR_DOMNT_BUSY) {
1635 /* TODO: invoke something similar to
1636 Process::killProcessWithOpenFiles(DATA_MNT_POINT,
1637 retries > RETRY_MOUNT_ATTEMPT/2 ? 1 : 2 ) */
1638 SLOGI("Failed to mount %s because it is busy - waiting",
1639 crypto_blkdev);
1640 if (--retries) {
1641 sleep(RETRY_MOUNT_DELAY_SECONDS);
1642 } else {
1643 /* Let's hope that a reboot clears away whatever is keeping
1644 the mount busy */
1645 cryptfs_reboot(reboot);
1646 }
1647 } else {
1648 SLOGE("Failed to mount decrypted data");
1649 cryptfs_set_corrupt();
1650 cryptfs_trigger_restart_min_framework();
1651 SLOGI("Started framework to offer wipe");
1652 return -1;
1653 }
Paul Lawrence74f29f12014-08-28 15:54:10 -07001654 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001655
Ken Sumralle5032c42012-04-01 23:58:44 -07001656 property_set("vold.decrypt", "trigger_load_persist_props");
1657 /* Create necessary paths on /data */
1658 if (prep_data_fs()) {
1659 return -1;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001660 }
Ken Sumralle5032c42012-04-01 23:58:44 -07001661
1662 /* startup service classes main and late_start */
1663 property_set("vold.decrypt", "trigger_restart_framework");
1664 SLOGD("Just triggered restart_framework\n");
1665
1666 /* Give it a few moments to get started */
1667 sleep(1);
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001668 }
1669
Ken Sumrall0cc16632011-01-18 20:32:26 -08001670 if (rc == 0) {
1671 restart_successful = 1;
1672 }
1673
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001674 return rc;
1675}
1676
Paul Lawrencef4faa572014-01-29 13:31:03 -08001677int cryptfs_restart(void)
1678{
Paul Lawrence8175a0b2015-03-05 09:46:23 -08001679 SLOGI("cryptfs_restart");
1680 if (e4crypt_crypto_complete(DATA_MNT_POINT) == 0) {
1681 struct fstab_rec* rec;
1682 int rc;
1683
1684 if (e4crypt_restart(DATA_MNT_POINT)) {
1685 SLOGE("Can't unmount e4crypt temp volume\n");
1686 return -1;
1687 }
1688
1689 rec = fs_mgr_get_entry_for_mount_point(fstab, DATA_MNT_POINT);
1690 if (!rec) {
1691 SLOGE("Can't get fstab record for %s\n", DATA_MNT_POINT);
1692 return -1;
1693 }
1694
1695 rc = fs_mgr_do_mount(fstab, DATA_MNT_POINT, rec->blk_device, 0);
1696 if (rc) {
1697 SLOGE("Can't mount %s\n", DATA_MNT_POINT);
1698 return rc;
1699 }
1700
1701 property_set("vold.decrypt", "trigger_restart_framework");
1702 return 0;
1703 }
1704
Paul Lawrencef4faa572014-01-29 13:31:03 -08001705 /* Call internal implementation forcing a restart of main service group */
1706 return cryptfs_restart_internal(1);
1707}
1708
Paul Lawrence8175a0b2015-03-05 09:46:23 -08001709static int do_crypto_complete(char *mount_point)
Ken Sumrall7f7dbaa2011-02-01 15:46:41 -08001710{
1711 struct crypt_mnt_ftr crypt_ftr;
Ken Sumrall29d8da82011-05-18 17:20:07 -07001712 char encrypted_state[PROPERTY_VALUE_MAX];
Ken Sumralle1a45852011-12-14 21:24:27 -08001713 char key_loc[PROPERTY_VALUE_MAX];
Ken Sumrall7f7dbaa2011-02-01 15:46:41 -08001714
1715 property_get("ro.crypto.state", encrypted_state, "");
1716 if (strcmp(encrypted_state, "encrypted") ) {
1717 SLOGE("not running with encryption, aborting");
Paul Lawrence74f29f12014-08-28 15:54:10 -07001718 return CRYPTO_COMPLETE_NOT_ENCRYPTED;
Ken Sumrall7f7dbaa2011-02-01 15:46:41 -08001719 }
1720
Paul Lawrence8175a0b2015-03-05 09:46:23 -08001721 if (e4crypt_crypto_complete(mount_point) == 0) {
1722 return CRYPTO_COMPLETE_ENCRYPTED;
1723 }
1724
Ken Sumrall160b4d62013-04-22 12:15:39 -07001725 if (get_crypt_ftr_and_key(&crypt_ftr)) {
Ken Sumrall56ad03c2013-02-13 13:00:19 -08001726 fs_mgr_get_crypt_info(fstab, key_loc, 0, sizeof(key_loc));
Ken Sumralle5032c42012-04-01 23:58:44 -07001727
Ken Sumralle1a45852011-12-14 21:24:27 -08001728 /*
1729 * Only report this error if key_loc is a file and it exists.
1730 * If the device was never encrypted, and /data is not mountable for
1731 * some reason, returning 1 should prevent the UI from presenting the
1732 * a "enter password" screen, or worse, a "press button to wipe the
1733 * device" screen.
1734 */
1735 if ((key_loc[0] == '/') && (access("key_loc", F_OK) == -1)) {
1736 SLOGE("master key file does not exist, aborting");
Paul Lawrence74f29f12014-08-28 15:54:10 -07001737 return CRYPTO_COMPLETE_NOT_ENCRYPTED;
Ken Sumralle1a45852011-12-14 21:24:27 -08001738 } else {
1739 SLOGE("Error getting crypt footer and key\n");
Paul Lawrence74f29f12014-08-28 15:54:10 -07001740 return CRYPTO_COMPLETE_BAD_METADATA;
Ken Sumralle1a45852011-12-14 21:24:27 -08001741 }
Ken Sumrall7f7dbaa2011-02-01 15:46:41 -08001742 }
1743
Paul Lawrence74f29f12014-08-28 15:54:10 -07001744 // Test for possible error flags
1745 if (crypt_ftr.flags & CRYPT_ENCRYPTION_IN_PROGRESS){
1746 SLOGE("Encryption process is partway completed\n");
1747 return CRYPTO_COMPLETE_PARTIAL;
1748 }
1749
1750 if (crypt_ftr.flags & CRYPT_INCONSISTENT_STATE){
1751 SLOGE("Encryption process was interrupted but cannot continue\n");
1752 return CRYPTO_COMPLETE_INCONSISTENT;
1753 }
1754
1755 if (crypt_ftr.flags & CRYPT_DATA_CORRUPT){
1756 SLOGE("Encryption is successful but data is corrupt\n");
1757 return CRYPTO_COMPLETE_CORRUPT;
Ken Sumrall7f7dbaa2011-02-01 15:46:41 -08001758 }
1759
1760 /* We passed the test! We shall diminish, and return to the west */
Paul Lawrence74f29f12014-08-28 15:54:10 -07001761 return CRYPTO_COMPLETE_ENCRYPTED;
Ken Sumrall7f7dbaa2011-02-01 15:46:41 -08001762}
1763
Paul Lawrencef4faa572014-01-29 13:31:03 -08001764static int test_mount_encrypted_fs(struct crypt_mnt_ftr* crypt_ftr,
1765 char *passwd, char *mount_point, char *label)
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001766{
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001767 /* Allocate enough space for a 256 bit key, but we may use less */
Ken Sumrall160b4d62013-04-22 12:15:39 -07001768 unsigned char decrypted_master_key[32];
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001769 char crypto_blkdev[MAXPATHLEN];
1770 char real_blkdev[MAXPATHLEN];
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001771 char tmp_mount_point[64];
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001772 unsigned int orig_failed_decrypt_count;
1773 int rc;
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001774 int use_keymaster = 0;
1775 int upgrade = 0;
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001776 unsigned char* intermediate_key = 0;
1777 size_t intermediate_key_size = 0;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001778
Paul Lawrencef4faa572014-01-29 13:31:03 -08001779 SLOGD("crypt_ftr->fs_size = %lld\n", crypt_ftr->fs_size);
1780 orig_failed_decrypt_count = crypt_ftr->failed_decrypt_count;
Ken Sumrall0cc16632011-01-18 20:32:26 -08001781
Paul Lawrencef4faa572014-01-29 13:31:03 -08001782 if (! (crypt_ftr->flags & CRYPT_MNT_KEY_UNENCRYPTED) ) {
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001783 if (decrypt_master_key(passwd, decrypted_master_key, crypt_ftr,
1784 &intermediate_key, &intermediate_key_size)) {
JP Abgrall7bdfa522013-11-15 13:42:56 -08001785 SLOGE("Failed to decrypt master key\n");
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001786 rc = -1;
1787 goto errout;
JP Abgrall7bdfa522013-11-15 13:42:56 -08001788 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001789 }
1790
Paul Lawrencef4faa572014-01-29 13:31:03 -08001791 fs_mgr_get_crypt_info(fstab, 0, real_blkdev, sizeof(real_blkdev));
1792
Ajay Dudani87701e22014-09-17 21:02:52 -07001793#ifdef CONFIG_HW_DISK_ENCRYPTION
Iliyan Malchevbb7d9af2014-11-20 18:42:23 -08001794 if (!strcmp((char *)crypt_ftr->crypto_type_name, "aes-xts")) {
1795 if(!set_hw_device_encryption_key(passwd, (char*) crypt_ftr->crypto_type_name)) {
1796 SLOGE("Hardware encryption key does not match");
1797 }
Ajay Dudani87701e22014-09-17 21:02:52 -07001798 }
1799#endif
1800
Paul Lawrence74f29f12014-08-28 15:54:10 -07001801 // Create crypto block device - all (non fatal) code paths
1802 // need it
Paul Lawrencef4faa572014-01-29 13:31:03 -08001803 if (create_crypto_blk_dev(crypt_ftr, decrypted_master_key,
1804 real_blkdev, crypto_blkdev, label)) {
Paul Lawrence74f29f12014-08-28 15:54:10 -07001805 SLOGE("Error creating decrypted block device\n");
1806 rc = -1;
1807 goto errout;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001808 }
1809
Paul Lawrence74f29f12014-08-28 15:54:10 -07001810 /* Work out if the problem is the password or the data */
1811 unsigned char scrypted_intermediate_key[sizeof(crypt_ftr->
1812 scrypted_intermediate_key)];
1813 int N = 1 << crypt_ftr->N_factor;
1814 int r = 1 << crypt_ftr->r_factor;
1815 int p = 1 << crypt_ftr->p_factor;
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001816
Paul Lawrence74f29f12014-08-28 15:54:10 -07001817 rc = crypto_scrypt(intermediate_key, intermediate_key_size,
1818 crypt_ftr->salt, sizeof(crypt_ftr->salt),
1819 N, r, p, scrypted_intermediate_key,
1820 sizeof(scrypted_intermediate_key));
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001821
Paul Lawrence74f29f12014-08-28 15:54:10 -07001822 // Does the key match the crypto footer?
1823 if (rc == 0 && memcmp(scrypted_intermediate_key,
1824 crypt_ftr->scrypted_intermediate_key,
1825 sizeof(scrypted_intermediate_key)) == 0) {
1826 SLOGI("Password matches");
1827 rc = 0;
1828 } else {
1829 /* Try mounting the file system anyway, just in case the problem's with
1830 * the footer, not the key. */
1831 sprintf(tmp_mount_point, "%s/tmp_mnt", mount_point);
1832 mkdir(tmp_mount_point, 0755);
1833 if (fs_mgr_do_mount(fstab, DATA_MNT_POINT, crypto_blkdev, tmp_mount_point)) {
1834 SLOGE("Error temp mounting decrypted block device\n");
1835 delete_crypto_blk_dev(label);
1836
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001837 rc = ++crypt_ftr->failed_decrypt_count;
1838 put_crypt_ftr_and_key(crypt_ftr);
Paul Lawrence74f29f12014-08-28 15:54:10 -07001839 } else {
1840 /* Success! */
1841 SLOGI("Password did not match but decrypted drive mounted - continue");
1842 umount(tmp_mount_point);
1843 rc = 0;
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001844 }
Paul Lawrence74f29f12014-08-28 15:54:10 -07001845 }
1846
1847 if (rc == 0) {
1848 crypt_ftr->failed_decrypt_count = 0;
Paul Lawrence72b8b822014-10-05 12:57:37 -07001849 if (orig_failed_decrypt_count != 0) {
1850 put_crypt_ftr_and_key(crypt_ftr);
1851 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001852
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001853 /* Save the name of the crypto block device
Paul Lawrence74f29f12014-08-28 15:54:10 -07001854 * so we can mount it when restarting the framework. */
Ken Sumrall6864b7e2011-01-14 15:20:02 -08001855 property_set("ro.crypto.fs_crypto_blkdev", crypto_blkdev);
Jason parks70a4b3f2011-01-28 10:10:47 -06001856
1857 /* Also save a the master key so we can reencrypted the key
Paul Lawrence74f29f12014-08-28 15:54:10 -07001858 * the key when we want to change the password on it. */
Jason parks70a4b3f2011-01-28 10:10:47 -06001859 memcpy(saved_master_key, decrypted_master_key, KEY_LEN_BYTES);
Ken Sumrall3ad90722011-10-04 20:38:29 -07001860 saved_mount_point = strdup(mount_point);
Jason parks70a4b3f2011-01-28 10:10:47 -06001861 master_key_saved = 1;
JP Abgrall7bdfa522013-11-15 13:42:56 -08001862 SLOGD("%s(): Master key saved\n", __FUNCTION__);
Ken Sumrall6864b7e2011-01-14 15:20:02 -08001863 rc = 0;
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001864
Paul Lawrence74f29f12014-08-28 15:54:10 -07001865 // Upgrade if we're not using the latest KDF.
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001866 use_keymaster = keymaster_check_compatibility();
1867 if (crypt_ftr->kdf_type == KDF_SCRYPT_KEYMASTER) {
Shawn Willden47ba10d2014-09-03 17:07:06 -06001868 // Don't allow downgrade
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001869 } else if (use_keymaster == 1 && crypt_ftr->kdf_type != KDF_SCRYPT_KEYMASTER) {
1870 crypt_ftr->kdf_type = KDF_SCRYPT_KEYMASTER;
1871 upgrade = 1;
1872 } else if (use_keymaster == 0 && crypt_ftr->kdf_type != KDF_SCRYPT) {
Paul Lawrencef4faa572014-01-29 13:31:03 -08001873 crypt_ftr->kdf_type = KDF_SCRYPT;
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001874 upgrade = 1;
1875 }
1876
1877 if (upgrade) {
Paul Lawrencef4faa572014-01-29 13:31:03 -08001878 rc = encrypt_master_key(passwd, crypt_ftr->salt, saved_master_key,
1879 crypt_ftr->master_key, crypt_ftr);
JP Abgrall7bdfa522013-11-15 13:42:56 -08001880 if (!rc) {
Paul Lawrencef4faa572014-01-29 13:31:03 -08001881 rc = put_crypt_ftr_and_key(crypt_ftr);
JP Abgrall7bdfa522013-11-15 13:42:56 -08001882 }
1883 SLOGD("Key Derivation Function upgrade: rc=%d\n", rc);
Paul Lawrenceb2f682b2014-09-08 11:28:19 -07001884
1885 // Do not fail even if upgrade failed - machine is bootable
1886 // Note that if this code is ever hit, there is a *serious* problem
1887 // since KDFs should never fail. You *must* fix the kdf before
1888 // proceeding!
1889 if (rc) {
1890 SLOGW("Upgrade failed with error %d,"
1891 " but continuing with previous state",
1892 rc);
1893 rc = 0;
1894 }
JP Abgrall7bdfa522013-11-15 13:42:56 -08001895 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001896 }
1897
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001898 errout:
1899 if (intermediate_key) {
1900 memset(intermediate_key, 0, intermediate_key_size);
1901 free(intermediate_key);
1902 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001903 return rc;
1904}
1905
Ken Sumrall0b8b5972011-08-31 16:14:23 -07001906/* Called by vold when it wants to undo the crypto mapping of a volume it
1907 * manages. This is usually in response to a factory reset, when we want
1908 * to undo the crypto mapping so the volume is formatted in the clear.
1909 */
1910int cryptfs_revert_volume(const char *label)
1911{
1912 return delete_crypto_blk_dev((char *)label);
1913}
1914
Ken Sumrall29d8da82011-05-18 17:20:07 -07001915/*
1916 * Called by vold when it's asked to mount an encrypted, nonremovable volume.
1917 * Setup a dm-crypt mapping, use the saved master key from
1918 * setting up the /data mapping, and return the new device path.
1919 */
1920int cryptfs_setup_volume(const char *label, int major, int minor,
1921 char *crypto_sys_path, unsigned int max_path,
1922 int *new_major, int *new_minor)
1923{
1924 char real_blkdev[MAXPATHLEN], crypto_blkdev[MAXPATHLEN];
1925 struct crypt_mnt_ftr sd_crypt_ftr;
Ken Sumrall29d8da82011-05-18 17:20:07 -07001926 struct stat statbuf;
Ken Sumrall29d8da82011-05-18 17:20:07 -07001927
1928 sprintf(real_blkdev, "/dev/block/vold/%d:%d", major, minor);
1929
Ken Sumrall160b4d62013-04-22 12:15:39 -07001930 get_crypt_ftr_and_key(&sd_crypt_ftr);
Ken Sumrall29d8da82011-05-18 17:20:07 -07001931
1932 /* Update the fs_size field to be the size of the volume */
Hiroaki Miyazawa14eab552015-02-04 13:29:15 +09001933 int fd = open(real_blkdev, O_RDONLY);
1934 if (fd == -1) {
1935 SLOGE("Cannot open volume %s\n", real_blkdev);
1936 return -1;
1937 }
1938
1939 unsigned long nr_sec = 0;
1940 get_blkdev_size(fd, &nr_sec);
Ken Sumrall29d8da82011-05-18 17:20:07 -07001941 close(fd);
Hiroaki Miyazawa14eab552015-02-04 13:29:15 +09001942
Ken Sumrall29d8da82011-05-18 17:20:07 -07001943 if (nr_sec == 0) {
1944 SLOGE("Cannot get size of volume %s\n", real_blkdev);
1945 return -1;
1946 }
1947
1948 sd_crypt_ftr.fs_size = nr_sec;
1949 create_crypto_blk_dev(&sd_crypt_ftr, saved_master_key, real_blkdev,
1950 crypto_blkdev, label);
1951
JP Abgrall3334c6a2014-10-10 15:52:11 -07001952 if (stat(crypto_blkdev, &statbuf) < 0) {
1953 SLOGE("Error get stat for crypto_blkdev %s. err=%d(%s)\n",
1954 crypto_blkdev, errno, strerror(errno));
1955 }
Ken Sumrall29d8da82011-05-18 17:20:07 -07001956 *new_major = MAJOR(statbuf.st_rdev);
1957 *new_minor = MINOR(statbuf.st_rdev);
1958
1959 /* Create path to sys entry for this block device */
1960 snprintf(crypto_sys_path, max_path, "/devices/virtual/block/%s", strrchr(crypto_blkdev, '/')+1);
1961
1962 return 0;
1963}
1964
Ken Sumrall7f7dbaa2011-02-01 15:46:41 -08001965int cryptfs_crypto_complete(void)
1966{
1967 return do_crypto_complete("/data");
1968}
1969
Paul Lawrencef4faa572014-01-29 13:31:03 -08001970int check_unmounted_and_get_ftr(struct crypt_mnt_ftr* crypt_ftr)
1971{
1972 char encrypted_state[PROPERTY_VALUE_MAX];
1973 property_get("ro.crypto.state", encrypted_state, "");
1974 if ( master_key_saved || strcmp(encrypted_state, "encrypted") ) {
1975 SLOGE("encrypted fs already validated or not running with encryption,"
1976 " aborting");
1977 return -1;
1978 }
1979
1980 if (get_crypt_ftr_and_key(crypt_ftr)) {
1981 SLOGE("Error getting crypt footer and key");
1982 return -1;
1983 }
1984
1985 return 0;
1986}
1987
Paul Lawrencefc615042014-10-04 15:32:29 -07001988/*
1989 * TODO - transition patterns to new format in calling code
1990 * and remove this vile hack, and the use of hex in
1991 * the password passing code.
1992 *
1993 * Patterns are passed in zero based (i.e. the top left dot
1994 * is represented by zero, the top middle one etc), but we want
1995 * to store them '1' based.
1996 * This is to allow us to migrate the calling code to use this
1997 * convention. It also solves a nasty problem whereby scrypt ignores
1998 * trailing zeros, so patterns ending at the top left could be
1999 * truncated, and similarly, you could add the top left to any
2000 * pattern and still match.
2001 * adjust_passwd is a hack function that returns the alternate representation
2002 * if the password appears to be a pattern (hex numbers all less than 09)
2003 * If it succeeds we need to try both, and in particular try the alternate
2004 * first. If the original matches, then we need to update the footer
2005 * with the alternate.
2006 * All code that accepts passwords must adjust them first. Since
2007 * cryptfs_check_passwd is always the first function called after a migration
2008 * (and indeed on any boot) we only need to do the double try in this
2009 * function.
2010 */
2011char* adjust_passwd(const char* passwd)
2012{
2013 size_t index, length;
2014
2015 if (!passwd) {
2016 return 0;
2017 }
2018
2019 // Check even length. Hex encoded passwords are always
2020 // an even length, since each character encodes to two characters.
2021 length = strlen(passwd);
2022 if (length % 2) {
2023 SLOGW("Password not correctly hex encoded.");
2024 return 0;
2025 }
2026
2027 // Check password is old-style pattern - a collection of hex
2028 // encoded bytes less than 9 (00 through 08)
2029 for (index = 0; index < length; index +=2) {
2030 if (passwd[index] != '0'
2031 || passwd[index + 1] < '0' || passwd[index + 1] > '8') {
2032 return 0;
2033 }
2034 }
2035
2036 // Allocate room for adjusted passwd and null terminate
2037 char* adjusted = malloc(length + 1);
2038 adjusted[length] = 0;
2039
2040 // Add 0x31 ('1') to each character
2041 for (index = 0; index < length; index += 2) {
2042 // output is 31 through 39 so set first byte to three, second to src + 1
2043 adjusted[index] = '3';
2044 adjusted[index + 1] = passwd[index + 1] + 1;
2045 }
2046
2047 return adjusted;
2048}
2049
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002050int cryptfs_check_passwd(char *passwd)
2051{
Paul Lawrence8175a0b2015-03-05 09:46:23 -08002052 SLOGI("cryptfs_check_passwd");
2053 if (e4crypt_crypto_complete(DATA_MNT_POINT) == 0) {
2054 return e4crypt_check_passwd(DATA_MNT_POINT, passwd);
2055 }
2056
Paul Lawrencef4faa572014-01-29 13:31:03 -08002057 struct crypt_mnt_ftr crypt_ftr;
2058 int rc;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002059
Paul Lawrencef4faa572014-01-29 13:31:03 -08002060 rc = check_unmounted_and_get_ftr(&crypt_ftr);
2061 if (rc)
2062 return rc;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002063
Paul Lawrencefc615042014-10-04 15:32:29 -07002064 char* adjusted_passwd = adjust_passwd(passwd);
2065 if (adjusted_passwd) {
2066 int failed_decrypt_count = crypt_ftr.failed_decrypt_count;
2067 rc = test_mount_encrypted_fs(&crypt_ftr, adjusted_passwd,
2068 DATA_MNT_POINT, "userdata");
2069
2070 // Maybe the original one still works?
2071 if (rc) {
2072 // Don't double count this failure
2073 crypt_ftr.failed_decrypt_count = failed_decrypt_count;
2074 rc = test_mount_encrypted_fs(&crypt_ftr, passwd,
2075 DATA_MNT_POINT, "userdata");
2076 if (!rc) {
2077 // cryptfs_changepw also adjusts so pass original
2078 // Note that adjust_passwd only recognises patterns
2079 // so we can safely use CRYPT_TYPE_PATTERN
2080 SLOGI("Updating pattern to new format");
2081 cryptfs_changepw(CRYPT_TYPE_PATTERN, passwd);
2082 }
2083 }
2084 free(adjusted_passwd);
2085 } else {
2086 rc = test_mount_encrypted_fs(&crypt_ftr, passwd,
2087 DATA_MNT_POINT, "userdata");
2088 }
Paul Lawrence684dbdf2014-02-07 12:07:22 -08002089
2090 if (rc == 0 && crypt_ftr.crypt_type != CRYPT_TYPE_DEFAULT) {
Paul Lawrence399317e2014-03-10 13:20:50 -07002091 cryptfs_clear_password();
2092 password = strdup(passwd);
2093 struct timespec now;
2094 clock_gettime(CLOCK_BOOTTIME, &now);
2095 password_expiry_time = now.tv_sec + password_max_age_seconds;
Paul Lawrence684dbdf2014-02-07 12:07:22 -08002096 }
2097
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002098 return rc;
2099}
2100
Ken Sumrall3ad90722011-10-04 20:38:29 -07002101int cryptfs_verify_passwd(char *passwd)
2102{
2103 struct crypt_mnt_ftr crypt_ftr;
2104 /* Allocate enough space for a 256 bit key, but we may use less */
Ken Sumrall160b4d62013-04-22 12:15:39 -07002105 unsigned char decrypted_master_key[32];
Ken Sumrall3ad90722011-10-04 20:38:29 -07002106 char encrypted_state[PROPERTY_VALUE_MAX];
2107 int rc;
2108
2109 property_get("ro.crypto.state", encrypted_state, "");
2110 if (strcmp(encrypted_state, "encrypted") ) {
2111 SLOGE("device not encrypted, aborting");
2112 return -2;
2113 }
2114
2115 if (!master_key_saved) {
2116 SLOGE("encrypted fs not yet mounted, aborting");
2117 return -1;
2118 }
2119
2120 if (!saved_mount_point) {
2121 SLOGE("encrypted fs failed to save mount point, aborting");
2122 return -1;
2123 }
2124
Ken Sumrall160b4d62013-04-22 12:15:39 -07002125 if (get_crypt_ftr_and_key(&crypt_ftr)) {
Ken Sumrall3ad90722011-10-04 20:38:29 -07002126 SLOGE("Error getting crypt footer and key\n");
2127 return -1;
2128 }
2129
2130 if (crypt_ftr.flags & CRYPT_MNT_KEY_UNENCRYPTED) {
2131 /* If the device has no password, then just say the password is valid */
2132 rc = 0;
2133 } else {
Paul Lawrencefc615042014-10-04 15:32:29 -07002134 char* adjusted_passwd = adjust_passwd(passwd);
2135 if (adjusted_passwd) {
2136 passwd = adjusted_passwd;
2137 }
2138
Paul Lawrenced0c7b172014-08-08 14:28:10 -07002139 decrypt_master_key(passwd, decrypted_master_key, &crypt_ftr, 0, 0);
Ken Sumrall3ad90722011-10-04 20:38:29 -07002140 if (!memcmp(decrypted_master_key, saved_master_key, crypt_ftr.keysize)) {
2141 /* They match, the password is correct */
2142 rc = 0;
2143 } else {
2144 /* If incorrect, sleep for a bit to prevent dictionary attacks */
2145 sleep(1);
2146 rc = 1;
2147 }
Paul Lawrencefc615042014-10-04 15:32:29 -07002148
2149 free(adjusted_passwd);
Ken Sumrall3ad90722011-10-04 20:38:29 -07002150 }
2151
2152 return rc;
2153}
2154
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002155/* Initialize a crypt_mnt_ftr structure. The keysize is
2156 * defaulted to 16 bytes, and the filesystem size to 0.
2157 * Presumably, at a minimum, the caller will update the
2158 * filesystem size and crypto_type_name after calling this function.
2159 */
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07002160static int cryptfs_init_crypt_mnt_ftr(struct crypt_mnt_ftr *ftr)
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002161{
Ken Sumrall160b4d62013-04-22 12:15:39 -07002162 off64_t off;
2163
2164 memset(ftr, 0, sizeof(struct crypt_mnt_ftr));
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002165 ftr->magic = CRYPT_MNT_MAGIC;
Kenny Rootc96a5f82013-06-14 12:08:28 -07002166 ftr->major_version = CURRENT_MAJOR_VERSION;
2167 ftr->minor_version = CURRENT_MINOR_VERSION;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002168 ftr->ftr_size = sizeof(struct crypt_mnt_ftr);
Jason parks70a4b3f2011-01-28 10:10:47 -06002169 ftr->keysize = KEY_LEN_BYTES;
Ken Sumrall160b4d62013-04-22 12:15:39 -07002170
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07002171 switch (keymaster_check_compatibility()) {
2172 case 1:
2173 ftr->kdf_type = KDF_SCRYPT_KEYMASTER;
2174 break;
2175
2176 case 0:
2177 ftr->kdf_type = KDF_SCRYPT;
2178 break;
2179
2180 default:
2181 SLOGE("keymaster_check_compatibility failed");
2182 return -1;
2183 }
2184
Kenny Rootc4c70f12013-06-14 12:11:38 -07002185 get_device_scrypt_params(ftr);
2186
Ken Sumrall160b4d62013-04-22 12:15:39 -07002187 ftr->persist_data_size = CRYPT_PERSIST_DATA_SIZE;
2188 if (get_crypt_ftr_info(NULL, &off) == 0) {
2189 ftr->persist_data_offset[0] = off + CRYPT_FOOTER_TO_PERSIST_OFFSET;
2190 ftr->persist_data_offset[1] = off + CRYPT_FOOTER_TO_PERSIST_OFFSET +
2191 ftr->persist_data_size;
2192 }
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07002193
2194 return 0;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002195}
2196
Ken Sumrall29d8da82011-05-18 17:20:07 -07002197static int cryptfs_enable_wipe(char *crypto_blkdev, off64_t size, int type)
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002198{
Ken Sumralle550f782013-08-20 13:48:23 -07002199 const char *args[10];
2200 char size_str[32]; /* Must be large enough to hold a %lld and null byte */
2201 int num_args;
2202 int status;
2203 int tmp;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002204 int rc = -1;
2205
Ken Sumrall29d8da82011-05-18 17:20:07 -07002206 if (type == EXT4_FS) {
Ken Sumralle550f782013-08-20 13:48:23 -07002207 args[0] = "/system/bin/make_ext4fs";
2208 args[1] = "-a";
2209 args[2] = "/data";
2210 args[3] = "-l";
Elliott Hughes73737162014-06-25 17:27:42 -07002211 snprintf(size_str, sizeof(size_str), "%" PRId64, size * 512);
Ken Sumralle550f782013-08-20 13:48:23 -07002212 args[4] = size_str;
2213 args[5] = crypto_blkdev;
2214 num_args = 6;
2215 SLOGI("Making empty filesystem with command %s %s %s %s %s %s\n",
2216 args[0], args[1], args[2], args[3], args[4], args[5]);
JP Abgrall62c7af32014-06-16 13:01:23 -07002217 } else if (type == F2FS_FS) {
2218 args[0] = "/system/bin/mkfs.f2fs";
2219 args[1] = "-t";
2220 args[2] = "-d1";
2221 args[3] = crypto_blkdev;
Elliott Hughes73737162014-06-25 17:27:42 -07002222 snprintf(size_str, sizeof(size_str), "%" PRId64, size);
JP Abgrall62c7af32014-06-16 13:01:23 -07002223 args[4] = size_str;
2224 num_args = 5;
2225 SLOGI("Making empty filesystem with command %s %s %s %s %s\n",
2226 args[0], args[1], args[2], args[3], args[4]);
Ken Sumrall29d8da82011-05-18 17:20:07 -07002227 } else {
2228 SLOGE("cryptfs_enable_wipe(): unknown filesystem type %d\n", type);
2229 return -1;
2230 }
2231
Ken Sumralle550f782013-08-20 13:48:23 -07002232 tmp = android_fork_execvp(num_args, (char **)args, &status, false, true);
2233
2234 if (tmp != 0) {
2235 SLOGE("Error creating empty filesystem on %s due to logwrap error\n", crypto_blkdev);
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002236 } else {
Ken Sumralle550f782013-08-20 13:48:23 -07002237 if (WIFEXITED(status)) {
2238 if (WEXITSTATUS(status)) {
2239 SLOGE("Error creating filesystem on %s, exit status %d ",
2240 crypto_blkdev, WEXITSTATUS(status));
2241 } else {
2242 SLOGD("Successfully created filesystem on %s\n", crypto_blkdev);
2243 rc = 0;
2244 }
2245 } else {
2246 SLOGE("Error creating filesystem on %s, did not exit normally\n", crypto_blkdev);
2247 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002248 }
2249
2250 return rc;
2251}
2252
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002253#define CRYPT_INPLACE_BUFSIZE 4096
Paul Lawrence87999172014-02-20 12:21:31 -08002254#define CRYPT_SECTORS_PER_BUFSIZE (CRYPT_INPLACE_BUFSIZE / CRYPT_SECTOR_SIZE)
2255#define CRYPT_SECTOR_SIZE 512
Paul Lawrenceae59fe62014-01-21 08:23:27 -08002256
2257/* aligned 32K writes tends to make flash happy.
2258 * SD card association recommends it.
2259 */
Ajay Dudani87701e22014-09-17 21:02:52 -07002260#ifndef CONFIG_HW_DISK_ENCRYPTION
Paul Lawrenceae59fe62014-01-21 08:23:27 -08002261#define BLOCKS_AT_A_TIME 8
Ajay Dudani87701e22014-09-17 21:02:52 -07002262#else
2263#define BLOCKS_AT_A_TIME 1024
2264#endif
Paul Lawrenceae59fe62014-01-21 08:23:27 -08002265
2266struct encryptGroupsData
2267{
2268 int realfd;
2269 int cryptofd;
2270 off64_t numblocks;
2271 off64_t one_pct, cur_pct, new_pct;
2272 off64_t blocks_already_done, tot_numblocks;
Paul Lawrence58c58cf2014-06-04 13:12:21 -07002273 off64_t used_blocks_already_done, tot_used_blocks;
Paul Lawrenceae59fe62014-01-21 08:23:27 -08002274 char* real_blkdev, * crypto_blkdev;
2275 int count;
2276 off64_t offset;
2277 char* buffer;
Paul Lawrence87999172014-02-20 12:21:31 -08002278 off64_t last_written_sector;
2279 int completed;
Paul Lawrencea96d9c92014-06-04 14:05:01 -07002280 time_t time_started;
2281 int remaining_time;
Paul Lawrenceae59fe62014-01-21 08:23:27 -08002282};
2283
Paul Lawrence58c58cf2014-06-04 13:12:21 -07002284static void update_progress(struct encryptGroupsData* data, int is_used)
Paul Lawrenceae59fe62014-01-21 08:23:27 -08002285{
2286 data->blocks_already_done++;
Paul Lawrence58c58cf2014-06-04 13:12:21 -07002287
2288 if (is_used) {
2289 data->used_blocks_already_done++;
2290 }
Paul Lawrence58c58cf2014-06-04 13:12:21 -07002291 if (data->tot_used_blocks) {
2292 data->new_pct = data->used_blocks_already_done / data->one_pct;
2293 } else {
2294 data->new_pct = data->blocks_already_done / data->one_pct;
2295 }
2296
Paul Lawrenceae59fe62014-01-21 08:23:27 -08002297 if (data->new_pct > data->cur_pct) {
2298 char buf[8];
2299 data->cur_pct = data->new_pct;
Elliott Hughescb33f572014-06-25 18:25:11 -07002300 snprintf(buf, sizeof(buf), "%" PRId64, data->cur_pct);
Paul Lawrenceae59fe62014-01-21 08:23:27 -08002301 property_set("vold.encrypt_progress", buf);
2302 }
Paul Lawrencea96d9c92014-06-04 14:05:01 -07002303
2304 if (data->cur_pct >= 5) {
Paul Lawrence9c58a872014-09-30 09:12:51 -07002305 struct timespec time_now;
2306 if (clock_gettime(CLOCK_MONOTONIC, &time_now)) {
2307 SLOGW("Error getting time");
2308 } else {
2309 double elapsed_time = difftime(time_now.tv_sec, data->time_started);
2310 off64_t remaining_blocks = data->tot_used_blocks
2311 - data->used_blocks_already_done;
2312 int remaining_time = (int)(elapsed_time * remaining_blocks
2313 / data->used_blocks_already_done);
Paul Lawrence71577502014-08-13 14:55:55 -07002314
Paul Lawrence9c58a872014-09-30 09:12:51 -07002315 // Change time only if not yet set, lower, or a lot higher for
2316 // best user experience
2317 if (data->remaining_time == -1
2318 || remaining_time < data->remaining_time
2319 || remaining_time > data->remaining_time + 60) {
2320 char buf[8];
2321 snprintf(buf, sizeof(buf), "%d", remaining_time);
2322 property_set("vold.encrypt_time_remaining", buf);
2323 data->remaining_time = remaining_time;
2324 }
Paul Lawrencea96d9c92014-06-04 14:05:01 -07002325 }
2326 }
Paul Lawrenceae59fe62014-01-21 08:23:27 -08002327}
2328
Paul Lawrence3846be12014-09-22 11:33:54 -07002329static void log_progress(struct encryptGroupsData const* data, bool completed)
2330{
2331 // Precondition - if completed data = 0 else data != 0
2332
2333 // Track progress so we can skip logging blocks
2334 static off64_t offset = -1;
2335
2336 // Need to close existing 'Encrypting from' log?
2337 if (completed || (offset != -1 && data->offset != offset)) {
2338 SLOGI("Encrypted to sector %" PRId64,
2339 offset / info.block_size * CRYPT_SECTOR_SIZE);
2340 offset = -1;
2341 }
2342
2343 // Need to start new 'Encrypting from' log?
2344 if (!completed && offset != data->offset) {
2345 SLOGI("Encrypting from sector %" PRId64,
2346 data->offset / info.block_size * CRYPT_SECTOR_SIZE);
2347 }
2348
2349 // Update offset
2350 if (!completed) {
2351 offset = data->offset + (off64_t)data->count * info.block_size;
2352 }
2353}
2354
Paul Lawrenceae59fe62014-01-21 08:23:27 -08002355static int flush_outstanding_data(struct encryptGroupsData* data)
2356{
2357 if (data->count == 0) {
2358 return 0;
2359 }
2360
Elliott Hughes231bdba2014-06-25 18:36:19 -07002361 SLOGV("Copying %d blocks at offset %" PRIx64, data->count, data->offset);
Paul Lawrenceae59fe62014-01-21 08:23:27 -08002362
2363 if (pread64(data->realfd, data->buffer,
2364 info.block_size * data->count, data->offset)
2365 <= 0) {
2366 SLOGE("Error reading real_blkdev %s for inplace encrypt",
2367 data->real_blkdev);
2368 return -1;
2369 }
2370
2371 if (pwrite64(data->cryptofd, data->buffer,
2372 info.block_size * data->count, data->offset)
2373 <= 0) {
2374 SLOGE("Error writing crypto_blkdev %s for inplace encrypt",
2375 data->crypto_blkdev);
2376 return -1;
Paul Lawrence87999172014-02-20 12:21:31 -08002377 } else {
Paul Lawrence3846be12014-09-22 11:33:54 -07002378 log_progress(data, false);
Paul Lawrenceae59fe62014-01-21 08:23:27 -08002379 }
2380
2381 data->count = 0;
Paul Lawrence87999172014-02-20 12:21:31 -08002382 data->last_written_sector = (data->offset + data->count)
2383 / info.block_size * CRYPT_SECTOR_SIZE - 1;
Paul Lawrenceae59fe62014-01-21 08:23:27 -08002384 return 0;
2385}
2386
2387static int encrypt_groups(struct encryptGroupsData* data)
2388{
2389 unsigned int i;
2390 u8 *block_bitmap = 0;
2391 unsigned int block;
2392 off64_t ret;
2393 int rc = -1;
2394
2395 data->buffer = malloc(info.block_size * BLOCKS_AT_A_TIME);
2396 if (!data->buffer) {
2397 SLOGE("Failed to allocate crypto buffer");
2398 goto errout;
2399 }
2400
2401 block_bitmap = malloc(info.block_size);
2402 if (!block_bitmap) {
2403 SLOGE("failed to allocate block bitmap");
2404 goto errout;
2405 }
2406
2407 for (i = 0; i < aux_info.groups; ++i) {
2408 SLOGI("Encrypting group %d", i);
2409
2410 u32 first_block = aux_info.first_data_block + i * info.blocks_per_group;
2411 u32 block_count = min(info.blocks_per_group,
2412 aux_info.len_blocks - first_block);
2413
2414 off64_t offset = (u64)info.block_size
2415 * aux_info.bg_desc[i].bg_block_bitmap;
2416
2417 ret = pread64(data->realfd, block_bitmap, info.block_size, offset);
2418 if (ret != (int)info.block_size) {
2419 SLOGE("failed to read all of block group bitmap %d", i);
2420 goto errout;
2421 }
2422
2423 offset = (u64)info.block_size * first_block;
2424
2425 data->count = 0;
2426
2427 for (block = 0; block < block_count; block++) {
Paul Lawrence58c58cf2014-06-04 13:12:21 -07002428 int used = bitmap_get_bit(block_bitmap, block);
2429 update_progress(data, used);
2430 if (used) {
Paul Lawrenceae59fe62014-01-21 08:23:27 -08002431 if (data->count == 0) {
2432 data->offset = offset;
2433 }
2434 data->count++;
2435 } else {
2436 if (flush_outstanding_data(data)) {
2437 goto errout;
2438 }
2439 }
2440
2441 offset += info.block_size;
2442
2443 /* Write data if we are aligned or buffer size reached */
2444 if (offset % (info.block_size * BLOCKS_AT_A_TIME) == 0
2445 || data->count == BLOCKS_AT_A_TIME) {
2446 if (flush_outstanding_data(data)) {
2447 goto errout;
2448 }
2449 }
Paul Lawrence87999172014-02-20 12:21:31 -08002450
Paul Lawrence73d7a022014-06-09 14:10:09 -07002451 if (!is_battery_ok_to_continue()) {
Paul Lawrence87999172014-02-20 12:21:31 -08002452 SLOGE("Stopping encryption due to low battery");
2453 rc = 0;
2454 goto errout;
2455 }
2456
Paul Lawrenceae59fe62014-01-21 08:23:27 -08002457 }
2458 if (flush_outstanding_data(data)) {
2459 goto errout;
2460 }
2461 }
2462
Paul Lawrence87999172014-02-20 12:21:31 -08002463 data->completed = 1;
Paul Lawrenceae59fe62014-01-21 08:23:27 -08002464 rc = 0;
2465
2466errout:
Paul Lawrence3846be12014-09-22 11:33:54 -07002467 log_progress(0, true);
Paul Lawrenceae59fe62014-01-21 08:23:27 -08002468 free(data->buffer);
2469 free(block_bitmap);
2470 return rc;
2471}
2472
2473static int cryptfs_enable_inplace_ext4(char *crypto_blkdev,
2474 char *real_blkdev,
2475 off64_t size,
2476 off64_t *size_already_done,
Paul Lawrence87999172014-02-20 12:21:31 -08002477 off64_t tot_size,
2478 off64_t previously_encrypted_upto)
Paul Lawrenceae59fe62014-01-21 08:23:27 -08002479{
Paul Lawrence58c58cf2014-06-04 13:12:21 -07002480 u32 i;
Paul Lawrenceae59fe62014-01-21 08:23:27 -08002481 struct encryptGroupsData data;
Paul Lawrence74f29f12014-08-28 15:54:10 -07002482 int rc; // Can't initialize without causing warning -Wclobbered
Paul Lawrenceae59fe62014-01-21 08:23:27 -08002483
Paul Lawrence87999172014-02-20 12:21:31 -08002484 if (previously_encrypted_upto > *size_already_done) {
2485 SLOGD("Not fast encrypting since resuming part way through");
2486 return -1;
2487 }
2488
Paul Lawrenceae59fe62014-01-21 08:23:27 -08002489 memset(&data, 0, sizeof(data));
2490 data.real_blkdev = real_blkdev;
2491 data.crypto_blkdev = crypto_blkdev;
2492
2493 if ( (data.realfd = open(real_blkdev, O_RDWR)) < 0) {
JP Abgrall3334c6a2014-10-10 15:52:11 -07002494 SLOGE("Error opening real_blkdev %s for inplace encrypt. err=%d(%s)\n",
2495 real_blkdev, errno, strerror(errno));
Paul Lawrence74f29f12014-08-28 15:54:10 -07002496 rc = -1;
Paul Lawrenceae59fe62014-01-21 08:23:27 -08002497 goto errout;
2498 }
2499
2500 if ( (data.cryptofd = open(crypto_blkdev, O_WRONLY)) < 0) {
JP Abgrall7fc1de82014-10-10 18:43:41 -07002501 SLOGE("Error opening crypto_blkdev %s for ext4 inplace encrypt. err=%d(%s)\n",
JP Abgrall3334c6a2014-10-10 15:52:11 -07002502 crypto_blkdev, errno, strerror(errno));
JP Abgrall7fc1de82014-10-10 18:43:41 -07002503 rc = ENABLE_INPLACE_ERR_DEV;
Paul Lawrenceae59fe62014-01-21 08:23:27 -08002504 goto errout;
2505 }
2506
2507 if (setjmp(setjmp_env)) {
JP Abgrall7fc1de82014-10-10 18:43:41 -07002508 SLOGE("Reading ext4 extent caused an exception\n");
Paul Lawrence74f29f12014-08-28 15:54:10 -07002509 rc = -1;
Paul Lawrenceae59fe62014-01-21 08:23:27 -08002510 goto errout;
2511 }
2512
2513 if (read_ext(data.realfd, 0) != 0) {
JP Abgrall7fc1de82014-10-10 18:43:41 -07002514 SLOGE("Failed to read ext4 extent\n");
Paul Lawrence74f29f12014-08-28 15:54:10 -07002515 rc = -1;
Paul Lawrenceae59fe62014-01-21 08:23:27 -08002516 goto errout;
2517 }
2518
2519 data.numblocks = size / CRYPT_SECTORS_PER_BUFSIZE;
2520 data.tot_numblocks = tot_size / CRYPT_SECTORS_PER_BUFSIZE;
2521 data.blocks_already_done = *size_already_done / CRYPT_SECTORS_PER_BUFSIZE;
2522
JP Abgrall7fc1de82014-10-10 18:43:41 -07002523 SLOGI("Encrypting ext4 filesystem in place...");
Paul Lawrenceae59fe62014-01-21 08:23:27 -08002524
Paul Lawrence58c58cf2014-06-04 13:12:21 -07002525 data.tot_used_blocks = data.numblocks;
2526 for (i = 0; i < aux_info.groups; ++i) {
2527 data.tot_used_blocks -= aux_info.bg_desc[i].bg_free_blocks_count;
2528 }
2529
2530 data.one_pct = data.tot_used_blocks / 100;
Paul Lawrenceae59fe62014-01-21 08:23:27 -08002531 data.cur_pct = 0;
Paul Lawrence9c58a872014-09-30 09:12:51 -07002532
2533 struct timespec time_started = {0};
2534 if (clock_gettime(CLOCK_MONOTONIC, &time_started)) {
2535 SLOGW("Error getting time at start");
2536 // Note - continue anyway - we'll run with 0
2537 }
2538 data.time_started = time_started.tv_sec;
Paul Lawrencea96d9c92014-06-04 14:05:01 -07002539 data.remaining_time = -1;
Paul Lawrenceae59fe62014-01-21 08:23:27 -08002540
2541 rc = encrypt_groups(&data);
2542 if (rc) {
2543 SLOGE("Error encrypting groups");
2544 goto errout;
2545 }
2546
Paul Lawrence87999172014-02-20 12:21:31 -08002547 *size_already_done += data.completed ? size : data.last_written_sector;
Paul Lawrenceae59fe62014-01-21 08:23:27 -08002548 rc = 0;
2549
2550errout:
2551 close(data.realfd);
2552 close(data.cryptofd);
2553
2554 return rc;
2555}
2556
Paul Lawrence3846be12014-09-22 11:33:54 -07002557static void log_progress_f2fs(u64 block, bool completed)
2558{
2559 // Precondition - if completed data = 0 else data != 0
2560
2561 // Track progress so we can skip logging blocks
2562 static u64 last_block = (u64)-1;
2563
2564 // Need to close existing 'Encrypting from' log?
2565 if (completed || (last_block != (u64)-1 && block != last_block + 1)) {
2566 SLOGI("Encrypted to block %" PRId64, last_block);
2567 last_block = -1;
2568 }
2569
2570 // Need to start new 'Encrypting from' log?
2571 if (!completed && (last_block == (u64)-1 || block != last_block + 1)) {
2572 SLOGI("Encrypting from block %" PRId64, block);
2573 }
2574
2575 // Update offset
2576 if (!completed) {
2577 last_block = block;
2578 }
2579}
2580
Daniel Rosenberge82df162014-08-15 22:19:23 +00002581static int encrypt_one_block_f2fs(u64 pos, void *data)
2582{
2583 struct encryptGroupsData *priv_dat = (struct encryptGroupsData *)data;
2584
2585 priv_dat->blocks_already_done = pos - 1;
2586 update_progress(priv_dat, 1);
2587
2588 off64_t offset = pos * CRYPT_INPLACE_BUFSIZE;
2589
2590 if (pread64(priv_dat->realfd, priv_dat->buffer, CRYPT_INPLACE_BUFSIZE, offset) <= 0) {
JP Abgrall7fc1de82014-10-10 18:43:41 -07002591 SLOGE("Error reading real_blkdev %s for f2fs inplace encrypt", priv_dat->crypto_blkdev);
Daniel Rosenberge82df162014-08-15 22:19:23 +00002592 return -1;
2593 }
2594
2595 if (pwrite64(priv_dat->cryptofd, priv_dat->buffer, CRYPT_INPLACE_BUFSIZE, offset) <= 0) {
JP Abgrall7fc1de82014-10-10 18:43:41 -07002596 SLOGE("Error writing crypto_blkdev %s for f2fs inplace encrypt", priv_dat->crypto_blkdev);
Daniel Rosenberge82df162014-08-15 22:19:23 +00002597 return -1;
2598 } else {
Paul Lawrence3846be12014-09-22 11:33:54 -07002599 log_progress_f2fs(pos, false);
Daniel Rosenberge82df162014-08-15 22:19:23 +00002600 }
2601
2602 return 0;
2603}
2604
2605static int cryptfs_enable_inplace_f2fs(char *crypto_blkdev,
2606 char *real_blkdev,
2607 off64_t size,
2608 off64_t *size_already_done,
2609 off64_t tot_size,
2610 off64_t previously_encrypted_upto)
2611{
Daniel Rosenberge82df162014-08-15 22:19:23 +00002612 struct encryptGroupsData data;
2613 struct f2fs_info *f2fs_info = NULL;
JP Abgrall7fc1de82014-10-10 18:43:41 -07002614 int rc = ENABLE_INPLACE_ERR_OTHER;
Daniel Rosenberge82df162014-08-15 22:19:23 +00002615 if (previously_encrypted_upto > *size_already_done) {
2616 SLOGD("Not fast encrypting since resuming part way through");
JP Abgrall7fc1de82014-10-10 18:43:41 -07002617 return ENABLE_INPLACE_ERR_OTHER;
Daniel Rosenberge82df162014-08-15 22:19:23 +00002618 }
2619 memset(&data, 0, sizeof(data));
2620 data.real_blkdev = real_blkdev;
2621 data.crypto_blkdev = crypto_blkdev;
2622 data.realfd = -1;
2623 data.cryptofd = -1;
2624 if ( (data.realfd = open64(real_blkdev, O_RDWR)) < 0) {
JP Abgrall7fc1de82014-10-10 18:43:41 -07002625 SLOGE("Error opening real_blkdev %s for f2fs inplace encrypt\n",
Daniel Rosenberge82df162014-08-15 22:19:23 +00002626 real_blkdev);
2627 goto errout;
2628 }
2629 if ( (data.cryptofd = open64(crypto_blkdev, O_WRONLY)) < 0) {
JP Abgrall7fc1de82014-10-10 18:43:41 -07002630 SLOGE("Error opening crypto_blkdev %s for f2fs inplace encrypt. err=%d(%s)\n",
JP Abgrall3334c6a2014-10-10 15:52:11 -07002631 crypto_blkdev, errno, strerror(errno));
JP Abgrall7fc1de82014-10-10 18:43:41 -07002632 rc = ENABLE_INPLACE_ERR_DEV;
Daniel Rosenberge82df162014-08-15 22:19:23 +00002633 goto errout;
2634 }
2635
2636 f2fs_info = generate_f2fs_info(data.realfd);
2637 if (!f2fs_info)
2638 goto errout;
2639
2640 data.numblocks = size / CRYPT_SECTORS_PER_BUFSIZE;
2641 data.tot_numblocks = tot_size / CRYPT_SECTORS_PER_BUFSIZE;
2642 data.blocks_already_done = *size_already_done / CRYPT_SECTORS_PER_BUFSIZE;
2643
2644 data.tot_used_blocks = get_num_blocks_used(f2fs_info);
2645
2646 data.one_pct = data.tot_used_blocks / 100;
2647 data.cur_pct = 0;
2648 data.time_started = time(NULL);
2649 data.remaining_time = -1;
2650
2651 data.buffer = malloc(f2fs_info->block_size);
2652 if (!data.buffer) {
2653 SLOGE("Failed to allocate crypto buffer");
2654 goto errout;
2655 }
2656
2657 data.count = 0;
2658
2659 /* Currently, this either runs to completion, or hits a nonrecoverable error */
2660 rc = run_on_used_blocks(data.blocks_already_done, f2fs_info, &encrypt_one_block_f2fs, &data);
2661
2662 if (rc) {
JP Abgrall7fc1de82014-10-10 18:43:41 -07002663 SLOGE("Error in running over f2fs blocks");
2664 rc = ENABLE_INPLACE_ERR_OTHER;
Daniel Rosenberge82df162014-08-15 22:19:23 +00002665 goto errout;
2666 }
2667
2668 *size_already_done += size;
2669 rc = 0;
2670
2671errout:
2672 if (rc)
2673 SLOGE("Failed to encrypt f2fs filesystem on %s", real_blkdev);
2674
Paul Lawrence3846be12014-09-22 11:33:54 -07002675 log_progress_f2fs(0, true);
Daniel Rosenberge82df162014-08-15 22:19:23 +00002676 free(f2fs_info);
2677 free(data.buffer);
2678 close(data.realfd);
2679 close(data.cryptofd);
2680
2681 return rc;
2682}
2683
Paul Lawrenceae59fe62014-01-21 08:23:27 -08002684static int cryptfs_enable_inplace_full(char *crypto_blkdev, char *real_blkdev,
2685 off64_t size, off64_t *size_already_done,
Paul Lawrence87999172014-02-20 12:21:31 -08002686 off64_t tot_size,
2687 off64_t previously_encrypted_upto)
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002688{
2689 int realfd, cryptofd;
2690 char *buf[CRYPT_INPLACE_BUFSIZE];
JP Abgrall7fc1de82014-10-10 18:43:41 -07002691 int rc = ENABLE_INPLACE_ERR_OTHER;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002692 off64_t numblocks, i, remainder;
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002693 off64_t one_pct, cur_pct, new_pct;
Ken Sumrall29d8da82011-05-18 17:20:07 -07002694 off64_t blocks_already_done, tot_numblocks;
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002695
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002696 if ( (realfd = open(real_blkdev, O_RDONLY)) < 0) {
2697 SLOGE("Error opening real_blkdev %s for inplace encrypt\n", real_blkdev);
JP Abgrall7fc1de82014-10-10 18:43:41 -07002698 return ENABLE_INPLACE_ERR_OTHER;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002699 }
2700
2701 if ( (cryptofd = open(crypto_blkdev, O_WRONLY)) < 0) {
JP Abgrall3334c6a2014-10-10 15:52:11 -07002702 SLOGE("Error opening crypto_blkdev %s for inplace encrypt. err=%d(%s)\n",
2703 crypto_blkdev, errno, strerror(errno));
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002704 close(realfd);
JP Abgrall7fc1de82014-10-10 18:43:41 -07002705 return ENABLE_INPLACE_ERR_DEV;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002706 }
2707
2708 /* This is pretty much a simple loop of reading 4K, and writing 4K.
2709 * The size passed in is the number of 512 byte sectors in the filesystem.
2710 * So compute the number of whole 4K blocks we should read/write,
2711 * and the remainder.
2712 */
2713 numblocks = size / CRYPT_SECTORS_PER_BUFSIZE;
2714 remainder = size % CRYPT_SECTORS_PER_BUFSIZE;
Ken Sumrall29d8da82011-05-18 17:20:07 -07002715 tot_numblocks = tot_size / CRYPT_SECTORS_PER_BUFSIZE;
2716 blocks_already_done = *size_already_done / CRYPT_SECTORS_PER_BUFSIZE;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002717
2718 SLOGE("Encrypting filesystem in place...");
2719
Paul Lawrence87999172014-02-20 12:21:31 -08002720 i = previously_encrypted_upto + 1 - *size_already_done;
2721
2722 if (lseek64(realfd, i * CRYPT_SECTOR_SIZE, SEEK_SET) < 0) {
2723 SLOGE("Cannot seek to previously encrypted point on %s", real_blkdev);
2724 goto errout;
2725 }
2726
2727 if (lseek64(cryptofd, i * CRYPT_SECTOR_SIZE, SEEK_SET) < 0) {
2728 SLOGE("Cannot seek to previously encrypted point on %s", crypto_blkdev);
2729 goto errout;
2730 }
2731
2732 for (;i < size && i % CRYPT_SECTORS_PER_BUFSIZE != 0; ++i) {
2733 if (unix_read(realfd, buf, CRYPT_SECTOR_SIZE) <= 0) {
2734 SLOGE("Error reading initial sectors from real_blkdev %s for "
2735 "inplace encrypt\n", crypto_blkdev);
2736 goto errout;
2737 }
2738 if (unix_write(cryptofd, buf, CRYPT_SECTOR_SIZE) <= 0) {
2739 SLOGE("Error writing initial sectors to crypto_blkdev %s for "
2740 "inplace encrypt\n", crypto_blkdev);
2741 goto errout;
2742 } else {
Elliott Hughescb33f572014-06-25 18:25:11 -07002743 SLOGI("Encrypted 1 block at %" PRId64, i);
Paul Lawrence87999172014-02-20 12:21:31 -08002744 }
2745 }
2746
Ken Sumrall29d8da82011-05-18 17:20:07 -07002747 one_pct = tot_numblocks / 100;
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002748 cur_pct = 0;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002749 /* process the majority of the filesystem in blocks */
Paul Lawrence87999172014-02-20 12:21:31 -08002750 for (i/=CRYPT_SECTORS_PER_BUFSIZE; i<numblocks; i++) {
Ken Sumrall29d8da82011-05-18 17:20:07 -07002751 new_pct = (i + blocks_already_done) / one_pct;
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002752 if (new_pct > cur_pct) {
2753 char buf[8];
2754
2755 cur_pct = new_pct;
Elliott Hughes73737162014-06-25 17:27:42 -07002756 snprintf(buf, sizeof(buf), "%" PRId64, cur_pct);
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002757 property_set("vold.encrypt_progress", buf);
2758 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002759 if (unix_read(realfd, buf, CRYPT_INPLACE_BUFSIZE) <= 0) {
Paul Lawrence87999172014-02-20 12:21:31 -08002760 SLOGE("Error reading real_blkdev %s for inplace encrypt", crypto_blkdev);
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002761 goto errout;
2762 }
2763 if (unix_write(cryptofd, buf, CRYPT_INPLACE_BUFSIZE) <= 0) {
Paul Lawrence87999172014-02-20 12:21:31 -08002764 SLOGE("Error writing crypto_blkdev %s for inplace encrypt", crypto_blkdev);
2765 goto errout;
2766 } else {
Elliott Hughescb33f572014-06-25 18:25:11 -07002767 SLOGD("Encrypted %d block at %" PRId64,
Paul Lawrence87999172014-02-20 12:21:31 -08002768 CRYPT_SECTORS_PER_BUFSIZE,
2769 i * CRYPT_SECTORS_PER_BUFSIZE);
2770 }
2771
Paul Lawrence73d7a022014-06-09 14:10:09 -07002772 if (!is_battery_ok_to_continue()) {
Paul Lawrence87999172014-02-20 12:21:31 -08002773 SLOGE("Stopping encryption due to low battery");
2774 *size_already_done += (i + 1) * CRYPT_SECTORS_PER_BUFSIZE - 1;
2775 rc = 0;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002776 goto errout;
2777 }
2778 }
2779
2780 /* Do any remaining sectors */
2781 for (i=0; i<remainder; i++) {
Paul Lawrence87999172014-02-20 12:21:31 -08002782 if (unix_read(realfd, buf, CRYPT_SECTOR_SIZE) <= 0) {
2783 SLOGE("Error reading final sectors from real_blkdev %s for inplace encrypt", crypto_blkdev);
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002784 goto errout;
2785 }
Paul Lawrence87999172014-02-20 12:21:31 -08002786 if (unix_write(cryptofd, buf, CRYPT_SECTOR_SIZE) <= 0) {
2787 SLOGE("Error writing final sectors to crypto_blkdev %s for inplace encrypt", crypto_blkdev);
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002788 goto errout;
Paul Lawrence87999172014-02-20 12:21:31 -08002789 } else {
2790 SLOGI("Encrypted 1 block at next location");
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002791 }
2792 }
2793
Ken Sumrall29d8da82011-05-18 17:20:07 -07002794 *size_already_done += size;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002795 rc = 0;
2796
2797errout:
2798 close(realfd);
2799 close(cryptofd);
2800
2801 return rc;
2802}
2803
JP Abgrall7fc1de82014-10-10 18:43:41 -07002804/* returns on of the ENABLE_INPLACE_* return codes */
Paul Lawrenceae59fe62014-01-21 08:23:27 -08002805static int cryptfs_enable_inplace(char *crypto_blkdev, char *real_blkdev,
2806 off64_t size, off64_t *size_already_done,
Paul Lawrence87999172014-02-20 12:21:31 -08002807 off64_t tot_size,
2808 off64_t previously_encrypted_upto)
Paul Lawrenceae59fe62014-01-21 08:23:27 -08002809{
JP Abgrall7fc1de82014-10-10 18:43:41 -07002810 int rc_ext4, rc_f2fs, rc_full;
Paul Lawrence87999172014-02-20 12:21:31 -08002811 if (previously_encrypted_upto) {
Elliott Hughescb33f572014-06-25 18:25:11 -07002812 SLOGD("Continuing encryption from %" PRId64, previously_encrypted_upto);
Paul Lawrence87999172014-02-20 12:21:31 -08002813 }
2814
2815 if (*size_already_done + size < previously_encrypted_upto) {
2816 *size_already_done += size;
2817 return 0;
2818 }
2819
Daniel Rosenberge82df162014-08-15 22:19:23 +00002820 /* TODO: identify filesystem type.
2821 * As is, cryptfs_enable_inplace_ext4 will fail on an f2fs partition, and
2822 * then we will drop down to cryptfs_enable_inplace_f2fs.
2823 * */
JP Abgrall7fc1de82014-10-10 18:43:41 -07002824 if ((rc_ext4 = cryptfs_enable_inplace_ext4(crypto_blkdev, real_blkdev,
Daniel Rosenberge82df162014-08-15 22:19:23 +00002825 size, size_already_done,
JP Abgrall7fc1de82014-10-10 18:43:41 -07002826 tot_size, previously_encrypted_upto)) == 0) {
Daniel Rosenberge82df162014-08-15 22:19:23 +00002827 return 0;
2828 }
JP Abgrall7fc1de82014-10-10 18:43:41 -07002829 SLOGD("cryptfs_enable_inplace_ext4()=%d\n", rc_ext4);
Daniel Rosenberge82df162014-08-15 22:19:23 +00002830
JP Abgrall7fc1de82014-10-10 18:43:41 -07002831 if ((rc_f2fs = cryptfs_enable_inplace_f2fs(crypto_blkdev, real_blkdev,
Daniel Rosenberge82df162014-08-15 22:19:23 +00002832 size, size_already_done,
JP Abgrall7fc1de82014-10-10 18:43:41 -07002833 tot_size, previously_encrypted_upto)) == 0) {
Daniel Rosenberge82df162014-08-15 22:19:23 +00002834 return 0;
Paul Lawrenceae59fe62014-01-21 08:23:27 -08002835 }
JP Abgrall7fc1de82014-10-10 18:43:41 -07002836 SLOGD("cryptfs_enable_inplace_f2fs()=%d\n", rc_f2fs);
Paul Lawrenceae59fe62014-01-21 08:23:27 -08002837
JP Abgrall7fc1de82014-10-10 18:43:41 -07002838 rc_full = cryptfs_enable_inplace_full(crypto_blkdev, real_blkdev,
Paul Lawrence87999172014-02-20 12:21:31 -08002839 size, size_already_done, tot_size,
2840 previously_encrypted_upto);
JP Abgrall7fc1de82014-10-10 18:43:41 -07002841 SLOGD("cryptfs_enable_inplace_full()=%d\n", rc_full);
2842
2843 /* Hack for b/17898962, the following is the symptom... */
2844 if (rc_ext4 == ENABLE_INPLACE_ERR_DEV
2845 && rc_f2fs == ENABLE_INPLACE_ERR_DEV
2846 && rc_full == ENABLE_INPLACE_ERR_DEV) {
2847 return ENABLE_INPLACE_ERR_DEV;
2848 }
2849 return rc_full;
Paul Lawrenceae59fe62014-01-21 08:23:27 -08002850}
2851
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002852#define CRYPTO_ENABLE_WIPE 1
2853#define CRYPTO_ENABLE_INPLACE 2
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002854
2855#define FRAMEWORK_BOOT_WAIT 60
2856
Ken Sumrall29d8da82011-05-18 17:20:07 -07002857static inline int should_encrypt(struct volume_info *volume)
2858{
Paul Lawrenceae59fe62014-01-21 08:23:27 -08002859 return (volume->flags & (VOL_ENCRYPTABLE | VOL_NONREMOVABLE)) ==
Ken Sumrall29d8da82011-05-18 17:20:07 -07002860 (VOL_ENCRYPTABLE | VOL_NONREMOVABLE);
2861}
2862
Paul Lawrence87999172014-02-20 12:21:31 -08002863static int cryptfs_SHA256_fileblock(const char* filename, __le8* buf)
2864{
2865 int fd = open(filename, O_RDONLY);
2866 if (fd == -1) {
2867 SLOGE("Error opening file %s", filename);
2868 return -1;
2869 }
2870
2871 char block[CRYPT_INPLACE_BUFSIZE];
2872 memset(block, 0, sizeof(block));
2873 if (unix_read(fd, block, sizeof(block)) < 0) {
2874 SLOGE("Error reading file %s", filename);
2875 close(fd);
2876 return -1;
2877 }
2878
2879 close(fd);
2880
2881 SHA256_CTX c;
2882 SHA256_Init(&c);
2883 SHA256_Update(&c, block, sizeof(block));
2884 SHA256_Final(buf, &c);
2885
2886 return 0;
2887}
2888
JP Abgrall62c7af32014-06-16 13:01:23 -07002889static int get_fs_type(struct fstab_rec *rec)
2890{
2891 if (!strcmp(rec->fs_type, "ext4")) {
2892 return EXT4_FS;
2893 } else if (!strcmp(rec->fs_type, "f2fs")) {
2894 return F2FS_FS;
2895 } else {
2896 return -1;
2897 }
2898}
2899
Paul Lawrence87999172014-02-20 12:21:31 -08002900static int cryptfs_enable_all_volumes(struct crypt_mnt_ftr *crypt_ftr, int how,
2901 char *crypto_blkdev, char *real_blkdev,
2902 int previously_encrypted_upto)
2903{
2904 off64_t cur_encryption_done=0, tot_encryption_size=0;
Tim Murray8439dc92014-12-15 11:56:11 -08002905 int rc = -1;
Paul Lawrence87999172014-02-20 12:21:31 -08002906
Paul Lawrence73d7a022014-06-09 14:10:09 -07002907 if (!is_battery_ok_to_start()) {
2908 SLOGW("Not starting encryption due to low battery");
Paul Lawrence87999172014-02-20 12:21:31 -08002909 return 0;
2910 }
2911
2912 /* The size of the userdata partition, and add in the vold volumes below */
2913 tot_encryption_size = crypt_ftr->fs_size;
2914
2915 if (how == CRYPTO_ENABLE_WIPE) {
JP Abgrall62c7af32014-06-16 13:01:23 -07002916 struct fstab_rec* rec = fs_mgr_get_entry_for_mount_point(fstab, DATA_MNT_POINT);
2917 int fs_type = get_fs_type(rec);
2918 if (fs_type < 0) {
2919 SLOGE("cryptfs_enable: unsupported fs type %s\n", rec->fs_type);
2920 return -1;
2921 }
2922 rc = cryptfs_enable_wipe(crypto_blkdev, crypt_ftr->fs_size, fs_type);
Paul Lawrence87999172014-02-20 12:21:31 -08002923 } else if (how == CRYPTO_ENABLE_INPLACE) {
2924 rc = cryptfs_enable_inplace(crypto_blkdev, real_blkdev,
2925 crypt_ftr->fs_size, &cur_encryption_done,
2926 tot_encryption_size,
2927 previously_encrypted_upto);
2928
JP Abgrall7fc1de82014-10-10 18:43:41 -07002929 if (rc == ENABLE_INPLACE_ERR_DEV) {
2930 /* Hack for b/17898962 */
2931 SLOGE("cryptfs_enable: crypto block dev failure. Must reboot...\n");
2932 cryptfs_reboot(reboot);
2933 }
2934
Paul Lawrence73d7a022014-06-09 14:10:09 -07002935 if (!rc) {
Paul Lawrence87999172014-02-20 12:21:31 -08002936 crypt_ftr->encrypted_upto = cur_encryption_done;
2937 }
2938
Paul Lawrence73d7a022014-06-09 14:10:09 -07002939 if (!rc && crypt_ftr->encrypted_upto == crypt_ftr->fs_size) {
Paul Lawrence87999172014-02-20 12:21:31 -08002940 /* The inplace routine never actually sets the progress to 100% due
2941 * to the round down nature of integer division, so set it here */
2942 property_set("vold.encrypt_progress", "100");
2943 }
2944 } else {
2945 /* Shouldn't happen */
2946 SLOGE("cryptfs_enable: internal error, unknown option\n");
2947 rc = -1;
2948 }
2949
2950 return rc;
2951}
2952
Paul Lawrence13486032014-02-03 13:28:11 -08002953int cryptfs_enable_internal(char *howarg, int crypt_type, char *passwd,
2954 int allow_reboot)
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002955{
2956 int how = 0;
Paul Lawrence87999172014-02-20 12:21:31 -08002957 char crypto_blkdev[MAXPATHLEN], real_blkdev[MAXPATHLEN];
Ken Sumrall160b4d62013-04-22 12:15:39 -07002958 unsigned char decrypted_master_key[KEY_LEN_BYTES];
Hiroaki Miyazawa14eab552015-02-04 13:29:15 +09002959 int rc=-1, i;
Paul Lawrence87999172014-02-20 12:21:31 -08002960 struct crypt_mnt_ftr crypt_ftr;
Ken Sumrall160b4d62013-04-22 12:15:39 -07002961 struct crypt_persist_data *pdata;
Ken Sumrall29d8da82011-05-18 17:20:07 -07002962 char encrypted_state[PROPERTY_VALUE_MAX];
Ken Sumrall5d4c68e2011-01-30 19:06:03 -08002963 char lockid[32] = { 0 };
Ken Sumrall29d8da82011-05-18 17:20:07 -07002964 char key_loc[PROPERTY_VALUE_MAX];
2965 char fuse_sdcard[PROPERTY_VALUE_MAX];
2966 char *sd_mnt_point;
Ken Sumrall29d8da82011-05-18 17:20:07 -07002967 int num_vols;
2968 struct volume_info *vol_list = 0;
Paul Lawrence87999172014-02-20 12:21:31 -08002969 off64_t previously_encrypted_upto = 0;
Ken Sumrall29d8da82011-05-18 17:20:07 -07002970
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002971 if (!strcmp(howarg, "wipe")) {
2972 how = CRYPTO_ENABLE_WIPE;
2973 } else if (! strcmp(howarg, "inplace")) {
2974 how = CRYPTO_ENABLE_INPLACE;
2975 } else {
2976 /* Shouldn't happen, as CommandListener vets the args */
Ken Sumrall3ed82362011-01-28 23:31:16 -08002977 goto error_unencrypted;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002978 }
2979
Paul Lawrence87999172014-02-20 12:21:31 -08002980 /* See if an encryption was underway and interrupted */
2981 if (how == CRYPTO_ENABLE_INPLACE
2982 && get_crypt_ftr_and_key(&crypt_ftr) == 0
2983 && (crypt_ftr.flags & CRYPT_ENCRYPTION_IN_PROGRESS)) {
2984 previously_encrypted_upto = crypt_ftr.encrypted_upto;
2985 crypt_ftr.encrypted_upto = 0;
Paul Lawrence6bfed202014-07-28 12:47:22 -07002986 crypt_ftr.flags &= ~CRYPT_ENCRYPTION_IN_PROGRESS;
2987
2988 /* At this point, we are in an inconsistent state. Until we successfully
2989 complete encryption, a reboot will leave us broken. So mark the
2990 encryption failed in case that happens.
2991 On successfully completing encryption, remove this flag */
2992 crypt_ftr.flags |= CRYPT_INCONSISTENT_STATE;
2993
2994 put_crypt_ftr_and_key(&crypt_ftr);
Paul Lawrence87999172014-02-20 12:21:31 -08002995 }
2996
2997 property_get("ro.crypto.state", encrypted_state, "");
2998 if (!strcmp(encrypted_state, "encrypted") && !previously_encrypted_upto) {
2999 SLOGE("Device is already running encrypted, aborting");
3000 goto error_unencrypted;
3001 }
3002
3003 // TODO refactor fs_mgr_get_crypt_info to get both in one call
3004 fs_mgr_get_crypt_info(fstab, key_loc, 0, sizeof(key_loc));
Ken Sumrall56ad03c2013-02-13 13:00:19 -08003005 fs_mgr_get_crypt_info(fstab, 0, real_blkdev, sizeof(real_blkdev));
Ken Sumrall8f869aa2010-12-03 03:47:09 -08003006
Ken Sumrall3ed82362011-01-28 23:31:16 -08003007 /* Get the size of the real block device */
Hiroaki Miyazawa14eab552015-02-04 13:29:15 +09003008 int fd = open(real_blkdev, O_RDONLY);
3009 if (fd == -1) {
3010 SLOGE("Cannot open block device %s\n", real_blkdev);
3011 goto error_unencrypted;
3012 }
3013 unsigned long nr_sec;
3014 get_blkdev_size(fd, &nr_sec);
3015 if (nr_sec == 0) {
Ken Sumrall3ed82362011-01-28 23:31:16 -08003016 SLOGE("Cannot get size of block device %s\n", real_blkdev);
3017 goto error_unencrypted;
3018 }
3019 close(fd);
3020
3021 /* If doing inplace encryption, make sure the orig fs doesn't include the crypto footer */
Ken Sumrall29d8da82011-05-18 17:20:07 -07003022 if ((how == CRYPTO_ENABLE_INPLACE) && (!strcmp(key_loc, KEY_IN_FOOTER))) {
Ken Sumrall3ed82362011-01-28 23:31:16 -08003023 unsigned int fs_size_sec, max_fs_size_sec;
Jim Millera70abc62014-08-15 02:00:45 +00003024 fs_size_sec = get_fs_size(real_blkdev);
Daniel Rosenberge82df162014-08-15 22:19:23 +00003025 if (fs_size_sec == 0)
3026 fs_size_sec = get_f2fs_filesystem_size_sec(real_blkdev);
3027
Paul Lawrence87999172014-02-20 12:21:31 -08003028 max_fs_size_sec = nr_sec - (CRYPT_FOOTER_OFFSET / CRYPT_SECTOR_SIZE);
Ken Sumrall3ed82362011-01-28 23:31:16 -08003029
3030 if (fs_size_sec > max_fs_size_sec) {
3031 SLOGE("Orig filesystem overlaps crypto footer region. Cannot encrypt in place.");
3032 goto error_unencrypted;
3033 }
3034 }
3035
Ken Sumrall5d4c68e2011-01-30 19:06:03 -08003036 /* Get a wakelock as this may take a while, and we don't want the
3037 * device to sleep on us. We'll grab a partial wakelock, and if the UI
3038 * wants to keep the screen on, it can grab a full wakelock.
3039 */
Ken Sumrall29d8da82011-05-18 17:20:07 -07003040 snprintf(lockid, sizeof(lockid), "enablecrypto%d", (int) getpid());
Ken Sumrall5d4c68e2011-01-30 19:06:03 -08003041 acquire_wake_lock(PARTIAL_WAKE_LOCK, lockid);
3042
Jeff Sharkey7382f812012-08-23 14:08:59 -07003043 /* Get the sdcard mount point */
Jeff Sharkeyb77bc462012-10-01 14:36:26 -07003044 sd_mnt_point = getenv("EMULATED_STORAGE_SOURCE");
Jeff Sharkey7382f812012-08-23 14:08:59 -07003045 if (!sd_mnt_point) {
3046 sd_mnt_point = getenv("EXTERNAL_STORAGE");
3047 }
3048 if (!sd_mnt_point) {
3049 sd_mnt_point = "/mnt/sdcard";
3050 }
Ken Sumrall29d8da82011-05-18 17:20:07 -07003051
Paul Lawrence87999172014-02-20 12:21:31 -08003052 /* TODO
3053 * Currently do not have test devices with multiple encryptable volumes.
3054 * When we acquire some, re-add support.
3055 */
Ken Sumrall29d8da82011-05-18 17:20:07 -07003056 num_vols=vold_getNumDirectVolumes();
3057 vol_list = malloc(sizeof(struct volume_info) * num_vols);
3058 vold_getDirectVolumeList(vol_list);
3059
3060 for (i=0; i<num_vols; i++) {
3061 if (should_encrypt(&vol_list[i])) {
Paul Lawrence87999172014-02-20 12:21:31 -08003062 SLOGE("Cannot encrypt if there are multiple encryptable volumes"
3063 "%s\n", vol_list[i].label);
3064 goto error_unencrypted;
Ken Sumrall29d8da82011-05-18 17:20:07 -07003065 }
3066 }
3067
Ken Sumrall8f869aa2010-12-03 03:47:09 -08003068 /* The init files are setup to stop the class main and late start when
Ken Sumrall8ddbe402011-01-17 15:26:29 -08003069 * vold sets trigger_shutdown_framework.
Ken Sumrall8f869aa2010-12-03 03:47:09 -08003070 */
3071 property_set("vold.decrypt", "trigger_shutdown_framework");
3072 SLOGD("Just asked init to shut down class main\n");
3073
Ken Sumrall425524d2012-06-14 20:55:28 -07003074 if (vold_unmountAllAsecs()) {
3075 /* Just report the error. If any are left mounted,
3076 * umounting /data below will fail and handle the error.
3077 */
3078 SLOGE("Error unmounting internal asecs");
3079 }
3080
Ken Sumrall29d8da82011-05-18 17:20:07 -07003081 property_get("ro.crypto.fuse_sdcard", fuse_sdcard, "");
3082 if (!strcmp(fuse_sdcard, "true")) {
3083 /* This is a device using the fuse layer to emulate the sdcard semantics
3084 * on top of the userdata partition. vold does not manage it, it is managed
3085 * by the sdcard service. The sdcard service was killed by the property trigger
3086 * above, so just unmount it now. We must do this _AFTER_ killing the framework,
3087 * unlike the case for vold managed devices above.
3088 */
Greg Hackmann6e8440f2014-10-02 17:18:20 -07003089 if (wait_and_unmount(sd_mnt_point, false)) {
Ken Sumrall29d8da82011-05-18 17:20:07 -07003090 goto error_shutting_down;
3091 }
Ken Sumrall2eaf7132011-01-14 12:45:48 -08003092 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08003093
3094 /* Now unmount the /data partition. */
Greg Hackmann6e8440f2014-10-02 17:18:20 -07003095 if (wait_and_unmount(DATA_MNT_POINT, false)) {
JP Abgrall502dc742013-11-01 13:06:20 -07003096 if (allow_reboot) {
3097 goto error_shutting_down;
3098 } else {
3099 goto error_unencrypted;
3100 }
Ken Sumrall8ddbe402011-01-17 15:26:29 -08003101 }
3102
3103 /* Do extra work for a better UX when doing the long inplace encryption */
3104 if (how == CRYPTO_ENABLE_INPLACE) {
3105 /* Now that /data is unmounted, we need to mount a tmpfs
3106 * /data, set a property saying we're doing inplace encryption,
3107 * and restart the framework.
Ken Sumrall8f869aa2010-12-03 03:47:09 -08003108 */
Ken Sumralle5032c42012-04-01 23:58:44 -07003109 if (fs_mgr_do_tmpfs_mount(DATA_MNT_POINT)) {
Ken Sumrall3ed82362011-01-28 23:31:16 -08003110 goto error_shutting_down;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08003111 }
Ken Sumrall8ddbe402011-01-17 15:26:29 -08003112 /* Tells the framework that inplace encryption is starting */
Ken Sumrall7df84122011-01-18 14:04:08 -08003113 property_set("vold.encrypt_progress", "0");
Ken Sumrall8f869aa2010-12-03 03:47:09 -08003114
Ken Sumrall8ddbe402011-01-17 15:26:29 -08003115 /* restart the framework. */
3116 /* Create necessary paths on /data */
3117 if (prep_data_fs()) {
Ken Sumrall3ed82362011-01-28 23:31:16 -08003118 goto error_shutting_down;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08003119 }
3120
Ken Sumrall92736ef2012-10-17 20:57:14 -07003121 /* Ugh, shutting down the framework is not synchronous, so until it
3122 * can be fixed, this horrible hack will wait a moment for it all to
3123 * shut down before proceeding. Without it, some devices cannot
3124 * restart the graphics services.
3125 */
3126 sleep(2);
Ken Sumrall8ddbe402011-01-17 15:26:29 -08003127 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08003128
Ken Sumrall8ddbe402011-01-17 15:26:29 -08003129 /* Start the actual work of making an encrypted filesystem */
Ken Sumrall8ddbe402011-01-17 15:26:29 -08003130 /* Initialize a crypt_mnt_ftr for the partition */
Paul Lawrence87999172014-02-20 12:21:31 -08003131 if (previously_encrypted_upto == 0) {
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07003132 if (cryptfs_init_crypt_mnt_ftr(&crypt_ftr)) {
3133 goto error_shutting_down;
3134 }
Ken Sumrall160b4d62013-04-22 12:15:39 -07003135
Paul Lawrence87999172014-02-20 12:21:31 -08003136 if (!strcmp(key_loc, KEY_IN_FOOTER)) {
3137 crypt_ftr.fs_size = nr_sec
3138 - (CRYPT_FOOTER_OFFSET / CRYPT_SECTOR_SIZE);
3139 } else {
3140 crypt_ftr.fs_size = nr_sec;
3141 }
Paul Lawrence6bfed202014-07-28 12:47:22 -07003142 /* At this point, we are in an inconsistent state. Until we successfully
3143 complete encryption, a reboot will leave us broken. So mark the
3144 encryption failed in case that happens.
3145 On successfully completing encryption, remove this flag */
3146 crypt_ftr.flags |= CRYPT_INCONSISTENT_STATE;
Paul Lawrence87999172014-02-20 12:21:31 -08003147 crypt_ftr.crypt_type = crypt_type;
Ajay Dudani87701e22014-09-17 21:02:52 -07003148#ifndef CONFIG_HW_DISK_ENCRYPTION
3149 strlcpy((char *)crypt_ftr.crypto_type_name, "aes-cbc-essiv:sha256", MAX_CRYPTO_TYPE_NAME_LEN);
3150#else
3151 strlcpy((char *)crypt_ftr.crypto_type_name, "aes-xts", MAX_CRYPTO_TYPE_NAME_LEN);
3152
Iliyan Malchevbb7d9af2014-11-20 18:42:23 -08003153 rc = clear_hw_device_encryption_key();
Ajay Dudani87701e22014-09-17 21:02:52 -07003154 if (!rc) {
3155 SLOGE("Error clearing device encryption hardware key. rc = %d", rc);
3156 }
3157
3158 rc = set_hw_device_encryption_key(passwd,
3159 (char*) crypt_ftr.crypto_type_name);
3160 if (!rc) {
3161 SLOGE("Error initializing device encryption hardware key. rc = %d", rc);
3162 goto error_shutting_down;
3163 }
3164#endif
Ken Sumrall8ddbe402011-01-17 15:26:29 -08003165
Paul Lawrence87999172014-02-20 12:21:31 -08003166 /* Make an encrypted master key */
3167 if (create_encrypted_random_key(passwd, crypt_ftr.master_key, crypt_ftr.salt, &crypt_ftr)) {
3168 SLOGE("Cannot create encrypted master key\n");
3169 goto error_shutting_down;
3170 }
Ken Sumrall8ddbe402011-01-17 15:26:29 -08003171
Paul Lawrence87999172014-02-20 12:21:31 -08003172 /* Write the key to the end of the partition */
3173 put_crypt_ftr_and_key(&crypt_ftr);
Ken Sumrall8ddbe402011-01-17 15:26:29 -08003174
Paul Lawrence87999172014-02-20 12:21:31 -08003175 /* If any persistent data has been remembered, save it.
3176 * If none, create a valid empty table and save that.
3177 */
3178 if (!persist_data) {
3179 pdata = malloc(CRYPT_PERSIST_DATA_SIZE);
3180 if (pdata) {
3181 init_empty_persist_data(pdata, CRYPT_PERSIST_DATA_SIZE);
3182 persist_data = pdata;
3183 }
3184 }
3185 if (persist_data) {
3186 save_persistent_data();
3187 }
Ken Sumrall160b4d62013-04-22 12:15:39 -07003188 }
3189
Ajay Dudani87701e22014-09-17 21:02:52 -07003190 if (how == CRYPTO_ENABLE_INPLACE) {
3191 /* startup service classes main and late_start */
3192 property_set("vold.decrypt", "trigger_restart_min_framework");
3193 SLOGD("Just triggered restart_min_framework\n");
3194
3195 /* OK, the framework is restarted and will soon be showing a
3196 * progress bar. Time to setup an encrypted mapping, and
3197 * either write a new filesystem, or encrypt in place updating
3198 * the progress bar as we work.
3199 */
3200 }
3201
Paul Lawrenced0c7b172014-08-08 14:28:10 -07003202 decrypt_master_key(passwd, decrypted_master_key, &crypt_ftr, 0, 0);
Ken Sumrall29d8da82011-05-18 17:20:07 -07003203 create_crypto_blk_dev(&crypt_ftr, decrypted_master_key, real_blkdev, crypto_blkdev,
3204 "userdata");
3205
Paul Lawrence87999172014-02-20 12:21:31 -08003206 /* If we are continuing, check checksums match */
3207 rc = 0;
3208 if (previously_encrypted_upto) {
3209 __le8 hash_first_block[SHA256_DIGEST_LENGTH];
3210 rc = cryptfs_SHA256_fileblock(crypto_blkdev, hash_first_block);
Ken Sumrall128626f2011-06-28 18:45:14 -07003211
Paul Lawrence87999172014-02-20 12:21:31 -08003212 if (!rc && memcmp(hash_first_block, crypt_ftr.hash_first_block,
3213 sizeof(hash_first_block)) != 0) {
3214 SLOGE("Checksums do not match - trigger wipe");
3215 rc = -1;
Ken Sumrall29d8da82011-05-18 17:20:07 -07003216 }
3217 }
Ken Sumrall8ddbe402011-01-17 15:26:29 -08003218
Paul Lawrence87999172014-02-20 12:21:31 -08003219 if (!rc) {
3220 rc = cryptfs_enable_all_volumes(&crypt_ftr, how,
3221 crypto_blkdev, real_blkdev,
3222 previously_encrypted_upto);
3223 }
3224
3225 /* Calculate checksum if we are not finished */
Paul Lawrenceb1eb7a02014-11-25 14:57:32 -08003226 if (!rc && how == CRYPTO_ENABLE_INPLACE
3227 && crypt_ftr.encrypted_upto != crypt_ftr.fs_size) {
Paul Lawrence87999172014-02-20 12:21:31 -08003228 rc = cryptfs_SHA256_fileblock(crypto_blkdev,
3229 crypt_ftr.hash_first_block);
Paul Lawrence73d7a022014-06-09 14:10:09 -07003230 if (rc) {
Paul Lawrence87999172014-02-20 12:21:31 -08003231 SLOGE("Error calculating checksum for continuing encryption");
3232 rc = -1;
Ken Sumrall29d8da82011-05-18 17:20:07 -07003233 }
Ken Sumrall8ddbe402011-01-17 15:26:29 -08003234 }
3235
3236 /* Undo the dm-crypt mapping whether we succeed or not */
Ken Sumrall29d8da82011-05-18 17:20:07 -07003237 delete_crypto_blk_dev("userdata");
Ken Sumrall29d8da82011-05-18 17:20:07 -07003238
3239 free(vol_list);
Ken Sumrall8ddbe402011-01-17 15:26:29 -08003240
3241 if (! rc) {
3242 /* Success */
Paul Lawrence6bfed202014-07-28 12:47:22 -07003243 crypt_ftr.flags &= ~CRYPT_INCONSISTENT_STATE;
Ken Sumrall7f7dbaa2011-02-01 15:46:41 -08003244
Paul Lawrenceb1eb7a02014-11-25 14:57:32 -08003245 if (how == CRYPTO_ENABLE_INPLACE
3246 && crypt_ftr.encrypted_upto != crypt_ftr.fs_size) {
Paul Lawrence87999172014-02-20 12:21:31 -08003247 SLOGD("Encrypted up to sector %lld - will continue after reboot",
3248 crypt_ftr.encrypted_upto);
Paul Lawrence6bfed202014-07-28 12:47:22 -07003249 crypt_ftr.flags |= CRYPT_ENCRYPTION_IN_PROGRESS;
Paul Lawrence87999172014-02-20 12:21:31 -08003250 }
Paul Lawrence73d7a022014-06-09 14:10:09 -07003251
Paul Lawrence6bfed202014-07-28 12:47:22 -07003252 put_crypt_ftr_and_key(&crypt_ftr);
Ken Sumralld33d4172011-02-01 00:49:13 -08003253
Paul Lawrenceb1eb7a02014-11-25 14:57:32 -08003254 if (how == CRYPTO_ENABLE_WIPE
3255 || crypt_ftr.encrypted_upto == crypt_ftr.fs_size) {
Paul Lawrenceb6672e12014-08-15 07:37:28 -07003256 char value[PROPERTY_VALUE_MAX];
3257 property_get("ro.crypto.state", value, "");
3258 if (!strcmp(value, "")) {
3259 /* default encryption - continue first boot sequence */
3260 property_set("ro.crypto.state", "encrypted");
3261 release_wake_lock(lockid);
3262 cryptfs_check_passwd(DEFAULT_PASSWORD);
3263 cryptfs_restart_internal(1);
3264 return 0;
3265 } else {
3266 sleep(2); /* Give the UI a chance to show 100% progress */
Paul Lawrence87999172014-02-20 12:21:31 -08003267 cryptfs_reboot(reboot);
Paul Lawrenceb6672e12014-08-15 07:37:28 -07003268 }
Paul Lawrence87999172014-02-20 12:21:31 -08003269 } else {
Paul Lawrenceb6672e12014-08-15 07:37:28 -07003270 sleep(2); /* Partially encrypted, ensure writes flushed to ssd */
Paul Lawrence87999172014-02-20 12:21:31 -08003271 cryptfs_reboot(shutdown);
3272 }
Ken Sumrall3ed82362011-01-28 23:31:16 -08003273 } else {
Mike Lockwoodee6d8c42012-02-15 13:43:28 -08003274 char value[PROPERTY_VALUE_MAX];
3275
Ken Sumrall319369a2012-06-27 16:30:18 -07003276 property_get("ro.vold.wipe_on_crypt_fail", value, "0");
Mike Lockwoodee6d8c42012-02-15 13:43:28 -08003277 if (!strcmp(value, "1")) {
3278 /* wipe data if encryption failed */
3279 SLOGE("encryption failed - rebooting into recovery to wipe data\n");
3280 mkdir("/cache/recovery", 0700);
Nick Kralevich4684e582012-06-26 15:07:03 -07003281 int fd = open("/cache/recovery/command", O_RDWR|O_CREAT|O_TRUNC, 0600);
Mike Lockwoodee6d8c42012-02-15 13:43:28 -08003282 if (fd >= 0) {
Jeff Sharkeydd1a8042014-09-24 11:46:51 -07003283 write(fd, "--wipe_data\n", strlen("--wipe_data\n") + 1);
3284 write(fd, "--reason=cryptfs_enable_internal\n", strlen("--reason=cryptfs_enable_internal\n") + 1);
Mike Lockwoodee6d8c42012-02-15 13:43:28 -08003285 close(fd);
3286 } else {
3287 SLOGE("could not open /cache/recovery/command\n");
3288 }
Paul Lawrence87999172014-02-20 12:21:31 -08003289 cryptfs_reboot(recovery);
Mike Lockwoodee6d8c42012-02-15 13:43:28 -08003290 } else {
3291 /* set property to trigger dialog */
3292 property_set("vold.encrypt_progress", "error_partially_encrypted");
3293 release_wake_lock(lockid);
3294 }
Ken Sumrall3ed82362011-01-28 23:31:16 -08003295 return -1;
Ken Sumrall8ddbe402011-01-17 15:26:29 -08003296 }
3297
Ken Sumrall3ed82362011-01-28 23:31:16 -08003298 /* hrm, the encrypt step claims success, but the reboot failed.
3299 * This should not happen.
3300 * Set the property and return. Hope the framework can deal with it.
3301 */
3302 property_set("vold.encrypt_progress", "error_reboot_failed");
Ken Sumrall5d4c68e2011-01-30 19:06:03 -08003303 release_wake_lock(lockid);
Ken Sumrall8ddbe402011-01-17 15:26:29 -08003304 return rc;
Ken Sumrall3ed82362011-01-28 23:31:16 -08003305
3306error_unencrypted:
Ken Sumrall29d8da82011-05-18 17:20:07 -07003307 free(vol_list);
Ken Sumrall3ed82362011-01-28 23:31:16 -08003308 property_set("vold.encrypt_progress", "error_not_encrypted");
Ken Sumrall5d4c68e2011-01-30 19:06:03 -08003309 if (lockid[0]) {
3310 release_wake_lock(lockid);
3311 }
Ken Sumrall3ed82362011-01-28 23:31:16 -08003312 return -1;
3313
3314error_shutting_down:
3315 /* we failed, and have not encrypted anthing, so the users's data is still intact,
3316 * but the framework is stopped and not restarted to show the error, so it's up to
3317 * vold to restart the system.
3318 */
3319 SLOGE("Error enabling encryption after framework is shutdown, no data changed, restarting system");
Paul Lawrence87999172014-02-20 12:21:31 -08003320 cryptfs_reboot(reboot);
Ken Sumrall3ed82362011-01-28 23:31:16 -08003321
3322 /* shouldn't get here */
3323 property_set("vold.encrypt_progress", "error_shutting_down");
Ken Sumrall29d8da82011-05-18 17:20:07 -07003324 free(vol_list);
Ken Sumrall5d4c68e2011-01-30 19:06:03 -08003325 if (lockid[0]) {
3326 release_wake_lock(lockid);
3327 }
Ken Sumrall3ed82362011-01-28 23:31:16 -08003328 return -1;
Ken Sumrall8ddbe402011-01-17 15:26:29 -08003329}
3330
Paul Lawrence45f10532014-04-04 18:11:56 +00003331int cryptfs_enable(char *howarg, int type, char *passwd, int allow_reboot)
Paul Lawrence13486032014-02-03 13:28:11 -08003332{
Paul Lawrencefc615042014-10-04 15:32:29 -07003333 char* adjusted_passwd = adjust_passwd(passwd);
3334 if (adjusted_passwd) {
3335 passwd = adjusted_passwd;
3336 }
3337
3338 int rc = cryptfs_enable_internal(howarg, type, passwd, allow_reboot);
3339
3340 free(adjusted_passwd);
3341 return rc;
Paul Lawrence13486032014-02-03 13:28:11 -08003342}
3343
3344int cryptfs_enable_default(char *howarg, int allow_reboot)
3345{
3346 return cryptfs_enable_internal(howarg, CRYPT_TYPE_DEFAULT,
3347 DEFAULT_PASSWORD, allow_reboot);
3348}
3349
3350int cryptfs_changepw(int crypt_type, const char *newpw)
Ken Sumrall8ddbe402011-01-17 15:26:29 -08003351{
Paul Lawrence8175a0b2015-03-05 09:46:23 -08003352 if (e4crypt_crypto_complete(DATA_MNT_POINT) == 0) {
3353 return e4crypt_change_password(DATA_MNT_POINT, crypt_type, newpw);
3354 }
3355
Ken Sumrall8ddbe402011-01-17 15:26:29 -08003356 struct crypt_mnt_ftr crypt_ftr;
Ken Sumrall8ddbe402011-01-17 15:26:29 -08003357
3358 /* This is only allowed after we've successfully decrypted the master key */
Paul Lawrencef4faa572014-01-29 13:31:03 -08003359 if (!master_key_saved) {
Ken Sumrall0cc16632011-01-18 20:32:26 -08003360 SLOGE("Key not saved, aborting");
Ken Sumrall8ddbe402011-01-17 15:26:29 -08003361 return -1;
3362 }
3363
Paul Lawrencef4faa572014-01-29 13:31:03 -08003364 if (crypt_type < 0 || crypt_type > CRYPT_TYPE_MAX_TYPE) {
3365 SLOGE("Invalid crypt_type %d", crypt_type);
3366 return -1;
3367 }
3368
Ken Sumrall8ddbe402011-01-17 15:26:29 -08003369 /* get key */
Ken Sumrall160b4d62013-04-22 12:15:39 -07003370 if (get_crypt_ftr_and_key(&crypt_ftr)) {
Paul Lawrencef4faa572014-01-29 13:31:03 -08003371 SLOGE("Error getting crypt footer and key");
3372 return -1;
Ken Sumrall8ddbe402011-01-17 15:26:29 -08003373 }
3374
Paul Lawrencef4faa572014-01-29 13:31:03 -08003375 crypt_ftr.crypt_type = crypt_type;
3376
Paul Lawrencefc615042014-10-04 15:32:29 -07003377 char* adjusted_passwd = adjust_passwd(newpw);
3378 if (adjusted_passwd) {
3379 newpw = adjusted_passwd;
3380 }
3381
Paul Lawrencef4faa572014-01-29 13:31:03 -08003382 encrypt_master_key(crypt_type == CRYPT_TYPE_DEFAULT ? DEFAULT_PASSWORD
3383 : newpw,
3384 crypt_ftr.salt,
3385 saved_master_key,
3386 crypt_ftr.master_key,
3387 &crypt_ftr);
Ken Sumrall8ddbe402011-01-17 15:26:29 -08003388
Jason parks70a4b3f2011-01-28 10:10:47 -06003389 /* save the key */
Ken Sumrall160b4d62013-04-22 12:15:39 -07003390 put_crypt_ftr_and_key(&crypt_ftr);
Ken Sumrall8f869aa2010-12-03 03:47:09 -08003391
Paul Lawrencefc615042014-10-04 15:32:29 -07003392 free(adjusted_passwd);
Ajay Dudani87701e22014-09-17 21:02:52 -07003393
3394#ifdef CONFIG_HW_DISK_ENCRYPTION
Iliyan Malchevbb7d9af2014-11-20 18:42:23 -08003395 if (!strcmp((char *)crypt_ftr.crypto_type_name, "aes-xts")) {
3396 if (crypt_type == CRYPT_TYPE_DEFAULT) {
3397 int rc = update_hw_device_encryption_key(DEFAULT_PASSWORD, (char*) crypt_ftr.crypto_type_name);
3398 SLOGD("Update hardware encryption key to default for crypt_type: %d. rc = %d", crypt_type, rc);
3399 if (!rc)
3400 return -1;
3401 } else {
3402 int rc = update_hw_device_encryption_key(newpw, (char*) crypt_ftr.crypto_type_name);
3403 SLOGD("Update hardware encryption key for crypt_type: %d. rc = %d", crypt_type, rc);
3404 if (!rc)
3405 return -1;
3406 }
Ajay Dudani87701e22014-09-17 21:02:52 -07003407 }
3408#endif
Ken Sumrall8f869aa2010-12-03 03:47:09 -08003409 return 0;
3410}
Ken Sumrall160b4d62013-04-22 12:15:39 -07003411
Rubin Xu85c01f92014-10-13 12:49:54 +01003412static unsigned int persist_get_max_entries(int encrypted) {
3413 struct crypt_mnt_ftr crypt_ftr;
3414 unsigned int dsize;
3415 unsigned int max_persistent_entries;
3416
3417 /* If encrypted, use the values from the crypt_ftr, otherwise
3418 * use the values for the current spec.
3419 */
3420 if (encrypted) {
3421 if (get_crypt_ftr_and_key(&crypt_ftr)) {
3422 return -1;
3423 }
3424 dsize = crypt_ftr.persist_data_size;
3425 } else {
3426 dsize = CRYPT_PERSIST_DATA_SIZE;
3427 }
3428
3429 max_persistent_entries = (dsize - sizeof(struct crypt_persist_data)) /
3430 sizeof(struct crypt_persist_entry);
3431
3432 return max_persistent_entries;
3433}
3434
3435static int persist_get_key(const char *fieldname, char *value)
Ken Sumrall160b4d62013-04-22 12:15:39 -07003436{
3437 unsigned int i;
3438
3439 if (persist_data == NULL) {
3440 return -1;
3441 }
3442 for (i = 0; i < persist_data->persist_valid_entries; i++) {
3443 if (!strncmp(persist_data->persist_entry[i].key, fieldname, PROPERTY_KEY_MAX)) {
3444 /* We found it! */
3445 strlcpy(value, persist_data->persist_entry[i].val, PROPERTY_VALUE_MAX);
3446 return 0;
3447 }
3448 }
3449
3450 return -1;
3451}
3452
Rubin Xu85c01f92014-10-13 12:49:54 +01003453static int persist_set_key(const char *fieldname, const char *value, int encrypted)
Ken Sumrall160b4d62013-04-22 12:15:39 -07003454{
3455 unsigned int i;
3456 unsigned int num;
Ken Sumrall160b4d62013-04-22 12:15:39 -07003457 unsigned int max_persistent_entries;
Ken Sumrall160b4d62013-04-22 12:15:39 -07003458
3459 if (persist_data == NULL) {
3460 return -1;
3461 }
3462
Rubin Xu85c01f92014-10-13 12:49:54 +01003463 max_persistent_entries = persist_get_max_entries(encrypted);
Ken Sumrall160b4d62013-04-22 12:15:39 -07003464
3465 num = persist_data->persist_valid_entries;
3466
3467 for (i = 0; i < num; i++) {
3468 if (!strncmp(persist_data->persist_entry[i].key, fieldname, PROPERTY_KEY_MAX)) {
3469 /* We found an existing entry, update it! */
3470 memset(persist_data->persist_entry[i].val, 0, PROPERTY_VALUE_MAX);
3471 strlcpy(persist_data->persist_entry[i].val, value, PROPERTY_VALUE_MAX);
3472 return 0;
3473 }
3474 }
3475
3476 /* We didn't find it, add it to the end, if there is room */
3477 if (persist_data->persist_valid_entries < max_persistent_entries) {
3478 memset(&persist_data->persist_entry[num], 0, sizeof(struct crypt_persist_entry));
3479 strlcpy(persist_data->persist_entry[num].key, fieldname, PROPERTY_KEY_MAX);
3480 strlcpy(persist_data->persist_entry[num].val, value, PROPERTY_VALUE_MAX);
3481 persist_data->persist_valid_entries++;
3482 return 0;
3483 }
3484
3485 return -1;
3486}
3487
Rubin Xu85c01f92014-10-13 12:49:54 +01003488/**
3489 * Test if key is part of the multi-entry (field, index) sequence. Return non-zero if key is in the
3490 * sequence and its index is greater than or equal to index. Return 0 otherwise.
3491 */
3492static int match_multi_entry(const char *key, const char *field, unsigned index) {
Rubin Xu85c01f92014-10-13 12:49:54 +01003493 unsigned int field_len;
3494 unsigned int key_index;
3495 field_len = strlen(field);
3496
3497 if (index == 0) {
3498 // The first key in a multi-entry field is just the filedname itself.
3499 if (!strcmp(key, field)) {
3500 return 1;
3501 }
3502 }
3503 // Match key against "%s_%d" % (field, index)
3504 if (strlen(key) < field_len + 1 + 1) {
3505 // Need at least a '_' and a digit.
3506 return 0;
3507 }
3508 if (strncmp(key, field, field_len)) {
3509 // If the key does not begin with field, it's not a match.
3510 return 0;
3511 }
3512 if (1 != sscanf(&key[field_len],"_%d", &key_index)) {
3513 return 0;
3514 }
3515 return key_index >= index;
3516}
3517
3518/*
3519 * Delete entry/entries from persist_data. If the entries are part of a multi-segment field, all
3520 * remaining entries starting from index will be deleted.
3521 * returns PERSIST_DEL_KEY_OK if deletion succeeds,
3522 * PERSIST_DEL_KEY_ERROR_NO_FIELD if the field does not exist,
3523 * and PERSIST_DEL_KEY_ERROR_OTHER if error occurs.
3524 *
3525 */
3526static int persist_del_keys(const char *fieldname, unsigned index)
3527{
3528 unsigned int i;
3529 unsigned int j;
3530 unsigned int num;
3531
3532 if (persist_data == NULL) {
3533 return PERSIST_DEL_KEY_ERROR_OTHER;
3534 }
3535
3536 num = persist_data->persist_valid_entries;
3537
3538 j = 0; // points to the end of non-deleted entries.
3539 // Filter out to-be-deleted entries in place.
3540 for (i = 0; i < num; i++) {
3541 if (!match_multi_entry(persist_data->persist_entry[i].key, fieldname, index)) {
3542 persist_data->persist_entry[j] = persist_data->persist_entry[i];
3543 j++;
3544 }
3545 }
3546
3547 if (j < num) {
3548 persist_data->persist_valid_entries = j;
3549 // Zeroise the remaining entries
3550 memset(&persist_data->persist_entry[j], 0, (num - j) * sizeof(struct crypt_persist_entry));
3551 return PERSIST_DEL_KEY_OK;
3552 } else {
3553 // Did not find an entry matching the given fieldname
3554 return PERSIST_DEL_KEY_ERROR_NO_FIELD;
3555 }
3556}
3557
3558static int persist_count_keys(const char *fieldname)
3559{
3560 unsigned int i;
3561 unsigned int count;
3562
3563 if (persist_data == NULL) {
3564 return -1;
3565 }
3566
3567 count = 0;
3568 for (i = 0; i < persist_data->persist_valid_entries; i++) {
3569 if (match_multi_entry(persist_data->persist_entry[i].key, fieldname, 0)) {
3570 count++;
3571 }
3572 }
3573
3574 return count;
3575}
3576
Ken Sumrall160b4d62013-04-22 12:15:39 -07003577/* Return the value of the specified field. */
Rubin Xu85c01f92014-10-13 12:49:54 +01003578int cryptfs_getfield(const char *fieldname, char *value, int len)
Ken Sumrall160b4d62013-04-22 12:15:39 -07003579{
3580 char temp_value[PROPERTY_VALUE_MAX];
Rubin Xu85c01f92014-10-13 12:49:54 +01003581 /* CRYPTO_GETFIELD_OK is success,
3582 * CRYPTO_GETFIELD_ERROR_NO_FIELD is value not set,
3583 * CRYPTO_GETFIELD_ERROR_BUF_TOO_SMALL is buffer (as given by len) too small,
3584 * CRYPTO_GETFIELD_ERROR_OTHER is any other error
Ken Sumrall160b4d62013-04-22 12:15:39 -07003585 */
Rubin Xu85c01f92014-10-13 12:49:54 +01003586 int rc = CRYPTO_GETFIELD_ERROR_OTHER;
3587 int i;
3588 char temp_field[PROPERTY_KEY_MAX];
Ken Sumrall160b4d62013-04-22 12:15:39 -07003589
3590 if (persist_data == NULL) {
3591 load_persistent_data();
3592 if (persist_data == NULL) {
3593 SLOGE("Getfield error, cannot load persistent data");
3594 goto out;
3595 }
3596 }
3597
Rubin Xu85c01f92014-10-13 12:49:54 +01003598 // Read value from persistent entries. If the original value is split into multiple entries,
3599 // stitch them back together.
Ken Sumrall160b4d62013-04-22 12:15:39 -07003600 if (!persist_get_key(fieldname, temp_value)) {
Rubin Xu85c01f92014-10-13 12:49:54 +01003601 // We found it, copy it to the caller's buffer and keep going until all entries are read.
3602 if (strlcpy(value, temp_value, len) >= (unsigned) len) {
3603 // value too small
3604 rc = CRYPTO_GETFIELD_ERROR_BUF_TOO_SMALL;
3605 goto out;
3606 }
3607 rc = CRYPTO_GETFIELD_OK;
3608
3609 for (i = 1; /* break explicitly */; i++) {
3610 if (snprintf(temp_field, sizeof(temp_field), "%s_%d", fieldname, i) >=
3611 (int) sizeof(temp_field)) {
3612 // If the fieldname is very long, we stop as soon as it begins to overflow the
3613 // maximum field length. At this point we have in fact fully read out the original
3614 // value because cryptfs_setfield would not allow fields with longer names to be
3615 // written in the first place.
3616 break;
3617 }
3618 if (!persist_get_key(temp_field, temp_value)) {
3619 if (strlcat(value, temp_value, len) >= (unsigned)len) {
3620 // value too small.
3621 rc = CRYPTO_GETFIELD_ERROR_BUF_TOO_SMALL;
3622 goto out;
3623 }
3624 } else {
3625 // Exhaust all entries.
3626 break;
3627 }
3628 }
Ken Sumrall160b4d62013-04-22 12:15:39 -07003629 } else {
3630 /* Sadness, it's not there. Return the error */
Rubin Xu85c01f92014-10-13 12:49:54 +01003631 rc = CRYPTO_GETFIELD_ERROR_NO_FIELD;
Ken Sumrall160b4d62013-04-22 12:15:39 -07003632 }
3633
3634out:
3635 return rc;
3636}
3637
3638/* Set the value of the specified field. */
Rubin Xu85c01f92014-10-13 12:49:54 +01003639int cryptfs_setfield(const char *fieldname, const char *value)
Ken Sumrall160b4d62013-04-22 12:15:39 -07003640{
Ken Sumrall160b4d62013-04-22 12:15:39 -07003641 char encrypted_state[PROPERTY_VALUE_MAX];
Rubin Xu85c01f92014-10-13 12:49:54 +01003642 /* 0 is success, negative values are error */
3643 int rc = CRYPTO_SETFIELD_ERROR_OTHER;
Ken Sumrall160b4d62013-04-22 12:15:39 -07003644 int encrypted = 0;
Rubin Xu85c01f92014-10-13 12:49:54 +01003645 unsigned int field_id;
3646 char temp_field[PROPERTY_KEY_MAX];
3647 unsigned int num_entries;
3648 unsigned int max_keylen;
Ken Sumrall160b4d62013-04-22 12:15:39 -07003649
3650 if (persist_data == NULL) {
3651 load_persistent_data();
3652 if (persist_data == NULL) {
3653 SLOGE("Setfield error, cannot load persistent data");
3654 goto out;
3655 }
3656 }
3657
3658 property_get("ro.crypto.state", encrypted_state, "");
3659 if (!strcmp(encrypted_state, "encrypted") ) {
3660 encrypted = 1;
3661 }
3662
Rubin Xu85c01f92014-10-13 12:49:54 +01003663 // Compute the number of entries required to store value, each entry can store up to
3664 // (PROPERTY_VALUE_MAX - 1) chars
3665 if (strlen(value) == 0) {
3666 // Empty value also needs one entry to store.
3667 num_entries = 1;
3668 } else {
3669 num_entries = (strlen(value) + (PROPERTY_VALUE_MAX - 1) - 1) / (PROPERTY_VALUE_MAX - 1);
3670 }
3671
3672 max_keylen = strlen(fieldname);
3673 if (num_entries > 1) {
3674 // Need an extra "_%d" suffix.
3675 max_keylen += 1 + log10(num_entries);
3676 }
3677 if (max_keylen > PROPERTY_KEY_MAX - 1) {
3678 rc = CRYPTO_SETFIELD_ERROR_FIELD_TOO_LONG;
Ken Sumrall160b4d62013-04-22 12:15:39 -07003679 goto out;
3680 }
3681
Rubin Xu85c01f92014-10-13 12:49:54 +01003682 // Make sure we have enough space to write the new value
3683 if (persist_data->persist_valid_entries + num_entries - persist_count_keys(fieldname) >
3684 persist_get_max_entries(encrypted)) {
3685 rc = CRYPTO_SETFIELD_ERROR_VALUE_TOO_LONG;
3686 goto out;
3687 }
3688
3689 // Now that we know persist_data has enough space for value, let's delete the old field first
3690 // to make up space.
3691 persist_del_keys(fieldname, 0);
3692
3693 if (persist_set_key(fieldname, value, encrypted)) {
3694 // fail to set key, should not happen as we have already checked the available space
3695 SLOGE("persist_set_key() error during setfield()");
3696 goto out;
3697 }
3698
3699 for (field_id = 1; field_id < num_entries; field_id++) {
3700 snprintf(temp_field, sizeof(temp_field), "%s_%d", fieldname, field_id);
3701
3702 if (persist_set_key(temp_field, value + field_id * (PROPERTY_VALUE_MAX - 1), encrypted)) {
3703 // fail to set key, should not happen as we have already checked the available space.
3704 SLOGE("persist_set_key() error during setfield()");
3705 goto out;
3706 }
3707 }
3708
Ken Sumrall160b4d62013-04-22 12:15:39 -07003709 /* If we are running encrypted, save the persistent data now */
3710 if (encrypted) {
3711 if (save_persistent_data()) {
3712 SLOGE("Setfield error, cannot save persistent data");
3713 goto out;
3714 }
3715 }
3716
Rubin Xu85c01f92014-10-13 12:49:54 +01003717 rc = CRYPTO_SETFIELD_OK;
Ken Sumrall160b4d62013-04-22 12:15:39 -07003718
3719out:
3720 return rc;
3721}
Paul Lawrencef4faa572014-01-29 13:31:03 -08003722
3723/* Checks userdata. Attempt to mount the volume if default-
3724 * encrypted.
3725 * On success trigger next init phase and return 0.
3726 * Currently do not handle failure - see TODO below.
3727 */
3728int cryptfs_mount_default_encrypted(void)
3729{
3730 char decrypt_state[PROPERTY_VALUE_MAX];
3731 property_get("vold.decrypt", decrypt_state, "0");
3732 if (!strcmp(decrypt_state, "0")) {
3733 SLOGE("Not encrypted - should not call here");
3734 } else {
3735 int crypt_type = cryptfs_get_password_type();
3736 if (crypt_type < 0 || crypt_type > CRYPT_TYPE_MAX_TYPE) {
3737 SLOGE("Bad crypt type - error");
3738 } else if (crypt_type != CRYPT_TYPE_DEFAULT) {
3739 SLOGD("Password is not default - "
3740 "starting min framework to prompt");
3741 property_set("vold.decrypt", "trigger_restart_min_framework");
3742 return 0;
3743 } else if (cryptfs_check_passwd(DEFAULT_PASSWORD) == 0) {
3744 SLOGD("Password is default - restarting filesystem");
3745 cryptfs_restart_internal(0);
3746 return 0;
3747 } else {
3748 SLOGE("Encrypted, default crypt type but can't decrypt");
3749 }
3750 }
3751
Paul Lawrence6bfed202014-07-28 12:47:22 -07003752 /** Corrupt. Allow us to boot into framework, which will detect bad
3753 crypto when it calls do_crypto_complete, then do a factory reset
Paul Lawrencef4faa572014-01-29 13:31:03 -08003754 */
Paul Lawrence6bfed202014-07-28 12:47:22 -07003755 property_set("vold.decrypt", "trigger_restart_min_framework");
Paul Lawrencef4faa572014-01-29 13:31:03 -08003756 return 0;
3757}
3758
3759/* Returns type of the password, default, pattern, pin or password.
3760 */
3761int cryptfs_get_password_type(void)
3762{
Paul Lawrence8175a0b2015-03-05 09:46:23 -08003763 if (e4crypt_crypto_complete(DATA_MNT_POINT) == 0) {
3764 return e4crypt_get_password_type(DATA_MNT_POINT);
3765 }
3766
Paul Lawrencef4faa572014-01-29 13:31:03 -08003767 struct crypt_mnt_ftr crypt_ftr;
3768
3769 if (get_crypt_ftr_and_key(&crypt_ftr)) {
3770 SLOGE("Error getting crypt footer and key\n");
3771 return -1;
3772 }
3773
Paul Lawrence6bfed202014-07-28 12:47:22 -07003774 if (crypt_ftr.flags & CRYPT_INCONSISTENT_STATE) {
3775 return -1;
3776 }
3777
Paul Lawrencef4faa572014-01-29 13:31:03 -08003778 return crypt_ftr.crypt_type;
3779}
Paul Lawrence684dbdf2014-02-07 12:07:22 -08003780
Paul Lawrence8175a0b2015-03-05 09:46:23 -08003781const char* cryptfs_get_password()
Paul Lawrence684dbdf2014-02-07 12:07:22 -08003782{
Paul Lawrence8175a0b2015-03-05 09:46:23 -08003783 if (e4crypt_crypto_complete(DATA_MNT_POINT) == 0) {
3784 return e4crypt_get_password(DATA_MNT_POINT);
3785 }
3786
Paul Lawrence399317e2014-03-10 13:20:50 -07003787 struct timespec now;
Paul Lawrenceef2b5be2014-11-11 12:47:03 -08003788 clock_gettime(CLOCK_BOOTTIME, &now);
Paul Lawrence399317e2014-03-10 13:20:50 -07003789 if (now.tv_sec < password_expiry_time) {
3790 return password;
3791 } else {
3792 cryptfs_clear_password();
3793 return 0;
3794 }
3795}
3796
3797void cryptfs_clear_password()
3798{
3799 if (password) {
3800 size_t len = strlen(password);
3801 memset(password, 0, len);
3802 free(password);
3803 password = 0;
3804 password_expiry_time = 0;
3805 }
Paul Lawrence684dbdf2014-02-07 12:07:22 -08003806}