blob: 496b960ad09b42e4a58a2a45cddec4fff5d14bea [file] [log] [blame]
Ethan Yonker4eca40d2014-11-11 14:52:28 -06001/*
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/wait.h>
25#include <sys/stat.h>
26#include <ctype.h>
27#include <fcntl.h>
28#include <inttypes.h>
29#include <unistd.h>
30#include <stdio.h>
31#include <sys/ioctl.h>
32#include <linux/dm-ioctl.h>
33#include <libgen.h>
34#include <stdlib.h>
35#include <sys/param.h>
36#include <string.h>
37#include <sys/mount.h>
38#include <openssl/evp.h>
39#include <errno.h>
Ethan Yonker4eca40d2014-11-11 14:52:28 -060040#include <linux/kdev_t.h>
Ethan Yonker4eca40d2014-11-11 14:52:28 -060041#include <time.h>
42#include "cryptfs.h"
Ethan Yonker4eca40d2014-11-11 14:52:28 -060043#include "cutils/properties.h"
Ethan Yonker4eca40d2014-11-11 14:52:28 -060044#include "crypto_scrypt.h"
Ethan Yonker4eca40d2014-11-11 14:52:28 -060045#include <hardware/keymaster.h>
46
Ethan Yonker253368a2014-11-25 15:00:52 -060047#ifndef min /* already defined by windows.h */
48#define min(a, b) ((a) < (b) ? (a) : (b))
49#endif
50
Ethan Yonker4eca40d2014-11-11 14:52:28 -060051#define UNUSED __attribute__((unused))
52
53#define UNUSED __attribute__((unused))
54
55#define DM_CRYPT_BUF_SIZE 4096
56
57#define HASH_COUNT 2000
58#define KEY_LEN_BYTES 16
59#define IV_LEN_BYTES 16
60
61#define KEY_IN_FOOTER "footer"
62
63// "default_password" encoded into hex (d=0x64 etc)
64#define DEFAULT_PASSWORD "64656661756c745f70617373776f7264"
65
66#define EXT4_FS 1
67#define F2FS_FS 2
68
69#define TABLE_LOAD_RETRIES 10
70
71#define RSA_KEY_SIZE 2048
72#define RSA_KEY_SIZE_BYTES (RSA_KEY_SIZE / 8)
73#define RSA_EXPONENT 0x10001
74
75#define RETRY_MOUNT_ATTEMPTS 10
76#define RETRY_MOUNT_DELAY_SECONDS 1
77
78char *me = "cryptfs";
79
80static unsigned char saved_master_key[KEY_LEN_BYTES];
81static char *saved_mount_point;
82static int master_key_saved = 0;
83static struct crypt_persist_data *persist_data = NULL;
Ethan Yonker253368a2014-11-25 15:00:52 -060084static char key_fname[PROPERTY_VALUE_MAX] = "";
85static char real_blkdev[PROPERTY_VALUE_MAX] = "";
86static char file_system[PROPERTY_VALUE_MAX] = "";
87
88void set_partition_data(const char* block_device, const char* key_location, const char* fs)
89{
90 strcpy(key_fname, key_location);
91 strcpy(real_blkdev, block_device);
92 strcpy(file_system, fs);
93}
Ethan Yonker4eca40d2014-11-11 14:52:28 -060094
95static int keymaster_init(keymaster_device_t **keymaster_dev)
96{
97 int rc;
98
99 const hw_module_t* mod;
100 rc = hw_get_module_by_class(KEYSTORE_HARDWARE_MODULE_ID, NULL, &mod);
101 if (rc) {
102 printf("could not find any keystore module\n");
103 goto out;
104 }
105
106 rc = keymaster_open(mod, keymaster_dev);
107 if (rc) {
108 printf("could not open keymaster device in %s (%s)\n",
109 KEYSTORE_HARDWARE_MODULE_ID, strerror(-rc));
110 goto out;
111 }
112
113 return 0;
114
115out:
116 *keymaster_dev = NULL;
117 return rc;
118}
119
120/* Should we use keymaster? */
121static int keymaster_check_compatibility()
122{
123 keymaster_device_t *keymaster_dev = 0;
124 int rc = 0;
125
126 if (keymaster_init(&keymaster_dev)) {
127 printf("Failed to init keymaster\n");
128 rc = -1;
129 goto out;
130 }
131
132 printf("keymaster version is %d\n", keymaster_dev->common.module->module_api_version);
133
thatceb7b8e2014-12-09 23:15:16 +0100134#if (KEYMASTER_HEADER_VERSION >= 3)
Ethan Yonker4eca40d2014-11-11 14:52:28 -0600135 if (keymaster_dev->common.module->module_api_version
136 < KEYMASTER_MODULE_API_VERSION_0_3) {
137 rc = 0;
138 goto out;
139 }
140
141 if (keymaster_dev->flags & KEYMASTER_BLOBS_ARE_STANDALONE) {
142 rc = 1;
143 }
144
thatceb7b8e2014-12-09 23:15:16 +0100145#endif
Ethan Yonker4eca40d2014-11-11 14:52:28 -0600146out:
147 keymaster_close(keymaster_dev);
148 return rc;
149}
150
151/* Create a new keymaster key and store it in this footer */
152static int keymaster_create_key(struct crypt_mnt_ftr *ftr)
153{
154 uint8_t* key = 0;
155 keymaster_device_t *keymaster_dev = 0;
156
157 if (keymaster_init(&keymaster_dev)) {
158 printf("Failed to init keymaster\n");
159 return -1;
160 }
161
162 int rc = 0;
163
164 keymaster_rsa_keygen_params_t params;
165 memset(&params, '\0', sizeof(params));
166 params.public_exponent = RSA_EXPONENT;
167 params.modulus_size = RSA_KEY_SIZE;
168
169 size_t key_size;
170 if (keymaster_dev->generate_keypair(keymaster_dev, TYPE_RSA, &params,
171 &key, &key_size)) {
172 printf("Failed to generate keypair\n");
173 rc = -1;
174 goto out;
175 }
176
177 if (key_size > KEYMASTER_BLOB_SIZE) {
178 printf("Keymaster key too large for crypto footer\n");
179 rc = -1;
180 goto out;
181 }
182
183 memcpy(ftr->keymaster_blob, key, key_size);
184 ftr->keymaster_blob_size = key_size;
185
186out:
187 keymaster_close(keymaster_dev);
188 free(key);
189 return rc;
190}
191
192/* This signs the given object using the keymaster key. */
193static int keymaster_sign_object(struct crypt_mnt_ftr *ftr,
194 const unsigned char *object,
195 const size_t object_size,
196 unsigned char **signature,
197 size_t *signature_size)
198{
199 int rc = 0;
200 keymaster_device_t *keymaster_dev = 0;
201 if (keymaster_init(&keymaster_dev)) {
202 printf("Failed to init keymaster\n");
203 return -1;
204 }
205
206 /* We currently set the digest type to DIGEST_NONE because it's the
207 * only supported value for keymaster. A similar issue exists with
208 * PADDING_NONE. Long term both of these should likely change.
209 */
210 keymaster_rsa_sign_params_t params;
211 params.digest_type = DIGEST_NONE;
212 params.padding_type = PADDING_NONE;
213
214 unsigned char to_sign[RSA_KEY_SIZE_BYTES];
215 size_t to_sign_size = sizeof(to_sign);
216 memset(to_sign, 0, RSA_KEY_SIZE_BYTES);
217
218 // To sign a message with RSA, the message must satisfy two
219 // constraints:
220 //
221 // 1. The message, when interpreted as a big-endian numeric value, must
222 // be strictly less than the public modulus of the RSA key. Note
223 // that because the most significant bit of the public modulus is
224 // guaranteed to be 1 (else it's an (n-1)-bit key, not an n-bit
225 // key), an n-bit message with most significant bit 0 always
226 // satisfies this requirement.
227 //
228 // 2. The message must have the same length in bits as the public
229 // modulus of the RSA key. This requirement isn't mathematically
230 // necessary, but is necessary to ensure consistency in
231 // implementations.
232 switch (ftr->kdf_type) {
233 case KDF_SCRYPT_KEYMASTER_UNPADDED:
234 // This is broken: It produces a message which is shorter than
235 // the public modulus, failing criterion 2.
236 memcpy(to_sign, object, object_size);
237 to_sign_size = object_size;
238 printf("Signing unpadded object\n");
239 break;
240 case KDF_SCRYPT_KEYMASTER_BADLY_PADDED:
241 // This is broken: Since the value of object is uniformly
242 // distributed, it produces a message that is larger than the
243 // public modulus with probability 0.25.
244 memcpy(to_sign, object, min(RSA_KEY_SIZE_BYTES, object_size));
245 printf("Signing end-padded object\n");
246 break;
247 case KDF_SCRYPT_KEYMASTER:
248 // This ensures the most significant byte of the signed message
249 // is zero. We could have zero-padded to the left instead, but
250 // this approach is slightly more robust against changes in
251 // object size. However, it's still broken (but not unusably
252 // so) because we really should be using a proper RSA padding
253 // function, such as OAEP.
254 //
255 // TODO(paullawrence): When keymaster 0.4 is available, change
256 // this to use the padding options it provides.
257 memcpy(to_sign + 1, object, min(RSA_KEY_SIZE_BYTES - 1, object_size));
258 printf("Signing safely-padded object\n");
259 break;
260 default:
261 printf("Unknown KDF type %d\n", ftr->kdf_type);
262 return -1;
263 }
264
265 rc = keymaster_dev->sign_data(keymaster_dev,
266 &params,
267 ftr->keymaster_blob,
268 ftr->keymaster_blob_size,
269 to_sign,
270 to_sign_size,
271 signature,
272 signature_size);
273
274 keymaster_close(keymaster_dev);
275 return rc;
276}
277
278/* Store password when userdata is successfully decrypted and mounted.
279 * Cleared by cryptfs_clear_password
280 *
281 * To avoid a double prompt at boot, we need to store the CryptKeeper
282 * password and pass it to KeyGuard, which uses it to unlock KeyStore.
283 * Since the entire framework is torn down and rebuilt after encryption,
284 * we have to use a daemon or similar to store the password. Since vold
285 * is secured against IPC except from system processes, it seems a reasonable
286 * place to store this.
287 *
288 * password should be cleared once it has been used.
289 *
290 * password is aged out after password_max_age_seconds seconds.
291 */
292static char* password = 0;
293static int password_expiry_time = 0;
294static const int password_max_age_seconds = 60;
295
Ethan Yonker4eca40d2014-11-11 14:52:28 -0600296static void ioctl_init(struct dm_ioctl *io, size_t dataSize, const char *name, unsigned flags)
297{
298 memset(io, 0, dataSize);
299 io->data_size = dataSize;
300 io->data_start = sizeof(struct dm_ioctl);
301 io->version[0] = 4;
302 io->version[1] = 0;
303 io->version[2] = 0;
304 io->flags = flags;
305 if (name) {
306 strncpy(io->name, name, sizeof(io->name));
307 }
308}
309
310/**
311 * Gets the default device scrypt parameters for key derivation time tuning.
312 * The parameters should lead to about one second derivation time for the
313 * given device.
314 */
315static void get_device_scrypt_params(struct crypt_mnt_ftr *ftr) {
316 const int default_params[] = SCRYPT_DEFAULTS;
317 int params[] = SCRYPT_DEFAULTS;
318 char paramstr[PROPERTY_VALUE_MAX];
319 char *token;
320 char *saveptr;
321 int i;
322
323 property_get(SCRYPT_PROP, paramstr, "");
324 if (paramstr[0] != '\0') {
325 /*
326 * The token we're looking for should be three integers separated by
327 * colons (e.g., "12:8:1"). Scan the property to make sure it matches.
328 */
329 for (i = 0, token = strtok_r(paramstr, ":", &saveptr);
330 token != NULL && i < 3;
331 i++, token = strtok_r(NULL, ":", &saveptr)) {
332 char *endptr;
333 params[i] = strtol(token, &endptr, 10);
334
335 /*
336 * Check that there was a valid number and it's 8-bit. If not,
337 * break out and the end check will take the default values.
338 */
339 if ((*token == '\0') || (*endptr != '\0') || params[i] < 0 || params[i] > 255) {
340 break;
341 }
342 }
343
344 /*
345 * If there were not enough tokens or a token was malformed (not an
346 * integer), it will end up here and the default parameters can be
347 * taken.
348 */
349 if ((i != 3) || (token != NULL)) {
350 printf("bad scrypt parameters '%s' should be like '12:8:1'; using defaults", paramstr);
351 memcpy(params, default_params, sizeof(params));
352 }
353 }
354
355 ftr->N_factor = params[0];
356 ftr->r_factor = params[1];
357 ftr->p_factor = params[2];
358}
359
Ethan Yonker4eca40d2014-11-11 14:52:28 -0600360static unsigned int get_blkdev_size(int fd)
361{
362 unsigned int nr_sec;
363
364 if ( (ioctl(fd, BLKGETSIZE, &nr_sec)) == -1) {
365 nr_sec = 0;
366 }
367
368 return nr_sec;
369}
370
371static int get_crypt_ftr_info(char **metadata_fname, off64_t *off)
372{
373 static int cached_data = 0;
374 static off64_t cached_off = 0;
375 static char cached_metadata_fname[PROPERTY_VALUE_MAX] = "";
376 int fd;
Ethan Yonker4eca40d2014-11-11 14:52:28 -0600377 unsigned int nr_sec;
378 int rc = -1;
379
380 if (!cached_data) {
Ethan Yonker253368a2014-11-25 15:00:52 -0600381 printf("get_crypt_ftr_info crypto key location: '%s'\n", key_fname);
382 if (!strcmp(key_fname, KEY_IN_FOOTER)) {
Ethan Yonker4eca40d2014-11-11 14:52:28 -0600383 if ( (fd = open(real_blkdev, O_RDWR)) < 0) {
384 printf("Cannot open real block device %s\n", real_blkdev);
385 return -1;
386 }
387
388 if ((nr_sec = get_blkdev_size(fd))) {
389 /* If it's an encrypted Android partition, the last 16 Kbytes contain the
390 * encryption info footer and key, and plenty of bytes to spare for future
391 * growth.
392 */
393 strlcpy(cached_metadata_fname, real_blkdev, sizeof(cached_metadata_fname));
394 cached_off = ((off64_t)nr_sec * 512) - CRYPT_FOOTER_OFFSET;
395 cached_data = 1;
396 } else {
397 printf("Cannot get size of block device %s\n", real_blkdev);
398 }
399 close(fd);
400 } else {
Ethan Yonker253368a2014-11-25 15:00:52 -0600401 strlcpy(cached_metadata_fname, key_fname, sizeof(cached_metadata_fname));
Ethan Yonker4eca40d2014-11-11 14:52:28 -0600402 cached_off = 0;
403 cached_data = 1;
404 }
405 }
406
407 if (cached_data) {
408 if (metadata_fname) {
409 *metadata_fname = cached_metadata_fname;
410 }
411 if (off) {
412 *off = cached_off;
413 }
414 rc = 0;
415 }
416
417 return rc;
418}
419
Ethan Yonker4eca40d2014-11-11 14:52:28 -0600420static inline int unix_read(int fd, void* buff, int len)
421{
422 return TEMP_FAILURE_RETRY(read(fd, buff, len));
423}
424
425static inline int unix_write(int fd, const void* buff, int len)
426{
427 return TEMP_FAILURE_RETRY(write(fd, buff, len));
428}
429
430static void init_empty_persist_data(struct crypt_persist_data *pdata, int len)
431{
432 memset(pdata, 0, len);
433 pdata->persist_magic = PERSIST_DATA_MAGIC;
434 pdata->persist_valid_entries = 0;
435}
436
Ethan Yonker4eca40d2014-11-11 14:52:28 -0600437static int get_crypt_ftr_and_key(struct crypt_mnt_ftr *crypt_ftr)
438{
439 int fd;
440 unsigned int nr_sec, cnt;
441 off64_t starting_off;
442 int rc = -1;
443 char *fname = NULL;
444 struct stat statbuf;
445
446 if (get_crypt_ftr_info(&fname, &starting_off)) {
447 printf("Unable to get crypt_ftr_info\n");
448 return -1;
449 }
450 if (fname[0] != '/') {
451 printf("Unexpected value for crypto key location\n");
452 return -1;
453 }
454 if ( (fd = open(fname, O_RDWR)) < 0) {
455 printf("Cannot open footer file %s for get\n", fname);
456 return -1;
457 }
458
459 /* Make sure it's 16 Kbytes in length */
460 fstat(fd, &statbuf);
461 if (S_ISREG(statbuf.st_mode) && (statbuf.st_size != 0x4000)) {
462 printf("footer file %s is not the expected size!\n", fname);
463 goto errout;
464 }
465
466 /* Seek to the start of the crypt footer */
467 if (lseek64(fd, starting_off, SEEK_SET) == -1) {
468 printf("Cannot seek to real block device footer\n");
469 goto errout;
470 }
471
472 if ( (cnt = read(fd, crypt_ftr, sizeof(struct crypt_mnt_ftr))) != sizeof(struct crypt_mnt_ftr)) {
473 printf("Cannot read real block device footer\n");
474 goto errout;
475 }
476
477 if (crypt_ftr->magic != CRYPT_MNT_MAGIC) {
478 printf("Bad magic for real block device %s\n", fname);
479 goto errout;
480 }
481
482 if (crypt_ftr->major_version != CURRENT_MAJOR_VERSION) {
483 printf("Cannot understand major version %d real block device footer; expected %d\n",
484 crypt_ftr->major_version, CURRENT_MAJOR_VERSION);
485 goto errout;
486 }
487
488 if (crypt_ftr->minor_version > CURRENT_MINOR_VERSION) {
489 printf("Warning: crypto footer minor version %d, expected <= %d, continuing...\n",
490 crypt_ftr->minor_version, CURRENT_MINOR_VERSION);
491 }
492
493 /* If this is a verion 1.0 crypt_ftr, make it a 1.1 crypt footer, and update the
494 * copy on disk before returning.
495 */
Ethan Yonker253368a2014-11-25 15:00:52 -0600496 /*if (crypt_ftr->minor_version < CURRENT_MINOR_VERSION) {
Ethan Yonker4eca40d2014-11-11 14:52:28 -0600497 upgrade_crypt_ftr(fd, crypt_ftr, starting_off);
Ethan Yonker253368a2014-11-25 15:00:52 -0600498 }*/
Ethan Yonker4eca40d2014-11-11 14:52:28 -0600499
500 /* Success! */
501 rc = 0;
502
503errout:
504 close(fd);
505 return rc;
506}
507
Ethan Yonker4eca40d2014-11-11 14:52:28 -0600508static int hexdigit (char c)
509{
510 if (c >= '0' && c <= '9') return c - '0';
511 c = tolower(c);
512 if (c >= 'a' && c <= 'f') return c - 'a' + 10;
513 return -1;
514}
515
516static unsigned char* convert_hex_ascii_to_key(const char* master_key_ascii,
517 unsigned int* out_keysize)
518{
519 unsigned int i;
520 *out_keysize = 0;
521
522 size_t size = strlen (master_key_ascii);
523 if (size % 2) {
524 printf("Trying to convert ascii string of odd length");
525 return NULL;
526 }
527
528 unsigned char* master_key = (unsigned char*) malloc(size / 2);
529 if (master_key == 0) {
530 printf("Cannot allocate");
531 return NULL;
532 }
533
534 for (i = 0; i < size; i += 2) {
535 int high_nibble = hexdigit (master_key_ascii[i]);
536 int low_nibble = hexdigit (master_key_ascii[i + 1]);
537
538 if(high_nibble < 0 || low_nibble < 0) {
539 printf("Invalid hex string");
540 free (master_key);
541 return NULL;
542 }
543
544 master_key[*out_keysize] = high_nibble * 16 + low_nibble;
545 (*out_keysize)++;
546 }
547
548 return master_key;
549}
550
551/* Convert a binary key of specified length into an ascii hex string equivalent,
552 * without the leading 0x and with null termination
553 */
554static void convert_key_to_hex_ascii(unsigned char *master_key, unsigned int keysize,
555 char *master_key_ascii)
556{
557 unsigned int i, a;
558 unsigned char nibble;
559
560 for (i=0, a=0; i<keysize; i++, a+=2) {
561 /* For each byte, write out two ascii hex digits */
562 nibble = (master_key[i] >> 4) & 0xf;
563 master_key_ascii[a] = nibble + (nibble > 9 ? 0x37 : 0x30);
564
565 nibble = master_key[i] & 0xf;
566 master_key_ascii[a+1] = nibble + (nibble > 9 ? 0x37 : 0x30);
567 }
568
569 /* Add the null termination */
570 master_key_ascii[a] = '\0';
571
572}
573
574static int load_crypto_mapping_table(struct crypt_mnt_ftr *crypt_ftr, unsigned char *master_key,
575 char *real_blk_name, const char *name, int fd,
576 char *extra_params)
577{
578 char buffer[DM_CRYPT_BUF_SIZE];
579 struct dm_ioctl *io;
580 struct dm_target_spec *tgt;
581 char *crypt_params;
582 char master_key_ascii[129]; /* Large enough to hold 512 bit key and null */
583 int i;
584
585 io = (struct dm_ioctl *) buffer;
586
587 /* Load the mapping table for this device */
588 tgt = (struct dm_target_spec *) &buffer[sizeof(struct dm_ioctl)];
589
590 ioctl_init(io, DM_CRYPT_BUF_SIZE, name, 0);
591 io->target_count = 1;
592 tgt->status = 0;
593 tgt->sector_start = 0;
594 tgt->length = crypt_ftr->fs_size;
595 strcpy(tgt->target_type, "crypt");
596
597 crypt_params = buffer + sizeof(struct dm_ioctl) + sizeof(struct dm_target_spec);
598 convert_key_to_hex_ascii(master_key, crypt_ftr->keysize, master_key_ascii);
599 sprintf(crypt_params, "%s %s 0 %s 0 %s", crypt_ftr->crypto_type_name,
600 master_key_ascii, real_blk_name, extra_params);
601 crypt_params += strlen(crypt_params) + 1;
602 crypt_params = (char *) (((unsigned long)crypt_params + 7) & ~8); /* Align to an 8 byte boundary */
603 tgt->next = crypt_params - buffer;
604
605 for (i = 0; i < TABLE_LOAD_RETRIES; i++) {
606 if (! ioctl(fd, DM_TABLE_LOAD, io)) {
607 break;
608 }
609 usleep(500000);
610 }
611
612 if (i == TABLE_LOAD_RETRIES) {
613 /* We failed to load the table, return an error */
614 return -1;
615 } else {
616 return i + 1;
617 }
618}
619
620
621static int get_dm_crypt_version(int fd, const char *name, int *version)
622{
623 char buffer[DM_CRYPT_BUF_SIZE];
624 struct dm_ioctl *io;
625 struct dm_target_versions *v;
626 int i;
627
628 io = (struct dm_ioctl *) buffer;
629
630 ioctl_init(io, DM_CRYPT_BUF_SIZE, name, 0);
631
632 if (ioctl(fd, DM_LIST_VERSIONS, io)) {
633 return -1;
634 }
635
636 /* Iterate over the returned versions, looking for name of "crypt".
637 * When found, get and return the version.
638 */
639 v = (struct dm_target_versions *) &buffer[sizeof(struct dm_ioctl)];
640 while (v->next) {
641 if (! strcmp(v->name, "crypt")) {
642 /* We found the crypt driver, return the version, and get out */
643 version[0] = v->version[0];
644 version[1] = v->version[1];
645 version[2] = v->version[2];
646 return 0;
647 }
648 v = (struct dm_target_versions *)(((char *)v) + v->next);
649 }
650
651 return -1;
652}
653
654static int create_crypto_blk_dev(struct crypt_mnt_ftr *crypt_ftr, unsigned char *master_key,
655 char *real_blk_name, char *crypto_blk_name, const char *name)
656{
657 char buffer[DM_CRYPT_BUF_SIZE];
658 char master_key_ascii[129]; /* Large enough to hold 512 bit key and null */
659 char *crypt_params;
660 struct dm_ioctl *io;
661 struct dm_target_spec *tgt;
662 unsigned int minor;
663 int fd;
664 int i;
665 int retval = -1;
666 int version[3];
667 char *extra_params;
668 int load_count;
669
670 if ((fd = open("/dev/device-mapper", O_RDWR)) < 0 ) {
671 printf("Cannot open device-mapper\n");
672 goto errout;
673 }
674
675 io = (struct dm_ioctl *) buffer;
676
677 ioctl_init(io, DM_CRYPT_BUF_SIZE, name, 0);
678 if (ioctl(fd, DM_DEV_CREATE, io)) {
679 printf("Cannot create dm-crypt device\n");
680 goto errout;
681 }
682
683 /* Get the device status, in particular, the name of it's device file */
684 ioctl_init(io, DM_CRYPT_BUF_SIZE, name, 0);
685 if (ioctl(fd, DM_DEV_STATUS, io)) {
686 printf("Cannot retrieve dm-crypt device status\n");
687 goto errout;
688 }
689 minor = (io->dev & 0xff) | ((io->dev >> 12) & 0xfff00);
690 snprintf(crypto_blk_name, MAXPATHLEN, "/dev/block/dm-%u", minor);
691
692 extra_params = "";
693 if (! get_dm_crypt_version(fd, name, version)) {
694 /* Support for allow_discards was added in version 1.11.0 */
695 if ((version[0] >= 2) ||
696 ((version[0] == 1) && (version[1] >= 11))) {
697 extra_params = "1 allow_discards";
698 printf("Enabling support for allow_discards in dmcrypt.\n");
699 }
700 }
701
702 load_count = load_crypto_mapping_table(crypt_ftr, master_key, real_blk_name, name,
703 fd, extra_params);
704 if (load_count < 0) {
705 printf("Cannot load dm-crypt mapping table.\n");
706 goto errout;
707 } else if (load_count > 1) {
708 printf("Took %d tries to load dmcrypt table.\n", load_count);
709 }
710
711 /* Resume this device to activate it */
712 ioctl_init(io, DM_CRYPT_BUF_SIZE, name, 0);
713
714 if (ioctl(fd, DM_DEV_SUSPEND, io)) {
715 printf("Cannot resume the dm-crypt device\n");
716 goto errout;
717 }
718
719 /* We made it here with no errors. Woot! */
720 retval = 0;
721
722errout:
723 close(fd); /* If fd is <0 from a failed open call, it's safe to just ignore the close error */
724
725 return retval;
726}
727
Ethan Yonkerd79d9bc2014-12-20 15:38:29 -0600728int delete_crypto_blk_dev(char *name)
Ethan Yonker4eca40d2014-11-11 14:52:28 -0600729{
730 int fd;
731 char buffer[DM_CRYPT_BUF_SIZE];
732 struct dm_ioctl *io;
733 int retval = -1;
734
735 if ((fd = open("/dev/device-mapper", O_RDWR)) < 0 ) {
736 printf("Cannot open device-mapper\n");
737 goto errout;
738 }
739
740 io = (struct dm_ioctl *) buffer;
741
742 ioctl_init(io, DM_CRYPT_BUF_SIZE, name, 0);
743 if (ioctl(fd, DM_DEV_REMOVE, io)) {
744 printf("Cannot remove dm-crypt device\n");
745 goto errout;
746 }
747
748 /* We made it here with no errors. Woot! */
749 retval = 0;
750
751errout:
752 close(fd); /* If fd is <0 from a failed open call, it's safe to just ignore the close error */
753
754 return retval;
755
756}
757
758static int pbkdf2(const char *passwd, const unsigned char *salt,
759 unsigned char *ikey, void *params UNUSED)
760{
761 printf("Using pbkdf2 for cryptfs KDF");
762
763 /* Turn the password into a key and IV that can decrypt the master key */
764 unsigned int keysize;
765 char* master_key = (char*)convert_hex_ascii_to_key(passwd, &keysize);
766 if (!master_key) return -1;
767 PKCS5_PBKDF2_HMAC_SHA1(master_key, keysize, salt, SALT_LEN,
768 HASH_COUNT, KEY_LEN_BYTES+IV_LEN_BYTES, ikey);
769
770 memset(master_key, 0, keysize);
771 free (master_key);
772 return 0;
773}
774
775static int scrypt(const char *passwd, const unsigned char *salt,
776 unsigned char *ikey, void *params)
777{
778 printf("Using scrypt for cryptfs KDF\n");
779
780 struct crypt_mnt_ftr *ftr = (struct crypt_mnt_ftr *) params;
781
782 int N = 1 << ftr->N_factor;
783 int r = 1 << ftr->r_factor;
784 int p = 1 << ftr->p_factor;
785
786 /* Turn the password into a key and IV that can decrypt the master key */
787 unsigned int keysize;
788 unsigned char* master_key = convert_hex_ascii_to_key(passwd, &keysize);
789 if (!master_key) return -1;
790 crypto_scrypt(master_key, keysize, salt, SALT_LEN, N, r, p, ikey,
791 KEY_LEN_BYTES + IV_LEN_BYTES);
792
793 memset(master_key, 0, keysize);
794 free (master_key);
795 return 0;
796}
797
798static int scrypt_keymaster(const char *passwd, const unsigned char *salt,
799 unsigned char *ikey, void *params)
800{
801 printf("Using scrypt with keymaster for cryptfs KDF\n");
802
803 int rc;
804 unsigned int key_size;
805 size_t signature_size;
806 unsigned char* signature;
807 struct crypt_mnt_ftr *ftr = (struct crypt_mnt_ftr *) params;
808
809 int N = 1 << ftr->N_factor;
810 int r = 1 << ftr->r_factor;
811 int p = 1 << ftr->p_factor;
812
813 unsigned char* master_key = convert_hex_ascii_to_key(passwd, &key_size);
814 if (!master_key) {
Ethan Yonkercceebb82014-11-18 10:17:59 -0600815 printf("Failed to convert passwd from hex\n");
Ethan Yonker4eca40d2014-11-11 14:52:28 -0600816 return -1;
817 }
818
819 rc = crypto_scrypt(master_key, key_size, salt, SALT_LEN,
820 N, r, p, ikey, KEY_LEN_BYTES + IV_LEN_BYTES);
821 memset(master_key, 0, key_size);
822 free(master_key);
823
824 if (rc) {
Ethan Yonkercceebb82014-11-18 10:17:59 -0600825 printf("scrypt failed\n");
Ethan Yonker4eca40d2014-11-11 14:52:28 -0600826 return -1;
827 }
828
829 if (keymaster_sign_object(ftr, ikey, KEY_LEN_BYTES + IV_LEN_BYTES,
830 &signature, &signature_size)) {
Ethan Yonkercceebb82014-11-18 10:17:59 -0600831 printf("Signing failed\n");
Ethan Yonker4eca40d2014-11-11 14:52:28 -0600832 return -1;
833 }
834
835 rc = crypto_scrypt(signature, signature_size, salt, SALT_LEN,
836 N, r, p, ikey, KEY_LEN_BYTES + IV_LEN_BYTES);
837 free(signature);
838
839 if (rc) {
Ethan Yonkercceebb82014-11-18 10:17:59 -0600840 printf("scrypt failed\n");
Ethan Yonker4eca40d2014-11-11 14:52:28 -0600841 return -1;
842 }
843
844 return 0;
845}
846
847static int encrypt_master_key(const char *passwd, const unsigned char *salt,
848 const unsigned char *decrypted_master_key,
849 unsigned char *encrypted_master_key,
850 struct crypt_mnt_ftr *crypt_ftr)
851{
852 unsigned char ikey[32+32] = { 0 }; /* Big enough to hold a 256 bit key and 256 bit IV */
853 EVP_CIPHER_CTX e_ctx;
854 int encrypted_len, final_len;
855 int rc = 0;
856
857 /* Turn the password into an intermediate key and IV that can decrypt the master key */
858 get_device_scrypt_params(crypt_ftr);
859
860 switch (crypt_ftr->kdf_type) {
861 case KDF_SCRYPT_KEYMASTER_UNPADDED:
862 case KDF_SCRYPT_KEYMASTER_BADLY_PADDED:
863 case KDF_SCRYPT_KEYMASTER:
864 if (keymaster_create_key(crypt_ftr)) {
865 printf("keymaster_create_key failed");
866 return -1;
867 }
868
869 if (scrypt_keymaster(passwd, salt, ikey, crypt_ftr)) {
870 printf("scrypt failed");
871 return -1;
872 }
873 break;
874
875 case KDF_SCRYPT:
876 if (scrypt(passwd, salt, ikey, crypt_ftr)) {
877 printf("scrypt failed");
878 return -1;
879 }
880 break;
881
882 default:
883 printf("Invalid kdf_type");
884 return -1;
885 }
886
887 /* Initialize the decryption engine */
888 if (! EVP_EncryptInit(&e_ctx, EVP_aes_128_cbc(), ikey, ikey+KEY_LEN_BYTES)) {
889 printf("EVP_EncryptInit failed\n");
890 return -1;
891 }
892 EVP_CIPHER_CTX_set_padding(&e_ctx, 0); /* Turn off padding as our data is block aligned */
893
894 /* Encrypt the master key */
895 if (! EVP_EncryptUpdate(&e_ctx, encrypted_master_key, &encrypted_len,
896 decrypted_master_key, KEY_LEN_BYTES)) {
897 printf("EVP_EncryptUpdate failed\n");
898 return -1;
899 }
900 if (! EVP_EncryptFinal(&e_ctx, encrypted_master_key + encrypted_len, &final_len)) {
901 printf("EVP_EncryptFinal failed\n");
902 return -1;
903 }
904
905 if (encrypted_len + final_len != KEY_LEN_BYTES) {
906 printf("EVP_Encryption length check failed with %d, %d bytes\n", encrypted_len, final_len);
907 return -1;
908 }
909
910 /* Store the scrypt of the intermediate key, so we can validate if it's a
911 password error or mount error when things go wrong.
912 Note there's no need to check for errors, since if this is incorrect, we
913 simply won't wipe userdata, which is the correct default behavior
914 */
915 int N = 1 << crypt_ftr->N_factor;
916 int r = 1 << crypt_ftr->r_factor;
917 int p = 1 << crypt_ftr->p_factor;
918
919 rc = crypto_scrypt(ikey, KEY_LEN_BYTES,
920 crypt_ftr->salt, sizeof(crypt_ftr->salt), N, r, p,
921 crypt_ftr->scrypted_intermediate_key,
922 sizeof(crypt_ftr->scrypted_intermediate_key));
923
924 if (rc) {
925 printf("encrypt_master_key: crypto_scrypt failed");
926 }
927
928 return 0;
929}
930
931static int decrypt_master_key_aux(char *passwd, unsigned char *salt,
932 unsigned char *encrypted_master_key,
933 unsigned char *decrypted_master_key,
934 kdf_func kdf, void *kdf_params,
935 unsigned char** intermediate_key,
936 size_t* intermediate_key_size)
937{
938 unsigned char ikey[32+32] = { 0 }; /* Big enough to hold a 256 bit key and 256 bit IV */
939 EVP_CIPHER_CTX d_ctx;
940 int decrypted_len, final_len;
941
942 /* Turn the password into an intermediate key and IV that can decrypt the
943 master key */
944 if (kdf(passwd, salt, ikey, kdf_params)) {
945 printf("kdf failed");
946 return -1;
947 }
948
949 /* Initialize the decryption engine */
950 if (! EVP_DecryptInit(&d_ctx, EVP_aes_128_cbc(), ikey, ikey+KEY_LEN_BYTES)) {
951 return -1;
952 }
953 EVP_CIPHER_CTX_set_padding(&d_ctx, 0); /* Turn off padding as our data is block aligned */
954 /* Decrypt the master key */
955 if (! EVP_DecryptUpdate(&d_ctx, decrypted_master_key, &decrypted_len,
956 encrypted_master_key, KEY_LEN_BYTES)) {
957 return -1;
958 }
959 if (! EVP_DecryptFinal(&d_ctx, decrypted_master_key + decrypted_len, &final_len)) {
960 return -1;
961 }
962
963 if (decrypted_len + final_len != KEY_LEN_BYTES) {
964 return -1;
965 }
966
967 /* Copy intermediate key if needed by params */
968 if (intermediate_key && intermediate_key_size) {
969 *intermediate_key = (unsigned char*) malloc(KEY_LEN_BYTES);
970 if (intermediate_key) {
971 memcpy(*intermediate_key, ikey, KEY_LEN_BYTES);
972 *intermediate_key_size = KEY_LEN_BYTES;
973 }
974 }
975
976 return 0;
977}
978
979static void get_kdf_func(struct crypt_mnt_ftr *ftr, kdf_func *kdf, void** kdf_params)
980{
981 if (ftr->kdf_type == KDF_SCRYPT_KEYMASTER_UNPADDED ||
982 ftr->kdf_type == KDF_SCRYPT_KEYMASTER_BADLY_PADDED ||
983 ftr->kdf_type == KDF_SCRYPT_KEYMASTER) {
984 *kdf = scrypt_keymaster;
985 *kdf_params = ftr;
986 } else if (ftr->kdf_type == KDF_SCRYPT) {
987 *kdf = scrypt;
988 *kdf_params = ftr;
989 } else {
990 *kdf = pbkdf2;
991 *kdf_params = NULL;
992 }
993}
994
995static int decrypt_master_key(char *passwd, unsigned char *decrypted_master_key,
996 struct crypt_mnt_ftr *crypt_ftr,
997 unsigned char** intermediate_key,
998 size_t* intermediate_key_size)
999{
1000 kdf_func kdf;
1001 void *kdf_params;
1002 int ret;
1003
1004 get_kdf_func(crypt_ftr, &kdf, &kdf_params);
1005 ret = decrypt_master_key_aux(passwd, crypt_ftr->salt, crypt_ftr->master_key,
1006 decrypted_master_key, kdf, kdf_params,
1007 intermediate_key, intermediate_key_size);
1008 if (ret != 0) {
1009 printf("failure decrypting master key");
1010 }
1011
1012 return ret;
1013}
1014
Ethan Yonker4eca40d2014-11-11 14:52:28 -06001015static int test_mount_encrypted_fs(struct crypt_mnt_ftr* crypt_ftr,
1016 char *passwd, char *mount_point, char *label)
1017{
1018 /* Allocate enough space for a 256 bit key, but we may use less */
1019 unsigned char decrypted_master_key[32];
1020 char crypto_blkdev[MAXPATHLEN];
Ethan Yonker4eca40d2014-11-11 14:52:28 -06001021 char tmp_mount_point[64];
1022 unsigned int orig_failed_decrypt_count;
1023 int rc;
1024 kdf_func kdf;
1025 void *kdf_params;
1026 int use_keymaster = 0;
1027 int upgrade = 0;
1028 unsigned char* intermediate_key = 0;
1029 size_t intermediate_key_size = 0;
1030
1031 printf("crypt_ftr->fs_size = %lld\n", crypt_ftr->fs_size);
1032 orig_failed_decrypt_count = crypt_ftr->failed_decrypt_count;
1033
1034 if (! (crypt_ftr->flags & CRYPT_MNT_KEY_UNENCRYPTED) ) {
1035 if (decrypt_master_key(passwd, decrypted_master_key, crypt_ftr,
1036 &intermediate_key, &intermediate_key_size)) {
1037 printf("Failed to decrypt master key\n");
1038 rc = -1;
1039 goto errout;
1040 }
1041 }
1042
Ethan Yonker4eca40d2014-11-11 14:52:28 -06001043 // Create crypto block device - all (non fatal) code paths
1044 // need it
1045 if (create_crypto_blk_dev(crypt_ftr, decrypted_master_key,
1046 real_blkdev, crypto_blkdev, label)) {
1047 printf("Error creating decrypted block device\n");
1048 rc = -1;
1049 goto errout;
1050 }
1051
1052 /* Work out if the problem is the password or the data */
1053 unsigned char scrypted_intermediate_key[sizeof(crypt_ftr->
1054 scrypted_intermediate_key)];
1055 int N = 1 << crypt_ftr->N_factor;
1056 int r = 1 << crypt_ftr->r_factor;
1057 int p = 1 << crypt_ftr->p_factor;
1058
1059 rc = crypto_scrypt(intermediate_key, intermediate_key_size,
1060 crypt_ftr->salt, sizeof(crypt_ftr->salt),
1061 N, r, p, scrypted_intermediate_key,
1062 sizeof(scrypted_intermediate_key));
1063
1064 // Does the key match the crypto footer?
1065 if (rc == 0 && memcmp(scrypted_intermediate_key,
1066 crypt_ftr->scrypted_intermediate_key,
1067 sizeof(scrypted_intermediate_key)) == 0) {
1068 printf("Password matches\n");
1069 rc = 0;
1070 } else {
1071 /* Try mounting the file system anyway, just in case the problem's with
1072 * the footer, not the key. */
1073 sprintf(tmp_mount_point, "%s/tmp_mnt", mount_point);
1074 mkdir(tmp_mount_point, 0755);
Ethan Yonker253368a2014-11-25 15:00:52 -06001075 if (mount(crypto_blkdev, tmp_mount_point, file_system, NULL, NULL) != 0) {
Ethan Yonker4eca40d2014-11-11 14:52:28 -06001076 printf("Error temp mounting decrypted block device '%s'\n", crypto_blkdev);
1077 delete_crypto_blk_dev(label);
1078
1079 rc = ++crypt_ftr->failed_decrypt_count;
1080 //put_crypt_ftr_and_key(crypt_ftr); // Do not penalize for attempting to decrypt in recovery
1081 } else {
1082 /* Success! */
1083 printf("Password did not match but decrypted drive mounted - continue\n");
1084 umount(tmp_mount_point);
1085 rc = 0;
1086 }
1087 }
1088
1089 if (rc == 0) {
1090 /*crypt_ftr->failed_decrypt_count = 0;
1091 if (orig_failed_decrypt_count != 0) {
1092 put_crypt_ftr_and_key(crypt_ftr);
1093 }*/
1094
1095 /* Save the name of the crypto block device
1096 * so we can mount it when restarting the framework. */
1097 property_set("ro.crypto.fs_crypto_blkdev", crypto_blkdev);
1098
1099 /* Also save a the master key so we can reencrypted the key
1100 * the key when we want to change the password on it. */
1101 /*memcpy(saved_master_key, decrypted_master_key, KEY_LEN_BYTES);
1102 saved_mount_point = strdup(mount_point);
1103 master_key_saved = 1;
1104 printf("%s(): Master key saved\n", __FUNCTION__);*/
1105 rc = 0;
1106
1107 // Upgrade if we're not using the latest KDF.
1108 /*use_keymaster = keymaster_check_compatibility();
1109 if (crypt_ftr->kdf_type == KDF_SCRYPT_KEYMASTER) {
1110 // Don't allow downgrade
1111 } else if (use_keymaster == 1 && crypt_ftr->kdf_type != KDF_SCRYPT_KEYMASTER) {
1112 crypt_ftr->kdf_type = KDF_SCRYPT_KEYMASTER;
1113 upgrade = 1;
1114 } else if (use_keymaster == 0 && crypt_ftr->kdf_type != KDF_SCRYPT) {
1115 crypt_ftr->kdf_type = KDF_SCRYPT;
1116 upgrade = 1;
1117 }
1118
1119 if (upgrade) {
1120 rc = encrypt_master_key(passwd, crypt_ftr->salt, saved_master_key,
1121 crypt_ftr->master_key, crypt_ftr);
1122 if (!rc) {
1123 rc = put_crypt_ftr_and_key(crypt_ftr);
1124 }
1125 printf("Key Derivation Function upgrade: rc=%d\n", rc);
1126
1127 // Do not fail even if upgrade failed - machine is bootable
1128 // Note that if this code is ever hit, there is a *serious* problem
1129 // since KDFs should never fail. You *must* fix the kdf before
1130 // proceeding!
1131 if (rc) {
1132 printf("Upgrade failed with error %d,"
1133 " but continuing with previous state\n",
1134 rc);
1135 rc = 0;
1136 }
1137 }*/
1138 }
1139
1140 errout:
1141 if (intermediate_key) {
1142 memset(intermediate_key, 0, intermediate_key_size);
1143 free(intermediate_key);
1144 }
1145 return rc;
1146}
1147
1148/* Called by vold when it wants to undo the crypto mapping of a volume it
1149 * manages. This is usually in response to a factory reset, when we want
1150 * to undo the crypto mapping so the volume is formatted in the clear.
1151 */
1152int cryptfs_revert_volume(const char *label)
1153{
1154 return delete_crypto_blk_dev((char *)label);
1155}
1156
Ethan Yonker4eca40d2014-11-11 14:52:28 -06001157int check_unmounted_and_get_ftr(struct crypt_mnt_ftr* crypt_ftr)
1158{
1159 char encrypted_state[PROPERTY_VALUE_MAX];
1160 property_get("ro.crypto.state", encrypted_state, "");
1161 if ( master_key_saved || strcmp(encrypted_state, "encrypted") ) {
1162 printf("encrypted fs already validated or not running with encryption,"
Ethan Yonkercceebb82014-11-18 10:17:59 -06001163 " aborting\n");
1164 //return -1;
Ethan Yonker4eca40d2014-11-11 14:52:28 -06001165 }
1166
1167 if (get_crypt_ftr_and_key(crypt_ftr)) {
Ethan Yonkercceebb82014-11-18 10:17:59 -06001168 printf("Error getting crypt footer and key\n");
Ethan Yonker4eca40d2014-11-11 14:52:28 -06001169 return -1;
1170 }
1171
1172 return 0;
1173}
1174
1175/*
1176 * TODO - transition patterns to new format in calling code
1177 * and remove this vile hack, and the use of hex in
1178 * the password passing code.
1179 *
1180 * Patterns are passed in zero based (i.e. the top left dot
1181 * is represented by zero, the top middle one etc), but we want
1182 * to store them '1' based.
1183 * This is to allow us to migrate the calling code to use this
1184 * convention. It also solves a nasty problem whereby scrypt ignores
1185 * trailing zeros, so patterns ending at the top left could be
1186 * truncated, and similarly, you could add the top left to any
1187 * pattern and still match.
1188 * adjust_passwd is a hack function that returns the alternate representation
1189 * if the password appears to be a pattern (hex numbers all less than 09)
1190 * If it succeeds we need to try both, and in particular try the alternate
1191 * first. If the original matches, then we need to update the footer
1192 * with the alternate.
1193 * All code that accepts passwords must adjust them first. Since
1194 * cryptfs_check_passwd is always the first function called after a migration
1195 * (and indeed on any boot) we only need to do the double try in this
1196 * function.
1197 */
1198char* adjust_passwd(const char* passwd)
1199{
1200 size_t index, length;
1201
1202 if (!passwd) {
1203 return 0;
1204 }
1205
1206 // Check even length. Hex encoded passwords are always
1207 // an even length, since each character encodes to two characters.
1208 length = strlen(passwd);
1209 if (length % 2) {
1210 printf("Password not correctly hex encoded.");
1211 return 0;
1212 }
1213
1214 // Check password is old-style pattern - a collection of hex
1215 // encoded bytes less than 9 (00 through 08)
1216 for (index = 0; index < length; index +=2) {
1217 if (passwd[index] != '0'
1218 || passwd[index + 1] < '0' || passwd[index + 1] > '8') {
1219 return 0;
1220 }
1221 }
1222
1223 // Allocate room for adjusted passwd and null terminate
1224 char* adjusted = malloc(length + 1);
1225 adjusted[length] = 0;
1226
1227 // Add 0x31 ('1') to each character
1228 for (index = 0; index < length; index += 2) {
1229 // output is 31 through 39 so set first byte to three, second to src + 1
1230 adjusted[index] = '3';
1231 adjusted[index + 1] = passwd[index + 1] + 1;
1232 }
1233
1234 return adjusted;
1235}
1236
1237/*
1238 * Passwords in L get passed from Android to cryptfs in hex, so a '1'
1239 * gets converted to '31' where 31 is 0x31 which is the ascii character
1240 * code in hex of the character '1'. This function will convert the
1241 * regular character codes to their hexadecimal representation to make
1242 * decrypt work properly with Android 5.0 lollipop decryption.
1243 */
1244char* hexadj_passwd(const char* passwd)
1245{
1246 size_t index, length;
1247 char* ptr = passwd;
1248
1249 if (!passwd) {
1250 return 0;
1251 }
1252
1253 length = strlen(passwd);
1254
1255 // Allocate room for hex passwd and null terminate
1256 char* hex = malloc((length * 2) + 1);
1257 hex[length * 2] = 0;
1258
1259 // Convert to hex
1260 for (index = 0; index < length; index++) {
1261 sprintf(hex + (index * 2), "%02X", *ptr);
1262 ptr++;
1263 }
1264
1265 return hex;
1266}
1267
Ethan Yonker253368a2014-11-25 15:00:52 -06001268int cryptfs_check_footer()
Ethan Yonker4eca40d2014-11-11 14:52:28 -06001269{
1270 int rc = -1;
Ethan Yonker4eca40d2014-11-11 14:52:28 -06001271 struct crypt_mnt_ftr crypt_ftr;
1272
Ethan Yonker4eca40d2014-11-11 14:52:28 -06001273 rc = get_crypt_ftr_and_key(&crypt_ftr);
1274
1275 return rc;
1276}
1277
1278int cryptfs_check_passwd(char *passwd)
1279{
1280 struct crypt_mnt_ftr crypt_ftr;
1281 int rc;
Ethan Yonker4eca40d2014-11-11 14:52:28 -06001282
1283 rc = check_unmounted_and_get_ftr(&crypt_ftr);
1284 if (rc)
1285 return rc;
1286
1287 char* adjusted_passwd = adjust_passwd(passwd);
1288 char* hex_passwd = hexadj_passwd(passwd);
1289
1290 if (adjusted_passwd) {
1291 int failed_decrypt_count = crypt_ftr.failed_decrypt_count;
1292 rc = test_mount_encrypted_fs(&crypt_ftr, adjusted_passwd,
1293 DATA_MNT_POINT, "userdata");
1294
1295 // Maybe the original one still works?
1296 if (rc) {
1297 // Don't double count this failure
1298 crypt_ftr.failed_decrypt_count = failed_decrypt_count;
1299 rc = test_mount_encrypted_fs(&crypt_ftr, passwd,
1300 DATA_MNT_POINT, "userdata");
1301 if (!rc) {
1302 // cryptfs_changepw also adjusts so pass original
1303 // Note that adjust_passwd only recognises patterns
1304 // so we can safely use CRYPT_TYPE_PATTERN
1305 printf("TWRP NOT Updating pattern to new format");
1306 //cryptfs_changepw(CRYPT_TYPE_PATTERN, passwd);
1307 } else if (hex_passwd) {
1308 rc = test_mount_encrypted_fs(&crypt_ftr, hex_passwd,
1309 DATA_MNT_POINT, "userdata");
1310 }
1311 }
1312 free(adjusted_passwd);
1313 } else {
1314 rc = test_mount_encrypted_fs(&crypt_ftr, passwd,
1315 DATA_MNT_POINT, "userdata");
1316 if (rc && hex_passwd) {
1317 rc = test_mount_encrypted_fs(&crypt_ftr, hex_passwd,
1318 DATA_MNT_POINT, "userdata");
1319 }
1320 }
1321
1322 if (hex_passwd)
1323 free(hex_passwd);
1324
1325 /*if (rc == 0 && crypt_ftr.crypt_type != CRYPT_TYPE_DEFAULT) {
1326 printf("cryptfs_check_passwd update expiry time?\n");
1327 cryptfs_clear_password();
1328 password = strdup(passwd);
1329 struct timespec now;
1330 clock_gettime(CLOCK_BOOTTIME, &now);
1331 password_expiry_time = now.tv_sec + password_max_age_seconds;
1332 }*/
1333
1334 return rc;
1335}
1336
1337int cryptfs_verify_passwd(char *passwd)
1338{
1339 struct crypt_mnt_ftr crypt_ftr;
1340 /* Allocate enough space for a 256 bit key, but we may use less */
1341 unsigned char decrypted_master_key[32];
1342 char encrypted_state[PROPERTY_VALUE_MAX];
1343 int rc;
1344
1345 property_get("ro.crypto.state", encrypted_state, "");
1346 if (strcmp(encrypted_state, "encrypted") ) {
1347 printf("device not encrypted, aborting");
1348 return -2;
1349 }
1350
1351 if (!master_key_saved) {
1352 printf("encrypted fs not yet mounted, aborting");
1353 return -1;
1354 }
1355
1356 if (!saved_mount_point) {
1357 printf("encrypted fs failed to save mount point, aborting");
1358 return -1;
1359 }
1360
1361 if (get_crypt_ftr_and_key(&crypt_ftr)) {
1362 printf("Error getting crypt footer and key\n");
1363 return -1;
1364 }
1365
1366 if (crypt_ftr.flags & CRYPT_MNT_KEY_UNENCRYPTED) {
1367 /* If the device has no password, then just say the password is valid */
1368 rc = 0;
1369 } else {
1370 char* adjusted_passwd = adjust_passwd(passwd);
1371 if (adjusted_passwd) {
1372 passwd = adjusted_passwd;
1373 }
1374
1375 decrypt_master_key(passwd, decrypted_master_key, &crypt_ftr, 0, 0);
1376 if (!memcmp(decrypted_master_key, saved_master_key, crypt_ftr.keysize)) {
1377 /* They match, the password is correct */
1378 rc = 0;
1379 } else {
1380 /* If incorrect, sleep for a bit to prevent dictionary attacks */
1381 sleep(1);
1382 rc = 1;
1383 }
1384
1385 free(adjusted_passwd);
1386 }
1387
1388 return rc;
1389}
1390
1391/* Initialize a crypt_mnt_ftr structure. The keysize is
1392 * defaulted to 16 bytes, and the filesystem size to 0.
1393 * Presumably, at a minimum, the caller will update the
1394 * filesystem size and crypto_type_name after calling this function.
1395 */
1396static int cryptfs_init_crypt_mnt_ftr(struct crypt_mnt_ftr *ftr)
1397{
1398 off64_t off;
1399
1400 memset(ftr, 0, sizeof(struct crypt_mnt_ftr));
1401 ftr->magic = CRYPT_MNT_MAGIC;
1402 ftr->major_version = CURRENT_MAJOR_VERSION;
1403 ftr->minor_version = CURRENT_MINOR_VERSION;
1404 ftr->ftr_size = sizeof(struct crypt_mnt_ftr);
1405 ftr->keysize = KEY_LEN_BYTES;
1406
1407 switch (keymaster_check_compatibility()) {
1408 case 1:
1409 ftr->kdf_type = KDF_SCRYPT_KEYMASTER;
1410 break;
1411
1412 case 0:
1413 ftr->kdf_type = KDF_SCRYPT;
1414 break;
1415
1416 default:
1417 printf("keymaster_check_compatibility failed");
1418 return -1;
1419 }
1420
1421 get_device_scrypt_params(ftr);
1422
1423 ftr->persist_data_size = CRYPT_PERSIST_DATA_SIZE;
1424 if (get_crypt_ftr_info(NULL, &off) == 0) {
1425 ftr->persist_data_offset[0] = off + CRYPT_FOOTER_TO_PERSIST_OFFSET;
1426 ftr->persist_data_offset[1] = off + CRYPT_FOOTER_TO_PERSIST_OFFSET +
1427 ftr->persist_data_size;
1428 }
1429
1430 return 0;
1431}
1432
Ethan Yonker4eca40d2014-11-11 14:52:28 -06001433/* Returns type of the password, default, pattern, pin or password.
1434 */
1435int cryptfs_get_password_type(void)
1436{
1437 struct crypt_mnt_ftr crypt_ftr;
Ethan Yonker4eca40d2014-11-11 14:52:28 -06001438
1439 if (get_crypt_ftr_and_key(&crypt_ftr)) {
1440 printf("Error getting crypt footer and key\n");
1441 return -1;
1442 }
1443
1444 if (crypt_ftr.flags & CRYPT_INCONSISTENT_STATE) {
1445 return -1;
1446 }
1447
1448 return crypt_ftr.crypt_type;
1449}