blob: 97303b9b3bf60db8acecef1eb1a0b6d854eb5b78 [file] [log] [blame]
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001/*
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
Logan Chiend557d762018-05-02 11:36:45 +080023#define LOG_TAG "Cryptfs"
24
25#include "cryptfs.h"
26
27#include "EncryptInplace.h"
28#include "Ext4Crypt.h"
29#include "Keymaster.h"
30#include "Process.h"
31#include "ScryptParameters.h"
32#include "VoldUtil.h"
33#include "VolumeManager.h"
34#include "secontext.h"
35
Logan Chien3f2b1222018-05-02 11:39:03 +080036#include <android-base/properties.h>
Logan Chiend557d762018-05-02 11:36:45 +080037#include <bootloader_message/bootloader_message.h>
Logan Chien3f2b1222018-05-02 11:39:03 +080038#include <cutils/android_reboot.h>
Logan Chien3f2b1222018-05-02 11:39:03 +080039#include <cutils/properties.h>
Paul Crowley3b71fc52017-10-09 10:55:21 -070040#include <ext4_utils/ext4_crypt.h>
Tao Bao5a95ddb2016-10-05 18:01:19 -070041#include <ext4_utils/ext4_utils.h>
Logan Chien3f2b1222018-05-02 11:39:03 +080042#include <f2fs_sparseblock.h>
Ken Sumralle5032c42012-04-01 23:58:44 -070043#include <fs_mgr.h>
Logan Chien3f2b1222018-05-02 11:39:03 +080044#include <hardware_legacy/power.h>
Logan Chien188b0ab2018-04-23 13:37:39 +080045#include <log/log.h>
Ken Sumralle550f782013-08-20 13:48:23 -070046#include <logwrap/logwrap.h>
Logan Chiend557d762018-05-02 11:36:45 +080047#include <openssl/evp.h>
48#include <openssl/sha.h>
Ken Sumrallc290eaf2011-03-07 23:40:35 -080049#include <selinux/selinux.h>
Logan Chiend557d762018-05-02 11:36:45 +080050
51#include <ctype.h>
52#include <errno.h>
53#include <fcntl.h>
54#include <inttypes.h>
55#include <libgen.h>
56#include <linux/dm-ioctl.h>
57#include <linux/kdev_t.h>
58#include <math.h>
59#include <stdio.h>
60#include <stdlib.h>
61#include <string.h>
62#include <sys/ioctl.h>
63#include <sys/mount.h>
64#include <sys/param.h>
65#include <sys/stat.h>
66#include <sys/types.h>
67#include <sys/wait.h>
68#include <time.h>
69#include <unistd.h>
70
AnilKumar Chimata98dc8352018-05-11 00:25:09 +053071#ifdef CONFIG_HW_DISK_ENCRYPTION
72#include <cryptfs_hw.h>
73#endif
Wei Wang4375f1b2017-02-24 17:43:01 -080074extern "C" {
75#include <crypto_scrypt.h>
76}
Mark Salyzyn3e971272014-01-21 13:27:04 -080077
Mark Salyzyn5eecc442014-02-12 14:16:14 -080078#define UNUSED __attribute__((unused))
79
Ken Sumrall8f869aa2010-12-03 03:47:09 -080080#define DM_CRYPT_BUF_SIZE 4096
81
Jason parks70a4b3f2011-01-28 10:10:47 -060082#define HASH_COUNT 2000
Greg Kaiserc0de9c72018-02-14 20:05:54 -080083
84constexpr size_t INTERMEDIATE_KEY_LEN_BYTES = 16;
85constexpr size_t INTERMEDIATE_IV_LEN_BYTES = 16;
86constexpr size_t INTERMEDIATE_BUF_SIZE =
87 (INTERMEDIATE_KEY_LEN_BYTES + INTERMEDIATE_IV_LEN_BYTES);
88
89// SCRYPT_LEN is used by struct crypt_mnt_ftr for its intermediate key.
90static_assert(INTERMEDIATE_BUF_SIZE == SCRYPT_LEN,
91 "Mismatch of intermediate key sizes");
Jason parks70a4b3f2011-01-28 10:10:47 -060092
Ken Sumrall29d8da82011-05-18 17:20:07 -070093#define KEY_IN_FOOTER "footer"
94
AnilKumar Chimata98dc8352018-05-11 00:25:09 +053095#define DEFAULT_HEX_PASSWORD "64656661756c745f70617373776f7264"
Paul Lawrence3bd36d52015-06-09 13:37:44 -070096#define DEFAULT_PASSWORD "default_password"
Paul Lawrencef4faa572014-01-29 13:31:03 -080097
Paul Lawrence3d99eba2015-11-20 07:07:19 -080098#define CRYPTO_BLOCK_DEVICE "userdata"
99
100#define BREADCRUMB_FILE "/data/misc/vold/convert_fde"
101
Ken Sumrall29d8da82011-05-18 17:20:07 -0700102#define EXT4_FS 1
JP Abgrall62c7af32014-06-16 13:01:23 -0700103#define F2FS_FS 2
Ken Sumrall29d8da82011-05-18 17:20:07 -0700104
Ken Sumralle919efe2012-09-29 17:07:41 -0700105#define TABLE_LOAD_RETRIES 10
106
Shawn Willden47ba10d2014-09-03 17:07:06 -0600107#define RSA_KEY_SIZE 2048
108#define RSA_KEY_SIZE_BYTES (RSA_KEY_SIZE / 8)
109#define RSA_EXPONENT 0x10001
Shawn Willdenda6e8992015-06-03 09:40:45 -0600110#define KEYMASTER_CRYPTFS_RATE_LIMIT 1 // Maximum one try per second
AnilKumar Chimata98dc8352018-05-11 00:25:09 +0530111#define KEY_LEN_BYTES 16
Paul Lawrence69f4ebd2014-04-14 12:17:14 -0700112
Paul Lawrence8e3f4512014-09-08 10:11:17 -0700113#define RETRY_MOUNT_ATTEMPTS 10
114#define RETRY_MOUNT_DELAY_SECONDS 1
115
Paul Crowley5afbc622017-11-27 09:42:17 -0800116#define CREATE_CRYPTO_BLK_DEV_FLAGS_ALLOW_ENCRYPT_OVERRIDE (1)
117
Paul Crowley73473332017-11-21 15:43:51 -0800118static int put_crypt_ftr_and_key(struct crypt_mnt_ftr* crypt_ftr);
119
Greg Kaiser59ad0182018-02-16 13:01:36 -0800120static unsigned char saved_master_key[MAX_KEY_LEN];
Ken Sumrall3ad90722011-10-04 20:38:29 -0700121static char *saved_mount_point;
Jason parks70a4b3f2011-01-28 10:10:47 -0600122static int master_key_saved = 0;
Ken Sumrall160b4d62013-04-22 12:15:39 -0700123static struct crypt_persist_data *persist_data = NULL;
Ken Sumrall56ad03c2013-02-13 13:00:19 -0800124
AnilKumar Chimata98dc8352018-05-11 00:25:09 +0530125static int previous_type;
126
127#ifdef CONFIG_HW_DISK_ENCRYPTION
128static int scrypt_keymaster(const char *passwd, const unsigned char *salt,
129 unsigned char *ikey, void *params);
130static void convert_key_to_hex_ascii(const unsigned char *master_key,
131 unsigned int keysize, char *master_key_ascii);
132static int put_crypt_ftr_and_key(struct crypt_mnt_ftr *crypt_ftr);
133static int test_mount_hw_encrypted_fs(struct crypt_mnt_ftr* crypt_ftr,
134 const char *passwd, const char *mount_point, const char *label);
135int cryptfs_changepw_hw_fde(int crypt_type, const char *currentpw,
136 const char *newpw);
137int cryptfs_check_passwd_hw(char *passwd);
138int cryptfs_get_master_key(struct crypt_mnt_ftr* ftr, const char* password,
139 unsigned char* master_key);
140
141static void convert_key_to_hex_ascii_for_upgrade(const unsigned char *master_key,
142 unsigned int keysize, char *master_key_ascii)
143{
144 unsigned int i, a;
145 unsigned char nibble;
146
147 for (i = 0, a = 0; i < keysize; i++, a += 2) {
148 /* For each byte, write out two ascii hex digits */
149 nibble = (master_key[i] >> 4) & 0xf;
150 master_key_ascii[a] = nibble + (nibble > 9 ? 0x57 : 0x30);
151
152 nibble = master_key[i] & 0xf;
153 master_key_ascii[a + 1] = nibble + (nibble > 9 ? 0x57 : 0x30);
154 }
155
156 /* Add the null termination */
157 master_key_ascii[a] = '\0';
158}
159
160static int get_keymaster_hw_fde_passwd(const char* passwd, unsigned char* newpw,
161 unsigned char* salt,
162 const struct crypt_mnt_ftr *ftr)
163{
164 /* if newpw updated, return 0
165 * if newpw not updated return -1
166 */
167 int rc = -1;
168
169 if (should_use_keymaster()) {
170 if (scrypt_keymaster(passwd, salt, newpw, (void*)ftr)) {
171 SLOGE("scrypt failed");
172 } else {
173 rc = 0;
174 }
175 }
176
177 return rc;
178}
179
180static int verify_hw_fde_passwd(const char *passwd, struct crypt_mnt_ftr* crypt_ftr)
181{
182 unsigned char newpw[32] = {0};
183 int key_index;
184 if (get_keymaster_hw_fde_passwd(passwd, newpw, crypt_ftr->salt, crypt_ftr))
185 key_index = set_hw_device_encryption_key(passwd,
186 (char*) crypt_ftr->crypto_type_name);
187 else
188 key_index = set_hw_device_encryption_key((const char*)newpw,
189 (char*) crypt_ftr->crypto_type_name);
190 return key_index;
191}
192
193static int verify_and_update_hw_fde_passwd(const char *passwd,
194 struct crypt_mnt_ftr* crypt_ftr)
195{
196 char* new_passwd = NULL;
197 unsigned char newpw[32] = {0};
198 int key_index = -1;
199 int passwd_updated = -1;
200 int ascii_passwd_updated = (crypt_ftr->flags & CRYPT_ASCII_PASSWORD_UPDATED);
201
202 key_index = verify_hw_fde_passwd(passwd, crypt_ftr);
203 if (key_index < 0) {
204 ++crypt_ftr->failed_decrypt_count;
205
206 if (ascii_passwd_updated) {
207 SLOGI("Ascii password was updated");
208 } else {
209 /* Code in else part would execute only once:
210 * When device is upgraded from L->M release.
211 * Once upgraded, code flow should never come here.
212 * L release passed actual password in hex, so try with hex
213 * Each nible of passwd was encoded as a byte, so allocate memory
214 * twice of password len plus one more byte for null termination
215 */
216 if (crypt_ftr->crypt_type == CRYPT_TYPE_DEFAULT) {
217 new_passwd = (char*)malloc(strlen(DEFAULT_HEX_PASSWORD) + 1);
218 if (new_passwd == NULL) {
219 SLOGE("System out of memory. Password verification incomplete");
220 goto out;
221 }
222 strlcpy(new_passwd, DEFAULT_HEX_PASSWORD, strlen(DEFAULT_HEX_PASSWORD) + 1);
223 } else {
224 new_passwd = (char*)malloc(strlen(passwd) * 2 + 1);
225 if (new_passwd == NULL) {
226 SLOGE("System out of memory. Password verification incomplete");
227 goto out;
228 }
229 convert_key_to_hex_ascii_for_upgrade((const unsigned char*)passwd,
230 strlen(passwd), new_passwd);
231 }
232 key_index = set_hw_device_encryption_key((const char*)new_passwd,
233 (char*) crypt_ftr->crypto_type_name);
234 if (key_index >=0) {
235 crypt_ftr->failed_decrypt_count = 0;
236 SLOGI("Hex password verified...will try to update with Ascii value");
237 /* Before updating password, tie that with keymaster to tie with ROT */
238
239 if (get_keymaster_hw_fde_passwd(passwd, newpw,
240 crypt_ftr->salt, crypt_ftr)) {
241 passwd_updated = update_hw_device_encryption_key(new_passwd,
242 passwd, (char*)crypt_ftr->crypto_type_name);
243 } else {
244 passwd_updated = update_hw_device_encryption_key(new_passwd,
245 (const char*)newpw, (char*)crypt_ftr->crypto_type_name);
246 }
247
248 if (passwd_updated >= 0) {
249 crypt_ftr->flags |= CRYPT_ASCII_PASSWORD_UPDATED;
250 SLOGI("Ascii password recorded and updated");
251 } else {
252 SLOGI("Passwd verified, could not update...Will try next time");
253 }
254 } else {
255 ++crypt_ftr->failed_decrypt_count;
256 }
257 free(new_passwd);
258 }
259 } else {
260 if (!ascii_passwd_updated)
261 crypt_ftr->flags |= CRYPT_ASCII_PASSWORD_UPDATED;
262 }
263out:
264 // update footer before leaving
265 put_crypt_ftr_and_key(crypt_ftr);
266 return key_index;
267}
268#endif
269
Paul Lawrence69f4ebd2014-04-14 12:17:14 -0700270/* Should we use keymaster? */
271static int keymaster_check_compatibility()
272{
Janis Danisevskis015ec302017-01-31 11:31:08 +0000273 return keymaster_compatibility_cryptfs_scrypt();
Paul Lawrence69f4ebd2014-04-14 12:17:14 -0700274}
275
276/* Create a new keymaster key and store it in this footer */
277static int keymaster_create_key(struct crypt_mnt_ftr *ftr)
278{
Paul Lawrence3d99eba2015-11-20 07:07:19 -0800279 if (ftr->keymaster_blob_size) {
280 SLOGI("Already have key");
281 return 0;
282 }
283
Janis Danisevskis015ec302017-01-31 11:31:08 +0000284 int rc = keymaster_create_key_for_cryptfs_scrypt(RSA_KEY_SIZE, RSA_EXPONENT,
285 KEYMASTER_CRYPTFS_RATE_LIMIT, ftr->keymaster_blob, KEYMASTER_BLOB_SIZE,
286 &ftr->keymaster_blob_size);
287 if (rc) {
288 if (ftr->keymaster_blob_size > KEYMASTER_BLOB_SIZE) {
Paul Crowley73473332017-11-21 15:43:51 -0800289 SLOGE("Keymaster key blob too large");
Janis Danisevskis015ec302017-01-31 11:31:08 +0000290 ftr->keymaster_blob_size = 0;
291 }
292 SLOGE("Failed to generate keypair");
Paul Lawrence69f4ebd2014-04-14 12:17:14 -0700293 return -1;
294 }
Janis Danisevskis015ec302017-01-31 11:31:08 +0000295 return 0;
Paul Lawrence69f4ebd2014-04-14 12:17:14 -0700296}
297
Shawn Willdene17a9c42014-09-08 13:04:08 -0600298/* This signs the given object using the keymaster key. */
299static int keymaster_sign_object(struct crypt_mnt_ftr *ftr,
Shawn Willden47ba10d2014-09-03 17:07:06 -0600300 const unsigned char *object,
301 const size_t object_size,
302 unsigned char **signature,
303 size_t *signature_size)
304{
Shawn Willden47ba10d2014-09-03 17:07:06 -0600305 unsigned char to_sign[RSA_KEY_SIZE_BYTES];
Shawn Willdene17a9c42014-09-08 13:04:08 -0600306 size_t to_sign_size = sizeof(to_sign);
Shawn Willden47ba10d2014-09-03 17:07:06 -0600307 memset(to_sign, 0, RSA_KEY_SIZE_BYTES);
Shawn Willden47ba10d2014-09-03 17:07:06 -0600308
Shawn Willdene17a9c42014-09-08 13:04:08 -0600309 // To sign a message with RSA, the message must satisfy two
310 // constraints:
311 //
312 // 1. The message, when interpreted as a big-endian numeric value, must
313 // be strictly less than the public modulus of the RSA key. Note
314 // that because the most significant bit of the public modulus is
315 // guaranteed to be 1 (else it's an (n-1)-bit key, not an n-bit
316 // key), an n-bit message with most significant bit 0 always
317 // satisfies this requirement.
318 //
319 // 2. The message must have the same length in bits as the public
320 // modulus of the RSA key. This requirement isn't mathematically
321 // necessary, but is necessary to ensure consistency in
322 // implementations.
323 switch (ftr->kdf_type) {
Shawn Willdene17a9c42014-09-08 13:04:08 -0600324 case KDF_SCRYPT_KEYMASTER:
325 // This ensures the most significant byte of the signed message
326 // is zero. We could have zero-padded to the left instead, but
327 // this approach is slightly more robust against changes in
328 // object size. However, it's still broken (but not unusably
Shawn Willdenda6e8992015-06-03 09:40:45 -0600329 // so) because we really should be using a proper deterministic
330 // RSA padding function, such as PKCS1.
Wei Wang4375f1b2017-02-24 17:43:01 -0800331 memcpy(to_sign + 1, object, std::min((size_t)RSA_KEY_SIZE_BYTES - 1, object_size));
Shawn Willdene17a9c42014-09-08 13:04:08 -0600332 SLOGI("Signing safely-padded object");
333 break;
334 default:
335 SLOGE("Unknown KDF type %d", ftr->kdf_type);
Janis Danisevskis015ec302017-01-31 11:31:08 +0000336 return -1;
Shawn Willdene17a9c42014-09-08 13:04:08 -0600337 }
Paul Crowley73473332017-11-21 15:43:51 -0800338 for (;;) {
339 auto result = keymaster_sign_object_for_cryptfs_scrypt(
340 ftr->keymaster_blob, ftr->keymaster_blob_size, KEYMASTER_CRYPTFS_RATE_LIMIT, to_sign,
341 to_sign_size, signature, signature_size);
342 switch (result) {
343 case KeymasterSignResult::ok:
344 return 0;
345 case KeymasterSignResult::upgrade:
346 break;
347 default:
348 return -1;
349 }
350 SLOGD("Upgrading key");
351 if (keymaster_upgrade_key_for_cryptfs_scrypt(
352 RSA_KEY_SIZE, RSA_EXPONENT, KEYMASTER_CRYPTFS_RATE_LIMIT, ftr->keymaster_blob,
353 ftr->keymaster_blob_size, ftr->keymaster_blob, KEYMASTER_BLOB_SIZE,
354 &ftr->keymaster_blob_size) != 0) {
355 SLOGE("Failed to upgrade key");
356 return -1;
357 }
358 if (put_crypt_ftr_and_key(ftr) != 0) {
359 SLOGE("Failed to write upgraded key to disk");
360 }
361 SLOGD("Key upgraded successfully");
362 }
Shawn Willden47ba10d2014-09-03 17:07:06 -0600363}
364
Paul Lawrence399317e2014-03-10 13:20:50 -0700365/* Store password when userdata is successfully decrypted and mounted.
366 * Cleared by cryptfs_clear_password
367 *
368 * To avoid a double prompt at boot, we need to store the CryptKeeper
369 * password and pass it to KeyGuard, which uses it to unlock KeyStore.
370 * Since the entire framework is torn down and rebuilt after encryption,
371 * we have to use a daemon or similar to store the password. Since vold
372 * is secured against IPC except from system processes, it seems a reasonable
373 * place to store this.
374 *
375 * password should be cleared once it has been used.
376 *
377 * password is aged out after password_max_age_seconds seconds.
Paul Lawrence684dbdf2014-02-07 12:07:22 -0800378 */
Paul Lawrence399317e2014-03-10 13:20:50 -0700379static char* password = 0;
380static int password_expiry_time = 0;
381static const int password_max_age_seconds = 60;
Paul Lawrence684dbdf2014-02-07 12:07:22 -0800382
Josh Gaofec44372017-08-28 13:22:55 -0700383enum class RebootType {reboot, recovery, shutdown};
384static void cryptfs_reboot(RebootType rt)
Ken Sumralladfba362013-06-04 16:37:52 -0700385{
Josh Gaofec44372017-08-28 13:22:55 -0700386 switch (rt) {
387 case RebootType::reboot:
Paul Lawrence87999172014-02-20 12:21:31 -0800388 property_set(ANDROID_RB_PROPERTY, "reboot");
389 break;
390
Josh Gaofec44372017-08-28 13:22:55 -0700391 case RebootType::recovery:
Paul Lawrence87999172014-02-20 12:21:31 -0800392 property_set(ANDROID_RB_PROPERTY, "reboot,recovery");
393 break;
394
Josh Gaofec44372017-08-28 13:22:55 -0700395 case RebootType::shutdown:
Paul Lawrence87999172014-02-20 12:21:31 -0800396 property_set(ANDROID_RB_PROPERTY, "shutdown");
397 break;
Ken Sumralladfba362013-06-04 16:37:52 -0700398 }
Paul Lawrence87999172014-02-20 12:21:31 -0800399
Ken Sumralladfba362013-06-04 16:37:52 -0700400 sleep(20);
401
402 /* Shouldn't get here, reboot should happen before sleep times out */
403 return;
404}
405
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800406static void ioctl_init(struct dm_ioctl *io, size_t dataSize, const char *name, unsigned flags)
407{
408 memset(io, 0, dataSize);
409 io->data_size = dataSize;
410 io->data_start = sizeof(struct dm_ioctl);
411 io->version[0] = 4;
412 io->version[1] = 0;
413 io->version[2] = 0;
414 io->flags = flags;
415 if (name) {
Marek Pola5e6b9142015-02-05 14:22:34 +0100416 strlcpy(io->name, name, sizeof(io->name));
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800417 }
418}
419
Greg Kaiser38723f22018-02-16 13:35:35 -0800420namespace {
421
422struct CryptoType;
423
424// Use to get the CryptoType in use on this device.
425const CryptoType &get_crypto_type();
426
427struct CryptoType {
428 // We should only be constructing CryptoTypes as part of
429 // supported_crypto_types[]. We do it via this pseudo-builder pattern,
430 // which isn't pure or fully protected as a concession to being able to
431 // do it all at compile time. Add new CryptoTypes in
432 // supported_crypto_types[] below.
433 constexpr CryptoType() : CryptoType(nullptr, nullptr, 0xFFFFFFFF) {}
434 constexpr CryptoType set_keysize(uint32_t size) const {
435 return CryptoType(this->property_name, this->crypto_name, size);
436 }
437 constexpr CryptoType set_property_name(const char *property) const {
438 return CryptoType(property, this->crypto_name, this->keysize);
439 }
440 constexpr CryptoType set_crypto_name(const char *crypto) const {
441 return CryptoType(this->property_name, crypto, this->keysize);
442 }
443
444 constexpr const char *get_property_name() const { return property_name; }
445 constexpr const char *get_crypto_name() const { return crypto_name; }
446 constexpr uint32_t get_keysize() const { return keysize; }
447
448 private:
449 const char *property_name;
450 const char *crypto_name;
451 uint32_t keysize;
452
453 constexpr CryptoType(const char *property, const char *crypto,
454 uint32_t ksize)
455 : property_name(property), crypto_name(crypto), keysize(ksize) {}
456 friend const CryptoType &get_crypto_type();
457 static const CryptoType &get_device_crypto_algorithm();
458};
459
460// We only want to parse this read-only property once. But we need to wait
461// until the system is initialized before we can read it. So we use a static
462// scoped within this function to get it only once.
463const CryptoType &get_crypto_type() {
464 static CryptoType crypto_type = CryptoType::get_device_crypto_algorithm();
465 return crypto_type;
466}
467
468constexpr CryptoType default_crypto_type = CryptoType()
469 .set_property_name("AES-128-CBC")
470 .set_crypto_name("aes-cbc-essiv:sha256")
471 .set_keysize(16);
472
473constexpr CryptoType supported_crypto_types[] = {
474 default_crypto_type,
Greg Kaiser38723f22018-02-16 13:35:35 -0800475 // Add new CryptoTypes here. Order is not important.
476};
477
478
479// ---------- START COMPILE-TIME SANITY CHECK BLOCK -------------------------
480// We confirm all supported_crypto_types have a small enough keysize and
481// had both set_property_name() and set_crypto_name() called.
482
483template <typename T, size_t N>
484constexpr size_t array_length(T (&)[N]) { return N; }
485
486constexpr bool indexOutOfBoundsForCryptoTypes(size_t index) {
487 return (index >= array_length(supported_crypto_types));
488}
489
490constexpr bool isValidCryptoType(const CryptoType &crypto_type) {
491 return ((crypto_type.get_property_name() != nullptr) &&
492 (crypto_type.get_crypto_name() != nullptr) &&
493 (crypto_type.get_keysize() <= MAX_KEY_LEN));
494}
495
496// Note in C++11 that constexpr functions can only have a single line.
497// So our code is a bit convoluted (using recursion instead of a loop),
498// but it's asserting at compile time that all of our key lengths are valid.
499constexpr bool validateSupportedCryptoTypes(size_t index) {
500 return indexOutOfBoundsForCryptoTypes(index) ||
501 (isValidCryptoType(supported_crypto_types[index]) &&
502 validateSupportedCryptoTypes(index + 1));
503}
504
505static_assert(validateSupportedCryptoTypes(0),
506 "We have a CryptoType with keysize > MAX_KEY_LEN or which was "
507 "incompletely constructed.");
508// ---------- END COMPILE-TIME SANITY CHECK BLOCK -------------------------
509
510
511// Don't call this directly, use get_crypto_type(), which caches this result.
512const CryptoType &CryptoType::get_device_crypto_algorithm() {
513 constexpr char CRYPT_ALGO_PROP[] = "ro.crypto.fde_algorithm";
514 char paramstr[PROPERTY_VALUE_MAX];
515
516 property_get(CRYPT_ALGO_PROP, paramstr,
517 default_crypto_type.get_property_name());
518 for (auto const &ctype : supported_crypto_types) {
519 if (strcmp(paramstr, ctype.get_property_name()) == 0) {
520 return ctype;
521 }
522 }
523 ALOGE("Invalid name (%s) for %s. Defaulting to %s\n", paramstr,
524 CRYPT_ALGO_PROP, default_crypto_type.get_property_name());
525 return default_crypto_type;
526}
527
528} // namespace
529
530
531
Kenny Rootc4c70f12013-06-14 12:11:38 -0700532/**
533 * Gets the default device scrypt parameters for key derivation time tuning.
534 * The parameters should lead to about one second derivation time for the
535 * given device.
536 */
537static void get_device_scrypt_params(struct crypt_mnt_ftr *ftr) {
Kenny Rootc4c70f12013-06-14 12:11:38 -0700538 char paramstr[PROPERTY_VALUE_MAX];
Paul Crowley63c18d32016-02-10 14:02:47 +0000539 int Nf, rf, pf;
Kenny Rootc4c70f12013-06-14 12:11:38 -0700540
Paul Crowley63c18d32016-02-10 14:02:47 +0000541 property_get(SCRYPT_PROP, paramstr, SCRYPT_DEFAULTS);
542 if (!parse_scrypt_parameters(paramstr, &Nf, &rf, &pf)) {
543 SLOGW("bad scrypt parameters '%s' should be like '12:8:1'; using defaults", paramstr);
544 parse_scrypt_parameters(SCRYPT_DEFAULTS, &Nf, &rf, &pf);
Kenny Rootc4c70f12013-06-14 12:11:38 -0700545 }
Paul Crowley63c18d32016-02-10 14:02:47 +0000546 ftr->N_factor = Nf;
547 ftr->r_factor = rf;
548 ftr->p_factor = pf;
Kenny Rootc4c70f12013-06-14 12:11:38 -0700549}
550
Greg Kaiser57f9af62018-02-16 13:13:58 -0800551uint32_t cryptfs_get_keysize() {
Greg Kaiser38723f22018-02-16 13:35:35 -0800552 return get_crypto_type().get_keysize();
Greg Kaiser57f9af62018-02-16 13:13:58 -0800553}
554
555const char *cryptfs_get_crypto_name() {
Greg Kaiser38723f22018-02-16 13:35:35 -0800556 return get_crypto_type().get_crypto_name();
Greg Kaiser57f9af62018-02-16 13:13:58 -0800557}
558
Ken Sumrall3ed82362011-01-28 23:31:16 -0800559static unsigned int get_fs_size(char *dev)
560{
561 int fd, block_size;
562 struct ext4_super_block sb;
563 off64_t len;
564
Jeff Sharkeyce6a9132015-04-08 21:07:21 -0700565 if ((fd = open(dev, O_RDONLY|O_CLOEXEC)) < 0) {
Ken Sumrall3ed82362011-01-28 23:31:16 -0800566 SLOGE("Cannot open device to get filesystem size ");
567 return 0;
568 }
569
570 if (lseek64(fd, 1024, SEEK_SET) < 0) {
571 SLOGE("Cannot seek to superblock");
572 return 0;
573 }
574
575 if (read(fd, &sb, sizeof(sb)) != sizeof(sb)) {
576 SLOGE("Cannot read superblock");
577 return 0;
578 }
579
580 close(fd);
581
Daniel Rosenberge82df162014-08-15 22:19:23 +0000582 if (le32_to_cpu(sb.s_magic) != EXT4_SUPER_MAGIC) {
583 SLOGE("Not a valid ext4 superblock");
584 return 0;
585 }
Ken Sumrall3ed82362011-01-28 23:31:16 -0800586 block_size = 1024 << sb.s_log_block_size;
587 /* compute length in bytes */
588 len = ( ((off64_t)sb.s_blocks_count_hi << 32) + sb.s_blocks_count_lo) * block_size;
589
590 /* return length in sectors */
591 return (unsigned int) (len / 512);
592}
593
Ken Sumrall160b4d62013-04-22 12:15:39 -0700594static int get_crypt_ftr_info(char **metadata_fname, off64_t *off)
595{
596 static int cached_data = 0;
597 static off64_t cached_off = 0;
598 static char cached_metadata_fname[PROPERTY_VALUE_MAX] = "";
599 int fd;
600 char key_loc[PROPERTY_VALUE_MAX];
601 char real_blkdev[PROPERTY_VALUE_MAX];
Ken Sumrall160b4d62013-04-22 12:15:39 -0700602 int rc = -1;
603
604 if (!cached_data) {
Paul Crowleye2ee1522017-09-26 14:05:26 -0700605 fs_mgr_get_crypt_info(fstab_default, key_loc, real_blkdev, sizeof(key_loc));
Ken Sumrall160b4d62013-04-22 12:15:39 -0700606
607 if (!strcmp(key_loc, KEY_IN_FOOTER)) {
Jeff Sharkeyce6a9132015-04-08 21:07:21 -0700608 if ( (fd = open(real_blkdev, O_RDWR|O_CLOEXEC)) < 0) {
Ken Sumrall160b4d62013-04-22 12:15:39 -0700609 SLOGE("Cannot open real block device %s\n", real_blkdev);
610 return -1;
611 }
612
Hiroaki Miyazawa14eab552015-02-04 13:29:15 +0900613 unsigned long nr_sec = 0;
614 get_blkdev_size(fd, &nr_sec);
615 if (nr_sec != 0) {
Ken Sumrall160b4d62013-04-22 12:15:39 -0700616 /* If it's an encrypted Android partition, the last 16 Kbytes contain the
617 * encryption info footer and key, and plenty of bytes to spare for future
618 * growth.
619 */
620 strlcpy(cached_metadata_fname, real_blkdev, sizeof(cached_metadata_fname));
621 cached_off = ((off64_t)nr_sec * 512) - CRYPT_FOOTER_OFFSET;
622 cached_data = 1;
623 } else {
624 SLOGE("Cannot get size of block device %s\n", real_blkdev);
625 }
626 close(fd);
627 } else {
628 strlcpy(cached_metadata_fname, key_loc, sizeof(cached_metadata_fname));
629 cached_off = 0;
630 cached_data = 1;
631 }
632 }
633
634 if (cached_data) {
635 if (metadata_fname) {
636 *metadata_fname = cached_metadata_fname;
637 }
638 if (off) {
639 *off = cached_off;
640 }
641 rc = 0;
642 }
643
644 return rc;
645}
646
Paul Lawrence3d99eba2015-11-20 07:07:19 -0800647/* Set sha256 checksum in structure */
648static void set_ftr_sha(struct crypt_mnt_ftr *crypt_ftr)
649{
650 SHA256_CTX c;
651 SHA256_Init(&c);
652 memset(crypt_ftr->sha256, 0, sizeof(crypt_ftr->sha256));
653 SHA256_Update(&c, crypt_ftr, sizeof(*crypt_ftr));
654 SHA256_Final(crypt_ftr->sha256, &c);
655}
656
Ken Sumralle8744072011-01-18 22:01:55 -0800657/* key or salt can be NULL, in which case just skip writing that value. Useful to
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800658 * update the failed mount count but not change the key.
659 */
Ken Sumrall160b4d62013-04-22 12:15:39 -0700660static int put_crypt_ftr_and_key(struct crypt_mnt_ftr *crypt_ftr)
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800661{
662 int fd;
Tim Murray8439dc92014-12-15 11:56:11 -0800663 unsigned int cnt;
Ken Sumrall160b4d62013-04-22 12:15:39 -0700664 /* starting_off is set to the SEEK_SET offset
665 * where the crypto structure starts
666 */
667 off64_t starting_off;
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800668 int rc = -1;
Ken Sumrall160b4d62013-04-22 12:15:39 -0700669 char *fname = NULL;
Ken Sumrall3be890f2011-09-14 16:53:46 -0700670 struct stat statbuf;
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800671
Paul Lawrence3d99eba2015-11-20 07:07:19 -0800672 set_ftr_sha(crypt_ftr);
673
Ken Sumrall160b4d62013-04-22 12:15:39 -0700674 if (get_crypt_ftr_info(&fname, &starting_off)) {
675 SLOGE("Unable to get crypt_ftr_info\n");
676 return -1;
677 }
678 if (fname[0] != '/') {
Ken Sumralle5032c42012-04-01 23:58:44 -0700679 SLOGE("Unexpected value for crypto key location\n");
Ken Sumrall160b4d62013-04-22 12:15:39 -0700680 return -1;
681 }
Jeff Sharkeyce6a9132015-04-08 21:07:21 -0700682 if ( (fd = open(fname, O_RDWR | O_CREAT|O_CLOEXEC, 0600)) < 0) {
Ken Sumralle550f782013-08-20 13:48:23 -0700683 SLOGE("Cannot open footer file %s for put\n", fname);
Ken Sumrall160b4d62013-04-22 12:15:39 -0700684 return -1;
685 }
686
687 /* Seek to the start of the crypt footer */
688 if (lseek64(fd, starting_off, SEEK_SET) == -1) {
689 SLOGE("Cannot seek to real block device footer\n");
690 goto errout;
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800691 }
692
693 if ((cnt = write(fd, crypt_ftr, sizeof(struct crypt_mnt_ftr))) != sizeof(struct crypt_mnt_ftr)) {
694 SLOGE("Cannot write real block device footer\n");
695 goto errout;
696 }
697
Ken Sumrall3be890f2011-09-14 16:53:46 -0700698 fstat(fd, &statbuf);
699 /* If the keys are kept on a raw block device, do not try to truncate it. */
Ken Sumralle550f782013-08-20 13:48:23 -0700700 if (S_ISREG(statbuf.st_mode)) {
Ken Sumrall29d8da82011-05-18 17:20:07 -0700701 if (ftruncate(fd, 0x4000)) {
Colin Cross59846b62014-02-06 20:34:29 -0800702 SLOGE("Cannot set footer file size\n");
Ken Sumralle8744072011-01-18 22:01:55 -0800703 goto errout;
704 }
705 }
706
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800707 /* Success! */
708 rc = 0;
709
710errout:
711 close(fd);
712 return rc;
713
714}
715
Paul Lawrence3d99eba2015-11-20 07:07:19 -0800716static bool check_ftr_sha(const struct crypt_mnt_ftr *crypt_ftr)
717{
718 struct crypt_mnt_ftr copy;
719 memcpy(&copy, crypt_ftr, sizeof(copy));
720 set_ftr_sha(&copy);
721 return memcmp(copy.sha256, crypt_ftr->sha256, sizeof(copy.sha256)) == 0;
722}
723
Ken Sumrall160b4d62013-04-22 12:15:39 -0700724static inline int unix_read(int fd, void* buff, int len)
725{
726 return TEMP_FAILURE_RETRY(read(fd, buff, len));
727}
728
729static inline int unix_write(int fd, const void* buff, int len)
730{
731 return TEMP_FAILURE_RETRY(write(fd, buff, len));
732}
733
734static void init_empty_persist_data(struct crypt_persist_data *pdata, int len)
735{
736 memset(pdata, 0, len);
737 pdata->persist_magic = PERSIST_DATA_MAGIC;
738 pdata->persist_valid_entries = 0;
739}
740
741/* A routine to update the passed in crypt_ftr to the lastest version.
742 * fd is open read/write on the device that holds the crypto footer and persistent
743 * data, crypt_ftr is a pointer to the struct to be updated, and offset is the
744 * absolute offset to the start of the crypt_mnt_ftr on the passed in fd.
745 */
746static void upgrade_crypt_ftr(int fd, struct crypt_mnt_ftr *crypt_ftr, off64_t offset)
747{
Kenny Root7434b312013-06-14 11:29:53 -0700748 int orig_major = crypt_ftr->major_version;
749 int orig_minor = crypt_ftr->minor_version;
Ken Sumrall160b4d62013-04-22 12:15:39 -0700750
Kenny Root7434b312013-06-14 11:29:53 -0700751 if ((crypt_ftr->major_version == 1) && (crypt_ftr->minor_version == 0)) {
752 struct crypt_persist_data *pdata;
753 off64_t pdata_offset = offset + CRYPT_FOOTER_TO_PERSIST_OFFSET;
Ken Sumrall160b4d62013-04-22 12:15:39 -0700754
Kenny Rootc4c70f12013-06-14 12:11:38 -0700755 SLOGW("upgrading crypto footer to 1.1");
756
Wei Wang4375f1b2017-02-24 17:43:01 -0800757 pdata = (crypt_persist_data *)malloc(CRYPT_PERSIST_DATA_SIZE);
Kenny Root7434b312013-06-14 11:29:53 -0700758 if (pdata == NULL) {
759 SLOGE("Cannot allocate persisent data\n");
760 return;
761 }
762 memset(pdata, 0, CRYPT_PERSIST_DATA_SIZE);
763
764 /* Need to initialize the persistent data area */
765 if (lseek64(fd, pdata_offset, SEEK_SET) == -1) {
766 SLOGE("Cannot seek to persisent data offset\n");
Henrik Baard91064632015-02-05 15:09:17 +0100767 free(pdata);
Kenny Root7434b312013-06-14 11:29:53 -0700768 return;
769 }
770 /* Write all zeros to the first copy, making it invalid */
771 unix_write(fd, pdata, CRYPT_PERSIST_DATA_SIZE);
772
773 /* Write a valid but empty structure to the second copy */
774 init_empty_persist_data(pdata, CRYPT_PERSIST_DATA_SIZE);
775 unix_write(fd, pdata, CRYPT_PERSIST_DATA_SIZE);
776
777 /* Update the footer */
778 crypt_ftr->persist_data_size = CRYPT_PERSIST_DATA_SIZE;
779 crypt_ftr->persist_data_offset[0] = pdata_offset;
780 crypt_ftr->persist_data_offset[1] = pdata_offset + CRYPT_PERSIST_DATA_SIZE;
781 crypt_ftr->minor_version = 1;
Henrik Baard91064632015-02-05 15:09:17 +0100782 free(pdata);
Ken Sumrall160b4d62013-04-22 12:15:39 -0700783 }
784
Paul Lawrencef4faa572014-01-29 13:31:03 -0800785 if ((crypt_ftr->major_version == 1) && (crypt_ftr->minor_version == 1)) {
Kenny Rootc4c70f12013-06-14 12:11:38 -0700786 SLOGW("upgrading crypto footer to 1.2");
JP Abgrall7bdfa522013-11-15 13:42:56 -0800787 /* But keep the old kdf_type.
788 * It will get updated later to KDF_SCRYPT after the password has been verified.
789 */
Kenny Rootc4c70f12013-06-14 12:11:38 -0700790 crypt_ftr->kdf_type = KDF_PBKDF2;
791 get_device_scrypt_params(crypt_ftr);
792 crypt_ftr->minor_version = 2;
793 }
794
Paul Lawrencef4faa572014-01-29 13:31:03 -0800795 if ((crypt_ftr->major_version == 1) && (crypt_ftr->minor_version == 2)) {
796 SLOGW("upgrading crypto footer to 1.3");
797 crypt_ftr->crypt_type = CRYPT_TYPE_PASSWORD;
798 crypt_ftr->minor_version = 3;
799 }
800
Kenny Root7434b312013-06-14 11:29:53 -0700801 if ((orig_major != crypt_ftr->major_version) || (orig_minor != crypt_ftr->minor_version)) {
802 if (lseek64(fd, offset, SEEK_SET) == -1) {
803 SLOGE("Cannot seek to crypt footer\n");
804 return;
805 }
806 unix_write(fd, crypt_ftr, sizeof(struct crypt_mnt_ftr));
Ken Sumrall160b4d62013-04-22 12:15:39 -0700807 }
Ken Sumrall160b4d62013-04-22 12:15:39 -0700808}
809
810
811static int get_crypt_ftr_and_key(struct crypt_mnt_ftr *crypt_ftr)
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800812{
813 int fd;
Tim Murray8439dc92014-12-15 11:56:11 -0800814 unsigned int cnt;
Ken Sumrall160b4d62013-04-22 12:15:39 -0700815 off64_t starting_off;
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800816 int rc = -1;
Ken Sumrall160b4d62013-04-22 12:15:39 -0700817 char *fname = NULL;
Ken Sumrall29d8da82011-05-18 17:20:07 -0700818 struct stat statbuf;
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800819
Ken Sumrall160b4d62013-04-22 12:15:39 -0700820 if (get_crypt_ftr_info(&fname, &starting_off)) {
821 SLOGE("Unable to get crypt_ftr_info\n");
822 return -1;
823 }
824 if (fname[0] != '/') {
Ken Sumralle5032c42012-04-01 23:58:44 -0700825 SLOGE("Unexpected value for crypto key location\n");
Ken Sumrall160b4d62013-04-22 12:15:39 -0700826 return -1;
827 }
Jeff Sharkeyce6a9132015-04-08 21:07:21 -0700828 if ( (fd = open(fname, O_RDWR|O_CLOEXEC)) < 0) {
Ken Sumralle550f782013-08-20 13:48:23 -0700829 SLOGE("Cannot open footer file %s for get\n", fname);
Ken Sumrall160b4d62013-04-22 12:15:39 -0700830 return -1;
831 }
832
833 /* Make sure it's 16 Kbytes in length */
834 fstat(fd, &statbuf);
835 if (S_ISREG(statbuf.st_mode) && (statbuf.st_size != 0x4000)) {
836 SLOGE("footer file %s is not the expected size!\n", fname);
837 goto errout;
838 }
839
840 /* Seek to the start of the crypt footer */
841 if (lseek64(fd, starting_off, SEEK_SET) == -1) {
842 SLOGE("Cannot seek to real block device footer\n");
843 goto errout;
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800844 }
845
846 if ( (cnt = read(fd, crypt_ftr, sizeof(struct crypt_mnt_ftr))) != sizeof(struct crypt_mnt_ftr)) {
847 SLOGE("Cannot read real block device footer\n");
848 goto errout;
849 }
850
851 if (crypt_ftr->magic != CRYPT_MNT_MAGIC) {
Ken Sumrall29d8da82011-05-18 17:20:07 -0700852 SLOGE("Bad magic for real block device %s\n", fname);
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800853 goto errout;
854 }
855
Kenny Rootc96a5f82013-06-14 12:08:28 -0700856 if (crypt_ftr->major_version != CURRENT_MAJOR_VERSION) {
857 SLOGE("Cannot understand major version %d real block device footer; expected %d\n",
858 crypt_ftr->major_version, CURRENT_MAJOR_VERSION);
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800859 goto errout;
860 }
861
Greg Kaiser59ad0182018-02-16 13:01:36 -0800862 // We risk buffer overflows with oversized keys, so we just reject them.
863 // 0-sized keys are problematic (essentially by-passing encryption), and
864 // AES-CBC key wrapping only works for multiples of 16 bytes.
865 if ((crypt_ftr->keysize == 0) || ((crypt_ftr->keysize % 16) != 0) ||
866 (crypt_ftr->keysize > MAX_KEY_LEN)) {
867 SLOGE("Invalid keysize (%u) for block device %s; Must be non-zero, "
868 "divisible by 16, and <= %d\n", crypt_ftr->keysize, fname,
869 MAX_KEY_LEN);
870 goto errout;
871 }
872
Kenny Rootc96a5f82013-06-14 12:08:28 -0700873 if (crypt_ftr->minor_version > CURRENT_MINOR_VERSION) {
874 SLOGW("Warning: crypto footer minor version %d, expected <= %d, continuing...\n",
875 crypt_ftr->minor_version, CURRENT_MINOR_VERSION);
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800876 }
877
Ken Sumrall160b4d62013-04-22 12:15:39 -0700878 /* If this is a verion 1.0 crypt_ftr, make it a 1.1 crypt footer, and update the
879 * copy on disk before returning.
880 */
Kenny Rootc96a5f82013-06-14 12:08:28 -0700881 if (crypt_ftr->minor_version < CURRENT_MINOR_VERSION) {
Ken Sumrall160b4d62013-04-22 12:15:39 -0700882 upgrade_crypt_ftr(fd, crypt_ftr, starting_off);
Ken Sumralle8744072011-01-18 22:01:55 -0800883 }
884
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800885 /* Success! */
886 rc = 0;
887
888errout:
889 close(fd);
890 return rc;
891}
892
Ken Sumrall160b4d62013-04-22 12:15:39 -0700893static int validate_persistent_data_storage(struct crypt_mnt_ftr *crypt_ftr)
894{
895 if (crypt_ftr->persist_data_offset[0] + crypt_ftr->persist_data_size >
896 crypt_ftr->persist_data_offset[1]) {
897 SLOGE("Crypt_ftr persist data regions overlap");
898 return -1;
899 }
900
901 if (crypt_ftr->persist_data_offset[0] >= crypt_ftr->persist_data_offset[1]) {
902 SLOGE("Crypt_ftr persist data region 0 starts after region 1");
903 return -1;
904 }
905
906 if (((crypt_ftr->persist_data_offset[1] + crypt_ftr->persist_data_size) -
907 (crypt_ftr->persist_data_offset[0] - CRYPT_FOOTER_TO_PERSIST_OFFSET)) >
908 CRYPT_FOOTER_OFFSET) {
909 SLOGE("Persistent data extends past crypto footer");
910 return -1;
911 }
912
913 return 0;
914}
915
916static int load_persistent_data(void)
917{
918 struct crypt_mnt_ftr crypt_ftr;
919 struct crypt_persist_data *pdata = NULL;
920 char encrypted_state[PROPERTY_VALUE_MAX];
921 char *fname;
922 int found = 0;
923 int fd;
924 int ret;
925 int i;
926
927 if (persist_data) {
928 /* Nothing to do, we've already loaded or initialized it */
929 return 0;
930 }
931
932
933 /* If not encrypted, just allocate an empty table and initialize it */
934 property_get("ro.crypto.state", encrypted_state, "");
935 if (strcmp(encrypted_state, "encrypted") ) {
Wei Wang4375f1b2017-02-24 17:43:01 -0800936 pdata = (crypt_persist_data*)malloc(CRYPT_PERSIST_DATA_SIZE);
Ken Sumrall160b4d62013-04-22 12:15:39 -0700937 if (pdata) {
938 init_empty_persist_data(pdata, CRYPT_PERSIST_DATA_SIZE);
939 persist_data = pdata;
940 return 0;
941 }
942 return -1;
943 }
944
945 if(get_crypt_ftr_and_key(&crypt_ftr)) {
946 return -1;
947 }
948
Paul Lawrence8561b5c2014-03-17 14:10:51 -0700949 if ((crypt_ftr.major_version < 1)
950 || (crypt_ftr.major_version == 1 && crypt_ftr.minor_version < 1)) {
Ken Sumrall160b4d62013-04-22 12:15:39 -0700951 SLOGE("Crypt_ftr version doesn't support persistent data");
952 return -1;
953 }
954
955 if (get_crypt_ftr_info(&fname, NULL)) {
956 return -1;
957 }
958
959 ret = validate_persistent_data_storage(&crypt_ftr);
960 if (ret) {
961 return -1;
962 }
963
Jeff Sharkeyce6a9132015-04-08 21:07:21 -0700964 fd = open(fname, O_RDONLY|O_CLOEXEC);
Ken Sumrall160b4d62013-04-22 12:15:39 -0700965 if (fd < 0) {
966 SLOGE("Cannot open %s metadata file", fname);
967 return -1;
968 }
969
Wei Wang4375f1b2017-02-24 17:43:01 -0800970 pdata = (crypt_persist_data*)malloc(crypt_ftr.persist_data_size);
Paul Lawrence300dae72016-03-11 11:02:52 -0800971 if (pdata == NULL) {
972 SLOGE("Cannot allocate memory for persistent data");
973 goto err;
Ken Sumrall160b4d62013-04-22 12:15:39 -0700974 }
975
976 for (i = 0; i < 2; i++) {
977 if (lseek64(fd, crypt_ftr.persist_data_offset[i], SEEK_SET) < 0) {
978 SLOGE("Cannot seek to read persistent data on %s", fname);
979 goto err2;
980 }
981 if (unix_read(fd, pdata, crypt_ftr.persist_data_size) < 0){
982 SLOGE("Error reading persistent data on iteration %d", i);
983 goto err2;
984 }
985 if (pdata->persist_magic == PERSIST_DATA_MAGIC) {
986 found = 1;
987 break;
988 }
989 }
990
991 if (!found) {
992 SLOGI("Could not find valid persistent data, creating");
993 init_empty_persist_data(pdata, crypt_ftr.persist_data_size);
994 }
995
996 /* Success */
997 persist_data = pdata;
998 close(fd);
999 return 0;
1000
1001err2:
1002 free(pdata);
1003
1004err:
1005 close(fd);
1006 return -1;
1007}
1008
1009static int save_persistent_data(void)
1010{
1011 struct crypt_mnt_ftr crypt_ftr;
1012 struct crypt_persist_data *pdata;
1013 char *fname;
1014 off64_t write_offset;
1015 off64_t erase_offset;
Ken Sumrall160b4d62013-04-22 12:15:39 -07001016 int fd;
1017 int ret;
1018
1019 if (persist_data == NULL) {
1020 SLOGE("No persistent data to save");
1021 return -1;
1022 }
1023
1024 if(get_crypt_ftr_and_key(&crypt_ftr)) {
1025 return -1;
1026 }
1027
Paul Lawrence8561b5c2014-03-17 14:10:51 -07001028 if ((crypt_ftr.major_version < 1)
1029 || (crypt_ftr.major_version == 1 && crypt_ftr.minor_version < 1)) {
Ken Sumrall160b4d62013-04-22 12:15:39 -07001030 SLOGE("Crypt_ftr version doesn't support persistent data");
1031 return -1;
1032 }
1033
1034 ret = validate_persistent_data_storage(&crypt_ftr);
1035 if (ret) {
1036 return -1;
1037 }
1038
1039 if (get_crypt_ftr_info(&fname, NULL)) {
1040 return -1;
1041 }
1042
Jeff Sharkeyce6a9132015-04-08 21:07:21 -07001043 fd = open(fname, O_RDWR|O_CLOEXEC);
Ken Sumrall160b4d62013-04-22 12:15:39 -07001044 if (fd < 0) {
1045 SLOGE("Cannot open %s metadata file", fname);
1046 return -1;
1047 }
1048
Wei Wang4375f1b2017-02-24 17:43:01 -08001049 pdata = (crypt_persist_data*)malloc(crypt_ftr.persist_data_size);
Ken Sumrall160b4d62013-04-22 12:15:39 -07001050 if (pdata == NULL) {
1051 SLOGE("Cannot allocate persistant data");
1052 goto err;
1053 }
1054
1055 if (lseek64(fd, crypt_ftr.persist_data_offset[0], SEEK_SET) < 0) {
1056 SLOGE("Cannot seek to read persistent data on %s", fname);
1057 goto err2;
1058 }
1059
1060 if (unix_read(fd, pdata, crypt_ftr.persist_data_size) < 0) {
1061 SLOGE("Error reading persistent data before save");
1062 goto err2;
1063 }
1064
1065 if (pdata->persist_magic == PERSIST_DATA_MAGIC) {
1066 /* The first copy is the curent valid copy, so write to
1067 * the second copy and erase this one */
1068 write_offset = crypt_ftr.persist_data_offset[1];
1069 erase_offset = crypt_ftr.persist_data_offset[0];
1070 } else {
1071 /* The second copy must be the valid copy, so write to
1072 * the first copy, and erase the second */
1073 write_offset = crypt_ftr.persist_data_offset[0];
1074 erase_offset = crypt_ftr.persist_data_offset[1];
1075 }
1076
1077 /* Write the new copy first, if successful, then erase the old copy */
Björn Landström96dbee72015-01-20 12:43:56 +01001078 if (lseek64(fd, write_offset, SEEK_SET) < 0) {
Ken Sumrall160b4d62013-04-22 12:15:39 -07001079 SLOGE("Cannot seek to write persistent data");
1080 goto err2;
1081 }
1082 if (unix_write(fd, persist_data, crypt_ftr.persist_data_size) ==
1083 (int) crypt_ftr.persist_data_size) {
Björn Landström96dbee72015-01-20 12:43:56 +01001084 if (lseek64(fd, erase_offset, SEEK_SET) < 0) {
Ken Sumrall160b4d62013-04-22 12:15:39 -07001085 SLOGE("Cannot seek to erase previous persistent data");
1086 goto err2;
1087 }
1088 fsync(fd);
1089 memset(pdata, 0, crypt_ftr.persist_data_size);
1090 if (unix_write(fd, pdata, crypt_ftr.persist_data_size) !=
1091 (int) crypt_ftr.persist_data_size) {
1092 SLOGE("Cannot write to erase previous persistent data");
1093 goto err2;
1094 }
1095 fsync(fd);
1096 } else {
1097 SLOGE("Cannot write to save persistent data");
1098 goto err2;
1099 }
1100
1101 /* Success */
1102 free(pdata);
1103 close(fd);
1104 return 0;
1105
1106err2:
1107 free(pdata);
1108err:
1109 close(fd);
1110 return -1;
1111}
1112
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001113/* Convert a binary key of specified length into an ascii hex string equivalent,
1114 * without the leading 0x and with null termination
1115 */
Jeff Sharkey9c484982015-03-31 10:35:33 -07001116static void convert_key_to_hex_ascii(const unsigned char *master_key,
Paul Lawrence3bd36d52015-06-09 13:37:44 -07001117 unsigned int keysize, char *master_key_ascii) {
1118 unsigned int i, a;
1119 unsigned char nibble;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001120
Paul Lawrence3bd36d52015-06-09 13:37:44 -07001121 for (i=0, a=0; i<keysize; i++, a+=2) {
1122 /* For each byte, write out two ascii hex digits */
1123 nibble = (master_key[i] >> 4) & 0xf;
1124 master_key_ascii[a] = nibble + (nibble > 9 ? 0x37 : 0x30);
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001125
Paul Lawrence3bd36d52015-06-09 13:37:44 -07001126 nibble = master_key[i] & 0xf;
1127 master_key_ascii[a+1] = nibble + (nibble > 9 ? 0x37 : 0x30);
1128 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001129
Paul Lawrence3bd36d52015-06-09 13:37:44 -07001130 /* Add the null termination */
1131 master_key_ascii[a] = '\0';
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001132
1133}
1134
Jeff Sharkey9c484982015-03-31 10:35:33 -07001135static int load_crypto_mapping_table(struct crypt_mnt_ftr *crypt_ftr,
1136 const unsigned char *master_key, const char *real_blk_name,
1137 const char *name, int fd, const char *extra_params) {
Wei Wang4375f1b2017-02-24 17:43:01 -08001138 alignas(struct dm_ioctl) char buffer[DM_CRYPT_BUF_SIZE];
Ken Sumralldb5e0262013-02-05 17:39:48 -08001139 struct dm_ioctl *io;
1140 struct dm_target_spec *tgt;
1141 char *crypt_params;
Greg Kaiser59ad0182018-02-16 13:01:36 -08001142 // We need two ASCII characters to represent each byte, and need space for
1143 // the '\0' terminator.
1144 char master_key_ascii[MAX_KEY_LEN * 2 + 1];
George Burgess IV605d7ae2016-02-29 13:39:17 -08001145 size_t buff_offset;
Ken Sumralldb5e0262013-02-05 17:39:48 -08001146 int i;
1147
1148 io = (struct dm_ioctl *) buffer;
1149
1150 /* Load the mapping table for this device */
1151 tgt = (struct dm_target_spec *) &buffer[sizeof(struct dm_ioctl)];
1152
1153 ioctl_init(io, DM_CRYPT_BUF_SIZE, name, 0);
1154 io->target_count = 1;
1155 tgt->status = 0;
1156 tgt->sector_start = 0;
1157 tgt->length = crypt_ftr->fs_size;
Ken Sumralldb5e0262013-02-05 17:39:48 -08001158 crypt_params = buffer + sizeof(struct dm_ioctl) + sizeof(struct dm_target_spec);
George Burgess IV605d7ae2016-02-29 13:39:17 -08001159 buff_offset = crypt_params - buffer;
Paul Crowley5afbc622017-11-27 09:42:17 -08001160 SLOGI("Extra parameters for dm_crypt: %s\n", extra_params);
AnilKumar Chimata98dc8352018-05-11 00:25:09 +05301161
1162#ifdef CONFIG_HW_DISK_ENCRYPTION
1163 if(is_hw_disk_encryption((char*)crypt_ftr->crypto_type_name)) {
1164 strlcpy(tgt->target_type, "req-crypt",DM_MAX_TYPE_NAME);
1165 if (is_ice_enabled())
1166 convert_key_to_hex_ascii(master_key, sizeof(int), master_key_ascii);
1167 else
1168 convert_key_to_hex_ascii(master_key, crypt_ftr->keysize, master_key_ascii);
1169 }
1170 else {
1171 convert_key_to_hex_ascii(master_key, crypt_ftr->keysize, master_key_ascii);
1172 strlcpy(tgt->target_type, "crypt", DM_MAX_TYPE_NAME);
1173 }
1174 snprintf(crypt_params, sizeof(buffer) - buff_offset, "%s %s 0 %s 0 %s 0",
1175 crypt_ftr->crypto_type_name, master_key_ascii,
1176 real_blk_name, extra_params);
1177
1178 SLOGI("target_type = %s", tgt->target_type);
1179 SLOGI("real_blk_name = %s, extra_params = %s", real_blk_name, extra_params);
1180#else
1181 convert_key_to_hex_ascii(master_key, crypt_ftr->keysize, master_key_ascii);
1182 strlcpy(tgt->target_type, "crypt", DM_MAX_TYPE_NAME);
George Burgess IV605d7ae2016-02-29 13:39:17 -08001183 snprintf(crypt_params, sizeof(buffer) - buff_offset, "%s %s 0 %s 0 %s",
1184 crypt_ftr->crypto_type_name, master_key_ascii, real_blk_name,
1185 extra_params);
AnilKumar Chimata98dc8352018-05-11 00:25:09 +05301186#endif
1187
Ken Sumralldb5e0262013-02-05 17:39:48 -08001188 crypt_params += strlen(crypt_params) + 1;
1189 crypt_params = (char *) (((unsigned long)crypt_params + 7) & ~8); /* Align to an 8 byte boundary */
1190 tgt->next = crypt_params - buffer;
1191
1192 for (i = 0; i < TABLE_LOAD_RETRIES; i++) {
1193 if (! ioctl(fd, DM_TABLE_LOAD, io)) {
1194 break;
1195 }
1196 usleep(500000);
1197 }
1198
1199 if (i == TABLE_LOAD_RETRIES) {
1200 /* We failed to load the table, return an error */
1201 return -1;
1202 } else {
1203 return i + 1;
1204 }
1205}
1206
Ken Sumralldb5e0262013-02-05 17:39:48 -08001207static int get_dm_crypt_version(int fd, const char *name, int *version)
1208{
1209 char buffer[DM_CRYPT_BUF_SIZE];
1210 struct dm_ioctl *io;
1211 struct dm_target_versions *v;
Ken Sumralldb5e0262013-02-05 17:39:48 -08001212
1213 io = (struct dm_ioctl *) buffer;
1214
1215 ioctl_init(io, DM_CRYPT_BUF_SIZE, name, 0);
1216
1217 if (ioctl(fd, DM_LIST_VERSIONS, io)) {
1218 return -1;
1219 }
1220
1221 /* Iterate over the returned versions, looking for name of "crypt".
1222 * When found, get and return the version.
1223 */
1224 v = (struct dm_target_versions *) &buffer[sizeof(struct dm_ioctl)];
1225 while (v->next) {
AnilKumar Chimata98dc8352018-05-11 00:25:09 +05301226#ifdef CONFIG_HW_DISK_ENCRYPTION
1227 if (! strcmp(v->name, "crypt") || ! strcmp(v->name, "req-crypt")) {
1228#else
Ken Sumralldb5e0262013-02-05 17:39:48 -08001229 if (! strcmp(v->name, "crypt")) {
AnilKumar Chimata98dc8352018-05-11 00:25:09 +05301230#endif
Ken Sumralldb5e0262013-02-05 17:39:48 -08001231 /* We found the crypt driver, return the version, and get out */
1232 version[0] = v->version[0];
1233 version[1] = v->version[1];
1234 version[2] = v->version[2];
1235 return 0;
1236 }
1237 v = (struct dm_target_versions *)(((char *)v) + v->next);
1238 }
1239
1240 return -1;
1241}
1242
AnilKumar Chimata98dc8352018-05-11 00:25:09 +05301243#ifndef CONFIG_HW_DISK_ENCRYPTION
Paul Crowley5afbc622017-11-27 09:42:17 -08001244static std::string extra_params_as_string(const std::vector<std::string>& extra_params_vec) {
1245 if (extra_params_vec.empty()) return "";
1246 std::string extra_params = std::to_string(extra_params_vec.size());
1247 for (const auto& p : extra_params_vec) {
1248 extra_params.append(" ");
1249 extra_params.append(p);
1250 }
1251 return extra_params;
1252}
AnilKumar Chimata98dc8352018-05-11 00:25:09 +05301253#endif
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001254
Paul Crowley5afbc622017-11-27 09:42:17 -08001255static int create_crypto_blk_dev(struct crypt_mnt_ftr* crypt_ftr, const unsigned char* master_key,
1256 const char* real_blk_name, char* crypto_blk_name, const char* name,
1257 uint32_t flags) {
1258 char buffer[DM_CRYPT_BUF_SIZE];
1259 struct dm_ioctl* io;
1260 unsigned int minor;
1261 int fd = 0;
1262 int err;
1263 int retval = -1;
1264 int version[3];
1265 int load_count;
AnilKumar Chimata98dc8352018-05-11 00:25:09 +05301266#ifdef CONFIG_HW_DISK_ENCRYPTION
1267 char encrypted_state[PROPERTY_VALUE_MAX] = {0};
1268 char progress[PROPERTY_VALUE_MAX] = {0};
1269 const char *extra_params;
1270#else
Paul Crowley5afbc622017-11-27 09:42:17 -08001271 std::vector<std::string> extra_params_vec;
AnilKumar Chimata98dc8352018-05-11 00:25:09 +05301272#endif
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001273
Paul Crowley5afbc622017-11-27 09:42:17 -08001274 if ((fd = open("/dev/device-mapper", O_RDWR | O_CLOEXEC)) < 0) {
1275 SLOGE("Cannot open device-mapper\n");
1276 goto errout;
1277 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001278
Paul Crowley5afbc622017-11-27 09:42:17 -08001279 io = (struct dm_ioctl*)buffer;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001280
Paul Crowley5afbc622017-11-27 09:42:17 -08001281 ioctl_init(io, DM_CRYPT_BUF_SIZE, name, 0);
1282 err = ioctl(fd, DM_DEV_CREATE, io);
1283 if (err) {
1284 SLOGE("Cannot create dm-crypt device %s: %s\n", name, strerror(errno));
1285 goto errout;
1286 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001287
Paul Crowley5afbc622017-11-27 09:42:17 -08001288 /* Get the device status, in particular, the name of it's device file */
1289 ioctl_init(io, DM_CRYPT_BUF_SIZE, name, 0);
1290 if (ioctl(fd, DM_DEV_STATUS, io)) {
1291 SLOGE("Cannot retrieve dm-crypt device status\n");
1292 goto errout;
1293 }
1294 minor = (io->dev & 0xff) | ((io->dev >> 12) & 0xfff00);
1295 snprintf(crypto_blk_name, MAXPATHLEN, "/dev/block/dm-%u", minor);
Ken Sumralle919efe2012-09-29 17:07:41 -07001296
AnilKumar Chimata98dc8352018-05-11 00:25:09 +05301297#ifdef CONFIG_HW_DISK_ENCRYPTION
1298 if(is_hw_disk_encryption((char*)crypt_ftr->crypto_type_name)) {
1299 /* Set fde_enabled if either FDE completed or in-progress */
1300 property_get("ro.crypto.state", encrypted_state, ""); /* FDE completed */
1301 property_get("vold.encrypt_progress", progress, ""); /* FDE in progress */
1302 if (!strcmp(encrypted_state, "encrypted") || strcmp(progress, "")) {
1303 if (is_ice_enabled()) {
1304 if (flags & CREATE_CRYPTO_BLK_DEV_FLAGS_ALLOW_ENCRYPT_OVERRIDE)
1305 extra_params = "fde_enabled ice allow_encrypt_override";
1306 else
1307 extra_params = "fde_enabled ice";
1308 } else {
1309 if (flags & CREATE_CRYPTO_BLK_DEV_FLAGS_ALLOW_ENCRYPT_OVERRIDE)
1310 extra_params = "fde_enabled allow_encrypt_override";
1311 else
1312 extra_params = "fde_enabled";
1313 }
1314 } else {
1315 if (flags & CREATE_CRYPTO_BLK_DEV_FLAGS_ALLOW_ENCRYPT_OVERRIDE)
1316 extra_params = "fde_enabled allow_encrypt_override";
1317 else
1318 extra_params = "fde_enabled";
1319 }
1320 } else {
1321 extra_params = "";
1322 if (! get_dm_crypt_version(fd, name, version)) {
1323 /* Support for allow_discards was added in version 1.11.0 */
1324 if ((version[0] >= 2) || ((version[0] == 1) && (version[1] >= 11))) {
1325 if (flags & CREATE_CRYPTO_BLK_DEV_FLAGS_ALLOW_ENCRYPT_OVERRIDE)
1326 extra_params = "2 allow_discards allow_encrypt_override";
1327 else
1328 extra_params = "1 allow_discards";
1329 SLOGI("Enabling support for allow_discards in dmcrypt.\n");
1330 }
1331 }
1332 }
1333 load_count = load_crypto_mapping_table(crypt_ftr, master_key, real_blk_name, name, fd,
1334 extra_params);
1335#else
Paul Crowley5afbc622017-11-27 09:42:17 -08001336 if (!get_dm_crypt_version(fd, name, version)) {
1337 /* Support for allow_discards was added in version 1.11.0 */
1338 if ((version[0] >= 2) || ((version[0] == 1) && (version[1] >= 11))) {
1339 extra_params_vec.emplace_back("allow_discards");
1340 }
1341 }
1342 if (flags & CREATE_CRYPTO_BLK_DEV_FLAGS_ALLOW_ENCRYPT_OVERRIDE) {
1343 extra_params_vec.emplace_back("allow_encrypt_override");
1344 }
1345 load_count = load_crypto_mapping_table(crypt_ftr, master_key, real_blk_name, name, fd,
1346 extra_params_as_string(extra_params_vec).c_str());
AnilKumar Chimata98dc8352018-05-11 00:25:09 +05301347#endif
Paul Crowley5afbc622017-11-27 09:42:17 -08001348 if (load_count < 0) {
1349 SLOGE("Cannot load dm-crypt mapping table.\n");
1350 goto errout;
1351 } else if (load_count > 1) {
1352 SLOGI("Took %d tries to load dmcrypt table.\n", load_count);
1353 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001354
Paul Crowley5afbc622017-11-27 09:42:17 -08001355 /* Resume this device to activate it */
1356 ioctl_init(io, DM_CRYPT_BUF_SIZE, name, 0);
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001357
Paul Crowley5afbc622017-11-27 09:42:17 -08001358 if (ioctl(fd, DM_DEV_SUSPEND, io)) {
1359 SLOGE("Cannot resume the dm-crypt device\n");
1360 goto errout;
1361 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001362
Paul Crowley5afbc622017-11-27 09:42:17 -08001363 /* We made it here with no errors. Woot! */
1364 retval = 0;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001365
1366errout:
1367 close(fd); /* If fd is <0 from a failed open call, it's safe to just ignore the close error */
1368
1369 return retval;
1370}
1371
Wei Wang4375f1b2017-02-24 17:43:01 -08001372static int delete_crypto_blk_dev(const char *name)
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001373{
1374 int fd;
1375 char buffer[DM_CRYPT_BUF_SIZE];
1376 struct dm_ioctl *io;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001377 int retval = -1;
1378
Jeff Sharkeyce6a9132015-04-08 21:07:21 -07001379 if ((fd = open("/dev/device-mapper", O_RDWR|O_CLOEXEC)) < 0 ) {
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001380 SLOGE("Cannot open device-mapper\n");
1381 goto errout;
1382 }
1383
1384 io = (struct dm_ioctl *) buffer;
1385
1386 ioctl_init(io, DM_CRYPT_BUF_SIZE, name, 0);
1387 if (ioctl(fd, DM_DEV_REMOVE, io)) {
1388 SLOGE("Cannot remove dm-crypt device\n");
1389 goto errout;
1390 }
1391
1392 /* We made it here with no errors. Woot! */
1393 retval = 0;
1394
1395errout:
1396 close(fd); /* If fd is <0 from a failed open call, it's safe to just ignore the close error */
1397
1398 return retval;
1399
1400}
1401
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001402static int pbkdf2(const char *passwd, const unsigned char *salt,
Paul Lawrencef4faa572014-01-29 13:31:03 -08001403 unsigned char *ikey, void *params UNUSED)
1404{
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001405 SLOGI("Using pbkdf2 for cryptfs KDF");
1406
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001407 /* Turn the password into a key and IV that can decrypt the master key */
Adam Langleybf0d9722015-11-04 14:51:39 -08001408 return PKCS5_PBKDF2_HMAC_SHA1(passwd, strlen(passwd), salt, SALT_LEN,
Greg Kaiserc0de9c72018-02-14 20:05:54 -08001409 HASH_COUNT, INTERMEDIATE_BUF_SIZE,
Adam Langleybf0d9722015-11-04 14:51:39 -08001410 ikey) != 1;
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001411}
1412
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001413static int scrypt(const char *passwd, const unsigned char *salt,
Paul Lawrencef4faa572014-01-29 13:31:03 -08001414 unsigned char *ikey, void *params)
1415{
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001416 SLOGI("Using scrypt for cryptfs KDF");
1417
Kenny Rootc4c70f12013-06-14 12:11:38 -07001418 struct crypt_mnt_ftr *ftr = (struct crypt_mnt_ftr *) params;
1419
1420 int N = 1 << ftr->N_factor;
1421 int r = 1 << ftr->r_factor;
1422 int p = 1 << ftr->p_factor;
1423
1424 /* Turn the password into a key and IV that can decrypt the master key */
Paul Lawrence3bd36d52015-06-09 13:37:44 -07001425 crypto_scrypt((const uint8_t*)passwd, strlen(passwd),
1426 salt, SALT_LEN, N, r, p, ikey,
Greg Kaiserc0de9c72018-02-14 20:05:54 -08001427 INTERMEDIATE_BUF_SIZE);
Paul Lawrencef4faa572014-01-29 13:31:03 -08001428
Paul Lawrence3bd36d52015-06-09 13:37:44 -07001429 return 0;
Kenny Rootc4c70f12013-06-14 12:11:38 -07001430}
1431
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001432static int scrypt_keymaster(const char *passwd, const unsigned char *salt,
1433 unsigned char *ikey, void *params)
1434{
1435 SLOGI("Using scrypt with keymaster for cryptfs KDF");
1436
1437 int rc;
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001438 size_t signature_size;
1439 unsigned char* signature;
1440 struct crypt_mnt_ftr *ftr = (struct crypt_mnt_ftr *) params;
1441
1442 int N = 1 << ftr->N_factor;
1443 int r = 1 << ftr->r_factor;
1444 int p = 1 << ftr->p_factor;
1445
Paul Lawrence3bd36d52015-06-09 13:37:44 -07001446 rc = crypto_scrypt((const uint8_t*)passwd, strlen(passwd),
1447 salt, SALT_LEN, N, r, p, ikey,
Greg Kaiserc0de9c72018-02-14 20:05:54 -08001448 INTERMEDIATE_BUF_SIZE);
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001449
1450 if (rc) {
1451 SLOGE("scrypt failed");
1452 return -1;
1453 }
1454
Greg Kaiserc0de9c72018-02-14 20:05:54 -08001455 if (keymaster_sign_object(ftr, ikey, INTERMEDIATE_BUF_SIZE,
Shawn Willdene17a9c42014-09-08 13:04:08 -06001456 &signature, &signature_size)) {
1457 SLOGE("Signing failed");
1458 return -1;
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001459 }
1460
1461 rc = crypto_scrypt(signature, signature_size, salt, SALT_LEN,
Greg Kaiserc0de9c72018-02-14 20:05:54 -08001462 N, r, p, ikey, INTERMEDIATE_BUF_SIZE);
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001463 free(signature);
1464
1465 if (rc) {
1466 SLOGE("scrypt failed");
1467 return -1;
1468 }
1469
1470 return 0;
1471}
1472
1473static int encrypt_master_key(const char *passwd, const unsigned char *salt,
1474 const unsigned char *decrypted_master_key,
Kenny Rootc4c70f12013-06-14 12:11:38 -07001475 unsigned char *encrypted_master_key,
AnilKumar Chimata98dc8352018-05-11 00:25:09 +05301476 struct crypt_mnt_ftr *crypt_ftr,
1477 bool create_keymaster_key)
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001478{
Greg Kaiserc0de9c72018-02-14 20:05:54 -08001479 unsigned char ikey[INTERMEDIATE_BUF_SIZE] = { 0 };
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001480 EVP_CIPHER_CTX e_ctx;
1481 int encrypted_len, final_len;
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001482 int rc = 0;
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001483
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001484 /* Turn the password into an intermediate key and IV that can decrypt the master key */
Kenny Rootc4c70f12013-06-14 12:11:38 -07001485 get_device_scrypt_params(crypt_ftr);
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001486
1487 switch (crypt_ftr->kdf_type) {
1488 case KDF_SCRYPT_KEYMASTER:
AnilKumar Chimata98dc8352018-05-11 00:25:09 +05301489 if (create_keymaster_key && keymaster_create_key(crypt_ftr)) {
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001490 SLOGE("keymaster_create_key failed");
1491 return -1;
1492 }
1493
1494 if (scrypt_keymaster(passwd, salt, ikey, crypt_ftr)) {
1495 SLOGE("scrypt failed");
1496 return -1;
1497 }
1498 break;
1499
1500 case KDF_SCRYPT:
1501 if (scrypt(passwd, salt, ikey, crypt_ftr)) {
1502 SLOGE("scrypt failed");
1503 return -1;
1504 }
1505 break;
1506
1507 default:
1508 SLOGE("Invalid kdf_type");
Paul Lawrencef4faa572014-01-29 13:31:03 -08001509 return -1;
1510 }
Kenny Rootc4c70f12013-06-14 12:11:38 -07001511
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001512 /* Initialize the decryption engine */
Adam Langley889c4f12014-09-03 14:23:13 -07001513 EVP_CIPHER_CTX_init(&e_ctx);
Greg Kaiserc0de9c72018-02-14 20:05:54 -08001514 if (! EVP_EncryptInit_ex(&e_ctx, EVP_aes_128_cbc(), NULL, ikey,
1515 ikey+INTERMEDIATE_KEY_LEN_BYTES)) {
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001516 SLOGE("EVP_EncryptInit failed\n");
1517 return -1;
1518 }
1519 EVP_CIPHER_CTX_set_padding(&e_ctx, 0); /* Turn off padding as our data is block aligned */
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001520
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001521 /* Encrypt the master key */
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001522 if (! EVP_EncryptUpdate(&e_ctx, encrypted_master_key, &encrypted_len,
Greg Kaiser59ad0182018-02-16 13:01:36 -08001523 decrypted_master_key, crypt_ftr->keysize)) {
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001524 SLOGE("EVP_EncryptUpdate failed\n");
1525 return -1;
1526 }
Adam Langley889c4f12014-09-03 14:23:13 -07001527 if (! EVP_EncryptFinal_ex(&e_ctx, encrypted_master_key + encrypted_len, &final_len)) {
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001528 SLOGE("EVP_EncryptFinal failed\n");
1529 return -1;
1530 }
1531
Greg Kaiser59ad0182018-02-16 13:01:36 -08001532 if (encrypted_len + final_len != static_cast<int>(crypt_ftr->keysize)) {
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001533 SLOGE("EVP_Encryption length check failed with %d, %d bytes\n", encrypted_len, final_len);
1534 return -1;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001535 }
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001536
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001537 /* Store the scrypt of the intermediate key, so we can validate if it's a
1538 password error or mount error when things go wrong.
1539 Note there's no need to check for errors, since if this is incorrect, we
1540 simply won't wipe userdata, which is the correct default behavior
1541 */
1542 int N = 1 << crypt_ftr->N_factor;
1543 int r = 1 << crypt_ftr->r_factor;
1544 int p = 1 << crypt_ftr->p_factor;
1545
Greg Kaiserc0de9c72018-02-14 20:05:54 -08001546 rc = crypto_scrypt(ikey, INTERMEDIATE_KEY_LEN_BYTES,
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001547 crypt_ftr->salt, sizeof(crypt_ftr->salt), N, r, p,
1548 crypt_ftr->scrypted_intermediate_key,
1549 sizeof(crypt_ftr->scrypted_intermediate_key));
1550
1551 if (rc) {
1552 SLOGE("encrypt_master_key: crypto_scrypt failed");
1553 }
1554
Thurston Hou Yeen Dang06dc3112016-07-18 14:16:37 -07001555 EVP_CIPHER_CTX_cleanup(&e_ctx);
1556
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001557 return 0;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001558}
1559
Paul Lawrence731a7a22015-04-28 22:14:15 +00001560static int decrypt_master_key_aux(const char *passwd, unsigned char *salt,
Greg Kaiser59ad0182018-02-16 13:01:36 -08001561 const unsigned char *encrypted_master_key,
1562 size_t keysize,
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001563 unsigned char *decrypted_master_key,
1564 kdf_func kdf, void *kdf_params,
1565 unsigned char** intermediate_key,
1566 size_t* intermediate_key_size)
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001567{
Greg Kaiserc0de9c72018-02-14 20:05:54 -08001568 unsigned char ikey[INTERMEDIATE_BUF_SIZE] = { 0 };
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001569 EVP_CIPHER_CTX d_ctx;
1570 int decrypted_len, final_len;
1571
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001572 /* Turn the password into an intermediate key and IV that can decrypt the
1573 master key */
Paul Lawrencef4faa572014-01-29 13:31:03 -08001574 if (kdf(passwd, salt, ikey, kdf_params)) {
1575 SLOGE("kdf failed");
1576 return -1;
1577 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001578
1579 /* Initialize the decryption engine */
Adam Langley889c4f12014-09-03 14:23:13 -07001580 EVP_CIPHER_CTX_init(&d_ctx);
Greg Kaiserc0de9c72018-02-14 20:05:54 -08001581 if (! EVP_DecryptInit_ex(&d_ctx, EVP_aes_128_cbc(), NULL, ikey, ikey+INTERMEDIATE_KEY_LEN_BYTES)) {
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001582 return -1;
1583 }
1584 EVP_CIPHER_CTX_set_padding(&d_ctx, 0); /* Turn off padding as our data is block aligned */
1585 /* Decrypt the master key */
1586 if (! EVP_DecryptUpdate(&d_ctx, decrypted_master_key, &decrypted_len,
Greg Kaiser59ad0182018-02-16 13:01:36 -08001587 encrypted_master_key, keysize)) {
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001588 return -1;
1589 }
Adam Langley889c4f12014-09-03 14:23:13 -07001590 if (! EVP_DecryptFinal_ex(&d_ctx, decrypted_master_key + decrypted_len, &final_len)) {
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001591 return -1;
1592 }
1593
Greg Kaiser59ad0182018-02-16 13:01:36 -08001594 if (decrypted_len + final_len != static_cast<int>(keysize)) {
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001595 return -1;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001596 }
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001597
1598 /* Copy intermediate key if needed by params */
1599 if (intermediate_key && intermediate_key_size) {
Greg Kaiserc0de9c72018-02-14 20:05:54 -08001600 *intermediate_key = (unsigned char*) malloc(INTERMEDIATE_KEY_LEN_BYTES);
Greg Kaisere8167af2016-04-20 10:50:15 -07001601 if (*intermediate_key) {
Greg Kaiserc0de9c72018-02-14 20:05:54 -08001602 memcpy(*intermediate_key, ikey, INTERMEDIATE_KEY_LEN_BYTES);
1603 *intermediate_key_size = INTERMEDIATE_KEY_LEN_BYTES;
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001604 }
1605 }
1606
Thurston Hou Yeen Dang06dc3112016-07-18 14:16:37 -07001607 EVP_CIPHER_CTX_cleanup(&d_ctx);
1608
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001609 return 0;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001610}
1611
Kenny Rootc4c70f12013-06-14 12:11:38 -07001612static void get_kdf_func(struct crypt_mnt_ftr *ftr, kdf_func *kdf, void** kdf_params)
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001613{
Paul Lawrencedb3730c2015-02-03 13:08:10 -08001614 if (ftr->kdf_type == KDF_SCRYPT_KEYMASTER) {
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001615 *kdf = scrypt_keymaster;
1616 *kdf_params = ftr;
1617 } else if (ftr->kdf_type == KDF_SCRYPT) {
Kenny Rootc4c70f12013-06-14 12:11:38 -07001618 *kdf = scrypt;
1619 *kdf_params = ftr;
1620 } else {
1621 *kdf = pbkdf2;
1622 *kdf_params = NULL;
1623 }
1624}
1625
Paul Lawrence731a7a22015-04-28 22:14:15 +00001626static int decrypt_master_key(const char *passwd, unsigned char *decrypted_master_key,
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001627 struct crypt_mnt_ftr *crypt_ftr,
1628 unsigned char** intermediate_key,
1629 size_t* intermediate_key_size)
Kenny Rootc4c70f12013-06-14 12:11:38 -07001630{
1631 kdf_func kdf;
1632 void *kdf_params;
1633 int ret;
1634
1635 get_kdf_func(crypt_ftr, &kdf, &kdf_params);
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001636 ret = decrypt_master_key_aux(passwd, crypt_ftr->salt, crypt_ftr->master_key,
Greg Kaiser59ad0182018-02-16 13:01:36 -08001637 crypt_ftr->keysize,
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001638 decrypted_master_key, kdf, kdf_params,
1639 intermediate_key, intermediate_key_size);
Kenny Rootc4c70f12013-06-14 12:11:38 -07001640 if (ret != 0) {
1641 SLOGW("failure decrypting master key");
Kenny Rootc4c70f12013-06-14 12:11:38 -07001642 }
1643
1644 return ret;
1645}
1646
Wei Wang4375f1b2017-02-24 17:43:01 -08001647static int create_encrypted_random_key(const char *passwd, unsigned char *master_key, unsigned char *salt,
Kenny Rootc4c70f12013-06-14 12:11:38 -07001648 struct crypt_mnt_ftr *crypt_ftr) {
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001649 int fd;
Greg Kaiser59ad0182018-02-16 13:01:36 -08001650 unsigned char key_buf[MAX_KEY_LEN];
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001651
1652 /* Get some random bits for a key */
Jeff Sharkeyce6a9132015-04-08 21:07:21 -07001653 fd = open("/dev/urandom", O_RDONLY|O_CLOEXEC);
Ken Sumralle8744072011-01-18 22:01:55 -08001654 read(fd, key_buf, sizeof(key_buf));
1655 read(fd, salt, SALT_LEN);
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001656 close(fd);
1657
1658 /* Now encrypt it with the password */
AnilKumar Chimata98dc8352018-05-11 00:25:09 +05301659 return encrypt_master_key(passwd, salt, key_buf, master_key, crypt_ftr, true);
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001660}
1661
Paul Lawrence2f32cda2015-05-05 14:28:25 -07001662int wait_and_unmount(const char *mountpoint, bool kill)
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001663{
Greg Hackmann955653e2014-09-24 14:55:20 -07001664 int i, err, rc;
AnilKumar Chimata98dc8352018-05-11 00:25:09 +05301665#define WAIT_UNMOUNT_COUNT 200
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001666
1667 /* Now umount the tmpfs filesystem */
1668 for (i=0; i<WAIT_UNMOUNT_COUNT; i++) {
Greg Hackmann6e8440f2014-10-02 17:18:20 -07001669 if (umount(mountpoint) == 0) {
1670 break;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001671 }
Greg Hackmann6e8440f2014-10-02 17:18:20 -07001672
1673 if (errno == EINVAL) {
1674 /* EINVAL is returned if the directory is not a mountpoint,
1675 * i.e. there is no filesystem mounted there. So just get out.
1676 */
1677 break;
1678 }
1679
1680 err = errno;
1681
AnilKumar Chimata98dc8352018-05-11 00:25:09 +05301682 /* If allowed, be increasingly aggressive before the last 2 seconds */
Greg Hackmann6e8440f2014-10-02 17:18:20 -07001683 if (kill) {
AnilKumar Chimata98dc8352018-05-11 00:25:09 +05301684 if (i == (WAIT_UNMOUNT_COUNT - 30)) {
Greg Hackmann6e8440f2014-10-02 17:18:20 -07001685 SLOGW("sending SIGHUP to processes with open files\n");
Jeff Sharkey3472e522017-10-06 18:02:53 -06001686 android::vold::KillProcessesWithOpenFiles(mountpoint, SIGTERM);
AnilKumar Chimata98dc8352018-05-11 00:25:09 +05301687 } else if (i == (WAIT_UNMOUNT_COUNT - 20)) {
Greg Hackmann6e8440f2014-10-02 17:18:20 -07001688 SLOGW("sending SIGKILL to processes with open files\n");
Jeff Sharkey3472e522017-10-06 18:02:53 -06001689 android::vold::KillProcessesWithOpenFiles(mountpoint, SIGKILL);
Greg Hackmann6e8440f2014-10-02 17:18:20 -07001690 }
1691 }
1692
AnilKumar Chimata98dc8352018-05-11 00:25:09 +05301693 usleep(100000);
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001694 }
1695
1696 if (i < WAIT_UNMOUNT_COUNT) {
1697 SLOGD("unmounting %s succeeded\n", mountpoint);
1698 rc = 0;
1699 } else {
Jeff Sharkey3472e522017-10-06 18:02:53 -06001700 android::vold::KillProcessesWithOpenFiles(mountpoint, 0);
Greg Hackmann955653e2014-09-24 14:55:20 -07001701 SLOGE("unmounting %s failed: %s\n", mountpoint, strerror(err));
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001702 rc = -1;
1703 }
1704
1705 return rc;
1706}
1707
Wei Wang42e38102017-06-07 10:46:12 -07001708static void prep_data_fs(void)
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001709{
Jeff Sharkey47695b22016-02-01 17:02:29 -07001710 // NOTE: post_fs_data results in init calling back around to vold, so all
1711 // callers to this method must be async
1712
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001713 /* Do the prep of the /data filesystem */
1714 property_set("vold.post_fs_data_done", "0");
1715 property_set("vold.decrypt", "trigger_post_fs_data");
Wei Wang42e38102017-06-07 10:46:12 -07001716 SLOGD("Just triggered post_fs_data");
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001717
Ken Sumrallc5872692013-05-14 15:26:31 -07001718 /* Wait a max of 50 seconds, hopefully it takes much less */
Wei Wang42e38102017-06-07 10:46:12 -07001719 while (!android::base::WaitForProperty("vold.post_fs_data_done",
Wei Wang4375f1b2017-02-24 17:43:01 -08001720 "1",
Wei Wang42e38102017-06-07 10:46:12 -07001721 std::chrono::seconds(15))) {
1722 /* We timed out to prep /data in time. Continue wait. */
1723 SLOGE("waited 15s for vold.post_fs_data_done, still waiting...");
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001724 }
Wei Wang42e38102017-06-07 10:46:12 -07001725 SLOGD("post_fs_data done");
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001726}
1727
Paul Lawrence74f29f12014-08-28 15:54:10 -07001728static void cryptfs_set_corrupt()
1729{
1730 // Mark the footer as bad
1731 struct crypt_mnt_ftr crypt_ftr;
1732 if (get_crypt_ftr_and_key(&crypt_ftr)) {
1733 SLOGE("Failed to get crypto footer - panic");
1734 return;
1735 }
1736
1737 crypt_ftr.flags |= CRYPT_DATA_CORRUPT;
1738 if (put_crypt_ftr_and_key(&crypt_ftr)) {
1739 SLOGE("Failed to set crypto footer - panic");
1740 return;
1741 }
1742}
1743
1744static void cryptfs_trigger_restart_min_framework()
1745{
1746 if (fs_mgr_do_tmpfs_mount(DATA_MNT_POINT)) {
1747 SLOGE("Failed to mount tmpfs on data - panic");
1748 return;
1749 }
1750
1751 if (property_set("vold.decrypt", "trigger_post_fs_data")) {
1752 SLOGE("Failed to trigger post fs data - panic");
1753 return;
1754 }
1755
1756 if (property_set("vold.decrypt", "trigger_restart_min_framework")) {
1757 SLOGE("Failed to trigger restart min framework - panic");
1758 return;
1759 }
1760}
1761
Paul Lawrence8e3f4512014-09-08 10:11:17 -07001762/* returns < 0 on failure */
Paul Lawrencef4faa572014-01-29 13:31:03 -08001763static int cryptfs_restart_internal(int restart_main)
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001764{
Ken Sumrall6864b7e2011-01-14 15:20:02 -08001765 char crypto_blkdev[MAXPATHLEN];
AnilKumar Chimatad08106a2018-02-11 17:11:24 +05301766#ifdef CONFIG_HW_DISK_ENCRYPTION
1767 char blkdev[MAXPATHLEN];
1768#endif
Tim Murray8439dc92014-12-15 11:56:11 -08001769 int rc = -1;
Ken Sumrall0cc16632011-01-18 20:32:26 -08001770 static int restart_successful = 0;
1771
1772 /* Validate that it's OK to call this routine */
Jason parks70a4b3f2011-01-28 10:10:47 -06001773 if (! master_key_saved) {
Ken Sumrall0cc16632011-01-18 20:32:26 -08001774 SLOGE("Encrypted filesystem not validated, aborting");
1775 return -1;
1776 }
1777
1778 if (restart_successful) {
1779 SLOGE("System already restarted with encrypted disk, aborting");
1780 return -1;
1781 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001782
Paul Lawrencef4faa572014-01-29 13:31:03 -08001783 if (restart_main) {
1784 /* Here is where we shut down the framework. The init scripts
1785 * start all services in one of three classes: core, main or late_start.
1786 * On boot, we start core and main. Now, we stop main, but not core,
1787 * as core includes vold and a few other really important things that
1788 * we need to keep running. Once main has stopped, we should be able
1789 * to umount the tmpfs /data, then mount the encrypted /data.
1790 * We then restart the class main, and also the class late_start.
1791 * At the moment, I've only put a few things in late_start that I know
1792 * are not needed to bring up the framework, and that also cause problems
1793 * with unmounting the tmpfs /data, but I hope to add add more services
1794 * to the late_start class as we optimize this to decrease the delay
1795 * till the user is asked for the password to the filesystem.
1796 */
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001797
Paul Lawrencef4faa572014-01-29 13:31:03 -08001798 /* The init files are setup to stop the class main when vold.decrypt is
1799 * set to trigger_reset_main.
1800 */
1801 property_set("vold.decrypt", "trigger_reset_main");
1802 SLOGD("Just asked init to shut down class main\n");
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001803
Paul Lawrencef4faa572014-01-29 13:31:03 -08001804 /* Ugh, shutting down the framework is not synchronous, so until it
1805 * can be fixed, this horrible hack will wait a moment for it all to
1806 * shut down before proceeding. Without it, some devices cannot
1807 * restart the graphics services.
1808 */
1809 sleep(2);
1810 }
Ken Sumrall9dedfd42012-10-09 14:16:59 -07001811
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001812 /* Now that the framework is shutdown, we should be able to umount()
1813 * the tmpfs filesystem, and mount the real one.
1814 */
1815
AnilKumar Chimatad08106a2018-02-11 17:11:24 +05301816#if defined(CONFIG_HW_DISK_ENCRYPTION)
1817#if defined(CONFIG_HW_DISK_ENCRYPT_PERF)
1818 if (is_ice_enabled()) {
1819 fs_mgr_get_crypt_info(fstab_default, 0, blkdev, sizeof(blkdev));
1820 if (set_ice_param(START_ENCDEC)) {
1821 SLOGE("Failed to set ICE data");
1822 return -1;
1823 }
1824 }
1825#else
1826 property_get("ro.crypto.fs_crypto_blkdev", blkdev, "");
1827 if (strlen(blkdev) == 0) {
1828 SLOGE("fs_crypto_blkdev not set\n");
1829 return -1;
1830 }
1831 if (!(rc = wait_and_unmount(DATA_MNT_POINT, true))) {
1832#endif
1833#else
Ken Sumrall6864b7e2011-01-14 15:20:02 -08001834 property_get("ro.crypto.fs_crypto_blkdev", crypto_blkdev, "");
1835 if (strlen(crypto_blkdev) == 0) {
1836 SLOGE("fs_crypto_blkdev not set\n");
1837 return -1;
1838 }
1839
Greg Hackmann6e8440f2014-10-02 17:18:20 -07001840 if (! (rc = wait_and_unmount(DATA_MNT_POINT, true)) ) {
AnilKumar Chimatad08106a2018-02-11 17:11:24 +05301841#endif
Doug Zongker6fd57712013-12-17 09:43:23 -08001842 /* If ro.crypto.readonly is set to 1, mount the decrypted
1843 * filesystem readonly. This is used when /data is mounted by
1844 * recovery mode.
1845 */
1846 char ro_prop[PROPERTY_VALUE_MAX];
1847 property_get("ro.crypto.readonly", ro_prop, "");
Jeff Sharkey95440eb2017-09-18 18:19:28 -06001848 if (strlen(ro_prop) > 0 && std::stoi(ro_prop)) {
Paul Crowleye2ee1522017-09-26 14:05:26 -07001849 struct fstab_rec* rec = fs_mgr_get_entry_for_mount_point(fstab_default, DATA_MNT_POINT);
Luis Hector Chavezf86566f2018-05-30 15:47:50 -07001850 if (rec) {
1851 rec->flags |= MS_RDONLY;
1852 }
Doug Zongker6fd57712013-12-17 09:43:23 -08001853 }
JP Abgrall62c7af32014-06-16 13:01:23 -07001854
Ken Sumralle5032c42012-04-01 23:58:44 -07001855 /* If that succeeded, then mount the decrypted filesystem */
Paul Lawrence8e3f4512014-09-08 10:11:17 -07001856 int retries = RETRY_MOUNT_ATTEMPTS;
1857 int mount_rc;
Jeff Vander Stoepdf725752016-01-29 15:34:43 -08001858
1859 /*
1860 * fs_mgr_do_mount runs fsck. Use setexeccon to run trusted
1861 * partitions in the fsck domain.
1862 */
1863 if (setexeccon(secontextFsck())){
1864 SLOGE("Failed to setexeccon");
1865 return -1;
1866 }
AnilKumar Chimatad08106a2018-02-11 17:11:24 +05301867#ifdef CONFIG_HW_DISK_ENCRYPTION
1868 while ((mount_rc = fs_mgr_do_mount(fstab_default, DATA_MNT_POINT,
1869 blkdev, 0))
1870 != 0) {
1871#else
Paul Crowleye2ee1522017-09-26 14:05:26 -07001872 while ((mount_rc = fs_mgr_do_mount(fstab_default, DATA_MNT_POINT,
Paul Lawrence8e3f4512014-09-08 10:11:17 -07001873 crypto_blkdev, 0))
1874 != 0) {
AnilKumar Chimatad08106a2018-02-11 17:11:24 +05301875#endif
Paul Lawrence8e3f4512014-09-08 10:11:17 -07001876 if (mount_rc == FS_MGR_DOMNT_BUSY) {
1877 /* TODO: invoke something similar to
1878 Process::killProcessWithOpenFiles(DATA_MNT_POINT,
1879 retries > RETRY_MOUNT_ATTEMPT/2 ? 1 : 2 ) */
AnilKumar Chimatad08106a2018-02-11 17:11:24 +05301880#ifdef CONFIG_HW_DISK_ENCRYPTION
1881 SLOGI("Failed to mount %s because it is busy - waiting",
1882 blkdev);
1883#else
Paul Lawrence8e3f4512014-09-08 10:11:17 -07001884 SLOGI("Failed to mount %s because it is busy - waiting",
1885 crypto_blkdev);
AnilKumar Chimatad08106a2018-02-11 17:11:24 +05301886#endif
Paul Lawrence8e3f4512014-09-08 10:11:17 -07001887 if (--retries) {
1888 sleep(RETRY_MOUNT_DELAY_SECONDS);
1889 } else {
1890 /* Let's hope that a reboot clears away whatever is keeping
1891 the mount busy */
Josh Gaofec44372017-08-28 13:22:55 -07001892 cryptfs_reboot(RebootType::reboot);
Paul Lawrence8e3f4512014-09-08 10:11:17 -07001893 }
1894 } else {
AnilKumar Chimata98dc8352018-05-11 00:25:09 +05301895#ifdef CONFIG_HW_DISK_ENCRYPTION
1896 if (--retries) {
1897 sleep(RETRY_MOUNT_DELAY_SECONDS);
1898 } else {
1899 SLOGE("Failed to mount decrypted data");
1900 cryptfs_set_corrupt();
1901 cryptfs_trigger_restart_min_framework();
1902 SLOGI("Started framework to offer wipe");
1903 return -1;
1904 }
1905#else
Paul Lawrence8e3f4512014-09-08 10:11:17 -07001906 SLOGE("Failed to mount decrypted data");
1907 cryptfs_set_corrupt();
1908 cryptfs_trigger_restart_min_framework();
1909 SLOGI("Started framework to offer wipe");
Jeff Vander Stoepdf725752016-01-29 15:34:43 -08001910 if (setexeccon(NULL)) {
1911 SLOGE("Failed to setexeccon");
1912 }
Paul Lawrence8e3f4512014-09-08 10:11:17 -07001913 return -1;
AnilKumar Chimata98dc8352018-05-11 00:25:09 +05301914#endif
Paul Lawrence8e3f4512014-09-08 10:11:17 -07001915 }
Paul Lawrence74f29f12014-08-28 15:54:10 -07001916 }
Jeff Vander Stoepdf725752016-01-29 15:34:43 -08001917 if (setexeccon(NULL)) {
1918 SLOGE("Failed to setexeccon");
1919 return -1;
1920 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001921
Ken Sumralle5032c42012-04-01 23:58:44 -07001922 /* Create necessary paths on /data */
Wei Wang42e38102017-06-07 10:46:12 -07001923 prep_data_fs();
Seigo Nonakae2ef0c02016-06-20 17:05:40 +09001924 property_set("vold.decrypt", "trigger_load_persist_props");
Ken Sumralle5032c42012-04-01 23:58:44 -07001925
1926 /* startup service classes main and late_start */
1927 property_set("vold.decrypt", "trigger_restart_framework");
1928 SLOGD("Just triggered restart_framework\n");
1929
1930 /* Give it a few moments to get started */
1931 sleep(1);
AnilKumar Chimatad08106a2018-02-11 17:11:24 +05301932#ifndef CONFIG_HW_DISK_ENCRYPT_PERF
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001933 }
AnilKumar Chimatad08106a2018-02-11 17:11:24 +05301934#endif
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001935
Ken Sumrall0cc16632011-01-18 20:32:26 -08001936 if (rc == 0) {
1937 restart_successful = 1;
1938 }
1939
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001940 return rc;
1941}
1942
Paul Lawrencef4faa572014-01-29 13:31:03 -08001943int cryptfs_restart(void)
1944{
Paul Lawrence05335c32015-03-05 09:46:23 -08001945 SLOGI("cryptfs_restart");
Paul Crowley38132a12016-02-09 09:50:32 +00001946 if (e4crypt_is_native()) {
Paul Lawrence7b6b5652016-02-02 11:14:59 -08001947 SLOGE("cryptfs_restart not valid for file encryption:");
1948 return -1;
Paul Lawrence05335c32015-03-05 09:46:23 -08001949 }
1950
Paul Lawrencef4faa572014-01-29 13:31:03 -08001951 /* Call internal implementation forcing a restart of main service group */
1952 return cryptfs_restart_internal(1);
1953}
1954
Wei Wang4375f1b2017-02-24 17:43:01 -08001955static int do_crypto_complete(const char *mount_point)
Ken Sumrall7f7dbaa2011-02-01 15:46:41 -08001956{
1957 struct crypt_mnt_ftr crypt_ftr;
Ken Sumrall29d8da82011-05-18 17:20:07 -07001958 char encrypted_state[PROPERTY_VALUE_MAX];
Ken Sumralle1a45852011-12-14 21:24:27 -08001959 char key_loc[PROPERTY_VALUE_MAX];
Ken Sumrall7f7dbaa2011-02-01 15:46:41 -08001960
1961 property_get("ro.crypto.state", encrypted_state, "");
1962 if (strcmp(encrypted_state, "encrypted") ) {
1963 SLOGE("not running with encryption, aborting");
Paul Lawrence74f29f12014-08-28 15:54:10 -07001964 return CRYPTO_COMPLETE_NOT_ENCRYPTED;
Ken Sumrall7f7dbaa2011-02-01 15:46:41 -08001965 }
1966
Paul Lawrence7b6b5652016-02-02 11:14:59 -08001967 // crypto_complete is full disk encrypted status
Paul Crowley38132a12016-02-09 09:50:32 +00001968 if (e4crypt_is_native()) {
Paul Lawrence7b6b5652016-02-02 11:14:59 -08001969 return CRYPTO_COMPLETE_NOT_ENCRYPTED;
Paul Lawrence05335c32015-03-05 09:46:23 -08001970 }
1971
Ken Sumrall160b4d62013-04-22 12:15:39 -07001972 if (get_crypt_ftr_and_key(&crypt_ftr)) {
Paul Crowleye2ee1522017-09-26 14:05:26 -07001973 fs_mgr_get_crypt_info(fstab_default, key_loc, 0, sizeof(key_loc));
Ken Sumralle5032c42012-04-01 23:58:44 -07001974
Ken Sumralle1a45852011-12-14 21:24:27 -08001975 /*
1976 * Only report this error if key_loc is a file and it exists.
1977 * If the device was never encrypted, and /data is not mountable for
1978 * some reason, returning 1 should prevent the UI from presenting the
1979 * a "enter password" screen, or worse, a "press button to wipe the
1980 * device" screen.
1981 */
1982 if ((key_loc[0] == '/') && (access("key_loc", F_OK) == -1)) {
1983 SLOGE("master key file does not exist, aborting");
Paul Lawrence74f29f12014-08-28 15:54:10 -07001984 return CRYPTO_COMPLETE_NOT_ENCRYPTED;
Ken Sumralle1a45852011-12-14 21:24:27 -08001985 } else {
1986 SLOGE("Error getting crypt footer and key\n");
Paul Lawrence74f29f12014-08-28 15:54:10 -07001987 return CRYPTO_COMPLETE_BAD_METADATA;
Ken Sumralle1a45852011-12-14 21:24:27 -08001988 }
Ken Sumrall7f7dbaa2011-02-01 15:46:41 -08001989 }
1990
Paul Lawrence74f29f12014-08-28 15:54:10 -07001991 // Test for possible error flags
1992 if (crypt_ftr.flags & CRYPT_ENCRYPTION_IN_PROGRESS){
1993 SLOGE("Encryption process is partway completed\n");
1994 return CRYPTO_COMPLETE_PARTIAL;
1995 }
1996
1997 if (crypt_ftr.flags & CRYPT_INCONSISTENT_STATE){
1998 SLOGE("Encryption process was interrupted but cannot continue\n");
1999 return CRYPTO_COMPLETE_INCONSISTENT;
2000 }
2001
2002 if (crypt_ftr.flags & CRYPT_DATA_CORRUPT){
2003 SLOGE("Encryption is successful but data is corrupt\n");
2004 return CRYPTO_COMPLETE_CORRUPT;
Ken Sumrall7f7dbaa2011-02-01 15:46:41 -08002005 }
2006
2007 /* We passed the test! We shall diminish, and return to the west */
Paul Lawrence74f29f12014-08-28 15:54:10 -07002008 return CRYPTO_COMPLETE_ENCRYPTED;
Ken Sumrall7f7dbaa2011-02-01 15:46:41 -08002009}
2010
AnilKumar Chimata98dc8352018-05-11 00:25:09 +05302011#ifdef CONFIG_HW_DISK_ENCRYPTION
2012static int test_mount_hw_encrypted_fs(struct crypt_mnt_ftr* crypt_ftr,
2013 const char *passwd, const char *mount_point, const char *label)
2014{
2015 /* Allocate enough space for a 256 bit key, but we may use less */
2016 unsigned char decrypted_master_key[32];
2017 char crypto_blkdev[MAXPATHLEN];
2018 char real_blkdev[MAXPATHLEN];
2019 unsigned int orig_failed_decrypt_count;
2020 int rc = 0;
2021
2022 SLOGD("crypt_ftr->fs_size = %lld\n", crypt_ftr->fs_size);
2023 orig_failed_decrypt_count = crypt_ftr->failed_decrypt_count;
2024
2025 fs_mgr_get_crypt_info(fstab_default, 0, real_blkdev, sizeof(real_blkdev));
2026
2027 int key_index = 0;
2028 if(is_hw_disk_encryption((char*)crypt_ftr->crypto_type_name)) {
2029 key_index = verify_and_update_hw_fde_passwd(passwd, crypt_ftr);
2030 if (key_index < 0) {
2031 rc = crypt_ftr->failed_decrypt_count;
2032 goto errout;
2033 }
2034 else {
2035 if (is_ice_enabled()) {
AnilKumar Chimatad08106a2018-02-11 17:11:24 +05302036#ifndef CONFIG_HW_DISK_ENCRYPT_PERF
AnilKumar Chimata98dc8352018-05-11 00:25:09 +05302037 if (create_crypto_blk_dev(crypt_ftr, (unsigned char*)&key_index,
2038 real_blkdev, crypto_blkdev, label, 0)) {
2039 SLOGE("Error creating decrypted block device");
2040 rc = -1;
2041 goto errout;
2042 }
AnilKumar Chimatad08106a2018-02-11 17:11:24 +05302043#endif
AnilKumar Chimata98dc8352018-05-11 00:25:09 +05302044 } else {
2045 if (create_crypto_blk_dev(crypt_ftr, decrypted_master_key,
2046 real_blkdev, crypto_blkdev, label, 0)) {
2047 SLOGE("Error creating decrypted block device");
2048 rc = -1;
2049 goto errout;
2050 }
2051 }
2052 }
2053 }
2054
2055 if (rc == 0) {
2056 crypt_ftr->failed_decrypt_count = 0;
2057 if (orig_failed_decrypt_count != 0) {
2058 put_crypt_ftr_and_key(crypt_ftr);
2059 }
2060
2061 /* Save the name of the crypto block device
2062 * so we can mount it when restarting the framework. */
AnilKumar Chimatad08106a2018-02-11 17:11:24 +05302063#ifdef CONFIG_HW_DISK_ENCRYPT_PERF
2064 if (!is_ice_enabled())
2065#endif
AnilKumar Chimata98dc8352018-05-11 00:25:09 +05302066 property_set("ro.crypto.fs_crypto_blkdev", crypto_blkdev);
2067 master_key_saved = 1;
2068 }
2069
2070 errout:
2071 return rc;
2072}
2073#endif
2074
2075
Paul Lawrencef4faa572014-01-29 13:31:03 -08002076static int test_mount_encrypted_fs(struct crypt_mnt_ftr* crypt_ftr,
Wei Wang4375f1b2017-02-24 17:43:01 -08002077 const char *passwd, const char *mount_point, const char *label)
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002078{
Greg Kaiser59ad0182018-02-16 13:01:36 -08002079 unsigned char decrypted_master_key[MAX_KEY_LEN];
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002080 char crypto_blkdev[MAXPATHLEN];
2081 char real_blkdev[MAXPATHLEN];
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002082 char tmp_mount_point[64];
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002083 unsigned int orig_failed_decrypt_count;
2084 int rc;
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07002085 int use_keymaster = 0;
2086 int upgrade = 0;
Paul Lawrenced0c7b172014-08-08 14:28:10 -07002087 unsigned char* intermediate_key = 0;
2088 size_t intermediate_key_size = 0;
Wei Wang4375f1b2017-02-24 17:43:01 -08002089 int N = 1 << crypt_ftr->N_factor;
2090 int r = 1 << crypt_ftr->r_factor;
2091 int p = 1 << crypt_ftr->p_factor;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002092
Paul Lawrencef4faa572014-01-29 13:31:03 -08002093 SLOGD("crypt_ftr->fs_size = %lld\n", crypt_ftr->fs_size);
2094 orig_failed_decrypt_count = crypt_ftr->failed_decrypt_count;
Ken Sumrall0cc16632011-01-18 20:32:26 -08002095
Paul Lawrencef4faa572014-01-29 13:31:03 -08002096 if (! (crypt_ftr->flags & CRYPT_MNT_KEY_UNENCRYPTED) ) {
Paul Lawrenced0c7b172014-08-08 14:28:10 -07002097 if (decrypt_master_key(passwd, decrypted_master_key, crypt_ftr,
2098 &intermediate_key, &intermediate_key_size)) {
JP Abgrall7bdfa522013-11-15 13:42:56 -08002099 SLOGE("Failed to decrypt master key\n");
Paul Lawrenced0c7b172014-08-08 14:28:10 -07002100 rc = -1;
2101 goto errout;
JP Abgrall7bdfa522013-11-15 13:42:56 -08002102 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002103 }
2104
Paul Crowleye2ee1522017-09-26 14:05:26 -07002105 fs_mgr_get_crypt_info(fstab_default, 0, real_blkdev, sizeof(real_blkdev));
Paul Lawrencef4faa572014-01-29 13:31:03 -08002106
Paul Lawrence74f29f12014-08-28 15:54:10 -07002107 // Create crypto block device - all (non fatal) code paths
2108 // need it
Paul Crowley5afbc622017-11-27 09:42:17 -08002109 if (create_crypto_blk_dev(crypt_ftr, decrypted_master_key, real_blkdev, crypto_blkdev, label, 0)) {
2110 SLOGE("Error creating decrypted block device\n");
2111 rc = -1;
2112 goto errout;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002113 }
2114
Paul Lawrence74f29f12014-08-28 15:54:10 -07002115 /* Work out if the problem is the password or the data */
2116 unsigned char scrypted_intermediate_key[sizeof(crypt_ftr->
2117 scrypted_intermediate_key)];
Paul Lawrenced0c7b172014-08-08 14:28:10 -07002118
Paul Lawrence74f29f12014-08-28 15:54:10 -07002119 rc = crypto_scrypt(intermediate_key, intermediate_key_size,
2120 crypt_ftr->salt, sizeof(crypt_ftr->salt),
2121 N, r, p, scrypted_intermediate_key,
2122 sizeof(scrypted_intermediate_key));
Paul Lawrenced0c7b172014-08-08 14:28:10 -07002123
Paul Lawrence74f29f12014-08-28 15:54:10 -07002124 // Does the key match the crypto footer?
2125 if (rc == 0 && memcmp(scrypted_intermediate_key,
2126 crypt_ftr->scrypted_intermediate_key,
2127 sizeof(scrypted_intermediate_key)) == 0) {
2128 SLOGI("Password matches");
2129 rc = 0;
2130 } else {
2131 /* Try mounting the file system anyway, just in case the problem's with
2132 * the footer, not the key. */
George Burgess IV605d7ae2016-02-29 13:39:17 -08002133 snprintf(tmp_mount_point, sizeof(tmp_mount_point), "%s/tmp_mnt",
2134 mount_point);
Paul Lawrence74f29f12014-08-28 15:54:10 -07002135 mkdir(tmp_mount_point, 0755);
Paul Crowleye2ee1522017-09-26 14:05:26 -07002136 if (fs_mgr_do_mount(fstab_default, DATA_MNT_POINT, crypto_blkdev, tmp_mount_point)) {
Paul Lawrence74f29f12014-08-28 15:54:10 -07002137 SLOGE("Error temp mounting decrypted block device\n");
2138 delete_crypto_blk_dev(label);
2139
Paul Lawrenced0c7b172014-08-08 14:28:10 -07002140 rc = ++crypt_ftr->failed_decrypt_count;
2141 put_crypt_ftr_and_key(crypt_ftr);
Paul Lawrence74f29f12014-08-28 15:54:10 -07002142 } else {
2143 /* Success! */
2144 SLOGI("Password did not match but decrypted drive mounted - continue");
2145 umount(tmp_mount_point);
2146 rc = 0;
Paul Lawrenced0c7b172014-08-08 14:28:10 -07002147 }
Paul Lawrence74f29f12014-08-28 15:54:10 -07002148 }
2149
2150 if (rc == 0) {
2151 crypt_ftr->failed_decrypt_count = 0;
Paul Lawrence72b8b822014-10-05 12:57:37 -07002152 if (orig_failed_decrypt_count != 0) {
2153 put_crypt_ftr_and_key(crypt_ftr);
2154 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002155
Paul Lawrenced0c7b172014-08-08 14:28:10 -07002156 /* Save the name of the crypto block device
Paul Lawrence74f29f12014-08-28 15:54:10 -07002157 * so we can mount it when restarting the framework. */
Ken Sumrall6864b7e2011-01-14 15:20:02 -08002158 property_set("ro.crypto.fs_crypto_blkdev", crypto_blkdev);
Jason parks70a4b3f2011-01-28 10:10:47 -06002159
2160 /* Also save a the master key so we can reencrypted the key
Paul Lawrence74f29f12014-08-28 15:54:10 -07002161 * the key when we want to change the password on it. */
Greg Kaiser59ad0182018-02-16 13:01:36 -08002162 memcpy(saved_master_key, decrypted_master_key, crypt_ftr->keysize);
Ken Sumrall3ad90722011-10-04 20:38:29 -07002163 saved_mount_point = strdup(mount_point);
Jason parks70a4b3f2011-01-28 10:10:47 -06002164 master_key_saved = 1;
JP Abgrall7bdfa522013-11-15 13:42:56 -08002165 SLOGD("%s(): Master key saved\n", __FUNCTION__);
Ken Sumrall6864b7e2011-01-14 15:20:02 -08002166 rc = 0;
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07002167
Paul Lawrence74f29f12014-08-28 15:54:10 -07002168 // Upgrade if we're not using the latest KDF.
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07002169 use_keymaster = keymaster_check_compatibility();
2170 if (crypt_ftr->kdf_type == KDF_SCRYPT_KEYMASTER) {
Shawn Willden47ba10d2014-09-03 17:07:06 -06002171 // Don't allow downgrade
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07002172 } else if (use_keymaster == 1 && crypt_ftr->kdf_type != KDF_SCRYPT_KEYMASTER) {
2173 crypt_ftr->kdf_type = KDF_SCRYPT_KEYMASTER;
2174 upgrade = 1;
2175 } else if (use_keymaster == 0 && crypt_ftr->kdf_type != KDF_SCRYPT) {
Paul Lawrencef4faa572014-01-29 13:31:03 -08002176 crypt_ftr->kdf_type = KDF_SCRYPT;
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07002177 upgrade = 1;
2178 }
2179
2180 if (upgrade) {
Paul Lawrencef4faa572014-01-29 13:31:03 -08002181 rc = encrypt_master_key(passwd, crypt_ftr->salt, saved_master_key,
AnilKumar Chimata98dc8352018-05-11 00:25:09 +05302182 crypt_ftr->master_key, crypt_ftr, true);
JP Abgrall7bdfa522013-11-15 13:42:56 -08002183 if (!rc) {
Paul Lawrencef4faa572014-01-29 13:31:03 -08002184 rc = put_crypt_ftr_and_key(crypt_ftr);
JP Abgrall7bdfa522013-11-15 13:42:56 -08002185 }
2186 SLOGD("Key Derivation Function upgrade: rc=%d\n", rc);
Paul Lawrenceb2f682b2014-09-08 11:28:19 -07002187
2188 // Do not fail even if upgrade failed - machine is bootable
2189 // Note that if this code is ever hit, there is a *serious* problem
2190 // since KDFs should never fail. You *must* fix the kdf before
2191 // proceeding!
2192 if (rc) {
2193 SLOGW("Upgrade failed with error %d,"
2194 " but continuing with previous state",
2195 rc);
2196 rc = 0;
2197 }
JP Abgrall7bdfa522013-11-15 13:42:56 -08002198 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002199 }
2200
Paul Lawrenced0c7b172014-08-08 14:28:10 -07002201 errout:
2202 if (intermediate_key) {
2203 memset(intermediate_key, 0, intermediate_key_size);
2204 free(intermediate_key);
2205 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002206 return rc;
2207}
2208
Ken Sumrall29d8da82011-05-18 17:20:07 -07002209/*
Jeff Sharkey9c484982015-03-31 10:35:33 -07002210 * Called by vold when it's asked to mount an encrypted external
2211 * storage volume. The incoming partition has no crypto header/footer,
Greg Kaiser57f9af62018-02-16 13:13:58 -08002212 * as any metadata is been stored in a separate, small partition. We
2213 * assume it must be using our same crypt type and keysize.
Jeff Sharkey9c484982015-03-31 10:35:33 -07002214 *
2215 * out_crypto_blkdev must be MAXPATHLEN.
Ken Sumrall29d8da82011-05-18 17:20:07 -07002216 */
Jeff Sharkey9c484982015-03-31 10:35:33 -07002217int cryptfs_setup_ext_volume(const char* label, const char* real_blkdev,
Greg Kaiser57f9af62018-02-16 13:13:58 -08002218 const unsigned char* key, char* out_crypto_blkdev) {
Jeff Sharkeyce6a9132015-04-08 21:07:21 -07002219 int fd = open(real_blkdev, O_RDONLY|O_CLOEXEC);
Hiroaki Miyazawa14eab552015-02-04 13:29:15 +09002220 if (fd == -1) {
Jeff Sharkey9c484982015-03-31 10:35:33 -07002221 SLOGE("Failed to open %s: %s", real_blkdev, strerror(errno));
Hiroaki Miyazawa14eab552015-02-04 13:29:15 +09002222 return -1;
2223 }
2224
2225 unsigned long nr_sec = 0;
2226 get_blkdev_size(fd, &nr_sec);
Ken Sumrall29d8da82011-05-18 17:20:07 -07002227 close(fd);
Hiroaki Miyazawa14eab552015-02-04 13:29:15 +09002228
Ken Sumrall29d8da82011-05-18 17:20:07 -07002229 if (nr_sec == 0) {
Jeff Sharkey9c484982015-03-31 10:35:33 -07002230 SLOGE("Failed to get size of %s: %s", real_blkdev, strerror(errno));
Ken Sumrall29d8da82011-05-18 17:20:07 -07002231 return -1;
2232 }
2233
Jeff Sharkey9c484982015-03-31 10:35:33 -07002234 struct crypt_mnt_ftr ext_crypt_ftr;
2235 memset(&ext_crypt_ftr, 0, sizeof(ext_crypt_ftr));
2236 ext_crypt_ftr.fs_size = nr_sec;
Greg Kaiser57f9af62018-02-16 13:13:58 -08002237 ext_crypt_ftr.keysize = cryptfs_get_keysize();
2238 strlcpy((char*) ext_crypt_ftr.crypto_type_name, cryptfs_get_crypto_name(),
Jeff Sharkey32ebb732017-03-27 16:18:50 -06002239 MAX_CRYPTO_TYPE_NAME_LEN);
Paul Crowley385cb8c2018-03-29 13:27:23 -07002240 uint32_t flags = 0;
2241 if (e4crypt_is_native() &&
2242 android::base::GetBoolProperty("ro.crypto.allow_encrypt_override", false))
2243 flags |= CREATE_CRYPTO_BLK_DEV_FLAGS_ALLOW_ENCRYPT_OVERRIDE;
Ken Sumrall29d8da82011-05-18 17:20:07 -07002244
Paul Crowley385cb8c2018-03-29 13:27:23 -07002245 return create_crypto_blk_dev(&ext_crypt_ftr, key, real_blkdev, out_crypto_blkdev, label, flags);
Jeff Sharkey9c484982015-03-31 10:35:33 -07002246}
Ken Sumrall29d8da82011-05-18 17:20:07 -07002247
Jeff Sharkey9c484982015-03-31 10:35:33 -07002248/*
2249 * Called by vold when it's asked to unmount an encrypted external
2250 * storage volume.
2251 */
2252int cryptfs_revert_ext_volume(const char* label) {
2253 return delete_crypto_blk_dev((char*) label);
Ken Sumrall29d8da82011-05-18 17:20:07 -07002254}
2255
Ken Sumrall7f7dbaa2011-02-01 15:46:41 -08002256int cryptfs_crypto_complete(void)
2257{
2258 return do_crypto_complete("/data");
2259}
2260
Paul Lawrencef4faa572014-01-29 13:31:03 -08002261int check_unmounted_and_get_ftr(struct crypt_mnt_ftr* crypt_ftr)
2262{
2263 char encrypted_state[PROPERTY_VALUE_MAX];
2264 property_get("ro.crypto.state", encrypted_state, "");
2265 if ( master_key_saved || strcmp(encrypted_state, "encrypted") ) {
2266 SLOGE("encrypted fs already validated or not running with encryption,"
2267 " aborting");
2268 return -1;
2269 }
2270
2271 if (get_crypt_ftr_and_key(crypt_ftr)) {
2272 SLOGE("Error getting crypt footer and key");
2273 return -1;
2274 }
2275
2276 return 0;
2277}
2278
AnilKumar Chimata98dc8352018-05-11 00:25:09 +05302279#ifdef CONFIG_HW_DISK_ENCRYPTION
2280int cryptfs_check_passwd_hw(const char* passwd)
2281{
2282 struct crypt_mnt_ftr crypt_ftr;
2283 int rc;
2284 unsigned char master_key[KEY_LEN_BYTES];
2285
2286 /* get key */
2287 if (get_crypt_ftr_and_key(&crypt_ftr)) {
2288 SLOGE("Error getting crypt footer and key");
2289 return -1;
2290 }
2291
2292 /*
2293 * in case of manual encryption (from GUI), the encryption is done with
2294 * default password
2295 */
2296 if (crypt_ftr.flags & CRYPT_FORCE_COMPLETE) {
2297 /* compare scrypted_intermediate_key with stored scrypted_intermediate_key
2298 * which was created with actual password before reboot.
2299 */
2300 rc = cryptfs_get_master_key(&crypt_ftr, passwd, master_key);
2301 if (rc) {
2302 SLOGE("password doesn't match");
2303 rc = ++crypt_ftr.failed_decrypt_count;
2304 put_crypt_ftr_and_key(&crypt_ftr);
2305 return rc;
2306 }
2307
2308 rc = test_mount_hw_encrypted_fs(&crypt_ftr, DEFAULT_PASSWORD,
2309 DATA_MNT_POINT, CRYPTO_BLOCK_DEVICE);
2310
2311 if (rc) {
2312 SLOGE("Default password did not match on reboot encryption");
2313 return rc;
2314 }
2315
2316 crypt_ftr.flags &= ~CRYPT_FORCE_COMPLETE;
2317 put_crypt_ftr_and_key(&crypt_ftr);
2318 rc = cryptfs_changepw(crypt_ftr.crypt_type, DEFAULT_PASSWORD, passwd);
2319 if (rc) {
2320 SLOGE("Could not change password on reboot encryption");
2321 return rc;
2322 }
2323 } else
2324 rc = test_mount_hw_encrypted_fs(&crypt_ftr, passwd,
2325 DATA_MNT_POINT, CRYPTO_BLOCK_DEVICE);
2326
2327 if (crypt_ftr.crypt_type != CRYPT_TYPE_DEFAULT) {
2328 cryptfs_clear_password();
2329 password = strdup(passwd);
2330 struct timespec now;
2331 clock_gettime(CLOCK_BOOTTIME, &now);
2332 password_expiry_time = now.tv_sec + password_max_age_seconds;
2333 }
2334
2335 return rc;
2336}
2337#endif
2338
Wei Wang4375f1b2017-02-24 17:43:01 -08002339int cryptfs_check_passwd(const char *passwd)
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002340{
Paul Lawrence05335c32015-03-05 09:46:23 -08002341 SLOGI("cryptfs_check_passwd");
Paul Crowley38132a12016-02-09 09:50:32 +00002342 if (e4crypt_is_native()) {
Paul Lawrence7b6b5652016-02-02 11:14:59 -08002343 SLOGE("cryptfs_check_passwd not valid for file encryption");
2344 return -1;
Paul Lawrence05335c32015-03-05 09:46:23 -08002345 }
2346
Paul Lawrencef4faa572014-01-29 13:31:03 -08002347 struct crypt_mnt_ftr crypt_ftr;
2348 int rc;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002349
Paul Lawrencef4faa572014-01-29 13:31:03 -08002350 rc = check_unmounted_and_get_ftr(&crypt_ftr);
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002351 if (rc) {
2352 SLOGE("Could not get footer");
Paul Lawrencef4faa572014-01-29 13:31:03 -08002353 return rc;
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002354 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002355
AnilKumar Chimata98dc8352018-05-11 00:25:09 +05302356#ifdef CONFIG_HW_DISK_ENCRYPTION
2357 if (is_hw_disk_encryption((char*)crypt_ftr.crypto_type_name))
2358 return cryptfs_check_passwd_hw(passwd);
2359#endif
2360
Paul Lawrence3bd36d52015-06-09 13:37:44 -07002361 rc = test_mount_encrypted_fs(&crypt_ftr, passwd,
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002362 DATA_MNT_POINT, CRYPTO_BLOCK_DEVICE);
AnilKumar Chimata98dc8352018-05-11 00:25:09 +05302363
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002364 if (rc) {
2365 SLOGE("Password did not match");
2366 return rc;
2367 }
Paul Lawrence684dbdf2014-02-07 12:07:22 -08002368
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002369 if (crypt_ftr.flags & CRYPT_FORCE_COMPLETE) {
2370 // Here we have a default actual password but a real password
2371 // we must test against the scrypted value
2372 // First, we must delete the crypto block device that
2373 // test_mount_encrypted_fs leaves behind as a side effect
2374 delete_crypto_blk_dev(CRYPTO_BLOCK_DEVICE);
2375 rc = test_mount_encrypted_fs(&crypt_ftr, DEFAULT_PASSWORD,
2376 DATA_MNT_POINT, CRYPTO_BLOCK_DEVICE);
2377 if (rc) {
2378 SLOGE("Default password did not match on reboot encryption");
2379 return rc;
2380 }
2381
2382 crypt_ftr.flags &= ~CRYPT_FORCE_COMPLETE;
2383 put_crypt_ftr_and_key(&crypt_ftr);
AnilKumar Chimata98dc8352018-05-11 00:25:09 +05302384 rc = cryptfs_changepw(crypt_ftr.crypt_type, DEFAULT_PASSWORD, passwd);
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002385 if (rc) {
2386 SLOGE("Could not change password on reboot encryption");
2387 return rc;
2388 }
2389 }
2390
2391 if (crypt_ftr.crypt_type != CRYPT_TYPE_DEFAULT) {
Paul Lawrence399317e2014-03-10 13:20:50 -07002392 cryptfs_clear_password();
2393 password = strdup(passwd);
2394 struct timespec now;
2395 clock_gettime(CLOCK_BOOTTIME, &now);
2396 password_expiry_time = now.tv_sec + password_max_age_seconds;
Paul Lawrence684dbdf2014-02-07 12:07:22 -08002397 }
2398
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002399 return rc;
2400}
2401
Jeff Sharkey83b559c2017-09-12 16:30:52 -06002402int cryptfs_verify_passwd(const char *passwd)
Ken Sumrall3ad90722011-10-04 20:38:29 -07002403{
2404 struct crypt_mnt_ftr crypt_ftr;
Greg Kaiser59ad0182018-02-16 13:01:36 -08002405 unsigned char decrypted_master_key[MAX_KEY_LEN];
Ken Sumrall3ad90722011-10-04 20:38:29 -07002406 char encrypted_state[PROPERTY_VALUE_MAX];
2407 int rc;
2408
2409 property_get("ro.crypto.state", encrypted_state, "");
2410 if (strcmp(encrypted_state, "encrypted") ) {
2411 SLOGE("device not encrypted, aborting");
2412 return -2;
2413 }
2414
2415 if (!master_key_saved) {
2416 SLOGE("encrypted fs not yet mounted, aborting");
2417 return -1;
2418 }
2419
2420 if (!saved_mount_point) {
2421 SLOGE("encrypted fs failed to save mount point, aborting");
2422 return -1;
2423 }
2424
Ken Sumrall160b4d62013-04-22 12:15:39 -07002425 if (get_crypt_ftr_and_key(&crypt_ftr)) {
Ken Sumrall3ad90722011-10-04 20:38:29 -07002426 SLOGE("Error getting crypt footer and key\n");
2427 return -1;
2428 }
2429
2430 if (crypt_ftr.flags & CRYPT_MNT_KEY_UNENCRYPTED) {
2431 /* If the device has no password, then just say the password is valid */
2432 rc = 0;
2433 } else {
AnilKumar Chimata98dc8352018-05-11 00:25:09 +05302434#ifdef CONFIG_HW_DISK_ENCRYPTION
2435 if(is_hw_disk_encryption((char*)crypt_ftr.crypto_type_name)) {
2436 if (verify_hw_fde_passwd(passwd, &crypt_ftr) >= 0)
2437 rc = 0;
2438 else
2439 rc = -1;
2440 } else {
2441 decrypt_master_key(passwd, decrypted_master_key, &crypt_ftr, 0, 0);
2442 if (!memcmp(decrypted_master_key, saved_master_key, crypt_ftr.keysize)) {
2443 /* They match, the password is correct */
2444 rc = 0;
2445 } else {
2446 /* If incorrect, sleep for a bit to prevent dictionary attacks */
2447 sleep(1);
2448 rc = 1;
2449 }
2450 }
2451#else
Paul Lawrenced0c7b172014-08-08 14:28:10 -07002452 decrypt_master_key(passwd, decrypted_master_key, &crypt_ftr, 0, 0);
Ken Sumrall3ad90722011-10-04 20:38:29 -07002453 if (!memcmp(decrypted_master_key, saved_master_key, crypt_ftr.keysize)) {
2454 /* They match, the password is correct */
2455 rc = 0;
2456 } else {
2457 /* If incorrect, sleep for a bit to prevent dictionary attacks */
2458 sleep(1);
2459 rc = 1;
2460 }
AnilKumar Chimata98dc8352018-05-11 00:25:09 +05302461#endif
Ken Sumrall3ad90722011-10-04 20:38:29 -07002462 }
2463
2464 return rc;
2465}
2466
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002467/* Initialize a crypt_mnt_ftr structure. The keysize is
Greg Kaiser57f9af62018-02-16 13:13:58 -08002468 * defaulted to cryptfs_get_keysize() bytes, and the filesystem size to 0.
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002469 * Presumably, at a minimum, the caller will update the
2470 * filesystem size and crypto_type_name after calling this function.
2471 */
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07002472static int cryptfs_init_crypt_mnt_ftr(struct crypt_mnt_ftr *ftr)
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002473{
Ken Sumrall160b4d62013-04-22 12:15:39 -07002474 off64_t off;
2475
2476 memset(ftr, 0, sizeof(struct crypt_mnt_ftr));
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002477 ftr->magic = CRYPT_MNT_MAGIC;
Kenny Rootc96a5f82013-06-14 12:08:28 -07002478 ftr->major_version = CURRENT_MAJOR_VERSION;
2479 ftr->minor_version = CURRENT_MINOR_VERSION;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002480 ftr->ftr_size = sizeof(struct crypt_mnt_ftr);
Greg Kaiser57f9af62018-02-16 13:13:58 -08002481 ftr->keysize = cryptfs_get_keysize();
Ken Sumrall160b4d62013-04-22 12:15:39 -07002482
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07002483 switch (keymaster_check_compatibility()) {
2484 case 1:
2485 ftr->kdf_type = KDF_SCRYPT_KEYMASTER;
2486 break;
2487
2488 case 0:
2489 ftr->kdf_type = KDF_SCRYPT;
2490 break;
2491
2492 default:
2493 SLOGE("keymaster_check_compatibility failed");
2494 return -1;
2495 }
2496
Kenny Rootc4c70f12013-06-14 12:11:38 -07002497 get_device_scrypt_params(ftr);
2498
Ken Sumrall160b4d62013-04-22 12:15:39 -07002499 ftr->persist_data_size = CRYPT_PERSIST_DATA_SIZE;
2500 if (get_crypt_ftr_info(NULL, &off) == 0) {
2501 ftr->persist_data_offset[0] = off + CRYPT_FOOTER_TO_PERSIST_OFFSET;
2502 ftr->persist_data_offset[1] = off + CRYPT_FOOTER_TO_PERSIST_OFFSET +
2503 ftr->persist_data_size;
2504 }
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07002505
2506 return 0;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002507}
2508
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002509#define FRAMEWORK_BOOT_WAIT 60
2510
Paul Lawrence87999172014-02-20 12:21:31 -08002511static int cryptfs_SHA256_fileblock(const char* filename, __le8* buf)
2512{
Jeff Sharkeyce6a9132015-04-08 21:07:21 -07002513 int fd = open(filename, O_RDONLY|O_CLOEXEC);
Paul Lawrence87999172014-02-20 12:21:31 -08002514 if (fd == -1) {
2515 SLOGE("Error opening file %s", filename);
2516 return -1;
2517 }
2518
2519 char block[CRYPT_INPLACE_BUFSIZE];
2520 memset(block, 0, sizeof(block));
2521 if (unix_read(fd, block, sizeof(block)) < 0) {
2522 SLOGE("Error reading file %s", filename);
2523 close(fd);
2524 return -1;
2525 }
2526
2527 close(fd);
2528
2529 SHA256_CTX c;
2530 SHA256_Init(&c);
2531 SHA256_Update(&c, block, sizeof(block));
2532 SHA256_Final(buf, &c);
2533
2534 return 0;
2535}
2536
Paul Lawrence7ee87cf2017-12-22 10:12:06 -08002537static int cryptfs_enable_all_volumes(struct crypt_mnt_ftr* crypt_ftr, char* crypto_blkdev,
2538 char* real_blkdev, int previously_encrypted_upto) {
Paul Lawrence87999172014-02-20 12:21:31 -08002539 off64_t cur_encryption_done=0, tot_encryption_size=0;
Tim Murray8439dc92014-12-15 11:56:11 -08002540 int rc = -1;
Paul Lawrence87999172014-02-20 12:21:31 -08002541
Paul Lawrence87999172014-02-20 12:21:31 -08002542 /* The size of the userdata partition, and add in the vold volumes below */
2543 tot_encryption_size = crypt_ftr->fs_size;
2544
Paul Lawrence7ee87cf2017-12-22 10:12:06 -08002545 rc = cryptfs_enable_inplace(crypto_blkdev, real_blkdev, crypt_ftr->fs_size, &cur_encryption_done,
Paul Crowley0fd26262018-01-30 09:48:19 -08002546 tot_encryption_size, previously_encrypted_upto, true);
Paul Lawrence87999172014-02-20 12:21:31 -08002547
Paul Lawrence7ee87cf2017-12-22 10:12:06 -08002548 if (rc == ENABLE_INPLACE_ERR_DEV) {
2549 /* Hack for b/17898962 */
2550 SLOGE("cryptfs_enable: crypto block dev failure. Must reboot...\n");
2551 cryptfs_reboot(RebootType::reboot);
2552 }
JP Abgrall7fc1de82014-10-10 18:43:41 -07002553
Paul Lawrence7ee87cf2017-12-22 10:12:06 -08002554 if (!rc) {
2555 crypt_ftr->encrypted_upto = cur_encryption_done;
2556 }
Paul Lawrence87999172014-02-20 12:21:31 -08002557
Paul Lawrence7ee87cf2017-12-22 10:12:06 -08002558 if (!rc && crypt_ftr->encrypted_upto == crypt_ftr->fs_size) {
2559 /* The inplace routine never actually sets the progress to 100% due
2560 * to the round down nature of integer division, so set it here */
2561 property_set("vold.encrypt_progress", "100");
Paul Lawrence87999172014-02-20 12:21:31 -08002562 }
2563
2564 return rc;
2565}
2566
Paul Crowleyb64933a2017-10-31 08:25:55 -07002567static int vold_unmountAll(void) {
2568 VolumeManager* vm = VolumeManager::Instance();
2569 return vm->unmountAll();
2570}
2571
Paul Lawrence7ee87cf2017-12-22 10:12:06 -08002572int cryptfs_enable_internal(int crypt_type, const char* passwd, int no_ui) {
Paul Lawrence87999172014-02-20 12:21:31 -08002573 char crypto_blkdev[MAXPATHLEN], real_blkdev[MAXPATHLEN];
Greg Kaiser59ad0182018-02-16 13:01:36 -08002574 unsigned char decrypted_master_key[MAX_KEY_LEN];
Hiroaki Miyazawa14eab552015-02-04 13:29:15 +09002575 int rc=-1, i;
Paul Lawrence87999172014-02-20 12:21:31 -08002576 struct crypt_mnt_ftr crypt_ftr;
Ken Sumrall160b4d62013-04-22 12:15:39 -07002577 struct crypt_persist_data *pdata;
Ken Sumrall29d8da82011-05-18 17:20:07 -07002578 char encrypted_state[PROPERTY_VALUE_MAX];
Ken Sumrall5d4c68e2011-01-30 19:06:03 -08002579 char lockid[32] = { 0 };
Ken Sumrall29d8da82011-05-18 17:20:07 -07002580 char key_loc[PROPERTY_VALUE_MAX];
Ken Sumrall29d8da82011-05-18 17:20:07 -07002581 int num_vols;
Paul Lawrence87999172014-02-20 12:21:31 -08002582 off64_t previously_encrypted_upto = 0;
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002583 bool rebootEncryption = false;
Wei Wang4375f1b2017-02-24 17:43:01 -08002584 bool onlyCreateHeader = false;
AnilKumar Chimata98dc8352018-05-11 00:25:09 +05302585#ifdef CONFIG_HW_DISK_ENCRYPTION
2586 unsigned char newpw[32];
2587 int key_index = 0;
2588#endif
2589 int index = 0;
2590
Wei Wang4375f1b2017-02-24 17:43:01 -08002591 int fd = -1;
Ken Sumrall29d8da82011-05-18 17:20:07 -07002592
Paul Lawrence7ee87cf2017-12-22 10:12:06 -08002593 if (get_crypt_ftr_and_key(&crypt_ftr) == 0) {
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002594 if (crypt_ftr.flags & CRYPT_ENCRYPTION_IN_PROGRESS) {
2595 /* An encryption was underway and was interrupted */
2596 previously_encrypted_upto = crypt_ftr.encrypted_upto;
2597 crypt_ftr.encrypted_upto = 0;
2598 crypt_ftr.flags &= ~CRYPT_ENCRYPTION_IN_PROGRESS;
Paul Lawrence6bfed202014-07-28 12:47:22 -07002599
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002600 /* At this point, we are in an inconsistent state. Until we successfully
2601 complete encryption, a reboot will leave us broken. So mark the
2602 encryption failed in case that happens.
2603 On successfully completing encryption, remove this flag */
2604 crypt_ftr.flags |= CRYPT_INCONSISTENT_STATE;
Paul Lawrence6bfed202014-07-28 12:47:22 -07002605
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002606 put_crypt_ftr_and_key(&crypt_ftr);
2607 } else if (crypt_ftr.flags & CRYPT_FORCE_ENCRYPTION) {
2608 if (!check_ftr_sha(&crypt_ftr)) {
2609 memset(&crypt_ftr, 0, sizeof(crypt_ftr));
2610 put_crypt_ftr_and_key(&crypt_ftr);
2611 goto error_unencrypted;
2612 }
2613
2614 /* Doing a reboot-encryption*/
2615 crypt_ftr.flags &= ~CRYPT_FORCE_ENCRYPTION;
2616 crypt_ftr.flags |= CRYPT_FORCE_COMPLETE;
2617 rebootEncryption = true;
2618 }
Greg Kaiser59ad0182018-02-16 13:01:36 -08002619 } else {
2620 // We don't want to accidentally reference invalid data.
2621 memset(&crypt_ftr, 0, sizeof(crypt_ftr));
Paul Lawrence87999172014-02-20 12:21:31 -08002622 }
2623
2624 property_get("ro.crypto.state", encrypted_state, "");
2625 if (!strcmp(encrypted_state, "encrypted") && !previously_encrypted_upto) {
2626 SLOGE("Device is already running encrypted, aborting");
2627 goto error_unencrypted;
2628 }
2629
2630 // TODO refactor fs_mgr_get_crypt_info to get both in one call
Paul Crowleye2ee1522017-09-26 14:05:26 -07002631 fs_mgr_get_crypt_info(fstab_default, key_loc, 0, sizeof(key_loc));
2632 fs_mgr_get_crypt_info(fstab_default, 0, real_blkdev, sizeof(real_blkdev));
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002633
Ken Sumrall3ed82362011-01-28 23:31:16 -08002634 /* Get the size of the real block device */
Wei Wang4375f1b2017-02-24 17:43:01 -08002635 fd = open(real_blkdev, O_RDONLY|O_CLOEXEC);
Hiroaki Miyazawa14eab552015-02-04 13:29:15 +09002636 if (fd == -1) {
2637 SLOGE("Cannot open block device %s\n", real_blkdev);
2638 goto error_unencrypted;
2639 }
2640 unsigned long nr_sec;
2641 get_blkdev_size(fd, &nr_sec);
2642 if (nr_sec == 0) {
Ken Sumrall3ed82362011-01-28 23:31:16 -08002643 SLOGE("Cannot get size of block device %s\n", real_blkdev);
2644 goto error_unencrypted;
2645 }
2646 close(fd);
2647
2648 /* If doing inplace encryption, make sure the orig fs doesn't include the crypto footer */
Paul Lawrence7ee87cf2017-12-22 10:12:06 -08002649 if (!strcmp(key_loc, KEY_IN_FOOTER)) {
Ken Sumrall3ed82362011-01-28 23:31:16 -08002650 unsigned int fs_size_sec, max_fs_size_sec;
Jim Millera70abc62014-08-15 02:00:45 +00002651 fs_size_sec = get_fs_size(real_blkdev);
Daniel Rosenberge82df162014-08-15 22:19:23 +00002652 if (fs_size_sec == 0)
2653 fs_size_sec = get_f2fs_filesystem_size_sec(real_blkdev);
2654
Paul Lawrence87999172014-02-20 12:21:31 -08002655 max_fs_size_sec = nr_sec - (CRYPT_FOOTER_OFFSET / CRYPT_SECTOR_SIZE);
Ken Sumrall3ed82362011-01-28 23:31:16 -08002656
2657 if (fs_size_sec > max_fs_size_sec) {
2658 SLOGE("Orig filesystem overlaps crypto footer region. Cannot encrypt in place.");
2659 goto error_unencrypted;
2660 }
2661 }
2662
Ken Sumrall5d4c68e2011-01-30 19:06:03 -08002663 /* Get a wakelock as this may take a while, and we don't want the
2664 * device to sleep on us. We'll grab a partial wakelock, and if the UI
2665 * wants to keep the screen on, it can grab a full wakelock.
2666 */
Ken Sumrall29d8da82011-05-18 17:20:07 -07002667 snprintf(lockid, sizeof(lockid), "enablecrypto%d", (int) getpid());
Ken Sumrall5d4c68e2011-01-30 19:06:03 -08002668 acquire_wake_lock(PARTIAL_WAKE_LOCK, lockid);
2669
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002670 /* The init files are setup to stop the class main and late start when
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002671 * vold sets trigger_shutdown_framework.
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002672 */
2673 property_set("vold.decrypt", "trigger_shutdown_framework");
2674 SLOGD("Just asked init to shut down class main\n");
2675
Jeff Sharkey9c484982015-03-31 10:35:33 -07002676 /* Ask vold to unmount all devices that it manages */
2677 if (vold_unmountAll()) {
2678 SLOGE("Failed to unmount all vold managed devices");
Ken Sumrall2eaf7132011-01-14 12:45:48 -08002679 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002680
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002681 /* no_ui means we are being called from init, not settings.
2682 Now we always reboot from settings, so !no_ui means reboot
2683 */
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002684 if (!no_ui) {
2685 /* Try fallback, which is to reboot and try there */
2686 onlyCreateHeader = true;
2687 FILE* breadcrumb = fopen(BREADCRUMB_FILE, "we");
2688 if (breadcrumb == 0) {
2689 SLOGE("Failed to create breadcrumb file");
2690 goto error_shutting_down;
2691 }
2692 fclose(breadcrumb);
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002693 }
2694
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002695 /* Start the actual work of making an encrypted filesystem */
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002696 /* Initialize a crypt_mnt_ftr for the partition */
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002697 if (previously_encrypted_upto == 0 && !rebootEncryption) {
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07002698 if (cryptfs_init_crypt_mnt_ftr(&crypt_ftr)) {
2699 goto error_shutting_down;
2700 }
Ken Sumrall160b4d62013-04-22 12:15:39 -07002701
Paul Lawrence87999172014-02-20 12:21:31 -08002702 if (!strcmp(key_loc, KEY_IN_FOOTER)) {
2703 crypt_ftr.fs_size = nr_sec
2704 - (CRYPT_FOOTER_OFFSET / CRYPT_SECTOR_SIZE);
2705 } else {
2706 crypt_ftr.fs_size = nr_sec;
2707 }
Paul Lawrence6bfed202014-07-28 12:47:22 -07002708 /* At this point, we are in an inconsistent state. Until we successfully
2709 complete encryption, a reboot will leave us broken. So mark the
2710 encryption failed in case that happens.
2711 On successfully completing encryption, remove this flag */
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002712 if (onlyCreateHeader) {
2713 crypt_ftr.flags |= CRYPT_FORCE_ENCRYPTION;
2714 } else {
2715 crypt_ftr.flags |= CRYPT_INCONSISTENT_STATE;
2716 }
Paul Lawrence87999172014-02-20 12:21:31 -08002717 crypt_ftr.crypt_type = crypt_type;
AnilKumar Chimata98dc8352018-05-11 00:25:09 +05302718#ifdef CONFIG_HW_DISK_ENCRYPTION
2719 strlcpy((char *)crypt_ftr.crypto_type_name, "aes-xts", MAX_CRYPTO_TYPE_NAME_LEN);
2720#else
Greg Kaiser57f9af62018-02-16 13:13:58 -08002721 strlcpy((char *)crypt_ftr.crypto_type_name, cryptfs_get_crypto_name(), MAX_CRYPTO_TYPE_NAME_LEN);
AnilKumar Chimata98dc8352018-05-11 00:25:09 +05302722#endif
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002723
Paul Lawrence87999172014-02-20 12:21:31 -08002724 /* Make an encrypted master key */
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002725 if (create_encrypted_random_key(onlyCreateHeader ? DEFAULT_PASSWORD : passwd,
2726 crypt_ftr.master_key, crypt_ftr.salt, &crypt_ftr)) {
Paul Lawrence87999172014-02-20 12:21:31 -08002727 SLOGE("Cannot create encrypted master key\n");
2728 goto error_shutting_down;
2729 }
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002730
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002731 /* Replace scrypted intermediate key if we are preparing for a reboot */
2732 if (onlyCreateHeader) {
Greg Kaiser59ad0182018-02-16 13:01:36 -08002733 unsigned char fake_master_key[MAX_KEY_LEN];
2734 unsigned char encrypted_fake_master_key[MAX_KEY_LEN];
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002735 memset(fake_master_key, 0, sizeof(fake_master_key));
2736 encrypt_master_key(passwd, crypt_ftr.salt, fake_master_key,
AnilKumar Chimata98dc8352018-05-11 00:25:09 +05302737 encrypted_fake_master_key, &crypt_ftr, true);
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002738 }
2739
Paul Lawrence87999172014-02-20 12:21:31 -08002740 /* Write the key to the end of the partition */
2741 put_crypt_ftr_and_key(&crypt_ftr);
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002742
Paul Lawrence87999172014-02-20 12:21:31 -08002743 /* If any persistent data has been remembered, save it.
2744 * If none, create a valid empty table and save that.
2745 */
2746 if (!persist_data) {
Wei Wang4375f1b2017-02-24 17:43:01 -08002747 pdata = (crypt_persist_data *)malloc(CRYPT_PERSIST_DATA_SIZE);
Paul Lawrence87999172014-02-20 12:21:31 -08002748 if (pdata) {
2749 init_empty_persist_data(pdata, CRYPT_PERSIST_DATA_SIZE);
2750 persist_data = pdata;
2751 }
2752 }
2753 if (persist_data) {
2754 save_persistent_data();
2755 }
Ken Sumrall160b4d62013-04-22 12:15:39 -07002756 }
2757
AnilKumar Chimata98dc8352018-05-11 00:25:09 +05302758 /* When encryption triggered from settings, encryption starts after reboot.
2759 So set the encryption key when the actual encryption starts.
2760 */
2761#ifdef CONFIG_HW_DISK_ENCRYPTION
2762 if (previously_encrypted_upto == 0) {
2763 if (!rebootEncryption)
2764 clear_hw_device_encryption_key();
2765
2766 if (get_keymaster_hw_fde_passwd(
2767 onlyCreateHeader ? DEFAULT_PASSWORD : passwd,
2768 newpw, crypt_ftr.salt, &crypt_ftr))
2769 key_index = set_hw_device_encryption_key(
2770 onlyCreateHeader ? DEFAULT_PASSWORD : passwd,
2771 (char*)crypt_ftr.crypto_type_name);
2772 else
2773 key_index = set_hw_device_encryption_key((const char*)newpw,
2774 (char*) crypt_ftr.crypto_type_name);
2775 if (key_index < 0)
2776 goto error_shutting_down;
2777
2778 crypt_ftr.flags |= CRYPT_ASCII_PASSWORD_UPDATED;
2779 put_crypt_ftr_and_key(&crypt_ftr);
2780 }
2781#endif
2782
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002783 if (onlyCreateHeader) {
2784 sleep(2);
Josh Gaofec44372017-08-28 13:22:55 -07002785 cryptfs_reboot(RebootType::reboot);
AnilKumar Chimata98dc8352018-05-11 00:25:09 +05302786 } else {
2787 /* Do extra work for a better UX when doing the long inplace encryption */
2788 /* Now that /data is unmounted, we need to mount a tmpfs
2789 * /data, set a property saying we're doing inplace encryption,
2790 * and restart the framework.
2791 */
2792 if (fs_mgr_do_tmpfs_mount(DATA_MNT_POINT)) {
2793 goto error_shutting_down;
2794 }
2795 /* Tells the framework that inplace encryption is starting */
2796 property_set("vold.encrypt_progress", "0");
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002797
AnilKumar Chimata98dc8352018-05-11 00:25:09 +05302798 /* restart the framework. */
2799 /* Create necessary paths on /data */
2800 prep_data_fs();
2801
2802 /* Ugh, shutting down the framework is not synchronous, so until it
2803 * can be fixed, this horrible hack will wait a moment for it all to
2804 * shut down before proceeding. Without it, some devices cannot
2805 * restart the graphics services.
2806 */
2807 sleep(2);
2808
Ajay Dudani87701e22014-09-17 21:02:52 -07002809 /* startup service classes main and late_start */
2810 property_set("vold.decrypt", "trigger_restart_min_framework");
2811 SLOGD("Just triggered restart_min_framework\n");
2812
2813 /* OK, the framework is restarted and will soon be showing a
2814 * progress bar. Time to setup an encrypted mapping, and
2815 * either write a new filesystem, or encrypt in place updating
2816 * the progress bar as we work.
2817 */
2818 }
2819
Paul Lawrenced0c7b172014-08-08 14:28:10 -07002820 decrypt_master_key(passwd, decrypted_master_key, &crypt_ftr, 0, 0);
AnilKumar Chimata98dc8352018-05-11 00:25:09 +05302821#ifdef CONFIG_HW_DISK_ENCRYPTION
2822 if (is_hw_disk_encryption((char*)crypt_ftr.crypto_type_name) && is_ice_enabled())
AnilKumar Chimatad08106a2018-02-11 17:11:24 +05302823#ifdef CONFIG_HW_DISK_ENCRYPT_PERF
2824 strlcpy(crypto_blkdev, real_blkdev, sizeof(crypto_blkdev));
2825#else
AnilKumar Chimata98dc8352018-05-11 00:25:09 +05302826 create_crypto_blk_dev(&crypt_ftr, (unsigned char*)&key_index, real_blkdev, crypto_blkdev,
2827 CRYPTO_BLOCK_DEVICE, 0);
AnilKumar Chimatad08106a2018-02-11 17:11:24 +05302828#endif
AnilKumar Chimata98dc8352018-05-11 00:25:09 +05302829 else
2830 create_crypto_blk_dev(&crypt_ftr, decrypted_master_key, real_blkdev, crypto_blkdev,
2831 CRYPTO_BLOCK_DEVICE, 0);
2832#else
Ken Sumrall29d8da82011-05-18 17:20:07 -07002833 create_crypto_blk_dev(&crypt_ftr, decrypted_master_key, real_blkdev, crypto_blkdev,
Paul Crowley5afbc622017-11-27 09:42:17 -08002834 CRYPTO_BLOCK_DEVICE, 0);
AnilKumar Chimata98dc8352018-05-11 00:25:09 +05302835#endif
Ken Sumrall29d8da82011-05-18 17:20:07 -07002836
Paul Lawrence87999172014-02-20 12:21:31 -08002837 /* If we are continuing, check checksums match */
2838 rc = 0;
2839 if (previously_encrypted_upto) {
2840 __le8 hash_first_block[SHA256_DIGEST_LENGTH];
AnilKumar Chimatad08106a2018-02-11 17:11:24 +05302841#if defined(CONFIG_HW_DISK_ENCRYPTION) && defined(CONFIG_HW_DISK_ENCRYPT_PERF)
2842 if (set_ice_param(START_ENCDEC)) {
2843 SLOGE("Failed to set ICE data");
2844 goto error_shutting_down;
2845 }
2846#endif
Paul Lawrence87999172014-02-20 12:21:31 -08002847 rc = cryptfs_SHA256_fileblock(crypto_blkdev, hash_first_block);
Ken Sumrall128626f2011-06-28 18:45:14 -07002848
Paul Lawrence87999172014-02-20 12:21:31 -08002849 if (!rc && memcmp(hash_first_block, crypt_ftr.hash_first_block,
2850 sizeof(hash_first_block)) != 0) {
2851 SLOGE("Checksums do not match - trigger wipe");
2852 rc = -1;
Ken Sumrall29d8da82011-05-18 17:20:07 -07002853 }
2854 }
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002855
AnilKumar Chimatad08106a2018-02-11 17:11:24 +05302856#if defined(CONFIG_HW_DISK_ENCRYPTION) && defined(CONFIG_HW_DISK_ENCRYPT_PERF)
2857 if (set_ice_param(START_ENC)) {
2858 SLOGE("Failed to set ICE data");
2859 goto error_shutting_down;
2860 }
2861#endif
Paul Lawrence87999172014-02-20 12:21:31 -08002862 if (!rc) {
Paul Lawrence7ee87cf2017-12-22 10:12:06 -08002863 rc = cryptfs_enable_all_volumes(&crypt_ftr, crypto_blkdev, real_blkdev,
Paul Lawrence87999172014-02-20 12:21:31 -08002864 previously_encrypted_upto);
2865 }
2866
AnilKumar Chimatad08106a2018-02-11 17:11:24 +05302867#if defined(CONFIG_HW_DISK_ENCRYPTION) && defined(CONFIG_HW_DISK_ENCRYPT_PERF)
2868 if (set_ice_param(START_ENCDEC)) {
2869 SLOGE("Failed to set ICE data");
2870 goto error_shutting_down;
2871 }
2872#endif
Paul Lawrence87999172014-02-20 12:21:31 -08002873 /* Calculate checksum if we are not finished */
Paul Lawrence7ee87cf2017-12-22 10:12:06 -08002874 if (!rc && crypt_ftr.encrypted_upto != crypt_ftr.fs_size) {
Paul Lawrence87999172014-02-20 12:21:31 -08002875 rc = cryptfs_SHA256_fileblock(crypto_blkdev,
2876 crypt_ftr.hash_first_block);
Paul Lawrence73d7a022014-06-09 14:10:09 -07002877 if (rc) {
Paul Lawrence87999172014-02-20 12:21:31 -08002878 SLOGE("Error calculating checksum for continuing encryption");
2879 rc = -1;
Ken Sumrall29d8da82011-05-18 17:20:07 -07002880 }
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002881 }
2882
2883 /* Undo the dm-crypt mapping whether we succeed or not */
AnilKumar Chimatad08106a2018-02-11 17:11:24 +05302884#if defined(CONFIG_HW_DISK_ENCRYPTION) && defined(CONFIG_HW_DISK_ENCRYPT_PERF)
2885 if (!is_ice_enabled())
2886 delete_crypto_blk_dev(CRYPTO_BLOCK_DEVICE);
2887#else
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002888 delete_crypto_blk_dev(CRYPTO_BLOCK_DEVICE);
AnilKumar Chimatad08106a2018-02-11 17:11:24 +05302889#endif
Ken Sumrall29d8da82011-05-18 17:20:07 -07002890
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002891 if (! rc) {
2892 /* Success */
Paul Lawrence6bfed202014-07-28 12:47:22 -07002893 crypt_ftr.flags &= ~CRYPT_INCONSISTENT_STATE;
Ken Sumrall7f7dbaa2011-02-01 15:46:41 -08002894
Paul Lawrence7ee87cf2017-12-22 10:12:06 -08002895 if (crypt_ftr.encrypted_upto != crypt_ftr.fs_size) {
Paul Lawrence87999172014-02-20 12:21:31 -08002896 SLOGD("Encrypted up to sector %lld - will continue after reboot",
2897 crypt_ftr.encrypted_upto);
Paul Lawrence6bfed202014-07-28 12:47:22 -07002898 crypt_ftr.flags |= CRYPT_ENCRYPTION_IN_PROGRESS;
Paul Lawrence87999172014-02-20 12:21:31 -08002899 }
Paul Lawrence73d7a022014-06-09 14:10:09 -07002900
Paul Lawrence6bfed202014-07-28 12:47:22 -07002901 put_crypt_ftr_and_key(&crypt_ftr);
Ken Sumralld33d4172011-02-01 00:49:13 -08002902
Paul Lawrence7ee87cf2017-12-22 10:12:06 -08002903 if (crypt_ftr.encrypted_upto == crypt_ftr.fs_size) {
2904 char value[PROPERTY_VALUE_MAX];
2905 property_get("ro.crypto.state", value, "");
2906 if (!strcmp(value, "")) {
2907 /* default encryption - continue first boot sequence */
2908 property_set("ro.crypto.state", "encrypted");
2909 property_set("ro.crypto.type", "block");
2910 release_wake_lock(lockid);
2911 if (rebootEncryption && crypt_ftr.crypt_type != CRYPT_TYPE_DEFAULT) {
2912 // Bring up cryptkeeper that will check the password and set it
2913 property_set("vold.decrypt", "trigger_shutdown_framework");
2914 sleep(2);
2915 property_set("vold.encrypt_progress", "");
2916 cryptfs_trigger_restart_min_framework();
2917 } else {
2918 cryptfs_check_passwd(DEFAULT_PASSWORD);
2919 cryptfs_restart_internal(1);
2920 }
2921 return 0;
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002922 } else {
Paul Lawrence7ee87cf2017-12-22 10:12:06 -08002923 sleep(2); /* Give the UI a chance to show 100% progress */
2924 cryptfs_reboot(RebootType::reboot);
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002925 }
Paul Lawrence87999172014-02-20 12:21:31 -08002926 } else {
Paul Lawrenceb6672e12014-08-15 07:37:28 -07002927 sleep(2); /* Partially encrypted, ensure writes flushed to ssd */
Josh Gaofec44372017-08-28 13:22:55 -07002928 cryptfs_reboot(RebootType::shutdown);
Paul Lawrence87999172014-02-20 12:21:31 -08002929 }
Ken Sumrall3ed82362011-01-28 23:31:16 -08002930 } else {
Mike Lockwoodee6d8c42012-02-15 13:43:28 -08002931 char value[PROPERTY_VALUE_MAX];
2932
Ken Sumrall319369a2012-06-27 16:30:18 -07002933 property_get("ro.vold.wipe_on_crypt_fail", value, "0");
Mike Lockwoodee6d8c42012-02-15 13:43:28 -08002934 if (!strcmp(value, "1")) {
2935 /* wipe data if encryption failed */
2936 SLOGE("encryption failed - rebooting into recovery to wipe data\n");
Wei Wang4375f1b2017-02-24 17:43:01 -08002937 std::string err;
2938 const std::vector<std::string> options = {
2939 "--wipe_data\n--reason=cryptfs_enable_internal\n"
2940 };
2941 if (!write_bootloader_message(options, &err)) {
2942 SLOGE("could not write bootloader message: %s", err.c_str());
Mike Lockwoodee6d8c42012-02-15 13:43:28 -08002943 }
Josh Gaofec44372017-08-28 13:22:55 -07002944 cryptfs_reboot(RebootType::recovery);
Mike Lockwoodee6d8c42012-02-15 13:43:28 -08002945 } else {
2946 /* set property to trigger dialog */
2947 property_set("vold.encrypt_progress", "error_partially_encrypted");
2948 release_wake_lock(lockid);
2949 }
Ken Sumrall3ed82362011-01-28 23:31:16 -08002950 return -1;
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002951 }
2952
Ken Sumrall3ed82362011-01-28 23:31:16 -08002953 /* hrm, the encrypt step claims success, but the reboot failed.
2954 * This should not happen.
2955 * Set the property and return. Hope the framework can deal with it.
2956 */
2957 property_set("vold.encrypt_progress", "error_reboot_failed");
Ken Sumrall5d4c68e2011-01-30 19:06:03 -08002958 release_wake_lock(lockid);
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002959 return rc;
Ken Sumrall3ed82362011-01-28 23:31:16 -08002960
2961error_unencrypted:
2962 property_set("vold.encrypt_progress", "error_not_encrypted");
Ken Sumrall5d4c68e2011-01-30 19:06:03 -08002963 if (lockid[0]) {
2964 release_wake_lock(lockid);
2965 }
Ken Sumrall3ed82362011-01-28 23:31:16 -08002966 return -1;
2967
2968error_shutting_down:
2969 /* we failed, and have not encrypted anthing, so the users's data is still intact,
2970 * but the framework is stopped and not restarted to show the error, so it's up to
2971 * vold to restart the system.
2972 */
2973 SLOGE("Error enabling encryption after framework is shutdown, no data changed, restarting system");
Josh Gaofec44372017-08-28 13:22:55 -07002974 cryptfs_reboot(RebootType::reboot);
Ken Sumrall3ed82362011-01-28 23:31:16 -08002975
2976 /* shouldn't get here */
2977 property_set("vold.encrypt_progress", "error_shutting_down");
Ken Sumrall5d4c68e2011-01-30 19:06:03 -08002978 if (lockid[0]) {
2979 release_wake_lock(lockid);
2980 }
Ken Sumrall3ed82362011-01-28 23:31:16 -08002981 return -1;
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002982}
2983
Paul Lawrence7ee87cf2017-12-22 10:12:06 -08002984int cryptfs_enable(int type, const char* passwd, int no_ui) {
2985 return cryptfs_enable_internal(type, passwd, no_ui);
Paul Lawrence13486032014-02-03 13:28:11 -08002986}
2987
Paul Lawrence7ee87cf2017-12-22 10:12:06 -08002988int cryptfs_enable_default(int no_ui) {
2989 return cryptfs_enable_internal(CRYPT_TYPE_DEFAULT, DEFAULT_PASSWORD, no_ui);
Paul Lawrence13486032014-02-03 13:28:11 -08002990}
2991
AnilKumar Chimata98dc8352018-05-11 00:25:09 +05302992int cryptfs_changepw(int crypt_type, const char *currentpw, const char *newpw)
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002993{
Paul Crowley38132a12016-02-09 09:50:32 +00002994 if (e4crypt_is_native()) {
Paul Lawrence7b6b5652016-02-02 11:14:59 -08002995 SLOGE("cryptfs_changepw not valid for file encryption");
2996 return -1;
Paul Lawrence05335c32015-03-05 09:46:23 -08002997 }
2998
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002999 struct crypt_mnt_ftr crypt_ftr;
JP Abgrall933216c2015-02-11 13:44:32 -08003000 int rc;
Ken Sumrall8ddbe402011-01-17 15:26:29 -08003001
3002 /* This is only allowed after we've successfully decrypted the master key */
Paul Lawrencef4faa572014-01-29 13:31:03 -08003003 if (!master_key_saved) {
Ken Sumrall0cc16632011-01-18 20:32:26 -08003004 SLOGE("Key not saved, aborting");
Ken Sumrall8ddbe402011-01-17 15:26:29 -08003005 return -1;
3006 }
3007
Paul Lawrencef4faa572014-01-29 13:31:03 -08003008 if (crypt_type < 0 || crypt_type > CRYPT_TYPE_MAX_TYPE) {
3009 SLOGE("Invalid crypt_type %d", crypt_type);
3010 return -1;
3011 }
3012
Ken Sumrall8ddbe402011-01-17 15:26:29 -08003013 /* get key */
Ken Sumrall160b4d62013-04-22 12:15:39 -07003014 if (get_crypt_ftr_and_key(&crypt_ftr)) {
Paul Lawrencef4faa572014-01-29 13:31:03 -08003015 SLOGE("Error getting crypt footer and key");
3016 return -1;
Ken Sumrall8ddbe402011-01-17 15:26:29 -08003017 }
3018
AnilKumar Chimata98dc8352018-05-11 00:25:09 +05303019#ifdef CONFIG_HW_DISK_ENCRYPTION
3020 if(is_hw_disk_encryption((char*)crypt_ftr.crypto_type_name))
3021 return cryptfs_changepw_hw_fde(crypt_type, currentpw, newpw);
3022 else {
3023 crypt_ftr.crypt_type = crypt_type;
3024
3025 rc = encrypt_master_key(crypt_type == CRYPT_TYPE_DEFAULT ?
3026 DEFAULT_PASSWORD : newpw,
3027 crypt_ftr.salt,
3028 saved_master_key,
3029 crypt_ftr.master_key,
3030 &crypt_ftr, false);
3031 if (rc) {
3032 SLOGE("Encrypt master key failed: %d", rc);
3033 return -1;
3034 }
3035 /* save the key */
3036 put_crypt_ftr_and_key(&crypt_ftr);
3037
3038 return 0;
3039 }
3040#else
Paul Lawrencef4faa572014-01-29 13:31:03 -08003041 crypt_ftr.crypt_type = crypt_type;
3042
JP Abgrall933216c2015-02-11 13:44:32 -08003043 rc = encrypt_master_key(crypt_type == CRYPT_TYPE_DEFAULT ? DEFAULT_PASSWORD
Paul Lawrencef4faa572014-01-29 13:31:03 -08003044 : newpw,
3045 crypt_ftr.salt,
3046 saved_master_key,
3047 crypt_ftr.master_key,
AnilKumar Chimata98dc8352018-05-11 00:25:09 +05303048 &crypt_ftr, false);
JP Abgrall933216c2015-02-11 13:44:32 -08003049 if (rc) {
3050 SLOGE("Encrypt master key failed: %d", rc);
3051 return -1;
3052 }
Jason parks70a4b3f2011-01-28 10:10:47 -06003053 /* save the key */
Ken Sumrall160b4d62013-04-22 12:15:39 -07003054 put_crypt_ftr_and_key(&crypt_ftr);
Ken Sumrall8f869aa2010-12-03 03:47:09 -08003055
3056 return 0;
AnilKumar Chimata98dc8352018-05-11 00:25:09 +05303057#endif
Ken Sumrall8f869aa2010-12-03 03:47:09 -08003058}
Ken Sumrall160b4d62013-04-22 12:15:39 -07003059
AnilKumar Chimata98dc8352018-05-11 00:25:09 +05303060#ifdef CONFIG_HW_DISK_ENCRYPTION
3061int cryptfs_changepw_hw_fde(int crypt_type, const char *currentpw, const char *newpw)
3062{
3063 struct crypt_mnt_ftr crypt_ftr;
3064 int rc;
3065 int previous_type;
3066
3067 /* get key */
3068 if (get_crypt_ftr_and_key(&crypt_ftr)) {
3069 SLOGE("Error getting crypt footer and key");
3070 return -1;
3071 }
3072
3073 previous_type = crypt_ftr.crypt_type;
3074 int rc1;
3075 unsigned char tmp_curpw[32] = {0};
3076 rc1 = get_keymaster_hw_fde_passwd(crypt_ftr.crypt_type == CRYPT_TYPE_DEFAULT ?
3077 DEFAULT_PASSWORD : currentpw, tmp_curpw,
3078 crypt_ftr.salt, &crypt_ftr);
3079
3080 crypt_ftr.crypt_type = crypt_type;
3081
3082 int ret, rc2;
3083 unsigned char tmp_newpw[32] = {0};
3084
3085 rc2 = get_keymaster_hw_fde_passwd(crypt_type == CRYPT_TYPE_DEFAULT ?
3086 DEFAULT_PASSWORD : newpw , tmp_newpw,
3087 crypt_ftr.salt, &crypt_ftr);
3088
3089 if (is_hw_disk_encryption((char*)crypt_ftr.crypto_type_name)) {
3090 ret = update_hw_device_encryption_key(
3091 rc1 ? (previous_type == CRYPT_TYPE_DEFAULT ? DEFAULT_PASSWORD : currentpw) : (const char*)tmp_curpw,
3092 rc2 ? (crypt_type == CRYPT_TYPE_DEFAULT ? DEFAULT_PASSWORD : newpw): (const char*)tmp_newpw,
3093 (char*)crypt_ftr.crypto_type_name);
3094 if (ret) {
3095 SLOGE("Error updating device encryption hardware key ret %d", ret);
3096 return -1;
3097 } else {
3098 SLOGI("Encryption hardware key updated");
3099 }
3100 }
3101
3102 /* save the key */
3103 put_crypt_ftr_and_key(&crypt_ftr);
3104 return 0;
3105}
3106#endif
3107
Rubin Xu85c01f92014-10-13 12:49:54 +01003108static unsigned int persist_get_max_entries(int encrypted) {
3109 struct crypt_mnt_ftr crypt_ftr;
3110 unsigned int dsize;
3111 unsigned int max_persistent_entries;
3112
3113 /* If encrypted, use the values from the crypt_ftr, otherwise
3114 * use the values for the current spec.
3115 */
3116 if (encrypted) {
3117 if (get_crypt_ftr_and_key(&crypt_ftr)) {
3118 return -1;
3119 }
3120 dsize = crypt_ftr.persist_data_size;
3121 } else {
3122 dsize = CRYPT_PERSIST_DATA_SIZE;
3123 }
3124
3125 max_persistent_entries = (dsize - sizeof(struct crypt_persist_data)) /
3126 sizeof(struct crypt_persist_entry);
3127
3128 return max_persistent_entries;
3129}
3130
3131static int persist_get_key(const char *fieldname, char *value)
Ken Sumrall160b4d62013-04-22 12:15:39 -07003132{
3133 unsigned int i;
3134
3135 if (persist_data == NULL) {
3136 return -1;
3137 }
3138 for (i = 0; i < persist_data->persist_valid_entries; i++) {
3139 if (!strncmp(persist_data->persist_entry[i].key, fieldname, PROPERTY_KEY_MAX)) {
3140 /* We found it! */
3141 strlcpy(value, persist_data->persist_entry[i].val, PROPERTY_VALUE_MAX);
3142 return 0;
3143 }
3144 }
3145
3146 return -1;
3147}
3148
Rubin Xu85c01f92014-10-13 12:49:54 +01003149static int persist_set_key(const char *fieldname, const char *value, int encrypted)
Ken Sumrall160b4d62013-04-22 12:15:39 -07003150{
3151 unsigned int i;
3152 unsigned int num;
Ken Sumrall160b4d62013-04-22 12:15:39 -07003153 unsigned int max_persistent_entries;
Ken Sumrall160b4d62013-04-22 12:15:39 -07003154
3155 if (persist_data == NULL) {
3156 return -1;
3157 }
3158
Rubin Xu85c01f92014-10-13 12:49:54 +01003159 max_persistent_entries = persist_get_max_entries(encrypted);
Ken Sumrall160b4d62013-04-22 12:15:39 -07003160
3161 num = persist_data->persist_valid_entries;
3162
3163 for (i = 0; i < num; i++) {
3164 if (!strncmp(persist_data->persist_entry[i].key, fieldname, PROPERTY_KEY_MAX)) {
3165 /* We found an existing entry, update it! */
3166 memset(persist_data->persist_entry[i].val, 0, PROPERTY_VALUE_MAX);
3167 strlcpy(persist_data->persist_entry[i].val, value, PROPERTY_VALUE_MAX);
3168 return 0;
3169 }
3170 }
3171
3172 /* We didn't find it, add it to the end, if there is room */
3173 if (persist_data->persist_valid_entries < max_persistent_entries) {
3174 memset(&persist_data->persist_entry[num], 0, sizeof(struct crypt_persist_entry));
3175 strlcpy(persist_data->persist_entry[num].key, fieldname, PROPERTY_KEY_MAX);
3176 strlcpy(persist_data->persist_entry[num].val, value, PROPERTY_VALUE_MAX);
3177 persist_data->persist_valid_entries++;
3178 return 0;
3179 }
3180
3181 return -1;
3182}
3183
Rubin Xu85c01f92014-10-13 12:49:54 +01003184/**
3185 * Test if key is part of the multi-entry (field, index) sequence. Return non-zero if key is in the
3186 * sequence and its index is greater than or equal to index. Return 0 otherwise.
3187 */
Jeff Sharkey95440eb2017-09-18 18:19:28 -06003188int match_multi_entry(const char *key, const char *field, unsigned index) {
3189 std::string key_ = key;
3190 std::string field_ = field;
Rubin Xu85c01f92014-10-13 12:49:54 +01003191
Jeff Sharkey95440eb2017-09-18 18:19:28 -06003192 std::string parsed_field;
3193 unsigned parsed_index;
3194
3195 std::string::size_type split = key_.find_last_of('_');
3196 if (split == std::string::npos) {
3197 parsed_field = key_;
3198 parsed_index = 0;
3199 } else {
3200 parsed_field = key_.substr(0, split);
3201 parsed_index = std::stoi(key_.substr(split + 1));
Rubin Xu85c01f92014-10-13 12:49:54 +01003202 }
Jeff Sharkey95440eb2017-09-18 18:19:28 -06003203
3204 return parsed_field == field_ && parsed_index >= index;
Rubin Xu85c01f92014-10-13 12:49:54 +01003205}
3206
3207/*
3208 * Delete entry/entries from persist_data. If the entries are part of a multi-segment field, all
3209 * remaining entries starting from index will be deleted.
3210 * returns PERSIST_DEL_KEY_OK if deletion succeeds,
3211 * PERSIST_DEL_KEY_ERROR_NO_FIELD if the field does not exist,
3212 * and PERSIST_DEL_KEY_ERROR_OTHER if error occurs.
3213 *
3214 */
3215static int persist_del_keys(const char *fieldname, unsigned index)
3216{
3217 unsigned int i;
3218 unsigned int j;
3219 unsigned int num;
3220
3221 if (persist_data == NULL) {
3222 return PERSIST_DEL_KEY_ERROR_OTHER;
3223 }
3224
3225 num = persist_data->persist_valid_entries;
3226
3227 j = 0; // points to the end of non-deleted entries.
3228 // Filter out to-be-deleted entries in place.
3229 for (i = 0; i < num; i++) {
3230 if (!match_multi_entry(persist_data->persist_entry[i].key, fieldname, index)) {
3231 persist_data->persist_entry[j] = persist_data->persist_entry[i];
3232 j++;
3233 }
3234 }
3235
3236 if (j < num) {
3237 persist_data->persist_valid_entries = j;
3238 // Zeroise the remaining entries
3239 memset(&persist_data->persist_entry[j], 0, (num - j) * sizeof(struct crypt_persist_entry));
3240 return PERSIST_DEL_KEY_OK;
3241 } else {
3242 // Did not find an entry matching the given fieldname
3243 return PERSIST_DEL_KEY_ERROR_NO_FIELD;
3244 }
3245}
3246
3247static int persist_count_keys(const char *fieldname)
3248{
3249 unsigned int i;
3250 unsigned int count;
3251
3252 if (persist_data == NULL) {
3253 return -1;
3254 }
3255
3256 count = 0;
3257 for (i = 0; i < persist_data->persist_valid_entries; i++) {
3258 if (match_multi_entry(persist_data->persist_entry[i].key, fieldname, 0)) {
3259 count++;
3260 }
3261 }
3262
3263 return count;
3264}
3265
Ken Sumrall160b4d62013-04-22 12:15:39 -07003266/* Return the value of the specified field. */
Rubin Xu85c01f92014-10-13 12:49:54 +01003267int cryptfs_getfield(const char *fieldname, char *value, int len)
Ken Sumrall160b4d62013-04-22 12:15:39 -07003268{
Paul Crowley38132a12016-02-09 09:50:32 +00003269 if (e4crypt_is_native()) {
Paul Lawrence5a06a642016-02-03 13:39:13 -08003270 SLOGE("Cannot get field when file encrypted");
3271 return -1;
Paul Lawrence368d7942015-04-15 14:12:00 -07003272 }
3273
Ken Sumrall160b4d62013-04-22 12:15:39 -07003274 char temp_value[PROPERTY_VALUE_MAX];
Rubin Xu85c01f92014-10-13 12:49:54 +01003275 /* CRYPTO_GETFIELD_OK is success,
3276 * CRYPTO_GETFIELD_ERROR_NO_FIELD is value not set,
3277 * CRYPTO_GETFIELD_ERROR_BUF_TOO_SMALL is buffer (as given by len) too small,
3278 * CRYPTO_GETFIELD_ERROR_OTHER is any other error
Ken Sumrall160b4d62013-04-22 12:15:39 -07003279 */
Rubin Xu85c01f92014-10-13 12:49:54 +01003280 int rc = CRYPTO_GETFIELD_ERROR_OTHER;
3281 int i;
3282 char temp_field[PROPERTY_KEY_MAX];
Ken Sumrall160b4d62013-04-22 12:15:39 -07003283
3284 if (persist_data == NULL) {
3285 load_persistent_data();
3286 if (persist_data == NULL) {
3287 SLOGE("Getfield error, cannot load persistent data");
3288 goto out;
3289 }
3290 }
3291
Rubin Xu85c01f92014-10-13 12:49:54 +01003292 // Read value from persistent entries. If the original value is split into multiple entries,
3293 // stitch them back together.
Ken Sumrall160b4d62013-04-22 12:15:39 -07003294 if (!persist_get_key(fieldname, temp_value)) {
Rubin Xu85c01f92014-10-13 12:49:54 +01003295 // We found it, copy it to the caller's buffer and keep going until all entries are read.
3296 if (strlcpy(value, temp_value, len) >= (unsigned) len) {
3297 // value too small
3298 rc = CRYPTO_GETFIELD_ERROR_BUF_TOO_SMALL;
3299 goto out;
3300 }
3301 rc = CRYPTO_GETFIELD_OK;
3302
3303 for (i = 1; /* break explicitly */; i++) {
3304 if (snprintf(temp_field, sizeof(temp_field), "%s_%d", fieldname, i) >=
3305 (int) sizeof(temp_field)) {
3306 // If the fieldname is very long, we stop as soon as it begins to overflow the
3307 // maximum field length. At this point we have in fact fully read out the original
3308 // value because cryptfs_setfield would not allow fields with longer names to be
3309 // written in the first place.
3310 break;
3311 }
3312 if (!persist_get_key(temp_field, temp_value)) {
3313 if (strlcat(value, temp_value, len) >= (unsigned)len) {
3314 // value too small.
3315 rc = CRYPTO_GETFIELD_ERROR_BUF_TOO_SMALL;
3316 goto out;
3317 }
3318 } else {
3319 // Exhaust all entries.
3320 break;
3321 }
3322 }
Ken Sumrall160b4d62013-04-22 12:15:39 -07003323 } else {
3324 /* Sadness, it's not there. Return the error */
Rubin Xu85c01f92014-10-13 12:49:54 +01003325 rc = CRYPTO_GETFIELD_ERROR_NO_FIELD;
Ken Sumrall160b4d62013-04-22 12:15:39 -07003326 }
3327
3328out:
3329 return rc;
3330}
3331
3332/* Set the value of the specified field. */
Rubin Xu85c01f92014-10-13 12:49:54 +01003333int cryptfs_setfield(const char *fieldname, const char *value)
Ken Sumrall160b4d62013-04-22 12:15:39 -07003334{
Paul Crowley38132a12016-02-09 09:50:32 +00003335 if (e4crypt_is_native()) {
Paul Lawrence5a06a642016-02-03 13:39:13 -08003336 SLOGE("Cannot set field when file encrypted");
3337 return -1;
Paul Lawrence368d7942015-04-15 14:12:00 -07003338 }
3339
Ken Sumrall160b4d62013-04-22 12:15:39 -07003340 char encrypted_state[PROPERTY_VALUE_MAX];
Rubin Xu85c01f92014-10-13 12:49:54 +01003341 /* 0 is success, negative values are error */
3342 int rc = CRYPTO_SETFIELD_ERROR_OTHER;
Ken Sumrall160b4d62013-04-22 12:15:39 -07003343 int encrypted = 0;
Rubin Xu85c01f92014-10-13 12:49:54 +01003344 unsigned int field_id;
3345 char temp_field[PROPERTY_KEY_MAX];
3346 unsigned int num_entries;
3347 unsigned int max_keylen;
Ken Sumrall160b4d62013-04-22 12:15:39 -07003348
3349 if (persist_data == NULL) {
3350 load_persistent_data();
3351 if (persist_data == NULL) {
3352 SLOGE("Setfield error, cannot load persistent data");
3353 goto out;
3354 }
3355 }
3356
3357 property_get("ro.crypto.state", encrypted_state, "");
3358 if (!strcmp(encrypted_state, "encrypted") ) {
3359 encrypted = 1;
3360 }
3361
Rubin Xu85c01f92014-10-13 12:49:54 +01003362 // Compute the number of entries required to store value, each entry can store up to
3363 // (PROPERTY_VALUE_MAX - 1) chars
3364 if (strlen(value) == 0) {
3365 // Empty value also needs one entry to store.
3366 num_entries = 1;
3367 } else {
3368 num_entries = (strlen(value) + (PROPERTY_VALUE_MAX - 1) - 1) / (PROPERTY_VALUE_MAX - 1);
3369 }
3370
3371 max_keylen = strlen(fieldname);
3372 if (num_entries > 1) {
3373 // Need an extra "_%d" suffix.
3374 max_keylen += 1 + log10(num_entries);
3375 }
3376 if (max_keylen > PROPERTY_KEY_MAX - 1) {
3377 rc = CRYPTO_SETFIELD_ERROR_FIELD_TOO_LONG;
Ken Sumrall160b4d62013-04-22 12:15:39 -07003378 goto out;
3379 }
3380
Rubin Xu85c01f92014-10-13 12:49:54 +01003381 // Make sure we have enough space to write the new value
3382 if (persist_data->persist_valid_entries + num_entries - persist_count_keys(fieldname) >
3383 persist_get_max_entries(encrypted)) {
3384 rc = CRYPTO_SETFIELD_ERROR_VALUE_TOO_LONG;
3385 goto out;
3386 }
3387
3388 // Now that we know persist_data has enough space for value, let's delete the old field first
3389 // to make up space.
3390 persist_del_keys(fieldname, 0);
3391
3392 if (persist_set_key(fieldname, value, encrypted)) {
3393 // fail to set key, should not happen as we have already checked the available space
3394 SLOGE("persist_set_key() error during setfield()");
3395 goto out;
3396 }
3397
3398 for (field_id = 1; field_id < num_entries; field_id++) {
Greg Kaiserb610e772018-02-09 09:19:54 -08003399 snprintf(temp_field, sizeof(temp_field), "%s_%u", fieldname, field_id);
Rubin Xu85c01f92014-10-13 12:49:54 +01003400
3401 if (persist_set_key(temp_field, value + field_id * (PROPERTY_VALUE_MAX - 1), encrypted)) {
3402 // fail to set key, should not happen as we have already checked the available space.
3403 SLOGE("persist_set_key() error during setfield()");
3404 goto out;
3405 }
3406 }
3407
Ken Sumrall160b4d62013-04-22 12:15:39 -07003408 /* If we are running encrypted, save the persistent data now */
3409 if (encrypted) {
3410 if (save_persistent_data()) {
3411 SLOGE("Setfield error, cannot save persistent data");
3412 goto out;
3413 }
3414 }
3415
Rubin Xu85c01f92014-10-13 12:49:54 +01003416 rc = CRYPTO_SETFIELD_OK;
Ken Sumrall160b4d62013-04-22 12:15:39 -07003417
3418out:
3419 return rc;
3420}
Paul Lawrencef4faa572014-01-29 13:31:03 -08003421
3422/* Checks userdata. Attempt to mount the volume if default-
3423 * encrypted.
3424 * On success trigger next init phase and return 0.
3425 * Currently do not handle failure - see TODO below.
3426 */
3427int cryptfs_mount_default_encrypted(void)
3428{
Paul Lawrence84274cc2016-04-15 15:41:33 -07003429 int crypt_type = cryptfs_get_password_type();
3430 if (crypt_type < 0 || crypt_type > CRYPT_TYPE_MAX_TYPE) {
3431 SLOGE("Bad crypt type - error");
3432 } else if (crypt_type != CRYPT_TYPE_DEFAULT) {
3433 SLOGD("Password is not default - "
3434 "starting min framework to prompt");
3435 property_set("vold.decrypt", "trigger_restart_min_framework");
3436 return 0;
3437 } else if (cryptfs_check_passwd(DEFAULT_PASSWORD) == 0) {
3438 SLOGD("Password is default - restarting filesystem");
3439 cryptfs_restart_internal(0);
3440 return 0;
Paul Lawrencef4faa572014-01-29 13:31:03 -08003441 } else {
Paul Lawrence84274cc2016-04-15 15:41:33 -07003442 SLOGE("Encrypted, default crypt type but can't decrypt");
Paul Lawrencef4faa572014-01-29 13:31:03 -08003443 }
3444
Paul Lawrence6bfed202014-07-28 12:47:22 -07003445 /** Corrupt. Allow us to boot into framework, which will detect bad
3446 crypto when it calls do_crypto_complete, then do a factory reset
Paul Lawrencef4faa572014-01-29 13:31:03 -08003447 */
Paul Lawrence6bfed202014-07-28 12:47:22 -07003448 property_set("vold.decrypt", "trigger_restart_min_framework");
Paul Lawrencef4faa572014-01-29 13:31:03 -08003449 return 0;
3450}
3451
3452/* Returns type of the password, default, pattern, pin or password.
3453 */
3454int cryptfs_get_password_type(void)
3455{
Paul Crowley38132a12016-02-09 09:50:32 +00003456 if (e4crypt_is_native()) {
Paul Lawrence7b6b5652016-02-02 11:14:59 -08003457 SLOGE("cryptfs_get_password_type not valid for file encryption");
3458 return -1;
Paul Lawrence05335c32015-03-05 09:46:23 -08003459 }
3460
Paul Lawrencef4faa572014-01-29 13:31:03 -08003461 struct crypt_mnt_ftr crypt_ftr;
3462
3463 if (get_crypt_ftr_and_key(&crypt_ftr)) {
3464 SLOGE("Error getting crypt footer and key\n");
3465 return -1;
3466 }
3467
Paul Lawrence6bfed202014-07-28 12:47:22 -07003468 if (crypt_ftr.flags & CRYPT_INCONSISTENT_STATE) {
3469 return -1;
3470 }
3471
Paul Lawrencef4faa572014-01-29 13:31:03 -08003472 return crypt_ftr.crypt_type;
3473}
Paul Lawrence684dbdf2014-02-07 12:07:22 -08003474
Paul Lawrence05335c32015-03-05 09:46:23 -08003475const char* cryptfs_get_password()
Paul Lawrence684dbdf2014-02-07 12:07:22 -08003476{
Paul Crowley38132a12016-02-09 09:50:32 +00003477 if (e4crypt_is_native()) {
Paul Lawrence7b6b5652016-02-02 11:14:59 -08003478 SLOGE("cryptfs_get_password not valid for file encryption");
3479 return 0;
Paul Lawrence05335c32015-03-05 09:46:23 -08003480 }
3481
Paul Lawrence399317e2014-03-10 13:20:50 -07003482 struct timespec now;
Paul Lawrenceef2b5be2014-11-11 12:47:03 -08003483 clock_gettime(CLOCK_BOOTTIME, &now);
Paul Lawrence399317e2014-03-10 13:20:50 -07003484 if (now.tv_sec < password_expiry_time) {
3485 return password;
3486 } else {
3487 cryptfs_clear_password();
3488 return 0;
3489 }
3490}
3491
3492void cryptfs_clear_password()
3493{
3494 if (password) {
3495 size_t len = strlen(password);
3496 memset(password, 0, len);
3497 free(password);
3498 password = 0;
3499 password_expiry_time = 0;
3500 }
Paul Lawrence684dbdf2014-02-07 12:07:22 -08003501}
Paul Lawrence731a7a22015-04-28 22:14:15 +00003502
Paul Lawrence0c247462015-10-29 10:30:57 -07003503int cryptfs_isConvertibleToFBE()
3504{
Paul Crowleye2ee1522017-09-26 14:05:26 -07003505 struct fstab_rec* rec = fs_mgr_get_entry_for_mount_point(fstab_default, DATA_MNT_POINT);
Luis Hector Chavezf86566f2018-05-30 15:47:50 -07003506 return (rec && fs_mgr_is_convertible_to_fbe(rec)) ? 1 : 0;
Paul Lawrence0c247462015-10-29 10:30:57 -07003507}
AnilKumar Chimata98dc8352018-05-11 00:25:09 +05303508
3509int cryptfs_create_default_ftr(struct crypt_mnt_ftr* crypt_ftr, __attribute__((unused))int key_length)
3510{
3511 if (cryptfs_init_crypt_mnt_ftr(crypt_ftr)) {
3512 SLOGE("Failed to initialize crypt_ftr");
3513 return -1;
3514 }
3515
3516 if (create_encrypted_random_key(DEFAULT_PASSWORD, crypt_ftr->master_key,
3517 crypt_ftr->salt, crypt_ftr)) {
3518 SLOGE("Cannot create encrypted master key\n");
3519 return -1;
3520 }
3521
3522 //crypt_ftr->keysize = key_length / 8;
3523 return 0;
3524}
3525
3526int cryptfs_get_master_key(struct crypt_mnt_ftr* ftr, const char* password,
3527 unsigned char* master_key)
3528{
3529 int rc;
3530
3531 unsigned char* intermediate_key = 0;
3532 size_t intermediate_key_size = 0;
3533
3534 if (password == 0 || *password == 0) {
3535 password = DEFAULT_PASSWORD;
3536 }
3537
3538 rc = decrypt_master_key(password, master_key, ftr, &intermediate_key,
3539 &intermediate_key_size);
3540
3541 if (rc) {
3542 SLOGE("Can't calculate intermediate key");
3543 return rc;
3544 }
3545
3546 int N = 1 << ftr->N_factor;
3547 int r = 1 << ftr->r_factor;
3548 int p = 1 << ftr->p_factor;
3549
3550 unsigned char scrypted_intermediate_key[sizeof(ftr->scrypted_intermediate_key)];
3551
3552 rc = crypto_scrypt(intermediate_key, intermediate_key_size,
3553 ftr->salt, sizeof(ftr->salt), N, r, p,
3554 scrypted_intermediate_key,
3555 sizeof(scrypted_intermediate_key));
3556
3557 free(intermediate_key);
3558
3559 if (rc) {
3560 SLOGE("Can't scrypt intermediate key");
3561 return rc;
3562 }
3563
3564 return memcmp(scrypted_intermediate_key, ftr->scrypted_intermediate_key,
3565 intermediate_key_size);
3566}