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