blob: 01dfec3115e3335e9839e71e1a348e3631fa0ff2 [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>
Ken Sumrall8f869aa2010-12-03 03:47:09 -080043#include "cryptfs.h"
44#define LOG_TAG "Cryptfs"
45#include "cutils/log.h"
46#include "cutils/properties.h"
Ken Sumralladfba362013-06-04 16:37:52 -070047#include "cutils/android_reboot.h"
Ken Sumrall5d4c68e2011-01-30 19:06:03 -080048#include "hardware_legacy/power.h"
Ken Sumralle550f782013-08-20 13:48:23 -070049#include <logwrap/logwrap.h>
Ken Sumrall29d8da82011-05-18 17:20:07 -070050#include "VolumeManager.h"
Ken Sumrall9caab762013-06-11 19:10:20 -070051#include "VoldUtil.h"
Kenny Rootc4c70f12013-06-14 12:11:38 -070052#include "crypto_scrypt.h"
Paul Lawrenceae59fe62014-01-21 08:23:27 -080053#include "ext4_utils.h"
Daniel Rosenberge82df162014-08-15 22:19:23 +000054#include "f2fs_sparseblock.h"
Paul Lawrence87999172014-02-20 12:21:31 -080055#include "CheckBattery.h"
jessica_yu3f14fe42014-09-22 15:57:40 +080056#include "Process.h"
Ken Sumrall8f869aa2010-12-03 03:47:09 -080057
Paul Lawrence69f4ebd2014-04-14 12:17:14 -070058#include <hardware/keymaster.h>
59
Mark Salyzyn3e971272014-01-21 13:27:04 -080060#define UNUSED __attribute__((unused))
61
Mark Salyzyn5eecc442014-02-12 14:16:14 -080062#define UNUSED __attribute__((unused))
63
Ken Sumrall8f869aa2010-12-03 03:47:09 -080064#define DM_CRYPT_BUF_SIZE 4096
65
Jason parks70a4b3f2011-01-28 10:10:47 -060066#define HASH_COUNT 2000
67#define KEY_LEN_BYTES 16
68#define IV_LEN_BYTES 16
69
Ken Sumrall29d8da82011-05-18 17:20:07 -070070#define KEY_IN_FOOTER "footer"
71
Paul Lawrencef4faa572014-01-29 13:31:03 -080072// "default_password" encoded into hex (d=0x64 etc)
73#define DEFAULT_PASSWORD "64656661756c745f70617373776f7264"
74
Ken Sumrall29d8da82011-05-18 17:20:07 -070075#define EXT4_FS 1
JP Abgrall62c7af32014-06-16 13:01:23 -070076#define F2FS_FS 2
Ken Sumrall29d8da82011-05-18 17:20:07 -070077
Ken Sumralle919efe2012-09-29 17:07:41 -070078#define TABLE_LOAD_RETRIES 10
79
Shawn Willden47ba10d2014-09-03 17:07:06 -060080#define RSA_KEY_SIZE 2048
81#define RSA_KEY_SIZE_BYTES (RSA_KEY_SIZE / 8)
82#define RSA_EXPONENT 0x10001
Paul Lawrence69f4ebd2014-04-14 12:17:14 -070083
Paul Lawrence8e3f4512014-09-08 10:11:17 -070084#define RETRY_MOUNT_ATTEMPTS 10
85#define RETRY_MOUNT_DELAY_SECONDS 1
86
Ken Sumrall8f869aa2010-12-03 03:47:09 -080087char *me = "cryptfs";
88
Jason parks70a4b3f2011-01-28 10:10:47 -060089static unsigned char saved_master_key[KEY_LEN_BYTES];
Ken Sumrall3ad90722011-10-04 20:38:29 -070090static char *saved_mount_point;
Jason parks70a4b3f2011-01-28 10:10:47 -060091static int master_key_saved = 0;
Ken Sumrall160b4d62013-04-22 12:15:39 -070092static struct crypt_persist_data *persist_data = NULL;
Ken Sumrall56ad03c2013-02-13 13:00:19 -080093
Paul Lawrence69f4ebd2014-04-14 12:17:14 -070094static int keymaster_init(keymaster_device_t **keymaster_dev)
95{
96 int rc;
97
98 const hw_module_t* mod;
99 rc = hw_get_module_by_class(KEYSTORE_HARDWARE_MODULE_ID, NULL, &mod);
100 if (rc) {
101 ALOGE("could not find any keystore module");
102 goto out;
103 }
104
105 rc = keymaster_open(mod, keymaster_dev);
106 if (rc) {
107 ALOGE("could not open keymaster device in %s (%s)",
108 KEYSTORE_HARDWARE_MODULE_ID, strerror(-rc));
109 goto out;
110 }
111
112 return 0;
113
114out:
115 *keymaster_dev = NULL;
116 return rc;
117}
118
119/* Should we use keymaster? */
120static int keymaster_check_compatibility()
121{
122 keymaster_device_t *keymaster_dev = 0;
123 int rc = 0;
124
125 if (keymaster_init(&keymaster_dev)) {
126 SLOGE("Failed to init keymaster");
127 rc = -1;
128 goto out;
129 }
130
Paul Lawrence8c008392014-05-06 14:02:48 -0700131 SLOGI("keymaster version is %d", keymaster_dev->common.module->module_api_version);
132
133 if (keymaster_dev->common.module->module_api_version
134 < KEYMASTER_MODULE_API_VERSION_0_3) {
135 rc = 0;
136 goto out;
137 }
138
Paul Lawrence69f4ebd2014-04-14 12:17:14 -0700139 if (keymaster_dev->flags & KEYMASTER_BLOBS_ARE_STANDALONE) {
140 rc = 1;
141 }
142
143out:
144 keymaster_close(keymaster_dev);
145 return rc;
146}
147
148/* Create a new keymaster key and store it in this footer */
149static int keymaster_create_key(struct crypt_mnt_ftr *ftr)
150{
151 uint8_t* key = 0;
152 keymaster_device_t *keymaster_dev = 0;
153
154 if (keymaster_init(&keymaster_dev)) {
155 SLOGE("Failed to init keymaster");
156 return -1;
157 }
158
159 int rc = 0;
160
161 keymaster_rsa_keygen_params_t params;
162 memset(&params, '\0', sizeof(params));
Shawn Willden47ba10d2014-09-03 17:07:06 -0600163 params.public_exponent = RSA_EXPONENT;
164 params.modulus_size = RSA_KEY_SIZE;
Paul Lawrence69f4ebd2014-04-14 12:17:14 -0700165
166 size_t key_size;
167 if (keymaster_dev->generate_keypair(keymaster_dev, TYPE_RSA, &params,
168 &key, &key_size)) {
169 SLOGE("Failed to generate keypair");
170 rc = -1;
171 goto out;
172 }
173
174 if (key_size > KEYMASTER_BLOB_SIZE) {
175 SLOGE("Keymaster key too large for crypto footer");
176 rc = -1;
177 goto out;
178 }
179
180 memcpy(ftr->keymaster_blob, key, key_size);
181 ftr->keymaster_blob_size = key_size;
182
183out:
184 keymaster_close(keymaster_dev);
185 free(key);
186 return rc;
187}
188
Shawn Willdene17a9c42014-09-08 13:04:08 -0600189/* This signs the given object using the keymaster key. */
190static int keymaster_sign_object(struct crypt_mnt_ftr *ftr,
Shawn Willden47ba10d2014-09-03 17:07:06 -0600191 const unsigned char *object,
192 const size_t object_size,
193 unsigned char **signature,
194 size_t *signature_size)
195{
196 int rc = 0;
197 keymaster_device_t *keymaster_dev = 0;
198 if (keymaster_init(&keymaster_dev)) {
199 SLOGE("Failed to init keymaster");
200 return -1;
201 }
202
203 /* We currently set the digest type to DIGEST_NONE because it's the
204 * only supported value for keymaster. A similar issue exists with
205 * PADDING_NONE. Long term both of these should likely change.
206 */
207 keymaster_rsa_sign_params_t params;
208 params.digest_type = DIGEST_NONE;
209 params.padding_type = PADDING_NONE;
210
211 unsigned char to_sign[RSA_KEY_SIZE_BYTES];
Shawn Willdene17a9c42014-09-08 13:04:08 -0600212 size_t to_sign_size = sizeof(to_sign);
Shawn Willden47ba10d2014-09-03 17:07:06 -0600213 memset(to_sign, 0, RSA_KEY_SIZE_BYTES);
Shawn Willden47ba10d2014-09-03 17:07:06 -0600214
Shawn Willdene17a9c42014-09-08 13:04:08 -0600215 // To sign a message with RSA, the message must satisfy two
216 // constraints:
217 //
218 // 1. The message, when interpreted as a big-endian numeric value, must
219 // be strictly less than the public modulus of the RSA key. Note
220 // that because the most significant bit of the public modulus is
221 // guaranteed to be 1 (else it's an (n-1)-bit key, not an n-bit
222 // key), an n-bit message with most significant bit 0 always
223 // satisfies this requirement.
224 //
225 // 2. The message must have the same length in bits as the public
226 // modulus of the RSA key. This requirement isn't mathematically
227 // necessary, but is necessary to ensure consistency in
228 // implementations.
229 switch (ftr->kdf_type) {
230 case KDF_SCRYPT_KEYMASTER_UNPADDED:
231 // This is broken: It produces a message which is shorter than
232 // the public modulus, failing criterion 2.
233 memcpy(to_sign, object, object_size);
234 to_sign_size = object_size;
235 SLOGI("Signing unpadded object");
236 break;
237 case KDF_SCRYPT_KEYMASTER_BADLY_PADDED:
238 // This is broken: Since the value of object is uniformly
239 // distributed, it produces a message that is larger than the
240 // public modulus with probability 0.25.
241 memcpy(to_sign, object, min(RSA_KEY_SIZE_BYTES, object_size));
242 SLOGI("Signing end-padded object");
243 break;
244 case KDF_SCRYPT_KEYMASTER:
245 // This ensures the most significant byte of the signed message
246 // is zero. We could have zero-padded to the left instead, but
247 // this approach is slightly more robust against changes in
248 // object size. However, it's still broken (but not unusably
249 // so) because we really should be using a proper RSA padding
250 // function, such as OAEP.
251 //
252 // TODO(paullawrence): When keymaster 0.4 is available, change
253 // this to use the padding options it provides.
254 memcpy(to_sign + 1, object, min(RSA_KEY_SIZE_BYTES - 1, object_size));
255 SLOGI("Signing safely-padded object");
256 break;
257 default:
258 SLOGE("Unknown KDF type %d", ftr->kdf_type);
259 return -1;
260 }
261
Shawn Willden47ba10d2014-09-03 17:07:06 -0600262 rc = keymaster_dev->sign_data(keymaster_dev,
263 &params,
264 ftr->keymaster_blob,
265 ftr->keymaster_blob_size,
266 to_sign,
Shawn Willdene17a9c42014-09-08 13:04:08 -0600267 to_sign_size,
Shawn Willden47ba10d2014-09-03 17:07:06 -0600268 signature,
269 signature_size);
270
271 keymaster_close(keymaster_dev);
272 return rc;
273}
274
Paul Lawrence399317e2014-03-10 13:20:50 -0700275/* Store password when userdata is successfully decrypted and mounted.
276 * Cleared by cryptfs_clear_password
277 *
278 * To avoid a double prompt at boot, we need to store the CryptKeeper
279 * password and pass it to KeyGuard, which uses it to unlock KeyStore.
280 * Since the entire framework is torn down and rebuilt after encryption,
281 * we have to use a daemon or similar to store the password. Since vold
282 * is secured against IPC except from system processes, it seems a reasonable
283 * place to store this.
284 *
285 * password should be cleared once it has been used.
286 *
287 * password is aged out after password_max_age_seconds seconds.
Paul Lawrence684dbdf2014-02-07 12:07:22 -0800288 */
Paul Lawrence399317e2014-03-10 13:20:50 -0700289static char* password = 0;
290static int password_expiry_time = 0;
291static const int password_max_age_seconds = 60;
Paul Lawrence684dbdf2014-02-07 12:07:22 -0800292
Ken Sumrall56ad03c2013-02-13 13:00:19 -0800293extern struct fstab *fstab;
Ken Sumrall8ddbe402011-01-17 15:26:29 -0800294
Paul Lawrence87999172014-02-20 12:21:31 -0800295enum RebootType {reboot, recovery, shutdown};
296static void cryptfs_reboot(enum RebootType rt)
Ken Sumralladfba362013-06-04 16:37:52 -0700297{
Paul Lawrence87999172014-02-20 12:21:31 -0800298 switch(rt) {
299 case reboot:
300 property_set(ANDROID_RB_PROPERTY, "reboot");
301 break;
302
303 case recovery:
304 property_set(ANDROID_RB_PROPERTY, "reboot,recovery");
305 break;
306
307 case shutdown:
308 property_set(ANDROID_RB_PROPERTY, "shutdown");
309 break;
Ken Sumralladfba362013-06-04 16:37:52 -0700310 }
Paul Lawrence87999172014-02-20 12:21:31 -0800311
Ken Sumralladfba362013-06-04 16:37:52 -0700312 sleep(20);
313
314 /* Shouldn't get here, reboot should happen before sleep times out */
315 return;
316}
317
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800318static void ioctl_init(struct dm_ioctl *io, size_t dataSize, const char *name, unsigned flags)
319{
320 memset(io, 0, dataSize);
321 io->data_size = dataSize;
322 io->data_start = sizeof(struct dm_ioctl);
323 io->version[0] = 4;
324 io->version[1] = 0;
325 io->version[2] = 0;
326 io->flags = flags;
327 if (name) {
328 strncpy(io->name, name, sizeof(io->name));
329 }
330}
331
Kenny Rootc4c70f12013-06-14 12:11:38 -0700332/**
333 * Gets the default device scrypt parameters for key derivation time tuning.
334 * The parameters should lead to about one second derivation time for the
335 * given device.
336 */
337static void get_device_scrypt_params(struct crypt_mnt_ftr *ftr) {
338 const int default_params[] = SCRYPT_DEFAULTS;
339 int params[] = SCRYPT_DEFAULTS;
340 char paramstr[PROPERTY_VALUE_MAX];
341 char *token;
342 char *saveptr;
343 int i;
344
345 property_get(SCRYPT_PROP, paramstr, "");
346 if (paramstr[0] != '\0') {
347 /*
348 * The token we're looking for should be three integers separated by
349 * colons (e.g., "12:8:1"). Scan the property to make sure it matches.
350 */
Kenny Root2947e342013-08-14 15:54:49 -0700351 for (i = 0, token = strtok_r(paramstr, ":", &saveptr);
352 token != NULL && i < 3;
Kenny Rootc4c70f12013-06-14 12:11:38 -0700353 i++, token = strtok_r(NULL, ":", &saveptr)) {
354 char *endptr;
355 params[i] = strtol(token, &endptr, 10);
356
357 /*
358 * Check that there was a valid number and it's 8-bit. If not,
359 * break out and the end check will take the default values.
360 */
361 if ((*token == '\0') || (*endptr != '\0') || params[i] < 0 || params[i] > 255) {
362 break;
363 }
364 }
365
366 /*
367 * If there were not enough tokens or a token was malformed (not an
368 * integer), it will end up here and the default parameters can be
369 * taken.
370 */
371 if ((i != 3) || (token != NULL)) {
372 SLOGW("bad scrypt parameters '%s' should be like '12:8:1'; using defaults", paramstr);
373 memcpy(params, default_params, sizeof(params));
374 }
375 }
376
377 ftr->N_factor = params[0];
378 ftr->r_factor = params[1];
379 ftr->p_factor = params[2];
380}
381
Ken Sumrall3ed82362011-01-28 23:31:16 -0800382static unsigned int get_fs_size(char *dev)
383{
384 int fd, block_size;
385 struct ext4_super_block sb;
386 off64_t len;
387
388 if ((fd = open(dev, O_RDONLY)) < 0) {
389 SLOGE("Cannot open device to get filesystem size ");
390 return 0;
391 }
392
393 if (lseek64(fd, 1024, SEEK_SET) < 0) {
394 SLOGE("Cannot seek to superblock");
395 return 0;
396 }
397
398 if (read(fd, &sb, sizeof(sb)) != sizeof(sb)) {
399 SLOGE("Cannot read superblock");
400 return 0;
401 }
402
403 close(fd);
404
Daniel Rosenberge82df162014-08-15 22:19:23 +0000405 if (le32_to_cpu(sb.s_magic) != EXT4_SUPER_MAGIC) {
406 SLOGE("Not a valid ext4 superblock");
407 return 0;
408 }
Ken Sumrall3ed82362011-01-28 23:31:16 -0800409 block_size = 1024 << sb.s_log_block_size;
410 /* compute length in bytes */
411 len = ( ((off64_t)sb.s_blocks_count_hi << 32) + sb.s_blocks_count_lo) * block_size;
412
413 /* return length in sectors */
414 return (unsigned int) (len / 512);
415}
416
Ken Sumrall160b4d62013-04-22 12:15:39 -0700417static int get_crypt_ftr_info(char **metadata_fname, off64_t *off)
418{
419 static int cached_data = 0;
420 static off64_t cached_off = 0;
421 static char cached_metadata_fname[PROPERTY_VALUE_MAX] = "";
422 int fd;
423 char key_loc[PROPERTY_VALUE_MAX];
424 char real_blkdev[PROPERTY_VALUE_MAX];
425 unsigned int nr_sec;
426 int rc = -1;
427
428 if (!cached_data) {
429 fs_mgr_get_crypt_info(fstab, key_loc, real_blkdev, sizeof(key_loc));
430
431 if (!strcmp(key_loc, KEY_IN_FOOTER)) {
432 if ( (fd = open(real_blkdev, O_RDWR)) < 0) {
433 SLOGE("Cannot open real block device %s\n", real_blkdev);
434 return -1;
435 }
436
437 if ((nr_sec = get_blkdev_size(fd))) {
438 /* If it's an encrypted Android partition, the last 16 Kbytes contain the
439 * encryption info footer and key, and plenty of bytes to spare for future
440 * growth.
441 */
442 strlcpy(cached_metadata_fname, real_blkdev, sizeof(cached_metadata_fname));
443 cached_off = ((off64_t)nr_sec * 512) - CRYPT_FOOTER_OFFSET;
444 cached_data = 1;
445 } else {
446 SLOGE("Cannot get size of block device %s\n", real_blkdev);
447 }
448 close(fd);
449 } else {
450 strlcpy(cached_metadata_fname, key_loc, sizeof(cached_metadata_fname));
451 cached_off = 0;
452 cached_data = 1;
453 }
454 }
455
456 if (cached_data) {
457 if (metadata_fname) {
458 *metadata_fname = cached_metadata_fname;
459 }
460 if (off) {
461 *off = cached_off;
462 }
463 rc = 0;
464 }
465
466 return rc;
467}
468
Ken Sumralle8744072011-01-18 22:01:55 -0800469/* key or salt can be NULL, in which case just skip writing that value. Useful to
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800470 * update the failed mount count but not change the key.
471 */
Ken Sumrall160b4d62013-04-22 12:15:39 -0700472static int put_crypt_ftr_and_key(struct crypt_mnt_ftr *crypt_ftr)
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800473{
474 int fd;
475 unsigned int nr_sec, cnt;
Ken Sumrall160b4d62013-04-22 12:15:39 -0700476 /* starting_off is set to the SEEK_SET offset
477 * where the crypto structure starts
478 */
479 off64_t starting_off;
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800480 int rc = -1;
Ken Sumrall160b4d62013-04-22 12:15:39 -0700481 char *fname = NULL;
Ken Sumrall3be890f2011-09-14 16:53:46 -0700482 struct stat statbuf;
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800483
Ken Sumrall160b4d62013-04-22 12:15:39 -0700484 if (get_crypt_ftr_info(&fname, &starting_off)) {
485 SLOGE("Unable to get crypt_ftr_info\n");
486 return -1;
487 }
488 if (fname[0] != '/') {
Ken Sumralle5032c42012-04-01 23:58:44 -0700489 SLOGE("Unexpected value for crypto key location\n");
Ken Sumrall160b4d62013-04-22 12:15:39 -0700490 return -1;
491 }
Ken Sumralle550f782013-08-20 13:48:23 -0700492 if ( (fd = open(fname, O_RDWR | O_CREAT, 0600)) < 0) {
493 SLOGE("Cannot open footer file %s for put\n", fname);
Ken Sumrall160b4d62013-04-22 12:15:39 -0700494 return -1;
495 }
496
497 /* Seek to the start of the crypt footer */
498 if (lseek64(fd, starting_off, SEEK_SET) == -1) {
499 SLOGE("Cannot seek to real block device footer\n");
500 goto errout;
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800501 }
502
503 if ((cnt = write(fd, crypt_ftr, sizeof(struct crypt_mnt_ftr))) != sizeof(struct crypt_mnt_ftr)) {
504 SLOGE("Cannot write real block device footer\n");
505 goto errout;
506 }
507
Ken Sumrall3be890f2011-09-14 16:53:46 -0700508 fstat(fd, &statbuf);
509 /* If the keys are kept on a raw block device, do not try to truncate it. */
Ken Sumralle550f782013-08-20 13:48:23 -0700510 if (S_ISREG(statbuf.st_mode)) {
Ken Sumrall29d8da82011-05-18 17:20:07 -0700511 if (ftruncate(fd, 0x4000)) {
Colin Cross59846b62014-02-06 20:34:29 -0800512 SLOGE("Cannot set footer file size\n");
Ken Sumralle8744072011-01-18 22:01:55 -0800513 goto errout;
514 }
515 }
516
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800517 /* Success! */
518 rc = 0;
519
520errout:
521 close(fd);
522 return rc;
523
524}
525
Ken Sumrall160b4d62013-04-22 12:15:39 -0700526static inline int unix_read(int fd, void* buff, int len)
527{
528 return TEMP_FAILURE_RETRY(read(fd, buff, len));
529}
530
531static inline int unix_write(int fd, const void* buff, int len)
532{
533 return TEMP_FAILURE_RETRY(write(fd, buff, len));
534}
535
536static void init_empty_persist_data(struct crypt_persist_data *pdata, int len)
537{
538 memset(pdata, 0, len);
539 pdata->persist_magic = PERSIST_DATA_MAGIC;
540 pdata->persist_valid_entries = 0;
541}
542
543/* A routine to update the passed in crypt_ftr to the lastest version.
544 * fd is open read/write on the device that holds the crypto footer and persistent
545 * data, crypt_ftr is a pointer to the struct to be updated, and offset is the
546 * absolute offset to the start of the crypt_mnt_ftr on the passed in fd.
547 */
548static void upgrade_crypt_ftr(int fd, struct crypt_mnt_ftr *crypt_ftr, off64_t offset)
549{
Kenny Root7434b312013-06-14 11:29:53 -0700550 int orig_major = crypt_ftr->major_version;
551 int orig_minor = crypt_ftr->minor_version;
Ken Sumrall160b4d62013-04-22 12:15:39 -0700552
Kenny Root7434b312013-06-14 11:29:53 -0700553 if ((crypt_ftr->major_version == 1) && (crypt_ftr->minor_version == 0)) {
554 struct crypt_persist_data *pdata;
555 off64_t pdata_offset = offset + CRYPT_FOOTER_TO_PERSIST_OFFSET;
Ken Sumrall160b4d62013-04-22 12:15:39 -0700556
Kenny Rootc4c70f12013-06-14 12:11:38 -0700557 SLOGW("upgrading crypto footer to 1.1");
558
Kenny Root7434b312013-06-14 11:29:53 -0700559 pdata = malloc(CRYPT_PERSIST_DATA_SIZE);
560 if (pdata == NULL) {
561 SLOGE("Cannot allocate persisent data\n");
562 return;
563 }
564 memset(pdata, 0, CRYPT_PERSIST_DATA_SIZE);
565
566 /* Need to initialize the persistent data area */
567 if (lseek64(fd, pdata_offset, SEEK_SET) == -1) {
568 SLOGE("Cannot seek to persisent data offset\n");
569 return;
570 }
571 /* Write all zeros to the first copy, making it invalid */
572 unix_write(fd, pdata, CRYPT_PERSIST_DATA_SIZE);
573
574 /* Write a valid but empty structure to the second copy */
575 init_empty_persist_data(pdata, CRYPT_PERSIST_DATA_SIZE);
576 unix_write(fd, pdata, CRYPT_PERSIST_DATA_SIZE);
577
578 /* Update the footer */
579 crypt_ftr->persist_data_size = CRYPT_PERSIST_DATA_SIZE;
580 crypt_ftr->persist_data_offset[0] = pdata_offset;
581 crypt_ftr->persist_data_offset[1] = pdata_offset + CRYPT_PERSIST_DATA_SIZE;
582 crypt_ftr->minor_version = 1;
Ken Sumrall160b4d62013-04-22 12:15:39 -0700583 }
584
Paul Lawrencef4faa572014-01-29 13:31:03 -0800585 if ((crypt_ftr->major_version == 1) && (crypt_ftr->minor_version == 1)) {
Kenny Rootc4c70f12013-06-14 12:11:38 -0700586 SLOGW("upgrading crypto footer to 1.2");
JP Abgrall7bdfa522013-11-15 13:42:56 -0800587 /* But keep the old kdf_type.
588 * It will get updated later to KDF_SCRYPT after the password has been verified.
589 */
Kenny Rootc4c70f12013-06-14 12:11:38 -0700590 crypt_ftr->kdf_type = KDF_PBKDF2;
591 get_device_scrypt_params(crypt_ftr);
592 crypt_ftr->minor_version = 2;
593 }
594
Paul Lawrencef4faa572014-01-29 13:31:03 -0800595 if ((crypt_ftr->major_version == 1) && (crypt_ftr->minor_version == 2)) {
596 SLOGW("upgrading crypto footer to 1.3");
597 crypt_ftr->crypt_type = CRYPT_TYPE_PASSWORD;
598 crypt_ftr->minor_version = 3;
599 }
600
Kenny Root7434b312013-06-14 11:29:53 -0700601 if ((orig_major != crypt_ftr->major_version) || (orig_minor != crypt_ftr->minor_version)) {
602 if (lseek64(fd, offset, SEEK_SET) == -1) {
603 SLOGE("Cannot seek to crypt footer\n");
604 return;
605 }
606 unix_write(fd, crypt_ftr, sizeof(struct crypt_mnt_ftr));
Ken Sumrall160b4d62013-04-22 12:15:39 -0700607 }
Ken Sumrall160b4d62013-04-22 12:15:39 -0700608}
609
610
611static int get_crypt_ftr_and_key(struct crypt_mnt_ftr *crypt_ftr)
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800612{
613 int fd;
614 unsigned int nr_sec, cnt;
Ken Sumrall160b4d62013-04-22 12:15:39 -0700615 off64_t starting_off;
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800616 int rc = -1;
Ken Sumrall160b4d62013-04-22 12:15:39 -0700617 char *fname = NULL;
Ken Sumrall29d8da82011-05-18 17:20:07 -0700618 struct stat statbuf;
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800619
Ken Sumrall160b4d62013-04-22 12:15:39 -0700620 if (get_crypt_ftr_info(&fname, &starting_off)) {
621 SLOGE("Unable to get crypt_ftr_info\n");
622 return -1;
623 }
624 if (fname[0] != '/') {
Ken Sumralle5032c42012-04-01 23:58:44 -0700625 SLOGE("Unexpected value for crypto key location\n");
Ken Sumrall160b4d62013-04-22 12:15:39 -0700626 return -1;
627 }
628 if ( (fd = open(fname, O_RDWR)) < 0) {
Ken Sumralle550f782013-08-20 13:48:23 -0700629 SLOGE("Cannot open footer file %s for get\n", fname);
Ken Sumrall160b4d62013-04-22 12:15:39 -0700630 return -1;
631 }
632
633 /* Make sure it's 16 Kbytes in length */
634 fstat(fd, &statbuf);
635 if (S_ISREG(statbuf.st_mode) && (statbuf.st_size != 0x4000)) {
636 SLOGE("footer file %s is not the expected size!\n", fname);
637 goto errout;
638 }
639
640 /* Seek to the start of the crypt footer */
641 if (lseek64(fd, starting_off, SEEK_SET) == -1) {
642 SLOGE("Cannot seek to real block device footer\n");
643 goto errout;
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800644 }
645
646 if ( (cnt = read(fd, crypt_ftr, sizeof(struct crypt_mnt_ftr))) != sizeof(struct crypt_mnt_ftr)) {
647 SLOGE("Cannot read real block device footer\n");
648 goto errout;
649 }
650
651 if (crypt_ftr->magic != CRYPT_MNT_MAGIC) {
Ken Sumrall29d8da82011-05-18 17:20:07 -0700652 SLOGE("Bad magic for real block device %s\n", fname);
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800653 goto errout;
654 }
655
Kenny Rootc96a5f82013-06-14 12:08:28 -0700656 if (crypt_ftr->major_version != CURRENT_MAJOR_VERSION) {
657 SLOGE("Cannot understand major version %d real block device footer; expected %d\n",
658 crypt_ftr->major_version, CURRENT_MAJOR_VERSION);
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800659 goto errout;
660 }
661
Kenny Rootc96a5f82013-06-14 12:08:28 -0700662 if (crypt_ftr->minor_version > CURRENT_MINOR_VERSION) {
663 SLOGW("Warning: crypto footer minor version %d, expected <= %d, continuing...\n",
664 crypt_ftr->minor_version, CURRENT_MINOR_VERSION);
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800665 }
666
Ken Sumrall160b4d62013-04-22 12:15:39 -0700667 /* If this is a verion 1.0 crypt_ftr, make it a 1.1 crypt footer, and update the
668 * copy on disk before returning.
669 */
Kenny Rootc96a5f82013-06-14 12:08:28 -0700670 if (crypt_ftr->minor_version < CURRENT_MINOR_VERSION) {
Ken Sumrall160b4d62013-04-22 12:15:39 -0700671 upgrade_crypt_ftr(fd, crypt_ftr, starting_off);
Ken Sumralle8744072011-01-18 22:01:55 -0800672 }
673
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800674 /* Success! */
675 rc = 0;
676
677errout:
678 close(fd);
679 return rc;
680}
681
Ken Sumrall160b4d62013-04-22 12:15:39 -0700682static int validate_persistent_data_storage(struct crypt_mnt_ftr *crypt_ftr)
683{
684 if (crypt_ftr->persist_data_offset[0] + crypt_ftr->persist_data_size >
685 crypt_ftr->persist_data_offset[1]) {
686 SLOGE("Crypt_ftr persist data regions overlap");
687 return -1;
688 }
689
690 if (crypt_ftr->persist_data_offset[0] >= crypt_ftr->persist_data_offset[1]) {
691 SLOGE("Crypt_ftr persist data region 0 starts after region 1");
692 return -1;
693 }
694
695 if (((crypt_ftr->persist_data_offset[1] + crypt_ftr->persist_data_size) -
696 (crypt_ftr->persist_data_offset[0] - CRYPT_FOOTER_TO_PERSIST_OFFSET)) >
697 CRYPT_FOOTER_OFFSET) {
698 SLOGE("Persistent data extends past crypto footer");
699 return -1;
700 }
701
702 return 0;
703}
704
705static int load_persistent_data(void)
706{
707 struct crypt_mnt_ftr crypt_ftr;
708 struct crypt_persist_data *pdata = NULL;
709 char encrypted_state[PROPERTY_VALUE_MAX];
710 char *fname;
711 int found = 0;
712 int fd;
713 int ret;
714 int i;
715
716 if (persist_data) {
717 /* Nothing to do, we've already loaded or initialized it */
718 return 0;
719 }
720
721
722 /* If not encrypted, just allocate an empty table and initialize it */
723 property_get("ro.crypto.state", encrypted_state, "");
724 if (strcmp(encrypted_state, "encrypted") ) {
725 pdata = malloc(CRYPT_PERSIST_DATA_SIZE);
726 if (pdata) {
727 init_empty_persist_data(pdata, CRYPT_PERSIST_DATA_SIZE);
728 persist_data = pdata;
729 return 0;
730 }
731 return -1;
732 }
733
734 if(get_crypt_ftr_and_key(&crypt_ftr)) {
735 return -1;
736 }
737
Paul Lawrence8561b5c2014-03-17 14:10:51 -0700738 if ((crypt_ftr.major_version < 1)
739 || (crypt_ftr.major_version == 1 && crypt_ftr.minor_version < 1)) {
Ken Sumrall160b4d62013-04-22 12:15:39 -0700740 SLOGE("Crypt_ftr version doesn't support persistent data");
741 return -1;
742 }
743
744 if (get_crypt_ftr_info(&fname, NULL)) {
745 return -1;
746 }
747
748 ret = validate_persistent_data_storage(&crypt_ftr);
749 if (ret) {
750 return -1;
751 }
752
753 fd = open(fname, O_RDONLY);
754 if (fd < 0) {
755 SLOGE("Cannot open %s metadata file", fname);
756 return -1;
757 }
758
759 if (persist_data == NULL) {
760 pdata = malloc(crypt_ftr.persist_data_size);
761 if (pdata == NULL) {
762 SLOGE("Cannot allocate memory for persistent data");
763 goto err;
764 }
765 }
766
767 for (i = 0; i < 2; i++) {
768 if (lseek64(fd, crypt_ftr.persist_data_offset[i], SEEK_SET) < 0) {
769 SLOGE("Cannot seek to read persistent data on %s", fname);
770 goto err2;
771 }
772 if (unix_read(fd, pdata, crypt_ftr.persist_data_size) < 0){
773 SLOGE("Error reading persistent data on iteration %d", i);
774 goto err2;
775 }
776 if (pdata->persist_magic == PERSIST_DATA_MAGIC) {
777 found = 1;
778 break;
779 }
780 }
781
782 if (!found) {
783 SLOGI("Could not find valid persistent data, creating");
784 init_empty_persist_data(pdata, crypt_ftr.persist_data_size);
785 }
786
787 /* Success */
788 persist_data = pdata;
789 close(fd);
790 return 0;
791
792err2:
793 free(pdata);
794
795err:
796 close(fd);
797 return -1;
798}
799
800static int save_persistent_data(void)
801{
802 struct crypt_mnt_ftr crypt_ftr;
803 struct crypt_persist_data *pdata;
804 char *fname;
805 off64_t write_offset;
806 off64_t erase_offset;
807 int found = 0;
808 int fd;
809 int ret;
810
811 if (persist_data == NULL) {
812 SLOGE("No persistent data to save");
813 return -1;
814 }
815
816 if(get_crypt_ftr_and_key(&crypt_ftr)) {
817 return -1;
818 }
819
Paul Lawrence8561b5c2014-03-17 14:10:51 -0700820 if ((crypt_ftr.major_version < 1)
821 || (crypt_ftr.major_version == 1 && crypt_ftr.minor_version < 1)) {
Ken Sumrall160b4d62013-04-22 12:15:39 -0700822 SLOGE("Crypt_ftr version doesn't support persistent data");
823 return -1;
824 }
825
826 ret = validate_persistent_data_storage(&crypt_ftr);
827 if (ret) {
828 return -1;
829 }
830
831 if (get_crypt_ftr_info(&fname, NULL)) {
832 return -1;
833 }
834
835 fd = open(fname, O_RDWR);
836 if (fd < 0) {
837 SLOGE("Cannot open %s metadata file", fname);
838 return -1;
839 }
840
841 pdata = malloc(crypt_ftr.persist_data_size);
842 if (pdata == NULL) {
843 SLOGE("Cannot allocate persistant data");
844 goto err;
845 }
846
847 if (lseek64(fd, crypt_ftr.persist_data_offset[0], SEEK_SET) < 0) {
848 SLOGE("Cannot seek to read persistent data on %s", fname);
849 goto err2;
850 }
851
852 if (unix_read(fd, pdata, crypt_ftr.persist_data_size) < 0) {
853 SLOGE("Error reading persistent data before save");
854 goto err2;
855 }
856
857 if (pdata->persist_magic == PERSIST_DATA_MAGIC) {
858 /* The first copy is the curent valid copy, so write to
859 * the second copy and erase this one */
860 write_offset = crypt_ftr.persist_data_offset[1];
861 erase_offset = crypt_ftr.persist_data_offset[0];
862 } else {
863 /* The second copy must be the valid copy, so write to
864 * the first copy, and erase the second */
865 write_offset = crypt_ftr.persist_data_offset[0];
866 erase_offset = crypt_ftr.persist_data_offset[1];
867 }
868
869 /* Write the new copy first, if successful, then erase the old copy */
870 if (lseek(fd, write_offset, SEEK_SET) < 0) {
871 SLOGE("Cannot seek to write persistent data");
872 goto err2;
873 }
874 if (unix_write(fd, persist_data, crypt_ftr.persist_data_size) ==
875 (int) crypt_ftr.persist_data_size) {
876 if (lseek(fd, erase_offset, SEEK_SET) < 0) {
877 SLOGE("Cannot seek to erase previous persistent data");
878 goto err2;
879 }
880 fsync(fd);
881 memset(pdata, 0, crypt_ftr.persist_data_size);
882 if (unix_write(fd, pdata, crypt_ftr.persist_data_size) !=
883 (int) crypt_ftr.persist_data_size) {
884 SLOGE("Cannot write to erase previous persistent data");
885 goto err2;
886 }
887 fsync(fd);
888 } else {
889 SLOGE("Cannot write to save persistent data");
890 goto err2;
891 }
892
893 /* Success */
894 free(pdata);
895 close(fd);
896 return 0;
897
898err2:
899 free(pdata);
900err:
901 close(fd);
902 return -1;
903}
904
Paul Lawrencef4faa572014-01-29 13:31:03 -0800905static int hexdigit (char c)
906{
907 if (c >= '0' && c <= '9') return c - '0';
908 c = tolower(c);
909 if (c >= 'a' && c <= 'f') return c - 'a' + 10;
910 return -1;
911}
912
913static unsigned char* convert_hex_ascii_to_key(const char* master_key_ascii,
914 unsigned int* out_keysize)
915{
916 unsigned int i;
917 *out_keysize = 0;
918
919 size_t size = strlen (master_key_ascii);
920 if (size % 2) {
921 SLOGE("Trying to convert ascii string of odd length");
922 return NULL;
923 }
924
925 unsigned char* master_key = (unsigned char*) malloc(size / 2);
926 if (master_key == 0) {
927 SLOGE("Cannot allocate");
928 return NULL;
929 }
930
931 for (i = 0; i < size; i += 2) {
932 int high_nibble = hexdigit (master_key_ascii[i]);
933 int low_nibble = hexdigit (master_key_ascii[i + 1]);
934
935 if(high_nibble < 0 || low_nibble < 0) {
936 SLOGE("Invalid hex string");
937 free (master_key);
938 return NULL;
939 }
940
941 master_key[*out_keysize] = high_nibble * 16 + low_nibble;
942 (*out_keysize)++;
943 }
944
945 return master_key;
946}
947
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800948/* Convert a binary key of specified length into an ascii hex string equivalent,
949 * without the leading 0x and with null termination
950 */
Paul Lawrencef4faa572014-01-29 13:31:03 -0800951static void convert_key_to_hex_ascii(unsigned char *master_key, unsigned int keysize,
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800952 char *master_key_ascii)
953{
954 unsigned int i, a;
955 unsigned char nibble;
956
957 for (i=0, a=0; i<keysize; i++, a+=2) {
958 /* For each byte, write out two ascii hex digits */
959 nibble = (master_key[i] >> 4) & 0xf;
960 master_key_ascii[a] = nibble + (nibble > 9 ? 0x37 : 0x30);
961
962 nibble = master_key[i] & 0xf;
963 master_key_ascii[a+1] = nibble + (nibble > 9 ? 0x37 : 0x30);
964 }
965
966 /* Add the null termination */
967 master_key_ascii[a] = '\0';
968
969}
970
Ken Sumralldb5e0262013-02-05 17:39:48 -0800971static int load_crypto_mapping_table(struct crypt_mnt_ftr *crypt_ftr, unsigned char *master_key,
972 char *real_blk_name, const char *name, int fd,
973 char *extra_params)
974{
975 char buffer[DM_CRYPT_BUF_SIZE];
976 struct dm_ioctl *io;
977 struct dm_target_spec *tgt;
978 char *crypt_params;
979 char master_key_ascii[129]; /* Large enough to hold 512 bit key and null */
980 int i;
981
982 io = (struct dm_ioctl *) buffer;
983
984 /* Load the mapping table for this device */
985 tgt = (struct dm_target_spec *) &buffer[sizeof(struct dm_ioctl)];
986
987 ioctl_init(io, DM_CRYPT_BUF_SIZE, name, 0);
988 io->target_count = 1;
989 tgt->status = 0;
990 tgt->sector_start = 0;
991 tgt->length = crypt_ftr->fs_size;
992 strcpy(tgt->target_type, "crypt");
993
994 crypt_params = buffer + sizeof(struct dm_ioctl) + sizeof(struct dm_target_spec);
995 convert_key_to_hex_ascii(master_key, crypt_ftr->keysize, master_key_ascii);
996 sprintf(crypt_params, "%s %s 0 %s 0 %s", crypt_ftr->crypto_type_name,
997 master_key_ascii, real_blk_name, extra_params);
998 crypt_params += strlen(crypt_params) + 1;
999 crypt_params = (char *) (((unsigned long)crypt_params + 7) & ~8); /* Align to an 8 byte boundary */
1000 tgt->next = crypt_params - buffer;
1001
1002 for (i = 0; i < TABLE_LOAD_RETRIES; i++) {
1003 if (! ioctl(fd, DM_TABLE_LOAD, io)) {
1004 break;
1005 }
1006 usleep(500000);
1007 }
1008
1009 if (i == TABLE_LOAD_RETRIES) {
1010 /* We failed to load the table, return an error */
1011 return -1;
1012 } else {
1013 return i + 1;
1014 }
1015}
1016
1017
1018static int get_dm_crypt_version(int fd, const char *name, int *version)
1019{
1020 char buffer[DM_CRYPT_BUF_SIZE];
1021 struct dm_ioctl *io;
1022 struct dm_target_versions *v;
1023 int i;
1024
1025 io = (struct dm_ioctl *) buffer;
1026
1027 ioctl_init(io, DM_CRYPT_BUF_SIZE, name, 0);
1028
1029 if (ioctl(fd, DM_LIST_VERSIONS, io)) {
1030 return -1;
1031 }
1032
1033 /* Iterate over the returned versions, looking for name of "crypt".
1034 * When found, get and return the version.
1035 */
1036 v = (struct dm_target_versions *) &buffer[sizeof(struct dm_ioctl)];
1037 while (v->next) {
1038 if (! strcmp(v->name, "crypt")) {
1039 /* We found the crypt driver, return the version, and get out */
1040 version[0] = v->version[0];
1041 version[1] = v->version[1];
1042 version[2] = v->version[2];
1043 return 0;
1044 }
1045 v = (struct dm_target_versions *)(((char *)v) + v->next);
1046 }
1047
1048 return -1;
1049}
1050
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001051static int create_crypto_blk_dev(struct crypt_mnt_ftr *crypt_ftr, unsigned char *master_key,
Ken Sumrall29d8da82011-05-18 17:20:07 -07001052 char *real_blk_name, char *crypto_blk_name, const char *name)
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001053{
1054 char buffer[DM_CRYPT_BUF_SIZE];
1055 char master_key_ascii[129]; /* Large enough to hold 512 bit key and null */
1056 char *crypt_params;
1057 struct dm_ioctl *io;
1058 struct dm_target_spec *tgt;
1059 unsigned int minor;
1060 int fd;
Ken Sumralle919efe2012-09-29 17:07:41 -07001061 int i;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001062 int retval = -1;
Ken Sumralldb5e0262013-02-05 17:39:48 -08001063 int version[3];
1064 char *extra_params;
1065 int load_count;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001066
1067 if ((fd = open("/dev/device-mapper", O_RDWR)) < 0 ) {
1068 SLOGE("Cannot open device-mapper\n");
1069 goto errout;
1070 }
1071
1072 io = (struct dm_ioctl *) buffer;
1073
1074 ioctl_init(io, DM_CRYPT_BUF_SIZE, name, 0);
1075 if (ioctl(fd, DM_DEV_CREATE, io)) {
1076 SLOGE("Cannot create dm-crypt device\n");
1077 goto errout;
1078 }
1079
1080 /* Get the device status, in particular, the name of it's device file */
1081 ioctl_init(io, DM_CRYPT_BUF_SIZE, name, 0);
1082 if (ioctl(fd, DM_DEV_STATUS, io)) {
1083 SLOGE("Cannot retrieve dm-crypt device status\n");
1084 goto errout;
1085 }
1086 minor = (io->dev & 0xff) | ((io->dev >> 12) & 0xfff00);
1087 snprintf(crypto_blk_name, MAXPATHLEN, "/dev/block/dm-%u", minor);
1088
Ken Sumralldb5e0262013-02-05 17:39:48 -08001089 extra_params = "";
1090 if (! get_dm_crypt_version(fd, name, version)) {
1091 /* Support for allow_discards was added in version 1.11.0 */
1092 if ((version[0] >= 2) ||
1093 ((version[0] == 1) && (version[1] >= 11))) {
1094 extra_params = "1 allow_discards";
1095 SLOGI("Enabling support for allow_discards in dmcrypt.\n");
1096 }
Ken Sumralle919efe2012-09-29 17:07:41 -07001097 }
1098
Ken Sumralldb5e0262013-02-05 17:39:48 -08001099 load_count = load_crypto_mapping_table(crypt_ftr, master_key, real_blk_name, name,
1100 fd, extra_params);
1101 if (load_count < 0) {
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001102 SLOGE("Cannot load dm-crypt mapping table.\n");
1103 goto errout;
Ken Sumralldb5e0262013-02-05 17:39:48 -08001104 } else if (load_count > 1) {
1105 SLOGI("Took %d tries to load dmcrypt table.\n", load_count);
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001106 }
1107
1108 /* Resume this device to activate it */
Ken Sumralldb5e0262013-02-05 17:39:48 -08001109 ioctl_init(io, DM_CRYPT_BUF_SIZE, name, 0);
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001110
1111 if (ioctl(fd, DM_DEV_SUSPEND, io)) {
1112 SLOGE("Cannot resume the dm-crypt device\n");
1113 goto errout;
1114 }
1115
1116 /* We made it here with no errors. Woot! */
1117 retval = 0;
1118
1119errout:
1120 close(fd); /* If fd is <0 from a failed open call, it's safe to just ignore the close error */
1121
1122 return retval;
1123}
1124
Ken Sumrall29d8da82011-05-18 17:20:07 -07001125static int delete_crypto_blk_dev(char *name)
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001126{
1127 int fd;
1128 char buffer[DM_CRYPT_BUF_SIZE];
1129 struct dm_ioctl *io;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001130 int retval = -1;
1131
1132 if ((fd = open("/dev/device-mapper", O_RDWR)) < 0 ) {
1133 SLOGE("Cannot open device-mapper\n");
1134 goto errout;
1135 }
1136
1137 io = (struct dm_ioctl *) buffer;
1138
1139 ioctl_init(io, DM_CRYPT_BUF_SIZE, name, 0);
1140 if (ioctl(fd, DM_DEV_REMOVE, io)) {
1141 SLOGE("Cannot remove dm-crypt device\n");
1142 goto errout;
1143 }
1144
1145 /* We made it here with no errors. Woot! */
1146 retval = 0;
1147
1148errout:
1149 close(fd); /* If fd is <0 from a failed open call, it's safe to just ignore the close error */
1150
1151 return retval;
1152
1153}
1154
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001155static int pbkdf2(const char *passwd, const unsigned char *salt,
Paul Lawrencef4faa572014-01-29 13:31:03 -08001156 unsigned char *ikey, void *params UNUSED)
1157{
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001158 SLOGI("Using pbkdf2 for cryptfs KDF");
1159
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001160 /* Turn the password into a key and IV that can decrypt the master key */
Paul Lawrencef4faa572014-01-29 13:31:03 -08001161 unsigned int keysize;
1162 char* master_key = (char*)convert_hex_ascii_to_key(passwd, &keysize);
1163 if (!master_key) return -1;
1164 PKCS5_PBKDF2_HMAC_SHA1(master_key, keysize, salt, SALT_LEN,
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001165 HASH_COUNT, KEY_LEN_BYTES+IV_LEN_BYTES, ikey);
Paul Lawrencef4faa572014-01-29 13:31:03 -08001166
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001167 memset(master_key, 0, keysize);
Paul Lawrencef4faa572014-01-29 13:31:03 -08001168 free (master_key);
1169 return 0;
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001170}
1171
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001172static int scrypt(const char *passwd, const unsigned char *salt,
Paul Lawrencef4faa572014-01-29 13:31:03 -08001173 unsigned char *ikey, void *params)
1174{
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001175 SLOGI("Using scrypt for cryptfs KDF");
1176
Kenny Rootc4c70f12013-06-14 12:11:38 -07001177 struct crypt_mnt_ftr *ftr = (struct crypt_mnt_ftr *) params;
1178
1179 int N = 1 << ftr->N_factor;
1180 int r = 1 << ftr->r_factor;
1181 int p = 1 << ftr->p_factor;
1182
1183 /* Turn the password into a key and IV that can decrypt the master key */
Paul Lawrencef4faa572014-01-29 13:31:03 -08001184 unsigned int keysize;
1185 unsigned char* master_key = convert_hex_ascii_to_key(passwd, &keysize);
1186 if (!master_key) return -1;
1187 crypto_scrypt(master_key, keysize, salt, SALT_LEN, N, r, p, ikey,
Kenny Rootc4c70f12013-06-14 12:11:38 -07001188 KEY_LEN_BYTES + IV_LEN_BYTES);
Paul Lawrencef4faa572014-01-29 13:31:03 -08001189
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001190 memset(master_key, 0, keysize);
Paul Lawrencef4faa572014-01-29 13:31:03 -08001191 free (master_key);
1192 return 0;
Kenny Rootc4c70f12013-06-14 12:11:38 -07001193}
1194
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001195static int scrypt_keymaster(const char *passwd, const unsigned char *salt,
1196 unsigned char *ikey, void *params)
1197{
1198 SLOGI("Using scrypt with keymaster for cryptfs KDF");
1199
1200 int rc;
1201 unsigned int key_size;
1202 size_t signature_size;
1203 unsigned char* signature;
1204 struct crypt_mnt_ftr *ftr = (struct crypt_mnt_ftr *) params;
1205
1206 int N = 1 << ftr->N_factor;
1207 int r = 1 << ftr->r_factor;
1208 int p = 1 << ftr->p_factor;
1209
1210 unsigned char* master_key = convert_hex_ascii_to_key(passwd, &key_size);
1211 if (!master_key) {
1212 SLOGE("Failed to convert passwd from hex");
1213 return -1;
1214 }
1215
1216 rc = crypto_scrypt(master_key, key_size, salt, SALT_LEN,
1217 N, r, p, ikey, KEY_LEN_BYTES + IV_LEN_BYTES);
1218 memset(master_key, 0, key_size);
1219 free(master_key);
1220
1221 if (rc) {
1222 SLOGE("scrypt failed");
1223 return -1;
1224 }
1225
Shawn Willdene17a9c42014-09-08 13:04:08 -06001226 if (keymaster_sign_object(ftr, ikey, KEY_LEN_BYTES + IV_LEN_BYTES,
1227 &signature, &signature_size)) {
1228 SLOGE("Signing failed");
1229 return -1;
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001230 }
1231
1232 rc = crypto_scrypt(signature, signature_size, salt, SALT_LEN,
1233 N, r, p, ikey, KEY_LEN_BYTES + IV_LEN_BYTES);
1234 free(signature);
1235
1236 if (rc) {
1237 SLOGE("scrypt failed");
1238 return -1;
1239 }
1240
1241 return 0;
1242}
1243
1244static int encrypt_master_key(const char *passwd, const unsigned char *salt,
1245 const unsigned char *decrypted_master_key,
Kenny Rootc4c70f12013-06-14 12:11:38 -07001246 unsigned char *encrypted_master_key,
1247 struct crypt_mnt_ftr *crypt_ftr)
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001248{
1249 unsigned char ikey[32+32] = { 0 }; /* Big enough to hold a 256 bit key and 256 bit IV */
1250 EVP_CIPHER_CTX e_ctx;
1251 int encrypted_len, final_len;
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001252 int rc = 0;
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001253
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001254 /* Turn the password into an intermediate key and IV that can decrypt the master key */
Kenny Rootc4c70f12013-06-14 12:11:38 -07001255 get_device_scrypt_params(crypt_ftr);
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001256
1257 switch (crypt_ftr->kdf_type) {
Shawn Willdene17a9c42014-09-08 13:04:08 -06001258 case KDF_SCRYPT_KEYMASTER_UNPADDED:
1259 case KDF_SCRYPT_KEYMASTER_BADLY_PADDED:
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001260 case KDF_SCRYPT_KEYMASTER:
1261 if (keymaster_create_key(crypt_ftr)) {
1262 SLOGE("keymaster_create_key failed");
1263 return -1;
1264 }
1265
1266 if (scrypt_keymaster(passwd, salt, ikey, crypt_ftr)) {
1267 SLOGE("scrypt failed");
1268 return -1;
1269 }
1270 break;
1271
1272 case KDF_SCRYPT:
1273 if (scrypt(passwd, salt, ikey, crypt_ftr)) {
1274 SLOGE("scrypt failed");
1275 return -1;
1276 }
1277 break;
1278
1279 default:
1280 SLOGE("Invalid kdf_type");
Paul Lawrencef4faa572014-01-29 13:31:03 -08001281 return -1;
1282 }
Kenny Rootc4c70f12013-06-14 12:11:38 -07001283
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001284 /* Initialize the decryption engine */
1285 if (! EVP_EncryptInit(&e_ctx, EVP_aes_128_cbc(), ikey, ikey+KEY_LEN_BYTES)) {
1286 SLOGE("EVP_EncryptInit failed\n");
1287 return -1;
1288 }
1289 EVP_CIPHER_CTX_set_padding(&e_ctx, 0); /* Turn off padding as our data is block aligned */
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001290
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001291 /* Encrypt the master key */
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001292 if (! EVP_EncryptUpdate(&e_ctx, encrypted_master_key, &encrypted_len,
1293 decrypted_master_key, KEY_LEN_BYTES)) {
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001294 SLOGE("EVP_EncryptUpdate failed\n");
1295 return -1;
1296 }
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001297 if (! EVP_EncryptFinal(&e_ctx, encrypted_master_key + encrypted_len, &final_len)) {
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001298 SLOGE("EVP_EncryptFinal failed\n");
1299 return -1;
1300 }
1301
1302 if (encrypted_len + final_len != KEY_LEN_BYTES) {
1303 SLOGE("EVP_Encryption length check failed with %d, %d bytes\n", encrypted_len, final_len);
1304 return -1;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001305 }
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001306
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001307 /* Store the scrypt of the intermediate key, so we can validate if it's a
1308 password error or mount error when things go wrong.
1309 Note there's no need to check for errors, since if this is incorrect, we
1310 simply won't wipe userdata, which is the correct default behavior
1311 */
1312 int N = 1 << crypt_ftr->N_factor;
1313 int r = 1 << crypt_ftr->r_factor;
1314 int p = 1 << crypt_ftr->p_factor;
1315
1316 rc = crypto_scrypt(ikey, KEY_LEN_BYTES,
1317 crypt_ftr->salt, sizeof(crypt_ftr->salt), N, r, p,
1318 crypt_ftr->scrypted_intermediate_key,
1319 sizeof(crypt_ftr->scrypted_intermediate_key));
1320
1321 if (rc) {
1322 SLOGE("encrypt_master_key: crypto_scrypt failed");
1323 }
1324
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001325 return 0;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001326}
1327
JP Abgrall7bdfa522013-11-15 13:42:56 -08001328static int decrypt_master_key_aux(char *passwd, unsigned char *salt,
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001329 unsigned char *encrypted_master_key,
1330 unsigned char *decrypted_master_key,
1331 kdf_func kdf, void *kdf_params,
1332 unsigned char** intermediate_key,
1333 size_t* intermediate_key_size)
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001334{
1335 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 -08001336 EVP_CIPHER_CTX d_ctx;
1337 int decrypted_len, final_len;
1338
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001339 /* Turn the password into an intermediate key and IV that can decrypt the
1340 master key */
Paul Lawrencef4faa572014-01-29 13:31:03 -08001341 if (kdf(passwd, salt, ikey, kdf_params)) {
1342 SLOGE("kdf failed");
1343 return -1;
1344 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001345
1346 /* Initialize the decryption engine */
1347 if (! EVP_DecryptInit(&d_ctx, EVP_aes_128_cbc(), ikey, ikey+KEY_LEN_BYTES)) {
1348 return -1;
1349 }
1350 EVP_CIPHER_CTX_set_padding(&d_ctx, 0); /* Turn off padding as our data is block aligned */
1351 /* Decrypt the master key */
1352 if (! EVP_DecryptUpdate(&d_ctx, decrypted_master_key, &decrypted_len,
1353 encrypted_master_key, KEY_LEN_BYTES)) {
1354 return -1;
1355 }
1356 if (! EVP_DecryptFinal(&d_ctx, decrypted_master_key + decrypted_len, &final_len)) {
1357 return -1;
1358 }
1359
1360 if (decrypted_len + final_len != KEY_LEN_BYTES) {
1361 return -1;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001362 }
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001363
1364 /* Copy intermediate key if needed by params */
1365 if (intermediate_key && intermediate_key_size) {
1366 *intermediate_key = (unsigned char*) malloc(KEY_LEN_BYTES);
1367 if (intermediate_key) {
1368 memcpy(*intermediate_key, ikey, KEY_LEN_BYTES);
1369 *intermediate_key_size = KEY_LEN_BYTES;
1370 }
1371 }
1372
1373 return 0;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001374}
1375
Kenny Rootc4c70f12013-06-14 12:11:38 -07001376static void get_kdf_func(struct crypt_mnt_ftr *ftr, kdf_func *kdf, void** kdf_params)
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001377{
Shawn Willdene17a9c42014-09-08 13:04:08 -06001378 if (ftr->kdf_type == KDF_SCRYPT_KEYMASTER_UNPADDED ||
1379 ftr->kdf_type == KDF_SCRYPT_KEYMASTER_BADLY_PADDED ||
1380 ftr->kdf_type == KDF_SCRYPT_KEYMASTER) {
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001381 *kdf = scrypt_keymaster;
1382 *kdf_params = ftr;
1383 } else if (ftr->kdf_type == KDF_SCRYPT) {
Kenny Rootc4c70f12013-06-14 12:11:38 -07001384 *kdf = scrypt;
1385 *kdf_params = ftr;
1386 } else {
1387 *kdf = pbkdf2;
1388 *kdf_params = NULL;
1389 }
1390}
1391
JP Abgrall7bdfa522013-11-15 13:42:56 -08001392static int decrypt_master_key(char *passwd, unsigned char *decrypted_master_key,
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001393 struct crypt_mnt_ftr *crypt_ftr,
1394 unsigned char** intermediate_key,
1395 size_t* intermediate_key_size)
Kenny Rootc4c70f12013-06-14 12:11:38 -07001396{
1397 kdf_func kdf;
1398 void *kdf_params;
1399 int ret;
1400
1401 get_kdf_func(crypt_ftr, &kdf, &kdf_params);
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001402 ret = decrypt_master_key_aux(passwd, crypt_ftr->salt, crypt_ftr->master_key,
1403 decrypted_master_key, kdf, kdf_params,
1404 intermediate_key, intermediate_key_size);
Kenny Rootc4c70f12013-06-14 12:11:38 -07001405 if (ret != 0) {
1406 SLOGW("failure decrypting master key");
Kenny Rootc4c70f12013-06-14 12:11:38 -07001407 }
1408
1409 return ret;
1410}
1411
1412static int create_encrypted_random_key(char *passwd, unsigned char *master_key, unsigned char *salt,
1413 struct crypt_mnt_ftr *crypt_ftr) {
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001414 int fd;
Ken Sumralle8744072011-01-18 22:01:55 -08001415 unsigned char key_buf[KEY_LEN_BYTES];
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001416 EVP_CIPHER_CTX e_ctx;
1417 int encrypted_len, final_len;
1418
1419 /* Get some random bits for a key */
1420 fd = open("/dev/urandom", O_RDONLY);
Ken Sumralle8744072011-01-18 22:01:55 -08001421 read(fd, key_buf, sizeof(key_buf));
1422 read(fd, salt, SALT_LEN);
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001423 close(fd);
1424
1425 /* Now encrypt it with the password */
Kenny Rootc4c70f12013-06-14 12:11:38 -07001426 return encrypt_master_key(passwd, salt, key_buf, master_key, crypt_ftr);
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001427}
1428
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001429static int wait_and_unmount(char *mountpoint)
1430{
Greg Hackmann955653e2014-09-24 14:55:20 -07001431 int i, err, rc;
Ken Sumrall2eaf7132011-01-14 12:45:48 -08001432#define WAIT_UNMOUNT_COUNT 20
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001433
1434 /* Now umount the tmpfs filesystem */
1435 for (i=0; i<WAIT_UNMOUNT_COUNT; i++) {
1436 if (umount(mountpoint)) {
Ken Sumrall29d8da82011-05-18 17:20:07 -07001437 if (errno == EINVAL) {
1438 /* EINVAL is returned if the directory is not a mountpoint,
1439 * i.e. there is no filesystem mounted there. So just get out.
1440 */
1441 break;
1442 }
Greg Hackmann955653e2014-09-24 14:55:20 -07001443 err = errno;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001444 sleep(1);
1445 i++;
1446 } else {
1447 break;
1448 }
1449 }
1450
1451 if (i < WAIT_UNMOUNT_COUNT) {
1452 SLOGD("unmounting %s succeeded\n", mountpoint);
1453 rc = 0;
1454 } else {
jessica_yu3f14fe42014-09-22 15:57:40 +08001455 vold_killProcessesWithOpenFiles(mountpoint, 0);
Greg Hackmann955653e2014-09-24 14:55:20 -07001456 SLOGE("unmounting %s failed: %s\n", mountpoint, strerror(err));
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001457 rc = -1;
1458 }
1459
1460 return rc;
1461}
1462
Ken Sumrallc5872692013-05-14 15:26:31 -07001463#define DATA_PREP_TIMEOUT 200
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001464static int prep_data_fs(void)
1465{
1466 int i;
1467
1468 /* Do the prep of the /data filesystem */
1469 property_set("vold.post_fs_data_done", "0");
1470 property_set("vold.decrypt", "trigger_post_fs_data");
1471 SLOGD("Just triggered post_fs_data\n");
1472
Ken Sumrallc5872692013-05-14 15:26:31 -07001473 /* Wait a max of 50 seconds, hopefully it takes much less */
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001474 for (i=0; i<DATA_PREP_TIMEOUT; i++) {
Ken Sumrall29d8da82011-05-18 17:20:07 -07001475 char p[PROPERTY_VALUE_MAX];
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001476
1477 property_get("vold.post_fs_data_done", p, "0");
1478 if (*p == '1') {
1479 break;
1480 } else {
1481 usleep(250000);
1482 }
1483 }
1484 if (i == DATA_PREP_TIMEOUT) {
1485 /* Ugh, we failed to prep /data in time. Bail. */
Ken Sumrallc5872692013-05-14 15:26:31 -07001486 SLOGE("post_fs_data timed out!\n");
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001487 return -1;
1488 } else {
1489 SLOGD("post_fs_data done\n");
1490 return 0;
1491 }
1492}
1493
Paul Lawrence74f29f12014-08-28 15:54:10 -07001494static void cryptfs_set_corrupt()
1495{
1496 // Mark the footer as bad
1497 struct crypt_mnt_ftr crypt_ftr;
1498 if (get_crypt_ftr_and_key(&crypt_ftr)) {
1499 SLOGE("Failed to get crypto footer - panic");
1500 return;
1501 }
1502
1503 crypt_ftr.flags |= CRYPT_DATA_CORRUPT;
1504 if (put_crypt_ftr_and_key(&crypt_ftr)) {
1505 SLOGE("Failed to set crypto footer - panic");
1506 return;
1507 }
1508}
1509
1510static void cryptfs_trigger_restart_min_framework()
1511{
1512 if (fs_mgr_do_tmpfs_mount(DATA_MNT_POINT)) {
1513 SLOGE("Failed to mount tmpfs on data - panic");
1514 return;
1515 }
1516
1517 if (property_set("vold.decrypt", "trigger_post_fs_data")) {
1518 SLOGE("Failed to trigger post fs data - panic");
1519 return;
1520 }
1521
1522 if (property_set("vold.decrypt", "trigger_restart_min_framework")) {
1523 SLOGE("Failed to trigger restart min framework - panic");
1524 return;
1525 }
1526}
1527
Paul Lawrence8e3f4512014-09-08 10:11:17 -07001528/* returns < 0 on failure */
Paul Lawrencef4faa572014-01-29 13:31:03 -08001529static int cryptfs_restart_internal(int restart_main)
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001530{
1531 char fs_type[32];
1532 char real_blkdev[MAXPATHLEN];
Ken Sumrall6864b7e2011-01-14 15:20:02 -08001533 char crypto_blkdev[MAXPATHLEN];
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001534 char fs_options[256];
1535 unsigned long mnt_flags;
1536 struct stat statbuf;
1537 int rc = -1, i;
Ken Sumrall0cc16632011-01-18 20:32:26 -08001538 static int restart_successful = 0;
1539
1540 /* Validate that it's OK to call this routine */
Jason parks70a4b3f2011-01-28 10:10:47 -06001541 if (! master_key_saved) {
Ken Sumrall0cc16632011-01-18 20:32:26 -08001542 SLOGE("Encrypted filesystem not validated, aborting");
1543 return -1;
1544 }
1545
1546 if (restart_successful) {
1547 SLOGE("System already restarted with encrypted disk, aborting");
1548 return -1;
1549 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001550
Paul Lawrencef4faa572014-01-29 13:31:03 -08001551 if (restart_main) {
1552 /* Here is where we shut down the framework. The init scripts
1553 * start all services in one of three classes: core, main or late_start.
1554 * On boot, we start core and main. Now, we stop main, but not core,
1555 * as core includes vold and a few other really important things that
1556 * we need to keep running. Once main has stopped, we should be able
1557 * to umount the tmpfs /data, then mount the encrypted /data.
1558 * We then restart the class main, and also the class late_start.
1559 * At the moment, I've only put a few things in late_start that I know
1560 * are not needed to bring up the framework, and that also cause problems
1561 * with unmounting the tmpfs /data, but I hope to add add more services
1562 * to the late_start class as we optimize this to decrease the delay
1563 * till the user is asked for the password to the filesystem.
1564 */
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001565
Paul Lawrencef4faa572014-01-29 13:31:03 -08001566 /* The init files are setup to stop the class main when vold.decrypt is
1567 * set to trigger_reset_main.
1568 */
1569 property_set("vold.decrypt", "trigger_reset_main");
1570 SLOGD("Just asked init to shut down class main\n");
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001571
Paul Lawrencef4faa572014-01-29 13:31:03 -08001572 /* Ugh, shutting down the framework is not synchronous, so until it
1573 * can be fixed, this horrible hack will wait a moment for it all to
1574 * shut down before proceeding. Without it, some devices cannot
1575 * restart the graphics services.
1576 */
1577 sleep(2);
1578 }
Ken Sumrall9dedfd42012-10-09 14:16:59 -07001579
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001580 /* Now that the framework is shutdown, we should be able to umount()
1581 * the tmpfs filesystem, and mount the real one.
1582 */
1583
Ken Sumrall6864b7e2011-01-14 15:20:02 -08001584 property_get("ro.crypto.fs_crypto_blkdev", crypto_blkdev, "");
1585 if (strlen(crypto_blkdev) == 0) {
1586 SLOGE("fs_crypto_blkdev not set\n");
1587 return -1;
1588 }
1589
Ken Sumralle5032c42012-04-01 23:58:44 -07001590 if (! (rc = wait_and_unmount(DATA_MNT_POINT)) ) {
Doug Zongker6fd57712013-12-17 09:43:23 -08001591 /* If ro.crypto.readonly is set to 1, mount the decrypted
1592 * filesystem readonly. This is used when /data is mounted by
1593 * recovery mode.
1594 */
1595 char ro_prop[PROPERTY_VALUE_MAX];
1596 property_get("ro.crypto.readonly", ro_prop, "");
1597 if (strlen(ro_prop) > 0 && atoi(ro_prop)) {
1598 struct fstab_rec* rec = fs_mgr_get_entry_for_mount_point(fstab, DATA_MNT_POINT);
1599 rec->flags |= MS_RDONLY;
1600 }
JP Abgrall62c7af32014-06-16 13:01:23 -07001601
Ken Sumralle5032c42012-04-01 23:58:44 -07001602 /* If that succeeded, then mount the decrypted filesystem */
Paul Lawrence8e3f4512014-09-08 10:11:17 -07001603 int retries = RETRY_MOUNT_ATTEMPTS;
1604 int mount_rc;
1605 while ((mount_rc = fs_mgr_do_mount(fstab, DATA_MNT_POINT,
1606 crypto_blkdev, 0))
1607 != 0) {
1608 if (mount_rc == FS_MGR_DOMNT_BUSY) {
1609 /* TODO: invoke something similar to
1610 Process::killProcessWithOpenFiles(DATA_MNT_POINT,
1611 retries > RETRY_MOUNT_ATTEMPT/2 ? 1 : 2 ) */
1612 SLOGI("Failed to mount %s because it is busy - waiting",
1613 crypto_blkdev);
1614 if (--retries) {
1615 sleep(RETRY_MOUNT_DELAY_SECONDS);
1616 } else {
1617 /* Let's hope that a reboot clears away whatever is keeping
1618 the mount busy */
1619 cryptfs_reboot(reboot);
1620 }
1621 } else {
1622 SLOGE("Failed to mount decrypted data");
1623 cryptfs_set_corrupt();
1624 cryptfs_trigger_restart_min_framework();
1625 SLOGI("Started framework to offer wipe");
1626 return -1;
1627 }
Paul Lawrence74f29f12014-08-28 15:54:10 -07001628 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001629
Ken Sumralle5032c42012-04-01 23:58:44 -07001630 property_set("vold.decrypt", "trigger_load_persist_props");
1631 /* Create necessary paths on /data */
1632 if (prep_data_fs()) {
1633 return -1;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001634 }
Ken Sumralle5032c42012-04-01 23:58:44 -07001635
1636 /* startup service classes main and late_start */
1637 property_set("vold.decrypt", "trigger_restart_framework");
1638 SLOGD("Just triggered restart_framework\n");
1639
1640 /* Give it a few moments to get started */
1641 sleep(1);
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001642 }
1643
Ken Sumrall0cc16632011-01-18 20:32:26 -08001644 if (rc == 0) {
1645 restart_successful = 1;
1646 }
1647
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001648 return rc;
1649}
1650
Paul Lawrencef4faa572014-01-29 13:31:03 -08001651int cryptfs_restart(void)
1652{
1653 /* Call internal implementation forcing a restart of main service group */
1654 return cryptfs_restart_internal(1);
1655}
1656
Mark Salyzyn3e971272014-01-21 13:27:04 -08001657static int do_crypto_complete(char *mount_point UNUSED)
Ken Sumrall7f7dbaa2011-02-01 15:46:41 -08001658{
1659 struct crypt_mnt_ftr crypt_ftr;
Ken Sumrall29d8da82011-05-18 17:20:07 -07001660 char encrypted_state[PROPERTY_VALUE_MAX];
Ken Sumralle1a45852011-12-14 21:24:27 -08001661 char key_loc[PROPERTY_VALUE_MAX];
Ken Sumrall7f7dbaa2011-02-01 15:46:41 -08001662
1663 property_get("ro.crypto.state", encrypted_state, "");
1664 if (strcmp(encrypted_state, "encrypted") ) {
1665 SLOGE("not running with encryption, aborting");
Paul Lawrence74f29f12014-08-28 15:54:10 -07001666 return CRYPTO_COMPLETE_NOT_ENCRYPTED;
Ken Sumrall7f7dbaa2011-02-01 15:46:41 -08001667 }
1668
Ken Sumrall160b4d62013-04-22 12:15:39 -07001669 if (get_crypt_ftr_and_key(&crypt_ftr)) {
Ken Sumrall56ad03c2013-02-13 13:00:19 -08001670 fs_mgr_get_crypt_info(fstab, key_loc, 0, sizeof(key_loc));
Ken Sumralle5032c42012-04-01 23:58:44 -07001671
Ken Sumralle1a45852011-12-14 21:24:27 -08001672 /*
1673 * Only report this error if key_loc is a file and it exists.
1674 * If the device was never encrypted, and /data is not mountable for
1675 * some reason, returning 1 should prevent the UI from presenting the
1676 * a "enter password" screen, or worse, a "press button to wipe the
1677 * device" screen.
1678 */
1679 if ((key_loc[0] == '/') && (access("key_loc", F_OK) == -1)) {
1680 SLOGE("master key file does not exist, aborting");
Paul Lawrence74f29f12014-08-28 15:54:10 -07001681 return CRYPTO_COMPLETE_NOT_ENCRYPTED;
Ken Sumralle1a45852011-12-14 21:24:27 -08001682 } else {
1683 SLOGE("Error getting crypt footer and key\n");
Paul Lawrence74f29f12014-08-28 15:54:10 -07001684 return CRYPTO_COMPLETE_BAD_METADATA;
Ken Sumralle1a45852011-12-14 21:24:27 -08001685 }
Ken Sumrall7f7dbaa2011-02-01 15:46:41 -08001686 }
1687
Paul Lawrence74f29f12014-08-28 15:54:10 -07001688 // Test for possible error flags
1689 if (crypt_ftr.flags & CRYPT_ENCRYPTION_IN_PROGRESS){
1690 SLOGE("Encryption process is partway completed\n");
1691 return CRYPTO_COMPLETE_PARTIAL;
1692 }
1693
1694 if (crypt_ftr.flags & CRYPT_INCONSISTENT_STATE){
1695 SLOGE("Encryption process was interrupted but cannot continue\n");
1696 return CRYPTO_COMPLETE_INCONSISTENT;
1697 }
1698
1699 if (crypt_ftr.flags & CRYPT_DATA_CORRUPT){
1700 SLOGE("Encryption is successful but data is corrupt\n");
1701 return CRYPTO_COMPLETE_CORRUPT;
Ken Sumrall7f7dbaa2011-02-01 15:46:41 -08001702 }
1703
1704 /* We passed the test! We shall diminish, and return to the west */
Paul Lawrence74f29f12014-08-28 15:54:10 -07001705 return CRYPTO_COMPLETE_ENCRYPTED;
Ken Sumrall7f7dbaa2011-02-01 15:46:41 -08001706}
1707
Paul Lawrencef4faa572014-01-29 13:31:03 -08001708static int test_mount_encrypted_fs(struct crypt_mnt_ftr* crypt_ftr,
1709 char *passwd, char *mount_point, char *label)
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001710{
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001711 /* Allocate enough space for a 256 bit key, but we may use less */
Ken Sumrall160b4d62013-04-22 12:15:39 -07001712 unsigned char decrypted_master_key[32];
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001713 char crypto_blkdev[MAXPATHLEN];
1714 char real_blkdev[MAXPATHLEN];
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001715 char tmp_mount_point[64];
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001716 unsigned int orig_failed_decrypt_count;
1717 int rc;
Kenny Rootc4c70f12013-06-14 12:11:38 -07001718 kdf_func kdf;
1719 void *kdf_params;
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001720 int use_keymaster = 0;
1721 int upgrade = 0;
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001722 unsigned char* intermediate_key = 0;
1723 size_t intermediate_key_size = 0;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001724
Paul Lawrencef4faa572014-01-29 13:31:03 -08001725 SLOGD("crypt_ftr->fs_size = %lld\n", crypt_ftr->fs_size);
1726 orig_failed_decrypt_count = crypt_ftr->failed_decrypt_count;
Ken Sumrall0cc16632011-01-18 20:32:26 -08001727
Paul Lawrencef4faa572014-01-29 13:31:03 -08001728 if (! (crypt_ftr->flags & CRYPT_MNT_KEY_UNENCRYPTED) ) {
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001729 if (decrypt_master_key(passwd, decrypted_master_key, crypt_ftr,
1730 &intermediate_key, &intermediate_key_size)) {
JP Abgrall7bdfa522013-11-15 13:42:56 -08001731 SLOGE("Failed to decrypt master key\n");
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001732 rc = -1;
1733 goto errout;
JP Abgrall7bdfa522013-11-15 13:42:56 -08001734 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001735 }
1736
Paul Lawrencef4faa572014-01-29 13:31:03 -08001737 fs_mgr_get_crypt_info(fstab, 0, real_blkdev, sizeof(real_blkdev));
1738
Paul Lawrence74f29f12014-08-28 15:54:10 -07001739 // Create crypto block device - all (non fatal) code paths
1740 // need it
Paul Lawrencef4faa572014-01-29 13:31:03 -08001741 if (create_crypto_blk_dev(crypt_ftr, decrypted_master_key,
1742 real_blkdev, crypto_blkdev, label)) {
Paul Lawrence74f29f12014-08-28 15:54:10 -07001743 SLOGE("Error creating decrypted block device\n");
1744 rc = -1;
1745 goto errout;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001746 }
1747
Paul Lawrence74f29f12014-08-28 15:54:10 -07001748 /* Work out if the problem is the password or the data */
1749 unsigned char scrypted_intermediate_key[sizeof(crypt_ftr->
1750 scrypted_intermediate_key)];
1751 int N = 1 << crypt_ftr->N_factor;
1752 int r = 1 << crypt_ftr->r_factor;
1753 int p = 1 << crypt_ftr->p_factor;
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001754
Paul Lawrence74f29f12014-08-28 15:54:10 -07001755 rc = crypto_scrypt(intermediate_key, intermediate_key_size,
1756 crypt_ftr->salt, sizeof(crypt_ftr->salt),
1757 N, r, p, scrypted_intermediate_key,
1758 sizeof(scrypted_intermediate_key));
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001759
Paul Lawrence74f29f12014-08-28 15:54:10 -07001760 // Does the key match the crypto footer?
1761 if (rc == 0 && memcmp(scrypted_intermediate_key,
1762 crypt_ftr->scrypted_intermediate_key,
1763 sizeof(scrypted_intermediate_key)) == 0) {
1764 SLOGI("Password matches");
1765 rc = 0;
1766 } else {
1767 /* Try mounting the file system anyway, just in case the problem's with
1768 * the footer, not the key. */
1769 sprintf(tmp_mount_point, "%s/tmp_mnt", mount_point);
1770 mkdir(tmp_mount_point, 0755);
1771 if (fs_mgr_do_mount(fstab, DATA_MNT_POINT, crypto_blkdev, tmp_mount_point)) {
1772 SLOGE("Error temp mounting decrypted block device\n");
1773 delete_crypto_blk_dev(label);
1774
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001775 rc = ++crypt_ftr->failed_decrypt_count;
1776 put_crypt_ftr_and_key(crypt_ftr);
Paul Lawrence74f29f12014-08-28 15:54:10 -07001777 } else {
1778 /* Success! */
1779 SLOGI("Password did not match but decrypted drive mounted - continue");
1780 umount(tmp_mount_point);
1781 rc = 0;
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001782 }
Paul Lawrence74f29f12014-08-28 15:54:10 -07001783 }
1784
1785 if (rc == 0) {
1786 crypt_ftr->failed_decrypt_count = 0;
Paul Lawrence72b8b822014-10-05 12:57:37 -07001787 if (orig_failed_decrypt_count != 0) {
1788 put_crypt_ftr_and_key(crypt_ftr);
1789 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001790
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001791 /* Save the name of the crypto block device
Paul Lawrence74f29f12014-08-28 15:54:10 -07001792 * so we can mount it when restarting the framework. */
Ken Sumrall6864b7e2011-01-14 15:20:02 -08001793 property_set("ro.crypto.fs_crypto_blkdev", crypto_blkdev);
Jason parks70a4b3f2011-01-28 10:10:47 -06001794
1795 /* Also save a the master key so we can reencrypted the key
Paul Lawrence74f29f12014-08-28 15:54:10 -07001796 * the key when we want to change the password on it. */
Jason parks70a4b3f2011-01-28 10:10:47 -06001797 memcpy(saved_master_key, decrypted_master_key, KEY_LEN_BYTES);
Ken Sumrall3ad90722011-10-04 20:38:29 -07001798 saved_mount_point = strdup(mount_point);
Jason parks70a4b3f2011-01-28 10:10:47 -06001799 master_key_saved = 1;
JP Abgrall7bdfa522013-11-15 13:42:56 -08001800 SLOGD("%s(): Master key saved\n", __FUNCTION__);
Ken Sumrall6864b7e2011-01-14 15:20:02 -08001801 rc = 0;
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001802
Paul Lawrence74f29f12014-08-28 15:54:10 -07001803 // Upgrade if we're not using the latest KDF.
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001804 use_keymaster = keymaster_check_compatibility();
1805 if (crypt_ftr->kdf_type == KDF_SCRYPT_KEYMASTER) {
Shawn Willden47ba10d2014-09-03 17:07:06 -06001806 // Don't allow downgrade
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001807 } else if (use_keymaster == 1 && crypt_ftr->kdf_type != KDF_SCRYPT_KEYMASTER) {
1808 crypt_ftr->kdf_type = KDF_SCRYPT_KEYMASTER;
1809 upgrade = 1;
1810 } else if (use_keymaster == 0 && crypt_ftr->kdf_type != KDF_SCRYPT) {
Paul Lawrencef4faa572014-01-29 13:31:03 -08001811 crypt_ftr->kdf_type = KDF_SCRYPT;
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001812 upgrade = 1;
1813 }
1814
1815 if (upgrade) {
Paul Lawrencef4faa572014-01-29 13:31:03 -08001816 rc = encrypt_master_key(passwd, crypt_ftr->salt, saved_master_key,
1817 crypt_ftr->master_key, crypt_ftr);
JP Abgrall7bdfa522013-11-15 13:42:56 -08001818 if (!rc) {
Paul Lawrencef4faa572014-01-29 13:31:03 -08001819 rc = put_crypt_ftr_and_key(crypt_ftr);
JP Abgrall7bdfa522013-11-15 13:42:56 -08001820 }
1821 SLOGD("Key Derivation Function upgrade: rc=%d\n", rc);
Paul Lawrenceb2f682b2014-09-08 11:28:19 -07001822
1823 // Do not fail even if upgrade failed - machine is bootable
1824 // Note that if this code is ever hit, there is a *serious* problem
1825 // since KDFs should never fail. You *must* fix the kdf before
1826 // proceeding!
1827 if (rc) {
1828 SLOGW("Upgrade failed with error %d,"
1829 " but continuing with previous state",
1830 rc);
1831 rc = 0;
1832 }
JP Abgrall7bdfa522013-11-15 13:42:56 -08001833 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001834 }
1835
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001836 errout:
1837 if (intermediate_key) {
1838 memset(intermediate_key, 0, intermediate_key_size);
1839 free(intermediate_key);
1840 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001841 return rc;
1842}
1843
Ken Sumrall0b8b5972011-08-31 16:14:23 -07001844/* Called by vold when it wants to undo the crypto mapping of a volume it
1845 * manages. This is usually in response to a factory reset, when we want
1846 * to undo the crypto mapping so the volume is formatted in the clear.
1847 */
1848int cryptfs_revert_volume(const char *label)
1849{
1850 return delete_crypto_blk_dev((char *)label);
1851}
1852
Ken Sumrall29d8da82011-05-18 17:20:07 -07001853/*
1854 * Called by vold when it's asked to mount an encrypted, nonremovable volume.
1855 * Setup a dm-crypt mapping, use the saved master key from
1856 * setting up the /data mapping, and return the new device path.
1857 */
1858int cryptfs_setup_volume(const char *label, int major, int minor,
1859 char *crypto_sys_path, unsigned int max_path,
1860 int *new_major, int *new_minor)
1861{
1862 char real_blkdev[MAXPATHLEN], crypto_blkdev[MAXPATHLEN];
1863 struct crypt_mnt_ftr sd_crypt_ftr;
Ken Sumrall29d8da82011-05-18 17:20:07 -07001864 struct stat statbuf;
1865 int nr_sec, fd;
1866
1867 sprintf(real_blkdev, "/dev/block/vold/%d:%d", major, minor);
1868
Ken Sumrall160b4d62013-04-22 12:15:39 -07001869 get_crypt_ftr_and_key(&sd_crypt_ftr);
Ken Sumrall29d8da82011-05-18 17:20:07 -07001870
1871 /* Update the fs_size field to be the size of the volume */
1872 fd = open(real_blkdev, O_RDONLY);
1873 nr_sec = get_blkdev_size(fd);
1874 close(fd);
1875 if (nr_sec == 0) {
1876 SLOGE("Cannot get size of volume %s\n", real_blkdev);
1877 return -1;
1878 }
1879
1880 sd_crypt_ftr.fs_size = nr_sec;
1881 create_crypto_blk_dev(&sd_crypt_ftr, saved_master_key, real_blkdev,
1882 crypto_blkdev, label);
1883
1884 stat(crypto_blkdev, &statbuf);
1885 *new_major = MAJOR(statbuf.st_rdev);
1886 *new_minor = MINOR(statbuf.st_rdev);
1887
1888 /* Create path to sys entry for this block device */
1889 snprintf(crypto_sys_path, max_path, "/devices/virtual/block/%s", strrchr(crypto_blkdev, '/')+1);
1890
1891 return 0;
1892}
1893
Ken Sumrall7f7dbaa2011-02-01 15:46:41 -08001894int cryptfs_crypto_complete(void)
1895{
1896 return do_crypto_complete("/data");
1897}
1898
Paul Lawrencef4faa572014-01-29 13:31:03 -08001899int check_unmounted_and_get_ftr(struct crypt_mnt_ftr* crypt_ftr)
1900{
1901 char encrypted_state[PROPERTY_VALUE_MAX];
1902 property_get("ro.crypto.state", encrypted_state, "");
1903 if ( master_key_saved || strcmp(encrypted_state, "encrypted") ) {
1904 SLOGE("encrypted fs already validated or not running with encryption,"
1905 " aborting");
1906 return -1;
1907 }
1908
1909 if (get_crypt_ftr_and_key(crypt_ftr)) {
1910 SLOGE("Error getting crypt footer and key");
1911 return -1;
1912 }
1913
1914 return 0;
1915}
1916
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001917int cryptfs_check_passwd(char *passwd)
1918{
Paul Lawrencef4faa572014-01-29 13:31:03 -08001919 struct crypt_mnt_ftr crypt_ftr;
1920 int rc;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001921
Paul Lawrencef4faa572014-01-29 13:31:03 -08001922 rc = check_unmounted_and_get_ftr(&crypt_ftr);
1923 if (rc)
1924 return rc;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001925
Paul Lawrencef4faa572014-01-29 13:31:03 -08001926 rc = test_mount_encrypted_fs(&crypt_ftr, passwd,
1927 DATA_MNT_POINT, "userdata");
Paul Lawrence684dbdf2014-02-07 12:07:22 -08001928
1929 if (rc == 0 && crypt_ftr.crypt_type != CRYPT_TYPE_DEFAULT) {
Paul Lawrence399317e2014-03-10 13:20:50 -07001930 cryptfs_clear_password();
1931 password = strdup(passwd);
1932 struct timespec now;
1933 clock_gettime(CLOCK_BOOTTIME, &now);
1934 password_expiry_time = now.tv_sec + password_max_age_seconds;
Paul Lawrence684dbdf2014-02-07 12:07:22 -08001935 }
1936
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001937 return rc;
1938}
1939
Ken Sumrall3ad90722011-10-04 20:38:29 -07001940int cryptfs_verify_passwd(char *passwd)
1941{
1942 struct crypt_mnt_ftr crypt_ftr;
1943 /* Allocate enough space for a 256 bit key, but we may use less */
Ken Sumrall160b4d62013-04-22 12:15:39 -07001944 unsigned char decrypted_master_key[32];
Ken Sumrall3ad90722011-10-04 20:38:29 -07001945 char encrypted_state[PROPERTY_VALUE_MAX];
1946 int rc;
1947
1948 property_get("ro.crypto.state", encrypted_state, "");
1949 if (strcmp(encrypted_state, "encrypted") ) {
1950 SLOGE("device not encrypted, aborting");
1951 return -2;
1952 }
1953
1954 if (!master_key_saved) {
1955 SLOGE("encrypted fs not yet mounted, aborting");
1956 return -1;
1957 }
1958
1959 if (!saved_mount_point) {
1960 SLOGE("encrypted fs failed to save mount point, aborting");
1961 return -1;
1962 }
1963
Ken Sumrall160b4d62013-04-22 12:15:39 -07001964 if (get_crypt_ftr_and_key(&crypt_ftr)) {
Ken Sumrall3ad90722011-10-04 20:38:29 -07001965 SLOGE("Error getting crypt footer and key\n");
1966 return -1;
1967 }
1968
1969 if (crypt_ftr.flags & CRYPT_MNT_KEY_UNENCRYPTED) {
1970 /* If the device has no password, then just say the password is valid */
1971 rc = 0;
1972 } else {
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001973 decrypt_master_key(passwd, decrypted_master_key, &crypt_ftr, 0, 0);
Ken Sumrall3ad90722011-10-04 20:38:29 -07001974 if (!memcmp(decrypted_master_key, saved_master_key, crypt_ftr.keysize)) {
1975 /* They match, the password is correct */
1976 rc = 0;
1977 } else {
1978 /* If incorrect, sleep for a bit to prevent dictionary attacks */
1979 sleep(1);
1980 rc = 1;
1981 }
1982 }
1983
1984 return rc;
1985}
1986
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001987/* Initialize a crypt_mnt_ftr structure. The keysize is
1988 * defaulted to 16 bytes, and the filesystem size to 0.
1989 * Presumably, at a minimum, the caller will update the
1990 * filesystem size and crypto_type_name after calling this function.
1991 */
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001992static int cryptfs_init_crypt_mnt_ftr(struct crypt_mnt_ftr *ftr)
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001993{
Ken Sumrall160b4d62013-04-22 12:15:39 -07001994 off64_t off;
1995
1996 memset(ftr, 0, sizeof(struct crypt_mnt_ftr));
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001997 ftr->magic = CRYPT_MNT_MAGIC;
Kenny Rootc96a5f82013-06-14 12:08:28 -07001998 ftr->major_version = CURRENT_MAJOR_VERSION;
1999 ftr->minor_version = CURRENT_MINOR_VERSION;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002000 ftr->ftr_size = sizeof(struct crypt_mnt_ftr);
Jason parks70a4b3f2011-01-28 10:10:47 -06002001 ftr->keysize = KEY_LEN_BYTES;
Ken Sumrall160b4d62013-04-22 12:15:39 -07002002
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07002003 switch (keymaster_check_compatibility()) {
2004 case 1:
2005 ftr->kdf_type = KDF_SCRYPT_KEYMASTER;
2006 break;
2007
2008 case 0:
2009 ftr->kdf_type = KDF_SCRYPT;
2010 break;
2011
2012 default:
2013 SLOGE("keymaster_check_compatibility failed");
2014 return -1;
2015 }
2016
Kenny Rootc4c70f12013-06-14 12:11:38 -07002017 get_device_scrypt_params(ftr);
2018
Ken Sumrall160b4d62013-04-22 12:15:39 -07002019 ftr->persist_data_size = CRYPT_PERSIST_DATA_SIZE;
2020 if (get_crypt_ftr_info(NULL, &off) == 0) {
2021 ftr->persist_data_offset[0] = off + CRYPT_FOOTER_TO_PERSIST_OFFSET;
2022 ftr->persist_data_offset[1] = off + CRYPT_FOOTER_TO_PERSIST_OFFSET +
2023 ftr->persist_data_size;
2024 }
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07002025
2026 return 0;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002027}
2028
Ken Sumrall29d8da82011-05-18 17:20:07 -07002029static int cryptfs_enable_wipe(char *crypto_blkdev, off64_t size, int type)
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002030{
Ken Sumralle550f782013-08-20 13:48:23 -07002031 const char *args[10];
2032 char size_str[32]; /* Must be large enough to hold a %lld and null byte */
2033 int num_args;
2034 int status;
2035 int tmp;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002036 int rc = -1;
2037
Ken Sumrall29d8da82011-05-18 17:20:07 -07002038 if (type == EXT4_FS) {
Ken Sumralle550f782013-08-20 13:48:23 -07002039 args[0] = "/system/bin/make_ext4fs";
2040 args[1] = "-a";
2041 args[2] = "/data";
2042 args[3] = "-l";
Elliott Hughes73737162014-06-25 17:27:42 -07002043 snprintf(size_str, sizeof(size_str), "%" PRId64, size * 512);
Ken Sumralle550f782013-08-20 13:48:23 -07002044 args[4] = size_str;
2045 args[5] = crypto_blkdev;
2046 num_args = 6;
2047 SLOGI("Making empty filesystem with command %s %s %s %s %s %s\n",
2048 args[0], args[1], args[2], args[3], args[4], args[5]);
JP Abgrall62c7af32014-06-16 13:01:23 -07002049 } else if (type == F2FS_FS) {
2050 args[0] = "/system/bin/mkfs.f2fs";
2051 args[1] = "-t";
2052 args[2] = "-d1";
2053 args[3] = crypto_blkdev;
Elliott Hughes73737162014-06-25 17:27:42 -07002054 snprintf(size_str, sizeof(size_str), "%" PRId64, size);
JP Abgrall62c7af32014-06-16 13:01:23 -07002055 args[4] = size_str;
2056 num_args = 5;
2057 SLOGI("Making empty filesystem with command %s %s %s %s %s\n",
2058 args[0], args[1], args[2], args[3], args[4]);
Ken Sumrall29d8da82011-05-18 17:20:07 -07002059 } else {
2060 SLOGE("cryptfs_enable_wipe(): unknown filesystem type %d\n", type);
2061 return -1;
2062 }
2063
Ken Sumralle550f782013-08-20 13:48:23 -07002064 tmp = android_fork_execvp(num_args, (char **)args, &status, false, true);
2065
2066 if (tmp != 0) {
2067 SLOGE("Error creating empty filesystem on %s due to logwrap error\n", crypto_blkdev);
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002068 } else {
Ken Sumralle550f782013-08-20 13:48:23 -07002069 if (WIFEXITED(status)) {
2070 if (WEXITSTATUS(status)) {
2071 SLOGE("Error creating filesystem on %s, exit status %d ",
2072 crypto_blkdev, WEXITSTATUS(status));
2073 } else {
2074 SLOGD("Successfully created filesystem on %s\n", crypto_blkdev);
2075 rc = 0;
2076 }
2077 } else {
2078 SLOGE("Error creating filesystem on %s, did not exit normally\n", crypto_blkdev);
2079 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002080 }
2081
2082 return rc;
2083}
2084
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002085#define CRYPT_INPLACE_BUFSIZE 4096
Paul Lawrence87999172014-02-20 12:21:31 -08002086#define CRYPT_SECTORS_PER_BUFSIZE (CRYPT_INPLACE_BUFSIZE / CRYPT_SECTOR_SIZE)
2087#define CRYPT_SECTOR_SIZE 512
Paul Lawrenceae59fe62014-01-21 08:23:27 -08002088
2089/* aligned 32K writes tends to make flash happy.
2090 * SD card association recommends it.
2091 */
2092#define BLOCKS_AT_A_TIME 8
2093
2094struct encryptGroupsData
2095{
2096 int realfd;
2097 int cryptofd;
2098 off64_t numblocks;
2099 off64_t one_pct, cur_pct, new_pct;
2100 off64_t blocks_already_done, tot_numblocks;
Paul Lawrence58c58cf2014-06-04 13:12:21 -07002101 off64_t used_blocks_already_done, tot_used_blocks;
Paul Lawrenceae59fe62014-01-21 08:23:27 -08002102 char* real_blkdev, * crypto_blkdev;
2103 int count;
2104 off64_t offset;
2105 char* buffer;
Paul Lawrence87999172014-02-20 12:21:31 -08002106 off64_t last_written_sector;
2107 int completed;
Paul Lawrencea96d9c92014-06-04 14:05:01 -07002108 time_t time_started;
2109 int remaining_time;
Paul Lawrenceae59fe62014-01-21 08:23:27 -08002110};
2111
Paul Lawrence58c58cf2014-06-04 13:12:21 -07002112static void update_progress(struct encryptGroupsData* data, int is_used)
Paul Lawrenceae59fe62014-01-21 08:23:27 -08002113{
2114 data->blocks_already_done++;
Paul Lawrence58c58cf2014-06-04 13:12:21 -07002115
2116 if (is_used) {
2117 data->used_blocks_already_done++;
2118 }
Paul Lawrence58c58cf2014-06-04 13:12:21 -07002119 if (data->tot_used_blocks) {
2120 data->new_pct = data->used_blocks_already_done / data->one_pct;
2121 } else {
2122 data->new_pct = data->blocks_already_done / data->one_pct;
2123 }
2124
Paul Lawrenceae59fe62014-01-21 08:23:27 -08002125 if (data->new_pct > data->cur_pct) {
2126 char buf[8];
2127 data->cur_pct = data->new_pct;
Elliott Hughescb33f572014-06-25 18:25:11 -07002128 snprintf(buf, sizeof(buf), "%" PRId64, data->cur_pct);
Paul Lawrenceae59fe62014-01-21 08:23:27 -08002129 property_set("vold.encrypt_progress", buf);
2130 }
Paul Lawrencea96d9c92014-06-04 14:05:01 -07002131
2132 if (data->cur_pct >= 5) {
2133 double elapsed_time = difftime(time(NULL), data->time_started);
2134 off64_t remaining_blocks = data->tot_used_blocks
2135 - data->used_blocks_already_done;
2136 int remaining_time = (int)(elapsed_time * remaining_blocks
2137 / data->used_blocks_already_done);
Paul Lawrence71577502014-08-13 14:55:55 -07002138
2139 // Change time only if not yet set, lower, or a lot higher for
2140 // best user experience
Paul Lawrencea96d9c92014-06-04 14:05:01 -07002141 if (data->remaining_time == -1
Paul Lawrence71577502014-08-13 14:55:55 -07002142 || remaining_time < data->remaining_time
2143 || remaining_time > data->remaining_time + 60) {
Paul Lawrencea96d9c92014-06-04 14:05:01 -07002144 char buf[8];
2145 snprintf(buf, sizeof(buf), "%d", remaining_time);
2146 property_set("vold.encrypt_time_remaining", buf);
Paul Lawrencea96d9c92014-06-04 14:05:01 -07002147 data->remaining_time = remaining_time;
2148 }
2149 }
Paul Lawrenceae59fe62014-01-21 08:23:27 -08002150}
2151
Paul Lawrence3846be12014-09-22 11:33:54 -07002152static void log_progress(struct encryptGroupsData const* data, bool completed)
2153{
2154 // Precondition - if completed data = 0 else data != 0
2155
2156 // Track progress so we can skip logging blocks
2157 static off64_t offset = -1;
2158
2159 // Need to close existing 'Encrypting from' log?
2160 if (completed || (offset != -1 && data->offset != offset)) {
2161 SLOGI("Encrypted to sector %" PRId64,
2162 offset / info.block_size * CRYPT_SECTOR_SIZE);
2163 offset = -1;
2164 }
2165
2166 // Need to start new 'Encrypting from' log?
2167 if (!completed && offset != data->offset) {
2168 SLOGI("Encrypting from sector %" PRId64,
2169 data->offset / info.block_size * CRYPT_SECTOR_SIZE);
2170 }
2171
2172 // Update offset
2173 if (!completed) {
2174 offset = data->offset + (off64_t)data->count * info.block_size;
2175 }
2176}
2177
Paul Lawrenceae59fe62014-01-21 08:23:27 -08002178static int flush_outstanding_data(struct encryptGroupsData* data)
2179{
2180 if (data->count == 0) {
2181 return 0;
2182 }
2183
Elliott Hughes231bdba2014-06-25 18:36:19 -07002184 SLOGV("Copying %d blocks at offset %" PRIx64, data->count, data->offset);
Paul Lawrenceae59fe62014-01-21 08:23:27 -08002185
2186 if (pread64(data->realfd, data->buffer,
2187 info.block_size * data->count, data->offset)
2188 <= 0) {
2189 SLOGE("Error reading real_blkdev %s for inplace encrypt",
2190 data->real_blkdev);
2191 return -1;
2192 }
2193
2194 if (pwrite64(data->cryptofd, data->buffer,
2195 info.block_size * data->count, data->offset)
2196 <= 0) {
2197 SLOGE("Error writing crypto_blkdev %s for inplace encrypt",
2198 data->crypto_blkdev);
2199 return -1;
Paul Lawrence87999172014-02-20 12:21:31 -08002200 } else {
Paul Lawrence3846be12014-09-22 11:33:54 -07002201 log_progress(data, false);
Paul Lawrenceae59fe62014-01-21 08:23:27 -08002202 }
2203
2204 data->count = 0;
Paul Lawrence87999172014-02-20 12:21:31 -08002205 data->last_written_sector = (data->offset + data->count)
2206 / info.block_size * CRYPT_SECTOR_SIZE - 1;
Paul Lawrenceae59fe62014-01-21 08:23:27 -08002207 return 0;
2208}
2209
2210static int encrypt_groups(struct encryptGroupsData* data)
2211{
2212 unsigned int i;
2213 u8 *block_bitmap = 0;
2214 unsigned int block;
2215 off64_t ret;
2216 int rc = -1;
2217
2218 data->buffer = malloc(info.block_size * BLOCKS_AT_A_TIME);
2219 if (!data->buffer) {
2220 SLOGE("Failed to allocate crypto buffer");
2221 goto errout;
2222 }
2223
2224 block_bitmap = malloc(info.block_size);
2225 if (!block_bitmap) {
2226 SLOGE("failed to allocate block bitmap");
2227 goto errout;
2228 }
2229
2230 for (i = 0; i < aux_info.groups; ++i) {
2231 SLOGI("Encrypting group %d", i);
2232
2233 u32 first_block = aux_info.first_data_block + i * info.blocks_per_group;
2234 u32 block_count = min(info.blocks_per_group,
2235 aux_info.len_blocks - first_block);
2236
2237 off64_t offset = (u64)info.block_size
2238 * aux_info.bg_desc[i].bg_block_bitmap;
2239
2240 ret = pread64(data->realfd, block_bitmap, info.block_size, offset);
2241 if (ret != (int)info.block_size) {
2242 SLOGE("failed to read all of block group bitmap %d", i);
2243 goto errout;
2244 }
2245
2246 offset = (u64)info.block_size * first_block;
2247
2248 data->count = 0;
2249
2250 for (block = 0; block < block_count; block++) {
Paul Lawrence58c58cf2014-06-04 13:12:21 -07002251 int used = bitmap_get_bit(block_bitmap, block);
2252 update_progress(data, used);
2253 if (used) {
Paul Lawrenceae59fe62014-01-21 08:23:27 -08002254 if (data->count == 0) {
2255 data->offset = offset;
2256 }
2257 data->count++;
2258 } else {
2259 if (flush_outstanding_data(data)) {
2260 goto errout;
2261 }
2262 }
2263
2264 offset += info.block_size;
2265
2266 /* Write data if we are aligned or buffer size reached */
2267 if (offset % (info.block_size * BLOCKS_AT_A_TIME) == 0
2268 || data->count == BLOCKS_AT_A_TIME) {
2269 if (flush_outstanding_data(data)) {
2270 goto errout;
2271 }
2272 }
Paul Lawrence87999172014-02-20 12:21:31 -08002273
Paul Lawrence73d7a022014-06-09 14:10:09 -07002274 if (!is_battery_ok_to_continue()) {
Paul Lawrence87999172014-02-20 12:21:31 -08002275 SLOGE("Stopping encryption due to low battery");
2276 rc = 0;
2277 goto errout;
2278 }
2279
Paul Lawrenceae59fe62014-01-21 08:23:27 -08002280 }
2281 if (flush_outstanding_data(data)) {
2282 goto errout;
2283 }
2284 }
2285
Paul Lawrence87999172014-02-20 12:21:31 -08002286 data->completed = 1;
Paul Lawrenceae59fe62014-01-21 08:23:27 -08002287 rc = 0;
2288
2289errout:
Paul Lawrence3846be12014-09-22 11:33:54 -07002290 log_progress(0, true);
Paul Lawrenceae59fe62014-01-21 08:23:27 -08002291 free(data->buffer);
2292 free(block_bitmap);
2293 return rc;
2294}
2295
2296static int cryptfs_enable_inplace_ext4(char *crypto_blkdev,
2297 char *real_blkdev,
2298 off64_t size,
2299 off64_t *size_already_done,
Paul Lawrence87999172014-02-20 12:21:31 -08002300 off64_t tot_size,
2301 off64_t previously_encrypted_upto)
Paul Lawrenceae59fe62014-01-21 08:23:27 -08002302{
Paul Lawrence58c58cf2014-06-04 13:12:21 -07002303 u32 i;
Paul Lawrenceae59fe62014-01-21 08:23:27 -08002304 struct encryptGroupsData data;
Paul Lawrence74f29f12014-08-28 15:54:10 -07002305 int rc; // Can't initialize without causing warning -Wclobbered
Paul Lawrenceae59fe62014-01-21 08:23:27 -08002306
Paul Lawrence87999172014-02-20 12:21:31 -08002307 if (previously_encrypted_upto > *size_already_done) {
2308 SLOGD("Not fast encrypting since resuming part way through");
2309 return -1;
2310 }
2311
Paul Lawrenceae59fe62014-01-21 08:23:27 -08002312 memset(&data, 0, sizeof(data));
2313 data.real_blkdev = real_blkdev;
2314 data.crypto_blkdev = crypto_blkdev;
2315
2316 if ( (data.realfd = open(real_blkdev, O_RDWR)) < 0) {
2317 SLOGE("Error opening real_blkdev %s for inplace encrypt\n",
2318 real_blkdev);
Paul Lawrence74f29f12014-08-28 15:54:10 -07002319 rc = -1;
Paul Lawrenceae59fe62014-01-21 08:23:27 -08002320 goto errout;
2321 }
2322
2323 if ( (data.cryptofd = open(crypto_blkdev, O_WRONLY)) < 0) {
2324 SLOGE("Error opening crypto_blkdev %s for inplace encrypt\n",
2325 crypto_blkdev);
Paul Lawrence74f29f12014-08-28 15:54:10 -07002326 rc = -1;
Paul Lawrenceae59fe62014-01-21 08:23:27 -08002327 goto errout;
2328 }
2329
2330 if (setjmp(setjmp_env)) {
2331 SLOGE("Reading extent caused an exception");
Paul Lawrence74f29f12014-08-28 15:54:10 -07002332 rc = -1;
Paul Lawrenceae59fe62014-01-21 08:23:27 -08002333 goto errout;
2334 }
2335
2336 if (read_ext(data.realfd, 0) != 0) {
2337 SLOGE("Failed to read extent");
Paul Lawrence74f29f12014-08-28 15:54:10 -07002338 rc = -1;
Paul Lawrenceae59fe62014-01-21 08:23:27 -08002339 goto errout;
2340 }
2341
2342 data.numblocks = size / CRYPT_SECTORS_PER_BUFSIZE;
2343 data.tot_numblocks = tot_size / CRYPT_SECTORS_PER_BUFSIZE;
2344 data.blocks_already_done = *size_already_done / CRYPT_SECTORS_PER_BUFSIZE;
2345
2346 SLOGI("Encrypting filesystem in place...");
2347
Paul Lawrence58c58cf2014-06-04 13:12:21 -07002348 data.tot_used_blocks = data.numblocks;
2349 for (i = 0; i < aux_info.groups; ++i) {
2350 data.tot_used_blocks -= aux_info.bg_desc[i].bg_free_blocks_count;
2351 }
2352
2353 data.one_pct = data.tot_used_blocks / 100;
Paul Lawrenceae59fe62014-01-21 08:23:27 -08002354 data.cur_pct = 0;
Paul Lawrencea96d9c92014-06-04 14:05:01 -07002355 data.time_started = time(NULL);
2356 data.remaining_time = -1;
Paul Lawrenceae59fe62014-01-21 08:23:27 -08002357
2358 rc = encrypt_groups(&data);
2359 if (rc) {
2360 SLOGE("Error encrypting groups");
2361 goto errout;
2362 }
2363
Paul Lawrence87999172014-02-20 12:21:31 -08002364 *size_already_done += data.completed ? size : data.last_written_sector;
Paul Lawrenceae59fe62014-01-21 08:23:27 -08002365 rc = 0;
2366
2367errout:
2368 close(data.realfd);
2369 close(data.cryptofd);
2370
2371 return rc;
2372}
2373
Paul Lawrence3846be12014-09-22 11:33:54 -07002374static void log_progress_f2fs(u64 block, bool completed)
2375{
2376 // Precondition - if completed data = 0 else data != 0
2377
2378 // Track progress so we can skip logging blocks
2379 static u64 last_block = (u64)-1;
2380
2381 // Need to close existing 'Encrypting from' log?
2382 if (completed || (last_block != (u64)-1 && block != last_block + 1)) {
2383 SLOGI("Encrypted to block %" PRId64, last_block);
2384 last_block = -1;
2385 }
2386
2387 // Need to start new 'Encrypting from' log?
2388 if (!completed && (last_block == (u64)-1 || block != last_block + 1)) {
2389 SLOGI("Encrypting from block %" PRId64, block);
2390 }
2391
2392 // Update offset
2393 if (!completed) {
2394 last_block = block;
2395 }
2396}
2397
Daniel Rosenberge82df162014-08-15 22:19:23 +00002398static int encrypt_one_block_f2fs(u64 pos, void *data)
2399{
2400 struct encryptGroupsData *priv_dat = (struct encryptGroupsData *)data;
2401
2402 priv_dat->blocks_already_done = pos - 1;
2403 update_progress(priv_dat, 1);
2404
2405 off64_t offset = pos * CRYPT_INPLACE_BUFSIZE;
2406
2407 if (pread64(priv_dat->realfd, priv_dat->buffer, CRYPT_INPLACE_BUFSIZE, offset) <= 0) {
2408 SLOGE("Error reading real_blkdev %s for inplace encrypt", priv_dat->crypto_blkdev);
2409 return -1;
2410 }
2411
2412 if (pwrite64(priv_dat->cryptofd, priv_dat->buffer, CRYPT_INPLACE_BUFSIZE, offset) <= 0) {
2413 SLOGE("Error writing crypto_blkdev %s for inplace encrypt", priv_dat->crypto_blkdev);
2414 return -1;
2415 } else {
Paul Lawrence3846be12014-09-22 11:33:54 -07002416 log_progress_f2fs(pos, false);
Daniel Rosenberge82df162014-08-15 22:19:23 +00002417 }
2418
2419 return 0;
2420}
2421
2422static int cryptfs_enable_inplace_f2fs(char *crypto_blkdev,
2423 char *real_blkdev,
2424 off64_t size,
2425 off64_t *size_already_done,
2426 off64_t tot_size,
2427 off64_t previously_encrypted_upto)
2428{
2429 u32 i;
2430 struct encryptGroupsData data;
2431 struct f2fs_info *f2fs_info = NULL;
2432 int rc = -1;
2433 if (previously_encrypted_upto > *size_already_done) {
2434 SLOGD("Not fast encrypting since resuming part way through");
2435 return -1;
2436 }
2437 memset(&data, 0, sizeof(data));
2438 data.real_blkdev = real_blkdev;
2439 data.crypto_blkdev = crypto_blkdev;
2440 data.realfd = -1;
2441 data.cryptofd = -1;
2442 if ( (data.realfd = open64(real_blkdev, O_RDWR)) < 0) {
2443 SLOGE("Error opening real_blkdev %s for inplace encrypt\n",
2444 real_blkdev);
2445 goto errout;
2446 }
2447 if ( (data.cryptofd = open64(crypto_blkdev, O_WRONLY)) < 0) {
2448 SLOGE("Error opening crypto_blkdev %s for inplace encrypt\n",
2449 crypto_blkdev);
2450 goto errout;
2451 }
2452
2453 f2fs_info = generate_f2fs_info(data.realfd);
2454 if (!f2fs_info)
2455 goto errout;
2456
2457 data.numblocks = size / CRYPT_SECTORS_PER_BUFSIZE;
2458 data.tot_numblocks = tot_size / CRYPT_SECTORS_PER_BUFSIZE;
2459 data.blocks_already_done = *size_already_done / CRYPT_SECTORS_PER_BUFSIZE;
2460
2461 data.tot_used_blocks = get_num_blocks_used(f2fs_info);
2462
2463 data.one_pct = data.tot_used_blocks / 100;
2464 data.cur_pct = 0;
2465 data.time_started = time(NULL);
2466 data.remaining_time = -1;
2467
2468 data.buffer = malloc(f2fs_info->block_size);
2469 if (!data.buffer) {
2470 SLOGE("Failed to allocate crypto buffer");
2471 goto errout;
2472 }
2473
2474 data.count = 0;
2475
2476 /* Currently, this either runs to completion, or hits a nonrecoverable error */
2477 rc = run_on_used_blocks(data.blocks_already_done, f2fs_info, &encrypt_one_block_f2fs, &data);
2478
2479 if (rc) {
2480 SLOGE("Error in running over blocks");
2481 goto errout;
2482 }
2483
2484 *size_already_done += size;
2485 rc = 0;
2486
2487errout:
2488 if (rc)
2489 SLOGE("Failed to encrypt f2fs filesystem on %s", real_blkdev);
2490
Paul Lawrence3846be12014-09-22 11:33:54 -07002491 log_progress_f2fs(0, true);
Daniel Rosenberge82df162014-08-15 22:19:23 +00002492 free(f2fs_info);
2493 free(data.buffer);
2494 close(data.realfd);
2495 close(data.cryptofd);
2496
2497 return rc;
2498}
2499
Paul Lawrenceae59fe62014-01-21 08:23:27 -08002500static int cryptfs_enable_inplace_full(char *crypto_blkdev, char *real_blkdev,
2501 off64_t size, off64_t *size_already_done,
Paul Lawrence87999172014-02-20 12:21:31 -08002502 off64_t tot_size,
2503 off64_t previously_encrypted_upto)
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002504{
2505 int realfd, cryptofd;
2506 char *buf[CRYPT_INPLACE_BUFSIZE];
2507 int rc = -1;
2508 off64_t numblocks, i, remainder;
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002509 off64_t one_pct, cur_pct, new_pct;
Ken Sumrall29d8da82011-05-18 17:20:07 -07002510 off64_t blocks_already_done, tot_numblocks;
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002511
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002512 if ( (realfd = open(real_blkdev, O_RDONLY)) < 0) {
2513 SLOGE("Error opening real_blkdev %s for inplace encrypt\n", real_blkdev);
2514 return -1;
2515 }
2516
2517 if ( (cryptofd = open(crypto_blkdev, O_WRONLY)) < 0) {
2518 SLOGE("Error opening crypto_blkdev %s for inplace encrypt\n", crypto_blkdev);
2519 close(realfd);
2520 return -1;
2521 }
2522
2523 /* This is pretty much a simple loop of reading 4K, and writing 4K.
2524 * The size passed in is the number of 512 byte sectors in the filesystem.
2525 * So compute the number of whole 4K blocks we should read/write,
2526 * and the remainder.
2527 */
2528 numblocks = size / CRYPT_SECTORS_PER_BUFSIZE;
2529 remainder = size % CRYPT_SECTORS_PER_BUFSIZE;
Ken Sumrall29d8da82011-05-18 17:20:07 -07002530 tot_numblocks = tot_size / CRYPT_SECTORS_PER_BUFSIZE;
2531 blocks_already_done = *size_already_done / CRYPT_SECTORS_PER_BUFSIZE;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002532
2533 SLOGE("Encrypting filesystem in place...");
2534
Paul Lawrence87999172014-02-20 12:21:31 -08002535 i = previously_encrypted_upto + 1 - *size_already_done;
2536
2537 if (lseek64(realfd, i * CRYPT_SECTOR_SIZE, SEEK_SET) < 0) {
2538 SLOGE("Cannot seek to previously encrypted point on %s", real_blkdev);
2539 goto errout;
2540 }
2541
2542 if (lseek64(cryptofd, i * CRYPT_SECTOR_SIZE, SEEK_SET) < 0) {
2543 SLOGE("Cannot seek to previously encrypted point on %s", crypto_blkdev);
2544 goto errout;
2545 }
2546
2547 for (;i < size && i % CRYPT_SECTORS_PER_BUFSIZE != 0; ++i) {
2548 if (unix_read(realfd, buf, CRYPT_SECTOR_SIZE) <= 0) {
2549 SLOGE("Error reading initial sectors from real_blkdev %s for "
2550 "inplace encrypt\n", crypto_blkdev);
2551 goto errout;
2552 }
2553 if (unix_write(cryptofd, buf, CRYPT_SECTOR_SIZE) <= 0) {
2554 SLOGE("Error writing initial sectors to crypto_blkdev %s for "
2555 "inplace encrypt\n", crypto_blkdev);
2556 goto errout;
2557 } else {
Elliott Hughescb33f572014-06-25 18:25:11 -07002558 SLOGI("Encrypted 1 block at %" PRId64, i);
Paul Lawrence87999172014-02-20 12:21:31 -08002559 }
2560 }
2561
Ken Sumrall29d8da82011-05-18 17:20:07 -07002562 one_pct = tot_numblocks / 100;
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002563 cur_pct = 0;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002564 /* process the majority of the filesystem in blocks */
Paul Lawrence87999172014-02-20 12:21:31 -08002565 for (i/=CRYPT_SECTORS_PER_BUFSIZE; i<numblocks; i++) {
Ken Sumrall29d8da82011-05-18 17:20:07 -07002566 new_pct = (i + blocks_already_done) / one_pct;
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002567 if (new_pct > cur_pct) {
2568 char buf[8];
2569
2570 cur_pct = new_pct;
Elliott Hughes73737162014-06-25 17:27:42 -07002571 snprintf(buf, sizeof(buf), "%" PRId64, cur_pct);
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002572 property_set("vold.encrypt_progress", buf);
2573 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002574 if (unix_read(realfd, buf, CRYPT_INPLACE_BUFSIZE) <= 0) {
Paul Lawrence87999172014-02-20 12:21:31 -08002575 SLOGE("Error reading real_blkdev %s for inplace encrypt", crypto_blkdev);
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002576 goto errout;
2577 }
2578 if (unix_write(cryptofd, buf, CRYPT_INPLACE_BUFSIZE) <= 0) {
Paul Lawrence87999172014-02-20 12:21:31 -08002579 SLOGE("Error writing crypto_blkdev %s for inplace encrypt", crypto_blkdev);
2580 goto errout;
2581 } else {
Elliott Hughescb33f572014-06-25 18:25:11 -07002582 SLOGD("Encrypted %d block at %" PRId64,
Paul Lawrence87999172014-02-20 12:21:31 -08002583 CRYPT_SECTORS_PER_BUFSIZE,
2584 i * CRYPT_SECTORS_PER_BUFSIZE);
2585 }
2586
Paul Lawrence73d7a022014-06-09 14:10:09 -07002587 if (!is_battery_ok_to_continue()) {
Paul Lawrence87999172014-02-20 12:21:31 -08002588 SLOGE("Stopping encryption due to low battery");
2589 *size_already_done += (i + 1) * CRYPT_SECTORS_PER_BUFSIZE - 1;
2590 rc = 0;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002591 goto errout;
2592 }
2593 }
2594
2595 /* Do any remaining sectors */
2596 for (i=0; i<remainder; i++) {
Paul Lawrence87999172014-02-20 12:21:31 -08002597 if (unix_read(realfd, buf, CRYPT_SECTOR_SIZE) <= 0) {
2598 SLOGE("Error reading final sectors from real_blkdev %s for inplace encrypt", crypto_blkdev);
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002599 goto errout;
2600 }
Paul Lawrence87999172014-02-20 12:21:31 -08002601 if (unix_write(cryptofd, buf, CRYPT_SECTOR_SIZE) <= 0) {
2602 SLOGE("Error writing final sectors to crypto_blkdev %s for inplace encrypt", crypto_blkdev);
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002603 goto errout;
Paul Lawrence87999172014-02-20 12:21:31 -08002604 } else {
2605 SLOGI("Encrypted 1 block at next location");
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002606 }
2607 }
2608
Ken Sumrall29d8da82011-05-18 17:20:07 -07002609 *size_already_done += size;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002610 rc = 0;
2611
2612errout:
2613 close(realfd);
2614 close(cryptofd);
2615
2616 return rc;
2617}
2618
Paul Lawrenceae59fe62014-01-21 08:23:27 -08002619static int cryptfs_enable_inplace(char *crypto_blkdev, char *real_blkdev,
2620 off64_t size, off64_t *size_already_done,
Paul Lawrence87999172014-02-20 12:21:31 -08002621 off64_t tot_size,
2622 off64_t previously_encrypted_upto)
Paul Lawrenceae59fe62014-01-21 08:23:27 -08002623{
Paul Lawrence87999172014-02-20 12:21:31 -08002624 if (previously_encrypted_upto) {
Elliott Hughescb33f572014-06-25 18:25:11 -07002625 SLOGD("Continuing encryption from %" PRId64, previously_encrypted_upto);
Paul Lawrence87999172014-02-20 12:21:31 -08002626 }
2627
2628 if (*size_already_done + size < previously_encrypted_upto) {
2629 *size_already_done += size;
2630 return 0;
2631 }
2632
Daniel Rosenberge82df162014-08-15 22:19:23 +00002633 /* TODO: identify filesystem type.
2634 * As is, cryptfs_enable_inplace_ext4 will fail on an f2fs partition, and
2635 * then we will drop down to cryptfs_enable_inplace_f2fs.
2636 * */
Paul Lawrenceae59fe62014-01-21 08:23:27 -08002637 if (cryptfs_enable_inplace_ext4(crypto_blkdev, real_blkdev,
Daniel Rosenberge82df162014-08-15 22:19:23 +00002638 size, size_already_done,
2639 tot_size, previously_encrypted_upto) == 0) {
2640 return 0;
2641 }
2642
2643 if (cryptfs_enable_inplace_f2fs(crypto_blkdev, real_blkdev,
2644 size, size_already_done,
2645 tot_size, previously_encrypted_upto) == 0) {
2646 return 0;
Paul Lawrenceae59fe62014-01-21 08:23:27 -08002647 }
2648
2649 return cryptfs_enable_inplace_full(crypto_blkdev, real_blkdev,
Paul Lawrence87999172014-02-20 12:21:31 -08002650 size, size_already_done, tot_size,
2651 previously_encrypted_upto);
Paul Lawrenceae59fe62014-01-21 08:23:27 -08002652}
2653
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002654#define CRYPTO_ENABLE_WIPE 1
2655#define CRYPTO_ENABLE_INPLACE 2
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002656
2657#define FRAMEWORK_BOOT_WAIT 60
2658
Ken Sumrall29d8da82011-05-18 17:20:07 -07002659static inline int should_encrypt(struct volume_info *volume)
2660{
Paul Lawrenceae59fe62014-01-21 08:23:27 -08002661 return (volume->flags & (VOL_ENCRYPTABLE | VOL_NONREMOVABLE)) ==
Ken Sumrall29d8da82011-05-18 17:20:07 -07002662 (VOL_ENCRYPTABLE | VOL_NONREMOVABLE);
2663}
2664
Paul Lawrence87999172014-02-20 12:21:31 -08002665static int cryptfs_SHA256_fileblock(const char* filename, __le8* buf)
2666{
2667 int fd = open(filename, O_RDONLY);
2668 if (fd == -1) {
2669 SLOGE("Error opening file %s", filename);
2670 return -1;
2671 }
2672
2673 char block[CRYPT_INPLACE_BUFSIZE];
2674 memset(block, 0, sizeof(block));
2675 if (unix_read(fd, block, sizeof(block)) < 0) {
2676 SLOGE("Error reading file %s", filename);
2677 close(fd);
2678 return -1;
2679 }
2680
2681 close(fd);
2682
2683 SHA256_CTX c;
2684 SHA256_Init(&c);
2685 SHA256_Update(&c, block, sizeof(block));
2686 SHA256_Final(buf, &c);
2687
2688 return 0;
2689}
2690
JP Abgrall62c7af32014-06-16 13:01:23 -07002691static int get_fs_type(struct fstab_rec *rec)
2692{
2693 if (!strcmp(rec->fs_type, "ext4")) {
2694 return EXT4_FS;
2695 } else if (!strcmp(rec->fs_type, "f2fs")) {
2696 return F2FS_FS;
2697 } else {
2698 return -1;
2699 }
2700}
2701
Paul Lawrence87999172014-02-20 12:21:31 -08002702static int cryptfs_enable_all_volumes(struct crypt_mnt_ftr *crypt_ftr, int how,
2703 char *crypto_blkdev, char *real_blkdev,
2704 int previously_encrypted_upto)
2705{
2706 off64_t cur_encryption_done=0, tot_encryption_size=0;
2707 int i, rc = -1;
2708
Paul Lawrence73d7a022014-06-09 14:10:09 -07002709 if (!is_battery_ok_to_start()) {
2710 SLOGW("Not starting encryption due to low battery");
Paul Lawrence87999172014-02-20 12:21:31 -08002711 return 0;
2712 }
2713
2714 /* The size of the userdata partition, and add in the vold volumes below */
2715 tot_encryption_size = crypt_ftr->fs_size;
2716
2717 if (how == CRYPTO_ENABLE_WIPE) {
JP Abgrall62c7af32014-06-16 13:01:23 -07002718 struct fstab_rec* rec = fs_mgr_get_entry_for_mount_point(fstab, DATA_MNT_POINT);
2719 int fs_type = get_fs_type(rec);
2720 if (fs_type < 0) {
2721 SLOGE("cryptfs_enable: unsupported fs type %s\n", rec->fs_type);
2722 return -1;
2723 }
2724 rc = cryptfs_enable_wipe(crypto_blkdev, crypt_ftr->fs_size, fs_type);
Paul Lawrence87999172014-02-20 12:21:31 -08002725 } else if (how == CRYPTO_ENABLE_INPLACE) {
2726 rc = cryptfs_enable_inplace(crypto_blkdev, real_blkdev,
2727 crypt_ftr->fs_size, &cur_encryption_done,
2728 tot_encryption_size,
2729 previously_encrypted_upto);
2730
Paul Lawrence73d7a022014-06-09 14:10:09 -07002731 if (!rc) {
Paul Lawrence87999172014-02-20 12:21:31 -08002732 crypt_ftr->encrypted_upto = cur_encryption_done;
2733 }
2734
Paul Lawrence73d7a022014-06-09 14:10:09 -07002735 if (!rc && crypt_ftr->encrypted_upto == crypt_ftr->fs_size) {
Paul Lawrence87999172014-02-20 12:21:31 -08002736 /* The inplace routine never actually sets the progress to 100% due
2737 * to the round down nature of integer division, so set it here */
2738 property_set("vold.encrypt_progress", "100");
2739 }
2740 } else {
2741 /* Shouldn't happen */
2742 SLOGE("cryptfs_enable: internal error, unknown option\n");
2743 rc = -1;
2744 }
2745
2746 return rc;
2747}
2748
Paul Lawrence13486032014-02-03 13:28:11 -08002749int cryptfs_enable_internal(char *howarg, int crypt_type, char *passwd,
2750 int allow_reboot)
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002751{
2752 int how = 0;
Paul Lawrence87999172014-02-20 12:21:31 -08002753 char crypto_blkdev[MAXPATHLEN], real_blkdev[MAXPATHLEN];
Ken Sumralle5032c42012-04-01 23:58:44 -07002754 unsigned long nr_sec;
Ken Sumrall160b4d62013-04-22 12:15:39 -07002755 unsigned char decrypted_master_key[KEY_LEN_BYTES];
Ken Sumrall319b1042011-06-14 14:01:55 -07002756 int rc=-1, fd, i, ret;
Paul Lawrence87999172014-02-20 12:21:31 -08002757 struct crypt_mnt_ftr crypt_ftr;
Ken Sumrall160b4d62013-04-22 12:15:39 -07002758 struct crypt_persist_data *pdata;
Ken Sumrall29d8da82011-05-18 17:20:07 -07002759 char encrypted_state[PROPERTY_VALUE_MAX];
Ken Sumrall5d4c68e2011-01-30 19:06:03 -08002760 char lockid[32] = { 0 };
Ken Sumrall29d8da82011-05-18 17:20:07 -07002761 char key_loc[PROPERTY_VALUE_MAX];
2762 char fuse_sdcard[PROPERTY_VALUE_MAX];
2763 char *sd_mnt_point;
Ken Sumrall29d8da82011-05-18 17:20:07 -07002764 int num_vols;
2765 struct volume_info *vol_list = 0;
Paul Lawrence87999172014-02-20 12:21:31 -08002766 off64_t previously_encrypted_upto = 0;
Ken Sumrall29d8da82011-05-18 17:20:07 -07002767
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002768 if (!strcmp(howarg, "wipe")) {
2769 how = CRYPTO_ENABLE_WIPE;
2770 } else if (! strcmp(howarg, "inplace")) {
2771 how = CRYPTO_ENABLE_INPLACE;
2772 } else {
2773 /* Shouldn't happen, as CommandListener vets the args */
Ken Sumrall3ed82362011-01-28 23:31:16 -08002774 goto error_unencrypted;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002775 }
2776
Paul Lawrence87999172014-02-20 12:21:31 -08002777 /* See if an encryption was underway and interrupted */
2778 if (how == CRYPTO_ENABLE_INPLACE
2779 && get_crypt_ftr_and_key(&crypt_ftr) == 0
2780 && (crypt_ftr.flags & CRYPT_ENCRYPTION_IN_PROGRESS)) {
2781 previously_encrypted_upto = crypt_ftr.encrypted_upto;
2782 crypt_ftr.encrypted_upto = 0;
Paul Lawrence6bfed202014-07-28 12:47:22 -07002783 crypt_ftr.flags &= ~CRYPT_ENCRYPTION_IN_PROGRESS;
2784
2785 /* At this point, we are in an inconsistent state. Until we successfully
2786 complete encryption, a reboot will leave us broken. So mark the
2787 encryption failed in case that happens.
2788 On successfully completing encryption, remove this flag */
2789 crypt_ftr.flags |= CRYPT_INCONSISTENT_STATE;
2790
2791 put_crypt_ftr_and_key(&crypt_ftr);
Paul Lawrence87999172014-02-20 12:21:31 -08002792 }
2793
2794 property_get("ro.crypto.state", encrypted_state, "");
2795 if (!strcmp(encrypted_state, "encrypted") && !previously_encrypted_upto) {
2796 SLOGE("Device is already running encrypted, aborting");
2797 goto error_unencrypted;
2798 }
2799
2800 // TODO refactor fs_mgr_get_crypt_info to get both in one call
2801 fs_mgr_get_crypt_info(fstab, key_loc, 0, sizeof(key_loc));
Ken Sumrall56ad03c2013-02-13 13:00:19 -08002802 fs_mgr_get_crypt_info(fstab, 0, real_blkdev, sizeof(real_blkdev));
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002803
Ken Sumrall3ed82362011-01-28 23:31:16 -08002804 /* Get the size of the real block device */
2805 fd = open(real_blkdev, O_RDONLY);
2806 if ( (nr_sec = get_blkdev_size(fd)) == 0) {
2807 SLOGE("Cannot get size of block device %s\n", real_blkdev);
2808 goto error_unencrypted;
2809 }
2810 close(fd);
2811
2812 /* If doing inplace encryption, make sure the orig fs doesn't include the crypto footer */
Ken Sumrall29d8da82011-05-18 17:20:07 -07002813 if ((how == CRYPTO_ENABLE_INPLACE) && (!strcmp(key_loc, KEY_IN_FOOTER))) {
Ken Sumrall3ed82362011-01-28 23:31:16 -08002814 unsigned int fs_size_sec, max_fs_size_sec;
Jim Millera70abc62014-08-15 02:00:45 +00002815 fs_size_sec = get_fs_size(real_blkdev);
Daniel Rosenberge82df162014-08-15 22:19:23 +00002816 if (fs_size_sec == 0)
2817 fs_size_sec = get_f2fs_filesystem_size_sec(real_blkdev);
2818
Paul Lawrence87999172014-02-20 12:21:31 -08002819 max_fs_size_sec = nr_sec - (CRYPT_FOOTER_OFFSET / CRYPT_SECTOR_SIZE);
Ken Sumrall3ed82362011-01-28 23:31:16 -08002820
2821 if (fs_size_sec > max_fs_size_sec) {
2822 SLOGE("Orig filesystem overlaps crypto footer region. Cannot encrypt in place.");
2823 goto error_unencrypted;
2824 }
2825 }
2826
Ken Sumrall5d4c68e2011-01-30 19:06:03 -08002827 /* Get a wakelock as this may take a while, and we don't want the
2828 * device to sleep on us. We'll grab a partial wakelock, and if the UI
2829 * wants to keep the screen on, it can grab a full wakelock.
2830 */
Ken Sumrall29d8da82011-05-18 17:20:07 -07002831 snprintf(lockid, sizeof(lockid), "enablecrypto%d", (int) getpid());
Ken Sumrall5d4c68e2011-01-30 19:06:03 -08002832 acquire_wake_lock(PARTIAL_WAKE_LOCK, lockid);
2833
Jeff Sharkey7382f812012-08-23 14:08:59 -07002834 /* Get the sdcard mount point */
Jeff Sharkeyb77bc462012-10-01 14:36:26 -07002835 sd_mnt_point = getenv("EMULATED_STORAGE_SOURCE");
Jeff Sharkey7382f812012-08-23 14:08:59 -07002836 if (!sd_mnt_point) {
2837 sd_mnt_point = getenv("EXTERNAL_STORAGE");
2838 }
2839 if (!sd_mnt_point) {
2840 sd_mnt_point = "/mnt/sdcard";
2841 }
Ken Sumrall29d8da82011-05-18 17:20:07 -07002842
Paul Lawrence87999172014-02-20 12:21:31 -08002843 /* TODO
2844 * Currently do not have test devices with multiple encryptable volumes.
2845 * When we acquire some, re-add support.
2846 */
Ken Sumrall29d8da82011-05-18 17:20:07 -07002847 num_vols=vold_getNumDirectVolumes();
2848 vol_list = malloc(sizeof(struct volume_info) * num_vols);
2849 vold_getDirectVolumeList(vol_list);
2850
2851 for (i=0; i<num_vols; i++) {
2852 if (should_encrypt(&vol_list[i])) {
Paul Lawrence87999172014-02-20 12:21:31 -08002853 SLOGE("Cannot encrypt if there are multiple encryptable volumes"
2854 "%s\n", vol_list[i].label);
2855 goto error_unencrypted;
Ken Sumrall29d8da82011-05-18 17:20:07 -07002856 }
2857 }
2858
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002859 /* The init files are setup to stop the class main and late start when
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002860 * vold sets trigger_shutdown_framework.
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002861 */
2862 property_set("vold.decrypt", "trigger_shutdown_framework");
2863 SLOGD("Just asked init to shut down class main\n");
2864
Ken Sumrall425524d2012-06-14 20:55:28 -07002865 if (vold_unmountAllAsecs()) {
2866 /* Just report the error. If any are left mounted,
2867 * umounting /data below will fail and handle the error.
2868 */
2869 SLOGE("Error unmounting internal asecs");
2870 }
2871
Ken Sumrall29d8da82011-05-18 17:20:07 -07002872 property_get("ro.crypto.fuse_sdcard", fuse_sdcard, "");
2873 if (!strcmp(fuse_sdcard, "true")) {
2874 /* This is a device using the fuse layer to emulate the sdcard semantics
2875 * on top of the userdata partition. vold does not manage it, it is managed
2876 * by the sdcard service. The sdcard service was killed by the property trigger
2877 * above, so just unmount it now. We must do this _AFTER_ killing the framework,
2878 * unlike the case for vold managed devices above.
2879 */
2880 if (wait_and_unmount(sd_mnt_point)) {
2881 goto error_shutting_down;
2882 }
Ken Sumrall2eaf7132011-01-14 12:45:48 -08002883 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002884
2885 /* Now unmount the /data partition. */
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002886 if (wait_and_unmount(DATA_MNT_POINT)) {
JP Abgrall502dc742013-11-01 13:06:20 -07002887 if (allow_reboot) {
2888 goto error_shutting_down;
2889 } else {
2890 goto error_unencrypted;
2891 }
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002892 }
2893
2894 /* Do extra work for a better UX when doing the long inplace encryption */
2895 if (how == CRYPTO_ENABLE_INPLACE) {
2896 /* Now that /data is unmounted, we need to mount a tmpfs
2897 * /data, set a property saying we're doing inplace encryption,
2898 * and restart the framework.
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002899 */
Ken Sumralle5032c42012-04-01 23:58:44 -07002900 if (fs_mgr_do_tmpfs_mount(DATA_MNT_POINT)) {
Ken Sumrall3ed82362011-01-28 23:31:16 -08002901 goto error_shutting_down;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002902 }
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002903 /* Tells the framework that inplace encryption is starting */
Ken Sumrall7df84122011-01-18 14:04:08 -08002904 property_set("vold.encrypt_progress", "0");
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002905
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002906 /* restart the framework. */
2907 /* Create necessary paths on /data */
2908 if (prep_data_fs()) {
Ken Sumrall3ed82362011-01-28 23:31:16 -08002909 goto error_shutting_down;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002910 }
2911
Ken Sumrall92736ef2012-10-17 20:57:14 -07002912 /* Ugh, shutting down the framework is not synchronous, so until it
2913 * can be fixed, this horrible hack will wait a moment for it all to
2914 * shut down before proceeding. Without it, some devices cannot
2915 * restart the graphics services.
2916 */
2917 sleep(2);
2918
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002919 /* startup service classes main and late_start */
2920 property_set("vold.decrypt", "trigger_restart_min_framework");
2921 SLOGD("Just triggered restart_min_framework\n");
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002922
Ken Sumrall7df84122011-01-18 14:04:08 -08002923 /* OK, the framework is restarted and will soon be showing a
2924 * progress bar. Time to setup an encrypted mapping, and
2925 * either write a new filesystem, or encrypt in place updating
2926 * the progress bar as we work.
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002927 */
2928 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002929
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002930 /* Start the actual work of making an encrypted filesystem */
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002931 /* Initialize a crypt_mnt_ftr for the partition */
Paul Lawrence87999172014-02-20 12:21:31 -08002932 if (previously_encrypted_upto == 0) {
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07002933 if (cryptfs_init_crypt_mnt_ftr(&crypt_ftr)) {
2934 goto error_shutting_down;
2935 }
Ken Sumrall160b4d62013-04-22 12:15:39 -07002936
Paul Lawrence87999172014-02-20 12:21:31 -08002937 if (!strcmp(key_loc, KEY_IN_FOOTER)) {
2938 crypt_ftr.fs_size = nr_sec
2939 - (CRYPT_FOOTER_OFFSET / CRYPT_SECTOR_SIZE);
2940 } else {
2941 crypt_ftr.fs_size = nr_sec;
2942 }
Paul Lawrence6bfed202014-07-28 12:47:22 -07002943 /* At this point, we are in an inconsistent state. Until we successfully
2944 complete encryption, a reboot will leave us broken. So mark the
2945 encryption failed in case that happens.
2946 On successfully completing encryption, remove this flag */
2947 crypt_ftr.flags |= CRYPT_INCONSISTENT_STATE;
Paul Lawrence87999172014-02-20 12:21:31 -08002948 crypt_ftr.crypt_type = crypt_type;
2949 strcpy((char *)crypt_ftr.crypto_type_name, "aes-cbc-essiv:sha256");
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002950
Paul Lawrence87999172014-02-20 12:21:31 -08002951 /* Make an encrypted master key */
2952 if (create_encrypted_random_key(passwd, crypt_ftr.master_key, crypt_ftr.salt, &crypt_ftr)) {
2953 SLOGE("Cannot create encrypted master key\n");
2954 goto error_shutting_down;
2955 }
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002956
Paul Lawrence87999172014-02-20 12:21:31 -08002957 /* Write the key to the end of the partition */
2958 put_crypt_ftr_and_key(&crypt_ftr);
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002959
Paul Lawrence87999172014-02-20 12:21:31 -08002960 /* If any persistent data has been remembered, save it.
2961 * If none, create a valid empty table and save that.
2962 */
2963 if (!persist_data) {
2964 pdata = malloc(CRYPT_PERSIST_DATA_SIZE);
2965 if (pdata) {
2966 init_empty_persist_data(pdata, CRYPT_PERSIST_DATA_SIZE);
2967 persist_data = pdata;
2968 }
2969 }
2970 if (persist_data) {
2971 save_persistent_data();
2972 }
Ken Sumrall160b4d62013-04-22 12:15:39 -07002973 }
2974
Paul Lawrenced0c7b172014-08-08 14:28:10 -07002975 decrypt_master_key(passwd, decrypted_master_key, &crypt_ftr, 0, 0);
Ken Sumrall29d8da82011-05-18 17:20:07 -07002976 create_crypto_blk_dev(&crypt_ftr, decrypted_master_key, real_blkdev, crypto_blkdev,
2977 "userdata");
2978
Paul Lawrence87999172014-02-20 12:21:31 -08002979 /* If we are continuing, check checksums match */
2980 rc = 0;
2981 if (previously_encrypted_upto) {
2982 __le8 hash_first_block[SHA256_DIGEST_LENGTH];
2983 rc = cryptfs_SHA256_fileblock(crypto_blkdev, hash_first_block);
Ken Sumrall128626f2011-06-28 18:45:14 -07002984
Paul Lawrence87999172014-02-20 12:21:31 -08002985 if (!rc && memcmp(hash_first_block, crypt_ftr.hash_first_block,
2986 sizeof(hash_first_block)) != 0) {
2987 SLOGE("Checksums do not match - trigger wipe");
2988 rc = -1;
Ken Sumrall29d8da82011-05-18 17:20:07 -07002989 }
2990 }
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002991
Paul Lawrence87999172014-02-20 12:21:31 -08002992 if (!rc) {
2993 rc = cryptfs_enable_all_volumes(&crypt_ftr, how,
2994 crypto_blkdev, real_blkdev,
2995 previously_encrypted_upto);
2996 }
2997
2998 /* Calculate checksum if we are not finished */
Paul Lawrence73d7a022014-06-09 14:10:09 -07002999 if (!rc && crypt_ftr.encrypted_upto != crypt_ftr.fs_size) {
Paul Lawrence87999172014-02-20 12:21:31 -08003000 rc = cryptfs_SHA256_fileblock(crypto_blkdev,
3001 crypt_ftr.hash_first_block);
Paul Lawrence73d7a022014-06-09 14:10:09 -07003002 if (rc) {
Paul Lawrence87999172014-02-20 12:21:31 -08003003 SLOGE("Error calculating checksum for continuing encryption");
3004 rc = -1;
Ken Sumrall29d8da82011-05-18 17:20:07 -07003005 }
Ken Sumrall8ddbe402011-01-17 15:26:29 -08003006 }
3007
3008 /* Undo the dm-crypt mapping whether we succeed or not */
Ken Sumrall29d8da82011-05-18 17:20:07 -07003009 delete_crypto_blk_dev("userdata");
Ken Sumrall29d8da82011-05-18 17:20:07 -07003010
3011 free(vol_list);
Ken Sumrall8ddbe402011-01-17 15:26:29 -08003012
3013 if (! rc) {
3014 /* Success */
Paul Lawrence6bfed202014-07-28 12:47:22 -07003015 crypt_ftr.flags &= ~CRYPT_INCONSISTENT_STATE;
Ken Sumrall7f7dbaa2011-02-01 15:46:41 -08003016
Paul Lawrence6bfed202014-07-28 12:47:22 -07003017 if (crypt_ftr.encrypted_upto != crypt_ftr.fs_size) {
Paul Lawrence87999172014-02-20 12:21:31 -08003018 SLOGD("Encrypted up to sector %lld - will continue after reboot",
3019 crypt_ftr.encrypted_upto);
Paul Lawrence6bfed202014-07-28 12:47:22 -07003020 crypt_ftr.flags |= CRYPT_ENCRYPTION_IN_PROGRESS;
Paul Lawrence87999172014-02-20 12:21:31 -08003021 }
Paul Lawrence73d7a022014-06-09 14:10:09 -07003022
Paul Lawrence6bfed202014-07-28 12:47:22 -07003023 put_crypt_ftr_and_key(&crypt_ftr);
Ken Sumralld33d4172011-02-01 00:49:13 -08003024
Paul Lawrence73d7a022014-06-09 14:10:09 -07003025 if (crypt_ftr.encrypted_upto == crypt_ftr.fs_size) {
Paul Lawrenceb6672e12014-08-15 07:37:28 -07003026 char value[PROPERTY_VALUE_MAX];
3027 property_get("ro.crypto.state", value, "");
3028 if (!strcmp(value, "")) {
3029 /* default encryption - continue first boot sequence */
3030 property_set("ro.crypto.state", "encrypted");
3031 release_wake_lock(lockid);
3032 cryptfs_check_passwd(DEFAULT_PASSWORD);
3033 cryptfs_restart_internal(1);
3034 return 0;
3035 } else {
3036 sleep(2); /* Give the UI a chance to show 100% progress */
Paul Lawrence87999172014-02-20 12:21:31 -08003037 cryptfs_reboot(reboot);
Paul Lawrenceb6672e12014-08-15 07:37:28 -07003038 }
Paul Lawrence87999172014-02-20 12:21:31 -08003039 } else {
Paul Lawrenceb6672e12014-08-15 07:37:28 -07003040 sleep(2); /* Partially encrypted, ensure writes flushed to ssd */
Paul Lawrence87999172014-02-20 12:21:31 -08003041 cryptfs_reboot(shutdown);
3042 }
Ken Sumrall3ed82362011-01-28 23:31:16 -08003043 } else {
Mike Lockwoodee6d8c42012-02-15 13:43:28 -08003044 char value[PROPERTY_VALUE_MAX];
3045
Ken Sumrall319369a2012-06-27 16:30:18 -07003046 property_get("ro.vold.wipe_on_crypt_fail", value, "0");
Mike Lockwoodee6d8c42012-02-15 13:43:28 -08003047 if (!strcmp(value, "1")) {
3048 /* wipe data if encryption failed */
3049 SLOGE("encryption failed - rebooting into recovery to wipe data\n");
3050 mkdir("/cache/recovery", 0700);
Nick Kralevich4684e582012-06-26 15:07:03 -07003051 int fd = open("/cache/recovery/command", O_RDWR|O_CREAT|O_TRUNC, 0600);
Mike Lockwoodee6d8c42012-02-15 13:43:28 -08003052 if (fd >= 0) {
Jeff Sharkeydd1a8042014-09-24 11:46:51 -07003053 write(fd, "--wipe_data\n", strlen("--wipe_data\n") + 1);
3054 write(fd, "--reason=cryptfs_enable_internal\n", strlen("--reason=cryptfs_enable_internal\n") + 1);
Mike Lockwoodee6d8c42012-02-15 13:43:28 -08003055 close(fd);
3056 } else {
3057 SLOGE("could not open /cache/recovery/command\n");
3058 }
Paul Lawrence87999172014-02-20 12:21:31 -08003059 cryptfs_reboot(recovery);
Mike Lockwoodee6d8c42012-02-15 13:43:28 -08003060 } else {
3061 /* set property to trigger dialog */
3062 property_set("vold.encrypt_progress", "error_partially_encrypted");
3063 release_wake_lock(lockid);
3064 }
Ken Sumrall3ed82362011-01-28 23:31:16 -08003065 return -1;
Ken Sumrall8ddbe402011-01-17 15:26:29 -08003066 }
3067
Ken Sumrall3ed82362011-01-28 23:31:16 -08003068 /* hrm, the encrypt step claims success, but the reboot failed.
3069 * This should not happen.
3070 * Set the property and return. Hope the framework can deal with it.
3071 */
3072 property_set("vold.encrypt_progress", "error_reboot_failed");
Ken Sumrall5d4c68e2011-01-30 19:06:03 -08003073 release_wake_lock(lockid);
Ken Sumrall8ddbe402011-01-17 15:26:29 -08003074 return rc;
Ken Sumrall3ed82362011-01-28 23:31:16 -08003075
3076error_unencrypted:
Ken Sumrall29d8da82011-05-18 17:20:07 -07003077 free(vol_list);
Ken Sumrall3ed82362011-01-28 23:31:16 -08003078 property_set("vold.encrypt_progress", "error_not_encrypted");
Ken Sumrall5d4c68e2011-01-30 19:06:03 -08003079 if (lockid[0]) {
3080 release_wake_lock(lockid);
3081 }
Ken Sumrall3ed82362011-01-28 23:31:16 -08003082 return -1;
3083
3084error_shutting_down:
3085 /* we failed, and have not encrypted anthing, so the users's data is still intact,
3086 * but the framework is stopped and not restarted to show the error, so it's up to
3087 * vold to restart the system.
3088 */
3089 SLOGE("Error enabling encryption after framework is shutdown, no data changed, restarting system");
Paul Lawrence87999172014-02-20 12:21:31 -08003090 cryptfs_reboot(reboot);
Ken Sumrall3ed82362011-01-28 23:31:16 -08003091
3092 /* shouldn't get here */
3093 property_set("vold.encrypt_progress", "error_shutting_down");
Ken Sumrall29d8da82011-05-18 17:20:07 -07003094 free(vol_list);
Ken Sumrall5d4c68e2011-01-30 19:06:03 -08003095 if (lockid[0]) {
3096 release_wake_lock(lockid);
3097 }
Ken Sumrall3ed82362011-01-28 23:31:16 -08003098 return -1;
Ken Sumrall8ddbe402011-01-17 15:26:29 -08003099}
3100
Paul Lawrence45f10532014-04-04 18:11:56 +00003101int cryptfs_enable(char *howarg, int type, char *passwd, int allow_reboot)
Paul Lawrence13486032014-02-03 13:28:11 -08003102{
Paul Lawrence45f10532014-04-04 18:11:56 +00003103 return cryptfs_enable_internal(howarg, type, passwd, allow_reboot);
Paul Lawrence13486032014-02-03 13:28:11 -08003104}
3105
3106int cryptfs_enable_default(char *howarg, int allow_reboot)
3107{
3108 return cryptfs_enable_internal(howarg, CRYPT_TYPE_DEFAULT,
3109 DEFAULT_PASSWORD, allow_reboot);
3110}
3111
3112int cryptfs_changepw(int crypt_type, const char *newpw)
Ken Sumrall8ddbe402011-01-17 15:26:29 -08003113{
3114 struct crypt_mnt_ftr crypt_ftr;
Ken Sumrall160b4d62013-04-22 12:15:39 -07003115 unsigned char decrypted_master_key[KEY_LEN_BYTES];
Ken Sumrall8ddbe402011-01-17 15:26:29 -08003116
3117 /* This is only allowed after we've successfully decrypted the master key */
Paul Lawrencef4faa572014-01-29 13:31:03 -08003118 if (!master_key_saved) {
Ken Sumrall0cc16632011-01-18 20:32:26 -08003119 SLOGE("Key not saved, aborting");
Ken Sumrall8ddbe402011-01-17 15:26:29 -08003120 return -1;
3121 }
3122
Paul Lawrencef4faa572014-01-29 13:31:03 -08003123 if (crypt_type < 0 || crypt_type > CRYPT_TYPE_MAX_TYPE) {
3124 SLOGE("Invalid crypt_type %d", crypt_type);
3125 return -1;
3126 }
3127
Ken Sumrall8ddbe402011-01-17 15:26:29 -08003128 /* get key */
Ken Sumrall160b4d62013-04-22 12:15:39 -07003129 if (get_crypt_ftr_and_key(&crypt_ftr)) {
Paul Lawrencef4faa572014-01-29 13:31:03 -08003130 SLOGE("Error getting crypt footer and key");
3131 return -1;
Ken Sumrall8ddbe402011-01-17 15:26:29 -08003132 }
3133
Paul Lawrencef4faa572014-01-29 13:31:03 -08003134 crypt_ftr.crypt_type = crypt_type;
3135
3136 encrypt_master_key(crypt_type == CRYPT_TYPE_DEFAULT ? DEFAULT_PASSWORD
3137 : newpw,
3138 crypt_ftr.salt,
3139 saved_master_key,
3140 crypt_ftr.master_key,
3141 &crypt_ftr);
Ken Sumrall8ddbe402011-01-17 15:26:29 -08003142
Jason parks70a4b3f2011-01-28 10:10:47 -06003143 /* save the key */
Ken Sumrall160b4d62013-04-22 12:15:39 -07003144 put_crypt_ftr_and_key(&crypt_ftr);
Ken Sumrall8f869aa2010-12-03 03:47:09 -08003145
3146 return 0;
3147}
Ken Sumrall160b4d62013-04-22 12:15:39 -07003148
3149static int persist_get_key(char *fieldname, char *value)
3150{
3151 unsigned int i;
3152
3153 if (persist_data == NULL) {
3154 return -1;
3155 }
3156 for (i = 0; i < persist_data->persist_valid_entries; i++) {
3157 if (!strncmp(persist_data->persist_entry[i].key, fieldname, PROPERTY_KEY_MAX)) {
3158 /* We found it! */
3159 strlcpy(value, persist_data->persist_entry[i].val, PROPERTY_VALUE_MAX);
3160 return 0;
3161 }
3162 }
3163
3164 return -1;
3165}
3166
3167static int persist_set_key(char *fieldname, char *value, int encrypted)
3168{
3169 unsigned int i;
3170 unsigned int num;
3171 struct crypt_mnt_ftr crypt_ftr;
3172 unsigned int max_persistent_entries;
3173 unsigned int dsize;
3174
3175 if (persist_data == NULL) {
3176 return -1;
3177 }
3178
3179 /* If encrypted, use the values from the crypt_ftr, otherwise
3180 * use the values for the current spec.
3181 */
3182 if (encrypted) {
3183 if(get_crypt_ftr_and_key(&crypt_ftr)) {
3184 return -1;
3185 }
3186 dsize = crypt_ftr.persist_data_size;
3187 } else {
3188 dsize = CRYPT_PERSIST_DATA_SIZE;
3189 }
3190 max_persistent_entries = (dsize - sizeof(struct crypt_persist_data)) /
3191 sizeof(struct crypt_persist_entry);
3192
3193 num = persist_data->persist_valid_entries;
3194
3195 for (i = 0; i < num; i++) {
3196 if (!strncmp(persist_data->persist_entry[i].key, fieldname, PROPERTY_KEY_MAX)) {
3197 /* We found an existing entry, update it! */
3198 memset(persist_data->persist_entry[i].val, 0, PROPERTY_VALUE_MAX);
3199 strlcpy(persist_data->persist_entry[i].val, value, PROPERTY_VALUE_MAX);
3200 return 0;
3201 }
3202 }
3203
3204 /* We didn't find it, add it to the end, if there is room */
3205 if (persist_data->persist_valid_entries < max_persistent_entries) {
3206 memset(&persist_data->persist_entry[num], 0, sizeof(struct crypt_persist_entry));
3207 strlcpy(persist_data->persist_entry[num].key, fieldname, PROPERTY_KEY_MAX);
3208 strlcpy(persist_data->persist_entry[num].val, value, PROPERTY_VALUE_MAX);
3209 persist_data->persist_valid_entries++;
3210 return 0;
3211 }
3212
3213 return -1;
3214}
3215
3216/* Return the value of the specified field. */
3217int cryptfs_getfield(char *fieldname, char *value, int len)
3218{
3219 char temp_value[PROPERTY_VALUE_MAX];
3220 char real_blkdev[MAXPATHLEN];
3221 /* 0 is success, 1 is not encrypted,
3222 * -1 is value not set, -2 is any other error
3223 */
3224 int rc = -2;
3225
3226 if (persist_data == NULL) {
3227 load_persistent_data();
3228 if (persist_data == NULL) {
3229 SLOGE("Getfield error, cannot load persistent data");
3230 goto out;
3231 }
3232 }
3233
3234 if (!persist_get_key(fieldname, temp_value)) {
3235 /* We found it, copy it to the caller's buffer and return */
3236 strlcpy(value, temp_value, len);
3237 rc = 0;
3238 } else {
3239 /* Sadness, it's not there. Return the error */
3240 rc = -1;
3241 }
3242
3243out:
3244 return rc;
3245}
3246
3247/* Set the value of the specified field. */
3248int cryptfs_setfield(char *fieldname, char *value)
3249{
3250 struct crypt_persist_data stored_pdata;
3251 struct crypt_persist_data *pdata_p;
3252 struct crypt_mnt_ftr crypt_ftr;
3253 char encrypted_state[PROPERTY_VALUE_MAX];
3254 /* 0 is success, -1 is an error */
3255 int rc = -1;
3256 int encrypted = 0;
3257
3258 if (persist_data == NULL) {
3259 load_persistent_data();
3260 if (persist_data == NULL) {
3261 SLOGE("Setfield error, cannot load persistent data");
3262 goto out;
3263 }
3264 }
3265
3266 property_get("ro.crypto.state", encrypted_state, "");
3267 if (!strcmp(encrypted_state, "encrypted") ) {
3268 encrypted = 1;
3269 }
3270
3271 if (persist_set_key(fieldname, value, encrypted)) {
3272 goto out;
3273 }
3274
3275 /* If we are running encrypted, save the persistent data now */
3276 if (encrypted) {
3277 if (save_persistent_data()) {
3278 SLOGE("Setfield error, cannot save persistent data");
3279 goto out;
3280 }
3281 }
3282
3283 rc = 0;
3284
3285out:
3286 return rc;
3287}
Paul Lawrencef4faa572014-01-29 13:31:03 -08003288
3289/* Checks userdata. Attempt to mount the volume if default-
3290 * encrypted.
3291 * On success trigger next init phase and return 0.
3292 * Currently do not handle failure - see TODO below.
3293 */
3294int cryptfs_mount_default_encrypted(void)
3295{
3296 char decrypt_state[PROPERTY_VALUE_MAX];
3297 property_get("vold.decrypt", decrypt_state, "0");
3298 if (!strcmp(decrypt_state, "0")) {
3299 SLOGE("Not encrypted - should not call here");
3300 } else {
3301 int crypt_type = cryptfs_get_password_type();
3302 if (crypt_type < 0 || crypt_type > CRYPT_TYPE_MAX_TYPE) {
3303 SLOGE("Bad crypt type - error");
3304 } else if (crypt_type != CRYPT_TYPE_DEFAULT) {
3305 SLOGD("Password is not default - "
3306 "starting min framework to prompt");
3307 property_set("vold.decrypt", "trigger_restart_min_framework");
3308 return 0;
3309 } else if (cryptfs_check_passwd(DEFAULT_PASSWORD) == 0) {
3310 SLOGD("Password is default - restarting filesystem");
3311 cryptfs_restart_internal(0);
3312 return 0;
3313 } else {
3314 SLOGE("Encrypted, default crypt type but can't decrypt");
3315 }
3316 }
3317
Paul Lawrence6bfed202014-07-28 12:47:22 -07003318 /** Corrupt. Allow us to boot into framework, which will detect bad
3319 crypto when it calls do_crypto_complete, then do a factory reset
Paul Lawrencef4faa572014-01-29 13:31:03 -08003320 */
Paul Lawrence6bfed202014-07-28 12:47:22 -07003321 property_set("vold.decrypt", "trigger_restart_min_framework");
Paul Lawrencef4faa572014-01-29 13:31:03 -08003322 return 0;
3323}
3324
3325/* Returns type of the password, default, pattern, pin or password.
3326 */
3327int cryptfs_get_password_type(void)
3328{
3329 struct crypt_mnt_ftr crypt_ftr;
3330
3331 if (get_crypt_ftr_and_key(&crypt_ftr)) {
3332 SLOGE("Error getting crypt footer and key\n");
3333 return -1;
3334 }
3335
Paul Lawrence6bfed202014-07-28 12:47:22 -07003336 if (crypt_ftr.flags & CRYPT_INCONSISTENT_STATE) {
3337 return -1;
3338 }
3339
Paul Lawrencef4faa572014-01-29 13:31:03 -08003340 return crypt_ftr.crypt_type;
3341}
Paul Lawrence684dbdf2014-02-07 12:07:22 -08003342
Paul Lawrence399317e2014-03-10 13:20:50 -07003343char* cryptfs_get_password()
Paul Lawrence684dbdf2014-02-07 12:07:22 -08003344{
Paul Lawrence399317e2014-03-10 13:20:50 -07003345 struct timespec now;
3346 clock_gettime(CLOCK_MONOTONIC, &now);
3347 if (now.tv_sec < password_expiry_time) {
3348 return password;
3349 } else {
3350 cryptfs_clear_password();
3351 return 0;
3352 }
3353}
3354
3355void cryptfs_clear_password()
3356{
3357 if (password) {
3358 size_t len = strlen(password);
3359 memset(password, 0, len);
3360 free(password);
3361 password = 0;
3362 password_expiry_time = 0;
3363 }
Paul Lawrence684dbdf2014-02-07 12:07:22 -08003364}