blob: 606b9f1cf9833d94dc3da2053659b55f7d0b76c3 [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>
39#include <errno.h>
Ken Sumrall3ed82362011-01-28 23:31:16 -080040#include <ext4.h>
Ken Sumrall29d8da82011-05-18 17:20:07 -070041#include <linux/kdev_t.h>
Ken Sumralle5032c42012-04-01 23:58:44 -070042#include <fs_mgr.h>
Paul Lawrence9c58a872014-09-30 09:12:51 -070043#include <time.h>
Ken Sumrall8f869aa2010-12-03 03:47:09 -080044#include "cryptfs.h"
45#define LOG_TAG "Cryptfs"
46#include "cutils/log.h"
47#include "cutils/properties.h"
Ken Sumralladfba362013-06-04 16:37:52 -070048#include "cutils/android_reboot.h"
Ken Sumrall5d4c68e2011-01-30 19:06:03 -080049#include "hardware_legacy/power.h"
Ken Sumralle550f782013-08-20 13:48:23 -070050#include <logwrap/logwrap.h>
Ken Sumrall29d8da82011-05-18 17:20:07 -070051#include "VolumeManager.h"
Ken Sumrall9caab762013-06-11 19:10:20 -070052#include "VoldUtil.h"
Kenny Rootc4c70f12013-06-14 12:11:38 -070053#include "crypto_scrypt.h"
Paul Lawrenceae59fe62014-01-21 08:23:27 -080054#include "ext4_utils.h"
Daniel Rosenberge82df162014-08-15 22:19:23 +000055#include "f2fs_sparseblock.h"
Paul Lawrence87999172014-02-20 12:21:31 -080056#include "CheckBattery.h"
jessica_yu3f14fe42014-09-22 15:57:40 +080057#include "Process.h"
Ken Sumrall8f869aa2010-12-03 03:47:09 -080058
Paul Lawrence69f4ebd2014-04-14 12:17:14 -070059#include <hardware/keymaster.h>
60
Mark Salyzyn3e971272014-01-21 13:27:04 -080061#define UNUSED __attribute__((unused))
62
Mark Salyzyn5eecc442014-02-12 14:16:14 -080063#define UNUSED __attribute__((unused))
64
Ken Sumrall8f869aa2010-12-03 03:47:09 -080065#define DM_CRYPT_BUF_SIZE 4096
66
Jason parks70a4b3f2011-01-28 10:10:47 -060067#define HASH_COUNT 2000
68#define KEY_LEN_BYTES 16
69#define IV_LEN_BYTES 16
70
Ken Sumrall29d8da82011-05-18 17:20:07 -070071#define KEY_IN_FOOTER "footer"
72
Paul Lawrencef4faa572014-01-29 13:31:03 -080073// "default_password" encoded into hex (d=0x64 etc)
74#define DEFAULT_PASSWORD "64656661756c745f70617373776f7264"
75
Ken Sumrall29d8da82011-05-18 17:20:07 -070076#define EXT4_FS 1
JP Abgrall62c7af32014-06-16 13:01:23 -070077#define F2FS_FS 2
Ken Sumrall29d8da82011-05-18 17:20:07 -070078
Ken Sumralle919efe2012-09-29 17:07:41 -070079#define TABLE_LOAD_RETRIES 10
80
Shawn Willden47ba10d2014-09-03 17:07:06 -060081#define RSA_KEY_SIZE 2048
82#define RSA_KEY_SIZE_BYTES (RSA_KEY_SIZE / 8)
83#define RSA_EXPONENT 0x10001
Paul Lawrence69f4ebd2014-04-14 12:17:14 -070084
Paul Lawrence8e3f4512014-09-08 10:11:17 -070085#define RETRY_MOUNT_ATTEMPTS 10
86#define RETRY_MOUNT_DELAY_SECONDS 1
87
Ken Sumrall8f869aa2010-12-03 03:47:09 -080088char *me = "cryptfs";
89
Jason parks70a4b3f2011-01-28 10:10:47 -060090static unsigned char saved_master_key[KEY_LEN_BYTES];
Ken Sumrall3ad90722011-10-04 20:38:29 -070091static char *saved_mount_point;
Jason parks70a4b3f2011-01-28 10:10:47 -060092static int master_key_saved = 0;
Ken Sumrall160b4d62013-04-22 12:15:39 -070093static struct crypt_persist_data *persist_data = NULL;
Ken Sumrall56ad03c2013-02-13 13:00:19 -080094
Paul Lawrence69f4ebd2014-04-14 12:17:14 -070095static int keymaster_init(keymaster_device_t **keymaster_dev)
96{
97 int rc;
98
99 const hw_module_t* mod;
100 rc = hw_get_module_by_class(KEYSTORE_HARDWARE_MODULE_ID, NULL, &mod);
101 if (rc) {
102 ALOGE("could not find any keystore module");
103 goto out;
104 }
105
106 rc = keymaster_open(mod, keymaster_dev);
107 if (rc) {
108 ALOGE("could not open keymaster device in %s (%s)",
109 KEYSTORE_HARDWARE_MODULE_ID, strerror(-rc));
110 goto out;
111 }
112
113 return 0;
114
115out:
116 *keymaster_dev = NULL;
117 return rc;
118}
119
120/* Should we use keymaster? */
121static int keymaster_check_compatibility()
122{
123 keymaster_device_t *keymaster_dev = 0;
124 int rc = 0;
125
126 if (keymaster_init(&keymaster_dev)) {
127 SLOGE("Failed to init keymaster");
128 rc = -1;
129 goto out;
130 }
131
Paul Lawrence8c008392014-05-06 14:02:48 -0700132 SLOGI("keymaster version is %d", keymaster_dev->common.module->module_api_version);
133
134 if (keymaster_dev->common.module->module_api_version
135 < KEYMASTER_MODULE_API_VERSION_0_3) {
136 rc = 0;
137 goto out;
138 }
139
Paul Lawrence69f4ebd2014-04-14 12:17:14 -0700140 if (keymaster_dev->flags & KEYMASTER_BLOBS_ARE_STANDALONE) {
141 rc = 1;
142 }
143
144out:
145 keymaster_close(keymaster_dev);
146 return rc;
147}
148
149/* Create a new keymaster key and store it in this footer */
150static int keymaster_create_key(struct crypt_mnt_ftr *ftr)
151{
152 uint8_t* key = 0;
153 keymaster_device_t *keymaster_dev = 0;
154
155 if (keymaster_init(&keymaster_dev)) {
156 SLOGE("Failed to init keymaster");
157 return -1;
158 }
159
160 int rc = 0;
161
162 keymaster_rsa_keygen_params_t params;
163 memset(&params, '\0', sizeof(params));
Shawn Willden47ba10d2014-09-03 17:07:06 -0600164 params.public_exponent = RSA_EXPONENT;
165 params.modulus_size = RSA_KEY_SIZE;
Paul Lawrence69f4ebd2014-04-14 12:17:14 -0700166
167 size_t key_size;
168 if (keymaster_dev->generate_keypair(keymaster_dev, TYPE_RSA, &params,
169 &key, &key_size)) {
170 SLOGE("Failed to generate keypair");
171 rc = -1;
172 goto out;
173 }
174
175 if (key_size > KEYMASTER_BLOB_SIZE) {
176 SLOGE("Keymaster key too large for crypto footer");
177 rc = -1;
178 goto out;
179 }
180
181 memcpy(ftr->keymaster_blob, key, key_size);
182 ftr->keymaster_blob_size = key_size;
183
184out:
185 keymaster_close(keymaster_dev);
186 free(key);
187 return rc;
188}
189
Shawn Willdene17a9c42014-09-08 13:04:08 -0600190/* This signs the given object using the keymaster key. */
191static int keymaster_sign_object(struct crypt_mnt_ftr *ftr,
Shawn Willden47ba10d2014-09-03 17:07:06 -0600192 const unsigned char *object,
193 const size_t object_size,
194 unsigned char **signature,
195 size_t *signature_size)
196{
197 int rc = 0;
198 keymaster_device_t *keymaster_dev = 0;
199 if (keymaster_init(&keymaster_dev)) {
200 SLOGE("Failed to init keymaster");
201 return -1;
202 }
203
204 /* We currently set the digest type to DIGEST_NONE because it's the
205 * only supported value for keymaster. A similar issue exists with
206 * PADDING_NONE. Long term both of these should likely change.
207 */
208 keymaster_rsa_sign_params_t params;
209 params.digest_type = DIGEST_NONE;
210 params.padding_type = PADDING_NONE;
211
212 unsigned char to_sign[RSA_KEY_SIZE_BYTES];
Shawn Willdene17a9c42014-09-08 13:04:08 -0600213 size_t to_sign_size = sizeof(to_sign);
Shawn Willden47ba10d2014-09-03 17:07:06 -0600214 memset(to_sign, 0, RSA_KEY_SIZE_BYTES);
Shawn Willden47ba10d2014-09-03 17:07:06 -0600215
Shawn Willdene17a9c42014-09-08 13:04:08 -0600216 // To sign a message with RSA, the message must satisfy two
217 // constraints:
218 //
219 // 1. The message, when interpreted as a big-endian numeric value, must
220 // be strictly less than the public modulus of the RSA key. Note
221 // that because the most significant bit of the public modulus is
222 // guaranteed to be 1 (else it's an (n-1)-bit key, not an n-bit
223 // key), an n-bit message with most significant bit 0 always
224 // satisfies this requirement.
225 //
226 // 2. The message must have the same length in bits as the public
227 // modulus of the RSA key. This requirement isn't mathematically
228 // necessary, but is necessary to ensure consistency in
229 // implementations.
230 switch (ftr->kdf_type) {
231 case KDF_SCRYPT_KEYMASTER_UNPADDED:
232 // This is broken: It produces a message which is shorter than
233 // the public modulus, failing criterion 2.
234 memcpy(to_sign, object, object_size);
235 to_sign_size = object_size;
236 SLOGI("Signing unpadded object");
237 break;
238 case KDF_SCRYPT_KEYMASTER_BADLY_PADDED:
239 // This is broken: Since the value of object is uniformly
240 // distributed, it produces a message that is larger than the
241 // public modulus with probability 0.25.
242 memcpy(to_sign, object, min(RSA_KEY_SIZE_BYTES, object_size));
243 SLOGI("Signing end-padded object");
244 break;
245 case KDF_SCRYPT_KEYMASTER:
246 // This ensures the most significant byte of the signed message
247 // is zero. We could have zero-padded to the left instead, but
248 // this approach is slightly more robust against changes in
249 // object size. However, it's still broken (but not unusably
250 // so) because we really should be using a proper RSA padding
251 // function, such as OAEP.
252 //
253 // TODO(paullawrence): When keymaster 0.4 is available, change
254 // this to use the padding options it provides.
255 memcpy(to_sign + 1, object, min(RSA_KEY_SIZE_BYTES - 1, object_size));
256 SLOGI("Signing safely-padded object");
257 break;
258 default:
259 SLOGE("Unknown KDF type %d", ftr->kdf_type);
260 return -1;
261 }
262
Shawn Willden47ba10d2014-09-03 17:07:06 -0600263 rc = keymaster_dev->sign_data(keymaster_dev,
264 &params,
265 ftr->keymaster_blob,
266 ftr->keymaster_blob_size,
267 to_sign,
Shawn Willdene17a9c42014-09-08 13:04:08 -0600268 to_sign_size,
Shawn Willden47ba10d2014-09-03 17:07:06 -0600269 signature,
270 signature_size);
271
272 keymaster_close(keymaster_dev);
273 return rc;
274}
275
Paul Lawrence399317e2014-03-10 13:20:50 -0700276/* Store password when userdata is successfully decrypted and mounted.
277 * Cleared by cryptfs_clear_password
278 *
279 * To avoid a double prompt at boot, we need to store the CryptKeeper
280 * password and pass it to KeyGuard, which uses it to unlock KeyStore.
281 * Since the entire framework is torn down and rebuilt after encryption,
282 * we have to use a daemon or similar to store the password. Since vold
283 * is secured against IPC except from system processes, it seems a reasonable
284 * place to store this.
285 *
286 * password should be cleared once it has been used.
287 *
288 * password is aged out after password_max_age_seconds seconds.
Paul Lawrence684dbdf2014-02-07 12:07:22 -0800289 */
Paul Lawrence399317e2014-03-10 13:20:50 -0700290static char* password = 0;
291static int password_expiry_time = 0;
292static const int password_max_age_seconds = 60;
Paul Lawrence684dbdf2014-02-07 12:07:22 -0800293
Ken Sumrall56ad03c2013-02-13 13:00:19 -0800294extern struct fstab *fstab;
Ken Sumrall8ddbe402011-01-17 15:26:29 -0800295
Paul Lawrence87999172014-02-20 12:21:31 -0800296enum RebootType {reboot, recovery, shutdown};
297static void cryptfs_reboot(enum RebootType rt)
Ken Sumralladfba362013-06-04 16:37:52 -0700298{
Paul Lawrence87999172014-02-20 12:21:31 -0800299 switch(rt) {
300 case reboot:
301 property_set(ANDROID_RB_PROPERTY, "reboot");
302 break;
303
304 case recovery:
305 property_set(ANDROID_RB_PROPERTY, "reboot,recovery");
306 break;
307
308 case shutdown:
309 property_set(ANDROID_RB_PROPERTY, "shutdown");
310 break;
Ken Sumralladfba362013-06-04 16:37:52 -0700311 }
Paul Lawrence87999172014-02-20 12:21:31 -0800312
Ken Sumralladfba362013-06-04 16:37:52 -0700313 sleep(20);
314
315 /* Shouldn't get here, reboot should happen before sleep times out */
316 return;
317}
318
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800319static void ioctl_init(struct dm_ioctl *io, size_t dataSize, const char *name, unsigned flags)
320{
321 memset(io, 0, dataSize);
322 io->data_size = dataSize;
323 io->data_start = sizeof(struct dm_ioctl);
324 io->version[0] = 4;
325 io->version[1] = 0;
326 io->version[2] = 0;
327 io->flags = flags;
328 if (name) {
329 strncpy(io->name, name, sizeof(io->name));
330 }
331}
332
Kenny Rootc4c70f12013-06-14 12:11:38 -0700333/**
334 * Gets the default device scrypt parameters for key derivation time tuning.
335 * The parameters should lead to about one second derivation time for the
336 * given device.
337 */
338static void get_device_scrypt_params(struct crypt_mnt_ftr *ftr) {
339 const int default_params[] = SCRYPT_DEFAULTS;
340 int params[] = SCRYPT_DEFAULTS;
341 char paramstr[PROPERTY_VALUE_MAX];
342 char *token;
343 char *saveptr;
344 int i;
345
346 property_get(SCRYPT_PROP, paramstr, "");
347 if (paramstr[0] != '\0') {
348 /*
349 * The token we're looking for should be three integers separated by
350 * colons (e.g., "12:8:1"). Scan the property to make sure it matches.
351 */
Kenny Root2947e342013-08-14 15:54:49 -0700352 for (i = 0, token = strtok_r(paramstr, ":", &saveptr);
353 token != NULL && i < 3;
Kenny Rootc4c70f12013-06-14 12:11:38 -0700354 i++, token = strtok_r(NULL, ":", &saveptr)) {
355 char *endptr;
356 params[i] = strtol(token, &endptr, 10);
357
358 /*
359 * Check that there was a valid number and it's 8-bit. If not,
360 * break out and the end check will take the default values.
361 */
362 if ((*token == '\0') || (*endptr != '\0') || params[i] < 0 || params[i] > 255) {
363 break;
364 }
365 }
366
367 /*
368 * If there were not enough tokens or a token was malformed (not an
369 * integer), it will end up here and the default parameters can be
370 * taken.
371 */
372 if ((i != 3) || (token != NULL)) {
373 SLOGW("bad scrypt parameters '%s' should be like '12:8:1'; using defaults", paramstr);
374 memcpy(params, default_params, sizeof(params));
375 }
376 }
377
378 ftr->N_factor = params[0];
379 ftr->r_factor = params[1];
380 ftr->p_factor = params[2];
381}
382
Ken Sumrall3ed82362011-01-28 23:31:16 -0800383static unsigned int get_fs_size(char *dev)
384{
385 int fd, block_size;
386 struct ext4_super_block sb;
387 off64_t len;
388
389 if ((fd = open(dev, O_RDONLY)) < 0) {
390 SLOGE("Cannot open device to get filesystem size ");
391 return 0;
392 }
393
394 if (lseek64(fd, 1024, SEEK_SET) < 0) {
395 SLOGE("Cannot seek to superblock");
396 return 0;
397 }
398
399 if (read(fd, &sb, sizeof(sb)) != sizeof(sb)) {
400 SLOGE("Cannot read superblock");
401 return 0;
402 }
403
404 close(fd);
405
Daniel Rosenberge82df162014-08-15 22:19:23 +0000406 if (le32_to_cpu(sb.s_magic) != EXT4_SUPER_MAGIC) {
407 SLOGE("Not a valid ext4 superblock");
408 return 0;
409 }
Ken Sumrall3ed82362011-01-28 23:31:16 -0800410 block_size = 1024 << sb.s_log_block_size;
411 /* compute length in bytes */
412 len = ( ((off64_t)sb.s_blocks_count_hi << 32) + sb.s_blocks_count_lo) * block_size;
413
414 /* return length in sectors */
415 return (unsigned int) (len / 512);
416}
417
Ken Sumrall160b4d62013-04-22 12:15:39 -0700418static int get_crypt_ftr_info(char **metadata_fname, off64_t *off)
419{
420 static int cached_data = 0;
421 static off64_t cached_off = 0;
422 static char cached_metadata_fname[PROPERTY_VALUE_MAX] = "";
423 int fd;
424 char key_loc[PROPERTY_VALUE_MAX];
425 char real_blkdev[PROPERTY_VALUE_MAX];
426 unsigned int nr_sec;
427 int rc = -1;
428
429 if (!cached_data) {
430 fs_mgr_get_crypt_info(fstab, key_loc, real_blkdev, sizeof(key_loc));
431
432 if (!strcmp(key_loc, KEY_IN_FOOTER)) {
433 if ( (fd = open(real_blkdev, O_RDWR)) < 0) {
434 SLOGE("Cannot open real block device %s\n", real_blkdev);
435 return -1;
436 }
437
438 if ((nr_sec = get_blkdev_size(fd))) {
439 /* If it's an encrypted Android partition, the last 16 Kbytes contain the
440 * encryption info footer and key, and plenty of bytes to spare for future
441 * growth.
442 */
443 strlcpy(cached_metadata_fname, real_blkdev, sizeof(cached_metadata_fname));
444 cached_off = ((off64_t)nr_sec * 512) - CRYPT_FOOTER_OFFSET;
445 cached_data = 1;
446 } else {
447 SLOGE("Cannot get size of block device %s\n", real_blkdev);
448 }
449 close(fd);
450 } else {
451 strlcpy(cached_metadata_fname, key_loc, sizeof(cached_metadata_fname));
452 cached_off = 0;
453 cached_data = 1;
454 }
455 }
456
457 if (cached_data) {
458 if (metadata_fname) {
459 *metadata_fname = cached_metadata_fname;
460 }
461 if (off) {
462 *off = cached_off;
463 }
464 rc = 0;
465 }
466
467 return rc;
468}
469
Ken Sumralle8744072011-01-18 22:01:55 -0800470/* key or salt can be NULL, in which case just skip writing that value. Useful to
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800471 * update the failed mount count but not change the key.
472 */
Ken Sumrall160b4d62013-04-22 12:15:39 -0700473static int put_crypt_ftr_and_key(struct crypt_mnt_ftr *crypt_ftr)
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800474{
475 int fd;
476 unsigned int nr_sec, cnt;
Ken Sumrall160b4d62013-04-22 12:15:39 -0700477 /* starting_off is set to the SEEK_SET offset
478 * where the crypto structure starts
479 */
480 off64_t starting_off;
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800481 int rc = -1;
Ken Sumrall160b4d62013-04-22 12:15:39 -0700482 char *fname = NULL;
Ken Sumrall3be890f2011-09-14 16:53:46 -0700483 struct stat statbuf;
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800484
Ken Sumrall160b4d62013-04-22 12:15:39 -0700485 if (get_crypt_ftr_info(&fname, &starting_off)) {
486 SLOGE("Unable to get crypt_ftr_info\n");
487 return -1;
488 }
489 if (fname[0] != '/') {
Ken Sumralle5032c42012-04-01 23:58:44 -0700490 SLOGE("Unexpected value for crypto key location\n");
Ken Sumrall160b4d62013-04-22 12:15:39 -0700491 return -1;
492 }
Ken Sumralle550f782013-08-20 13:48:23 -0700493 if ( (fd = open(fname, O_RDWR | O_CREAT, 0600)) < 0) {
494 SLOGE("Cannot open footer file %s for put\n", fname);
Ken Sumrall160b4d62013-04-22 12:15:39 -0700495 return -1;
496 }
497
498 /* Seek to the start of the crypt footer */
499 if (lseek64(fd, starting_off, SEEK_SET) == -1) {
500 SLOGE("Cannot seek to real block device footer\n");
501 goto errout;
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800502 }
503
504 if ((cnt = write(fd, crypt_ftr, sizeof(struct crypt_mnt_ftr))) != sizeof(struct crypt_mnt_ftr)) {
505 SLOGE("Cannot write real block device footer\n");
506 goto errout;
507 }
508
Ken Sumrall3be890f2011-09-14 16:53:46 -0700509 fstat(fd, &statbuf);
510 /* If the keys are kept on a raw block device, do not try to truncate it. */
Ken Sumralle550f782013-08-20 13:48:23 -0700511 if (S_ISREG(statbuf.st_mode)) {
Ken Sumrall29d8da82011-05-18 17:20:07 -0700512 if (ftruncate(fd, 0x4000)) {
Colin Cross59846b62014-02-06 20:34:29 -0800513 SLOGE("Cannot set footer file size\n");
Ken Sumralle8744072011-01-18 22:01:55 -0800514 goto errout;
515 }
516 }
517
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800518 /* Success! */
519 rc = 0;
520
521errout:
522 close(fd);
523 return rc;
524
525}
526
Ken Sumrall160b4d62013-04-22 12:15:39 -0700527static inline int unix_read(int fd, void* buff, int len)
528{
529 return TEMP_FAILURE_RETRY(read(fd, buff, len));
530}
531
532static inline int unix_write(int fd, const void* buff, int len)
533{
534 return TEMP_FAILURE_RETRY(write(fd, buff, len));
535}
536
537static void init_empty_persist_data(struct crypt_persist_data *pdata, int len)
538{
539 memset(pdata, 0, len);
540 pdata->persist_magic = PERSIST_DATA_MAGIC;
541 pdata->persist_valid_entries = 0;
542}
543
544/* A routine to update the passed in crypt_ftr to the lastest version.
545 * fd is open read/write on the device that holds the crypto footer and persistent
546 * data, crypt_ftr is a pointer to the struct to be updated, and offset is the
547 * absolute offset to the start of the crypt_mnt_ftr on the passed in fd.
548 */
549static void upgrade_crypt_ftr(int fd, struct crypt_mnt_ftr *crypt_ftr, off64_t offset)
550{
Kenny Root7434b312013-06-14 11:29:53 -0700551 int orig_major = crypt_ftr->major_version;
552 int orig_minor = crypt_ftr->minor_version;
Ken Sumrall160b4d62013-04-22 12:15:39 -0700553
Kenny Root7434b312013-06-14 11:29:53 -0700554 if ((crypt_ftr->major_version == 1) && (crypt_ftr->minor_version == 0)) {
555 struct crypt_persist_data *pdata;
556 off64_t pdata_offset = offset + CRYPT_FOOTER_TO_PERSIST_OFFSET;
Ken Sumrall160b4d62013-04-22 12:15:39 -0700557
Kenny Rootc4c70f12013-06-14 12:11:38 -0700558 SLOGW("upgrading crypto footer to 1.1");
559
Kenny Root7434b312013-06-14 11:29:53 -0700560 pdata = malloc(CRYPT_PERSIST_DATA_SIZE);
561 if (pdata == NULL) {
562 SLOGE("Cannot allocate persisent data\n");
563 return;
564 }
565 memset(pdata, 0, CRYPT_PERSIST_DATA_SIZE);
566
567 /* Need to initialize the persistent data area */
568 if (lseek64(fd, pdata_offset, SEEK_SET) == -1) {
569 SLOGE("Cannot seek to persisent data offset\n");
570 return;
571 }
572 /* Write all zeros to the first copy, making it invalid */
573 unix_write(fd, pdata, CRYPT_PERSIST_DATA_SIZE);
574
575 /* Write a valid but empty structure to the second copy */
576 init_empty_persist_data(pdata, CRYPT_PERSIST_DATA_SIZE);
577 unix_write(fd, pdata, CRYPT_PERSIST_DATA_SIZE);
578
579 /* Update the footer */
580 crypt_ftr->persist_data_size = CRYPT_PERSIST_DATA_SIZE;
581 crypt_ftr->persist_data_offset[0] = pdata_offset;
582 crypt_ftr->persist_data_offset[1] = pdata_offset + CRYPT_PERSIST_DATA_SIZE;
583 crypt_ftr->minor_version = 1;
Ken Sumrall160b4d62013-04-22 12:15:39 -0700584 }
585
Paul Lawrencef4faa572014-01-29 13:31:03 -0800586 if ((crypt_ftr->major_version == 1) && (crypt_ftr->minor_version == 1)) {
Kenny Rootc4c70f12013-06-14 12:11:38 -0700587 SLOGW("upgrading crypto footer to 1.2");
JP Abgrall7bdfa522013-11-15 13:42:56 -0800588 /* But keep the old kdf_type.
589 * It will get updated later to KDF_SCRYPT after the password has been verified.
590 */
Kenny Rootc4c70f12013-06-14 12:11:38 -0700591 crypt_ftr->kdf_type = KDF_PBKDF2;
592 get_device_scrypt_params(crypt_ftr);
593 crypt_ftr->minor_version = 2;
594 }
595
Paul Lawrencef4faa572014-01-29 13:31:03 -0800596 if ((crypt_ftr->major_version == 1) && (crypt_ftr->minor_version == 2)) {
597 SLOGW("upgrading crypto footer to 1.3");
598 crypt_ftr->crypt_type = CRYPT_TYPE_PASSWORD;
599 crypt_ftr->minor_version = 3;
600 }
601
Kenny Root7434b312013-06-14 11:29:53 -0700602 if ((orig_major != crypt_ftr->major_version) || (orig_minor != crypt_ftr->minor_version)) {
603 if (lseek64(fd, offset, SEEK_SET) == -1) {
604 SLOGE("Cannot seek to crypt footer\n");
605 return;
606 }
607 unix_write(fd, crypt_ftr, sizeof(struct crypt_mnt_ftr));
Ken Sumrall160b4d62013-04-22 12:15:39 -0700608 }
Ken Sumrall160b4d62013-04-22 12:15:39 -0700609}
610
611
612static int get_crypt_ftr_and_key(struct crypt_mnt_ftr *crypt_ftr)
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800613{
614 int fd;
615 unsigned int nr_sec, cnt;
Ken Sumrall160b4d62013-04-22 12:15:39 -0700616 off64_t starting_off;
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800617 int rc = -1;
Ken Sumrall160b4d62013-04-22 12:15:39 -0700618 char *fname = NULL;
Ken Sumrall29d8da82011-05-18 17:20:07 -0700619 struct stat statbuf;
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800620
Ken Sumrall160b4d62013-04-22 12:15:39 -0700621 if (get_crypt_ftr_info(&fname, &starting_off)) {
622 SLOGE("Unable to get crypt_ftr_info\n");
623 return -1;
624 }
625 if (fname[0] != '/') {
Ken Sumralle5032c42012-04-01 23:58:44 -0700626 SLOGE("Unexpected value for crypto key location\n");
Ken Sumrall160b4d62013-04-22 12:15:39 -0700627 return -1;
628 }
629 if ( (fd = open(fname, O_RDWR)) < 0) {
Ken Sumralle550f782013-08-20 13:48:23 -0700630 SLOGE("Cannot open footer file %s for get\n", fname);
Ken Sumrall160b4d62013-04-22 12:15:39 -0700631 return -1;
632 }
633
634 /* Make sure it's 16 Kbytes in length */
635 fstat(fd, &statbuf);
636 if (S_ISREG(statbuf.st_mode) && (statbuf.st_size != 0x4000)) {
637 SLOGE("footer file %s is not the expected size!\n", fname);
638 goto errout;
639 }
640
641 /* Seek to the start of the crypt footer */
642 if (lseek64(fd, starting_off, SEEK_SET) == -1) {
643 SLOGE("Cannot seek to real block device footer\n");
644 goto errout;
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800645 }
646
647 if ( (cnt = read(fd, crypt_ftr, sizeof(struct crypt_mnt_ftr))) != sizeof(struct crypt_mnt_ftr)) {
648 SLOGE("Cannot read real block device footer\n");
649 goto errout;
650 }
651
652 if (crypt_ftr->magic != CRYPT_MNT_MAGIC) {
Ken Sumrall29d8da82011-05-18 17:20:07 -0700653 SLOGE("Bad magic for real block device %s\n", fname);
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800654 goto errout;
655 }
656
Kenny Rootc96a5f82013-06-14 12:08:28 -0700657 if (crypt_ftr->major_version != CURRENT_MAJOR_VERSION) {
658 SLOGE("Cannot understand major version %d real block device footer; expected %d\n",
659 crypt_ftr->major_version, CURRENT_MAJOR_VERSION);
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800660 goto errout;
661 }
662
Kenny Rootc96a5f82013-06-14 12:08:28 -0700663 if (crypt_ftr->minor_version > CURRENT_MINOR_VERSION) {
664 SLOGW("Warning: crypto footer minor version %d, expected <= %d, continuing...\n",
665 crypt_ftr->minor_version, CURRENT_MINOR_VERSION);
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800666 }
667
Ken Sumrall160b4d62013-04-22 12:15:39 -0700668 /* If this is a verion 1.0 crypt_ftr, make it a 1.1 crypt footer, and update the
669 * copy on disk before returning.
670 */
Kenny Rootc96a5f82013-06-14 12:08:28 -0700671 if (crypt_ftr->minor_version < CURRENT_MINOR_VERSION) {
Ken Sumrall160b4d62013-04-22 12:15:39 -0700672 upgrade_crypt_ftr(fd, crypt_ftr, starting_off);
Ken Sumralle8744072011-01-18 22:01:55 -0800673 }
674
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800675 /* Success! */
676 rc = 0;
677
678errout:
679 close(fd);
680 return rc;
681}
682
Ken Sumrall160b4d62013-04-22 12:15:39 -0700683static int validate_persistent_data_storage(struct crypt_mnt_ftr *crypt_ftr)
684{
685 if (crypt_ftr->persist_data_offset[0] + crypt_ftr->persist_data_size >
686 crypt_ftr->persist_data_offset[1]) {
687 SLOGE("Crypt_ftr persist data regions overlap");
688 return -1;
689 }
690
691 if (crypt_ftr->persist_data_offset[0] >= crypt_ftr->persist_data_offset[1]) {
692 SLOGE("Crypt_ftr persist data region 0 starts after region 1");
693 return -1;
694 }
695
696 if (((crypt_ftr->persist_data_offset[1] + crypt_ftr->persist_data_size) -
697 (crypt_ftr->persist_data_offset[0] - CRYPT_FOOTER_TO_PERSIST_OFFSET)) >
698 CRYPT_FOOTER_OFFSET) {
699 SLOGE("Persistent data extends past crypto footer");
700 return -1;
701 }
702
703 return 0;
704}
705
706static int load_persistent_data(void)
707{
708 struct crypt_mnt_ftr crypt_ftr;
709 struct crypt_persist_data *pdata = NULL;
710 char encrypted_state[PROPERTY_VALUE_MAX];
711 char *fname;
712 int found = 0;
713 int fd;
714 int ret;
715 int i;
716
717 if (persist_data) {
718 /* Nothing to do, we've already loaded or initialized it */
719 return 0;
720 }
721
722
723 /* If not encrypted, just allocate an empty table and initialize it */
724 property_get("ro.crypto.state", encrypted_state, "");
725 if (strcmp(encrypted_state, "encrypted") ) {
726 pdata = malloc(CRYPT_PERSIST_DATA_SIZE);
727 if (pdata) {
728 init_empty_persist_data(pdata, CRYPT_PERSIST_DATA_SIZE);
729 persist_data = pdata;
730 return 0;
731 }
732 return -1;
733 }
734
735 if(get_crypt_ftr_and_key(&crypt_ftr)) {
736 return -1;
737 }
738
Paul Lawrence8561b5c2014-03-17 14:10:51 -0700739 if ((crypt_ftr.major_version < 1)
740 || (crypt_ftr.major_version == 1 && crypt_ftr.minor_version < 1)) {
Ken Sumrall160b4d62013-04-22 12:15:39 -0700741 SLOGE("Crypt_ftr version doesn't support persistent data");
742 return -1;
743 }
744
745 if (get_crypt_ftr_info(&fname, NULL)) {
746 return -1;
747 }
748
749 ret = validate_persistent_data_storage(&crypt_ftr);
750 if (ret) {
751 return -1;
752 }
753
754 fd = open(fname, O_RDONLY);
755 if (fd < 0) {
756 SLOGE("Cannot open %s metadata file", fname);
757 return -1;
758 }
759
760 if (persist_data == NULL) {
761 pdata = malloc(crypt_ftr.persist_data_size);
762 if (pdata == NULL) {
763 SLOGE("Cannot allocate memory for persistent data");
764 goto err;
765 }
766 }
767
768 for (i = 0; i < 2; i++) {
769 if (lseek64(fd, crypt_ftr.persist_data_offset[i], SEEK_SET) < 0) {
770 SLOGE("Cannot seek to read persistent data on %s", fname);
771 goto err2;
772 }
773 if (unix_read(fd, pdata, crypt_ftr.persist_data_size) < 0){
774 SLOGE("Error reading persistent data on iteration %d", i);
775 goto err2;
776 }
777 if (pdata->persist_magic == PERSIST_DATA_MAGIC) {
778 found = 1;
779 break;
780 }
781 }
782
783 if (!found) {
784 SLOGI("Could not find valid persistent data, creating");
785 init_empty_persist_data(pdata, crypt_ftr.persist_data_size);
786 }
787
788 /* Success */
789 persist_data = pdata;
790 close(fd);
791 return 0;
792
793err2:
794 free(pdata);
795
796err:
797 close(fd);
798 return -1;
799}
800
801static int save_persistent_data(void)
802{
803 struct crypt_mnt_ftr crypt_ftr;
804 struct crypt_persist_data *pdata;
805 char *fname;
806 off64_t write_offset;
807 off64_t erase_offset;
808 int found = 0;
809 int fd;
810 int ret;
811
812 if (persist_data == NULL) {
813 SLOGE("No persistent data to save");
814 return -1;
815 }
816
817 if(get_crypt_ftr_and_key(&crypt_ftr)) {
818 return -1;
819 }
820
Paul Lawrence8561b5c2014-03-17 14:10:51 -0700821 if ((crypt_ftr.major_version < 1)
822 || (crypt_ftr.major_version == 1 && crypt_ftr.minor_version < 1)) {
Ken Sumrall160b4d62013-04-22 12:15:39 -0700823 SLOGE("Crypt_ftr version doesn't support persistent data");
824 return -1;
825 }
826
827 ret = validate_persistent_data_storage(&crypt_ftr);
828 if (ret) {
829 return -1;
830 }
831
832 if (get_crypt_ftr_info(&fname, NULL)) {
833 return -1;
834 }
835
836 fd = open(fname, O_RDWR);
837 if (fd < 0) {
838 SLOGE("Cannot open %s metadata file", fname);
839 return -1;
840 }
841
842 pdata = malloc(crypt_ftr.persist_data_size);
843 if (pdata == NULL) {
844 SLOGE("Cannot allocate persistant data");
845 goto err;
846 }
847
848 if (lseek64(fd, crypt_ftr.persist_data_offset[0], SEEK_SET) < 0) {
849 SLOGE("Cannot seek to read persistent data on %s", fname);
850 goto err2;
851 }
852
853 if (unix_read(fd, pdata, crypt_ftr.persist_data_size) < 0) {
854 SLOGE("Error reading persistent data before save");
855 goto err2;
856 }
857
858 if (pdata->persist_magic == PERSIST_DATA_MAGIC) {
859 /* The first copy is the curent valid copy, so write to
860 * the second copy and erase this one */
861 write_offset = crypt_ftr.persist_data_offset[1];
862 erase_offset = crypt_ftr.persist_data_offset[0];
863 } else {
864 /* The second copy must be the valid copy, so write to
865 * the first copy, and erase the second */
866 write_offset = crypt_ftr.persist_data_offset[0];
867 erase_offset = crypt_ftr.persist_data_offset[1];
868 }
869
870 /* Write the new copy first, if successful, then erase the old copy */
871 if (lseek(fd, write_offset, SEEK_SET) < 0) {
872 SLOGE("Cannot seek to write persistent data");
873 goto err2;
874 }
875 if (unix_write(fd, persist_data, crypt_ftr.persist_data_size) ==
876 (int) crypt_ftr.persist_data_size) {
877 if (lseek(fd, erase_offset, SEEK_SET) < 0) {
878 SLOGE("Cannot seek to erase previous persistent data");
879 goto err2;
880 }
881 fsync(fd);
882 memset(pdata, 0, crypt_ftr.persist_data_size);
883 if (unix_write(fd, pdata, crypt_ftr.persist_data_size) !=
884 (int) crypt_ftr.persist_data_size) {
885 SLOGE("Cannot write to erase previous persistent data");
886 goto err2;
887 }
888 fsync(fd);
889 } else {
890 SLOGE("Cannot write to save persistent data");
891 goto err2;
892 }
893
894 /* Success */
895 free(pdata);
896 close(fd);
897 return 0;
898
899err2:
900 free(pdata);
901err:
902 close(fd);
903 return -1;
904}
905
Paul Lawrencef4faa572014-01-29 13:31:03 -0800906static int hexdigit (char c)
907{
908 if (c >= '0' && c <= '9') return c - '0';
909 c = tolower(c);
910 if (c >= 'a' && c <= 'f') return c - 'a' + 10;
911 return -1;
912}
913
914static unsigned char* convert_hex_ascii_to_key(const char* master_key_ascii,
915 unsigned int* out_keysize)
916{
917 unsigned int i;
918 *out_keysize = 0;
919
920 size_t size = strlen (master_key_ascii);
921 if (size % 2) {
922 SLOGE("Trying to convert ascii string of odd length");
923 return NULL;
924 }
925
926 unsigned char* master_key = (unsigned char*) malloc(size / 2);
927 if (master_key == 0) {
928 SLOGE("Cannot allocate");
929 return NULL;
930 }
931
932 for (i = 0; i < size; i += 2) {
933 int high_nibble = hexdigit (master_key_ascii[i]);
934 int low_nibble = hexdigit (master_key_ascii[i + 1]);
935
936 if(high_nibble < 0 || low_nibble < 0) {
937 SLOGE("Invalid hex string");
938 free (master_key);
939 return NULL;
940 }
941
942 master_key[*out_keysize] = high_nibble * 16 + low_nibble;
943 (*out_keysize)++;
944 }
945
946 return master_key;
947}
948
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800949/* Convert a binary key of specified length into an ascii hex string equivalent,
950 * without the leading 0x and with null termination
951 */
Paul Lawrencef4faa572014-01-29 13:31:03 -0800952static void convert_key_to_hex_ascii(unsigned char *master_key, unsigned int keysize,
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800953 char *master_key_ascii)
954{
955 unsigned int i, a;
956 unsigned char nibble;
957
958 for (i=0, a=0; i<keysize; i++, a+=2) {
959 /* For each byte, write out two ascii hex digits */
960 nibble = (master_key[i] >> 4) & 0xf;
961 master_key_ascii[a] = nibble + (nibble > 9 ? 0x37 : 0x30);
962
963 nibble = master_key[i] & 0xf;
964 master_key_ascii[a+1] = nibble + (nibble > 9 ? 0x37 : 0x30);
965 }
966
967 /* Add the null termination */
968 master_key_ascii[a] = '\0';
969
970}
971
Ken Sumralldb5e0262013-02-05 17:39:48 -0800972static int load_crypto_mapping_table(struct crypt_mnt_ftr *crypt_ftr, unsigned char *master_key,
973 char *real_blk_name, const char *name, int fd,
974 char *extra_params)
975{
976 char buffer[DM_CRYPT_BUF_SIZE];
977 struct dm_ioctl *io;
978 struct dm_target_spec *tgt;
979 char *crypt_params;
980 char master_key_ascii[129]; /* Large enough to hold 512 bit key and null */
981 int i;
982
983 io = (struct dm_ioctl *) buffer;
984
985 /* Load the mapping table for this device */
986 tgt = (struct dm_target_spec *) &buffer[sizeof(struct dm_ioctl)];
987
988 ioctl_init(io, DM_CRYPT_BUF_SIZE, name, 0);
989 io->target_count = 1;
990 tgt->status = 0;
991 tgt->sector_start = 0;
992 tgt->length = crypt_ftr->fs_size;
993 strcpy(tgt->target_type, "crypt");
994
995 crypt_params = buffer + sizeof(struct dm_ioctl) + sizeof(struct dm_target_spec);
996 convert_key_to_hex_ascii(master_key, crypt_ftr->keysize, master_key_ascii);
997 sprintf(crypt_params, "%s %s 0 %s 0 %s", crypt_ftr->crypto_type_name,
998 master_key_ascii, real_blk_name, extra_params);
999 crypt_params += strlen(crypt_params) + 1;
1000 crypt_params = (char *) (((unsigned long)crypt_params + 7) & ~8); /* Align to an 8 byte boundary */
1001 tgt->next = crypt_params - buffer;
1002
1003 for (i = 0; i < TABLE_LOAD_RETRIES; i++) {
1004 if (! ioctl(fd, DM_TABLE_LOAD, io)) {
1005 break;
1006 }
1007 usleep(500000);
1008 }
1009
1010 if (i == TABLE_LOAD_RETRIES) {
1011 /* We failed to load the table, return an error */
1012 return -1;
1013 } else {
1014 return i + 1;
1015 }
1016}
1017
1018
1019static int get_dm_crypt_version(int fd, const char *name, int *version)
1020{
1021 char buffer[DM_CRYPT_BUF_SIZE];
1022 struct dm_ioctl *io;
1023 struct dm_target_versions *v;
1024 int i;
1025
1026 io = (struct dm_ioctl *) buffer;
1027
1028 ioctl_init(io, DM_CRYPT_BUF_SIZE, name, 0);
1029
1030 if (ioctl(fd, DM_LIST_VERSIONS, io)) {
1031 return -1;
1032 }
1033
1034 /* Iterate over the returned versions, looking for name of "crypt".
1035 * When found, get and return the version.
1036 */
1037 v = (struct dm_target_versions *) &buffer[sizeof(struct dm_ioctl)];
1038 while (v->next) {
1039 if (! strcmp(v->name, "crypt")) {
1040 /* We found the crypt driver, return the version, and get out */
1041 version[0] = v->version[0];
1042 version[1] = v->version[1];
1043 version[2] = v->version[2];
1044 return 0;
1045 }
1046 v = (struct dm_target_versions *)(((char *)v) + v->next);
1047 }
1048
1049 return -1;
1050}
1051
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001052static int create_crypto_blk_dev(struct crypt_mnt_ftr *crypt_ftr, unsigned char *master_key,
Ken Sumrall29d8da82011-05-18 17:20:07 -07001053 char *real_blk_name, char *crypto_blk_name, const char *name)
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001054{
1055 char buffer[DM_CRYPT_BUF_SIZE];
1056 char master_key_ascii[129]; /* Large enough to hold 512 bit key and null */
1057 char *crypt_params;
1058 struct dm_ioctl *io;
1059 struct dm_target_spec *tgt;
1060 unsigned int minor;
1061 int fd;
Ken Sumralle919efe2012-09-29 17:07:41 -07001062 int i;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001063 int retval = -1;
Ken Sumralldb5e0262013-02-05 17:39:48 -08001064 int version[3];
1065 char *extra_params;
1066 int load_count;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001067
1068 if ((fd = open("/dev/device-mapper", O_RDWR)) < 0 ) {
1069 SLOGE("Cannot open device-mapper\n");
1070 goto errout;
1071 }
1072
1073 io = (struct dm_ioctl *) buffer;
1074
1075 ioctl_init(io, DM_CRYPT_BUF_SIZE, name, 0);
1076 if (ioctl(fd, DM_DEV_CREATE, io)) {
1077 SLOGE("Cannot create dm-crypt device\n");
1078 goto errout;
1079 }
1080
1081 /* Get the device status, in particular, the name of it's device file */
1082 ioctl_init(io, DM_CRYPT_BUF_SIZE, name, 0);
1083 if (ioctl(fd, DM_DEV_STATUS, io)) {
1084 SLOGE("Cannot retrieve dm-crypt device status\n");
1085 goto errout;
1086 }
1087 minor = (io->dev & 0xff) | ((io->dev >> 12) & 0xfff00);
1088 snprintf(crypto_blk_name, MAXPATHLEN, "/dev/block/dm-%u", minor);
1089
Ken Sumralldb5e0262013-02-05 17:39:48 -08001090 extra_params = "";
1091 if (! get_dm_crypt_version(fd, name, version)) {
1092 /* Support for allow_discards was added in version 1.11.0 */
1093 if ((version[0] >= 2) ||
1094 ((version[0] == 1) && (version[1] >= 11))) {
1095 extra_params = "1 allow_discards";
1096 SLOGI("Enabling support for allow_discards in dmcrypt.\n");
1097 }
Ken Sumralle919efe2012-09-29 17:07:41 -07001098 }
1099
Ken Sumralldb5e0262013-02-05 17:39:48 -08001100 load_count = load_crypto_mapping_table(crypt_ftr, master_key, real_blk_name, name,
1101 fd, extra_params);
1102 if (load_count < 0) {
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001103 SLOGE("Cannot load dm-crypt mapping table.\n");
1104 goto errout;
Ken Sumralldb5e0262013-02-05 17:39:48 -08001105 } else if (load_count > 1) {
1106 SLOGI("Took %d tries to load dmcrypt table.\n", load_count);
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001107 }
1108
1109 /* Resume this device to activate it */
Ken Sumralldb5e0262013-02-05 17:39:48 -08001110 ioctl_init(io, DM_CRYPT_BUF_SIZE, name, 0);
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001111
1112 if (ioctl(fd, DM_DEV_SUSPEND, io)) {
1113 SLOGE("Cannot resume the dm-crypt device\n");
1114 goto errout;
1115 }
1116
1117 /* We made it here with no errors. Woot! */
1118 retval = 0;
1119
1120errout:
1121 close(fd); /* If fd is <0 from a failed open call, it's safe to just ignore the close error */
1122
1123 return retval;
1124}
1125
Ken Sumrall29d8da82011-05-18 17:20:07 -07001126static int delete_crypto_blk_dev(char *name)
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001127{
1128 int fd;
1129 char buffer[DM_CRYPT_BUF_SIZE];
1130 struct dm_ioctl *io;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001131 int retval = -1;
1132
1133 if ((fd = open("/dev/device-mapper", O_RDWR)) < 0 ) {
1134 SLOGE("Cannot open device-mapper\n");
1135 goto errout;
1136 }
1137
1138 io = (struct dm_ioctl *) buffer;
1139
1140 ioctl_init(io, DM_CRYPT_BUF_SIZE, name, 0);
1141 if (ioctl(fd, DM_DEV_REMOVE, io)) {
1142 SLOGE("Cannot remove dm-crypt device\n");
1143 goto errout;
1144 }
1145
1146 /* We made it here with no errors. Woot! */
1147 retval = 0;
1148
1149errout:
1150 close(fd); /* If fd is <0 from a failed open call, it's safe to just ignore the close error */
1151
1152 return retval;
1153
1154}
1155
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001156static int pbkdf2(const char *passwd, const unsigned char *salt,
Paul Lawrencef4faa572014-01-29 13:31:03 -08001157 unsigned char *ikey, void *params UNUSED)
1158{
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001159 SLOGI("Using pbkdf2 for cryptfs KDF");
1160
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001161 /* Turn the password into a key and IV that can decrypt the master key */
Paul Lawrencef4faa572014-01-29 13:31:03 -08001162 unsigned int keysize;
1163 char* master_key = (char*)convert_hex_ascii_to_key(passwd, &keysize);
1164 if (!master_key) return -1;
1165 PKCS5_PBKDF2_HMAC_SHA1(master_key, keysize, salt, SALT_LEN,
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001166 HASH_COUNT, KEY_LEN_BYTES+IV_LEN_BYTES, ikey);
Paul Lawrencef4faa572014-01-29 13:31:03 -08001167
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001168 memset(master_key, 0, keysize);
Paul Lawrencef4faa572014-01-29 13:31:03 -08001169 free (master_key);
1170 return 0;
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001171}
1172
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001173static int scrypt(const char *passwd, const unsigned char *salt,
Paul Lawrencef4faa572014-01-29 13:31:03 -08001174 unsigned char *ikey, void *params)
1175{
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001176 SLOGI("Using scrypt for cryptfs KDF");
1177
Kenny Rootc4c70f12013-06-14 12:11:38 -07001178 struct crypt_mnt_ftr *ftr = (struct crypt_mnt_ftr *) params;
1179
1180 int N = 1 << ftr->N_factor;
1181 int r = 1 << ftr->r_factor;
1182 int p = 1 << ftr->p_factor;
1183
1184 /* Turn the password into a key and IV that can decrypt the master key */
Paul Lawrencef4faa572014-01-29 13:31:03 -08001185 unsigned int keysize;
1186 unsigned char* master_key = convert_hex_ascii_to_key(passwd, &keysize);
1187 if (!master_key) return -1;
1188 crypto_scrypt(master_key, keysize, salt, SALT_LEN, N, r, p, ikey,
Kenny Rootc4c70f12013-06-14 12:11:38 -07001189 KEY_LEN_BYTES + IV_LEN_BYTES);
Paul Lawrencef4faa572014-01-29 13:31:03 -08001190
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001191 memset(master_key, 0, keysize);
Paul Lawrencef4faa572014-01-29 13:31:03 -08001192 free (master_key);
1193 return 0;
Kenny Rootc4c70f12013-06-14 12:11:38 -07001194}
1195
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001196static int scrypt_keymaster(const char *passwd, const unsigned char *salt,
1197 unsigned char *ikey, void *params)
1198{
1199 SLOGI("Using scrypt with keymaster for cryptfs KDF");
1200
1201 int rc;
1202 unsigned int key_size;
1203 size_t signature_size;
1204 unsigned char* signature;
1205 struct crypt_mnt_ftr *ftr = (struct crypt_mnt_ftr *) params;
1206
1207 int N = 1 << ftr->N_factor;
1208 int r = 1 << ftr->r_factor;
1209 int p = 1 << ftr->p_factor;
1210
1211 unsigned char* master_key = convert_hex_ascii_to_key(passwd, &key_size);
1212 if (!master_key) {
1213 SLOGE("Failed to convert passwd from hex");
1214 return -1;
1215 }
1216
1217 rc = crypto_scrypt(master_key, key_size, salt, SALT_LEN,
1218 N, r, p, ikey, KEY_LEN_BYTES + IV_LEN_BYTES);
1219 memset(master_key, 0, key_size);
1220 free(master_key);
1221
1222 if (rc) {
1223 SLOGE("scrypt failed");
1224 return -1;
1225 }
1226
Shawn Willdene17a9c42014-09-08 13:04:08 -06001227 if (keymaster_sign_object(ftr, ikey, KEY_LEN_BYTES + IV_LEN_BYTES,
1228 &signature, &signature_size)) {
1229 SLOGE("Signing failed");
1230 return -1;
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001231 }
1232
1233 rc = crypto_scrypt(signature, signature_size, salt, SALT_LEN,
1234 N, r, p, ikey, KEY_LEN_BYTES + IV_LEN_BYTES);
1235 free(signature);
1236
1237 if (rc) {
1238 SLOGE("scrypt failed");
1239 return -1;
1240 }
1241
1242 return 0;
1243}
1244
1245static int encrypt_master_key(const char *passwd, const unsigned char *salt,
1246 const unsigned char *decrypted_master_key,
Kenny Rootc4c70f12013-06-14 12:11:38 -07001247 unsigned char *encrypted_master_key,
1248 struct crypt_mnt_ftr *crypt_ftr)
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001249{
1250 unsigned char ikey[32+32] = { 0 }; /* Big enough to hold a 256 bit key and 256 bit IV */
1251 EVP_CIPHER_CTX e_ctx;
1252 int encrypted_len, final_len;
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001253 int rc = 0;
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001254
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001255 /* Turn the password into an intermediate key and IV that can decrypt the master key */
Kenny Rootc4c70f12013-06-14 12:11:38 -07001256 get_device_scrypt_params(crypt_ftr);
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001257
1258 switch (crypt_ftr->kdf_type) {
Shawn Willdene17a9c42014-09-08 13:04:08 -06001259 case KDF_SCRYPT_KEYMASTER_UNPADDED:
1260 case KDF_SCRYPT_KEYMASTER_BADLY_PADDED:
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001261 case KDF_SCRYPT_KEYMASTER:
1262 if (keymaster_create_key(crypt_ftr)) {
1263 SLOGE("keymaster_create_key failed");
1264 return -1;
1265 }
1266
1267 if (scrypt_keymaster(passwd, salt, ikey, crypt_ftr)) {
1268 SLOGE("scrypt failed");
1269 return -1;
1270 }
1271 break;
1272
1273 case KDF_SCRYPT:
1274 if (scrypt(passwd, salt, ikey, crypt_ftr)) {
1275 SLOGE("scrypt failed");
1276 return -1;
1277 }
1278 break;
1279
1280 default:
1281 SLOGE("Invalid kdf_type");
Paul Lawrencef4faa572014-01-29 13:31:03 -08001282 return -1;
1283 }
Kenny Rootc4c70f12013-06-14 12:11:38 -07001284
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001285 /* Initialize the decryption engine */
1286 if (! EVP_EncryptInit(&e_ctx, EVP_aes_128_cbc(), ikey, ikey+KEY_LEN_BYTES)) {
1287 SLOGE("EVP_EncryptInit failed\n");
1288 return -1;
1289 }
1290 EVP_CIPHER_CTX_set_padding(&e_ctx, 0); /* Turn off padding as our data is block aligned */
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001291
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001292 /* Encrypt the master key */
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001293 if (! EVP_EncryptUpdate(&e_ctx, encrypted_master_key, &encrypted_len,
1294 decrypted_master_key, KEY_LEN_BYTES)) {
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001295 SLOGE("EVP_EncryptUpdate failed\n");
1296 return -1;
1297 }
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001298 if (! EVP_EncryptFinal(&e_ctx, encrypted_master_key + encrypted_len, &final_len)) {
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001299 SLOGE("EVP_EncryptFinal failed\n");
1300 return -1;
1301 }
1302
1303 if (encrypted_len + final_len != KEY_LEN_BYTES) {
1304 SLOGE("EVP_Encryption length check failed with %d, %d bytes\n", encrypted_len, final_len);
1305 return -1;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001306 }
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001307
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001308 /* Store the scrypt of the intermediate key, so we can validate if it's a
1309 password error or mount error when things go wrong.
1310 Note there's no need to check for errors, since if this is incorrect, we
1311 simply won't wipe userdata, which is the correct default behavior
1312 */
1313 int N = 1 << crypt_ftr->N_factor;
1314 int r = 1 << crypt_ftr->r_factor;
1315 int p = 1 << crypt_ftr->p_factor;
1316
1317 rc = crypto_scrypt(ikey, KEY_LEN_BYTES,
1318 crypt_ftr->salt, sizeof(crypt_ftr->salt), N, r, p,
1319 crypt_ftr->scrypted_intermediate_key,
1320 sizeof(crypt_ftr->scrypted_intermediate_key));
1321
1322 if (rc) {
1323 SLOGE("encrypt_master_key: crypto_scrypt failed");
1324 }
1325
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001326 return 0;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001327}
1328
JP Abgrall7bdfa522013-11-15 13:42:56 -08001329static int decrypt_master_key_aux(char *passwd, unsigned char *salt,
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001330 unsigned char *encrypted_master_key,
1331 unsigned char *decrypted_master_key,
1332 kdf_func kdf, void *kdf_params,
1333 unsigned char** intermediate_key,
1334 size_t* intermediate_key_size)
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001335{
1336 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 -08001337 EVP_CIPHER_CTX d_ctx;
1338 int decrypted_len, final_len;
1339
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001340 /* Turn the password into an intermediate key and IV that can decrypt the
1341 master key */
Paul Lawrencef4faa572014-01-29 13:31:03 -08001342 if (kdf(passwd, salt, ikey, kdf_params)) {
1343 SLOGE("kdf failed");
1344 return -1;
1345 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001346
1347 /* Initialize the decryption engine */
1348 if (! EVP_DecryptInit(&d_ctx, EVP_aes_128_cbc(), ikey, ikey+KEY_LEN_BYTES)) {
1349 return -1;
1350 }
1351 EVP_CIPHER_CTX_set_padding(&d_ctx, 0); /* Turn off padding as our data is block aligned */
1352 /* Decrypt the master key */
1353 if (! EVP_DecryptUpdate(&d_ctx, decrypted_master_key, &decrypted_len,
1354 encrypted_master_key, KEY_LEN_BYTES)) {
1355 return -1;
1356 }
1357 if (! EVP_DecryptFinal(&d_ctx, decrypted_master_key + decrypted_len, &final_len)) {
1358 return -1;
1359 }
1360
1361 if (decrypted_len + final_len != KEY_LEN_BYTES) {
1362 return -1;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001363 }
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001364
1365 /* Copy intermediate key if needed by params */
1366 if (intermediate_key && intermediate_key_size) {
1367 *intermediate_key = (unsigned char*) malloc(KEY_LEN_BYTES);
1368 if (intermediate_key) {
1369 memcpy(*intermediate_key, ikey, KEY_LEN_BYTES);
1370 *intermediate_key_size = KEY_LEN_BYTES;
1371 }
1372 }
1373
1374 return 0;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001375}
1376
Kenny Rootc4c70f12013-06-14 12:11:38 -07001377static void get_kdf_func(struct crypt_mnt_ftr *ftr, kdf_func *kdf, void** kdf_params)
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001378{
Shawn Willdene17a9c42014-09-08 13:04:08 -06001379 if (ftr->kdf_type == KDF_SCRYPT_KEYMASTER_UNPADDED ||
1380 ftr->kdf_type == KDF_SCRYPT_KEYMASTER_BADLY_PADDED ||
1381 ftr->kdf_type == KDF_SCRYPT_KEYMASTER) {
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001382 *kdf = scrypt_keymaster;
1383 *kdf_params = ftr;
1384 } else if (ftr->kdf_type == KDF_SCRYPT) {
Kenny Rootc4c70f12013-06-14 12:11:38 -07001385 *kdf = scrypt;
1386 *kdf_params = ftr;
1387 } else {
1388 *kdf = pbkdf2;
1389 *kdf_params = NULL;
1390 }
1391}
1392
JP Abgrall7bdfa522013-11-15 13:42:56 -08001393static int decrypt_master_key(char *passwd, unsigned char *decrypted_master_key,
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001394 struct crypt_mnt_ftr *crypt_ftr,
1395 unsigned char** intermediate_key,
1396 size_t* intermediate_key_size)
Kenny Rootc4c70f12013-06-14 12:11:38 -07001397{
1398 kdf_func kdf;
1399 void *kdf_params;
1400 int ret;
1401
1402 get_kdf_func(crypt_ftr, &kdf, &kdf_params);
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001403 ret = decrypt_master_key_aux(passwd, crypt_ftr->salt, crypt_ftr->master_key,
1404 decrypted_master_key, kdf, kdf_params,
1405 intermediate_key, intermediate_key_size);
Kenny Rootc4c70f12013-06-14 12:11:38 -07001406 if (ret != 0) {
1407 SLOGW("failure decrypting master key");
Kenny Rootc4c70f12013-06-14 12:11:38 -07001408 }
1409
1410 return ret;
1411}
1412
1413static int create_encrypted_random_key(char *passwd, unsigned char *master_key, unsigned char *salt,
1414 struct crypt_mnt_ftr *crypt_ftr) {
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001415 int fd;
Ken Sumralle8744072011-01-18 22:01:55 -08001416 unsigned char key_buf[KEY_LEN_BYTES];
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001417 EVP_CIPHER_CTX e_ctx;
1418 int encrypted_len, final_len;
1419
1420 /* Get some random bits for a key */
1421 fd = open("/dev/urandom", O_RDONLY);
Ken Sumralle8744072011-01-18 22:01:55 -08001422 read(fd, key_buf, sizeof(key_buf));
1423 read(fd, salt, SALT_LEN);
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001424 close(fd);
1425
1426 /* Now encrypt it with the password */
Kenny Rootc4c70f12013-06-14 12:11:38 -07001427 return encrypt_master_key(passwd, salt, key_buf, master_key, crypt_ftr);
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001428}
1429
Greg Hackmann6e8440f2014-10-02 17:18:20 -07001430static int wait_and_unmount(char *mountpoint, bool kill)
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001431{
Greg Hackmann955653e2014-09-24 14:55:20 -07001432 int i, err, rc;
Ken Sumrall2eaf7132011-01-14 12:45:48 -08001433#define WAIT_UNMOUNT_COUNT 20
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001434
1435 /* Now umount the tmpfs filesystem */
1436 for (i=0; i<WAIT_UNMOUNT_COUNT; i++) {
Greg Hackmann6e8440f2014-10-02 17:18:20 -07001437 if (umount(mountpoint) == 0) {
1438 break;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001439 }
Greg Hackmann6e8440f2014-10-02 17:18:20 -07001440
1441 if (errno == EINVAL) {
1442 /* EINVAL is returned if the directory is not a mountpoint,
1443 * i.e. there is no filesystem mounted there. So just get out.
1444 */
1445 break;
1446 }
1447
1448 err = errno;
1449
1450 /* If allowed, be increasingly aggressive before the last two retries */
1451 if (kill) {
1452 if (i == (WAIT_UNMOUNT_COUNT - 3)) {
1453 SLOGW("sending SIGHUP to processes with open files\n");
1454 vold_killProcessesWithOpenFiles(mountpoint, 1);
1455 } else if (i == (WAIT_UNMOUNT_COUNT - 2)) {
1456 SLOGW("sending SIGKILL to processes with open files\n");
1457 vold_killProcessesWithOpenFiles(mountpoint, 2);
1458 }
1459 }
1460
1461 sleep(1);
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001462 }
1463
1464 if (i < WAIT_UNMOUNT_COUNT) {
1465 SLOGD("unmounting %s succeeded\n", mountpoint);
1466 rc = 0;
1467 } else {
jessica_yu3f14fe42014-09-22 15:57:40 +08001468 vold_killProcessesWithOpenFiles(mountpoint, 0);
Greg Hackmann955653e2014-09-24 14:55:20 -07001469 SLOGE("unmounting %s failed: %s\n", mountpoint, strerror(err));
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001470 rc = -1;
1471 }
1472
1473 return rc;
1474}
1475
Ken Sumrallc5872692013-05-14 15:26:31 -07001476#define DATA_PREP_TIMEOUT 200
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001477static int prep_data_fs(void)
1478{
1479 int i;
1480
1481 /* Do the prep of the /data filesystem */
1482 property_set("vold.post_fs_data_done", "0");
1483 property_set("vold.decrypt", "trigger_post_fs_data");
1484 SLOGD("Just triggered post_fs_data\n");
1485
Ken Sumrallc5872692013-05-14 15:26:31 -07001486 /* Wait a max of 50 seconds, hopefully it takes much less */
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001487 for (i=0; i<DATA_PREP_TIMEOUT; i++) {
Ken Sumrall29d8da82011-05-18 17:20:07 -07001488 char p[PROPERTY_VALUE_MAX];
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001489
1490 property_get("vold.post_fs_data_done", p, "0");
1491 if (*p == '1') {
1492 break;
1493 } else {
1494 usleep(250000);
1495 }
1496 }
1497 if (i == DATA_PREP_TIMEOUT) {
1498 /* Ugh, we failed to prep /data in time. Bail. */
Ken Sumrallc5872692013-05-14 15:26:31 -07001499 SLOGE("post_fs_data timed out!\n");
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001500 return -1;
1501 } else {
1502 SLOGD("post_fs_data done\n");
1503 return 0;
1504 }
1505}
1506
Paul Lawrence74f29f12014-08-28 15:54:10 -07001507static void cryptfs_set_corrupt()
1508{
1509 // Mark the footer as bad
1510 struct crypt_mnt_ftr crypt_ftr;
1511 if (get_crypt_ftr_and_key(&crypt_ftr)) {
1512 SLOGE("Failed to get crypto footer - panic");
1513 return;
1514 }
1515
1516 crypt_ftr.flags |= CRYPT_DATA_CORRUPT;
1517 if (put_crypt_ftr_and_key(&crypt_ftr)) {
1518 SLOGE("Failed to set crypto footer - panic");
1519 return;
1520 }
1521}
1522
1523static void cryptfs_trigger_restart_min_framework()
1524{
1525 if (fs_mgr_do_tmpfs_mount(DATA_MNT_POINT)) {
1526 SLOGE("Failed to mount tmpfs on data - panic");
1527 return;
1528 }
1529
1530 if (property_set("vold.decrypt", "trigger_post_fs_data")) {
1531 SLOGE("Failed to trigger post fs data - panic");
1532 return;
1533 }
1534
1535 if (property_set("vold.decrypt", "trigger_restart_min_framework")) {
1536 SLOGE("Failed to trigger restart min framework - panic");
1537 return;
1538 }
1539}
1540
Paul Lawrence8e3f4512014-09-08 10:11:17 -07001541/* returns < 0 on failure */
Paul Lawrencef4faa572014-01-29 13:31:03 -08001542static int cryptfs_restart_internal(int restart_main)
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001543{
1544 char fs_type[32];
1545 char real_blkdev[MAXPATHLEN];
Ken Sumrall6864b7e2011-01-14 15:20:02 -08001546 char crypto_blkdev[MAXPATHLEN];
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001547 char fs_options[256];
1548 unsigned long mnt_flags;
1549 struct stat statbuf;
1550 int rc = -1, i;
Ken Sumrall0cc16632011-01-18 20:32:26 -08001551 static int restart_successful = 0;
1552
1553 /* Validate that it's OK to call this routine */
Jason parks70a4b3f2011-01-28 10:10:47 -06001554 if (! master_key_saved) {
Ken Sumrall0cc16632011-01-18 20:32:26 -08001555 SLOGE("Encrypted filesystem not validated, aborting");
1556 return -1;
1557 }
1558
1559 if (restart_successful) {
1560 SLOGE("System already restarted with encrypted disk, aborting");
1561 return -1;
1562 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001563
Paul Lawrencef4faa572014-01-29 13:31:03 -08001564 if (restart_main) {
1565 /* Here is where we shut down the framework. The init scripts
1566 * start all services in one of three classes: core, main or late_start.
1567 * On boot, we start core and main. Now, we stop main, but not core,
1568 * as core includes vold and a few other really important things that
1569 * we need to keep running. Once main has stopped, we should be able
1570 * to umount the tmpfs /data, then mount the encrypted /data.
1571 * We then restart the class main, and also the class late_start.
1572 * At the moment, I've only put a few things in late_start that I know
1573 * are not needed to bring up the framework, and that also cause problems
1574 * with unmounting the tmpfs /data, but I hope to add add more services
1575 * to the late_start class as we optimize this to decrease the delay
1576 * till the user is asked for the password to the filesystem.
1577 */
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001578
Paul Lawrencef4faa572014-01-29 13:31:03 -08001579 /* The init files are setup to stop the class main when vold.decrypt is
1580 * set to trigger_reset_main.
1581 */
1582 property_set("vold.decrypt", "trigger_reset_main");
1583 SLOGD("Just asked init to shut down class main\n");
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001584
Paul Lawrencef4faa572014-01-29 13:31:03 -08001585 /* Ugh, shutting down the framework is not synchronous, so until it
1586 * can be fixed, this horrible hack will wait a moment for it all to
1587 * shut down before proceeding. Without it, some devices cannot
1588 * restart the graphics services.
1589 */
1590 sleep(2);
1591 }
Ken Sumrall9dedfd42012-10-09 14:16:59 -07001592
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001593 /* Now that the framework is shutdown, we should be able to umount()
1594 * the tmpfs filesystem, and mount the real one.
1595 */
1596
Ken Sumrall6864b7e2011-01-14 15:20:02 -08001597 property_get("ro.crypto.fs_crypto_blkdev", crypto_blkdev, "");
1598 if (strlen(crypto_blkdev) == 0) {
1599 SLOGE("fs_crypto_blkdev not set\n");
1600 return -1;
1601 }
1602
Greg Hackmann6e8440f2014-10-02 17:18:20 -07001603 if (! (rc = wait_and_unmount(DATA_MNT_POINT, true)) ) {
Doug Zongker6fd57712013-12-17 09:43:23 -08001604 /* If ro.crypto.readonly is set to 1, mount the decrypted
1605 * filesystem readonly. This is used when /data is mounted by
1606 * recovery mode.
1607 */
1608 char ro_prop[PROPERTY_VALUE_MAX];
1609 property_get("ro.crypto.readonly", ro_prop, "");
1610 if (strlen(ro_prop) > 0 && atoi(ro_prop)) {
1611 struct fstab_rec* rec = fs_mgr_get_entry_for_mount_point(fstab, DATA_MNT_POINT);
1612 rec->flags |= MS_RDONLY;
1613 }
JP Abgrall62c7af32014-06-16 13:01:23 -07001614
Ken Sumralle5032c42012-04-01 23:58:44 -07001615 /* If that succeeded, then mount the decrypted filesystem */
Paul Lawrence8e3f4512014-09-08 10:11:17 -07001616 int retries = RETRY_MOUNT_ATTEMPTS;
1617 int mount_rc;
1618 while ((mount_rc = fs_mgr_do_mount(fstab, DATA_MNT_POINT,
1619 crypto_blkdev, 0))
1620 != 0) {
1621 if (mount_rc == FS_MGR_DOMNT_BUSY) {
1622 /* TODO: invoke something similar to
1623 Process::killProcessWithOpenFiles(DATA_MNT_POINT,
1624 retries > RETRY_MOUNT_ATTEMPT/2 ? 1 : 2 ) */
1625 SLOGI("Failed to mount %s because it is busy - waiting",
1626 crypto_blkdev);
1627 if (--retries) {
1628 sleep(RETRY_MOUNT_DELAY_SECONDS);
1629 } else {
1630 /* Let's hope that a reboot clears away whatever is keeping
1631 the mount busy */
1632 cryptfs_reboot(reboot);
1633 }
1634 } else {
1635 SLOGE("Failed to mount decrypted data");
1636 cryptfs_set_corrupt();
1637 cryptfs_trigger_restart_min_framework();
1638 SLOGI("Started framework to offer wipe");
1639 return -1;
1640 }
Paul Lawrence74f29f12014-08-28 15:54:10 -07001641 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001642
Ken Sumralle5032c42012-04-01 23:58:44 -07001643 property_set("vold.decrypt", "trigger_load_persist_props");
1644 /* Create necessary paths on /data */
1645 if (prep_data_fs()) {
1646 return -1;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001647 }
Ken Sumralle5032c42012-04-01 23:58:44 -07001648
1649 /* startup service classes main and late_start */
1650 property_set("vold.decrypt", "trigger_restart_framework");
1651 SLOGD("Just triggered restart_framework\n");
1652
1653 /* Give it a few moments to get started */
1654 sleep(1);
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001655 }
1656
Ken Sumrall0cc16632011-01-18 20:32:26 -08001657 if (rc == 0) {
1658 restart_successful = 1;
1659 }
1660
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001661 return rc;
1662}
1663
Paul Lawrencef4faa572014-01-29 13:31:03 -08001664int cryptfs_restart(void)
1665{
1666 /* Call internal implementation forcing a restart of main service group */
1667 return cryptfs_restart_internal(1);
1668}
1669
Mark Salyzyn3e971272014-01-21 13:27:04 -08001670static int do_crypto_complete(char *mount_point UNUSED)
Ken Sumrall7f7dbaa2011-02-01 15:46:41 -08001671{
1672 struct crypt_mnt_ftr crypt_ftr;
Ken Sumrall29d8da82011-05-18 17:20:07 -07001673 char encrypted_state[PROPERTY_VALUE_MAX];
Ken Sumralle1a45852011-12-14 21:24:27 -08001674 char key_loc[PROPERTY_VALUE_MAX];
Ken Sumrall7f7dbaa2011-02-01 15:46:41 -08001675
1676 property_get("ro.crypto.state", encrypted_state, "");
1677 if (strcmp(encrypted_state, "encrypted") ) {
1678 SLOGE("not running with encryption, aborting");
Paul Lawrence74f29f12014-08-28 15:54:10 -07001679 return CRYPTO_COMPLETE_NOT_ENCRYPTED;
Ken Sumrall7f7dbaa2011-02-01 15:46:41 -08001680 }
1681
Ken Sumrall160b4d62013-04-22 12:15:39 -07001682 if (get_crypt_ftr_and_key(&crypt_ftr)) {
Ken Sumrall56ad03c2013-02-13 13:00:19 -08001683 fs_mgr_get_crypt_info(fstab, key_loc, 0, sizeof(key_loc));
Ken Sumralle5032c42012-04-01 23:58:44 -07001684
Ken Sumralle1a45852011-12-14 21:24:27 -08001685 /*
1686 * Only report this error if key_loc is a file and it exists.
1687 * If the device was never encrypted, and /data is not mountable for
1688 * some reason, returning 1 should prevent the UI from presenting the
1689 * a "enter password" screen, or worse, a "press button to wipe the
1690 * device" screen.
1691 */
1692 if ((key_loc[0] == '/') && (access("key_loc", F_OK) == -1)) {
1693 SLOGE("master key file does not exist, aborting");
Paul Lawrence74f29f12014-08-28 15:54:10 -07001694 return CRYPTO_COMPLETE_NOT_ENCRYPTED;
Ken Sumralle1a45852011-12-14 21:24:27 -08001695 } else {
1696 SLOGE("Error getting crypt footer and key\n");
Paul Lawrence74f29f12014-08-28 15:54:10 -07001697 return CRYPTO_COMPLETE_BAD_METADATA;
Ken Sumralle1a45852011-12-14 21:24:27 -08001698 }
Ken Sumrall7f7dbaa2011-02-01 15:46:41 -08001699 }
1700
Paul Lawrence74f29f12014-08-28 15:54:10 -07001701 // Test for possible error flags
1702 if (crypt_ftr.flags & CRYPT_ENCRYPTION_IN_PROGRESS){
1703 SLOGE("Encryption process is partway completed\n");
1704 return CRYPTO_COMPLETE_PARTIAL;
1705 }
1706
1707 if (crypt_ftr.flags & CRYPT_INCONSISTENT_STATE){
1708 SLOGE("Encryption process was interrupted but cannot continue\n");
1709 return CRYPTO_COMPLETE_INCONSISTENT;
1710 }
1711
1712 if (crypt_ftr.flags & CRYPT_DATA_CORRUPT){
1713 SLOGE("Encryption is successful but data is corrupt\n");
1714 return CRYPTO_COMPLETE_CORRUPT;
Ken Sumrall7f7dbaa2011-02-01 15:46:41 -08001715 }
1716
1717 /* We passed the test! We shall diminish, and return to the west */
Paul Lawrence74f29f12014-08-28 15:54:10 -07001718 return CRYPTO_COMPLETE_ENCRYPTED;
Ken Sumrall7f7dbaa2011-02-01 15:46:41 -08001719}
1720
Paul Lawrencef4faa572014-01-29 13:31:03 -08001721static int test_mount_encrypted_fs(struct crypt_mnt_ftr* crypt_ftr,
1722 char *passwd, char *mount_point, char *label)
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001723{
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001724 /* Allocate enough space for a 256 bit key, but we may use less */
Ken Sumrall160b4d62013-04-22 12:15:39 -07001725 unsigned char decrypted_master_key[32];
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001726 char crypto_blkdev[MAXPATHLEN];
1727 char real_blkdev[MAXPATHLEN];
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001728 char tmp_mount_point[64];
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001729 unsigned int orig_failed_decrypt_count;
1730 int rc;
Kenny Rootc4c70f12013-06-14 12:11:38 -07001731 kdf_func kdf;
1732 void *kdf_params;
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001733 int use_keymaster = 0;
1734 int upgrade = 0;
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001735 unsigned char* intermediate_key = 0;
1736 size_t intermediate_key_size = 0;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001737
Paul Lawrencef4faa572014-01-29 13:31:03 -08001738 SLOGD("crypt_ftr->fs_size = %lld\n", crypt_ftr->fs_size);
1739 orig_failed_decrypt_count = crypt_ftr->failed_decrypt_count;
Ken Sumrall0cc16632011-01-18 20:32:26 -08001740
Paul Lawrencef4faa572014-01-29 13:31:03 -08001741 if (! (crypt_ftr->flags & CRYPT_MNT_KEY_UNENCRYPTED) ) {
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001742 if (decrypt_master_key(passwd, decrypted_master_key, crypt_ftr,
1743 &intermediate_key, &intermediate_key_size)) {
JP Abgrall7bdfa522013-11-15 13:42:56 -08001744 SLOGE("Failed to decrypt master key\n");
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001745 rc = -1;
1746 goto errout;
JP Abgrall7bdfa522013-11-15 13:42:56 -08001747 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001748 }
1749
Paul Lawrencef4faa572014-01-29 13:31:03 -08001750 fs_mgr_get_crypt_info(fstab, 0, real_blkdev, sizeof(real_blkdev));
1751
Paul Lawrence74f29f12014-08-28 15:54:10 -07001752 // Create crypto block device - all (non fatal) code paths
1753 // need it
Paul Lawrencef4faa572014-01-29 13:31:03 -08001754 if (create_crypto_blk_dev(crypt_ftr, decrypted_master_key,
1755 real_blkdev, crypto_blkdev, label)) {
Paul Lawrence74f29f12014-08-28 15:54:10 -07001756 SLOGE("Error creating decrypted block device\n");
1757 rc = -1;
1758 goto errout;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001759 }
1760
Paul Lawrence74f29f12014-08-28 15:54:10 -07001761 /* Work out if the problem is the password or the data */
1762 unsigned char scrypted_intermediate_key[sizeof(crypt_ftr->
1763 scrypted_intermediate_key)];
1764 int N = 1 << crypt_ftr->N_factor;
1765 int r = 1 << crypt_ftr->r_factor;
1766 int p = 1 << crypt_ftr->p_factor;
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001767
Paul Lawrence74f29f12014-08-28 15:54:10 -07001768 rc = crypto_scrypt(intermediate_key, intermediate_key_size,
1769 crypt_ftr->salt, sizeof(crypt_ftr->salt),
1770 N, r, p, scrypted_intermediate_key,
1771 sizeof(scrypted_intermediate_key));
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001772
Paul Lawrence74f29f12014-08-28 15:54:10 -07001773 // Does the key match the crypto footer?
1774 if (rc == 0 && memcmp(scrypted_intermediate_key,
1775 crypt_ftr->scrypted_intermediate_key,
1776 sizeof(scrypted_intermediate_key)) == 0) {
1777 SLOGI("Password matches");
1778 rc = 0;
1779 } else {
1780 /* Try mounting the file system anyway, just in case the problem's with
1781 * the footer, not the key. */
1782 sprintf(tmp_mount_point, "%s/tmp_mnt", mount_point);
1783 mkdir(tmp_mount_point, 0755);
1784 if (fs_mgr_do_mount(fstab, DATA_MNT_POINT, crypto_blkdev, tmp_mount_point)) {
1785 SLOGE("Error temp mounting decrypted block device\n");
1786 delete_crypto_blk_dev(label);
1787
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001788 rc = ++crypt_ftr->failed_decrypt_count;
1789 put_crypt_ftr_and_key(crypt_ftr);
Paul Lawrence74f29f12014-08-28 15:54:10 -07001790 } else {
1791 /* Success! */
1792 SLOGI("Password did not match but decrypted drive mounted - continue");
1793 umount(tmp_mount_point);
1794 rc = 0;
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001795 }
Paul Lawrence74f29f12014-08-28 15:54:10 -07001796 }
1797
1798 if (rc == 0) {
1799 crypt_ftr->failed_decrypt_count = 0;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001800
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001801 /* Save the name of the crypto block device
Paul Lawrence74f29f12014-08-28 15:54:10 -07001802 * so we can mount it when restarting the framework. */
Ken Sumrall6864b7e2011-01-14 15:20:02 -08001803 property_set("ro.crypto.fs_crypto_blkdev", crypto_blkdev);
Jason parks70a4b3f2011-01-28 10:10:47 -06001804
1805 /* Also save a the master key so we can reencrypted the key
Paul Lawrence74f29f12014-08-28 15:54:10 -07001806 * the key when we want to change the password on it. */
Jason parks70a4b3f2011-01-28 10:10:47 -06001807 memcpy(saved_master_key, decrypted_master_key, KEY_LEN_BYTES);
Ken Sumrall3ad90722011-10-04 20:38:29 -07001808 saved_mount_point = strdup(mount_point);
Jason parks70a4b3f2011-01-28 10:10:47 -06001809 master_key_saved = 1;
JP Abgrall7bdfa522013-11-15 13:42:56 -08001810 SLOGD("%s(): Master key saved\n", __FUNCTION__);
Ken Sumrall6864b7e2011-01-14 15:20:02 -08001811 rc = 0;
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001812
Paul Lawrence74f29f12014-08-28 15:54:10 -07001813 // Upgrade if we're not using the latest KDF.
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001814 use_keymaster = keymaster_check_compatibility();
1815 if (crypt_ftr->kdf_type == KDF_SCRYPT_KEYMASTER) {
Shawn Willden47ba10d2014-09-03 17:07:06 -06001816 // Don't allow downgrade
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001817 } else if (use_keymaster == 1 && crypt_ftr->kdf_type != KDF_SCRYPT_KEYMASTER) {
1818 crypt_ftr->kdf_type = KDF_SCRYPT_KEYMASTER;
1819 upgrade = 1;
1820 } else if (use_keymaster == 0 && crypt_ftr->kdf_type != KDF_SCRYPT) {
Paul Lawrencef4faa572014-01-29 13:31:03 -08001821 crypt_ftr->kdf_type = KDF_SCRYPT;
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001822 upgrade = 1;
1823 }
1824
1825 if (upgrade) {
Paul Lawrencef4faa572014-01-29 13:31:03 -08001826 rc = encrypt_master_key(passwd, crypt_ftr->salt, saved_master_key,
1827 crypt_ftr->master_key, crypt_ftr);
JP Abgrall7bdfa522013-11-15 13:42:56 -08001828 if (!rc) {
Paul Lawrencef4faa572014-01-29 13:31:03 -08001829 rc = put_crypt_ftr_and_key(crypt_ftr);
JP Abgrall7bdfa522013-11-15 13:42:56 -08001830 }
1831 SLOGD("Key Derivation Function upgrade: rc=%d\n", rc);
Paul Lawrenceb2f682b2014-09-08 11:28:19 -07001832
1833 // Do not fail even if upgrade failed - machine is bootable
1834 // Note that if this code is ever hit, there is a *serious* problem
1835 // since KDFs should never fail. You *must* fix the kdf before
1836 // proceeding!
1837 if (rc) {
1838 SLOGW("Upgrade failed with error %d,"
1839 " but continuing with previous state",
1840 rc);
1841 rc = 0;
1842 }
JP Abgrall7bdfa522013-11-15 13:42:56 -08001843 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001844 }
1845
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001846 errout:
1847 if (intermediate_key) {
1848 memset(intermediate_key, 0, intermediate_key_size);
1849 free(intermediate_key);
1850 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001851 return rc;
1852}
1853
Ken Sumrall0b8b5972011-08-31 16:14:23 -07001854/* Called by vold when it wants to undo the crypto mapping of a volume it
1855 * manages. This is usually in response to a factory reset, when we want
1856 * to undo the crypto mapping so the volume is formatted in the clear.
1857 */
1858int cryptfs_revert_volume(const char *label)
1859{
1860 return delete_crypto_blk_dev((char *)label);
1861}
1862
Ken Sumrall29d8da82011-05-18 17:20:07 -07001863/*
1864 * Called by vold when it's asked to mount an encrypted, nonremovable volume.
1865 * Setup a dm-crypt mapping, use the saved master key from
1866 * setting up the /data mapping, and return the new device path.
1867 */
1868int cryptfs_setup_volume(const char *label, int major, int minor,
1869 char *crypto_sys_path, unsigned int max_path,
1870 int *new_major, int *new_minor)
1871{
1872 char real_blkdev[MAXPATHLEN], crypto_blkdev[MAXPATHLEN];
1873 struct crypt_mnt_ftr sd_crypt_ftr;
Ken Sumrall29d8da82011-05-18 17:20:07 -07001874 struct stat statbuf;
1875 int nr_sec, fd;
1876
1877 sprintf(real_blkdev, "/dev/block/vold/%d:%d", major, minor);
1878
Ken Sumrall160b4d62013-04-22 12:15:39 -07001879 get_crypt_ftr_and_key(&sd_crypt_ftr);
Ken Sumrall29d8da82011-05-18 17:20:07 -07001880
1881 /* Update the fs_size field to be the size of the volume */
1882 fd = open(real_blkdev, O_RDONLY);
1883 nr_sec = get_blkdev_size(fd);
1884 close(fd);
1885 if (nr_sec == 0) {
1886 SLOGE("Cannot get size of volume %s\n", real_blkdev);
1887 return -1;
1888 }
1889
1890 sd_crypt_ftr.fs_size = nr_sec;
1891 create_crypto_blk_dev(&sd_crypt_ftr, saved_master_key, real_blkdev,
1892 crypto_blkdev, label);
1893
1894 stat(crypto_blkdev, &statbuf);
1895 *new_major = MAJOR(statbuf.st_rdev);
1896 *new_minor = MINOR(statbuf.st_rdev);
1897
1898 /* Create path to sys entry for this block device */
1899 snprintf(crypto_sys_path, max_path, "/devices/virtual/block/%s", strrchr(crypto_blkdev, '/')+1);
1900
1901 return 0;
1902}
1903
Ken Sumrall7f7dbaa2011-02-01 15:46:41 -08001904int cryptfs_crypto_complete(void)
1905{
1906 return do_crypto_complete("/data");
1907}
1908
Paul Lawrencef4faa572014-01-29 13:31:03 -08001909int check_unmounted_and_get_ftr(struct crypt_mnt_ftr* crypt_ftr)
1910{
1911 char encrypted_state[PROPERTY_VALUE_MAX];
1912 property_get("ro.crypto.state", encrypted_state, "");
1913 if ( master_key_saved || strcmp(encrypted_state, "encrypted") ) {
1914 SLOGE("encrypted fs already validated or not running with encryption,"
1915 " aborting");
1916 return -1;
1917 }
1918
1919 if (get_crypt_ftr_and_key(crypt_ftr)) {
1920 SLOGE("Error getting crypt footer and key");
1921 return -1;
1922 }
1923
1924 return 0;
1925}
1926
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001927int cryptfs_check_passwd(char *passwd)
1928{
Paul Lawrencef4faa572014-01-29 13:31:03 -08001929 struct crypt_mnt_ftr crypt_ftr;
1930 int rc;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001931
Paul Lawrencef4faa572014-01-29 13:31:03 -08001932 rc = check_unmounted_and_get_ftr(&crypt_ftr);
1933 if (rc)
1934 return rc;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001935
Paul Lawrencef4faa572014-01-29 13:31:03 -08001936 rc = test_mount_encrypted_fs(&crypt_ftr, passwd,
1937 DATA_MNT_POINT, "userdata");
Paul Lawrence684dbdf2014-02-07 12:07:22 -08001938
1939 if (rc == 0 && crypt_ftr.crypt_type != CRYPT_TYPE_DEFAULT) {
Paul Lawrence399317e2014-03-10 13:20:50 -07001940 cryptfs_clear_password();
1941 password = strdup(passwd);
1942 struct timespec now;
1943 clock_gettime(CLOCK_BOOTTIME, &now);
1944 password_expiry_time = now.tv_sec + password_max_age_seconds;
Paul Lawrence684dbdf2014-02-07 12:07:22 -08001945 }
1946
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001947 return rc;
1948}
1949
Ken Sumrall3ad90722011-10-04 20:38:29 -07001950int cryptfs_verify_passwd(char *passwd)
1951{
1952 struct crypt_mnt_ftr crypt_ftr;
1953 /* Allocate enough space for a 256 bit key, but we may use less */
Ken Sumrall160b4d62013-04-22 12:15:39 -07001954 unsigned char decrypted_master_key[32];
Ken Sumrall3ad90722011-10-04 20:38:29 -07001955 char encrypted_state[PROPERTY_VALUE_MAX];
1956 int rc;
1957
1958 property_get("ro.crypto.state", encrypted_state, "");
1959 if (strcmp(encrypted_state, "encrypted") ) {
1960 SLOGE("device not encrypted, aborting");
1961 return -2;
1962 }
1963
1964 if (!master_key_saved) {
1965 SLOGE("encrypted fs not yet mounted, aborting");
1966 return -1;
1967 }
1968
1969 if (!saved_mount_point) {
1970 SLOGE("encrypted fs failed to save mount point, aborting");
1971 return -1;
1972 }
1973
Ken Sumrall160b4d62013-04-22 12:15:39 -07001974 if (get_crypt_ftr_and_key(&crypt_ftr)) {
Ken Sumrall3ad90722011-10-04 20:38:29 -07001975 SLOGE("Error getting crypt footer and key\n");
1976 return -1;
1977 }
1978
1979 if (crypt_ftr.flags & CRYPT_MNT_KEY_UNENCRYPTED) {
1980 /* If the device has no password, then just say the password is valid */
1981 rc = 0;
1982 } else {
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001983 decrypt_master_key(passwd, decrypted_master_key, &crypt_ftr, 0, 0);
Ken Sumrall3ad90722011-10-04 20:38:29 -07001984 if (!memcmp(decrypted_master_key, saved_master_key, crypt_ftr.keysize)) {
1985 /* They match, the password is correct */
1986 rc = 0;
1987 } else {
1988 /* If incorrect, sleep for a bit to prevent dictionary attacks */
1989 sleep(1);
1990 rc = 1;
1991 }
1992 }
1993
1994 return rc;
1995}
1996
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001997/* Initialize a crypt_mnt_ftr structure. The keysize is
1998 * defaulted to 16 bytes, and the filesystem size to 0.
1999 * Presumably, at a minimum, the caller will update the
2000 * filesystem size and crypto_type_name after calling this function.
2001 */
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07002002static int cryptfs_init_crypt_mnt_ftr(struct crypt_mnt_ftr *ftr)
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002003{
Ken Sumrall160b4d62013-04-22 12:15:39 -07002004 off64_t off;
2005
2006 memset(ftr, 0, sizeof(struct crypt_mnt_ftr));
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002007 ftr->magic = CRYPT_MNT_MAGIC;
Kenny Rootc96a5f82013-06-14 12:08:28 -07002008 ftr->major_version = CURRENT_MAJOR_VERSION;
2009 ftr->minor_version = CURRENT_MINOR_VERSION;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002010 ftr->ftr_size = sizeof(struct crypt_mnt_ftr);
Jason parks70a4b3f2011-01-28 10:10:47 -06002011 ftr->keysize = KEY_LEN_BYTES;
Ken Sumrall160b4d62013-04-22 12:15:39 -07002012
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07002013 switch (keymaster_check_compatibility()) {
2014 case 1:
2015 ftr->kdf_type = KDF_SCRYPT_KEYMASTER;
2016 break;
2017
2018 case 0:
2019 ftr->kdf_type = KDF_SCRYPT;
2020 break;
2021
2022 default:
2023 SLOGE("keymaster_check_compatibility failed");
2024 return -1;
2025 }
2026
Kenny Rootc4c70f12013-06-14 12:11:38 -07002027 get_device_scrypt_params(ftr);
2028
Ken Sumrall160b4d62013-04-22 12:15:39 -07002029 ftr->persist_data_size = CRYPT_PERSIST_DATA_SIZE;
2030 if (get_crypt_ftr_info(NULL, &off) == 0) {
2031 ftr->persist_data_offset[0] = off + CRYPT_FOOTER_TO_PERSIST_OFFSET;
2032 ftr->persist_data_offset[1] = off + CRYPT_FOOTER_TO_PERSIST_OFFSET +
2033 ftr->persist_data_size;
2034 }
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07002035
2036 return 0;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002037}
2038
Ken Sumrall29d8da82011-05-18 17:20:07 -07002039static int cryptfs_enable_wipe(char *crypto_blkdev, off64_t size, int type)
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002040{
Ken Sumralle550f782013-08-20 13:48:23 -07002041 const char *args[10];
2042 char size_str[32]; /* Must be large enough to hold a %lld and null byte */
2043 int num_args;
2044 int status;
2045 int tmp;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002046 int rc = -1;
2047
Ken Sumrall29d8da82011-05-18 17:20:07 -07002048 if (type == EXT4_FS) {
Ken Sumralle550f782013-08-20 13:48:23 -07002049 args[0] = "/system/bin/make_ext4fs";
2050 args[1] = "-a";
2051 args[2] = "/data";
2052 args[3] = "-l";
Elliott Hughes73737162014-06-25 17:27:42 -07002053 snprintf(size_str, sizeof(size_str), "%" PRId64, size * 512);
Ken Sumralle550f782013-08-20 13:48:23 -07002054 args[4] = size_str;
2055 args[5] = crypto_blkdev;
2056 num_args = 6;
2057 SLOGI("Making empty filesystem with command %s %s %s %s %s %s\n",
2058 args[0], args[1], args[2], args[3], args[4], args[5]);
JP Abgrall62c7af32014-06-16 13:01:23 -07002059 } else if (type == F2FS_FS) {
2060 args[0] = "/system/bin/mkfs.f2fs";
2061 args[1] = "-t";
2062 args[2] = "-d1";
2063 args[3] = crypto_blkdev;
Elliott Hughes73737162014-06-25 17:27:42 -07002064 snprintf(size_str, sizeof(size_str), "%" PRId64, size);
JP Abgrall62c7af32014-06-16 13:01:23 -07002065 args[4] = size_str;
2066 num_args = 5;
2067 SLOGI("Making empty filesystem with command %s %s %s %s %s\n",
2068 args[0], args[1], args[2], args[3], args[4]);
Ken Sumrall29d8da82011-05-18 17:20:07 -07002069 } else {
2070 SLOGE("cryptfs_enable_wipe(): unknown filesystem type %d\n", type);
2071 return -1;
2072 }
2073
Ken Sumralle550f782013-08-20 13:48:23 -07002074 tmp = android_fork_execvp(num_args, (char **)args, &status, false, true);
2075
2076 if (tmp != 0) {
2077 SLOGE("Error creating empty filesystem on %s due to logwrap error\n", crypto_blkdev);
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002078 } else {
Ken Sumralle550f782013-08-20 13:48:23 -07002079 if (WIFEXITED(status)) {
2080 if (WEXITSTATUS(status)) {
2081 SLOGE("Error creating filesystem on %s, exit status %d ",
2082 crypto_blkdev, WEXITSTATUS(status));
2083 } else {
2084 SLOGD("Successfully created filesystem on %s\n", crypto_blkdev);
2085 rc = 0;
2086 }
2087 } else {
2088 SLOGE("Error creating filesystem on %s, did not exit normally\n", crypto_blkdev);
2089 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002090 }
2091
2092 return rc;
2093}
2094
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002095#define CRYPT_INPLACE_BUFSIZE 4096
Paul Lawrence87999172014-02-20 12:21:31 -08002096#define CRYPT_SECTORS_PER_BUFSIZE (CRYPT_INPLACE_BUFSIZE / CRYPT_SECTOR_SIZE)
2097#define CRYPT_SECTOR_SIZE 512
Paul Lawrenceae59fe62014-01-21 08:23:27 -08002098
2099/* aligned 32K writes tends to make flash happy.
2100 * SD card association recommends it.
2101 */
2102#define BLOCKS_AT_A_TIME 8
2103
2104struct encryptGroupsData
2105{
2106 int realfd;
2107 int cryptofd;
2108 off64_t numblocks;
2109 off64_t one_pct, cur_pct, new_pct;
2110 off64_t blocks_already_done, tot_numblocks;
Paul Lawrence58c58cf2014-06-04 13:12:21 -07002111 off64_t used_blocks_already_done, tot_used_blocks;
Paul Lawrenceae59fe62014-01-21 08:23:27 -08002112 char* real_blkdev, * crypto_blkdev;
2113 int count;
2114 off64_t offset;
2115 char* buffer;
Paul Lawrence87999172014-02-20 12:21:31 -08002116 off64_t last_written_sector;
2117 int completed;
Paul Lawrencea96d9c92014-06-04 14:05:01 -07002118 time_t time_started;
2119 int remaining_time;
Paul Lawrenceae59fe62014-01-21 08:23:27 -08002120};
2121
Paul Lawrence58c58cf2014-06-04 13:12:21 -07002122static void update_progress(struct encryptGroupsData* data, int is_used)
Paul Lawrenceae59fe62014-01-21 08:23:27 -08002123{
2124 data->blocks_already_done++;
Paul Lawrence58c58cf2014-06-04 13:12:21 -07002125
2126 if (is_used) {
2127 data->used_blocks_already_done++;
2128 }
Paul Lawrence58c58cf2014-06-04 13:12:21 -07002129 if (data->tot_used_blocks) {
2130 data->new_pct = data->used_blocks_already_done / data->one_pct;
2131 } else {
2132 data->new_pct = data->blocks_already_done / data->one_pct;
2133 }
2134
Paul Lawrenceae59fe62014-01-21 08:23:27 -08002135 if (data->new_pct > data->cur_pct) {
2136 char buf[8];
2137 data->cur_pct = data->new_pct;
Elliott Hughescb33f572014-06-25 18:25:11 -07002138 snprintf(buf, sizeof(buf), "%" PRId64, data->cur_pct);
Paul Lawrenceae59fe62014-01-21 08:23:27 -08002139 property_set("vold.encrypt_progress", buf);
2140 }
Paul Lawrencea96d9c92014-06-04 14:05:01 -07002141
2142 if (data->cur_pct >= 5) {
Paul Lawrence9c58a872014-09-30 09:12:51 -07002143 struct timespec time_now;
2144 if (clock_gettime(CLOCK_MONOTONIC, &time_now)) {
2145 SLOGW("Error getting time");
2146 } else {
2147 double elapsed_time = difftime(time_now.tv_sec, data->time_started);
2148 off64_t remaining_blocks = data->tot_used_blocks
2149 - data->used_blocks_already_done;
2150 int remaining_time = (int)(elapsed_time * remaining_blocks
2151 / data->used_blocks_already_done);
Paul Lawrence71577502014-08-13 14:55:55 -07002152
Paul Lawrence9c58a872014-09-30 09:12:51 -07002153 // Change time only if not yet set, lower, or a lot higher for
2154 // best user experience
2155 if (data->remaining_time == -1
2156 || remaining_time < data->remaining_time
2157 || remaining_time > data->remaining_time + 60) {
2158 char buf[8];
2159 snprintf(buf, sizeof(buf), "%d", remaining_time);
2160 property_set("vold.encrypt_time_remaining", buf);
2161 data->remaining_time = remaining_time;
2162 }
Paul Lawrencea96d9c92014-06-04 14:05:01 -07002163 }
2164 }
Paul Lawrenceae59fe62014-01-21 08:23:27 -08002165}
2166
Paul Lawrence3846be12014-09-22 11:33:54 -07002167static void log_progress(struct encryptGroupsData const* data, bool completed)
2168{
2169 // Precondition - if completed data = 0 else data != 0
2170
2171 // Track progress so we can skip logging blocks
2172 static off64_t offset = -1;
2173
2174 // Need to close existing 'Encrypting from' log?
2175 if (completed || (offset != -1 && data->offset != offset)) {
2176 SLOGI("Encrypted to sector %" PRId64,
2177 offset / info.block_size * CRYPT_SECTOR_SIZE);
2178 offset = -1;
2179 }
2180
2181 // Need to start new 'Encrypting from' log?
2182 if (!completed && offset != data->offset) {
2183 SLOGI("Encrypting from sector %" PRId64,
2184 data->offset / info.block_size * CRYPT_SECTOR_SIZE);
2185 }
2186
2187 // Update offset
2188 if (!completed) {
2189 offset = data->offset + (off64_t)data->count * info.block_size;
2190 }
2191}
2192
Paul Lawrenceae59fe62014-01-21 08:23:27 -08002193static int flush_outstanding_data(struct encryptGroupsData* data)
2194{
2195 if (data->count == 0) {
2196 return 0;
2197 }
2198
Elliott Hughes231bdba2014-06-25 18:36:19 -07002199 SLOGV("Copying %d blocks at offset %" PRIx64, data->count, data->offset);
Paul Lawrenceae59fe62014-01-21 08:23:27 -08002200
2201 if (pread64(data->realfd, data->buffer,
2202 info.block_size * data->count, data->offset)
2203 <= 0) {
2204 SLOGE("Error reading real_blkdev %s for inplace encrypt",
2205 data->real_blkdev);
2206 return -1;
2207 }
2208
2209 if (pwrite64(data->cryptofd, data->buffer,
2210 info.block_size * data->count, data->offset)
2211 <= 0) {
2212 SLOGE("Error writing crypto_blkdev %s for inplace encrypt",
2213 data->crypto_blkdev);
2214 return -1;
Paul Lawrence87999172014-02-20 12:21:31 -08002215 } else {
Paul Lawrence3846be12014-09-22 11:33:54 -07002216 log_progress(data, false);
Paul Lawrenceae59fe62014-01-21 08:23:27 -08002217 }
2218
2219 data->count = 0;
Paul Lawrence87999172014-02-20 12:21:31 -08002220 data->last_written_sector = (data->offset + data->count)
2221 / info.block_size * CRYPT_SECTOR_SIZE - 1;
Paul Lawrenceae59fe62014-01-21 08:23:27 -08002222 return 0;
2223}
2224
2225static int encrypt_groups(struct encryptGroupsData* data)
2226{
2227 unsigned int i;
2228 u8 *block_bitmap = 0;
2229 unsigned int block;
2230 off64_t ret;
2231 int rc = -1;
2232
2233 data->buffer = malloc(info.block_size * BLOCKS_AT_A_TIME);
2234 if (!data->buffer) {
2235 SLOGE("Failed to allocate crypto buffer");
2236 goto errout;
2237 }
2238
2239 block_bitmap = malloc(info.block_size);
2240 if (!block_bitmap) {
2241 SLOGE("failed to allocate block bitmap");
2242 goto errout;
2243 }
2244
2245 for (i = 0; i < aux_info.groups; ++i) {
2246 SLOGI("Encrypting group %d", i);
2247
2248 u32 first_block = aux_info.first_data_block + i * info.blocks_per_group;
2249 u32 block_count = min(info.blocks_per_group,
2250 aux_info.len_blocks - first_block);
2251
2252 off64_t offset = (u64)info.block_size
2253 * aux_info.bg_desc[i].bg_block_bitmap;
2254
2255 ret = pread64(data->realfd, block_bitmap, info.block_size, offset);
2256 if (ret != (int)info.block_size) {
2257 SLOGE("failed to read all of block group bitmap %d", i);
2258 goto errout;
2259 }
2260
2261 offset = (u64)info.block_size * first_block;
2262
2263 data->count = 0;
2264
2265 for (block = 0; block < block_count; block++) {
Paul Lawrence58c58cf2014-06-04 13:12:21 -07002266 int used = bitmap_get_bit(block_bitmap, block);
2267 update_progress(data, used);
2268 if (used) {
Paul Lawrenceae59fe62014-01-21 08:23:27 -08002269 if (data->count == 0) {
2270 data->offset = offset;
2271 }
2272 data->count++;
2273 } else {
2274 if (flush_outstanding_data(data)) {
2275 goto errout;
2276 }
2277 }
2278
2279 offset += info.block_size;
2280
2281 /* Write data if we are aligned or buffer size reached */
2282 if (offset % (info.block_size * BLOCKS_AT_A_TIME) == 0
2283 || data->count == BLOCKS_AT_A_TIME) {
2284 if (flush_outstanding_data(data)) {
2285 goto errout;
2286 }
2287 }
Paul Lawrence87999172014-02-20 12:21:31 -08002288
Paul Lawrence73d7a022014-06-09 14:10:09 -07002289 if (!is_battery_ok_to_continue()) {
Paul Lawrence87999172014-02-20 12:21:31 -08002290 SLOGE("Stopping encryption due to low battery");
2291 rc = 0;
2292 goto errout;
2293 }
2294
Paul Lawrenceae59fe62014-01-21 08:23:27 -08002295 }
2296 if (flush_outstanding_data(data)) {
2297 goto errout;
2298 }
2299 }
2300
Paul Lawrence87999172014-02-20 12:21:31 -08002301 data->completed = 1;
Paul Lawrenceae59fe62014-01-21 08:23:27 -08002302 rc = 0;
2303
2304errout:
Paul Lawrence3846be12014-09-22 11:33:54 -07002305 log_progress(0, true);
Paul Lawrenceae59fe62014-01-21 08:23:27 -08002306 free(data->buffer);
2307 free(block_bitmap);
2308 return rc;
2309}
2310
2311static int cryptfs_enable_inplace_ext4(char *crypto_blkdev,
2312 char *real_blkdev,
2313 off64_t size,
2314 off64_t *size_already_done,
Paul Lawrence87999172014-02-20 12:21:31 -08002315 off64_t tot_size,
2316 off64_t previously_encrypted_upto)
Paul Lawrenceae59fe62014-01-21 08:23:27 -08002317{
Paul Lawrence58c58cf2014-06-04 13:12:21 -07002318 u32 i;
Paul Lawrenceae59fe62014-01-21 08:23:27 -08002319 struct encryptGroupsData data;
Paul Lawrence74f29f12014-08-28 15:54:10 -07002320 int rc; // Can't initialize without causing warning -Wclobbered
Paul Lawrenceae59fe62014-01-21 08:23:27 -08002321
Paul Lawrence87999172014-02-20 12:21:31 -08002322 if (previously_encrypted_upto > *size_already_done) {
2323 SLOGD("Not fast encrypting since resuming part way through");
2324 return -1;
2325 }
2326
Paul Lawrenceae59fe62014-01-21 08:23:27 -08002327 memset(&data, 0, sizeof(data));
2328 data.real_blkdev = real_blkdev;
2329 data.crypto_blkdev = crypto_blkdev;
2330
2331 if ( (data.realfd = open(real_blkdev, O_RDWR)) < 0) {
2332 SLOGE("Error opening real_blkdev %s for inplace encrypt\n",
2333 real_blkdev);
Paul Lawrence74f29f12014-08-28 15:54:10 -07002334 rc = -1;
Paul Lawrenceae59fe62014-01-21 08:23:27 -08002335 goto errout;
2336 }
2337
2338 if ( (data.cryptofd = open(crypto_blkdev, O_WRONLY)) < 0) {
2339 SLOGE("Error opening crypto_blkdev %s for inplace encrypt\n",
2340 crypto_blkdev);
Paul Lawrence74f29f12014-08-28 15:54:10 -07002341 rc = -1;
Paul Lawrenceae59fe62014-01-21 08:23:27 -08002342 goto errout;
2343 }
2344
2345 if (setjmp(setjmp_env)) {
2346 SLOGE("Reading extent caused an exception");
Paul Lawrence74f29f12014-08-28 15:54:10 -07002347 rc = -1;
Paul Lawrenceae59fe62014-01-21 08:23:27 -08002348 goto errout;
2349 }
2350
2351 if (read_ext(data.realfd, 0) != 0) {
2352 SLOGE("Failed to read extent");
Paul Lawrence74f29f12014-08-28 15:54:10 -07002353 rc = -1;
Paul Lawrenceae59fe62014-01-21 08:23:27 -08002354 goto errout;
2355 }
2356
2357 data.numblocks = size / CRYPT_SECTORS_PER_BUFSIZE;
2358 data.tot_numblocks = tot_size / CRYPT_SECTORS_PER_BUFSIZE;
2359 data.blocks_already_done = *size_already_done / CRYPT_SECTORS_PER_BUFSIZE;
2360
2361 SLOGI("Encrypting filesystem in place...");
2362
Paul Lawrence58c58cf2014-06-04 13:12:21 -07002363 data.tot_used_blocks = data.numblocks;
2364 for (i = 0; i < aux_info.groups; ++i) {
2365 data.tot_used_blocks -= aux_info.bg_desc[i].bg_free_blocks_count;
2366 }
2367
2368 data.one_pct = data.tot_used_blocks / 100;
Paul Lawrenceae59fe62014-01-21 08:23:27 -08002369 data.cur_pct = 0;
Paul Lawrence9c58a872014-09-30 09:12:51 -07002370
2371 struct timespec time_started = {0};
2372 if (clock_gettime(CLOCK_MONOTONIC, &time_started)) {
2373 SLOGW("Error getting time at start");
2374 // Note - continue anyway - we'll run with 0
2375 }
2376 data.time_started = time_started.tv_sec;
Paul Lawrencea96d9c92014-06-04 14:05:01 -07002377 data.remaining_time = -1;
Paul Lawrenceae59fe62014-01-21 08:23:27 -08002378
2379 rc = encrypt_groups(&data);
2380 if (rc) {
2381 SLOGE("Error encrypting groups");
2382 goto errout;
2383 }
2384
Paul Lawrence87999172014-02-20 12:21:31 -08002385 *size_already_done += data.completed ? size : data.last_written_sector;
Paul Lawrenceae59fe62014-01-21 08:23:27 -08002386 rc = 0;
2387
2388errout:
2389 close(data.realfd);
2390 close(data.cryptofd);
2391
2392 return rc;
2393}
2394
Paul Lawrence3846be12014-09-22 11:33:54 -07002395static void log_progress_f2fs(u64 block, bool completed)
2396{
2397 // Precondition - if completed data = 0 else data != 0
2398
2399 // Track progress so we can skip logging blocks
2400 static u64 last_block = (u64)-1;
2401
2402 // Need to close existing 'Encrypting from' log?
2403 if (completed || (last_block != (u64)-1 && block != last_block + 1)) {
2404 SLOGI("Encrypted to block %" PRId64, last_block);
2405 last_block = -1;
2406 }
2407
2408 // Need to start new 'Encrypting from' log?
2409 if (!completed && (last_block == (u64)-1 || block != last_block + 1)) {
2410 SLOGI("Encrypting from block %" PRId64, block);
2411 }
2412
2413 // Update offset
2414 if (!completed) {
2415 last_block = block;
2416 }
2417}
2418
Daniel Rosenberge82df162014-08-15 22:19:23 +00002419static int encrypt_one_block_f2fs(u64 pos, void *data)
2420{
2421 struct encryptGroupsData *priv_dat = (struct encryptGroupsData *)data;
2422
2423 priv_dat->blocks_already_done = pos - 1;
2424 update_progress(priv_dat, 1);
2425
2426 off64_t offset = pos * CRYPT_INPLACE_BUFSIZE;
2427
2428 if (pread64(priv_dat->realfd, priv_dat->buffer, CRYPT_INPLACE_BUFSIZE, offset) <= 0) {
2429 SLOGE("Error reading real_blkdev %s for inplace encrypt", priv_dat->crypto_blkdev);
2430 return -1;
2431 }
2432
2433 if (pwrite64(priv_dat->cryptofd, priv_dat->buffer, CRYPT_INPLACE_BUFSIZE, offset) <= 0) {
2434 SLOGE("Error writing crypto_blkdev %s for inplace encrypt", priv_dat->crypto_blkdev);
2435 return -1;
2436 } else {
Paul Lawrence3846be12014-09-22 11:33:54 -07002437 log_progress_f2fs(pos, false);
Daniel Rosenberge82df162014-08-15 22:19:23 +00002438 }
2439
2440 return 0;
2441}
2442
2443static int cryptfs_enable_inplace_f2fs(char *crypto_blkdev,
2444 char *real_blkdev,
2445 off64_t size,
2446 off64_t *size_already_done,
2447 off64_t tot_size,
2448 off64_t previously_encrypted_upto)
2449{
2450 u32 i;
2451 struct encryptGroupsData data;
2452 struct f2fs_info *f2fs_info = NULL;
2453 int rc = -1;
2454 if (previously_encrypted_upto > *size_already_done) {
2455 SLOGD("Not fast encrypting since resuming part way through");
2456 return -1;
2457 }
2458 memset(&data, 0, sizeof(data));
2459 data.real_blkdev = real_blkdev;
2460 data.crypto_blkdev = crypto_blkdev;
2461 data.realfd = -1;
2462 data.cryptofd = -1;
2463 if ( (data.realfd = open64(real_blkdev, O_RDWR)) < 0) {
2464 SLOGE("Error opening real_blkdev %s for inplace encrypt\n",
2465 real_blkdev);
2466 goto errout;
2467 }
2468 if ( (data.cryptofd = open64(crypto_blkdev, O_WRONLY)) < 0) {
2469 SLOGE("Error opening crypto_blkdev %s for inplace encrypt\n",
2470 crypto_blkdev);
2471 goto errout;
2472 }
2473
2474 f2fs_info = generate_f2fs_info(data.realfd);
2475 if (!f2fs_info)
2476 goto errout;
2477
2478 data.numblocks = size / CRYPT_SECTORS_PER_BUFSIZE;
2479 data.tot_numblocks = tot_size / CRYPT_SECTORS_PER_BUFSIZE;
2480 data.blocks_already_done = *size_already_done / CRYPT_SECTORS_PER_BUFSIZE;
2481
2482 data.tot_used_blocks = get_num_blocks_used(f2fs_info);
2483
2484 data.one_pct = data.tot_used_blocks / 100;
2485 data.cur_pct = 0;
2486 data.time_started = time(NULL);
2487 data.remaining_time = -1;
2488
2489 data.buffer = malloc(f2fs_info->block_size);
2490 if (!data.buffer) {
2491 SLOGE("Failed to allocate crypto buffer");
2492 goto errout;
2493 }
2494
2495 data.count = 0;
2496
2497 /* Currently, this either runs to completion, or hits a nonrecoverable error */
2498 rc = run_on_used_blocks(data.blocks_already_done, f2fs_info, &encrypt_one_block_f2fs, &data);
2499
2500 if (rc) {
2501 SLOGE("Error in running over blocks");
2502 goto errout;
2503 }
2504
2505 *size_already_done += size;
2506 rc = 0;
2507
2508errout:
2509 if (rc)
2510 SLOGE("Failed to encrypt f2fs filesystem on %s", real_blkdev);
2511
Paul Lawrence3846be12014-09-22 11:33:54 -07002512 log_progress_f2fs(0, true);
Daniel Rosenberge82df162014-08-15 22:19:23 +00002513 free(f2fs_info);
2514 free(data.buffer);
2515 close(data.realfd);
2516 close(data.cryptofd);
2517
2518 return rc;
2519}
2520
Paul Lawrenceae59fe62014-01-21 08:23:27 -08002521static int cryptfs_enable_inplace_full(char *crypto_blkdev, char *real_blkdev,
2522 off64_t size, off64_t *size_already_done,
Paul Lawrence87999172014-02-20 12:21:31 -08002523 off64_t tot_size,
2524 off64_t previously_encrypted_upto)
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002525{
2526 int realfd, cryptofd;
2527 char *buf[CRYPT_INPLACE_BUFSIZE];
2528 int rc = -1;
2529 off64_t numblocks, i, remainder;
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002530 off64_t one_pct, cur_pct, new_pct;
Ken Sumrall29d8da82011-05-18 17:20:07 -07002531 off64_t blocks_already_done, tot_numblocks;
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002532
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002533 if ( (realfd = open(real_blkdev, O_RDONLY)) < 0) {
2534 SLOGE("Error opening real_blkdev %s for inplace encrypt\n", real_blkdev);
2535 return -1;
2536 }
2537
2538 if ( (cryptofd = open(crypto_blkdev, O_WRONLY)) < 0) {
2539 SLOGE("Error opening crypto_blkdev %s for inplace encrypt\n", crypto_blkdev);
2540 close(realfd);
2541 return -1;
2542 }
2543
2544 /* This is pretty much a simple loop of reading 4K, and writing 4K.
2545 * The size passed in is the number of 512 byte sectors in the filesystem.
2546 * So compute the number of whole 4K blocks we should read/write,
2547 * and the remainder.
2548 */
2549 numblocks = size / CRYPT_SECTORS_PER_BUFSIZE;
2550 remainder = size % CRYPT_SECTORS_PER_BUFSIZE;
Ken Sumrall29d8da82011-05-18 17:20:07 -07002551 tot_numblocks = tot_size / CRYPT_SECTORS_PER_BUFSIZE;
2552 blocks_already_done = *size_already_done / CRYPT_SECTORS_PER_BUFSIZE;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002553
2554 SLOGE("Encrypting filesystem in place...");
2555
Paul Lawrence87999172014-02-20 12:21:31 -08002556 i = previously_encrypted_upto + 1 - *size_already_done;
2557
2558 if (lseek64(realfd, i * CRYPT_SECTOR_SIZE, SEEK_SET) < 0) {
2559 SLOGE("Cannot seek to previously encrypted point on %s", real_blkdev);
2560 goto errout;
2561 }
2562
2563 if (lseek64(cryptofd, i * CRYPT_SECTOR_SIZE, SEEK_SET) < 0) {
2564 SLOGE("Cannot seek to previously encrypted point on %s", crypto_blkdev);
2565 goto errout;
2566 }
2567
2568 for (;i < size && i % CRYPT_SECTORS_PER_BUFSIZE != 0; ++i) {
2569 if (unix_read(realfd, buf, CRYPT_SECTOR_SIZE) <= 0) {
2570 SLOGE("Error reading initial sectors from real_blkdev %s for "
2571 "inplace encrypt\n", crypto_blkdev);
2572 goto errout;
2573 }
2574 if (unix_write(cryptofd, buf, CRYPT_SECTOR_SIZE) <= 0) {
2575 SLOGE("Error writing initial sectors to crypto_blkdev %s for "
2576 "inplace encrypt\n", crypto_blkdev);
2577 goto errout;
2578 } else {
Elliott Hughescb33f572014-06-25 18:25:11 -07002579 SLOGI("Encrypted 1 block at %" PRId64, i);
Paul Lawrence87999172014-02-20 12:21:31 -08002580 }
2581 }
2582
Ken Sumrall29d8da82011-05-18 17:20:07 -07002583 one_pct = tot_numblocks / 100;
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002584 cur_pct = 0;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002585 /* process the majority of the filesystem in blocks */
Paul Lawrence87999172014-02-20 12:21:31 -08002586 for (i/=CRYPT_SECTORS_PER_BUFSIZE; i<numblocks; i++) {
Ken Sumrall29d8da82011-05-18 17:20:07 -07002587 new_pct = (i + blocks_already_done) / one_pct;
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002588 if (new_pct > cur_pct) {
2589 char buf[8];
2590
2591 cur_pct = new_pct;
Elliott Hughes73737162014-06-25 17:27:42 -07002592 snprintf(buf, sizeof(buf), "%" PRId64, cur_pct);
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002593 property_set("vold.encrypt_progress", buf);
2594 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002595 if (unix_read(realfd, buf, CRYPT_INPLACE_BUFSIZE) <= 0) {
Paul Lawrence87999172014-02-20 12:21:31 -08002596 SLOGE("Error reading real_blkdev %s for inplace encrypt", crypto_blkdev);
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002597 goto errout;
2598 }
2599 if (unix_write(cryptofd, buf, CRYPT_INPLACE_BUFSIZE) <= 0) {
Paul Lawrence87999172014-02-20 12:21:31 -08002600 SLOGE("Error writing crypto_blkdev %s for inplace encrypt", crypto_blkdev);
2601 goto errout;
2602 } else {
Elliott Hughescb33f572014-06-25 18:25:11 -07002603 SLOGD("Encrypted %d block at %" PRId64,
Paul Lawrence87999172014-02-20 12:21:31 -08002604 CRYPT_SECTORS_PER_BUFSIZE,
2605 i * CRYPT_SECTORS_PER_BUFSIZE);
2606 }
2607
Paul Lawrence73d7a022014-06-09 14:10:09 -07002608 if (!is_battery_ok_to_continue()) {
Paul Lawrence87999172014-02-20 12:21:31 -08002609 SLOGE("Stopping encryption due to low battery");
2610 *size_already_done += (i + 1) * CRYPT_SECTORS_PER_BUFSIZE - 1;
2611 rc = 0;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002612 goto errout;
2613 }
2614 }
2615
2616 /* Do any remaining sectors */
2617 for (i=0; i<remainder; i++) {
Paul Lawrence87999172014-02-20 12:21:31 -08002618 if (unix_read(realfd, buf, CRYPT_SECTOR_SIZE) <= 0) {
2619 SLOGE("Error reading final sectors from real_blkdev %s for inplace encrypt", crypto_blkdev);
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002620 goto errout;
2621 }
Paul Lawrence87999172014-02-20 12:21:31 -08002622 if (unix_write(cryptofd, buf, CRYPT_SECTOR_SIZE) <= 0) {
2623 SLOGE("Error writing final sectors to crypto_blkdev %s for inplace encrypt", crypto_blkdev);
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002624 goto errout;
Paul Lawrence87999172014-02-20 12:21:31 -08002625 } else {
2626 SLOGI("Encrypted 1 block at next location");
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002627 }
2628 }
2629
Ken Sumrall29d8da82011-05-18 17:20:07 -07002630 *size_already_done += size;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002631 rc = 0;
2632
2633errout:
2634 close(realfd);
2635 close(cryptofd);
2636
2637 return rc;
2638}
2639
Paul Lawrenceae59fe62014-01-21 08:23:27 -08002640static int cryptfs_enable_inplace(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)
Paul Lawrenceae59fe62014-01-21 08:23:27 -08002644{
Paul Lawrence87999172014-02-20 12:21:31 -08002645 if (previously_encrypted_upto) {
Elliott Hughescb33f572014-06-25 18:25:11 -07002646 SLOGD("Continuing encryption from %" PRId64, previously_encrypted_upto);
Paul Lawrence87999172014-02-20 12:21:31 -08002647 }
2648
2649 if (*size_already_done + size < previously_encrypted_upto) {
2650 *size_already_done += size;
2651 return 0;
2652 }
2653
Daniel Rosenberge82df162014-08-15 22:19:23 +00002654 /* TODO: identify filesystem type.
2655 * As is, cryptfs_enable_inplace_ext4 will fail on an f2fs partition, and
2656 * then we will drop down to cryptfs_enable_inplace_f2fs.
2657 * */
Paul Lawrenceae59fe62014-01-21 08:23:27 -08002658 if (cryptfs_enable_inplace_ext4(crypto_blkdev, real_blkdev,
Daniel Rosenberge82df162014-08-15 22:19:23 +00002659 size, size_already_done,
2660 tot_size, previously_encrypted_upto) == 0) {
2661 return 0;
2662 }
2663
2664 if (cryptfs_enable_inplace_f2fs(crypto_blkdev, real_blkdev,
2665 size, size_already_done,
2666 tot_size, previously_encrypted_upto) == 0) {
2667 return 0;
Paul Lawrenceae59fe62014-01-21 08:23:27 -08002668 }
2669
2670 return cryptfs_enable_inplace_full(crypto_blkdev, real_blkdev,
Paul Lawrence87999172014-02-20 12:21:31 -08002671 size, size_already_done, tot_size,
2672 previously_encrypted_upto);
Paul Lawrenceae59fe62014-01-21 08:23:27 -08002673}
2674
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002675#define CRYPTO_ENABLE_WIPE 1
2676#define CRYPTO_ENABLE_INPLACE 2
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002677
2678#define FRAMEWORK_BOOT_WAIT 60
2679
Ken Sumrall29d8da82011-05-18 17:20:07 -07002680static inline int should_encrypt(struct volume_info *volume)
2681{
Paul Lawrenceae59fe62014-01-21 08:23:27 -08002682 return (volume->flags & (VOL_ENCRYPTABLE | VOL_NONREMOVABLE)) ==
Ken Sumrall29d8da82011-05-18 17:20:07 -07002683 (VOL_ENCRYPTABLE | VOL_NONREMOVABLE);
2684}
2685
Paul Lawrence87999172014-02-20 12:21:31 -08002686static int cryptfs_SHA256_fileblock(const char* filename, __le8* buf)
2687{
2688 int fd = open(filename, O_RDONLY);
2689 if (fd == -1) {
2690 SLOGE("Error opening file %s", filename);
2691 return -1;
2692 }
2693
2694 char block[CRYPT_INPLACE_BUFSIZE];
2695 memset(block, 0, sizeof(block));
2696 if (unix_read(fd, block, sizeof(block)) < 0) {
2697 SLOGE("Error reading file %s", filename);
2698 close(fd);
2699 return -1;
2700 }
2701
2702 close(fd);
2703
2704 SHA256_CTX c;
2705 SHA256_Init(&c);
2706 SHA256_Update(&c, block, sizeof(block));
2707 SHA256_Final(buf, &c);
2708
2709 return 0;
2710}
2711
JP Abgrall62c7af32014-06-16 13:01:23 -07002712static int get_fs_type(struct fstab_rec *rec)
2713{
2714 if (!strcmp(rec->fs_type, "ext4")) {
2715 return EXT4_FS;
2716 } else if (!strcmp(rec->fs_type, "f2fs")) {
2717 return F2FS_FS;
2718 } else {
2719 return -1;
2720 }
2721}
2722
Paul Lawrence87999172014-02-20 12:21:31 -08002723static int cryptfs_enable_all_volumes(struct crypt_mnt_ftr *crypt_ftr, int how,
2724 char *crypto_blkdev, char *real_blkdev,
2725 int previously_encrypted_upto)
2726{
2727 off64_t cur_encryption_done=0, tot_encryption_size=0;
2728 int i, rc = -1;
2729
Paul Lawrence73d7a022014-06-09 14:10:09 -07002730 if (!is_battery_ok_to_start()) {
2731 SLOGW("Not starting encryption due to low battery");
Paul Lawrence87999172014-02-20 12:21:31 -08002732 return 0;
2733 }
2734
2735 /* The size of the userdata partition, and add in the vold volumes below */
2736 tot_encryption_size = crypt_ftr->fs_size;
2737
2738 if (how == CRYPTO_ENABLE_WIPE) {
JP Abgrall62c7af32014-06-16 13:01:23 -07002739 struct fstab_rec* rec = fs_mgr_get_entry_for_mount_point(fstab, DATA_MNT_POINT);
2740 int fs_type = get_fs_type(rec);
2741 if (fs_type < 0) {
2742 SLOGE("cryptfs_enable: unsupported fs type %s\n", rec->fs_type);
2743 return -1;
2744 }
2745 rc = cryptfs_enable_wipe(crypto_blkdev, crypt_ftr->fs_size, fs_type);
Paul Lawrence87999172014-02-20 12:21:31 -08002746 } else if (how == CRYPTO_ENABLE_INPLACE) {
2747 rc = cryptfs_enable_inplace(crypto_blkdev, real_blkdev,
2748 crypt_ftr->fs_size, &cur_encryption_done,
2749 tot_encryption_size,
2750 previously_encrypted_upto);
2751
Paul Lawrence73d7a022014-06-09 14:10:09 -07002752 if (!rc) {
Paul Lawrence87999172014-02-20 12:21:31 -08002753 crypt_ftr->encrypted_upto = cur_encryption_done;
2754 }
2755
Paul Lawrence73d7a022014-06-09 14:10:09 -07002756 if (!rc && crypt_ftr->encrypted_upto == crypt_ftr->fs_size) {
Paul Lawrence87999172014-02-20 12:21:31 -08002757 /* The inplace routine never actually sets the progress to 100% due
2758 * to the round down nature of integer division, so set it here */
2759 property_set("vold.encrypt_progress", "100");
2760 }
2761 } else {
2762 /* Shouldn't happen */
2763 SLOGE("cryptfs_enable: internal error, unknown option\n");
2764 rc = -1;
2765 }
2766
2767 return rc;
2768}
2769
Paul Lawrence13486032014-02-03 13:28:11 -08002770int cryptfs_enable_internal(char *howarg, int crypt_type, char *passwd,
2771 int allow_reboot)
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002772{
2773 int how = 0;
Paul Lawrence87999172014-02-20 12:21:31 -08002774 char crypto_blkdev[MAXPATHLEN], real_blkdev[MAXPATHLEN];
Ken Sumralle5032c42012-04-01 23:58:44 -07002775 unsigned long nr_sec;
Ken Sumrall160b4d62013-04-22 12:15:39 -07002776 unsigned char decrypted_master_key[KEY_LEN_BYTES];
Ken Sumrall319b1042011-06-14 14:01:55 -07002777 int rc=-1, fd, i, ret;
Paul Lawrence87999172014-02-20 12:21:31 -08002778 struct crypt_mnt_ftr crypt_ftr;
Ken Sumrall160b4d62013-04-22 12:15:39 -07002779 struct crypt_persist_data *pdata;
Ken Sumrall29d8da82011-05-18 17:20:07 -07002780 char encrypted_state[PROPERTY_VALUE_MAX];
Ken Sumrall5d4c68e2011-01-30 19:06:03 -08002781 char lockid[32] = { 0 };
Ken Sumrall29d8da82011-05-18 17:20:07 -07002782 char key_loc[PROPERTY_VALUE_MAX];
2783 char fuse_sdcard[PROPERTY_VALUE_MAX];
2784 char *sd_mnt_point;
Ken Sumrall29d8da82011-05-18 17:20:07 -07002785 int num_vols;
2786 struct volume_info *vol_list = 0;
Paul Lawrence87999172014-02-20 12:21:31 -08002787 off64_t previously_encrypted_upto = 0;
Ken Sumrall29d8da82011-05-18 17:20:07 -07002788
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002789 if (!strcmp(howarg, "wipe")) {
2790 how = CRYPTO_ENABLE_WIPE;
2791 } else if (! strcmp(howarg, "inplace")) {
2792 how = CRYPTO_ENABLE_INPLACE;
2793 } else {
2794 /* Shouldn't happen, as CommandListener vets the args */
Ken Sumrall3ed82362011-01-28 23:31:16 -08002795 goto error_unencrypted;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002796 }
2797
Paul Lawrence87999172014-02-20 12:21:31 -08002798 /* See if an encryption was underway and interrupted */
2799 if (how == CRYPTO_ENABLE_INPLACE
2800 && get_crypt_ftr_and_key(&crypt_ftr) == 0
2801 && (crypt_ftr.flags & CRYPT_ENCRYPTION_IN_PROGRESS)) {
2802 previously_encrypted_upto = crypt_ftr.encrypted_upto;
2803 crypt_ftr.encrypted_upto = 0;
Paul Lawrence6bfed202014-07-28 12:47:22 -07002804 crypt_ftr.flags &= ~CRYPT_ENCRYPTION_IN_PROGRESS;
2805
2806 /* At this point, we are in an inconsistent state. Until we successfully
2807 complete encryption, a reboot will leave us broken. So mark the
2808 encryption failed in case that happens.
2809 On successfully completing encryption, remove this flag */
2810 crypt_ftr.flags |= CRYPT_INCONSISTENT_STATE;
2811
2812 put_crypt_ftr_and_key(&crypt_ftr);
Paul Lawrence87999172014-02-20 12:21:31 -08002813 }
2814
2815 property_get("ro.crypto.state", encrypted_state, "");
2816 if (!strcmp(encrypted_state, "encrypted") && !previously_encrypted_upto) {
2817 SLOGE("Device is already running encrypted, aborting");
2818 goto error_unencrypted;
2819 }
2820
2821 // TODO refactor fs_mgr_get_crypt_info to get both in one call
2822 fs_mgr_get_crypt_info(fstab, key_loc, 0, sizeof(key_loc));
Ken Sumrall56ad03c2013-02-13 13:00:19 -08002823 fs_mgr_get_crypt_info(fstab, 0, real_blkdev, sizeof(real_blkdev));
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002824
Ken Sumrall3ed82362011-01-28 23:31:16 -08002825 /* Get the size of the real block device */
2826 fd = open(real_blkdev, O_RDONLY);
2827 if ( (nr_sec = get_blkdev_size(fd)) == 0) {
2828 SLOGE("Cannot get size of block device %s\n", real_blkdev);
2829 goto error_unencrypted;
2830 }
2831 close(fd);
2832
2833 /* If doing inplace encryption, make sure the orig fs doesn't include the crypto footer */
Ken Sumrall29d8da82011-05-18 17:20:07 -07002834 if ((how == CRYPTO_ENABLE_INPLACE) && (!strcmp(key_loc, KEY_IN_FOOTER))) {
Ken Sumrall3ed82362011-01-28 23:31:16 -08002835 unsigned int fs_size_sec, max_fs_size_sec;
Jim Millera70abc62014-08-15 02:00:45 +00002836 fs_size_sec = get_fs_size(real_blkdev);
Daniel Rosenberge82df162014-08-15 22:19:23 +00002837 if (fs_size_sec == 0)
2838 fs_size_sec = get_f2fs_filesystem_size_sec(real_blkdev);
2839
Paul Lawrence87999172014-02-20 12:21:31 -08002840 max_fs_size_sec = nr_sec - (CRYPT_FOOTER_OFFSET / CRYPT_SECTOR_SIZE);
Ken Sumrall3ed82362011-01-28 23:31:16 -08002841
2842 if (fs_size_sec > max_fs_size_sec) {
2843 SLOGE("Orig filesystem overlaps crypto footer region. Cannot encrypt in place.");
2844 goto error_unencrypted;
2845 }
2846 }
2847
Ken Sumrall5d4c68e2011-01-30 19:06:03 -08002848 /* Get a wakelock as this may take a while, and we don't want the
2849 * device to sleep on us. We'll grab a partial wakelock, and if the UI
2850 * wants to keep the screen on, it can grab a full wakelock.
2851 */
Ken Sumrall29d8da82011-05-18 17:20:07 -07002852 snprintf(lockid, sizeof(lockid), "enablecrypto%d", (int) getpid());
Ken Sumrall5d4c68e2011-01-30 19:06:03 -08002853 acquire_wake_lock(PARTIAL_WAKE_LOCK, lockid);
2854
Jeff Sharkey7382f812012-08-23 14:08:59 -07002855 /* Get the sdcard mount point */
Jeff Sharkeyb77bc462012-10-01 14:36:26 -07002856 sd_mnt_point = getenv("EMULATED_STORAGE_SOURCE");
Jeff Sharkey7382f812012-08-23 14:08:59 -07002857 if (!sd_mnt_point) {
2858 sd_mnt_point = getenv("EXTERNAL_STORAGE");
2859 }
2860 if (!sd_mnt_point) {
2861 sd_mnt_point = "/mnt/sdcard";
2862 }
Ken Sumrall29d8da82011-05-18 17:20:07 -07002863
Paul Lawrence87999172014-02-20 12:21:31 -08002864 /* TODO
2865 * Currently do not have test devices with multiple encryptable volumes.
2866 * When we acquire some, re-add support.
2867 */
Ken Sumrall29d8da82011-05-18 17:20:07 -07002868 num_vols=vold_getNumDirectVolumes();
2869 vol_list = malloc(sizeof(struct volume_info) * num_vols);
2870 vold_getDirectVolumeList(vol_list);
2871
2872 for (i=0; i<num_vols; i++) {
2873 if (should_encrypt(&vol_list[i])) {
Paul Lawrence87999172014-02-20 12:21:31 -08002874 SLOGE("Cannot encrypt if there are multiple encryptable volumes"
2875 "%s\n", vol_list[i].label);
2876 goto error_unencrypted;
Ken Sumrall29d8da82011-05-18 17:20:07 -07002877 }
2878 }
2879
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002880 /* The init files are setup to stop the class main and late start when
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002881 * vold sets trigger_shutdown_framework.
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002882 */
2883 property_set("vold.decrypt", "trigger_shutdown_framework");
2884 SLOGD("Just asked init to shut down class main\n");
2885
Ken Sumrall425524d2012-06-14 20:55:28 -07002886 if (vold_unmountAllAsecs()) {
2887 /* Just report the error. If any are left mounted,
2888 * umounting /data below will fail and handle the error.
2889 */
2890 SLOGE("Error unmounting internal asecs");
2891 }
2892
Ken Sumrall29d8da82011-05-18 17:20:07 -07002893 property_get("ro.crypto.fuse_sdcard", fuse_sdcard, "");
2894 if (!strcmp(fuse_sdcard, "true")) {
2895 /* This is a device using the fuse layer to emulate the sdcard semantics
2896 * on top of the userdata partition. vold does not manage it, it is managed
2897 * by the sdcard service. The sdcard service was killed by the property trigger
2898 * above, so just unmount it now. We must do this _AFTER_ killing the framework,
2899 * unlike the case for vold managed devices above.
2900 */
Greg Hackmann6e8440f2014-10-02 17:18:20 -07002901 if (wait_and_unmount(sd_mnt_point, false)) {
Ken Sumrall29d8da82011-05-18 17:20:07 -07002902 goto error_shutting_down;
2903 }
Ken Sumrall2eaf7132011-01-14 12:45:48 -08002904 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002905
2906 /* Now unmount the /data partition. */
Greg Hackmann6e8440f2014-10-02 17:18:20 -07002907 if (wait_and_unmount(DATA_MNT_POINT, false)) {
JP Abgrall502dc742013-11-01 13:06:20 -07002908 if (allow_reboot) {
2909 goto error_shutting_down;
2910 } else {
2911 goto error_unencrypted;
2912 }
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002913 }
2914
2915 /* Do extra work for a better UX when doing the long inplace encryption */
2916 if (how == CRYPTO_ENABLE_INPLACE) {
2917 /* Now that /data is unmounted, we need to mount a tmpfs
2918 * /data, set a property saying we're doing inplace encryption,
2919 * and restart the framework.
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002920 */
Ken Sumralle5032c42012-04-01 23:58:44 -07002921 if (fs_mgr_do_tmpfs_mount(DATA_MNT_POINT)) {
Ken Sumrall3ed82362011-01-28 23:31:16 -08002922 goto error_shutting_down;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002923 }
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002924 /* Tells the framework that inplace encryption is starting */
Ken Sumrall7df84122011-01-18 14:04:08 -08002925 property_set("vold.encrypt_progress", "0");
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002926
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002927 /* restart the framework. */
2928 /* Create necessary paths on /data */
2929 if (prep_data_fs()) {
Ken Sumrall3ed82362011-01-28 23:31:16 -08002930 goto error_shutting_down;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002931 }
2932
Ken Sumrall92736ef2012-10-17 20:57:14 -07002933 /* Ugh, shutting down the framework is not synchronous, so until it
2934 * can be fixed, this horrible hack will wait a moment for it all to
2935 * shut down before proceeding. Without it, some devices cannot
2936 * restart the graphics services.
2937 */
2938 sleep(2);
2939
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002940 /* startup service classes main and late_start */
2941 property_set("vold.decrypt", "trigger_restart_min_framework");
2942 SLOGD("Just triggered restart_min_framework\n");
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002943
Ken Sumrall7df84122011-01-18 14:04:08 -08002944 /* OK, the framework is restarted and will soon be showing a
2945 * progress bar. Time to setup an encrypted mapping, and
2946 * either write a new filesystem, or encrypt in place updating
2947 * the progress bar as we work.
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002948 */
2949 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002950
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002951 /* Start the actual work of making an encrypted filesystem */
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002952 /* Initialize a crypt_mnt_ftr for the partition */
Paul Lawrence87999172014-02-20 12:21:31 -08002953 if (previously_encrypted_upto == 0) {
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07002954 if (cryptfs_init_crypt_mnt_ftr(&crypt_ftr)) {
2955 goto error_shutting_down;
2956 }
Ken Sumrall160b4d62013-04-22 12:15:39 -07002957
Paul Lawrence87999172014-02-20 12:21:31 -08002958 if (!strcmp(key_loc, KEY_IN_FOOTER)) {
2959 crypt_ftr.fs_size = nr_sec
2960 - (CRYPT_FOOTER_OFFSET / CRYPT_SECTOR_SIZE);
2961 } else {
2962 crypt_ftr.fs_size = nr_sec;
2963 }
Paul Lawrence6bfed202014-07-28 12:47:22 -07002964 /* At this point, we are in an inconsistent state. Until we successfully
2965 complete encryption, a reboot will leave us broken. So mark the
2966 encryption failed in case that happens.
2967 On successfully completing encryption, remove this flag */
2968 crypt_ftr.flags |= CRYPT_INCONSISTENT_STATE;
Paul Lawrence87999172014-02-20 12:21:31 -08002969 crypt_ftr.crypt_type = crypt_type;
2970 strcpy((char *)crypt_ftr.crypto_type_name, "aes-cbc-essiv:sha256");
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002971
Paul Lawrence87999172014-02-20 12:21:31 -08002972 /* Make an encrypted master key */
2973 if (create_encrypted_random_key(passwd, crypt_ftr.master_key, crypt_ftr.salt, &crypt_ftr)) {
2974 SLOGE("Cannot create encrypted master key\n");
2975 goto error_shutting_down;
2976 }
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002977
Paul Lawrence87999172014-02-20 12:21:31 -08002978 /* Write the key to the end of the partition */
2979 put_crypt_ftr_and_key(&crypt_ftr);
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002980
Paul Lawrence87999172014-02-20 12:21:31 -08002981 /* If any persistent data has been remembered, save it.
2982 * If none, create a valid empty table and save that.
2983 */
2984 if (!persist_data) {
2985 pdata = malloc(CRYPT_PERSIST_DATA_SIZE);
2986 if (pdata) {
2987 init_empty_persist_data(pdata, CRYPT_PERSIST_DATA_SIZE);
2988 persist_data = pdata;
2989 }
2990 }
2991 if (persist_data) {
2992 save_persistent_data();
2993 }
Ken Sumrall160b4d62013-04-22 12:15:39 -07002994 }
2995
Paul Lawrenced0c7b172014-08-08 14:28:10 -07002996 decrypt_master_key(passwd, decrypted_master_key, &crypt_ftr, 0, 0);
Ken Sumrall29d8da82011-05-18 17:20:07 -07002997 create_crypto_blk_dev(&crypt_ftr, decrypted_master_key, real_blkdev, crypto_blkdev,
2998 "userdata");
2999
Paul Lawrence87999172014-02-20 12:21:31 -08003000 /* If we are continuing, check checksums match */
3001 rc = 0;
3002 if (previously_encrypted_upto) {
3003 __le8 hash_first_block[SHA256_DIGEST_LENGTH];
3004 rc = cryptfs_SHA256_fileblock(crypto_blkdev, hash_first_block);
Ken Sumrall128626f2011-06-28 18:45:14 -07003005
Paul Lawrence87999172014-02-20 12:21:31 -08003006 if (!rc && memcmp(hash_first_block, crypt_ftr.hash_first_block,
3007 sizeof(hash_first_block)) != 0) {
3008 SLOGE("Checksums do not match - trigger wipe");
3009 rc = -1;
Ken Sumrall29d8da82011-05-18 17:20:07 -07003010 }
3011 }
Ken Sumrall8ddbe402011-01-17 15:26:29 -08003012
Paul Lawrence87999172014-02-20 12:21:31 -08003013 if (!rc) {
3014 rc = cryptfs_enable_all_volumes(&crypt_ftr, how,
3015 crypto_blkdev, real_blkdev,
3016 previously_encrypted_upto);
3017 }
3018
3019 /* Calculate checksum if we are not finished */
Paul Lawrence73d7a022014-06-09 14:10:09 -07003020 if (!rc && crypt_ftr.encrypted_upto != crypt_ftr.fs_size) {
Paul Lawrence87999172014-02-20 12:21:31 -08003021 rc = cryptfs_SHA256_fileblock(crypto_blkdev,
3022 crypt_ftr.hash_first_block);
Paul Lawrence73d7a022014-06-09 14:10:09 -07003023 if (rc) {
Paul Lawrence87999172014-02-20 12:21:31 -08003024 SLOGE("Error calculating checksum for continuing encryption");
3025 rc = -1;
Ken Sumrall29d8da82011-05-18 17:20:07 -07003026 }
Ken Sumrall8ddbe402011-01-17 15:26:29 -08003027 }
3028
3029 /* Undo the dm-crypt mapping whether we succeed or not */
Ken Sumrall29d8da82011-05-18 17:20:07 -07003030 delete_crypto_blk_dev("userdata");
Ken Sumrall29d8da82011-05-18 17:20:07 -07003031
3032 free(vol_list);
Ken Sumrall8ddbe402011-01-17 15:26:29 -08003033
3034 if (! rc) {
3035 /* Success */
Paul Lawrence6bfed202014-07-28 12:47:22 -07003036 crypt_ftr.flags &= ~CRYPT_INCONSISTENT_STATE;
Ken Sumrall7f7dbaa2011-02-01 15:46:41 -08003037
Paul Lawrence6bfed202014-07-28 12:47:22 -07003038 if (crypt_ftr.encrypted_upto != crypt_ftr.fs_size) {
Paul Lawrence87999172014-02-20 12:21:31 -08003039 SLOGD("Encrypted up to sector %lld - will continue after reboot",
3040 crypt_ftr.encrypted_upto);
Paul Lawrence6bfed202014-07-28 12:47:22 -07003041 crypt_ftr.flags |= CRYPT_ENCRYPTION_IN_PROGRESS;
Paul Lawrence87999172014-02-20 12:21:31 -08003042 }
Paul Lawrence73d7a022014-06-09 14:10:09 -07003043
Paul Lawrence6bfed202014-07-28 12:47:22 -07003044 put_crypt_ftr_and_key(&crypt_ftr);
Ken Sumralld33d4172011-02-01 00:49:13 -08003045
Paul Lawrence73d7a022014-06-09 14:10:09 -07003046 if (crypt_ftr.encrypted_upto == crypt_ftr.fs_size) {
Paul Lawrenceb6672e12014-08-15 07:37:28 -07003047 char value[PROPERTY_VALUE_MAX];
3048 property_get("ro.crypto.state", value, "");
3049 if (!strcmp(value, "")) {
3050 /* default encryption - continue first boot sequence */
3051 property_set("ro.crypto.state", "encrypted");
3052 release_wake_lock(lockid);
3053 cryptfs_check_passwd(DEFAULT_PASSWORD);
3054 cryptfs_restart_internal(1);
3055 return 0;
3056 } else {
3057 sleep(2); /* Give the UI a chance to show 100% progress */
Paul Lawrence87999172014-02-20 12:21:31 -08003058 cryptfs_reboot(reboot);
Paul Lawrenceb6672e12014-08-15 07:37:28 -07003059 }
Paul Lawrence87999172014-02-20 12:21:31 -08003060 } else {
Paul Lawrenceb6672e12014-08-15 07:37:28 -07003061 sleep(2); /* Partially encrypted, ensure writes flushed to ssd */
Paul Lawrence87999172014-02-20 12:21:31 -08003062 cryptfs_reboot(shutdown);
3063 }
Ken Sumrall3ed82362011-01-28 23:31:16 -08003064 } else {
Mike Lockwoodee6d8c42012-02-15 13:43:28 -08003065 char value[PROPERTY_VALUE_MAX];
3066
Ken Sumrall319369a2012-06-27 16:30:18 -07003067 property_get("ro.vold.wipe_on_crypt_fail", value, "0");
Mike Lockwoodee6d8c42012-02-15 13:43:28 -08003068 if (!strcmp(value, "1")) {
3069 /* wipe data if encryption failed */
3070 SLOGE("encryption failed - rebooting into recovery to wipe data\n");
3071 mkdir("/cache/recovery", 0700);
Nick Kralevich4684e582012-06-26 15:07:03 -07003072 int fd = open("/cache/recovery/command", O_RDWR|O_CREAT|O_TRUNC, 0600);
Mike Lockwoodee6d8c42012-02-15 13:43:28 -08003073 if (fd >= 0) {
Jeff Sharkeydd1a8042014-09-24 11:46:51 -07003074 write(fd, "--wipe_data\n", strlen("--wipe_data\n") + 1);
3075 write(fd, "--reason=cryptfs_enable_internal\n", strlen("--reason=cryptfs_enable_internal\n") + 1);
Mike Lockwoodee6d8c42012-02-15 13:43:28 -08003076 close(fd);
3077 } else {
3078 SLOGE("could not open /cache/recovery/command\n");
3079 }
Paul Lawrence87999172014-02-20 12:21:31 -08003080 cryptfs_reboot(recovery);
Mike Lockwoodee6d8c42012-02-15 13:43:28 -08003081 } else {
3082 /* set property to trigger dialog */
3083 property_set("vold.encrypt_progress", "error_partially_encrypted");
3084 release_wake_lock(lockid);
3085 }
Ken Sumrall3ed82362011-01-28 23:31:16 -08003086 return -1;
Ken Sumrall8ddbe402011-01-17 15:26:29 -08003087 }
3088
Ken Sumrall3ed82362011-01-28 23:31:16 -08003089 /* hrm, the encrypt step claims success, but the reboot failed.
3090 * This should not happen.
3091 * Set the property and return. Hope the framework can deal with it.
3092 */
3093 property_set("vold.encrypt_progress", "error_reboot_failed");
Ken Sumrall5d4c68e2011-01-30 19:06:03 -08003094 release_wake_lock(lockid);
Ken Sumrall8ddbe402011-01-17 15:26:29 -08003095 return rc;
Ken Sumrall3ed82362011-01-28 23:31:16 -08003096
3097error_unencrypted:
Ken Sumrall29d8da82011-05-18 17:20:07 -07003098 free(vol_list);
Ken Sumrall3ed82362011-01-28 23:31:16 -08003099 property_set("vold.encrypt_progress", "error_not_encrypted");
Ken Sumrall5d4c68e2011-01-30 19:06:03 -08003100 if (lockid[0]) {
3101 release_wake_lock(lockid);
3102 }
Ken Sumrall3ed82362011-01-28 23:31:16 -08003103 return -1;
3104
3105error_shutting_down:
3106 /* we failed, and have not encrypted anthing, so the users's data is still intact,
3107 * but the framework is stopped and not restarted to show the error, so it's up to
3108 * vold to restart the system.
3109 */
3110 SLOGE("Error enabling encryption after framework is shutdown, no data changed, restarting system");
Paul Lawrence87999172014-02-20 12:21:31 -08003111 cryptfs_reboot(reboot);
Ken Sumrall3ed82362011-01-28 23:31:16 -08003112
3113 /* shouldn't get here */
3114 property_set("vold.encrypt_progress", "error_shutting_down");
Ken Sumrall29d8da82011-05-18 17:20:07 -07003115 free(vol_list);
Ken Sumrall5d4c68e2011-01-30 19:06:03 -08003116 if (lockid[0]) {
3117 release_wake_lock(lockid);
3118 }
Ken Sumrall3ed82362011-01-28 23:31:16 -08003119 return -1;
Ken Sumrall8ddbe402011-01-17 15:26:29 -08003120}
3121
Paul Lawrence45f10532014-04-04 18:11:56 +00003122int cryptfs_enable(char *howarg, int type, char *passwd, int allow_reboot)
Paul Lawrence13486032014-02-03 13:28:11 -08003123{
Paul Lawrence45f10532014-04-04 18:11:56 +00003124 return cryptfs_enable_internal(howarg, type, passwd, allow_reboot);
Paul Lawrence13486032014-02-03 13:28:11 -08003125}
3126
3127int cryptfs_enable_default(char *howarg, int allow_reboot)
3128{
3129 return cryptfs_enable_internal(howarg, CRYPT_TYPE_DEFAULT,
3130 DEFAULT_PASSWORD, allow_reboot);
3131}
3132
3133int cryptfs_changepw(int crypt_type, const char *newpw)
Ken Sumrall8ddbe402011-01-17 15:26:29 -08003134{
3135 struct crypt_mnt_ftr crypt_ftr;
Ken Sumrall160b4d62013-04-22 12:15:39 -07003136 unsigned char decrypted_master_key[KEY_LEN_BYTES];
Ken Sumrall8ddbe402011-01-17 15:26:29 -08003137
3138 /* This is only allowed after we've successfully decrypted the master key */
Paul Lawrencef4faa572014-01-29 13:31:03 -08003139 if (!master_key_saved) {
Ken Sumrall0cc16632011-01-18 20:32:26 -08003140 SLOGE("Key not saved, aborting");
Ken Sumrall8ddbe402011-01-17 15:26:29 -08003141 return -1;
3142 }
3143
Paul Lawrencef4faa572014-01-29 13:31:03 -08003144 if (crypt_type < 0 || crypt_type > CRYPT_TYPE_MAX_TYPE) {
3145 SLOGE("Invalid crypt_type %d", crypt_type);
3146 return -1;
3147 }
3148
Ken Sumrall8ddbe402011-01-17 15:26:29 -08003149 /* get key */
Ken Sumrall160b4d62013-04-22 12:15:39 -07003150 if (get_crypt_ftr_and_key(&crypt_ftr)) {
Paul Lawrencef4faa572014-01-29 13:31:03 -08003151 SLOGE("Error getting crypt footer and key");
3152 return -1;
Ken Sumrall8ddbe402011-01-17 15:26:29 -08003153 }
3154
Paul Lawrencef4faa572014-01-29 13:31:03 -08003155 crypt_ftr.crypt_type = crypt_type;
3156
3157 encrypt_master_key(crypt_type == CRYPT_TYPE_DEFAULT ? DEFAULT_PASSWORD
3158 : newpw,
3159 crypt_ftr.salt,
3160 saved_master_key,
3161 crypt_ftr.master_key,
3162 &crypt_ftr);
Ken Sumrall8ddbe402011-01-17 15:26:29 -08003163
Jason parks70a4b3f2011-01-28 10:10:47 -06003164 /* save the key */
Ken Sumrall160b4d62013-04-22 12:15:39 -07003165 put_crypt_ftr_and_key(&crypt_ftr);
Ken Sumrall8f869aa2010-12-03 03:47:09 -08003166
3167 return 0;
3168}
Ken Sumrall160b4d62013-04-22 12:15:39 -07003169
3170static int persist_get_key(char *fieldname, char *value)
3171{
3172 unsigned int i;
3173
3174 if (persist_data == NULL) {
3175 return -1;
3176 }
3177 for (i = 0; i < persist_data->persist_valid_entries; i++) {
3178 if (!strncmp(persist_data->persist_entry[i].key, fieldname, PROPERTY_KEY_MAX)) {
3179 /* We found it! */
3180 strlcpy(value, persist_data->persist_entry[i].val, PROPERTY_VALUE_MAX);
3181 return 0;
3182 }
3183 }
3184
3185 return -1;
3186}
3187
3188static int persist_set_key(char *fieldname, char *value, int encrypted)
3189{
3190 unsigned int i;
3191 unsigned int num;
3192 struct crypt_mnt_ftr crypt_ftr;
3193 unsigned int max_persistent_entries;
3194 unsigned int dsize;
3195
3196 if (persist_data == NULL) {
3197 return -1;
3198 }
3199
3200 /* If encrypted, use the values from the crypt_ftr, otherwise
3201 * use the values for the current spec.
3202 */
3203 if (encrypted) {
3204 if(get_crypt_ftr_and_key(&crypt_ftr)) {
3205 return -1;
3206 }
3207 dsize = crypt_ftr.persist_data_size;
3208 } else {
3209 dsize = CRYPT_PERSIST_DATA_SIZE;
3210 }
3211 max_persistent_entries = (dsize - sizeof(struct crypt_persist_data)) /
3212 sizeof(struct crypt_persist_entry);
3213
3214 num = persist_data->persist_valid_entries;
3215
3216 for (i = 0; i < num; i++) {
3217 if (!strncmp(persist_data->persist_entry[i].key, fieldname, PROPERTY_KEY_MAX)) {
3218 /* We found an existing entry, update it! */
3219 memset(persist_data->persist_entry[i].val, 0, PROPERTY_VALUE_MAX);
3220 strlcpy(persist_data->persist_entry[i].val, value, PROPERTY_VALUE_MAX);
3221 return 0;
3222 }
3223 }
3224
3225 /* We didn't find it, add it to the end, if there is room */
3226 if (persist_data->persist_valid_entries < max_persistent_entries) {
3227 memset(&persist_data->persist_entry[num], 0, sizeof(struct crypt_persist_entry));
3228 strlcpy(persist_data->persist_entry[num].key, fieldname, PROPERTY_KEY_MAX);
3229 strlcpy(persist_data->persist_entry[num].val, value, PROPERTY_VALUE_MAX);
3230 persist_data->persist_valid_entries++;
3231 return 0;
3232 }
3233
3234 return -1;
3235}
3236
3237/* Return the value of the specified field. */
3238int cryptfs_getfield(char *fieldname, char *value, int len)
3239{
3240 char temp_value[PROPERTY_VALUE_MAX];
3241 char real_blkdev[MAXPATHLEN];
3242 /* 0 is success, 1 is not encrypted,
3243 * -1 is value not set, -2 is any other error
3244 */
3245 int rc = -2;
3246
3247 if (persist_data == NULL) {
3248 load_persistent_data();
3249 if (persist_data == NULL) {
3250 SLOGE("Getfield error, cannot load persistent data");
3251 goto out;
3252 }
3253 }
3254
3255 if (!persist_get_key(fieldname, temp_value)) {
3256 /* We found it, copy it to the caller's buffer and return */
3257 strlcpy(value, temp_value, len);
3258 rc = 0;
3259 } else {
3260 /* Sadness, it's not there. Return the error */
3261 rc = -1;
3262 }
3263
3264out:
3265 return rc;
3266}
3267
3268/* Set the value of the specified field. */
3269int cryptfs_setfield(char *fieldname, char *value)
3270{
3271 struct crypt_persist_data stored_pdata;
3272 struct crypt_persist_data *pdata_p;
3273 struct crypt_mnt_ftr crypt_ftr;
3274 char encrypted_state[PROPERTY_VALUE_MAX];
3275 /* 0 is success, -1 is an error */
3276 int rc = -1;
3277 int encrypted = 0;
3278
3279 if (persist_data == NULL) {
3280 load_persistent_data();
3281 if (persist_data == NULL) {
3282 SLOGE("Setfield error, cannot load persistent data");
3283 goto out;
3284 }
3285 }
3286
3287 property_get("ro.crypto.state", encrypted_state, "");
3288 if (!strcmp(encrypted_state, "encrypted") ) {
3289 encrypted = 1;
3290 }
3291
3292 if (persist_set_key(fieldname, value, encrypted)) {
3293 goto out;
3294 }
3295
3296 /* If we are running encrypted, save the persistent data now */
3297 if (encrypted) {
3298 if (save_persistent_data()) {
3299 SLOGE("Setfield error, cannot save persistent data");
3300 goto out;
3301 }
3302 }
3303
3304 rc = 0;
3305
3306out:
3307 return rc;
3308}
Paul Lawrencef4faa572014-01-29 13:31:03 -08003309
3310/* Checks userdata. Attempt to mount the volume if default-
3311 * encrypted.
3312 * On success trigger next init phase and return 0.
3313 * Currently do not handle failure - see TODO below.
3314 */
3315int cryptfs_mount_default_encrypted(void)
3316{
3317 char decrypt_state[PROPERTY_VALUE_MAX];
3318 property_get("vold.decrypt", decrypt_state, "0");
3319 if (!strcmp(decrypt_state, "0")) {
3320 SLOGE("Not encrypted - should not call here");
3321 } else {
3322 int crypt_type = cryptfs_get_password_type();
3323 if (crypt_type < 0 || crypt_type > CRYPT_TYPE_MAX_TYPE) {
3324 SLOGE("Bad crypt type - error");
3325 } else if (crypt_type != CRYPT_TYPE_DEFAULT) {
3326 SLOGD("Password is not default - "
3327 "starting min framework to prompt");
3328 property_set("vold.decrypt", "trigger_restart_min_framework");
3329 return 0;
3330 } else if (cryptfs_check_passwd(DEFAULT_PASSWORD) == 0) {
3331 SLOGD("Password is default - restarting filesystem");
3332 cryptfs_restart_internal(0);
3333 return 0;
3334 } else {
3335 SLOGE("Encrypted, default crypt type but can't decrypt");
3336 }
3337 }
3338
Paul Lawrence6bfed202014-07-28 12:47:22 -07003339 /** Corrupt. Allow us to boot into framework, which will detect bad
3340 crypto when it calls do_crypto_complete, then do a factory reset
Paul Lawrencef4faa572014-01-29 13:31:03 -08003341 */
Paul Lawrence6bfed202014-07-28 12:47:22 -07003342 property_set("vold.decrypt", "trigger_restart_min_framework");
Paul Lawrencef4faa572014-01-29 13:31:03 -08003343 return 0;
3344}
3345
3346/* Returns type of the password, default, pattern, pin or password.
3347 */
3348int cryptfs_get_password_type(void)
3349{
3350 struct crypt_mnt_ftr crypt_ftr;
3351
3352 if (get_crypt_ftr_and_key(&crypt_ftr)) {
3353 SLOGE("Error getting crypt footer and key\n");
3354 return -1;
3355 }
3356
Paul Lawrence6bfed202014-07-28 12:47:22 -07003357 if (crypt_ftr.flags & CRYPT_INCONSISTENT_STATE) {
3358 return -1;
3359 }
3360
Paul Lawrencef4faa572014-01-29 13:31:03 -08003361 return crypt_ftr.crypt_type;
3362}
Paul Lawrence684dbdf2014-02-07 12:07:22 -08003363
Paul Lawrence399317e2014-03-10 13:20:50 -07003364char* cryptfs_get_password()
Paul Lawrence684dbdf2014-02-07 12:07:22 -08003365{
Paul Lawrence399317e2014-03-10 13:20:50 -07003366 struct timespec now;
3367 clock_gettime(CLOCK_MONOTONIC, &now);
3368 if (now.tv_sec < password_expiry_time) {
3369 return password;
3370 } else {
3371 cryptfs_clear_password();
3372 return 0;
3373 }
3374}
3375
3376void cryptfs_clear_password()
3377{
3378 if (password) {
3379 size_t len = strlen(password);
3380 memset(password, 0, len);
3381 free(password);
3382 password = 0;
3383 password_expiry_time = 0;
3384 }
Paul Lawrence684dbdf2014-02-07 12:07:22 -08003385}