blob: 40a473f38b7f73c74a4d987fdeed62bf9683df6a [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>
28#include <unistd.h>
29#include <stdio.h>
30#include <sys/ioctl.h>
31#include <linux/dm-ioctl.h>
32#include <libgen.h>
33#include <stdlib.h>
34#include <sys/param.h>
35#include <string.h>
36#include <sys/mount.h>
37#include <openssl/evp.h>
38#include <errno.h>
Ken Sumrall3ed82362011-01-28 23:31:16 -080039#include <ext4.h>
Ken Sumrall29d8da82011-05-18 17:20:07 -070040#include <linux/kdev_t.h>
Ken Sumralle5032c42012-04-01 23:58:44 -070041#include <fs_mgr.h>
Ken Sumrall8f869aa2010-12-03 03:47:09 -080042#include "cryptfs.h"
43#define LOG_TAG "Cryptfs"
44#include "cutils/log.h"
45#include "cutils/properties.h"
Ken Sumralladfba362013-06-04 16:37:52 -070046#include "cutils/android_reboot.h"
Ken Sumrall5d4c68e2011-01-30 19:06:03 -080047#include "hardware_legacy/power.h"
Ken Sumralle550f782013-08-20 13:48:23 -070048#include <logwrap/logwrap.h>
Ken Sumrall29d8da82011-05-18 17:20:07 -070049#include "VolumeManager.h"
Ken Sumrall9caab762013-06-11 19:10:20 -070050#include "VoldUtil.h"
Kenny Rootc4c70f12013-06-14 12:11:38 -070051#include "crypto_scrypt.h"
Paul Lawrenceae59fe62014-01-21 08:23:27 -080052#include "ext4_utils.h"
Paul Lawrence87999172014-02-20 12:21:31 -080053#include "CheckBattery.h"
Ken Sumrall8f869aa2010-12-03 03:47:09 -080054
Mark Salyzyn3e971272014-01-21 13:27:04 -080055#define UNUSED __attribute__((unused))
56
Mark Salyzyn5eecc442014-02-12 14:16:14 -080057#define UNUSED __attribute__((unused))
58
Ken Sumrall8f869aa2010-12-03 03:47:09 -080059#define DM_CRYPT_BUF_SIZE 4096
60
Jason parks70a4b3f2011-01-28 10:10:47 -060061#define HASH_COUNT 2000
62#define KEY_LEN_BYTES 16
63#define IV_LEN_BYTES 16
64
Ken Sumrall29d8da82011-05-18 17:20:07 -070065#define KEY_IN_FOOTER "footer"
66
Paul Lawrencef4faa572014-01-29 13:31:03 -080067// "default_password" encoded into hex (d=0x64 etc)
68#define DEFAULT_PASSWORD "64656661756c745f70617373776f7264"
69
Ken Sumrall29d8da82011-05-18 17:20:07 -070070#define EXT4_FS 1
71#define FAT_FS 2
72
Ken Sumralle919efe2012-09-29 17:07:41 -070073#define TABLE_LOAD_RETRIES 10
74
Ken Sumrall8f869aa2010-12-03 03:47:09 -080075char *me = "cryptfs";
76
Jason parks70a4b3f2011-01-28 10:10:47 -060077static unsigned char saved_master_key[KEY_LEN_BYTES];
Ken Sumrall3ad90722011-10-04 20:38:29 -070078static char *saved_mount_point;
Jason parks70a4b3f2011-01-28 10:10:47 -060079static int master_key_saved = 0;
Ken Sumrall160b4d62013-04-22 12:15:39 -070080static struct crypt_persist_data *persist_data = NULL;
Ken Sumrall56ad03c2013-02-13 13:00:19 -080081
Paul Lawrence399317e2014-03-10 13:20:50 -070082/* Store password when userdata is successfully decrypted and mounted.
83 * Cleared by cryptfs_clear_password
84 *
85 * To avoid a double prompt at boot, we need to store the CryptKeeper
86 * password and pass it to KeyGuard, which uses it to unlock KeyStore.
87 * Since the entire framework is torn down and rebuilt after encryption,
88 * we have to use a daemon or similar to store the password. Since vold
89 * is secured against IPC except from system processes, it seems a reasonable
90 * place to store this.
91 *
92 * password should be cleared once it has been used.
93 *
94 * password is aged out after password_max_age_seconds seconds.
Paul Lawrence684dbdf2014-02-07 12:07:22 -080095 */
Paul Lawrence399317e2014-03-10 13:20:50 -070096static char* password = 0;
97static int password_expiry_time = 0;
98static const int password_max_age_seconds = 60;
Paul Lawrence684dbdf2014-02-07 12:07:22 -080099
Ken Sumrall56ad03c2013-02-13 13:00:19 -0800100extern struct fstab *fstab;
Ken Sumrall8ddbe402011-01-17 15:26:29 -0800101
Paul Lawrence87999172014-02-20 12:21:31 -0800102enum RebootType {reboot, recovery, shutdown};
103static void cryptfs_reboot(enum RebootType rt)
Ken Sumralladfba362013-06-04 16:37:52 -0700104{
Paul Lawrence87999172014-02-20 12:21:31 -0800105 switch(rt) {
106 case reboot:
107 property_set(ANDROID_RB_PROPERTY, "reboot");
108 break;
109
110 case recovery:
111 property_set(ANDROID_RB_PROPERTY, "reboot,recovery");
112 break;
113
114 case shutdown:
115 property_set(ANDROID_RB_PROPERTY, "shutdown");
116 break;
Ken Sumralladfba362013-06-04 16:37:52 -0700117 }
Paul Lawrence87999172014-02-20 12:21:31 -0800118
Ken Sumralladfba362013-06-04 16:37:52 -0700119 sleep(20);
120
121 /* Shouldn't get here, reboot should happen before sleep times out */
122 return;
123}
124
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800125static void ioctl_init(struct dm_ioctl *io, size_t dataSize, const char *name, unsigned flags)
126{
127 memset(io, 0, dataSize);
128 io->data_size = dataSize;
129 io->data_start = sizeof(struct dm_ioctl);
130 io->version[0] = 4;
131 io->version[1] = 0;
132 io->version[2] = 0;
133 io->flags = flags;
134 if (name) {
135 strncpy(io->name, name, sizeof(io->name));
136 }
137}
138
Kenny Rootc4c70f12013-06-14 12:11:38 -0700139/**
140 * Gets the default device scrypt parameters for key derivation time tuning.
141 * The parameters should lead to about one second derivation time for the
142 * given device.
143 */
144static void get_device_scrypt_params(struct crypt_mnt_ftr *ftr) {
145 const int default_params[] = SCRYPT_DEFAULTS;
146 int params[] = SCRYPT_DEFAULTS;
147 char paramstr[PROPERTY_VALUE_MAX];
148 char *token;
149 char *saveptr;
150 int i;
151
152 property_get(SCRYPT_PROP, paramstr, "");
153 if (paramstr[0] != '\0') {
154 /*
155 * The token we're looking for should be three integers separated by
156 * colons (e.g., "12:8:1"). Scan the property to make sure it matches.
157 */
Kenny Root2947e342013-08-14 15:54:49 -0700158 for (i = 0, token = strtok_r(paramstr, ":", &saveptr);
159 token != NULL && i < 3;
Kenny Rootc4c70f12013-06-14 12:11:38 -0700160 i++, token = strtok_r(NULL, ":", &saveptr)) {
161 char *endptr;
162 params[i] = strtol(token, &endptr, 10);
163
164 /*
165 * Check that there was a valid number and it's 8-bit. If not,
166 * break out and the end check will take the default values.
167 */
168 if ((*token == '\0') || (*endptr != '\0') || params[i] < 0 || params[i] > 255) {
169 break;
170 }
171 }
172
173 /*
174 * If there were not enough tokens or a token was malformed (not an
175 * integer), it will end up here and the default parameters can be
176 * taken.
177 */
178 if ((i != 3) || (token != NULL)) {
179 SLOGW("bad scrypt parameters '%s' should be like '12:8:1'; using defaults", paramstr);
180 memcpy(params, default_params, sizeof(params));
181 }
182 }
183
184 ftr->N_factor = params[0];
185 ftr->r_factor = params[1];
186 ftr->p_factor = params[2];
187}
188
Ken Sumrall3ed82362011-01-28 23:31:16 -0800189static unsigned int get_fs_size(char *dev)
190{
191 int fd, block_size;
192 struct ext4_super_block sb;
193 off64_t len;
194
195 if ((fd = open(dev, O_RDONLY)) < 0) {
196 SLOGE("Cannot open device to get filesystem size ");
197 return 0;
198 }
199
200 if (lseek64(fd, 1024, SEEK_SET) < 0) {
201 SLOGE("Cannot seek to superblock");
202 return 0;
203 }
204
205 if (read(fd, &sb, sizeof(sb)) != sizeof(sb)) {
206 SLOGE("Cannot read superblock");
207 return 0;
208 }
209
210 close(fd);
211
212 block_size = 1024 << sb.s_log_block_size;
213 /* compute length in bytes */
214 len = ( ((off64_t)sb.s_blocks_count_hi << 32) + sb.s_blocks_count_lo) * block_size;
215
216 /* return length in sectors */
217 return (unsigned int) (len / 512);
218}
219
Ken Sumrall160b4d62013-04-22 12:15:39 -0700220static int get_crypt_ftr_info(char **metadata_fname, off64_t *off)
221{
222 static int cached_data = 0;
223 static off64_t cached_off = 0;
224 static char cached_metadata_fname[PROPERTY_VALUE_MAX] = "";
225 int fd;
226 char key_loc[PROPERTY_VALUE_MAX];
227 char real_blkdev[PROPERTY_VALUE_MAX];
228 unsigned int nr_sec;
229 int rc = -1;
230
231 if (!cached_data) {
232 fs_mgr_get_crypt_info(fstab, key_loc, real_blkdev, sizeof(key_loc));
233
234 if (!strcmp(key_loc, KEY_IN_FOOTER)) {
235 if ( (fd = open(real_blkdev, O_RDWR)) < 0) {
236 SLOGE("Cannot open real block device %s\n", real_blkdev);
237 return -1;
238 }
239
240 if ((nr_sec = get_blkdev_size(fd))) {
241 /* If it's an encrypted Android partition, the last 16 Kbytes contain the
242 * encryption info footer and key, and plenty of bytes to spare for future
243 * growth.
244 */
245 strlcpy(cached_metadata_fname, real_blkdev, sizeof(cached_metadata_fname));
246 cached_off = ((off64_t)nr_sec * 512) - CRYPT_FOOTER_OFFSET;
247 cached_data = 1;
248 } else {
249 SLOGE("Cannot get size of block device %s\n", real_blkdev);
250 }
251 close(fd);
252 } else {
253 strlcpy(cached_metadata_fname, key_loc, sizeof(cached_metadata_fname));
254 cached_off = 0;
255 cached_data = 1;
256 }
257 }
258
259 if (cached_data) {
260 if (metadata_fname) {
261 *metadata_fname = cached_metadata_fname;
262 }
263 if (off) {
264 *off = cached_off;
265 }
266 rc = 0;
267 }
268
269 return rc;
270}
271
Ken Sumralle8744072011-01-18 22:01:55 -0800272/* key or salt can be NULL, in which case just skip writing that value. Useful to
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800273 * update the failed mount count but not change the key.
274 */
Ken Sumrall160b4d62013-04-22 12:15:39 -0700275static int put_crypt_ftr_and_key(struct crypt_mnt_ftr *crypt_ftr)
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800276{
277 int fd;
278 unsigned int nr_sec, cnt;
Ken Sumrall160b4d62013-04-22 12:15:39 -0700279 /* starting_off is set to the SEEK_SET offset
280 * where the crypto structure starts
281 */
282 off64_t starting_off;
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800283 int rc = -1;
Ken Sumrall160b4d62013-04-22 12:15:39 -0700284 char *fname = NULL;
Ken Sumrall3be890f2011-09-14 16:53:46 -0700285 struct stat statbuf;
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800286
Ken Sumrall160b4d62013-04-22 12:15:39 -0700287 if (get_crypt_ftr_info(&fname, &starting_off)) {
288 SLOGE("Unable to get crypt_ftr_info\n");
289 return -1;
290 }
291 if (fname[0] != '/') {
Ken Sumralle5032c42012-04-01 23:58:44 -0700292 SLOGE("Unexpected value for crypto key location\n");
Ken Sumrall160b4d62013-04-22 12:15:39 -0700293 return -1;
294 }
Ken Sumralle550f782013-08-20 13:48:23 -0700295 if ( (fd = open(fname, O_RDWR | O_CREAT, 0600)) < 0) {
296 SLOGE("Cannot open footer file %s for put\n", fname);
Ken Sumrall160b4d62013-04-22 12:15:39 -0700297 return -1;
298 }
299
300 /* Seek to the start of the crypt footer */
301 if (lseek64(fd, starting_off, SEEK_SET) == -1) {
302 SLOGE("Cannot seek to real block device footer\n");
303 goto errout;
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800304 }
305
306 if ((cnt = write(fd, crypt_ftr, sizeof(struct crypt_mnt_ftr))) != sizeof(struct crypt_mnt_ftr)) {
307 SLOGE("Cannot write real block device footer\n");
308 goto errout;
309 }
310
Ken Sumrall3be890f2011-09-14 16:53:46 -0700311 fstat(fd, &statbuf);
312 /* If the keys are kept on a raw block device, do not try to truncate it. */
Ken Sumralle550f782013-08-20 13:48:23 -0700313 if (S_ISREG(statbuf.st_mode)) {
Ken Sumrall29d8da82011-05-18 17:20:07 -0700314 if (ftruncate(fd, 0x4000)) {
Colin Cross59846b62014-02-06 20:34:29 -0800315 SLOGE("Cannot set footer file size\n");
Ken Sumralle8744072011-01-18 22:01:55 -0800316 goto errout;
317 }
318 }
319
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800320 /* Success! */
321 rc = 0;
322
323errout:
324 close(fd);
325 return rc;
326
327}
328
Ken Sumrall160b4d62013-04-22 12:15:39 -0700329static inline int unix_read(int fd, void* buff, int len)
330{
331 return TEMP_FAILURE_RETRY(read(fd, buff, len));
332}
333
334static inline int unix_write(int fd, const void* buff, int len)
335{
336 return TEMP_FAILURE_RETRY(write(fd, buff, len));
337}
338
339static void init_empty_persist_data(struct crypt_persist_data *pdata, int len)
340{
341 memset(pdata, 0, len);
342 pdata->persist_magic = PERSIST_DATA_MAGIC;
343 pdata->persist_valid_entries = 0;
344}
345
346/* A routine to update the passed in crypt_ftr to the lastest version.
347 * fd is open read/write on the device that holds the crypto footer and persistent
348 * data, crypt_ftr is a pointer to the struct to be updated, and offset is the
349 * absolute offset to the start of the crypt_mnt_ftr on the passed in fd.
350 */
351static void upgrade_crypt_ftr(int fd, struct crypt_mnt_ftr *crypt_ftr, off64_t offset)
352{
Kenny Root7434b312013-06-14 11:29:53 -0700353 int orig_major = crypt_ftr->major_version;
354 int orig_minor = crypt_ftr->minor_version;
Ken Sumrall160b4d62013-04-22 12:15:39 -0700355
Kenny Root7434b312013-06-14 11:29:53 -0700356 if ((crypt_ftr->major_version == 1) && (crypt_ftr->minor_version == 0)) {
357 struct crypt_persist_data *pdata;
358 off64_t pdata_offset = offset + CRYPT_FOOTER_TO_PERSIST_OFFSET;
Ken Sumrall160b4d62013-04-22 12:15:39 -0700359
Kenny Rootc4c70f12013-06-14 12:11:38 -0700360 SLOGW("upgrading crypto footer to 1.1");
361
Kenny Root7434b312013-06-14 11:29:53 -0700362 pdata = malloc(CRYPT_PERSIST_DATA_SIZE);
363 if (pdata == NULL) {
364 SLOGE("Cannot allocate persisent data\n");
365 return;
366 }
367 memset(pdata, 0, CRYPT_PERSIST_DATA_SIZE);
368
369 /* Need to initialize the persistent data area */
370 if (lseek64(fd, pdata_offset, SEEK_SET) == -1) {
371 SLOGE("Cannot seek to persisent data offset\n");
372 return;
373 }
374 /* Write all zeros to the first copy, making it invalid */
375 unix_write(fd, pdata, CRYPT_PERSIST_DATA_SIZE);
376
377 /* Write a valid but empty structure to the second copy */
378 init_empty_persist_data(pdata, CRYPT_PERSIST_DATA_SIZE);
379 unix_write(fd, pdata, CRYPT_PERSIST_DATA_SIZE);
380
381 /* Update the footer */
382 crypt_ftr->persist_data_size = CRYPT_PERSIST_DATA_SIZE;
383 crypt_ftr->persist_data_offset[0] = pdata_offset;
384 crypt_ftr->persist_data_offset[1] = pdata_offset + CRYPT_PERSIST_DATA_SIZE;
385 crypt_ftr->minor_version = 1;
Ken Sumrall160b4d62013-04-22 12:15:39 -0700386 }
387
Paul Lawrencef4faa572014-01-29 13:31:03 -0800388 if ((crypt_ftr->major_version == 1) && (crypt_ftr->minor_version == 1)) {
Kenny Rootc4c70f12013-06-14 12:11:38 -0700389 SLOGW("upgrading crypto footer to 1.2");
JP Abgrall7bdfa522013-11-15 13:42:56 -0800390 /* But keep the old kdf_type.
391 * It will get updated later to KDF_SCRYPT after the password has been verified.
392 */
Kenny Rootc4c70f12013-06-14 12:11:38 -0700393 crypt_ftr->kdf_type = KDF_PBKDF2;
394 get_device_scrypt_params(crypt_ftr);
395 crypt_ftr->minor_version = 2;
396 }
397
Paul Lawrencef4faa572014-01-29 13:31:03 -0800398 if ((crypt_ftr->major_version == 1) && (crypt_ftr->minor_version == 2)) {
399 SLOGW("upgrading crypto footer to 1.3");
400 crypt_ftr->crypt_type = CRYPT_TYPE_PASSWORD;
401 crypt_ftr->minor_version = 3;
402 }
403
Kenny Root7434b312013-06-14 11:29:53 -0700404 if ((orig_major != crypt_ftr->major_version) || (orig_minor != crypt_ftr->minor_version)) {
405 if (lseek64(fd, offset, SEEK_SET) == -1) {
406 SLOGE("Cannot seek to crypt footer\n");
407 return;
408 }
409 unix_write(fd, crypt_ftr, sizeof(struct crypt_mnt_ftr));
Ken Sumrall160b4d62013-04-22 12:15:39 -0700410 }
Ken Sumrall160b4d62013-04-22 12:15:39 -0700411}
412
413
414static int get_crypt_ftr_and_key(struct crypt_mnt_ftr *crypt_ftr)
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800415{
416 int fd;
417 unsigned int nr_sec, cnt;
Ken Sumrall160b4d62013-04-22 12:15:39 -0700418 off64_t starting_off;
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800419 int rc = -1;
Ken Sumrall160b4d62013-04-22 12:15:39 -0700420 char *fname = NULL;
Ken Sumrall29d8da82011-05-18 17:20:07 -0700421 struct stat statbuf;
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800422
Ken Sumrall160b4d62013-04-22 12:15:39 -0700423 if (get_crypt_ftr_info(&fname, &starting_off)) {
424 SLOGE("Unable to get crypt_ftr_info\n");
425 return -1;
426 }
427 if (fname[0] != '/') {
Ken Sumralle5032c42012-04-01 23:58:44 -0700428 SLOGE("Unexpected value for crypto key location\n");
Ken Sumrall160b4d62013-04-22 12:15:39 -0700429 return -1;
430 }
431 if ( (fd = open(fname, O_RDWR)) < 0) {
Ken Sumralle550f782013-08-20 13:48:23 -0700432 SLOGE("Cannot open footer file %s for get\n", fname);
Ken Sumrall160b4d62013-04-22 12:15:39 -0700433 return -1;
434 }
435
436 /* Make sure it's 16 Kbytes in length */
437 fstat(fd, &statbuf);
438 if (S_ISREG(statbuf.st_mode) && (statbuf.st_size != 0x4000)) {
439 SLOGE("footer file %s is not the expected size!\n", fname);
440 goto errout;
441 }
442
443 /* Seek to the start of the crypt footer */
444 if (lseek64(fd, starting_off, SEEK_SET) == -1) {
445 SLOGE("Cannot seek to real block device footer\n");
446 goto errout;
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800447 }
448
449 if ( (cnt = read(fd, crypt_ftr, sizeof(struct crypt_mnt_ftr))) != sizeof(struct crypt_mnt_ftr)) {
450 SLOGE("Cannot read real block device footer\n");
451 goto errout;
452 }
453
454 if (crypt_ftr->magic != CRYPT_MNT_MAGIC) {
Ken Sumrall29d8da82011-05-18 17:20:07 -0700455 SLOGE("Bad magic for real block device %s\n", fname);
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800456 goto errout;
457 }
458
Kenny Rootc96a5f82013-06-14 12:08:28 -0700459 if (crypt_ftr->major_version != CURRENT_MAJOR_VERSION) {
460 SLOGE("Cannot understand major version %d real block device footer; expected %d\n",
461 crypt_ftr->major_version, CURRENT_MAJOR_VERSION);
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800462 goto errout;
463 }
464
Kenny Rootc96a5f82013-06-14 12:08:28 -0700465 if (crypt_ftr->minor_version > CURRENT_MINOR_VERSION) {
466 SLOGW("Warning: crypto footer minor version %d, expected <= %d, continuing...\n",
467 crypt_ftr->minor_version, CURRENT_MINOR_VERSION);
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800468 }
469
Ken Sumrall160b4d62013-04-22 12:15:39 -0700470 /* If this is a verion 1.0 crypt_ftr, make it a 1.1 crypt footer, and update the
471 * copy on disk before returning.
472 */
Kenny Rootc96a5f82013-06-14 12:08:28 -0700473 if (crypt_ftr->minor_version < CURRENT_MINOR_VERSION) {
Ken Sumrall160b4d62013-04-22 12:15:39 -0700474 upgrade_crypt_ftr(fd, crypt_ftr, starting_off);
Ken Sumralle8744072011-01-18 22:01:55 -0800475 }
476
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800477 /* Success! */
478 rc = 0;
479
480errout:
481 close(fd);
482 return rc;
483}
484
Ken Sumrall160b4d62013-04-22 12:15:39 -0700485static int validate_persistent_data_storage(struct crypt_mnt_ftr *crypt_ftr)
486{
487 if (crypt_ftr->persist_data_offset[0] + crypt_ftr->persist_data_size >
488 crypt_ftr->persist_data_offset[1]) {
489 SLOGE("Crypt_ftr persist data regions overlap");
490 return -1;
491 }
492
493 if (crypt_ftr->persist_data_offset[0] >= crypt_ftr->persist_data_offset[1]) {
494 SLOGE("Crypt_ftr persist data region 0 starts after region 1");
495 return -1;
496 }
497
498 if (((crypt_ftr->persist_data_offset[1] + crypt_ftr->persist_data_size) -
499 (crypt_ftr->persist_data_offset[0] - CRYPT_FOOTER_TO_PERSIST_OFFSET)) >
500 CRYPT_FOOTER_OFFSET) {
501 SLOGE("Persistent data extends past crypto footer");
502 return -1;
503 }
504
505 return 0;
506}
507
508static int load_persistent_data(void)
509{
510 struct crypt_mnt_ftr crypt_ftr;
511 struct crypt_persist_data *pdata = NULL;
512 char encrypted_state[PROPERTY_VALUE_MAX];
513 char *fname;
514 int found = 0;
515 int fd;
516 int ret;
517 int i;
518
519 if (persist_data) {
520 /* Nothing to do, we've already loaded or initialized it */
521 return 0;
522 }
523
524
525 /* If not encrypted, just allocate an empty table and initialize it */
526 property_get("ro.crypto.state", encrypted_state, "");
527 if (strcmp(encrypted_state, "encrypted") ) {
528 pdata = malloc(CRYPT_PERSIST_DATA_SIZE);
529 if (pdata) {
530 init_empty_persist_data(pdata, CRYPT_PERSIST_DATA_SIZE);
531 persist_data = pdata;
532 return 0;
533 }
534 return -1;
535 }
536
537 if(get_crypt_ftr_and_key(&crypt_ftr)) {
538 return -1;
539 }
540
Paul Lawrence8561b5c2014-03-17 14:10:51 -0700541 if ((crypt_ftr.major_version < 1)
542 || (crypt_ftr.major_version == 1 && crypt_ftr.minor_version < 1)) {
Ken Sumrall160b4d62013-04-22 12:15:39 -0700543 SLOGE("Crypt_ftr version doesn't support persistent data");
544 return -1;
545 }
546
547 if (get_crypt_ftr_info(&fname, NULL)) {
548 return -1;
549 }
550
551 ret = validate_persistent_data_storage(&crypt_ftr);
552 if (ret) {
553 return -1;
554 }
555
556 fd = open(fname, O_RDONLY);
557 if (fd < 0) {
558 SLOGE("Cannot open %s metadata file", fname);
559 return -1;
560 }
561
562 if (persist_data == NULL) {
563 pdata = malloc(crypt_ftr.persist_data_size);
564 if (pdata == NULL) {
565 SLOGE("Cannot allocate memory for persistent data");
566 goto err;
567 }
568 }
569
570 for (i = 0; i < 2; i++) {
571 if (lseek64(fd, crypt_ftr.persist_data_offset[i], SEEK_SET) < 0) {
572 SLOGE("Cannot seek to read persistent data on %s", fname);
573 goto err2;
574 }
575 if (unix_read(fd, pdata, crypt_ftr.persist_data_size) < 0){
576 SLOGE("Error reading persistent data on iteration %d", i);
577 goto err2;
578 }
579 if (pdata->persist_magic == PERSIST_DATA_MAGIC) {
580 found = 1;
581 break;
582 }
583 }
584
585 if (!found) {
586 SLOGI("Could not find valid persistent data, creating");
587 init_empty_persist_data(pdata, crypt_ftr.persist_data_size);
588 }
589
590 /* Success */
591 persist_data = pdata;
592 close(fd);
593 return 0;
594
595err2:
596 free(pdata);
597
598err:
599 close(fd);
600 return -1;
601}
602
603static int save_persistent_data(void)
604{
605 struct crypt_mnt_ftr crypt_ftr;
606 struct crypt_persist_data *pdata;
607 char *fname;
608 off64_t write_offset;
609 off64_t erase_offset;
610 int found = 0;
611 int fd;
612 int ret;
613
614 if (persist_data == NULL) {
615 SLOGE("No persistent data to save");
616 return -1;
617 }
618
619 if(get_crypt_ftr_and_key(&crypt_ftr)) {
620 return -1;
621 }
622
Paul Lawrence8561b5c2014-03-17 14:10:51 -0700623 if ((crypt_ftr.major_version < 1)
624 || (crypt_ftr.major_version == 1 && crypt_ftr.minor_version < 1)) {
Ken Sumrall160b4d62013-04-22 12:15:39 -0700625 SLOGE("Crypt_ftr version doesn't support persistent data");
626 return -1;
627 }
628
629 ret = validate_persistent_data_storage(&crypt_ftr);
630 if (ret) {
631 return -1;
632 }
633
634 if (get_crypt_ftr_info(&fname, NULL)) {
635 return -1;
636 }
637
638 fd = open(fname, O_RDWR);
639 if (fd < 0) {
640 SLOGE("Cannot open %s metadata file", fname);
641 return -1;
642 }
643
644 pdata = malloc(crypt_ftr.persist_data_size);
645 if (pdata == NULL) {
646 SLOGE("Cannot allocate persistant data");
647 goto err;
648 }
649
650 if (lseek64(fd, crypt_ftr.persist_data_offset[0], SEEK_SET) < 0) {
651 SLOGE("Cannot seek to read persistent data on %s", fname);
652 goto err2;
653 }
654
655 if (unix_read(fd, pdata, crypt_ftr.persist_data_size) < 0) {
656 SLOGE("Error reading persistent data before save");
657 goto err2;
658 }
659
660 if (pdata->persist_magic == PERSIST_DATA_MAGIC) {
661 /* The first copy is the curent valid copy, so write to
662 * the second copy and erase this one */
663 write_offset = crypt_ftr.persist_data_offset[1];
664 erase_offset = crypt_ftr.persist_data_offset[0];
665 } else {
666 /* The second copy must be the valid copy, so write to
667 * the first copy, and erase the second */
668 write_offset = crypt_ftr.persist_data_offset[0];
669 erase_offset = crypt_ftr.persist_data_offset[1];
670 }
671
672 /* Write the new copy first, if successful, then erase the old copy */
673 if (lseek(fd, write_offset, SEEK_SET) < 0) {
674 SLOGE("Cannot seek to write persistent data");
675 goto err2;
676 }
677 if (unix_write(fd, persist_data, crypt_ftr.persist_data_size) ==
678 (int) crypt_ftr.persist_data_size) {
679 if (lseek(fd, erase_offset, SEEK_SET) < 0) {
680 SLOGE("Cannot seek to erase previous persistent data");
681 goto err2;
682 }
683 fsync(fd);
684 memset(pdata, 0, crypt_ftr.persist_data_size);
685 if (unix_write(fd, pdata, crypt_ftr.persist_data_size) !=
686 (int) crypt_ftr.persist_data_size) {
687 SLOGE("Cannot write to erase previous persistent data");
688 goto err2;
689 }
690 fsync(fd);
691 } else {
692 SLOGE("Cannot write to save persistent data");
693 goto err2;
694 }
695
696 /* Success */
697 free(pdata);
698 close(fd);
699 return 0;
700
701err2:
702 free(pdata);
703err:
704 close(fd);
705 return -1;
706}
707
Paul Lawrencef4faa572014-01-29 13:31:03 -0800708static int hexdigit (char c)
709{
710 if (c >= '0' && c <= '9') return c - '0';
711 c = tolower(c);
712 if (c >= 'a' && c <= 'f') return c - 'a' + 10;
713 return -1;
714}
715
716static unsigned char* convert_hex_ascii_to_key(const char* master_key_ascii,
717 unsigned int* out_keysize)
718{
719 unsigned int i;
720 *out_keysize = 0;
721
722 size_t size = strlen (master_key_ascii);
723 if (size % 2) {
724 SLOGE("Trying to convert ascii string of odd length");
725 return NULL;
726 }
727
728 unsigned char* master_key = (unsigned char*) malloc(size / 2);
729 if (master_key == 0) {
730 SLOGE("Cannot allocate");
731 return NULL;
732 }
733
734 for (i = 0; i < size; i += 2) {
735 int high_nibble = hexdigit (master_key_ascii[i]);
736 int low_nibble = hexdigit (master_key_ascii[i + 1]);
737
738 if(high_nibble < 0 || low_nibble < 0) {
739 SLOGE("Invalid hex string");
740 free (master_key);
741 return NULL;
742 }
743
744 master_key[*out_keysize] = high_nibble * 16 + low_nibble;
745 (*out_keysize)++;
746 }
747
748 return master_key;
749}
750
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800751/* Convert a binary key of specified length into an ascii hex string equivalent,
752 * without the leading 0x and with null termination
753 */
Paul Lawrencef4faa572014-01-29 13:31:03 -0800754static void convert_key_to_hex_ascii(unsigned char *master_key, unsigned int keysize,
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800755 char *master_key_ascii)
756{
757 unsigned int i, a;
758 unsigned char nibble;
759
760 for (i=0, a=0; i<keysize; i++, a+=2) {
761 /* For each byte, write out two ascii hex digits */
762 nibble = (master_key[i] >> 4) & 0xf;
763 master_key_ascii[a] = nibble + (nibble > 9 ? 0x37 : 0x30);
764
765 nibble = master_key[i] & 0xf;
766 master_key_ascii[a+1] = nibble + (nibble > 9 ? 0x37 : 0x30);
767 }
768
769 /* Add the null termination */
770 master_key_ascii[a] = '\0';
771
772}
773
Ken Sumralldb5e0262013-02-05 17:39:48 -0800774static int load_crypto_mapping_table(struct crypt_mnt_ftr *crypt_ftr, unsigned char *master_key,
775 char *real_blk_name, const char *name, int fd,
776 char *extra_params)
777{
778 char buffer[DM_CRYPT_BUF_SIZE];
779 struct dm_ioctl *io;
780 struct dm_target_spec *tgt;
781 char *crypt_params;
782 char master_key_ascii[129]; /* Large enough to hold 512 bit key and null */
783 int i;
784
785 io = (struct dm_ioctl *) buffer;
786
787 /* Load the mapping table for this device */
788 tgt = (struct dm_target_spec *) &buffer[sizeof(struct dm_ioctl)];
789
790 ioctl_init(io, DM_CRYPT_BUF_SIZE, name, 0);
791 io->target_count = 1;
792 tgt->status = 0;
793 tgt->sector_start = 0;
794 tgt->length = crypt_ftr->fs_size;
795 strcpy(tgt->target_type, "crypt");
796
797 crypt_params = buffer + sizeof(struct dm_ioctl) + sizeof(struct dm_target_spec);
798 convert_key_to_hex_ascii(master_key, crypt_ftr->keysize, master_key_ascii);
799 sprintf(crypt_params, "%s %s 0 %s 0 %s", crypt_ftr->crypto_type_name,
800 master_key_ascii, real_blk_name, extra_params);
801 crypt_params += strlen(crypt_params) + 1;
802 crypt_params = (char *) (((unsigned long)crypt_params + 7) & ~8); /* Align to an 8 byte boundary */
803 tgt->next = crypt_params - buffer;
804
805 for (i = 0; i < TABLE_LOAD_RETRIES; i++) {
806 if (! ioctl(fd, DM_TABLE_LOAD, io)) {
807 break;
808 }
809 usleep(500000);
810 }
811
812 if (i == TABLE_LOAD_RETRIES) {
813 /* We failed to load the table, return an error */
814 return -1;
815 } else {
816 return i + 1;
817 }
818}
819
820
821static int get_dm_crypt_version(int fd, const char *name, int *version)
822{
823 char buffer[DM_CRYPT_BUF_SIZE];
824 struct dm_ioctl *io;
825 struct dm_target_versions *v;
826 int i;
827
828 io = (struct dm_ioctl *) buffer;
829
830 ioctl_init(io, DM_CRYPT_BUF_SIZE, name, 0);
831
832 if (ioctl(fd, DM_LIST_VERSIONS, io)) {
833 return -1;
834 }
835
836 /* Iterate over the returned versions, looking for name of "crypt".
837 * When found, get and return the version.
838 */
839 v = (struct dm_target_versions *) &buffer[sizeof(struct dm_ioctl)];
840 while (v->next) {
841 if (! strcmp(v->name, "crypt")) {
842 /* We found the crypt driver, return the version, and get out */
843 version[0] = v->version[0];
844 version[1] = v->version[1];
845 version[2] = v->version[2];
846 return 0;
847 }
848 v = (struct dm_target_versions *)(((char *)v) + v->next);
849 }
850
851 return -1;
852}
853
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800854static int create_crypto_blk_dev(struct crypt_mnt_ftr *crypt_ftr, unsigned char *master_key,
Ken Sumrall29d8da82011-05-18 17:20:07 -0700855 char *real_blk_name, char *crypto_blk_name, const char *name)
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800856{
857 char buffer[DM_CRYPT_BUF_SIZE];
858 char master_key_ascii[129]; /* Large enough to hold 512 bit key and null */
859 char *crypt_params;
860 struct dm_ioctl *io;
861 struct dm_target_spec *tgt;
862 unsigned int minor;
863 int fd;
Ken Sumralle919efe2012-09-29 17:07:41 -0700864 int i;
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800865 int retval = -1;
Ken Sumralldb5e0262013-02-05 17:39:48 -0800866 int version[3];
867 char *extra_params;
868 int load_count;
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800869
870 if ((fd = open("/dev/device-mapper", O_RDWR)) < 0 ) {
871 SLOGE("Cannot open device-mapper\n");
872 goto errout;
873 }
874
875 io = (struct dm_ioctl *) buffer;
876
877 ioctl_init(io, DM_CRYPT_BUF_SIZE, name, 0);
878 if (ioctl(fd, DM_DEV_CREATE, io)) {
879 SLOGE("Cannot create dm-crypt device\n");
880 goto errout;
881 }
882
883 /* Get the device status, in particular, the name of it's device file */
884 ioctl_init(io, DM_CRYPT_BUF_SIZE, name, 0);
885 if (ioctl(fd, DM_DEV_STATUS, io)) {
886 SLOGE("Cannot retrieve dm-crypt device status\n");
887 goto errout;
888 }
889 minor = (io->dev & 0xff) | ((io->dev >> 12) & 0xfff00);
890 snprintf(crypto_blk_name, MAXPATHLEN, "/dev/block/dm-%u", minor);
891
Ken Sumralldb5e0262013-02-05 17:39:48 -0800892 extra_params = "";
893 if (! get_dm_crypt_version(fd, name, version)) {
894 /* Support for allow_discards was added in version 1.11.0 */
895 if ((version[0] >= 2) ||
896 ((version[0] == 1) && (version[1] >= 11))) {
897 extra_params = "1 allow_discards";
898 SLOGI("Enabling support for allow_discards in dmcrypt.\n");
899 }
Ken Sumralle919efe2012-09-29 17:07:41 -0700900 }
901
Ken Sumralldb5e0262013-02-05 17:39:48 -0800902 load_count = load_crypto_mapping_table(crypt_ftr, master_key, real_blk_name, name,
903 fd, extra_params);
904 if (load_count < 0) {
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800905 SLOGE("Cannot load dm-crypt mapping table.\n");
906 goto errout;
Ken Sumralldb5e0262013-02-05 17:39:48 -0800907 } else if (load_count > 1) {
908 SLOGI("Took %d tries to load dmcrypt table.\n", load_count);
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800909 }
910
911 /* Resume this device to activate it */
Ken Sumralldb5e0262013-02-05 17:39:48 -0800912 ioctl_init(io, DM_CRYPT_BUF_SIZE, name, 0);
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800913
914 if (ioctl(fd, DM_DEV_SUSPEND, io)) {
915 SLOGE("Cannot resume the dm-crypt device\n");
916 goto errout;
917 }
918
919 /* We made it here with no errors. Woot! */
920 retval = 0;
921
922errout:
923 close(fd); /* If fd is <0 from a failed open call, it's safe to just ignore the close error */
924
925 return retval;
926}
927
Ken Sumrall29d8da82011-05-18 17:20:07 -0700928static int delete_crypto_blk_dev(char *name)
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800929{
930 int fd;
931 char buffer[DM_CRYPT_BUF_SIZE];
932 struct dm_ioctl *io;
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800933 int retval = -1;
934
935 if ((fd = open("/dev/device-mapper", O_RDWR)) < 0 ) {
936 SLOGE("Cannot open device-mapper\n");
937 goto errout;
938 }
939
940 io = (struct dm_ioctl *) buffer;
941
942 ioctl_init(io, DM_CRYPT_BUF_SIZE, name, 0);
943 if (ioctl(fd, DM_DEV_REMOVE, io)) {
944 SLOGE("Cannot remove dm-crypt device\n");
945 goto errout;
946 }
947
948 /* We made it here with no errors. Woot! */
949 retval = 0;
950
951errout:
952 close(fd); /* If fd is <0 from a failed open call, it's safe to just ignore the close error */
953
954 return retval;
955
956}
957
Paul Lawrence13486032014-02-03 13:28:11 -0800958static int pbkdf2(const char *passwd, unsigned char *salt,
Paul Lawrencef4faa572014-01-29 13:31:03 -0800959 unsigned char *ikey, void *params UNUSED)
960{
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800961 /* Turn the password into a key and IV that can decrypt the master key */
Paul Lawrencef4faa572014-01-29 13:31:03 -0800962 unsigned int keysize;
963 char* master_key = (char*)convert_hex_ascii_to_key(passwd, &keysize);
964 if (!master_key) return -1;
965 PKCS5_PBKDF2_HMAC_SHA1(master_key, keysize, salt, SALT_LEN,
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800966 HASH_COUNT, KEY_LEN_BYTES+IV_LEN_BYTES, ikey);
Paul Lawrencef4faa572014-01-29 13:31:03 -0800967
968 free (master_key);
969 return 0;
Ken Sumrall8ddbe402011-01-17 15:26:29 -0800970}
971
Paul Lawrence13486032014-02-03 13:28:11 -0800972static int scrypt(const char *passwd, unsigned char *salt,
Paul Lawrencef4faa572014-01-29 13:31:03 -0800973 unsigned char *ikey, void *params)
974{
Kenny Rootc4c70f12013-06-14 12:11:38 -0700975 struct crypt_mnt_ftr *ftr = (struct crypt_mnt_ftr *) params;
976
977 int N = 1 << ftr->N_factor;
978 int r = 1 << ftr->r_factor;
979 int p = 1 << ftr->p_factor;
980
981 /* Turn the password into a key and IV that can decrypt the master key */
Paul Lawrencef4faa572014-01-29 13:31:03 -0800982 unsigned int keysize;
983 unsigned char* master_key = convert_hex_ascii_to_key(passwd, &keysize);
984 if (!master_key) return -1;
985 crypto_scrypt(master_key, keysize, salt, SALT_LEN, N, r, p, ikey,
Kenny Rootc4c70f12013-06-14 12:11:38 -0700986 KEY_LEN_BYTES + IV_LEN_BYTES);
Paul Lawrencef4faa572014-01-29 13:31:03 -0800987
988 free (master_key);
989 return 0;
Kenny Rootc4c70f12013-06-14 12:11:38 -0700990}
991
Paul Lawrence13486032014-02-03 13:28:11 -0800992static int encrypt_master_key(const char *passwd, unsigned char *salt,
Ken Sumralle8744072011-01-18 22:01:55 -0800993 unsigned char *decrypted_master_key,
Kenny Rootc4c70f12013-06-14 12:11:38 -0700994 unsigned char *encrypted_master_key,
995 struct crypt_mnt_ftr *crypt_ftr)
Ken Sumrall8ddbe402011-01-17 15:26:29 -0800996{
997 unsigned char ikey[32+32] = { 0 }; /* Big enough to hold a 256 bit key and 256 bit IV */
998 EVP_CIPHER_CTX e_ctx;
999 int encrypted_len, final_len;
1000
1001 /* Turn the password into a key and IV that can decrypt the master key */
Kenny Rootc4c70f12013-06-14 12:11:38 -07001002 get_device_scrypt_params(crypt_ftr);
Paul Lawrencef4faa572014-01-29 13:31:03 -08001003 if (scrypt(passwd, salt, ikey, crypt_ftr)) {
1004 SLOGE("scrypt failed");
1005 return -1;
1006 }
Kenny Rootc4c70f12013-06-14 12:11:38 -07001007
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001008 /* Initialize the decryption engine */
1009 if (! EVP_EncryptInit(&e_ctx, EVP_aes_128_cbc(), ikey, ikey+KEY_LEN_BYTES)) {
1010 SLOGE("EVP_EncryptInit failed\n");
1011 return -1;
1012 }
1013 EVP_CIPHER_CTX_set_padding(&e_ctx, 0); /* Turn off padding as our data is block aligned */
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001014
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001015 /* Encrypt the master key */
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001016 if (! EVP_EncryptUpdate(&e_ctx, encrypted_master_key, &encrypted_len,
1017 decrypted_master_key, KEY_LEN_BYTES)) {
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001018 SLOGE("EVP_EncryptUpdate failed\n");
1019 return -1;
1020 }
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001021 if (! EVP_EncryptFinal(&e_ctx, encrypted_master_key + encrypted_len, &final_len)) {
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001022 SLOGE("EVP_EncryptFinal failed\n");
1023 return -1;
1024 }
1025
1026 if (encrypted_len + final_len != KEY_LEN_BYTES) {
1027 SLOGE("EVP_Encryption length check failed with %d, %d bytes\n", encrypted_len, final_len);
1028 return -1;
1029 } else {
1030 return 0;
1031 }
1032}
1033
JP Abgrall7bdfa522013-11-15 13:42:56 -08001034static int decrypt_master_key_aux(char *passwd, unsigned char *salt,
Ken Sumralle8744072011-01-18 22:01:55 -08001035 unsigned char *encrypted_master_key,
Kenny Rootc4c70f12013-06-14 12:11:38 -07001036 unsigned char *decrypted_master_key,
1037 kdf_func kdf, void *kdf_params)
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001038{
1039 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 -08001040 EVP_CIPHER_CTX d_ctx;
1041 int decrypted_len, final_len;
1042
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001043 /* Turn the password into a key and IV that can decrypt the master key */
Paul Lawrencef4faa572014-01-29 13:31:03 -08001044 if (kdf(passwd, salt, ikey, kdf_params)) {
1045 SLOGE("kdf failed");
1046 return -1;
1047 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001048
1049 /* Initialize the decryption engine */
1050 if (! EVP_DecryptInit(&d_ctx, EVP_aes_128_cbc(), ikey, ikey+KEY_LEN_BYTES)) {
1051 return -1;
1052 }
1053 EVP_CIPHER_CTX_set_padding(&d_ctx, 0); /* Turn off padding as our data is block aligned */
1054 /* Decrypt the master key */
1055 if (! EVP_DecryptUpdate(&d_ctx, decrypted_master_key, &decrypted_len,
1056 encrypted_master_key, KEY_LEN_BYTES)) {
1057 return -1;
1058 }
1059 if (! EVP_DecryptFinal(&d_ctx, decrypted_master_key + decrypted_len, &final_len)) {
1060 return -1;
1061 }
1062
1063 if (decrypted_len + final_len != KEY_LEN_BYTES) {
1064 return -1;
1065 } else {
1066 return 0;
1067 }
1068}
1069
Kenny Rootc4c70f12013-06-14 12:11:38 -07001070static void get_kdf_func(struct crypt_mnt_ftr *ftr, kdf_func *kdf, void** kdf_params)
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001071{
Kenny Rootc4c70f12013-06-14 12:11:38 -07001072 if (ftr->kdf_type == KDF_SCRYPT) {
1073 *kdf = scrypt;
1074 *kdf_params = ftr;
1075 } else {
1076 *kdf = pbkdf2;
1077 *kdf_params = NULL;
1078 }
1079}
1080
JP Abgrall7bdfa522013-11-15 13:42:56 -08001081static int decrypt_master_key(char *passwd, unsigned char *decrypted_master_key,
Kenny Rootc4c70f12013-06-14 12:11:38 -07001082 struct crypt_mnt_ftr *crypt_ftr)
1083{
1084 kdf_func kdf;
1085 void *kdf_params;
1086 int ret;
1087
1088 get_kdf_func(crypt_ftr, &kdf, &kdf_params);
JP Abgrall7bdfa522013-11-15 13:42:56 -08001089 ret = decrypt_master_key_aux(passwd, crypt_ftr->salt, crypt_ftr->master_key, decrypted_master_key, kdf,
Kenny Rootc4c70f12013-06-14 12:11:38 -07001090 kdf_params);
1091 if (ret != 0) {
1092 SLOGW("failure decrypting master key");
Kenny Rootc4c70f12013-06-14 12:11:38 -07001093 }
1094
1095 return ret;
1096}
1097
1098static int create_encrypted_random_key(char *passwd, unsigned char *master_key, unsigned char *salt,
1099 struct crypt_mnt_ftr *crypt_ftr) {
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001100 int fd;
Ken Sumralle8744072011-01-18 22:01:55 -08001101 unsigned char key_buf[KEY_LEN_BYTES];
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001102 EVP_CIPHER_CTX e_ctx;
1103 int encrypted_len, final_len;
1104
1105 /* Get some random bits for a key */
1106 fd = open("/dev/urandom", O_RDONLY);
Ken Sumralle8744072011-01-18 22:01:55 -08001107 read(fd, key_buf, sizeof(key_buf));
1108 read(fd, salt, SALT_LEN);
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001109 close(fd);
1110
1111 /* Now encrypt it with the password */
Kenny Rootc4c70f12013-06-14 12:11:38 -07001112 return encrypt_master_key(passwd, salt, key_buf, master_key, crypt_ftr);
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001113}
1114
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001115static int wait_and_unmount(char *mountpoint)
1116{
1117 int i, rc;
Ken Sumrall2eaf7132011-01-14 12:45:48 -08001118#define WAIT_UNMOUNT_COUNT 20
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001119
1120 /* Now umount the tmpfs filesystem */
1121 for (i=0; i<WAIT_UNMOUNT_COUNT; i++) {
1122 if (umount(mountpoint)) {
Ken Sumrall29d8da82011-05-18 17:20:07 -07001123 if (errno == EINVAL) {
1124 /* EINVAL is returned if the directory is not a mountpoint,
1125 * i.e. there is no filesystem mounted there. So just get out.
1126 */
1127 break;
1128 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001129 sleep(1);
1130 i++;
1131 } else {
1132 break;
1133 }
1134 }
1135
1136 if (i < WAIT_UNMOUNT_COUNT) {
1137 SLOGD("unmounting %s succeeded\n", mountpoint);
1138 rc = 0;
1139 } else {
1140 SLOGE("unmounting %s failed\n", mountpoint);
1141 rc = -1;
1142 }
1143
1144 return rc;
1145}
1146
Ken Sumrallc5872692013-05-14 15:26:31 -07001147#define DATA_PREP_TIMEOUT 200
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001148static int prep_data_fs(void)
1149{
1150 int i;
1151
1152 /* Do the prep of the /data filesystem */
1153 property_set("vold.post_fs_data_done", "0");
1154 property_set("vold.decrypt", "trigger_post_fs_data");
1155 SLOGD("Just triggered post_fs_data\n");
1156
Ken Sumrallc5872692013-05-14 15:26:31 -07001157 /* Wait a max of 50 seconds, hopefully it takes much less */
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001158 for (i=0; i<DATA_PREP_TIMEOUT; i++) {
Ken Sumrall29d8da82011-05-18 17:20:07 -07001159 char p[PROPERTY_VALUE_MAX];
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001160
1161 property_get("vold.post_fs_data_done", p, "0");
1162 if (*p == '1') {
1163 break;
1164 } else {
1165 usleep(250000);
1166 }
1167 }
1168 if (i == DATA_PREP_TIMEOUT) {
1169 /* Ugh, we failed to prep /data in time. Bail. */
Ken Sumrallc5872692013-05-14 15:26:31 -07001170 SLOGE("post_fs_data timed out!\n");
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001171 return -1;
1172 } else {
1173 SLOGD("post_fs_data done\n");
1174 return 0;
1175 }
1176}
1177
Paul Lawrencef4faa572014-01-29 13:31:03 -08001178static int cryptfs_restart_internal(int restart_main)
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001179{
1180 char fs_type[32];
1181 char real_blkdev[MAXPATHLEN];
Ken Sumrall6864b7e2011-01-14 15:20:02 -08001182 char crypto_blkdev[MAXPATHLEN];
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001183 char fs_options[256];
1184 unsigned long mnt_flags;
1185 struct stat statbuf;
1186 int rc = -1, i;
Ken Sumrall0cc16632011-01-18 20:32:26 -08001187 static int restart_successful = 0;
1188
1189 /* Validate that it's OK to call this routine */
Jason parks70a4b3f2011-01-28 10:10:47 -06001190 if (! master_key_saved) {
Ken Sumrall0cc16632011-01-18 20:32:26 -08001191 SLOGE("Encrypted filesystem not validated, aborting");
1192 return -1;
1193 }
1194
1195 if (restart_successful) {
1196 SLOGE("System already restarted with encrypted disk, aborting");
1197 return -1;
1198 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001199
Paul Lawrencef4faa572014-01-29 13:31:03 -08001200 if (restart_main) {
1201 /* Here is where we shut down the framework. The init scripts
1202 * start all services in one of three classes: core, main or late_start.
1203 * On boot, we start core and main. Now, we stop main, but not core,
1204 * as core includes vold and a few other really important things that
1205 * we need to keep running. Once main has stopped, we should be able
1206 * to umount the tmpfs /data, then mount the encrypted /data.
1207 * We then restart the class main, and also the class late_start.
1208 * At the moment, I've only put a few things in late_start that I know
1209 * are not needed to bring up the framework, and that also cause problems
1210 * with unmounting the tmpfs /data, but I hope to add add more services
1211 * to the late_start class as we optimize this to decrease the delay
1212 * till the user is asked for the password to the filesystem.
1213 */
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001214
Paul Lawrencef4faa572014-01-29 13:31:03 -08001215 /* The init files are setup to stop the class main when vold.decrypt is
1216 * set to trigger_reset_main.
1217 */
1218 property_set("vold.decrypt", "trigger_reset_main");
1219 SLOGD("Just asked init to shut down class main\n");
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001220
Paul Lawrencef4faa572014-01-29 13:31:03 -08001221 /* Ugh, shutting down the framework is not synchronous, so until it
1222 * can be fixed, this horrible hack will wait a moment for it all to
1223 * shut down before proceeding. Without it, some devices cannot
1224 * restart the graphics services.
1225 */
1226 sleep(2);
1227 }
Ken Sumrall9dedfd42012-10-09 14:16:59 -07001228
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001229 /* Now that the framework is shutdown, we should be able to umount()
1230 * the tmpfs filesystem, and mount the real one.
1231 */
1232
Ken Sumrall6864b7e2011-01-14 15:20:02 -08001233 property_get("ro.crypto.fs_crypto_blkdev", crypto_blkdev, "");
1234 if (strlen(crypto_blkdev) == 0) {
1235 SLOGE("fs_crypto_blkdev not set\n");
1236 return -1;
1237 }
1238
Ken Sumralle5032c42012-04-01 23:58:44 -07001239 if (! (rc = wait_and_unmount(DATA_MNT_POINT)) ) {
Doug Zongker6fd57712013-12-17 09:43:23 -08001240 /* If ro.crypto.readonly is set to 1, mount the decrypted
1241 * filesystem readonly. This is used when /data is mounted by
1242 * recovery mode.
1243 */
1244 char ro_prop[PROPERTY_VALUE_MAX];
1245 property_get("ro.crypto.readonly", ro_prop, "");
1246 if (strlen(ro_prop) > 0 && atoi(ro_prop)) {
1247 struct fstab_rec* rec = fs_mgr_get_entry_for_mount_point(fstab, DATA_MNT_POINT);
1248 rec->flags |= MS_RDONLY;
1249 }
1250
Ken Sumralle5032c42012-04-01 23:58:44 -07001251 /* If that succeeded, then mount the decrypted filesystem */
Ken Sumrall56ad03c2013-02-13 13:00:19 -08001252 fs_mgr_do_mount(fstab, DATA_MNT_POINT, crypto_blkdev, 0);
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001253
Ken Sumralle5032c42012-04-01 23:58:44 -07001254 property_set("vold.decrypt", "trigger_load_persist_props");
1255 /* Create necessary paths on /data */
1256 if (prep_data_fs()) {
1257 return -1;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001258 }
Ken Sumralle5032c42012-04-01 23:58:44 -07001259
1260 /* startup service classes main and late_start */
1261 property_set("vold.decrypt", "trigger_restart_framework");
1262 SLOGD("Just triggered restart_framework\n");
1263
1264 /* Give it a few moments to get started */
1265 sleep(1);
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001266 }
1267
Ken Sumrall0cc16632011-01-18 20:32:26 -08001268 if (rc == 0) {
1269 restart_successful = 1;
1270 }
1271
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001272 return rc;
1273}
1274
Paul Lawrencef4faa572014-01-29 13:31:03 -08001275int cryptfs_restart(void)
1276{
1277 /* Call internal implementation forcing a restart of main service group */
1278 return cryptfs_restart_internal(1);
1279}
1280
Mark Salyzyn3e971272014-01-21 13:27:04 -08001281static int do_crypto_complete(char *mount_point UNUSED)
Ken Sumrall7f7dbaa2011-02-01 15:46:41 -08001282{
1283 struct crypt_mnt_ftr crypt_ftr;
Ken Sumrall29d8da82011-05-18 17:20:07 -07001284 char encrypted_state[PROPERTY_VALUE_MAX];
Ken Sumralle1a45852011-12-14 21:24:27 -08001285 char key_loc[PROPERTY_VALUE_MAX];
Ken Sumrall7f7dbaa2011-02-01 15:46:41 -08001286
1287 property_get("ro.crypto.state", encrypted_state, "");
1288 if (strcmp(encrypted_state, "encrypted") ) {
1289 SLOGE("not running with encryption, aborting");
1290 return 1;
1291 }
1292
Ken Sumrall160b4d62013-04-22 12:15:39 -07001293 if (get_crypt_ftr_and_key(&crypt_ftr)) {
Ken Sumrall56ad03c2013-02-13 13:00:19 -08001294 fs_mgr_get_crypt_info(fstab, key_loc, 0, sizeof(key_loc));
Ken Sumralle5032c42012-04-01 23:58:44 -07001295
Ken Sumralle1a45852011-12-14 21:24:27 -08001296 /*
1297 * Only report this error if key_loc is a file and it exists.
1298 * If the device was never encrypted, and /data is not mountable for
1299 * some reason, returning 1 should prevent the UI from presenting the
1300 * a "enter password" screen, or worse, a "press button to wipe the
1301 * device" screen.
1302 */
1303 if ((key_loc[0] == '/') && (access("key_loc", F_OK) == -1)) {
1304 SLOGE("master key file does not exist, aborting");
1305 return 1;
1306 } else {
1307 SLOGE("Error getting crypt footer and key\n");
1308 return -1;
1309 }
Ken Sumrall7f7dbaa2011-02-01 15:46:41 -08001310 }
1311
1312 if (crypt_ftr.flags & CRYPT_ENCRYPTION_IN_PROGRESS) {
1313 SLOGE("Encryption process didn't finish successfully\n");
1314 return -2; /* -2 is the clue to the UI that there is no usable data on the disk,
1315 * and give the user an option to wipe the disk */
1316 }
1317
1318 /* We passed the test! We shall diminish, and return to the west */
1319 return 0;
1320}
1321
Paul Lawrencef4faa572014-01-29 13:31:03 -08001322static int test_mount_encrypted_fs(struct crypt_mnt_ftr* crypt_ftr,
1323 char *passwd, char *mount_point, char *label)
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001324{
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001325 /* Allocate enough space for a 256 bit key, but we may use less */
Ken Sumrall160b4d62013-04-22 12:15:39 -07001326 unsigned char decrypted_master_key[32];
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001327 char crypto_blkdev[MAXPATHLEN];
1328 char real_blkdev[MAXPATHLEN];
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001329 char tmp_mount_point[64];
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001330 unsigned int orig_failed_decrypt_count;
1331 int rc;
Kenny Rootc4c70f12013-06-14 12:11:38 -07001332 kdf_func kdf;
1333 void *kdf_params;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001334
Paul Lawrencef4faa572014-01-29 13:31:03 -08001335 SLOGD("crypt_ftr->fs_size = %lld\n", crypt_ftr->fs_size);
1336 orig_failed_decrypt_count = crypt_ftr->failed_decrypt_count;
Ken Sumrall0cc16632011-01-18 20:32:26 -08001337
Paul Lawrencef4faa572014-01-29 13:31:03 -08001338 if (! (crypt_ftr->flags & CRYPT_MNT_KEY_UNENCRYPTED) ) {
1339 if (decrypt_master_key(passwd, decrypted_master_key, crypt_ftr)) {
JP Abgrall7bdfa522013-11-15 13:42:56 -08001340 SLOGE("Failed to decrypt master key\n");
1341 return -1;
1342 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001343 }
1344
Paul Lawrencef4faa572014-01-29 13:31:03 -08001345 fs_mgr_get_crypt_info(fstab, 0, real_blkdev, sizeof(real_blkdev));
1346
1347 if (create_crypto_blk_dev(crypt_ftr, decrypted_master_key,
1348 real_blkdev, crypto_blkdev, label)) {
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001349 SLOGE("Error creating decrypted block device\n");
1350 return -1;
1351 }
1352
Alex Klyubin707795a2013-05-10 15:17:07 -07001353 /* If init detects an encrypted filesystem, it writes a file for each such
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001354 * encrypted fs into the tmpfs /data filesystem, and then the framework finds those
1355 * files and passes that data to me */
1356 /* Create a tmp mount point to try mounting the decryptd fs
1357 * Since we're here, the mount_point should be a tmpfs filesystem, so make
1358 * a directory in it to test mount the decrypted filesystem.
1359 */
1360 sprintf(tmp_mount_point, "%s/tmp_mnt", mount_point);
1361 mkdir(tmp_mount_point, 0755);
Ken Sumrall56ad03c2013-02-13 13:00:19 -08001362 if (fs_mgr_do_mount(fstab, DATA_MNT_POINT, crypto_blkdev, tmp_mount_point)) {
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001363 SLOGE("Error temp mounting decrypted block device\n");
Ken Sumrall29d8da82011-05-18 17:20:07 -07001364 delete_crypto_blk_dev(label);
Paul Lawrencef4faa572014-01-29 13:31:03 -08001365 crypt_ftr->failed_decrypt_count++;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001366 } else {
1367 /* Success, so just umount and we'll mount it properly when we restart
1368 * the framework.
1369 */
1370 umount(tmp_mount_point);
Paul Lawrencef4faa572014-01-29 13:31:03 -08001371 crypt_ftr->failed_decrypt_count = 0;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001372 }
1373
Paul Lawrencef4faa572014-01-29 13:31:03 -08001374 if (orig_failed_decrypt_count != crypt_ftr->failed_decrypt_count) {
1375 put_crypt_ftr_and_key(crypt_ftr);
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001376 }
1377
Paul Lawrencef4faa572014-01-29 13:31:03 -08001378 if (crypt_ftr->failed_decrypt_count) {
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001379 /* We failed to mount the device, so return an error */
Paul Lawrencef4faa572014-01-29 13:31:03 -08001380 rc = crypt_ftr->failed_decrypt_count;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001381
1382 } else {
Ken Sumrall6864b7e2011-01-14 15:20:02 -08001383 /* Woot! Success! Save the name of the crypto block device
1384 * so we can mount it when restarting the framework.
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001385 */
Ken Sumrall6864b7e2011-01-14 15:20:02 -08001386 property_set("ro.crypto.fs_crypto_blkdev", crypto_blkdev);
Jason parks70a4b3f2011-01-28 10:10:47 -06001387
1388 /* Also save a the master key so we can reencrypted the key
1389 * the key when we want to change the password on it.
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001390 */
Jason parks70a4b3f2011-01-28 10:10:47 -06001391 memcpy(saved_master_key, decrypted_master_key, KEY_LEN_BYTES);
Ken Sumrall3ad90722011-10-04 20:38:29 -07001392 saved_mount_point = strdup(mount_point);
Jason parks70a4b3f2011-01-28 10:10:47 -06001393 master_key_saved = 1;
JP Abgrall7bdfa522013-11-15 13:42:56 -08001394 SLOGD("%s(): Master key saved\n", __FUNCTION__);
Ken Sumrall6864b7e2011-01-14 15:20:02 -08001395 rc = 0;
JP Abgrall7bdfa522013-11-15 13:42:56 -08001396 /*
1397 * Upgrade if we're not using the latest KDF.
1398 */
Paul Lawrencef4faa572014-01-29 13:31:03 -08001399 if (crypt_ftr->kdf_type != KDF_SCRYPT) {
1400 crypt_ftr->kdf_type = KDF_SCRYPT;
1401 rc = encrypt_master_key(passwd, crypt_ftr->salt, saved_master_key,
1402 crypt_ftr->master_key, crypt_ftr);
JP Abgrall7bdfa522013-11-15 13:42:56 -08001403 if (!rc) {
Paul Lawrencef4faa572014-01-29 13:31:03 -08001404 rc = put_crypt_ftr_and_key(crypt_ftr);
JP Abgrall7bdfa522013-11-15 13:42:56 -08001405 }
1406 SLOGD("Key Derivation Function upgrade: rc=%d\n", rc);
1407 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001408 }
1409
1410 return rc;
1411}
1412
Ken Sumrall0b8b5972011-08-31 16:14:23 -07001413/* Called by vold when it wants to undo the crypto mapping of a volume it
1414 * manages. This is usually in response to a factory reset, when we want
1415 * to undo the crypto mapping so the volume is formatted in the clear.
1416 */
1417int cryptfs_revert_volume(const char *label)
1418{
1419 return delete_crypto_blk_dev((char *)label);
1420}
1421
Ken Sumrall29d8da82011-05-18 17:20:07 -07001422/*
1423 * Called by vold when it's asked to mount an encrypted, nonremovable volume.
1424 * Setup a dm-crypt mapping, use the saved master key from
1425 * setting up the /data mapping, and return the new device path.
1426 */
1427int cryptfs_setup_volume(const char *label, int major, int minor,
1428 char *crypto_sys_path, unsigned int max_path,
1429 int *new_major, int *new_minor)
1430{
1431 char real_blkdev[MAXPATHLEN], crypto_blkdev[MAXPATHLEN];
1432 struct crypt_mnt_ftr sd_crypt_ftr;
Ken Sumrall29d8da82011-05-18 17:20:07 -07001433 struct stat statbuf;
1434 int nr_sec, fd;
1435
1436 sprintf(real_blkdev, "/dev/block/vold/%d:%d", major, minor);
1437
Ken Sumrall160b4d62013-04-22 12:15:39 -07001438 get_crypt_ftr_and_key(&sd_crypt_ftr);
Ken Sumrall29d8da82011-05-18 17:20:07 -07001439
1440 /* Update the fs_size field to be the size of the volume */
1441 fd = open(real_blkdev, O_RDONLY);
1442 nr_sec = get_blkdev_size(fd);
1443 close(fd);
1444 if (nr_sec == 0) {
1445 SLOGE("Cannot get size of volume %s\n", real_blkdev);
1446 return -1;
1447 }
1448
1449 sd_crypt_ftr.fs_size = nr_sec;
1450 create_crypto_blk_dev(&sd_crypt_ftr, saved_master_key, real_blkdev,
1451 crypto_blkdev, label);
1452
1453 stat(crypto_blkdev, &statbuf);
1454 *new_major = MAJOR(statbuf.st_rdev);
1455 *new_minor = MINOR(statbuf.st_rdev);
1456
1457 /* Create path to sys entry for this block device */
1458 snprintf(crypto_sys_path, max_path, "/devices/virtual/block/%s", strrchr(crypto_blkdev, '/')+1);
1459
1460 return 0;
1461}
1462
Ken Sumrall7f7dbaa2011-02-01 15:46:41 -08001463int cryptfs_crypto_complete(void)
1464{
1465 return do_crypto_complete("/data");
1466}
1467
Paul Lawrencef4faa572014-01-29 13:31:03 -08001468int check_unmounted_and_get_ftr(struct crypt_mnt_ftr* crypt_ftr)
1469{
1470 char encrypted_state[PROPERTY_VALUE_MAX];
1471 property_get("ro.crypto.state", encrypted_state, "");
1472 if ( master_key_saved || strcmp(encrypted_state, "encrypted") ) {
1473 SLOGE("encrypted fs already validated or not running with encryption,"
1474 " aborting");
1475 return -1;
1476 }
1477
1478 if (get_crypt_ftr_and_key(crypt_ftr)) {
1479 SLOGE("Error getting crypt footer and key");
1480 return -1;
1481 }
1482
1483 return 0;
1484}
1485
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001486int cryptfs_check_passwd(char *passwd)
1487{
Paul Lawrencef4faa572014-01-29 13:31:03 -08001488 struct crypt_mnt_ftr crypt_ftr;
1489 int rc;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001490
Paul Lawrencef4faa572014-01-29 13:31:03 -08001491 rc = check_unmounted_and_get_ftr(&crypt_ftr);
1492 if (rc)
1493 return rc;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001494
Paul Lawrencef4faa572014-01-29 13:31:03 -08001495 rc = test_mount_encrypted_fs(&crypt_ftr, passwd,
1496 DATA_MNT_POINT, "userdata");
Paul Lawrence684dbdf2014-02-07 12:07:22 -08001497
1498 if (rc == 0 && crypt_ftr.crypt_type != CRYPT_TYPE_DEFAULT) {
Paul Lawrence399317e2014-03-10 13:20:50 -07001499 cryptfs_clear_password();
1500 password = strdup(passwd);
1501 struct timespec now;
1502 clock_gettime(CLOCK_BOOTTIME, &now);
1503 password_expiry_time = now.tv_sec + password_max_age_seconds;
Paul Lawrence684dbdf2014-02-07 12:07:22 -08001504 }
1505
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001506 return rc;
1507}
1508
Ken Sumrall3ad90722011-10-04 20:38:29 -07001509int cryptfs_verify_passwd(char *passwd)
1510{
1511 struct crypt_mnt_ftr crypt_ftr;
1512 /* Allocate enough space for a 256 bit key, but we may use less */
Ken Sumrall160b4d62013-04-22 12:15:39 -07001513 unsigned char decrypted_master_key[32];
Ken Sumrall3ad90722011-10-04 20:38:29 -07001514 char encrypted_state[PROPERTY_VALUE_MAX];
1515 int rc;
1516
1517 property_get("ro.crypto.state", encrypted_state, "");
1518 if (strcmp(encrypted_state, "encrypted") ) {
1519 SLOGE("device not encrypted, aborting");
1520 return -2;
1521 }
1522
1523 if (!master_key_saved) {
1524 SLOGE("encrypted fs not yet mounted, aborting");
1525 return -1;
1526 }
1527
1528 if (!saved_mount_point) {
1529 SLOGE("encrypted fs failed to save mount point, aborting");
1530 return -1;
1531 }
1532
Ken Sumrall160b4d62013-04-22 12:15:39 -07001533 if (get_crypt_ftr_and_key(&crypt_ftr)) {
Ken Sumrall3ad90722011-10-04 20:38:29 -07001534 SLOGE("Error getting crypt footer and key\n");
1535 return -1;
1536 }
1537
1538 if (crypt_ftr.flags & CRYPT_MNT_KEY_UNENCRYPTED) {
1539 /* If the device has no password, then just say the password is valid */
1540 rc = 0;
1541 } else {
JP Abgrall7bdfa522013-11-15 13:42:56 -08001542 decrypt_master_key(passwd, decrypted_master_key, &crypt_ftr);
Ken Sumrall3ad90722011-10-04 20:38:29 -07001543 if (!memcmp(decrypted_master_key, saved_master_key, crypt_ftr.keysize)) {
1544 /* They match, the password is correct */
1545 rc = 0;
1546 } else {
1547 /* If incorrect, sleep for a bit to prevent dictionary attacks */
1548 sleep(1);
1549 rc = 1;
1550 }
1551 }
1552
1553 return rc;
1554}
1555
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001556/* Initialize a crypt_mnt_ftr structure. The keysize is
1557 * defaulted to 16 bytes, and the filesystem size to 0.
1558 * Presumably, at a minimum, the caller will update the
1559 * filesystem size and crypto_type_name after calling this function.
1560 */
1561static void cryptfs_init_crypt_mnt_ftr(struct crypt_mnt_ftr *ftr)
1562{
Ken Sumrall160b4d62013-04-22 12:15:39 -07001563 off64_t off;
1564
1565 memset(ftr, 0, sizeof(struct crypt_mnt_ftr));
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001566 ftr->magic = CRYPT_MNT_MAGIC;
Kenny Rootc96a5f82013-06-14 12:08:28 -07001567 ftr->major_version = CURRENT_MAJOR_VERSION;
1568 ftr->minor_version = CURRENT_MINOR_VERSION;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001569 ftr->ftr_size = sizeof(struct crypt_mnt_ftr);
Jason parks70a4b3f2011-01-28 10:10:47 -06001570 ftr->keysize = KEY_LEN_BYTES;
Ken Sumrall160b4d62013-04-22 12:15:39 -07001571
Kenny Rootc4c70f12013-06-14 12:11:38 -07001572 ftr->kdf_type = KDF_SCRYPT;
1573 get_device_scrypt_params(ftr);
1574
Ken Sumrall160b4d62013-04-22 12:15:39 -07001575 ftr->persist_data_size = CRYPT_PERSIST_DATA_SIZE;
1576 if (get_crypt_ftr_info(NULL, &off) == 0) {
1577 ftr->persist_data_offset[0] = off + CRYPT_FOOTER_TO_PERSIST_OFFSET;
1578 ftr->persist_data_offset[1] = off + CRYPT_FOOTER_TO_PERSIST_OFFSET +
1579 ftr->persist_data_size;
1580 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001581}
1582
Ken Sumrall29d8da82011-05-18 17:20:07 -07001583static int cryptfs_enable_wipe(char *crypto_blkdev, off64_t size, int type)
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001584{
Ken Sumralle550f782013-08-20 13:48:23 -07001585 const char *args[10];
1586 char size_str[32]; /* Must be large enough to hold a %lld and null byte */
1587 int num_args;
1588 int status;
1589 int tmp;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001590 int rc = -1;
1591
Ken Sumrall29d8da82011-05-18 17:20:07 -07001592 if (type == EXT4_FS) {
Ken Sumralle550f782013-08-20 13:48:23 -07001593 args[0] = "/system/bin/make_ext4fs";
1594 args[1] = "-a";
1595 args[2] = "/data";
1596 args[3] = "-l";
1597 snprintf(size_str, sizeof(size_str), "%lld", size * 512);
1598 args[4] = size_str;
1599 args[5] = crypto_blkdev;
1600 num_args = 6;
1601 SLOGI("Making empty filesystem with command %s %s %s %s %s %s\n",
1602 args[0], args[1], args[2], args[3], args[4], args[5]);
Ken Sumrall29d8da82011-05-18 17:20:07 -07001603 } else if (type== FAT_FS) {
Ken Sumralle550f782013-08-20 13:48:23 -07001604 args[0] = "/system/bin/newfs_msdos";
1605 args[1] = "-F";
1606 args[2] = "32";
1607 args[3] = "-O";
1608 args[4] = "android";
1609 args[5] = "-c";
1610 args[6] = "8";
1611 args[7] = "-s";
1612 snprintf(size_str, sizeof(size_str), "%lld", size);
1613 args[8] = size_str;
1614 args[9] = crypto_blkdev;
1615 num_args = 10;
1616 SLOGI("Making empty filesystem with command %s %s %s %s %s %s %s %s %s %s\n",
1617 args[0], args[1], args[2], args[3], args[4], args[5],
1618 args[6], args[7], args[8], args[9]);
Ken Sumrall29d8da82011-05-18 17:20:07 -07001619 } else {
1620 SLOGE("cryptfs_enable_wipe(): unknown filesystem type %d\n", type);
1621 return -1;
1622 }
1623
Ken Sumralle550f782013-08-20 13:48:23 -07001624 tmp = android_fork_execvp(num_args, (char **)args, &status, false, true);
1625
1626 if (tmp != 0) {
1627 SLOGE("Error creating empty filesystem on %s due to logwrap error\n", crypto_blkdev);
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001628 } else {
Ken Sumralle550f782013-08-20 13:48:23 -07001629 if (WIFEXITED(status)) {
1630 if (WEXITSTATUS(status)) {
1631 SLOGE("Error creating filesystem on %s, exit status %d ",
1632 crypto_blkdev, WEXITSTATUS(status));
1633 } else {
1634 SLOGD("Successfully created filesystem on %s\n", crypto_blkdev);
1635 rc = 0;
1636 }
1637 } else {
1638 SLOGE("Error creating filesystem on %s, did not exit normally\n", crypto_blkdev);
1639 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001640 }
1641
1642 return rc;
1643}
1644
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001645#define CRYPT_INPLACE_BUFSIZE 4096
Paul Lawrence87999172014-02-20 12:21:31 -08001646#define CRYPT_SECTORS_PER_BUFSIZE (CRYPT_INPLACE_BUFSIZE / CRYPT_SECTOR_SIZE)
1647#define CRYPT_SECTOR_SIZE 512
Paul Lawrenceae59fe62014-01-21 08:23:27 -08001648
1649/* aligned 32K writes tends to make flash happy.
1650 * SD card association recommends it.
1651 */
1652#define BLOCKS_AT_A_TIME 8
1653
1654struct encryptGroupsData
1655{
1656 int realfd;
1657 int cryptofd;
1658 off64_t numblocks;
1659 off64_t one_pct, cur_pct, new_pct;
1660 off64_t blocks_already_done, tot_numblocks;
1661 char* real_blkdev, * crypto_blkdev;
1662 int count;
1663 off64_t offset;
1664 char* buffer;
Paul Lawrence87999172014-02-20 12:21:31 -08001665 off64_t last_written_sector;
1666 int completed;
Paul Lawrenceae59fe62014-01-21 08:23:27 -08001667};
1668
1669static void update_progress(struct encryptGroupsData* data)
1670{
1671 data->blocks_already_done++;
1672 data->new_pct = data->blocks_already_done / data->one_pct;
1673 if (data->new_pct > data->cur_pct) {
1674 char buf[8];
1675 data->cur_pct = data->new_pct;
1676 snprintf(buf, sizeof(buf), "%lld", data->cur_pct);
1677 property_set("vold.encrypt_progress", buf);
1678 }
1679}
1680
1681static int flush_outstanding_data(struct encryptGroupsData* data)
1682{
1683 if (data->count == 0) {
1684 return 0;
1685 }
1686
1687 SLOGV("Copying %d blocks at offset %llx", data->count, data->offset);
1688
1689 if (pread64(data->realfd, data->buffer,
1690 info.block_size * data->count, data->offset)
1691 <= 0) {
1692 SLOGE("Error reading real_blkdev %s for inplace encrypt",
1693 data->real_blkdev);
1694 return -1;
1695 }
1696
1697 if (pwrite64(data->cryptofd, data->buffer,
1698 info.block_size * data->count, data->offset)
1699 <= 0) {
1700 SLOGE("Error writing crypto_blkdev %s for inplace encrypt",
1701 data->crypto_blkdev);
1702 return -1;
Paul Lawrence87999172014-02-20 12:21:31 -08001703 } else {
1704 SLOGI("Encrypted %d blocks at sector %lld",
1705 data->count, data->offset / info.block_size * CRYPT_SECTOR_SIZE);
Paul Lawrenceae59fe62014-01-21 08:23:27 -08001706 }
1707
1708 data->count = 0;
Paul Lawrence87999172014-02-20 12:21:31 -08001709 data->last_written_sector = (data->offset + data->count)
1710 / info.block_size * CRYPT_SECTOR_SIZE - 1;
Paul Lawrenceae59fe62014-01-21 08:23:27 -08001711 return 0;
1712}
1713
1714static int encrypt_groups(struct encryptGroupsData* data)
1715{
1716 unsigned int i;
1717 u8 *block_bitmap = 0;
1718 unsigned int block;
1719 off64_t ret;
1720 int rc = -1;
1721
1722 data->buffer = malloc(info.block_size * BLOCKS_AT_A_TIME);
1723 if (!data->buffer) {
1724 SLOGE("Failed to allocate crypto buffer");
1725 goto errout;
1726 }
1727
1728 block_bitmap = malloc(info.block_size);
1729 if (!block_bitmap) {
1730 SLOGE("failed to allocate block bitmap");
1731 goto errout;
1732 }
1733
1734 for (i = 0; i < aux_info.groups; ++i) {
1735 SLOGI("Encrypting group %d", i);
1736
1737 u32 first_block = aux_info.first_data_block + i * info.blocks_per_group;
1738 u32 block_count = min(info.blocks_per_group,
1739 aux_info.len_blocks - first_block);
1740
1741 off64_t offset = (u64)info.block_size
1742 * aux_info.bg_desc[i].bg_block_bitmap;
1743
1744 ret = pread64(data->realfd, block_bitmap, info.block_size, offset);
1745 if (ret != (int)info.block_size) {
1746 SLOGE("failed to read all of block group bitmap %d", i);
1747 goto errout;
1748 }
1749
1750 offset = (u64)info.block_size * first_block;
1751
1752 data->count = 0;
1753
1754 for (block = 0; block < block_count; block++) {
1755 update_progress(data);
1756 if (bitmap_get_bit(block_bitmap, block)) {
1757 if (data->count == 0) {
1758 data->offset = offset;
1759 }
1760 data->count++;
1761 } else {
1762 if (flush_outstanding_data(data)) {
1763 goto errout;
1764 }
1765 }
1766
1767 offset += info.block_size;
1768
1769 /* Write data if we are aligned or buffer size reached */
1770 if (offset % (info.block_size * BLOCKS_AT_A_TIME) == 0
1771 || data->count == BLOCKS_AT_A_TIME) {
1772 if (flush_outstanding_data(data)) {
1773 goto errout;
1774 }
1775 }
Paul Lawrence87999172014-02-20 12:21:31 -08001776
1777 if (!is_battery_ok()) {
1778 SLOGE("Stopping encryption due to low battery");
1779 rc = 0;
1780 goto errout;
1781 }
1782
Paul Lawrenceae59fe62014-01-21 08:23:27 -08001783 }
1784 if (flush_outstanding_data(data)) {
1785 goto errout;
1786 }
1787 }
1788
Paul Lawrence87999172014-02-20 12:21:31 -08001789 data->completed = 1;
Paul Lawrenceae59fe62014-01-21 08:23:27 -08001790 rc = 0;
1791
1792errout:
1793 free(data->buffer);
1794 free(block_bitmap);
1795 return rc;
1796}
1797
1798static int cryptfs_enable_inplace_ext4(char *crypto_blkdev,
1799 char *real_blkdev,
1800 off64_t size,
1801 off64_t *size_already_done,
Paul Lawrence87999172014-02-20 12:21:31 -08001802 off64_t tot_size,
1803 off64_t previously_encrypted_upto)
Paul Lawrenceae59fe62014-01-21 08:23:27 -08001804{
1805 int i;
1806 struct encryptGroupsData data;
1807 int rc = -1;
1808
Paul Lawrence87999172014-02-20 12:21:31 -08001809 if (previously_encrypted_upto > *size_already_done) {
1810 SLOGD("Not fast encrypting since resuming part way through");
1811 return -1;
1812 }
1813
Paul Lawrenceae59fe62014-01-21 08:23:27 -08001814 memset(&data, 0, sizeof(data));
1815 data.real_blkdev = real_blkdev;
1816 data.crypto_blkdev = crypto_blkdev;
1817
1818 if ( (data.realfd = open(real_blkdev, O_RDWR)) < 0) {
1819 SLOGE("Error opening real_blkdev %s for inplace encrypt\n",
1820 real_blkdev);
1821 goto errout;
1822 }
1823
1824 if ( (data.cryptofd = open(crypto_blkdev, O_WRONLY)) < 0) {
1825 SLOGE("Error opening crypto_blkdev %s for inplace encrypt\n",
1826 crypto_blkdev);
1827 goto errout;
1828 }
1829
1830 if (setjmp(setjmp_env)) {
1831 SLOGE("Reading extent caused an exception");
1832 goto errout;
1833 }
1834
1835 if (read_ext(data.realfd, 0) != 0) {
1836 SLOGE("Failed to read extent");
1837 goto errout;
1838 }
1839
1840 data.numblocks = size / CRYPT_SECTORS_PER_BUFSIZE;
1841 data.tot_numblocks = tot_size / CRYPT_SECTORS_PER_BUFSIZE;
1842 data.blocks_already_done = *size_already_done / CRYPT_SECTORS_PER_BUFSIZE;
1843
1844 SLOGI("Encrypting filesystem in place...");
1845
1846 data.one_pct = data.tot_numblocks / 100;
1847 data.cur_pct = 0;
1848
1849 rc = encrypt_groups(&data);
1850 if (rc) {
1851 SLOGE("Error encrypting groups");
1852 goto errout;
1853 }
1854
Paul Lawrence87999172014-02-20 12:21:31 -08001855 *size_already_done += data.completed ? size : data.last_written_sector;
Paul Lawrenceae59fe62014-01-21 08:23:27 -08001856 rc = 0;
1857
1858errout:
1859 close(data.realfd);
1860 close(data.cryptofd);
1861
1862 return rc;
1863}
1864
1865static int cryptfs_enable_inplace_full(char *crypto_blkdev, char *real_blkdev,
1866 off64_t size, off64_t *size_already_done,
Paul Lawrence87999172014-02-20 12:21:31 -08001867 off64_t tot_size,
1868 off64_t previously_encrypted_upto)
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001869{
1870 int realfd, cryptofd;
1871 char *buf[CRYPT_INPLACE_BUFSIZE];
1872 int rc = -1;
1873 off64_t numblocks, i, remainder;
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001874 off64_t one_pct, cur_pct, new_pct;
Ken Sumrall29d8da82011-05-18 17:20:07 -07001875 off64_t blocks_already_done, tot_numblocks;
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001876
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001877 if ( (realfd = open(real_blkdev, O_RDONLY)) < 0) {
1878 SLOGE("Error opening real_blkdev %s for inplace encrypt\n", real_blkdev);
1879 return -1;
1880 }
1881
1882 if ( (cryptofd = open(crypto_blkdev, O_WRONLY)) < 0) {
1883 SLOGE("Error opening crypto_blkdev %s for inplace encrypt\n", crypto_blkdev);
1884 close(realfd);
1885 return -1;
1886 }
1887
1888 /* This is pretty much a simple loop of reading 4K, and writing 4K.
1889 * The size passed in is the number of 512 byte sectors in the filesystem.
1890 * So compute the number of whole 4K blocks we should read/write,
1891 * and the remainder.
1892 */
1893 numblocks = size / CRYPT_SECTORS_PER_BUFSIZE;
1894 remainder = size % CRYPT_SECTORS_PER_BUFSIZE;
Ken Sumrall29d8da82011-05-18 17:20:07 -07001895 tot_numblocks = tot_size / CRYPT_SECTORS_PER_BUFSIZE;
1896 blocks_already_done = *size_already_done / CRYPT_SECTORS_PER_BUFSIZE;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001897
1898 SLOGE("Encrypting filesystem in place...");
1899
Paul Lawrence87999172014-02-20 12:21:31 -08001900 i = previously_encrypted_upto + 1 - *size_already_done;
1901
1902 if (lseek64(realfd, i * CRYPT_SECTOR_SIZE, SEEK_SET) < 0) {
1903 SLOGE("Cannot seek to previously encrypted point on %s", real_blkdev);
1904 goto errout;
1905 }
1906
1907 if (lseek64(cryptofd, i * CRYPT_SECTOR_SIZE, SEEK_SET) < 0) {
1908 SLOGE("Cannot seek to previously encrypted point on %s", crypto_blkdev);
1909 goto errout;
1910 }
1911
1912 for (;i < size && i % CRYPT_SECTORS_PER_BUFSIZE != 0; ++i) {
1913 if (unix_read(realfd, buf, CRYPT_SECTOR_SIZE) <= 0) {
1914 SLOGE("Error reading initial sectors from real_blkdev %s for "
1915 "inplace encrypt\n", crypto_blkdev);
1916 goto errout;
1917 }
1918 if (unix_write(cryptofd, buf, CRYPT_SECTOR_SIZE) <= 0) {
1919 SLOGE("Error writing initial sectors to crypto_blkdev %s for "
1920 "inplace encrypt\n", crypto_blkdev);
1921 goto errout;
1922 } else {
1923 SLOGI("Encrypted 1 block at %lld", i);
1924 }
1925 }
1926
Ken Sumrall29d8da82011-05-18 17:20:07 -07001927 one_pct = tot_numblocks / 100;
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001928 cur_pct = 0;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001929 /* process the majority of the filesystem in blocks */
Paul Lawrence87999172014-02-20 12:21:31 -08001930 for (i/=CRYPT_SECTORS_PER_BUFSIZE; i<numblocks; i++) {
Ken Sumrall29d8da82011-05-18 17:20:07 -07001931 new_pct = (i + blocks_already_done) / one_pct;
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001932 if (new_pct > cur_pct) {
1933 char buf[8];
1934
1935 cur_pct = new_pct;
1936 snprintf(buf, sizeof(buf), "%lld", cur_pct);
1937 property_set("vold.encrypt_progress", buf);
1938 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001939 if (unix_read(realfd, buf, CRYPT_INPLACE_BUFSIZE) <= 0) {
Paul Lawrence87999172014-02-20 12:21:31 -08001940 SLOGE("Error reading real_blkdev %s for inplace encrypt", crypto_blkdev);
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001941 goto errout;
1942 }
1943 if (unix_write(cryptofd, buf, CRYPT_INPLACE_BUFSIZE) <= 0) {
Paul Lawrence87999172014-02-20 12:21:31 -08001944 SLOGE("Error writing crypto_blkdev %s for inplace encrypt", crypto_blkdev);
1945 goto errout;
1946 } else {
1947 SLOGD("Encrypted %d block at %lld",
1948 CRYPT_SECTORS_PER_BUFSIZE,
1949 i * CRYPT_SECTORS_PER_BUFSIZE);
1950 }
1951
1952 if (!is_battery_ok()) {
1953 SLOGE("Stopping encryption due to low battery");
1954 *size_already_done += (i + 1) * CRYPT_SECTORS_PER_BUFSIZE - 1;
1955 rc = 0;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001956 goto errout;
1957 }
1958 }
1959
1960 /* Do any remaining sectors */
1961 for (i=0; i<remainder; i++) {
Paul Lawrence87999172014-02-20 12:21:31 -08001962 if (unix_read(realfd, buf, CRYPT_SECTOR_SIZE) <= 0) {
1963 SLOGE("Error reading final sectors from real_blkdev %s for inplace encrypt", crypto_blkdev);
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001964 goto errout;
1965 }
Paul Lawrence87999172014-02-20 12:21:31 -08001966 if (unix_write(cryptofd, buf, CRYPT_SECTOR_SIZE) <= 0) {
1967 SLOGE("Error writing final sectors to crypto_blkdev %s for inplace encrypt", crypto_blkdev);
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001968 goto errout;
Paul Lawrence87999172014-02-20 12:21:31 -08001969 } else {
1970 SLOGI("Encrypted 1 block at next location");
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001971 }
1972 }
1973
Ken Sumrall29d8da82011-05-18 17:20:07 -07001974 *size_already_done += size;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001975 rc = 0;
1976
1977errout:
1978 close(realfd);
1979 close(cryptofd);
1980
1981 return rc;
1982}
1983
Paul Lawrenceae59fe62014-01-21 08:23:27 -08001984static int cryptfs_enable_inplace(char *crypto_blkdev, char *real_blkdev,
1985 off64_t size, off64_t *size_already_done,
Paul Lawrence87999172014-02-20 12:21:31 -08001986 off64_t tot_size,
1987 off64_t previously_encrypted_upto)
Paul Lawrenceae59fe62014-01-21 08:23:27 -08001988{
Paul Lawrence87999172014-02-20 12:21:31 -08001989 if (previously_encrypted_upto) {
1990 SLOGD("Continuing encryption from %lld", previously_encrypted_upto);
1991 }
1992
1993 if (*size_already_done + size < previously_encrypted_upto) {
1994 *size_already_done += size;
1995 return 0;
1996 }
1997
Paul Lawrenceae59fe62014-01-21 08:23:27 -08001998 if (cryptfs_enable_inplace_ext4(crypto_blkdev, real_blkdev,
Paul Lawrence87999172014-02-20 12:21:31 -08001999 size, size_already_done,
2000 tot_size, previously_encrypted_upto) == 0) {
Paul Lawrenceae59fe62014-01-21 08:23:27 -08002001 return 0;
2002 }
2003
2004 return cryptfs_enable_inplace_full(crypto_blkdev, real_blkdev,
Paul Lawrence87999172014-02-20 12:21:31 -08002005 size, size_already_done, tot_size,
2006 previously_encrypted_upto);
Paul Lawrenceae59fe62014-01-21 08:23:27 -08002007}
2008
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002009#define CRYPTO_ENABLE_WIPE 1
2010#define CRYPTO_ENABLE_INPLACE 2
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002011
2012#define FRAMEWORK_BOOT_WAIT 60
2013
Ken Sumrall29d8da82011-05-18 17:20:07 -07002014static inline int should_encrypt(struct volume_info *volume)
2015{
Paul Lawrenceae59fe62014-01-21 08:23:27 -08002016 return (volume->flags & (VOL_ENCRYPTABLE | VOL_NONREMOVABLE)) ==
Ken Sumrall29d8da82011-05-18 17:20:07 -07002017 (VOL_ENCRYPTABLE | VOL_NONREMOVABLE);
2018}
2019
Paul Lawrence87999172014-02-20 12:21:31 -08002020static int cryptfs_SHA256_fileblock(const char* filename, __le8* buf)
2021{
2022 int fd = open(filename, O_RDONLY);
2023 if (fd == -1) {
2024 SLOGE("Error opening file %s", filename);
2025 return -1;
2026 }
2027
2028 char block[CRYPT_INPLACE_BUFSIZE];
2029 memset(block, 0, sizeof(block));
2030 if (unix_read(fd, block, sizeof(block)) < 0) {
2031 SLOGE("Error reading file %s", filename);
2032 close(fd);
2033 return -1;
2034 }
2035
2036 close(fd);
2037
2038 SHA256_CTX c;
2039 SHA256_Init(&c);
2040 SHA256_Update(&c, block, sizeof(block));
2041 SHA256_Final(buf, &c);
2042
2043 return 0;
2044}
2045
2046static int cryptfs_enable_all_volumes(struct crypt_mnt_ftr *crypt_ftr, int how,
2047 char *crypto_blkdev, char *real_blkdev,
2048 int previously_encrypted_upto)
2049{
2050 off64_t cur_encryption_done=0, tot_encryption_size=0;
2051 int i, rc = -1;
2052
2053 if (!is_battery_ok()) {
2054 SLOGE("Stopping encryption due to low battery");
2055 return 0;
2056 }
2057
2058 /* The size of the userdata partition, and add in the vold volumes below */
2059 tot_encryption_size = crypt_ftr->fs_size;
2060
2061 if (how == CRYPTO_ENABLE_WIPE) {
2062 rc = cryptfs_enable_wipe(crypto_blkdev, crypt_ftr->fs_size, EXT4_FS);
2063 } else if (how == CRYPTO_ENABLE_INPLACE) {
2064 rc = cryptfs_enable_inplace(crypto_blkdev, real_blkdev,
2065 crypt_ftr->fs_size, &cur_encryption_done,
2066 tot_encryption_size,
2067 previously_encrypted_upto);
2068
2069 if (!rc && cur_encryption_done != (off64_t)crypt_ftr->fs_size) {
2070 crypt_ftr->encrypted_upto = cur_encryption_done;
2071 }
2072
2073 if (!rc && !crypt_ftr->encrypted_upto) {
2074 /* The inplace routine never actually sets the progress to 100% due
2075 * to the round down nature of integer division, so set it here */
2076 property_set("vold.encrypt_progress", "100");
2077 }
2078 } else {
2079 /* Shouldn't happen */
2080 SLOGE("cryptfs_enable: internal error, unknown option\n");
2081 rc = -1;
2082 }
2083
2084 return rc;
2085}
2086
Paul Lawrence13486032014-02-03 13:28:11 -08002087int cryptfs_enable_internal(char *howarg, int crypt_type, char *passwd,
2088 int allow_reboot)
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002089{
2090 int how = 0;
Paul Lawrence87999172014-02-20 12:21:31 -08002091 char crypto_blkdev[MAXPATHLEN], real_blkdev[MAXPATHLEN];
Ken Sumralle5032c42012-04-01 23:58:44 -07002092 unsigned long nr_sec;
Ken Sumrall160b4d62013-04-22 12:15:39 -07002093 unsigned char decrypted_master_key[KEY_LEN_BYTES];
Ken Sumrall319b1042011-06-14 14:01:55 -07002094 int rc=-1, fd, i, ret;
Paul Lawrence87999172014-02-20 12:21:31 -08002095 struct crypt_mnt_ftr crypt_ftr;
Ken Sumrall160b4d62013-04-22 12:15:39 -07002096 struct crypt_persist_data *pdata;
Ken Sumrall29d8da82011-05-18 17:20:07 -07002097 char encrypted_state[PROPERTY_VALUE_MAX];
Ken Sumrall5d4c68e2011-01-30 19:06:03 -08002098 char lockid[32] = { 0 };
Ken Sumrall29d8da82011-05-18 17:20:07 -07002099 char key_loc[PROPERTY_VALUE_MAX];
2100 char fuse_sdcard[PROPERTY_VALUE_MAX];
2101 char *sd_mnt_point;
Ken Sumrall29d8da82011-05-18 17:20:07 -07002102 int num_vols;
2103 struct volume_info *vol_list = 0;
Paul Lawrence87999172014-02-20 12:21:31 -08002104 off64_t previously_encrypted_upto = 0;
Ken Sumrall29d8da82011-05-18 17:20:07 -07002105
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002106 if (!strcmp(howarg, "wipe")) {
2107 how = CRYPTO_ENABLE_WIPE;
2108 } else if (! strcmp(howarg, "inplace")) {
2109 how = CRYPTO_ENABLE_INPLACE;
2110 } else {
2111 /* Shouldn't happen, as CommandListener vets the args */
Ken Sumrall3ed82362011-01-28 23:31:16 -08002112 goto error_unencrypted;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002113 }
2114
Paul Lawrence87999172014-02-20 12:21:31 -08002115 /* See if an encryption was underway and interrupted */
2116 if (how == CRYPTO_ENABLE_INPLACE
2117 && get_crypt_ftr_and_key(&crypt_ftr) == 0
2118 && (crypt_ftr.flags & CRYPT_ENCRYPTION_IN_PROGRESS)) {
2119 previously_encrypted_upto = crypt_ftr.encrypted_upto;
2120 crypt_ftr.encrypted_upto = 0;
2121 }
2122
2123 property_get("ro.crypto.state", encrypted_state, "");
2124 if (!strcmp(encrypted_state, "encrypted") && !previously_encrypted_upto) {
2125 SLOGE("Device is already running encrypted, aborting");
2126 goto error_unencrypted;
2127 }
2128
2129 // TODO refactor fs_mgr_get_crypt_info to get both in one call
2130 fs_mgr_get_crypt_info(fstab, key_loc, 0, sizeof(key_loc));
Ken Sumrall56ad03c2013-02-13 13:00:19 -08002131 fs_mgr_get_crypt_info(fstab, 0, real_blkdev, sizeof(real_blkdev));
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002132
Ken Sumrall3ed82362011-01-28 23:31:16 -08002133 /* Get the size of the real block device */
2134 fd = open(real_blkdev, O_RDONLY);
2135 if ( (nr_sec = get_blkdev_size(fd)) == 0) {
2136 SLOGE("Cannot get size of block device %s\n", real_blkdev);
2137 goto error_unencrypted;
2138 }
2139 close(fd);
2140
2141 /* If doing inplace encryption, make sure the orig fs doesn't include the crypto footer */
Ken Sumrall29d8da82011-05-18 17:20:07 -07002142 if ((how == CRYPTO_ENABLE_INPLACE) && (!strcmp(key_loc, KEY_IN_FOOTER))) {
Ken Sumrall3ed82362011-01-28 23:31:16 -08002143 unsigned int fs_size_sec, max_fs_size_sec;
2144
2145 fs_size_sec = get_fs_size(real_blkdev);
Paul Lawrence87999172014-02-20 12:21:31 -08002146 max_fs_size_sec = nr_sec - (CRYPT_FOOTER_OFFSET / CRYPT_SECTOR_SIZE);
Ken Sumrall3ed82362011-01-28 23:31:16 -08002147
2148 if (fs_size_sec > max_fs_size_sec) {
2149 SLOGE("Orig filesystem overlaps crypto footer region. Cannot encrypt in place.");
2150 goto error_unencrypted;
2151 }
2152 }
2153
Ken Sumrall5d4c68e2011-01-30 19:06:03 -08002154 /* Get a wakelock as this may take a while, and we don't want the
2155 * device to sleep on us. We'll grab a partial wakelock, and if the UI
2156 * wants to keep the screen on, it can grab a full wakelock.
2157 */
Ken Sumrall29d8da82011-05-18 17:20:07 -07002158 snprintf(lockid, sizeof(lockid), "enablecrypto%d", (int) getpid());
Ken Sumrall5d4c68e2011-01-30 19:06:03 -08002159 acquire_wake_lock(PARTIAL_WAKE_LOCK, lockid);
2160
Jeff Sharkey7382f812012-08-23 14:08:59 -07002161 /* Get the sdcard mount point */
Jeff Sharkeyb77bc462012-10-01 14:36:26 -07002162 sd_mnt_point = getenv("EMULATED_STORAGE_SOURCE");
Jeff Sharkey7382f812012-08-23 14:08:59 -07002163 if (!sd_mnt_point) {
2164 sd_mnt_point = getenv("EXTERNAL_STORAGE");
2165 }
2166 if (!sd_mnt_point) {
2167 sd_mnt_point = "/mnt/sdcard";
2168 }
Ken Sumrall29d8da82011-05-18 17:20:07 -07002169
Paul Lawrence87999172014-02-20 12:21:31 -08002170 /* TODO
2171 * Currently do not have test devices with multiple encryptable volumes.
2172 * When we acquire some, re-add support.
2173 */
Ken Sumrall29d8da82011-05-18 17:20:07 -07002174 num_vols=vold_getNumDirectVolumes();
2175 vol_list = malloc(sizeof(struct volume_info) * num_vols);
2176 vold_getDirectVolumeList(vol_list);
2177
2178 for (i=0; i<num_vols; i++) {
2179 if (should_encrypt(&vol_list[i])) {
Paul Lawrence87999172014-02-20 12:21:31 -08002180 SLOGE("Cannot encrypt if there are multiple encryptable volumes"
2181 "%s\n", vol_list[i].label);
2182 goto error_unencrypted;
Ken Sumrall29d8da82011-05-18 17:20:07 -07002183 }
2184 }
2185
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002186 /* The init files are setup to stop the class main and late start when
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002187 * vold sets trigger_shutdown_framework.
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002188 */
2189 property_set("vold.decrypt", "trigger_shutdown_framework");
2190 SLOGD("Just asked init to shut down class main\n");
2191
Ken Sumrall425524d2012-06-14 20:55:28 -07002192 if (vold_unmountAllAsecs()) {
2193 /* Just report the error. If any are left mounted,
2194 * umounting /data below will fail and handle the error.
2195 */
2196 SLOGE("Error unmounting internal asecs");
2197 }
2198
Ken Sumrall29d8da82011-05-18 17:20:07 -07002199 property_get("ro.crypto.fuse_sdcard", fuse_sdcard, "");
2200 if (!strcmp(fuse_sdcard, "true")) {
2201 /* This is a device using the fuse layer to emulate the sdcard semantics
2202 * on top of the userdata partition. vold does not manage it, it is managed
2203 * by the sdcard service. The sdcard service was killed by the property trigger
2204 * above, so just unmount it now. We must do this _AFTER_ killing the framework,
2205 * unlike the case for vold managed devices above.
2206 */
2207 if (wait_and_unmount(sd_mnt_point)) {
2208 goto error_shutting_down;
2209 }
Ken Sumrall2eaf7132011-01-14 12:45:48 -08002210 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002211
2212 /* Now unmount the /data partition. */
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002213 if (wait_and_unmount(DATA_MNT_POINT)) {
JP Abgrall502dc742013-11-01 13:06:20 -07002214 if (allow_reboot) {
2215 goto error_shutting_down;
2216 } else {
2217 goto error_unencrypted;
2218 }
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002219 }
2220
2221 /* Do extra work for a better UX when doing the long inplace encryption */
2222 if (how == CRYPTO_ENABLE_INPLACE) {
2223 /* Now that /data is unmounted, we need to mount a tmpfs
2224 * /data, set a property saying we're doing inplace encryption,
2225 * and restart the framework.
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002226 */
Ken Sumralle5032c42012-04-01 23:58:44 -07002227 if (fs_mgr_do_tmpfs_mount(DATA_MNT_POINT)) {
Ken Sumrall3ed82362011-01-28 23:31:16 -08002228 goto error_shutting_down;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002229 }
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002230 /* Tells the framework that inplace encryption is starting */
Ken Sumrall7df84122011-01-18 14:04:08 -08002231 property_set("vold.encrypt_progress", "0");
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002232
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002233 /* restart the framework. */
2234 /* Create necessary paths on /data */
2235 if (prep_data_fs()) {
Ken Sumrall3ed82362011-01-28 23:31:16 -08002236 goto error_shutting_down;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002237 }
2238
Ken Sumrall92736ef2012-10-17 20:57:14 -07002239 /* Ugh, shutting down the framework is not synchronous, so until it
2240 * can be fixed, this horrible hack will wait a moment for it all to
2241 * shut down before proceeding. Without it, some devices cannot
2242 * restart the graphics services.
2243 */
2244 sleep(2);
2245
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002246 /* startup service classes main and late_start */
2247 property_set("vold.decrypt", "trigger_restart_min_framework");
2248 SLOGD("Just triggered restart_min_framework\n");
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002249
Ken Sumrall7df84122011-01-18 14:04:08 -08002250 /* OK, the framework is restarted and will soon be showing a
2251 * progress bar. Time to setup an encrypted mapping, and
2252 * either write a new filesystem, or encrypt in place updating
2253 * the progress bar as we work.
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002254 */
2255 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002256
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002257 /* Start the actual work of making an encrypted filesystem */
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002258 /* Initialize a crypt_mnt_ftr for the partition */
Paul Lawrence87999172014-02-20 12:21:31 -08002259 if (previously_encrypted_upto == 0) {
2260 cryptfs_init_crypt_mnt_ftr(&crypt_ftr);
Ken Sumrall160b4d62013-04-22 12:15:39 -07002261
Paul Lawrence87999172014-02-20 12:21:31 -08002262 if (!strcmp(key_loc, KEY_IN_FOOTER)) {
2263 crypt_ftr.fs_size = nr_sec
2264 - (CRYPT_FOOTER_OFFSET / CRYPT_SECTOR_SIZE);
2265 } else {
2266 crypt_ftr.fs_size = nr_sec;
2267 }
2268 crypt_ftr.flags |= CRYPT_ENCRYPTION_IN_PROGRESS;
2269 crypt_ftr.crypt_type = crypt_type;
2270 strcpy((char *)crypt_ftr.crypto_type_name, "aes-cbc-essiv:sha256");
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002271
Paul Lawrence87999172014-02-20 12:21:31 -08002272 /* Make an encrypted master key */
2273 if (create_encrypted_random_key(passwd, crypt_ftr.master_key, crypt_ftr.salt, &crypt_ftr)) {
2274 SLOGE("Cannot create encrypted master key\n");
2275 goto error_shutting_down;
2276 }
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002277
Paul Lawrence87999172014-02-20 12:21:31 -08002278 /* Write the key to the end of the partition */
2279 put_crypt_ftr_and_key(&crypt_ftr);
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002280
Paul Lawrence87999172014-02-20 12:21:31 -08002281 /* If any persistent data has been remembered, save it.
2282 * If none, create a valid empty table and save that.
2283 */
2284 if (!persist_data) {
2285 pdata = malloc(CRYPT_PERSIST_DATA_SIZE);
2286 if (pdata) {
2287 init_empty_persist_data(pdata, CRYPT_PERSIST_DATA_SIZE);
2288 persist_data = pdata;
2289 }
2290 }
2291 if (persist_data) {
2292 save_persistent_data();
2293 }
Ken Sumrall160b4d62013-04-22 12:15:39 -07002294 }
2295
JP Abgrall7bdfa522013-11-15 13:42:56 -08002296 decrypt_master_key(passwd, decrypted_master_key, &crypt_ftr);
Ken Sumrall29d8da82011-05-18 17:20:07 -07002297 create_crypto_blk_dev(&crypt_ftr, decrypted_master_key, real_blkdev, crypto_blkdev,
2298 "userdata");
2299
Paul Lawrence87999172014-02-20 12:21:31 -08002300 /* If we are continuing, check checksums match */
2301 rc = 0;
2302 if (previously_encrypted_upto) {
2303 __le8 hash_first_block[SHA256_DIGEST_LENGTH];
2304 rc = cryptfs_SHA256_fileblock(crypto_blkdev, hash_first_block);
Ken Sumrall128626f2011-06-28 18:45:14 -07002305
Paul Lawrence87999172014-02-20 12:21:31 -08002306 if (!rc && memcmp(hash_first_block, crypt_ftr.hash_first_block,
2307 sizeof(hash_first_block)) != 0) {
2308 SLOGE("Checksums do not match - trigger wipe");
2309 rc = -1;
Ken Sumrall29d8da82011-05-18 17:20:07 -07002310 }
2311 }
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002312
Paul Lawrence87999172014-02-20 12:21:31 -08002313 if (!rc) {
2314 rc = cryptfs_enable_all_volumes(&crypt_ftr, how,
2315 crypto_blkdev, real_blkdev,
2316 previously_encrypted_upto);
2317 }
2318
2319 /* Calculate checksum if we are not finished */
2320 if (!rc && crypt_ftr.encrypted_upto) {
2321 rc = cryptfs_SHA256_fileblock(crypto_blkdev,
2322 crypt_ftr.hash_first_block);
Ken Sumrall29d8da82011-05-18 17:20:07 -07002323 if (!rc) {
Paul Lawrence87999172014-02-20 12:21:31 -08002324 SLOGE("Error calculating checksum for continuing encryption");
2325 rc = -1;
Ken Sumrall29d8da82011-05-18 17:20:07 -07002326 }
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002327 }
2328
2329 /* Undo the dm-crypt mapping whether we succeed or not */
Ken Sumrall29d8da82011-05-18 17:20:07 -07002330 delete_crypto_blk_dev("userdata");
Ken Sumrall29d8da82011-05-18 17:20:07 -07002331
2332 free(vol_list);
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002333
2334 if (! rc) {
2335 /* Success */
Ken Sumrall7f7dbaa2011-02-01 15:46:41 -08002336
Ken Sumralld33d4172011-02-01 00:49:13 -08002337 /* Clear the encryption in progres flag in the footer */
Paul Lawrence87999172014-02-20 12:21:31 -08002338 if (!crypt_ftr.encrypted_upto) {
2339 crypt_ftr.flags &= ~CRYPT_ENCRYPTION_IN_PROGRESS;
2340 } else {
2341 SLOGD("Encrypted up to sector %lld - will continue after reboot",
2342 crypt_ftr.encrypted_upto);
2343 }
Ken Sumrall160b4d62013-04-22 12:15:39 -07002344 put_crypt_ftr_and_key(&crypt_ftr);
Ken Sumralld33d4172011-02-01 00:49:13 -08002345
Ken Sumrall29d8da82011-05-18 17:20:07 -07002346 sleep(2); /* Give the UI a chance to show 100% progress */
Paul Lawrence87999172014-02-20 12:21:31 -08002347 /* Partially encrypted - ensure writes are flushed to ssd */
2348
2349 if (!crypt_ftr.encrypted_upto) {
2350 cryptfs_reboot(reboot);
2351 } else {
2352 cryptfs_reboot(shutdown);
2353 }
Ken Sumrall3ed82362011-01-28 23:31:16 -08002354 } else {
Mike Lockwoodee6d8c42012-02-15 13:43:28 -08002355 char value[PROPERTY_VALUE_MAX];
2356
Ken Sumrall319369a2012-06-27 16:30:18 -07002357 property_get("ro.vold.wipe_on_crypt_fail", value, "0");
Mike Lockwoodee6d8c42012-02-15 13:43:28 -08002358 if (!strcmp(value, "1")) {
2359 /* wipe data if encryption failed */
2360 SLOGE("encryption failed - rebooting into recovery to wipe data\n");
2361 mkdir("/cache/recovery", 0700);
Nick Kralevich4684e582012-06-26 15:07:03 -07002362 int fd = open("/cache/recovery/command", O_RDWR|O_CREAT|O_TRUNC, 0600);
Mike Lockwoodee6d8c42012-02-15 13:43:28 -08002363 if (fd >= 0) {
2364 write(fd, "--wipe_data", strlen("--wipe_data") + 1);
2365 close(fd);
2366 } else {
2367 SLOGE("could not open /cache/recovery/command\n");
2368 }
Paul Lawrence87999172014-02-20 12:21:31 -08002369 cryptfs_reboot(recovery);
Mike Lockwoodee6d8c42012-02-15 13:43:28 -08002370 } else {
2371 /* set property to trigger dialog */
2372 property_set("vold.encrypt_progress", "error_partially_encrypted");
2373 release_wake_lock(lockid);
2374 }
Ken Sumrall3ed82362011-01-28 23:31:16 -08002375 return -1;
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002376 }
2377
Ken Sumrall3ed82362011-01-28 23:31:16 -08002378 /* hrm, the encrypt step claims success, but the reboot failed.
2379 * This should not happen.
2380 * Set the property and return. Hope the framework can deal with it.
2381 */
2382 property_set("vold.encrypt_progress", "error_reboot_failed");
Ken Sumrall5d4c68e2011-01-30 19:06:03 -08002383 release_wake_lock(lockid);
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002384 return rc;
Ken Sumrall3ed82362011-01-28 23:31:16 -08002385
2386error_unencrypted:
Ken Sumrall29d8da82011-05-18 17:20:07 -07002387 free(vol_list);
Ken Sumrall3ed82362011-01-28 23:31:16 -08002388 property_set("vold.encrypt_progress", "error_not_encrypted");
Ken Sumrall5d4c68e2011-01-30 19:06:03 -08002389 if (lockid[0]) {
2390 release_wake_lock(lockid);
2391 }
Ken Sumrall3ed82362011-01-28 23:31:16 -08002392 return -1;
2393
2394error_shutting_down:
2395 /* we failed, and have not encrypted anthing, so the users's data is still intact,
2396 * but the framework is stopped and not restarted to show the error, so it's up to
2397 * vold to restart the system.
2398 */
2399 SLOGE("Error enabling encryption after framework is shutdown, no data changed, restarting system");
Paul Lawrence87999172014-02-20 12:21:31 -08002400 cryptfs_reboot(reboot);
Ken Sumrall3ed82362011-01-28 23:31:16 -08002401
2402 /* shouldn't get here */
2403 property_set("vold.encrypt_progress", "error_shutting_down");
Ken Sumrall29d8da82011-05-18 17:20:07 -07002404 free(vol_list);
Ken Sumrall5d4c68e2011-01-30 19:06:03 -08002405 if (lockid[0]) {
2406 release_wake_lock(lockid);
2407 }
Ken Sumrall3ed82362011-01-28 23:31:16 -08002408 return -1;
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002409}
2410
Paul Lawrence45f10532014-04-04 18:11:56 +00002411int cryptfs_enable(char *howarg, int type, char *passwd, int allow_reboot)
Paul Lawrence13486032014-02-03 13:28:11 -08002412{
Paul Lawrence45f10532014-04-04 18:11:56 +00002413 return cryptfs_enable_internal(howarg, type, passwd, allow_reboot);
Paul Lawrence13486032014-02-03 13:28:11 -08002414}
2415
2416int cryptfs_enable_default(char *howarg, int allow_reboot)
2417{
2418 return cryptfs_enable_internal(howarg, CRYPT_TYPE_DEFAULT,
2419 DEFAULT_PASSWORD, allow_reboot);
2420}
2421
2422int cryptfs_changepw(int crypt_type, const char *newpw)
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002423{
2424 struct crypt_mnt_ftr crypt_ftr;
Ken Sumrall160b4d62013-04-22 12:15:39 -07002425 unsigned char decrypted_master_key[KEY_LEN_BYTES];
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002426
2427 /* This is only allowed after we've successfully decrypted the master key */
Paul Lawrencef4faa572014-01-29 13:31:03 -08002428 if (!master_key_saved) {
Ken Sumrall0cc16632011-01-18 20:32:26 -08002429 SLOGE("Key not saved, aborting");
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002430 return -1;
2431 }
2432
Paul Lawrencef4faa572014-01-29 13:31:03 -08002433 if (crypt_type < 0 || crypt_type > CRYPT_TYPE_MAX_TYPE) {
2434 SLOGE("Invalid crypt_type %d", crypt_type);
2435 return -1;
2436 }
2437
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002438 /* get key */
Ken Sumrall160b4d62013-04-22 12:15:39 -07002439 if (get_crypt_ftr_and_key(&crypt_ftr)) {
Paul Lawrencef4faa572014-01-29 13:31:03 -08002440 SLOGE("Error getting crypt footer and key");
2441 return -1;
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002442 }
2443
Paul Lawrencef4faa572014-01-29 13:31:03 -08002444 crypt_ftr.crypt_type = crypt_type;
2445
2446 encrypt_master_key(crypt_type == CRYPT_TYPE_DEFAULT ? DEFAULT_PASSWORD
2447 : newpw,
2448 crypt_ftr.salt,
2449 saved_master_key,
2450 crypt_ftr.master_key,
2451 &crypt_ftr);
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002452
Jason parks70a4b3f2011-01-28 10:10:47 -06002453 /* save the key */
Ken Sumrall160b4d62013-04-22 12:15:39 -07002454 put_crypt_ftr_and_key(&crypt_ftr);
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002455
2456 return 0;
2457}
Ken Sumrall160b4d62013-04-22 12:15:39 -07002458
2459static int persist_get_key(char *fieldname, char *value)
2460{
2461 unsigned int i;
2462
2463 if (persist_data == NULL) {
2464 return -1;
2465 }
2466 for (i = 0; i < persist_data->persist_valid_entries; i++) {
2467 if (!strncmp(persist_data->persist_entry[i].key, fieldname, PROPERTY_KEY_MAX)) {
2468 /* We found it! */
2469 strlcpy(value, persist_data->persist_entry[i].val, PROPERTY_VALUE_MAX);
2470 return 0;
2471 }
2472 }
2473
2474 return -1;
2475}
2476
2477static int persist_set_key(char *fieldname, char *value, int encrypted)
2478{
2479 unsigned int i;
2480 unsigned int num;
2481 struct crypt_mnt_ftr crypt_ftr;
2482 unsigned int max_persistent_entries;
2483 unsigned int dsize;
2484
2485 if (persist_data == NULL) {
2486 return -1;
2487 }
2488
2489 /* If encrypted, use the values from the crypt_ftr, otherwise
2490 * use the values for the current spec.
2491 */
2492 if (encrypted) {
2493 if(get_crypt_ftr_and_key(&crypt_ftr)) {
2494 return -1;
2495 }
2496 dsize = crypt_ftr.persist_data_size;
2497 } else {
2498 dsize = CRYPT_PERSIST_DATA_SIZE;
2499 }
2500 max_persistent_entries = (dsize - sizeof(struct crypt_persist_data)) /
2501 sizeof(struct crypt_persist_entry);
2502
2503 num = persist_data->persist_valid_entries;
2504
2505 for (i = 0; i < num; i++) {
2506 if (!strncmp(persist_data->persist_entry[i].key, fieldname, PROPERTY_KEY_MAX)) {
2507 /* We found an existing entry, update it! */
2508 memset(persist_data->persist_entry[i].val, 0, PROPERTY_VALUE_MAX);
2509 strlcpy(persist_data->persist_entry[i].val, value, PROPERTY_VALUE_MAX);
2510 return 0;
2511 }
2512 }
2513
2514 /* We didn't find it, add it to the end, if there is room */
2515 if (persist_data->persist_valid_entries < max_persistent_entries) {
2516 memset(&persist_data->persist_entry[num], 0, sizeof(struct crypt_persist_entry));
2517 strlcpy(persist_data->persist_entry[num].key, fieldname, PROPERTY_KEY_MAX);
2518 strlcpy(persist_data->persist_entry[num].val, value, PROPERTY_VALUE_MAX);
2519 persist_data->persist_valid_entries++;
2520 return 0;
2521 }
2522
2523 return -1;
2524}
2525
2526/* Return the value of the specified field. */
2527int cryptfs_getfield(char *fieldname, char *value, int len)
2528{
2529 char temp_value[PROPERTY_VALUE_MAX];
2530 char real_blkdev[MAXPATHLEN];
2531 /* 0 is success, 1 is not encrypted,
2532 * -1 is value not set, -2 is any other error
2533 */
2534 int rc = -2;
2535
2536 if (persist_data == NULL) {
2537 load_persistent_data();
2538 if (persist_data == NULL) {
2539 SLOGE("Getfield error, cannot load persistent data");
2540 goto out;
2541 }
2542 }
2543
2544 if (!persist_get_key(fieldname, temp_value)) {
2545 /* We found it, copy it to the caller's buffer and return */
2546 strlcpy(value, temp_value, len);
2547 rc = 0;
2548 } else {
2549 /* Sadness, it's not there. Return the error */
2550 rc = -1;
2551 }
2552
2553out:
2554 return rc;
2555}
2556
2557/* Set the value of the specified field. */
2558int cryptfs_setfield(char *fieldname, char *value)
2559{
2560 struct crypt_persist_data stored_pdata;
2561 struct crypt_persist_data *pdata_p;
2562 struct crypt_mnt_ftr crypt_ftr;
2563 char encrypted_state[PROPERTY_VALUE_MAX];
2564 /* 0 is success, -1 is an error */
2565 int rc = -1;
2566 int encrypted = 0;
2567
2568 if (persist_data == NULL) {
2569 load_persistent_data();
2570 if (persist_data == NULL) {
2571 SLOGE("Setfield error, cannot load persistent data");
2572 goto out;
2573 }
2574 }
2575
2576 property_get("ro.crypto.state", encrypted_state, "");
2577 if (!strcmp(encrypted_state, "encrypted") ) {
2578 encrypted = 1;
2579 }
2580
2581 if (persist_set_key(fieldname, value, encrypted)) {
2582 goto out;
2583 }
2584
2585 /* If we are running encrypted, save the persistent data now */
2586 if (encrypted) {
2587 if (save_persistent_data()) {
2588 SLOGE("Setfield error, cannot save persistent data");
2589 goto out;
2590 }
2591 }
2592
2593 rc = 0;
2594
2595out:
2596 return rc;
2597}
Paul Lawrencef4faa572014-01-29 13:31:03 -08002598
2599/* Checks userdata. Attempt to mount the volume if default-
2600 * encrypted.
2601 * On success trigger next init phase and return 0.
2602 * Currently do not handle failure - see TODO below.
2603 */
2604int cryptfs_mount_default_encrypted(void)
2605{
2606 char decrypt_state[PROPERTY_VALUE_MAX];
2607 property_get("vold.decrypt", decrypt_state, "0");
2608 if (!strcmp(decrypt_state, "0")) {
2609 SLOGE("Not encrypted - should not call here");
2610 } else {
2611 int crypt_type = cryptfs_get_password_type();
2612 if (crypt_type < 0 || crypt_type > CRYPT_TYPE_MAX_TYPE) {
2613 SLOGE("Bad crypt type - error");
2614 } else if (crypt_type != CRYPT_TYPE_DEFAULT) {
2615 SLOGD("Password is not default - "
2616 "starting min framework to prompt");
2617 property_set("vold.decrypt", "trigger_restart_min_framework");
2618 return 0;
2619 } else if (cryptfs_check_passwd(DEFAULT_PASSWORD) == 0) {
2620 SLOGD("Password is default - restarting filesystem");
2621 cryptfs_restart_internal(0);
2622 return 0;
2623 } else {
2624 SLOGE("Encrypted, default crypt type but can't decrypt");
2625 }
2626 }
2627
2628 /** @TODO make sure we factory wipe in this situation
2629 * In general if we got here there is no recovery
2630 */
2631 return 0;
2632}
2633
2634/* Returns type of the password, default, pattern, pin or password.
2635 */
2636int cryptfs_get_password_type(void)
2637{
2638 struct crypt_mnt_ftr crypt_ftr;
2639
2640 if (get_crypt_ftr_and_key(&crypt_ftr)) {
2641 SLOGE("Error getting crypt footer and key\n");
2642 return -1;
2643 }
2644
2645 return crypt_ftr.crypt_type;
2646}
Paul Lawrence684dbdf2014-02-07 12:07:22 -08002647
Paul Lawrence399317e2014-03-10 13:20:50 -07002648char* cryptfs_get_password()
Paul Lawrence684dbdf2014-02-07 12:07:22 -08002649{
Paul Lawrence399317e2014-03-10 13:20:50 -07002650 struct timespec now;
2651 clock_gettime(CLOCK_MONOTONIC, &now);
2652 if (now.tv_sec < password_expiry_time) {
2653 return password;
2654 } else {
2655 cryptfs_clear_password();
2656 return 0;
2657 }
2658}
2659
2660void cryptfs_clear_password()
2661{
2662 if (password) {
2663 size_t len = strlen(password);
2664 memset(password, 0, len);
2665 free(password);
2666 password = 0;
2667 password_expiry_time = 0;
2668 }
Paul Lawrence684dbdf2014-02-07 12:07:22 -08002669}