blob: 3f248235f549d5429e3e03cd86660a8f163b33e2 [file] [log] [blame]
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001/*
2 * Copyright (C) 2010 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17/* TO DO:
18 * 1. Perhaps keep several copies of the encrypted key, in case something
19 * goes horribly wrong?
20 *
21 */
22
Logan Chiend557d762018-05-02 11:36:45 +080023#define LOG_TAG "Cryptfs"
24
25#include "cryptfs.h"
26
Daniel Rosenberg4f684712018-08-28 01:58:49 -070027#include "Checkpoint.h"
Logan Chiend557d762018-05-02 11:36:45 +080028#include "EncryptInplace.h"
Eric Biggersa701c452018-10-23 13:06:55 -070029#include "FsCrypt.h"
Logan Chiend557d762018-05-02 11:36:45 +080030#include "Keymaster.h"
31#include "Process.h"
32#include "ScryptParameters.h"
Paul Crowley298fa322018-10-30 15:59:24 -070033#include "Utils.h"
Logan Chiend557d762018-05-02 11:36:45 +080034#include "VoldUtil.h"
35#include "VolumeManager.h"
Logan Chiend557d762018-05-02 11:36:45 +080036
Eric Biggersed45ec32019-01-25 10:47:55 -080037#include <android-base/parseint.h>
Logan Chien3f2b1222018-05-02 11:39:03 +080038#include <android-base/properties.h>
Greg Kaiserab1e84a2018-12-11 12:40:51 -080039#include <android-base/stringprintf.h>
Logan Chiend557d762018-05-02 11:36:45 +080040#include <bootloader_message/bootloader_message.h>
Logan Chien3f2b1222018-05-02 11:39:03 +080041#include <cutils/android_reboot.h>
Logan Chien3f2b1222018-05-02 11:39:03 +080042#include <cutils/properties.h>
Tao Bao5a95ddb2016-10-05 18:01:19 -070043#include <ext4_utils/ext4_utils.h>
Logan Chien3f2b1222018-05-02 11:39:03 +080044#include <f2fs_sparseblock.h>
Ken Sumralle5032c42012-04-01 23:58:44 -070045#include <fs_mgr.h>
Eric Biggersa701c452018-10-23 13:06:55 -070046#include <fscrypt/fscrypt.h>
David Andersonb9224732019-05-13 13:02:54 -070047#include <libdm/dm.h>
Logan Chien188b0ab2018-04-23 13:37:39 +080048#include <log/log.h>
Ken Sumralle550f782013-08-20 13:48:23 -070049#include <logwrap/logwrap.h>
Logan Chiend557d762018-05-02 11:36:45 +080050#include <openssl/evp.h>
51#include <openssl/sha.h>
Ken Sumrallc290eaf2011-03-07 23:40:35 -080052#include <selinux/selinux.h>
Tri Vo15bbe222019-06-21 12:21:48 -070053#include <wakelock/wakelock.h>
Logan Chiend557d762018-05-02 11:36:45 +080054
55#include <ctype.h>
56#include <errno.h>
57#include <fcntl.h>
58#include <inttypes.h>
59#include <libgen.h>
Logan Chiend557d762018-05-02 11:36:45 +080060#include <linux/kdev_t.h>
61#include <math.h>
62#include <stdio.h>
63#include <stdlib.h>
64#include <string.h>
Logan Chiend557d762018-05-02 11:36:45 +080065#include <sys/mount.h>
66#include <sys/param.h>
67#include <sys/stat.h>
68#include <sys/types.h>
69#include <sys/wait.h>
70#include <time.h>
71#include <unistd.h>
72
AnilKumar Chimata98dc8352018-05-11 00:25:09 +053073#ifdef CONFIG_HW_DISK_ENCRYPTION
Neeraj Soni73b46952019-09-12 16:47:27 +053074#include <linux/dm-ioctl.h>
75#include <sys/ioctl.h>
AnilKumar Chimata98dc8352018-05-11 00:25:09 +053076#include <cryptfs_hw.h>
77#endif
Wei Wang4375f1b2017-02-24 17:43:01 -080078extern "C" {
79#include <crypto_scrypt.h>
80}
Mark Salyzyn3e971272014-01-21 13:27:04 -080081
Eric Biggersed45ec32019-01-25 10:47:55 -080082using android::base::ParseUint;
Greg Kaiserab1e84a2018-12-11 12:40:51 -080083using android::base::StringPrintf;
Tom Cherry4c5bde22019-01-29 14:34:01 -080084using android::fs_mgr::GetEntryForMountPoint;
David Andersonb9224732019-05-13 13:02:54 -070085using namespace android::dm;
Paul Crowley298fa322018-10-30 15:59:24 -070086using namespace std::chrono_literals;
87
Mark Salyzyn5eecc442014-02-12 14:16:14 -080088#define UNUSED __attribute__((unused))
89
Jason parks70a4b3f2011-01-28 10:10:47 -060090#define HASH_COUNT 2000
Greg Kaiserc0de9c72018-02-14 20:05:54 -080091
92constexpr size_t INTERMEDIATE_KEY_LEN_BYTES = 16;
93constexpr size_t INTERMEDIATE_IV_LEN_BYTES = 16;
Paul Crowley14c8c072018-09-18 13:30:21 -070094constexpr size_t INTERMEDIATE_BUF_SIZE = (INTERMEDIATE_KEY_LEN_BYTES + INTERMEDIATE_IV_LEN_BYTES);
Greg Kaiserc0de9c72018-02-14 20:05:54 -080095
96// SCRYPT_LEN is used by struct crypt_mnt_ftr for its intermediate key.
Paul Crowley14c8c072018-09-18 13:30:21 -070097static_assert(INTERMEDIATE_BUF_SIZE == SCRYPT_LEN, "Mismatch of intermediate key sizes");
Jason parks70a4b3f2011-01-28 10:10:47 -060098
Paul Crowley14c8c072018-09-18 13:30:21 -070099#define KEY_IN_FOOTER "footer"
Ken Sumrall29d8da82011-05-18 17:20:07 -0700100
AnilKumar Chimata98dc8352018-05-11 00:25:09 +0530101#define DEFAULT_HEX_PASSWORD "64656661756c745f70617373776f7264"
Paul Lawrence3bd36d52015-06-09 13:37:44 -0700102#define DEFAULT_PASSWORD "default_password"
Paul Lawrencef4faa572014-01-29 13:31:03 -0800103
Paul Lawrence3d99eba2015-11-20 07:07:19 -0800104#define CRYPTO_BLOCK_DEVICE "userdata"
105
106#define BREADCRUMB_FILE "/data/misc/vold/convert_fde"
107
Ken Sumrall29d8da82011-05-18 17:20:07 -0700108#define EXT4_FS 1
JP Abgrall62c7af32014-06-16 13:01:23 -0700109#define F2FS_FS 2
Ken Sumrall29d8da82011-05-18 17:20:07 -0700110
Ken Sumralle919efe2012-09-29 17:07:41 -0700111#define TABLE_LOAD_RETRIES 10
112
Shawn Willden47ba10d2014-09-03 17:07:06 -0600113#define RSA_KEY_SIZE 2048
114#define RSA_KEY_SIZE_BYTES (RSA_KEY_SIZE / 8)
115#define RSA_EXPONENT 0x10001
Shawn Willdenda6e8992015-06-03 09:40:45 -0600116#define KEYMASTER_CRYPTFS_RATE_LIMIT 1 // Maximum one try per second
AnilKumar Chimata98dc8352018-05-11 00:25:09 +0530117#define KEY_LEN_BYTES 16
Paul Lawrence69f4ebd2014-04-14 12:17:14 -0700118
Paul Lawrence8e3f4512014-09-08 10:11:17 -0700119#define RETRY_MOUNT_ATTEMPTS 10
120#define RETRY_MOUNT_DELAY_SECONDS 1
121
Paul Crowley5afbc622017-11-27 09:42:17 -0800122#define CREATE_CRYPTO_BLK_DEV_FLAGS_ALLOW_ENCRYPT_OVERRIDE (1)
123
Paul Crowley73473332017-11-21 15:43:51 -0800124static int put_crypt_ftr_and_key(struct crypt_mnt_ftr* crypt_ftr);
125
Greg Kaiser59ad0182018-02-16 13:01:36 -0800126static unsigned char saved_master_key[MAX_KEY_LEN];
Paul Crowley14c8c072018-09-18 13:30:21 -0700127static char* saved_mount_point;
128static int master_key_saved = 0;
129static struct crypt_persist_data* persist_data = NULL;
Ken Sumrall56ad03c2013-02-13 13:00:19 -0800130
AnilKumar Chimata98dc8352018-05-11 00:25:09 +0530131static int previous_type;
132
133#ifdef CONFIG_HW_DISK_ENCRYPTION
134static int scrypt_keymaster(const char *passwd, const unsigned char *salt,
135 unsigned char *ikey, void *params);
136static void convert_key_to_hex_ascii(const unsigned char *master_key,
137 unsigned int keysize, char *master_key_ascii);
138static int put_crypt_ftr_and_key(struct crypt_mnt_ftr *crypt_ftr);
139static int test_mount_hw_encrypted_fs(struct crypt_mnt_ftr* crypt_ftr,
140 const char *passwd, const char *mount_point, const char *label);
141int cryptfs_changepw_hw_fde(int crypt_type, const char *currentpw,
142 const char *newpw);
143int cryptfs_check_passwd_hw(char *passwd);
144int cryptfs_get_master_key(struct crypt_mnt_ftr* ftr, const char* password,
145 unsigned char* master_key);
146
147static void convert_key_to_hex_ascii_for_upgrade(const unsigned char *master_key,
148 unsigned int keysize, char *master_key_ascii)
149{
150 unsigned int i, a;
151 unsigned char nibble;
152
153 for (i = 0, a = 0; i < keysize; i++, a += 2) {
154 /* For each byte, write out two ascii hex digits */
155 nibble = (master_key[i] >> 4) & 0xf;
156 master_key_ascii[a] = nibble + (nibble > 9 ? 0x57 : 0x30);
157
158 nibble = master_key[i] & 0xf;
159 master_key_ascii[a + 1] = nibble + (nibble > 9 ? 0x57 : 0x30);
160 }
161
162 /* Add the null termination */
163 master_key_ascii[a] = '\0';
164}
165
166static int get_keymaster_hw_fde_passwd(const char* passwd, unsigned char* newpw,
167 unsigned char* salt,
168 const struct crypt_mnt_ftr *ftr)
169{
170 /* if newpw updated, return 0
171 * if newpw not updated return -1
172 */
173 int rc = -1;
174
175 if (should_use_keymaster()) {
176 if (scrypt_keymaster(passwd, salt, newpw, (void*)ftr)) {
177 SLOGE("scrypt failed");
178 } else {
179 rc = 0;
180 }
181 }
182
183 return rc;
184}
185
186static int verify_hw_fde_passwd(const char *passwd, struct crypt_mnt_ftr* crypt_ftr)
187{
188 unsigned char newpw[32] = {0};
189 int key_index;
190 if (get_keymaster_hw_fde_passwd(passwd, newpw, crypt_ftr->salt, crypt_ftr))
191 key_index = set_hw_device_encryption_key(passwd,
192 (char*) crypt_ftr->crypto_type_name);
193 else
194 key_index = set_hw_device_encryption_key((const char*)newpw,
195 (char*) crypt_ftr->crypto_type_name);
196 return key_index;
197}
198
199static int verify_and_update_hw_fde_passwd(const char *passwd,
200 struct crypt_mnt_ftr* crypt_ftr)
201{
202 char* new_passwd = NULL;
203 unsigned char newpw[32] = {0};
204 int key_index = -1;
205 int passwd_updated = -1;
206 int ascii_passwd_updated = (crypt_ftr->flags & CRYPT_ASCII_PASSWORD_UPDATED);
207
208 key_index = verify_hw_fde_passwd(passwd, crypt_ftr);
209 if (key_index < 0) {
210 ++crypt_ftr->failed_decrypt_count;
211
212 if (ascii_passwd_updated) {
213 SLOGI("Ascii password was updated");
214 } else {
215 /* Code in else part would execute only once:
216 * When device is upgraded from L->M release.
217 * Once upgraded, code flow should never come here.
218 * L release passed actual password in hex, so try with hex
219 * Each nible of passwd was encoded as a byte, so allocate memory
220 * twice of password len plus one more byte for null termination
221 */
222 if (crypt_ftr->crypt_type == CRYPT_TYPE_DEFAULT) {
223 new_passwd = (char*)malloc(strlen(DEFAULT_HEX_PASSWORD) + 1);
224 if (new_passwd == NULL) {
225 SLOGE("System out of memory. Password verification incomplete");
226 goto out;
227 }
228 strlcpy(new_passwd, DEFAULT_HEX_PASSWORD, strlen(DEFAULT_HEX_PASSWORD) + 1);
229 } else {
230 new_passwd = (char*)malloc(strlen(passwd) * 2 + 1);
231 if (new_passwd == NULL) {
232 SLOGE("System out of memory. Password verification incomplete");
233 goto out;
234 }
235 convert_key_to_hex_ascii_for_upgrade((const unsigned char*)passwd,
236 strlen(passwd), new_passwd);
237 }
238 key_index = set_hw_device_encryption_key((const char*)new_passwd,
239 (char*) crypt_ftr->crypto_type_name);
240 if (key_index >=0) {
241 crypt_ftr->failed_decrypt_count = 0;
242 SLOGI("Hex password verified...will try to update with Ascii value");
243 /* Before updating password, tie that with keymaster to tie with ROT */
244
245 if (get_keymaster_hw_fde_passwd(passwd, newpw,
246 crypt_ftr->salt, crypt_ftr)) {
247 passwd_updated = update_hw_device_encryption_key(new_passwd,
248 passwd, (char*)crypt_ftr->crypto_type_name);
249 } else {
250 passwd_updated = update_hw_device_encryption_key(new_passwd,
251 (const char*)newpw, (char*)crypt_ftr->crypto_type_name);
252 }
253
254 if (passwd_updated >= 0) {
255 crypt_ftr->flags |= CRYPT_ASCII_PASSWORD_UPDATED;
256 SLOGI("Ascii password recorded and updated");
257 } else {
258 SLOGI("Passwd verified, could not update...Will try next time");
259 }
260 } else {
261 ++crypt_ftr->failed_decrypt_count;
262 }
263 free(new_passwd);
264 }
265 } else {
266 if (!ascii_passwd_updated)
267 crypt_ftr->flags |= CRYPT_ASCII_PASSWORD_UPDATED;
268 }
269out:
270 // update footer before leaving
271 put_crypt_ftr_and_key(crypt_ftr);
272 return key_index;
273}
274#endif
275
Paul Lawrence69f4ebd2014-04-14 12:17:14 -0700276/* Should we use keymaster? */
Paul Crowley14c8c072018-09-18 13:30:21 -0700277static int keymaster_check_compatibility() {
Janis Danisevskis015ec302017-01-31 11:31:08 +0000278 return keymaster_compatibility_cryptfs_scrypt();
Paul Lawrence69f4ebd2014-04-14 12:17:14 -0700279}
280
281/* Create a new keymaster key and store it in this footer */
Paul Crowley14c8c072018-09-18 13:30:21 -0700282static int keymaster_create_key(struct crypt_mnt_ftr* ftr) {
Paul Lawrence3d99eba2015-11-20 07:07:19 -0800283 if (ftr->keymaster_blob_size) {
284 SLOGI("Already have key");
285 return 0;
286 }
287
Paul Crowley14c8c072018-09-18 13:30:21 -0700288 int rc = keymaster_create_key_for_cryptfs_scrypt(
289 RSA_KEY_SIZE, RSA_EXPONENT, KEYMASTER_CRYPTFS_RATE_LIMIT, ftr->keymaster_blob,
290 KEYMASTER_BLOB_SIZE, &ftr->keymaster_blob_size);
Janis Danisevskis015ec302017-01-31 11:31:08 +0000291 if (rc) {
292 if (ftr->keymaster_blob_size > KEYMASTER_BLOB_SIZE) {
Paul Crowley73473332017-11-21 15:43:51 -0800293 SLOGE("Keymaster key blob too large");
Janis Danisevskis015ec302017-01-31 11:31:08 +0000294 ftr->keymaster_blob_size = 0;
295 }
296 SLOGE("Failed to generate keypair");
Paul Lawrence69f4ebd2014-04-14 12:17:14 -0700297 return -1;
298 }
Janis Danisevskis015ec302017-01-31 11:31:08 +0000299 return 0;
Paul Lawrence69f4ebd2014-04-14 12:17:14 -0700300}
301
Shawn Willdene17a9c42014-09-08 13:04:08 -0600302/* This signs the given object using the keymaster key. */
Paul Crowley14c8c072018-09-18 13:30:21 -0700303static int keymaster_sign_object(struct crypt_mnt_ftr* ftr, const unsigned char* object,
304 const size_t object_size, unsigned char** signature,
305 size_t* signature_size) {
Shawn Willden47ba10d2014-09-03 17:07:06 -0600306 unsigned char to_sign[RSA_KEY_SIZE_BYTES];
Shawn Willdene17a9c42014-09-08 13:04:08 -0600307 size_t to_sign_size = sizeof(to_sign);
Shawn Willden47ba10d2014-09-03 17:07:06 -0600308 memset(to_sign, 0, RSA_KEY_SIZE_BYTES);
Shawn Willden47ba10d2014-09-03 17:07:06 -0600309
Shawn Willdene17a9c42014-09-08 13:04:08 -0600310 // To sign a message with RSA, the message must satisfy two
311 // constraints:
312 //
313 // 1. The message, when interpreted as a big-endian numeric value, must
314 // be strictly less than the public modulus of the RSA key. Note
315 // that because the most significant bit of the public modulus is
316 // guaranteed to be 1 (else it's an (n-1)-bit key, not an n-bit
317 // key), an n-bit message with most significant bit 0 always
318 // satisfies this requirement.
319 //
320 // 2. The message must have the same length in bits as the public
321 // modulus of the RSA key. This requirement isn't mathematically
322 // necessary, but is necessary to ensure consistency in
323 // implementations.
324 switch (ftr->kdf_type) {
Shawn Willdene17a9c42014-09-08 13:04:08 -0600325 case KDF_SCRYPT_KEYMASTER:
326 // This ensures the most significant byte of the signed message
327 // is zero. We could have zero-padded to the left instead, but
328 // this approach is slightly more robust against changes in
329 // object size. However, it's still broken (but not unusably
Shawn Willdenda6e8992015-06-03 09:40:45 -0600330 // so) because we really should be using a proper deterministic
331 // RSA padding function, such as PKCS1.
Wei Wang4375f1b2017-02-24 17:43:01 -0800332 memcpy(to_sign + 1, object, std::min((size_t)RSA_KEY_SIZE_BYTES - 1, object_size));
Shawn Willdene17a9c42014-09-08 13:04:08 -0600333 SLOGI("Signing safely-padded object");
334 break;
335 default:
336 SLOGE("Unknown KDF type %d", ftr->kdf_type);
Janis Danisevskis015ec302017-01-31 11:31:08 +0000337 return -1;
Shawn Willdene17a9c42014-09-08 13:04:08 -0600338 }
Paul Crowley73473332017-11-21 15:43:51 -0800339 for (;;) {
340 auto result = keymaster_sign_object_for_cryptfs_scrypt(
341 ftr->keymaster_blob, ftr->keymaster_blob_size, KEYMASTER_CRYPTFS_RATE_LIMIT, to_sign,
342 to_sign_size, signature, signature_size);
343 switch (result) {
344 case KeymasterSignResult::ok:
345 return 0;
346 case KeymasterSignResult::upgrade:
347 break;
348 default:
349 return -1;
350 }
351 SLOGD("Upgrading key");
352 if (keymaster_upgrade_key_for_cryptfs_scrypt(
353 RSA_KEY_SIZE, RSA_EXPONENT, KEYMASTER_CRYPTFS_RATE_LIMIT, ftr->keymaster_blob,
354 ftr->keymaster_blob_size, ftr->keymaster_blob, KEYMASTER_BLOB_SIZE,
355 &ftr->keymaster_blob_size) != 0) {
356 SLOGE("Failed to upgrade key");
357 return -1;
358 }
359 if (put_crypt_ftr_and_key(ftr) != 0) {
360 SLOGE("Failed to write upgraded key to disk");
361 }
362 SLOGD("Key upgraded successfully");
363 }
Shawn Willden47ba10d2014-09-03 17:07:06 -0600364}
365
Paul Lawrence399317e2014-03-10 13:20:50 -0700366/* Store password when userdata is successfully decrypted and mounted.
367 * Cleared by cryptfs_clear_password
368 *
369 * To avoid a double prompt at boot, we need to store the CryptKeeper
370 * password and pass it to KeyGuard, which uses it to unlock KeyStore.
371 * Since the entire framework is torn down and rebuilt after encryption,
372 * we have to use a daemon or similar to store the password. Since vold
373 * is secured against IPC except from system processes, it seems a reasonable
374 * place to store this.
375 *
376 * password should be cleared once it has been used.
377 *
378 * password is aged out after password_max_age_seconds seconds.
Paul Lawrence684dbdf2014-02-07 12:07:22 -0800379 */
Paul Lawrence399317e2014-03-10 13:20:50 -0700380static char* password = 0;
381static int password_expiry_time = 0;
382static const int password_max_age_seconds = 60;
Paul Lawrence684dbdf2014-02-07 12:07:22 -0800383
Paul Crowley14c8c072018-09-18 13:30:21 -0700384enum class RebootType { reboot, recovery, shutdown };
385static void cryptfs_reboot(RebootType rt) {
386 switch (rt) {
387 case RebootType::reboot:
388 property_set(ANDROID_RB_PROPERTY, "reboot");
389 break;
Paul Lawrence87999172014-02-20 12:21:31 -0800390
Paul Crowley14c8c072018-09-18 13:30:21 -0700391 case RebootType::recovery:
392 property_set(ANDROID_RB_PROPERTY, "reboot,recovery");
393 break;
Paul Lawrence87999172014-02-20 12:21:31 -0800394
Paul Crowley14c8c072018-09-18 13:30:21 -0700395 case RebootType::shutdown:
396 property_set(ANDROID_RB_PROPERTY, "shutdown");
397 break;
Ken Sumralladfba362013-06-04 16:37:52 -0700398 }
Paul Lawrence87999172014-02-20 12:21:31 -0800399
Ken Sumralladfba362013-06-04 16:37:52 -0700400 sleep(20);
401
402 /* Shouldn't get here, reboot should happen before sleep times out */
403 return;
404}
405
Greg Kaiser38723f22018-02-16 13:35:35 -0800406namespace {
407
408struct CryptoType;
409
410// Use to get the CryptoType in use on this device.
Paul Crowley14c8c072018-09-18 13:30:21 -0700411const CryptoType& get_crypto_type();
Greg Kaiser38723f22018-02-16 13:35:35 -0800412
413struct CryptoType {
414 // We should only be constructing CryptoTypes as part of
415 // supported_crypto_types[]. We do it via this pseudo-builder pattern,
416 // which isn't pure or fully protected as a concession to being able to
417 // do it all at compile time. Add new CryptoTypes in
418 // supported_crypto_types[] below.
419 constexpr CryptoType() : CryptoType(nullptr, nullptr, 0xFFFFFFFF) {}
420 constexpr CryptoType set_keysize(uint32_t size) const {
421 return CryptoType(this->property_name, this->crypto_name, size);
422 }
Paul Crowley14c8c072018-09-18 13:30:21 -0700423 constexpr CryptoType set_property_name(const char* property) const {
Greg Kaiser38723f22018-02-16 13:35:35 -0800424 return CryptoType(property, this->crypto_name, this->keysize);
425 }
Paul Crowley14c8c072018-09-18 13:30:21 -0700426 constexpr CryptoType set_crypto_name(const char* crypto) const {
Greg Kaiser38723f22018-02-16 13:35:35 -0800427 return CryptoType(this->property_name, crypto, this->keysize);
428 }
429
Paul Crowley14c8c072018-09-18 13:30:21 -0700430 constexpr const char* get_property_name() const { return property_name; }
431 constexpr const char* get_crypto_name() const { return crypto_name; }
Greg Kaiser38723f22018-02-16 13:35:35 -0800432 constexpr uint32_t get_keysize() const { return keysize; }
433
Paul Crowley14c8c072018-09-18 13:30:21 -0700434 private:
435 const char* property_name;
436 const char* crypto_name;
Greg Kaiser38723f22018-02-16 13:35:35 -0800437 uint32_t keysize;
438
Paul Crowley14c8c072018-09-18 13:30:21 -0700439 constexpr CryptoType(const char* property, const char* crypto, uint32_t ksize)
Greg Kaiser38723f22018-02-16 13:35:35 -0800440 : property_name(property), crypto_name(crypto), keysize(ksize) {}
Paul Crowley14c8c072018-09-18 13:30:21 -0700441 friend const CryptoType& get_crypto_type();
442 static const CryptoType& get_device_crypto_algorithm();
Greg Kaiser38723f22018-02-16 13:35:35 -0800443};
444
445// We only want to parse this read-only property once. But we need to wait
446// until the system is initialized before we can read it. So we use a static
447// scoped within this function to get it only once.
Paul Crowley14c8c072018-09-18 13:30:21 -0700448const CryptoType& get_crypto_type() {
Greg Kaiser38723f22018-02-16 13:35:35 -0800449 static CryptoType crypto_type = CryptoType::get_device_crypto_algorithm();
450 return crypto_type;
451}
452
453constexpr CryptoType default_crypto_type = CryptoType()
Paul Crowley14c8c072018-09-18 13:30:21 -0700454 .set_property_name("AES-128-CBC")
455 .set_crypto_name("aes-cbc-essiv:sha256")
456 .set_keysize(16);
Greg Kaiser38723f22018-02-16 13:35:35 -0800457
458constexpr CryptoType supported_crypto_types[] = {
459 default_crypto_type,
Greg Kaiser8cb4c9f2018-12-03 11:23:19 -0800460 CryptoType()
461 .set_property_name("adiantum")
462 .set_crypto_name("xchacha12,aes-adiantum-plain64")
463 .set_keysize(32),
Greg Kaiser38723f22018-02-16 13:35:35 -0800464 // Add new CryptoTypes here. Order is not important.
465};
466
Greg Kaiser38723f22018-02-16 13:35:35 -0800467// ---------- START COMPILE-TIME SANITY CHECK BLOCK -------------------------
468// We confirm all supported_crypto_types have a small enough keysize and
469// had both set_property_name() and set_crypto_name() called.
470
471template <typename T, size_t N>
Paul Crowley14c8c072018-09-18 13:30:21 -0700472constexpr size_t array_length(T (&)[N]) {
473 return N;
474}
Greg Kaiser38723f22018-02-16 13:35:35 -0800475
476constexpr bool indexOutOfBoundsForCryptoTypes(size_t index) {
477 return (index >= array_length(supported_crypto_types));
478}
479
Paul Crowley14c8c072018-09-18 13:30:21 -0700480constexpr bool isValidCryptoType(const CryptoType& crypto_type) {
Greg Kaiser38723f22018-02-16 13:35:35 -0800481 return ((crypto_type.get_property_name() != nullptr) &&
482 (crypto_type.get_crypto_name() != nullptr) &&
483 (crypto_type.get_keysize() <= MAX_KEY_LEN));
484}
485
486// Note in C++11 that constexpr functions can only have a single line.
487// So our code is a bit convoluted (using recursion instead of a loop),
488// but it's asserting at compile time that all of our key lengths are valid.
489constexpr bool validateSupportedCryptoTypes(size_t index) {
490 return indexOutOfBoundsForCryptoTypes(index) ||
Paul Crowley14c8c072018-09-18 13:30:21 -0700491 (isValidCryptoType(supported_crypto_types[index]) &&
492 validateSupportedCryptoTypes(index + 1));
Greg Kaiser38723f22018-02-16 13:35:35 -0800493}
494
495static_assert(validateSupportedCryptoTypes(0),
496 "We have a CryptoType with keysize > MAX_KEY_LEN or which was "
497 "incompletely constructed.");
498// ---------- END COMPILE-TIME SANITY CHECK BLOCK -------------------------
499
Greg Kaiser38723f22018-02-16 13:35:35 -0800500// Don't call this directly, use get_crypto_type(), which caches this result.
Paul Crowley14c8c072018-09-18 13:30:21 -0700501const CryptoType& CryptoType::get_device_crypto_algorithm() {
Greg Kaiser38723f22018-02-16 13:35:35 -0800502 constexpr char CRYPT_ALGO_PROP[] = "ro.crypto.fde_algorithm";
503 char paramstr[PROPERTY_VALUE_MAX];
504
Paul Crowley14c8c072018-09-18 13:30:21 -0700505 property_get(CRYPT_ALGO_PROP, paramstr, default_crypto_type.get_property_name());
506 for (auto const& ctype : supported_crypto_types) {
Greg Kaiser38723f22018-02-16 13:35:35 -0800507 if (strcmp(paramstr, ctype.get_property_name()) == 0) {
508 return ctype;
509 }
510 }
Paul Crowley14c8c072018-09-18 13:30:21 -0700511 ALOGE("Invalid name (%s) for %s. Defaulting to %s\n", paramstr, CRYPT_ALGO_PROP,
512 default_crypto_type.get_property_name());
Greg Kaiser38723f22018-02-16 13:35:35 -0800513 return default_crypto_type;
514}
515
516} // namespace
517
Kenny Rootc4c70f12013-06-14 12:11:38 -0700518/**
519 * Gets the default device scrypt parameters for key derivation time tuning.
520 * The parameters should lead to about one second derivation time for the
521 * given device.
522 */
Paul Crowley14c8c072018-09-18 13:30:21 -0700523static void get_device_scrypt_params(struct crypt_mnt_ftr* ftr) {
Kenny Rootc4c70f12013-06-14 12:11:38 -0700524 char paramstr[PROPERTY_VALUE_MAX];
Paul Crowley63c18d32016-02-10 14:02:47 +0000525 int Nf, rf, pf;
Kenny Rootc4c70f12013-06-14 12:11:38 -0700526
Paul Crowley63c18d32016-02-10 14:02:47 +0000527 property_get(SCRYPT_PROP, paramstr, SCRYPT_DEFAULTS);
528 if (!parse_scrypt_parameters(paramstr, &Nf, &rf, &pf)) {
529 SLOGW("bad scrypt parameters '%s' should be like '12:8:1'; using defaults", paramstr);
530 parse_scrypt_parameters(SCRYPT_DEFAULTS, &Nf, &rf, &pf);
Kenny Rootc4c70f12013-06-14 12:11:38 -0700531 }
Paul Crowley63c18d32016-02-10 14:02:47 +0000532 ftr->N_factor = Nf;
533 ftr->r_factor = rf;
534 ftr->p_factor = pf;
Kenny Rootc4c70f12013-06-14 12:11:38 -0700535}
536
Greg Kaiser57f9af62018-02-16 13:13:58 -0800537uint32_t cryptfs_get_keysize() {
Greg Kaiser38723f22018-02-16 13:35:35 -0800538 return get_crypto_type().get_keysize();
Greg Kaiser57f9af62018-02-16 13:13:58 -0800539}
540
Paul Crowley14c8c072018-09-18 13:30:21 -0700541const char* cryptfs_get_crypto_name() {
Greg Kaiser38723f22018-02-16 13:35:35 -0800542 return get_crypto_type().get_crypto_name();
Greg Kaiser57f9af62018-02-16 13:13:58 -0800543}
544
Tom Cherry4c5bde22019-01-29 14:34:01 -0800545static uint64_t get_fs_size(const char* dev) {
Ken Sumrall3ed82362011-01-28 23:31:16 -0800546 int fd, block_size;
547 struct ext4_super_block sb;
Oleksiy Avramchenko625dc782018-05-23 10:50:46 +0200548 uint64_t len;
Ken Sumrall3ed82362011-01-28 23:31:16 -0800549
Paul Crowley14c8c072018-09-18 13:30:21 -0700550 if ((fd = open(dev, O_RDONLY | O_CLOEXEC)) < 0) {
Ken Sumrall3ed82362011-01-28 23:31:16 -0800551 SLOGE("Cannot open device to get filesystem size ");
552 return 0;
553 }
554
555 if (lseek64(fd, 1024, SEEK_SET) < 0) {
556 SLOGE("Cannot seek to superblock");
557 return 0;
558 }
559
560 if (read(fd, &sb, sizeof(sb)) != sizeof(sb)) {
561 SLOGE("Cannot read superblock");
562 return 0;
563 }
564
565 close(fd);
566
Daniel Rosenberge82df162014-08-15 22:19:23 +0000567 if (le32_to_cpu(sb.s_magic) != EXT4_SUPER_MAGIC) {
568 SLOGE("Not a valid ext4 superblock");
569 return 0;
570 }
Ken Sumrall3ed82362011-01-28 23:31:16 -0800571 block_size = 1024 << sb.s_log_block_size;
572 /* compute length in bytes */
Oleksiy Avramchenko625dc782018-05-23 10:50:46 +0200573 len = (((uint64_t)sb.s_blocks_count_hi << 32) + sb.s_blocks_count_lo) * block_size;
Ken Sumrall3ed82362011-01-28 23:31:16 -0800574
575 /* return length in sectors */
Oleksiy Avramchenko625dc782018-05-23 10:50:46 +0200576 return len / 512;
Ken Sumrall3ed82362011-01-28 23:31:16 -0800577}
578
Tom Cherry4c5bde22019-01-29 14:34:01 -0800579static void get_crypt_info(std::string* key_loc, std::string* real_blk_device) {
580 for (const auto& entry : fstab_default) {
581 if (!entry.fs_mgr_flags.vold_managed &&
582 (entry.fs_mgr_flags.crypt || entry.fs_mgr_flags.force_crypt ||
583 entry.fs_mgr_flags.force_fde_or_fbe || entry.fs_mgr_flags.file_encryption)) {
584 if (key_loc != nullptr) {
585 *key_loc = entry.key_loc;
586 }
587 if (real_blk_device != nullptr) {
588 *real_blk_device = entry.blk_device;
589 }
590 return;
591 }
592 }
593}
594
Paul Crowley14c8c072018-09-18 13:30:21 -0700595static int get_crypt_ftr_info(char** metadata_fname, off64_t* off) {
596 static int cached_data = 0;
Oleksiy Avramchenko625dc782018-05-23 10:50:46 +0200597 static uint64_t cached_off = 0;
Paul Crowley14c8c072018-09-18 13:30:21 -0700598 static char cached_metadata_fname[PROPERTY_VALUE_MAX] = "";
Paul Crowley14c8c072018-09-18 13:30:21 -0700599 char key_loc[PROPERTY_VALUE_MAX];
600 char real_blkdev[PROPERTY_VALUE_MAX];
601 int rc = -1;
Ken Sumrall160b4d62013-04-22 12:15:39 -0700602
Paul Crowley14c8c072018-09-18 13:30:21 -0700603 if (!cached_data) {
Tom Cherry4c5bde22019-01-29 14:34:01 -0800604 std::string key_loc;
605 std::string real_blkdev;
606 get_crypt_info(&key_loc, &real_blkdev);
Ken Sumrall160b4d62013-04-22 12:15:39 -0700607
Tom Cherry4c5bde22019-01-29 14:34:01 -0800608 if (key_loc == KEY_IN_FOOTER) {
Oleksiy Avramchenko625dc782018-05-23 10:50:46 +0200609 if (android::vold::GetBlockDevSize(real_blkdev, &cached_off) == android::OK) {
Paul Crowley14c8c072018-09-18 13:30:21 -0700610 /* If it's an encrypted Android partition, the last 16 Kbytes contain the
611 * encryption info footer and key, and plenty of bytes to spare for future
612 * growth.
613 */
Tom Cherry4c5bde22019-01-29 14:34:01 -0800614 strlcpy(cached_metadata_fname, real_blkdev.c_str(), sizeof(cached_metadata_fname));
Oleksiy Avramchenko625dc782018-05-23 10:50:46 +0200615 cached_off -= CRYPT_FOOTER_OFFSET;
Paul Crowley14c8c072018-09-18 13:30:21 -0700616 cached_data = 1;
617 } else {
Tom Cherry4c5bde22019-01-29 14:34:01 -0800618 SLOGE("Cannot get size of block device %s\n", real_blkdev.c_str());
Paul Crowley14c8c072018-09-18 13:30:21 -0700619 }
Paul Crowley14c8c072018-09-18 13:30:21 -0700620 } else {
Tom Cherry4c5bde22019-01-29 14:34:01 -0800621 strlcpy(cached_metadata_fname, key_loc.c_str(), sizeof(cached_metadata_fname));
Paul Crowley14c8c072018-09-18 13:30:21 -0700622 cached_off = 0;
623 cached_data = 1;
624 }
Ken Sumrall160b4d62013-04-22 12:15:39 -0700625 }
Ken Sumrall160b4d62013-04-22 12:15:39 -0700626
Paul Crowley14c8c072018-09-18 13:30:21 -0700627 if (cached_data) {
628 if (metadata_fname) {
629 *metadata_fname = cached_metadata_fname;
630 }
631 if (off) {
632 *off = cached_off;
633 }
634 rc = 0;
Ken Sumrall160b4d62013-04-22 12:15:39 -0700635 }
Ken Sumrall160b4d62013-04-22 12:15:39 -0700636
Paul Crowley14c8c072018-09-18 13:30:21 -0700637 return rc;
Ken Sumrall160b4d62013-04-22 12:15:39 -0700638}
639
Paul Lawrence3d99eba2015-11-20 07:07:19 -0800640/* Set sha256 checksum in structure */
Paul Crowley14c8c072018-09-18 13:30:21 -0700641static void set_ftr_sha(struct crypt_mnt_ftr* crypt_ftr) {
Paul Lawrence3d99eba2015-11-20 07:07:19 -0800642 SHA256_CTX c;
643 SHA256_Init(&c);
644 memset(crypt_ftr->sha256, 0, sizeof(crypt_ftr->sha256));
645 SHA256_Update(&c, crypt_ftr, sizeof(*crypt_ftr));
646 SHA256_Final(crypt_ftr->sha256, &c);
647}
648
Ken Sumralle8744072011-01-18 22:01:55 -0800649/* key or salt can be NULL, in which case just skip writing that value. Useful to
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800650 * update the failed mount count but not change the key.
651 */
Paul Crowley14c8c072018-09-18 13:30:21 -0700652static int put_crypt_ftr_and_key(struct crypt_mnt_ftr* crypt_ftr) {
653 int fd;
654 unsigned int cnt;
655 /* starting_off is set to the SEEK_SET offset
656 * where the crypto structure starts
657 */
658 off64_t starting_off;
659 int rc = -1;
660 char* fname = NULL;
661 struct stat statbuf;
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800662
Paul Crowley14c8c072018-09-18 13:30:21 -0700663 set_ftr_sha(crypt_ftr);
Paul Lawrence3d99eba2015-11-20 07:07:19 -0800664
Paul Crowley14c8c072018-09-18 13:30:21 -0700665 if (get_crypt_ftr_info(&fname, &starting_off)) {
666 SLOGE("Unable to get crypt_ftr_info\n");
667 return -1;
Ken Sumralle8744072011-01-18 22:01:55 -0800668 }
Paul Crowley14c8c072018-09-18 13:30:21 -0700669 if (fname[0] != '/') {
670 SLOGE("Unexpected value for crypto key location\n");
671 return -1;
672 }
673 if ((fd = open(fname, O_RDWR | O_CREAT | O_CLOEXEC, 0600)) < 0) {
674 SLOGE("Cannot open footer file %s for put\n", fname);
675 return -1;
676 }
Ken Sumralle8744072011-01-18 22:01:55 -0800677
Paul Crowley14c8c072018-09-18 13:30:21 -0700678 /* Seek to the start of the crypt footer */
679 if (lseek64(fd, starting_off, SEEK_SET) == -1) {
680 SLOGE("Cannot seek to real block device footer\n");
681 goto errout;
682 }
683
684 if ((cnt = write(fd, crypt_ftr, sizeof(struct crypt_mnt_ftr))) != sizeof(struct crypt_mnt_ftr)) {
685 SLOGE("Cannot write real block device footer\n");
686 goto errout;
687 }
688
689 fstat(fd, &statbuf);
690 /* If the keys are kept on a raw block device, do not try to truncate it. */
691 if (S_ISREG(statbuf.st_mode)) {
692 if (ftruncate(fd, 0x4000)) {
693 SLOGE("Cannot set footer file size\n");
694 goto errout;
695 }
696 }
697
698 /* Success! */
699 rc = 0;
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800700
701errout:
Paul Crowley14c8c072018-09-18 13:30:21 -0700702 close(fd);
703 return rc;
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800704}
705
Paul Crowley14c8c072018-09-18 13:30:21 -0700706static bool check_ftr_sha(const struct crypt_mnt_ftr* crypt_ftr) {
Paul Lawrence3d99eba2015-11-20 07:07:19 -0800707 struct crypt_mnt_ftr copy;
708 memcpy(&copy, crypt_ftr, sizeof(copy));
709 set_ftr_sha(&copy);
710 return memcmp(copy.sha256, crypt_ftr->sha256, sizeof(copy.sha256)) == 0;
711}
712
Paul Crowley14c8c072018-09-18 13:30:21 -0700713static inline int unix_read(int fd, void* buff, int len) {
Ken Sumrall160b4d62013-04-22 12:15:39 -0700714 return TEMP_FAILURE_RETRY(read(fd, buff, len));
715}
716
Paul Crowley14c8c072018-09-18 13:30:21 -0700717static inline int unix_write(int fd, const void* buff, int len) {
Ken Sumrall160b4d62013-04-22 12:15:39 -0700718 return TEMP_FAILURE_RETRY(write(fd, buff, len));
719}
720
Paul Crowley14c8c072018-09-18 13:30:21 -0700721static void init_empty_persist_data(struct crypt_persist_data* pdata, int len) {
Ken Sumrall160b4d62013-04-22 12:15:39 -0700722 memset(pdata, 0, len);
723 pdata->persist_magic = PERSIST_DATA_MAGIC;
724 pdata->persist_valid_entries = 0;
725}
726
727/* A routine to update the passed in crypt_ftr to the lastest version.
728 * fd is open read/write on the device that holds the crypto footer and persistent
729 * data, crypt_ftr is a pointer to the struct to be updated, and offset is the
730 * absolute offset to the start of the crypt_mnt_ftr on the passed in fd.
731 */
Paul Crowley14c8c072018-09-18 13:30:21 -0700732static void upgrade_crypt_ftr(int fd, struct crypt_mnt_ftr* crypt_ftr, off64_t offset) {
Kenny Root7434b312013-06-14 11:29:53 -0700733 int orig_major = crypt_ftr->major_version;
734 int orig_minor = crypt_ftr->minor_version;
Ken Sumrall160b4d62013-04-22 12:15:39 -0700735
Kenny Root7434b312013-06-14 11:29:53 -0700736 if ((crypt_ftr->major_version == 1) && (crypt_ftr->minor_version == 0)) {
Paul Crowley14c8c072018-09-18 13:30:21 -0700737 struct crypt_persist_data* pdata;
Kenny Root7434b312013-06-14 11:29:53 -0700738 off64_t pdata_offset = offset + CRYPT_FOOTER_TO_PERSIST_OFFSET;
Ken Sumrall160b4d62013-04-22 12:15:39 -0700739
Kenny Rootc4c70f12013-06-14 12:11:38 -0700740 SLOGW("upgrading crypto footer to 1.1");
741
Paul Crowley14c8c072018-09-18 13:30:21 -0700742 pdata = (crypt_persist_data*)malloc(CRYPT_PERSIST_DATA_SIZE);
Kenny Root7434b312013-06-14 11:29:53 -0700743 if (pdata == NULL) {
744 SLOGE("Cannot allocate persisent data\n");
745 return;
746 }
747 memset(pdata, 0, CRYPT_PERSIST_DATA_SIZE);
748
749 /* Need to initialize the persistent data area */
750 if (lseek64(fd, pdata_offset, SEEK_SET) == -1) {
751 SLOGE("Cannot seek to persisent data offset\n");
Henrik Baard91064632015-02-05 15:09:17 +0100752 free(pdata);
Kenny Root7434b312013-06-14 11:29:53 -0700753 return;
754 }
755 /* Write all zeros to the first copy, making it invalid */
756 unix_write(fd, pdata, CRYPT_PERSIST_DATA_SIZE);
757
758 /* Write a valid but empty structure to the second copy */
759 init_empty_persist_data(pdata, CRYPT_PERSIST_DATA_SIZE);
760 unix_write(fd, pdata, CRYPT_PERSIST_DATA_SIZE);
761
762 /* Update the footer */
763 crypt_ftr->persist_data_size = CRYPT_PERSIST_DATA_SIZE;
764 crypt_ftr->persist_data_offset[0] = pdata_offset;
765 crypt_ftr->persist_data_offset[1] = pdata_offset + CRYPT_PERSIST_DATA_SIZE;
766 crypt_ftr->minor_version = 1;
Henrik Baard91064632015-02-05 15:09:17 +0100767 free(pdata);
Ken Sumrall160b4d62013-04-22 12:15:39 -0700768 }
769
Paul Lawrencef4faa572014-01-29 13:31:03 -0800770 if ((crypt_ftr->major_version == 1) && (crypt_ftr->minor_version == 1)) {
Kenny Rootc4c70f12013-06-14 12:11:38 -0700771 SLOGW("upgrading crypto footer to 1.2");
JP Abgrall7bdfa522013-11-15 13:42:56 -0800772 /* But keep the old kdf_type.
773 * It will get updated later to KDF_SCRYPT after the password has been verified.
774 */
Kenny Rootc4c70f12013-06-14 12:11:38 -0700775 crypt_ftr->kdf_type = KDF_PBKDF2;
776 get_device_scrypt_params(crypt_ftr);
777 crypt_ftr->minor_version = 2;
778 }
779
Paul Lawrencef4faa572014-01-29 13:31:03 -0800780 if ((crypt_ftr->major_version == 1) && (crypt_ftr->minor_version == 2)) {
781 SLOGW("upgrading crypto footer to 1.3");
782 crypt_ftr->crypt_type = CRYPT_TYPE_PASSWORD;
783 crypt_ftr->minor_version = 3;
784 }
785
Kenny Root7434b312013-06-14 11:29:53 -0700786 if ((orig_major != crypt_ftr->major_version) || (orig_minor != crypt_ftr->minor_version)) {
787 if (lseek64(fd, offset, SEEK_SET) == -1) {
788 SLOGE("Cannot seek to crypt footer\n");
789 return;
790 }
791 unix_write(fd, crypt_ftr, sizeof(struct crypt_mnt_ftr));
Ken Sumrall160b4d62013-04-22 12:15:39 -0700792 }
Ken Sumrall160b4d62013-04-22 12:15:39 -0700793}
794
Paul Crowley14c8c072018-09-18 13:30:21 -0700795static int get_crypt_ftr_and_key(struct crypt_mnt_ftr* crypt_ftr) {
796 int fd;
797 unsigned int cnt;
798 off64_t starting_off;
799 int rc = -1;
800 char* fname = NULL;
801 struct stat statbuf;
Ken Sumrall160b4d62013-04-22 12:15:39 -0700802
Paul Crowley14c8c072018-09-18 13:30:21 -0700803 if (get_crypt_ftr_info(&fname, &starting_off)) {
804 SLOGE("Unable to get crypt_ftr_info\n");
805 return -1;
806 }
807 if (fname[0] != '/') {
808 SLOGE("Unexpected value for crypto key location\n");
809 return -1;
810 }
811 if ((fd = open(fname, O_RDWR | O_CLOEXEC)) < 0) {
812 SLOGE("Cannot open footer file %s for get\n", fname);
813 return -1;
814 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800815
Paul Crowley14c8c072018-09-18 13:30:21 -0700816 /* Make sure it's 16 Kbytes in length */
817 fstat(fd, &statbuf);
818 if (S_ISREG(statbuf.st_mode) && (statbuf.st_size != 0x4000)) {
819 SLOGE("footer file %s is not the expected size!\n", fname);
820 goto errout;
821 }
Ken Sumrall160b4d62013-04-22 12:15:39 -0700822
Paul Crowley14c8c072018-09-18 13:30:21 -0700823 /* Seek to the start of the crypt footer */
824 if (lseek64(fd, starting_off, SEEK_SET) == -1) {
825 SLOGE("Cannot seek to real block device footer\n");
826 goto errout;
827 }
Ken Sumrall160b4d62013-04-22 12:15:39 -0700828
Paul Crowley14c8c072018-09-18 13:30:21 -0700829 if ((cnt = read(fd, crypt_ftr, sizeof(struct crypt_mnt_ftr))) != sizeof(struct crypt_mnt_ftr)) {
830 SLOGE("Cannot read real block device footer\n");
831 goto errout;
832 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800833
Paul Crowley14c8c072018-09-18 13:30:21 -0700834 if (crypt_ftr->magic != CRYPT_MNT_MAGIC) {
835 SLOGE("Bad magic for real block device %s\n", fname);
836 goto errout;
837 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800838
Paul Crowley14c8c072018-09-18 13:30:21 -0700839 if (crypt_ftr->major_version != CURRENT_MAJOR_VERSION) {
840 SLOGE("Cannot understand major version %d real block device footer; expected %d\n",
841 crypt_ftr->major_version, CURRENT_MAJOR_VERSION);
842 goto errout;
843 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800844
Paul Crowley14c8c072018-09-18 13:30:21 -0700845 // We risk buffer overflows with oversized keys, so we just reject them.
846 // 0-sized keys are problematic (essentially by-passing encryption), and
847 // AES-CBC key wrapping only works for multiples of 16 bytes.
848 if ((crypt_ftr->keysize == 0) || ((crypt_ftr->keysize % 16) != 0) ||
849 (crypt_ftr->keysize > MAX_KEY_LEN)) {
850 SLOGE(
851 "Invalid keysize (%u) for block device %s; Must be non-zero, "
852 "divisible by 16, and <= %d\n",
853 crypt_ftr->keysize, fname, MAX_KEY_LEN);
854 goto errout;
855 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800856
Paul Crowley14c8c072018-09-18 13:30:21 -0700857 if (crypt_ftr->minor_version > CURRENT_MINOR_VERSION) {
858 SLOGW("Warning: crypto footer minor version %d, expected <= %d, continuing...\n",
859 crypt_ftr->minor_version, CURRENT_MINOR_VERSION);
860 }
Greg Kaiser59ad0182018-02-16 13:01:36 -0800861
Paul Crowley14c8c072018-09-18 13:30:21 -0700862 /* If this is a verion 1.0 crypt_ftr, make it a 1.1 crypt footer, and update the
863 * copy on disk before returning.
864 */
865 if (crypt_ftr->minor_version < CURRENT_MINOR_VERSION) {
866 upgrade_crypt_ftr(fd, crypt_ftr, starting_off);
867 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800868
Paul Crowley14c8c072018-09-18 13:30:21 -0700869 /* Success! */
870 rc = 0;
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800871
872errout:
Paul Crowley14c8c072018-09-18 13:30:21 -0700873 close(fd);
874 return rc;
Ken Sumrall8f869aa2010-12-03 03:47:09 -0800875}
876
Paul Crowley14c8c072018-09-18 13:30:21 -0700877static int validate_persistent_data_storage(struct crypt_mnt_ftr* crypt_ftr) {
Ken Sumrall160b4d62013-04-22 12:15:39 -0700878 if (crypt_ftr->persist_data_offset[0] + crypt_ftr->persist_data_size >
879 crypt_ftr->persist_data_offset[1]) {
880 SLOGE("Crypt_ftr persist data regions overlap");
881 return -1;
882 }
883
884 if (crypt_ftr->persist_data_offset[0] >= crypt_ftr->persist_data_offset[1]) {
885 SLOGE("Crypt_ftr persist data region 0 starts after region 1");
886 return -1;
887 }
888
889 if (((crypt_ftr->persist_data_offset[1] + crypt_ftr->persist_data_size) -
Paul Crowley14c8c072018-09-18 13:30:21 -0700890 (crypt_ftr->persist_data_offset[0] - CRYPT_FOOTER_TO_PERSIST_OFFSET)) >
Ken Sumrall160b4d62013-04-22 12:15:39 -0700891 CRYPT_FOOTER_OFFSET) {
892 SLOGE("Persistent data extends past crypto footer");
893 return -1;
894 }
895
896 return 0;
897}
898
Paul Crowley14c8c072018-09-18 13:30:21 -0700899static int load_persistent_data(void) {
Ken Sumrall160b4d62013-04-22 12:15:39 -0700900 struct crypt_mnt_ftr crypt_ftr;
Paul Crowley14c8c072018-09-18 13:30:21 -0700901 struct crypt_persist_data* pdata = NULL;
Ken Sumrall160b4d62013-04-22 12:15:39 -0700902 char encrypted_state[PROPERTY_VALUE_MAX];
Paul Crowley14c8c072018-09-18 13:30:21 -0700903 char* fname;
Ken Sumrall160b4d62013-04-22 12:15:39 -0700904 int found = 0;
905 int fd;
906 int ret;
907 int i;
908
909 if (persist_data) {
910 /* Nothing to do, we've already loaded or initialized it */
911 return 0;
912 }
913
Ken Sumrall160b4d62013-04-22 12:15:39 -0700914 /* If not encrypted, just allocate an empty table and initialize it */
915 property_get("ro.crypto.state", encrypted_state, "");
Paul Crowley14c8c072018-09-18 13:30:21 -0700916 if (strcmp(encrypted_state, "encrypted")) {
Wei Wang4375f1b2017-02-24 17:43:01 -0800917 pdata = (crypt_persist_data*)malloc(CRYPT_PERSIST_DATA_SIZE);
Ken Sumrall160b4d62013-04-22 12:15:39 -0700918 if (pdata) {
919 init_empty_persist_data(pdata, CRYPT_PERSIST_DATA_SIZE);
920 persist_data = pdata;
921 return 0;
922 }
923 return -1;
924 }
925
Paul Crowley14c8c072018-09-18 13:30:21 -0700926 if (get_crypt_ftr_and_key(&crypt_ftr)) {
Ken Sumrall160b4d62013-04-22 12:15:39 -0700927 return -1;
928 }
929
Paul Crowley14c8c072018-09-18 13:30:21 -0700930 if ((crypt_ftr.major_version < 1) ||
931 (crypt_ftr.major_version == 1 && crypt_ftr.minor_version < 1)) {
Ken Sumrall160b4d62013-04-22 12:15:39 -0700932 SLOGE("Crypt_ftr version doesn't support persistent data");
933 return -1;
934 }
935
936 if (get_crypt_ftr_info(&fname, NULL)) {
937 return -1;
938 }
939
940 ret = validate_persistent_data_storage(&crypt_ftr);
941 if (ret) {
942 return -1;
943 }
944
Paul Crowley14c8c072018-09-18 13:30:21 -0700945 fd = open(fname, O_RDONLY | O_CLOEXEC);
Ken Sumrall160b4d62013-04-22 12:15:39 -0700946 if (fd < 0) {
947 SLOGE("Cannot open %s metadata file", fname);
948 return -1;
949 }
950
Wei Wang4375f1b2017-02-24 17:43:01 -0800951 pdata = (crypt_persist_data*)malloc(crypt_ftr.persist_data_size);
Paul Lawrence300dae72016-03-11 11:02:52 -0800952 if (pdata == NULL) {
953 SLOGE("Cannot allocate memory for persistent data");
954 goto err;
Ken Sumrall160b4d62013-04-22 12:15:39 -0700955 }
956
957 for (i = 0; i < 2; i++) {
958 if (lseek64(fd, crypt_ftr.persist_data_offset[i], SEEK_SET) < 0) {
959 SLOGE("Cannot seek to read persistent data on %s", fname);
960 goto err2;
961 }
Paul Crowley14c8c072018-09-18 13:30:21 -0700962 if (unix_read(fd, pdata, crypt_ftr.persist_data_size) < 0) {
Ken Sumrall160b4d62013-04-22 12:15:39 -0700963 SLOGE("Error reading persistent data on iteration %d", i);
964 goto err2;
965 }
966 if (pdata->persist_magic == PERSIST_DATA_MAGIC) {
967 found = 1;
968 break;
969 }
970 }
971
972 if (!found) {
973 SLOGI("Could not find valid persistent data, creating");
974 init_empty_persist_data(pdata, crypt_ftr.persist_data_size);
975 }
976
977 /* Success */
978 persist_data = pdata;
979 close(fd);
980 return 0;
981
982err2:
983 free(pdata);
984
985err:
986 close(fd);
987 return -1;
988}
989
Paul Crowley14c8c072018-09-18 13:30:21 -0700990static int save_persistent_data(void) {
Ken Sumrall160b4d62013-04-22 12:15:39 -0700991 struct crypt_mnt_ftr crypt_ftr;
Paul Crowley14c8c072018-09-18 13:30:21 -0700992 struct crypt_persist_data* pdata;
993 char* fname;
Ken Sumrall160b4d62013-04-22 12:15:39 -0700994 off64_t write_offset;
995 off64_t erase_offset;
Ken Sumrall160b4d62013-04-22 12:15:39 -0700996 int fd;
997 int ret;
998
999 if (persist_data == NULL) {
1000 SLOGE("No persistent data to save");
1001 return -1;
1002 }
1003
Paul Crowley14c8c072018-09-18 13:30:21 -07001004 if (get_crypt_ftr_and_key(&crypt_ftr)) {
Ken Sumrall160b4d62013-04-22 12:15:39 -07001005 return -1;
1006 }
1007
Paul Crowley14c8c072018-09-18 13:30:21 -07001008 if ((crypt_ftr.major_version < 1) ||
1009 (crypt_ftr.major_version == 1 && crypt_ftr.minor_version < 1)) {
Ken Sumrall160b4d62013-04-22 12:15:39 -07001010 SLOGE("Crypt_ftr version doesn't support persistent data");
1011 return -1;
1012 }
1013
1014 ret = validate_persistent_data_storage(&crypt_ftr);
1015 if (ret) {
1016 return -1;
1017 }
1018
1019 if (get_crypt_ftr_info(&fname, NULL)) {
1020 return -1;
1021 }
1022
Paul Crowley14c8c072018-09-18 13:30:21 -07001023 fd = open(fname, O_RDWR | O_CLOEXEC);
Ken Sumrall160b4d62013-04-22 12:15:39 -07001024 if (fd < 0) {
1025 SLOGE("Cannot open %s metadata file", fname);
1026 return -1;
1027 }
1028
Wei Wang4375f1b2017-02-24 17:43:01 -08001029 pdata = (crypt_persist_data*)malloc(crypt_ftr.persist_data_size);
Ken Sumrall160b4d62013-04-22 12:15:39 -07001030 if (pdata == NULL) {
1031 SLOGE("Cannot allocate persistant data");
1032 goto err;
1033 }
1034
1035 if (lseek64(fd, crypt_ftr.persist_data_offset[0], SEEK_SET) < 0) {
1036 SLOGE("Cannot seek to read persistent data on %s", fname);
1037 goto err2;
1038 }
1039
1040 if (unix_read(fd, pdata, crypt_ftr.persist_data_size) < 0) {
Paul Crowley14c8c072018-09-18 13:30:21 -07001041 SLOGE("Error reading persistent data before save");
1042 goto err2;
Ken Sumrall160b4d62013-04-22 12:15:39 -07001043 }
1044
1045 if (pdata->persist_magic == PERSIST_DATA_MAGIC) {
1046 /* The first copy is the curent valid copy, so write to
1047 * the second copy and erase this one */
Paul Crowley14c8c072018-09-18 13:30:21 -07001048 write_offset = crypt_ftr.persist_data_offset[1];
1049 erase_offset = crypt_ftr.persist_data_offset[0];
Ken Sumrall160b4d62013-04-22 12:15:39 -07001050 } else {
1051 /* The second copy must be the valid copy, so write to
1052 * the first copy, and erase the second */
Paul Crowley14c8c072018-09-18 13:30:21 -07001053 write_offset = crypt_ftr.persist_data_offset[0];
1054 erase_offset = crypt_ftr.persist_data_offset[1];
Ken Sumrall160b4d62013-04-22 12:15:39 -07001055 }
1056
1057 /* Write the new copy first, if successful, then erase the old copy */
Björn Landström96dbee72015-01-20 12:43:56 +01001058 if (lseek64(fd, write_offset, SEEK_SET) < 0) {
Ken Sumrall160b4d62013-04-22 12:15:39 -07001059 SLOGE("Cannot seek to write persistent data");
1060 goto err2;
1061 }
1062 if (unix_write(fd, persist_data, crypt_ftr.persist_data_size) ==
Paul Crowley14c8c072018-09-18 13:30:21 -07001063 (int)crypt_ftr.persist_data_size) {
Björn Landström96dbee72015-01-20 12:43:56 +01001064 if (lseek64(fd, erase_offset, SEEK_SET) < 0) {
Ken Sumrall160b4d62013-04-22 12:15:39 -07001065 SLOGE("Cannot seek to erase previous persistent data");
1066 goto err2;
1067 }
1068 fsync(fd);
1069 memset(pdata, 0, crypt_ftr.persist_data_size);
Paul Crowley14c8c072018-09-18 13:30:21 -07001070 if (unix_write(fd, pdata, crypt_ftr.persist_data_size) != (int)crypt_ftr.persist_data_size) {
Ken Sumrall160b4d62013-04-22 12:15:39 -07001071 SLOGE("Cannot write to erase previous persistent data");
1072 goto err2;
1073 }
1074 fsync(fd);
1075 } else {
1076 SLOGE("Cannot write to save persistent data");
1077 goto err2;
1078 }
1079
1080 /* Success */
1081 free(pdata);
1082 close(fd);
1083 return 0;
1084
1085err2:
1086 free(pdata);
1087err:
1088 close(fd);
1089 return -1;
1090}
1091
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001092/* Convert a binary key of specified length into an ascii hex string equivalent,
1093 * without the leading 0x and with null termination
1094 */
Paul Crowley14c8c072018-09-18 13:30:21 -07001095static void convert_key_to_hex_ascii(const unsigned char* master_key, unsigned int keysize,
1096 char* master_key_ascii) {
Paul Lawrence3bd36d52015-06-09 13:37:44 -07001097 unsigned int i, a;
1098 unsigned char nibble;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001099
Paul Crowley14c8c072018-09-18 13:30:21 -07001100 for (i = 0, a = 0; i < keysize; i++, a += 2) {
Paul Lawrence3bd36d52015-06-09 13:37:44 -07001101 /* For each byte, write out two ascii hex digits */
1102 nibble = (master_key[i] >> 4) & 0xf;
1103 master_key_ascii[a] = nibble + (nibble > 9 ? 0x37 : 0x30);
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001104
Paul Lawrence3bd36d52015-06-09 13:37:44 -07001105 nibble = master_key[i] & 0xf;
Paul Crowley14c8c072018-09-18 13:30:21 -07001106 master_key_ascii[a + 1] = nibble + (nibble > 9 ? 0x37 : 0x30);
Paul Lawrence3bd36d52015-06-09 13:37:44 -07001107 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001108
Paul Lawrence3bd36d52015-06-09 13:37:44 -07001109 /* Add the null termination */
1110 master_key_ascii[a] = '\0';
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001111}
1112
Eric Biggersed45ec32019-01-25 10:47:55 -08001113/*
1114 * If the ro.crypto.fde_sector_size system property is set, append the
1115 * parameters to make dm-crypt use the specified crypto sector size and round
1116 * the crypto device size down to a crypto sector boundary.
1117 */
David Andersonb9224732019-05-13 13:02:54 -07001118static int add_sector_size_param(DmTargetCrypt* target, struct crypt_mnt_ftr* ftr) {
Greg Kaiserab1e84a2018-12-11 12:40:51 -08001119 constexpr char DM_CRYPT_SECTOR_SIZE[] = "ro.crypto.fde_sector_size";
Eric Biggersed45ec32019-01-25 10:47:55 -08001120 char value[PROPERTY_VALUE_MAX];
Greg Kaiserab1e84a2018-12-11 12:40:51 -08001121
Eric Biggersed45ec32019-01-25 10:47:55 -08001122 if (property_get(DM_CRYPT_SECTOR_SIZE, value, "") > 0) {
1123 unsigned int sector_size;
1124
1125 if (!ParseUint(value, &sector_size) || sector_size < 512 || sector_size > 4096 ||
1126 (sector_size & (sector_size - 1)) != 0) {
1127 SLOGE("Invalid value for %s: %s. Must be >= 512, <= 4096, and a power of 2\n",
1128 DM_CRYPT_SECTOR_SIZE, value);
1129 return -1;
1130 }
1131
David Andersonb9224732019-05-13 13:02:54 -07001132 target->SetSectorSize(sector_size);
Greg Kaiserab1e84a2018-12-11 12:40:51 -08001133
1134 // With this option, IVs will match the sector numbering, instead
1135 // of being hard-coded to being based on 512-byte sectors.
David Andersonb9224732019-05-13 13:02:54 -07001136 target->SetIvLargeSectors();
Eric Biggersed45ec32019-01-25 10:47:55 -08001137
1138 // Round the crypto device size down to a crypto sector boundary.
1139 ftr->fs_size &= ~((sector_size / 512) - 1);
Greg Kaiserab1e84a2018-12-11 12:40:51 -08001140 }
Eric Biggersed45ec32019-01-25 10:47:55 -08001141 return 0;
Greg Kaiserab1e84a2018-12-11 12:40:51 -08001142}
1143
Neeraj Soni73b46952019-09-12 16:47:27 +05301144#if defined(CONFIG_HW_DISK_ENCRYPTION) && !defined(CONFIG_HW_DISK_ENCRYPT_PERF)
1145#define DM_CRYPT_BUF_SIZE 4096
1146
1147static void ioctl_init(struct dm_ioctl* io, size_t dataSize, const char* name, unsigned flags) {
1148 memset(io, 0, dataSize);
1149 io->data_size = dataSize;
1150 io->data_start = sizeof(struct dm_ioctl);
1151 io->version[0] = 4;
1152 io->version[1] = 0;
1153 io->version[2] = 0;
1154 io->flags = flags;
1155 if (name) {
1156 strlcpy(io->name, name, sizeof(io->name));
1157 }
1158}
1159
1160static int load_crypto_mapping_table(struct crypt_mnt_ftr* crypt_ftr,
1161 const unsigned char* master_key, const char* real_blk_name,
1162 const char* name, int fd, const char* extra_params) {
1163 alignas(struct dm_ioctl) char buffer[DM_CRYPT_BUF_SIZE];
1164 struct dm_ioctl* io;
1165 struct dm_target_spec* tgt;
1166 char* crypt_params;
1167 // We need two ASCII characters to represent each byte, and need space for
1168 // the '\0' terminator.
1169 char master_key_ascii[MAX_KEY_LEN * 2 + 1];
1170 size_t buff_offset;
1171 int i;
1172
1173 io = (struct dm_ioctl*)buffer;
1174
1175 /* Load the mapping table for this device */
1176 tgt = (struct dm_target_spec*)&buffer[sizeof(struct dm_ioctl)];
1177
1178 ioctl_init(io, DM_CRYPT_BUF_SIZE, name, 0);
1179 io->target_count = 1;
1180 tgt->status = 0;
1181 tgt->sector_start = 0;
1182 tgt->length = crypt_ftr->fs_size;
1183 crypt_params = buffer + sizeof(struct dm_ioctl) + sizeof(struct dm_target_spec);
1184 buff_offset = crypt_params - buffer;
1185 SLOGI(
1186 "Creating crypto dev \"%s\"; cipher=%s, keysize=%u, real_dev=%s, len=%llu, params=\"%s\"\n",
1187 name, crypt_ftr->crypto_type_name, crypt_ftr->keysize, real_blk_name, tgt->length * 512,
1188 extra_params);
1189 if(is_hw_disk_encryption((char*)crypt_ftr->crypto_type_name)) {
1190 strlcpy(tgt->target_type, "req-crypt",DM_MAX_TYPE_NAME);
1191 if (is_ice_enabled())
1192 convert_key_to_hex_ascii(master_key, sizeof(int), master_key_ascii);
1193 else
1194 convert_key_to_hex_ascii(master_key, crypt_ftr->keysize, master_key_ascii);
1195 }
1196 snprintf(crypt_params, sizeof(buffer) - buff_offset, "%s %s 0 %s 0 %s 0",
1197 crypt_ftr->crypto_type_name, master_key_ascii,
1198 real_blk_name, extra_params);
1199
1200 SLOGI("target_type = %s", tgt->target_type);
1201 SLOGI("real_blk_name = %s, extra_params = %s", real_blk_name, extra_params);
1202
1203 crypt_params += strlen(crypt_params) + 1;
1204 crypt_params =
1205 (char*)(((unsigned long)crypt_params + 7) & ~8); /* Align to an 8 byte boundary */
1206 tgt->next = crypt_params - buffer;
1207
1208 for (i = 0; i < TABLE_LOAD_RETRIES; i++) {
1209 if (!ioctl(fd, DM_TABLE_LOAD, io)) {
1210 break;
1211 }
1212 usleep(500000);
1213 }
1214
1215 if (i == TABLE_LOAD_RETRIES) {
1216 /* We failed to load the table, return an error */
1217 return -1;
1218 } else {
1219 return i + 1;
1220 }
1221}
1222
1223static int create_crypto_blk_dev_hw(struct crypt_mnt_ftr* crypt_ftr, const unsigned char* master_key,
1224 const char* real_blk_name, char* crypto_blk_name, const char* name,
1225 uint32_t flags) {
1226 char buffer[DM_CRYPT_BUF_SIZE];
1227 struct dm_ioctl* io;
1228 unsigned int minor;
1229 int fd = 0;
1230 int err;
1231 int retval = -1;
1232 int version[3];
1233 int load_count;
1234 char encrypted_state[PROPERTY_VALUE_MAX] = {0};
1235 char progress[PROPERTY_VALUE_MAX] = {0};
1236 const char *extra_params;
1237
1238 if ((fd = open("/dev/device-mapper", O_RDWR | O_CLOEXEC)) < 0) {
1239 SLOGE("Cannot open device-mapper\n");
1240 goto errout;
1241 }
1242
1243 io = (struct dm_ioctl*)buffer;
1244
1245 ioctl_init(io, DM_CRYPT_BUF_SIZE, name, 0);
1246 err = ioctl(fd, DM_DEV_CREATE, io);
1247 if (err) {
1248 SLOGE("Cannot create dm-crypt device %s: %s\n", name, strerror(errno));
1249 goto errout;
1250 }
1251
1252 /* Get the device status, in particular, the name of it's device file */
1253 ioctl_init(io, DM_CRYPT_BUF_SIZE, name, 0);
1254 if (ioctl(fd, DM_DEV_STATUS, io)) {
1255 SLOGE("Cannot retrieve dm-crypt device status\n");
1256 goto errout;
1257 }
1258 minor = (io->dev & 0xff) | ((io->dev >> 12) & 0xfff00);
1259 snprintf(crypto_blk_name, MAXPATHLEN, "/dev/block/dm-%u", minor);
1260
1261 if(is_hw_disk_encryption((char*)crypt_ftr->crypto_type_name)) {
1262 /* Set fde_enabled if either FDE completed or in-progress */
1263 property_get("ro.crypto.state", encrypted_state, ""); /* FDE completed */
1264 property_get("vold.encrypt_progress", progress, ""); /* FDE in progress */
1265 if (!strcmp(encrypted_state, "encrypted") || strcmp(progress, "")) {
1266 if (is_ice_enabled()) {
1267 extra_params = "fde_enabled ice allow_encrypt_override";
1268 } else {
1269 extra_params = "fde_enabled allow_encrypt_override";
1270 }
1271 } else {
1272 extra_params = "fde_enabled allow_encrypt_override";
1273 }
1274 load_count = load_crypto_mapping_table(crypt_ftr, master_key, real_blk_name, name, fd,
1275 extra_params);
1276 }
1277
1278 if (load_count < 0) {
1279 SLOGE("Cannot load dm-crypt mapping table.\n");
1280 goto errout;
1281 } else if (load_count > 1) {
1282 SLOGI("Took %d tries to load dmcrypt table.\n", load_count);
1283 }
1284
1285 /* Resume this device to activate it */
1286 ioctl_init(io, DM_CRYPT_BUF_SIZE, name, 0);
1287
1288 if (ioctl(fd, DM_DEV_SUSPEND, io)) {
1289 SLOGE("Cannot resume the dm-crypt device\n");
1290 goto errout;
1291 }
1292
1293 /* Ensure the dm device has been created before returning. */
1294 if (android::vold::WaitForFile(crypto_blk_name, 1s) < 0) {
1295 // WaitForFile generates a suitable log message
1296 goto errout;
1297 }
1298
1299 /* We made it here with no errors. Woot! */
1300 retval = 0;
1301
1302errout:
1303 close(fd); /* If fd is <0 from a failed open call, it's safe to just ignore the close error */
1304
1305 return retval;
1306}
1307#endif
1308
Paul Crowley5afbc622017-11-27 09:42:17 -08001309static int create_crypto_blk_dev(struct crypt_mnt_ftr* crypt_ftr, const unsigned char* master_key,
1310 const char* real_blk_name, char* crypto_blk_name, const char* name,
1311 uint32_t flags) {
David Andersonb9224732019-05-13 13:02:54 -07001312 auto& dm = DeviceMapper::Instance();
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001313
David Andersonb9224732019-05-13 13:02:54 -07001314 // We need two ASCII characters to represent each byte, and need space for
1315 // the '\0' terminator.
1316 char master_key_ascii[MAX_KEY_LEN * 2 + 1];
1317 convert_key_to_hex_ascii(master_key, crypt_ftr->keysize, master_key_ascii);
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001318
David Andersonb9224732019-05-13 13:02:54 -07001319 auto target = std::make_unique<DmTargetCrypt>(0, crypt_ftr->fs_size,
1320 (const char*)crypt_ftr->crypto_type_name,
1321 master_key_ascii, 0, real_blk_name, 0);
1322 target->AllowDiscards();
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001323
Paul Crowley5afbc622017-11-27 09:42:17 -08001324 if (flags & CREATE_CRYPTO_BLK_DEV_FLAGS_ALLOW_ENCRYPT_OVERRIDE) {
David Andersonb9224732019-05-13 13:02:54 -07001325 target->AllowEncryptOverride();
Paul Crowley5afbc622017-11-27 09:42:17 -08001326 }
David Andersonb9224732019-05-13 13:02:54 -07001327 if (add_sector_size_param(target.get(), crypt_ftr)) {
Eric Biggersed45ec32019-01-25 10:47:55 -08001328 SLOGE("Error processing dm-crypt sector size param\n");
David Andersonb9224732019-05-13 13:02:54 -07001329 return -1;
Eric Biggersed45ec32019-01-25 10:47:55 -08001330 }
David Andersonb9224732019-05-13 13:02:54 -07001331
1332 DmTable table;
1333 table.AddTarget(std::move(target));
1334
1335 int load_count = 1;
1336 while (load_count < TABLE_LOAD_RETRIES) {
1337 if (dm.CreateDevice(name, table)) {
1338 break;
1339 }
1340 load_count++;
1341 }
1342
1343 if (load_count >= TABLE_LOAD_RETRIES) {
Paul Crowley5afbc622017-11-27 09:42:17 -08001344 SLOGE("Cannot load dm-crypt mapping table.\n");
David Andersonb9224732019-05-13 13:02:54 -07001345 return -1;
1346 }
1347 if (load_count > 1) {
Paul Crowley5afbc622017-11-27 09:42:17 -08001348 SLOGI("Took %d tries to load dmcrypt table.\n", load_count);
1349 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001350
David Andersonb9224732019-05-13 13:02:54 -07001351 std::string path;
1352 if (!dm.GetDmDevicePathByName(name, &path)) {
1353 SLOGE("Cannot determine dm-crypt path for %s.\n", name);
1354 return -1;
Paul Crowley5afbc622017-11-27 09:42:17 -08001355 }
David Andersonb9224732019-05-13 13:02:54 -07001356 snprintf(crypto_blk_name, MAXPATHLEN, "%s", path.c_str());
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001357
Paul Crowley298fa322018-10-30 15:59:24 -07001358 /* Ensure the dm device has been created before returning. */
1359 if (android::vold::WaitForFile(crypto_blk_name, 1s) < 0) {
1360 // WaitForFile generates a suitable log message
David Andersonb9224732019-05-13 13:02:54 -07001361 return -1;
Paul Crowley298fa322018-10-30 15:59:24 -07001362 }
David Andersonb9224732019-05-13 13:02:54 -07001363 return 0;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001364}
1365
David Andersonb9224732019-05-13 13:02:54 -07001366static int delete_crypto_blk_dev(const std::string& name) {
1367 auto& dm = DeviceMapper::Instance();
1368 if (!dm.DeleteDevice(name)) {
1369 SLOGE("Cannot remove dm-crypt device %s: %s\n", name.c_str(), strerror(errno));
1370 return -1;
Paul Crowley14c8c072018-09-18 13:30:21 -07001371 }
David Andersonb9224732019-05-13 13:02:54 -07001372 return 0;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001373}
1374
Paul Crowley14c8c072018-09-18 13:30:21 -07001375static int pbkdf2(const char* passwd, const unsigned char* salt, unsigned char* ikey,
1376 void* params UNUSED) {
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001377 SLOGI("Using pbkdf2 for cryptfs KDF");
1378
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001379 /* Turn the password into a key and IV that can decrypt the master key */
Paul Crowley14c8c072018-09-18 13:30:21 -07001380 return PKCS5_PBKDF2_HMAC_SHA1(passwd, strlen(passwd), salt, SALT_LEN, HASH_COUNT,
1381 INTERMEDIATE_BUF_SIZE, ikey) != 1;
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001382}
1383
Paul Crowley14c8c072018-09-18 13:30:21 -07001384static int scrypt(const char* passwd, const unsigned char* salt, unsigned char* ikey, void* params) {
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001385 SLOGI("Using scrypt for cryptfs KDF");
1386
Paul Crowley14c8c072018-09-18 13:30:21 -07001387 struct crypt_mnt_ftr* ftr = (struct crypt_mnt_ftr*)params;
Kenny Rootc4c70f12013-06-14 12:11:38 -07001388
1389 int N = 1 << ftr->N_factor;
1390 int r = 1 << ftr->r_factor;
1391 int p = 1 << ftr->p_factor;
1392
1393 /* Turn the password into a key and IV that can decrypt the master key */
Paul Crowley14c8c072018-09-18 13:30:21 -07001394 crypto_scrypt((const uint8_t*)passwd, strlen(passwd), salt, SALT_LEN, N, r, p, ikey,
Greg Kaiserc0de9c72018-02-14 20:05:54 -08001395 INTERMEDIATE_BUF_SIZE);
Paul Lawrencef4faa572014-01-29 13:31:03 -08001396
Paul Crowley14c8c072018-09-18 13:30:21 -07001397 return 0;
Kenny Rootc4c70f12013-06-14 12:11:38 -07001398}
1399
Paul Crowley14c8c072018-09-18 13:30:21 -07001400static int scrypt_keymaster(const char* passwd, const unsigned char* salt, unsigned char* ikey,
1401 void* params) {
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001402 SLOGI("Using scrypt with keymaster for cryptfs KDF");
1403
1404 int rc;
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001405 size_t signature_size;
1406 unsigned char* signature;
Paul Crowley14c8c072018-09-18 13:30:21 -07001407 struct crypt_mnt_ftr* ftr = (struct crypt_mnt_ftr*)params;
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001408
1409 int N = 1 << ftr->N_factor;
1410 int r = 1 << ftr->r_factor;
1411 int p = 1 << ftr->p_factor;
1412
Paul Crowley14c8c072018-09-18 13:30:21 -07001413 rc = crypto_scrypt((const uint8_t*)passwd, strlen(passwd), salt, SALT_LEN, N, r, p, ikey,
Greg Kaiserc0de9c72018-02-14 20:05:54 -08001414 INTERMEDIATE_BUF_SIZE);
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001415
1416 if (rc) {
1417 SLOGE("scrypt failed");
1418 return -1;
1419 }
1420
Paul Crowley14c8c072018-09-18 13:30:21 -07001421 if (keymaster_sign_object(ftr, ikey, INTERMEDIATE_BUF_SIZE, &signature, &signature_size)) {
Shawn Willdene17a9c42014-09-08 13:04:08 -06001422 SLOGE("Signing failed");
1423 return -1;
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001424 }
1425
Paul Crowley14c8c072018-09-18 13:30:21 -07001426 rc = crypto_scrypt(signature, signature_size, salt, SALT_LEN, N, r, p, ikey,
1427 INTERMEDIATE_BUF_SIZE);
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001428 free(signature);
1429
1430 if (rc) {
1431 SLOGE("scrypt failed");
1432 return -1;
1433 }
1434
1435 return 0;
1436}
1437
Paul Crowley14c8c072018-09-18 13:30:21 -07001438static int encrypt_master_key(const char* passwd, const unsigned char* salt,
1439 const unsigned char* decrypted_master_key,
Bill Peckham0db11972018-10-10 10:25:42 -07001440 unsigned char* encrypted_master_key, struct crypt_mnt_ftr* crypt_ftr,
1441 bool create_keymaster_key) {
Paul Crowley14c8c072018-09-18 13:30:21 -07001442 unsigned char ikey[INTERMEDIATE_BUF_SIZE] = {0};
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001443 EVP_CIPHER_CTX e_ctx;
1444 int encrypted_len, final_len;
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001445 int rc = 0;
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001446
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001447 /* Turn the password into an intermediate key and IV that can decrypt the master key */
Kenny Rootc4c70f12013-06-14 12:11:38 -07001448 get_device_scrypt_params(crypt_ftr);
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001449
1450 switch (crypt_ftr->kdf_type) {
Paul Crowley14c8c072018-09-18 13:30:21 -07001451 case KDF_SCRYPT_KEYMASTER:
Bill Peckham0db11972018-10-10 10:25:42 -07001452 if (create_keymaster_key && keymaster_create_key(crypt_ftr)) {
Paul Crowley14c8c072018-09-18 13:30:21 -07001453 SLOGE("keymaster_create_key failed");
1454 return -1;
1455 }
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001456
Paul Crowley14c8c072018-09-18 13:30:21 -07001457 if (scrypt_keymaster(passwd, salt, ikey, crypt_ftr)) {
1458 SLOGE("scrypt failed");
1459 return -1;
1460 }
1461 break;
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001462
Paul Crowley14c8c072018-09-18 13:30:21 -07001463 case KDF_SCRYPT:
1464 if (scrypt(passwd, salt, ikey, crypt_ftr)) {
1465 SLOGE("scrypt failed");
1466 return -1;
1467 }
1468 break;
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001469
Paul Crowley14c8c072018-09-18 13:30:21 -07001470 default:
1471 SLOGE("Invalid kdf_type");
1472 return -1;
Paul Lawrencef4faa572014-01-29 13:31:03 -08001473 }
Kenny Rootc4c70f12013-06-14 12:11:38 -07001474
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001475 /* Initialize the decryption engine */
Adam Langley889c4f12014-09-03 14:23:13 -07001476 EVP_CIPHER_CTX_init(&e_ctx);
Paul Crowley14c8c072018-09-18 13:30:21 -07001477 if (!EVP_EncryptInit_ex(&e_ctx, EVP_aes_128_cbc(), NULL, ikey,
1478 ikey + INTERMEDIATE_KEY_LEN_BYTES)) {
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001479 SLOGE("EVP_EncryptInit failed\n");
1480 return -1;
1481 }
1482 EVP_CIPHER_CTX_set_padding(&e_ctx, 0); /* Turn off padding as our data is block aligned */
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001483
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001484 /* Encrypt the master key */
Paul Crowley14c8c072018-09-18 13:30:21 -07001485 if (!EVP_EncryptUpdate(&e_ctx, encrypted_master_key, &encrypted_len, decrypted_master_key,
1486 crypt_ftr->keysize)) {
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001487 SLOGE("EVP_EncryptUpdate failed\n");
1488 return -1;
1489 }
Paul Crowley14c8c072018-09-18 13:30:21 -07001490 if (!EVP_EncryptFinal_ex(&e_ctx, encrypted_master_key + encrypted_len, &final_len)) {
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001491 SLOGE("EVP_EncryptFinal failed\n");
1492 return -1;
1493 }
1494
Greg Kaiser59ad0182018-02-16 13:01:36 -08001495 if (encrypted_len + final_len != static_cast<int>(crypt_ftr->keysize)) {
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001496 SLOGE("EVP_Encryption length check failed with %d, %d bytes\n", encrypted_len, final_len);
1497 return -1;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001498 }
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001499
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001500 /* Store the scrypt of the intermediate key, so we can validate if it's a
1501 password error or mount error when things go wrong.
1502 Note there's no need to check for errors, since if this is incorrect, we
1503 simply won't wipe userdata, which is the correct default behavior
1504 */
1505 int N = 1 << crypt_ftr->N_factor;
1506 int r = 1 << crypt_ftr->r_factor;
1507 int p = 1 << crypt_ftr->p_factor;
1508
Paul Crowley14c8c072018-09-18 13:30:21 -07001509 rc = crypto_scrypt(ikey, INTERMEDIATE_KEY_LEN_BYTES, crypt_ftr->salt, sizeof(crypt_ftr->salt),
1510 N, r, p, crypt_ftr->scrypted_intermediate_key,
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001511 sizeof(crypt_ftr->scrypted_intermediate_key));
1512
1513 if (rc) {
Paul Crowley14c8c072018-09-18 13:30:21 -07001514 SLOGE("encrypt_master_key: crypto_scrypt failed");
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001515 }
1516
Thurston Hou Yeen Dang06dc3112016-07-18 14:16:37 -07001517 EVP_CIPHER_CTX_cleanup(&e_ctx);
1518
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001519 return 0;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001520}
1521
Paul Crowley14c8c072018-09-18 13:30:21 -07001522static int decrypt_master_key_aux(const char* passwd, unsigned char* salt,
1523 const unsigned char* encrypted_master_key, size_t keysize,
1524 unsigned char* decrypted_master_key, kdf_func kdf,
1525 void* kdf_params, unsigned char** intermediate_key,
1526 size_t* intermediate_key_size) {
1527 unsigned char ikey[INTERMEDIATE_BUF_SIZE] = {0};
1528 EVP_CIPHER_CTX d_ctx;
1529 int decrypted_len, final_len;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001530
Paul Crowley14c8c072018-09-18 13:30:21 -07001531 /* Turn the password into an intermediate key and IV that can decrypt the
1532 master key */
1533 if (kdf(passwd, salt, ikey, kdf_params)) {
1534 SLOGE("kdf failed");
1535 return -1;
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001536 }
Paul Lawrenced0c7b172014-08-08 14:28:10 -07001537
Paul Crowley14c8c072018-09-18 13:30:21 -07001538 /* Initialize the decryption engine */
1539 EVP_CIPHER_CTX_init(&d_ctx);
1540 if (!EVP_DecryptInit_ex(&d_ctx, EVP_aes_128_cbc(), NULL, ikey,
1541 ikey + INTERMEDIATE_KEY_LEN_BYTES)) {
1542 return -1;
1543 }
1544 EVP_CIPHER_CTX_set_padding(&d_ctx, 0); /* Turn off padding as our data is block aligned */
1545 /* Decrypt the master key */
1546 if (!EVP_DecryptUpdate(&d_ctx, decrypted_master_key, &decrypted_len, encrypted_master_key,
1547 keysize)) {
1548 return -1;
1549 }
1550 if (!EVP_DecryptFinal_ex(&d_ctx, decrypted_master_key + decrypted_len, &final_len)) {
1551 return -1;
1552 }
Thurston Hou Yeen Dang06dc3112016-07-18 14:16:37 -07001553
Paul Crowley14c8c072018-09-18 13:30:21 -07001554 if (decrypted_len + final_len != static_cast<int>(keysize)) {
1555 return -1;
1556 }
1557
1558 /* Copy intermediate key if needed by params */
1559 if (intermediate_key && intermediate_key_size) {
1560 *intermediate_key = (unsigned char*)malloc(INTERMEDIATE_KEY_LEN_BYTES);
1561 if (*intermediate_key) {
1562 memcpy(*intermediate_key, ikey, INTERMEDIATE_KEY_LEN_BYTES);
1563 *intermediate_key_size = INTERMEDIATE_KEY_LEN_BYTES;
1564 }
1565 }
1566
1567 EVP_CIPHER_CTX_cleanup(&d_ctx);
1568
1569 return 0;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001570}
1571
Paul Crowley14c8c072018-09-18 13:30:21 -07001572static void get_kdf_func(struct crypt_mnt_ftr* ftr, kdf_func* kdf, void** kdf_params) {
Paul Lawrencedb3730c2015-02-03 13:08:10 -08001573 if (ftr->kdf_type == KDF_SCRYPT_KEYMASTER) {
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07001574 *kdf = scrypt_keymaster;
1575 *kdf_params = ftr;
1576 } else if (ftr->kdf_type == KDF_SCRYPT) {
Kenny Rootc4c70f12013-06-14 12:11:38 -07001577 *kdf = scrypt;
1578 *kdf_params = ftr;
1579 } else {
1580 *kdf = pbkdf2;
1581 *kdf_params = NULL;
1582 }
1583}
1584
Paul Crowley14c8c072018-09-18 13:30:21 -07001585static int decrypt_master_key(const char* passwd, unsigned char* decrypted_master_key,
1586 struct crypt_mnt_ftr* crypt_ftr, unsigned char** intermediate_key,
1587 size_t* intermediate_key_size) {
Kenny Rootc4c70f12013-06-14 12:11:38 -07001588 kdf_func kdf;
Paul Crowley14c8c072018-09-18 13:30:21 -07001589 void* kdf_params;
Kenny Rootc4c70f12013-06-14 12:11:38 -07001590 int ret;
1591
1592 get_kdf_func(crypt_ftr, &kdf, &kdf_params);
Paul Crowley14c8c072018-09-18 13:30:21 -07001593 ret = decrypt_master_key_aux(passwd, crypt_ftr->salt, crypt_ftr->master_key, crypt_ftr->keysize,
1594 decrypted_master_key, kdf, kdf_params, intermediate_key,
1595 intermediate_key_size);
Kenny Rootc4c70f12013-06-14 12:11:38 -07001596 if (ret != 0) {
1597 SLOGW("failure decrypting master key");
Kenny Rootc4c70f12013-06-14 12:11:38 -07001598 }
1599
1600 return ret;
1601}
1602
Paul Crowley14c8c072018-09-18 13:30:21 -07001603static int create_encrypted_random_key(const char* passwd, unsigned char* master_key,
1604 unsigned char* salt, struct crypt_mnt_ftr* crypt_ftr) {
Greg Kaiser59ad0182018-02-16 13:01:36 -08001605 unsigned char key_buf[MAX_KEY_LEN];
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001606
Eric Biggers3a2f7db2019-01-16 13:05:34 -08001607 /* Get some random bits for a key and salt */
1608 if (android::vold::ReadRandomBytes(sizeof(key_buf), reinterpret_cast<char*>(key_buf)) != 0) {
1609 return -1;
1610 }
1611 if (android::vold::ReadRandomBytes(SALT_LEN, reinterpret_cast<char*>(salt)) != 0) {
1612 return -1;
1613 }
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001614
1615 /* Now encrypt it with the password */
AnilKumar Chimata98dc8352018-05-11 00:25:09 +05301616 return encrypt_master_key(passwd, salt, key_buf, master_key, crypt_ftr, true);
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001617}
1618
Paul Crowley14c8c072018-09-18 13:30:21 -07001619int wait_and_unmount(const char* mountpoint, bool kill) {
Greg Hackmann955653e2014-09-24 14:55:20 -07001620 int i, err, rc;
AnilKumar Chimata98dc8352018-05-11 00:25:09 +05301621#define WAIT_UNMOUNT_COUNT 200
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001622
1623 /* Now umount the tmpfs filesystem */
Paul Crowley14c8c072018-09-18 13:30:21 -07001624 for (i = 0; i < WAIT_UNMOUNT_COUNT; i++) {
Greg Hackmann6e8440f2014-10-02 17:18:20 -07001625 if (umount(mountpoint) == 0) {
1626 break;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001627 }
Greg Hackmann6e8440f2014-10-02 17:18:20 -07001628
1629 if (errno == EINVAL) {
1630 /* EINVAL is returned if the directory is not a mountpoint,
1631 * i.e. there is no filesystem mounted there. So just get out.
1632 */
1633 break;
1634 }
1635
1636 err = errno;
1637
AnilKumar Chimata98dc8352018-05-11 00:25:09 +05301638 /* If allowed, be increasingly aggressive before the last 2 seconds */
Greg Hackmann6e8440f2014-10-02 17:18:20 -07001639 if (kill) {
AnilKumar Chimata98dc8352018-05-11 00:25:09 +05301640 if (i == (WAIT_UNMOUNT_COUNT - 30)) {
Greg Hackmann6e8440f2014-10-02 17:18:20 -07001641 SLOGW("sending SIGHUP to processes with open files\n");
Jeff Sharkey3472e522017-10-06 18:02:53 -06001642 android::vold::KillProcessesWithOpenFiles(mountpoint, SIGTERM);
AnilKumar Chimata98dc8352018-05-11 00:25:09 +05301643 } else if (i == (WAIT_UNMOUNT_COUNT - 20)) {
Greg Hackmann6e8440f2014-10-02 17:18:20 -07001644 SLOGW("sending SIGKILL to processes with open files\n");
Jeff Sharkey3472e522017-10-06 18:02:53 -06001645 android::vold::KillProcessesWithOpenFiles(mountpoint, SIGKILL);
Greg Hackmann6e8440f2014-10-02 17:18:20 -07001646 }
1647 }
1648
AnilKumar Chimata98dc8352018-05-11 00:25:09 +05301649 usleep(100000);
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001650 }
1651
1652 if (i < WAIT_UNMOUNT_COUNT) {
Paul Crowley14c8c072018-09-18 13:30:21 -07001653 SLOGD("unmounting %s succeeded\n", mountpoint);
1654 rc = 0;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001655 } else {
Paul Crowley14c8c072018-09-18 13:30:21 -07001656 android::vold::KillProcessesWithOpenFiles(mountpoint, 0);
1657 SLOGE("unmounting %s failed: %s\n", mountpoint, strerror(err));
1658 rc = -1;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001659 }
1660
1661 return rc;
1662}
1663
Paul Crowley14c8c072018-09-18 13:30:21 -07001664static void prep_data_fs(void) {
Jeff Sharkey47695b22016-02-01 17:02:29 -07001665 // NOTE: post_fs_data results in init calling back around to vold, so all
1666 // callers to this method must be async
1667
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001668 /* Do the prep of the /data filesystem */
1669 property_set("vold.post_fs_data_done", "0");
1670 property_set("vold.decrypt", "trigger_post_fs_data");
Wei Wang42e38102017-06-07 10:46:12 -07001671 SLOGD("Just triggered post_fs_data");
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001672
Ken Sumrallc5872692013-05-14 15:26:31 -07001673 /* Wait a max of 50 seconds, hopefully it takes much less */
Paul Crowley14c8c072018-09-18 13:30:21 -07001674 while (!android::base::WaitForProperty("vold.post_fs_data_done", "1", std::chrono::seconds(15))) {
Wei Wang42e38102017-06-07 10:46:12 -07001675 /* We timed out to prep /data in time. Continue wait. */
1676 SLOGE("waited 15s for vold.post_fs_data_done, still waiting...");
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001677 }
Wei Wang42e38102017-06-07 10:46:12 -07001678 SLOGD("post_fs_data done");
Ken Sumrall8ddbe402011-01-17 15:26:29 -08001679}
1680
Paul Crowley14c8c072018-09-18 13:30:21 -07001681static void cryptfs_set_corrupt() {
Paul Lawrence74f29f12014-08-28 15:54:10 -07001682 // Mark the footer as bad
1683 struct crypt_mnt_ftr crypt_ftr;
1684 if (get_crypt_ftr_and_key(&crypt_ftr)) {
1685 SLOGE("Failed to get crypto footer - panic");
1686 return;
1687 }
1688
1689 crypt_ftr.flags |= CRYPT_DATA_CORRUPT;
1690 if (put_crypt_ftr_and_key(&crypt_ftr)) {
1691 SLOGE("Failed to set crypto footer - panic");
1692 return;
1693 }
1694}
1695
Paul Crowley14c8c072018-09-18 13:30:21 -07001696static void cryptfs_trigger_restart_min_framework() {
Paul Lawrence74f29f12014-08-28 15:54:10 -07001697 if (fs_mgr_do_tmpfs_mount(DATA_MNT_POINT)) {
Paul Crowley14c8c072018-09-18 13:30:21 -07001698 SLOGE("Failed to mount tmpfs on data - panic");
1699 return;
Paul Lawrence74f29f12014-08-28 15:54:10 -07001700 }
1701
1702 if (property_set("vold.decrypt", "trigger_post_fs_data")) {
1703 SLOGE("Failed to trigger post fs data - panic");
1704 return;
1705 }
1706
1707 if (property_set("vold.decrypt", "trigger_restart_min_framework")) {
1708 SLOGE("Failed to trigger restart min framework - panic");
1709 return;
1710 }
1711}
1712
Paul Lawrence8e3f4512014-09-08 10:11:17 -07001713/* returns < 0 on failure */
Paul Crowley14c8c072018-09-18 13:30:21 -07001714static int cryptfs_restart_internal(int restart_main) {
Yifan Hong804afe12019-02-07 12:56:47 -08001715 std::string crypto_blkdev;
AnilKumar Chimatad08106a2018-02-11 17:11:24 +05301716#ifdef CONFIG_HW_DISK_ENCRYPTION
Yifan Hong804afe12019-02-07 12:56:47 -08001717 std::string blkdev;
AnilKumar Chimatad08106a2018-02-11 17:11:24 +05301718#endif
Tim Murray8439dc92014-12-15 11:56:11 -08001719 int rc = -1;
Ken Sumrall0cc16632011-01-18 20:32:26 -08001720 static int restart_successful = 0;
1721
1722 /* Validate that it's OK to call this routine */
Paul Crowley14c8c072018-09-18 13:30:21 -07001723 if (!master_key_saved) {
Ken Sumrall0cc16632011-01-18 20:32:26 -08001724 SLOGE("Encrypted filesystem not validated, aborting");
1725 return -1;
1726 }
1727
1728 if (restart_successful) {
1729 SLOGE("System already restarted with encrypted disk, aborting");
1730 return -1;
1731 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001732
Paul Lawrencef4faa572014-01-29 13:31:03 -08001733 if (restart_main) {
1734 /* Here is where we shut down the framework. The init scripts
Martijn Coenenf629b002019-04-24 10:41:11 +02001735 * start all services in one of these classes: core, early_hal, hal,
1736 * main and late_start. To get to the minimal UI for PIN entry, we
1737 * need to start core, early_hal, hal and main. When we want to
1738 * shutdown the framework again, we need to stop most of the services in
1739 * these classes, but only those services that were started after
1740 * /data was mounted. This excludes critical services like vold and
1741 * ueventd, which need to keep running. We could possible stop
1742 * even fewer services, but because we want services to pick up APEX
1743 * libraries from the real /data, restarting is better, as it makes
1744 * these devices consistent with FBE devices and lets them use the
1745 * most recent code.
1746 *
1747 * Once these services have stopped, we should be able
Paul Lawrencef4faa572014-01-29 13:31:03 -08001748 * to umount the tmpfs /data, then mount the encrypted /data.
Martijn Coenenf629b002019-04-24 10:41:11 +02001749 * We then restart the class core, hal, main, and also the class
1750 * late_start.
1751 *
Paul Lawrencef4faa572014-01-29 13:31:03 -08001752 * At the moment, I've only put a few things in late_start that I know
1753 * are not needed to bring up the framework, and that also cause problems
1754 * with unmounting the tmpfs /data, but I hope to add add more services
1755 * to the late_start class as we optimize this to decrease the delay
1756 * till the user is asked for the password to the filesystem.
1757 */
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001758
Martijn Coenenf629b002019-04-24 10:41:11 +02001759 /* The init files are setup to stop the right set of services when
1760 * vold.decrypt is set to trigger_shutdown_framework.
Paul Lawrencef4faa572014-01-29 13:31:03 -08001761 */
Martijn Coenenf629b002019-04-24 10:41:11 +02001762 property_set("vold.decrypt", "trigger_shutdown_framework");
Paul Lawrencef4faa572014-01-29 13:31:03 -08001763 SLOGD("Just asked init to shut down class main\n");
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001764
Paul Lawrencef4faa572014-01-29 13:31:03 -08001765 /* Ugh, shutting down the framework is not synchronous, so until it
1766 * can be fixed, this horrible hack will wait a moment for it all to
1767 * shut down before proceeding. Without it, some devices cannot
1768 * restart the graphics services.
1769 */
1770 sleep(2);
1771 }
Ken Sumrall9dedfd42012-10-09 14:16:59 -07001772
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001773 /* Now that the framework is shutdown, we should be able to umount()
1774 * the tmpfs filesystem, and mount the real one.
1775 */
1776
AnilKumar Chimatad08106a2018-02-11 17:11:24 +05301777#if defined(CONFIG_HW_DISK_ENCRYPTION)
1778#if defined(CONFIG_HW_DISK_ENCRYPT_PERF)
1779 if (is_ice_enabled()) {
Yifan Hong804afe12019-02-07 12:56:47 -08001780 get_crypt_info(nullptr, &blkdev);
AnilKumar Chimatad08106a2018-02-11 17:11:24 +05301781 if (set_ice_param(START_ENCDEC)) {
1782 SLOGE("Failed to set ICE data");
1783 return -1;
1784 }
1785 }
1786#else
Yifan Hong804afe12019-02-07 12:56:47 -08001787 blkdev = android::base::GetProperty("ro.crypto.fs_crypto_blkdev", "");
1788 if (blkdev.empty()) {
AnilKumar Chimatad08106a2018-02-11 17:11:24 +05301789 SLOGE("fs_crypto_blkdev not set\n");
1790 return -1;
1791 }
1792 if (!(rc = wait_and_unmount(DATA_MNT_POINT, true))) {
1793#endif
1794#else
Yifan Hong804afe12019-02-07 12:56:47 -08001795 crypto_blkdev = android::base::GetProperty("ro.crypto.fs_crypto_blkdev", "");
1796 if (crypto_blkdev.empty()) {
Ken Sumrall6864b7e2011-01-14 15:20:02 -08001797 SLOGE("fs_crypto_blkdev not set\n");
1798 return -1;
1799 }
1800
Paul Crowley14c8c072018-09-18 13:30:21 -07001801 if (!(rc = wait_and_unmount(DATA_MNT_POINT, true))) {
AnilKumar Chimatad08106a2018-02-11 17:11:24 +05301802#endif
Doug Zongker6fd57712013-12-17 09:43:23 -08001803 /* If ro.crypto.readonly is set to 1, mount the decrypted
1804 * filesystem readonly. This is used when /data is mounted by
1805 * recovery mode.
1806 */
1807 char ro_prop[PROPERTY_VALUE_MAX];
1808 property_get("ro.crypto.readonly", ro_prop, "");
Jeff Sharkey95440eb2017-09-18 18:19:28 -06001809 if (strlen(ro_prop) > 0 && std::stoi(ro_prop)) {
Tom Cherry4c5bde22019-01-29 14:34:01 -08001810 auto entry = GetEntryForMountPoint(&fstab_default, DATA_MNT_POINT);
1811 if (entry != nullptr) {
1812 entry->flags |= MS_RDONLY;
Luis Hector Chavezf86566f2018-05-30 15:47:50 -07001813 }
Doug Zongker6fd57712013-12-17 09:43:23 -08001814 }
JP Abgrall62c7af32014-06-16 13:01:23 -07001815
Ken Sumralle5032c42012-04-01 23:58:44 -07001816 /* If that succeeded, then mount the decrypted filesystem */
Paul Lawrence8e3f4512014-09-08 10:11:17 -07001817 int retries = RETRY_MOUNT_ATTEMPTS;
1818 int mount_rc;
Jeff Vander Stoepdf725752016-01-29 15:34:43 -08001819
1820 /*
1821 * fs_mgr_do_mount runs fsck. Use setexeccon to run trusted
1822 * partitions in the fsck domain.
1823 */
LongPing Wei7f3ab952019-01-30 16:03:14 +08001824 if (setexeccon(android::vold::sFsckContext)) {
Jeff Vander Stoepdf725752016-01-29 15:34:43 -08001825 SLOGE("Failed to setexeccon");
1826 return -1;
1827 }
Daniel Rosenberg4f684712018-08-28 01:58:49 -07001828 bool needs_cp = android::vold::cp_needsCheckpoint();
AnilKumar Chimatad08106a2018-02-11 17:11:24 +05301829#ifdef CONFIG_HW_DISK_ENCRYPTION
Yifan Hong804afe12019-02-07 12:56:47 -08001830 while ((mount_rc = fs_mgr_do_mount(&fstab_default, DATA_MNT_POINT, blkdev.data(), 0,
Bill Peckham0db11972018-10-10 10:25:42 -07001831 needs_cp)) != 0) {
AnilKumar Chimatad08106a2018-02-11 17:11:24 +05301832#else
Yifan Hong804afe12019-02-07 12:56:47 -08001833 while ((mount_rc = fs_mgr_do_mount(&fstab_default, DATA_MNT_POINT, crypto_blkdev.data(), 0,
Daniel Rosenberg4f684712018-08-28 01:58:49 -07001834 needs_cp)) != 0) {
AnilKumar Chimatad08106a2018-02-11 17:11:24 +05301835#endif
Paul Lawrence8e3f4512014-09-08 10:11:17 -07001836 if (mount_rc == FS_MGR_DOMNT_BUSY) {
1837 /* TODO: invoke something similar to
1838 Process::killProcessWithOpenFiles(DATA_MNT_POINT,
1839 retries > RETRY_MOUNT_ATTEMPT/2 ? 1 : 2 ) */
AnilKumar Chimatad08106a2018-02-11 17:11:24 +05301840#ifdef CONFIG_HW_DISK_ENCRYPTION
Yifan Hong804afe12019-02-07 12:56:47 -08001841 SLOGI("Failed to mount %s because it is busy - waiting", blkdev.c_str());
AnilKumar Chimatad08106a2018-02-11 17:11:24 +05301842#else
Yifan Hong804afe12019-02-07 12:56:47 -08001843 SLOGI("Failed to mount %s because it is busy - waiting", crypto_blkdev.c_str());
AnilKumar Chimatad08106a2018-02-11 17:11:24 +05301844#endif
Paul Lawrence8e3f4512014-09-08 10:11:17 -07001845 if (--retries) {
1846 sleep(RETRY_MOUNT_DELAY_SECONDS);
1847 } else {
1848 /* Let's hope that a reboot clears away whatever is keeping
1849 the mount busy */
Josh Gaofec44372017-08-28 13:22:55 -07001850 cryptfs_reboot(RebootType::reboot);
Paul Lawrence8e3f4512014-09-08 10:11:17 -07001851 }
1852 } else {
AnilKumar Chimata98dc8352018-05-11 00:25:09 +05301853#ifdef CONFIG_HW_DISK_ENCRYPTION
1854 if (--retries) {
1855 sleep(RETRY_MOUNT_DELAY_SECONDS);
1856 } else {
1857 SLOGE("Failed to mount decrypted data");
1858 cryptfs_set_corrupt();
1859 cryptfs_trigger_restart_min_framework();
1860 SLOGI("Started framework to offer wipe");
1861 return -1;
1862 }
1863#else
Paul Lawrence8e3f4512014-09-08 10:11:17 -07001864 SLOGE("Failed to mount decrypted data");
1865 cryptfs_set_corrupt();
1866 cryptfs_trigger_restart_min_framework();
1867 SLOGI("Started framework to offer wipe");
Jeff Vander Stoepdf725752016-01-29 15:34:43 -08001868 if (setexeccon(NULL)) {
1869 SLOGE("Failed to setexeccon");
1870 }
Paul Lawrence8e3f4512014-09-08 10:11:17 -07001871 return -1;
AnilKumar Chimata98dc8352018-05-11 00:25:09 +05301872#endif
Paul Lawrence8e3f4512014-09-08 10:11:17 -07001873 }
Paul Lawrence74f29f12014-08-28 15:54:10 -07001874 }
Jeff Vander Stoepdf725752016-01-29 15:34:43 -08001875 if (setexeccon(NULL)) {
1876 SLOGE("Failed to setexeccon");
1877 return -1;
1878 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001879
Ken Sumralle5032c42012-04-01 23:58:44 -07001880 /* Create necessary paths on /data */
Wei Wang42e38102017-06-07 10:46:12 -07001881 prep_data_fs();
Seigo Nonakae2ef0c02016-06-20 17:05:40 +09001882 property_set("vold.decrypt", "trigger_load_persist_props");
Ken Sumralle5032c42012-04-01 23:58:44 -07001883
1884 /* startup service classes main and late_start */
1885 property_set("vold.decrypt", "trigger_restart_framework");
1886 SLOGD("Just triggered restart_framework\n");
1887
1888 /* Give it a few moments to get started */
1889 sleep(1);
AnilKumar Chimatad08106a2018-02-11 17:11:24 +05301890#ifndef CONFIG_HW_DISK_ENCRYPT_PERF
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001891 }
AnilKumar Chimatad08106a2018-02-11 17:11:24 +05301892#endif
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001893
Ken Sumrall0cc16632011-01-18 20:32:26 -08001894 if (rc == 0) {
1895 restart_successful = 1;
1896 }
1897
Ken Sumrall8f869aa2010-12-03 03:47:09 -08001898 return rc;
1899}
1900
Paul Crowley14c8c072018-09-18 13:30:21 -07001901int cryptfs_restart(void) {
Paul Lawrence05335c32015-03-05 09:46:23 -08001902 SLOGI("cryptfs_restart");
Eric Biggersa701c452018-10-23 13:06:55 -07001903 if (fscrypt_is_native()) {
Paul Lawrence7b6b5652016-02-02 11:14:59 -08001904 SLOGE("cryptfs_restart not valid for file encryption:");
1905 return -1;
Paul Lawrence05335c32015-03-05 09:46:23 -08001906 }
1907
Paul Lawrencef4faa572014-01-29 13:31:03 -08001908 /* Call internal implementation forcing a restart of main service group */
1909 return cryptfs_restart_internal(1);
1910}
1911
Paul Crowley14c8c072018-09-18 13:30:21 -07001912static int do_crypto_complete(const char* mount_point) {
1913 struct crypt_mnt_ftr crypt_ftr;
1914 char encrypted_state[PROPERTY_VALUE_MAX];
Ken Sumrall7f7dbaa2011-02-01 15:46:41 -08001915
Paul Crowley14c8c072018-09-18 13:30:21 -07001916 property_get("ro.crypto.state", encrypted_state, "");
1917 if (strcmp(encrypted_state, "encrypted")) {
1918 SLOGE("not running with encryption, aborting");
1919 return CRYPTO_COMPLETE_NOT_ENCRYPTED;
Ken Sumralle1a45852011-12-14 21:24:27 -08001920 }
Ken Sumrall7f7dbaa2011-02-01 15:46:41 -08001921
Paul Crowley14c8c072018-09-18 13:30:21 -07001922 // crypto_complete is full disk encrypted status
Eric Biggersa701c452018-10-23 13:06:55 -07001923 if (fscrypt_is_native()) {
Paul Crowley14c8c072018-09-18 13:30:21 -07001924 return CRYPTO_COMPLETE_NOT_ENCRYPTED;
1925 }
Paul Lawrence74f29f12014-08-28 15:54:10 -07001926
Paul Crowley14c8c072018-09-18 13:30:21 -07001927 if (get_crypt_ftr_and_key(&crypt_ftr)) {
Tom Cherry4c5bde22019-01-29 14:34:01 -08001928 std::string key_loc;
1929 get_crypt_info(&key_loc, nullptr);
Paul Lawrence74f29f12014-08-28 15:54:10 -07001930
Paul Crowley14c8c072018-09-18 13:30:21 -07001931 /*
1932 * Only report this error if key_loc is a file and it exists.
1933 * If the device was never encrypted, and /data is not mountable for
1934 * some reason, returning 1 should prevent the UI from presenting the
1935 * a "enter password" screen, or worse, a "press button to wipe the
1936 * device" screen.
1937 */
Tom Cherry4c5bde22019-01-29 14:34:01 -08001938 if (!key_loc.empty() && key_loc[0] == '/' && (access("key_loc", F_OK) == -1)) {
Paul Crowley14c8c072018-09-18 13:30:21 -07001939 SLOGE("master key file does not exist, aborting");
1940 return CRYPTO_COMPLETE_NOT_ENCRYPTED;
1941 } else {
1942 SLOGE("Error getting crypt footer and key\n");
1943 return CRYPTO_COMPLETE_BAD_METADATA;
1944 }
1945 }
Ken Sumrall7f7dbaa2011-02-01 15:46:41 -08001946
Paul Crowley14c8c072018-09-18 13:30:21 -07001947 // Test for possible error flags
1948 if (crypt_ftr.flags & CRYPT_ENCRYPTION_IN_PROGRESS) {
1949 SLOGE("Encryption process is partway completed\n");
1950 return CRYPTO_COMPLETE_PARTIAL;
1951 }
1952
1953 if (crypt_ftr.flags & CRYPT_INCONSISTENT_STATE) {
1954 SLOGE("Encryption process was interrupted but cannot continue\n");
1955 return CRYPTO_COMPLETE_INCONSISTENT;
1956 }
1957
1958 if (crypt_ftr.flags & CRYPT_DATA_CORRUPT) {
1959 SLOGE("Encryption is successful but data is corrupt\n");
1960 return CRYPTO_COMPLETE_CORRUPT;
1961 }
1962
1963 /* We passed the test! We shall diminish, and return to the west */
1964 return CRYPTO_COMPLETE_ENCRYPTED;
Ken Sumrall7f7dbaa2011-02-01 15:46:41 -08001965}
1966
AnilKumar Chimata98dc8352018-05-11 00:25:09 +05301967#ifdef CONFIG_HW_DISK_ENCRYPTION
1968static int test_mount_hw_encrypted_fs(struct crypt_mnt_ftr* crypt_ftr,
1969 const char *passwd, const char *mount_point, const char *label)
1970{
Bill Peckham0db11972018-10-10 10:25:42 -07001971 /* Allocate enough space for a 256 bit key, but we may use less */
1972 unsigned char decrypted_master_key[32];
1973 char crypto_blkdev[MAXPATHLEN];
Yifan Hong804afe12019-02-07 12:56:47 -08001974 std::string real_blkdev;
Bill Peckham0db11972018-10-10 10:25:42 -07001975 unsigned int orig_failed_decrypt_count;
1976 int rc = 0;
AnilKumar Chimata98dc8352018-05-11 00:25:09 +05301977
Bill Peckham0db11972018-10-10 10:25:42 -07001978 SLOGD("crypt_ftr->fs_size = %lld\n", crypt_ftr->fs_size);
1979 orig_failed_decrypt_count = crypt_ftr->failed_decrypt_count;
AnilKumar Chimata98dc8352018-05-11 00:25:09 +05301980
Yifan Hong804afe12019-02-07 12:56:47 -08001981 get_crypt_info(nullptr, &real_blkdev);
AnilKumar Chimata98dc8352018-05-11 00:25:09 +05301982
Bill Peckham0db11972018-10-10 10:25:42 -07001983 int key_index = 0;
1984 if(is_hw_disk_encryption((char*)crypt_ftr->crypto_type_name)) {
1985 key_index = verify_and_update_hw_fde_passwd(passwd, crypt_ftr);
1986 if (key_index < 0) {
1987 rc = crypt_ftr->failed_decrypt_count;
1988 goto errout;
1989 }
1990 else {
1991 if (is_ice_enabled()) {
AnilKumar Chimatad08106a2018-02-11 17:11:24 +05301992#ifndef CONFIG_HW_DISK_ENCRYPT_PERF
Neeraj Soni73b46952019-09-12 16:47:27 +05301993 if (create_crypto_blk_dev_hw(crypt_ftr, (unsigned char*)&key_index,
Yifan Hong804afe12019-02-07 12:56:47 -08001994 real_blkdev.c_str(), crypto_blkdev, label, 0)) {
Bill Peckham0db11972018-10-10 10:25:42 -07001995 SLOGE("Error creating decrypted block device");
1996 rc = -1;
1997 goto errout;
1998 }
AnilKumar Chimatad08106a2018-02-11 17:11:24 +05301999#endif
Bill Peckham0db11972018-10-10 10:25:42 -07002000 } else {
2001 if (create_crypto_blk_dev(crypt_ftr, decrypted_master_key,
Yifan Hong804afe12019-02-07 12:56:47 -08002002 real_blkdev.c_str(), crypto_blkdev, label, 0)) {
Bill Peckham0db11972018-10-10 10:25:42 -07002003 SLOGE("Error creating decrypted block device");
2004 rc = -1;
2005 goto errout;
2006 }
2007 }
AnilKumar Chimata98dc8352018-05-11 00:25:09 +05302008 }
AnilKumar Chimata98dc8352018-05-11 00:25:09 +05302009 }
2010
Bill Peckham0db11972018-10-10 10:25:42 -07002011 if (rc == 0) {
2012 crypt_ftr->failed_decrypt_count = 0;
2013 if (orig_failed_decrypt_count != 0) {
2014 put_crypt_ftr_and_key(crypt_ftr);
2015 }
2016
2017 /* Save the name of the crypto block device
2018 * so we can mount it when restarting the framework. */
AnilKumar Chimatad08106a2018-02-11 17:11:24 +05302019#ifdef CONFIG_HW_DISK_ENCRYPT_PERF
Bill Peckham0db11972018-10-10 10:25:42 -07002020 if (!is_ice_enabled())
AnilKumar Chimatad08106a2018-02-11 17:11:24 +05302021#endif
Bill Peckham0db11972018-10-10 10:25:42 -07002022 property_set("ro.crypto.fs_crypto_blkdev", crypto_blkdev);
2023 master_key_saved = 1;
2024 }
AnilKumar Chimata98dc8352018-05-11 00:25:09 +05302025
Bill Peckham0db11972018-10-10 10:25:42 -07002026 errout:
2027 return rc;
AnilKumar Chimata98dc8352018-05-11 00:25:09 +05302028}
2029#endif
2030
Paul Crowley14c8c072018-09-18 13:30:21 -07002031static int test_mount_encrypted_fs(struct crypt_mnt_ftr* crypt_ftr, const char* passwd,
2032 const char* mount_point, const char* label) {
2033 unsigned char decrypted_master_key[MAX_KEY_LEN];
2034 char crypto_blkdev[MAXPATHLEN];
Tom Cherry4c5bde22019-01-29 14:34:01 -08002035 std::string real_blkdev;
Paul Crowley14c8c072018-09-18 13:30:21 -07002036 char tmp_mount_point[64];
2037 unsigned int orig_failed_decrypt_count;
2038 int rc;
2039 int use_keymaster = 0;
2040 int upgrade = 0;
2041 unsigned char* intermediate_key = 0;
2042 size_t intermediate_key_size = 0;
2043 int N = 1 << crypt_ftr->N_factor;
2044 int r = 1 << crypt_ftr->r_factor;
2045 int p = 1 << crypt_ftr->p_factor;
AnilKumar Chimata98dc8352018-05-11 00:25:09 +05302046
Paul Crowley14c8c072018-09-18 13:30:21 -07002047 SLOGD("crypt_ftr->fs_size = %lld\n", crypt_ftr->fs_size);
2048 orig_failed_decrypt_count = crypt_ftr->failed_decrypt_count;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002049
Paul Crowley14c8c072018-09-18 13:30:21 -07002050 if (!(crypt_ftr->flags & CRYPT_MNT_KEY_UNENCRYPTED)) {
2051 if (decrypt_master_key(passwd, decrypted_master_key, crypt_ftr, &intermediate_key,
2052 &intermediate_key_size)) {
2053 SLOGE("Failed to decrypt master key\n");
2054 rc = -1;
2055 goto errout;
2056 }
JP Abgrall7bdfa522013-11-15 13:42:56 -08002057 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002058
Tom Cherry4c5bde22019-01-29 14:34:01 -08002059 get_crypt_info(nullptr, &real_blkdev);
Paul Lawrencef4faa572014-01-29 13:31:03 -08002060
Paul Crowley14c8c072018-09-18 13:30:21 -07002061 // Create crypto block device - all (non fatal) code paths
2062 // need it
Tom Cherry4c5bde22019-01-29 14:34:01 -08002063 if (create_crypto_blk_dev(crypt_ftr, decrypted_master_key, real_blkdev.c_str(), crypto_blkdev,
2064 label, 0)) {
Paul Crowley14c8c072018-09-18 13:30:21 -07002065 SLOGE("Error creating decrypted block device\n");
2066 rc = -1;
2067 goto errout;
2068 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002069
Paul Crowley14c8c072018-09-18 13:30:21 -07002070 /* Work out if the problem is the password or the data */
2071 unsigned char scrypted_intermediate_key[sizeof(crypt_ftr->scrypted_intermediate_key)];
Paul Lawrenced0c7b172014-08-08 14:28:10 -07002072
Paul Crowley14c8c072018-09-18 13:30:21 -07002073 rc = crypto_scrypt(intermediate_key, intermediate_key_size, crypt_ftr->salt,
2074 sizeof(crypt_ftr->salt), N, r, p, scrypted_intermediate_key,
2075 sizeof(scrypted_intermediate_key));
Paul Lawrenced0c7b172014-08-08 14:28:10 -07002076
Paul Crowley14c8c072018-09-18 13:30:21 -07002077 // Does the key match the crypto footer?
2078 if (rc == 0 && memcmp(scrypted_intermediate_key, crypt_ftr->scrypted_intermediate_key,
2079 sizeof(scrypted_intermediate_key)) == 0) {
2080 SLOGI("Password matches");
2081 rc = 0;
Paul Lawrence74f29f12014-08-28 15:54:10 -07002082 } else {
Paul Crowley14c8c072018-09-18 13:30:21 -07002083 /* Try mounting the file system anyway, just in case the problem's with
2084 * the footer, not the key. */
2085 snprintf(tmp_mount_point, sizeof(tmp_mount_point), "%s/tmp_mnt", mount_point);
2086 mkdir(tmp_mount_point, 0755);
Tom Cherry4c5bde22019-01-29 14:34:01 -08002087 if (fs_mgr_do_mount(&fstab_default, DATA_MNT_POINT, crypto_blkdev, tmp_mount_point)) {
Paul Crowley14c8c072018-09-18 13:30:21 -07002088 SLOGE("Error temp mounting decrypted block device\n");
2089 delete_crypto_blk_dev(label);
Paul Lawrence74f29f12014-08-28 15:54:10 -07002090
Paul Crowley14c8c072018-09-18 13:30:21 -07002091 rc = ++crypt_ftr->failed_decrypt_count;
2092 put_crypt_ftr_and_key(crypt_ftr);
2093 } else {
2094 /* Success! */
2095 SLOGI("Password did not match but decrypted drive mounted - continue");
2096 umount(tmp_mount_point);
2097 rc = 0;
Paul Lawrenceb2f682b2014-09-08 11:28:19 -07002098 }
JP Abgrall7bdfa522013-11-15 13:42:56 -08002099 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002100
Paul Crowley14c8c072018-09-18 13:30:21 -07002101 if (rc == 0) {
2102 crypt_ftr->failed_decrypt_count = 0;
2103 if (orig_failed_decrypt_count != 0) {
2104 put_crypt_ftr_and_key(crypt_ftr);
2105 }
2106
2107 /* Save the name of the crypto block device
2108 * so we can mount it when restarting the framework. */
2109 property_set("ro.crypto.fs_crypto_blkdev", crypto_blkdev);
2110
2111 /* Also save a the master key so we can reencrypted the key
2112 * the key when we want to change the password on it. */
2113 memcpy(saved_master_key, decrypted_master_key, crypt_ftr->keysize);
2114 saved_mount_point = strdup(mount_point);
2115 master_key_saved = 1;
2116 SLOGD("%s(): Master key saved\n", __FUNCTION__);
2117 rc = 0;
2118
2119 // Upgrade if we're not using the latest KDF.
2120 use_keymaster = keymaster_check_compatibility();
2121 if (crypt_ftr->kdf_type == KDF_SCRYPT_KEYMASTER) {
2122 // Don't allow downgrade
2123 } else if (use_keymaster == 1 && crypt_ftr->kdf_type != KDF_SCRYPT_KEYMASTER) {
2124 crypt_ftr->kdf_type = KDF_SCRYPT_KEYMASTER;
2125 upgrade = 1;
2126 } else if (use_keymaster == 0 && crypt_ftr->kdf_type != KDF_SCRYPT) {
2127 crypt_ftr->kdf_type = KDF_SCRYPT;
2128 upgrade = 1;
2129 }
2130
2131 if (upgrade) {
2132 rc = encrypt_master_key(passwd, crypt_ftr->salt, saved_master_key,
Bill Peckham0db11972018-10-10 10:25:42 -07002133 crypt_ftr->master_key, crypt_ftr, true);
Paul Crowley14c8c072018-09-18 13:30:21 -07002134 if (!rc) {
2135 rc = put_crypt_ftr_and_key(crypt_ftr);
2136 }
2137 SLOGD("Key Derivation Function upgrade: rc=%d\n", rc);
2138
2139 // Do not fail even if upgrade failed - machine is bootable
2140 // Note that if this code is ever hit, there is a *serious* problem
2141 // since KDFs should never fail. You *must* fix the kdf before
2142 // proceeding!
2143 if (rc) {
2144 SLOGW(
2145 "Upgrade failed with error %d,"
2146 " but continuing with previous state",
2147 rc);
2148 rc = 0;
2149 }
2150 }
2151 }
2152
2153errout:
2154 if (intermediate_key) {
2155 memset(intermediate_key, 0, intermediate_key_size);
2156 free(intermediate_key);
2157 }
2158 return rc;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002159}
2160
Ken Sumrall29d8da82011-05-18 17:20:07 -07002161/*
Jeff Sharkey9c484982015-03-31 10:35:33 -07002162 * Called by vold when it's asked to mount an encrypted external
2163 * storage volume. The incoming partition has no crypto header/footer,
Greg Kaiser57f9af62018-02-16 13:13:58 -08002164 * as any metadata is been stored in a separate, small partition. We
2165 * assume it must be using our same crypt type and keysize.
Jeff Sharkey9c484982015-03-31 10:35:33 -07002166 *
2167 * out_crypto_blkdev must be MAXPATHLEN.
Ken Sumrall29d8da82011-05-18 17:20:07 -07002168 */
Paul Crowley14c8c072018-09-18 13:30:21 -07002169int cryptfs_setup_ext_volume(const char* label, const char* real_blkdev, const unsigned char* key,
2170 char* out_crypto_blkdev) {
Oleksiy Avramchenko625dc782018-05-23 10:50:46 +02002171 uint64_t nr_sec = 0;
2172 if (android::vold::GetBlockDev512Sectors(real_blkdev, &nr_sec) != android::OK) {
Jeff Sharkey9c484982015-03-31 10:35:33 -07002173 SLOGE("Failed to get size of %s: %s", real_blkdev, strerror(errno));
Ken Sumrall29d8da82011-05-18 17:20:07 -07002174 return -1;
2175 }
2176
Jeff Sharkey9c484982015-03-31 10:35:33 -07002177 struct crypt_mnt_ftr ext_crypt_ftr;
2178 memset(&ext_crypt_ftr, 0, sizeof(ext_crypt_ftr));
2179 ext_crypt_ftr.fs_size = nr_sec;
Greg Kaiser57f9af62018-02-16 13:13:58 -08002180 ext_crypt_ftr.keysize = cryptfs_get_keysize();
Paul Crowley14c8c072018-09-18 13:30:21 -07002181 strlcpy((char*)ext_crypt_ftr.crypto_type_name, cryptfs_get_crypto_name(),
Jeff Sharkey32ebb732017-03-27 16:18:50 -06002182 MAX_CRYPTO_TYPE_NAME_LEN);
Paul Crowley385cb8c2018-03-29 13:27:23 -07002183 uint32_t flags = 0;
Eric Biggersa701c452018-10-23 13:06:55 -07002184 if (fscrypt_is_native() &&
Paul Crowley385cb8c2018-03-29 13:27:23 -07002185 android::base::GetBoolProperty("ro.crypto.allow_encrypt_override", false))
2186 flags |= CREATE_CRYPTO_BLK_DEV_FLAGS_ALLOW_ENCRYPT_OVERRIDE;
Ken Sumrall29d8da82011-05-18 17:20:07 -07002187
Paul Crowley385cb8c2018-03-29 13:27:23 -07002188 return create_crypto_blk_dev(&ext_crypt_ftr, key, real_blkdev, out_crypto_blkdev, label, flags);
Jeff Sharkey9c484982015-03-31 10:35:33 -07002189}
Ken Sumrall29d8da82011-05-18 17:20:07 -07002190
Jeff Sharkey9c484982015-03-31 10:35:33 -07002191/*
2192 * Called by vold when it's asked to unmount an encrypted external
2193 * storage volume.
2194 */
2195int cryptfs_revert_ext_volume(const char* label) {
David Andersonb9224732019-05-13 13:02:54 -07002196 return delete_crypto_blk_dev(label);
Ken Sumrall29d8da82011-05-18 17:20:07 -07002197}
2198
Paul Crowley14c8c072018-09-18 13:30:21 -07002199int cryptfs_crypto_complete(void) {
2200 return do_crypto_complete("/data");
Ken Sumrall7f7dbaa2011-02-01 15:46:41 -08002201}
2202
Paul Crowley14c8c072018-09-18 13:30:21 -07002203int check_unmounted_and_get_ftr(struct crypt_mnt_ftr* crypt_ftr) {
Paul Lawrencef4faa572014-01-29 13:31:03 -08002204 char encrypted_state[PROPERTY_VALUE_MAX];
2205 property_get("ro.crypto.state", encrypted_state, "");
Paul Crowley14c8c072018-09-18 13:30:21 -07002206 if (master_key_saved || strcmp(encrypted_state, "encrypted")) {
2207 SLOGE(
2208 "encrypted fs already validated or not running with encryption,"
2209 " aborting");
Paul Lawrencef4faa572014-01-29 13:31:03 -08002210 return -1;
2211 }
2212
2213 if (get_crypt_ftr_and_key(crypt_ftr)) {
2214 SLOGE("Error getting crypt footer and key");
2215 return -1;
2216 }
2217
2218 return 0;
2219}
2220
AnilKumar Chimata98dc8352018-05-11 00:25:09 +05302221#ifdef CONFIG_HW_DISK_ENCRYPTION
2222int cryptfs_check_passwd_hw(const char* passwd)
2223{
2224 struct crypt_mnt_ftr crypt_ftr;
2225 int rc;
2226 unsigned char master_key[KEY_LEN_BYTES];
2227
2228 /* get key */
2229 if (get_crypt_ftr_and_key(&crypt_ftr)) {
2230 SLOGE("Error getting crypt footer and key");
2231 return -1;
2232 }
2233
2234 /*
2235 * in case of manual encryption (from GUI), the encryption is done with
2236 * default password
2237 */
2238 if (crypt_ftr.flags & CRYPT_FORCE_COMPLETE) {
2239 /* compare scrypted_intermediate_key with stored scrypted_intermediate_key
2240 * which was created with actual password before reboot.
2241 */
2242 rc = cryptfs_get_master_key(&crypt_ftr, passwd, master_key);
2243 if (rc) {
2244 SLOGE("password doesn't match");
2245 rc = ++crypt_ftr.failed_decrypt_count;
2246 put_crypt_ftr_and_key(&crypt_ftr);
2247 return rc;
2248 }
2249
2250 rc = test_mount_hw_encrypted_fs(&crypt_ftr, DEFAULT_PASSWORD,
2251 DATA_MNT_POINT, CRYPTO_BLOCK_DEVICE);
2252
2253 if (rc) {
2254 SLOGE("Default password did not match on reboot encryption");
2255 return rc;
2256 }
2257
2258 crypt_ftr.flags &= ~CRYPT_FORCE_COMPLETE;
2259 put_crypt_ftr_and_key(&crypt_ftr);
2260 rc = cryptfs_changepw(crypt_ftr.crypt_type, DEFAULT_PASSWORD, passwd);
2261 if (rc) {
2262 SLOGE("Could not change password on reboot encryption");
2263 return rc;
2264 }
2265 } else
2266 rc = test_mount_hw_encrypted_fs(&crypt_ftr, passwd,
2267 DATA_MNT_POINT, CRYPTO_BLOCK_DEVICE);
2268
2269 if (crypt_ftr.crypt_type != CRYPT_TYPE_DEFAULT) {
2270 cryptfs_clear_password();
2271 password = strdup(passwd);
2272 struct timespec now;
2273 clock_gettime(CLOCK_BOOTTIME, &now);
2274 password_expiry_time = now.tv_sec + password_max_age_seconds;
2275 }
2276
2277 return rc;
2278}
2279#endif
2280
Paul Crowley14c8c072018-09-18 13:30:21 -07002281int cryptfs_check_passwd(const char* passwd) {
Paul Lawrence05335c32015-03-05 09:46:23 -08002282 SLOGI("cryptfs_check_passwd");
Eric Biggersa701c452018-10-23 13:06:55 -07002283 if (fscrypt_is_native()) {
Paul Lawrence7b6b5652016-02-02 11:14:59 -08002284 SLOGE("cryptfs_check_passwd not valid for file encryption");
2285 return -1;
Paul Lawrence05335c32015-03-05 09:46:23 -08002286 }
2287
Paul Lawrencef4faa572014-01-29 13:31:03 -08002288 struct crypt_mnt_ftr crypt_ftr;
2289 int rc;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002290
Paul Lawrencef4faa572014-01-29 13:31:03 -08002291 rc = check_unmounted_and_get_ftr(&crypt_ftr);
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002292 if (rc) {
2293 SLOGE("Could not get footer");
Paul Lawrencef4faa572014-01-29 13:31:03 -08002294 return rc;
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002295 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002296
AnilKumar Chimata98dc8352018-05-11 00:25:09 +05302297#ifdef CONFIG_HW_DISK_ENCRYPTION
2298 if (is_hw_disk_encryption((char*)crypt_ftr.crypto_type_name))
2299 return cryptfs_check_passwd_hw(passwd);
2300#endif
2301
Paul Crowley14c8c072018-09-18 13:30:21 -07002302 rc = test_mount_encrypted_fs(&crypt_ftr, passwd, DATA_MNT_POINT, CRYPTO_BLOCK_DEVICE);
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002303 if (rc) {
2304 SLOGE("Password did not match");
2305 return rc;
2306 }
Paul Lawrence684dbdf2014-02-07 12:07:22 -08002307
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002308 if (crypt_ftr.flags & CRYPT_FORCE_COMPLETE) {
2309 // Here we have a default actual password but a real password
2310 // we must test against the scrypted value
2311 // First, we must delete the crypto block device that
2312 // test_mount_encrypted_fs leaves behind as a side effect
2313 delete_crypto_blk_dev(CRYPTO_BLOCK_DEVICE);
Paul Crowley14c8c072018-09-18 13:30:21 -07002314 rc = test_mount_encrypted_fs(&crypt_ftr, DEFAULT_PASSWORD, DATA_MNT_POINT,
2315 CRYPTO_BLOCK_DEVICE);
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002316 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);
AnilKumar Chimata98dc8352018-05-11 00:25:09 +05302323 rc = cryptfs_changepw(crypt_ftr.crypt_type, DEFAULT_PASSWORD, passwd);
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002324 if (rc) {
2325 SLOGE("Could not change password on reboot encryption");
2326 return rc;
2327 }
2328 }
2329
2330 if (crypt_ftr.crypt_type != CRYPT_TYPE_DEFAULT) {
Paul Lawrence399317e2014-03-10 13:20:50 -07002331 cryptfs_clear_password();
2332 password = strdup(passwd);
2333 struct timespec now;
2334 clock_gettime(CLOCK_BOOTTIME, &now);
2335 password_expiry_time = now.tv_sec + password_max_age_seconds;
Paul Lawrence684dbdf2014-02-07 12:07:22 -08002336 }
2337
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002338 return rc;
2339}
2340
Paul Crowley14c8c072018-09-18 13:30:21 -07002341int cryptfs_verify_passwd(const char* passwd) {
Ken Sumrall3ad90722011-10-04 20:38:29 -07002342 struct crypt_mnt_ftr crypt_ftr;
Greg Kaiser59ad0182018-02-16 13:01:36 -08002343 unsigned char decrypted_master_key[MAX_KEY_LEN];
Ken Sumrall3ad90722011-10-04 20:38:29 -07002344 char encrypted_state[PROPERTY_VALUE_MAX];
2345 int rc;
2346
2347 property_get("ro.crypto.state", encrypted_state, "");
Paul Crowley14c8c072018-09-18 13:30:21 -07002348 if (strcmp(encrypted_state, "encrypted")) {
Ken Sumrall3ad90722011-10-04 20:38:29 -07002349 SLOGE("device not encrypted, aborting");
2350 return -2;
2351 }
2352
2353 if (!master_key_saved) {
2354 SLOGE("encrypted fs not yet mounted, aborting");
2355 return -1;
2356 }
2357
2358 if (!saved_mount_point) {
2359 SLOGE("encrypted fs failed to save mount point, aborting");
2360 return -1;
2361 }
2362
Ken Sumrall160b4d62013-04-22 12:15:39 -07002363 if (get_crypt_ftr_and_key(&crypt_ftr)) {
Ken Sumrall3ad90722011-10-04 20:38:29 -07002364 SLOGE("Error getting crypt footer and key\n");
2365 return -1;
2366 }
2367
2368 if (crypt_ftr.flags & CRYPT_MNT_KEY_UNENCRYPTED) {
2369 /* If the device has no password, then just say the password is valid */
2370 rc = 0;
2371 } else {
AnilKumar Chimata98dc8352018-05-11 00:25:09 +05302372#ifdef CONFIG_HW_DISK_ENCRYPTION
2373 if(is_hw_disk_encryption((char*)crypt_ftr.crypto_type_name)) {
2374 if (verify_hw_fde_passwd(passwd, &crypt_ftr) >= 0)
2375 rc = 0;
2376 else
2377 rc = -1;
2378 } else {
2379 decrypt_master_key(passwd, decrypted_master_key, &crypt_ftr, 0, 0);
2380 if (!memcmp(decrypted_master_key, saved_master_key, crypt_ftr.keysize)) {
2381 /* They match, the password is correct */
2382 rc = 0;
2383 } else {
2384 /* If incorrect, sleep for a bit to prevent dictionary attacks */
2385 sleep(1);
2386 rc = 1;
2387 }
2388 }
2389#else
Paul Lawrenced0c7b172014-08-08 14:28:10 -07002390 decrypt_master_key(passwd, decrypted_master_key, &crypt_ftr, 0, 0);
Ken Sumrall3ad90722011-10-04 20:38:29 -07002391 if (!memcmp(decrypted_master_key, saved_master_key, crypt_ftr.keysize)) {
2392 /* They match, the password is correct */
2393 rc = 0;
2394 } else {
2395 /* If incorrect, sleep for a bit to prevent dictionary attacks */
2396 sleep(1);
2397 rc = 1;
2398 }
AnilKumar Chimata98dc8352018-05-11 00:25:09 +05302399#endif
Ken Sumrall3ad90722011-10-04 20:38:29 -07002400 }
2401
2402 return rc;
2403}
2404
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002405/* Initialize a crypt_mnt_ftr structure. The keysize is
Greg Kaiser57f9af62018-02-16 13:13:58 -08002406 * defaulted to cryptfs_get_keysize() bytes, and the filesystem size to 0.
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002407 * Presumably, at a minimum, the caller will update the
2408 * filesystem size and crypto_type_name after calling this function.
2409 */
Paul Crowley14c8c072018-09-18 13:30:21 -07002410static int cryptfs_init_crypt_mnt_ftr(struct crypt_mnt_ftr* ftr) {
Ken Sumrall160b4d62013-04-22 12:15:39 -07002411 off64_t off;
2412
2413 memset(ftr, 0, sizeof(struct crypt_mnt_ftr));
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002414 ftr->magic = CRYPT_MNT_MAGIC;
Kenny Rootc96a5f82013-06-14 12:08:28 -07002415 ftr->major_version = CURRENT_MAJOR_VERSION;
2416 ftr->minor_version = CURRENT_MINOR_VERSION;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002417 ftr->ftr_size = sizeof(struct crypt_mnt_ftr);
Greg Kaiser57f9af62018-02-16 13:13:58 -08002418 ftr->keysize = cryptfs_get_keysize();
Ken Sumrall160b4d62013-04-22 12:15:39 -07002419
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07002420 switch (keymaster_check_compatibility()) {
Paul Crowley14c8c072018-09-18 13:30:21 -07002421 case 1:
2422 ftr->kdf_type = KDF_SCRYPT_KEYMASTER;
2423 break;
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07002424
Paul Crowley14c8c072018-09-18 13:30:21 -07002425 case 0:
2426 ftr->kdf_type = KDF_SCRYPT;
2427 break;
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07002428
Paul Crowley14c8c072018-09-18 13:30:21 -07002429 default:
2430 SLOGE("keymaster_check_compatibility failed");
2431 return -1;
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07002432 }
2433
Kenny Rootc4c70f12013-06-14 12:11:38 -07002434 get_device_scrypt_params(ftr);
2435
Ken Sumrall160b4d62013-04-22 12:15:39 -07002436 ftr->persist_data_size = CRYPT_PERSIST_DATA_SIZE;
2437 if (get_crypt_ftr_info(NULL, &off) == 0) {
2438 ftr->persist_data_offset[0] = off + CRYPT_FOOTER_TO_PERSIST_OFFSET;
Paul Crowley14c8c072018-09-18 13:30:21 -07002439 ftr->persist_data_offset[1] = off + CRYPT_FOOTER_TO_PERSIST_OFFSET + ftr->persist_data_size;
Ken Sumrall160b4d62013-04-22 12:15:39 -07002440 }
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07002441
2442 return 0;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002443}
2444
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002445#define FRAMEWORK_BOOT_WAIT 60
2446
Paul Crowley14c8c072018-09-18 13:30:21 -07002447static int cryptfs_SHA256_fileblock(const char* filename, __le8* buf) {
2448 int fd = open(filename, O_RDONLY | O_CLOEXEC);
Paul Lawrence87999172014-02-20 12:21:31 -08002449 if (fd == -1) {
2450 SLOGE("Error opening file %s", filename);
2451 return -1;
2452 }
2453
2454 char block[CRYPT_INPLACE_BUFSIZE];
2455 memset(block, 0, sizeof(block));
2456 if (unix_read(fd, block, sizeof(block)) < 0) {
2457 SLOGE("Error reading file %s", filename);
2458 close(fd);
2459 return -1;
2460 }
2461
2462 close(fd);
2463
2464 SHA256_CTX c;
2465 SHA256_Init(&c);
2466 SHA256_Update(&c, block, sizeof(block));
2467 SHA256_Final(buf, &c);
2468
2469 return 0;
2470}
2471
Paul Lawrence7ee87cf2017-12-22 10:12:06 -08002472static int cryptfs_enable_all_volumes(struct crypt_mnt_ftr* crypt_ftr, char* crypto_blkdev,
2473 char* real_blkdev, int previously_encrypted_upto) {
Paul Crowley14c8c072018-09-18 13:30:21 -07002474 off64_t cur_encryption_done = 0, tot_encryption_size = 0;
Tim Murray8439dc92014-12-15 11:56:11 -08002475 int rc = -1;
Paul Lawrence87999172014-02-20 12:21:31 -08002476
Paul Lawrence87999172014-02-20 12:21:31 -08002477 /* The size of the userdata partition, and add in the vold volumes below */
2478 tot_encryption_size = crypt_ftr->fs_size;
2479
Paul Lawrence7ee87cf2017-12-22 10:12:06 -08002480 rc = cryptfs_enable_inplace(crypto_blkdev, real_blkdev, crypt_ftr->fs_size, &cur_encryption_done,
Paul Crowley0fd26262018-01-30 09:48:19 -08002481 tot_encryption_size, previously_encrypted_upto, true);
Paul Lawrence87999172014-02-20 12:21:31 -08002482
Paul Lawrence7ee87cf2017-12-22 10:12:06 -08002483 if (rc == ENABLE_INPLACE_ERR_DEV) {
2484 /* Hack for b/17898962 */
2485 SLOGE("cryptfs_enable: crypto block dev failure. Must reboot...\n");
2486 cryptfs_reboot(RebootType::reboot);
2487 }
JP Abgrall7fc1de82014-10-10 18:43:41 -07002488
Paul Lawrence7ee87cf2017-12-22 10:12:06 -08002489 if (!rc) {
2490 crypt_ftr->encrypted_upto = cur_encryption_done;
2491 }
Paul Lawrence87999172014-02-20 12:21:31 -08002492
Paul Lawrence7ee87cf2017-12-22 10:12:06 -08002493 if (!rc && crypt_ftr->encrypted_upto == crypt_ftr->fs_size) {
2494 /* The inplace routine never actually sets the progress to 100% due
2495 * to the round down nature of integer division, so set it here */
2496 property_set("vold.encrypt_progress", "100");
Paul Lawrence87999172014-02-20 12:21:31 -08002497 }
2498
2499 return rc;
2500}
2501
Paul Crowleyb64933a2017-10-31 08:25:55 -07002502static int vold_unmountAll(void) {
2503 VolumeManager* vm = VolumeManager::Instance();
2504 return vm->unmountAll();
2505}
2506
Paul Lawrence7ee87cf2017-12-22 10:12:06 -08002507int cryptfs_enable_internal(int crypt_type, const char* passwd, int no_ui) {
Tom Cherry4c5bde22019-01-29 14:34:01 -08002508 char crypto_blkdev[MAXPATHLEN];
2509 std::string real_blkdev;
Greg Kaiser59ad0182018-02-16 13:01:36 -08002510 unsigned char decrypted_master_key[MAX_KEY_LEN];
Paul Crowley14c8c072018-09-18 13:30:21 -07002511 int rc = -1, i;
Paul Lawrence87999172014-02-20 12:21:31 -08002512 struct crypt_mnt_ftr crypt_ftr;
Paul Crowley14c8c072018-09-18 13:30:21 -07002513 struct crypt_persist_data* pdata;
Ken Sumrall29d8da82011-05-18 17:20:07 -07002514 char encrypted_state[PROPERTY_VALUE_MAX];
Paul Crowley14c8c072018-09-18 13:30:21 -07002515 char lockid[32] = {0};
Tom Cherry4c5bde22019-01-29 14:34:01 -08002516 std::string key_loc;
Ken Sumrall29d8da82011-05-18 17:20:07 -07002517 int num_vols;
Paul Lawrence87999172014-02-20 12:21:31 -08002518 off64_t previously_encrypted_upto = 0;
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002519 bool rebootEncryption = false;
Wei Wang4375f1b2017-02-24 17:43:01 -08002520 bool onlyCreateHeader = false;
AnilKumar Chimata98dc8352018-05-11 00:25:09 +05302521#ifdef CONFIG_HW_DISK_ENCRYPTION
2522 unsigned char newpw[32];
2523 int key_index = 0;
2524#endif
2525 int index = 0;
Tri Vo15bbe222019-06-21 12:21:48 -07002526 std::unique_ptr<android::wakelock::WakeLock> wakeLock = nullptr;
AnilKumar Chimata98dc8352018-05-11 00:25:09 +05302527
Paul Lawrence7ee87cf2017-12-22 10:12:06 -08002528 if (get_crypt_ftr_and_key(&crypt_ftr) == 0) {
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002529 if (crypt_ftr.flags & CRYPT_ENCRYPTION_IN_PROGRESS) {
2530 /* An encryption was underway and was interrupted */
2531 previously_encrypted_upto = crypt_ftr.encrypted_upto;
2532 crypt_ftr.encrypted_upto = 0;
2533 crypt_ftr.flags &= ~CRYPT_ENCRYPTION_IN_PROGRESS;
Paul Lawrence6bfed202014-07-28 12:47:22 -07002534
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002535 /* At this point, we are in an inconsistent state. Until we successfully
2536 complete encryption, a reboot will leave us broken. So mark the
2537 encryption failed in case that happens.
2538 On successfully completing encryption, remove this flag */
2539 crypt_ftr.flags |= CRYPT_INCONSISTENT_STATE;
Paul Lawrence6bfed202014-07-28 12:47:22 -07002540
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002541 put_crypt_ftr_and_key(&crypt_ftr);
2542 } else if (crypt_ftr.flags & CRYPT_FORCE_ENCRYPTION) {
2543 if (!check_ftr_sha(&crypt_ftr)) {
2544 memset(&crypt_ftr, 0, sizeof(crypt_ftr));
2545 put_crypt_ftr_and_key(&crypt_ftr);
2546 goto error_unencrypted;
2547 }
2548
2549 /* Doing a reboot-encryption*/
2550 crypt_ftr.flags &= ~CRYPT_FORCE_ENCRYPTION;
2551 crypt_ftr.flags |= CRYPT_FORCE_COMPLETE;
2552 rebootEncryption = true;
2553 }
Greg Kaiser59ad0182018-02-16 13:01:36 -08002554 } else {
2555 // We don't want to accidentally reference invalid data.
2556 memset(&crypt_ftr, 0, sizeof(crypt_ftr));
Paul Lawrence87999172014-02-20 12:21:31 -08002557 }
2558
2559 property_get("ro.crypto.state", encrypted_state, "");
2560 if (!strcmp(encrypted_state, "encrypted") && !previously_encrypted_upto) {
2561 SLOGE("Device is already running encrypted, aborting");
2562 goto error_unencrypted;
2563 }
2564
Tom Cherry4c5bde22019-01-29 14:34:01 -08002565 get_crypt_info(&key_loc, &real_blkdev);
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002566
Ken Sumrall3ed82362011-01-28 23:31:16 -08002567 /* Get the size of the real block device */
Oleksiy Avramchenko625dc782018-05-23 10:50:46 +02002568 uint64_t nr_sec;
2569 if (android::vold::GetBlockDev512Sectors(real_blkdev, &nr_sec) != android::OK) {
Tom Cherry4c5bde22019-01-29 14:34:01 -08002570 SLOGE("Cannot get size of block device %s\n", real_blkdev.c_str());
Ken Sumrall3ed82362011-01-28 23:31:16 -08002571 goto error_unencrypted;
2572 }
Ken Sumrall3ed82362011-01-28 23:31:16 -08002573
2574 /* If doing inplace encryption, make sure the orig fs doesn't include the crypto footer */
Tom Cherry4c5bde22019-01-29 14:34:01 -08002575 if (key_loc == KEY_IN_FOOTER) {
Oleksiy Avramchenko625dc782018-05-23 10:50:46 +02002576 uint64_t fs_size_sec, max_fs_size_sec;
Tom Cherry4c5bde22019-01-29 14:34:01 -08002577 fs_size_sec = get_fs_size(real_blkdev.c_str());
2578 if (fs_size_sec == 0) fs_size_sec = get_f2fs_filesystem_size_sec(real_blkdev.data());
Daniel Rosenberge82df162014-08-15 22:19:23 +00002579
Paul Lawrence87999172014-02-20 12:21:31 -08002580 max_fs_size_sec = nr_sec - (CRYPT_FOOTER_OFFSET / CRYPT_SECTOR_SIZE);
Ken Sumrall3ed82362011-01-28 23:31:16 -08002581
2582 if (fs_size_sec > max_fs_size_sec) {
2583 SLOGE("Orig filesystem overlaps crypto footer region. Cannot encrypt in place.");
2584 goto error_unencrypted;
2585 }
2586 }
2587
Ken Sumrall5d4c68e2011-01-30 19:06:03 -08002588 /* Get a wakelock as this may take a while, and we don't want the
2589 * device to sleep on us. We'll grab a partial wakelock, and if the UI
2590 * wants to keep the screen on, it can grab a full wakelock.
2591 */
Paul Crowley14c8c072018-09-18 13:30:21 -07002592 snprintf(lockid, sizeof(lockid), "enablecrypto%d", (int)getpid());
Tri Vo15bbe222019-06-21 12:21:48 -07002593 wakeLock = std::make_unique<android::wakelock::WakeLock>(lockid);
Ken Sumrall5d4c68e2011-01-30 19:06:03 -08002594
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002595 /* The init files are setup to stop the class main and late start when
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002596 * vold sets trigger_shutdown_framework.
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002597 */
2598 property_set("vold.decrypt", "trigger_shutdown_framework");
2599 SLOGD("Just asked init to shut down class main\n");
2600
Jeff Sharkey9c484982015-03-31 10:35:33 -07002601 /* Ask vold to unmount all devices that it manages */
2602 if (vold_unmountAll()) {
2603 SLOGE("Failed to unmount all vold managed devices");
Ken Sumrall2eaf7132011-01-14 12:45:48 -08002604 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002605
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002606 /* no_ui means we are being called from init, not settings.
2607 Now we always reboot from settings, so !no_ui means reboot
2608 */
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002609 if (!no_ui) {
2610 /* Try fallback, which is to reboot and try there */
2611 onlyCreateHeader = true;
2612 FILE* breadcrumb = fopen(BREADCRUMB_FILE, "we");
2613 if (breadcrumb == 0) {
2614 SLOGE("Failed to create breadcrumb file");
2615 goto error_shutting_down;
2616 }
2617 fclose(breadcrumb);
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002618 }
2619
2620 /* Do extra work for a better UX when doing the long inplace encryption */
Paul Lawrence7ee87cf2017-12-22 10:12:06 -08002621 if (!onlyCreateHeader) {
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002622 /* Now that /data is unmounted, we need to mount a tmpfs
2623 * /data, set a property saying we're doing inplace encryption,
2624 * and restart the framework.
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002625 */
xzj7e38a3a2018-10-12 10:17:11 +08002626 wait_and_unmount(DATA_MNT_POINT, true);
Ken Sumralle5032c42012-04-01 23:58:44 -07002627 if (fs_mgr_do_tmpfs_mount(DATA_MNT_POINT)) {
Ken Sumrall3ed82362011-01-28 23:31:16 -08002628 goto error_shutting_down;
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002629 }
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002630 /* Tells the framework that inplace encryption is starting */
Ken Sumrall7df84122011-01-18 14:04:08 -08002631 property_set("vold.encrypt_progress", "0");
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002632
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002633 /* restart the framework. */
2634 /* Create necessary paths on /data */
Wei Wang42e38102017-06-07 10:46:12 -07002635 prep_data_fs();
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002636
Ken Sumrall92736ef2012-10-17 20:57:14 -07002637 /* Ugh, shutting down the framework is not synchronous, so until it
2638 * can be fixed, this horrible hack will wait a moment for it all to
2639 * shut down before proceeding. Without it, some devices cannot
2640 * restart the graphics services.
2641 */
2642 sleep(2);
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002643 }
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002644
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002645 /* Start the actual work of making an encrypted filesystem */
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002646 /* Initialize a crypt_mnt_ftr for the partition */
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002647 if (previously_encrypted_upto == 0 && !rebootEncryption) {
Paul Lawrence69f4ebd2014-04-14 12:17:14 -07002648 if (cryptfs_init_crypt_mnt_ftr(&crypt_ftr)) {
2649 goto error_shutting_down;
2650 }
Ken Sumrall160b4d62013-04-22 12:15:39 -07002651
Tom Cherry4c5bde22019-01-29 14:34:01 -08002652 if (key_loc == KEY_IN_FOOTER) {
Paul Crowley14c8c072018-09-18 13:30:21 -07002653 crypt_ftr.fs_size = nr_sec - (CRYPT_FOOTER_OFFSET / CRYPT_SECTOR_SIZE);
Paul Lawrence87999172014-02-20 12:21:31 -08002654 } else {
2655 crypt_ftr.fs_size = nr_sec;
2656 }
Paul Lawrence6bfed202014-07-28 12:47:22 -07002657 /* At this point, we are in an inconsistent state. Until we successfully
2658 complete encryption, a reboot will leave us broken. So mark the
2659 encryption failed in case that happens.
2660 On successfully completing encryption, remove this flag */
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002661 if (onlyCreateHeader) {
2662 crypt_ftr.flags |= CRYPT_FORCE_ENCRYPTION;
2663 } else {
2664 crypt_ftr.flags |= CRYPT_INCONSISTENT_STATE;
2665 }
Paul Lawrence87999172014-02-20 12:21:31 -08002666 crypt_ftr.crypt_type = crypt_type;
AnilKumar Chimata98dc8352018-05-11 00:25:09 +05302667#ifdef CONFIG_HW_DISK_ENCRYPTION
Bill Peckham0db11972018-10-10 10:25:42 -07002668 strlcpy((char*)crypt_ftr.crypto_type_name, "aes-xts",
2669 MAX_CRYPTO_TYPE_NAME_LEN);
AnilKumar Chimata98dc8352018-05-11 00:25:09 +05302670#else
Paul Crowley14c8c072018-09-18 13:30:21 -07002671 strlcpy((char*)crypt_ftr.crypto_type_name, cryptfs_get_crypto_name(),
2672 MAX_CRYPTO_TYPE_NAME_LEN);
AnilKumar Chimata98dc8352018-05-11 00:25:09 +05302673#endif
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002674
Paul Lawrence87999172014-02-20 12:21:31 -08002675 /* Make an encrypted master key */
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002676 if (create_encrypted_random_key(onlyCreateHeader ? DEFAULT_PASSWORD : passwd,
2677 crypt_ftr.master_key, crypt_ftr.salt, &crypt_ftr)) {
Paul Lawrence87999172014-02-20 12:21:31 -08002678 SLOGE("Cannot create encrypted master key\n");
2679 goto error_shutting_down;
2680 }
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002681
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002682 /* Replace scrypted intermediate key if we are preparing for a reboot */
2683 if (onlyCreateHeader) {
Greg Kaiser59ad0182018-02-16 13:01:36 -08002684 unsigned char fake_master_key[MAX_KEY_LEN];
2685 unsigned char encrypted_fake_master_key[MAX_KEY_LEN];
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002686 memset(fake_master_key, 0, sizeof(fake_master_key));
Paul Crowley14c8c072018-09-18 13:30:21 -07002687 encrypt_master_key(passwd, crypt_ftr.salt, fake_master_key, encrypted_fake_master_key,
Bill Peckham0db11972018-10-10 10:25:42 -07002688 &crypt_ftr, true);
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002689 }
2690
Paul Lawrence87999172014-02-20 12:21:31 -08002691 /* Write the key to the end of the partition */
2692 put_crypt_ftr_and_key(&crypt_ftr);
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002693
Paul Lawrence87999172014-02-20 12:21:31 -08002694 /* If any persistent data has been remembered, save it.
2695 * If none, create a valid empty table and save that.
2696 */
2697 if (!persist_data) {
Paul Crowley14c8c072018-09-18 13:30:21 -07002698 pdata = (crypt_persist_data*)malloc(CRYPT_PERSIST_DATA_SIZE);
2699 if (pdata) {
2700 init_empty_persist_data(pdata, CRYPT_PERSIST_DATA_SIZE);
2701 persist_data = pdata;
2702 }
Paul Lawrence87999172014-02-20 12:21:31 -08002703 }
2704 if (persist_data) {
2705 save_persistent_data();
2706 }
Ken Sumrall160b4d62013-04-22 12:15:39 -07002707 }
2708
AnilKumar Chimata98dc8352018-05-11 00:25:09 +05302709 /* When encryption triggered from settings, encryption starts after reboot.
2710 So set the encryption key when the actual encryption starts.
2711 */
2712#ifdef CONFIG_HW_DISK_ENCRYPTION
2713 if (previously_encrypted_upto == 0) {
2714 if (!rebootEncryption)
2715 clear_hw_device_encryption_key();
2716
2717 if (get_keymaster_hw_fde_passwd(
2718 onlyCreateHeader ? DEFAULT_PASSWORD : passwd,
2719 newpw, crypt_ftr.salt, &crypt_ftr))
2720 key_index = set_hw_device_encryption_key(
2721 onlyCreateHeader ? DEFAULT_PASSWORD : passwd,
2722 (char*)crypt_ftr.crypto_type_name);
2723 else
2724 key_index = set_hw_device_encryption_key((const char*)newpw,
2725 (char*) crypt_ftr.crypto_type_name);
2726 if (key_index < 0)
2727 goto error_shutting_down;
2728
2729 crypt_ftr.flags |= CRYPT_ASCII_PASSWORD_UPDATED;
2730 put_crypt_ftr_and_key(&crypt_ftr);
2731 }
2732#endif
2733
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002734 if (onlyCreateHeader) {
2735 sleep(2);
Josh Gaofec44372017-08-28 13:22:55 -07002736 cryptfs_reboot(RebootType::reboot);
AnilKumar Chimata98dc8352018-05-11 00:25:09 +05302737 } else {
2738 /* Do extra work for a better UX when doing the long inplace encryption */
2739 /* Now that /data is unmounted, we need to mount a tmpfs
2740 * /data, set a property saying we're doing inplace encryption,
2741 * and restart the framework.
2742 */
2743 if (fs_mgr_do_tmpfs_mount(DATA_MNT_POINT)) {
2744 goto error_shutting_down;
2745 }
2746 /* Tells the framework that inplace encryption is starting */
2747 property_set("vold.encrypt_progress", "0");
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002748
AnilKumar Chimata98dc8352018-05-11 00:25:09 +05302749 /* restart the framework. */
2750 /* Create necessary paths on /data */
2751 prep_data_fs();
2752
2753 /* Ugh, shutting down the framework is not synchronous, so until it
2754 * can be fixed, this horrible hack will wait a moment for it all to
2755 * shut down before proceeding. Without it, some devices cannot
2756 * restart the graphics services.
2757 */
2758 sleep(2);
2759
Ajay Dudani87701e22014-09-17 21:02:52 -07002760 /* startup service classes main and late_start */
2761 property_set("vold.decrypt", "trigger_restart_min_framework");
2762 SLOGD("Just triggered restart_min_framework\n");
2763
2764 /* OK, the framework is restarted and will soon be showing a
2765 * progress bar. Time to setup an encrypted mapping, and
2766 * either write a new filesystem, or encrypt in place updating
2767 * the progress bar as we work.
2768 */
2769 }
2770
Paul Lawrenced0c7b172014-08-08 14:28:10 -07002771 decrypt_master_key(passwd, decrypted_master_key, &crypt_ftr, 0, 0);
AnilKumar Chimata98dc8352018-05-11 00:25:09 +05302772#ifdef CONFIG_HW_DISK_ENCRYPTION
2773 if (is_hw_disk_encryption((char*)crypt_ftr.crypto_type_name) && is_ice_enabled())
AnilKumar Chimatad08106a2018-02-11 17:11:24 +05302774#ifdef CONFIG_HW_DISK_ENCRYPT_PERF
Yifan Hong804afe12019-02-07 12:56:47 -08002775 strlcpy(crypto_blkdev, real_blkdev.c_str(), sizeof(crypto_blkdev));
AnilKumar Chimatad08106a2018-02-11 17:11:24 +05302776#else
Neeraj Soni73b46952019-09-12 16:47:27 +05302777 create_crypto_blk_dev_hw(&crypt_ftr, (unsigned char*)&key_index, real_blkdev.c_str(), crypto_blkdev,
AnilKumar Chimata98dc8352018-05-11 00:25:09 +05302778 CRYPTO_BLOCK_DEVICE, 0);
AnilKumar Chimatad08106a2018-02-11 17:11:24 +05302779#endif
AnilKumar Chimata98dc8352018-05-11 00:25:09 +05302780 else
Eric Arseneau2f8ce652019-02-06 14:23:39 -08002781 create_crypto_blk_dev(&crypt_ftr, decrypted_master_key, real_blkdev.c_str(), crypto_blkdev,
AnilKumar Chimata98dc8352018-05-11 00:25:09 +05302782 CRYPTO_BLOCK_DEVICE, 0);
2783#else
Tom Cherry4c5bde22019-01-29 14:34:01 -08002784 create_crypto_blk_dev(&crypt_ftr, decrypted_master_key, real_blkdev.c_str(), crypto_blkdev,
Paul Crowley5afbc622017-11-27 09:42:17 -08002785 CRYPTO_BLOCK_DEVICE, 0);
AnilKumar Chimata98dc8352018-05-11 00:25:09 +05302786#endif
Ken Sumrall29d8da82011-05-18 17:20:07 -07002787
Paul Lawrence87999172014-02-20 12:21:31 -08002788 /* If we are continuing, check checksums match */
2789 rc = 0;
2790 if (previously_encrypted_upto) {
2791 __le8 hash_first_block[SHA256_DIGEST_LENGTH];
AnilKumar Chimatad08106a2018-02-11 17:11:24 +05302792#if defined(CONFIG_HW_DISK_ENCRYPTION) && defined(CONFIG_HW_DISK_ENCRYPT_PERF)
2793 if (set_ice_param(START_ENCDEC)) {
2794 SLOGE("Failed to set ICE data");
2795 goto error_shutting_down;
2796 }
2797#endif
Paul Lawrence87999172014-02-20 12:21:31 -08002798 rc = cryptfs_SHA256_fileblock(crypto_blkdev, hash_first_block);
Ken Sumrall128626f2011-06-28 18:45:14 -07002799
Paul Crowley14c8c072018-09-18 13:30:21 -07002800 if (!rc &&
2801 memcmp(hash_first_block, crypt_ftr.hash_first_block, sizeof(hash_first_block)) != 0) {
Paul Lawrence87999172014-02-20 12:21:31 -08002802 SLOGE("Checksums do not match - trigger wipe");
2803 rc = -1;
Ken Sumrall29d8da82011-05-18 17:20:07 -07002804 }
2805 }
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002806
AnilKumar Chimatad08106a2018-02-11 17:11:24 +05302807#if defined(CONFIG_HW_DISK_ENCRYPTION) && defined(CONFIG_HW_DISK_ENCRYPT_PERF)
2808 if (set_ice_param(START_ENC)) {
2809 SLOGE("Failed to set ICE data");
2810 goto error_shutting_down;
2811 }
2812#endif
Paul Lawrence87999172014-02-20 12:21:31 -08002813 if (!rc) {
Tom Cherry4c5bde22019-01-29 14:34:01 -08002814 rc = cryptfs_enable_all_volumes(&crypt_ftr, crypto_blkdev, real_blkdev.data(),
Paul Lawrence87999172014-02-20 12:21:31 -08002815 previously_encrypted_upto);
2816 }
2817
AnilKumar Chimatad08106a2018-02-11 17:11:24 +05302818#if defined(CONFIG_HW_DISK_ENCRYPTION) && defined(CONFIG_HW_DISK_ENCRYPT_PERF)
2819 if (set_ice_param(START_ENCDEC)) {
2820 SLOGE("Failed to set ICE data");
2821 goto error_shutting_down;
2822 }
2823#endif
Paul Lawrence87999172014-02-20 12:21:31 -08002824 /* Calculate checksum if we are not finished */
Paul Lawrence7ee87cf2017-12-22 10:12:06 -08002825 if (!rc && crypt_ftr.encrypted_upto != crypt_ftr.fs_size) {
Paul Crowley14c8c072018-09-18 13:30:21 -07002826 rc = cryptfs_SHA256_fileblock(crypto_blkdev, crypt_ftr.hash_first_block);
Paul Lawrence73d7a022014-06-09 14:10:09 -07002827 if (rc) {
Paul Lawrence87999172014-02-20 12:21:31 -08002828 SLOGE("Error calculating checksum for continuing encryption");
2829 rc = -1;
Ken Sumrall29d8da82011-05-18 17:20:07 -07002830 }
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002831 }
2832
2833 /* Undo the dm-crypt mapping whether we succeed or not */
AnilKumar Chimatad08106a2018-02-11 17:11:24 +05302834#if defined(CONFIG_HW_DISK_ENCRYPTION) && defined(CONFIG_HW_DISK_ENCRYPT_PERF)
2835 if (!is_ice_enabled())
2836 delete_crypto_blk_dev(CRYPTO_BLOCK_DEVICE);
2837#else
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002838 delete_crypto_blk_dev(CRYPTO_BLOCK_DEVICE);
AnilKumar Chimatad08106a2018-02-11 17:11:24 +05302839#endif
Ken Sumrall29d8da82011-05-18 17:20:07 -07002840
Paul Crowley14c8c072018-09-18 13:30:21 -07002841 if (!rc) {
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002842 /* Success */
Paul Lawrence6bfed202014-07-28 12:47:22 -07002843 crypt_ftr.flags &= ~CRYPT_INCONSISTENT_STATE;
Ken Sumrall7f7dbaa2011-02-01 15:46:41 -08002844
Paul Lawrence7ee87cf2017-12-22 10:12:06 -08002845 if (crypt_ftr.encrypted_upto != crypt_ftr.fs_size) {
Paul Lawrence87999172014-02-20 12:21:31 -08002846 SLOGD("Encrypted up to sector %lld - will continue after reboot",
2847 crypt_ftr.encrypted_upto);
Paul Lawrence6bfed202014-07-28 12:47:22 -07002848 crypt_ftr.flags |= CRYPT_ENCRYPTION_IN_PROGRESS;
Paul Lawrence87999172014-02-20 12:21:31 -08002849 }
Paul Lawrence73d7a022014-06-09 14:10:09 -07002850
Paul Lawrence6bfed202014-07-28 12:47:22 -07002851 put_crypt_ftr_and_key(&crypt_ftr);
Ken Sumralld33d4172011-02-01 00:49:13 -08002852
Paul Lawrence7ee87cf2017-12-22 10:12:06 -08002853 if (crypt_ftr.encrypted_upto == crypt_ftr.fs_size) {
2854 char value[PROPERTY_VALUE_MAX];
2855 property_get("ro.crypto.state", value, "");
2856 if (!strcmp(value, "")) {
2857 /* default encryption - continue first boot sequence */
2858 property_set("ro.crypto.state", "encrypted");
2859 property_set("ro.crypto.type", "block");
Tri Vo15bbe222019-06-21 12:21:48 -07002860 wakeLock.reset(nullptr);
Paul Lawrence7ee87cf2017-12-22 10:12:06 -08002861 if (rebootEncryption && crypt_ftr.crypt_type != CRYPT_TYPE_DEFAULT) {
2862 // Bring up cryptkeeper that will check the password and set it
2863 property_set("vold.decrypt", "trigger_shutdown_framework");
2864 sleep(2);
2865 property_set("vold.encrypt_progress", "");
2866 cryptfs_trigger_restart_min_framework();
2867 } else {
2868 cryptfs_check_passwd(DEFAULT_PASSWORD);
2869 cryptfs_restart_internal(1);
2870 }
2871 return 0;
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002872 } else {
Paul Lawrence7ee87cf2017-12-22 10:12:06 -08002873 sleep(2); /* Give the UI a chance to show 100% progress */
2874 cryptfs_reboot(RebootType::reboot);
Paul Lawrence3d99eba2015-11-20 07:07:19 -08002875 }
Paul Lawrence87999172014-02-20 12:21:31 -08002876 } else {
Paul Lawrenceb6672e12014-08-15 07:37:28 -07002877 sleep(2); /* Partially encrypted, ensure writes flushed to ssd */
Josh Gaofec44372017-08-28 13:22:55 -07002878 cryptfs_reboot(RebootType::shutdown);
Paul Lawrence87999172014-02-20 12:21:31 -08002879 }
Ken Sumrall3ed82362011-01-28 23:31:16 -08002880 } else {
Mike Lockwoodee6d8c42012-02-15 13:43:28 -08002881 char value[PROPERTY_VALUE_MAX];
2882
Ken Sumrall319369a2012-06-27 16:30:18 -07002883 property_get("ro.vold.wipe_on_crypt_fail", value, "0");
Mike Lockwoodee6d8c42012-02-15 13:43:28 -08002884 if (!strcmp(value, "1")) {
2885 /* wipe data if encryption failed */
2886 SLOGE("encryption failed - rebooting into recovery to wipe data\n");
Wei Wang4375f1b2017-02-24 17:43:01 -08002887 std::string err;
2888 const std::vector<std::string> options = {
Paul Crowley14c8c072018-09-18 13:30:21 -07002889 "--wipe_data\n--reason=cryptfs_enable_internal\n"};
Wei Wang4375f1b2017-02-24 17:43:01 -08002890 if (!write_bootloader_message(options, &err)) {
2891 SLOGE("could not write bootloader message: %s", err.c_str());
Mike Lockwoodee6d8c42012-02-15 13:43:28 -08002892 }
Josh Gaofec44372017-08-28 13:22:55 -07002893 cryptfs_reboot(RebootType::recovery);
Mike Lockwoodee6d8c42012-02-15 13:43:28 -08002894 } else {
2895 /* set property to trigger dialog */
2896 property_set("vold.encrypt_progress", "error_partially_encrypted");
Mike Lockwoodee6d8c42012-02-15 13:43:28 -08002897 }
Ken Sumrall3ed82362011-01-28 23:31:16 -08002898 return -1;
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002899 }
2900
Ken Sumrall3ed82362011-01-28 23:31:16 -08002901 /* hrm, the encrypt step claims success, but the reboot failed.
2902 * This should not happen.
2903 * Set the property and return. Hope the framework can deal with it.
2904 */
2905 property_set("vold.encrypt_progress", "error_reboot_failed");
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002906 return rc;
Ken Sumrall3ed82362011-01-28 23:31:16 -08002907
2908error_unencrypted:
2909 property_set("vold.encrypt_progress", "error_not_encrypted");
2910 return -1;
2911
2912error_shutting_down:
2913 /* we failed, and have not encrypted anthing, so the users's data is still intact,
2914 * but the framework is stopped and not restarted to show the error, so it's up to
2915 * vold to restart the system.
2916 */
Paul Crowley14c8c072018-09-18 13:30:21 -07002917 SLOGE(
2918 "Error enabling encryption after framework is shutdown, no data changed, restarting "
2919 "system");
Josh Gaofec44372017-08-28 13:22:55 -07002920 cryptfs_reboot(RebootType::reboot);
Ken Sumrall3ed82362011-01-28 23:31:16 -08002921
2922 /* shouldn't get here */
2923 property_set("vold.encrypt_progress", "error_shutting_down");
2924 return -1;
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002925}
2926
Paul Lawrence7ee87cf2017-12-22 10:12:06 -08002927int cryptfs_enable(int type, const char* passwd, int no_ui) {
2928 return cryptfs_enable_internal(type, passwd, no_ui);
Paul Lawrence13486032014-02-03 13:28:11 -08002929}
2930
Paul Lawrence7ee87cf2017-12-22 10:12:06 -08002931int cryptfs_enable_default(int no_ui) {
2932 return cryptfs_enable_internal(CRYPT_TYPE_DEFAULT, DEFAULT_PASSWORD, no_ui);
Paul Lawrence13486032014-02-03 13:28:11 -08002933}
2934
Bill Peckham0db11972018-10-10 10:25:42 -07002935int cryptfs_changepw(int crypt_type, const char* currentpw, const char* newpw) {
Eric Biggersa701c452018-10-23 13:06:55 -07002936 if (fscrypt_is_native()) {
Paul Lawrence7b6b5652016-02-02 11:14:59 -08002937 SLOGE("cryptfs_changepw not valid for file encryption");
2938 return -1;
Paul Lawrence05335c32015-03-05 09:46:23 -08002939 }
2940
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002941 struct crypt_mnt_ftr crypt_ftr;
JP Abgrall933216c2015-02-11 13:44:32 -08002942 int rc;
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002943
2944 /* This is only allowed after we've successfully decrypted the master key */
Paul Lawrencef4faa572014-01-29 13:31:03 -08002945 if (!master_key_saved) {
Ken Sumrall0cc16632011-01-18 20:32:26 -08002946 SLOGE("Key not saved, aborting");
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002947 return -1;
2948 }
2949
Paul Lawrencef4faa572014-01-29 13:31:03 -08002950 if (crypt_type < 0 || crypt_type > CRYPT_TYPE_MAX_TYPE) {
2951 SLOGE("Invalid crypt_type %d", crypt_type);
2952 return -1;
2953 }
2954
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002955 /* get key */
Ken Sumrall160b4d62013-04-22 12:15:39 -07002956 if (get_crypt_ftr_and_key(&crypt_ftr)) {
Paul Lawrencef4faa572014-01-29 13:31:03 -08002957 SLOGE("Error getting crypt footer and key");
2958 return -1;
Ken Sumrall8ddbe402011-01-17 15:26:29 -08002959 }
2960
AnilKumar Chimata98dc8352018-05-11 00:25:09 +05302961#ifdef CONFIG_HW_DISK_ENCRYPTION
2962 if(is_hw_disk_encryption((char*)crypt_ftr.crypto_type_name))
2963 return cryptfs_changepw_hw_fde(crypt_type, currentpw, newpw);
2964 else {
2965 crypt_ftr.crypt_type = crypt_type;
2966
2967 rc = encrypt_master_key(crypt_type == CRYPT_TYPE_DEFAULT ?
2968 DEFAULT_PASSWORD : newpw,
2969 crypt_ftr.salt,
2970 saved_master_key,
2971 crypt_ftr.master_key,
2972 &crypt_ftr, false);
2973 if (rc) {
2974 SLOGE("Encrypt master key failed: %d", rc);
2975 return -1;
2976 }
2977 /* save the key */
2978 put_crypt_ftr_and_key(&crypt_ftr);
2979
2980 return 0;
2981 }
2982#else
Paul Lawrencef4faa572014-01-29 13:31:03 -08002983 crypt_ftr.crypt_type = crypt_type;
2984
Paul Crowley14c8c072018-09-18 13:30:21 -07002985 rc = encrypt_master_key(crypt_type == CRYPT_TYPE_DEFAULT ? DEFAULT_PASSWORD : newpw,
Bill Peckham0db11972018-10-10 10:25:42 -07002986 crypt_ftr.salt, saved_master_key, crypt_ftr.master_key, &crypt_ftr,
2987 false);
JP Abgrall933216c2015-02-11 13:44:32 -08002988 if (rc) {
2989 SLOGE("Encrypt master key failed: %d", rc);
2990 return -1;
2991 }
Jason parks70a4b3f2011-01-28 10:10:47 -06002992 /* save the key */
Ken Sumrall160b4d62013-04-22 12:15:39 -07002993 put_crypt_ftr_and_key(&crypt_ftr);
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002994
2995 return 0;
AnilKumar Chimata98dc8352018-05-11 00:25:09 +05302996#endif
Ken Sumrall8f869aa2010-12-03 03:47:09 -08002997}
Ken Sumrall160b4d62013-04-22 12:15:39 -07002998
AnilKumar Chimata98dc8352018-05-11 00:25:09 +05302999#ifdef CONFIG_HW_DISK_ENCRYPTION
3000int cryptfs_changepw_hw_fde(int crypt_type, const char *currentpw, const char *newpw)
3001{
3002 struct crypt_mnt_ftr crypt_ftr;
3003 int rc;
3004 int previous_type;
3005
3006 /* get key */
3007 if (get_crypt_ftr_and_key(&crypt_ftr)) {
3008 SLOGE("Error getting crypt footer and key");
3009 return -1;
3010 }
3011
3012 previous_type = crypt_ftr.crypt_type;
3013 int rc1;
3014 unsigned char tmp_curpw[32] = {0};
3015 rc1 = get_keymaster_hw_fde_passwd(crypt_ftr.crypt_type == CRYPT_TYPE_DEFAULT ?
3016 DEFAULT_PASSWORD : currentpw, tmp_curpw,
3017 crypt_ftr.salt, &crypt_ftr);
3018
3019 crypt_ftr.crypt_type = crypt_type;
3020
3021 int ret, rc2;
3022 unsigned char tmp_newpw[32] = {0};
3023
3024 rc2 = get_keymaster_hw_fde_passwd(crypt_type == CRYPT_TYPE_DEFAULT ?
3025 DEFAULT_PASSWORD : newpw , tmp_newpw,
3026 crypt_ftr.salt, &crypt_ftr);
3027
3028 if (is_hw_disk_encryption((char*)crypt_ftr.crypto_type_name)) {
3029 ret = update_hw_device_encryption_key(
3030 rc1 ? (previous_type == CRYPT_TYPE_DEFAULT ? DEFAULT_PASSWORD : currentpw) : (const char*)tmp_curpw,
3031 rc2 ? (crypt_type == CRYPT_TYPE_DEFAULT ? DEFAULT_PASSWORD : newpw): (const char*)tmp_newpw,
3032 (char*)crypt_ftr.crypto_type_name);
3033 if (ret) {
3034 SLOGE("Error updating device encryption hardware key ret %d", ret);
3035 return -1;
3036 } else {
3037 SLOGI("Encryption hardware key updated");
3038 }
3039 }
3040
3041 /* save the key */
3042 put_crypt_ftr_and_key(&crypt_ftr);
3043 return 0;
3044}
3045#endif
3046
Rubin Xu85c01f92014-10-13 12:49:54 +01003047static unsigned int persist_get_max_entries(int encrypted) {
3048 struct crypt_mnt_ftr crypt_ftr;
3049 unsigned int dsize;
Rubin Xu85c01f92014-10-13 12:49:54 +01003050
3051 /* If encrypted, use the values from the crypt_ftr, otherwise
3052 * use the values for the current spec.
3053 */
3054 if (encrypted) {
3055 if (get_crypt_ftr_and_key(&crypt_ftr)) {
Rubin Xud78181b2018-10-09 16:13:38 +01003056 /* Something is wrong, assume no space for entries */
3057 return 0;
Rubin Xu85c01f92014-10-13 12:49:54 +01003058 }
3059 dsize = crypt_ftr.persist_data_size;
3060 } else {
3061 dsize = CRYPT_PERSIST_DATA_SIZE;
3062 }
3063
Rubin Xud78181b2018-10-09 16:13:38 +01003064 if (dsize > sizeof(struct crypt_persist_data)) {
3065 return (dsize - sizeof(struct crypt_persist_data)) / sizeof(struct crypt_persist_entry);
3066 } else {
3067 return 0;
3068 }
Rubin Xu85c01f92014-10-13 12:49:54 +01003069}
3070
Paul Crowley14c8c072018-09-18 13:30:21 -07003071static int persist_get_key(const char* fieldname, char* value) {
Ken Sumrall160b4d62013-04-22 12:15:39 -07003072 unsigned int i;
3073
3074 if (persist_data == NULL) {
3075 return -1;
3076 }
3077 for (i = 0; i < persist_data->persist_valid_entries; i++) {
3078 if (!strncmp(persist_data->persist_entry[i].key, fieldname, PROPERTY_KEY_MAX)) {
3079 /* We found it! */
3080 strlcpy(value, persist_data->persist_entry[i].val, PROPERTY_VALUE_MAX);
3081 return 0;
3082 }
3083 }
3084
3085 return -1;
3086}
3087
Paul Crowley14c8c072018-09-18 13:30:21 -07003088static int persist_set_key(const char* fieldname, const char* value, int encrypted) {
Ken Sumrall160b4d62013-04-22 12:15:39 -07003089 unsigned int i;
3090 unsigned int num;
Ken Sumrall160b4d62013-04-22 12:15:39 -07003091 unsigned int max_persistent_entries;
Ken Sumrall160b4d62013-04-22 12:15:39 -07003092
3093 if (persist_data == NULL) {
3094 return -1;
3095 }
3096
Rubin Xu85c01f92014-10-13 12:49:54 +01003097 max_persistent_entries = persist_get_max_entries(encrypted);
Ken Sumrall160b4d62013-04-22 12:15:39 -07003098
3099 num = persist_data->persist_valid_entries;
3100
3101 for (i = 0; i < num; i++) {
3102 if (!strncmp(persist_data->persist_entry[i].key, fieldname, PROPERTY_KEY_MAX)) {
3103 /* We found an existing entry, update it! */
3104 memset(persist_data->persist_entry[i].val, 0, PROPERTY_VALUE_MAX);
3105 strlcpy(persist_data->persist_entry[i].val, value, PROPERTY_VALUE_MAX);
3106 return 0;
3107 }
3108 }
3109
3110 /* We didn't find it, add it to the end, if there is room */
3111 if (persist_data->persist_valid_entries < max_persistent_entries) {
3112 memset(&persist_data->persist_entry[num], 0, sizeof(struct crypt_persist_entry));
3113 strlcpy(persist_data->persist_entry[num].key, fieldname, PROPERTY_KEY_MAX);
3114 strlcpy(persist_data->persist_entry[num].val, value, PROPERTY_VALUE_MAX);
3115 persist_data->persist_valid_entries++;
3116 return 0;
3117 }
3118
3119 return -1;
3120}
3121
Rubin Xu85c01f92014-10-13 12:49:54 +01003122/**
3123 * Test if key is part of the multi-entry (field, index) sequence. Return non-zero if key is in the
3124 * sequence and its index is greater than or equal to index. Return 0 otherwise.
3125 */
Paul Crowley14c8c072018-09-18 13:30:21 -07003126int match_multi_entry(const char* key, const char* field, unsigned index) {
Jeff Sharkey95440eb2017-09-18 18:19:28 -06003127 std::string key_ = key;
3128 std::string field_ = field;
Rubin Xu85c01f92014-10-13 12:49:54 +01003129
Jeff Sharkey95440eb2017-09-18 18:19:28 -06003130 std::string parsed_field;
3131 unsigned parsed_index;
3132
3133 std::string::size_type split = key_.find_last_of('_');
3134 if (split == std::string::npos) {
3135 parsed_field = key_;
3136 parsed_index = 0;
3137 } else {
3138 parsed_field = key_.substr(0, split);
3139 parsed_index = std::stoi(key_.substr(split + 1));
Rubin Xu85c01f92014-10-13 12:49:54 +01003140 }
Jeff Sharkey95440eb2017-09-18 18:19:28 -06003141
3142 return parsed_field == field_ && parsed_index >= index;
Rubin Xu85c01f92014-10-13 12:49:54 +01003143}
3144
3145/*
3146 * Delete entry/entries from persist_data. If the entries are part of a multi-segment field, all
3147 * remaining entries starting from index will be deleted.
3148 * returns PERSIST_DEL_KEY_OK if deletion succeeds,
3149 * PERSIST_DEL_KEY_ERROR_NO_FIELD if the field does not exist,
3150 * and PERSIST_DEL_KEY_ERROR_OTHER if error occurs.
3151 *
3152 */
Paul Crowley14c8c072018-09-18 13:30:21 -07003153static int persist_del_keys(const char* fieldname, unsigned index) {
Rubin Xu85c01f92014-10-13 12:49:54 +01003154 unsigned int i;
3155 unsigned int j;
3156 unsigned int num;
3157
3158 if (persist_data == NULL) {
3159 return PERSIST_DEL_KEY_ERROR_OTHER;
3160 }
3161
3162 num = persist_data->persist_valid_entries;
3163
Paul Crowley14c8c072018-09-18 13:30:21 -07003164 j = 0; // points to the end of non-deleted entries.
Rubin Xu85c01f92014-10-13 12:49:54 +01003165 // Filter out to-be-deleted entries in place.
3166 for (i = 0; i < num; i++) {
3167 if (!match_multi_entry(persist_data->persist_entry[i].key, fieldname, index)) {
3168 persist_data->persist_entry[j] = persist_data->persist_entry[i];
3169 j++;
3170 }
3171 }
3172
3173 if (j < num) {
3174 persist_data->persist_valid_entries = j;
3175 // Zeroise the remaining entries
3176 memset(&persist_data->persist_entry[j], 0, (num - j) * sizeof(struct crypt_persist_entry));
3177 return PERSIST_DEL_KEY_OK;
3178 } else {
3179 // Did not find an entry matching the given fieldname
3180 return PERSIST_DEL_KEY_ERROR_NO_FIELD;
3181 }
3182}
3183
Paul Crowley14c8c072018-09-18 13:30:21 -07003184static int persist_count_keys(const char* fieldname) {
Rubin Xu85c01f92014-10-13 12:49:54 +01003185 unsigned int i;
3186 unsigned int count;
3187
3188 if (persist_data == NULL) {
3189 return -1;
3190 }
3191
3192 count = 0;
3193 for (i = 0; i < persist_data->persist_valid_entries; i++) {
3194 if (match_multi_entry(persist_data->persist_entry[i].key, fieldname, 0)) {
3195 count++;
3196 }
3197 }
3198
3199 return count;
3200}
3201
Ken Sumrall160b4d62013-04-22 12:15:39 -07003202/* Return the value of the specified field. */
Paul Crowley14c8c072018-09-18 13:30:21 -07003203int cryptfs_getfield(const char* fieldname, char* value, int len) {
Eric Biggersa701c452018-10-23 13:06:55 -07003204 if (fscrypt_is_native()) {
Paul Lawrence5a06a642016-02-03 13:39:13 -08003205 SLOGE("Cannot get field when file encrypted");
3206 return -1;
Paul Lawrence368d7942015-04-15 14:12:00 -07003207 }
3208
Ken Sumrall160b4d62013-04-22 12:15:39 -07003209 char temp_value[PROPERTY_VALUE_MAX];
Rubin Xu85c01f92014-10-13 12:49:54 +01003210 /* CRYPTO_GETFIELD_OK is success,
3211 * CRYPTO_GETFIELD_ERROR_NO_FIELD is value not set,
3212 * CRYPTO_GETFIELD_ERROR_BUF_TOO_SMALL is buffer (as given by len) too small,
3213 * CRYPTO_GETFIELD_ERROR_OTHER is any other error
Ken Sumrall160b4d62013-04-22 12:15:39 -07003214 */
Rubin Xu85c01f92014-10-13 12:49:54 +01003215 int rc = CRYPTO_GETFIELD_ERROR_OTHER;
3216 int i;
3217 char temp_field[PROPERTY_KEY_MAX];
Ken Sumrall160b4d62013-04-22 12:15:39 -07003218
3219 if (persist_data == NULL) {
3220 load_persistent_data();
3221 if (persist_data == NULL) {
3222 SLOGE("Getfield error, cannot load persistent data");
3223 goto out;
3224 }
3225 }
3226
Rubin Xu85c01f92014-10-13 12:49:54 +01003227 // Read value from persistent entries. If the original value is split into multiple entries,
3228 // stitch them back together.
Ken Sumrall160b4d62013-04-22 12:15:39 -07003229 if (!persist_get_key(fieldname, temp_value)) {
Rubin Xu85c01f92014-10-13 12:49:54 +01003230 // 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 -07003231 if (strlcpy(value, temp_value, len) >= (unsigned)len) {
Rubin Xu85c01f92014-10-13 12:49:54 +01003232 // value too small
3233 rc = CRYPTO_GETFIELD_ERROR_BUF_TOO_SMALL;
3234 goto out;
3235 }
3236 rc = CRYPTO_GETFIELD_OK;
3237
3238 for (i = 1; /* break explicitly */; i++) {
3239 if (snprintf(temp_field, sizeof(temp_field), "%s_%d", fieldname, i) >=
Paul Crowley14c8c072018-09-18 13:30:21 -07003240 (int)sizeof(temp_field)) {
Rubin Xu85c01f92014-10-13 12:49:54 +01003241 // If the fieldname is very long, we stop as soon as it begins to overflow the
3242 // maximum field length. At this point we have in fact fully read out the original
3243 // value because cryptfs_setfield would not allow fields with longer names to be
3244 // written in the first place.
3245 break;
3246 }
3247 if (!persist_get_key(temp_field, temp_value)) {
Paul Crowley14c8c072018-09-18 13:30:21 -07003248 if (strlcat(value, temp_value, len) >= (unsigned)len) {
3249 // value too small.
3250 rc = CRYPTO_GETFIELD_ERROR_BUF_TOO_SMALL;
3251 goto out;
3252 }
Rubin Xu85c01f92014-10-13 12:49:54 +01003253 } else {
3254 // Exhaust all entries.
3255 break;
3256 }
3257 }
Ken Sumrall160b4d62013-04-22 12:15:39 -07003258 } else {
3259 /* Sadness, it's not there. Return the error */
Rubin Xu85c01f92014-10-13 12:49:54 +01003260 rc = CRYPTO_GETFIELD_ERROR_NO_FIELD;
Ken Sumrall160b4d62013-04-22 12:15:39 -07003261 }
3262
3263out:
3264 return rc;
3265}
3266
3267/* Set the value of the specified field. */
Paul Crowley14c8c072018-09-18 13:30:21 -07003268int cryptfs_setfield(const char* fieldname, const char* value) {
Eric Biggersa701c452018-10-23 13:06:55 -07003269 if (fscrypt_is_native()) {
Paul Lawrence5a06a642016-02-03 13:39:13 -08003270 SLOGE("Cannot set field when file encrypted");
3271 return -1;
Paul Lawrence368d7942015-04-15 14:12:00 -07003272 }
3273
Ken Sumrall160b4d62013-04-22 12:15:39 -07003274 char encrypted_state[PROPERTY_VALUE_MAX];
Rubin Xu85c01f92014-10-13 12:49:54 +01003275 /* 0 is success, negative values are error */
3276 int rc = CRYPTO_SETFIELD_ERROR_OTHER;
Ken Sumrall160b4d62013-04-22 12:15:39 -07003277 int encrypted = 0;
Rubin Xu85c01f92014-10-13 12:49:54 +01003278 unsigned int field_id;
3279 char temp_field[PROPERTY_KEY_MAX];
3280 unsigned int num_entries;
3281 unsigned int max_keylen;
Ken Sumrall160b4d62013-04-22 12:15:39 -07003282
3283 if (persist_data == NULL) {
3284 load_persistent_data();
3285 if (persist_data == NULL) {
3286 SLOGE("Setfield error, cannot load persistent data");
3287 goto out;
3288 }
3289 }
3290
3291 property_get("ro.crypto.state", encrypted_state, "");
Paul Crowley14c8c072018-09-18 13:30:21 -07003292 if (!strcmp(encrypted_state, "encrypted")) {
Ken Sumrall160b4d62013-04-22 12:15:39 -07003293 encrypted = 1;
3294 }
3295
Rubin Xu85c01f92014-10-13 12:49:54 +01003296 // Compute the number of entries required to store value, each entry can store up to
3297 // (PROPERTY_VALUE_MAX - 1) chars
3298 if (strlen(value) == 0) {
3299 // Empty value also needs one entry to store.
3300 num_entries = 1;
3301 } else {
3302 num_entries = (strlen(value) + (PROPERTY_VALUE_MAX - 1) - 1) / (PROPERTY_VALUE_MAX - 1);
3303 }
3304
3305 max_keylen = strlen(fieldname);
3306 if (num_entries > 1) {
3307 // Need an extra "_%d" suffix.
3308 max_keylen += 1 + log10(num_entries);
3309 }
3310 if (max_keylen > PROPERTY_KEY_MAX - 1) {
3311 rc = CRYPTO_SETFIELD_ERROR_FIELD_TOO_LONG;
Ken Sumrall160b4d62013-04-22 12:15:39 -07003312 goto out;
3313 }
3314
Rubin Xu85c01f92014-10-13 12:49:54 +01003315 // Make sure we have enough space to write the new value
3316 if (persist_data->persist_valid_entries + num_entries - persist_count_keys(fieldname) >
3317 persist_get_max_entries(encrypted)) {
3318 rc = CRYPTO_SETFIELD_ERROR_VALUE_TOO_LONG;
3319 goto out;
3320 }
3321
3322 // Now that we know persist_data has enough space for value, let's delete the old field first
3323 // to make up space.
3324 persist_del_keys(fieldname, 0);
3325
3326 if (persist_set_key(fieldname, value, encrypted)) {
3327 // fail to set key, should not happen as we have already checked the available space
3328 SLOGE("persist_set_key() error during setfield()");
3329 goto out;
3330 }
3331
3332 for (field_id = 1; field_id < num_entries; field_id++) {
Greg Kaiserb610e772018-02-09 09:19:54 -08003333 snprintf(temp_field, sizeof(temp_field), "%s_%u", fieldname, field_id);
Rubin Xu85c01f92014-10-13 12:49:54 +01003334
3335 if (persist_set_key(temp_field, value + field_id * (PROPERTY_VALUE_MAX - 1), encrypted)) {
3336 // fail to set key, should not happen as we have already checked the available space.
3337 SLOGE("persist_set_key() error during setfield()");
3338 goto out;
3339 }
3340 }
3341
Ken Sumrall160b4d62013-04-22 12:15:39 -07003342 /* If we are running encrypted, save the persistent data now */
3343 if (encrypted) {
3344 if (save_persistent_data()) {
3345 SLOGE("Setfield error, cannot save persistent data");
3346 goto out;
3347 }
3348 }
3349
Rubin Xu85c01f92014-10-13 12:49:54 +01003350 rc = CRYPTO_SETFIELD_OK;
Ken Sumrall160b4d62013-04-22 12:15:39 -07003351
3352out:
3353 return rc;
3354}
Paul Lawrencef4faa572014-01-29 13:31:03 -08003355
3356/* Checks userdata. Attempt to mount the volume if default-
3357 * encrypted.
3358 * On success trigger next init phase and return 0.
3359 * Currently do not handle failure - see TODO below.
3360 */
Paul Crowley14c8c072018-09-18 13:30:21 -07003361int cryptfs_mount_default_encrypted(void) {
Paul Lawrence84274cc2016-04-15 15:41:33 -07003362 int crypt_type = cryptfs_get_password_type();
3363 if (crypt_type < 0 || crypt_type > CRYPT_TYPE_MAX_TYPE) {
3364 SLOGE("Bad crypt type - error");
3365 } else if (crypt_type != CRYPT_TYPE_DEFAULT) {
Paul Crowley14c8c072018-09-18 13:30:21 -07003366 SLOGD(
3367 "Password is not default - "
3368 "starting min framework to prompt");
Paul Lawrence84274cc2016-04-15 15:41:33 -07003369 property_set("vold.decrypt", "trigger_restart_min_framework");
3370 return 0;
3371 } else if (cryptfs_check_passwd(DEFAULT_PASSWORD) == 0) {
3372 SLOGD("Password is default - restarting filesystem");
3373 cryptfs_restart_internal(0);
3374 return 0;
Paul Lawrencef4faa572014-01-29 13:31:03 -08003375 } else {
Paul Lawrence84274cc2016-04-15 15:41:33 -07003376 SLOGE("Encrypted, default crypt type but can't decrypt");
Paul Lawrencef4faa572014-01-29 13:31:03 -08003377 }
3378
Paul Lawrence6bfed202014-07-28 12:47:22 -07003379 /** Corrupt. Allow us to boot into framework, which will detect bad
3380 crypto when it calls do_crypto_complete, then do a factory reset
Paul Lawrencef4faa572014-01-29 13:31:03 -08003381 */
Paul Lawrence6bfed202014-07-28 12:47:22 -07003382 property_set("vold.decrypt", "trigger_restart_min_framework");
Paul Lawrencef4faa572014-01-29 13:31:03 -08003383 return 0;
3384}
3385
3386/* Returns type of the password, default, pattern, pin or password.
3387 */
Paul Crowley14c8c072018-09-18 13:30:21 -07003388int cryptfs_get_password_type(void) {
Eric Biggersa701c452018-10-23 13:06:55 -07003389 if (fscrypt_is_native()) {
Paul Lawrence7b6b5652016-02-02 11:14:59 -08003390 SLOGE("cryptfs_get_password_type not valid for file encryption");
3391 return -1;
Paul Lawrence05335c32015-03-05 09:46:23 -08003392 }
3393
Paul Lawrencef4faa572014-01-29 13:31:03 -08003394 struct crypt_mnt_ftr crypt_ftr;
3395
3396 if (get_crypt_ftr_and_key(&crypt_ftr)) {
3397 SLOGE("Error getting crypt footer and key\n");
3398 return -1;
3399 }
3400
Paul Lawrence6bfed202014-07-28 12:47:22 -07003401 if (crypt_ftr.flags & CRYPT_INCONSISTENT_STATE) {
3402 return -1;
3403 }
3404
Paul Lawrencef4faa572014-01-29 13:31:03 -08003405 return crypt_ftr.crypt_type;
3406}
Paul Lawrence684dbdf2014-02-07 12:07:22 -08003407
Paul Crowley14c8c072018-09-18 13:30:21 -07003408const char* cryptfs_get_password() {
Eric Biggersa701c452018-10-23 13:06:55 -07003409 if (fscrypt_is_native()) {
Paul Lawrence7b6b5652016-02-02 11:14:59 -08003410 SLOGE("cryptfs_get_password not valid for file encryption");
3411 return 0;
Paul Lawrence05335c32015-03-05 09:46:23 -08003412 }
3413
Paul Lawrence399317e2014-03-10 13:20:50 -07003414 struct timespec now;
Paul Lawrenceef2b5be2014-11-11 12:47:03 -08003415 clock_gettime(CLOCK_BOOTTIME, &now);
Paul Lawrence399317e2014-03-10 13:20:50 -07003416 if (now.tv_sec < password_expiry_time) {
3417 return password;
3418 } else {
3419 cryptfs_clear_password();
3420 return 0;
3421 }
3422}
3423
Paul Crowley14c8c072018-09-18 13:30:21 -07003424void cryptfs_clear_password() {
Paul Lawrence399317e2014-03-10 13:20:50 -07003425 if (password) {
3426 size_t len = strlen(password);
3427 memset(password, 0, len);
3428 free(password);
3429 password = 0;
3430 password_expiry_time = 0;
3431 }
Paul Lawrence684dbdf2014-02-07 12:07:22 -08003432}
Paul Lawrence731a7a22015-04-28 22:14:15 +00003433
Paul Crowley14c8c072018-09-18 13:30:21 -07003434int cryptfs_isConvertibleToFBE() {
Tom Cherry4c5bde22019-01-29 14:34:01 -08003435 auto entry = GetEntryForMountPoint(&fstab_default, DATA_MNT_POINT);
3436 return entry && entry->fs_mgr_flags.force_fde_or_fbe;
Paul Lawrence0c247462015-10-29 10:30:57 -07003437}
AnilKumar Chimata98dc8352018-05-11 00:25:09 +05303438
3439int cryptfs_create_default_ftr(struct crypt_mnt_ftr* crypt_ftr, __attribute__((unused))int key_length)
3440{
3441 if (cryptfs_init_crypt_mnt_ftr(crypt_ftr)) {
3442 SLOGE("Failed to initialize crypt_ftr");
3443 return -1;
3444 }
3445
3446 if (create_encrypted_random_key(DEFAULT_PASSWORD, crypt_ftr->master_key,
3447 crypt_ftr->salt, crypt_ftr)) {
3448 SLOGE("Cannot create encrypted master key\n");
3449 return -1;
3450 }
3451
3452 //crypt_ftr->keysize = key_length / 8;
3453 return 0;
3454}
3455
3456int cryptfs_get_master_key(struct crypt_mnt_ftr* ftr, const char* password,
3457 unsigned char* master_key)
3458{
3459 int rc;
3460
3461 unsigned char* intermediate_key = 0;
3462 size_t intermediate_key_size = 0;
3463
3464 if (password == 0 || *password == 0) {
3465 password = DEFAULT_PASSWORD;
3466 }
3467
3468 rc = decrypt_master_key(password, master_key, ftr, &intermediate_key,
3469 &intermediate_key_size);
3470
3471 if (rc) {
3472 SLOGE("Can't calculate intermediate key");
3473 return rc;
3474 }
3475
3476 int N = 1 << ftr->N_factor;
3477 int r = 1 << ftr->r_factor;
3478 int p = 1 << ftr->p_factor;
3479
3480 unsigned char scrypted_intermediate_key[sizeof(ftr->scrypted_intermediate_key)];
3481
3482 rc = crypto_scrypt(intermediate_key, intermediate_key_size,
3483 ftr->salt, sizeof(ftr->salt), N, r, p,
3484 scrypted_intermediate_key,
3485 sizeof(scrypted_intermediate_key));
3486
3487 free(intermediate_key);
3488
3489 if (rc) {
3490 SLOGE("Can't scrypt intermediate key");
3491 return rc;
3492 }
3493
3494 return memcmp(scrypted_intermediate_key, ftr->scrypted_intermediate_key,
3495 intermediate_key_size);
3496}