blob: fe075c4ad50bc0b72fecc94193c7746bb823cce3 [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 Yonker4eca40d2014-11-11 14:52:28 -0600845/* Convert a binary key of specified length into an ascii hex string equivalent,
846 * without the leading 0x and with null termination
847 */
Ethan Yonkerba95ad12016-01-18 15:18:15 -0600848static void convert_key_to_hex_ascii(const unsigned char *master_key,
849 unsigned int keysize, char *master_key_ascii) {
850 unsigned int i, a;
851 unsigned char nibble;
Ethan Yonker4eca40d2014-11-11 14:52:28 -0600852
Ethan Yonkerba95ad12016-01-18 15:18:15 -0600853 for (i=0, a=0; i<keysize; i++, a+=2) {
854 /* For each byte, write out two ascii hex digits */
855 nibble = (master_key[i] >> 4) & 0xf;
856 master_key_ascii[a] = nibble + (nibble > 9 ? 0x37 : 0x30);
Ethan Yonker4eca40d2014-11-11 14:52:28 -0600857
Ethan Yonkerba95ad12016-01-18 15:18:15 -0600858 nibble = master_key[i] & 0xf;
859 master_key_ascii[a+1] = nibble + (nibble > 9 ? 0x37 : 0x30);
860 }
Ethan Yonker4eca40d2014-11-11 14:52:28 -0600861
Ethan Yonkerba95ad12016-01-18 15:18:15 -0600862 /* Add the null termination */
863 master_key_ascii[a] = '\0';
Ethan Yonker4eca40d2014-11-11 14:52:28 -0600864
865}
866
Sultan Qasim Khana7e63a22016-02-12 20:57:15 -0500867static int load_crypto_mapping_table(struct crypt_mnt_ftr *crypt_ftr, const unsigned char *master_key,
868 const char *real_blk_name, const char *name, int fd,
Ethan Yonker4eca40d2014-11-11 14:52:28 -0600869 char *extra_params)
870{
871 char buffer[DM_CRYPT_BUF_SIZE];
872 struct dm_ioctl *io;
873 struct dm_target_spec *tgt;
874 char *crypt_params;
875 char master_key_ascii[129]; /* Large enough to hold 512 bit key and null */
876 int i;
877
878 io = (struct dm_ioctl *) buffer;
879
880 /* Load the mapping table for this device */
881 tgt = (struct dm_target_spec *) &buffer[sizeof(struct dm_ioctl)];
882
883 ioctl_init(io, DM_CRYPT_BUF_SIZE, name, 0);
884 io->target_count = 1;
885 tgt->status = 0;
886 tgt->sector_start = 0;
887 tgt->length = crypt_ftr->fs_size;
Dees Troyc657cc02015-01-16 22:48:47 +0000888#ifdef CONFIG_HW_DISK_ENCRYPTION
Ethan Yonkerba95ad12016-01-18 15:18:15 -0600889 if(is_hw_disk_encryption((char*)crypt_ftr->crypto_type_name)) {
890 strlcpy(tgt->target_type, "req-crypt",DM_MAX_TYPE_NAME);
891 if (is_ice_enabled())
892 convert_key_to_hex_ascii(master_key, sizeof(int), master_key_ascii);
893 else
894 convert_key_to_hex_ascii(master_key, crypt_ftr->keysize, master_key_ascii);
895 }
896 else {
897 convert_key_to_hex_ascii(master_key, crypt_ftr->keysize, master_key_ascii);
898 strlcpy(tgt->target_type, "crypt", DM_MAX_TYPE_NAME);
899 }
Dees Troyc657cc02015-01-16 22:48:47 +0000900#else
Ethan Yonkerba95ad12016-01-18 15:18:15 -0600901 convert_key_to_hex_ascii(master_key, crypt_ftr->keysize, master_key_ascii);
902 strlcpy(tgt->target_type, "crypt", DM_MAX_TYPE_NAME);
Dees Troyc657cc02015-01-16 22:48:47 +0000903#endif
Ethan Yonker4eca40d2014-11-11 14:52:28 -0600904
905 crypt_params = buffer + sizeof(struct dm_ioctl) + sizeof(struct dm_target_spec);
906 convert_key_to_hex_ascii(master_key, crypt_ftr->keysize, master_key_ascii);
907 sprintf(crypt_params, "%s %s 0 %s 0 %s", crypt_ftr->crypto_type_name,
908 master_key_ascii, real_blk_name, extra_params);
Dees Troyc657cc02015-01-16 22:48:47 +0000909
910 printf("%s: target_type = %s\n", __func__, tgt->target_type);
911 printf("%s: real_blk_name = %s, extra_params = %s\n", __func__, real_blk_name, extra_params);
912
Ethan Yonker4eca40d2014-11-11 14:52:28 -0600913 crypt_params += strlen(crypt_params) + 1;
914 crypt_params = (char *) (((unsigned long)crypt_params + 7) & ~8); /* Align to an 8 byte boundary */
915 tgt->next = crypt_params - buffer;
916
917 for (i = 0; i < TABLE_LOAD_RETRIES; i++) {
918 if (! ioctl(fd, DM_TABLE_LOAD, io)) {
919 break;
920 }
Ethan Yonker66a19492015-12-10 10:19:45 -0600921 printf("%i\n", errno);
Ethan Yonker4eca40d2014-11-11 14:52:28 -0600922 usleep(500000);
923 }
924
925 if (i == TABLE_LOAD_RETRIES) {
926 /* We failed to load the table, return an error */
927 return -1;
928 } else {
929 return i + 1;
930 }
931}
932
933
934static int get_dm_crypt_version(int fd, const char *name, int *version)
935{
936 char buffer[DM_CRYPT_BUF_SIZE];
937 struct dm_ioctl *io;
938 struct dm_target_versions *v;
Dees Troyc657cc02015-01-16 22:48:47 +0000939 int flag;
Ethan Yonker4eca40d2014-11-11 14:52:28 -0600940 int i;
941
942 io = (struct dm_ioctl *) buffer;
943
944 ioctl_init(io, DM_CRYPT_BUF_SIZE, name, 0);
945
946 if (ioctl(fd, DM_LIST_VERSIONS, io)) {
947 return -1;
948 }
949
950 /* Iterate over the returned versions, looking for name of "crypt".
951 * When found, get and return the version.
952 */
953 v = (struct dm_target_versions *) &buffer[sizeof(struct dm_ioctl)];
954 while (v->next) {
Dees Troyc657cc02015-01-16 22:48:47 +0000955#ifdef CONFIG_HW_DISK_ENCRYPTION
956 if (is_hw_fde_enabled()) {
957 flag = (!strcmp(v->name, "crypt") || !strcmp(v->name, "req-crypt"));
958 } else {
959 flag = (!strcmp(v->name, "crypt"));
960 }
961 printf("get_dm_crypt_version flag: %i, name: '%s'\n", flag, v->name);
962 if (flag) {
963#else
Ethan Yonker4eca40d2014-11-11 14:52:28 -0600964 if (! strcmp(v->name, "crypt")) {
Dees Troyc657cc02015-01-16 22:48:47 +0000965#endif
Ethan Yonker4eca40d2014-11-11 14:52:28 -0600966 /* We found the crypt driver, return the version, and get out */
967 version[0] = v->version[0];
968 version[1] = v->version[1];
969 version[2] = v->version[2];
970 return 0;
971 }
972 v = (struct dm_target_versions *)(((char *)v) + v->next);
973 }
974
975 return -1;
976}
977
Sultan Qasim Khana7e63a22016-02-12 20:57:15 -0500978static int create_crypto_blk_dev(struct crypt_mnt_ftr *crypt_ftr, const unsigned char *master_key,
979 const char *real_blk_name, char *crypto_blk_name, const char *name)
Ethan Yonker4eca40d2014-11-11 14:52:28 -0600980{
981 char buffer[DM_CRYPT_BUF_SIZE];
982 char master_key_ascii[129]; /* Large enough to hold 512 bit key and null */
983 char *crypt_params;
984 struct dm_ioctl *io;
985 struct dm_target_spec *tgt;
986 unsigned int minor;
Dees Troyc657cc02015-01-16 22:48:47 +0000987 int fd=0;
Ethan Yonker4eca40d2014-11-11 14:52:28 -0600988 int i;
989 int retval = -1;
990 int version[3];
991 char *extra_params;
992 int load_count;
Dees Troyc657cc02015-01-16 22:48:47 +0000993#ifdef CONFIG_HW_DISK_ENCRYPTION
994 char encrypted_state[PROPERTY_VALUE_MAX] = {0};
995 char progress[PROPERTY_VALUE_MAX] = {0};
996#endif
Ethan Yonker4eca40d2014-11-11 14:52:28 -0600997
998 if ((fd = open("/dev/device-mapper", O_RDWR)) < 0 ) {
999 printf("Cannot open device-mapper\n");
1000 goto errout;
1001 }
1002
1003 io = (struct dm_ioctl *) buffer;
1004
1005 ioctl_init(io, DM_CRYPT_BUF_SIZE, name, 0);
1006 if (ioctl(fd, DM_DEV_CREATE, io)) {
Ethan Yonker66a19492015-12-10 10:19:45 -06001007 printf("Cannot create dm-crypt device %i\n", errno);
Ethan Yonker4eca40d2014-11-11 14:52:28 -06001008 goto errout;
1009 }
1010
1011 /* Get the device status, in particular, the name of it's device file */
1012 ioctl_init(io, DM_CRYPT_BUF_SIZE, name, 0);
1013 if (ioctl(fd, DM_DEV_STATUS, io)) {
1014 printf("Cannot retrieve dm-crypt device status\n");
1015 goto errout;
1016 }
1017 minor = (io->dev & 0xff) | ((io->dev >> 12) & 0xfff00);
1018 snprintf(crypto_blk_name, MAXPATHLEN, "/dev/block/dm-%u", minor);
1019
Dees Troyc657cc02015-01-16 22:48:47 +00001020#ifdef CONFIG_HW_DISK_ENCRYPTION
Ethan Yonkerba95ad12016-01-18 15:18:15 -06001021 if(is_hw_disk_encryption((char*)crypt_ftr->crypto_type_name)) {
1022 /* Set fde_enabled if either FDE completed or in-progress */
1023 property_get("ro.crypto.state", encrypted_state, ""); /* FDE completed */
1024 property_get("vold.encrypt_progress", progress, ""); /* FDE in progress */
1025 if (!strcmp(encrypted_state, "encrypted") || strcmp(progress, "")) {
1026 if (is_ice_enabled())
1027 extra_params = "fde_enabled ice";
1028 else
1029 extra_params = "fde_enabled";
1030 } else
1031 extra_params = "fde_disabled";
Dees Troyc657cc02015-01-16 22:48:47 +00001032 } else {
Ethan Yonkerba95ad12016-01-18 15:18:15 -06001033 extra_params = "";
1034 if (! get_dm_crypt_version(fd, name, version)) {
1035 /* Support for allow_discards was added in version 1.11.0 */
1036 if ((version[0] >= 2) ||
1037 ((version[0] == 1) && (version[1] >= 11))) {
1038 extra_params = "1 allow_discards";
1039 printf("Enabling support for allow_discards in dmcrypt.\n");
Dees Troyc657cc02015-01-16 22:48:47 +00001040 }
Ethan Yonkerba95ad12016-01-18 15:18:15 -06001041 }
Dees Troyc657cc02015-01-16 22:48:47 +00001042 }
1043#else
Ethan Yonker4eca40d2014-11-11 14:52:28 -06001044 extra_params = "";
1045 if (! get_dm_crypt_version(fd, name, version)) {
1046 /* Support for allow_discards was added in version 1.11.0 */
1047 if ((version[0] >= 2) ||
1048 ((version[0] == 1) && (version[1] >= 11))) {
1049 extra_params = "1 allow_discards";
1050 printf("Enabling support for allow_discards in dmcrypt.\n");
1051 }
1052 }
Dees Troyc657cc02015-01-16 22:48:47 +00001053#endif
Ethan Yonker4eca40d2014-11-11 14:52:28 -06001054
1055 load_count = load_crypto_mapping_table(crypt_ftr, master_key, real_blk_name, name,
1056 fd, extra_params);
1057 if (load_count < 0) {
1058 printf("Cannot load dm-crypt mapping table.\n");
1059 goto errout;
1060 } else if (load_count > 1) {
1061 printf("Took %d tries to load dmcrypt table.\n", load_count);
1062 }
1063
1064 /* Resume this device to activate it */
1065 ioctl_init(io, DM_CRYPT_BUF_SIZE, name, 0);
1066
1067 if (ioctl(fd, DM_DEV_SUSPEND, io)) {
1068 printf("Cannot resume the dm-crypt device\n");
1069 goto errout;
1070 }
1071
1072 /* We made it here with no errors. Woot! */
1073 retval = 0;
1074
1075errout:
1076 close(fd); /* If fd is <0 from a failed open call, it's safe to just ignore the close error */
1077
1078 return retval;
1079}
1080
Ethan Yonkerd79d9bc2014-12-20 15:38:29 -06001081int delete_crypto_blk_dev(char *name)
Ethan Yonker4eca40d2014-11-11 14:52:28 -06001082{
1083 int fd;
1084 char buffer[DM_CRYPT_BUF_SIZE];
1085 struct dm_ioctl *io;
1086 int retval = -1;
1087
1088 if ((fd = open("/dev/device-mapper", O_RDWR)) < 0 ) {
1089 printf("Cannot open device-mapper\n");
1090 goto errout;
1091 }
1092
1093 io = (struct dm_ioctl *) buffer;
1094
1095 ioctl_init(io, DM_CRYPT_BUF_SIZE, name, 0);
1096 if (ioctl(fd, DM_DEV_REMOVE, io)) {
1097 printf("Cannot remove dm-crypt device\n");
1098 goto errout;
1099 }
1100
1101 /* We made it here with no errors. Woot! */
1102 retval = 0;
1103
1104errout:
1105 close(fd); /* If fd is <0 from a failed open call, it's safe to just ignore the close error */
1106
1107 return retval;
1108
1109}
1110
1111static int pbkdf2(const char *passwd, const unsigned char *salt,
1112 unsigned char *ikey, void *params UNUSED)
1113{
Ethan Yonkerc798c9c2015-10-09 11:15:26 -05001114 printf("Using pbkdf2 for cryptfs KDF\n");
Ethan Yonker4eca40d2014-11-11 14:52:28 -06001115
1116 /* Turn the password into a key and IV that can decrypt the master key */
Sultan Qasim Khana7e63a22016-02-12 20:57:15 -05001117 PKCS5_PBKDF2_HMAC_SHA1(passwd, strlen(passwd), salt, SALT_LEN,
Ethan Yonker4eca40d2014-11-11 14:52:28 -06001118 HASH_COUNT, KEY_LEN_BYTES+IV_LEN_BYTES, ikey);
1119
Ethan Yonker4eca40d2014-11-11 14:52:28 -06001120 return 0;
1121}
1122
1123static int scrypt(const char *passwd, const unsigned char *salt,
1124 unsigned char *ikey, void *params)
1125{
1126 printf("Using scrypt for cryptfs KDF\n");
1127
1128 struct crypt_mnt_ftr *ftr = (struct crypt_mnt_ftr *) params;
1129
1130 int N = 1 << ftr->N_factor;
1131 int r = 1 << ftr->r_factor;
1132 int p = 1 << ftr->p_factor;
1133
1134 /* Turn the password into a key and IV that can decrypt the master key */
Sultan Qasim Khana7e63a22016-02-12 20:57:15 -05001135 crypto_scrypt((const uint8_t *)passwd, strlen(passwd), salt, SALT_LEN,
1136 N, r, p, ikey, KEY_LEN_BYTES + IV_LEN_BYTES);
Ethan Yonker4eca40d2014-11-11 14:52:28 -06001137
Ethan Yonker4eca40d2014-11-11 14:52:28 -06001138 return 0;
1139}
1140
1141static int scrypt_keymaster(const char *passwd, const unsigned char *salt,
1142 unsigned char *ikey, void *params)
1143{
1144 printf("Using scrypt with keymaster for cryptfs KDF\n");
1145
1146 int rc;
1147 unsigned int key_size;
1148 size_t signature_size;
1149 unsigned char* signature;
1150 struct crypt_mnt_ftr *ftr = (struct crypt_mnt_ftr *) params;
1151
1152 int N = 1 << ftr->N_factor;
1153 int r = 1 << ftr->r_factor;
1154 int p = 1 << ftr->p_factor;
1155
Sultan Qasim Khana7e63a22016-02-12 20:57:15 -05001156 rc = crypto_scrypt((const uint8_t *)passwd, strlen(passwd), salt, SALT_LEN,
Ethan Yonker4eca40d2014-11-11 14:52:28 -06001157 N, r, p, ikey, KEY_LEN_BYTES + IV_LEN_BYTES);
Ethan Yonker4eca40d2014-11-11 14:52:28 -06001158
1159 if (rc) {
Ethan Yonkercceebb82014-11-18 10:17:59 -06001160 printf("scrypt failed\n");
Ethan Yonker4eca40d2014-11-11 14:52:28 -06001161 return -1;
1162 }
1163
1164 if (keymaster_sign_object(ftr, ikey, KEY_LEN_BYTES + IV_LEN_BYTES,
1165 &signature, &signature_size)) {
Ethan Yonkercceebb82014-11-18 10:17:59 -06001166 printf("Signing failed\n");
Ethan Yonker4eca40d2014-11-11 14:52:28 -06001167 return -1;
1168 }
1169
1170 rc = crypto_scrypt(signature, signature_size, salt, SALT_LEN,
1171 N, r, p, ikey, KEY_LEN_BYTES + IV_LEN_BYTES);
1172 free(signature);
1173
1174 if (rc) {
Ethan Yonkercceebb82014-11-18 10:17:59 -06001175 printf("scrypt failed\n");
Ethan Yonker4eca40d2014-11-11 14:52:28 -06001176 return -1;
1177 }
1178
1179 return 0;
1180}
1181
Ethan Yonker4eca40d2014-11-11 14:52:28 -06001182static int decrypt_master_key_aux(char *passwd, unsigned char *salt,
1183 unsigned char *encrypted_master_key,
1184 unsigned char *decrypted_master_key,
1185 kdf_func kdf, void *kdf_params,
1186 unsigned char** intermediate_key,
1187 size_t* intermediate_key_size)
1188{
1189 unsigned char ikey[32+32] = { 0 }; /* Big enough to hold a 256 bit key and 256 bit IV */
1190 EVP_CIPHER_CTX d_ctx;
1191 int decrypted_len, final_len;
1192
1193 /* Turn the password into an intermediate key and IV that can decrypt the
1194 master key */
1195 if (kdf(passwd, salt, ikey, kdf_params)) {
Ethan Yonkerc798c9c2015-10-09 11:15:26 -05001196 printf("kdf failed\n");
Ethan Yonker4eca40d2014-11-11 14:52:28 -06001197 return -1;
1198 }
1199
1200 /* Initialize the decryption engine */
1201 if (! EVP_DecryptInit(&d_ctx, EVP_aes_128_cbc(), ikey, ikey+KEY_LEN_BYTES)) {
1202 return -1;
1203 }
1204 EVP_CIPHER_CTX_set_padding(&d_ctx, 0); /* Turn off padding as our data is block aligned */
1205 /* Decrypt the master key */
1206 if (! EVP_DecryptUpdate(&d_ctx, decrypted_master_key, &decrypted_len,
1207 encrypted_master_key, KEY_LEN_BYTES)) {
1208 return -1;
1209 }
Ethan Yonkerc798c9c2015-10-09 11:15:26 -05001210#ifndef TW_CRYPTO_HAVE_KEYMASTERX
Ethan Yonker4eca40d2014-11-11 14:52:28 -06001211 if (! EVP_DecryptFinal(&d_ctx, decrypted_master_key + decrypted_len, &final_len)) {
Ethan Yonkerc798c9c2015-10-09 11:15:26 -05001212#else
1213 if (! EVP_DecryptFinal_ex(&d_ctx, decrypted_master_key + decrypted_len, &final_len)) {
1214#endif
Ethan Yonker4eca40d2014-11-11 14:52:28 -06001215 return -1;
1216 }
1217
1218 if (decrypted_len + final_len != KEY_LEN_BYTES) {
1219 return -1;
1220 }
1221
1222 /* Copy intermediate key if needed by params */
1223 if (intermediate_key && intermediate_key_size) {
1224 *intermediate_key = (unsigned char*) malloc(KEY_LEN_BYTES);
1225 if (intermediate_key) {
1226 memcpy(*intermediate_key, ikey, KEY_LEN_BYTES);
1227 *intermediate_key_size = KEY_LEN_BYTES;
1228 }
1229 }
1230
1231 return 0;
1232}
1233
1234static void get_kdf_func(struct crypt_mnt_ftr *ftr, kdf_func *kdf, void** kdf_params)
1235{
1236 if (ftr->kdf_type == KDF_SCRYPT_KEYMASTER_UNPADDED ||
1237 ftr->kdf_type == KDF_SCRYPT_KEYMASTER_BADLY_PADDED ||
1238 ftr->kdf_type == KDF_SCRYPT_KEYMASTER) {
1239 *kdf = scrypt_keymaster;
1240 *kdf_params = ftr;
1241 } else if (ftr->kdf_type == KDF_SCRYPT) {
1242 *kdf = scrypt;
1243 *kdf_params = ftr;
1244 } else {
1245 *kdf = pbkdf2;
1246 *kdf_params = NULL;
1247 }
1248}
1249
1250static int decrypt_master_key(char *passwd, unsigned char *decrypted_master_key,
1251 struct crypt_mnt_ftr *crypt_ftr,
1252 unsigned char** intermediate_key,
1253 size_t* intermediate_key_size)
1254{
1255 kdf_func kdf;
1256 void *kdf_params;
1257 int ret;
1258
1259 get_kdf_func(crypt_ftr, &kdf, &kdf_params);
1260 ret = decrypt_master_key_aux(passwd, crypt_ftr->salt, crypt_ftr->master_key,
1261 decrypted_master_key, kdf, kdf_params,
1262 intermediate_key, intermediate_key_size);
1263 if (ret != 0) {
Ethan Yonkerc798c9c2015-10-09 11:15:26 -05001264 printf("failure decrypting master key\n");
Ethan Yonker4eca40d2014-11-11 14:52:28 -06001265 }
1266
1267 return ret;
1268}
1269
Ethan Yonker4eca40d2014-11-11 14:52:28 -06001270static int test_mount_encrypted_fs(struct crypt_mnt_ftr* crypt_ftr,
1271 char *passwd, char *mount_point, char *label)
1272{
1273 /* Allocate enough space for a 256 bit key, but we may use less */
1274 unsigned char decrypted_master_key[32];
1275 char crypto_blkdev[MAXPATHLEN];
Ethan Yonker4eca40d2014-11-11 14:52:28 -06001276 char tmp_mount_point[64];
Dees Troyc657cc02015-01-16 22:48:47 +00001277 int rc = 0;
Ethan Yonker4eca40d2014-11-11 14:52:28 -06001278 kdf_func kdf;
1279 void *kdf_params;
1280 int use_keymaster = 0;
1281 int upgrade = 0;
1282 unsigned char* intermediate_key = 0;
1283 size_t intermediate_key_size = 0;
1284
1285 printf("crypt_ftr->fs_size = %lld\n", crypt_ftr->fs_size);
Ethan Yonker4eca40d2014-11-11 14:52:28 -06001286
1287 if (! (crypt_ftr->flags & CRYPT_MNT_KEY_UNENCRYPTED) ) {
1288 if (decrypt_master_key(passwd, decrypted_master_key, crypt_ftr,
1289 &intermediate_key, &intermediate_key_size)) {
1290 printf("Failed to decrypt master key\n");
1291 rc = -1;
1292 goto errout;
1293 }
1294 }
1295
Dees Troyc657cc02015-01-16 22:48:47 +00001296#ifdef CONFIG_HW_DISK_ENCRYPTION
Ethan Yonkerba95ad12016-01-18 15:18:15 -06001297 int key_index = 0;
1298 if(is_hw_disk_encryption((char*)crypt_ftr->crypto_type_name)) {
Sultan Qasim Khana7e63a22016-02-12 20:57:15 -05001299 key_index = verify_hw_fde_passwd(passwd, crypt_ftr);
1300
Ethan Yonkerba95ad12016-01-18 15:18:15 -06001301 if (key_index < 0) {
Sultan Qasim Khana7e63a22016-02-12 20:57:15 -05001302 rc = 1;
Ethan Yonkerba95ad12016-01-18 15:18:15 -06001303 goto errout;
1304 }
1305 else {
1306 if (is_ice_enabled()) {
1307 if (create_crypto_blk_dev(crypt_ftr, (unsigned char*)&key_index,
1308 real_blkdev, crypto_blkdev, label)) {
1309 printf("Error creating decrypted block device");
1310 rc = -1;
1311 goto errout;
1312 }
1313 } else {
1314 if (create_crypto_blk_dev(crypt_ftr, decrypted_master_key,
1315 real_blkdev, crypto_blkdev, label)) {
1316 printf("Error creating decrypted block device");
1317 rc = -1;
1318 goto errout;
1319 }
Dees Troyc657cc02015-01-16 22:48:47 +00001320 }
1321 }
Ethan Yonkerba95ad12016-01-18 15:18:15 -06001322 } else {
1323 /* in case HW FDE is delivered through OTA and device is already encrypted
1324 * using SW FDE, we should let user continue using SW FDE until userdata is
1325 * wiped.
1326 */
1327 if (create_crypto_blk_dev(crypt_ftr, decrypted_master_key,
1328 real_blkdev, crypto_blkdev, label)) {
1329 printf("Error creating decrypted block device");
1330 rc = -1;
1331 goto errout;
1332 }
Dees Troyc657cc02015-01-16 22:48:47 +00001333 }
Ethan Yonkerba95ad12016-01-18 15:18:15 -06001334#else
Ethan Yonker4eca40d2014-11-11 14:52:28 -06001335 // Create crypto block device - all (non fatal) code paths
1336 // need it
1337 if (create_crypto_blk_dev(crypt_ftr, decrypted_master_key,
1338 real_blkdev, crypto_blkdev, label)) {
1339 printf("Error creating decrypted block device\n");
1340 rc = -1;
1341 goto errout;
1342 }
Ethan Yonkerba95ad12016-01-18 15:18:15 -06001343#endif
Ethan Yonker4eca40d2014-11-11 14:52:28 -06001344
1345 /* Work out if the problem is the password or the data */
1346 unsigned char scrypted_intermediate_key[sizeof(crypt_ftr->
1347 scrypted_intermediate_key)];
1348 int N = 1 << crypt_ftr->N_factor;
1349 int r = 1 << crypt_ftr->r_factor;
1350 int p = 1 << crypt_ftr->p_factor;
1351
1352 rc = crypto_scrypt(intermediate_key, intermediate_key_size,
1353 crypt_ftr->salt, sizeof(crypt_ftr->salt),
1354 N, r, p, scrypted_intermediate_key,
1355 sizeof(scrypted_intermediate_key));
1356
1357 // Does the key match the crypto footer?
1358 if (rc == 0 && memcmp(scrypted_intermediate_key,
1359 crypt_ftr->scrypted_intermediate_key,
1360 sizeof(scrypted_intermediate_key)) == 0) {
1361 printf("Password matches\n");
1362 rc = 0;
1363 } else {
1364 /* Try mounting the file system anyway, just in case the problem's with
1365 * the footer, not the key. */
1366 sprintf(tmp_mount_point, "%s/tmp_mnt", mount_point);
1367 mkdir(tmp_mount_point, 0755);
Ethan Yonkerceb1e8a2015-12-22 11:41:40 -06001368 if (mount(crypto_blkdev, tmp_mount_point, file_system, 0, NULL) != 0) {
Ethan Yonker4eca40d2014-11-11 14:52:28 -06001369 printf("Error temp mounting decrypted block device '%s'\n", crypto_blkdev);
1370 delete_crypto_blk_dev(label);
Sultan Qasim Khana7e63a22016-02-12 20:57:15 -05001371 rc = 1;
Ethan Yonker4eca40d2014-11-11 14:52:28 -06001372 } else {
1373 /* Success! */
1374 printf("Password did not match but decrypted drive mounted - continue\n");
1375 umount(tmp_mount_point);
1376 rc = 0;
1377 }
1378 }
1379
1380 if (rc == 0) {
Sultan Qasim Khana7e63a22016-02-12 20:57:15 -05001381 // Don't increment the failed attempt counter as it doesn't
1382 // make sense to do so in TWRP
Ethan Yonker4eca40d2014-11-11 14:52:28 -06001383
1384 /* Save the name of the crypto block device
1385 * so we can mount it when restarting the framework. */
1386 property_set("ro.crypto.fs_crypto_blkdev", crypto_blkdev);
1387
Sultan Qasim Khana7e63a22016-02-12 20:57:15 -05001388 // TWRP shouldn't change the stored key
Ethan Yonker4eca40d2014-11-11 14:52:28 -06001389 }
1390
1391 errout:
1392 if (intermediate_key) {
1393 memset(intermediate_key, 0, intermediate_key_size);
1394 free(intermediate_key);
1395 }
1396 return rc;
1397}
1398
Ethan Yonker4eca40d2014-11-11 14:52:28 -06001399int check_unmounted_and_get_ftr(struct crypt_mnt_ftr* crypt_ftr)
1400{
1401 char encrypted_state[PROPERTY_VALUE_MAX];
1402 property_get("ro.crypto.state", encrypted_state, "");
1403 if ( master_key_saved || strcmp(encrypted_state, "encrypted") ) {
1404 printf("encrypted fs already validated or not running with encryption,"
Ethan Yonkercceebb82014-11-18 10:17:59 -06001405 " aborting\n");
1406 //return -1;
Ethan Yonker4eca40d2014-11-11 14:52:28 -06001407 }
1408
1409 if (get_crypt_ftr_and_key(crypt_ftr)) {
Ethan Yonkercceebb82014-11-18 10:17:59 -06001410 printf("Error getting crypt footer and key\n");
Ethan Yonker4eca40d2014-11-11 14:52:28 -06001411 return -1;
1412 }
1413
1414 return 0;
1415}
1416
Ethan Yonker253368a2014-11-25 15:00:52 -06001417int cryptfs_check_footer()
Ethan Yonker4eca40d2014-11-11 14:52:28 -06001418{
1419 int rc = -1;
Ethan Yonker4eca40d2014-11-11 14:52:28 -06001420 struct crypt_mnt_ftr crypt_ftr;
1421
Ethan Yonker4eca40d2014-11-11 14:52:28 -06001422 rc = get_crypt_ftr_and_key(&crypt_ftr);
1423
1424 return rc;
1425}
1426
1427int cryptfs_check_passwd(char *passwd)
1428{
1429 struct crypt_mnt_ftr crypt_ftr;
1430 int rc;
Sultan Qasim Khana7e63a22016-02-12 20:57:15 -05001431
1432 if (!passwd) {
1433 printf("cryptfs_check_passwd: passwd is NULL!\n");
1434 return -1;
1435 }
Ethan Yonker4eca40d2014-11-11 14:52:28 -06001436
1437 rc = check_unmounted_and_get_ftr(&crypt_ftr);
1438 if (rc)
1439 return rc;
1440
Sultan Qasim Khana7e63a22016-02-12 20:57:15 -05001441 rc = test_mount_encrypted_fs(&crypt_ftr, passwd,
1442 DATA_MNT_POINT, "userdata");
Ethan Yonker4eca40d2014-11-11 14:52:28 -06001443
Sultan Qasim Khana7e63a22016-02-12 20:57:15 -05001444 // try falling back to Lollipop hex passwords
1445 if (rc) {
1446 int hex_pass_len = strlen(passwd) * 2 + 1;
1447 char *hex_passwd = (char *)malloc(hex_pass_len);
Dees Troyc657cc02015-01-16 22:48:47 +00001448 if (hex_passwd) {
Sultan Qasim Khana7e63a22016-02-12 20:57:15 -05001449 convert_key_to_hex_ascii((unsigned char *)passwd,
1450 strlen(passwd), hex_passwd);
Ethan Yonker4eca40d2014-11-11 14:52:28 -06001451 rc = test_mount_encrypted_fs(&crypt_ftr, hex_passwd,
Sultan Qasim Khana7e63a22016-02-12 20:57:15 -05001452 DATA_MNT_POINT, "userdata");
1453 memset(hex_passwd, 0, hex_pass_len);
1454 free(hex_passwd);
Dees Troyc657cc02015-01-16 22:48:47 +00001455 }
Ethan Yonker4eca40d2014-11-11 14:52:28 -06001456 }
1457
1458 return rc;
1459}
1460
Ethan Yonker4eca40d2014-11-11 14:52:28 -06001461/* Returns type of the password, default, pattern, pin or password.
1462 */
1463int cryptfs_get_password_type(void)
1464{
1465 struct crypt_mnt_ftr crypt_ftr;
Ethan Yonker4eca40d2014-11-11 14:52:28 -06001466
1467 if (get_crypt_ftr_and_key(&crypt_ftr)) {
1468 printf("Error getting crypt footer and key\n");
1469 return -1;
1470 }
1471
1472 if (crypt_ftr.flags & CRYPT_INCONSISTENT_STATE) {
1473 return -1;
1474 }
1475
1476 return crypt_ftr.crypt_type;
1477}
Ethan Yonker66a19492015-12-10 10:19:45 -06001478
1479/*
1480 * Called by vold when it's asked to mount an encrypted external
1481 * storage volume. The incoming partition has no crypto header/footer,
1482 * as any metadata is been stored in a separate, small partition.
1483 *
1484 * out_crypto_blkdev must be MAXPATHLEN.
1485 */
1486int cryptfs_setup_ext_volume(const char* label, const char* real_blkdev,
1487 const unsigned char* key, int keysize, char* out_crypto_blkdev) {
1488 int fd = open(real_blkdev, O_RDONLY|O_CLOEXEC);
1489 if (fd == -1) {
1490 printf("Failed to open %s: %s", real_blkdev, strerror(errno));
1491 return -1;
1492 }
1493
1494 unsigned long nr_sec = 0;
1495 nr_sec = get_blkdev_size(fd);
1496 close(fd);
1497
1498 if (nr_sec == 0) {
1499 printf("Failed to get size of %s: %s", real_blkdev, strerror(errno));
1500 return -1;
1501 }
1502
1503 struct crypt_mnt_ftr ext_crypt_ftr;
1504 memset(&ext_crypt_ftr, 0, sizeof(ext_crypt_ftr));
1505 ext_crypt_ftr.fs_size = nr_sec;
1506 ext_crypt_ftr.keysize = keysize;
1507 strcpy((char*) ext_crypt_ftr.crypto_type_name, "aes-cbc-essiv:sha256");
1508
1509 return create_crypto_blk_dev(&ext_crypt_ftr, key, real_blkdev,
1510 out_crypto_blkdev, label);
1511}
1512
1513/*
1514 * Called by vold when it's asked to unmount an encrypted external
1515 * storage volume.
1516 */
1517int cryptfs_revert_ext_volume(const char* label) {
1518 return delete_crypto_blk_dev((char*) label);
1519}