blob: 88e0eadd2429d278e60478076ab5e4e1e8093400 [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 Lawrenceae59fe62014-01-21 08:23:27 -080056#include "ext4_utils.h"
Daniel Rosenberge82df162014-08-15 22:19:23 +000057#include "f2fs_sparseblock.h"
Paul Lawrence87999172014-02-20 12:21:31 -080058#include "CheckBattery.h"
jessica_yu3f14fe42014-09-22 15:57:40 +080059#include "Process.h"
Ken Sumrall8f869aa2010-12-03 03:47:09 -080060
Paul Lawrence69f4ebd2014-04-14 12:17:14 -070061#include <hardware/keymaster.h>
62
Mark Salyzyn3e971272014-01-21 13:27:04 -080063#define UNUSED __attribute__((unused))
64
Mark Salyzyn5eecc442014-02-12 14:16:14 -080065#define UNUSED __attribute__((unused))
66
Ajay Dudani87701e22014-09-17 21:02:52 -070067#ifdef CONFIG_HW_DISK_ENCRYPTION
68#include "cryptfs_hw.h"
69#endif
70
Ken Sumrall8f869aa2010-12-03 03:47:09 -080071#define DM_CRYPT_BUF_SIZE 4096
72
Jason parks70a4b3f2011-01-28 10:10:47 -060073#define HASH_COUNT 2000
74#define KEY_LEN_BYTES 16
75#define IV_LEN_BYTES 16
76
Ken Sumrall29d8da82011-05-18 17:20:07 -070077#define KEY_IN_FOOTER "footer"
78
Paul Lawrencef4faa572014-01-29 13:31:03 -080079// "default_password" encoded into hex (d=0x64 etc)
80#define DEFAULT_PASSWORD "64656661756c745f70617373776f7264"
81
Ken Sumrall29d8da82011-05-18 17:20:07 -070082#define EXT4_FS 1
JP Abgrall62c7af32014-06-16 13:01:23 -070083#define F2FS_FS 2
Ken Sumrall29d8da82011-05-18 17:20:07 -070084
Ken Sumralle919efe2012-09-29 17:07:41 -070085#define TABLE_LOAD_RETRIES 10
86
Shawn Willden47ba10d2014-09-03 17:07:06 -060087#define RSA_KEY_SIZE 2048
88#define RSA_KEY_SIZE_BYTES (RSA_KEY_SIZE / 8)
89#define RSA_EXPONENT 0x10001
Paul Lawrence69f4ebd2014-04-14 12:17:14 -070090
Paul Lawrence8e3f4512014-09-08 10:11:17 -070091#define RETRY_MOUNT_ATTEMPTS 10
92#define RETRY_MOUNT_DELAY_SECONDS 1
93
Ken Sumrall8f869aa2010-12-03 03:47:09 -080094char *me = "cryptfs";
95
Jason parks70a4b3f2011-01-28 10:10:47 -060096static unsigned char saved_master_key[KEY_LEN_BYTES];
Ken Sumrall3ad90722011-10-04 20:38:29 -070097static char *saved_mount_point;
Jason parks70a4b3f2011-01-28 10:10:47 -060098static int master_key_saved = 0;
Ken Sumrall160b4d62013-04-22 12:15:39 -070099static struct crypt_persist_data *persist_data = NULL;
Ken Sumrall56ad03c2013-02-13 13:00:19 -0800100
Paul Lawrence69f4ebd2014-04-14 12:17:14 -0700101static int keymaster_init(keymaster_device_t **keymaster_dev)
102{
103 int rc;
104
105 const hw_module_t* mod;
106 rc = hw_get_module_by_class(KEYSTORE_HARDWARE_MODULE_ID, NULL, &mod);
107 if (rc) {
108 ALOGE("could not find any keystore module");
109 goto out;
110 }
111
112 rc = keymaster_open(mod, keymaster_dev);
113 if (rc) {
114 ALOGE("could not open keymaster device in %s (%s)",
115 KEYSTORE_HARDWARE_MODULE_ID, strerror(-rc));
116 goto out;
117 }
118
119 return 0;
120
121out:
122 *keymaster_dev = NULL;
123 return rc;
124}
125
126/* Should we use keymaster? */
127static int keymaster_check_compatibility()
128{
129 keymaster_device_t *keymaster_dev = 0;
130 int rc = 0;
131
132 if (keymaster_init(&keymaster_dev)) {
133 SLOGE("Failed to init keymaster");
134 rc = -1;
135 goto out;
136 }
137
Paul Lawrence8c008392014-05-06 14:02:48 -0700138 SLOGI("keymaster version is %d", keymaster_dev->common.module->module_api_version);
139
140 if (keymaster_dev->common.module->module_api_version
141 < KEYMASTER_MODULE_API_VERSION_0_3) {
142 rc = 0;
143 goto out;
144 }
145
Shawn Willden7c49ab02014-10-30 08:12:32 -0600146 if (!(keymaster_dev->flags & KEYMASTER_SOFTWARE_ONLY) &&
147 (keymaster_dev->flags & KEYMASTER_BLOBS_ARE_STANDALONE)) {
Paul Lawrence69f4ebd2014-04-14 12:17:14 -0700148 rc = 1;
149 }
150
151out:
152 keymaster_close(keymaster_dev);
153 return rc;
154}
155
156/* Create a new keymaster key and store it in this footer */
157static int keymaster_create_key(struct crypt_mnt_ftr *ftr)
158{
159 uint8_t* key = 0;
160 keymaster_device_t *keymaster_dev = 0;
161
162 if (keymaster_init(&keymaster_dev)) {
163 SLOGE("Failed to init keymaster");
164 return -1;
165 }
166
167 int rc = 0;
168
169 keymaster_rsa_keygen_params_t params;
170 memset(&params, '\0', sizeof(params));
Shawn Willden47ba10d2014-09-03 17:07:06 -0600171 params.public_exponent = RSA_EXPONENT;
172 params.modulus_size = RSA_KEY_SIZE;
Paul Lawrence69f4ebd2014-04-14 12:17:14 -0700173
174 size_t key_size;
175 if (keymaster_dev->generate_keypair(keymaster_dev, TYPE_RSA, &params,
176 &key, &key_size)) {
177 SLOGE("Failed to generate keypair");
178 rc = -1;
179 goto out;
180 }
181
182 if (key_size > KEYMASTER_BLOB_SIZE) {
183 SLOGE("Keymaster key too large for crypto footer");
184 rc = -1;
185 goto out;
186 }
187
188 memcpy(ftr->keymaster_blob, key, key_size);
189 ftr->keymaster_blob_size = key_size;
190
191out:
192 keymaster_close(keymaster_dev);
193 free(key);
194 return rc;
195}
196
Shawn Willdene17a9c42014-09-08 13:04:08 -0600197/* This signs the given object using the keymaster key. */
198static int keymaster_sign_object(struct crypt_mnt_ftr *ftr,
Shawn Willden47ba10d2014-09-03 17:07:06 -0600199 const unsigned char *object,
200 const size_t object_size,
201 unsigned char **signature,
202 size_t *signature_size)
203{
204 int rc = 0;
205 keymaster_device_t *keymaster_dev = 0;
206 if (keymaster_init(&keymaster_dev)) {
207 SLOGE("Failed to init keymaster");
208 return -1;
209 }
210
211 /* We currently set the digest type to DIGEST_NONE because it's the
212 * only supported value for keymaster. A similar issue exists with
213 * PADDING_NONE. Long term both of these should likely change.
214 */
215 keymaster_rsa_sign_params_t params;
216 params.digest_type = DIGEST_NONE;
217 params.padding_type = PADDING_NONE;
218
219 unsigned char to_sign[RSA_KEY_SIZE_BYTES];
Shawn Willdene17a9c42014-09-08 13:04:08 -0600220 size_t to_sign_size = sizeof(to_sign);
Shawn Willden47ba10d2014-09-03 17:07:06 -0600221 memset(to_sign, 0, RSA_KEY_SIZE_BYTES);
Shawn Willden47ba10d2014-09-03 17:07:06 -0600222
Shawn Willdene17a9c42014-09-08 13:04:08 -0600223 // To sign a message with RSA, the message must satisfy two
224 // constraints:
225 //
226 // 1. The message, when interpreted as a big-endian numeric value, must
227 // be strictly less than the public modulus of the RSA key. Note
228 // that because the most significant bit of the public modulus is
229 // guaranteed to be 1 (else it's an (n-1)-bit key, not an n-bit
230 // key), an n-bit message with most significant bit 0 always
231 // satisfies this requirement.
232 //
233 // 2. The message must have the same length in bits as the public
234 // modulus of the RSA key. This requirement isn't mathematically
235 // necessary, but is necessary to ensure consistency in
236 // implementations.
237 switch (ftr->kdf_type) {
238 case KDF_SCRYPT_KEYMASTER_UNPADDED:
239 // This is broken: It produces a message which is shorter than
240 // the public modulus, failing criterion 2.
241 memcpy(to_sign, object, object_size);
242 to_sign_size = object_size;
243 SLOGI("Signing unpadded object");
244 break;
245 case KDF_SCRYPT_KEYMASTER_BADLY_PADDED:
246 // This is broken: Since the value of object is uniformly
247 // distributed, it produces a message that is larger than the
248 // public modulus with probability 0.25.
249 memcpy(to_sign, object, min(RSA_KEY_SIZE_BYTES, object_size));
250 SLOGI("Signing end-padded object");
251 break;
252 case KDF_SCRYPT_KEYMASTER:
253 // This ensures the most significant byte of the signed message
254 // is zero. We could have zero-padded to the left instead, but
255 // this approach is slightly more robust against changes in
256 // object size. However, it's still broken (but not unusably
257 // so) because we really should be using a proper RSA padding
258 // function, such as OAEP.
259 //
260 // TODO(paullawrence): When keymaster 0.4 is available, change
261 // this to use the padding options it provides.
262 memcpy(to_sign + 1, object, min(RSA_KEY_SIZE_BYTES - 1, object_size));
263 SLOGI("Signing safely-padded object");
264 break;
265 default:
266 SLOGE("Unknown KDF type %d", ftr->kdf_type);
267 return -1;
268 }
269
Shawn Willden47ba10d2014-09-03 17:07:06 -0600270 rc = keymaster_dev->sign_data(keymaster_dev,
271 &params,
272 ftr->keymaster_blob,
273 ftr->keymaster_blob_size,
274 to_sign,
Shawn Willdene17a9c42014-09-08 13:04:08 -0600275 to_sign_size,
Shawn Willden47ba10d2014-09-03 17:07:06 -0600276 signature,
277 signature_size);
278
279 keymaster_close(keymaster_dev);
280 return rc;
281}
282
Paul Lawrence399317e2014-03-10 13:20:50 -0700283/* Store password when userdata is successfully decrypted and mounted.
284 * Cleared by cryptfs_clear_password
285 *
286 * To avoid a double prompt at boot, we need to store the CryptKeeper
287 * password and pass it to KeyGuard, which uses it to unlock KeyStore.
288 * Since the entire framework is torn down and rebuilt after encryption,
289 * we have to use a daemon or similar to store the password. Since vold
290 * is secured against IPC except from system processes, it seems a reasonable
291 * place to store this.
292 *
293 * password should be cleared once it has been used.
294 *
295 * password is aged out after password_max_age_seconds seconds.
Paul Lawrence684dbdf2014-02-07 12:07:22 -0800296 */
Paul Lawrence399317e2014-03-10 13:20:50 -0700297static char* password = 0;
298static int password_expiry_time = 0;
299static const int password_max_age_seconds = 60;
Paul Lawrence684dbdf2014-02-07 12:07:22 -0800300
Ken Sumrall56ad03c2013-02-13 13:00:19 -0800301extern struct fstab *fstab;
Ken Sumrall8ddbe402011-01-17 15:26:29 -0800302
Paul Lawrence87999172014-02-20 12:21:31 -0800303enum RebootType {reboot, recovery, shutdown};
304static void cryptfs_reboot(enum RebootType rt)
Ken Sumralladfba362013-06-04 16:37:52 -0700305{
Paul Lawrence87999172014-02-20 12:21:31 -0800306 switch(rt) {
307 case reboot:
308 property_set(ANDROID_RB_PROPERTY, "reboot");
309 break;
310
311 case recovery:
312 property_set(ANDROID_RB_PROPERTY, "reboot,recovery");
313 break;
314
315 case shutdown:
316 property_set(ANDROID_RB_PROPERTY, "shutdown");
317 break;
Ken Sumralladfba362013-06-04 16:37:52 -0700318 }
Paul Lawrence87999172014-02-20 12:21:31 -0800319
Ken Sumralladfba362013-06-04 16:37:52 -0700320 sleep(20);
321
322 /* Shouldn't get here, reboot should happen before sleep times out */
323 return;
324}
325
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800326static void ioctl_init(struct dm_ioctl *io, size_t dataSize, const char *name, unsigned flags)
327{
328 memset(io, 0, dataSize);
329 io->data_size = dataSize;
330 io->data_start = sizeof(struct dm_ioctl);
331 io->version[0] = 4;
332 io->version[1] = 0;
333 io->version[2] = 0;
334 io->flags = flags;
335 if (name) {
336 strncpy(io->name, name, sizeof(io->name));
337 }
338}
339
Kenny Rootc4c70f12013-06-14 12:11:38 -0700340/**
341 * Gets the default device scrypt parameters for key derivation time tuning.
342 * The parameters should lead to about one second derivation time for the
343 * given device.
344 */
345static void get_device_scrypt_params(struct crypt_mnt_ftr *ftr) {
346 const int default_params[] = SCRYPT_DEFAULTS;
347 int params[] = SCRYPT_DEFAULTS;
348 char paramstr[PROPERTY_VALUE_MAX];
349 char *token;
350 char *saveptr;
351 int i;
352
353 property_get(SCRYPT_PROP, paramstr, "");
354 if (paramstr[0] != '\0') {
355 /*
356 * The token we're looking for should be three integers separated by
357 * colons (e.g., "12:8:1"). Scan the property to make sure it matches.
358 */
Kenny Root2947e342013-08-14 15:54:49 -0700359 for (i = 0, token = strtok_r(paramstr, ":", &saveptr);
360 token != NULL && i < 3;
Kenny Rootc4c70f12013-06-14 12:11:38 -0700361 i++, token = strtok_r(NULL, ":", &saveptr)) {
362 char *endptr;
363 params[i] = strtol(token, &endptr, 10);
364
365 /*
366 * Check that there was a valid number and it's 8-bit. If not,
367 * break out and the end check will take the default values.
368 */
369 if ((*token == '\0') || (*endptr != '\0') || params[i] < 0 || params[i] > 255) {
370 break;
371 }
372 }
373
374 /*
375 * If there were not enough tokens or a token was malformed (not an
376 * integer), it will end up here and the default parameters can be
377 * taken.
378 */
379 if ((i != 3) || (token != NULL)) {
380 SLOGW("bad scrypt parameters '%s' should be like '12:8:1'; using defaults", paramstr);
381 memcpy(params, default_params, sizeof(params));
382 }
383 }
384
385 ftr->N_factor = params[0];
386 ftr->r_factor = params[1];
387 ftr->p_factor = params[2];
388}
389
Ken Sumrall3ed82362011-01-28 23:31:16 -0800390static unsigned int get_fs_size(char *dev)
391{
392 int fd, block_size;
393 struct ext4_super_block sb;
394 off64_t len;
395
396 if ((fd = open(dev, O_RDONLY)) < 0) {
397 SLOGE("Cannot open device to get filesystem size ");
398 return 0;
399 }
400
401 if (lseek64(fd, 1024, SEEK_SET) < 0) {
402 SLOGE("Cannot seek to superblock");
403 return 0;
404 }
405
406 if (read(fd, &sb, sizeof(sb)) != sizeof(sb)) {
407 SLOGE("Cannot read superblock");
408 return 0;
409 }
410
411 close(fd);
412
Daniel Rosenberge82df162014-08-15 22:19:23 +0000413 if (le32_to_cpu(sb.s_magic) != EXT4_SUPER_MAGIC) {
414 SLOGE("Not a valid ext4 superblock");
415 return 0;
416 }
Ken Sumrall3ed82362011-01-28 23:31:16 -0800417 block_size = 1024 << sb.s_log_block_size;
418 /* compute length in bytes */
419 len = ( ((off64_t)sb.s_blocks_count_hi << 32) + sb.s_blocks_count_lo) * block_size;
420
421 /* return length in sectors */
422 return (unsigned int) (len / 512);
423}
424
Ken Sumrall160b4d62013-04-22 12:15:39 -0700425static int get_crypt_ftr_info(char **metadata_fname, off64_t *off)
426{
427 static int cached_data = 0;
428 static off64_t cached_off = 0;
429 static char cached_metadata_fname[PROPERTY_VALUE_MAX] = "";
430 int fd;
431 char key_loc[PROPERTY_VALUE_MAX];
432 char real_blkdev[PROPERTY_VALUE_MAX];
433 unsigned int nr_sec;
434 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
445 if ((nr_sec = get_blkdev_size(fd))) {
446 /* If it's an encrypted Android partition, the last 16 Kbytes contain the
447 * encryption info footer and key, and plenty of bytes to spare for future
448 * growth.
449 */
450 strlcpy(cached_metadata_fname, real_blkdev, sizeof(cached_metadata_fname));
451 cached_off = ((off64_t)nr_sec * 512) - CRYPT_FOOTER_OFFSET;
452 cached_data = 1;
453 } else {
454 SLOGE("Cannot get size of block device %s\n", real_blkdev);
455 }
456 close(fd);
457 } else {
458 strlcpy(cached_metadata_fname, key_loc, sizeof(cached_metadata_fname));
459 cached_off = 0;
460 cached_data = 1;
461 }
462 }
463
464 if (cached_data) {
465 if (metadata_fname) {
466 *metadata_fname = cached_metadata_fname;
467 }
468 if (off) {
469 *off = cached_off;
470 }
471 rc = 0;
472 }
473
474 return rc;
475}
476
Ken Sumralle8744072011-01-18 22:01:55 -0800477/* key or salt can be NULL, in which case just skip writing that value. Useful to
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800478 * update the failed mount count but not change the key.
479 */
Ken Sumrall160b4d62013-04-22 12:15:39 -0700480static int put_crypt_ftr_and_key(struct crypt_mnt_ftr *crypt_ftr)
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800481{
482 int fd;
Tim Murray8439dc92014-12-15 11:56:11 -0800483 unsigned int cnt;
Ken Sumrall160b4d62013-04-22 12:15:39 -0700484 /* starting_off is set to the SEEK_SET offset
485 * where the crypto structure starts
486 */
487 off64_t starting_off;
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800488 int rc = -1;
Ken Sumrall160b4d62013-04-22 12:15:39 -0700489 char *fname = NULL;
Ken Sumrall3be890f2011-09-14 16:53:46 -0700490 struct stat statbuf;
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800491
Ken Sumrall160b4d62013-04-22 12:15:39 -0700492 if (get_crypt_ftr_info(&fname, &starting_off)) {
493 SLOGE("Unable to get crypt_ftr_info\n");
494 return -1;
495 }
496 if (fname[0] != '/') {
Ken Sumralle5032c42012-04-01 23:58:44 -0700497 SLOGE("Unexpected value for crypto key location\n");
Ken Sumrall160b4d62013-04-22 12:15:39 -0700498 return -1;
499 }
Ken Sumralle550f782013-08-20 13:48:23 -0700500 if ( (fd = open(fname, O_RDWR | O_CREAT, 0600)) < 0) {
501 SLOGE("Cannot open footer file %s for put\n", fname);
Ken Sumrall160b4d62013-04-22 12:15:39 -0700502 return -1;
503 }
504
505 /* Seek to the start of the crypt footer */
506 if (lseek64(fd, starting_off, SEEK_SET) == -1) {
507 SLOGE("Cannot seek to real block device footer\n");
508 goto errout;
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800509 }
510
511 if ((cnt = write(fd, crypt_ftr, sizeof(struct crypt_mnt_ftr))) != sizeof(struct crypt_mnt_ftr)) {
512 SLOGE("Cannot write real block device footer\n");
513 goto errout;
514 }
515
Ken Sumrall3be890f2011-09-14 16:53:46 -0700516 fstat(fd, &statbuf);
517 /* If the keys are kept on a raw block device, do not try to truncate it. */
Ken Sumralle550f782013-08-20 13:48:23 -0700518 if (S_ISREG(statbuf.st_mode)) {
Ken Sumrall29d8da82011-05-18 17:20:07 -0700519 if (ftruncate(fd, 0x4000)) {
Colin Cross59846b62014-02-06 20:34:29 -0800520 SLOGE("Cannot set footer file size\n");
Ken Sumralle8744072011-01-18 22:01:55 -0800521 goto errout;
522 }
523 }
524
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800525 /* Success! */
526 rc = 0;
527
528errout:
529 close(fd);
530 return rc;
531
532}
533
Ken Sumrall160b4d62013-04-22 12:15:39 -0700534static inline int unix_read(int fd, void* buff, int len)
535{
536 return TEMP_FAILURE_RETRY(read(fd, buff, len));
537}
538
539static inline int unix_write(int fd, const void* buff, int len)
540{
541 return TEMP_FAILURE_RETRY(write(fd, buff, len));
542}
543
544static void init_empty_persist_data(struct crypt_persist_data *pdata, int len)
545{
546 memset(pdata, 0, len);
547 pdata->persist_magic = PERSIST_DATA_MAGIC;
548 pdata->persist_valid_entries = 0;
549}
550
551/* A routine to update the passed in crypt_ftr to the lastest version.
552 * fd is open read/write on the device that holds the crypto footer and persistent
553 * data, crypt_ftr is a pointer to the struct to be updated, and offset is the
554 * absolute offset to the start of the crypt_mnt_ftr on the passed in fd.
555 */
556static void upgrade_crypt_ftr(int fd, struct crypt_mnt_ftr *crypt_ftr, off64_t offset)
557{
Kenny Root7434b312013-06-14 11:29:53 -0700558 int orig_major = crypt_ftr->major_version;
559 int orig_minor = crypt_ftr->minor_version;
Ken Sumrall160b4d62013-04-22 12:15:39 -0700560
Kenny Root7434b312013-06-14 11:29:53 -0700561 if ((crypt_ftr->major_version == 1) && (crypt_ftr->minor_version == 0)) {
562 struct crypt_persist_data *pdata;
563 off64_t pdata_offset = offset + CRYPT_FOOTER_TO_PERSIST_OFFSET;
Ken Sumrall160b4d62013-04-22 12:15:39 -0700564
Kenny Rootc4c70f12013-06-14 12:11:38 -0700565 SLOGW("upgrading crypto footer to 1.1");
566
Kenny Root7434b312013-06-14 11:29:53 -0700567 pdata = malloc(CRYPT_PERSIST_DATA_SIZE);
568 if (pdata == NULL) {
569 SLOGE("Cannot allocate persisent data\n");
570 return;
571 }
572 memset(pdata, 0, CRYPT_PERSIST_DATA_SIZE);
573
574 /* Need to initialize the persistent data area */
575 if (lseek64(fd, pdata_offset, SEEK_SET) == -1) {
576 SLOGE("Cannot seek to persisent data offset\n");
577 return;
578 }
579 /* Write all zeros to the first copy, making it invalid */
580 unix_write(fd, pdata, CRYPT_PERSIST_DATA_SIZE);
581
582 /* Write a valid but empty structure to the second copy */
583 init_empty_persist_data(pdata, CRYPT_PERSIST_DATA_SIZE);
584 unix_write(fd, pdata, CRYPT_PERSIST_DATA_SIZE);
585
586 /* Update the footer */
587 crypt_ftr->persist_data_size = CRYPT_PERSIST_DATA_SIZE;
588 crypt_ftr->persist_data_offset[0] = pdata_offset;
589 crypt_ftr->persist_data_offset[1] = pdata_offset + CRYPT_PERSIST_DATA_SIZE;
590 crypt_ftr->minor_version = 1;
Ken Sumrall160b4d62013-04-22 12:15:39 -0700591 }
592
Paul Lawrencef4faa572014-01-29 13:31:03 -0800593 if ((crypt_ftr->major_version == 1) && (crypt_ftr->minor_version == 1)) {
Kenny Rootc4c70f12013-06-14 12:11:38 -0700594 SLOGW("upgrading crypto footer to 1.2");
JP Abgrall7bdfa522013-11-15 13:42:56 -0800595 /* But keep the old kdf_type.
596 * It will get updated later to KDF_SCRYPT after the password has been verified.
597 */
Kenny Rootc4c70f12013-06-14 12:11:38 -0700598 crypt_ftr->kdf_type = KDF_PBKDF2;
599 get_device_scrypt_params(crypt_ftr);
600 crypt_ftr->minor_version = 2;
601 }
602
Paul Lawrencef4faa572014-01-29 13:31:03 -0800603 if ((crypt_ftr->major_version == 1) && (crypt_ftr->minor_version == 2)) {
604 SLOGW("upgrading crypto footer to 1.3");
605 crypt_ftr->crypt_type = CRYPT_TYPE_PASSWORD;
606 crypt_ftr->minor_version = 3;
607 }
608
Kenny Root7434b312013-06-14 11:29:53 -0700609 if ((orig_major != crypt_ftr->major_version) || (orig_minor != crypt_ftr->minor_version)) {
610 if (lseek64(fd, offset, SEEK_SET) == -1) {
611 SLOGE("Cannot seek to crypt footer\n");
612 return;
613 }
614 unix_write(fd, crypt_ftr, sizeof(struct crypt_mnt_ftr));
Ken Sumrall160b4d62013-04-22 12:15:39 -0700615 }
Ken Sumrall160b4d62013-04-22 12:15:39 -0700616}
617
618
619static int get_crypt_ftr_and_key(struct crypt_mnt_ftr *crypt_ftr)
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800620{
621 int fd;
Tim Murray8439dc92014-12-15 11:56:11 -0800622 unsigned int cnt;
Ken Sumrall160b4d62013-04-22 12:15:39 -0700623 off64_t starting_off;
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800624 int rc = -1;
Ken Sumrall160b4d62013-04-22 12:15:39 -0700625 char *fname = NULL;
Ken Sumrall29d8da82011-05-18 17:20:07 -0700626 struct stat statbuf;
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800627
Ken Sumrall160b4d62013-04-22 12:15:39 -0700628 if (get_crypt_ftr_info(&fname, &starting_off)) {
629 SLOGE("Unable to get crypt_ftr_info\n");
630 return -1;
631 }
632 if (fname[0] != '/') {
Ken Sumralle5032c42012-04-01 23:58:44 -0700633 SLOGE("Unexpected value for crypto key location\n");
Ken Sumrall160b4d62013-04-22 12:15:39 -0700634 return -1;
635 }
636 if ( (fd = open(fname, O_RDWR)) < 0) {
Ken Sumralle550f782013-08-20 13:48:23 -0700637 SLOGE("Cannot open footer file %s for get\n", fname);
Ken Sumrall160b4d62013-04-22 12:15:39 -0700638 return -1;
639 }
640
641 /* Make sure it's 16 Kbytes in length */
642 fstat(fd, &statbuf);
643 if (S_ISREG(statbuf.st_mode) && (statbuf.st_size != 0x4000)) {
644 SLOGE("footer file %s is not the expected size!\n", fname);
645 goto errout;
646 }
647
648 /* Seek to the start of the crypt footer */
649 if (lseek64(fd, starting_off, SEEK_SET) == -1) {
650 SLOGE("Cannot seek to real block device footer\n");
651 goto errout;
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800652 }
653
654 if ( (cnt = read(fd, crypt_ftr, sizeof(struct crypt_mnt_ftr))) != sizeof(struct crypt_mnt_ftr)) {
655 SLOGE("Cannot read real block device footer\n");
656 goto errout;
657 }
658
659 if (crypt_ftr->magic != CRYPT_MNT_MAGIC) {
Ken Sumrall29d8da82011-05-18 17:20:07 -0700660 SLOGE("Bad magic for real block device %s\n", fname);
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800661 goto errout;
662 }
663
Kenny Rootc96a5f82013-06-14 12:08:28 -0700664 if (crypt_ftr->major_version != CURRENT_MAJOR_VERSION) {
665 SLOGE("Cannot understand major version %d real block device footer; expected %d\n",
666 crypt_ftr->major_version, CURRENT_MAJOR_VERSION);
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800667 goto errout;
668 }
669
Kenny Rootc96a5f82013-06-14 12:08:28 -0700670 if (crypt_ftr->minor_version > CURRENT_MINOR_VERSION) {
671 SLOGW("Warning: crypto footer minor version %d, expected <= %d, continuing...\n",
672 crypt_ftr->minor_version, CURRENT_MINOR_VERSION);
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800673 }
674
Ken Sumrall160b4d62013-04-22 12:15:39 -0700675 /* If this is a verion 1.0 crypt_ftr, make it a 1.1 crypt footer, and update the
676 * copy on disk before returning.
677 */
Kenny Rootc96a5f82013-06-14 12:08:28 -0700678 if (crypt_ftr->minor_version < CURRENT_MINOR_VERSION) {
Ken Sumrall160b4d62013-04-22 12:15:39 -0700679 upgrade_crypt_ftr(fd, crypt_ftr, starting_off);
Ken Sumralle8744072011-01-18 22:01:55 -0800680 }
681
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800682 /* Success! */
683 rc = 0;
684
685errout:
686 close(fd);
687 return rc;
688}
689
Ken Sumrall160b4d62013-04-22 12:15:39 -0700690static int validate_persistent_data_storage(struct crypt_mnt_ftr *crypt_ftr)
691{
692 if (crypt_ftr->persist_data_offset[0] + crypt_ftr->persist_data_size >
693 crypt_ftr->persist_data_offset[1]) {
694 SLOGE("Crypt_ftr persist data regions overlap");
695 return -1;
696 }
697
698 if (crypt_ftr->persist_data_offset[0] >= crypt_ftr->persist_data_offset[1]) {
699 SLOGE("Crypt_ftr persist data region 0 starts after region 1");
700 return -1;
701 }
702
703 if (((crypt_ftr->persist_data_offset[1] + crypt_ftr->persist_data_size) -
704 (crypt_ftr->persist_data_offset[0] - CRYPT_FOOTER_TO_PERSIST_OFFSET)) >
705 CRYPT_FOOTER_OFFSET) {
706 SLOGE("Persistent data extends past crypto footer");
707 return -1;
708 }
709
710 return 0;
711}
712
713static int load_persistent_data(void)
714{
715 struct crypt_mnt_ftr crypt_ftr;
716 struct crypt_persist_data *pdata = NULL;
717 char encrypted_state[PROPERTY_VALUE_MAX];
718 char *fname;
719 int found = 0;
720 int fd;
721 int ret;
722 int i;
723
724 if (persist_data) {
725 /* Nothing to do, we've already loaded or initialized it */
726 return 0;
727 }
728
729
730 /* If not encrypted, just allocate an empty table and initialize it */
731 property_get("ro.crypto.state", encrypted_state, "");
732 if (strcmp(encrypted_state, "encrypted") ) {
733 pdata = malloc(CRYPT_PERSIST_DATA_SIZE);
734 if (pdata) {
735 init_empty_persist_data(pdata, CRYPT_PERSIST_DATA_SIZE);
736 persist_data = pdata;
737 return 0;
738 }
739 return -1;
740 }
741
742 if(get_crypt_ftr_and_key(&crypt_ftr)) {
743 return -1;
744 }
745
Paul Lawrence8561b5c2014-03-17 14:10:51 -0700746 if ((crypt_ftr.major_version < 1)
747 || (crypt_ftr.major_version == 1 && crypt_ftr.minor_version < 1)) {
Ken Sumrall160b4d62013-04-22 12:15:39 -0700748 SLOGE("Crypt_ftr version doesn't support persistent data");
749 return -1;
750 }
751
752 if (get_crypt_ftr_info(&fname, NULL)) {
753 return -1;
754 }
755
756 ret = validate_persistent_data_storage(&crypt_ftr);
757 if (ret) {
758 return -1;
759 }
760
761 fd = open(fname, O_RDONLY);
762 if (fd < 0) {
763 SLOGE("Cannot open %s metadata file", fname);
764 return -1;
765 }
766
767 if (persist_data == NULL) {
768 pdata = malloc(crypt_ftr.persist_data_size);
769 if (pdata == NULL) {
770 SLOGE("Cannot allocate memory for persistent data");
771 goto err;
772 }
773 }
774
775 for (i = 0; i < 2; i++) {
776 if (lseek64(fd, crypt_ftr.persist_data_offset[i], SEEK_SET) < 0) {
777 SLOGE("Cannot seek to read persistent data on %s", fname);
778 goto err2;
779 }
780 if (unix_read(fd, pdata, crypt_ftr.persist_data_size) < 0){
781 SLOGE("Error reading persistent data on iteration %d", i);
782 goto err2;
783 }
784 if (pdata->persist_magic == PERSIST_DATA_MAGIC) {
785 found = 1;
786 break;
787 }
788 }
789
790 if (!found) {
791 SLOGI("Could not find valid persistent data, creating");
792 init_empty_persist_data(pdata, crypt_ftr.persist_data_size);
793 }
794
795 /* Success */
796 persist_data = pdata;
797 close(fd);
798 return 0;
799
800err2:
801 free(pdata);
802
803err:
804 close(fd);
805 return -1;
806}
807
808static int save_persistent_data(void)
809{
810 struct crypt_mnt_ftr crypt_ftr;
811 struct crypt_persist_data *pdata;
812 char *fname;
813 off64_t write_offset;
814 off64_t erase_offset;
Ken Sumrall160b4d62013-04-22 12:15:39 -0700815 int fd;
816 int ret;
817
818 if (persist_data == NULL) {
819 SLOGE("No persistent data to save");
820 return -1;
821 }
822
823 if(get_crypt_ftr_and_key(&crypt_ftr)) {
824 return -1;
825 }
826
Paul Lawrence8561b5c2014-03-17 14:10:51 -0700827 if ((crypt_ftr.major_version < 1)
828 || (crypt_ftr.major_version == 1 && crypt_ftr.minor_version < 1)) {
Ken Sumrall160b4d62013-04-22 12:15:39 -0700829 SLOGE("Crypt_ftr version doesn't support persistent data");
830 return -1;
831 }
832
833 ret = validate_persistent_data_storage(&crypt_ftr);
834 if (ret) {
835 return -1;
836 }
837
838 if (get_crypt_ftr_info(&fname, NULL)) {
839 return -1;
840 }
841
842 fd = open(fname, O_RDWR);
843 if (fd < 0) {
844 SLOGE("Cannot open %s metadata file", fname);
845 return -1;
846 }
847
848 pdata = malloc(crypt_ftr.persist_data_size);
849 if (pdata == NULL) {
850 SLOGE("Cannot allocate persistant data");
851 goto err;
852 }
853
854 if (lseek64(fd, crypt_ftr.persist_data_offset[0], SEEK_SET) < 0) {
855 SLOGE("Cannot seek to read persistent data on %s", fname);
856 goto err2;
857 }
858
859 if (unix_read(fd, pdata, crypt_ftr.persist_data_size) < 0) {
860 SLOGE("Error reading persistent data before save");
861 goto err2;
862 }
863
864 if (pdata->persist_magic == PERSIST_DATA_MAGIC) {
865 /* The first copy is the curent valid copy, so write to
866 * the second copy and erase this one */
867 write_offset = crypt_ftr.persist_data_offset[1];
868 erase_offset = crypt_ftr.persist_data_offset[0];
869 } else {
870 /* The second copy must be the valid copy, so write to
871 * the first copy, and erase the second */
872 write_offset = crypt_ftr.persist_data_offset[0];
873 erase_offset = crypt_ftr.persist_data_offset[1];
874 }
875
876 /* Write the new copy first, if successful, then erase the old copy */
877 if (lseek(fd, write_offset, SEEK_SET) < 0) {
878 SLOGE("Cannot seek to write persistent data");
879 goto err2;
880 }
881 if (unix_write(fd, persist_data, crypt_ftr.persist_data_size) ==
882 (int) crypt_ftr.persist_data_size) {
883 if (lseek(fd, erase_offset, SEEK_SET) < 0) {
884 SLOGE("Cannot seek to erase previous persistent data");
885 goto err2;
886 }
887 fsync(fd);
888 memset(pdata, 0, crypt_ftr.persist_data_size);
889 if (unix_write(fd, pdata, crypt_ftr.persist_data_size) !=
890 (int) crypt_ftr.persist_data_size) {
891 SLOGE("Cannot write to erase previous persistent data");
892 goto err2;
893 }
894 fsync(fd);
895 } else {
896 SLOGE("Cannot write to save persistent data");
897 goto err2;
898 }
899
900 /* Success */
901 free(pdata);
902 close(fd);
903 return 0;
904
905err2:
906 free(pdata);
907err:
908 close(fd);
909 return -1;
910}
911
Paul Lawrencef4faa572014-01-29 13:31:03 -0800912static int hexdigit (char c)
913{
914 if (c >= '0' && c <= '9') return c - '0';
915 c = tolower(c);
916 if (c >= 'a' && c <= 'f') return c - 'a' + 10;
917 return -1;
918}
919
920static unsigned char* convert_hex_ascii_to_key(const char* master_key_ascii,
921 unsigned int* out_keysize)
922{
923 unsigned int i;
924 *out_keysize = 0;
925
926 size_t size = strlen (master_key_ascii);
927 if (size % 2) {
928 SLOGE("Trying to convert ascii string of odd length");
929 return NULL;
930 }
931
932 unsigned char* master_key = (unsigned char*) malloc(size / 2);
933 if (master_key == 0) {
934 SLOGE("Cannot allocate");
935 return NULL;
936 }
937
938 for (i = 0; i < size; i += 2) {
939 int high_nibble = hexdigit (master_key_ascii[i]);
940 int low_nibble = hexdigit (master_key_ascii[i + 1]);
941
942 if(high_nibble < 0 || low_nibble < 0) {
943 SLOGE("Invalid hex string");
944 free (master_key);
945 return NULL;
946 }
947
948 master_key[*out_keysize] = high_nibble * 16 + low_nibble;
949 (*out_keysize)++;
950 }
951
952 return master_key;
953}
954
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800955/* Convert a binary key of specified length into an ascii hex string equivalent,
956 * without the leading 0x and with null termination
957 */
Paul Lawrencef4faa572014-01-29 13:31:03 -0800958static void convert_key_to_hex_ascii(unsigned char *master_key, unsigned int keysize,
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800959 char *master_key_ascii)
960{
961 unsigned int i, a;
962 unsigned char nibble;
963
964 for (i=0, a=0; i<keysize; i++, a+=2) {
965 /* For each byte, write out two ascii hex digits */
966 nibble = (master_key[i] >> 4) & 0xf;
967 master_key_ascii[a] = nibble + (nibble > 9 ? 0x37 : 0x30);
968
969 nibble = master_key[i] & 0xf;
970 master_key_ascii[a+1] = nibble + (nibble > 9 ? 0x37 : 0x30);
971 }
972
973 /* Add the null termination */
974 master_key_ascii[a] = '\0';
975
976}
977
Ken Sumralldb5e0262013-02-05 17:39:48 -0800978static int load_crypto_mapping_table(struct crypt_mnt_ftr *crypt_ftr, unsigned char *master_key,
979 char *real_blk_name, const char *name, int fd,
980 char *extra_params)
981{
Dan Albertc07fa3f2014-12-18 10:00:55 -0800982 _Alignas(struct dm_ioctl) char buffer[DM_CRYPT_BUF_SIZE];
Ken Sumralldb5e0262013-02-05 17:39:48 -0800983 struct dm_ioctl *io;
984 struct dm_target_spec *tgt;
985 char *crypt_params;
986 char master_key_ascii[129]; /* Large enough to hold 512 bit key and null */
987 int i;
988
989 io = (struct dm_ioctl *) buffer;
990
991 /* Load the mapping table for this device */
992 tgt = (struct dm_target_spec *) &buffer[sizeof(struct dm_ioctl)];
993
994 ioctl_init(io, DM_CRYPT_BUF_SIZE, name, 0);
995 io->target_count = 1;
996 tgt->status = 0;
997 tgt->sector_start = 0;
998 tgt->length = crypt_ftr->fs_size;
Ajay Dudani87701e22014-09-17 21:02:52 -0700999#ifdef CONFIG_HW_DISK_ENCRYPTION
Iliyan Malchevbb7d9af2014-11-20 18:42:23 -08001000 if (!strcmp((char *)crypt_ftr->crypto_type_name, "aes-xts")) {
1001 strlcpy(tgt->target_type, "req-crypt", DM_MAX_TYPE_NAME);
1002 }
1003 else {
1004 strlcpy(tgt->target_type, "crypt", DM_MAX_TYPE_NAME);
1005 }
Ajay Dudani87701e22014-09-17 21:02:52 -07001006#else
1007 strlcpy(tgt->target_type, "crypt", DM_MAX_TYPE_NAME);
1008#endif
Ken Sumralldb5e0262013-02-05 17:39:48 -08001009
1010 crypt_params = buffer + sizeof(struct dm_ioctl) + sizeof(struct dm_target_spec);
1011 convert_key_to_hex_ascii(master_key, crypt_ftr->keysize, master_key_ascii);
1012 sprintf(crypt_params, "%s %s 0 %s 0 %s", crypt_ftr->crypto_type_name,
1013 master_key_ascii, real_blk_name, extra_params);
1014 crypt_params += strlen(crypt_params) + 1;
1015 crypt_params = (char *) (((unsigned long)crypt_params + 7) & ~8); /* Align to an 8 byte boundary */
1016 tgt->next = crypt_params - buffer;
1017
1018 for (i = 0; i < TABLE_LOAD_RETRIES; i++) {
1019 if (! ioctl(fd, DM_TABLE_LOAD, io)) {
1020 break;
1021 }
1022 usleep(500000);
1023 }
1024
1025 if (i == TABLE_LOAD_RETRIES) {
1026 /* We failed to load the table, return an error */
1027 return -1;
1028 } else {
1029 return i + 1;
1030 }
1031}
1032
1033
1034static int get_dm_crypt_version(int fd, const char *name, int *version)
1035{
1036 char buffer[DM_CRYPT_BUF_SIZE];
1037 struct dm_ioctl *io;
1038 struct dm_target_versions *v;
Ken Sumralldb5e0262013-02-05 17:39:48 -08001039
1040 io = (struct dm_ioctl *) buffer;
1041
1042 ioctl_init(io, DM_CRYPT_BUF_SIZE, name, 0);
1043
1044 if (ioctl(fd, DM_LIST_VERSIONS, io)) {
1045 return -1;
1046 }
1047
1048 /* Iterate over the returned versions, looking for name of "crypt".
1049 * When found, get and return the version.
1050 */
1051 v = (struct dm_target_versions *) &buffer[sizeof(struct dm_ioctl)];
1052 while (v->next) {
Ajay Dudani87701e22014-09-17 21:02:52 -07001053#ifdef CONFIG_HW_DISK_ENCRYPTION
Iliyan Malchevbb7d9af2014-11-20 18:42:23 -08001054 if (! strcmp(v->name, "crypt") || ! strcmp(v->name, "req-crypt")) {
Ajay Dudani87701e22014-09-17 21:02:52 -07001055#else
Ken Sumralldb5e0262013-02-05 17:39:48 -08001056 if (! strcmp(v->name, "crypt")) {
Ajay Dudani87701e22014-09-17 21:02:52 -07001057#endif
Ken Sumralldb5e0262013-02-05 17:39:48 -08001058 /* We found the crypt driver, return the version, and get out */
1059 version[0] = v->version[0];
1060 version[1] = v->version[1];
1061 version[2] = v->version[2];
1062 return 0;
1063 }
1064 v = (struct dm_target_versions *)(((char *)v) + v->next);
1065 }
1066
1067 return -1;
1068}
1069
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001070static int create_crypto_blk_dev(struct crypt_mnt_ftr *crypt_ftr, unsigned char *master_key,
Ken Sumrall29d8da82011-05-18 17:20:07 -07001071 char *real_blk_name, char *crypto_blk_name, const char *name)
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001072{
1073 char buffer[DM_CRYPT_BUF_SIZE];
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001074 struct dm_ioctl *io;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001075 unsigned int minor;
Ajay Dudani87701e22014-09-17 21:02:52 -07001076 int fd=0;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001077 int retval = -1;
Ken Sumralldb5e0262013-02-05 17:39:48 -08001078 int version[3];
1079 char *extra_params;
1080 int load_count;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001081
1082 if ((fd = open("/dev/device-mapper", O_RDWR)) < 0 ) {
1083 SLOGE("Cannot open device-mapper\n");
1084 goto errout;
1085 }
1086
1087 io = (struct dm_ioctl *) buffer;
1088
1089 ioctl_init(io, DM_CRYPT_BUF_SIZE, name, 0);
1090 if (ioctl(fd, DM_DEV_CREATE, io)) {
1091 SLOGE("Cannot create dm-crypt device\n");
1092 goto errout;
1093 }
1094
1095 /* Get the device status, in particular, the name of it's device file */
1096 ioctl_init(io, DM_CRYPT_BUF_SIZE, name, 0);
1097 if (ioctl(fd, DM_DEV_STATUS, io)) {
1098 SLOGE("Cannot retrieve dm-crypt device status\n");
1099 goto errout;
1100 }
1101 minor = (io->dev & 0xff) | ((io->dev >> 12) & 0xfff00);
1102 snprintf(crypto_blk_name, MAXPATHLEN, "/dev/block/dm-%u", minor);
1103
Ken Sumralldb5e0262013-02-05 17:39:48 -08001104 extra_params = "";
1105 if (! get_dm_crypt_version(fd, name, version)) {
1106 /* Support for allow_discards was added in version 1.11.0 */
1107 if ((version[0] >= 2) ||
1108 ((version[0] == 1) && (version[1] >= 11))) {
1109 extra_params = "1 allow_discards";
1110 SLOGI("Enabling support for allow_discards in dmcrypt.\n");
1111 }
Ken Sumralle919efe2012-09-29 17:07:41 -07001112 }
1113
Ken Sumralldb5e0262013-02-05 17:39:48 -08001114 load_count = load_crypto_mapping_table(crypt_ftr, master_key, real_blk_name, name,
1115 fd, extra_params);
1116 if (load_count < 0) {
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001117 SLOGE("Cannot load dm-crypt mapping table.\n");
1118 goto errout;
Ken Sumralldb5e0262013-02-05 17:39:48 -08001119 } else if (load_count > 1) {
1120 SLOGI("Took %d tries to load dmcrypt table.\n", load_count);
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001121 }
1122
1123 /* Resume this device to activate it */
Ken Sumralldb5e0262013-02-05 17:39:48 -08001124 ioctl_init(io, DM_CRYPT_BUF_SIZE, name, 0);
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001125
1126 if (ioctl(fd, DM_DEV_SUSPEND, io)) {
1127 SLOGE("Cannot resume the dm-crypt device\n");
1128 goto errout;
1129 }
1130
1131 /* We made it here with no errors. Woot! */
1132 retval = 0;
1133
1134errout:
1135 close(fd); /* If fd is <0 from a failed open call, it's safe to just ignore the close error */
1136
1137 return retval;
1138}
1139
Ken Sumrall29d8da82011-05-18 17:20:07 -07001140static int delete_crypto_blk_dev(char *name)
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001141{
1142 int fd;
1143 char buffer[DM_CRYPT_BUF_SIZE];
1144 struct dm_ioctl *io;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001145 int retval = -1;
1146
1147 if ((fd = open("/dev/device-mapper", O_RDWR)) < 0 ) {
1148 SLOGE("Cannot open device-mapper\n");
1149 goto errout;
1150 }
1151
1152 io = (struct dm_ioctl *) buffer;
1153
1154 ioctl_init(io, DM_CRYPT_BUF_SIZE, name, 0);
1155 if (ioctl(fd, DM_DEV_REMOVE, io)) {
1156 SLOGE("Cannot remove dm-crypt device\n");
1157 goto errout;
1158 }
1159
1160 /* We made it here with no errors. Woot! */
1161 retval = 0;
1162
1163errout:
1164 close(fd); /* If fd is <0 from a failed open call, it's safe to just ignore the close error */
1165
1166 return retval;
1167
1168}
1169
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001170static int pbkdf2(const char *passwd, const unsigned char *salt,
Paul Lawrencef4faa572014-01-29 13:31:03 -08001171 unsigned char *ikey, void *params UNUSED)
1172{
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001173 SLOGI("Using pbkdf2 for cryptfs KDF");
1174
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001175 /* Turn the password into a key and IV that can decrypt the master key */
Paul Lawrencef4faa572014-01-29 13:31:03 -08001176 unsigned int keysize;
1177 char* master_key = (char*)convert_hex_ascii_to_key(passwd, &keysize);
1178 if (!master_key) return -1;
1179 PKCS5_PBKDF2_HMAC_SHA1(master_key, keysize, salt, SALT_LEN,
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001180 HASH_COUNT, KEY_LEN_BYTES+IV_LEN_BYTES, ikey);
Paul Lawrencef4faa572014-01-29 13:31:03 -08001181
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001182 memset(master_key, 0, keysize);
Paul Lawrencef4faa572014-01-29 13:31:03 -08001183 free (master_key);
1184 return 0;
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001185}
1186
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001187static int scrypt(const char *passwd, const unsigned char *salt,
Paul Lawrencef4faa572014-01-29 13:31:03 -08001188 unsigned char *ikey, void *params)
1189{
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001190 SLOGI("Using scrypt for cryptfs KDF");
1191
Kenny Rootc4c70f12013-06-14 12:11:38 -07001192 struct crypt_mnt_ftr *ftr = (struct crypt_mnt_ftr *) params;
1193
1194 int N = 1 << ftr->N_factor;
1195 int r = 1 << ftr->r_factor;
1196 int p = 1 << ftr->p_factor;
1197
1198 /* Turn the password into a key and IV that can decrypt the master key */
Paul Lawrencef4faa572014-01-29 13:31:03 -08001199 unsigned int keysize;
1200 unsigned char* master_key = convert_hex_ascii_to_key(passwd, &keysize);
1201 if (!master_key) return -1;
1202 crypto_scrypt(master_key, keysize, salt, SALT_LEN, N, r, p, ikey,
Kenny Rootc4c70f12013-06-14 12:11:38 -07001203 KEY_LEN_BYTES + IV_LEN_BYTES);
Paul Lawrencef4faa572014-01-29 13:31:03 -08001204
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001205 memset(master_key, 0, keysize);
Paul Lawrencef4faa572014-01-29 13:31:03 -08001206 free (master_key);
1207 return 0;
Kenny Rootc4c70f12013-06-14 12:11:38 -07001208}
1209
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001210static int scrypt_keymaster(const char *passwd, const unsigned char *salt,
1211 unsigned char *ikey, void *params)
1212{
1213 SLOGI("Using scrypt with keymaster for cryptfs KDF");
1214
1215 int rc;
1216 unsigned int key_size;
1217 size_t signature_size;
1218 unsigned char* signature;
1219 struct crypt_mnt_ftr *ftr = (struct crypt_mnt_ftr *) params;
1220
1221 int N = 1 << ftr->N_factor;
1222 int r = 1 << ftr->r_factor;
1223 int p = 1 << ftr->p_factor;
1224
1225 unsigned char* master_key = convert_hex_ascii_to_key(passwd, &key_size);
1226 if (!master_key) {
1227 SLOGE("Failed to convert passwd from hex");
1228 return -1;
1229 }
1230
1231 rc = crypto_scrypt(master_key, key_size, salt, SALT_LEN,
1232 N, r, p, ikey, KEY_LEN_BYTES + IV_LEN_BYTES);
1233 memset(master_key, 0, key_size);
1234 free(master_key);
1235
1236 if (rc) {
1237 SLOGE("scrypt failed");
1238 return -1;
1239 }
1240
Shawn Willdene17a9c42014-09-08 13:04:08 -06001241 if (keymaster_sign_object(ftr, ikey, KEY_LEN_BYTES + IV_LEN_BYTES,
1242 &signature, &signature_size)) {
1243 SLOGE("Signing failed");
1244 return -1;
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001245 }
1246
1247 rc = crypto_scrypt(signature, signature_size, salt, SALT_LEN,
1248 N, r, p, ikey, KEY_LEN_BYTES + IV_LEN_BYTES);
1249 free(signature);
1250
1251 if (rc) {
1252 SLOGE("scrypt failed");
1253 return -1;
1254 }
1255
1256 return 0;
1257}
1258
1259static int encrypt_master_key(const char *passwd, const unsigned char *salt,
1260 const unsigned char *decrypted_master_key,
Kenny Rootc4c70f12013-06-14 12:11:38 -07001261 unsigned char *encrypted_master_key,
1262 struct crypt_mnt_ftr *crypt_ftr)
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001263{
1264 unsigned char ikey[32+32] = { 0 }; /* Big enough to hold a 256 bit key and 256 bit IV */
1265 EVP_CIPHER_CTX e_ctx;
1266 int encrypted_len, final_len;
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001267 int rc = 0;
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001268
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001269 /* Turn the password into an intermediate key and IV that can decrypt the master key */
Kenny Rootc4c70f12013-06-14 12:11:38 -07001270 get_device_scrypt_params(crypt_ftr);
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001271
1272 switch (crypt_ftr->kdf_type) {
Shawn Willdene17a9c42014-09-08 13:04:08 -06001273 case KDF_SCRYPT_KEYMASTER_UNPADDED:
1274 case KDF_SCRYPT_KEYMASTER_BADLY_PADDED:
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001275 case KDF_SCRYPT_KEYMASTER:
1276 if (keymaster_create_key(crypt_ftr)) {
1277 SLOGE("keymaster_create_key failed");
1278 return -1;
1279 }
1280
1281 if (scrypt_keymaster(passwd, salt, ikey, crypt_ftr)) {
1282 SLOGE("scrypt failed");
1283 return -1;
1284 }
1285 break;
1286
1287 case KDF_SCRYPT:
1288 if (scrypt(passwd, salt, ikey, crypt_ftr)) {
1289 SLOGE("scrypt failed");
1290 return -1;
1291 }
1292 break;
1293
1294 default:
1295 SLOGE("Invalid kdf_type");
Paul Lawrencef4faa572014-01-29 13:31:03 -08001296 return -1;
1297 }
Kenny Rootc4c70f12013-06-14 12:11:38 -07001298
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001299 /* Initialize the decryption engine */
Adam Langley889c4f12014-09-03 14:23:13 -07001300 EVP_CIPHER_CTX_init(&e_ctx);
1301 if (! EVP_EncryptInit_ex(&e_ctx, EVP_aes_128_cbc(), NULL, ikey, ikey+KEY_LEN_BYTES)) {
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001302 SLOGE("EVP_EncryptInit failed\n");
1303 return -1;
1304 }
1305 EVP_CIPHER_CTX_set_padding(&e_ctx, 0); /* Turn off padding as our data is block aligned */
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001306
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001307 /* Encrypt the master key */
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001308 if (! EVP_EncryptUpdate(&e_ctx, encrypted_master_key, &encrypted_len,
1309 decrypted_master_key, KEY_LEN_BYTES)) {
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001310 SLOGE("EVP_EncryptUpdate failed\n");
1311 return -1;
1312 }
Adam Langley889c4f12014-09-03 14:23:13 -07001313 if (! EVP_EncryptFinal_ex(&e_ctx, encrypted_master_key + encrypted_len, &final_len)) {
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001314 SLOGE("EVP_EncryptFinal failed\n");
1315 return -1;
1316 }
1317
1318 if (encrypted_len + final_len != KEY_LEN_BYTES) {
1319 SLOGE("EVP_Encryption length check failed with %d, %d bytes\n", encrypted_len, final_len);
1320 return -1;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001321 }
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001322
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001323 /* Store the scrypt of the intermediate key, so we can validate if it's a
1324 password error or mount error when things go wrong.
1325 Note there's no need to check for errors, since if this is incorrect, we
1326 simply won't wipe userdata, which is the correct default behavior
1327 */
1328 int N = 1 << crypt_ftr->N_factor;
1329 int r = 1 << crypt_ftr->r_factor;
1330 int p = 1 << crypt_ftr->p_factor;
1331
1332 rc = crypto_scrypt(ikey, KEY_LEN_BYTES,
1333 crypt_ftr->salt, sizeof(crypt_ftr->salt), N, r, p,
1334 crypt_ftr->scrypted_intermediate_key,
1335 sizeof(crypt_ftr->scrypted_intermediate_key));
1336
1337 if (rc) {
1338 SLOGE("encrypt_master_key: crypto_scrypt failed");
1339 }
1340
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001341 return 0;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001342}
1343
JP Abgrall7bdfa522013-11-15 13:42:56 -08001344static int decrypt_master_key_aux(char *passwd, unsigned char *salt,
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001345 unsigned char *encrypted_master_key,
1346 unsigned char *decrypted_master_key,
1347 kdf_func kdf, void *kdf_params,
1348 unsigned char** intermediate_key,
1349 size_t* intermediate_key_size)
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001350{
1351 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 -08001352 EVP_CIPHER_CTX d_ctx;
1353 int decrypted_len, final_len;
1354
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001355 /* Turn the password into an intermediate key and IV that can decrypt the
1356 master key */
Paul Lawrencef4faa572014-01-29 13:31:03 -08001357 if (kdf(passwd, salt, ikey, kdf_params)) {
1358 SLOGE("kdf failed");
1359 return -1;
1360 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001361
1362 /* Initialize the decryption engine */
Adam Langley889c4f12014-09-03 14:23:13 -07001363 EVP_CIPHER_CTX_init(&d_ctx);
1364 if (! EVP_DecryptInit_ex(&d_ctx, EVP_aes_128_cbc(), NULL, ikey, ikey+KEY_LEN_BYTES)) {
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001365 return -1;
1366 }
1367 EVP_CIPHER_CTX_set_padding(&d_ctx, 0); /* Turn off padding as our data is block aligned */
1368 /* Decrypt the master key */
1369 if (! EVP_DecryptUpdate(&d_ctx, decrypted_master_key, &decrypted_len,
1370 encrypted_master_key, KEY_LEN_BYTES)) {
1371 return -1;
1372 }
Adam Langley889c4f12014-09-03 14:23:13 -07001373 if (! EVP_DecryptFinal_ex(&d_ctx, decrypted_master_key + decrypted_len, &final_len)) {
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001374 return -1;
1375 }
1376
1377 if (decrypted_len + final_len != KEY_LEN_BYTES) {
1378 return -1;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001379 }
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001380
1381 /* Copy intermediate key if needed by params */
1382 if (intermediate_key && intermediate_key_size) {
1383 *intermediate_key = (unsigned char*) malloc(KEY_LEN_BYTES);
1384 if (intermediate_key) {
1385 memcpy(*intermediate_key, ikey, KEY_LEN_BYTES);
1386 *intermediate_key_size = KEY_LEN_BYTES;
1387 }
1388 }
1389
1390 return 0;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001391}
1392
Kenny Rootc4c70f12013-06-14 12:11:38 -07001393static void get_kdf_func(struct crypt_mnt_ftr *ftr, kdf_func *kdf, void** kdf_params)
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001394{
Shawn Willdene17a9c42014-09-08 13:04:08 -06001395 if (ftr->kdf_type == KDF_SCRYPT_KEYMASTER_UNPADDED ||
1396 ftr->kdf_type == KDF_SCRYPT_KEYMASTER_BADLY_PADDED ||
1397 ftr->kdf_type == KDF_SCRYPT_KEYMASTER) {
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001398 *kdf = scrypt_keymaster;
1399 *kdf_params = ftr;
1400 } else if (ftr->kdf_type == KDF_SCRYPT) {
Kenny Rootc4c70f12013-06-14 12:11:38 -07001401 *kdf = scrypt;
1402 *kdf_params = ftr;
1403 } else {
1404 *kdf = pbkdf2;
1405 *kdf_params = NULL;
1406 }
1407}
1408
JP Abgrall7bdfa522013-11-15 13:42:56 -08001409static int decrypt_master_key(char *passwd, unsigned char *decrypted_master_key,
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001410 struct crypt_mnt_ftr *crypt_ftr,
1411 unsigned char** intermediate_key,
1412 size_t* intermediate_key_size)
Kenny Rootc4c70f12013-06-14 12:11:38 -07001413{
1414 kdf_func kdf;
1415 void *kdf_params;
1416 int ret;
1417
1418 get_kdf_func(crypt_ftr, &kdf, &kdf_params);
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001419 ret = decrypt_master_key_aux(passwd, crypt_ftr->salt, crypt_ftr->master_key,
1420 decrypted_master_key, kdf, kdf_params,
1421 intermediate_key, intermediate_key_size);
Kenny Rootc4c70f12013-06-14 12:11:38 -07001422 if (ret != 0) {
1423 SLOGW("failure decrypting master key");
Kenny Rootc4c70f12013-06-14 12:11:38 -07001424 }
1425
1426 return ret;
1427}
1428
1429static int create_encrypted_random_key(char *passwd, unsigned char *master_key, unsigned char *salt,
1430 struct crypt_mnt_ftr *crypt_ftr) {
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001431 int fd;
Ken Sumralle8744072011-01-18 22:01:55 -08001432 unsigned char key_buf[KEY_LEN_BYTES];
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001433
1434 /* Get some random bits for a key */
1435 fd = open("/dev/urandom", O_RDONLY);
Ken Sumralle8744072011-01-18 22:01:55 -08001436 read(fd, key_buf, sizeof(key_buf));
1437 read(fd, salt, SALT_LEN);
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001438 close(fd);
1439
1440 /* Now encrypt it with the password */
Kenny Rootc4c70f12013-06-14 12:11:38 -07001441 return encrypt_master_key(passwd, salt, key_buf, master_key, crypt_ftr);
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001442}
1443
Greg Hackmann6e8440f2014-10-02 17:18:20 -07001444static int wait_and_unmount(char *mountpoint, bool kill)
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001445{
Greg Hackmann955653e2014-09-24 14:55:20 -07001446 int i, err, rc;
Ken Sumrall2eaf7132011-01-14 12:45:48 -08001447#define WAIT_UNMOUNT_COUNT 20
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001448
1449 /* Now umount the tmpfs filesystem */
1450 for (i=0; i<WAIT_UNMOUNT_COUNT; i++) {
Greg Hackmann6e8440f2014-10-02 17:18:20 -07001451 if (umount(mountpoint) == 0) {
1452 break;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001453 }
Greg Hackmann6e8440f2014-10-02 17:18:20 -07001454
1455 if (errno == EINVAL) {
1456 /* EINVAL is returned if the directory is not a mountpoint,
1457 * i.e. there is no filesystem mounted there. So just get out.
1458 */
1459 break;
1460 }
1461
1462 err = errno;
1463
1464 /* If allowed, be increasingly aggressive before the last two retries */
1465 if (kill) {
1466 if (i == (WAIT_UNMOUNT_COUNT - 3)) {
1467 SLOGW("sending SIGHUP to processes with open files\n");
1468 vold_killProcessesWithOpenFiles(mountpoint, 1);
1469 } else if (i == (WAIT_UNMOUNT_COUNT - 2)) {
1470 SLOGW("sending SIGKILL to processes with open files\n");
1471 vold_killProcessesWithOpenFiles(mountpoint, 2);
1472 }
1473 }
1474
1475 sleep(1);
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001476 }
1477
1478 if (i < WAIT_UNMOUNT_COUNT) {
1479 SLOGD("unmounting %s succeeded\n", mountpoint);
1480 rc = 0;
1481 } else {
jessica_yu3f14fe42014-09-22 15:57:40 +08001482 vold_killProcessesWithOpenFiles(mountpoint, 0);
Greg Hackmann955653e2014-09-24 14:55:20 -07001483 SLOGE("unmounting %s failed: %s\n", mountpoint, strerror(err));
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001484 rc = -1;
1485 }
1486
1487 return rc;
1488}
1489
Ken Sumrallc5872692013-05-14 15:26:31 -07001490#define DATA_PREP_TIMEOUT 200
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001491static int prep_data_fs(void)
1492{
1493 int i;
1494
1495 /* Do the prep of the /data filesystem */
1496 property_set("vold.post_fs_data_done", "0");
1497 property_set("vold.decrypt", "trigger_post_fs_data");
1498 SLOGD("Just triggered post_fs_data\n");
1499
Ken Sumrallc5872692013-05-14 15:26:31 -07001500 /* Wait a max of 50 seconds, hopefully it takes much less */
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001501 for (i=0; i<DATA_PREP_TIMEOUT; i++) {
Ken Sumrall29d8da82011-05-18 17:20:07 -07001502 char p[PROPERTY_VALUE_MAX];
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001503
1504 property_get("vold.post_fs_data_done", p, "0");
1505 if (*p == '1') {
1506 break;
1507 } else {
1508 usleep(250000);
1509 }
1510 }
1511 if (i == DATA_PREP_TIMEOUT) {
1512 /* Ugh, we failed to prep /data in time. Bail. */
Ken Sumrallc5872692013-05-14 15:26:31 -07001513 SLOGE("post_fs_data timed out!\n");
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001514 return -1;
1515 } else {
1516 SLOGD("post_fs_data done\n");
1517 return 0;
1518 }
1519}
1520
Paul Lawrence74f29f12014-08-28 15:54:10 -07001521static void cryptfs_set_corrupt()
1522{
1523 // Mark the footer as bad
1524 struct crypt_mnt_ftr crypt_ftr;
1525 if (get_crypt_ftr_and_key(&crypt_ftr)) {
1526 SLOGE("Failed to get crypto footer - panic");
1527 return;
1528 }
1529
1530 crypt_ftr.flags |= CRYPT_DATA_CORRUPT;
1531 if (put_crypt_ftr_and_key(&crypt_ftr)) {
1532 SLOGE("Failed to set crypto footer - panic");
1533 return;
1534 }
1535}
1536
1537static void cryptfs_trigger_restart_min_framework()
1538{
1539 if (fs_mgr_do_tmpfs_mount(DATA_MNT_POINT)) {
1540 SLOGE("Failed to mount tmpfs on data - panic");
1541 return;
1542 }
1543
1544 if (property_set("vold.decrypt", "trigger_post_fs_data")) {
1545 SLOGE("Failed to trigger post fs data - panic");
1546 return;
1547 }
1548
1549 if (property_set("vold.decrypt", "trigger_restart_min_framework")) {
1550 SLOGE("Failed to trigger restart min framework - panic");
1551 return;
1552 }
1553}
1554
Paul Lawrence8e3f4512014-09-08 10:11:17 -07001555/* returns < 0 on failure */
Paul Lawrencef4faa572014-01-29 13:31:03 -08001556static int cryptfs_restart_internal(int restart_main)
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001557{
Ken Sumrall6864b7e2011-01-14 15:20:02 -08001558 char crypto_blkdev[MAXPATHLEN];
Tim Murray8439dc92014-12-15 11:56:11 -08001559 int rc = -1;
Ken Sumrall0cc16632011-01-18 20:32:26 -08001560 static int restart_successful = 0;
1561
1562 /* Validate that it's OK to call this routine */
Jason parks70a4b3f2011-01-28 10:10:47 -06001563 if (! master_key_saved) {
Ken Sumrall0cc16632011-01-18 20:32:26 -08001564 SLOGE("Encrypted filesystem not validated, aborting");
1565 return -1;
1566 }
1567
1568 if (restart_successful) {
1569 SLOGE("System already restarted with encrypted disk, aborting");
1570 return -1;
1571 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001572
Paul Lawrencef4faa572014-01-29 13:31:03 -08001573 if (restart_main) {
1574 /* Here is where we shut down the framework. The init scripts
1575 * start all services in one of three classes: core, main or late_start.
1576 * On boot, we start core and main. Now, we stop main, but not core,
1577 * as core includes vold and a few other really important things that
1578 * we need to keep running. Once main has stopped, we should be able
1579 * to umount the tmpfs /data, then mount the encrypted /data.
1580 * We then restart the class main, and also the class late_start.
1581 * At the moment, I've only put a few things in late_start that I know
1582 * are not needed to bring up the framework, and that also cause problems
1583 * with unmounting the tmpfs /data, but I hope to add add more services
1584 * to the late_start class as we optimize this to decrease the delay
1585 * till the user is asked for the password to the filesystem.
1586 */
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001587
Paul Lawrencef4faa572014-01-29 13:31:03 -08001588 /* The init files are setup to stop the class main when vold.decrypt is
1589 * set to trigger_reset_main.
1590 */
1591 property_set("vold.decrypt", "trigger_reset_main");
1592 SLOGD("Just asked init to shut down class main\n");
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001593
Paul Lawrencef4faa572014-01-29 13:31:03 -08001594 /* Ugh, shutting down the framework is not synchronous, so until it
1595 * can be fixed, this horrible hack will wait a moment for it all to
1596 * shut down before proceeding. Without it, some devices cannot
1597 * restart the graphics services.
1598 */
1599 sleep(2);
1600 }
Ken Sumrall9dedfd42012-10-09 14:16:59 -07001601
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001602 /* Now that the framework is shutdown, we should be able to umount()
1603 * the tmpfs filesystem, and mount the real one.
1604 */
1605
Ken Sumrall6864b7e2011-01-14 15:20:02 -08001606 property_get("ro.crypto.fs_crypto_blkdev", crypto_blkdev, "");
1607 if (strlen(crypto_blkdev) == 0) {
1608 SLOGE("fs_crypto_blkdev not set\n");
1609 return -1;
1610 }
1611
Greg Hackmann6e8440f2014-10-02 17:18:20 -07001612 if (! (rc = wait_and_unmount(DATA_MNT_POINT, true)) ) {
Doug Zongker6fd57712013-12-17 09:43:23 -08001613 /* If ro.crypto.readonly is set to 1, mount the decrypted
1614 * filesystem readonly. This is used when /data is mounted by
1615 * recovery mode.
1616 */
1617 char ro_prop[PROPERTY_VALUE_MAX];
1618 property_get("ro.crypto.readonly", ro_prop, "");
1619 if (strlen(ro_prop) > 0 && atoi(ro_prop)) {
1620 struct fstab_rec* rec = fs_mgr_get_entry_for_mount_point(fstab, DATA_MNT_POINT);
1621 rec->flags |= MS_RDONLY;
1622 }
JP Abgrall62c7af32014-06-16 13:01:23 -07001623
Ken Sumralle5032c42012-04-01 23:58:44 -07001624 /* If that succeeded, then mount the decrypted filesystem */
Paul Lawrence8e3f4512014-09-08 10:11:17 -07001625 int retries = RETRY_MOUNT_ATTEMPTS;
1626 int mount_rc;
1627 while ((mount_rc = fs_mgr_do_mount(fstab, DATA_MNT_POINT,
1628 crypto_blkdev, 0))
1629 != 0) {
1630 if (mount_rc == FS_MGR_DOMNT_BUSY) {
1631 /* TODO: invoke something similar to
1632 Process::killProcessWithOpenFiles(DATA_MNT_POINT,
1633 retries > RETRY_MOUNT_ATTEMPT/2 ? 1 : 2 ) */
1634 SLOGI("Failed to mount %s because it is busy - waiting",
1635 crypto_blkdev);
1636 if (--retries) {
1637 sleep(RETRY_MOUNT_DELAY_SECONDS);
1638 } else {
1639 /* Let's hope that a reboot clears away whatever is keeping
1640 the mount busy */
1641 cryptfs_reboot(reboot);
1642 }
1643 } else {
1644 SLOGE("Failed to mount decrypted data");
1645 cryptfs_set_corrupt();
1646 cryptfs_trigger_restart_min_framework();
1647 SLOGI("Started framework to offer wipe");
1648 return -1;
1649 }
Paul Lawrence74f29f12014-08-28 15:54:10 -07001650 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001651
Ken Sumralle5032c42012-04-01 23:58:44 -07001652 property_set("vold.decrypt", "trigger_load_persist_props");
1653 /* Create necessary paths on /data */
1654 if (prep_data_fs()) {
1655 return -1;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001656 }
Ken Sumralle5032c42012-04-01 23:58:44 -07001657
1658 /* startup service classes main and late_start */
1659 property_set("vold.decrypt", "trigger_restart_framework");
1660 SLOGD("Just triggered restart_framework\n");
1661
1662 /* Give it a few moments to get started */
1663 sleep(1);
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001664 }
1665
Ken Sumrall0cc16632011-01-18 20:32:26 -08001666 if (rc == 0) {
1667 restart_successful = 1;
1668 }
1669
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001670 return rc;
1671}
1672
Paul Lawrencef4faa572014-01-29 13:31:03 -08001673int cryptfs_restart(void)
1674{
1675 /* Call internal implementation forcing a restart of main service group */
1676 return cryptfs_restart_internal(1);
1677}
1678
Mark Salyzyn3e971272014-01-21 13:27:04 -08001679static int do_crypto_complete(char *mount_point UNUSED)
Ken Sumrall7f7dbaa2011-02-01 15:46:41 -08001680{
1681 struct crypt_mnt_ftr crypt_ftr;
Ken Sumrall29d8da82011-05-18 17:20:07 -07001682 char encrypted_state[PROPERTY_VALUE_MAX];
Ken Sumralle1a45852011-12-14 21:24:27 -08001683 char key_loc[PROPERTY_VALUE_MAX];
Ken Sumrall7f7dbaa2011-02-01 15:46:41 -08001684
1685 property_get("ro.crypto.state", encrypted_state, "");
1686 if (strcmp(encrypted_state, "encrypted") ) {
1687 SLOGE("not running with encryption, aborting");
Paul Lawrence74f29f12014-08-28 15:54:10 -07001688 return CRYPTO_COMPLETE_NOT_ENCRYPTED;
Ken Sumrall7f7dbaa2011-02-01 15:46:41 -08001689 }
1690
Ken Sumrall160b4d62013-04-22 12:15:39 -07001691 if (get_crypt_ftr_and_key(&crypt_ftr)) {
Ken Sumrall56ad03c2013-02-13 13:00:19 -08001692 fs_mgr_get_crypt_info(fstab, key_loc, 0, sizeof(key_loc));
Ken Sumralle5032c42012-04-01 23:58:44 -07001693
Ken Sumralle1a45852011-12-14 21:24:27 -08001694 /*
1695 * Only report this error if key_loc is a file and it exists.
1696 * If the device was never encrypted, and /data is not mountable for
1697 * some reason, returning 1 should prevent the UI from presenting the
1698 * a "enter password" screen, or worse, a "press button to wipe the
1699 * device" screen.
1700 */
1701 if ((key_loc[0] == '/') && (access("key_loc", F_OK) == -1)) {
1702 SLOGE("master key file does not exist, aborting");
Paul Lawrence74f29f12014-08-28 15:54:10 -07001703 return CRYPTO_COMPLETE_NOT_ENCRYPTED;
Ken Sumralle1a45852011-12-14 21:24:27 -08001704 } else {
1705 SLOGE("Error getting crypt footer and key\n");
Paul Lawrence74f29f12014-08-28 15:54:10 -07001706 return CRYPTO_COMPLETE_BAD_METADATA;
Ken Sumralle1a45852011-12-14 21:24:27 -08001707 }
Ken Sumrall7f7dbaa2011-02-01 15:46:41 -08001708 }
1709
Paul Lawrence74f29f12014-08-28 15:54:10 -07001710 // Test for possible error flags
1711 if (crypt_ftr.flags & CRYPT_ENCRYPTION_IN_PROGRESS){
1712 SLOGE("Encryption process is partway completed\n");
1713 return CRYPTO_COMPLETE_PARTIAL;
1714 }
1715
1716 if (crypt_ftr.flags & CRYPT_INCONSISTENT_STATE){
1717 SLOGE("Encryption process was interrupted but cannot continue\n");
1718 return CRYPTO_COMPLETE_INCONSISTENT;
1719 }
1720
1721 if (crypt_ftr.flags & CRYPT_DATA_CORRUPT){
1722 SLOGE("Encryption is successful but data is corrupt\n");
1723 return CRYPTO_COMPLETE_CORRUPT;
Ken Sumrall7f7dbaa2011-02-01 15:46:41 -08001724 }
1725
1726 /* We passed the test! We shall diminish, and return to the west */
Paul Lawrence74f29f12014-08-28 15:54:10 -07001727 return CRYPTO_COMPLETE_ENCRYPTED;
Ken Sumrall7f7dbaa2011-02-01 15:46:41 -08001728}
1729
Paul Lawrencef4faa572014-01-29 13:31:03 -08001730static int test_mount_encrypted_fs(struct crypt_mnt_ftr* crypt_ftr,
1731 char *passwd, char *mount_point, char *label)
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001732{
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001733 /* Allocate enough space for a 256 bit key, but we may use less */
Ken Sumrall160b4d62013-04-22 12:15:39 -07001734 unsigned char decrypted_master_key[32];
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001735 char crypto_blkdev[MAXPATHLEN];
1736 char real_blkdev[MAXPATHLEN];
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001737 char tmp_mount_point[64];
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001738 unsigned int orig_failed_decrypt_count;
1739 int rc;
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001740 int use_keymaster = 0;
1741 int upgrade = 0;
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001742 unsigned char* intermediate_key = 0;
1743 size_t intermediate_key_size = 0;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001744
Paul Lawrencef4faa572014-01-29 13:31:03 -08001745 SLOGD("crypt_ftr->fs_size = %lld\n", crypt_ftr->fs_size);
1746 orig_failed_decrypt_count = crypt_ftr->failed_decrypt_count;
Ken Sumrall0cc16632011-01-18 20:32:26 -08001747
Paul Lawrencef4faa572014-01-29 13:31:03 -08001748 if (! (crypt_ftr->flags & CRYPT_MNT_KEY_UNENCRYPTED) ) {
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001749 if (decrypt_master_key(passwd, decrypted_master_key, crypt_ftr,
1750 &intermediate_key, &intermediate_key_size)) {
JP Abgrall7bdfa522013-11-15 13:42:56 -08001751 SLOGE("Failed to decrypt master key\n");
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001752 rc = -1;
1753 goto errout;
JP Abgrall7bdfa522013-11-15 13:42:56 -08001754 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001755 }
1756
Paul Lawrencef4faa572014-01-29 13:31:03 -08001757 fs_mgr_get_crypt_info(fstab, 0, real_blkdev, sizeof(real_blkdev));
1758
Ajay Dudani87701e22014-09-17 21:02:52 -07001759#ifdef CONFIG_HW_DISK_ENCRYPTION
Iliyan Malchevbb7d9af2014-11-20 18:42:23 -08001760 if (!strcmp((char *)crypt_ftr->crypto_type_name, "aes-xts")) {
1761 if(!set_hw_device_encryption_key(passwd, (char*) crypt_ftr->crypto_type_name)) {
1762 SLOGE("Hardware encryption key does not match");
1763 }
Ajay Dudani87701e22014-09-17 21:02:52 -07001764 }
1765#endif
1766
Paul Lawrence74f29f12014-08-28 15:54:10 -07001767 // Create crypto block device - all (non fatal) code paths
1768 // need it
Paul Lawrencef4faa572014-01-29 13:31:03 -08001769 if (create_crypto_blk_dev(crypt_ftr, decrypted_master_key,
1770 real_blkdev, crypto_blkdev, label)) {
Paul Lawrence74f29f12014-08-28 15:54:10 -07001771 SLOGE("Error creating decrypted block device\n");
1772 rc = -1;
1773 goto errout;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001774 }
1775
Paul Lawrence74f29f12014-08-28 15:54:10 -07001776 /* Work out if the problem is the password or the data */
1777 unsigned char scrypted_intermediate_key[sizeof(crypt_ftr->
1778 scrypted_intermediate_key)];
1779 int N = 1 << crypt_ftr->N_factor;
1780 int r = 1 << crypt_ftr->r_factor;
1781 int p = 1 << crypt_ftr->p_factor;
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001782
Paul Lawrence74f29f12014-08-28 15:54:10 -07001783 rc = crypto_scrypt(intermediate_key, intermediate_key_size,
1784 crypt_ftr->salt, sizeof(crypt_ftr->salt),
1785 N, r, p, scrypted_intermediate_key,
1786 sizeof(scrypted_intermediate_key));
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001787
Paul Lawrence74f29f12014-08-28 15:54:10 -07001788 // Does the key match the crypto footer?
1789 if (rc == 0 && memcmp(scrypted_intermediate_key,
1790 crypt_ftr->scrypted_intermediate_key,
1791 sizeof(scrypted_intermediate_key)) == 0) {
1792 SLOGI("Password matches");
1793 rc = 0;
1794 } else {
1795 /* Try mounting the file system anyway, just in case the problem's with
1796 * the footer, not the key. */
1797 sprintf(tmp_mount_point, "%s/tmp_mnt", mount_point);
1798 mkdir(tmp_mount_point, 0755);
1799 if (fs_mgr_do_mount(fstab, DATA_MNT_POINT, crypto_blkdev, tmp_mount_point)) {
1800 SLOGE("Error temp mounting decrypted block device\n");
1801 delete_crypto_blk_dev(label);
1802
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001803 rc = ++crypt_ftr->failed_decrypt_count;
1804 put_crypt_ftr_and_key(crypt_ftr);
Paul Lawrence74f29f12014-08-28 15:54:10 -07001805 } else {
1806 /* Success! */
1807 SLOGI("Password did not match but decrypted drive mounted - continue");
1808 umount(tmp_mount_point);
1809 rc = 0;
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001810 }
Paul Lawrence74f29f12014-08-28 15:54:10 -07001811 }
1812
1813 if (rc == 0) {
1814 crypt_ftr->failed_decrypt_count = 0;
Paul Lawrence72b8b822014-10-05 12:57:37 -07001815 if (orig_failed_decrypt_count != 0) {
1816 put_crypt_ftr_and_key(crypt_ftr);
1817 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001818
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001819 /* Save the name of the crypto block device
Paul Lawrence74f29f12014-08-28 15:54:10 -07001820 * so we can mount it when restarting the framework. */
Ken Sumrall6864b7e2011-01-14 15:20:02 -08001821 property_set("ro.crypto.fs_crypto_blkdev", crypto_blkdev);
Jason parks70a4b3f2011-01-28 10:10:47 -06001822
1823 /* Also save a the master key so we can reencrypted the key
Paul Lawrence74f29f12014-08-28 15:54:10 -07001824 * the key when we want to change the password on it. */
Jason parks70a4b3f2011-01-28 10:10:47 -06001825 memcpy(saved_master_key, decrypted_master_key, KEY_LEN_BYTES);
Ken Sumrall3ad90722011-10-04 20:38:29 -07001826 saved_mount_point = strdup(mount_point);
Jason parks70a4b3f2011-01-28 10:10:47 -06001827 master_key_saved = 1;
JP Abgrall7bdfa522013-11-15 13:42:56 -08001828 SLOGD("%s(): Master key saved\n", __FUNCTION__);
Ken Sumrall6864b7e2011-01-14 15:20:02 -08001829 rc = 0;
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001830
Paul Lawrence74f29f12014-08-28 15:54:10 -07001831 // Upgrade if we're not using the latest KDF.
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001832 use_keymaster = keymaster_check_compatibility();
1833 if (crypt_ftr->kdf_type == KDF_SCRYPT_KEYMASTER) {
Shawn Willden47ba10d2014-09-03 17:07:06 -06001834 // Don't allow downgrade
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001835 } else if (use_keymaster == 1 && crypt_ftr->kdf_type != KDF_SCRYPT_KEYMASTER) {
1836 crypt_ftr->kdf_type = KDF_SCRYPT_KEYMASTER;
1837 upgrade = 1;
1838 } else if (use_keymaster == 0 && crypt_ftr->kdf_type != KDF_SCRYPT) {
Paul Lawrencef4faa572014-01-29 13:31:03 -08001839 crypt_ftr->kdf_type = KDF_SCRYPT;
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001840 upgrade = 1;
1841 }
1842
1843 if (upgrade) {
Paul Lawrencef4faa572014-01-29 13:31:03 -08001844 rc = encrypt_master_key(passwd, crypt_ftr->salt, saved_master_key,
1845 crypt_ftr->master_key, crypt_ftr);
JP Abgrall7bdfa522013-11-15 13:42:56 -08001846 if (!rc) {
Paul Lawrencef4faa572014-01-29 13:31:03 -08001847 rc = put_crypt_ftr_and_key(crypt_ftr);
JP Abgrall7bdfa522013-11-15 13:42:56 -08001848 }
1849 SLOGD("Key Derivation Function upgrade: rc=%d\n", rc);
Paul Lawrenceb2f682b2014-09-08 11:28:19 -07001850
1851 // Do not fail even if upgrade failed - machine is bootable
1852 // Note that if this code is ever hit, there is a *serious* problem
1853 // since KDFs should never fail. You *must* fix the kdf before
1854 // proceeding!
1855 if (rc) {
1856 SLOGW("Upgrade failed with error %d,"
1857 " but continuing with previous state",
1858 rc);
1859 rc = 0;
1860 }
JP Abgrall7bdfa522013-11-15 13:42:56 -08001861 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001862 }
1863
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001864 errout:
1865 if (intermediate_key) {
1866 memset(intermediate_key, 0, intermediate_key_size);
1867 free(intermediate_key);
1868 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001869 return rc;
1870}
1871
Ken Sumrall0b8b5972011-08-31 16:14:23 -07001872/* Called by vold when it wants to undo the crypto mapping of a volume it
1873 * manages. This is usually in response to a factory reset, when we want
1874 * to undo the crypto mapping so the volume is formatted in the clear.
1875 */
1876int cryptfs_revert_volume(const char *label)
1877{
1878 return delete_crypto_blk_dev((char *)label);
1879}
1880
Ken Sumrall29d8da82011-05-18 17:20:07 -07001881/*
1882 * Called by vold when it's asked to mount an encrypted, nonremovable volume.
1883 * Setup a dm-crypt mapping, use the saved master key from
1884 * setting up the /data mapping, and return the new device path.
1885 */
1886int cryptfs_setup_volume(const char *label, int major, int minor,
1887 char *crypto_sys_path, unsigned int max_path,
1888 int *new_major, int *new_minor)
1889{
1890 char real_blkdev[MAXPATHLEN], crypto_blkdev[MAXPATHLEN];
1891 struct crypt_mnt_ftr sd_crypt_ftr;
Ken Sumrall29d8da82011-05-18 17:20:07 -07001892 struct stat statbuf;
Tim Murray8439dc92014-12-15 11:56:11 -08001893 unsigned int nr_sec;
1894 int fd;
Ken Sumrall29d8da82011-05-18 17:20:07 -07001895
1896 sprintf(real_blkdev, "/dev/block/vold/%d:%d", major, minor);
1897
Ken Sumrall160b4d62013-04-22 12:15:39 -07001898 get_crypt_ftr_and_key(&sd_crypt_ftr);
Ken Sumrall29d8da82011-05-18 17:20:07 -07001899
1900 /* Update the fs_size field to be the size of the volume */
1901 fd = open(real_blkdev, O_RDONLY);
1902 nr_sec = get_blkdev_size(fd);
1903 close(fd);
1904 if (nr_sec == 0) {
1905 SLOGE("Cannot get size of volume %s\n", real_blkdev);
1906 return -1;
1907 }
1908
1909 sd_crypt_ftr.fs_size = nr_sec;
1910 create_crypto_blk_dev(&sd_crypt_ftr, saved_master_key, real_blkdev,
1911 crypto_blkdev, label);
1912
JP Abgrall3334c6a2014-10-10 15:52:11 -07001913 if (stat(crypto_blkdev, &statbuf) < 0) {
1914 SLOGE("Error get stat for crypto_blkdev %s. err=%d(%s)\n",
1915 crypto_blkdev, errno, strerror(errno));
1916 }
Ken Sumrall29d8da82011-05-18 17:20:07 -07001917 *new_major = MAJOR(statbuf.st_rdev);
1918 *new_minor = MINOR(statbuf.st_rdev);
1919
1920 /* Create path to sys entry for this block device */
1921 snprintf(crypto_sys_path, max_path, "/devices/virtual/block/%s", strrchr(crypto_blkdev, '/')+1);
1922
1923 return 0;
1924}
1925
Ken Sumrall7f7dbaa2011-02-01 15:46:41 -08001926int cryptfs_crypto_complete(void)
1927{
1928 return do_crypto_complete("/data");
1929}
1930
Paul Lawrencef4faa572014-01-29 13:31:03 -08001931int check_unmounted_and_get_ftr(struct crypt_mnt_ftr* crypt_ftr)
1932{
1933 char encrypted_state[PROPERTY_VALUE_MAX];
1934 property_get("ro.crypto.state", encrypted_state, "");
1935 if ( master_key_saved || strcmp(encrypted_state, "encrypted") ) {
1936 SLOGE("encrypted fs already validated or not running with encryption,"
1937 " aborting");
1938 return -1;
1939 }
1940
1941 if (get_crypt_ftr_and_key(crypt_ftr)) {
1942 SLOGE("Error getting crypt footer and key");
1943 return -1;
1944 }
1945
1946 return 0;
1947}
1948
Paul Lawrencefc615042014-10-04 15:32:29 -07001949/*
1950 * TODO - transition patterns to new format in calling code
1951 * and remove this vile hack, and the use of hex in
1952 * the password passing code.
1953 *
1954 * Patterns are passed in zero based (i.e. the top left dot
1955 * is represented by zero, the top middle one etc), but we want
1956 * to store them '1' based.
1957 * This is to allow us to migrate the calling code to use this
1958 * convention. It also solves a nasty problem whereby scrypt ignores
1959 * trailing zeros, so patterns ending at the top left could be
1960 * truncated, and similarly, you could add the top left to any
1961 * pattern and still match.
1962 * adjust_passwd is a hack function that returns the alternate representation
1963 * if the password appears to be a pattern (hex numbers all less than 09)
1964 * If it succeeds we need to try both, and in particular try the alternate
1965 * first. If the original matches, then we need to update the footer
1966 * with the alternate.
1967 * All code that accepts passwords must adjust them first. Since
1968 * cryptfs_check_passwd is always the first function called after a migration
1969 * (and indeed on any boot) we only need to do the double try in this
1970 * function.
1971 */
1972char* adjust_passwd(const char* passwd)
1973{
1974 size_t index, length;
1975
1976 if (!passwd) {
1977 return 0;
1978 }
1979
1980 // Check even length. Hex encoded passwords are always
1981 // an even length, since each character encodes to two characters.
1982 length = strlen(passwd);
1983 if (length % 2) {
1984 SLOGW("Password not correctly hex encoded.");
1985 return 0;
1986 }
1987
1988 // Check password is old-style pattern - a collection of hex
1989 // encoded bytes less than 9 (00 through 08)
1990 for (index = 0; index < length; index +=2) {
1991 if (passwd[index] != '0'
1992 || passwd[index + 1] < '0' || passwd[index + 1] > '8') {
1993 return 0;
1994 }
1995 }
1996
1997 // Allocate room for adjusted passwd and null terminate
1998 char* adjusted = malloc(length + 1);
1999 adjusted[length] = 0;
2000
2001 // Add 0x31 ('1') to each character
2002 for (index = 0; index < length; index += 2) {
2003 // output is 31 through 39 so set first byte to three, second to src + 1
2004 adjusted[index] = '3';
2005 adjusted[index + 1] = passwd[index + 1] + 1;
2006 }
2007
2008 return adjusted;
2009}
2010
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002011int cryptfs_check_passwd(char *passwd)
2012{
Paul Lawrencef4faa572014-01-29 13:31:03 -08002013 struct crypt_mnt_ftr crypt_ftr;
2014 int rc;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002015
Paul Lawrencef4faa572014-01-29 13:31:03 -08002016 rc = check_unmounted_and_get_ftr(&crypt_ftr);
2017 if (rc)
2018 return rc;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002019
Paul Lawrencefc615042014-10-04 15:32:29 -07002020 char* adjusted_passwd = adjust_passwd(passwd);
2021 if (adjusted_passwd) {
2022 int failed_decrypt_count = crypt_ftr.failed_decrypt_count;
2023 rc = test_mount_encrypted_fs(&crypt_ftr, adjusted_passwd,
2024 DATA_MNT_POINT, "userdata");
2025
2026 // Maybe the original one still works?
2027 if (rc) {
2028 // Don't double count this failure
2029 crypt_ftr.failed_decrypt_count = failed_decrypt_count;
2030 rc = test_mount_encrypted_fs(&crypt_ftr, passwd,
2031 DATA_MNT_POINT, "userdata");
2032 if (!rc) {
2033 // cryptfs_changepw also adjusts so pass original
2034 // Note that adjust_passwd only recognises patterns
2035 // so we can safely use CRYPT_TYPE_PATTERN
2036 SLOGI("Updating pattern to new format");
2037 cryptfs_changepw(CRYPT_TYPE_PATTERN, passwd);
2038 }
2039 }
2040 free(adjusted_passwd);
2041 } else {
2042 rc = test_mount_encrypted_fs(&crypt_ftr, passwd,
2043 DATA_MNT_POINT, "userdata");
2044 }
Paul Lawrence684dbdf2014-02-07 12:07:22 -08002045
2046 if (rc == 0 && crypt_ftr.crypt_type != CRYPT_TYPE_DEFAULT) {
Paul Lawrence399317e2014-03-10 13:20:50 -07002047 cryptfs_clear_password();
2048 password = strdup(passwd);
2049 struct timespec now;
2050 clock_gettime(CLOCK_BOOTTIME, &now);
2051 password_expiry_time = now.tv_sec + password_max_age_seconds;
Paul Lawrence684dbdf2014-02-07 12:07:22 -08002052 }
2053
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002054 return rc;
2055}
2056
Ken Sumrall3ad90722011-10-04 20:38:29 -07002057int cryptfs_verify_passwd(char *passwd)
2058{
2059 struct crypt_mnt_ftr crypt_ftr;
2060 /* Allocate enough space for a 256 bit key, but we may use less */
Ken Sumrall160b4d62013-04-22 12:15:39 -07002061 unsigned char decrypted_master_key[32];
Ken Sumrall3ad90722011-10-04 20:38:29 -07002062 char encrypted_state[PROPERTY_VALUE_MAX];
2063 int rc;
2064
2065 property_get("ro.crypto.state", encrypted_state, "");
2066 if (strcmp(encrypted_state, "encrypted") ) {
2067 SLOGE("device not encrypted, aborting");
2068 return -2;
2069 }
2070
2071 if (!master_key_saved) {
2072 SLOGE("encrypted fs not yet mounted, aborting");
2073 return -1;
2074 }
2075
2076 if (!saved_mount_point) {
2077 SLOGE("encrypted fs failed to save mount point, aborting");
2078 return -1;
2079 }
2080
Ken Sumrall160b4d62013-04-22 12:15:39 -07002081 if (get_crypt_ftr_and_key(&crypt_ftr)) {
Ken Sumrall3ad90722011-10-04 20:38:29 -07002082 SLOGE("Error getting crypt footer and key\n");
2083 return -1;
2084 }
2085
2086 if (crypt_ftr.flags & CRYPT_MNT_KEY_UNENCRYPTED) {
2087 /* If the device has no password, then just say the password is valid */
2088 rc = 0;
2089 } else {
Paul Lawrencefc615042014-10-04 15:32:29 -07002090 char* adjusted_passwd = adjust_passwd(passwd);
2091 if (adjusted_passwd) {
2092 passwd = adjusted_passwd;
2093 }
2094
Paul Lawrenced0c7b172014-08-08 14:28:10 -07002095 decrypt_master_key(passwd, decrypted_master_key, &crypt_ftr, 0, 0);
Ken Sumrall3ad90722011-10-04 20:38:29 -07002096 if (!memcmp(decrypted_master_key, saved_master_key, crypt_ftr.keysize)) {
2097 /* They match, the password is correct */
2098 rc = 0;
2099 } else {
2100 /* If incorrect, sleep for a bit to prevent dictionary attacks */
2101 sleep(1);
2102 rc = 1;
2103 }
Paul Lawrencefc615042014-10-04 15:32:29 -07002104
2105 free(adjusted_passwd);
Ken Sumrall3ad90722011-10-04 20:38:29 -07002106 }
2107
2108 return rc;
2109}
2110
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002111/* Initialize a crypt_mnt_ftr structure. The keysize is
2112 * defaulted to 16 bytes, and the filesystem size to 0.
2113 * Presumably, at a minimum, the caller will update the
2114 * filesystem size and crypto_type_name after calling this function.
2115 */
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07002116static int cryptfs_init_crypt_mnt_ftr(struct crypt_mnt_ftr *ftr)
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002117{
Ken Sumrall160b4d62013-04-22 12:15:39 -07002118 off64_t off;
2119
2120 memset(ftr, 0, sizeof(struct crypt_mnt_ftr));
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002121 ftr->magic = CRYPT_MNT_MAGIC;
Kenny Rootc96a5f82013-06-14 12:08:28 -07002122 ftr->major_version = CURRENT_MAJOR_VERSION;
2123 ftr->minor_version = CURRENT_MINOR_VERSION;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002124 ftr->ftr_size = sizeof(struct crypt_mnt_ftr);
Jason parks70a4b3f2011-01-28 10:10:47 -06002125 ftr->keysize = KEY_LEN_BYTES;
Ken Sumrall160b4d62013-04-22 12:15:39 -07002126
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07002127 switch (keymaster_check_compatibility()) {
2128 case 1:
2129 ftr->kdf_type = KDF_SCRYPT_KEYMASTER;
2130 break;
2131
2132 case 0:
2133 ftr->kdf_type = KDF_SCRYPT;
2134 break;
2135
2136 default:
2137 SLOGE("keymaster_check_compatibility failed");
2138 return -1;
2139 }
2140
Kenny Rootc4c70f12013-06-14 12:11:38 -07002141 get_device_scrypt_params(ftr);
2142
Ken Sumrall160b4d62013-04-22 12:15:39 -07002143 ftr->persist_data_size = CRYPT_PERSIST_DATA_SIZE;
2144 if (get_crypt_ftr_info(NULL, &off) == 0) {
2145 ftr->persist_data_offset[0] = off + CRYPT_FOOTER_TO_PERSIST_OFFSET;
2146 ftr->persist_data_offset[1] = off + CRYPT_FOOTER_TO_PERSIST_OFFSET +
2147 ftr->persist_data_size;
2148 }
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07002149
2150 return 0;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002151}
2152
Ken Sumrall29d8da82011-05-18 17:20:07 -07002153static int cryptfs_enable_wipe(char *crypto_blkdev, off64_t size, int type)
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002154{
Ken Sumralle550f782013-08-20 13:48:23 -07002155 const char *args[10];
2156 char size_str[32]; /* Must be large enough to hold a %lld and null byte */
2157 int num_args;
2158 int status;
2159 int tmp;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002160 int rc = -1;
2161
Ken Sumrall29d8da82011-05-18 17:20:07 -07002162 if (type == EXT4_FS) {
Ken Sumralle550f782013-08-20 13:48:23 -07002163 args[0] = "/system/bin/make_ext4fs";
2164 args[1] = "-a";
2165 args[2] = "/data";
2166 args[3] = "-l";
Elliott Hughes73737162014-06-25 17:27:42 -07002167 snprintf(size_str, sizeof(size_str), "%" PRId64, size * 512);
Ken Sumralle550f782013-08-20 13:48:23 -07002168 args[4] = size_str;
2169 args[5] = crypto_blkdev;
2170 num_args = 6;
2171 SLOGI("Making empty filesystem with command %s %s %s %s %s %s\n",
2172 args[0], args[1], args[2], args[3], args[4], args[5]);
JP Abgrall62c7af32014-06-16 13:01:23 -07002173 } else if (type == F2FS_FS) {
2174 args[0] = "/system/bin/mkfs.f2fs";
2175 args[1] = "-t";
2176 args[2] = "-d1";
2177 args[3] = crypto_blkdev;
Elliott Hughes73737162014-06-25 17:27:42 -07002178 snprintf(size_str, sizeof(size_str), "%" PRId64, size);
JP Abgrall62c7af32014-06-16 13:01:23 -07002179 args[4] = size_str;
2180 num_args = 5;
2181 SLOGI("Making empty filesystem with command %s %s %s %s %s\n",
2182 args[0], args[1], args[2], args[3], args[4]);
Ken Sumrall29d8da82011-05-18 17:20:07 -07002183 } else {
2184 SLOGE("cryptfs_enable_wipe(): unknown filesystem type %d\n", type);
2185 return -1;
2186 }
2187
Ken Sumralle550f782013-08-20 13:48:23 -07002188 tmp = android_fork_execvp(num_args, (char **)args, &status, false, true);
2189
2190 if (tmp != 0) {
2191 SLOGE("Error creating empty filesystem on %s due to logwrap error\n", crypto_blkdev);
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002192 } else {
Ken Sumralle550f782013-08-20 13:48:23 -07002193 if (WIFEXITED(status)) {
2194 if (WEXITSTATUS(status)) {
2195 SLOGE("Error creating filesystem on %s, exit status %d ",
2196 crypto_blkdev, WEXITSTATUS(status));
2197 } else {
2198 SLOGD("Successfully created filesystem on %s\n", crypto_blkdev);
2199 rc = 0;
2200 }
2201 } else {
2202 SLOGE("Error creating filesystem on %s, did not exit normally\n", crypto_blkdev);
2203 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002204 }
2205
2206 return rc;
2207}
2208
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002209#define CRYPT_INPLACE_BUFSIZE 4096
Paul Lawrence87999172014-02-20 12:21:31 -08002210#define CRYPT_SECTORS_PER_BUFSIZE (CRYPT_INPLACE_BUFSIZE / CRYPT_SECTOR_SIZE)
2211#define CRYPT_SECTOR_SIZE 512
Paul Lawrenceae59fe62014-01-21 08:23:27 -08002212
2213/* aligned 32K writes tends to make flash happy.
2214 * SD card association recommends it.
2215 */
Ajay Dudani87701e22014-09-17 21:02:52 -07002216#ifndef CONFIG_HW_DISK_ENCRYPTION
Paul Lawrenceae59fe62014-01-21 08:23:27 -08002217#define BLOCKS_AT_A_TIME 8
Ajay Dudani87701e22014-09-17 21:02:52 -07002218#else
2219#define BLOCKS_AT_A_TIME 1024
2220#endif
Paul Lawrenceae59fe62014-01-21 08:23:27 -08002221
2222struct encryptGroupsData
2223{
2224 int realfd;
2225 int cryptofd;
2226 off64_t numblocks;
2227 off64_t one_pct, cur_pct, new_pct;
2228 off64_t blocks_already_done, tot_numblocks;
Paul Lawrence58c58cf2014-06-04 13:12:21 -07002229 off64_t used_blocks_already_done, tot_used_blocks;
Paul Lawrenceae59fe62014-01-21 08:23:27 -08002230 char* real_blkdev, * crypto_blkdev;
2231 int count;
2232 off64_t offset;
2233 char* buffer;
Paul Lawrence87999172014-02-20 12:21:31 -08002234 off64_t last_written_sector;
2235 int completed;
Paul Lawrencea96d9c92014-06-04 14:05:01 -07002236 time_t time_started;
2237 int remaining_time;
Paul Lawrenceae59fe62014-01-21 08:23:27 -08002238};
2239
Paul Lawrence58c58cf2014-06-04 13:12:21 -07002240static void update_progress(struct encryptGroupsData* data, int is_used)
Paul Lawrenceae59fe62014-01-21 08:23:27 -08002241{
2242 data->blocks_already_done++;
Paul Lawrence58c58cf2014-06-04 13:12:21 -07002243
2244 if (is_used) {
2245 data->used_blocks_already_done++;
2246 }
Paul Lawrence58c58cf2014-06-04 13:12:21 -07002247 if (data->tot_used_blocks) {
2248 data->new_pct = data->used_blocks_already_done / data->one_pct;
2249 } else {
2250 data->new_pct = data->blocks_already_done / data->one_pct;
2251 }
2252
Paul Lawrenceae59fe62014-01-21 08:23:27 -08002253 if (data->new_pct > data->cur_pct) {
2254 char buf[8];
2255 data->cur_pct = data->new_pct;
Elliott Hughescb33f572014-06-25 18:25:11 -07002256 snprintf(buf, sizeof(buf), "%" PRId64, data->cur_pct);
Paul Lawrenceae59fe62014-01-21 08:23:27 -08002257 property_set("vold.encrypt_progress", buf);
2258 }
Paul Lawrencea96d9c92014-06-04 14:05:01 -07002259
2260 if (data->cur_pct >= 5) {
Paul Lawrence9c58a872014-09-30 09:12:51 -07002261 struct timespec time_now;
2262 if (clock_gettime(CLOCK_MONOTONIC, &time_now)) {
2263 SLOGW("Error getting time");
2264 } else {
2265 double elapsed_time = difftime(time_now.tv_sec, data->time_started);
2266 off64_t remaining_blocks = data->tot_used_blocks
2267 - data->used_blocks_already_done;
2268 int remaining_time = (int)(elapsed_time * remaining_blocks
2269 / data->used_blocks_already_done);
Paul Lawrence71577502014-08-13 14:55:55 -07002270
Paul Lawrence9c58a872014-09-30 09:12:51 -07002271 // Change time only if not yet set, lower, or a lot higher for
2272 // best user experience
2273 if (data->remaining_time == -1
2274 || remaining_time < data->remaining_time
2275 || remaining_time > data->remaining_time + 60) {
2276 char buf[8];
2277 snprintf(buf, sizeof(buf), "%d", remaining_time);
2278 property_set("vold.encrypt_time_remaining", buf);
2279 data->remaining_time = remaining_time;
2280 }
Paul Lawrencea96d9c92014-06-04 14:05:01 -07002281 }
2282 }
Paul Lawrenceae59fe62014-01-21 08:23:27 -08002283}
2284
Paul Lawrence3846be12014-09-22 11:33:54 -07002285static void log_progress(struct encryptGroupsData const* data, bool completed)
2286{
2287 // Precondition - if completed data = 0 else data != 0
2288
2289 // Track progress so we can skip logging blocks
2290 static off64_t offset = -1;
2291
2292 // Need to close existing 'Encrypting from' log?
2293 if (completed || (offset != -1 && data->offset != offset)) {
2294 SLOGI("Encrypted to sector %" PRId64,
2295 offset / info.block_size * CRYPT_SECTOR_SIZE);
2296 offset = -1;
2297 }
2298
2299 // Need to start new 'Encrypting from' log?
2300 if (!completed && offset != data->offset) {
2301 SLOGI("Encrypting from sector %" PRId64,
2302 data->offset / info.block_size * CRYPT_SECTOR_SIZE);
2303 }
2304
2305 // Update offset
2306 if (!completed) {
2307 offset = data->offset + (off64_t)data->count * info.block_size;
2308 }
2309}
2310
Paul Lawrenceae59fe62014-01-21 08:23:27 -08002311static int flush_outstanding_data(struct encryptGroupsData* data)
2312{
2313 if (data->count == 0) {
2314 return 0;
2315 }
2316
Elliott Hughes231bdba2014-06-25 18:36:19 -07002317 SLOGV("Copying %d blocks at offset %" PRIx64, data->count, data->offset);
Paul Lawrenceae59fe62014-01-21 08:23:27 -08002318
2319 if (pread64(data->realfd, data->buffer,
2320 info.block_size * data->count, data->offset)
2321 <= 0) {
2322 SLOGE("Error reading real_blkdev %s for inplace encrypt",
2323 data->real_blkdev);
2324 return -1;
2325 }
2326
2327 if (pwrite64(data->cryptofd, data->buffer,
2328 info.block_size * data->count, data->offset)
2329 <= 0) {
2330 SLOGE("Error writing crypto_blkdev %s for inplace encrypt",
2331 data->crypto_blkdev);
2332 return -1;
Paul Lawrence87999172014-02-20 12:21:31 -08002333 } else {
Paul Lawrence3846be12014-09-22 11:33:54 -07002334 log_progress(data, false);
Paul Lawrenceae59fe62014-01-21 08:23:27 -08002335 }
2336
2337 data->count = 0;
Paul Lawrence87999172014-02-20 12:21:31 -08002338 data->last_written_sector = (data->offset + data->count)
2339 / info.block_size * CRYPT_SECTOR_SIZE - 1;
Paul Lawrenceae59fe62014-01-21 08:23:27 -08002340 return 0;
2341}
2342
2343static int encrypt_groups(struct encryptGroupsData* data)
2344{
2345 unsigned int i;
2346 u8 *block_bitmap = 0;
2347 unsigned int block;
2348 off64_t ret;
2349 int rc = -1;
2350
2351 data->buffer = malloc(info.block_size * BLOCKS_AT_A_TIME);
2352 if (!data->buffer) {
2353 SLOGE("Failed to allocate crypto buffer");
2354 goto errout;
2355 }
2356
2357 block_bitmap = malloc(info.block_size);
2358 if (!block_bitmap) {
2359 SLOGE("failed to allocate block bitmap");
2360 goto errout;
2361 }
2362
2363 for (i = 0; i < aux_info.groups; ++i) {
2364 SLOGI("Encrypting group %d", i);
2365
2366 u32 first_block = aux_info.first_data_block + i * info.blocks_per_group;
2367 u32 block_count = min(info.blocks_per_group,
2368 aux_info.len_blocks - first_block);
2369
2370 off64_t offset = (u64)info.block_size
2371 * aux_info.bg_desc[i].bg_block_bitmap;
2372
2373 ret = pread64(data->realfd, block_bitmap, info.block_size, offset);
2374 if (ret != (int)info.block_size) {
2375 SLOGE("failed to read all of block group bitmap %d", i);
2376 goto errout;
2377 }
2378
2379 offset = (u64)info.block_size * first_block;
2380
2381 data->count = 0;
2382
2383 for (block = 0; block < block_count; block++) {
Paul Lawrence58c58cf2014-06-04 13:12:21 -07002384 int used = bitmap_get_bit(block_bitmap, block);
2385 update_progress(data, used);
2386 if (used) {
Paul Lawrenceae59fe62014-01-21 08:23:27 -08002387 if (data->count == 0) {
2388 data->offset = offset;
2389 }
2390 data->count++;
2391 } else {
2392 if (flush_outstanding_data(data)) {
2393 goto errout;
2394 }
2395 }
2396
2397 offset += info.block_size;
2398
2399 /* Write data if we are aligned or buffer size reached */
2400 if (offset % (info.block_size * BLOCKS_AT_A_TIME) == 0
2401 || data->count == BLOCKS_AT_A_TIME) {
2402 if (flush_outstanding_data(data)) {
2403 goto errout;
2404 }
2405 }
Paul Lawrence87999172014-02-20 12:21:31 -08002406
Paul Lawrence73d7a022014-06-09 14:10:09 -07002407 if (!is_battery_ok_to_continue()) {
Paul Lawrence87999172014-02-20 12:21:31 -08002408 SLOGE("Stopping encryption due to low battery");
2409 rc = 0;
2410 goto errout;
2411 }
2412
Paul Lawrenceae59fe62014-01-21 08:23:27 -08002413 }
2414 if (flush_outstanding_data(data)) {
2415 goto errout;
2416 }
2417 }
2418
Paul Lawrence87999172014-02-20 12:21:31 -08002419 data->completed = 1;
Paul Lawrenceae59fe62014-01-21 08:23:27 -08002420 rc = 0;
2421
2422errout:
Paul Lawrence3846be12014-09-22 11:33:54 -07002423 log_progress(0, true);
Paul Lawrenceae59fe62014-01-21 08:23:27 -08002424 free(data->buffer);
2425 free(block_bitmap);
2426 return rc;
2427}
2428
2429static int cryptfs_enable_inplace_ext4(char *crypto_blkdev,
2430 char *real_blkdev,
2431 off64_t size,
2432 off64_t *size_already_done,
Paul Lawrence87999172014-02-20 12:21:31 -08002433 off64_t tot_size,
2434 off64_t previously_encrypted_upto)
Paul Lawrenceae59fe62014-01-21 08:23:27 -08002435{
Paul Lawrence58c58cf2014-06-04 13:12:21 -07002436 u32 i;
Paul Lawrenceae59fe62014-01-21 08:23:27 -08002437 struct encryptGroupsData data;
Paul Lawrence74f29f12014-08-28 15:54:10 -07002438 int rc; // Can't initialize without causing warning -Wclobbered
Paul Lawrenceae59fe62014-01-21 08:23:27 -08002439
Paul Lawrence87999172014-02-20 12:21:31 -08002440 if (previously_encrypted_upto > *size_already_done) {
2441 SLOGD("Not fast encrypting since resuming part way through");
2442 return -1;
2443 }
2444
Paul Lawrenceae59fe62014-01-21 08:23:27 -08002445 memset(&data, 0, sizeof(data));
2446 data.real_blkdev = real_blkdev;
2447 data.crypto_blkdev = crypto_blkdev;
2448
2449 if ( (data.realfd = open(real_blkdev, O_RDWR)) < 0) {
JP Abgrall3334c6a2014-10-10 15:52:11 -07002450 SLOGE("Error opening real_blkdev %s for inplace encrypt. err=%d(%s)\n",
2451 real_blkdev, errno, strerror(errno));
Paul Lawrence74f29f12014-08-28 15:54:10 -07002452 rc = -1;
Paul Lawrenceae59fe62014-01-21 08:23:27 -08002453 goto errout;
2454 }
2455
2456 if ( (data.cryptofd = open(crypto_blkdev, O_WRONLY)) < 0) {
JP Abgrall7fc1de82014-10-10 18:43:41 -07002457 SLOGE("Error opening crypto_blkdev %s for ext4 inplace encrypt. err=%d(%s)\n",
JP Abgrall3334c6a2014-10-10 15:52:11 -07002458 crypto_blkdev, errno, strerror(errno));
JP Abgrall7fc1de82014-10-10 18:43:41 -07002459 rc = ENABLE_INPLACE_ERR_DEV;
Paul Lawrenceae59fe62014-01-21 08:23:27 -08002460 goto errout;
2461 }
2462
2463 if (setjmp(setjmp_env)) {
JP Abgrall7fc1de82014-10-10 18:43:41 -07002464 SLOGE("Reading ext4 extent caused an exception\n");
Paul Lawrence74f29f12014-08-28 15:54:10 -07002465 rc = -1;
Paul Lawrenceae59fe62014-01-21 08:23:27 -08002466 goto errout;
2467 }
2468
2469 if (read_ext(data.realfd, 0) != 0) {
JP Abgrall7fc1de82014-10-10 18:43:41 -07002470 SLOGE("Failed to read ext4 extent\n");
Paul Lawrence74f29f12014-08-28 15:54:10 -07002471 rc = -1;
Paul Lawrenceae59fe62014-01-21 08:23:27 -08002472 goto errout;
2473 }
2474
2475 data.numblocks = size / CRYPT_SECTORS_PER_BUFSIZE;
2476 data.tot_numblocks = tot_size / CRYPT_SECTORS_PER_BUFSIZE;
2477 data.blocks_already_done = *size_already_done / CRYPT_SECTORS_PER_BUFSIZE;
2478
JP Abgrall7fc1de82014-10-10 18:43:41 -07002479 SLOGI("Encrypting ext4 filesystem in place...");
Paul Lawrenceae59fe62014-01-21 08:23:27 -08002480
Paul Lawrence58c58cf2014-06-04 13:12:21 -07002481 data.tot_used_blocks = data.numblocks;
2482 for (i = 0; i < aux_info.groups; ++i) {
2483 data.tot_used_blocks -= aux_info.bg_desc[i].bg_free_blocks_count;
2484 }
2485
2486 data.one_pct = data.tot_used_blocks / 100;
Paul Lawrenceae59fe62014-01-21 08:23:27 -08002487 data.cur_pct = 0;
Paul Lawrence9c58a872014-09-30 09:12:51 -07002488
2489 struct timespec time_started = {0};
2490 if (clock_gettime(CLOCK_MONOTONIC, &time_started)) {
2491 SLOGW("Error getting time at start");
2492 // Note - continue anyway - we'll run with 0
2493 }
2494 data.time_started = time_started.tv_sec;
Paul Lawrencea96d9c92014-06-04 14:05:01 -07002495 data.remaining_time = -1;
Paul Lawrenceae59fe62014-01-21 08:23:27 -08002496
2497 rc = encrypt_groups(&data);
2498 if (rc) {
2499 SLOGE("Error encrypting groups");
2500 goto errout;
2501 }
2502
Paul Lawrence87999172014-02-20 12:21:31 -08002503 *size_already_done += data.completed ? size : data.last_written_sector;
Paul Lawrenceae59fe62014-01-21 08:23:27 -08002504 rc = 0;
2505
2506errout:
2507 close(data.realfd);
2508 close(data.cryptofd);
2509
2510 return rc;
2511}
2512
Paul Lawrence3846be12014-09-22 11:33:54 -07002513static void log_progress_f2fs(u64 block, bool completed)
2514{
2515 // Precondition - if completed data = 0 else data != 0
2516
2517 // Track progress so we can skip logging blocks
2518 static u64 last_block = (u64)-1;
2519
2520 // Need to close existing 'Encrypting from' log?
2521 if (completed || (last_block != (u64)-1 && block != last_block + 1)) {
2522 SLOGI("Encrypted to block %" PRId64, last_block);
2523 last_block = -1;
2524 }
2525
2526 // Need to start new 'Encrypting from' log?
2527 if (!completed && (last_block == (u64)-1 || block != last_block + 1)) {
2528 SLOGI("Encrypting from block %" PRId64, block);
2529 }
2530
2531 // Update offset
2532 if (!completed) {
2533 last_block = block;
2534 }
2535}
2536
Daniel Rosenberge82df162014-08-15 22:19:23 +00002537static int encrypt_one_block_f2fs(u64 pos, void *data)
2538{
2539 struct encryptGroupsData *priv_dat = (struct encryptGroupsData *)data;
2540
2541 priv_dat->blocks_already_done = pos - 1;
2542 update_progress(priv_dat, 1);
2543
2544 off64_t offset = pos * CRYPT_INPLACE_BUFSIZE;
2545
2546 if (pread64(priv_dat->realfd, priv_dat->buffer, CRYPT_INPLACE_BUFSIZE, offset) <= 0) {
JP Abgrall7fc1de82014-10-10 18:43:41 -07002547 SLOGE("Error reading real_blkdev %s for f2fs inplace encrypt", priv_dat->crypto_blkdev);
Daniel Rosenberge82df162014-08-15 22:19:23 +00002548 return -1;
2549 }
2550
2551 if (pwrite64(priv_dat->cryptofd, priv_dat->buffer, CRYPT_INPLACE_BUFSIZE, offset) <= 0) {
JP Abgrall7fc1de82014-10-10 18:43:41 -07002552 SLOGE("Error writing crypto_blkdev %s for f2fs inplace encrypt", priv_dat->crypto_blkdev);
Daniel Rosenberge82df162014-08-15 22:19:23 +00002553 return -1;
2554 } else {
Paul Lawrence3846be12014-09-22 11:33:54 -07002555 log_progress_f2fs(pos, false);
Daniel Rosenberge82df162014-08-15 22:19:23 +00002556 }
2557
2558 return 0;
2559}
2560
2561static int cryptfs_enable_inplace_f2fs(char *crypto_blkdev,
2562 char *real_blkdev,
2563 off64_t size,
2564 off64_t *size_already_done,
2565 off64_t tot_size,
2566 off64_t previously_encrypted_upto)
2567{
Daniel Rosenberge82df162014-08-15 22:19:23 +00002568 struct encryptGroupsData data;
2569 struct f2fs_info *f2fs_info = NULL;
JP Abgrall7fc1de82014-10-10 18:43:41 -07002570 int rc = ENABLE_INPLACE_ERR_OTHER;
Daniel Rosenberge82df162014-08-15 22:19:23 +00002571 if (previously_encrypted_upto > *size_already_done) {
2572 SLOGD("Not fast encrypting since resuming part way through");
JP Abgrall7fc1de82014-10-10 18:43:41 -07002573 return ENABLE_INPLACE_ERR_OTHER;
Daniel Rosenberge82df162014-08-15 22:19:23 +00002574 }
2575 memset(&data, 0, sizeof(data));
2576 data.real_blkdev = real_blkdev;
2577 data.crypto_blkdev = crypto_blkdev;
2578 data.realfd = -1;
2579 data.cryptofd = -1;
2580 if ( (data.realfd = open64(real_blkdev, O_RDWR)) < 0) {
JP Abgrall7fc1de82014-10-10 18:43:41 -07002581 SLOGE("Error opening real_blkdev %s for f2fs inplace encrypt\n",
Daniel Rosenberge82df162014-08-15 22:19:23 +00002582 real_blkdev);
2583 goto errout;
2584 }
2585 if ( (data.cryptofd = open64(crypto_blkdev, O_WRONLY)) < 0) {
JP Abgrall7fc1de82014-10-10 18:43:41 -07002586 SLOGE("Error opening crypto_blkdev %s for f2fs inplace encrypt. err=%d(%s)\n",
JP Abgrall3334c6a2014-10-10 15:52:11 -07002587 crypto_blkdev, errno, strerror(errno));
JP Abgrall7fc1de82014-10-10 18:43:41 -07002588 rc = ENABLE_INPLACE_ERR_DEV;
Daniel Rosenberge82df162014-08-15 22:19:23 +00002589 goto errout;
2590 }
2591
2592 f2fs_info = generate_f2fs_info(data.realfd);
2593 if (!f2fs_info)
2594 goto errout;
2595
2596 data.numblocks = size / CRYPT_SECTORS_PER_BUFSIZE;
2597 data.tot_numblocks = tot_size / CRYPT_SECTORS_PER_BUFSIZE;
2598 data.blocks_already_done = *size_already_done / CRYPT_SECTORS_PER_BUFSIZE;
2599
2600 data.tot_used_blocks = get_num_blocks_used(f2fs_info);
2601
2602 data.one_pct = data.tot_used_blocks / 100;
2603 data.cur_pct = 0;
2604 data.time_started = time(NULL);
2605 data.remaining_time = -1;
2606
2607 data.buffer = malloc(f2fs_info->block_size);
2608 if (!data.buffer) {
2609 SLOGE("Failed to allocate crypto buffer");
2610 goto errout;
2611 }
2612
2613 data.count = 0;
2614
2615 /* Currently, this either runs to completion, or hits a nonrecoverable error */
2616 rc = run_on_used_blocks(data.blocks_already_done, f2fs_info, &encrypt_one_block_f2fs, &data);
2617
2618 if (rc) {
JP Abgrall7fc1de82014-10-10 18:43:41 -07002619 SLOGE("Error in running over f2fs blocks");
2620 rc = ENABLE_INPLACE_ERR_OTHER;
Daniel Rosenberge82df162014-08-15 22:19:23 +00002621 goto errout;
2622 }
2623
2624 *size_already_done += size;
2625 rc = 0;
2626
2627errout:
2628 if (rc)
2629 SLOGE("Failed to encrypt f2fs filesystem on %s", real_blkdev);
2630
Paul Lawrence3846be12014-09-22 11:33:54 -07002631 log_progress_f2fs(0, true);
Daniel Rosenberge82df162014-08-15 22:19:23 +00002632 free(f2fs_info);
2633 free(data.buffer);
2634 close(data.realfd);
2635 close(data.cryptofd);
2636
2637 return rc;
2638}
2639
Paul Lawrenceae59fe62014-01-21 08:23:27 -08002640static int cryptfs_enable_inplace_full(char *crypto_blkdev, char *real_blkdev,
2641 off64_t size, off64_t *size_already_done,
Paul Lawrence87999172014-02-20 12:21:31 -08002642 off64_t tot_size,
2643 off64_t previously_encrypted_upto)
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002644{
2645 int realfd, cryptofd;
2646 char *buf[CRYPT_INPLACE_BUFSIZE];
JP Abgrall7fc1de82014-10-10 18:43:41 -07002647 int rc = ENABLE_INPLACE_ERR_OTHER;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002648 off64_t numblocks, i, remainder;
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002649 off64_t one_pct, cur_pct, new_pct;
Ken Sumrall29d8da82011-05-18 17:20:07 -07002650 off64_t blocks_already_done, tot_numblocks;
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002651
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002652 if ( (realfd = open(real_blkdev, O_RDONLY)) < 0) {
2653 SLOGE("Error opening real_blkdev %s for inplace encrypt\n", real_blkdev);
JP Abgrall7fc1de82014-10-10 18:43:41 -07002654 return ENABLE_INPLACE_ERR_OTHER;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002655 }
2656
2657 if ( (cryptofd = open(crypto_blkdev, O_WRONLY)) < 0) {
JP Abgrall3334c6a2014-10-10 15:52:11 -07002658 SLOGE("Error opening crypto_blkdev %s for inplace encrypt. err=%d(%s)\n",
2659 crypto_blkdev, errno, strerror(errno));
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002660 close(realfd);
JP Abgrall7fc1de82014-10-10 18:43:41 -07002661 return ENABLE_INPLACE_ERR_DEV;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002662 }
2663
2664 /* This is pretty much a simple loop of reading 4K, and writing 4K.
2665 * The size passed in is the number of 512 byte sectors in the filesystem.
2666 * So compute the number of whole 4K blocks we should read/write,
2667 * and the remainder.
2668 */
2669 numblocks = size / CRYPT_SECTORS_PER_BUFSIZE;
2670 remainder = size % CRYPT_SECTORS_PER_BUFSIZE;
Ken Sumrall29d8da82011-05-18 17:20:07 -07002671 tot_numblocks = tot_size / CRYPT_SECTORS_PER_BUFSIZE;
2672 blocks_already_done = *size_already_done / CRYPT_SECTORS_PER_BUFSIZE;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002673
2674 SLOGE("Encrypting filesystem in place...");
2675
Paul Lawrence87999172014-02-20 12:21:31 -08002676 i = previously_encrypted_upto + 1 - *size_already_done;
2677
2678 if (lseek64(realfd, i * CRYPT_SECTOR_SIZE, SEEK_SET) < 0) {
2679 SLOGE("Cannot seek to previously encrypted point on %s", real_blkdev);
2680 goto errout;
2681 }
2682
2683 if (lseek64(cryptofd, i * CRYPT_SECTOR_SIZE, SEEK_SET) < 0) {
2684 SLOGE("Cannot seek to previously encrypted point on %s", crypto_blkdev);
2685 goto errout;
2686 }
2687
2688 for (;i < size && i % CRYPT_SECTORS_PER_BUFSIZE != 0; ++i) {
2689 if (unix_read(realfd, buf, CRYPT_SECTOR_SIZE) <= 0) {
2690 SLOGE("Error reading initial sectors from real_blkdev %s for "
2691 "inplace encrypt\n", crypto_blkdev);
2692 goto errout;
2693 }
2694 if (unix_write(cryptofd, buf, CRYPT_SECTOR_SIZE) <= 0) {
2695 SLOGE("Error writing initial sectors to crypto_blkdev %s for "
2696 "inplace encrypt\n", crypto_blkdev);
2697 goto errout;
2698 } else {
Elliott Hughescb33f572014-06-25 18:25:11 -07002699 SLOGI("Encrypted 1 block at %" PRId64, i);
Paul Lawrence87999172014-02-20 12:21:31 -08002700 }
2701 }
2702
Ken Sumrall29d8da82011-05-18 17:20:07 -07002703 one_pct = tot_numblocks / 100;
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002704 cur_pct = 0;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002705 /* process the majority of the filesystem in blocks */
Paul Lawrence87999172014-02-20 12:21:31 -08002706 for (i/=CRYPT_SECTORS_PER_BUFSIZE; i<numblocks; i++) {
Ken Sumrall29d8da82011-05-18 17:20:07 -07002707 new_pct = (i + blocks_already_done) / one_pct;
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002708 if (new_pct > cur_pct) {
2709 char buf[8];
2710
2711 cur_pct = new_pct;
Elliott Hughes73737162014-06-25 17:27:42 -07002712 snprintf(buf, sizeof(buf), "%" PRId64, cur_pct);
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002713 property_set("vold.encrypt_progress", buf);
2714 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002715 if (unix_read(realfd, buf, CRYPT_INPLACE_BUFSIZE) <= 0) {
Paul Lawrence87999172014-02-20 12:21:31 -08002716 SLOGE("Error reading real_blkdev %s for inplace encrypt", crypto_blkdev);
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002717 goto errout;
2718 }
2719 if (unix_write(cryptofd, buf, CRYPT_INPLACE_BUFSIZE) <= 0) {
Paul Lawrence87999172014-02-20 12:21:31 -08002720 SLOGE("Error writing crypto_blkdev %s for inplace encrypt", crypto_blkdev);
2721 goto errout;
2722 } else {
Elliott Hughescb33f572014-06-25 18:25:11 -07002723 SLOGD("Encrypted %d block at %" PRId64,
Paul Lawrence87999172014-02-20 12:21:31 -08002724 CRYPT_SECTORS_PER_BUFSIZE,
2725 i * CRYPT_SECTORS_PER_BUFSIZE);
2726 }
2727
Paul Lawrence73d7a022014-06-09 14:10:09 -07002728 if (!is_battery_ok_to_continue()) {
Paul Lawrence87999172014-02-20 12:21:31 -08002729 SLOGE("Stopping encryption due to low battery");
2730 *size_already_done += (i + 1) * CRYPT_SECTORS_PER_BUFSIZE - 1;
2731 rc = 0;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002732 goto errout;
2733 }
2734 }
2735
2736 /* Do any remaining sectors */
2737 for (i=0; i<remainder; i++) {
Paul Lawrence87999172014-02-20 12:21:31 -08002738 if (unix_read(realfd, buf, CRYPT_SECTOR_SIZE) <= 0) {
2739 SLOGE("Error reading final sectors from real_blkdev %s for inplace encrypt", crypto_blkdev);
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002740 goto errout;
2741 }
Paul Lawrence87999172014-02-20 12:21:31 -08002742 if (unix_write(cryptofd, buf, CRYPT_SECTOR_SIZE) <= 0) {
2743 SLOGE("Error writing final sectors to crypto_blkdev %s for inplace encrypt", crypto_blkdev);
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002744 goto errout;
Paul Lawrence87999172014-02-20 12:21:31 -08002745 } else {
2746 SLOGI("Encrypted 1 block at next location");
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002747 }
2748 }
2749
Ken Sumrall29d8da82011-05-18 17:20:07 -07002750 *size_already_done += size;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002751 rc = 0;
2752
2753errout:
2754 close(realfd);
2755 close(cryptofd);
2756
2757 return rc;
2758}
2759
JP Abgrall7fc1de82014-10-10 18:43:41 -07002760/* returns on of the ENABLE_INPLACE_* return codes */
Paul Lawrenceae59fe62014-01-21 08:23:27 -08002761static int cryptfs_enable_inplace(char *crypto_blkdev, char *real_blkdev,
2762 off64_t size, off64_t *size_already_done,
Paul Lawrence87999172014-02-20 12:21:31 -08002763 off64_t tot_size,
2764 off64_t previously_encrypted_upto)
Paul Lawrenceae59fe62014-01-21 08:23:27 -08002765{
JP Abgrall7fc1de82014-10-10 18:43:41 -07002766 int rc_ext4, rc_f2fs, rc_full;
Paul Lawrence87999172014-02-20 12:21:31 -08002767 if (previously_encrypted_upto) {
Elliott Hughescb33f572014-06-25 18:25:11 -07002768 SLOGD("Continuing encryption from %" PRId64, previously_encrypted_upto);
Paul Lawrence87999172014-02-20 12:21:31 -08002769 }
2770
2771 if (*size_already_done + size < previously_encrypted_upto) {
2772 *size_already_done += size;
2773 return 0;
2774 }
2775
Daniel Rosenberge82df162014-08-15 22:19:23 +00002776 /* TODO: identify filesystem type.
2777 * As is, cryptfs_enable_inplace_ext4 will fail on an f2fs partition, and
2778 * then we will drop down to cryptfs_enable_inplace_f2fs.
2779 * */
JP Abgrall7fc1de82014-10-10 18:43:41 -07002780 if ((rc_ext4 = cryptfs_enable_inplace_ext4(crypto_blkdev, real_blkdev,
Daniel Rosenberge82df162014-08-15 22:19:23 +00002781 size, size_already_done,
JP Abgrall7fc1de82014-10-10 18:43:41 -07002782 tot_size, previously_encrypted_upto)) == 0) {
Daniel Rosenberge82df162014-08-15 22:19:23 +00002783 return 0;
2784 }
JP Abgrall7fc1de82014-10-10 18:43:41 -07002785 SLOGD("cryptfs_enable_inplace_ext4()=%d\n", rc_ext4);
Daniel Rosenberge82df162014-08-15 22:19:23 +00002786
JP Abgrall7fc1de82014-10-10 18:43:41 -07002787 if ((rc_f2fs = cryptfs_enable_inplace_f2fs(crypto_blkdev, real_blkdev,
Daniel Rosenberge82df162014-08-15 22:19:23 +00002788 size, size_already_done,
JP Abgrall7fc1de82014-10-10 18:43:41 -07002789 tot_size, previously_encrypted_upto)) == 0) {
Daniel Rosenberge82df162014-08-15 22:19:23 +00002790 return 0;
Paul Lawrenceae59fe62014-01-21 08:23:27 -08002791 }
JP Abgrall7fc1de82014-10-10 18:43:41 -07002792 SLOGD("cryptfs_enable_inplace_f2fs()=%d\n", rc_f2fs);
Paul Lawrenceae59fe62014-01-21 08:23:27 -08002793
JP Abgrall7fc1de82014-10-10 18:43:41 -07002794 rc_full = cryptfs_enable_inplace_full(crypto_blkdev, real_blkdev,
Paul Lawrence87999172014-02-20 12:21:31 -08002795 size, size_already_done, tot_size,
2796 previously_encrypted_upto);
JP Abgrall7fc1de82014-10-10 18:43:41 -07002797 SLOGD("cryptfs_enable_inplace_full()=%d\n", rc_full);
2798
2799 /* Hack for b/17898962, the following is the symptom... */
2800 if (rc_ext4 == ENABLE_INPLACE_ERR_DEV
2801 && rc_f2fs == ENABLE_INPLACE_ERR_DEV
2802 && rc_full == ENABLE_INPLACE_ERR_DEV) {
2803 return ENABLE_INPLACE_ERR_DEV;
2804 }
2805 return rc_full;
Paul Lawrenceae59fe62014-01-21 08:23:27 -08002806}
2807
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002808#define CRYPTO_ENABLE_WIPE 1
2809#define CRYPTO_ENABLE_INPLACE 2
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002810
2811#define FRAMEWORK_BOOT_WAIT 60
2812
Ken Sumrall29d8da82011-05-18 17:20:07 -07002813static inline int should_encrypt(struct volume_info *volume)
2814{
Paul Lawrenceae59fe62014-01-21 08:23:27 -08002815 return (volume->flags & (VOL_ENCRYPTABLE | VOL_NONREMOVABLE)) ==
Ken Sumrall29d8da82011-05-18 17:20:07 -07002816 (VOL_ENCRYPTABLE | VOL_NONREMOVABLE);
2817}
2818
Paul Lawrence87999172014-02-20 12:21:31 -08002819static int cryptfs_SHA256_fileblock(const char* filename, __le8* buf)
2820{
2821 int fd = open(filename, O_RDONLY);
2822 if (fd == -1) {
2823 SLOGE("Error opening file %s", filename);
2824 return -1;
2825 }
2826
2827 char block[CRYPT_INPLACE_BUFSIZE];
2828 memset(block, 0, sizeof(block));
2829 if (unix_read(fd, block, sizeof(block)) < 0) {
2830 SLOGE("Error reading file %s", filename);
2831 close(fd);
2832 return -1;
2833 }
2834
2835 close(fd);
2836
2837 SHA256_CTX c;
2838 SHA256_Init(&c);
2839 SHA256_Update(&c, block, sizeof(block));
2840 SHA256_Final(buf, &c);
2841
2842 return 0;
2843}
2844
JP Abgrall62c7af32014-06-16 13:01:23 -07002845static int get_fs_type(struct fstab_rec *rec)
2846{
2847 if (!strcmp(rec->fs_type, "ext4")) {
2848 return EXT4_FS;
2849 } else if (!strcmp(rec->fs_type, "f2fs")) {
2850 return F2FS_FS;
2851 } else {
2852 return -1;
2853 }
2854}
2855
Paul Lawrence87999172014-02-20 12:21:31 -08002856static int cryptfs_enable_all_volumes(struct crypt_mnt_ftr *crypt_ftr, int how,
2857 char *crypto_blkdev, char *real_blkdev,
2858 int previously_encrypted_upto)
2859{
2860 off64_t cur_encryption_done=0, tot_encryption_size=0;
Tim Murray8439dc92014-12-15 11:56:11 -08002861 int rc = -1;
Paul Lawrence87999172014-02-20 12:21:31 -08002862
Paul Lawrence73d7a022014-06-09 14:10:09 -07002863 if (!is_battery_ok_to_start()) {
2864 SLOGW("Not starting encryption due to low battery");
Paul Lawrence87999172014-02-20 12:21:31 -08002865 return 0;
2866 }
2867
2868 /* The size of the userdata partition, and add in the vold volumes below */
2869 tot_encryption_size = crypt_ftr->fs_size;
2870
2871 if (how == CRYPTO_ENABLE_WIPE) {
JP Abgrall62c7af32014-06-16 13:01:23 -07002872 struct fstab_rec* rec = fs_mgr_get_entry_for_mount_point(fstab, DATA_MNT_POINT);
2873 int fs_type = get_fs_type(rec);
2874 if (fs_type < 0) {
2875 SLOGE("cryptfs_enable: unsupported fs type %s\n", rec->fs_type);
2876 return -1;
2877 }
2878 rc = cryptfs_enable_wipe(crypto_blkdev, crypt_ftr->fs_size, fs_type);
Paul Lawrence87999172014-02-20 12:21:31 -08002879 } else if (how == CRYPTO_ENABLE_INPLACE) {
2880 rc = cryptfs_enable_inplace(crypto_blkdev, real_blkdev,
2881 crypt_ftr->fs_size, &cur_encryption_done,
2882 tot_encryption_size,
2883 previously_encrypted_upto);
2884
JP Abgrall7fc1de82014-10-10 18:43:41 -07002885 if (rc == ENABLE_INPLACE_ERR_DEV) {
2886 /* Hack for b/17898962 */
2887 SLOGE("cryptfs_enable: crypto block dev failure. Must reboot...\n");
2888 cryptfs_reboot(reboot);
2889 }
2890
Paul Lawrence73d7a022014-06-09 14:10:09 -07002891 if (!rc) {
Paul Lawrence87999172014-02-20 12:21:31 -08002892 crypt_ftr->encrypted_upto = cur_encryption_done;
2893 }
2894
Paul Lawrence73d7a022014-06-09 14:10:09 -07002895 if (!rc && crypt_ftr->encrypted_upto == crypt_ftr->fs_size) {
Paul Lawrence87999172014-02-20 12:21:31 -08002896 /* The inplace routine never actually sets the progress to 100% due
2897 * to the round down nature of integer division, so set it here */
2898 property_set("vold.encrypt_progress", "100");
2899 }
2900 } else {
2901 /* Shouldn't happen */
2902 SLOGE("cryptfs_enable: internal error, unknown option\n");
2903 rc = -1;
2904 }
2905
2906 return rc;
2907}
2908
Paul Lawrence13486032014-02-03 13:28:11 -08002909int cryptfs_enable_internal(char *howarg, int crypt_type, char *passwd,
2910 int allow_reboot)
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002911{
2912 int how = 0;
Paul Lawrence87999172014-02-20 12:21:31 -08002913 char crypto_blkdev[MAXPATHLEN], real_blkdev[MAXPATHLEN];
Ken Sumralle5032c42012-04-01 23:58:44 -07002914 unsigned long nr_sec;
Ken Sumrall160b4d62013-04-22 12:15:39 -07002915 unsigned char decrypted_master_key[KEY_LEN_BYTES];
Tim Murray8439dc92014-12-15 11:56:11 -08002916 int rc=-1, fd, i;
Paul Lawrence87999172014-02-20 12:21:31 -08002917 struct crypt_mnt_ftr crypt_ftr;
Ken Sumrall160b4d62013-04-22 12:15:39 -07002918 struct crypt_persist_data *pdata;
Ken Sumrall29d8da82011-05-18 17:20:07 -07002919 char encrypted_state[PROPERTY_VALUE_MAX];
Ken Sumrall5d4c68e2011-01-30 19:06:03 -08002920 char lockid[32] = { 0 };
Ken Sumrall29d8da82011-05-18 17:20:07 -07002921 char key_loc[PROPERTY_VALUE_MAX];
2922 char fuse_sdcard[PROPERTY_VALUE_MAX];
2923 char *sd_mnt_point;
Ken Sumrall29d8da82011-05-18 17:20:07 -07002924 int num_vols;
2925 struct volume_info *vol_list = 0;
Paul Lawrence87999172014-02-20 12:21:31 -08002926 off64_t previously_encrypted_upto = 0;
Ken Sumrall29d8da82011-05-18 17:20:07 -07002927
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002928 if (!strcmp(howarg, "wipe")) {
2929 how = CRYPTO_ENABLE_WIPE;
2930 } else if (! strcmp(howarg, "inplace")) {
2931 how = CRYPTO_ENABLE_INPLACE;
2932 } else {
2933 /* Shouldn't happen, as CommandListener vets the args */
Ken Sumrall3ed82362011-01-28 23:31:16 -08002934 goto error_unencrypted;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002935 }
2936
Paul Lawrence87999172014-02-20 12:21:31 -08002937 /* See if an encryption was underway and interrupted */
2938 if (how == CRYPTO_ENABLE_INPLACE
2939 && get_crypt_ftr_and_key(&crypt_ftr) == 0
2940 && (crypt_ftr.flags & CRYPT_ENCRYPTION_IN_PROGRESS)) {
2941 previously_encrypted_upto = crypt_ftr.encrypted_upto;
2942 crypt_ftr.encrypted_upto = 0;
Paul Lawrence6bfed202014-07-28 12:47:22 -07002943 crypt_ftr.flags &= ~CRYPT_ENCRYPTION_IN_PROGRESS;
2944
2945 /* At this point, we are in an inconsistent state. Until we successfully
2946 complete encryption, a reboot will leave us broken. So mark the
2947 encryption failed in case that happens.
2948 On successfully completing encryption, remove this flag */
2949 crypt_ftr.flags |= CRYPT_INCONSISTENT_STATE;
2950
2951 put_crypt_ftr_and_key(&crypt_ftr);
Paul Lawrence87999172014-02-20 12:21:31 -08002952 }
2953
2954 property_get("ro.crypto.state", encrypted_state, "");
2955 if (!strcmp(encrypted_state, "encrypted") && !previously_encrypted_upto) {
2956 SLOGE("Device is already running encrypted, aborting");
2957 goto error_unencrypted;
2958 }
2959
2960 // TODO refactor fs_mgr_get_crypt_info to get both in one call
2961 fs_mgr_get_crypt_info(fstab, key_loc, 0, sizeof(key_loc));
Ken Sumrall56ad03c2013-02-13 13:00:19 -08002962 fs_mgr_get_crypt_info(fstab, 0, real_blkdev, sizeof(real_blkdev));
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002963
Ken Sumrall3ed82362011-01-28 23:31:16 -08002964 /* Get the size of the real block device */
2965 fd = open(real_blkdev, O_RDONLY);
2966 if ( (nr_sec = get_blkdev_size(fd)) == 0) {
2967 SLOGE("Cannot get size of block device %s\n", real_blkdev);
2968 goto error_unencrypted;
2969 }
2970 close(fd);
2971
2972 /* If doing inplace encryption, make sure the orig fs doesn't include the crypto footer */
Ken Sumrall29d8da82011-05-18 17:20:07 -07002973 if ((how == CRYPTO_ENABLE_INPLACE) && (!strcmp(key_loc, KEY_IN_FOOTER))) {
Ken Sumrall3ed82362011-01-28 23:31:16 -08002974 unsigned int fs_size_sec, max_fs_size_sec;
Jim Millera70abc62014-08-15 02:00:45 +00002975 fs_size_sec = get_fs_size(real_blkdev);
Daniel Rosenberge82df162014-08-15 22:19:23 +00002976 if (fs_size_sec == 0)
2977 fs_size_sec = get_f2fs_filesystem_size_sec(real_blkdev);
2978
Paul Lawrence87999172014-02-20 12:21:31 -08002979 max_fs_size_sec = nr_sec - (CRYPT_FOOTER_OFFSET / CRYPT_SECTOR_SIZE);
Ken Sumrall3ed82362011-01-28 23:31:16 -08002980
2981 if (fs_size_sec > max_fs_size_sec) {
2982 SLOGE("Orig filesystem overlaps crypto footer region. Cannot encrypt in place.");
2983 goto error_unencrypted;
2984 }
2985 }
2986
Ken Sumrall5d4c68e2011-01-30 19:06:03 -08002987 /* Get a wakelock as this may take a while, and we don't want the
2988 * device to sleep on us. We'll grab a partial wakelock, and if the UI
2989 * wants to keep the screen on, it can grab a full wakelock.
2990 */
Ken Sumrall29d8da82011-05-18 17:20:07 -07002991 snprintf(lockid, sizeof(lockid), "enablecrypto%d", (int) getpid());
Ken Sumrall5d4c68e2011-01-30 19:06:03 -08002992 acquire_wake_lock(PARTIAL_WAKE_LOCK, lockid);
2993
Jeff Sharkey7382f812012-08-23 14:08:59 -07002994 /* Get the sdcard mount point */
Jeff Sharkeyb77bc462012-10-01 14:36:26 -07002995 sd_mnt_point = getenv("EMULATED_STORAGE_SOURCE");
Jeff Sharkey7382f812012-08-23 14:08:59 -07002996 if (!sd_mnt_point) {
2997 sd_mnt_point = getenv("EXTERNAL_STORAGE");
2998 }
2999 if (!sd_mnt_point) {
3000 sd_mnt_point = "/mnt/sdcard";
3001 }
Ken Sumrall29d8da82011-05-18 17:20:07 -07003002
Paul Lawrence87999172014-02-20 12:21:31 -08003003 /* TODO
3004 * Currently do not have test devices with multiple encryptable volumes.
3005 * When we acquire some, re-add support.
3006 */
Ken Sumrall29d8da82011-05-18 17:20:07 -07003007 num_vols=vold_getNumDirectVolumes();
3008 vol_list = malloc(sizeof(struct volume_info) * num_vols);
3009 vold_getDirectVolumeList(vol_list);
3010
3011 for (i=0; i<num_vols; i++) {
3012 if (should_encrypt(&vol_list[i])) {
Paul Lawrence87999172014-02-20 12:21:31 -08003013 SLOGE("Cannot encrypt if there are multiple encryptable volumes"
3014 "%s\n", vol_list[i].label);
3015 goto error_unencrypted;
Ken Sumrall29d8da82011-05-18 17:20:07 -07003016 }
3017 }
3018
Ken Sumrall8f869aa2010-12-03 03:47:09 -08003019 /* The init files are setup to stop the class main and late start when
Ken Sumrall8ddbe402011-01-17 15:26:29 -08003020 * vold sets trigger_shutdown_framework.
Ken Sumrall8f869aa2010-12-03 03:47:09 -08003021 */
3022 property_set("vold.decrypt", "trigger_shutdown_framework");
3023 SLOGD("Just asked init to shut down class main\n");
3024
Ken Sumrall425524d2012-06-14 20:55:28 -07003025 if (vold_unmountAllAsecs()) {
3026 /* Just report the error. If any are left mounted,
3027 * umounting /data below will fail and handle the error.
3028 */
3029 SLOGE("Error unmounting internal asecs");
3030 }
3031
Ken Sumrall29d8da82011-05-18 17:20:07 -07003032 property_get("ro.crypto.fuse_sdcard", fuse_sdcard, "");
3033 if (!strcmp(fuse_sdcard, "true")) {
3034 /* This is a device using the fuse layer to emulate the sdcard semantics
3035 * on top of the userdata partition. vold does not manage it, it is managed
3036 * by the sdcard service. The sdcard service was killed by the property trigger
3037 * above, so just unmount it now. We must do this _AFTER_ killing the framework,
3038 * unlike the case for vold managed devices above.
3039 */
Greg Hackmann6e8440f2014-10-02 17:18:20 -07003040 if (wait_and_unmount(sd_mnt_point, false)) {
Ken Sumrall29d8da82011-05-18 17:20:07 -07003041 goto error_shutting_down;
3042 }
Ken Sumrall2eaf7132011-01-14 12:45:48 -08003043 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08003044
3045 /* Now unmount the /data partition. */
Greg Hackmann6e8440f2014-10-02 17:18:20 -07003046 if (wait_and_unmount(DATA_MNT_POINT, false)) {
JP Abgrall502dc742013-11-01 13:06:20 -07003047 if (allow_reboot) {
3048 goto error_shutting_down;
3049 } else {
3050 goto error_unencrypted;
3051 }
Ken Sumrall8ddbe402011-01-17 15:26:29 -08003052 }
3053
3054 /* Do extra work for a better UX when doing the long inplace encryption */
3055 if (how == CRYPTO_ENABLE_INPLACE) {
3056 /* Now that /data is unmounted, we need to mount a tmpfs
3057 * /data, set a property saying we're doing inplace encryption,
3058 * and restart the framework.
Ken Sumrall8f869aa2010-12-03 03:47:09 -08003059 */
Ken Sumralle5032c42012-04-01 23:58:44 -07003060 if (fs_mgr_do_tmpfs_mount(DATA_MNT_POINT)) {
Ken Sumrall3ed82362011-01-28 23:31:16 -08003061 goto error_shutting_down;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08003062 }
Ken Sumrall8ddbe402011-01-17 15:26:29 -08003063 /* Tells the framework that inplace encryption is starting */
Ken Sumrall7df84122011-01-18 14:04:08 -08003064 property_set("vold.encrypt_progress", "0");
Ken Sumrall8f869aa2010-12-03 03:47:09 -08003065
Ken Sumrall8ddbe402011-01-17 15:26:29 -08003066 /* restart the framework. */
3067 /* Create necessary paths on /data */
3068 if (prep_data_fs()) {
Ken Sumrall3ed82362011-01-28 23:31:16 -08003069 goto error_shutting_down;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08003070 }
3071
Ken Sumrall92736ef2012-10-17 20:57:14 -07003072 /* Ugh, shutting down the framework is not synchronous, so until it
3073 * can be fixed, this horrible hack will wait a moment for it all to
3074 * shut down before proceeding. Without it, some devices cannot
3075 * restart the graphics services.
3076 */
3077 sleep(2);
Ken Sumrall8ddbe402011-01-17 15:26:29 -08003078 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08003079
Ken Sumrall8ddbe402011-01-17 15:26:29 -08003080 /* Start the actual work of making an encrypted filesystem */
Ken Sumrall8ddbe402011-01-17 15:26:29 -08003081 /* Initialize a crypt_mnt_ftr for the partition */
Paul Lawrence87999172014-02-20 12:21:31 -08003082 if (previously_encrypted_upto == 0) {
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07003083 if (cryptfs_init_crypt_mnt_ftr(&crypt_ftr)) {
3084 goto error_shutting_down;
3085 }
Ken Sumrall160b4d62013-04-22 12:15:39 -07003086
Paul Lawrence87999172014-02-20 12:21:31 -08003087 if (!strcmp(key_loc, KEY_IN_FOOTER)) {
3088 crypt_ftr.fs_size = nr_sec
3089 - (CRYPT_FOOTER_OFFSET / CRYPT_SECTOR_SIZE);
3090 } else {
3091 crypt_ftr.fs_size = nr_sec;
3092 }
Paul Lawrence6bfed202014-07-28 12:47:22 -07003093 /* At this point, we are in an inconsistent state. Until we successfully
3094 complete encryption, a reboot will leave us broken. So mark the
3095 encryption failed in case that happens.
3096 On successfully completing encryption, remove this flag */
3097 crypt_ftr.flags |= CRYPT_INCONSISTENT_STATE;
Paul Lawrence87999172014-02-20 12:21:31 -08003098 crypt_ftr.crypt_type = crypt_type;
Ajay Dudani87701e22014-09-17 21:02:52 -07003099#ifndef CONFIG_HW_DISK_ENCRYPTION
3100 strlcpy((char *)crypt_ftr.crypto_type_name, "aes-cbc-essiv:sha256", MAX_CRYPTO_TYPE_NAME_LEN);
3101#else
3102 strlcpy((char *)crypt_ftr.crypto_type_name, "aes-xts", MAX_CRYPTO_TYPE_NAME_LEN);
3103
Iliyan Malchevbb7d9af2014-11-20 18:42:23 -08003104 rc = clear_hw_device_encryption_key();
Ajay Dudani87701e22014-09-17 21:02:52 -07003105 if (!rc) {
3106 SLOGE("Error clearing device encryption hardware key. rc = %d", rc);
3107 }
3108
3109 rc = set_hw_device_encryption_key(passwd,
3110 (char*) crypt_ftr.crypto_type_name);
3111 if (!rc) {
3112 SLOGE("Error initializing device encryption hardware key. rc = %d", rc);
3113 goto error_shutting_down;
3114 }
3115#endif
Ken Sumrall8ddbe402011-01-17 15:26:29 -08003116
Paul Lawrence87999172014-02-20 12:21:31 -08003117 /* Make an encrypted master key */
3118 if (create_encrypted_random_key(passwd, crypt_ftr.master_key, crypt_ftr.salt, &crypt_ftr)) {
3119 SLOGE("Cannot create encrypted master key\n");
3120 goto error_shutting_down;
3121 }
Ken Sumrall8ddbe402011-01-17 15:26:29 -08003122
Paul Lawrence87999172014-02-20 12:21:31 -08003123 /* Write the key to the end of the partition */
3124 put_crypt_ftr_and_key(&crypt_ftr);
Ken Sumrall8ddbe402011-01-17 15:26:29 -08003125
Paul Lawrence87999172014-02-20 12:21:31 -08003126 /* If any persistent data has been remembered, save it.
3127 * If none, create a valid empty table and save that.
3128 */
3129 if (!persist_data) {
3130 pdata = malloc(CRYPT_PERSIST_DATA_SIZE);
3131 if (pdata) {
3132 init_empty_persist_data(pdata, CRYPT_PERSIST_DATA_SIZE);
3133 persist_data = pdata;
3134 }
3135 }
3136 if (persist_data) {
3137 save_persistent_data();
3138 }
Ken Sumrall160b4d62013-04-22 12:15:39 -07003139 }
3140
Ajay Dudani87701e22014-09-17 21:02:52 -07003141 if (how == CRYPTO_ENABLE_INPLACE) {
3142 /* startup service classes main and late_start */
3143 property_set("vold.decrypt", "trigger_restart_min_framework");
3144 SLOGD("Just triggered restart_min_framework\n");
3145
3146 /* OK, the framework is restarted and will soon be showing a
3147 * progress bar. Time to setup an encrypted mapping, and
3148 * either write a new filesystem, or encrypt in place updating
3149 * the progress bar as we work.
3150 */
3151 }
3152
Paul Lawrenced0c7b172014-08-08 14:28:10 -07003153 decrypt_master_key(passwd, decrypted_master_key, &crypt_ftr, 0, 0);
Ken Sumrall29d8da82011-05-18 17:20:07 -07003154 create_crypto_blk_dev(&crypt_ftr, decrypted_master_key, real_blkdev, crypto_blkdev,
3155 "userdata");
3156
Paul Lawrence87999172014-02-20 12:21:31 -08003157 /* If we are continuing, check checksums match */
3158 rc = 0;
3159 if (previously_encrypted_upto) {
3160 __le8 hash_first_block[SHA256_DIGEST_LENGTH];
3161 rc = cryptfs_SHA256_fileblock(crypto_blkdev, hash_first_block);
Ken Sumrall128626f2011-06-28 18:45:14 -07003162
Paul Lawrence87999172014-02-20 12:21:31 -08003163 if (!rc && memcmp(hash_first_block, crypt_ftr.hash_first_block,
3164 sizeof(hash_first_block)) != 0) {
3165 SLOGE("Checksums do not match - trigger wipe");
3166 rc = -1;
Ken Sumrall29d8da82011-05-18 17:20:07 -07003167 }
3168 }
Ken Sumrall8ddbe402011-01-17 15:26:29 -08003169
Paul Lawrence87999172014-02-20 12:21:31 -08003170 if (!rc) {
3171 rc = cryptfs_enable_all_volumes(&crypt_ftr, how,
3172 crypto_blkdev, real_blkdev,
3173 previously_encrypted_upto);
3174 }
3175
3176 /* Calculate checksum if we are not finished */
Paul Lawrenceb1eb7a02014-11-25 14:57:32 -08003177 if (!rc && how == CRYPTO_ENABLE_INPLACE
3178 && crypt_ftr.encrypted_upto != crypt_ftr.fs_size) {
Paul Lawrence87999172014-02-20 12:21:31 -08003179 rc = cryptfs_SHA256_fileblock(crypto_blkdev,
3180 crypt_ftr.hash_first_block);
Paul Lawrence73d7a022014-06-09 14:10:09 -07003181 if (rc) {
Paul Lawrence87999172014-02-20 12:21:31 -08003182 SLOGE("Error calculating checksum for continuing encryption");
3183 rc = -1;
Ken Sumrall29d8da82011-05-18 17:20:07 -07003184 }
Ken Sumrall8ddbe402011-01-17 15:26:29 -08003185 }
3186
3187 /* Undo the dm-crypt mapping whether we succeed or not */
Ken Sumrall29d8da82011-05-18 17:20:07 -07003188 delete_crypto_blk_dev("userdata");
Ken Sumrall29d8da82011-05-18 17:20:07 -07003189
3190 free(vol_list);
Ken Sumrall8ddbe402011-01-17 15:26:29 -08003191
3192 if (! rc) {
3193 /* Success */
Paul Lawrence6bfed202014-07-28 12:47:22 -07003194 crypt_ftr.flags &= ~CRYPT_INCONSISTENT_STATE;
Ken Sumrall7f7dbaa2011-02-01 15:46:41 -08003195
Paul Lawrenceb1eb7a02014-11-25 14:57:32 -08003196 if (how == CRYPTO_ENABLE_INPLACE
3197 && crypt_ftr.encrypted_upto != crypt_ftr.fs_size) {
Paul Lawrence87999172014-02-20 12:21:31 -08003198 SLOGD("Encrypted up to sector %lld - will continue after reboot",
3199 crypt_ftr.encrypted_upto);
Paul Lawrence6bfed202014-07-28 12:47:22 -07003200 crypt_ftr.flags |= CRYPT_ENCRYPTION_IN_PROGRESS;
Paul Lawrence87999172014-02-20 12:21:31 -08003201 }
Paul Lawrence73d7a022014-06-09 14:10:09 -07003202
Paul Lawrence6bfed202014-07-28 12:47:22 -07003203 put_crypt_ftr_and_key(&crypt_ftr);
Ken Sumralld33d4172011-02-01 00:49:13 -08003204
Paul Lawrenceb1eb7a02014-11-25 14:57:32 -08003205 if (how == CRYPTO_ENABLE_WIPE
3206 || crypt_ftr.encrypted_upto == crypt_ftr.fs_size) {
Paul Lawrenceb6672e12014-08-15 07:37:28 -07003207 char value[PROPERTY_VALUE_MAX];
3208 property_get("ro.crypto.state", value, "");
3209 if (!strcmp(value, "")) {
3210 /* default encryption - continue first boot sequence */
3211 property_set("ro.crypto.state", "encrypted");
3212 release_wake_lock(lockid);
3213 cryptfs_check_passwd(DEFAULT_PASSWORD);
3214 cryptfs_restart_internal(1);
3215 return 0;
3216 } else {
3217 sleep(2); /* Give the UI a chance to show 100% progress */
Paul Lawrence87999172014-02-20 12:21:31 -08003218 cryptfs_reboot(reboot);
Paul Lawrenceb6672e12014-08-15 07:37:28 -07003219 }
Paul Lawrence87999172014-02-20 12:21:31 -08003220 } else {
Paul Lawrenceb6672e12014-08-15 07:37:28 -07003221 sleep(2); /* Partially encrypted, ensure writes flushed to ssd */
Paul Lawrence87999172014-02-20 12:21:31 -08003222 cryptfs_reboot(shutdown);
3223 }
Ken Sumrall3ed82362011-01-28 23:31:16 -08003224 } else {
Mike Lockwoodee6d8c42012-02-15 13:43:28 -08003225 char value[PROPERTY_VALUE_MAX];
3226
Ken Sumrall319369a2012-06-27 16:30:18 -07003227 property_get("ro.vold.wipe_on_crypt_fail", value, "0");
Mike Lockwoodee6d8c42012-02-15 13:43:28 -08003228 if (!strcmp(value, "1")) {
3229 /* wipe data if encryption failed */
3230 SLOGE("encryption failed - rebooting into recovery to wipe data\n");
3231 mkdir("/cache/recovery", 0700);
Nick Kralevich4684e582012-06-26 15:07:03 -07003232 int fd = open("/cache/recovery/command", O_RDWR|O_CREAT|O_TRUNC, 0600);
Mike Lockwoodee6d8c42012-02-15 13:43:28 -08003233 if (fd >= 0) {
Jeff Sharkeydd1a8042014-09-24 11:46:51 -07003234 write(fd, "--wipe_data\n", strlen("--wipe_data\n") + 1);
3235 write(fd, "--reason=cryptfs_enable_internal\n", strlen("--reason=cryptfs_enable_internal\n") + 1);
Mike Lockwoodee6d8c42012-02-15 13:43:28 -08003236 close(fd);
3237 } else {
3238 SLOGE("could not open /cache/recovery/command\n");
3239 }
Paul Lawrence87999172014-02-20 12:21:31 -08003240 cryptfs_reboot(recovery);
Mike Lockwoodee6d8c42012-02-15 13:43:28 -08003241 } else {
3242 /* set property to trigger dialog */
3243 property_set("vold.encrypt_progress", "error_partially_encrypted");
3244 release_wake_lock(lockid);
3245 }
Ken Sumrall3ed82362011-01-28 23:31:16 -08003246 return -1;
Ken Sumrall8ddbe402011-01-17 15:26:29 -08003247 }
3248
Ken Sumrall3ed82362011-01-28 23:31:16 -08003249 /* hrm, the encrypt step claims success, but the reboot failed.
3250 * This should not happen.
3251 * Set the property and return. Hope the framework can deal with it.
3252 */
3253 property_set("vold.encrypt_progress", "error_reboot_failed");
Ken Sumrall5d4c68e2011-01-30 19:06:03 -08003254 release_wake_lock(lockid);
Ken Sumrall8ddbe402011-01-17 15:26:29 -08003255 return rc;
Ken Sumrall3ed82362011-01-28 23:31:16 -08003256
3257error_unencrypted:
Ken Sumrall29d8da82011-05-18 17:20:07 -07003258 free(vol_list);
Ken Sumrall3ed82362011-01-28 23:31:16 -08003259 property_set("vold.encrypt_progress", "error_not_encrypted");
Ken Sumrall5d4c68e2011-01-30 19:06:03 -08003260 if (lockid[0]) {
3261 release_wake_lock(lockid);
3262 }
Ken Sumrall3ed82362011-01-28 23:31:16 -08003263 return -1;
3264
3265error_shutting_down:
3266 /* we failed, and have not encrypted anthing, so the users's data is still intact,
3267 * but the framework is stopped and not restarted to show the error, so it's up to
3268 * vold to restart the system.
3269 */
3270 SLOGE("Error enabling encryption after framework is shutdown, no data changed, restarting system");
Paul Lawrence87999172014-02-20 12:21:31 -08003271 cryptfs_reboot(reboot);
Ken Sumrall3ed82362011-01-28 23:31:16 -08003272
3273 /* shouldn't get here */
3274 property_set("vold.encrypt_progress", "error_shutting_down");
Ken Sumrall29d8da82011-05-18 17:20:07 -07003275 free(vol_list);
Ken Sumrall5d4c68e2011-01-30 19:06:03 -08003276 if (lockid[0]) {
3277 release_wake_lock(lockid);
3278 }
Ken Sumrall3ed82362011-01-28 23:31:16 -08003279 return -1;
Ken Sumrall8ddbe402011-01-17 15:26:29 -08003280}
3281
Paul Lawrence45f10532014-04-04 18:11:56 +00003282int cryptfs_enable(char *howarg, int type, char *passwd, int allow_reboot)
Paul Lawrence13486032014-02-03 13:28:11 -08003283{
Paul Lawrencefc615042014-10-04 15:32:29 -07003284 char* adjusted_passwd = adjust_passwd(passwd);
3285 if (adjusted_passwd) {
3286 passwd = adjusted_passwd;
3287 }
3288
3289 int rc = cryptfs_enable_internal(howarg, type, passwd, allow_reboot);
3290
3291 free(adjusted_passwd);
3292 return rc;
Paul Lawrence13486032014-02-03 13:28:11 -08003293}
3294
3295int cryptfs_enable_default(char *howarg, int allow_reboot)
3296{
3297 return cryptfs_enable_internal(howarg, CRYPT_TYPE_DEFAULT,
3298 DEFAULT_PASSWORD, allow_reboot);
3299}
3300
Paul Lawrence6a69cfc2015-01-21 09:58:26 -08003301static int device_is_force_encrypted() {
3302 int ret = -1;
3303 char value[PROP_VALUE_MAX];
3304 ret = __system_property_get("ro.vold.forceencryption", value);
3305 if (ret < 0)
3306 return 0;
3307 return strcmp(value, "1") ? 0 : 1;
3308}
3309
3310int cryptfs_maybe_enable_default_crypto()
3311{
3312 // Enable default crypt if /forceencrypt or /encryptable and
3313 // ro.vold.forceencrypt=1, else mount data and continue unencrypted
3314 struct fstab_rec *fstab_rec = 0;
3315 fstab_rec = fs_mgr_get_entry_for_mount_point(fstab, DATA_MNT_POINT);
3316 if (!fstab_rec) {
3317 SLOGE("Error getting fstab record");
3318 return -1;
3319 }
3320
3321 // See if we should encrypt?
3322 if ( !fs_mgr_is_encryptable(fstab_rec)
3323 || (!fs_mgr_is_force_encrypted(fstab_rec)
3324 && !device_is_force_encrypted())) {
3325 int rc = 0;
3326
3327 rc = fs_mgr_do_mount(fstab, DATA_MNT_POINT, fstab_rec->blk_device, 0);
3328 property_set("vold.decrypt", "trigger_load_persist_props");
3329
3330 /* Create necessary paths on /data */
3331 if (prep_data_fs()) {
3332 return -1;
3333 }
3334
3335 property_set("ro.crypto.state", "unencrypted");
3336 property_set("vold.decrypt", "trigger_restart_framework");
3337 SLOGD("Unencrypted - restart_framework\n");
3338 return rc;
3339 }
3340
3341 return cryptfs_enable_default("inplace", 0);
3342}
3343
Paul Lawrence13486032014-02-03 13:28:11 -08003344int cryptfs_changepw(int crypt_type, const char *newpw)
Ken Sumrall8ddbe402011-01-17 15:26:29 -08003345{
3346 struct crypt_mnt_ftr crypt_ftr;
Ken Sumrall8ddbe402011-01-17 15:26:29 -08003347
3348 /* This is only allowed after we've successfully decrypted the master key */
Paul Lawrencef4faa572014-01-29 13:31:03 -08003349 if (!master_key_saved) {
Ken Sumrall0cc16632011-01-18 20:32:26 -08003350 SLOGE("Key not saved, aborting");
Ken Sumrall8ddbe402011-01-17 15:26:29 -08003351 return -1;
3352 }
3353
Paul Lawrencef4faa572014-01-29 13:31:03 -08003354 if (crypt_type < 0 || crypt_type > CRYPT_TYPE_MAX_TYPE) {
3355 SLOGE("Invalid crypt_type %d", crypt_type);
3356 return -1;
3357 }
3358
Ken Sumrall8ddbe402011-01-17 15:26:29 -08003359 /* get key */
Ken Sumrall160b4d62013-04-22 12:15:39 -07003360 if (get_crypt_ftr_and_key(&crypt_ftr)) {
Paul Lawrencef4faa572014-01-29 13:31:03 -08003361 SLOGE("Error getting crypt footer and key");
3362 return -1;
Ken Sumrall8ddbe402011-01-17 15:26:29 -08003363 }
3364
Paul Lawrencef4faa572014-01-29 13:31:03 -08003365 crypt_ftr.crypt_type = crypt_type;
3366
Paul Lawrencefc615042014-10-04 15:32:29 -07003367 char* adjusted_passwd = adjust_passwd(newpw);
3368 if (adjusted_passwd) {
3369 newpw = adjusted_passwd;
3370 }
3371
Paul Lawrencef4faa572014-01-29 13:31:03 -08003372 encrypt_master_key(crypt_type == CRYPT_TYPE_DEFAULT ? DEFAULT_PASSWORD
3373 : newpw,
3374 crypt_ftr.salt,
3375 saved_master_key,
3376 crypt_ftr.master_key,
3377 &crypt_ftr);
Ken Sumrall8ddbe402011-01-17 15:26:29 -08003378
Jason parks70a4b3f2011-01-28 10:10:47 -06003379 /* save the key */
Ken Sumrall160b4d62013-04-22 12:15:39 -07003380 put_crypt_ftr_and_key(&crypt_ftr);
Ken Sumrall8f869aa2010-12-03 03:47:09 -08003381
Paul Lawrencefc615042014-10-04 15:32:29 -07003382 free(adjusted_passwd);
Ajay Dudani87701e22014-09-17 21:02:52 -07003383
3384#ifdef CONFIG_HW_DISK_ENCRYPTION
Iliyan Malchevbb7d9af2014-11-20 18:42:23 -08003385 if (!strcmp((char *)crypt_ftr.crypto_type_name, "aes-xts")) {
3386 if (crypt_type == CRYPT_TYPE_DEFAULT) {
3387 int rc = update_hw_device_encryption_key(DEFAULT_PASSWORD, (char*) crypt_ftr.crypto_type_name);
3388 SLOGD("Update hardware encryption key to default for crypt_type: %d. rc = %d", crypt_type, rc);
3389 if (!rc)
3390 return -1;
3391 } else {
3392 int rc = update_hw_device_encryption_key(newpw, (char*) crypt_ftr.crypto_type_name);
3393 SLOGD("Update hardware encryption key for crypt_type: %d. rc = %d", crypt_type, rc);
3394 if (!rc)
3395 return -1;
3396 }
Ajay Dudani87701e22014-09-17 21:02:52 -07003397 }
3398#endif
Ken Sumrall8f869aa2010-12-03 03:47:09 -08003399 return 0;
3400}
Ken Sumrall160b4d62013-04-22 12:15:39 -07003401
Rubin Xu85c01f92014-10-13 12:49:54 +01003402static unsigned int persist_get_max_entries(int encrypted) {
3403 struct crypt_mnt_ftr crypt_ftr;
3404 unsigned int dsize;
3405 unsigned int max_persistent_entries;
3406
3407 /* If encrypted, use the values from the crypt_ftr, otherwise
3408 * use the values for the current spec.
3409 */
3410 if (encrypted) {
3411 if (get_crypt_ftr_and_key(&crypt_ftr)) {
3412 return -1;
3413 }
3414 dsize = crypt_ftr.persist_data_size;
3415 } else {
3416 dsize = CRYPT_PERSIST_DATA_SIZE;
3417 }
3418
3419 max_persistent_entries = (dsize - sizeof(struct crypt_persist_data)) /
3420 sizeof(struct crypt_persist_entry);
3421
3422 return max_persistent_entries;
3423}
3424
3425static int persist_get_key(const char *fieldname, char *value)
Ken Sumrall160b4d62013-04-22 12:15:39 -07003426{
3427 unsigned int i;
3428
3429 if (persist_data == NULL) {
3430 return -1;
3431 }
3432 for (i = 0; i < persist_data->persist_valid_entries; i++) {
3433 if (!strncmp(persist_data->persist_entry[i].key, fieldname, PROPERTY_KEY_MAX)) {
3434 /* We found it! */
3435 strlcpy(value, persist_data->persist_entry[i].val, PROPERTY_VALUE_MAX);
3436 return 0;
3437 }
3438 }
3439
3440 return -1;
3441}
3442
Rubin Xu85c01f92014-10-13 12:49:54 +01003443static int persist_set_key(const char *fieldname, const char *value, int encrypted)
Ken Sumrall160b4d62013-04-22 12:15:39 -07003444{
3445 unsigned int i;
3446 unsigned int num;
Ken Sumrall160b4d62013-04-22 12:15:39 -07003447 unsigned int max_persistent_entries;
Ken Sumrall160b4d62013-04-22 12:15:39 -07003448
3449 if (persist_data == NULL) {
3450 return -1;
3451 }
3452
Rubin Xu85c01f92014-10-13 12:49:54 +01003453 max_persistent_entries = persist_get_max_entries(encrypted);
Ken Sumrall160b4d62013-04-22 12:15:39 -07003454
3455 num = persist_data->persist_valid_entries;
3456
3457 for (i = 0; i < num; i++) {
3458 if (!strncmp(persist_data->persist_entry[i].key, fieldname, PROPERTY_KEY_MAX)) {
3459 /* We found an existing entry, update it! */
3460 memset(persist_data->persist_entry[i].val, 0, PROPERTY_VALUE_MAX);
3461 strlcpy(persist_data->persist_entry[i].val, value, PROPERTY_VALUE_MAX);
3462 return 0;
3463 }
3464 }
3465
3466 /* We didn't find it, add it to the end, if there is room */
3467 if (persist_data->persist_valid_entries < max_persistent_entries) {
3468 memset(&persist_data->persist_entry[num], 0, sizeof(struct crypt_persist_entry));
3469 strlcpy(persist_data->persist_entry[num].key, fieldname, PROPERTY_KEY_MAX);
3470 strlcpy(persist_data->persist_entry[num].val, value, PROPERTY_VALUE_MAX);
3471 persist_data->persist_valid_entries++;
3472 return 0;
3473 }
3474
3475 return -1;
3476}
3477
Rubin Xu85c01f92014-10-13 12:49:54 +01003478/**
3479 * Test if key is part of the multi-entry (field, index) sequence. Return non-zero if key is in the
3480 * sequence and its index is greater than or equal to index. Return 0 otherwise.
3481 */
3482static int match_multi_entry(const char *key, const char *field, unsigned index) {
Rubin Xu85c01f92014-10-13 12:49:54 +01003483 unsigned int field_len;
3484 unsigned int key_index;
3485 field_len = strlen(field);
3486
3487 if (index == 0) {
3488 // The first key in a multi-entry field is just the filedname itself.
3489 if (!strcmp(key, field)) {
3490 return 1;
3491 }
3492 }
3493 // Match key against "%s_%d" % (field, index)
3494 if (strlen(key) < field_len + 1 + 1) {
3495 // Need at least a '_' and a digit.
3496 return 0;
3497 }
3498 if (strncmp(key, field, field_len)) {
3499 // If the key does not begin with field, it's not a match.
3500 return 0;
3501 }
3502 if (1 != sscanf(&key[field_len],"_%d", &key_index)) {
3503 return 0;
3504 }
3505 return key_index >= index;
3506}
3507
3508/*
3509 * Delete entry/entries from persist_data. If the entries are part of a multi-segment field, all
3510 * remaining entries starting from index will be deleted.
3511 * returns PERSIST_DEL_KEY_OK if deletion succeeds,
3512 * PERSIST_DEL_KEY_ERROR_NO_FIELD if the field does not exist,
3513 * and PERSIST_DEL_KEY_ERROR_OTHER if error occurs.
3514 *
3515 */
3516static int persist_del_keys(const char *fieldname, unsigned index)
3517{
3518 unsigned int i;
3519 unsigned int j;
3520 unsigned int num;
3521
3522 if (persist_data == NULL) {
3523 return PERSIST_DEL_KEY_ERROR_OTHER;
3524 }
3525
3526 num = persist_data->persist_valid_entries;
3527
3528 j = 0; // points to the end of non-deleted entries.
3529 // Filter out to-be-deleted entries in place.
3530 for (i = 0; i < num; i++) {
3531 if (!match_multi_entry(persist_data->persist_entry[i].key, fieldname, index)) {
3532 persist_data->persist_entry[j] = persist_data->persist_entry[i];
3533 j++;
3534 }
3535 }
3536
3537 if (j < num) {
3538 persist_data->persist_valid_entries = j;
3539 // Zeroise the remaining entries
3540 memset(&persist_data->persist_entry[j], 0, (num - j) * sizeof(struct crypt_persist_entry));
3541 return PERSIST_DEL_KEY_OK;
3542 } else {
3543 // Did not find an entry matching the given fieldname
3544 return PERSIST_DEL_KEY_ERROR_NO_FIELD;
3545 }
3546}
3547
3548static int persist_count_keys(const char *fieldname)
3549{
3550 unsigned int i;
3551 unsigned int count;
3552
3553 if (persist_data == NULL) {
3554 return -1;
3555 }
3556
3557 count = 0;
3558 for (i = 0; i < persist_data->persist_valid_entries; i++) {
3559 if (match_multi_entry(persist_data->persist_entry[i].key, fieldname, 0)) {
3560 count++;
3561 }
3562 }
3563
3564 return count;
3565}
3566
Ken Sumrall160b4d62013-04-22 12:15:39 -07003567/* Return the value of the specified field. */
Rubin Xu85c01f92014-10-13 12:49:54 +01003568int cryptfs_getfield(const char *fieldname, char *value, int len)
Ken Sumrall160b4d62013-04-22 12:15:39 -07003569{
3570 char temp_value[PROPERTY_VALUE_MAX];
Rubin Xu85c01f92014-10-13 12:49:54 +01003571 /* CRYPTO_GETFIELD_OK is success,
3572 * CRYPTO_GETFIELD_ERROR_NO_FIELD is value not set,
3573 * CRYPTO_GETFIELD_ERROR_BUF_TOO_SMALL is buffer (as given by len) too small,
3574 * CRYPTO_GETFIELD_ERROR_OTHER is any other error
Ken Sumrall160b4d62013-04-22 12:15:39 -07003575 */
Rubin Xu85c01f92014-10-13 12:49:54 +01003576 int rc = CRYPTO_GETFIELD_ERROR_OTHER;
3577 int i;
3578 char temp_field[PROPERTY_KEY_MAX];
Ken Sumrall160b4d62013-04-22 12:15:39 -07003579
3580 if (persist_data == NULL) {
3581 load_persistent_data();
3582 if (persist_data == NULL) {
3583 SLOGE("Getfield error, cannot load persistent data");
3584 goto out;
3585 }
3586 }
3587
Rubin Xu85c01f92014-10-13 12:49:54 +01003588 // Read value from persistent entries. If the original value is split into multiple entries,
3589 // stitch them back together.
Ken Sumrall160b4d62013-04-22 12:15:39 -07003590 if (!persist_get_key(fieldname, temp_value)) {
Rubin Xu85c01f92014-10-13 12:49:54 +01003591 // We found it, copy it to the caller's buffer and keep going until all entries are read.
3592 if (strlcpy(value, temp_value, len) >= (unsigned) len) {
3593 // value too small
3594 rc = CRYPTO_GETFIELD_ERROR_BUF_TOO_SMALL;
3595 goto out;
3596 }
3597 rc = CRYPTO_GETFIELD_OK;
3598
3599 for (i = 1; /* break explicitly */; i++) {
3600 if (snprintf(temp_field, sizeof(temp_field), "%s_%d", fieldname, i) >=
3601 (int) sizeof(temp_field)) {
3602 // If the fieldname is very long, we stop as soon as it begins to overflow the
3603 // maximum field length. At this point we have in fact fully read out the original
3604 // value because cryptfs_setfield would not allow fields with longer names to be
3605 // written in the first place.
3606 break;
3607 }
3608 if (!persist_get_key(temp_field, temp_value)) {
3609 if (strlcat(value, temp_value, len) >= (unsigned)len) {
3610 // value too small.
3611 rc = CRYPTO_GETFIELD_ERROR_BUF_TOO_SMALL;
3612 goto out;
3613 }
3614 } else {
3615 // Exhaust all entries.
3616 break;
3617 }
3618 }
Ken Sumrall160b4d62013-04-22 12:15:39 -07003619 } else {
3620 /* Sadness, it's not there. Return the error */
Rubin Xu85c01f92014-10-13 12:49:54 +01003621 rc = CRYPTO_GETFIELD_ERROR_NO_FIELD;
Ken Sumrall160b4d62013-04-22 12:15:39 -07003622 }
3623
3624out:
3625 return rc;
3626}
3627
3628/* Set the value of the specified field. */
Rubin Xu85c01f92014-10-13 12:49:54 +01003629int cryptfs_setfield(const char *fieldname, const char *value)
Ken Sumrall160b4d62013-04-22 12:15:39 -07003630{
Ken Sumrall160b4d62013-04-22 12:15:39 -07003631 char encrypted_state[PROPERTY_VALUE_MAX];
Rubin Xu85c01f92014-10-13 12:49:54 +01003632 /* 0 is success, negative values are error */
3633 int rc = CRYPTO_SETFIELD_ERROR_OTHER;
Ken Sumrall160b4d62013-04-22 12:15:39 -07003634 int encrypted = 0;
Rubin Xu85c01f92014-10-13 12:49:54 +01003635 unsigned int field_id;
3636 char temp_field[PROPERTY_KEY_MAX];
3637 unsigned int num_entries;
3638 unsigned int max_keylen;
Ken Sumrall160b4d62013-04-22 12:15:39 -07003639
3640 if (persist_data == NULL) {
3641 load_persistent_data();
3642 if (persist_data == NULL) {
3643 SLOGE("Setfield error, cannot load persistent data");
3644 goto out;
3645 }
3646 }
3647
3648 property_get("ro.crypto.state", encrypted_state, "");
3649 if (!strcmp(encrypted_state, "encrypted") ) {
3650 encrypted = 1;
3651 }
3652
Rubin Xu85c01f92014-10-13 12:49:54 +01003653 // Compute the number of entries required to store value, each entry can store up to
3654 // (PROPERTY_VALUE_MAX - 1) chars
3655 if (strlen(value) == 0) {
3656 // Empty value also needs one entry to store.
3657 num_entries = 1;
3658 } else {
3659 num_entries = (strlen(value) + (PROPERTY_VALUE_MAX - 1) - 1) / (PROPERTY_VALUE_MAX - 1);
3660 }
3661
3662 max_keylen = strlen(fieldname);
3663 if (num_entries > 1) {
3664 // Need an extra "_%d" suffix.
3665 max_keylen += 1 + log10(num_entries);
3666 }
3667 if (max_keylen > PROPERTY_KEY_MAX - 1) {
3668 rc = CRYPTO_SETFIELD_ERROR_FIELD_TOO_LONG;
Ken Sumrall160b4d62013-04-22 12:15:39 -07003669 goto out;
3670 }
3671
Rubin Xu85c01f92014-10-13 12:49:54 +01003672 // Make sure we have enough space to write the new value
3673 if (persist_data->persist_valid_entries + num_entries - persist_count_keys(fieldname) >
3674 persist_get_max_entries(encrypted)) {
3675 rc = CRYPTO_SETFIELD_ERROR_VALUE_TOO_LONG;
3676 goto out;
3677 }
3678
3679 // Now that we know persist_data has enough space for value, let's delete the old field first
3680 // to make up space.
3681 persist_del_keys(fieldname, 0);
3682
3683 if (persist_set_key(fieldname, value, encrypted)) {
3684 // fail to set key, should not happen as we have already checked the available space
3685 SLOGE("persist_set_key() error during setfield()");
3686 goto out;
3687 }
3688
3689 for (field_id = 1; field_id < num_entries; field_id++) {
3690 snprintf(temp_field, sizeof(temp_field), "%s_%d", fieldname, field_id);
3691
3692 if (persist_set_key(temp_field, value + field_id * (PROPERTY_VALUE_MAX - 1), encrypted)) {
3693 // fail to set key, should not happen as we have already checked the available space.
3694 SLOGE("persist_set_key() error during setfield()");
3695 goto out;
3696 }
3697 }
3698
Ken Sumrall160b4d62013-04-22 12:15:39 -07003699 /* If we are running encrypted, save the persistent data now */
3700 if (encrypted) {
3701 if (save_persistent_data()) {
3702 SLOGE("Setfield error, cannot save persistent data");
3703 goto out;
3704 }
3705 }
3706
Rubin Xu85c01f92014-10-13 12:49:54 +01003707 rc = CRYPTO_SETFIELD_OK;
Ken Sumrall160b4d62013-04-22 12:15:39 -07003708
3709out:
3710 return rc;
3711}
Paul Lawrencef4faa572014-01-29 13:31:03 -08003712
3713/* Checks userdata. Attempt to mount the volume if default-
3714 * encrypted.
3715 * On success trigger next init phase and return 0.
3716 * Currently do not handle failure - see TODO below.
3717 */
3718int cryptfs_mount_default_encrypted(void)
3719{
3720 char decrypt_state[PROPERTY_VALUE_MAX];
3721 property_get("vold.decrypt", decrypt_state, "0");
3722 if (!strcmp(decrypt_state, "0")) {
3723 SLOGE("Not encrypted - should not call here");
3724 } else {
3725 int crypt_type = cryptfs_get_password_type();
3726 if (crypt_type < 0 || crypt_type > CRYPT_TYPE_MAX_TYPE) {
3727 SLOGE("Bad crypt type - error");
3728 } else if (crypt_type != CRYPT_TYPE_DEFAULT) {
3729 SLOGD("Password is not default - "
3730 "starting min framework to prompt");
3731 property_set("vold.decrypt", "trigger_restart_min_framework");
3732 return 0;
3733 } else if (cryptfs_check_passwd(DEFAULT_PASSWORD) == 0) {
3734 SLOGD("Password is default - restarting filesystem");
3735 cryptfs_restart_internal(0);
3736 return 0;
3737 } else {
3738 SLOGE("Encrypted, default crypt type but can't decrypt");
3739 }
3740 }
3741
Paul Lawrence6bfed202014-07-28 12:47:22 -07003742 /** Corrupt. Allow us to boot into framework, which will detect bad
3743 crypto when it calls do_crypto_complete, then do a factory reset
Paul Lawrencef4faa572014-01-29 13:31:03 -08003744 */
Paul Lawrence6bfed202014-07-28 12:47:22 -07003745 property_set("vold.decrypt", "trigger_restart_min_framework");
Paul Lawrencef4faa572014-01-29 13:31:03 -08003746 return 0;
3747}
3748
3749/* Returns type of the password, default, pattern, pin or password.
3750 */
3751int cryptfs_get_password_type(void)
3752{
3753 struct crypt_mnt_ftr crypt_ftr;
3754
3755 if (get_crypt_ftr_and_key(&crypt_ftr)) {
3756 SLOGE("Error getting crypt footer and key\n");
3757 return -1;
3758 }
3759
Paul Lawrence6bfed202014-07-28 12:47:22 -07003760 if (crypt_ftr.flags & CRYPT_INCONSISTENT_STATE) {
3761 return -1;
3762 }
3763
Paul Lawrencef4faa572014-01-29 13:31:03 -08003764 return crypt_ftr.crypt_type;
3765}
Paul Lawrence684dbdf2014-02-07 12:07:22 -08003766
Paul Lawrence399317e2014-03-10 13:20:50 -07003767char* cryptfs_get_password()
Paul Lawrence684dbdf2014-02-07 12:07:22 -08003768{
Paul Lawrence399317e2014-03-10 13:20:50 -07003769 struct timespec now;
Paul Lawrenceef2b5be2014-11-11 12:47:03 -08003770 clock_gettime(CLOCK_BOOTTIME, &now);
Paul Lawrence399317e2014-03-10 13:20:50 -07003771 if (now.tv_sec < password_expiry_time) {
3772 return password;
3773 } else {
3774 cryptfs_clear_password();
3775 return 0;
3776 }
3777}
3778
3779void cryptfs_clear_password()
3780{
3781 if (password) {
3782 size_t len = strlen(password);
3783 memset(password, 0, len);
3784 free(password);
3785 password = 0;
3786 password_expiry_time = 0;
3787 }
Paul Lawrence684dbdf2014-02-07 12:07:22 -08003788}