blob: 534f0c0f633c6668e26b0bf579caaea2d1bd1a6f [file] [log] [blame]
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001/*
2 * Copyright (C) 2010 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17/* TO DO:
18 * 1. Perhaps keep several copies of the encrypted key, in case something
19 * goes horribly wrong?
20 *
21 */
22
23#include <sys/types.h>
Ken Sumralle550f782013-08-20 13:48:23 -070024#include <sys/wait.h>
Ken Sumrall8f869aa2010-12-03 03:47:09 -080025#include <sys/stat.h>
Paul Lawrencef4faa572014-01-29 13:31:03 -080026#include <ctype.h>
Ken Sumrall8f869aa2010-12-03 03:47:09 -080027#include <fcntl.h>
Elliott Hughes73737162014-06-25 17:27:42 -070028#include <inttypes.h>
Ken Sumrall8f869aa2010-12-03 03:47:09 -080029#include <unistd.h>
30#include <stdio.h>
31#include <sys/ioctl.h>
32#include <linux/dm-ioctl.h>
33#include <libgen.h>
34#include <stdlib.h>
35#include <sys/param.h>
36#include <string.h>
37#include <sys/mount.h>
38#include <openssl/evp.h>
39#include <errno.h>
Ken Sumrall3ed82362011-01-28 23:31:16 -080040#include <ext4.h>
Ken Sumrall29d8da82011-05-18 17:20:07 -070041#include <linux/kdev_t.h>
Ken Sumralle5032c42012-04-01 23:58:44 -070042#include <fs_mgr.h>
Paul Lawrence9c58a872014-09-30 09:12:51 -070043#include <time.h>
Ken Sumrall8f869aa2010-12-03 03:47:09 -080044#include "cryptfs.h"
45#define LOG_TAG "Cryptfs"
46#include "cutils/log.h"
47#include "cutils/properties.h"
Ken Sumralladfba362013-06-04 16:37:52 -070048#include "cutils/android_reboot.h"
Ken Sumrall5d4c68e2011-01-30 19:06:03 -080049#include "hardware_legacy/power.h"
Ken Sumralle550f782013-08-20 13:48:23 -070050#include <logwrap/logwrap.h>
Ken Sumrall29d8da82011-05-18 17:20:07 -070051#include "VolumeManager.h"
Ken Sumrall9caab762013-06-11 19:10:20 -070052#include "VoldUtil.h"
Kenny Rootc4c70f12013-06-14 12:11:38 -070053#include "crypto_scrypt.h"
Paul Lawrenceae59fe62014-01-21 08:23:27 -080054#include "ext4_utils.h"
Daniel Rosenberge82df162014-08-15 22:19:23 +000055#include "f2fs_sparseblock.h"
Paul Lawrence87999172014-02-20 12:21:31 -080056#include "CheckBattery.h"
jessica_yu3f14fe42014-09-22 15:57:40 +080057#include "Process.h"
Ken Sumrall8f869aa2010-12-03 03:47:09 -080058
Paul Lawrence69f4ebd2014-04-14 12:17:14 -070059#include <hardware/keymaster.h>
60
Mark Salyzyn3e971272014-01-21 13:27:04 -080061#define UNUSED __attribute__((unused))
62
Mark Salyzyn5eecc442014-02-12 14:16:14 -080063#define UNUSED __attribute__((unused))
64
Ken Sumrall8f869aa2010-12-03 03:47:09 -080065#define DM_CRYPT_BUF_SIZE 4096
66
Jason parks70a4b3f2011-01-28 10:10:47 -060067#define HASH_COUNT 2000
68#define KEY_LEN_BYTES 16
69#define IV_LEN_BYTES 16
70
Ken Sumrall29d8da82011-05-18 17:20:07 -070071#define KEY_IN_FOOTER "footer"
72
Paul Lawrencef4faa572014-01-29 13:31:03 -080073// "default_password" encoded into hex (d=0x64 etc)
74#define DEFAULT_PASSWORD "64656661756c745f70617373776f7264"
75
Ken Sumrall29d8da82011-05-18 17:20:07 -070076#define EXT4_FS 1
JP Abgrall62c7af32014-06-16 13:01:23 -070077#define F2FS_FS 2
Ken Sumrall29d8da82011-05-18 17:20:07 -070078
Ken Sumralle919efe2012-09-29 17:07:41 -070079#define TABLE_LOAD_RETRIES 10
80
Shawn Willden47ba10d2014-09-03 17:07:06 -060081#define RSA_KEY_SIZE 2048
82#define RSA_KEY_SIZE_BYTES (RSA_KEY_SIZE / 8)
83#define RSA_EXPONENT 0x10001
Paul Lawrence69f4ebd2014-04-14 12:17:14 -070084
Paul Lawrence8e3f4512014-09-08 10:11:17 -070085#define RETRY_MOUNT_ATTEMPTS 10
86#define RETRY_MOUNT_DELAY_SECONDS 1
87
Ken Sumrall8f869aa2010-12-03 03:47:09 -080088char *me = "cryptfs";
89
Jason parks70a4b3f2011-01-28 10:10:47 -060090static unsigned char saved_master_key[KEY_LEN_BYTES];
Ken Sumrall3ad90722011-10-04 20:38:29 -070091static char *saved_mount_point;
Jason parks70a4b3f2011-01-28 10:10:47 -060092static int master_key_saved = 0;
Ken Sumrall160b4d62013-04-22 12:15:39 -070093static struct crypt_persist_data *persist_data = NULL;
Ken Sumrall56ad03c2013-02-13 13:00:19 -080094
Paul Lawrence69f4ebd2014-04-14 12:17:14 -070095static int keymaster_init(keymaster_device_t **keymaster_dev)
96{
97 int rc;
98
99 const hw_module_t* mod;
100 rc = hw_get_module_by_class(KEYSTORE_HARDWARE_MODULE_ID, NULL, &mod);
101 if (rc) {
102 ALOGE("could not find any keystore module");
103 goto out;
104 }
105
106 rc = keymaster_open(mod, keymaster_dev);
107 if (rc) {
108 ALOGE("could not open keymaster device in %s (%s)",
109 KEYSTORE_HARDWARE_MODULE_ID, strerror(-rc));
110 goto out;
111 }
112
113 return 0;
114
115out:
116 *keymaster_dev = NULL;
117 return rc;
118}
119
120/* Should we use keymaster? */
121static int keymaster_check_compatibility()
122{
123 keymaster_device_t *keymaster_dev = 0;
124 int rc = 0;
125
126 if (keymaster_init(&keymaster_dev)) {
127 SLOGE("Failed to init keymaster");
128 rc = -1;
129 goto out;
130 }
131
Paul Lawrence8c008392014-05-06 14:02:48 -0700132 SLOGI("keymaster version is %d", keymaster_dev->common.module->module_api_version);
133
134 if (keymaster_dev->common.module->module_api_version
135 < KEYMASTER_MODULE_API_VERSION_0_3) {
136 rc = 0;
137 goto out;
138 }
139
Paul Lawrence69f4ebd2014-04-14 12:17:14 -0700140 if (keymaster_dev->flags & KEYMASTER_BLOBS_ARE_STANDALONE) {
141 rc = 1;
142 }
143
144out:
145 keymaster_close(keymaster_dev);
146 return rc;
147}
148
149/* Create a new keymaster key and store it in this footer */
150static int keymaster_create_key(struct crypt_mnt_ftr *ftr)
151{
152 uint8_t* key = 0;
153 keymaster_device_t *keymaster_dev = 0;
154
155 if (keymaster_init(&keymaster_dev)) {
156 SLOGE("Failed to init keymaster");
157 return -1;
158 }
159
160 int rc = 0;
161
162 keymaster_rsa_keygen_params_t params;
163 memset(&params, '\0', sizeof(params));
Shawn Willden47ba10d2014-09-03 17:07:06 -0600164 params.public_exponent = RSA_EXPONENT;
165 params.modulus_size = RSA_KEY_SIZE;
Paul Lawrence69f4ebd2014-04-14 12:17:14 -0700166
167 size_t key_size;
168 if (keymaster_dev->generate_keypair(keymaster_dev, TYPE_RSA, &params,
169 &key, &key_size)) {
170 SLOGE("Failed to generate keypair");
171 rc = -1;
172 goto out;
173 }
174
175 if (key_size > KEYMASTER_BLOB_SIZE) {
176 SLOGE("Keymaster key too large for crypto footer");
177 rc = -1;
178 goto out;
179 }
180
181 memcpy(ftr->keymaster_blob, key, key_size);
182 ftr->keymaster_blob_size = key_size;
183
184out:
185 keymaster_close(keymaster_dev);
186 free(key);
187 return rc;
188}
189
Shawn Willdene17a9c42014-09-08 13:04:08 -0600190/* This signs the given object using the keymaster key. */
191static int keymaster_sign_object(struct crypt_mnt_ftr *ftr,
Shawn Willden47ba10d2014-09-03 17:07:06 -0600192 const unsigned char *object,
193 const size_t object_size,
194 unsigned char **signature,
195 size_t *signature_size)
196{
197 int rc = 0;
198 keymaster_device_t *keymaster_dev = 0;
199 if (keymaster_init(&keymaster_dev)) {
200 SLOGE("Failed to init keymaster");
201 return -1;
202 }
203
204 /* We currently set the digest type to DIGEST_NONE because it's the
205 * only supported value for keymaster. A similar issue exists with
206 * PADDING_NONE. Long term both of these should likely change.
207 */
208 keymaster_rsa_sign_params_t params;
209 params.digest_type = DIGEST_NONE;
210 params.padding_type = PADDING_NONE;
211
212 unsigned char to_sign[RSA_KEY_SIZE_BYTES];
Shawn Willdene17a9c42014-09-08 13:04:08 -0600213 size_t to_sign_size = sizeof(to_sign);
Shawn Willden47ba10d2014-09-03 17:07:06 -0600214 memset(to_sign, 0, RSA_KEY_SIZE_BYTES);
Shawn Willden47ba10d2014-09-03 17:07:06 -0600215
Shawn Willdene17a9c42014-09-08 13:04:08 -0600216 // To sign a message with RSA, the message must satisfy two
217 // constraints:
218 //
219 // 1. The message, when interpreted as a big-endian numeric value, must
220 // be strictly less than the public modulus of the RSA key. Note
221 // that because the most significant bit of the public modulus is
222 // guaranteed to be 1 (else it's an (n-1)-bit key, not an n-bit
223 // key), an n-bit message with most significant bit 0 always
224 // satisfies this requirement.
225 //
226 // 2. The message must have the same length in bits as the public
227 // modulus of the RSA key. This requirement isn't mathematically
228 // necessary, but is necessary to ensure consistency in
229 // implementations.
230 switch (ftr->kdf_type) {
231 case KDF_SCRYPT_KEYMASTER_UNPADDED:
232 // This is broken: It produces a message which is shorter than
233 // the public modulus, failing criterion 2.
234 memcpy(to_sign, object, object_size);
235 to_sign_size = object_size;
236 SLOGI("Signing unpadded object");
237 break;
238 case KDF_SCRYPT_KEYMASTER_BADLY_PADDED:
239 // This is broken: Since the value of object is uniformly
240 // distributed, it produces a message that is larger than the
241 // public modulus with probability 0.25.
242 memcpy(to_sign, object, min(RSA_KEY_SIZE_BYTES, object_size));
243 SLOGI("Signing end-padded object");
244 break;
245 case KDF_SCRYPT_KEYMASTER:
246 // This ensures the most significant byte of the signed message
247 // is zero. We could have zero-padded to the left instead, but
248 // this approach is slightly more robust against changes in
249 // object size. However, it's still broken (but not unusably
250 // so) because we really should be using a proper RSA padding
251 // function, such as OAEP.
252 //
253 // TODO(paullawrence): When keymaster 0.4 is available, change
254 // this to use the padding options it provides.
255 memcpy(to_sign + 1, object, min(RSA_KEY_SIZE_BYTES - 1, object_size));
256 SLOGI("Signing safely-padded object");
257 break;
258 default:
259 SLOGE("Unknown KDF type %d", ftr->kdf_type);
260 return -1;
261 }
262
Shawn Willden47ba10d2014-09-03 17:07:06 -0600263 rc = keymaster_dev->sign_data(keymaster_dev,
264 &params,
265 ftr->keymaster_blob,
266 ftr->keymaster_blob_size,
267 to_sign,
Shawn Willdene17a9c42014-09-08 13:04:08 -0600268 to_sign_size,
Shawn Willden47ba10d2014-09-03 17:07:06 -0600269 signature,
270 signature_size);
271
272 keymaster_close(keymaster_dev);
273 return rc;
274}
275
Paul Lawrence399317e2014-03-10 13:20:50 -0700276/* Store password when userdata is successfully decrypted and mounted.
277 * Cleared by cryptfs_clear_password
278 *
279 * To avoid a double prompt at boot, we need to store the CryptKeeper
280 * password and pass it to KeyGuard, which uses it to unlock KeyStore.
281 * Since the entire framework is torn down and rebuilt after encryption,
282 * we have to use a daemon or similar to store the password. Since vold
283 * is secured against IPC except from system processes, it seems a reasonable
284 * place to store this.
285 *
286 * password should be cleared once it has been used.
287 *
288 * password is aged out after password_max_age_seconds seconds.
Paul Lawrence684dbdf2014-02-07 12:07:22 -0800289 */
Paul Lawrence399317e2014-03-10 13:20:50 -0700290static char* password = 0;
291static int password_expiry_time = 0;
292static const int password_max_age_seconds = 60;
Paul Lawrence684dbdf2014-02-07 12:07:22 -0800293
Ken Sumrall56ad03c2013-02-13 13:00:19 -0800294extern struct fstab *fstab;
Ken Sumrall8ddbe402011-01-17 15:26:29 -0800295
Paul Lawrence87999172014-02-20 12:21:31 -0800296enum RebootType {reboot, recovery, shutdown};
297static void cryptfs_reboot(enum RebootType rt)
Ken Sumralladfba362013-06-04 16:37:52 -0700298{
Paul Lawrence87999172014-02-20 12:21:31 -0800299 switch(rt) {
300 case reboot:
301 property_set(ANDROID_RB_PROPERTY, "reboot");
302 break;
303
304 case recovery:
305 property_set(ANDROID_RB_PROPERTY, "reboot,recovery");
306 break;
307
308 case shutdown:
309 property_set(ANDROID_RB_PROPERTY, "shutdown");
310 break;
Ken Sumralladfba362013-06-04 16:37:52 -0700311 }
Paul Lawrence87999172014-02-20 12:21:31 -0800312
Ken Sumralladfba362013-06-04 16:37:52 -0700313 sleep(20);
314
315 /* Shouldn't get here, reboot should happen before sleep times out */
316 return;
317}
318
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800319static void ioctl_init(struct dm_ioctl *io, size_t dataSize, const char *name, unsigned flags)
320{
321 memset(io, 0, dataSize);
322 io->data_size = dataSize;
323 io->data_start = sizeof(struct dm_ioctl);
324 io->version[0] = 4;
325 io->version[1] = 0;
326 io->version[2] = 0;
327 io->flags = flags;
328 if (name) {
329 strncpy(io->name, name, sizeof(io->name));
330 }
331}
332
Kenny Rootc4c70f12013-06-14 12:11:38 -0700333/**
334 * Gets the default device scrypt parameters for key derivation time tuning.
335 * The parameters should lead to about one second derivation time for the
336 * given device.
337 */
338static void get_device_scrypt_params(struct crypt_mnt_ftr *ftr) {
339 const int default_params[] = SCRYPT_DEFAULTS;
340 int params[] = SCRYPT_DEFAULTS;
341 char paramstr[PROPERTY_VALUE_MAX];
342 char *token;
343 char *saveptr;
344 int i;
345
346 property_get(SCRYPT_PROP, paramstr, "");
347 if (paramstr[0] != '\0') {
348 /*
349 * The token we're looking for should be three integers separated by
350 * colons (e.g., "12:8:1"). Scan the property to make sure it matches.
351 */
Kenny Root2947e342013-08-14 15:54:49 -0700352 for (i = 0, token = strtok_r(paramstr, ":", &saveptr);
353 token != NULL && i < 3;
Kenny Rootc4c70f12013-06-14 12:11:38 -0700354 i++, token = strtok_r(NULL, ":", &saveptr)) {
355 char *endptr;
356 params[i] = strtol(token, &endptr, 10);
357
358 /*
359 * Check that there was a valid number and it's 8-bit. If not,
360 * break out and the end check will take the default values.
361 */
362 if ((*token == '\0') || (*endptr != '\0') || params[i] < 0 || params[i] > 255) {
363 break;
364 }
365 }
366
367 /*
368 * If there were not enough tokens or a token was malformed (not an
369 * integer), it will end up here and the default parameters can be
370 * taken.
371 */
372 if ((i != 3) || (token != NULL)) {
373 SLOGW("bad scrypt parameters '%s' should be like '12:8:1'; using defaults", paramstr);
374 memcpy(params, default_params, sizeof(params));
375 }
376 }
377
378 ftr->N_factor = params[0];
379 ftr->r_factor = params[1];
380 ftr->p_factor = params[2];
381}
382
Ken Sumrall3ed82362011-01-28 23:31:16 -0800383static unsigned int get_fs_size(char *dev)
384{
385 int fd, block_size;
386 struct ext4_super_block sb;
387 off64_t len;
388
389 if ((fd = open(dev, O_RDONLY)) < 0) {
390 SLOGE("Cannot open device to get filesystem size ");
391 return 0;
392 }
393
394 if (lseek64(fd, 1024, SEEK_SET) < 0) {
395 SLOGE("Cannot seek to superblock");
396 return 0;
397 }
398
399 if (read(fd, &sb, sizeof(sb)) != sizeof(sb)) {
400 SLOGE("Cannot read superblock");
401 return 0;
402 }
403
404 close(fd);
405
Daniel Rosenberge82df162014-08-15 22:19:23 +0000406 if (le32_to_cpu(sb.s_magic) != EXT4_SUPER_MAGIC) {
407 SLOGE("Not a valid ext4 superblock");
408 return 0;
409 }
Ken Sumrall3ed82362011-01-28 23:31:16 -0800410 block_size = 1024 << sb.s_log_block_size;
411 /* compute length in bytes */
412 len = ( ((off64_t)sb.s_blocks_count_hi << 32) + sb.s_blocks_count_lo) * block_size;
413
414 /* return length in sectors */
415 return (unsigned int) (len / 512);
416}
417
Ken Sumrall160b4d62013-04-22 12:15:39 -0700418static int get_crypt_ftr_info(char **metadata_fname, off64_t *off)
419{
420 static int cached_data = 0;
421 static off64_t cached_off = 0;
422 static char cached_metadata_fname[PROPERTY_VALUE_MAX] = "";
423 int fd;
424 char key_loc[PROPERTY_VALUE_MAX];
425 char real_blkdev[PROPERTY_VALUE_MAX];
426 unsigned int nr_sec;
427 int rc = -1;
428
429 if (!cached_data) {
430 fs_mgr_get_crypt_info(fstab, key_loc, real_blkdev, sizeof(key_loc));
431
432 if (!strcmp(key_loc, KEY_IN_FOOTER)) {
433 if ( (fd = open(real_blkdev, O_RDWR)) < 0) {
434 SLOGE("Cannot open real block device %s\n", real_blkdev);
435 return -1;
436 }
437
438 if ((nr_sec = get_blkdev_size(fd))) {
439 /* If it's an encrypted Android partition, the last 16 Kbytes contain the
440 * encryption info footer and key, and plenty of bytes to spare for future
441 * growth.
442 */
443 strlcpy(cached_metadata_fname, real_blkdev, sizeof(cached_metadata_fname));
444 cached_off = ((off64_t)nr_sec * 512) - CRYPT_FOOTER_OFFSET;
445 cached_data = 1;
446 } else {
447 SLOGE("Cannot get size of block device %s\n", real_blkdev);
448 }
449 close(fd);
450 } else {
451 strlcpy(cached_metadata_fname, key_loc, sizeof(cached_metadata_fname));
452 cached_off = 0;
453 cached_data = 1;
454 }
455 }
456
457 if (cached_data) {
458 if (metadata_fname) {
459 *metadata_fname = cached_metadata_fname;
460 }
461 if (off) {
462 *off = cached_off;
463 }
464 rc = 0;
465 }
466
467 return rc;
468}
469
Ken Sumralle8744072011-01-18 22:01:55 -0800470/* key or salt can be NULL, in which case just skip writing that value. Useful to
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800471 * update the failed mount count but not change the key.
472 */
Ken Sumrall160b4d62013-04-22 12:15:39 -0700473static int put_crypt_ftr_and_key(struct crypt_mnt_ftr *crypt_ftr)
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800474{
475 int fd;
Tim Murray8439dc92014-12-15 11:56:11 -0800476 unsigned int cnt;
Ken Sumrall160b4d62013-04-22 12:15:39 -0700477 /* starting_off is set to the SEEK_SET offset
478 * where the crypto structure starts
479 */
480 off64_t starting_off;
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800481 int rc = -1;
Ken Sumrall160b4d62013-04-22 12:15:39 -0700482 char *fname = NULL;
Ken Sumrall3be890f2011-09-14 16:53:46 -0700483 struct stat statbuf;
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800484
Ken Sumrall160b4d62013-04-22 12:15:39 -0700485 if (get_crypt_ftr_info(&fname, &starting_off)) {
486 SLOGE("Unable to get crypt_ftr_info\n");
487 return -1;
488 }
489 if (fname[0] != '/') {
Ken Sumralle5032c42012-04-01 23:58:44 -0700490 SLOGE("Unexpected value for crypto key location\n");
Ken Sumrall160b4d62013-04-22 12:15:39 -0700491 return -1;
492 }
Ken Sumralle550f782013-08-20 13:48:23 -0700493 if ( (fd = open(fname, O_RDWR | O_CREAT, 0600)) < 0) {
494 SLOGE("Cannot open footer file %s for put\n", fname);
Ken Sumrall160b4d62013-04-22 12:15:39 -0700495 return -1;
496 }
497
498 /* Seek to the start of the crypt footer */
499 if (lseek64(fd, starting_off, SEEK_SET) == -1) {
500 SLOGE("Cannot seek to real block device footer\n");
501 goto errout;
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800502 }
503
504 if ((cnt = write(fd, crypt_ftr, sizeof(struct crypt_mnt_ftr))) != sizeof(struct crypt_mnt_ftr)) {
505 SLOGE("Cannot write real block device footer\n");
506 goto errout;
507 }
508
Ken Sumrall3be890f2011-09-14 16:53:46 -0700509 fstat(fd, &statbuf);
510 /* If the keys are kept on a raw block device, do not try to truncate it. */
Ken Sumralle550f782013-08-20 13:48:23 -0700511 if (S_ISREG(statbuf.st_mode)) {
Ken Sumrall29d8da82011-05-18 17:20:07 -0700512 if (ftruncate(fd, 0x4000)) {
Colin Cross59846b62014-02-06 20:34:29 -0800513 SLOGE("Cannot set footer file size\n");
Ken Sumralle8744072011-01-18 22:01:55 -0800514 goto errout;
515 }
516 }
517
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800518 /* Success! */
519 rc = 0;
520
521errout:
522 close(fd);
523 return rc;
524
525}
526
Ken Sumrall160b4d62013-04-22 12:15:39 -0700527static inline int unix_read(int fd, void* buff, int len)
528{
529 return TEMP_FAILURE_RETRY(read(fd, buff, len));
530}
531
532static inline int unix_write(int fd, const void* buff, int len)
533{
534 return TEMP_FAILURE_RETRY(write(fd, buff, len));
535}
536
537static void init_empty_persist_data(struct crypt_persist_data *pdata, int len)
538{
539 memset(pdata, 0, len);
540 pdata->persist_magic = PERSIST_DATA_MAGIC;
541 pdata->persist_valid_entries = 0;
542}
543
544/* A routine to update the passed in crypt_ftr to the lastest version.
545 * fd is open read/write on the device that holds the crypto footer and persistent
546 * data, crypt_ftr is a pointer to the struct to be updated, and offset is the
547 * absolute offset to the start of the crypt_mnt_ftr on the passed in fd.
548 */
549static void upgrade_crypt_ftr(int fd, struct crypt_mnt_ftr *crypt_ftr, off64_t offset)
550{
Kenny Root7434b312013-06-14 11:29:53 -0700551 int orig_major = crypt_ftr->major_version;
552 int orig_minor = crypt_ftr->minor_version;
Ken Sumrall160b4d62013-04-22 12:15:39 -0700553
Kenny Root7434b312013-06-14 11:29:53 -0700554 if ((crypt_ftr->major_version == 1) && (crypt_ftr->minor_version == 0)) {
555 struct crypt_persist_data *pdata;
556 off64_t pdata_offset = offset + CRYPT_FOOTER_TO_PERSIST_OFFSET;
Ken Sumrall160b4d62013-04-22 12:15:39 -0700557
Kenny Rootc4c70f12013-06-14 12:11:38 -0700558 SLOGW("upgrading crypto footer to 1.1");
559
Kenny Root7434b312013-06-14 11:29:53 -0700560 pdata = malloc(CRYPT_PERSIST_DATA_SIZE);
561 if (pdata == NULL) {
562 SLOGE("Cannot allocate persisent data\n");
563 return;
564 }
565 memset(pdata, 0, CRYPT_PERSIST_DATA_SIZE);
566
567 /* Need to initialize the persistent data area */
568 if (lseek64(fd, pdata_offset, SEEK_SET) == -1) {
569 SLOGE("Cannot seek to persisent data offset\n");
Henrik Baard91064632015-02-05 15:09:17 +0100570 free(pdata);
Kenny Root7434b312013-06-14 11:29:53 -0700571 return;
572 }
573 /* Write all zeros to the first copy, making it invalid */
574 unix_write(fd, pdata, CRYPT_PERSIST_DATA_SIZE);
575
576 /* Write a valid but empty structure to the second copy */
577 init_empty_persist_data(pdata, CRYPT_PERSIST_DATA_SIZE);
578 unix_write(fd, pdata, CRYPT_PERSIST_DATA_SIZE);
579
580 /* Update the footer */
581 crypt_ftr->persist_data_size = CRYPT_PERSIST_DATA_SIZE;
582 crypt_ftr->persist_data_offset[0] = pdata_offset;
583 crypt_ftr->persist_data_offset[1] = pdata_offset + CRYPT_PERSIST_DATA_SIZE;
584 crypt_ftr->minor_version = 1;
Henrik Baard91064632015-02-05 15:09:17 +0100585 free(pdata);
Ken Sumrall160b4d62013-04-22 12:15:39 -0700586 }
587
Paul Lawrencef4faa572014-01-29 13:31:03 -0800588 if ((crypt_ftr->major_version == 1) && (crypt_ftr->minor_version == 1)) {
Kenny Rootc4c70f12013-06-14 12:11:38 -0700589 SLOGW("upgrading crypto footer to 1.2");
JP Abgrall7bdfa522013-11-15 13:42:56 -0800590 /* But keep the old kdf_type.
591 * It will get updated later to KDF_SCRYPT after the password has been verified.
592 */
Kenny Rootc4c70f12013-06-14 12:11:38 -0700593 crypt_ftr->kdf_type = KDF_PBKDF2;
594 get_device_scrypt_params(crypt_ftr);
595 crypt_ftr->minor_version = 2;
596 }
597
Paul Lawrencef4faa572014-01-29 13:31:03 -0800598 if ((crypt_ftr->major_version == 1) && (crypt_ftr->minor_version == 2)) {
599 SLOGW("upgrading crypto footer to 1.3");
600 crypt_ftr->crypt_type = CRYPT_TYPE_PASSWORD;
601 crypt_ftr->minor_version = 3;
602 }
603
Kenny Root7434b312013-06-14 11:29:53 -0700604 if ((orig_major != crypt_ftr->major_version) || (orig_minor != crypt_ftr->minor_version)) {
605 if (lseek64(fd, offset, SEEK_SET) == -1) {
606 SLOGE("Cannot seek to crypt footer\n");
607 return;
608 }
609 unix_write(fd, crypt_ftr, sizeof(struct crypt_mnt_ftr));
Ken Sumrall160b4d62013-04-22 12:15:39 -0700610 }
Ken Sumrall160b4d62013-04-22 12:15:39 -0700611}
612
613
614static int get_crypt_ftr_and_key(struct crypt_mnt_ftr *crypt_ftr)
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800615{
616 int fd;
Tim Murray8439dc92014-12-15 11:56:11 -0800617 unsigned int cnt;
Ken Sumrall160b4d62013-04-22 12:15:39 -0700618 off64_t starting_off;
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800619 int rc = -1;
Ken Sumrall160b4d62013-04-22 12:15:39 -0700620 char *fname = NULL;
Ken Sumrall29d8da82011-05-18 17:20:07 -0700621 struct stat statbuf;
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800622
Ken Sumrall160b4d62013-04-22 12:15:39 -0700623 if (get_crypt_ftr_info(&fname, &starting_off)) {
624 SLOGE("Unable to get crypt_ftr_info\n");
625 return -1;
626 }
627 if (fname[0] != '/') {
Ken Sumralle5032c42012-04-01 23:58:44 -0700628 SLOGE("Unexpected value for crypto key location\n");
Ken Sumrall160b4d62013-04-22 12:15:39 -0700629 return -1;
630 }
631 if ( (fd = open(fname, O_RDWR)) < 0) {
Ken Sumralle550f782013-08-20 13:48:23 -0700632 SLOGE("Cannot open footer file %s for get\n", fname);
Ken Sumrall160b4d62013-04-22 12:15:39 -0700633 return -1;
634 }
635
636 /* Make sure it's 16 Kbytes in length */
637 fstat(fd, &statbuf);
638 if (S_ISREG(statbuf.st_mode) && (statbuf.st_size != 0x4000)) {
639 SLOGE("footer file %s is not the expected size!\n", fname);
640 goto errout;
641 }
642
643 /* Seek to the start of the crypt footer */
644 if (lseek64(fd, starting_off, SEEK_SET) == -1) {
645 SLOGE("Cannot seek to real block device footer\n");
646 goto errout;
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800647 }
648
649 if ( (cnt = read(fd, crypt_ftr, sizeof(struct crypt_mnt_ftr))) != sizeof(struct crypt_mnt_ftr)) {
650 SLOGE("Cannot read real block device footer\n");
651 goto errout;
652 }
653
654 if (crypt_ftr->magic != CRYPT_MNT_MAGIC) {
Ken Sumrall29d8da82011-05-18 17:20:07 -0700655 SLOGE("Bad magic for real block device %s\n", fname);
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800656 goto errout;
657 }
658
Kenny Rootc96a5f82013-06-14 12:08:28 -0700659 if (crypt_ftr->major_version != CURRENT_MAJOR_VERSION) {
660 SLOGE("Cannot understand major version %d real block device footer; expected %d\n",
661 crypt_ftr->major_version, CURRENT_MAJOR_VERSION);
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800662 goto errout;
663 }
664
Kenny Rootc96a5f82013-06-14 12:08:28 -0700665 if (crypt_ftr->minor_version > CURRENT_MINOR_VERSION) {
666 SLOGW("Warning: crypto footer minor version %d, expected <= %d, continuing...\n",
667 crypt_ftr->minor_version, CURRENT_MINOR_VERSION);
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800668 }
669
Ken Sumrall160b4d62013-04-22 12:15:39 -0700670 /* If this is a verion 1.0 crypt_ftr, make it a 1.1 crypt footer, and update the
671 * copy on disk before returning.
672 */
Kenny Rootc96a5f82013-06-14 12:08:28 -0700673 if (crypt_ftr->minor_version < CURRENT_MINOR_VERSION) {
Ken Sumrall160b4d62013-04-22 12:15:39 -0700674 upgrade_crypt_ftr(fd, crypt_ftr, starting_off);
Ken Sumralle8744072011-01-18 22:01:55 -0800675 }
676
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800677 /* Success! */
678 rc = 0;
679
680errout:
681 close(fd);
682 return rc;
683}
684
Ken Sumrall160b4d62013-04-22 12:15:39 -0700685static int validate_persistent_data_storage(struct crypt_mnt_ftr *crypt_ftr)
686{
687 if (crypt_ftr->persist_data_offset[0] + crypt_ftr->persist_data_size >
688 crypt_ftr->persist_data_offset[1]) {
689 SLOGE("Crypt_ftr persist data regions overlap");
690 return -1;
691 }
692
693 if (crypt_ftr->persist_data_offset[0] >= crypt_ftr->persist_data_offset[1]) {
694 SLOGE("Crypt_ftr persist data region 0 starts after region 1");
695 return -1;
696 }
697
698 if (((crypt_ftr->persist_data_offset[1] + crypt_ftr->persist_data_size) -
699 (crypt_ftr->persist_data_offset[0] - CRYPT_FOOTER_TO_PERSIST_OFFSET)) >
700 CRYPT_FOOTER_OFFSET) {
701 SLOGE("Persistent data extends past crypto footer");
702 return -1;
703 }
704
705 return 0;
706}
707
708static int load_persistent_data(void)
709{
710 struct crypt_mnt_ftr crypt_ftr;
711 struct crypt_persist_data *pdata = NULL;
712 char encrypted_state[PROPERTY_VALUE_MAX];
713 char *fname;
714 int found = 0;
715 int fd;
716 int ret;
717 int i;
718
719 if (persist_data) {
720 /* Nothing to do, we've already loaded or initialized it */
721 return 0;
722 }
723
724
725 /* If not encrypted, just allocate an empty table and initialize it */
726 property_get("ro.crypto.state", encrypted_state, "");
727 if (strcmp(encrypted_state, "encrypted") ) {
728 pdata = malloc(CRYPT_PERSIST_DATA_SIZE);
729 if (pdata) {
730 init_empty_persist_data(pdata, CRYPT_PERSIST_DATA_SIZE);
731 persist_data = pdata;
732 return 0;
733 }
734 return -1;
735 }
736
737 if(get_crypt_ftr_and_key(&crypt_ftr)) {
738 return -1;
739 }
740
Paul Lawrence8561b5c2014-03-17 14:10:51 -0700741 if ((crypt_ftr.major_version < 1)
742 || (crypt_ftr.major_version == 1 && crypt_ftr.minor_version < 1)) {
Ken Sumrall160b4d62013-04-22 12:15:39 -0700743 SLOGE("Crypt_ftr version doesn't support persistent data");
744 return -1;
745 }
746
747 if (get_crypt_ftr_info(&fname, NULL)) {
748 return -1;
749 }
750
751 ret = validate_persistent_data_storage(&crypt_ftr);
752 if (ret) {
753 return -1;
754 }
755
756 fd = open(fname, O_RDONLY);
757 if (fd < 0) {
758 SLOGE("Cannot open %s metadata file", fname);
759 return -1;
760 }
761
762 if (persist_data == NULL) {
763 pdata = malloc(crypt_ftr.persist_data_size);
764 if (pdata == NULL) {
765 SLOGE("Cannot allocate memory for persistent data");
766 goto err;
767 }
768 }
769
770 for (i = 0; i < 2; i++) {
771 if (lseek64(fd, crypt_ftr.persist_data_offset[i], SEEK_SET) < 0) {
772 SLOGE("Cannot seek to read persistent data on %s", fname);
773 goto err2;
774 }
775 if (unix_read(fd, pdata, crypt_ftr.persist_data_size) < 0){
776 SLOGE("Error reading persistent data on iteration %d", i);
777 goto err2;
778 }
779 if (pdata->persist_magic == PERSIST_DATA_MAGIC) {
780 found = 1;
781 break;
782 }
783 }
784
785 if (!found) {
786 SLOGI("Could not find valid persistent data, creating");
787 init_empty_persist_data(pdata, crypt_ftr.persist_data_size);
788 }
789
790 /* Success */
791 persist_data = pdata;
792 close(fd);
793 return 0;
794
795err2:
796 free(pdata);
797
798err:
799 close(fd);
800 return -1;
801}
802
803static int save_persistent_data(void)
804{
805 struct crypt_mnt_ftr crypt_ftr;
806 struct crypt_persist_data *pdata;
807 char *fname;
808 off64_t write_offset;
809 off64_t erase_offset;
Ken Sumrall160b4d62013-04-22 12:15:39 -0700810 int fd;
811 int ret;
812
813 if (persist_data == NULL) {
814 SLOGE("No persistent data to save");
815 return -1;
816 }
817
818 if(get_crypt_ftr_and_key(&crypt_ftr)) {
819 return -1;
820 }
821
Paul Lawrence8561b5c2014-03-17 14:10:51 -0700822 if ((crypt_ftr.major_version < 1)
823 || (crypt_ftr.major_version == 1 && crypt_ftr.minor_version < 1)) {
Ken Sumrall160b4d62013-04-22 12:15:39 -0700824 SLOGE("Crypt_ftr version doesn't support persistent data");
825 return -1;
826 }
827
828 ret = validate_persistent_data_storage(&crypt_ftr);
829 if (ret) {
830 return -1;
831 }
832
833 if (get_crypt_ftr_info(&fname, NULL)) {
834 return -1;
835 }
836
837 fd = open(fname, O_RDWR);
838 if (fd < 0) {
839 SLOGE("Cannot open %s metadata file", fname);
840 return -1;
841 }
842
843 pdata = malloc(crypt_ftr.persist_data_size);
844 if (pdata == NULL) {
845 SLOGE("Cannot allocate persistant data");
846 goto err;
847 }
848
849 if (lseek64(fd, crypt_ftr.persist_data_offset[0], SEEK_SET) < 0) {
850 SLOGE("Cannot seek to read persistent data on %s", fname);
851 goto err2;
852 }
853
854 if (unix_read(fd, pdata, crypt_ftr.persist_data_size) < 0) {
855 SLOGE("Error reading persistent data before save");
856 goto err2;
857 }
858
859 if (pdata->persist_magic == PERSIST_DATA_MAGIC) {
860 /* The first copy is the curent valid copy, so write to
861 * the second copy and erase this one */
862 write_offset = crypt_ftr.persist_data_offset[1];
863 erase_offset = crypt_ftr.persist_data_offset[0];
864 } else {
865 /* The second copy must be the valid copy, so write to
866 * the first copy, and erase the second */
867 write_offset = crypt_ftr.persist_data_offset[0];
868 erase_offset = crypt_ftr.persist_data_offset[1];
869 }
870
871 /* Write the new copy first, if successful, then erase the old copy */
872 if (lseek(fd, write_offset, SEEK_SET) < 0) {
873 SLOGE("Cannot seek to write persistent data");
874 goto err2;
875 }
876 if (unix_write(fd, persist_data, crypt_ftr.persist_data_size) ==
877 (int) crypt_ftr.persist_data_size) {
878 if (lseek(fd, erase_offset, SEEK_SET) < 0) {
879 SLOGE("Cannot seek to erase previous persistent data");
880 goto err2;
881 }
882 fsync(fd);
883 memset(pdata, 0, crypt_ftr.persist_data_size);
884 if (unix_write(fd, pdata, crypt_ftr.persist_data_size) !=
885 (int) crypt_ftr.persist_data_size) {
886 SLOGE("Cannot write to erase previous persistent data");
887 goto err2;
888 }
889 fsync(fd);
890 } else {
891 SLOGE("Cannot write to save persistent data");
892 goto err2;
893 }
894
895 /* Success */
896 free(pdata);
897 close(fd);
898 return 0;
899
900err2:
901 free(pdata);
902err:
903 close(fd);
904 return -1;
905}
906
Paul Lawrencef4faa572014-01-29 13:31:03 -0800907static int hexdigit (char c)
908{
909 if (c >= '0' && c <= '9') return c - '0';
910 c = tolower(c);
911 if (c >= 'a' && c <= 'f') return c - 'a' + 10;
912 return -1;
913}
914
915static unsigned char* convert_hex_ascii_to_key(const char* master_key_ascii,
916 unsigned int* out_keysize)
917{
918 unsigned int i;
919 *out_keysize = 0;
920
921 size_t size = strlen (master_key_ascii);
922 if (size % 2) {
923 SLOGE("Trying to convert ascii string of odd length");
924 return NULL;
925 }
926
927 unsigned char* master_key = (unsigned char*) malloc(size / 2);
928 if (master_key == 0) {
929 SLOGE("Cannot allocate");
930 return NULL;
931 }
932
933 for (i = 0; i < size; i += 2) {
934 int high_nibble = hexdigit (master_key_ascii[i]);
935 int low_nibble = hexdigit (master_key_ascii[i + 1]);
936
937 if(high_nibble < 0 || low_nibble < 0) {
938 SLOGE("Invalid hex string");
939 free (master_key);
940 return NULL;
941 }
942
943 master_key[*out_keysize] = high_nibble * 16 + low_nibble;
944 (*out_keysize)++;
945 }
946
947 return master_key;
948}
949
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800950/* Convert a binary key of specified length into an ascii hex string equivalent,
951 * without the leading 0x and with null termination
952 */
Paul Lawrencef4faa572014-01-29 13:31:03 -0800953static void convert_key_to_hex_ascii(unsigned char *master_key, unsigned int keysize,
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800954 char *master_key_ascii)
955{
956 unsigned int i, a;
957 unsigned char nibble;
958
959 for (i=0, a=0; i<keysize; i++, a+=2) {
960 /* For each byte, write out two ascii hex digits */
961 nibble = (master_key[i] >> 4) & 0xf;
962 master_key_ascii[a] = nibble + (nibble > 9 ? 0x37 : 0x30);
963
964 nibble = master_key[i] & 0xf;
965 master_key_ascii[a+1] = nibble + (nibble > 9 ? 0x37 : 0x30);
966 }
967
968 /* Add the null termination */
969 master_key_ascii[a] = '\0';
970
971}
972
Ken Sumralldb5e0262013-02-05 17:39:48 -0800973static int load_crypto_mapping_table(struct crypt_mnt_ftr *crypt_ftr, unsigned char *master_key,
974 char *real_blk_name, const char *name, int fd,
975 char *extra_params)
976{
Dan Albertc07fa3f2014-12-18 10:00:55 -0800977 _Alignas(struct dm_ioctl) char buffer[DM_CRYPT_BUF_SIZE];
Ken Sumralldb5e0262013-02-05 17:39:48 -0800978 struct dm_ioctl *io;
979 struct dm_target_spec *tgt;
980 char *crypt_params;
981 char master_key_ascii[129]; /* Large enough to hold 512 bit key and null */
982 int i;
983
984 io = (struct dm_ioctl *) buffer;
985
986 /* Load the mapping table for this device */
987 tgt = (struct dm_target_spec *) &buffer[sizeof(struct dm_ioctl)];
988
989 ioctl_init(io, DM_CRYPT_BUF_SIZE, name, 0);
990 io->target_count = 1;
991 tgt->status = 0;
992 tgt->sector_start = 0;
993 tgt->length = crypt_ftr->fs_size;
994 strcpy(tgt->target_type, "crypt");
995
996 crypt_params = buffer + sizeof(struct dm_ioctl) + sizeof(struct dm_target_spec);
997 convert_key_to_hex_ascii(master_key, crypt_ftr->keysize, master_key_ascii);
998 sprintf(crypt_params, "%s %s 0 %s 0 %s", crypt_ftr->crypto_type_name,
999 master_key_ascii, real_blk_name, extra_params);
1000 crypt_params += strlen(crypt_params) + 1;
1001 crypt_params = (char *) (((unsigned long)crypt_params + 7) & ~8); /* Align to an 8 byte boundary */
1002 tgt->next = crypt_params - buffer;
1003
1004 for (i = 0; i < TABLE_LOAD_RETRIES; i++) {
1005 if (! ioctl(fd, DM_TABLE_LOAD, io)) {
1006 break;
1007 }
1008 usleep(500000);
1009 }
1010
1011 if (i == TABLE_LOAD_RETRIES) {
1012 /* We failed to load the table, return an error */
1013 return -1;
1014 } else {
1015 return i + 1;
1016 }
1017}
1018
1019
1020static int get_dm_crypt_version(int fd, const char *name, int *version)
1021{
1022 char buffer[DM_CRYPT_BUF_SIZE];
1023 struct dm_ioctl *io;
1024 struct dm_target_versions *v;
Ken Sumralldb5e0262013-02-05 17:39:48 -08001025
1026 io = (struct dm_ioctl *) buffer;
1027
1028 ioctl_init(io, DM_CRYPT_BUF_SIZE, name, 0);
1029
1030 if (ioctl(fd, DM_LIST_VERSIONS, io)) {
1031 return -1;
1032 }
1033
1034 /* Iterate over the returned versions, looking for name of "crypt".
1035 * When found, get and return the version.
1036 */
1037 v = (struct dm_target_versions *) &buffer[sizeof(struct dm_ioctl)];
1038 while (v->next) {
1039 if (! strcmp(v->name, "crypt")) {
1040 /* We found the crypt driver, return the version, and get out */
1041 version[0] = v->version[0];
1042 version[1] = v->version[1];
1043 version[2] = v->version[2];
1044 return 0;
1045 }
1046 v = (struct dm_target_versions *)(((char *)v) + v->next);
1047 }
1048
1049 return -1;
1050}
1051
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001052static int create_crypto_blk_dev(struct crypt_mnt_ftr *crypt_ftr, unsigned char *master_key,
Ken Sumrall29d8da82011-05-18 17:20:07 -07001053 char *real_blk_name, char *crypto_blk_name, const char *name)
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001054{
1055 char buffer[DM_CRYPT_BUF_SIZE];
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001056 struct dm_ioctl *io;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001057 unsigned int minor;
1058 int fd;
1059 int retval = -1;
Ken Sumralldb5e0262013-02-05 17:39:48 -08001060 int version[3];
1061 char *extra_params;
1062 int load_count;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001063
1064 if ((fd = open("/dev/device-mapper", O_RDWR)) < 0 ) {
1065 SLOGE("Cannot open device-mapper\n");
1066 goto errout;
1067 }
1068
1069 io = (struct dm_ioctl *) buffer;
1070
1071 ioctl_init(io, DM_CRYPT_BUF_SIZE, name, 0);
1072 if (ioctl(fd, DM_DEV_CREATE, io)) {
1073 SLOGE("Cannot create dm-crypt device\n");
1074 goto errout;
1075 }
1076
1077 /* Get the device status, in particular, the name of it's device file */
1078 ioctl_init(io, DM_CRYPT_BUF_SIZE, name, 0);
1079 if (ioctl(fd, DM_DEV_STATUS, io)) {
1080 SLOGE("Cannot retrieve dm-crypt device status\n");
1081 goto errout;
1082 }
1083 minor = (io->dev & 0xff) | ((io->dev >> 12) & 0xfff00);
1084 snprintf(crypto_blk_name, MAXPATHLEN, "/dev/block/dm-%u", minor);
1085
Ken Sumralldb5e0262013-02-05 17:39:48 -08001086 extra_params = "";
1087 if (! get_dm_crypt_version(fd, name, version)) {
1088 /* Support for allow_discards was added in version 1.11.0 */
1089 if ((version[0] >= 2) ||
1090 ((version[0] == 1) && (version[1] >= 11))) {
1091 extra_params = "1 allow_discards";
1092 SLOGI("Enabling support for allow_discards in dmcrypt.\n");
1093 }
Ken Sumralle919efe2012-09-29 17:07:41 -07001094 }
1095
Ken Sumralldb5e0262013-02-05 17:39:48 -08001096 load_count = load_crypto_mapping_table(crypt_ftr, master_key, real_blk_name, name,
1097 fd, extra_params);
1098 if (load_count < 0) {
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001099 SLOGE("Cannot load dm-crypt mapping table.\n");
1100 goto errout;
Ken Sumralldb5e0262013-02-05 17:39:48 -08001101 } else if (load_count > 1) {
1102 SLOGI("Took %d tries to load dmcrypt table.\n", load_count);
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001103 }
1104
1105 /* Resume this device to activate it */
Ken Sumralldb5e0262013-02-05 17:39:48 -08001106 ioctl_init(io, DM_CRYPT_BUF_SIZE, name, 0);
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001107
1108 if (ioctl(fd, DM_DEV_SUSPEND, io)) {
1109 SLOGE("Cannot resume the dm-crypt device\n");
1110 goto errout;
1111 }
1112
1113 /* We made it here with no errors. Woot! */
1114 retval = 0;
1115
1116errout:
1117 close(fd); /* If fd is <0 from a failed open call, it's safe to just ignore the close error */
1118
1119 return retval;
1120}
1121
Ken Sumrall29d8da82011-05-18 17:20:07 -07001122static int delete_crypto_blk_dev(char *name)
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001123{
1124 int fd;
1125 char buffer[DM_CRYPT_BUF_SIZE];
1126 struct dm_ioctl *io;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001127 int retval = -1;
1128
1129 if ((fd = open("/dev/device-mapper", O_RDWR)) < 0 ) {
1130 SLOGE("Cannot open device-mapper\n");
1131 goto errout;
1132 }
1133
1134 io = (struct dm_ioctl *) buffer;
1135
1136 ioctl_init(io, DM_CRYPT_BUF_SIZE, name, 0);
1137 if (ioctl(fd, DM_DEV_REMOVE, io)) {
1138 SLOGE("Cannot remove dm-crypt device\n");
1139 goto errout;
1140 }
1141
1142 /* We made it here with no errors. Woot! */
1143 retval = 0;
1144
1145errout:
1146 close(fd); /* If fd is <0 from a failed open call, it's safe to just ignore the close error */
1147
1148 return retval;
1149
1150}
1151
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001152static int pbkdf2(const char *passwd, const unsigned char *salt,
Paul Lawrencef4faa572014-01-29 13:31:03 -08001153 unsigned char *ikey, void *params UNUSED)
1154{
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001155 SLOGI("Using pbkdf2 for cryptfs KDF");
1156
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001157 /* Turn the password into a key and IV that can decrypt the master key */
Paul Lawrencef4faa572014-01-29 13:31:03 -08001158 unsigned int keysize;
1159 char* master_key = (char*)convert_hex_ascii_to_key(passwd, &keysize);
1160 if (!master_key) return -1;
1161 PKCS5_PBKDF2_HMAC_SHA1(master_key, keysize, salt, SALT_LEN,
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001162 HASH_COUNT, KEY_LEN_BYTES+IV_LEN_BYTES, ikey);
Paul Lawrencef4faa572014-01-29 13:31:03 -08001163
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001164 memset(master_key, 0, keysize);
Paul Lawrencef4faa572014-01-29 13:31:03 -08001165 free (master_key);
1166 return 0;
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001167}
1168
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001169static int scrypt(const char *passwd, const unsigned char *salt,
Paul Lawrencef4faa572014-01-29 13:31:03 -08001170 unsigned char *ikey, void *params)
1171{
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001172 SLOGI("Using scrypt for cryptfs KDF");
1173
Kenny Rootc4c70f12013-06-14 12:11:38 -07001174 struct crypt_mnt_ftr *ftr = (struct crypt_mnt_ftr *) params;
1175
1176 int N = 1 << ftr->N_factor;
1177 int r = 1 << ftr->r_factor;
1178 int p = 1 << ftr->p_factor;
1179
1180 /* Turn the password into a key and IV that can decrypt the master key */
Paul Lawrencef4faa572014-01-29 13:31:03 -08001181 unsigned int keysize;
1182 unsigned char* master_key = convert_hex_ascii_to_key(passwd, &keysize);
1183 if (!master_key) return -1;
1184 crypto_scrypt(master_key, keysize, salt, SALT_LEN, N, r, p, ikey,
Kenny Rootc4c70f12013-06-14 12:11:38 -07001185 KEY_LEN_BYTES + IV_LEN_BYTES);
Paul Lawrencef4faa572014-01-29 13:31:03 -08001186
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001187 memset(master_key, 0, keysize);
Paul Lawrencef4faa572014-01-29 13:31:03 -08001188 free (master_key);
1189 return 0;
Kenny Rootc4c70f12013-06-14 12:11:38 -07001190}
1191
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001192static int scrypt_keymaster(const char *passwd, const unsigned char *salt,
1193 unsigned char *ikey, void *params)
1194{
1195 SLOGI("Using scrypt with keymaster for cryptfs KDF");
1196
1197 int rc;
1198 unsigned int key_size;
1199 size_t signature_size;
1200 unsigned char* signature;
1201 struct crypt_mnt_ftr *ftr = (struct crypt_mnt_ftr *) params;
1202
1203 int N = 1 << ftr->N_factor;
1204 int r = 1 << ftr->r_factor;
1205 int p = 1 << ftr->p_factor;
1206
1207 unsigned char* master_key = convert_hex_ascii_to_key(passwd, &key_size);
1208 if (!master_key) {
1209 SLOGE("Failed to convert passwd from hex");
1210 return -1;
1211 }
1212
1213 rc = crypto_scrypt(master_key, key_size, salt, SALT_LEN,
1214 N, r, p, ikey, KEY_LEN_BYTES + IV_LEN_BYTES);
1215 memset(master_key, 0, key_size);
1216 free(master_key);
1217
1218 if (rc) {
1219 SLOGE("scrypt failed");
1220 return -1;
1221 }
1222
Shawn Willdene17a9c42014-09-08 13:04:08 -06001223 if (keymaster_sign_object(ftr, ikey, KEY_LEN_BYTES + IV_LEN_BYTES,
1224 &signature, &signature_size)) {
1225 SLOGE("Signing failed");
1226 return -1;
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001227 }
1228
1229 rc = crypto_scrypt(signature, signature_size, salt, SALT_LEN,
1230 N, r, p, ikey, KEY_LEN_BYTES + IV_LEN_BYTES);
1231 free(signature);
1232
1233 if (rc) {
1234 SLOGE("scrypt failed");
1235 return -1;
1236 }
1237
1238 return 0;
1239}
1240
1241static int encrypt_master_key(const char *passwd, const unsigned char *salt,
1242 const unsigned char *decrypted_master_key,
Kenny Rootc4c70f12013-06-14 12:11:38 -07001243 unsigned char *encrypted_master_key,
1244 struct crypt_mnt_ftr *crypt_ftr)
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001245{
1246 unsigned char ikey[32+32] = { 0 }; /* Big enough to hold a 256 bit key and 256 bit IV */
1247 EVP_CIPHER_CTX e_ctx;
1248 int encrypted_len, final_len;
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001249 int rc = 0;
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001250
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001251 /* Turn the password into an intermediate key and IV that can decrypt the master key */
Kenny Rootc4c70f12013-06-14 12:11:38 -07001252 get_device_scrypt_params(crypt_ftr);
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001253
1254 switch (crypt_ftr->kdf_type) {
Shawn Willdene17a9c42014-09-08 13:04:08 -06001255 case KDF_SCRYPT_KEYMASTER_UNPADDED:
1256 case KDF_SCRYPT_KEYMASTER_BADLY_PADDED:
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001257 case KDF_SCRYPT_KEYMASTER:
1258 if (keymaster_create_key(crypt_ftr)) {
1259 SLOGE("keymaster_create_key failed");
1260 return -1;
1261 }
1262
1263 if (scrypt_keymaster(passwd, salt, ikey, crypt_ftr)) {
1264 SLOGE("scrypt failed");
1265 return -1;
1266 }
1267 break;
1268
1269 case KDF_SCRYPT:
1270 if (scrypt(passwd, salt, ikey, crypt_ftr)) {
1271 SLOGE("scrypt failed");
1272 return -1;
1273 }
1274 break;
1275
1276 default:
1277 SLOGE("Invalid kdf_type");
Paul Lawrencef4faa572014-01-29 13:31:03 -08001278 return -1;
1279 }
Kenny Rootc4c70f12013-06-14 12:11:38 -07001280
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001281 /* Initialize the decryption engine */
Adam Langley889c4f12014-09-03 14:23:13 -07001282 EVP_CIPHER_CTX_init(&e_ctx);
1283 if (! EVP_EncryptInit_ex(&e_ctx, EVP_aes_128_cbc(), NULL, ikey, ikey+KEY_LEN_BYTES)) {
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001284 SLOGE("EVP_EncryptInit failed\n");
1285 return -1;
1286 }
1287 EVP_CIPHER_CTX_set_padding(&e_ctx, 0); /* Turn off padding as our data is block aligned */
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001288
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001289 /* Encrypt the master key */
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001290 if (! EVP_EncryptUpdate(&e_ctx, encrypted_master_key, &encrypted_len,
1291 decrypted_master_key, KEY_LEN_BYTES)) {
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001292 SLOGE("EVP_EncryptUpdate failed\n");
1293 return -1;
1294 }
Adam Langley889c4f12014-09-03 14:23:13 -07001295 if (! EVP_EncryptFinal_ex(&e_ctx, encrypted_master_key + encrypted_len, &final_len)) {
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001296 SLOGE("EVP_EncryptFinal failed\n");
1297 return -1;
1298 }
1299
1300 if (encrypted_len + final_len != KEY_LEN_BYTES) {
1301 SLOGE("EVP_Encryption length check failed with %d, %d bytes\n", encrypted_len, final_len);
1302 return -1;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001303 }
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001304
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001305 /* Store the scrypt of the intermediate key, so we can validate if it's a
1306 password error or mount error when things go wrong.
1307 Note there's no need to check for errors, since if this is incorrect, we
1308 simply won't wipe userdata, which is the correct default behavior
1309 */
1310 int N = 1 << crypt_ftr->N_factor;
1311 int r = 1 << crypt_ftr->r_factor;
1312 int p = 1 << crypt_ftr->p_factor;
1313
1314 rc = crypto_scrypt(ikey, KEY_LEN_BYTES,
1315 crypt_ftr->salt, sizeof(crypt_ftr->salt), N, r, p,
1316 crypt_ftr->scrypted_intermediate_key,
1317 sizeof(crypt_ftr->scrypted_intermediate_key));
1318
1319 if (rc) {
1320 SLOGE("encrypt_master_key: crypto_scrypt failed");
1321 }
1322
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001323 return 0;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001324}
1325
JP Abgrall7bdfa522013-11-15 13:42:56 -08001326static int decrypt_master_key_aux(char *passwd, unsigned char *salt,
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001327 unsigned char *encrypted_master_key,
1328 unsigned char *decrypted_master_key,
1329 kdf_func kdf, void *kdf_params,
1330 unsigned char** intermediate_key,
1331 size_t* intermediate_key_size)
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001332{
1333 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 -08001334 EVP_CIPHER_CTX d_ctx;
1335 int decrypted_len, final_len;
1336
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001337 /* Turn the password into an intermediate key and IV that can decrypt the
1338 master key */
Paul Lawrencef4faa572014-01-29 13:31:03 -08001339 if (kdf(passwd, salt, ikey, kdf_params)) {
1340 SLOGE("kdf failed");
1341 return -1;
1342 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001343
1344 /* Initialize the decryption engine */
Adam Langley889c4f12014-09-03 14:23:13 -07001345 EVP_CIPHER_CTX_init(&d_ctx);
1346 if (! EVP_DecryptInit_ex(&d_ctx, EVP_aes_128_cbc(), NULL, ikey, ikey+KEY_LEN_BYTES)) {
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001347 return -1;
1348 }
1349 EVP_CIPHER_CTX_set_padding(&d_ctx, 0); /* Turn off padding as our data is block aligned */
1350 /* Decrypt the master key */
1351 if (! EVP_DecryptUpdate(&d_ctx, decrypted_master_key, &decrypted_len,
1352 encrypted_master_key, KEY_LEN_BYTES)) {
1353 return -1;
1354 }
Adam Langley889c4f12014-09-03 14:23:13 -07001355 if (! EVP_DecryptFinal_ex(&d_ctx, decrypted_master_key + decrypted_len, &final_len)) {
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001356 return -1;
1357 }
1358
1359 if (decrypted_len + final_len != KEY_LEN_BYTES) {
1360 return -1;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001361 }
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001362
1363 /* Copy intermediate key if needed by params */
1364 if (intermediate_key && intermediate_key_size) {
1365 *intermediate_key = (unsigned char*) malloc(KEY_LEN_BYTES);
1366 if (intermediate_key) {
1367 memcpy(*intermediate_key, ikey, KEY_LEN_BYTES);
1368 *intermediate_key_size = KEY_LEN_BYTES;
1369 }
1370 }
1371
1372 return 0;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001373}
1374
Kenny Rootc4c70f12013-06-14 12:11:38 -07001375static void get_kdf_func(struct crypt_mnt_ftr *ftr, kdf_func *kdf, void** kdf_params)
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001376{
Shawn Willdene17a9c42014-09-08 13:04:08 -06001377 if (ftr->kdf_type == KDF_SCRYPT_KEYMASTER_UNPADDED ||
1378 ftr->kdf_type == KDF_SCRYPT_KEYMASTER_BADLY_PADDED ||
1379 ftr->kdf_type == KDF_SCRYPT_KEYMASTER) {
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001380 *kdf = scrypt_keymaster;
1381 *kdf_params = ftr;
1382 } else if (ftr->kdf_type == KDF_SCRYPT) {
Kenny Rootc4c70f12013-06-14 12:11:38 -07001383 *kdf = scrypt;
1384 *kdf_params = ftr;
1385 } else {
1386 *kdf = pbkdf2;
1387 *kdf_params = NULL;
1388 }
1389}
1390
JP Abgrall7bdfa522013-11-15 13:42:56 -08001391static int decrypt_master_key(char *passwd, unsigned char *decrypted_master_key,
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001392 struct crypt_mnt_ftr *crypt_ftr,
1393 unsigned char** intermediate_key,
1394 size_t* intermediate_key_size)
Kenny Rootc4c70f12013-06-14 12:11:38 -07001395{
1396 kdf_func kdf;
1397 void *kdf_params;
1398 int ret;
1399
1400 get_kdf_func(crypt_ftr, &kdf, &kdf_params);
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001401 ret = decrypt_master_key_aux(passwd, crypt_ftr->salt, crypt_ftr->master_key,
1402 decrypted_master_key, kdf, kdf_params,
1403 intermediate_key, intermediate_key_size);
Kenny Rootc4c70f12013-06-14 12:11:38 -07001404 if (ret != 0) {
1405 SLOGW("failure decrypting master key");
Kenny Rootc4c70f12013-06-14 12:11:38 -07001406 }
1407
1408 return ret;
1409}
1410
1411static int create_encrypted_random_key(char *passwd, unsigned char *master_key, unsigned char *salt,
1412 struct crypt_mnt_ftr *crypt_ftr) {
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001413 int fd;
Ken Sumralle8744072011-01-18 22:01:55 -08001414 unsigned char key_buf[KEY_LEN_BYTES];
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001415
1416 /* Get some random bits for a key */
1417 fd = open("/dev/urandom", O_RDONLY);
Ken Sumralle8744072011-01-18 22:01:55 -08001418 read(fd, key_buf, sizeof(key_buf));
1419 read(fd, salt, SALT_LEN);
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001420 close(fd);
1421
1422 /* Now encrypt it with the password */
Kenny Rootc4c70f12013-06-14 12:11:38 -07001423 return encrypt_master_key(passwd, salt, key_buf, master_key, crypt_ftr);
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001424}
1425
Greg Hackmann6e8440f2014-10-02 17:18:20 -07001426static int wait_and_unmount(char *mountpoint, bool kill)
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001427{
Greg Hackmann955653e2014-09-24 14:55:20 -07001428 int i, err, rc;
Ken Sumrall2eaf7132011-01-14 12:45:48 -08001429#define WAIT_UNMOUNT_COUNT 20
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001430
1431 /* Now umount the tmpfs filesystem */
1432 for (i=0; i<WAIT_UNMOUNT_COUNT; i++) {
Greg Hackmann6e8440f2014-10-02 17:18:20 -07001433 if (umount(mountpoint) == 0) {
1434 break;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001435 }
Greg Hackmann6e8440f2014-10-02 17:18:20 -07001436
1437 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 }
1443
1444 err = errno;
1445
1446 /* If allowed, be increasingly aggressive before the last two retries */
1447 if (kill) {
1448 if (i == (WAIT_UNMOUNT_COUNT - 3)) {
1449 SLOGW("sending SIGHUP to processes with open files\n");
1450 vold_killProcessesWithOpenFiles(mountpoint, 1);
1451 } else if (i == (WAIT_UNMOUNT_COUNT - 2)) {
1452 SLOGW("sending SIGKILL to processes with open files\n");
1453 vold_killProcessesWithOpenFiles(mountpoint, 2);
1454 }
1455 }
1456
1457 sleep(1);
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001458 }
1459
1460 if (i < WAIT_UNMOUNT_COUNT) {
1461 SLOGD("unmounting %s succeeded\n", mountpoint);
1462 rc = 0;
1463 } else {
jessica_yu3f14fe42014-09-22 15:57:40 +08001464 vold_killProcessesWithOpenFiles(mountpoint, 0);
Greg Hackmann955653e2014-09-24 14:55:20 -07001465 SLOGE("unmounting %s failed: %s\n", mountpoint, strerror(err));
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001466 rc = -1;
1467 }
1468
1469 return rc;
1470}
1471
Ken Sumrallc5872692013-05-14 15:26:31 -07001472#define DATA_PREP_TIMEOUT 200
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001473static int prep_data_fs(void)
1474{
1475 int i;
1476
1477 /* Do the prep of the /data filesystem */
1478 property_set("vold.post_fs_data_done", "0");
1479 property_set("vold.decrypt", "trigger_post_fs_data");
1480 SLOGD("Just triggered post_fs_data\n");
1481
Ken Sumrallc5872692013-05-14 15:26:31 -07001482 /* Wait a max of 50 seconds, hopefully it takes much less */
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001483 for (i=0; i<DATA_PREP_TIMEOUT; i++) {
Ken Sumrall29d8da82011-05-18 17:20:07 -07001484 char p[PROPERTY_VALUE_MAX];
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001485
1486 property_get("vold.post_fs_data_done", p, "0");
1487 if (*p == '1') {
1488 break;
1489 } else {
1490 usleep(250000);
1491 }
1492 }
1493 if (i == DATA_PREP_TIMEOUT) {
1494 /* Ugh, we failed to prep /data in time. Bail. */
Ken Sumrallc5872692013-05-14 15:26:31 -07001495 SLOGE("post_fs_data timed out!\n");
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001496 return -1;
1497 } else {
1498 SLOGD("post_fs_data done\n");
1499 return 0;
1500 }
1501}
1502
Paul Lawrence74f29f12014-08-28 15:54:10 -07001503static void cryptfs_set_corrupt()
1504{
1505 // Mark the footer as bad
1506 struct crypt_mnt_ftr crypt_ftr;
1507 if (get_crypt_ftr_and_key(&crypt_ftr)) {
1508 SLOGE("Failed to get crypto footer - panic");
1509 return;
1510 }
1511
1512 crypt_ftr.flags |= CRYPT_DATA_CORRUPT;
1513 if (put_crypt_ftr_and_key(&crypt_ftr)) {
1514 SLOGE("Failed to set crypto footer - panic");
1515 return;
1516 }
1517}
1518
1519static void cryptfs_trigger_restart_min_framework()
1520{
1521 if (fs_mgr_do_tmpfs_mount(DATA_MNT_POINT)) {
1522 SLOGE("Failed to mount tmpfs on data - panic");
1523 return;
1524 }
1525
1526 if (property_set("vold.decrypt", "trigger_post_fs_data")) {
1527 SLOGE("Failed to trigger post fs data - panic");
1528 return;
1529 }
1530
1531 if (property_set("vold.decrypt", "trigger_restart_min_framework")) {
1532 SLOGE("Failed to trigger restart min framework - panic");
1533 return;
1534 }
1535}
1536
Paul Lawrence8e3f4512014-09-08 10:11:17 -07001537/* returns < 0 on failure */
Paul Lawrencef4faa572014-01-29 13:31:03 -08001538static int cryptfs_restart_internal(int restart_main)
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001539{
Ken Sumrall6864b7e2011-01-14 15:20:02 -08001540 char crypto_blkdev[MAXPATHLEN];
Tim Murray8439dc92014-12-15 11:56:11 -08001541 int rc = -1;
Ken Sumrall0cc16632011-01-18 20:32:26 -08001542 static int restart_successful = 0;
1543
1544 /* Validate that it's OK to call this routine */
Jason parks70a4b3f2011-01-28 10:10:47 -06001545 if (! master_key_saved) {
Ken Sumrall0cc16632011-01-18 20:32:26 -08001546 SLOGE("Encrypted filesystem not validated, aborting");
1547 return -1;
1548 }
1549
1550 if (restart_successful) {
1551 SLOGE("System already restarted with encrypted disk, aborting");
1552 return -1;
1553 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001554
Paul Lawrencef4faa572014-01-29 13:31:03 -08001555 if (restart_main) {
1556 /* Here is where we shut down the framework. The init scripts
1557 * start all services in one of three classes: core, main or late_start.
1558 * On boot, we start core and main. Now, we stop main, but not core,
1559 * as core includes vold and a few other really important things that
1560 * we need to keep running. Once main has stopped, we should be able
1561 * to umount the tmpfs /data, then mount the encrypted /data.
1562 * We then restart the class main, and also the class late_start.
1563 * At the moment, I've only put a few things in late_start that I know
1564 * are not needed to bring up the framework, and that also cause problems
1565 * with unmounting the tmpfs /data, but I hope to add add more services
1566 * to the late_start class as we optimize this to decrease the delay
1567 * till the user is asked for the password to the filesystem.
1568 */
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001569
Paul Lawrencef4faa572014-01-29 13:31:03 -08001570 /* The init files are setup to stop the class main when vold.decrypt is
1571 * set to trigger_reset_main.
1572 */
1573 property_set("vold.decrypt", "trigger_reset_main");
1574 SLOGD("Just asked init to shut down class main\n");
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001575
Paul Lawrencef4faa572014-01-29 13:31:03 -08001576 /* Ugh, shutting down the framework is not synchronous, so until it
1577 * can be fixed, this horrible hack will wait a moment for it all to
1578 * shut down before proceeding. Without it, some devices cannot
1579 * restart the graphics services.
1580 */
1581 sleep(2);
1582 }
Ken Sumrall9dedfd42012-10-09 14:16:59 -07001583
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001584 /* Now that the framework is shutdown, we should be able to umount()
1585 * the tmpfs filesystem, and mount the real one.
1586 */
1587
Ken Sumrall6864b7e2011-01-14 15:20:02 -08001588 property_get("ro.crypto.fs_crypto_blkdev", crypto_blkdev, "");
1589 if (strlen(crypto_blkdev) == 0) {
1590 SLOGE("fs_crypto_blkdev not set\n");
1591 return -1;
1592 }
1593
Greg Hackmann6e8440f2014-10-02 17:18:20 -07001594 if (! (rc = wait_and_unmount(DATA_MNT_POINT, true)) ) {
Doug Zongker6fd57712013-12-17 09:43:23 -08001595 /* If ro.crypto.readonly is set to 1, mount the decrypted
1596 * filesystem readonly. This is used when /data is mounted by
1597 * recovery mode.
1598 */
1599 char ro_prop[PROPERTY_VALUE_MAX];
1600 property_get("ro.crypto.readonly", ro_prop, "");
1601 if (strlen(ro_prop) > 0 && atoi(ro_prop)) {
1602 struct fstab_rec* rec = fs_mgr_get_entry_for_mount_point(fstab, DATA_MNT_POINT);
1603 rec->flags |= MS_RDONLY;
1604 }
JP Abgrall62c7af32014-06-16 13:01:23 -07001605
Ken Sumralle5032c42012-04-01 23:58:44 -07001606 /* If that succeeded, then mount the decrypted filesystem */
Paul Lawrence8e3f4512014-09-08 10:11:17 -07001607 int retries = RETRY_MOUNT_ATTEMPTS;
1608 int mount_rc;
1609 while ((mount_rc = fs_mgr_do_mount(fstab, DATA_MNT_POINT,
1610 crypto_blkdev, 0))
1611 != 0) {
1612 if (mount_rc == FS_MGR_DOMNT_BUSY) {
1613 /* TODO: invoke something similar to
1614 Process::killProcessWithOpenFiles(DATA_MNT_POINT,
1615 retries > RETRY_MOUNT_ATTEMPT/2 ? 1 : 2 ) */
1616 SLOGI("Failed to mount %s because it is busy - waiting",
1617 crypto_blkdev);
1618 if (--retries) {
1619 sleep(RETRY_MOUNT_DELAY_SECONDS);
1620 } else {
1621 /* Let's hope that a reboot clears away whatever is keeping
1622 the mount busy */
1623 cryptfs_reboot(reboot);
1624 }
1625 } else {
1626 SLOGE("Failed to mount decrypted data");
1627 cryptfs_set_corrupt();
1628 cryptfs_trigger_restart_min_framework();
1629 SLOGI("Started framework to offer wipe");
1630 return -1;
1631 }
Paul Lawrence74f29f12014-08-28 15:54:10 -07001632 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001633
Ken Sumralle5032c42012-04-01 23:58:44 -07001634 property_set("vold.decrypt", "trigger_load_persist_props");
1635 /* Create necessary paths on /data */
1636 if (prep_data_fs()) {
1637 return -1;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001638 }
Ken Sumralle5032c42012-04-01 23:58:44 -07001639
1640 /* startup service classes main and late_start */
1641 property_set("vold.decrypt", "trigger_restart_framework");
1642 SLOGD("Just triggered restart_framework\n");
1643
1644 /* Give it a few moments to get started */
1645 sleep(1);
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001646 }
1647
Ken Sumrall0cc16632011-01-18 20:32:26 -08001648 if (rc == 0) {
1649 restart_successful = 1;
1650 }
1651
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001652 return rc;
1653}
1654
Paul Lawrencef4faa572014-01-29 13:31:03 -08001655int cryptfs_restart(void)
1656{
1657 /* Call internal implementation forcing a restart of main service group */
1658 return cryptfs_restart_internal(1);
1659}
1660
Mark Salyzyn3e971272014-01-21 13:27:04 -08001661static int do_crypto_complete(char *mount_point UNUSED)
Ken Sumrall7f7dbaa2011-02-01 15:46:41 -08001662{
1663 struct crypt_mnt_ftr crypt_ftr;
Ken Sumrall29d8da82011-05-18 17:20:07 -07001664 char encrypted_state[PROPERTY_VALUE_MAX];
Ken Sumralle1a45852011-12-14 21:24:27 -08001665 char key_loc[PROPERTY_VALUE_MAX];
Ken Sumrall7f7dbaa2011-02-01 15:46:41 -08001666
1667 property_get("ro.crypto.state", encrypted_state, "");
1668 if (strcmp(encrypted_state, "encrypted") ) {
1669 SLOGE("not running with encryption, aborting");
Paul Lawrence74f29f12014-08-28 15:54:10 -07001670 return CRYPTO_COMPLETE_NOT_ENCRYPTED;
Ken Sumrall7f7dbaa2011-02-01 15:46:41 -08001671 }
1672
Ken Sumrall160b4d62013-04-22 12:15:39 -07001673 if (get_crypt_ftr_and_key(&crypt_ftr)) {
Ken Sumrall56ad03c2013-02-13 13:00:19 -08001674 fs_mgr_get_crypt_info(fstab, key_loc, 0, sizeof(key_loc));
Ken Sumralle5032c42012-04-01 23:58:44 -07001675
Ken Sumralle1a45852011-12-14 21:24:27 -08001676 /*
1677 * Only report this error if key_loc is a file and it exists.
1678 * If the device was never encrypted, and /data is not mountable for
1679 * some reason, returning 1 should prevent the UI from presenting the
1680 * a "enter password" screen, or worse, a "press button to wipe the
1681 * device" screen.
1682 */
1683 if ((key_loc[0] == '/') && (access("key_loc", F_OK) == -1)) {
1684 SLOGE("master key file does not exist, aborting");
Paul Lawrence74f29f12014-08-28 15:54:10 -07001685 return CRYPTO_COMPLETE_NOT_ENCRYPTED;
Ken Sumralle1a45852011-12-14 21:24:27 -08001686 } else {
1687 SLOGE("Error getting crypt footer and key\n");
Paul Lawrence74f29f12014-08-28 15:54:10 -07001688 return CRYPTO_COMPLETE_BAD_METADATA;
Ken Sumralle1a45852011-12-14 21:24:27 -08001689 }
Ken Sumrall7f7dbaa2011-02-01 15:46:41 -08001690 }
1691
Paul Lawrence74f29f12014-08-28 15:54:10 -07001692 // Test for possible error flags
1693 if (crypt_ftr.flags & CRYPT_ENCRYPTION_IN_PROGRESS){
1694 SLOGE("Encryption process is partway completed\n");
1695 return CRYPTO_COMPLETE_PARTIAL;
1696 }
1697
1698 if (crypt_ftr.flags & CRYPT_INCONSISTENT_STATE){
1699 SLOGE("Encryption process was interrupted but cannot continue\n");
1700 return CRYPTO_COMPLETE_INCONSISTENT;
1701 }
1702
1703 if (crypt_ftr.flags & CRYPT_DATA_CORRUPT){
1704 SLOGE("Encryption is successful but data is corrupt\n");
1705 return CRYPTO_COMPLETE_CORRUPT;
Ken Sumrall7f7dbaa2011-02-01 15:46:41 -08001706 }
1707
1708 /* We passed the test! We shall diminish, and return to the west */
Paul Lawrence74f29f12014-08-28 15:54:10 -07001709 return CRYPTO_COMPLETE_ENCRYPTED;
Ken Sumrall7f7dbaa2011-02-01 15:46:41 -08001710}
1711
Paul Lawrencef4faa572014-01-29 13:31:03 -08001712static int test_mount_encrypted_fs(struct crypt_mnt_ftr* crypt_ftr,
1713 char *passwd, char *mount_point, char *label)
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001714{
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001715 /* Allocate enough space for a 256 bit key, but we may use less */
Ken Sumrall160b4d62013-04-22 12:15:39 -07001716 unsigned char decrypted_master_key[32];
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001717 char crypto_blkdev[MAXPATHLEN];
1718 char real_blkdev[MAXPATHLEN];
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001719 char tmp_mount_point[64];
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001720 unsigned int orig_failed_decrypt_count;
1721 int rc;
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001722 int use_keymaster = 0;
1723 int upgrade = 0;
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001724 unsigned char* intermediate_key = 0;
1725 size_t intermediate_key_size = 0;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001726
Paul Lawrencef4faa572014-01-29 13:31:03 -08001727 SLOGD("crypt_ftr->fs_size = %lld\n", crypt_ftr->fs_size);
1728 orig_failed_decrypt_count = crypt_ftr->failed_decrypt_count;
Ken Sumrall0cc16632011-01-18 20:32:26 -08001729
Paul Lawrencef4faa572014-01-29 13:31:03 -08001730 if (! (crypt_ftr->flags & CRYPT_MNT_KEY_UNENCRYPTED) ) {
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001731 if (decrypt_master_key(passwd, decrypted_master_key, crypt_ftr,
1732 &intermediate_key, &intermediate_key_size)) {
JP Abgrall7bdfa522013-11-15 13:42:56 -08001733 SLOGE("Failed to decrypt master key\n");
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001734 rc = -1;
1735 goto errout;
JP Abgrall7bdfa522013-11-15 13:42:56 -08001736 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001737 }
1738
Paul Lawrencef4faa572014-01-29 13:31:03 -08001739 fs_mgr_get_crypt_info(fstab, 0, real_blkdev, sizeof(real_blkdev));
1740
Paul Lawrence74f29f12014-08-28 15:54:10 -07001741 // Create crypto block device - all (non fatal) code paths
1742 // need it
Paul Lawrencef4faa572014-01-29 13:31:03 -08001743 if (create_crypto_blk_dev(crypt_ftr, decrypted_master_key,
1744 real_blkdev, crypto_blkdev, label)) {
Paul Lawrence74f29f12014-08-28 15:54:10 -07001745 SLOGE("Error creating decrypted block device\n");
1746 rc = -1;
1747 goto errout;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001748 }
1749
Paul Lawrence74f29f12014-08-28 15:54:10 -07001750 /* Work out if the problem is the password or the data */
1751 unsigned char scrypted_intermediate_key[sizeof(crypt_ftr->
1752 scrypted_intermediate_key)];
1753 int N = 1 << crypt_ftr->N_factor;
1754 int r = 1 << crypt_ftr->r_factor;
1755 int p = 1 << crypt_ftr->p_factor;
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001756
Paul Lawrence74f29f12014-08-28 15:54:10 -07001757 rc = crypto_scrypt(intermediate_key, intermediate_key_size,
1758 crypt_ftr->salt, sizeof(crypt_ftr->salt),
1759 N, r, p, scrypted_intermediate_key,
1760 sizeof(scrypted_intermediate_key));
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001761
Paul Lawrence74f29f12014-08-28 15:54:10 -07001762 // Does the key match the crypto footer?
1763 if (rc == 0 && memcmp(scrypted_intermediate_key,
1764 crypt_ftr->scrypted_intermediate_key,
1765 sizeof(scrypted_intermediate_key)) == 0) {
1766 SLOGI("Password matches");
1767 rc = 0;
1768 } else {
1769 /* Try mounting the file system anyway, just in case the problem's with
1770 * the footer, not the key. */
1771 sprintf(tmp_mount_point, "%s/tmp_mnt", mount_point);
1772 mkdir(tmp_mount_point, 0755);
1773 if (fs_mgr_do_mount(fstab, DATA_MNT_POINT, crypto_blkdev, tmp_mount_point)) {
1774 SLOGE("Error temp mounting decrypted block device\n");
1775 delete_crypto_blk_dev(label);
1776
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001777 rc = ++crypt_ftr->failed_decrypt_count;
1778 put_crypt_ftr_and_key(crypt_ftr);
Paul Lawrence74f29f12014-08-28 15:54:10 -07001779 } else {
1780 /* Success! */
1781 SLOGI("Password did not match but decrypted drive mounted - continue");
1782 umount(tmp_mount_point);
1783 rc = 0;
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001784 }
Paul Lawrence74f29f12014-08-28 15:54:10 -07001785 }
1786
1787 if (rc == 0) {
1788 crypt_ftr->failed_decrypt_count = 0;
Paul Lawrence72b8b822014-10-05 12:57:37 -07001789 if (orig_failed_decrypt_count != 0) {
1790 put_crypt_ftr_and_key(crypt_ftr);
1791 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001792
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001793 /* Save the name of the crypto block device
Paul Lawrence74f29f12014-08-28 15:54:10 -07001794 * so we can mount it when restarting the framework. */
Ken Sumrall6864b7e2011-01-14 15:20:02 -08001795 property_set("ro.crypto.fs_crypto_blkdev", crypto_blkdev);
Jason parks70a4b3f2011-01-28 10:10:47 -06001796
1797 /* Also save a the master key so we can reencrypted the key
Paul Lawrence74f29f12014-08-28 15:54:10 -07001798 * the key when we want to change the password on it. */
Jason parks70a4b3f2011-01-28 10:10:47 -06001799 memcpy(saved_master_key, decrypted_master_key, KEY_LEN_BYTES);
Ken Sumrall3ad90722011-10-04 20:38:29 -07001800 saved_mount_point = strdup(mount_point);
Jason parks70a4b3f2011-01-28 10:10:47 -06001801 master_key_saved = 1;
JP Abgrall7bdfa522013-11-15 13:42:56 -08001802 SLOGD("%s(): Master key saved\n", __FUNCTION__);
Ken Sumrall6864b7e2011-01-14 15:20:02 -08001803 rc = 0;
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001804
Paul Lawrence74f29f12014-08-28 15:54:10 -07001805 // Upgrade if we're not using the latest KDF.
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001806 use_keymaster = keymaster_check_compatibility();
1807 if (crypt_ftr->kdf_type == KDF_SCRYPT_KEYMASTER) {
Shawn Willden47ba10d2014-09-03 17:07:06 -06001808 // Don't allow downgrade
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001809 } else if (use_keymaster == 1 && crypt_ftr->kdf_type != KDF_SCRYPT_KEYMASTER) {
1810 crypt_ftr->kdf_type = KDF_SCRYPT_KEYMASTER;
1811 upgrade = 1;
1812 } else if (use_keymaster == 0 && crypt_ftr->kdf_type != KDF_SCRYPT) {
Paul Lawrencef4faa572014-01-29 13:31:03 -08001813 crypt_ftr->kdf_type = KDF_SCRYPT;
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001814 upgrade = 1;
1815 }
1816
1817 if (upgrade) {
Paul Lawrencef4faa572014-01-29 13:31:03 -08001818 rc = encrypt_master_key(passwd, crypt_ftr->salt, saved_master_key,
1819 crypt_ftr->master_key, crypt_ftr);
JP Abgrall7bdfa522013-11-15 13:42:56 -08001820 if (!rc) {
Paul Lawrencef4faa572014-01-29 13:31:03 -08001821 rc = put_crypt_ftr_and_key(crypt_ftr);
JP Abgrall7bdfa522013-11-15 13:42:56 -08001822 }
1823 SLOGD("Key Derivation Function upgrade: rc=%d\n", rc);
Paul Lawrenceb2f682b2014-09-08 11:28:19 -07001824
1825 // Do not fail even if upgrade failed - machine is bootable
1826 // Note that if this code is ever hit, there is a *serious* problem
1827 // since KDFs should never fail. You *must* fix the kdf before
1828 // proceeding!
1829 if (rc) {
1830 SLOGW("Upgrade failed with error %d,"
1831 " but continuing with previous state",
1832 rc);
1833 rc = 0;
1834 }
JP Abgrall7bdfa522013-11-15 13:42:56 -08001835 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001836 }
1837
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001838 errout:
1839 if (intermediate_key) {
1840 memset(intermediate_key, 0, intermediate_key_size);
1841 free(intermediate_key);
1842 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001843 return rc;
1844}
1845
Ken Sumrall0b8b5972011-08-31 16:14:23 -07001846/* Called by vold when it wants to undo the crypto mapping of a volume it
1847 * manages. This is usually in response to a factory reset, when we want
1848 * to undo the crypto mapping so the volume is formatted in the clear.
1849 */
1850int cryptfs_revert_volume(const char *label)
1851{
1852 return delete_crypto_blk_dev((char *)label);
1853}
1854
Ken Sumrall29d8da82011-05-18 17:20:07 -07001855/*
1856 * Called by vold when it's asked to mount an encrypted, nonremovable volume.
1857 * Setup a dm-crypt mapping, use the saved master key from
1858 * setting up the /data mapping, and return the new device path.
1859 */
1860int cryptfs_setup_volume(const char *label, int major, int minor,
1861 char *crypto_sys_path, unsigned int max_path,
1862 int *new_major, int *new_minor)
1863{
1864 char real_blkdev[MAXPATHLEN], crypto_blkdev[MAXPATHLEN];
1865 struct crypt_mnt_ftr sd_crypt_ftr;
Ken Sumrall29d8da82011-05-18 17:20:07 -07001866 struct stat statbuf;
Tim Murray8439dc92014-12-15 11:56:11 -08001867 unsigned int nr_sec;
1868 int fd;
Ken Sumrall29d8da82011-05-18 17:20:07 -07001869
1870 sprintf(real_blkdev, "/dev/block/vold/%d:%d", major, minor);
1871
Ken Sumrall160b4d62013-04-22 12:15:39 -07001872 get_crypt_ftr_and_key(&sd_crypt_ftr);
Ken Sumrall29d8da82011-05-18 17:20:07 -07001873
1874 /* Update the fs_size field to be the size of the volume */
1875 fd = open(real_blkdev, O_RDONLY);
1876 nr_sec = get_blkdev_size(fd);
1877 close(fd);
1878 if (nr_sec == 0) {
1879 SLOGE("Cannot get size of volume %s\n", real_blkdev);
1880 return -1;
1881 }
1882
1883 sd_crypt_ftr.fs_size = nr_sec;
1884 create_crypto_blk_dev(&sd_crypt_ftr, saved_master_key, real_blkdev,
1885 crypto_blkdev, label);
1886
1887 stat(crypto_blkdev, &statbuf);
1888 *new_major = MAJOR(statbuf.st_rdev);
1889 *new_minor = MINOR(statbuf.st_rdev);
1890
1891 /* Create path to sys entry for this block device */
1892 snprintf(crypto_sys_path, max_path, "/devices/virtual/block/%s", strrchr(crypto_blkdev, '/')+1);
1893
1894 return 0;
1895}
1896
Ken Sumrall7f7dbaa2011-02-01 15:46:41 -08001897int cryptfs_crypto_complete(void)
1898{
1899 return do_crypto_complete("/data");
1900}
1901
Paul Lawrencef4faa572014-01-29 13:31:03 -08001902int check_unmounted_and_get_ftr(struct crypt_mnt_ftr* crypt_ftr)
1903{
1904 char encrypted_state[PROPERTY_VALUE_MAX];
1905 property_get("ro.crypto.state", encrypted_state, "");
1906 if ( master_key_saved || strcmp(encrypted_state, "encrypted") ) {
1907 SLOGE("encrypted fs already validated or not running with encryption,"
1908 " aborting");
1909 return -1;
1910 }
1911
1912 if (get_crypt_ftr_and_key(crypt_ftr)) {
1913 SLOGE("Error getting crypt footer and key");
1914 return -1;
1915 }
1916
1917 return 0;
1918}
1919
Paul Lawrencefc615042014-10-04 15:32:29 -07001920/*
1921 * TODO - transition patterns to new format in calling code
1922 * and remove this vile hack, and the use of hex in
1923 * the password passing code.
1924 *
1925 * Patterns are passed in zero based (i.e. the top left dot
1926 * is represented by zero, the top middle one etc), but we want
1927 * to store them '1' based.
1928 * This is to allow us to migrate the calling code to use this
1929 * convention. It also solves a nasty problem whereby scrypt ignores
1930 * trailing zeros, so patterns ending at the top left could be
1931 * truncated, and similarly, you could add the top left to any
1932 * pattern and still match.
1933 * adjust_passwd is a hack function that returns the alternate representation
1934 * if the password appears to be a pattern (hex numbers all less than 09)
1935 * If it succeeds we need to try both, and in particular try the alternate
1936 * first. If the original matches, then we need to update the footer
1937 * with the alternate.
1938 * All code that accepts passwords must adjust them first. Since
1939 * cryptfs_check_passwd is always the first function called after a migration
1940 * (and indeed on any boot) we only need to do the double try in this
1941 * function.
1942 */
1943char* adjust_passwd(const char* passwd)
1944{
1945 size_t index, length;
1946
1947 if (!passwd) {
1948 return 0;
1949 }
1950
1951 // Check even length. Hex encoded passwords are always
1952 // an even length, since each character encodes to two characters.
1953 length = strlen(passwd);
1954 if (length % 2) {
1955 SLOGW("Password not correctly hex encoded.");
1956 return 0;
1957 }
1958
1959 // Check password is old-style pattern - a collection of hex
1960 // encoded bytes less than 9 (00 through 08)
1961 for (index = 0; index < length; index +=2) {
1962 if (passwd[index] != '0'
1963 || passwd[index + 1] < '0' || passwd[index + 1] > '8') {
1964 return 0;
1965 }
1966 }
1967
1968 // Allocate room for adjusted passwd and null terminate
1969 char* adjusted = malloc(length + 1);
1970 adjusted[length] = 0;
1971
1972 // Add 0x31 ('1') to each character
1973 for (index = 0; index < length; index += 2) {
1974 // output is 31 through 39 so set first byte to three, second to src + 1
1975 adjusted[index] = '3';
1976 adjusted[index + 1] = passwd[index + 1] + 1;
1977 }
1978
1979 return adjusted;
1980}
1981
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001982int cryptfs_check_passwd(char *passwd)
1983{
Paul Lawrencef4faa572014-01-29 13:31:03 -08001984 struct crypt_mnt_ftr crypt_ftr;
1985 int rc;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001986
Paul Lawrencef4faa572014-01-29 13:31:03 -08001987 rc = check_unmounted_and_get_ftr(&crypt_ftr);
1988 if (rc)
1989 return rc;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001990
Paul Lawrencefc615042014-10-04 15:32:29 -07001991 char* adjusted_passwd = adjust_passwd(passwd);
1992 if (adjusted_passwd) {
1993 int failed_decrypt_count = crypt_ftr.failed_decrypt_count;
1994 rc = test_mount_encrypted_fs(&crypt_ftr, adjusted_passwd,
1995 DATA_MNT_POINT, "userdata");
1996
1997 // Maybe the original one still works?
1998 if (rc) {
1999 // Don't double count this failure
2000 crypt_ftr.failed_decrypt_count = failed_decrypt_count;
2001 rc = test_mount_encrypted_fs(&crypt_ftr, passwd,
2002 DATA_MNT_POINT, "userdata");
2003 if (!rc) {
2004 // cryptfs_changepw also adjusts so pass original
2005 // Note that adjust_passwd only recognises patterns
2006 // so we can safely use CRYPT_TYPE_PATTERN
2007 SLOGI("Updating pattern to new format");
2008 cryptfs_changepw(CRYPT_TYPE_PATTERN, passwd);
2009 }
2010 }
2011 free(adjusted_passwd);
2012 } else {
2013 rc = test_mount_encrypted_fs(&crypt_ftr, passwd,
2014 DATA_MNT_POINT, "userdata");
2015 }
Paul Lawrence684dbdf2014-02-07 12:07:22 -08002016
2017 if (rc == 0 && crypt_ftr.crypt_type != CRYPT_TYPE_DEFAULT) {
Paul Lawrence399317e2014-03-10 13:20:50 -07002018 cryptfs_clear_password();
2019 password = strdup(passwd);
2020 struct timespec now;
2021 clock_gettime(CLOCK_BOOTTIME, &now);
2022 password_expiry_time = now.tv_sec + password_max_age_seconds;
Paul Lawrence684dbdf2014-02-07 12:07:22 -08002023 }
2024
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002025 return rc;
2026}
2027
Ken Sumrall3ad90722011-10-04 20:38:29 -07002028int cryptfs_verify_passwd(char *passwd)
2029{
2030 struct crypt_mnt_ftr crypt_ftr;
2031 /* Allocate enough space for a 256 bit key, but we may use less */
Ken Sumrall160b4d62013-04-22 12:15:39 -07002032 unsigned char decrypted_master_key[32];
Ken Sumrall3ad90722011-10-04 20:38:29 -07002033 char encrypted_state[PROPERTY_VALUE_MAX];
2034 int rc;
2035
2036 property_get("ro.crypto.state", encrypted_state, "");
2037 if (strcmp(encrypted_state, "encrypted") ) {
2038 SLOGE("device not encrypted, aborting");
2039 return -2;
2040 }
2041
2042 if (!master_key_saved) {
2043 SLOGE("encrypted fs not yet mounted, aborting");
2044 return -1;
2045 }
2046
2047 if (!saved_mount_point) {
2048 SLOGE("encrypted fs failed to save mount point, aborting");
2049 return -1;
2050 }
2051
Ken Sumrall160b4d62013-04-22 12:15:39 -07002052 if (get_crypt_ftr_and_key(&crypt_ftr)) {
Ken Sumrall3ad90722011-10-04 20:38:29 -07002053 SLOGE("Error getting crypt footer and key\n");
2054 return -1;
2055 }
2056
2057 if (crypt_ftr.flags & CRYPT_MNT_KEY_UNENCRYPTED) {
2058 /* If the device has no password, then just say the password is valid */
2059 rc = 0;
2060 } else {
Paul Lawrencefc615042014-10-04 15:32:29 -07002061 char* adjusted_passwd = adjust_passwd(passwd);
2062 if (adjusted_passwd) {
2063 passwd = adjusted_passwd;
2064 }
2065
Paul Lawrenced0c7b172014-08-08 14:28:10 -07002066 decrypt_master_key(passwd, decrypted_master_key, &crypt_ftr, 0, 0);
Ken Sumrall3ad90722011-10-04 20:38:29 -07002067 if (!memcmp(decrypted_master_key, saved_master_key, crypt_ftr.keysize)) {
2068 /* They match, the password is correct */
2069 rc = 0;
2070 } else {
2071 /* If incorrect, sleep for a bit to prevent dictionary attacks */
2072 sleep(1);
2073 rc = 1;
2074 }
Paul Lawrencefc615042014-10-04 15:32:29 -07002075
2076 free(adjusted_passwd);
Ken Sumrall3ad90722011-10-04 20:38:29 -07002077 }
2078
2079 return rc;
2080}
2081
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002082/* Initialize a crypt_mnt_ftr structure. The keysize is
2083 * defaulted to 16 bytes, and the filesystem size to 0.
2084 * Presumably, at a minimum, the caller will update the
2085 * filesystem size and crypto_type_name after calling this function.
2086 */
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07002087static int cryptfs_init_crypt_mnt_ftr(struct crypt_mnt_ftr *ftr)
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002088{
Ken Sumrall160b4d62013-04-22 12:15:39 -07002089 off64_t off;
2090
2091 memset(ftr, 0, sizeof(struct crypt_mnt_ftr));
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002092 ftr->magic = CRYPT_MNT_MAGIC;
Kenny Rootc96a5f82013-06-14 12:08:28 -07002093 ftr->major_version = CURRENT_MAJOR_VERSION;
2094 ftr->minor_version = CURRENT_MINOR_VERSION;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002095 ftr->ftr_size = sizeof(struct crypt_mnt_ftr);
Jason parks70a4b3f2011-01-28 10:10:47 -06002096 ftr->keysize = KEY_LEN_BYTES;
Ken Sumrall160b4d62013-04-22 12:15:39 -07002097
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07002098 switch (keymaster_check_compatibility()) {
2099 case 1:
2100 ftr->kdf_type = KDF_SCRYPT_KEYMASTER;
2101 break;
2102
2103 case 0:
2104 ftr->kdf_type = KDF_SCRYPT;
2105 break;
2106
2107 default:
2108 SLOGE("keymaster_check_compatibility failed");
2109 return -1;
2110 }
2111
Kenny Rootc4c70f12013-06-14 12:11:38 -07002112 get_device_scrypt_params(ftr);
2113
Ken Sumrall160b4d62013-04-22 12:15:39 -07002114 ftr->persist_data_size = CRYPT_PERSIST_DATA_SIZE;
2115 if (get_crypt_ftr_info(NULL, &off) == 0) {
2116 ftr->persist_data_offset[0] = off + CRYPT_FOOTER_TO_PERSIST_OFFSET;
2117 ftr->persist_data_offset[1] = off + CRYPT_FOOTER_TO_PERSIST_OFFSET +
2118 ftr->persist_data_size;
2119 }
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07002120
2121 return 0;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002122}
2123
Ken Sumrall29d8da82011-05-18 17:20:07 -07002124static int cryptfs_enable_wipe(char *crypto_blkdev, off64_t size, int type)
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002125{
Ken Sumralle550f782013-08-20 13:48:23 -07002126 const char *args[10];
2127 char size_str[32]; /* Must be large enough to hold a %lld and null byte */
2128 int num_args;
2129 int status;
2130 int tmp;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002131 int rc = -1;
2132
Ken Sumrall29d8da82011-05-18 17:20:07 -07002133 if (type == EXT4_FS) {
Ken Sumralle550f782013-08-20 13:48:23 -07002134 args[0] = "/system/bin/make_ext4fs";
2135 args[1] = "-a";
2136 args[2] = "/data";
2137 args[3] = "-l";
Elliott Hughes73737162014-06-25 17:27:42 -07002138 snprintf(size_str, sizeof(size_str), "%" PRId64, size * 512);
Ken Sumralle550f782013-08-20 13:48:23 -07002139 args[4] = size_str;
2140 args[5] = crypto_blkdev;
2141 num_args = 6;
2142 SLOGI("Making empty filesystem with command %s %s %s %s %s %s\n",
2143 args[0], args[1], args[2], args[3], args[4], args[5]);
JP Abgrall62c7af32014-06-16 13:01:23 -07002144 } else if (type == F2FS_FS) {
2145 args[0] = "/system/bin/mkfs.f2fs";
2146 args[1] = "-t";
2147 args[2] = "-d1";
2148 args[3] = crypto_blkdev;
Elliott Hughes73737162014-06-25 17:27:42 -07002149 snprintf(size_str, sizeof(size_str), "%" PRId64, size);
JP Abgrall62c7af32014-06-16 13:01:23 -07002150 args[4] = size_str;
2151 num_args = 5;
2152 SLOGI("Making empty filesystem with command %s %s %s %s %s\n",
2153 args[0], args[1], args[2], args[3], args[4]);
Ken Sumrall29d8da82011-05-18 17:20:07 -07002154 } else {
2155 SLOGE("cryptfs_enable_wipe(): unknown filesystem type %d\n", type);
2156 return -1;
2157 }
2158
Ken Sumralle550f782013-08-20 13:48:23 -07002159 tmp = android_fork_execvp(num_args, (char **)args, &status, false, true);
2160
2161 if (tmp != 0) {
2162 SLOGE("Error creating empty filesystem on %s due to logwrap error\n", crypto_blkdev);
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002163 } else {
Ken Sumralle550f782013-08-20 13:48:23 -07002164 if (WIFEXITED(status)) {
2165 if (WEXITSTATUS(status)) {
2166 SLOGE("Error creating filesystem on %s, exit status %d ",
2167 crypto_blkdev, WEXITSTATUS(status));
2168 } else {
2169 SLOGD("Successfully created filesystem on %s\n", crypto_blkdev);
2170 rc = 0;
2171 }
2172 } else {
2173 SLOGE("Error creating filesystem on %s, did not exit normally\n", crypto_blkdev);
2174 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002175 }
2176
2177 return rc;
2178}
2179
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002180#define CRYPT_INPLACE_BUFSIZE 4096
Paul Lawrence87999172014-02-20 12:21:31 -08002181#define CRYPT_SECTORS_PER_BUFSIZE (CRYPT_INPLACE_BUFSIZE / CRYPT_SECTOR_SIZE)
2182#define CRYPT_SECTOR_SIZE 512
Paul Lawrenceae59fe62014-01-21 08:23:27 -08002183
2184/* aligned 32K writes tends to make flash happy.
2185 * SD card association recommends it.
2186 */
2187#define BLOCKS_AT_A_TIME 8
2188
2189struct encryptGroupsData
2190{
2191 int realfd;
2192 int cryptofd;
2193 off64_t numblocks;
2194 off64_t one_pct, cur_pct, new_pct;
2195 off64_t blocks_already_done, tot_numblocks;
Paul Lawrence58c58cf2014-06-04 13:12:21 -07002196 off64_t used_blocks_already_done, tot_used_blocks;
Paul Lawrenceae59fe62014-01-21 08:23:27 -08002197 char* real_blkdev, * crypto_blkdev;
2198 int count;
2199 off64_t offset;
2200 char* buffer;
Paul Lawrence87999172014-02-20 12:21:31 -08002201 off64_t last_written_sector;
2202 int completed;
Paul Lawrencea96d9c92014-06-04 14:05:01 -07002203 time_t time_started;
2204 int remaining_time;
Paul Lawrenceae59fe62014-01-21 08:23:27 -08002205};
2206
Paul Lawrence58c58cf2014-06-04 13:12:21 -07002207static void update_progress(struct encryptGroupsData* data, int is_used)
Paul Lawrenceae59fe62014-01-21 08:23:27 -08002208{
2209 data->blocks_already_done++;
Paul Lawrence58c58cf2014-06-04 13:12:21 -07002210
2211 if (is_used) {
2212 data->used_blocks_already_done++;
2213 }
Paul Lawrence58c58cf2014-06-04 13:12:21 -07002214 if (data->tot_used_blocks) {
2215 data->new_pct = data->used_blocks_already_done / data->one_pct;
2216 } else {
2217 data->new_pct = data->blocks_already_done / data->one_pct;
2218 }
2219
Paul Lawrenceae59fe62014-01-21 08:23:27 -08002220 if (data->new_pct > data->cur_pct) {
2221 char buf[8];
2222 data->cur_pct = data->new_pct;
Elliott Hughescb33f572014-06-25 18:25:11 -07002223 snprintf(buf, sizeof(buf), "%" PRId64, data->cur_pct);
Paul Lawrenceae59fe62014-01-21 08:23:27 -08002224 property_set("vold.encrypt_progress", buf);
2225 }
Paul Lawrencea96d9c92014-06-04 14:05:01 -07002226
2227 if (data->cur_pct >= 5) {
Paul Lawrence9c58a872014-09-30 09:12:51 -07002228 struct timespec time_now;
2229 if (clock_gettime(CLOCK_MONOTONIC, &time_now)) {
2230 SLOGW("Error getting time");
2231 } else {
2232 double elapsed_time = difftime(time_now.tv_sec, data->time_started);
2233 off64_t remaining_blocks = data->tot_used_blocks
2234 - data->used_blocks_already_done;
2235 int remaining_time = (int)(elapsed_time * remaining_blocks
2236 / data->used_blocks_already_done);
Paul Lawrence71577502014-08-13 14:55:55 -07002237
Paul Lawrence9c58a872014-09-30 09:12:51 -07002238 // Change time only if not yet set, lower, or a lot higher for
2239 // best user experience
2240 if (data->remaining_time == -1
2241 || remaining_time < data->remaining_time
2242 || remaining_time > data->remaining_time + 60) {
2243 char buf[8];
2244 snprintf(buf, sizeof(buf), "%d", remaining_time);
2245 property_set("vold.encrypt_time_remaining", buf);
2246 data->remaining_time = remaining_time;
2247 }
Paul Lawrencea96d9c92014-06-04 14:05:01 -07002248 }
2249 }
Paul Lawrenceae59fe62014-01-21 08:23:27 -08002250}
2251
Paul Lawrence3846be12014-09-22 11:33:54 -07002252static void log_progress(struct encryptGroupsData const* data, bool completed)
2253{
2254 // Precondition - if completed data = 0 else data != 0
2255
2256 // Track progress so we can skip logging blocks
2257 static off64_t offset = -1;
2258
2259 // Need to close existing 'Encrypting from' log?
2260 if (completed || (offset != -1 && data->offset != offset)) {
2261 SLOGI("Encrypted to sector %" PRId64,
2262 offset / info.block_size * CRYPT_SECTOR_SIZE);
2263 offset = -1;
2264 }
2265
2266 // Need to start new 'Encrypting from' log?
2267 if (!completed && offset != data->offset) {
2268 SLOGI("Encrypting from sector %" PRId64,
2269 data->offset / info.block_size * CRYPT_SECTOR_SIZE);
2270 }
2271
2272 // Update offset
2273 if (!completed) {
2274 offset = data->offset + (off64_t)data->count * info.block_size;
2275 }
2276}
2277
Paul Lawrenceae59fe62014-01-21 08:23:27 -08002278static int flush_outstanding_data(struct encryptGroupsData* data)
2279{
2280 if (data->count == 0) {
2281 return 0;
2282 }
2283
Elliott Hughes231bdba2014-06-25 18:36:19 -07002284 SLOGV("Copying %d blocks at offset %" PRIx64, data->count, data->offset);
Paul Lawrenceae59fe62014-01-21 08:23:27 -08002285
2286 if (pread64(data->realfd, data->buffer,
2287 info.block_size * data->count, data->offset)
2288 <= 0) {
2289 SLOGE("Error reading real_blkdev %s for inplace encrypt",
2290 data->real_blkdev);
2291 return -1;
2292 }
2293
2294 if (pwrite64(data->cryptofd, data->buffer,
2295 info.block_size * data->count, data->offset)
2296 <= 0) {
2297 SLOGE("Error writing crypto_blkdev %s for inplace encrypt",
2298 data->crypto_blkdev);
2299 return -1;
Paul Lawrence87999172014-02-20 12:21:31 -08002300 } else {
Paul Lawrence3846be12014-09-22 11:33:54 -07002301 log_progress(data, false);
Paul Lawrenceae59fe62014-01-21 08:23:27 -08002302 }
2303
2304 data->count = 0;
Paul Lawrence87999172014-02-20 12:21:31 -08002305 data->last_written_sector = (data->offset + data->count)
2306 / info.block_size * CRYPT_SECTOR_SIZE - 1;
Paul Lawrenceae59fe62014-01-21 08:23:27 -08002307 return 0;
2308}
2309
2310static int encrypt_groups(struct encryptGroupsData* data)
2311{
2312 unsigned int i;
2313 u8 *block_bitmap = 0;
2314 unsigned int block;
2315 off64_t ret;
2316 int rc = -1;
2317
2318 data->buffer = malloc(info.block_size * BLOCKS_AT_A_TIME);
2319 if (!data->buffer) {
2320 SLOGE("Failed to allocate crypto buffer");
2321 goto errout;
2322 }
2323
2324 block_bitmap = malloc(info.block_size);
2325 if (!block_bitmap) {
2326 SLOGE("failed to allocate block bitmap");
2327 goto errout;
2328 }
2329
2330 for (i = 0; i < aux_info.groups; ++i) {
2331 SLOGI("Encrypting group %d", i);
2332
2333 u32 first_block = aux_info.first_data_block + i * info.blocks_per_group;
2334 u32 block_count = min(info.blocks_per_group,
2335 aux_info.len_blocks - first_block);
2336
2337 off64_t offset = (u64)info.block_size
2338 * aux_info.bg_desc[i].bg_block_bitmap;
2339
2340 ret = pread64(data->realfd, block_bitmap, info.block_size, offset);
2341 if (ret != (int)info.block_size) {
2342 SLOGE("failed to read all of block group bitmap %d", i);
2343 goto errout;
2344 }
2345
2346 offset = (u64)info.block_size * first_block;
2347
2348 data->count = 0;
2349
2350 for (block = 0; block < block_count; block++) {
Paul Lawrence58c58cf2014-06-04 13:12:21 -07002351 int used = bitmap_get_bit(block_bitmap, block);
2352 update_progress(data, used);
2353 if (used) {
Paul Lawrenceae59fe62014-01-21 08:23:27 -08002354 if (data->count == 0) {
2355 data->offset = offset;
2356 }
2357 data->count++;
2358 } else {
2359 if (flush_outstanding_data(data)) {
2360 goto errout;
2361 }
2362 }
2363
2364 offset += info.block_size;
2365
2366 /* Write data if we are aligned or buffer size reached */
2367 if (offset % (info.block_size * BLOCKS_AT_A_TIME) == 0
2368 || data->count == BLOCKS_AT_A_TIME) {
2369 if (flush_outstanding_data(data)) {
2370 goto errout;
2371 }
2372 }
Paul Lawrence87999172014-02-20 12:21:31 -08002373
Paul Lawrence73d7a022014-06-09 14:10:09 -07002374 if (!is_battery_ok_to_continue()) {
Paul Lawrence87999172014-02-20 12:21:31 -08002375 SLOGE("Stopping encryption due to low battery");
2376 rc = 0;
2377 goto errout;
2378 }
2379
Paul Lawrenceae59fe62014-01-21 08:23:27 -08002380 }
2381 if (flush_outstanding_data(data)) {
2382 goto errout;
2383 }
2384 }
2385
Paul Lawrence87999172014-02-20 12:21:31 -08002386 data->completed = 1;
Paul Lawrenceae59fe62014-01-21 08:23:27 -08002387 rc = 0;
2388
2389errout:
Paul Lawrence3846be12014-09-22 11:33:54 -07002390 log_progress(0, true);
Paul Lawrenceae59fe62014-01-21 08:23:27 -08002391 free(data->buffer);
2392 free(block_bitmap);
2393 return rc;
2394}
2395
2396static int cryptfs_enable_inplace_ext4(char *crypto_blkdev,
2397 char *real_blkdev,
2398 off64_t size,
2399 off64_t *size_already_done,
Paul Lawrence87999172014-02-20 12:21:31 -08002400 off64_t tot_size,
2401 off64_t previously_encrypted_upto)
Paul Lawrenceae59fe62014-01-21 08:23:27 -08002402{
Paul Lawrence58c58cf2014-06-04 13:12:21 -07002403 u32 i;
Paul Lawrenceae59fe62014-01-21 08:23:27 -08002404 struct encryptGroupsData data;
Paul Lawrence74f29f12014-08-28 15:54:10 -07002405 int rc; // Can't initialize without causing warning -Wclobbered
Paul Lawrenceae59fe62014-01-21 08:23:27 -08002406
Paul Lawrence87999172014-02-20 12:21:31 -08002407 if (previously_encrypted_upto > *size_already_done) {
2408 SLOGD("Not fast encrypting since resuming part way through");
2409 return -1;
2410 }
2411
Paul Lawrenceae59fe62014-01-21 08:23:27 -08002412 memset(&data, 0, sizeof(data));
2413 data.real_blkdev = real_blkdev;
2414 data.crypto_blkdev = crypto_blkdev;
2415
2416 if ( (data.realfd = open(real_blkdev, O_RDWR)) < 0) {
JP Abgrall77768712014-10-10 15:52:11 -07002417 SLOGE("Error opening real_blkdev %s for inplace encrypt. err=%d(%s)\n",
2418 real_blkdev, errno, strerror(errno));
Paul Lawrence74f29f12014-08-28 15:54:10 -07002419 rc = -1;
Paul Lawrenceae59fe62014-01-21 08:23:27 -08002420 goto errout;
2421 }
2422
2423 if ( (data.cryptofd = open(crypto_blkdev, O_WRONLY)) < 0) {
JP Abgrall512f0d52014-10-10 18:43:41 -07002424 SLOGE("Error opening crypto_blkdev %s for ext4 inplace encrypt. err=%d(%s)\n",
JP Abgrall77768712014-10-10 15:52:11 -07002425 crypto_blkdev, errno, strerror(errno));
JP Abgrall512f0d52014-10-10 18:43:41 -07002426 rc = ENABLE_INPLACE_ERR_DEV;
Paul Lawrenceae59fe62014-01-21 08:23:27 -08002427 goto errout;
2428 }
2429
2430 if (setjmp(setjmp_env)) {
JP Abgrall512f0d52014-10-10 18:43:41 -07002431 SLOGE("Reading ext4 extent caused an exception\n");
Paul Lawrence74f29f12014-08-28 15:54:10 -07002432 rc = -1;
Paul Lawrenceae59fe62014-01-21 08:23:27 -08002433 goto errout;
2434 }
2435
2436 if (read_ext(data.realfd, 0) != 0) {
JP Abgrall512f0d52014-10-10 18:43:41 -07002437 SLOGE("Failed to read ext4 extent\n");
Paul Lawrence74f29f12014-08-28 15:54:10 -07002438 rc = -1;
Paul Lawrenceae59fe62014-01-21 08:23:27 -08002439 goto errout;
2440 }
2441
2442 data.numblocks = size / CRYPT_SECTORS_PER_BUFSIZE;
2443 data.tot_numblocks = tot_size / CRYPT_SECTORS_PER_BUFSIZE;
2444 data.blocks_already_done = *size_already_done / CRYPT_SECTORS_PER_BUFSIZE;
2445
JP Abgrall512f0d52014-10-10 18:43:41 -07002446 SLOGI("Encrypting ext4 filesystem in place...");
Paul Lawrenceae59fe62014-01-21 08:23:27 -08002447
Paul Lawrence58c58cf2014-06-04 13:12:21 -07002448 data.tot_used_blocks = data.numblocks;
2449 for (i = 0; i < aux_info.groups; ++i) {
2450 data.tot_used_blocks -= aux_info.bg_desc[i].bg_free_blocks_count;
2451 }
2452
2453 data.one_pct = data.tot_used_blocks / 100;
Paul Lawrenceae59fe62014-01-21 08:23:27 -08002454 data.cur_pct = 0;
Paul Lawrence9c58a872014-09-30 09:12:51 -07002455
2456 struct timespec time_started = {0};
2457 if (clock_gettime(CLOCK_MONOTONIC, &time_started)) {
2458 SLOGW("Error getting time at start");
2459 // Note - continue anyway - we'll run with 0
2460 }
2461 data.time_started = time_started.tv_sec;
Paul Lawrencea96d9c92014-06-04 14:05:01 -07002462 data.remaining_time = -1;
Paul Lawrenceae59fe62014-01-21 08:23:27 -08002463
2464 rc = encrypt_groups(&data);
2465 if (rc) {
2466 SLOGE("Error encrypting groups");
2467 goto errout;
2468 }
2469
Paul Lawrence87999172014-02-20 12:21:31 -08002470 *size_already_done += data.completed ? size : data.last_written_sector;
Paul Lawrenceae59fe62014-01-21 08:23:27 -08002471 rc = 0;
2472
2473errout:
2474 close(data.realfd);
2475 close(data.cryptofd);
2476
2477 return rc;
2478}
2479
Paul Lawrence3846be12014-09-22 11:33:54 -07002480static void log_progress_f2fs(u64 block, bool completed)
2481{
2482 // Precondition - if completed data = 0 else data != 0
2483
2484 // Track progress so we can skip logging blocks
2485 static u64 last_block = (u64)-1;
2486
2487 // Need to close existing 'Encrypting from' log?
2488 if (completed || (last_block != (u64)-1 && block != last_block + 1)) {
2489 SLOGI("Encrypted to block %" PRId64, last_block);
2490 last_block = -1;
2491 }
2492
2493 // Need to start new 'Encrypting from' log?
2494 if (!completed && (last_block == (u64)-1 || block != last_block + 1)) {
2495 SLOGI("Encrypting from block %" PRId64, block);
2496 }
2497
2498 // Update offset
2499 if (!completed) {
2500 last_block = block;
2501 }
2502}
2503
Daniel Rosenberge82df162014-08-15 22:19:23 +00002504static int encrypt_one_block_f2fs(u64 pos, void *data)
2505{
2506 struct encryptGroupsData *priv_dat = (struct encryptGroupsData *)data;
2507
2508 priv_dat->blocks_already_done = pos - 1;
2509 update_progress(priv_dat, 1);
2510
2511 off64_t offset = pos * CRYPT_INPLACE_BUFSIZE;
2512
2513 if (pread64(priv_dat->realfd, priv_dat->buffer, CRYPT_INPLACE_BUFSIZE, offset) <= 0) {
JP Abgrall512f0d52014-10-10 18:43:41 -07002514 SLOGE("Error reading real_blkdev %s for f2fs inplace encrypt", priv_dat->crypto_blkdev);
Daniel Rosenberge82df162014-08-15 22:19:23 +00002515 return -1;
2516 }
2517
2518 if (pwrite64(priv_dat->cryptofd, priv_dat->buffer, CRYPT_INPLACE_BUFSIZE, offset) <= 0) {
JP Abgrall512f0d52014-10-10 18:43:41 -07002519 SLOGE("Error writing crypto_blkdev %s for f2fs inplace encrypt", priv_dat->crypto_blkdev);
Daniel Rosenberge82df162014-08-15 22:19:23 +00002520 return -1;
2521 } else {
Paul Lawrence3846be12014-09-22 11:33:54 -07002522 log_progress_f2fs(pos, false);
Daniel Rosenberge82df162014-08-15 22:19:23 +00002523 }
2524
2525 return 0;
2526}
2527
2528static int cryptfs_enable_inplace_f2fs(char *crypto_blkdev,
2529 char *real_blkdev,
2530 off64_t size,
2531 off64_t *size_already_done,
2532 off64_t tot_size,
2533 off64_t previously_encrypted_upto)
2534{
Daniel Rosenberge82df162014-08-15 22:19:23 +00002535 struct encryptGroupsData data;
2536 struct f2fs_info *f2fs_info = NULL;
JP Abgrall512f0d52014-10-10 18:43:41 -07002537 int rc = ENABLE_INPLACE_ERR_OTHER;
Daniel Rosenberge82df162014-08-15 22:19:23 +00002538 if (previously_encrypted_upto > *size_already_done) {
2539 SLOGD("Not fast encrypting since resuming part way through");
JP Abgrall512f0d52014-10-10 18:43:41 -07002540 return ENABLE_INPLACE_ERR_OTHER;
Daniel Rosenberge82df162014-08-15 22:19:23 +00002541 }
2542 memset(&data, 0, sizeof(data));
2543 data.real_blkdev = real_blkdev;
2544 data.crypto_blkdev = crypto_blkdev;
2545 data.realfd = -1;
2546 data.cryptofd = -1;
2547 if ( (data.realfd = open64(real_blkdev, O_RDWR)) < 0) {
JP Abgrall512f0d52014-10-10 18:43:41 -07002548 SLOGE("Error opening real_blkdev %s for f2fs inplace encrypt\n",
Daniel Rosenberge82df162014-08-15 22:19:23 +00002549 real_blkdev);
2550 goto errout;
2551 }
2552 if ( (data.cryptofd = open64(crypto_blkdev, O_WRONLY)) < 0) {
JP Abgrall512f0d52014-10-10 18:43:41 -07002553 SLOGE("Error opening crypto_blkdev %s for f2fs inplace encrypt. err=%d(%s)\n",
JP Abgrall77768712014-10-10 15:52:11 -07002554 crypto_blkdev, errno, strerror(errno));
JP Abgrall512f0d52014-10-10 18:43:41 -07002555 rc = ENABLE_INPLACE_ERR_DEV;
Daniel Rosenberge82df162014-08-15 22:19:23 +00002556 goto errout;
2557 }
2558
2559 f2fs_info = generate_f2fs_info(data.realfd);
2560 if (!f2fs_info)
2561 goto errout;
2562
2563 data.numblocks = size / CRYPT_SECTORS_PER_BUFSIZE;
2564 data.tot_numblocks = tot_size / CRYPT_SECTORS_PER_BUFSIZE;
2565 data.blocks_already_done = *size_already_done / CRYPT_SECTORS_PER_BUFSIZE;
2566
2567 data.tot_used_blocks = get_num_blocks_used(f2fs_info);
2568
2569 data.one_pct = data.tot_used_blocks / 100;
2570 data.cur_pct = 0;
2571 data.time_started = time(NULL);
2572 data.remaining_time = -1;
2573
2574 data.buffer = malloc(f2fs_info->block_size);
2575 if (!data.buffer) {
2576 SLOGE("Failed to allocate crypto buffer");
2577 goto errout;
2578 }
2579
2580 data.count = 0;
2581
2582 /* Currently, this either runs to completion, or hits a nonrecoverable error */
2583 rc = run_on_used_blocks(data.blocks_already_done, f2fs_info, &encrypt_one_block_f2fs, &data);
2584
2585 if (rc) {
JP Abgrall512f0d52014-10-10 18:43:41 -07002586 SLOGE("Error in running over f2fs blocks");
2587 rc = ENABLE_INPLACE_ERR_OTHER;
Daniel Rosenberge82df162014-08-15 22:19:23 +00002588 goto errout;
2589 }
2590
2591 *size_already_done += size;
2592 rc = 0;
2593
2594errout:
2595 if (rc)
2596 SLOGE("Failed to encrypt f2fs filesystem on %s", real_blkdev);
2597
Paul Lawrence3846be12014-09-22 11:33:54 -07002598 log_progress_f2fs(0, true);
Daniel Rosenberge82df162014-08-15 22:19:23 +00002599 free(f2fs_info);
2600 free(data.buffer);
2601 close(data.realfd);
2602 close(data.cryptofd);
2603
2604 return rc;
2605}
2606
Paul Lawrenceae59fe62014-01-21 08:23:27 -08002607static int cryptfs_enable_inplace_full(char *crypto_blkdev, char *real_blkdev,
2608 off64_t size, off64_t *size_already_done,
Paul Lawrence87999172014-02-20 12:21:31 -08002609 off64_t tot_size,
2610 off64_t previously_encrypted_upto)
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002611{
2612 int realfd, cryptofd;
2613 char *buf[CRYPT_INPLACE_BUFSIZE];
JP Abgrall512f0d52014-10-10 18:43:41 -07002614 int rc = ENABLE_INPLACE_ERR_OTHER;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002615 off64_t numblocks, i, remainder;
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002616 off64_t one_pct, cur_pct, new_pct;
Ken Sumrall29d8da82011-05-18 17:20:07 -07002617 off64_t blocks_already_done, tot_numblocks;
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002618
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002619 if ( (realfd = open(real_blkdev, O_RDONLY)) < 0) {
2620 SLOGE("Error opening real_blkdev %s for inplace encrypt\n", real_blkdev);
JP Abgrall512f0d52014-10-10 18:43:41 -07002621 return ENABLE_INPLACE_ERR_OTHER;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002622 }
2623
2624 if ( (cryptofd = open(crypto_blkdev, O_WRONLY)) < 0) {
JP Abgrall77768712014-10-10 15:52:11 -07002625 SLOGE("Error opening crypto_blkdev %s for inplace encrypt. err=%d(%s)\n",
2626 crypto_blkdev, errno, strerror(errno));
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002627 close(realfd);
JP Abgrall512f0d52014-10-10 18:43:41 -07002628 return ENABLE_INPLACE_ERR_DEV;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002629 }
2630
2631 /* This is pretty much a simple loop of reading 4K, and writing 4K.
2632 * The size passed in is the number of 512 byte sectors in the filesystem.
2633 * So compute the number of whole 4K blocks we should read/write,
2634 * and the remainder.
2635 */
2636 numblocks = size / CRYPT_SECTORS_PER_BUFSIZE;
2637 remainder = size % CRYPT_SECTORS_PER_BUFSIZE;
Ken Sumrall29d8da82011-05-18 17:20:07 -07002638 tot_numblocks = tot_size / CRYPT_SECTORS_PER_BUFSIZE;
2639 blocks_already_done = *size_already_done / CRYPT_SECTORS_PER_BUFSIZE;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002640
2641 SLOGE("Encrypting filesystem in place...");
2642
Paul Lawrence87999172014-02-20 12:21:31 -08002643 i = previously_encrypted_upto + 1 - *size_already_done;
2644
2645 if (lseek64(realfd, i * CRYPT_SECTOR_SIZE, SEEK_SET) < 0) {
2646 SLOGE("Cannot seek to previously encrypted point on %s", real_blkdev);
2647 goto errout;
2648 }
2649
2650 if (lseek64(cryptofd, i * CRYPT_SECTOR_SIZE, SEEK_SET) < 0) {
2651 SLOGE("Cannot seek to previously encrypted point on %s", crypto_blkdev);
2652 goto errout;
2653 }
2654
2655 for (;i < size && i % CRYPT_SECTORS_PER_BUFSIZE != 0; ++i) {
2656 if (unix_read(realfd, buf, CRYPT_SECTOR_SIZE) <= 0) {
2657 SLOGE("Error reading initial sectors from real_blkdev %s for "
2658 "inplace encrypt\n", crypto_blkdev);
2659 goto errout;
2660 }
2661 if (unix_write(cryptofd, buf, CRYPT_SECTOR_SIZE) <= 0) {
2662 SLOGE("Error writing initial sectors to crypto_blkdev %s for "
2663 "inplace encrypt\n", crypto_blkdev);
2664 goto errout;
2665 } else {
Elliott Hughescb33f572014-06-25 18:25:11 -07002666 SLOGI("Encrypted 1 block at %" PRId64, i);
Paul Lawrence87999172014-02-20 12:21:31 -08002667 }
2668 }
2669
Ken Sumrall29d8da82011-05-18 17:20:07 -07002670 one_pct = tot_numblocks / 100;
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002671 cur_pct = 0;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002672 /* process the majority of the filesystem in blocks */
Paul Lawrence87999172014-02-20 12:21:31 -08002673 for (i/=CRYPT_SECTORS_PER_BUFSIZE; i<numblocks; i++) {
Ken Sumrall29d8da82011-05-18 17:20:07 -07002674 new_pct = (i + blocks_already_done) / one_pct;
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002675 if (new_pct > cur_pct) {
2676 char buf[8];
2677
2678 cur_pct = new_pct;
Elliott Hughes73737162014-06-25 17:27:42 -07002679 snprintf(buf, sizeof(buf), "%" PRId64, cur_pct);
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002680 property_set("vold.encrypt_progress", buf);
2681 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002682 if (unix_read(realfd, buf, CRYPT_INPLACE_BUFSIZE) <= 0) {
Paul Lawrence87999172014-02-20 12:21:31 -08002683 SLOGE("Error reading real_blkdev %s for inplace encrypt", crypto_blkdev);
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002684 goto errout;
2685 }
2686 if (unix_write(cryptofd, buf, CRYPT_INPLACE_BUFSIZE) <= 0) {
Paul Lawrence87999172014-02-20 12:21:31 -08002687 SLOGE("Error writing crypto_blkdev %s for inplace encrypt", crypto_blkdev);
2688 goto errout;
2689 } else {
Elliott Hughescb33f572014-06-25 18:25:11 -07002690 SLOGD("Encrypted %d block at %" PRId64,
Paul Lawrence87999172014-02-20 12:21:31 -08002691 CRYPT_SECTORS_PER_BUFSIZE,
2692 i * CRYPT_SECTORS_PER_BUFSIZE);
2693 }
2694
Paul Lawrence73d7a022014-06-09 14:10:09 -07002695 if (!is_battery_ok_to_continue()) {
Paul Lawrence87999172014-02-20 12:21:31 -08002696 SLOGE("Stopping encryption due to low battery");
2697 *size_already_done += (i + 1) * CRYPT_SECTORS_PER_BUFSIZE - 1;
2698 rc = 0;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002699 goto errout;
2700 }
2701 }
2702
2703 /* Do any remaining sectors */
2704 for (i=0; i<remainder; i++) {
Paul Lawrence87999172014-02-20 12:21:31 -08002705 if (unix_read(realfd, buf, CRYPT_SECTOR_SIZE) <= 0) {
2706 SLOGE("Error reading final sectors from real_blkdev %s for inplace encrypt", crypto_blkdev);
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002707 goto errout;
2708 }
Paul Lawrence87999172014-02-20 12:21:31 -08002709 if (unix_write(cryptofd, buf, CRYPT_SECTOR_SIZE) <= 0) {
2710 SLOGE("Error writing final sectors to crypto_blkdev %s for inplace encrypt", crypto_blkdev);
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002711 goto errout;
Paul Lawrence87999172014-02-20 12:21:31 -08002712 } else {
2713 SLOGI("Encrypted 1 block at next location");
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002714 }
2715 }
2716
Ken Sumrall29d8da82011-05-18 17:20:07 -07002717 *size_already_done += size;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002718 rc = 0;
2719
2720errout:
2721 close(realfd);
2722 close(cryptofd);
2723
2724 return rc;
2725}
2726
JP Abgrall512f0d52014-10-10 18:43:41 -07002727/* returns on of the ENABLE_INPLACE_* return codes */
Paul Lawrenceae59fe62014-01-21 08:23:27 -08002728static int cryptfs_enable_inplace(char *crypto_blkdev, char *real_blkdev,
2729 off64_t size, off64_t *size_already_done,
Paul Lawrence87999172014-02-20 12:21:31 -08002730 off64_t tot_size,
2731 off64_t previously_encrypted_upto)
Paul Lawrenceae59fe62014-01-21 08:23:27 -08002732{
JP Abgrall512f0d52014-10-10 18:43:41 -07002733 int rc_ext4, rc_f2fs, rc_full;
Paul Lawrence87999172014-02-20 12:21:31 -08002734 if (previously_encrypted_upto) {
Elliott Hughescb33f572014-06-25 18:25:11 -07002735 SLOGD("Continuing encryption from %" PRId64, previously_encrypted_upto);
Paul Lawrence87999172014-02-20 12:21:31 -08002736 }
2737
2738 if (*size_already_done + size < previously_encrypted_upto) {
2739 *size_already_done += size;
2740 return 0;
2741 }
2742
Daniel Rosenberge82df162014-08-15 22:19:23 +00002743 /* TODO: identify filesystem type.
2744 * As is, cryptfs_enable_inplace_ext4 will fail on an f2fs partition, and
2745 * then we will drop down to cryptfs_enable_inplace_f2fs.
2746 * */
JP Abgrall512f0d52014-10-10 18:43:41 -07002747 if ((rc_ext4 = cryptfs_enable_inplace_ext4(crypto_blkdev, real_blkdev,
Daniel Rosenberge82df162014-08-15 22:19:23 +00002748 size, size_already_done,
JP Abgrall512f0d52014-10-10 18:43:41 -07002749 tot_size, previously_encrypted_upto)) == 0) {
Daniel Rosenberge82df162014-08-15 22:19:23 +00002750 return 0;
2751 }
JP Abgrall512f0d52014-10-10 18:43:41 -07002752 SLOGD("cryptfs_enable_inplace_ext4()=%d\n", rc_ext4);
Daniel Rosenberge82df162014-08-15 22:19:23 +00002753
JP Abgrall512f0d52014-10-10 18:43:41 -07002754 if ((rc_f2fs = cryptfs_enable_inplace_f2fs(crypto_blkdev, real_blkdev,
Daniel Rosenberge82df162014-08-15 22:19:23 +00002755 size, size_already_done,
JP Abgrall512f0d52014-10-10 18:43:41 -07002756 tot_size, previously_encrypted_upto)) == 0) {
Daniel Rosenberge82df162014-08-15 22:19:23 +00002757 return 0;
Paul Lawrenceae59fe62014-01-21 08:23:27 -08002758 }
JP Abgrall512f0d52014-10-10 18:43:41 -07002759 SLOGD("cryptfs_enable_inplace_f2fs()=%d\n", rc_f2fs);
Paul Lawrenceae59fe62014-01-21 08:23:27 -08002760
JP Abgrall512f0d52014-10-10 18:43:41 -07002761 rc_full = cryptfs_enable_inplace_full(crypto_blkdev, real_blkdev,
Paul Lawrence87999172014-02-20 12:21:31 -08002762 size, size_already_done, tot_size,
2763 previously_encrypted_upto);
JP Abgrall512f0d52014-10-10 18:43:41 -07002764 SLOGD("cryptfs_enable_inplace_full()=%d\n", rc_full);
2765
2766 /* Hack for b/17898962, the following is the symptom... */
2767 if (rc_ext4 == ENABLE_INPLACE_ERR_DEV
2768 && rc_f2fs == ENABLE_INPLACE_ERR_DEV
2769 && rc_full == ENABLE_INPLACE_ERR_DEV) {
2770 return ENABLE_INPLACE_ERR_DEV;
2771 }
2772 return rc_full;
Paul Lawrenceae59fe62014-01-21 08:23:27 -08002773}
2774
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002775#define CRYPTO_ENABLE_WIPE 1
2776#define CRYPTO_ENABLE_INPLACE 2
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002777
2778#define FRAMEWORK_BOOT_WAIT 60
2779
Ken Sumrall29d8da82011-05-18 17:20:07 -07002780static inline int should_encrypt(struct volume_info *volume)
2781{
Paul Lawrenceae59fe62014-01-21 08:23:27 -08002782 return (volume->flags & (VOL_ENCRYPTABLE | VOL_NONREMOVABLE)) ==
Ken Sumrall29d8da82011-05-18 17:20:07 -07002783 (VOL_ENCRYPTABLE | VOL_NONREMOVABLE);
2784}
2785
Paul Lawrence87999172014-02-20 12:21:31 -08002786static int cryptfs_SHA256_fileblock(const char* filename, __le8* buf)
2787{
2788 int fd = open(filename, O_RDONLY);
2789 if (fd == -1) {
2790 SLOGE("Error opening file %s", filename);
2791 return -1;
2792 }
2793
2794 char block[CRYPT_INPLACE_BUFSIZE];
2795 memset(block, 0, sizeof(block));
2796 if (unix_read(fd, block, sizeof(block)) < 0) {
2797 SLOGE("Error reading file %s", filename);
2798 close(fd);
2799 return -1;
2800 }
2801
2802 close(fd);
2803
2804 SHA256_CTX c;
2805 SHA256_Init(&c);
2806 SHA256_Update(&c, block, sizeof(block));
2807 SHA256_Final(buf, &c);
2808
2809 return 0;
2810}
2811
JP Abgrall62c7af32014-06-16 13:01:23 -07002812static int get_fs_type(struct fstab_rec *rec)
2813{
2814 if (!strcmp(rec->fs_type, "ext4")) {
2815 return EXT4_FS;
2816 } else if (!strcmp(rec->fs_type, "f2fs")) {
2817 return F2FS_FS;
2818 } else {
2819 return -1;
2820 }
2821}
2822
Paul Lawrence87999172014-02-20 12:21:31 -08002823static int cryptfs_enable_all_volumes(struct crypt_mnt_ftr *crypt_ftr, int how,
2824 char *crypto_blkdev, char *real_blkdev,
2825 int previously_encrypted_upto)
2826{
2827 off64_t cur_encryption_done=0, tot_encryption_size=0;
Tim Murray8439dc92014-12-15 11:56:11 -08002828 int rc = -1;
Paul Lawrence87999172014-02-20 12:21:31 -08002829
Paul Lawrence73d7a022014-06-09 14:10:09 -07002830 if (!is_battery_ok_to_start()) {
2831 SLOGW("Not starting encryption due to low battery");
Paul Lawrence87999172014-02-20 12:21:31 -08002832 return 0;
2833 }
2834
2835 /* The size of the userdata partition, and add in the vold volumes below */
2836 tot_encryption_size = crypt_ftr->fs_size;
2837
2838 if (how == CRYPTO_ENABLE_WIPE) {
JP Abgrall62c7af32014-06-16 13:01:23 -07002839 struct fstab_rec* rec = fs_mgr_get_entry_for_mount_point(fstab, DATA_MNT_POINT);
2840 int fs_type = get_fs_type(rec);
2841 if (fs_type < 0) {
2842 SLOGE("cryptfs_enable: unsupported fs type %s\n", rec->fs_type);
2843 return -1;
2844 }
2845 rc = cryptfs_enable_wipe(crypto_blkdev, crypt_ftr->fs_size, fs_type);
Paul Lawrence87999172014-02-20 12:21:31 -08002846 } else if (how == CRYPTO_ENABLE_INPLACE) {
2847 rc = cryptfs_enable_inplace(crypto_blkdev, real_blkdev,
2848 crypt_ftr->fs_size, &cur_encryption_done,
2849 tot_encryption_size,
2850 previously_encrypted_upto);
2851
JP Abgrall512f0d52014-10-10 18:43:41 -07002852 if (rc == ENABLE_INPLACE_ERR_DEV) {
2853 /* Hack for b/17898962 */
2854 SLOGE("cryptfs_enable: crypto block dev failure. Must reboot...\n");
2855 cryptfs_reboot(reboot);
2856 }
2857
Paul Lawrence73d7a022014-06-09 14:10:09 -07002858 if (!rc) {
Paul Lawrence87999172014-02-20 12:21:31 -08002859 crypt_ftr->encrypted_upto = cur_encryption_done;
2860 }
2861
Paul Lawrence73d7a022014-06-09 14:10:09 -07002862 if (!rc && crypt_ftr->encrypted_upto == crypt_ftr->fs_size) {
Paul Lawrence87999172014-02-20 12:21:31 -08002863 /* The inplace routine never actually sets the progress to 100% due
2864 * to the round down nature of integer division, so set it here */
2865 property_set("vold.encrypt_progress", "100");
2866 }
2867 } else {
2868 /* Shouldn't happen */
2869 SLOGE("cryptfs_enable: internal error, unknown option\n");
2870 rc = -1;
2871 }
2872
2873 return rc;
2874}
2875
Paul Lawrence13486032014-02-03 13:28:11 -08002876int cryptfs_enable_internal(char *howarg, int crypt_type, char *passwd,
2877 int allow_reboot)
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002878{
2879 int how = 0;
Paul Lawrence87999172014-02-20 12:21:31 -08002880 char crypto_blkdev[MAXPATHLEN], real_blkdev[MAXPATHLEN];
Ken Sumralle5032c42012-04-01 23:58:44 -07002881 unsigned long nr_sec;
Ken Sumrall160b4d62013-04-22 12:15:39 -07002882 unsigned char decrypted_master_key[KEY_LEN_BYTES];
Tim Murray8439dc92014-12-15 11:56:11 -08002883 int rc=-1, fd, i;
Paul Lawrence87999172014-02-20 12:21:31 -08002884 struct crypt_mnt_ftr crypt_ftr;
Ken Sumrall160b4d62013-04-22 12:15:39 -07002885 struct crypt_persist_data *pdata;
Ken Sumrall29d8da82011-05-18 17:20:07 -07002886 char encrypted_state[PROPERTY_VALUE_MAX];
Ken Sumrall5d4c68e2011-01-30 19:06:03 -08002887 char lockid[32] = { 0 };
Ken Sumrall29d8da82011-05-18 17:20:07 -07002888 char key_loc[PROPERTY_VALUE_MAX];
2889 char fuse_sdcard[PROPERTY_VALUE_MAX];
2890 char *sd_mnt_point;
Ken Sumrall29d8da82011-05-18 17:20:07 -07002891 int num_vols;
2892 struct volume_info *vol_list = 0;
Paul Lawrence87999172014-02-20 12:21:31 -08002893 off64_t previously_encrypted_upto = 0;
Ken Sumrall29d8da82011-05-18 17:20:07 -07002894
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002895 if (!strcmp(howarg, "wipe")) {
2896 how = CRYPTO_ENABLE_WIPE;
2897 } else if (! strcmp(howarg, "inplace")) {
2898 how = CRYPTO_ENABLE_INPLACE;
2899 } else {
2900 /* Shouldn't happen, as CommandListener vets the args */
Ken Sumrall3ed82362011-01-28 23:31:16 -08002901 goto error_unencrypted;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002902 }
2903
Paul Lawrence87999172014-02-20 12:21:31 -08002904 /* See if an encryption was underway and interrupted */
2905 if (how == CRYPTO_ENABLE_INPLACE
2906 && get_crypt_ftr_and_key(&crypt_ftr) == 0
2907 && (crypt_ftr.flags & CRYPT_ENCRYPTION_IN_PROGRESS)) {
2908 previously_encrypted_upto = crypt_ftr.encrypted_upto;
2909 crypt_ftr.encrypted_upto = 0;
Paul Lawrence6bfed202014-07-28 12:47:22 -07002910 crypt_ftr.flags &= ~CRYPT_ENCRYPTION_IN_PROGRESS;
2911
2912 /* At this point, we are in an inconsistent state. Until we successfully
2913 complete encryption, a reboot will leave us broken. So mark the
2914 encryption failed in case that happens.
2915 On successfully completing encryption, remove this flag */
2916 crypt_ftr.flags |= CRYPT_INCONSISTENT_STATE;
2917
2918 put_crypt_ftr_and_key(&crypt_ftr);
Paul Lawrence87999172014-02-20 12:21:31 -08002919 }
2920
2921 property_get("ro.crypto.state", encrypted_state, "");
2922 if (!strcmp(encrypted_state, "encrypted") && !previously_encrypted_upto) {
2923 SLOGE("Device is already running encrypted, aborting");
2924 goto error_unencrypted;
2925 }
2926
2927 // TODO refactor fs_mgr_get_crypt_info to get both in one call
2928 fs_mgr_get_crypt_info(fstab, key_loc, 0, sizeof(key_loc));
Ken Sumrall56ad03c2013-02-13 13:00:19 -08002929 fs_mgr_get_crypt_info(fstab, 0, real_blkdev, sizeof(real_blkdev));
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002930
Ken Sumrall3ed82362011-01-28 23:31:16 -08002931 /* Get the size of the real block device */
2932 fd = open(real_blkdev, O_RDONLY);
2933 if ( (nr_sec = get_blkdev_size(fd)) == 0) {
2934 SLOGE("Cannot get size of block device %s\n", real_blkdev);
2935 goto error_unencrypted;
2936 }
2937 close(fd);
2938
2939 /* If doing inplace encryption, make sure the orig fs doesn't include the crypto footer */
Ken Sumrall29d8da82011-05-18 17:20:07 -07002940 if ((how == CRYPTO_ENABLE_INPLACE) && (!strcmp(key_loc, KEY_IN_FOOTER))) {
Ken Sumrall3ed82362011-01-28 23:31:16 -08002941 unsigned int fs_size_sec, max_fs_size_sec;
Jim Millera70abc62014-08-15 02:00:45 +00002942 fs_size_sec = get_fs_size(real_blkdev);
Daniel Rosenberge82df162014-08-15 22:19:23 +00002943 if (fs_size_sec == 0)
2944 fs_size_sec = get_f2fs_filesystem_size_sec(real_blkdev);
2945
Paul Lawrence87999172014-02-20 12:21:31 -08002946 max_fs_size_sec = nr_sec - (CRYPT_FOOTER_OFFSET / CRYPT_SECTOR_SIZE);
Ken Sumrall3ed82362011-01-28 23:31:16 -08002947
2948 if (fs_size_sec > max_fs_size_sec) {
2949 SLOGE("Orig filesystem overlaps crypto footer region. Cannot encrypt in place.");
2950 goto error_unencrypted;
2951 }
2952 }
2953
Ken Sumrall5d4c68e2011-01-30 19:06:03 -08002954 /* Get a wakelock as this may take a while, and we don't want the
2955 * device to sleep on us. We'll grab a partial wakelock, and if the UI
2956 * wants to keep the screen on, it can grab a full wakelock.
2957 */
Ken Sumrall29d8da82011-05-18 17:20:07 -07002958 snprintf(lockid, sizeof(lockid), "enablecrypto%d", (int) getpid());
Ken Sumrall5d4c68e2011-01-30 19:06:03 -08002959 acquire_wake_lock(PARTIAL_WAKE_LOCK, lockid);
2960
Jeff Sharkey7382f812012-08-23 14:08:59 -07002961 /* Get the sdcard mount point */
Jeff Sharkeyb77bc462012-10-01 14:36:26 -07002962 sd_mnt_point = getenv("EMULATED_STORAGE_SOURCE");
Jeff Sharkey7382f812012-08-23 14:08:59 -07002963 if (!sd_mnt_point) {
2964 sd_mnt_point = getenv("EXTERNAL_STORAGE");
2965 }
2966 if (!sd_mnt_point) {
2967 sd_mnt_point = "/mnt/sdcard";
2968 }
Ken Sumrall29d8da82011-05-18 17:20:07 -07002969
Paul Lawrence87999172014-02-20 12:21:31 -08002970 /* TODO
2971 * Currently do not have test devices with multiple encryptable volumes.
2972 * When we acquire some, re-add support.
2973 */
Ken Sumrall29d8da82011-05-18 17:20:07 -07002974 num_vols=vold_getNumDirectVolumes();
2975 vol_list = malloc(sizeof(struct volume_info) * num_vols);
2976 vold_getDirectVolumeList(vol_list);
2977
2978 for (i=0; i<num_vols; i++) {
2979 if (should_encrypt(&vol_list[i])) {
Paul Lawrence87999172014-02-20 12:21:31 -08002980 SLOGE("Cannot encrypt if there are multiple encryptable volumes"
2981 "%s\n", vol_list[i].label);
2982 goto error_unencrypted;
Ken Sumrall29d8da82011-05-18 17:20:07 -07002983 }
2984 }
2985
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002986 /* The init files are setup to stop the class main and late start when
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002987 * vold sets trigger_shutdown_framework.
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002988 */
2989 property_set("vold.decrypt", "trigger_shutdown_framework");
2990 SLOGD("Just asked init to shut down class main\n");
2991
Ken Sumrall425524d2012-06-14 20:55:28 -07002992 if (vold_unmountAllAsecs()) {
2993 /* Just report the error. If any are left mounted,
2994 * umounting /data below will fail and handle the error.
2995 */
2996 SLOGE("Error unmounting internal asecs");
2997 }
2998
Ken Sumrall29d8da82011-05-18 17:20:07 -07002999 property_get("ro.crypto.fuse_sdcard", fuse_sdcard, "");
3000 if (!strcmp(fuse_sdcard, "true")) {
3001 /* This is a device using the fuse layer to emulate the sdcard semantics
3002 * on top of the userdata partition. vold does not manage it, it is managed
3003 * by the sdcard service. The sdcard service was killed by the property trigger
3004 * above, so just unmount it now. We must do this _AFTER_ killing the framework,
3005 * unlike the case for vold managed devices above.
3006 */
Greg Hackmann6e8440f2014-10-02 17:18:20 -07003007 if (wait_and_unmount(sd_mnt_point, false)) {
Ken Sumrall29d8da82011-05-18 17:20:07 -07003008 goto error_shutting_down;
3009 }
Ken Sumrall2eaf7132011-01-14 12:45:48 -08003010 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08003011
3012 /* Now unmount the /data partition. */
Greg Hackmann6e8440f2014-10-02 17:18:20 -07003013 if (wait_and_unmount(DATA_MNT_POINT, false)) {
JP Abgrall502dc742013-11-01 13:06:20 -07003014 if (allow_reboot) {
3015 goto error_shutting_down;
3016 } else {
3017 goto error_unencrypted;
3018 }
Ken Sumrall8ddbe402011-01-17 15:26:29 -08003019 }
3020
3021 /* Do extra work for a better UX when doing the long inplace encryption */
3022 if (how == CRYPTO_ENABLE_INPLACE) {
3023 /* Now that /data is unmounted, we need to mount a tmpfs
3024 * /data, set a property saying we're doing inplace encryption,
3025 * and restart the framework.
Ken Sumrall8f869aa2010-12-03 03:47:09 -08003026 */
Ken Sumralle5032c42012-04-01 23:58:44 -07003027 if (fs_mgr_do_tmpfs_mount(DATA_MNT_POINT)) {
Ken Sumrall3ed82362011-01-28 23:31:16 -08003028 goto error_shutting_down;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08003029 }
Ken Sumrall8ddbe402011-01-17 15:26:29 -08003030 /* Tells the framework that inplace encryption is starting */
Ken Sumrall7df84122011-01-18 14:04:08 -08003031 property_set("vold.encrypt_progress", "0");
Ken Sumrall8f869aa2010-12-03 03:47:09 -08003032
Ken Sumrall8ddbe402011-01-17 15:26:29 -08003033 /* restart the framework. */
3034 /* Create necessary paths on /data */
3035 if (prep_data_fs()) {
Ken Sumrall3ed82362011-01-28 23:31:16 -08003036 goto error_shutting_down;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08003037 }
3038
Ken Sumrall92736ef2012-10-17 20:57:14 -07003039 /* Ugh, shutting down the framework is not synchronous, so until it
3040 * can be fixed, this horrible hack will wait a moment for it all to
3041 * shut down before proceeding. Without it, some devices cannot
3042 * restart the graphics services.
3043 */
3044 sleep(2);
3045
Ken Sumrall8ddbe402011-01-17 15:26:29 -08003046 /* startup service classes main and late_start */
3047 property_set("vold.decrypt", "trigger_restart_min_framework");
3048 SLOGD("Just triggered restart_min_framework\n");
Ken Sumrall8f869aa2010-12-03 03:47:09 -08003049
Ken Sumrall7df84122011-01-18 14:04:08 -08003050 /* OK, the framework is restarted and will soon be showing a
3051 * progress bar. Time to setup an encrypted mapping, and
3052 * either write a new filesystem, or encrypt in place updating
3053 * the progress bar as we work.
Ken Sumrall8ddbe402011-01-17 15:26:29 -08003054 */
3055 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08003056
Ken Sumrall8ddbe402011-01-17 15:26:29 -08003057 /* Start the actual work of making an encrypted filesystem */
Ken Sumrall8ddbe402011-01-17 15:26:29 -08003058 /* Initialize a crypt_mnt_ftr for the partition */
Paul Lawrence87999172014-02-20 12:21:31 -08003059 if (previously_encrypted_upto == 0) {
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07003060 if (cryptfs_init_crypt_mnt_ftr(&crypt_ftr)) {
3061 goto error_shutting_down;
3062 }
Ken Sumrall160b4d62013-04-22 12:15:39 -07003063
Paul Lawrence87999172014-02-20 12:21:31 -08003064 if (!strcmp(key_loc, KEY_IN_FOOTER)) {
3065 crypt_ftr.fs_size = nr_sec
3066 - (CRYPT_FOOTER_OFFSET / CRYPT_SECTOR_SIZE);
3067 } else {
3068 crypt_ftr.fs_size = nr_sec;
3069 }
Paul Lawrence6bfed202014-07-28 12:47:22 -07003070 /* At this point, we are in an inconsistent state. Until we successfully
3071 complete encryption, a reboot will leave us broken. So mark the
3072 encryption failed in case that happens.
3073 On successfully completing encryption, remove this flag */
3074 crypt_ftr.flags |= CRYPT_INCONSISTENT_STATE;
Paul Lawrence87999172014-02-20 12:21:31 -08003075 crypt_ftr.crypt_type = crypt_type;
3076 strcpy((char *)crypt_ftr.crypto_type_name, "aes-cbc-essiv:sha256");
Ken Sumrall8ddbe402011-01-17 15:26:29 -08003077
Paul Lawrence87999172014-02-20 12:21:31 -08003078 /* Make an encrypted master key */
3079 if (create_encrypted_random_key(passwd, crypt_ftr.master_key, crypt_ftr.salt, &crypt_ftr)) {
3080 SLOGE("Cannot create encrypted master key\n");
3081 goto error_shutting_down;
3082 }
Ken Sumrall8ddbe402011-01-17 15:26:29 -08003083
Paul Lawrence87999172014-02-20 12:21:31 -08003084 /* Write the key to the end of the partition */
3085 put_crypt_ftr_and_key(&crypt_ftr);
Ken Sumrall8ddbe402011-01-17 15:26:29 -08003086
Paul Lawrence87999172014-02-20 12:21:31 -08003087 /* If any persistent data has been remembered, save it.
3088 * If none, create a valid empty table and save that.
3089 */
3090 if (!persist_data) {
3091 pdata = malloc(CRYPT_PERSIST_DATA_SIZE);
3092 if (pdata) {
3093 init_empty_persist_data(pdata, CRYPT_PERSIST_DATA_SIZE);
3094 persist_data = pdata;
3095 }
3096 }
3097 if (persist_data) {
3098 save_persistent_data();
3099 }
Ken Sumrall160b4d62013-04-22 12:15:39 -07003100 }
3101
Paul Lawrenced0c7b172014-08-08 14:28:10 -07003102 decrypt_master_key(passwd, decrypted_master_key, &crypt_ftr, 0, 0);
Ken Sumrall29d8da82011-05-18 17:20:07 -07003103 create_crypto_blk_dev(&crypt_ftr, decrypted_master_key, real_blkdev, crypto_blkdev,
3104 "userdata");
3105
Paul Lawrence87999172014-02-20 12:21:31 -08003106 /* If we are continuing, check checksums match */
3107 rc = 0;
3108 if (previously_encrypted_upto) {
3109 __le8 hash_first_block[SHA256_DIGEST_LENGTH];
3110 rc = cryptfs_SHA256_fileblock(crypto_blkdev, hash_first_block);
Ken Sumrall128626f2011-06-28 18:45:14 -07003111
Paul Lawrence87999172014-02-20 12:21:31 -08003112 if (!rc && memcmp(hash_first_block, crypt_ftr.hash_first_block,
3113 sizeof(hash_first_block)) != 0) {
3114 SLOGE("Checksums do not match - trigger wipe");
3115 rc = -1;
Ken Sumrall29d8da82011-05-18 17:20:07 -07003116 }
3117 }
Ken Sumrall8ddbe402011-01-17 15:26:29 -08003118
Paul Lawrence87999172014-02-20 12:21:31 -08003119 if (!rc) {
3120 rc = cryptfs_enable_all_volumes(&crypt_ftr, how,
3121 crypto_blkdev, real_blkdev,
3122 previously_encrypted_upto);
3123 }
3124
3125 /* Calculate checksum if we are not finished */
Paul Lawrence73d7a022014-06-09 14:10:09 -07003126 if (!rc && crypt_ftr.encrypted_upto != crypt_ftr.fs_size) {
Paul Lawrence87999172014-02-20 12:21:31 -08003127 rc = cryptfs_SHA256_fileblock(crypto_blkdev,
3128 crypt_ftr.hash_first_block);
Paul Lawrence73d7a022014-06-09 14:10:09 -07003129 if (rc) {
Paul Lawrence87999172014-02-20 12:21:31 -08003130 SLOGE("Error calculating checksum for continuing encryption");
3131 rc = -1;
Ken Sumrall29d8da82011-05-18 17:20:07 -07003132 }
Ken Sumrall8ddbe402011-01-17 15:26:29 -08003133 }
3134
3135 /* Undo the dm-crypt mapping whether we succeed or not */
Ken Sumrall29d8da82011-05-18 17:20:07 -07003136 delete_crypto_blk_dev("userdata");
Ken Sumrall29d8da82011-05-18 17:20:07 -07003137
3138 free(vol_list);
Ken Sumrall8ddbe402011-01-17 15:26:29 -08003139
3140 if (! rc) {
3141 /* Success */
Paul Lawrence6bfed202014-07-28 12:47:22 -07003142 crypt_ftr.flags &= ~CRYPT_INCONSISTENT_STATE;
Ken Sumrall7f7dbaa2011-02-01 15:46:41 -08003143
Paul Lawrence6bfed202014-07-28 12:47:22 -07003144 if (crypt_ftr.encrypted_upto != crypt_ftr.fs_size) {
Paul Lawrence87999172014-02-20 12:21:31 -08003145 SLOGD("Encrypted up to sector %lld - will continue after reboot",
3146 crypt_ftr.encrypted_upto);
Paul Lawrence6bfed202014-07-28 12:47:22 -07003147 crypt_ftr.flags |= CRYPT_ENCRYPTION_IN_PROGRESS;
Paul Lawrence87999172014-02-20 12:21:31 -08003148 }
Paul Lawrence73d7a022014-06-09 14:10:09 -07003149
Paul Lawrence6bfed202014-07-28 12:47:22 -07003150 put_crypt_ftr_and_key(&crypt_ftr);
Ken Sumralld33d4172011-02-01 00:49:13 -08003151
Paul Lawrence73d7a022014-06-09 14:10:09 -07003152 if (crypt_ftr.encrypted_upto == crypt_ftr.fs_size) {
Paul Lawrenceb6672e12014-08-15 07:37:28 -07003153 char value[PROPERTY_VALUE_MAX];
3154 property_get("ro.crypto.state", value, "");
3155 if (!strcmp(value, "")) {
3156 /* default encryption - continue first boot sequence */
3157 property_set("ro.crypto.state", "encrypted");
3158 release_wake_lock(lockid);
3159 cryptfs_check_passwd(DEFAULT_PASSWORD);
3160 cryptfs_restart_internal(1);
3161 return 0;
3162 } else {
3163 sleep(2); /* Give the UI a chance to show 100% progress */
Paul Lawrence87999172014-02-20 12:21:31 -08003164 cryptfs_reboot(reboot);
Paul Lawrenceb6672e12014-08-15 07:37:28 -07003165 }
Paul Lawrence87999172014-02-20 12:21:31 -08003166 } else {
Paul Lawrenceb6672e12014-08-15 07:37:28 -07003167 sleep(2); /* Partially encrypted, ensure writes flushed to ssd */
Paul Lawrence87999172014-02-20 12:21:31 -08003168 cryptfs_reboot(shutdown);
3169 }
Ken Sumrall3ed82362011-01-28 23:31:16 -08003170 } else {
Mike Lockwoodee6d8c42012-02-15 13:43:28 -08003171 char value[PROPERTY_VALUE_MAX];
3172
Ken Sumrall319369a2012-06-27 16:30:18 -07003173 property_get("ro.vold.wipe_on_crypt_fail", value, "0");
Mike Lockwoodee6d8c42012-02-15 13:43:28 -08003174 if (!strcmp(value, "1")) {
3175 /* wipe data if encryption failed */
3176 SLOGE("encryption failed - rebooting into recovery to wipe data\n");
3177 mkdir("/cache/recovery", 0700);
Nick Kralevich4684e582012-06-26 15:07:03 -07003178 int fd = open("/cache/recovery/command", O_RDWR|O_CREAT|O_TRUNC, 0600);
Mike Lockwoodee6d8c42012-02-15 13:43:28 -08003179 if (fd >= 0) {
Jeff Sharkeydd1a8042014-09-24 11:46:51 -07003180 write(fd, "--wipe_data\n", strlen("--wipe_data\n") + 1);
3181 write(fd, "--reason=cryptfs_enable_internal\n", strlen("--reason=cryptfs_enable_internal\n") + 1);
Mike Lockwoodee6d8c42012-02-15 13:43:28 -08003182 close(fd);
3183 } else {
3184 SLOGE("could not open /cache/recovery/command\n");
3185 }
Paul Lawrence87999172014-02-20 12:21:31 -08003186 cryptfs_reboot(recovery);
Mike Lockwoodee6d8c42012-02-15 13:43:28 -08003187 } else {
3188 /* set property to trigger dialog */
3189 property_set("vold.encrypt_progress", "error_partially_encrypted");
3190 release_wake_lock(lockid);
3191 }
Ken Sumrall3ed82362011-01-28 23:31:16 -08003192 return -1;
Ken Sumrall8ddbe402011-01-17 15:26:29 -08003193 }
3194
Ken Sumrall3ed82362011-01-28 23:31:16 -08003195 /* hrm, the encrypt step claims success, but the reboot failed.
3196 * This should not happen.
3197 * Set the property and return. Hope the framework can deal with it.
3198 */
3199 property_set("vold.encrypt_progress", "error_reboot_failed");
Ken Sumrall5d4c68e2011-01-30 19:06:03 -08003200 release_wake_lock(lockid);
Ken Sumrall8ddbe402011-01-17 15:26:29 -08003201 return rc;
Ken Sumrall3ed82362011-01-28 23:31:16 -08003202
3203error_unencrypted:
Ken Sumrall29d8da82011-05-18 17:20:07 -07003204 free(vol_list);
Ken Sumrall3ed82362011-01-28 23:31:16 -08003205 property_set("vold.encrypt_progress", "error_not_encrypted");
Ken Sumrall5d4c68e2011-01-30 19:06:03 -08003206 if (lockid[0]) {
3207 release_wake_lock(lockid);
3208 }
Ken Sumrall3ed82362011-01-28 23:31:16 -08003209 return -1;
3210
3211error_shutting_down:
3212 /* we failed, and have not encrypted anthing, so the users's data is still intact,
3213 * but the framework is stopped and not restarted to show the error, so it's up to
3214 * vold to restart the system.
3215 */
3216 SLOGE("Error enabling encryption after framework is shutdown, no data changed, restarting system");
Paul Lawrence87999172014-02-20 12:21:31 -08003217 cryptfs_reboot(reboot);
Ken Sumrall3ed82362011-01-28 23:31:16 -08003218
3219 /* shouldn't get here */
3220 property_set("vold.encrypt_progress", "error_shutting_down");
Ken Sumrall29d8da82011-05-18 17:20:07 -07003221 free(vol_list);
Ken Sumrall5d4c68e2011-01-30 19:06:03 -08003222 if (lockid[0]) {
3223 release_wake_lock(lockid);
3224 }
Ken Sumrall3ed82362011-01-28 23:31:16 -08003225 return -1;
Ken Sumrall8ddbe402011-01-17 15:26:29 -08003226}
3227
Paul Lawrence45f10532014-04-04 18:11:56 +00003228int cryptfs_enable(char *howarg, int type, char *passwd, int allow_reboot)
Paul Lawrence13486032014-02-03 13:28:11 -08003229{
Paul Lawrencefc615042014-10-04 15:32:29 -07003230 char* adjusted_passwd = adjust_passwd(passwd);
3231 if (adjusted_passwd) {
3232 passwd = adjusted_passwd;
3233 }
3234
3235 int rc = cryptfs_enable_internal(howarg, type, passwd, allow_reboot);
3236
3237 free(adjusted_passwd);
3238 return rc;
Paul Lawrence13486032014-02-03 13:28:11 -08003239}
3240
3241int cryptfs_enable_default(char *howarg, int allow_reboot)
3242{
3243 return cryptfs_enable_internal(howarg, CRYPT_TYPE_DEFAULT,
3244 DEFAULT_PASSWORD, allow_reboot);
3245}
3246
3247int cryptfs_changepw(int crypt_type, const char *newpw)
Ken Sumrall8ddbe402011-01-17 15:26:29 -08003248{
3249 struct crypt_mnt_ftr crypt_ftr;
Ken Sumrall8ddbe402011-01-17 15:26:29 -08003250
3251 /* This is only allowed after we've successfully decrypted the master key */
Paul Lawrencef4faa572014-01-29 13:31:03 -08003252 if (!master_key_saved) {
Ken Sumrall0cc16632011-01-18 20:32:26 -08003253 SLOGE("Key not saved, aborting");
Ken Sumrall8ddbe402011-01-17 15:26:29 -08003254 return -1;
3255 }
3256
Paul Lawrencef4faa572014-01-29 13:31:03 -08003257 if (crypt_type < 0 || crypt_type > CRYPT_TYPE_MAX_TYPE) {
3258 SLOGE("Invalid crypt_type %d", crypt_type);
3259 return -1;
3260 }
3261
Ken Sumrall8ddbe402011-01-17 15:26:29 -08003262 /* get key */
Ken Sumrall160b4d62013-04-22 12:15:39 -07003263 if (get_crypt_ftr_and_key(&crypt_ftr)) {
Paul Lawrencef4faa572014-01-29 13:31:03 -08003264 SLOGE("Error getting crypt footer and key");
3265 return -1;
Ken Sumrall8ddbe402011-01-17 15:26:29 -08003266 }
3267
Paul Lawrencef4faa572014-01-29 13:31:03 -08003268 crypt_ftr.crypt_type = crypt_type;
3269
Paul Lawrencefc615042014-10-04 15:32:29 -07003270 char* adjusted_passwd = adjust_passwd(newpw);
3271 if (adjusted_passwd) {
3272 newpw = adjusted_passwd;
3273 }
3274
Paul Lawrencef4faa572014-01-29 13:31:03 -08003275 encrypt_master_key(crypt_type == CRYPT_TYPE_DEFAULT ? DEFAULT_PASSWORD
3276 : newpw,
3277 crypt_ftr.salt,
3278 saved_master_key,
3279 crypt_ftr.master_key,
3280 &crypt_ftr);
Ken Sumrall8ddbe402011-01-17 15:26:29 -08003281
Jason parks70a4b3f2011-01-28 10:10:47 -06003282 /* save the key */
Ken Sumrall160b4d62013-04-22 12:15:39 -07003283 put_crypt_ftr_and_key(&crypt_ftr);
Ken Sumrall8f869aa2010-12-03 03:47:09 -08003284
Paul Lawrencefc615042014-10-04 15:32:29 -07003285 free(adjusted_passwd);
Ken Sumrall8f869aa2010-12-03 03:47:09 -08003286 return 0;
3287}
Ken Sumrall160b4d62013-04-22 12:15:39 -07003288
3289static int persist_get_key(char *fieldname, char *value)
3290{
3291 unsigned int i;
3292
3293 if (persist_data == NULL) {
3294 return -1;
3295 }
3296 for (i = 0; i < persist_data->persist_valid_entries; i++) {
3297 if (!strncmp(persist_data->persist_entry[i].key, fieldname, PROPERTY_KEY_MAX)) {
3298 /* We found it! */
3299 strlcpy(value, persist_data->persist_entry[i].val, PROPERTY_VALUE_MAX);
3300 return 0;
3301 }
3302 }
3303
3304 return -1;
3305}
3306
3307static int persist_set_key(char *fieldname, char *value, int encrypted)
3308{
3309 unsigned int i;
3310 unsigned int num;
3311 struct crypt_mnt_ftr crypt_ftr;
3312 unsigned int max_persistent_entries;
3313 unsigned int dsize;
3314
3315 if (persist_data == NULL) {
3316 return -1;
3317 }
3318
3319 /* If encrypted, use the values from the crypt_ftr, otherwise
3320 * use the values for the current spec.
3321 */
3322 if (encrypted) {
3323 if(get_crypt_ftr_and_key(&crypt_ftr)) {
3324 return -1;
3325 }
3326 dsize = crypt_ftr.persist_data_size;
3327 } else {
3328 dsize = CRYPT_PERSIST_DATA_SIZE;
3329 }
3330 max_persistent_entries = (dsize - sizeof(struct crypt_persist_data)) /
3331 sizeof(struct crypt_persist_entry);
3332
3333 num = persist_data->persist_valid_entries;
3334
3335 for (i = 0; i < num; i++) {
3336 if (!strncmp(persist_data->persist_entry[i].key, fieldname, PROPERTY_KEY_MAX)) {
3337 /* We found an existing entry, update it! */
3338 memset(persist_data->persist_entry[i].val, 0, PROPERTY_VALUE_MAX);
3339 strlcpy(persist_data->persist_entry[i].val, value, PROPERTY_VALUE_MAX);
3340 return 0;
3341 }
3342 }
3343
3344 /* We didn't find it, add it to the end, if there is room */
3345 if (persist_data->persist_valid_entries < max_persistent_entries) {
3346 memset(&persist_data->persist_entry[num], 0, sizeof(struct crypt_persist_entry));
3347 strlcpy(persist_data->persist_entry[num].key, fieldname, PROPERTY_KEY_MAX);
3348 strlcpy(persist_data->persist_entry[num].val, value, PROPERTY_VALUE_MAX);
3349 persist_data->persist_valid_entries++;
3350 return 0;
3351 }
3352
3353 return -1;
3354}
3355
3356/* Return the value of the specified field. */
3357int cryptfs_getfield(char *fieldname, char *value, int len)
3358{
3359 char temp_value[PROPERTY_VALUE_MAX];
Ken Sumrall160b4d62013-04-22 12:15:39 -07003360 /* 0 is success, 1 is not encrypted,
3361 * -1 is value not set, -2 is any other error
3362 */
3363 int rc = -2;
3364
3365 if (persist_data == NULL) {
3366 load_persistent_data();
3367 if (persist_data == NULL) {
3368 SLOGE("Getfield error, cannot load persistent data");
3369 goto out;
3370 }
3371 }
3372
3373 if (!persist_get_key(fieldname, temp_value)) {
3374 /* We found it, copy it to the caller's buffer and return */
3375 strlcpy(value, temp_value, len);
3376 rc = 0;
3377 } else {
3378 /* Sadness, it's not there. Return the error */
3379 rc = -1;
3380 }
3381
3382out:
3383 return rc;
3384}
3385
3386/* Set the value of the specified field. */
3387int cryptfs_setfield(char *fieldname, char *value)
3388{
Ken Sumrall160b4d62013-04-22 12:15:39 -07003389 char encrypted_state[PROPERTY_VALUE_MAX];
3390 /* 0 is success, -1 is an error */
3391 int rc = -1;
3392 int encrypted = 0;
3393
3394 if (persist_data == NULL) {
3395 load_persistent_data();
3396 if (persist_data == NULL) {
3397 SLOGE("Setfield error, cannot load persistent data");
3398 goto out;
3399 }
3400 }
3401
3402 property_get("ro.crypto.state", encrypted_state, "");
3403 if (!strcmp(encrypted_state, "encrypted") ) {
3404 encrypted = 1;
3405 }
3406
3407 if (persist_set_key(fieldname, value, encrypted)) {
3408 goto out;
3409 }
3410
3411 /* If we are running encrypted, save the persistent data now */
3412 if (encrypted) {
3413 if (save_persistent_data()) {
3414 SLOGE("Setfield error, cannot save persistent data");
3415 goto out;
3416 }
3417 }
3418
3419 rc = 0;
3420
3421out:
3422 return rc;
3423}
Paul Lawrencef4faa572014-01-29 13:31:03 -08003424
3425/* Checks userdata. Attempt to mount the volume if default-
3426 * encrypted.
3427 * On success trigger next init phase and return 0.
3428 * Currently do not handle failure - see TODO below.
3429 */
3430int cryptfs_mount_default_encrypted(void)
3431{
3432 char decrypt_state[PROPERTY_VALUE_MAX];
3433 property_get("vold.decrypt", decrypt_state, "0");
3434 if (!strcmp(decrypt_state, "0")) {
3435 SLOGE("Not encrypted - should not call here");
3436 } else {
3437 int crypt_type = cryptfs_get_password_type();
3438 if (crypt_type < 0 || crypt_type > CRYPT_TYPE_MAX_TYPE) {
3439 SLOGE("Bad crypt type - error");
3440 } else if (crypt_type != CRYPT_TYPE_DEFAULT) {
3441 SLOGD("Password is not default - "
3442 "starting min framework to prompt");
3443 property_set("vold.decrypt", "trigger_restart_min_framework");
3444 return 0;
3445 } else if (cryptfs_check_passwd(DEFAULT_PASSWORD) == 0) {
3446 SLOGD("Password is default - restarting filesystem");
3447 cryptfs_restart_internal(0);
3448 return 0;
3449 } else {
3450 SLOGE("Encrypted, default crypt type but can't decrypt");
3451 }
3452 }
3453
Paul Lawrence6bfed202014-07-28 12:47:22 -07003454 /** Corrupt. Allow us to boot into framework, which will detect bad
3455 crypto when it calls do_crypto_complete, then do a factory reset
Paul Lawrencef4faa572014-01-29 13:31:03 -08003456 */
Paul Lawrence6bfed202014-07-28 12:47:22 -07003457 property_set("vold.decrypt", "trigger_restart_min_framework");
Paul Lawrencef4faa572014-01-29 13:31:03 -08003458 return 0;
3459}
3460
3461/* Returns type of the password, default, pattern, pin or password.
3462 */
3463int cryptfs_get_password_type(void)
3464{
3465 struct crypt_mnt_ftr crypt_ftr;
3466
3467 if (get_crypt_ftr_and_key(&crypt_ftr)) {
3468 SLOGE("Error getting crypt footer and key\n");
3469 return -1;
3470 }
3471
Paul Lawrence6bfed202014-07-28 12:47:22 -07003472 if (crypt_ftr.flags & CRYPT_INCONSISTENT_STATE) {
3473 return -1;
3474 }
3475
Paul Lawrencef4faa572014-01-29 13:31:03 -08003476 return crypt_ftr.crypt_type;
3477}
Paul Lawrence684dbdf2014-02-07 12:07:22 -08003478
Paul Lawrence399317e2014-03-10 13:20:50 -07003479char* cryptfs_get_password()
Paul Lawrence684dbdf2014-02-07 12:07:22 -08003480{
Paul Lawrence399317e2014-03-10 13:20:50 -07003481 struct timespec now;
3482 clock_gettime(CLOCK_MONOTONIC, &now);
3483 if (now.tv_sec < password_expiry_time) {
3484 return password;
3485 } else {
3486 cryptfs_clear_password();
3487 return 0;
3488 }
3489}
3490
3491void cryptfs_clear_password()
3492{
3493 if (password) {
3494 size_t len = strlen(password);
3495 memset(password, 0, len);
3496 free(password);
3497 password = 0;
3498 password_expiry_time = 0;
3499 }
Paul Lawrence684dbdf2014-02-07 12:07:22 -08003500}