blob: d3bf629550d6aaeec8c1275648d3d05bd6a9cc87 [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
Ethan Yonker4eca40d2014-11-11 14:52:28 -060092static int master_key_saved = 0;
Ethan Yonker253368a2014-11-25 15:00:52 -060093static char key_fname[PROPERTY_VALUE_MAX] = "";
94static char real_blkdev[PROPERTY_VALUE_MAX] = "";
95static char file_system[PROPERTY_VALUE_MAX] = "";
96
Ethan Yonkerba95ad12016-01-18 15:18:15 -060097#ifdef CONFIG_HW_DISK_ENCRYPTION
Ethan Yonkerba95ad12016-01-18 15:18:15 -060098static int scrypt_keymaster(const char *passwd, const unsigned char *salt,
99 unsigned char *ikey, void *params);
100static void convert_key_to_hex_ascii(const unsigned char *master_key,
101 unsigned int keysize, char *master_key_ascii);
Ethan Yonkerba95ad12016-01-18 15:18:15 -0600102static int get_keymaster_hw_fde_passwd(const char* passwd, unsigned char* newpw,
103 unsigned char* salt,
104 const struct crypt_mnt_ftr *ftr)
105{
106 /* if newpw updated, return 0
107 * if newpw not updated return -1
108 */
109 int rc = -1;
110
111 if (should_use_keymaster()) {
112 if (scrypt_keymaster(passwd, salt, newpw, (void*)ftr)) {
113 printf("scrypt failed");
114 } else {
115 rc = 0;
116 }
117 }
118
119 return rc;
120}
121
122static int verify_hw_fde_passwd(char *passwd, struct crypt_mnt_ftr* crypt_ftr)
123{
124 unsigned char newpw[32] = {0};
125 int key_index;
126 if (get_keymaster_hw_fde_passwd(passwd, newpw, crypt_ftr->salt, crypt_ftr))
127 key_index = set_hw_device_encryption_key(passwd,
128 (char*) crypt_ftr->crypto_type_name);
129 else
130 key_index = set_hw_device_encryption_key((const char*)newpw,
131 (char*) crypt_ftr->crypto_type_name);
132 return key_index;
133}
Ethan Yonkerba95ad12016-01-18 15:18:15 -0600134#endif
135
Ethan Yonker253368a2014-11-25 15:00:52 -0600136void set_partition_data(const char* block_device, const char* key_location, const char* fs)
137{
138 strcpy(key_fname, key_location);
139 strcpy(real_blkdev, block_device);
140 strcpy(file_system, fs);
141}
Ethan Yonker4eca40d2014-11-11 14:52:28 -0600142
Ethan Yonkerc798c9c2015-10-09 11:15:26 -0500143#ifndef TW_CRYPTO_HAVE_KEYMASTERX
Ethan Yonker4eca40d2014-11-11 14:52:28 -0600144static int keymaster_init(keymaster_device_t **keymaster_dev)
145{
146 int rc;
147
148 const hw_module_t* mod;
149 rc = hw_get_module_by_class(KEYSTORE_HARDWARE_MODULE_ID, NULL, &mod);
150 if (rc) {
151 printf("could not find any keystore module\n");
152 goto out;
153 }
154
155 rc = keymaster_open(mod, keymaster_dev);
156 if (rc) {
157 printf("could not open keymaster device in %s (%s)\n",
158 KEYSTORE_HARDWARE_MODULE_ID, strerror(-rc));
159 goto out;
160 }
161
162 return 0;
163
164out:
165 *keymaster_dev = NULL;
166 return rc;
167}
168
169/* Should we use keymaster? */
170static int keymaster_check_compatibility()
171{
172 keymaster_device_t *keymaster_dev = 0;
173 int rc = 0;
174
175 if (keymaster_init(&keymaster_dev)) {
176 printf("Failed to init keymaster\n");
177 rc = -1;
178 goto out;
179 }
180
181 printf("keymaster version is %d\n", keymaster_dev->common.module->module_api_version);
182
thatceb7b8e2014-12-09 23:15:16 +0100183#if (KEYMASTER_HEADER_VERSION >= 3)
Ethan Yonker4eca40d2014-11-11 14:52:28 -0600184 if (keymaster_dev->common.module->module_api_version
185 < KEYMASTER_MODULE_API_VERSION_0_3) {
186 rc = 0;
187 goto out;
188 }
189
190 if (keymaster_dev->flags & KEYMASTER_BLOBS_ARE_STANDALONE) {
191 rc = 1;
192 }
193
thatceb7b8e2014-12-09 23:15:16 +0100194#endif
Ethan Yonker4eca40d2014-11-11 14:52:28 -0600195out:
196 keymaster_close(keymaster_dev);
197 return rc;
198}
199
200/* Create a new keymaster key and store it in this footer */
201static int keymaster_create_key(struct crypt_mnt_ftr *ftr)
202{
203 uint8_t* key = 0;
204 keymaster_device_t *keymaster_dev = 0;
205
206 if (keymaster_init(&keymaster_dev)) {
207 printf("Failed to init keymaster\n");
208 return -1;
209 }
210
211 int rc = 0;
212
213 keymaster_rsa_keygen_params_t params;
214 memset(&params, '\0', sizeof(params));
215 params.public_exponent = RSA_EXPONENT;
216 params.modulus_size = RSA_KEY_SIZE;
217
218 size_t key_size;
219 if (keymaster_dev->generate_keypair(keymaster_dev, TYPE_RSA, &params,
220 &key, &key_size)) {
221 printf("Failed to generate keypair\n");
222 rc = -1;
223 goto out;
224 }
225
226 if (key_size > KEYMASTER_BLOB_SIZE) {
227 printf("Keymaster key too large for crypto footer\n");
228 rc = -1;
229 goto out;
230 }
231
232 memcpy(ftr->keymaster_blob, key, key_size);
233 ftr->keymaster_blob_size = key_size;
234
235out:
236 keymaster_close(keymaster_dev);
237 free(key);
238 return rc;
239}
240
241/* This signs the given object using the keymaster key. */
242static int keymaster_sign_object(struct crypt_mnt_ftr *ftr,
243 const unsigned char *object,
244 const size_t object_size,
245 unsigned char **signature,
246 size_t *signature_size)
247{
248 int rc = 0;
249 keymaster_device_t *keymaster_dev = 0;
250 if (keymaster_init(&keymaster_dev)) {
251 printf("Failed to init keymaster\n");
252 return -1;
253 }
254
255 /* We currently set the digest type to DIGEST_NONE because it's the
256 * only supported value for keymaster. A similar issue exists with
257 * PADDING_NONE. Long term both of these should likely change.
258 */
259 keymaster_rsa_sign_params_t params;
260 params.digest_type = DIGEST_NONE;
261 params.padding_type = PADDING_NONE;
262
263 unsigned char to_sign[RSA_KEY_SIZE_BYTES];
264 size_t to_sign_size = sizeof(to_sign);
265 memset(to_sign, 0, RSA_KEY_SIZE_BYTES);
266
267 // To sign a message with RSA, the message must satisfy two
268 // constraints:
269 //
270 // 1. The message, when interpreted as a big-endian numeric value, must
271 // be strictly less than the public modulus of the RSA key. Note
272 // that because the most significant bit of the public modulus is
273 // guaranteed to be 1 (else it's an (n-1)-bit key, not an n-bit
274 // key), an n-bit message with most significant bit 0 always
275 // satisfies this requirement.
276 //
277 // 2. The message must have the same length in bits as the public
278 // modulus of the RSA key. This requirement isn't mathematically
279 // necessary, but is necessary to ensure consistency in
280 // implementations.
281 switch (ftr->kdf_type) {
282 case KDF_SCRYPT_KEYMASTER_UNPADDED:
283 // This is broken: It produces a message which is shorter than
284 // the public modulus, failing criterion 2.
285 memcpy(to_sign, object, object_size);
286 to_sign_size = object_size;
287 printf("Signing unpadded object\n");
288 break;
289 case KDF_SCRYPT_KEYMASTER_BADLY_PADDED:
290 // This is broken: Since the value of object is uniformly
291 // distributed, it produces a message that is larger than the
292 // public modulus with probability 0.25.
293 memcpy(to_sign, object, min(RSA_KEY_SIZE_BYTES, object_size));
294 printf("Signing end-padded object\n");
295 break;
296 case KDF_SCRYPT_KEYMASTER:
297 // This ensures the most significant byte of the signed message
298 // is zero. We could have zero-padded to the left instead, but
299 // this approach is slightly more robust against changes in
300 // object size. However, it's still broken (but not unusably
301 // so) because we really should be using a proper RSA padding
302 // function, such as OAEP.
303 //
304 // TODO(paullawrence): When keymaster 0.4 is available, change
305 // this to use the padding options it provides.
306 memcpy(to_sign + 1, object, min(RSA_KEY_SIZE_BYTES - 1, object_size));
307 printf("Signing safely-padded object\n");
308 break;
309 default:
310 printf("Unknown KDF type %d\n", ftr->kdf_type);
311 return -1;
312 }
313
314 rc = keymaster_dev->sign_data(keymaster_dev,
315 &params,
316 ftr->keymaster_blob,
317 ftr->keymaster_blob_size,
318 to_sign,
319 to_sign_size,
320 signature,
321 signature_size);
322
323 keymaster_close(keymaster_dev);
324 return rc;
325}
Ethan Yonkerc798c9c2015-10-09 11:15:26 -0500326#else //#ifndef TW_CRYPTO_HAVE_KEYMASTERX
327static int keymaster_init(keymaster0_device_t **keymaster0_dev,
328 keymaster1_device_t **keymaster1_dev)
329{
330 int rc;
331
332 const hw_module_t* mod;
333 rc = hw_get_module_by_class(KEYSTORE_HARDWARE_MODULE_ID, NULL, &mod);
334 if (rc) {
335 printf("could not find any keystore module\n");
336 goto err;
337 }
338
339 printf("keymaster module name is %s\n", mod->name);
340 printf("keymaster version is %d\n", mod->module_api_version);
341
342 *keymaster0_dev = NULL;
343 *keymaster1_dev = NULL;
344 if (mod->module_api_version == KEYMASTER_MODULE_API_VERSION_1_0) {
345 printf("Found keymaster1 module, using keymaster1 API.\n");
346 rc = keymaster1_open(mod, keymaster1_dev);
347 } else {
348 printf("Found keymaster0 module, using keymaster0 API.\n");
349 rc = keymaster0_open(mod, keymaster0_dev);
350 }
351
352 if (rc) {
353 printf("could not open keymaster device in %s (%s)\n",
354 KEYSTORE_HARDWARE_MODULE_ID, strerror(-rc));
355 goto err;
356 }
357
358 return 0;
359
360err:
361 *keymaster0_dev = NULL;
362 *keymaster1_dev = NULL;
363 return rc;
364}
365
366/* Should we use keymaster? */
367static int keymaster_check_compatibility()
368{
369 keymaster0_device_t *keymaster0_dev = 0;
370 keymaster1_device_t *keymaster1_dev = 0;
371 int rc = 0;
372
373 if (keymaster_init(&keymaster0_dev, &keymaster1_dev)) {
374 printf("Failed to init keymaster\n");
375 rc = -1;
376 goto out;
377 }
378
379 if (keymaster1_dev) {
380 rc = 1;
381 goto out;
382 }
383
384 // TODO(swillden): Check to see if there's any reason to require v0.3. I think v0.1 and v0.2
385 // should work.
386 if (keymaster0_dev->common.module->module_api_version
387 < KEYMASTER_MODULE_API_VERSION_0_3) {
388 rc = 0;
389 goto out;
390 }
391
392 if (!(keymaster0_dev->flags & KEYMASTER_SOFTWARE_ONLY) &&
393 (keymaster0_dev->flags & KEYMASTER_BLOBS_ARE_STANDALONE)) {
394 rc = 1;
395 }
396
397out:
398 if (keymaster1_dev) {
399 keymaster1_close(keymaster1_dev);
400 }
401 if (keymaster0_dev) {
402 keymaster0_close(keymaster0_dev);
403 }
404 return rc;
405}
406
407/* Create a new keymaster key and store it in this footer */
408static int keymaster_create_key(struct crypt_mnt_ftr *ftr)
409{
410 uint8_t* key = 0;
411 keymaster0_device_t *keymaster0_dev = 0;
412 keymaster1_device_t *keymaster1_dev = 0;
413
414 if (keymaster_init(&keymaster0_dev, &keymaster1_dev)) {
415 printf("Failed to init keymaster\n");
416 return -1;
417 }
418
419 int rc = 0;
420 size_t key_size = 0;
421 if (keymaster1_dev) {
422 keymaster_key_param_t params[] = {
423 /* Algorithm & size specifications. Stick with RSA for now. Switch to AES later. */
424 keymaster_param_enum(KM_TAG_ALGORITHM, KM_ALGORITHM_RSA),
425 keymaster_param_int(KM_TAG_KEY_SIZE, RSA_KEY_SIZE),
426 keymaster_param_long(KM_TAG_RSA_PUBLIC_EXPONENT, RSA_EXPONENT),
427
428 /* The only allowed purpose for this key is signing. */
429 keymaster_param_enum(KM_TAG_PURPOSE, KM_PURPOSE_SIGN),
430
431 /* Padding & digest specifications. */
432 keymaster_param_enum(KM_TAG_PADDING, KM_PAD_NONE),
433 keymaster_param_enum(KM_TAG_DIGEST, KM_DIGEST_NONE),
434
435 /* Require that the key be usable in standalone mode. File system isn't available. */
436 keymaster_param_enum(KM_TAG_BLOB_USAGE_REQUIREMENTS, KM_BLOB_STANDALONE),
437
438 /* No auth requirements, because cryptfs is not yet integrated with gatekeeper. */
439 keymaster_param_bool(KM_TAG_NO_AUTH_REQUIRED),
440
441 /* Rate-limit key usage attempts, to rate-limit brute force */
442 keymaster_param_int(KM_TAG_MIN_SECONDS_BETWEEN_OPS, KEYMASTER_CRYPTFS_RATE_LIMIT),
443 };
444 keymaster_key_param_set_t param_set = { params, sizeof(params)/sizeof(*params) };
445 keymaster_key_blob_t key_blob;
446 keymaster_error_t error = keymaster1_dev->generate_key(keymaster1_dev, &param_set,
447 &key_blob,
448 NULL /* characteristics */);
449 if (error != KM_ERROR_OK) {
450 printf("Failed to generate keymaster1 key, error %d\n", error);
451 rc = -1;
452 goto out;
453 }
454
455 key = (uint8_t*)key_blob.key_material;
456 key_size = key_blob.key_material_size;
457 }
458 else if (keymaster0_dev) {
459 keymaster_rsa_keygen_params_t params;
460 memset(&params, '\0', sizeof(params));
461 params.public_exponent = RSA_EXPONENT;
462 params.modulus_size = RSA_KEY_SIZE;
463
464 if (keymaster0_dev->generate_keypair(keymaster0_dev, TYPE_RSA, &params,
465 &key, &key_size)) {
466 printf("Failed to generate keypair\n");
467 rc = -1;
468 goto out;
469 }
470 } else {
471 printf("Cryptfs bug: keymaster_init succeeded but didn't initialize a device\n");
472 rc = -1;
473 goto out;
474 }
475
476 if (key_size > KEYMASTER_BLOB_SIZE) {
477 printf("Keymaster key too large for crypto footer\n");
478 rc = -1;
479 goto out;
480 }
481
482 memcpy(ftr->keymaster_blob, key, key_size);
483 ftr->keymaster_blob_size = key_size;
484
485out:
486 if (keymaster0_dev)
487 keymaster0_close(keymaster0_dev);
488 if (keymaster1_dev)
489 keymaster1_close(keymaster1_dev);
490 free(key);
491 return rc;
492}
493
494/* This signs the given object using the keymaster key. */
495static int keymaster_sign_object(struct crypt_mnt_ftr *ftr,
496 const unsigned char *object,
497 const size_t object_size,
498 unsigned char **signature,
499 size_t *signature_size)
500{
501 int rc = 0;
502 keymaster0_device_t *keymaster0_dev = 0;
503 keymaster1_device_t *keymaster1_dev = 0;
504 if (keymaster_init(&keymaster0_dev, &keymaster1_dev)) {
505 printf("Failed to init keymaster\n");
506 rc = -1;
507 goto out;
508 }
509
510 unsigned char to_sign[RSA_KEY_SIZE_BYTES];
511 size_t to_sign_size = sizeof(to_sign);
512 memset(to_sign, 0, RSA_KEY_SIZE_BYTES);
513
514 // To sign a message with RSA, the message must satisfy two
515 // constraints:
516 //
517 // 1. The message, when interpreted as a big-endian numeric value, must
518 // be strictly less than the public modulus of the RSA key. Note
519 // that because the most significant bit of the public modulus is
520 // guaranteed to be 1 (else it's an (n-1)-bit key, not an n-bit
521 // key), an n-bit message with most significant bit 0 always
522 // satisfies this requirement.
523 //
524 // 2. The message must have the same length in bits as the public
525 // modulus of the RSA key. This requirement isn't mathematically
526 // necessary, but is necessary to ensure consistency in
527 // implementations.
528 switch (ftr->kdf_type) {
529 case KDF_SCRYPT_KEYMASTER:
530 // This ensures the most significant byte of the signed message
531 // is zero. We could have zero-padded to the left instead, but
532 // this approach is slightly more robust against changes in
533 // object size. However, it's still broken (but not unusably
534 // so) because we really should be using a proper deterministic
535 // RSA padding function, such as PKCS1.
536 memcpy(to_sign + 1, object, min(RSA_KEY_SIZE_BYTES - 1, object_size));
537 printf("Signing safely-padded object\n");
538 break;
539 default:
540 printf("Unknown KDF type %d\n", ftr->kdf_type);
541 rc = -1;
542 goto out;
543 }
544
545 if (keymaster0_dev) {
546 keymaster_rsa_sign_params_t params;
547 params.digest_type = DIGEST_NONE;
548 params.padding_type = PADDING_NONE;
549
550 rc = keymaster0_dev->sign_data(keymaster0_dev,
551 &params,
552 ftr->keymaster_blob,
553 ftr->keymaster_blob_size,
554 to_sign,
555 to_sign_size,
556 signature,
557 signature_size);
558 goto out;
559 } else if (keymaster1_dev) {
560 keymaster_key_blob_t key = { ftr->keymaster_blob, ftr->keymaster_blob_size };
561 keymaster_key_param_t params[] = {
562 keymaster_param_enum(KM_TAG_PADDING, KM_PAD_NONE),
563 keymaster_param_enum(KM_TAG_DIGEST, KM_DIGEST_NONE),
564 };
565 keymaster_key_param_set_t param_set = { params, sizeof(params)/sizeof(*params) };
566 keymaster_operation_handle_t op_handle;
567 keymaster_error_t error = keymaster1_dev->begin(keymaster1_dev, KM_PURPOSE_SIGN, &key,
568 &param_set, NULL /* out_params */,
569 &op_handle);
570 if (error == KM_ERROR_KEY_RATE_LIMIT_EXCEEDED) {
571 // Key usage has been rate-limited. Wait a bit and try again.
572 sleep(KEYMASTER_CRYPTFS_RATE_LIMIT);
573 error = keymaster1_dev->begin(keymaster1_dev, KM_PURPOSE_SIGN, &key,
574 &param_set, NULL /* out_params */,
575 &op_handle);
576 }
577 if (error != KM_ERROR_OK) {
578 printf("Error starting keymaster signature transaction: %d\n", error);
579 rc = -1;
580 goto out;
581 }
582
583 keymaster_blob_t input = { to_sign, to_sign_size };
584 size_t input_consumed;
585 error = keymaster1_dev->update(keymaster1_dev, op_handle, NULL /* in_params */,
586 &input, &input_consumed, NULL /* out_params */,
587 NULL /* output */);
588 if (error != KM_ERROR_OK) {
589 printf("Error sending data to keymaster signature transaction: %d\n", error);
590 rc = -1;
591 goto out;
592 }
593 if (input_consumed != to_sign_size) {
594 // This should never happen. If it does, it's a bug in the keymaster implementation.
595 printf("Keymaster update() did not consume all data.\n");
596 keymaster1_dev->abort(keymaster1_dev, op_handle);
597 rc = -1;
598 goto out;
599 }
600
601 keymaster_blob_t tmp_sig;
602 error = keymaster1_dev->finish(keymaster1_dev, op_handle, NULL /* in_params */,
603 NULL /* verify signature */, NULL /* out_params */,
604 &tmp_sig);
605 if (error != KM_ERROR_OK) {
606 printf("Error finishing keymaster signature transaction: %d\n", error);
607 rc = -1;
608 goto out;
609 }
610
611 *signature = (uint8_t*)tmp_sig.data;
612 *signature_size = tmp_sig.data_length;
613 } else {
614 printf("Cryptfs bug: keymaster_init succeded but didn't initialize a device.\n");
615 rc = -1;
616 goto out;
617 }
618
619 out:
620 if (keymaster1_dev)
621 keymaster1_close(keymaster1_dev);
622 if (keymaster0_dev)
623 keymaster0_close(keymaster0_dev);
624
625 return rc;
626}
627#endif //#ifndef TW_CRYPTO_HAVE_KEYMASTERX
Ethan Yonker4eca40d2014-11-11 14:52:28 -0600628
Ethan Yonker4eca40d2014-11-11 14:52:28 -0600629static void ioctl_init(struct dm_ioctl *io, size_t dataSize, const char *name, unsigned flags)
630{
631 memset(io, 0, dataSize);
632 io->data_size = dataSize;
633 io->data_start = sizeof(struct dm_ioctl);
634 io->version[0] = 4;
635 io->version[1] = 0;
636 io->version[2] = 0;
637 io->flags = flags;
638 if (name) {
639 strncpy(io->name, name, sizeof(io->name));
640 }
641}
642
643/**
644 * Gets the default device scrypt parameters for key derivation time tuning.
645 * The parameters should lead to about one second derivation time for the
646 * given device.
647 */
648static void get_device_scrypt_params(struct crypt_mnt_ftr *ftr) {
649 const int default_params[] = SCRYPT_DEFAULTS;
650 int params[] = SCRYPT_DEFAULTS;
651 char paramstr[PROPERTY_VALUE_MAX];
652 char *token;
653 char *saveptr;
654 int i;
655
656 property_get(SCRYPT_PROP, paramstr, "");
657 if (paramstr[0] != '\0') {
658 /*
659 * The token we're looking for should be three integers separated by
660 * colons (e.g., "12:8:1"). Scan the property to make sure it matches.
661 */
662 for (i = 0, token = strtok_r(paramstr, ":", &saveptr);
663 token != NULL && i < 3;
664 i++, token = strtok_r(NULL, ":", &saveptr)) {
665 char *endptr;
666 params[i] = strtol(token, &endptr, 10);
667
668 /*
669 * Check that there was a valid number and it's 8-bit. If not,
670 * break out and the end check will take the default values.
671 */
672 if ((*token == '\0') || (*endptr != '\0') || params[i] < 0 || params[i] > 255) {
673 break;
674 }
675 }
676
677 /*
678 * If there were not enough tokens or a token was malformed (not an
679 * integer), it will end up here and the default parameters can be
680 * taken.
681 */
682 if ((i != 3) || (token != NULL)) {
Ethan Yonkerc798c9c2015-10-09 11:15:26 -0500683 printf("bad scrypt parameters '%s' should be like '12:8:1'; using defaults\n", paramstr);
Ethan Yonker4eca40d2014-11-11 14:52:28 -0600684 memcpy(params, default_params, sizeof(params));
685 }
686 }
687
688 ftr->N_factor = params[0];
689 ftr->r_factor = params[1];
690 ftr->p_factor = params[2];
691}
692
Ethan Yonker4eca40d2014-11-11 14:52:28 -0600693static unsigned int get_blkdev_size(int fd)
694{
nijel82dd66f42017-02-18 21:15:41 -0500695 unsigned long nr_sec;
Ethan Yonker4eca40d2014-11-11 14:52:28 -0600696
697 if ( (ioctl(fd, BLKGETSIZE, &nr_sec)) == -1) {
698 nr_sec = 0;
699 }
700
nijel82dd66f42017-02-18 21:15:41 -0500701 return (unsigned int) nr_sec;
Ethan Yonker4eca40d2014-11-11 14:52:28 -0600702}
703
704static int get_crypt_ftr_info(char **metadata_fname, off64_t *off)
705{
706 static int cached_data = 0;
707 static off64_t cached_off = 0;
708 static char cached_metadata_fname[PROPERTY_VALUE_MAX] = "";
709 int fd;
Ethan Yonker4eca40d2014-11-11 14:52:28 -0600710 unsigned int nr_sec;
711 int rc = -1;
712
713 if (!cached_data) {
Ethan Yonker253368a2014-11-25 15:00:52 -0600714 printf("get_crypt_ftr_info crypto key location: '%s'\n", key_fname);
715 if (!strcmp(key_fname, KEY_IN_FOOTER)) {
Ethan Yonker4eca40d2014-11-11 14:52:28 -0600716 if ( (fd = open(real_blkdev, O_RDWR)) < 0) {
717 printf("Cannot open real block device %s\n", real_blkdev);
718 return -1;
719 }
720
721 if ((nr_sec = get_blkdev_size(fd))) {
722 /* If it's an encrypted Android partition, the last 16 Kbytes contain the
723 * encryption info footer and key, and plenty of bytes to spare for future
724 * growth.
725 */
726 strlcpy(cached_metadata_fname, real_blkdev, sizeof(cached_metadata_fname));
727 cached_off = ((off64_t)nr_sec * 512) - CRYPT_FOOTER_OFFSET;
728 cached_data = 1;
729 } else {
730 printf("Cannot get size of block device %s\n", real_blkdev);
731 }
732 close(fd);
733 } else {
Ethan Yonker253368a2014-11-25 15:00:52 -0600734 strlcpy(cached_metadata_fname, key_fname, sizeof(cached_metadata_fname));
Ethan Yonker4eca40d2014-11-11 14:52:28 -0600735 cached_off = 0;
736 cached_data = 1;
737 }
738 }
739
740 if (cached_data) {
741 if (metadata_fname) {
742 *metadata_fname = cached_metadata_fname;
743 }
744 if (off) {
745 *off = cached_off;
746 }
747 rc = 0;
748 }
749
750 return rc;
751}
752
Ethan Yonker4eca40d2014-11-11 14:52:28 -0600753static int get_crypt_ftr_and_key(struct crypt_mnt_ftr *crypt_ftr)
754{
755 int fd;
Ethan Yonker58f21322018-08-24 11:17:36 -0500756 unsigned int cnt;
Ethan Yonker4eca40d2014-11-11 14:52:28 -0600757 off64_t starting_off;
758 int rc = -1;
759 char *fname = NULL;
760 struct stat statbuf;
761
762 if (get_crypt_ftr_info(&fname, &starting_off)) {
763 printf("Unable to get crypt_ftr_info\n");
764 return -1;
765 }
766 if (fname[0] != '/') {
767 printf("Unexpected value for crypto key location\n");
768 return -1;
769 }
770 if ( (fd = open(fname, O_RDWR)) < 0) {
771 printf("Cannot open footer file %s for get\n", fname);
772 return -1;
773 }
774
775 /* Make sure it's 16 Kbytes in length */
776 fstat(fd, &statbuf);
777 if (S_ISREG(statbuf.st_mode) && (statbuf.st_size != 0x4000)) {
778 printf("footer file %s is not the expected size!\n", fname);
779 goto errout;
780 }
781
782 /* Seek to the start of the crypt footer */
783 if (lseek64(fd, starting_off, SEEK_SET) == -1) {
784 printf("Cannot seek to real block device footer\n");
785 goto errout;
786 }
787
788 if ( (cnt = read(fd, crypt_ftr, sizeof(struct crypt_mnt_ftr))) != sizeof(struct crypt_mnt_ftr)) {
789 printf("Cannot read real block device footer\n");
790 goto errout;
791 }
792
793 if (crypt_ftr->magic != CRYPT_MNT_MAGIC) {
794 printf("Bad magic for real block device %s\n", fname);
795 goto errout;
796 }
797
798 if (crypt_ftr->major_version != CURRENT_MAJOR_VERSION) {
799 printf("Cannot understand major version %d real block device footer; expected %d\n",
800 crypt_ftr->major_version, CURRENT_MAJOR_VERSION);
801 goto errout;
802 }
803
804 if (crypt_ftr->minor_version > CURRENT_MINOR_VERSION) {
805 printf("Warning: crypto footer minor version %d, expected <= %d, continuing...\n",
806 crypt_ftr->minor_version, CURRENT_MINOR_VERSION);
807 }
808
809 /* If this is a verion 1.0 crypt_ftr, make it a 1.1 crypt footer, and update the
810 * copy on disk before returning.
811 */
Ethan Yonker253368a2014-11-25 15:00:52 -0600812 /*if (crypt_ftr->minor_version < CURRENT_MINOR_VERSION) {
Ethan Yonker4eca40d2014-11-11 14:52:28 -0600813 upgrade_crypt_ftr(fd, crypt_ftr, starting_off);
Ethan Yonker253368a2014-11-25 15:00:52 -0600814 }*/
Ethan Yonker4eca40d2014-11-11 14:52:28 -0600815
816 /* Success! */
817 rc = 0;
818
819errout:
820 close(fd);
821 return rc;
822}
823
Ethan Yonkerd3e96ff2016-02-17 13:36:43 -0600824static int hexdigit (char c)
825{
826 if (c >= '0' && c <= '9') return c - '0';
827 c = tolower(c);
828 if (c >= 'a' && c <= 'f') return c - 'a' + 10;
829 return -1;
830}
831
832static unsigned char* convert_hex_ascii_to_key(const char* master_key_ascii,
833 unsigned int* out_keysize)
834{
835 unsigned int i;
836 *out_keysize = 0;
837
838 size_t size = strlen (master_key_ascii);
839 if (size % 2) {
840 printf("Trying to convert ascii string of odd length\n");
841 return NULL;
842 }
843
844 unsigned char* master_key = (unsigned char*) malloc(size / 2);
845 if (master_key == 0) {
846 printf("Cannot allocate\n");
847 return NULL;
848 }
849
850 for (i = 0; i < size; i += 2) {
851 int high_nibble = hexdigit (master_key_ascii[i]);
852 int low_nibble = hexdigit (master_key_ascii[i + 1]);
853
854 if(high_nibble < 0 || low_nibble < 0) {
855 printf("Invalid hex string\n");
856 free (master_key);
857 return NULL;
858 }
859
860 master_key[*out_keysize] = high_nibble * 16 + low_nibble;
861 (*out_keysize)++;
862 }
863
864 return master_key;
865}
866
Ethan Yonker4eca40d2014-11-11 14:52:28 -0600867/* Convert a binary key of specified length into an ascii hex string equivalent,
868 * without the leading 0x and with null termination
869 */
Ethan Yonkerba95ad12016-01-18 15:18:15 -0600870static void convert_key_to_hex_ascii(const unsigned char *master_key,
871 unsigned int keysize, char *master_key_ascii) {
872 unsigned int i, a;
873 unsigned char nibble;
Ethan Yonker4eca40d2014-11-11 14:52:28 -0600874
Ethan Yonkerba95ad12016-01-18 15:18:15 -0600875 for (i=0, a=0; i<keysize; i++, a+=2) {
876 /* For each byte, write out two ascii hex digits */
877 nibble = (master_key[i] >> 4) & 0xf;
878 master_key_ascii[a] = nibble + (nibble > 9 ? 0x37 : 0x30);
Ethan Yonker4eca40d2014-11-11 14:52:28 -0600879
Ethan Yonkerba95ad12016-01-18 15:18:15 -0600880 nibble = master_key[i] & 0xf;
881 master_key_ascii[a+1] = nibble + (nibble > 9 ? 0x37 : 0x30);
882 }
Ethan Yonker4eca40d2014-11-11 14:52:28 -0600883
Ethan Yonkerba95ad12016-01-18 15:18:15 -0600884 /* Add the null termination */
885 master_key_ascii[a] = '\0';
Ethan Yonker4eca40d2014-11-11 14:52:28 -0600886
887}
888
Sultan Qasim Khana7e63a22016-02-12 20:57:15 -0500889static int load_crypto_mapping_table(struct crypt_mnt_ftr *crypt_ftr, const unsigned char *master_key,
890 const char *real_blk_name, const char *name, int fd,
Ethan Yonker4eca40d2014-11-11 14:52:28 -0600891 char *extra_params)
892{
893 char buffer[DM_CRYPT_BUF_SIZE];
894 struct dm_ioctl *io;
895 struct dm_target_spec *tgt;
896 char *crypt_params;
897 char master_key_ascii[129]; /* Large enough to hold 512 bit key and null */
898 int i;
899
900 io = (struct dm_ioctl *) buffer;
901
902 /* Load the mapping table for this device */
903 tgt = (struct dm_target_spec *) &buffer[sizeof(struct dm_ioctl)];
904
905 ioctl_init(io, DM_CRYPT_BUF_SIZE, name, 0);
906 io->target_count = 1;
907 tgt->status = 0;
908 tgt->sector_start = 0;
909 tgt->length = crypt_ftr->fs_size;
Captain Throwback35df6382016-05-17 11:25:52 -0400910 crypt_params = buffer + sizeof(struct dm_ioctl) + sizeof(struct dm_target_spec);
911
Dees Troyc657cc02015-01-16 22:48:47 +0000912#ifdef CONFIG_HW_DISK_ENCRYPTION
Ethan Yonkerba95ad12016-01-18 15:18:15 -0600913 if(is_hw_disk_encryption((char*)crypt_ftr->crypto_type_name)) {
914 strlcpy(tgt->target_type, "req-crypt",DM_MAX_TYPE_NAME);
915 if (is_ice_enabled())
916 convert_key_to_hex_ascii(master_key, sizeof(int), master_key_ascii);
917 else
918 convert_key_to_hex_ascii(master_key, crypt_ftr->keysize, master_key_ascii);
919 }
920 else {
921 convert_key_to_hex_ascii(master_key, crypt_ftr->keysize, master_key_ascii);
922 strlcpy(tgt->target_type, "crypt", DM_MAX_TYPE_NAME);
923 }
Dees Troyc657cc02015-01-16 22:48:47 +0000924#else
Ethan Yonkerba95ad12016-01-18 15:18:15 -0600925 convert_key_to_hex_ascii(master_key, crypt_ftr->keysize, master_key_ascii);
926 strlcpy(tgt->target_type, "crypt", DM_MAX_TYPE_NAME);
Dees Troyc657cc02015-01-16 22:48:47 +0000927#endif
Ethan Yonker4eca40d2014-11-11 14:52:28 -0600928
Ethan Yonker4eca40d2014-11-11 14:52:28 -0600929 sprintf(crypt_params, "%s %s 0 %s 0 %s", crypt_ftr->crypto_type_name,
930 master_key_ascii, real_blk_name, extra_params);
Dees Troyc657cc02015-01-16 22:48:47 +0000931
932 printf("%s: target_type = %s\n", __func__, tgt->target_type);
933 printf("%s: real_blk_name = %s, extra_params = %s\n", __func__, real_blk_name, extra_params);
934
Ethan Yonker4eca40d2014-11-11 14:52:28 -0600935 crypt_params += strlen(crypt_params) + 1;
936 crypt_params = (char *) (((unsigned long)crypt_params + 7) & ~8); /* Align to an 8 byte boundary */
937 tgt->next = crypt_params - buffer;
938
939 for (i = 0; i < TABLE_LOAD_RETRIES; i++) {
940 if (! ioctl(fd, DM_TABLE_LOAD, io)) {
941 break;
942 }
Ethan Yonker66a19492015-12-10 10:19:45 -0600943 printf("%i\n", errno);
Ethan Yonker4eca40d2014-11-11 14:52:28 -0600944 usleep(500000);
945 }
946
947 if (i == TABLE_LOAD_RETRIES) {
948 /* We failed to load the table, return an error */
949 return -1;
950 } else {
951 return i + 1;
952 }
953}
954
955
956static int get_dm_crypt_version(int fd, const char *name, int *version)
957{
958 char buffer[DM_CRYPT_BUF_SIZE];
959 struct dm_ioctl *io;
960 struct dm_target_versions *v;
Ethan Yonker4eca40d2014-11-11 14:52:28 -0600961
962 io = (struct dm_ioctl *) buffer;
963
964 ioctl_init(io, DM_CRYPT_BUF_SIZE, name, 0);
965
966 if (ioctl(fd, DM_LIST_VERSIONS, io)) {
967 return -1;
968 }
969
970 /* Iterate over the returned versions, looking for name of "crypt".
971 * When found, get and return the version.
972 */
973 v = (struct dm_target_versions *) &buffer[sizeof(struct dm_ioctl)];
974 while (v->next) {
Dees Troyc657cc02015-01-16 22:48:47 +0000975#ifdef CONFIG_HW_DISK_ENCRYPTION
Ethan Yonker58f21322018-08-24 11:17:36 -0500976 int flag;
Dees Troyc657cc02015-01-16 22:48:47 +0000977 if (is_hw_fde_enabled()) {
978 flag = (!strcmp(v->name, "crypt") || !strcmp(v->name, "req-crypt"));
979 } else {
980 flag = (!strcmp(v->name, "crypt"));
981 }
982 printf("get_dm_crypt_version flag: %i, name: '%s'\n", flag, v->name);
983 if (flag) {
984#else
Ethan Yonker4eca40d2014-11-11 14:52:28 -0600985 if (! strcmp(v->name, "crypt")) {
Dees Troyc657cc02015-01-16 22:48:47 +0000986#endif
Ethan Yonker4eca40d2014-11-11 14:52:28 -0600987 /* We found the crypt driver, return the version, and get out */
988 version[0] = v->version[0];
989 version[1] = v->version[1];
990 version[2] = v->version[2];
991 return 0;
992 }
993 v = (struct dm_target_versions *)(((char *)v) + v->next);
994 }
995
996 return -1;
997}
998
Sultan Qasim Khana7e63a22016-02-12 20:57:15 -0500999static int create_crypto_blk_dev(struct crypt_mnt_ftr *crypt_ftr, const unsigned char *master_key,
1000 const char *real_blk_name, char *crypto_blk_name, const char *name)
Ethan Yonker4eca40d2014-11-11 14:52:28 -06001001{
1002 char buffer[DM_CRYPT_BUF_SIZE];
Ethan Yonker4eca40d2014-11-11 14:52:28 -06001003 struct dm_ioctl *io;
Ethan Yonker4eca40d2014-11-11 14:52:28 -06001004 unsigned int minor;
Dees Troyc657cc02015-01-16 22:48:47 +00001005 int fd=0;
Ethan Yonker4eca40d2014-11-11 14:52:28 -06001006 int retval = -1;
1007 int version[3];
1008 char *extra_params;
1009 int load_count;
Dees Troyc657cc02015-01-16 22:48:47 +00001010#ifdef CONFIG_HW_DISK_ENCRYPTION
1011 char encrypted_state[PROPERTY_VALUE_MAX] = {0};
1012 char progress[PROPERTY_VALUE_MAX] = {0};
1013#endif
Ethan Yonker4eca40d2014-11-11 14:52:28 -06001014
1015 if ((fd = open("/dev/device-mapper", O_RDWR)) < 0 ) {
1016 printf("Cannot open device-mapper\n");
1017 goto errout;
1018 }
1019
1020 io = (struct dm_ioctl *) buffer;
1021
1022 ioctl_init(io, DM_CRYPT_BUF_SIZE, name, 0);
1023 if (ioctl(fd, DM_DEV_CREATE, io)) {
Ethan Yonker66a19492015-12-10 10:19:45 -06001024 printf("Cannot create dm-crypt device %i\n", errno);
Ethan Yonker4eca40d2014-11-11 14:52:28 -06001025 goto errout;
1026 }
1027
1028 /* Get the device status, in particular, the name of it's device file */
1029 ioctl_init(io, DM_CRYPT_BUF_SIZE, name, 0);
1030 if (ioctl(fd, DM_DEV_STATUS, io)) {
1031 printf("Cannot retrieve dm-crypt device status\n");
1032 goto errout;
1033 }
1034 minor = (io->dev & 0xff) | ((io->dev >> 12) & 0xfff00);
1035 snprintf(crypto_blk_name, MAXPATHLEN, "/dev/block/dm-%u", minor);
1036
Dees Troyc657cc02015-01-16 22:48:47 +00001037#ifdef CONFIG_HW_DISK_ENCRYPTION
Ethan Yonkerba95ad12016-01-18 15:18:15 -06001038 if(is_hw_disk_encryption((char*)crypt_ftr->crypto_type_name)) {
1039 /* Set fde_enabled if either FDE completed or in-progress */
1040 property_get("ro.crypto.state", encrypted_state, ""); /* FDE completed */
1041 property_get("vold.encrypt_progress", progress, ""); /* FDE in progress */
1042 if (!strcmp(encrypted_state, "encrypted") || strcmp(progress, "")) {
1043 if (is_ice_enabled())
1044 extra_params = "fde_enabled ice";
1045 else
1046 extra_params = "fde_enabled";
1047 } else
1048 extra_params = "fde_disabled";
Dees Troyc657cc02015-01-16 22:48:47 +00001049 } else {
Ethan Yonkerba95ad12016-01-18 15:18:15 -06001050 extra_params = "";
1051 if (! get_dm_crypt_version(fd, name, version)) {
1052 /* Support for allow_discards was added in version 1.11.0 */
1053 if ((version[0] >= 2) ||
1054 ((version[0] == 1) && (version[1] >= 11))) {
1055 extra_params = "1 allow_discards";
1056 printf("Enabling support for allow_discards in dmcrypt.\n");
Dees Troyc657cc02015-01-16 22:48:47 +00001057 }
Ethan Yonkerba95ad12016-01-18 15:18:15 -06001058 }
Dees Troyc657cc02015-01-16 22:48:47 +00001059 }
1060#else
Ethan Yonker4eca40d2014-11-11 14:52:28 -06001061 extra_params = "";
1062 if (! get_dm_crypt_version(fd, name, version)) {
1063 /* Support for allow_discards was added in version 1.11.0 */
1064 if ((version[0] >= 2) ||
1065 ((version[0] == 1) && (version[1] >= 11))) {
1066 extra_params = "1 allow_discards";
1067 printf("Enabling support for allow_discards in dmcrypt.\n");
1068 }
1069 }
Dees Troyc657cc02015-01-16 22:48:47 +00001070#endif
Ethan Yonker4eca40d2014-11-11 14:52:28 -06001071
1072 load_count = load_crypto_mapping_table(crypt_ftr, master_key, real_blk_name, name,
1073 fd, extra_params);
1074 if (load_count < 0) {
1075 printf("Cannot load dm-crypt mapping table.\n");
nkk7150730032017-04-05 22:14:22 +03001076
1077 // Remove the dm-crypt device, otherwise it cannot be used later on by other
1078 // processes (eg vold_decrypt) or further testing/debugging in recovery
1079 ioctl_init(io, DM_CRYPT_BUF_SIZE, name, 0);
1080 if (ioctl(fd, DM_DEV_REMOVE, io)) {
1081 printf("Cannot remove dm-crypt device %i\n", errno);
1082 }
Ethan Yonker4eca40d2014-11-11 14:52:28 -06001083 goto errout;
1084 } else if (load_count > 1) {
1085 printf("Took %d tries to load dmcrypt table.\n", load_count);
1086 }
1087
1088 /* Resume this device to activate it */
1089 ioctl_init(io, DM_CRYPT_BUF_SIZE, name, 0);
1090
1091 if (ioctl(fd, DM_DEV_SUSPEND, io)) {
1092 printf("Cannot resume the dm-crypt device\n");
nkk7150730032017-04-05 22:14:22 +03001093
1094 // Remove the dm-crypt device, otherwise it cannot be used later on by other
1095 // processes (eg vold_decrypt) or further testing/debugging in recovery
1096 ioctl_init(io, DM_CRYPT_BUF_SIZE, name, 0);
1097 if (ioctl(fd, DM_DEV_REMOVE, io)) {
1098 printf("Cannot remove dm-crypt device %i\n", errno);
1099 }
Ethan Yonker4eca40d2014-11-11 14:52:28 -06001100 goto errout;
1101 }
1102
1103 /* We made it here with no errors. Woot! */
1104 retval = 0;
1105
1106errout:
1107 close(fd); /* If fd is <0 from a failed open call, it's safe to just ignore the close error */
1108
1109 return retval;
1110}
1111
Ethan Yonkerd79d9bc2014-12-20 15:38:29 -06001112int delete_crypto_blk_dev(char *name)
Ethan Yonker4eca40d2014-11-11 14:52:28 -06001113{
1114 int fd;
1115 char buffer[DM_CRYPT_BUF_SIZE];
1116 struct dm_ioctl *io;
1117 int retval = -1;
1118
1119 if ((fd = open("/dev/device-mapper", O_RDWR)) < 0 ) {
1120 printf("Cannot open device-mapper\n");
1121 goto errout;
1122 }
1123
1124 io = (struct dm_ioctl *) buffer;
1125
1126 ioctl_init(io, DM_CRYPT_BUF_SIZE, name, 0);
1127 if (ioctl(fd, DM_DEV_REMOVE, io)) {
1128 printf("Cannot remove dm-crypt device\n");
1129 goto errout;
1130 }
1131
1132 /* We made it here with no errors. Woot! */
1133 retval = 0;
1134
1135errout:
1136 close(fd); /* If fd is <0 from a failed open call, it's safe to just ignore the close error */
1137
1138 return retval;
1139
1140}
1141
1142static int pbkdf2(const char *passwd, const unsigned char *salt,
1143 unsigned char *ikey, void *params UNUSED)
1144{
Ethan Yonkerc798c9c2015-10-09 11:15:26 -05001145 printf("Using pbkdf2 for cryptfs KDF\n");
Ethan Yonker4eca40d2014-11-11 14:52:28 -06001146
1147 /* Turn the password into a key and IV that can decrypt the master key */
Ethan Yonkerd3e96ff2016-02-17 13:36:43 -06001148 unsigned int keysize;
1149 char* master_key = (char*)convert_hex_ascii_to_key(passwd, &keysize);
1150 if (!master_key) return -1;
1151 PKCS5_PBKDF2_HMAC_SHA1(master_key, keysize, salt, SALT_LEN,
Ethan Yonker4eca40d2014-11-11 14:52:28 -06001152 HASH_COUNT, KEY_LEN_BYTES+IV_LEN_BYTES, ikey);
1153
Ethan Yonkerd3e96ff2016-02-17 13:36:43 -06001154 memset(master_key, 0, keysize);
1155 free (master_key);
Ethan Yonker4eca40d2014-11-11 14:52:28 -06001156 return 0;
1157}
1158
1159static int scrypt(const char *passwd, const unsigned char *salt,
1160 unsigned char *ikey, void *params)
1161{
1162 printf("Using scrypt for cryptfs KDF\n");
1163
1164 struct crypt_mnt_ftr *ftr = (struct crypt_mnt_ftr *) params;
1165
1166 int N = 1 << ftr->N_factor;
1167 int r = 1 << ftr->r_factor;
1168 int p = 1 << ftr->p_factor;
1169
1170 /* Turn the password into a key and IV that can decrypt the master key */
Ethan Yonkerd3e96ff2016-02-17 13:36:43 -06001171 unsigned int keysize;
1172 unsigned char* master_key = convert_hex_ascii_to_key(passwd, &keysize);
1173 if (!master_key) return -1;
1174 crypto_scrypt(master_key, keysize, salt, SALT_LEN, N, r, p, ikey,
1175 KEY_LEN_BYTES + IV_LEN_BYTES);
Ethan Yonker4eca40d2014-11-11 14:52:28 -06001176
Ethan Yonkerd3e96ff2016-02-17 13:36:43 -06001177 memset(master_key, 0, keysize);
1178 free (master_key);
Ethan Yonker4eca40d2014-11-11 14:52:28 -06001179 return 0;
1180}
1181
1182static int scrypt_keymaster(const char *passwd, const unsigned char *salt,
1183 unsigned char *ikey, void *params)
1184{
1185 printf("Using scrypt with keymaster for cryptfs KDF\n");
1186
1187 int rc;
1188 unsigned int key_size;
1189 size_t signature_size;
1190 unsigned char* signature;
1191 struct crypt_mnt_ftr *ftr = (struct crypt_mnt_ftr *) params;
1192
1193 int N = 1 << ftr->N_factor;
1194 int r = 1 << ftr->r_factor;
1195 int p = 1 << ftr->p_factor;
1196
Ethan Yonkerd3e96ff2016-02-17 13:36:43 -06001197 unsigned char* master_key = convert_hex_ascii_to_key(passwd, &key_size);
1198 if (!master_key) {
Ethan Yonker9f1f2f72016-04-21 11:54:00 -05001199 printf("Failed to convert passwd from hex, using passwd instead\n");
Ethan Yonker58f21322018-08-24 11:17:36 -05001200 master_key = (unsigned char*)strdup(passwd);
Ethan Yonkerd3e96ff2016-02-17 13:36:43 -06001201 }
1202
1203 rc = crypto_scrypt(master_key, key_size, salt, SALT_LEN,
Ethan Yonker4eca40d2014-11-11 14:52:28 -06001204 N, r, p, ikey, KEY_LEN_BYTES + IV_LEN_BYTES);
Ethan Yonkerd3e96ff2016-02-17 13:36:43 -06001205 memset(master_key, 0, key_size);
1206 free(master_key);
Ethan Yonker4eca40d2014-11-11 14:52:28 -06001207
1208 if (rc) {
Ethan Yonkercceebb82014-11-18 10:17:59 -06001209 printf("scrypt failed\n");
Ethan Yonker4eca40d2014-11-11 14:52:28 -06001210 return -1;
1211 }
1212
1213 if (keymaster_sign_object(ftr, ikey, KEY_LEN_BYTES + IV_LEN_BYTES,
1214 &signature, &signature_size)) {
Ethan Yonkercceebb82014-11-18 10:17:59 -06001215 printf("Signing failed\n");
Ethan Yonker4eca40d2014-11-11 14:52:28 -06001216 return -1;
1217 }
1218
1219 rc = crypto_scrypt(signature, signature_size, salt, SALT_LEN,
1220 N, r, p, ikey, KEY_LEN_BYTES + IV_LEN_BYTES);
1221 free(signature);
1222
1223 if (rc) {
Ethan Yonkercceebb82014-11-18 10:17:59 -06001224 printf("scrypt failed\n");
Ethan Yonker4eca40d2014-11-11 14:52:28 -06001225 return -1;
1226 }
1227
1228 return 0;
1229}
1230
Ethan Yonker4eca40d2014-11-11 14:52:28 -06001231static int decrypt_master_key_aux(char *passwd, unsigned char *salt,
1232 unsigned char *encrypted_master_key,
1233 unsigned char *decrypted_master_key,
1234 kdf_func kdf, void *kdf_params,
1235 unsigned char** intermediate_key,
1236 size_t* intermediate_key_size)
1237{
1238 unsigned char ikey[32+32] = { 0 }; /* Big enough to hold a 256 bit key and 256 bit IV */
1239 EVP_CIPHER_CTX d_ctx;
1240 int decrypted_len, final_len;
1241
1242 /* Turn the password into an intermediate key and IV that can decrypt the
1243 master key */
1244 if (kdf(passwd, salt, ikey, kdf_params)) {
Ethan Yonkerc798c9c2015-10-09 11:15:26 -05001245 printf("kdf failed\n");
Ethan Yonker4eca40d2014-11-11 14:52:28 -06001246 return -1;
1247 }
1248
1249 /* Initialize the decryption engine */
1250 if (! EVP_DecryptInit(&d_ctx, EVP_aes_128_cbc(), ikey, ikey+KEY_LEN_BYTES)) {
1251 return -1;
1252 }
1253 EVP_CIPHER_CTX_set_padding(&d_ctx, 0); /* Turn off padding as our data is block aligned */
1254 /* Decrypt the master key */
1255 if (! EVP_DecryptUpdate(&d_ctx, decrypted_master_key, &decrypted_len,
1256 encrypted_master_key, KEY_LEN_BYTES)) {
1257 return -1;
1258 }
Ethan Yonkerc798c9c2015-10-09 11:15:26 -05001259#ifndef TW_CRYPTO_HAVE_KEYMASTERX
Ethan Yonker4eca40d2014-11-11 14:52:28 -06001260 if (! EVP_DecryptFinal(&d_ctx, decrypted_master_key + decrypted_len, &final_len)) {
Ethan Yonkerc798c9c2015-10-09 11:15:26 -05001261#else
1262 if (! EVP_DecryptFinal_ex(&d_ctx, decrypted_master_key + decrypted_len, &final_len)) {
1263#endif
Ethan Yonker4eca40d2014-11-11 14:52:28 -06001264 return -1;
1265 }
1266
1267 if (decrypted_len + final_len != KEY_LEN_BYTES) {
1268 return -1;
1269 }
1270
1271 /* Copy intermediate key if needed by params */
1272 if (intermediate_key && intermediate_key_size) {
1273 *intermediate_key = (unsigned char*) malloc(KEY_LEN_BYTES);
1274 if (intermediate_key) {
1275 memcpy(*intermediate_key, ikey, KEY_LEN_BYTES);
1276 *intermediate_key_size = KEY_LEN_BYTES;
1277 }
1278 }
1279
1280 return 0;
1281}
1282
1283static void get_kdf_func(struct crypt_mnt_ftr *ftr, kdf_func *kdf, void** kdf_params)
1284{
1285 if (ftr->kdf_type == KDF_SCRYPT_KEYMASTER_UNPADDED ||
1286 ftr->kdf_type == KDF_SCRYPT_KEYMASTER_BADLY_PADDED ||
1287 ftr->kdf_type == KDF_SCRYPT_KEYMASTER) {
1288 *kdf = scrypt_keymaster;
1289 *kdf_params = ftr;
1290 } else if (ftr->kdf_type == KDF_SCRYPT) {
1291 *kdf = scrypt;
1292 *kdf_params = ftr;
1293 } else {
1294 *kdf = pbkdf2;
1295 *kdf_params = NULL;
1296 }
1297}
1298
1299static int decrypt_master_key(char *passwd, unsigned char *decrypted_master_key,
1300 struct crypt_mnt_ftr *crypt_ftr,
1301 unsigned char** intermediate_key,
1302 size_t* intermediate_key_size)
1303{
1304 kdf_func kdf;
1305 void *kdf_params;
1306 int ret;
1307
1308 get_kdf_func(crypt_ftr, &kdf, &kdf_params);
1309 ret = decrypt_master_key_aux(passwd, crypt_ftr->salt, crypt_ftr->master_key,
1310 decrypted_master_key, kdf, kdf_params,
1311 intermediate_key, intermediate_key_size);
1312 if (ret != 0) {
Ethan Yonkerc798c9c2015-10-09 11:15:26 -05001313 printf("failure decrypting master key\n");
Ethan Yonker4eca40d2014-11-11 14:52:28 -06001314 }
1315
1316 return ret;
1317}
1318
James Christopher Adduonoc51bd352017-01-21 00:17:30 -05001319static int try_mount_multiple_fs(const char *crypto_blkdev,
1320 const char *mount_point,
1321 const char *file_system)
1322{
1323 if (!mount(crypto_blkdev, mount_point, file_system, 0, NULL))
1324 return 0;
1325 if (strcmp(file_system, "ext4") &&
1326 !mount(crypto_blkdev, mount_point, "ext4", 0, NULL))
1327 return 0;
1328 if (strcmp(file_system, "f2fs") &&
1329 !mount(crypto_blkdev, mount_point, "f2fs", 0, NULL))
1330 return 0;
1331 return 1;
1332}
1333
Ethan Yonker4eca40d2014-11-11 14:52:28 -06001334static int test_mount_encrypted_fs(struct crypt_mnt_ftr* crypt_ftr,
1335 char *passwd, char *mount_point, char *label)
1336{
1337 /* Allocate enough space for a 256 bit key, but we may use less */
1338 unsigned char decrypted_master_key[32];
1339 char crypto_blkdev[MAXPATHLEN];
Ethan Yonker4eca40d2014-11-11 14:52:28 -06001340 char tmp_mount_point[64];
Dees Troyc657cc02015-01-16 22:48:47 +00001341 int rc = 0;
Ethan Yonker4eca40d2014-11-11 14:52:28 -06001342 unsigned char* intermediate_key = 0;
1343 size_t intermediate_key_size = 0;
1344
1345 printf("crypt_ftr->fs_size = %lld\n", crypt_ftr->fs_size);
Ethan Yonker4eca40d2014-11-11 14:52:28 -06001346
1347 if (! (crypt_ftr->flags & CRYPT_MNT_KEY_UNENCRYPTED) ) {
1348 if (decrypt_master_key(passwd, decrypted_master_key, crypt_ftr,
1349 &intermediate_key, &intermediate_key_size)) {
1350 printf("Failed to decrypt master key\n");
1351 rc = -1;
1352 goto errout;
1353 }
1354 }
1355
Dees Troyc657cc02015-01-16 22:48:47 +00001356#ifdef CONFIG_HW_DISK_ENCRYPTION
Ethan Yonkerba95ad12016-01-18 15:18:15 -06001357 int key_index = 0;
1358 if(is_hw_disk_encryption((char*)crypt_ftr->crypto_type_name)) {
Sultan Qasim Khana7e63a22016-02-12 20:57:15 -05001359 key_index = verify_hw_fde_passwd(passwd, crypt_ftr);
1360
Ethan Yonkerba95ad12016-01-18 15:18:15 -06001361 if (key_index < 0) {
Sultan Qasim Khana7e63a22016-02-12 20:57:15 -05001362 rc = 1;
Ethan Yonkerba95ad12016-01-18 15:18:15 -06001363 goto errout;
1364 }
1365 else {
1366 if (is_ice_enabled()) {
1367 if (create_crypto_blk_dev(crypt_ftr, (unsigned char*)&key_index,
1368 real_blkdev, crypto_blkdev, label)) {
1369 printf("Error creating decrypted block device");
1370 rc = -1;
1371 goto errout;
1372 }
1373 } else {
1374 if (create_crypto_blk_dev(crypt_ftr, decrypted_master_key,
1375 real_blkdev, crypto_blkdev, label)) {
1376 printf("Error creating decrypted block device");
1377 rc = -1;
1378 goto errout;
1379 }
Dees Troyc657cc02015-01-16 22:48:47 +00001380 }
1381 }
Ethan Yonkerba95ad12016-01-18 15:18:15 -06001382 } else {
1383 /* in case HW FDE is delivered through OTA and device is already encrypted
1384 * using SW FDE, we should let user continue using SW FDE until userdata is
1385 * wiped.
1386 */
1387 if (create_crypto_blk_dev(crypt_ftr, decrypted_master_key,
1388 real_blkdev, crypto_blkdev, label)) {
1389 printf("Error creating decrypted block device");
1390 rc = -1;
1391 goto errout;
1392 }
Dees Troyc657cc02015-01-16 22:48:47 +00001393 }
Ethan Yonkerba95ad12016-01-18 15:18:15 -06001394#else
Ethan Yonker4eca40d2014-11-11 14:52:28 -06001395 // Create crypto block device - all (non fatal) code paths
1396 // need it
1397 if (create_crypto_blk_dev(crypt_ftr, decrypted_master_key,
1398 real_blkdev, crypto_blkdev, label)) {
1399 printf("Error creating decrypted block device\n");
1400 rc = -1;
1401 goto errout;
1402 }
Ethan Yonkerba95ad12016-01-18 15:18:15 -06001403#endif
Ethan Yonker4eca40d2014-11-11 14:52:28 -06001404
1405 /* Work out if the problem is the password or the data */
1406 unsigned char scrypted_intermediate_key[sizeof(crypt_ftr->
1407 scrypted_intermediate_key)];
1408 int N = 1 << crypt_ftr->N_factor;
1409 int r = 1 << crypt_ftr->r_factor;
1410 int p = 1 << crypt_ftr->p_factor;
1411
1412 rc = crypto_scrypt(intermediate_key, intermediate_key_size,
1413 crypt_ftr->salt, sizeof(crypt_ftr->salt),
1414 N, r, p, scrypted_intermediate_key,
1415 sizeof(scrypted_intermediate_key));
1416
1417 // Does the key match the crypto footer?
1418 if (rc == 0 && memcmp(scrypted_intermediate_key,
1419 crypt_ftr->scrypted_intermediate_key,
1420 sizeof(scrypted_intermediate_key)) == 0) {
1421 printf("Password matches\n");
1422 rc = 0;
1423 } else {
1424 /* Try mounting the file system anyway, just in case the problem's with
1425 * the footer, not the key. */
1426 sprintf(tmp_mount_point, "%s/tmp_mnt", mount_point);
1427 mkdir(tmp_mount_point, 0755);
James Christopher Adduonoc51bd352017-01-21 00:17:30 -05001428 if (try_mount_multiple_fs(crypto_blkdev, tmp_mount_point, file_system)) {
Ethan Yonker4eca40d2014-11-11 14:52:28 -06001429 printf("Error temp mounting decrypted block device '%s'\n", crypto_blkdev);
1430 delete_crypto_blk_dev(label);
Sultan Qasim Khana7e63a22016-02-12 20:57:15 -05001431 rc = 1;
Ethan Yonker4eca40d2014-11-11 14:52:28 -06001432 } else {
1433 /* Success! */
1434 printf("Password did not match but decrypted drive mounted - continue\n");
1435 umount(tmp_mount_point);
1436 rc = 0;
1437 }
1438 }
1439
1440 if (rc == 0) {
Sultan Qasim Khana7e63a22016-02-12 20:57:15 -05001441 // Don't increment the failed attempt counter as it doesn't
1442 // make sense to do so in TWRP
Ethan Yonker4eca40d2014-11-11 14:52:28 -06001443
1444 /* Save the name of the crypto block device
1445 * so we can mount it when restarting the framework. */
1446 property_set("ro.crypto.fs_crypto_blkdev", crypto_blkdev);
1447
Sultan Qasim Khana7e63a22016-02-12 20:57:15 -05001448 // TWRP shouldn't change the stored key
Ethan Yonker4eca40d2014-11-11 14:52:28 -06001449 }
1450
1451 errout:
1452 if (intermediate_key) {
1453 memset(intermediate_key, 0, intermediate_key_size);
1454 free(intermediate_key);
1455 }
1456 return rc;
1457}
1458
Ethan Yonker4eca40d2014-11-11 14:52:28 -06001459int check_unmounted_and_get_ftr(struct crypt_mnt_ftr* crypt_ftr)
1460{
1461 char encrypted_state[PROPERTY_VALUE_MAX];
1462 property_get("ro.crypto.state", encrypted_state, "");
1463 if ( master_key_saved || strcmp(encrypted_state, "encrypted") ) {
1464 printf("encrypted fs already validated or not running with encryption,"
Ethan Yonkercceebb82014-11-18 10:17:59 -06001465 " aborting\n");
1466 //return -1;
Ethan Yonker4eca40d2014-11-11 14:52:28 -06001467 }
1468
1469 if (get_crypt_ftr_and_key(crypt_ftr)) {
Ethan Yonkercceebb82014-11-18 10:17:59 -06001470 printf("Error getting crypt footer and key\n");
Ethan Yonker4eca40d2014-11-11 14:52:28 -06001471 return -1;
1472 }
1473
1474 return 0;
1475}
1476
Ethan Yonker253368a2014-11-25 15:00:52 -06001477int cryptfs_check_footer()
Ethan Yonker4eca40d2014-11-11 14:52:28 -06001478{
1479 int rc = -1;
Ethan Yonker4eca40d2014-11-11 14:52:28 -06001480 struct crypt_mnt_ftr crypt_ftr;
1481
Ethan Yonker4eca40d2014-11-11 14:52:28 -06001482 rc = get_crypt_ftr_and_key(&crypt_ftr);
1483
1484 return rc;
1485}
1486
1487int cryptfs_check_passwd(char *passwd)
1488{
1489 struct crypt_mnt_ftr crypt_ftr;
1490 int rc;
Sultan Qasim Khana7e63a22016-02-12 20:57:15 -05001491
1492 if (!passwd) {
1493 printf("cryptfs_check_passwd: passwd is NULL!\n");
1494 return -1;
1495 }
Ethan Yonker4eca40d2014-11-11 14:52:28 -06001496
1497 rc = check_unmounted_and_get_ftr(&crypt_ftr);
1498 if (rc)
1499 return rc;
1500
Sultan Qasim Khana7e63a22016-02-12 20:57:15 -05001501 rc = test_mount_encrypted_fs(&crypt_ftr, passwd,
1502 DATA_MNT_POINT, "userdata");
Ethan Yonker4eca40d2014-11-11 14:52:28 -06001503
Sultan Qasim Khana7e63a22016-02-12 20:57:15 -05001504 // try falling back to Lollipop hex passwords
1505 if (rc) {
1506 int hex_pass_len = strlen(passwd) * 2 + 1;
1507 char *hex_passwd = (char *)malloc(hex_pass_len);
Dees Troyc657cc02015-01-16 22:48:47 +00001508 if (hex_passwd) {
Sultan Qasim Khana7e63a22016-02-12 20:57:15 -05001509 convert_key_to_hex_ascii((unsigned char *)passwd,
1510 strlen(passwd), hex_passwd);
Ethan Yonker4eca40d2014-11-11 14:52:28 -06001511 rc = test_mount_encrypted_fs(&crypt_ftr, hex_passwd,
Sultan Qasim Khana7e63a22016-02-12 20:57:15 -05001512 DATA_MNT_POINT, "userdata");
1513 memset(hex_passwd, 0, hex_pass_len);
1514 free(hex_passwd);
Dees Troyc657cc02015-01-16 22:48:47 +00001515 }
Ethan Yonker4eca40d2014-11-11 14:52:28 -06001516 }
1517
1518 return rc;
1519}
1520
Ethan Yonker4eca40d2014-11-11 14:52:28 -06001521/* Returns type of the password, default, pattern, pin or password.
1522 */
1523int cryptfs_get_password_type(void)
1524{
1525 struct crypt_mnt_ftr crypt_ftr;
Ethan Yonker4eca40d2014-11-11 14:52:28 -06001526
1527 if (get_crypt_ftr_and_key(&crypt_ftr)) {
1528 printf("Error getting crypt footer and key\n");
1529 return -1;
1530 }
1531
1532 if (crypt_ftr.flags & CRYPT_INCONSISTENT_STATE) {
1533 return -1;
1534 }
1535
1536 return crypt_ftr.crypt_type;
1537}
Ethan Yonker66a19492015-12-10 10:19:45 -06001538
1539/*
1540 * Called by vold when it's asked to mount an encrypted external
1541 * storage volume. The incoming partition has no crypto header/footer,
1542 * as any metadata is been stored in a separate, small partition.
1543 *
1544 * out_crypto_blkdev must be MAXPATHLEN.
1545 */
1546int cryptfs_setup_ext_volume(const char* label, const char* real_blkdev,
1547 const unsigned char* key, int keysize, char* out_crypto_blkdev) {
1548 int fd = open(real_blkdev, O_RDONLY|O_CLOEXEC);
1549 if (fd == -1) {
1550 printf("Failed to open %s: %s", real_blkdev, strerror(errno));
1551 return -1;
1552 }
1553
1554 unsigned long nr_sec = 0;
1555 nr_sec = get_blkdev_size(fd);
1556 close(fd);
1557
1558 if (nr_sec == 0) {
1559 printf("Failed to get size of %s: %s", real_blkdev, strerror(errno));
1560 return -1;
1561 }
1562
1563 struct crypt_mnt_ftr ext_crypt_ftr;
1564 memset(&ext_crypt_ftr, 0, sizeof(ext_crypt_ftr));
1565 ext_crypt_ftr.fs_size = nr_sec;
1566 ext_crypt_ftr.keysize = keysize;
1567 strcpy((char*) ext_crypt_ftr.crypto_type_name, "aes-cbc-essiv:sha256");
1568
1569 return create_crypto_blk_dev(&ext_crypt_ftr, key, real_blkdev,
1570 out_crypto_blkdev, label);
1571}
1572
1573/*
1574 * Called by vold when it's asked to unmount an encrypted external
1575 * storage volume.
1576 */
1577int cryptfs_revert_ext_volume(const char* label) {
1578 return delete_crypto_blk_dev((char*) label);
1579}