blob: 0c7848d8f4b97cb4dae99d0bf1ee457909298356 [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 Yonkerc798c9c2015-10-09 11:15:26 -050046
47#ifndef TW_CRYPTO_HAVE_KEYMASTERX
Ethan Yonker4eca40d2014-11-11 14:52:28 -060048#include <hardware/keymaster.h>
Ethan Yonkerc798c9c2015-10-09 11:15:26 -050049#else
50#include <stdbool.h>
51#include <openssl/evp.h>
52#include <openssl/sha.h>
53#include <hardware/keymaster0.h>
54#include <hardware/keymaster1.h>
55#endif
Ethan Yonker4eca40d2014-11-11 14:52:28 -060056
Ethan Yonker253368a2014-11-25 15:00:52 -060057#ifndef min /* already defined by windows.h */
58#define min(a, b) ((a) < (b) ? (a) : (b))
59#endif
60
Ethan Yonker4eca40d2014-11-11 14:52:28 -060061#define UNUSED __attribute__((unused))
62
63#define UNUSED __attribute__((unused))
64
Dees Troyc657cc02015-01-16 22:48:47 +000065#ifdef CONFIG_HW_DISK_ENCRYPTION
66#include "cryptfs_hw.h"
67#endif
68
Ethan Yonker4eca40d2014-11-11 14:52:28 -060069#define DM_CRYPT_BUF_SIZE 4096
70
71#define HASH_COUNT 2000
72#define KEY_LEN_BYTES 16
73#define IV_LEN_BYTES 16
74
75#define KEY_IN_FOOTER "footer"
76
Ethan Yonker4eca40d2014-11-11 14:52:28 -060077#define EXT4_FS 1
78#define F2FS_FS 2
79
80#define TABLE_LOAD_RETRIES 10
81
82#define RSA_KEY_SIZE 2048
83#define RSA_KEY_SIZE_BYTES (RSA_KEY_SIZE / 8)
84#define RSA_EXPONENT 0x10001
Ethan Yonkerc798c9c2015-10-09 11:15:26 -050085#define KEYMASTER_CRYPTFS_RATE_LIMIT 1 // Maximum one try per second
Ethan Yonker4eca40d2014-11-11 14:52:28 -060086
87#define RETRY_MOUNT_ATTEMPTS 10
88#define RETRY_MOUNT_DELAY_SECONDS 1
89
90char *me = "cryptfs";
91
92static unsigned char saved_master_key[KEY_LEN_BYTES];
93static char *saved_mount_point;
94static int master_key_saved = 0;
95static struct crypt_persist_data *persist_data = NULL;
Ethan Yonker253368a2014-11-25 15:00:52 -060096static char key_fname[PROPERTY_VALUE_MAX] = "";
97static char real_blkdev[PROPERTY_VALUE_MAX] = "";
98static char file_system[PROPERTY_VALUE_MAX] = "";
99
Ethan Yonkerba95ad12016-01-18 15:18:15 -0600100#ifdef CONFIG_HW_DISK_ENCRYPTION
Ethan Yonkerba95ad12016-01-18 15:18:15 -0600101static int scrypt_keymaster(const char *passwd, const unsigned char *salt,
102 unsigned char *ikey, void *params);
103static void convert_key_to_hex_ascii(const unsigned char *master_key,
104 unsigned int keysize, char *master_key_ascii);
Ethan Yonkerba95ad12016-01-18 15:18:15 -0600105static int get_keymaster_hw_fde_passwd(const char* passwd, unsigned char* newpw,
106 unsigned char* salt,
107 const struct crypt_mnt_ftr *ftr)
108{
109 /* if newpw updated, return 0
110 * if newpw not updated return -1
111 */
112 int rc = -1;
113
114 if (should_use_keymaster()) {
115 if (scrypt_keymaster(passwd, salt, newpw, (void*)ftr)) {
116 printf("scrypt failed");
117 } else {
118 rc = 0;
119 }
120 }
121
122 return rc;
123}
124
125static int verify_hw_fde_passwd(char *passwd, struct crypt_mnt_ftr* crypt_ftr)
126{
127 unsigned char newpw[32] = {0};
128 int key_index;
129 if (get_keymaster_hw_fde_passwd(passwd, newpw, crypt_ftr->salt, crypt_ftr))
130 key_index = set_hw_device_encryption_key(passwd,
131 (char*) crypt_ftr->crypto_type_name);
132 else
133 key_index = set_hw_device_encryption_key((const char*)newpw,
134 (char*) crypt_ftr->crypto_type_name);
135 return key_index;
136}
Ethan Yonkerba95ad12016-01-18 15:18:15 -0600137#endif
138
Ethan Yonker253368a2014-11-25 15:00:52 -0600139void set_partition_data(const char* block_device, const char* key_location, const char* fs)
140{
141 strcpy(key_fname, key_location);
142 strcpy(real_blkdev, block_device);
143 strcpy(file_system, fs);
144}
Ethan Yonker4eca40d2014-11-11 14:52:28 -0600145
Ethan Yonkerc798c9c2015-10-09 11:15:26 -0500146#ifndef TW_CRYPTO_HAVE_KEYMASTERX
Ethan Yonker4eca40d2014-11-11 14:52:28 -0600147static int keymaster_init(keymaster_device_t **keymaster_dev)
148{
149 int rc;
150
151 const hw_module_t* mod;
152 rc = hw_get_module_by_class(KEYSTORE_HARDWARE_MODULE_ID, NULL, &mod);
153 if (rc) {
154 printf("could not find any keystore module\n");
155 goto out;
156 }
157
158 rc = keymaster_open(mod, keymaster_dev);
159 if (rc) {
160 printf("could not open keymaster device in %s (%s)\n",
161 KEYSTORE_HARDWARE_MODULE_ID, strerror(-rc));
162 goto out;
163 }
164
165 return 0;
166
167out:
168 *keymaster_dev = NULL;
169 return rc;
170}
171
172/* Should we use keymaster? */
173static int keymaster_check_compatibility()
174{
175 keymaster_device_t *keymaster_dev = 0;
176 int rc = 0;
177
178 if (keymaster_init(&keymaster_dev)) {
179 printf("Failed to init keymaster\n");
180 rc = -1;
181 goto out;
182 }
183
184 printf("keymaster version is %d\n", keymaster_dev->common.module->module_api_version);
185
thatceb7b8e2014-12-09 23:15:16 +0100186#if (KEYMASTER_HEADER_VERSION >= 3)
Ethan Yonker4eca40d2014-11-11 14:52:28 -0600187 if (keymaster_dev->common.module->module_api_version
188 < KEYMASTER_MODULE_API_VERSION_0_3) {
189 rc = 0;
190 goto out;
191 }
192
193 if (keymaster_dev->flags & KEYMASTER_BLOBS_ARE_STANDALONE) {
194 rc = 1;
195 }
196
thatceb7b8e2014-12-09 23:15:16 +0100197#endif
Ethan Yonker4eca40d2014-11-11 14:52:28 -0600198out:
199 keymaster_close(keymaster_dev);
200 return rc;
201}
202
203/* Create a new keymaster key and store it in this footer */
204static int keymaster_create_key(struct crypt_mnt_ftr *ftr)
205{
206 uint8_t* key = 0;
207 keymaster_device_t *keymaster_dev = 0;
208
209 if (keymaster_init(&keymaster_dev)) {
210 printf("Failed to init keymaster\n");
211 return -1;
212 }
213
214 int rc = 0;
215
216 keymaster_rsa_keygen_params_t params;
217 memset(&params, '\0', sizeof(params));
218 params.public_exponent = RSA_EXPONENT;
219 params.modulus_size = RSA_KEY_SIZE;
220
221 size_t key_size;
222 if (keymaster_dev->generate_keypair(keymaster_dev, TYPE_RSA, &params,
223 &key, &key_size)) {
224 printf("Failed to generate keypair\n");
225 rc = -1;
226 goto out;
227 }
228
229 if (key_size > KEYMASTER_BLOB_SIZE) {
230 printf("Keymaster key too large for crypto footer\n");
231 rc = -1;
232 goto out;
233 }
234
235 memcpy(ftr->keymaster_blob, key, key_size);
236 ftr->keymaster_blob_size = key_size;
237
238out:
239 keymaster_close(keymaster_dev);
240 free(key);
241 return rc;
242}
243
244/* This signs the given object using the keymaster key. */
245static int keymaster_sign_object(struct crypt_mnt_ftr *ftr,
246 const unsigned char *object,
247 const size_t object_size,
248 unsigned char **signature,
249 size_t *signature_size)
250{
251 int rc = 0;
252 keymaster_device_t *keymaster_dev = 0;
253 if (keymaster_init(&keymaster_dev)) {
254 printf("Failed to init keymaster\n");
255 return -1;
256 }
257
258 /* We currently set the digest type to DIGEST_NONE because it's the
259 * only supported value for keymaster. A similar issue exists with
260 * PADDING_NONE. Long term both of these should likely change.
261 */
262 keymaster_rsa_sign_params_t params;
263 params.digest_type = DIGEST_NONE;
264 params.padding_type = PADDING_NONE;
265
266 unsigned char to_sign[RSA_KEY_SIZE_BYTES];
267 size_t to_sign_size = sizeof(to_sign);
268 memset(to_sign, 0, RSA_KEY_SIZE_BYTES);
269
270 // To sign a message with RSA, the message must satisfy two
271 // constraints:
272 //
273 // 1. The message, when interpreted as a big-endian numeric value, must
274 // be strictly less than the public modulus of the RSA key. Note
275 // that because the most significant bit of the public modulus is
276 // guaranteed to be 1 (else it's an (n-1)-bit key, not an n-bit
277 // key), an n-bit message with most significant bit 0 always
278 // satisfies this requirement.
279 //
280 // 2. The message must have the same length in bits as the public
281 // modulus of the RSA key. This requirement isn't mathematically
282 // necessary, but is necessary to ensure consistency in
283 // implementations.
284 switch (ftr->kdf_type) {
285 case KDF_SCRYPT_KEYMASTER_UNPADDED:
286 // This is broken: It produces a message which is shorter than
287 // the public modulus, failing criterion 2.
288 memcpy(to_sign, object, object_size);
289 to_sign_size = object_size;
290 printf("Signing unpadded object\n");
291 break;
292 case KDF_SCRYPT_KEYMASTER_BADLY_PADDED:
293 // This is broken: Since the value of object is uniformly
294 // distributed, it produces a message that is larger than the
295 // public modulus with probability 0.25.
296 memcpy(to_sign, object, min(RSA_KEY_SIZE_BYTES, object_size));
297 printf("Signing end-padded object\n");
298 break;
299 case KDF_SCRYPT_KEYMASTER:
300 // This ensures the most significant byte of the signed message
301 // is zero. We could have zero-padded to the left instead, but
302 // this approach is slightly more robust against changes in
303 // object size. However, it's still broken (but not unusably
304 // so) because we really should be using a proper RSA padding
305 // function, such as OAEP.
306 //
307 // TODO(paullawrence): When keymaster 0.4 is available, change
308 // this to use the padding options it provides.
309 memcpy(to_sign + 1, object, min(RSA_KEY_SIZE_BYTES - 1, object_size));
310 printf("Signing safely-padded object\n");
311 break;
312 default:
313 printf("Unknown KDF type %d\n", ftr->kdf_type);
314 return -1;
315 }
316
317 rc = keymaster_dev->sign_data(keymaster_dev,
318 &params,
319 ftr->keymaster_blob,
320 ftr->keymaster_blob_size,
321 to_sign,
322 to_sign_size,
323 signature,
324 signature_size);
325
326 keymaster_close(keymaster_dev);
327 return rc;
328}
Ethan Yonkerc798c9c2015-10-09 11:15:26 -0500329#else //#ifndef TW_CRYPTO_HAVE_KEYMASTERX
330static int keymaster_init(keymaster0_device_t **keymaster0_dev,
331 keymaster1_device_t **keymaster1_dev)
332{
333 int rc;
334
335 const hw_module_t* mod;
336 rc = hw_get_module_by_class(KEYSTORE_HARDWARE_MODULE_ID, NULL, &mod);
337 if (rc) {
338 printf("could not find any keystore module\n");
339 goto err;
340 }
341
342 printf("keymaster module name is %s\n", mod->name);
343 printf("keymaster version is %d\n", mod->module_api_version);
344
345 *keymaster0_dev = NULL;
346 *keymaster1_dev = NULL;
347 if (mod->module_api_version == KEYMASTER_MODULE_API_VERSION_1_0) {
348 printf("Found keymaster1 module, using keymaster1 API.\n");
349 rc = keymaster1_open(mod, keymaster1_dev);
350 } else {
351 printf("Found keymaster0 module, using keymaster0 API.\n");
352 rc = keymaster0_open(mod, keymaster0_dev);
353 }
354
355 if (rc) {
356 printf("could not open keymaster device in %s (%s)\n",
357 KEYSTORE_HARDWARE_MODULE_ID, strerror(-rc));
358 goto err;
359 }
360
361 return 0;
362
363err:
364 *keymaster0_dev = NULL;
365 *keymaster1_dev = NULL;
366 return rc;
367}
368
369/* Should we use keymaster? */
370static int keymaster_check_compatibility()
371{
372 keymaster0_device_t *keymaster0_dev = 0;
373 keymaster1_device_t *keymaster1_dev = 0;
374 int rc = 0;
375
376 if (keymaster_init(&keymaster0_dev, &keymaster1_dev)) {
377 printf("Failed to init keymaster\n");
378 rc = -1;
379 goto out;
380 }
381
382 if (keymaster1_dev) {
383 rc = 1;
384 goto out;
385 }
386
387 // TODO(swillden): Check to see if there's any reason to require v0.3. I think v0.1 and v0.2
388 // should work.
389 if (keymaster0_dev->common.module->module_api_version
390 < KEYMASTER_MODULE_API_VERSION_0_3) {
391 rc = 0;
392 goto out;
393 }
394
395 if (!(keymaster0_dev->flags & KEYMASTER_SOFTWARE_ONLY) &&
396 (keymaster0_dev->flags & KEYMASTER_BLOBS_ARE_STANDALONE)) {
397 rc = 1;
398 }
399
400out:
401 if (keymaster1_dev) {
402 keymaster1_close(keymaster1_dev);
403 }
404 if (keymaster0_dev) {
405 keymaster0_close(keymaster0_dev);
406 }
407 return rc;
408}
409
410/* Create a new keymaster key and store it in this footer */
411static int keymaster_create_key(struct crypt_mnt_ftr *ftr)
412{
413 uint8_t* key = 0;
414 keymaster0_device_t *keymaster0_dev = 0;
415 keymaster1_device_t *keymaster1_dev = 0;
416
417 if (keymaster_init(&keymaster0_dev, &keymaster1_dev)) {
418 printf("Failed to init keymaster\n");
419 return -1;
420 }
421
422 int rc = 0;
423 size_t key_size = 0;
424 if (keymaster1_dev) {
425 keymaster_key_param_t params[] = {
426 /* Algorithm & size specifications. Stick with RSA for now. Switch to AES later. */
427 keymaster_param_enum(KM_TAG_ALGORITHM, KM_ALGORITHM_RSA),
428 keymaster_param_int(KM_TAG_KEY_SIZE, RSA_KEY_SIZE),
429 keymaster_param_long(KM_TAG_RSA_PUBLIC_EXPONENT, RSA_EXPONENT),
430
431 /* The only allowed purpose for this key is signing. */
432 keymaster_param_enum(KM_TAG_PURPOSE, KM_PURPOSE_SIGN),
433
434 /* Padding & digest specifications. */
435 keymaster_param_enum(KM_TAG_PADDING, KM_PAD_NONE),
436 keymaster_param_enum(KM_TAG_DIGEST, KM_DIGEST_NONE),
437
438 /* Require that the key be usable in standalone mode. File system isn't available. */
439 keymaster_param_enum(KM_TAG_BLOB_USAGE_REQUIREMENTS, KM_BLOB_STANDALONE),
440
441 /* No auth requirements, because cryptfs is not yet integrated with gatekeeper. */
442 keymaster_param_bool(KM_TAG_NO_AUTH_REQUIRED),
443
444 /* Rate-limit key usage attempts, to rate-limit brute force */
445 keymaster_param_int(KM_TAG_MIN_SECONDS_BETWEEN_OPS, KEYMASTER_CRYPTFS_RATE_LIMIT),
446 };
447 keymaster_key_param_set_t param_set = { params, sizeof(params)/sizeof(*params) };
448 keymaster_key_blob_t key_blob;
449 keymaster_error_t error = keymaster1_dev->generate_key(keymaster1_dev, &param_set,
450 &key_blob,
451 NULL /* characteristics */);
452 if (error != KM_ERROR_OK) {
453 printf("Failed to generate keymaster1 key, error %d\n", error);
454 rc = -1;
455 goto out;
456 }
457
458 key = (uint8_t*)key_blob.key_material;
459 key_size = key_blob.key_material_size;
460 }
461 else if (keymaster0_dev) {
462 keymaster_rsa_keygen_params_t params;
463 memset(&params, '\0', sizeof(params));
464 params.public_exponent = RSA_EXPONENT;
465 params.modulus_size = RSA_KEY_SIZE;
466
467 if (keymaster0_dev->generate_keypair(keymaster0_dev, TYPE_RSA, &params,
468 &key, &key_size)) {
469 printf("Failed to generate keypair\n");
470 rc = -1;
471 goto out;
472 }
473 } else {
474 printf("Cryptfs bug: keymaster_init succeeded but didn't initialize a device\n");
475 rc = -1;
476 goto out;
477 }
478
479 if (key_size > KEYMASTER_BLOB_SIZE) {
480 printf("Keymaster key too large for crypto footer\n");
481 rc = -1;
482 goto out;
483 }
484
485 memcpy(ftr->keymaster_blob, key, key_size);
486 ftr->keymaster_blob_size = key_size;
487
488out:
489 if (keymaster0_dev)
490 keymaster0_close(keymaster0_dev);
491 if (keymaster1_dev)
492 keymaster1_close(keymaster1_dev);
493 free(key);
494 return rc;
495}
496
497/* This signs the given object using the keymaster key. */
498static int keymaster_sign_object(struct crypt_mnt_ftr *ftr,
499 const unsigned char *object,
500 const size_t object_size,
501 unsigned char **signature,
502 size_t *signature_size)
503{
504 int rc = 0;
505 keymaster0_device_t *keymaster0_dev = 0;
506 keymaster1_device_t *keymaster1_dev = 0;
507 if (keymaster_init(&keymaster0_dev, &keymaster1_dev)) {
508 printf("Failed to init keymaster\n");
509 rc = -1;
510 goto out;
511 }
512
513 unsigned char to_sign[RSA_KEY_SIZE_BYTES];
514 size_t to_sign_size = sizeof(to_sign);
515 memset(to_sign, 0, RSA_KEY_SIZE_BYTES);
516
517 // To sign a message with RSA, the message must satisfy two
518 // constraints:
519 //
520 // 1. The message, when interpreted as a big-endian numeric value, must
521 // be strictly less than the public modulus of the RSA key. Note
522 // that because the most significant bit of the public modulus is
523 // guaranteed to be 1 (else it's an (n-1)-bit key, not an n-bit
524 // key), an n-bit message with most significant bit 0 always
525 // satisfies this requirement.
526 //
527 // 2. The message must have the same length in bits as the public
528 // modulus of the RSA key. This requirement isn't mathematically
529 // necessary, but is necessary to ensure consistency in
530 // implementations.
531 switch (ftr->kdf_type) {
532 case KDF_SCRYPT_KEYMASTER:
533 // This ensures the most significant byte of the signed message
534 // is zero. We could have zero-padded to the left instead, but
535 // this approach is slightly more robust against changes in
536 // object size. However, it's still broken (but not unusably
537 // so) because we really should be using a proper deterministic
538 // RSA padding function, such as PKCS1.
539 memcpy(to_sign + 1, object, min(RSA_KEY_SIZE_BYTES - 1, object_size));
540 printf("Signing safely-padded object\n");
541 break;
542 default:
543 printf("Unknown KDF type %d\n", ftr->kdf_type);
544 rc = -1;
545 goto out;
546 }
547
548 if (keymaster0_dev) {
549 keymaster_rsa_sign_params_t params;
550 params.digest_type = DIGEST_NONE;
551 params.padding_type = PADDING_NONE;
552
553 rc = keymaster0_dev->sign_data(keymaster0_dev,
554 &params,
555 ftr->keymaster_blob,
556 ftr->keymaster_blob_size,
557 to_sign,
558 to_sign_size,
559 signature,
560 signature_size);
561 goto out;
562 } else if (keymaster1_dev) {
563 keymaster_key_blob_t key = { ftr->keymaster_blob, ftr->keymaster_blob_size };
564 keymaster_key_param_t params[] = {
565 keymaster_param_enum(KM_TAG_PADDING, KM_PAD_NONE),
566 keymaster_param_enum(KM_TAG_DIGEST, KM_DIGEST_NONE),
567 };
568 keymaster_key_param_set_t param_set = { params, sizeof(params)/sizeof(*params) };
569 keymaster_operation_handle_t op_handle;
570 keymaster_error_t error = keymaster1_dev->begin(keymaster1_dev, KM_PURPOSE_SIGN, &key,
571 &param_set, NULL /* out_params */,
572 &op_handle);
573 if (error == KM_ERROR_KEY_RATE_LIMIT_EXCEEDED) {
574 // Key usage has been rate-limited. Wait a bit and try again.
575 sleep(KEYMASTER_CRYPTFS_RATE_LIMIT);
576 error = keymaster1_dev->begin(keymaster1_dev, KM_PURPOSE_SIGN, &key,
577 &param_set, NULL /* out_params */,
578 &op_handle);
579 }
580 if (error != KM_ERROR_OK) {
581 printf("Error starting keymaster signature transaction: %d\n", error);
582 rc = -1;
583 goto out;
584 }
585
586 keymaster_blob_t input = { to_sign, to_sign_size };
587 size_t input_consumed;
588 error = keymaster1_dev->update(keymaster1_dev, op_handle, NULL /* in_params */,
589 &input, &input_consumed, NULL /* out_params */,
590 NULL /* output */);
591 if (error != KM_ERROR_OK) {
592 printf("Error sending data to keymaster signature transaction: %d\n", error);
593 rc = -1;
594 goto out;
595 }
596 if (input_consumed != to_sign_size) {
597 // This should never happen. If it does, it's a bug in the keymaster implementation.
598 printf("Keymaster update() did not consume all data.\n");
599 keymaster1_dev->abort(keymaster1_dev, op_handle);
600 rc = -1;
601 goto out;
602 }
603
604 keymaster_blob_t tmp_sig;
605 error = keymaster1_dev->finish(keymaster1_dev, op_handle, NULL /* in_params */,
606 NULL /* verify signature */, NULL /* out_params */,
607 &tmp_sig);
608 if (error != KM_ERROR_OK) {
609 printf("Error finishing keymaster signature transaction: %d\n", error);
610 rc = -1;
611 goto out;
612 }
613
614 *signature = (uint8_t*)tmp_sig.data;
615 *signature_size = tmp_sig.data_length;
616 } else {
617 printf("Cryptfs bug: keymaster_init succeded but didn't initialize a device.\n");
618 rc = -1;
619 goto out;
620 }
621
622 out:
623 if (keymaster1_dev)
624 keymaster1_close(keymaster1_dev);
625 if (keymaster0_dev)
626 keymaster0_close(keymaster0_dev);
627
628 return rc;
629}
630#endif //#ifndef TW_CRYPTO_HAVE_KEYMASTERX
Ethan Yonker4eca40d2014-11-11 14:52:28 -0600631
632/* Store password when userdata is successfully decrypted and mounted.
633 * Cleared by cryptfs_clear_password
634 *
635 * To avoid a double prompt at boot, we need to store the CryptKeeper
636 * password and pass it to KeyGuard, which uses it to unlock KeyStore.
637 * Since the entire framework is torn down and rebuilt after encryption,
638 * we have to use a daemon or similar to store the password. Since vold
639 * is secured against IPC except from system processes, it seems a reasonable
640 * place to store this.
641 *
642 * password should be cleared once it has been used.
643 *
644 * password is aged out after password_max_age_seconds seconds.
645 */
646static char* password = 0;
647static int password_expiry_time = 0;
648static const int password_max_age_seconds = 60;
649
Ethan Yonker4eca40d2014-11-11 14:52:28 -0600650static void ioctl_init(struct dm_ioctl *io, size_t dataSize, const char *name, unsigned flags)
651{
652 memset(io, 0, dataSize);
653 io->data_size = dataSize;
654 io->data_start = sizeof(struct dm_ioctl);
655 io->version[0] = 4;
656 io->version[1] = 0;
657 io->version[2] = 0;
658 io->flags = flags;
659 if (name) {
660 strncpy(io->name, name, sizeof(io->name));
661 }
662}
663
664/**
665 * Gets the default device scrypt parameters for key derivation time tuning.
666 * The parameters should lead to about one second derivation time for the
667 * given device.
668 */
669static void get_device_scrypt_params(struct crypt_mnt_ftr *ftr) {
670 const int default_params[] = SCRYPT_DEFAULTS;
671 int params[] = SCRYPT_DEFAULTS;
672 char paramstr[PROPERTY_VALUE_MAX];
673 char *token;
674 char *saveptr;
675 int i;
676
677 property_get(SCRYPT_PROP, paramstr, "");
678 if (paramstr[0] != '\0') {
679 /*
680 * The token we're looking for should be three integers separated by
681 * colons (e.g., "12:8:1"). Scan the property to make sure it matches.
682 */
683 for (i = 0, token = strtok_r(paramstr, ":", &saveptr);
684 token != NULL && i < 3;
685 i++, token = strtok_r(NULL, ":", &saveptr)) {
686 char *endptr;
687 params[i] = strtol(token, &endptr, 10);
688
689 /*
690 * Check that there was a valid number and it's 8-bit. If not,
691 * break out and the end check will take the default values.
692 */
693 if ((*token == '\0') || (*endptr != '\0') || params[i] < 0 || params[i] > 255) {
694 break;
695 }
696 }
697
698 /*
699 * If there were not enough tokens or a token was malformed (not an
700 * integer), it will end up here and the default parameters can be
701 * taken.
702 */
703 if ((i != 3) || (token != NULL)) {
Ethan Yonkerc798c9c2015-10-09 11:15:26 -0500704 printf("bad scrypt parameters '%s' should be like '12:8:1'; using defaults\n", paramstr);
Ethan Yonker4eca40d2014-11-11 14:52:28 -0600705 memcpy(params, default_params, sizeof(params));
706 }
707 }
708
709 ftr->N_factor = params[0];
710 ftr->r_factor = params[1];
711 ftr->p_factor = params[2];
712}
713
Ethan Yonker4eca40d2014-11-11 14:52:28 -0600714static unsigned int get_blkdev_size(int fd)
715{
716 unsigned int nr_sec;
717
718 if ( (ioctl(fd, BLKGETSIZE, &nr_sec)) == -1) {
719 nr_sec = 0;
720 }
721
722 return nr_sec;
723}
724
725static int get_crypt_ftr_info(char **metadata_fname, off64_t *off)
726{
727 static int cached_data = 0;
728 static off64_t cached_off = 0;
729 static char cached_metadata_fname[PROPERTY_VALUE_MAX] = "";
730 int fd;
Ethan Yonker4eca40d2014-11-11 14:52:28 -0600731 unsigned int nr_sec;
732 int rc = -1;
733
734 if (!cached_data) {
Ethan Yonker253368a2014-11-25 15:00:52 -0600735 printf("get_crypt_ftr_info crypto key location: '%s'\n", key_fname);
736 if (!strcmp(key_fname, KEY_IN_FOOTER)) {
Ethan Yonker4eca40d2014-11-11 14:52:28 -0600737 if ( (fd = open(real_blkdev, O_RDWR)) < 0) {
738 printf("Cannot open real block device %s\n", real_blkdev);
739 return -1;
740 }
741
742 if ((nr_sec = get_blkdev_size(fd))) {
743 /* If it's an encrypted Android partition, the last 16 Kbytes contain the
744 * encryption info footer and key, and plenty of bytes to spare for future
745 * growth.
746 */
747 strlcpy(cached_metadata_fname, real_blkdev, sizeof(cached_metadata_fname));
748 cached_off = ((off64_t)nr_sec * 512) - CRYPT_FOOTER_OFFSET;
749 cached_data = 1;
750 } else {
751 printf("Cannot get size of block device %s\n", real_blkdev);
752 }
753 close(fd);
754 } else {
Ethan Yonker253368a2014-11-25 15:00:52 -0600755 strlcpy(cached_metadata_fname, key_fname, sizeof(cached_metadata_fname));
Ethan Yonker4eca40d2014-11-11 14:52:28 -0600756 cached_off = 0;
757 cached_data = 1;
758 }
759 }
760
761 if (cached_data) {
762 if (metadata_fname) {
763 *metadata_fname = cached_metadata_fname;
764 }
765 if (off) {
766 *off = cached_off;
767 }
768 rc = 0;
769 }
770
771 return rc;
772}
773
Ethan Yonker4eca40d2014-11-11 14:52:28 -0600774static int get_crypt_ftr_and_key(struct crypt_mnt_ftr *crypt_ftr)
775{
776 int fd;
777 unsigned int nr_sec, cnt;
778 off64_t starting_off;
779 int rc = -1;
780 char *fname = NULL;
781 struct stat statbuf;
782
783 if (get_crypt_ftr_info(&fname, &starting_off)) {
784 printf("Unable to get crypt_ftr_info\n");
785 return -1;
786 }
787 if (fname[0] != '/') {
788 printf("Unexpected value for crypto key location\n");
789 return -1;
790 }
791 if ( (fd = open(fname, O_RDWR)) < 0) {
792 printf("Cannot open footer file %s for get\n", fname);
793 return -1;
794 }
795
796 /* Make sure it's 16 Kbytes in length */
797 fstat(fd, &statbuf);
798 if (S_ISREG(statbuf.st_mode) && (statbuf.st_size != 0x4000)) {
799 printf("footer file %s is not the expected size!\n", fname);
800 goto errout;
801 }
802
803 /* Seek to the start of the crypt footer */
804 if (lseek64(fd, starting_off, SEEK_SET) == -1) {
805 printf("Cannot seek to real block device footer\n");
806 goto errout;
807 }
808
809 if ( (cnt = read(fd, crypt_ftr, sizeof(struct crypt_mnt_ftr))) != sizeof(struct crypt_mnt_ftr)) {
810 printf("Cannot read real block device footer\n");
811 goto errout;
812 }
813
814 if (crypt_ftr->magic != CRYPT_MNT_MAGIC) {
815 printf("Bad magic for real block device %s\n", fname);
816 goto errout;
817 }
818
819 if (crypt_ftr->major_version != CURRENT_MAJOR_VERSION) {
820 printf("Cannot understand major version %d real block device footer; expected %d\n",
821 crypt_ftr->major_version, CURRENT_MAJOR_VERSION);
822 goto errout;
823 }
824
825 if (crypt_ftr->minor_version > CURRENT_MINOR_VERSION) {
826 printf("Warning: crypto footer minor version %d, expected <= %d, continuing...\n",
827 crypt_ftr->minor_version, CURRENT_MINOR_VERSION);
828 }
829
830 /* If this is a verion 1.0 crypt_ftr, make it a 1.1 crypt footer, and update the
831 * copy on disk before returning.
832 */
Ethan Yonker253368a2014-11-25 15:00:52 -0600833 /*if (crypt_ftr->minor_version < CURRENT_MINOR_VERSION) {
Ethan Yonker4eca40d2014-11-11 14:52:28 -0600834 upgrade_crypt_ftr(fd, crypt_ftr, starting_off);
Ethan Yonker253368a2014-11-25 15:00:52 -0600835 }*/
Ethan Yonker4eca40d2014-11-11 14:52:28 -0600836
837 /* Success! */
838 rc = 0;
839
840errout:
841 close(fd);
842 return rc;
843}
844
Ethan Yonkerd3e96ff2016-02-17 13:36:43 -0600845static int hexdigit (char c)
846{
847 if (c >= '0' && c <= '9') return c - '0';
848 c = tolower(c);
849 if (c >= 'a' && c <= 'f') return c - 'a' + 10;
850 return -1;
851}
852
853static unsigned char* convert_hex_ascii_to_key(const char* master_key_ascii,
854 unsigned int* out_keysize)
855{
856 unsigned int i;
857 *out_keysize = 0;
858
859 size_t size = strlen (master_key_ascii);
860 if (size % 2) {
861 printf("Trying to convert ascii string of odd length\n");
862 return NULL;
863 }
864
865 unsigned char* master_key = (unsigned char*) malloc(size / 2);
866 if (master_key == 0) {
867 printf("Cannot allocate\n");
868 return NULL;
869 }
870
871 for (i = 0; i < size; i += 2) {
872 int high_nibble = hexdigit (master_key_ascii[i]);
873 int low_nibble = hexdigit (master_key_ascii[i + 1]);
874
875 if(high_nibble < 0 || low_nibble < 0) {
876 printf("Invalid hex string\n");
877 free (master_key);
878 return NULL;
879 }
880
881 master_key[*out_keysize] = high_nibble * 16 + low_nibble;
882 (*out_keysize)++;
883 }
884
885 return master_key;
886}
887
Ethan Yonker4eca40d2014-11-11 14:52:28 -0600888/* Convert a binary key of specified length into an ascii hex string equivalent,
889 * without the leading 0x and with null termination
890 */
Ethan Yonkerba95ad12016-01-18 15:18:15 -0600891static void convert_key_to_hex_ascii(const unsigned char *master_key,
892 unsigned int keysize, char *master_key_ascii) {
893 unsigned int i, a;
894 unsigned char nibble;
Ethan Yonker4eca40d2014-11-11 14:52:28 -0600895
Ethan Yonkerba95ad12016-01-18 15:18:15 -0600896 for (i=0, a=0; i<keysize; i++, a+=2) {
897 /* For each byte, write out two ascii hex digits */
898 nibble = (master_key[i] >> 4) & 0xf;
899 master_key_ascii[a] = nibble + (nibble > 9 ? 0x37 : 0x30);
Ethan Yonker4eca40d2014-11-11 14:52:28 -0600900
Ethan Yonkerba95ad12016-01-18 15:18:15 -0600901 nibble = master_key[i] & 0xf;
902 master_key_ascii[a+1] = nibble + (nibble > 9 ? 0x37 : 0x30);
903 }
Ethan Yonker4eca40d2014-11-11 14:52:28 -0600904
Ethan Yonkerba95ad12016-01-18 15:18:15 -0600905 /* Add the null termination */
906 master_key_ascii[a] = '\0';
Ethan Yonker4eca40d2014-11-11 14:52:28 -0600907
908}
909
Sultan Qasim Khana7e63a22016-02-12 20:57:15 -0500910static int load_crypto_mapping_table(struct crypt_mnt_ftr *crypt_ftr, const unsigned char *master_key,
911 const char *real_blk_name, const char *name, int fd,
Ethan Yonker4eca40d2014-11-11 14:52:28 -0600912 char *extra_params)
913{
914 char buffer[DM_CRYPT_BUF_SIZE];
915 struct dm_ioctl *io;
916 struct dm_target_spec *tgt;
917 char *crypt_params;
918 char master_key_ascii[129]; /* Large enough to hold 512 bit key and null */
919 int i;
920
921 io = (struct dm_ioctl *) buffer;
922
923 /* Load the mapping table for this device */
924 tgt = (struct dm_target_spec *) &buffer[sizeof(struct dm_ioctl)];
925
926 ioctl_init(io, DM_CRYPT_BUF_SIZE, name, 0);
927 io->target_count = 1;
928 tgt->status = 0;
929 tgt->sector_start = 0;
930 tgt->length = crypt_ftr->fs_size;
Captain Throwback35df6382016-05-17 11:25:52 -0400931 crypt_params = buffer + sizeof(struct dm_ioctl) + sizeof(struct dm_target_spec);
932
Dees Troyc657cc02015-01-16 22:48:47 +0000933#ifdef CONFIG_HW_DISK_ENCRYPTION
Ethan Yonkerba95ad12016-01-18 15:18:15 -0600934 if(is_hw_disk_encryption((char*)crypt_ftr->crypto_type_name)) {
935 strlcpy(tgt->target_type, "req-crypt",DM_MAX_TYPE_NAME);
936 if (is_ice_enabled())
937 convert_key_to_hex_ascii(master_key, sizeof(int), master_key_ascii);
938 else
939 convert_key_to_hex_ascii(master_key, crypt_ftr->keysize, master_key_ascii);
940 }
941 else {
942 convert_key_to_hex_ascii(master_key, crypt_ftr->keysize, master_key_ascii);
943 strlcpy(tgt->target_type, "crypt", DM_MAX_TYPE_NAME);
944 }
Dees Troyc657cc02015-01-16 22:48:47 +0000945#else
Ethan Yonkerba95ad12016-01-18 15:18:15 -0600946 convert_key_to_hex_ascii(master_key, crypt_ftr->keysize, master_key_ascii);
947 strlcpy(tgt->target_type, "crypt", DM_MAX_TYPE_NAME);
Dees Troyc657cc02015-01-16 22:48:47 +0000948#endif
Ethan Yonker4eca40d2014-11-11 14:52:28 -0600949
Ethan Yonker4eca40d2014-11-11 14:52:28 -0600950 sprintf(crypt_params, "%s %s 0 %s 0 %s", crypt_ftr->crypto_type_name,
951 master_key_ascii, real_blk_name, extra_params);
Dees Troyc657cc02015-01-16 22:48:47 +0000952
953 printf("%s: target_type = %s\n", __func__, tgt->target_type);
954 printf("%s: real_blk_name = %s, extra_params = %s\n", __func__, real_blk_name, extra_params);
955
Ethan Yonker4eca40d2014-11-11 14:52:28 -0600956 crypt_params += strlen(crypt_params) + 1;
957 crypt_params = (char *) (((unsigned long)crypt_params + 7) & ~8); /* Align to an 8 byte boundary */
958 tgt->next = crypt_params - buffer;
959
960 for (i = 0; i < TABLE_LOAD_RETRIES; i++) {
961 if (! ioctl(fd, DM_TABLE_LOAD, io)) {
962 break;
963 }
Ethan Yonker66a19492015-12-10 10:19:45 -0600964 printf("%i\n", errno);
Ethan Yonker4eca40d2014-11-11 14:52:28 -0600965 usleep(500000);
966 }
967
968 if (i == TABLE_LOAD_RETRIES) {
969 /* We failed to load the table, return an error */
970 return -1;
971 } else {
972 return i + 1;
973 }
974}
975
976
977static int get_dm_crypt_version(int fd, const char *name, int *version)
978{
979 char buffer[DM_CRYPT_BUF_SIZE];
980 struct dm_ioctl *io;
981 struct dm_target_versions *v;
Dees Troyc657cc02015-01-16 22:48:47 +0000982 int flag;
Ethan Yonker4eca40d2014-11-11 14:52:28 -0600983 int i;
984
985 io = (struct dm_ioctl *) buffer;
986
987 ioctl_init(io, DM_CRYPT_BUF_SIZE, name, 0);
988
989 if (ioctl(fd, DM_LIST_VERSIONS, io)) {
990 return -1;
991 }
992
993 /* Iterate over the returned versions, looking for name of "crypt".
994 * When found, get and return the version.
995 */
996 v = (struct dm_target_versions *) &buffer[sizeof(struct dm_ioctl)];
997 while (v->next) {
Dees Troyc657cc02015-01-16 22:48:47 +0000998#ifdef CONFIG_HW_DISK_ENCRYPTION
999 if (is_hw_fde_enabled()) {
1000 flag = (!strcmp(v->name, "crypt") || !strcmp(v->name, "req-crypt"));
1001 } else {
1002 flag = (!strcmp(v->name, "crypt"));
1003 }
1004 printf("get_dm_crypt_version flag: %i, name: '%s'\n", flag, v->name);
1005 if (flag) {
1006#else
Ethan Yonker4eca40d2014-11-11 14:52:28 -06001007 if (! strcmp(v->name, "crypt")) {
Dees Troyc657cc02015-01-16 22:48:47 +00001008#endif
Ethan Yonker4eca40d2014-11-11 14:52:28 -06001009 /* We found the crypt driver, return the version, and get out */
1010 version[0] = v->version[0];
1011 version[1] = v->version[1];
1012 version[2] = v->version[2];
1013 return 0;
1014 }
1015 v = (struct dm_target_versions *)(((char *)v) + v->next);
1016 }
1017
1018 return -1;
1019}
1020
Sultan Qasim Khana7e63a22016-02-12 20:57:15 -05001021static int create_crypto_blk_dev(struct crypt_mnt_ftr *crypt_ftr, const unsigned char *master_key,
1022 const char *real_blk_name, char *crypto_blk_name, const char *name)
Ethan Yonker4eca40d2014-11-11 14:52:28 -06001023{
1024 char buffer[DM_CRYPT_BUF_SIZE];
1025 char master_key_ascii[129]; /* Large enough to hold 512 bit key and null */
1026 char *crypt_params;
1027 struct dm_ioctl *io;
1028 struct dm_target_spec *tgt;
1029 unsigned int minor;
Dees Troyc657cc02015-01-16 22:48:47 +00001030 int fd=0;
Ethan Yonker4eca40d2014-11-11 14:52:28 -06001031 int i;
1032 int retval = -1;
1033 int version[3];
1034 char *extra_params;
1035 int load_count;
Dees Troyc657cc02015-01-16 22:48:47 +00001036#ifdef CONFIG_HW_DISK_ENCRYPTION
1037 char encrypted_state[PROPERTY_VALUE_MAX] = {0};
1038 char progress[PROPERTY_VALUE_MAX] = {0};
1039#endif
Ethan Yonker4eca40d2014-11-11 14:52:28 -06001040
1041 if ((fd = open("/dev/device-mapper", O_RDWR)) < 0 ) {
1042 printf("Cannot open device-mapper\n");
1043 goto errout;
1044 }
1045
1046 io = (struct dm_ioctl *) buffer;
1047
1048 ioctl_init(io, DM_CRYPT_BUF_SIZE, name, 0);
1049 if (ioctl(fd, DM_DEV_CREATE, io)) {
Ethan Yonker66a19492015-12-10 10:19:45 -06001050 printf("Cannot create dm-crypt device %i\n", errno);
Ethan Yonker4eca40d2014-11-11 14:52:28 -06001051 goto errout;
1052 }
1053
1054 /* Get the device status, in particular, the name of it's device file */
1055 ioctl_init(io, DM_CRYPT_BUF_SIZE, name, 0);
1056 if (ioctl(fd, DM_DEV_STATUS, io)) {
1057 printf("Cannot retrieve dm-crypt device status\n");
1058 goto errout;
1059 }
1060 minor = (io->dev & 0xff) | ((io->dev >> 12) & 0xfff00);
1061 snprintf(crypto_blk_name, MAXPATHLEN, "/dev/block/dm-%u", minor);
1062
Dees Troyc657cc02015-01-16 22:48:47 +00001063#ifdef CONFIG_HW_DISK_ENCRYPTION
Ethan Yonkerba95ad12016-01-18 15:18:15 -06001064 if(is_hw_disk_encryption((char*)crypt_ftr->crypto_type_name)) {
1065 /* Set fde_enabled if either FDE completed or in-progress */
1066 property_get("ro.crypto.state", encrypted_state, ""); /* FDE completed */
1067 property_get("vold.encrypt_progress", progress, ""); /* FDE in progress */
1068 if (!strcmp(encrypted_state, "encrypted") || strcmp(progress, "")) {
1069 if (is_ice_enabled())
1070 extra_params = "fde_enabled ice";
1071 else
1072 extra_params = "fde_enabled";
1073 } else
1074 extra_params = "fde_disabled";
Dees Troyc657cc02015-01-16 22:48:47 +00001075 } else {
Ethan Yonkerba95ad12016-01-18 15:18:15 -06001076 extra_params = "";
1077 if (! get_dm_crypt_version(fd, name, version)) {
1078 /* Support for allow_discards was added in version 1.11.0 */
1079 if ((version[0] >= 2) ||
1080 ((version[0] == 1) && (version[1] >= 11))) {
1081 extra_params = "1 allow_discards";
1082 printf("Enabling support for allow_discards in dmcrypt.\n");
Dees Troyc657cc02015-01-16 22:48:47 +00001083 }
Ethan Yonkerba95ad12016-01-18 15:18:15 -06001084 }
Dees Troyc657cc02015-01-16 22:48:47 +00001085 }
1086#else
Ethan Yonker4eca40d2014-11-11 14:52:28 -06001087 extra_params = "";
1088 if (! get_dm_crypt_version(fd, name, version)) {
1089 /* Support for allow_discards was added in version 1.11.0 */
1090 if ((version[0] >= 2) ||
1091 ((version[0] == 1) && (version[1] >= 11))) {
1092 extra_params = "1 allow_discards";
1093 printf("Enabling support for allow_discards in dmcrypt.\n");
1094 }
1095 }
Dees Troyc657cc02015-01-16 22:48:47 +00001096#endif
Ethan Yonker4eca40d2014-11-11 14:52:28 -06001097
1098 load_count = load_crypto_mapping_table(crypt_ftr, master_key, real_blk_name, name,
1099 fd, extra_params);
1100 if (load_count < 0) {
1101 printf("Cannot load dm-crypt mapping table.\n");
1102 goto errout;
1103 } else if (load_count > 1) {
1104 printf("Took %d tries to load dmcrypt table.\n", load_count);
1105 }
1106
1107 /* Resume this device to activate it */
1108 ioctl_init(io, DM_CRYPT_BUF_SIZE, name, 0);
1109
1110 if (ioctl(fd, DM_DEV_SUSPEND, io)) {
1111 printf("Cannot resume the dm-crypt device\n");
1112 goto errout;
1113 }
1114
1115 /* We made it here with no errors. Woot! */
1116 retval = 0;
1117
1118errout:
1119 close(fd); /* If fd is <0 from a failed open call, it's safe to just ignore the close error */
1120
1121 return retval;
1122}
1123
Ethan Yonkerd79d9bc2014-12-20 15:38:29 -06001124int delete_crypto_blk_dev(char *name)
Ethan Yonker4eca40d2014-11-11 14:52:28 -06001125{
1126 int fd;
1127 char buffer[DM_CRYPT_BUF_SIZE];
1128 struct dm_ioctl *io;
1129 int retval = -1;
1130
1131 if ((fd = open("/dev/device-mapper", O_RDWR)) < 0 ) {
1132 printf("Cannot open device-mapper\n");
1133 goto errout;
1134 }
1135
1136 io = (struct dm_ioctl *) buffer;
1137
1138 ioctl_init(io, DM_CRYPT_BUF_SIZE, name, 0);
1139 if (ioctl(fd, DM_DEV_REMOVE, io)) {
1140 printf("Cannot remove dm-crypt device\n");
1141 goto errout;
1142 }
1143
1144 /* We made it here with no errors. Woot! */
1145 retval = 0;
1146
1147errout:
1148 close(fd); /* If fd is <0 from a failed open call, it's safe to just ignore the close error */
1149
1150 return retval;
1151
1152}
1153
1154static int pbkdf2(const char *passwd, const unsigned char *salt,
1155 unsigned char *ikey, void *params UNUSED)
1156{
Ethan Yonkerc798c9c2015-10-09 11:15:26 -05001157 printf("Using pbkdf2 for cryptfs KDF\n");
Ethan Yonker4eca40d2014-11-11 14:52:28 -06001158
1159 /* Turn the password into a key and IV that can decrypt the master key */
Ethan Yonkerd3e96ff2016-02-17 13:36:43 -06001160 unsigned int keysize;
1161 char* master_key = (char*)convert_hex_ascii_to_key(passwd, &keysize);
1162 if (!master_key) return -1;
1163 PKCS5_PBKDF2_HMAC_SHA1(master_key, keysize, salt, SALT_LEN,
Ethan Yonker4eca40d2014-11-11 14:52:28 -06001164 HASH_COUNT, KEY_LEN_BYTES+IV_LEN_BYTES, ikey);
1165
Ethan Yonkerd3e96ff2016-02-17 13:36:43 -06001166 memset(master_key, 0, keysize);
1167 free (master_key);
Ethan Yonker4eca40d2014-11-11 14:52:28 -06001168 return 0;
1169}
1170
1171static int scrypt(const char *passwd, const unsigned char *salt,
1172 unsigned char *ikey, void *params)
1173{
1174 printf("Using scrypt for cryptfs KDF\n");
1175
1176 struct crypt_mnt_ftr *ftr = (struct crypt_mnt_ftr *) params;
1177
1178 int N = 1 << ftr->N_factor;
1179 int r = 1 << ftr->r_factor;
1180 int p = 1 << ftr->p_factor;
1181
1182 /* Turn the password into a key and IV that can decrypt the master key */
Ethan Yonkerd3e96ff2016-02-17 13:36:43 -06001183 unsigned int keysize;
1184 unsigned char* master_key = convert_hex_ascii_to_key(passwd, &keysize);
1185 if (!master_key) return -1;
1186 crypto_scrypt(master_key, keysize, salt, SALT_LEN, N, r, p, ikey,
1187 KEY_LEN_BYTES + IV_LEN_BYTES);
Ethan Yonker4eca40d2014-11-11 14:52:28 -06001188
Ethan Yonkerd3e96ff2016-02-17 13:36:43 -06001189 memset(master_key, 0, keysize);
1190 free (master_key);
Ethan Yonker4eca40d2014-11-11 14:52:28 -06001191 return 0;
1192}
1193
1194static int scrypt_keymaster(const char *passwd, const unsigned char *salt,
1195 unsigned char *ikey, void *params)
1196{
1197 printf("Using scrypt with keymaster for cryptfs KDF\n");
1198
1199 int rc;
1200 unsigned int key_size;
1201 size_t signature_size;
1202 unsigned char* signature;
1203 struct crypt_mnt_ftr *ftr = (struct crypt_mnt_ftr *) params;
1204
1205 int N = 1 << ftr->N_factor;
1206 int r = 1 << ftr->r_factor;
1207 int p = 1 << ftr->p_factor;
1208
Ethan Yonkerd3e96ff2016-02-17 13:36:43 -06001209 unsigned char* master_key = convert_hex_ascii_to_key(passwd, &key_size);
1210 if (!master_key) {
Ethan Yonker9f1f2f72016-04-21 11:54:00 -05001211 printf("Failed to convert passwd from hex, using passwd instead\n");
1212 master_key = strdup(passwd);
Ethan Yonkerd3e96ff2016-02-17 13:36:43 -06001213 }
1214
1215 rc = crypto_scrypt(master_key, key_size, salt, SALT_LEN,
Ethan Yonker4eca40d2014-11-11 14:52:28 -06001216 N, r, p, ikey, KEY_LEN_BYTES + IV_LEN_BYTES);
Ethan Yonkerd3e96ff2016-02-17 13:36:43 -06001217 memset(master_key, 0, key_size);
1218 free(master_key);
Ethan Yonker4eca40d2014-11-11 14:52:28 -06001219
1220 if (rc) {
Ethan Yonkercceebb82014-11-18 10:17:59 -06001221 printf("scrypt failed\n");
Ethan Yonker4eca40d2014-11-11 14:52:28 -06001222 return -1;
1223 }
1224
1225 if (keymaster_sign_object(ftr, ikey, KEY_LEN_BYTES + IV_LEN_BYTES,
1226 &signature, &signature_size)) {
Ethan Yonkercceebb82014-11-18 10:17:59 -06001227 printf("Signing failed\n");
Ethan Yonker4eca40d2014-11-11 14:52:28 -06001228 return -1;
1229 }
1230
1231 rc = crypto_scrypt(signature, signature_size, salt, SALT_LEN,
1232 N, r, p, ikey, KEY_LEN_BYTES + IV_LEN_BYTES);
1233 free(signature);
1234
1235 if (rc) {
Ethan Yonkercceebb82014-11-18 10:17:59 -06001236 printf("scrypt failed\n");
Ethan Yonker4eca40d2014-11-11 14:52:28 -06001237 return -1;
1238 }
1239
1240 return 0;
1241}
1242
Ethan Yonker4eca40d2014-11-11 14:52:28 -06001243static int decrypt_master_key_aux(char *passwd, unsigned char *salt,
1244 unsigned char *encrypted_master_key,
1245 unsigned char *decrypted_master_key,
1246 kdf_func kdf, void *kdf_params,
1247 unsigned char** intermediate_key,
1248 size_t* intermediate_key_size)
1249{
1250 unsigned char ikey[32+32] = { 0 }; /* Big enough to hold a 256 bit key and 256 bit IV */
1251 EVP_CIPHER_CTX d_ctx;
1252 int decrypted_len, final_len;
1253
1254 /* Turn the password into an intermediate key and IV that can decrypt the
1255 master key */
1256 if (kdf(passwd, salt, ikey, kdf_params)) {
Ethan Yonkerc798c9c2015-10-09 11:15:26 -05001257 printf("kdf failed\n");
Ethan Yonker4eca40d2014-11-11 14:52:28 -06001258 return -1;
1259 }
1260
1261 /* Initialize the decryption engine */
1262 if (! EVP_DecryptInit(&d_ctx, EVP_aes_128_cbc(), ikey, ikey+KEY_LEN_BYTES)) {
1263 return -1;
1264 }
1265 EVP_CIPHER_CTX_set_padding(&d_ctx, 0); /* Turn off padding as our data is block aligned */
1266 /* Decrypt the master key */
1267 if (! EVP_DecryptUpdate(&d_ctx, decrypted_master_key, &decrypted_len,
1268 encrypted_master_key, KEY_LEN_BYTES)) {
1269 return -1;
1270 }
Ethan Yonkerc798c9c2015-10-09 11:15:26 -05001271#ifndef TW_CRYPTO_HAVE_KEYMASTERX
Ethan Yonker4eca40d2014-11-11 14:52:28 -06001272 if (! EVP_DecryptFinal(&d_ctx, decrypted_master_key + decrypted_len, &final_len)) {
Ethan Yonkerc798c9c2015-10-09 11:15:26 -05001273#else
1274 if (! EVP_DecryptFinal_ex(&d_ctx, decrypted_master_key + decrypted_len, &final_len)) {
1275#endif
Ethan Yonker4eca40d2014-11-11 14:52:28 -06001276 return -1;
1277 }
1278
1279 if (decrypted_len + final_len != KEY_LEN_BYTES) {
1280 return -1;
1281 }
1282
1283 /* Copy intermediate key if needed by params */
1284 if (intermediate_key && intermediate_key_size) {
1285 *intermediate_key = (unsigned char*) malloc(KEY_LEN_BYTES);
1286 if (intermediate_key) {
1287 memcpy(*intermediate_key, ikey, KEY_LEN_BYTES);
1288 *intermediate_key_size = KEY_LEN_BYTES;
1289 }
1290 }
1291
1292 return 0;
1293}
1294
1295static void get_kdf_func(struct crypt_mnt_ftr *ftr, kdf_func *kdf, void** kdf_params)
1296{
1297 if (ftr->kdf_type == KDF_SCRYPT_KEYMASTER_UNPADDED ||
1298 ftr->kdf_type == KDF_SCRYPT_KEYMASTER_BADLY_PADDED ||
1299 ftr->kdf_type == KDF_SCRYPT_KEYMASTER) {
1300 *kdf = scrypt_keymaster;
1301 *kdf_params = ftr;
1302 } else if (ftr->kdf_type == KDF_SCRYPT) {
1303 *kdf = scrypt;
1304 *kdf_params = ftr;
1305 } else {
1306 *kdf = pbkdf2;
1307 *kdf_params = NULL;
1308 }
1309}
1310
1311static int decrypt_master_key(char *passwd, unsigned char *decrypted_master_key,
1312 struct crypt_mnt_ftr *crypt_ftr,
1313 unsigned char** intermediate_key,
1314 size_t* intermediate_key_size)
1315{
1316 kdf_func kdf;
1317 void *kdf_params;
1318 int ret;
1319
1320 get_kdf_func(crypt_ftr, &kdf, &kdf_params);
1321 ret = decrypt_master_key_aux(passwd, crypt_ftr->salt, crypt_ftr->master_key,
1322 decrypted_master_key, kdf, kdf_params,
1323 intermediate_key, intermediate_key_size);
1324 if (ret != 0) {
Ethan Yonkerc798c9c2015-10-09 11:15:26 -05001325 printf("failure decrypting master key\n");
Ethan Yonker4eca40d2014-11-11 14:52:28 -06001326 }
1327
1328 return ret;
1329}
1330
Ethan Yonker4eca40d2014-11-11 14:52:28 -06001331static int test_mount_encrypted_fs(struct crypt_mnt_ftr* crypt_ftr,
1332 char *passwd, char *mount_point, char *label)
1333{
1334 /* Allocate enough space for a 256 bit key, but we may use less */
1335 unsigned char decrypted_master_key[32];
1336 char crypto_blkdev[MAXPATHLEN];
Ethan Yonker4eca40d2014-11-11 14:52:28 -06001337 char tmp_mount_point[64];
Dees Troyc657cc02015-01-16 22:48:47 +00001338 int rc = 0;
Ethan Yonker4eca40d2014-11-11 14:52:28 -06001339 kdf_func kdf;
1340 void *kdf_params;
1341 int use_keymaster = 0;
1342 int upgrade = 0;
1343 unsigned char* intermediate_key = 0;
1344 size_t intermediate_key_size = 0;
1345
1346 printf("crypt_ftr->fs_size = %lld\n", crypt_ftr->fs_size);
Ethan Yonker4eca40d2014-11-11 14:52:28 -06001347
1348 if (! (crypt_ftr->flags & CRYPT_MNT_KEY_UNENCRYPTED) ) {
1349 if (decrypt_master_key(passwd, decrypted_master_key, crypt_ftr,
1350 &intermediate_key, &intermediate_key_size)) {
1351 printf("Failed to decrypt master key\n");
1352 rc = -1;
1353 goto errout;
1354 }
1355 }
1356
Dees Troyc657cc02015-01-16 22:48:47 +00001357#ifdef CONFIG_HW_DISK_ENCRYPTION
Ethan Yonkerba95ad12016-01-18 15:18:15 -06001358 int key_index = 0;
1359 if(is_hw_disk_encryption((char*)crypt_ftr->crypto_type_name)) {
Sultan Qasim Khana7e63a22016-02-12 20:57:15 -05001360 key_index = verify_hw_fde_passwd(passwd, crypt_ftr);
1361
Ethan Yonkerba95ad12016-01-18 15:18:15 -06001362 if (key_index < 0) {
Sultan Qasim Khana7e63a22016-02-12 20:57:15 -05001363 rc = 1;
Ethan Yonkerba95ad12016-01-18 15:18:15 -06001364 goto errout;
1365 }
1366 else {
1367 if (is_ice_enabled()) {
1368 if (create_crypto_blk_dev(crypt_ftr, (unsigned char*)&key_index,
1369 real_blkdev, crypto_blkdev, label)) {
1370 printf("Error creating decrypted block device");
1371 rc = -1;
1372 goto errout;
1373 }
1374 } else {
1375 if (create_crypto_blk_dev(crypt_ftr, decrypted_master_key,
1376 real_blkdev, crypto_blkdev, label)) {
1377 printf("Error creating decrypted block device");
1378 rc = -1;
1379 goto errout;
1380 }
Dees Troyc657cc02015-01-16 22:48:47 +00001381 }
1382 }
Ethan Yonkerba95ad12016-01-18 15:18:15 -06001383 } else {
1384 /* in case HW FDE is delivered through OTA and device is already encrypted
1385 * using SW FDE, we should let user continue using SW FDE until userdata is
1386 * wiped.
1387 */
1388 if (create_crypto_blk_dev(crypt_ftr, decrypted_master_key,
1389 real_blkdev, crypto_blkdev, label)) {
1390 printf("Error creating decrypted block device");
1391 rc = -1;
1392 goto errout;
1393 }
Dees Troyc657cc02015-01-16 22:48:47 +00001394 }
Ethan Yonkerba95ad12016-01-18 15:18:15 -06001395#else
Ethan Yonker4eca40d2014-11-11 14:52:28 -06001396 // Create crypto block device - all (non fatal) code paths
1397 // need it
1398 if (create_crypto_blk_dev(crypt_ftr, decrypted_master_key,
1399 real_blkdev, crypto_blkdev, label)) {
1400 printf("Error creating decrypted block device\n");
1401 rc = -1;
1402 goto errout;
1403 }
Ethan Yonkerba95ad12016-01-18 15:18:15 -06001404#endif
Ethan Yonker4eca40d2014-11-11 14:52:28 -06001405
1406 /* Work out if the problem is the password or the data */
1407 unsigned char scrypted_intermediate_key[sizeof(crypt_ftr->
1408 scrypted_intermediate_key)];
1409 int N = 1 << crypt_ftr->N_factor;
1410 int r = 1 << crypt_ftr->r_factor;
1411 int p = 1 << crypt_ftr->p_factor;
1412
1413 rc = crypto_scrypt(intermediate_key, intermediate_key_size,
1414 crypt_ftr->salt, sizeof(crypt_ftr->salt),
1415 N, r, p, scrypted_intermediate_key,
1416 sizeof(scrypted_intermediate_key));
1417
1418 // Does the key match the crypto footer?
1419 if (rc == 0 && memcmp(scrypted_intermediate_key,
1420 crypt_ftr->scrypted_intermediate_key,
1421 sizeof(scrypted_intermediate_key)) == 0) {
1422 printf("Password matches\n");
1423 rc = 0;
1424 } else {
1425 /* Try mounting the file system anyway, just in case the problem's with
1426 * the footer, not the key. */
1427 sprintf(tmp_mount_point, "%s/tmp_mnt", mount_point);
1428 mkdir(tmp_mount_point, 0755);
Ethan Yonkerceb1e8a2015-12-22 11:41:40 -06001429 if (mount(crypto_blkdev, tmp_mount_point, file_system, 0, NULL) != 0) {
Ethan Yonker4eca40d2014-11-11 14:52:28 -06001430 printf("Error temp mounting decrypted block device '%s'\n", crypto_blkdev);
1431 delete_crypto_blk_dev(label);
Sultan Qasim Khana7e63a22016-02-12 20:57:15 -05001432 rc = 1;
Ethan Yonker4eca40d2014-11-11 14:52:28 -06001433 } else {
1434 /* Success! */
1435 printf("Password did not match but decrypted drive mounted - continue\n");
1436 umount(tmp_mount_point);
1437 rc = 0;
1438 }
1439 }
1440
1441 if (rc == 0) {
Sultan Qasim Khana7e63a22016-02-12 20:57:15 -05001442 // Don't increment the failed attempt counter as it doesn't
1443 // make sense to do so in TWRP
Ethan Yonker4eca40d2014-11-11 14:52:28 -06001444
1445 /* Save the name of the crypto block device
1446 * so we can mount it when restarting the framework. */
1447 property_set("ro.crypto.fs_crypto_blkdev", crypto_blkdev);
1448
Sultan Qasim Khana7e63a22016-02-12 20:57:15 -05001449 // TWRP shouldn't change the stored key
Ethan Yonker4eca40d2014-11-11 14:52:28 -06001450 }
1451
1452 errout:
1453 if (intermediate_key) {
1454 memset(intermediate_key, 0, intermediate_key_size);
1455 free(intermediate_key);
1456 }
1457 return rc;
1458}
1459
Ethan Yonker4eca40d2014-11-11 14:52:28 -06001460int check_unmounted_and_get_ftr(struct crypt_mnt_ftr* crypt_ftr)
1461{
1462 char encrypted_state[PROPERTY_VALUE_MAX];
1463 property_get("ro.crypto.state", encrypted_state, "");
1464 if ( master_key_saved || strcmp(encrypted_state, "encrypted") ) {
1465 printf("encrypted fs already validated or not running with encryption,"
Ethan Yonkercceebb82014-11-18 10:17:59 -06001466 " aborting\n");
1467 //return -1;
Ethan Yonker4eca40d2014-11-11 14:52:28 -06001468 }
1469
1470 if (get_crypt_ftr_and_key(crypt_ftr)) {
Ethan Yonkercceebb82014-11-18 10:17:59 -06001471 printf("Error getting crypt footer and key\n");
Ethan Yonker4eca40d2014-11-11 14:52:28 -06001472 return -1;
1473 }
1474
1475 return 0;
1476}
1477
Ethan Yonker253368a2014-11-25 15:00:52 -06001478int cryptfs_check_footer()
Ethan Yonker4eca40d2014-11-11 14:52:28 -06001479{
1480 int rc = -1;
Ethan Yonker4eca40d2014-11-11 14:52:28 -06001481 struct crypt_mnt_ftr crypt_ftr;
1482
Ethan Yonker4eca40d2014-11-11 14:52:28 -06001483 rc = get_crypt_ftr_and_key(&crypt_ftr);
1484
1485 return rc;
1486}
1487
1488int cryptfs_check_passwd(char *passwd)
1489{
1490 struct crypt_mnt_ftr crypt_ftr;
1491 int rc;
Sultan Qasim Khana7e63a22016-02-12 20:57:15 -05001492
1493 if (!passwd) {
1494 printf("cryptfs_check_passwd: passwd is NULL!\n");
1495 return -1;
1496 }
Ethan Yonker4eca40d2014-11-11 14:52:28 -06001497
1498 rc = check_unmounted_and_get_ftr(&crypt_ftr);
1499 if (rc)
1500 return rc;
1501
Sultan Qasim Khana7e63a22016-02-12 20:57:15 -05001502 rc = test_mount_encrypted_fs(&crypt_ftr, passwd,
1503 DATA_MNT_POINT, "userdata");
Ethan Yonker4eca40d2014-11-11 14:52:28 -06001504
Sultan Qasim Khana7e63a22016-02-12 20:57:15 -05001505 // try falling back to Lollipop hex passwords
1506 if (rc) {
1507 int hex_pass_len = strlen(passwd) * 2 + 1;
1508 char *hex_passwd = (char *)malloc(hex_pass_len);
Dees Troyc657cc02015-01-16 22:48:47 +00001509 if (hex_passwd) {
Sultan Qasim Khana7e63a22016-02-12 20:57:15 -05001510 convert_key_to_hex_ascii((unsigned char *)passwd,
1511 strlen(passwd), hex_passwd);
Ethan Yonker4eca40d2014-11-11 14:52:28 -06001512 rc = test_mount_encrypted_fs(&crypt_ftr, hex_passwd,
Sultan Qasim Khana7e63a22016-02-12 20:57:15 -05001513 DATA_MNT_POINT, "userdata");
1514 memset(hex_passwd, 0, hex_pass_len);
1515 free(hex_passwd);
Dees Troyc657cc02015-01-16 22:48:47 +00001516 }
Ethan Yonker4eca40d2014-11-11 14:52:28 -06001517 }
1518
1519 return rc;
1520}
1521
Ethan Yonker4eca40d2014-11-11 14:52:28 -06001522/* Returns type of the password, default, pattern, pin or password.
1523 */
1524int cryptfs_get_password_type(void)
1525{
1526 struct crypt_mnt_ftr crypt_ftr;
Ethan Yonker4eca40d2014-11-11 14:52:28 -06001527
1528 if (get_crypt_ftr_and_key(&crypt_ftr)) {
1529 printf("Error getting crypt footer and key\n");
1530 return -1;
1531 }
1532
1533 if (crypt_ftr.flags & CRYPT_INCONSISTENT_STATE) {
1534 return -1;
1535 }
1536
1537 return crypt_ftr.crypt_type;
1538}
Ethan Yonker66a19492015-12-10 10:19:45 -06001539
1540/*
1541 * Called by vold when it's asked to mount an encrypted external
1542 * storage volume. The incoming partition has no crypto header/footer,
1543 * as any metadata is been stored in a separate, small partition.
1544 *
1545 * out_crypto_blkdev must be MAXPATHLEN.
1546 */
1547int cryptfs_setup_ext_volume(const char* label, const char* real_blkdev,
1548 const unsigned char* key, int keysize, char* out_crypto_blkdev) {
1549 int fd = open(real_blkdev, O_RDONLY|O_CLOEXEC);
1550 if (fd == -1) {
1551 printf("Failed to open %s: %s", real_blkdev, strerror(errno));
1552 return -1;
1553 }
1554
1555 unsigned long nr_sec = 0;
1556 nr_sec = get_blkdev_size(fd);
1557 close(fd);
1558
1559 if (nr_sec == 0) {
1560 printf("Failed to get size of %s: %s", real_blkdev, strerror(errno));
1561 return -1;
1562 }
1563
1564 struct crypt_mnt_ftr ext_crypt_ftr;
1565 memset(&ext_crypt_ftr, 0, sizeof(ext_crypt_ftr));
1566 ext_crypt_ftr.fs_size = nr_sec;
1567 ext_crypt_ftr.keysize = keysize;
1568 strcpy((char*) ext_crypt_ftr.crypto_type_name, "aes-cbc-essiv:sha256");
1569
1570 return create_crypto_blk_dev(&ext_crypt_ftr, key, real_blkdev,
1571 out_crypto_blkdev, label);
1572}
1573
1574/*
1575 * Called by vold when it's asked to unmount an encrypted external
1576 * storage volume.
1577 */
1578int cryptfs_revert_ext_volume(const char* label) {
1579 return delete_crypto_blk_dev((char*) label);
1580}