blob: 30e13a3061264a338afb93c3cb93fb400ef728a6 [file] [log] [blame]
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001/*
2 * Copyright (C) 2010 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17/* TO DO:
18 * 1. Perhaps keep several copies of the encrypted key, in case something
19 * goes horribly wrong?
20 *
21 */
22
23#include <sys/types.h>
Ken Sumralle550f782013-08-20 13:48:23 -070024#include <sys/wait.h>
Ken Sumrall8f869aa2010-12-03 03:47:09 -080025#include <sys/stat.h>
Paul Lawrencef4faa572014-01-29 13:31:03 -080026#include <ctype.h>
Ken Sumrall8f869aa2010-12-03 03:47:09 -080027#include <fcntl.h>
28#include <unistd.h>
29#include <stdio.h>
30#include <sys/ioctl.h>
31#include <linux/dm-ioctl.h>
32#include <libgen.h>
33#include <stdlib.h>
34#include <sys/param.h>
35#include <string.h>
36#include <sys/mount.h>
37#include <openssl/evp.h>
38#include <errno.h>
Ken Sumrall3ed82362011-01-28 23:31:16 -080039#include <ext4.h>
Ken Sumrall29d8da82011-05-18 17:20:07 -070040#include <linux/kdev_t.h>
Ken Sumralle5032c42012-04-01 23:58:44 -070041#include <fs_mgr.h>
Ken Sumrall8f869aa2010-12-03 03:47:09 -080042#include "cryptfs.h"
43#define LOG_TAG "Cryptfs"
44#include "cutils/log.h"
45#include "cutils/properties.h"
Ken Sumralladfba362013-06-04 16:37:52 -070046#include "cutils/android_reboot.h"
Ken Sumrall5d4c68e2011-01-30 19:06:03 -080047#include "hardware_legacy/power.h"
Ken Sumralle550f782013-08-20 13:48:23 -070048#include <logwrap/logwrap.h>
Ken Sumrall29d8da82011-05-18 17:20:07 -070049#include "VolumeManager.h"
Ken Sumrall9caab762013-06-11 19:10:20 -070050#include "VoldUtil.h"
Kenny Rootc4c70f12013-06-14 12:11:38 -070051#include "crypto_scrypt.h"
Paul Lawrenceae59fe62014-01-21 08:23:27 -080052#include "ext4_utils.h"
Paul Lawrence87999172014-02-20 12:21:31 -080053#include "CheckBattery.h"
Ken Sumrall8f869aa2010-12-03 03:47:09 -080054
Mark Salyzyn3e971272014-01-21 13:27:04 -080055#define UNUSED __attribute__((unused))
56
Mark Salyzyn5eecc442014-02-12 14:16:14 -080057#define UNUSED __attribute__((unused))
58
Ken Sumrall8f869aa2010-12-03 03:47:09 -080059#define DM_CRYPT_BUF_SIZE 4096
60
Jason parks70a4b3f2011-01-28 10:10:47 -060061#define HASH_COUNT 2000
62#define KEY_LEN_BYTES 16
63#define IV_LEN_BYTES 16
64
Ken Sumrall29d8da82011-05-18 17:20:07 -070065#define KEY_IN_FOOTER "footer"
66
Paul Lawrencef4faa572014-01-29 13:31:03 -080067// "default_password" encoded into hex (d=0x64 etc)
68#define DEFAULT_PASSWORD "64656661756c745f70617373776f7264"
69
Ken Sumrall29d8da82011-05-18 17:20:07 -070070#define EXT4_FS 1
71#define FAT_FS 2
72
Ken Sumralle919efe2012-09-29 17:07:41 -070073#define TABLE_LOAD_RETRIES 10
74
Ken Sumrall8f869aa2010-12-03 03:47:09 -080075char *me = "cryptfs";
76
Jason parks70a4b3f2011-01-28 10:10:47 -060077static unsigned char saved_master_key[KEY_LEN_BYTES];
Ken Sumrall3ad90722011-10-04 20:38:29 -070078static char *saved_mount_point;
Jason parks70a4b3f2011-01-28 10:10:47 -060079static int master_key_saved = 0;
Ken Sumrall160b4d62013-04-22 12:15:39 -070080static struct crypt_persist_data *persist_data = NULL;
Ken Sumrall56ad03c2013-02-13 13:00:19 -080081
Paul Lawrence684dbdf2014-02-07 12:07:22 -080082/* Set when userdata is successfully decrypted and mounted.
83 * Reset whenever read (via cryptfs_just_decrypted)
84 * (Read by keyguard to avoid a double prompt.)
85 */
86static int just_decrypted = 0;
87
Ken Sumrall56ad03c2013-02-13 13:00:19 -080088extern struct fstab *fstab;
Ken Sumrall8ddbe402011-01-17 15:26:29 -080089
Paul Lawrence87999172014-02-20 12:21:31 -080090enum RebootType {reboot, recovery, shutdown};
91static void cryptfs_reboot(enum RebootType rt)
Ken Sumralladfba362013-06-04 16:37:52 -070092{
Paul Lawrence87999172014-02-20 12:21:31 -080093 switch(rt) {
94 case reboot:
95 property_set(ANDROID_RB_PROPERTY, "reboot");
96 break;
97
98 case recovery:
99 property_set(ANDROID_RB_PROPERTY, "reboot,recovery");
100 break;
101
102 case shutdown:
103 property_set(ANDROID_RB_PROPERTY, "shutdown");
104 break;
Ken Sumralladfba362013-06-04 16:37:52 -0700105 }
Paul Lawrence87999172014-02-20 12:21:31 -0800106
Ken Sumralladfba362013-06-04 16:37:52 -0700107 sleep(20);
108
109 /* Shouldn't get here, reboot should happen before sleep times out */
110 return;
111}
112
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800113static void ioctl_init(struct dm_ioctl *io, size_t dataSize, const char *name, unsigned flags)
114{
115 memset(io, 0, dataSize);
116 io->data_size = dataSize;
117 io->data_start = sizeof(struct dm_ioctl);
118 io->version[0] = 4;
119 io->version[1] = 0;
120 io->version[2] = 0;
121 io->flags = flags;
122 if (name) {
123 strncpy(io->name, name, sizeof(io->name));
124 }
125}
126
Kenny Rootc4c70f12013-06-14 12:11:38 -0700127/**
128 * Gets the default device scrypt parameters for key derivation time tuning.
129 * The parameters should lead to about one second derivation time for the
130 * given device.
131 */
132static void get_device_scrypt_params(struct crypt_mnt_ftr *ftr) {
133 const int default_params[] = SCRYPT_DEFAULTS;
134 int params[] = SCRYPT_DEFAULTS;
135 char paramstr[PROPERTY_VALUE_MAX];
136 char *token;
137 char *saveptr;
138 int i;
139
140 property_get(SCRYPT_PROP, paramstr, "");
141 if (paramstr[0] != '\0') {
142 /*
143 * The token we're looking for should be three integers separated by
144 * colons (e.g., "12:8:1"). Scan the property to make sure it matches.
145 */
Kenny Root2947e342013-08-14 15:54:49 -0700146 for (i = 0, token = strtok_r(paramstr, ":", &saveptr);
147 token != NULL && i < 3;
Kenny Rootc4c70f12013-06-14 12:11:38 -0700148 i++, token = strtok_r(NULL, ":", &saveptr)) {
149 char *endptr;
150 params[i] = strtol(token, &endptr, 10);
151
152 /*
153 * Check that there was a valid number and it's 8-bit. If not,
154 * break out and the end check will take the default values.
155 */
156 if ((*token == '\0') || (*endptr != '\0') || params[i] < 0 || params[i] > 255) {
157 break;
158 }
159 }
160
161 /*
162 * If there were not enough tokens or a token was malformed (not an
163 * integer), it will end up here and the default parameters can be
164 * taken.
165 */
166 if ((i != 3) || (token != NULL)) {
167 SLOGW("bad scrypt parameters '%s' should be like '12:8:1'; using defaults", paramstr);
168 memcpy(params, default_params, sizeof(params));
169 }
170 }
171
172 ftr->N_factor = params[0];
173 ftr->r_factor = params[1];
174 ftr->p_factor = params[2];
175}
176
Ken Sumrall3ed82362011-01-28 23:31:16 -0800177static unsigned int get_fs_size(char *dev)
178{
179 int fd, block_size;
180 struct ext4_super_block sb;
181 off64_t len;
182
183 if ((fd = open(dev, O_RDONLY)) < 0) {
184 SLOGE("Cannot open device to get filesystem size ");
185 return 0;
186 }
187
188 if (lseek64(fd, 1024, SEEK_SET) < 0) {
189 SLOGE("Cannot seek to superblock");
190 return 0;
191 }
192
193 if (read(fd, &sb, sizeof(sb)) != sizeof(sb)) {
194 SLOGE("Cannot read superblock");
195 return 0;
196 }
197
198 close(fd);
199
200 block_size = 1024 << sb.s_log_block_size;
201 /* compute length in bytes */
202 len = ( ((off64_t)sb.s_blocks_count_hi << 32) + sb.s_blocks_count_lo) * block_size;
203
204 /* return length in sectors */
205 return (unsigned int) (len / 512);
206}
207
Ken Sumrall160b4d62013-04-22 12:15:39 -0700208static int get_crypt_ftr_info(char **metadata_fname, off64_t *off)
209{
210 static int cached_data = 0;
211 static off64_t cached_off = 0;
212 static char cached_metadata_fname[PROPERTY_VALUE_MAX] = "";
213 int fd;
214 char key_loc[PROPERTY_VALUE_MAX];
215 char real_blkdev[PROPERTY_VALUE_MAX];
216 unsigned int nr_sec;
217 int rc = -1;
218
219 if (!cached_data) {
220 fs_mgr_get_crypt_info(fstab, key_loc, real_blkdev, sizeof(key_loc));
221
222 if (!strcmp(key_loc, KEY_IN_FOOTER)) {
223 if ( (fd = open(real_blkdev, O_RDWR)) < 0) {
224 SLOGE("Cannot open real block device %s\n", real_blkdev);
225 return -1;
226 }
227
228 if ((nr_sec = get_blkdev_size(fd))) {
229 /* If it's an encrypted Android partition, the last 16 Kbytes contain the
230 * encryption info footer and key, and plenty of bytes to spare for future
231 * growth.
232 */
233 strlcpy(cached_metadata_fname, real_blkdev, sizeof(cached_metadata_fname));
234 cached_off = ((off64_t)nr_sec * 512) - CRYPT_FOOTER_OFFSET;
235 cached_data = 1;
236 } else {
237 SLOGE("Cannot get size of block device %s\n", real_blkdev);
238 }
239 close(fd);
240 } else {
241 strlcpy(cached_metadata_fname, key_loc, sizeof(cached_metadata_fname));
242 cached_off = 0;
243 cached_data = 1;
244 }
245 }
246
247 if (cached_data) {
248 if (metadata_fname) {
249 *metadata_fname = cached_metadata_fname;
250 }
251 if (off) {
252 *off = cached_off;
253 }
254 rc = 0;
255 }
256
257 return rc;
258}
259
Ken Sumralle8744072011-01-18 22:01:55 -0800260/* key or salt can be NULL, in which case just skip writing that value. Useful to
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800261 * update the failed mount count but not change the key.
262 */
Ken Sumrall160b4d62013-04-22 12:15:39 -0700263static int put_crypt_ftr_and_key(struct crypt_mnt_ftr *crypt_ftr)
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800264{
265 int fd;
266 unsigned int nr_sec, cnt;
Ken Sumrall160b4d62013-04-22 12:15:39 -0700267 /* starting_off is set to the SEEK_SET offset
268 * where the crypto structure starts
269 */
270 off64_t starting_off;
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800271 int rc = -1;
Ken Sumrall160b4d62013-04-22 12:15:39 -0700272 char *fname = NULL;
Ken Sumrall3be890f2011-09-14 16:53:46 -0700273 struct stat statbuf;
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800274
Ken Sumrall160b4d62013-04-22 12:15:39 -0700275 if (get_crypt_ftr_info(&fname, &starting_off)) {
276 SLOGE("Unable to get crypt_ftr_info\n");
277 return -1;
278 }
279 if (fname[0] != '/') {
Ken Sumralle5032c42012-04-01 23:58:44 -0700280 SLOGE("Unexpected value for crypto key location\n");
Ken Sumrall160b4d62013-04-22 12:15:39 -0700281 return -1;
282 }
Ken Sumralle550f782013-08-20 13:48:23 -0700283 if ( (fd = open(fname, O_RDWR | O_CREAT, 0600)) < 0) {
284 SLOGE("Cannot open footer file %s for put\n", fname);
Ken Sumrall160b4d62013-04-22 12:15:39 -0700285 return -1;
286 }
287
288 /* Seek to the start of the crypt footer */
289 if (lseek64(fd, starting_off, SEEK_SET) == -1) {
290 SLOGE("Cannot seek to real block device footer\n");
291 goto errout;
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800292 }
293
294 if ((cnt = write(fd, crypt_ftr, sizeof(struct crypt_mnt_ftr))) != sizeof(struct crypt_mnt_ftr)) {
295 SLOGE("Cannot write real block device footer\n");
296 goto errout;
297 }
298
Ken Sumrall3be890f2011-09-14 16:53:46 -0700299 fstat(fd, &statbuf);
300 /* If the keys are kept on a raw block device, do not try to truncate it. */
Ken Sumralle550f782013-08-20 13:48:23 -0700301 if (S_ISREG(statbuf.st_mode)) {
Ken Sumrall29d8da82011-05-18 17:20:07 -0700302 if (ftruncate(fd, 0x4000)) {
Colin Cross59846b62014-02-06 20:34:29 -0800303 SLOGE("Cannot set footer file size\n");
Ken Sumralle8744072011-01-18 22:01:55 -0800304 goto errout;
305 }
306 }
307
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800308 /* Success! */
309 rc = 0;
310
311errout:
312 close(fd);
313 return rc;
314
315}
316
Ken Sumrall160b4d62013-04-22 12:15:39 -0700317static inline int unix_read(int fd, void* buff, int len)
318{
319 return TEMP_FAILURE_RETRY(read(fd, buff, len));
320}
321
322static inline int unix_write(int fd, const void* buff, int len)
323{
324 return TEMP_FAILURE_RETRY(write(fd, buff, len));
325}
326
327static void init_empty_persist_data(struct crypt_persist_data *pdata, int len)
328{
329 memset(pdata, 0, len);
330 pdata->persist_magic = PERSIST_DATA_MAGIC;
331 pdata->persist_valid_entries = 0;
332}
333
334/* A routine to update the passed in crypt_ftr to the lastest version.
335 * fd is open read/write on the device that holds the crypto footer and persistent
336 * data, crypt_ftr is a pointer to the struct to be updated, and offset is the
337 * absolute offset to the start of the crypt_mnt_ftr on the passed in fd.
338 */
339static void upgrade_crypt_ftr(int fd, struct crypt_mnt_ftr *crypt_ftr, off64_t offset)
340{
Kenny Root7434b312013-06-14 11:29:53 -0700341 int orig_major = crypt_ftr->major_version;
342 int orig_minor = crypt_ftr->minor_version;
Ken Sumrall160b4d62013-04-22 12:15:39 -0700343
Kenny Root7434b312013-06-14 11:29:53 -0700344 if ((crypt_ftr->major_version == 1) && (crypt_ftr->minor_version == 0)) {
345 struct crypt_persist_data *pdata;
346 off64_t pdata_offset = offset + CRYPT_FOOTER_TO_PERSIST_OFFSET;
Ken Sumrall160b4d62013-04-22 12:15:39 -0700347
Kenny Rootc4c70f12013-06-14 12:11:38 -0700348 SLOGW("upgrading crypto footer to 1.1");
349
Kenny Root7434b312013-06-14 11:29:53 -0700350 pdata = malloc(CRYPT_PERSIST_DATA_SIZE);
351 if (pdata == NULL) {
352 SLOGE("Cannot allocate persisent data\n");
353 return;
354 }
355 memset(pdata, 0, CRYPT_PERSIST_DATA_SIZE);
356
357 /* Need to initialize the persistent data area */
358 if (lseek64(fd, pdata_offset, SEEK_SET) == -1) {
359 SLOGE("Cannot seek to persisent data offset\n");
360 return;
361 }
362 /* Write all zeros to the first copy, making it invalid */
363 unix_write(fd, pdata, CRYPT_PERSIST_DATA_SIZE);
364
365 /* Write a valid but empty structure to the second copy */
366 init_empty_persist_data(pdata, CRYPT_PERSIST_DATA_SIZE);
367 unix_write(fd, pdata, CRYPT_PERSIST_DATA_SIZE);
368
369 /* Update the footer */
370 crypt_ftr->persist_data_size = CRYPT_PERSIST_DATA_SIZE;
371 crypt_ftr->persist_data_offset[0] = pdata_offset;
372 crypt_ftr->persist_data_offset[1] = pdata_offset + CRYPT_PERSIST_DATA_SIZE;
373 crypt_ftr->minor_version = 1;
Ken Sumrall160b4d62013-04-22 12:15:39 -0700374 }
375
Paul Lawrencef4faa572014-01-29 13:31:03 -0800376 if ((crypt_ftr->major_version == 1) && (crypt_ftr->minor_version == 1)) {
Kenny Rootc4c70f12013-06-14 12:11:38 -0700377 SLOGW("upgrading crypto footer to 1.2");
JP Abgrall7bdfa522013-11-15 13:42:56 -0800378 /* But keep the old kdf_type.
379 * It will get updated later to KDF_SCRYPT after the password has been verified.
380 */
Kenny Rootc4c70f12013-06-14 12:11:38 -0700381 crypt_ftr->kdf_type = KDF_PBKDF2;
382 get_device_scrypt_params(crypt_ftr);
383 crypt_ftr->minor_version = 2;
384 }
385
Paul Lawrencef4faa572014-01-29 13:31:03 -0800386 if ((crypt_ftr->major_version == 1) && (crypt_ftr->minor_version == 2)) {
387 SLOGW("upgrading crypto footer to 1.3");
388 crypt_ftr->crypt_type = CRYPT_TYPE_PASSWORD;
389 crypt_ftr->minor_version = 3;
390 }
391
Kenny Root7434b312013-06-14 11:29:53 -0700392 if ((orig_major != crypt_ftr->major_version) || (orig_minor != crypt_ftr->minor_version)) {
393 if (lseek64(fd, offset, SEEK_SET) == -1) {
394 SLOGE("Cannot seek to crypt footer\n");
395 return;
396 }
397 unix_write(fd, crypt_ftr, sizeof(struct crypt_mnt_ftr));
Ken Sumrall160b4d62013-04-22 12:15:39 -0700398 }
Ken Sumrall160b4d62013-04-22 12:15:39 -0700399}
400
401
402static int get_crypt_ftr_and_key(struct crypt_mnt_ftr *crypt_ftr)
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800403{
404 int fd;
405 unsigned int nr_sec, cnt;
Ken Sumrall160b4d62013-04-22 12:15:39 -0700406 off64_t starting_off;
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800407 int rc = -1;
Ken Sumrall160b4d62013-04-22 12:15:39 -0700408 char *fname = NULL;
Ken Sumrall29d8da82011-05-18 17:20:07 -0700409 struct stat statbuf;
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800410
Ken Sumrall160b4d62013-04-22 12:15:39 -0700411 if (get_crypt_ftr_info(&fname, &starting_off)) {
412 SLOGE("Unable to get crypt_ftr_info\n");
413 return -1;
414 }
415 if (fname[0] != '/') {
Ken Sumralle5032c42012-04-01 23:58:44 -0700416 SLOGE("Unexpected value for crypto key location\n");
Ken Sumrall160b4d62013-04-22 12:15:39 -0700417 return -1;
418 }
419 if ( (fd = open(fname, O_RDWR)) < 0) {
Ken Sumralle550f782013-08-20 13:48:23 -0700420 SLOGE("Cannot open footer file %s for get\n", fname);
Ken Sumrall160b4d62013-04-22 12:15:39 -0700421 return -1;
422 }
423
424 /* Make sure it's 16 Kbytes in length */
425 fstat(fd, &statbuf);
426 if (S_ISREG(statbuf.st_mode) && (statbuf.st_size != 0x4000)) {
427 SLOGE("footer file %s is not the expected size!\n", fname);
428 goto errout;
429 }
430
431 /* Seek to the start of the crypt footer */
432 if (lseek64(fd, starting_off, SEEK_SET) == -1) {
433 SLOGE("Cannot seek to real block device footer\n");
434 goto errout;
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800435 }
436
437 if ( (cnt = read(fd, crypt_ftr, sizeof(struct crypt_mnt_ftr))) != sizeof(struct crypt_mnt_ftr)) {
438 SLOGE("Cannot read real block device footer\n");
439 goto errout;
440 }
441
442 if (crypt_ftr->magic != CRYPT_MNT_MAGIC) {
Ken Sumrall29d8da82011-05-18 17:20:07 -0700443 SLOGE("Bad magic for real block device %s\n", fname);
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800444 goto errout;
445 }
446
Kenny Rootc96a5f82013-06-14 12:08:28 -0700447 if (crypt_ftr->major_version != CURRENT_MAJOR_VERSION) {
448 SLOGE("Cannot understand major version %d real block device footer; expected %d\n",
449 crypt_ftr->major_version, CURRENT_MAJOR_VERSION);
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800450 goto errout;
451 }
452
Kenny Rootc96a5f82013-06-14 12:08:28 -0700453 if (crypt_ftr->minor_version > CURRENT_MINOR_VERSION) {
454 SLOGW("Warning: crypto footer minor version %d, expected <= %d, continuing...\n",
455 crypt_ftr->minor_version, CURRENT_MINOR_VERSION);
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800456 }
457
Ken Sumrall160b4d62013-04-22 12:15:39 -0700458 /* If this is a verion 1.0 crypt_ftr, make it a 1.1 crypt footer, and update the
459 * copy on disk before returning.
460 */
Kenny Rootc96a5f82013-06-14 12:08:28 -0700461 if (crypt_ftr->minor_version < CURRENT_MINOR_VERSION) {
Ken Sumrall160b4d62013-04-22 12:15:39 -0700462 upgrade_crypt_ftr(fd, crypt_ftr, starting_off);
Ken Sumralle8744072011-01-18 22:01:55 -0800463 }
464
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800465 /* Success! */
466 rc = 0;
467
468errout:
469 close(fd);
470 return rc;
471}
472
Ken Sumrall160b4d62013-04-22 12:15:39 -0700473static int validate_persistent_data_storage(struct crypt_mnt_ftr *crypt_ftr)
474{
475 if (crypt_ftr->persist_data_offset[0] + crypt_ftr->persist_data_size >
476 crypt_ftr->persist_data_offset[1]) {
477 SLOGE("Crypt_ftr persist data regions overlap");
478 return -1;
479 }
480
481 if (crypt_ftr->persist_data_offset[0] >= crypt_ftr->persist_data_offset[1]) {
482 SLOGE("Crypt_ftr persist data region 0 starts after region 1");
483 return -1;
484 }
485
486 if (((crypt_ftr->persist_data_offset[1] + crypt_ftr->persist_data_size) -
487 (crypt_ftr->persist_data_offset[0] - CRYPT_FOOTER_TO_PERSIST_OFFSET)) >
488 CRYPT_FOOTER_OFFSET) {
489 SLOGE("Persistent data extends past crypto footer");
490 return -1;
491 }
492
493 return 0;
494}
495
496static int load_persistent_data(void)
497{
498 struct crypt_mnt_ftr crypt_ftr;
499 struct crypt_persist_data *pdata = NULL;
500 char encrypted_state[PROPERTY_VALUE_MAX];
501 char *fname;
502 int found = 0;
503 int fd;
504 int ret;
505 int i;
506
507 if (persist_data) {
508 /* Nothing to do, we've already loaded or initialized it */
509 return 0;
510 }
511
512
513 /* If not encrypted, just allocate an empty table and initialize it */
514 property_get("ro.crypto.state", encrypted_state, "");
515 if (strcmp(encrypted_state, "encrypted") ) {
516 pdata = malloc(CRYPT_PERSIST_DATA_SIZE);
517 if (pdata) {
518 init_empty_persist_data(pdata, CRYPT_PERSIST_DATA_SIZE);
519 persist_data = pdata;
520 return 0;
521 }
522 return -1;
523 }
524
525 if(get_crypt_ftr_and_key(&crypt_ftr)) {
526 return -1;
527 }
528
529 if ((crypt_ftr.major_version != 1) || (crypt_ftr.minor_version != 1)) {
530 SLOGE("Crypt_ftr version doesn't support persistent data");
531 return -1;
532 }
533
534 if (get_crypt_ftr_info(&fname, NULL)) {
535 return -1;
536 }
537
538 ret = validate_persistent_data_storage(&crypt_ftr);
539 if (ret) {
540 return -1;
541 }
542
543 fd = open(fname, O_RDONLY);
544 if (fd < 0) {
545 SLOGE("Cannot open %s metadata file", fname);
546 return -1;
547 }
548
549 if (persist_data == NULL) {
550 pdata = malloc(crypt_ftr.persist_data_size);
551 if (pdata == NULL) {
552 SLOGE("Cannot allocate memory for persistent data");
553 goto err;
554 }
555 }
556
557 for (i = 0; i < 2; i++) {
558 if (lseek64(fd, crypt_ftr.persist_data_offset[i], SEEK_SET) < 0) {
559 SLOGE("Cannot seek to read persistent data on %s", fname);
560 goto err2;
561 }
562 if (unix_read(fd, pdata, crypt_ftr.persist_data_size) < 0){
563 SLOGE("Error reading persistent data on iteration %d", i);
564 goto err2;
565 }
566 if (pdata->persist_magic == PERSIST_DATA_MAGIC) {
567 found = 1;
568 break;
569 }
570 }
571
572 if (!found) {
573 SLOGI("Could not find valid persistent data, creating");
574 init_empty_persist_data(pdata, crypt_ftr.persist_data_size);
575 }
576
577 /* Success */
578 persist_data = pdata;
579 close(fd);
580 return 0;
581
582err2:
583 free(pdata);
584
585err:
586 close(fd);
587 return -1;
588}
589
590static int save_persistent_data(void)
591{
592 struct crypt_mnt_ftr crypt_ftr;
593 struct crypt_persist_data *pdata;
594 char *fname;
595 off64_t write_offset;
596 off64_t erase_offset;
597 int found = 0;
598 int fd;
599 int ret;
600
601 if (persist_data == NULL) {
602 SLOGE("No persistent data to save");
603 return -1;
604 }
605
606 if(get_crypt_ftr_and_key(&crypt_ftr)) {
607 return -1;
608 }
609
610 if ((crypt_ftr.major_version != 1) || (crypt_ftr.minor_version != 1)) {
611 SLOGE("Crypt_ftr version doesn't support persistent data");
612 return -1;
613 }
614
615 ret = validate_persistent_data_storage(&crypt_ftr);
616 if (ret) {
617 return -1;
618 }
619
620 if (get_crypt_ftr_info(&fname, NULL)) {
621 return -1;
622 }
623
624 fd = open(fname, O_RDWR);
625 if (fd < 0) {
626 SLOGE("Cannot open %s metadata file", fname);
627 return -1;
628 }
629
630 pdata = malloc(crypt_ftr.persist_data_size);
631 if (pdata == NULL) {
632 SLOGE("Cannot allocate persistant data");
633 goto err;
634 }
635
636 if (lseek64(fd, crypt_ftr.persist_data_offset[0], SEEK_SET) < 0) {
637 SLOGE("Cannot seek to read persistent data on %s", fname);
638 goto err2;
639 }
640
641 if (unix_read(fd, pdata, crypt_ftr.persist_data_size) < 0) {
642 SLOGE("Error reading persistent data before save");
643 goto err2;
644 }
645
646 if (pdata->persist_magic == PERSIST_DATA_MAGIC) {
647 /* The first copy is the curent valid copy, so write to
648 * the second copy and erase this one */
649 write_offset = crypt_ftr.persist_data_offset[1];
650 erase_offset = crypt_ftr.persist_data_offset[0];
651 } else {
652 /* The second copy must be the valid copy, so write to
653 * the first copy, and erase the second */
654 write_offset = crypt_ftr.persist_data_offset[0];
655 erase_offset = crypt_ftr.persist_data_offset[1];
656 }
657
658 /* Write the new copy first, if successful, then erase the old copy */
659 if (lseek(fd, write_offset, SEEK_SET) < 0) {
660 SLOGE("Cannot seek to write persistent data");
661 goto err2;
662 }
663 if (unix_write(fd, persist_data, crypt_ftr.persist_data_size) ==
664 (int) crypt_ftr.persist_data_size) {
665 if (lseek(fd, erase_offset, SEEK_SET) < 0) {
666 SLOGE("Cannot seek to erase previous persistent data");
667 goto err2;
668 }
669 fsync(fd);
670 memset(pdata, 0, crypt_ftr.persist_data_size);
671 if (unix_write(fd, pdata, crypt_ftr.persist_data_size) !=
672 (int) crypt_ftr.persist_data_size) {
673 SLOGE("Cannot write to erase previous persistent data");
674 goto err2;
675 }
676 fsync(fd);
677 } else {
678 SLOGE("Cannot write to save persistent data");
679 goto err2;
680 }
681
682 /* Success */
683 free(pdata);
684 close(fd);
685 return 0;
686
687err2:
688 free(pdata);
689err:
690 close(fd);
691 return -1;
692}
693
Paul Lawrencef4faa572014-01-29 13:31:03 -0800694static int hexdigit (char c)
695{
696 if (c >= '0' && c <= '9') return c - '0';
697 c = tolower(c);
698 if (c >= 'a' && c <= 'f') return c - 'a' + 10;
699 return -1;
700}
701
702static unsigned char* convert_hex_ascii_to_key(const char* master_key_ascii,
703 unsigned int* out_keysize)
704{
705 unsigned int i;
706 *out_keysize = 0;
707
708 size_t size = strlen (master_key_ascii);
709 if (size % 2) {
710 SLOGE("Trying to convert ascii string of odd length");
711 return NULL;
712 }
713
714 unsigned char* master_key = (unsigned char*) malloc(size / 2);
715 if (master_key == 0) {
716 SLOGE("Cannot allocate");
717 return NULL;
718 }
719
720 for (i = 0; i < size; i += 2) {
721 int high_nibble = hexdigit (master_key_ascii[i]);
722 int low_nibble = hexdigit (master_key_ascii[i + 1]);
723
724 if(high_nibble < 0 || low_nibble < 0) {
725 SLOGE("Invalid hex string");
726 free (master_key);
727 return NULL;
728 }
729
730 master_key[*out_keysize] = high_nibble * 16 + low_nibble;
731 (*out_keysize)++;
732 }
733
734 return master_key;
735}
736
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800737/* Convert a binary key of specified length into an ascii hex string equivalent,
738 * without the leading 0x and with null termination
739 */
Paul Lawrencef4faa572014-01-29 13:31:03 -0800740static void convert_key_to_hex_ascii(unsigned char *master_key, unsigned int keysize,
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800741 char *master_key_ascii)
742{
743 unsigned int i, a;
744 unsigned char nibble;
745
746 for (i=0, a=0; i<keysize; i++, a+=2) {
747 /* For each byte, write out two ascii hex digits */
748 nibble = (master_key[i] >> 4) & 0xf;
749 master_key_ascii[a] = nibble + (nibble > 9 ? 0x37 : 0x30);
750
751 nibble = master_key[i] & 0xf;
752 master_key_ascii[a+1] = nibble + (nibble > 9 ? 0x37 : 0x30);
753 }
754
755 /* Add the null termination */
756 master_key_ascii[a] = '\0';
757
758}
759
Ken Sumralldb5e0262013-02-05 17:39:48 -0800760static int load_crypto_mapping_table(struct crypt_mnt_ftr *crypt_ftr, unsigned char *master_key,
761 char *real_blk_name, const char *name, int fd,
762 char *extra_params)
763{
764 char buffer[DM_CRYPT_BUF_SIZE];
765 struct dm_ioctl *io;
766 struct dm_target_spec *tgt;
767 char *crypt_params;
768 char master_key_ascii[129]; /* Large enough to hold 512 bit key and null */
769 int i;
770
771 io = (struct dm_ioctl *) buffer;
772
773 /* Load the mapping table for this device */
774 tgt = (struct dm_target_spec *) &buffer[sizeof(struct dm_ioctl)];
775
776 ioctl_init(io, DM_CRYPT_BUF_SIZE, name, 0);
777 io->target_count = 1;
778 tgt->status = 0;
779 tgt->sector_start = 0;
780 tgt->length = crypt_ftr->fs_size;
781 strcpy(tgt->target_type, "crypt");
782
783 crypt_params = buffer + sizeof(struct dm_ioctl) + sizeof(struct dm_target_spec);
784 convert_key_to_hex_ascii(master_key, crypt_ftr->keysize, master_key_ascii);
785 sprintf(crypt_params, "%s %s 0 %s 0 %s", crypt_ftr->crypto_type_name,
786 master_key_ascii, real_blk_name, extra_params);
787 crypt_params += strlen(crypt_params) + 1;
788 crypt_params = (char *) (((unsigned long)crypt_params + 7) & ~8); /* Align to an 8 byte boundary */
789 tgt->next = crypt_params - buffer;
790
791 for (i = 0; i < TABLE_LOAD_RETRIES; i++) {
792 if (! ioctl(fd, DM_TABLE_LOAD, io)) {
793 break;
794 }
795 usleep(500000);
796 }
797
798 if (i == TABLE_LOAD_RETRIES) {
799 /* We failed to load the table, return an error */
800 return -1;
801 } else {
802 return i + 1;
803 }
804}
805
806
807static int get_dm_crypt_version(int fd, const char *name, int *version)
808{
809 char buffer[DM_CRYPT_BUF_SIZE];
810 struct dm_ioctl *io;
811 struct dm_target_versions *v;
812 int i;
813
814 io = (struct dm_ioctl *) buffer;
815
816 ioctl_init(io, DM_CRYPT_BUF_SIZE, name, 0);
817
818 if (ioctl(fd, DM_LIST_VERSIONS, io)) {
819 return -1;
820 }
821
822 /* Iterate over the returned versions, looking for name of "crypt".
823 * When found, get and return the version.
824 */
825 v = (struct dm_target_versions *) &buffer[sizeof(struct dm_ioctl)];
826 while (v->next) {
827 if (! strcmp(v->name, "crypt")) {
828 /* We found the crypt driver, return the version, and get out */
829 version[0] = v->version[0];
830 version[1] = v->version[1];
831 version[2] = v->version[2];
832 return 0;
833 }
834 v = (struct dm_target_versions *)(((char *)v) + v->next);
835 }
836
837 return -1;
838}
839
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800840static int create_crypto_blk_dev(struct crypt_mnt_ftr *crypt_ftr, unsigned char *master_key,
Ken Sumrall29d8da82011-05-18 17:20:07 -0700841 char *real_blk_name, char *crypto_blk_name, const char *name)
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800842{
843 char buffer[DM_CRYPT_BUF_SIZE];
844 char master_key_ascii[129]; /* Large enough to hold 512 bit key and null */
845 char *crypt_params;
846 struct dm_ioctl *io;
847 struct dm_target_spec *tgt;
848 unsigned int minor;
849 int fd;
Ken Sumralle919efe2012-09-29 17:07:41 -0700850 int i;
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800851 int retval = -1;
Ken Sumralldb5e0262013-02-05 17:39:48 -0800852 int version[3];
853 char *extra_params;
854 int load_count;
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800855
856 if ((fd = open("/dev/device-mapper", O_RDWR)) < 0 ) {
857 SLOGE("Cannot open device-mapper\n");
858 goto errout;
859 }
860
861 io = (struct dm_ioctl *) buffer;
862
863 ioctl_init(io, DM_CRYPT_BUF_SIZE, name, 0);
864 if (ioctl(fd, DM_DEV_CREATE, io)) {
865 SLOGE("Cannot create dm-crypt device\n");
866 goto errout;
867 }
868
869 /* Get the device status, in particular, the name of it's device file */
870 ioctl_init(io, DM_CRYPT_BUF_SIZE, name, 0);
871 if (ioctl(fd, DM_DEV_STATUS, io)) {
872 SLOGE("Cannot retrieve dm-crypt device status\n");
873 goto errout;
874 }
875 minor = (io->dev & 0xff) | ((io->dev >> 12) & 0xfff00);
876 snprintf(crypto_blk_name, MAXPATHLEN, "/dev/block/dm-%u", minor);
877
Ken Sumralldb5e0262013-02-05 17:39:48 -0800878 extra_params = "";
879 if (! get_dm_crypt_version(fd, name, version)) {
880 /* Support for allow_discards was added in version 1.11.0 */
881 if ((version[0] >= 2) ||
882 ((version[0] == 1) && (version[1] >= 11))) {
883 extra_params = "1 allow_discards";
884 SLOGI("Enabling support for allow_discards in dmcrypt.\n");
885 }
Ken Sumralle919efe2012-09-29 17:07:41 -0700886 }
887
Ken Sumralldb5e0262013-02-05 17:39:48 -0800888 load_count = load_crypto_mapping_table(crypt_ftr, master_key, real_blk_name, name,
889 fd, extra_params);
890 if (load_count < 0) {
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800891 SLOGE("Cannot load dm-crypt mapping table.\n");
892 goto errout;
Ken Sumralldb5e0262013-02-05 17:39:48 -0800893 } else if (load_count > 1) {
894 SLOGI("Took %d tries to load dmcrypt table.\n", load_count);
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800895 }
896
897 /* Resume this device to activate it */
Ken Sumralldb5e0262013-02-05 17:39:48 -0800898 ioctl_init(io, DM_CRYPT_BUF_SIZE, name, 0);
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800899
900 if (ioctl(fd, DM_DEV_SUSPEND, io)) {
901 SLOGE("Cannot resume the dm-crypt device\n");
902 goto errout;
903 }
904
905 /* We made it here with no errors. Woot! */
906 retval = 0;
907
908errout:
909 close(fd); /* If fd is <0 from a failed open call, it's safe to just ignore the close error */
910
911 return retval;
912}
913
Ken Sumrall29d8da82011-05-18 17:20:07 -0700914static int delete_crypto_blk_dev(char *name)
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800915{
916 int fd;
917 char buffer[DM_CRYPT_BUF_SIZE];
918 struct dm_ioctl *io;
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800919 int retval = -1;
920
921 if ((fd = open("/dev/device-mapper", O_RDWR)) < 0 ) {
922 SLOGE("Cannot open device-mapper\n");
923 goto errout;
924 }
925
926 io = (struct dm_ioctl *) buffer;
927
928 ioctl_init(io, DM_CRYPT_BUF_SIZE, name, 0);
929 if (ioctl(fd, DM_DEV_REMOVE, io)) {
930 SLOGE("Cannot remove dm-crypt device\n");
931 goto errout;
932 }
933
934 /* We made it here with no errors. Woot! */
935 retval = 0;
936
937errout:
938 close(fd); /* If fd is <0 from a failed open call, it's safe to just ignore the close error */
939
940 return retval;
941
942}
943
Paul Lawrence13486032014-02-03 13:28:11 -0800944static int pbkdf2(const char *passwd, unsigned char *salt,
Paul Lawrencef4faa572014-01-29 13:31:03 -0800945 unsigned char *ikey, void *params UNUSED)
946{
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800947 /* Turn the password into a key and IV that can decrypt the master key */
Paul Lawrencef4faa572014-01-29 13:31:03 -0800948 unsigned int keysize;
949 char* master_key = (char*)convert_hex_ascii_to_key(passwd, &keysize);
950 if (!master_key) return -1;
951 PKCS5_PBKDF2_HMAC_SHA1(master_key, keysize, salt, SALT_LEN,
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800952 HASH_COUNT, KEY_LEN_BYTES+IV_LEN_BYTES, ikey);
Paul Lawrencef4faa572014-01-29 13:31:03 -0800953
954 free (master_key);
955 return 0;
Ken Sumrall8ddbe402011-01-17 15:26:29 -0800956}
957
Paul Lawrence13486032014-02-03 13:28:11 -0800958static int scrypt(const char *passwd, unsigned char *salt,
Paul Lawrencef4faa572014-01-29 13:31:03 -0800959 unsigned char *ikey, void *params)
960{
Kenny Rootc4c70f12013-06-14 12:11:38 -0700961 struct crypt_mnt_ftr *ftr = (struct crypt_mnt_ftr *) params;
962
963 int N = 1 << ftr->N_factor;
964 int r = 1 << ftr->r_factor;
965 int p = 1 << ftr->p_factor;
966
967 /* Turn the password into a key and IV that can decrypt the master key */
Paul Lawrencef4faa572014-01-29 13:31:03 -0800968 unsigned int keysize;
969 unsigned char* master_key = convert_hex_ascii_to_key(passwd, &keysize);
970 if (!master_key) return -1;
971 crypto_scrypt(master_key, keysize, salt, SALT_LEN, N, r, p, ikey,
Kenny Rootc4c70f12013-06-14 12:11:38 -0700972 KEY_LEN_BYTES + IV_LEN_BYTES);
Paul Lawrencef4faa572014-01-29 13:31:03 -0800973
974 free (master_key);
975 return 0;
Kenny Rootc4c70f12013-06-14 12:11:38 -0700976}
977
Paul Lawrence13486032014-02-03 13:28:11 -0800978static int encrypt_master_key(const char *passwd, unsigned char *salt,
Ken Sumralle8744072011-01-18 22:01:55 -0800979 unsigned char *decrypted_master_key,
Kenny Rootc4c70f12013-06-14 12:11:38 -0700980 unsigned char *encrypted_master_key,
981 struct crypt_mnt_ftr *crypt_ftr)
Ken Sumrall8ddbe402011-01-17 15:26:29 -0800982{
983 unsigned char ikey[32+32] = { 0 }; /* Big enough to hold a 256 bit key and 256 bit IV */
984 EVP_CIPHER_CTX e_ctx;
985 int encrypted_len, final_len;
986
987 /* Turn the password into a key and IV that can decrypt the master key */
Kenny Rootc4c70f12013-06-14 12:11:38 -0700988 get_device_scrypt_params(crypt_ftr);
Paul Lawrencef4faa572014-01-29 13:31:03 -0800989 if (scrypt(passwd, salt, ikey, crypt_ftr)) {
990 SLOGE("scrypt failed");
991 return -1;
992 }
Kenny Rootc4c70f12013-06-14 12:11:38 -0700993
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800994 /* Initialize the decryption engine */
995 if (! EVP_EncryptInit(&e_ctx, EVP_aes_128_cbc(), ikey, ikey+KEY_LEN_BYTES)) {
996 SLOGE("EVP_EncryptInit failed\n");
997 return -1;
998 }
999 EVP_CIPHER_CTX_set_padding(&e_ctx, 0); /* Turn off padding as our data is block aligned */
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001000
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001001 /* Encrypt the master key */
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001002 if (! EVP_EncryptUpdate(&e_ctx, encrypted_master_key, &encrypted_len,
1003 decrypted_master_key, KEY_LEN_BYTES)) {
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001004 SLOGE("EVP_EncryptUpdate failed\n");
1005 return -1;
1006 }
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001007 if (! EVP_EncryptFinal(&e_ctx, encrypted_master_key + encrypted_len, &final_len)) {
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001008 SLOGE("EVP_EncryptFinal failed\n");
1009 return -1;
1010 }
1011
1012 if (encrypted_len + final_len != KEY_LEN_BYTES) {
1013 SLOGE("EVP_Encryption length check failed with %d, %d bytes\n", encrypted_len, final_len);
1014 return -1;
1015 } else {
1016 return 0;
1017 }
1018}
1019
JP Abgrall7bdfa522013-11-15 13:42:56 -08001020static int decrypt_master_key_aux(char *passwd, unsigned char *salt,
Ken Sumralle8744072011-01-18 22:01:55 -08001021 unsigned char *encrypted_master_key,
Kenny Rootc4c70f12013-06-14 12:11:38 -07001022 unsigned char *decrypted_master_key,
1023 kdf_func kdf, void *kdf_params)
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001024{
1025 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 -08001026 EVP_CIPHER_CTX d_ctx;
1027 int decrypted_len, final_len;
1028
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001029 /* Turn the password into a key and IV that can decrypt the master key */
Paul Lawrencef4faa572014-01-29 13:31:03 -08001030 if (kdf(passwd, salt, ikey, kdf_params)) {
1031 SLOGE("kdf failed");
1032 return -1;
1033 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001034
1035 /* Initialize the decryption engine */
1036 if (! EVP_DecryptInit(&d_ctx, EVP_aes_128_cbc(), ikey, ikey+KEY_LEN_BYTES)) {
1037 return -1;
1038 }
1039 EVP_CIPHER_CTX_set_padding(&d_ctx, 0); /* Turn off padding as our data is block aligned */
1040 /* Decrypt the master key */
1041 if (! EVP_DecryptUpdate(&d_ctx, decrypted_master_key, &decrypted_len,
1042 encrypted_master_key, KEY_LEN_BYTES)) {
1043 return -1;
1044 }
1045 if (! EVP_DecryptFinal(&d_ctx, decrypted_master_key + decrypted_len, &final_len)) {
1046 return -1;
1047 }
1048
1049 if (decrypted_len + final_len != KEY_LEN_BYTES) {
1050 return -1;
1051 } else {
1052 return 0;
1053 }
1054}
1055
Kenny Rootc4c70f12013-06-14 12:11:38 -07001056static void get_kdf_func(struct crypt_mnt_ftr *ftr, kdf_func *kdf, void** kdf_params)
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001057{
Kenny Rootc4c70f12013-06-14 12:11:38 -07001058 if (ftr->kdf_type == KDF_SCRYPT) {
1059 *kdf = scrypt;
1060 *kdf_params = ftr;
1061 } else {
1062 *kdf = pbkdf2;
1063 *kdf_params = NULL;
1064 }
1065}
1066
JP Abgrall7bdfa522013-11-15 13:42:56 -08001067static int decrypt_master_key(char *passwd, unsigned char *decrypted_master_key,
Kenny Rootc4c70f12013-06-14 12:11:38 -07001068 struct crypt_mnt_ftr *crypt_ftr)
1069{
1070 kdf_func kdf;
1071 void *kdf_params;
1072 int ret;
1073
1074 get_kdf_func(crypt_ftr, &kdf, &kdf_params);
JP Abgrall7bdfa522013-11-15 13:42:56 -08001075 ret = decrypt_master_key_aux(passwd, crypt_ftr->salt, crypt_ftr->master_key, decrypted_master_key, kdf,
Kenny Rootc4c70f12013-06-14 12:11:38 -07001076 kdf_params);
1077 if (ret != 0) {
1078 SLOGW("failure decrypting master key");
Kenny Rootc4c70f12013-06-14 12:11:38 -07001079 }
1080
1081 return ret;
1082}
1083
1084static int create_encrypted_random_key(char *passwd, unsigned char *master_key, unsigned char *salt,
1085 struct crypt_mnt_ftr *crypt_ftr) {
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001086 int fd;
Ken Sumralle8744072011-01-18 22:01:55 -08001087 unsigned char key_buf[KEY_LEN_BYTES];
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001088 EVP_CIPHER_CTX e_ctx;
1089 int encrypted_len, final_len;
1090
1091 /* Get some random bits for a key */
1092 fd = open("/dev/urandom", O_RDONLY);
Ken Sumralle8744072011-01-18 22:01:55 -08001093 read(fd, key_buf, sizeof(key_buf));
1094 read(fd, salt, SALT_LEN);
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001095 close(fd);
1096
1097 /* Now encrypt it with the password */
Kenny Rootc4c70f12013-06-14 12:11:38 -07001098 return encrypt_master_key(passwd, salt, key_buf, master_key, crypt_ftr);
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001099}
1100
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001101static int wait_and_unmount(char *mountpoint)
1102{
1103 int i, rc;
Ken Sumrall2eaf7132011-01-14 12:45:48 -08001104#define WAIT_UNMOUNT_COUNT 20
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001105
1106 /* Now umount the tmpfs filesystem */
1107 for (i=0; i<WAIT_UNMOUNT_COUNT; i++) {
1108 if (umount(mountpoint)) {
Ken Sumrall29d8da82011-05-18 17:20:07 -07001109 if (errno == EINVAL) {
1110 /* EINVAL is returned if the directory is not a mountpoint,
1111 * i.e. there is no filesystem mounted there. So just get out.
1112 */
1113 break;
1114 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001115 sleep(1);
1116 i++;
1117 } else {
1118 break;
1119 }
1120 }
1121
1122 if (i < WAIT_UNMOUNT_COUNT) {
1123 SLOGD("unmounting %s succeeded\n", mountpoint);
1124 rc = 0;
1125 } else {
1126 SLOGE("unmounting %s failed\n", mountpoint);
1127 rc = -1;
1128 }
1129
1130 return rc;
1131}
1132
Ken Sumrallc5872692013-05-14 15:26:31 -07001133#define DATA_PREP_TIMEOUT 200
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001134static int prep_data_fs(void)
1135{
1136 int i;
1137
1138 /* Do the prep of the /data filesystem */
1139 property_set("vold.post_fs_data_done", "0");
1140 property_set("vold.decrypt", "trigger_post_fs_data");
1141 SLOGD("Just triggered post_fs_data\n");
1142
Ken Sumrallc5872692013-05-14 15:26:31 -07001143 /* Wait a max of 50 seconds, hopefully it takes much less */
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001144 for (i=0; i<DATA_PREP_TIMEOUT; i++) {
Ken Sumrall29d8da82011-05-18 17:20:07 -07001145 char p[PROPERTY_VALUE_MAX];
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001146
1147 property_get("vold.post_fs_data_done", p, "0");
1148 if (*p == '1') {
1149 break;
1150 } else {
1151 usleep(250000);
1152 }
1153 }
1154 if (i == DATA_PREP_TIMEOUT) {
1155 /* Ugh, we failed to prep /data in time. Bail. */
Ken Sumrallc5872692013-05-14 15:26:31 -07001156 SLOGE("post_fs_data timed out!\n");
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001157 return -1;
1158 } else {
1159 SLOGD("post_fs_data done\n");
1160 return 0;
1161 }
1162}
1163
Paul Lawrencef4faa572014-01-29 13:31:03 -08001164static int cryptfs_restart_internal(int restart_main)
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001165{
1166 char fs_type[32];
1167 char real_blkdev[MAXPATHLEN];
Ken Sumrall6864b7e2011-01-14 15:20:02 -08001168 char crypto_blkdev[MAXPATHLEN];
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001169 char fs_options[256];
1170 unsigned long mnt_flags;
1171 struct stat statbuf;
1172 int rc = -1, i;
Ken Sumrall0cc16632011-01-18 20:32:26 -08001173 static int restart_successful = 0;
1174
1175 /* Validate that it's OK to call this routine */
Jason parks70a4b3f2011-01-28 10:10:47 -06001176 if (! master_key_saved) {
Ken Sumrall0cc16632011-01-18 20:32:26 -08001177 SLOGE("Encrypted filesystem not validated, aborting");
1178 return -1;
1179 }
1180
1181 if (restart_successful) {
1182 SLOGE("System already restarted with encrypted disk, aborting");
1183 return -1;
1184 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001185
Paul Lawrencef4faa572014-01-29 13:31:03 -08001186 if (restart_main) {
1187 /* Here is where we shut down the framework. The init scripts
1188 * start all services in one of three classes: core, main or late_start.
1189 * On boot, we start core and main. Now, we stop main, but not core,
1190 * as core includes vold and a few other really important things that
1191 * we need to keep running. Once main has stopped, we should be able
1192 * to umount the tmpfs /data, then mount the encrypted /data.
1193 * We then restart the class main, and also the class late_start.
1194 * At the moment, I've only put a few things in late_start that I know
1195 * are not needed to bring up the framework, and that also cause problems
1196 * with unmounting the tmpfs /data, but I hope to add add more services
1197 * to the late_start class as we optimize this to decrease the delay
1198 * till the user is asked for the password to the filesystem.
1199 */
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001200
Paul Lawrencef4faa572014-01-29 13:31:03 -08001201 /* The init files are setup to stop the class main when vold.decrypt is
1202 * set to trigger_reset_main.
1203 */
1204 property_set("vold.decrypt", "trigger_reset_main");
1205 SLOGD("Just asked init to shut down class main\n");
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001206
Paul Lawrencef4faa572014-01-29 13:31:03 -08001207 /* Ugh, shutting down the framework is not synchronous, so until it
1208 * can be fixed, this horrible hack will wait a moment for it all to
1209 * shut down before proceeding. Without it, some devices cannot
1210 * restart the graphics services.
1211 */
1212 sleep(2);
1213 }
Ken Sumrall9dedfd42012-10-09 14:16:59 -07001214
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001215 /* Now that the framework is shutdown, we should be able to umount()
1216 * the tmpfs filesystem, and mount the real one.
1217 */
1218
Ken Sumrall6864b7e2011-01-14 15:20:02 -08001219 property_get("ro.crypto.fs_crypto_blkdev", crypto_blkdev, "");
1220 if (strlen(crypto_blkdev) == 0) {
1221 SLOGE("fs_crypto_blkdev not set\n");
1222 return -1;
1223 }
1224
Ken Sumralle5032c42012-04-01 23:58:44 -07001225 if (! (rc = wait_and_unmount(DATA_MNT_POINT)) ) {
Doug Zongker6fd57712013-12-17 09:43:23 -08001226 /* If ro.crypto.readonly is set to 1, mount the decrypted
1227 * filesystem readonly. This is used when /data is mounted by
1228 * recovery mode.
1229 */
1230 char ro_prop[PROPERTY_VALUE_MAX];
1231 property_get("ro.crypto.readonly", ro_prop, "");
1232 if (strlen(ro_prop) > 0 && atoi(ro_prop)) {
1233 struct fstab_rec* rec = fs_mgr_get_entry_for_mount_point(fstab, DATA_MNT_POINT);
1234 rec->flags |= MS_RDONLY;
1235 }
1236
Ken Sumralle5032c42012-04-01 23:58:44 -07001237 /* If that succeeded, then mount the decrypted filesystem */
Ken Sumrall56ad03c2013-02-13 13:00:19 -08001238 fs_mgr_do_mount(fstab, DATA_MNT_POINT, crypto_blkdev, 0);
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001239
Ken Sumralle5032c42012-04-01 23:58:44 -07001240 property_set("vold.decrypt", "trigger_load_persist_props");
1241 /* Create necessary paths on /data */
1242 if (prep_data_fs()) {
1243 return -1;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001244 }
Ken Sumralle5032c42012-04-01 23:58:44 -07001245
1246 /* startup service classes main and late_start */
1247 property_set("vold.decrypt", "trigger_restart_framework");
1248 SLOGD("Just triggered restart_framework\n");
1249
1250 /* Give it a few moments to get started */
1251 sleep(1);
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001252 }
1253
Ken Sumrall0cc16632011-01-18 20:32:26 -08001254 if (rc == 0) {
1255 restart_successful = 1;
1256 }
1257
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001258 return rc;
1259}
1260
Paul Lawrencef4faa572014-01-29 13:31:03 -08001261int cryptfs_restart(void)
1262{
1263 /* Call internal implementation forcing a restart of main service group */
1264 return cryptfs_restart_internal(1);
1265}
1266
Mark Salyzyn3e971272014-01-21 13:27:04 -08001267static int do_crypto_complete(char *mount_point UNUSED)
Ken Sumrall7f7dbaa2011-02-01 15:46:41 -08001268{
1269 struct crypt_mnt_ftr crypt_ftr;
Ken Sumrall29d8da82011-05-18 17:20:07 -07001270 char encrypted_state[PROPERTY_VALUE_MAX];
Ken Sumralle1a45852011-12-14 21:24:27 -08001271 char key_loc[PROPERTY_VALUE_MAX];
Ken Sumrall7f7dbaa2011-02-01 15:46:41 -08001272
1273 property_get("ro.crypto.state", encrypted_state, "");
1274 if (strcmp(encrypted_state, "encrypted") ) {
1275 SLOGE("not running with encryption, aborting");
1276 return 1;
1277 }
1278
Ken Sumrall160b4d62013-04-22 12:15:39 -07001279 if (get_crypt_ftr_and_key(&crypt_ftr)) {
Ken Sumrall56ad03c2013-02-13 13:00:19 -08001280 fs_mgr_get_crypt_info(fstab, key_loc, 0, sizeof(key_loc));
Ken Sumralle5032c42012-04-01 23:58:44 -07001281
Ken Sumralle1a45852011-12-14 21:24:27 -08001282 /*
1283 * Only report this error if key_loc is a file and it exists.
1284 * If the device was never encrypted, and /data is not mountable for
1285 * some reason, returning 1 should prevent the UI from presenting the
1286 * a "enter password" screen, or worse, a "press button to wipe the
1287 * device" screen.
1288 */
1289 if ((key_loc[0] == '/') && (access("key_loc", F_OK) == -1)) {
1290 SLOGE("master key file does not exist, aborting");
1291 return 1;
1292 } else {
1293 SLOGE("Error getting crypt footer and key\n");
1294 return -1;
1295 }
Ken Sumrall7f7dbaa2011-02-01 15:46:41 -08001296 }
1297
1298 if (crypt_ftr.flags & CRYPT_ENCRYPTION_IN_PROGRESS) {
1299 SLOGE("Encryption process didn't finish successfully\n");
1300 return -2; /* -2 is the clue to the UI that there is no usable data on the disk,
1301 * and give the user an option to wipe the disk */
1302 }
1303
1304 /* We passed the test! We shall diminish, and return to the west */
1305 return 0;
1306}
1307
Paul Lawrencef4faa572014-01-29 13:31:03 -08001308static int test_mount_encrypted_fs(struct crypt_mnt_ftr* crypt_ftr,
1309 char *passwd, char *mount_point, char *label)
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001310{
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001311 /* Allocate enough space for a 256 bit key, but we may use less */
Ken Sumrall160b4d62013-04-22 12:15:39 -07001312 unsigned char decrypted_master_key[32];
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001313 char crypto_blkdev[MAXPATHLEN];
1314 char real_blkdev[MAXPATHLEN];
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001315 char tmp_mount_point[64];
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001316 unsigned int orig_failed_decrypt_count;
1317 int rc;
Kenny Rootc4c70f12013-06-14 12:11:38 -07001318 kdf_func kdf;
1319 void *kdf_params;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001320
Paul Lawrencef4faa572014-01-29 13:31:03 -08001321 SLOGD("crypt_ftr->fs_size = %lld\n", crypt_ftr->fs_size);
1322 orig_failed_decrypt_count = crypt_ftr->failed_decrypt_count;
Ken Sumrall0cc16632011-01-18 20:32:26 -08001323
Paul Lawrencef4faa572014-01-29 13:31:03 -08001324 if (! (crypt_ftr->flags & CRYPT_MNT_KEY_UNENCRYPTED) ) {
1325 if (decrypt_master_key(passwd, decrypted_master_key, crypt_ftr)) {
JP Abgrall7bdfa522013-11-15 13:42:56 -08001326 SLOGE("Failed to decrypt master key\n");
1327 return -1;
1328 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001329 }
1330
Paul Lawrencef4faa572014-01-29 13:31:03 -08001331 fs_mgr_get_crypt_info(fstab, 0, real_blkdev, sizeof(real_blkdev));
1332
1333 if (create_crypto_blk_dev(crypt_ftr, decrypted_master_key,
1334 real_blkdev, crypto_blkdev, label)) {
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001335 SLOGE("Error creating decrypted block device\n");
1336 return -1;
1337 }
1338
Alex Klyubin707795a2013-05-10 15:17:07 -07001339 /* If init detects an encrypted filesystem, it writes a file for each such
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001340 * encrypted fs into the tmpfs /data filesystem, and then the framework finds those
1341 * files and passes that data to me */
1342 /* Create a tmp mount point to try mounting the decryptd fs
1343 * Since we're here, the mount_point should be a tmpfs filesystem, so make
1344 * a directory in it to test mount the decrypted filesystem.
1345 */
1346 sprintf(tmp_mount_point, "%s/tmp_mnt", mount_point);
1347 mkdir(tmp_mount_point, 0755);
Ken Sumrall56ad03c2013-02-13 13:00:19 -08001348 if (fs_mgr_do_mount(fstab, DATA_MNT_POINT, crypto_blkdev, tmp_mount_point)) {
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001349 SLOGE("Error temp mounting decrypted block device\n");
Ken Sumrall29d8da82011-05-18 17:20:07 -07001350 delete_crypto_blk_dev(label);
Paul Lawrencef4faa572014-01-29 13:31:03 -08001351 crypt_ftr->failed_decrypt_count++;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001352 } else {
1353 /* Success, so just umount and we'll mount it properly when we restart
1354 * the framework.
1355 */
1356 umount(tmp_mount_point);
Paul Lawrencef4faa572014-01-29 13:31:03 -08001357 crypt_ftr->failed_decrypt_count = 0;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001358 }
1359
Paul Lawrencef4faa572014-01-29 13:31:03 -08001360 if (orig_failed_decrypt_count != crypt_ftr->failed_decrypt_count) {
1361 put_crypt_ftr_and_key(crypt_ftr);
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001362 }
1363
Paul Lawrencef4faa572014-01-29 13:31:03 -08001364 if (crypt_ftr->failed_decrypt_count) {
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001365 /* We failed to mount the device, so return an error */
Paul Lawrencef4faa572014-01-29 13:31:03 -08001366 rc = crypt_ftr->failed_decrypt_count;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001367
1368 } else {
Ken Sumrall6864b7e2011-01-14 15:20:02 -08001369 /* Woot! Success! Save the name of the crypto block device
1370 * so we can mount it when restarting the framework.
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001371 */
Ken Sumrall6864b7e2011-01-14 15:20:02 -08001372 property_set("ro.crypto.fs_crypto_blkdev", crypto_blkdev);
Jason parks70a4b3f2011-01-28 10:10:47 -06001373
1374 /* Also save a the master key so we can reencrypted the key
1375 * the key when we want to change the password on it.
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001376 */
Jason parks70a4b3f2011-01-28 10:10:47 -06001377 memcpy(saved_master_key, decrypted_master_key, KEY_LEN_BYTES);
Ken Sumrall3ad90722011-10-04 20:38:29 -07001378 saved_mount_point = strdup(mount_point);
Jason parks70a4b3f2011-01-28 10:10:47 -06001379 master_key_saved = 1;
JP Abgrall7bdfa522013-11-15 13:42:56 -08001380 SLOGD("%s(): Master key saved\n", __FUNCTION__);
Ken Sumrall6864b7e2011-01-14 15:20:02 -08001381 rc = 0;
JP Abgrall7bdfa522013-11-15 13:42:56 -08001382 /*
1383 * Upgrade if we're not using the latest KDF.
1384 */
Paul Lawrencef4faa572014-01-29 13:31:03 -08001385 if (crypt_ftr->kdf_type != KDF_SCRYPT) {
1386 crypt_ftr->kdf_type = KDF_SCRYPT;
1387 rc = encrypt_master_key(passwd, crypt_ftr->salt, saved_master_key,
1388 crypt_ftr->master_key, crypt_ftr);
JP Abgrall7bdfa522013-11-15 13:42:56 -08001389 if (!rc) {
Paul Lawrencef4faa572014-01-29 13:31:03 -08001390 rc = put_crypt_ftr_and_key(crypt_ftr);
JP Abgrall7bdfa522013-11-15 13:42:56 -08001391 }
1392 SLOGD("Key Derivation Function upgrade: rc=%d\n", rc);
1393 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001394 }
1395
1396 return rc;
1397}
1398
Ken Sumrall0b8b5972011-08-31 16:14:23 -07001399/* Called by vold when it wants to undo the crypto mapping of a volume it
1400 * manages. This is usually in response to a factory reset, when we want
1401 * to undo the crypto mapping so the volume is formatted in the clear.
1402 */
1403int cryptfs_revert_volume(const char *label)
1404{
1405 return delete_crypto_blk_dev((char *)label);
1406}
1407
Ken Sumrall29d8da82011-05-18 17:20:07 -07001408/*
1409 * Called by vold when it's asked to mount an encrypted, nonremovable volume.
1410 * Setup a dm-crypt mapping, use the saved master key from
1411 * setting up the /data mapping, and return the new device path.
1412 */
1413int cryptfs_setup_volume(const char *label, int major, int minor,
1414 char *crypto_sys_path, unsigned int max_path,
1415 int *new_major, int *new_minor)
1416{
1417 char real_blkdev[MAXPATHLEN], crypto_blkdev[MAXPATHLEN];
1418 struct crypt_mnt_ftr sd_crypt_ftr;
Ken Sumrall29d8da82011-05-18 17:20:07 -07001419 struct stat statbuf;
1420 int nr_sec, fd;
1421
1422 sprintf(real_blkdev, "/dev/block/vold/%d:%d", major, minor);
1423
Ken Sumrall160b4d62013-04-22 12:15:39 -07001424 get_crypt_ftr_and_key(&sd_crypt_ftr);
Ken Sumrall29d8da82011-05-18 17:20:07 -07001425
1426 /* Update the fs_size field to be the size of the volume */
1427 fd = open(real_blkdev, O_RDONLY);
1428 nr_sec = get_blkdev_size(fd);
1429 close(fd);
1430 if (nr_sec == 0) {
1431 SLOGE("Cannot get size of volume %s\n", real_blkdev);
1432 return -1;
1433 }
1434
1435 sd_crypt_ftr.fs_size = nr_sec;
1436 create_crypto_blk_dev(&sd_crypt_ftr, saved_master_key, real_blkdev,
1437 crypto_blkdev, label);
1438
1439 stat(crypto_blkdev, &statbuf);
1440 *new_major = MAJOR(statbuf.st_rdev);
1441 *new_minor = MINOR(statbuf.st_rdev);
1442
1443 /* Create path to sys entry for this block device */
1444 snprintf(crypto_sys_path, max_path, "/devices/virtual/block/%s", strrchr(crypto_blkdev, '/')+1);
1445
1446 return 0;
1447}
1448
Ken Sumrall7f7dbaa2011-02-01 15:46:41 -08001449int cryptfs_crypto_complete(void)
1450{
1451 return do_crypto_complete("/data");
1452}
1453
Paul Lawrencef4faa572014-01-29 13:31:03 -08001454int check_unmounted_and_get_ftr(struct crypt_mnt_ftr* crypt_ftr)
1455{
1456 char encrypted_state[PROPERTY_VALUE_MAX];
1457 property_get("ro.crypto.state", encrypted_state, "");
1458 if ( master_key_saved || strcmp(encrypted_state, "encrypted") ) {
1459 SLOGE("encrypted fs already validated or not running with encryption,"
1460 " aborting");
1461 return -1;
1462 }
1463
1464 if (get_crypt_ftr_and_key(crypt_ftr)) {
1465 SLOGE("Error getting crypt footer and key");
1466 return -1;
1467 }
1468
1469 return 0;
1470}
1471
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001472int cryptfs_check_passwd(char *passwd)
1473{
Paul Lawrencef4faa572014-01-29 13:31:03 -08001474 struct crypt_mnt_ftr crypt_ftr;
1475 int rc;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001476
Paul Lawrencef4faa572014-01-29 13:31:03 -08001477 rc = check_unmounted_and_get_ftr(&crypt_ftr);
1478 if (rc)
1479 return rc;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001480
Paul Lawrencef4faa572014-01-29 13:31:03 -08001481 rc = test_mount_encrypted_fs(&crypt_ftr, passwd,
1482 DATA_MNT_POINT, "userdata");
Paul Lawrence684dbdf2014-02-07 12:07:22 -08001483
1484 if (rc == 0 && crypt_ftr.crypt_type != CRYPT_TYPE_DEFAULT) {
1485 just_decrypted = 1;
1486 }
1487
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001488 return rc;
1489}
1490
Ken Sumrall3ad90722011-10-04 20:38:29 -07001491int cryptfs_verify_passwd(char *passwd)
1492{
1493 struct crypt_mnt_ftr crypt_ftr;
1494 /* Allocate enough space for a 256 bit key, but we may use less */
Ken Sumrall160b4d62013-04-22 12:15:39 -07001495 unsigned char decrypted_master_key[32];
Ken Sumrall3ad90722011-10-04 20:38:29 -07001496 char encrypted_state[PROPERTY_VALUE_MAX];
1497 int rc;
1498
1499 property_get("ro.crypto.state", encrypted_state, "");
1500 if (strcmp(encrypted_state, "encrypted") ) {
1501 SLOGE("device not encrypted, aborting");
1502 return -2;
1503 }
1504
1505 if (!master_key_saved) {
1506 SLOGE("encrypted fs not yet mounted, aborting");
1507 return -1;
1508 }
1509
1510 if (!saved_mount_point) {
1511 SLOGE("encrypted fs failed to save mount point, aborting");
1512 return -1;
1513 }
1514
Ken Sumrall160b4d62013-04-22 12:15:39 -07001515 if (get_crypt_ftr_and_key(&crypt_ftr)) {
Ken Sumrall3ad90722011-10-04 20:38:29 -07001516 SLOGE("Error getting crypt footer and key\n");
1517 return -1;
1518 }
1519
1520 if (crypt_ftr.flags & CRYPT_MNT_KEY_UNENCRYPTED) {
1521 /* If the device has no password, then just say the password is valid */
1522 rc = 0;
1523 } else {
JP Abgrall7bdfa522013-11-15 13:42:56 -08001524 decrypt_master_key(passwd, decrypted_master_key, &crypt_ftr);
Ken Sumrall3ad90722011-10-04 20:38:29 -07001525 if (!memcmp(decrypted_master_key, saved_master_key, crypt_ftr.keysize)) {
1526 /* They match, the password is correct */
1527 rc = 0;
1528 } else {
1529 /* If incorrect, sleep for a bit to prevent dictionary attacks */
1530 sleep(1);
1531 rc = 1;
1532 }
1533 }
1534
1535 return rc;
1536}
1537
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001538/* Initialize a crypt_mnt_ftr structure. The keysize is
1539 * defaulted to 16 bytes, and the filesystem size to 0.
1540 * Presumably, at a minimum, the caller will update the
1541 * filesystem size and crypto_type_name after calling this function.
1542 */
1543static void cryptfs_init_crypt_mnt_ftr(struct crypt_mnt_ftr *ftr)
1544{
Ken Sumrall160b4d62013-04-22 12:15:39 -07001545 off64_t off;
1546
1547 memset(ftr, 0, sizeof(struct crypt_mnt_ftr));
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001548 ftr->magic = CRYPT_MNT_MAGIC;
Kenny Rootc96a5f82013-06-14 12:08:28 -07001549 ftr->major_version = CURRENT_MAJOR_VERSION;
1550 ftr->minor_version = CURRENT_MINOR_VERSION;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001551 ftr->ftr_size = sizeof(struct crypt_mnt_ftr);
Jason parks70a4b3f2011-01-28 10:10:47 -06001552 ftr->keysize = KEY_LEN_BYTES;
Ken Sumrall160b4d62013-04-22 12:15:39 -07001553
Kenny Rootc4c70f12013-06-14 12:11:38 -07001554 ftr->kdf_type = KDF_SCRYPT;
1555 get_device_scrypt_params(ftr);
1556
Ken Sumrall160b4d62013-04-22 12:15:39 -07001557 ftr->persist_data_size = CRYPT_PERSIST_DATA_SIZE;
1558 if (get_crypt_ftr_info(NULL, &off) == 0) {
1559 ftr->persist_data_offset[0] = off + CRYPT_FOOTER_TO_PERSIST_OFFSET;
1560 ftr->persist_data_offset[1] = off + CRYPT_FOOTER_TO_PERSIST_OFFSET +
1561 ftr->persist_data_size;
1562 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001563}
1564
Ken Sumrall29d8da82011-05-18 17:20:07 -07001565static int cryptfs_enable_wipe(char *crypto_blkdev, off64_t size, int type)
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001566{
Ken Sumralle550f782013-08-20 13:48:23 -07001567 const char *args[10];
1568 char size_str[32]; /* Must be large enough to hold a %lld and null byte */
1569 int num_args;
1570 int status;
1571 int tmp;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001572 int rc = -1;
1573
Ken Sumrall29d8da82011-05-18 17:20:07 -07001574 if (type == EXT4_FS) {
Ken Sumralle550f782013-08-20 13:48:23 -07001575 args[0] = "/system/bin/make_ext4fs";
1576 args[1] = "-a";
1577 args[2] = "/data";
1578 args[3] = "-l";
1579 snprintf(size_str, sizeof(size_str), "%lld", size * 512);
1580 args[4] = size_str;
1581 args[5] = crypto_blkdev;
1582 num_args = 6;
1583 SLOGI("Making empty filesystem with command %s %s %s %s %s %s\n",
1584 args[0], args[1], args[2], args[3], args[4], args[5]);
Ken Sumrall29d8da82011-05-18 17:20:07 -07001585 } else if (type== FAT_FS) {
Ken Sumralle550f782013-08-20 13:48:23 -07001586 args[0] = "/system/bin/newfs_msdos";
1587 args[1] = "-F";
1588 args[2] = "32";
1589 args[3] = "-O";
1590 args[4] = "android";
1591 args[5] = "-c";
1592 args[6] = "8";
1593 args[7] = "-s";
1594 snprintf(size_str, sizeof(size_str), "%lld", size);
1595 args[8] = size_str;
1596 args[9] = crypto_blkdev;
1597 num_args = 10;
1598 SLOGI("Making empty filesystem with command %s %s %s %s %s %s %s %s %s %s\n",
1599 args[0], args[1], args[2], args[3], args[4], args[5],
1600 args[6], args[7], args[8], args[9]);
Ken Sumrall29d8da82011-05-18 17:20:07 -07001601 } else {
1602 SLOGE("cryptfs_enable_wipe(): unknown filesystem type %d\n", type);
1603 return -1;
1604 }
1605
Ken Sumralle550f782013-08-20 13:48:23 -07001606 tmp = android_fork_execvp(num_args, (char **)args, &status, false, true);
1607
1608 if (tmp != 0) {
1609 SLOGE("Error creating empty filesystem on %s due to logwrap error\n", crypto_blkdev);
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001610 } else {
Ken Sumralle550f782013-08-20 13:48:23 -07001611 if (WIFEXITED(status)) {
1612 if (WEXITSTATUS(status)) {
1613 SLOGE("Error creating filesystem on %s, exit status %d ",
1614 crypto_blkdev, WEXITSTATUS(status));
1615 } else {
1616 SLOGD("Successfully created filesystem on %s\n", crypto_blkdev);
1617 rc = 0;
1618 }
1619 } else {
1620 SLOGE("Error creating filesystem on %s, did not exit normally\n", crypto_blkdev);
1621 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001622 }
1623
1624 return rc;
1625}
1626
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001627#define CRYPT_INPLACE_BUFSIZE 4096
Paul Lawrence87999172014-02-20 12:21:31 -08001628#define CRYPT_SECTORS_PER_BUFSIZE (CRYPT_INPLACE_BUFSIZE / CRYPT_SECTOR_SIZE)
1629#define CRYPT_SECTOR_SIZE 512
Paul Lawrenceae59fe62014-01-21 08:23:27 -08001630
1631/* aligned 32K writes tends to make flash happy.
1632 * SD card association recommends it.
1633 */
1634#define BLOCKS_AT_A_TIME 8
1635
1636struct encryptGroupsData
1637{
1638 int realfd;
1639 int cryptofd;
1640 off64_t numblocks;
1641 off64_t one_pct, cur_pct, new_pct;
1642 off64_t blocks_already_done, tot_numblocks;
1643 char* real_blkdev, * crypto_blkdev;
1644 int count;
1645 off64_t offset;
1646 char* buffer;
Paul Lawrence87999172014-02-20 12:21:31 -08001647 off64_t last_written_sector;
1648 int completed;
Paul Lawrenceae59fe62014-01-21 08:23:27 -08001649};
1650
1651static void update_progress(struct encryptGroupsData* data)
1652{
1653 data->blocks_already_done++;
1654 data->new_pct = data->blocks_already_done / data->one_pct;
1655 if (data->new_pct > data->cur_pct) {
1656 char buf[8];
1657 data->cur_pct = data->new_pct;
1658 snprintf(buf, sizeof(buf), "%lld", data->cur_pct);
1659 property_set("vold.encrypt_progress", buf);
1660 }
1661}
1662
1663static int flush_outstanding_data(struct encryptGroupsData* data)
1664{
1665 if (data->count == 0) {
1666 return 0;
1667 }
1668
1669 SLOGV("Copying %d blocks at offset %llx", data->count, data->offset);
1670
1671 if (pread64(data->realfd, data->buffer,
1672 info.block_size * data->count, data->offset)
1673 <= 0) {
1674 SLOGE("Error reading real_blkdev %s for inplace encrypt",
1675 data->real_blkdev);
1676 return -1;
1677 }
1678
1679 if (pwrite64(data->cryptofd, data->buffer,
1680 info.block_size * data->count, data->offset)
1681 <= 0) {
1682 SLOGE("Error writing crypto_blkdev %s for inplace encrypt",
1683 data->crypto_blkdev);
1684 return -1;
Paul Lawrence87999172014-02-20 12:21:31 -08001685 } else {
1686 SLOGI("Encrypted %d blocks at sector %lld",
1687 data->count, data->offset / info.block_size * CRYPT_SECTOR_SIZE);
Paul Lawrenceae59fe62014-01-21 08:23:27 -08001688 }
1689
1690 data->count = 0;
Paul Lawrence87999172014-02-20 12:21:31 -08001691 data->last_written_sector = (data->offset + data->count)
1692 / info.block_size * CRYPT_SECTOR_SIZE - 1;
Paul Lawrenceae59fe62014-01-21 08:23:27 -08001693 return 0;
1694}
1695
1696static int encrypt_groups(struct encryptGroupsData* data)
1697{
1698 unsigned int i;
1699 u8 *block_bitmap = 0;
1700 unsigned int block;
1701 off64_t ret;
1702 int rc = -1;
1703
1704 data->buffer = malloc(info.block_size * BLOCKS_AT_A_TIME);
1705 if (!data->buffer) {
1706 SLOGE("Failed to allocate crypto buffer");
1707 goto errout;
1708 }
1709
1710 block_bitmap = malloc(info.block_size);
1711 if (!block_bitmap) {
1712 SLOGE("failed to allocate block bitmap");
1713 goto errout;
1714 }
1715
1716 for (i = 0; i < aux_info.groups; ++i) {
1717 SLOGI("Encrypting group %d", i);
1718
1719 u32 first_block = aux_info.first_data_block + i * info.blocks_per_group;
1720 u32 block_count = min(info.blocks_per_group,
1721 aux_info.len_blocks - first_block);
1722
1723 off64_t offset = (u64)info.block_size
1724 * aux_info.bg_desc[i].bg_block_bitmap;
1725
1726 ret = pread64(data->realfd, block_bitmap, info.block_size, offset);
1727 if (ret != (int)info.block_size) {
1728 SLOGE("failed to read all of block group bitmap %d", i);
1729 goto errout;
1730 }
1731
1732 offset = (u64)info.block_size * first_block;
1733
1734 data->count = 0;
1735
1736 for (block = 0; block < block_count; block++) {
1737 update_progress(data);
1738 if (bitmap_get_bit(block_bitmap, block)) {
1739 if (data->count == 0) {
1740 data->offset = offset;
1741 }
1742 data->count++;
1743 } else {
1744 if (flush_outstanding_data(data)) {
1745 goto errout;
1746 }
1747 }
1748
1749 offset += info.block_size;
1750
1751 /* Write data if we are aligned or buffer size reached */
1752 if (offset % (info.block_size * BLOCKS_AT_A_TIME) == 0
1753 || data->count == BLOCKS_AT_A_TIME) {
1754 if (flush_outstanding_data(data)) {
1755 goto errout;
1756 }
1757 }
Paul Lawrence87999172014-02-20 12:21:31 -08001758
1759 if (!is_battery_ok()) {
1760 SLOGE("Stopping encryption due to low battery");
1761 rc = 0;
1762 goto errout;
1763 }
1764
Paul Lawrenceae59fe62014-01-21 08:23:27 -08001765 }
1766 if (flush_outstanding_data(data)) {
1767 goto errout;
1768 }
1769 }
1770
Paul Lawrence87999172014-02-20 12:21:31 -08001771 data->completed = 1;
Paul Lawrenceae59fe62014-01-21 08:23:27 -08001772 rc = 0;
1773
1774errout:
1775 free(data->buffer);
1776 free(block_bitmap);
1777 return rc;
1778}
1779
1780static int cryptfs_enable_inplace_ext4(char *crypto_blkdev,
1781 char *real_blkdev,
1782 off64_t size,
1783 off64_t *size_already_done,
Paul Lawrence87999172014-02-20 12:21:31 -08001784 off64_t tot_size,
1785 off64_t previously_encrypted_upto)
Paul Lawrenceae59fe62014-01-21 08:23:27 -08001786{
1787 int i;
1788 struct encryptGroupsData data;
1789 int rc = -1;
1790
Paul Lawrence87999172014-02-20 12:21:31 -08001791 if (previously_encrypted_upto > *size_already_done) {
1792 SLOGD("Not fast encrypting since resuming part way through");
1793 return -1;
1794 }
1795
Paul Lawrenceae59fe62014-01-21 08:23:27 -08001796 memset(&data, 0, sizeof(data));
1797 data.real_blkdev = real_blkdev;
1798 data.crypto_blkdev = crypto_blkdev;
1799
1800 if ( (data.realfd = open(real_blkdev, O_RDWR)) < 0) {
1801 SLOGE("Error opening real_blkdev %s for inplace encrypt\n",
1802 real_blkdev);
1803 goto errout;
1804 }
1805
1806 if ( (data.cryptofd = open(crypto_blkdev, O_WRONLY)) < 0) {
1807 SLOGE("Error opening crypto_blkdev %s for inplace encrypt\n",
1808 crypto_blkdev);
1809 goto errout;
1810 }
1811
1812 if (setjmp(setjmp_env)) {
1813 SLOGE("Reading extent caused an exception");
1814 goto errout;
1815 }
1816
1817 if (read_ext(data.realfd, 0) != 0) {
1818 SLOGE("Failed to read extent");
1819 goto errout;
1820 }
1821
1822 data.numblocks = size / CRYPT_SECTORS_PER_BUFSIZE;
1823 data.tot_numblocks = tot_size / CRYPT_SECTORS_PER_BUFSIZE;
1824 data.blocks_already_done = *size_already_done / CRYPT_SECTORS_PER_BUFSIZE;
1825
1826 SLOGI("Encrypting filesystem in place...");
1827
1828 data.one_pct = data.tot_numblocks / 100;
1829 data.cur_pct = 0;
1830
1831 rc = encrypt_groups(&data);
1832 if (rc) {
1833 SLOGE("Error encrypting groups");
1834 goto errout;
1835 }
1836
Paul Lawrence87999172014-02-20 12:21:31 -08001837 *size_already_done += data.completed ? size : data.last_written_sector;
Paul Lawrenceae59fe62014-01-21 08:23:27 -08001838 rc = 0;
1839
1840errout:
1841 close(data.realfd);
1842 close(data.cryptofd);
1843
1844 return rc;
1845}
1846
1847static int cryptfs_enable_inplace_full(char *crypto_blkdev, char *real_blkdev,
1848 off64_t size, off64_t *size_already_done,
Paul Lawrence87999172014-02-20 12:21:31 -08001849 off64_t tot_size,
1850 off64_t previously_encrypted_upto)
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001851{
1852 int realfd, cryptofd;
1853 char *buf[CRYPT_INPLACE_BUFSIZE];
1854 int rc = -1;
1855 off64_t numblocks, i, remainder;
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001856 off64_t one_pct, cur_pct, new_pct;
Ken Sumrall29d8da82011-05-18 17:20:07 -07001857 off64_t blocks_already_done, tot_numblocks;
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001858
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001859 if ( (realfd = open(real_blkdev, O_RDONLY)) < 0) {
1860 SLOGE("Error opening real_blkdev %s for inplace encrypt\n", real_blkdev);
1861 return -1;
1862 }
1863
1864 if ( (cryptofd = open(crypto_blkdev, O_WRONLY)) < 0) {
1865 SLOGE("Error opening crypto_blkdev %s for inplace encrypt\n", crypto_blkdev);
1866 close(realfd);
1867 return -1;
1868 }
1869
1870 /* This is pretty much a simple loop of reading 4K, and writing 4K.
1871 * The size passed in is the number of 512 byte sectors in the filesystem.
1872 * So compute the number of whole 4K blocks we should read/write,
1873 * and the remainder.
1874 */
1875 numblocks = size / CRYPT_SECTORS_PER_BUFSIZE;
1876 remainder = size % CRYPT_SECTORS_PER_BUFSIZE;
Ken Sumrall29d8da82011-05-18 17:20:07 -07001877 tot_numblocks = tot_size / CRYPT_SECTORS_PER_BUFSIZE;
1878 blocks_already_done = *size_already_done / CRYPT_SECTORS_PER_BUFSIZE;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001879
1880 SLOGE("Encrypting filesystem in place...");
1881
Paul Lawrence87999172014-02-20 12:21:31 -08001882 i = previously_encrypted_upto + 1 - *size_already_done;
1883
1884 if (lseek64(realfd, i * CRYPT_SECTOR_SIZE, SEEK_SET) < 0) {
1885 SLOGE("Cannot seek to previously encrypted point on %s", real_blkdev);
1886 goto errout;
1887 }
1888
1889 if (lseek64(cryptofd, i * CRYPT_SECTOR_SIZE, SEEK_SET) < 0) {
1890 SLOGE("Cannot seek to previously encrypted point on %s", crypto_blkdev);
1891 goto errout;
1892 }
1893
1894 for (;i < size && i % CRYPT_SECTORS_PER_BUFSIZE != 0; ++i) {
1895 if (unix_read(realfd, buf, CRYPT_SECTOR_SIZE) <= 0) {
1896 SLOGE("Error reading initial sectors from real_blkdev %s for "
1897 "inplace encrypt\n", crypto_blkdev);
1898 goto errout;
1899 }
1900 if (unix_write(cryptofd, buf, CRYPT_SECTOR_SIZE) <= 0) {
1901 SLOGE("Error writing initial sectors to crypto_blkdev %s for "
1902 "inplace encrypt\n", crypto_blkdev);
1903 goto errout;
1904 } else {
1905 SLOGI("Encrypted 1 block at %lld", i);
1906 }
1907 }
1908
Ken Sumrall29d8da82011-05-18 17:20:07 -07001909 one_pct = tot_numblocks / 100;
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001910 cur_pct = 0;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001911 /* process the majority of the filesystem in blocks */
Paul Lawrence87999172014-02-20 12:21:31 -08001912 for (i/=CRYPT_SECTORS_PER_BUFSIZE; i<numblocks; i++) {
Ken Sumrall29d8da82011-05-18 17:20:07 -07001913 new_pct = (i + blocks_already_done) / one_pct;
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001914 if (new_pct > cur_pct) {
1915 char buf[8];
1916
1917 cur_pct = new_pct;
1918 snprintf(buf, sizeof(buf), "%lld", cur_pct);
1919 property_set("vold.encrypt_progress", buf);
1920 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001921 if (unix_read(realfd, buf, CRYPT_INPLACE_BUFSIZE) <= 0) {
Paul Lawrence87999172014-02-20 12:21:31 -08001922 SLOGE("Error reading real_blkdev %s for inplace encrypt", crypto_blkdev);
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001923 goto errout;
1924 }
1925 if (unix_write(cryptofd, buf, CRYPT_INPLACE_BUFSIZE) <= 0) {
Paul Lawrence87999172014-02-20 12:21:31 -08001926 SLOGE("Error writing crypto_blkdev %s for inplace encrypt", crypto_blkdev);
1927 goto errout;
1928 } else {
1929 SLOGD("Encrypted %d block at %lld",
1930 CRYPT_SECTORS_PER_BUFSIZE,
1931 i * CRYPT_SECTORS_PER_BUFSIZE);
1932 }
1933
1934 if (!is_battery_ok()) {
1935 SLOGE("Stopping encryption due to low battery");
1936 *size_already_done += (i + 1) * CRYPT_SECTORS_PER_BUFSIZE - 1;
1937 rc = 0;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001938 goto errout;
1939 }
1940 }
1941
1942 /* Do any remaining sectors */
1943 for (i=0; i<remainder; i++) {
Paul Lawrence87999172014-02-20 12:21:31 -08001944 if (unix_read(realfd, buf, CRYPT_SECTOR_SIZE) <= 0) {
1945 SLOGE("Error reading final sectors from real_blkdev %s for inplace encrypt", crypto_blkdev);
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001946 goto errout;
1947 }
Paul Lawrence87999172014-02-20 12:21:31 -08001948 if (unix_write(cryptofd, buf, CRYPT_SECTOR_SIZE) <= 0) {
1949 SLOGE("Error writing final sectors to crypto_blkdev %s for inplace encrypt", crypto_blkdev);
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001950 goto errout;
Paul Lawrence87999172014-02-20 12:21:31 -08001951 } else {
1952 SLOGI("Encrypted 1 block at next location");
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001953 }
1954 }
1955
Ken Sumrall29d8da82011-05-18 17:20:07 -07001956 *size_already_done += size;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001957 rc = 0;
1958
1959errout:
1960 close(realfd);
1961 close(cryptofd);
1962
1963 return rc;
1964}
1965
Paul Lawrenceae59fe62014-01-21 08:23:27 -08001966static int cryptfs_enable_inplace(char *crypto_blkdev, char *real_blkdev,
1967 off64_t size, off64_t *size_already_done,
Paul Lawrence87999172014-02-20 12:21:31 -08001968 off64_t tot_size,
1969 off64_t previously_encrypted_upto)
Paul Lawrenceae59fe62014-01-21 08:23:27 -08001970{
Paul Lawrence87999172014-02-20 12:21:31 -08001971 if (previously_encrypted_upto) {
1972 SLOGD("Continuing encryption from %lld", previously_encrypted_upto);
1973 }
1974
1975 if (*size_already_done + size < previously_encrypted_upto) {
1976 *size_already_done += size;
1977 return 0;
1978 }
1979
Paul Lawrenceae59fe62014-01-21 08:23:27 -08001980 if (cryptfs_enable_inplace_ext4(crypto_blkdev, real_blkdev,
Paul Lawrence87999172014-02-20 12:21:31 -08001981 size, size_already_done,
1982 tot_size, previously_encrypted_upto) == 0) {
Paul Lawrenceae59fe62014-01-21 08:23:27 -08001983 return 0;
1984 }
1985
1986 return cryptfs_enable_inplace_full(crypto_blkdev, real_blkdev,
Paul Lawrence87999172014-02-20 12:21:31 -08001987 size, size_already_done, tot_size,
1988 previously_encrypted_upto);
Paul Lawrenceae59fe62014-01-21 08:23:27 -08001989}
1990
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001991#define CRYPTO_ENABLE_WIPE 1
1992#define CRYPTO_ENABLE_INPLACE 2
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001993
1994#define FRAMEWORK_BOOT_WAIT 60
1995
Ken Sumrall29d8da82011-05-18 17:20:07 -07001996static inline int should_encrypt(struct volume_info *volume)
1997{
Paul Lawrenceae59fe62014-01-21 08:23:27 -08001998 return (volume->flags & (VOL_ENCRYPTABLE | VOL_NONREMOVABLE)) ==
Ken Sumrall29d8da82011-05-18 17:20:07 -07001999 (VOL_ENCRYPTABLE | VOL_NONREMOVABLE);
2000}
2001
Paul Lawrence87999172014-02-20 12:21:31 -08002002static int cryptfs_SHA256_fileblock(const char* filename, __le8* buf)
2003{
2004 int fd = open(filename, O_RDONLY);
2005 if (fd == -1) {
2006 SLOGE("Error opening file %s", filename);
2007 return -1;
2008 }
2009
2010 char block[CRYPT_INPLACE_BUFSIZE];
2011 memset(block, 0, sizeof(block));
2012 if (unix_read(fd, block, sizeof(block)) < 0) {
2013 SLOGE("Error reading file %s", filename);
2014 close(fd);
2015 return -1;
2016 }
2017
2018 close(fd);
2019
2020 SHA256_CTX c;
2021 SHA256_Init(&c);
2022 SHA256_Update(&c, block, sizeof(block));
2023 SHA256_Final(buf, &c);
2024
2025 return 0;
2026}
2027
2028static int cryptfs_enable_all_volumes(struct crypt_mnt_ftr *crypt_ftr, int how,
2029 char *crypto_blkdev, char *real_blkdev,
2030 int previously_encrypted_upto)
2031{
2032 off64_t cur_encryption_done=0, tot_encryption_size=0;
2033 int i, rc = -1;
2034
2035 if (!is_battery_ok()) {
2036 SLOGE("Stopping encryption due to low battery");
2037 return 0;
2038 }
2039
2040 /* The size of the userdata partition, and add in the vold volumes below */
2041 tot_encryption_size = crypt_ftr->fs_size;
2042
2043 if (how == CRYPTO_ENABLE_WIPE) {
2044 rc = cryptfs_enable_wipe(crypto_blkdev, crypt_ftr->fs_size, EXT4_FS);
2045 } else if (how == CRYPTO_ENABLE_INPLACE) {
2046 rc = cryptfs_enable_inplace(crypto_blkdev, real_blkdev,
2047 crypt_ftr->fs_size, &cur_encryption_done,
2048 tot_encryption_size,
2049 previously_encrypted_upto);
2050
2051 if (!rc && cur_encryption_done != (off64_t)crypt_ftr->fs_size) {
2052 crypt_ftr->encrypted_upto = cur_encryption_done;
2053 }
2054
2055 if (!rc && !crypt_ftr->encrypted_upto) {
2056 /* The inplace routine never actually sets the progress to 100% due
2057 * to the round down nature of integer division, so set it here */
2058 property_set("vold.encrypt_progress", "100");
2059 }
2060 } else {
2061 /* Shouldn't happen */
2062 SLOGE("cryptfs_enable: internal error, unknown option\n");
2063 rc = -1;
2064 }
2065
2066 return rc;
2067}
2068
Paul Lawrence13486032014-02-03 13:28:11 -08002069int cryptfs_enable_internal(char *howarg, int crypt_type, char *passwd,
2070 int allow_reboot)
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002071{
2072 int how = 0;
Paul Lawrence87999172014-02-20 12:21:31 -08002073 char crypto_blkdev[MAXPATHLEN], real_blkdev[MAXPATHLEN];
Ken Sumralle5032c42012-04-01 23:58:44 -07002074 unsigned long nr_sec;
Ken Sumrall160b4d62013-04-22 12:15:39 -07002075 unsigned char decrypted_master_key[KEY_LEN_BYTES];
Ken Sumrall319b1042011-06-14 14:01:55 -07002076 int rc=-1, fd, i, ret;
Paul Lawrence87999172014-02-20 12:21:31 -08002077 struct crypt_mnt_ftr crypt_ftr;
Ken Sumrall160b4d62013-04-22 12:15:39 -07002078 struct crypt_persist_data *pdata;
Ken Sumrall29d8da82011-05-18 17:20:07 -07002079 char encrypted_state[PROPERTY_VALUE_MAX];
Ken Sumrall5d4c68e2011-01-30 19:06:03 -08002080 char lockid[32] = { 0 };
Ken Sumrall29d8da82011-05-18 17:20:07 -07002081 char key_loc[PROPERTY_VALUE_MAX];
2082 char fuse_sdcard[PROPERTY_VALUE_MAX];
2083 char *sd_mnt_point;
Ken Sumrall29d8da82011-05-18 17:20:07 -07002084 int num_vols;
2085 struct volume_info *vol_list = 0;
Paul Lawrence87999172014-02-20 12:21:31 -08002086 off64_t previously_encrypted_upto = 0;
Ken Sumrall29d8da82011-05-18 17:20:07 -07002087
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002088 if (!strcmp(howarg, "wipe")) {
2089 how = CRYPTO_ENABLE_WIPE;
2090 } else if (! strcmp(howarg, "inplace")) {
2091 how = CRYPTO_ENABLE_INPLACE;
2092 } else {
2093 /* Shouldn't happen, as CommandListener vets the args */
Ken Sumrall3ed82362011-01-28 23:31:16 -08002094 goto error_unencrypted;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002095 }
2096
Paul Lawrence87999172014-02-20 12:21:31 -08002097 /* See if an encryption was underway and interrupted */
2098 if (how == CRYPTO_ENABLE_INPLACE
2099 && get_crypt_ftr_and_key(&crypt_ftr) == 0
2100 && (crypt_ftr.flags & CRYPT_ENCRYPTION_IN_PROGRESS)) {
2101 previously_encrypted_upto = crypt_ftr.encrypted_upto;
2102 crypt_ftr.encrypted_upto = 0;
2103 }
2104
2105 property_get("ro.crypto.state", encrypted_state, "");
2106 if (!strcmp(encrypted_state, "encrypted") && !previously_encrypted_upto) {
2107 SLOGE("Device is already running encrypted, aborting");
2108 goto error_unencrypted;
2109 }
2110
2111 // TODO refactor fs_mgr_get_crypt_info to get both in one call
2112 fs_mgr_get_crypt_info(fstab, key_loc, 0, sizeof(key_loc));
Ken Sumrall56ad03c2013-02-13 13:00:19 -08002113 fs_mgr_get_crypt_info(fstab, 0, real_blkdev, sizeof(real_blkdev));
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002114
Ken Sumrall3ed82362011-01-28 23:31:16 -08002115 /* Get the size of the real block device */
2116 fd = open(real_blkdev, O_RDONLY);
2117 if ( (nr_sec = get_blkdev_size(fd)) == 0) {
2118 SLOGE("Cannot get size of block device %s\n", real_blkdev);
2119 goto error_unencrypted;
2120 }
2121 close(fd);
2122
2123 /* If doing inplace encryption, make sure the orig fs doesn't include the crypto footer */
Ken Sumrall29d8da82011-05-18 17:20:07 -07002124 if ((how == CRYPTO_ENABLE_INPLACE) && (!strcmp(key_loc, KEY_IN_FOOTER))) {
Ken Sumrall3ed82362011-01-28 23:31:16 -08002125 unsigned int fs_size_sec, max_fs_size_sec;
2126
2127 fs_size_sec = get_fs_size(real_blkdev);
Paul Lawrence87999172014-02-20 12:21:31 -08002128 max_fs_size_sec = nr_sec - (CRYPT_FOOTER_OFFSET / CRYPT_SECTOR_SIZE);
Ken Sumrall3ed82362011-01-28 23:31:16 -08002129
2130 if (fs_size_sec > max_fs_size_sec) {
2131 SLOGE("Orig filesystem overlaps crypto footer region. Cannot encrypt in place.");
2132 goto error_unencrypted;
2133 }
2134 }
2135
Ken Sumrall5d4c68e2011-01-30 19:06:03 -08002136 /* Get a wakelock as this may take a while, and we don't want the
2137 * device to sleep on us. We'll grab a partial wakelock, and if the UI
2138 * wants to keep the screen on, it can grab a full wakelock.
2139 */
Ken Sumrall29d8da82011-05-18 17:20:07 -07002140 snprintf(lockid, sizeof(lockid), "enablecrypto%d", (int) getpid());
Ken Sumrall5d4c68e2011-01-30 19:06:03 -08002141 acquire_wake_lock(PARTIAL_WAKE_LOCK, lockid);
2142
Jeff Sharkey7382f812012-08-23 14:08:59 -07002143 /* Get the sdcard mount point */
Jeff Sharkeyb77bc462012-10-01 14:36:26 -07002144 sd_mnt_point = getenv("EMULATED_STORAGE_SOURCE");
Jeff Sharkey7382f812012-08-23 14:08:59 -07002145 if (!sd_mnt_point) {
2146 sd_mnt_point = getenv("EXTERNAL_STORAGE");
2147 }
2148 if (!sd_mnt_point) {
2149 sd_mnt_point = "/mnt/sdcard";
2150 }
Ken Sumrall29d8da82011-05-18 17:20:07 -07002151
Paul Lawrence87999172014-02-20 12:21:31 -08002152 /* TODO
2153 * Currently do not have test devices with multiple encryptable volumes.
2154 * When we acquire some, re-add support.
2155 */
Ken Sumrall29d8da82011-05-18 17:20:07 -07002156 num_vols=vold_getNumDirectVolumes();
2157 vol_list = malloc(sizeof(struct volume_info) * num_vols);
2158 vold_getDirectVolumeList(vol_list);
2159
2160 for (i=0; i<num_vols; i++) {
2161 if (should_encrypt(&vol_list[i])) {
Paul Lawrence87999172014-02-20 12:21:31 -08002162 SLOGE("Cannot encrypt if there are multiple encryptable volumes"
2163 "%s\n", vol_list[i].label);
2164 goto error_unencrypted;
Ken Sumrall29d8da82011-05-18 17:20:07 -07002165 }
2166 }
2167
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002168 /* The init files are setup to stop the class main and late start when
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002169 * vold sets trigger_shutdown_framework.
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002170 */
2171 property_set("vold.decrypt", "trigger_shutdown_framework");
2172 SLOGD("Just asked init to shut down class main\n");
2173
Ken Sumrall425524d2012-06-14 20:55:28 -07002174 if (vold_unmountAllAsecs()) {
2175 /* Just report the error. If any are left mounted,
2176 * umounting /data below will fail and handle the error.
2177 */
2178 SLOGE("Error unmounting internal asecs");
2179 }
2180
Ken Sumrall29d8da82011-05-18 17:20:07 -07002181 property_get("ro.crypto.fuse_sdcard", fuse_sdcard, "");
2182 if (!strcmp(fuse_sdcard, "true")) {
2183 /* This is a device using the fuse layer to emulate the sdcard semantics
2184 * on top of the userdata partition. vold does not manage it, it is managed
2185 * by the sdcard service. The sdcard service was killed by the property trigger
2186 * above, so just unmount it now. We must do this _AFTER_ killing the framework,
2187 * unlike the case for vold managed devices above.
2188 */
2189 if (wait_and_unmount(sd_mnt_point)) {
2190 goto error_shutting_down;
2191 }
Ken Sumrall2eaf7132011-01-14 12:45:48 -08002192 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002193
2194 /* Now unmount the /data partition. */
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002195 if (wait_and_unmount(DATA_MNT_POINT)) {
JP Abgrall502dc742013-11-01 13:06:20 -07002196 if (allow_reboot) {
2197 goto error_shutting_down;
2198 } else {
2199 goto error_unencrypted;
2200 }
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002201 }
2202
2203 /* Do extra work for a better UX when doing the long inplace encryption */
2204 if (how == CRYPTO_ENABLE_INPLACE) {
2205 /* Now that /data is unmounted, we need to mount a tmpfs
2206 * /data, set a property saying we're doing inplace encryption,
2207 * and restart the framework.
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002208 */
Ken Sumralle5032c42012-04-01 23:58:44 -07002209 if (fs_mgr_do_tmpfs_mount(DATA_MNT_POINT)) {
Ken Sumrall3ed82362011-01-28 23:31:16 -08002210 goto error_shutting_down;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002211 }
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002212 /* Tells the framework that inplace encryption is starting */
Ken Sumrall7df84122011-01-18 14:04:08 -08002213 property_set("vold.encrypt_progress", "0");
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002214
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002215 /* restart the framework. */
2216 /* Create necessary paths on /data */
2217 if (prep_data_fs()) {
Ken Sumrall3ed82362011-01-28 23:31:16 -08002218 goto error_shutting_down;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002219 }
2220
Ken Sumrall92736ef2012-10-17 20:57:14 -07002221 /* Ugh, shutting down the framework is not synchronous, so until it
2222 * can be fixed, this horrible hack will wait a moment for it all to
2223 * shut down before proceeding. Without it, some devices cannot
2224 * restart the graphics services.
2225 */
2226 sleep(2);
2227
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002228 /* startup service classes main and late_start */
2229 property_set("vold.decrypt", "trigger_restart_min_framework");
2230 SLOGD("Just triggered restart_min_framework\n");
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002231
Ken Sumrall7df84122011-01-18 14:04:08 -08002232 /* OK, the framework is restarted and will soon be showing a
2233 * progress bar. Time to setup an encrypted mapping, and
2234 * either write a new filesystem, or encrypt in place updating
2235 * the progress bar as we work.
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002236 */
2237 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002238
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002239 /* Start the actual work of making an encrypted filesystem */
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002240 /* Initialize a crypt_mnt_ftr for the partition */
Paul Lawrence87999172014-02-20 12:21:31 -08002241 if (previously_encrypted_upto == 0) {
2242 cryptfs_init_crypt_mnt_ftr(&crypt_ftr);
Ken Sumrall160b4d62013-04-22 12:15:39 -07002243
Paul Lawrence87999172014-02-20 12:21:31 -08002244 if (!strcmp(key_loc, KEY_IN_FOOTER)) {
2245 crypt_ftr.fs_size = nr_sec
2246 - (CRYPT_FOOTER_OFFSET / CRYPT_SECTOR_SIZE);
2247 } else {
2248 crypt_ftr.fs_size = nr_sec;
2249 }
2250 crypt_ftr.flags |= CRYPT_ENCRYPTION_IN_PROGRESS;
2251 crypt_ftr.crypt_type = crypt_type;
2252 strcpy((char *)crypt_ftr.crypto_type_name, "aes-cbc-essiv:sha256");
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002253
Paul Lawrence87999172014-02-20 12:21:31 -08002254 /* Make an encrypted master key */
2255 if (create_encrypted_random_key(passwd, crypt_ftr.master_key, crypt_ftr.salt, &crypt_ftr)) {
2256 SLOGE("Cannot create encrypted master key\n");
2257 goto error_shutting_down;
2258 }
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002259
Paul Lawrence87999172014-02-20 12:21:31 -08002260 /* Write the key to the end of the partition */
2261 put_crypt_ftr_and_key(&crypt_ftr);
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002262
Paul Lawrence87999172014-02-20 12:21:31 -08002263 /* If any persistent data has been remembered, save it.
2264 * If none, create a valid empty table and save that.
2265 */
2266 if (!persist_data) {
2267 pdata = malloc(CRYPT_PERSIST_DATA_SIZE);
2268 if (pdata) {
2269 init_empty_persist_data(pdata, CRYPT_PERSIST_DATA_SIZE);
2270 persist_data = pdata;
2271 }
2272 }
2273 if (persist_data) {
2274 save_persistent_data();
2275 }
Ken Sumrall160b4d62013-04-22 12:15:39 -07002276 }
2277
JP Abgrall7bdfa522013-11-15 13:42:56 -08002278 decrypt_master_key(passwd, decrypted_master_key, &crypt_ftr);
Ken Sumrall29d8da82011-05-18 17:20:07 -07002279 create_crypto_blk_dev(&crypt_ftr, decrypted_master_key, real_blkdev, crypto_blkdev,
2280 "userdata");
2281
Paul Lawrence87999172014-02-20 12:21:31 -08002282 /* If we are continuing, check checksums match */
2283 rc = 0;
2284 if (previously_encrypted_upto) {
2285 __le8 hash_first_block[SHA256_DIGEST_LENGTH];
2286 rc = cryptfs_SHA256_fileblock(crypto_blkdev, hash_first_block);
Ken Sumrall128626f2011-06-28 18:45:14 -07002287
Paul Lawrence87999172014-02-20 12:21:31 -08002288 if (!rc && memcmp(hash_first_block, crypt_ftr.hash_first_block,
2289 sizeof(hash_first_block)) != 0) {
2290 SLOGE("Checksums do not match - trigger wipe");
2291 rc = -1;
Ken Sumrall29d8da82011-05-18 17:20:07 -07002292 }
2293 }
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002294
Paul Lawrence87999172014-02-20 12:21:31 -08002295 if (!rc) {
2296 rc = cryptfs_enable_all_volumes(&crypt_ftr, how,
2297 crypto_blkdev, real_blkdev,
2298 previously_encrypted_upto);
2299 }
2300
2301 /* Calculate checksum if we are not finished */
2302 if (!rc && crypt_ftr.encrypted_upto) {
2303 rc = cryptfs_SHA256_fileblock(crypto_blkdev,
2304 crypt_ftr.hash_first_block);
Ken Sumrall29d8da82011-05-18 17:20:07 -07002305 if (!rc) {
Paul Lawrence87999172014-02-20 12:21:31 -08002306 SLOGE("Error calculating checksum for continuing encryption");
2307 rc = -1;
Ken Sumrall29d8da82011-05-18 17:20:07 -07002308 }
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002309 }
2310
2311 /* Undo the dm-crypt mapping whether we succeed or not */
Ken Sumrall29d8da82011-05-18 17:20:07 -07002312 delete_crypto_blk_dev("userdata");
Ken Sumrall29d8da82011-05-18 17:20:07 -07002313
2314 free(vol_list);
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002315
2316 if (! rc) {
2317 /* Success */
Ken Sumrall7f7dbaa2011-02-01 15:46:41 -08002318
Ken Sumralld33d4172011-02-01 00:49:13 -08002319 /* Clear the encryption in progres flag in the footer */
Paul Lawrence87999172014-02-20 12:21:31 -08002320 if (!crypt_ftr.encrypted_upto) {
2321 crypt_ftr.flags &= ~CRYPT_ENCRYPTION_IN_PROGRESS;
2322 } else {
2323 SLOGD("Encrypted up to sector %lld - will continue after reboot",
2324 crypt_ftr.encrypted_upto);
2325 }
Ken Sumrall160b4d62013-04-22 12:15:39 -07002326 put_crypt_ftr_and_key(&crypt_ftr);
Ken Sumralld33d4172011-02-01 00:49:13 -08002327
Ken Sumrall29d8da82011-05-18 17:20:07 -07002328 sleep(2); /* Give the UI a chance to show 100% progress */
Paul Lawrence87999172014-02-20 12:21:31 -08002329 /* Partially encrypted - ensure writes are flushed to ssd */
2330
2331 if (!crypt_ftr.encrypted_upto) {
2332 cryptfs_reboot(reboot);
2333 } else {
2334 cryptfs_reboot(shutdown);
2335 }
Ken Sumrall3ed82362011-01-28 23:31:16 -08002336 } else {
Mike Lockwoodee6d8c42012-02-15 13:43:28 -08002337 char value[PROPERTY_VALUE_MAX];
2338
Ken Sumrall319369a2012-06-27 16:30:18 -07002339 property_get("ro.vold.wipe_on_crypt_fail", value, "0");
Mike Lockwoodee6d8c42012-02-15 13:43:28 -08002340 if (!strcmp(value, "1")) {
2341 /* wipe data if encryption failed */
2342 SLOGE("encryption failed - rebooting into recovery to wipe data\n");
2343 mkdir("/cache/recovery", 0700);
Nick Kralevich4684e582012-06-26 15:07:03 -07002344 int fd = open("/cache/recovery/command", O_RDWR|O_CREAT|O_TRUNC, 0600);
Mike Lockwoodee6d8c42012-02-15 13:43:28 -08002345 if (fd >= 0) {
2346 write(fd, "--wipe_data", strlen("--wipe_data") + 1);
2347 close(fd);
2348 } else {
2349 SLOGE("could not open /cache/recovery/command\n");
2350 }
Paul Lawrence87999172014-02-20 12:21:31 -08002351 cryptfs_reboot(recovery);
Mike Lockwoodee6d8c42012-02-15 13:43:28 -08002352 } else {
2353 /* set property to trigger dialog */
2354 property_set("vold.encrypt_progress", "error_partially_encrypted");
2355 release_wake_lock(lockid);
2356 }
Ken Sumrall3ed82362011-01-28 23:31:16 -08002357 return -1;
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002358 }
2359
Ken Sumrall3ed82362011-01-28 23:31:16 -08002360 /* hrm, the encrypt step claims success, but the reboot failed.
2361 * This should not happen.
2362 * Set the property and return. Hope the framework can deal with it.
2363 */
2364 property_set("vold.encrypt_progress", "error_reboot_failed");
Ken Sumrall5d4c68e2011-01-30 19:06:03 -08002365 release_wake_lock(lockid);
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002366 return rc;
Ken Sumrall3ed82362011-01-28 23:31:16 -08002367
2368error_unencrypted:
Ken Sumrall29d8da82011-05-18 17:20:07 -07002369 free(vol_list);
Ken Sumrall3ed82362011-01-28 23:31:16 -08002370 property_set("vold.encrypt_progress", "error_not_encrypted");
Ken Sumrall5d4c68e2011-01-30 19:06:03 -08002371 if (lockid[0]) {
2372 release_wake_lock(lockid);
2373 }
Ken Sumrall3ed82362011-01-28 23:31:16 -08002374 return -1;
2375
2376error_shutting_down:
2377 /* we failed, and have not encrypted anthing, so the users's data is still intact,
2378 * but the framework is stopped and not restarted to show the error, so it's up to
2379 * vold to restart the system.
2380 */
2381 SLOGE("Error enabling encryption after framework is shutdown, no data changed, restarting system");
Paul Lawrence87999172014-02-20 12:21:31 -08002382 cryptfs_reboot(reboot);
Ken Sumrall3ed82362011-01-28 23:31:16 -08002383
2384 /* shouldn't get here */
2385 property_set("vold.encrypt_progress", "error_shutting_down");
Ken Sumrall29d8da82011-05-18 17:20:07 -07002386 free(vol_list);
Ken Sumrall5d4c68e2011-01-30 19:06:03 -08002387 if (lockid[0]) {
2388 release_wake_lock(lockid);
2389 }
Ken Sumrall3ed82362011-01-28 23:31:16 -08002390 return -1;
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002391}
2392
Paul Lawrence13486032014-02-03 13:28:11 -08002393int cryptfs_enable(char *howarg, char *passwd, int allow_reboot)
2394{
2395 /** @todo If we keep this route (user selected encryption)
2396 * need to take a type in and pass it to here.
2397 */
2398 return cryptfs_enable_internal(howarg, CRYPT_TYPE_PASSWORD,
2399 passwd, allow_reboot);
2400}
2401
2402int cryptfs_enable_default(char *howarg, int allow_reboot)
2403{
2404 return cryptfs_enable_internal(howarg, CRYPT_TYPE_DEFAULT,
2405 DEFAULT_PASSWORD, allow_reboot);
2406}
2407
2408int cryptfs_changepw(int crypt_type, const char *newpw)
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002409{
2410 struct crypt_mnt_ftr crypt_ftr;
Ken Sumrall160b4d62013-04-22 12:15:39 -07002411 unsigned char decrypted_master_key[KEY_LEN_BYTES];
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002412
2413 /* This is only allowed after we've successfully decrypted the master key */
Paul Lawrencef4faa572014-01-29 13:31:03 -08002414 if (!master_key_saved) {
Ken Sumrall0cc16632011-01-18 20:32:26 -08002415 SLOGE("Key not saved, aborting");
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002416 return -1;
2417 }
2418
Paul Lawrencef4faa572014-01-29 13:31:03 -08002419 if (crypt_type < 0 || crypt_type > CRYPT_TYPE_MAX_TYPE) {
2420 SLOGE("Invalid crypt_type %d", crypt_type);
2421 return -1;
2422 }
2423
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002424 /* get key */
Ken Sumrall160b4d62013-04-22 12:15:39 -07002425 if (get_crypt_ftr_and_key(&crypt_ftr)) {
Paul Lawrencef4faa572014-01-29 13:31:03 -08002426 SLOGE("Error getting crypt footer and key");
2427 return -1;
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002428 }
2429
Paul Lawrencef4faa572014-01-29 13:31:03 -08002430 crypt_ftr.crypt_type = crypt_type;
2431
2432 encrypt_master_key(crypt_type == CRYPT_TYPE_DEFAULT ? DEFAULT_PASSWORD
2433 : newpw,
2434 crypt_ftr.salt,
2435 saved_master_key,
2436 crypt_ftr.master_key,
2437 &crypt_ftr);
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002438
Jason parks70a4b3f2011-01-28 10:10:47 -06002439 /* save the key */
Ken Sumrall160b4d62013-04-22 12:15:39 -07002440 put_crypt_ftr_and_key(&crypt_ftr);
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002441
2442 return 0;
2443}
Ken Sumrall160b4d62013-04-22 12:15:39 -07002444
2445static int persist_get_key(char *fieldname, char *value)
2446{
2447 unsigned int i;
2448
2449 if (persist_data == NULL) {
2450 return -1;
2451 }
2452 for (i = 0; i < persist_data->persist_valid_entries; i++) {
2453 if (!strncmp(persist_data->persist_entry[i].key, fieldname, PROPERTY_KEY_MAX)) {
2454 /* We found it! */
2455 strlcpy(value, persist_data->persist_entry[i].val, PROPERTY_VALUE_MAX);
2456 return 0;
2457 }
2458 }
2459
2460 return -1;
2461}
2462
2463static int persist_set_key(char *fieldname, char *value, int encrypted)
2464{
2465 unsigned int i;
2466 unsigned int num;
2467 struct crypt_mnt_ftr crypt_ftr;
2468 unsigned int max_persistent_entries;
2469 unsigned int dsize;
2470
2471 if (persist_data == NULL) {
2472 return -1;
2473 }
2474
2475 /* If encrypted, use the values from the crypt_ftr, otherwise
2476 * use the values for the current spec.
2477 */
2478 if (encrypted) {
2479 if(get_crypt_ftr_and_key(&crypt_ftr)) {
2480 return -1;
2481 }
2482 dsize = crypt_ftr.persist_data_size;
2483 } else {
2484 dsize = CRYPT_PERSIST_DATA_SIZE;
2485 }
2486 max_persistent_entries = (dsize - sizeof(struct crypt_persist_data)) /
2487 sizeof(struct crypt_persist_entry);
2488
2489 num = persist_data->persist_valid_entries;
2490
2491 for (i = 0; i < num; i++) {
2492 if (!strncmp(persist_data->persist_entry[i].key, fieldname, PROPERTY_KEY_MAX)) {
2493 /* We found an existing entry, update it! */
2494 memset(persist_data->persist_entry[i].val, 0, PROPERTY_VALUE_MAX);
2495 strlcpy(persist_data->persist_entry[i].val, value, PROPERTY_VALUE_MAX);
2496 return 0;
2497 }
2498 }
2499
2500 /* We didn't find it, add it to the end, if there is room */
2501 if (persist_data->persist_valid_entries < max_persistent_entries) {
2502 memset(&persist_data->persist_entry[num], 0, sizeof(struct crypt_persist_entry));
2503 strlcpy(persist_data->persist_entry[num].key, fieldname, PROPERTY_KEY_MAX);
2504 strlcpy(persist_data->persist_entry[num].val, value, PROPERTY_VALUE_MAX);
2505 persist_data->persist_valid_entries++;
2506 return 0;
2507 }
2508
2509 return -1;
2510}
2511
2512/* Return the value of the specified field. */
2513int cryptfs_getfield(char *fieldname, char *value, int len)
2514{
2515 char temp_value[PROPERTY_VALUE_MAX];
2516 char real_blkdev[MAXPATHLEN];
2517 /* 0 is success, 1 is not encrypted,
2518 * -1 is value not set, -2 is any other error
2519 */
2520 int rc = -2;
2521
2522 if (persist_data == NULL) {
2523 load_persistent_data();
2524 if (persist_data == NULL) {
2525 SLOGE("Getfield error, cannot load persistent data");
2526 goto out;
2527 }
2528 }
2529
2530 if (!persist_get_key(fieldname, temp_value)) {
2531 /* We found it, copy it to the caller's buffer and return */
2532 strlcpy(value, temp_value, len);
2533 rc = 0;
2534 } else {
2535 /* Sadness, it's not there. Return the error */
2536 rc = -1;
2537 }
2538
2539out:
2540 return rc;
2541}
2542
2543/* Set the value of the specified field. */
2544int cryptfs_setfield(char *fieldname, char *value)
2545{
2546 struct crypt_persist_data stored_pdata;
2547 struct crypt_persist_data *pdata_p;
2548 struct crypt_mnt_ftr crypt_ftr;
2549 char encrypted_state[PROPERTY_VALUE_MAX];
2550 /* 0 is success, -1 is an error */
2551 int rc = -1;
2552 int encrypted = 0;
2553
2554 if (persist_data == NULL) {
2555 load_persistent_data();
2556 if (persist_data == NULL) {
2557 SLOGE("Setfield error, cannot load persistent data");
2558 goto out;
2559 }
2560 }
2561
2562 property_get("ro.crypto.state", encrypted_state, "");
2563 if (!strcmp(encrypted_state, "encrypted") ) {
2564 encrypted = 1;
2565 }
2566
2567 if (persist_set_key(fieldname, value, encrypted)) {
2568 goto out;
2569 }
2570
2571 /* If we are running encrypted, save the persistent data now */
2572 if (encrypted) {
2573 if (save_persistent_data()) {
2574 SLOGE("Setfield error, cannot save persistent data");
2575 goto out;
2576 }
2577 }
2578
2579 rc = 0;
2580
2581out:
2582 return rc;
2583}
Paul Lawrencef4faa572014-01-29 13:31:03 -08002584
2585/* Checks userdata. Attempt to mount the volume if default-
2586 * encrypted.
2587 * On success trigger next init phase and return 0.
2588 * Currently do not handle failure - see TODO below.
2589 */
2590int cryptfs_mount_default_encrypted(void)
2591{
2592 char decrypt_state[PROPERTY_VALUE_MAX];
2593 property_get("vold.decrypt", decrypt_state, "0");
2594 if (!strcmp(decrypt_state, "0")) {
2595 SLOGE("Not encrypted - should not call here");
2596 } else {
2597 int crypt_type = cryptfs_get_password_type();
2598 if (crypt_type < 0 || crypt_type > CRYPT_TYPE_MAX_TYPE) {
2599 SLOGE("Bad crypt type - error");
2600 } else if (crypt_type != CRYPT_TYPE_DEFAULT) {
2601 SLOGD("Password is not default - "
2602 "starting min framework to prompt");
2603 property_set("vold.decrypt", "trigger_restart_min_framework");
2604 return 0;
2605 } else if (cryptfs_check_passwd(DEFAULT_PASSWORD) == 0) {
2606 SLOGD("Password is default - restarting filesystem");
2607 cryptfs_restart_internal(0);
2608 return 0;
2609 } else {
2610 SLOGE("Encrypted, default crypt type but can't decrypt");
2611 }
2612 }
2613
2614 /** @TODO make sure we factory wipe in this situation
2615 * In general if we got here there is no recovery
2616 */
2617 return 0;
2618}
2619
2620/* Returns type of the password, default, pattern, pin or password.
2621 */
2622int cryptfs_get_password_type(void)
2623{
2624 struct crypt_mnt_ftr crypt_ftr;
2625
2626 if (get_crypt_ftr_and_key(&crypt_ftr)) {
2627 SLOGE("Error getting crypt footer and key\n");
2628 return -1;
2629 }
2630
2631 return crypt_ftr.crypt_type;
2632}
Paul Lawrence684dbdf2014-02-07 12:07:22 -08002633
2634int cryptfs_just_decrypted(void)
2635{
2636 int rc = just_decrypted;
2637 just_decrypted = 0;
2638 return rc;
2639}