blob: 97447cd57cccb91569e180d922c9bf2f6de0b946 [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
Daniel Rosenberg4f684712018-08-28 01:58:49 -070027#include "Checkpoint.h"
Logan Chiend557d762018-05-02 11:36:45 +080028#include "EncryptInplace.h"
Eric Biggersa701c452018-10-23 13:06:55 -070029#include "FsCrypt.h"
Logan Chiend557d762018-05-02 11:36:45 +080030#include "Keymaster.h"
31#include "Process.h"
32#include "ScryptParameters.h"
Paul Crowley298fa322018-10-30 15:59:24 -070033#include "Utils.h"
Logan Chiend557d762018-05-02 11:36:45 +080034#include "VoldUtil.h"
35#include "VolumeManager.h"
Logan Chiend557d762018-05-02 11:36:45 +080036
Eric Biggersed45ec32019-01-25 10:47:55 -080037#include <android-base/parseint.h>
Logan Chien3f2b1222018-05-02 11:39:03 +080038#include <android-base/properties.h>
Greg Kaiserab1e84a2018-12-11 12:40:51 -080039#include <android-base/stringprintf.h>
Logan Chiend557d762018-05-02 11:36:45 +080040#include <bootloader_message/bootloader_message.h>
Logan Chien3f2b1222018-05-02 11:39:03 +080041#include <cutils/android_reboot.h>
Logan Chien3f2b1222018-05-02 11:39:03 +080042#include <cutils/properties.h>
Tao Bao5a95ddb2016-10-05 18:01:19 -070043#include <ext4_utils/ext4_utils.h>
Logan Chien3f2b1222018-05-02 11:39:03 +080044#include <f2fs_sparseblock.h>
Ken Sumralle5032c42012-04-01 23:58:44 -070045#include <fs_mgr.h>
Eric Biggersa701c452018-10-23 13:06:55 -070046#include <fscrypt/fscrypt.h>
Logan Chien3f2b1222018-05-02 11:39:03 +080047#include <hardware_legacy/power.h>
Logan Chien188b0ab2018-04-23 13:37:39 +080048#include <log/log.h>
Ken Sumralle550f782013-08-20 13:48:23 -070049#include <logwrap/logwrap.h>
Logan Chiend557d762018-05-02 11:36:45 +080050#include <openssl/evp.h>
51#include <openssl/sha.h>
Ken Sumrallc290eaf2011-03-07 23:40:35 -080052#include <selinux/selinux.h>
Logan Chiend557d762018-05-02 11:36:45 +080053
54#include <ctype.h>
55#include <errno.h>
56#include <fcntl.h>
57#include <inttypes.h>
58#include <libgen.h>
59#include <linux/dm-ioctl.h>
60#include <linux/kdev_t.h>
61#include <math.h>
62#include <stdio.h>
63#include <stdlib.h>
64#include <string.h>
65#include <sys/ioctl.h>
66#include <sys/mount.h>
67#include <sys/param.h>
68#include <sys/stat.h>
69#include <sys/types.h>
70#include <sys/wait.h>
71#include <time.h>
72#include <unistd.h>
73
AnilKumar Chimata98dc8352018-05-11 00:25:09 +053074#ifdef CONFIG_HW_DISK_ENCRYPTION
75#include <cryptfs_hw.h>
76#endif
Wei Wang4375f1b2017-02-24 17:43:01 -080077extern "C" {
78#include <crypto_scrypt.h>
79}
Mark Salyzyn3e971272014-01-21 13:27:04 -080080
Eric Biggersed45ec32019-01-25 10:47:55 -080081using android::base::ParseUint;
Greg Kaiserab1e84a2018-12-11 12:40:51 -080082using android::base::StringPrintf;
Tom Cherry4c5bde22019-01-29 14:34:01 -080083using android::fs_mgr::GetEntryForMountPoint;
Paul Crowley298fa322018-10-30 15:59:24 -070084using namespace std::chrono_literals;
85
Mark Salyzyn5eecc442014-02-12 14:16:14 -080086#define UNUSED __attribute__((unused))
87
Ken Sumrall8f869aa2010-12-03 03:47:09 -080088#define DM_CRYPT_BUF_SIZE 4096
89
Jason parks70a4b3f2011-01-28 10:10:47 -060090#define HASH_COUNT 2000
Greg Kaiserc0de9c72018-02-14 20:05:54 -080091
92constexpr size_t INTERMEDIATE_KEY_LEN_BYTES = 16;
93constexpr size_t INTERMEDIATE_IV_LEN_BYTES = 16;
Paul Crowley14c8c072018-09-18 13:30:21 -070094constexpr size_t INTERMEDIATE_BUF_SIZE = (INTERMEDIATE_KEY_LEN_BYTES + INTERMEDIATE_IV_LEN_BYTES);
Greg Kaiserc0de9c72018-02-14 20:05:54 -080095
96// SCRYPT_LEN is used by struct crypt_mnt_ftr for its intermediate key.
Paul Crowley14c8c072018-09-18 13:30:21 -070097static_assert(INTERMEDIATE_BUF_SIZE == SCRYPT_LEN, "Mismatch of intermediate key sizes");
Jason parks70a4b3f2011-01-28 10:10:47 -060098
Paul Crowley14c8c072018-09-18 13:30:21 -070099#define KEY_IN_FOOTER "footer"
Ken Sumrall29d8da82011-05-18 17:20:07 -0700100
AnilKumar Chimata98dc8352018-05-11 00:25:09 +0530101#define DEFAULT_HEX_PASSWORD "64656661756c745f70617373776f7264"
Paul Lawrence3bd36d52015-06-09 13:37:44 -0700102#define DEFAULT_PASSWORD "default_password"
Paul Lawrencef4faa572014-01-29 13:31:03 -0800103
Paul Lawrence3d99eba2015-11-20 07:07:19 -0800104#define CRYPTO_BLOCK_DEVICE "userdata"
105
106#define BREADCRUMB_FILE "/data/misc/vold/convert_fde"
107
Ken Sumrall29d8da82011-05-18 17:20:07 -0700108#define EXT4_FS 1
JP Abgrall62c7af32014-06-16 13:01:23 -0700109#define F2FS_FS 2
Ken Sumrall29d8da82011-05-18 17:20:07 -0700110
Ken Sumralle919efe2012-09-29 17:07:41 -0700111#define TABLE_LOAD_RETRIES 10
112
Shawn Willden47ba10d2014-09-03 17:07:06 -0600113#define RSA_KEY_SIZE 2048
114#define RSA_KEY_SIZE_BYTES (RSA_KEY_SIZE / 8)
115#define RSA_EXPONENT 0x10001
Shawn Willdenda6e8992015-06-03 09:40:45 -0600116#define KEYMASTER_CRYPTFS_RATE_LIMIT 1 // Maximum one try per second
AnilKumar Chimata98dc8352018-05-11 00:25:09 +0530117#define KEY_LEN_BYTES 16
Paul Lawrence69f4ebd2014-04-14 12:17:14 -0700118
Paul Lawrence8e3f4512014-09-08 10:11:17 -0700119#define RETRY_MOUNT_ATTEMPTS 10
120#define RETRY_MOUNT_DELAY_SECONDS 1
121
Paul Crowley5afbc622017-11-27 09:42:17 -0800122#define CREATE_CRYPTO_BLK_DEV_FLAGS_ALLOW_ENCRYPT_OVERRIDE (1)
123
Paul Crowley73473332017-11-21 15:43:51 -0800124static int put_crypt_ftr_and_key(struct crypt_mnt_ftr* crypt_ftr);
125
Greg Kaiser59ad0182018-02-16 13:01:36 -0800126static unsigned char saved_master_key[MAX_KEY_LEN];
Paul Crowley14c8c072018-09-18 13:30:21 -0700127static char* saved_mount_point;
128static int master_key_saved = 0;
129static struct crypt_persist_data* persist_data = NULL;
Ken Sumrall56ad03c2013-02-13 13:00:19 -0800130
AnilKumar Chimata98dc8352018-05-11 00:25:09 +0530131static int previous_type;
132
133#ifdef CONFIG_HW_DISK_ENCRYPTION
134static int scrypt_keymaster(const char *passwd, const unsigned char *salt,
135 unsigned char *ikey, void *params);
136static void convert_key_to_hex_ascii(const unsigned char *master_key,
137 unsigned int keysize, char *master_key_ascii);
138static int put_crypt_ftr_and_key(struct crypt_mnt_ftr *crypt_ftr);
139static int test_mount_hw_encrypted_fs(struct crypt_mnt_ftr* crypt_ftr,
140 const char *passwd, const char *mount_point, const char *label);
141int cryptfs_changepw_hw_fde(int crypt_type, const char *currentpw,
142 const char *newpw);
143int cryptfs_check_passwd_hw(char *passwd);
144int cryptfs_get_master_key(struct crypt_mnt_ftr* ftr, const char* password,
145 unsigned char* master_key);
146
147static void convert_key_to_hex_ascii_for_upgrade(const unsigned char *master_key,
148 unsigned int keysize, char *master_key_ascii)
149{
150 unsigned int i, a;
151 unsigned char nibble;
152
153 for (i = 0, a = 0; i < keysize; i++, a += 2) {
154 /* For each byte, write out two ascii hex digits */
155 nibble = (master_key[i] >> 4) & 0xf;
156 master_key_ascii[a] = nibble + (nibble > 9 ? 0x57 : 0x30);
157
158 nibble = master_key[i] & 0xf;
159 master_key_ascii[a + 1] = nibble + (nibble > 9 ? 0x57 : 0x30);
160 }
161
162 /* Add the null termination */
163 master_key_ascii[a] = '\0';
164}
165
166static int get_keymaster_hw_fde_passwd(const char* passwd, unsigned char* newpw,
167 unsigned char* salt,
168 const struct crypt_mnt_ftr *ftr)
169{
170 /* if newpw updated, return 0
171 * if newpw not updated return -1
172 */
173 int rc = -1;
174
175 if (should_use_keymaster()) {
176 if (scrypt_keymaster(passwd, salt, newpw, (void*)ftr)) {
177 SLOGE("scrypt failed");
178 } else {
179 rc = 0;
180 }
181 }
182
183 return rc;
184}
185
186static int verify_hw_fde_passwd(const char *passwd, struct crypt_mnt_ftr* crypt_ftr)
187{
188 unsigned char newpw[32] = {0};
189 int key_index;
190 if (get_keymaster_hw_fde_passwd(passwd, newpw, crypt_ftr->salt, crypt_ftr))
191 key_index = set_hw_device_encryption_key(passwd,
192 (char*) crypt_ftr->crypto_type_name);
193 else
194 key_index = set_hw_device_encryption_key((const char*)newpw,
195 (char*) crypt_ftr->crypto_type_name);
196 return key_index;
197}
198
199static int verify_and_update_hw_fde_passwd(const char *passwd,
200 struct crypt_mnt_ftr* crypt_ftr)
201{
202 char* new_passwd = NULL;
203 unsigned char newpw[32] = {0};
204 int key_index = -1;
205 int passwd_updated = -1;
206 int ascii_passwd_updated = (crypt_ftr->flags & CRYPT_ASCII_PASSWORD_UPDATED);
207
208 key_index = verify_hw_fde_passwd(passwd, crypt_ftr);
209 if (key_index < 0) {
210 ++crypt_ftr->failed_decrypt_count;
211
212 if (ascii_passwd_updated) {
213 SLOGI("Ascii password was updated");
214 } else {
215 /* Code in else part would execute only once:
216 * When device is upgraded from L->M release.
217 * Once upgraded, code flow should never come here.
218 * L release passed actual password in hex, so try with hex
219 * Each nible of passwd was encoded as a byte, so allocate memory
220 * twice of password len plus one more byte for null termination
221 */
222 if (crypt_ftr->crypt_type == CRYPT_TYPE_DEFAULT) {
223 new_passwd = (char*)malloc(strlen(DEFAULT_HEX_PASSWORD) + 1);
224 if (new_passwd == NULL) {
225 SLOGE("System out of memory. Password verification incomplete");
226 goto out;
227 }
228 strlcpy(new_passwd, DEFAULT_HEX_PASSWORD, strlen(DEFAULT_HEX_PASSWORD) + 1);
229 } else {
230 new_passwd = (char*)malloc(strlen(passwd) * 2 + 1);
231 if (new_passwd == NULL) {
232 SLOGE("System out of memory. Password verification incomplete");
233 goto out;
234 }
235 convert_key_to_hex_ascii_for_upgrade((const unsigned char*)passwd,
236 strlen(passwd), new_passwd);
237 }
238 key_index = set_hw_device_encryption_key((const char*)new_passwd,
239 (char*) crypt_ftr->crypto_type_name);
240 if (key_index >=0) {
241 crypt_ftr->failed_decrypt_count = 0;
242 SLOGI("Hex password verified...will try to update with Ascii value");
243 /* Before updating password, tie that with keymaster to tie with ROT */
244
245 if (get_keymaster_hw_fde_passwd(passwd, newpw,
246 crypt_ftr->salt, crypt_ftr)) {
247 passwd_updated = update_hw_device_encryption_key(new_passwd,
248 passwd, (char*)crypt_ftr->crypto_type_name);
249 } else {
250 passwd_updated = update_hw_device_encryption_key(new_passwd,
251 (const char*)newpw, (char*)crypt_ftr->crypto_type_name);
252 }
253
254 if (passwd_updated >= 0) {
255 crypt_ftr->flags |= CRYPT_ASCII_PASSWORD_UPDATED;
256 SLOGI("Ascii password recorded and updated");
257 } else {
258 SLOGI("Passwd verified, could not update...Will try next time");
259 }
260 } else {
261 ++crypt_ftr->failed_decrypt_count;
262 }
263 free(new_passwd);
264 }
265 } else {
266 if (!ascii_passwd_updated)
267 crypt_ftr->flags |= CRYPT_ASCII_PASSWORD_UPDATED;
268 }
269out:
270 // update footer before leaving
271 put_crypt_ftr_and_key(crypt_ftr);
272 return key_index;
273}
274#endif
275
Paul Lawrence69f4ebd2014-04-14 12:17:14 -0700276/* Should we use keymaster? */
Paul Crowley14c8c072018-09-18 13:30:21 -0700277static int keymaster_check_compatibility() {
Janis Danisevskis015ec302017-01-31 11:31:08 +0000278 return keymaster_compatibility_cryptfs_scrypt();
Paul Lawrence69f4ebd2014-04-14 12:17:14 -0700279}
280
281/* Create a new keymaster key and store it in this footer */
Paul Crowley14c8c072018-09-18 13:30:21 -0700282static int keymaster_create_key(struct crypt_mnt_ftr* ftr) {
Paul Lawrence3d99eba2015-11-20 07:07:19 -0800283 if (ftr->keymaster_blob_size) {
284 SLOGI("Already have key");
285 return 0;
286 }
287
Paul Crowley14c8c072018-09-18 13:30:21 -0700288 int rc = keymaster_create_key_for_cryptfs_scrypt(
289 RSA_KEY_SIZE, RSA_EXPONENT, KEYMASTER_CRYPTFS_RATE_LIMIT, ftr->keymaster_blob,
290 KEYMASTER_BLOB_SIZE, &ftr->keymaster_blob_size);
Janis Danisevskis015ec302017-01-31 11:31:08 +0000291 if (rc) {
292 if (ftr->keymaster_blob_size > KEYMASTER_BLOB_SIZE) {
Paul Crowley73473332017-11-21 15:43:51 -0800293 SLOGE("Keymaster key blob too large");
Janis Danisevskis015ec302017-01-31 11:31:08 +0000294 ftr->keymaster_blob_size = 0;
295 }
296 SLOGE("Failed to generate keypair");
Paul Lawrence69f4ebd2014-04-14 12:17:14 -0700297 return -1;
298 }
Janis Danisevskis015ec302017-01-31 11:31:08 +0000299 return 0;
Paul Lawrence69f4ebd2014-04-14 12:17:14 -0700300}
301
Shawn Willdene17a9c42014-09-08 13:04:08 -0600302/* This signs the given object using the keymaster key. */
Paul Crowley14c8c072018-09-18 13:30:21 -0700303static int keymaster_sign_object(struct crypt_mnt_ftr* ftr, const unsigned char* object,
304 const size_t object_size, unsigned char** signature,
305 size_t* signature_size) {
Shawn Willden47ba10d2014-09-03 17:07:06 -0600306 unsigned char to_sign[RSA_KEY_SIZE_BYTES];
Shawn Willdene17a9c42014-09-08 13:04:08 -0600307 size_t to_sign_size = sizeof(to_sign);
Shawn Willden47ba10d2014-09-03 17:07:06 -0600308 memset(to_sign, 0, RSA_KEY_SIZE_BYTES);
Shawn Willden47ba10d2014-09-03 17:07:06 -0600309
Shawn Willdene17a9c42014-09-08 13:04:08 -0600310 // To sign a message with RSA, the message must satisfy two
311 // constraints:
312 //
313 // 1. The message, when interpreted as a big-endian numeric value, must
314 // be strictly less than the public modulus of the RSA key. Note
315 // that because the most significant bit of the public modulus is
316 // guaranteed to be 1 (else it's an (n-1)-bit key, not an n-bit
317 // key), an n-bit message with most significant bit 0 always
318 // satisfies this requirement.
319 //
320 // 2. The message must have the same length in bits as the public
321 // modulus of the RSA key. This requirement isn't mathematically
322 // necessary, but is necessary to ensure consistency in
323 // implementations.
324 switch (ftr->kdf_type) {
Shawn Willdene17a9c42014-09-08 13:04:08 -0600325 case KDF_SCRYPT_KEYMASTER:
326 // This ensures the most significant byte of the signed message
327 // is zero. We could have zero-padded to the left instead, but
328 // this approach is slightly more robust against changes in
329 // object size. However, it's still broken (but not unusably
Shawn Willdenda6e8992015-06-03 09:40:45 -0600330 // so) because we really should be using a proper deterministic
331 // RSA padding function, such as PKCS1.
Wei Wang4375f1b2017-02-24 17:43:01 -0800332 memcpy(to_sign + 1, object, std::min((size_t)RSA_KEY_SIZE_BYTES - 1, object_size));
Shawn Willdene17a9c42014-09-08 13:04:08 -0600333 SLOGI("Signing safely-padded object");
334 break;
335 default:
336 SLOGE("Unknown KDF type %d", ftr->kdf_type);
Janis Danisevskis015ec302017-01-31 11:31:08 +0000337 return -1;
Shawn Willdene17a9c42014-09-08 13:04:08 -0600338 }
Paul Crowley73473332017-11-21 15:43:51 -0800339 for (;;) {
340 auto result = keymaster_sign_object_for_cryptfs_scrypt(
341 ftr->keymaster_blob, ftr->keymaster_blob_size, KEYMASTER_CRYPTFS_RATE_LIMIT, to_sign,
342 to_sign_size, signature, signature_size);
343 switch (result) {
344 case KeymasterSignResult::ok:
345 return 0;
346 case KeymasterSignResult::upgrade:
347 break;
348 default:
349 return -1;
350 }
351 SLOGD("Upgrading key");
352 if (keymaster_upgrade_key_for_cryptfs_scrypt(
353 RSA_KEY_SIZE, RSA_EXPONENT, KEYMASTER_CRYPTFS_RATE_LIMIT, ftr->keymaster_blob,
354 ftr->keymaster_blob_size, ftr->keymaster_blob, KEYMASTER_BLOB_SIZE,
355 &ftr->keymaster_blob_size) != 0) {
356 SLOGE("Failed to upgrade key");
357 return -1;
358 }
359 if (put_crypt_ftr_and_key(ftr) != 0) {
360 SLOGE("Failed to write upgraded key to disk");
361 }
362 SLOGD("Key upgraded successfully");
363 }
Shawn Willden47ba10d2014-09-03 17:07:06 -0600364}
365
Paul Lawrence399317e2014-03-10 13:20:50 -0700366/* Store password when userdata is successfully decrypted and mounted.
367 * Cleared by cryptfs_clear_password
368 *
369 * To avoid a double prompt at boot, we need to store the CryptKeeper
370 * password and pass it to KeyGuard, which uses it to unlock KeyStore.
371 * Since the entire framework is torn down and rebuilt after encryption,
372 * we have to use a daemon or similar to store the password. Since vold
373 * is secured against IPC except from system processes, it seems a reasonable
374 * place to store this.
375 *
376 * password should be cleared once it has been used.
377 *
378 * password is aged out after password_max_age_seconds seconds.
Paul Lawrence684dbdf2014-02-07 12:07:22 -0800379 */
Paul Lawrence399317e2014-03-10 13:20:50 -0700380static char* password = 0;
381static int password_expiry_time = 0;
382static const int password_max_age_seconds = 60;
Paul Lawrence684dbdf2014-02-07 12:07:22 -0800383
Paul Crowley14c8c072018-09-18 13:30:21 -0700384enum class RebootType { reboot, recovery, shutdown };
385static void cryptfs_reboot(RebootType rt) {
386 switch (rt) {
387 case RebootType::reboot:
388 property_set(ANDROID_RB_PROPERTY, "reboot");
389 break;
Paul Lawrence87999172014-02-20 12:21:31 -0800390
Paul Crowley14c8c072018-09-18 13:30:21 -0700391 case RebootType::recovery:
392 property_set(ANDROID_RB_PROPERTY, "reboot,recovery");
393 break;
Paul Lawrence87999172014-02-20 12:21:31 -0800394
Paul Crowley14c8c072018-09-18 13:30:21 -0700395 case RebootType::shutdown:
396 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
Paul Crowley14c8c072018-09-18 13:30:21 -0700406static void ioctl_init(struct dm_ioctl* io, size_t dataSize, const char* name, unsigned flags) {
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800407 memset(io, 0, dataSize);
408 io->data_size = dataSize;
409 io->data_start = sizeof(struct dm_ioctl);
410 io->version[0] = 4;
411 io->version[1] = 0;
412 io->version[2] = 0;
413 io->flags = flags;
414 if (name) {
Marek Pola5e6b9142015-02-05 14:22:34 +0100415 strlcpy(io->name, name, sizeof(io->name));
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800416 }
417}
418
Greg Kaiser38723f22018-02-16 13:35:35 -0800419namespace {
420
421struct CryptoType;
422
423// Use to get the CryptoType in use on this device.
Paul Crowley14c8c072018-09-18 13:30:21 -0700424const CryptoType& get_crypto_type();
Greg Kaiser38723f22018-02-16 13:35:35 -0800425
426struct CryptoType {
427 // We should only be constructing CryptoTypes as part of
428 // supported_crypto_types[]. We do it via this pseudo-builder pattern,
429 // which isn't pure or fully protected as a concession to being able to
430 // do it all at compile time. Add new CryptoTypes in
431 // supported_crypto_types[] below.
432 constexpr CryptoType() : CryptoType(nullptr, nullptr, 0xFFFFFFFF) {}
433 constexpr CryptoType set_keysize(uint32_t size) const {
434 return CryptoType(this->property_name, this->crypto_name, size);
435 }
Paul Crowley14c8c072018-09-18 13:30:21 -0700436 constexpr CryptoType set_property_name(const char* property) const {
Greg Kaiser38723f22018-02-16 13:35:35 -0800437 return CryptoType(property, this->crypto_name, this->keysize);
438 }
Paul Crowley14c8c072018-09-18 13:30:21 -0700439 constexpr CryptoType set_crypto_name(const char* crypto) const {
Greg Kaiser38723f22018-02-16 13:35:35 -0800440 return CryptoType(this->property_name, crypto, this->keysize);
441 }
442
Paul Crowley14c8c072018-09-18 13:30:21 -0700443 constexpr const char* get_property_name() const { return property_name; }
444 constexpr const char* get_crypto_name() const { return crypto_name; }
Greg Kaiser38723f22018-02-16 13:35:35 -0800445 constexpr uint32_t get_keysize() const { return keysize; }
446
Paul Crowley14c8c072018-09-18 13:30:21 -0700447 private:
448 const char* property_name;
449 const char* crypto_name;
Greg Kaiser38723f22018-02-16 13:35:35 -0800450 uint32_t keysize;
451
Paul Crowley14c8c072018-09-18 13:30:21 -0700452 constexpr CryptoType(const char* property, const char* crypto, uint32_t ksize)
Greg Kaiser38723f22018-02-16 13:35:35 -0800453 : property_name(property), crypto_name(crypto), keysize(ksize) {}
Paul Crowley14c8c072018-09-18 13:30:21 -0700454 friend const CryptoType& get_crypto_type();
455 static const CryptoType& get_device_crypto_algorithm();
Greg Kaiser38723f22018-02-16 13:35:35 -0800456};
457
458// We only want to parse this read-only property once. But we need to wait
459// until the system is initialized before we can read it. So we use a static
460// scoped within this function to get it only once.
Paul Crowley14c8c072018-09-18 13:30:21 -0700461const CryptoType& get_crypto_type() {
Greg Kaiser38723f22018-02-16 13:35:35 -0800462 static CryptoType crypto_type = CryptoType::get_device_crypto_algorithm();
463 return crypto_type;
464}
465
466constexpr CryptoType default_crypto_type = CryptoType()
Paul Crowley14c8c072018-09-18 13:30:21 -0700467 .set_property_name("AES-128-CBC")
468 .set_crypto_name("aes-cbc-essiv:sha256")
469 .set_keysize(16);
Greg Kaiser38723f22018-02-16 13:35:35 -0800470
471constexpr CryptoType supported_crypto_types[] = {
472 default_crypto_type,
Greg Kaiser8cb4c9f2018-12-03 11:23:19 -0800473 CryptoType()
474 .set_property_name("adiantum")
475 .set_crypto_name("xchacha12,aes-adiantum-plain64")
476 .set_keysize(32),
Greg Kaiser38723f22018-02-16 13:35:35 -0800477 // Add new CryptoTypes here. Order is not important.
478};
479
Greg Kaiser38723f22018-02-16 13:35:35 -0800480// ---------- START COMPILE-TIME SANITY CHECK BLOCK -------------------------
481// We confirm all supported_crypto_types have a small enough keysize and
482// had both set_property_name() and set_crypto_name() called.
483
484template <typename T, size_t N>
Paul Crowley14c8c072018-09-18 13:30:21 -0700485constexpr size_t array_length(T (&)[N]) {
486 return N;
487}
Greg Kaiser38723f22018-02-16 13:35:35 -0800488
489constexpr bool indexOutOfBoundsForCryptoTypes(size_t index) {
490 return (index >= array_length(supported_crypto_types));
491}
492
Paul Crowley14c8c072018-09-18 13:30:21 -0700493constexpr bool isValidCryptoType(const CryptoType& crypto_type) {
Greg Kaiser38723f22018-02-16 13:35:35 -0800494 return ((crypto_type.get_property_name() != nullptr) &&
495 (crypto_type.get_crypto_name() != nullptr) &&
496 (crypto_type.get_keysize() <= MAX_KEY_LEN));
497}
498
499// Note in C++11 that constexpr functions can only have a single line.
500// So our code is a bit convoluted (using recursion instead of a loop),
501// but it's asserting at compile time that all of our key lengths are valid.
502constexpr bool validateSupportedCryptoTypes(size_t index) {
503 return indexOutOfBoundsForCryptoTypes(index) ||
Paul Crowley14c8c072018-09-18 13:30:21 -0700504 (isValidCryptoType(supported_crypto_types[index]) &&
505 validateSupportedCryptoTypes(index + 1));
Greg Kaiser38723f22018-02-16 13:35:35 -0800506}
507
508static_assert(validateSupportedCryptoTypes(0),
509 "We have a CryptoType with keysize > MAX_KEY_LEN or which was "
510 "incompletely constructed.");
511// ---------- END COMPILE-TIME SANITY CHECK BLOCK -------------------------
512
Greg Kaiser38723f22018-02-16 13:35:35 -0800513// Don't call this directly, use get_crypto_type(), which caches this result.
Paul Crowley14c8c072018-09-18 13:30:21 -0700514const CryptoType& CryptoType::get_device_crypto_algorithm() {
Greg Kaiser38723f22018-02-16 13:35:35 -0800515 constexpr char CRYPT_ALGO_PROP[] = "ro.crypto.fde_algorithm";
516 char paramstr[PROPERTY_VALUE_MAX];
517
Paul Crowley14c8c072018-09-18 13:30:21 -0700518 property_get(CRYPT_ALGO_PROP, paramstr, default_crypto_type.get_property_name());
519 for (auto const& ctype : supported_crypto_types) {
Greg Kaiser38723f22018-02-16 13:35:35 -0800520 if (strcmp(paramstr, ctype.get_property_name()) == 0) {
521 return ctype;
522 }
523 }
Paul Crowley14c8c072018-09-18 13:30:21 -0700524 ALOGE("Invalid name (%s) for %s. Defaulting to %s\n", paramstr, CRYPT_ALGO_PROP,
525 default_crypto_type.get_property_name());
Greg Kaiser38723f22018-02-16 13:35:35 -0800526 return default_crypto_type;
527}
528
529} // namespace
530
Kenny Rootc4c70f12013-06-14 12:11:38 -0700531/**
532 * Gets the default device scrypt parameters for key derivation time tuning.
533 * The parameters should lead to about one second derivation time for the
534 * given device.
535 */
Paul Crowley14c8c072018-09-18 13:30:21 -0700536static void get_device_scrypt_params(struct crypt_mnt_ftr* ftr) {
Kenny Rootc4c70f12013-06-14 12:11:38 -0700537 char paramstr[PROPERTY_VALUE_MAX];
Paul Crowley63c18d32016-02-10 14:02:47 +0000538 int Nf, rf, pf;
Kenny Rootc4c70f12013-06-14 12:11:38 -0700539
Paul Crowley63c18d32016-02-10 14:02:47 +0000540 property_get(SCRYPT_PROP, paramstr, SCRYPT_DEFAULTS);
541 if (!parse_scrypt_parameters(paramstr, &Nf, &rf, &pf)) {
542 SLOGW("bad scrypt parameters '%s' should be like '12:8:1'; using defaults", paramstr);
543 parse_scrypt_parameters(SCRYPT_DEFAULTS, &Nf, &rf, &pf);
Kenny Rootc4c70f12013-06-14 12:11:38 -0700544 }
Paul Crowley63c18d32016-02-10 14:02:47 +0000545 ftr->N_factor = Nf;
546 ftr->r_factor = rf;
547 ftr->p_factor = pf;
Kenny Rootc4c70f12013-06-14 12:11:38 -0700548}
549
Greg Kaiser57f9af62018-02-16 13:13:58 -0800550uint32_t cryptfs_get_keysize() {
Greg Kaiser38723f22018-02-16 13:35:35 -0800551 return get_crypto_type().get_keysize();
Greg Kaiser57f9af62018-02-16 13:13:58 -0800552}
553
Paul Crowley14c8c072018-09-18 13:30:21 -0700554const char* cryptfs_get_crypto_name() {
Greg Kaiser38723f22018-02-16 13:35:35 -0800555 return get_crypto_type().get_crypto_name();
Greg Kaiser57f9af62018-02-16 13:13:58 -0800556}
557
Tom Cherry4c5bde22019-01-29 14:34:01 -0800558static uint64_t get_fs_size(const char* dev) {
Ken Sumrall3ed82362011-01-28 23:31:16 -0800559 int fd, block_size;
560 struct ext4_super_block sb;
Oleksiy Avramchenko625dc782018-05-23 10:50:46 +0200561 uint64_t len;
Ken Sumrall3ed82362011-01-28 23:31:16 -0800562
Paul Crowley14c8c072018-09-18 13:30:21 -0700563 if ((fd = open(dev, O_RDONLY | O_CLOEXEC)) < 0) {
Ken Sumrall3ed82362011-01-28 23:31:16 -0800564 SLOGE("Cannot open device to get filesystem size ");
565 return 0;
566 }
567
568 if (lseek64(fd, 1024, SEEK_SET) < 0) {
569 SLOGE("Cannot seek to superblock");
570 return 0;
571 }
572
573 if (read(fd, &sb, sizeof(sb)) != sizeof(sb)) {
574 SLOGE("Cannot read superblock");
575 return 0;
576 }
577
578 close(fd);
579
Daniel Rosenberge82df162014-08-15 22:19:23 +0000580 if (le32_to_cpu(sb.s_magic) != EXT4_SUPER_MAGIC) {
581 SLOGE("Not a valid ext4 superblock");
582 return 0;
583 }
Ken Sumrall3ed82362011-01-28 23:31:16 -0800584 block_size = 1024 << sb.s_log_block_size;
585 /* compute length in bytes */
Oleksiy Avramchenko625dc782018-05-23 10:50:46 +0200586 len = (((uint64_t)sb.s_blocks_count_hi << 32) + sb.s_blocks_count_lo) * block_size;
Ken Sumrall3ed82362011-01-28 23:31:16 -0800587
588 /* return length in sectors */
Oleksiy Avramchenko625dc782018-05-23 10:50:46 +0200589 return len / 512;
Ken Sumrall3ed82362011-01-28 23:31:16 -0800590}
591
Tom Cherry4c5bde22019-01-29 14:34:01 -0800592static void get_crypt_info(std::string* key_loc, std::string* real_blk_device) {
593 for (const auto& entry : fstab_default) {
594 if (!entry.fs_mgr_flags.vold_managed &&
595 (entry.fs_mgr_flags.crypt || entry.fs_mgr_flags.force_crypt ||
596 entry.fs_mgr_flags.force_fde_or_fbe || entry.fs_mgr_flags.file_encryption)) {
597 if (key_loc != nullptr) {
598 *key_loc = entry.key_loc;
599 }
600 if (real_blk_device != nullptr) {
601 *real_blk_device = entry.blk_device;
602 }
603 return;
604 }
605 }
606}
607
Paul Crowley14c8c072018-09-18 13:30:21 -0700608static int get_crypt_ftr_info(char** metadata_fname, off64_t* off) {
609 static int cached_data = 0;
Oleksiy Avramchenko625dc782018-05-23 10:50:46 +0200610 static uint64_t cached_off = 0;
Paul Crowley14c8c072018-09-18 13:30:21 -0700611 static char cached_metadata_fname[PROPERTY_VALUE_MAX] = "";
Paul Crowley14c8c072018-09-18 13:30:21 -0700612 char key_loc[PROPERTY_VALUE_MAX];
613 char real_blkdev[PROPERTY_VALUE_MAX];
614 int rc = -1;
Ken Sumrall160b4d62013-04-22 12:15:39 -0700615
Paul Crowley14c8c072018-09-18 13:30:21 -0700616 if (!cached_data) {
Tom Cherry4c5bde22019-01-29 14:34:01 -0800617 std::string key_loc;
618 std::string real_blkdev;
619 get_crypt_info(&key_loc, &real_blkdev);
Ken Sumrall160b4d62013-04-22 12:15:39 -0700620
Tom Cherry4c5bde22019-01-29 14:34:01 -0800621 if (key_loc == KEY_IN_FOOTER) {
Oleksiy Avramchenko625dc782018-05-23 10:50:46 +0200622 if (android::vold::GetBlockDevSize(real_blkdev, &cached_off) == android::OK) {
Paul Crowley14c8c072018-09-18 13:30:21 -0700623 /* If it's an encrypted Android partition, the last 16 Kbytes contain the
624 * encryption info footer and key, and plenty of bytes to spare for future
625 * growth.
626 */
Tom Cherry4c5bde22019-01-29 14:34:01 -0800627 strlcpy(cached_metadata_fname, real_blkdev.c_str(), sizeof(cached_metadata_fname));
Oleksiy Avramchenko625dc782018-05-23 10:50:46 +0200628 cached_off -= CRYPT_FOOTER_OFFSET;
Paul Crowley14c8c072018-09-18 13:30:21 -0700629 cached_data = 1;
630 } else {
Tom Cherry4c5bde22019-01-29 14:34:01 -0800631 SLOGE("Cannot get size of block device %s\n", real_blkdev.c_str());
Paul Crowley14c8c072018-09-18 13:30:21 -0700632 }
Paul Crowley14c8c072018-09-18 13:30:21 -0700633 } else {
Tom Cherry4c5bde22019-01-29 14:34:01 -0800634 strlcpy(cached_metadata_fname, key_loc.c_str(), sizeof(cached_metadata_fname));
Paul Crowley14c8c072018-09-18 13:30:21 -0700635 cached_off = 0;
636 cached_data = 1;
637 }
Ken Sumrall160b4d62013-04-22 12:15:39 -0700638 }
Ken Sumrall160b4d62013-04-22 12:15:39 -0700639
Paul Crowley14c8c072018-09-18 13:30:21 -0700640 if (cached_data) {
641 if (metadata_fname) {
642 *metadata_fname = cached_metadata_fname;
643 }
644 if (off) {
645 *off = cached_off;
646 }
647 rc = 0;
Ken Sumrall160b4d62013-04-22 12:15:39 -0700648 }
Ken Sumrall160b4d62013-04-22 12:15:39 -0700649
Paul Crowley14c8c072018-09-18 13:30:21 -0700650 return rc;
Ken Sumrall160b4d62013-04-22 12:15:39 -0700651}
652
Paul Lawrence3d99eba2015-11-20 07:07:19 -0800653/* Set sha256 checksum in structure */
Paul Crowley14c8c072018-09-18 13:30:21 -0700654static void set_ftr_sha(struct crypt_mnt_ftr* crypt_ftr) {
Paul Lawrence3d99eba2015-11-20 07:07:19 -0800655 SHA256_CTX c;
656 SHA256_Init(&c);
657 memset(crypt_ftr->sha256, 0, sizeof(crypt_ftr->sha256));
658 SHA256_Update(&c, crypt_ftr, sizeof(*crypt_ftr));
659 SHA256_Final(crypt_ftr->sha256, &c);
660}
661
Ken Sumralle8744072011-01-18 22:01:55 -0800662/* key or salt can be NULL, in which case just skip writing that value. Useful to
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800663 * update the failed mount count but not change the key.
664 */
Paul Crowley14c8c072018-09-18 13:30:21 -0700665static int put_crypt_ftr_and_key(struct crypt_mnt_ftr* crypt_ftr) {
666 int fd;
667 unsigned int cnt;
668 /* starting_off is set to the SEEK_SET offset
669 * where the crypto structure starts
670 */
671 off64_t starting_off;
672 int rc = -1;
673 char* fname = NULL;
674 struct stat statbuf;
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800675
Paul Crowley14c8c072018-09-18 13:30:21 -0700676 set_ftr_sha(crypt_ftr);
Paul Lawrence3d99eba2015-11-20 07:07:19 -0800677
Paul Crowley14c8c072018-09-18 13:30:21 -0700678 if (get_crypt_ftr_info(&fname, &starting_off)) {
679 SLOGE("Unable to get crypt_ftr_info\n");
680 return -1;
Ken Sumralle8744072011-01-18 22:01:55 -0800681 }
Paul Crowley14c8c072018-09-18 13:30:21 -0700682 if (fname[0] != '/') {
683 SLOGE("Unexpected value for crypto key location\n");
684 return -1;
685 }
686 if ((fd = open(fname, O_RDWR | O_CREAT | O_CLOEXEC, 0600)) < 0) {
687 SLOGE("Cannot open footer file %s for put\n", fname);
688 return -1;
689 }
Ken Sumralle8744072011-01-18 22:01:55 -0800690
Paul Crowley14c8c072018-09-18 13:30:21 -0700691 /* Seek to the start of the crypt footer */
692 if (lseek64(fd, starting_off, SEEK_SET) == -1) {
693 SLOGE("Cannot seek to real block device footer\n");
694 goto errout;
695 }
696
697 if ((cnt = write(fd, crypt_ftr, sizeof(struct crypt_mnt_ftr))) != sizeof(struct crypt_mnt_ftr)) {
698 SLOGE("Cannot write real block device footer\n");
699 goto errout;
700 }
701
702 fstat(fd, &statbuf);
703 /* If the keys are kept on a raw block device, do not try to truncate it. */
704 if (S_ISREG(statbuf.st_mode)) {
705 if (ftruncate(fd, 0x4000)) {
706 SLOGE("Cannot set footer file size\n");
707 goto errout;
708 }
709 }
710
711 /* Success! */
712 rc = 0;
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800713
714errout:
Paul Crowley14c8c072018-09-18 13:30:21 -0700715 close(fd);
716 return rc;
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800717}
718
Paul Crowley14c8c072018-09-18 13:30:21 -0700719static bool check_ftr_sha(const struct crypt_mnt_ftr* crypt_ftr) {
Paul Lawrence3d99eba2015-11-20 07:07:19 -0800720 struct crypt_mnt_ftr copy;
721 memcpy(&copy, crypt_ftr, sizeof(copy));
722 set_ftr_sha(&copy);
723 return memcmp(copy.sha256, crypt_ftr->sha256, sizeof(copy.sha256)) == 0;
724}
725
Paul Crowley14c8c072018-09-18 13:30:21 -0700726static inline int unix_read(int fd, void* buff, int len) {
Ken Sumrall160b4d62013-04-22 12:15:39 -0700727 return TEMP_FAILURE_RETRY(read(fd, buff, len));
728}
729
Paul Crowley14c8c072018-09-18 13:30:21 -0700730static inline int unix_write(int fd, const void* buff, int len) {
Ken Sumrall160b4d62013-04-22 12:15:39 -0700731 return TEMP_FAILURE_RETRY(write(fd, buff, len));
732}
733
Paul Crowley14c8c072018-09-18 13:30:21 -0700734static void init_empty_persist_data(struct crypt_persist_data* pdata, int len) {
Ken Sumrall160b4d62013-04-22 12:15:39 -0700735 memset(pdata, 0, len);
736 pdata->persist_magic = PERSIST_DATA_MAGIC;
737 pdata->persist_valid_entries = 0;
738}
739
740/* A routine to update the passed in crypt_ftr to the lastest version.
741 * fd is open read/write on the device that holds the crypto footer and persistent
742 * data, crypt_ftr is a pointer to the struct to be updated, and offset is the
743 * absolute offset to the start of the crypt_mnt_ftr on the passed in fd.
744 */
Paul Crowley14c8c072018-09-18 13:30:21 -0700745static void upgrade_crypt_ftr(int fd, struct crypt_mnt_ftr* crypt_ftr, off64_t offset) {
Kenny Root7434b312013-06-14 11:29:53 -0700746 int orig_major = crypt_ftr->major_version;
747 int orig_minor = crypt_ftr->minor_version;
Ken Sumrall160b4d62013-04-22 12:15:39 -0700748
Kenny Root7434b312013-06-14 11:29:53 -0700749 if ((crypt_ftr->major_version == 1) && (crypt_ftr->minor_version == 0)) {
Paul Crowley14c8c072018-09-18 13:30:21 -0700750 struct crypt_persist_data* pdata;
Kenny Root7434b312013-06-14 11:29:53 -0700751 off64_t pdata_offset = offset + CRYPT_FOOTER_TO_PERSIST_OFFSET;
Ken Sumrall160b4d62013-04-22 12:15:39 -0700752
Kenny Rootc4c70f12013-06-14 12:11:38 -0700753 SLOGW("upgrading crypto footer to 1.1");
754
Paul Crowley14c8c072018-09-18 13:30:21 -0700755 pdata = (crypt_persist_data*)malloc(CRYPT_PERSIST_DATA_SIZE);
Kenny Root7434b312013-06-14 11:29:53 -0700756 if (pdata == NULL) {
757 SLOGE("Cannot allocate persisent data\n");
758 return;
759 }
760 memset(pdata, 0, CRYPT_PERSIST_DATA_SIZE);
761
762 /* Need to initialize the persistent data area */
763 if (lseek64(fd, pdata_offset, SEEK_SET) == -1) {
764 SLOGE("Cannot seek to persisent data offset\n");
Henrik Baard91064632015-02-05 15:09:17 +0100765 free(pdata);
Kenny Root7434b312013-06-14 11:29:53 -0700766 return;
767 }
768 /* Write all zeros to the first copy, making it invalid */
769 unix_write(fd, pdata, CRYPT_PERSIST_DATA_SIZE);
770
771 /* Write a valid but empty structure to the second copy */
772 init_empty_persist_data(pdata, CRYPT_PERSIST_DATA_SIZE);
773 unix_write(fd, pdata, CRYPT_PERSIST_DATA_SIZE);
774
775 /* Update the footer */
776 crypt_ftr->persist_data_size = CRYPT_PERSIST_DATA_SIZE;
777 crypt_ftr->persist_data_offset[0] = pdata_offset;
778 crypt_ftr->persist_data_offset[1] = pdata_offset + CRYPT_PERSIST_DATA_SIZE;
779 crypt_ftr->minor_version = 1;
Henrik Baard91064632015-02-05 15:09:17 +0100780 free(pdata);
Ken Sumrall160b4d62013-04-22 12:15:39 -0700781 }
782
Paul Lawrencef4faa572014-01-29 13:31:03 -0800783 if ((crypt_ftr->major_version == 1) && (crypt_ftr->minor_version == 1)) {
Kenny Rootc4c70f12013-06-14 12:11:38 -0700784 SLOGW("upgrading crypto footer to 1.2");
JP Abgrall7bdfa522013-11-15 13:42:56 -0800785 /* But keep the old kdf_type.
786 * It will get updated later to KDF_SCRYPT after the password has been verified.
787 */
Kenny Rootc4c70f12013-06-14 12:11:38 -0700788 crypt_ftr->kdf_type = KDF_PBKDF2;
789 get_device_scrypt_params(crypt_ftr);
790 crypt_ftr->minor_version = 2;
791 }
792
Paul Lawrencef4faa572014-01-29 13:31:03 -0800793 if ((crypt_ftr->major_version == 1) && (crypt_ftr->minor_version == 2)) {
794 SLOGW("upgrading crypto footer to 1.3");
795 crypt_ftr->crypt_type = CRYPT_TYPE_PASSWORD;
796 crypt_ftr->minor_version = 3;
797 }
798
Kenny Root7434b312013-06-14 11:29:53 -0700799 if ((orig_major != crypt_ftr->major_version) || (orig_minor != crypt_ftr->minor_version)) {
800 if (lseek64(fd, offset, SEEK_SET) == -1) {
801 SLOGE("Cannot seek to crypt footer\n");
802 return;
803 }
804 unix_write(fd, crypt_ftr, sizeof(struct crypt_mnt_ftr));
Ken Sumrall160b4d62013-04-22 12:15:39 -0700805 }
Ken Sumrall160b4d62013-04-22 12:15:39 -0700806}
807
Paul Crowley14c8c072018-09-18 13:30:21 -0700808static int get_crypt_ftr_and_key(struct crypt_mnt_ftr* crypt_ftr) {
809 int fd;
810 unsigned int cnt;
811 off64_t starting_off;
812 int rc = -1;
813 char* fname = NULL;
814 struct stat statbuf;
Ken Sumrall160b4d62013-04-22 12:15:39 -0700815
Paul Crowley14c8c072018-09-18 13:30:21 -0700816 if (get_crypt_ftr_info(&fname, &starting_off)) {
817 SLOGE("Unable to get crypt_ftr_info\n");
818 return -1;
819 }
820 if (fname[0] != '/') {
821 SLOGE("Unexpected value for crypto key location\n");
822 return -1;
823 }
824 if ((fd = open(fname, O_RDWR | O_CLOEXEC)) < 0) {
825 SLOGE("Cannot open footer file %s for get\n", fname);
826 return -1;
827 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800828
Paul Crowley14c8c072018-09-18 13:30:21 -0700829 /* Make sure it's 16 Kbytes in length */
830 fstat(fd, &statbuf);
831 if (S_ISREG(statbuf.st_mode) && (statbuf.st_size != 0x4000)) {
832 SLOGE("footer file %s is not the expected size!\n", fname);
833 goto errout;
834 }
Ken Sumrall160b4d62013-04-22 12:15:39 -0700835
Paul Crowley14c8c072018-09-18 13:30:21 -0700836 /* Seek to the start of the crypt footer */
837 if (lseek64(fd, starting_off, SEEK_SET) == -1) {
838 SLOGE("Cannot seek to real block device footer\n");
839 goto errout;
840 }
Ken Sumrall160b4d62013-04-22 12:15:39 -0700841
Paul Crowley14c8c072018-09-18 13:30:21 -0700842 if ((cnt = read(fd, crypt_ftr, sizeof(struct crypt_mnt_ftr))) != sizeof(struct crypt_mnt_ftr)) {
843 SLOGE("Cannot read real block device footer\n");
844 goto errout;
845 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800846
Paul Crowley14c8c072018-09-18 13:30:21 -0700847 if (crypt_ftr->magic != CRYPT_MNT_MAGIC) {
848 SLOGE("Bad magic for real block device %s\n", fname);
849 goto errout;
850 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800851
Paul Crowley14c8c072018-09-18 13:30:21 -0700852 if (crypt_ftr->major_version != CURRENT_MAJOR_VERSION) {
853 SLOGE("Cannot understand major version %d real block device footer; expected %d\n",
854 crypt_ftr->major_version, CURRENT_MAJOR_VERSION);
855 goto errout;
856 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800857
Paul Crowley14c8c072018-09-18 13:30:21 -0700858 // We risk buffer overflows with oversized keys, so we just reject them.
859 // 0-sized keys are problematic (essentially by-passing encryption), and
860 // AES-CBC key wrapping only works for multiples of 16 bytes.
861 if ((crypt_ftr->keysize == 0) || ((crypt_ftr->keysize % 16) != 0) ||
862 (crypt_ftr->keysize > MAX_KEY_LEN)) {
863 SLOGE(
864 "Invalid keysize (%u) for block device %s; Must be non-zero, "
865 "divisible by 16, and <= %d\n",
866 crypt_ftr->keysize, fname, MAX_KEY_LEN);
867 goto errout;
868 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800869
Paul Crowley14c8c072018-09-18 13:30:21 -0700870 if (crypt_ftr->minor_version > CURRENT_MINOR_VERSION) {
871 SLOGW("Warning: crypto footer minor version %d, expected <= %d, continuing...\n",
872 crypt_ftr->minor_version, CURRENT_MINOR_VERSION);
873 }
Greg Kaiser59ad0182018-02-16 13:01:36 -0800874
Paul Crowley14c8c072018-09-18 13:30:21 -0700875 /* If this is a verion 1.0 crypt_ftr, make it a 1.1 crypt footer, and update the
876 * copy on disk before returning.
877 */
878 if (crypt_ftr->minor_version < CURRENT_MINOR_VERSION) {
879 upgrade_crypt_ftr(fd, crypt_ftr, starting_off);
880 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800881
Paul Crowley14c8c072018-09-18 13:30:21 -0700882 /* Success! */
883 rc = 0;
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800884
885errout:
Paul Crowley14c8c072018-09-18 13:30:21 -0700886 close(fd);
887 return rc;
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800888}
889
Paul Crowley14c8c072018-09-18 13:30:21 -0700890static int validate_persistent_data_storage(struct crypt_mnt_ftr* crypt_ftr) {
Ken Sumrall160b4d62013-04-22 12:15:39 -0700891 if (crypt_ftr->persist_data_offset[0] + crypt_ftr->persist_data_size >
892 crypt_ftr->persist_data_offset[1]) {
893 SLOGE("Crypt_ftr persist data regions overlap");
894 return -1;
895 }
896
897 if (crypt_ftr->persist_data_offset[0] >= crypt_ftr->persist_data_offset[1]) {
898 SLOGE("Crypt_ftr persist data region 0 starts after region 1");
899 return -1;
900 }
901
902 if (((crypt_ftr->persist_data_offset[1] + crypt_ftr->persist_data_size) -
Paul Crowley14c8c072018-09-18 13:30:21 -0700903 (crypt_ftr->persist_data_offset[0] - CRYPT_FOOTER_TO_PERSIST_OFFSET)) >
Ken Sumrall160b4d62013-04-22 12:15:39 -0700904 CRYPT_FOOTER_OFFSET) {
905 SLOGE("Persistent data extends past crypto footer");
906 return -1;
907 }
908
909 return 0;
910}
911
Paul Crowley14c8c072018-09-18 13:30:21 -0700912static int load_persistent_data(void) {
Ken Sumrall160b4d62013-04-22 12:15:39 -0700913 struct crypt_mnt_ftr crypt_ftr;
Paul Crowley14c8c072018-09-18 13:30:21 -0700914 struct crypt_persist_data* pdata = NULL;
Ken Sumrall160b4d62013-04-22 12:15:39 -0700915 char encrypted_state[PROPERTY_VALUE_MAX];
Paul Crowley14c8c072018-09-18 13:30:21 -0700916 char* fname;
Ken Sumrall160b4d62013-04-22 12:15:39 -0700917 int found = 0;
918 int fd;
919 int ret;
920 int i;
921
922 if (persist_data) {
923 /* Nothing to do, we've already loaded or initialized it */
924 return 0;
925 }
926
Ken Sumrall160b4d62013-04-22 12:15:39 -0700927 /* If not encrypted, just allocate an empty table and initialize it */
928 property_get("ro.crypto.state", encrypted_state, "");
Paul Crowley14c8c072018-09-18 13:30:21 -0700929 if (strcmp(encrypted_state, "encrypted")) {
Wei Wang4375f1b2017-02-24 17:43:01 -0800930 pdata = (crypt_persist_data*)malloc(CRYPT_PERSIST_DATA_SIZE);
Ken Sumrall160b4d62013-04-22 12:15:39 -0700931 if (pdata) {
932 init_empty_persist_data(pdata, CRYPT_PERSIST_DATA_SIZE);
933 persist_data = pdata;
934 return 0;
935 }
936 return -1;
937 }
938
Paul Crowley14c8c072018-09-18 13:30:21 -0700939 if (get_crypt_ftr_and_key(&crypt_ftr)) {
Ken Sumrall160b4d62013-04-22 12:15:39 -0700940 return -1;
941 }
942
Paul Crowley14c8c072018-09-18 13:30:21 -0700943 if ((crypt_ftr.major_version < 1) ||
944 (crypt_ftr.major_version == 1 && crypt_ftr.minor_version < 1)) {
Ken Sumrall160b4d62013-04-22 12:15:39 -0700945 SLOGE("Crypt_ftr version doesn't support persistent data");
946 return -1;
947 }
948
949 if (get_crypt_ftr_info(&fname, NULL)) {
950 return -1;
951 }
952
953 ret = validate_persistent_data_storage(&crypt_ftr);
954 if (ret) {
955 return -1;
956 }
957
Paul Crowley14c8c072018-09-18 13:30:21 -0700958 fd = open(fname, O_RDONLY | O_CLOEXEC);
Ken Sumrall160b4d62013-04-22 12:15:39 -0700959 if (fd < 0) {
960 SLOGE("Cannot open %s metadata file", fname);
961 return -1;
962 }
963
Wei Wang4375f1b2017-02-24 17:43:01 -0800964 pdata = (crypt_persist_data*)malloc(crypt_ftr.persist_data_size);
Paul Lawrence300dae72016-03-11 11:02:52 -0800965 if (pdata == NULL) {
966 SLOGE("Cannot allocate memory for persistent data");
967 goto err;
Ken Sumrall160b4d62013-04-22 12:15:39 -0700968 }
969
970 for (i = 0; i < 2; i++) {
971 if (lseek64(fd, crypt_ftr.persist_data_offset[i], SEEK_SET) < 0) {
972 SLOGE("Cannot seek to read persistent data on %s", fname);
973 goto err2;
974 }
Paul Crowley14c8c072018-09-18 13:30:21 -0700975 if (unix_read(fd, pdata, crypt_ftr.persist_data_size) < 0) {
Ken Sumrall160b4d62013-04-22 12:15:39 -0700976 SLOGE("Error reading persistent data on iteration %d", i);
977 goto err2;
978 }
979 if (pdata->persist_magic == PERSIST_DATA_MAGIC) {
980 found = 1;
981 break;
982 }
983 }
984
985 if (!found) {
986 SLOGI("Could not find valid persistent data, creating");
987 init_empty_persist_data(pdata, crypt_ftr.persist_data_size);
988 }
989
990 /* Success */
991 persist_data = pdata;
992 close(fd);
993 return 0;
994
995err2:
996 free(pdata);
997
998err:
999 close(fd);
1000 return -1;
1001}
1002
Paul Crowley14c8c072018-09-18 13:30:21 -07001003static int save_persistent_data(void) {
Ken Sumrall160b4d62013-04-22 12:15:39 -07001004 struct crypt_mnt_ftr crypt_ftr;
Paul Crowley14c8c072018-09-18 13:30:21 -07001005 struct crypt_persist_data* pdata;
1006 char* fname;
Ken Sumrall160b4d62013-04-22 12:15:39 -07001007 off64_t write_offset;
1008 off64_t erase_offset;
Ken Sumrall160b4d62013-04-22 12:15:39 -07001009 int fd;
1010 int ret;
1011
1012 if (persist_data == NULL) {
1013 SLOGE("No persistent data to save");
1014 return -1;
1015 }
1016
Paul Crowley14c8c072018-09-18 13:30:21 -07001017 if (get_crypt_ftr_and_key(&crypt_ftr)) {
Ken Sumrall160b4d62013-04-22 12:15:39 -07001018 return -1;
1019 }
1020
Paul Crowley14c8c072018-09-18 13:30:21 -07001021 if ((crypt_ftr.major_version < 1) ||
1022 (crypt_ftr.major_version == 1 && crypt_ftr.minor_version < 1)) {
Ken Sumrall160b4d62013-04-22 12:15:39 -07001023 SLOGE("Crypt_ftr version doesn't support persistent data");
1024 return -1;
1025 }
1026
1027 ret = validate_persistent_data_storage(&crypt_ftr);
1028 if (ret) {
1029 return -1;
1030 }
1031
1032 if (get_crypt_ftr_info(&fname, NULL)) {
1033 return -1;
1034 }
1035
Paul Crowley14c8c072018-09-18 13:30:21 -07001036 fd = open(fname, O_RDWR | O_CLOEXEC);
Ken Sumrall160b4d62013-04-22 12:15:39 -07001037 if (fd < 0) {
1038 SLOGE("Cannot open %s metadata file", fname);
1039 return -1;
1040 }
1041
Wei Wang4375f1b2017-02-24 17:43:01 -08001042 pdata = (crypt_persist_data*)malloc(crypt_ftr.persist_data_size);
Ken Sumrall160b4d62013-04-22 12:15:39 -07001043 if (pdata == NULL) {
1044 SLOGE("Cannot allocate persistant data");
1045 goto err;
1046 }
1047
1048 if (lseek64(fd, crypt_ftr.persist_data_offset[0], SEEK_SET) < 0) {
1049 SLOGE("Cannot seek to read persistent data on %s", fname);
1050 goto err2;
1051 }
1052
1053 if (unix_read(fd, pdata, crypt_ftr.persist_data_size) < 0) {
Paul Crowley14c8c072018-09-18 13:30:21 -07001054 SLOGE("Error reading persistent data before save");
1055 goto err2;
Ken Sumrall160b4d62013-04-22 12:15:39 -07001056 }
1057
1058 if (pdata->persist_magic == PERSIST_DATA_MAGIC) {
1059 /* The first copy is the curent valid copy, so write to
1060 * the second copy and erase this one */
Paul Crowley14c8c072018-09-18 13:30:21 -07001061 write_offset = crypt_ftr.persist_data_offset[1];
1062 erase_offset = crypt_ftr.persist_data_offset[0];
Ken Sumrall160b4d62013-04-22 12:15:39 -07001063 } else {
1064 /* The second copy must be the valid copy, so write to
1065 * the first copy, and erase the second */
Paul Crowley14c8c072018-09-18 13:30:21 -07001066 write_offset = crypt_ftr.persist_data_offset[0];
1067 erase_offset = crypt_ftr.persist_data_offset[1];
Ken Sumrall160b4d62013-04-22 12:15:39 -07001068 }
1069
1070 /* Write the new copy first, if successful, then erase the old copy */
Björn Landström96dbee72015-01-20 12:43:56 +01001071 if (lseek64(fd, write_offset, SEEK_SET) < 0) {
Ken Sumrall160b4d62013-04-22 12:15:39 -07001072 SLOGE("Cannot seek to write persistent data");
1073 goto err2;
1074 }
1075 if (unix_write(fd, persist_data, crypt_ftr.persist_data_size) ==
Paul Crowley14c8c072018-09-18 13:30:21 -07001076 (int)crypt_ftr.persist_data_size) {
Björn Landström96dbee72015-01-20 12:43:56 +01001077 if (lseek64(fd, erase_offset, SEEK_SET) < 0) {
Ken Sumrall160b4d62013-04-22 12:15:39 -07001078 SLOGE("Cannot seek to erase previous persistent data");
1079 goto err2;
1080 }
1081 fsync(fd);
1082 memset(pdata, 0, crypt_ftr.persist_data_size);
Paul Crowley14c8c072018-09-18 13:30:21 -07001083 if (unix_write(fd, pdata, crypt_ftr.persist_data_size) != (int)crypt_ftr.persist_data_size) {
Ken Sumrall160b4d62013-04-22 12:15:39 -07001084 SLOGE("Cannot write to erase previous persistent data");
1085 goto err2;
1086 }
1087 fsync(fd);
1088 } else {
1089 SLOGE("Cannot write to save persistent data");
1090 goto err2;
1091 }
1092
1093 /* Success */
1094 free(pdata);
1095 close(fd);
1096 return 0;
1097
1098err2:
1099 free(pdata);
1100err:
1101 close(fd);
1102 return -1;
1103}
1104
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001105/* Convert a binary key of specified length into an ascii hex string equivalent,
1106 * without the leading 0x and with null termination
1107 */
Paul Crowley14c8c072018-09-18 13:30:21 -07001108static void convert_key_to_hex_ascii(const unsigned char* master_key, unsigned int keysize,
1109 char* master_key_ascii) {
Paul Lawrence3bd36d52015-06-09 13:37:44 -07001110 unsigned int i, a;
1111 unsigned char nibble;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001112
Paul Crowley14c8c072018-09-18 13:30:21 -07001113 for (i = 0, a = 0; i < keysize; i++, a += 2) {
Paul Lawrence3bd36d52015-06-09 13:37:44 -07001114 /* For each byte, write out two ascii hex digits */
1115 nibble = (master_key[i] >> 4) & 0xf;
1116 master_key_ascii[a] = nibble + (nibble > 9 ? 0x37 : 0x30);
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001117
Paul Lawrence3bd36d52015-06-09 13:37:44 -07001118 nibble = master_key[i] & 0xf;
Paul Crowley14c8c072018-09-18 13:30:21 -07001119 master_key_ascii[a + 1] = nibble + (nibble > 9 ? 0x37 : 0x30);
Paul Lawrence3bd36d52015-06-09 13:37:44 -07001120 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001121
Paul Lawrence3bd36d52015-06-09 13:37:44 -07001122 /* Add the null termination */
1123 master_key_ascii[a] = '\0';
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001124}
1125
Paul Crowley14c8c072018-09-18 13:30:21 -07001126static int load_crypto_mapping_table(struct crypt_mnt_ftr* crypt_ftr,
1127 const unsigned char* master_key, const char* real_blk_name,
1128 const char* name, int fd, const char* extra_params) {
1129 alignas(struct dm_ioctl) char buffer[DM_CRYPT_BUF_SIZE];
1130 struct dm_ioctl* io;
1131 struct dm_target_spec* tgt;
1132 char* crypt_params;
1133 // We need two ASCII characters to represent each byte, and need space for
1134 // the '\0' terminator.
1135 char master_key_ascii[MAX_KEY_LEN * 2 + 1];
1136 size_t buff_offset;
1137 int i;
Ken Sumralldb5e0262013-02-05 17:39:48 -08001138
Paul Crowley14c8c072018-09-18 13:30:21 -07001139 io = (struct dm_ioctl*)buffer;
Ken Sumralldb5e0262013-02-05 17:39:48 -08001140
Paul Crowley14c8c072018-09-18 13:30:21 -07001141 /* Load the mapping table for this device */
1142 tgt = (struct dm_target_spec*)&buffer[sizeof(struct dm_ioctl)];
Ken Sumralldb5e0262013-02-05 17:39:48 -08001143
Paul Crowley14c8c072018-09-18 13:30:21 -07001144 ioctl_init(io, DM_CRYPT_BUF_SIZE, name, 0);
1145 io->target_count = 1;
1146 tgt->status = 0;
1147 tgt->sector_start = 0;
1148 tgt->length = crypt_ftr->fs_size;
Paul Crowley14c8c072018-09-18 13:30:21 -07001149 crypt_params = buffer + sizeof(struct dm_ioctl) + sizeof(struct dm_target_spec);
Paul Crowley14c8c072018-09-18 13:30:21 -07001150 buff_offset = crypt_params - buffer;
Eric Biggerse1a7e772019-01-25 12:11:25 -08001151 SLOGI(
1152 "Creating crypto dev \"%s\"; cipher=%s, keysize=%u, real_dev=%s, len=%llu, params=\"%s\"\n",
1153 name, crypt_ftr->crypto_type_name, crypt_ftr->keysize, real_blk_name, tgt->length * 512,
1154 extra_params);
AnilKumar Chimata98dc8352018-05-11 00:25:09 +05301155#ifdef CONFIG_HW_DISK_ENCRYPTION
Bill Peckham0db11972018-10-10 10:25:42 -07001156 if(is_hw_disk_encryption((char*)crypt_ftr->crypto_type_name)) {
1157 strlcpy(tgt->target_type, "req-crypt",DM_MAX_TYPE_NAME);
1158 if (is_ice_enabled())
1159 convert_key_to_hex_ascii(master_key, sizeof(int), master_key_ascii);
1160 else
1161 convert_key_to_hex_ascii(master_key, crypt_ftr->keysize, master_key_ascii);
1162 }
1163 else {
1164 convert_key_to_hex_ascii(master_key, crypt_ftr->keysize, master_key_ascii);
1165 strlcpy(tgt->target_type, "crypt", DM_MAX_TYPE_NAME);
1166 }
1167 snprintf(crypt_params, sizeof(buffer) - buff_offset, "%s %s 0 %s 0 %s 0",
1168 crypt_ftr->crypto_type_name, master_key_ascii,
1169 real_blk_name, extra_params);
1170
1171 SLOGI("target_type = %s", tgt->target_type);
1172 SLOGI("real_blk_name = %s, extra_params = %s", real_blk_name, extra_params);
1173#else
AnilKumar Chimata98dc8352018-05-11 00:25:09 +05301174 convert_key_to_hex_ascii(master_key, crypt_ftr->keysize, master_key_ascii);
1175 strlcpy(tgt->target_type, "crypt", DM_MAX_TYPE_NAME);
Paul Crowley14c8c072018-09-18 13:30:21 -07001176 snprintf(crypt_params, sizeof(buffer) - buff_offset, "%s %s 0 %s 0 %s",
1177 crypt_ftr->crypto_type_name, master_key_ascii, real_blk_name, extra_params);
AnilKumar Chimata98dc8352018-05-11 00:25:09 +05301178#endif
1179
Paul Crowley14c8c072018-09-18 13:30:21 -07001180 crypt_params += strlen(crypt_params) + 1;
1181 crypt_params =
1182 (char*)(((unsigned long)crypt_params + 7) & ~8); /* Align to an 8 byte boundary */
1183 tgt->next = crypt_params - buffer;
Ken Sumralldb5e0262013-02-05 17:39:48 -08001184
Paul Crowley14c8c072018-09-18 13:30:21 -07001185 for (i = 0; i < TABLE_LOAD_RETRIES; i++) {
1186 if (!ioctl(fd, DM_TABLE_LOAD, io)) {
1187 break;
1188 }
1189 usleep(500000);
Ken Sumralldb5e0262013-02-05 17:39:48 -08001190 }
Ken Sumralldb5e0262013-02-05 17:39:48 -08001191
Paul Crowley14c8c072018-09-18 13:30:21 -07001192 if (i == TABLE_LOAD_RETRIES) {
1193 /* We failed to load the table, return an error */
1194 return -1;
1195 } else {
1196 return i + 1;
1197 }
Ken Sumralldb5e0262013-02-05 17:39:48 -08001198}
1199
Paul Crowley14c8c072018-09-18 13:30:21 -07001200static int get_dm_crypt_version(int fd, const char* name, int* version) {
Ken Sumralldb5e0262013-02-05 17:39:48 -08001201 char buffer[DM_CRYPT_BUF_SIZE];
Paul Crowley14c8c072018-09-18 13:30:21 -07001202 struct dm_ioctl* io;
1203 struct dm_target_versions* v;
Ken Sumralldb5e0262013-02-05 17:39:48 -08001204
Paul Crowley14c8c072018-09-18 13:30:21 -07001205 io = (struct dm_ioctl*)buffer;
Ken Sumralldb5e0262013-02-05 17:39:48 -08001206
1207 ioctl_init(io, DM_CRYPT_BUF_SIZE, name, 0);
1208
1209 if (ioctl(fd, DM_LIST_VERSIONS, io)) {
1210 return -1;
1211 }
1212
1213 /* Iterate over the returned versions, looking for name of "crypt".
1214 * When found, get and return the version.
1215 */
Paul Crowley14c8c072018-09-18 13:30:21 -07001216 v = (struct dm_target_versions*)&buffer[sizeof(struct dm_ioctl)];
Ken Sumralldb5e0262013-02-05 17:39:48 -08001217 while (v->next) {
AnilKumar Chimata98dc8352018-05-11 00:25:09 +05301218#ifdef CONFIG_HW_DISK_ENCRYPTION
Bill Peckham0db11972018-10-10 10:25:42 -07001219 if (!strcmp(v->name, "crypt") || !strcmp(v->name, "req-crypt")) {
AnilKumar Chimata98dc8352018-05-11 00:25:09 +05301220#else
Paul Crowley14c8c072018-09-18 13:30:21 -07001221 if (!strcmp(v->name, "crypt")) {
AnilKumar Chimata98dc8352018-05-11 00:25:09 +05301222#endif
Ken Sumralldb5e0262013-02-05 17:39:48 -08001223 /* We found the crypt driver, return the version, and get out */
1224 version[0] = v->version[0];
1225 version[1] = v->version[1];
1226 version[2] = v->version[2];
1227 return 0;
1228 }
Paul Crowley14c8c072018-09-18 13:30:21 -07001229 v = (struct dm_target_versions*)(((char*)v) + v->next);
Ken Sumralldb5e0262013-02-05 17:39:48 -08001230 }
1231
1232 return -1;
1233}
1234
AnilKumar Chimata98dc8352018-05-11 00:25:09 +05301235#ifndef CONFIG_HW_DISK_ENCRYPTION
Paul Crowley5afbc622017-11-27 09:42:17 -08001236static std::string extra_params_as_string(const std::vector<std::string>& extra_params_vec) {
1237 if (extra_params_vec.empty()) return "";
1238 std::string extra_params = std::to_string(extra_params_vec.size());
1239 for (const auto& p : extra_params_vec) {
1240 extra_params.append(" ");
1241 extra_params.append(p);
1242 }
1243 return extra_params;
1244}
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001245
Eric Biggersed45ec32019-01-25 10:47:55 -08001246/*
1247 * If the ro.crypto.fde_sector_size system property is set, append the
1248 * parameters to make dm-crypt use the specified crypto sector size and round
1249 * the crypto device size down to a crypto sector boundary.
1250 */
1251static int add_sector_size_param(std::vector<std::string>* extra_params_vec,
1252 struct crypt_mnt_ftr* ftr) {
Greg Kaiserab1e84a2018-12-11 12:40:51 -08001253 constexpr char DM_CRYPT_SECTOR_SIZE[] = "ro.crypto.fde_sector_size";
Eric Biggersed45ec32019-01-25 10:47:55 -08001254 char value[PROPERTY_VALUE_MAX];
Greg Kaiserab1e84a2018-12-11 12:40:51 -08001255
Eric Biggersed45ec32019-01-25 10:47:55 -08001256 if (property_get(DM_CRYPT_SECTOR_SIZE, value, "") > 0) {
1257 unsigned int sector_size;
1258
1259 if (!ParseUint(value, &sector_size) || sector_size < 512 || sector_size > 4096 ||
1260 (sector_size & (sector_size - 1)) != 0) {
1261 SLOGE("Invalid value for %s: %s. Must be >= 512, <= 4096, and a power of 2\n",
1262 DM_CRYPT_SECTOR_SIZE, value);
1263 return -1;
1264 }
1265
1266 std::string param = StringPrintf("sector_size:%u", sector_size);
Greg Kaiserab1e84a2018-12-11 12:40:51 -08001267 extra_params_vec->push_back(std::move(param));
1268
1269 // With this option, IVs will match the sector numbering, instead
1270 // of being hard-coded to being based on 512-byte sectors.
1271 extra_params_vec->emplace_back("iv_large_sectors");
Eric Biggersed45ec32019-01-25 10:47:55 -08001272
1273 // Round the crypto device size down to a crypto sector boundary.
1274 ftr->fs_size &= ~((sector_size / 512) - 1);
Greg Kaiserab1e84a2018-12-11 12:40:51 -08001275 }
Eric Biggersed45ec32019-01-25 10:47:55 -08001276 return 0;
Greg Kaiserab1e84a2018-12-11 12:40:51 -08001277}
Steven Laverec1b6bc2019-01-15 11:03:32 -08001278#endif
Greg Kaiserab1e84a2018-12-11 12:40:51 -08001279
Paul Crowley5afbc622017-11-27 09:42:17 -08001280static int create_crypto_blk_dev(struct crypt_mnt_ftr* crypt_ftr, const unsigned char* master_key,
1281 const char* real_blk_name, char* crypto_blk_name, const char* name,
1282 uint32_t flags) {
1283 char buffer[DM_CRYPT_BUF_SIZE];
1284 struct dm_ioctl* io;
1285 unsigned int minor;
1286 int fd = 0;
1287 int err;
1288 int retval = -1;
1289 int version[3];
1290 int load_count;
AnilKumar Chimata98dc8352018-05-11 00:25:09 +05301291#ifdef CONFIG_HW_DISK_ENCRYPTION
1292 char encrypted_state[PROPERTY_VALUE_MAX] = {0};
1293 char progress[PROPERTY_VALUE_MAX] = {0};
1294 const char *extra_params;
1295#else
Paul Crowley5afbc622017-11-27 09:42:17 -08001296 std::vector<std::string> extra_params_vec;
AnilKumar Chimata98dc8352018-05-11 00:25:09 +05301297#endif
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001298
Paul Crowley5afbc622017-11-27 09:42:17 -08001299 if ((fd = open("/dev/device-mapper", O_RDWR | O_CLOEXEC)) < 0) {
1300 SLOGE("Cannot open device-mapper\n");
1301 goto errout;
1302 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001303
Paul Crowley5afbc622017-11-27 09:42:17 -08001304 io = (struct dm_ioctl*)buffer;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001305
Paul Crowley5afbc622017-11-27 09:42:17 -08001306 ioctl_init(io, DM_CRYPT_BUF_SIZE, name, 0);
1307 err = ioctl(fd, DM_DEV_CREATE, io);
1308 if (err) {
1309 SLOGE("Cannot create dm-crypt device %s: %s\n", name, strerror(errno));
1310 goto errout;
1311 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001312
Paul Crowley5afbc622017-11-27 09:42:17 -08001313 /* Get the device status, in particular, the name of it's device file */
1314 ioctl_init(io, DM_CRYPT_BUF_SIZE, name, 0);
1315 if (ioctl(fd, DM_DEV_STATUS, io)) {
1316 SLOGE("Cannot retrieve dm-crypt device status\n");
1317 goto errout;
1318 }
1319 minor = (io->dev & 0xff) | ((io->dev >> 12) & 0xfff00);
1320 snprintf(crypto_blk_name, MAXPATHLEN, "/dev/block/dm-%u", minor);
Ken Sumralle919efe2012-09-29 17:07:41 -07001321
AnilKumar Chimata98dc8352018-05-11 00:25:09 +05301322#ifdef CONFIG_HW_DISK_ENCRYPTION
1323 if(is_hw_disk_encryption((char*)crypt_ftr->crypto_type_name)) {
1324 /* Set fde_enabled if either FDE completed or in-progress */
1325 property_get("ro.crypto.state", encrypted_state, ""); /* FDE completed */
1326 property_get("vold.encrypt_progress", progress, ""); /* FDE in progress */
1327 if (!strcmp(encrypted_state, "encrypted") || strcmp(progress, "")) {
1328 if (is_ice_enabled()) {
1329 if (flags & CREATE_CRYPTO_BLK_DEV_FLAGS_ALLOW_ENCRYPT_OVERRIDE)
1330 extra_params = "fde_enabled ice allow_encrypt_override";
1331 else
1332 extra_params = "fde_enabled ice";
1333 } else {
1334 if (flags & CREATE_CRYPTO_BLK_DEV_FLAGS_ALLOW_ENCRYPT_OVERRIDE)
1335 extra_params = "fde_enabled allow_encrypt_override";
1336 else
1337 extra_params = "fde_enabled";
1338 }
1339 } else {
1340 if (flags & CREATE_CRYPTO_BLK_DEV_FLAGS_ALLOW_ENCRYPT_OVERRIDE)
1341 extra_params = "fde_enabled allow_encrypt_override";
1342 else
1343 extra_params = "fde_enabled";
1344 }
1345 } else {
1346 extra_params = "";
1347 if (! get_dm_crypt_version(fd, name, version)) {
1348 /* Support for allow_discards was added in version 1.11.0 */
1349 if ((version[0] >= 2) || ((version[0] == 1) && (version[1] >= 11))) {
1350 if (flags & CREATE_CRYPTO_BLK_DEV_FLAGS_ALLOW_ENCRYPT_OVERRIDE)
1351 extra_params = "2 allow_discards allow_encrypt_override";
1352 else
1353 extra_params = "1 allow_discards";
1354 SLOGI("Enabling support for allow_discards in dmcrypt.\n");
1355 }
1356 }
1357 }
1358 load_count = load_crypto_mapping_table(crypt_ftr, master_key, real_blk_name, name, fd,
1359 extra_params);
1360#else
Paul Crowley5afbc622017-11-27 09:42:17 -08001361 if (!get_dm_crypt_version(fd, name, version)) {
1362 /* Support for allow_discards was added in version 1.11.0 */
1363 if ((version[0] >= 2) || ((version[0] == 1) && (version[1] >= 11))) {
1364 extra_params_vec.emplace_back("allow_discards");
1365 }
1366 }
1367 if (flags & CREATE_CRYPTO_BLK_DEV_FLAGS_ALLOW_ENCRYPT_OVERRIDE) {
1368 extra_params_vec.emplace_back("allow_encrypt_override");
1369 }
Eric Biggersed45ec32019-01-25 10:47:55 -08001370 if (add_sector_size_param(&extra_params_vec, crypt_ftr)) {
1371 SLOGE("Error processing dm-crypt sector size param\n");
1372 goto errout;
1373 }
Paul Crowley5afbc622017-11-27 09:42:17 -08001374 load_count = load_crypto_mapping_table(crypt_ftr, master_key, real_blk_name, name, fd,
1375 extra_params_as_string(extra_params_vec).c_str());
AnilKumar Chimata98dc8352018-05-11 00:25:09 +05301376#endif
Paul Crowley5afbc622017-11-27 09:42:17 -08001377 if (load_count < 0) {
1378 SLOGE("Cannot load dm-crypt mapping table.\n");
1379 goto errout;
1380 } else if (load_count > 1) {
1381 SLOGI("Took %d tries to load dmcrypt table.\n", load_count);
1382 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001383
Paul Crowley5afbc622017-11-27 09:42:17 -08001384 /* Resume this device to activate it */
1385 ioctl_init(io, DM_CRYPT_BUF_SIZE, name, 0);
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001386
Paul Crowley5afbc622017-11-27 09:42:17 -08001387 if (ioctl(fd, DM_DEV_SUSPEND, io)) {
1388 SLOGE("Cannot resume the dm-crypt device\n");
1389 goto errout;
1390 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001391
Paul Crowley298fa322018-10-30 15:59:24 -07001392 /* Ensure the dm device has been created before returning. */
1393 if (android::vold::WaitForFile(crypto_blk_name, 1s) < 0) {
1394 // WaitForFile generates a suitable log message
1395 goto errout;
1396 }
1397
Paul Crowley5afbc622017-11-27 09:42:17 -08001398 /* We made it here with no errors. Woot! */
1399 retval = 0;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001400
1401errout:
Paul Crowley14c8c072018-09-18 13:30:21 -07001402 close(fd); /* If fd is <0 from a failed open call, it's safe to just ignore the close error */
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001403
Paul Crowley14c8c072018-09-18 13:30:21 -07001404 return retval;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001405}
1406
Paul Crowley14c8c072018-09-18 13:30:21 -07001407static int delete_crypto_blk_dev(const char* name) {
1408 int fd;
1409 char buffer[DM_CRYPT_BUF_SIZE];
1410 struct dm_ioctl* io;
1411 int retval = -1;
Yue Hu9d6cc182018-12-17 17:09:55 +08001412 int err;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001413
Paul Crowley14c8c072018-09-18 13:30:21 -07001414 if ((fd = open("/dev/device-mapper", O_RDWR | O_CLOEXEC)) < 0) {
1415 SLOGE("Cannot open device-mapper\n");
1416 goto errout;
1417 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001418
Paul Crowley14c8c072018-09-18 13:30:21 -07001419 io = (struct dm_ioctl*)buffer;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001420
Paul Crowley14c8c072018-09-18 13:30:21 -07001421 ioctl_init(io, DM_CRYPT_BUF_SIZE, name, 0);
Yue Hu9d6cc182018-12-17 17:09:55 +08001422 err = ioctl(fd, DM_DEV_REMOVE, io);
1423 if (err) {
1424 SLOGE("Cannot remove dm-crypt device %s: %s\n", name, strerror(errno));
Paul Crowley14c8c072018-09-18 13:30:21 -07001425 goto errout;
1426 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001427
Paul Crowley14c8c072018-09-18 13:30:21 -07001428 /* We made it here with no errors. Woot! */
1429 retval = 0;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001430
1431errout:
Paul Crowley14c8c072018-09-18 13:30:21 -07001432 close(fd); /* If fd is <0 from a failed open call, it's safe to just ignore the close error */
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001433
Paul Crowley14c8c072018-09-18 13:30:21 -07001434 return retval;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001435}
1436
Paul Crowley14c8c072018-09-18 13:30:21 -07001437static int pbkdf2(const char* passwd, const unsigned char* salt, unsigned char* ikey,
1438 void* params UNUSED) {
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001439 SLOGI("Using pbkdf2 for cryptfs KDF");
1440
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001441 /* Turn the password into a key and IV that can decrypt the master key */
Paul Crowley14c8c072018-09-18 13:30:21 -07001442 return PKCS5_PBKDF2_HMAC_SHA1(passwd, strlen(passwd), salt, SALT_LEN, HASH_COUNT,
1443 INTERMEDIATE_BUF_SIZE, ikey) != 1;
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001444}
1445
Paul Crowley14c8c072018-09-18 13:30:21 -07001446static int scrypt(const char* passwd, const unsigned char* salt, unsigned char* ikey, void* params) {
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001447 SLOGI("Using scrypt for cryptfs KDF");
1448
Paul Crowley14c8c072018-09-18 13:30:21 -07001449 struct crypt_mnt_ftr* ftr = (struct crypt_mnt_ftr*)params;
Kenny Rootc4c70f12013-06-14 12:11:38 -07001450
1451 int N = 1 << ftr->N_factor;
1452 int r = 1 << ftr->r_factor;
1453 int p = 1 << ftr->p_factor;
1454
1455 /* Turn the password into a key and IV that can decrypt the master key */
Paul Crowley14c8c072018-09-18 13:30:21 -07001456 crypto_scrypt((const uint8_t*)passwd, strlen(passwd), salt, SALT_LEN, N, r, p, ikey,
Greg Kaiserc0de9c72018-02-14 20:05:54 -08001457 INTERMEDIATE_BUF_SIZE);
Paul Lawrencef4faa572014-01-29 13:31:03 -08001458
Paul Crowley14c8c072018-09-18 13:30:21 -07001459 return 0;
Kenny Rootc4c70f12013-06-14 12:11:38 -07001460}
1461
Paul Crowley14c8c072018-09-18 13:30:21 -07001462static int scrypt_keymaster(const char* passwd, const unsigned char* salt, unsigned char* ikey,
1463 void* params) {
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001464 SLOGI("Using scrypt with keymaster for cryptfs KDF");
1465
1466 int rc;
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001467 size_t signature_size;
1468 unsigned char* signature;
Paul Crowley14c8c072018-09-18 13:30:21 -07001469 struct crypt_mnt_ftr* ftr = (struct crypt_mnt_ftr*)params;
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001470
1471 int N = 1 << ftr->N_factor;
1472 int r = 1 << ftr->r_factor;
1473 int p = 1 << ftr->p_factor;
1474
Paul Crowley14c8c072018-09-18 13:30:21 -07001475 rc = crypto_scrypt((const uint8_t*)passwd, strlen(passwd), salt, SALT_LEN, N, r, p, ikey,
Greg Kaiserc0de9c72018-02-14 20:05:54 -08001476 INTERMEDIATE_BUF_SIZE);
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001477
1478 if (rc) {
1479 SLOGE("scrypt failed");
1480 return -1;
1481 }
1482
Paul Crowley14c8c072018-09-18 13:30:21 -07001483 if (keymaster_sign_object(ftr, ikey, INTERMEDIATE_BUF_SIZE, &signature, &signature_size)) {
Shawn Willdene17a9c42014-09-08 13:04:08 -06001484 SLOGE("Signing failed");
1485 return -1;
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001486 }
1487
Paul Crowley14c8c072018-09-18 13:30:21 -07001488 rc = crypto_scrypt(signature, signature_size, salt, SALT_LEN, N, r, p, ikey,
1489 INTERMEDIATE_BUF_SIZE);
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001490 free(signature);
1491
1492 if (rc) {
1493 SLOGE("scrypt failed");
1494 return -1;
1495 }
1496
1497 return 0;
1498}
1499
Paul Crowley14c8c072018-09-18 13:30:21 -07001500static int encrypt_master_key(const char* passwd, const unsigned char* salt,
1501 const unsigned char* decrypted_master_key,
Bill Peckham0db11972018-10-10 10:25:42 -07001502 unsigned char* encrypted_master_key, struct crypt_mnt_ftr* crypt_ftr,
1503 bool create_keymaster_key) {
Paul Crowley14c8c072018-09-18 13:30:21 -07001504 unsigned char ikey[INTERMEDIATE_BUF_SIZE] = {0};
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001505 EVP_CIPHER_CTX e_ctx;
1506 int encrypted_len, final_len;
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001507 int rc = 0;
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001508
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001509 /* Turn the password into an intermediate key and IV that can decrypt the master key */
Kenny Rootc4c70f12013-06-14 12:11:38 -07001510 get_device_scrypt_params(crypt_ftr);
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001511
1512 switch (crypt_ftr->kdf_type) {
Paul Crowley14c8c072018-09-18 13:30:21 -07001513 case KDF_SCRYPT_KEYMASTER:
Bill Peckham0db11972018-10-10 10:25:42 -07001514 if (create_keymaster_key && keymaster_create_key(crypt_ftr)) {
Paul Crowley14c8c072018-09-18 13:30:21 -07001515 SLOGE("keymaster_create_key failed");
1516 return -1;
1517 }
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001518
Paul Crowley14c8c072018-09-18 13:30:21 -07001519 if (scrypt_keymaster(passwd, salt, ikey, crypt_ftr)) {
1520 SLOGE("scrypt failed");
1521 return -1;
1522 }
1523 break;
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001524
Paul Crowley14c8c072018-09-18 13:30:21 -07001525 case KDF_SCRYPT:
1526 if (scrypt(passwd, salt, ikey, crypt_ftr)) {
1527 SLOGE("scrypt failed");
1528 return -1;
1529 }
1530 break;
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001531
Paul Crowley14c8c072018-09-18 13:30:21 -07001532 default:
1533 SLOGE("Invalid kdf_type");
1534 return -1;
Paul Lawrencef4faa572014-01-29 13:31:03 -08001535 }
Kenny Rootc4c70f12013-06-14 12:11:38 -07001536
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001537 /* Initialize the decryption engine */
Adam Langley889c4f12014-09-03 14:23:13 -07001538 EVP_CIPHER_CTX_init(&e_ctx);
Paul Crowley14c8c072018-09-18 13:30:21 -07001539 if (!EVP_EncryptInit_ex(&e_ctx, EVP_aes_128_cbc(), NULL, ikey,
1540 ikey + INTERMEDIATE_KEY_LEN_BYTES)) {
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001541 SLOGE("EVP_EncryptInit failed\n");
1542 return -1;
1543 }
1544 EVP_CIPHER_CTX_set_padding(&e_ctx, 0); /* Turn off padding as our data is block aligned */
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001545
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001546 /* Encrypt the master key */
Paul Crowley14c8c072018-09-18 13:30:21 -07001547 if (!EVP_EncryptUpdate(&e_ctx, encrypted_master_key, &encrypted_len, decrypted_master_key,
1548 crypt_ftr->keysize)) {
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001549 SLOGE("EVP_EncryptUpdate failed\n");
1550 return -1;
1551 }
Paul Crowley14c8c072018-09-18 13:30:21 -07001552 if (!EVP_EncryptFinal_ex(&e_ctx, encrypted_master_key + encrypted_len, &final_len)) {
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001553 SLOGE("EVP_EncryptFinal failed\n");
1554 return -1;
1555 }
1556
Greg Kaiser59ad0182018-02-16 13:01:36 -08001557 if (encrypted_len + final_len != static_cast<int>(crypt_ftr->keysize)) {
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001558 SLOGE("EVP_Encryption length check failed with %d, %d bytes\n", encrypted_len, final_len);
1559 return -1;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001560 }
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001561
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001562 /* Store the scrypt of the intermediate key, so we can validate if it's a
1563 password error or mount error when things go wrong.
1564 Note there's no need to check for errors, since if this is incorrect, we
1565 simply won't wipe userdata, which is the correct default behavior
1566 */
1567 int N = 1 << crypt_ftr->N_factor;
1568 int r = 1 << crypt_ftr->r_factor;
1569 int p = 1 << crypt_ftr->p_factor;
1570
Paul Crowley14c8c072018-09-18 13:30:21 -07001571 rc = crypto_scrypt(ikey, INTERMEDIATE_KEY_LEN_BYTES, crypt_ftr->salt, sizeof(crypt_ftr->salt),
1572 N, r, p, crypt_ftr->scrypted_intermediate_key,
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001573 sizeof(crypt_ftr->scrypted_intermediate_key));
1574
1575 if (rc) {
Paul Crowley14c8c072018-09-18 13:30:21 -07001576 SLOGE("encrypt_master_key: crypto_scrypt failed");
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001577 }
1578
Thurston Hou Yeen Dang06dc3112016-07-18 14:16:37 -07001579 EVP_CIPHER_CTX_cleanup(&e_ctx);
1580
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001581 return 0;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001582}
1583
Paul Crowley14c8c072018-09-18 13:30:21 -07001584static int decrypt_master_key_aux(const char* passwd, unsigned char* salt,
1585 const unsigned char* encrypted_master_key, size_t keysize,
1586 unsigned char* decrypted_master_key, kdf_func kdf,
1587 void* kdf_params, unsigned char** intermediate_key,
1588 size_t* intermediate_key_size) {
1589 unsigned char ikey[INTERMEDIATE_BUF_SIZE] = {0};
1590 EVP_CIPHER_CTX d_ctx;
1591 int decrypted_len, final_len;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001592
Paul Crowley14c8c072018-09-18 13:30:21 -07001593 /* Turn the password into an intermediate key and IV that can decrypt the
1594 master key */
1595 if (kdf(passwd, salt, ikey, kdf_params)) {
1596 SLOGE("kdf failed");
1597 return -1;
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001598 }
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001599
Paul Crowley14c8c072018-09-18 13:30:21 -07001600 /* Initialize the decryption engine */
1601 EVP_CIPHER_CTX_init(&d_ctx);
1602 if (!EVP_DecryptInit_ex(&d_ctx, EVP_aes_128_cbc(), NULL, ikey,
1603 ikey + INTERMEDIATE_KEY_LEN_BYTES)) {
1604 return -1;
1605 }
1606 EVP_CIPHER_CTX_set_padding(&d_ctx, 0); /* Turn off padding as our data is block aligned */
1607 /* Decrypt the master key */
1608 if (!EVP_DecryptUpdate(&d_ctx, decrypted_master_key, &decrypted_len, encrypted_master_key,
1609 keysize)) {
1610 return -1;
1611 }
1612 if (!EVP_DecryptFinal_ex(&d_ctx, decrypted_master_key + decrypted_len, &final_len)) {
1613 return -1;
1614 }
Thurston Hou Yeen Dang06dc3112016-07-18 14:16:37 -07001615
Paul Crowley14c8c072018-09-18 13:30:21 -07001616 if (decrypted_len + final_len != static_cast<int>(keysize)) {
1617 return -1;
1618 }
1619
1620 /* Copy intermediate key if needed by params */
1621 if (intermediate_key && intermediate_key_size) {
1622 *intermediate_key = (unsigned char*)malloc(INTERMEDIATE_KEY_LEN_BYTES);
1623 if (*intermediate_key) {
1624 memcpy(*intermediate_key, ikey, INTERMEDIATE_KEY_LEN_BYTES);
1625 *intermediate_key_size = INTERMEDIATE_KEY_LEN_BYTES;
1626 }
1627 }
1628
1629 EVP_CIPHER_CTX_cleanup(&d_ctx);
1630
1631 return 0;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001632}
1633
Paul Crowley14c8c072018-09-18 13:30:21 -07001634static void get_kdf_func(struct crypt_mnt_ftr* ftr, kdf_func* kdf, void** kdf_params) {
Paul Lawrencedb3730c2015-02-03 13:08:10 -08001635 if (ftr->kdf_type == KDF_SCRYPT_KEYMASTER) {
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001636 *kdf = scrypt_keymaster;
1637 *kdf_params = ftr;
1638 } else if (ftr->kdf_type == KDF_SCRYPT) {
Kenny Rootc4c70f12013-06-14 12:11:38 -07001639 *kdf = scrypt;
1640 *kdf_params = ftr;
1641 } else {
1642 *kdf = pbkdf2;
1643 *kdf_params = NULL;
1644 }
1645}
1646
Paul Crowley14c8c072018-09-18 13:30:21 -07001647static int decrypt_master_key(const char* passwd, unsigned char* decrypted_master_key,
1648 struct crypt_mnt_ftr* crypt_ftr, unsigned char** intermediate_key,
1649 size_t* intermediate_key_size) {
Kenny Rootc4c70f12013-06-14 12:11:38 -07001650 kdf_func kdf;
Paul Crowley14c8c072018-09-18 13:30:21 -07001651 void* kdf_params;
Kenny Rootc4c70f12013-06-14 12:11:38 -07001652 int ret;
1653
1654 get_kdf_func(crypt_ftr, &kdf, &kdf_params);
Paul Crowley14c8c072018-09-18 13:30:21 -07001655 ret = decrypt_master_key_aux(passwd, crypt_ftr->salt, crypt_ftr->master_key, crypt_ftr->keysize,
1656 decrypted_master_key, kdf, kdf_params, intermediate_key,
1657 intermediate_key_size);
Kenny Rootc4c70f12013-06-14 12:11:38 -07001658 if (ret != 0) {
1659 SLOGW("failure decrypting master key");
Kenny Rootc4c70f12013-06-14 12:11:38 -07001660 }
1661
1662 return ret;
1663}
1664
Paul Crowley14c8c072018-09-18 13:30:21 -07001665static int create_encrypted_random_key(const char* passwd, unsigned char* master_key,
1666 unsigned char* salt, struct crypt_mnt_ftr* crypt_ftr) {
Greg Kaiser59ad0182018-02-16 13:01:36 -08001667 unsigned char key_buf[MAX_KEY_LEN];
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001668
Eric Biggers3a2f7db2019-01-16 13:05:34 -08001669 /* Get some random bits for a key and salt */
1670 if (android::vold::ReadRandomBytes(sizeof(key_buf), reinterpret_cast<char*>(key_buf)) != 0) {
1671 return -1;
1672 }
1673 if (android::vold::ReadRandomBytes(SALT_LEN, reinterpret_cast<char*>(salt)) != 0) {
1674 return -1;
1675 }
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001676
1677 /* Now encrypt it with the password */
AnilKumar Chimata98dc8352018-05-11 00:25:09 +05301678 return encrypt_master_key(passwd, salt, key_buf, master_key, crypt_ftr, true);
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001679}
1680
Paul Crowley14c8c072018-09-18 13:30:21 -07001681int wait_and_unmount(const char* mountpoint, bool kill) {
Greg Hackmann955653e2014-09-24 14:55:20 -07001682 int i, err, rc;
AnilKumar Chimata98dc8352018-05-11 00:25:09 +05301683#define WAIT_UNMOUNT_COUNT 200
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001684
1685 /* Now umount the tmpfs filesystem */
Paul Crowley14c8c072018-09-18 13:30:21 -07001686 for (i = 0; i < WAIT_UNMOUNT_COUNT; i++) {
Greg Hackmann6e8440f2014-10-02 17:18:20 -07001687 if (umount(mountpoint) == 0) {
1688 break;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001689 }
Greg Hackmann6e8440f2014-10-02 17:18:20 -07001690
1691 if (errno == EINVAL) {
1692 /* EINVAL is returned if the directory is not a mountpoint,
1693 * i.e. there is no filesystem mounted there. So just get out.
1694 */
1695 break;
1696 }
1697
1698 err = errno;
1699
AnilKumar Chimata98dc8352018-05-11 00:25:09 +05301700 /* If allowed, be increasingly aggressive before the last 2 seconds */
Greg Hackmann6e8440f2014-10-02 17:18:20 -07001701 if (kill) {
AnilKumar Chimata98dc8352018-05-11 00:25:09 +05301702 if (i == (WAIT_UNMOUNT_COUNT - 30)) {
Greg Hackmann6e8440f2014-10-02 17:18:20 -07001703 SLOGW("sending SIGHUP to processes with open files\n");
Jeff Sharkey3472e522017-10-06 18:02:53 -06001704 android::vold::KillProcessesWithOpenFiles(mountpoint, SIGTERM);
AnilKumar Chimata98dc8352018-05-11 00:25:09 +05301705 } else if (i == (WAIT_UNMOUNT_COUNT - 20)) {
Greg Hackmann6e8440f2014-10-02 17:18:20 -07001706 SLOGW("sending SIGKILL to processes with open files\n");
Jeff Sharkey3472e522017-10-06 18:02:53 -06001707 android::vold::KillProcessesWithOpenFiles(mountpoint, SIGKILL);
Greg Hackmann6e8440f2014-10-02 17:18:20 -07001708 }
1709 }
1710
AnilKumar Chimata98dc8352018-05-11 00:25:09 +05301711 usleep(100000);
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001712 }
1713
1714 if (i < WAIT_UNMOUNT_COUNT) {
Paul Crowley14c8c072018-09-18 13:30:21 -07001715 SLOGD("unmounting %s succeeded\n", mountpoint);
1716 rc = 0;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001717 } else {
Paul Crowley14c8c072018-09-18 13:30:21 -07001718 android::vold::KillProcessesWithOpenFiles(mountpoint, 0);
1719 SLOGE("unmounting %s failed: %s\n", mountpoint, strerror(err));
1720 rc = -1;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001721 }
1722
1723 return rc;
1724}
1725
Paul Crowley14c8c072018-09-18 13:30:21 -07001726static void prep_data_fs(void) {
Jeff Sharkey47695b22016-02-01 17:02:29 -07001727 // NOTE: post_fs_data results in init calling back around to vold, so all
1728 // callers to this method must be async
1729
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001730 /* Do the prep of the /data filesystem */
1731 property_set("vold.post_fs_data_done", "0");
1732 property_set("vold.decrypt", "trigger_post_fs_data");
Wei Wang42e38102017-06-07 10:46:12 -07001733 SLOGD("Just triggered post_fs_data");
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001734
Ken Sumrallc5872692013-05-14 15:26:31 -07001735 /* Wait a max of 50 seconds, hopefully it takes much less */
Paul Crowley14c8c072018-09-18 13:30:21 -07001736 while (!android::base::WaitForProperty("vold.post_fs_data_done", "1", std::chrono::seconds(15))) {
Wei Wang42e38102017-06-07 10:46:12 -07001737 /* We timed out to prep /data in time. Continue wait. */
1738 SLOGE("waited 15s for vold.post_fs_data_done, still waiting...");
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001739 }
Wei Wang42e38102017-06-07 10:46:12 -07001740 SLOGD("post_fs_data done");
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001741}
1742
Paul Crowley14c8c072018-09-18 13:30:21 -07001743static void cryptfs_set_corrupt() {
Paul Lawrence74f29f12014-08-28 15:54:10 -07001744 // Mark the footer as bad
1745 struct crypt_mnt_ftr crypt_ftr;
1746 if (get_crypt_ftr_and_key(&crypt_ftr)) {
1747 SLOGE("Failed to get crypto footer - panic");
1748 return;
1749 }
1750
1751 crypt_ftr.flags |= CRYPT_DATA_CORRUPT;
1752 if (put_crypt_ftr_and_key(&crypt_ftr)) {
1753 SLOGE("Failed to set crypto footer - panic");
1754 return;
1755 }
1756}
1757
Paul Crowley14c8c072018-09-18 13:30:21 -07001758static void cryptfs_trigger_restart_min_framework() {
Paul Lawrence74f29f12014-08-28 15:54:10 -07001759 if (fs_mgr_do_tmpfs_mount(DATA_MNT_POINT)) {
Paul Crowley14c8c072018-09-18 13:30:21 -07001760 SLOGE("Failed to mount tmpfs on data - panic");
1761 return;
Paul Lawrence74f29f12014-08-28 15:54:10 -07001762 }
1763
1764 if (property_set("vold.decrypt", "trigger_post_fs_data")) {
1765 SLOGE("Failed to trigger post fs data - panic");
1766 return;
1767 }
1768
1769 if (property_set("vold.decrypt", "trigger_restart_min_framework")) {
1770 SLOGE("Failed to trigger restart min framework - panic");
1771 return;
1772 }
1773}
1774
Paul Lawrence8e3f4512014-09-08 10:11:17 -07001775/* returns < 0 on failure */
Paul Crowley14c8c072018-09-18 13:30:21 -07001776static int cryptfs_restart_internal(int restart_main) {
Ken Sumrall6864b7e2011-01-14 15:20:02 -08001777 char crypto_blkdev[MAXPATHLEN];
AnilKumar Chimatad08106a2018-02-11 17:11:24 +05301778#ifdef CONFIG_HW_DISK_ENCRYPTION
1779 char blkdev[MAXPATHLEN];
1780#endif
Tim Murray8439dc92014-12-15 11:56:11 -08001781 int rc = -1;
Ken Sumrall0cc16632011-01-18 20:32:26 -08001782 static int restart_successful = 0;
1783
1784 /* Validate that it's OK to call this routine */
Paul Crowley14c8c072018-09-18 13:30:21 -07001785 if (!master_key_saved) {
Ken Sumrall0cc16632011-01-18 20:32:26 -08001786 SLOGE("Encrypted filesystem not validated, aborting");
1787 return -1;
1788 }
1789
1790 if (restart_successful) {
1791 SLOGE("System already restarted with encrypted disk, aborting");
1792 return -1;
1793 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001794
Paul Lawrencef4faa572014-01-29 13:31:03 -08001795 if (restart_main) {
1796 /* Here is where we shut down the framework. The init scripts
1797 * start all services in one of three classes: core, main or late_start.
1798 * On boot, we start core and main. Now, we stop main, but not core,
1799 * as core includes vold and a few other really important things that
1800 * we need to keep running. Once main has stopped, we should be able
1801 * to umount the tmpfs /data, then mount the encrypted /data.
1802 * We then restart the class main, and also the class late_start.
1803 * At the moment, I've only put a few things in late_start that I know
1804 * are not needed to bring up the framework, and that also cause problems
1805 * with unmounting the tmpfs /data, but I hope to add add more services
1806 * to the late_start class as we optimize this to decrease the delay
1807 * till the user is asked for the password to the filesystem.
1808 */
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001809
Paul Lawrencef4faa572014-01-29 13:31:03 -08001810 /* The init files are setup to stop the class main when vold.decrypt is
1811 * set to trigger_reset_main.
1812 */
1813 property_set("vold.decrypt", "trigger_reset_main");
1814 SLOGD("Just asked init to shut down class main\n");
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001815
Paul Lawrencef4faa572014-01-29 13:31:03 -08001816 /* Ugh, shutting down the framework is not synchronous, so until it
1817 * can be fixed, this horrible hack will wait a moment for it all to
1818 * shut down before proceeding. Without it, some devices cannot
1819 * restart the graphics services.
1820 */
1821 sleep(2);
1822 }
Ken Sumrall9dedfd42012-10-09 14:16:59 -07001823
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001824 /* Now that the framework is shutdown, we should be able to umount()
1825 * the tmpfs filesystem, and mount the real one.
1826 */
1827
AnilKumar Chimatad08106a2018-02-11 17:11:24 +05301828#if defined(CONFIG_HW_DISK_ENCRYPTION)
1829#if defined(CONFIG_HW_DISK_ENCRYPT_PERF)
1830 if (is_ice_enabled()) {
1831 fs_mgr_get_crypt_info(fstab_default, 0, blkdev, sizeof(blkdev));
1832 if (set_ice_param(START_ENCDEC)) {
1833 SLOGE("Failed to set ICE data");
1834 return -1;
1835 }
1836 }
1837#else
1838 property_get("ro.crypto.fs_crypto_blkdev", blkdev, "");
1839 if (strlen(blkdev) == 0) {
1840 SLOGE("fs_crypto_blkdev not set\n");
1841 return -1;
1842 }
1843 if (!(rc = wait_and_unmount(DATA_MNT_POINT, true))) {
1844#endif
1845#else
Ken Sumrall6864b7e2011-01-14 15:20:02 -08001846 property_get("ro.crypto.fs_crypto_blkdev", crypto_blkdev, "");
1847 if (strlen(crypto_blkdev) == 0) {
1848 SLOGE("fs_crypto_blkdev not set\n");
1849 return -1;
1850 }
1851
Paul Crowley14c8c072018-09-18 13:30:21 -07001852 if (!(rc = wait_and_unmount(DATA_MNT_POINT, true))) {
AnilKumar Chimatad08106a2018-02-11 17:11:24 +05301853#endif
Doug Zongker6fd57712013-12-17 09:43:23 -08001854 /* If ro.crypto.readonly is set to 1, mount the decrypted
1855 * filesystem readonly. This is used when /data is mounted by
1856 * recovery mode.
1857 */
1858 char ro_prop[PROPERTY_VALUE_MAX];
1859 property_get("ro.crypto.readonly", ro_prop, "");
Jeff Sharkey95440eb2017-09-18 18:19:28 -06001860 if (strlen(ro_prop) > 0 && std::stoi(ro_prop)) {
Tom Cherry4c5bde22019-01-29 14:34:01 -08001861 auto entry = GetEntryForMountPoint(&fstab_default, DATA_MNT_POINT);
1862 if (entry != nullptr) {
1863 entry->flags |= MS_RDONLY;
Luis Hector Chavezf86566f2018-05-30 15:47:50 -07001864 }
Doug Zongker6fd57712013-12-17 09:43:23 -08001865 }
JP Abgrall62c7af32014-06-16 13:01:23 -07001866
Ken Sumralle5032c42012-04-01 23:58:44 -07001867 /* If that succeeded, then mount the decrypted filesystem */
Paul Lawrence8e3f4512014-09-08 10:11:17 -07001868 int retries = RETRY_MOUNT_ATTEMPTS;
1869 int mount_rc;
Jeff Vander Stoepdf725752016-01-29 15:34:43 -08001870
1871 /*
1872 * fs_mgr_do_mount runs fsck. Use setexeccon to run trusted
1873 * partitions in the fsck domain.
1874 */
LongPing Wei7f3ab952019-01-30 16:03:14 +08001875 if (setexeccon(android::vold::sFsckContext)) {
Jeff Vander Stoepdf725752016-01-29 15:34:43 -08001876 SLOGE("Failed to setexeccon");
1877 return -1;
1878 }
Daniel Rosenberg4f684712018-08-28 01:58:49 -07001879 bool needs_cp = android::vold::cp_needsCheckpoint();
AnilKumar Chimatad08106a2018-02-11 17:11:24 +05301880#ifdef CONFIG_HW_DISK_ENCRYPTION
Eric Arseneau2f8ce652019-02-06 14:23:39 -08001881 while ((mount_rc = fs_mgr_do_mount(&fstab_default, DATA_MNT_POINT, blkdev, 0,
Bill Peckham0db11972018-10-10 10:25:42 -07001882 needs_cp)) != 0) {
AnilKumar Chimatad08106a2018-02-11 17:11:24 +05301883#else
Tom Cherry4c5bde22019-01-29 14:34:01 -08001884 while ((mount_rc = fs_mgr_do_mount(&fstab_default, DATA_MNT_POINT, crypto_blkdev, 0,
Daniel Rosenberg4f684712018-08-28 01:58:49 -07001885 needs_cp)) != 0) {
AnilKumar Chimatad08106a2018-02-11 17:11:24 +05301886#endif
Paul Lawrence8e3f4512014-09-08 10:11:17 -07001887 if (mount_rc == FS_MGR_DOMNT_BUSY) {
1888 /* TODO: invoke something similar to
1889 Process::killProcessWithOpenFiles(DATA_MNT_POINT,
1890 retries > RETRY_MOUNT_ATTEMPT/2 ? 1 : 2 ) */
AnilKumar Chimatad08106a2018-02-11 17:11:24 +05301891#ifdef CONFIG_HW_DISK_ENCRYPTION
Bill Peckham0db11972018-10-10 10:25:42 -07001892 SLOGI("Failed to mount %s because it is busy - waiting", blkdev);
AnilKumar Chimatad08106a2018-02-11 17:11:24 +05301893#else
Paul Crowley14c8c072018-09-18 13:30:21 -07001894 SLOGI("Failed to mount %s because it is busy - waiting", crypto_blkdev);
AnilKumar Chimatad08106a2018-02-11 17:11:24 +05301895#endif
Paul Lawrence8e3f4512014-09-08 10:11:17 -07001896 if (--retries) {
1897 sleep(RETRY_MOUNT_DELAY_SECONDS);
1898 } else {
1899 /* Let's hope that a reboot clears away whatever is keeping
1900 the mount busy */
Josh Gaofec44372017-08-28 13:22:55 -07001901 cryptfs_reboot(RebootType::reboot);
Paul Lawrence8e3f4512014-09-08 10:11:17 -07001902 }
1903 } else {
AnilKumar Chimata98dc8352018-05-11 00:25:09 +05301904#ifdef CONFIG_HW_DISK_ENCRYPTION
1905 if (--retries) {
1906 sleep(RETRY_MOUNT_DELAY_SECONDS);
1907 } else {
1908 SLOGE("Failed to mount decrypted data");
1909 cryptfs_set_corrupt();
1910 cryptfs_trigger_restart_min_framework();
1911 SLOGI("Started framework to offer wipe");
1912 return -1;
1913 }
1914#else
Paul Lawrence8e3f4512014-09-08 10:11:17 -07001915 SLOGE("Failed to mount decrypted data");
1916 cryptfs_set_corrupt();
1917 cryptfs_trigger_restart_min_framework();
1918 SLOGI("Started framework to offer wipe");
Jeff Vander Stoepdf725752016-01-29 15:34:43 -08001919 if (setexeccon(NULL)) {
1920 SLOGE("Failed to setexeccon");
1921 }
Paul Lawrence8e3f4512014-09-08 10:11:17 -07001922 return -1;
AnilKumar Chimata98dc8352018-05-11 00:25:09 +05301923#endif
Paul Lawrence8e3f4512014-09-08 10:11:17 -07001924 }
Paul Lawrence74f29f12014-08-28 15:54:10 -07001925 }
Jeff Vander Stoepdf725752016-01-29 15:34:43 -08001926 if (setexeccon(NULL)) {
1927 SLOGE("Failed to setexeccon");
1928 return -1;
1929 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001930
Ken Sumralle5032c42012-04-01 23:58:44 -07001931 /* Create necessary paths on /data */
Wei Wang42e38102017-06-07 10:46:12 -07001932 prep_data_fs();
Seigo Nonakae2ef0c02016-06-20 17:05:40 +09001933 property_set("vold.decrypt", "trigger_load_persist_props");
Ken Sumralle5032c42012-04-01 23:58:44 -07001934
1935 /* startup service classes main and late_start */
1936 property_set("vold.decrypt", "trigger_restart_framework");
1937 SLOGD("Just triggered restart_framework\n");
1938
1939 /* Give it a few moments to get started */
1940 sleep(1);
AnilKumar Chimatad08106a2018-02-11 17:11:24 +05301941#ifndef CONFIG_HW_DISK_ENCRYPT_PERF
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001942 }
AnilKumar Chimatad08106a2018-02-11 17:11:24 +05301943#endif
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001944
Ken Sumrall0cc16632011-01-18 20:32:26 -08001945 if (rc == 0) {
1946 restart_successful = 1;
1947 }
1948
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001949 return rc;
1950}
1951
Paul Crowley14c8c072018-09-18 13:30:21 -07001952int cryptfs_restart(void) {
Paul Lawrence05335c32015-03-05 09:46:23 -08001953 SLOGI("cryptfs_restart");
Eric Biggersa701c452018-10-23 13:06:55 -07001954 if (fscrypt_is_native()) {
Paul Lawrence7b6b5652016-02-02 11:14:59 -08001955 SLOGE("cryptfs_restart not valid for file encryption:");
1956 return -1;
Paul Lawrence05335c32015-03-05 09:46:23 -08001957 }
1958
Paul Lawrencef4faa572014-01-29 13:31:03 -08001959 /* Call internal implementation forcing a restart of main service group */
1960 return cryptfs_restart_internal(1);
1961}
1962
Paul Crowley14c8c072018-09-18 13:30:21 -07001963static int do_crypto_complete(const char* mount_point) {
1964 struct crypt_mnt_ftr crypt_ftr;
1965 char encrypted_state[PROPERTY_VALUE_MAX];
Ken Sumrall7f7dbaa2011-02-01 15:46:41 -08001966
Paul Crowley14c8c072018-09-18 13:30:21 -07001967 property_get("ro.crypto.state", encrypted_state, "");
1968 if (strcmp(encrypted_state, "encrypted")) {
1969 SLOGE("not running with encryption, aborting");
1970 return CRYPTO_COMPLETE_NOT_ENCRYPTED;
Ken Sumralle1a45852011-12-14 21:24:27 -08001971 }
Ken Sumrall7f7dbaa2011-02-01 15:46:41 -08001972
Paul Crowley14c8c072018-09-18 13:30:21 -07001973 // crypto_complete is full disk encrypted status
Eric Biggersa701c452018-10-23 13:06:55 -07001974 if (fscrypt_is_native()) {
Paul Crowley14c8c072018-09-18 13:30:21 -07001975 return CRYPTO_COMPLETE_NOT_ENCRYPTED;
1976 }
Paul Lawrence74f29f12014-08-28 15:54:10 -07001977
Paul Crowley14c8c072018-09-18 13:30:21 -07001978 if (get_crypt_ftr_and_key(&crypt_ftr)) {
Tom Cherry4c5bde22019-01-29 14:34:01 -08001979 std::string key_loc;
1980 get_crypt_info(&key_loc, nullptr);
Paul Lawrence74f29f12014-08-28 15:54:10 -07001981
Paul Crowley14c8c072018-09-18 13:30:21 -07001982 /*
1983 * Only report this error if key_loc is a file and it exists.
1984 * If the device was never encrypted, and /data is not mountable for
1985 * some reason, returning 1 should prevent the UI from presenting the
1986 * a "enter password" screen, or worse, a "press button to wipe the
1987 * device" screen.
1988 */
Tom Cherry4c5bde22019-01-29 14:34:01 -08001989 if (!key_loc.empty() && key_loc[0] == '/' && (access("key_loc", F_OK) == -1)) {
Paul Crowley14c8c072018-09-18 13:30:21 -07001990 SLOGE("master key file does not exist, aborting");
1991 return CRYPTO_COMPLETE_NOT_ENCRYPTED;
1992 } else {
1993 SLOGE("Error getting crypt footer and key\n");
1994 return CRYPTO_COMPLETE_BAD_METADATA;
1995 }
1996 }
Ken Sumrall7f7dbaa2011-02-01 15:46:41 -08001997
Paul Crowley14c8c072018-09-18 13:30:21 -07001998 // Test for possible error flags
1999 if (crypt_ftr.flags & CRYPT_ENCRYPTION_IN_PROGRESS) {
2000 SLOGE("Encryption process is partway completed\n");
2001 return CRYPTO_COMPLETE_PARTIAL;
2002 }
2003
2004 if (crypt_ftr.flags & CRYPT_INCONSISTENT_STATE) {
2005 SLOGE("Encryption process was interrupted but cannot continue\n");
2006 return CRYPTO_COMPLETE_INCONSISTENT;
2007 }
2008
2009 if (crypt_ftr.flags & CRYPT_DATA_CORRUPT) {
2010 SLOGE("Encryption is successful but data is corrupt\n");
2011 return CRYPTO_COMPLETE_CORRUPT;
2012 }
2013
2014 /* We passed the test! We shall diminish, and return to the west */
2015 return CRYPTO_COMPLETE_ENCRYPTED;
Ken Sumrall7f7dbaa2011-02-01 15:46:41 -08002016}
2017
AnilKumar Chimata98dc8352018-05-11 00:25:09 +05302018#ifdef CONFIG_HW_DISK_ENCRYPTION
2019static int test_mount_hw_encrypted_fs(struct crypt_mnt_ftr* crypt_ftr,
2020 const char *passwd, const char *mount_point, const char *label)
2021{
Bill Peckham0db11972018-10-10 10:25:42 -07002022 /* Allocate enough space for a 256 bit key, but we may use less */
2023 unsigned char decrypted_master_key[32];
2024 char crypto_blkdev[MAXPATHLEN];
2025 char real_blkdev[MAXPATHLEN];
2026 unsigned int orig_failed_decrypt_count;
2027 int rc = 0;
AnilKumar Chimata98dc8352018-05-11 00:25:09 +05302028
Bill Peckham0db11972018-10-10 10:25:42 -07002029 SLOGD("crypt_ftr->fs_size = %lld\n", crypt_ftr->fs_size);
2030 orig_failed_decrypt_count = crypt_ftr->failed_decrypt_count;
AnilKumar Chimata98dc8352018-05-11 00:25:09 +05302031
Bill Peckham0db11972018-10-10 10:25:42 -07002032 fs_mgr_get_crypt_info(fstab_default, 0, real_blkdev, sizeof(real_blkdev));
AnilKumar Chimata98dc8352018-05-11 00:25:09 +05302033
Bill Peckham0db11972018-10-10 10:25:42 -07002034 int key_index = 0;
2035 if(is_hw_disk_encryption((char*)crypt_ftr->crypto_type_name)) {
2036 key_index = verify_and_update_hw_fde_passwd(passwd, crypt_ftr);
2037 if (key_index < 0) {
2038 rc = crypt_ftr->failed_decrypt_count;
2039 goto errout;
2040 }
2041 else {
2042 if (is_ice_enabled()) {
AnilKumar Chimatad08106a2018-02-11 17:11:24 +05302043#ifndef CONFIG_HW_DISK_ENCRYPT_PERF
Bill Peckham0db11972018-10-10 10:25:42 -07002044 if (create_crypto_blk_dev(crypt_ftr, (unsigned char*)&key_index,
2045 real_blkdev, crypto_blkdev, label, 0)) {
2046 SLOGE("Error creating decrypted block device");
2047 rc = -1;
2048 goto errout;
2049 }
AnilKumar Chimatad08106a2018-02-11 17:11:24 +05302050#endif
Bill Peckham0db11972018-10-10 10:25:42 -07002051 } else {
2052 if (create_crypto_blk_dev(crypt_ftr, decrypted_master_key,
2053 real_blkdev, crypto_blkdev, label, 0)) {
2054 SLOGE("Error creating decrypted block device");
2055 rc = -1;
2056 goto errout;
2057 }
2058 }
AnilKumar Chimata98dc8352018-05-11 00:25:09 +05302059 }
AnilKumar Chimata98dc8352018-05-11 00:25:09 +05302060 }
2061
Bill Peckham0db11972018-10-10 10:25:42 -07002062 if (rc == 0) {
2063 crypt_ftr->failed_decrypt_count = 0;
2064 if (orig_failed_decrypt_count != 0) {
2065 put_crypt_ftr_and_key(crypt_ftr);
2066 }
2067
2068 /* Save the name of the crypto block device
2069 * so we can mount it when restarting the framework. */
AnilKumar Chimatad08106a2018-02-11 17:11:24 +05302070#ifdef CONFIG_HW_DISK_ENCRYPT_PERF
Bill Peckham0db11972018-10-10 10:25:42 -07002071 if (!is_ice_enabled())
AnilKumar Chimatad08106a2018-02-11 17:11:24 +05302072#endif
Bill Peckham0db11972018-10-10 10:25:42 -07002073 property_set("ro.crypto.fs_crypto_blkdev", crypto_blkdev);
2074 master_key_saved = 1;
2075 }
AnilKumar Chimata98dc8352018-05-11 00:25:09 +05302076
Bill Peckham0db11972018-10-10 10:25:42 -07002077 errout:
2078 return rc;
AnilKumar Chimata98dc8352018-05-11 00:25:09 +05302079}
2080#endif
2081
Paul Crowley14c8c072018-09-18 13:30:21 -07002082static int test_mount_encrypted_fs(struct crypt_mnt_ftr* crypt_ftr, const char* passwd,
2083 const char* mount_point, const char* label) {
2084 unsigned char decrypted_master_key[MAX_KEY_LEN];
2085 char crypto_blkdev[MAXPATHLEN];
Tom Cherry4c5bde22019-01-29 14:34:01 -08002086 std::string real_blkdev;
Paul Crowley14c8c072018-09-18 13:30:21 -07002087 char tmp_mount_point[64];
2088 unsigned int orig_failed_decrypt_count;
2089 int rc;
2090 int use_keymaster = 0;
2091 int upgrade = 0;
2092 unsigned char* intermediate_key = 0;
2093 size_t intermediate_key_size = 0;
2094 int N = 1 << crypt_ftr->N_factor;
2095 int r = 1 << crypt_ftr->r_factor;
2096 int p = 1 << crypt_ftr->p_factor;
AnilKumar Chimata98dc8352018-05-11 00:25:09 +05302097
Paul Crowley14c8c072018-09-18 13:30:21 -07002098 SLOGD("crypt_ftr->fs_size = %lld\n", crypt_ftr->fs_size);
2099 orig_failed_decrypt_count = crypt_ftr->failed_decrypt_count;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002100
Paul Crowley14c8c072018-09-18 13:30:21 -07002101 if (!(crypt_ftr->flags & CRYPT_MNT_KEY_UNENCRYPTED)) {
2102 if (decrypt_master_key(passwd, decrypted_master_key, crypt_ftr, &intermediate_key,
2103 &intermediate_key_size)) {
2104 SLOGE("Failed to decrypt master key\n");
2105 rc = -1;
2106 goto errout;
2107 }
JP Abgrall7bdfa522013-11-15 13:42:56 -08002108 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002109
Tom Cherry4c5bde22019-01-29 14:34:01 -08002110 get_crypt_info(nullptr, &real_blkdev);
Paul Lawrencef4faa572014-01-29 13:31:03 -08002111
Paul Crowley14c8c072018-09-18 13:30:21 -07002112 // Create crypto block device - all (non fatal) code paths
2113 // need it
Tom Cherry4c5bde22019-01-29 14:34:01 -08002114 if (create_crypto_blk_dev(crypt_ftr, decrypted_master_key, real_blkdev.c_str(), crypto_blkdev,
2115 label, 0)) {
Paul Crowley14c8c072018-09-18 13:30:21 -07002116 SLOGE("Error creating decrypted block device\n");
2117 rc = -1;
2118 goto errout;
2119 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002120
Paul Crowley14c8c072018-09-18 13:30:21 -07002121 /* Work out if the problem is the password or the data */
2122 unsigned char scrypted_intermediate_key[sizeof(crypt_ftr->scrypted_intermediate_key)];
Paul Lawrenced0c7b172014-08-08 14:28:10 -07002123
Paul Crowley14c8c072018-09-18 13:30:21 -07002124 rc = crypto_scrypt(intermediate_key, intermediate_key_size, crypt_ftr->salt,
2125 sizeof(crypt_ftr->salt), N, r, p, scrypted_intermediate_key,
2126 sizeof(scrypted_intermediate_key));
Paul Lawrenced0c7b172014-08-08 14:28:10 -07002127
Paul Crowley14c8c072018-09-18 13:30:21 -07002128 // Does the key match the crypto footer?
2129 if (rc == 0 && memcmp(scrypted_intermediate_key, crypt_ftr->scrypted_intermediate_key,
2130 sizeof(scrypted_intermediate_key)) == 0) {
2131 SLOGI("Password matches");
2132 rc = 0;
Paul Lawrence74f29f12014-08-28 15:54:10 -07002133 } else {
Paul Crowley14c8c072018-09-18 13:30:21 -07002134 /* Try mounting the file system anyway, just in case the problem's with
2135 * the footer, not the key. */
2136 snprintf(tmp_mount_point, sizeof(tmp_mount_point), "%s/tmp_mnt", mount_point);
2137 mkdir(tmp_mount_point, 0755);
Tom Cherry4c5bde22019-01-29 14:34:01 -08002138 if (fs_mgr_do_mount(&fstab_default, DATA_MNT_POINT, crypto_blkdev, tmp_mount_point)) {
Paul Crowley14c8c072018-09-18 13:30:21 -07002139 SLOGE("Error temp mounting decrypted block device\n");
2140 delete_crypto_blk_dev(label);
Paul Lawrence74f29f12014-08-28 15:54:10 -07002141
Paul Crowley14c8c072018-09-18 13:30:21 -07002142 rc = ++crypt_ftr->failed_decrypt_count;
2143 put_crypt_ftr_and_key(crypt_ftr);
2144 } else {
2145 /* Success! */
2146 SLOGI("Password did not match but decrypted drive mounted - continue");
2147 umount(tmp_mount_point);
2148 rc = 0;
Paul Lawrenceb2f682b2014-09-08 11:28:19 -07002149 }
JP Abgrall7bdfa522013-11-15 13:42:56 -08002150 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002151
Paul Crowley14c8c072018-09-18 13:30:21 -07002152 if (rc == 0) {
2153 crypt_ftr->failed_decrypt_count = 0;
2154 if (orig_failed_decrypt_count != 0) {
2155 put_crypt_ftr_and_key(crypt_ftr);
2156 }
2157
2158 /* Save the name of the crypto block device
2159 * so we can mount it when restarting the framework. */
2160 property_set("ro.crypto.fs_crypto_blkdev", crypto_blkdev);
2161
2162 /* Also save a the master key so we can reencrypted the key
2163 * the key when we want to change the password on it. */
2164 memcpy(saved_master_key, decrypted_master_key, crypt_ftr->keysize);
2165 saved_mount_point = strdup(mount_point);
2166 master_key_saved = 1;
2167 SLOGD("%s(): Master key saved\n", __FUNCTION__);
2168 rc = 0;
2169
2170 // Upgrade if we're not using the latest KDF.
2171 use_keymaster = keymaster_check_compatibility();
2172 if (crypt_ftr->kdf_type == KDF_SCRYPT_KEYMASTER) {
2173 // Don't allow downgrade
2174 } else if (use_keymaster == 1 && crypt_ftr->kdf_type != KDF_SCRYPT_KEYMASTER) {
2175 crypt_ftr->kdf_type = KDF_SCRYPT_KEYMASTER;
2176 upgrade = 1;
2177 } else if (use_keymaster == 0 && crypt_ftr->kdf_type != KDF_SCRYPT) {
2178 crypt_ftr->kdf_type = KDF_SCRYPT;
2179 upgrade = 1;
2180 }
2181
2182 if (upgrade) {
2183 rc = encrypt_master_key(passwd, crypt_ftr->salt, saved_master_key,
Bill Peckham0db11972018-10-10 10:25:42 -07002184 crypt_ftr->master_key, crypt_ftr, true);
Paul Crowley14c8c072018-09-18 13:30:21 -07002185 if (!rc) {
2186 rc = put_crypt_ftr_and_key(crypt_ftr);
2187 }
2188 SLOGD("Key Derivation Function upgrade: rc=%d\n", rc);
2189
2190 // Do not fail even if upgrade failed - machine is bootable
2191 // Note that if this code is ever hit, there is a *serious* problem
2192 // since KDFs should never fail. You *must* fix the kdf before
2193 // proceeding!
2194 if (rc) {
2195 SLOGW(
2196 "Upgrade failed with error %d,"
2197 " but continuing with previous state",
2198 rc);
2199 rc = 0;
2200 }
2201 }
2202 }
2203
2204errout:
2205 if (intermediate_key) {
2206 memset(intermediate_key, 0, intermediate_key_size);
2207 free(intermediate_key);
2208 }
2209 return rc;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002210}
2211
Ken Sumrall29d8da82011-05-18 17:20:07 -07002212/*
Jeff Sharkey9c484982015-03-31 10:35:33 -07002213 * Called by vold when it's asked to mount an encrypted external
2214 * storage volume. The incoming partition has no crypto header/footer,
Greg Kaiser57f9af62018-02-16 13:13:58 -08002215 * as any metadata is been stored in a separate, small partition. We
2216 * assume it must be using our same crypt type and keysize.
Jeff Sharkey9c484982015-03-31 10:35:33 -07002217 *
2218 * out_crypto_blkdev must be MAXPATHLEN.
Ken Sumrall29d8da82011-05-18 17:20:07 -07002219 */
Paul Crowley14c8c072018-09-18 13:30:21 -07002220int cryptfs_setup_ext_volume(const char* label, const char* real_blkdev, const unsigned char* key,
2221 char* out_crypto_blkdev) {
Oleksiy Avramchenko625dc782018-05-23 10:50:46 +02002222 uint64_t nr_sec = 0;
2223 if (android::vold::GetBlockDev512Sectors(real_blkdev, &nr_sec) != android::OK) {
Jeff Sharkey9c484982015-03-31 10:35:33 -07002224 SLOGE("Failed to get size of %s: %s", real_blkdev, strerror(errno));
Ken Sumrall29d8da82011-05-18 17:20:07 -07002225 return -1;
2226 }
2227
Jeff Sharkey9c484982015-03-31 10:35:33 -07002228 struct crypt_mnt_ftr ext_crypt_ftr;
2229 memset(&ext_crypt_ftr, 0, sizeof(ext_crypt_ftr));
2230 ext_crypt_ftr.fs_size = nr_sec;
Greg Kaiser57f9af62018-02-16 13:13:58 -08002231 ext_crypt_ftr.keysize = cryptfs_get_keysize();
Paul Crowley14c8c072018-09-18 13:30:21 -07002232 strlcpy((char*)ext_crypt_ftr.crypto_type_name, cryptfs_get_crypto_name(),
Jeff Sharkey32ebb732017-03-27 16:18:50 -06002233 MAX_CRYPTO_TYPE_NAME_LEN);
Paul Crowley385cb8c2018-03-29 13:27:23 -07002234 uint32_t flags = 0;
Eric Biggersa701c452018-10-23 13:06:55 -07002235 if (fscrypt_is_native() &&
Paul Crowley385cb8c2018-03-29 13:27:23 -07002236 android::base::GetBoolProperty("ro.crypto.allow_encrypt_override", false))
2237 flags |= CREATE_CRYPTO_BLK_DEV_FLAGS_ALLOW_ENCRYPT_OVERRIDE;
Ken Sumrall29d8da82011-05-18 17:20:07 -07002238
Paul Crowley385cb8c2018-03-29 13:27:23 -07002239 return create_crypto_blk_dev(&ext_crypt_ftr, key, real_blkdev, out_crypto_blkdev, label, flags);
Jeff Sharkey9c484982015-03-31 10:35:33 -07002240}
Ken Sumrall29d8da82011-05-18 17:20:07 -07002241
Jeff Sharkey9c484982015-03-31 10:35:33 -07002242/*
2243 * Called by vold when it's asked to unmount an encrypted external
2244 * storage volume.
2245 */
2246int cryptfs_revert_ext_volume(const char* label) {
Paul Crowley14c8c072018-09-18 13:30:21 -07002247 return delete_crypto_blk_dev((char*)label);
Ken Sumrall29d8da82011-05-18 17:20:07 -07002248}
2249
Paul Crowley14c8c072018-09-18 13:30:21 -07002250int cryptfs_crypto_complete(void) {
2251 return do_crypto_complete("/data");
Ken Sumrall7f7dbaa2011-02-01 15:46:41 -08002252}
2253
Paul Crowley14c8c072018-09-18 13:30:21 -07002254int check_unmounted_and_get_ftr(struct crypt_mnt_ftr* crypt_ftr) {
Paul Lawrencef4faa572014-01-29 13:31:03 -08002255 char encrypted_state[PROPERTY_VALUE_MAX];
2256 property_get("ro.crypto.state", encrypted_state, "");
Paul Crowley14c8c072018-09-18 13:30:21 -07002257 if (master_key_saved || strcmp(encrypted_state, "encrypted")) {
2258 SLOGE(
2259 "encrypted fs already validated or not running with encryption,"
2260 " aborting");
Paul Lawrencef4faa572014-01-29 13:31:03 -08002261 return -1;
2262 }
2263
2264 if (get_crypt_ftr_and_key(crypt_ftr)) {
2265 SLOGE("Error getting crypt footer and key");
2266 return -1;
2267 }
2268
2269 return 0;
2270}
2271
AnilKumar Chimata98dc8352018-05-11 00:25:09 +05302272#ifdef CONFIG_HW_DISK_ENCRYPTION
2273int cryptfs_check_passwd_hw(const char* passwd)
2274{
2275 struct crypt_mnt_ftr crypt_ftr;
2276 int rc;
2277 unsigned char master_key[KEY_LEN_BYTES];
2278
2279 /* get key */
2280 if (get_crypt_ftr_and_key(&crypt_ftr)) {
2281 SLOGE("Error getting crypt footer and key");
2282 return -1;
2283 }
2284
2285 /*
2286 * in case of manual encryption (from GUI), the encryption is done with
2287 * default password
2288 */
2289 if (crypt_ftr.flags & CRYPT_FORCE_COMPLETE) {
2290 /* compare scrypted_intermediate_key with stored scrypted_intermediate_key
2291 * which was created with actual password before reboot.
2292 */
2293 rc = cryptfs_get_master_key(&crypt_ftr, passwd, master_key);
2294 if (rc) {
2295 SLOGE("password doesn't match");
2296 rc = ++crypt_ftr.failed_decrypt_count;
2297 put_crypt_ftr_and_key(&crypt_ftr);
2298 return rc;
2299 }
2300
2301 rc = test_mount_hw_encrypted_fs(&crypt_ftr, DEFAULT_PASSWORD,
2302 DATA_MNT_POINT, CRYPTO_BLOCK_DEVICE);
2303
2304 if (rc) {
2305 SLOGE("Default password did not match on reboot encryption");
2306 return rc;
2307 }
2308
2309 crypt_ftr.flags &= ~CRYPT_FORCE_COMPLETE;
2310 put_crypt_ftr_and_key(&crypt_ftr);
2311 rc = cryptfs_changepw(crypt_ftr.crypt_type, DEFAULT_PASSWORD, passwd);
2312 if (rc) {
2313 SLOGE("Could not change password on reboot encryption");
2314 return rc;
2315 }
2316 } else
2317 rc = test_mount_hw_encrypted_fs(&crypt_ftr, passwd,
2318 DATA_MNT_POINT, CRYPTO_BLOCK_DEVICE);
2319
2320 if (crypt_ftr.crypt_type != CRYPT_TYPE_DEFAULT) {
2321 cryptfs_clear_password();
2322 password = strdup(passwd);
2323 struct timespec now;
2324 clock_gettime(CLOCK_BOOTTIME, &now);
2325 password_expiry_time = now.tv_sec + password_max_age_seconds;
2326 }
2327
2328 return rc;
2329}
2330#endif
2331
Paul Crowley14c8c072018-09-18 13:30:21 -07002332int cryptfs_check_passwd(const char* passwd) {
Paul Lawrence05335c32015-03-05 09:46:23 -08002333 SLOGI("cryptfs_check_passwd");
Eric Biggersa701c452018-10-23 13:06:55 -07002334 if (fscrypt_is_native()) {
Paul Lawrence7b6b5652016-02-02 11:14:59 -08002335 SLOGE("cryptfs_check_passwd not valid for file encryption");
2336 return -1;
Paul Lawrence05335c32015-03-05 09:46:23 -08002337 }
2338
Paul Lawrencef4faa572014-01-29 13:31:03 -08002339 struct crypt_mnt_ftr crypt_ftr;
2340 int rc;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002341
Paul Lawrencef4faa572014-01-29 13:31:03 -08002342 rc = check_unmounted_and_get_ftr(&crypt_ftr);
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002343 if (rc) {
2344 SLOGE("Could not get footer");
Paul Lawrencef4faa572014-01-29 13:31:03 -08002345 return rc;
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002346 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002347
AnilKumar Chimata98dc8352018-05-11 00:25:09 +05302348#ifdef CONFIG_HW_DISK_ENCRYPTION
2349 if (is_hw_disk_encryption((char*)crypt_ftr.crypto_type_name))
2350 return cryptfs_check_passwd_hw(passwd);
2351#endif
2352
Paul Crowley14c8c072018-09-18 13:30:21 -07002353 rc = test_mount_encrypted_fs(&crypt_ftr, passwd, DATA_MNT_POINT, CRYPTO_BLOCK_DEVICE);
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002354 if (rc) {
2355 SLOGE("Password did not match");
2356 return rc;
2357 }
Paul Lawrence684dbdf2014-02-07 12:07:22 -08002358
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002359 if (crypt_ftr.flags & CRYPT_FORCE_COMPLETE) {
2360 // Here we have a default actual password but a real password
2361 // we must test against the scrypted value
2362 // First, we must delete the crypto block device that
2363 // test_mount_encrypted_fs leaves behind as a side effect
2364 delete_crypto_blk_dev(CRYPTO_BLOCK_DEVICE);
Paul Crowley14c8c072018-09-18 13:30:21 -07002365 rc = test_mount_encrypted_fs(&crypt_ftr, DEFAULT_PASSWORD, DATA_MNT_POINT,
2366 CRYPTO_BLOCK_DEVICE);
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002367 if (rc) {
2368 SLOGE("Default password did not match on reboot encryption");
2369 return rc;
2370 }
2371
2372 crypt_ftr.flags &= ~CRYPT_FORCE_COMPLETE;
2373 put_crypt_ftr_and_key(&crypt_ftr);
AnilKumar Chimata98dc8352018-05-11 00:25:09 +05302374 rc = cryptfs_changepw(crypt_ftr.crypt_type, DEFAULT_PASSWORD, passwd);
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002375 if (rc) {
2376 SLOGE("Could not change password on reboot encryption");
2377 return rc;
2378 }
2379 }
2380
2381 if (crypt_ftr.crypt_type != CRYPT_TYPE_DEFAULT) {
Paul Lawrence399317e2014-03-10 13:20:50 -07002382 cryptfs_clear_password();
2383 password = strdup(passwd);
2384 struct timespec now;
2385 clock_gettime(CLOCK_BOOTTIME, &now);
2386 password_expiry_time = now.tv_sec + password_max_age_seconds;
Paul Lawrence684dbdf2014-02-07 12:07:22 -08002387 }
2388
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002389 return rc;
2390}
2391
Paul Crowley14c8c072018-09-18 13:30:21 -07002392int cryptfs_verify_passwd(const char* passwd) {
Ken Sumrall3ad90722011-10-04 20:38:29 -07002393 struct crypt_mnt_ftr crypt_ftr;
Greg Kaiser59ad0182018-02-16 13:01:36 -08002394 unsigned char decrypted_master_key[MAX_KEY_LEN];
Ken Sumrall3ad90722011-10-04 20:38:29 -07002395 char encrypted_state[PROPERTY_VALUE_MAX];
2396 int rc;
2397
2398 property_get("ro.crypto.state", encrypted_state, "");
Paul Crowley14c8c072018-09-18 13:30:21 -07002399 if (strcmp(encrypted_state, "encrypted")) {
Ken Sumrall3ad90722011-10-04 20:38:29 -07002400 SLOGE("device not encrypted, aborting");
2401 return -2;
2402 }
2403
2404 if (!master_key_saved) {
2405 SLOGE("encrypted fs not yet mounted, aborting");
2406 return -1;
2407 }
2408
2409 if (!saved_mount_point) {
2410 SLOGE("encrypted fs failed to save mount point, aborting");
2411 return -1;
2412 }
2413
Ken Sumrall160b4d62013-04-22 12:15:39 -07002414 if (get_crypt_ftr_and_key(&crypt_ftr)) {
Ken Sumrall3ad90722011-10-04 20:38:29 -07002415 SLOGE("Error getting crypt footer and key\n");
2416 return -1;
2417 }
2418
2419 if (crypt_ftr.flags & CRYPT_MNT_KEY_UNENCRYPTED) {
2420 /* If the device has no password, then just say the password is valid */
2421 rc = 0;
2422 } else {
AnilKumar Chimata98dc8352018-05-11 00:25:09 +05302423#ifdef CONFIG_HW_DISK_ENCRYPTION
2424 if(is_hw_disk_encryption((char*)crypt_ftr.crypto_type_name)) {
2425 if (verify_hw_fde_passwd(passwd, &crypt_ftr) >= 0)
2426 rc = 0;
2427 else
2428 rc = -1;
2429 } else {
2430 decrypt_master_key(passwd, decrypted_master_key, &crypt_ftr, 0, 0);
2431 if (!memcmp(decrypted_master_key, saved_master_key, crypt_ftr.keysize)) {
2432 /* They match, the password is correct */
2433 rc = 0;
2434 } else {
2435 /* If incorrect, sleep for a bit to prevent dictionary attacks */
2436 sleep(1);
2437 rc = 1;
2438 }
2439 }
2440#else
Paul Lawrenced0c7b172014-08-08 14:28:10 -07002441 decrypt_master_key(passwd, decrypted_master_key, &crypt_ftr, 0, 0);
Ken Sumrall3ad90722011-10-04 20:38:29 -07002442 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 }
AnilKumar Chimata98dc8352018-05-11 00:25:09 +05302450#endif
Ken Sumrall3ad90722011-10-04 20:38:29 -07002451 }
2452
2453 return rc;
2454}
2455
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002456/* Initialize a crypt_mnt_ftr structure. The keysize is
Greg Kaiser57f9af62018-02-16 13:13:58 -08002457 * defaulted to cryptfs_get_keysize() bytes, and the filesystem size to 0.
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002458 * Presumably, at a minimum, the caller will update the
2459 * filesystem size and crypto_type_name after calling this function.
2460 */
Paul Crowley14c8c072018-09-18 13:30:21 -07002461static int cryptfs_init_crypt_mnt_ftr(struct crypt_mnt_ftr* ftr) {
Ken Sumrall160b4d62013-04-22 12:15:39 -07002462 off64_t off;
2463
2464 memset(ftr, 0, sizeof(struct crypt_mnt_ftr));
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002465 ftr->magic = CRYPT_MNT_MAGIC;
Kenny Rootc96a5f82013-06-14 12:08:28 -07002466 ftr->major_version = CURRENT_MAJOR_VERSION;
2467 ftr->minor_version = CURRENT_MINOR_VERSION;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002468 ftr->ftr_size = sizeof(struct crypt_mnt_ftr);
Greg Kaiser57f9af62018-02-16 13:13:58 -08002469 ftr->keysize = cryptfs_get_keysize();
Ken Sumrall160b4d62013-04-22 12:15:39 -07002470
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07002471 switch (keymaster_check_compatibility()) {
Paul Crowley14c8c072018-09-18 13:30:21 -07002472 case 1:
2473 ftr->kdf_type = KDF_SCRYPT_KEYMASTER;
2474 break;
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07002475
Paul Crowley14c8c072018-09-18 13:30:21 -07002476 case 0:
2477 ftr->kdf_type = KDF_SCRYPT;
2478 break;
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07002479
Paul Crowley14c8c072018-09-18 13:30:21 -07002480 default:
2481 SLOGE("keymaster_check_compatibility failed");
2482 return -1;
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07002483 }
2484
Kenny Rootc4c70f12013-06-14 12:11:38 -07002485 get_device_scrypt_params(ftr);
2486
Ken Sumrall160b4d62013-04-22 12:15:39 -07002487 ftr->persist_data_size = CRYPT_PERSIST_DATA_SIZE;
2488 if (get_crypt_ftr_info(NULL, &off) == 0) {
2489 ftr->persist_data_offset[0] = off + CRYPT_FOOTER_TO_PERSIST_OFFSET;
Paul Crowley14c8c072018-09-18 13:30:21 -07002490 ftr->persist_data_offset[1] = off + CRYPT_FOOTER_TO_PERSIST_OFFSET + ftr->persist_data_size;
Ken Sumrall160b4d62013-04-22 12:15:39 -07002491 }
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07002492
2493 return 0;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002494}
2495
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002496#define FRAMEWORK_BOOT_WAIT 60
2497
Paul Crowley14c8c072018-09-18 13:30:21 -07002498static int cryptfs_SHA256_fileblock(const char* filename, __le8* buf) {
2499 int fd = open(filename, O_RDONLY | O_CLOEXEC);
Paul Lawrence87999172014-02-20 12:21:31 -08002500 if (fd == -1) {
2501 SLOGE("Error opening file %s", filename);
2502 return -1;
2503 }
2504
2505 char block[CRYPT_INPLACE_BUFSIZE];
2506 memset(block, 0, sizeof(block));
2507 if (unix_read(fd, block, sizeof(block)) < 0) {
2508 SLOGE("Error reading file %s", filename);
2509 close(fd);
2510 return -1;
2511 }
2512
2513 close(fd);
2514
2515 SHA256_CTX c;
2516 SHA256_Init(&c);
2517 SHA256_Update(&c, block, sizeof(block));
2518 SHA256_Final(buf, &c);
2519
2520 return 0;
2521}
2522
Paul Lawrence7ee87cf2017-12-22 10:12:06 -08002523static int cryptfs_enable_all_volumes(struct crypt_mnt_ftr* crypt_ftr, char* crypto_blkdev,
2524 char* real_blkdev, int previously_encrypted_upto) {
Paul Crowley14c8c072018-09-18 13:30:21 -07002525 off64_t cur_encryption_done = 0, tot_encryption_size = 0;
Tim Murray8439dc92014-12-15 11:56:11 -08002526 int rc = -1;
Paul Lawrence87999172014-02-20 12:21:31 -08002527
Paul Lawrence87999172014-02-20 12:21:31 -08002528 /* The size of the userdata partition, and add in the vold volumes below */
2529 tot_encryption_size = crypt_ftr->fs_size;
2530
Paul Lawrence7ee87cf2017-12-22 10:12:06 -08002531 rc = cryptfs_enable_inplace(crypto_blkdev, real_blkdev, crypt_ftr->fs_size, &cur_encryption_done,
Paul Crowley0fd26262018-01-30 09:48:19 -08002532 tot_encryption_size, previously_encrypted_upto, true);
Paul Lawrence87999172014-02-20 12:21:31 -08002533
Paul Lawrence7ee87cf2017-12-22 10:12:06 -08002534 if (rc == ENABLE_INPLACE_ERR_DEV) {
2535 /* Hack for b/17898962 */
2536 SLOGE("cryptfs_enable: crypto block dev failure. Must reboot...\n");
2537 cryptfs_reboot(RebootType::reboot);
2538 }
JP Abgrall7fc1de82014-10-10 18:43:41 -07002539
Paul Lawrence7ee87cf2017-12-22 10:12:06 -08002540 if (!rc) {
2541 crypt_ftr->encrypted_upto = cur_encryption_done;
2542 }
Paul Lawrence87999172014-02-20 12:21:31 -08002543
Paul Lawrence7ee87cf2017-12-22 10:12:06 -08002544 if (!rc && crypt_ftr->encrypted_upto == crypt_ftr->fs_size) {
2545 /* The inplace routine never actually sets the progress to 100% due
2546 * to the round down nature of integer division, so set it here */
2547 property_set("vold.encrypt_progress", "100");
Paul Lawrence87999172014-02-20 12:21:31 -08002548 }
2549
2550 return rc;
2551}
2552
Paul Crowleyb64933a2017-10-31 08:25:55 -07002553static int vold_unmountAll(void) {
2554 VolumeManager* vm = VolumeManager::Instance();
2555 return vm->unmountAll();
2556}
2557
Paul Lawrence7ee87cf2017-12-22 10:12:06 -08002558int cryptfs_enable_internal(int crypt_type, const char* passwd, int no_ui) {
Tom Cherry4c5bde22019-01-29 14:34:01 -08002559 char crypto_blkdev[MAXPATHLEN];
2560 std::string real_blkdev;
Greg Kaiser59ad0182018-02-16 13:01:36 -08002561 unsigned char decrypted_master_key[MAX_KEY_LEN];
Paul Crowley14c8c072018-09-18 13:30:21 -07002562 int rc = -1, i;
Paul Lawrence87999172014-02-20 12:21:31 -08002563 struct crypt_mnt_ftr crypt_ftr;
Paul Crowley14c8c072018-09-18 13:30:21 -07002564 struct crypt_persist_data* pdata;
Ken Sumrall29d8da82011-05-18 17:20:07 -07002565 char encrypted_state[PROPERTY_VALUE_MAX];
Paul Crowley14c8c072018-09-18 13:30:21 -07002566 char lockid[32] = {0};
Tom Cherry4c5bde22019-01-29 14:34:01 -08002567 std::string key_loc;
Ken Sumrall29d8da82011-05-18 17:20:07 -07002568 int num_vols;
Paul Lawrence87999172014-02-20 12:21:31 -08002569 off64_t previously_encrypted_upto = 0;
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002570 bool rebootEncryption = false;
Wei Wang4375f1b2017-02-24 17:43:01 -08002571 bool onlyCreateHeader = false;
AnilKumar Chimata98dc8352018-05-11 00:25:09 +05302572#ifdef CONFIG_HW_DISK_ENCRYPTION
2573 unsigned char newpw[32];
2574 int key_index = 0;
2575#endif
2576 int index = 0;
2577
Paul Lawrence7ee87cf2017-12-22 10:12:06 -08002578 if (get_crypt_ftr_and_key(&crypt_ftr) == 0) {
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002579 if (crypt_ftr.flags & CRYPT_ENCRYPTION_IN_PROGRESS) {
2580 /* An encryption was underway and was interrupted */
2581 previously_encrypted_upto = crypt_ftr.encrypted_upto;
2582 crypt_ftr.encrypted_upto = 0;
2583 crypt_ftr.flags &= ~CRYPT_ENCRYPTION_IN_PROGRESS;
Paul Lawrence6bfed202014-07-28 12:47:22 -07002584
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002585 /* At this point, we are in an inconsistent state. Until we successfully
2586 complete encryption, a reboot will leave us broken. So mark the
2587 encryption failed in case that happens.
2588 On successfully completing encryption, remove this flag */
2589 crypt_ftr.flags |= CRYPT_INCONSISTENT_STATE;
Paul Lawrence6bfed202014-07-28 12:47:22 -07002590
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002591 put_crypt_ftr_and_key(&crypt_ftr);
2592 } else if (crypt_ftr.flags & CRYPT_FORCE_ENCRYPTION) {
2593 if (!check_ftr_sha(&crypt_ftr)) {
2594 memset(&crypt_ftr, 0, sizeof(crypt_ftr));
2595 put_crypt_ftr_and_key(&crypt_ftr);
2596 goto error_unencrypted;
2597 }
2598
2599 /* Doing a reboot-encryption*/
2600 crypt_ftr.flags &= ~CRYPT_FORCE_ENCRYPTION;
2601 crypt_ftr.flags |= CRYPT_FORCE_COMPLETE;
2602 rebootEncryption = true;
2603 }
Greg Kaiser59ad0182018-02-16 13:01:36 -08002604 } else {
2605 // We don't want to accidentally reference invalid data.
2606 memset(&crypt_ftr, 0, sizeof(crypt_ftr));
Paul Lawrence87999172014-02-20 12:21:31 -08002607 }
2608
2609 property_get("ro.crypto.state", encrypted_state, "");
2610 if (!strcmp(encrypted_state, "encrypted") && !previously_encrypted_upto) {
2611 SLOGE("Device is already running encrypted, aborting");
2612 goto error_unencrypted;
2613 }
2614
Tom Cherry4c5bde22019-01-29 14:34:01 -08002615 get_crypt_info(&key_loc, &real_blkdev);
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002616
Ken Sumrall3ed82362011-01-28 23:31:16 -08002617 /* Get the size of the real block device */
Oleksiy Avramchenko625dc782018-05-23 10:50:46 +02002618 uint64_t nr_sec;
2619 if (android::vold::GetBlockDev512Sectors(real_blkdev, &nr_sec) != android::OK) {
Tom Cherry4c5bde22019-01-29 14:34:01 -08002620 SLOGE("Cannot get size of block device %s\n", real_blkdev.c_str());
Ken Sumrall3ed82362011-01-28 23:31:16 -08002621 goto error_unencrypted;
2622 }
Ken Sumrall3ed82362011-01-28 23:31:16 -08002623
2624 /* If doing inplace encryption, make sure the orig fs doesn't include the crypto footer */
Tom Cherry4c5bde22019-01-29 14:34:01 -08002625 if (key_loc == KEY_IN_FOOTER) {
Oleksiy Avramchenko625dc782018-05-23 10:50:46 +02002626 uint64_t fs_size_sec, max_fs_size_sec;
Tom Cherry4c5bde22019-01-29 14:34:01 -08002627 fs_size_sec = get_fs_size(real_blkdev.c_str());
2628 if (fs_size_sec == 0) fs_size_sec = get_f2fs_filesystem_size_sec(real_blkdev.data());
Daniel Rosenberge82df162014-08-15 22:19:23 +00002629
Paul Lawrence87999172014-02-20 12:21:31 -08002630 max_fs_size_sec = nr_sec - (CRYPT_FOOTER_OFFSET / CRYPT_SECTOR_SIZE);
Ken Sumrall3ed82362011-01-28 23:31:16 -08002631
2632 if (fs_size_sec > max_fs_size_sec) {
2633 SLOGE("Orig filesystem overlaps crypto footer region. Cannot encrypt in place.");
2634 goto error_unencrypted;
2635 }
2636 }
2637
Ken Sumrall5d4c68e2011-01-30 19:06:03 -08002638 /* Get a wakelock as this may take a while, and we don't want the
2639 * device to sleep on us. We'll grab a partial wakelock, and if the UI
2640 * wants to keep the screen on, it can grab a full wakelock.
2641 */
Paul Crowley14c8c072018-09-18 13:30:21 -07002642 snprintf(lockid, sizeof(lockid), "enablecrypto%d", (int)getpid());
Ken Sumrall5d4c68e2011-01-30 19:06:03 -08002643 acquire_wake_lock(PARTIAL_WAKE_LOCK, lockid);
2644
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002645 /* The init files are setup to stop the class main and late start when
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002646 * vold sets trigger_shutdown_framework.
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002647 */
2648 property_set("vold.decrypt", "trigger_shutdown_framework");
2649 SLOGD("Just asked init to shut down class main\n");
2650
Jeff Sharkey9c484982015-03-31 10:35:33 -07002651 /* Ask vold to unmount all devices that it manages */
2652 if (vold_unmountAll()) {
2653 SLOGE("Failed to unmount all vold managed devices");
Ken Sumrall2eaf7132011-01-14 12:45:48 -08002654 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002655
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002656 /* no_ui means we are being called from init, not settings.
2657 Now we always reboot from settings, so !no_ui means reboot
2658 */
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002659 if (!no_ui) {
2660 /* Try fallback, which is to reboot and try there */
2661 onlyCreateHeader = true;
2662 FILE* breadcrumb = fopen(BREADCRUMB_FILE, "we");
2663 if (breadcrumb == 0) {
2664 SLOGE("Failed to create breadcrumb file");
2665 goto error_shutting_down;
2666 }
2667 fclose(breadcrumb);
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002668 }
2669
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002670 /* Start the actual work of making an encrypted filesystem */
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002671 /* Initialize a crypt_mnt_ftr for the partition */
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002672 if (previously_encrypted_upto == 0 && !rebootEncryption) {
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07002673 if (cryptfs_init_crypt_mnt_ftr(&crypt_ftr)) {
2674 goto error_shutting_down;
2675 }
Ken Sumrall160b4d62013-04-22 12:15:39 -07002676
Tom Cherry4c5bde22019-01-29 14:34:01 -08002677 if (key_loc == KEY_IN_FOOTER) {
Paul Crowley14c8c072018-09-18 13:30:21 -07002678 crypt_ftr.fs_size = nr_sec - (CRYPT_FOOTER_OFFSET / CRYPT_SECTOR_SIZE);
Paul Lawrence87999172014-02-20 12:21:31 -08002679 } else {
2680 crypt_ftr.fs_size = nr_sec;
2681 }
Paul Lawrence6bfed202014-07-28 12:47:22 -07002682 /* At this point, we are in an inconsistent state. Until we successfully
2683 complete encryption, a reboot will leave us broken. So mark the
2684 encryption failed in case that happens.
2685 On successfully completing encryption, remove this flag */
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002686 if (onlyCreateHeader) {
2687 crypt_ftr.flags |= CRYPT_FORCE_ENCRYPTION;
2688 } else {
2689 crypt_ftr.flags |= CRYPT_INCONSISTENT_STATE;
2690 }
Paul Lawrence87999172014-02-20 12:21:31 -08002691 crypt_ftr.crypt_type = crypt_type;
AnilKumar Chimata98dc8352018-05-11 00:25:09 +05302692#ifdef CONFIG_HW_DISK_ENCRYPTION
Bill Peckham0db11972018-10-10 10:25:42 -07002693 strlcpy((char*)crypt_ftr.crypto_type_name, "aes-xts",
2694 MAX_CRYPTO_TYPE_NAME_LEN);
AnilKumar Chimata98dc8352018-05-11 00:25:09 +05302695#else
Paul Crowley14c8c072018-09-18 13:30:21 -07002696 strlcpy((char*)crypt_ftr.crypto_type_name, cryptfs_get_crypto_name(),
2697 MAX_CRYPTO_TYPE_NAME_LEN);
AnilKumar Chimata98dc8352018-05-11 00:25:09 +05302698#endif
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002699
Paul Lawrence87999172014-02-20 12:21:31 -08002700 /* Make an encrypted master key */
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002701 if (create_encrypted_random_key(onlyCreateHeader ? DEFAULT_PASSWORD : passwd,
2702 crypt_ftr.master_key, crypt_ftr.salt, &crypt_ftr)) {
Paul Lawrence87999172014-02-20 12:21:31 -08002703 SLOGE("Cannot create encrypted master key\n");
2704 goto error_shutting_down;
2705 }
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002706
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002707 /* Replace scrypted intermediate key if we are preparing for a reboot */
2708 if (onlyCreateHeader) {
Greg Kaiser59ad0182018-02-16 13:01:36 -08002709 unsigned char fake_master_key[MAX_KEY_LEN];
2710 unsigned char encrypted_fake_master_key[MAX_KEY_LEN];
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002711 memset(fake_master_key, 0, sizeof(fake_master_key));
Paul Crowley14c8c072018-09-18 13:30:21 -07002712 encrypt_master_key(passwd, crypt_ftr.salt, fake_master_key, encrypted_fake_master_key,
Bill Peckham0db11972018-10-10 10:25:42 -07002713 &crypt_ftr, true);
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002714 }
2715
Paul Lawrence87999172014-02-20 12:21:31 -08002716 /* Write the key to the end of the partition */
2717 put_crypt_ftr_and_key(&crypt_ftr);
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002718
Paul Lawrence87999172014-02-20 12:21:31 -08002719 /* If any persistent data has been remembered, save it.
2720 * If none, create a valid empty table and save that.
2721 */
2722 if (!persist_data) {
Paul Crowley14c8c072018-09-18 13:30:21 -07002723 pdata = (crypt_persist_data*)malloc(CRYPT_PERSIST_DATA_SIZE);
2724 if (pdata) {
2725 init_empty_persist_data(pdata, CRYPT_PERSIST_DATA_SIZE);
2726 persist_data = pdata;
2727 }
Paul Lawrence87999172014-02-20 12:21:31 -08002728 }
2729 if (persist_data) {
2730 save_persistent_data();
2731 }
Ken Sumrall160b4d62013-04-22 12:15:39 -07002732 }
2733
AnilKumar Chimata98dc8352018-05-11 00:25:09 +05302734 /* When encryption triggered from settings, encryption starts after reboot.
2735 So set the encryption key when the actual encryption starts.
2736 */
2737#ifdef CONFIG_HW_DISK_ENCRYPTION
2738 if (previously_encrypted_upto == 0) {
2739 if (!rebootEncryption)
2740 clear_hw_device_encryption_key();
2741
2742 if (get_keymaster_hw_fde_passwd(
2743 onlyCreateHeader ? DEFAULT_PASSWORD : passwd,
2744 newpw, crypt_ftr.salt, &crypt_ftr))
2745 key_index = set_hw_device_encryption_key(
2746 onlyCreateHeader ? DEFAULT_PASSWORD : passwd,
2747 (char*)crypt_ftr.crypto_type_name);
2748 else
2749 key_index = set_hw_device_encryption_key((const char*)newpw,
2750 (char*) crypt_ftr.crypto_type_name);
2751 if (key_index < 0)
2752 goto error_shutting_down;
2753
2754 crypt_ftr.flags |= CRYPT_ASCII_PASSWORD_UPDATED;
2755 put_crypt_ftr_and_key(&crypt_ftr);
2756 }
2757#endif
2758
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002759 if (onlyCreateHeader) {
2760 sleep(2);
Josh Gaofec44372017-08-28 13:22:55 -07002761 cryptfs_reboot(RebootType::reboot);
AnilKumar Chimata98dc8352018-05-11 00:25:09 +05302762 } else {
2763 /* Do extra work for a better UX when doing the long inplace encryption */
2764 /* Now that /data is unmounted, we need to mount a tmpfs
2765 * /data, set a property saying we're doing inplace encryption,
2766 * and restart the framework.
2767 */
2768 if (fs_mgr_do_tmpfs_mount(DATA_MNT_POINT)) {
2769 goto error_shutting_down;
2770 }
2771 /* Tells the framework that inplace encryption is starting */
2772 property_set("vold.encrypt_progress", "0");
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002773
AnilKumar Chimata98dc8352018-05-11 00:25:09 +05302774 /* restart the framework. */
2775 /* Create necessary paths on /data */
2776 prep_data_fs();
2777
2778 /* Ugh, shutting down the framework is not synchronous, so until it
2779 * can be fixed, this horrible hack will wait a moment for it all to
2780 * shut down before proceeding. Without it, some devices cannot
2781 * restart the graphics services.
2782 */
2783 sleep(2);
2784
Ajay Dudani87701e22014-09-17 21:02:52 -07002785 /* startup service classes main and late_start */
2786 property_set("vold.decrypt", "trigger_restart_min_framework");
2787 SLOGD("Just triggered restart_min_framework\n");
2788
2789 /* OK, the framework is restarted and will soon be showing a
2790 * progress bar. Time to setup an encrypted mapping, and
2791 * either write a new filesystem, or encrypt in place updating
2792 * the progress bar as we work.
2793 */
2794 }
2795
Paul Lawrenced0c7b172014-08-08 14:28:10 -07002796 decrypt_master_key(passwd, decrypted_master_key, &crypt_ftr, 0, 0);
AnilKumar Chimata98dc8352018-05-11 00:25:09 +05302797#ifdef CONFIG_HW_DISK_ENCRYPTION
2798 if (is_hw_disk_encryption((char*)crypt_ftr.crypto_type_name) && is_ice_enabled())
AnilKumar Chimatad08106a2018-02-11 17:11:24 +05302799#ifdef CONFIG_HW_DISK_ENCRYPT_PERF
2800 strlcpy(crypto_blkdev, real_blkdev, sizeof(crypto_blkdev));
2801#else
Eric Arseneau2f8ce652019-02-06 14:23:39 -08002802 create_crypto_blk_dev(&crypt_ftr, (unsigned char*)&key_index, real_blkdev.c_str(), crypto_blkdev,
AnilKumar Chimata98dc8352018-05-11 00:25:09 +05302803 CRYPTO_BLOCK_DEVICE, 0);
AnilKumar Chimatad08106a2018-02-11 17:11:24 +05302804#endif
AnilKumar Chimata98dc8352018-05-11 00:25:09 +05302805 else
Eric Arseneau2f8ce652019-02-06 14:23:39 -08002806 create_crypto_blk_dev(&crypt_ftr, decrypted_master_key, real_blkdev.c_str(), crypto_blkdev,
AnilKumar Chimata98dc8352018-05-11 00:25:09 +05302807 CRYPTO_BLOCK_DEVICE, 0);
2808#else
Tom Cherry4c5bde22019-01-29 14:34:01 -08002809 create_crypto_blk_dev(&crypt_ftr, decrypted_master_key, real_blkdev.c_str(), crypto_blkdev,
Paul Crowley5afbc622017-11-27 09:42:17 -08002810 CRYPTO_BLOCK_DEVICE, 0);
AnilKumar Chimata98dc8352018-05-11 00:25:09 +05302811#endif
Ken Sumrall29d8da82011-05-18 17:20:07 -07002812
Paul Lawrence87999172014-02-20 12:21:31 -08002813 /* If we are continuing, check checksums match */
2814 rc = 0;
2815 if (previously_encrypted_upto) {
2816 __le8 hash_first_block[SHA256_DIGEST_LENGTH];
AnilKumar Chimatad08106a2018-02-11 17:11:24 +05302817#if defined(CONFIG_HW_DISK_ENCRYPTION) && defined(CONFIG_HW_DISK_ENCRYPT_PERF)
2818 if (set_ice_param(START_ENCDEC)) {
2819 SLOGE("Failed to set ICE data");
2820 goto error_shutting_down;
2821 }
2822#endif
Paul Lawrence87999172014-02-20 12:21:31 -08002823 rc = cryptfs_SHA256_fileblock(crypto_blkdev, hash_first_block);
Ken Sumrall128626f2011-06-28 18:45:14 -07002824
Paul Crowley14c8c072018-09-18 13:30:21 -07002825 if (!rc &&
2826 memcmp(hash_first_block, crypt_ftr.hash_first_block, sizeof(hash_first_block)) != 0) {
Paul Lawrence87999172014-02-20 12:21:31 -08002827 SLOGE("Checksums do not match - trigger wipe");
2828 rc = -1;
Ken Sumrall29d8da82011-05-18 17:20:07 -07002829 }
2830 }
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002831
AnilKumar Chimatad08106a2018-02-11 17:11:24 +05302832#if defined(CONFIG_HW_DISK_ENCRYPTION) && defined(CONFIG_HW_DISK_ENCRYPT_PERF)
2833 if (set_ice_param(START_ENC)) {
2834 SLOGE("Failed to set ICE data");
2835 goto error_shutting_down;
2836 }
2837#endif
Paul Lawrence87999172014-02-20 12:21:31 -08002838 if (!rc) {
Tom Cherry4c5bde22019-01-29 14:34:01 -08002839 rc = cryptfs_enable_all_volumes(&crypt_ftr, crypto_blkdev, real_blkdev.data(),
Paul Lawrence87999172014-02-20 12:21:31 -08002840 previously_encrypted_upto);
2841 }
2842
AnilKumar Chimatad08106a2018-02-11 17:11:24 +05302843#if defined(CONFIG_HW_DISK_ENCRYPTION) && defined(CONFIG_HW_DISK_ENCRYPT_PERF)
2844 if (set_ice_param(START_ENCDEC)) {
2845 SLOGE("Failed to set ICE data");
2846 goto error_shutting_down;
2847 }
2848#endif
Paul Lawrence87999172014-02-20 12:21:31 -08002849 /* Calculate checksum if we are not finished */
Paul Lawrence7ee87cf2017-12-22 10:12:06 -08002850 if (!rc && crypt_ftr.encrypted_upto != crypt_ftr.fs_size) {
Paul Crowley14c8c072018-09-18 13:30:21 -07002851 rc = cryptfs_SHA256_fileblock(crypto_blkdev, crypt_ftr.hash_first_block);
Paul Lawrence73d7a022014-06-09 14:10:09 -07002852 if (rc) {
Paul Lawrence87999172014-02-20 12:21:31 -08002853 SLOGE("Error calculating checksum for continuing encryption");
2854 rc = -1;
Ken Sumrall29d8da82011-05-18 17:20:07 -07002855 }
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002856 }
2857
2858 /* Undo the dm-crypt mapping whether we succeed or not */
AnilKumar Chimatad08106a2018-02-11 17:11:24 +05302859#if defined(CONFIG_HW_DISK_ENCRYPTION) && defined(CONFIG_HW_DISK_ENCRYPT_PERF)
2860 if (!is_ice_enabled())
2861 delete_crypto_blk_dev(CRYPTO_BLOCK_DEVICE);
2862#else
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002863 delete_crypto_blk_dev(CRYPTO_BLOCK_DEVICE);
AnilKumar Chimatad08106a2018-02-11 17:11:24 +05302864#endif
Ken Sumrall29d8da82011-05-18 17:20:07 -07002865
Paul Crowley14c8c072018-09-18 13:30:21 -07002866 if (!rc) {
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002867 /* Success */
Paul Lawrence6bfed202014-07-28 12:47:22 -07002868 crypt_ftr.flags &= ~CRYPT_INCONSISTENT_STATE;
Ken Sumrall7f7dbaa2011-02-01 15:46:41 -08002869
Paul Lawrence7ee87cf2017-12-22 10:12:06 -08002870 if (crypt_ftr.encrypted_upto != crypt_ftr.fs_size) {
Paul Lawrence87999172014-02-20 12:21:31 -08002871 SLOGD("Encrypted up to sector %lld - will continue after reboot",
2872 crypt_ftr.encrypted_upto);
Paul Lawrence6bfed202014-07-28 12:47:22 -07002873 crypt_ftr.flags |= CRYPT_ENCRYPTION_IN_PROGRESS;
Paul Lawrence87999172014-02-20 12:21:31 -08002874 }
Paul Lawrence73d7a022014-06-09 14:10:09 -07002875
Paul Lawrence6bfed202014-07-28 12:47:22 -07002876 put_crypt_ftr_and_key(&crypt_ftr);
Ken Sumralld33d4172011-02-01 00:49:13 -08002877
Paul Lawrence7ee87cf2017-12-22 10:12:06 -08002878 if (crypt_ftr.encrypted_upto == crypt_ftr.fs_size) {
2879 char value[PROPERTY_VALUE_MAX];
2880 property_get("ro.crypto.state", value, "");
2881 if (!strcmp(value, "")) {
2882 /* default encryption - continue first boot sequence */
2883 property_set("ro.crypto.state", "encrypted");
2884 property_set("ro.crypto.type", "block");
2885 release_wake_lock(lockid);
2886 if (rebootEncryption && crypt_ftr.crypt_type != CRYPT_TYPE_DEFAULT) {
2887 // Bring up cryptkeeper that will check the password and set it
2888 property_set("vold.decrypt", "trigger_shutdown_framework");
2889 sleep(2);
2890 property_set("vold.encrypt_progress", "");
2891 cryptfs_trigger_restart_min_framework();
2892 } else {
2893 cryptfs_check_passwd(DEFAULT_PASSWORD);
2894 cryptfs_restart_internal(1);
2895 }
2896 return 0;
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002897 } else {
Paul Lawrence7ee87cf2017-12-22 10:12:06 -08002898 sleep(2); /* Give the UI a chance to show 100% progress */
2899 cryptfs_reboot(RebootType::reboot);
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002900 }
Paul Lawrence87999172014-02-20 12:21:31 -08002901 } else {
Paul Lawrenceb6672e12014-08-15 07:37:28 -07002902 sleep(2); /* Partially encrypted, ensure writes flushed to ssd */
Josh Gaofec44372017-08-28 13:22:55 -07002903 cryptfs_reboot(RebootType::shutdown);
Paul Lawrence87999172014-02-20 12:21:31 -08002904 }
Ken Sumrall3ed82362011-01-28 23:31:16 -08002905 } else {
Mike Lockwoodee6d8c42012-02-15 13:43:28 -08002906 char value[PROPERTY_VALUE_MAX];
2907
Ken Sumrall319369a2012-06-27 16:30:18 -07002908 property_get("ro.vold.wipe_on_crypt_fail", value, "0");
Mike Lockwoodee6d8c42012-02-15 13:43:28 -08002909 if (!strcmp(value, "1")) {
2910 /* wipe data if encryption failed */
2911 SLOGE("encryption failed - rebooting into recovery to wipe data\n");
Wei Wang4375f1b2017-02-24 17:43:01 -08002912 std::string err;
2913 const std::vector<std::string> options = {
Paul Crowley14c8c072018-09-18 13:30:21 -07002914 "--wipe_data\n--reason=cryptfs_enable_internal\n"};
Wei Wang4375f1b2017-02-24 17:43:01 -08002915 if (!write_bootloader_message(options, &err)) {
2916 SLOGE("could not write bootloader message: %s", err.c_str());
Mike Lockwoodee6d8c42012-02-15 13:43:28 -08002917 }
Josh Gaofec44372017-08-28 13:22:55 -07002918 cryptfs_reboot(RebootType::recovery);
Mike Lockwoodee6d8c42012-02-15 13:43:28 -08002919 } else {
2920 /* set property to trigger dialog */
2921 property_set("vold.encrypt_progress", "error_partially_encrypted");
2922 release_wake_lock(lockid);
2923 }
Ken Sumrall3ed82362011-01-28 23:31:16 -08002924 return -1;
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002925 }
2926
Ken Sumrall3ed82362011-01-28 23:31:16 -08002927 /* hrm, the encrypt step claims success, but the reboot failed.
2928 * This should not happen.
2929 * Set the property and return. Hope the framework can deal with it.
2930 */
2931 property_set("vold.encrypt_progress", "error_reboot_failed");
Ken Sumrall5d4c68e2011-01-30 19:06:03 -08002932 release_wake_lock(lockid);
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002933 return rc;
Ken Sumrall3ed82362011-01-28 23:31:16 -08002934
2935error_unencrypted:
2936 property_set("vold.encrypt_progress", "error_not_encrypted");
Ken Sumrall5d4c68e2011-01-30 19:06:03 -08002937 if (lockid[0]) {
2938 release_wake_lock(lockid);
2939 }
Ken Sumrall3ed82362011-01-28 23:31:16 -08002940 return -1;
2941
2942error_shutting_down:
2943 /* we failed, and have not encrypted anthing, so the users's data is still intact,
2944 * but the framework is stopped and not restarted to show the error, so it's up to
2945 * vold to restart the system.
2946 */
Paul Crowley14c8c072018-09-18 13:30:21 -07002947 SLOGE(
2948 "Error enabling encryption after framework is shutdown, no data changed, restarting "
2949 "system");
Josh Gaofec44372017-08-28 13:22:55 -07002950 cryptfs_reboot(RebootType::reboot);
Ken Sumrall3ed82362011-01-28 23:31:16 -08002951
2952 /* shouldn't get here */
2953 property_set("vold.encrypt_progress", "error_shutting_down");
Ken Sumrall5d4c68e2011-01-30 19:06:03 -08002954 if (lockid[0]) {
2955 release_wake_lock(lockid);
2956 }
Ken Sumrall3ed82362011-01-28 23:31:16 -08002957 return -1;
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002958}
2959
Paul Lawrence7ee87cf2017-12-22 10:12:06 -08002960int cryptfs_enable(int type, const char* passwd, int no_ui) {
2961 return cryptfs_enable_internal(type, passwd, no_ui);
Paul Lawrence13486032014-02-03 13:28:11 -08002962}
2963
Paul Lawrence7ee87cf2017-12-22 10:12:06 -08002964int cryptfs_enable_default(int no_ui) {
2965 return cryptfs_enable_internal(CRYPT_TYPE_DEFAULT, DEFAULT_PASSWORD, no_ui);
Paul Lawrence13486032014-02-03 13:28:11 -08002966}
2967
Bill Peckham0db11972018-10-10 10:25:42 -07002968int cryptfs_changepw(int crypt_type, const char* currentpw, const char* newpw) {
Eric Biggersa701c452018-10-23 13:06:55 -07002969 if (fscrypt_is_native()) {
Paul Lawrence7b6b5652016-02-02 11:14:59 -08002970 SLOGE("cryptfs_changepw not valid for file encryption");
2971 return -1;
Paul Lawrence05335c32015-03-05 09:46:23 -08002972 }
2973
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002974 struct crypt_mnt_ftr crypt_ftr;
JP Abgrall933216c2015-02-11 13:44:32 -08002975 int rc;
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002976
2977 /* This is only allowed after we've successfully decrypted the master key */
Paul Lawrencef4faa572014-01-29 13:31:03 -08002978 if (!master_key_saved) {
Ken Sumrall0cc16632011-01-18 20:32:26 -08002979 SLOGE("Key not saved, aborting");
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002980 return -1;
2981 }
2982
Paul Lawrencef4faa572014-01-29 13:31:03 -08002983 if (crypt_type < 0 || crypt_type > CRYPT_TYPE_MAX_TYPE) {
2984 SLOGE("Invalid crypt_type %d", crypt_type);
2985 return -1;
2986 }
2987
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002988 /* get key */
Ken Sumrall160b4d62013-04-22 12:15:39 -07002989 if (get_crypt_ftr_and_key(&crypt_ftr)) {
Paul Lawrencef4faa572014-01-29 13:31:03 -08002990 SLOGE("Error getting crypt footer and key");
2991 return -1;
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002992 }
2993
AnilKumar Chimata98dc8352018-05-11 00:25:09 +05302994#ifdef CONFIG_HW_DISK_ENCRYPTION
2995 if(is_hw_disk_encryption((char*)crypt_ftr.crypto_type_name))
2996 return cryptfs_changepw_hw_fde(crypt_type, currentpw, newpw);
2997 else {
2998 crypt_ftr.crypt_type = crypt_type;
2999
3000 rc = encrypt_master_key(crypt_type == CRYPT_TYPE_DEFAULT ?
3001 DEFAULT_PASSWORD : newpw,
3002 crypt_ftr.salt,
3003 saved_master_key,
3004 crypt_ftr.master_key,
3005 &crypt_ftr, false);
3006 if (rc) {
3007 SLOGE("Encrypt master key failed: %d", rc);
3008 return -1;
3009 }
3010 /* save the key */
3011 put_crypt_ftr_and_key(&crypt_ftr);
3012
3013 return 0;
3014 }
3015#else
Paul Lawrencef4faa572014-01-29 13:31:03 -08003016 crypt_ftr.crypt_type = crypt_type;
3017
Paul Crowley14c8c072018-09-18 13:30:21 -07003018 rc = encrypt_master_key(crypt_type == CRYPT_TYPE_DEFAULT ? DEFAULT_PASSWORD : newpw,
Bill Peckham0db11972018-10-10 10:25:42 -07003019 crypt_ftr.salt, saved_master_key, crypt_ftr.master_key, &crypt_ftr,
3020 false);
JP Abgrall933216c2015-02-11 13:44:32 -08003021 if (rc) {
3022 SLOGE("Encrypt master key failed: %d", rc);
3023 return -1;
3024 }
Jason parks70a4b3f2011-01-28 10:10:47 -06003025 /* save the key */
Ken Sumrall160b4d62013-04-22 12:15:39 -07003026 put_crypt_ftr_and_key(&crypt_ftr);
Ken Sumrall8f869aa2010-12-03 03:47:09 -08003027
3028 return 0;
AnilKumar Chimata98dc8352018-05-11 00:25:09 +05303029#endif
Ken Sumrall8f869aa2010-12-03 03:47:09 -08003030}
Ken Sumrall160b4d62013-04-22 12:15:39 -07003031
AnilKumar Chimata98dc8352018-05-11 00:25:09 +05303032#ifdef CONFIG_HW_DISK_ENCRYPTION
3033int cryptfs_changepw_hw_fde(int crypt_type, const char *currentpw, const char *newpw)
3034{
3035 struct crypt_mnt_ftr crypt_ftr;
3036 int rc;
3037 int previous_type;
3038
3039 /* get key */
3040 if (get_crypt_ftr_and_key(&crypt_ftr)) {
3041 SLOGE("Error getting crypt footer and key");
3042 return -1;
3043 }
3044
3045 previous_type = crypt_ftr.crypt_type;
3046 int rc1;
3047 unsigned char tmp_curpw[32] = {0};
3048 rc1 = get_keymaster_hw_fde_passwd(crypt_ftr.crypt_type == CRYPT_TYPE_DEFAULT ?
3049 DEFAULT_PASSWORD : currentpw, tmp_curpw,
3050 crypt_ftr.salt, &crypt_ftr);
3051
3052 crypt_ftr.crypt_type = crypt_type;
3053
3054 int ret, rc2;
3055 unsigned char tmp_newpw[32] = {0};
3056
3057 rc2 = get_keymaster_hw_fde_passwd(crypt_type == CRYPT_TYPE_DEFAULT ?
3058 DEFAULT_PASSWORD : newpw , tmp_newpw,
3059 crypt_ftr.salt, &crypt_ftr);
3060
3061 if (is_hw_disk_encryption((char*)crypt_ftr.crypto_type_name)) {
3062 ret = update_hw_device_encryption_key(
3063 rc1 ? (previous_type == CRYPT_TYPE_DEFAULT ? DEFAULT_PASSWORD : currentpw) : (const char*)tmp_curpw,
3064 rc2 ? (crypt_type == CRYPT_TYPE_DEFAULT ? DEFAULT_PASSWORD : newpw): (const char*)tmp_newpw,
3065 (char*)crypt_ftr.crypto_type_name);
3066 if (ret) {
3067 SLOGE("Error updating device encryption hardware key ret %d", ret);
3068 return -1;
3069 } else {
3070 SLOGI("Encryption hardware key updated");
3071 }
3072 }
3073
3074 /* save the key */
3075 put_crypt_ftr_and_key(&crypt_ftr);
3076 return 0;
3077}
3078#endif
3079
Rubin Xu85c01f92014-10-13 12:49:54 +01003080static unsigned int persist_get_max_entries(int encrypted) {
3081 struct crypt_mnt_ftr crypt_ftr;
3082 unsigned int dsize;
Rubin Xu85c01f92014-10-13 12:49:54 +01003083
3084 /* If encrypted, use the values from the crypt_ftr, otherwise
3085 * use the values for the current spec.
3086 */
3087 if (encrypted) {
3088 if (get_crypt_ftr_and_key(&crypt_ftr)) {
Rubin Xud78181b2018-10-09 16:13:38 +01003089 /* Something is wrong, assume no space for entries */
3090 return 0;
Rubin Xu85c01f92014-10-13 12:49:54 +01003091 }
3092 dsize = crypt_ftr.persist_data_size;
3093 } else {
3094 dsize = CRYPT_PERSIST_DATA_SIZE;
3095 }
3096
Rubin Xud78181b2018-10-09 16:13:38 +01003097 if (dsize > sizeof(struct crypt_persist_data)) {
3098 return (dsize - sizeof(struct crypt_persist_data)) / sizeof(struct crypt_persist_entry);
3099 } else {
3100 return 0;
3101 }
Rubin Xu85c01f92014-10-13 12:49:54 +01003102}
3103
Paul Crowley14c8c072018-09-18 13:30:21 -07003104static int persist_get_key(const char* fieldname, char* value) {
Ken Sumrall160b4d62013-04-22 12:15:39 -07003105 unsigned int i;
3106
3107 if (persist_data == NULL) {
3108 return -1;
3109 }
3110 for (i = 0; i < persist_data->persist_valid_entries; i++) {
3111 if (!strncmp(persist_data->persist_entry[i].key, fieldname, PROPERTY_KEY_MAX)) {
3112 /* We found it! */
3113 strlcpy(value, persist_data->persist_entry[i].val, PROPERTY_VALUE_MAX);
3114 return 0;
3115 }
3116 }
3117
3118 return -1;
3119}
3120
Paul Crowley14c8c072018-09-18 13:30:21 -07003121static int persist_set_key(const char* fieldname, const char* value, int encrypted) {
Ken Sumrall160b4d62013-04-22 12:15:39 -07003122 unsigned int i;
3123 unsigned int num;
Ken Sumrall160b4d62013-04-22 12:15:39 -07003124 unsigned int max_persistent_entries;
Ken Sumrall160b4d62013-04-22 12:15:39 -07003125
3126 if (persist_data == NULL) {
3127 return -1;
3128 }
3129
Rubin Xu85c01f92014-10-13 12:49:54 +01003130 max_persistent_entries = persist_get_max_entries(encrypted);
Ken Sumrall160b4d62013-04-22 12:15:39 -07003131
3132 num = persist_data->persist_valid_entries;
3133
3134 for (i = 0; i < num; i++) {
3135 if (!strncmp(persist_data->persist_entry[i].key, fieldname, PROPERTY_KEY_MAX)) {
3136 /* We found an existing entry, update it! */
3137 memset(persist_data->persist_entry[i].val, 0, PROPERTY_VALUE_MAX);
3138 strlcpy(persist_data->persist_entry[i].val, value, PROPERTY_VALUE_MAX);
3139 return 0;
3140 }
3141 }
3142
3143 /* We didn't find it, add it to the end, if there is room */
3144 if (persist_data->persist_valid_entries < max_persistent_entries) {
3145 memset(&persist_data->persist_entry[num], 0, sizeof(struct crypt_persist_entry));
3146 strlcpy(persist_data->persist_entry[num].key, fieldname, PROPERTY_KEY_MAX);
3147 strlcpy(persist_data->persist_entry[num].val, value, PROPERTY_VALUE_MAX);
3148 persist_data->persist_valid_entries++;
3149 return 0;
3150 }
3151
3152 return -1;
3153}
3154
Rubin Xu85c01f92014-10-13 12:49:54 +01003155/**
3156 * Test if key is part of the multi-entry (field, index) sequence. Return non-zero if key is in the
3157 * sequence and its index is greater than or equal to index. Return 0 otherwise.
3158 */
Paul Crowley14c8c072018-09-18 13:30:21 -07003159int match_multi_entry(const char* key, const char* field, unsigned index) {
Jeff Sharkey95440eb2017-09-18 18:19:28 -06003160 std::string key_ = key;
3161 std::string field_ = field;
Rubin Xu85c01f92014-10-13 12:49:54 +01003162
Jeff Sharkey95440eb2017-09-18 18:19:28 -06003163 std::string parsed_field;
3164 unsigned parsed_index;
3165
3166 std::string::size_type split = key_.find_last_of('_');
3167 if (split == std::string::npos) {
3168 parsed_field = key_;
3169 parsed_index = 0;
3170 } else {
3171 parsed_field = key_.substr(0, split);
3172 parsed_index = std::stoi(key_.substr(split + 1));
Rubin Xu85c01f92014-10-13 12:49:54 +01003173 }
Jeff Sharkey95440eb2017-09-18 18:19:28 -06003174
3175 return parsed_field == field_ && parsed_index >= index;
Rubin Xu85c01f92014-10-13 12:49:54 +01003176}
3177
3178/*
3179 * Delete entry/entries from persist_data. If the entries are part of a multi-segment field, all
3180 * remaining entries starting from index will be deleted.
3181 * returns PERSIST_DEL_KEY_OK if deletion succeeds,
3182 * PERSIST_DEL_KEY_ERROR_NO_FIELD if the field does not exist,
3183 * and PERSIST_DEL_KEY_ERROR_OTHER if error occurs.
3184 *
3185 */
Paul Crowley14c8c072018-09-18 13:30:21 -07003186static int persist_del_keys(const char* fieldname, unsigned index) {
Rubin Xu85c01f92014-10-13 12:49:54 +01003187 unsigned int i;
3188 unsigned int j;
3189 unsigned int num;
3190
3191 if (persist_data == NULL) {
3192 return PERSIST_DEL_KEY_ERROR_OTHER;
3193 }
3194
3195 num = persist_data->persist_valid_entries;
3196
Paul Crowley14c8c072018-09-18 13:30:21 -07003197 j = 0; // points to the end of non-deleted entries.
Rubin Xu85c01f92014-10-13 12:49:54 +01003198 // Filter out to-be-deleted entries in place.
3199 for (i = 0; i < num; i++) {
3200 if (!match_multi_entry(persist_data->persist_entry[i].key, fieldname, index)) {
3201 persist_data->persist_entry[j] = persist_data->persist_entry[i];
3202 j++;
3203 }
3204 }
3205
3206 if (j < num) {
3207 persist_data->persist_valid_entries = j;
3208 // Zeroise the remaining entries
3209 memset(&persist_data->persist_entry[j], 0, (num - j) * sizeof(struct crypt_persist_entry));
3210 return PERSIST_DEL_KEY_OK;
3211 } else {
3212 // Did not find an entry matching the given fieldname
3213 return PERSIST_DEL_KEY_ERROR_NO_FIELD;
3214 }
3215}
3216
Paul Crowley14c8c072018-09-18 13:30:21 -07003217static int persist_count_keys(const char* fieldname) {
Rubin Xu85c01f92014-10-13 12:49:54 +01003218 unsigned int i;
3219 unsigned int count;
3220
3221 if (persist_data == NULL) {
3222 return -1;
3223 }
3224
3225 count = 0;
3226 for (i = 0; i < persist_data->persist_valid_entries; i++) {
3227 if (match_multi_entry(persist_data->persist_entry[i].key, fieldname, 0)) {
3228 count++;
3229 }
3230 }
3231
3232 return count;
3233}
3234
Ken Sumrall160b4d62013-04-22 12:15:39 -07003235/* Return the value of the specified field. */
Paul Crowley14c8c072018-09-18 13:30:21 -07003236int cryptfs_getfield(const char* fieldname, char* value, int len) {
Eric Biggersa701c452018-10-23 13:06:55 -07003237 if (fscrypt_is_native()) {
Paul Lawrence5a06a642016-02-03 13:39:13 -08003238 SLOGE("Cannot get field when file encrypted");
3239 return -1;
Paul Lawrence368d7942015-04-15 14:12:00 -07003240 }
3241
Ken Sumrall160b4d62013-04-22 12:15:39 -07003242 char temp_value[PROPERTY_VALUE_MAX];
Rubin Xu85c01f92014-10-13 12:49:54 +01003243 /* CRYPTO_GETFIELD_OK is success,
3244 * CRYPTO_GETFIELD_ERROR_NO_FIELD is value not set,
3245 * CRYPTO_GETFIELD_ERROR_BUF_TOO_SMALL is buffer (as given by len) too small,
3246 * CRYPTO_GETFIELD_ERROR_OTHER is any other error
Ken Sumrall160b4d62013-04-22 12:15:39 -07003247 */
Rubin Xu85c01f92014-10-13 12:49:54 +01003248 int rc = CRYPTO_GETFIELD_ERROR_OTHER;
3249 int i;
3250 char temp_field[PROPERTY_KEY_MAX];
Ken Sumrall160b4d62013-04-22 12:15:39 -07003251
3252 if (persist_data == NULL) {
3253 load_persistent_data();
3254 if (persist_data == NULL) {
3255 SLOGE("Getfield error, cannot load persistent data");
3256 goto out;
3257 }
3258 }
3259
Rubin Xu85c01f92014-10-13 12:49:54 +01003260 // Read value from persistent entries. If the original value is split into multiple entries,
3261 // stitch them back together.
Ken Sumrall160b4d62013-04-22 12:15:39 -07003262 if (!persist_get_key(fieldname, temp_value)) {
Rubin Xu85c01f92014-10-13 12:49:54 +01003263 // We found it, copy it to the caller's buffer and keep going until all entries are read.
Paul Crowley14c8c072018-09-18 13:30:21 -07003264 if (strlcpy(value, temp_value, len) >= (unsigned)len) {
Rubin Xu85c01f92014-10-13 12:49:54 +01003265 // value too small
3266 rc = CRYPTO_GETFIELD_ERROR_BUF_TOO_SMALL;
3267 goto out;
3268 }
3269 rc = CRYPTO_GETFIELD_OK;
3270
3271 for (i = 1; /* break explicitly */; i++) {
3272 if (snprintf(temp_field, sizeof(temp_field), "%s_%d", fieldname, i) >=
Paul Crowley14c8c072018-09-18 13:30:21 -07003273 (int)sizeof(temp_field)) {
Rubin Xu85c01f92014-10-13 12:49:54 +01003274 // If the fieldname is very long, we stop as soon as it begins to overflow the
3275 // maximum field length. At this point we have in fact fully read out the original
3276 // value because cryptfs_setfield would not allow fields with longer names to be
3277 // written in the first place.
3278 break;
3279 }
3280 if (!persist_get_key(temp_field, temp_value)) {
Paul Crowley14c8c072018-09-18 13:30:21 -07003281 if (strlcat(value, temp_value, len) >= (unsigned)len) {
3282 // value too small.
3283 rc = CRYPTO_GETFIELD_ERROR_BUF_TOO_SMALL;
3284 goto out;
3285 }
Rubin Xu85c01f92014-10-13 12:49:54 +01003286 } else {
3287 // Exhaust all entries.
3288 break;
3289 }
3290 }
Ken Sumrall160b4d62013-04-22 12:15:39 -07003291 } else {
3292 /* Sadness, it's not there. Return the error */
Rubin Xu85c01f92014-10-13 12:49:54 +01003293 rc = CRYPTO_GETFIELD_ERROR_NO_FIELD;
Ken Sumrall160b4d62013-04-22 12:15:39 -07003294 }
3295
3296out:
3297 return rc;
3298}
3299
3300/* Set the value of the specified field. */
Paul Crowley14c8c072018-09-18 13:30:21 -07003301int cryptfs_setfield(const char* fieldname, const char* value) {
Eric Biggersa701c452018-10-23 13:06:55 -07003302 if (fscrypt_is_native()) {
Paul Lawrence5a06a642016-02-03 13:39:13 -08003303 SLOGE("Cannot set field when file encrypted");
3304 return -1;
Paul Lawrence368d7942015-04-15 14:12:00 -07003305 }
3306
Ken Sumrall160b4d62013-04-22 12:15:39 -07003307 char encrypted_state[PROPERTY_VALUE_MAX];
Rubin Xu85c01f92014-10-13 12:49:54 +01003308 /* 0 is success, negative values are error */
3309 int rc = CRYPTO_SETFIELD_ERROR_OTHER;
Ken Sumrall160b4d62013-04-22 12:15:39 -07003310 int encrypted = 0;
Rubin Xu85c01f92014-10-13 12:49:54 +01003311 unsigned int field_id;
3312 char temp_field[PROPERTY_KEY_MAX];
3313 unsigned int num_entries;
3314 unsigned int max_keylen;
Ken Sumrall160b4d62013-04-22 12:15:39 -07003315
3316 if (persist_data == NULL) {
3317 load_persistent_data();
3318 if (persist_data == NULL) {
3319 SLOGE("Setfield error, cannot load persistent data");
3320 goto out;
3321 }
3322 }
3323
3324 property_get("ro.crypto.state", encrypted_state, "");
Paul Crowley14c8c072018-09-18 13:30:21 -07003325 if (!strcmp(encrypted_state, "encrypted")) {
Ken Sumrall160b4d62013-04-22 12:15:39 -07003326 encrypted = 1;
3327 }
3328
Rubin Xu85c01f92014-10-13 12:49:54 +01003329 // Compute the number of entries required to store value, each entry can store up to
3330 // (PROPERTY_VALUE_MAX - 1) chars
3331 if (strlen(value) == 0) {
3332 // Empty value also needs one entry to store.
3333 num_entries = 1;
3334 } else {
3335 num_entries = (strlen(value) + (PROPERTY_VALUE_MAX - 1) - 1) / (PROPERTY_VALUE_MAX - 1);
3336 }
3337
3338 max_keylen = strlen(fieldname);
3339 if (num_entries > 1) {
3340 // Need an extra "_%d" suffix.
3341 max_keylen += 1 + log10(num_entries);
3342 }
3343 if (max_keylen > PROPERTY_KEY_MAX - 1) {
3344 rc = CRYPTO_SETFIELD_ERROR_FIELD_TOO_LONG;
Ken Sumrall160b4d62013-04-22 12:15:39 -07003345 goto out;
3346 }
3347
Rubin Xu85c01f92014-10-13 12:49:54 +01003348 // Make sure we have enough space to write the new value
3349 if (persist_data->persist_valid_entries + num_entries - persist_count_keys(fieldname) >
3350 persist_get_max_entries(encrypted)) {
3351 rc = CRYPTO_SETFIELD_ERROR_VALUE_TOO_LONG;
3352 goto out;
3353 }
3354
3355 // Now that we know persist_data has enough space for value, let's delete the old field first
3356 // to make up space.
3357 persist_del_keys(fieldname, 0);
3358
3359 if (persist_set_key(fieldname, value, encrypted)) {
3360 // fail to set key, should not happen as we have already checked the available space
3361 SLOGE("persist_set_key() error during setfield()");
3362 goto out;
3363 }
3364
3365 for (field_id = 1; field_id < num_entries; field_id++) {
Greg Kaiserb610e772018-02-09 09:19:54 -08003366 snprintf(temp_field, sizeof(temp_field), "%s_%u", fieldname, field_id);
Rubin Xu85c01f92014-10-13 12:49:54 +01003367
3368 if (persist_set_key(temp_field, value + field_id * (PROPERTY_VALUE_MAX - 1), encrypted)) {
3369 // fail to set key, should not happen as we have already checked the available space.
3370 SLOGE("persist_set_key() error during setfield()");
3371 goto out;
3372 }
3373 }
3374
Ken Sumrall160b4d62013-04-22 12:15:39 -07003375 /* If we are running encrypted, save the persistent data now */
3376 if (encrypted) {
3377 if (save_persistent_data()) {
3378 SLOGE("Setfield error, cannot save persistent data");
3379 goto out;
3380 }
3381 }
3382
Rubin Xu85c01f92014-10-13 12:49:54 +01003383 rc = CRYPTO_SETFIELD_OK;
Ken Sumrall160b4d62013-04-22 12:15:39 -07003384
3385out:
3386 return rc;
3387}
Paul Lawrencef4faa572014-01-29 13:31:03 -08003388
3389/* Checks userdata. Attempt to mount the volume if default-
3390 * encrypted.
3391 * On success trigger next init phase and return 0.
3392 * Currently do not handle failure - see TODO below.
3393 */
Paul Crowley14c8c072018-09-18 13:30:21 -07003394int cryptfs_mount_default_encrypted(void) {
Paul Lawrence84274cc2016-04-15 15:41:33 -07003395 int crypt_type = cryptfs_get_password_type();
3396 if (crypt_type < 0 || crypt_type > CRYPT_TYPE_MAX_TYPE) {
3397 SLOGE("Bad crypt type - error");
3398 } else if (crypt_type != CRYPT_TYPE_DEFAULT) {
Paul Crowley14c8c072018-09-18 13:30:21 -07003399 SLOGD(
3400 "Password is not default - "
3401 "starting min framework to prompt");
Paul Lawrence84274cc2016-04-15 15:41:33 -07003402 property_set("vold.decrypt", "trigger_restart_min_framework");
3403 return 0;
3404 } else if (cryptfs_check_passwd(DEFAULT_PASSWORD) == 0) {
3405 SLOGD("Password is default - restarting filesystem");
3406 cryptfs_restart_internal(0);
3407 return 0;
Paul Lawrencef4faa572014-01-29 13:31:03 -08003408 } else {
Paul Lawrence84274cc2016-04-15 15:41:33 -07003409 SLOGE("Encrypted, default crypt type but can't decrypt");
Paul Lawrencef4faa572014-01-29 13:31:03 -08003410 }
3411
Paul Lawrence6bfed202014-07-28 12:47:22 -07003412 /** Corrupt. Allow us to boot into framework, which will detect bad
3413 crypto when it calls do_crypto_complete, then do a factory reset
Paul Lawrencef4faa572014-01-29 13:31:03 -08003414 */
Paul Lawrence6bfed202014-07-28 12:47:22 -07003415 property_set("vold.decrypt", "trigger_restart_min_framework");
Paul Lawrencef4faa572014-01-29 13:31:03 -08003416 return 0;
3417}
3418
3419/* Returns type of the password, default, pattern, pin or password.
3420 */
Paul Crowley14c8c072018-09-18 13:30:21 -07003421int cryptfs_get_password_type(void) {
Eric Biggersa701c452018-10-23 13:06:55 -07003422 if (fscrypt_is_native()) {
Paul Lawrence7b6b5652016-02-02 11:14:59 -08003423 SLOGE("cryptfs_get_password_type not valid for file encryption");
3424 return -1;
Paul Lawrence05335c32015-03-05 09:46:23 -08003425 }
3426
Paul Lawrencef4faa572014-01-29 13:31:03 -08003427 struct crypt_mnt_ftr crypt_ftr;
3428
3429 if (get_crypt_ftr_and_key(&crypt_ftr)) {
3430 SLOGE("Error getting crypt footer and key\n");
3431 return -1;
3432 }
3433
Paul Lawrence6bfed202014-07-28 12:47:22 -07003434 if (crypt_ftr.flags & CRYPT_INCONSISTENT_STATE) {
3435 return -1;
3436 }
3437
Paul Lawrencef4faa572014-01-29 13:31:03 -08003438 return crypt_ftr.crypt_type;
3439}
Paul Lawrence684dbdf2014-02-07 12:07:22 -08003440
Paul Crowley14c8c072018-09-18 13:30:21 -07003441const char* cryptfs_get_password() {
Eric Biggersa701c452018-10-23 13:06:55 -07003442 if (fscrypt_is_native()) {
Paul Lawrence7b6b5652016-02-02 11:14:59 -08003443 SLOGE("cryptfs_get_password not valid for file encryption");
3444 return 0;
Paul Lawrence05335c32015-03-05 09:46:23 -08003445 }
3446
Paul Lawrence399317e2014-03-10 13:20:50 -07003447 struct timespec now;
Paul Lawrenceef2b5be2014-11-11 12:47:03 -08003448 clock_gettime(CLOCK_BOOTTIME, &now);
Paul Lawrence399317e2014-03-10 13:20:50 -07003449 if (now.tv_sec < password_expiry_time) {
3450 return password;
3451 } else {
3452 cryptfs_clear_password();
3453 return 0;
3454 }
3455}
3456
Paul Crowley14c8c072018-09-18 13:30:21 -07003457void cryptfs_clear_password() {
Paul Lawrence399317e2014-03-10 13:20:50 -07003458 if (password) {
3459 size_t len = strlen(password);
3460 memset(password, 0, len);
3461 free(password);
3462 password = 0;
3463 password_expiry_time = 0;
3464 }
Paul Lawrence684dbdf2014-02-07 12:07:22 -08003465}
Paul Lawrence731a7a22015-04-28 22:14:15 +00003466
Paul Crowley14c8c072018-09-18 13:30:21 -07003467int cryptfs_isConvertibleToFBE() {
Tom Cherry4c5bde22019-01-29 14:34:01 -08003468 auto entry = GetEntryForMountPoint(&fstab_default, DATA_MNT_POINT);
3469 return entry && entry->fs_mgr_flags.force_fde_or_fbe;
Paul Lawrence0c247462015-10-29 10:30:57 -07003470}
AnilKumar Chimata98dc8352018-05-11 00:25:09 +05303471
3472int cryptfs_create_default_ftr(struct crypt_mnt_ftr* crypt_ftr, __attribute__((unused))int key_length)
3473{
3474 if (cryptfs_init_crypt_mnt_ftr(crypt_ftr)) {
3475 SLOGE("Failed to initialize crypt_ftr");
3476 return -1;
3477 }
3478
3479 if (create_encrypted_random_key(DEFAULT_PASSWORD, crypt_ftr->master_key,
3480 crypt_ftr->salt, crypt_ftr)) {
3481 SLOGE("Cannot create encrypted master key\n");
3482 return -1;
3483 }
3484
3485 //crypt_ftr->keysize = key_length / 8;
3486 return 0;
3487}
3488
3489int cryptfs_get_master_key(struct crypt_mnt_ftr* ftr, const char* password,
3490 unsigned char* master_key)
3491{
3492 int rc;
3493
3494 unsigned char* intermediate_key = 0;
3495 size_t intermediate_key_size = 0;
3496
3497 if (password == 0 || *password == 0) {
3498 password = DEFAULT_PASSWORD;
3499 }
3500
3501 rc = decrypt_master_key(password, master_key, ftr, &intermediate_key,
3502 &intermediate_key_size);
3503
3504 if (rc) {
3505 SLOGE("Can't calculate intermediate key");
3506 return rc;
3507 }
3508
3509 int N = 1 << ftr->N_factor;
3510 int r = 1 << ftr->r_factor;
3511 int p = 1 << ftr->p_factor;
3512
3513 unsigned char scrypted_intermediate_key[sizeof(ftr->scrypted_intermediate_key)];
3514
3515 rc = crypto_scrypt(intermediate_key, intermediate_key_size,
3516 ftr->salt, sizeof(ftr->salt), N, r, p,
3517 scrypted_intermediate_key,
3518 sizeof(scrypted_intermediate_key));
3519
3520 free(intermediate_key);
3521
3522 if (rc) {
3523 SLOGE("Can't scrypt intermediate key");
3524 return rc;
3525 }
3526
3527 return memcmp(scrypted_intermediate_key, ftr->scrypted_intermediate_key,
3528 intermediate_key_size);
3529}