blob: e4728004c8eebf809f2dcd18c395aa75f8e34eb1 [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>
Ken Sumrall8ddbe402011-01-17 15:26:29 -080038#include <openssl/sha.h>
Ken Sumrall8f869aa2010-12-03 03:47:09 -080039#include <errno.h>
Ken Sumrall3ed82362011-01-28 23:31:16 -080040#include <ext4.h>
Ken Sumrall29d8da82011-05-18 17:20:07 -070041#include <linux/kdev_t.h>
Ken Sumralle5032c42012-04-01 23:58:44 -070042#include <fs_mgr.h>
Ken Sumrall8f869aa2010-12-03 03:47:09 -080043#include "cryptfs.h"
44#define LOG_TAG "Cryptfs"
45#include "cutils/log.h"
46#include "cutils/properties.h"
Ken Sumralladfba362013-06-04 16:37:52 -070047#include "cutils/android_reboot.h"
Ken Sumrall5d4c68e2011-01-30 19:06:03 -080048#include "hardware_legacy/power.h"
Ken Sumralle550f782013-08-20 13:48:23 -070049#include <logwrap/logwrap.h>
Ken Sumrall29d8da82011-05-18 17:20:07 -070050#include "VolumeManager.h"
Ken Sumrall9caab762013-06-11 19:10:20 -070051#include "VoldUtil.h"
Kenny Rootc4c70f12013-06-14 12:11:38 -070052#include "crypto_scrypt.h"
Paul Lawrenceae59fe62014-01-21 08:23:27 -080053#include "ext4_utils.h"
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
Ken Sumralladfba362013-06-04 16:37:52 -0700102static void cryptfs_reboot(int recovery)
103{
104 if (recovery) {
105 property_set(ANDROID_RB_PROPERTY, "reboot,recovery");
106 } else {
107 property_set(ANDROID_RB_PROPERTY, "reboot");
108 }
109 sleep(20);
110
111 /* Shouldn't get here, reboot should happen before sleep times out */
112 return;
113}
114
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800115static void ioctl_init(struct dm_ioctl *io, size_t dataSize, const char *name, unsigned flags)
116{
117 memset(io, 0, dataSize);
118 io->data_size = dataSize;
119 io->data_start = sizeof(struct dm_ioctl);
120 io->version[0] = 4;
121 io->version[1] = 0;
122 io->version[2] = 0;
123 io->flags = flags;
124 if (name) {
125 strncpy(io->name, name, sizeof(io->name));
126 }
127}
128
Kenny Rootc4c70f12013-06-14 12:11:38 -0700129/**
130 * Gets the default device scrypt parameters for key derivation time tuning.
131 * The parameters should lead to about one second derivation time for the
132 * given device.
133 */
134static void get_device_scrypt_params(struct crypt_mnt_ftr *ftr) {
135 const int default_params[] = SCRYPT_DEFAULTS;
136 int params[] = SCRYPT_DEFAULTS;
137 char paramstr[PROPERTY_VALUE_MAX];
138 char *token;
139 char *saveptr;
140 int i;
141
142 property_get(SCRYPT_PROP, paramstr, "");
143 if (paramstr[0] != '\0') {
144 /*
145 * The token we're looking for should be three integers separated by
146 * colons (e.g., "12:8:1"). Scan the property to make sure it matches.
147 */
Kenny Root2947e342013-08-14 15:54:49 -0700148 for (i = 0, token = strtok_r(paramstr, ":", &saveptr);
149 token != NULL && i < 3;
Kenny Rootc4c70f12013-06-14 12:11:38 -0700150 i++, token = strtok_r(NULL, ":", &saveptr)) {
151 char *endptr;
152 params[i] = strtol(token, &endptr, 10);
153
154 /*
155 * Check that there was a valid number and it's 8-bit. If not,
156 * break out and the end check will take the default values.
157 */
158 if ((*token == '\0') || (*endptr != '\0') || params[i] < 0 || params[i] > 255) {
159 break;
160 }
161 }
162
163 /*
164 * If there were not enough tokens or a token was malformed (not an
165 * integer), it will end up here and the default parameters can be
166 * taken.
167 */
168 if ((i != 3) || (token != NULL)) {
169 SLOGW("bad scrypt parameters '%s' should be like '12:8:1'; using defaults", paramstr);
170 memcpy(params, default_params, sizeof(params));
171 }
172 }
173
174 ftr->N_factor = params[0];
175 ftr->r_factor = params[1];
176 ftr->p_factor = params[2];
177}
178
Ken Sumrall3ed82362011-01-28 23:31:16 -0800179static unsigned int get_fs_size(char *dev)
180{
181 int fd, block_size;
182 struct ext4_super_block sb;
183 off64_t len;
184
185 if ((fd = open(dev, O_RDONLY)) < 0) {
186 SLOGE("Cannot open device to get filesystem size ");
187 return 0;
188 }
189
190 if (lseek64(fd, 1024, SEEK_SET) < 0) {
191 SLOGE("Cannot seek to superblock");
192 return 0;
193 }
194
195 if (read(fd, &sb, sizeof(sb)) != sizeof(sb)) {
196 SLOGE("Cannot read superblock");
197 return 0;
198 }
199
200 close(fd);
201
202 block_size = 1024 << sb.s_log_block_size;
203 /* compute length in bytes */
204 len = ( ((off64_t)sb.s_blocks_count_hi << 32) + sb.s_blocks_count_lo) * block_size;
205
206 /* return length in sectors */
207 return (unsigned int) (len / 512);
208}
209
Ken Sumrall160b4d62013-04-22 12:15:39 -0700210static int get_crypt_ftr_info(char **metadata_fname, off64_t *off)
211{
212 static int cached_data = 0;
213 static off64_t cached_off = 0;
214 static char cached_metadata_fname[PROPERTY_VALUE_MAX] = "";
215 int fd;
216 char key_loc[PROPERTY_VALUE_MAX];
217 char real_blkdev[PROPERTY_VALUE_MAX];
218 unsigned int nr_sec;
219 int rc = -1;
220
221 if (!cached_data) {
222 fs_mgr_get_crypt_info(fstab, key_loc, real_blkdev, sizeof(key_loc));
223
224 if (!strcmp(key_loc, KEY_IN_FOOTER)) {
225 if ( (fd = open(real_blkdev, O_RDWR)) < 0) {
226 SLOGE("Cannot open real block device %s\n", real_blkdev);
227 return -1;
228 }
229
230 if ((nr_sec = get_blkdev_size(fd))) {
231 /* If it's an encrypted Android partition, the last 16 Kbytes contain the
232 * encryption info footer and key, and plenty of bytes to spare for future
233 * growth.
234 */
235 strlcpy(cached_metadata_fname, real_blkdev, sizeof(cached_metadata_fname));
236 cached_off = ((off64_t)nr_sec * 512) - CRYPT_FOOTER_OFFSET;
237 cached_data = 1;
238 } else {
239 SLOGE("Cannot get size of block device %s\n", real_blkdev);
240 }
241 close(fd);
242 } else {
243 strlcpy(cached_metadata_fname, key_loc, sizeof(cached_metadata_fname));
244 cached_off = 0;
245 cached_data = 1;
246 }
247 }
248
249 if (cached_data) {
250 if (metadata_fname) {
251 *metadata_fname = cached_metadata_fname;
252 }
253 if (off) {
254 *off = cached_off;
255 }
256 rc = 0;
257 }
258
259 return rc;
260}
261
Ken Sumralle8744072011-01-18 22:01:55 -0800262/* key or salt can be NULL, in which case just skip writing that value. Useful to
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800263 * update the failed mount count but not change the key.
264 */
Ken Sumrall160b4d62013-04-22 12:15:39 -0700265static int put_crypt_ftr_and_key(struct crypt_mnt_ftr *crypt_ftr)
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800266{
267 int fd;
268 unsigned int nr_sec, cnt;
Ken Sumrall160b4d62013-04-22 12:15:39 -0700269 /* starting_off is set to the SEEK_SET offset
270 * where the crypto structure starts
271 */
272 off64_t starting_off;
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800273 int rc = -1;
Ken Sumrall160b4d62013-04-22 12:15:39 -0700274 char *fname = NULL;
Ken Sumrall3be890f2011-09-14 16:53:46 -0700275 struct stat statbuf;
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800276
Ken Sumrall160b4d62013-04-22 12:15:39 -0700277 if (get_crypt_ftr_info(&fname, &starting_off)) {
278 SLOGE("Unable to get crypt_ftr_info\n");
279 return -1;
280 }
281 if (fname[0] != '/') {
Ken Sumralle5032c42012-04-01 23:58:44 -0700282 SLOGE("Unexpected value for crypto key location\n");
Ken Sumrall160b4d62013-04-22 12:15:39 -0700283 return -1;
284 }
Ken Sumralle550f782013-08-20 13:48:23 -0700285 if ( (fd = open(fname, O_RDWR | O_CREAT, 0600)) < 0) {
286 SLOGE("Cannot open footer file %s for put\n", fname);
Ken Sumrall160b4d62013-04-22 12:15:39 -0700287 return -1;
288 }
289
290 /* Seek to the start of the crypt footer */
291 if (lseek64(fd, starting_off, SEEK_SET) == -1) {
292 SLOGE("Cannot seek to real block device footer\n");
293 goto errout;
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800294 }
295
296 if ((cnt = write(fd, crypt_ftr, sizeof(struct crypt_mnt_ftr))) != sizeof(struct crypt_mnt_ftr)) {
297 SLOGE("Cannot write real block device footer\n");
298 goto errout;
299 }
300
Ken Sumrall3be890f2011-09-14 16:53:46 -0700301 fstat(fd, &statbuf);
302 /* If the keys are kept on a raw block device, do not try to truncate it. */
Ken Sumralle550f782013-08-20 13:48:23 -0700303 if (S_ISREG(statbuf.st_mode)) {
Ken Sumrall29d8da82011-05-18 17:20:07 -0700304 if (ftruncate(fd, 0x4000)) {
Colin Cross59846b62014-02-06 20:34:29 -0800305 SLOGE("Cannot set footer file size\n");
Ken Sumralle8744072011-01-18 22:01:55 -0800306 goto errout;
307 }
308 }
309
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800310 /* Success! */
311 rc = 0;
312
313errout:
314 close(fd);
315 return rc;
316
317}
318
Ken Sumrall160b4d62013-04-22 12:15:39 -0700319static inline int unix_read(int fd, void* buff, int len)
320{
321 return TEMP_FAILURE_RETRY(read(fd, buff, len));
322}
323
324static inline int unix_write(int fd, const void* buff, int len)
325{
326 return TEMP_FAILURE_RETRY(write(fd, buff, len));
327}
328
329static void init_empty_persist_data(struct crypt_persist_data *pdata, int len)
330{
331 memset(pdata, 0, len);
332 pdata->persist_magic = PERSIST_DATA_MAGIC;
333 pdata->persist_valid_entries = 0;
334}
335
336/* A routine to update the passed in crypt_ftr to the lastest version.
337 * fd is open read/write on the device that holds the crypto footer and persistent
338 * data, crypt_ftr is a pointer to the struct to be updated, and offset is the
339 * absolute offset to the start of the crypt_mnt_ftr on the passed in fd.
340 */
341static void upgrade_crypt_ftr(int fd, struct crypt_mnt_ftr *crypt_ftr, off64_t offset)
342{
Kenny Root7434b312013-06-14 11:29:53 -0700343 int orig_major = crypt_ftr->major_version;
344 int orig_minor = crypt_ftr->minor_version;
Ken Sumrall160b4d62013-04-22 12:15:39 -0700345
Kenny Root7434b312013-06-14 11:29:53 -0700346 if ((crypt_ftr->major_version == 1) && (crypt_ftr->minor_version == 0)) {
347 struct crypt_persist_data *pdata;
348 off64_t pdata_offset = offset + CRYPT_FOOTER_TO_PERSIST_OFFSET;
Ken Sumrall160b4d62013-04-22 12:15:39 -0700349
Kenny Rootc4c70f12013-06-14 12:11:38 -0700350 SLOGW("upgrading crypto footer to 1.1");
351
Kenny Root7434b312013-06-14 11:29:53 -0700352 pdata = malloc(CRYPT_PERSIST_DATA_SIZE);
353 if (pdata == NULL) {
354 SLOGE("Cannot allocate persisent data\n");
355 return;
356 }
357 memset(pdata, 0, CRYPT_PERSIST_DATA_SIZE);
358
359 /* Need to initialize the persistent data area */
360 if (lseek64(fd, pdata_offset, SEEK_SET) == -1) {
361 SLOGE("Cannot seek to persisent data offset\n");
362 return;
363 }
364 /* Write all zeros to the first copy, making it invalid */
365 unix_write(fd, pdata, CRYPT_PERSIST_DATA_SIZE);
366
367 /* Write a valid but empty structure to the second copy */
368 init_empty_persist_data(pdata, CRYPT_PERSIST_DATA_SIZE);
369 unix_write(fd, pdata, CRYPT_PERSIST_DATA_SIZE);
370
371 /* Update the footer */
372 crypt_ftr->persist_data_size = CRYPT_PERSIST_DATA_SIZE;
373 crypt_ftr->persist_data_offset[0] = pdata_offset;
374 crypt_ftr->persist_data_offset[1] = pdata_offset + CRYPT_PERSIST_DATA_SIZE;
375 crypt_ftr->minor_version = 1;
Ken Sumrall160b4d62013-04-22 12:15:39 -0700376 }
377
Paul Lawrencef4faa572014-01-29 13:31:03 -0800378 if ((crypt_ftr->major_version == 1) && (crypt_ftr->minor_version == 1)) {
Kenny Rootc4c70f12013-06-14 12:11:38 -0700379 SLOGW("upgrading crypto footer to 1.2");
JP Abgrall7bdfa522013-11-15 13:42:56 -0800380 /* But keep the old kdf_type.
381 * It will get updated later to KDF_SCRYPT after the password has been verified.
382 */
Kenny Rootc4c70f12013-06-14 12:11:38 -0700383 crypt_ftr->kdf_type = KDF_PBKDF2;
384 get_device_scrypt_params(crypt_ftr);
385 crypt_ftr->minor_version = 2;
386 }
387
Paul Lawrencef4faa572014-01-29 13:31:03 -0800388 if ((crypt_ftr->major_version == 1) && (crypt_ftr->minor_version == 2)) {
389 SLOGW("upgrading crypto footer to 1.3");
390 crypt_ftr->crypt_type = CRYPT_TYPE_PASSWORD;
391 crypt_ftr->minor_version = 3;
392 }
393
Kenny Root7434b312013-06-14 11:29:53 -0700394 if ((orig_major != crypt_ftr->major_version) || (orig_minor != crypt_ftr->minor_version)) {
395 if (lseek64(fd, offset, SEEK_SET) == -1) {
396 SLOGE("Cannot seek to crypt footer\n");
397 return;
398 }
399 unix_write(fd, crypt_ftr, sizeof(struct crypt_mnt_ftr));
Ken Sumrall160b4d62013-04-22 12:15:39 -0700400 }
Ken Sumrall160b4d62013-04-22 12:15:39 -0700401}
402
403
404static int get_crypt_ftr_and_key(struct crypt_mnt_ftr *crypt_ftr)
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800405{
406 int fd;
407 unsigned int nr_sec, cnt;
Ken Sumrall160b4d62013-04-22 12:15:39 -0700408 off64_t starting_off;
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800409 int rc = -1;
Ken Sumrall160b4d62013-04-22 12:15:39 -0700410 char *fname = NULL;
Ken Sumrall29d8da82011-05-18 17:20:07 -0700411 struct stat statbuf;
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800412
Ken Sumrall160b4d62013-04-22 12:15:39 -0700413 if (get_crypt_ftr_info(&fname, &starting_off)) {
414 SLOGE("Unable to get crypt_ftr_info\n");
415 return -1;
416 }
417 if (fname[0] != '/') {
Ken Sumralle5032c42012-04-01 23:58:44 -0700418 SLOGE("Unexpected value for crypto key location\n");
Ken Sumrall160b4d62013-04-22 12:15:39 -0700419 return -1;
420 }
421 if ( (fd = open(fname, O_RDWR)) < 0) {
Ken Sumralle550f782013-08-20 13:48:23 -0700422 SLOGE("Cannot open footer file %s for get\n", fname);
Ken Sumrall160b4d62013-04-22 12:15:39 -0700423 return -1;
424 }
425
426 /* Make sure it's 16 Kbytes in length */
427 fstat(fd, &statbuf);
428 if (S_ISREG(statbuf.st_mode) && (statbuf.st_size != 0x4000)) {
429 SLOGE("footer file %s is not the expected size!\n", fname);
430 goto errout;
431 }
432
433 /* Seek to the start of the crypt footer */
434 if (lseek64(fd, starting_off, SEEK_SET) == -1) {
435 SLOGE("Cannot seek to real block device footer\n");
436 goto errout;
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800437 }
438
439 if ( (cnt = read(fd, crypt_ftr, sizeof(struct crypt_mnt_ftr))) != sizeof(struct crypt_mnt_ftr)) {
440 SLOGE("Cannot read real block device footer\n");
441 goto errout;
442 }
443
444 if (crypt_ftr->magic != CRYPT_MNT_MAGIC) {
Ken Sumrall29d8da82011-05-18 17:20:07 -0700445 SLOGE("Bad magic for real block device %s\n", fname);
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800446 goto errout;
447 }
448
Kenny Rootc96a5f82013-06-14 12:08:28 -0700449 if (crypt_ftr->major_version != CURRENT_MAJOR_VERSION) {
450 SLOGE("Cannot understand major version %d real block device footer; expected %d\n",
451 crypt_ftr->major_version, CURRENT_MAJOR_VERSION);
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800452 goto errout;
453 }
454
Kenny Rootc96a5f82013-06-14 12:08:28 -0700455 if (crypt_ftr->minor_version > CURRENT_MINOR_VERSION) {
456 SLOGW("Warning: crypto footer minor version %d, expected <= %d, continuing...\n",
457 crypt_ftr->minor_version, CURRENT_MINOR_VERSION);
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800458 }
459
Ken Sumrall160b4d62013-04-22 12:15:39 -0700460 /* If this is a verion 1.0 crypt_ftr, make it a 1.1 crypt footer, and update the
461 * copy on disk before returning.
462 */
Kenny Rootc96a5f82013-06-14 12:08:28 -0700463 if (crypt_ftr->minor_version < CURRENT_MINOR_VERSION) {
Ken Sumrall160b4d62013-04-22 12:15:39 -0700464 upgrade_crypt_ftr(fd, crypt_ftr, starting_off);
Ken Sumralle8744072011-01-18 22:01:55 -0800465 }
466
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800467 /* Success! */
468 rc = 0;
469
470errout:
471 close(fd);
472 return rc;
473}
474
Ken Sumrall160b4d62013-04-22 12:15:39 -0700475static int validate_persistent_data_storage(struct crypt_mnt_ftr *crypt_ftr)
476{
477 if (crypt_ftr->persist_data_offset[0] + crypt_ftr->persist_data_size >
478 crypt_ftr->persist_data_offset[1]) {
479 SLOGE("Crypt_ftr persist data regions overlap");
480 return -1;
481 }
482
483 if (crypt_ftr->persist_data_offset[0] >= crypt_ftr->persist_data_offset[1]) {
484 SLOGE("Crypt_ftr persist data region 0 starts after region 1");
485 return -1;
486 }
487
488 if (((crypt_ftr->persist_data_offset[1] + crypt_ftr->persist_data_size) -
489 (crypt_ftr->persist_data_offset[0] - CRYPT_FOOTER_TO_PERSIST_OFFSET)) >
490 CRYPT_FOOTER_OFFSET) {
491 SLOGE("Persistent data extends past crypto footer");
492 return -1;
493 }
494
495 return 0;
496}
497
498static int load_persistent_data(void)
499{
500 struct crypt_mnt_ftr crypt_ftr;
501 struct crypt_persist_data *pdata = NULL;
502 char encrypted_state[PROPERTY_VALUE_MAX];
503 char *fname;
504 int found = 0;
505 int fd;
506 int ret;
507 int i;
508
509 if (persist_data) {
510 /* Nothing to do, we've already loaded or initialized it */
511 return 0;
512 }
513
514
515 /* If not encrypted, just allocate an empty table and initialize it */
516 property_get("ro.crypto.state", encrypted_state, "");
517 if (strcmp(encrypted_state, "encrypted") ) {
518 pdata = malloc(CRYPT_PERSIST_DATA_SIZE);
519 if (pdata) {
520 init_empty_persist_data(pdata, CRYPT_PERSIST_DATA_SIZE);
521 persist_data = pdata;
522 return 0;
523 }
524 return -1;
525 }
526
527 if(get_crypt_ftr_and_key(&crypt_ftr)) {
528 return -1;
529 }
530
531 if ((crypt_ftr.major_version != 1) || (crypt_ftr.minor_version != 1)) {
532 SLOGE("Crypt_ftr version doesn't support persistent data");
533 return -1;
534 }
535
536 if (get_crypt_ftr_info(&fname, NULL)) {
537 return -1;
538 }
539
540 ret = validate_persistent_data_storage(&crypt_ftr);
541 if (ret) {
542 return -1;
543 }
544
545 fd = open(fname, O_RDONLY);
546 if (fd < 0) {
547 SLOGE("Cannot open %s metadata file", fname);
548 return -1;
549 }
550
551 if (persist_data == NULL) {
552 pdata = malloc(crypt_ftr.persist_data_size);
553 if (pdata == NULL) {
554 SLOGE("Cannot allocate memory for persistent data");
555 goto err;
556 }
557 }
558
559 for (i = 0; i < 2; i++) {
560 if (lseek64(fd, crypt_ftr.persist_data_offset[i], SEEK_SET) < 0) {
561 SLOGE("Cannot seek to read persistent data on %s", fname);
562 goto err2;
563 }
564 if (unix_read(fd, pdata, crypt_ftr.persist_data_size) < 0){
565 SLOGE("Error reading persistent data on iteration %d", i);
566 goto err2;
567 }
568 if (pdata->persist_magic == PERSIST_DATA_MAGIC) {
569 found = 1;
570 break;
571 }
572 }
573
574 if (!found) {
575 SLOGI("Could not find valid persistent data, creating");
576 init_empty_persist_data(pdata, crypt_ftr.persist_data_size);
577 }
578
579 /* Success */
580 persist_data = pdata;
581 close(fd);
582 return 0;
583
584err2:
585 free(pdata);
586
587err:
588 close(fd);
589 return -1;
590}
591
592static int save_persistent_data(void)
593{
594 struct crypt_mnt_ftr crypt_ftr;
595 struct crypt_persist_data *pdata;
596 char *fname;
597 off64_t write_offset;
598 off64_t erase_offset;
599 int found = 0;
600 int fd;
601 int ret;
602
603 if (persist_data == NULL) {
604 SLOGE("No persistent data to save");
605 return -1;
606 }
607
608 if(get_crypt_ftr_and_key(&crypt_ftr)) {
609 return -1;
610 }
611
612 if ((crypt_ftr.major_version != 1) || (crypt_ftr.minor_version != 1)) {
613 SLOGE("Crypt_ftr version doesn't support persistent data");
614 return -1;
615 }
616
617 ret = validate_persistent_data_storage(&crypt_ftr);
618 if (ret) {
619 return -1;
620 }
621
622 if (get_crypt_ftr_info(&fname, NULL)) {
623 return -1;
624 }
625
626 fd = open(fname, O_RDWR);
627 if (fd < 0) {
628 SLOGE("Cannot open %s metadata file", fname);
629 return -1;
630 }
631
632 pdata = malloc(crypt_ftr.persist_data_size);
633 if (pdata == NULL) {
634 SLOGE("Cannot allocate persistant data");
635 goto err;
636 }
637
638 if (lseek64(fd, crypt_ftr.persist_data_offset[0], SEEK_SET) < 0) {
639 SLOGE("Cannot seek to read persistent data on %s", fname);
640 goto err2;
641 }
642
643 if (unix_read(fd, pdata, crypt_ftr.persist_data_size) < 0) {
644 SLOGE("Error reading persistent data before save");
645 goto err2;
646 }
647
648 if (pdata->persist_magic == PERSIST_DATA_MAGIC) {
649 /* The first copy is the curent valid copy, so write to
650 * the second copy and erase this one */
651 write_offset = crypt_ftr.persist_data_offset[1];
652 erase_offset = crypt_ftr.persist_data_offset[0];
653 } else {
654 /* The second copy must be the valid copy, so write to
655 * the first copy, and erase the second */
656 write_offset = crypt_ftr.persist_data_offset[0];
657 erase_offset = crypt_ftr.persist_data_offset[1];
658 }
659
660 /* Write the new copy first, if successful, then erase the old copy */
661 if (lseek(fd, write_offset, SEEK_SET) < 0) {
662 SLOGE("Cannot seek to write persistent data");
663 goto err2;
664 }
665 if (unix_write(fd, persist_data, crypt_ftr.persist_data_size) ==
666 (int) crypt_ftr.persist_data_size) {
667 if (lseek(fd, erase_offset, SEEK_SET) < 0) {
668 SLOGE("Cannot seek to erase previous persistent data");
669 goto err2;
670 }
671 fsync(fd);
672 memset(pdata, 0, crypt_ftr.persist_data_size);
673 if (unix_write(fd, pdata, crypt_ftr.persist_data_size) !=
674 (int) crypt_ftr.persist_data_size) {
675 SLOGE("Cannot write to erase previous persistent data");
676 goto err2;
677 }
678 fsync(fd);
679 } else {
680 SLOGE("Cannot write to save persistent data");
681 goto err2;
682 }
683
684 /* Success */
685 free(pdata);
686 close(fd);
687 return 0;
688
689err2:
690 free(pdata);
691err:
692 close(fd);
693 return -1;
694}
695
Paul Lawrencef4faa572014-01-29 13:31:03 -0800696static int hexdigit (char c)
697{
698 if (c >= '0' && c <= '9') return c - '0';
699 c = tolower(c);
700 if (c >= 'a' && c <= 'f') return c - 'a' + 10;
701 return -1;
702}
703
704static unsigned char* convert_hex_ascii_to_key(const char* master_key_ascii,
705 unsigned int* out_keysize)
706{
707 unsigned int i;
708 *out_keysize = 0;
709
710 size_t size = strlen (master_key_ascii);
711 if (size % 2) {
712 SLOGE("Trying to convert ascii string of odd length");
713 return NULL;
714 }
715
716 unsigned char* master_key = (unsigned char*) malloc(size / 2);
717 if (master_key == 0) {
718 SLOGE("Cannot allocate");
719 return NULL;
720 }
721
722 for (i = 0; i < size; i += 2) {
723 int high_nibble = hexdigit (master_key_ascii[i]);
724 int low_nibble = hexdigit (master_key_ascii[i + 1]);
725
726 if(high_nibble < 0 || low_nibble < 0) {
727 SLOGE("Invalid hex string");
728 free (master_key);
729 return NULL;
730 }
731
732 master_key[*out_keysize] = high_nibble * 16 + low_nibble;
733 (*out_keysize)++;
734 }
735
736 return master_key;
737}
738
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800739/* Convert a binary key of specified length into an ascii hex string equivalent,
740 * without the leading 0x and with null termination
741 */
Paul Lawrencef4faa572014-01-29 13:31:03 -0800742static void convert_key_to_hex_ascii(unsigned char *master_key, unsigned int keysize,
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800743 char *master_key_ascii)
744{
745 unsigned int i, a;
746 unsigned char nibble;
747
748 for (i=0, a=0; i<keysize; i++, a+=2) {
749 /* For each byte, write out two ascii hex digits */
750 nibble = (master_key[i] >> 4) & 0xf;
751 master_key_ascii[a] = nibble + (nibble > 9 ? 0x37 : 0x30);
752
753 nibble = master_key[i] & 0xf;
754 master_key_ascii[a+1] = nibble + (nibble > 9 ? 0x37 : 0x30);
755 }
756
757 /* Add the null termination */
758 master_key_ascii[a] = '\0';
759
760}
761
Ken Sumralldb5e0262013-02-05 17:39:48 -0800762static int load_crypto_mapping_table(struct crypt_mnt_ftr *crypt_ftr, unsigned char *master_key,
763 char *real_blk_name, const char *name, int fd,
764 char *extra_params)
765{
766 char buffer[DM_CRYPT_BUF_SIZE];
767 struct dm_ioctl *io;
768 struct dm_target_spec *tgt;
769 char *crypt_params;
770 char master_key_ascii[129]; /* Large enough to hold 512 bit key and null */
771 int i;
772
773 io = (struct dm_ioctl *) buffer;
774
775 /* Load the mapping table for this device */
776 tgt = (struct dm_target_spec *) &buffer[sizeof(struct dm_ioctl)];
777
778 ioctl_init(io, DM_CRYPT_BUF_SIZE, name, 0);
779 io->target_count = 1;
780 tgt->status = 0;
781 tgt->sector_start = 0;
782 tgt->length = crypt_ftr->fs_size;
783 strcpy(tgt->target_type, "crypt");
784
785 crypt_params = buffer + sizeof(struct dm_ioctl) + sizeof(struct dm_target_spec);
786 convert_key_to_hex_ascii(master_key, crypt_ftr->keysize, master_key_ascii);
787 sprintf(crypt_params, "%s %s 0 %s 0 %s", crypt_ftr->crypto_type_name,
788 master_key_ascii, real_blk_name, extra_params);
789 crypt_params += strlen(crypt_params) + 1;
790 crypt_params = (char *) (((unsigned long)crypt_params + 7) & ~8); /* Align to an 8 byte boundary */
791 tgt->next = crypt_params - buffer;
792
793 for (i = 0; i < TABLE_LOAD_RETRIES; i++) {
794 if (! ioctl(fd, DM_TABLE_LOAD, io)) {
795 break;
796 }
797 usleep(500000);
798 }
799
800 if (i == TABLE_LOAD_RETRIES) {
801 /* We failed to load the table, return an error */
802 return -1;
803 } else {
804 return i + 1;
805 }
806}
807
808
809static int get_dm_crypt_version(int fd, const char *name, int *version)
810{
811 char buffer[DM_CRYPT_BUF_SIZE];
812 struct dm_ioctl *io;
813 struct dm_target_versions *v;
814 int i;
815
816 io = (struct dm_ioctl *) buffer;
817
818 ioctl_init(io, DM_CRYPT_BUF_SIZE, name, 0);
819
820 if (ioctl(fd, DM_LIST_VERSIONS, io)) {
821 return -1;
822 }
823
824 /* Iterate over the returned versions, looking for name of "crypt".
825 * When found, get and return the version.
826 */
827 v = (struct dm_target_versions *) &buffer[sizeof(struct dm_ioctl)];
828 while (v->next) {
829 if (! strcmp(v->name, "crypt")) {
830 /* We found the crypt driver, return the version, and get out */
831 version[0] = v->version[0];
832 version[1] = v->version[1];
833 version[2] = v->version[2];
834 return 0;
835 }
836 v = (struct dm_target_versions *)(((char *)v) + v->next);
837 }
838
839 return -1;
840}
841
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800842static int create_crypto_blk_dev(struct crypt_mnt_ftr *crypt_ftr, unsigned char *master_key,
Ken Sumrall29d8da82011-05-18 17:20:07 -0700843 char *real_blk_name, char *crypto_blk_name, const char *name)
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800844{
845 char buffer[DM_CRYPT_BUF_SIZE];
846 char master_key_ascii[129]; /* Large enough to hold 512 bit key and null */
847 char *crypt_params;
848 struct dm_ioctl *io;
849 struct dm_target_spec *tgt;
850 unsigned int minor;
851 int fd;
Ken Sumralle919efe2012-09-29 17:07:41 -0700852 int i;
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800853 int retval = -1;
Ken Sumralldb5e0262013-02-05 17:39:48 -0800854 int version[3];
855 char *extra_params;
856 int load_count;
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800857
858 if ((fd = open("/dev/device-mapper", O_RDWR)) < 0 ) {
859 SLOGE("Cannot open device-mapper\n");
860 goto errout;
861 }
862
863 io = (struct dm_ioctl *) buffer;
864
865 ioctl_init(io, DM_CRYPT_BUF_SIZE, name, 0);
866 if (ioctl(fd, DM_DEV_CREATE, io)) {
867 SLOGE("Cannot create dm-crypt device\n");
868 goto errout;
869 }
870
871 /* Get the device status, in particular, the name of it's device file */
872 ioctl_init(io, DM_CRYPT_BUF_SIZE, name, 0);
873 if (ioctl(fd, DM_DEV_STATUS, io)) {
874 SLOGE("Cannot retrieve dm-crypt device status\n");
875 goto errout;
876 }
877 minor = (io->dev & 0xff) | ((io->dev >> 12) & 0xfff00);
878 snprintf(crypto_blk_name, MAXPATHLEN, "/dev/block/dm-%u", minor);
879
Ken Sumralldb5e0262013-02-05 17:39:48 -0800880 extra_params = "";
881 if (! get_dm_crypt_version(fd, name, version)) {
882 /* Support for allow_discards was added in version 1.11.0 */
883 if ((version[0] >= 2) ||
884 ((version[0] == 1) && (version[1] >= 11))) {
885 extra_params = "1 allow_discards";
886 SLOGI("Enabling support for allow_discards in dmcrypt.\n");
887 }
Ken Sumralle919efe2012-09-29 17:07:41 -0700888 }
889
Ken Sumralldb5e0262013-02-05 17:39:48 -0800890 load_count = load_crypto_mapping_table(crypt_ftr, master_key, real_blk_name, name,
891 fd, extra_params);
892 if (load_count < 0) {
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800893 SLOGE("Cannot load dm-crypt mapping table.\n");
894 goto errout;
Ken Sumralldb5e0262013-02-05 17:39:48 -0800895 } else if (load_count > 1) {
896 SLOGI("Took %d tries to load dmcrypt table.\n", load_count);
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800897 }
898
899 /* Resume this device to activate it */
Ken Sumralldb5e0262013-02-05 17:39:48 -0800900 ioctl_init(io, DM_CRYPT_BUF_SIZE, name, 0);
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800901
902 if (ioctl(fd, DM_DEV_SUSPEND, io)) {
903 SLOGE("Cannot resume the dm-crypt device\n");
904 goto errout;
905 }
906
907 /* We made it here with no errors. Woot! */
908 retval = 0;
909
910errout:
911 close(fd); /* If fd is <0 from a failed open call, it's safe to just ignore the close error */
912
913 return retval;
914}
915
Ken Sumrall29d8da82011-05-18 17:20:07 -0700916static int delete_crypto_blk_dev(char *name)
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800917{
918 int fd;
919 char buffer[DM_CRYPT_BUF_SIZE];
920 struct dm_ioctl *io;
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800921 int retval = -1;
922
923 if ((fd = open("/dev/device-mapper", O_RDWR)) < 0 ) {
924 SLOGE("Cannot open device-mapper\n");
925 goto errout;
926 }
927
928 io = (struct dm_ioctl *) buffer;
929
930 ioctl_init(io, DM_CRYPT_BUF_SIZE, name, 0);
931 if (ioctl(fd, DM_DEV_REMOVE, io)) {
932 SLOGE("Cannot remove dm-crypt device\n");
933 goto errout;
934 }
935
936 /* We made it here with no errors. Woot! */
937 retval = 0;
938
939errout:
940 close(fd); /* If fd is <0 from a failed open call, it's safe to just ignore the close error */
941
942 return retval;
943
944}
945
Paul Lawrence13486032014-02-03 13:28:11 -0800946static int pbkdf2(const char *passwd, unsigned char *salt,
Paul Lawrencef4faa572014-01-29 13:31:03 -0800947 unsigned char *ikey, void *params UNUSED)
948{
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800949 /* Turn the password into a key and IV that can decrypt the master key */
Paul Lawrencef4faa572014-01-29 13:31:03 -0800950 unsigned int keysize;
951 char* master_key = (char*)convert_hex_ascii_to_key(passwd, &keysize);
952 if (!master_key) return -1;
953 PKCS5_PBKDF2_HMAC_SHA1(master_key, keysize, salt, SALT_LEN,
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800954 HASH_COUNT, KEY_LEN_BYTES+IV_LEN_BYTES, ikey);
Paul Lawrencef4faa572014-01-29 13:31:03 -0800955
956 free (master_key);
957 return 0;
Ken Sumrall8ddbe402011-01-17 15:26:29 -0800958}
959
Paul Lawrence13486032014-02-03 13:28:11 -0800960static int scrypt(const char *passwd, unsigned char *salt,
Paul Lawrencef4faa572014-01-29 13:31:03 -0800961 unsigned char *ikey, void *params)
962{
Kenny Rootc4c70f12013-06-14 12:11:38 -0700963 struct crypt_mnt_ftr *ftr = (struct crypt_mnt_ftr *) params;
964
965 int N = 1 << ftr->N_factor;
966 int r = 1 << ftr->r_factor;
967 int p = 1 << ftr->p_factor;
968
969 /* Turn the password into a key and IV that can decrypt the master key */
Paul Lawrencef4faa572014-01-29 13:31:03 -0800970 unsigned int keysize;
971 unsigned char* master_key = convert_hex_ascii_to_key(passwd, &keysize);
972 if (!master_key) return -1;
973 crypto_scrypt(master_key, keysize, salt, SALT_LEN, N, r, p, ikey,
Kenny Rootc4c70f12013-06-14 12:11:38 -0700974 KEY_LEN_BYTES + IV_LEN_BYTES);
Paul Lawrencef4faa572014-01-29 13:31:03 -0800975
976 free (master_key);
977 return 0;
Kenny Rootc4c70f12013-06-14 12:11:38 -0700978}
979
Paul Lawrence13486032014-02-03 13:28:11 -0800980static int encrypt_master_key(const char *passwd, unsigned char *salt,
Ken Sumralle8744072011-01-18 22:01:55 -0800981 unsigned char *decrypted_master_key,
Kenny Rootc4c70f12013-06-14 12:11:38 -0700982 unsigned char *encrypted_master_key,
983 struct crypt_mnt_ftr *crypt_ftr)
Ken Sumrall8ddbe402011-01-17 15:26:29 -0800984{
985 unsigned char ikey[32+32] = { 0 }; /* Big enough to hold a 256 bit key and 256 bit IV */
986 EVP_CIPHER_CTX e_ctx;
987 int encrypted_len, final_len;
988
989 /* Turn the password into a key and IV that can decrypt the master key */
Kenny Rootc4c70f12013-06-14 12:11:38 -0700990 get_device_scrypt_params(crypt_ftr);
Paul Lawrencef4faa572014-01-29 13:31:03 -0800991 if (scrypt(passwd, salt, ikey, crypt_ftr)) {
992 SLOGE("scrypt failed");
993 return -1;
994 }
Kenny Rootc4c70f12013-06-14 12:11:38 -0700995
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800996 /* Initialize the decryption engine */
997 if (! EVP_EncryptInit(&e_ctx, EVP_aes_128_cbc(), ikey, ikey+KEY_LEN_BYTES)) {
998 SLOGE("EVP_EncryptInit failed\n");
999 return -1;
1000 }
1001 EVP_CIPHER_CTX_set_padding(&e_ctx, 0); /* Turn off padding as our data is block aligned */
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001002
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001003 /* Encrypt the master key */
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001004 if (! EVP_EncryptUpdate(&e_ctx, encrypted_master_key, &encrypted_len,
1005 decrypted_master_key, KEY_LEN_BYTES)) {
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001006 SLOGE("EVP_EncryptUpdate failed\n");
1007 return -1;
1008 }
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001009 if (! EVP_EncryptFinal(&e_ctx, encrypted_master_key + encrypted_len, &final_len)) {
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001010 SLOGE("EVP_EncryptFinal failed\n");
1011 return -1;
1012 }
1013
1014 if (encrypted_len + final_len != KEY_LEN_BYTES) {
1015 SLOGE("EVP_Encryption length check failed with %d, %d bytes\n", encrypted_len, final_len);
1016 return -1;
1017 } else {
1018 return 0;
1019 }
1020}
1021
JP Abgrall7bdfa522013-11-15 13:42:56 -08001022static int decrypt_master_key_aux(char *passwd, unsigned char *salt,
Ken Sumralle8744072011-01-18 22:01:55 -08001023 unsigned char *encrypted_master_key,
Kenny Rootc4c70f12013-06-14 12:11:38 -07001024 unsigned char *decrypted_master_key,
1025 kdf_func kdf, void *kdf_params)
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001026{
1027 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 -08001028 EVP_CIPHER_CTX d_ctx;
1029 int decrypted_len, final_len;
1030
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001031 /* Turn the password into a key and IV that can decrypt the master key */
Paul Lawrencef4faa572014-01-29 13:31:03 -08001032 if (kdf(passwd, salt, ikey, kdf_params)) {
1033 SLOGE("kdf failed");
1034 return -1;
1035 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001036
1037 /* Initialize the decryption engine */
1038 if (! EVP_DecryptInit(&d_ctx, EVP_aes_128_cbc(), ikey, ikey+KEY_LEN_BYTES)) {
1039 return -1;
1040 }
1041 EVP_CIPHER_CTX_set_padding(&d_ctx, 0); /* Turn off padding as our data is block aligned */
1042 /* Decrypt the master key */
1043 if (! EVP_DecryptUpdate(&d_ctx, decrypted_master_key, &decrypted_len,
1044 encrypted_master_key, KEY_LEN_BYTES)) {
1045 return -1;
1046 }
1047 if (! EVP_DecryptFinal(&d_ctx, decrypted_master_key + decrypted_len, &final_len)) {
1048 return -1;
1049 }
1050
1051 if (decrypted_len + final_len != KEY_LEN_BYTES) {
1052 return -1;
1053 } else {
1054 return 0;
1055 }
1056}
1057
Kenny Rootc4c70f12013-06-14 12:11:38 -07001058static void get_kdf_func(struct crypt_mnt_ftr *ftr, kdf_func *kdf, void** kdf_params)
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001059{
Kenny Rootc4c70f12013-06-14 12:11:38 -07001060 if (ftr->kdf_type == KDF_SCRYPT) {
1061 *kdf = scrypt;
1062 *kdf_params = ftr;
1063 } else {
1064 *kdf = pbkdf2;
1065 *kdf_params = NULL;
1066 }
1067}
1068
JP Abgrall7bdfa522013-11-15 13:42:56 -08001069static int decrypt_master_key(char *passwd, unsigned char *decrypted_master_key,
Kenny Rootc4c70f12013-06-14 12:11:38 -07001070 struct crypt_mnt_ftr *crypt_ftr)
1071{
1072 kdf_func kdf;
1073 void *kdf_params;
1074 int ret;
1075
1076 get_kdf_func(crypt_ftr, &kdf, &kdf_params);
JP Abgrall7bdfa522013-11-15 13:42:56 -08001077 ret = decrypt_master_key_aux(passwd, crypt_ftr->salt, crypt_ftr->master_key, decrypted_master_key, kdf,
Kenny Rootc4c70f12013-06-14 12:11:38 -07001078 kdf_params);
1079 if (ret != 0) {
1080 SLOGW("failure decrypting master key");
Kenny Rootc4c70f12013-06-14 12:11:38 -07001081 }
1082
1083 return ret;
1084}
1085
1086static int create_encrypted_random_key(char *passwd, unsigned char *master_key, unsigned char *salt,
1087 struct crypt_mnt_ftr *crypt_ftr) {
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001088 int fd;
Ken Sumralle8744072011-01-18 22:01:55 -08001089 unsigned char key_buf[KEY_LEN_BYTES];
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001090 EVP_CIPHER_CTX e_ctx;
1091 int encrypted_len, final_len;
1092
1093 /* Get some random bits for a key */
1094 fd = open("/dev/urandom", O_RDONLY);
Ken Sumralle8744072011-01-18 22:01:55 -08001095 read(fd, key_buf, sizeof(key_buf));
1096 read(fd, salt, SALT_LEN);
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001097 close(fd);
1098
1099 /* Now encrypt it with the password */
Kenny Rootc4c70f12013-06-14 12:11:38 -07001100 return encrypt_master_key(passwd, salt, key_buf, master_key, crypt_ftr);
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001101}
1102
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001103static int wait_and_unmount(char *mountpoint)
1104{
1105 int i, rc;
Ken Sumrall2eaf7132011-01-14 12:45:48 -08001106#define WAIT_UNMOUNT_COUNT 20
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001107
1108 /* Now umount the tmpfs filesystem */
1109 for (i=0; i<WAIT_UNMOUNT_COUNT; i++) {
1110 if (umount(mountpoint)) {
Ken Sumrall29d8da82011-05-18 17:20:07 -07001111 if (errno == EINVAL) {
1112 /* EINVAL is returned if the directory is not a mountpoint,
1113 * i.e. there is no filesystem mounted there. So just get out.
1114 */
1115 break;
1116 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001117 sleep(1);
1118 i++;
1119 } else {
1120 break;
1121 }
1122 }
1123
1124 if (i < WAIT_UNMOUNT_COUNT) {
1125 SLOGD("unmounting %s succeeded\n", mountpoint);
1126 rc = 0;
1127 } else {
1128 SLOGE("unmounting %s failed\n", mountpoint);
1129 rc = -1;
1130 }
1131
1132 return rc;
1133}
1134
Ken Sumrallc5872692013-05-14 15:26:31 -07001135#define DATA_PREP_TIMEOUT 200
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001136static int prep_data_fs(void)
1137{
1138 int i;
1139
1140 /* Do the prep of the /data filesystem */
1141 property_set("vold.post_fs_data_done", "0");
1142 property_set("vold.decrypt", "trigger_post_fs_data");
1143 SLOGD("Just triggered post_fs_data\n");
1144
Ken Sumrallc5872692013-05-14 15:26:31 -07001145 /* Wait a max of 50 seconds, hopefully it takes much less */
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001146 for (i=0; i<DATA_PREP_TIMEOUT; i++) {
Ken Sumrall29d8da82011-05-18 17:20:07 -07001147 char p[PROPERTY_VALUE_MAX];
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001148
1149 property_get("vold.post_fs_data_done", p, "0");
1150 if (*p == '1') {
1151 break;
1152 } else {
1153 usleep(250000);
1154 }
1155 }
1156 if (i == DATA_PREP_TIMEOUT) {
1157 /* Ugh, we failed to prep /data in time. Bail. */
Ken Sumrallc5872692013-05-14 15:26:31 -07001158 SLOGE("post_fs_data timed out!\n");
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001159 return -1;
1160 } else {
1161 SLOGD("post_fs_data done\n");
1162 return 0;
1163 }
1164}
1165
Paul Lawrencef4faa572014-01-29 13:31:03 -08001166static int cryptfs_restart_internal(int restart_main)
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001167{
1168 char fs_type[32];
1169 char real_blkdev[MAXPATHLEN];
Ken Sumrall6864b7e2011-01-14 15:20:02 -08001170 char crypto_blkdev[MAXPATHLEN];
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001171 char fs_options[256];
1172 unsigned long mnt_flags;
1173 struct stat statbuf;
1174 int rc = -1, i;
Ken Sumrall0cc16632011-01-18 20:32:26 -08001175 static int restart_successful = 0;
1176
1177 /* Validate that it's OK to call this routine */
Jason parks70a4b3f2011-01-28 10:10:47 -06001178 if (! master_key_saved) {
Ken Sumrall0cc16632011-01-18 20:32:26 -08001179 SLOGE("Encrypted filesystem not validated, aborting");
1180 return -1;
1181 }
1182
1183 if (restart_successful) {
1184 SLOGE("System already restarted with encrypted disk, aborting");
1185 return -1;
1186 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001187
Paul Lawrencef4faa572014-01-29 13:31:03 -08001188 if (restart_main) {
1189 /* Here is where we shut down the framework. The init scripts
1190 * start all services in one of three classes: core, main or late_start.
1191 * On boot, we start core and main. Now, we stop main, but not core,
1192 * as core includes vold and a few other really important things that
1193 * we need to keep running. Once main has stopped, we should be able
1194 * to umount the tmpfs /data, then mount the encrypted /data.
1195 * We then restart the class main, and also the class late_start.
1196 * At the moment, I've only put a few things in late_start that I know
1197 * are not needed to bring up the framework, and that also cause problems
1198 * with unmounting the tmpfs /data, but I hope to add add more services
1199 * to the late_start class as we optimize this to decrease the delay
1200 * till the user is asked for the password to the filesystem.
1201 */
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001202
Paul Lawrencef4faa572014-01-29 13:31:03 -08001203 /* The init files are setup to stop the class main when vold.decrypt is
1204 * set to trigger_reset_main.
1205 */
1206 property_set("vold.decrypt", "trigger_reset_main");
1207 SLOGD("Just asked init to shut down class main\n");
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001208
Paul Lawrencef4faa572014-01-29 13:31:03 -08001209 /* Ugh, shutting down the framework is not synchronous, so until it
1210 * can be fixed, this horrible hack will wait a moment for it all to
1211 * shut down before proceeding. Without it, some devices cannot
1212 * restart the graphics services.
1213 */
1214 sleep(2);
1215 }
Ken Sumrall9dedfd42012-10-09 14:16:59 -07001216
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001217 /* Now that the framework is shutdown, we should be able to umount()
1218 * the tmpfs filesystem, and mount the real one.
1219 */
1220
Ken Sumrall6864b7e2011-01-14 15:20:02 -08001221 property_get("ro.crypto.fs_crypto_blkdev", crypto_blkdev, "");
1222 if (strlen(crypto_blkdev) == 0) {
1223 SLOGE("fs_crypto_blkdev not set\n");
1224 return -1;
1225 }
1226
Ken Sumralle5032c42012-04-01 23:58:44 -07001227 if (! (rc = wait_and_unmount(DATA_MNT_POINT)) ) {
Doug Zongker6fd57712013-12-17 09:43:23 -08001228 /* If ro.crypto.readonly is set to 1, mount the decrypted
1229 * filesystem readonly. This is used when /data is mounted by
1230 * recovery mode.
1231 */
1232 char ro_prop[PROPERTY_VALUE_MAX];
1233 property_get("ro.crypto.readonly", ro_prop, "");
1234 if (strlen(ro_prop) > 0 && atoi(ro_prop)) {
1235 struct fstab_rec* rec = fs_mgr_get_entry_for_mount_point(fstab, DATA_MNT_POINT);
1236 rec->flags |= MS_RDONLY;
1237 }
1238
Ken Sumralle5032c42012-04-01 23:58:44 -07001239 /* If that succeeded, then mount the decrypted filesystem */
Ken Sumrall56ad03c2013-02-13 13:00:19 -08001240 fs_mgr_do_mount(fstab, DATA_MNT_POINT, crypto_blkdev, 0);
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001241
Ken Sumralle5032c42012-04-01 23:58:44 -07001242 property_set("vold.decrypt", "trigger_load_persist_props");
1243 /* Create necessary paths on /data */
1244 if (prep_data_fs()) {
1245 return -1;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001246 }
Ken Sumralle5032c42012-04-01 23:58:44 -07001247
1248 /* startup service classes main and late_start */
1249 property_set("vold.decrypt", "trigger_restart_framework");
1250 SLOGD("Just triggered restart_framework\n");
1251
1252 /* Give it a few moments to get started */
1253 sleep(1);
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001254 }
1255
Ken Sumrall0cc16632011-01-18 20:32:26 -08001256 if (rc == 0) {
1257 restart_successful = 1;
1258 }
1259
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001260 return rc;
1261}
1262
Paul Lawrencef4faa572014-01-29 13:31:03 -08001263int cryptfs_restart(void)
1264{
1265 /* Call internal implementation forcing a restart of main service group */
1266 return cryptfs_restart_internal(1);
1267}
1268
Mark Salyzyn3e971272014-01-21 13:27:04 -08001269static int do_crypto_complete(char *mount_point UNUSED)
Ken Sumrall7f7dbaa2011-02-01 15:46:41 -08001270{
1271 struct crypt_mnt_ftr crypt_ftr;
Ken Sumrall29d8da82011-05-18 17:20:07 -07001272 char encrypted_state[PROPERTY_VALUE_MAX];
Ken Sumralle1a45852011-12-14 21:24:27 -08001273 char key_loc[PROPERTY_VALUE_MAX];
Ken Sumrall7f7dbaa2011-02-01 15:46:41 -08001274
1275 property_get("ro.crypto.state", encrypted_state, "");
1276 if (strcmp(encrypted_state, "encrypted") ) {
1277 SLOGE("not running with encryption, aborting");
1278 return 1;
1279 }
1280
Ken Sumrall160b4d62013-04-22 12:15:39 -07001281 if (get_crypt_ftr_and_key(&crypt_ftr)) {
Ken Sumrall56ad03c2013-02-13 13:00:19 -08001282 fs_mgr_get_crypt_info(fstab, key_loc, 0, sizeof(key_loc));
Ken Sumralle5032c42012-04-01 23:58:44 -07001283
Ken Sumralle1a45852011-12-14 21:24:27 -08001284 /*
1285 * Only report this error if key_loc is a file and it exists.
1286 * If the device was never encrypted, and /data is not mountable for
1287 * some reason, returning 1 should prevent the UI from presenting the
1288 * a "enter password" screen, or worse, a "press button to wipe the
1289 * device" screen.
1290 */
1291 if ((key_loc[0] == '/') && (access("key_loc", F_OK) == -1)) {
1292 SLOGE("master key file does not exist, aborting");
1293 return 1;
1294 } else {
1295 SLOGE("Error getting crypt footer and key\n");
1296 return -1;
1297 }
Ken Sumrall7f7dbaa2011-02-01 15:46:41 -08001298 }
1299
1300 if (crypt_ftr.flags & CRYPT_ENCRYPTION_IN_PROGRESS) {
1301 SLOGE("Encryption process didn't finish successfully\n");
1302 return -2; /* -2 is the clue to the UI that there is no usable data on the disk,
1303 * and give the user an option to wipe the disk */
1304 }
1305
1306 /* We passed the test! We shall diminish, and return to the west */
1307 return 0;
1308}
1309
Paul Lawrencef4faa572014-01-29 13:31:03 -08001310static int test_mount_encrypted_fs(struct crypt_mnt_ftr* crypt_ftr,
1311 char *passwd, char *mount_point, char *label)
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001312{
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001313 /* Allocate enough space for a 256 bit key, but we may use less */
Ken Sumrall160b4d62013-04-22 12:15:39 -07001314 unsigned char decrypted_master_key[32];
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001315 char crypto_blkdev[MAXPATHLEN];
1316 char real_blkdev[MAXPATHLEN];
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001317 char tmp_mount_point[64];
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001318 unsigned int orig_failed_decrypt_count;
1319 int rc;
Kenny Rootc4c70f12013-06-14 12:11:38 -07001320 kdf_func kdf;
1321 void *kdf_params;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001322
Paul Lawrencef4faa572014-01-29 13:31:03 -08001323 SLOGD("crypt_ftr->fs_size = %lld\n", crypt_ftr->fs_size);
1324 orig_failed_decrypt_count = crypt_ftr->failed_decrypt_count;
Ken Sumrall0cc16632011-01-18 20:32:26 -08001325
Paul Lawrencef4faa572014-01-29 13:31:03 -08001326 if (! (crypt_ftr->flags & CRYPT_MNT_KEY_UNENCRYPTED) ) {
1327 if (decrypt_master_key(passwd, decrypted_master_key, crypt_ftr)) {
JP Abgrall7bdfa522013-11-15 13:42:56 -08001328 SLOGE("Failed to decrypt master key\n");
1329 return -1;
1330 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001331 }
1332
Paul Lawrencef4faa572014-01-29 13:31:03 -08001333 fs_mgr_get_crypt_info(fstab, 0, real_blkdev, sizeof(real_blkdev));
1334
1335 if (create_crypto_blk_dev(crypt_ftr, decrypted_master_key,
1336 real_blkdev, crypto_blkdev, label)) {
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001337 SLOGE("Error creating decrypted block device\n");
1338 return -1;
1339 }
1340
Alex Klyubin707795a2013-05-10 15:17:07 -07001341 /* If init detects an encrypted filesystem, it writes a file for each such
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001342 * encrypted fs into the tmpfs /data filesystem, and then the framework finds those
1343 * files and passes that data to me */
1344 /* Create a tmp mount point to try mounting the decryptd fs
1345 * Since we're here, the mount_point should be a tmpfs filesystem, so make
1346 * a directory in it to test mount the decrypted filesystem.
1347 */
1348 sprintf(tmp_mount_point, "%s/tmp_mnt", mount_point);
1349 mkdir(tmp_mount_point, 0755);
Ken Sumrall56ad03c2013-02-13 13:00:19 -08001350 if (fs_mgr_do_mount(fstab, DATA_MNT_POINT, crypto_blkdev, tmp_mount_point)) {
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001351 SLOGE("Error temp mounting decrypted block device\n");
Ken Sumrall29d8da82011-05-18 17:20:07 -07001352 delete_crypto_blk_dev(label);
Paul Lawrencef4faa572014-01-29 13:31:03 -08001353 crypt_ftr->failed_decrypt_count++;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001354 } else {
1355 /* Success, so just umount and we'll mount it properly when we restart
1356 * the framework.
1357 */
1358 umount(tmp_mount_point);
Paul Lawrencef4faa572014-01-29 13:31:03 -08001359 crypt_ftr->failed_decrypt_count = 0;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001360 }
1361
Paul Lawrencef4faa572014-01-29 13:31:03 -08001362 if (orig_failed_decrypt_count != crypt_ftr->failed_decrypt_count) {
1363 put_crypt_ftr_and_key(crypt_ftr);
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001364 }
1365
Paul Lawrencef4faa572014-01-29 13:31:03 -08001366 if (crypt_ftr->failed_decrypt_count) {
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001367 /* We failed to mount the device, so return an error */
Paul Lawrencef4faa572014-01-29 13:31:03 -08001368 rc = crypt_ftr->failed_decrypt_count;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001369
1370 } else {
Ken Sumrall6864b7e2011-01-14 15:20:02 -08001371 /* Woot! Success! Save the name of the crypto block device
1372 * so we can mount it when restarting the framework.
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001373 */
Ken Sumrall6864b7e2011-01-14 15:20:02 -08001374 property_set("ro.crypto.fs_crypto_blkdev", crypto_blkdev);
Jason parks70a4b3f2011-01-28 10:10:47 -06001375
1376 /* Also save a the master key so we can reencrypted the key
1377 * the key when we want to change the password on it.
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001378 */
Jason parks70a4b3f2011-01-28 10:10:47 -06001379 memcpy(saved_master_key, decrypted_master_key, KEY_LEN_BYTES);
Ken Sumrall3ad90722011-10-04 20:38:29 -07001380 saved_mount_point = strdup(mount_point);
Jason parks70a4b3f2011-01-28 10:10:47 -06001381 master_key_saved = 1;
JP Abgrall7bdfa522013-11-15 13:42:56 -08001382 SLOGD("%s(): Master key saved\n", __FUNCTION__);
Ken Sumrall6864b7e2011-01-14 15:20:02 -08001383 rc = 0;
JP Abgrall7bdfa522013-11-15 13:42:56 -08001384 /*
1385 * Upgrade if we're not using the latest KDF.
1386 */
Paul Lawrencef4faa572014-01-29 13:31:03 -08001387 if (crypt_ftr->kdf_type != KDF_SCRYPT) {
1388 crypt_ftr->kdf_type = KDF_SCRYPT;
1389 rc = encrypt_master_key(passwd, crypt_ftr->salt, saved_master_key,
1390 crypt_ftr->master_key, crypt_ftr);
JP Abgrall7bdfa522013-11-15 13:42:56 -08001391 if (!rc) {
Paul Lawrencef4faa572014-01-29 13:31:03 -08001392 rc = put_crypt_ftr_and_key(crypt_ftr);
JP Abgrall7bdfa522013-11-15 13:42:56 -08001393 }
1394 SLOGD("Key Derivation Function upgrade: rc=%d\n", rc);
1395 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001396 }
1397
1398 return rc;
1399}
1400
Ken Sumrall0b8b5972011-08-31 16:14:23 -07001401/* Called by vold when it wants to undo the crypto mapping of a volume it
1402 * manages. This is usually in response to a factory reset, when we want
1403 * to undo the crypto mapping so the volume is formatted in the clear.
1404 */
1405int cryptfs_revert_volume(const char *label)
1406{
1407 return delete_crypto_blk_dev((char *)label);
1408}
1409
Ken Sumrall29d8da82011-05-18 17:20:07 -07001410/*
1411 * Called by vold when it's asked to mount an encrypted, nonremovable volume.
1412 * Setup a dm-crypt mapping, use the saved master key from
1413 * setting up the /data mapping, and return the new device path.
1414 */
1415int cryptfs_setup_volume(const char *label, int major, int minor,
1416 char *crypto_sys_path, unsigned int max_path,
1417 int *new_major, int *new_minor)
1418{
1419 char real_blkdev[MAXPATHLEN], crypto_blkdev[MAXPATHLEN];
1420 struct crypt_mnt_ftr sd_crypt_ftr;
Ken Sumrall29d8da82011-05-18 17:20:07 -07001421 struct stat statbuf;
1422 int nr_sec, fd;
1423
1424 sprintf(real_blkdev, "/dev/block/vold/%d:%d", major, minor);
1425
Ken Sumrall160b4d62013-04-22 12:15:39 -07001426 get_crypt_ftr_and_key(&sd_crypt_ftr);
Ken Sumrall29d8da82011-05-18 17:20:07 -07001427
1428 /* Update the fs_size field to be the size of the volume */
1429 fd = open(real_blkdev, O_RDONLY);
1430 nr_sec = get_blkdev_size(fd);
1431 close(fd);
1432 if (nr_sec == 0) {
1433 SLOGE("Cannot get size of volume %s\n", real_blkdev);
1434 return -1;
1435 }
1436
1437 sd_crypt_ftr.fs_size = nr_sec;
1438 create_crypto_blk_dev(&sd_crypt_ftr, saved_master_key, real_blkdev,
1439 crypto_blkdev, label);
1440
1441 stat(crypto_blkdev, &statbuf);
1442 *new_major = MAJOR(statbuf.st_rdev);
1443 *new_minor = MINOR(statbuf.st_rdev);
1444
1445 /* Create path to sys entry for this block device */
1446 snprintf(crypto_sys_path, max_path, "/devices/virtual/block/%s", strrchr(crypto_blkdev, '/')+1);
1447
1448 return 0;
1449}
1450
Ken Sumrall7f7dbaa2011-02-01 15:46:41 -08001451int cryptfs_crypto_complete(void)
1452{
1453 return do_crypto_complete("/data");
1454}
1455
Paul Lawrencef4faa572014-01-29 13:31:03 -08001456int check_unmounted_and_get_ftr(struct crypt_mnt_ftr* crypt_ftr)
1457{
1458 char encrypted_state[PROPERTY_VALUE_MAX];
1459 property_get("ro.crypto.state", encrypted_state, "");
1460 if ( master_key_saved || strcmp(encrypted_state, "encrypted") ) {
1461 SLOGE("encrypted fs already validated or not running with encryption,"
1462 " aborting");
1463 return -1;
1464 }
1465
1466 if (get_crypt_ftr_and_key(crypt_ftr)) {
1467 SLOGE("Error getting crypt footer and key");
1468 return -1;
1469 }
1470
1471 return 0;
1472}
1473
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001474int cryptfs_check_passwd(char *passwd)
1475{
Paul Lawrencef4faa572014-01-29 13:31:03 -08001476 struct crypt_mnt_ftr crypt_ftr;
1477 int rc;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001478
Paul Lawrencef4faa572014-01-29 13:31:03 -08001479 rc = check_unmounted_and_get_ftr(&crypt_ftr);
1480 if (rc)
1481 return rc;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001482
Paul Lawrencef4faa572014-01-29 13:31:03 -08001483 rc = test_mount_encrypted_fs(&crypt_ftr, passwd,
1484 DATA_MNT_POINT, "userdata");
Paul Lawrence684dbdf2014-02-07 12:07:22 -08001485
1486 if (rc == 0 && crypt_ftr.crypt_type != CRYPT_TYPE_DEFAULT) {
Paul Lawrence399317e2014-03-10 13:20:50 -07001487 cryptfs_clear_password();
1488 password = strdup(passwd);
1489 struct timespec now;
1490 clock_gettime(CLOCK_BOOTTIME, &now);
1491 password_expiry_time = now.tv_sec + password_max_age_seconds;
Paul Lawrence684dbdf2014-02-07 12:07:22 -08001492 }
1493
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001494 return rc;
1495}
1496
Ken Sumrall3ad90722011-10-04 20:38:29 -07001497int cryptfs_verify_passwd(char *passwd)
1498{
1499 struct crypt_mnt_ftr crypt_ftr;
1500 /* Allocate enough space for a 256 bit key, but we may use less */
Ken Sumrall160b4d62013-04-22 12:15:39 -07001501 unsigned char decrypted_master_key[32];
Ken Sumrall3ad90722011-10-04 20:38:29 -07001502 char encrypted_state[PROPERTY_VALUE_MAX];
1503 int rc;
1504
1505 property_get("ro.crypto.state", encrypted_state, "");
1506 if (strcmp(encrypted_state, "encrypted") ) {
1507 SLOGE("device not encrypted, aborting");
1508 return -2;
1509 }
1510
1511 if (!master_key_saved) {
1512 SLOGE("encrypted fs not yet mounted, aborting");
1513 return -1;
1514 }
1515
1516 if (!saved_mount_point) {
1517 SLOGE("encrypted fs failed to save mount point, aborting");
1518 return -1;
1519 }
1520
Ken Sumrall160b4d62013-04-22 12:15:39 -07001521 if (get_crypt_ftr_and_key(&crypt_ftr)) {
Ken Sumrall3ad90722011-10-04 20:38:29 -07001522 SLOGE("Error getting crypt footer and key\n");
1523 return -1;
1524 }
1525
1526 if (crypt_ftr.flags & CRYPT_MNT_KEY_UNENCRYPTED) {
1527 /* If the device has no password, then just say the password is valid */
1528 rc = 0;
1529 } else {
JP Abgrall7bdfa522013-11-15 13:42:56 -08001530 decrypt_master_key(passwd, decrypted_master_key, &crypt_ftr);
Ken Sumrall3ad90722011-10-04 20:38:29 -07001531 if (!memcmp(decrypted_master_key, saved_master_key, crypt_ftr.keysize)) {
1532 /* They match, the password is correct */
1533 rc = 0;
1534 } else {
1535 /* If incorrect, sleep for a bit to prevent dictionary attacks */
1536 sleep(1);
1537 rc = 1;
1538 }
1539 }
1540
1541 return rc;
1542}
1543
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001544/* Initialize a crypt_mnt_ftr structure. The keysize is
1545 * defaulted to 16 bytes, and the filesystem size to 0.
1546 * Presumably, at a minimum, the caller will update the
1547 * filesystem size and crypto_type_name after calling this function.
1548 */
1549static void cryptfs_init_crypt_mnt_ftr(struct crypt_mnt_ftr *ftr)
1550{
Ken Sumrall160b4d62013-04-22 12:15:39 -07001551 off64_t off;
1552
1553 memset(ftr, 0, sizeof(struct crypt_mnt_ftr));
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001554 ftr->magic = CRYPT_MNT_MAGIC;
Kenny Rootc96a5f82013-06-14 12:08:28 -07001555 ftr->major_version = CURRENT_MAJOR_VERSION;
1556 ftr->minor_version = CURRENT_MINOR_VERSION;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001557 ftr->ftr_size = sizeof(struct crypt_mnt_ftr);
Jason parks70a4b3f2011-01-28 10:10:47 -06001558 ftr->keysize = KEY_LEN_BYTES;
Ken Sumrall160b4d62013-04-22 12:15:39 -07001559
Kenny Rootc4c70f12013-06-14 12:11:38 -07001560 ftr->kdf_type = KDF_SCRYPT;
1561 get_device_scrypt_params(ftr);
1562
Ken Sumrall160b4d62013-04-22 12:15:39 -07001563 ftr->persist_data_size = CRYPT_PERSIST_DATA_SIZE;
1564 if (get_crypt_ftr_info(NULL, &off) == 0) {
1565 ftr->persist_data_offset[0] = off + CRYPT_FOOTER_TO_PERSIST_OFFSET;
1566 ftr->persist_data_offset[1] = off + CRYPT_FOOTER_TO_PERSIST_OFFSET +
1567 ftr->persist_data_size;
1568 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001569}
1570
Ken Sumrall29d8da82011-05-18 17:20:07 -07001571static int cryptfs_enable_wipe(char *crypto_blkdev, off64_t size, int type)
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001572{
Ken Sumralle550f782013-08-20 13:48:23 -07001573 const char *args[10];
1574 char size_str[32]; /* Must be large enough to hold a %lld and null byte */
1575 int num_args;
1576 int status;
1577 int tmp;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001578 int rc = -1;
1579
Ken Sumrall29d8da82011-05-18 17:20:07 -07001580 if (type == EXT4_FS) {
Ken Sumralle550f782013-08-20 13:48:23 -07001581 args[0] = "/system/bin/make_ext4fs";
1582 args[1] = "-a";
1583 args[2] = "/data";
1584 args[3] = "-l";
1585 snprintf(size_str, sizeof(size_str), "%lld", size * 512);
1586 args[4] = size_str;
1587 args[5] = crypto_blkdev;
1588 num_args = 6;
1589 SLOGI("Making empty filesystem with command %s %s %s %s %s %s\n",
1590 args[0], args[1], args[2], args[3], args[4], args[5]);
Ken Sumrall29d8da82011-05-18 17:20:07 -07001591 } else if (type== FAT_FS) {
Ken Sumralle550f782013-08-20 13:48:23 -07001592 args[0] = "/system/bin/newfs_msdos";
1593 args[1] = "-F";
1594 args[2] = "32";
1595 args[3] = "-O";
1596 args[4] = "android";
1597 args[5] = "-c";
1598 args[6] = "8";
1599 args[7] = "-s";
1600 snprintf(size_str, sizeof(size_str), "%lld", size);
1601 args[8] = size_str;
1602 args[9] = crypto_blkdev;
1603 num_args = 10;
1604 SLOGI("Making empty filesystem with command %s %s %s %s %s %s %s %s %s %s\n",
1605 args[0], args[1], args[2], args[3], args[4], args[5],
1606 args[6], args[7], args[8], args[9]);
Ken Sumrall29d8da82011-05-18 17:20:07 -07001607 } else {
1608 SLOGE("cryptfs_enable_wipe(): unknown filesystem type %d\n", type);
1609 return -1;
1610 }
1611
Ken Sumralle550f782013-08-20 13:48:23 -07001612 tmp = android_fork_execvp(num_args, (char **)args, &status, false, true);
1613
1614 if (tmp != 0) {
1615 SLOGE("Error creating empty filesystem on %s due to logwrap error\n", crypto_blkdev);
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001616 } else {
Ken Sumralle550f782013-08-20 13:48:23 -07001617 if (WIFEXITED(status)) {
1618 if (WEXITSTATUS(status)) {
1619 SLOGE("Error creating filesystem on %s, exit status %d ",
1620 crypto_blkdev, WEXITSTATUS(status));
1621 } else {
1622 SLOGD("Successfully created filesystem on %s\n", crypto_blkdev);
1623 rc = 0;
1624 }
1625 } else {
1626 SLOGE("Error creating filesystem on %s, did not exit normally\n", crypto_blkdev);
1627 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001628 }
1629
1630 return rc;
1631}
1632
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001633#define CRYPT_INPLACE_BUFSIZE 4096
1634#define CRYPT_SECTORS_PER_BUFSIZE (CRYPT_INPLACE_BUFSIZE / 512)
Paul Lawrenceae59fe62014-01-21 08:23:27 -08001635
1636/* aligned 32K writes tends to make flash happy.
1637 * SD card association recommends it.
1638 */
1639#define BLOCKS_AT_A_TIME 8
1640
1641struct encryptGroupsData
1642{
1643 int realfd;
1644 int cryptofd;
1645 off64_t numblocks;
1646 off64_t one_pct, cur_pct, new_pct;
1647 off64_t blocks_already_done, tot_numblocks;
1648 char* real_blkdev, * crypto_blkdev;
1649 int count;
1650 off64_t offset;
1651 char* buffer;
1652};
1653
1654static void update_progress(struct encryptGroupsData* data)
1655{
1656 data->blocks_already_done++;
1657 data->new_pct = data->blocks_already_done / data->one_pct;
1658 if (data->new_pct > data->cur_pct) {
1659 char buf[8];
1660 data->cur_pct = data->new_pct;
1661 snprintf(buf, sizeof(buf), "%lld", data->cur_pct);
1662 property_set("vold.encrypt_progress", buf);
1663 }
1664}
1665
1666static int flush_outstanding_data(struct encryptGroupsData* data)
1667{
1668 if (data->count == 0) {
1669 return 0;
1670 }
1671
1672 SLOGV("Copying %d blocks at offset %llx", data->count, data->offset);
1673
1674 if (pread64(data->realfd, data->buffer,
1675 info.block_size * data->count, data->offset)
1676 <= 0) {
1677 SLOGE("Error reading real_blkdev %s for inplace encrypt",
1678 data->real_blkdev);
1679 return -1;
1680 }
1681
1682 if (pwrite64(data->cryptofd, data->buffer,
1683 info.block_size * data->count, data->offset)
1684 <= 0) {
1685 SLOGE("Error writing crypto_blkdev %s for inplace encrypt",
1686 data->crypto_blkdev);
1687 return -1;
1688 }
1689
1690 data->count = 0;
1691 return 0;
1692}
1693
1694static int encrypt_groups(struct encryptGroupsData* data)
1695{
1696 unsigned int i;
1697 u8 *block_bitmap = 0;
1698 unsigned int block;
1699 off64_t ret;
1700 int rc = -1;
1701
1702 data->buffer = malloc(info.block_size * BLOCKS_AT_A_TIME);
1703 if (!data->buffer) {
1704 SLOGE("Failed to allocate crypto buffer");
1705 goto errout;
1706 }
1707
1708 block_bitmap = malloc(info.block_size);
1709 if (!block_bitmap) {
1710 SLOGE("failed to allocate block bitmap");
1711 goto errout;
1712 }
1713
1714 for (i = 0; i < aux_info.groups; ++i) {
1715 SLOGI("Encrypting group %d", i);
1716
1717 u32 first_block = aux_info.first_data_block + i * info.blocks_per_group;
1718 u32 block_count = min(info.blocks_per_group,
1719 aux_info.len_blocks - first_block);
1720
1721 off64_t offset = (u64)info.block_size
1722 * aux_info.bg_desc[i].bg_block_bitmap;
1723
1724 ret = pread64(data->realfd, block_bitmap, info.block_size, offset);
1725 if (ret != (int)info.block_size) {
1726 SLOGE("failed to read all of block group bitmap %d", i);
1727 goto errout;
1728 }
1729
1730 offset = (u64)info.block_size * first_block;
1731
1732 data->count = 0;
1733
1734 for (block = 0; block < block_count; block++) {
1735 update_progress(data);
1736 if (bitmap_get_bit(block_bitmap, block)) {
1737 if (data->count == 0) {
1738 data->offset = offset;
1739 }
1740 data->count++;
1741 } else {
1742 if (flush_outstanding_data(data)) {
1743 goto errout;
1744 }
1745 }
1746
1747 offset += info.block_size;
1748
1749 /* Write data if we are aligned or buffer size reached */
1750 if (offset % (info.block_size * BLOCKS_AT_A_TIME) == 0
1751 || data->count == BLOCKS_AT_A_TIME) {
1752 if (flush_outstanding_data(data)) {
1753 goto errout;
1754 }
1755 }
1756 }
1757 if (flush_outstanding_data(data)) {
1758 goto errout;
1759 }
1760 }
1761
1762 rc = 0;
1763
1764errout:
1765 free(data->buffer);
1766 free(block_bitmap);
1767 return rc;
1768}
1769
1770static int cryptfs_enable_inplace_ext4(char *crypto_blkdev,
1771 char *real_blkdev,
1772 off64_t size,
1773 off64_t *size_already_done,
1774 off64_t tot_size)
1775{
1776 int i;
1777 struct encryptGroupsData data;
1778 int rc = -1;
1779
1780 memset(&data, 0, sizeof(data));
1781 data.real_blkdev = real_blkdev;
1782 data.crypto_blkdev = crypto_blkdev;
1783
1784 if ( (data.realfd = open(real_blkdev, O_RDWR)) < 0) {
1785 SLOGE("Error opening real_blkdev %s for inplace encrypt\n",
1786 real_blkdev);
1787 goto errout;
1788 }
1789
1790 if ( (data.cryptofd = open(crypto_blkdev, O_WRONLY)) < 0) {
1791 SLOGE("Error opening crypto_blkdev %s for inplace encrypt\n",
1792 crypto_blkdev);
1793 goto errout;
1794 }
1795
1796 if (setjmp(setjmp_env)) {
1797 SLOGE("Reading extent caused an exception");
1798 goto errout;
1799 }
1800
1801 if (read_ext(data.realfd, 0) != 0) {
1802 SLOGE("Failed to read extent");
1803 goto errout;
1804 }
1805
1806 data.numblocks = size / CRYPT_SECTORS_PER_BUFSIZE;
1807 data.tot_numblocks = tot_size / CRYPT_SECTORS_PER_BUFSIZE;
1808 data.blocks_already_done = *size_already_done / CRYPT_SECTORS_PER_BUFSIZE;
1809
1810 SLOGI("Encrypting filesystem in place...");
1811
1812 data.one_pct = data.tot_numblocks / 100;
1813 data.cur_pct = 0;
1814
1815 rc = encrypt_groups(&data);
1816 if (rc) {
1817 SLOGE("Error encrypting groups");
1818 goto errout;
1819 }
1820
1821 *size_already_done += size;
1822 rc = 0;
1823
1824errout:
1825 close(data.realfd);
1826 close(data.cryptofd);
1827
1828 return rc;
1829}
1830
1831static int cryptfs_enable_inplace_full(char *crypto_blkdev, char *real_blkdev,
1832 off64_t size, off64_t *size_already_done,
1833 off64_t tot_size)
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001834{
1835 int realfd, cryptofd;
1836 char *buf[CRYPT_INPLACE_BUFSIZE];
1837 int rc = -1;
1838 off64_t numblocks, i, remainder;
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001839 off64_t one_pct, cur_pct, new_pct;
Ken Sumrall29d8da82011-05-18 17:20:07 -07001840 off64_t blocks_already_done, tot_numblocks;
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001841
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001842 if ( (realfd = open(real_blkdev, O_RDONLY)) < 0) {
1843 SLOGE("Error opening real_blkdev %s for inplace encrypt\n", real_blkdev);
1844 return -1;
1845 }
1846
1847 if ( (cryptofd = open(crypto_blkdev, O_WRONLY)) < 0) {
1848 SLOGE("Error opening crypto_blkdev %s for inplace encrypt\n", crypto_blkdev);
1849 close(realfd);
1850 return -1;
1851 }
1852
1853 /* This is pretty much a simple loop of reading 4K, and writing 4K.
1854 * The size passed in is the number of 512 byte sectors in the filesystem.
1855 * So compute the number of whole 4K blocks we should read/write,
1856 * and the remainder.
1857 */
1858 numblocks = size / CRYPT_SECTORS_PER_BUFSIZE;
1859 remainder = size % CRYPT_SECTORS_PER_BUFSIZE;
Ken Sumrall29d8da82011-05-18 17:20:07 -07001860 tot_numblocks = tot_size / CRYPT_SECTORS_PER_BUFSIZE;
1861 blocks_already_done = *size_already_done / CRYPT_SECTORS_PER_BUFSIZE;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001862
1863 SLOGE("Encrypting filesystem in place...");
1864
Ken Sumrall29d8da82011-05-18 17:20:07 -07001865 one_pct = tot_numblocks / 100;
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001866 cur_pct = 0;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001867 /* process the majority of the filesystem in blocks */
1868 for (i=0; i<numblocks; i++) {
Ken Sumrall29d8da82011-05-18 17:20:07 -07001869 new_pct = (i + blocks_already_done) / one_pct;
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001870 if (new_pct > cur_pct) {
1871 char buf[8];
1872
1873 cur_pct = new_pct;
1874 snprintf(buf, sizeof(buf), "%lld", cur_pct);
1875 property_set("vold.encrypt_progress", buf);
1876 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001877 if (unix_read(realfd, buf, CRYPT_INPLACE_BUFSIZE) <= 0) {
1878 SLOGE("Error reading real_blkdev %s for inplace encrypt\n", crypto_blkdev);
1879 goto errout;
1880 }
1881 if (unix_write(cryptofd, buf, CRYPT_INPLACE_BUFSIZE) <= 0) {
1882 SLOGE("Error writing crypto_blkdev %s for inplace encrypt\n", crypto_blkdev);
1883 goto errout;
1884 }
1885 }
1886
1887 /* Do any remaining sectors */
1888 for (i=0; i<remainder; i++) {
1889 if (unix_read(realfd, buf, 512) <= 0) {
1890 SLOGE("Error reading rival sectors from real_blkdev %s for inplace encrypt\n", crypto_blkdev);
1891 goto errout;
1892 }
1893 if (unix_write(cryptofd, buf, 512) <= 0) {
1894 SLOGE("Error writing final sectors to crypto_blkdev %s for inplace encrypt\n", crypto_blkdev);
1895 goto errout;
1896 }
1897 }
1898
Ken Sumrall29d8da82011-05-18 17:20:07 -07001899 *size_already_done += size;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001900 rc = 0;
1901
1902errout:
1903 close(realfd);
1904 close(cryptofd);
1905
1906 return rc;
1907}
1908
Paul Lawrenceae59fe62014-01-21 08:23:27 -08001909static int cryptfs_enable_inplace(char *crypto_blkdev, char *real_blkdev,
1910 off64_t size, off64_t *size_already_done,
1911 off64_t tot_size)
1912{
1913 if (cryptfs_enable_inplace_ext4(crypto_blkdev, real_blkdev,
1914 size, size_already_done, tot_size) == 0) {
1915 return 0;
1916 }
1917
1918 return cryptfs_enable_inplace_full(crypto_blkdev, real_blkdev,
1919 size, size_already_done, tot_size);
1920}
1921
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001922#define CRYPTO_ENABLE_WIPE 1
1923#define CRYPTO_ENABLE_INPLACE 2
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001924
1925#define FRAMEWORK_BOOT_WAIT 60
1926
Ken Sumrall29d8da82011-05-18 17:20:07 -07001927static inline int should_encrypt(struct volume_info *volume)
1928{
Paul Lawrenceae59fe62014-01-21 08:23:27 -08001929 return (volume->flags & (VOL_ENCRYPTABLE | VOL_NONREMOVABLE)) ==
Ken Sumrall29d8da82011-05-18 17:20:07 -07001930 (VOL_ENCRYPTABLE | VOL_NONREMOVABLE);
1931}
1932
Paul Lawrence13486032014-02-03 13:28:11 -08001933int cryptfs_enable_internal(char *howarg, int crypt_type, char *passwd,
1934 int allow_reboot)
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001935{
1936 int how = 0;
Ken Sumrall29d8da82011-05-18 17:20:07 -07001937 char crypto_blkdev[MAXPATHLEN], real_blkdev[MAXPATHLEN], sd_crypto_blkdev[MAXPATHLEN];
Ken Sumralle5032c42012-04-01 23:58:44 -07001938 unsigned long nr_sec;
Ken Sumrall160b4d62013-04-22 12:15:39 -07001939 unsigned char decrypted_master_key[KEY_LEN_BYTES];
Ken Sumrall319b1042011-06-14 14:01:55 -07001940 int rc=-1, fd, i, ret;
Ken Sumrall29d8da82011-05-18 17:20:07 -07001941 struct crypt_mnt_ftr crypt_ftr, sd_crypt_ftr;;
Ken Sumrall160b4d62013-04-22 12:15:39 -07001942 struct crypt_persist_data *pdata;
Ken Sumrall29d8da82011-05-18 17:20:07 -07001943 char tmpfs_options[PROPERTY_VALUE_MAX];
1944 char encrypted_state[PROPERTY_VALUE_MAX];
Ken Sumrall5d4c68e2011-01-30 19:06:03 -08001945 char lockid[32] = { 0 };
Ken Sumrall29d8da82011-05-18 17:20:07 -07001946 char key_loc[PROPERTY_VALUE_MAX];
1947 char fuse_sdcard[PROPERTY_VALUE_MAX];
1948 char *sd_mnt_point;
1949 char sd_blk_dev[256] = { 0 };
1950 int num_vols;
1951 struct volume_info *vol_list = 0;
1952 off64_t cur_encryption_done=0, tot_encryption_size=0;
Ken Sumrall0cc16632011-01-18 20:32:26 -08001953
1954 property_get("ro.crypto.state", encrypted_state, "");
JP Abgrall502dc742013-11-01 13:06:20 -07001955 if (!strcmp(encrypted_state, "encrypted")) {
Ken Sumrall0cc16632011-01-18 20:32:26 -08001956 SLOGE("Device is already running encrypted, aborting");
Ken Sumrall3ed82362011-01-28 23:31:16 -08001957 goto error_unencrypted;
Ken Sumrall0cc16632011-01-18 20:32:26 -08001958 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001959
Ken Sumrall56ad03c2013-02-13 13:00:19 -08001960 fs_mgr_get_crypt_info(fstab, key_loc, 0, sizeof(key_loc));
Ken Sumrall29d8da82011-05-18 17:20:07 -07001961
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001962 if (!strcmp(howarg, "wipe")) {
1963 how = CRYPTO_ENABLE_WIPE;
1964 } else if (! strcmp(howarg, "inplace")) {
1965 how = CRYPTO_ENABLE_INPLACE;
1966 } else {
1967 /* Shouldn't happen, as CommandListener vets the args */
Ken Sumrall3ed82362011-01-28 23:31:16 -08001968 goto error_unencrypted;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001969 }
1970
Ken Sumrall56ad03c2013-02-13 13:00:19 -08001971 fs_mgr_get_crypt_info(fstab, 0, real_blkdev, sizeof(real_blkdev));
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001972
Ken Sumrall3ed82362011-01-28 23:31:16 -08001973 /* Get the size of the real block device */
1974 fd = open(real_blkdev, O_RDONLY);
1975 if ( (nr_sec = get_blkdev_size(fd)) == 0) {
1976 SLOGE("Cannot get size of block device %s\n", real_blkdev);
1977 goto error_unencrypted;
1978 }
1979 close(fd);
1980
1981 /* If doing inplace encryption, make sure the orig fs doesn't include the crypto footer */
Ken Sumrall29d8da82011-05-18 17:20:07 -07001982 if ((how == CRYPTO_ENABLE_INPLACE) && (!strcmp(key_loc, KEY_IN_FOOTER))) {
Ken Sumrall3ed82362011-01-28 23:31:16 -08001983 unsigned int fs_size_sec, max_fs_size_sec;
1984
1985 fs_size_sec = get_fs_size(real_blkdev);
1986 max_fs_size_sec = nr_sec - (CRYPT_FOOTER_OFFSET / 512);
1987
1988 if (fs_size_sec > max_fs_size_sec) {
1989 SLOGE("Orig filesystem overlaps crypto footer region. Cannot encrypt in place.");
1990 goto error_unencrypted;
1991 }
1992 }
1993
Ken Sumrall5d4c68e2011-01-30 19:06:03 -08001994 /* Get a wakelock as this may take a while, and we don't want the
1995 * device to sleep on us. We'll grab a partial wakelock, and if the UI
1996 * wants to keep the screen on, it can grab a full wakelock.
1997 */
Ken Sumrall29d8da82011-05-18 17:20:07 -07001998 snprintf(lockid, sizeof(lockid), "enablecrypto%d", (int) getpid());
Ken Sumrall5d4c68e2011-01-30 19:06:03 -08001999 acquire_wake_lock(PARTIAL_WAKE_LOCK, lockid);
2000
Jeff Sharkey7382f812012-08-23 14:08:59 -07002001 /* Get the sdcard mount point */
Jeff Sharkeyb77bc462012-10-01 14:36:26 -07002002 sd_mnt_point = getenv("EMULATED_STORAGE_SOURCE");
Jeff Sharkey7382f812012-08-23 14:08:59 -07002003 if (!sd_mnt_point) {
2004 sd_mnt_point = getenv("EXTERNAL_STORAGE");
2005 }
2006 if (!sd_mnt_point) {
2007 sd_mnt_point = "/mnt/sdcard";
2008 }
Ken Sumrall29d8da82011-05-18 17:20:07 -07002009
2010 num_vols=vold_getNumDirectVolumes();
2011 vol_list = malloc(sizeof(struct volume_info) * num_vols);
2012 vold_getDirectVolumeList(vol_list);
2013
2014 for (i=0; i<num_vols; i++) {
2015 if (should_encrypt(&vol_list[i])) {
2016 fd = open(vol_list[i].blk_dev, O_RDONLY);
2017 if ( (vol_list[i].size = get_blkdev_size(fd)) == 0) {
2018 SLOGE("Cannot get size of block device %s\n", vol_list[i].blk_dev);
2019 goto error_unencrypted;
2020 }
2021 close(fd);
2022
Ken Sumrall3b170052011-07-11 15:38:57 -07002023 ret=vold_disableVol(vol_list[i].label);
Ken Sumrall319b1042011-06-14 14:01:55 -07002024 if ((ret < 0) && (ret != UNMOUNT_NOT_MOUNTED_ERR)) {
2025 /* -2 is returned when the device exists but is not currently mounted.
2026 * ignore the error and continue. */
Ken Sumrall29d8da82011-05-18 17:20:07 -07002027 SLOGE("Failed to unmount volume %s\n", vol_list[i].label);
2028 goto error_unencrypted;
2029 }
2030 }
2031 }
2032
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002033 /* The init files are setup to stop the class main and late start when
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002034 * vold sets trigger_shutdown_framework.
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002035 */
2036 property_set("vold.decrypt", "trigger_shutdown_framework");
2037 SLOGD("Just asked init to shut down class main\n");
2038
Ken Sumrall425524d2012-06-14 20:55:28 -07002039 if (vold_unmountAllAsecs()) {
2040 /* Just report the error. If any are left mounted,
2041 * umounting /data below will fail and handle the error.
2042 */
2043 SLOGE("Error unmounting internal asecs");
2044 }
2045
Ken Sumrall29d8da82011-05-18 17:20:07 -07002046 property_get("ro.crypto.fuse_sdcard", fuse_sdcard, "");
2047 if (!strcmp(fuse_sdcard, "true")) {
2048 /* This is a device using the fuse layer to emulate the sdcard semantics
2049 * on top of the userdata partition. vold does not manage it, it is managed
2050 * by the sdcard service. The sdcard service was killed by the property trigger
2051 * above, so just unmount it now. We must do this _AFTER_ killing the framework,
2052 * unlike the case for vold managed devices above.
2053 */
2054 if (wait_and_unmount(sd_mnt_point)) {
2055 goto error_shutting_down;
2056 }
Ken Sumrall2eaf7132011-01-14 12:45:48 -08002057 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002058
2059 /* Now unmount the /data partition. */
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002060 if (wait_and_unmount(DATA_MNT_POINT)) {
JP Abgrall502dc742013-11-01 13:06:20 -07002061 if (allow_reboot) {
2062 goto error_shutting_down;
2063 } else {
2064 goto error_unencrypted;
2065 }
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002066 }
2067
2068 /* Do extra work for a better UX when doing the long inplace encryption */
2069 if (how == CRYPTO_ENABLE_INPLACE) {
2070 /* Now that /data is unmounted, we need to mount a tmpfs
2071 * /data, set a property saying we're doing inplace encryption,
2072 * and restart the framework.
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002073 */
Ken Sumralle5032c42012-04-01 23:58:44 -07002074 if (fs_mgr_do_tmpfs_mount(DATA_MNT_POINT)) {
Ken Sumrall3ed82362011-01-28 23:31:16 -08002075 goto error_shutting_down;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002076 }
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002077 /* Tells the framework that inplace encryption is starting */
Ken Sumrall7df84122011-01-18 14:04:08 -08002078 property_set("vold.encrypt_progress", "0");
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002079
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002080 /* restart the framework. */
2081 /* Create necessary paths on /data */
2082 if (prep_data_fs()) {
Ken Sumrall3ed82362011-01-28 23:31:16 -08002083 goto error_shutting_down;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002084 }
2085
Ken Sumrall92736ef2012-10-17 20:57:14 -07002086 /* Ugh, shutting down the framework is not synchronous, so until it
2087 * can be fixed, this horrible hack will wait a moment for it all to
2088 * shut down before proceeding. Without it, some devices cannot
2089 * restart the graphics services.
2090 */
2091 sleep(2);
2092
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002093 /* startup service classes main and late_start */
2094 property_set("vold.decrypt", "trigger_restart_min_framework");
2095 SLOGD("Just triggered restart_min_framework\n");
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002096
Ken Sumrall7df84122011-01-18 14:04:08 -08002097 /* OK, the framework is restarted and will soon be showing a
2098 * progress bar. Time to setup an encrypted mapping, and
2099 * either write a new filesystem, or encrypt in place updating
2100 * the progress bar as we work.
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002101 */
2102 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002103
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002104 /* Start the actual work of making an encrypted filesystem */
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002105 /* Initialize a crypt_mnt_ftr for the partition */
2106 cryptfs_init_crypt_mnt_ftr(&crypt_ftr);
Ken Sumrall160b4d62013-04-22 12:15:39 -07002107
Ken Sumrall29d8da82011-05-18 17:20:07 -07002108 if (!strcmp(key_loc, KEY_IN_FOOTER)) {
2109 crypt_ftr.fs_size = nr_sec - (CRYPT_FOOTER_OFFSET / 512);
2110 } else {
2111 crypt_ftr.fs_size = nr_sec;
2112 }
Ken Sumralld33d4172011-02-01 00:49:13 -08002113 crypt_ftr.flags |= CRYPT_ENCRYPTION_IN_PROGRESS;
Paul Lawrence13486032014-02-03 13:28:11 -08002114 crypt_ftr.crypt_type = crypt_type;
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002115 strcpy((char *)crypt_ftr.crypto_type_name, "aes-cbc-essiv:sha256");
2116
2117 /* Make an encrypted master key */
Kenny Rootc4c70f12013-06-14 12:11:38 -07002118 if (create_encrypted_random_key(passwd, crypt_ftr.master_key, crypt_ftr.salt, &crypt_ftr)) {
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002119 SLOGE("Cannot create encrypted master key\n");
JP Abgrall502dc742013-11-01 13:06:20 -07002120 goto error_shutting_down;
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002121 }
2122
2123 /* Write the key to the end of the partition */
Ken Sumrall160b4d62013-04-22 12:15:39 -07002124 put_crypt_ftr_and_key(&crypt_ftr);
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002125
Ken Sumrall160b4d62013-04-22 12:15:39 -07002126 /* If any persistent data has been remembered, save it.
2127 * If none, create a valid empty table and save that.
2128 */
2129 if (!persist_data) {
2130 pdata = malloc(CRYPT_PERSIST_DATA_SIZE);
2131 if (pdata) {
2132 init_empty_persist_data(pdata, CRYPT_PERSIST_DATA_SIZE);
2133 persist_data = pdata;
2134 }
2135 }
2136 if (persist_data) {
2137 save_persistent_data();
2138 }
2139
JP Abgrall7bdfa522013-11-15 13:42:56 -08002140 decrypt_master_key(passwd, decrypted_master_key, &crypt_ftr);
Ken Sumrall29d8da82011-05-18 17:20:07 -07002141 create_crypto_blk_dev(&crypt_ftr, decrypted_master_key, real_blkdev, crypto_blkdev,
2142 "userdata");
2143
Ken Sumrall128626f2011-06-28 18:45:14 -07002144 /* The size of the userdata partition, and add in the vold volumes below */
2145 tot_encryption_size = crypt_ftr.fs_size;
2146
Ken Sumrall29d8da82011-05-18 17:20:07 -07002147 /* setup crypto mapping for all encryptable volumes handled by vold */
2148 for (i=0; i<num_vols; i++) {
2149 if (should_encrypt(&vol_list[i])) {
2150 vol_list[i].crypt_ftr = crypt_ftr; /* gotta love struct assign */
2151 vol_list[i].crypt_ftr.fs_size = vol_list[i].size;
2152 create_crypto_blk_dev(&vol_list[i].crypt_ftr, decrypted_master_key,
2153 vol_list[i].blk_dev, vol_list[i].crypto_blkdev,
2154 vol_list[i].label);
Ken Sumrall128626f2011-06-28 18:45:14 -07002155 tot_encryption_size += vol_list[i].size;
Ken Sumrall29d8da82011-05-18 17:20:07 -07002156 }
2157 }
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002158
2159 if (how == CRYPTO_ENABLE_WIPE) {
Ken Sumrall29d8da82011-05-18 17:20:07 -07002160 rc = cryptfs_enable_wipe(crypto_blkdev, crypt_ftr.fs_size, EXT4_FS);
2161 /* Encrypt all encryptable volumes handled by vold */
2162 if (!rc) {
2163 for (i=0; i<num_vols; i++) {
2164 if (should_encrypt(&vol_list[i])) {
2165 rc = cryptfs_enable_wipe(vol_list[i].crypto_blkdev,
2166 vol_list[i].crypt_ftr.fs_size, FAT_FS);
2167 }
2168 }
2169 }
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002170 } else if (how == CRYPTO_ENABLE_INPLACE) {
Ken Sumrall29d8da82011-05-18 17:20:07 -07002171 rc = cryptfs_enable_inplace(crypto_blkdev, real_blkdev, crypt_ftr.fs_size,
2172 &cur_encryption_done, tot_encryption_size);
2173 /* Encrypt all encryptable volumes handled by vold */
2174 if (!rc) {
2175 for (i=0; i<num_vols; i++) {
2176 if (should_encrypt(&vol_list[i])) {
2177 rc = cryptfs_enable_inplace(vol_list[i].crypto_blkdev,
2178 vol_list[i].blk_dev,
2179 vol_list[i].crypt_ftr.fs_size,
2180 &cur_encryption_done, tot_encryption_size);
2181 }
2182 }
2183 }
2184 if (!rc) {
2185 /* The inplace routine never actually sets the progress to 100%
2186 * due to the round down nature of integer division, so set it here */
2187 property_set("vold.encrypt_progress", "100");
2188 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002189 } else {
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002190 /* Shouldn't happen */
2191 SLOGE("cryptfs_enable: internal error, unknown option\n");
JP Abgrall502dc742013-11-01 13:06:20 -07002192 goto error_shutting_down;
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002193 }
2194
2195 /* Undo the dm-crypt mapping whether we succeed or not */
Ken Sumrall29d8da82011-05-18 17:20:07 -07002196 delete_crypto_blk_dev("userdata");
2197 for (i=0; i<num_vols; i++) {
2198 if (should_encrypt(&vol_list[i])) {
2199 delete_crypto_blk_dev(vol_list[i].label);
2200 }
2201 }
2202
2203 free(vol_list);
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002204
2205 if (! rc) {
2206 /* Success */
Ken Sumrall7f7dbaa2011-02-01 15:46:41 -08002207
Ken Sumralld33d4172011-02-01 00:49:13 -08002208 /* Clear the encryption in progres flag in the footer */
2209 crypt_ftr.flags &= ~CRYPT_ENCRYPTION_IN_PROGRESS;
Ken Sumrall160b4d62013-04-22 12:15:39 -07002210 put_crypt_ftr_and_key(&crypt_ftr);
Ken Sumralld33d4172011-02-01 00:49:13 -08002211
Ken Sumrall29d8da82011-05-18 17:20:07 -07002212 sleep(2); /* Give the UI a chance to show 100% progress */
Ken Sumralladfba362013-06-04 16:37:52 -07002213 cryptfs_reboot(0);
Ken Sumrall3ed82362011-01-28 23:31:16 -08002214 } else {
Mike Lockwoodee6d8c42012-02-15 13:43:28 -08002215 char value[PROPERTY_VALUE_MAX];
2216
Ken Sumrall319369a2012-06-27 16:30:18 -07002217 property_get("ro.vold.wipe_on_crypt_fail", value, "0");
Mike Lockwoodee6d8c42012-02-15 13:43:28 -08002218 if (!strcmp(value, "1")) {
2219 /* wipe data if encryption failed */
2220 SLOGE("encryption failed - rebooting into recovery to wipe data\n");
2221 mkdir("/cache/recovery", 0700);
Nick Kralevich4684e582012-06-26 15:07:03 -07002222 int fd = open("/cache/recovery/command", O_RDWR|O_CREAT|O_TRUNC, 0600);
Mike Lockwoodee6d8c42012-02-15 13:43:28 -08002223 if (fd >= 0) {
2224 write(fd, "--wipe_data", strlen("--wipe_data") + 1);
2225 close(fd);
2226 } else {
2227 SLOGE("could not open /cache/recovery/command\n");
2228 }
Ken Sumralladfba362013-06-04 16:37:52 -07002229 cryptfs_reboot(1);
Mike Lockwoodee6d8c42012-02-15 13:43:28 -08002230 } else {
2231 /* set property to trigger dialog */
2232 property_set("vold.encrypt_progress", "error_partially_encrypted");
2233 release_wake_lock(lockid);
2234 }
Ken Sumrall3ed82362011-01-28 23:31:16 -08002235 return -1;
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002236 }
2237
Ken Sumrall3ed82362011-01-28 23:31:16 -08002238 /* hrm, the encrypt step claims success, but the reboot failed.
2239 * This should not happen.
2240 * Set the property and return. Hope the framework can deal with it.
2241 */
2242 property_set("vold.encrypt_progress", "error_reboot_failed");
Ken Sumrall5d4c68e2011-01-30 19:06:03 -08002243 release_wake_lock(lockid);
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002244 return rc;
Ken Sumrall3ed82362011-01-28 23:31:16 -08002245
2246error_unencrypted:
Ken Sumrall29d8da82011-05-18 17:20:07 -07002247 free(vol_list);
Ken Sumrall3ed82362011-01-28 23:31:16 -08002248 property_set("vold.encrypt_progress", "error_not_encrypted");
Ken Sumrall5d4c68e2011-01-30 19:06:03 -08002249 if (lockid[0]) {
2250 release_wake_lock(lockid);
2251 }
Ken Sumrall3ed82362011-01-28 23:31:16 -08002252 return -1;
2253
2254error_shutting_down:
2255 /* we failed, and have not encrypted anthing, so the users's data is still intact,
2256 * but the framework is stopped and not restarted to show the error, so it's up to
2257 * vold to restart the system.
2258 */
2259 SLOGE("Error enabling encryption after framework is shutdown, no data changed, restarting system");
Ken Sumralladfba362013-06-04 16:37:52 -07002260 cryptfs_reboot(0);
Ken Sumrall3ed82362011-01-28 23:31:16 -08002261
2262 /* shouldn't get here */
2263 property_set("vold.encrypt_progress", "error_shutting_down");
Ken Sumrall29d8da82011-05-18 17:20:07 -07002264 free(vol_list);
Ken Sumrall5d4c68e2011-01-30 19:06:03 -08002265 if (lockid[0]) {
2266 release_wake_lock(lockid);
2267 }
Ken Sumrall3ed82362011-01-28 23:31:16 -08002268 return -1;
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002269}
2270
Paul Lawrence13486032014-02-03 13:28:11 -08002271int cryptfs_enable(char *howarg, char *passwd, int allow_reboot)
2272{
2273 /** @todo If we keep this route (user selected encryption)
2274 * need to take a type in and pass it to here.
2275 */
2276 return cryptfs_enable_internal(howarg, CRYPT_TYPE_PASSWORD,
2277 passwd, allow_reboot);
2278}
2279
2280int cryptfs_enable_default(char *howarg, int allow_reboot)
2281{
2282 return cryptfs_enable_internal(howarg, CRYPT_TYPE_DEFAULT,
2283 DEFAULT_PASSWORD, allow_reboot);
2284}
2285
2286int cryptfs_changepw(int crypt_type, const char *newpw)
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002287{
2288 struct crypt_mnt_ftr crypt_ftr;
Ken Sumrall160b4d62013-04-22 12:15:39 -07002289 unsigned char decrypted_master_key[KEY_LEN_BYTES];
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002290
2291 /* This is only allowed after we've successfully decrypted the master key */
Paul Lawrencef4faa572014-01-29 13:31:03 -08002292 if (!master_key_saved) {
Ken Sumrall0cc16632011-01-18 20:32:26 -08002293 SLOGE("Key not saved, aborting");
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002294 return -1;
2295 }
2296
Paul Lawrencef4faa572014-01-29 13:31:03 -08002297 if (crypt_type < 0 || crypt_type > CRYPT_TYPE_MAX_TYPE) {
2298 SLOGE("Invalid crypt_type %d", crypt_type);
2299 return -1;
2300 }
2301
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002302 /* get key */
Ken Sumrall160b4d62013-04-22 12:15:39 -07002303 if (get_crypt_ftr_and_key(&crypt_ftr)) {
Paul Lawrencef4faa572014-01-29 13:31:03 -08002304 SLOGE("Error getting crypt footer and key");
2305 return -1;
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002306 }
2307
Paul Lawrencef4faa572014-01-29 13:31:03 -08002308 crypt_ftr.crypt_type = crypt_type;
2309
2310 encrypt_master_key(crypt_type == CRYPT_TYPE_DEFAULT ? DEFAULT_PASSWORD
2311 : newpw,
2312 crypt_ftr.salt,
2313 saved_master_key,
2314 crypt_ftr.master_key,
2315 &crypt_ftr);
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002316
Jason parks70a4b3f2011-01-28 10:10:47 -06002317 /* save the key */
Ken Sumrall160b4d62013-04-22 12:15:39 -07002318 put_crypt_ftr_and_key(&crypt_ftr);
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002319
2320 return 0;
2321}
Ken Sumrall160b4d62013-04-22 12:15:39 -07002322
2323static int persist_get_key(char *fieldname, char *value)
2324{
2325 unsigned int i;
2326
2327 if (persist_data == NULL) {
2328 return -1;
2329 }
2330 for (i = 0; i < persist_data->persist_valid_entries; i++) {
2331 if (!strncmp(persist_data->persist_entry[i].key, fieldname, PROPERTY_KEY_MAX)) {
2332 /* We found it! */
2333 strlcpy(value, persist_data->persist_entry[i].val, PROPERTY_VALUE_MAX);
2334 return 0;
2335 }
2336 }
2337
2338 return -1;
2339}
2340
2341static int persist_set_key(char *fieldname, char *value, int encrypted)
2342{
2343 unsigned int i;
2344 unsigned int num;
2345 struct crypt_mnt_ftr crypt_ftr;
2346 unsigned int max_persistent_entries;
2347 unsigned int dsize;
2348
2349 if (persist_data == NULL) {
2350 return -1;
2351 }
2352
2353 /* If encrypted, use the values from the crypt_ftr, otherwise
2354 * use the values for the current spec.
2355 */
2356 if (encrypted) {
2357 if(get_crypt_ftr_and_key(&crypt_ftr)) {
2358 return -1;
2359 }
2360 dsize = crypt_ftr.persist_data_size;
2361 } else {
2362 dsize = CRYPT_PERSIST_DATA_SIZE;
2363 }
2364 max_persistent_entries = (dsize - sizeof(struct crypt_persist_data)) /
2365 sizeof(struct crypt_persist_entry);
2366
2367 num = persist_data->persist_valid_entries;
2368
2369 for (i = 0; i < num; i++) {
2370 if (!strncmp(persist_data->persist_entry[i].key, fieldname, PROPERTY_KEY_MAX)) {
2371 /* We found an existing entry, update it! */
2372 memset(persist_data->persist_entry[i].val, 0, PROPERTY_VALUE_MAX);
2373 strlcpy(persist_data->persist_entry[i].val, value, PROPERTY_VALUE_MAX);
2374 return 0;
2375 }
2376 }
2377
2378 /* We didn't find it, add it to the end, if there is room */
2379 if (persist_data->persist_valid_entries < max_persistent_entries) {
2380 memset(&persist_data->persist_entry[num], 0, sizeof(struct crypt_persist_entry));
2381 strlcpy(persist_data->persist_entry[num].key, fieldname, PROPERTY_KEY_MAX);
2382 strlcpy(persist_data->persist_entry[num].val, value, PROPERTY_VALUE_MAX);
2383 persist_data->persist_valid_entries++;
2384 return 0;
2385 }
2386
2387 return -1;
2388}
2389
2390/* Return the value of the specified field. */
2391int cryptfs_getfield(char *fieldname, char *value, int len)
2392{
2393 char temp_value[PROPERTY_VALUE_MAX];
2394 char real_blkdev[MAXPATHLEN];
2395 /* 0 is success, 1 is not encrypted,
2396 * -1 is value not set, -2 is any other error
2397 */
2398 int rc = -2;
2399
2400 if (persist_data == NULL) {
2401 load_persistent_data();
2402 if (persist_data == NULL) {
2403 SLOGE("Getfield error, cannot load persistent data");
2404 goto out;
2405 }
2406 }
2407
2408 if (!persist_get_key(fieldname, temp_value)) {
2409 /* We found it, copy it to the caller's buffer and return */
2410 strlcpy(value, temp_value, len);
2411 rc = 0;
2412 } else {
2413 /* Sadness, it's not there. Return the error */
2414 rc = -1;
2415 }
2416
2417out:
2418 return rc;
2419}
2420
2421/* Set the value of the specified field. */
2422int cryptfs_setfield(char *fieldname, char *value)
2423{
2424 struct crypt_persist_data stored_pdata;
2425 struct crypt_persist_data *pdata_p;
2426 struct crypt_mnt_ftr crypt_ftr;
2427 char encrypted_state[PROPERTY_VALUE_MAX];
2428 /* 0 is success, -1 is an error */
2429 int rc = -1;
2430 int encrypted = 0;
2431
2432 if (persist_data == NULL) {
2433 load_persistent_data();
2434 if (persist_data == NULL) {
2435 SLOGE("Setfield error, cannot load persistent data");
2436 goto out;
2437 }
2438 }
2439
2440 property_get("ro.crypto.state", encrypted_state, "");
2441 if (!strcmp(encrypted_state, "encrypted") ) {
2442 encrypted = 1;
2443 }
2444
2445 if (persist_set_key(fieldname, value, encrypted)) {
2446 goto out;
2447 }
2448
2449 /* If we are running encrypted, save the persistent data now */
2450 if (encrypted) {
2451 if (save_persistent_data()) {
2452 SLOGE("Setfield error, cannot save persistent data");
2453 goto out;
2454 }
2455 }
2456
2457 rc = 0;
2458
2459out:
2460 return rc;
2461}
Paul Lawrencef4faa572014-01-29 13:31:03 -08002462
2463/* Checks userdata. Attempt to mount the volume if default-
2464 * encrypted.
2465 * On success trigger next init phase and return 0.
2466 * Currently do not handle failure - see TODO below.
2467 */
2468int cryptfs_mount_default_encrypted(void)
2469{
2470 char decrypt_state[PROPERTY_VALUE_MAX];
2471 property_get("vold.decrypt", decrypt_state, "0");
2472 if (!strcmp(decrypt_state, "0")) {
2473 SLOGE("Not encrypted - should not call here");
2474 } else {
2475 int crypt_type = cryptfs_get_password_type();
2476 if (crypt_type < 0 || crypt_type > CRYPT_TYPE_MAX_TYPE) {
2477 SLOGE("Bad crypt type - error");
2478 } else if (crypt_type != CRYPT_TYPE_DEFAULT) {
2479 SLOGD("Password is not default - "
2480 "starting min framework to prompt");
2481 property_set("vold.decrypt", "trigger_restart_min_framework");
2482 return 0;
2483 } else if (cryptfs_check_passwd(DEFAULT_PASSWORD) == 0) {
2484 SLOGD("Password is default - restarting filesystem");
2485 cryptfs_restart_internal(0);
2486 return 0;
2487 } else {
2488 SLOGE("Encrypted, default crypt type but can't decrypt");
2489 }
2490 }
2491
2492 /** @TODO make sure we factory wipe in this situation
2493 * In general if we got here there is no recovery
2494 */
2495 return 0;
2496}
2497
2498/* Returns type of the password, default, pattern, pin or password.
2499 */
2500int cryptfs_get_password_type(void)
2501{
2502 struct crypt_mnt_ftr crypt_ftr;
2503
2504 if (get_crypt_ftr_and_key(&crypt_ftr)) {
2505 SLOGE("Error getting crypt footer and key\n");
2506 return -1;
2507 }
2508
2509 return crypt_ftr.crypt_type;
2510}
Paul Lawrence684dbdf2014-02-07 12:07:22 -08002511
Paul Lawrence399317e2014-03-10 13:20:50 -07002512char* cryptfs_get_password()
Paul Lawrence684dbdf2014-02-07 12:07:22 -08002513{
Paul Lawrence399317e2014-03-10 13:20:50 -07002514 struct timespec now;
2515 clock_gettime(CLOCK_MONOTONIC, &now);
2516 if (now.tv_sec < password_expiry_time) {
2517 return password;
2518 } else {
2519 cryptfs_clear_password();
2520 return 0;
2521 }
2522}
2523
2524void cryptfs_clear_password()
2525{
2526 if (password) {
2527 size_t len = strlen(password);
2528 memset(password, 0, len);
2529 free(password);
2530 password = 0;
2531 password_expiry_time = 0;
2532 }
Paul Lawrence684dbdf2014-02-07 12:07:22 -08002533}