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