blob: 5751cf74da4420d226c2a89fd12e1a11738a26e0 [file] [log] [blame]
Dees_Troy51a0e822012-09-05 15:24:24 -04001/*
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>
24#include <sys/stat.h>
25#include <fcntl.h>
26#include <unistd.h>
27#include <stdio.h>
28#include <sys/ioctl.h>
29#include <linux/dm-ioctl.h>
30#include <libgen.h>
31#include <stdlib.h>
32#include <sys/param.h>
33#include <string.h>
34#include <sys/mount.h>
35#include <openssl/evp.h>
36#include <openssl/sha.h>
37#include <errno.h>
38#include <cutils/android_reboot.h>
39#include <ext4.h>
40#include <linux/kdev_t.h>
41#include "cryptfs.h"
42#define LOG_TAG "Cryptfs"
43#include "cutils/log.h"
44#include "cutils/properties.h"
45#include "hardware_legacy/power.h"
46//#include "VolumeManager.h"
47
48#define DM_CRYPT_BUF_SIZE 4096
49#define DATA_MNT_POINT "/data"
50
51#define HASH_COUNT 2000
52#define KEY_LEN_BYTES 16
53#define IV_LEN_BYTES 16
54
55#define KEY_LOC_PROP "ro.crypto.keyfile.userdata"
56#define KEY_IN_FOOTER "footer"
57
58#define EXT4_FS 1
59#define FAT_FS 2
60
61char *me = "cryptfs";
62
63static unsigned char saved_master_key[KEY_LEN_BYTES];
64static char *saved_data_blkdev;
65static char *saved_mount_point;
66static int master_key_saved = 0;
67
68static void ioctl_init(struct dm_ioctl *io, size_t dataSize, const char *name, unsigned flags)
69{
70 memset(io, 0, dataSize);
71 io->data_size = dataSize;
72 io->data_start = sizeof(struct dm_ioctl);
73 io->version[0] = 4;
74 io->version[1] = 0;
75 io->version[2] = 0;
76 io->flags = flags;
77 if (name) {
78 strncpy(io->name, name, sizeof(io->name));
79 }
80}
81
82static unsigned int get_fs_size(char *dev)
83{
84 int fd, block_size;
85 struct ext4_super_block sb;
86 off64_t len;
87
88 if ((fd = open(dev, O_RDONLY)) < 0) {
89 SLOGE("Cannot open device to get filesystem size ");
90 return 0;
91 }
92
93 if (lseek64(fd, 1024, SEEK_SET) < 0) {
94 SLOGE("Cannot seek to superblock");
95 return 0;
96 }
97
98 if (read(fd, &sb, sizeof(sb)) != sizeof(sb)) {
99 SLOGE("Cannot read superblock");
100 return 0;
101 }
102
103 close(fd);
104
105 block_size = 1024 << sb.s_log_block_size;
106 /* compute length in bytes */
107 len = ( ((off64_t)sb.s_blocks_count_hi << 32) + sb.s_blocks_count_lo) * block_size;
108
109 /* return length in sectors */
110 return (unsigned int) (len / 512);
111}
112
113static unsigned int get_blkdev_size(int fd)
114{
115 unsigned int nr_sec;
116
117 if ( (ioctl(fd, BLKGETSIZE, &nr_sec)) == -1) {
118 nr_sec = 0;
119 }
120
121 return nr_sec;
122}
123
124/* key or salt can be NULL, in which case just skip writing that value. Useful to
125 * update the failed mount count but not change the key.
126 */
127static int put_crypt_ftr_and_key(char *real_blk_name, struct crypt_mnt_ftr *crypt_ftr,
128 unsigned char *key, unsigned char *salt)
129{
130 int fd;
131 unsigned int nr_sec, cnt;
132 off64_t off;
133 int rc = -1;
134 char *fname;
135 char key_loc[PROPERTY_VALUE_MAX];
136 struct stat statbuf;
137
138 property_get(KEY_LOC_PROP, key_loc, KEY_IN_FOOTER);
139
140 if (!strcmp(key_loc, KEY_IN_FOOTER)) {
141 fname = real_blk_name;
142 if ( (fd = open(fname, O_RDWR)) < 0) {
143 SLOGE("Cannot open real block device %s\n", fname);
144 return -1;
145 }
146
147 if ( (nr_sec = get_blkdev_size(fd)) == 0) {
148 SLOGE("Cannot get size of block device %s\n", fname);
149 goto errout;
150 }
151
152 /* If it's an encrypted Android partition, the last 16 Kbytes contain the
153 * encryption info footer and key, and plenty of bytes to spare for future
154 * growth.
155 */
156 off = ((off64_t)nr_sec * 512) - CRYPT_FOOTER_OFFSET;
157
158 if (lseek64(fd, off, SEEK_SET) == -1) {
159 SLOGE("Cannot seek to real block device footer\n");
160 goto errout;
161 }
162 } else if (key_loc[0] == '/') {
163 fname = key_loc;
164 if ( (fd = open(fname, O_RDWR | O_CREAT, 0600)) < 0) {
165 SLOGE("Cannot open footer file %s\n", fname);
166 return -1;
167 }
168 } else {
169 SLOGE("Unexpected value for" KEY_LOC_PROP "\n");
170 return -1;;
171 }
172
173 if ((cnt = write(fd, crypt_ftr, sizeof(struct crypt_mnt_ftr))) != sizeof(struct crypt_mnt_ftr)) {
174 SLOGE("Cannot write real block device footer\n");
175 goto errout;
176 }
177
178 if (key) {
179 if (crypt_ftr->keysize != KEY_LEN_BYTES) {
180 SLOGE("Keysize of %d bits not supported for real block device %s\n",
181 crypt_ftr->keysize*8, fname);
182 goto errout;
183 }
184
185 if ( (cnt = write(fd, key, crypt_ftr->keysize)) != crypt_ftr->keysize) {
186 SLOGE("Cannot write key for real block device %s\n", fname);
187 goto errout;
188 }
189 }
190
191 if (salt) {
192 /* Compute the offset from the last write to the salt */
193 off = KEY_TO_SALT_PADDING;
194 if (! key)
195 off += crypt_ftr->keysize;
196
197 if (lseek64(fd, off, SEEK_CUR) == -1) {
198 SLOGE("Cannot seek to real block device salt \n");
199 goto errout;
200 }
201
202 if ( (cnt = write(fd, salt, SALT_LEN)) != SALT_LEN) {
203 SLOGE("Cannot write salt for real block device %s\n", fname);
204 goto errout;
205 }
206 }
207
208 fstat(fd, &statbuf);
209 /* If the keys are kept on a raw block device, do not try to truncate it. */
210 if (S_ISREG(statbuf.st_mode) && (key_loc[0] == '/')) {
211 if (ftruncate(fd, 0x4000)) {
212 SLOGE("Cannot set footer file size\n", fname);
213 goto errout;
214 }
215 }
216
217 /* Success! */
218 rc = 0;
219
220errout:
221 close(fd);
222 return rc;
223
224}
225
226static int get_crypt_ftr_and_key(char *real_blk_name, struct crypt_mnt_ftr *crypt_ftr,
227 unsigned char *key, unsigned char *salt)
228{
229 int fd;
230 unsigned int nr_sec, cnt;
231 off64_t off;
232 int rc = -1;
233 char key_loc[PROPERTY_VALUE_MAX];
234 char *fname;
235 struct stat statbuf;
236
237 property_get(KEY_LOC_PROP, key_loc, KEY_IN_FOOTER);
238
239 if (!strcmp(key_loc, KEY_IN_FOOTER)) {
240 fname = real_blk_name;
241 if ( (fd = open(fname, O_RDONLY)) < 0) {
Dees_Troyab10ee22012-09-21 14:27:30 -0400242 printf("Cannot open real block device %s\n", fname);
Dees_Troy51a0e822012-09-05 15:24:24 -0400243 return -1;
244 }
245
246 if ( (nr_sec = get_blkdev_size(fd)) == 0) {
247 SLOGE("Cannot get size of block device %s\n", fname);
248 goto errout;
249 }
250
251 /* If it's an encrypted Android partition, the last 16 Kbytes contain the
252 * encryption info footer and key, and plenty of bytes to spare for future
253 * growth.
254 */
255 off = ((off64_t)nr_sec * 512) - CRYPT_FOOTER_OFFSET;
256
257 if (lseek64(fd, off, SEEK_SET) == -1) {
Dees_Troyab10ee22012-09-21 14:27:30 -0400258 printf("Cannot seek to real block device footer\n");
Dees_Troy51a0e822012-09-05 15:24:24 -0400259 goto errout;
260 }
261 } else if (key_loc[0] == '/') {
262 fname = key_loc;
263 if ( (fd = open(fname, O_RDONLY)) < 0) {
Dees_Troyab10ee22012-09-21 14:27:30 -0400264 printf("Cannot open footer file %s\n", fname);
Dees_Troy51a0e822012-09-05 15:24:24 -0400265 return -1;
266 }
267
268 /* Make sure it's 16 Kbytes in length */
269 fstat(fd, &statbuf);
270 if (S_ISREG(statbuf.st_mode) && (statbuf.st_size != 0x4000)) {
Dees_Troyab10ee22012-09-21 14:27:30 -0400271 printf("footer file %s is not the expected size!\n", fname);
Dees_Troy51a0e822012-09-05 15:24:24 -0400272 goto errout;
273 }
274 } else {
Dees_Troyab10ee22012-09-21 14:27:30 -0400275 printf("Unexpected value for" KEY_LOC_PROP "\n");
Dees_Troy51a0e822012-09-05 15:24:24 -0400276 return -1;;
277 }
278
279 if ( (cnt = read(fd, crypt_ftr, sizeof(struct crypt_mnt_ftr))) != sizeof(struct crypt_mnt_ftr)) {
Dees_Troyab10ee22012-09-21 14:27:30 -0400280 printf("Cannot read real block device footer\n");
Dees_Troy51a0e822012-09-05 15:24:24 -0400281 goto errout;
282 }
283
284 if (crypt_ftr->magic != CRYPT_MNT_MAGIC) {
Dees_Troyab10ee22012-09-21 14:27:30 -0400285 printf("Bad magic for real block device %s\n", fname);
Dees_Troy51a0e822012-09-05 15:24:24 -0400286 goto errout;
287 }
288
289 if (crypt_ftr->major_version != 1) {
Dees_Troyab10ee22012-09-21 14:27:30 -0400290 printf("Cannot understand major version %d real block device footer\n",
Dees_Troy51a0e822012-09-05 15:24:24 -0400291 crypt_ftr->major_version);
292 goto errout;
293 }
294
295 if (crypt_ftr->minor_version != 0) {
Dees_Troyab10ee22012-09-21 14:27:30 -0400296 printf("Warning: crypto footer minor version %d, expected 0, continuing...\n",
Dees_Troy51a0e822012-09-05 15:24:24 -0400297 crypt_ftr->minor_version);
298 }
299
300 if (crypt_ftr->ftr_size > sizeof(struct crypt_mnt_ftr)) {
301 /* the footer size is bigger than we expected.
302 * Skip to it's stated end so we can read the key.
303 */
304 if (lseek(fd, crypt_ftr->ftr_size - sizeof(struct crypt_mnt_ftr), SEEK_CUR) == -1) {
Dees_Troyab10ee22012-09-21 14:27:30 -0400305 printf("Cannot seek to start of key\n");
Dees_Troy51a0e822012-09-05 15:24:24 -0400306 goto errout;
307 }
308 }
309
310 if (crypt_ftr->keysize != KEY_LEN_BYTES) {
Dees_Troyab10ee22012-09-21 14:27:30 -0400311 printf("Keysize of %d bits not supported for real block device %s\n",
Dees_Troy51a0e822012-09-05 15:24:24 -0400312 crypt_ftr->keysize * 8, fname);
313 goto errout;
314 }
315
316 if ( (cnt = read(fd, key, crypt_ftr->keysize)) != crypt_ftr->keysize) {
Dees_Troyab10ee22012-09-21 14:27:30 -0400317 printf("Cannot read key for real block device %s\n", fname);
Dees_Troy51a0e822012-09-05 15:24:24 -0400318 goto errout;
319 }
320
321 if (lseek64(fd, KEY_TO_SALT_PADDING, SEEK_CUR) == -1) {
Dees_Troyab10ee22012-09-21 14:27:30 -0400322 printf("Cannot seek to real block device salt\n");
Dees_Troy51a0e822012-09-05 15:24:24 -0400323 goto errout;
324 }
325
326 if ( (cnt = read(fd, salt, SALT_LEN)) != SALT_LEN) {
Dees_Troyab10ee22012-09-21 14:27:30 -0400327 printf("Cannot read salt for real block device %s\n", fname);
Dees_Troy51a0e822012-09-05 15:24:24 -0400328 goto errout;
329 }
330
331 /* Success! */
332 rc = 0;
333
334errout:
335 close(fd);
336 return rc;
337}
338
339/* Convert a binary key of specified length into an ascii hex string equivalent,
340 * without the leading 0x and with null termination
341 */
342void convert_key_to_hex_ascii(unsigned char *master_key, unsigned int keysize,
343 char *master_key_ascii)
344{
345 unsigned int i, a;
346 unsigned char nibble;
347
348 for (i=0, a=0; i<keysize; i++, a+=2) {
349 /* For each byte, write out two ascii hex digits */
350 nibble = (master_key[i] >> 4) & 0xf;
351 master_key_ascii[a] = nibble + (nibble > 9 ? 0x37 : 0x30);
352
353 nibble = master_key[i] & 0xf;
354 master_key_ascii[a+1] = nibble + (nibble > 9 ? 0x37 : 0x30);
355 }
356
357 /* Add the null termination */
358 master_key_ascii[a] = '\0';
359
360}
361
362static int create_crypto_blk_dev(struct crypt_mnt_ftr *crypt_ftr, unsigned char *master_key,
363 char *real_blk_name, char *crypto_blk_name, const char *name)
364{
365 char buffer[DM_CRYPT_BUF_SIZE];
366 char master_key_ascii[129]; /* Large enough to hold 512 bit key and null */
367 char *crypt_params;
368 struct dm_ioctl *io;
369 struct dm_target_spec *tgt;
370 unsigned int minor;
371 int fd;
372 int retval = -1;
373
374 if ((fd = open("/dev/device-mapper", O_RDWR)) < 0 ) {
Dees_Troyab10ee22012-09-21 14:27:30 -0400375 printf("Cannot open device-mapper\n");
Dees_Troy51a0e822012-09-05 15:24:24 -0400376 goto errout;
377 }
378
379 io = (struct dm_ioctl *) buffer;
380
381 ioctl_init(io, DM_CRYPT_BUF_SIZE, name, 0);
382 if (ioctl(fd, DM_DEV_CREATE, io)) {
Dees_Troyab10ee22012-09-21 14:27:30 -0400383 printf("Cannot create dm-crypt device\n");
Dees_Troy51a0e822012-09-05 15:24:24 -0400384 goto errout;
385 }
386
387 /* Get the device status, in particular, the name of it's device file */
388 ioctl_init(io, DM_CRYPT_BUF_SIZE, name, 0);
389 if (ioctl(fd, DM_DEV_STATUS, io)) {
Dees_Troyab10ee22012-09-21 14:27:30 -0400390 printf("Cannot retrieve dm-crypt device status\n");
Dees_Troy51a0e822012-09-05 15:24:24 -0400391 goto errout;
392 }
393 minor = (io->dev & 0xff) | ((io->dev >> 12) & 0xfff00);
394 snprintf(crypto_blk_name, MAXPATHLEN, "/dev/block/dm-%u", minor);
395
396 /* Load the mapping table for this device */
397 tgt = (struct dm_target_spec *) &buffer[sizeof(struct dm_ioctl)];
398
399 ioctl_init(io, 4096, name, 0);
400 io->target_count = 1;
401 tgt->status = 0;
402 tgt->sector_start = 0;
403 tgt->length = crypt_ftr->fs_size;
404 strcpy(tgt->target_type, "crypt");
405
406 crypt_params = buffer + sizeof(struct dm_ioctl) + sizeof(struct dm_target_spec);
407 convert_key_to_hex_ascii(master_key, crypt_ftr->keysize, master_key_ascii);
408 sprintf(crypt_params, "%s %s 0 %s 0", crypt_ftr->crypto_type_name,
409 master_key_ascii, real_blk_name);
410 crypt_params += strlen(crypt_params) + 1;
411 crypt_params = (char *) (((unsigned long)crypt_params + 7) & ~8); /* Align to an 8 byte boundary */
412 tgt->next = crypt_params - buffer;
413
414 if (ioctl(fd, DM_TABLE_LOAD, io)) {
Dees_Troyab10ee22012-09-21 14:27:30 -0400415 printf("Cannot load dm-crypt mapping table.\n");
Dees_Troy51a0e822012-09-05 15:24:24 -0400416 goto errout;
417 }
418
419 /* Resume this device to activate it */
420 ioctl_init(io, 4096, name, 0);
421
422 if (ioctl(fd, DM_DEV_SUSPEND, io)) {
Dees_Troyab10ee22012-09-21 14:27:30 -0400423 printf("Cannot resume the dm-crypt device\n");
Dees_Troy51a0e822012-09-05 15:24:24 -0400424 goto errout;
425 }
426
427 /* We made it here with no errors. Woot! */
428 retval = 0;
429
430errout:
431 close(fd); /* If fd is <0 from a failed open call, it's safe to just ignore the close error */
432
433 return retval;
434}
435
436static int delete_crypto_blk_dev(char *name)
437{
438 int fd;
439 char buffer[DM_CRYPT_BUF_SIZE];
440 struct dm_ioctl *io;
441 int retval = -1;
442
443 if ((fd = open("/dev/device-mapper", O_RDWR)) < 0 ) {
Dees_Troyab10ee22012-09-21 14:27:30 -0400444 printf("Cannot open device-mapper\n");
Dees_Troy51a0e822012-09-05 15:24:24 -0400445 goto errout;
446 }
447
448 io = (struct dm_ioctl *) buffer;
449
450 ioctl_init(io, DM_CRYPT_BUF_SIZE, name, 0);
451 if (ioctl(fd, DM_DEV_REMOVE, io)) {
Dees_Troyab10ee22012-09-21 14:27:30 -0400452 printf("Cannot remove dm-crypt device\n");
Dees_Troy51a0e822012-09-05 15:24:24 -0400453 goto errout;
454 }
455
456 /* We made it here with no errors. Woot! */
457 retval = 0;
458
459errout:
460 close(fd); /* If fd is <0 from a failed open call, it's safe to just ignore the close error */
461
462 return retval;
463
464}
465
466static void pbkdf2(char *passwd, unsigned char *salt, unsigned char *ikey)
467{
468 /* Turn the password into a key and IV that can decrypt the master key */
469 PKCS5_PBKDF2_HMAC_SHA1(passwd, strlen(passwd), salt, SALT_LEN,
470 HASH_COUNT, KEY_LEN_BYTES+IV_LEN_BYTES, ikey);
471}
472
473static int encrypt_master_key(char *passwd, unsigned char *salt,
474 unsigned char *decrypted_master_key,
475 unsigned char *encrypted_master_key)
476{
477 unsigned char ikey[32+32] = { 0 }; /* Big enough to hold a 256 bit key and 256 bit IV */
478 EVP_CIPHER_CTX e_ctx;
479 int encrypted_len, final_len;
480
481 /* Turn the password into a key and IV that can decrypt the master key */
482 pbkdf2(passwd, salt, ikey);
483
484 /* Initialize the decryption engine */
485 if (! EVP_EncryptInit(&e_ctx, EVP_aes_128_cbc(), ikey, ikey+KEY_LEN_BYTES)) {
486 SLOGE("EVP_EncryptInit failed\n");
487 return -1;
488 }
489 EVP_CIPHER_CTX_set_padding(&e_ctx, 0); /* Turn off padding as our data is block aligned */
490
491 /* Encrypt the master key */
492 if (! EVP_EncryptUpdate(&e_ctx, encrypted_master_key, &encrypted_len,
493 decrypted_master_key, KEY_LEN_BYTES)) {
494 SLOGE("EVP_EncryptUpdate failed\n");
495 return -1;
496 }
497 if (! EVP_EncryptFinal(&e_ctx, encrypted_master_key + encrypted_len, &final_len)) {
498 SLOGE("EVP_EncryptFinal failed\n");
499 return -1;
500 }
501
502 if (encrypted_len + final_len != KEY_LEN_BYTES) {
503 SLOGE("EVP_Encryption length check failed with %d, %d bytes\n", encrypted_len, final_len);
504 return -1;
505 } else {
506 return 0;
507 }
508}
509
510static int decrypt_master_key(char *passwd, unsigned char *salt,
511 unsigned char *encrypted_master_key,
512 unsigned char *decrypted_master_key)
513{
514 unsigned char ikey[32+32] = { 0 }; /* Big enough to hold a 256 bit key and 256 bit IV */
515 EVP_CIPHER_CTX d_ctx;
516 int decrypted_len, final_len;
517
518 /* Turn the password into a key and IV that can decrypt the master key */
519 pbkdf2(passwd, salt, ikey);
520
521 /* Initialize the decryption engine */
522 if (! EVP_DecryptInit(&d_ctx, EVP_aes_128_cbc(), ikey, ikey+KEY_LEN_BYTES)) {
523 return -1;
524 }
525 EVP_CIPHER_CTX_set_padding(&d_ctx, 0); /* Turn off padding as our data is block aligned */
526 /* Decrypt the master key */
527 if (! EVP_DecryptUpdate(&d_ctx, decrypted_master_key, &decrypted_len,
528 encrypted_master_key, KEY_LEN_BYTES)) {
529 return -1;
530 }
531 if (! EVP_DecryptFinal(&d_ctx, decrypted_master_key + decrypted_len, &final_len)) {
532 return -1;
533 }
534
535 if (decrypted_len + final_len != KEY_LEN_BYTES) {
536 return -1;
537 } else {
538 return 0;
539 }
540}
541
542static int create_encrypted_random_key(char *passwd, unsigned char *master_key, unsigned char *salt)
543{
544 int fd;
545 unsigned char key_buf[KEY_LEN_BYTES];
546 EVP_CIPHER_CTX e_ctx;
547 int encrypted_len, final_len;
548
549 /* Get some random bits for a key */
550 fd = open("/dev/urandom", O_RDONLY);
551 read(fd, key_buf, sizeof(key_buf));
552 read(fd, salt, SALT_LEN);
553 close(fd);
554
555 /* Now encrypt it with the password */
556 return encrypt_master_key(passwd, salt, key_buf, master_key);
557}
558
559static int get_orig_mount_parms(char *mount_point, char *fs_type, char *real_blkdev,
560 unsigned long *mnt_flags, char *fs_options)
561{
562 char mount_point2[PROPERTY_VALUE_MAX];
563 char fs_flags[PROPERTY_VALUE_MAX];
564
565 property_get("ro.crypto.fs_type", fs_type, "");
566 property_get("ro.crypto.fs_real_blkdev", real_blkdev, "");
567 property_get("ro.crypto.fs_mnt_point", mount_point2, "");
568 property_get("ro.crypto.fs_options", fs_options, "");
569 property_get("ro.crypto.fs_flags", fs_flags, "");
570 *mnt_flags = strtol(fs_flags, 0, 0);
571
572 if (strcmp(mount_point, mount_point2)) {
573 /* Consistency check. These should match. If not, something odd happened. */
574 return -1;
575 }
576
577 return 0;
578}
579
580static int wait_and_unmount(char *mountpoint)
581{
582 int i, rc;
583#define WAIT_UNMOUNT_COUNT 20
584
585 /* Now umount the tmpfs filesystem */
586 for (i=0; i<WAIT_UNMOUNT_COUNT; i++) {
587 if (umount(mountpoint)) {
588 if (errno == EINVAL) {
589 /* EINVAL is returned if the directory is not a mountpoint,
590 * i.e. there is no filesystem mounted there. So just get out.
591 */
592 break;
593 }
594 sleep(1);
595 i++;
596 } else {
597 break;
598 }
599 }
600
601 if (i < WAIT_UNMOUNT_COUNT) {
602 SLOGD("unmounting %s succeeded\n", mountpoint);
603 rc = 0;
604 } else {
605 SLOGE("unmounting %s failed\n", mountpoint);
606 rc = -1;
607 }
608
609 return rc;
610}
611
612#define DATA_PREP_TIMEOUT 100
613static int prep_data_fs(void)
614{
615 int i;
616
617 /* Do the prep of the /data filesystem */
618 property_set("vold.post_fs_data_done", "0");
619 property_set("vold.decrypt", "trigger_post_fs_data");
620 SLOGD("Just triggered post_fs_data\n");
621
622 /* Wait a max of 25 seconds, hopefully it takes much less */
623 for (i=0; i<DATA_PREP_TIMEOUT; i++) {
624 char p[PROPERTY_VALUE_MAX];
625
626 property_get("vold.post_fs_data_done", p, "0");
627 if (*p == '1') {
628 break;
629 } else {
630 usleep(250000);
631 }
632 }
633 if (i == DATA_PREP_TIMEOUT) {
634 /* Ugh, we failed to prep /data in time. Bail. */
635 return -1;
636 } else {
637 SLOGD("post_fs_data done\n");
638 return 0;
639 }
640}
641
642int cryptfs_restart(void)
643{
644 char fs_type[32];
645 char real_blkdev[MAXPATHLEN];
646 char crypto_blkdev[MAXPATHLEN];
647 char fs_options[256];
648 unsigned long mnt_flags;
649 struct stat statbuf;
650 int rc = -1, i;
651 static int restart_successful = 0;
652
653 /* Validate that it's OK to call this routine */
654 if (! master_key_saved) {
655 SLOGE("Encrypted filesystem not validated, aborting");
656 return -1;
657 }
658
659 if (restart_successful) {
660 SLOGE("System already restarted with encrypted disk, aborting");
661 return -1;
662 }
663
664 /* Here is where we shut down the framework. The init scripts
665 * start all services in one of three classes: core, main or late_start.
666 * On boot, we start core and main. Now, we stop main, but not core,
667 * as core includes vold and a few other really important things that
668 * we need to keep running. Once main has stopped, we should be able
669 * to umount the tmpfs /data, then mount the encrypted /data.
670 * We then restart the class main, and also the class late_start.
671 * At the moment, I've only put a few things in late_start that I know
672 * are not needed to bring up the framework, and that also cause problems
673 * with unmounting the tmpfs /data, but I hope to add add more services
674 * to the late_start class as we optimize this to decrease the delay
675 * till the user is asked for the password to the filesystem.
676 */
677
678 /* The init files are setup to stop the class main when vold.decrypt is
679 * set to trigger_reset_main.
680 */
681 property_set("vold.decrypt", "trigger_reset_main");
682 SLOGD("Just asked init to shut down class main\n");
683
684 /* Now that the framework is shutdown, we should be able to umount()
685 * the tmpfs filesystem, and mount the real one.
686 */
687
688 property_get("ro.crypto.fs_crypto_blkdev", crypto_blkdev, "");
689 if (strlen(crypto_blkdev) == 0) {
690 SLOGE("fs_crypto_blkdev not set\n");
691 return -1;
692 }
693
694 if (! get_orig_mount_parms(DATA_MNT_POINT, fs_type, real_blkdev, &mnt_flags, fs_options)) {
695 SLOGD("Just got orig mount parms\n");
696
697 if (! (rc = wait_and_unmount(DATA_MNT_POINT)) ) {
698 /* If that succeeded, then mount the decrypted filesystem */
699 mount(crypto_blkdev, DATA_MNT_POINT, fs_type, mnt_flags, fs_options);
700
701 property_set("vold.decrypt", "trigger_load_persist_props");
702 /* Create necessary paths on /data */
703 if (prep_data_fs()) {
704 return -1;
705 }
706
707 /* startup service classes main and late_start */
708 property_set("vold.decrypt", "trigger_restart_framework");
709 SLOGD("Just triggered restart_framework\n");
710
711 /* Give it a few moments to get started */
712 sleep(1);
713 }
714 }
715
716 if (rc == 0) {
717 restart_successful = 1;
718 }
719
720 return rc;
721}
722
723static int do_crypto_complete(char *mount_point)
724{
725 struct crypt_mnt_ftr crypt_ftr;
726 unsigned char encrypted_master_key[32];
727 unsigned char salt[SALT_LEN];
728 char real_blkdev[MAXPATHLEN];
729 char fs_type[PROPERTY_VALUE_MAX];
730 char fs_options[PROPERTY_VALUE_MAX];
731 unsigned long mnt_flags;
732 char encrypted_state[PROPERTY_VALUE_MAX];
733
734 property_get("ro.crypto.state", encrypted_state, "");
735 if (strcmp(encrypted_state, "encrypted") ) {
736 SLOGE("not running with encryption, aborting");
737 return 1;
738 }
739
740 if (get_orig_mount_parms(mount_point, fs_type, real_blkdev, &mnt_flags, fs_options)) {
741 SLOGE("Error reading original mount parms for mount point %s\n", mount_point);
742 return -1;
743 }
744
745 if (get_crypt_ftr_and_key(real_blkdev, &crypt_ftr, encrypted_master_key, salt)) {
746 SLOGE("Error getting crypt footer and key\n");
747 return -1;
748 }
749
750 if (crypt_ftr.flags & CRYPT_ENCRYPTION_IN_PROGRESS) {
751 SLOGE("Encryption process didn't finish successfully\n");
752 return -2; /* -2 is the clue to the UI that there is no usable data on the disk,
753 * and give the user an option to wipe the disk */
754 }
755
756 /* We passed the test! We shall diminish, and return to the west */
757 return 0;
758}
759
760static int test_mount_encrypted_fs(char *passwd, char *mount_point, char *label)
761{
762 struct crypt_mnt_ftr crypt_ftr;
763 /* Allocate enough space for a 256 bit key, but we may use less */
764 unsigned char encrypted_master_key[32], decrypted_master_key[32];
765 unsigned char salt[SALT_LEN];
766 char crypto_blkdev[MAXPATHLEN];
767 char real_blkdev[MAXPATHLEN];
768 char fs_type[PROPERTY_VALUE_MAX];
769 char fs_options[PROPERTY_VALUE_MAX];
770 char tmp_mount_point[64];
771 unsigned long mnt_flags;
772 unsigned int orig_failed_decrypt_count;
773 char encrypted_state[PROPERTY_VALUE_MAX];
774 int rc;
775
776 property_get("ro.crypto.state", encrypted_state, "");
777 if ( master_key_saved || strcmp(encrypted_state, "encrypted") ) {
Dees_Troyab10ee22012-09-21 14:27:30 -0400778 printf("encrypted fs already validated or not running with encryption, aborting");
Dees_Troy51a0e822012-09-05 15:24:24 -0400779 return -1;
780 }
781
782 if (get_orig_mount_parms(mount_point, fs_type, real_blkdev, &mnt_flags, fs_options)) {
Dees_Troyab10ee22012-09-21 14:27:30 -0400783 printf("Error reading original mount parms for mount point %s\n", mount_point);
Dees_Troy51a0e822012-09-05 15:24:24 -0400784 return -1;
785 }
786
787 if (get_crypt_ftr_and_key(real_blkdev, &crypt_ftr, encrypted_master_key, salt)) {
Dees_Troyab10ee22012-09-21 14:27:30 -0400788 printf("Error getting crypt footer and key\n");
Dees_Troy51a0e822012-09-05 15:24:24 -0400789 return -1;
790 }
791
Dees_Troyab10ee22012-09-21 14:27:30 -0400792 printf("crypt_ftr->fs_size = %lld\n", crypt_ftr.fs_size);
Dees_Troy51a0e822012-09-05 15:24:24 -0400793 orig_failed_decrypt_count = crypt_ftr.failed_decrypt_count;
794
795 if (! (crypt_ftr.flags & CRYPT_MNT_KEY_UNENCRYPTED) ) {
796 decrypt_master_key(passwd, salt, encrypted_master_key, decrypted_master_key);
797 }
798
799 if (create_crypto_blk_dev(&crypt_ftr, decrypted_master_key,
800 real_blkdev, crypto_blkdev, label)) {
Dees_Troyab10ee22012-09-21 14:27:30 -0400801 printf("Error creating decrypted block device\n");
Dees_Troy51a0e822012-09-05 15:24:24 -0400802 return -1;
803 }
804
805 /* If init detects an encrypted filesystme, it writes a file for each such
806 * encrypted fs into the tmpfs /data filesystem, and then the framework finds those
807 * files and passes that data to me */
808 /* Create a tmp mount point to try mounting the decryptd fs
809 * Since we're here, the mount_point should be a tmpfs filesystem, so make
810 * a directory in it to test mount the decrypted filesystem.
811 */
812 sprintf(tmp_mount_point, "%s/tmp_mnt", mount_point);
813 mkdir(tmp_mount_point, 0755);
814 if ( mount(crypto_blkdev, tmp_mount_point, "ext4", MS_RDONLY, "") ) {
Dees_Troyab10ee22012-09-21 14:27:30 -0400815 printf("Error temp mounting decrypted block device\n");
Dees_Troy51a0e822012-09-05 15:24:24 -0400816 delete_crypto_blk_dev(label);
817 crypt_ftr.failed_decrypt_count++;
818 } else {
819 /* Success, so just umount and we'll mount it properly when we restart
820 * the framework.
821 */
822 umount(tmp_mount_point);
823 crypt_ftr.failed_decrypt_count = 0;
824 }
825
826 if (orig_failed_decrypt_count != crypt_ftr.failed_decrypt_count) {
827 put_crypt_ftr_and_key(real_blkdev, &crypt_ftr, 0, 0);
828 }
829
830 if (crypt_ftr.failed_decrypt_count) {
831 /* We failed to mount the device, so return an error */
832 rc = crypt_ftr.failed_decrypt_count;
833
834 } else {
835 /* Woot! Success! Save the name of the crypto block device
836 * so we can mount it when restarting the framework.
837 */
838 property_set("ro.crypto.fs_crypto_blkdev", crypto_blkdev);
839
840 /* Also save a the master key so we can reencrypted the key
841 * the key when we want to change the password on it.
842 */
843 memcpy(saved_master_key, decrypted_master_key, KEY_LEN_BYTES);
844 saved_data_blkdev = strdup(real_blkdev);
845 saved_mount_point = strdup(mount_point);
846 master_key_saved = 1;
847 rc = 0;
848 }
849
850 return rc;
851}
852
853/* Called by vold when it wants to undo the crypto mapping of a volume it
854 * manages. This is usually in response to a factory reset, when we want
855 * to undo the crypto mapping so the volume is formatted in the clear.
856 */
857int cryptfs_revert_volume(const char *label)
858{
859 return delete_crypto_blk_dev((char *)label);
860}
861
862/*
863 * Called by vold when it's asked to mount an encrypted, nonremovable volume.
864 * Setup a dm-crypt mapping, use the saved master key from
865 * setting up the /data mapping, and return the new device path.
866 */
867int cryptfs_setup_volume(const char *label, int major, int minor,
868 char *crypto_sys_path, unsigned int max_path,
869 int *new_major, int *new_minor)
870{
871 char real_blkdev[MAXPATHLEN], crypto_blkdev[MAXPATHLEN];
872 struct crypt_mnt_ftr sd_crypt_ftr;
873 unsigned char key[32], salt[32];
874 struct stat statbuf;
875 int nr_sec, fd;
876
877 sprintf(real_blkdev, "/dev/block/vold/%d:%d", major, minor);
878
879 /* Just want the footer, but gotta get it all */
880 get_crypt_ftr_and_key(saved_data_blkdev, &sd_crypt_ftr, key, salt);
881
882 /* Update the fs_size field to be the size of the volume */
883 fd = open(real_blkdev, O_RDONLY);
884 nr_sec = get_blkdev_size(fd);
885 close(fd);
886 if (nr_sec == 0) {
887 SLOGE("Cannot get size of volume %s\n", real_blkdev);
888 return -1;
889 }
890
891 sd_crypt_ftr.fs_size = nr_sec;
892 create_crypto_blk_dev(&sd_crypt_ftr, saved_master_key, real_blkdev,
893 crypto_blkdev, label);
894
895 stat(crypto_blkdev, &statbuf);
896 *new_major = MAJOR(statbuf.st_rdev);
897 *new_minor = MINOR(statbuf.st_rdev);
898
899 /* Create path to sys entry for this block device */
900 snprintf(crypto_sys_path, max_path, "/devices/virtual/block/%s", strrchr(crypto_blkdev, '/')+1);
901
902 return 0;
903}
904
905int cryptfs_crypto_complete(void)
906{
907 return do_crypto_complete("/data");
908}
909
910int cryptfs_check_passwd(char *passwd)
911{
912 int rc = -1;
913
914 rc = test_mount_encrypted_fs(passwd, DATA_MNT_POINT, "userdata");
915
916 return rc;
917}
918
919int cryptfs_verify_passwd(char *passwd)
920{
921 struct crypt_mnt_ftr crypt_ftr;
922 /* Allocate enough space for a 256 bit key, but we may use less */
923 unsigned char encrypted_master_key[32], decrypted_master_key[32];
924 unsigned char salt[SALT_LEN];
925 char real_blkdev[MAXPATHLEN];
926 char fs_type[PROPERTY_VALUE_MAX];
927 char fs_options[PROPERTY_VALUE_MAX];
928 unsigned long mnt_flags;
929 char encrypted_state[PROPERTY_VALUE_MAX];
930 int rc;
931
932 property_get("ro.crypto.state", encrypted_state, "");
933 if (strcmp(encrypted_state, "encrypted") ) {
934 SLOGE("device not encrypted, aborting");
935 return -2;
936 }
937
938 if (!master_key_saved) {
939 SLOGE("encrypted fs not yet mounted, aborting");
940 return -1;
941 }
942
943 if (!saved_mount_point) {
944 SLOGE("encrypted fs failed to save mount point, aborting");
945 return -1;
946 }
947
948 if (get_orig_mount_parms(saved_mount_point, fs_type, real_blkdev, &mnt_flags, fs_options)) {
949 SLOGE("Error reading original mount parms for mount point %s\n", saved_mount_point);
950 return -1;
951 }
952
953 if (get_crypt_ftr_and_key(real_blkdev, &crypt_ftr, encrypted_master_key, salt)) {
954 SLOGE("Error getting crypt footer and key\n");
955 return -1;
956 }
957
958 if (crypt_ftr.flags & CRYPT_MNT_KEY_UNENCRYPTED) {
959 /* If the device has no password, then just say the password is valid */
960 rc = 0;
961 } else {
962 decrypt_master_key(passwd, salt, encrypted_master_key, decrypted_master_key);
963 if (!memcmp(decrypted_master_key, saved_master_key, crypt_ftr.keysize)) {
964 /* They match, the password is correct */
965 rc = 0;
966 } else {
967 /* If incorrect, sleep for a bit to prevent dictionary attacks */
968 sleep(1);
969 rc = 1;
970 }
971 }
972
973 return rc;
974}
975
976/* Initialize a crypt_mnt_ftr structure. The keysize is
977 * defaulted to 16 bytes, and the filesystem size to 0.
978 * Presumably, at a minimum, the caller will update the
979 * filesystem size and crypto_type_name after calling this function.
980 */
981static void cryptfs_init_crypt_mnt_ftr(struct crypt_mnt_ftr *ftr)
982{
983 ftr->magic = CRYPT_MNT_MAGIC;
984 ftr->major_version = 1;
985 ftr->minor_version = 0;
986 ftr->ftr_size = sizeof(struct crypt_mnt_ftr);
987 ftr->flags = 0;
988 ftr->keysize = KEY_LEN_BYTES;
989 ftr->spare1 = 0;
990 ftr->fs_size = 0;
991 ftr->failed_decrypt_count = 0;
992 ftr->crypto_type_name[0] = '\0';
993}
994
995static int cryptfs_enable_wipe(char *crypto_blkdev, off64_t size, int type)
996{
997 char cmdline[256];
998 int rc = -1;
999
1000 if (type == EXT4_FS) {
1001 snprintf(cmdline, sizeof(cmdline), "/system/bin/make_ext4fs -a /data -l %lld %s",
1002 size * 512, crypto_blkdev);
1003 SLOGI("Making empty filesystem with command %s\n", cmdline);
1004 } else if (type== FAT_FS) {
1005 snprintf(cmdline, sizeof(cmdline), "/system/bin/newfs_msdos -F 32 -O android -c 8 -s %lld %s",
1006 size, crypto_blkdev);
1007 SLOGI("Making empty filesystem with command %s\n", cmdline);
1008 } else {
1009 SLOGE("cryptfs_enable_wipe(): unknown filesystem type %d\n", type);
1010 return -1;
1011 }
1012
1013 if (system(cmdline)) {
1014 SLOGE("Error creating empty filesystem on %s\n", crypto_blkdev);
1015 } else {
1016 SLOGD("Successfully created empty filesystem on %s\n", crypto_blkdev);
1017 rc = 0;
1018 }
1019
1020 return rc;
1021}
1022
1023static inline int unix_read(int fd, void* buff, int len)
1024{
1025 int ret;
1026 do { ret = read(fd, buff, len); } while (ret < 0 && errno == EINTR);
1027 return ret;
1028}
1029
1030static inline int unix_write(int fd, const void* buff, int len)
1031{
1032 int ret;
1033 do { ret = write(fd, buff, len); } while (ret < 0 && errno == EINTR);
1034 return ret;
1035}
1036
1037#define CRYPT_INPLACE_BUFSIZE 4096
1038#define CRYPT_SECTORS_PER_BUFSIZE (CRYPT_INPLACE_BUFSIZE / 512)
1039static int cryptfs_enable_inplace(char *crypto_blkdev, char *real_blkdev, off64_t size,
1040 off64_t *size_already_done, off64_t tot_size)
1041{
1042 int realfd, cryptofd;
1043 char *buf[CRYPT_INPLACE_BUFSIZE];
1044 int rc = -1;
1045 off64_t numblocks, i, remainder;
1046 off64_t one_pct, cur_pct, new_pct;
1047 off64_t blocks_already_done, tot_numblocks;
1048
1049 if ( (realfd = open(real_blkdev, O_RDONLY)) < 0) {
1050 SLOGE("Error opening real_blkdev %s for inplace encrypt\n", real_blkdev);
1051 return -1;
1052 }
1053
1054 if ( (cryptofd = open(crypto_blkdev, O_WRONLY)) < 0) {
1055 SLOGE("Error opening crypto_blkdev %s for inplace encrypt\n", crypto_blkdev);
1056 close(realfd);
1057 return -1;
1058 }
1059
1060 /* This is pretty much a simple loop of reading 4K, and writing 4K.
1061 * The size passed in is the number of 512 byte sectors in the filesystem.
1062 * So compute the number of whole 4K blocks we should read/write,
1063 * and the remainder.
1064 */
1065 numblocks = size / CRYPT_SECTORS_PER_BUFSIZE;
1066 remainder = size % CRYPT_SECTORS_PER_BUFSIZE;
1067 tot_numblocks = tot_size / CRYPT_SECTORS_PER_BUFSIZE;
1068 blocks_already_done = *size_already_done / CRYPT_SECTORS_PER_BUFSIZE;
1069
1070 SLOGE("Encrypting filesystem in place...");
1071
1072 one_pct = tot_numblocks / 100;
1073 cur_pct = 0;
1074 /* process the majority of the filesystem in blocks */
1075 for (i=0; i<numblocks; i++) {
1076 new_pct = (i + blocks_already_done) / one_pct;
1077 if (new_pct > cur_pct) {
1078 char buf[8];
1079
1080 cur_pct = new_pct;
1081 snprintf(buf, sizeof(buf), "%lld", cur_pct);
1082 property_set("vold.encrypt_progress", buf);
1083 }
1084 if (unix_read(realfd, buf, CRYPT_INPLACE_BUFSIZE) <= 0) {
1085 SLOGE("Error reading real_blkdev %s for inplace encrypt\n", crypto_blkdev);
1086 goto errout;
1087 }
1088 if (unix_write(cryptofd, buf, CRYPT_INPLACE_BUFSIZE) <= 0) {
1089 SLOGE("Error writing crypto_blkdev %s for inplace encrypt\n", crypto_blkdev);
1090 goto errout;
1091 }
1092 }
1093
1094 /* Do any remaining sectors */
1095 for (i=0; i<remainder; i++) {
1096 if (unix_read(realfd, buf, 512) <= 0) {
1097 SLOGE("Error reading rival sectors from real_blkdev %s for inplace encrypt\n", crypto_blkdev);
1098 goto errout;
1099 }
1100 if (unix_write(cryptofd, buf, 512) <= 0) {
1101 SLOGE("Error writing final sectors to crypto_blkdev %s for inplace encrypt\n", crypto_blkdev);
1102 goto errout;
1103 }
1104 }
1105
1106 *size_already_done += size;
1107 rc = 0;
1108
1109errout:
1110 close(realfd);
1111 close(cryptofd);
1112
1113 return rc;
1114}
1115
1116#define CRYPTO_ENABLE_WIPE 1
1117#define CRYPTO_ENABLE_INPLACE 2
1118
1119#define FRAMEWORK_BOOT_WAIT 60
1120
1121static inline int should_encrypt(struct volume_info *volume)
1122{
1123 return (volume->flags & (VOL_ENCRYPTABLE | VOL_NONREMOVABLE)) ==
1124 (VOL_ENCRYPTABLE | VOL_NONREMOVABLE);
1125}
1126
1127int cryptfs_enable(char *howarg, char *passwd)
1128{
1129 // Code removed because it needs other parts of vold that aren't needed for decryption
1130 return -1;
1131}
1132
1133int cryptfs_changepw(char *newpw)
1134{
1135 struct crypt_mnt_ftr crypt_ftr;
1136 unsigned char encrypted_master_key[KEY_LEN_BYTES], decrypted_master_key[KEY_LEN_BYTES];
1137 unsigned char salt[SALT_LEN];
1138 char real_blkdev[MAXPATHLEN];
1139
1140 /* This is only allowed after we've successfully decrypted the master key */
1141 if (! master_key_saved) {
1142 SLOGE("Key not saved, aborting");
1143 return -1;
1144 }
1145
1146 property_get("ro.crypto.fs_real_blkdev", real_blkdev, "");
1147 if (strlen(real_blkdev) == 0) {
1148 SLOGE("Can't find real blkdev");
1149 return -1;
1150 }
1151
1152 /* get key */
1153 if (get_crypt_ftr_and_key(real_blkdev, &crypt_ftr, encrypted_master_key, salt)) {
1154 SLOGE("Error getting crypt footer and key");
1155 return -1;
1156 }
1157
1158 encrypt_master_key(newpw, salt, saved_master_key, encrypted_master_key);
1159
1160 /* save the key */
1161 put_crypt_ftr_and_key(real_blkdev, &crypt_ftr, encrypted_master_key, salt);
1162
1163 return 0;
1164}