blob: 5b8757c52d14fe2bfe9f4976bc2878a49db0685a [file] [log] [blame]
Ethan Yonker98661c12018-10-17 08:39:28 -05001/*
2 * Copyright (C) 2010 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17/* TO DO:
18 * 1. Perhaps keep several copies of the encrypted key, in case something
19 * goes horribly wrong?
20 *
21 */
22
23#include <sys/types.h>
24#include <sys/wait.h>
25#include <sys/stat.h>
26#include <ctype.h>
27#include <fcntl.h>
28#include <inttypes.h>
29#include <unistd.h>
30#include <stdio.h>
31#include <sys/ioctl.h>
32#include <linux/dm-ioctl.h>
33#include <libgen.h>
34#include <stdlib.h>
35#include <sys/param.h>
36#include <string.h>
37#include <sys/mount.h>
38#include <openssl/evp.h>
39#include <openssl/sha.h>
40#include <errno.h>
41//#include <ext4_utils/ext4_crypt.h>
42//#include <ext4_utils/ext4_utils.h>
43#include <linux/kdev_t.h>
44//#include <fs_mgr.h>
45#include <time.h>
46#include <math.h>
47//#include <selinux/selinux.h>
48#include "cryptfs.h"
49//#include "secontext.h"
50#define LOG_TAG "Cryptfs"
51//#include "cutils/log.h"
52#include "cutils/properties.h"
53//#include "cutils/android_reboot.h"
54//#include "hardware_legacy/power.h"
55//#include <logwrap/logwrap.h>
56//#include "ScryptParameters.h"
57//#include "VolumeManager.h"
58//#include "VoldUtil.h"
59//#include "Ext4Crypt.h"
60//#include "f2fs_sparseblock.h"
61//#include "EncryptInplace.h"
62//#include "Process.h"
63#if TW_KEYMASTER_MAX_API == 3
64#include "../ext4crypt/Keymaster3.h"
65#endif
66#if TW_KEYMASTER_MAX_API == 4
67#include "../ext4crypt/Keymaster4.h"
68#endif
69#if TW_KEYMASTER_MAX_API == 0
70#include <hardware/keymaster.h>
71#else // so far, all trees that have keymaster >= 1 have keymaster 1 support
72#include <stdbool.h>
73#include <openssl/evp.h>
74#include <openssl/sha.h>
75#include <hardware/keymaster0.h>
76#include <hardware/keymaster1.h>
77#endif
78//#include "android-base/properties.h"
79//#include <bootloader_message/bootloader_message.h>
80#ifdef CONFIG_HW_DISK_ENCRYPTION
81#include <cryptfs_hw.h>
82#endif
83extern "C" {
84#include <crypto_scrypt.h>
85}
86#include <string>
87#include <vector>
88
89#define ALOGE(...) fprintf(stdout, "E:" __VA_ARGS__)
90#define SLOGE(...) fprintf(stdout, "E:" __VA_ARGS__)
91#define SLOGW(...) fprintf(stdout, "W:" __VA_ARGS__)
92#define SLOGI(...) fprintf(stdout, "I:" __VA_ARGS__)
93#define SLOGD(...) fprintf(stdout, "D:" __VA_ARGS__)
94
95#define UNUSED __attribute__((unused))
96
97#define DM_CRYPT_BUF_SIZE 4096
98
99#define HASH_COUNT 2000
100
101#ifndef min /* already defined by windows.h */
102#define min(a, b) ((a) < (b) ? (a) : (b))
103#endif
104
105constexpr size_t INTERMEDIATE_KEY_LEN_BYTES = 16;
106constexpr size_t INTERMEDIATE_IV_LEN_BYTES = 16;
107constexpr size_t INTERMEDIATE_BUF_SIZE =
108 (INTERMEDIATE_KEY_LEN_BYTES + INTERMEDIATE_IV_LEN_BYTES);
109
110// SCRYPT_LEN is used by struct crypt_mnt_ftr for its intermediate key.
111static_assert(INTERMEDIATE_BUF_SIZE == SCRYPT_LEN,
112 "Mismatch of intermediate key sizes");
113
114#define KEY_IN_FOOTER "footer"
115
116#define DEFAULT_HEX_PASSWORD "64656661756c745f70617373776f7264"
117#define DEFAULT_PASSWORD "default_password"
118
119#define CRYPTO_BLOCK_DEVICE "userdata"
120
121#define TABLE_LOAD_RETRIES 10
122
123#define RSA_KEY_SIZE 2048
124#define RSA_KEY_SIZE_BYTES (RSA_KEY_SIZE / 8)
125#define RSA_EXPONENT 0x10001
126#define KEYMASTER_CRYPTFS_RATE_LIMIT 1 // Maximum one try per second
127#define KEY_LEN_BYTES 16
128
129#define RETRY_MOUNT_ATTEMPTS 10
130#define RETRY_MOUNT_DELAY_SECONDS 1
131
132#define CREATE_CRYPTO_BLK_DEV_FLAGS_ALLOW_ENCRYPT_OVERRIDE (1)
133
134static unsigned char saved_master_key[MAX_KEY_LEN];
135static char *saved_mount_point;
136static int master_key_saved = 0;
137static struct crypt_persist_data *persist_data = NULL;
138
139static int previous_type;
140
141static char key_fname[PROPERTY_VALUE_MAX] = "";
142static char real_blkdev[PROPERTY_VALUE_MAX] = "";
143static char file_system[PROPERTY_VALUE_MAX] = "";
144
145static void get_blkdev_size(int fd, unsigned long *nr_sec)
146{
147 if ( (ioctl(fd, BLKGETSIZE, nr_sec)) == -1) {
148 *nr_sec = 0;
149 }
150}
151
152#if TW_KEYMASTER_MAX_API == 0
153static int keymaster_init(keymaster_device_t **keymaster_dev)
154{
155 int rc;
156
157 const hw_module_t* mod;
158 rc = hw_get_module_by_class(KEYSTORE_HARDWARE_MODULE_ID, NULL, &mod);
159 if (rc) {
160 printf("could not find any keystore module\n");
161 goto out;
162 }
163
164 rc = keymaster_open(mod, keymaster_dev);
165 if (rc) {
166 printf("could not open keymaster device in %s (%s)\n",
167 KEYSTORE_HARDWARE_MODULE_ID, strerror(-rc));
168 goto out;
169 }
170
171 return 0;
172
173out:
174 *keymaster_dev = NULL;
175 return rc;
176}
177#else //TW_KEYMASTER_MAX_API == 0
178static int keymaster_init(keymaster0_device_t **keymaster0_dev,
179 keymaster1_device_t **keymaster1_dev)
180{
181 int rc;
182
183 const hw_module_t* mod;
184 rc = hw_get_module_by_class(KEYSTORE_HARDWARE_MODULE_ID, NULL, &mod);
185 if (rc) {
186 printf("could not find any keystore module\n");
187 goto err;
188 }
189
190 printf("keymaster module name is %s\n", mod->name);
191 printf("keymaster version is %d\n", mod->module_api_version);
192
193 *keymaster0_dev = NULL;
194 *keymaster1_dev = NULL;
195 if (mod->module_api_version == KEYMASTER_MODULE_API_VERSION_1_0) {
196 printf("Found keymaster1 module, using keymaster1 API.\n");
197 rc = keymaster1_open(mod, keymaster1_dev);
198 } else {
199 printf("Found keymaster0 module, using keymaster0 API.\n");
200 rc = keymaster0_open(mod, keymaster0_dev);
201 }
202
203 if (rc) {
204 printf("could not open keymaster device in %s (%s)\n",
205 KEYSTORE_HARDWARE_MODULE_ID, strerror(-rc));
206 goto err;
207 }
208
209 return 0;
210
211err:
212 *keymaster0_dev = NULL;
213 *keymaster1_dev = NULL;
214 return rc;
215}
216#endif //TW_KEYMASTER_MAX_API == 0
217
218#ifdef CONFIG_HW_DISK_ENCRYPTION
219static int scrypt_keymaster(const char *passwd, const unsigned char *salt,
220 unsigned char *ikey, void *params);
221static void convert_key_to_hex_ascii(const unsigned char *master_key,
222 unsigned int keysize, char *master_key_ascii);
223static int test_mount_hw_encrypted_fs(struct crypt_mnt_ftr* crypt_ftr,
224 const char *passwd, const char *mount_point, const char *label);
225int cryptfs_check_passwd_hw(char *passwd);
226int cryptfs_get_master_key(struct crypt_mnt_ftr* ftr, const char* password,
227 unsigned char* master_key);
228
229static void convert_key_to_hex_ascii_for_upgrade(const unsigned char *master_key,
230 unsigned int keysize, char *master_key_ascii)
231{
232 unsigned int i, a;
233 unsigned char nibble;
234
235 for (i = 0, a = 0; i < keysize; i++, a += 2) {
236 /* For each byte, write out two ascii hex digits */
237 nibble = (master_key[i] >> 4) & 0xf;
238 master_key_ascii[a] = nibble + (nibble > 9 ? 0x57 : 0x30);
239
240 nibble = master_key[i] & 0xf;
241 master_key_ascii[a + 1] = nibble + (nibble > 9 ? 0x57 : 0x30);
242 }
243
244 /* Add the null termination */
245 master_key_ascii[a] = '\0';
246}
247
248static int get_keymaster_hw_fde_passwd(const char* passwd, unsigned char* newpw,
249 unsigned char* salt,
250 const struct crypt_mnt_ftr *ftr)
251{
252 /* if newpw updated, return 0
253 * if newpw not updated return -1
254 */
255 int rc = -1;
256
257 if (should_use_keymaster()) {
258 if (scrypt_keymaster(passwd, salt, newpw, (void*)ftr)) {
Captain Throwback49cfb7e2020-01-28 17:37:00 -0500259 SLOGE("scrypt failed\n");
Ethan Yonker98661c12018-10-17 08:39:28 -0500260 } else {
261 rc = 0;
262 }
263 }
264
265 return rc;
266}
267
268static int verify_hw_fde_passwd(const char *passwd, struct crypt_mnt_ftr* crypt_ftr)
269{
270 unsigned char newpw[32] = {0};
271 int key_index;
272 SLOGI("starting verify_hw_fde_passwd\n");
273 if (get_keymaster_hw_fde_passwd(passwd, newpw, crypt_ftr->salt, crypt_ftr))
274 key_index = set_hw_device_encryption_key(passwd,
275 (char*) crypt_ftr->crypto_type_name);
276 else
277 key_index = set_hw_device_encryption_key((const char*)newpw,
278 (char*) crypt_ftr->crypto_type_name);
279 return key_index;
280}
281
282static int verify_and_update_hw_fde_passwd(const char *passwd,
283 struct crypt_mnt_ftr* crypt_ftr)
284{
285 char* new_passwd = NULL;
286 unsigned char newpw[32] = {0};
287 int key_index = -1;
288 int passwd_updated = -1;
289 int ascii_passwd_updated = (crypt_ftr->flags & CRYPT_ASCII_PASSWORD_UPDATED);
290
291 key_index = verify_hw_fde_passwd(passwd, crypt_ftr);
292 if (key_index < 0) {
293 ++crypt_ftr->failed_decrypt_count;
294
295 if (ascii_passwd_updated) {
Captain Throwback49cfb7e2020-01-28 17:37:00 -0500296 SLOGI("Ascii password was updated\n");
Ethan Yonker98661c12018-10-17 08:39:28 -0500297 } else {
298 /* Code in else part would execute only once:
299 * When device is upgraded from L->M release.
300 * Once upgraded, code flow should never come here.
301 * L release passed actual password in hex, so try with hex
302 * Each nible of passwd was encoded as a byte, so allocate memory
303 * twice of password len plus one more byte for null termination
304 */
305 if (crypt_ftr->crypt_type == CRYPT_TYPE_DEFAULT) {
306 new_passwd = (char*)malloc(strlen(DEFAULT_HEX_PASSWORD) + 1);
307 if (new_passwd == NULL) {
Captain Throwbacka5283b32020-02-19 12:11:23 -0500308 SLOGE("System out of memory. Password verification incomplete\n");
Ethan Yonker98661c12018-10-17 08:39:28 -0500309 goto out;
310 }
311 strlcpy(new_passwd, DEFAULT_HEX_PASSWORD, strlen(DEFAULT_HEX_PASSWORD) + 1);
312 } else {
313 new_passwd = (char*)malloc(strlen(passwd) * 2 + 1);
314 if (new_passwd == NULL) {
Captain Throwbacka5283b32020-02-19 12:11:23 -0500315 SLOGE("System out of memory. Password verification incomplete\n");
Ethan Yonker98661c12018-10-17 08:39:28 -0500316 goto out;
317 }
318 convert_key_to_hex_ascii_for_upgrade((const unsigned char*)passwd,
319 strlen(passwd), new_passwd);
320 }
321 key_index = set_hw_device_encryption_key((const char*)new_passwd,
322 (char*) crypt_ftr->crypto_type_name);
323 if (key_index >=0) {
324 crypt_ftr->failed_decrypt_count = 0;
Captain Throwbacka5283b32020-02-19 12:11:23 -0500325 SLOGI("Hex password verified...will try to update with Ascii value\n");
Ethan Yonker98661c12018-10-17 08:39:28 -0500326 /* Before updating password, tie that with keymaster to tie with ROT */
327
328 if (get_keymaster_hw_fde_passwd(passwd, newpw,
329 crypt_ftr->salt, crypt_ftr)) {
330 passwd_updated = update_hw_device_encryption_key(new_passwd,
331 passwd, (char*)crypt_ftr->crypto_type_name);
332 } else {
333 passwd_updated = update_hw_device_encryption_key(new_passwd,
334 (const char*)newpw, (char*)crypt_ftr->crypto_type_name);
335 }
336
337 if (passwd_updated >= 0) {
338 crypt_ftr->flags |= CRYPT_ASCII_PASSWORD_UPDATED;
Captain Throwbacka5283b32020-02-19 12:11:23 -0500339 SLOGI("Ascii password recorded and updated\n");
Ethan Yonker98661c12018-10-17 08:39:28 -0500340 } else {
Captain Throwbacka5283b32020-02-19 12:11:23 -0500341 SLOGI("Passwd verified, could not update...Will try next time\n");
Ethan Yonker98661c12018-10-17 08:39:28 -0500342 }
343 } else {
344 ++crypt_ftr->failed_decrypt_count;
345 }
346 free(new_passwd);
347 }
348 } else {
349 if (!ascii_passwd_updated)
350 crypt_ftr->flags |= CRYPT_ASCII_PASSWORD_UPDATED;
351 }
352out:
353 // update footer before leaving
354 //put_crypt_ftr_and_key(crypt_ftr);
355 return key_index;
356}
357#endif
358
359void set_partition_data(const char* block_device, const char* key_location, const char* fs)
360{
361 strcpy(key_fname, key_location);
362 strcpy(real_blkdev, block_device);
363 strcpy(file_system, fs);
364}
365
366/* This signs the given object using the keymaster key. */
367static int keymaster_sign_object(struct crypt_mnt_ftr *ftr,
368 const unsigned char *object,
369 const size_t object_size,
370 unsigned char **signature,
371 size_t *signature_size)
372{
373 SLOGI("TWRP keymaster max API: %i\n", TW_KEYMASTER_MAX_API);
374 unsigned char to_sign[RSA_KEY_SIZE_BYTES];
375 size_t to_sign_size = sizeof(to_sign);
376 memset(to_sign, 0, RSA_KEY_SIZE_BYTES);
377
378 // To sign a message with RSA, the message must satisfy two
379 // constraints:
380 //
381 // 1. The message, when interpreted as a big-endian numeric value, must
382 // be strictly less than the public modulus of the RSA key. Note
383 // that because the most significant bit of the public modulus is
384 // guaranteed to be 1 (else it's an (n-1)-bit key, not an n-bit
385 // key), an n-bit message with most significant bit 0 always
386 // satisfies this requirement.
387 //
388 // 2. The message must have the same length in bits as the public
389 // modulus of the RSA key. This requirement isn't mathematically
390 // necessary, but is necessary to ensure consistency in
391 // implementations.
392 switch (ftr->kdf_type) {
393 case KDF_SCRYPT_KEYMASTER_UNPADDED:
394 // This is broken: It produces a message which is shorter than
395 // the public modulus, failing criterion 2.
396 memcpy(to_sign, object, object_size);
397 to_sign_size = object_size;
398 SLOGI("Signing unpadded object\n");
399 break;
400 case KDF_SCRYPT_KEYMASTER_BADLY_PADDED:
401 // This is broken: Since the value of object is uniformly
402 // distributed, it produces a message that is larger than the
403 // public modulus with probability 0.25.
404 memcpy(to_sign, object, min(RSA_KEY_SIZE_BYTES, object_size));
405 SLOGI("Signing end-padded object\n");
406 break;
407 case KDF_SCRYPT_KEYMASTER:
408 // This ensures the most significant byte of the signed message
409 // is zero. We could have zero-padded to the left instead, but
410 // this approach is slightly more robust against changes in
411 // object size. However, it's still broken (but not unusably
412 // so) because we really should be using a proper deterministic
413 // RSA padding function, such as PKCS1.
414 memcpy(to_sign + 1, object, min((size_t)RSA_KEY_SIZE_BYTES - 1, object_size));
Captain Throwback49cfb7e2020-01-28 17:37:00 -0500415 SLOGI("Signing safely-padded object\n");
Ethan Yonker98661c12018-10-17 08:39:28 -0500416 break;
417 default:
Captain Throwbacka5283b32020-02-19 12:11:23 -0500418 SLOGE("Unknown KDF type %d\n", ftr->kdf_type);
Ethan Yonker98661c12018-10-17 08:39:28 -0500419 return -1;
420 }
421
422 int rc = -1;
423
424#if TW_KEYMASTER_MAX_API >= 1
425 keymaster0_device_t *keymaster0_dev = 0;
426 keymaster1_device_t *keymaster1_dev = 0;
427 if (keymaster_init(&keymaster0_dev, &keymaster1_dev)) {
428#else
429 keymaster_device_t *keymaster0_dev = 0;
430 if (keymaster_init(&keymaster0_dev)) {
431#endif
432 printf("Failed to init keymaster 0/1\n");
433 goto initfail;
434 }
435 if (keymaster0_dev) {
436 keymaster_rsa_sign_params_t params;
437 params.digest_type = DIGEST_NONE;
438 params.padding_type = PADDING_NONE;
439
440 rc = keymaster0_dev->sign_data(keymaster0_dev,
441 &params,
442 ftr->keymaster_blob,
443 ftr->keymaster_blob_size,
444 to_sign,
445 to_sign_size,
446 signature,
447 signature_size);
448 goto out;
449 }
450#if TW_KEYMASTER_MAX_API >= 1
451 else if (keymaster1_dev) {
452 keymaster_key_blob_t key = { ftr->keymaster_blob, ftr->keymaster_blob_size };
453 keymaster_key_param_t params[] = {
454 keymaster_param_enum(KM_TAG_PADDING, KM_PAD_NONE),
455 keymaster_param_enum(KM_TAG_DIGEST, KM_DIGEST_NONE),
456 };
457 keymaster_key_param_set_t param_set = { params, sizeof(params)/sizeof(*params) };
458 keymaster_operation_handle_t op_handle;
459 keymaster_error_t error = keymaster1_dev->begin(keymaster1_dev, KM_PURPOSE_SIGN, &key,
460 &param_set, NULL /* out_params */,
461 &op_handle);
462 if (error == KM_ERROR_KEY_RATE_LIMIT_EXCEEDED) {
463 // Key usage has been rate-limited. Wait a bit and try again.
464 sleep(KEYMASTER_CRYPTFS_RATE_LIMIT);
465 error = keymaster1_dev->begin(keymaster1_dev, KM_PURPOSE_SIGN, &key,
466 &param_set, NULL /* out_params */,
467 &op_handle);
468 }
469 if (error != KM_ERROR_OK) {
470 printf("Error starting keymaster signature transaction: %d\n", error);
471 rc = -1;
472 goto out;
473 }
474
475 keymaster_blob_t input = { to_sign, to_sign_size };
476 size_t input_consumed;
477 error = keymaster1_dev->update(keymaster1_dev, op_handle, NULL /* in_params */,
478 &input, &input_consumed, NULL /* out_params */,
479 NULL /* output */);
480 if (error != KM_ERROR_OK) {
481 printf("Error sending data to keymaster signature transaction: %d\n", error);
482 rc = -1;
483 goto out;
484 }
485 if (input_consumed != to_sign_size) {
486 // This should never happen. If it does, it's a bug in the keymaster implementation.
487 printf("Keymaster update() did not consume all data.\n");
488 keymaster1_dev->abort(keymaster1_dev, op_handle);
489 rc = -1;
490 goto out;
491 }
492
493 keymaster_blob_t tmp_sig;
494 error = keymaster1_dev->finish(keymaster1_dev, op_handle, NULL /* in_params */,
495 NULL /* verify signature */, NULL /* out_params */,
496 &tmp_sig);
497 if (error != KM_ERROR_OK) {
498 printf("Error finishing keymaster signature transaction: %d\n", error);
499 rc = -1;
500 goto out;
501 }
502
503 *signature = (uint8_t*)tmp_sig.data;
504 *signature_size = tmp_sig.data_length;
505 rc = 0;
506 }
507#endif // TW_KEYMASTER_API >= 1
508
509 out:
510#if TW_KEYMASTER_MAX_API >= 1
511 if (keymaster1_dev)
512 keymaster1_close(keymaster1_dev);
513#endif
514 if (keymaster0_dev)
515#if TW_KEYMASTER_MAX_API >= 1
516 keymaster0_close(keymaster0_dev);
517#else
518 keymaster_close(keymaster0_dev);
519#endif
520
521 if (rc == 0)
522 return 0; // otherwise we'll try for a newer keymaster API
523
524initfail:
525#if TW_KEYMASTER_MAX_API == 3
526 return keymaster_sign_object_for_cryptfs_scrypt(ftr->keymaster_blob, ftr->keymaster_blob_size,
527 KEYMASTER_CRYPTFS_RATE_LIMIT, to_sign, to_sign_size, signature, signature_size,
528 ftr->keymaster_blob, KEYMASTER_BLOB_SIZE, &ftr->keymaster_blob_size);
529#endif //TW_KEYMASTER_MAX_API == 3
530#if TW_KEYMASTER_MAX_API >= 4
531 //for (;;) {
532 auto result = keymaster_sign_object_for_cryptfs_scrypt(
533 ftr->keymaster_blob, ftr->keymaster_blob_size, KEYMASTER_CRYPTFS_RATE_LIMIT, to_sign,
534 to_sign_size, signature, signature_size);
535 switch (result) {
536 case KeymasterSignResult::ok:
537 return 0;
538 case KeymasterSignResult::upgrade:
539 break;
540 default:
541 return -1;
542 }
543 SLOGD("Upgrading key\n");
544 if (keymaster_upgrade_key_for_cryptfs_scrypt(
545 RSA_KEY_SIZE, RSA_EXPONENT, KEYMASTER_CRYPTFS_RATE_LIMIT, ftr->keymaster_blob,
546 ftr->keymaster_blob_size, ftr->keymaster_blob, KEYMASTER_BLOB_SIZE,
547 &ftr->keymaster_blob_size) != 0) {
548 SLOGE("Failed to upgrade key\n");
549 return -1;
550 }
551 /*if (put_crypt_ftr_and_key(ftr) != 0) {
Captain Throwbacka5283b32020-02-19 12:11:23 -0500552 SLOGE("Failed to write upgraded key to disk\n");
Ethan Yonker98661c12018-10-17 08:39:28 -0500553 }*/
554 SLOGD("Key upgraded successfully\n");
555 return 0;
556 //}
557#endif
558 return -1;
559}
560
561static void ioctl_init(struct dm_ioctl *io, size_t dataSize, const char *name, unsigned flags)
562{
563 memset(io, 0, dataSize);
564 io->data_size = dataSize;
565 io->data_start = sizeof(struct dm_ioctl);
566 io->version[0] = 4;
567 io->version[1] = 0;
568 io->version[2] = 0;
569 io->flags = flags;
570 if (name) {
571 strlcpy(io->name, name, sizeof(io->name));
572 }
573}
574
575namespace {
576
577struct CryptoType;
578
579// Use to get the CryptoType in use on this device.
580const CryptoType &get_crypto_type();
581
582struct CryptoType {
583 // We should only be constructing CryptoTypes as part of
584 // supported_crypto_types[]. We do it via this pseudo-builder pattern,
585 // which isn't pure or fully protected as a concession to being able to
586 // do it all at compile time. Add new CryptoTypes in
587 // supported_crypto_types[] below.
588 constexpr CryptoType() : CryptoType(nullptr, nullptr, 0xFFFFFFFF) {}
589 constexpr CryptoType set_keysize(uint32_t size) const {
590 return CryptoType(this->property_name, this->crypto_name, size);
591 }
592 constexpr CryptoType set_property_name(const char *property) const {
593 return CryptoType(property, this->crypto_name, this->keysize);
594 }
595 constexpr CryptoType set_crypto_name(const char *crypto) const {
596 return CryptoType(this->property_name, crypto, this->keysize);
597 }
598
599 constexpr const char *get_property_name() const { return property_name; }
600 constexpr const char *get_crypto_name() const { return crypto_name; }
601 constexpr uint32_t get_keysize() const { return keysize; }
602
603 private:
604 const char *property_name;
605 const char *crypto_name;
606 uint32_t keysize;
607
608 constexpr CryptoType(const char *property, const char *crypto,
609 uint32_t ksize)
610 : property_name(property), crypto_name(crypto), keysize(ksize) {}
611 friend const CryptoType &get_crypto_type();
612 static const CryptoType &get_device_crypto_algorithm();
613};
614
615// We only want to parse this read-only property once. But we need to wait
616// until the system is initialized before we can read it. So we use a static
617// scoped within this function to get it only once.
618const CryptoType &get_crypto_type() {
619 static CryptoType crypto_type = CryptoType::get_device_crypto_algorithm();
620 return crypto_type;
621}
622
623constexpr CryptoType default_crypto_type = CryptoType()
624 .set_property_name("AES-128-CBC")
625 .set_crypto_name("aes-cbc-essiv:sha256")
626 .set_keysize(16);
627
628constexpr CryptoType supported_crypto_types[] = {
629 default_crypto_type,
630 CryptoType()
631 .set_property_name("Speck128/128-XTS")
632 .set_crypto_name("speck128-xts-plain64")
633 .set_keysize(32),
634 // Add new CryptoTypes here. Order is not important.
635};
636
637
638// ---------- START COMPILE-TIME SANITY CHECK BLOCK -------------------------
639// We confirm all supported_crypto_types have a small enough keysize and
640// had both set_property_name() and set_crypto_name() called.
641
642template <typename T, size_t N>
643constexpr size_t array_length(T (&)[N]) { return N; }
644
645constexpr bool indexOutOfBoundsForCryptoTypes(size_t index) {
646 return (index >= array_length(supported_crypto_types));
647}
648
649constexpr bool isValidCryptoType(const CryptoType &crypto_type) {
650 return ((crypto_type.get_property_name() != nullptr) &&
651 (crypto_type.get_crypto_name() != nullptr) &&
652 (crypto_type.get_keysize() <= MAX_KEY_LEN));
653}
654
655// Note in C++11 that constexpr functions can only have a single line.
656// So our code is a bit convoluted (using recursion instead of a loop),
657// but it's asserting at compile time that all of our key lengths are valid.
658constexpr bool validateSupportedCryptoTypes(size_t index) {
659 return indexOutOfBoundsForCryptoTypes(index) ||
660 (isValidCryptoType(supported_crypto_types[index]) &&
661 validateSupportedCryptoTypes(index + 1));
662}
663
664static_assert(validateSupportedCryptoTypes(0),
665 "We have a CryptoType with keysize > MAX_KEY_LEN or which was "
666 "incompletely constructed.");
667// ---------- END COMPILE-TIME SANITY CHECK BLOCK -------------------------
668
669
670// Don't call this directly, use get_crypto_type(), which caches this result.
671const CryptoType &CryptoType::get_device_crypto_algorithm() {
672 constexpr char CRYPT_ALGO_PROP[] = "ro.crypto.fde_algorithm";
673 char paramstr[PROPERTY_VALUE_MAX];
674
675 property_get(CRYPT_ALGO_PROP, paramstr,
676 default_crypto_type.get_property_name());
677 for (auto const &ctype : supported_crypto_types) {
678 if (strcmp(paramstr, ctype.get_property_name()) == 0) {
679 return ctype;
680 }
681 }
682 ALOGE("Invalid name (%s) for %s. Defaulting to %s\n", paramstr,
683 CRYPT_ALGO_PROP, default_crypto_type.get_property_name());
684 return default_crypto_type;
685}
686
687} // namespace
688
689#define SCRYPT_PROP "ro.crypto.scrypt_params"
690#define SCRYPT_DEFAULTS "15:3:1"
691
692bool parse_scrypt_parameters(const char* paramstr, int *Nf, int *rf, int *pf) {
693 int params[3] = {};
694 char *token;
695 char *saveptr;
696 int i;
697
698 /*
699 * The token we're looking for should be three integers separated by
700 * colons (e.g., "12:8:1"). Scan the property to make sure it matches.
701 */
702 for (i = 0, token = strtok_r(const_cast<char *>(paramstr), ":", &saveptr);
703 token != nullptr && i < 3;
704 i++, token = strtok_r(nullptr, ":", &saveptr)) {
705 char *endptr;
706 params[i] = strtol(token, &endptr, 10);
707
708 /*
709 * Check that there was a valid number and it's 8-bit.
710 */
711 if ((*token == '\0') || (*endptr != '\0') || params[i] < 0 || params[i] > 255) {
712 return false;
713 }
714 }
715 if (token != nullptr) {
716 return false;
717 }
718 *Nf = params[0]; *rf = params[1]; *pf = params[2];
719 return true;
720}
721
722uint32_t cryptfs_get_keysize() {
723 return get_crypto_type().get_keysize();
724}
725
726const char *cryptfs_get_crypto_name() {
727 return get_crypto_type().get_crypto_name();
728}
729
730static int get_crypt_ftr_info(char **metadata_fname, off64_t *off)
731{
732 static int cached_data = 0;
733 static off64_t cached_off = 0;
734 static char cached_metadata_fname[PROPERTY_VALUE_MAX] = "";
735 int fd;
736 //char key_loc[PROPERTY_VALUE_MAX];
737 //char real_blkdev[PROPERTY_VALUE_MAX];
738 int rc = -1;
739
740 if (!cached_data) {
741 //fs_mgr_get_crypt_info(fstab_default, key_loc, real_blkdev, sizeof(key_loc));
742
743 if (!strcmp(key_fname, KEY_IN_FOOTER)) {
744 if ( (fd = open(real_blkdev, O_RDWR|O_CLOEXEC)) < 0) {
745 SLOGE("Cannot open real block device %s\n", real_blkdev);
746 return -1;
747 }
748
749 unsigned long nr_sec = 0;
750 get_blkdev_size(fd, &nr_sec);
751 if (nr_sec != 0) {
752 /* If it's an encrypted Android partition, the last 16 Kbytes contain the
753 * encryption info footer and key, and plenty of bytes to spare for future
754 * growth.
755 */
756 strlcpy(cached_metadata_fname, real_blkdev, sizeof(cached_metadata_fname));
757 cached_off = ((off64_t)nr_sec * 512) - CRYPT_FOOTER_OFFSET;
758 cached_data = 1;
759 } else {
760 SLOGE("Cannot get size of block device %s\n", real_blkdev);
761 }
762 close(fd);
763 } else {
764 strlcpy(cached_metadata_fname, key_fname, sizeof(cached_metadata_fname));
765 cached_off = 0;
766 cached_data = 1;
767 }
768 }
769
770 if (cached_data) {
771 if (metadata_fname) {
772 *metadata_fname = cached_metadata_fname;
773 }
774 if (off) {
775 *off = cached_off;
776 }
777 rc = 0;
778 }
779
780 return rc;
781}
782
783static int get_crypt_ftr_and_key(struct crypt_mnt_ftr *crypt_ftr)
784{
785 int fd;
786 unsigned int cnt;
787 off64_t starting_off;
788 int rc = -1;
789 char *fname = NULL;
790 struct stat statbuf;
791
792 if (get_crypt_ftr_info(&fname, &starting_off)) {
793 SLOGE("Unable to get crypt_ftr_info\n");
794 return -1;
795 }
796 if (fname[0] != '/') {
797 SLOGE("Unexpected value for crypto key location\n");
798 return -1;
799 }
800 if ( (fd = open(fname, O_RDWR|O_CLOEXEC)) < 0) {
801 SLOGE("Cannot open footer file %s for get\n", fname);
802 return -1;
803 }
804
805 /* Make sure it's 16 Kbytes in length */
806 fstat(fd, &statbuf);
807 if (S_ISREG(statbuf.st_mode) && (statbuf.st_size != 0x4000)) {
808 SLOGE("footer file %s is not the expected size!\n", fname);
809 goto errout;
810 }
811
812 /* Seek to the start of the crypt footer */
813 if (lseek64(fd, starting_off, SEEK_SET) == -1) {
814 SLOGE("Cannot seek to real block device footer\n");
815 goto errout;
816 }
817
818 if ( (cnt = read(fd, crypt_ftr, sizeof(struct crypt_mnt_ftr))) != sizeof(struct crypt_mnt_ftr)) {
819 SLOGE("Cannot read real block device footer\n");
820 goto errout;
821 }
822
823 if (crypt_ftr->magic != CRYPT_MNT_MAGIC) {
824 SLOGE("Bad magic for real block device %s\n", fname);
825 goto errout;
826 }
827
828 if (crypt_ftr->major_version != CURRENT_MAJOR_VERSION) {
829 SLOGE("Cannot understand major version %d real block device footer; expected %d\n",
830 crypt_ftr->major_version, CURRENT_MAJOR_VERSION);
831 goto errout;
832 }
833
834 // We risk buffer overflows with oversized keys, so we just reject them.
835 // 0-sized keys are problematic (essentially by-passing encryption), and
836 // AES-CBC key wrapping only works for multiples of 16 bytes.
837 if ((crypt_ftr->keysize == 0) || ((crypt_ftr->keysize % 16) != 0) ||
838 (crypt_ftr->keysize > MAX_KEY_LEN)) {
839 SLOGE("Invalid keysize (%u) for block device %s; Must be non-zero, "
840 "divisible by 16, and <= %d\n", crypt_ftr->keysize, fname,
841 MAX_KEY_LEN);
842 goto errout;
843 }
844
845 if (crypt_ftr->minor_version > CURRENT_MINOR_VERSION) {
846 SLOGW("Warning: crypto footer minor version %d, expected <= %d, continuing...\n",
847 crypt_ftr->minor_version, CURRENT_MINOR_VERSION);
848 }
849
850 /* Success! */
851 rc = 0;
852
853errout:
854 close(fd);
855 return rc;
856}
857
858int cryptfs_check_footer()
859{
860 int rc = -1;
861 struct crypt_mnt_ftr crypt_ftr;
862
863 rc = get_crypt_ftr_and_key(&crypt_ftr);
864
865 return rc;
866}
867
868/* Convert a binary key of specified length into an ascii hex string equivalent,
869 * without the leading 0x and with null termination
870 */
871static void convert_key_to_hex_ascii(const unsigned char *master_key,
872 unsigned int keysize, char *master_key_ascii) {
873 unsigned int i, a;
874 unsigned char nibble;
875
876 for (i=0, a=0; i<keysize; i++, a+=2) {
877 /* For each byte, write out two ascii hex digits */
878 nibble = (master_key[i] >> 4) & 0xf;
879 master_key_ascii[a] = nibble + (nibble > 9 ? 0x37 : 0x30);
880
881 nibble = master_key[i] & 0xf;
882 master_key_ascii[a+1] = nibble + (nibble > 9 ? 0x37 : 0x30);
883 }
884
885 /* Add the null termination */
886 master_key_ascii[a] = '\0';
887
888}
889
890static int load_crypto_mapping_table(struct crypt_mnt_ftr *crypt_ftr,
891 const unsigned char *master_key, const char *real_blk_name,
892 const char *name, int fd, const char *extra_params) {
893 alignas(struct dm_ioctl) char buffer[DM_CRYPT_BUF_SIZE];
894 struct dm_ioctl *io;
895 struct dm_target_spec *tgt;
896 char *crypt_params;
897 // We need two ASCII characters to represent each byte, and need space for
898 // the '\0' terminator.
899 char master_key_ascii[MAX_KEY_LEN * 2 + 1];
900 size_t buff_offset;
901 int i;
902
903 io = (struct dm_ioctl *) buffer;
904
905 /* Load the mapping table for this device */
906 tgt = (struct dm_target_spec *) &buffer[sizeof(struct dm_ioctl)];
907
908 ioctl_init(io, DM_CRYPT_BUF_SIZE, name, 0);
909 io->target_count = 1;
910 tgt->status = 0;
911 tgt->sector_start = 0;
912 tgt->length = crypt_ftr->fs_size;
913 crypt_params = buffer + sizeof(struct dm_ioctl) + sizeof(struct dm_target_spec);
914 buff_offset = crypt_params - buffer;
915 SLOGI("Extra parameters for dm_crypt: %s\n", extra_params);
916
917#ifdef CONFIG_HW_DISK_ENCRYPTION
918 if(is_hw_disk_encryption((char*)crypt_ftr->crypto_type_name)) {
919 strlcpy(tgt->target_type, "req-crypt",DM_MAX_TYPE_NAME);
920 if (is_ice_enabled())
921 convert_key_to_hex_ascii(master_key, sizeof(int), master_key_ascii);
922 else
923 convert_key_to_hex_ascii(master_key, crypt_ftr->keysize, master_key_ascii);
924 }
925 else {
926 convert_key_to_hex_ascii(master_key, crypt_ftr->keysize, master_key_ascii);
927 strlcpy(tgt->target_type, "crypt", DM_MAX_TYPE_NAME);
928 }
929 snprintf(crypt_params, sizeof(buffer) - buff_offset, "%s %s 0 %s 0 %s 0",
930 crypt_ftr->crypto_type_name, master_key_ascii,
931 real_blk_name, extra_params);
932
Captain Throwback49cfb7e2020-01-28 17:37:00 -0500933 SLOGI("target_type = %s\n", tgt->target_type);
934 SLOGI("real_blk_name = %s, extra_params = %s\n", real_blk_name, extra_params);
Ethan Yonker98661c12018-10-17 08:39:28 -0500935#else
936 convert_key_to_hex_ascii(master_key, crypt_ftr->keysize, master_key_ascii);
937 strlcpy(tgt->target_type, "crypt", DM_MAX_TYPE_NAME);
938 snprintf(crypt_params, sizeof(buffer) - buff_offset, "%s %s 0 %s 0 %s",
939 crypt_ftr->crypto_type_name, master_key_ascii, real_blk_name,
940 extra_params);
941#endif
942
943 crypt_params += strlen(crypt_params) + 1;
944 crypt_params = (char *) (((unsigned long)crypt_params + 7) & ~8); /* Align to an 8 byte boundary */
945 tgt->next = crypt_params - buffer;
946
947 for (i = 0; i < TABLE_LOAD_RETRIES; i++) {
948 if (! ioctl(fd, DM_TABLE_LOAD, io)) {
949 break;
950 }
951 usleep(500000);
952 }
953
954 if (i == TABLE_LOAD_RETRIES) {
955 /* We failed to load the table, return an error */
956 return -1;
957 } else {
958 return i + 1;
959 }
960}
961
962static int get_dm_crypt_version(int fd, const char *name, int *version)
963{
964 char buffer[DM_CRYPT_BUF_SIZE];
965 struct dm_ioctl *io;
966 struct dm_target_versions *v;
967
968 io = (struct dm_ioctl *) buffer;
969
970 ioctl_init(io, DM_CRYPT_BUF_SIZE, name, 0);
971
972 if (ioctl(fd, DM_LIST_VERSIONS, io)) {
973 return -1;
974 }
975
976 /* Iterate over the returned versions, looking for name of "crypt".
977 * When found, get and return the version.
978 */
979 v = (struct dm_target_versions *) &buffer[sizeof(struct dm_ioctl)];
980 while (v->next) {
981#ifdef CONFIG_HW_DISK_ENCRYPTION
982 if (! strcmp(v->name, "crypt") || ! strcmp(v->name, "req-crypt")) {
983#else
984 if (! strcmp(v->name, "crypt")) {
985#endif
986 /* We found the crypt driver, return the version, and get out */
987 version[0] = v->version[0];
988 version[1] = v->version[1];
989 version[2] = v->version[2];
990 return 0;
991 }
992 v = (struct dm_target_versions *)(((char *)v) + v->next);
993 }
994
995 return -1;
996}
997
998#ifndef CONFIG_HW_DISK_ENCRYPTION
999static std::string extra_params_as_string(const std::vector<std::string>& extra_params_vec) {
1000 if (extra_params_vec.empty()) return "";
1001 char temp[10];
1002 snprintf(temp, sizeof(temp), "%zd", extra_params_vec.size());
1003 std::string extra_params = temp; //std::to_string(extra_params_vec.size());
1004 for (const auto& p : extra_params_vec) {
1005 extra_params.append(" ");
1006 extra_params.append(p);
1007 }
1008 return extra_params;
1009}
1010#endif
1011
1012static int create_crypto_blk_dev(struct crypt_mnt_ftr* crypt_ftr, const unsigned char* master_key,
1013 const char* real_blk_name, char* crypto_blk_name, const char* name,
1014 uint32_t flags) {
1015 char buffer[DM_CRYPT_BUF_SIZE];
1016 struct dm_ioctl* io;
1017 unsigned int minor;
1018 int fd = 0;
1019 int err;
1020 int retval = -1;
1021 int version[3];
1022 int load_count;
1023#ifdef CONFIG_HW_DISK_ENCRYPTION
1024 char encrypted_state[PROPERTY_VALUE_MAX] = {0};
1025 char progress[PROPERTY_VALUE_MAX] = {0};
1026 const char *extra_params;
1027#else
1028 std::vector<std::string> extra_params_vec;
1029#endif
1030
1031 if ((fd = open("/dev/device-mapper", O_RDWR | O_CLOEXEC)) < 0) {
1032 SLOGE("Cannot open device-mapper\n");
1033 goto errout;
1034 }
1035
1036 io = (struct dm_ioctl*)buffer;
1037
1038 ioctl_init(io, DM_CRYPT_BUF_SIZE, name, 0);
1039 err = ioctl(fd, DM_DEV_CREATE, io);
1040 if (err) {
1041 SLOGE("Cannot create dm-crypt device %s: %s\n", name, strerror(errno));
1042 goto errout;
1043 }
1044
1045 /* Get the device status, in particular, the name of it's device file */
1046 ioctl_init(io, DM_CRYPT_BUF_SIZE, name, 0);
1047 if (ioctl(fd, DM_DEV_STATUS, io)) {
1048 SLOGE("Cannot retrieve dm-crypt device status\n");
1049 goto errout;
1050 }
1051 minor = (io->dev & 0xff) | ((io->dev >> 12) & 0xfff00);
1052 snprintf(crypto_blk_name, MAXPATHLEN, "/dev/block/dm-%u", minor);
1053
1054#ifdef CONFIG_HW_DISK_ENCRYPTION
1055 if(is_hw_disk_encryption((char*)crypt_ftr->crypto_type_name)) {
1056 /* Set fde_enabled if either FDE completed or in-progress */
1057 property_get("ro.crypto.state", encrypted_state, ""); /* FDE completed */
1058 property_get("vold.encrypt_progress", progress, ""); /* FDE in progress */
1059 if (!strcmp(encrypted_state, "encrypted") || strcmp(progress, "")) {
1060 if (is_ice_enabled()) {
1061 if (flags & CREATE_CRYPTO_BLK_DEV_FLAGS_ALLOW_ENCRYPT_OVERRIDE)
1062 extra_params = "fde_enabled ice allow_encrypt_override";
1063 else
1064 extra_params = "fde_enabled ice";
1065 } else {
1066 if (flags & CREATE_CRYPTO_BLK_DEV_FLAGS_ALLOW_ENCRYPT_OVERRIDE)
1067 extra_params = "fde_enabled allow_encrypt_override";
1068 else
1069 extra_params = "fde_enabled";
1070 }
1071 } else {
1072 if (flags & CREATE_CRYPTO_BLK_DEV_FLAGS_ALLOW_ENCRYPT_OVERRIDE)
1073 extra_params = "fde_enabled allow_encrypt_override";
1074 else
1075 extra_params = "fde_enabled";
1076 }
1077 } else {
1078 extra_params = "";
1079 if (! get_dm_crypt_version(fd, name, version)) {
1080 /* Support for allow_discards was added in version 1.11.0 */
1081 if ((version[0] >= 2) || ((version[0] == 1) && (version[1] >= 11))) {
1082 if (flags & CREATE_CRYPTO_BLK_DEV_FLAGS_ALLOW_ENCRYPT_OVERRIDE)
1083 extra_params = "2 allow_discards allow_encrypt_override";
1084 else
1085 extra_params = "1 allow_discards";
1086 SLOGI("Enabling support for allow_discards in dmcrypt.\n");
1087 }
1088 }
1089 }
1090 load_count = load_crypto_mapping_table(crypt_ftr, master_key, real_blk_name, name, fd,
1091 extra_params);
1092#else
1093 if (!get_dm_crypt_version(fd, name, version)) {
1094 /* Support for allow_discards was added in version 1.11.0 */
1095 if ((version[0] >= 2) || ((version[0] == 1) && (version[1] >= 11))) {
1096 extra_params_vec.push_back(std::string("allow_discards")); // Used to be extra_params_vec.emplace_back("allow_discards"); but this won't compile in 5.1 trees
1097 }
1098 }
1099 if (flags & CREATE_CRYPTO_BLK_DEV_FLAGS_ALLOW_ENCRYPT_OVERRIDE) {
1100 extra_params_vec.push_back(std::string("allow_encrypt_override")); // Used to be extra_params_vec.emplace_back("allow_encrypt_override"); but this won't compile in 5.1 trees
1101 }
1102 load_count = load_crypto_mapping_table(crypt_ftr, master_key, real_blk_name, name, fd,
1103 extra_params_as_string(extra_params_vec).c_str());
1104#endif
1105 if (load_count < 0) {
1106 SLOGE("Cannot load dm-crypt mapping table.\n");
1107 goto errout;
1108 } else if (load_count > 1) {
1109 SLOGI("Took %d tries to load dmcrypt table.\n", load_count);
1110 }
1111
1112 /* Resume this device to activate it */
1113 ioctl_init(io, DM_CRYPT_BUF_SIZE, name, 0);
1114
1115 if (ioctl(fd, DM_DEV_SUSPEND, io)) {
1116 SLOGE("Cannot resume the dm-crypt device\n");
1117 goto errout;
1118 }
1119
1120 /* We made it here with no errors. Woot! */
1121 retval = 0;
1122
1123errout:
1124 close(fd); /* If fd is <0 from a failed open call, it's safe to just ignore the close error */
1125
1126 return retval;
1127}
1128
1129int delete_crypto_blk_dev(const char *name)
1130{
1131 int fd;
1132 char buffer[DM_CRYPT_BUF_SIZE];
1133 struct dm_ioctl *io;
1134 int retval = -1;
1135
1136 if ((fd = open("/dev/device-mapper", O_RDWR|O_CLOEXEC)) < 0 ) {
1137 SLOGE("Cannot open device-mapper\n");
1138 goto errout;
1139 }
1140
1141 io = (struct dm_ioctl *) buffer;
1142
1143 ioctl_init(io, DM_CRYPT_BUF_SIZE, name, 0);
1144 if (ioctl(fd, DM_DEV_REMOVE, io)) {
1145 SLOGE("Cannot remove dm-crypt device\n");
1146 goto errout;
1147 }
1148
1149 /* We made it here with no errors. Woot! */
1150 retval = 0;
1151
1152errout:
1153 close(fd); /* If fd is <0 from a failed open call, it's safe to just ignore the close error */
1154
1155 return retval;
1156
1157}
1158
1159static int pbkdf2(const char *passwd, const unsigned char *salt,
1160 unsigned char *ikey, void *params UNUSED)
1161{
1162 SLOGI("Using pbkdf2 for cryptfs KDF\n");
1163
1164 /* Turn the password into a key and IV that can decrypt the master key */
1165 return PKCS5_PBKDF2_HMAC_SHA1(passwd, strlen(passwd), salt, SALT_LEN,
1166 HASH_COUNT, INTERMEDIATE_BUF_SIZE,
1167 ikey) != 1;
1168}
1169
1170static int scrypt(const char *passwd, const unsigned char *salt,
1171 unsigned char *ikey, void *params)
1172{
1173 SLOGI("Using scrypt for cryptfs KDF\n");
1174
1175 struct crypt_mnt_ftr *ftr = (struct crypt_mnt_ftr *) params;
1176
1177 int N = 1 << ftr->N_factor;
1178 int r = 1 << ftr->r_factor;
1179 int p = 1 << ftr->p_factor;
1180
1181 /* Turn the password into a key and IV that can decrypt the master key */
1182 crypto_scrypt((const uint8_t*)passwd, strlen(passwd),
1183 salt, SALT_LEN, N, r, p, ikey,
1184 INTERMEDIATE_BUF_SIZE);
1185
1186 return 0;
1187}
1188
1189static int scrypt_keymaster(const char *passwd, const unsigned char *salt,
1190 unsigned char *ikey, void *params)
1191{
1192 SLOGI("Using scrypt with keymaster for cryptfs KDF\n");
1193
1194 int rc;
1195 size_t signature_size;
1196 unsigned char* signature;
1197 struct crypt_mnt_ftr *ftr = (struct crypt_mnt_ftr *) params;
1198
1199 int N = 1 << ftr->N_factor;
1200 int r = 1 << ftr->r_factor;
1201 int p = 1 << ftr->p_factor;
1202
1203 rc = crypto_scrypt((const uint8_t*)passwd, strlen(passwd),
1204 salt, SALT_LEN, N, r, p, ikey,
1205 INTERMEDIATE_BUF_SIZE);
1206
1207 if (rc) {
Captain Throwbacka5283b32020-02-19 12:11:23 -05001208 SLOGE("scrypt failed\n");
Ethan Yonker98661c12018-10-17 08:39:28 -05001209 return -1;
1210 }
1211
1212 if (keymaster_sign_object(ftr, ikey, INTERMEDIATE_BUF_SIZE,
1213 &signature, &signature_size)) {
Captain Throwbacka5283b32020-02-19 12:11:23 -05001214 SLOGE("Keymaster signing failed\n");
Ethan Yonker98661c12018-10-17 08:39:28 -05001215 return -1;
1216 }
1217
1218 rc = crypto_scrypt(signature, signature_size, salt, SALT_LEN,
1219 N, r, p, ikey, INTERMEDIATE_BUF_SIZE);
1220 free(signature);
1221
1222 if (rc) {
Captain Throwbacka5283b32020-02-19 12:11:23 -05001223 SLOGE("scrypt failed\n");
Ethan Yonker98661c12018-10-17 08:39:28 -05001224 return -1;
1225 }
1226
1227 return 0;
1228}
1229
1230static int decrypt_master_key_aux(const char *passwd, unsigned char *salt,
1231 const unsigned char *encrypted_master_key,
1232 size_t keysize,
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[INTERMEDIATE_BUF_SIZE] = { 0 };
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)) {
Captain Throwbacka5283b32020-02-19 12:11:23 -05001245 SLOGE("kdf failed\n");
Ethan Yonker98661c12018-10-17 08:39:28 -05001246 return -1;
1247 }
1248
1249 /* Initialize the decryption engine */
1250 EVP_CIPHER_CTX_init(&d_ctx);
1251 if (! EVP_DecryptInit_ex(&d_ctx, EVP_aes_128_cbc(), NULL, ikey, ikey+INTERMEDIATE_KEY_LEN_BYTES)) {
1252 return -1;
1253 }
1254 EVP_CIPHER_CTX_set_padding(&d_ctx, 0); /* Turn off padding as our data is block aligned */
1255 /* Decrypt the master key */
1256 if (! EVP_DecryptUpdate(&d_ctx, decrypted_master_key, &decrypted_len,
1257 encrypted_master_key, keysize)) {
1258 return -1;
1259 }
1260 if (! EVP_DecryptFinal_ex(&d_ctx, decrypted_master_key + decrypted_len, &final_len)) {
1261 return -1;
1262 }
1263
1264 if (decrypted_len + final_len != static_cast<int>(keysize)) {
1265 return -1;
1266 }
1267
1268 /* Copy intermediate key if needed by params */
1269 if (intermediate_key && intermediate_key_size) {
1270 *intermediate_key = (unsigned char*) malloc(INTERMEDIATE_KEY_LEN_BYTES);
1271 if (*intermediate_key) {
1272 memcpy(*intermediate_key, ikey, INTERMEDIATE_KEY_LEN_BYTES);
1273 *intermediate_key_size = INTERMEDIATE_KEY_LEN_BYTES;
1274 }
1275 }
1276
1277 EVP_CIPHER_CTX_cleanup(&d_ctx);
1278
1279 return 0;
1280}
1281
1282static void get_kdf_func(struct crypt_mnt_ftr *ftr, kdf_func *kdf, void** kdf_params)
1283{
1284 if (ftr->kdf_type == KDF_SCRYPT_KEYMASTER) {
1285 *kdf = scrypt_keymaster;
1286 *kdf_params = ftr;
1287 } else if (ftr->kdf_type == KDF_SCRYPT) {
1288 *kdf = scrypt;
1289 *kdf_params = ftr;
1290 } else {
1291 *kdf = pbkdf2;
1292 *kdf_params = NULL;
1293 }
1294}
1295
1296static int decrypt_master_key(const char *passwd, unsigned char *decrypted_master_key,
1297 struct crypt_mnt_ftr *crypt_ftr,
1298 unsigned char** intermediate_key,
1299 size_t* intermediate_key_size)
1300{
1301 kdf_func kdf;
1302 void *kdf_params;
1303 int ret;
1304
1305 get_kdf_func(crypt_ftr, &kdf, &kdf_params);
1306 ret = decrypt_master_key_aux(passwd, crypt_ftr->salt, crypt_ftr->master_key,
1307 crypt_ftr->keysize,
1308 decrypted_master_key, kdf, kdf_params,
1309 intermediate_key, intermediate_key_size);
1310 if (ret != 0) {
Captain Throwbacka5283b32020-02-19 12:11:23 -05001311 SLOGW("failure decrypting master key\n");
Ethan Yonker98661c12018-10-17 08:39:28 -05001312 }
1313
1314 return ret;
1315}
1316
1317#ifdef CONFIG_HW_DISK_ENCRYPTION
1318static int test_mount_hw_encrypted_fs(struct crypt_mnt_ftr* crypt_ftr,
1319 const char *passwd, const char *mount_point, const char *label)
1320{
1321 /* Allocate enough space for a 256 bit key, but we may use less */
1322 unsigned char decrypted_master_key[32];
1323 char crypto_blkdev[MAXPATHLEN];
1324 //char real_blkdev[MAXPATHLEN];
1325 unsigned int orig_failed_decrypt_count;
1326 int rc = 0;
1327
1328 SLOGD("crypt_ftr->fs_size = %lld\n", crypt_ftr->fs_size);
1329 orig_failed_decrypt_count = crypt_ftr->failed_decrypt_count;
1330
1331 //fs_mgr_get_crypt_info(fstab_default, 0, real_blkdev, sizeof(real_blkdev));
1332
1333 int key_index = 0;
1334 if(is_hw_disk_encryption((char*)crypt_ftr->crypto_type_name)) {
Mohd Faraz191a6942020-02-15 22:06:14 +05301335 if (crypt_ftr->flags & CRYPT_FORCE_COMPLETE) {
1336 if (decrypt_master_key(passwd, decrypted_master_key, crypt_ftr, 0, 0)) {
1337 printf("Failed to decrypt master key\n");
1338 rc = -1;
1339 goto errout;
1340 }
1341 }
Ethan Yonker98661c12018-10-17 08:39:28 -05001342 key_index = verify_and_update_hw_fde_passwd(passwd, crypt_ftr);
1343 if (key_index < 0) {
1344 rc = -1;
1345 goto errout;
1346 }
1347 else {
1348 if (is_ice_enabled()) {
1349#ifndef CONFIG_HW_DISK_ENCRYPT_PERF
1350 if (create_crypto_blk_dev(crypt_ftr, (unsigned char*)&key_index,
1351 real_blkdev, crypto_blkdev, label, 0)) {
Captain Throwback49cfb7e2020-01-28 17:37:00 -05001352 SLOGE("Error creating decrypted block device\n");
Ethan Yonker98661c12018-10-17 08:39:28 -05001353 rc = -1;
1354 goto errout;
1355 }
1356#endif
1357 } else {
1358 if (create_crypto_blk_dev(crypt_ftr, decrypted_master_key,
1359 real_blkdev, crypto_blkdev, label, 0)) {
Captain Throwback49cfb7e2020-01-28 17:37:00 -05001360 SLOGE("Error creating decrypted block device\n");
Ethan Yonker98661c12018-10-17 08:39:28 -05001361 rc = -1;
1362 goto errout;
1363 }
1364 }
1365 }
1366 }
1367
1368 if (rc == 0) {
1369 /* Save the name of the crypto block device
1370 * so we can mount it when restarting the framework. */
1371#ifdef CONFIG_HW_DISK_ENCRYPT_PERF
1372 if (!is_ice_enabled())
1373#endif
1374 property_set("ro.crypto.fs_crypto_blkdev", crypto_blkdev);
1375 master_key_saved = 1;
1376 }
1377
1378 errout:
1379 return rc;
1380}
1381#endif
1382
1383static int try_mount_multiple_fs(const char *crypto_blkdev,
1384 const char *mount_point,
1385 const char *file_system)
1386{
1387 if (!mount(crypto_blkdev, mount_point, file_system, 0, NULL))
1388 return 0;
1389 if (strcmp(file_system, "ext4") &&
1390 !mount(crypto_blkdev, mount_point, "ext4", 0, NULL))
1391 return 0;
1392 if (strcmp(file_system, "f2fs") &&
1393 !mount(crypto_blkdev, mount_point, "f2fs", 0, NULL))
1394 return 0;
1395 return 1;
1396}
1397
1398static int test_mount_encrypted_fs(struct crypt_mnt_ftr* crypt_ftr,
1399 const char *passwd, const char *mount_point, const char *label)
1400{
1401 unsigned char decrypted_master_key[MAX_KEY_LEN];
1402 char crypto_blkdev[MAXPATHLEN];
1403 //char real_blkdev[MAXPATHLEN];
1404 char tmp_mount_point[64];
1405 unsigned int orig_failed_decrypt_count;
Mohd Faraz191a6942020-02-15 22:06:14 +05301406 int rc = 0;
Ethan Yonker98661c12018-10-17 08:39:28 -05001407 int use_keymaster = 0;
1408 unsigned char* intermediate_key = 0;
1409 size_t intermediate_key_size = 0;
1410 int N = 1 << crypt_ftr->N_factor;
1411 int r = 1 << crypt_ftr->r_factor;
1412 int p = 1 << crypt_ftr->p_factor;
1413
1414 SLOGD("crypt_ftr->fs_size = %lld\n", crypt_ftr->fs_size);
1415 orig_failed_decrypt_count = crypt_ftr->failed_decrypt_count;
1416
1417 if (! (crypt_ftr->flags & CRYPT_MNT_KEY_UNENCRYPTED) ) {
1418 if (decrypt_master_key(passwd, decrypted_master_key, crypt_ftr,
1419 &intermediate_key, &intermediate_key_size)) {
1420 SLOGE("Failed to decrypt master key\n");
1421 rc = -1;
1422 goto errout;
1423 }
1424 }
1425
1426 //fs_mgr_get_crypt_info(fstab_default, 0, real_blkdev, sizeof(real_blkdev));
1427
1428 // Create crypto block device - all (non fatal) code paths
1429 // need it
1430 if (create_crypto_blk_dev(crypt_ftr, decrypted_master_key, real_blkdev, crypto_blkdev, label, 0)) {
1431 SLOGE("Error creating decrypted block device\n");
1432 rc = -1;
1433 goto errout;
1434 }
1435
1436 /* Work out if the problem is the password or the data */
1437 unsigned char scrypted_intermediate_key[sizeof(crypt_ftr->
1438 scrypted_intermediate_key)];
1439
1440 rc = crypto_scrypt(intermediate_key, intermediate_key_size,
1441 crypt_ftr->salt, sizeof(crypt_ftr->salt),
1442 N, r, p, scrypted_intermediate_key,
1443 sizeof(scrypted_intermediate_key));
1444
1445 // Does the key match the crypto footer?
1446 if (rc == 0 && memcmp(scrypted_intermediate_key,
1447 crypt_ftr->scrypted_intermediate_key,
1448 sizeof(scrypted_intermediate_key)) == 0) {
Captain Throwback49cfb7e2020-01-28 17:37:00 -05001449 SLOGI("Password matches\n");
Ethan Yonker98661c12018-10-17 08:39:28 -05001450 rc = 0;
1451 } else {
1452 /* Try mounting the file system anyway, just in case the problem's with
1453 * the footer, not the key. */
1454 snprintf(tmp_mount_point, sizeof(tmp_mount_point), "%s/tmp_mnt",
1455 mount_point);
1456 mkdir(tmp_mount_point, 0755);
1457 if (try_mount_multiple_fs(crypto_blkdev, tmp_mount_point, file_system)) {
1458 SLOGE("Error temp mounting decrypted block device\n");
1459 delete_crypto_blk_dev(label);
1460
1461 rc = -1;
1462 } else {
1463 /* Success! */
Captain Throwback49cfb7e2020-01-28 17:37:00 -05001464 SLOGI("Password did not match but decrypted drive mounted - continue\n");
Ethan Yonker98661c12018-10-17 08:39:28 -05001465 umount(tmp_mount_point);
1466 rc = 0;
1467 }
1468 }
1469
1470 if (rc == 0) {
1471 /* Save the name of the crypto block device
1472 * so we can mount it when restarting the framework. */
1473 property_set("ro.crypto.fs_crypto_blkdev", crypto_blkdev);
1474
1475 /* Also save a the master key so we can reencrypted the key
1476 * the key when we want to change the password on it. */
1477 memcpy(saved_master_key, decrypted_master_key, crypt_ftr->keysize);
1478 saved_mount_point = strdup(mount_point);
1479 master_key_saved = 1;
1480 SLOGD("%s(): Master key saved\n", __FUNCTION__);
1481 rc = 0;
1482 }
1483
1484 errout:
1485 if (intermediate_key) {
1486 memset(intermediate_key, 0, intermediate_key_size);
1487 free(intermediate_key);
1488 }
1489 return rc;
1490}
1491
1492/*
1493 * Called by vold when it's asked to mount an encrypted external
1494 * storage volume. The incoming partition has no crypto header/footer,
1495 * as any metadata is been stored in a separate, small partition. We
1496 * assume it must be using our same crypt type and keysize.
1497 *
1498 * out_crypto_blkdev must be MAXPATHLEN.
1499 */
1500int cryptfs_setup_ext_volume(const char* label, const char* real_blkdev,
1501 const unsigned char* key, int keysize, char* out_crypto_blkdev) {
1502 int fd = open(real_blkdev, O_RDONLY|O_CLOEXEC);
1503 if (fd == -1) {
Captain Throwbacka5283b32020-02-19 12:11:23 -05001504 SLOGE("Failed to open %s: %s\n", real_blkdev, strerror(errno));
Ethan Yonker98661c12018-10-17 08:39:28 -05001505 return -1;
1506 }
1507
1508 unsigned long nr_sec = 0;
1509 get_blkdev_size(fd, &nr_sec);
1510 close(fd);
1511
1512 if (nr_sec == 0) {
Captain Throwbacka5283b32020-02-19 12:11:23 -05001513 SLOGE("Failed to get size of %s: %s\n", real_blkdev, strerror(errno));
Ethan Yonker98661c12018-10-17 08:39:28 -05001514 return -1;
1515 }
1516
1517 struct crypt_mnt_ftr ext_crypt_ftr;
1518 memset(&ext_crypt_ftr, 0, sizeof(ext_crypt_ftr));
1519 ext_crypt_ftr.fs_size = nr_sec;
1520 ext_crypt_ftr.keysize = cryptfs_get_keysize();
1521 strlcpy((char*) ext_crypt_ftr.crypto_type_name, cryptfs_get_crypto_name(),
1522 MAX_CRYPTO_TYPE_NAME_LEN);
1523 uint32_t flags = 0;
1524 /*if (e4crypt_is_native() &&
1525 android::base::GetBoolProperty("ro.crypto.allow_encrypt_override", false))
1526 flags |= CREATE_CRYPTO_BLK_DEV_FLAGS_ALLOW_ENCRYPT_OVERRIDE;*/
1527
1528 return create_crypto_blk_dev(&ext_crypt_ftr, key, real_blkdev, out_crypto_blkdev, label, flags);
1529}
1530
1531/*
1532 * Called by vold when it's asked to unmount an encrypted external
1533 * storage volume.
1534 */
1535int cryptfs_revert_ext_volume(const char* label) {
1536 return delete_crypto_blk_dev(label);
1537}
1538
1539int check_unmounted_and_get_ftr(struct crypt_mnt_ftr* crypt_ftr)
1540{
1541 char encrypted_state[PROPERTY_VALUE_MAX];
1542 property_get("ro.crypto.state", encrypted_state, "");
1543 if ( master_key_saved || strcmp(encrypted_state, "encrypted") ) {
1544 SLOGE("encrypted fs already validated or not running with encryption,"
Captain Throwbacka5283b32020-02-19 12:11:23 -05001545 " aborting\n");
Ethan Yonker98661c12018-10-17 08:39:28 -05001546 return -1;
1547 }
1548
1549 if (get_crypt_ftr_and_key(crypt_ftr)) {
Captain Throwbacka5283b32020-02-19 12:11:23 -05001550 SLOGE("Error getting crypt footer and key\n");
Ethan Yonker98661c12018-10-17 08:39:28 -05001551 return -1;
1552 }
1553
1554 return 0;
1555}
1556
1557#ifdef CONFIG_HW_DISK_ENCRYPTION
1558int cryptfs_check_passwd_hw(const char* passwd)
1559{
1560 struct crypt_mnt_ftr crypt_ftr;
Mohd Faraz191a6942020-02-15 22:06:14 +05301561 int rc = 0;
Ethan Yonker98661c12018-10-17 08:39:28 -05001562 unsigned char master_key[KEY_LEN_BYTES];
1563 /* get key */
1564 if (get_crypt_ftr_and_key(&crypt_ftr)) {
Captain Throwbacka5283b32020-02-19 12:11:23 -05001565 SLOGE("Error getting crypt footer and key\n");
Ethan Yonker98661c12018-10-17 08:39:28 -05001566 return -1;
1567 }
1568
1569 /*
1570 * in case of manual encryption (from GUI), the encryption is done with
1571 * default password
1572 */
1573 if (crypt_ftr.flags & CRYPT_FORCE_COMPLETE) {
1574 /* compare scrypted_intermediate_key with stored scrypted_intermediate_key
1575 * which was created with actual password before reboot.
1576 */
1577 rc = cryptfs_get_master_key(&crypt_ftr, passwd, master_key);
1578 if (rc) {
Captain Throwbacka5283b32020-02-19 12:11:23 -05001579 SLOGE("password doesn't match\n");
Ethan Yonker98661c12018-10-17 08:39:28 -05001580 return rc;
1581 }
1582
1583 rc = test_mount_hw_encrypted_fs(&crypt_ftr, DEFAULT_PASSWORD,
1584 DATA_MNT_POINT, CRYPTO_BLOCK_DEVICE);
1585
1586 if (rc) {
Captain Throwbacka5283b32020-02-19 12:11:23 -05001587 SLOGE("Default password did not match on reboot encryption\n");
Ethan Yonker98661c12018-10-17 08:39:28 -05001588 return rc;
1589 }
1590 } else {
1591 rc = test_mount_hw_encrypted_fs(&crypt_ftr, passwd,
1592 DATA_MNT_POINT, CRYPTO_BLOCK_DEVICE);
1593 SLOGE("test mount returned %i\n", rc);
1594 }
1595
1596 return rc;
1597}
1598#endif
1599
1600int cryptfs_check_passwd(const char *passwd)
1601{
1602 /*if (e4crypt_is_native()) {
Captain Throwbacka5283b32020-02-19 12:11:23 -05001603 SLOGE("cryptfs_check_passwd not valid for file encryption\n");
Ethan Yonker98661c12018-10-17 08:39:28 -05001604 return -1;
1605 }*/
1606
1607 struct crypt_mnt_ftr crypt_ftr;
1608 int rc;
1609
1610 rc = check_unmounted_and_get_ftr(&crypt_ftr);
1611 if (rc) {
Captain Throwbacka5283b32020-02-19 12:11:23 -05001612 SLOGE("Could not get footer\n");
Ethan Yonker98661c12018-10-17 08:39:28 -05001613 return rc;
1614 }
1615
1616#ifdef CONFIG_HW_DISK_ENCRYPTION
1617 if (is_hw_disk_encryption((char*)crypt_ftr.crypto_type_name))
1618 return cryptfs_check_passwd_hw(passwd);
1619#endif
1620
1621 rc = test_mount_encrypted_fs(&crypt_ftr, passwd,
1622 DATA_MNT_POINT, CRYPTO_BLOCK_DEVICE);
1623
1624 if (rc) {
Captain Throwbacka5283b32020-02-19 12:11:23 -05001625 SLOGE("Password did not match\n");
Ethan Yonker98661c12018-10-17 08:39:28 -05001626 return rc;
1627 }
1628
1629 if (crypt_ftr.flags & CRYPT_FORCE_COMPLETE) {
1630 // Here we have a default actual password but a real password
1631 // we must test against the scrypted value
1632 // First, we must delete the crypto block device that
1633 // test_mount_encrypted_fs leaves behind as a side effect
1634 delete_crypto_blk_dev(CRYPTO_BLOCK_DEVICE);
1635 rc = test_mount_encrypted_fs(&crypt_ftr, DEFAULT_PASSWORD,
1636 DATA_MNT_POINT, CRYPTO_BLOCK_DEVICE);
1637 if (rc) {
Captain Throwbacka5283b32020-02-19 12:11:23 -05001638 SLOGE("Default password did not match on reboot encryption\n");
Ethan Yonker98661c12018-10-17 08:39:28 -05001639 return rc;
1640 }
1641 }
1642
1643 return rc;
1644}
1645
1646int cryptfs_verify_passwd(const char *passwd)
1647{
1648 struct crypt_mnt_ftr crypt_ftr;
1649 unsigned char decrypted_master_key[MAX_KEY_LEN];
1650 char encrypted_state[PROPERTY_VALUE_MAX];
1651 int rc;
1652
1653 property_get("ro.crypto.state", encrypted_state, "");
1654 if (strcmp(encrypted_state, "encrypted") ) {
Captain Throwbacka5283b32020-02-19 12:11:23 -05001655 SLOGE("device not encrypted, aborting\n");
Ethan Yonker98661c12018-10-17 08:39:28 -05001656 return -2;
1657 }
1658
1659 if (!master_key_saved) {
Captain Throwbacka5283b32020-02-19 12:11:23 -05001660 SLOGE("encrypted fs not yet mounted, aborting\n");
Ethan Yonker98661c12018-10-17 08:39:28 -05001661 return -1;
1662 }
1663
1664 if (!saved_mount_point) {
Captain Throwbacka5283b32020-02-19 12:11:23 -05001665 SLOGE("encrypted fs failed to save mount point, aborting\n");
Ethan Yonker98661c12018-10-17 08:39:28 -05001666 return -1;
1667 }
1668
1669 if (get_crypt_ftr_and_key(&crypt_ftr)) {
1670 SLOGE("Error getting crypt footer and key\n");
1671 return -1;
1672 }
1673
1674 if (crypt_ftr.flags & CRYPT_MNT_KEY_UNENCRYPTED) {
1675 /* If the device has no password, then just say the password is valid */
1676 rc = 0;
1677 } else {
1678#ifdef CONFIG_HW_DISK_ENCRYPTION
1679 if(is_hw_disk_encryption((char*)crypt_ftr.crypto_type_name)) {
1680 if (verify_hw_fde_passwd(passwd, &crypt_ftr) >= 0)
1681 rc = 0;
1682 else
1683 rc = -1;
1684 } else {
1685 decrypt_master_key(passwd, decrypted_master_key, &crypt_ftr, 0, 0);
1686 if (!memcmp(decrypted_master_key, saved_master_key, crypt_ftr.keysize)) {
1687 /* They match, the password is correct */
1688 rc = 0;
1689 } else {
1690 /* If incorrect, sleep for a bit to prevent dictionary attacks */
1691 sleep(1);
1692 rc = 1;
1693 }
1694 }
1695#else
1696 decrypt_master_key(passwd, decrypted_master_key, &crypt_ftr, 0, 0);
1697 if (!memcmp(decrypted_master_key, saved_master_key, crypt_ftr.keysize)) {
1698 /* They match, the password is correct */
1699 rc = 0;
1700 } else {
1701 /* If incorrect, sleep for a bit to prevent dictionary attacks */
1702 sleep(1);
1703 rc = 1;
1704 }
1705#endif
1706 }
1707
1708 return rc;
1709}
1710
1711/* Returns type of the password, default, pattern, pin or password.
1712 */
1713int cryptfs_get_password_type(void)
1714{
1715 struct crypt_mnt_ftr crypt_ftr;
1716
1717 if (get_crypt_ftr_and_key(&crypt_ftr)) {
1718 SLOGE("Error getting crypt footer and key\n");
1719 return -1;
1720 }
1721
1722 if (crypt_ftr.flags & CRYPT_INCONSISTENT_STATE) {
1723 return -1;
1724 }
1725
1726 return crypt_ftr.crypt_type;
1727}
1728
1729int cryptfs_get_master_key(struct crypt_mnt_ftr* ftr, const char* password,
1730 unsigned char* master_key)
1731{
1732 int rc;
1733
1734 unsigned char* intermediate_key = 0;
1735 size_t intermediate_key_size = 0;
1736
1737 if (password == 0 || *password == 0) {
1738 password = DEFAULT_PASSWORD;
1739 }
1740
1741 rc = decrypt_master_key(password, master_key, ftr, &intermediate_key,
1742 &intermediate_key_size);
1743
1744 if (rc) {
Captain Throwbacka5283b32020-02-19 12:11:23 -05001745 SLOGE("Can't calculate intermediate key\n");
Ethan Yonker98661c12018-10-17 08:39:28 -05001746 return rc;
1747 }
1748
1749 int N = 1 << ftr->N_factor;
1750 int r = 1 << ftr->r_factor;
1751 int p = 1 << ftr->p_factor;
1752
1753 unsigned char scrypted_intermediate_key[sizeof(ftr->scrypted_intermediate_key)];
1754
1755 rc = crypto_scrypt(intermediate_key, intermediate_key_size,
1756 ftr->salt, sizeof(ftr->salt), N, r, p,
1757 scrypted_intermediate_key,
1758 sizeof(scrypted_intermediate_key));
1759
1760 free(intermediate_key);
1761
1762 if (rc) {
Captain Throwbacka5283b32020-02-19 12:11:23 -05001763 SLOGE("Can't scrypt intermediate key\n");
Ethan Yonker98661c12018-10-17 08:39:28 -05001764 return rc;
1765 }
1766
1767 return memcmp(scrypted_intermediate_key, ftr->scrypted_intermediate_key,
1768 intermediate_key_size);
1769}
1770