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