blob: ed9a53ea831dd14ccfc7342089122c9e87dba6bb [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 Rosenberg65f99c92018-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 Crowleycfe39722018-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>
Logan Chiend557d762018-05-02 11:36:45 +080049#include <logwrap/logwrap.h>
50#include <openssl/evp.h>
51#include <openssl/sha.h>
Jeff Vander Stoepdf725752016-01-29 15:34:43 -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 Chimataedac9df2018-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 Crowleycfe39722018-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 Chimataedac9df2018-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 Chimataedac9df2018-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 Chimataedac9df2018-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 Chimataedac9df2018-05-11 00:25:09 +05301155#ifdef CONFIG_HW_DISK_ENCRYPTION
1156 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
1174 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 Chimataedac9df2018-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 Chimataedac9df2018-05-11 00:25:09 +05301218#ifdef CONFIG_HW_DISK_ENCRYPTION
1219 if (!strcmp(v->name, "crypt") || !strcmp(v->name, "req-crypt")) {
1220#else
Paul Crowley14c8c072018-09-18 13:30:21 -07001221 if (!strcmp(v->name, "crypt")) {
AnilKumar Chimataedac9df2018-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
Paul Crowley5afbc622017-11-27 09:42:17 -08001235static std::string extra_params_as_string(const std::vector<std::string>& extra_params_vec) {
1236 if (extra_params_vec.empty()) return "";
1237 std::string extra_params = std::to_string(extra_params_vec.size());
1238 for (const auto& p : extra_params_vec) {
1239 extra_params.append(" ");
1240 extra_params.append(p);
1241 }
1242 return extra_params;
1243}
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001244
Eric Biggersed45ec32019-01-25 10:47:55 -08001245/*
1246 * If the ro.crypto.fde_sector_size system property is set, append the
1247 * parameters to make dm-crypt use the specified crypto sector size and round
1248 * the crypto device size down to a crypto sector boundary.
1249 */
1250static int add_sector_size_param(std::vector<std::string>* extra_params_vec,
1251 struct crypt_mnt_ftr* ftr) {
Greg Kaiserab1e84a2018-12-11 12:40:51 -08001252 constexpr char DM_CRYPT_SECTOR_SIZE[] = "ro.crypto.fde_sector_size";
Eric Biggersed45ec32019-01-25 10:47:55 -08001253 char value[PROPERTY_VALUE_MAX];
Greg Kaiserab1e84a2018-12-11 12:40:51 -08001254
Eric Biggersed45ec32019-01-25 10:47:55 -08001255 if (property_get(DM_CRYPT_SECTOR_SIZE, value, "") > 0) {
1256 unsigned int sector_size;
1257
1258 if (!ParseUint(value, &sector_size) || sector_size < 512 || sector_size > 4096 ||
1259 (sector_size & (sector_size - 1)) != 0) {
1260 SLOGE("Invalid value for %s: %s. Must be >= 512, <= 4096, and a power of 2\n",
1261 DM_CRYPT_SECTOR_SIZE, value);
1262 return -1;
1263 }
1264
1265 std::string param = StringPrintf("sector_size:%u", sector_size);
Greg Kaiserab1e84a2018-12-11 12:40:51 -08001266 extra_params_vec->push_back(std::move(param));
1267
1268 // With this option, IVs will match the sector numbering, instead
1269 // of being hard-coded to being based on 512-byte sectors.
1270 extra_params_vec->emplace_back("iv_large_sectors");
Eric Biggersed45ec32019-01-25 10:47:55 -08001271
1272 // Round the crypto device size down to a crypto sector boundary.
1273 ftr->fs_size &= ~((sector_size / 512) - 1);
Greg Kaiserab1e84a2018-12-11 12:40:51 -08001274 }
Eric Biggersed45ec32019-01-25 10:47:55 -08001275 return 0;
Greg Kaiserab1e84a2018-12-11 12:40:51 -08001276}
1277
Paul Crowley5afbc622017-11-27 09:42:17 -08001278static int create_crypto_blk_dev(struct crypt_mnt_ftr* crypt_ftr, const unsigned char* master_key,
1279 const char* real_blk_name, char* crypto_blk_name, const char* name,
1280 uint32_t flags) {
1281 char buffer[DM_CRYPT_BUF_SIZE];
1282 struct dm_ioctl* io;
1283 unsigned int minor;
1284 int fd = 0;
1285 int err;
1286 int retval = -1;
1287 int version[3];
1288 int load_count;
AnilKumar Chimataedac9df2018-05-11 00:25:09 +05301289#ifdef CONFIG_HW_DISK_ENCRYPTION
1290 char encrypted_state[PROPERTY_VALUE_MAX] = {0};
1291 char progress[PROPERTY_VALUE_MAX] = {0};
1292 const char *extra_params;
AnilKumar Chimataedac9df2018-05-11 00:25:09 +05301293#endif
Neeraj Sonib66fc8a2019-06-20 11:15:00 +05301294 std::vector<std::string> extra_params_vec;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001295
Paul Crowley5afbc622017-11-27 09:42:17 -08001296 if ((fd = open("/dev/device-mapper", O_RDWR | O_CLOEXEC)) < 0) {
1297 SLOGE("Cannot open device-mapper\n");
1298 goto errout;
1299 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001300
Paul Crowley5afbc622017-11-27 09:42:17 -08001301 io = (struct dm_ioctl*)buffer;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001302
Paul Crowley5afbc622017-11-27 09:42:17 -08001303 ioctl_init(io, DM_CRYPT_BUF_SIZE, name, 0);
1304 err = ioctl(fd, DM_DEV_CREATE, io);
1305 if (err) {
1306 SLOGE("Cannot create dm-crypt device %s: %s\n", name, strerror(errno));
1307 goto errout;
1308 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001309
Paul Crowley5afbc622017-11-27 09:42:17 -08001310 /* Get the device status, in particular, the name of it's device file */
1311 ioctl_init(io, DM_CRYPT_BUF_SIZE, name, 0);
1312 if (ioctl(fd, DM_DEV_STATUS, io)) {
1313 SLOGE("Cannot retrieve dm-crypt device status\n");
1314 goto errout;
1315 }
1316 minor = (io->dev & 0xff) | ((io->dev >> 12) & 0xfff00);
1317 snprintf(crypto_blk_name, MAXPATHLEN, "/dev/block/dm-%u", minor);
Ken Sumralle919efe2012-09-29 17:07:41 -07001318
AnilKumar Chimataedac9df2018-05-11 00:25:09 +05301319#ifdef CONFIG_HW_DISK_ENCRYPTION
1320 if(is_hw_disk_encryption((char*)crypt_ftr->crypto_type_name)) {
1321 /* Set fde_enabled if either FDE completed or in-progress */
1322 property_get("ro.crypto.state", encrypted_state, ""); /* FDE completed */
1323 property_get("vold.encrypt_progress", progress, ""); /* FDE in progress */
1324 if (!strcmp(encrypted_state, "encrypted") || strcmp(progress, "")) {
1325 if (is_ice_enabled()) {
1326 if (flags & CREATE_CRYPTO_BLK_DEV_FLAGS_ALLOW_ENCRYPT_OVERRIDE)
1327 extra_params = "fde_enabled ice allow_encrypt_override";
1328 else
1329 extra_params = "fde_enabled ice";
1330 } else {
1331 if (flags & CREATE_CRYPTO_BLK_DEV_FLAGS_ALLOW_ENCRYPT_OVERRIDE)
1332 extra_params = "fde_enabled allow_encrypt_override";
1333 else
1334 extra_params = "fde_enabled";
1335 }
1336 } else {
1337 if (flags & CREATE_CRYPTO_BLK_DEV_FLAGS_ALLOW_ENCRYPT_OVERRIDE)
1338 extra_params = "fde_enabled allow_encrypt_override";
1339 else
1340 extra_params = "fde_enabled";
1341 }
Neeraj Sonib66fc8a2019-06-20 11:15:00 +05301342 load_count = load_crypto_mapping_table(crypt_ftr, master_key, real_blk_name, name, fd,
AnilKumar Chimataedac9df2018-05-11 00:25:09 +05301343 extra_params);
Neeraj Sonib66fc8a2019-06-20 11:15:00 +05301344 } else {
1345 if (!get_dm_crypt_version(fd, name, version)) {
1346 /* Support for allow_discards was added in version 1.11.0 */
1347 if ((version[0] >= 2) || ((version[0] == 1) && (version[1] >= 11))) {
1348 extra_params_vec.emplace_back("allow_discards");
1349 }
1350 }
1351 if (flags & CREATE_CRYPTO_BLK_DEV_FLAGS_ALLOW_ENCRYPT_OVERRIDE) {
1352 extra_params_vec.emplace_back("allow_encrypt_override");
1353 }
1354 if (add_sector_size_param(&extra_params_vec, crypt_ftr)) {
1355 SLOGE("Error processing dm-crypt sector size param\n");
1356 goto errout;
1357 }
1358 load_count = load_crypto_mapping_table(crypt_ftr, master_key, real_blk_name, name, fd,
1359 extra_params_as_string(extra_params_vec).c_str());
1360 }
AnilKumar Chimataedac9df2018-05-11 00:25:09 +05301361#else
Paul Crowley5afbc622017-11-27 09:42:17 -08001362 if (!get_dm_crypt_version(fd, name, version)) {
1363 /* Support for allow_discards was added in version 1.11.0 */
1364 if ((version[0] >= 2) || ((version[0] == 1) && (version[1] >= 11))) {
1365 extra_params_vec.emplace_back("allow_discards");
1366 }
1367 }
1368 if (flags & CREATE_CRYPTO_BLK_DEV_FLAGS_ALLOW_ENCRYPT_OVERRIDE) {
1369 extra_params_vec.emplace_back("allow_encrypt_override");
1370 }
Eric Biggersed45ec32019-01-25 10:47:55 -08001371 if (add_sector_size_param(&extra_params_vec, crypt_ftr)) {
1372 SLOGE("Error processing dm-crypt sector size param\n");
1373 goto errout;
1374 }
Paul Crowley5afbc622017-11-27 09:42:17 -08001375 load_count = load_crypto_mapping_table(crypt_ftr, master_key, real_blk_name, name, fd,
1376 extra_params_as_string(extra_params_vec).c_str());
AnilKumar Chimataedac9df2018-05-11 00:25:09 +05301377#endif
Paul Crowley5afbc622017-11-27 09:42:17 -08001378 if (load_count < 0) {
1379 SLOGE("Cannot load dm-crypt mapping table.\n");
1380 goto errout;
1381 } else if (load_count > 1) {
1382 SLOGI("Took %d tries to load dmcrypt table.\n", load_count);
1383 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001384
Paul Crowley5afbc622017-11-27 09:42:17 -08001385 /* Resume this device to activate it */
1386 ioctl_init(io, DM_CRYPT_BUF_SIZE, name, 0);
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001387
Paul Crowley5afbc622017-11-27 09:42:17 -08001388 if (ioctl(fd, DM_DEV_SUSPEND, io)) {
1389 SLOGE("Cannot resume the dm-crypt device\n");
1390 goto errout;
1391 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001392
Paul Crowleycfe39722018-10-30 15:59:24 -07001393 /* Ensure the dm device has been created before returning. */
1394 if (android::vold::WaitForFile(crypto_blk_name, 1s) < 0) {
1395 // WaitForFile generates a suitable log message
1396 goto errout;
1397 }
1398
Paul Crowley5afbc622017-11-27 09:42:17 -08001399 /* We made it here with no errors. Woot! */
1400 retval = 0;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001401
1402errout:
Paul Crowley14c8c072018-09-18 13:30:21 -07001403 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 -08001404
Paul Crowley14c8c072018-09-18 13:30:21 -07001405 return retval;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001406}
1407
Paul Crowley14c8c072018-09-18 13:30:21 -07001408static int delete_crypto_blk_dev(const char* name) {
1409 int fd;
1410 char buffer[DM_CRYPT_BUF_SIZE];
1411 struct dm_ioctl* io;
1412 int retval = -1;
Yue Hu9d6cc182018-12-17 17:09:55 +08001413 int err;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001414
Paul Crowley14c8c072018-09-18 13:30:21 -07001415 if ((fd = open("/dev/device-mapper", O_RDWR | O_CLOEXEC)) < 0) {
1416 SLOGE("Cannot open device-mapper\n");
1417 goto errout;
1418 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001419
Paul Crowley14c8c072018-09-18 13:30:21 -07001420 io = (struct dm_ioctl*)buffer;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001421
Paul Crowley14c8c072018-09-18 13:30:21 -07001422 ioctl_init(io, DM_CRYPT_BUF_SIZE, name, 0);
Yue Hu9d6cc182018-12-17 17:09:55 +08001423 err = ioctl(fd, DM_DEV_REMOVE, io);
1424 if (err) {
1425 SLOGE("Cannot remove dm-crypt device %s: %s\n", name, strerror(errno));
Paul Crowley14c8c072018-09-18 13:30:21 -07001426 goto errout;
1427 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001428
Paul Crowley14c8c072018-09-18 13:30:21 -07001429 /* We made it here with no errors. Woot! */
1430 retval = 0;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001431
1432errout:
Paul Crowley14c8c072018-09-18 13:30:21 -07001433 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 -08001434
Paul Crowley14c8c072018-09-18 13:30:21 -07001435 return retval;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001436}
1437
Paul Crowley14c8c072018-09-18 13:30:21 -07001438static int pbkdf2(const char* passwd, const unsigned char* salt, unsigned char* ikey,
1439 void* params UNUSED) {
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001440 SLOGI("Using pbkdf2 for cryptfs KDF");
1441
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001442 /* Turn the password into a key and IV that can decrypt the master key */
Paul Crowley14c8c072018-09-18 13:30:21 -07001443 return PKCS5_PBKDF2_HMAC_SHA1(passwd, strlen(passwd), salt, SALT_LEN, HASH_COUNT,
1444 INTERMEDIATE_BUF_SIZE, ikey) != 1;
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001445}
1446
Paul Crowley14c8c072018-09-18 13:30:21 -07001447static int scrypt(const char* passwd, const unsigned char* salt, unsigned char* ikey, void* params) {
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001448 SLOGI("Using scrypt for cryptfs KDF");
1449
Paul Crowley14c8c072018-09-18 13:30:21 -07001450 struct crypt_mnt_ftr* ftr = (struct crypt_mnt_ftr*)params;
Kenny Rootc4c70f12013-06-14 12:11:38 -07001451
1452 int N = 1 << ftr->N_factor;
1453 int r = 1 << ftr->r_factor;
1454 int p = 1 << ftr->p_factor;
1455
1456 /* Turn the password into a key and IV that can decrypt the master key */
Paul Crowley14c8c072018-09-18 13:30:21 -07001457 crypto_scrypt((const uint8_t*)passwd, strlen(passwd), salt, SALT_LEN, N, r, p, ikey,
Greg Kaiserc0de9c72018-02-14 20:05:54 -08001458 INTERMEDIATE_BUF_SIZE);
Paul Lawrencef4faa572014-01-29 13:31:03 -08001459
Paul Crowley14c8c072018-09-18 13:30:21 -07001460 return 0;
Kenny Rootc4c70f12013-06-14 12:11:38 -07001461}
1462
Paul Crowley14c8c072018-09-18 13:30:21 -07001463static int scrypt_keymaster(const char* passwd, const unsigned char* salt, unsigned char* ikey,
1464 void* params) {
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001465 SLOGI("Using scrypt with keymaster for cryptfs KDF");
1466
1467 int rc;
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001468 size_t signature_size;
1469 unsigned char* signature;
Paul Crowley14c8c072018-09-18 13:30:21 -07001470 struct crypt_mnt_ftr* ftr = (struct crypt_mnt_ftr*)params;
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001471
1472 int N = 1 << ftr->N_factor;
1473 int r = 1 << ftr->r_factor;
1474 int p = 1 << ftr->p_factor;
1475
Paul Crowley14c8c072018-09-18 13:30:21 -07001476 rc = crypto_scrypt((const uint8_t*)passwd, strlen(passwd), salt, SALT_LEN, N, r, p, ikey,
Greg Kaiserc0de9c72018-02-14 20:05:54 -08001477 INTERMEDIATE_BUF_SIZE);
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001478
1479 if (rc) {
1480 SLOGE("scrypt failed");
1481 return -1;
1482 }
1483
Paul Crowley14c8c072018-09-18 13:30:21 -07001484 if (keymaster_sign_object(ftr, ikey, INTERMEDIATE_BUF_SIZE, &signature, &signature_size)) {
Shawn Willdene17a9c42014-09-08 13:04:08 -06001485 SLOGE("Signing failed");
1486 return -1;
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001487 }
1488
Paul Crowley14c8c072018-09-18 13:30:21 -07001489 rc = crypto_scrypt(signature, signature_size, salt, SALT_LEN, N, r, p, ikey,
1490 INTERMEDIATE_BUF_SIZE);
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001491 free(signature);
1492
1493 if (rc) {
1494 SLOGE("scrypt failed");
1495 return -1;
1496 }
1497
1498 return 0;
1499}
1500
Paul Crowley14c8c072018-09-18 13:30:21 -07001501static int encrypt_master_key(const char* passwd, const unsigned char* salt,
1502 const unsigned char* decrypted_master_key,
AnilKumar Chimataedac9df2018-05-11 00:25:09 +05301503 unsigned char* encrypted_master_key, struct crypt_mnt_ftr* crypt_ftr,
1504 bool create_keymaster_key) {
Paul Crowley14c8c072018-09-18 13:30:21 -07001505 unsigned char ikey[INTERMEDIATE_BUF_SIZE] = {0};
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001506 EVP_CIPHER_CTX e_ctx;
1507 int encrypted_len, final_len;
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001508 int rc = 0;
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001509
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001510 /* Turn the password into an intermediate key and IV that can decrypt the master key */
Kenny Rootc4c70f12013-06-14 12:11:38 -07001511 get_device_scrypt_params(crypt_ftr);
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001512
1513 switch (crypt_ftr->kdf_type) {
Paul Crowley14c8c072018-09-18 13:30:21 -07001514 case KDF_SCRYPT_KEYMASTER:
AnilKumar Chimataedac9df2018-05-11 00:25:09 +05301515 if (create_keymaster_key && keymaster_create_key(crypt_ftr)) {
Paul Crowley14c8c072018-09-18 13:30:21 -07001516 SLOGE("keymaster_create_key failed");
1517 return -1;
1518 }
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001519
Paul Crowley14c8c072018-09-18 13:30:21 -07001520 if (scrypt_keymaster(passwd, salt, ikey, crypt_ftr)) {
1521 SLOGE("scrypt failed");
1522 return -1;
1523 }
1524 break;
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001525
Paul Crowley14c8c072018-09-18 13:30:21 -07001526 case KDF_SCRYPT:
1527 if (scrypt(passwd, salt, ikey, crypt_ftr)) {
1528 SLOGE("scrypt failed");
1529 return -1;
1530 }
1531 break;
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001532
Paul Crowley14c8c072018-09-18 13:30:21 -07001533 default:
1534 SLOGE("Invalid kdf_type");
1535 return -1;
Paul Lawrencef4faa572014-01-29 13:31:03 -08001536 }
Kenny Rootc4c70f12013-06-14 12:11:38 -07001537
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001538 /* Initialize the decryption engine */
Adam Langley889c4f12014-09-03 14:23:13 -07001539 EVP_CIPHER_CTX_init(&e_ctx);
Paul Crowley14c8c072018-09-18 13:30:21 -07001540 if (!EVP_EncryptInit_ex(&e_ctx, EVP_aes_128_cbc(), NULL, ikey,
1541 ikey + INTERMEDIATE_KEY_LEN_BYTES)) {
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001542 SLOGE("EVP_EncryptInit failed\n");
1543 return -1;
1544 }
1545 EVP_CIPHER_CTX_set_padding(&e_ctx, 0); /* Turn off padding as our data is block aligned */
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001546
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001547 /* Encrypt the master key */
Paul Crowley14c8c072018-09-18 13:30:21 -07001548 if (!EVP_EncryptUpdate(&e_ctx, encrypted_master_key, &encrypted_len, decrypted_master_key,
1549 crypt_ftr->keysize)) {
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001550 SLOGE("EVP_EncryptUpdate failed\n");
1551 return -1;
1552 }
Paul Crowley14c8c072018-09-18 13:30:21 -07001553 if (!EVP_EncryptFinal_ex(&e_ctx, encrypted_master_key + encrypted_len, &final_len)) {
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001554 SLOGE("EVP_EncryptFinal failed\n");
1555 return -1;
1556 }
1557
Greg Kaiser59ad0182018-02-16 13:01:36 -08001558 if (encrypted_len + final_len != static_cast<int>(crypt_ftr->keysize)) {
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001559 SLOGE("EVP_Encryption length check failed with %d, %d bytes\n", encrypted_len, final_len);
1560 return -1;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001561 }
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001562
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001563 /* Store the scrypt of the intermediate key, so we can validate if it's a
1564 password error or mount error when things go wrong.
1565 Note there's no need to check for errors, since if this is incorrect, we
1566 simply won't wipe userdata, which is the correct default behavior
1567 */
1568 int N = 1 << crypt_ftr->N_factor;
1569 int r = 1 << crypt_ftr->r_factor;
1570 int p = 1 << crypt_ftr->p_factor;
1571
Paul Crowley14c8c072018-09-18 13:30:21 -07001572 rc = crypto_scrypt(ikey, INTERMEDIATE_KEY_LEN_BYTES, crypt_ftr->salt, sizeof(crypt_ftr->salt),
1573 N, r, p, crypt_ftr->scrypted_intermediate_key,
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001574 sizeof(crypt_ftr->scrypted_intermediate_key));
1575
1576 if (rc) {
Paul Crowley14c8c072018-09-18 13:30:21 -07001577 SLOGE("encrypt_master_key: crypto_scrypt failed");
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001578 }
1579
Thurston Hou Yeen Dang06dc3112016-07-18 14:16:37 -07001580 EVP_CIPHER_CTX_cleanup(&e_ctx);
1581
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001582 return 0;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001583}
1584
Paul Crowley14c8c072018-09-18 13:30:21 -07001585static int decrypt_master_key_aux(const char* passwd, unsigned char* salt,
1586 const unsigned char* encrypted_master_key, size_t keysize,
1587 unsigned char* decrypted_master_key, kdf_func kdf,
1588 void* kdf_params, unsigned char** intermediate_key,
1589 size_t* intermediate_key_size) {
1590 unsigned char ikey[INTERMEDIATE_BUF_SIZE] = {0};
1591 EVP_CIPHER_CTX d_ctx;
1592 int decrypted_len, final_len;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001593
Paul Crowley14c8c072018-09-18 13:30:21 -07001594 /* Turn the password into an intermediate key and IV that can decrypt the
1595 master key */
1596 if (kdf(passwd, salt, ikey, kdf_params)) {
1597 SLOGE("kdf failed");
1598 return -1;
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001599 }
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001600
Paul Crowley14c8c072018-09-18 13:30:21 -07001601 /* Initialize the decryption engine */
1602 EVP_CIPHER_CTX_init(&d_ctx);
1603 if (!EVP_DecryptInit_ex(&d_ctx, EVP_aes_128_cbc(), NULL, ikey,
1604 ikey + INTERMEDIATE_KEY_LEN_BYTES)) {
1605 return -1;
1606 }
1607 EVP_CIPHER_CTX_set_padding(&d_ctx, 0); /* Turn off padding as our data is block aligned */
1608 /* Decrypt the master key */
1609 if (!EVP_DecryptUpdate(&d_ctx, decrypted_master_key, &decrypted_len, encrypted_master_key,
1610 keysize)) {
1611 return -1;
1612 }
1613 if (!EVP_DecryptFinal_ex(&d_ctx, decrypted_master_key + decrypted_len, &final_len)) {
1614 return -1;
1615 }
Thurston Hou Yeen Dang06dc3112016-07-18 14:16:37 -07001616
Paul Crowley14c8c072018-09-18 13:30:21 -07001617 if (decrypted_len + final_len != static_cast<int>(keysize)) {
1618 return -1;
1619 }
1620
1621 /* Copy intermediate key if needed by params */
1622 if (intermediate_key && intermediate_key_size) {
1623 *intermediate_key = (unsigned char*)malloc(INTERMEDIATE_KEY_LEN_BYTES);
1624 if (*intermediate_key) {
1625 memcpy(*intermediate_key, ikey, INTERMEDIATE_KEY_LEN_BYTES);
1626 *intermediate_key_size = INTERMEDIATE_KEY_LEN_BYTES;
1627 }
1628 }
1629
1630 EVP_CIPHER_CTX_cleanup(&d_ctx);
1631
1632 return 0;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001633}
1634
Paul Crowley14c8c072018-09-18 13:30:21 -07001635static void get_kdf_func(struct crypt_mnt_ftr* ftr, kdf_func* kdf, void** kdf_params) {
Paul Lawrencedb3730c2015-02-03 13:08:10 -08001636 if (ftr->kdf_type == KDF_SCRYPT_KEYMASTER) {
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001637 *kdf = scrypt_keymaster;
1638 *kdf_params = ftr;
1639 } else if (ftr->kdf_type == KDF_SCRYPT) {
Kenny Rootc4c70f12013-06-14 12:11:38 -07001640 *kdf = scrypt;
1641 *kdf_params = ftr;
1642 } else {
1643 *kdf = pbkdf2;
1644 *kdf_params = NULL;
1645 }
1646}
1647
Paul Crowley14c8c072018-09-18 13:30:21 -07001648static int decrypt_master_key(const char* passwd, unsigned char* decrypted_master_key,
1649 struct crypt_mnt_ftr* crypt_ftr, unsigned char** intermediate_key,
1650 size_t* intermediate_key_size) {
Kenny Rootc4c70f12013-06-14 12:11:38 -07001651 kdf_func kdf;
Paul Crowley14c8c072018-09-18 13:30:21 -07001652 void* kdf_params;
Kenny Rootc4c70f12013-06-14 12:11:38 -07001653 int ret;
1654
1655 get_kdf_func(crypt_ftr, &kdf, &kdf_params);
Paul Crowley14c8c072018-09-18 13:30:21 -07001656 ret = decrypt_master_key_aux(passwd, crypt_ftr->salt, crypt_ftr->master_key, crypt_ftr->keysize,
1657 decrypted_master_key, kdf, kdf_params, intermediate_key,
1658 intermediate_key_size);
Kenny Rootc4c70f12013-06-14 12:11:38 -07001659 if (ret != 0) {
1660 SLOGW("failure decrypting master key");
Kenny Rootc4c70f12013-06-14 12:11:38 -07001661 }
1662
1663 return ret;
1664}
1665
Paul Crowley14c8c072018-09-18 13:30:21 -07001666static int create_encrypted_random_key(const char* passwd, unsigned char* master_key,
1667 unsigned char* salt, struct crypt_mnt_ftr* crypt_ftr) {
Greg Kaiser59ad0182018-02-16 13:01:36 -08001668 unsigned char key_buf[MAX_KEY_LEN];
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001669
Eric Biggers3a2f7db2019-01-16 13:05:34 -08001670 /* Get some random bits for a key and salt */
1671 if (android::vold::ReadRandomBytes(sizeof(key_buf), reinterpret_cast<char*>(key_buf)) != 0) {
1672 return -1;
1673 }
1674 if (android::vold::ReadRandomBytes(SALT_LEN, reinterpret_cast<char*>(salt)) != 0) {
1675 return -1;
1676 }
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001677
1678 /* Now encrypt it with the password */
AnilKumar Chimataedac9df2018-05-11 00:25:09 +05301679 return encrypt_master_key(passwd, salt, key_buf, master_key, crypt_ftr, true);
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001680}
1681
Paul Crowley14c8c072018-09-18 13:30:21 -07001682int wait_and_unmount(const char* mountpoint, bool kill) {
Greg Hackmann955653e2014-09-24 14:55:20 -07001683 int i, err, rc;
AnilKumar Chimataedac9df2018-05-11 00:25:09 +05301684#define WAIT_UNMOUNT_COUNT 200
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001685
1686 /* Now umount the tmpfs filesystem */
Paul Crowley14c8c072018-09-18 13:30:21 -07001687 for (i = 0; i < WAIT_UNMOUNT_COUNT; i++) {
Greg Hackmann6e8440f2014-10-02 17:18:20 -07001688 if (umount(mountpoint) == 0) {
1689 break;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001690 }
Greg Hackmann6e8440f2014-10-02 17:18:20 -07001691
1692 if (errno == EINVAL) {
1693 /* EINVAL is returned if the directory is not a mountpoint,
1694 * i.e. there is no filesystem mounted there. So just get out.
1695 */
1696 break;
1697 }
1698
1699 err = errno;
1700
AnilKumar Chimataedac9df2018-05-11 00:25:09 +05301701 /* If allowed, be increasingly aggressive before the last 2 seconds */
Greg Hackmann6e8440f2014-10-02 17:18:20 -07001702 if (kill) {
AnilKumar Chimataedac9df2018-05-11 00:25:09 +05301703 if (i == (WAIT_UNMOUNT_COUNT - 30)) {
Greg Hackmann6e8440f2014-10-02 17:18:20 -07001704 SLOGW("sending SIGHUP to processes with open files\n");
Jeff Sharkey3472e522017-10-06 18:02:53 -06001705 android::vold::KillProcessesWithOpenFiles(mountpoint, SIGTERM);
AnilKumar Chimataedac9df2018-05-11 00:25:09 +05301706 } else if (i == (WAIT_UNMOUNT_COUNT - 20)) {
Greg Hackmann6e8440f2014-10-02 17:18:20 -07001707 SLOGW("sending SIGKILL to processes with open files\n");
Jeff Sharkey3472e522017-10-06 18:02:53 -06001708 android::vold::KillProcessesWithOpenFiles(mountpoint, SIGKILL);
Greg Hackmann6e8440f2014-10-02 17:18:20 -07001709 }
1710 }
1711
AnilKumar Chimataedac9df2018-05-11 00:25:09 +05301712 usleep(100000);
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001713 }
1714
1715 if (i < WAIT_UNMOUNT_COUNT) {
Paul Crowley14c8c072018-09-18 13:30:21 -07001716 SLOGD("unmounting %s succeeded\n", mountpoint);
1717 rc = 0;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001718 } else {
Paul Crowley14c8c072018-09-18 13:30:21 -07001719 android::vold::KillProcessesWithOpenFiles(mountpoint, 0);
1720 SLOGE("unmounting %s failed: %s\n", mountpoint, strerror(err));
1721 rc = -1;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001722 }
1723
1724 return rc;
1725}
1726
Paul Crowley14c8c072018-09-18 13:30:21 -07001727static void prep_data_fs(void) {
Jeff Sharkey47695b22016-02-01 17:02:29 -07001728 // NOTE: post_fs_data results in init calling back around to vold, so all
1729 // callers to this method must be async
1730
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001731 /* Do the prep of the /data filesystem */
1732 property_set("vold.post_fs_data_done", "0");
1733 property_set("vold.decrypt", "trigger_post_fs_data");
Wei Wang42e38102017-06-07 10:46:12 -07001734 SLOGD("Just triggered post_fs_data");
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001735
Ken Sumrallc5872692013-05-14 15:26:31 -07001736 /* Wait a max of 50 seconds, hopefully it takes much less */
Paul Crowley14c8c072018-09-18 13:30:21 -07001737 while (!android::base::WaitForProperty("vold.post_fs_data_done", "1", std::chrono::seconds(15))) {
Wei Wang42e38102017-06-07 10:46:12 -07001738 /* We timed out to prep /data in time. Continue wait. */
1739 SLOGE("waited 15s for vold.post_fs_data_done, still waiting...");
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001740 }
Wei Wang42e38102017-06-07 10:46:12 -07001741 SLOGD("post_fs_data done");
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001742}
1743
Paul Crowley14c8c072018-09-18 13:30:21 -07001744static void cryptfs_set_corrupt() {
Paul Lawrence74f29f12014-08-28 15:54:10 -07001745 // Mark the footer as bad
1746 struct crypt_mnt_ftr crypt_ftr;
1747 if (get_crypt_ftr_and_key(&crypt_ftr)) {
1748 SLOGE("Failed to get crypto footer - panic");
1749 return;
1750 }
1751
1752 crypt_ftr.flags |= CRYPT_DATA_CORRUPT;
1753 if (put_crypt_ftr_and_key(&crypt_ftr)) {
1754 SLOGE("Failed to set crypto footer - panic");
1755 return;
1756 }
1757}
1758
Paul Crowley14c8c072018-09-18 13:30:21 -07001759static void cryptfs_trigger_restart_min_framework() {
Paul Lawrence74f29f12014-08-28 15:54:10 -07001760 if (fs_mgr_do_tmpfs_mount(DATA_MNT_POINT)) {
Paul Crowley14c8c072018-09-18 13:30:21 -07001761 SLOGE("Failed to mount tmpfs on data - panic");
1762 return;
Paul Lawrence74f29f12014-08-28 15:54:10 -07001763 }
1764
1765 if (property_set("vold.decrypt", "trigger_post_fs_data")) {
1766 SLOGE("Failed to trigger post fs data - panic");
1767 return;
1768 }
1769
1770 if (property_set("vold.decrypt", "trigger_restart_min_framework")) {
1771 SLOGE("Failed to trigger restart min framework - panic");
1772 return;
1773 }
1774}
1775
Paul Lawrence8e3f4512014-09-08 10:11:17 -07001776/* returns < 0 on failure */
Paul Crowley14c8c072018-09-18 13:30:21 -07001777static int cryptfs_restart_internal(int restart_main) {
Yifan Hongeaca4fe2019-02-07 12:56:47 -08001778 std::string crypto_blkdev;
AnilKumar Chimata47386642018-02-11 17:11:24 +05301779#ifdef CONFIG_HW_DISK_ENCRYPTION
Yifan Hongeaca4fe2019-02-07 12:56:47 -08001780 std::string blkdev;
AnilKumar Chimata47386642018-02-11 17:11:24 +05301781#endif
Tim Murray8439dc92014-12-15 11:56:11 -08001782 int rc = -1;
Ken Sumrall0cc16632011-01-18 20:32:26 -08001783 static int restart_successful = 0;
1784
1785 /* Validate that it's OK to call this routine */
Paul Crowley14c8c072018-09-18 13:30:21 -07001786 if (!master_key_saved) {
Ken Sumrall0cc16632011-01-18 20:32:26 -08001787 SLOGE("Encrypted filesystem not validated, aborting");
1788 return -1;
1789 }
1790
1791 if (restart_successful) {
1792 SLOGE("System already restarted with encrypted disk, aborting");
1793 return -1;
1794 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001795
Paul Lawrencef4faa572014-01-29 13:31:03 -08001796 if (restart_main) {
1797 /* Here is where we shut down the framework. The init scripts
Martijn Coenenf629b002019-04-24 10:41:11 +02001798 * start all services in one of these classes: core, early_hal, hal,
1799 * main and late_start. To get to the minimal UI for PIN entry, we
1800 * need to start core, early_hal, hal and main. When we want to
1801 * shutdown the framework again, we need to stop most of the services in
1802 * these classes, but only those services that were started after
1803 * /data was mounted. This excludes critical services like vold and
1804 * ueventd, which need to keep running. We could possible stop
1805 * even fewer services, but because we want services to pick up APEX
1806 * libraries from the real /data, restarting is better, as it makes
1807 * these devices consistent with FBE devices and lets them use the
1808 * most recent code.
1809 *
1810 * Once these services have stopped, we should be able
Paul Lawrencef4faa572014-01-29 13:31:03 -08001811 * to umount the tmpfs /data, then mount the encrypted /data.
Martijn Coenenf629b002019-04-24 10:41:11 +02001812 * We then restart the class core, hal, main, and also the class
1813 * late_start.
1814 *
Paul Lawrencef4faa572014-01-29 13:31:03 -08001815 * At the moment, I've only put a few things in late_start that I know
1816 * are not needed to bring up the framework, and that also cause problems
1817 * with unmounting the tmpfs /data, but I hope to add add more services
1818 * to the late_start class as we optimize this to decrease the delay
1819 * till the user is asked for the password to the filesystem.
1820 */
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001821
Martijn Coenenf629b002019-04-24 10:41:11 +02001822 /* The init files are setup to stop the right set of services when
1823 * vold.decrypt is set to trigger_shutdown_framework.
Paul Lawrencef4faa572014-01-29 13:31:03 -08001824 */
Martijn Coenenf629b002019-04-24 10:41:11 +02001825 property_set("vold.decrypt", "trigger_shutdown_framework");
Paul Lawrencef4faa572014-01-29 13:31:03 -08001826 SLOGD("Just asked init to shut down class main\n");
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001827
Paul Lawrencef4faa572014-01-29 13:31:03 -08001828 /* Ugh, shutting down the framework is not synchronous, so until it
1829 * can be fixed, this horrible hack will wait a moment for it all to
1830 * shut down before proceeding. Without it, some devices cannot
1831 * restart the graphics services.
1832 */
1833 sleep(2);
1834 }
Ken Sumrall9dedfd42012-10-09 14:16:59 -07001835
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001836 /* Now that the framework is shutdown, we should be able to umount()
1837 * the tmpfs filesystem, and mount the real one.
1838 */
1839
AnilKumar Chimata47386642018-02-11 17:11:24 +05301840#if defined(CONFIG_HW_DISK_ENCRYPTION)
1841#if defined(CONFIG_HW_DISK_ENCRYPT_PERF)
1842 if (is_ice_enabled()) {
Yifan Hongeaca4fe2019-02-07 12:56:47 -08001843 get_crypt_info(nullptr, &blkdev);
AnilKumar Chimata47386642018-02-11 17:11:24 +05301844 if (set_ice_param(START_ENCDEC)) {
1845 SLOGE("Failed to set ICE data");
1846 return -1;
1847 }
1848 }
1849#else
Yifan Hongeaca4fe2019-02-07 12:56:47 -08001850 blkdev = android::base::GetProperty("ro.crypto.fs_crypto_blkdev", "");
1851 if (blkdev.empty()) {
AnilKumar Chimata47386642018-02-11 17:11:24 +05301852 SLOGE("fs_crypto_blkdev not set\n");
1853 return -1;
1854 }
1855 if (!(rc = wait_and_unmount(DATA_MNT_POINT, true))) {
1856#endif
1857#else
Yifan Hongeaca4fe2019-02-07 12:56:47 -08001858 crypto_blkdev = android::base::GetProperty("ro.crypto.fs_crypto_blkdev", "");
1859 if (crypto_blkdev.empty()) {
Ken Sumrall6864b7e2011-01-14 15:20:02 -08001860 SLOGE("fs_crypto_blkdev not set\n");
1861 return -1;
1862 }
1863
Paul Crowley14c8c072018-09-18 13:30:21 -07001864 if (!(rc = wait_and_unmount(DATA_MNT_POINT, true))) {
AnilKumar Chimata47386642018-02-11 17:11:24 +05301865#endif
Doug Zongker6fd57712013-12-17 09:43:23 -08001866 /* If ro.crypto.readonly is set to 1, mount the decrypted
1867 * filesystem readonly. This is used when /data is mounted by
1868 * recovery mode.
1869 */
1870 char ro_prop[PROPERTY_VALUE_MAX];
1871 property_get("ro.crypto.readonly", ro_prop, "");
Jeff Sharkey95440eb2017-09-18 18:19:28 -06001872 if (strlen(ro_prop) > 0 && std::stoi(ro_prop)) {
Tom Cherry4c5bde22019-01-29 14:34:01 -08001873 auto entry = GetEntryForMountPoint(&fstab_default, DATA_MNT_POINT);
1874 if (entry != nullptr) {
1875 entry->flags |= MS_RDONLY;
Luis Hector Chavezbbb512d2018-05-30 15:47:50 -07001876 }
Doug Zongker6fd57712013-12-17 09:43:23 -08001877 }
JP Abgrall62c7af32014-06-16 13:01:23 -07001878
Ken Sumralle5032c42012-04-01 23:58:44 -07001879 /* If that succeeded, then mount the decrypted filesystem */
Paul Lawrence8e3f4512014-09-08 10:11:17 -07001880 int retries = RETRY_MOUNT_ATTEMPTS;
1881 int mount_rc;
Jeff Vander Stoepdf725752016-01-29 15:34:43 -08001882
1883 /*
1884 * fs_mgr_do_mount runs fsck. Use setexeccon to run trusted
1885 * partitions in the fsck domain.
1886 */
LongPing Wei7f3ab952019-01-30 16:03:14 +08001887 if (setexeccon(android::vold::sFsckContext)) {
Jeff Vander Stoepdf725752016-01-29 15:34:43 -08001888 SLOGE("Failed to setexeccon");
1889 return -1;
1890 }
Daniel Rosenberg65f99c92018-08-28 01:58:49 -07001891 bool needs_cp = android::vold::cp_needsCheckpoint();
AnilKumar Chimata47386642018-02-11 17:11:24 +05301892#ifdef CONFIG_HW_DISK_ENCRYPTION
Yifan Hongeaca4fe2019-02-07 12:56:47 -08001893 while ((mount_rc = fs_mgr_do_mount(&fstab_default, DATA_MNT_POINT, blkdev.data(), 0,
AnilKumar Chimata47386642018-02-11 17:11:24 +05301894 needs_cp)) != 0) {
1895#else
Yifan Hongeaca4fe2019-02-07 12:56:47 -08001896 while ((mount_rc = fs_mgr_do_mount(&fstab_default, DATA_MNT_POINT, crypto_blkdev.data(), 0,
Daniel Rosenberg65f99c92018-08-28 01:58:49 -07001897 needs_cp)) != 0) {
AnilKumar Chimata47386642018-02-11 17:11:24 +05301898#endif
Paul Lawrence8e3f4512014-09-08 10:11:17 -07001899 if (mount_rc == FS_MGR_DOMNT_BUSY) {
1900 /* TODO: invoke something similar to
1901 Process::killProcessWithOpenFiles(DATA_MNT_POINT,
1902 retries > RETRY_MOUNT_ATTEMPT/2 ? 1 : 2 ) */
AnilKumar Chimata47386642018-02-11 17:11:24 +05301903#ifdef CONFIG_HW_DISK_ENCRYPTION
Yifan Hongeaca4fe2019-02-07 12:56:47 -08001904 SLOGI("Failed to mount %s because it is busy - waiting", blkdev.c_str());
AnilKumar Chimata47386642018-02-11 17:11:24 +05301905#else
Yifan Hongeaca4fe2019-02-07 12:56:47 -08001906 SLOGI("Failed to mount %s because it is busy - waiting", crypto_blkdev.c_str());
AnilKumar Chimata47386642018-02-11 17:11:24 +05301907#endif
Paul Lawrence8e3f4512014-09-08 10:11:17 -07001908 if (--retries) {
1909 sleep(RETRY_MOUNT_DELAY_SECONDS);
1910 } else {
1911 /* Let's hope that a reboot clears away whatever is keeping
1912 the mount busy */
Josh Gaofec44372017-08-28 13:22:55 -07001913 cryptfs_reboot(RebootType::reboot);
Paul Lawrence8e3f4512014-09-08 10:11:17 -07001914 }
1915 } else {
AnilKumar Chimataedac9df2018-05-11 00:25:09 +05301916#ifdef CONFIG_HW_DISK_ENCRYPTION
1917 if (--retries) {
1918 sleep(RETRY_MOUNT_DELAY_SECONDS);
1919 } else {
1920 SLOGE("Failed to mount decrypted data");
1921 cryptfs_set_corrupt();
1922 cryptfs_trigger_restart_min_framework();
1923 SLOGI("Started framework to offer wipe");
1924 return -1;
1925 }
1926#else
Paul Lawrence8e3f4512014-09-08 10:11:17 -07001927 SLOGE("Failed to mount decrypted data");
1928 cryptfs_set_corrupt();
1929 cryptfs_trigger_restart_min_framework();
1930 SLOGI("Started framework to offer wipe");
Jeff Vander Stoepdf725752016-01-29 15:34:43 -08001931 if (setexeccon(NULL)) {
1932 SLOGE("Failed to setexeccon");
1933 }
Paul Lawrence8e3f4512014-09-08 10:11:17 -07001934 return -1;
AnilKumar Chimataedac9df2018-05-11 00:25:09 +05301935#endif
Paul Lawrence8e3f4512014-09-08 10:11:17 -07001936 }
Paul Lawrence74f29f12014-08-28 15:54:10 -07001937 }
Jeff Vander Stoepdf725752016-01-29 15:34:43 -08001938 if (setexeccon(NULL)) {
1939 SLOGE("Failed to setexeccon");
1940 return -1;
1941 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001942
Ken Sumralle5032c42012-04-01 23:58:44 -07001943 /* Create necessary paths on /data */
Wei Wang42e38102017-06-07 10:46:12 -07001944 prep_data_fs();
Seigo Nonakae2ef0c02016-06-20 17:05:40 +09001945 property_set("vold.decrypt", "trigger_load_persist_props");
Ken Sumralle5032c42012-04-01 23:58:44 -07001946
1947 /* startup service classes main and late_start */
1948 property_set("vold.decrypt", "trigger_restart_framework");
1949 SLOGD("Just triggered restart_framework\n");
1950
1951 /* Give it a few moments to get started */
1952 sleep(1);
AnilKumar Chimata47386642018-02-11 17:11:24 +05301953#ifndef CONFIG_HW_DISK_ENCRYPT_PERF
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001954 }
AnilKumar Chimata47386642018-02-11 17:11:24 +05301955#endif
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001956
Ken Sumrall0cc16632011-01-18 20:32:26 -08001957 if (rc == 0) {
1958 restart_successful = 1;
1959 }
1960
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001961 return rc;
1962}
1963
Paul Crowley14c8c072018-09-18 13:30:21 -07001964int cryptfs_restart(void) {
Paul Lawrence05335c32015-03-05 09:46:23 -08001965 SLOGI("cryptfs_restart");
Eric Biggersa701c452018-10-23 13:06:55 -07001966 if (fscrypt_is_native()) {
Paul Lawrence7b6b5652016-02-02 11:14:59 -08001967 SLOGE("cryptfs_restart not valid for file encryption:");
1968 return -1;
Paul Lawrence05335c32015-03-05 09:46:23 -08001969 }
1970
Paul Lawrencef4faa572014-01-29 13:31:03 -08001971 /* Call internal implementation forcing a restart of main service group */
1972 return cryptfs_restart_internal(1);
1973}
1974
Paul Crowley14c8c072018-09-18 13:30:21 -07001975static int do_crypto_complete(const char* mount_point) {
1976 struct crypt_mnt_ftr crypt_ftr;
1977 char encrypted_state[PROPERTY_VALUE_MAX];
Ken Sumrall7f7dbaa2011-02-01 15:46:41 -08001978
Paul Crowley14c8c072018-09-18 13:30:21 -07001979 property_get("ro.crypto.state", encrypted_state, "");
1980 if (strcmp(encrypted_state, "encrypted")) {
1981 SLOGE("not running with encryption, aborting");
1982 return CRYPTO_COMPLETE_NOT_ENCRYPTED;
Ken Sumralle1a45852011-12-14 21:24:27 -08001983 }
Ken Sumrall7f7dbaa2011-02-01 15:46:41 -08001984
Paul Crowley14c8c072018-09-18 13:30:21 -07001985 // crypto_complete is full disk encrypted status
Eric Biggersa701c452018-10-23 13:06:55 -07001986 if (fscrypt_is_native()) {
Paul Crowley14c8c072018-09-18 13:30:21 -07001987 return CRYPTO_COMPLETE_NOT_ENCRYPTED;
1988 }
Paul Lawrence74f29f12014-08-28 15:54:10 -07001989
Paul Crowley14c8c072018-09-18 13:30:21 -07001990 if (get_crypt_ftr_and_key(&crypt_ftr)) {
Tom Cherry4c5bde22019-01-29 14:34:01 -08001991 std::string key_loc;
1992 get_crypt_info(&key_loc, nullptr);
Paul Lawrence74f29f12014-08-28 15:54:10 -07001993
Paul Crowley14c8c072018-09-18 13:30:21 -07001994 /*
1995 * Only report this error if key_loc is a file and it exists.
1996 * If the device was never encrypted, and /data is not mountable for
1997 * some reason, returning 1 should prevent the UI from presenting the
1998 * a "enter password" screen, or worse, a "press button to wipe the
1999 * device" screen.
2000 */
Tom Cherry4c5bde22019-01-29 14:34:01 -08002001 if (!key_loc.empty() && key_loc[0] == '/' && (access("key_loc", F_OK) == -1)) {
Paul Crowley14c8c072018-09-18 13:30:21 -07002002 SLOGE("master key file does not exist, aborting");
2003 return CRYPTO_COMPLETE_NOT_ENCRYPTED;
2004 } else {
2005 SLOGE("Error getting crypt footer and key\n");
2006 return CRYPTO_COMPLETE_BAD_METADATA;
2007 }
2008 }
Ken Sumrall7f7dbaa2011-02-01 15:46:41 -08002009
Paul Crowley14c8c072018-09-18 13:30:21 -07002010 // Test for possible error flags
2011 if (crypt_ftr.flags & CRYPT_ENCRYPTION_IN_PROGRESS) {
2012 SLOGE("Encryption process is partway completed\n");
2013 return CRYPTO_COMPLETE_PARTIAL;
2014 }
2015
2016 if (crypt_ftr.flags & CRYPT_INCONSISTENT_STATE) {
2017 SLOGE("Encryption process was interrupted but cannot continue\n");
2018 return CRYPTO_COMPLETE_INCONSISTENT;
2019 }
2020
2021 if (crypt_ftr.flags & CRYPT_DATA_CORRUPT) {
2022 SLOGE("Encryption is successful but data is corrupt\n");
2023 return CRYPTO_COMPLETE_CORRUPT;
2024 }
2025
2026 /* We passed the test! We shall diminish, and return to the west */
2027 return CRYPTO_COMPLETE_ENCRYPTED;
Ken Sumrall7f7dbaa2011-02-01 15:46:41 -08002028}
2029
AnilKumar Chimataedac9df2018-05-11 00:25:09 +05302030#ifdef CONFIG_HW_DISK_ENCRYPTION
2031static int test_mount_hw_encrypted_fs(struct crypt_mnt_ftr* crypt_ftr,
2032 const char *passwd, const char *mount_point, const char *label)
2033{
2034 /* Allocate enough space for a 256 bit key, but we may use less */
2035 unsigned char decrypted_master_key[32];
2036 char crypto_blkdev[MAXPATHLEN];
Yifan Hongeaca4fe2019-02-07 12:56:47 -08002037 std::string real_blkdev;
AnilKumar Chimataedac9df2018-05-11 00:25:09 +05302038 unsigned int orig_failed_decrypt_count;
2039 int rc = 0;
2040
2041 SLOGD("crypt_ftr->fs_size = %lld\n", crypt_ftr->fs_size);
2042 orig_failed_decrypt_count = crypt_ftr->failed_decrypt_count;
2043
Yifan Hongeaca4fe2019-02-07 12:56:47 -08002044 get_crypt_info(nullptr, &real_blkdev);
AnilKumar Chimataedac9df2018-05-11 00:25:09 +05302045
2046 int key_index = 0;
2047 if(is_hw_disk_encryption((char*)crypt_ftr->crypto_type_name)) {
2048 key_index = verify_and_update_hw_fde_passwd(passwd, crypt_ftr);
2049 if (key_index < 0) {
2050 rc = crypt_ftr->failed_decrypt_count;
2051 goto errout;
2052 }
2053 else {
2054 if (is_ice_enabled()) {
AnilKumar Chimata47386642018-02-11 17:11:24 +05302055#ifndef CONFIG_HW_DISK_ENCRYPT_PERF
AnilKumar Chimataedac9df2018-05-11 00:25:09 +05302056 if (create_crypto_blk_dev(crypt_ftr, (unsigned char*)&key_index,
Yifan Hongeaca4fe2019-02-07 12:56:47 -08002057 real_blkdev.c_str(), crypto_blkdev, label, 0)) {
AnilKumar Chimataedac9df2018-05-11 00:25:09 +05302058 SLOGE("Error creating decrypted block device");
2059 rc = -1;
2060 goto errout;
2061 }
AnilKumar Chimata47386642018-02-11 17:11:24 +05302062#endif
AnilKumar Chimataedac9df2018-05-11 00:25:09 +05302063 } else {
2064 if (create_crypto_blk_dev(crypt_ftr, decrypted_master_key,
Yifan Hongeaca4fe2019-02-07 12:56:47 -08002065 real_blkdev.c_str(), crypto_blkdev, label, 0)) {
AnilKumar Chimataedac9df2018-05-11 00:25:09 +05302066 SLOGE("Error creating decrypted block device");
2067 rc = -1;
2068 goto errout;
2069 }
2070 }
2071 }
2072 }
2073
2074 if (rc == 0) {
2075 crypt_ftr->failed_decrypt_count = 0;
2076 if (orig_failed_decrypt_count != 0) {
2077 put_crypt_ftr_and_key(crypt_ftr);
2078 }
2079
2080 /* Save the name of the crypto block device
2081 * so we can mount it when restarting the framework. */
AnilKumar Chimata47386642018-02-11 17:11:24 +05302082#ifdef CONFIG_HW_DISK_ENCRYPT_PERF
2083 if (!is_ice_enabled())
2084#endif
AnilKumar Chimataedac9df2018-05-11 00:25:09 +05302085 property_set("ro.crypto.fs_crypto_blkdev", crypto_blkdev);
2086 master_key_saved = 1;
2087 }
2088
2089 errout:
2090 return rc;
2091}
2092#endif
2093
Paul Crowley14c8c072018-09-18 13:30:21 -07002094static int test_mount_encrypted_fs(struct crypt_mnt_ftr* crypt_ftr, const char* passwd,
2095 const char* mount_point, const char* label) {
2096 unsigned char decrypted_master_key[MAX_KEY_LEN];
2097 char crypto_blkdev[MAXPATHLEN];
Tom Cherry4c5bde22019-01-29 14:34:01 -08002098 std::string real_blkdev;
Paul Crowley14c8c072018-09-18 13:30:21 -07002099 char tmp_mount_point[64];
2100 unsigned int orig_failed_decrypt_count;
2101 int rc;
2102 int use_keymaster = 0;
2103 int upgrade = 0;
2104 unsigned char* intermediate_key = 0;
2105 size_t intermediate_key_size = 0;
2106 int N = 1 << crypt_ftr->N_factor;
2107 int r = 1 << crypt_ftr->r_factor;
2108 int p = 1 << crypt_ftr->p_factor;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002109
Paul Crowley14c8c072018-09-18 13:30:21 -07002110 SLOGD("crypt_ftr->fs_size = %lld\n", crypt_ftr->fs_size);
2111 orig_failed_decrypt_count = crypt_ftr->failed_decrypt_count;
Ken Sumrall0cc16632011-01-18 20:32:26 -08002112
Paul Crowley14c8c072018-09-18 13:30:21 -07002113 if (!(crypt_ftr->flags & CRYPT_MNT_KEY_UNENCRYPTED)) {
2114 if (decrypt_master_key(passwd, decrypted_master_key, crypt_ftr, &intermediate_key,
2115 &intermediate_key_size)) {
2116 SLOGE("Failed to decrypt master key\n");
2117 rc = -1;
2118 goto errout;
2119 }
JP Abgrall7bdfa522013-11-15 13:42:56 -08002120 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002121
Tom Cherry4c5bde22019-01-29 14:34:01 -08002122 get_crypt_info(nullptr, &real_blkdev);
Paul Lawrencef4faa572014-01-29 13:31:03 -08002123
Paul Crowley14c8c072018-09-18 13:30:21 -07002124 // Create crypto block device - all (non fatal) code paths
2125 // need it
Tom Cherry4c5bde22019-01-29 14:34:01 -08002126 if (create_crypto_blk_dev(crypt_ftr, decrypted_master_key, real_blkdev.c_str(), crypto_blkdev,
2127 label, 0)) {
Paul Crowley14c8c072018-09-18 13:30:21 -07002128 SLOGE("Error creating decrypted block device\n");
2129 rc = -1;
2130 goto errout;
2131 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002132
Paul Crowley14c8c072018-09-18 13:30:21 -07002133 /* Work out if the problem is the password or the data */
2134 unsigned char scrypted_intermediate_key[sizeof(crypt_ftr->scrypted_intermediate_key)];
Paul Lawrenced0c7b172014-08-08 14:28:10 -07002135
Paul Crowley14c8c072018-09-18 13:30:21 -07002136 rc = crypto_scrypt(intermediate_key, intermediate_key_size, crypt_ftr->salt,
2137 sizeof(crypt_ftr->salt), N, r, p, scrypted_intermediate_key,
2138 sizeof(scrypted_intermediate_key));
Paul Lawrenced0c7b172014-08-08 14:28:10 -07002139
Paul Crowley14c8c072018-09-18 13:30:21 -07002140 // Does the key match the crypto footer?
2141 if (rc == 0 && memcmp(scrypted_intermediate_key, crypt_ftr->scrypted_intermediate_key,
2142 sizeof(scrypted_intermediate_key)) == 0) {
2143 SLOGI("Password matches");
2144 rc = 0;
Paul Lawrence74f29f12014-08-28 15:54:10 -07002145 } else {
Paul Crowley14c8c072018-09-18 13:30:21 -07002146 /* Try mounting the file system anyway, just in case the problem's with
2147 * the footer, not the key. */
2148 snprintf(tmp_mount_point, sizeof(tmp_mount_point), "%s/tmp_mnt", mount_point);
2149 mkdir(tmp_mount_point, 0755);
Tom Cherry4c5bde22019-01-29 14:34:01 -08002150 if (fs_mgr_do_mount(&fstab_default, DATA_MNT_POINT, crypto_blkdev, tmp_mount_point)) {
Paul Crowley14c8c072018-09-18 13:30:21 -07002151 SLOGE("Error temp mounting decrypted block device\n");
2152 delete_crypto_blk_dev(label);
Paul Lawrence74f29f12014-08-28 15:54:10 -07002153
Paul Crowley14c8c072018-09-18 13:30:21 -07002154 rc = ++crypt_ftr->failed_decrypt_count;
2155 put_crypt_ftr_and_key(crypt_ftr);
2156 } else {
2157 /* Success! */
2158 SLOGI("Password did not match but decrypted drive mounted - continue");
2159 umount(tmp_mount_point);
2160 rc = 0;
Paul Lawrenceb2f682b2014-09-08 11:28:19 -07002161 }
JP Abgrall7bdfa522013-11-15 13:42:56 -08002162 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002163
Paul Crowley14c8c072018-09-18 13:30:21 -07002164 if (rc == 0) {
2165 crypt_ftr->failed_decrypt_count = 0;
2166 if (orig_failed_decrypt_count != 0) {
2167 put_crypt_ftr_and_key(crypt_ftr);
2168 }
2169
2170 /* Save the name of the crypto block device
2171 * so we can mount it when restarting the framework. */
2172 property_set("ro.crypto.fs_crypto_blkdev", crypto_blkdev);
2173
2174 /* Also save a the master key so we can reencrypted the key
2175 * the key when we want to change the password on it. */
2176 memcpy(saved_master_key, decrypted_master_key, crypt_ftr->keysize);
2177 saved_mount_point = strdup(mount_point);
2178 master_key_saved = 1;
2179 SLOGD("%s(): Master key saved\n", __FUNCTION__);
2180 rc = 0;
2181
2182 // Upgrade if we're not using the latest KDF.
2183 use_keymaster = keymaster_check_compatibility();
2184 if (crypt_ftr->kdf_type == KDF_SCRYPT_KEYMASTER) {
2185 // Don't allow downgrade
2186 } else if (use_keymaster == 1 && crypt_ftr->kdf_type != KDF_SCRYPT_KEYMASTER) {
2187 crypt_ftr->kdf_type = KDF_SCRYPT_KEYMASTER;
2188 upgrade = 1;
2189 } else if (use_keymaster == 0 && crypt_ftr->kdf_type != KDF_SCRYPT) {
2190 crypt_ftr->kdf_type = KDF_SCRYPT;
2191 upgrade = 1;
2192 }
2193
2194 if (upgrade) {
2195 rc = encrypt_master_key(passwd, crypt_ftr->salt, saved_master_key,
AnilKumar Chimataedac9df2018-05-11 00:25:09 +05302196 crypt_ftr->master_key, crypt_ftr, true);
Paul Crowley14c8c072018-09-18 13:30:21 -07002197 if (!rc) {
2198 rc = put_crypt_ftr_and_key(crypt_ftr);
2199 }
2200 SLOGD("Key Derivation Function upgrade: rc=%d\n", rc);
2201
2202 // Do not fail even if upgrade failed - machine is bootable
2203 // Note that if this code is ever hit, there is a *serious* problem
2204 // since KDFs should never fail. You *must* fix the kdf before
2205 // proceeding!
2206 if (rc) {
2207 SLOGW(
2208 "Upgrade failed with error %d,"
2209 " but continuing with previous state",
2210 rc);
2211 rc = 0;
2212 }
2213 }
2214 }
2215
2216errout:
2217 if (intermediate_key) {
2218 memset(intermediate_key, 0, intermediate_key_size);
2219 free(intermediate_key);
2220 }
2221 return rc;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002222}
2223
Ken Sumrall29d8da82011-05-18 17:20:07 -07002224/*
Jeff Sharkey9c484982015-03-31 10:35:33 -07002225 * Called by vold when it's asked to mount an encrypted external
2226 * storage volume. The incoming partition has no crypto header/footer,
Greg Kaiser57f9af62018-02-16 13:13:58 -08002227 * as any metadata is been stored in a separate, small partition. We
2228 * assume it must be using our same crypt type and keysize.
Jeff Sharkey9c484982015-03-31 10:35:33 -07002229 *
2230 * out_crypto_blkdev must be MAXPATHLEN.
Ken Sumrall29d8da82011-05-18 17:20:07 -07002231 */
Paul Crowley14c8c072018-09-18 13:30:21 -07002232int cryptfs_setup_ext_volume(const char* label, const char* real_blkdev, const unsigned char* key,
2233 char* out_crypto_blkdev) {
Oleksiy Avramchenko625dc782018-05-23 10:50:46 +02002234 uint64_t nr_sec = 0;
2235 if (android::vold::GetBlockDev512Sectors(real_blkdev, &nr_sec) != android::OK) {
Jeff Sharkey9c484982015-03-31 10:35:33 -07002236 SLOGE("Failed to get size of %s: %s", real_blkdev, strerror(errno));
Ken Sumrall29d8da82011-05-18 17:20:07 -07002237 return -1;
2238 }
2239
Jeff Sharkey9c484982015-03-31 10:35:33 -07002240 struct crypt_mnt_ftr ext_crypt_ftr;
2241 memset(&ext_crypt_ftr, 0, sizeof(ext_crypt_ftr));
2242 ext_crypt_ftr.fs_size = nr_sec;
Greg Kaiser57f9af62018-02-16 13:13:58 -08002243 ext_crypt_ftr.keysize = cryptfs_get_keysize();
Paul Crowley14c8c072018-09-18 13:30:21 -07002244 strlcpy((char*)ext_crypt_ftr.crypto_type_name, cryptfs_get_crypto_name(),
Jeff Sharkey32ebb732017-03-27 16:18:50 -06002245 MAX_CRYPTO_TYPE_NAME_LEN);
Paul Crowley385cb8c2018-03-29 13:27:23 -07002246 uint32_t flags = 0;
Eric Biggersa701c452018-10-23 13:06:55 -07002247 if (fscrypt_is_native() &&
Paul Crowley385cb8c2018-03-29 13:27:23 -07002248 android::base::GetBoolProperty("ro.crypto.allow_encrypt_override", false))
2249 flags |= CREATE_CRYPTO_BLK_DEV_FLAGS_ALLOW_ENCRYPT_OVERRIDE;
Ken Sumrall29d8da82011-05-18 17:20:07 -07002250
Paul Crowley385cb8c2018-03-29 13:27:23 -07002251 return create_crypto_blk_dev(&ext_crypt_ftr, key, real_blkdev, out_crypto_blkdev, label, flags);
Jeff Sharkey9c484982015-03-31 10:35:33 -07002252}
Ken Sumrall29d8da82011-05-18 17:20:07 -07002253
Jeff Sharkey9c484982015-03-31 10:35:33 -07002254/*
2255 * Called by vold when it's asked to unmount an encrypted external
2256 * storage volume.
2257 */
2258int cryptfs_revert_ext_volume(const char* label) {
Paul Crowley14c8c072018-09-18 13:30:21 -07002259 return delete_crypto_blk_dev((char*)label);
Ken Sumrall29d8da82011-05-18 17:20:07 -07002260}
2261
Paul Crowley14c8c072018-09-18 13:30:21 -07002262int cryptfs_crypto_complete(void) {
2263 return do_crypto_complete("/data");
Ken Sumrall7f7dbaa2011-02-01 15:46:41 -08002264}
2265
Paul Crowley14c8c072018-09-18 13:30:21 -07002266int check_unmounted_and_get_ftr(struct crypt_mnt_ftr* crypt_ftr) {
Paul Lawrencef4faa572014-01-29 13:31:03 -08002267 char encrypted_state[PROPERTY_VALUE_MAX];
2268 property_get("ro.crypto.state", encrypted_state, "");
Paul Crowley14c8c072018-09-18 13:30:21 -07002269 if (master_key_saved || strcmp(encrypted_state, "encrypted")) {
2270 SLOGE(
2271 "encrypted fs already validated or not running with encryption,"
2272 " aborting");
Paul Lawrencef4faa572014-01-29 13:31:03 -08002273 return -1;
2274 }
2275
2276 if (get_crypt_ftr_and_key(crypt_ftr)) {
2277 SLOGE("Error getting crypt footer and key");
2278 return -1;
2279 }
2280
2281 return 0;
2282}
2283
AnilKumar Chimataedac9df2018-05-11 00:25:09 +05302284#ifdef CONFIG_HW_DISK_ENCRYPTION
2285int cryptfs_check_passwd_hw(const char* passwd)
2286{
2287 struct crypt_mnt_ftr crypt_ftr;
2288 int rc;
2289 unsigned char master_key[KEY_LEN_BYTES];
2290
2291 /* get key */
2292 if (get_crypt_ftr_and_key(&crypt_ftr)) {
2293 SLOGE("Error getting crypt footer and key");
2294 return -1;
2295 }
2296
2297 /*
2298 * in case of manual encryption (from GUI), the encryption is done with
2299 * default password
2300 */
2301 if (crypt_ftr.flags & CRYPT_FORCE_COMPLETE) {
2302 /* compare scrypted_intermediate_key with stored scrypted_intermediate_key
2303 * which was created with actual password before reboot.
2304 */
2305 rc = cryptfs_get_master_key(&crypt_ftr, passwd, master_key);
2306 if (rc) {
2307 SLOGE("password doesn't match");
2308 rc = ++crypt_ftr.failed_decrypt_count;
2309 put_crypt_ftr_and_key(&crypt_ftr);
2310 return rc;
2311 }
2312
2313 rc = test_mount_hw_encrypted_fs(&crypt_ftr, DEFAULT_PASSWORD,
2314 DATA_MNT_POINT, CRYPTO_BLOCK_DEVICE);
2315
2316 if (rc) {
2317 SLOGE("Default password did not match on reboot encryption");
2318 return rc;
2319 }
2320
2321 crypt_ftr.flags &= ~CRYPT_FORCE_COMPLETE;
2322 put_crypt_ftr_and_key(&crypt_ftr);
2323 rc = cryptfs_changepw(crypt_ftr.crypt_type, DEFAULT_PASSWORD, passwd);
2324 if (rc) {
2325 SLOGE("Could not change password on reboot encryption");
2326 return rc;
2327 }
2328 } else
2329 rc = test_mount_hw_encrypted_fs(&crypt_ftr, passwd,
2330 DATA_MNT_POINT, CRYPTO_BLOCK_DEVICE);
2331
2332 if (crypt_ftr.crypt_type != CRYPT_TYPE_DEFAULT) {
2333 cryptfs_clear_password();
2334 password = strdup(passwd);
2335 struct timespec now;
2336 clock_gettime(CLOCK_BOOTTIME, &now);
2337 password_expiry_time = now.tv_sec + password_max_age_seconds;
2338 }
2339
2340 return rc;
2341}
2342#endif
2343
Paul Crowley14c8c072018-09-18 13:30:21 -07002344int cryptfs_check_passwd(const char* passwd) {
Paul Lawrence05335c32015-03-05 09:46:23 -08002345 SLOGI("cryptfs_check_passwd");
Eric Biggersa701c452018-10-23 13:06:55 -07002346 if (fscrypt_is_native()) {
Paul Lawrence7b6b5652016-02-02 11:14:59 -08002347 SLOGE("cryptfs_check_passwd not valid for file encryption");
2348 return -1;
Paul Lawrence05335c32015-03-05 09:46:23 -08002349 }
2350
Paul Lawrencef4faa572014-01-29 13:31:03 -08002351 struct crypt_mnt_ftr crypt_ftr;
2352 int rc;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002353
Paul Lawrencef4faa572014-01-29 13:31:03 -08002354 rc = check_unmounted_and_get_ftr(&crypt_ftr);
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002355 if (rc) {
2356 SLOGE("Could not get footer");
Paul Lawrencef4faa572014-01-29 13:31:03 -08002357 return rc;
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002358 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002359
AnilKumar Chimataedac9df2018-05-11 00:25:09 +05302360#ifdef CONFIG_HW_DISK_ENCRYPTION
2361 if (is_hw_disk_encryption((char*)crypt_ftr.crypto_type_name))
2362 return cryptfs_check_passwd_hw(passwd);
2363#endif
2364
Paul Crowley14c8c072018-09-18 13:30:21 -07002365 rc = test_mount_encrypted_fs(&crypt_ftr, passwd, DATA_MNT_POINT, CRYPTO_BLOCK_DEVICE);
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002366 if (rc) {
2367 SLOGE("Password did not match");
2368 return rc;
2369 }
Paul Lawrence684dbdf2014-02-07 12:07:22 -08002370
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002371 if (crypt_ftr.flags & CRYPT_FORCE_COMPLETE) {
2372 // Here we have a default actual password but a real password
2373 // we must test against the scrypted value
2374 // First, we must delete the crypto block device that
2375 // test_mount_encrypted_fs leaves behind as a side effect
2376 delete_crypto_blk_dev(CRYPTO_BLOCK_DEVICE);
Paul Crowley14c8c072018-09-18 13:30:21 -07002377 rc = test_mount_encrypted_fs(&crypt_ftr, DEFAULT_PASSWORD, DATA_MNT_POINT,
2378 CRYPTO_BLOCK_DEVICE);
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002379 if (rc) {
2380 SLOGE("Default password did not match on reboot encryption");
2381 return rc;
2382 }
2383
2384 crypt_ftr.flags &= ~CRYPT_FORCE_COMPLETE;
2385 put_crypt_ftr_and_key(&crypt_ftr);
AnilKumar Chimataedac9df2018-05-11 00:25:09 +05302386 rc = cryptfs_changepw(crypt_ftr.crypt_type, DEFAULT_PASSWORD, passwd);
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002387 if (rc) {
2388 SLOGE("Could not change password on reboot encryption");
2389 return rc;
2390 }
2391 }
2392
2393 if (crypt_ftr.crypt_type != CRYPT_TYPE_DEFAULT) {
Paul Lawrence399317e2014-03-10 13:20:50 -07002394 cryptfs_clear_password();
2395 password = strdup(passwd);
2396 struct timespec now;
2397 clock_gettime(CLOCK_BOOTTIME, &now);
2398 password_expiry_time = now.tv_sec + password_max_age_seconds;
Paul Lawrence684dbdf2014-02-07 12:07:22 -08002399 }
2400
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002401 return rc;
2402}
2403
Paul Crowley14c8c072018-09-18 13:30:21 -07002404int cryptfs_verify_passwd(const char* passwd) {
Ken Sumrall3ad90722011-10-04 20:38:29 -07002405 struct crypt_mnt_ftr crypt_ftr;
Greg Kaiser59ad0182018-02-16 13:01:36 -08002406 unsigned char decrypted_master_key[MAX_KEY_LEN];
Ken Sumrall3ad90722011-10-04 20:38:29 -07002407 char encrypted_state[PROPERTY_VALUE_MAX];
2408 int rc;
2409
2410 property_get("ro.crypto.state", encrypted_state, "");
Paul Crowley14c8c072018-09-18 13:30:21 -07002411 if (strcmp(encrypted_state, "encrypted")) {
Ken Sumrall3ad90722011-10-04 20:38:29 -07002412 SLOGE("device not encrypted, aborting");
2413 return -2;
2414 }
2415
2416 if (!master_key_saved) {
2417 SLOGE("encrypted fs not yet mounted, aborting");
2418 return -1;
2419 }
2420
2421 if (!saved_mount_point) {
2422 SLOGE("encrypted fs failed to save mount point, aborting");
2423 return -1;
2424 }
2425
Ken Sumrall160b4d62013-04-22 12:15:39 -07002426 if (get_crypt_ftr_and_key(&crypt_ftr)) {
Ken Sumrall3ad90722011-10-04 20:38:29 -07002427 SLOGE("Error getting crypt footer and key\n");
2428 return -1;
2429 }
2430
2431 if (crypt_ftr.flags & CRYPT_MNT_KEY_UNENCRYPTED) {
2432 /* If the device has no password, then just say the password is valid */
2433 rc = 0;
2434 } else {
AnilKumar Chimataedac9df2018-05-11 00:25:09 +05302435#ifdef CONFIG_HW_DISK_ENCRYPTION
2436 if(is_hw_disk_encryption((char*)crypt_ftr.crypto_type_name)) {
2437 if (verify_hw_fde_passwd(passwd, &crypt_ftr) >= 0)
2438 rc = 0;
2439 else
2440 rc = -1;
2441 } else {
2442 decrypt_master_key(passwd, decrypted_master_key, &crypt_ftr, 0, 0);
2443 if (!memcmp(decrypted_master_key, saved_master_key, crypt_ftr.keysize)) {
2444 /* They match, the password is correct */
2445 rc = 0;
2446 } else {
2447 /* If incorrect, sleep for a bit to prevent dictionary attacks */
2448 sleep(1);
2449 rc = 1;
2450 }
2451 }
2452#else
Paul Lawrenced0c7b172014-08-08 14:28:10 -07002453 decrypt_master_key(passwd, decrypted_master_key, &crypt_ftr, 0, 0);
Ken Sumrall3ad90722011-10-04 20:38:29 -07002454 if (!memcmp(decrypted_master_key, saved_master_key, crypt_ftr.keysize)) {
2455 /* They match, the password is correct */
2456 rc = 0;
2457 } else {
2458 /* If incorrect, sleep for a bit to prevent dictionary attacks */
2459 sleep(1);
2460 rc = 1;
2461 }
AnilKumar Chimataedac9df2018-05-11 00:25:09 +05302462#endif
Ken Sumrall3ad90722011-10-04 20:38:29 -07002463 }
2464
2465 return rc;
2466}
2467
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002468/* Initialize a crypt_mnt_ftr structure. The keysize is
Greg Kaiser57f9af62018-02-16 13:13:58 -08002469 * defaulted to cryptfs_get_keysize() bytes, and the filesystem size to 0.
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002470 * Presumably, at a minimum, the caller will update the
2471 * filesystem size and crypto_type_name after calling this function.
2472 */
Paul Crowley14c8c072018-09-18 13:30:21 -07002473static int cryptfs_init_crypt_mnt_ftr(struct crypt_mnt_ftr* ftr) {
Ken Sumrall160b4d62013-04-22 12:15:39 -07002474 off64_t off;
2475
2476 memset(ftr, 0, sizeof(struct crypt_mnt_ftr));
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002477 ftr->magic = CRYPT_MNT_MAGIC;
Kenny Rootc96a5f82013-06-14 12:08:28 -07002478 ftr->major_version = CURRENT_MAJOR_VERSION;
2479 ftr->minor_version = CURRENT_MINOR_VERSION;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002480 ftr->ftr_size = sizeof(struct crypt_mnt_ftr);
Greg Kaiser57f9af62018-02-16 13:13:58 -08002481 ftr->keysize = cryptfs_get_keysize();
Ken Sumrall160b4d62013-04-22 12:15:39 -07002482
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07002483 switch (keymaster_check_compatibility()) {
Paul Crowley14c8c072018-09-18 13:30:21 -07002484 case 1:
2485 ftr->kdf_type = KDF_SCRYPT_KEYMASTER;
2486 break;
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07002487
Paul Crowley14c8c072018-09-18 13:30:21 -07002488 case 0:
2489 ftr->kdf_type = KDF_SCRYPT;
2490 break;
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07002491
Paul Crowley14c8c072018-09-18 13:30:21 -07002492 default:
2493 SLOGE("keymaster_check_compatibility failed");
2494 return -1;
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07002495 }
2496
Kenny Rootc4c70f12013-06-14 12:11:38 -07002497 get_device_scrypt_params(ftr);
2498
Ken Sumrall160b4d62013-04-22 12:15:39 -07002499 ftr->persist_data_size = CRYPT_PERSIST_DATA_SIZE;
2500 if (get_crypt_ftr_info(NULL, &off) == 0) {
2501 ftr->persist_data_offset[0] = off + CRYPT_FOOTER_TO_PERSIST_OFFSET;
Paul Crowley14c8c072018-09-18 13:30:21 -07002502 ftr->persist_data_offset[1] = off + CRYPT_FOOTER_TO_PERSIST_OFFSET + ftr->persist_data_size;
Ken Sumrall160b4d62013-04-22 12:15:39 -07002503 }
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07002504
2505 return 0;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002506}
2507
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002508#define FRAMEWORK_BOOT_WAIT 60
2509
Paul Crowley14c8c072018-09-18 13:30:21 -07002510static int cryptfs_SHA256_fileblock(const char* filename, __le8* buf) {
2511 int fd = open(filename, O_RDONLY | O_CLOEXEC);
Paul Lawrence87999172014-02-20 12:21:31 -08002512 if (fd == -1) {
2513 SLOGE("Error opening file %s", filename);
2514 return -1;
2515 }
2516
2517 char block[CRYPT_INPLACE_BUFSIZE];
2518 memset(block, 0, sizeof(block));
2519 if (unix_read(fd, block, sizeof(block)) < 0) {
2520 SLOGE("Error reading file %s", filename);
2521 close(fd);
2522 return -1;
2523 }
2524
2525 close(fd);
2526
2527 SHA256_CTX c;
2528 SHA256_Init(&c);
2529 SHA256_Update(&c, block, sizeof(block));
2530 SHA256_Final(buf, &c);
2531
2532 return 0;
2533}
2534
Paul Lawrence7ee87cf2017-12-22 10:12:06 -08002535static int cryptfs_enable_all_volumes(struct crypt_mnt_ftr* crypt_ftr, char* crypto_blkdev,
2536 char* real_blkdev, int previously_encrypted_upto) {
Paul Crowley14c8c072018-09-18 13:30:21 -07002537 off64_t cur_encryption_done = 0, tot_encryption_size = 0;
Tim Murray8439dc92014-12-15 11:56:11 -08002538 int rc = -1;
Paul Lawrence87999172014-02-20 12:21:31 -08002539
Paul Lawrence87999172014-02-20 12:21:31 -08002540 /* The size of the userdata partition, and add in the vold volumes below */
2541 tot_encryption_size = crypt_ftr->fs_size;
2542
Paul Lawrence7ee87cf2017-12-22 10:12:06 -08002543 rc = cryptfs_enable_inplace(crypto_blkdev, real_blkdev, crypt_ftr->fs_size, &cur_encryption_done,
Paul Crowley0fd26262018-01-30 09:48:19 -08002544 tot_encryption_size, previously_encrypted_upto, true);
Paul Lawrence87999172014-02-20 12:21:31 -08002545
Paul Lawrence7ee87cf2017-12-22 10:12:06 -08002546 if (rc == ENABLE_INPLACE_ERR_DEV) {
2547 /* Hack for b/17898962 */
2548 SLOGE("cryptfs_enable: crypto block dev failure. Must reboot...\n");
2549 cryptfs_reboot(RebootType::reboot);
2550 }
JP Abgrall7fc1de82014-10-10 18:43:41 -07002551
Paul Lawrence7ee87cf2017-12-22 10:12:06 -08002552 if (!rc) {
2553 crypt_ftr->encrypted_upto = cur_encryption_done;
2554 }
Paul Lawrence87999172014-02-20 12:21:31 -08002555
Paul Lawrence7ee87cf2017-12-22 10:12:06 -08002556 if (!rc && crypt_ftr->encrypted_upto == crypt_ftr->fs_size) {
2557 /* The inplace routine never actually sets the progress to 100% due
2558 * to the round down nature of integer division, so set it here */
2559 property_set("vold.encrypt_progress", "100");
Paul Lawrence87999172014-02-20 12:21:31 -08002560 }
2561
2562 return rc;
2563}
2564
Paul Crowleyb64933a2017-10-31 08:25:55 -07002565static int vold_unmountAll(void) {
2566 VolumeManager* vm = VolumeManager::Instance();
2567 return vm->unmountAll();
2568}
2569
Paul Lawrence7ee87cf2017-12-22 10:12:06 -08002570int cryptfs_enable_internal(int crypt_type, const char* passwd, int no_ui) {
Tom Cherry4c5bde22019-01-29 14:34:01 -08002571 char crypto_blkdev[MAXPATHLEN];
2572 std::string real_blkdev;
Greg Kaiser59ad0182018-02-16 13:01:36 -08002573 unsigned char decrypted_master_key[MAX_KEY_LEN];
Paul Crowley14c8c072018-09-18 13:30:21 -07002574 int rc = -1, i;
Paul Lawrence87999172014-02-20 12:21:31 -08002575 struct crypt_mnt_ftr crypt_ftr;
Paul Crowley14c8c072018-09-18 13:30:21 -07002576 struct crypt_persist_data* pdata;
Ken Sumrall29d8da82011-05-18 17:20:07 -07002577 char encrypted_state[PROPERTY_VALUE_MAX];
Paul Crowley14c8c072018-09-18 13:30:21 -07002578 char lockid[32] = {0};
Tom Cherry4c5bde22019-01-29 14:34:01 -08002579 std::string key_loc;
Ken Sumrall29d8da82011-05-18 17:20:07 -07002580 int num_vols;
Paul Lawrence87999172014-02-20 12:21:31 -08002581 off64_t previously_encrypted_upto = 0;
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002582 bool rebootEncryption = false;
Wei Wang4375f1b2017-02-24 17:43:01 -08002583 bool onlyCreateHeader = false;
AnilKumar Chimataedac9df2018-05-11 00:25:09 +05302584#ifdef CONFIG_HW_DISK_ENCRYPTION
2585 unsigned char newpw[32];
2586 int key_index = 0;
2587#endif
2588 int index = 0;
Ken Sumrall29d8da82011-05-18 17:20:07 -07002589
Paul Lawrence7ee87cf2017-12-22 10:12:06 -08002590 if (get_crypt_ftr_and_key(&crypt_ftr) == 0) {
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002591 if (crypt_ftr.flags & CRYPT_ENCRYPTION_IN_PROGRESS) {
2592 /* An encryption was underway and was interrupted */
2593 previously_encrypted_upto = crypt_ftr.encrypted_upto;
2594 crypt_ftr.encrypted_upto = 0;
2595 crypt_ftr.flags &= ~CRYPT_ENCRYPTION_IN_PROGRESS;
Paul Lawrence6bfed202014-07-28 12:47:22 -07002596
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002597 /* At this point, we are in an inconsistent state. Until we successfully
2598 complete encryption, a reboot will leave us broken. So mark the
2599 encryption failed in case that happens.
2600 On successfully completing encryption, remove this flag */
2601 crypt_ftr.flags |= CRYPT_INCONSISTENT_STATE;
Paul Lawrence6bfed202014-07-28 12:47:22 -07002602
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002603 put_crypt_ftr_and_key(&crypt_ftr);
2604 } else if (crypt_ftr.flags & CRYPT_FORCE_ENCRYPTION) {
2605 if (!check_ftr_sha(&crypt_ftr)) {
2606 memset(&crypt_ftr, 0, sizeof(crypt_ftr));
2607 put_crypt_ftr_and_key(&crypt_ftr);
2608 goto error_unencrypted;
2609 }
2610
2611 /* Doing a reboot-encryption*/
2612 crypt_ftr.flags &= ~CRYPT_FORCE_ENCRYPTION;
2613 crypt_ftr.flags |= CRYPT_FORCE_COMPLETE;
2614 rebootEncryption = true;
2615 }
Greg Kaiser59ad0182018-02-16 13:01:36 -08002616 } else {
2617 // We don't want to accidentally reference invalid data.
2618 memset(&crypt_ftr, 0, sizeof(crypt_ftr));
Paul Lawrence87999172014-02-20 12:21:31 -08002619 }
2620
2621 property_get("ro.crypto.state", encrypted_state, "");
2622 if (!strcmp(encrypted_state, "encrypted") && !previously_encrypted_upto) {
2623 SLOGE("Device is already running encrypted, aborting");
2624 goto error_unencrypted;
2625 }
2626
Tom Cherry4c5bde22019-01-29 14:34:01 -08002627 get_crypt_info(&key_loc, &real_blkdev);
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002628
Ken Sumrall3ed82362011-01-28 23:31:16 -08002629 /* Get the size of the real block device */
Oleksiy Avramchenko625dc782018-05-23 10:50:46 +02002630 uint64_t nr_sec;
2631 if (android::vold::GetBlockDev512Sectors(real_blkdev, &nr_sec) != android::OK) {
Tom Cherry4c5bde22019-01-29 14:34:01 -08002632 SLOGE("Cannot get size of block device %s\n", real_blkdev.c_str());
Ken Sumrall3ed82362011-01-28 23:31:16 -08002633 goto error_unencrypted;
2634 }
Ken Sumrall3ed82362011-01-28 23:31:16 -08002635
2636 /* If doing inplace encryption, make sure the orig fs doesn't include the crypto footer */
Tom Cherry4c5bde22019-01-29 14:34:01 -08002637 if (key_loc == KEY_IN_FOOTER) {
Oleksiy Avramchenko625dc782018-05-23 10:50:46 +02002638 uint64_t fs_size_sec, max_fs_size_sec;
Tom Cherry4c5bde22019-01-29 14:34:01 -08002639 fs_size_sec = get_fs_size(real_blkdev.c_str());
2640 if (fs_size_sec == 0) fs_size_sec = get_f2fs_filesystem_size_sec(real_blkdev.data());
Daniel Rosenberge82df162014-08-15 22:19:23 +00002641
Paul Lawrence87999172014-02-20 12:21:31 -08002642 max_fs_size_sec = nr_sec - (CRYPT_FOOTER_OFFSET / CRYPT_SECTOR_SIZE);
Ken Sumrall3ed82362011-01-28 23:31:16 -08002643
2644 if (fs_size_sec > max_fs_size_sec) {
2645 SLOGE("Orig filesystem overlaps crypto footer region. Cannot encrypt in place.");
2646 goto error_unencrypted;
2647 }
2648 }
2649
Ken Sumrall5d4c68e2011-01-30 19:06:03 -08002650 /* Get a wakelock as this may take a while, and we don't want the
2651 * device to sleep on us. We'll grab a partial wakelock, and if the UI
2652 * wants to keep the screen on, it can grab a full wakelock.
2653 */
Paul Crowley14c8c072018-09-18 13:30:21 -07002654 snprintf(lockid, sizeof(lockid), "enablecrypto%d", (int)getpid());
Ken Sumrall5d4c68e2011-01-30 19:06:03 -08002655 acquire_wake_lock(PARTIAL_WAKE_LOCK, lockid);
2656
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002657 /* The init files are setup to stop the class main and late start when
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002658 * vold sets trigger_shutdown_framework.
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002659 */
2660 property_set("vold.decrypt", "trigger_shutdown_framework");
2661 SLOGD("Just asked init to shut down class main\n");
2662
Jeff Sharkey9c484982015-03-31 10:35:33 -07002663 /* Ask vold to unmount all devices that it manages */
2664 if (vold_unmountAll()) {
2665 SLOGE("Failed to unmount all vold managed devices");
Ken Sumrall2eaf7132011-01-14 12:45:48 -08002666 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002667
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002668 /* no_ui means we are being called from init, not settings.
2669 Now we always reboot from settings, so !no_ui means reboot
2670 */
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002671 if (!no_ui) {
2672 /* Try fallback, which is to reboot and try there */
2673 onlyCreateHeader = true;
2674 FILE* breadcrumb = fopen(BREADCRUMB_FILE, "we");
2675 if (breadcrumb == 0) {
2676 SLOGE("Failed to create breadcrumb file");
2677 goto error_shutting_down;
2678 }
2679 fclose(breadcrumb);
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002680 }
2681
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002682 /* Start the actual work of making an encrypted filesystem */
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002683 /* Initialize a crypt_mnt_ftr for the partition */
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002684 if (previously_encrypted_upto == 0 && !rebootEncryption) {
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07002685 if (cryptfs_init_crypt_mnt_ftr(&crypt_ftr)) {
2686 goto error_shutting_down;
2687 }
Ken Sumrall160b4d62013-04-22 12:15:39 -07002688
Tom Cherry4c5bde22019-01-29 14:34:01 -08002689 if (key_loc == KEY_IN_FOOTER) {
Paul Crowley14c8c072018-09-18 13:30:21 -07002690 crypt_ftr.fs_size = nr_sec - (CRYPT_FOOTER_OFFSET / CRYPT_SECTOR_SIZE);
Paul Lawrence87999172014-02-20 12:21:31 -08002691 } else {
2692 crypt_ftr.fs_size = nr_sec;
2693 }
Paul Lawrence6bfed202014-07-28 12:47:22 -07002694 /* At this point, we are in an inconsistent state. Until we successfully
2695 complete encryption, a reboot will leave us broken. So mark the
2696 encryption failed in case that happens.
2697 On successfully completing encryption, remove this flag */
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002698 if (onlyCreateHeader) {
2699 crypt_ftr.flags |= CRYPT_FORCE_ENCRYPTION;
2700 } else {
2701 crypt_ftr.flags |= CRYPT_INCONSISTENT_STATE;
2702 }
Paul Lawrence87999172014-02-20 12:21:31 -08002703 crypt_ftr.crypt_type = crypt_type;
AnilKumar Chimataedac9df2018-05-11 00:25:09 +05302704#ifdef CONFIG_HW_DISK_ENCRYPTION
2705 strlcpy((char*)crypt_ftr.crypto_type_name, "aes-xts",
2706 MAX_CRYPTO_TYPE_NAME_LEN);
2707#else
Paul Crowley14c8c072018-09-18 13:30:21 -07002708 strlcpy((char*)crypt_ftr.crypto_type_name, cryptfs_get_crypto_name(),
2709 MAX_CRYPTO_TYPE_NAME_LEN);
AnilKumar Chimataedac9df2018-05-11 00:25:09 +05302710#endif
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002711
Paul Lawrence87999172014-02-20 12:21:31 -08002712 /* Make an encrypted master key */
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002713 if (create_encrypted_random_key(onlyCreateHeader ? DEFAULT_PASSWORD : passwd,
2714 crypt_ftr.master_key, crypt_ftr.salt, &crypt_ftr)) {
Paul Lawrence87999172014-02-20 12:21:31 -08002715 SLOGE("Cannot create encrypted master key\n");
2716 goto error_shutting_down;
2717 }
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002718
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002719 /* Replace scrypted intermediate key if we are preparing for a reboot */
2720 if (onlyCreateHeader) {
Greg Kaiser59ad0182018-02-16 13:01:36 -08002721 unsigned char fake_master_key[MAX_KEY_LEN];
2722 unsigned char encrypted_fake_master_key[MAX_KEY_LEN];
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002723 memset(fake_master_key, 0, sizeof(fake_master_key));
Paul Crowley14c8c072018-09-18 13:30:21 -07002724 encrypt_master_key(passwd, crypt_ftr.salt, fake_master_key, encrypted_fake_master_key,
AnilKumar Chimataedac9df2018-05-11 00:25:09 +05302725 &crypt_ftr, true);
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002726 }
2727
Paul Lawrence87999172014-02-20 12:21:31 -08002728 /* Write the key to the end of the partition */
2729 put_crypt_ftr_and_key(&crypt_ftr);
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002730
Paul Lawrence87999172014-02-20 12:21:31 -08002731 /* If any persistent data has been remembered, save it.
2732 * If none, create a valid empty table and save that.
2733 */
2734 if (!persist_data) {
Paul Crowley14c8c072018-09-18 13:30:21 -07002735 pdata = (crypt_persist_data*)malloc(CRYPT_PERSIST_DATA_SIZE);
2736 if (pdata) {
2737 init_empty_persist_data(pdata, CRYPT_PERSIST_DATA_SIZE);
2738 persist_data = pdata;
2739 }
Paul Lawrence87999172014-02-20 12:21:31 -08002740 }
2741 if (persist_data) {
2742 save_persistent_data();
2743 }
Ken Sumrall160b4d62013-04-22 12:15:39 -07002744 }
2745
AnilKumar Chimataedac9df2018-05-11 00:25:09 +05302746 /* When encryption triggered from settings, encryption starts after reboot.
2747 So set the encryption key when the actual encryption starts.
2748 */
2749#ifdef CONFIG_HW_DISK_ENCRYPTION
2750 if (previously_encrypted_upto == 0) {
2751 if (!rebootEncryption)
2752 clear_hw_device_encryption_key();
2753
2754 if (get_keymaster_hw_fde_passwd(
2755 onlyCreateHeader ? DEFAULT_PASSWORD : passwd,
2756 newpw, crypt_ftr.salt, &crypt_ftr))
2757 key_index = set_hw_device_encryption_key(
2758 onlyCreateHeader ? DEFAULT_PASSWORD : passwd,
2759 (char*)crypt_ftr.crypto_type_name);
2760 else
2761 key_index = set_hw_device_encryption_key((const char*)newpw,
2762 (char*) crypt_ftr.crypto_type_name);
2763 if (key_index < 0)
2764 goto error_shutting_down;
2765
2766 crypt_ftr.flags |= CRYPT_ASCII_PASSWORD_UPDATED;
2767 put_crypt_ftr_and_key(&crypt_ftr);
2768 }
2769#endif
2770
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002771 if (onlyCreateHeader) {
2772 sleep(2);
Josh Gaofec44372017-08-28 13:22:55 -07002773 cryptfs_reboot(RebootType::reboot);
AnilKumar Chimataedac9df2018-05-11 00:25:09 +05302774 } else {
2775 /* Do extra work for a better UX when doing the long inplace encryption */
2776 /* Now that /data is unmounted, we need to mount a tmpfs
2777 * /data, set a property saying we're doing inplace encryption,
2778 * and restart the framework.
2779 */
2780 if (fs_mgr_do_tmpfs_mount(DATA_MNT_POINT)) {
2781 goto error_shutting_down;
2782 }
2783 /* Tells the framework that inplace encryption is starting */
2784 property_set("vold.encrypt_progress", "0");
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002785
AnilKumar Chimataedac9df2018-05-11 00:25:09 +05302786 /* restart the framework. */
2787 /* Create necessary paths on /data */
2788 prep_data_fs();
2789
2790 /* Ugh, shutting down the framework is not synchronous, so until it
2791 * can be fixed, this horrible hack will wait a moment for it all to
2792 * shut down before proceeding. Without it, some devices cannot
2793 * restart the graphics services.
2794 */
2795 sleep(2);
2796
Ajay Dudani87701e22014-09-17 21:02:52 -07002797 /* startup service classes main and late_start */
2798 property_set("vold.decrypt", "trigger_restart_min_framework");
2799 SLOGD("Just triggered restart_min_framework\n");
2800
2801 /* OK, the framework is restarted and will soon be showing a
2802 * progress bar. Time to setup an encrypted mapping, and
2803 * either write a new filesystem, or encrypt in place updating
2804 * the progress bar as we work.
2805 */
2806 }
2807
Paul Lawrenced0c7b172014-08-08 14:28:10 -07002808 decrypt_master_key(passwd, decrypted_master_key, &crypt_ftr, 0, 0);
AnilKumar Chimataedac9df2018-05-11 00:25:09 +05302809#ifdef CONFIG_HW_DISK_ENCRYPTION
2810 if (is_hw_disk_encryption((char*)crypt_ftr.crypto_type_name) && is_ice_enabled())
AnilKumar Chimata47386642018-02-11 17:11:24 +05302811#ifdef CONFIG_HW_DISK_ENCRYPT_PERF
Yifan Hongeaca4fe2019-02-07 12:56:47 -08002812 strlcpy(crypto_blkdev, real_blkdev.c_str(), sizeof(crypto_blkdev));
AnilKumar Chimata47386642018-02-11 17:11:24 +05302813#else
AnilKumar Chimataedac9df2018-05-11 00:25:09 +05302814 create_crypto_blk_dev(&crypt_ftr, (unsigned char*)&key_index, real_blkdev.c_str(), crypto_blkdev,
2815 CRYPTO_BLOCK_DEVICE, 0);
AnilKumar Chimata47386642018-02-11 17:11:24 +05302816#endif
AnilKumar Chimataedac9df2018-05-11 00:25:09 +05302817 else
2818 create_crypto_blk_dev(&crypt_ftr, decrypted_master_key, real_blkdev.c_str(), crypto_blkdev,
2819 CRYPTO_BLOCK_DEVICE, 0);
2820#else
Tom Cherry4c5bde22019-01-29 14:34:01 -08002821 create_crypto_blk_dev(&crypt_ftr, decrypted_master_key, real_blkdev.c_str(), crypto_blkdev,
Paul Crowley5afbc622017-11-27 09:42:17 -08002822 CRYPTO_BLOCK_DEVICE, 0);
AnilKumar Chimataedac9df2018-05-11 00:25:09 +05302823#endif
Ken Sumrall29d8da82011-05-18 17:20:07 -07002824
Paul Lawrence87999172014-02-20 12:21:31 -08002825 /* If we are continuing, check checksums match */
2826 rc = 0;
2827 if (previously_encrypted_upto) {
2828 __le8 hash_first_block[SHA256_DIGEST_LENGTH];
AnilKumar Chimata47386642018-02-11 17:11:24 +05302829#if defined(CONFIG_HW_DISK_ENCRYPTION) && defined(CONFIG_HW_DISK_ENCRYPT_PERF)
2830 if (set_ice_param(START_ENCDEC)) {
2831 SLOGE("Failed to set ICE data");
2832 goto error_shutting_down;
2833 }
2834#endif
Paul Lawrence87999172014-02-20 12:21:31 -08002835 rc = cryptfs_SHA256_fileblock(crypto_blkdev, hash_first_block);
Ken Sumrall128626f2011-06-28 18:45:14 -07002836
Paul Crowley14c8c072018-09-18 13:30:21 -07002837 if (!rc &&
2838 memcmp(hash_first_block, crypt_ftr.hash_first_block, sizeof(hash_first_block)) != 0) {
Paul Lawrence87999172014-02-20 12:21:31 -08002839 SLOGE("Checksums do not match - trigger wipe");
2840 rc = -1;
Ken Sumrall29d8da82011-05-18 17:20:07 -07002841 }
2842 }
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002843
AnilKumar Chimata47386642018-02-11 17:11:24 +05302844#if defined(CONFIG_HW_DISK_ENCRYPTION) && defined(CONFIG_HW_DISK_ENCRYPT_PERF)
2845 if (set_ice_param(START_ENC)) {
2846 SLOGE("Failed to set ICE data");
2847 goto error_shutting_down;
2848 }
2849#endif
Paul Lawrence87999172014-02-20 12:21:31 -08002850 if (!rc) {
Tom Cherry4c5bde22019-01-29 14:34:01 -08002851 rc = cryptfs_enable_all_volumes(&crypt_ftr, crypto_blkdev, real_blkdev.data(),
Paul Lawrence87999172014-02-20 12:21:31 -08002852 previously_encrypted_upto);
2853 }
2854
AnilKumar Chimata47386642018-02-11 17:11:24 +05302855#if defined(CONFIG_HW_DISK_ENCRYPTION) && defined(CONFIG_HW_DISK_ENCRYPT_PERF)
2856 if (set_ice_param(START_ENCDEC)) {
2857 SLOGE("Failed to set ICE data");
2858 goto error_shutting_down;
2859 }
2860#endif
Paul Lawrence87999172014-02-20 12:21:31 -08002861 /* Calculate checksum if we are not finished */
Paul Lawrence7ee87cf2017-12-22 10:12:06 -08002862 if (!rc && crypt_ftr.encrypted_upto != crypt_ftr.fs_size) {
Paul Crowley14c8c072018-09-18 13:30:21 -07002863 rc = cryptfs_SHA256_fileblock(crypto_blkdev, crypt_ftr.hash_first_block);
Paul Lawrence73d7a022014-06-09 14:10:09 -07002864 if (rc) {
Paul Lawrence87999172014-02-20 12:21:31 -08002865 SLOGE("Error calculating checksum for continuing encryption");
2866 rc = -1;
Ken Sumrall29d8da82011-05-18 17:20:07 -07002867 }
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002868 }
2869
2870 /* Undo the dm-crypt mapping whether we succeed or not */
AnilKumar Chimata47386642018-02-11 17:11:24 +05302871#if defined(CONFIG_HW_DISK_ENCRYPTION) && defined(CONFIG_HW_DISK_ENCRYPT_PERF)
2872 if (!is_ice_enabled())
2873 delete_crypto_blk_dev(CRYPTO_BLOCK_DEVICE);
2874#else
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002875 delete_crypto_blk_dev(CRYPTO_BLOCK_DEVICE);
AnilKumar Chimata47386642018-02-11 17:11:24 +05302876#endif
Ken Sumrall29d8da82011-05-18 17:20:07 -07002877
Paul Crowley14c8c072018-09-18 13:30:21 -07002878 if (!rc) {
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002879 /* Success */
Paul Lawrence6bfed202014-07-28 12:47:22 -07002880 crypt_ftr.flags &= ~CRYPT_INCONSISTENT_STATE;
Ken Sumrall7f7dbaa2011-02-01 15:46:41 -08002881
Paul Lawrence7ee87cf2017-12-22 10:12:06 -08002882 if (crypt_ftr.encrypted_upto != crypt_ftr.fs_size) {
Paul Lawrence87999172014-02-20 12:21:31 -08002883 SLOGD("Encrypted up to sector %lld - will continue after reboot",
2884 crypt_ftr.encrypted_upto);
Paul Lawrence6bfed202014-07-28 12:47:22 -07002885 crypt_ftr.flags |= CRYPT_ENCRYPTION_IN_PROGRESS;
Paul Lawrence87999172014-02-20 12:21:31 -08002886 }
Paul Lawrence73d7a022014-06-09 14:10:09 -07002887
Paul Lawrence6bfed202014-07-28 12:47:22 -07002888 put_crypt_ftr_and_key(&crypt_ftr);
Ken Sumralld33d4172011-02-01 00:49:13 -08002889
Paul Lawrence7ee87cf2017-12-22 10:12:06 -08002890 if (crypt_ftr.encrypted_upto == crypt_ftr.fs_size) {
2891 char value[PROPERTY_VALUE_MAX];
2892 property_get("ro.crypto.state", value, "");
2893 if (!strcmp(value, "")) {
2894 /* default encryption - continue first boot sequence */
2895 property_set("ro.crypto.state", "encrypted");
2896 property_set("ro.crypto.type", "block");
2897 release_wake_lock(lockid);
2898 if (rebootEncryption && crypt_ftr.crypt_type != CRYPT_TYPE_DEFAULT) {
2899 // Bring up cryptkeeper that will check the password and set it
2900 property_set("vold.decrypt", "trigger_shutdown_framework");
2901 sleep(2);
2902 property_set("vold.encrypt_progress", "");
2903 cryptfs_trigger_restart_min_framework();
2904 } else {
2905 cryptfs_check_passwd(DEFAULT_PASSWORD);
2906 cryptfs_restart_internal(1);
2907 }
2908 return 0;
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002909 } else {
Paul Lawrence7ee87cf2017-12-22 10:12:06 -08002910 sleep(2); /* Give the UI a chance to show 100% progress */
2911 cryptfs_reboot(RebootType::reboot);
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002912 }
Paul Lawrence87999172014-02-20 12:21:31 -08002913 } else {
Paul Lawrenceb6672e12014-08-15 07:37:28 -07002914 sleep(2); /* Partially encrypted, ensure writes flushed to ssd */
Josh Gaofec44372017-08-28 13:22:55 -07002915 cryptfs_reboot(RebootType::shutdown);
Paul Lawrence87999172014-02-20 12:21:31 -08002916 }
Ken Sumrall3ed82362011-01-28 23:31:16 -08002917 } else {
Mike Lockwoodee6d8c42012-02-15 13:43:28 -08002918 char value[PROPERTY_VALUE_MAX];
2919
Ken Sumrall319369a2012-06-27 16:30:18 -07002920 property_get("ro.vold.wipe_on_crypt_fail", value, "0");
Mike Lockwoodee6d8c42012-02-15 13:43:28 -08002921 if (!strcmp(value, "1")) {
2922 /* wipe data if encryption failed */
2923 SLOGE("encryption failed - rebooting into recovery to wipe data\n");
Wei Wang4375f1b2017-02-24 17:43:01 -08002924 std::string err;
2925 const std::vector<std::string> options = {
Paul Crowley14c8c072018-09-18 13:30:21 -07002926 "--wipe_data\n--reason=cryptfs_enable_internal\n"};
Wei Wang4375f1b2017-02-24 17:43:01 -08002927 if (!write_bootloader_message(options, &err)) {
2928 SLOGE("could not write bootloader message: %s", err.c_str());
Mike Lockwoodee6d8c42012-02-15 13:43:28 -08002929 }
Josh Gaofec44372017-08-28 13:22:55 -07002930 cryptfs_reboot(RebootType::recovery);
Mike Lockwoodee6d8c42012-02-15 13:43:28 -08002931 } else {
2932 /* set property to trigger dialog */
2933 property_set("vold.encrypt_progress", "error_partially_encrypted");
2934 release_wake_lock(lockid);
2935 }
Ken Sumrall3ed82362011-01-28 23:31:16 -08002936 return -1;
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002937 }
2938
Ken Sumrall3ed82362011-01-28 23:31:16 -08002939 /* hrm, the encrypt step claims success, but the reboot failed.
2940 * This should not happen.
2941 * Set the property and return. Hope the framework can deal with it.
2942 */
2943 property_set("vold.encrypt_progress", "error_reboot_failed");
Ken Sumrall5d4c68e2011-01-30 19:06:03 -08002944 release_wake_lock(lockid);
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002945 return rc;
Ken Sumrall3ed82362011-01-28 23:31:16 -08002946
2947error_unencrypted:
2948 property_set("vold.encrypt_progress", "error_not_encrypted");
Ken Sumrall5d4c68e2011-01-30 19:06:03 -08002949 if (lockid[0]) {
2950 release_wake_lock(lockid);
2951 }
Ken Sumrall3ed82362011-01-28 23:31:16 -08002952 return -1;
2953
2954error_shutting_down:
2955 /* we failed, and have not encrypted anthing, so the users's data is still intact,
2956 * but the framework is stopped and not restarted to show the error, so it's up to
2957 * vold to restart the system.
2958 */
Paul Crowley14c8c072018-09-18 13:30:21 -07002959 SLOGE(
2960 "Error enabling encryption after framework is shutdown, no data changed, restarting "
2961 "system");
Josh Gaofec44372017-08-28 13:22:55 -07002962 cryptfs_reboot(RebootType::reboot);
Ken Sumrall3ed82362011-01-28 23:31:16 -08002963
2964 /* shouldn't get here */
2965 property_set("vold.encrypt_progress", "error_shutting_down");
Ken Sumrall5d4c68e2011-01-30 19:06:03 -08002966 if (lockid[0]) {
2967 release_wake_lock(lockid);
2968 }
Ken Sumrall3ed82362011-01-28 23:31:16 -08002969 return -1;
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002970}
2971
Paul Lawrence7ee87cf2017-12-22 10:12:06 -08002972int cryptfs_enable(int type, const char* passwd, int no_ui) {
2973 return cryptfs_enable_internal(type, passwd, no_ui);
Paul Lawrence13486032014-02-03 13:28:11 -08002974}
2975
Paul Lawrence7ee87cf2017-12-22 10:12:06 -08002976int cryptfs_enable_default(int no_ui) {
2977 return cryptfs_enable_internal(CRYPT_TYPE_DEFAULT, DEFAULT_PASSWORD, no_ui);
Paul Lawrence13486032014-02-03 13:28:11 -08002978}
2979
AnilKumar Chimataedac9df2018-05-11 00:25:09 +05302980int cryptfs_changepw(int crypt_type, const char* currentpw, const char* newpw) {
Eric Biggersa701c452018-10-23 13:06:55 -07002981 if (fscrypt_is_native()) {
Paul Lawrence7b6b5652016-02-02 11:14:59 -08002982 SLOGE("cryptfs_changepw not valid for file encryption");
2983 return -1;
Paul Lawrence05335c32015-03-05 09:46:23 -08002984 }
2985
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002986 struct crypt_mnt_ftr crypt_ftr;
JP Abgrall933216c2015-02-11 13:44:32 -08002987 int rc;
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002988
2989 /* This is only allowed after we've successfully decrypted the master key */
Paul Lawrencef4faa572014-01-29 13:31:03 -08002990 if (!master_key_saved) {
Ken Sumrall0cc16632011-01-18 20:32:26 -08002991 SLOGE("Key not saved, aborting");
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002992 return -1;
2993 }
2994
Paul Lawrencef4faa572014-01-29 13:31:03 -08002995 if (crypt_type < 0 || crypt_type > CRYPT_TYPE_MAX_TYPE) {
2996 SLOGE("Invalid crypt_type %d", crypt_type);
2997 return -1;
2998 }
2999
Ken Sumrall8ddbe402011-01-17 15:26:29 -08003000 /* get key */
Ken Sumrall160b4d62013-04-22 12:15:39 -07003001 if (get_crypt_ftr_and_key(&crypt_ftr)) {
Paul Lawrencef4faa572014-01-29 13:31:03 -08003002 SLOGE("Error getting crypt footer and key");
3003 return -1;
Ken Sumrall8ddbe402011-01-17 15:26:29 -08003004 }
3005
AnilKumar Chimataedac9df2018-05-11 00:25:09 +05303006#ifdef CONFIG_HW_DISK_ENCRYPTION
3007 if(is_hw_disk_encryption((char*)crypt_ftr.crypto_type_name))
3008 return cryptfs_changepw_hw_fde(crypt_type, currentpw, newpw);
3009 else {
3010 crypt_ftr.crypt_type = crypt_type;
3011
3012 rc = encrypt_master_key(crypt_type == CRYPT_TYPE_DEFAULT ?
3013 DEFAULT_PASSWORD : newpw,
3014 crypt_ftr.salt,
3015 saved_master_key,
3016 crypt_ftr.master_key,
3017 &crypt_ftr, false);
3018 if (rc) {
3019 SLOGE("Encrypt master key failed: %d", rc);
3020 return -1;
3021 }
3022 /* save the key */
3023 put_crypt_ftr_and_key(&crypt_ftr);
3024
3025 return 0;
3026 }
3027#else
Paul Lawrencef4faa572014-01-29 13:31:03 -08003028 crypt_ftr.crypt_type = crypt_type;
3029
Paul Crowley14c8c072018-09-18 13:30:21 -07003030 rc = encrypt_master_key(crypt_type == CRYPT_TYPE_DEFAULT ? DEFAULT_PASSWORD : newpw,
AnilKumar Chimataedac9df2018-05-11 00:25:09 +05303031 crypt_ftr.salt, saved_master_key, crypt_ftr.master_key, &crypt_ftr,
3032 false);
JP Abgrall933216c2015-02-11 13:44:32 -08003033 if (rc) {
3034 SLOGE("Encrypt master key failed: %d", rc);
3035 return -1;
3036 }
Jason parks70a4b3f2011-01-28 10:10:47 -06003037 /* save the key */
Ken Sumrall160b4d62013-04-22 12:15:39 -07003038 put_crypt_ftr_and_key(&crypt_ftr);
Ken Sumrall8f869aa2010-12-03 03:47:09 -08003039
3040 return 0;
AnilKumar Chimataedac9df2018-05-11 00:25:09 +05303041#endif
Ken Sumrall8f869aa2010-12-03 03:47:09 -08003042}
Ken Sumrall160b4d62013-04-22 12:15:39 -07003043
AnilKumar Chimataedac9df2018-05-11 00:25:09 +05303044#ifdef CONFIG_HW_DISK_ENCRYPTION
3045int cryptfs_changepw_hw_fde(int crypt_type, const char *currentpw, const char *newpw)
3046{
3047 struct crypt_mnt_ftr crypt_ftr;
3048 int rc;
3049 int previous_type;
3050
3051 /* get key */
3052 if (get_crypt_ftr_and_key(&crypt_ftr)) {
3053 SLOGE("Error getting crypt footer and key");
3054 return -1;
3055 }
3056
3057 previous_type = crypt_ftr.crypt_type;
3058 int rc1;
3059 unsigned char tmp_curpw[32] = {0};
3060 rc1 = get_keymaster_hw_fde_passwd(crypt_ftr.crypt_type == CRYPT_TYPE_DEFAULT ?
3061 DEFAULT_PASSWORD : currentpw, tmp_curpw,
3062 crypt_ftr.salt, &crypt_ftr);
3063
3064 crypt_ftr.crypt_type = crypt_type;
3065
3066 int ret, rc2;
3067 unsigned char tmp_newpw[32] = {0};
3068
3069 rc2 = get_keymaster_hw_fde_passwd(crypt_type == CRYPT_TYPE_DEFAULT ?
3070 DEFAULT_PASSWORD : newpw , tmp_newpw,
3071 crypt_ftr.salt, &crypt_ftr);
3072
3073 if (is_hw_disk_encryption((char*)crypt_ftr.crypto_type_name)) {
3074 ret = update_hw_device_encryption_key(
3075 rc1 ? (previous_type == CRYPT_TYPE_DEFAULT ? DEFAULT_PASSWORD : currentpw) : (const char*)tmp_curpw,
3076 rc2 ? (crypt_type == CRYPT_TYPE_DEFAULT ? DEFAULT_PASSWORD : newpw): (const char*)tmp_newpw,
3077 (char*)crypt_ftr.crypto_type_name);
3078 if (ret) {
3079 SLOGE("Error updating device encryption hardware key ret %d", ret);
3080 return -1;
3081 } else {
3082 SLOGI("Encryption hardware key updated");
3083 }
3084 }
3085
3086 /* save the key */
3087 put_crypt_ftr_and_key(&crypt_ftr);
3088 return 0;
3089}
3090#endif
3091
Rubin Xu85c01f92014-10-13 12:49:54 +01003092static unsigned int persist_get_max_entries(int encrypted) {
3093 struct crypt_mnt_ftr crypt_ftr;
3094 unsigned int dsize;
Rubin Xu85c01f92014-10-13 12:49:54 +01003095
3096 /* If encrypted, use the values from the crypt_ftr, otherwise
3097 * use the values for the current spec.
3098 */
3099 if (encrypted) {
3100 if (get_crypt_ftr_and_key(&crypt_ftr)) {
Rubin Xuf83cc612018-10-09 16:13:38 +01003101 /* Something is wrong, assume no space for entries */
3102 return 0;
Rubin Xu85c01f92014-10-13 12:49:54 +01003103 }
3104 dsize = crypt_ftr.persist_data_size;
3105 } else {
3106 dsize = CRYPT_PERSIST_DATA_SIZE;
3107 }
3108
Rubin Xuf83cc612018-10-09 16:13:38 +01003109 if (dsize > sizeof(struct crypt_persist_data)) {
3110 return (dsize - sizeof(struct crypt_persist_data)) / sizeof(struct crypt_persist_entry);
3111 } else {
3112 return 0;
3113 }
Rubin Xu85c01f92014-10-13 12:49:54 +01003114}
3115
Paul Crowley14c8c072018-09-18 13:30:21 -07003116static int persist_get_key(const char* fieldname, char* value) {
Ken Sumrall160b4d62013-04-22 12:15:39 -07003117 unsigned int i;
3118
3119 if (persist_data == NULL) {
3120 return -1;
3121 }
3122 for (i = 0; i < persist_data->persist_valid_entries; i++) {
3123 if (!strncmp(persist_data->persist_entry[i].key, fieldname, PROPERTY_KEY_MAX)) {
3124 /* We found it! */
3125 strlcpy(value, persist_data->persist_entry[i].val, PROPERTY_VALUE_MAX);
3126 return 0;
3127 }
3128 }
3129
3130 return -1;
3131}
3132
Paul Crowley14c8c072018-09-18 13:30:21 -07003133static int persist_set_key(const char* fieldname, const char* value, int encrypted) {
Ken Sumrall160b4d62013-04-22 12:15:39 -07003134 unsigned int i;
3135 unsigned int num;
Ken Sumrall160b4d62013-04-22 12:15:39 -07003136 unsigned int max_persistent_entries;
Ken Sumrall160b4d62013-04-22 12:15:39 -07003137
3138 if (persist_data == NULL) {
3139 return -1;
3140 }
3141
Rubin Xu85c01f92014-10-13 12:49:54 +01003142 max_persistent_entries = persist_get_max_entries(encrypted);
Ken Sumrall160b4d62013-04-22 12:15:39 -07003143
3144 num = persist_data->persist_valid_entries;
3145
3146 for (i = 0; i < num; i++) {
3147 if (!strncmp(persist_data->persist_entry[i].key, fieldname, PROPERTY_KEY_MAX)) {
3148 /* We found an existing entry, update it! */
3149 memset(persist_data->persist_entry[i].val, 0, PROPERTY_VALUE_MAX);
3150 strlcpy(persist_data->persist_entry[i].val, value, PROPERTY_VALUE_MAX);
3151 return 0;
3152 }
3153 }
3154
3155 /* We didn't find it, add it to the end, if there is room */
3156 if (persist_data->persist_valid_entries < max_persistent_entries) {
3157 memset(&persist_data->persist_entry[num], 0, sizeof(struct crypt_persist_entry));
3158 strlcpy(persist_data->persist_entry[num].key, fieldname, PROPERTY_KEY_MAX);
3159 strlcpy(persist_data->persist_entry[num].val, value, PROPERTY_VALUE_MAX);
3160 persist_data->persist_valid_entries++;
3161 return 0;
3162 }
3163
3164 return -1;
3165}
3166
Rubin Xu85c01f92014-10-13 12:49:54 +01003167/**
3168 * Test if key is part of the multi-entry (field, index) sequence. Return non-zero if key is in the
3169 * sequence and its index is greater than or equal to index. Return 0 otherwise.
3170 */
Paul Crowley14c8c072018-09-18 13:30:21 -07003171int match_multi_entry(const char* key, const char* field, unsigned index) {
Jeff Sharkey95440eb2017-09-18 18:19:28 -06003172 std::string key_ = key;
3173 std::string field_ = field;
Rubin Xu85c01f92014-10-13 12:49:54 +01003174
Jeff Sharkey95440eb2017-09-18 18:19:28 -06003175 std::string parsed_field;
3176 unsigned parsed_index;
3177
3178 std::string::size_type split = key_.find_last_of('_');
3179 if (split == std::string::npos) {
3180 parsed_field = key_;
3181 parsed_index = 0;
3182 } else {
3183 parsed_field = key_.substr(0, split);
3184 parsed_index = std::stoi(key_.substr(split + 1));
Rubin Xu85c01f92014-10-13 12:49:54 +01003185 }
Jeff Sharkey95440eb2017-09-18 18:19:28 -06003186
3187 return parsed_field == field_ && parsed_index >= index;
Rubin Xu85c01f92014-10-13 12:49:54 +01003188}
3189
3190/*
3191 * Delete entry/entries from persist_data. If the entries are part of a multi-segment field, all
3192 * remaining entries starting from index will be deleted.
3193 * returns PERSIST_DEL_KEY_OK if deletion succeeds,
3194 * PERSIST_DEL_KEY_ERROR_NO_FIELD if the field does not exist,
3195 * and PERSIST_DEL_KEY_ERROR_OTHER if error occurs.
3196 *
3197 */
Paul Crowley14c8c072018-09-18 13:30:21 -07003198static int persist_del_keys(const char* fieldname, unsigned index) {
Rubin Xu85c01f92014-10-13 12:49:54 +01003199 unsigned int i;
3200 unsigned int j;
3201 unsigned int num;
3202
3203 if (persist_data == NULL) {
3204 return PERSIST_DEL_KEY_ERROR_OTHER;
3205 }
3206
3207 num = persist_data->persist_valid_entries;
3208
Paul Crowley14c8c072018-09-18 13:30:21 -07003209 j = 0; // points to the end of non-deleted entries.
Rubin Xu85c01f92014-10-13 12:49:54 +01003210 // Filter out to-be-deleted entries in place.
3211 for (i = 0; i < num; i++) {
3212 if (!match_multi_entry(persist_data->persist_entry[i].key, fieldname, index)) {
3213 persist_data->persist_entry[j] = persist_data->persist_entry[i];
3214 j++;
3215 }
3216 }
3217
3218 if (j < num) {
3219 persist_data->persist_valid_entries = j;
3220 // Zeroise the remaining entries
3221 memset(&persist_data->persist_entry[j], 0, (num - j) * sizeof(struct crypt_persist_entry));
3222 return PERSIST_DEL_KEY_OK;
3223 } else {
3224 // Did not find an entry matching the given fieldname
3225 return PERSIST_DEL_KEY_ERROR_NO_FIELD;
3226 }
3227}
3228
Paul Crowley14c8c072018-09-18 13:30:21 -07003229static int persist_count_keys(const char* fieldname) {
Rubin Xu85c01f92014-10-13 12:49:54 +01003230 unsigned int i;
3231 unsigned int count;
3232
3233 if (persist_data == NULL) {
3234 return -1;
3235 }
3236
3237 count = 0;
3238 for (i = 0; i < persist_data->persist_valid_entries; i++) {
3239 if (match_multi_entry(persist_data->persist_entry[i].key, fieldname, 0)) {
3240 count++;
3241 }
3242 }
3243
3244 return count;
3245}
3246
Ken Sumrall160b4d62013-04-22 12:15:39 -07003247/* Return the value of the specified field. */
Paul Crowley14c8c072018-09-18 13:30:21 -07003248int cryptfs_getfield(const char* fieldname, char* value, int len) {
Eric Biggersa701c452018-10-23 13:06:55 -07003249 if (fscrypt_is_native()) {
Paul Lawrence5a06a642016-02-03 13:39:13 -08003250 SLOGE("Cannot get field when file encrypted");
3251 return -1;
Paul Lawrence368d7942015-04-15 14:12:00 -07003252 }
3253
Ken Sumrall160b4d62013-04-22 12:15:39 -07003254 char temp_value[PROPERTY_VALUE_MAX];
Rubin Xu85c01f92014-10-13 12:49:54 +01003255 /* CRYPTO_GETFIELD_OK is success,
3256 * CRYPTO_GETFIELD_ERROR_NO_FIELD is value not set,
3257 * CRYPTO_GETFIELD_ERROR_BUF_TOO_SMALL is buffer (as given by len) too small,
3258 * CRYPTO_GETFIELD_ERROR_OTHER is any other error
Ken Sumrall160b4d62013-04-22 12:15:39 -07003259 */
Rubin Xu85c01f92014-10-13 12:49:54 +01003260 int rc = CRYPTO_GETFIELD_ERROR_OTHER;
3261 int i;
3262 char temp_field[PROPERTY_KEY_MAX];
Ken Sumrall160b4d62013-04-22 12:15:39 -07003263
3264 if (persist_data == NULL) {
3265 load_persistent_data();
3266 if (persist_data == NULL) {
3267 SLOGE("Getfield error, cannot load persistent data");
3268 goto out;
3269 }
3270 }
3271
Rubin Xu85c01f92014-10-13 12:49:54 +01003272 // Read value from persistent entries. If the original value is split into multiple entries,
3273 // stitch them back together.
Ken Sumrall160b4d62013-04-22 12:15:39 -07003274 if (!persist_get_key(fieldname, temp_value)) {
Rubin Xu85c01f92014-10-13 12:49:54 +01003275 // 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 -07003276 if (strlcpy(value, temp_value, len) >= (unsigned)len) {
Rubin Xu85c01f92014-10-13 12:49:54 +01003277 // value too small
3278 rc = CRYPTO_GETFIELD_ERROR_BUF_TOO_SMALL;
3279 goto out;
3280 }
3281 rc = CRYPTO_GETFIELD_OK;
3282
3283 for (i = 1; /* break explicitly */; i++) {
3284 if (snprintf(temp_field, sizeof(temp_field), "%s_%d", fieldname, i) >=
Paul Crowley14c8c072018-09-18 13:30:21 -07003285 (int)sizeof(temp_field)) {
Rubin Xu85c01f92014-10-13 12:49:54 +01003286 // If the fieldname is very long, we stop as soon as it begins to overflow the
3287 // maximum field length. At this point we have in fact fully read out the original
3288 // value because cryptfs_setfield would not allow fields with longer names to be
3289 // written in the first place.
3290 break;
3291 }
3292 if (!persist_get_key(temp_field, temp_value)) {
Paul Crowley14c8c072018-09-18 13:30:21 -07003293 if (strlcat(value, temp_value, len) >= (unsigned)len) {
3294 // value too small.
3295 rc = CRYPTO_GETFIELD_ERROR_BUF_TOO_SMALL;
3296 goto out;
3297 }
Rubin Xu85c01f92014-10-13 12:49:54 +01003298 } else {
3299 // Exhaust all entries.
3300 break;
3301 }
3302 }
Ken Sumrall160b4d62013-04-22 12:15:39 -07003303 } else {
3304 /* Sadness, it's not there. Return the error */
Rubin Xu85c01f92014-10-13 12:49:54 +01003305 rc = CRYPTO_GETFIELD_ERROR_NO_FIELD;
Ken Sumrall160b4d62013-04-22 12:15:39 -07003306 }
3307
3308out:
3309 return rc;
3310}
3311
3312/* Set the value of the specified field. */
Paul Crowley14c8c072018-09-18 13:30:21 -07003313int cryptfs_setfield(const char* fieldname, const char* value) {
Eric Biggersa701c452018-10-23 13:06:55 -07003314 if (fscrypt_is_native()) {
Paul Lawrence5a06a642016-02-03 13:39:13 -08003315 SLOGE("Cannot set field when file encrypted");
3316 return -1;
Paul Lawrence368d7942015-04-15 14:12:00 -07003317 }
3318
Ken Sumrall160b4d62013-04-22 12:15:39 -07003319 char encrypted_state[PROPERTY_VALUE_MAX];
Rubin Xu85c01f92014-10-13 12:49:54 +01003320 /* 0 is success, negative values are error */
3321 int rc = CRYPTO_SETFIELD_ERROR_OTHER;
Ken Sumrall160b4d62013-04-22 12:15:39 -07003322 int encrypted = 0;
Rubin Xu85c01f92014-10-13 12:49:54 +01003323 unsigned int field_id;
3324 char temp_field[PROPERTY_KEY_MAX];
3325 unsigned int num_entries;
3326 unsigned int max_keylen;
Ken Sumrall160b4d62013-04-22 12:15:39 -07003327
3328 if (persist_data == NULL) {
3329 load_persistent_data();
3330 if (persist_data == NULL) {
3331 SLOGE("Setfield error, cannot load persistent data");
3332 goto out;
3333 }
3334 }
3335
3336 property_get("ro.crypto.state", encrypted_state, "");
Paul Crowley14c8c072018-09-18 13:30:21 -07003337 if (!strcmp(encrypted_state, "encrypted")) {
Ken Sumrall160b4d62013-04-22 12:15:39 -07003338 encrypted = 1;
3339 }
3340
Rubin Xu85c01f92014-10-13 12:49:54 +01003341 // Compute the number of entries required to store value, each entry can store up to
3342 // (PROPERTY_VALUE_MAX - 1) chars
3343 if (strlen(value) == 0) {
3344 // Empty value also needs one entry to store.
3345 num_entries = 1;
3346 } else {
3347 num_entries = (strlen(value) + (PROPERTY_VALUE_MAX - 1) - 1) / (PROPERTY_VALUE_MAX - 1);
3348 }
3349
3350 max_keylen = strlen(fieldname);
3351 if (num_entries > 1) {
3352 // Need an extra "_%d" suffix.
3353 max_keylen += 1 + log10(num_entries);
3354 }
3355 if (max_keylen > PROPERTY_KEY_MAX - 1) {
3356 rc = CRYPTO_SETFIELD_ERROR_FIELD_TOO_LONG;
Ken Sumrall160b4d62013-04-22 12:15:39 -07003357 goto out;
3358 }
3359
Rubin Xu85c01f92014-10-13 12:49:54 +01003360 // Make sure we have enough space to write the new value
3361 if (persist_data->persist_valid_entries + num_entries - persist_count_keys(fieldname) >
3362 persist_get_max_entries(encrypted)) {
3363 rc = CRYPTO_SETFIELD_ERROR_VALUE_TOO_LONG;
3364 goto out;
3365 }
3366
3367 // Now that we know persist_data has enough space for value, let's delete the old field first
3368 // to make up space.
3369 persist_del_keys(fieldname, 0);
3370
3371 if (persist_set_key(fieldname, value, encrypted)) {
3372 // fail to set key, should not happen as we have already checked the available space
3373 SLOGE("persist_set_key() error during setfield()");
3374 goto out;
3375 }
3376
3377 for (field_id = 1; field_id < num_entries; field_id++) {
Greg Kaiserb610e772018-02-09 09:19:54 -08003378 snprintf(temp_field, sizeof(temp_field), "%s_%u", fieldname, field_id);
Rubin Xu85c01f92014-10-13 12:49:54 +01003379
3380 if (persist_set_key(temp_field, value + field_id * (PROPERTY_VALUE_MAX - 1), encrypted)) {
3381 // fail to set key, should not happen as we have already checked the available space.
3382 SLOGE("persist_set_key() error during setfield()");
3383 goto out;
3384 }
3385 }
3386
Ken Sumrall160b4d62013-04-22 12:15:39 -07003387 /* If we are running encrypted, save the persistent data now */
3388 if (encrypted) {
3389 if (save_persistent_data()) {
3390 SLOGE("Setfield error, cannot save persistent data");
3391 goto out;
3392 }
3393 }
3394
Rubin Xu85c01f92014-10-13 12:49:54 +01003395 rc = CRYPTO_SETFIELD_OK;
Ken Sumrall160b4d62013-04-22 12:15:39 -07003396
3397out:
3398 return rc;
3399}
Paul Lawrencef4faa572014-01-29 13:31:03 -08003400
3401/* Checks userdata. Attempt to mount the volume if default-
3402 * encrypted.
3403 * On success trigger next init phase and return 0.
3404 * Currently do not handle failure - see TODO below.
3405 */
Paul Crowley14c8c072018-09-18 13:30:21 -07003406int cryptfs_mount_default_encrypted(void) {
Paul Lawrence84274cc2016-04-15 15:41:33 -07003407 int crypt_type = cryptfs_get_password_type();
3408 if (crypt_type < 0 || crypt_type > CRYPT_TYPE_MAX_TYPE) {
3409 SLOGE("Bad crypt type - error");
3410 } else if (crypt_type != CRYPT_TYPE_DEFAULT) {
Paul Crowley14c8c072018-09-18 13:30:21 -07003411 SLOGD(
3412 "Password is not default - "
3413 "starting min framework to prompt");
Paul Lawrence84274cc2016-04-15 15:41:33 -07003414 property_set("vold.decrypt", "trigger_restart_min_framework");
3415 return 0;
3416 } else if (cryptfs_check_passwd(DEFAULT_PASSWORD) == 0) {
3417 SLOGD("Password is default - restarting filesystem");
3418 cryptfs_restart_internal(0);
3419 return 0;
Paul Lawrencef4faa572014-01-29 13:31:03 -08003420 } else {
Paul Lawrence84274cc2016-04-15 15:41:33 -07003421 SLOGE("Encrypted, default crypt type but can't decrypt");
Paul Lawrencef4faa572014-01-29 13:31:03 -08003422 }
3423
Paul Lawrence6bfed202014-07-28 12:47:22 -07003424 /** Corrupt. Allow us to boot into framework, which will detect bad
3425 crypto when it calls do_crypto_complete, then do a factory reset
Paul Lawrencef4faa572014-01-29 13:31:03 -08003426 */
Paul Lawrence6bfed202014-07-28 12:47:22 -07003427 property_set("vold.decrypt", "trigger_restart_min_framework");
Paul Lawrencef4faa572014-01-29 13:31:03 -08003428 return 0;
3429}
3430
3431/* Returns type of the password, default, pattern, pin or password.
3432 */
Paul Crowley14c8c072018-09-18 13:30:21 -07003433int cryptfs_get_password_type(void) {
Eric Biggersa701c452018-10-23 13:06:55 -07003434 if (fscrypt_is_native()) {
Paul Lawrence7b6b5652016-02-02 11:14:59 -08003435 SLOGE("cryptfs_get_password_type not valid for file encryption");
3436 return -1;
Paul Lawrence05335c32015-03-05 09:46:23 -08003437 }
3438
Paul Lawrencef4faa572014-01-29 13:31:03 -08003439 struct crypt_mnt_ftr crypt_ftr;
3440
3441 if (get_crypt_ftr_and_key(&crypt_ftr)) {
3442 SLOGE("Error getting crypt footer and key\n");
3443 return -1;
3444 }
3445
Paul Lawrence6bfed202014-07-28 12:47:22 -07003446 if (crypt_ftr.flags & CRYPT_INCONSISTENT_STATE) {
3447 return -1;
3448 }
3449
Paul Lawrencef4faa572014-01-29 13:31:03 -08003450 return crypt_ftr.crypt_type;
3451}
Paul Lawrence684dbdf2014-02-07 12:07:22 -08003452
Paul Crowley14c8c072018-09-18 13:30:21 -07003453const char* cryptfs_get_password() {
Eric Biggersa701c452018-10-23 13:06:55 -07003454 if (fscrypt_is_native()) {
Paul Lawrence7b6b5652016-02-02 11:14:59 -08003455 SLOGE("cryptfs_get_password not valid for file encryption");
3456 return 0;
Paul Lawrence05335c32015-03-05 09:46:23 -08003457 }
3458
Paul Lawrence399317e2014-03-10 13:20:50 -07003459 struct timespec now;
Paul Lawrenceef2b5be2014-11-11 12:47:03 -08003460 clock_gettime(CLOCK_BOOTTIME, &now);
Paul Lawrence399317e2014-03-10 13:20:50 -07003461 if (now.tv_sec < password_expiry_time) {
3462 return password;
3463 } else {
3464 cryptfs_clear_password();
3465 return 0;
3466 }
3467}
3468
Paul Crowley14c8c072018-09-18 13:30:21 -07003469void cryptfs_clear_password() {
Paul Lawrence399317e2014-03-10 13:20:50 -07003470 if (password) {
3471 size_t len = strlen(password);
3472 memset(password, 0, len);
3473 free(password);
3474 password = 0;
3475 password_expiry_time = 0;
3476 }
Paul Lawrence684dbdf2014-02-07 12:07:22 -08003477}
Paul Lawrence731a7a22015-04-28 22:14:15 +00003478
Paul Crowley14c8c072018-09-18 13:30:21 -07003479int cryptfs_isConvertibleToFBE() {
Tom Cherry4c5bde22019-01-29 14:34:01 -08003480 auto entry = GetEntryForMountPoint(&fstab_default, DATA_MNT_POINT);
3481 return entry && entry->fs_mgr_flags.force_fde_or_fbe;
Paul Lawrence0c247462015-10-29 10:30:57 -07003482}
AnilKumar Chimataedac9df2018-05-11 00:25:09 +05303483
3484int cryptfs_create_default_ftr(struct crypt_mnt_ftr* crypt_ftr, __attribute__((unused))int key_length)
3485{
3486 if (cryptfs_init_crypt_mnt_ftr(crypt_ftr)) {
3487 SLOGE("Failed to initialize crypt_ftr");
3488 return -1;
3489 }
3490
3491 if (create_encrypted_random_key(DEFAULT_PASSWORD, crypt_ftr->master_key,
3492 crypt_ftr->salt, crypt_ftr)) {
3493 SLOGE("Cannot create encrypted master key\n");
3494 return -1;
3495 }
3496
3497 //crypt_ftr->keysize = key_length / 8;
3498 return 0;
3499}
3500
3501int cryptfs_get_master_key(struct crypt_mnt_ftr* ftr, const char* password,
3502 unsigned char* master_key)
3503{
3504 int rc;
3505
3506 unsigned char* intermediate_key = 0;
3507 size_t intermediate_key_size = 0;
3508
3509 if (password == 0 || *password == 0) {
3510 password = DEFAULT_PASSWORD;
3511 }
3512
3513 rc = decrypt_master_key(password, master_key, ftr, &intermediate_key,
3514 &intermediate_key_size);
3515
3516 if (rc) {
3517 SLOGE("Can't calculate intermediate key");
3518 return rc;
3519 }
3520
3521 int N = 1 << ftr->N_factor;
3522 int r = 1 << ftr->r_factor;
3523 int p = 1 << ftr->p_factor;
3524
3525 unsigned char scrypted_intermediate_key[sizeof(ftr->scrypted_intermediate_key)];
3526
3527 rc = crypto_scrypt(intermediate_key, intermediate_key_size,
3528 ftr->salt, sizeof(ftr->salt), N, r, p,
3529 scrypted_intermediate_key,
3530 sizeof(scrypted_intermediate_key));
3531
3532 free(intermediate_key);
3533
3534 if (rc) {
3535 SLOGE("Can't scrypt intermediate key");
3536 return rc;
3537 }
3538
3539 return memcmp(scrypted_intermediate_key, ftr->scrypted_intermediate_key,
3540 intermediate_key_size);
3541}